summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorAde Lee <alee@redhat.com>2012-01-09 23:32:31 -0500
committerAde Lee <alee@redhat.com>2012-01-09 23:32:31 -0500
commit466533710c179f62865e08b3031748072a0247a3 (patch)
tree4c04c20d50239be26ba8319076de90226526a542
parentc9e3c48de53fce6908f625f40ac2b2f75d66b5a1 (diff)
downloadpki-466533710c179f62865e08b3031748072a0247a3.tar.gz
pki-466533710c179f62865e08b3031748072a0247a3.tar.xz
pki-466533710c179f62865e08b3031748072a0247a3.zip
Formatting (no wrap)
-rw-r--r--pki/.settings/org.eclipse.jdt.core.prefs6
-rw-r--r--pki/base/ca/src/com/netscape/ca/CAPolicy.java51
-rw-r--r--pki/base/ca/src/com/netscape/ca/CAService.java636
-rw-r--r--pki/base/ca/src/com/netscape/ca/CMSCRLExtensions.java191
-rw-r--r--pki/base/ca/src/com/netscape/ca/CRLIssuingPoint.java973
-rw-r--r--pki/base/ca/src/com/netscape/ca/CRLWithExpiredCerts.java28
-rw-r--r--pki/base/ca/src/com/netscape/ca/CertificateAuthority.java593
-rw-r--r--pki/base/ca/src/com/netscape/ca/SigningUnit.java77
-rw-r--r--pki/base/common/src/com/netscape/certsrv/acls/ACL.java67
-rw-r--r--pki/base/common/src/com/netscape/certsrv/acls/ACLEntry.java72
-rw-r--r--pki/base/common/src/com/netscape/certsrv/acls/ACLsResources.java8
-rw-r--r--pki/base/common/src/com/netscape/certsrv/acls/EACLsException.java38
-rw-r--r--pki/base/common/src/com/netscape/certsrv/acls/IACL.java23
-rw-r--r--pki/base/common/src/com/netscape/certsrv/acls/IACLEntry.java6
-rw-r--r--pki/base/common/src/com/netscape/certsrv/apps/CMS.java540
-rw-r--r--pki/base/common/src/com/netscape/certsrv/apps/ICMSEngine.java398
-rw-r--r--pki/base/common/src/com/netscape/certsrv/apps/ICommandQueue.java14
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authentication/AuthCredentials.java38
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authentication/AuthManagerProxy.java13
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authentication/AuthMgrPlugin.java21
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authentication/AuthResources.java3
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authentication/AuthToken.java59
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authentication/EAuthException.java8
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authentication/EAuthInternalError.java5
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authentication/EAuthMgrNotFound.java1
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authentication/EAuthMgrPluginNotFound.java3
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authentication/EAuthUserError.java1
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authentication/ECompSyntaxErr.java1
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authentication/EFormSubjectDN.java1
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authentication/EInvalidCredentials.java1
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authentication/EMissingCredential.java1
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authentication/IAuthCredentials.java10
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authentication/IAuthManager.java32
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authentication/IAuthSubsystem.java41
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authentication/IAuthToken.java112
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authentication/ISSLClientCertProvider.java15
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authentication/ISharedToken.java5
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authority/IAuthority.java5
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authority/ICertAuthority.java28
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authorization/AuthzManagerProxy.java11
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authorization/AuthzMgrPlugin.java12
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authorization/AuthzResources.java4
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authorization/AuthzToken.java69
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authorization/EAuthzAccessDenied.java3
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authorization/EAuthzException.java9
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authorization/EAuthzInternalError.java1
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authorization/EAuthzMgrNotFound.java1
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authorization/EAuthzMgrPluginNotFound.java1
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authorization/EAuthzUnknownOperation.java4
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authorization/EAuthzUnknownProtectedRes.java4
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authorization/IAuthzManager.java70
-rw-r--r--pki/base/common/src/com/netscape/certsrv/authorization/IAuthzSubsystem.java33
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/ASubsystem.java16
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/AttributeNameHelper.java20
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/BaseResources.java10
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/EBaseException.java45
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/EPropertyNotDefined.java14
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/EPropertyNotFound.java14
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/ExtendedPluginInfo.java81
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/IArgBlock.java90
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/IAttrSet.java28
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/IAuthInfo.java12
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/ICRLPrettyPrint.java12
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/ICertPrettyPrint.java11
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/IConfigStore.java146
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/IConfigStoreEventListener.java16
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/IExtPrettyPrint.java11
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/IExtendedPluginInfo.java79
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/IPluginImpl.java37
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/IPrettyPrintFormat.java20
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/ISecurityDomainSessionTable.java15
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/ISourceConfigStore.java25
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/ISubsystem.java27
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/ISubsystemSource.java9
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/ITimeSource.java14
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/KeyGenInfo.java84
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/MessageFormatter.java50
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/MetaAttributeDef.java81
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/MetaInfo.java27
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/Nonces.java28
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/PasswordResources.java5
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/Plugin.java9
-rw-r--r--pki/base/common/src/com/netscape/certsrv/base/SessionContext.java52
-rw-r--r--pki/base/common/src/com/netscape/certsrv/ca/CAResources.java7
-rw-r--r--pki/base/common/src/com/netscape/certsrv/ca/ECAException.java11
-rw-r--r--pki/base/common/src/com/netscape/certsrv/ca/EErrorPublishCRL.java6
-rw-r--r--pki/base/common/src/com/netscape/certsrv/ca/ICAService.java33
-rw-r--r--pki/base/common/src/com/netscape/certsrv/ca/ICMSCRLExtension.java31
-rw-r--r--pki/base/common/src/com/netscape/certsrv/ca/ICMSCRLExtensions.java15
-rw-r--r--pki/base/common/src/com/netscape/certsrv/ca/ICRLIssuingPoint.java220
-rw-r--r--pki/base/common/src/com/netscape/certsrv/ca/ICertificateAuthority.java185
-rw-r--r--pki/base/common/src/com/netscape/certsrv/cert/ICrossCertPairSubsystem.java35
-rw-r--r--pki/base/common/src/com/netscape/certsrv/client/IDataProcessor.java12
-rw-r--r--pki/base/common/src/com/netscape/certsrv/client/connection/IAuthenticator.java3
-rw-r--r--pki/base/common/src/com/netscape/certsrv/client/connection/IConnection.java9
-rw-r--r--pki/base/common/src/com/netscape/certsrv/client/connection/IConnectionFactory.java20
-rw-r--r--pki/base/common/src/com/netscape/certsrv/common/ConfigConstants.java39
-rw-r--r--pki/base/common/src/com/netscape/certsrv/common/Constants.java318
-rw-r--r--pki/base/common/src/com/netscape/certsrv/common/DestDef.java8
-rw-r--r--pki/base/common/src/com/netscape/certsrv/common/NameValuePair.java21
-rw-r--r--pki/base/common/src/com/netscape/certsrv/common/NameValuePairs.java52
-rw-r--r--pki/base/common/src/com/netscape/certsrv/common/OpDef.java8
-rw-r--r--pki/base/common/src/com/netscape/certsrv/common/PrefixDef.java16
-rw-r--r--pki/base/common/src/com/netscape/certsrv/common/ScopeDef.java40
-rw-r--r--pki/base/common/src/com/netscape/certsrv/common/TaskId.java20
-rw-r--r--pki/base/common/src/com/netscape/certsrv/connector/IConnector.java24
-rw-r--r--pki/base/common/src/com/netscape/certsrv/connector/IHttpConnFactory.java25
-rw-r--r--pki/base/common/src/com/netscape/certsrv/connector/IHttpConnection.java18
-rw-r--r--pki/base/common/src/com/netscape/certsrv/connector/IHttpPKIMessage.java13
-rw-r--r--pki/base/common/src/com/netscape/certsrv/connector/IPKIMessage.java31
-rw-r--r--pki/base/common/src/com/netscape/certsrv/connector/IRemoteAuthority.java14
-rw-r--r--pki/base/common/src/com/netscape/certsrv/connector/IRequestEncoder.java18
-rw-r--r--pki/base/common/src/com/netscape/certsrv/connector/IResender.java15
-rw-r--r--pki/base/common/src/com/netscape/certsrv/dbs/DBResources.java5
-rw-r--r--pki/base/common/src/com/netscape/certsrv/dbs/EDBException.java14
-rw-r--r--pki/base/common/src/com/netscape/certsrv/dbs/EDBNotAvailException.java5
-rw-r--r--pki/base/common/src/com/netscape/certsrv/dbs/EDBRecordNotFoundException.java5
-rw-r--r--pki/base/common/src/com/netscape/certsrv/dbs/IDBAttrMapper.java41
-rw-r--r--pki/base/common/src/com/netscape/certsrv/dbs/IDBDynAttrMapper.java14
-rw-r--r--pki/base/common/src/com/netscape/certsrv/dbs/IDBObj.java17
-rw-r--r--pki/base/common/src/com/netscape/certsrv/dbs/IDBRegistry.java81
-rw-r--r--pki/base/common/src/com/netscape/certsrv/dbs/IDBSSession.java107
-rw-r--r--pki/base/common/src/com/netscape/certsrv/dbs/IDBSearchResults.java15
-rw-r--r--pki/base/common/src/com/netscape/certsrv/dbs/IDBSubsystem.java105
-rw-r--r--pki/base/common/src/com/netscape/certsrv/dbs/IDBVirtualList.java91
-rw-r--r--pki/base/common/src/com/netscape/certsrv/dbs/IElementProcessor.java6
-rw-r--r--pki/base/common/src/com/netscape/certsrv/dbs/IFilterConverter.java14
-rw-r--r--pki/base/common/src/com/netscape/certsrv/dbs/Modification.java19
-rw-r--r--pki/base/common/src/com/netscape/certsrv/dbs/ModificationSet.java12
-rw-r--r--pki/base/common/src/com/netscape/certsrv/dbs/certdb/ICertRecord.java70
-rw-r--r--pki/base/common/src/com/netscape/certsrv/dbs/certdb/ICertRecordList.java31
-rw-r--r--pki/base/common/src/com/netscape/certsrv/dbs/certdb/ICertificateRepository.java253
-rw-r--r--pki/base/common/src/com/netscape/certsrv/dbs/certdb/IRevocationInfo.java14
-rw-r--r--pki/base/common/src/com/netscape/certsrv/dbs/crldb/ICRLIssuingPointRecord.java50
-rw-r--r--pki/base/common/src/com/netscape/certsrv/dbs/crldb/ICRLRepository.java73
-rw-r--r--pki/base/common/src/com/netscape/certsrv/dbs/keydb/IKeyRecord.java44
-rw-r--r--pki/base/common/src/com/netscape/certsrv/dbs/keydb/IKeyRecordList.java12
-rw-r--r--pki/base/common/src/com/netscape/certsrv/dbs/keydb/IKeyRepository.java60
-rw-r--r--pki/base/common/src/com/netscape/certsrv/dbs/keydb/KeyState.java49
-rw-r--r--pki/base/common/src/com/netscape/certsrv/dbs/replicadb/IReplicaIDRepository.java7
-rw-r--r--pki/base/common/src/com/netscape/certsrv/dbs/repository/IRepository.java34
-rw-r--r--pki/base/common/src/com/netscape/certsrv/dbs/repository/IRepositoryRecord.java24
-rw-r--r--pki/base/common/src/com/netscape/certsrv/evaluators/IAccessEvaluator.java43
-rw-r--r--pki/base/common/src/com/netscape/certsrv/extensions/EExtensionsException.java6
-rw-r--r--pki/base/common/src/com/netscape/certsrv/extensions/ExtensionsResources.java4
-rw-r--r--pki/base/common/src/com/netscape/certsrv/extensions/ICMSExtension.java30
-rw-r--r--pki/base/common/src/com/netscape/certsrv/jobs/EJobsException.java4
-rw-r--r--pki/base/common/src/com/netscape/certsrv/jobs/IJob.java30
-rw-r--r--pki/base/common/src/com/netscape/certsrv/jobs/IJobCron.java31
-rw-r--r--pki/base/common/src/com/netscape/certsrv/jobs/IJobsScheduler.java138
-rw-r--r--pki/base/common/src/com/netscape/certsrv/jobs/JobPlugin.java20
-rw-r--r--pki/base/common/src/com/netscape/certsrv/jobs/JobsResources.java10
-rw-r--r--pki/base/common/src/com/netscape/certsrv/kra/EKRAException.java16
-rw-r--r--pki/base/common/src/com/netscape/certsrv/kra/IJoinShares.java9
-rw-r--r--pki/base/common/src/com/netscape/certsrv/kra/IKeyRecoveryAuthority.java128
-rw-r--r--pki/base/common/src/com/netscape/certsrv/kra/IKeyService.java101
-rw-r--r--pki/base/common/src/com/netscape/certsrv/kra/IProofOfArchival.java13
-rw-r--r--pki/base/common/src/com/netscape/certsrv/kra/IShare.java7
-rw-r--r--pki/base/common/src/com/netscape/certsrv/kra/KRAResources.java2
-rw-r--r--pki/base/common/src/com/netscape/certsrv/kra/ProofOfArchival.java83
-rw-r--r--pki/base/common/src/com/netscape/certsrv/ldap/ELdapException.java35
-rw-r--r--pki/base/common/src/com/netscape/certsrv/ldap/ELdapServerDownException.java4
-rw-r--r--pki/base/common/src/com/netscape/certsrv/ldap/ILdapAuthInfo.java33
-rw-r--r--pki/base/common/src/com/netscape/certsrv/ldap/ILdapBoundConnFactory.java18
-rw-r--r--pki/base/common/src/com/netscape/certsrv/ldap/ILdapConnFactory.java57
-rw-r--r--pki/base/common/src/com/netscape/certsrv/ldap/ILdapConnInfo.java24
-rw-r--r--pki/base/common/src/com/netscape/certsrv/ldap/ILdapConnModule.java41
-rw-r--r--pki/base/common/src/com/netscape/certsrv/ldap/LdapResources.java5
-rw-r--r--pki/base/common/src/com/netscape/certsrv/listeners/EListenersException.java15
-rw-r--r--pki/base/common/src/com/netscape/certsrv/listeners/IRequestListenerPlugin.java46
-rw-r--r--pki/base/common/src/com/netscape/certsrv/listeners/ListenersResources.java11
-rw-r--r--pki/base/common/src/com/netscape/certsrv/logging/AuditEvent.java116
-rw-r--r--pki/base/common/src/com/netscape/certsrv/logging/AuditFormat.java74
-rw-r--r--pki/base/common/src/com/netscape/certsrv/logging/ConsoleError.java9
-rw-r--r--pki/base/common/src/com/netscape/certsrv/logging/ConsoleLog.java58
-rw-r--r--pki/base/common/src/com/netscape/certsrv/logging/ELogException.java48
-rw-r--r--pki/base/common/src/com/netscape/certsrv/logging/ELogNotFound.java4
-rw-r--r--pki/base/common/src/com/netscape/certsrv/logging/ELogPluginNotFound.java5
-rw-r--r--pki/base/common/src/com/netscape/certsrv/logging/IBundleLogEvent.java20
-rw-r--r--pki/base/common/src/com/netscape/certsrv/logging/ILogEvent.java61
-rw-r--r--pki/base/common/src/com/netscape/certsrv/logging/ILogEventFactory.java15
-rw-r--r--pki/base/common/src/com/netscape/certsrv/logging/ILogEventListener.java82
-rw-r--r--pki/base/common/src/com/netscape/certsrv/logging/ILogQueue.java25
-rw-r--r--pki/base/common/src/com/netscape/certsrv/logging/ILogSubsystem.java74
-rw-r--r--pki/base/common/src/com/netscape/certsrv/logging/ILogger.java220
-rw-r--r--pki/base/common/src/com/netscape/certsrv/logging/LogPlugin.java6
-rw-r--r--pki/base/common/src/com/netscape/certsrv/logging/LogResources.java11
-rw-r--r--pki/base/common/src/com/netscape/certsrv/logging/SignedAuditEvent.java117
-rw-r--r--pki/base/common/src/com/netscape/certsrv/logging/SystemEvent.java114
-rw-r--r--pki/base/common/src/com/netscape/certsrv/notification/ENotificationException.java4
-rw-r--r--pki/base/common/src/com/netscape/certsrv/notification/IEmailFormProcessor.java26
-rw-r--r--pki/base/common/src/com/netscape/certsrv/notification/IEmailResolver.java17
-rw-r--r--pki/base/common/src/com/netscape/certsrv/notification/IEmailResolverKeys.java10
-rw-r--r--pki/base/common/src/com/netscape/certsrv/notification/IEmailTemplate.java11
-rw-r--r--pki/base/common/src/com/netscape/certsrv/notification/IMailNotification.java17
-rw-r--r--pki/base/common/src/com/netscape/certsrv/notification/NotificationResources.java10
-rw-r--r--pki/base/common/src/com/netscape/certsrv/ocsp/IDefStore.java74
-rw-r--r--pki/base/common/src/com/netscape/certsrv/ocsp/IOCSPAuthority.java63
-rw-r--r--pki/base/common/src/com/netscape/certsrv/ocsp/IOCSPService.java47
-rw-r--r--pki/base/common/src/com/netscape/certsrv/ocsp/IOCSPStore.java42
-rw-r--r--pki/base/common/src/com/netscape/certsrv/password/EPasswordCheckException.java7
-rw-r--r--pki/base/common/src/com/netscape/certsrv/password/IConfigPasswordCheck.java7
-rw-r--r--pki/base/common/src/com/netscape/certsrv/password/IPasswordCheck.java7
-rw-r--r--pki/base/common/src/com/netscape/certsrv/pattern/AttrSetCollection.java10
-rw-r--r--pki/base/common/src/com/netscape/certsrv/pattern/Pattern.java85
-rw-r--r--pki/base/common/src/com/netscape/certsrv/policy/EPolicyException.java45
-rw-r--r--pki/base/common/src/com/netscape/certsrv/policy/IEnrollmentPolicy.java10
-rw-r--r--pki/base/common/src/com/netscape/certsrv/policy/IExpression.java13
-rw-r--r--pki/base/common/src/com/netscape/certsrv/policy/IGeneralNameAsConstraintsConfig.java15
-rw-r--r--pki/base/common/src/com/netscape/certsrv/policy/IGeneralNameConfig.java23
-rw-r--r--pki/base/common/src/com/netscape/certsrv/policy/IGeneralNameUtil.java50
-rw-r--r--pki/base/common/src/com/netscape/certsrv/policy/IGeneralNamesAsConstraintsConfig.java15
-rw-r--r--pki/base/common/src/com/netscape/certsrv/policy/IGeneralNamesConfig.java15
-rw-r--r--pki/base/common/src/com/netscape/certsrv/policy/IKeyArchivalPolicy.java5
-rw-r--r--pki/base/common/src/com/netscape/certsrv/policy/IKeyRecoveryPolicy.java5
-rw-r--r--pki/base/common/src/com/netscape/certsrv/policy/IPolicyPredicateParser.java14
-rw-r--r--pki/base/common/src/com/netscape/certsrv/policy/IPolicyProcessor.java114
-rw-r--r--pki/base/common/src/com/netscape/certsrv/policy/IPolicyRule.java51
-rw-r--r--pki/base/common/src/com/netscape/certsrv/policy/IPolicySet.java51
-rw-r--r--pki/base/common/src/com/netscape/certsrv/policy/IRenewalPolicy.java5
-rw-r--r--pki/base/common/src/com/netscape/certsrv/policy/IRevocationPolicy.java5
-rw-r--r--pki/base/common/src/com/netscape/certsrv/policy/ISubjAltNameConfig.java16
-rw-r--r--pki/base/common/src/com/netscape/certsrv/policy/PolicyResources.java5
-rw-r--r--pki/base/common/src/com/netscape/certsrv/profile/CertInfoProfile.java67
-rw-r--r--pki/base/common/src/com/netscape/certsrv/profile/EDeferException.java21
-rw-r--r--pki/base/common/src/com/netscape/certsrv/profile/EProfileException.java12
-rw-r--r--pki/base/common/src/com/netscape/certsrv/profile/ERejectException.java19
-rw-r--r--pki/base/common/src/com/netscape/certsrv/profile/ICertInfoPolicyDefault.java2
-rw-r--r--pki/base/common/src/com/netscape/certsrv/profile/IEnrollProfile.java57
-rw-r--r--pki/base/common/src/com/netscape/certsrv/profile/IPolicyConstraint.java38
-rw-r--r--pki/base/common/src/com/netscape/certsrv/profile/IPolicyDefault.java80
-rw-r--r--pki/base/common/src/com/netscape/certsrv/profile/IProfile.java217
-rw-r--r--pki/base/common/src/com/netscape/certsrv/profile/IProfileAuthenticator.java48
-rw-r--r--pki/base/common/src/com/netscape/certsrv/profile/IProfileContext.java12
-rw-r--r--pki/base/common/src/com/netscape/certsrv/profile/IProfileEx.java9
-rw-r--r--pki/base/common/src/com/netscape/certsrv/profile/IProfileInput.java36
-rw-r--r--pki/base/common/src/com/netscape/certsrv/profile/IProfileOutput.java36
-rw-r--r--pki/base/common/src/com/netscape/certsrv/profile/IProfilePolicy.java15
-rw-r--r--pki/base/common/src/com/netscape/certsrv/profile/IProfileSubsystem.java52
-rw-r--r--pki/base/common/src/com/netscape/certsrv/profile/IProfileUpdater.java20
-rw-r--r--pki/base/common/src/com/netscape/certsrv/property/Descriptor.java22
-rw-r--r--pki/base/common/src/com/netscape/certsrv/property/EPropertyException.java5
-rw-r--r--pki/base/common/src/com/netscape/certsrv/property/IConfigTemplate.java22
-rw-r--r--pki/base/common/src/com/netscape/certsrv/property/IDescriptor.java22
-rw-r--r--pki/base/common/src/com/netscape/certsrv/property/PropertySet.java43
-rw-r--r--pki/base/common/src/com/netscape/certsrv/publish/ECompSyntaxErr.java17
-rw-r--r--pki/base/common/src/com/netscape/certsrv/publish/EMapperNotFound.java7
-rw-r--r--pki/base/common/src/com/netscape/certsrv/publish/EMapperPluginNotFound.java6
-rw-r--r--pki/base/common/src/com/netscape/certsrv/publish/EPublisherNotFound.java5
-rw-r--r--pki/base/common/src/com/netscape/certsrv/publish/EPublisherPluginNotFound.java9
-rw-r--r--pki/base/common/src/com/netscape/certsrv/publish/ERuleNotFound.java8
-rw-r--r--pki/base/common/src/com/netscape/certsrv/publish/ERulePluginNotFound.java9
-rw-r--r--pki/base/common/src/com/netscape/certsrv/publish/ICRLPublisher.java86
-rw-r--r--pki/base/common/src/com/netscape/certsrv/publish/ILdapCertMapper.java28
-rw-r--r--pki/base/common/src/com/netscape/certsrv/publish/ILdapCrlMapper.java31
-rw-r--r--pki/base/common/src/com/netscape/certsrv/publish/ILdapExpression.java26
-rw-r--r--pki/base/common/src/com/netscape/certsrv/publish/ILdapMapper.java33
-rw-r--r--pki/base/common/src/com/netscape/certsrv/publish/ILdapPlugin.java9
-rw-r--r--pki/base/common/src/com/netscape/certsrv/publish/ILdapPluginImpl.java12
-rw-r--r--pki/base/common/src/com/netscape/certsrv/publish/ILdapPublishModule.java20
-rw-r--r--pki/base/common/src/com/netscape/certsrv/publish/ILdapPublisher.java37
-rw-r--r--pki/base/common/src/com/netscape/certsrv/publish/ILdapRule.java9
-rw-r--r--pki/base/common/src/com/netscape/certsrv/publish/IPublishRuleSet.java71
-rw-r--r--pki/base/common/src/com/netscape/certsrv/publish/IPublisherProcessor.java148
-rw-r--r--pki/base/common/src/com/netscape/certsrv/publish/IXcertPublisherProcessor.java10
-rw-r--r--pki/base/common/src/com/netscape/certsrv/publish/LdapCertMapResult.java17
-rw-r--r--pki/base/common/src/com/netscape/certsrv/publish/MapperPlugin.java8
-rw-r--r--pki/base/common/src/com/netscape/certsrv/publish/MapperProxy.java18
-rw-r--r--pki/base/common/src/com/netscape/certsrv/publish/PublisherPlugin.java16
-rw-r--r--pki/base/common/src/com/netscape/certsrv/publish/PublisherProxy.java16
-rw-r--r--pki/base/common/src/com/netscape/certsrv/publish/RulePlugin.java9
-rw-r--r--pki/base/common/src/com/netscape/certsrv/ra/IRAService.java16
-rw-r--r--pki/base/common/src/com/netscape/certsrv/ra/IRegistrationAuthority.java52
-rw-r--r--pki/base/common/src/com/netscape/certsrv/registry/ERegistryException.java6
-rw-r--r--pki/base/common/src/com/netscape/certsrv/registry/IPluginInfo.java25
-rw-r--r--pki/base/common/src/com/netscape/certsrv/registry/IPluginRegistry.java31
-rw-r--r--pki/base/common/src/com/netscape/certsrv/request/ARequestNotifier.java180
-rw-r--r--pki/base/common/src/com/netscape/certsrv/request/AgentApproval.java16
-rw-r--r--pki/base/common/src/com/netscape/certsrv/request/AgentApprovals.java44
-rw-r--r--pki/base/common/src/com/netscape/certsrv/request/IEnrollmentRequest.java10
-rw-r--r--pki/base/common/src/com/netscape/certsrv/request/INotify.java22
-rw-r--r--pki/base/common/src/com/netscape/certsrv/request/IPolicy.java41
-rw-r--r--pki/base/common/src/com/netscape/certsrv/request/IRequest.java437
-rw-r--r--pki/base/common/src/com/netscape/certsrv/request/IRequestList.java26
-rw-r--r--pki/base/common/src/com/netscape/certsrv/request/IRequestListener.java16
-rw-r--r--pki/base/common/src/com/netscape/certsrv/request/IRequestNotifier.java36
-rw-r--r--pki/base/common/src/com/netscape/certsrv/request/IRequestQueue.java301
-rw-r--r--pki/base/common/src/com/netscape/certsrv/request/IRequestRecord.java29
-rw-r--r--pki/base/common/src/com/netscape/certsrv/request/IRequestScheduler.java14
-rw-r--r--pki/base/common/src/com/netscape/certsrv/request/IRequestSubsystem.java103
-rw-r--r--pki/base/common/src/com/netscape/certsrv/request/IRequestVirtualList.java12
-rw-r--r--pki/base/common/src/com/netscape/certsrv/request/IService.java27
-rw-r--r--pki/base/common/src/com/netscape/certsrv/request/PolicyMessage.java10
-rw-r--r--pki/base/common/src/com/netscape/certsrv/request/PolicyResult.java3
-rw-r--r--pki/base/common/src/com/netscape/certsrv/request/RequestId.java28
-rw-r--r--pki/base/common/src/com/netscape/certsrv/request/RequestStatus.java150
-rw-r--r--pki/base/common/src/com/netscape/certsrv/request/ldap/IRequestMod.java22
-rw-r--r--pki/base/common/src/com/netscape/certsrv/security/Credential.java16
-rw-r--r--pki/base/common/src/com/netscape/certsrv/security/ICryptoSubsystem.java234
-rw-r--r--pki/base/common/src/com/netscape/certsrv/security/IEncryptionUnit.java73
-rw-r--r--pki/base/common/src/com/netscape/certsrv/security/ISigningUnit.java45
-rw-r--r--pki/base/common/src/com/netscape/certsrv/security/IStorageKeyUnit.java34
-rw-r--r--pki/base/common/src/com/netscape/certsrv/security/IToken.java6
-rw-r--r--pki/base/common/src/com/netscape/certsrv/security/ITransportKeyUnit.java23
-rw-r--r--pki/base/common/src/com/netscape/certsrv/security/KeyCertData.java183
-rw-r--r--pki/base/common/src/com/netscape/certsrv/selftests/EDuplicateSelfTestException.java103
-rw-r--r--pki/base/common/src/com/netscape/certsrv/selftests/EInvalidSelfTestException.java103
-rw-r--r--pki/base/common/src/com/netscape/certsrv/selftests/EMissingSelfTestException.java105
-rw-r--r--pki/base/common/src/com/netscape/certsrv/selftests/ESelfTestException.java73
-rw-r--r--pki/base/common/src/com/netscape/certsrv/selftests/ISelfTest.java67
-rw-r--r--pki/base/common/src/com/netscape/certsrv/selftests/ISelfTestSubsystem.java253
-rw-r--r--pki/base/common/src/com/netscape/certsrv/selftests/SelfTestResources.java2
-rw-r--r--pki/base/common/src/com/netscape/certsrv/template/ArgList.java18
-rw-r--r--pki/base/common/src/com/netscape/certsrv/template/ArgSet.java18
-rw-r--r--pki/base/common/src/com/netscape/certsrv/template/ArgString.java8
-rw-r--r--pki/base/common/src/com/netscape/certsrv/template/IArgValue.java7
-rw-r--r--pki/base/common/src/com/netscape/certsrv/tks/ITKSAuthority.java18
-rw-r--r--pki/base/common/src/com/netscape/certsrv/usrgrp/Certificates.java10
-rw-r--r--pki/base/common/src/com/netscape/certsrv/usrgrp/EUsrGrpException.java16
-rw-r--r--pki/base/common/src/com/netscape/certsrv/usrgrp/ICertUserLocator.java14
-rw-r--r--pki/base/common/src/com/netscape/certsrv/usrgrp/IGroup.java17
-rw-r--r--pki/base/common/src/com/netscape/certsrv/usrgrp/IGroupConstants.java5
-rw-r--r--pki/base/common/src/com/netscape/certsrv/usrgrp/IIdEvaluator.java8
-rw-r--r--pki/base/common/src/com/netscape/certsrv/usrgrp/IUGSubsystem.java95
-rw-r--r--pki/base/common/src/com/netscape/certsrv/usrgrp/IUser.java30
-rw-r--r--pki/base/common/src/com/netscape/certsrv/usrgrp/IUserConstants.java5
-rw-r--r--pki/base/common/src/com/netscape/certsrv/usrgrp/IUsrGrp.java29
-rw-r--r--pki/base/common/src/com/netscape/certsrv/usrgrp/UsrGrpResources.java9
-rw-r--r--pki/base/common/src/com/netscape/certsrv/util/HttpInput.java198
-rw-r--r--pki/base/common/src/com/netscape/certsrv/util/IStatsSubsystem.java13
-rw-r--r--pki/base/common/src/com/netscape/certsrv/util/StatsEvent.java309
-rw-r--r--pki/base/common/src/com/netscape/cms/authentication/AVAPattern.java245
-rw-r--r--pki/base/common/src/com/netscape/cms/authentication/AgentCertAuthentication.java111
-rw-r--r--pki/base/common/src/com/netscape/cms/authentication/CMCAuth.java658
-rw-r--r--pki/base/common/src/com/netscape/cms/authentication/Crypt.java344
-rw-r--r--pki/base/common/src/com/netscape/cms/authentication/DNPattern.java73
-rw-r--r--pki/base/common/src/com/netscape/cms/authentication/DirBasedAuthentication.java283
-rw-r--r--pki/base/common/src/com/netscape/cms/authentication/FlatFileAuth.java168
-rw-r--r--pki/base/common/src/com/netscape/cms/authentication/HashAuthData.java12
-rw-r--r--pki/base/common/src/com/netscape/cms/authentication/HashAuthentication.java51
-rw-r--r--pki/base/common/src/com/netscape/cms/authentication/PortalEnroll.java211
-rw-r--r--pki/base/common/src/com/netscape/cms/authentication/RDNPattern.java91
-rw-r--r--pki/base/common/src/com/netscape/cms/authentication/SSLclientCertAuthentication.java143
-rw-r--r--pki/base/common/src/com/netscape/cms/authentication/SharedSecret.java2
-rw-r--r--pki/base/common/src/com/netscape/cms/authentication/TokenAuthentication.java99
-rw-r--r--pki/base/common/src/com/netscape/cms/authentication/UdnPwdDirAuthentication.java99
-rw-r--r--pki/base/common/src/com/netscape/cms/authentication/UidPwdDirAuthentication.java100
-rw-r--r--pki/base/common/src/com/netscape/cms/authentication/UidPwdPinDirAuthentication.java175
-rw-r--r--pki/base/common/src/com/netscape/cms/authorization/AAclAuthz.java294
-rw-r--r--pki/base/common/src/com/netscape/cms/authorization/BasicAclAuthz.java69
-rw-r--r--pki/base/common/src/com/netscape/cms/authorization/DirAclAuthz.java118
-rw-r--r--pki/base/common/src/com/netscape/cms/crl/CMSAuthInfoAccessExtension.java46
-rw-r--r--pki/base/common/src/com/netscape/cms/crl/CMSAuthorityKeyIdentifierExtension.java38
-rw-r--r--pki/base/common/src/com/netscape/cms/crl/CMSCRLNumberExtension.java28
-rw-r--r--pki/base/common/src/com/netscape/cms/crl/CMSCRLReasonExtension.java26
-rw-r--r--pki/base/common/src/com/netscape/cms/crl/CMSCertificateIssuerExtension.java23
-rw-r--r--pki/base/common/src/com/netscape/cms/crl/CMSDeltaCRLIndicatorExtension.java25
-rw-r--r--pki/base/common/src/com/netscape/cms/crl/CMSFreshestCRLExtension.java38
-rw-r--r--pki/base/common/src/com/netscape/cms/crl/CMSHoldInstructionExtension.java37
-rw-r--r--pki/base/common/src/com/netscape/cms/crl/CMSInvalidityDateExtension.java30
-rw-r--r--pki/base/common/src/com/netscape/cms/crl/CMSIssuerAlternativeNameExtension.java48
-rw-r--r--pki/base/common/src/com/netscape/cms/crl/CMSIssuingDistributionPointExtension.java82
-rw-r--r--pki/base/common/src/com/netscape/cms/evaluators/GroupAccessEvaluator.java48
-rw-r--r--pki/base/common/src/com/netscape/cms/evaluators/IPAddressAccessEvaluator.java24
-rw-r--r--pki/base/common/src/com/netscape/cms/evaluators/UserAccessEvaluator.java18
-rw-r--r--pki/base/common/src/com/netscape/cms/evaluators/UserOrigReqAccessEvaluator.java36
-rw-r--r--pki/base/common/src/com/netscape/cms/jobs/AJobBase.java59
-rw-r--r--pki/base/common/src/com/netscape/cms/jobs/PublishCertsJob.java224
-rw-r--r--pki/base/common/src/com/netscape/cms/jobs/RenewalNotificationJob.java354
-rw-r--r--pki/base/common/src/com/netscape/cms/jobs/RequestInQueueJob.java100
-rw-r--r--pki/base/common/src/com/netscape/cms/jobs/UnpublishExpiredJob.java211
-rw-r--r--pki/base/common/src/com/netscape/cms/listeners/CertificateIssuedListener.java109
-rw-r--r--pki/base/common/src/com/netscape/cms/listeners/CertificateRevokedListener.java105
-rw-r--r--pki/base/common/src/com/netscape/cms/listeners/PinRemovalListener.java32
-rw-r--r--pki/base/common/src/com/netscape/cms/listeners/RequestInQListener.java83
-rw-r--r--pki/base/common/src/com/netscape/cms/logging/LogEntry.java13
-rw-r--r--pki/base/common/src/com/netscape/cms/logging/LogFile.java565
-rw-r--r--pki/base/common/src/com/netscape/cms/logging/RollingLogFile.java192
-rw-r--r--pki/base/common/src/com/netscape/cms/notification/MailNotification.java37
-rw-r--r--pki/base/common/src/com/netscape/cms/ocsp/DefStore.java331
-rw-r--r--pki/base/common/src/com/netscape/cms/ocsp/LDAPStore.java191
-rw-r--r--pki/base/common/src/com/netscape/cms/password/PasswordChecker.java14
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/APolicyRule.java118
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/constraints/AgentPolicy.java59
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/constraints/AttributePresentConstraints.java132
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/constraints/DSAKeyConstraints.java86
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/constraints/DefaultRevocation.java38
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/constraints/IssuerConstraints.java92
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/constraints/KeyAlgorithmConstraints.java71
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/constraints/ManualAuthentication.java42
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/constraints/RSAKeyConstraints.java93
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/constraints/RenewalConstraints.java99
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/constraints/RenewalValidityConstraints.java143
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/constraints/RevocationConstraints.java73
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/constraints/SigningAlgorithmConstraints.java166
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/constraints/SubCANameConstraints.java56
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/constraints/UniqueSubjectName.java6
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/constraints/UniqueSubjectNameConstraints.java128
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/constraints/ValidityConstraints.java131
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/extensions/AuthInfoAccessExt.java184
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/extensions/AuthorityKeyIdentifierExt.java210
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/extensions/BasicConstraintsExt.java298
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/extensions/CRLDistributionPointsExt.java91
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/extensions/CertificatePoliciesExt.java259
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/extensions/CertificateRenewalWindowExt.java64
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/extensions/CertificateScopeOfUseExt.java160
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/extensions/ExtendedKeyUsageExt.java71
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/extensions/GenericASN1Ext.java178
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/extensions/IssuerAltNameExt.java73
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/extensions/KeyUsageExt.java136
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/extensions/NSCCommentExt.java98
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/extensions/NSCertTypeExt.java213
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/extensions/NameConstraintsExt.java197
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/extensions/OCSPNoCheckExt.java46
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/extensions/PolicyConstraintsExt.java149
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/extensions/PolicyMappingsExt.java202
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/extensions/PresenceExt.java33
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/extensions/PrivateKeyUsagePeriodExt.java80
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/extensions/RemoveBasicConstraintsExt.java35
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/extensions/SubjAltNameExt.java189
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/extensions/SubjectAltNameExt.java144
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/extensions/SubjectDirectoryAttributesExt.java127
-rw-r--r--pki/base/common/src/com/netscape/cms/policy/extensions/SubjectKeyIdentifierExt.java175
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/common/BasicProfile.java372
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/common/CACertCAEnrollProfile.java97
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/common/CAEnrollProfile.java114
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/common/EnrollProfile.java529
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/common/EnrollProfileContext.java12
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/common/ProfileContext.java4
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/common/ProfilePolicy.java9
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/common/RAEnrollProfile.java23
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/common/ServerCertCAEnrollProfile.java87
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/common/UserCertCAEnrollProfile.java105
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/constraint/BasicConstraintsExtConstraint.java93
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/constraint/CAEnrollConstraint.java7
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/constraint/CAValidityConstraint.java28
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/constraint/EnrollConstraint.java41
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/constraint/ExtendedKeyUsageExtConstraint.java55
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/constraint/ExtensionConstraint.java57
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/constraint/KeyConstraint.java505
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/constraint/KeyUsageExtConstraint.java136
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/constraint/NSCertTypeExtConstraint.java97
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/constraint/NoConstraint.java17
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/constraint/RenewGracePeriodConstraint.java156
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/constraint/SigningAlgConstraint.java51
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/constraint/SubjectNameConstraint.java54
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/constraint/UniqueKeyConstraint.java365
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/constraint/UniqueSubjectNameConstraint.java93
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/constraint/ValidityConstraint.java54
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/AuthInfoAccessExtDefault.java133
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/AuthTokenSubjectNameDefault.java38
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/AuthorityKeyIdentifierExtDefault.java73
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/AutoAssignDefault.java34
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/BasicConstraintsExtDefault.java123
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/CAEnrollDefault.java37
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/CAValidityDefault.java105
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/CRLDistributionPointsExtDefault.java212
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/CertificatePoliciesExtDefault.java336
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/CertificateVersionDefault.java81
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/EnrollDefault.java409
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/EnrollExtDefault.java10
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/ExtendedKeyUsageExtDefault.java85
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/FreshestCRLExtDefault.java192
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/GenericExtDefault.java80
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/ImageDefault.java24
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/InhibitAnyPolicyExtDefault.java104
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/IssuerAltNameExtDefault.java126
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/KeyUsageExtDefault.java204
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/NSCCommentExtDefault.java70
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/NSCertTypeExtDefault.java147
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/NameConstraintsExtDefault.java206
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/NoDefault.java18
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/OCSPNoCheckExtDefault.java68
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/PolicyConstraintsExtDefault.java120
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/PolicyMappingsExtDefault.java152
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/PrivateKeyUsagePeriodExtDefault.java130
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/SigningAlgDefault.java105
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/SubjectAltNameExtDefault.java274
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/SubjectDirAttributesExtDefault.java211
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/SubjectInfoAccessExtDefault.java124
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/SubjectKeyIdentifierExtDefault.java84
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/SubjectNameDefault.java59
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/UserExtensionDefault.java37
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/UserKeyDefault.java41
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/UserSigningAlgDefault.java29
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/UserSubjectNameDefault.java35
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/UserValidityDefault.java41
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/ValidityDefault.java81
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/nsHKeySubjectNameDefault.java117
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/nsNKeySubjectNameDefault.java403
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/nsTokenDeviceKeySubjectNameDefault.java106
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/def/nsTokenUserKeySubjectNameDefault.java278
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/input/CMCCertReqInput.java42
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/input/CertReqInput.java66
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/input/DualKeyGenInput.java61
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/input/EnrollInput.java95
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/input/FileSigningInput.java69
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/input/GenericInput.java87
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/input/ImageInput.java16
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/input/KeyGenInput.java54
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/input/SerialNumRenewInput.java18
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/input/SubjectDNInput.java44
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/input/SubjectNameInput.java199
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/input/SubmitterInfoInput.java18
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/input/nsHKeyCertReqInput.java105
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/input/nsNKeyCertReqInput.java50
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/output/CMMFOutput.java95
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/output/CertOutput.java31
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/output/EnrollOutput.java30
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/output/PKCS7Output.java91
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/output/nsNKeyOutput.java35
-rw-r--r--pki/base/common/src/com/netscape/cms/profile/updater/SubsystemGroupUpdater.java55
-rw-r--r--pki/base/common/src/com/netscape/cms/publish/mappers/AVAPattern.java215
-rw-r--r--pki/base/common/src/com/netscape/cms/publish/mappers/LdapCaSimpleMap.java162
-rw-r--r--pki/base/common/src/com/netscape/cms/publish/mappers/LdapCertCompsMap.java84
-rw-r--r--pki/base/common/src/com/netscape/cms/publish/mappers/LdapCertExactMap.java77
-rw-r--r--pki/base/common/src/com/netscape/cms/publish/mappers/LdapCertSubjMap.java130
-rw-r--r--pki/base/common/src/com/netscape/cms/publish/mappers/LdapCrlIssuerCompsMap.java78
-rw-r--r--pki/base/common/src/com/netscape/cms/publish/mappers/LdapDNCompsMap.java213
-rw-r--r--pki/base/common/src/com/netscape/cms/publish/mappers/LdapEnhancedMap.java373
-rw-r--r--pki/base/common/src/com/netscape/cms/publish/mappers/LdapSimpleMap.java133
-rw-r--r--pki/base/common/src/com/netscape/cms/publish/mappers/MapAVAPattern.java313
-rw-r--r--pki/base/common/src/com/netscape/cms/publish/mappers/MapDNPattern.java83
-rw-r--r--pki/base/common/src/com/netscape/cms/publish/mappers/MapRDNPattern.java94
-rw-r--r--pki/base/common/src/com/netscape/cms/publish/mappers/NoMap.java28
-rw-r--r--pki/base/common/src/com/netscape/cms/publish/publishers/FileBasedPublisher.java178
-rw-r--r--pki/base/common/src/com/netscape/cms/publish/publishers/LdapCaCertPublisher.java188
-rw-r--r--pki/base/common/src/com/netscape/cms/publish/publishers/LdapCertSubjPublisher.java113
-rw-r--r--pki/base/common/src/com/netscape/cms/publish/publishers/LdapCertificatePairPublisher.java91
-rw-r--r--pki/base/common/src/com/netscape/cms/publish/publishers/LdapCrlPublisher.java137
-rw-r--r--pki/base/common/src/com/netscape/cms/publish/publishers/LdapEncryptCertPublisher.java70
-rw-r--r--pki/base/common/src/com/netscape/cms/publish/publishers/LdapUserCertPublisher.java115
-rw-r--r--pki/base/common/src/com/netscape/cms/publish/publishers/OCSPPublisher.java171
-rw-r--r--pki/base/common/src/com/netscape/cms/publish/publishers/Utils.java20
-rw-r--r--pki/base/common/src/com/netscape/cms/request/RequestScheduler.java15
-rw-r--r--pki/base/common/src/com/netscape/cms/selftests/ASelfTest.java85
-rw-r--r--pki/base/common/src/com/netscape/cms/selftests/ca/CAPresence.java201
-rw-r--r--pki/base/common/src/com/netscape/cms/selftests/ca/CAValidity.java205
-rw-r--r--pki/base/common/src/com/netscape/cms/selftests/common/SystemCertsVerification.java168
-rw-r--r--pki/base/common/src/com/netscape/cms/selftests/kra/KRAPresence.java193
-rw-r--r--pki/base/common/src/com/netscape/cms/selftests/ocsp/OCSPPresence.java223
-rw-r--r--pki/base/common/src/com/netscape/cms/selftests/ocsp/OCSPValidity.java219
-rw-r--r--pki/base/common/src/com/netscape/cms/selftests/ra/RAPresence.java194
-rw-r--r--pki/base/common/src/com/netscape/cms/selftests/tks/TKSKnownSessionKey.java174
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/admin/ACLAdminServlet.java359
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/admin/AdminResources.java7
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/admin/AdminServlet.java362
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/admin/AuthAdminServlet.java621
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/admin/AuthCredentials.java38
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/admin/CAAdminServlet.java405
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/admin/CMSAdminServlet.java1156
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/admin/JobsAdminServlet.java487
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/admin/KRAAdminServlet.java123
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/admin/LogAdminServlet.java918
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/admin/OCSPAdminServlet.java132
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/admin/PolicyAdminServlet.java371
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/admin/ProfileAdminServlet.java783
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/admin/PublisherAdminServlet.java1484
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/admin/RAAdminServlet.java193
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/admin/RegistryAdminServlet.java103
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/admin/UsrGrpAdminServlet.java747
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/base/CMSServlet.java971
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/base/CMSStartServlet.java30
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/base/DisplayHtmlServlet.java27
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/base/DynamicVariablesServlet.java65
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/base/GetStats.java80
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/base/IndexServlet.java32
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/base/PortsServlet.java9
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/base/ProxyServlet.java300
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/base/SystemInfoServlet.java61
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/base/UserInfo.java19
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/CMCRevReqServlet.java497
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/ChallengeRevocationServlet1.java270
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/CloneRedirect.java41
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/DirAuthServlet.java36
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/DisableEnrollResult.java18
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/DisplayBySerial.java186
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/DisplayCRL.java140
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/DisplayHashUserEnroll.java36
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/DoRevoke.java435
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/DoRevokeTPS.java335
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/DoUnrevoke.java340
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/DoUnrevokeTPS.java279
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/EnableEnrollResult.java22
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/EnrollServlet.java841
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/GetBySerial.java108
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/GetCAChain.java480
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/GetCRL.java150
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/GetCertFromRequest.java133
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/GetEnableStatus.java29
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/GetInfo.java70
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/HashEnrollServlet.java694
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/ImportCertsTemplateFiller.java136
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/ListCerts.java401
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/Monitor.java75
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/ReasonToRevoke.java102
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/RemoteAuthConfig.java88
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/RenewalServlet.java338
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/RevocationServlet.java145
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/RevocationSuccessTemplateFiller.java38
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/SrchCerts.java187
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/UpdateCRL.java200
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/UpdateDir.java275
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/scep/CRSEnrollment.java3651
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/scep/ChallengePassword.java194
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/cert/scep/ExtensionsRequested.java189
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/common/AuthCredentials.java38
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/common/CMCOutputTemplate.java597
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/common/CMSFile.java4
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/common/CMSFileLoader.java53
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/common/CMSGWResources.java7
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/common/CMSGateway.java137
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/common/CMSLoadTemplate.java13
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/common/CMSRequest.java82
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/common/CMSTemplate.java194
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/common/CMSTemplateParams.java4
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/common/ECMSGWException.java6
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/common/GenErrorTemplateFiller.java47
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/common/GenPendingTemplateFiller.java84
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/common/GenRejectedTemplateFiller.java25
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/common/GenSuccessTemplateFiller.java22
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/common/GenSvcPendingTemplateFiller.java18
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/common/GenUnauthorizedTemplateFiller.java26
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/common/GenUnexpectedErrorTemplateFiller.java33
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/common/ICMSTemplateFiller.java24
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/common/IRawJS.java3
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/common/IndexTemplateFiller.java21
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/common/RawJS.java3
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/common/Utils.java14
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/connector/CloneServlet.java376
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/connector/ConnectorServlet.java543
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/connector/GenerateKeyPairServlet.java150
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/connector/TokenKeyRecoveryServlet.java188
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/AdminAuthenticatePanel.java64
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/AdminPanel.java140
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/AgentAuthenticatePanel.java69
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/AuthenticatePanel.java49
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/BackupKeyCertPanel.java104
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/BaseServlet.java43
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/CAInfoPanel.java92
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/Cert.java7
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/CertPrettyPrintPanel.java19
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/CertRequestPanel.java203
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/CertUtil.java230
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/CheckIdentity.java11
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigBaseServlet.java50
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigCertApprovalCallback.java10
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigCertReqServlet.java2
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigCloneServlet.java2
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigDatabaseServlet.java15
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigHSMLoginPanel.java93
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigHSMServlet.java16
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigImportCertServlet.java2
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigJoinServlet.java28
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigRootCAServlet.java27
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/CreateSubsystemPanel.java53
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/DatabasePanel.java598
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/DatabaseServlet.java2
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/DisplayCertChainPanel.java55
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/DisplayServlet.java2
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/DonePanel.java258
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/DownloadPKCS12.java24
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/GetCertChain.java21
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/GetConfigEntries.java53
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/GetCookie.java98
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/GetDomainXML.java73
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/GetStatus.java22
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/GetSubsystemCert.java23
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/GetTokenInfo.java25
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/GetTransportCert.java45
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/HierarchyPanel.java37
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/ImportAdminCertPanel.java85
-rwxr-xr-xpki/base/common/src/com/netscape/cms/servlet/csadmin/ImportCAChainPanel.java16
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/ImportTransportCert.java57
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/LDAPSecurityDomainSessionTable.java68
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/LoginServlet.java6
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/MainPageServlet.java41
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/ModulePanel.java55
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/ModuleServlet.java16
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/NamePanel.java581
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/RegisterUser.java191
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/RestoreKeyCertPanel.java219
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/SavePKCS12Panel.java25
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/SecurityDomainLogin.java9
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/SecurityDomainPanel.java230
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/SecurityDomainSessionTable.java18
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/SessionTimer.java10
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/SizePanel.java326
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/TokenAuthenticate.java22
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateConnector.java52
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateDomainXML.java227
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateNumberRange.java81
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateOCSPConfig.java53
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/WelcomePanel.java28
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/WelcomeServlet.java2
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/WizardPanelBase.java631
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/filter/AdminRequestFilter.java82
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/filter/AgentRequestFilter.java80
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/filter/EEClientAuthRequestFilter.java82
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/filter/EERequestFilter.java128
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/key/ConfirmRecoverBySerial.java55
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/key/DisplayBySerial.java40
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/key/DisplayBySerialForRecovery.java59
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/key/DisplayTransport.java33
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/key/ExamineRecovery.java95
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/key/GetApprovalStatus.java60
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/key/GetAsyncPk12.java89
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/key/GetPk12.java82
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/key/GrantAsyncRecovery.java53
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/key/GrantRecovery.java74
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/key/KeyRecordParser.java32
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/key/RecoverBySerial.java271
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/key/SrchKey.java86
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/key/SrchKeyForRecovery.java102
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/ocsp/AddCAServlet.java152
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/ocsp/AddCRLServlet.java359
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/ocsp/CheckCertServlet.java46
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/ocsp/GetOCSPInfo.java42
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/ocsp/ListCAServlet.java54
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/ocsp/OCSPServlet.java149
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/ocsp/RemoveCAServlet.java116
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/processors/CMCProcessor.java105
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/processors/CRMFProcessor.java134
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/processors/IPKIProcessor.java6
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/processors/KeyGenProcessor.java36
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/processors/PKCS10Processor.java87
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/processors/PKIProcessor.java149
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/profile/ProfileApproveServlet.java158
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/profile/ProfileListServlet.java40
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/profile/ProfileProcessServlet.java269
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/profile/ProfileReviewServlet.java102
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/profile/ProfileSelectServlet.java89
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/profile/ProfileServlet.java168
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/profile/ProfileSubmitCMCServlet.java339
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/profile/ProfileSubmitServlet.java749
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/profile/SSLClientCertProvider.java3
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/request/CertReqParser.java322
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/request/CheckRequest.java222
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/request/IReqParser.java11
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/request/KeyReqParser.java8
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/request/ProcessCertReq.java1094
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/request/ProcessReq.java127
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/request/QueryReq.java622
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/request/ReqParser.java31
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/request/SearchReqs.java68
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/tks/TokenServlet.java1087
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/wizard/IWizardPanel.java14
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/wizard/WizardServlet.java403
-rw-r--r--pki/base/common/src/com/netscape/cms/shares/OldJoinShares.java93
-rw-r--r--pki/base/common/src/com/netscape/cms/shares/OldShare.java58
-rw-r--r--pki/base/common/src/com/netscape/cmscore/apps/CMSEngine.java701
-rw-r--r--pki/base/common/src/com/netscape/cmscore/apps/CommandQueue.java26
-rw-r--r--pki/base/common/src/com/netscape/cmscore/apps/PKIServerEvent.java3
-rw-r--r--pki/base/common/src/com/netscape/cmscore/apps/PKIServerListener.java6
-rw-r--r--pki/base/common/src/com/netscape/cmscore/apps/Setup.java312
-rw-r--r--pki/base/common/src/com/netscape/cmscore/apps/Upgrade.java352
-rw-r--r--pki/base/common/src/com/netscape/cmscore/authentication/AuthSubsystem.java135
-rw-r--r--pki/base/common/src/com/netscape/cmscore/authentication/CertUserDBAuthentication.java87
-rw-r--r--pki/base/common/src/com/netscape/cmscore/authentication/ChallengePhraseAuthentication.java135
-rw-r--r--pki/base/common/src/com/netscape/cmscore/authentication/NullAuthentication.java62
-rw-r--r--pki/base/common/src/com/netscape/cmscore/authentication/PasswdUserDBAuthentication.java83
-rw-r--r--pki/base/common/src/com/netscape/cmscore/authentication/SSLClientCertAuthentication.java76
-rw-r--r--pki/base/common/src/com/netscape/cmscore/authentication/VerifiedCert.java17
-rw-r--r--pki/base/common/src/com/netscape/cmscore/authentication/VerifiedCerts.java30
-rw-r--r--pki/base/common/src/com/netscape/cmscore/authorization/AuthzSubsystem.java132
-rw-r--r--pki/base/common/src/com/netscape/cmscore/base/ArgBlock.java233
-rw-r--r--pki/base/common/src/com/netscape/cmscore/base/FileConfigStore.java74
-rw-r--r--pki/base/common/src/com/netscape/cmscore/base/JDialogPasswordCallback.java88
-rw-r--r--pki/base/common/src/com/netscape/cmscore/base/PropConfigStore.java238
-rw-r--r--pki/base/common/src/com/netscape/cmscore/base/SimpleProperties.java294
-rw-r--r--pki/base/common/src/com/netscape/cmscore/base/SourceConfigStore.java14
-rw-r--r--pki/base/common/src/com/netscape/cmscore/base/SubsystemLoader.java4
-rw-r--r--pki/base/common/src/com/netscape/cmscore/base/SubsystemRegistry.java3
-rw-r--r--pki/base/common/src/com/netscape/cmscore/cert/CertDateCompare.java8
-rw-r--r--pki/base/common/src/com/netscape/cmscore/cert/CertPrettyPrint.java7
-rw-r--r--pki/base/common/src/com/netscape/cmscore/cert/CertUtils.java293
-rw-r--r--pki/base/common/src/com/netscape/cmscore/cert/CertificatePair.java118
-rw-r--r--pki/base/common/src/com/netscape/cmscore/cert/CrlCachePrettyPrint.java114
-rw-r--r--pki/base/common/src/com/netscape/cmscore/cert/CrlPrettyPrint.java7
-rw-r--r--pki/base/common/src/com/netscape/cmscore/cert/CrossCertPairSubsystem.java136
-rw-r--r--pki/base/common/src/com/netscape/cmscore/cert/ExtPrettyPrint.java8
-rw-r--r--pki/base/common/src/com/netscape/cmscore/cert/OidLoaderSubsystem.java88
-rw-r--r--pki/base/common/src/com/netscape/cmscore/cert/PrettyPrintFormat.java82
-rw-r--r--pki/base/common/src/com/netscape/cmscore/cert/PrettyPrintResources.java245
-rw-r--r--pki/base/common/src/com/netscape/cmscore/cert/PubKeyPrettyPrint.java7
-rw-r--r--pki/base/common/src/com/netscape/cmscore/cert/X500NameSubsystem.java109
-rw-r--r--pki/base/common/src/com/netscape/cmscore/connector/HttpConnFactory.java173
-rw-r--r--pki/base/common/src/com/netscape/cmscore/connector/HttpConnection.java82
-rw-r--r--pki/base/common/src/com/netscape/cmscore/connector/HttpConnector.java63
-rw-r--r--pki/base/common/src/com/netscape/cmscore/connector/HttpPKIMessage.java90
-rw-r--r--pki/base/common/src/com/netscape/cmscore/connector/HttpRequestEncoder.java10
-rw-r--r--pki/base/common/src/com/netscape/cmscore/connector/LocalConnector.java75
-rw-r--r--pki/base/common/src/com/netscape/cmscore/connector/RemoteAuthority.java12
-rw-r--r--pki/base/common/src/com/netscape/cmscore/connector/RequestTransfer.java40
-rw-r--r--pki/base/common/src/com/netscape/cmscore/connector/Resender.java89
-rw-r--r--pki/base/common/src/com/netscape/cmscore/crmf/CRMFParser.java36
-rw-r--r--pki/base/common/src/com/netscape/cmscore/crmf/PKIArchiveOptionsContainer.java2
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/BigIntegerMapper.java30
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/ByteArrayMapper.java32
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/CRLDBSchema.java8
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/CRLIssuingPointRecord.java22
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/CRLRepository.java225
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/CertDBSchema.java9
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/CertRecord.java20
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/CertRecordList.java35
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/CertRecordMapper.java23
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/CertificateRepository.java758
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/DBRegistry.java162
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/DBSSession.java169
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/DBSUtil.java12
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/DBSearchResults.java28
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/DBSubsystem.java432
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/DBVirtualList.java464
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/DateArrayMapper.java28
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/DateMapper.java24
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/IntegerMapper.java30
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/KeyDBSchema.java16
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/KeyRecord.java41
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/KeyRecordList.java18
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/KeyRecordMapper.java47
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/KeyRepository.java266
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/KeyStateMapper.java25
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/LdapFilterConverter.java9
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/LongMapper.java30
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/MetaInfoMapper.java26
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/ObjectStreamMapper.java46
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/PublicKeyMapper.java44
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/ReplicaIDRepository.java22
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/Repository.java217
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/RepositoryRecord.java4
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/RepositorySchema.java8
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/RevocationInfo.java19
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/RevocationInfoMapper.java43
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/StringMapper.java32
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/StringVectorMapper.java28
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/X500NameMapper.java42
-rw-r--r--pki/base/common/src/com/netscape/cmscore/dbs/X509CertImplMapper.java77
-rw-r--r--pki/base/common/src/com/netscape/cmscore/extensions/CMSExtensionsMap.java29
-rw-r--r--pki/base/common/src/com/netscape/cmscore/extensions/KeyUsage.java63
-rw-r--r--pki/base/common/src/com/netscape/cmscore/jobs/CronItem.java49
-rw-r--r--pki/base/common/src/com/netscape/cmscore/jobs/CronRange.java36
-rw-r--r--pki/base/common/src/com/netscape/cmscore/jobs/JobCron.java87
-rw-r--r--pki/base/common/src/com/netscape/cmscore/jobs/JobsScheduler.java163
-rw-r--r--pki/base/common/src/com/netscape/cmscore/ldap/LdapAndExpression.java22
-rw-r--r--pki/base/common/src/com/netscape/cmscore/ldap/LdapConnModule.java48
-rw-r--r--pki/base/common/src/com/netscape/cmscore/ldap/LdapOrExpression.java25
-rw-r--r--pki/base/common/src/com/netscape/cmscore/ldap/LdapPredicateParser.java159
-rw-r--r--pki/base/common/src/com/netscape/cmscore/ldap/LdapPublishModule.java400
-rw-r--r--pki/base/common/src/com/netscape/cmscore/ldap/LdapRequestListener.java271
-rw-r--r--pki/base/common/src/com/netscape/cmscore/ldap/LdapRule.java88
-rw-r--r--pki/base/common/src/com/netscape/cmscore/ldap/LdapSimpleExpression.java50
-rw-r--r--pki/base/common/src/com/netscape/cmscore/ldap/PublishObject.java4
-rw-r--r--pki/base/common/src/com/netscape/cmscore/ldap/PublisherProcessor.java476
-rw-r--r--pki/base/common/src/com/netscape/cmscore/ldapconn/LdapAnonConnFactory.java295
-rw-r--r--pki/base/common/src/com/netscape/cmscore/ldapconn/LdapAnonConnection.java36
-rw-r--r--pki/base/common/src/com/netscape/cmscore/ldapconn/LdapAuthInfo.java137
-rw-r--r--pki/base/common/src/com/netscape/cmscore/ldapconn/LdapBoundConnFactory.java340
-rw-r--r--pki/base/common/src/com/netscape/cmscore/ldapconn/LdapBoundConnection.java122
-rw-r--r--pki/base/common/src/com/netscape/cmscore/ldapconn/LdapConnInfo.java45
-rw-r--r--pki/base/common/src/com/netscape/cmscore/ldapconn/LdapJssSSLSocketFactory.java16
-rw-r--r--pki/base/common/src/com/netscape/cmscore/listeners/ListenerPlugin.java13
-rw-r--r--pki/base/common/src/com/netscape/cmscore/logging/AuditEventFactory.java14
-rw-r--r--pki/base/common/src/com/netscape/cmscore/logging/AuditFormat.java66
-rw-r--r--pki/base/common/src/com/netscape/cmscore/logging/LogQueue.java39
-rw-r--r--pki/base/common/src/com/netscape/cmscore/logging/LogSubsystem.java27
-rw-r--r--pki/base/common/src/com/netscape/cmscore/logging/Logger.java131
-rw-r--r--pki/base/common/src/com/netscape/cmscore/logging/SignedAuditEventFactory.java17
-rw-r--r--pki/base/common/src/com/netscape/cmscore/logging/SignedAuditLogger.java14
-rw-r--r--pki/base/common/src/com/netscape/cmscore/logging/SystemEventFactory.java17
-rw-r--r--pki/base/common/src/com/netscape/cmscore/notification/EmailFormProcessor.java55
-rw-r--r--pki/base/common/src/com/netscape/cmscore/notification/EmailResolverKeys.java24
-rw-r--r--pki/base/common/src/com/netscape/cmscore/notification/EmailTemplate.java54
-rw-r--r--pki/base/common/src/com/netscape/cmscore/notification/ReqCertEmailResolver.java66
-rw-r--r--pki/base/common/src/com/netscape/cmscore/notification/ReqCertSANameEmailResolver.java120
-rw-r--r--pki/base/common/src/com/netscape/cmscore/policy/AndExpression.java16
-rw-r--r--pki/base/common/src/com/netscape/cmscore/policy/GeneralNameUtil.java309
-rw-r--r--pki/base/common/src/com/netscape/cmscore/policy/GenericPolicyProcessor.java626
-rw-r--r--pki/base/common/src/com/netscape/cmscore/policy/JavaScriptRequestProxy.java4
-rw-r--r--pki/base/common/src/com/netscape/cmscore/policy/OrExpression.java19
-rw-r--r--pki/base/common/src/com/netscape/cmscore/policy/PolicyPredicateParser.java157
-rw-r--r--pki/base/common/src/com/netscape/cmscore/policy/PolicySet.java90
-rw-r--r--pki/base/common/src/com/netscape/cmscore/policy/SimpleExpression.java47
-rw-r--r--pki/base/common/src/com/netscape/cmscore/profile/ProfileSubsystem.java65
-rw-r--r--pki/base/common/src/com/netscape/cmscore/registry/PluginInfo.java7
-rw-r--r--pki/base/common/src/com/netscape/cmscore/registry/PluginRegistry.java67
-rw-r--r--pki/base/common/src/com/netscape/cmscore/request/ARequestQueue.java383
-rw-r--r--pki/base/common/src/com/netscape/cmscore/request/ARequestRecord.java9
-rw-r--r--pki/base/common/src/com/netscape/cmscore/request/CertRequestConstants.java14
-rw-r--r--pki/base/common/src/com/netscape/cmscore/request/ExtDataHashtable.java19
-rw-r--r--pki/base/common/src/com/netscape/cmscore/request/RequestAttr.java14
-rw-r--r--pki/base/common/src/com/netscape/cmscore/request/RequestQueue.java248
-rw-r--r--pki/base/common/src/com/netscape/cmscore/request/RequestRecord.java313
-rw-r--r--pki/base/common/src/com/netscape/cmscore/request/RequestRepository.java89
-rw-r--r--pki/base/common/src/com/netscape/cmscore/request/RequestSubsystem.java69
-rw-r--r--pki/base/common/src/com/netscape/cmscore/request/Schema.java3
-rw-r--r--pki/base/common/src/com/netscape/cmscore/security/CASigningCert.java39
-rw-r--r--pki/base/common/src/com/netscape/cmscore/security/CertificateInfo.java81
-rw-r--r--pki/base/common/src/com/netscape/cmscore/security/JssSubsystem.java638
-rw-r--r--pki/base/common/src/com/netscape/cmscore/security/KRATransportCert.java38
-rw-r--r--pki/base/common/src/com/netscape/cmscore/security/KeyCertUtil.java323
-rw-r--r--pki/base/common/src/com/netscape/cmscore/security/OCSPSigningCert.java34
-rw-r--r--pki/base/common/src/com/netscape/cmscore/security/PWCBsdr.java81
-rw-r--r--pki/base/common/src/com/netscape/cmscore/security/PWUtil.java22
-rw-r--r--pki/base/common/src/com/netscape/cmscore/security/PWsdrCache.java146
-rw-r--r--pki/base/common/src/com/netscape/cmscore/security/Provider.java13
-rw-r--r--pki/base/common/src/com/netscape/cmscore/security/RASigningCert.java36
-rw-r--r--pki/base/common/src/com/netscape/cmscore/security/SSLCert.java38
-rw-r--r--pki/base/common/src/com/netscape/cmscore/security/SSLSelfSignedCert.java38
-rw-r--r--pki/base/common/src/com/netscape/cmscore/security/SubsystemCert.java3
-rw-r--r--pki/base/common/src/com/netscape/cmscore/selftests/SelfTestOrderedInstance.java45
-rw-r--r--pki/base/common/src/com/netscape/cmscore/selftests/SelfTestSubsystem.java827
-rw-r--r--pki/base/common/src/com/netscape/cmscore/time/SimpleTimeSource.java2
-rw-r--r--pki/base/common/src/com/netscape/cmscore/usrgrp/CertDNCertUserLocator.java19
-rw-r--r--pki/base/common/src/com/netscape/cmscore/usrgrp/ExactMatchCertUserLocator.java19
-rw-r--r--pki/base/common/src/com/netscape/cmscore/usrgrp/Group.java6
-rw-r--r--pki/base/common/src/com/netscape/cmscore/usrgrp/UGSubsystem.java624
-rw-r--r--pki/base/common/src/com/netscape/cmscore/usrgrp/User.java10
-rw-r--r--pki/base/common/src/com/netscape/cmscore/util/Assert.java1
-rw-r--r--pki/base/common/src/com/netscape/cmscore/util/AssertionException.java5
-rw-r--r--pki/base/common/src/com/netscape/cmscore/util/Debug.java256
-rw-r--r--pki/base/common/src/com/netscape/cmscore/util/ExceptionFormatter.java18
-rw-r--r--pki/base/common/src/com/netscape/cmscore/util/FileAsString.java34
-rw-r--r--pki/base/common/src/com/netscape/cmscore/util/FileDialogFilter.java45
-rw-r--r--pki/base/common/src/com/netscape/cmscore/util/OsSubsystem.java169
-rw-r--r--pki/base/common/src/com/netscape/cmscore/util/PFXUtils.java56
-rw-r--r--pki/base/common/src/com/netscape/cmscore/util/ProfileSubsystem.java127
-rw-r--r--pki/base/common/src/com/netscape/cmscore/util/StatsSubsystem.java225
-rw-r--r--pki/base/common/src/com/netscape/cmscore/util/UtilMessage.java48
-rw-r--r--pki/base/common/src/com/netscape/cmscore/util/UtilResources.java33
-rw-r--r--pki/base/common/test/com/netscape/certsrv/app/CMSEngineDefaultStub.java193
-rw-r--r--pki/base/common/test/com/netscape/certsrv/authentication/AuthTokenTest.java37
-rw-r--r--pki/base/common/test/com/netscape/certsrv/logging/LoggerDefaultStub.java2
-rw-r--r--pki/base/common/test/com/netscape/certsrv/request/AgentApprovalsTest.java6
-rw-r--r--pki/base/common/test/com/netscape/cmscore/dbs/CertRecordListTest.java3
-rw-r--r--pki/base/common/test/com/netscape/cmscore/dbs/DBRegistryDefaultStub.java1
-rw-r--r--pki/base/common/test/com/netscape/cmscore/dbs/DBRegistryTest.java17
-rw-r--r--pki/base/common/test/com/netscape/cmscore/dbs/DBSubsystemDefaultStub.java175
-rw-r--r--pki/base/common/test/com/netscape/cmscore/dbs/DBVirtualListDefaultStub.java12
-rw-r--r--pki/base/common/test/com/netscape/cmscore/request/ExtAttrDynMapperTest.java23
-rw-r--r--pki/base/common/test/com/netscape/cmscore/request/RequestDefaultStub.java4
-rw-r--r--pki/base/common/test/com/netscape/cmscore/request/RequestQueueTest.java2
-rw-r--r--pki/base/common/test/com/netscape/cmscore/request/RequestRecordTest.java9
-rw-r--r--pki/base/common/test/com/netscape/cmscore/request/RequestTest.java81
-rw-r--r--pki/base/common/test/com/netscape/cmscore/test/CMSBaseTestCase.java46
-rw-r--r--pki/base/java-tools/src/com/netscape/cmstools/AtoB.java72
-rw-r--r--pki/base/java-tools/src/com/netscape/cmstools/AuditVerify.java382
-rw-r--r--pki/base/java-tools/src/com/netscape/cmstools/BtoA.java53
-rw-r--r--pki/base/java-tools/src/com/netscape/cmstools/CMCEnroll.java218
-rw-r--r--pki/base/java-tools/src/com/netscape/cmstools/CMCRequest.java402
-rw-r--r--pki/base/java-tools/src/com/netscape/cmstools/CMCResponse.java114
-rw-r--r--pki/base/java-tools/src/com/netscape/cmstools/CMCRevoke.java172
-rw-r--r--pki/base/java-tools/src/com/netscape/cmstools/CRMFPopClient.java802
-rw-r--r--pki/base/java-tools/src/com/netscape/cmstools/DRMTool.java4764
-rw-r--r--pki/base/java-tools/src/com/netscape/cmstools/ExtJoiner.java22
-rw-r--r--pki/base/java-tools/src/com/netscape/cmstools/GenExtKeyUsage.java15
-rw-r--r--pki/base/java-tools/src/com/netscape/cmstools/GenIssuerAltNameExt.java38
-rw-r--r--pki/base/java-tools/src/com/netscape/cmstools/GenSubjectAltNameExt.java38
-rw-r--r--pki/base/java-tools/src/com/netscape/cmstools/HttpClient.java107
-rw-r--r--pki/base/java-tools/src/com/netscape/cmstools/OCSPClient.java259
-rw-r--r--pki/base/java-tools/src/com/netscape/cmstools/PKCS10Client.java139
-rw-r--r--pki/base/java-tools/src/com/netscape/cmstools/PKCS12Export.java77
-rw-r--r--pki/base/java-tools/src/com/netscape/cmstools/PasswordCache.java274
-rw-r--r--pki/base/java-tools/src/com/netscape/cmstools/PrettyPrintCert.java94
-rw-r--r--pki/base/java-tools/src/com/netscape/cmstools/PrettyPrintCrl.java94
-rw-r--r--pki/base/java-tools/src/com/netscape/cmstools/TestCRLSigning.java31
-rw-r--r--pki/base/java-tools/src/com/netscape/cmstools/TokenInfo.java62
-rw-r--r--pki/base/kra/src/com/netscape/kra/EncryptionUnit.java134
-rw-r--r--pki/base/kra/src/com/netscape/kra/EnrollmentService.java382
-rw-r--r--pki/base/kra/src/com/netscape/kra/KRANotify.java9
-rw-r--r--pki/base/kra/src/com/netscape/kra/KRAPolicy.java5
-rw-r--r--pki/base/kra/src/com/netscape/kra/KRAService.java35
-rw-r--r--pki/base/kra/src/com/netscape/kra/KeyRecoveryAuthority.java675
-rw-r--r--pki/base/kra/src/com/netscape/kra/NetkeyKeygenService.java602
-rw-r--r--pki/base/kra/src/com/netscape/kra/RecoveryService.java397
-rw-r--r--pki/base/kra/src/com/netscape/kra/StorageKeyUnit.java509
-rw-r--r--pki/base/kra/src/com/netscape/kra/TokenKeyRecoveryService.java557
-rw-r--r--pki/base/kra/src/com/netscape/kra/TransportKeyUnit.java24
-rw-r--r--pki/base/migrate/80/MigrateSecurityDomain.java67
-rw-r--r--pki/base/ocsp/src/com/netscape/ocsp/EOCSPException.java4
-rw-r--r--pki/base/ocsp/src/com/netscape/ocsp/OCSPAuthority.java249
-rw-r--r--pki/base/ocsp/src/com/netscape/ocsp/OCSPResources.java7
-rw-r--r--pki/base/ocsp/src/com/netscape/ocsp/SigningUnit.java76
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/ConfigureCA.java656
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/ConfigureDRM.java649
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/ConfigureOCSP.java543
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/ConfigureRA.java1755
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/ConfigureSubCA.java624
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/ConfigureTKS.java535
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/ConfigureTPS.java2240
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/CreateInstance.java11
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/PKISilent.java97
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParseException.java53
-rwxr-xr-xpki/base/silent/src/com/netscape/pkisilent/argparser/ArgParser.java4120
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParserTest.java3023
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/BooleanHolder.java52
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/CharHolder.java52
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/DoubleHolder.java51
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/FloatHolder.java52
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/IntHolder.java51
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/LongHolder.java51
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/ObjectHolder.java52
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/SimpleExample.java66
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/StringHolder.java53
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/StringScanException.java54
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/StringScanner.java1168
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/AutoInstaller.java255
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/BaseState.java39
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/CMSConfig.java40
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/CMSInstance.java62
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/CMSLDAP.java129
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/CMSProperties.java354
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/CMSTask.java15
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/CertificateRecord.java8
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/ComCrypto.java168
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/Con2Agent.java61
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/DirEnroll.java71
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/ParseXML.java19
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/PostQuery.java33
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/Request.java212
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/ServerInfo.java67
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/TestClient.java678
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/UserEnroll.java116
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/Utilities.java45
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/checkRequest.java90
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/http/CertSelection.java31
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/http/HTMLDocument.java1192
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/http/HTTPClient.java2361
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/http/HTTPResponse.java605
-rw-r--r--pki/base/symkey/src/com/netscape/symkey/SessionKey.java104
-rw-r--r--pki/base/test/src/com/netscape/test/TestListener.java29
-rw-r--r--pki/base/tks/src/com/netscape/tks/TKSAuthority.java74
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/crypto/CryptoUtil.java407
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/crypto/Module.java30
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/crypto/Token.java18
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/http/ConnectAsync.java7
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/http/Http.java1
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/http/HttpClient.java52
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/http/HttpEofException.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/http/HttpMessage.java40
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/http/HttpProtocolException.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/http/HttpRequest.java29
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/http/HttpResponse.java17
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/http/JssSSLSocketFactory.java54
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/ldap/LDAPUtil.java8
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/net/ISocketFactory.java22
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/ocsp/BasicOCSPResponse.java153
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/ocsp/CertID.java234
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/ocsp/CertStatus.java7
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/ocsp/GoodInfo.java92
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/ocsp/KeyHashID.java133
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/ocsp/NameID.java137
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/ocsp/OCSPRequest.java215
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/ocsp/OCSPResponse.java202
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/ocsp/OCSPResponseStatus.java160
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/ocsp/Request.java225
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/ocsp/ResponderID.java8
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/ocsp/Response.java9
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/ocsp/ResponseBytes.java190
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/ocsp/ResponseData.java123
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/ocsp/RevokedInfo.java126
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/ocsp/Signature.java243
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/ocsp/SingleResponse.java265
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/ocsp/TBSRequest.java103
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/ocsp/UnknownInfo.java92
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/password/IPasswordReader.java3
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/password/IPasswordStore.java6
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/password/IPasswordWriter.java7
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/password/PlainPasswordFile.java24
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/password/PlainPasswordReader.java23
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/password/PlainPasswordWriter.java32
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/AccessAccept.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/AccessChallenge.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/AccessReject.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/AccessRequest.java3
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/Attribute.java14
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/AttributeFactory.java56
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/AttributeSet.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/Authenticator.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/CHAPChallengeAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/CHAPPasswordAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/CallbackIdAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/CallbackNumberAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/CallerStationIdAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/CallingStationIdAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/ChallengeException.java3
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/FilterIdAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkLinkAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkNetworkAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkZoneAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/FramedCompressionAttribute.java8
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/FramedIPAddressAttribute.java10
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/FramedIPNetmaskAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/FramedIPXNetworkAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/FramedMTUAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/FramedProtocolAttribute.java8
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/FramedRouteAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/FramedRoutingAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/GenericAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/IdleTimeoutAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/LoginIPHostAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/LoginLATGroupAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/LoginLATNodeAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/LoginLATPortAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/LoginLATServiceAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/LoginServiceAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/LoginTCPPortAttribute.java12
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/NASClassAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/NASIPAddressAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/NASIdentifierAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/NASPacket.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/NASPortAttribute.java12
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/NASPortTypeAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/Packet.java15
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/PacketFactory.java4
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/PortLimitAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/ProxyStateAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/RadiusConn.java65
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/RejectException.java5
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/ReplyMessageAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/RequestAuthenticator.java6
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/ResponseAuthenticator.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/ServerPacket.java6
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/ServiceTypeAttribute.java8
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/SessionTimeoutAttribute.java12
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/StateAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/TerminationActionAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/UserNameAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/UserPasswordAttribute.java6
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/radius/VendorSpecificAttribute.java2
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/scep/CRSPKIMessage.java463
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/util/Cert.java34
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/util/Fmt.java158
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/util/HMACDigest.java62
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/util/Utils.java156
-rw-r--r--pki/base/util/src/com/netscape/cmsutil/xml/XMLObject.java34
-rw-r--r--pki/base/util/src/netscape/net/NetworkClient.java57
-rw-r--r--pki/base/util/src/netscape/net/TransferProtocolClient.java141
-rw-r--r--pki/base/util/src/netscape/net/smtp/SmtpClient.java300
-rw-r--r--pki/base/util/src/netscape/net/smtp/SmtpProtocolException.java7
-rw-r--r--pki/base/util/src/netscape/security/acl/AclEntryImpl.java152
-rw-r--r--pki/base/util/src/netscape/security/acl/AclImpl.java482
-rw-r--r--pki/base/util/src/netscape/security/acl/AllPermissionsImpl.java10
-rw-r--r--pki/base/util/src/netscape/security/acl/GroupImpl.java143
-rw-r--r--pki/base/util/src/netscape/security/acl/OwnerImpl.java100
-rw-r--r--pki/base/util/src/netscape/security/acl/PermissionImpl.java29
-rw-r--r--pki/base/util/src/netscape/security/acl/PrincipalImpl.java41
-rw-r--r--pki/base/util/src/netscape/security/acl/WorldGroupImpl.java9
-rw-r--r--pki/base/util/src/netscape/security/extensions/AccessDescription.java15
-rw-r--r--pki/base/util/src/netscape/security/extensions/AuthInfoAccessExtension.java63
-rw-r--r--pki/base/util/src/netscape/security/extensions/CertInfo.java36
-rw-r--r--pki/base/util/src/netscape/security/extensions/CertificateRenewalWindowExtension.java33
-rw-r--r--pki/base/util/src/netscape/security/extensions/CertificateScopeEntry.java17
-rw-r--r--pki/base/util/src/netscape/security/extensions/CertificateScopeOfUseExtension.java40
-rw-r--r--pki/base/util/src/netscape/security/extensions/ExtendedKeyUsageExtension.java57
-rw-r--r--pki/base/util/src/netscape/security/extensions/GenericASN1Extension.java331
-rw-r--r--pki/base/util/src/netscape/security/extensions/InhibitAnyPolicyExtension.java61
-rw-r--r--pki/base/util/src/netscape/security/extensions/KerberosName.java74
-rw-r--r--pki/base/util/src/netscape/security/extensions/NSCertTypeExtension.java128
-rw-r--r--pki/base/util/src/netscape/security/extensions/OCSPNoCheckExtension.java26
-rw-r--r--pki/base/util/src/netscape/security/extensions/PresenceServerExtension.java394
-rw-r--r--pki/base/util/src/netscape/security/extensions/SubjectInfoAccessExtension.java39
-rw-r--r--pki/base/util/src/netscape/security/pkcs/ContentInfo.java160
-rw-r--r--pki/base/util/src/netscape/security/pkcs/EncodingException.java4
-rw-r--r--pki/base/util/src/netscape/security/pkcs/PKCS10.java453
-rw-r--r--pki/base/util/src/netscape/security/pkcs/PKCS10Attribute.java189
-rw-r--r--pki/base/util/src/netscape/security/pkcs/PKCS10Attributes.java68
-rw-r--r--pki/base/util/src/netscape/security/pkcs/PKCS7.java537
-rw-r--r--pki/base/util/src/netscape/security/pkcs/PKCS8Key.java548
-rw-r--r--pki/base/util/src/netscape/security/pkcs/PKCS9Attribute.java1165
-rw-r--r--pki/base/util/src/netscape/security/pkcs/PKCS9Attributes.java353
-rw-r--r--pki/base/util/src/netscape/security/pkcs/ParsingException.java4
-rw-r--r--pki/base/util/src/netscape/security/pkcs/SignerInfo.java489
-rw-r--r--pki/base/util/src/netscape/security/provider/CMS.java29
-rw-r--r--pki/base/util/src/netscape/security/provider/DSA.java807
-rwxr-xr-xpki/base/util/src/netscape/security/provider/DSAKeyFactory.java334
-rw-r--r--pki/base/util/src/netscape/security/provider/DSAKeyPairGenerator.java530
-rwxr-xr-xpki/base/util/src/netscape/security/provider/DSAParameterGenerator.java330
-rwxr-xr-xpki/base/util/src/netscape/security/provider/DSAParameters.java112
-rw-r--r--pki/base/util/src/netscape/security/provider/DSAPrivateKey.java116
-rw-r--r--pki/base/util/src/netscape/security/provider/DSAPublicKey.java94
-rw-r--r--pki/base/util/src/netscape/security/provider/MD5.java469
-rw-r--r--pki/base/util/src/netscape/security/provider/RSAPublicKey.java180
-rw-r--r--pki/base/util/src/netscape/security/provider/SHA.java490
-rw-r--r--pki/base/util/src/netscape/security/provider/Sun.java106
-rw-r--r--pki/base/util/src/netscape/security/provider/SystemIdentity.java32
-rw-r--r--pki/base/util/src/netscape/security/provider/SystemSigner.java43
-rw-r--r--pki/base/util/src/netscape/security/provider/X509CertificateFactory.java54
-rw-r--r--pki/base/util/src/netscape/security/util/ASN1CharStrConvMap.java261
-rw-r--r--pki/base/util/src/netscape/security/util/BigInt.java214
-rw-r--r--pki/base/util/src/netscape/security/util/BitArray.java281
-rw-r--r--pki/base/util/src/netscape/security/util/ByteArrayLexOrder.java52
-rw-r--r--pki/base/util/src/netscape/security/util/ByteArrayTagOrder.java33
-rw-r--r--pki/base/util/src/netscape/security/util/ByteToCharIA5String.java58
-rw-r--r--pki/base/util/src/netscape/security/util/ByteToCharPrintable.java81
-rw-r--r--pki/base/util/src/netscape/security/util/ByteToCharUnicode.java241
-rw-r--r--pki/base/util/src/netscape/security/util/ByteToCharUniversalString.java107
-rw-r--r--pki/base/util/src/netscape/security/util/CertPrettyPrint.java144
-rw-r--r--pki/base/util/src/netscape/security/util/CharToByteIA5String.java78
-rw-r--r--pki/base/util/src/netscape/security/util/CharToBytePrintable.java134
-rw-r--r--pki/base/util/src/netscape/security/util/CharToByteUniversalString.java64
-rw-r--r--pki/base/util/src/netscape/security/util/CrlPrettyPrint.java121
-rw-r--r--pki/base/util/src/netscape/security/util/DerEncoder.java16
-rw-r--r--pki/base/util/src/netscape/security/util/DerInputBuffer.java238
-rw-r--r--pki/base/util/src/netscape/security/util/DerInputStream.java740
-rw-r--r--pki/base/util/src/netscape/security/util/DerOutputStream.java745
-rw-r--r--pki/base/util/src/netscape/security/util/DerValue.java695
-rw-r--r--pki/base/util/src/netscape/security/util/ExtPrettyPrint.java354
-rw-r--r--pki/base/util/src/netscape/security/util/ObjectIdentifier.java614
-rw-r--r--pki/base/util/src/netscape/security/util/PrettyPrintFormat.java158
-rw-r--r--pki/base/util/src/netscape/security/util/PrettyPrintResources.java253
-rw-r--r--pki/base/util/src/netscape/security/util/PubKeyPrettyPrint.java53
-rwxr-xr-xpki/base/util/src/netscape/security/x509/ACertAttrSet.java78
-rw-r--r--pki/base/util/src/netscape/security/x509/AVA.java328
-rw-r--r--pki/base/util/src/netscape/security/x509/AVAValueConverter.java76
-rw-r--r--pki/base/util/src/netscape/security/x509/AlgIdDSA.java173
-rw-r--r--pki/base/util/src/netscape/security/x509/AlgorithmId.java996
-rw-r--r--pki/base/util/src/netscape/security/x509/Attribute.java329
-rw-r--r--pki/base/util/src/netscape/security/x509/AuthorityKeyIdentifierExtension.java166
-rw-r--r--pki/base/util/src/netscape/security/x509/BasicConstraintsExtension.java252
-rw-r--r--pki/base/util/src/netscape/security/x509/CPSuri.java15
-rw-r--r--pki/base/util/src/netscape/security/x509/CRLDistributionPoint.java529
-rw-r--r--pki/base/util/src/netscape/security/x509/CRLDistributionPointsExtension.java332
-rwxr-xr-xpki/base/util/src/netscape/security/x509/CRLExtensions.java76
-rwxr-xr-xpki/base/util/src/netscape/security/x509/CRLNumberExtension.java106
-rw-r--r--pki/base/util/src/netscape/security/x509/CRLReasonExtension.java110
-rw-r--r--pki/base/util/src/netscape/security/x509/CertAndKeyGen.java335
-rwxr-xr-xpki/base/util/src/netscape/security/x509/CertAttrSet.java44
-rw-r--r--pki/base/util/src/netscape/security/x509/CertException.java83
-rw-r--r--pki/base/util/src/netscape/security/x509/CertParseError.java11
-rw-r--r--pki/base/util/src/netscape/security/x509/CertificateAlgorithmId.java43
-rw-r--r--pki/base/util/src/netscape/security/x509/CertificateChain.java192
-rw-r--r--pki/base/util/src/netscape/security/x509/CertificateExtensions.java71
-rw-r--r--pki/base/util/src/netscape/security/x509/CertificateIssuerExtension.java73
-rw-r--r--pki/base/util/src/netscape/security/x509/CertificateIssuerName.java31
-rw-r--r--pki/base/util/src/netscape/security/x509/CertificateIssuerUniqueIdentity.java39
-rw-r--r--pki/base/util/src/netscape/security/x509/CertificatePoliciesExtension.java273
-rw-r--r--pki/base/util/src/netscape/security/x509/CertificatePolicyId.java9
-rw-r--r--pki/base/util/src/netscape/security/x509/CertificatePolicyInfo.java52
-rw-r--r--pki/base/util/src/netscape/security/x509/CertificatePolicyMap.java10
-rw-r--r--pki/base/util/src/netscape/security/x509/CertificatePolicySet.java16
-rw-r--r--pki/base/util/src/netscape/security/x509/CertificateSerialNumber.java35
-rw-r--r--pki/base/util/src/netscape/security/x509/CertificateSubjectName.java41
-rw-r--r--pki/base/util/src/netscape/security/x509/CertificateSubjectUniqueIdentity.java47
-rw-r--r--pki/base/util/src/netscape/security/x509/CertificateValidity.java83
-rw-r--r--pki/base/util/src/netscape/security/x509/CertificateVersion.java52
-rw-r--r--pki/base/util/src/netscape/security/x509/CertificateX509Key.java47
-rw-r--r--pki/base/util/src/netscape/security/x509/DNSName.java12
-rwxr-xr-xpki/base/util/src/netscape/security/x509/DeltaCRLIndicatorExtension.java82
-rw-r--r--pki/base/util/src/netscape/security/x509/DirStrConverter.java248
-rw-r--r--pki/base/util/src/netscape/security/x509/DisplayText.java41
-rw-r--r--pki/base/util/src/netscape/security/x509/EDIPartyName.java35
-rw-r--r--pki/base/util/src/netscape/security/x509/Extension.java67
-rw-r--r--pki/base/util/src/netscape/security/x509/Extensions.java60
-rw-r--r--pki/base/util/src/netscape/security/x509/FreshestCRLExtension.java332
-rw-r--r--pki/base/util/src/netscape/security/x509/GeneralName.java132
-rw-r--r--pki/base/util/src/netscape/security/x509/GeneralNameInterface.java14
-rw-r--r--pki/base/util/src/netscape/security/x509/GeneralNames.java110
-rw-r--r--pki/base/util/src/netscape/security/x509/GeneralNamesException.java4
-rw-r--r--pki/base/util/src/netscape/security/x509/GeneralSubtree.java59
-rw-r--r--pki/base/util/src/netscape/security/x509/GeneralSubtrees.java26
-rw-r--r--pki/base/util/src/netscape/security/x509/GenericValueConverter.java198
-rw-r--r--pki/base/util/src/netscape/security/x509/HoldInstructionExtension.java148
-rw-r--r--pki/base/util/src/netscape/security/x509/IA5StringConverter.java136
-rw-r--r--pki/base/util/src/netscape/security/x509/IPAddressName.java325
-rw-r--r--pki/base/util/src/netscape/security/x509/InvalidIPAddressException.java17
-rwxr-xr-xpki/base/util/src/netscape/security/x509/InvalidityDateExtension.java88
-rw-r--r--pki/base/util/src/netscape/security/x509/IssuerAlternativeNameExtension.java130
-rw-r--r--pki/base/util/src/netscape/security/x509/IssuingDistributionPoint.java239
-rw-r--r--pki/base/util/src/netscape/security/x509/IssuingDistributionPointExtension.java231
-rw-r--r--pki/base/util/src/netscape/security/x509/KeyIdentifier.java18
-rw-r--r--pki/base/util/src/netscape/security/x509/KeyUsageExtension.java321
-rw-r--r--pki/base/util/src/netscape/security/x509/LdapDNStrConverter.java124
-rw-r--r--pki/base/util/src/netscape/security/x509/LdapV3DNStrConverter.java1028
-rw-r--r--pki/base/util/src/netscape/security/x509/NSCCommentExtension.java96
-rw-r--r--pki/base/util/src/netscape/security/x509/NameConstraintsExtension.java170
-rw-r--r--pki/base/util/src/netscape/security/x509/NoticeReference.java56
-rw-r--r--pki/base/util/src/netscape/security/x509/OIDMap.java182
-rw-r--r--pki/base/util/src/netscape/security/x509/OIDName.java16
-rw-r--r--pki/base/util/src/netscape/security/x509/OtherName.java142
-rw-r--r--pki/base/util/src/netscape/security/x509/PKIXExtensions.java155
-rw-r--r--pki/base/util/src/netscape/security/x509/PolicyConstraint.java78
-rw-r--r--pki/base/util/src/netscape/security/x509/PolicyConstraintsExtension.java163
-rw-r--r--pki/base/util/src/netscape/security/x509/PolicyMappingsExtension.java136
-rw-r--r--pki/base/util/src/netscape/security/x509/PolicyQualifierInfo.java67
-rw-r--r--pki/base/util/src/netscape/security/x509/PolicyQualifiers.java44
-rw-r--r--pki/base/util/src/netscape/security/x509/PrintableConverter.java115
-rw-r--r--pki/base/util/src/netscape/security/x509/PrivateKeyUsageExtension.java193
-rw-r--r--pki/base/util/src/netscape/security/x509/Qualifier.java18
-rw-r--r--pki/base/util/src/netscape/security/x509/RDN.java357
-rw-r--r--pki/base/util/src/netscape/security/x509/RFC1779StrConverter.java101
-rw-r--r--pki/base/util/src/netscape/security/x509/RFC822Name.java15
-rwxr-xr-xpki/base/util/src/netscape/security/x509/ReasonFlags.java232
-rw-r--r--pki/base/util/src/netscape/security/x509/RevocationReason.java101
-rwxr-xr-xpki/base/util/src/netscape/security/x509/RevokedCertImpl.java545
-rw-r--r--pki/base/util/src/netscape/security/x509/RevokedCertificate.java69
-rw-r--r--pki/base/util/src/netscape/security/x509/SerialNumber.java18
-rw-r--r--pki/base/util/src/netscape/security/x509/SubjectAlternativeNameExtension.java123
-rw-r--r--pki/base/util/src/netscape/security/x509/SubjectDirAttributesExtension.java171
-rw-r--r--pki/base/util/src/netscape/security/x509/SubjectKeyIdentifierExtension.java117
-rw-r--r--pki/base/util/src/netscape/security/x509/URIName.java12
-rw-r--r--pki/base/util/src/netscape/security/x509/UniqueIdentity.java23
-rw-r--r--pki/base/util/src/netscape/security/x509/UserNotice.java65
-rw-r--r--pki/base/util/src/netscape/security/x509/X500Name.java742
-rw-r--r--pki/base/util/src/netscape/security/x509/X500NameAttrMap.java381
-rw-r--r--pki/base/util/src/netscape/security/x509/X500Signer.java88
-rw-r--r--pki/base/util/src/netscape/security/x509/X509AttributeName.java8
-rwxr-xr-xpki/base/util/src/netscape/security/x509/X509CRLImpl.java521
-rw-r--r--pki/base/util/src/netscape/security/x509/X509Cert.java1127
-rwxr-xr-xpki/base/util/src/netscape/security/x509/X509CertImpl.java738
-rw-r--r--pki/base/util/src/netscape/security/x509/X509CertInfo.java407
-rw-r--r--pki/base/util/src/netscape/security/x509/X509ExtensionException.java17
-rw-r--r--pki/base/util/src/netscape/security/x509/X509Key.java675
-rw-r--r--pki/base/util/test/com/netscape/security/extensions/GenericASN1ExtensionTest.java16
-rw-r--r--pki/base/util/test/com/netscape/security/util/BMPStringTest.java68
-rw-r--r--pki/base/util/test/com/netscape/security/util/IA5StringTest.java60
-rw-r--r--pki/base/util/test/com/netscape/security/util/JSSUtil.java40
-rw-r--r--pki/base/util/test/com/netscape/security/util/PrintableStringTest.java60
-rw-r--r--pki/base/util/test/com/netscape/security/util/StringTestUtil.java14
-rw-r--r--pki/base/util/test/com/netscape/security/util/TeletexStringTest.java60
-rw-r--r--pki/base/util/test/com/netscape/security/util/UTF8StringTest.java60
-rw-r--r--pki/base/util/test/com/netscape/security/util/UniversalStringTest.java60
-rw-r--r--pki/base/util/test/com/netscape/security/x509/DirStrConverterTest.java40
-rw-r--r--pki/base/util/test/com/netscape/security/x509/GenericValueConverterTest.java42
-rw-r--r--pki/base/util/test/com/netscape/security/x509/IA5StringConverterTest.java24
-rw-r--r--pki/base/util/test/com/netscape/security/x509/PrintableConverterTest.java24
1325 files changed, 84785 insertions, 89360 deletions
diff --git a/pki/.settings/org.eclipse.jdt.core.prefs b/pki/.settings/org.eclipse.jdt.core.prefs
index 81aa4978..270a544f 100644
--- a/pki/.settings/org.eclipse.jdt.core.prefs
+++ b/pki/.settings/org.eclipse.jdt.core.prefs
@@ -1,4 +1,4 @@
-#Wed Dec 07 16:50:17 EST 2011
+#Mon Jan 09 23:31:27 EST 2012
eclipse.preferences.version=1
org.eclipse.jdt.core.formatter.align_type_members_on_columns=false
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16
@@ -251,12 +251,12 @@ org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constan
org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert
org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert
org.eclipse.jdt.core.formatter.join_lines_in_comments=true
-org.eclipse.jdt.core.formatter.join_wrapped_lines=true
+org.eclipse.jdt.core.formatter.join_wrapped_lines=false
org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false
org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false
org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false
org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false
-org.eclipse.jdt.core.formatter.lineSplit=80
+org.eclipse.jdt.core.formatter.lineSplit=500
org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false
org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false
org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0
diff --git a/pki/base/ca/src/com/netscape/ca/CAPolicy.java b/pki/base/ca/src/com/netscape/ca/CAPolicy.java
index 80c801a4..ae6d15b3 100644
--- a/pki/base/ca/src/com/netscape/ca/CAPolicy.java
+++ b/pki/base/ca/src/com/netscape/ca/CAPolicy.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.ca;
-
import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
@@ -32,14 +31,11 @@ import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cmscore.policy.GenericPolicyProcessor;
import com.netscape.cmscore.util.Debug;
-
/**
- * XXX Just inherit 'GenericPolicyProcessor' (from RA) for now.
- * This really bad. need to make a special case just for connector.
- * would like a much better way of doing this to handle both EE and
- * connectors.
- * XXX2 moved to just implement IPolicy since GenericPolicyProcessor is
- * unuseable for CA.
+ * XXX Just inherit 'GenericPolicyProcessor' (from RA) for now. This really bad.
+ * need to make a special case just for connector. would like a much better way
+ * of doing this to handle both EE and connectors. XXX2 moved to just implement
+ * IPolicy since GenericPolicyProcessor is unuseable for CA.
*
* @version $Revision$, $Date$
*/
@@ -47,8 +43,8 @@ public class CAPolicy implements IPolicy {
IConfigStore mConfig = null;
ICertificateAuthority mCA = null;
- public static String PROP_PROCESSOR =
- "processor";
+ public static String PROP_PROCESSOR =
+ "processor";
// These are the different types of policy that are
// allowed for the "processor" property
public static String PR_TYPE_CLASSIC = "classic";
@@ -64,12 +60,12 @@ public class CAPolicy implements IPolicy {
}
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mCA = (ICertificateAuthority) owner;
mConfig = config;
- String processorType = // XXX - need to upgrade 4.2
- config.getString(PROP_PROCESSOR, PR_TYPE_CLASSIC);
+ String processorType = // XXX - need to upgrade 4.2
+ config.getString(PROP_PROCESSOR, PR_TYPE_CLASSIC);
Debug.trace("selected policy processor = " + processorType);
if (processorType.equals(PR_TYPE_CLASSIC)) {
@@ -100,32 +96,32 @@ public class CAPolicy implements IPolicy {
}
Debug.trace("in CAPolicy.apply(requestType=" +
- r.getRequestType() + ",requestId=" +
- r.getRequestId().toString() + ",requestStatus=" +
- r.getRequestStatus().toString() + ")");
+ r.getRequestType() + ",requestId=" +
+ r.getRequestId().toString() + ",requestStatus=" +
+ r.getRequestStatus().toString() + ")");
- if (isProfileRequest(r)) {
- Debug.trace("CAPolicy: Profile-base Request " +
- r.getRequestId().toString());
+ if (isProfileRequest(r)) {
+ Debug.trace("CAPolicy: Profile-base Request " +
+ r.getRequestId().toString());
- CMS.debug("CAPolicy: requestId=" +
- r.getRequestId().toString());
+ CMS.debug("CAPolicy: requestId=" +
+ r.getRequestId().toString());
String profileId = r.getExtDataInString("profileId");
- if (profileId == null || profileId.equals("")) {
+ if (profileId == null || profileId.equals("")) {
return PolicyResult.REJECTED;
}
- IProfileSubsystem ps = (IProfileSubsystem)
- CMS.getSubsystem("profile");
+ IProfileSubsystem ps = (IProfileSubsystem)
+ CMS.getSubsystem("profile");
try {
- IProfile profile = ps.getProfile(profileId);
+ IProfile profile = ps.getProfile(profileId);
r.setExtData("dbStatus", "NOT_UPDATED");
- profile.populate(r);
- profile.validate(r);
+ profile.populate(r);
+ profile.validate(r);
return PolicyResult.ACCEPTED;
} catch (EBaseException e) {
CMS.debug("CAPolicy: " + e.toString());
@@ -137,4 +133,3 @@ public class CAPolicy implements IPolicy {
}
}
-
diff --git a/pki/base/ca/src/com/netscape/ca/CAService.java b/pki/base/ca/src/com/netscape/ca/CAService.java
index 64fd73e4..47e9c114 100644
--- a/pki/base/ca/src/com/netscape/ca/CAService.java
+++ b/pki/base/ca/src/com/netscape/ca/CAService.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.ca;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
@@ -93,7 +92,6 @@ import com.netscape.cmscore.dbs.CertificateRepository;
import com.netscape.cmscore.dbs.RevocationInfo;
import com.netscape.cmscore.util.Debug;
-
/**
* Request Service for CertificateAuthority.
*/
@@ -114,56 +112,55 @@ public class CAService implements ICAService, IService {
private Hashtable<String, ICRLIssuingPoint> mCRLIssuingPoints = new Hashtable<String, ICRLIssuingPoint>();
private ILogger mSignedAuditLogger = CMS.getSignedAuditLogger();
- private final static String
- LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST =
- "LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST_4";
+ private final static String LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST =
+ "LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST_4";
public CAService(ICertificateAuthority ca) {
mCA = ca;
- // init services.
+ // init services.
mServants.put(
- IRequest.ENROLLMENT_REQUEST,
- new serviceIssue(this));
+ IRequest.ENROLLMENT_REQUEST,
+ new serviceIssue(this));
mServants.put(
- IRequest.RENEWAL_REQUEST,
- new serviceRenewal(this));
+ IRequest.RENEWAL_REQUEST,
+ new serviceRenewal(this));
mServants.put(
- IRequest.REVOCATION_REQUEST,
- new serviceRevoke(this));
+ IRequest.REVOCATION_REQUEST,
+ new serviceRevoke(this));
mServants.put(
- IRequest.CMCREVOKE_REQUEST,
- new serviceRevoke(this));
+ IRequest.CMCREVOKE_REQUEST,
+ new serviceRevoke(this));
mServants.put(
- IRequest.REVOCATION_CHECK_CHALLENGE_REQUEST,
- new serviceCheckChallenge(this));
+ IRequest.REVOCATION_CHECK_CHALLENGE_REQUEST,
+ new serviceCheckChallenge(this));
mServants.put(
- IRequest.GETCERTS_FOR_CHALLENGE_REQUEST,
- new getCertsForChallenge(this));
+ IRequest.GETCERTS_FOR_CHALLENGE_REQUEST,
+ new getCertsForChallenge(this));
mServants.put(
- IRequest.UNREVOCATION_REQUEST,
- new serviceUnrevoke(this));
+ IRequest.UNREVOCATION_REQUEST,
+ new serviceUnrevoke(this));
mServants.put(
- IRequest.GETCACHAIN_REQUEST,
- new serviceGetCAChain(this));
+ IRequest.GETCACHAIN_REQUEST,
+ new serviceGetCAChain(this));
mServants.put(
- IRequest.GETCRL_REQUEST,
- new serviceGetCRL(this));
+ IRequest.GETCRL_REQUEST,
+ new serviceGetCRL(this));
mServants.put(
- IRequest.GETREVOCATIONINFO_REQUEST,
- new serviceGetRevocationInfo(this));
+ IRequest.GETREVOCATIONINFO_REQUEST,
+ new serviceGetRevocationInfo(this));
mServants.put(
- IRequest.GETCERTS_REQUEST,
- new serviceGetCertificates(this));
+ IRequest.GETCERTS_REQUEST,
+ new serviceGetCertificates(this));
mServants.put(
- IRequest.CLA_CERT4CRL_REQUEST,
- new serviceCert4Crl(this));
+ IRequest.CLA_CERT4CRL_REQUEST,
+ new serviceCert4Crl(this));
mServants.put(
- IRequest.CLA_UNCERT4CRL_REQUEST,
- new serviceUnCert4Crl(this));
+ IRequest.CLA_UNCERT4CRL_REQUEST,
+ new serviceUnCert4Crl(this));
mServants.put(
- IRequest.GETCERT_STATUS_REQUEST,
- new getCertStatus(this));
+ IRequest.GETCERT_STATUS_REQUEST,
+ new getCertStatus(this));
}
public void init(IConfigStore config) throws EBaseException {
@@ -171,20 +168,22 @@ public class CAService implements ICAService, IService {
try {
// MOVED TO com.netscape.certsrv.apps.CMS
- // java.security.Security.addProvider(new netscape.security.provider.CMS());
- // java.security.Provider pr = java.security.Security.getProvider("CMS");
- // if (pr != null) {
- // ;
- // }
- // else
- // Debug.trace("Something is wrong in CMS install !");
+ // java.security.Security.addProvider(new
+ // netscape.security.provider.CMS());
+ // java.security.Provider pr =
+ // java.security.Security.getProvider("CMS");
+ // if (pr != null) {
+ // ;
+ // }
+ // else
+ // Debug.trace("Something is wrong in CMS install !");
java.security.cert.CertificateFactory cf = java.security.cert.CertificateFactory.getInstance("X.509");
Debug.trace("CertificateFactory Type : " + cf.getType());
Debug.trace("CertificateFactory Provider : " + cf.getProvider().getInfo());
} catch (java.security.cert.CertificateException e) {
Debug.trace("Something is happen in install CMS provider !" + e.toString());
- }
+ }
}
public void startup() throws EBaseException {
@@ -229,8 +228,8 @@ public class CAService implements ICAService, IService {
mKRAConnector = c;
}
- public IConnector getConnector(IConfigStore config)
- throws EBaseException {
+ public IConnector getConnector(IConfigStore config)
+ throws EBaseException {
IConnector connector = null;
if (config == null || config.size() <= 0) {
@@ -279,25 +278,25 @@ public class CAService implements ICAService, IService {
int timeout = config.getInteger("timeout", 0);
// Insert end
// Changed by beomsuk
- //RemoteAuthority remauthority =
- // new RemoteAuthority(host, port, uri);
+ // RemoteAuthority remauthority =
+ // new RemoteAuthority(host, port, uri);
RemoteAuthority remauthority =
- new RemoteAuthority(host, port, uri, timeout);
+ new RemoteAuthority(host, port, uri, timeout);
- // Change end
- if (nickname == null)
+ // Change end
+ if (nickname == null)
nickname = mCA.getNickname();
- // Changed by beomsuk
- //connector =
- // new HttpConnector(mCA, nickname, remauthority, resendInterval);
+ // Changed by beomsuk
+ // connector =
+ // new HttpConnector(mCA, nickname, remauthority, resendInterval);
if (timeout == 0)
connector = new HttpConnector((IAuthority) mCA, nickname, remauthority, resendInterval, config);
else
connector = new HttpConnector((IAuthority) mCA, nickname, remauthority, resendInterval, config, timeout);
- // Change end
+ // Change end
- // log(ILogger.LL_INFO, "remote authority "+
- // host+":"+port+" "+uri+" inited");
+ // log(ILogger.LL_INFO, "remote authority "+
+ // host+":"+port+" "+uri+" inited");
}
return connector;
}
@@ -312,13 +311,13 @@ public class CAService implements ICAService, IService {
}
/**
- * After population of defaults, and constraint validation,
- * the profile request is processed here.
+ * After population of defaults, and constraint validation, the profile
+ * request is processed here.
*/
- public void serviceProfileRequest(IRequest request)
- throws EBaseException {
- CMS.debug("CAService: serviceProfileRequest requestId=" +
- request.getRequestId().toString());
+ public void serviceProfileRequest(IRequest request)
+ throws EBaseException {
+ CMS.debug("CAService: serviceProfileRequest requestId=" +
+ request.getRequestId().toString());
String profileId = request.getExtDataInString("profileId");
@@ -327,7 +326,7 @@ public class CAService implements ICAService, IService {
}
IProfileSubsystem ps = (IProfileSubsystem)
- CMS.getSubsystem("profile");
+ CMS.getSubsystem("profile");
IProfile profile = null;
try {
@@ -341,25 +340,26 @@ public class CAService implements ICAService, IService {
// assumed rejected
request.setExtData("dbStatus", "NOT_UPDATED");
- // profile.populate(request);
+ // profile.populate(request);
profile.validate(request);
profile.execute(request);
// This function is called only from ConnectorServlet
- // serialize to request queue
+ // serialize to request queue
}
/**
- * method interface for IService
+ * method interface for IService
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST used
- * whenever a user private key archive request is made. This is an option
- * in a cert enrollment request detected by an RA or a CA, so, if selected,
- * it should be logged immediately following the certificate request.
+ * whenever a user private key archive request is made. This is an option in
+ * a cert enrollment request detected by an RA or a CA, so, if selected, it
+ * should be logged immediately following the certificate request.
* </ul>
+ *
* @param request a certificate enrollment request from an RA or CA
* @return true or false
*/
@@ -417,7 +417,7 @@ public class CAService implements ICAService, IService {
mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_INVALID_REQUEST_TYPE", type));
request.setExtData(IRequest.RESULT, IRequest.RES_ERROR);
request.setExtData(IRequest.ERROR,
- new ECAException(CMS.getUserMessage("CMS_CA_UNRECOGNIZED_REQUEST_TYPE", type)));
+ new ECAException(CMS.getUserMessage("CMS_CA_UNRECOGNIZED_REQUEST_TYPE", type)));
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST,
@@ -433,8 +433,8 @@ public class CAService implements ICAService, IService {
try {
// send request to KRA first
- if (type.equals(IRequest.ENROLLMENT_REQUEST) &&
- isPKIArchiveOptionPresent(request) && mKRAConnector != null) {
+ if (type.equals(IRequest.ENROLLMENT_REQUEST) &&
+ isPKIArchiveOptionPresent(request) && mKRAConnector != null) {
if (Debug.ON) {
Debug.trace("*** Sending enrollment request to KRA");
}
@@ -443,9 +443,9 @@ public class CAService implements ICAService, IService {
if (mArchivalRequired == true) {
if (sendStatus == false) {
request.setExtData(IRequest.RESULT,
- IRequest.RES_ERROR);
+ IRequest.RES_ERROR);
request.setExtData(IRequest.ERROR,
- new ECAException(CMS.getUserMessage("CMS_CA_SEND_KRA_REQUEST")));
+ new ECAException(CMS.getUserMessage("CMS_CA_SEND_KRA_REQUEST")));
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -508,8 +508,7 @@ public class CAService implements ICAService, IService {
Debug.trace("serviceRequest completed = " + completed);
if (!(type.equals(IRequest.REVOCATION_REQUEST) ||
- type.equals(IRequest.UNREVOCATION_REQUEST) ||
- type.equals(IRequest.CMCREVOKE_REQUEST))) {
+ type.equals(IRequest.UNREVOCATION_REQUEST) || type.equals(IRequest.CMCREVOKE_REQUEST))) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST,
@@ -525,7 +524,7 @@ public class CAService implements ICAService, IService {
}
/**
- * register CRL Issuing Point
+ * register CRL Issuing Point
*/
public void addCRLIssuingPoint(String id, ICRLIssuingPoint crlIssuingPoint) {
mCRLIssuingPoints.put(id, crlIssuingPoint);
@@ -563,12 +562,12 @@ public class CAService implements ICAService, IService {
return false;
}
- ///
- /// CA related routines.
- ///
+ // /
+ // / CA related routines.
+ // /
public X509CertImpl issueX509Cert(X509CertInfo certi)
- throws EBaseException {
+ throws EBaseException {
return issueX509Cert(certi, null, null);
}
@@ -576,7 +575,7 @@ public class CAService implements ICAService, IService {
* issue cert for enrollment.
*/
public X509CertImpl issueX509Cert(X509CertInfo certi, String profileId, String rid)
- throws EBaseException {
+ throws EBaseException {
CMS.debug("issueX509Cert");
X509CertImpl certImpl = issueX509Cert("", certi, false, null);
@@ -587,7 +586,7 @@ public class CAService implements ICAService, IService {
}
X509CertImpl issueX509Cert(String rid, X509CertInfo certi)
- throws EBaseException {
+ throws EBaseException {
return issueX509Cert(rid, certi, false, null);
}
@@ -595,7 +594,7 @@ public class CAService implements ICAService, IService {
* issue cert for enrollment.
*/
void storeX509Cert(String profileId, String rid, X509CertImpl cert)
- throws EBaseException {
+ throws EBaseException {
storeX509Cert(rid, cert, false, null, null, null, profileId);
}
@@ -603,28 +602,27 @@ public class CAService implements ICAService, IService {
* issue cert for enrollment.
*/
void storeX509Cert(String rid, X509CertImpl cert, String crmfReqId)
- throws EBaseException {
+ throws EBaseException {
storeX509Cert(rid, cert, false, null, crmfReqId, null, null);
}
- void storeX509Cert(String rid, X509CertImpl cert, String crmfReqId,
- String challengePassword) throws EBaseException {
+ void storeX509Cert(String rid, X509CertImpl cert, String crmfReqId,
+ String challengePassword) throws EBaseException {
storeX509Cert(rid, cert, false, null, crmfReqId, challengePassword, null);
}
/**
- * issue cert for enrollment and renewal.
- * renewal is expected to have original cert serial no. in cert info
- * field.
+ * issue cert for enrollment and renewal. renewal is expected to have
+ * original cert serial no. in cert info field.
*/
- X509CertImpl issueX509Cert(String rid, X509CertInfo certi,
- boolean renewal, BigInteger oldSerialNo)
- throws EBaseException {
+ X509CertImpl issueX509Cert(String rid, X509CertInfo certi,
+ boolean renewal, BigInteger oldSerialNo)
+ throws EBaseException {
String algname = null;
X509CertImpl cert = null;
- // NOTE: In this implementation, the "oldSerialNo"
- // parameter is NOT used!
+ // NOTE: In this implementation, the "oldSerialNo"
+ // parameter is NOT used!
boolean doUTF8 = mConfig.getBoolean("dnUTF8Encoding", false);
@@ -633,10 +631,10 @@ public class CAService implements ICAService, IService {
try {
// check required fields in certinfo.
if (certi.get(X509CertInfo.SUBJECT) == null ||
- certi.get(X509CertInfo.KEY) == null) {
+ certi.get(X509CertInfo.KEY) == null) {
mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_MISSING_ATTR"));
- // XXX how do you reject a request in the service object ?
+ // XXX how do you reject a request in the service object ?
throw new ECAException(
CMS.getUserMessage("CMS_CA_MISSING_REQD_FIELDS_IN_CERTISSUE"));
}
@@ -648,10 +646,10 @@ public class CAService implements ICAService, IService {
}
// set default validity if not set.
- // validity would normally be set by policies or by
- // agent or by authentication module.
+ // validity would normally be set by policies or by
+ // agent or by authentication module.
CertificateValidity validity = (CertificateValidity)
- certi.get(X509CertInfo.VALIDITY);
+ certi.get(X509CertInfo.VALIDITY);
Date begin = null, end = null;
if (validity != null) {
@@ -660,22 +658,21 @@ public class CAService implements ICAService, IService {
end = (Date)
validity.get(CertificateValidity.NOT_AFTER);
}
- if (validity == null ||
- (begin.getTime() == 0 && end.getTime() == 0)) {
+ if (validity == null ||
+ (begin.getTime() == 0 && end.getTime() == 0)) {
if (Debug.ON) {
Debug.trace("setting default validity");
}
-
+
begin = CMS.getCurrentDate();
end = new Date(begin.getTime() + mCA.getDefaultValidity());
- certi.set(CertificateValidity.NAME,
- new CertificateValidity(begin, end));
+ certi.set(CertificateValidity.NAME,
+ new CertificateValidity(begin, end));
}
/*
- * For non-CA certs, check if validity exceeds CA time.
- * If so, set to CA's not after if default validity
- * exceeds ca's not after.
+ * For non-CA certs, check if validity exceeds CA time. If so, set
+ * to CA's not after if default validity exceeds ca's not after.
*/
// First find out if it is a CA cert
@@ -685,7 +682,7 @@ public class CAService implements ICAService, IService {
try {
exts = (CertificateExtensions)
- certi.get(X509CertInfo.EXTENSIONS);
+ certi.get(X509CertInfo.EXTENSIONS);
if (exts != null) {
Enumeration<Extension> e = exts.getAttributes();
@@ -697,7 +694,7 @@ public class CAService implements ICAService, IService {
}
}
- if(bc_ext != null) {
+ if (bc_ext != null) {
Boolean isCA = (Boolean) bc_ext.get(BasicConstraintsExtension.IS_CA);
is_ca = isCA.booleanValue();
}
@@ -706,8 +703,8 @@ public class CAService implements ICAService, IService {
CMS.debug("EnrollDefault: getExtension " + e.toString());
}
- Date caNotAfter =
- mCA.getSigningUnit().getCertImpl().getNotAfter();
+ Date caNotAfter =
+ mCA.getSigningUnit().getCertImpl().getNotAfter();
if (begin.after(caNotAfter)) {
mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_PAST_VALIDITY"));
@@ -715,31 +712,31 @@ public class CAService implements ICAService, IService {
}
if (end.after(caNotAfter)) {
- if(!is_ca) {
+ if (!is_ca) {
if (!mCA.isEnablePastCATime()) {
end = caNotAfter;
- certi.set(CertificateValidity.NAME,
- new CertificateValidity(begin, caNotAfter));
+ certi.set(CertificateValidity.NAME,
+ new CertificateValidity(begin, caNotAfter));
CMS.debug("CAService: issueX509Cert: cert past CA's NOT_AFTER...ca.enablePastCATime != true...resetting");
} else {
CMS.debug("CAService: issueX509Cert: cert past CA's NOT_AFTER...ca.enablePastCATime = true...not resetting");
}
} else {
CMS.debug("CAService: issueX509Cert: CA cert issuance past CA's NOT_AFTER.");
- } //!is_ca
+ } // !is_ca
mCA.log(ILogger.LL_INFO, CMS.getLogMessage("CMSCORE_CA_PAST_NOT_AFTER"));
}
// check algorithm in certinfo.
AlgorithmId algid = null;
CertificateAlgorithmId algor = (CertificateAlgorithmId)
- certi.get(X509CertInfo.ALGORITHM_ID);
+ certi.get(X509CertInfo.ALGORITHM_ID);
if (algor == null || algor.toString().equals(CertInfo.SERIALIZE_ALGOR.toString())) {
algname = mCA.getSigningUnit().getDefaultAlgorithm();
algid = AlgorithmId.get(algname);
- certi.set(X509CertInfo.ALGORITHM_ID,
- new CertificateAlgorithmId(algid));
+ certi.set(X509CertInfo.ALGORITHM_ID,
+ new CertificateAlgorithmId(algid));
} else {
algid = (AlgorithmId)
algor.get(CertificateAlgorithmId.ALGORITHM);
@@ -772,7 +769,7 @@ public class CAService implements ICAService, IService {
if (renewal) {
try {
CertificateSerialNumber serialno = (CertificateSerialNumber)
- certi.get(X509CertInfo.SERIAL_NUMBER);
+ certi.get(X509CertInfo.SERIAL_NUMBER);
if (serialno == null) {
mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_NULL_SERIAL_NUMBER"));
@@ -780,7 +777,7 @@ public class CAService implements ICAService, IService {
CMS.getUserMessage("CMS_CA_MISSING_INFO_IN_RENEWREQ"));
}
SerialNumber serialnum = (SerialNumber)
- serialno.get(CertificateSerialNumber.NUMBER);
+ serialno.get(CertificateSerialNumber.NUMBER);
if (serialnum == null) {
mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_NULL_SERIAL_NUMBER"));
@@ -788,12 +785,12 @@ public class CAService implements ICAService, IService {
CMS.getUserMessage("CMS_CA_MISSING_INFO_IN_RENEWREQ"));
}
} catch (CertificateException e) {
- // not possible
+ // not possible
mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_NO_ORG_SERIAL", e.getMessage()));
throw new ECAException(
CMS.getUserMessage("CMS_CA_MISSING_INFO_IN_RENEWREQ"));
} catch (IOException e) {
- // not possible.
+ // not possible.
mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_NO_ORG_SERIAL", e.getMessage()));
throw new ECAException(
CMS.getUserMessage("CMS_CA_MISSING_INFO_IN_RENEWREQ"));
@@ -802,11 +799,11 @@ public class CAService implements ICAService, IService {
// set issuer, serial number
try {
- BigInteger serialNo =
- mCA.getCertificateRepository().getNextSerialNumber();
+ BigInteger serialNo =
+ mCA.getCertificateRepository().getNextSerialNumber();
certi.set(X509CertInfo.SERIAL_NUMBER,
- new CertificateSerialNumber(serialNo));
+ new CertificateSerialNumber(serialNo));
mCA.log(ILogger.LL_INFO, CMS.getLogMessage("CMSCORE_CA_SIGN_SERIAL", serialNo.toString(16)));
} catch (EBaseException e) {
mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_NO_NEXT_SERIAL", e.toString()));
@@ -822,8 +819,8 @@ public class CAService implements ICAService, IService {
}
try {
- certi.set(X509CertInfo.ISSUER,
- new CertificateIssuerName(mCA.getX500Name()));
+ certi.set(X509CertInfo.ISSUER,
+ new CertificateIssuerName(mCA.getX500Name()));
} catch (CertificateException e) {
mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_SET_ISSUER", e.toString()));
throw new ECAException(CMS.getUserMessage("CMS_CA_SET_ISSUER_FAILED", rid));
@@ -844,7 +841,7 @@ public class CAService implements ICAService, IService {
certi.set(X509CertInfo.SUBJECT, new CertificateSubjectName(
new X500Name(subject,
- new LdapV3DNStrConverter(X500NameAttrMap.getDirDefault(), true), utf8_encodingOrder)));
+ new LdapV3DNStrConverter(X500NameAttrMap.getDirDefault(), true), utf8_encodingOrder)));
} catch (CertificateException e) {
mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_SET_SUBJECT", e.toString()));
@@ -860,22 +857,22 @@ public class CAService implements ICAService, IService {
return cert;
}
- void storeX509Cert(String rid, X509CertImpl cert,
- boolean renewal, BigInteger oldSerialNo)
- throws EBaseException {
+ void storeX509Cert(String rid, X509CertImpl cert,
+ boolean renewal, BigInteger oldSerialNo)
+ throws EBaseException {
storeX509Cert(rid, cert, renewal, oldSerialNo, null, null, null);
}
- void storeX509Cert(String rid, X509CertImpl cert,
- boolean renewal, BigInteger oldSerialNo, String crmfReqId,
- String challengePassword, String profileId) throws EBaseException {
+ void storeX509Cert(String rid, X509CertImpl cert,
+ boolean renewal, BigInteger oldSerialNo, String crmfReqId,
+ String challengePassword, String profileId) throws EBaseException {
// now store in repository.
- // if renewal, set the old serial number in the new cert,
- // set the new serial number in the old cert.
+ // if renewal, set the old serial number in the new cert,
+ // set the new serial number in the old cert.
CMS.debug("In storeX509Cert");
try {
- BigInteger newSerialNo = cert.getSerialNumber();
+ BigInteger newSerialNo = cert.getSerialNumber();
MetaInfo metaInfo = new MetaInfo();
if (profileId != null)
@@ -885,34 +882,34 @@ public class CAService implements ICAService, IService {
if (challengePassword != null && !challengePassword.equals(""))
metaInfo.set("challengePhrase", challengePassword);
if (crmfReqId != null) {
- //System.out.println("Adding crmf reqid "+crmfReqId);
+ // System.out.println("Adding crmf reqid "+crmfReqId);
metaInfo.set(CertRecord.META_CRMF_REQID, crmfReqId);
}
if (renewal)
metaInfo.set(CertRecord.META_OLD_CERT, oldSerialNo.toString());
mCA.getCertificateRepository().addCertificateRecord(
- new CertRecord(newSerialNo, cert, metaInfo));
+ new CertRecord(newSerialNo, cert, metaInfo));
mCA.log(ILogger.LL_INFO, CMS.getLogMessage("CMSCORE_CA_STORE_SERIAL", cert.getSerialNumber().toString(16)));
if (renewal) {
/*
- mCA.getCertificateRepository().markCertificateAsRenewed(
- BigIntegerMapper.BigIntegerToDB(oldSerialNo));
- mCA.mCertRepot.markCertificateAsRenewed(oldSerialNo);
+ * mCA.getCertificateRepository().markCertificateAsRenewed(
+ * BigIntegerMapper.BigIntegerToDB(oldSerialNo));
+ * mCA.mCertRepot.markCertificateAsRenewed(oldSerialNo);
*/
MetaInfo oldMeta = null;
CertRecord oldCertRec = (CertRecord)
- mCA.getCertificateRepository().readCertificateRecord(oldSerialNo);
+ mCA.getCertificateRepository().readCertificateRecord(oldSerialNo);
if (oldCertRec == null) {
- Exception e =
- new EBaseException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR",
- "Cannot read cert record for " + oldSerialNo));
+ Exception e =
+ new EBaseException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR",
+ "Cannot read cert record for " + oldSerialNo));
e.printStackTrace();
}
- if (oldCertRec != null)
+ if (oldCertRec != null)
oldMeta = oldCertRec.getMetaInfo();
if (oldMeta == null) {
if (Debug.ON) {
@@ -928,24 +925,24 @@ public class CAService implements ICAService, IService {
String name = (String) n.nextElement();
System.out.println("name " + name + " value " +
- oldMeta.get(name));
+ oldMeta.get(name));
}
}
}
- oldMeta.set(CertRecord.META_RENEWED_CERT,
- newSerialNo.toString());
+ oldMeta.set(CertRecord.META_RENEWED_CERT,
+ newSerialNo.toString());
ModificationSet modSet = new ModificationSet();
- modSet.add(CertRecord.ATTR_AUTO_RENEW,
- Modification.MOD_REPLACE,
- CertRecord.AUTO_RENEWAL_DONE);
- modSet.add(ICertRecord.ATTR_META_INFO,
- Modification.MOD_REPLACE, oldMeta);
+ modSet.add(CertRecord.ATTR_AUTO_RENEW,
+ Modification.MOD_REPLACE,
+ CertRecord.AUTO_RENEWAL_DONE);
+ modSet.add(ICertRecord.ATTR_META_INFO,
+ Modification.MOD_REPLACE, oldMeta);
mCA.getCertificateRepository().modifyCertificateRecord(oldSerialNo, modSet);
mCA.log(ILogger.LL_INFO, CMS.getLogMessage("CMSCORE_CA_MARK_SERIAL", oldSerialNo.toString(16), newSerialNo.toString(16)));
if (Debug.ON) {
CertRecord check = (CertRecord)
- mCA.getCertificateRepository().readCertificateRecord(oldSerialNo);
+ mCA.getCertificateRepository().readCertificateRecord(oldSerialNo);
MetaInfo meta = check.getMetaInfo();
Enumeration<String> n = oldMeta.getElements();
@@ -968,12 +965,12 @@ public class CAService implements ICAService, IService {
* revoke cert, check fields in crlentry, etc.
*/
public void revokeCert(RevokedCertImpl crlentry)
- throws EBaseException {
+ throws EBaseException {
revokeCert(crlentry, null);
}
public void revokeCert(RevokedCertImpl crlentry, String requestId)
- throws EBaseException {
+ throws EBaseException {
BigInteger serialno = crlentry.getSerialNumber();
Date revdate = crlentry.getRevocationDate();
CRLExtensions crlentryexts = crlentry.getExtensions();
@@ -983,8 +980,8 @@ public class CAService implements ICAService, IService {
if (certRec == null) {
mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CERT_NOT_FOUND", serialno.toString(16)));
throw new ECAException(
- CMS.getUserMessage("CMS_CA_CANT_FIND_CERT_SERIAL",
- "0x" + serialno.toString(16)));
+ CMS.getUserMessage("CMS_CA_CANT_FIND_CERT_SERIAL",
+ "0x" + serialno.toString(16)));
}
RevocationInfo revInfo = (RevocationInfo) certRec.getRevocationInfo();
CRLExtensions exts = null;
@@ -1004,13 +1001,13 @@ public class CAService implements ICAService, IService {
String certStatus = certRec.getStatus();
if (certStatus.equals(ICertRecord.STATUS_REVOKED) ||
- certStatus.equals(ICertRecord.STATUS_REVOKED_EXPIRED)) {
- throw new ECAException(CMS.getUserMessage("CMS_CA_CERT_ALREADY_REVOKED",
+ certStatus.equals(ICertRecord.STATUS_REVOKED_EXPIRED)) {
+ throw new ECAException(CMS.getUserMessage("CMS_CA_CERT_ALREADY_REVOKED",
"0x" + Long.toHexString(serialno.longValue())));
}
try {
- mCA.getCertificateRepository().markAsRevoked(serialno,
- new RevocationInfo(revdate, crlentryexts));
+ mCA.getCertificateRepository().markAsRevoked(serialno,
+ new RevocationInfo(revdate, crlentryexts));
mCA.log(ILogger.LL_INFO, CMS.getLogMessage("CMSCORE_CA_CERT_REVOKED",
serialno.toString(16)));
// inform all CRLIssuingPoints about revoked certificate
@@ -1025,23 +1022,25 @@ public class CAService implements ICAService, IService {
if (ip.isCACertsOnly()) {
X509CertImpl cert = certRec.getCertificate();
- if (cert != null) b = cert.getBasicConstraintsIsCA();
+ if (cert != null)
+ b = cert.getBasicConstraintsIsCA();
}
if (ip.isProfileCertsOnly()) {
MetaInfo metaInfo = certRec.getMetaInfo();
if (metaInfo != null) {
- String profileId = (String)metaInfo.get("profileId");
+ String profileId = (String) metaInfo.get("profileId");
if (profileId != null) {
b = ip.checkCurrentProfile(profileId);
}
}
}
- if (b) ip.addRevokedCert(serialno, crlentry, requestId);
+ if (b)
+ ip.addRevokedCert(serialno, crlentry, requestId);
}
}
} catch (EBaseException e) {
mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_ERROR_REVOCATION", serialno.toString(), e.toString()));
- //e.printStackTrace();
+ // e.printStackTrace();
throw e;
}
return;
@@ -1051,19 +1050,19 @@ public class CAService implements ICAService, IService {
* unrevoke cert, check serial number, etc.
*/
void unrevokeCert(BigInteger serialNo)
- throws EBaseException {
+ throws EBaseException {
unrevokeCert(serialNo, null);
}
void unrevokeCert(BigInteger serialNo, String requestId)
- throws EBaseException {
+ throws EBaseException {
CertRecord certRec = (CertRecord) mCA.getCertificateRepository().readCertificateRecord(serialNo);
if (certRec == null) {
mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CERT_NOT_FOUND", serialNo.toString(16)));
throw new ECAException(
- CMS.getUserMessage("CMS_CA_CANT_FIND_CERT_SERIAL",
- "0x" + serialNo.toString(16)));
+ CMS.getUserMessage("CMS_CA_CANT_FIND_CERT_SERIAL",
+ "0x" + serialNo.toString(16)));
}
RevocationInfo revInfo = (RevocationInfo) certRec.getRevocationInfo();
CRLExtensions exts = null;
@@ -1071,7 +1070,7 @@ public class CAService implements ICAService, IService {
if (revInfo == null) {
mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CERT_ON_HOLD", serialNo.toString()));
- throw new ECAException(CMS.getUserMessage("CMS_CA_IS_NOT_ON_HOLD",
+ throw new ECAException(CMS.getUserMessage("CMS_CA_IS_NOT_ON_HOLD",
serialNo.toString()));
}
exts = revInfo.getCRLEntryExtensions();
@@ -1080,23 +1079,23 @@ public class CAService implements ICAService, IService {
reasonext = (CRLReasonExtension)
exts.get(CRLReasonExtension.class.getSimpleName());
} catch (X509ExtensionException e) {
- mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CERT_ON_HOLD", serialNo.toString()));
- throw new ECAException(CMS.getUserMessage("CMS_CA_IS_NOT_ON_HOLD",
+ mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CERT_ON_HOLD", serialNo.toString()));
+ throw new ECAException(CMS.getUserMessage("CMS_CA_IS_NOT_ON_HOLD",
serialNo.toString()));
}
} else {
- mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CERT_ON_HOLD", serialNo.toString()));
- throw new ECAException(CMS.getUserMessage("CMS_CA_IS_NOT_ON_HOLD",
+ mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CERT_ON_HOLD", serialNo.toString()));
+ throw new ECAException(CMS.getUserMessage("CMS_CA_IS_NOT_ON_HOLD",
serialNo.toString()));
}
// allow unrevoking certs that are on hold.
if ((certRec.getStatus().equals(ICertRecord.STATUS_REVOKED) ||
certRec.getStatus().equals(ICertRecord.STATUS_REVOKED_EXPIRED)) &&
- reasonext != null &&
- reasonext.getReason() == RevocationReason.CERTIFICATE_HOLD) {
+ reasonext != null &&
+ reasonext.getReason() == RevocationReason.CERTIFICATE_HOLD) {
try {
mCA.getCertificateRepository().unmarkRevoked(serialNo, revInfo,
- certRec.getRevokedOn(), certRec.getRevokedBy());
+ certRec.getRevokedOn(), certRec.getRevokedBy());
mCA.log(ILogger.LL_INFO, CMS.getLogMessage("CMSCORE_CA_CERT_UNREVOKED", serialNo.toString(16)));
// inform all CRLIssuingPoints about unrevoked certificate
Enumeration<ICRLIssuingPoint> eIPs = mCRLIssuingPoints.elements();
@@ -1110,18 +1109,20 @@ public class CAService implements ICAService, IService {
if (ip.isCACertsOnly()) {
X509CertImpl cert = certRec.getCertificate();
- if (cert != null) b = cert.getBasicConstraintsIsCA();
+ if (cert != null)
+ b = cert.getBasicConstraintsIsCA();
}
if (ip.isProfileCertsOnly()) {
MetaInfo metaInfo = certRec.getMetaInfo();
if (metaInfo != null) {
- String profileId = (String)metaInfo.get("profileId");
+ String profileId = (String) metaInfo.get("profileId");
if (profileId != null) {
b = ip.checkCurrentProfile(profileId);
}
}
}
- if (b) ip.addUnrevokedCert(serialNo, requestId);
+ if (b)
+ ip.addUnrevokedCert(serialNo, requestId);
}
}
} catch (EBaseException e) {
@@ -1129,8 +1130,8 @@ public class CAService implements ICAService, IService {
throw e;
}
} else {
- mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CERT_ON_HOLD", serialNo.toString()));
- throw new ECAException(CMS.getUserMessage("CMS_CA_IS_NOT_ON_HOLD",
+ mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CERT_ON_HOLD", serialNo.toString()));
+ throw new ECAException(CMS.getUserMessage("CMS_CA_IS_NOT_ON_HOLD",
"0x" + serialNo.toString(16)));
}
@@ -1139,10 +1140,10 @@ public class CAService implements ICAService, IService {
/**
* Signed Audit Log
- *
+ *
* This method is called to store messages to the signed audit log.
* <P>
- *
+ *
* @param msg signed audit log message
*/
private void audit(String msg) {
@@ -1154,19 +1155,19 @@ public class CAService implements ICAService, IService {
}
mSignedAuditLogger.log(ILogger.EV_SIGNED_AUDIT,
- null,
- ILogger.S_SIGNED_AUDIT,
- ILogger.LL_SECURITY,
- msg);
+ null,
+ ILogger.S_SIGNED_AUDIT,
+ ILogger.LL_SECURITY,
+ msg);
}
/**
* Signed Audit Log Subject ID
- *
- * This method is called to obtain the "SubjectID" for
- * a signed audit log message.
+ *
+ * This method is called to obtain the "SubjectID" for a signed audit log
+ * message.
* <P>
- *
+ *
* @return id string containing the signed audit log message SubjectID
*/
private String auditSubjectID() {
@@ -1198,11 +1199,11 @@ public class CAService implements ICAService, IService {
/**
* Signed Audit Log Requester ID
- *
- * This method is called to obtain the "RequesterID" for
- * a signed audit log message.
+ *
+ * This method is called to obtain the "RequesterID" for a signed audit log
+ * message.
* <P>
- *
+ *
* @return id string containing the signed audit log message RequesterID
*/
private String auditRequesterID() {
@@ -1233,16 +1234,14 @@ public class CAService implements ICAService, IService {
}
}
-
-///
-/// servant classes
-///
+// /
+// / servant classes
+// /
interface IServant {
public boolean service(IRequest request) throws EBaseException;
}
-
class serviceIssue implements IServant {
private ICertificateAuthority mCA;
private CAService mService;
@@ -1253,8 +1252,8 @@ class serviceIssue implements IServant {
}
public boolean service(IRequest request)
- throws EBaseException {
- // XXX This is ugly. should associate attributes with
+ throws EBaseException {
+ // XXX This is ugly. should associate attributes with
// request types, not policy.
// XXX how do we know what to look for in request ?
@@ -1263,21 +1262,21 @@ class serviceIssue implements IServant {
else
return false; // Don't know what it is ?????
}
-
+
public boolean serviceX509(IRequest request)
- throws EBaseException {
- // XXX This is ugly. should associate attributes with
+ throws EBaseException {
+ // XXX This is ugly. should associate attributes with
// request types, not policy.
// XXX how do we know what to look for in request ?
- X509CertInfo certinfos[] =
- request.getExtDataInCertInfoArray(IRequest.CERT_INFO);
+ X509CertInfo certinfos[] =
+ request.getExtDataInCertInfoArray(IRequest.CERT_INFO);
if (certinfos == null || certinfos[0] == null) {
mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CERT_REQUEST_NOT_FOUND", request.getRequestId().toString()));
throw new ECAException(CMS.getUserMessage("CMS_CA_MISSING_INFO_IN_ISSUEREQ"));
}
- String challengePassword =
- request.getExtDataInString(CAService.CHALLENGE_PHRASE);
+ String challengePassword =
+ request.getExtDataInString(CAService.CHALLENGE_PHRASE);
X509CertImpl[] certs = new X509CertImpl[certinfos.length];
String rid = request.getRequestId().toString();
@@ -1300,16 +1299,16 @@ class serviceIssue implements IServant {
} catch (EBaseException e) {
e.printStackTrace();
mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_STORE_ERROR", Integer.toString(i), rid, e.toString()));
- ex = e; // save to throw later.
+ ex = e; // save to throw later.
break;
}
}
if (ex != null) {
for (int j = 0; j < i; j++) {
- // delete the stored cert records from the database.
- // we issue all or nothing.
- BigInteger serialNo =
- ((X509Certificate) certs[i]).getSerialNumber();
+ // delete the stored cert records from the database.
+ // we issue all or nothing.
+ BigInteger serialNo =
+ ((X509Certificate) certs[i]).getSerialNumber();
try {
mCA.getCertificateRepository().deleteCertificateRecord(serialNo);
@@ -1326,7 +1325,6 @@ class serviceIssue implements IServant {
}
}
-
class serviceRenewal implements IServant {
private ICertificateAuthority mCA;
private CAService mService;
@@ -1337,10 +1335,10 @@ class serviceRenewal implements IServant {
}
public boolean service(IRequest request)
- throws EBaseException {
+ throws EBaseException {
// XXX if one fails should all fail ? - can't backtrack.
- X509CertInfo certinfos[] =
- request.getExtDataInCertInfoArray(IRequest.CERT_INFO);
+ X509CertInfo certinfos[] =
+ request.getExtDataInCertInfoArray(IRequest.CERT_INFO);
if (certinfos == null || certinfos[0] == null) {
mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CERT_REQUEST_NOT_FOUND", request.getRequestId().toString()));
@@ -1364,7 +1362,7 @@ class serviceRenewal implements IServant {
try {
CertificateSerialNumber serialno = (CertificateSerialNumber)
- certinfos[i].get(X509CertInfo.SERIAL_NUMBER);
+ certinfos[i].get(X509CertInfo.SERIAL_NUMBER);
if (serialno == null) {
mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_NULL_SERIAL_NUMBER"));
@@ -1396,25 +1394,25 @@ class serviceRenewal implements IServant {
// get cert record
CertRecord certRecord = (CertRecord)
- mCA.getCertificateRepository().readCertificateRecord(oldSerialNo);
+ mCA.getCertificateRepository().readCertificateRecord(oldSerialNo);
if (certRecord == null) {
mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_NOT_FROM_CA", oldSerialNo.toString()));
svcerrors[i] = new ECAException(
- CMS.getUserMessage("CMS_CA_CANT_FIND_CERT_SERIAL",
- oldSerialNo.toString())).toString();
+ CMS.getUserMessage("CMS_CA_CANT_FIND_CERT_SERIAL",
+ oldSerialNo.toString())).toString();
continue;
}
- // check if cert has been revoked.
+ // check if cert has been revoked.
String certStatus = certRecord.getStatus();
- if (certStatus.equals(ICertRecord.STATUS_REVOKED) ||
- certStatus.equals(ICertRecord.STATUS_REVOKED_EXPIRED)) {
+ if (certStatus.equals(ICertRecord.STATUS_REVOKED) ||
+ certStatus.equals(ICertRecord.STATUS_REVOKED_EXPIRED)) {
mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_RENEW_REVOKED", oldSerialNo.toString()));
svcerrors[i] = new ECAException(
CMS.getUserMessage("CMS_CA_CANNOT_RENEW_REVOKED_CERT",
- "0x" + oldSerialNo.toString(16))).toString();
+ "0x" + oldSerialNo.toString(16))).toString();
continue;
}
@@ -1423,49 +1421,50 @@ class serviceRenewal implements IServant {
if (metaInfo != null) {
String renewed = (String)
- metaInfo.get(ICertRecord.META_RENEWED_CERT);
+ metaInfo.get(ICertRecord.META_RENEWED_CERT);
if (renewed != null) {
BigInteger serial = new BigInteger(renewed);
X509CertImpl cert = (X509CertImpl)
- mCA.getCertificateRepository().getX509Certificate(serial);
+ mCA.getCertificateRepository().getX509Certificate(serial);
if (cert == null) {
- // something wrong
+ // something wrong
mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_MISSING_RENEWED", serial.toString()));
svcerrors[i] = new ECAException(
CMS.getUserMessage("CMS_CA_ERROR_GETTING_RENEWED_CERT",
- oldSerialNo.toString(), serial.toString())).toString();
+ oldSerialNo.toString(), serial.toString())).toString();
continue;
}
// get cert record
CertRecord cRecord = (CertRecord)
- mCA.getCertificateRepository().readCertificateRecord(serial);
+ mCA.getCertificateRepository().readCertificateRecord(serial);
if (cRecord == null) {
mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_NOT_FROM_CA", serial.toString()));
svcerrors[i] = new ECAException(
- CMS.getUserMessage("CMS_CA_CANT_FIND_CERT_SERIAL",
- serial.toString())).toString();
+ CMS.getUserMessage("CMS_CA_CANT_FIND_CERT_SERIAL",
+ serial.toString())).toString();
continue;
}
// Check renewed certificate already REVOKED or EXPIRED
String status = cRecord.getStatus();
- if (status.equals(ICertRecord.STATUS_REVOKED) ||
- status.equals(ICertRecord.STATUS_REVOKED_EXPIRED)) {
+ if (status.equals(ICertRecord.STATUS_REVOKED) ||
+ status.equals(ICertRecord.STATUS_REVOKED_EXPIRED)) {
Debug.trace("It is already revoked or Expired !!!");
- } // it is still new ... So just return this certificate to user
- else {
+ } // it is still new ... So just return this certificate
+ // to user
+ else {
Debug.trace("It is still new !!!");
issuedCerts[i] = cert;
continue;
- }
+ }
}
}
// issue the cert.
- issuedCerts[i] =
+ issuedCerts[i] =
mService.issueX509Cert(rid, certinfos[i], true, oldSerialNo);
mService.storeX509Cert(rid, issuedCerts[i], true, oldSerialNo);
} catch (ECAException e) {
@@ -1473,14 +1472,15 @@ class serviceRenewal implements IServant {
mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CANNOT_RENEW", Integer.toString(i), request.getRequestId().toString()));
}
}
-
+
// always set issued certs regardless of error.
request.setExtData(IRequest.ISSUED_CERTS, issuedCerts);
// set and throw error if any.
int l;
- for (l = svcerrors.length - 1; l >= 0 && svcerrors[l] == null; l--);
+ for (l = svcerrors.length - 1; l >= 0 && svcerrors[l] == null; l--)
+ ;
if (l >= 0) {
request.setExtData(IRequest.SVCERRORS, svcerrors);
mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_NO_RENEW", request.getRequestId().toString()));
@@ -1490,7 +1490,6 @@ class serviceRenewal implements IServant {
}
}
-
class getCertsForChallenge implements IServant {
private ICertificateAuthority mCA;
private CAService mService;
@@ -1501,10 +1500,10 @@ class getCertsForChallenge implements IServant {
}
public boolean service(IRequest request)
- throws EBaseException {
+ throws EBaseException {
BigInteger[] serialNoArray =
- request.getExtDataInBigIntegerArray(CAService.SERIALNO_ARRAY);
- X509CertImpl[] certs = new X509CertImpl[serialNoArray.length];
+ request.getExtDataInBigIntegerArray(CAService.SERIALNO_ARRAY);
+ X509CertImpl[] certs = new X509CertImpl[serialNoArray.length];
for (int i = 0; i < serialNoArray.length; i++) {
certs[i] = mCA.getCertificateRepository().getX509Certificate(serialNoArray[i]);
@@ -1514,7 +1513,6 @@ class getCertsForChallenge implements IServant {
}
}
-
class getCertStatus implements IServant {
private ICertificateAuthority mCA;
private CAService mService;
@@ -1528,7 +1526,7 @@ class getCertStatus implements IServant {
BigInteger serialno = request.getExtDataInBigInteger("serialNumber");
String issuerDN = request.getExtDataInString("issuerDN");
CertificateRepository certDB = (CertificateRepository)
- mCA.getCertificateRepository();
+ mCA.getCertificateRepository();
String status = null;
@@ -1553,13 +1551,12 @@ class getCertStatus implements IServant {
}
}
}
-
+
request.setExtData(IRequest.CERT_STATUS, status);
return true;
}
}
-
class serviceCheckChallenge implements IServant {
private ICertificateAuthority mCA;
private CAService mService;
@@ -1576,9 +1573,9 @@ class serviceCheckChallenge implements IServant {
}
public boolean service(IRequest request)
- throws EBaseException {
- // note: some request attributes used below are set in
- // authentication/ChallengePhraseAuthentication.java :(
+ throws EBaseException {
+ // note: some request attributes used below are set in
+ // authentication/ChallengePhraseAuthentication.java :(
BigInteger serialno = request.getExtDataInBigInteger("serialNumber");
String pwd = request.getExtDataInString(
CAService.CHALLENGE_PHRASE);
@@ -1606,7 +1603,7 @@ class serviceCheckChallenge implements IServant {
} else {
bigIntArray = new BigInteger[0];
}
- } else
+ } else
bigIntArray = new BigInteger[0];
} else {
String subjectName = request.getExtDataInString("subjectName");
@@ -1623,7 +1620,7 @@ class serviceCheckChallenge implements IServant {
Vector<BigInteger> idv = new Vector<BigInteger>();
while (en.hasMoreElements()) {
- ICertRecord record = en.nextElement();
+ ICertRecord record = en.nextElement();
boolean samepwd = compareChallengePassword(record, pwd);
if (samepwd) {
@@ -1638,7 +1635,7 @@ class serviceCheckChallenge implements IServant {
}
}
- if (bigIntArray == null)
+ if (bigIntArray == null)
bigIntArray = new BigInteger[0];
request.setExtData(CAService.SERIALNO_ARRAY, bigIntArray);
@@ -1646,7 +1643,7 @@ class serviceCheckChallenge implements IServant {
}
private boolean compareChallengePassword(ICertRecord record, String pwd)
- throws EBaseException {
+ throws EBaseException {
MetaInfo metaInfo = (MetaInfo) record.get(CertRecord.ATTR_META_INFO);
if (metaInfo == null) {
@@ -1657,7 +1654,7 @@ class serviceCheckChallenge implements IServant {
// got metaInfo
String challengeString =
- (String) metaInfo.get(CertRecord.META_CHALLENGE_PHRASE);
+ (String) metaInfo.get(CertRecord.META_CHALLENGE_PHRASE);
if (!challengeString.equals(hashpwd)) {
return false;
@@ -1674,7 +1671,6 @@ class serviceCheckChallenge implements IServant {
}
}
-
class serviceRevoke implements IServant {
private ICertificateAuthority mCA;
private CAService mService;
@@ -1684,24 +1680,24 @@ class serviceRevoke implements IServant {
mCA = mService.getCA();
}
- public boolean service(IRequest request)
- throws EBaseException {
+ public boolean service(IRequest request)
+ throws EBaseException {
boolean sendStatus = true;
// XXX Need to think passing as array.
- // XXX every implemented according to servlet.
- RevokedCertImpl crlentries[] =
- request.getExtDataInRevokedCertArray(IRequest.CERT_INFO);
-
- if (crlentries == null ||
- crlentries.length == 0 ||
- crlentries[0] == null) {
- // XXX should this be an error ?
+ // XXX every implemented according to servlet.
+ RevokedCertImpl crlentries[] =
+ request.getExtDataInRevokedCertArray(IRequest.CERT_INFO);
+
+ if (crlentries == null ||
+ crlentries.length == 0 ||
+ crlentries[0] == null) {
+ // XXX should this be an error ?
mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CRL_NOT_FOUND", request.getRequestId().toString()));
throw new ECAException(CMS.getUserMessage("CMS_CA_MISSING_INFO_IN_REVREQ"));
}
- RevokedCertImpl revokedCerts[] =
- new RevokedCertImpl[crlentries.length];
+ RevokedCertImpl revokedCerts[] =
+ new RevokedCertImpl[crlentries.length];
String svcerrors[] = null;
for (int i = 0; i < crlentries.length; i++) {
@@ -1725,7 +1721,7 @@ class serviceRevoke implements IServant {
if (CAService.mCLAConnector != null) {
CMS.debug(CMS.getLogMessage("CMSCORE_CA_CLONE_READ_REVOKED"));
BigInteger revokedCertIds[] =
- new BigInteger[revokedCerts.length];
+ new BigInteger[revokedCerts.length];
for (int i = 0; i < revokedCerts.length; i++) {
revokedCertIds[i] = revokedCerts[i].getSerialNumber();
@@ -1733,16 +1729,16 @@ class serviceRevoke implements IServant {
request.deleteExtData(IRequest.CERT_INFO);
request.deleteExtData(IRequest.OLD_CERTS);
request.setExtData(IRequest.REVOKED_CERT_RECORDS, revokedCertIds);
-
+
CMS.debug(CMS.getLogMessage("CMSCORE_CA_CLONE_READ_REVOKED_CONNECTOR"));
request.setRequestType(IRequest.CLA_CERT4CRL_REQUEST);
sendStatus = CAService.mCLAConnector.send(request);
if (sendStatus == false) {
request.setExtData(IRequest.RESULT,
- IRequest.RES_ERROR);
+ IRequest.RES_ERROR);
request.setExtData(IRequest.ERROR,
- new ECAException(CMS.getUserMessage("CMS_CA_SEND_CLA_REQUEST")));
+ new ECAException(CMS.getUserMessage("CMS_CA_SEND_CLA_REQUEST")));
return sendStatus;
} else {
if (request.getExtDataInString(IRequest.ERROR) != null) {
@@ -1768,7 +1764,6 @@ class serviceRevoke implements IServant {
}
}
-
class serviceUnrevoke implements IServant {
private ICertificateAuthority mCA;
private CAService mService;
@@ -1778,11 +1773,11 @@ class serviceUnrevoke implements IServant {
mCA = mService.getCA();
}
- public boolean service(IRequest request)
- throws EBaseException {
+ public boolean service(IRequest request)
+ throws EBaseException {
boolean sendStatus = true;
- BigInteger oldSerialNo[] =
- request.getExtDataInBigIntegerArray(IRequest.OLD_SERIALS);
+ BigInteger oldSerialNo[] =
+ request.getExtDataInBigIntegerArray(IRequest.OLD_SERIALS);
if (oldSerialNo == null || oldSerialNo.length < 1) {
mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_UNREVOKE_MISSING_SERIAL"));
@@ -1808,7 +1803,7 @@ class serviceUnrevoke implements IServant {
}
if (needOldCerts) {
CertRecord certRec = (CertRecord)
- mCA.getCertificateRepository().readCertificateRecord(oldSerialNo[i]);
+ mCA.getCertificateRepository().readCertificateRecord(oldSerialNo[i]);
oldCerts[i] = certRec.getCertificate();
}
@@ -1828,9 +1823,9 @@ class serviceUnrevoke implements IServant {
sendStatus = CAService.mCLAConnector.send(request);
if (sendStatus == false) {
request.setExtData(IRequest.RESULT,
- IRequest.RES_ERROR);
+ IRequest.RES_ERROR);
request.setExtData(IRequest.ERROR,
- new ECAException(CMS.getUserMessage("CMS_CA_SEND_CLA_REQUEST")));
+ new ECAException(CMS.getUserMessage("CMS_CA_SEND_CLA_REQUEST")));
return sendStatus;
} else {
if (request.getExtDataInString(IRequest.ERROR) != null) {
@@ -1854,7 +1849,6 @@ class serviceUnrevoke implements IServant {
}
}
-
class serviceGetCAChain implements IServant {
private ICertificateAuthority mCA;
private CAService mService;
@@ -1878,7 +1872,6 @@ class serviceGetCAChain implements IServant {
}
}
-
class serviceGetCRL implements IServant {
private ICertificateAuthority mCA;
private CAService mService;
@@ -1889,10 +1882,10 @@ class serviceGetCRL implements IServant {
}
public boolean service(IRequest request)
- throws EBaseException {
+ throws EBaseException {
try {
- ICRLIssuingPointRecord crlRec =
- (ICRLIssuingPointRecord) mCA.getCRLRepository().readCRLIssuingPointRecord(ICertificateAuthority.PROP_MASTER_CRL);
+ ICRLIssuingPointRecord crlRec =
+ (ICRLIssuingPointRecord) mCA.getCRLRepository().readCRLIssuingPointRecord(ICertificateAuthority.PROP_MASTER_CRL);
X509CRLImpl crl = new X509CRLImpl(crlRec.getCRL());
request.setExtData(IRequest.CRL, crl.getEncoded());
@@ -1908,13 +1901,12 @@ class serviceGetCRL implements IServant {
mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_GETCRL_NO_ISSUING_REC"));
throw new ECAException(
CMS.getUserMessage("CMS_CA_CRL_ISSUEPT_EXT_NOGOOD",
- ICertificateAuthority.PROP_MASTER_CRL));
+ ICertificateAuthority.PROP_MASTER_CRL));
}
return true;
}
}
-
class serviceGetRevocationInfo implements IServant {
private ICertificateAuthority mCA;
private CAService mService;
@@ -1925,7 +1917,7 @@ class serviceGetRevocationInfo implements IServant {
}
public boolean service(IRequest request)
- throws EBaseException {
+ throws EBaseException {
Enumeration<String> enum1 = request.getExtDataKeys();
while (enum1.hasMoreElements()) {
@@ -1933,11 +1925,11 @@ class serviceGetRevocationInfo implements IServant {
if (name.equals(IRequest.ISSUED_CERTS)) {
X509CertImpl certsToCheck[] =
- request.getExtDataInCertArray(IRequest.ISSUED_CERTS);
+ request.getExtDataInCertArray(IRequest.ISSUED_CERTS);
CertificateRepository certDB = (CertificateRepository) mCA.getCertificateRepository();
- RevocationInfo info =
- certDB.isCertificateRevoked(certsToCheck[0]);
+ RevocationInfo info =
+ certDB.isCertificateRevoked(certsToCheck[0]);
if (info != null) {
RevokedCertImpl revokedCerts[] = new RevokedCertImpl[1];
@@ -1955,7 +1947,6 @@ class serviceGetRevocationInfo implements IServant {
}
}
-
class serviceGetCertificates implements IServant {
private ICertificateAuthority mCA;
private CAService mService;
@@ -1966,7 +1957,7 @@ class serviceGetCertificates implements IServant {
}
public boolean service(IRequest request)
- throws EBaseException {
+ throws EBaseException {
Enumeration<String> enum1 = request.getExtDataKeys();
while (enum1.hasMoreElements()) {
@@ -1987,7 +1978,6 @@ class serviceGetCertificates implements IServant {
}
}
-
class serviceCert4Crl implements IServant {
private ICertificateAuthority mCA;
private CAService mService;
@@ -1997,14 +1987,14 @@ class serviceCert4Crl implements IServant {
mCA = mService.getCA();
}
- public boolean service(IRequest request)
- throws EBaseException {
+ public boolean service(IRequest request)
+ throws EBaseException {
// XXX Need to think passing as array.
- // XXX every implemented according to servlet.
+ // XXX every implemented according to servlet.
BigInteger revokedCertIds[] = request.getExtDataInBigIntegerArray(
IRequest.REVOKED_CERT_RECORDS);
if (revokedCertIds == null ||
- revokedCertIds.length == 0) {
+ revokedCertIds.length == 0) {
mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CERT4CRL_NO_ENTRY", request.getRequestId().toString()));
throw new ECAException(CMS.getUserMessage("CMS_CA_MISSING_INFO_IN_CLAREQ"));
}
@@ -2013,26 +2003,26 @@ class serviceCert4Crl implements IServant {
for (int i = 0; i < revokedCertIds.length; i++) {
revokedCertRecs[i] = (CertRecord)
mCA.getCertificateRepository().readCertificateRecord(
- revokedCertIds[i]);
+ revokedCertIds[i]);
}
- if (revokedCertRecs == null ||
- revokedCertRecs.length == 0 ||
- revokedCertRecs[0] == null) {
- // XXX should this be an error ?
+ if (revokedCertRecs == null ||
+ revokedCertRecs.length == 0 ||
+ revokedCertRecs[0] == null) {
+ // XXX should this be an error ?
mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CERT4CRL_NO_ENTRY", request.getRequestId().toString()));
throw new ECAException(CMS.getUserMessage("CMS_CA_MISSING_INFO_IN_CLAREQ"));
}
- CertRecord recordedCerts[] =
- new CertRecord[revokedCertRecs.length];
+ CertRecord recordedCerts[] =
+ new CertRecord[revokedCertRecs.length];
String svcerrors[] = null;
for (int i = 0; i < revokedCertRecs.length; i++) {
try {
// for CLA, record it into cert repost
((CertificateRepository) mCA.getCertificateRepository()).addRevokedCertRecord(revokedCertRecs[i]);
- // mService.revokeCert(crlentries[i]);
+ // mService.revokeCert(crlentries[i]);
recordedCerts[i] = revokedCertRecs[i];
// inform all CRLIssuingPoints about revoked certificate
Hashtable<String, ICRLIssuingPoint> hips = mService.getCRLIssuingPoints();
@@ -2041,9 +2031,9 @@ class serviceCert4Crl implements IServant {
while (eIPs.hasMoreElements()) {
ICRLIssuingPoint ip = (ICRLIssuingPoint) eIPs.nextElement();
// form RevokedCertImpl
- RevokedCertImpl rci =
- new RevokedCertImpl(revokedCertRecs[i].getSerialNumber(),
- revokedCertRecs[i].getRevokedOn());
+ RevokedCertImpl rci =
+ new RevokedCertImpl(revokedCertRecs[i].getSerialNumber(),
+ revokedCertRecs[i].getRevokedOn());
if (ip != null) {
ip.addRevokedCert(revokedCertRecs[i].getSerialNumber(), rci);
@@ -2059,8 +2049,8 @@ class serviceCert4Crl implements IServant {
svcerrors[i] = e.toString();
}
}
- //need to record which gets recorded and which failed...cfu
- // request.set(IRequest.REVOKED_CERTS, revokedCerts);
+ // need to record which gets recorded and which failed...cfu
+ // request.set(IRequest.REVOKED_CERTS, revokedCerts);
if (svcerrors != null) {
request.setExtData(IRequest.SVCERRORS, svcerrors);
throw new ECAException(CMS.getUserMessage("CMS_CA_CERT4CRL_FAILED"));
@@ -2070,7 +2060,6 @@ class serviceCert4Crl implements IServant {
}
}
-
class serviceUnCert4Crl implements IServant {
private ICertificateAuthority mCA;
private CAService mService;
@@ -2080,10 +2069,10 @@ class serviceUnCert4Crl implements IServant {
mCA = mService.getCA();
}
- public boolean service(IRequest request)
- throws EBaseException {
- BigInteger oldSerialNo[] =
- request.getExtDataInBigIntegerArray(IRequest.OLD_SERIALS);
+ public boolean service(IRequest request)
+ throws EBaseException {
+ BigInteger oldSerialNo[] =
+ request.getExtDataInBigIntegerArray(IRequest.OLD_SERIALS);
if (oldSerialNo == null || oldSerialNo.length < 1) {
mCA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_UNREVOKE_MISSING_SERIAL"));
@@ -2125,4 +2114,3 @@ class serviceUnCert4Crl implements IServant {
return true;
}
}
-
diff --git a/pki/base/ca/src/com/netscape/ca/CMSCRLExtensions.java b/pki/base/ca/src/com/netscape/ca/CMSCRLExtensions.java
index 55449dff..e0064ddf 100644
--- a/pki/base/ca/src/com/netscape/ca/CMSCRLExtensions.java
+++ b/pki/base/ca/src/com/netscape/ca/CMSCRLExtensions.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.ca;
-
import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.Enumeration;
@@ -56,7 +55,6 @@ import com.netscape.certsrv.logging.ILogger;
import com.netscape.cms.crl.CMSIssuingDistributionPointExtension;
import com.netscape.cmscore.base.SubsystemRegistry;
-
public class CMSCRLExtensions implements ICMSCRLExtensions {
public static final String PROP_ENABLE = "enable";
public static final String PROP_EXTENSION = "extension";
@@ -65,7 +63,7 @@ public class CMSCRLExtensions implements ICMSCRLExtensions {
public static final String PROP_CRITICAL = "critical";
public static final String PROP_CRL_EXT = "CRLExtension";
public static final String PROP_CRL_ENTRY_EXT = "CRLEntryExtension";
-
+
private ICRLIssuingPoint mCRLIssuingPoint = null;
private IConfigStore mConfig = null;
@@ -100,91 +98,91 @@ public class CMSCRLExtensions implements ICMSCRLExtensions {
/* Default CRL Entry Extensions */
mDefaultCRLEntryExtensionNames.addElement(CRLReasonExtension.class.getSimpleName());
- //mDefaultCRLEntryExtensionNames.addElement(HoldInstructionExtension.NAME);
+ // mDefaultCRLEntryExtensionNames.addElement(HoldInstructionExtension.NAME);
mDefaultCRLEntryExtensionNames.addElement(InvalidityDateExtension.class.getSimpleName());
- //mDefaultCRLEntryExtensionNames.addElement(CertificateIssuerExtension.NAME);
+ // mDefaultCRLEntryExtensionNames.addElement(CertificateIssuerExtension.NAME);
/* Default Enabled CRL Extensions */
mDefaultEnabledCRLExtensions.addElement(CRLNumberExtension.class.getSimpleName());
- //mDefaultEnabledCRLExtensions.addElement(DeltaCRLIndicatorExtension.NAME);
+ // mDefaultEnabledCRLExtensions.addElement(DeltaCRLIndicatorExtension.NAME);
mDefaultEnabledCRLExtensions.addElement(CRLReasonExtension.class.getSimpleName());
mDefaultEnabledCRLExtensions.addElement(InvalidityDateExtension.class.getSimpleName());
/* Default Critical CRL Extensions */
mDefaultCriticalCRLExtensions.addElement(DeltaCRLIndicatorExtension.class.getSimpleName());
mDefaultCriticalCRLExtensions.addElement(IssuingDistributionPointExtension.class.getSimpleName());
- //mDefaultCriticalCRLExtensions.addElement(CertificateIssuerExtension.NAME);
+ // mDefaultCriticalCRLExtensions.addElement(CertificateIssuerExtension.NAME);
/* CRL extension IDs */
mDefaultCRLExtensionIDs.put(PKIXExtensions.AuthorityKey_Id.toString(),
- AuthorityKeyIdentifierExtension.class.getSimpleName());
+ AuthorityKeyIdentifierExtension.class.getSimpleName());
mDefaultCRLExtensionIDs.put(PKIXExtensions.IssuerAlternativeName_Id.toString(),
- IssuerAlternativeNameExtension.class.getSimpleName());
+ IssuerAlternativeNameExtension.class.getSimpleName());
mDefaultCRLExtensionIDs.put(PKIXExtensions.CRLNumber_Id.toString(),
- CRLNumberExtension.class.getSimpleName());
+ CRLNumberExtension.class.getSimpleName());
mDefaultCRLExtensionIDs.put(PKIXExtensions.DeltaCRLIndicator_Id.toString(),
- DeltaCRLIndicatorExtension.class.getSimpleName());
+ DeltaCRLIndicatorExtension.class.getSimpleName());
mDefaultCRLExtensionIDs.put(PKIXExtensions.IssuingDistributionPoint_Id.toString(),
- IssuingDistributionPointExtension.class.getSimpleName());
+ IssuingDistributionPointExtension.class.getSimpleName());
mDefaultCRLExtensionIDs.put(PKIXExtensions.ReasonCode_Id.toString(),
- CRLReasonExtension.class.getSimpleName());
+ CRLReasonExtension.class.getSimpleName());
mDefaultCRLExtensionIDs.put(PKIXExtensions.HoldInstructionCode_Id.toString(),
- HoldInstructionExtension.class.getSimpleName());
+ HoldInstructionExtension.class.getSimpleName());
mDefaultCRLExtensionIDs.put(PKIXExtensions.InvalidityDate_Id.toString(),
- InvalidityDateExtension.class.getSimpleName());
- //mDefaultCRLExtensionIDs.put(PKIXExtensions.CertificateIssuer_Id.toString(),
- // CertificateIssuerExtension.NAME);
+ InvalidityDateExtension.class.getSimpleName());
+ // mDefaultCRLExtensionIDs.put(PKIXExtensions.CertificateIssuer_Id.toString(),
+ // CertificateIssuerExtension.NAME);
mDefaultCRLExtensionIDs.put(PKIXExtensions.FreshestCRL_Id.toString(),
- FreshestCRLExtension.class.getSimpleName());
+ FreshestCRLExtension.class.getSimpleName());
mDefaultCRLExtensionIDs.put(AuthInfoAccessExtension.ID.toString(),
- AuthInfoAccessExtension.NAME2);
+ AuthInfoAccessExtension.NAME2);
/* Class names */
mDefaultCRLExtensionClassNames.put(AuthorityKeyIdentifierExtension.class.getSimpleName(),
- "com.netscape.cms.crl.CMSAuthorityKeyIdentifierExtension");
+ "com.netscape.cms.crl.CMSAuthorityKeyIdentifierExtension");
mDefaultCRLExtensionClassNames.put(IssuerAlternativeNameExtension.class.getSimpleName(),
- "com.netscape.cms.crl.CMSIssuerAlternativeNameExtension");
+ "com.netscape.cms.crl.CMSIssuerAlternativeNameExtension");
mDefaultCRLExtensionClassNames.put(CRLNumberExtension.class.getSimpleName(),
- "com.netscape.cms.crl.CMSCRLNumberExtension");
+ "com.netscape.cms.crl.CMSCRLNumberExtension");
mDefaultCRLExtensionClassNames.put(DeltaCRLIndicatorExtension.class.getSimpleName(),
- "com.netscape.cms.crl.CMSDeltaCRLIndicatorExtension");
+ "com.netscape.cms.crl.CMSDeltaCRLIndicatorExtension");
mDefaultCRLExtensionClassNames.put(IssuingDistributionPointExtension.class.getSimpleName(),
- "com.netscape.cms.crl.CMSIssuingDistributionPointExtension");
+ "com.netscape.cms.crl.CMSIssuingDistributionPointExtension");
mDefaultCRLExtensionClassNames.put(CRLReasonExtension.class.getSimpleName(),
- "com.netscape.cms.crl.CMSCRLReasonExtension");
+ "com.netscape.cms.crl.CMSCRLReasonExtension");
mDefaultCRLExtensionClassNames.put(HoldInstructionExtension.class.getSimpleName(),
- "com.netscape.cms.crl.CMSHoldInstructionExtension");
+ "com.netscape.cms.crl.CMSHoldInstructionExtension");
mDefaultCRLExtensionClassNames.put(InvalidityDateExtension.class.getSimpleName(),
- "com.netscape.cms.crl.CMSInvalidityDateExtension");
- //mDefaultCRLExtensionClassNames.put(CertificateIssuerExtension.NAME,
- // "com.netscape.cms.crl.CMSCertificateIssuerExtension");
+ "com.netscape.cms.crl.CMSInvalidityDateExtension");
+ // mDefaultCRLExtensionClassNames.put(CertificateIssuerExtension.NAME,
+ // "com.netscape.cms.crl.CMSCertificateIssuerExtension");
mDefaultCRLExtensionClassNames.put(FreshestCRLExtension.class.getSimpleName(),
- "com.netscape.cms.crl.CMSFreshestCRLExtension");
+ "com.netscape.cms.crl.CMSFreshestCRLExtension");
mDefaultCRLExtensionClassNames.put(AuthInfoAccessExtension.NAME2,
- "com.netscape.cms.crl.CMSAuthInfoAccessExtension");
+ "com.netscape.cms.crl.CMSAuthInfoAccessExtension");
try {
OIDMap.addAttribute(DeltaCRLIndicatorExtension.class.getName(),
- DeltaCRLIndicatorExtension.OID,
- DeltaCRLIndicatorExtension.class.getSimpleName());
+ DeltaCRLIndicatorExtension.OID,
+ DeltaCRLIndicatorExtension.class.getSimpleName());
} catch (CertificateException e) {
}
try {
OIDMap.addAttribute(HoldInstructionExtension.class.getName(),
- HoldInstructionExtension.OID,
- HoldInstructionExtension.class.getSimpleName());
+ HoldInstructionExtension.OID,
+ HoldInstructionExtension.class.getSimpleName());
} catch (CertificateException e) {
}
try {
OIDMap.addAttribute(InvalidityDateExtension.class.getName(),
- InvalidityDateExtension.OID,
- InvalidityDateExtension.class.getSimpleName());
+ InvalidityDateExtension.OID,
+ InvalidityDateExtension.class.getSimpleName());
} catch (CertificateException e) {
}
try {
OIDMap.addAttribute(FreshestCRLExtension.class.getName(),
- FreshestCRLExtension.OID,
- FreshestCRLExtension.class.getSimpleName());
+ FreshestCRLExtension.OID,
+ FreshestCRLExtension.class.getSimpleName());
} catch (CertificateException e) {
}
}
@@ -195,12 +193,12 @@ public class CMSCRLExtensions implements ICMSCRLExtensions {
public CMSCRLExtensions(ICRLIssuingPoint crlIssuingPoint, IConfigStore config) {
boolean modifiedConfig = false;
- mConfig = config;
+ mConfig = config;
mCRLExtConfig = config.getSubStore(PROP_EXTENSION);
mCRLIssuingPoint = crlIssuingPoint;
- IConfigStore mFileConfig =
- SubsystemRegistry.getInstance().get("MAIN").getConfigStore();
+ IConfigStore mFileConfig =
+ SubsystemRegistry.getInstance().get("MAIN").getConfigStore();
IConfigStore crlExtConfig = (IConfigStore) mFileConfig;
StringTokenizer st = new StringTokenizer(mCRLExtConfig.getName(), ".");
@@ -212,13 +210,13 @@ public class CMSCRLExtensions implements ICMSCRLExtensions {
if (newConfig != null) {
crlExtConfig = newConfig;
}
- }
+ }
if (crlExtConfig != null) {
Enumeration<String> enumExts = crlExtConfig.getSubStoreNames();
while (enumExts.hasMoreElements()) {
- String extName = enumExts.nextElement();
+ String extName = enumExts.nextElement();
IConfigStore extConfig = crlExtConfig.getSubStore(extName);
if (extConfig != null) {
@@ -361,10 +359,10 @@ public class CMSCRLExtensions implements ICMSCRLExtensions {
Class<ICMSCRLExtension> crlExtClass = (Class<ICMSCRLExtension>) Class.forName(extClass);
if (crlExtClass != null) {
- ICMSCRLExtension cmsCRLExt = crlExtClass.newInstance();
+ ICMSCRLExtension cmsCRLExt = crlExtClass.newInstance();
if (cmsCRLExt != null) {
- String id = cmsCRLExt.getCRLExtOID();
+ String id = cmsCRLExt.getCRLExtOID();
if (id != null) {
mCRLExtensionIDs.put(id, extName);
@@ -383,7 +381,7 @@ public class CMSCRLExtensions implements ICMSCRLExtensions {
} else {
if (mDefaultCRLExtensionClassNames.containsKey(extName)) {
- extClass = mCRLExtensionClassNames.get(extName);
+ extClass = mCRLExtensionClassNames.get(extName);
extConfig.putString(PROP_CLASS, extClass);
modifiedConfig = true;
}
@@ -391,14 +389,14 @@ public class CMSCRLExtensions implements ICMSCRLExtensions {
}
} catch (EPropertyNotFound e) {
if (mDefaultCRLExtensionClassNames.containsKey(extName)) {
- extClass = mDefaultCRLExtensionClassNames.get(extName);
+ extClass = mDefaultCRLExtensionClassNames.get(extName);
extConfig.putString(PROP_CLASS, extClass);
modifiedConfig = true;
}
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CRLEXTS_CLASS_MISSING", extName));
} catch (EBaseException e) {
if (mDefaultCRLExtensionClassNames.containsKey(extName)) {
- extClass = mDefaultCRLExtensionClassNames.get(extName);
+ extClass = mDefaultCRLExtensionClassNames.get(extName);
extConfig.putString(PROP_CLASS, extClass);
modifiedConfig = true;
}
@@ -416,9 +414,7 @@ public class CMSCRLExtensions implements ICMSCRLExtensions {
}
public boolean isCRLExtensionEnabled(String extName) {
- return ((mCRLExtensionNames.contains(extName) ||
- mCRLEntryExtensionNames.contains(extName)) &&
- mEnabledCRLExtensions.contains(extName));
+ return ((mCRLExtensionNames.contains(extName) || mCRLEntryExtensionNames.contains(extName)) && mEnabledCRLExtensions.contains(extName));
}
public boolean isCRLExtensionCritical(String extName) {
@@ -429,7 +425,7 @@ public class CMSCRLExtensions implements ICMSCRLExtensions {
String name = null;
if (mCRLExtensionIDs.containsKey(id)) {
- name = mCRLExtensionIDs.get(id);
+ name = mCRLExtensionIDs.get(id);
}
return name;
}
@@ -439,16 +435,16 @@ public class CMSCRLExtensions implements ICMSCRLExtensions {
}
public Vector<String> getCRLEntryExtensionNames() {
- return new Vector<String>( mCRLEntryExtensionNames);
+ return new Vector<String>(mCRLEntryExtensionNames);
}
public void addToCRLExtensions(CRLExtensions crlExts, String extName, Extension ext) {
if (mCRLExtensionClassNames.containsKey(extName)) {
- String name = mCRLExtensionClassNames.get(extName);
+ String name = mCRLExtensionClassNames.get(extName);
try {
@SuppressWarnings("unchecked")
- Class<ICMSCRLExtension > extClass = (Class<ICMSCRLExtension>) Class.forName(name);
+ Class<ICMSCRLExtension> extClass = (Class<ICMSCRLExtension>) Class.forName(name);
if (extClass != null) {
ICMSCRLExtension cmsCRLExt = extClass.newInstance();
@@ -488,21 +484,17 @@ public class CMSCRLExtensions implements ICMSCRLExtensions {
NameValuePairs nvp = null;
if (mCRLEntryExtensionNames.contains(id) ||
- mCRLExtensionNames.contains(id)) {
+ mCRLExtensionNames.contains(id)) {
nvp = new NameValuePairs();
/*
- if (mCRLEntryExtensionNames.contains(id)) {
- nvp.add(Constants.PR_CRLEXT_IMPL_NAME, "CRLEntryExtension");
- } else {
- nvp.add(Constants.PR_CRLEXT_IMPL_NAME, "CRLExtension");
- }
-
- if (mCRLEntryExtensionNames.contains(id)) {
- nvp.add(PROP_TYPE, "CRLEntryExtension");
- } else {
- nvp.add(PROP_TYPE, "CRLExtension");
- }
+ * if (mCRLEntryExtensionNames.contains(id)) {
+ * nvp.add(Constants.PR_CRLEXT_IMPL_NAME, "CRLEntryExtension"); }
+ * else { nvp.add(Constants.PR_CRLEXT_IMPL_NAME, "CRLExtension"); }
+ *
+ * if (mCRLEntryExtensionNames.contains(id)) { nvp.add(PROP_TYPE,
+ * "CRLEntryExtension"); } else { nvp.add(PROP_TYPE,
+ * "CRLExtension"); }
*/
if (mEnabledCRLExtensions.contains(id)) {
@@ -517,7 +509,7 @@ public class CMSCRLExtensions implements ICMSCRLExtensions {
}
if (mCRLExtensionClassNames.containsKey(id)) {
- String name = mCRLExtensionClassNames.get(id);
+ String name = mCRLExtensionClassNames.get(id);
if (name != null) {
@@ -555,12 +547,12 @@ public class CMSCRLExtensions implements ICMSCRLExtensions {
}
public void setConfigParams(String id, NameValuePairs nvp, IConfigStore config) {
- ICertificateAuthority ca = (ICertificateAuthority) CMS.getSubsystem(CMS.SUBSYSTEM_CA);
+ ICertificateAuthority ca = (ICertificateAuthority) CMS.getSubsystem(CMS.SUBSYSTEM_CA);
String ipId = nvp.getValue("id");
- ICRLIssuingPoint ip = null;
- if(ipId != null && ca != null) {
- ip = ca.getCRLIssuingPoint(ipId);
+ ICRLIssuingPoint ip = null;
+ if (ipId != null && ca != null) {
+ ip = ca.getCRLIssuingPoint(ipId);
}
for (int i = 0; i < nvp.size(); i++) {
@@ -569,8 +561,7 @@ public class CMSCRLExtensions implements ICMSCRLExtensions {
String value = p.getValue();
if (name.equals(PROP_ENABLE)) {
- if (!(value.equals(Constants.TRUE) ||
- value.equals(Constants.FALSE))) {
+ if (!(value.equals(Constants.TRUE) || value.equals(Constants.FALSE))) {
continue;
}
if (value.equals(Constants.TRUE)) {
@@ -584,8 +575,7 @@ public class CMSCRLExtensions implements ICMSCRLExtensions {
}
if (name.equals(PROP_CRITICAL)) {
- if (!(value.equals(Constants.TRUE) ||
- value.equals(Constants.FALSE))) {
+ if (!(value.equals(Constants.TRUE) || value.equals(Constants.FALSE))) {
continue;
}
if (value.equals(Constants.TRUE)) {
@@ -597,39 +587,40 @@ public class CMSCRLExtensions implements ICMSCRLExtensions {
mCriticalCRLExtensions.remove(id);
}
}
- //Sync the onlyContainsCACerts with similar property in CRLIssuingPoint
- //called caCertsOnly.
- if(name.equals(CMSIssuingDistributionPointExtension.PROP_CACERTS)) {
+ // Sync the onlyContainsCACerts with similar property in
+ // CRLIssuingPoint
+ // called caCertsOnly.
+ if (name.equals(CMSIssuingDistributionPointExtension.PROP_CACERTS)) {
NameValuePairs crlIssuingPointPairs = null;
boolean crlCACertsOnly = false;
boolean issuingDistPointExtEnabled = false;
CMSCRLExtensions cmsCRLExtensions = (CMSCRLExtensions) ip.getCRLExtensions();
- if(cmsCRLExtensions != null) {
- issuingDistPointExtEnabled = cmsCRLExtensions.isCRLExtensionEnabled(IssuingDistributionPointExtension.class.getSimpleName());
+ if (cmsCRLExtensions != null) {
+ issuingDistPointExtEnabled = cmsCRLExtensions.isCRLExtensionEnabled(IssuingDistributionPointExtension.class.getSimpleName());
}
CMS.debug("issuingDistPointExtEnabled = " + issuingDistPointExtEnabled);
- if (!(value.equals(Constants.TRUE) ||
- value.equals(Constants.FALSE))) {
+ if (!(value.equals(Constants.TRUE) || value.equals(Constants.FALSE))) {
continue;
}
- //Get value of caCertsOnly from CRLIssuingPoint
- if((ip != null) && (issuingDistPointExtEnabled == true)) {
+ // Get value of caCertsOnly from CRLIssuingPoint
+ if ((ip != null) && (issuingDistPointExtEnabled == true)) {
crlCACertsOnly = ip.isCACertsOnly();
CMS.debug("CRLCACertsOnly is: " + crlCACertsOnly);
crlIssuingPointPairs = new NameValuePairs();
-
+
}
String newValue = "";
boolean modifiedCRLConfig = false;
- //If the CRLCACertsOnly prop is false change it to true to sync.
- if(value.equals(Constants.TRUE) && (issuingDistPointExtEnabled == true)) {
- if(crlCACertsOnly == false) {
+ // If the CRLCACertsOnly prop is false change it to true to
+ // sync.
+ if (value.equals(Constants.TRUE) && (issuingDistPointExtEnabled == true)) {
+ if (crlCACertsOnly == false) {
CMS.debug(" value = true and CRLCACertsOnly is already false.");
crlIssuingPointPairs.add(Constants.PR_CA_CERTS_ONLY, Constants.TRUE);
newValue = Constants.TRUE;
@@ -638,24 +629,25 @@ public class CMSCRLExtensions implements ICMSCRLExtensions {
}
}
- //If the CRLCACertsOnly prop is true change it to false to sync.
- if(value.equals(Constants.FALSE) && (issuingDistPointExtEnabled == true)) {
+ // If the CRLCACertsOnly prop is true change it to false to
+ // sync.
+ if (value.equals(Constants.FALSE) && (issuingDistPointExtEnabled == true)) {
crlIssuingPointPairs.add(Constants.PR_CA_CERTS_ONLY, Constants.FALSE);
- if(ip != null) {
+ if (ip != null) {
ip.updateConfig(crlIssuingPointPairs);
newValue = Constants.FALSE;
modifiedCRLConfig = true;
}
}
-
- if(modifiedCRLConfig == true) {
- //Commit to this CRL IssuingPoint's config store
+
+ if (modifiedCRLConfig == true) {
+ // Commit to this CRL IssuingPoint's config store
ICertificateAuthority CA = (ICertificateAuthority) CMS.getSubsystem(CMS.SUBSYSTEM_CA);
IConfigStore crlsSubStore = CA.getConfigStore();
- crlsSubStore = crlsSubStore.getSubStore(ICertificateAuthority.PROP_CRL_SUBSTORE);
+ crlsSubStore = crlsSubStore.getSubStore(ICertificateAuthority.PROP_CRL_SUBSTORE);
crlsSubStore = crlsSubStore.getSubStore(ipId);
try {
- crlsSubStore.putString(Constants.PR_CA_CERTS_ONLY,newValue);
+ crlsSubStore.putString(Constants.PR_CA_CERTS_ONLY, newValue);
crlsSubStore.commit(true);
} catch (EBaseException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CRLEXTS_SAVE_CONF", e.toString()));
@@ -693,7 +685,6 @@ public class CMSCRLExtensions implements ICMSCRLExtensions {
private void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_CA, level,
- "CMSCRLExtension - " + msg);
+ "CMSCRLExtension - " + msg);
}
}
-
diff --git a/pki/base/ca/src/com/netscape/ca/CRLIssuingPoint.java b/pki/base/ca/src/com/netscape/ca/CRLIssuingPoint.java
index 5b98c62e..7a5a109b 100644
--- a/pki/base/ca/src/com/netscape/ca/CRLIssuingPoint.java
+++ b/pki/base/ca/src/com/netscape/ca/CRLIssuingPoint.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.ca;
-
import java.io.IOException;
import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
@@ -85,18 +84,17 @@ import com.netscape.cmscore.dbs.CertificateRepository;
import com.netscape.cmscore.util.Debug;
/**
- * This class encapsulates CRL issuing mechanism. CertificateAuthority
- * contains a map of CRLIssuingPoint indexed by string ids. Each issuing
- * point contains information about CRL issuing and publishing parameters
- * as well as state information which includes last issued CRL, next CRL
- * serial number, time of the next update etc.
- * If autoUpdateInterval is set to non-zero value then worker thread
- * is created that will perform CRL update at scheduled intervals. Update
- * can also be triggered by invoking updateCRL method directly. Another
- * parameter minUpdateInterval can be used to prevent CRL
- * from being updated too often
+ * This class encapsulates CRL issuing mechanism. CertificateAuthority contains
+ * a map of CRLIssuingPoint indexed by string ids. Each issuing point contains
+ * information about CRL issuing and publishing parameters as well as state
+ * information which includes last issued CRL, next CRL serial number, time of
+ * the next update etc. If autoUpdateInterval is set to non-zero value then
+ * worker thread is created that will perform CRL update at scheduled intervals.
+ * Update can also be triggered by invoking updateCRL method directly. Another
+ * parameter minUpdateInterval can be used to prevent CRL from being updated too
+ * often
* <P>
- *
+ *
* @author awnuk
* @author lhsiao
* @author galperin
@@ -133,8 +131,8 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
protected String mId = null;
/**
- * Reference to the CertificateAuthority instance which owns this
- * issuing point.
+ * Reference to the CertificateAuthority instance which owns this issuing
+ * point.
*/
protected ICertificateAuthority mCA = null;
@@ -161,16 +159,16 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
/**
* CRL cache
*/
- private Hashtable<BigInteger,RevokedCertificate> mCRLCerts = new Hashtable<BigInteger, RevokedCertificate>();
- private Hashtable<BigInteger,RevokedCertificate> mRevokedCerts = new Hashtable<BigInteger, RevokedCertificate>();
- private Hashtable<BigInteger,RevokedCertificate> mUnrevokedCerts = new Hashtable<BigInteger, RevokedCertificate>();
- private Hashtable<BigInteger,RevokedCertificate> mExpiredCerts = new Hashtable<BigInteger, RevokedCertificate>();
+ private Hashtable<BigInteger, RevokedCertificate> mCRLCerts = new Hashtable<BigInteger, RevokedCertificate>();
+ private Hashtable<BigInteger, RevokedCertificate> mRevokedCerts = new Hashtable<BigInteger, RevokedCertificate>();
+ private Hashtable<BigInteger, RevokedCertificate> mUnrevokedCerts = new Hashtable<BigInteger, RevokedCertificate>();
+ private Hashtable<BigInteger, RevokedCertificate> mExpiredCerts = new Hashtable<BigInteger, RevokedCertificate>();
private boolean mIncludeExpiredCerts = false;
private boolean mIncludeExpiredCertsOneExtraTime = false;
private boolean mCACertsOnly = false;
private boolean mProfileCertsOnly = false;
- private Vector<String> mProfileList = null;
+ private Vector<String> mProfileList = null;
/**
* Enable CRL cache.
@@ -178,7 +176,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
private boolean mEnableCRLCache = true;
private boolean mCRLCacheIsCleared = true;
private boolean mEnableCacheRecovery = false;
- private String mFirstUnsaved = null;
+ private String mFirstUnsaved = null;
private boolean mEnableCacheTesting = false;
/**
@@ -187,8 +185,8 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
private long mLastCacheUpdate = 0;
/**
- * Time interval in milliseconds between consequential CRL cache
- * updates performed automatically.
+ * Time interval in milliseconds between consequential CRL cache updates
+ * performed automatically.
*/
private long mCacheUpdateInterval;
@@ -207,7 +205,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
* Enable CRL daily updates at listed times.
*/
private boolean mEnableDailyUpdates = false;
- private Vector<Vector<Integer>> mDailyUpdates = null;
+ private Vector<Vector<Integer>> mDailyUpdates = null;
private int mCurrentDay = 0;
private int mLastDay = 0;
private int mTimeListSize = 0;
@@ -219,14 +217,14 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
private boolean mEnableUpdateFreq = false;
/**
- * Time interval in milliseconds between consequential CRL Enable CRL daily update at updates
- * performed automatically.
+ * Time interval in milliseconds between consequential CRL Enable CRL daily
+ * update at updates performed automatically.
*/
private long mAutoUpdateInterval;
/**
- * Minimum time interval in milliseconds between consequential
- * CRL updates (manual or automatic).
+ * Minimum time interval in milliseconds between consequential CRL updates
+ * (manual or automatic).
*/
private long mMinUpdateInterval;
@@ -238,17 +236,16 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
/**
* next update grace period
*/
- private long mNextUpdateGracePeriod;
+ private long mNextUpdateGracePeriod;
/**
- * Boolean flag controlling whether CRLv2 extensions are to be
- * used in CRL.
+ * Boolean flag controlling whether CRLv2 extensions are to be used in CRL.
*/
private boolean mAllowExtensions = false;
/**
- * DN of the directory entry where CRLs from this issuing point
- * are published.
+ * DN of the directory entry where CRLs from this issuing point are
+ * published.
*/
private String mPublishDN = null;
@@ -261,7 +258,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
/**
* Cached value of the CRL extensions to be placed in CRL
*/
- //protected CRLExtensions mCrlExtensions;
+ // protected CRLExtensions mCrlExtensions;
/**
* CRL number
@@ -296,7 +293,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
private Thread mUpdateThread = null;
/**
- * for going one more round when auto-interval is set to 0 (turned off)
+ * for going one more round when auto-interval is set to 0 (turned off)
*/
private boolean mDoLastAutoUpdate = false;
@@ -312,15 +309,15 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
private long mDeltaCRLSize = -1;
/**
- * update status, publishing status Strings to store in requests to
- * display result.
+ * update status, publishing status Strings to store in requests to display
+ * result.
*/
private String mCrlUpdateStatus;
private String mCrlUpdateError;
private String mCrlPublishStatus;
private String mCrlPublishError;
- /**
+ /**
* begin, end serial number range of revoked certs if any.
*/
protected BigInteger mBeginSerial = null;
@@ -329,7 +326,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
private int mUpdatingCRL = CRL_UPDATE_DONE;
private boolean mDoManualUpdate = false;
- private String mSignatureAlgorithmForManualUpdate = null;
+ private String mSignatureAlgorithmForManualUpdate = null;
private boolean mPublishOnStart = false;
private long[] mSplits = new long[10];
@@ -337,8 +334,8 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
private boolean mSaveMemory = false;
/**
- * Constructs a CRL issuing point from instantiating from class name.
- * CRL Issuing point must be followed by method call init(CA, id, config);
+ * Constructs a CRL issuing point from instantiating from class name. CRL
+ * Issuing point must be followed by method call init(CA, id, config);
*/
public CRLIssuingPoint() {
}
@@ -412,24 +409,23 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
}
}
}
-
+
return b;
}
-
/**
* Initializes a CRL issuing point config.
* <P>
- *
- * @param ca reference to CertificateAuthority instance which
- * owns this issuing point.
+ *
+ * @param ca reference to CertificateAuthority instance which owns this
+ * issuing point.
* @param id string id of this CRL issuing point.
* @param config configuration of this CRL issuing point.
* @exception EBaseException if initialization failed
* @exception IOException
*/
- public void init(ISubsystem ca, String id, IConfigStore config)
- throws EBaseException {
+ public void init(ISubsystem ca, String id, IConfigStore config)
+ throws EBaseException {
mCA = (ICertificateAuthority) ca;
mId = id;
@@ -449,15 +445,15 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
IConfigStore crlSubStore = mCA.getConfigStore().getSubStore(ICertificateAuthority.PROP_CRL_SUBSTORE);
mPageSize = crlSubStore.getInteger(ICertificateAuthority.PROP_CRL_PAGE_SIZE, CRL_PAGE_SIZE);
- CMS.debug("CRL Page Size: "+ mPageSize);
+ CMS.debug("CRL Page Size: " + mPageSize);
- mCountMod = config.getInteger("countMod",0);
+ mCountMod = config.getInteger("countMod", 0);
mCRLRepository = mCA.getCRLRepository();
mCertRepository = mCA.getCertificateRepository();
((CertificateRepository) mCertRepository).addCRLIssuingPoint(mId, this);
mPublisherProcessor = mCA.getPublisherProcessor();
- //mCRLPublisher = mCA.getCRLPublisher();
+ // mCRLPublisher = mCA.getCRLPublisher();
((CAService) mCA.getCAService()).addCRLIssuingPoint(mId, this);
// read in config parameters.
@@ -469,7 +465,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
if (mCA.getRequestListener(crlListName) == null) {
mCA.registerRequestListener(
- crlListName, new RevocationRequestListener());
+ crlListName, new RevocationRequestListener());
}
for (int i = 0; i < mSplits.length; i++) {
@@ -480,52 +476,60 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
setAutoUpdates();
}
-
private int checkTime(String time) {
String digits = "0123456789";
int len = time.length();
- if (len < 3 || len > 5) return -1;
+ if (len < 3 || len > 5)
+ return -1;
int s = time.indexOf(':');
- if (s < 0 || s > 2 || (len - s) != 3) return -1;
+ if (s < 0 || s > 2 || (len - s) != 3)
+ return -1;
int h = 0;
for (int i = 0; i < s; i++) {
h *= 10;
int k = digits.indexOf(time.charAt(i));
- if (k < 0) return -1;
+ if (k < 0)
+ return -1;
h += k;
}
- if (h > 23) return -1;
+ if (h > 23)
+ return -1;
int m = 0;
- for (int i = s+1; i < len; i++) {
+ for (int i = s + 1; i < len; i++) {
m *= 10;
int k = digits.indexOf(time.charAt(i));
- if (k < 0) return -1;
+ if (k < 0)
+ return -1;
m += k;
}
- if (m > 59) return -1;
+ if (m > 59)
+ return -1;
return ((h * 60) + m);
}
private boolean areTimeListsIdentical(Vector<Vector<Integer>> list1, Vector<Vector<Integer>> list2) {
boolean identical = true;
- if (list1 == null || list2 == null) identical = false;
- if (identical && list1.size() != list2.size()) identical = false;
+ if (list1 == null || list2 == null)
+ identical = false;
+ if (identical && list1.size() != list2.size())
+ identical = false;
for (int i = 0; identical && i < list1.size(); i++) {
Vector<Integer> times1 = list1.elementAt(i);
Vector<Integer> times2 = list2.elementAt(i);
- if (times1.size() != times2.size()) identical = false;
+ if (times1.size() != times2.size())
+ identical = false;
for (int j = 0; identical && j < times1.size(); j++) {
if ((((times1.elementAt(j))).intValue()) != (((times2.elementAt(j))).intValue())) {
identical = false;
}
}
}
- CMS.debug("areTimeListsIdentical: identical: "+identical);
+ CMS.debug("areTimeListsIdentical: identical: " + identical);
return identical;
}
@@ -533,23 +537,25 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
int listSize = 0;
for (int i = 0; listedDays != null && i < listedDays.size(); i++) {
Vector<Integer> listedTimes = listedDays.elementAt(i);
- listSize += ((listedTimes != null)? listedTimes.size(): 0);
+ listSize += ((listedTimes != null) ? listedTimes.size() : 0);
}
- CMS.debug("getTimeListSize: ListSize="+listSize);
+ CMS.debug("getTimeListSize: ListSize=" + listSize);
return listSize;
}
private boolean isTimeListExtended(String list) {
- boolean extendedTimeList = true;
- if (list == null || list.indexOf('*') == -1)
- extendedTimeList = false;
- return extendedTimeList;
+ boolean extendedTimeList = true;
+ if (list == null || list.indexOf('*') == -1)
+ extendedTimeList = false;
+ return extendedTimeList;
}
private Vector<Vector<Integer>> getTimeList(String list) {
boolean timeListPresent = false;
- if (list == null || list.length() == 0) return null;
- if (list.charAt(0) == ',' || list.charAt(list.length()-1) == ',') return null;
+ if (list == null || list.length() == 0)
+ return null;
+ if (list.charAt(0) == ',' || list.charAt(list.length() - 1) == ',')
+ return null;
Vector<Vector<Integer>> listedDays = new Vector<Vector<Integer>>();
@@ -557,7 +563,8 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
Vector<Integer> listedTimes = null;
while (days.hasMoreTokens()) {
String dayList = days.nextToken().trim();
- if (dayList == null) continue;
+ if (dayList == null)
+ continue;
if (dayList.equals(";")) {
if (timeListPresent) {
@@ -586,7 +593,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
return null;
} else {
if (t > t0) {
- listedTimes.addElement(new Integer(k*t));
+ listedTimes.addElement(new Integer(k * t));
t0 = t;
} else {
return null;
@@ -596,7 +603,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
}
if (!timeListPresent) {
listedTimes = new Vector<Integer>();
- listedDays.addElement(listedTimes);
+ listedDays.addElement(listedTimes);
}
return listedDays;
@@ -605,7 +612,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
private String checkProfile(String id, Enumeration<String> e) {
if (e != null) {
while (e.hasMoreElements()) {
- String profileId = e.nextElement();
+ String profileId = e.nextElement();
if (profileId != null && profileId.equalsIgnoreCase(id))
return id;
}
@@ -616,9 +623,12 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
private Vector<String> getProfileList(String list) {
Enumeration<String> e = null;
IConfigStore pc = CMS.getConfigStore().getSubStore("profile");
- if (pc != null) e = pc.getSubStoreNames();
- if (list == null) return null;
- if (list.length() > 0 && list.charAt(list.length()-1) == ',') return null;
+ if (pc != null)
+ e = pc.getSubStoreNames();
+ if (list == null)
+ return null;
+ if (list.length() > 0 && list.charAt(list.length() - 1) == ',')
+ return null;
Vector<String> listedProfiles = new Vector<String>();
@@ -627,8 +637,10 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
int n = 0;
while (elements.hasMoreTokens()) {
String element = elements.nextToken().trim();
- if (element == null || element.length() == 0) return null;
- if (element.equals(",") && n % 2 == 0) return null;
+ if (element == null || element.length() == 0)
+ return null;
+ if (element.equals(",") && n % 2 == 0)
+ return null;
if (n % 2 == 0) {
String id = checkProfile(element, e);
if (id != null) {
@@ -637,17 +649,17 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
}
n++;
}
- if (n % 2 == 0) return null;
+ if (n % 2 == 0)
+ return null;
return listedProfiles;
}
-
/**
* get CRL config store info
*/
protected void initConfig(IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mEnable = config.getBoolean(Constants.PR_ENABLE, true);
mDescription = config.getString(Constants.PR_DESCRIPTION);
@@ -684,13 +696,13 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
mAutoUpdateInterval = MINUTE * config.getInteger(Constants.PR_UPDATE_FREQ, 0);
mMinUpdateInterval = MINUTE * config.getInteger(PROP_MIN_UPDATE_INTERVAL, 0);
if (mEnableUpdateFreq && mAutoUpdateInterval > 0 &&
- mAutoUpdateInterval < mMinUpdateInterval)
+ mAutoUpdateInterval < mMinUpdateInterval)
mAutoUpdateInterval = mMinUpdateInterval;
- // get next update grace period
+ // get next update grace period
mNextUpdateGracePeriod = MINUTE * config.getInteger(Constants.PR_GRACE_PERIOD, 0);
- // Get V2 or V1 CRL
+ // Get V2 or V1 CRL
mAllowExtensions = config.getBoolean(Constants.PR_EXTENSIONS, false);
mIncludeExpiredCerts = config.getBoolean(Constants.PR_INCLUDE_EXPIREDCERTS, false);
@@ -708,13 +720,13 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
String algorithm = config.getString(Constants.PR_SIGNING_ALGORITHM, null);
if (algorithm != null) {
- // make sure this algorithm is acceptable to CA.
+ // make sure this algorithm is acceptable to CA.
mCA.getCRLSigningUnit().checkSigningAlgorithmFromName(algorithm);
mSigningAlgorithm = algorithm;
}
mPublishOnStart = config.getBoolean(PROP_PUBLISH_ON_START, false);
- // if publish dn is null then certificate will be published to
+ // if publish dn is null then certificate will be published to
// CA's entry in the directory.
mPublishDN = config.getString(PROP_PUBLISH_DN, null);
@@ -722,30 +734,29 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
mCMSCRLExtensions = new CMSCRLExtensions(this, config);
- mExtendedNextUpdate = ((mUpdateSchema > 1 || (mEnableDailyUpdates && mExtendedTimeList)) && isDeltaCRLEnabled())?
- config.getBoolean(Constants.PR_EXTENDED_NEXT_UPDATE, true):
+ mExtendedNextUpdate = ((mUpdateSchema > 1 || (mEnableDailyUpdates && mExtendedTimeList)) && isDeltaCRLEnabled()) ?
+ config.getBoolean(Constants.PR_EXTENDED_NEXT_UPDATE, true) :
false;
// Get serial number ranges if any.
mBeginSerial = config.getBigInteger(PROP_BEGIN_SERIAL, null);
if (mBeginSerial != null && mBeginSerial.compareTo(BigInteger.ZERO) < 0) {
throw new EBaseException(
- CMS.getUserMessage("CMS_BASE_INVALID_PROPERTY_1",
- PROP_BEGIN_SERIAL, "BigInteger", "positive number"));
+ CMS.getUserMessage("CMS_BASE_INVALID_PROPERTY_1",
+ PROP_BEGIN_SERIAL, "BigInteger", "positive number"));
}
mEndSerial = config.getBigInteger(PROP_END_SERIAL, null);
if (mEndSerial != null && mEndSerial.compareTo(BigInteger.ZERO) < 0) {
throw new EBaseException(
- CMS.getUserMessage("CMS_BASE_INVALID_PROPERTY_1",
- PROP_END_SERIAL, "BigInteger", "positive number"));
+ CMS.getUserMessage("CMS_BASE_INVALID_PROPERTY_1",
+ PROP_END_SERIAL, "BigInteger", "positive number"));
}
}
/**
- * Reads CRL issuing point, if missing, it creates one.
- * Initializes CRL cache and republishes CRL if requested
- * Called from auto update thread (run()).
- * Do not call it from init(), because it will block CMS on start.
+ * Reads CRL issuing point, if missing, it creates one. Initializes CRL
+ * cache and republishes CRL if requested Called from auto update thread
+ * (run()). Do not call it from init(), because it will block CMS on start.
*/
private void initCRL() {
ICRLIssuingPointRecord crlRecord = null;
@@ -760,7 +771,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
return;
} catch (EBaseException e) {
// CRL was never set.
- // fall to the following..
+ // fall to the following..
}
if (crlRecord != null) {
@@ -800,16 +811,16 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
mNextUpdate = crlRecord.getNextUpdate();
if (isDeltaCRLEnabled()) {
- mNextDeltaUpdate = (mNextUpdate != null)? new Date(mNextUpdate.getTime()): null;
+ mNextDeltaUpdate = (mNextUpdate != null) ? new Date(mNextUpdate.getTime()) : null;
}
mFirstUnsaved = crlRecord.getFirstUnsaved();
if (Debug.on()) {
- Debug.trace("initCRL CRLNumber="+mCRLNumber.toString()+" CRLSize="+mCRLSize+
- " FirstUnsaved="+mFirstUnsaved);
+ Debug.trace("initCRL CRLNumber=" + mCRLNumber.toString() + " CRLSize=" + mCRLSize +
+ " FirstUnsaved=" + mFirstUnsaved);
}
if (mFirstUnsaved == null ||
- (mFirstUnsaved != null && mFirstUnsaved.equals(ICRLIssuingPointRecord.NEW_CACHE))) {
+ (mFirstUnsaved != null && mFirstUnsaved.equals(ICRLIssuingPointRecord.NEW_CACHE))) {
clearCRLCache();
updateCRLCacheRepository();
} else {
@@ -877,24 +888,25 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
}
if (crlRecord == null) {
- // no crl was ever created, or crl in db is corrupted.
+ // no crl was ever created, or crl in db is corrupted.
// create new one.
try {
crlRecord = new CRLIssuingPointRecord(mId, BigInteger.ZERO, Long.valueOf(-1),
null, null, BigInteger.ZERO, Long.valueOf(-1),
mRevokedCerts, mUnrevokedCerts, mExpiredCerts);
mCRLRepository.addCRLIssuingPointRecord(crlRecord);
- mCRLNumber = BigInteger.ZERO; //BIG_ZERO;
- mNextCRLNumber = BigInteger.ONE; //BIG_ONE;
+ mCRLNumber = BigInteger.ZERO; // BIG_ZERO;
+ mNextCRLNumber = BigInteger.ONE; // BIG_ONE;
mLastCRLNumber = mCRLNumber;
mDeltaCRLNumber = mCRLNumber;
mNextDeltaCRLNumber = mNextCRLNumber;
mLastUpdate = new Date(0L);
if (crlRecord != null) {
- // This will trigger updateCRLNow, which will also publish CRL.
+ // This will trigger updateCRLNow, which will also publish
+ // CRL.
if ((mDoManualUpdate == false) &&
- (mEnableCRLCache || mAlwaysUpdate ||
- (mEnableUpdateFreq && mAutoUpdateInterval > 0))) {
+ (mEnableCRLCache || mAlwaysUpdate ||
+ (mEnableUpdateFreq && mAutoUpdateInterval > 0))) {
mInitialized = CRL_IP_INITIALIZED;
setManualUpdate(null);
}
@@ -919,7 +931,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
NameValuePair p = params.elementAt(i);
String name = p.getName();
String value = p.getValue();
-
+
// -- Update Schema --
if (name.equals(Constants.PR_ENABLE_CRL)) {
if (value.equals(Constants.FALSE) && mEnableCRLUpdates) {
@@ -1082,7 +1094,8 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
// -- CRL Format --
if (name.equals(Constants.PR_SIGNING_ALGORITHM)) {
- if (value != null) value = value.trim();
+ if (value != null)
+ value = value.trim();
if (!mSigningAlgorithm.equals(value)) {
mSigningAlgorithm = value;
}
@@ -1123,9 +1136,9 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
if (name.equals(Constants.PR_CA_CERTS_ONLY)) {
Extension distExt = getCRLExtension(IssuingDistributionPointExtension.class.getSimpleName());
IssuingDistributionPointExtension iExt = (IssuingDistributionPointExtension) distExt;
- IssuingDistributionPoint issuingDistributionPoint = null;
- if(iExt != null)
- issuingDistributionPoint = iExt.getIssuingDistributionPoint();
+ IssuingDistributionPoint issuingDistributionPoint = null;
+ if (iExt != null)
+ issuingDistributionPoint = iExt.getIssuingDistributionPoint();
if (value.equals(Constants.FALSE) && mCACertsOnly) {
clearCRLCache();
updateCRLCacheRepository();
@@ -1135,27 +1148,28 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
updateCRLCacheRepository();
mCACertsOnly = true;
}
- //attempt to sync the IssuingDistributionPoint Extension value of
- //onlyContainsCACerts
- if(issuingDistributionPoint != null && params.size() > 1) {
+ // attempt to sync the IssuingDistributionPoint Extension
+ // value of
+ // onlyContainsCACerts
+ if (issuingDistributionPoint != null && params.size() > 1) {
boolean onlyContainsCACerts = issuingDistributionPoint.getOnlyContainsCACerts();
- if(onlyContainsCACerts != mCACertsOnly) {
+ if (onlyContainsCACerts != mCACertsOnly) {
IConfigStore config = mCA.getConfigStore();
IConfigStore crlsSubStore =
- config.getSubStore(ICertificateAuthority.PROP_CRL_SUBSTORE);
+ config.getSubStore(ICertificateAuthority.PROP_CRL_SUBSTORE);
IConfigStore crlSubStore = crlsSubStore.getSubStore(mId);
IConfigStore crlExtsSubStore =
- crlSubStore.getSubStore(ICertificateAuthority.PROP_CRLEXT_SUBSTORE);
+ crlSubStore.getSubStore(ICertificateAuthority.PROP_CRLEXT_SUBSTORE);
crlExtsSubStore = crlExtsSubStore.getSubStore(IssuingDistributionPointExtension.class.getSimpleName());
- if(crlExtsSubStore != null) {
+ if (crlExtsSubStore != null) {
String val = "";
- if(mCACertsOnly == true) {
+ if (mCACertsOnly == true) {
val = Constants.TRUE;
} else {
val = Constants.FALSE;
}
- crlExtsSubStore.putString(PROP_CACERTS,val);
+ crlExtsSubStore.putString(PROP_CACERTS, val);
try {
crlExtsSubStore.commit(true);
} catch (Exception e) {
@@ -1180,11 +1194,11 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
if (name.equals(Constants.PR_PROFILE_LIST)) {
Vector<String> profileList = getProfileList(value);
if (((profileList != null) ^ (mProfileList != null)) ||
- (profileList != null && mProfileList != null &&
- (!mProfileList.equals(profileList)))) {
+ (profileList != null && mProfileList != null &&
+ (!mProfileList.equals(profileList)))) {
if (profileList != null) {
@SuppressWarnings("unchecked")
- Vector<String> newProfileList = (Vector<String>) profileList.clone();
+ Vector<String> newProfileList = (Vector<String>) profileList.clone();
mProfileList = newProfileList;
} else {
mProfileList = null;
@@ -1199,7 +1213,8 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
}
}
- if (modifiedSchedule) setAutoUpdates();
+ if (modifiedSchedule)
+ setAutoUpdates();
return noRestart;
}
@@ -1218,20 +1233,15 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
setAutoUpdates();
/*
- if (mUpdateThread != null) {
- try {
- mUpdateThread.interrupt();
- }
- catch (Exception e) {
- }
- }
- */
+ * if (mUpdateThread != null) { try { mUpdateThread.interrupt(); } catch
+ * (Exception e) { } }
+ */
}
/**
* Returns internal id of this CRL issuing point.
* <P>
- *
+ *
* @return internal id of this CRL issuing point
*/
public String getId() {
@@ -1241,7 +1251,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
/**
* Returns internal description of this CRL issuing point.
* <P>
- *
+ *
* @return internal description of this CRL issuing point
*/
public String getDescription() {
@@ -1250,7 +1260,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
/**
* Sets internal description of this CRL issuing point.
- *
+ *
* @param description description for this CRL issuing point.
*/
public void setDescription(String description) {
@@ -1258,10 +1268,10 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
}
/**
- * Returns DN of the directory entry where CRLs.from this issuing point
- * are published.
+ * Returns DN of the directory entry where CRLs.from this issuing point are
+ * published.
* <P>
- *
+ *
* @return DN of the directory entry where CRLs are published.
*/
public String getPublishDN() {
@@ -1271,7 +1281,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
/**
* Returns signing algorithm.
* <P>
- *
+ *
* @return SigningAlgorithm.
*/
public String getSigningAlgorithm() {
@@ -1285,7 +1295,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
/**
* Returns current CRL generation schema for this CRL issuing point.
* <P>
- *
+ *
* @return current CRL generation schema for this CRL issuing point
*/
public int getCRLSchema() {
@@ -1295,7 +1305,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
/**
* Returns current CRL number of this CRL issuing point.
* <P>
- *
+ *
* @return current CRL number of this CRL issuing point
*/
public BigInteger getCRLNumber() {
@@ -1305,17 +1315,17 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
/**
* Returns current delta CRL number of this CRL issuing point.
* <P>
- *
+ *
* @return current delta CRL number of this CRL issuing point
*/
public BigInteger getDeltaCRLNumber() {
- return (isDeltaCRLEnabled() && mDeltaCRLSize > -1)? mDeltaCRLNumber: BigInteger.ZERO;
+ return (isDeltaCRLEnabled() && mDeltaCRLSize > -1) ? mDeltaCRLNumber : BigInteger.ZERO;
}
/**
* Returns next CRL number of this CRL issuing point.
* <P>
- *
+ *
* @return next CRL number of this CRL issuing point
*/
public BigInteger getNextCRLNumber() {
@@ -1325,17 +1335,17 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
/**
* Returns number of entries in the CRL
* <P>
- *
+ *
* @return number of entries in the CRL
*/
public long getCRLSize() {
- return (mCRLCerts.size() > 0 && mCRLSize == 0)? mCRLCerts.size(): mCRLSize;
+ return (mCRLCerts.size() > 0 && mCRLSize == 0) ? mCRLCerts.size() : mCRLSize;
}
/**
* Returns number of entries in delta CRL
* <P>
- *
+ *
* @return number of entries in delta CRL
*/
public long getDeltaCRLSize() {
@@ -1345,7 +1355,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
/**
* Returns last update time
* <P>
- *
+ *
* @return last CRL update time
*/
public Date getLastUpdate() {
@@ -1355,7 +1365,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
/**
* Returns next update time
* <P>
- *
+ *
* @return next CRL update time
*/
public Date getNextUpdate() {
@@ -1365,7 +1375,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
/**
* Returns next update time
* <P>
- *
+ *
* @return next CRL update time
*/
public Date getNextDeltaUpdate() {
@@ -1375,7 +1385,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
/**
* Returns all the revoked certificates from the CRL cache.
* <P>
- *
+ *
* @return set of all the revoked certificates or null if there are none.
*/
public Set<RevokedCertificate> getRevokedCertificates(int start, int end) {
@@ -1390,7 +1400,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
/**
* Returns certificate authority.
* <P>
- *
+ *
* @return certificate authority
*/
public ISubsystem getCertificateAuthority() {
@@ -1403,13 +1413,13 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
private synchronized void setAutoUpdates() {
if ((mEnable && mUpdateThread == null) &&
- ((mEnableCRLCache && mCacheUpdateInterval > 0) ||
- (mEnableCRLUpdates &&
- ((mEnableDailyUpdates && mDailyUpdates != null &&
- mTimeListSize > 0) ||
- (mEnableUpdateFreq && mAutoUpdateInterval > 0) ||
- (mInitialized == CRL_IP_NOT_INITIALIZED) ||
- mDoLastAutoUpdate || mDoManualUpdate)))) {
+ ((mEnableCRLCache && mCacheUpdateInterval > 0) ||
+ (mEnableCRLUpdates &&
+ ((mEnableDailyUpdates && mDailyUpdates != null &&
+ mTimeListSize > 0) ||
+ (mEnableUpdateFreq && mAutoUpdateInterval > 0) ||
+ (mInitialized == CRL_IP_NOT_INITIALIZED) ||
+ mDoLastAutoUpdate || mDoManualUpdate)))) {
mUpdateThread = new Thread(this, "CRLIssuingPoint-" + mId);
log(ILogger.LL_INFO, CMS.getLogMessage("CMSCORE_CA_ISSUING_START_CRL", mId));
mUpdateThread.setDaemon(true);
@@ -1417,14 +1427,14 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
}
if ((mInitialized == CRL_IP_INITIALIZED) && (((mNextUpdate != null) ^
- ((mEnableDailyUpdates && mDailyUpdates != null && mTimeListSize > 0) ||
- (mEnableUpdateFreq && mAutoUpdateInterval > 0))) ||
- (!mEnableCRLUpdates && mNextUpdate != null))) {
- mDoLastAutoUpdate = true;
+ ((mEnableDailyUpdates && mDailyUpdates != null && mTimeListSize > 0) ||
+ (mEnableUpdateFreq && mAutoUpdateInterval > 0))) ||
+ (!mEnableCRLUpdates && mNextUpdate != null))) {
+ mDoLastAutoUpdate = true;
}
if (mEnableUpdateFreq && mAutoUpdateInterval > 0 &&
- mAutoUpdateInterval < mMinUpdateInterval) {
+ mAutoUpdateInterval < mMinUpdateInterval) {
mAutoUpdateInterval = mMinUpdateInterval;
}
@@ -1432,8 +1442,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
}
/**
- * Sets CRL manual-update
- * Starts or stops worker thread as necessary.
+ * Sets CRL manual-update Starts or stops worker thread as necessary.
*/
public synchronized void setManualUpdate(String signatureAlgorithm) {
if (!mDoManualUpdate) {
@@ -1451,13 +1460,13 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
* @return auto update interval in milliseconds.
*/
public long getAutoUpdateInterval() {
- return (mEnableUpdateFreq)? mAutoUpdateInterval: 0;
+ return (mEnableUpdateFreq) ? mAutoUpdateInterval : 0;
}
/**
- * @return always update the CRL
+ * @return always update the CRL
*/
- public boolean getAlwaysUpdate() {
+ public boolean getAlwaysUpdate() {
return mAlwaysUpdate;
}
@@ -1471,11 +1480,11 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
/**
* Finds next update time expressed as delay or time of the next update.
- *
- * @param fromLastUpdate if true, function returns delay to the next update time
- * otherwise returns the next update time.
- * @param delta if true, function returns the next update time for delta CRL,
- * otherwise returns the next update time for CRL.
+ *
+ * @param fromLastUpdate if true, function returns delay to the next update
+ * time otherwise returns the next update time.
+ * @param delta if true, function returns the next update time for delta
+ * CRL, otherwise returns the next update time for CRL.
* @return delay to the next update time or the next update time itself
*/
private long findNextUpdate(boolean fromLastUpdate, boolean delta) {
@@ -1483,52 +1492,53 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
TimeZone tz = TimeZone.getDefault();
int offset = tz.getOffset(now);
long oneDay = 1440L * MINUTE;
- long nowToday = (now + (long)offset) % oneDay;
+ long nowToday = (now + (long) offset) % oneDay;
long startOfToday = now - nowToday;
- long lastUpdated = (mLastUpdate != null)? mLastUpdate.getTime(): now;
- long lastUpdateDay = lastUpdated - ((lastUpdated + (long)offset) % oneDay);
+ long lastUpdated = (mLastUpdate != null) ? mLastUpdate.getTime() : now;
+ long lastUpdateDay = lastUpdated - ((lastUpdated + (long) offset) % oneDay);
- long lastUpdate = (mLastUpdate != null && fromLastUpdate)? mLastUpdate.getTime(): now;
- long last = (lastUpdate + (long)offset) % oneDay;
+ long lastUpdate = (mLastUpdate != null && fromLastUpdate) ? mLastUpdate.getTime() : now;
+ long last = (lastUpdate + (long) offset) % oneDay;
long lastDay = lastUpdate - last;
boolean isDeltaEnabled = isDeltaCRLEnabled();
long next = 0L;
long nextUpdate = 0L;
- CMS.debug("findNextUpdate: fromLastUpdate: "+fromLastUpdate+" delta: "+delta);
+ CMS.debug("findNextUpdate: fromLastUpdate: " + fromLastUpdate + " delta: " + delta);
- int numberOfDays = (int)((startOfToday - lastUpdateDay) / oneDay);
+ int numberOfDays = (int) ((startOfToday - lastUpdateDay) / oneDay);
if (numberOfDays > 0 && mDailyUpdates.size() > 1 &&
- ((mCurrentDay == mLastDay) ||
- (mCurrentDay != ((mLastDay + numberOfDays) % mDailyUpdates.size())))) {
+ ((mCurrentDay == mLastDay) ||
+ (mCurrentDay != ((mLastDay + numberOfDays) % mDailyUpdates.size())))) {
mCurrentDay = (mLastDay + numberOfDays) % mDailyUpdates.size();
}
if ((delta || fromLastUpdate) && isDeltaEnabled &&
- (mUpdateSchema > 1 || (mEnableDailyUpdates && mExtendedTimeList)) &&
- mNextDeltaUpdate != null) {
+ (mUpdateSchema > 1 || (mEnableDailyUpdates && mExtendedTimeList)) &&
+ mNextDeltaUpdate != null) {
nextUpdate = mNextDeltaUpdate.getTime();
} else if (mNextUpdate != null) {
nextUpdate = mNextUpdate.getTime();
}
if (mEnableDailyUpdates &&
- mDailyUpdates != null && mDailyUpdates.size() > 0) {
+ mDailyUpdates != null && mDailyUpdates.size() > 0) {
int n = 0;
if (mDailyUpdates.size() == 1 && mDailyUpdates.elementAt(0).size() == 1 &&
- mEnableUpdateFreq && mAutoUpdateInterval > 0) {
+ mEnableUpdateFreq && mAutoUpdateInterval > 0) {
// Interval updates with starting time
- long firstTime = MINUTE * ((Integer)mDailyUpdates.elementAt(0).elementAt(0)).longValue();
+ long firstTime = MINUTE * ((Integer) mDailyUpdates.elementAt(0).elementAt(0)).longValue();
long t = firstTime;
long interval = mAutoUpdateInterval;
if (mExtendedNextUpdate && (!fromLastUpdate) && (!delta) &&
- isDeltaEnabled && mUpdateSchema > 1) {
+ isDeltaEnabled && mUpdateSchema > 1) {
interval *= mUpdateSchema;
}
- while (t < oneDay) {
- if (t - mMinUpdateInterval > last) break;
+ while (t < oneDay) {
+ if (t - mMinUpdateInterval > last)
+ break;
t += interval;
n++;
}
@@ -1562,7 +1572,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
}
// search the current day
for (i = 0; i < mDailyUpdates.elementAt(mCurrentDay).size(); i++) {
- long t = MINUTE * ((Integer)mDailyUpdates.elementAt(mCurrentDay).elementAt(i)).longValue();
+ long t = MINUTE * ((Integer) mDailyUpdates.elementAt(mCurrentDay).elementAt(i)).longValue();
if (mEnableDailyUpdates && mExtendedTimeList) {
if (mExtendedNextUpdate && (!fromLastUpdate) && (!delta) && isDeltaEnabled) {
if (t < 0) {
@@ -1578,7 +1588,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
}
if (t - mMinUpdateInterval > last) {
if (mExtendedNextUpdate && (!fromLastUpdate) && (!(mEnableDailyUpdates && mExtendedTimeList)) && (!delta) &&
- isDeltaEnabled && mUpdateSchema > 1) {
+ isDeltaEnabled && mUpdateSchema > 1) {
i += mUpdateSchema - ((i + m) % mUpdateSchema);
}
break;
@@ -1588,14 +1598,14 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
if (i < mDailyUpdates.elementAt(mCurrentDay).size()) {
// found inside the current day
- next = (MINUTE * ((Integer)mDailyUpdates.elementAt(mCurrentDay).elementAt(i)).longValue());
+ next = (MINUTE * ((Integer) mDailyUpdates.elementAt(mCurrentDay).elementAt(i)).longValue());
if (mEnableDailyUpdates && mExtendedTimeList && next < 0) {
next *= -1;
if (fromLastUpdate) {
mSchemaCounter = 0;
}
}
- next += ((lastDay < lastUpdateDay)? lastDay: lastUpdateDay) + (oneDay * (mCurrentDay - mLastDay));
+ next += ((lastDay < lastUpdateDay) ? lastDay : lastUpdateDay) + (oneDay * (mCurrentDay - mLastDay));
if (fromLastUpdate && (!(mEnableDailyUpdates && mExtendedTimeList))) {
n = n % mUpdateSchema;
@@ -1616,8 +1626,9 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
while (nDays <= mDailyUpdates.size()) {
int nextDay = (mCurrentDay + nDays) % mDailyUpdates.size();
if (j < mDailyUpdates.elementAt(nextDay).size()) {
- if (nextDay == 0 && (!(mEnableDailyUpdates && mExtendedTimeList))) j = 0;
- t = MINUTE * ((Integer)mDailyUpdates.elementAt(nextDay).elementAt(j)).longValue();
+ if (nextDay == 0 && (!(mEnableDailyUpdates && mExtendedTimeList)))
+ j = 0;
+ t = MINUTE * ((Integer) mDailyUpdates.elementAt(nextDay).elementAt(j)).longValue();
if (mEnableDailyUpdates && mExtendedTimeList) {
if (mExtendedNextUpdate && (!fromLastUpdate) && (!delta) && isDeltaEnabled) {
if (t < 0) {
@@ -1642,7 +1653,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
nDays++;
}
}
- next = ((lastDay < lastUpdateDay)? lastDay: lastUpdateDay) + (oneDay * nDays) + t;
+ next = ((lastDay < lastUpdateDay) ? lastDay : lastUpdateDay) + (oneDay * nDays) + t;
if (fromLastUpdate && mDailyUpdates.size() < 2) {
mSchemaCounter = 0;
@@ -1651,7 +1662,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
}
} else if (mEnableUpdateFreq && mAutoUpdateInterval > 0) {
// Interval updates without starting time
- if (mExtendedNextUpdate && (!fromLastUpdate) && (!delta) && isDeltaEnabled && mUpdateSchema > 1) {
+ if (mExtendedNextUpdate && (!fromLastUpdate) && (!delta) && isDeltaEnabled && mUpdateSchema > 1) {
next = lastUpdate + (mUpdateSchema * mAutoUpdateInterval);
} else {
next = lastUpdate + mAutoUpdateInterval;
@@ -1662,15 +1673,14 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
next = nextUpdate;
}
- CMS.debug("findNextUpdate: "+((new Date(next)).toString())+((fromLastUpdate)? " delay: "+(next-now): ""));
+ CMS.debug("findNextUpdate: " + ((new Date(next)).toString()) + ((fromLastUpdate) ? " delay: " + (next - now) : ""));
- return (fromLastUpdate)? next-now: next;
+ return (fromLastUpdate) ? next - now : next;
}
-
/**
- * Implements Runnable interface. Defines auto-update
- * logic used by worker thread.
+ * Implements Runnable interface. Defines auto-update logic used by worker
+ * thread.
* <P>
*/
public void run() {
@@ -1678,8 +1688,8 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
(mInitialized == CRL_IP_NOT_INITIALIZED) ||
mDoLastAutoUpdate || (mEnableCRLUpdates &&
((mEnableDailyUpdates && mDailyUpdates != null &&
- mTimeListSize > 0) ||
- (mEnableUpdateFreq && mAutoUpdateInterval > 0) ||
+ mTimeListSize > 0) ||
+ (mEnableUpdateFreq && mAutoUpdateInterval > 0) ||
mDoManualUpdate)))) {
synchronized (this) {
@@ -1687,13 +1697,14 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
long delay2 = 0;
boolean doCacheUpdate = false;
boolean scheduledUpdates = mEnableCRLUpdates &&
- ((mEnableDailyUpdates && mDailyUpdates != null &&
- mTimeListSize > 0) ||
- (mEnableUpdateFreq && mAutoUpdateInterval > 0));
+ ((mEnableDailyUpdates && mDailyUpdates != null &&
+ mTimeListSize > 0) ||
+ (mEnableUpdateFreq && mAutoUpdateInterval > 0));
if (mInitialized == CRL_IP_NOT_INITIALIZED)
initCRL();
- if (mInitialized == CRL_IP_INITIALIZED && (!mEnable)) break;
+ if (mInitialized == CRL_IP_INITIALIZED && (!mEnable))
+ break;
if ((mEnableCRLUpdates && mDoManualUpdate) || mDoLastAutoUpdate) {
delay = 0;
@@ -1705,8 +1716,8 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
delay2 = mLastCacheUpdate + mCacheUpdateInterval -
System.currentTimeMillis();
if (delay2 < delay ||
- (!(scheduledUpdates || mDoLastAutoUpdate ||
- (mEnableCRLUpdates && mDoManualUpdate)))) {
+ (!(scheduledUpdates || mDoLastAutoUpdate ||
+ (mEnableCRLUpdates && mDoManualUpdate)))) {
delay = delay2;
if (delay <= 0) {
doCacheUpdate = true;
@@ -1716,7 +1727,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
}
if (delay > 0) {
- try {
+ try {
wait(delay);
} catch (InterruptedException e) {
}
@@ -1729,13 +1740,13 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
}
} catch (Exception e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_ISSUING_CRL",
- (doCacheUpdate)?"update CRL cache":"update CRL", e.toString()));
+ (doCacheUpdate) ? "update CRL cache" : "update CRL", e.toString()));
if (Debug.on()) {
- Debug.trace((doCacheUpdate)?"update CRL cache":"update CRL" + " error " + e);
+ Debug.trace((doCacheUpdate) ? "update CRL cache" : "update CRL" + " error " + e);
Debug.printStackTrace(e);
}
}
- // put this here to prevent continuous loop if internal
+ // put this here to prevent continuous loop if internal
// db is down.
if (mDoLastAutoUpdate)
mDoLastAutoUpdate = false;
@@ -1749,28 +1760,23 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
mUpdateThread = null;
}
-
/**
- * Updates CRL and publishes it.
- * If time elapsed since last CRL update is less than
- * minUpdateInterval silently returns.
- * Otherwise determines nextUpdate by adding autoUpdateInterval or
- * minUpdateInterval to the current time. If neither of the
- * intervals are defined nextUpdate will be null.
- * Then using specified configuration parameters it formulates new
- * CRL, signs it, updates CRLIssuingPointRecord in the database
- * and publishes CRL in the directory.
+ * Updates CRL and publishes it. If time elapsed since last CRL update is
+ * less than minUpdateInterval silently returns. Otherwise determines
+ * nextUpdate by adding autoUpdateInterval or minUpdateInterval to the
+ * current time. If neither of the intervals are defined nextUpdate will be
+ * null. Then using specified configuration parameters it formulates new
+ * CRL, signs it, updates CRLIssuingPointRecord in the database and
+ * publishes CRL in the directory.
* <P>
*/
private void updateCRL() throws EBaseException {
/*
- if (mEnableUpdateFreq && mAutoUpdateInterval > 0 &&
- (System.currentTimeMillis() - mLastUpdate.getTime() <
- mMinUpdateInterval)) {
- // log or alternatively throw an Exception
- return;
- }
- */
+ * if (mEnableUpdateFreq && mAutoUpdateInterval > 0 &&
+ * (System.currentTimeMillis() - mLastUpdate.getTime() <
+ * mMinUpdateInterval)) { // log or alternatively throw an Exception
+ * return; }
+ */
if (mDoManualUpdate && mSignatureAlgorithmForManualUpdate != null) {
updateCRLNow(mSignatureAlgorithmForManualUpdate);
} else {
@@ -1820,7 +1826,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
// get all revoked non-expired certs.
if (mEndSerial != null || mBeginSerial != null || mCACertsOnly ||
- (mProfileCertsOnly && mProfileList != null && mProfileList.size() > 0)) {
+ (mProfileCertsOnly && mProfileList != null && mProfileList.size() > 0)) {
filter = "(&" + filter + ")";
}
@@ -1828,27 +1834,27 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
}
/**
- * Gets a enumeration of revoked certs to put into CRL.
- * This does not include expired certs.
- * <i>Override this method to make a CRL other than the
- * full/complete CRL.</i>
- * @return Enumeration of CertRecords to put into CRL.
+ * Gets a enumeration of revoked certs to put into CRL. This does not
+ * include expired certs. <i>Override this method to make a CRL other than
+ * the full/complete CRL.</i>
+ *
+ * @return Enumeration of CertRecords to put into CRL.
* @exception EBaseException if an error occured in the database.
*/
public void processRevokedCerts(IElementProcessor p)
- throws EBaseException {
+ throws EBaseException {
CertRecProcessor cp = (CertRecProcessor) p;
String filter = getFilter();
- // NOTE: dangerous cast.
+ // NOTE: dangerous cast.
// correct way would be to modify interface and add
// accessor but we don't want to touch the interface
- CertificateRepository cr = (CertificateRepository)mCertRepository;
+ CertificateRepository cr = (CertificateRepository) mCertRepository;
synchronized (cr.mCertStatusUpdateThread) {
CMS.debug("Starting processRevokedCerts (entered lock)");
ICertRecordList list = mCertRepository.findCertRecordsInList(filter,
- new String[] {ICertRecord.ATTR_ID, ICertRecord.ATTR_REVO_INFO, "objectclass" },
+ new String[] { ICertRecord.ATTR_ID, ICertRecord.ATTR_REVO_INFO, "objectclass" },
"serialno",
mPageSize);
@@ -1888,18 +1894,18 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
if (mEnableCacheRecovery) {
// 553815 - original filter was not aligned with any VLV index
// String filter = "(&(requeststate=complete)"+
- // "(|(requestType=" + IRequest.REVOCATION_REQUEST + ")"+
- // "(requestType=" + IRequest.UNREVOCATION_REQUEST + ")))";
+ // "(|(requestType=" + IRequest.REVOCATION_REQUEST + ")"+
+ // "(requestType=" + IRequest.UNREVOCATION_REQUEST + ")))";
String filter = "(requeststate=complete)";
if (Debug.on()) {
- Debug.trace("recoverCRLCache mFirstUnsaved="+mFirstUnsaved+" filter="+filter);
+ Debug.trace("recoverCRLCache mFirstUnsaved=" + mFirstUnsaved + " filter=" + filter);
}
IRequestQueue mQueue = mCA.getRequestQueue();
IRequestVirtualList list = mQueue.getPagedRequestsByFilter(
new RequestId(mFirstUnsaved), filter, 500, "requestId");
if (Debug.on()) {
- Debug.trace("recoverCRLCache size="+list.getSize()+" index="+list.getCurrentIndex());
+ Debug.trace("recoverCRLCache size=" + list.getSize() + " index=" + list.getCurrentIndex());
}
CertRecProcessor cp = new CertRecProcessor(mCRLCerts, this, mLogger, mAllowExtensions);
@@ -1917,20 +1923,20 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
continue;
}
if (Debug.on()) {
- Debug.trace("recoverCRLCache request="+request.getRequestId().toString()+
- " type="+request.getRequestType());
+ Debug.trace("recoverCRLCache request=" + request.getRequestId().toString() +
+ " type=" + request.getRequestType());
}
if (IRequest.REVOCATION_REQUEST.equals(request.getRequestType())) {
RevokedCertImpl revokedCert[] =
- request.getExtDataInRevokedCertArray(IRequest.CERT_INFO);
+ request.getExtDataInRevokedCertArray(IRequest.CERT_INFO);
for (int j = 0; j < revokedCert.length; j++) {
if (Debug.on()) {
- Debug.trace("recoverCRLCache R j="+j+" length="+revokedCert.length+
- " SerialNumber=0x"+revokedCert[j].getSerialNumber().toString(16));
+ Debug.trace("recoverCRLCache R j=" + j + " length=" + revokedCert.length +
+ " SerialNumber=0x" + revokedCert[j].getSerialNumber().toString(16));
}
- if(cp != null)
- includeCert = cp.checkRevokedCertExtensions(revokedCert[j].getExtensions());
- if(includeCert) {
+ if (cp != null)
+ includeCert = cp.checkRevokedCertExtensions(revokedCert[j].getExtensions());
+ if (includeCert) {
updateRevokedCert(REVOKED_CERT, revokedCert[j].getSerialNumber(), revokedCert[j]);
}
}
@@ -1938,8 +1944,8 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
BigInteger serialNo[] = request.getExtDataInBigIntegerArray(IRequest.OLD_SERIALS);
for (int j = 0; j < serialNo.length; j++) {
if (Debug.on()) {
- Debug.trace("recoverCRLCache U j="+j+" length="+serialNo.length+
- " SerialNumber=0x"+serialNo[j].toString(16));
+ Debug.trace("recoverCRLCache U j=" + j + " length=" + serialNo.length +
+ " SerialNumber=0x" + serialNo[j].toString(16));
}
updateRevokedCert(UNREVOKED_CERT, serialNo[j], null);
}
@@ -1972,32 +1978,33 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
}
private Extension getCRLExtension(String extName) {
- if(mAllowExtensions == false) {
+ if (mAllowExtensions == false) {
return null;
}
- if(mCMSCRLExtensions.isCRLExtensionEnabled(extName) == false) {
+ if (mCMSCRLExtensions.isCRLExtensionEnabled(extName) == false) {
return null;
}
CMSCRLExtensions exts = (CMSCRLExtensions) this.getCRLExtensions();
CRLExtensions ext = new CRLExtensions();
-
+
Vector<String> extNames = exts.getCRLExtensionNames();
- for (int i = 0; i < extNames.size(); i++) {
- String curName = extNames.elementAt(i);
- if (curName.equals(extName)) {
- exts.addToCRLExtensions(ext, extName, null);
- }
- }
- Extension theExt = null;
- try {
- theExt = ext.get(extName);
- } catch (Exception e) {
+ for (int i = 0; i < extNames.size(); i++) {
+ String curName = extNames.elementAt(i);
+ if (curName.equals(extName)) {
+ exts.addToCRLExtensions(ext, extName, null);
}
+ }
+ Extension theExt = null;
+ try {
+ theExt = ext.get(extName);
+ } catch (Exception e) {
+ }
- CMS.debug("CRLIssuingPoint.getCRLExtension extension: " + theExt);
- return theExt;
+ CMS.debug("CRLIssuingPoint.getCRLExtension extension: " + theExt);
+ return theExt;
}
+
/**
* get required crl entry extensions
*/
@@ -2021,7 +2028,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
if (extName.equals(name)) {
if (!(ext instanceof CRLReasonExtension) ||
- (((CRLReasonExtension) ext).getReason().toInt() >
+ (((CRLReasonExtension) ext).getReason().toInt() >
RevocationReason.UNSPECIFIED.toInt())) {
mCMSCRLExtensions.addToCRLExtensions(entryExt, extName, ext);
}
@@ -2057,7 +2064,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
String requestId) {
synchronized (cacheMonitor) {
if (requestId != null && mFirstUnsaved != null &&
- mFirstUnsaved.equals(ICRLIssuingPointRecord.CLEAN_CACHE)) {
+ mFirstUnsaved.equals(ICRLIssuingPointRecord.CLEAN_CACHE)) {
mFirstUnsaved = requestId;
try {
mCRLRepository.updateFirstUnsaved(mId, mFirstUnsaved);
@@ -2072,7 +2079,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
Date revocationDate = revokedCert.getRevocationDate();
CRLExtensions entryExt = getRequiredEntryExtensions(revokedCert.getExtensions());
RevokedCertImpl newRevokedCert =
- new RevokedCertImpl(serialNumber, revocationDate, entryExt);
+ new RevokedCertImpl(serialNumber, revocationDate, entryExt);
mCRLCerts.put(serialNumber, newRevokedCert);
}
@@ -2080,7 +2087,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
Date revocationDate = revokedCert.getRevocationDate();
CRLExtensions entryExt = getRequiredEntryExtensions(revokedCert.getExtensions());
RevokedCertImpl newRevokedCert =
- new RevokedCertImpl(serialNumber, revocationDate, entryExt);
+ new RevokedCertImpl(serialNumber, revocationDate, entryExt);
mRevokedCerts.put(serialNumber, (RevokedCertificate) newRevokedCert);
}
@@ -2092,7 +2099,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
try {
entryExt.set(CRLReasonExtension.REMOVE_FROM_CRL.getName(),
- CRLReasonExtension.REMOVE_FROM_CRL);
+ CRLReasonExtension.REMOVE_FROM_CRL);
} catch (IOException e) {
}
RevokedCertImpl newRevokedCert = new RevokedCertImpl(serialNumber,
@@ -2116,8 +2123,8 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
CertRecProcessor cp = new CertRecProcessor(mCRLCerts, this, mLogger, mAllowExtensions);
boolean includeCert = true;
- if(cp != null)
- includeCert = cp.checkRevokedCertExtensions(revokedCert.getExtensions());
+ if (cp != null)
+ includeCert = cp.checkRevokedCertExtensions(revokedCert.getExtensions());
if (mEnable && mEnableCRLCache && includeCert == true) {
updateRevokedCert(REVOKED_CERT, serialNumber, revokedCert, requestId);
@@ -2166,7 +2173,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
try {
entryExt.set(CRLReasonExtension.REMOVE_FROM_CRL.getName(),
- CRLReasonExtension.REMOVE_FROM_CRL);
+ CRLReasonExtension.REMOVE_FROM_CRL);
} catch (IOException e) {
}
RevokedCertImpl newRevokedCert = new RevokedCertImpl(serialNumber,
@@ -2191,7 +2198,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
synchronized (repositoryMonitor) {
try {
mCRLRepository.updateCRLCache(mId, Long.valueOf(mCRLSize),
- mRevokedCerts, mUnrevokedCerts, mExpiredCerts);
+ mRevokedCerts, mUnrevokedCerts, mExpiredCerts);
mFirstUnsaved = ICRLIssuingPointRecord.CLEAN_CACHE;
} catch (EBaseException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_ISSUING_STORE_CRL_CACHE", e.toString()));
@@ -2202,8 +2209,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
public boolean isDeltaCRLEnabled() {
return (mAllowExtensions && mEnableCRLCache &&
mCMSCRLExtensions.isCRLExtensionEnabled(DeltaCRLIndicatorExtension.class.getSimpleName()) &&
- mCMSCRLExtensions.isCRLExtensionEnabled(CRLNumberExtension.class.getSimpleName()) &&
- mCMSCRLExtensions.isCRLExtensionEnabled(CRLReasonExtension.class.getSimpleName()));
+ mCMSCRLExtensions.isCRLExtensionEnabled(CRLNumberExtension.class.getSimpleName()) && mCMSCRLExtensions.isCRLExtensionEnabled(CRLReasonExtension.class.getSimpleName()));
}
public boolean isThisCurrentDeltaCRL(X509CRLImpl deltaCRL) {
@@ -2242,7 +2248,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
}
public boolean isCRLCacheEmpty() {
- return ((mCRLCerts != null)? mCRLCerts.isEmpty(): true);
+ return ((mCRLCerts != null) ? mCRLCerts.isEmpty() : true);
}
public boolean isCRLCacheTestingEnabled() {
@@ -2250,8 +2256,8 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
}
public Date getRevocationDateFromCache(BigInteger serialNumber,
- boolean checkDeltaCache,
- boolean includeExpiredCerts) {
+ boolean checkDeltaCache,
+ boolean includeExpiredCerts) {
Date revocationDate = null;
if (mCRLCerts.containsKey(serialNumber)) {
@@ -2290,26 +2296,27 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
* updates CRL and publishes it now
*/
public void updateCRLNow()
- throws EBaseException {
+ throws EBaseException {
updateCRLNow(null);
}
public synchronized void updateCRLNow(String signingAlgorithm)
- throws EBaseException {
+ throws EBaseException {
- if ((!mEnable) || (!mEnableCRLUpdates && !mDoLastAutoUpdate)) return;
+ if ((!mEnable) || (!mEnableCRLUpdates && !mDoLastAutoUpdate))
+ return;
CMS.debug("Updating CRL");
mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER, AuditFormat.LEVEL,
CMS.getLogMessage("CMSCORE_CA_CA_CRL_UPDATE_STARTED"),
new Object[] {
- getId(),
- getNextCRLNumber(),
- Boolean.toString(isDeltaCRLEnabled()),
- Boolean.toString(isCRLCacheEnabled()),
- Boolean.toString(mEnableCacheRecovery),
- Boolean.toString(mCRLCacheIsCleared),
- ""+mCRLCerts.size()+","+mRevokedCerts.size()+","+mUnrevokedCerts.size()+","+mExpiredCerts.size()+""
+ getId(),
+ getNextCRLNumber(),
+ Boolean.toString(isDeltaCRLEnabled()),
+ Boolean.toString(isCRLCacheEnabled()),
+ Boolean.toString(mEnableCacheRecovery),
+ Boolean.toString(mCRLCacheIsCleared),
+ "" + mCRLCerts.size() + "," + mRevokedCerts.size() + "," + mUnrevokedCerts.size() + "," + mExpiredCerts.size() + ""
}
);
mUpdatingCRL = CRL_UPDATE_STARTED;
@@ -2321,8 +2328,8 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
Date nextDeltaUpdate = null;
if (mEnableCRLUpdates && ((mEnableDailyUpdates &&
- mDailyUpdates != null && mTimeListSize > 0) ||
- (mEnableUpdateFreq && mAutoUpdateInterval > 0))) {
+ mDailyUpdates != null && mTimeListSize > 0) ||
+ (mEnableUpdateFreq && mAutoUpdateInterval > 0))) {
if ((!isDeltaCRLEnabled()) || mSchemaCounter == 0 || mUpdateSchema == 1) {
nextUpdate = new Date(findNextUpdate(false, false));
@@ -2332,7 +2339,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
if (mUpdateSchema > 1 || (mEnableDailyUpdates && mExtendedTimeList && mTimeListSize > 1)) {
nextDeltaUpdate = new Date(findNextUpdate(false, true));
if (mExtendedNextUpdate && mSchemaCounter > 0 &&
- mNextUpdate != null && mNextUpdate.equals(nextDeltaUpdate)) {
+ mNextUpdate != null && mNextUpdate.equals(nextDeltaUpdate)) {
if (mEnableDailyUpdates && mExtendedTimeList && mTimeListSize > 1) {
mSchemaCounter = mTimeListSize - 1;
} else {
@@ -2354,32 +2361,32 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
mLastUpdate = thisUpdate;
// mNextUpdate = nextUpdate;
- mNextDeltaUpdate = (nextDeltaUpdate != null)? new Date(nextDeltaUpdate.getTime()): null;
+ mNextDeltaUpdate = (nextDeltaUpdate != null) ? new Date(nextDeltaUpdate.getTime()) : null;
if (nextUpdate != null) {
- nextUpdate.setTime((nextUpdate.getTime())+mNextUpdateGracePeriod);
+ nextUpdate.setTime((nextUpdate.getTime()) + mNextUpdateGracePeriod);
}
if (nextDeltaUpdate != null) {
- nextDeltaUpdate.setTime((nextDeltaUpdate.getTime())+mNextUpdateGracePeriod);
+ nextDeltaUpdate.setTime((nextDeltaUpdate.getTime()) + mNextUpdateGracePeriod);
}
mSplits[0] -= System.currentTimeMillis();
@SuppressWarnings("unchecked")
- Hashtable<BigInteger, RevokedCertificate> clonedRevokedCerts = (Hashtable<BigInteger, RevokedCertificate>)mRevokedCerts.clone();
+ Hashtable<BigInteger, RevokedCertificate> clonedRevokedCerts = (Hashtable<BigInteger, RevokedCertificate>) mRevokedCerts.clone();
@SuppressWarnings("unchecked")
- Hashtable<BigInteger, RevokedCertificate> clonedUnrevokedCerts = (Hashtable<BigInteger, RevokedCertificate>)mUnrevokedCerts.clone();
+ Hashtable<BigInteger, RevokedCertificate> clonedUnrevokedCerts = (Hashtable<BigInteger, RevokedCertificate>) mUnrevokedCerts.clone();
@SuppressWarnings("unchecked")
- Hashtable<BigInteger, RevokedCertificate> clonedExpiredCerts = (Hashtable<BigInteger, RevokedCertificate> )mExpiredCerts.clone();
+ Hashtable<BigInteger, RevokedCertificate> clonedExpiredCerts = (Hashtable<BigInteger, RevokedCertificate>) mExpiredCerts.clone();
mSplits[0] += System.currentTimeMillis();
// starting from the beginning
if ((!mEnableCRLCache) ||
- ((mCRLCacheIsCleared && mCRLCerts.isEmpty() && clonedRevokedCerts.isEmpty() &&
- clonedUnrevokedCerts.isEmpty() && clonedExpiredCerts.isEmpty()) ||
- (mCRLCerts.isEmpty() && (!clonedUnrevokedCerts.isEmpty())) ||
- (mCRLCerts.size() < clonedUnrevokedCerts.size()) ||
- (mCRLCerts.isEmpty() && (mCRLSize > 0)) ||
+ ((mCRLCacheIsCleared && mCRLCerts.isEmpty() && clonedRevokedCerts.isEmpty() &&
+ clonedUnrevokedCerts.isEmpty() && clonedExpiredCerts.isEmpty()) ||
+ (mCRLCerts.isEmpty() && (!clonedUnrevokedCerts.isEmpty())) ||
+ (mCRLCerts.size() < clonedUnrevokedCerts.size()) ||
+ (mCRLCerts.isEmpty() && (mCRLSize > 0)) ||
(mCRLCerts.size() > 0 && mCRLSize == 0))) {
mSplits[5] -= System.currentTimeMillis();
@@ -2390,15 +2397,15 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
clonedExpiredCerts.clear();
mSchemaCounter = 0;
- IStatsSubsystem statsSub = (IStatsSubsystem)CMS.getSubsystem("stats");
+ IStatsSubsystem statsSub = (IStatsSubsystem) CMS.getSubsystem("stats");
if (statsSub != null) {
- statsSub.startTiming("generation");
+ statsSub.startTiming("generation");
}
CertRecProcessor cp = new CertRecProcessor(mCRLCerts, this, mLogger, mAllowExtensions);
processRevokedCerts(cp);
if (statsSub != null) {
- statsSub.endTiming("generation");
+ statsSub.endTiming("generation");
}
mCRLCacheIsCleared = false;
@@ -2407,7 +2414,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
if (isDeltaCRLEnabled()) {
mSplits[1] -= System.currentTimeMillis();
@SuppressWarnings("unchecked")
- Hashtable<BigInteger, RevokedCertificate> deltaCRLCerts = (Hashtable<BigInteger, RevokedCertificate> )clonedRevokedCerts.clone();
+ Hashtable<BigInteger, RevokedCertificate> deltaCRLCerts = (Hashtable<BigInteger, RevokedCertificate>) clonedRevokedCerts.clone();
deltaCRLCerts.putAll(clonedUnrevokedCerts);
if (mIncludeExpiredCertsOneExtraTime) {
@@ -2415,8 +2422,8 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
for (Enumeration<BigInteger> e = clonedExpiredCerts.keys(); e.hasMoreElements();) {
BigInteger serialNumber = e.nextElement();
if ((mLastFullUpdate != null &&
- mLastFullUpdate.after((mExpiredCerts.get(serialNumber)).getRevocationDate())) ||
- mLastFullUpdate == null) {
+ mLastFullUpdate.after((mExpiredCerts.get(serialNumber)).getRevocationDate())) ||
+ mLastFullUpdate == null) {
deltaCRLCerts.put(serialNumber, clonedExpiredCerts.get(serialNumber));
}
}
@@ -2434,7 +2441,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
String extName = extNames.elementAt(i);
if (mCMSCRLExtensions.isCRLExtensionEnabled(extName) &&
- (!extName.equals(FreshestCRLExtension.class.getSimpleName()))) {
+ (!extName.equals(FreshestCRLExtension.class.getSimpleName()))) {
mCMSCRLExtensions.addToCRLExtensions(ext, extName, null);
}
}
@@ -2447,7 +2454,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
byte[] newDeltaCRL;
// #56123 - dont generate CRL if no revoked certificates
- if (mConfigStore.getBoolean("noCRLIfNoRevokedCert", false)) {
+ if (mConfigStore.getBoolean("noCRLIfNoRevokedCert", false)) {
if (deltaCRLCerts.size() == 0) {
CMS.debug("CRLIssuingPoint: No Revoked Certificates Found And noCRLIfNoRevokedCert is set to true - No Delta CRL Generated");
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR", "No Revoked Certificates"));
@@ -2468,12 +2475,12 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
mDeltaCRLSize = deltaCRLCerts.size();
-
long totalTime = 0;
String splitTimes = " (";
for (int i = 1; i < mSplits.length && i < 5; i++) {
totalTime += mSplits[i];
- if (i > 1) splitTimes += ",";
+ if (i > 1)
+ splitTimes += ",";
splitTimes += Long.toString(mSplits[i]);
}
splitTimes += ")";
@@ -2481,13 +2488,13 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
AuditFormat.LEVEL,
CMS.getLogMessage("CMSCORE_CA_CA_DELTA_CRL_UPDATED"),
new Object[] {
- getId(),
- getNextCRLNumber(),
- getCRLNumber(),
- getLastUpdate(),
- getNextDeltaUpdate(),
- Long.toString(mDeltaCRLSize),
- Long.toString(totalTime)+splitTimes
+ getId(),
+ getNextCRLNumber(),
+ getCRLNumber(),
+ getLastUpdate(),
+ getNextDeltaUpdate(),
+ Long.toString(mDeltaCRLSize),
+ Long.toString(totalTime) + splitTimes
}
);
} catch (EBaseException e) {
@@ -2513,7 +2520,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
mSplits[4] += System.currentTimeMillis();
} catch (EBaseException e) {
newX509DeltaCRL = null;
- if (Debug.on())
+ if (Debug.on())
Debug.printStackTrace(e);
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_ISSUING_PUBLISH_DELTA", mCRLNumber.toString(), e.toString()));
} catch (OutOfMemoryError e) {
@@ -2528,8 +2535,8 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
if (mSchemaCounter == 0) {
if (((!mCRLCerts.isEmpty()) && ((!clonedRevokedCerts.isEmpty()) ||
- (!clonedUnrevokedCerts.isEmpty()) || (!clonedExpiredCerts.isEmpty()))) ||
- (mCRLCerts.isEmpty() && (mCRLSize == 0) && (!clonedRevokedCerts.isEmpty()))) {
+ (!clonedUnrevokedCerts.isEmpty()) || (!clonedExpiredCerts.isEmpty()))) ||
+ (mCRLCerts.isEmpty() && (mCRLSize == 0) && (!clonedRevokedCerts.isEmpty()))) {
if (!clonedUnrevokedCerts.isEmpty()) {
for (Enumeration<BigInteger> e = clonedUnrevokedCerts.keys(); e.hasMoreElements();) {
@@ -2556,9 +2563,9 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
BigInteger serialNumber = e.nextElement();
if ((!mIncludeExpiredCertsOneExtraTime) ||
- (mLastFullUpdate != null &&
- mLastFullUpdate.after((mExpiredCerts.get(serialNumber)).getRevocationDate())) ||
- mLastFullUpdate == null) {
+ (mLastFullUpdate != null &&
+ mLastFullUpdate.after((mExpiredCerts.get(serialNumber)).getRevocationDate())) ||
+ mLastFullUpdate == null) {
if (mCRLCerts.containsKey(serialNumber)) {
mCRLCerts.remove(serialNumber);
}
@@ -2595,7 +2602,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
String extName = extNames.elementAt(i);
if (mCMSCRLExtensions.isCRLExtensionEnabled(extName) &&
- (!extName.equals(DeltaCRLIndicatorExtension.class.getSimpleName()))) {
+ (!extName.equals(DeltaCRLIndicatorExtension.class.getSimpleName()))) {
mCMSCRLExtensions.addToCRLExtensions(ext, extName, null);
}
}
@@ -2609,16 +2616,16 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
byte[] newCRL;
CMS.debug("Making CRL with algorithm " +
- signingAlgorithm + " " + AlgorithmId.get(signingAlgorithm));
+ signingAlgorithm + " " + AlgorithmId.get(signingAlgorithm));
mSplits[7] -= System.currentTimeMillis();
// #56123 - dont generate CRL if no revoked certificates
- if (mConfigStore.getBoolean("noCRLIfNoRevokedCert", false)) {
- if (mCRLCerts.size() == 0) {
- CMS.debug("CRLIssuingPoint: No Revoked Certificates Found And noCRLIfNoRevokedCert is set to true - No CRL Generated");
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR", "No Revoked Certificates"));
- }
+ if (mConfigStore.getBoolean("noCRLIfNoRevokedCert", false)) {
+ if (mCRLCerts.size() == 0) {
+ CMS.debug("CRLIssuingPoint: No Revoked Certificates Found And noCRLIfNoRevokedCert is set to true - No CRL Generated");
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR", "No Revoked Certificates"));
+ }
}
CMS.debug("before new X509CRLImpl");
X509CRLImpl crl = new X509CRLImpl(mCA.getCRLX500Name(),
@@ -2637,19 +2644,19 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
Date nextUpdateDate = mNextUpdate;
if (isDeltaCRLEnabled() && (mUpdateSchema > 1 ||
- (mEnableDailyUpdates && mExtendedTimeList)) && mNextDeltaUpdate != null) {
+ (mEnableDailyUpdates && mExtendedTimeList)) && mNextDeltaUpdate != null) {
nextUpdateDate = mNextDeltaUpdate;
}
if (mSaveMemory) {
mCRLRepository.updateCRLIssuingPointRecord(
- mId, newCRL, thisUpdate, nextUpdateDate,
- mNextCRLNumber, Long.valueOf(mCRLCerts.size()));
+ mId, newCRL, thisUpdate, nextUpdateDate,
+ mNextCRLNumber, Long.valueOf(mCRLCerts.size()));
updateCRLCacheRepository();
} else {
mCRLRepository.updateCRLIssuingPointRecord(
- mId, newCRL, thisUpdate, nextUpdateDate,
- mNextCRLNumber, Long.valueOf(mCRLCerts.size()),
- mRevokedCerts, mUnrevokedCerts, mExpiredCerts);
+ mId, newCRL, thisUpdate, nextUpdateDate,
+ mNextCRLNumber, Long.valueOf(mCRLCerts.size()),
+ mRevokedCerts, mUnrevokedCerts, mExpiredCerts);
mFirstUnsaved = ICRLIssuingPointRecord.CLEAN_CACHE;
}
@@ -2661,11 +2668,10 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
mNextCRLNumber = mCRLNumber.add(BigInteger.ONE);
mNextDeltaCRLNumber = mNextCRLNumber;
-
CMS.debug("Logging CRL Update to transaction log");
- long totalTime = 0;
- long crlTime = 0;
- long deltaTime = 0;
+ long totalTime = 0;
+ long crlTime = 0;
+ long deltaTime = 0;
String splitTimes = " (";
for (int i = 0; i < mSplits.length; i++) {
totalTime += mSplits[i];
@@ -2674,22 +2680,23 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
} else {
crlTime += mSplits[i];
}
- if (i > 0) splitTimes += ",";
+ if (i > 0)
+ splitTimes += ",";
splitTimes += Long.toString(mSplits[i]);
}
splitTimes += "," + Long.toString(deltaTime) + "," + Long.toString(crlTime) + "," + Long.toString(totalTime) + ")";
mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
AuditFormat.LEVEL,
CMS.getLogMessage("CMSCORE_CA_CA_CRL_UPDATED"),
- new Object[] {
- getId(),
- getCRLNumber(),
- getLastUpdate(),
- getNextUpdate(),
- Long.toString(mCRLSize),
- Long.toString(totalTime),
- Long.toString(crlTime),
- Long.toString(deltaTime)+splitTimes
+ new Object[] {
+ getId(),
+ getCRLNumber(),
+ getLastUpdate(),
+ getNextUpdate(),
+ Long.toString(mCRLSize),
+ Long.toString(totalTime),
+ Long.toString(crlTime),
+ Long.toString(deltaTime) + splitTimes
}
);
CMS.debug("Finished Logging CRL Update to transaction log");
@@ -2697,7 +2704,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
} catch (EBaseException e) {
newX509CRL = null;
mUpdatingCRL = CRL_UPDATE_DONE;
- if (Debug.on())
+ if (Debug.on())
Debug.printStackTrace(e);
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_ISSUING_SIGN_OR_STORE_CRL", e.toString()));
throw new ECAException(CMS.getUserMessage("CMS_CA_FAILED_CONSTRUCTING_CRL", e.toString()));
@@ -2744,10 +2751,12 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
mDeltaCRLNumber = mNextDeltaCRLNumber;
mNextDeltaCRLNumber = mDeltaCRLNumber.add(BigInteger.ONE);
}
-
- if ((!(mEnableDailyUpdates && mExtendedTimeList)) || mSchemaCounter == 0) mSchemaCounter++;
+
+ if ((!(mEnableDailyUpdates && mExtendedTimeList)) || mSchemaCounter == 0)
+ mSchemaCounter++;
if ((mEnableDailyUpdates && mExtendedTimeList && mSchemaCounter >= mTimeListSize) ||
- (mUpdateSchema > 1 && mSchemaCounter >= mUpdateSchema)) mSchemaCounter = 0;
+ (mUpdateSchema > 1 && mSchemaCounter >= mUpdateSchema))
+ mSchemaCounter = 0;
mLastDay = mCurrentDay;
mUpdatingCRL = CRL_UPDATE_DONE;
@@ -2758,34 +2767,33 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
* publish CRL. called from updateCRLNow() and init().
*/
- public void publishCRL()
- throws EBaseException {
+ public void publishCRL()
+ throws EBaseException {
publishCRL(null);
}
- protected void publishCRL(X509CRLImpl x509crl)
- throws EBaseException {
+ protected void publishCRL(X509CRLImpl x509crl)
+ throws EBaseException {
publishCRL(x509crl, false);
}
-
+
/*
- * The Session Context is a Hashtable, but without type information.
- * Suppress the warnings generated by adding to the session context
- *
+ * The Session Context is a Hashtable, but without type information.
+ * Suppress the warnings generated by adding to the session context
*/
- protected void publishCRL(X509CRLImpl x509crl, boolean isDeltaCRL)
- throws EBaseException {
+ protected void publishCRL(X509CRLImpl x509crl, boolean isDeltaCRL)
+ throws EBaseException {
SessionContext sc = SessionContext.getContext();
- IStatsSubsystem statsSub = (IStatsSubsystem)CMS.getSubsystem("stats");
+ IStatsSubsystem statsSub = (IStatsSubsystem) CMS.getSubsystem("stats");
if (statsSub != null) {
- statsSub.startTiming("crl_publishing");
+ statsSub.startTiming("crl_publishing");
}
if (mCountMod == 0) {
- sc.put(SC_CRL_COUNT, Integer.toString(mCount));
+ sc.put(SC_CRL_COUNT, Integer.toString(mCount));
} else {
- sc.put(SC_CRL_COUNT, Integer.toString(mCount%mCountMod));
+ sc.put(SC_CRL_COUNT, Integer.toString(mCount % mCountMod));
}
mCount++;
sc.put(SC_ISSUING_POINT_ID, mId);
@@ -2810,7 +2818,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
}
}
if (x509crl != null &&
- mPublisherProcessor != null && mPublisherProcessor.enabled()) {
+ mPublisherProcessor != null && mPublisherProcessor.enabled()) {
Enumeration<ILdapRule> rules = mPublisherProcessor.getRules(IPublisherProcessor.PROP_LOCAL_CRL);
if (rules == null || !rules.hasMoreElements()) {
CMS.debug("CRL publishing is not enabled.");
@@ -2819,7 +2827,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
mPublisherProcessor.publishCRL(mPublishDN, x509crl);
CMS.debug("CRL published to " + mPublishDN);
} else {
- mPublisherProcessor.publishCRL(x509crl,getId());
+ mPublisherProcessor.publishCRL(x509crl, getId());
CMS.debug("CRL published.");
}
}
@@ -2830,15 +2838,15 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
throw new EErrorPublishCRL(
CMS.getUserMessage("CMS_CA_ERROR_PUBLISH_CRL", mId, e.toString()));
} finally {
- if (statsSub != null) {
- statsSub.endTiming("crl_publishing");
- }
+ if (statsSub != null) {
+ statsSub.endTiming("crl_publishing");
+ }
}
}
protected void log(int level, String msg) {
- mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_CA, level,
- "CRLIssuingPoint " + mId + " - " + msg);
+ mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_CA, level,
+ "CRLIssuingPoint " + mId + " - " + msg);
}
void setConfigParam(String name, String value) {
@@ -2848,7 +2856,7 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
class RevocationRequestListener implements IRequestListener {
public void init(ISubsystem sys, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
}
public void set(String name, String val) {
@@ -2858,36 +2866,36 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
String requestType = r.getRequestType();
if (requestType.equals(IRequest.REVOCATION_REQUEST) ||
- requestType.equals(IRequest.UNREVOCATION_REQUEST) ||
- requestType.equals(IRequest.CLA_CERT4CRL_REQUEST) ||
- requestType.equals(IRequest.CLA_UNCERT4CRL_REQUEST)) {
+ requestType.equals(IRequest.UNREVOCATION_REQUEST) ||
+ requestType.equals(IRequest.CLA_CERT4CRL_REQUEST) ||
+ requestType.equals(IRequest.CLA_UNCERT4CRL_REQUEST)) {
CMS.debug("Revocation listener called.");
// check if serial number is in begin/end range if set.
if (mBeginSerial != null || mEndSerial != null) {
CMS.debug(
- "Checking if serial number is between " +
- mBeginSerial + " and " + mEndSerial);
- BigInteger[] serialNos =
- r.getExtDataInBigIntegerArray(IRequest.OLD_SERIALS);
+ "Checking if serial number is between " +
+ mBeginSerial + " and " + mEndSerial);
+ BigInteger[] serialNos =
+ r.getExtDataInBigIntegerArray(IRequest.OLD_SERIALS);
if (serialNos == null || serialNos.length == 0) {
- X509CertImpl oldCerts[] =
- r.getExtDataInCertArray(IRequest.OLD_CERTS);
+ X509CertImpl oldCerts[] =
+ r.getExtDataInCertArray(IRequest.OLD_CERTS);
- if (oldCerts == null || oldCerts.length == 0)
+ if (oldCerts == null || oldCerts.length == 0)
return;
serialNos = new BigInteger[oldCerts.length];
for (int i = 0; i < oldCerts.length; i++) {
serialNos[i] = oldCerts[i].getSerialNumber();
}
}
-
+
boolean inRange = false;
for (int i = 0; i < serialNos.length; i++) {
- if ((mBeginSerial == null ||
+ if ((mBeginSerial == null ||
serialNos[i].compareTo(mBeginSerial) >= 0) &&
- (mEndSerial == null ||
+ (mEndSerial == null ||
serialNos[i].compareTo(mEndSerial) <= 0)) {
inRange = true;
}
@@ -2921,8 +2929,8 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
Debug.printStackTrace(e);
r.setExtData(mCrlUpdateStatus, IRequest.RES_ERROR);
r.setExtData(mCrlUpdateError,
- new EBaseException(
- CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR", e.toString())));
+ new EBaseException(
+ CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR", e.toString())));
}
}
}
@@ -2930,7 +2938,6 @@ public class CRLIssuingPoint implements ICRLIssuingPoint, Runnable {
}
}
-
class CertRecProcessor implements IElementProcessor {
private Hashtable<BigInteger, RevokedCertificate> mCRLCerts = null;
private boolean mAllowExtensions = false;
@@ -2947,101 +2954,100 @@ class CertRecProcessor implements IElementProcessor {
mIP = ip;
mAllowExtensions = allowExtensions;
mIssuingDistPointAttempted = false;
- mIssuingDistPointEnabled = false;
+ mIssuingDistPointEnabled = false;
mOnlySomeReasons = null;
}
private boolean initCRLIssuingDistPointExtension() {
- boolean result = false;
- CMSCRLExtensions exts = null;
-
- if(mIssuingDistPointAttempted == true) {
- if((mIssuingDistPointEnabled == true) && (mOnlySomeReasons != null )) {
- return true;
- } else {
- return false;
- }
- }
-
- mIssuingDistPointAttempted = true;
- exts = (CMSCRLExtensions) mIP.getCRLExtensions();
- if(exts == null) {
- return result;
- }
- boolean isIssuingDistPointExtEnabled = false;
- isIssuingDistPointExtEnabled = exts.isCRLExtensionEnabled(IssuingDistributionPointExtension.class.getSimpleName());
- if(isIssuingDistPointExtEnabled == false) {
+ boolean result = false;
+ CMSCRLExtensions exts = null;
+
+ if (mIssuingDistPointAttempted == true) {
+ if ((mIssuingDistPointEnabled == true) && (mOnlySomeReasons != null)) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ mIssuingDistPointAttempted = true;
+ exts = (CMSCRLExtensions) mIP.getCRLExtensions();
+ if (exts == null) {
+ return result;
+ }
+ boolean isIssuingDistPointExtEnabled = false;
+ isIssuingDistPointExtEnabled = exts.isCRLExtensionEnabled(IssuingDistributionPointExtension.class.getSimpleName());
+ if (isIssuingDistPointExtEnabled == false) {
mIssuingDistPointEnabled = false;
return false;
}
mIssuingDistPointEnabled = true;
- //Get info out of the IssuingDistPointExtension
+ // Get info out of the IssuingDistPointExtension
CRLExtensions ext = new CRLExtensions();
Vector<String> extNames = exts.getCRLExtensionNames();
- for (int i = 0; i < extNames.size(); i++) {
- String extName = extNames.elementAt(i);
- if (extName.equals(IssuingDistributionPointExtension.class.getSimpleName())) {
- exts.addToCRLExtensions(ext, extName, null);
- }
- }
- Extension issuingDistExt = null;
- try {
- issuingDistExt = ext.get(IssuingDistributionPointExtension.class.getSimpleName());
- } catch (Exception e) {
+ for (int i = 0; i < extNames.size(); i++) {
+ String extName = extNames.elementAt(i);
+ if (extName.equals(IssuingDistributionPointExtension.class.getSimpleName())) {
+ exts.addToCRLExtensions(ext, extName, null);
}
+ }
+ Extension issuingDistExt = null;
+ try {
+ issuingDistExt = ext.get(IssuingDistributionPointExtension.class.getSimpleName());
+ } catch (Exception e) {
+ }
- IssuingDistributionPointExtension iExt = null;
- if(issuingDistExt != null)
- iExt = (IssuingDistributionPointExtension) issuingDistExt;
- IssuingDistributionPoint issuingDistributionPoint = null;
- if(iExt != null)
- issuingDistributionPoint = iExt.getIssuingDistributionPoint();
+ IssuingDistributionPointExtension iExt = null;
+ if (issuingDistExt != null)
+ iExt = (IssuingDistributionPointExtension) issuingDistExt;
+ IssuingDistributionPoint issuingDistributionPoint = null;
+ if (iExt != null)
+ issuingDistributionPoint = iExt.getIssuingDistributionPoint();
- BitArray onlySomeReasons = null;
+ BitArray onlySomeReasons = null;
- if(issuingDistributionPoint != null)
- onlySomeReasons = issuingDistributionPoint.getOnlySomeReasons();
+ if (issuingDistributionPoint != null)
+ onlySomeReasons = issuingDistributionPoint.getOnlySomeReasons();
- boolean applyReasonMatch = false;
- boolean reasonMatch = true;
+ boolean applyReasonMatch = false;
+ boolean reasonMatch = true;
- if(onlySomeReasons != null) {
- applyReasonMatch = !onlySomeReasons.toString().equals("0000000");
- CMS.debug("applyReasonMatch " + applyReasonMatch);
- if(applyReasonMatch == true) {
- mOnlySomeReasons = onlySomeReasons;
- result = true;
- }
+ if (onlySomeReasons != null) {
+ applyReasonMatch = !onlySomeReasons.toString().equals("0000000");
+ CMS.debug("applyReasonMatch " + applyReasonMatch);
+ if (applyReasonMatch == true) {
+ mOnlySomeReasons = onlySomeReasons;
+ result = true;
}
- return result;
+ }
+ return result;
}
- private boolean checkOnlySomeReasonsExtension(CRLExtensions entryExts)
- {
+ private boolean checkOnlySomeReasonsExtension(CRLExtensions entryExts) {
boolean includeCert = true;
- //This is exactly how the Pretty Print code obtains the reason code
- //through the extensions
- if(entryExts == null) {
+ // This is exactly how the Pretty Print code obtains the reason code
+ // through the extensions
+ if (entryExts == null) {
return includeCert;
}
Extension crlReasonExt = null;
try {
- crlReasonExt = entryExts.get(CRLReasonExtension.class.getSimpleName());
+ crlReasonExt = entryExts.get(CRLReasonExtension.class.getSimpleName());
} catch (Exception e) {
return includeCert;
}
RevocationReason reason = null;
int reasonIndex = 0;
- if(crlReasonExt != null) {
+ if (crlReasonExt != null) {
try {
- CRLReasonExtension theReason = (CRLReasonExtension) crlReasonExt;
- reason = (RevocationReason) theReason.get("value");
- reasonIndex = reason.toInt();
- CMS.debug("revoked reason " + reason);
+ CRLReasonExtension theReason = (CRLReasonExtension) crlReasonExt;
+ reason = (RevocationReason) theReason.get("value");
+ reasonIndex = reason.toInt();
+ CMS.debug("revoked reason " + reason);
} catch (Exception e) {
return includeCert;
}
@@ -3049,37 +3055,37 @@ class CertRecProcessor implements IElementProcessor {
return includeCert;
}
boolean reasonMatch = false;
- if(reason != null) {
- if(mOnlySomeReasons != null) {
+ if (reason != null) {
+ if (mOnlySomeReasons != null) {
reasonMatch = mOnlySomeReasons.get(reasonIndex);
- if(reasonMatch != true) {
+ if (reasonMatch != true) {
includeCert = false;
} else {
CMS.debug("onlySomeReasons match! reason: " + reason);
}
}
}
-
+
return includeCert;
}
- public boolean checkRevokedCertExtensions(CRLExtensions crlExtensions)
- {
- //For now just check the onlySomeReason CRL IssuingDistributionPoint extension
+ public boolean checkRevokedCertExtensions(CRLExtensions crlExtensions) {
+ // For now just check the onlySomeReason CRL IssuingDistributionPoint
+ // extension
- boolean includeCert = true;
- if((crlExtensions == null) || (mAllowExtensions == false)) {
+ boolean includeCert = true;
+ if ((crlExtensions == null) || (mAllowExtensions == false)) {
return includeCert;
}
boolean inited = initCRLIssuingDistPointExtension();
- //If the CRLIssuingDistPointExtension is not available or
+ // If the CRLIssuingDistPointExtension is not available or
// if onlySomeReasons does not apply, bail.
- if(inited == false) {
+ if (inited == false) {
return includeCert;
- }
+ }
- //Check the onlySomeReasonsExtension
+ // Check the onlySomeReasonsExtension
includeCert = checkOnlySomeReasonsExtension(crlExtensions);
return includeCert;
@@ -3099,22 +3105,21 @@ class CertRecProcessor implements IElementProcessor {
entryExt = mIP.getRequiredEntryExtensions(crlExts);
}
RevokedCertificate newRevokedCert =
- new RevokedCertImpl(serialNumber, revocationDate, entryExt);
+ new RevokedCertImpl(serialNumber, revocationDate, entryExt);
boolean includeCert = checkRevokedCertExtensions(crlExts);
if (includeCert == true) {
mCRLCerts.put(serialNumber, (RevokedCertificate) newRevokedCert);
if (serialNumber != null) {
- CMS.debug("Putting certificate serial: 0x"+serialNumber.toString(16)+" into CRL hashtable");
+ CMS.debug("Putting certificate serial: 0x" + serialNumber.toString(16) + " into CRL hashtable");
}
}
} catch (EBaseException e) {
CMS.debug(
- "CA failed constructing CRL entry: " +
- (mCRLCerts.size() + 1) + " " + e);
+ "CA failed constructing CRL entry: " +
+ (mCRLCerts.size() + 1) + " " + e);
throw new ECAException(CMS.getUserMessage("CMS_CA_FAILED_CONSTRUCTING_CRL", e.toString()));
}
}
}
-
diff --git a/pki/base/ca/src/com/netscape/ca/CRLWithExpiredCerts.java b/pki/base/ca/src/com/netscape/ca/CRLWithExpiredCerts.java
index bb204386..8b756a4a 100644
--- a/pki/base/ca/src/com/netscape/ca/CRLWithExpiredCerts.java
+++ b/pki/base/ca/src/com/netscape/ca/CRLWithExpiredCerts.java
@@ -17,44 +17,42 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.ca;
-
import java.math.BigInteger;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.cmscore.dbs.CertRecord;
-
/**
- * A CRL Issuing point that contains revoked certs, include onces that
- * have expired.
+ * A CRL Issuing point that contains revoked certs, include onces that have
+ * expired.
*/
public class CRLWithExpiredCerts extends CRLIssuingPoint {
/**
- * overrides getRevokedCerts in CRLIssuingPoint to include
- * all revoked certs, including once that have expired.
- *
+ * overrides getRevokedCerts in CRLIssuingPoint to include all revoked
+ * certs, including once that have expired.
+ *
* @param thisUpdate parameter is ignored.
- *
+ *
* @exception EBaseException if an exception occured getting revoked
- * certificates from the database.
+ * certificates from the database.
*/
public String getFilter() {
// PLEASE DONT CHANGE THE FILTER. It is indexed.
// Changing it will degrade performance. See
// also com.netscape.certsetup.LDAPUtil.java
String filter =
- "(|(" + CertRecord.ATTR_CERT_STATUS + "=" +
- CertRecord.STATUS_REVOKED + ")" +
- "(" + CertRecord.ATTR_CERT_STATUS + "=" +
- CertRecord.STATUS_REVOKED_EXPIRED + "))";
+ "(|(" + CertRecord.ATTR_CERT_STATUS + "=" +
+ CertRecord.STATUS_REVOKED + ")" +
+ "(" + CertRecord.ATTR_CERT_STATUS + "=" +
+ CertRecord.STATUS_REVOKED_EXPIRED + "))";
// check if any ranges specified.
- if (mBeginSerial != null)
+ if (mBeginSerial != null)
filter += "(" + CertRecord.ATTR_ID + ">=" + mBeginSerial.toString() + ")";
if (mEndSerial != null)
filter += "(" + CertRecord.ATTR_ID + "<=" + mEndSerial.toString() + ")";
- // get all revoked non-expired certs.
+ // get all revoked non-expired certs.
if (mEndSerial != null || mBeginSerial != null) {
filter = "(&" + filter + ")";
}
diff --git a/pki/base/ca/src/com/netscape/ca/CertificateAuthority.java b/pki/base/ca/src/com/netscape/ca/CertificateAuthority.java
index 657ed72c..ccd0af39 100644
--- a/pki/base/ca/src/com/netscape/ca/CertificateAuthority.java
+++ b/pki/base/ca/src/com/netscape/ca/CertificateAuthority.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.ca;
-
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
@@ -117,12 +116,11 @@ import com.netscape.cmsutil.ocsp.SingleResponse;
import com.netscape.cmsutil.ocsp.TBSRequest;
import com.netscape.cmsutil.ocsp.UnknownInfo;
-
/**
- * A class represents a Certificate Authority that is
- * responsible for certificate specific operations.
+ * A class represents a Certificate Authority that is responsible for
+ * certificate specific operations.
* <P>
- *
+ *
* @author lhsiao
* @version $Revision$, $Date$
*/
@@ -134,8 +132,8 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
protected ISubsystem mOwner = null;
protected IConfigStore mConfig = null;
protected ILogger mLogger = CMS.getLogger();
- protected Hashtable<String, ICRLIssuingPoint> mCRLIssuePoints = new Hashtable<String, ICRLIssuingPoint>();
- protected CRLIssuingPoint mMasterCRLIssuePoint = null; // the complete crl.
+ protected Hashtable<String, ICRLIssuingPoint> mCRLIssuePoints = new Hashtable<String, ICRLIssuingPoint>();
+ protected CRLIssuingPoint mMasterCRLIssuePoint = null; // the complete crl.
protected SigningUnit mSigningUnit;
protected SigningUnit mOCSPSigningUnit;
protected SigningUnit mCRLSigningUnit;
@@ -143,8 +141,8 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
protected X500Name mName = null;
protected X500Name mCRLName = null;
protected X500Name mOCSPName = null;
- protected String mNickname = null; // nickname of CA signing cert.
- protected String mOCSPNickname = null; // nickname of OCSP signing cert.
+ protected String mNickname = null; // nickname of CA signing cert.
+ protected String mOCSPNickname = null; // nickname of OCSP signing cert.
protected long mCertSerialNumberCounter = System.currentTimeMillis();
protected long mRequestID = System.currentTimeMillis();
@@ -185,7 +183,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
protected boolean mEnableOCSP;
protected int mFastSigning = FASTSIGNING_DISABLED;
- protected static final long SECOND = 1000; // 1000 milliseconds
+ protected static final long SECOND = 1000; // 1000 milliseconds
protected static final long MINUTE = 60 * SECOND;
protected static final long HOUR = 60 * MINUTE;
protected static final long DAY = 24 * HOUR;
@@ -197,7 +195,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
// for the notification listeners
- /**
+ /**
* Package constants
*/
@@ -261,12 +259,12 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
}
}
-
public void publishCRLNow() throws EBaseException {
if (mMasterCRLIssuePoint != null) {
mMasterCRLIssuePoint.publishCRL();
}
}
+
public ICRLPublisher getCRLPublisher() {
return mCRLPublisher;
}
@@ -286,7 +284,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
/**
* Initializes this CA subsystem.
* <P>
- *
+ *
* @param owner owner of this subsystem
* @param config configuration of this subsystem
* @exception EBaseException failed to initialize this CA
@@ -294,97 +292,97 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
public void init(ISubsystem owner, IConfigStore config) throws
EBaseException {
- try {
- CMS.debug("CertificateAuthority init ");
- mOwner = owner;
- mConfig = config;
+ try {
+ CMS.debug("CertificateAuthority init ");
+ mOwner = owner;
+ mConfig = config;
- // init cert & crl database.
- initCaDatabases();
+ // init cert & crl database.
+ initCaDatabases();
- // init signing unit & CA cert.
- try {
- initSigUnit();
- // init default CA attributes like cert version, validity.
- initDefCaAttrs();
- } catch (EBaseException e) {
- if (CMS.isPreOpMode())
- ;
- else
- throw e;
- }
+ // init signing unit & CA cert.
+ try {
+ initSigUnit();
+ // init default CA attributes like cert version, validity.
+ initDefCaAttrs();
+ } catch (EBaseException e) {
+ if (CMS.isPreOpMode())
+ ;
+ else
+ throw e;
+ }
- // init web gateway.
- initWebGateway();
+ // init web gateway.
+ initWebGateway();
- mUseNonces = mConfig.getBoolean("enableNonces", true);
- mMaxNonces = mConfig.getInteger("maxNumberOfNonces", 100);
- if (mUseNonces) {
- mNonces = new Nonces(mMaxNonces);
- CMS.debug("CertificateAuthority init: Nonces enabled. ("+mNonces.size()+")");
- }
+ mUseNonces = mConfig.getBoolean("enableNonces", true);
+ mMaxNonces = mConfig.getInteger("maxNumberOfNonces", 100);
+ if (mUseNonces) {
+ mNonces = new Nonces(mMaxNonces);
+ CMS.debug("CertificateAuthority init: Nonces enabled. (" + mNonces.size() + ")");
+ }
- // init request queue and related modules.
- CMS.debug("CertificateAuthority init: initRequestQueue");
- initRequestQueue();
- if (CMS.isPreOpMode())
- return;
+ // init request queue and related modules.
+ CMS.debug("CertificateAuthority init: initRequestQueue");
+ initRequestQueue();
+ if (CMS.isPreOpMode())
+ return;
- // set certificate status to 10 minutes
- mCertRepot.setCertStatusUpdateInterval(
- mRequestQueue.getRequestRepository(),
- mConfig.getInteger("certStatusUpdateInterval", 10 * 60),
- mConfig.getBoolean("listenToCloneModifications", false));
- mCertRepot.setConsistencyCheck(
- mConfig.getBoolean("ConsistencyCheck", false));
- mCertRepot.setSkipIfInConsistent(
- mConfig.getBoolean("SkipIfInConsistent", false));
-
- mService.init(config.getSubStore("connector"));
+ // set certificate status to 10 minutes
+ mCertRepot.setCertStatusUpdateInterval(
+ mRequestQueue.getRequestRepository(),
+ mConfig.getInteger("certStatusUpdateInterval", 10 * 60),
+ mConfig.getBoolean("listenToCloneModifications", false));
+ mCertRepot.setConsistencyCheck(
+ mConfig.getBoolean("ConsistencyCheck", false));
+ mCertRepot.setSkipIfInConsistent(
+ mConfig.getBoolean("SkipIfInConsistent", false));
- initMiscellaneousListeners();
+ mService.init(config.getSubStore("connector"));
- // instantiate CRL publisher
- IConfigStore cpStore = null;
+ initMiscellaneousListeners();
- mByName = config.getBoolean("byName", true);
+ // instantiate CRL publisher
+ IConfigStore cpStore = null;
- cpStore = config.getSubStore("crlPublisher");
- if (cpStore != null && cpStore.size() > 0) {
- String publisherClass = cpStore.getString("class");
+ mByName = config.getBoolean("byName", true);
- if (publisherClass != null) {
- try {
- @SuppressWarnings("unchecked")
- Class<ICRLPublisher> pc = (Class<ICRLPublisher>) Class.forName(publisherClass);
-
- mCRLPublisher = pc.newInstance();
- mCRLPublisher.init(this, cpStore);
- } catch (ClassNotFoundException ee) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_NO_PUBLISHER", ee.toString()));
- } catch (IllegalAccessException ee) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_NO_PUBLISHER", ee.toString()));
- } catch (InstantiationException ee) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_NO_PUBLISHER", ee.toString()));
+ cpStore = config.getSubStore("crlPublisher");
+ if (cpStore != null && cpStore.size() > 0) {
+ String publisherClass = cpStore.getString("class");
+
+ if (publisherClass != null) {
+ try {
+ @SuppressWarnings("unchecked")
+ Class<ICRLPublisher> pc = (Class<ICRLPublisher>) Class.forName(publisherClass);
+
+ mCRLPublisher = pc.newInstance();
+ mCRLPublisher.init(this, cpStore);
+ } catch (ClassNotFoundException ee) {
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_NO_PUBLISHER", ee.toString()));
+ } catch (IllegalAccessException ee) {
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_NO_PUBLISHER", ee.toString()));
+ } catch (InstantiationException ee) {
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_NO_PUBLISHER", ee.toString()));
+ }
}
}
- }
- // initialize publisher processor (publish remote admin
- // rely on this subsystem, so it has to be initialized)
- initPublish();
+ // initialize publisher processor (publish remote admin
+ // rely on this subsystem, so it has to be initialized)
+ initPublish();
- // Initialize CRL issuing points.
- // note CRL framework depends on DBS, CRYPTO and PUBLISHING
- // being functional.
- initCRL();
+ // Initialize CRL issuing points.
+ // note CRL framework depends on DBS, CRYPTO and PUBLISHING
+ // being functional.
+ initCRL();
- } catch (EBaseException e) {
- if (CMS.isPreOpMode())
- return;
- else
- throw e;
- }
+ } catch (EBaseException e) {
+ if (CMS.isPreOpMode())
+ return;
+ else
+ throw e;
+ }
}
/**
@@ -393,7 +391,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
public IRequestQueue getRequestQueue() {
return mRequestQueue;
}
-
+
/**
* registers listener
*/
@@ -506,7 +504,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
}
mService.startup();
mRequestQueue.recover();
-
+
// Note that this could be null.
// setup Admin operations
@@ -514,7 +512,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
initNotificationListeners();
startPublish();
- // startCRL();
+ // startCRL();
}
/**
@@ -524,7 +522,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
public void shutdown() {
Enumeration<ICRLIssuingPoint> enums = mCRLIssuePoints.elements();
while (enums.hasMoreElements()) {
- CRLIssuingPoint point = (CRLIssuingPoint)enums.nextElement();
+ CRLIssuingPoint point = (CRLIssuingPoint) enums.nextElement();
point.shutdown();
}
@@ -577,7 +575,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
return mDefaultValidity;
}
- public SignatureAlgorithm getDefaultSignatureAlgorithm() {
+ public SignatureAlgorithm getDefaultSignatureAlgorithm() {
return mSigningUnit.getDefaultSignatureAlgorithm();
}
@@ -592,7 +590,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
public String getStartSerial() {
try {
BigInteger serial =
- ((Repository) mCertRepot).getTheSerialNumber();
+ ((Repository) mCertRepot).getTheSerialNumber();
if (serial == null)
return "";
@@ -600,7 +598,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
return serial.toString(16);
} catch (EBaseException e) {
// shouldn't get here.
- return "";
+ return "";
}
}
@@ -624,24 +622,23 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
/**
* Retrieves certificate repository.
* <P>
- *
+ *
* @return certificate repository
*/
public ICertificateRepository getCertificateRepository() {
return mCertRepot;
}
-
+
/**
* Retrieves replica repository.
* <P>
- *
+ *
* @return replica repository
*/
public IReplicaIDRepository getReplicaRepository() {
return mReplicaRepot;
}
-
/**
* Retrieves CRL repository.
*/
@@ -656,6 +653,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
/**
* Retrieves the CRL issuing point by id.
* <P>
+ *
* @param id string id of the CRL issuing point
* @return CRL issuing point
*/
@@ -666,6 +664,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
/**
* Enumerates CRL issuing points
* <P>
+ *
* @return security service
*/
public Enumeration<ICRLIssuingPoint> getCRLIssuingPoints() {
@@ -680,7 +679,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
* Adds CRL issuing point with the given identifier and description.
*/
@SuppressWarnings("unchecked")
- public boolean addCRLIssuingPoint(IConfigStore crlSubStore, String id,
+ public boolean addCRLIssuingPoint(IConfigStore crlSubStore, String id,
boolean enable, String description) {
crlSubStore.makeSubStore(id);
IConfigStore c = crlSubStore.getSubStore(id);
@@ -716,7 +715,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
c.putString("extension.AuthorityInformationAccess.critical", "false");
c.putString("extension.AuthorityInformationAccess.type", "CRLExtension");
c.putString("extension.AuthorityInformationAccess.class",
- "com.netscape.cms.crl.CMSAuthInfoAccessExtension");
+ "com.netscape.cms.crl.CMSAuthInfoAccessExtension");
c.putString("extension.AuthorityInformationAccess.numberOfAccessDescriptions", "1");
c.putString("extension.AuthorityInformationAccess.accessMethod0", "caIssuers");
c.putString("extension.AuthorityInformationAccess.accessLocationType0", "URI");
@@ -726,13 +725,13 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
c.putString("extension.AuthorityKeyIdentifier.critical", "false");
c.putString("extension.AuthorityKeyIdentifier.type", "CRLExtension");
c.putString("extension.AuthorityKeyIdentifier.class",
- "com.netscape.cms.crl.CMSAuthorityKeyIdentifierExtension");
+ "com.netscape.cms.crl.CMSAuthorityKeyIdentifierExtension");
// IssuerAlternativeName
c.putString("extension.IssuerAlternativeName.enable", "false");
c.putString("extension.IssuerAlternativeName.critical", "false");
c.putString("extension.IssuerAlternativeName.type", "CRLExtension");
c.putString("extension.IssuerAlternativeName.class",
- "com.netscape.cms.crl.CMSIssuerAlternativeNameExtension");
+ "com.netscape.cms.crl.CMSIssuerAlternativeNameExtension");
c.putString("extension.IssuerAlternativeName.numNames", "0");
c.putString("extension.IssuerAlternativeName.nameType0", "");
c.putString("extension.IssuerAlternativeName.name0", "");
@@ -741,62 +740,64 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
c.putString("extension.CRLNumber.critical", "false");
c.putString("extension.CRLNumber.type", "CRLExtension");
c.putString("extension.CRLNumber.class",
- "com.netscape.cms.crl.CMSCRLNumberExtension");
+ "com.netscape.cms.crl.CMSCRLNumberExtension");
// DeltaCRLIndicator
c.putString("extension.DeltaCRLIndicator.enable", "false");
c.putString("extension.DeltaCRLIndicator.critical", "true");
c.putString("extension.DeltaCRLIndicator.type", "CRLExtension");
c.putString("extension.DeltaCRLIndicator.class",
- "com.netscape.cms.crl.CMSDeltaCRLIndicatorExtension");
+ "com.netscape.cms.crl.CMSDeltaCRLIndicatorExtension");
// IssuingDistributionPoint
c.putString("extension.IssuingDistributionPoint.enable", "false");
c.putString("extension.IssuingDistributionPoint.critical", "true");
c.putString("extension.IssuingDistributionPoint.type", "CRLExtension");
c.putString("extension.IssuingDistributionPoint.class",
- "com.netscape.cms.crl.CMSIssuingDistributionPointExtension");
+ "com.netscape.cms.crl.CMSIssuingDistributionPointExtension");
c.putString("extension.IssuingDistributionPoint.pointType", "");
c.putString("extension.IssuingDistributionPoint.pointName", "");
c.putString("extension.IssuingDistributionPoint.onlyContainsUserCerts", "false");
c.putString("extension.IssuingDistributionPoint.onlyContainsCACerts", "false");
c.putString("extension.IssuingDistributionPoint.onlySomeReasons", "");
- //"keyCompromise,cACompromise,affiliationChanged,superseded,cessationOfOperation,certificateHold");
+ // "keyCompromise,cACompromise,affiliationChanged,superseded,cessationOfOperation,certificateHold");
c.putString("extension.IssuingDistributionPoint.indirectCRL", "false");
// CRLReason
c.putString("extension.CRLReason.enable", "true");
c.putString("extension.CRLReason.critical", "false");
c.putString("extension.CRLReason.type", "CRLEntryExtension");
c.putString("extension.CRLReason.class",
- "com.netscape.cms.crl.CMSCRLReasonExtension");
+ "com.netscape.cms.crl.CMSCRLReasonExtension");
// HoldInstruction - removed by RFC 5280
// c.putString("extension.HoldInstruction.enable", "false");
// c.putString("extension.HoldInstruction.critical", "false");
- // c.putString("extension.HoldInstruction.type", "CRLEntryExtension");
+ // c.putString("extension.HoldInstruction.type",
+ // "CRLEntryExtension");
// c.putString("extension.HoldInstruction.class",
- // "com.netscape.cms.crl.CMSHoldInstructionExtension");
+ // "com.netscape.cms.crl.CMSHoldInstructionExtension");
// c.putString("extension.HoldInstruction.instruction", "none");
// InvalidityDate
c.putString("extension.InvalidityDate.enable", "true");
c.putString("extension.InvalidityDate.critical", "false");
c.putString("extension.InvalidityDate.type", "CRLEntryExtension");
c.putString("extension.InvalidityDate.class",
- "com.netscape.cms.crl.CMSInvalidityDateExtension");
+ "com.netscape.cms.crl.CMSInvalidityDateExtension");
// CertificateIssuer
/*
- c.putString("extension.CertificateIssuer.enable", "false");
- c.putString("extension.CertificateIssuer.critical", "true");
- c.putString("extension.CertificateIssuer.type", "CRLEntryExtension");
- c.putString("extension.CertificateIssuer.class",
- "com.netscape.cms.crl.CMSCertificateIssuerExtension");
- c.putString("extension.CertificateIssuer.numNames", "0");
- c.putString("extension.CertificateIssuer.nameType0", "");
- c.putString("extension.CertificateIssuer.name0", "");
+ * c.putString("extension.CertificateIssuer.enable", "false");
+ * c.putString("extension.CertificateIssuer.critical", "true");
+ * c.putString("extension.CertificateIssuer.type",
+ * "CRLEntryExtension");
+ * c.putString("extension.CertificateIssuer.class",
+ * "com.netscape.cms.crl.CMSCertificateIssuerExtension");
+ * c.putString("extension.CertificateIssuer.numNames", "0");
+ * c.putString("extension.CertificateIssuer.nameType0", "");
+ * c.putString("extension.CertificateIssuer.name0", "");
*/
// FreshestCRL
c.putString("extension.FreshestCRL.enable", "false");
c.putString("extension.FreshestCRL.critical", "false");
c.putString("extension.FreshestCRL.type", "CRLExtension");
c.putString("extension.FreshestCRL.class",
- "com.netscape.cms.crl.CMSFreshestCRLExtension");
+ "com.netscape.cms.crl.CMSFreshestCRLExtension");
c.putString("extension.FreshestCRL.numPoints", "0");
c.putString("extension.FreshestCRL.pointType0", "");
c.putString("extension.FreshestCRL.pointName0", "");
@@ -807,7 +808,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
try {
issuingPointClassName = c.getString(PROP_CLASS);
- issuingPointClass = (Class<CRLIssuingPoint>)Class.forName(issuingPointClassName);
+ issuingPointClass = (Class<CRLIssuingPoint>) Class.forName(issuingPointClassName);
issuingPoint = (CRLIssuingPoint) issuingPointClass.newInstance();
issuingPoint.init(this, id, c);
mCRLIssuePoints.put(id, issuingPoint);
@@ -846,7 +847,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
mCRLRepot.deleteCRLIssuingPointRecord(id);
} catch (EBaseException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("FAILED_REMOVING_CRL_IP_2", id, e.toString()));
+ CMS.getLogMessage("FAILED_REMOVING_CRL_IP_2", id, e.toString()));
}
}
}
@@ -854,7 +855,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
/**
* Returns X500 name of the Certificate Authority
* <P>
- *
+ *
* @return CA name
*/
public X500Name getX500Name() {
@@ -872,6 +873,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
/**
* Returns nickname of CA's signing cert.
* <p>
+ *
* @return CA signing cert nickname.
*/
public String getNickname() {
@@ -881,6 +883,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
/**
* Returns nickname of OCSP's signing cert.
* <p>
+ *
* @return OCSP signing cert nickname.
*/
public String getOCSPNickname() {
@@ -890,7 +893,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
/**
* Returns default signing unit used by this CA
* <P>
- *
+ *
* @return request identifier
*/
public ISigningUnit getSigningUnit() {
@@ -910,24 +913,24 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
}
/**
- * Signs CRL using the specified signature algorithm.
- * If no algorithm is specified the CA's default signing algorithm
- * is used.
+ * Signs CRL using the specified signature algorithm. If no algorithm is
+ * specified the CA's default signing algorithm is used.
* <P>
+ *
* @param crl the CRL to be signed.
- * @param algname the algorithm name to use. This is a JCA name such
- * as MD5withRSA, etc. If set to null the default signing algorithm
- * is used.
- *
+ * @param algname the algorithm name to use. This is a JCA name such as
+ * MD5withRSA, etc. If set to null the default signing algorithm
+ * is used.
+ *
* @return the signed CRL
*/
public X509CRLImpl sign(X509CRLImpl crl, String algname)
- throws EBaseException {
+ throws EBaseException {
X509CRLImpl signedcrl = null;
- IStatsSubsystem statsSub = (IStatsSubsystem)CMS.getSubsystem("stats");
+ IStatsSubsystem statsSub = (IStatsSubsystem) CMS.getSubsystem("stats");
if (statsSub != null) {
- statsSub.startTiming("signing");
+ statsSub.startTiming("signing");
}
long startTime = CMS.getCurrentDate().getTime();
@@ -976,32 +979,33 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
throw new ECAException(
CMS.getUserMessage("CMS_CA_SIGNING_CRL_FAILED", e.getMessage()));
} finally {
- if (statsSub != null) {
- statsSub.endTiming("signing");
- }
+ if (statsSub != null) {
+ statsSub.endTiming("signing");
+ }
}
return signedcrl;
}
/**
- * Signs the given certificate info using specified signing algorithm
- * If no algorithm is specified the CA's default algorithm is used.
+ * Signs the given certificate info using specified signing algorithm If no
+ * algorithm is specified the CA's default algorithm is used.
* <P>
+ *
* @param certInfo the certificate info to be signed.
- * @param algname the signing algorithm to use. These are names defined
- * in JCA, such as MD5withRSA, etc. If null the CA's default
- * signing algorithm will be used.
+ * @param algname the signing algorithm to use. These are names defined in
+ * JCA, such as MD5withRSA, etc. If null the CA's default signing
+ * algorithm will be used.
* @return signed certificate
*/
- public X509CertImpl sign(X509CertInfo certInfo, String algname)
- throws EBaseException {
+ public X509CertImpl sign(X509CertInfo certInfo, String algname)
+ throws EBaseException {
X509CertImpl signedcert = null;
- IStatsSubsystem statsSub = (IStatsSubsystem)CMS.getSubsystem("stats");
+ IStatsSubsystem statsSub = (IStatsSubsystem) CMS.getSubsystem("stats");
if (statsSub != null) {
- statsSub.startTiming("signing");
+ statsSub.startTiming("signing");
}
long startTime = CMS.getCurrentDate().getTime();
@@ -1025,20 +1029,20 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
CMS.debug("sign cert encoding cert");
certInfo.encode(tmp);
byte[] rawCert = tmp.toByteArray();
-
+
// encode algorithm identifier
CMS.debug("sign cert encoding algorithm");
alg.encode(tmp);
-
+
CMS.debug("CA cert signing: signing cert");
byte[] signature = mSigningUnit.sign(rawCert, algname);
-
+
tmp.putBitString(signature);
-
+
// Wrap the signed data in a SEQUENCE { data, algorithm, sig }
out.write(DerValue.tag_Sequence, tmp);
- //log(ILogger.LL_INFO, "CertificateAuthority: done signing");
-
+ // log(ILogger.LL_INFO, "CertificateAuthority: done signing");
+
switch (mFastSigning) {
case FASTSIGNING_DISABLED:
signedcert = new X509CertImpl(out.toByteArray());
@@ -1051,8 +1055,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
default:
break;
}
- }
- catch (NoSuchAlgorithmException e) {
+ } catch (NoSuchAlgorithmException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_SIGN_CERT", e.toString(), e.getMessage()));
throw new ECAException(
CMS.getUserMessage("CMS_CA_SIGNING_CERT_FAILED", e.getMessage()));
@@ -1065,38 +1068,41 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
throw new ECAException(
CMS.getUserMessage("CMS_CA_SIGNING_CERT_FAILED", e.getMessage()));
} finally {
- if (statsSub != null) {
- statsSub.endTiming("signing");
- }
+ if (statsSub != null) {
+ statsSub.endTiming("signing");
+ }
}
return signedcert;
}
/**
- * Sign a byte array using the specified algorithm.
- * If algorithm is null the CA's default algorithm is used.
+ * Sign a byte array using the specified algorithm. If algorithm is null the
+ * CA's default algorithm is used.
* <p>
- * @param data the data to be signed in a byte array.
+ *
+ * @param data the data to be signed in a byte array.
* @param algname the algorithm to use.
* @return the signature in a byte array.
- */
- public byte[] sign(byte[] data, String algname)
- throws EBaseException {
+ */
+ public byte[] sign(byte[] data, String algname)
+ throws EBaseException {
return mSigningUnit.sign(data, algname);
}
/**
* logs a message in the CA area.
+ *
* @param level the debug level.
* @param msg the message to debug.
*/
public void log(int level, String msg) {
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_CA,
- level, msg);
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_CA,
+ level, msg);
}
/**
* Retrieves certificate chains of this CA.
+ *
* @return this CA's cert chain.
*/
public CertificateChain getCACertChain() {
@@ -1105,18 +1111,18 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
public X509CertImpl getCACert() {
if (mCaCert != null) {
- return mCaCert;
+ return mCaCert;
}
// during configuration
try {
- String cert = mConfig.getString("signing.cert", null);
- if (cert != null) {
- return new X509CertImpl(CMS.AtoB(cert));
- }
+ String cert = mConfig.getString("signing.cert", null);
+ if (cert != null) {
+ return new X509CertImpl(CMS.AtoB(cert));
+ }
} catch (EBaseException e) {
- CMS.debug(e);
+ CMS.debug(e);
} catch (CertificateException e) {
- CMS.debug(e);
+ CMS.debug(e);
}
return null;
}
@@ -1126,10 +1132,10 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
}
public String[] getCASigningAlgorithms() {
- if (mCASigningAlgorithms != null)
+ if (mCASigningAlgorithms != null)
return mCASigningAlgorithms;
- if (mCaCert == null)
+ if (mCaCert == null)
return null; // CA not inited yet.
X509Key caPubKey = null;
@@ -1137,39 +1143,38 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
caPubKey = (X509Key) mCaCert.get(X509CertImpl.PUBLIC_KEY);
} catch (CertificateParsingException e) {
}
- if (caPubKey == null)
- return null; // something seriously wrong.
+ if (caPubKey == null)
+ return null; // something seriously wrong.
AlgorithmId alg = caPubKey.getAlgorithmId();
- if (alg == null)
- return null; // something seriously wrong.
+ if (alg == null)
+ return null; // something seriously wrong.
mCASigningAlgorithms = AlgorithmId.getSigningAlgorithms(alg);
if (mCASigningAlgorithms == null) {
CMS.debug(
- "CA - no signing algorithms for " + alg.getName());
+ "CA - no signing algorithms for " + alg.getName());
} else {
- CMS.debug(
- "CA First signing algorithm is " + mCASigningAlgorithms[0]);
+ CMS.debug(
+ "CA First signing algorithm is " + mCASigningAlgorithms[0]);
}
return mCASigningAlgorithms;
}
- //////////
- // Initialization routines.
+ // ////////
+ // Initialization routines.
//
-
/**
* init CA signing unit & cert chain.
*/
private void initSigUnit()
- throws EBaseException {
+ throws EBaseException {
try {
// init signing unit
mSigningUnit = new SigningUnit();
IConfigStore caSigningCfg =
- mConfig.getSubStore(PROP_SIGNING_SUBSTORE);
+ mConfig.getSubStore(PROP_SIGNING_SUBSTORE);
mSigningUnit.init(this, caSigningCfg);
CMS.debug("CA signing unit inited");
@@ -1188,38 +1193,38 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
CryptoManager manager = CryptoManager.getInstance();
int caChainNum =
- caSigningCfg.getInteger(PROP_CA_CHAIN_NUM, 0);
+ caSigningCfg.getInteger(PROP_CA_CHAIN_NUM, 0);
CMS.debug("cachainNum= " + caChainNum);
if (caChainNum > 0) {
// custom build chain (for cross cert chain)
// audit here ***
IConfigStore chainStore =
- caSigningCfg.getSubStore(PROP_CA_CHAIN);
+ caSigningCfg.getSubStore(PROP_CA_CHAIN);
if (chainStore == null) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_CA_CA_OCSP_CHAIN",
- "ca cert chain config error"));
+ CMS.getLogMessage("CMSCORE_CA_CA_OCSP_CHAIN",
+ "ca cert chain config error"));
throw new ECAException(
CMS.getUserMessage("CMS_CA_BUILD_CA_CHAIN_FAILED",
- "ca cert chain config error"));
+ "ca cert chain config error"));
}
java.security.cert.X509Certificate[] implchain =
- new java.security.cert.X509Certificate[caChainNum];
+ new java.security.cert.X509Certificate[caChainNum];
for (int i = 0; i < caChainNum; i++) {
String subtreeName = PROP_CA_CERT + i;
// cert file name must be full path
String certFileName =
- chainStore.getString(subtreeName, null);
+ chainStore.getString(subtreeName, null);
if ((certFileName == null) || certFileName.equals("")) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_OCSP_CHAIN", "cert file config error"));
throw new ECAException(
CMS.getUserMessage("CMS_CA_BUILD_CA_CHAIN_FAILED",
- "cert file config error"));
+ "cert file config error"));
}
byte[] b64Bytes = getCertFromFile(certFileName);
String b64String = new String(b64Bytes);
@@ -1232,11 +1237,11 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
CMS.debug("in init - custom built CA cert chain.");
} else {
// build ca chain the traditional way
- org.mozilla.jss.crypto.X509Certificate[] chain =
- manager.buildCertificateChain(mSigningUnit.getCert());
+ org.mozilla.jss.crypto.X509Certificate[] chain =
+ manager.buildCertificateChain(mSigningUnit.getCert());
// do this in case other subsyss expect a X509CertImpl
java.security.cert.X509Certificate[] implchain =
- new java.security.cert.X509Certificate[chain.length];
+ new java.security.cert.X509Certificate[chain.length];
for (int i = 0; i < chain.length; i++) {
implchain[i] = new X509CertImpl(chain[i].getEncoded());
@@ -1256,11 +1261,11 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
CMS.debug("Shared OCSP signing unit inited");
}
- org.mozilla.jss.crypto.X509Certificate[] ocspChain =
- manager.buildCertificateChain(mOCSPSigningUnit.getCert());
+ org.mozilla.jss.crypto.X509Certificate[] ocspChain =
+ manager.buildCertificateChain(mOCSPSigningUnit.getCert());
// do this in case other subsyss expect a X509CertImpl
java.security.cert.X509Certificate[] ocspImplchain =
- new java.security.cert.X509Certificate[ocspChain.length];
+ new java.security.cert.X509Certificate[ocspChain.length];
for (int i = 0; i < ocspChain.length; i++) {
ocspImplchain[i] = new X509CertImpl(ocspChain[i].getEncoded());
@@ -1319,7 +1324,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
* read ca cert from path, converts and bytes
*/
byte[] getCertFromFile(String path)
- throws FileNotFoundException, IOException {
+ throws FileNotFoundException, IOException {
File file = new File(path);
Long l = Long.valueOf(file.length());
@@ -1331,32 +1336,32 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
return b;
}
- /**
+ /**
* init default cert attributes.
*/
private void initDefCaAttrs()
- throws EBaseException {
- int version = mConfig.getInteger(PROP_X509CERT_VERSION,
+ throws EBaseException {
+ int version = mConfig.getInteger(PROP_X509CERT_VERSION,
CertificateVersion.V3);
- if (version != CertificateVersion.V1 &&
- version != CertificateVersion.V3) {
+ if (version != CertificateVersion.V1 &&
+ version != CertificateVersion.V3) {
throw new ECAException(
CMS.getUserMessage("CMS_CA_X509CERT_VERSION_NOT_SUPPORTED"));
}
try {
mDefaultCertVersion = new CertificateVersion(version - 1);
} catch (IOException e) {
- // should never occur.
+ // should never occur.
}
int validity_in_days = mConfig.getInteger(PROP_DEF_VALIDITY, 2 * 365);
mDefaultValidity = validity_in_days * DAY; // days in config file.
- mEnablePastCATime =
+ mEnablePastCATime =
mConfig.getBoolean(PROP_ENABLE_PAST_CATIME, false);
- mEnableOCSP =
+ mEnableOCSP =
mConfig.getBoolean(PROP_ENABLE_OCSP, true);
String fs = mConfig.getString(PROP_FAST_SIGNING, "");
@@ -1373,19 +1378,19 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
* init cert & crl database
*/
private void initCaDatabases()
- throws EBaseException {
+ throws EBaseException {
int certdb_inc = mConfig.getInteger(PROP_CERTDB_INC, 5);
String certReposDN = mConfig.getString(PROP_CERT_REPOS_DN, null);
- if (certReposDN == null) {
- certReposDN = "ou=certificateRepository, ou=" + getId() +
+ if (certReposDN == null) {
+ certReposDN = "ou=certificateRepository, ou=" + getId() +
", " + getDBSubsystem().getBaseDN();
}
String reposDN = mConfig.getString(PROP_REPOS_DN, null);
- if (reposDN == null) {
- reposDN = "ou=certificateRepository, ou=" + getId() +
+ if (reposDN == null) {
+ reposDN = "ou=certificateRepository, ou=" + getId() +
", " + getDBSubsystem().getBaseDN();
}
@@ -1409,15 +1414,15 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
DBSubsystem.getInstance(),
crldb_inc,
"ou=crlIssuingPoints, ou=" + getId() + ", " +
- getDBSubsystem().getBaseDN());
+ getDBSubsystem().getBaseDN());
CMS.debug("CRL Repot inited");
String replicaReposDN = mConfig.getString(PROP_REPLICAID_DN, null);
if (replicaReposDN == null) {
- replicaReposDN = "ou=Replica," + getDBSubsystem().getBaseDN();
+ replicaReposDN = "ou=Replica," + getDBSubsystem().getBaseDN();
}
mReplicaRepot = new ReplicaIDRepository(
- DBSubsystem.getInstance(), 1, replicaReposDN);
+ DBSubsystem.getInstance(), 1, replicaReposDN);
CMS.debug("Replica Repot inited");
}
@@ -1426,12 +1431,12 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
* init web gateway - just gets the ee gateway for this CA.
*/
private void initWebGateway()
- throws EBaseException {
+ throws EBaseException {
}
private void startPublish()
- throws EBaseException {
- //xxx Note that CMS411 only support ca cert publishing to ldap
+ throws EBaseException {
+ // xxx Note that CMS411 only support ca cert publishing to ldap
// if ldap publishing is not enabled while publishing isenabled
// there will be a lot of problem.
try {
@@ -1449,7 +1454,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
* init publishing
*/
private void initPublish()
- throws EBaseException {
+ throws EBaseException {
IConfigStore c = null;
try {
@@ -1467,8 +1472,8 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
} catch (ELdapException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_ERROR_PUBLISH_MODULE", e.toString()));
- //throw new ECAException(
- // CAResources.INIT_PUBLISH_MODULE_FAILED, e);
+ // throw new ECAException(
+ // CAResources.INIT_PUBLISH_MODULE_FAILED, e);
}
}
@@ -1489,7 +1494,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
while (names.hasMoreElements()) {
String id = (String) names.nextElement();
- if (Debug.ON)
+ if (Debug.ON)
Debug.trace("registering listener impl: " + id);
String cl = implc.getString(id + "." + PROP_CLASS);
@@ -1515,18 +1520,19 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
throw new Exception("Cannot initialize");
}
String className = plugin.getClassPath();
-
+
try {
IRequestListener listener = null;
- listener = (IRequestListener)
+ listener = (IRequestListener)
Class.forName(className).newInstance();
- //listener.init(id, implName, iConfig);
+ // listener.init(id, implName, iConfig);
listener.init(this, iConfig);
- // registerRequestListener(id, (IRequestListener) listener);
- //log(ILogger.LL_INFO,
- // "Listener instance " + id + " added");
+ // registerRequestListener(id, (IRequestListener)
+ // listener);
+ // log(ILogger.LL_INFO,
+ // "Listener instance " + id + " added");
} catch (Exception e) {
if (Debug.ON) {
@@ -1537,13 +1543,13 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
throw e;
}
}
-
+
}
-
+
} catch (Exception e) {
log(ILogger.LL_INFO, CMS.getLogMessage("CMSCORE_CA_CA_FAILED_LISTENER", e.toString()));
}
-
+
}
/**
@@ -1567,7 +1573,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
}
// Initialize Revoke Request notification listener
-
+
String certificateRevokedListenerClassName = nc.getString("certificateIssuedListenerClassName", "com.netscape.cms.listeners.CertificateRevokedListener");
try {
@@ -1579,7 +1585,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
// Initialize Request In Queue notification listener
IConfigStore rq = nc.getSubStore(PROP_REQ_IN_Q_SUBSTORE);
-
+
String requestInQListenerClassName = nc.getString("certificateIssuedListenerClassName", "com.netscape.cms.listeners.RequestInQListener");
try {
@@ -1598,7 +1604,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
} catch (Exception e) {
e.printStackTrace();
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_NOTIFY_FAILED"));
- // throw e;
+ // throw e;
}
}
@@ -1606,14 +1612,14 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
* initialize request queue components
*/
private void initRequestQueue()
- throws EBaseException {
+ throws EBaseException {
mPolicy = new CAPolicy();
((CAPolicy) mPolicy).init(this, mConfig.getSubStore(PROP_POLICY));
CMS.debug("CA policy inited");
mService = new CAService(this);
CMS.debug("CA service inited");
- mNotify = new ARequestNotifier (this);
+ mNotify = new ARequestNotifier(this);
CMS.debug("CA notifier inited");
mPNotify = new ARequestNotifier();
CMS.debug("CA pending notifier inited");
@@ -1622,22 +1628,22 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
try {
int reqdb_inc = mConfig.getInteger("reqdbInc", 5);
- mRequestQueue =
+ mRequestQueue =
RequestSubsystem.getInstance().getRequestQueue(
- getId(), reqdb_inc, mPolicy, mService, mNotify, mPNotify);
+ getId(), reqdb_inc, mPolicy, mService, mNotify, mPNotify);
} catch (EBaseException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_QUEUE_FAILED", e.toString()));
throw e;
}
// init request scheduler if configured
- String schedulerClass =
- mConfig.getString("requestSchedulerClass", null);
+ String schedulerClass =
+ mConfig.getString("requestSchedulerClass", null);
if (schedulerClass != null) {
- try {
+ try {
IRequestScheduler scheduler = (IRequestScheduler)
- Class.forName(schedulerClass).newInstance();
+ Class.forName(schedulerClass).newInstance();
mRequestQueue.setRequestScheduler(scheduler);
} catch (Exception e) {
@@ -1647,36 +1653,30 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
}
/*
- private void startCRL()
- throws EBaseException
- {
- Enumeration e = mCRLIssuePoints.keys();
- while (e.hasMoreElements()) {
- CRLIssuingPoint cp = (CRLIssuingPoint)
- mCRLIssuePoints.get(e.nextElement());
- cp.startup();
- }
- }
+ * private void startCRL() throws EBaseException { Enumeration e =
+ * mCRLIssuePoints.keys(); while (e.hasMoreElements()) { CRLIssuingPoint cp
+ * = (CRLIssuingPoint) mCRLIssuePoints.get(e.nextElement()); cp.startup(); }
+ * }
*/
-
+
/**
- * initialize CRL
+ * initialize CRL
*/
@SuppressWarnings("unchecked")
- private void initCRL()
- throws EBaseException {
+ private void initCRL()
+ throws EBaseException {
IConfigStore crlConfig = mConfig.getSubStore(PROP_CRL_SUBSTORE);
if ((crlConfig == null) || (crlConfig.size() <= 0)) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_NO_MASTER_CRL"));
- //throw new ECAException(CAResources.NO_CONFIG_FOR_MASTER_CRL);
+ // throw new ECAException(CAResources.NO_CONFIG_FOR_MASTER_CRL);
return;
}
Enumeration<String> issuePointIdEnum = crlConfig.getSubStoreNames();
if (issuePointIdEnum == null || !issuePointIdEnum.hasMoreElements()) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_NO_MASTER_CRL_SUBSTORE"));
- //throw new ECAException(CAResources.NO_CONFIG_FOR_MASTER_CRL);
+ // throw new ECAException(CAResources.NO_CONFIG_FOR_MASTER_CRL);
return;
}
@@ -1686,7 +1686,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
String issuePointId = (String) issuePointIdEnum.nextElement();
CMS.debug(
- "initializing crl issue point " + issuePointId);
+ "initializing crl issue point " + issuePointId);
IConfigStore issuePointConfig = null;
String issuePointClassName = null;
@SuppressWarnings("unchecked")
@@ -1700,29 +1700,28 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
issuePoint = issuePointClass.newInstance();
issuePoint.init(this, issuePointId, issuePointConfig);
mCRLIssuePoints.put(issuePointId, issuePoint);
- if (mMasterCRLIssuePoint == null &&
- issuePointId.equals(PROP_MASTER_CRL))
+ if (mMasterCRLIssuePoint == null &&
+ issuePointId.equals(PROP_MASTER_CRL))
mMasterCRLIssuePoint = issuePoint;
} catch (ClassNotFoundException e) {
throw new ECAException(
CMS.getUserMessage("CMS_CA_CRL_ISSUING_POINT_INIT_FAILED",
- issuePointId, e.toString()));
+ issuePointId, e.toString()));
} catch (InstantiationException e) {
throw new ECAException(
CMS.getUserMessage("CMS_CA_CRL_ISSUING_POINT_INIT_FAILED",
- issuePointId, e.toString()));
+ issuePointId, e.toString()));
} catch (IllegalAccessException e) {
throw new ECAException(
CMS.getUserMessage("CMS_CA_CRL_ISSUING_POINT_INIT_FAILED",
- issuePointId, e.toString()));
+ issuePointId, e.toString()));
}
}
/*
- if (mMasterCRLIssuePoint == null) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_NO_FULL_CRL", PROP_MASTER_CRL));
- throw new ECAException(CAResources.NO_CONFIG_FOR_MASTER_CRL);
- }
+ * if (mMasterCRLIssuePoint == null) { log(ILogger.LL_FAILURE,
+ * CMS.getLogMessage("CMSCORE_CA_CA_NO_FULL_CRL", PROP_MASTER_CRL));
+ * throw new ECAException(CAResources.NO_CONFIG_FOR_MASTER_CRL); }
*/
log(ILogger.LL_INFO, "CRL Issuing Points inited");
}
@@ -1747,9 +1746,8 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
return mSignTime;
}
- public long getOCSPTotalLookupTime()
- {
- return mLookupTime;
+ public long getOCSPTotalLookupTime() {
+ return mLookupTime;
}
public ResponderID getResponderIDByName() {
@@ -1769,8 +1767,8 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
public ResponderID getResponderIDByHash() {
/*
- KeyHash ::= OCTET STRING --SHA-1 hash of responder's public key
- --(excluding the tag and length fields)
+ * KeyHash ::= OCTET STRING --SHA-1 hash of responder's public key
+ * --(excluding the tag and length fields)
*/
PublicKey publicKey = getOCSPSigningUnit().getPublicKey();
MessageDigest md = null;
@@ -1790,7 +1788,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
* Process OCSPRequest.
*/
public OCSPResponse validate(OCSPRequest request)
- throws EBaseException {
+ throws EBaseException {
if (!mEnableOCSP) {
CMS.debug("Local ocsp service is disable.");
@@ -1798,23 +1796,23 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
}
mNumOCSPRequest++;
- IStatsSubsystem statsSub = (IStatsSubsystem)CMS.getSubsystem("stats");
+ IStatsSubsystem statsSub = (IStatsSubsystem) CMS.getSubsystem("stats");
long startTime = CMS.getCurrentDate().getTime();
try {
- //log(ILogger.LL_INFO, "start OCSP request");
+ // log(ILogger.LL_INFO, "start OCSP request");
TBSRequest tbsReq = request.getTBSRequest();
// (3) look into database to check the
- // certificate's status
+ // certificate's status
Vector<SingleResponse> singleResponses = new Vector<SingleResponse>();
if (statsSub != null) {
- statsSub.startTiming("lookup");
+ statsSub.startTiming("lookup");
}
long lookupStartTime = CMS.getCurrentDate().getTime();
for (int i = 0; i < tbsReq.getRequestCount(); i++) {
com.netscape.cmsutil.ocsp.Request req =
- tbsReq.getRequestAt(i);
+ tbsReq.getRequestAt(i);
CertID cid = req.getCertID();
SingleResponse sr = processRequest(cid);
@@ -1822,12 +1820,12 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
}
long lookupEndTime = CMS.getCurrentDate().getTime();
if (statsSub != null) {
- statsSub.endTiming("lookup");
+ statsSub.endTiming("lookup");
}
mLookupTime += lookupEndTime - lookupStartTime;
if (statsSub != null) {
- statsSub.startTiming("build_response");
+ statsSub.startTiming("build_response");
}
SingleResponse res[] = new SingleResponse[singleResponses.size()];
@@ -1836,16 +1834,16 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
ResponderID rid = null;
if (mByName) {
if (mResponderIDByName == null) {
- mResponderIDByName = getResponderIDByName();
+ mResponderIDByName = getResponderIDByName();
}
rid = mResponderIDByName;
} else {
if (mResponderIDByHash == null) {
- mResponderIDByHash = getResponderIDByHash();
+ mResponderIDByHash = getResponderIDByHash();
}
rid = mResponderIDByHash;
}
-
+
Extension nonce[] = null;
for (int j = 0; j < tbsReq.getExtensionsCount(); j++) {
@@ -1859,26 +1857,26 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
ResponseData rd = new ResponseData(rid,
new GeneralizedTime(CMS.getCurrentDate()), res, nonce);
if (statsSub != null) {
- statsSub.endTiming("build_response");
+ statsSub.endTiming("build_response");
}
if (statsSub != null) {
- statsSub.startTiming("signing");
+ statsSub.startTiming("signing");
}
long signStartTime = CMS.getCurrentDate().getTime();
BasicOCSPResponse basicRes = sign(rd);
long signEndTime = CMS.getCurrentDate().getTime();
mSignTime += signEndTime - signStartTime;
if (statsSub != null) {
- statsSub.endTiming("signing");
+ statsSub.endTiming("signing");
}
OCSPResponse response = new OCSPResponse(
OCSPResponseStatus.SUCCESSFUL,
new ResponseBytes(ResponseBytes.OCSP_BASIC,
- new OCTET_STRING(ASN1Util.encode(basicRes))));
+ new OCTET_STRING(ASN1Util.encode(basicRes))));
- //log(ILogger.LL_INFO, "done OCSP request");
+ // log(ILogger.LL_INFO, "done OCSP request");
long endTime = CMS.getCurrentDate().getTime();
mTotalTime += endTime - startTime;
return response;
@@ -1893,11 +1891,11 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
DerOutputStream out = new DerOutputStream();
DerOutputStream tmp = new DerOutputStream();
- String algname = mOCSPSigningUnit.getDefaultAlgorithm();
+ String algname = mOCSPSigningUnit.getDefaultAlgorithm();
byte rd_data[] = ASN1Util.encode(rd);
if (rd_data != null) {
- mTotalData += rd_data.length;
+ mTotalData += rd_data.length;
}
rd.encode(tmp);
AlgorithmId.get(algname).encode(tmp);
@@ -1911,14 +1909,14 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
DerOutputStream tmp1 = new DerOutputStream();
DerOutputStream outChain = new DerOutputStream();
java.security.cert.X509Certificate chains[] =
- mOCSPCertChain.getChain();
+ mOCSPCertChain.getChain();
for (int i = 0; i < chains.length; i++) {
tmpChain.putDerValue(new DerValue(chains[i].getEncoded()));
}
tmp1.write(DerValue.tag_Sequence, tmpChain);
tmp.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0),
- tmp1);
+ tmp1);
out.write(DerValue.tag_Sequence, tmp);
@@ -1959,7 +1957,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
} catch (EBaseException e) {
}
CRLIssuingPoint point = (CRLIssuingPoint)
- getCRLIssuingPoint(issuingPointId);
+ getCRLIssuingPoint(issuingPointId);
if (point.isCRLCacheEnabled()) {
// only do this if cache is enabled
@@ -1987,7 +1985,7 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
}
}
- try {
+ try {
ICertRecord rec = mCertRepot.readCertificateRecord(serialNo);
String status = rec.getStatus();
@@ -2015,4 +2013,3 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
return new SingleResponse(cid, certStatus, thisUpdate, nextUpdate);
}
}
-
diff --git a/pki/base/ca/src/com/netscape/ca/SigningUnit.java b/pki/base/ca/src/com/netscape/ca/SigningUnit.java
index 6b0dfc64..db756526 100644
--- a/pki/base/ca/src/com/netscape/ca/SigningUnit.java
+++ b/pki/base/ca/src/com/netscape/ca/SigningUnit.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.ca;
-
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
@@ -50,10 +49,9 @@ import com.netscape.certsrv.security.ISigningUnit;
import com.netscape.cmscore.security.JssSubsystem;
import com.netscape.cmsutil.util.Cert;
-
/**
* CA signing unit based on JSS.
- *
+ *
* $Revision$ $Date$
*/
@@ -81,8 +79,8 @@ public final class SigningUnit implements ISigningUnit {
private ISubsystem mOwner = null;
- private String mDefSigningAlgname = null;
- private SignatureAlgorithm mDefSigningAlgorithm = null;
+ private String mDefSigningAlgname = null;
+ private SignatureAlgorithm mDefSigningAlgorithm = null;
public SigningUnit() {
}
@@ -114,7 +112,7 @@ public final class SigningUnit implements ISigningUnit {
public PrivateKey getPrivateKey() {
return mPrivk;
}
-
+
public void updateConfig(String nickname, String tokenname) {
mConfig.putString(PROP_CERT_NICKNAME, nickname);
mConfig.putString(PROP_TOKEN_NAME, tokenname);
@@ -133,8 +131,8 @@ public final class SigningUnit implements ISigningUnit {
}
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
- mOwner = owner;
+ throws EBaseException {
+ mOwner = owner;
mConfig = config;
String tokenname = null;
@@ -145,23 +143,23 @@ public final class SigningUnit implements ISigningUnit {
tokenname = config.getString(PROP_TOKEN_NAME);
if (tokenname.equalsIgnoreCase(Constants.PR_INTERNAL_TOKEN) ||
- tokenname.equalsIgnoreCase("Internal Key Storage Token")) {
+ tokenname.equalsIgnoreCase("Internal Key Storage Token")) {
mToken = mManager.getInternalKeyStorageToken();
- setNewNickName(mNickname);
+ setNewNickName(mNickname);
} else {
mToken = mManager.getTokenByName(tokenname);
- mNickname = tokenname + ":" + mNickname;
- setNewNickName(mNickname);
- }
+ mNickname = tokenname + ":" + mNickname;
+ setNewNickName(mNickname);
+ }
CMS.debug(config.getName() + " Signing Unit nickname " + mNickname);
CMS.debug("Got token " + tokenname + " by name");
- PasswordCallback cb = JssSubsystem.getInstance().getPWCB();
+ PasswordCallback cb = JssSubsystem.getInstance().getPWCB();
mToken.login(cb); // ONE_TIME by default.
mCert = mManager.findCertByNickname(mNickname);
- CMS.debug("Found cert by nickname: '"+mNickname+"' with serial number: "+mCert.getSerialNumber());
+ CMS.debug("Found cert by nickname: '" + mNickname + "' with serial number: " + mCert.getSerialNumber());
mCertImpl = new X509CertImpl(mCert.getEncoded());
CMS.debug("converted to x509CertImpl");
@@ -174,38 +172,38 @@ public final class SigningUnit implements ISigningUnit {
// get def alg and check if def sign alg is valid for token.
mDefSigningAlgname = config.getString(PROP_DEFAULT_SIGNALG);
- mDefSigningAlgorithm =
+ mDefSigningAlgorithm =
checkSigningAlgorithmFromName(mDefSigningAlgname);
CMS.debug(
- "got signing algorithm " + mDefSigningAlgorithm);
+ "got signing algorithm " + mDefSigningAlgorithm);
mInited = true;
} catch (java.security.cert.CertificateException e) {
- CMS.debug("SigningUnit init: debug "+ e.toString());
+ CMS.debug("SigningUnit init: debug " + e.toString());
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_SIGNING_CA_CERT", e.getMessage()));
throw new ECAException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR", e.toString()));
} catch (CryptoManager.NotInitializedException e) {
- CMS.debug("SigningUnit init: debug "+ e.toString());
+ CMS.debug("SigningUnit init: debug " + e.toString());
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_SIGNING_TOKEN_INIT", e.toString()));
throw new ECAException(CMS.getUserMessage("CMS_CA_CRYPTO_NOT_INITIALIZED"));
} catch (IncorrectPasswordException e) {
- CMS.debug("SigningUnit init: debug "+ e.toString());
+ CMS.debug("SigningUnit init: debug " + e.toString());
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_SIGNING_WRONG_PWD", e.toString()));
throw new ECAException(CMS.getUserMessage("CMS_CA_INVALID_PASSWORD"));
} catch (NoSuchTokenException e) {
- CMS.debug("SigningUnit init: debug "+ e.toString());
+ CMS.debug("SigningUnit init: debug " + e.toString());
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_SIGNING_TOKEN_NOT_FOUND", tokenname, e.toString()));
throw new ECAException(CMS.getUserMessage("CMS_CA_TOKEN_NOT_FOUND", tokenname));
} catch (ObjectNotFoundException e) {
- CMS.debug("SigningUnit init: debug "+ e.toString());
+ CMS.debug("SigningUnit init: debug " + e.toString());
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_SIGNING_CERT_NOT_FOUND", e.toString()));
throw new ECAException(CMS.getUserMessage("CMS_CA_CERT_OBJECT_NOT_FOUND"));
} catch (TokenException e) {
- CMS.debug("SigningUnit init: debug "+ e.toString());
+ CMS.debug("SigningUnit init: debug " + e.toString());
log(ILogger.LL_FAILURE, CMS.getLogMessage("OPERATION_ERROR", e.toString()));
throw new ECAException(CMS.getUserMessage("CMS_CA_TOKEN_ERROR"));
- } catch (Exception e){
- CMS.debug("SigningUnit init: debug "+ e.toString());
- }
+ } catch (Exception e) {
+ CMS.debug("SigningUnit init: debug " + e.toString());
+ }
}
/**
@@ -218,7 +216,7 @@ public final class SigningUnit implements ISigningUnit {
* @exception EBaseException if signing algorithm is not supported.
*/
public SignatureAlgorithm checkSigningAlgorithmFromName(String algname)
- throws EBaseException {
+ throws EBaseException {
try {
SignatureAlgorithm sigalg = null;
@@ -252,7 +250,7 @@ public final class SigningUnit implements ISigningUnit {
* @param algname is expected to be one of JCA's algorithm names.
*/
public byte[] sign(byte[] data, String algname)
- throws EBaseException {
+ throws EBaseException {
if (!mInited) {
throw new EBaseException("CASigningUnit not initialized!");
}
@@ -264,11 +262,11 @@ public final class SigningUnit implements ISigningUnit {
if (algname != null) {
signAlg = checkSigningAlgorithmFromName(algname);
}
-
- // XXX use a pool of signers based on alg ?
+
+ // XXX use a pool of signers based on alg ?
// XXX Map algor. name to id. hack: use hardcoded define for now.
CMS.debug(
- "Getting algorithm context for " + algname + " " + signAlg);
+ "Getting algorithm context for " + algname + " " + signAlg);
Signature signer = mToken.getSignatureContext(signAlg);
signer.initSign(mPrivk);
@@ -294,9 +292,9 @@ public final class SigningUnit implements ISigningUnit {
throw new EBaseException(e.toString());
}
}
-
+
public boolean verify(byte[] data, byte[] signature, String algname)
- throws EBaseException {
+ throws EBaseException {
if (!mInited) {
throw new EBaseException("CASigningUnit not initialized!");
}
@@ -337,8 +335,8 @@ public final class SigningUnit implements ISigningUnit {
private void log(int level, String msg) {
if (mLogger == null)
return;
- mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_CA,
- level, "CASigningUnit: " + msg);
+ mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_CA,
+ level, "CASigningUnit: " + msg);
}
/**
@@ -356,15 +354,15 @@ public final class SigningUnit implements ISigningUnit {
}
public void setDefaultAlgorithm(String algorithm) throws EBaseException {
- mConfig.putString(PROP_DEFAULT_SIGNALG, algorithm);
+ mConfig.putString(PROP_DEFAULT_SIGNALG, algorithm);
mDefSigningAlgname = algorithm;
- log(ILogger.LL_INFO,
- "Default signing algorithm is set to " + algorithm);
+ log(ILogger.LL_INFO,
+ "Default signing algorithm is set to " + algorithm);
}
/**
* get all possible algorithms for the CA signing key type.
- */
+ */
public String[] getAllAlgorithms() throws EBaseException {
byte[] keybytes = mPubk.getEncoded();
X509Key key = new X509Key();
@@ -389,4 +387,3 @@ public final class SigningUnit implements ISigningUnit {
return Cert.mapAlgorithmToJss(algname);
}
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/acls/ACL.java b/pki/base/common/src/com/netscape/certsrv/acls/ACL.java
index 4200b94a..8f415a7c 100644
--- a/pki/base/common/src/com/netscape/certsrv/acls/ACL.java
+++ b/pki/base/common/src/com/netscape/certsrv/acls/ACL.java
@@ -17,22 +17,19 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.acls;
-
import java.util.Enumeration;
import java.util.Vector;
-
/**
- * A class represents an access control list (ACL). An ACL
- * is associated with an protected resources. The policy
- * enforcer can verify the ACLs with the current
- * context to see if the corresponding resource is accessible.
+ * A class represents an access control list (ACL). An ACL is associated with an
+ * protected resources. The policy enforcer can verify the ACLs with the current
+ * context to see if the corresponding resource is accessible.
* <P>
- * An <code>ACL</code> may contain one or more <code>ACLEntry</code>.
- * However, in case of multiple <code>ACLEntry</code>, a subject must
- * pass ALL of the <code>ACLEntry</code> evaluation for permission
- * to be granted
+ * An <code>ACL</code> may contain one or more <code>ACLEntry</code>. However,
+ * in case of multiple <code>ACLEntry</code>, a subject must pass ALL of the
+ * <code>ACLEntry</code> evaluation for permission to be granted
* <P>
+ *
* @version $Revision$, $Date$
*/
public class ACL implements IACL, java.io.Serializable {
@@ -44,7 +41,8 @@ public class ACL implements IACL, java.io.Serializable {
protected Vector<ACLEntry> mEntries = new Vector<ACLEntry>(); // ACL entries
protected Vector<String> mRights = null; // possible rights entries
- protected String mResourceACLs = null; // exact resourceACLs string on ldap server
+ protected String mResourceACLs = null; // exact resourceACLs string on ldap
+ // server
protected String mName = null; // resource name
protected String mDescription = null; // resource description
@@ -55,17 +53,15 @@ public class ACL implements IACL, java.io.Serializable {
}
/**
- * Class constructor.
- * Constructs an access control list associated
- * with a resource name
+ * Class constructor. Constructs an access control list associated with a
+ * resource name
+ *
* @param name resource name
* @param rights applicable rights defined for this resource
* @param resourceACLs the entire ACL specification. For example:
- * "certServer.log.configuration:read,modify:
- * allow (read,modify)
- * group=\"Administrators\":
- * Allow administrators to read and modify log
- * configuration"
+ * "certServer.log.configuration:read,modify: allow (read,modify)
+ * group=\"Administrators\": Allow administrators to read and
+ * modify log configuration"
*/
public ACL(String name, Vector<String> rights, String resourceACLs) {
setName(name);
@@ -79,17 +75,17 @@ public class ACL implements IACL, java.io.Serializable {
}
/**
- * Sets the name of the resource governed by this
- * access control.
+ * Sets the name of the resource governed by this access control.
+ *
* @param name name of the resource
*/
public void setName(String name) {
mName = name;
}
-
+
/**
- * Retrieves the name of the resource governed by
- * this access control.
+ * Retrieves the name of the resource governed by this access control.
+ *
* @return name of the resource
*/
public String getName() {
@@ -98,6 +94,7 @@ public class ACL implements IACL, java.io.Serializable {
/**
* Retrieves the exact string of the resourceACLs
+ *
* @return resource's acl
*/
public String getResourceACLs() {
@@ -105,17 +102,18 @@ public class ACL implements IACL, java.io.Serializable {
}
/**
- * Sets the description of the resource governed by this
- * access control.
+ * Sets the description of the resource governed by this access control.
+ *
* @param description Description of the protected resource
*/
public void setDescription(String description) {
mDescription = description;
}
-
+
/**
- * Retrieves the description of the resource governed by
- * this access control.
+ * Retrieves the description of the resource governed by this access
+ * control.
+ *
* @return Description of the protected resource
*/
public String getDescription() {
@@ -124,6 +122,7 @@ public class ACL implements IACL, java.io.Serializable {
/**
* Adds an ACL entry to this list.
+ *
* @param entry the <code>ACLEntry</code> to be added to this resource
*/
public void addEntry(ACLEntry entry) {
@@ -132,6 +131,7 @@ public class ACL implements IACL, java.io.Serializable {
/**
* Returns ACL entries.
+ *
* @return enumeration for the <code>ACLEntry</code> vector
*/
public Enumeration<ACLEntry> entries() {
@@ -140,9 +140,9 @@ public class ACL implements IACL, java.io.Serializable {
/**
* Returns the string reprsentation.
- * @return the string representation of the ACL entries in the
- * following format:
- * <resource name>[<ACLEntry1>,<ACLEntry 2>,...<ACLEntry N>]
+ *
+ * @return the string representation of the ACL entries in the following
+ * format: <resource name>[<ACLEntry1>,<ACLEntry 2>,...<ACLEntry N>]
*/
public String toString() {
String entries = "";
@@ -160,6 +160,7 @@ public class ACL implements IACL, java.io.Serializable {
/**
* Adds an rights entry to this list.
+ *
* @param right The right to be added for this ACL
*/
public void addRight(String right) {
@@ -168,6 +169,7 @@ public class ACL implements IACL, java.io.Serializable {
/**
* Tells if the permission is one of the defined "rights"
+ *
* @param permission permission to be checked
* @return true if it's one of the "rights"; false otherwise
*/
@@ -177,6 +179,7 @@ public class ACL implements IACL, java.io.Serializable {
/**
* Returns rights entries.
+ *
* @return enumeration of rights defined for this ACL
*/
public Enumeration<String> rights() {
diff --git a/pki/base/common/src/com/netscape/certsrv/acls/ACLEntry.java b/pki/base/common/src/com/netscape/certsrv/acls/ACLEntry.java
index d689493b..2246a13c 100644
--- a/pki/base/common/src/com/netscape/certsrv/acls/ACLEntry.java
+++ b/pki/base/common/src/com/netscape/certsrv/acls/ACLEntry.java
@@ -17,15 +17,14 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.acls;
-
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.StringTokenizer;
-
/**
* A class represents an ACI entry of an access control list.
* <P>
+ *
* @version $Revision$, $Date$
*/
public class ACLEntry implements IACLEntry, java.io.Serializable {
@@ -47,8 +46,9 @@ public class ACLEntry implements IACLEntry, java.io.Serializable {
/**
* Checks if this ACL entry is set to negative.
- * @return true if this ACL entry expression is for "deny";
- * false if this ACL entry expression is for "allow"
+ *
+ * @return true if this ACL entry expression is for "deny"; false if this
+ * ACL entry expression is for "allow"
*/
public boolean isNegative() {
return mNegative;
@@ -63,8 +63,10 @@ public class ACLEntry implements IACLEntry, java.io.Serializable {
/**
* Sets the ACL entry string
+ *
* @param s string in the following format:
- * <PRE>
+ *
+ * <PRE>
* allow|deny (right[,right...]) attribute_expression
* </PRE>
*/
@@ -72,10 +74,12 @@ public class ACLEntry implements IACLEntry, java.io.Serializable {
mACLEntryString = s;
}
- /**
+ /**
* Gets the ACL Entry String
+ *
* @return ACL Entry string in the following format:
- * <PRE>
+ *
+ * <PRE>
* allow|deny (right[,right...]) attribute_expression
* </PRE>
*/
@@ -84,11 +88,12 @@ public class ACLEntry implements IACLEntry, java.io.Serializable {
}
/**
- * Adds permission to this entry. Permission must be one of the
- * "rights" defined for each protected resource in its ACL
+ * Adds permission to this entry. Permission must be one of the "rights"
+ * defined for each protected resource in its ACL
+ *
* @param acl the acl instance that this aclEntry is associated with
- * @param permission one of the "rights" defined for each
- * protected resource in its ACL
+ * @param permission one of the "rights" defined for each protected resource
+ * in its ACL
*/
public void addPermission(IACL acl, String permission) {
if (acl.checkRight(permission) == true) {
@@ -99,8 +104,8 @@ public class ACLEntry implements IACLEntry, java.io.Serializable {
}
/**
- * Returns a list of permissions associated with
- * this entry.
+ * Returns a list of permissions associated with this entry.
+ *
* @return a list of permissions for this ACL entry
*/
public Enumeration<String> permissions() {
@@ -109,8 +114,9 @@ public class ACLEntry implements IACLEntry, java.io.Serializable {
/**
* Sets the expression associated with this entry.
+ *
* @param expressions the evaluator expressions. For example,
- * group="Administrators"
+ * group="Administrators"
*/
public void setAttributeExpressions(String expressions) {
mExpressions = expressions;
@@ -118,20 +124,21 @@ public class ACLEntry implements IACLEntry, java.io.Serializable {
/**
* Retrieves the expression associated with this entry.
- * @return the evaluator expressions. For example,
- * group="Administrators"
+ *
+ * @return the evaluator expressions. For example, group="Administrators"
*/
public String getAttributeExpressions() {
return mExpressions;
}
/**
- * Checks to see if this <code>ACLEntry</code> contains a
- * particular permission
- * @param permission one of the "rights" defined for each
- * protected resource in its ACL
- * @return true if permission contained in the permission list
- * for this <code>ACLEntry</code>; false otherwise.
+ * Checks to see if this <code>ACLEntry</code> contains a particular
+ * permission
+ *
+ * @param permission one of the "rights" defined for each protected resource
+ * in its ACL
+ * @return true if permission contained in the permission list for this
+ * <code>ACLEntry</code>; false otherwise.
*/
public boolean containPermission(String permission) {
return (mPerms.get(permission) != null);
@@ -139,15 +146,16 @@ public class ACLEntry implements IACLEntry, java.io.Serializable {
/**
* Checks if this entry has the given permission.
- * @param permission one of the "rights" defined for each
- * protected resource in its ACL
- * @return true if the permission is allowed; false if the
- * permission is denied. If a permission is not
- * recognized by this ACL, it is considered denied
+ *
+ * @param permission one of the "rights" defined for each protected resource
+ * in its ACL
+ * @return true if the permission is allowed; false if the permission is
+ * denied. If a permission is not recognized by this ACL, it is
+ * considered denied
*/
public boolean checkPermission(String permission) {
// default - if we dont know about the requested permission,
- // don't grant permission
+ // don't grant permission
if (mPerms.get(permission) == null)
return false;
if (isNegative()) {
@@ -159,10 +167,13 @@ public class ACLEntry implements IACLEntry, java.io.Serializable {
/**
* Parse string in the following format:
+ *
* <PRE>
* allow|deny (right[,right...]) attribute_expression
* </PRE>
+ *
* into an instance of the <code>ACLEntry</code> class
+ *
* @param acl the acl instance associated with this aclentry
* @param aclEntryString aclEntryString in the specified format
* @return an instance of the <code>ACLEntry</code> class
@@ -175,7 +186,7 @@ public class ACLEntry implements IACLEntry, java.io.Serializable {
String te = aclEntryString.trim();
// locate first space
- int i = te.indexOf(' ');
+ int i = te.indexOf(' ');
// prefix should be "allowed" or "deny"
String prefix = te.substring(0, i);
String suffix = te.substring(i + 1).trim();
@@ -189,7 +200,7 @@ public class ACLEntry implements IACLEntry, java.io.Serializable {
return null;
}
// locate the second space
- i = suffix.indexOf(' ');
+ i = suffix.indexOf(' ');
// this prefix should be rights list, delimited by ","
prefix = suffix.substring(1, i - 1);
// the suffix is the rest, which is the "expressions"
@@ -206,6 +217,7 @@ public class ACLEntry implements IACLEntry, java.io.Serializable {
/**
* Returns the string representation of this ACLEntry
+ *
* @return string representation of this ACLEntry
*/
public String toString() {
diff --git a/pki/base/common/src/com/netscape/certsrv/acls/ACLsResources.java b/pki/base/common/src/com/netscape/certsrv/acls/ACLsResources.java
index 878fe163..9dc6d4ee 100644
--- a/pki/base/common/src/com/netscape/certsrv/acls/ACLsResources.java
+++ b/pki/base/common/src/com/netscape/certsrv/acls/ACLsResources.java
@@ -20,10 +20,9 @@ package com.netscape.certsrv.acls;
import java.util.ListResourceBundle;
/**
- * A class represents a resource bundle for the entire ACL component.
- * system.
+ * A class represents a resource bundle for the entire ACL component. system.
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
@@ -31,13 +30,14 @@ public class ACLsResources extends ListResourceBundle {
/**
* Returns the content of this resource.
+ *
* @return the content of this resource.
*/
public Object[][] getContents() {
return contents;
}
- /**
+ /**
* A set of constants for localized error messages.
*/
static final Object[][] contents = {};
diff --git a/pki/base/common/src/com/netscape/certsrv/acls/EACLsException.java b/pki/base/common/src/com/netscape/certsrv/acls/EACLsException.java
index e79bd724..96a9b7b9 100644
--- a/pki/base/common/src/com/netscape/certsrv/acls/EACLsException.java
+++ b/pki/base/common/src/com/netscape/certsrv/acls/EACLsException.java
@@ -17,21 +17,18 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.acls;
-
import java.util.Locale;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.MessageFormatter;
-
/**
- * A class represents an acls exception. Note that this is
- * an Runtime exception so that methods used AccessManager
- * do not have to explicity declare this exception. This
- * allows AccessManager to be easily integrated into any
+ * A class represents an acls exception. Note that this is an Runtime exception
+ * so that methods used AccessManager do not have to explicity declare this
+ * exception. This allows AccessManager to be easily integrated into any
* existing code.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class EACLsException extends EBaseException {
@@ -44,10 +41,11 @@ public class EACLsException extends EBaseException {
* resource class name
*/
private static final String ACL_RESOURCES = ACLsResources.class.getName();
-
+
/**
* Constructs an acls exception.
* <P>
+ *
* @param msgFormat exception details
*/
public EACLsException(String msgFormat) {
@@ -57,11 +55,12 @@ public class EACLsException extends EBaseException {
/**
* Constructs a base exception with a parameter. For example,
+ *
* <PRE>
- * new EACLsException("failed to load {0}", fileName);
+ * new EACLsException(&quot;failed to load {0}&quot;, fileName);
* </PRE>
* <P>
- *
+ *
* @param msgFormat exception details in message string format
* @param param message string parameter
*/
@@ -72,9 +71,9 @@ public class EACLsException extends EBaseException {
}
/**
- * Constructs a base exception. It can be used to carry
- * a system exception that may contain information about
- * the context. For example,
+ * Constructs a base exception. It can be used to carry a system exception
+ * that may contain information about the context. For example,
+ *
* <PRE>
* try {
* ...
@@ -83,7 +82,7 @@ public class EACLsException extends EBaseException {
* }
* </PRE>
* <P>
- *
+ *
* @param msgFormat exception details in message string format
* @param param system exception
*/
@@ -94,10 +93,10 @@ public class EACLsException extends EBaseException {
}
/**
- * Constructs a base exception with a list of parameters
- * that will be substituted into the message format.
+ * Constructs a base exception with a list of parameters that will be
+ * substituted into the message format.
* <P>
- *
+ *
* @param msgFormat exception details in message string format
* @param params list of message format parameters
*/
@@ -109,7 +108,7 @@ public class EACLsException extends EBaseException {
/**
* Returns a list of parameters.
* <P>
- *
+ *
* @return list of message format parameters
*/
public Object[] getParameters() {
@@ -118,6 +117,7 @@ public class EACLsException extends EBaseException {
/**
* String representation for the corresponding exception.
+ *
* @return String representation for the corresponding exception.
*/
public String toString() {
@@ -126,6 +126,7 @@ public class EACLsException extends EBaseException {
/**
* Returns string representation for the corresponding exception.
+ *
* @param locale client specified locale for string representation.
* @return String representation for the corresponding exception.
*/
@@ -136,6 +137,7 @@ public class EACLsException extends EBaseException {
/**
* Return the class name of the resource bundle.
+ *
* @return class name of the resource bundle.
*/
protected String getBundleName() {
diff --git a/pki/base/common/src/com/netscape/certsrv/acls/IACL.java b/pki/base/common/src/com/netscape/certsrv/acls/IACL.java
index d336fc26..32b6ad3d 100644
--- a/pki/base/common/src/com/netscape/certsrv/acls/IACL.java
+++ b/pki/base/common/src/com/netscape/certsrv/acls/IACL.java
@@ -17,49 +17,52 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.acls;
-
import java.util.Enumeration;
-
/**
- * A class represents an access control list (ACL). An ACL
- * is associated with a protected resource. The policy
- * enforcer can verify the ACLs with the current
- * context to see if the corresponding resource is accessible.
+ * A class represents an access control list (ACL). An ACL is associated with a
+ * protected resource. The policy enforcer can verify the ACLs with the current
+ * context to see if the corresponding resource is accessible.
* <P>
*
* @version $Revision$, $Date$
*/
-public interface IACL {
+public interface IACL {
/**
* Returns the name of the current ACL.
+ *
* @return the name of the current ACL.
*/
public String getName();
/**
* Returns the description of the current ACL.
+ *
* @return the description of the current ACL.
*/
- public String getDescription();
+ public String getDescription();
/**
* Returns a list of access rights of the current ACL.
+ *
* @return a list of access rights
*/
- public Enumeration<String> rights();
+ public Enumeration<String> rights();
/**
* Returns a list of entries of the current ACL.
+ *
* @return a list of entries
*/
public Enumeration<ACLEntry> entries();
/**
* Verifies if permission is granted.
+ *
* @param permission one of the applicable rights
- * @return true if the given permission is one of the applicable rights; false otherwise.
+ * @return true if the given permission is one of the applicable rights;
+ * false otherwise.
*/
public boolean checkRight(String permission);
}
diff --git a/pki/base/common/src/com/netscape/certsrv/acls/IACLEntry.java b/pki/base/common/src/com/netscape/certsrv/acls/IACLEntry.java
index f91ef38b..ff806f15 100644
--- a/pki/base/common/src/com/netscape/certsrv/acls/IACLEntry.java
+++ b/pki/base/common/src/com/netscape/certsrv/acls/IACLEntry.java
@@ -17,19 +17,17 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.acls;
-
-
-
/**
* A class represents an entry of access control list.
* <P>
*
* @version $Revision$, $Date$
*/
-public interface IACLEntry {
+public interface IACLEntry {
/**
* Returns the ACL entry string of the entry.
+ *
* @return the ACL entry string of the entry.
*/
public String getACLEntryString();
diff --git a/pki/base/common/src/com/netscape/certsrv/apps/CMS.java b/pki/base/common/src/com/netscape/certsrv/apps/CMS.java
index f093bb74..8ba3d06b 100644
--- a/pki/base/common/src/com/netscape/certsrv/apps/CMS.java
+++ b/pki/base/common/src/com/netscape/certsrv/apps/CMS.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.apps;
-
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.math.BigInteger;
@@ -98,18 +97,15 @@ import com.netscape.certsrv.usrgrp.IUGSubsystem;
import com.netscape.cmsutil.net.ISocketFactory;
import com.netscape.cmsutil.password.IPasswordStore;
-
/**
- * This represents the CMS server. Plugins can access other
- * public objects such as subsystems via this inteface.
- * This object also include a set of utility functions.
- *
- * This object does not include the actual implementation.
- * It acts as a public interface for plugins, and the
- * actual implementation is in the CMS engine
- * (com.netscape.cmscore.apps.CMSEngine) that implements
- * ICMSEngine interface.
- *
+ * This represents the CMS server. Plugins can access other public objects such
+ * as subsystems via this inteface. This object also include a set of utility
+ * functions.
+ *
+ * This object does not include the actual implementation. It acts as a public
+ * interface for plugins, and the actual implementation is in the CMS engine
+ * (com.netscape.cmscore.apps.CMSEngine) that implements ICMSEngine interface.
+ *
* @version $Revision$, $Date$
*/
public final class CMS {
@@ -129,7 +125,7 @@ public final class CMS {
public static final String SUBSYSTEM_KRA = IKeyRecoveryAuthority.ID;
public static final String SUBSYSTEM_OCSP = IOCSPAuthority.ID;
public static final String SUBSYSTEM_TKS = ITKSAuthority.ID;
- public static final String SUBSYSTEM_UG = IUGSubsystem.ID;
+ public static final String SUBSYSTEM_UG = IUGSubsystem.ID;
public static final String SUBSYSTEM_AUTH = IAuthSubsystem.ID;
public static final String SUBSYSTEM_AUTHZ = IAuthzSubsystem.ID;
public static final String SUBSYSTEM_REGISTRY = IPluginRegistry.ID;
@@ -141,7 +137,7 @@ public final class CMS {
/**
* Private constructor.
- *
+ *
* @param engine CMS engine implementation
*/
private CMS(ICMSEngine engine) {
@@ -149,8 +145,9 @@ public final class CMS {
}
/**
- * This method is used for unit tests. It allows the underlying _engine
- * to be stubbed out.
+ * This method is used for unit tests. It allows the underlying _engine to
+ * be stubbed out.
+ *
* @param engine The stub engine to set, for testing.
*/
public static void setCMSEngine(ICMSEngine engine) {
@@ -159,7 +156,7 @@ public final class CMS {
/**
* Gets this ID .
- *
+ *
* @return CMS engine identifier
*/
public static String getId() {
@@ -167,9 +164,9 @@ public final class CMS {
}
/**
- * Sets the identifier of this subsystem. Should never be called.
- * Returns error.
- *
+ * Sets the identifier of this subsystem. Should never be called. Returns
+ * error.
+ *
* @param id CMS engine identifier
*/
public static void setId(String id) throws EBaseException {
@@ -178,14 +175,14 @@ public final class CMS {
/**
* Initialize all static, dynamic and final static subsystems.
- *
+ *
* @param owner null
* @param config main config store.
- * @exception EBaseException if any error occur in subsystems during
- * initialization.
+ * @exception EBaseException if any error occur in subsystems during
+ * initialization.
*/
- public static void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ public static void init(ISubsystem owner, IConfigStore config)
+ throws EBaseException {
_engine.init(owner, config);
}
@@ -195,7 +192,7 @@ public final class CMS {
/**
* Starts up all subsystems. subsystems must be initialized.
- *
+ *
* @exception EBaseException if any subsystem fails to startup.
*/
public static void startup() throws EBaseException {
@@ -217,10 +214,10 @@ public final class CMS {
}
/**
- * Checks to ensure that all new incoming requests have been blocked.
- * This method is used for reentrancy protection.
+ * Checks to ensure that all new incoming requests have been blocked. This
+ * method is used for reentrancy protection.
* <P>
- *
+ *
* @return true or false
*/
public static boolean areRequestsDisabled() {
@@ -228,34 +225,33 @@ public final class CMS {
}
/**
- * Shuts down subsystems in backwards order
- * exceptions are ignored. process exists at end to force exit.
+ * Shuts down subsystems in backwards order exceptions are ignored. process
+ * exists at end to force exit.
*/
public static void shutdown() {
_engine.shutdown();
}
/**
- * Shuts down subsystems in backwards order
- * exceptions are ignored. process exists at end to force exit.
+ * Shuts down subsystems in backwards order exceptions are ignored. process
+ * exists at end to force exit.
*/
- public static void forceShutdown() {
+ public static void forceShutdown() {
- _engine.forceShutdown();
- }
+ _engine.forceShutdown();
+ }
- /**
- * mode = 0 (pre-operational)
- * mode = 1 (running)
- */
- public static void setCSState(int mode) {
- _engine.setCSState(mode);
- }
+ /**
+ * mode = 0 (pre-operational) mode = 1 (running)
+ */
+ public static void setCSState(int mode) {
+ _engine.setCSState(mode);
+ }
- public static int getCSState() {
- return _engine.getCSState();
- }
+ public static int getCSState() {
+ return _engine.getCSState();
+ }
public static boolean isPreOpMode() {
return _engine.isPreOpMode();
@@ -266,10 +262,9 @@ public final class CMS {
}
/**
- * Is the server in running state. After server startup, the
- * server will be initialization state first. After the
- * initialization state, the server will be in the running
- * state.
+ * Is the server in running state. After server startup, the server will be
+ * initialization state first. After the initialization state, the server
+ * will be in the running state.
*
* @return true if the server is in the running state
*/
@@ -278,10 +273,9 @@ public final class CMS {
}
/**
- * Returns the logger of the current server. The logger can
- * be used to log critical informational or critical error
- * messages.
- *
+ * Returns the logger of the current server. The logger can be used to log
+ * critical informational or critical error messages.
+ *
* @return logger
*/
public static ILogger getLogger() {
@@ -289,10 +283,9 @@ public final class CMS {
}
/**
- * Returns the signed audit logger of the current server. This logger can
- * be used to log critical informational or critical error
- * messages.
- *
+ * Returns the signed audit logger of the current server. This logger can be
+ * used to log critical informational or critical error messages.
+ *
* @return signed audit logger
*/
public static ILogger getSignedAuditLogger() {
@@ -301,7 +294,7 @@ public final class CMS {
/**
* Creates a repository record in the internal database.
- *
+ *
* @return repository record
*/
public static IRepositoryRecord createRepositoryRecord() {
@@ -310,8 +303,10 @@ public final class CMS {
/**
* Parse ACL resource attributes
+ *
* @param resACLs same format as the resourceACLs attribute:
- * <PRE>
+ *
+ * <PRE>
* <resource name>:<permission1,permission2,...permissionn>:
* <allow|deny> (<subset of the permission set>) <evaluator expression>
* </PRE>
@@ -324,7 +319,7 @@ public final class CMS {
/**
* Creates an issuing poing record.
- *
+ *
* @return issuing record
*/
public static ICRLIssuingPointRecord createCRLIssuingPointRecord(String id, BigInteger crlNumber, Long crlSize, Date thisUpdate, Date nextUpdate) {
@@ -333,7 +328,7 @@ public final class CMS {
/**
* Retrieves the default CRL issuing point record name.
- *
+ *
* @return CRL issuing point record name
*/
public static String getCRLIssuingPointRecordName() {
@@ -342,7 +337,7 @@ public final class CMS {
/**
* Retrieves the process id of this server.
- *
+ *
* @return process id of the server
*/
public static int getpid() {
@@ -351,7 +346,7 @@ public final class CMS {
/**
* Retrieves the instance roort path of this server.
- *
+ *
* @return instance directory path name
*/
public static String getInstanceDir() {
@@ -359,9 +354,9 @@ public final class CMS {
}
/**
- * Returns a server wide system time. Plugins should call
- * this method to retrieve system time.
- *
+ * Returns a server wide system time. Plugins should call this method to
+ * retrieve system time.
+ *
* @return current time
*/
public static Date getCurrentDate() {
@@ -372,7 +367,7 @@ public final class CMS {
/**
* Puts data of an byte array into the debug file.
- *
+ *
* @param data byte array to be recorded in the debug file
*/
public static void debug(byte data[]) {
@@ -382,7 +377,7 @@ public final class CMS {
/**
* Puts a message into the debug file.
- *
+ *
* @param msg debugging message
*/
public static void debug(String msg) {
@@ -392,7 +387,7 @@ public final class CMS {
/**
* Puts a message into the debug file.
- *
+ *
* @param level 0-10 (0 is less detail, 10 is more detail)
* @param msg debugging message
*/
@@ -403,7 +398,7 @@ public final class CMS {
/**
* Puts an exception into the debug file.
- *
+ *
* @param e exception
*/
public static void debug(Throwable e) {
@@ -413,7 +408,7 @@ public final class CMS {
/**
* Checks if the debug mode is on or not.
- *
+ *
* @return true if debug mode is on
*/
public static boolean debugOn() {
@@ -430,42 +425,45 @@ public final class CMS {
_engine.debugStackTrace();
}
- /*
- * If debugging for the particular realm is enabled, output name/value
- * pair info to the debug file. This is useful to dump out what hidden
- * config variables the server is looking at, or what HTTP variables it
- * is expecting to find, or what database attributes it is looking for.
- * @param type indicates what the source of key/val is. For example,
- * this could be 'CS.cfg', or something else. In the debug
- * subsystem, there is a mechanism to filter this so only the types
- * you care about are listed
- * @param key the 'key' of the hashtable which is being accessed.
- * This could be the name of the config parameter, or the http param
- * name.
- * @param val the value of the parameter
+ /*
+ * If debugging for the particular realm is enabled, output name/value pair
+ * info to the debug file. This is useful to dump out what hidden config
+ * variables the server is looking at, or what HTTP variables it is
+ * expecting to find, or what database attributes it is looking for.
+ *
+ * @param type indicates what the source of key/val is. For example, this
+ * could be 'CS.cfg', or something else. In the debug subsystem, there is a
+ * mechanism to filter this so only the types you care about are listed
+ *
+ * @param key the 'key' of the hashtable which is being accessed. This could
+ * be the name of the config parameter, or the http param name.
+ *
+ * @param val the value of the parameter
+ *
* @param default the default value if the param is not found
- */
+ */
public static void traceHashKey(String type, String key) {
if (_engine != null) {
- _engine.traceHashKey(type, key);
- }
- }
+ _engine.traceHashKey(type, key);
+ }
+ }
+
public static void traceHashKey(String type, String key, String val) {
if (_engine != null) {
- _engine.traceHashKey(type, key, val);
- }
- }
+ _engine.traceHashKey(type, key, val);
+ }
+ }
+
public static void traceHashKey(String type, String key, String val, String def) {
if (_engine != null) {
- _engine.traceHashKey(type, key, val, def);
- }
- }
-
+ _engine.traceHashKey(type, key, val, def);
+ }
+ }
/**
* Returns the names of all the registered subsystems.
- *
+ *
* @return a list of string-based subsystem names
*/
public static Enumeration<String> getSubsystemNames() {
@@ -478,7 +476,7 @@ public final class CMS {
/**
* Returns all the registered subsystems.
- *
+ *
* @return a list of ISubsystem-based subsystems
*/
public static Enumeration<ISubsystem> getSubsystems() {
@@ -487,7 +485,7 @@ public final class CMS {
/**
* Retrieves the registered subsytem with the given name.
- *
+ *
* @param name subsystem name
* @return subsystem of the given name
*/
@@ -497,7 +495,7 @@ public final class CMS {
/**
* Retrieves the localized user message from UserMessages.properties.
- *
+ *
* @param msgID message id defined in UserMessages.properties
* @return localized user message
*/
@@ -509,7 +507,7 @@ public final class CMS {
/**
* Retrieves the localized user message from UserMessages.properties.
- *
+ *
* @param locale end-user locale
* @param msgID message id defined in UserMessages.properties
* @return localized user message
@@ -522,7 +520,7 @@ public final class CMS {
/**
* Retrieves the localized user message from UserMessages.properties.
- *
+ *
* @param msgID message id defined in UserMessages.properties
* @param p1 1st parameter
* @return localized user message
@@ -535,7 +533,7 @@ public final class CMS {
/**
* Retrieves the localized user message from UserMessages.properties.
- *
+ *
* @param locale end-user locale
* @param msgID message id defined in UserMessages.properties
* @param p1 1st parameter
@@ -549,7 +547,7 @@ public final class CMS {
/**
* Retrieves the localized user message from UserMessages.properties.
- *
+ *
* @param msgID message id defined in UserMessages.properties
* @param p1 1st parameter
* @param p2 2nd parameter
@@ -563,7 +561,7 @@ public final class CMS {
/**
* Retrieves the localized user message from UserMessages.properties.
- *
+ *
* @param locale end-user locale
* @param msgID message id defined in UserMessages.properties
* @param p1 1st parameter
@@ -578,7 +576,7 @@ public final class CMS {
/**
* Retrieves the localized user message from UserMessages.properties.
- *
+ *
* @param msgID message id defined in UserMessages.properties
* @param p1 1st parameter
* @param p2 2nd parameter
@@ -593,15 +591,14 @@ public final class CMS {
public static LDAPConnection getBoundConnection(String host, int port,
int version, LDAPSSLSocketFactoryExt fac, String bindDN,
- String bindPW) throws LDAPException
- {
- return _engine.getBoundConnection(host, port, version, fac,
+ String bindPW) throws LDAPException {
+ return _engine.getBoundConnection(host, port, version, fac,
bindDN, bindPW);
}
/**
* Retrieves the localized user message from UserMessages.properties.
- *
+ *
* @param locale end-user locale
* @param msgID message id defined in UserMessages.properties
* @param p1 1st parameter
@@ -617,7 +614,7 @@ public final class CMS {
/**
* Retrieves the localized user message from UserMessages.properties.
- *
+ *
* @param msgID message id defined in UserMessages.properties
* @param p an array of parameters
* @return localized user message
@@ -630,7 +627,7 @@ public final class CMS {
/**
* Retrieves the localized user message from UserMessages.properties.
- *
+ *
* @param locale end-user locale
* @param msgID message id defined in UserMessages.properties
* @param p an array of parameters
@@ -644,7 +641,7 @@ public final class CMS {
/**
* Retrieves the centralized log message from LogMessages.properties.
- *
+ *
* @param msgID message id defined in LogMessages.properties
* @return localized log message
*/
@@ -654,7 +651,7 @@ public final class CMS {
/**
* Retrieves the centralized log message from LogMessages.properties.
- *
+ *
* @param msgID message id defined in LogMessages.properties
* @param p an array of parameters
* @return localized log message
@@ -665,7 +662,7 @@ public final class CMS {
/**
* Retrieves the centralized log message from LogMessages.properties.
- *
+ *
* @param msgID message id defined in LogMessages.properties
* @param p1 1st parameter
* @return localized log message
@@ -676,7 +673,7 @@ public final class CMS {
/**
* Retrieves the centralized log message from LogMessages.properties.
- *
+ *
* @param msgID message id defined in LogMessages.properties
* @param p1 1st parameter
* @param p2 2nd parameter
@@ -688,7 +685,7 @@ public final class CMS {
/**
* Retrieves the centralized log message from LogMessages.properties.
- *
+ *
* @param msgID message id defined in LogMessages.properties
* @param p1 1st parameter
* @param p2 2nd parameter
@@ -701,7 +698,7 @@ public final class CMS {
/**
* Retrieves the centralized log message from LogMessages.properties.
- *
+ *
* @param msgID message id defined in LogMessages.properties
* @param p1 1st parameter
* @param p2 2nd parameter
@@ -715,7 +712,7 @@ public final class CMS {
/**
* Retrieves the centralized log message from LogMessages.properties.
- *
+ *
* @param msgID message id defined in LogMessages.properties
* @param p1 1st parameter
* @param p2 2nd parameter
@@ -730,7 +727,7 @@ public final class CMS {
/**
* Retrieves the centralized log message from LogMessages.properties.
- *
+ *
* @param msgID message id defined in LogMessages.properties
* @param p1 1st parameter
* @param p2 2nd parameter
@@ -746,7 +743,7 @@ public final class CMS {
/**
* Retrieves the centralized log message from LogMessages.properties.
- *
+ *
* @param msgID message id defined in LogMessages.properties
* @param p1 1st parameter
* @param p2 2nd parameter
@@ -763,7 +760,7 @@ public final class CMS {
/**
* Retrieves the centralized log message from LogMessages.properties.
- *
+ *
* @param msgID message id defined in LogMessages.properties
* @param p1 1st parameter
* @param p2 2nd parameter
@@ -781,7 +778,7 @@ public final class CMS {
/**
* Retrieves the centralized log message from LogMessages.properties.
- *
+ *
* @param msgID message id defined in LogMessages.properties
* @param p1 1st parameter
* @param p2 2nd parameter
@@ -800,7 +797,7 @@ public final class CMS {
/**
* Returns the main config store. It is a handle to CMS.cfg.
- *
+ *
* @return configuration store
*/
public static IConfigStore getConfigStore() {
@@ -809,7 +806,7 @@ public final class CMS {
/**
* Retrieves time server started up.
- *
+ *
* @return last startup time
*/
public static long getStartupTime() {
@@ -818,41 +815,41 @@ public final class CMS {
/**
* Retrieves the HTTP Connection for use with connector.
- *
+ *
* @param authority remote authority
* @param factory socket factory
* @return http connection to the remote authority
*/
- public static IHttpConnection getHttpConnection(IRemoteAuthority authority,
- ISocketFactory factory) {
+ public static IHttpConnection getHttpConnection(IRemoteAuthority authority,
+ ISocketFactory factory) {
return _engine.getHttpConnection(authority, factory);
}
/**
* Retrieves the HTTP Connection for use with connector.
- *
+ *
* @param authority remote authority
* @param factory socket factory
* @param timeout return error if connection cannot be established within
- * the timeout period
+ * the timeout period
* @return http connection to the remote authority
*/
- public static IHttpConnection getHttpConnection(IRemoteAuthority authority,
- ISocketFactory factory, int timeout) {
+ public static IHttpConnection getHttpConnection(IRemoteAuthority authority,
+ ISocketFactory factory, int timeout) {
return _engine.getHttpConnection(authority, factory, timeout);
}
/**
* Retrieves the request sender for use with connector.
- *
+ *
* @param authority local authority
* @param nickname nickname of the client certificate
* @param remote remote authority
* @param interval timeout interval
* @return resender
*/
- public static IResender getResender(IAuthority authority, String nickname,
- IRemoteAuthority remote, int interval) {
+ public static IResender getResender(IAuthority authority, String nickname,
+ IRemoteAuthority remote, int interval) {
return _engine.getResender(authority, nickname, remote, interval);
}
@@ -867,7 +864,7 @@ public final class CMS {
/**
* Sets the nickname of the server's server certificate.
- *
+ *
* @param tokenName name of token where the certificate is located
* @param nickName name of server certificate
*/
@@ -877,7 +874,7 @@ public final class CMS {
/**
* Sets the nickname of the server's server certificate.
- *
+ *
* @param newName new nickname of server certificate
*/
public static void setServerCertNickname(String newName) {
@@ -886,7 +883,7 @@ public final class CMS {
/**
* Retrieves the host name of the server's secure end entity service.
- *
+ *
* @return host name of end-entity service
*/
public static String getEEHost() {
@@ -895,7 +892,7 @@ public final class CMS {
/**
* Retrieves the host name of the server's non-secure end entity service.
- *
+ *
* @return host name of end-entity non-secure service
*/
public static String getEENonSSLHost() {
@@ -904,7 +901,7 @@ public final class CMS {
/**
* Retrieves the IP address of the server's non-secure end entity service.
- *
+ *
* @return ip address of end-entity non-secure service
*/
public static String getEENonSSLIP() {
@@ -913,7 +910,7 @@ public final class CMS {
/**
* Retrieves the port number of the server's non-secure end entity service.
- *
+ *
* @return port of end-entity non-secure service
*/
public static String getEENonSSLPort() {
@@ -922,7 +919,7 @@ public final class CMS {
/**
* Retrieves the host name of the server's secure end entity service.
- *
+ *
* @return port of end-entity secure service
*/
public static String getEESSLHost() {
@@ -931,7 +928,7 @@ public final class CMS {
/**
* Retrieves the host name of the server's secure end entity service.
- *
+ *
* @return port of end-entity secure service
*/
public static String getEEClientAuthSSLPort() {
@@ -940,7 +937,7 @@ public final class CMS {
/**
* Retrieves the IP address of the server's secure end entity service.
- *
+ *
* @return ip address of end-entity secure service
*/
public static String getEESSLIP() {
@@ -949,7 +946,7 @@ public final class CMS {
/**
* Retrieves the port number of the server's secure end entity service.
- *
+ *
* @return port of end-entity secure service
*/
public static String getEESSLPort() {
@@ -958,7 +955,7 @@ public final class CMS {
/**
* Retrieves the host name of the server's agent service.
- *
+ *
* @return host name of agent service
*/
public static String getAgentHost() {
@@ -967,7 +964,7 @@ public final class CMS {
/**
* Retrieves the IP address of the server's agent service.
- *
+ *
* @return ip address of agent service
*/
public static String getAgentIP() {
@@ -976,7 +973,7 @@ public final class CMS {
/**
* Retrieves the port number of the server's agent service.
- *
+ *
* @return port of agent service
*/
public static String getAgentPort() {
@@ -985,7 +982,7 @@ public final class CMS {
/**
* Retrieves the host name of the server's administration service.
- *
+ *
* @return host name of administration service
*/
public static String getAdminHost() {
@@ -994,7 +991,7 @@ public final class CMS {
/**
* Retrieves the IP address of the server's administration service.
- *
+ *
* @return ip address of administration service
*/
public static String getAdminIP() {
@@ -1003,7 +1000,7 @@ public final class CMS {
/**
* Retrieves the port number of the server's administration service.
- *
+ *
* @return port of administration service
*/
public static String getAdminPort() {
@@ -1012,7 +1009,7 @@ public final class CMS {
/**
* Creates a general name constraints.
- *
+ *
* @param generalNameChoice type of general name
* @param value general name string
* @return general name object
@@ -1024,14 +1021,14 @@ public final class CMS {
/**
* Creates a general name.
- *
+ *
* @param generalNameChoice type of general name
* @param value general name string
* @return general name object
* @exception EBaseException failed to create general name
*/
public static GeneralName form_GeneralName(String generalNameChoice,
- String value) throws EBaseException {
+ String value) throws EBaseException {
return _engine.form_GeneralName(generalNameChoice, value);
}
@@ -1041,25 +1038,25 @@ public final class CMS {
* @param name configuration name
* @param params configuration parameters
*/
- public static void getSubjAltNameConfigDefaultParams(String name,
- Vector<String> params) {
+ public static void getSubjAltNameConfigDefaultParams(String name,
+ Vector<String> params) {
_engine.getSubjAltNameConfigDefaultParams(name, params);
}
/**
* Get extended plugin info for subject alt name configuration.
- *
+ *
* @param name configuration name
* @param params configuration parameters
*/
- public static void getSubjAltNameConfigExtendedPluginInfo(String name,
- Vector<String> params) {
+ public static void getSubjAltNameConfigExtendedPluginInfo(String name,
+ Vector<String> params) {
_engine.getSubjAltNameConfigExtendedPluginInfo(name, params);
}
/**
* Creates subject alt name configuration.
- *
+ *
* @param name configuration name
* @param config configuration store
* @param isValueConfigured true if value is configured
@@ -1072,162 +1069,161 @@ public final class CMS {
/**
* Retrieves default general name configuration.
- *
+ *
* @param name configuration name
* @param isValueConfigured true if value is configured
* @param params configuration parameters
* @exception EBaseException failed to create subject alt name configuration
*/
public static void getGeneralNameConfigDefaultParams(String name,
- boolean isValueConfigured, Vector<String> params) {
+ boolean isValueConfigured, Vector<String> params) {
_engine.getGeneralNameConfigDefaultParams(name,
- isValueConfigured, params);
+ isValueConfigured, params);
}
/**
* Retrieves default general names configuration.
- *
+ *
* @param name configuration name
* @param isValueConfigured true if value is configured
* @param params configuration parameters
* @exception EBaseException failed to create subject alt name configuration
*/
public static void getGeneralNamesConfigDefaultParams(String name,
- boolean isValueConfigured, Vector<String> params) {
+ boolean isValueConfigured, Vector<String> params) {
_engine.getGeneralNamesConfigDefaultParams(name,
- isValueConfigured, params);
+ isValueConfigured, params);
}
/**
* Retrieves extended plugin info for general name configuration.
- *
+ *
* @param name configuration name
* @param isValueConfigured true if value is configured
* @param info configuration parameters
* @exception EBaseException failed to create subject alt name configuration
*/
public static void getGeneralNameConfigExtendedPluginInfo(String name,
- boolean isValueConfigured, Vector<String> info) {
+ boolean isValueConfigured, Vector<String> info) {
_engine.getGeneralNameConfigExtendedPluginInfo(name,
- isValueConfigured, info);
+ isValueConfigured, info);
}
/**
* Retrieves extended plugin info for general name configuration.
- *
+ *
* @param name configuration name
* @param isValueConfigured true if value is configured
* @param info configuration parameters
* @exception EBaseException failed to create subject alt name configuration
*/
public static void getGeneralNamesConfigExtendedPluginInfo(String name,
- boolean isValueConfigured, Vector<String> info) {
+ boolean isValueConfigured, Vector<String> info) {
_engine.getGeneralNamesConfigExtendedPluginInfo(name,
- isValueConfigured, info);
+ isValueConfigured, info);
}
/**
* Created general names configuration.
- *
+ *
* @param name configuration name
* @param config configuration store
* @param isValueConfigured true if value is configured
* @param isPolicyEnabled true if policy is enabled
* @exception EBaseException failed to create subject alt name configuration
*/
- public static IGeneralNamesConfig createGeneralNamesConfig(String name,
- IConfigStore config, boolean isValueConfigured,
- boolean isPolicyEnabled) throws EBaseException {
+ public static IGeneralNamesConfig createGeneralNamesConfig(String name,
+ IConfigStore config, boolean isValueConfigured,
+ boolean isPolicyEnabled) throws EBaseException {
return _engine.createGeneralNamesConfig(name, config, isValueConfigured,
isPolicyEnabled);
}
/**
* Created general name constraints configuration.
- *
+ *
* @param name configuration name
* @param config configuration store
* @param isValueConfigured true if value is configured
* @param isPolicyEnabled true if policy is enabled
* @exception EBaseException failed to create subject alt name configuration
*/
- public static IGeneralNameAsConstraintsConfig createGeneralNameAsConstraintsConfig(String name, IConfigStore config, boolean isValueConfigured,
- boolean isPolicyEnabled) throws EBaseException {
+ public static IGeneralNameAsConstraintsConfig createGeneralNameAsConstraintsConfig(String name, IConfigStore config, boolean isValueConfigured,
+ boolean isPolicyEnabled) throws EBaseException {
return _engine.createGeneralNameAsConstraintsConfig(
name, config, isValueConfigured, isPolicyEnabled);
}
/**
* Created general name constraints configuration.
- *
+ *
* @param name configuration name
* @param config configuration store
* @param isValueConfigured true if value is configured
* @param isPolicyEnabled true if policy is enabled
* @exception EBaseException failed to create subject alt name configuration
*/
- public static IGeneralNamesAsConstraintsConfig createGeneralNamesAsConstraintsConfig(String name, IConfigStore config, boolean isValueConfigured,
- boolean isPolicyEnabled) throws EBaseException {
+ public static IGeneralNamesAsConstraintsConfig createGeneralNamesAsConstraintsConfig(String name, IConfigStore config, boolean isValueConfigured,
+ boolean isPolicyEnabled) throws EBaseException {
return _engine.createGeneralNamesAsConstraintsConfig(
name, config, isValueConfigured, isPolicyEnabled);
}
/**
* Returns the finger print of the given certificate.
- *
- * @param cert certificate
+ *
+ * @param cert certificate
* @return finger print of certificate
*/
public static String getFingerPrint(Certificate cert)
- throws CertificateEncodingException, NoSuchAlgorithmException {
+ throws CertificateEncodingException, NoSuchAlgorithmException {
return _engine.getFingerPrint(cert);
}
/**
* Returns the finger print of the given certificate.
- *
- * @param certDer DER byte array of the certificate
+ *
+ * @param certDer DER byte array of the certificate
* @return finger print of certificate
*/
public static String getFingerPrints(byte[] certDer)
- throws NoSuchAlgorithmException {
+ throws NoSuchAlgorithmException {
return _engine.getFingerPrints(certDer);
}
/**
* Returns the finger print of the given certificate.
- *
- * @param cert certificate
+ *
+ * @param cert certificate
* @return finger print of certificate
*/
public static String getFingerPrints(Certificate cert)
- throws NoSuchAlgorithmException, CertificateEncodingException {
+ throws NoSuchAlgorithmException, CertificateEncodingException {
return _engine.getFingerPrints(cert);
}
- /**
- * Creates a HTTP PKI Message that can be sent to a remote
- * authority.
- *
+ /**
+ * Creates a HTTP PKI Message that can be sent to a remote authority.
+ *
* @return a new PKI Message for remote authority
*/
public static IPKIMessage getHttpPKIMessage() {
return _engine.getHttpPKIMessage();
}
- /**
- * Creates a request encoder. A request cannot be sent to
- * the remote authority in its regular format.
- *
+ /**
+ * Creates a request encoder. A request cannot be sent to the remote
+ * authority in its regular format.
+ *
* @return a request encoder
*/
public static IRequestEncoder getHttpRequestEncoder() {
return _engine.getHttpRequestEncoder();
}
- /**
+ /**
* Converts a BER-encoded byte array into a MIME-64 encoded string.
- *
+ *
* @param data data in byte array format
* @return base-64 encoding for the data
*/
@@ -1235,9 +1231,9 @@ public final class CMS {
return _engine.BtoA(data);
}
- /**
+ /**
* Converts a MIME-64 encoded string into a BER-encoded byte array.
- *
+ *
* @param data base-64 encoding for the data
* @return data data in byte array format
*/
@@ -1246,42 +1242,40 @@ public final class CMS {
}
/**
- * Retrieves the ldap connection information from the configuration
- * store.
- *
+ * Retrieves the ldap connection information from the configuration store.
+ *
* @param config configuration parameters of ldap connection
* @return a LDAP connection info
*/
public static ILdapConnInfo getLdapConnInfo(IConfigStore config)
- throws EBaseException, ELdapException {
+ throws EBaseException, ELdapException {
return _engine.getLdapConnInfo(config);
}
/**
- * Creates a LDAP SSL socket with the given nickname. The
- * certificate associated with the nickname will be used
- * for client authentication.
- *
+ * Creates a LDAP SSL socket with the given nickname. The certificate
+ * associated with the nickname will be used for client authentication.
+ *
* @param certNickname nickname of client certificate
* @return LDAP SSL socket factory
*/
- public static LDAPSSLSocketFactoryExt getLdapJssSSLSocketFactory(
- String certNickname) {
+ public static LDAPSSLSocketFactoryExt getLdapJssSSLSocketFactory(
+ String certNickname) {
return _engine.getLdapJssSSLSocketFactory(certNickname);
}
/**
* Creates a LDAP SSL socket.
- *
+ *
* @return LDAP SSL socket factory
*/
- public static LDAPSSLSocketFactoryExt getLdapJssSSLSocketFactory() {
+ public static LDAPSSLSocketFactoryExt getLdapJssSSLSocketFactory() {
return _engine.getLdapJssSSLSocketFactory();
}
/**
* Creates a LDAP Auth Info object.
- *
+ *
* @return LDAP authentication info
*/
public static ILdapAuthInfo getLdapAuthInfo() {
@@ -1290,27 +1284,27 @@ public final class CMS {
/**
* Retrieves the LDAP connection factory.
- *
+ *
* @return bound LDAP connection pool
*/
public static ILdapConnFactory getLdapBoundConnFactory()
- throws ELdapException {
+ throws ELdapException {
return _engine.getLdapBoundConnFactory();
}
/**
* Retrieves the LDAP connection factory.
- *
+ *
* @return anonymous LDAP connection pool
*/
public static ILdapConnFactory getLdapAnonConnFactory()
- throws ELdapException {
+ throws ELdapException {
return _engine.getLdapAnonConnFactory();
}
/**
* Retrieves the default X.509 certificate template.
- *
+ *
* @return default certificate template
*/
public static X509CertInfo getDefaultX509CertInfo() {
@@ -1318,9 +1312,9 @@ public final class CMS {
}
/**
- * Retrieves the certifcate in MIME-64 encoded format
- * with header and footer.
- *
+ * Retrieves the certifcate in MIME-64 encoded format with header and
+ * footer.
+ *
* @param cert certificate
* @return base-64 format certificate
*/
@@ -1328,25 +1322,24 @@ public final class CMS {
return _engine.getEncodedCert(cert);
}
- /**
- * Verifies all system certs
- * with tags defined in <subsystemtype>.cert.list
- */
+ /**
+ * Verifies all system certs with tags defined in <subsystemtype>.cert.list
+ */
public static boolean verifySystemCerts() {
return _engine.verifySystemCerts();
}
- /**
- * Verify a system cert by tag name
- * with tags defined in <subsystemtype>.cert.list
- */
+ /**
+ * Verify a system cert by tag name with tags defined in
+ * <subsystemtype>.cert.list
+ */
public static boolean verifySystemCertByTag(String tag) {
return _engine.verifySystemCertByTag(tag);
}
- /**
- * Verify a system cert by certificate nickname
- */
+ /**
+ * Verify a system cert by certificate nickname
+ */
public static boolean verifySystemCertByNickname(String nickname, String certificateUsage) {
return _engine.verifySystemCertByNickname(nickname, certificateUsage);
}
@@ -1360,7 +1353,7 @@ public final class CMS {
/**
* Checks if the given certificate is a signing certificate.
- *
+ *
* @param cert certificate
* @return true if the given certificate is a signing certificate
*/
@@ -1370,7 +1363,7 @@ public final class CMS {
/**
* Checks if the given certificate is an encryption certificate.
- *
+ *
* @param cert certificate
* @return true if the given certificate is an encryption certificate
*/
@@ -1380,7 +1373,7 @@ public final class CMS {
/**
* Retrieves the email form processor.
- *
+ *
* @return email form processor
*/
public static IEmailFormProcessor getEmailFormProcessor() {
@@ -1389,7 +1382,7 @@ public final class CMS {
/**
* Retrieves the email form template.
- *
+ *
* @return email template
*/
public static IEmailTemplate getEmailTemplate(String path) {
@@ -1398,7 +1391,7 @@ public final class CMS {
/**
* Retrieves the email notification handler.
- *
+ *
* @return email notification
*/
public static IMailNotification getMailNotification() {
@@ -1407,7 +1400,7 @@ public final class CMS {
/**
* Retrieves the email key resolver.
- *
+ *
* @return email key resolver
*/
public static IEmailResolverKeys getEmailResolverKeys() {
@@ -1416,19 +1409,19 @@ public final class CMS {
/**
* Checks if the given OID is valid.
- *
+ *
* @param attrName attribute name
* @param value attribute value
* @return object identifier of the given attrName
*/
- public static ObjectIdentifier checkOID(String attrName, String value)
- throws EBaseException {
+ public static ObjectIdentifier checkOID(String attrName, String value)
+ throws EBaseException {
return _engine.checkOID(attrName, value);
}
/**
* Retrieves the email resolver that checks for subjectAlternateName.
- *
+ *
* @return email key resolver
*/
public static IEmailResolver getReqCertSANameEmailResolver() {
@@ -1437,7 +1430,7 @@ public final class CMS {
/**
* Retrieves the extension pretty print handler.
- *
+ *
* @param e extension
* @param indent indentation
* @return extension pretty print handler
@@ -1445,10 +1438,10 @@ public final class CMS {
public static IExtPrettyPrint getExtPrettyPrint(Extension e, int indent) {
return _engine.getExtPrettyPrint(e, indent);
}
-
+
/**
* Retrieves the certificate pretty print handler.
- *
+ *
* @param delimiter delimiter
* @return certificate pretty print handler
*/
@@ -1458,7 +1451,7 @@ public final class CMS {
/**
* Retrieves the CRL pretty print handler.
- *
+ *
* @param crl CRL
* @return CRL pretty print handler
*/
@@ -1468,7 +1461,7 @@ public final class CMS {
/**
* Retrieves the CRL cache pretty print handler.
- *
+ *
* @param ip CRL issuing point
* @return CRL pretty print handler
*/
@@ -1478,7 +1471,7 @@ public final class CMS {
/**
* Retrieves the certificate pretty print handler.
- *
+ *
* @param cert certificate
* @return certificate pretty print handler
*/
@@ -1496,7 +1489,7 @@ public final class CMS {
/**
* Retrieves the password check.
- *
+ *
* @return default password checker
*/
public static IPasswordCheck getPasswordChecker() {
@@ -1505,7 +1498,7 @@ public final class CMS {
/**
* Puts a password entry into the single-sign on cache.
- *
+ *
* @param tag password tag
* @param pw password
*/
@@ -1524,7 +1517,7 @@ public final class CMS {
/**
* Retrieves command queue
- *
+ *
* @return command queue
*/
public static ICommandQueue getCommandQueue() {
@@ -1533,25 +1526,20 @@ public final class CMS {
/**
* Loads the configuration file and starts CMS's core implementation.
- *
+ *
* @param path path to configuration file (CMS.cfg)
* @exception EBaseException failed to start CMS
*/
public static void start(String path) throws EBaseException {
- //FileConfigStore mainConfig = null;
-/*
- try {
- mainConfig = new FileConfigStore(path);
- } catch (EBaseException e) {
- e.printStackTrace();
- System.out.println(
- "Error: The Server is not fully configured.\n" +
- "Finish configuring server using Configure Setup Wizard in " +
- "the Certificate Server Console.");
- System.out.println(e.toString());
- System.exit(0);
- }
-*/
+ // FileConfigStore mainConfig = null;
+ /*
+ * try { mainConfig = new FileConfigStore(path); } catch (EBaseException
+ * e) { e.printStackTrace(); System.out.println(
+ * "Error: The Server is not fully configured.\n" +
+ * "Finish configuring server using Configure Setup Wizard in " +
+ * "the Certificate Server Console."); System.out.println(e.toString());
+ * System.exit(0); }
+ */
String classname = "com.netscape.cmscore.apps.CMSEngine";
@@ -1559,7 +1547,7 @@ public final class CMS {
try {
ICMSEngine engine = (ICMSEngine)
- Class.forName(classname).newInstance();
+ Class.forName(classname).newInstance();
cms = new CMS(engine);
IConfigStore mainConfig = createFileConfigStore(path);
@@ -1568,16 +1556,16 @@ public final class CMS {
} catch (EBaseException e) { // catch everything here purposely
CMS.debug("CMS:Caught EBaseException");
- CMS.debug(e);
+ CMS.debug(e);
- // Raidzilla Bug #57592: Always print error message to stdout.
+ // Raidzilla Bug #57592: Always print error message to stdout.
System.out.println(e.toString());
shutdown();
throw e;
- } catch (Exception e) { // catch everything here purposely
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(bos);
+ } catch (Exception e) { // catch everything here purposely
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ PrintStream ps = new PrintStream(bos);
e.printStackTrace(ps);
System.out.println(Constants.SERVER_SHUTDOWN_MESSAGE);
@@ -1609,7 +1597,7 @@ public final class CMS {
public static void setListOfVerifiedCerts(int size, long interval, long unknownStateInterval) {
_engine.setListOfVerifiedCerts(size, interval, unknownStateInterval);
}
-
+
public static IPasswordStore getPasswordStore() {
return _engine.getPasswordStore();
}
diff --git a/pki/base/common/src/com/netscape/certsrv/apps/ICMSEngine.java b/pki/base/common/src/com/netscape/certsrv/apps/ICMSEngine.java
index 7f5e4605..b764e7a4 100644
--- a/pki/base/common/src/com/netscape/certsrv/apps/ICMSEngine.java
+++ b/pki/base/common/src/com/netscape/certsrv/apps/ICMSEngine.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.apps;
-
import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
@@ -81,135 +80,135 @@ import com.netscape.cmsutil.net.ISocketFactory;
import com.netscape.cmsutil.password.IPasswordStore;
/**
- * This interface represents the CMS core framework. The
- * framework contains a set of services that provide
- * the foundation of a security application.
+ * This interface represents the CMS core framework. The framework contains a
+ * set of services that provide the foundation of a security application.
* <p>
- * The engine implementation is loaded by CMS at startup.
- * It is responsible for starting up all the related
- * subsystems.
+ * The engine implementation is loaded by CMS at startup. It is responsible for
+ * starting up all the related subsystems.
* <p>
- *
+ *
* @version $Revision$, $Date$
*/
public interface ICMSEngine extends ISubsystem {
/**
* Gets this ID .
- *
+ *
* @return CMS engine identifier
*/
public String getId();
/**
- * Sets the identifier of this subsystem. Should never be called.
- * Returns error.
- *
+ * Sets the identifier of this subsystem. Should never be called. Returns
+ * error.
+ *
* @param id CMS engine identifier
*/
public void setId(String id) throws EBaseException;
/**
* Retrieves the process id of this server.
- *
+ *
* @return process id of the server
*/
public int getpid();
public void reinit(String id) throws EBaseException;
+
public int getCSState();
+
public void setCSState(int mode);
+
public boolean isPreOpMode();
+
public boolean isRunningMode();
+
/**
* Retrieves the instance roort path of this server.
- *
+ *
* @return instance directory path name
*/
public String getInstanceDir();
/**
- * Returns a server wide system time. Plugins should call
- * this method to retrieve system time.
- *
+ * Returns a server wide system time. Plugins should call this method to
+ * retrieve system time.
+ *
* @return current time
*/
public Date getCurrentDate();
/**
* Retrieves time server started up.
- *
+ *
* @return last startup time
*/
public long getStartupTime();
/**
- * Is the server in running state. After server startup, the
- * server will be initialization state first. After the
- * initialization state, the server will be in the running
- * state.
- *
+ * Is the server in running state. After server startup, the server will be
+ * initialization state first. After the initialization state, the server
+ * will be in the running state.
+ *
* @return true if the server is in the running state
*/
public boolean isInRunningState();
/**
* Returns the names of all the registered subsystems.
- *
+ *
* @return a list of string-based subsystem names
*/
public Enumeration<String> getSubsystemNames();
/**
* Returns all the registered subsystems.
- *
+ *
* @return a list of ISubsystem-based subsystems
*/
public Enumeration<ISubsystem> getSubsystems();
/**
* Retrieves the registered subsytem with the given name.
- *
+ *
* @param name subsystem name
* @return subsystem of the given name
*/
public ISubsystem getSubsystem(String name);
/**
- * Returns the logger of the current server. The logger can
- * be used to log critical informational or critical error
- * messages.
- *
+ * Returns the logger of the current server. The logger can be used to log
+ * critical informational or critical error messages.
+ *
* @return logger
*/
public ILogger getLogger();
/**
- * Returns the signed audit logger of the current server. This logger can
- * be used to log critical informational or critical error
- * messages.
- *
+ * Returns the signed audit logger of the current server. This logger can be
+ * used to log critical informational or critical error messages.
+ *
* @return signed audit logger
*/
public ILogger getSignedAuditLogger();
/**
* Puts data of an byte array into the debug file.
- *
+ *
* @param data byte array to be recorded in the debug file
*/
public void debug(byte data[]);
/**
* Puts a message into the debug file.
- *
+ *
* @param msg debugging message
*/
public void debug(String msg);
/**
* Puts a message into the debug file.
- *
+ *
* @param level 0-10
* @param msg debugging message
*/
@@ -217,14 +216,14 @@ public interface ICMSEngine extends ISubsystem {
/**
* Puts an exception into the debug file.
- *
+ *
* @param e exception
*/
public void debug(Throwable e);
/**
* Checks if the debug mode is on or not.
- *
+ *
* @return true if debug mode is on
*/
public boolean debugOn();
@@ -234,20 +233,20 @@ public interface ICMSEngine extends ISubsystem {
*/
public void debugStackTrace();
-
- /**
- * Dump name/value pair debug information to debug file
- */
+ /**
+ * Dump name/value pair debug information to debug file
+ */
public void traceHashKey(String type, String key);
+
public void traceHashKey(String type, String key, String val);
- public void traceHashKey(String type, String key, String val, String def);
+ public void traceHashKey(String type, String key, String val, String def);
public byte[] getPKCS7(Locale locale, IRequest req);
/**
* Retrieves the localized user message from UserMessages.properties.
- *
+ *
* @param locale end-user locale
* @param msgID message id defined in UserMessages.properties
* @return localized user message
@@ -256,7 +255,7 @@ public interface ICMSEngine extends ISubsystem {
/**
* Retrieves the localized user message from UserMessages.properties.
- *
+ *
* @param locale end-user locale
* @param msgID message id defined in UserMessages.properties
* @param p an array of parameters
@@ -266,7 +265,7 @@ public interface ICMSEngine extends ISubsystem {
/**
* Retrieves the localized user message from UserMessages.properties.
- *
+ *
* @param locale end-user locale
* @param msgID message id defined in UserMessages.properties
* @param p1 1st parameter
@@ -276,7 +275,7 @@ public interface ICMSEngine extends ISubsystem {
/**
* Retrieves the localized user message from UserMessages.properties.
- *
+ *
* @param locale end-user locale
* @param msgID message id defined in UserMessages.properties
* @param p1 1st parameter
@@ -287,7 +286,7 @@ public interface ICMSEngine extends ISubsystem {
/**
* Retrieves the localized user message from UserMessages.properties.
- *
+ *
* @param locale end-user locale
* @param msgID message id defined in UserMessages.properties
* @param p1 1st parameter
@@ -299,7 +298,7 @@ public interface ICMSEngine extends ISubsystem {
/**
* Retrieves the centralized log message from LogMessages.properties.
- *
+ *
* @param msgID message id defined in LogMessages.properties
* @return localized log message
*/
@@ -307,7 +306,7 @@ public interface ICMSEngine extends ISubsystem {
/**
* Retrieves the centralized log message from LogMessages.properties.
- *
+ *
* @param msgID message id defined in LogMessages.properties
* @param p an array of parameters
* @return localized log message
@@ -316,7 +315,7 @@ public interface ICMSEngine extends ISubsystem {
/**
* Retrieves the centralized log message from LogMessages.properties.
- *
+ *
* @param msgID message id defined in LogMessages.properties
* @param p1 1st parameter
* @return localized log message
@@ -325,7 +324,7 @@ public interface ICMSEngine extends ISubsystem {
/**
* Retrieves the centralized log message from LogMessages.properties.
- *
+ *
* @param msgID message id defined in LogMessages.properties
* @param p1 1st parameter
* @param p2 2nd parameter
@@ -335,7 +334,7 @@ public interface ICMSEngine extends ISubsystem {
/**
* Retrieves the centralized log message from LogMessages.properties.
- *
+ *
* @param msgID message id defined in LogMessages.properties
* @param p1 1st parameter
* @param p2 2nd parameter
@@ -346,7 +345,7 @@ public interface ICMSEngine extends ISubsystem {
/**
* Retrieves the centralized log message from LogMessages.properties.
- *
+ *
* @param msgID message id defined in LogMessages.properties
* @param p1 1st parameter
* @param p2 2nd parameter
@@ -358,7 +357,7 @@ public interface ICMSEngine extends ISubsystem {
/**
* Retrieves the centralized log message from LogMessages.properties.
- *
+ *
* @param msgID message id defined in LogMessages.properties
* @param p1 1st parameter
* @param p2 2nd parameter
@@ -371,7 +370,7 @@ public interface ICMSEngine extends ISubsystem {
/**
* Retrieves the centralized log message from LogMessages.properties.
- *
+ *
* @param msgID message id defined in LogMessages.properties
* @param p1 1st parameter
* @param p2 2nd parameter
@@ -385,7 +384,7 @@ public interface ICMSEngine extends ISubsystem {
/**
* Retrieves the centralized log message from LogMessages.properties.
- *
+ *
* @param msgID message id defined in LogMessages.properties
* @param p1 1st parameter
* @param p2 2nd parameter
@@ -400,7 +399,7 @@ public interface ICMSEngine extends ISubsystem {
/**
* Retrieves the centralized log message from LogMessages.properties.
- *
+ *
* @param msgID message id defined in LogMessages.properties
* @param p1 1st parameter
* @param p2 2nd parameter
@@ -416,7 +415,7 @@ public interface ICMSEngine extends ISubsystem {
/**
* Retrieves the centralized log message from LogMessages.properties.
- *
+ *
* @param msgID message id defined in LogMessages.properties
* @param p1 1st parameter
* @param p2 2nd parameter
@@ -433,8 +432,10 @@ public interface ICMSEngine extends ISubsystem {
/**
* Parse ACL resource attributes
+ *
* @param resACLs same format as the resourceACLs attribute:
- * <PRE>
+ *
+ * <PRE>
* <resource name>:<permission1,permission2,...permissionn>:
* <allow|deny> (<subset of the permission set>) <evaluator expression>
* </PRE>
@@ -445,71 +446,71 @@ public interface ICMSEngine extends ISubsystem {
/**
* Creates an issuing poing record.
- *
+ *
* @return issuing record
*/
public ICRLIssuingPointRecord createCRLIssuingPointRecord(String id, BigInteger crlNumber, Long crlSize, Date thisUpdate, Date nextUpdate);
/**
* Retrieves the default CRL issuing point record name.
- *
+ *
* @return CRL issuing point record name
*/
public String getCRLIssuingPointRecordName();
/**
* Returns the finger print of the given certificate.
- *
+ *
* @param cert certificate
* @return finger print of certificate
*/
public String getFingerPrint(Certificate cert)
- throws CertificateEncodingException, NoSuchAlgorithmException;
+ throws CertificateEncodingException, NoSuchAlgorithmException;
/**
* Returns the finger print of the given certificate.
- *
+ *
* @param cert certificate
* @return finger print of certificate
*/
public String getFingerPrints(Certificate cert)
- throws NoSuchAlgorithmException, CertificateEncodingException;
+ throws NoSuchAlgorithmException, CertificateEncodingException;
- /*
+ /*
* Returns the finger print of the given certificate.
- *
+ *
* @param certDer DER byte array of certificate
+ *
* @return finger print of certificate
*/
public String getFingerPrints(byte[] certDer)
- throws NoSuchAlgorithmException;
+ throws NoSuchAlgorithmException;
/**
* Creates a repository record in the internal database.
- *
+ *
* @return repository record
*/
public IRepositoryRecord createRepositoryRecord();
/**
- * Creates a HTTP PKI Message that can be sent to a remote
- * authority.
- *
+ * Creates a HTTP PKI Message that can be sent to a remote authority.
+ *
* @return a new PKI Message for remote authority
*/
public IPKIMessage getHttpPKIMessage();
/**
- * Creates a request encoder. A request cannot be sent to
- * the remote authority in its regular format.
- *
+ * Creates a request encoder. A request cannot be sent to the remote
+ * authority in its regular format.
+ *
* @return a request encoder
*/
public IRequestEncoder getHttpRequestEncoder();
/**
* Converts a BER-encoded byte array into a MIME-64 encoded string.
- *
+ *
* @param data data in byte array format
* @return base-64 encoding for the data
*/
@@ -517,16 +518,16 @@ public interface ICMSEngine extends ISubsystem {
/**
* Converts a MIME-64 encoded string into a BER-encoded byte array.
- *
+ *
* @param data base-64 encoding for the data
* @return data data in byte array format
*/
public byte[] AtoB(String data);
/**
- * Retrieves the certifcate in MIME-64 encoded format
- * with header and footer.
- *
+ * Retrieves the certifcate in MIME-64 encoded format with header and
+ * footer.
+ *
* @param cert certificate
* @return base-64 format certificate
*/
@@ -534,7 +535,7 @@ public interface ICMSEngine extends ISubsystem {
/**
* Retrieves the certificate pretty print handler.
- *
+ *
* @param delimiter delimiter
* @return certificate pretty print handler
*/
@@ -542,7 +543,7 @@ public interface ICMSEngine extends ISubsystem {
/**
* Retrieves the extension pretty print handler.
- *
+ *
* @param e extension
* @param indent indentation
* @return extension pretty print handler
@@ -551,7 +552,7 @@ public interface ICMSEngine extends ISubsystem {
/**
* Retrieves the certificate pretty print handler.
- *
+ *
* @param cert certificate
* @return certificate pretty print handler
*/
@@ -559,7 +560,7 @@ public interface ICMSEngine extends ISubsystem {
/**
* Retrieves the CRL pretty print handler.
- *
+ *
* @param crl CRL
* @return CRL pretty print handler
*/
@@ -567,50 +568,48 @@ public interface ICMSEngine extends ISubsystem {
/**
* Retrieves the CRL cache pretty print handler.
- *
+ *
* @param ip CRL issuing point
* @return CRL pretty print handler
*/
public ICRLPrettyPrint getCRLCachePrettyPrint(ICRLIssuingPoint ip);
/**
- * Retrieves the ldap connection information from the configuration
- * store.
- *
+ * Retrieves the ldap connection information from the configuration store.
+ *
* @param config configuration parameters of ldap connection
* @return a LDAP connection info
*/
- public ILdapConnInfo getLdapConnInfo(IConfigStore config)
- throws EBaseException, ELdapException;
+ public ILdapConnInfo getLdapConnInfo(IConfigStore config)
+ throws EBaseException, ELdapException;
/**
- * Creates a LDAP SSL socket with the given nickname. The
- * certificate associated with the nickname will be used
- * for client authentication.
- *
+ * Creates a LDAP SSL socket with the given nickname. The certificate
+ * associated with the nickname will be used for client authentication.
+ *
* @param certNickname nickname of client certificate
* @return LDAP SSL socket factory
*/
- public LDAPSSLSocketFactoryExt getLdapJssSSLSocketFactory(
- String certNickname);
+ public LDAPSSLSocketFactoryExt getLdapJssSSLSocketFactory(
+ String certNickname);
/**
* Creates a LDAP SSL socket.
- *
+ *
* @return LDAP SSL socket factory
*/
- public LDAPSSLSocketFactoryExt getLdapJssSSLSocketFactory();
+ public LDAPSSLSocketFactoryExt getLdapJssSSLSocketFactory();
/**
* Creates a LDAP Auth Info object.
- *
+ *
* @return LDAP authentication info
*/
public ILdapAuthInfo getLdapAuthInfo();
/**
* Retrieves the LDAP connection factory.
- *
+ *
* @return bound LDAP connection pool
*/
public ILdapConnFactory getLdapBoundConnFactory() throws ELdapException;
@@ -618,23 +617,24 @@ public interface ICMSEngine extends ISubsystem {
public LDAPConnection getBoundConnection(String host, int port,
int version, LDAPSSLSocketFactoryExt fac, String bindDN,
String bindPW) throws LDAPException;
+
/**
* Retrieves the LDAP connection factory.
- *
+ *
* @return anonymous LDAP connection pool
*/
public ILdapConnFactory getLdapAnonConnFactory() throws ELdapException;
/**
* Retrieves the password check.
- *
+ *
* @return default password checker
*/
public IPasswordCheck getPasswordChecker();
/**
* Puts a password entry into the single-sign on cache.
- *
+ *
* @param tag password tag
* @param pw password
*/
@@ -642,21 +642,21 @@ public interface ICMSEngine extends ISubsystem {
/**
* Retrieves the password callback.
- *
+ *
* @return default password callback
*/
public PasswordCallback getPasswordCallback();
/**
* Retrieves the nickname of the server's server certificate.
- *
+ *
* @return nickname of the server certificate
*/
public String getServerCertNickname();
/**
* Sets the nickname of the server's server certificate.
- *
+ *
* @param tokenName name of token where the certificate is located
* @param nickName name of server certificate
*/
@@ -664,137 +664,142 @@ public interface ICMSEngine extends ISubsystem {
/**
* Sets the nickname of the server's server certificate.
- *
+ *
* @param newName new nickname of server certificate
*/
public void setServerCertNickname(String newName);
/**
* Retrieves the host name of the server's secure end entity service.
- *
+ *
* @return host name of end-entity service
*/
public String getEEHost();
/**
* Retrieves the host name of the server's non-secure end entity service.
- *
+ *
* @return host name of end-entity non-secure service
*/
public String getEENonSSLHost();
/**
* Retrieves the IP address of the server's non-secure end entity service.
- *
+ *
* @return ip address of end-entity non-secure service
*/
public String getEENonSSLIP();
/**
* Retrieves the port number of the server's non-secure end entity service.
- *
+ *
* @return port of end-entity non-secure service
*/
public String getEENonSSLPort();
/**
* Retrieves the host name of the server's secure end entity service.
- *
+ *
* @return port of end-entity secure service
*/
public String getEESSLHost();
/**
* Retrieves the IP address of the server's secure end entity service.
- *
+ *
* @return ip address of end-entity secure service
*/
public String getEESSLIP();
/**
* Retrieves the port number of the server's secure end entity service.
- *
+ *
* @return port of end-entity secure service
*/
public String getEESSLPort();
/**
- * Retrieves the port number of the server's client auth secure end entity service.
- *
+ * Retrieves the port number of the server's client auth secure end entity
+ * service.
+ *
* @return port of end-entity client auth secure service
*/
public String getEEClientAuthSSLPort();
/**
* Retrieves the host name of the server's agent service.
- *
+ *
* @return host name of agent service
*/
public String getAgentHost();
/**
* Retrieves the IP address of the server's agent service.
- *
+ *
* @return ip address of agent service
*/
public String getAgentIP();
/**
* Retrieves the port number of the server's agent service.
- *
+ *
* @return port of agent service
*/
public String getAgentPort();
/**
* Retrieves the host name of the server's administration service.
- *
+ *
* @return host name of administration service
*/
public String getAdminHost();
/**
* Retrieves the IP address of the server's administration service.
- *
+ *
* @return ip address of administration service
*/
public String getAdminIP();
/**
* Retrieves the port number of the server's administration service.
- *
+ *
* @return port of administration service
*/
public String getAdminPort();
/**
* Verifies all system certificates
+ *
* @return true if all passed, false otherwise
*/
- public boolean verifySystemCerts();
+ public boolean verifySystemCerts();
/**
- * Verifies a system certificate by its tag name
- * as defined in <subsystemtype>.cert.list
+ * Verifies a system certificate by its tag name as defined in
+ * <subsystemtype>.cert.list
+ *
* @return true if passed, false otherwise
*/
public boolean verifySystemCertByTag(String tag);
/**
* Verifies a system certificate by its nickname
+ *
* @return true if passed, false otherwise
*/
public boolean verifySystemCertByNickname(String nickname, String certificateUsage);
/**
* get the CertificateUsage as defined in JSS CryptoManager
+ *
* @return CertificateUsage as defined in JSS CryptoManager
*/
public CertificateUsage getCertificateUsage(String certusage);
/**
* Checks if the given certificate is a signing certificate.
- *
+ *
* @param cert certificate
* @return true if the given certificate is a signing certificate
*/
@@ -802,7 +807,7 @@ public interface ICMSEngine extends ISubsystem {
/**
* Checks if the given certificate is an encryption certificate.
- *
+ *
* @param cert certificate
* @return true if the given certificate is an encryption certificate
*/
@@ -810,209 +815,209 @@ public interface ICMSEngine extends ISubsystem {
/**
* Retrieves the default X.509 certificate template.
- *
+ *
* @return default certificate template
*/
public X509CertInfo getDefaultX509CertInfo();
/**
* Retrieves the email form processor.
- *
+ *
* @return email form processor
*/
public IEmailFormProcessor getEmailFormProcessor();
/**
* Retrieves the email form template.
- *
+ *
* @return email template
*/
public IEmailTemplate getEmailTemplate(String path);
/**
* Retrieves the email notification handler.
- *
+ *
* @return email notification
*/
public IMailNotification getMailNotification();
/**
* Retrieves the email key resolver.
- *
+ *
* @return email key resolver
*/
public IEmailResolverKeys getEmailResolverKeys();
/**
* Retrieves the email resolver that checks for subjectAlternateName.
- *
+ *
* @return email key resolver
*/
public IEmailResolver getReqCertSANameEmailResolver();
/**
* Checks if the given OID is valid.
- *
+ *
* @param attrName attribute name
* @param value attribute value
* @return object identifier of the given attrName
*/
public ObjectIdentifier checkOID(String attrName, String value)
- throws EBaseException;
+ throws EBaseException;
/**
* Creates a general name constraints.
- *
+ *
* @param generalNameChoice type of general name
* @param value general name string
* @return general name object
* @exception EBaseException failed to create general name constraint
*/
- public GeneralName form_GeneralNameAsConstraints(String generalNameChoice, String value) throws EBaseException;
+ public GeneralName form_GeneralNameAsConstraints(String generalNameChoice, String value) throws EBaseException;
/**
* Creates a general name.
- *
+ *
* @param generalNameChoice type of general name
* @param value general name string
* @return general name object
* @exception EBaseException failed to create general name
*/
- public GeneralName form_GeneralName(String generalNameChoice,
- String value) throws EBaseException;
+ public GeneralName form_GeneralName(String generalNameChoice,
+ String value) throws EBaseException;
/**
* Retrieves default general name configuration.
- *
+ *
* @param name configuration name
* @param isValueConfigured true if value is configured
* @param params configuration parameters
* @exception EBaseException failed to create subject alt name configuration
*/
- public void getGeneralNameConfigDefaultParams(String name,
- boolean isValueConfigured, Vector<String> params);
+ public void getGeneralNameConfigDefaultParams(String name,
+ boolean isValueConfigured, Vector<String> params);
/**
* Retrieves default general names configuration.
- *
+ *
* @param name configuration name
* @param isValueConfigured true if value is configured
* @param params configuration parameters
* @exception EBaseException failed to create subject alt name configuration
*/
- public void getGeneralNamesConfigDefaultParams(String name,
- boolean isValueConfigured, Vector<String> params);
+ public void getGeneralNamesConfigDefaultParams(String name,
+ boolean isValueConfigured, Vector<String> params);
/**
* Retrieves extended plugin info for general name configuration.
- *
+ *
* @param name configuration name
* @param isValueConfigured true if value is configured
* @param info configuration parameters
* @exception EBaseException failed to create subject alt name configuration
*/
- public void getGeneralNameConfigExtendedPluginInfo(String name,
- boolean isValueConfigured, Vector<String> info);
+ public void getGeneralNameConfigExtendedPluginInfo(String name,
+ boolean isValueConfigured, Vector<String> info);
/**
* Retrieves extended plugin info for general name configuration.
- *
+ *
* @param name configuration name
* @param isValueConfigured true if value is configured
* @param info configuration parameters
* @exception EBaseException failed to create subject alt name configuration
*/
- public void getGeneralNamesConfigExtendedPluginInfo(String name,
- boolean isValueConfigured, Vector<String> info);
+ public void getGeneralNamesConfigExtendedPluginInfo(String name,
+ boolean isValueConfigured, Vector<String> info);
/**
* Created general names configuration.
- *
+ *
* @param name configuration name
* @param config configuration store
* @param isValueConfigured true if value is configured
* @param isPolicyEnabled true if policy is enabled
* @exception EBaseException failed to create subject alt name configuration
*/
- public IGeneralNamesConfig createGeneralNamesConfig(String name,
- IConfigStore config, boolean isValueConfigured,
- boolean isPolicyEnabled) throws EBaseException;
+ public IGeneralNamesConfig createGeneralNamesConfig(String name,
+ IConfigStore config, boolean isValueConfigured,
+ boolean isPolicyEnabled) throws EBaseException;
/**
* Created general name constraints configuration.
- *
+ *
* @param name configuration name
* @param config configuration store
* @param isValueConfigured true if value is configured
* @param isPolicyEnabled true if policy is enabled
* @exception EBaseException failed to create subject alt name configuration
*/
- public IGeneralNameAsConstraintsConfig createGeneralNameAsConstraintsConfig(String name, IConfigStore config, boolean isValueConfigured,
- boolean isPolicyEnabled) throws EBaseException;
+ public IGeneralNameAsConstraintsConfig createGeneralNameAsConstraintsConfig(String name, IConfigStore config, boolean isValueConfigured,
+ boolean isPolicyEnabled) throws EBaseException;
/**
* Created general name constraints configuration.
- *
+ *
* @param name configuration name
* @param config configuration store
* @param isValueConfigured true if value is configured
* @param isPolicyEnabled true if policy is enabled
* @exception EBaseException failed to create subject alt name configuration
*/
- public IGeneralNamesAsConstraintsConfig createGeneralNamesAsConstraintsConfig(String name, IConfigStore config, boolean isValueConfigured,
- boolean isPolicyEnabled) throws EBaseException;
+ public IGeneralNamesAsConstraintsConfig createGeneralNamesAsConstraintsConfig(String name, IConfigStore config, boolean isValueConfigured,
+ boolean isPolicyEnabled) throws EBaseException;
/**
* Get default parameters for subject alt name configuration.
- *
+ *
* @param name configuration name
* @param params configuration parameters
*/
- public void getSubjAltNameConfigDefaultParams(String name, Vector<String> params);
+ public void getSubjAltNameConfigDefaultParams(String name, Vector<String> params);
/**
* Get extended plugin info for subject alt name configuration.
- *
+ *
* @param name configuration name
* @param params configuration parameters
*/
- public void getSubjAltNameConfigExtendedPluginInfo(String name, Vector<String> params);
+ public void getSubjAltNameConfigExtendedPluginInfo(String name, Vector<String> params);
/**
* Creates subject alt name configuration.
- *
+ *
* @param name configuration name
* @param config configuration store
* @param isValueConfigured true if value is configured
* @exception EBaseException failed to create subject alt name configuration
*/
- public ISubjAltNameConfig createSubjAltNameConfig(String name, IConfigStore config, boolean isValueConfigured) throws EBaseException;
+ public ISubjAltNameConfig createSubjAltNameConfig(String name, IConfigStore config, boolean isValueConfigured) throws EBaseException;
/**
* Retrieves the HTTP Connection for use with connector.
- *
+ *
* @param authority remote authority
* @param factory socket factory
* @return http connection to the remote authority
*/
public IHttpConnection getHttpConnection(IRemoteAuthority authority,
- ISocketFactory factory);
+ ISocketFactory factory);
/**
* Retrieves the HTTP Connection for use with connector.
- *
+ *
* @param authority remote authority
* @param factory socket factory
* @param timeout return error if connection cannot be established within
- * the timeout period
+ * the timeout period
* @return http connection to the remote authority
*/
public IHttpConnection getHttpConnection(IRemoteAuthority authority,
- ISocketFactory factory, int timeout);
+ ISocketFactory factory, int timeout);
/**
* Retrieves the request sender for use with connector.
- *
+ *
* @param authority local authority
* @param nickname nickname of the client certificate
* @param remote remote authority
@@ -1020,11 +1025,11 @@ public interface ICMSEngine extends ISubsystem {
* @return resender
*/
public IResender getResender(IAuthority authority, String nickname,
- IRemoteAuthority remote, int interval);
+ IRemoteAuthority remote, int interval);
/**
* Retrieves command queue
- *
+ *
* @return command queue
*/
public ICommandQueue getCommandQueue();
@@ -1040,22 +1045,23 @@ public interface ICMSEngine extends ISubsystem {
public void terminateRequests();
/**
- * Checks to ensure that all new incoming requests have been blocked.
- * This method is used for reentrancy protection.
+ * Checks to ensure that all new incoming requests have been blocked. This
+ * method is used for reentrancy protection.
* <P>
- *
+ *
* @return true or false
*/
public boolean areRequestsDisabled();
/**
* Create configuration file.
- *
+ *
* @param path configuration path
* @return configuration store
* @exception EBaseException failed to create file
*/
public IConfigStore createFileConfigStore(String path) throws EBaseException;
+
/**
* Creates argument block.
*/
@@ -1072,31 +1078,30 @@ public interface ICMSEngine extends ISubsystem {
public IArgBlock createArgBlock(Hashtable<String, String> httpReq);
/**
- * Checks against the local certificate repository to see
- * if the certificates are revoked.
- *
+ * Checks against the local certificate repository to see if the
+ * certificates are revoked.
+ *
* @param certificates certificates
- * @return true if certificate is revoked in the local
- * certificate repository
+ * @return true if certificate is revoked in the local certificate
+ * repository
*/
public boolean isRevoked(X509Certificate[] certificates);
/**
* Sets list of verified certificates
- *
+ *
* @param size size of verified certificates list
- * @param interval interval in which certificate is not recheck
- * against local certificate repository
- * @param unknownStateInterval interval in which certificate
- * may not recheck against local certificate repository
+ * @param interval interval in which certificate is not recheck against
+ * local certificate repository
+ * @param unknownStateInterval interval in which certificate may not recheck
+ * against local certificate repository
*/
public void setListOfVerifiedCerts(int size, long interval, long unknownStateInterval);
/**
- * Performs graceful shutdown of CMS.
- * Subsystems are shutdown in reverse order.
- * Exceptions are ignored.
- */
+ * Performs graceful shutdown of CMS. Subsystems are shutdown in reverse
+ * order. Exceptions are ignored.
+ */
public void forceShutdown();
public IPasswordStore getPasswordStore();
@@ -1107,4 +1112,3 @@ public interface ICMSEngine extends ISubsystem {
public String getConfigSDSessionId();
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/apps/ICommandQueue.java b/pki/base/common/src/com/netscape/certsrv/apps/ICommandQueue.java
index f41b2989..97d942c6 100644
--- a/pki/base/common/src/com/netscape/certsrv/apps/ICommandQueue.java
+++ b/pki/base/common/src/com/netscape/certsrv/apps/ICommandQueue.java
@@ -21,12 +21,9 @@ import javax.servlet.Servlet;
import com.netscape.cms.servlet.common.CMSRequest;
-
-
-
/**
- * This interface represents a command queue for registeration
- * and unregisteration proccess for clean shutdown
+ * This interface represents a command queue for registeration and
+ * unregisteration proccess for clean shutdown
*
* @version $Revision$, $Date$
*/
@@ -34,17 +31,18 @@ public interface ICommandQueue {
/**
* Registers a thread into the command queue.
- *
+ *
* @param currentRequest request object
* @param currentServlet servlet that serves the request object
*/
public boolean registerProcess(CMSRequest currentRequest, Servlet currentServlet);
+
/**
* UnRegisters a thread from the command queue.
- *
+ *
* @param currentRequest request object
* @param currentServlet servlet that serves the request object
*/
public void unRegisterProccess(Object currentRequest, Object currentServlet);
-
+
} // CommandQueue
diff --git a/pki/base/common/src/com/netscape/certsrv/authentication/AuthCredentials.java b/pki/base/common/src/com/netscape/certsrv/authentication/AuthCredentials.java
index de124a38..c13ec073 100644
--- a/pki/base/common/src/com/netscape/certsrv/authentication/AuthCredentials.java
+++ b/pki/base/common/src/com/netscape/certsrv/authentication/AuthCredentials.java
@@ -23,10 +23,10 @@ import java.util.Hashtable;
import com.netscape.certsrv.base.IArgBlock;
/**
- * Authentication Credentials as input to the authMgr. It contains all the
+ * Authentication Credentials as input to the authMgr. It contains all the
* information required for authentication in the authMgr.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class AuthCredentials implements IAuthCredentials {
@@ -34,7 +34,7 @@ public class AuthCredentials implements IAuthCredentials {
private static final long serialVersionUID = 5862936214648594328L;
private Hashtable<String, Object> authCreds = null;
private IArgBlock argblk = null;
-
+
/**
* Constructor
*/
@@ -43,7 +43,9 @@ public class AuthCredentials implements IAuthCredentials {
}
/**
- * Sets an authentication credential with credential name and the credential object
+ * Sets an authentication credential with credential name and the credential
+ * object
+ *
* @param name credential name
* @param cred credential object
*/
@@ -54,7 +56,8 @@ public class AuthCredentials implements IAuthCredentials {
/**
* Returns the credential to which the specified name is mapped in this
- * credential set
+ * credential set
+ *
* @param name credential name
* @return the authentication credential for the given name
*/
@@ -63,9 +66,10 @@ public class AuthCredentials implements IAuthCredentials {
}
/**
- * Removes the name and its corresponding credential from this
- * credential set. This method does nothing if the named
- * credential is not in the credential set.
+ * Removes the name and its corresponding credential from this credential
+ * set. This method does nothing if the named credential is not in the
+ * credential set.
+ *
* @param name credential name
*/
public void delete(String name) {
@@ -73,29 +77,29 @@ public class AuthCredentials implements IAuthCredentials {
}
/**
- * Returns an enumeration of the credentials in this credential
- * set. Use the Enumeration methods on the returned object to
- * fetch the elements sequentially.
+ * Returns an enumeration of the credentials in this credential set. Use the
+ * Enumeration methods on the returned object to fetch the elements
+ * sequentially.
+ *
* @return an enumeration of the values in this credential set
*/
public Enumeration<Object> getElements() {
return (authCreds.elements());
}
-
+
/**
- * Set the given argblock
-i * @param blk the given argblock.
+ * Set the given argblock i * @param blk the given argblock.
*/
public void setArgBlock(IArgBlock blk) {
argblk = blk;
- }
+ }
/**
* Returns the argblock.
+ *
* @return the argblock.
*/
public IArgBlock getArgBlock() {
return argblk;
- }
+ }
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/authentication/AuthManagerProxy.java b/pki/base/common/src/com/netscape/certsrv/authentication/AuthManagerProxy.java
index f98276ec..006065dd 100644
--- a/pki/base/common/src/com/netscape/certsrv/authentication/AuthManagerProxy.java
+++ b/pki/base/common/src/com/netscape/certsrv/authentication/AuthManagerProxy.java
@@ -17,10 +17,10 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.authentication;
-
/**
- * A class represents an authentication manager. It contains an
- * authentication manager instance and its state (enable or not).
+ * A class represents an authentication manager. It contains an authentication
+ * manager instance and its state (enable or not).
+ *
* @version $Revision$, $Date$
*/
public class AuthManagerProxy {
@@ -29,9 +29,10 @@ public class AuthManagerProxy {
/**
* Constructor
+ *
* @param enable true if the authMgr is enabled; false otherwise
* @param mgr authentication manager instance
- */
+ */
public AuthManagerProxy(boolean enable, IAuthManager mgr) {
mEnable = enable;
mMgr = mgr;
@@ -39,7 +40,8 @@ public class AuthManagerProxy {
/**
* Returns the state of the authentication manager instance
- * @return true if the state of the authentication manager instance is
+ *
+ * @return true if the state of the authentication manager instance is
* enabled; false otherwise.
*/
public boolean isEnable() {
@@ -48,6 +50,7 @@ public class AuthManagerProxy {
/**
* Returns an authentication manager instance.
+ *
* @return an authentication manager instance
*/
public IAuthManager getAuthManager() {
diff --git a/pki/base/common/src/com/netscape/certsrv/authentication/AuthMgrPlugin.java b/pki/base/common/src/com/netscape/certsrv/authentication/AuthMgrPlugin.java
index bdb2fe00..b9816e7b 100644
--- a/pki/base/common/src/com/netscape/certsrv/authentication/AuthMgrPlugin.java
+++ b/pki/base/common/src/com/netscape/certsrv/authentication/AuthMgrPlugin.java
@@ -17,13 +17,10 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.authentication;
-
-
-
/**
* This class represents a registered authentication manager plugin.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class AuthMgrPlugin {
@@ -33,21 +30,24 @@ public class AuthMgrPlugin {
/**
* Constructs a AuthManager plugin.
+ *
* @param id auth manager implementation name
* @param classPath class path
*/
public AuthMgrPlugin(String id, String classPath) {
/*
- if (id == null || classPath == null)
- throw new AssertionException("Authentication Manager id or classpath can't be null");
+ * if (id == null || classPath == null) throw new
+ * AssertionException("Authentication Manager id or classpath can't be null"
+ * );
*/
mId = id;
mClassPath = classPath;
}
-
+
/**
* Returns an auth manager implementation name
+ *
* @return an auth manager implementation name
*/
public String getId() {
@@ -56,22 +56,25 @@ public class AuthMgrPlugin {
/**
* Returns a classpath of a AuthManager plugin
+ *
* @return a classpath of a AuthManager plugin
*/
public String getClassPath() {
return mClassPath;
}
- /**
+ /**
* Returns a visibility of the plugin
+ *
* @return a visibility of the plugin
*/
public boolean isVisible() {
return mVisible;
}
- /**
+ /**
* Sets visibility of the plugin
+ *
* @param visibility visibility of the plugin
*/
public void setVisible(boolean visibility) {
diff --git a/pki/base/common/src/com/netscape/certsrv/authentication/AuthResources.java b/pki/base/common/src/com/netscape/certsrv/authentication/AuthResources.java
index 138a07eb..35e81011 100644
--- a/pki/base/common/src/com/netscape/certsrv/authentication/AuthResources.java
+++ b/pki/base/common/src/com/netscape/certsrv/authentication/AuthResources.java
@@ -22,7 +22,7 @@ import java.util.ListResourceBundle;
/**
* A class represents a resource bundle for the authentication component.
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
@@ -30,6 +30,7 @@ public class AuthResources extends ListResourceBundle {
/**
* Returns the content of this resource.
+ *
* @return the contents of this resource
*/
public Object[][] getContents() {
diff --git a/pki/base/common/src/com/netscape/certsrv/authentication/AuthToken.java b/pki/base/common/src/com/netscape/certsrv/authentication/AuthToken.java
index eae282c0..677e22a8 100644
--- a/pki/base/common/src/com/netscape/certsrv/authentication/AuthToken.java
+++ b/pki/base/common/src/com/netscape/certsrv/authentication/AuthToken.java
@@ -38,13 +38,13 @@ import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.usrgrp.Certificates;
/**
- * Authentication token returned by Authentication Managers.
- * Upon return, it contains authentication/identification information
- * as well as information retrieved from the database where the
- * authentication was done against. Each authentication manager has
- * its own list of such information. See individual authenticaiton
- * manager for more details.
+ * Authentication token returned by Authentication Managers. Upon return, it
+ * contains authentication/identification information as well as information
+ * retrieved from the database where the authentication was done against. Each
+ * authentication manager has its own list of such information. See individual
+ * authenticaiton manager for more details.
* <p>
+ *
* @version $Revision$, $Date$
*/
public class AuthToken implements IAuthToken {
@@ -74,43 +74,45 @@ public class AuthToken implements IAuthToken {
public static final String TOKEN_CERT_TO_REVOKE = "tokenCertToRevoke";
/**
- * Plugin name of the authentication manager that created the
- * AuthToken as a string.
+ * Plugin name of the authentication manager that created the AuthToken as a
+ * string.
*/
public static final String TOKEN_AUTHMGR_IMPL_NAME = "authMgrImplName";
/**
- * Name of the authentication manager that created the AuthToken
- * as a string.
+ * Name of the authentication manager that created the AuthToken as a
+ * string.
*/
public static final String TOKEN_AUTHMGR_INST_NAME = "authMgrInstName";
/**
- * Time of authentication as a java.util.Date
+ * Time of authentication as a java.util.Date
*/
public static final String TOKEN_AUTHTIME = "authTime";
/**
- * Constructs an instance of a authentication token.
- * The token by default contains the following attributes: <br>
+ * Constructs an instance of a authentication token. The token by default
+ * contains the following attributes: <br>
+ *
* <pre>
- * "authMgrInstName" - The authentication manager instance name.
- * "authMgrImplName" - The authentication manager plugin name.
- * "authTime" - The - The time of authentication.
+ * "authMgrInstName" - The authentication manager instance name.
+ * "authMgrImplName" - The authentication manager plugin name.
+ * "authTime" - The - The time of authentication.
* </pre>
+ *
* @param authMgr The authentication manager that created this Token.
*/
public AuthToken(IAuthManager authMgr) {
mAttrs = new Hashtable<String, Object>();
if (authMgr != null) {
- set(TOKEN_AUTHMGR_INST_NAME, authMgr.getName());
- set(TOKEN_AUTHMGR_IMPL_NAME, authMgr.getImplName());
+ set(TOKEN_AUTHMGR_INST_NAME, authMgr.getName());
+ set(TOKEN_AUTHMGR_IMPL_NAME, authMgr.getImplName());
}
set(TOKEN_AUTHTIME, new Date());
}
public String getInString(String attrName) {
- return (String)mAttrs.get(attrName);
+ return (String) mAttrs.get(attrName);
}
public boolean set(String attrName, String value) {
@@ -123,6 +125,7 @@ public class AuthToken implements IAuthToken {
/**
* Removes an attribute in the AuthToken
+ *
* @param attrName The name of the attribute to remove.
*/
public void delete(String attrName) {
@@ -131,6 +134,7 @@ public class AuthToken implements IAuthToken {
/**
* Enumerate all attribute names in the AuthToken.
+ *
* @return Enumeration of all attribute names in this AuthToken.
*/
public Enumeration<String> getElements() {
@@ -351,7 +355,7 @@ public class AuthToken implements IAuthToken {
for (int i = 0; i < certArray.length; i++) {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
try {
- X509CertImpl certImpl = (X509CertImpl)certArray[i];
+ X509CertImpl certImpl = (X509CertImpl) certArray[i];
certImpl.encode(byteStream);
derValues[i] = new DerValue(byteStream.toByteArray());
} catch (CertificateEncodingException e) {
@@ -406,6 +410,7 @@ public class AuthToken implements IAuthToken {
/**
* Enumerate all attribute values in the AuthToken.
+ *
* @return Enumeration of all attribute names in this AuthToken.
*/
public Enumeration<Object> getVals() {
@@ -413,10 +418,11 @@ public class AuthToken implements IAuthToken {
}
/**
- * Gets the name of the authentication manager instance that created
- * this token.
- * @return The name of the authentication manager instance that created
- * this token.
+ * Gets the name of the authentication manager instance that created this
+ * token.
+ *
+ * @return The name of the authentication manager instance that created this
+ * token.
*/
public String getAuthManagerInstName() {
return ((String) mAttrs.get(TOKEN_AUTHMGR_INST_NAME));
@@ -425,8 +431,9 @@ public class AuthToken implements IAuthToken {
/**
* Gets the plugin name of the authentication manager that created this
* token.
+ *
* @return The plugin name of the authentication manager that created this
- * token.
+ * token.
*/
public String getAuthManagerImplName() {
return ((String) mAttrs.get(TOKEN_AUTHMGR_IMPL_NAME));
@@ -434,10 +441,10 @@ public class AuthToken implements IAuthToken {
/**
* Gets the time of authentication.
+ *
* @return The time of authentication
*/
public Date getAuthTime() {
return ((Date) mAttrs.get(TOKEN_AUTHTIME));
}
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/authentication/EAuthException.java b/pki/base/common/src/com/netscape/certsrv/authentication/EAuthException.java
index b998ae8b..c79c3e9a 100644
--- a/pki/base/common/src/com/netscape/certsrv/authentication/EAuthException.java
+++ b/pki/base/common/src/com/netscape/certsrv/authentication/EAuthException.java
@@ -22,6 +22,7 @@ import com.netscape.certsrv.base.EBaseException;
/**
* This class represents authentication exceptions.
* <P>
+ *
* @version $Revision$, $Date$
*/
public class EAuthException extends EBaseException {
@@ -38,6 +39,7 @@ public class EAuthException extends EBaseException {
/**
* Constructs an authentication exception
* <P>
+ *
* @param msgFormat exception details
*/
public EAuthException(String msgFormat) {
@@ -45,8 +47,9 @@ public class EAuthException extends EBaseException {
}
/**
- * Constructs an authentication exception with a parameter.
+ * Constructs an authentication exception with a parameter.
* <p>
+ *
* @param msgFormat exception details in message string format
* @param param message string parameter
*/
@@ -57,6 +60,7 @@ public class EAuthException extends EBaseException {
/**
* Constructs a auth exception with a exception parameter.
* <P>
+ *
* @param msgFormat exception details in message string format
* @param exception system exception
*/
@@ -67,6 +71,7 @@ public class EAuthException extends EBaseException {
/**
* Constructs a auth exception with a list of parameters.
* <P>
+ *
* @param msgFormat the message format.
* @param params list of message format parameters
*/
@@ -76,6 +81,7 @@ public class EAuthException extends EBaseException {
/**
* Returns the resource bundle name
+ *
* @return resource bundle name.
*/
protected String getBundleName() {
diff --git a/pki/base/common/src/com/netscape/certsrv/authentication/EAuthInternalError.java b/pki/base/common/src/com/netscape/certsrv/authentication/EAuthInternalError.java
index fb4ad04b..1b2d848a 100644
--- a/pki/base/common/src/com/netscape/certsrv/authentication/EAuthInternalError.java
+++ b/pki/base/common/src/com/netscape/certsrv/authentication/EAuthInternalError.java
@@ -28,8 +28,9 @@ public class EAuthInternalError extends EAuthException {
private static final long serialVersionUID = -4020816090107820450L;
/**
- * Constructs an authentication internal error exception
- * with a detailed message.
+ * Constructs an authentication internal error exception with a detailed
+ * message.
+ *
* @param errorString Detailed error message.
*/
public EAuthInternalError(String errorString) {
diff --git a/pki/base/common/src/com/netscape/certsrv/authentication/EAuthMgrNotFound.java b/pki/base/common/src/com/netscape/certsrv/authentication/EAuthMgrNotFound.java
index 675fbe59..925aaabf 100644
--- a/pki/base/common/src/com/netscape/certsrv/authentication/EAuthMgrNotFound.java
+++ b/pki/base/common/src/com/netscape/certsrv/authentication/EAuthMgrNotFound.java
@@ -29,6 +29,7 @@ public class EAuthMgrNotFound extends EAuthException {
/**
* Constructs a exception for a missing authentication manager
+ *
* @param errorString error string for missing authentication manager
*/
public EAuthMgrNotFound(String errorString) {
diff --git a/pki/base/common/src/com/netscape/certsrv/authentication/EAuthMgrPluginNotFound.java b/pki/base/common/src/com/netscape/certsrv/authentication/EAuthMgrPluginNotFound.java
index 2210de2c..2ca90e3c 100644
--- a/pki/base/common/src/com/netscape/certsrv/authentication/EAuthMgrPluginNotFound.java
+++ b/pki/base/common/src/com/netscape/certsrv/authentication/EAuthMgrPluginNotFound.java
@@ -29,7 +29,8 @@ public class EAuthMgrPluginNotFound extends EAuthException {
/**
* Constructs a exception for a missing authentication manager plugin
- * @param errorString error for a missing authentication manager plugin
+ *
+ * @param errorString error for a missing authentication manager plugin
*/
public EAuthMgrPluginNotFound(String errorString) {
super(errorString);
diff --git a/pki/base/common/src/com/netscape/certsrv/authentication/EAuthUserError.java b/pki/base/common/src/com/netscape/certsrv/authentication/EAuthUserError.java
index b3bafd3c..f816c35e 100644
--- a/pki/base/common/src/com/netscape/certsrv/authentication/EAuthUserError.java
+++ b/pki/base/common/src/com/netscape/certsrv/authentication/EAuthUserError.java
@@ -29,6 +29,7 @@ public class EAuthUserError extends EAuthException {
/**
* Constructs a exception for a Invalid attribute value
+ *
* @param errorString Detailed error message.
*/
public EAuthUserError(String errorString) {
diff --git a/pki/base/common/src/com/netscape/certsrv/authentication/ECompSyntaxErr.java b/pki/base/common/src/com/netscape/certsrv/authentication/ECompSyntaxErr.java
index edbf13e6..84725bb9 100644
--- a/pki/base/common/src/com/netscape/certsrv/authentication/ECompSyntaxErr.java
+++ b/pki/base/common/src/com/netscape/certsrv/authentication/ECompSyntaxErr.java
@@ -29,6 +29,7 @@ public class ECompSyntaxErr extends EAuthException {
/**
* Constructs an component syntax error
+ *
* @param errorString Detailed error message.
*/
public ECompSyntaxErr(String errorString) {
diff --git a/pki/base/common/src/com/netscape/certsrv/authentication/EFormSubjectDN.java b/pki/base/common/src/com/netscape/certsrv/authentication/EFormSubjectDN.java
index b56a1e0a..95282448 100644
--- a/pki/base/common/src/com/netscape/certsrv/authentication/EFormSubjectDN.java
+++ b/pki/base/common/src/com/netscape/certsrv/authentication/EFormSubjectDN.java
@@ -29,6 +29,7 @@ public class EFormSubjectDN extends EAuthException {
/**
* Constructs an Error on formulating the subject dn.
+ *
* @param errorString Detailed error message.
*/
public EFormSubjectDN(String errorString) {
diff --git a/pki/base/common/src/com/netscape/certsrv/authentication/EInvalidCredentials.java b/pki/base/common/src/com/netscape/certsrv/authentication/EInvalidCredentials.java
index 894a07ca..3e4daaf0 100644
--- a/pki/base/common/src/com/netscape/certsrv/authentication/EInvalidCredentials.java
+++ b/pki/base/common/src/com/netscape/certsrv/authentication/EInvalidCredentials.java
@@ -29,6 +29,7 @@ public class EInvalidCredentials extends EAuthException {
/**
* Constructs an Invalid Credentials exception.
+ *
* @param errorString Detailed error message.
*/
public EInvalidCredentials(String errorString) {
diff --git a/pki/base/common/src/com/netscape/certsrv/authentication/EMissingCredential.java b/pki/base/common/src/com/netscape/certsrv/authentication/EMissingCredential.java
index 695dd15c..5de73aa0 100644
--- a/pki/base/common/src/com/netscape/certsrv/authentication/EMissingCredential.java
+++ b/pki/base/common/src/com/netscape/certsrv/authentication/EMissingCredential.java
@@ -29,6 +29,7 @@ public class EMissingCredential extends EAuthException {
/**
* Constructs a exception for a missing required authentication credential
+ *
* @param errorString Detailed error message.
*/
public EMissingCredential(String errorString) {
diff --git a/pki/base/common/src/com/netscape/certsrv/authentication/IAuthCredentials.java b/pki/base/common/src/com/netscape/certsrv/authentication/IAuthCredentials.java
index eb36f996..8056ae31 100644
--- a/pki/base/common/src/com/netscape/certsrv/authentication/IAuthCredentials.java
+++ b/pki/base/common/src/com/netscape/certsrv/authentication/IAuthCredentials.java
@@ -21,22 +21,24 @@ import com.netscape.certsrv.base.IArgBlock;
import com.netscape.certsrv.base.IAttrSet;
/**
- * An interface represents authentication credentials:
- * e.g. uid/pwd, uid/pin, certificate, etc.
+ * An interface represents authentication credentials: e.g. uid/pwd, uid/pin,
+ * certificate, etc.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IAuthCredentials extends IAttrSet {
- /**
+ /**
* Set argblock.
+ *
* @param blk argblock
*/
public void setArgBlock(IArgBlock blk);
/**
* Returns argblock.
+ *
* @return Argblock.
*/
public IArgBlock getArgBlock();
diff --git a/pki/base/common/src/com/netscape/certsrv/authentication/IAuthManager.java b/pki/base/common/src/com/netscape/certsrv/authentication/IAuthManager.java
index b2f7d69a..e3e3ede8 100644
--- a/pki/base/common/src/com/netscape/certsrv/authentication/IAuthManager.java
+++ b/pki/base/common/src/com/netscape/certsrv/authentication/IAuthManager.java
@@ -23,7 +23,7 @@ import com.netscape.certsrv.base.IConfigStore;
/**
* Authentication Manager interface.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IAuthManager {
@@ -41,6 +41,7 @@ public interface IAuthManager {
/**
* Get the name of this authentication manager instance.
* <p>
+ *
* @return the name of this authentication manager.
*/
public String getName();
@@ -48,58 +49,63 @@ public interface IAuthManager {
/**
* Get name of authentication manager plugin.
* <p>
+ *
* @return the name of the authentication manager plugin.
- */
+ */
public String getImplName();
/**
* Authenticate the given credentials.
+ *
* @param authCred The authentication credentials
* @return authentication token
- * @exception EMissingCredential If a required credential for this
- * authentication manager is missing.
+ * @exception EMissingCredential If a required credential for this
+ * authentication manager is missing.
* @exception EInvalidCredentials If credentials cannot be authenticated.
* @exception EBaseException If an internal error occurred.
*/
public IAuthToken authenticate(IAuthCredentials authCred)
- throws EMissingCredential, EInvalidCredentials, EBaseException;
+ throws EMissingCredential, EInvalidCredentials, EBaseException;
/**
* Initialize this authentication manager.
+ *
* @param name The name of this authentication manager instance.
* @param implName The name of the authentication manager plugin.
* @param config The configuration store for this authentication manager.
* @exception EBaseException If an initialization error occurred.
*/
public void init(String name, String implName, IConfigStore config)
- throws EBaseException;
+ throws EBaseException;
/**
- * Prepare this authentication manager for a shutdown.
- * Called when the server is exiting for any cleanup needed.
+ * Prepare this authentication manager for a shutdown. Called when the
+ * server is exiting for any cleanup needed.
*/
public void shutdown();
/**
* Gets a list of the required credentials for this authentication manager.
+ *
* @return The required credential attributes.
*/
public String[] getRequiredCreds();
/**
- * Get configuration parameters for this implementation.
- * The configuration parameters returned is passed to the
- * configuration console so configuration for instances of this
- * implementation can be made through the console.
+ * Get configuration parameters for this implementation. The configuration
+ * parameters returned is passed to the configuration console so
+ * configuration for instances of this implementation can be made through
+ * the console.
*
* @return a list of configuration parameters.
* @exception EBaseException If an internal error occurred
*/
public String[] getConfigParams()
- throws EBaseException;
+ throws EBaseException;
/**
* Get the configuration store for this authentication manager.
+ *
* @return The configuration store of this authentication manager.
*/
public IConfigStore getConfigStore();
diff --git a/pki/base/common/src/com/netscape/certsrv/authentication/IAuthSubsystem.java b/pki/base/common/src/com/netscape/certsrv/authentication/IAuthSubsystem.java
index 2de8ed26..ba983742 100644
--- a/pki/base/common/src/com/netscape/certsrv/authentication/IAuthSubsystem.java
+++ b/pki/base/common/src/com/netscape/certsrv/authentication/IAuthSubsystem.java
@@ -26,7 +26,7 @@ import com.netscape.certsrv.base.ISubsystem;
/**
* An interface that represents an authentication component
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IAuthSubsystem extends ISubsystem {
@@ -39,17 +39,17 @@ public interface IAuthSubsystem extends ISubsystem {
/**
* Constant for class.
*/
- public static final String PROP_CLASS = "class";
+ public static final String PROP_CLASS = "class";
/**
* Constant for impl
*/
- public static final String PROP_IMPL = "impl";
+ public static final String PROP_IMPL = "impl";
/**
* Constant for pluginName.
*/
- public static final String PROP_PLUGIN = "pluginName";
+ public static final String PROP_PLUGIN = "pluginName";
/**
* Constant for instance.
@@ -120,19 +120,22 @@ public interface IAuthSubsystem extends ISubsystem {
/**
* Authenticate the given credentials using the given manager name.
+ *
* @param authCred The authentication credentials
* @param authMgrName The authentication manager name
* @return a authentication token.
- * @exception EMissingCredential when missing credential during authentication
+ * @exception EMissingCredential when missing credential during
+ * authentication
* @exception EInvalidCredentials when the credential is invalid
* @exception EBaseException If an error occurs during authentication.
*/
public IAuthToken authenticate(IAuthCredentials authCred, String authMgrName)
- throws EMissingCredential, EInvalidCredentials, EBaseException;
+ throws EMissingCredential, EInvalidCredentials, EBaseException;
/**
* Gets the required credential attributes for the given authentication
* manager.
+ *
* @param authMgrName The authentication manager name
* @return a Vector of required credential attribute names.
* @exception EBaseException If the required credential is missing
@@ -141,6 +144,7 @@ public interface IAuthSubsystem extends ISubsystem {
/**
* Adds (registers) the given authentication manager.
+ *
* @param name The authentication manager name
* @param authMgr The authentication manager instance.
*/
@@ -148,12 +152,14 @@ public interface IAuthSubsystem extends ISubsystem {
/**
* Deletes (deregisters) the given authentication manager.
+ *
* @param name The authentication manager name to delete.
*/
public void delete(String name);
/**
* Gets the Authentication manager instance of the specified name.
+ *
* @param name The authentication manager's name.
* @exception EBaseException when internal error occurs.
*/
@@ -162,18 +168,21 @@ public interface IAuthSubsystem extends ISubsystem {
/**
* Gets an enumeration of authentication managers registered to the
* authentication subsystem.
+ *
* @return a list of authentication managers
*/
public Enumeration<IAuthManager> getAuthManagers();
/**
* Gets an enumeration of authentication manager plugins.
+ *
* @return a list of authentication plugins
*/
public Enumeration<AuthMgrPlugin> getAuthManagerPlugins();
/**
* Gets a single authentication manager plugin implementation
+ *
* @param name given authentication plugin name
* @return the given authentication plugin
*/
@@ -181,17 +190,20 @@ public interface IAuthSubsystem extends ISubsystem {
/**
* Get configuration parameters for a authentication mgr plugin.
+ *
* @param implName The plugin name.
- * @return configuration parameters for the given authentication manager plugin
- * @exception EAuthMgrPluginNotFound If the authentication manager
- * plugin is not found.
+ * @return configuration parameters for the given authentication manager
+ * plugin
+ * @exception EAuthMgrPluginNotFound If the authentication manager plugin is
+ * not found.
* @exception EBaseException If an internal error occurred.
*/
- public String[] getConfigParams(String implName)
- throws EAuthMgrPluginNotFound, EBaseException;
+ public String[] getConfigParams(String implName)
+ throws EAuthMgrPluginNotFound, EBaseException;
/**
* Log error message.
+ *
* @param level log level
* @param msg error message
*/
@@ -199,28 +211,31 @@ public interface IAuthSubsystem extends ISubsystem {
/**
* Get a hashtable containing all authentication plugins.
+ *
* @return all authentication plugins.
*/
public Hashtable<String, AuthMgrPlugin> getPlugins();
/**
* Get a hashtable containing all authentication instances.
+ *
* @return all authentication instances.
*/
public Hashtable<?, ?> getInstances();
/**
* Get an authentication manager interface for the given name.
+ *
* @param name given authentication manager name.
* @return an authentication manager for the given manager name.
*/
public IAuthManager get(String name);
/**
- * Get an authentication manager plugin impl for the given name.
+ * Get an authentication manager plugin impl for the given name.
+ *
* @param name given authentication manager name.
* @return an authentication manager plugin
*/
public AuthMgrPlugin getAuthManagerPluginImpl(String name);
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/authentication/IAuthToken.java b/pki/base/common/src/com/netscape/certsrv/authentication/IAuthToken.java
index 94279363..6569b62e 100644
--- a/pki/base/common/src/com/netscape/certsrv/authentication/IAuthToken.java
+++ b/pki/base/common/src/com/netscape/certsrv/authentication/IAuthToken.java
@@ -32,14 +32,14 @@ import com.netscape.certsrv.usrgrp.Certificates;
*/
public interface IAuthToken {
- /**
- * Constant for userid.
- */
- public static final String USER_ID = "userid";
+ /**
+ * Constant for userid.
+ */
+ public static final String USER_ID = "userid";
/**
* Sets an attribute value within this AttrSet.
- *
+ *
* @param name the name of the attribute
* @param value the attribute object.
* @return false on an error
@@ -48,7 +48,7 @@ public interface IAuthToken {
/**
* Gets an attribute value.
- *
+ *
* @param name the name of the attribute to return.
* @exception EBaseException on attribute handling errors.
* @return the attribute value
@@ -58,151 +58,167 @@ public interface IAuthToken {
/**
* Returns an enumeration of the names of the attributes existing within
* this AttrSet.
- *
+ *
* @return an enumeration of the attribute names.
*/
public Enumeration<String> getElements();
/************
- * Helpers for non-string sets and gets.
- * These are needed because AuthToken is stored in IRequest (which can
- * only store string values
+ * Helpers for non-string sets and gets. These are needed because AuthToken
+ * is stored in IRequest (which can only store string values
*/
/**
- * Retrieves the byte array value for name. The value should have been
+ * Retrieves the byte array value for name. The value should have been
* previously stored as a byte array (it will be CMS.AtoB decoded).
- * @param name The attribute name.
- * @return The byte array or null on error.
+ *
+ * @param name The attribute name.
+ * @return The byte array or null on error.
*/
public byte[] getInByteArray(String name);
/**
* Stores the byte array with the associated key.
- * @param name The attribute name.
- * @param value The value to store
+ *
+ * @param name The attribute name.
+ * @param value The value to store
* @return false on an error
*/
public boolean set(String name, byte[] value);
/**
* Retrieves the Integer value for name.
- * @param name The attribute name.
- * @return The Integer or null on error.
+ *
+ * @param name The attribute name.
+ * @return The Integer or null on error.
*/
public Integer getInInteger(String name);
/**
* Stores the Integer with the associated key.
- * @param name The attribute name.
- * @param value The value to store
+ *
+ * @param name The attribute name.
+ * @param value The value to store
* @return false on an error
*/
public boolean set(String name, Integer value);
/**
* Retrieves the BigInteger array value for name.
- * @param name The attribute name.
- * @return The value or null on error.
+ *
+ * @param name The attribute name.
+ * @return The value or null on error.
*/
public BigInteger[] getInBigIntegerArray(String name);
/**
* Stores the BigInteger array with the associated key.
- * @param name The attribute name.
- * @param value The value to store
+ *
+ * @param name The attribute name.
+ * @param value The value to store
* @return false on an error
*/
public boolean set(String name, BigInteger[] value);
/**
* Retrieves the Date value for name.
- * @param name The attribute name.
- * @return The value or null on error.
+ *
+ * @param name The attribute name.
+ * @return The value or null on error.
*/
public Date getInDate(String name);
/**
* Stores the Date with the associated key.
- * @param name The attribute name.
- * @param value The value to store
+ *
+ * @param name The attribute name.
+ * @param value The value to store
* @return false on an error
*/
public boolean set(String name, Date value);
/**
* Retrieves the String array value for name.
- * @param name The attribute name.
- * @return The value or null on error.
+ *
+ * @param name The attribute name.
+ * @return The value or null on error.
*/
public String[] getInStringArray(String name);
/**
* Stores the String array with the associated key.
- * @param name The attribute name.
- * @param value The value to store
+ *
+ * @param name The attribute name.
+ * @param value The value to store
* @return False on error.
*/
public boolean set(String name, String[] value);
/**
* Retrieves the X509CertImpl value for name.
- * @param name The attribute name.
- * @return The value or null on error.
+ *
+ * @param name The attribute name.
+ * @return The value or null on error.
*/
public X509CertImpl getInCert(String name);
/**
* Stores the X509CertImpl with the associated key.
- * @param name The attribute name.
- * @param value The value to store
+ *
+ * @param name The attribute name.
+ * @param value The value to store
* @return false on error
*/
public boolean set(String name, X509CertImpl value);
/**
* Retrieves the CertificateExtensions value for name.
- * @param name The attribute name.
- * @return The value or null on error.
+ *
+ * @param name The attribute name.
+ * @return The value or null on error.
*/
public CertificateExtensions getInCertExts(String name);
/**
* Stores the CertificateExtensions with the associated key.
- * @param name The attribute name.
- * @param value The value to store
+ *
+ * @param name The attribute name.
+ * @param value The value to store
* @return false on error
*/
public boolean set(String name, CertificateExtensions value);
/**
* Retrieves the Certificates value for name.
- * @param name The attribute name.
- * @return The value or null on error.
+ *
+ * @param name The attribute name.
+ * @return The value or null on error.
*/
public Certificates getInCertificates(String name);
/**
* Stores the Certificates with the associated key.
- * @param name The attribute name.
- * @param value The value to store
+ *
+ * @param name The attribute name.
+ * @param value The value to store
* @return false on error
*/
public boolean set(String name, Certificates value);
/**
* Retrieves the byte[][] value for name.
- * @param name The attribute name.
- * @return The value or null on error.
+ *
+ * @param name The attribute name.
+ * @return The value or null on error.
*/
public byte[][] getInByteArrayArray(String name);
/**
* Stores the byte[][] with the associated key.
- * @param name The attribute name.
- * @param value The value to store
+ *
+ * @param name The attribute name.
+ * @param value The value to store
* @return false on error
*/
public boolean set(String name, byte[][] value);
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/authentication/ISSLClientCertProvider.java b/pki/base/common/src/com/netscape/certsrv/authentication/ISSLClientCertProvider.java
index d4bdf7bb..c85e6278 100644
--- a/pki/base/common/src/com/netscape/certsrv/authentication/ISSLClientCertProvider.java
+++ b/pki/base/common/src/com/netscape/certsrv/authentication/ISSLClientCertProvider.java
@@ -17,18 +17,15 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.authentication;
-
import java.security.cert.X509Certificate;
-
/**
- * This interface represents an object that captures the
- * SSL client certificate in a SSL session. Normally, this
- * object is a servlet.
+ * This interface represents an object that captures the SSL client certificate
+ * in a SSL session. Normally, this object is a servlet.
* <p>
- *
- * This interface is used to avoid the internal imeplemtnation
- * to have servlet (protocol handler) dependency.
+ *
+ * This interface is used to avoid the internal imeplemtnation to have servlet
+ * (protocol handler) dependency.
* <p>
*
* @version $Revision$, $Date$
@@ -37,7 +34,7 @@ public interface ISSLClientCertProvider {
/**
* Retrieves the SSL client certificate chain.
- *
+ *
* @return certificate chain
*/
public X509Certificate[] getClientCertificateChain();
diff --git a/pki/base/common/src/com/netscape/certsrv/authentication/ISharedToken.java b/pki/base/common/src/com/netscape/certsrv/authentication/ISharedToken.java
index eae65d17..830c8866 100644
--- a/pki/base/common/src/com/netscape/certsrv/authentication/ISharedToken.java
+++ b/pki/base/common/src/com/netscape/certsrv/authentication/ISharedToken.java
@@ -26,6 +26,7 @@ import org.mozilla.jss.pkix.cmc.PKIData;
*/
public interface ISharedToken {
- public String getSharedToken(PKIData cmcData);
- public String getSharedToken(BigInteger serialnum);
+ public String getSharedToken(PKIData cmcData);
+
+ public String getSharedToken(BigInteger serialnum);
}
diff --git a/pki/base/common/src/com/netscape/certsrv/authority/IAuthority.java b/pki/base/common/src/com/netscape/certsrv/authority/IAuthority.java
index 5916ecd0..2875e4dd 100644
--- a/pki/base/common/src/com/netscape/certsrv/authority/IAuthority.java
+++ b/pki/base/common/src/com/netscape/certsrv/authority/IAuthority.java
@@ -17,15 +17,13 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.authority;
-
import com.netscape.certsrv.base.ISubsystem;
import com.netscape.certsrv.request.IRequestListener;
import com.netscape.certsrv.request.IRequestQueue;
-
/**
* Authority interface.
- *
+ *
* @version $Revision$ $Date$
*/
public interface IAuthority extends ISubsystem {
@@ -33,6 +31,7 @@ public interface IAuthority extends ISubsystem {
/**
* Retrieves the request queue for the Authority.
* <P>
+ *
* @return the request queue.
*/
public IRequestQueue getRequestQueue();
diff --git a/pki/base/common/src/com/netscape/certsrv/authority/ICertAuthority.java b/pki/base/common/src/com/netscape/certsrv/authority/ICertAuthority.java
index 94d6df40..dea1329e 100644
--- a/pki/base/common/src/com/netscape/certsrv/authority/ICertAuthority.java
+++ b/pki/base/common/src/com/netscape/certsrv/authority/ICertAuthority.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.authority;
-
import netscape.security.x509.CertificateChain;
import netscape.security.x509.X500Name;
import netscape.security.x509.X509CertImpl;
@@ -27,12 +26,10 @@ import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.publish.IPublisherProcessor;
import com.netscape.certsrv.request.IRequestListener;
-
/**
- * Authority that handles certificates needed by the cert registration
- * servlets.
+ * Authority that handles certificates needed by the cert registration servlets.
* <P>
- *
+ *
* @version $Revision$ $Date$
*/
public interface ICertAuthority extends IAuthority {
@@ -40,7 +37,7 @@ public interface ICertAuthority extends IAuthority {
/**
* Retrieves the certificate repository for this authority.
* <P>
- *
+ *
* @return the certificate repository.
*/
public ICertificateRepository getCertificateRepository();
@@ -48,6 +45,7 @@ public interface ICertAuthority extends IAuthority {
/**
* Returns CA's certificate chain.
* <P>
+ *
* @return the Certificate Chain for the CA.
*/
public CertificateChain getCACertChain();
@@ -55,18 +53,19 @@ public interface ICertAuthority extends IAuthority {
/**
* Returns CA's certificate implementaion.
* <P>
+ *
* @return CA's certificate.
*/
public X509CertImpl getCACert();
/**
- * Returns signing algorithms supported by the CA.
- * Dependent on CA's key type and algorithms supported by security lib.
+ * Returns signing algorithms supported by the CA. Dependent on CA's key
+ * type and algorithms supported by security lib.
*/
public String[] getCASigningAlgorithms();
/**
- * Returns authority's X500 Name. - XXX what's this for ??
+ * Returns authority's X500 Name. - XXX what's this for ??
*/
public X500Name getX500Name();
@@ -86,15 +85,14 @@ public interface ICertAuthority extends IAuthority {
public void registerPendingListener(IRequestListener l);
/**
- * get authority's publishing module if any.
+ * get authority's publishing module if any.
*/
public IPublisherProcessor getPublisherProcessor();
-
+
/**
- * Returns the logging interface for this authority.
- * Using this interface both System and Audit events can be
- * logged.
- *
+ * Returns the logging interface for this authority. Using this interface
+ * both System and Audit events can be logged.
+ *
*/
public ILogger getLogger();
diff --git a/pki/base/common/src/com/netscape/certsrv/authorization/AuthzManagerProxy.java b/pki/base/common/src/com/netscape/certsrv/authorization/AuthzManagerProxy.java
index 0960311e..ed0df89a 100644
--- a/pki/base/common/src/com/netscape/certsrv/authorization/AuthzManagerProxy.java
+++ b/pki/base/common/src/com/netscape/certsrv/authorization/AuthzManagerProxy.java
@@ -17,10 +17,10 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.authorization;
-
/**
- * A class represents an authorization manager. It contains an
- * authorization manager instance and its state (enable or not).
+ * A class represents an authorization manager. It contains an authorization
+ * manager instance and its state (enable or not).
+ *
* @version $Revision$, $Date$
*/
public class AuthzManagerProxy {
@@ -29,9 +29,10 @@ public class AuthzManagerProxy {
/**
* Constructor
+ *
* @param enable true if the authzMgr is enabled; false otherwise
* @param mgr authorization manager instance
- */
+ */
public AuthzManagerProxy(boolean enable, IAuthzManager mgr) {
mEnable = enable;
mMgr = mgr;
@@ -39,6 +40,7 @@ public class AuthzManagerProxy {
/**
* Returns the state of the authorization manager instance
+ *
* @return true if the state of the authorization manager instance is
* enabled; false otherwise.
*/
@@ -48,6 +50,7 @@ public class AuthzManagerProxy {
/**
* Returns an authorization manager instance.
+ *
* @return an authorization manager instance
*/
public IAuthzManager getAuthzManager() {
diff --git a/pki/base/common/src/com/netscape/certsrv/authorization/AuthzMgrPlugin.java b/pki/base/common/src/com/netscape/certsrv/authorization/AuthzMgrPlugin.java
index aebe9170..e47e5817 100644
--- a/pki/base/common/src/com/netscape/certsrv/authorization/AuthzMgrPlugin.java
+++ b/pki/base/common/src/com/netscape/certsrv/authorization/AuthzMgrPlugin.java
@@ -17,13 +17,10 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.authorization;
-
-
-
/**
* This class represents a registered authorization manager plugin.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class AuthzMgrPlugin {
@@ -33,6 +30,7 @@ public class AuthzMgrPlugin {
/**
* Constructs a AuthzManager plugin.
+ *
* @param id authz manager implementation name
* @param classPath class path
*/
@@ -40,9 +38,10 @@ public class AuthzMgrPlugin {
mId = id;
mClassPath = classPath;
}
-
+
/**
* Returns an authorization manager implementation name
+ *
* @return an authorization manager implementation name
*/
public String getId() {
@@ -51,6 +50,7 @@ public class AuthzMgrPlugin {
/**
* Returns a classpath of a AuthzManager plugin
+ *
* @return a classpath of a AuthzManager plugin
*/
public String getClassPath() {
@@ -59,6 +59,7 @@ public class AuthzMgrPlugin {
/**
* Returns a visibility of the plugin
+ *
* @return a visibility of the plugin
*/
public boolean isVisible() {
@@ -67,6 +68,7 @@ public class AuthzMgrPlugin {
/**
* Sets visibility of the plugin
+ *
* @param visibility visibility of the plugin
*/
public void setVisible(boolean visibility) {
diff --git a/pki/base/common/src/com/netscape/certsrv/authorization/AuthzResources.java b/pki/base/common/src/com/netscape/certsrv/authorization/AuthzResources.java
index 7cb5240a..13d33c21 100644
--- a/pki/base/common/src/com/netscape/certsrv/authorization/AuthzResources.java
+++ b/pki/base/common/src/com/netscape/certsrv/authorization/AuthzResources.java
@@ -17,13 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.authorization;
-
import java.util.ListResourceBundle;
-
/**
* A class represents a resource bundle for the authorization subsystem
* <P>
+ *
* @deprecated
* @version $Revision$, $Date$
*/
@@ -31,6 +30,7 @@ public class AuthzResources extends ListResourceBundle {
/**
* Returns the content of this resource.
+ *
* @return the content of this resource
*/
public Object[][] getContents() {
diff --git a/pki/base/common/src/com/netscape/certsrv/authorization/AuthzToken.java b/pki/base/common/src/com/netscape/certsrv/authorization/AuthzToken.java
index 0b5db00a..2ef87742 100644
--- a/pki/base/common/src/com/netscape/certsrv/authorization/AuthzToken.java
+++ b/pki/base/common/src/com/netscape/certsrv/authorization/AuthzToken.java
@@ -17,21 +17,19 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.authorization;
-
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import com.netscape.certsrv.base.IAttrSet;
-
/**
- * Authorization token returned by Authorization Managers.
- * Upon return, it contains the name of the authorization manager that create
- * the AuthzToken, the plugin name of the authorization manager, time of
- * authorization happened, name of the resource, type of operation performed
- * on the resource.
+ * Authorization token returned by Authorization Managers. Upon return, it
+ * contains the name of the authorization manager that create the AuthzToken,
+ * the plugin name of the authorization manager, time of authorization happened,
+ * name of the resource, type of operation performed on the resource.
* <p>
+ *
* @version $Revision$, $Date$
*/
public class AuthzToken implements IAttrSet {
@@ -39,19 +37,19 @@ public class AuthzToken implements IAttrSet {
private Hashtable<String, Object> mAttrs = null;
/**
- * Plugin name of the authorization manager that created the
- * AuthzToken as a string.
+ * Plugin name of the authorization manager that created the AuthzToken as a
+ * string.
*/
public static final String TOKEN_AUTHZMGR_IMPL_NAME = "authzMgrImplName";
/**
- * Name of the authorization manager that created the AuthzToken
- * as a string.
+ * Name of the authorization manager that created the AuthzToken as a
+ * string.
*/
public static final String TOKEN_AUTHZMGR_INST_NAME = "authzMgrInstName";
/**
- * Time of authorization as a java.util.Date
+ * Time of authorization as a java.util.Date
*/
public static final String TOKEN_AUTHZTIME = "authzTime";
@@ -61,7 +59,7 @@ public class AuthzToken implements IAttrSet {
public static final String TOKEN_AUTHZ_RESOURCE = "authzRes";
/**
- * name of the operation
+ * name of the operation
*/
public static final String TOKEN_AUTHZ_OPERATION = "authzOp";
@@ -69,41 +67,45 @@ public class AuthzToken implements IAttrSet {
* Status of the authorization evaluation
*/
public static final String TOKEN_AUTHZ_STATUS = "status";
-
+
/**
- * Constant for the success status of the authorization evaluation.
+ * Constant for the success status of the authorization evaluation.
*/
public static final String AUTHZ_STATUS_SUCCESS = "statusSuccess";
/**
- * Constructs an instance of a authorization token.
- * The token by default contains the following attributes: <br>
+ * Constructs an instance of a authorization token. The token by default
+ * contains the following attributes: <br>
+ *
* <pre>
- * "authzMgrInstName" - The authorization manager instance name.
- * "authzMgrImplName" - The authorization manager plugin name.
- * "authzTime" - The - The time of authorization.
+ * "authzMgrInstName" - The authorization manager instance name.
+ * "authzMgrImplName" - The authorization manager plugin name.
+ * "authzTime" - The - The time of authorization.
* </pre>
+ *
* @param authzMgr The authorization manager that created this Token.
*/
public AuthzToken(IAuthzManager authzMgr) {
mAttrs = new Hashtable<String, Object>();
- mAttrs.put(TOKEN_AUTHZMGR_INST_NAME, authzMgr.getName());
- mAttrs.put(TOKEN_AUTHZMGR_IMPL_NAME, authzMgr.getImplName());
+ mAttrs.put(TOKEN_AUTHZMGR_INST_NAME, authzMgr.getName());
+ mAttrs.put(TOKEN_AUTHZMGR_IMPL_NAME, authzMgr.getImplName());
mAttrs.put(TOKEN_AUTHZTIME, new Date());
}
/**
* Get the value of an attribute in the AuthzToken
+ *
* @param attrName The attribute name
- * @return The value of attrName if any.
+ * @return The value of attrName if any.
*/
public Object get(String attrName) {
return mAttrs.get(attrName);
}
/**
- * Used by an Authorization manager to set an attribute and value
- * in the AuthzToken.
+ * Used by an Authorization manager to set an attribute and value in the
+ * AuthzToken.
+ *
* @param attrName The name of the attribute
* @param value The value of the attribute to set.
*/
@@ -113,6 +115,7 @@ public class AuthzToken implements IAttrSet {
/**
* Removes an attribute in the AuthzToken
+ *
* @param attrName The name of the attribute to remove.
*/
public void delete(String attrName) {
@@ -121,6 +124,7 @@ public class AuthzToken implements IAttrSet {
/**
* Enumerate all attribute names in the AuthzToken.
+ *
* @return Enumeration of all attribute names in this AuthzToken.
*/
public Enumeration<String> getElements() {
@@ -129,6 +133,7 @@ public class AuthzToken implements IAttrSet {
/**
* Enumerate all attribute values in the AuthzToken.
+ *
* @return Enumeration of all attribute names in this AuthzToken.
*/
public Enumeration<Object> getVals() {
@@ -136,10 +141,11 @@ public class AuthzToken implements IAttrSet {
}
/**
- * Gets the name of the authorization manager instance that created
- * this token.
- * @return The name of the authorization manager instance that created
- * this token.
+ * Gets the name of the authorization manager instance that created this
+ * token.
+ *
+ * @return The name of the authorization manager instance that created this
+ * token.
*/
public String getAuthzManagerInstName() {
return ((String) mAttrs.get(TOKEN_AUTHZMGR_INST_NAME));
@@ -148,8 +154,9 @@ public class AuthzToken implements IAttrSet {
/**
* Gets the plugin name of the authorization manager that created this
* token.
+ *
* @return The plugin name of the authorization manager that created this
- * token.
+ * token.
*/
public String getAuthzManagerImplName() {
return ((String) mAttrs.get(TOKEN_AUTHZMGR_IMPL_NAME));
@@ -157,10 +164,10 @@ public class AuthzToken implements IAttrSet {
/**
* Gets the time of authorization.
+ *
* @return The time of authorization
*/
public Date getAuthzTime() {
return ((Date) mAttrs.get(TOKEN_AUTHZTIME));
}
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/authorization/EAuthzAccessDenied.java b/pki/base/common/src/com/netscape/certsrv/authorization/EAuthzAccessDenied.java
index 18429c98..9fc7777c 100644
--- a/pki/base/common/src/com/netscape/certsrv/authorization/EAuthzAccessDenied.java
+++ b/pki/base/common/src/com/netscape/certsrv/authorization/EAuthzAccessDenied.java
@@ -29,9 +29,10 @@ public class EAuthzAccessDenied extends EAuthzException {
/**
* Constructs a exception for access denied by Authz manager
+ *
* @param errorString Detailed error message.
*/
public EAuthzAccessDenied(String errorString) {
- super(errorString);
+ super(errorString);
}
}
diff --git a/pki/base/common/src/com/netscape/certsrv/authorization/EAuthzException.java b/pki/base/common/src/com/netscape/certsrv/authorization/EAuthzException.java
index 869a021c..65d95a57 100644
--- a/pki/base/common/src/com/netscape/certsrv/authorization/EAuthzException.java
+++ b/pki/base/common/src/com/netscape/certsrv/authorization/EAuthzException.java
@@ -17,12 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.authorization;
-
import com.netscape.certsrv.base.EBaseException;
/**
* This class represents authorization exceptions.
* <P>
+ *
* @version $Revision$, $Date$
*/
public class EAuthzException extends EBaseException {
@@ -39,6 +39,7 @@ public class EAuthzException extends EBaseException {
/**
* Constructs a authz exception
* <P>
+ *
* @param msgFormat exception details
*/
public EAuthzException(String msgFormat) {
@@ -46,8 +47,9 @@ public class EAuthzException extends EBaseException {
}
/**
- * Constructs a authz exception with a parameter.
+ * Constructs a authz exception with a parameter.
* <p>
+ *
* @param msgFormat exception details in message string format
* @param param message string parameter
*/
@@ -58,6 +60,7 @@ public class EAuthzException extends EBaseException {
/**
* Constructs a authz exception with a exception parameter.
* <P>
+ *
* @param msgFormat exception details in message string format
* @param param system exception
*/
@@ -68,6 +71,7 @@ public class EAuthzException extends EBaseException {
/**
* Constructs a authz exception with a list of parameters.
* <P>
+ *
* @param msgFormat the message format.
* @param params list of message format parameters
*/
@@ -77,6 +81,7 @@ public class EAuthzException extends EBaseException {
/**
* Returns the resource bundle name
+ *
* @return resource bundle name
*/
protected String getBundleName() {
diff --git a/pki/base/common/src/com/netscape/certsrv/authorization/EAuthzInternalError.java b/pki/base/common/src/com/netscape/certsrv/authorization/EAuthzInternalError.java
index ff7da13d..2afe2c74 100644
--- a/pki/base/common/src/com/netscape/certsrv/authorization/EAuthzInternalError.java
+++ b/pki/base/common/src/com/netscape/certsrv/authorization/EAuthzInternalError.java
@@ -29,6 +29,7 @@ public class EAuthzInternalError extends EAuthzException {
/**
* Constructs an authorization internal error exception
+ *
* @param errorString error with a detailed message.
*/
public EAuthzInternalError(String errorString) {
diff --git a/pki/base/common/src/com/netscape/certsrv/authorization/EAuthzMgrNotFound.java b/pki/base/common/src/com/netscape/certsrv/authorization/EAuthzMgrNotFound.java
index 944b9854..a920d37a 100644
--- a/pki/base/common/src/com/netscape/certsrv/authorization/EAuthzMgrNotFound.java
+++ b/pki/base/common/src/com/netscape/certsrv/authorization/EAuthzMgrNotFound.java
@@ -29,6 +29,7 @@ public class EAuthzMgrNotFound extends EAuthzException {
/**
* Constructs a exception for a missing required authorization manager
+ *
* @param errorString Detailed error message.
*/
public EAuthzMgrNotFound(String errorString) {
diff --git a/pki/base/common/src/com/netscape/certsrv/authorization/EAuthzMgrPluginNotFound.java b/pki/base/common/src/com/netscape/certsrv/authorization/EAuthzMgrPluginNotFound.java
index b44e4711..43ae6edc 100644
--- a/pki/base/common/src/com/netscape/certsrv/authorization/EAuthzMgrPluginNotFound.java
+++ b/pki/base/common/src/com/netscape/certsrv/authorization/EAuthzMgrPluginNotFound.java
@@ -29,6 +29,7 @@ public class EAuthzMgrPluginNotFound extends EAuthzException {
/**
* Constructs a exception for a missing authorization plugin
+ *
* @param errorString Detailed error message.
*/
public EAuthzMgrPluginNotFound(String errorString) {
diff --git a/pki/base/common/src/com/netscape/certsrv/authorization/EAuthzUnknownOperation.java b/pki/base/common/src/com/netscape/certsrv/authorization/EAuthzUnknownOperation.java
index 025306cb..9bbfa0c9 100644
--- a/pki/base/common/src/com/netscape/certsrv/authorization/EAuthzUnknownOperation.java
+++ b/pki/base/common/src/com/netscape/certsrv/authorization/EAuthzUnknownOperation.java
@@ -28,7 +28,9 @@ public class EAuthzUnknownOperation extends EAuthzException {
private static final long serialVersionUID = 4344508835702220953L;
/**
- * Constructs a exception for an operation unknown to the authorization manager
+ * Constructs a exception for an operation unknown to the authorization
+ * manager
+ *
* @param errorString Detailed error message.
*/
public EAuthzUnknownOperation(String errorString) {
diff --git a/pki/base/common/src/com/netscape/certsrv/authorization/EAuthzUnknownProtectedRes.java b/pki/base/common/src/com/netscape/certsrv/authorization/EAuthzUnknownProtectedRes.java
index 4d7695a8..0bc5a0ba 100644
--- a/pki/base/common/src/com/netscape/certsrv/authorization/EAuthzUnknownProtectedRes.java
+++ b/pki/base/common/src/com/netscape/certsrv/authorization/EAuthzUnknownProtectedRes.java
@@ -28,7 +28,9 @@ public class EAuthzUnknownProtectedRes extends EAuthzException {
private static final long serialVersionUID = 444663701711532889L;
/**
- * Constructs a exception for a protected resource unknown to the authorization manager
+ * Constructs a exception for a protected resource unknown to the
+ * authorization manager
+ *
* @param errorString Detailed error message.
*/
public EAuthzUnknownProtectedRes(String errorString) {
diff --git a/pki/base/common/src/com/netscape/certsrv/authorization/IAuthzManager.java b/pki/base/common/src/com/netscape/certsrv/authorization/IAuthzManager.java
index 25a66505..60c512c8 100644
--- a/pki/base/common/src/com/netscape/certsrv/authorization/IAuthzManager.java
+++ b/pki/base/common/src/com/netscape/certsrv/authorization/IAuthzManager.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.authorization;
-
import java.util.Enumeration;
import java.util.Hashtable;
@@ -29,12 +28,11 @@ import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.evaluators.IAccessEvaluator;
-
/**
- * Authorization Manager interface needs to be implemented by all
- * authorization managers.
+ * Authorization Manager interface needs to be implemented by all authorization
+ * managers.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IAuthzManager {
@@ -42,6 +40,7 @@ public interface IAuthzManager {
/**
* Get the name of this authorization manager instance.
* <p>
+ *
* @return String the name of this authorization manager.
*/
public String getName();
@@ -50,30 +49,34 @@ public interface IAuthzManager {
* Get implementation name of authorization manager plugin.
* <p>
* An example of an implementation name will be:
+ *
* <PRE>
* com.netscape.cms.BasicAclAuthz
* </PRE>
* <p>
+ *
* @return The name of the authorization manager plugin.
- */
+ */
public String getImplName();
/**
- * <code>accessInit</code> is for servlets who want to initialize their
- * own authorization information before full operation. It is supposed
- * to be called from the authzMgrAccessInit() method of the AuthzSubsystem.
+ * <code>accessInit</code> is for servlets who want to initialize their own
+ * authorization information before full operation. It is supposed to be
+ * called from the authzMgrAccessInit() method of the AuthzSubsystem.
* <p>
- * The accessInfo format is determined by each individual
- * authzmgr. For example, for BasicAclAuthz,
- * The accessInfo is the resACLs, whose format should conform
- * to the following:
+ * The accessInfo format is determined by each individual authzmgr. For
+ * example, for BasicAclAuthz, The accessInfo is the resACLs, whose format
+ * should conform to the following:
+ *
* <pre>
* <resource ID>:right-1[,right-n]:[allow,deny](right(s))<evaluatorType>=<value>:<comment for this resource acl
* </pre>
* <P>
- * Example:
- * resTurnKnob:left,right:allow(left) group="lefties":door knobs for lefties
- * @param accessInfo the access info string in the format specified in the authorization manager
+ * Example: resTurnKnob:left,right:allow(left) group="lefties":door knobs
+ * for lefties
+ *
+ * @param accessInfo the access info string in the format specified in the
+ * authorization manager
* @exception EBaseException error parsing the accessInfo
*/
public void accessInit(String accessInfo) throws EBaseException;
@@ -81,6 +84,7 @@ public interface IAuthzManager {
/**
* Check if the user is authorized to perform the given operation on the
* given resource.
+ *
* @param authToken the authToken associated with a user.
* @param resource - the protected resource name
* @param operation - the protected resource operation name
@@ -89,53 +93,56 @@ public interface IAuthzManager {
* @exception EAuthzAccessDenied if access denied
*/
public AuthzToken authorize(IAuthToken authToken, String resource, String operation)
- throws EAuthzInternalError, EAuthzAccessDenied;
+ throws EAuthzInternalError, EAuthzAccessDenied;
public AuthzToken authorize(IAuthToken authToken, String expression)
- throws EAuthzInternalError, EAuthzAccessDenied;
+ throws EAuthzInternalError, EAuthzAccessDenied;
/**
* Initialize this authorization manager.
+ *
* @param name The name of this authorization manager instance.
* @param implName The name of the authorization manager plugin.
* @param config The configuration store for this authorization manager.
* @exception EBaseException If an initialization error occurred.
*/
public void init(String name, String implName, IConfigStore config)
- throws EBaseException;
+ throws EBaseException;
/**
- * Prepare this authorization manager for a graceful shutdown.
- * Called when the server is exiting for any cleanup needed.
+ * Prepare this authorization manager for a graceful shutdown. Called when
+ * the server is exiting for any cleanup needed.
*/
public void shutdown();
/**
- * Get configuration parameters for this implementation.
- * The configuration parameters returned is passed to the
- * console so configuration for instances of this
- * implementation can be made through the console.
+ * Get configuration parameters for this implementation. The configuration
+ * parameters returned is passed to the console so configuration for
+ * instances of this implementation can be made through the console.
*
* @return a list of names for configuration parameters.
* @exception EBaseException If an internal error occurred
*/
public String[] getConfigParams()
- throws EBaseException;
+ throws EBaseException;
/**
* Get the configuration store for this authorization manager.
+ *
* @return The configuration store of this authorization manager.
*/
public IConfigStore getConfigStore();
/**
* Get ACL entries
+ *
* @return enumeration of ACL entries.
*/
public Enumeration<ACL> getACLs();
/**
* Get individual ACL entry for the given name of entry.
+ *
* @param target The name of the ACL entry
* @return The ACL entry.
*/
@@ -143,23 +150,26 @@ public interface IAuthzManager {
/**
* Update ACLs in the database
+ *
* @param id The name of the ACL entry (ie, resource id)
* @param rights The allowable rights for this resource
* @param strACLs The value of the ACL entry
* @param desc The description for this resource
* @exception EACLsException when update fails.
*/
- public void updateACLs(String id, String rights, String strACLs,
- String desc) throws EACLsException;
+ public void updateACLs(String id, String rights, String strACLs,
+ String desc) throws EACLsException;
/**
* Get all registered evaluators.
+ *
* @return All registered evaluators.
*/
public Enumeration<IAccessEvaluator> aclEvaluatorElements();
/**
* Register new evaluator
+ *
* @param type Type of evaluator
* @param evaluator Value of evaluator
*/
@@ -167,8 +177,8 @@ public interface IAuthzManager {
/**
* Return a table of evaluators
+ *
* @return A table of evaluators
*/
- public Hashtable<String, IAccessEvaluator> getAccessEvaluators();
+ public Hashtable<String, IAccessEvaluator> getAccessEvaluators();
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/authorization/IAuthzSubsystem.java b/pki/base/common/src/com/netscape/certsrv/authorization/IAuthzSubsystem.java
index 281a11a2..49c3570c 100644
--- a/pki/base/common/src/com/netscape/certsrv/authorization/IAuthzSubsystem.java
+++ b/pki/base/common/src/com/netscape/certsrv/authorization/IAuthzSubsystem.java
@@ -27,11 +27,11 @@ import com.netscape.certsrv.base.ISubsystem;
/**
* An interface that represents an authorization component
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IAuthzSubsystem extends ISubsystem {
-
+
/**
* Constant for auths.
*/
@@ -40,17 +40,17 @@ public interface IAuthzSubsystem extends ISubsystem {
/**
* Constant for class.
*/
- public static final String PROP_CLASS = "class";
+ public static final String PROP_CLASS = "class";
/**
* Constant for impl
*/
- public static final String PROP_IMPL = "impl";
+ public static final String PROP_IMPL = "impl";
/**
* Constant for pluginName.
*/
- public static final String PROP_PLUGIN = "pluginName";
+ public static final String PROP_PLUGIN = "pluginName";
/**
* Constant for instance.
@@ -60,22 +60,25 @@ public interface IAuthzSubsystem extends ISubsystem {
/**
* authorize the user associated with the given authToken for a given
* operation with the given authorization manager name
+ *
* @param authzMgrName The authorization manager name
* @param authToken the authenticaton token associated with a user
* @param resource the resource protected by the authorization system
- * @param operation the operation for resource protected by the authorization system
+ * @param operation the operation for resource protected by the
+ * authorization system
* @return a authorization token.
* @exception EBaseException If an error occurs during authorization.
*/
public AuthzToken authorize(String authzMgrName, IAuthToken authToken,
- String resource, String operation)
- throws EBaseException;
+ String resource, String operation)
+ throws EBaseException;
public AuthzToken authorize(String authzMgrName, IAuthToken authToken,
- String exp) throws EBaseException;
+ String exp) throws EBaseException;
/**
* Adds (registers) the given authorization manager.
+ *
* @param name The authorization manager name
* @param authzMgr The authorization manager instance.
*/
@@ -83,12 +86,14 @@ public interface IAuthzSubsystem extends ISubsystem {
/**
* Deletes (deregisters) the given authorization manager.
+ *
* @param name The authorization manager name to delete.
*/
public void delete(String name);
/**
* Gets the Authorization manager instance of the specified name.
+ *
* @param name The authorization manager's name.
* @return an authorization manager interface
*/
@@ -97,6 +102,7 @@ public interface IAuthzSubsystem extends ISubsystem {
/**
* Gets an enumeration of authorization managers registered to the
* authorization component.
+ *
* @return a list of authorization managers
*/
public Enumeration<IAuthzManager> getAuthzManagers();
@@ -112,12 +118,14 @@ public interface IAuthzSubsystem extends ISubsystem {
/**
* Gets an enumeration of authorization manager plugins.
+ *
* @return list of authorization manager plugins
*/
- public Enumeration<AuthzMgrPlugin> getAuthzManagerPlugins();
+ public Enumeration<AuthzMgrPlugin> getAuthzManagerPlugins();
/**
* Gets a single authorization manager plugin implementation
+ *
* @param name given authorization plugin name
* @return authorization manager plugin
*/
@@ -125,6 +133,7 @@ public interface IAuthzSubsystem extends ISubsystem {
/**
* Log error message.
+ *
* @param level log level
* @param msg error message
*/
@@ -132,21 +141,23 @@ public interface IAuthzSubsystem extends ISubsystem {
/**
* Get a hashtable containing all authentication plugins.
+ *
* @return all authentication plugins.
*/
public Hashtable<String, AuthzMgrPlugin> getPlugins();
/**
* Get a hashtable containing all authentication instances.
+ *
* @return all authentication instances.
*/
public Hashtable<String, AuthzManagerProxy> getInstances();
/**
* Get an authorization manager interface for the given name.
+ *
* @param name given authorization manager name.
* @return an authorization manager interface
*/
public IAuthzManager get(String name);
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/base/ASubsystem.java b/pki/base/common/src/com/netscape/certsrv/base/ASubsystem.java
index ea334230..d6b21052 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/ASubsystem.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/ASubsystem.java
@@ -17,12 +17,10 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.base;
-
/**
- * This class represents a basic subsystem. Each basic
- * subsystem is named with an identifier and has a
- * configuration store.
- *
+ * This class represents a basic subsystem. Each basic subsystem is named with
+ * an identifier and has a configuration store.
+ *
* @version $Revision$, $Date$
*/
public abstract class ASubsystem implements ISubsystem {
@@ -33,7 +31,7 @@ public abstract class ASubsystem implements ISubsystem {
/**
* Initializes this subsystem.
- *
+ *
* @param parent parent subsystem
* @param cfg configuration store
*/
@@ -44,7 +42,7 @@ public abstract class ASubsystem implements ISubsystem {
/**
* Retrieves the configuration store.
- *
+ *
* @return configuration store
*/
public IConfigStore getConfigStore() {
@@ -53,7 +51,7 @@ public abstract class ASubsystem implements ISubsystem {
/**
* Sets the identifier of this subsystem.
- *
+ *
* @param id subsystem identifier
*/
public void setId(String id) {
@@ -62,7 +60,7 @@ public abstract class ASubsystem implements ISubsystem {
/**
* Retrieves the subsystem identifier.
- *
+ *
* @return subsystem identifier
*/
public String getId() {
diff --git a/pki/base/common/src/com/netscape/certsrv/base/AttributeNameHelper.java b/pki/base/common/src/com/netscape/certsrv/base/AttributeNameHelper.java
index 786148a0..eee51ca0 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/AttributeNameHelper.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/AttributeNameHelper.java
@@ -17,25 +17,24 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.base;
-
/**
- * AttributeNameHelper. This Helper class used to decompose
- * dot-separated attribute name into prefix and suffix.
- *
+ * AttributeNameHelper. This Helper class used to decompose dot-separated
+ * attribute name into prefix and suffix.
+ *
* @version $Revision$, $Date$
*/
public class AttributeNameHelper {
// Public members
private static final char SEPARATOR = '.';
-
+
// Private data members
private String prefix = null;
private String suffix = null;
-
+
/**
* Default constructor for the class. Name is of the form
* "proofOfPosession.type".
- *
+ *
* @param name the attribute name.
*/
public AttributeNameHelper(String name) {
@@ -51,20 +50,19 @@ public class AttributeNameHelper {
/**
* Return the prefix of the name.
- *
+ *
* @return attribute prefix
*/
public String getPrefix() {
return (prefix);
}
-
+
/**
* Return the suffix of the name.
- *
+ *
* @return attribute suffix
*/
public String getSuffix() {
return (suffix);
}
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/base/BaseResources.java b/pki/base/common/src/com/netscape/certsrv/base/BaseResources.java
index f54f1377..e8752646 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/BaseResources.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/BaseResources.java
@@ -17,15 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.base;
-
import java.util.ListResourceBundle;
-
/**
- * A class represents a resource bundle for the entire
- * system.
+ * A class represents a resource bundle for the entire system.
* <P>
- *
+ *
* @version $Revision$, $Date$
* @see java.util.ListResourceBundle
*/
@@ -39,8 +36,7 @@ public class BaseResources extends ListResourceBundle {
}
/*
- * Constants. The suffix represents the number of
- * possible parameters.
+ * Constants. The suffix represents the number of possible parameters.
*/
static final Object[][] contents = {};
diff --git a/pki/base/common/src/com/netscape/certsrv/base/EBaseException.java b/pki/base/common/src/com/netscape/certsrv/base/EBaseException.java
index e58aaca2..8b84a636 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/EBaseException.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/EBaseException.java
@@ -17,15 +17,13 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.base;
-
import java.util.Locale;
-
/**
- * An exception with localizable error messages. It is the
- * base class for all exceptions in certificate server.
+ * An exception with localizable error messages. It is the base class for all
+ * exceptions in certificate server.
* <P>
- *
+ *
* @version $Revision$, $Date$
* @see java.text.MessageFormat
* @see com.netscape.certsrv.base.BaseResources
@@ -38,8 +36,8 @@ public class EBaseException extends Exception {
private static final long serialVersionUID = 8213021692117483973L;
/**
- * The resource bundle to use for error messages.
- * Subclasses can override to use its own resource bundle.
+ * The resource bundle to use for error messages. Subclasses can override to
+ * use its own resource bundle.
*/
private static final String BASE_RESOURCES = BaseResources.class.getName();
@@ -49,12 +47,13 @@ public class EBaseException extends Exception {
public Object mParams[] = null;
/**
- * Constructs an instance of this exception with the given resource key.
- * If resource key is not found in the resource bundle, the resource key
+ * Constructs an instance of this exception with the given resource key. If
+ * resource key is not found in the resource bundle, the resource key
* specified is used as the error message.
+ *
* <pre>
- * new EBaseException(BaseResources.PERMISSION_DENIED);
- * new EBaseException("An plain error message");
+ * new EBaseException(BaseResources.PERMISSION_DENIED);
+ * new EBaseException(&quot;An plain error message&quot;);
* <P>
* @param msgFormat The error message resource key.
*/
@@ -64,12 +63,14 @@ public class EBaseException extends Exception {
}
/**
- * Constructs an instance of this exception with the given resource key
- * and a parameter as a string.
+ * Constructs an instance of this exception with the given resource key and
+ * a parameter as a string.
+ *
* <PRE>
- * new EBaseException(BaseResource.NO_CONFIG_FILE, fileName);
+ * new EBaseException(BaseResource.NO_CONFIG_FILE, fileName);
* </PRE>
* <P>
+ *
* @param msgFormat exception details in message string format
* @param param message string parameter
*/
@@ -80,8 +81,9 @@ public class EBaseException extends Exception {
}
/**
- * Constructs an instance of the exception given the resource key and
- * a exception parameter.
+ * Constructs an instance of the exception given the resource key and a
+ * exception parameter.
+ *
* <PRE>
* try {
* ...
@@ -90,6 +92,7 @@ public class EBaseException extends Exception {
* }
* </PRE>
* <P>
+ *
* @param msgFormat The resource key
* @param param The parameter as an exception
*/
@@ -100,9 +103,10 @@ public class EBaseException extends Exception {
}
/**
- * Constructs an instance of this exception given the resource key and
- * an array of parameters.
+ * Constructs an instance of this exception given the resource key and an
+ * array of parameters.
* <P>
+ *
* @param msgFormat The resource key
* @param params Array of params
*/
@@ -114,7 +118,7 @@ public class EBaseException extends Exception {
/**
* Returns the list of parameters.
* <P>
- *
+ *
* @return List of parameters.
*/
public Object[] getParameters() {
@@ -124,6 +128,7 @@ public class EBaseException extends Exception {
/**
* Returns the exception string in the default locale.
* <P>
+ *
* @return The exception string in the default locale.
*/
public String toString() {
@@ -133,6 +138,7 @@ public class EBaseException extends Exception {
/**
* Returns the exception string in the given locale.
* <P>
+ *
* @param locale The locale
* @return The exception string in the given locale.
*/
@@ -143,6 +149,7 @@ public class EBaseException extends Exception {
/**
* Returns the given resource bundle name.
+ *
* @return the name of the resource bundle for this class.
*/
protected String getBundleName() {
diff --git a/pki/base/common/src/com/netscape/certsrv/base/EPropertyNotDefined.java b/pki/base/common/src/com/netscape/certsrv/base/EPropertyNotDefined.java
index 938c9fff..89a78031 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/EPropertyNotDefined.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/EPropertyNotDefined.java
@@ -17,13 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.base;
-
/**
- * This class represents an exception thrown when a
- * property is not defined (empty string) the configuration store.
- * It extends EBaseException and uses the same resource bundle.
+ * This class represents an exception thrown when a property is not defined
+ * (empty string) the configuration store. It extends EBaseException and uses
+ * the same resource bundle.
* <p>
- *
+ *
* @version $Revision$, $Date$
* @see com.netscape.certsrv.base.EBaseException
*/
@@ -35,9 +34,10 @@ public class EPropertyNotDefined extends EBaseException {
private static final long serialVersionUID = -7986464387187170352L;
/**
- * Constructs an instance of this exception given the name of the
- * property that's not found.
+ * Constructs an instance of this exception given the name of the property
+ * that's not found.
* <p>
+ *
* @param errorString Detailed error message.
*/
public EPropertyNotDefined(String errorString) {
diff --git a/pki/base/common/src/com/netscape/certsrv/base/EPropertyNotFound.java b/pki/base/common/src/com/netscape/certsrv/base/EPropertyNotFound.java
index 833a393a..b442f009 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/EPropertyNotFound.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/EPropertyNotFound.java
@@ -17,13 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.base;
-
/**
- * This class represents an exception thrown when a
- * property is not found in the configuration store.
- * It extends EBaseException and uses the same resource bundle.
+ * This class represents an exception thrown when a property is not found in the
+ * configuration store. It extends EBaseException and uses the same resource
+ * bundle.
* <p>
- *
+ *
* @version $Revision$, $Date$
* @see com.netscape.certsrv.base.EBaseException
*/
@@ -35,9 +34,10 @@ public class EPropertyNotFound extends EBaseException {
private static final long serialVersionUID = 2701966082697733003L;
/**
- * Constructs an instance of this exception given the name of the
- * property that's not found.
+ * Constructs an instance of this exception given the name of the property
+ * that's not found.
* <p>
+ *
* @param errorString Detailed error message.
*/
public EPropertyNotFound(String errorString) {
diff --git a/pki/base/common/src/com/netscape/certsrv/base/ExtendedPluginInfo.java b/pki/base/common/src/com/netscape/certsrv/base/ExtendedPluginInfo.java
index a0399d34..cba4482a 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/ExtendedPluginInfo.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/ExtendedPluginInfo.java
@@ -17,14 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.base;
-
import java.util.Locale;
-
/**
* Plugin which can return extended information to console
* <p>
- *
+ *
* @version $Revision$, $Date$
*/
public class ExtendedPluginInfo implements IExtendedPluginInfo {
@@ -33,7 +31,7 @@ public class ExtendedPluginInfo implements IExtendedPluginInfo {
/**
* Constructs an extended plugin info object.
- *
+ *
* @param epi plugin info list
*/
public ExtendedPluginInfo(String epi[]) {
@@ -41,48 +39,43 @@ public class ExtendedPluginInfo implements IExtendedPluginInfo {
}
/**
- * This method returns an array of strings. Each element of the
- * array represents a configurable parameter, or some other
- * meta-info (such as help-token)
+ * This method returns an array of strings. Each element of the array
+ * represents a configurable parameter, or some other meta-info (such as
+ * help-token)
+ *
+ * there is an entry indexed on that parameter name
+ * <param-name>;<type_info>[,required];<description>;...
+ *
+ * Where:
+ *
+ * type_info is either 'string', 'number', 'boolean', 'password' or
+ * 'choice(ch1,ch2,ch3,...)'
+ *
+ * If the marker 'required' is included after the type_info, the parameter
+ * will has some visually distinctive marking in the UI.
+ *
+ * 'description' is a short sentence describing the parameter 'choice' is
+ * rendered as a drop-down list. The first parameter in the list will be
+ * activated by default 'boolean' is rendered as a checkbox. The resulting
+ * parameter will be either 'true' or 'false' 'string' allows any characters
+ * 'number' allows only numbers 'password' is rendered as a password field
+ * (the characters are replaced with *'s when being types. This parameter is
+ * not passed through to the plugin. It is instead inserted directly into
+ * the password cache keyed on the instance name. The value of the parameter
+ * 'bindPWPrompt' (see example below) is set to the key.
+ *
+ * In addition to the configurable parameters, the following magic
+ * parameters may be defined:
+ *
+ * HELP_TOKEN;helptoken - a pointer to the online manual section for this
+ * plugin HELP_TEXT;helptext - a general help string describing the plugin
*
- * there is an entry indexed on that parameter name
- * <param-name>;<type_info>[,required];<description>;...
- *
- * Where:
- *
- * type_info is either 'string', 'number', 'boolean', 'password' or
- * 'choice(ch1,ch2,ch3,...)'
- *
- * If the marker 'required' is included after the type_info,
- * the parameter will has some visually distinctive marking in
- * the UI.
+ * For example: "username;string;The username you wish to login as"
+ * "bindPWPrompt;password;Enter password to bind as above user with"
+ * "algorithm;choice(RSA,DSA);Which algorithm do you want to use"
+ * "enable;boolean;Do you want to run this plugin"
+ * "port;number;Which port number do you want to use"
*
- * 'description' is a short sentence describing the parameter
- * 'choice' is rendered as a drop-down list. The first parameter in the
- * list will be activated by default
- * 'boolean' is rendered as a checkbox. The resulting parameter will be
- * either 'true' or 'false'
- * 'string' allows any characters
- * 'number' allows only numbers
- * 'password' is rendered as a password field (the characters are replaced
- * with *'s when being types. This parameter is not passed through to
- * the plugin. It is instead inserted directly into the password cache
- * keyed on the instance name. The value of the parameter
- * 'bindPWPrompt' (see example below) is set to the key.
- *
- * In addition to the configurable parameters, the following magic parameters
- * may be defined:
- *
- * HELP_TOKEN;helptoken - a pointer to the online manual section for this plugin
- * HELP_TEXT;helptext - a general help string describing the plugin
- *
- * For example:
- * "username;string;The username you wish to login as"
- * "bindPWPrompt;password;Enter password to bind as above user with"
- * "algorithm;choice(RSA,DSA);Which algorithm do you want to use"
- * "enable;boolean;Do you want to run this plugin"
- * "port;number;Which port number do you want to use"
- *
*/
public String[] getExtendedPluginInfo(Locale locale) {
return _epi;
diff --git a/pki/base/common/src/com/netscape/certsrv/base/IArgBlock.java b/pki/base/common/src/com/netscape/certsrv/base/IArgBlock.java
index 65ca140e..84e6e5ec 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/IArgBlock.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/IArgBlock.java
@@ -23,32 +23,30 @@ import java.util.Enumeration;
import netscape.security.pkcs.PKCS10;
-
/**
- * This interface defines the abstraction for the generic collection
- * of attributes indexed by string names.
- * Set of cooperating implementations of this interface may exploit
- * dot-separated attribute names to provide seamless access to the
- * attributes of attribute value which also implements AttrSet
- * interface as if it was direct attribute of the container
- * E.g., ((AttrSet)container.get("x")).get("y") is equivalent to
- * container.get("x.y");
+ * This interface defines the abstraction for the generic collection of
+ * attributes indexed by string names. Set of cooperating implementations of
+ * this interface may exploit dot-separated attribute names to provide seamless
+ * access to the attributes of attribute value which also implements AttrSet
+ * interface as if it was direct attribute of the container E.g.,
+ * ((AttrSet)container.get("x")).get("y") is equivalent to container.get("x.y");
* <p>
- *
+ *
* @version $Revision$, $Date$
**/
public interface IArgBlock extends Serializable {
/**
* Checks if this argument block contains the given key.
- *
+ *
* @param n key
* @return true if key is present
*/
public boolean isValuePresent(String n);
+
/**
* Adds string-based value into this argument block.
- *
+ *
* @param n key
* @param v value
* @return value
@@ -57,7 +55,7 @@ public interface IArgBlock extends Serializable {
/**
* Retrieves argument value as string.
- *
+ *
* @param n key
* @return argument value as string
* @exception EBaseException failed to retrieve value
@@ -66,7 +64,7 @@ public interface IArgBlock extends Serializable {
/**
* Retrieves argument value as string.
- *
+ *
* @param n key
* @param def default value to be returned if key is not present
* @return argument value as string
@@ -75,16 +73,16 @@ public interface IArgBlock extends Serializable {
/**
* Retrieves argument value as integer.
- *
+ *
* @param n key
* @return argument value as int
* @exception EBaseException failed to retrieve value
*/
- public int getValueAsInt(String n) throws EBaseException;
+ public int getValueAsInt(String n) throws EBaseException;
/**
* Retrieves argument value as integer.
- *
+ *
* @param n key
* @param def default value to be returned if key is not present
* @return argument value as int
@@ -93,7 +91,7 @@ public interface IArgBlock extends Serializable {
/**
* Retrieves argument value as big integer.
- *
+ *
* @param n key
* @return argument value as big integer
* @exception EBaseException failed to retrieve value
@@ -102,7 +100,7 @@ public interface IArgBlock extends Serializable {
/**
* Retrieves argument value as big integer.
- *
+ *
* @param n key
* @param def default value to be returned if key is not present
* @return argument value as big integer
@@ -111,7 +109,7 @@ public interface IArgBlock extends Serializable {
/**
* Retrieves argument value as object
- *
+ *
* @param n key
* @return argument value as object
* @exception EBaseException failed to retrieve value
@@ -120,7 +118,7 @@ public interface IArgBlock extends Serializable {
/**
* Retrieves argument value as object
- *
+ *
* @param n key
* @param def default value to be returned if key is not present
* @return argument value as object
@@ -129,7 +127,7 @@ public interface IArgBlock extends Serializable {
/**
* Gets boolean value. They should be "true" or "false".
- *
+ *
* @param name name of the input type
* @return boolean type: <code>true</code> or <code>false</code>
* @exception EBaseException failed to retrieve value
@@ -138,16 +136,16 @@ public interface IArgBlock extends Serializable {
/**
* Gets boolean value. They should be "true" or "false".
- *
+ *
* @param name name of the input type
- * @param def Default value to return.
+ * @param def Default value to return.
* @return boolean type: <code>true</code> or <code>false</code>
*/
public boolean getValueAsBoolean(String name, boolean def);
/**
* Gets KeyGenInfo
- *
+ *
* @param name name of the input type
* @param def default value to return
* @exception EBaseException On error.
@@ -156,9 +154,9 @@ public interface IArgBlock extends Serializable {
public KeyGenInfo getValueAsKeyGenInfo(String name, KeyGenInfo def) throws EBaseException;
/**
- * Gets PKCS10 request. This pkcs10 attribute does not
- * contain header information.
- *
+ * Gets PKCS10 request. This pkcs10 attribute does not contain header
+ * information.
+ *
* @param name name of the input type
* @return pkcs10 request
* @exception EBaseException failed to retrieve value
@@ -166,9 +164,9 @@ public interface IArgBlock extends Serializable {
public PKCS10 getValueAsRawPKCS10(String name) throws EBaseException;
/**
- * Gets PKCS10 request. This pkcs10 attribute does not
- * contain header information.
- *
+ * Gets PKCS10 request. This pkcs10 attribute does not contain header
+ * information.
+ *
* @param name name of the input type
* @param def default PKCS10
* @return pkcs10 request
@@ -178,8 +176,8 @@ public interface IArgBlock extends Serializable {
/**
* Retrieves PKCS10
- *
- * @param name name of the input type
+ *
+ * @param name name of the input type
* @param checkheader true if header must be present
* @return PKCS10 object
* @exception EBaseException failed to retrieve value
@@ -188,8 +186,8 @@ public interface IArgBlock extends Serializable {
/**
* Retrieves PKCS10
- *
- * @param name name of the input type
+ *
+ * @param name name of the input type
* @param checkheader true if header must be present
* @param def default PKCS10
* @return PKCS10 object
@@ -199,8 +197,8 @@ public interface IArgBlock extends Serializable {
/**
* Retrieves PKCS10
- *
- * @param name name of the input type
+ *
+ * @param name name of the input type
* @param def default PKCS10
* @return PKCS10 object
* @exception EBaseException on error
@@ -209,14 +207,14 @@ public interface IArgBlock extends Serializable {
/**
* Retrieves a list of argument keys.
- *
+ *
* @return a list of string-based keys
*/
public Enumeration<String> elements();
/**
* Adds long-type arguments to this block.
- *
+ *
* @param n key
* @param v value
* @return value
@@ -225,7 +223,7 @@ public interface IArgBlock extends Serializable {
/**
* Adds integer-type arguments to this block.
- *
+ *
* @param n key
* @param v value
* @return value
@@ -234,7 +232,7 @@ public interface IArgBlock extends Serializable {
/**
* Adds boolean-type arguments to this block.
- *
+ *
* @param n key
* @param v value
* @return value
@@ -243,7 +241,7 @@ public interface IArgBlock extends Serializable {
/**
* Adds integer-type arguments to this block.
- *
+ *
* @param n key
* @param v value
* @param radix radix
@@ -253,7 +251,7 @@ public interface IArgBlock extends Serializable {
/**
* Sets argument into this block.
- *
+ *
* @param name key
* @param obj value
*/
@@ -261,7 +259,7 @@ public interface IArgBlock extends Serializable {
/**
* Retrieves argument.
- *
+ *
* @param name key
* @return object value
*/
@@ -269,14 +267,14 @@ public interface IArgBlock extends Serializable {
/**
* Deletes argument by the given key.
- *
+ *
* @param name key
*/
public void delete(String name);
/**
* Retrieves a list of argument keys.
- *
+ *
* @return a list of string-based keys
*/
public Enumeration<String> getElements();
diff --git a/pki/base/common/src/com/netscape/certsrv/base/IAttrSet.java b/pki/base/common/src/com/netscape/certsrv/base/IAttrSet.java
index 28e36da6..c37cc01e 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/IAttrSet.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/IAttrSet.java
@@ -17,38 +17,34 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.base;
-
import java.io.Serializable;
import java.util.Enumeration;
-
/**
- * This interface defines the abstraction for the generic collection
- * of attributes indexed by string names.
- * Set of cooperating implementations of this interface may exploit
- * dot-separated attribute names to provide seamless access to the
- * attributes of attribute value which also implements AttrSet
- * interface as if it was direct attribute of the container
- * E.g., ((AttrSet)container.get("x")).get("y") is equivalent to
- * container.get("x.y");
+ * This interface defines the abstraction for the generic collection of
+ * attributes indexed by string names. Set of cooperating implementations of
+ * this interface may exploit dot-separated attribute names to provide seamless
+ * access to the attributes of attribute value which also implements AttrSet
+ * interface as if it was direct attribute of the container E.g.,
+ * ((AttrSet)container.get("x")).get("y") is equivalent to container.get("x.y");
* <p>
- *
+ *
* @version $Revision$, $Date$
**/
public interface IAttrSet extends Serializable {
/**
* Sets an attribute value within this AttrSet.
- *
+ *
* @param name the name of the attribute
* @param obj the attribute object.
* @exception EBaseException on attribute handling errors.
*/
- public void set(String name, Object obj)throws EBaseException;
+ public void set(String name, Object obj) throws EBaseException;
/**
* Gets an attribute value.
- *
+ *
* @param name the name of the attribute to return.
* @exception EBaseException on attribute handling errors.
*/
@@ -56,7 +52,7 @@ public interface IAttrSet extends Serializable {
/**
* Deletes an attribute value from this AttrSet.
- *
+ *
* @param name the name of the attribute to delete.
* @exception EBaseException on attribute handling errors.
*/
@@ -65,7 +61,7 @@ public interface IAttrSet extends Serializable {
/**
* Returns an enumeration of the names of the attributes existing within
* this AttrSet.
- *
+ *
* @return an enumeration of the attribute names.
*/
public Enumeration<?> getElements();
diff --git a/pki/base/common/src/com/netscape/certsrv/base/IAuthInfo.java b/pki/base/common/src/com/netscape/certsrv/base/IAuthInfo.java
index 91f9f51a..ed55d47e 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/IAuthInfo.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/IAuthInfo.java
@@ -17,15 +17,11 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.base;
-
-
-
/**
- * An interface represents an authentication context. This
- * is an entity that encapsulates the authentication
- * information of a service requestor. For example, CMS
- * user needs to authenticate to CMS using SSL. The
- * client certificate is expressed in authenticated context.
+ * An interface represents an authentication context. This is an entity that
+ * encapsulates the authentication information of a service requestor. For
+ * example, CMS user needs to authenticate to CMS using SSL. The client
+ * certificate is expressed in authenticated context.
* <P>
*
* @version $Revision$, $Date$
diff --git a/pki/base/common/src/com/netscape/certsrv/base/ICRLPrettyPrint.java b/pki/base/common/src/com/netscape/certsrv/base/ICRLPrettyPrint.java
index c770121f..eb11dfc8 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/ICRLPrettyPrint.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/ICRLPrettyPrint.java
@@ -17,21 +17,19 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.base;
-
import java.util.Locale;
-
/**
- * This interface represents a CRL pretty print handler.
- * It converts a CRL object into a printable CRL string.
- *
+ * This interface represents a CRL pretty print handler. It converts a CRL
+ * object into a printable CRL string.
+ *
* @version $Revision$, $Date$
*/
public interface ICRLPrettyPrint {
/**
* Retrieves the printable CRL string.
- *
+ *
* @param clientLocale end user clocale
* @param crlSize CRL size
* @param pageStart starting page number
@@ -42,7 +40,7 @@ public interface ICRLPrettyPrint {
/**
* Retrieves the printable CRL string.
- *
+ *
* @param clientLocale end user clocale
* @return printable CRL string
*/
diff --git a/pki/base/common/src/com/netscape/certsrv/base/ICertPrettyPrint.java b/pki/base/common/src/com/netscape/certsrv/base/ICertPrettyPrint.java
index fc4e8c29..fbef80f4 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/ICertPrettyPrint.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/ICertPrettyPrint.java
@@ -17,22 +17,19 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.base;
-
import java.util.Locale;
-
/**
- * This interface represents a certificate pretty print
- * handler. This handler converts certificate object into
- * a printable certificate string.
+ * This interface represents a certificate pretty print handler. This handler
+ * converts certificate object into a printable certificate string.
*
- * @version $Revision$, $Date$
+ * @version $Revision$, $Date$
*/
public interface ICertPrettyPrint {
/**
* Returns printable certificate string.
- *
+ *
* @param clientLocale end user locale
* @return printable certificate string
*/
diff --git a/pki/base/common/src/com/netscape/certsrv/base/IConfigStore.java b/pki/base/common/src/com/netscape/certsrv/base/IConfigStore.java
index aef83b1c..207ff83a 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/IConfigStore.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/IConfigStore.java
@@ -17,16 +17,16 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.base;
-
import java.math.BigInteger;
import java.util.Enumeration;
-
/**
- * An interface represents a configuration store.
- * A configuration store is an abstraction of a hierarchical store
- * to keep arbitrary data indexed by string names.<p>
- * In the following example:
+ * An interface represents a configuration store. A configuration store is an
+ * abstraction of a hierarchical store to keep arbitrary data indexed by string
+ * names.
+ * <p>
+ * In the following example:
+ *
* <pre>
* param1=value1
* configStore1.param11=value11
@@ -35,26 +35,28 @@ import java.util.Enumeration;
* configStore1.subStore1.param112=value112
* configStore2.param21=value21
* </pre>
- * The top config store has parameters <i>param1</i> and sub-stores
+ *
+ * The top config store has parameters <i>param1</i> and sub-stores
* <i>configStore1</i> and <i>configStore2</i>. <br>
* The following illustrates how a config store is used.
+ *
* <pre>
- * // the top config store is passed to the following method.
- * public void init(IConfigStore config) throws EBaseException {
- * IConfigStore store = config;
- * String valx = config.getString("param1");
- * // valx is "value1" <p>
- *
- * IConfigStore substore1 = config.getSubstore("configStore1");
- * String valy = substore1.getString("param11");
- * // valy is "value11" <p>
- *
- * IConfigStore substore2 = config.getSubstore("configStore2");
- * String valz = substore2.getString("param21");
- * // valz is "value21" <p>
- * }
+ * // the top config store is passed to the following method.
+ * public void init(IConfigStore config) throws EBaseException {
+ * IConfigStore store = config;
+ * String valx = config.getString(&quot;param1&quot;);
+ * // valx is &quot;value1&quot; &lt;p&gt;
+ *
+ * IConfigStore substore1 = config.getSubstore(&quot;configStore1&quot;);
+ * String valy = substore1.getString(&quot;param11&quot;);
+ * // valy is &quot;value11&quot; &lt;p&gt;
+ *
+ * IConfigStore substore2 = config.getSubstore(&quot;configStore2&quot;);
+ * String valz = substore2.getString(&quot;param21&quot;);
+ * // valz is &quot;value21&quot; &lt;p&gt;
+ * }
* </pre>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IConfigStore extends ISourceConfigStore {
@@ -62,6 +64,7 @@ public interface IConfigStore extends ISourceConfigStore {
/**
* Gets the name of this Configuration Store.
* <P>
+ *
* @return The name of this Configuration store
*/
public String getName();
@@ -69,60 +72,66 @@ public interface IConfigStore extends ISourceConfigStore {
/**
* Retrieves the value of the given property as a string.
* <p>
+ *
* @param name The name of the property to get
* @return The value of the property as a String
* @exception EPropertyNotFound If the property is not present
* @exception EBaseException If an internal error occurred
*/
- public String getString(String name)
- throws EPropertyNotFound, EBaseException;
+ public String getString(String name)
+ throws EPropertyNotFound, EBaseException;
/**
- * Retrieves the value of a given property as a string or the
- * given default value if the property is not present.
+ * Retrieves the value of a given property as a string or the given default
+ * value if the property is not present.
* <P>
+ *
* @param name The property to retrive
* @param defval The default value to return if the property is not present
* @return The roperty value as a string
* @exception EBaseException If an internal error occurred
*/
- public String getString(String name, String defval)
- throws EBaseException;
+ public String getString(String name, String defval)
+ throws EBaseException;
/**
- * Stores a property and its value as a string.
+ * Stores a property and its value as a string.
* <p>
+ *
* @param name The name of the property
* @param value The value as a string
- */
+ */
public void putString(String name, String value);
/**
* Retrieves the value of a property as a byte array.
* <P>
+ *
* @param name The property name
* @return The property value as a byte array
* @exception EPropertyNotFound If the property is not present
* @exception EBaseException If an internal error occurred
*/
- public byte[] getByteArray(String name)
- throws EPropertyNotFound, EBaseException;
+ public byte[] getByteArray(String name)
+ throws EPropertyNotFound, EBaseException;
/**
- * Retrieves the value of a property as a byte array, using the
- * given default value if property is not present.
+ * Retrieves the value of a property as a byte array, using the given
+ * default value if property is not present.
* <P>
+ *
* @param name The name of the property
* @param defval The default value if the property is not present.
* @return The property value as a byte array.
* @exception EBaseException If an internal error occurred
*/
- public byte[] getByteArray(String name, byte defval[])
- throws EBaseException;
+ public byte[] getByteArray(String name, byte defval[])
+ throws EBaseException;
/**
* Stores the given property and value as a byte array.
* <p>
+ *
* @param name The property name
* @param value The value as a byte array to store
*/
@@ -131,29 +140,32 @@ public interface IConfigStore extends ISourceConfigStore {
/**
* Retrieves the given property as a boolean.
* <P>
+ *
* @param name The name of the property as a string.
* @return The value of the property as a boolean.
* @exception EPropertyNotFound If the property is not present
* @exception EBaseException If an internal error occurred
*/
- public boolean getBoolean(String name)
- throws EPropertyNotFound, EBaseException;
+ public boolean getBoolean(String name)
+ throws EPropertyNotFound, EBaseException;
/**
* Retrieves the given property as a boolean.
* <P>
+ *
* @param name The name of the property
- * @param defval The default value to turn as a boolean if
- * property is not present
+ * @param defval The default value to turn as a boolean if property is not
+ * present
* @return The value of the property as a boolean.
* @exception EBaseException If an internal error occurred
*/
- public boolean getBoolean(String name, boolean defval)
- throws EBaseException;
+ public boolean getBoolean(String name, boolean defval)
+ throws EBaseException;
/**
* Stores the given property and its value as a boolean.
* <P>
+ *
* @param name The property name
* @param value The value as a boolean
*/
@@ -162,28 +174,30 @@ public interface IConfigStore extends ISourceConfigStore {
/**
* Retrieves the given property as an integer.
* <P>
+ *
* @param name The property name
* @return The property value as an integer
* @exception EPropertyNotFound If property is not found
* @exception EBaseException If an internal error occurred
*/
- public int getInteger(String name)
- throws EPropertyNotFound, EBaseException;
+ public int getInteger(String name)
+ throws EPropertyNotFound, EBaseException;
/**
* Retrieves the given property as an integer.
* <P>
+ *
* @param name The property name
* @return int The default value to return as an integer
- * @exception EBaseException If the value cannot be converted to a
- * integer
+ * @exception EBaseException If the value cannot be converted to a integer
*/
- public int getInteger(String name, int defval)
- throws EBaseException;
+ public int getInteger(String name, int defval)
+ throws EBaseException;
/**
* Sets a property and its value as an integer.
* <P>
+ *
* @param name parameter name
* @param value integer value
*/
@@ -192,28 +206,30 @@ public interface IConfigStore extends ISourceConfigStore {
/**
* Retrieves the given property as a big integer.
* <P>
+ *
* @param name The property name
* @return The property value as a big integer
* @exception EPropertyNotFound If property is not found
* @exception EBaseException If an internal error occurred
*/
- public BigInteger getBigInteger(String name)
- throws EPropertyNotFound, EBaseException;
+ public BigInteger getBigInteger(String name)
+ throws EPropertyNotFound, EBaseException;
/**
* Retrieves the given property as a big integer.
* <P>
+ *
* @param name The property name
* @return int The default value to return as a big integer
- * @exception EBaseException If the value cannot be converted to a
- * integer
+ * @exception EBaseException If the value cannot be converted to a integer
*/
- public BigInteger getBigInteger(String name, BigInteger defval)
- throws EBaseException;
+ public BigInteger getBigInteger(String name, BigInteger defval)
+ throws EBaseException;
/**
* Sets a property and its value as an integer.
* <P>
+ *
* @param name parameter name
* @param value big integer value
*/
@@ -222,23 +238,26 @@ public interface IConfigStore extends ISourceConfigStore {
/**
* Creates a nested sub-store with the specified name.
* <P>
+ *
* @param name The name of the sub-store
* @return The sub-store created
*/
public IConfigStore makeSubStore(String name);
/**
- * Retrieves the given sub-store.
+ * Retrieves the given sub-store.
* <P>
+ *
* @param name The name of the sub-store
* @return The sub-store
*/
public IConfigStore getSubStore(String name);
/**
- * Removes sub-store with the given name.
- * (Removes all properties and sub-stores under this sub-store.)
+ * Removes sub-store with the given name. (Removes all properties and
+ * sub-stores under this sub-store.)
* <P>
+ *
* @param name The name of the sub-store to remove
*/
public void removeSubStore(String name);
@@ -247,22 +266,24 @@ public interface IConfigStore extends ISourceConfigStore {
/**
* Retrives and enumeration of all properties in this config-store.
+ *
* @return An enumeration of all properties in this config-store
*/
public Enumeration<String> getPropertyNames();
/**
- * Returns an enumeration of the names of the substores of
- * this config-store.
+ * Returns an enumeration of the names of the substores of this
+ * config-store.
* <P>
- * @return An enumeration of the names of the sub-stores of this
- * config-store
+ *
+ * @return An enumeration of the names of the sub-stores of this
+ * config-store
*/
public Enumeration<String> getSubStoreNames();
/**
* Commits all the data into file immediately.
- *
+ *
* @param createBackup true if a backup file should be created
* @exception EBaseException failed to commit
*/
@@ -273,4 +294,3 @@ public interface IConfigStore extends ISourceConfigStore {
*/
public int size();
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/base/IConfigStoreEventListener.java b/pki/base/common/src/com/netscape/certsrv/base/IConfigStoreEventListener.java
index f2b6a03d..376b4e91 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/IConfigStoreEventListener.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/IConfigStoreEventListener.java
@@ -17,34 +17,32 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.base;
-
import java.util.Hashtable;
-
/**
* ConfigStore Parameters Event Notification.
- *
+ *
* @version $Revision$, $Date$
*/
public interface IConfigStoreEventListener {
/**
* Called to validate the config store parameters that changed
- *
+ *
* @param action action
* @param params configuration parameters changed
* @exception EBaseException failed to validate
*/
- public void validateConfigParams(String action,
- Hashtable params) throws EBaseException;
+ public void validateConfigParams(String action,
+ Hashtable params) throws EBaseException;
/**
* Validates the config store parameters that changed
- *
+ *
* @param action action
* @param params configuration parameters changed
* @exception EBaseException failed to validate
*/
- public void doConfigParams(String action,
- Hashtable params) throws EBaseException;
+ public void doConfigParams(String action,
+ Hashtable params) throws EBaseException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/base/IExtPrettyPrint.java b/pki/base/common/src/com/netscape/certsrv/base/IExtPrettyPrint.java
index 73e95b77..101af3fa 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/IExtPrettyPrint.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/IExtPrettyPrint.java
@@ -17,22 +17,17 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.base;
-
-
-
/**
- * This class will display the certificate content in predefined
- * format.
- *
+ * This class will display the certificate content in predefined format.
+ *
* @version $Revision$, $Date$
*/
public interface IExtPrettyPrint {
/**
* Retrieves the printable extension string.
- *
+ *
* @return printable extension string
*/
public String toString();
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/base/IExtendedPluginInfo.java b/pki/base/common/src/com/netscape/certsrv/base/IExtendedPluginInfo.java
index e8060b24..e0f87c4e 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/IExtendedPluginInfo.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/IExtendedPluginInfo.java
@@ -17,14 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.base;
-
import java.util.Locale;
-
/**
* Plugin which can return extended information to console
* <p>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IExtendedPluginInfo {
@@ -33,48 +31,43 @@ public interface IExtendedPluginInfo {
public static final String HELP_TEXT = "HELP_TEXT";
/**
- * This method returns an array of strings. Each element of the
- * array represents a configurable parameter, or some other
- * meta-info (such as help-token)
+ * This method returns an array of strings. Each element of the array
+ * represents a configurable parameter, or some other meta-info (such as
+ * help-token)
+ *
+ * there is an entry indexed on that parameter name
+ * <param-name>;<type_info>[,required];<description>;...
+ *
+ * Where:
+ *
+ * type_info is either 'string', 'number', 'boolean', 'password' or
+ * 'choice(ch1,ch2,ch3,...)'
+ *
+ * If the marker 'required' is included after the type_info, the parameter
+ * will has some visually distinctive marking in the UI.
+ *
+ * 'description' is a short sentence describing the parameter 'choice' is
+ * rendered as a drop-down list. The first parameter in the list will be
+ * activated by default 'boolean' is rendered as a checkbox. The resulting
+ * parameter will be either 'true' or 'false' 'string' allows any characters
+ * 'number' allows only numbers 'password' is rendered as a password field
+ * (the characters are replaced with *'s when being types. This parameter is
+ * not passed through to the plugin. It is instead inserted directly into
+ * the password cache keyed on the instance name. The value of the parameter
+ * 'bindPWPrompt' (see example below) is set to the key.
+ *
+ * In addition to the configurable parameters, the following magic
+ * parameters may be defined:
+ *
+ * HELP_TOKEN;helptoken - a pointer to the online manual section for this
+ * plugin HELP_TEXT;helptext - a general help string describing the plugin
*
- * there is an entry indexed on that parameter name
- * <param-name>;<type_info>[,required];<description>;...
- *
- * Where:
- *
- * type_info is either 'string', 'number', 'boolean', 'password' or
- * 'choice(ch1,ch2,ch3,...)'
- *
- * If the marker 'required' is included after the type_info,
- * the parameter will has some visually distinctive marking in
- * the UI.
+ * For example: "username;string;The username you wish to login as"
+ * "bindPWPrompt;password;Enter password to bind as above user with"
+ * "algorithm;choice(RSA,DSA);Which algorithm do you want to use"
+ * "enable;boolean;Do you want to run this plugin"
+ * "port;number;Which port number do you want to use"
*
- * 'description' is a short sentence describing the parameter
- * 'choice' is rendered as a drop-down list. The first parameter in the
- * list will be activated by default
- * 'boolean' is rendered as a checkbox. The resulting parameter will be
- * either 'true' or 'false'
- * 'string' allows any characters
- * 'number' allows only numbers
- * 'password' is rendered as a password field (the characters are replaced
- * with *'s when being types. This parameter is not passed through to
- * the plugin. It is instead inserted directly into the password cache
- * keyed on the instance name. The value of the parameter
- * 'bindPWPrompt' (see example below) is set to the key.
- *
- * In addition to the configurable parameters, the following magic parameters
- * may be defined:
- *
- * HELP_TOKEN;helptoken - a pointer to the online manual section for this plugin
- * HELP_TEXT;helptext - a general help string describing the plugin
- *
- * For example:
- * "username;string;The username you wish to login as"
- * "bindPWPrompt;password;Enter password to bind as above user with"
- * "algorithm;choice(RSA,DSA);Which algorithm do you want to use"
- * "enable;boolean;Do you want to run this plugin"
- * "port;number;Which port number do you want to use"
- *
*/
public String[] getExtendedPluginInfo(Locale locale);
diff --git a/pki/base/common/src/com/netscape/certsrv/base/IPluginImpl.java b/pki/base/common/src/com/netscape/certsrv/base/IPluginImpl.java
index 4a55af60..3ce494d9 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/IPluginImpl.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/IPluginImpl.java
@@ -17,12 +17,11 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.base;
-
import java.util.Vector;
/**
* This interface represents a plugin instance.
- *
+ *
* @version $Revision$, $Date$
*/
public interface IPluginImpl {
@@ -32,6 +31,7 @@ public interface IPluginImpl {
/**
* Gets the description for this plugin instance.
* <P>
+ *
* @return The Description for this plugin instance.
*/
public String getDescription();
@@ -39,7 +39,7 @@ public interface IPluginImpl {
/**
* Returns the name of the plugin class.
* <P>
- *
+ *
* @return The name of the plugin class.
*/
public String getImplName();
@@ -47,24 +47,24 @@ public interface IPluginImpl {
/**
* Returns the name of the plugin instance.
* <P>
- *
- * @return The name of the plugin instance. If none is set
- * the name of the implementation will be returned.xxxx
+ *
+ * @return The name of the plugin instance. If none is set the name of the
+ * implementation will be returned.xxxx
*/
public String getInstanceName();
/**
* Initializes this plugin instance.
- *
+ *
* @param sys parent subsystem
* @param instanceName instance name of this plugin
* @param className class name of this plugin
* @param config configuration store
* @exception EBaseException failed to initialize
*/
- public void init(ISubsystem sys, String instanceName, String className,
- IConfigStore config)
- throws EBaseException;
+ public void init(ISubsystem sys, String instanceName, String className,
+ IConfigStore config)
+ throws EBaseException;
/**
* Shutdowns this plugin.
@@ -73,33 +73,32 @@ public interface IPluginImpl {
/**
* Retrieves the configuration store.
- *
+ *
* @return configuration store
*/
public IConfigStore getConfigStore();
/**
* Return configured parameters for a plugin instance.
- *
- * @return nvPairs A Vector of name/value pairs. Each name/value
- * pair is constructed as a String in name=value format.
+ *
+ * @return nvPairs A Vector of name/value pairs. Each name/value pair is
+ * constructed as a String in name=value format.
*/
public Vector getInstanceParams();
/**
* Retrieves a list of configuration parameter names.
- *
+ *
* @return a list of parameter names
*/
public String[] getConfigParams();
/**
* Return default parameters for a plugin implementation.
- *
- * @return nvPairs A Vector of name/value pairs. Each name/value
- * pair is constructed as a String in name=value.
+ *
+ * @return nvPairs A Vector of name/value pairs. Each name/value pair is
+ * constructed as a String in name=value.
*/
public Vector getDefaultParams();
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/base/IPrettyPrintFormat.java b/pki/base/common/src/com/netscape/certsrv/base/IPrettyPrintFormat.java
index 1fba48f1..de03ec24 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/IPrettyPrintFormat.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/IPrettyPrintFormat.java
@@ -17,32 +17,28 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.base;
-
-
-
/**
- * This class will display the certificate content in predefined
- * format.
- *
+ * This class will display the certificate content in predefined format.
+ *
* @version $Revision$, $Date$
*/
public interface IPrettyPrintFormat {
/**
* Retrieves a pretty print string of the given byte array.
- *
+ *
* @param in byte array
* @param indentSize indentation size
* @param lineLen length of line
* @param separator separator string
* @return pretty print string
*/
- public String toHexString(byte[] in, int indentSize,
- int lineLen, String separator);
+ public String toHexString(byte[] in, int indentSize,
+ int lineLen, String separator);
/**
* Retrieves a pretty print string of the given byte array.
- *
+ *
* @param in byte array
* @param indentSize indentation size
* @param lineLen length of line
@@ -52,7 +48,7 @@ public interface IPrettyPrintFormat {
/**
* Retrieves a pretty print string of the given byte array.
- *
+ *
* @param in byte array
* @param indentSize indentation size
* @return pretty print string
@@ -61,7 +57,7 @@ public interface IPrettyPrintFormat {
/**
* Retrieves a pretty print string of the given byte array.
- *
+ *
* @param in byte array
* @return pretty print string
*/
diff --git a/pki/base/common/src/com/netscape/certsrv/base/ISecurityDomainSessionTable.java b/pki/base/common/src/com/netscape/certsrv/base/ISecurityDomainSessionTable.java
index ced3886c..24c55d08 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/ISecurityDomainSessionTable.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/ISecurityDomainSessionTable.java
@@ -19,21 +19,30 @@ package com.netscape.certsrv.base;
import java.util.Enumeration;
-
/**
* This interface defines the abstraction for the cookie table.
**/
public interface ISecurityDomainSessionTable {
- public static final int SUCCESS =0;
- public static final int FAILURE =1;
+ public static final int SUCCESS = 0;
+ public static final int FAILURE = 1;
+
public int addEntry(String cookieId, String ip, String uid, String group);
+
public int removeEntry(String sessionId);
+
public boolean isSessionIdExist(String sessionId);
+
public String getIP(String sessionId);
+
public String getUID(String sessionId);
+
public String getGroup(String sessionId);
+
public long getBeginTime(String sessionId);
+
public int getSize();
+
public long getTimeToLive();
+
public Enumeration<String> getSessionIds();
}
diff --git a/pki/base/common/src/com/netscape/certsrv/base/ISourceConfigStore.java b/pki/base/common/src/com/netscape/certsrv/base/ISourceConfigStore.java
index 03adb700..87a7ea40 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/ISourceConfigStore.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/ISourceConfigStore.java
@@ -17,20 +17,19 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.base;
-
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.Enumeration;
-
/**
- * An interface that represents the source that creates the configuration
- * store tree. Note that the tree can be built based on the information
- * from a text file or ldap entries.
+ * An interface that represents the source that creates the configuration store
+ * tree. Note that the tree can be built based on the information from a text
+ * file or ldap entries.
+ *
* @see com.netscape.certsrv.base.IConfigStore
- *
+ *
* @version $Revision$, $Date$
*/
public interface ISourceConfigStore extends Serializable {
@@ -38,7 +37,7 @@ public interface ISourceConfigStore extends Serializable {
/**
* Gets a property.
* <P>
- *
+ *
* @param name The property name
* @return property value
*/
@@ -47,7 +46,7 @@ public interface ISourceConfigStore extends Serializable {
/**
* Retrieves a property.
* <P>
- *
+ *
* @param name The property name
* @param value The property value
*/
@@ -56,7 +55,7 @@ public interface ISourceConfigStore extends Serializable {
/**
* Returns an enumeration of the config store's keys.
* <P>
- *
+ *
* @return a list of keys
* @see java.util.Hashtable#elements
* @see java.util.Enumeration
@@ -64,16 +63,16 @@ public interface ISourceConfigStore extends Serializable {
public Enumeration<String> keys();
/**
- * Reads a config store from an input stream.
- *
+ * Reads a config store from an input stream.
+ *
* @param in input stream where the properties are located
* @exception IOException If an IO error occurs while loading from input.
*/
public void load(InputStream in) throws IOException;
/**
- * Stores this config store to the specified output stream.
- *
+ * Stores this config store to the specified output stream.
+ *
* @param out output stream where the properties should be serialized
* @param header optional header to be serialized
*/
diff --git a/pki/base/common/src/com/netscape/certsrv/base/ISubsystem.java b/pki/base/common/src/com/netscape/certsrv/base/ISubsystem.java
index 77f1708a..994c8f75 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/ISubsystem.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/ISubsystem.java
@@ -17,13 +17,9 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.base;
-
-
-
/**
- * An interface represents a CMS subsystem. CMS is made up of a list
- * subsystems. Each subsystem is responsible for a set of
- * speciailized functions.
+ * An interface represents a CMS subsystem. CMS is made up of a list subsystems.
+ * Each subsystem is responsible for a set of speciailized functions.
* <P>
*
* @version $Revision$, $Date$
@@ -32,41 +28,40 @@ public interface ISubsystem {
/**
* Retrieves the name of this subsystem.
- *
+ *
* @return subsystem identifier
*/
public String getId();
/**
* Sets specific to this subsystem.
- *
+ *
* @param id subsystem identifier
* @exception EBaseException failed to set id
*/
public void setId(String id) throws EBaseException;
/**
- * Initializes this subsystem with the given configuration
- * store.
+ * Initializes this subsystem with the given configuration store.
* <P>
- *
+ *
* @param owner owner of this subsystem
* @param config configuration store
* @exception EBaseException failed to initialize
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException;
+ throws EBaseException;
/**
* Notifies this subsystem if owner is in running mode.
- *
+ *
* @exception EBaseException failed to start up
*/
public void startup() throws EBaseException;
/**
- * Stops this system. The owner may call shutdown
- * anytime after initialization.
+ * Stops this system. The owner may call shutdown anytime after
+ * initialization.
* <P>
*/
public void shutdown();
@@ -74,7 +69,7 @@ public interface ISubsystem {
/**
* Returns the root configuration storage of this system.
* <P>
- *
+ *
* @return configuration store of this subsystem
*/
public IConfigStore getConfigStore();
diff --git a/pki/base/common/src/com/netscape/certsrv/base/ISubsystemSource.java b/pki/base/common/src/com/netscape/certsrv/base/ISubsystemSource.java
index 23b82179..7c491d51 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/ISubsystemSource.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/ISubsystemSource.java
@@ -17,12 +17,9 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.base;
-
-
-
/**
- * An interface represents a subsystem source. A subsystem
- * source is a container that manages multiple subsystems.
+ * An interface represents a subsystem source. A subsystem source is a container
+ * that manages multiple subsystems.
* <P>
*
* @version $Revision$, $Date$
@@ -31,7 +28,7 @@ public interface ISubsystemSource {
/**
* Retrieves subsystem from the source.
- *
+ *
* @param sid subsystem identifier
* @return subsystem
*/
diff --git a/pki/base/common/src/com/netscape/certsrv/base/ITimeSource.java b/pki/base/common/src/com/netscape/certsrv/base/ITimeSource.java
index f1e3e25e..6805a5f9 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/ITimeSource.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/ITimeSource.java
@@ -17,17 +17,13 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.base;
-
import java.util.Date;
-
/**
- * This interface represents a time source where
- * current time can be retrieved. CMS is installed
- * with a default time source that returns
- * current time based on the system time. It is
- * possible to register a time source that returns
- * the current time from a NTP server.
+ * This interface represents a time source where current time can be retrieved.
+ * CMS is installed with a default time source that returns current time based
+ * on the system time. It is possible to register a time source that returns the
+ * current time from a NTP server.
*
* @version $Revision$, $Date$
*/
@@ -35,7 +31,7 @@ public interface ITimeSource {
/**
* Retrieves current time and date.
- *
+ *
* @return current time and date
*/
public Date getCurrentDate();
diff --git a/pki/base/common/src/com/netscape/certsrv/base/KeyGenInfo.java b/pki/base/common/src/com/netscape/certsrv/base/KeyGenInfo.java
index 17efca77..5fc4ea20 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/KeyGenInfo.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/KeyGenInfo.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.base;
-
import java.io.IOException;
import netscape.security.util.DerInputStream;
@@ -25,35 +24,36 @@ import netscape.security.util.DerValue;
import netscape.security.x509.AlgorithmId;
import netscape.security.x509.X509Key;
-
/**
- *
- * The <code>KeyGenInfo</code> represents the information generated by
- * the KeyGen tag of the HTML forms. It provides the parsing and accessing
- * mechanisms.<p>
- *
+ *
+ * The <code>KeyGenInfo</code> represents the information generated by the
+ * KeyGen tag of the HTML forms. It provides the parsing and accessing
+ * mechanisms.
+ * <p>
+ *
* <pre>
* SignedPublicKeyAndChallenge ::= SEQUENCE {
* publicKeyAndChallenge PublicKeyAndChallenge,
* signatureAlgorithm AlgorithmIdentifier,
* signature BIT STRING
* }
- *
+ *
* PublicKeyAndChallenge ::= SEQUENCE {
* spki SubjectPublicKeyInfo,
* challenge IA5STRING
* }
- *</pre>
- *
- *
+ * </pre>
+ *
+ *
* @version $Revision$, $Date$
*/
public class KeyGenInfo {
- /*==========================================================
- * variables
- *==========================================================*/
+ /*
+ * ========================================================== variables
+ * ==========================================================
+ */
private String mSPKACString;
private byte mPKAC[];
private byte mSPKAC[];
@@ -64,36 +64,38 @@ public class KeyGenInfo {
private byte mSignature[];
private AlgorithmId mAlgId;
- /*==========================================================
- * constructors
- *==========================================================*/
+ /*
+ * ========================================================== constructors
+ * ==========================================================
+ */
/**
- * Construct empty KeyGenInfo. Need to call decode function
- * later to initialize.
+ * Construct empty KeyGenInfo. Need to call decode function later to
+ * initialize.
*/
public KeyGenInfo() {
}
/**
- * Construct KeyGenInfo using the SignedPublicKeyAndChallenge
- * string representation.
- *
+ * Construct KeyGenInfo using the SignedPublicKeyAndChallenge string
+ * representation.
+ *
* @param spkac SignedPublicKeyAndChallenge string representation
*/
public KeyGenInfo(String spkac)
- throws IOException {
+ throws IOException {
decode(spkac);
}
- /*==========================================================
- * public methods
- *==========================================================*/
+ /*
+ * ========================================================== public methods
+ * ==========================================================
+ */
/**
* Initialize using the SPKAC string
- *
+ *
* @param spkac SPKAC string from the end user
*/
public void decode(String spkac) throws IOException {
@@ -104,7 +106,7 @@ public class KeyGenInfo {
/**
* Der encoded into buffer
- *
+ *
* @return Der encoded buffer
*/
public byte[] encode() {
@@ -113,7 +115,7 @@ public class KeyGenInfo {
/**
* Get SPKI in DerValue form
- *
+ *
* @return SPKI in DerValue form
*/
public DerValue getDerSPKI() {
@@ -122,7 +124,7 @@ public class KeyGenInfo {
/**
* Get SPKI as X509Key
- *
+ *
* @return SPKI in X509Key form
*/
public X509Key getSPKI() {
@@ -131,7 +133,7 @@ public class KeyGenInfo {
/**
* Get Challenge phrase in DerValue form
- *
+ *
* @return Challenge in DerValue form. null if none.
*/
public DerValue getDerChallenge() {
@@ -140,7 +142,7 @@ public class KeyGenInfo {
/**
* Get Challenge phrase in string format
- *
+ *
* @return challenge phrase. null if none.
*/
public String getChallenge() {
@@ -149,6 +151,7 @@ public class KeyGenInfo {
/**
* Get Signature
+ *
* @return signature
*/
public byte[] getSignature() {
@@ -157,6 +160,7 @@ public class KeyGenInfo {
/**
* Get Algorithm ID
+ *
* @return the algorithm id
*/
public AlgorithmId getAlgorithmId() {
@@ -165,7 +169,7 @@ public class KeyGenInfo {
/**
* Validate Signature and Challenge Phrase
- *
+ *
* @param challenge phrase; null if none
* @return true if validated; otherwise, false
*/
@@ -180,7 +184,7 @@ public class KeyGenInfo {
/**
* String representation of KenGenInfo
- *
+ *
* @return string representation of KeGenInfo
*/
public String toString() {
@@ -189,18 +193,19 @@ public class KeyGenInfo {
return "";
}
- /*==========================================================
- * private methods
- *==========================================================*/
+ /*
+ * ========================================================== private
+ * methods==========================================================
+ */
private byte[] base64Decode(String spkac)
- throws IOException {
+ throws IOException {
return com.netscape.osutil.OSUtil.AtoB(spkac);
}
private void derDecode(byte spkac[])
- throws IOException {
+ throws IOException {
DerInputStream derIn = new DerInputStream(spkac);
/* get SPKAC Algorithm & Signature */
@@ -224,4 +229,3 @@ public class KeyGenInfo {
}
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/base/MessageFormatter.java b/pki/base/common/src/com/netscape/certsrv/base/MessageFormatter.java
index 8e186fc4..3445e236 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/MessageFormatter.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/MessageFormatter.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.base;
-
import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.util.Date;
@@ -25,13 +24,12 @@ import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
-
/**
- * Factors out common function of formatting internatinalized
- * messages taking arguments and using java.util.ResourceBundle
- * and java.text.MessageFormat mechanism.
+ * Factors out common function of formatting internatinalized messages taking
+ * arguments and using java.util.ResourceBundle and java.text.MessageFormat
+ * mechanism.
* <P>
- *
+ *
* @version $Revision$, $Date$
* @see java.text.MessageFormat
* @see java.util.ResourceBundle
@@ -42,22 +40,22 @@ public class MessageFormatter {
/**
* Retrieves the localized string.
- *
+ *
* @param locale end user locale
* @param resourceBundleBaseName resource bundle class name
* @param formatString format string
* @return localized string
*/
public static String getLocalizedString(
- Locale locale, String resourceBundleBaseName,
- String formatString) {
- return getLocalizedString(locale, resourceBundleBaseName,
+ Locale locale, String resourceBundleBaseName,
+ String formatString) {
+ return getLocalizedString(locale, resourceBundleBaseName,
formatString, null);
}
/**
* Retrieves the localized string.
- *
+ *
* @param locale end user locale
* @param resourceBundleBaseName resource bundle class name
* @param formatString format string
@@ -65,18 +63,18 @@ public class MessageFormatter {
* @return localized string
*/
public static String getLocalizedString(
- Locale locale, String resourceBundleBaseName,
- String formatString, Object params) {
+ Locale locale, String resourceBundleBaseName,
+ String formatString, Object params) {
Object o[] = new Object[1];
o[0] = params;
- return getLocalizedString(locale, resourceBundleBaseName,
+ return getLocalizedString(locale, resourceBundleBaseName,
formatString, o);
}
/**
* Retrieves the localized string.
- *
+ *
* @param locale end user locale
* @param resourceBundleBaseName resource bundle class name
* @param formatString format string
@@ -84,8 +82,8 @@ public class MessageFormatter {
* @return localized string
*/
public static String getLocalizedString(
- Locale locale, String resourceBundleBaseName,
- String formatString, Object[] params) {
+ Locale locale, String resourceBundleBaseName,
+ String formatString, Object[] params) {
String localizedFormat = null;
@@ -100,7 +98,7 @@ public class MessageFormatter {
resourceBundleBaseName, locale).getString(formatString);
} catch (MissingResourceException e) {
return formatString;
-
+
}
Object[] localizedParams = params;
Object[] localeArg = null;
@@ -108,20 +106,21 @@ public class MessageFormatter {
if (params != null) {
for (int i = 0; i < params.length; ++i) {
if (!(params[i] instanceof String) ||
- !(params[i] instanceof Date) ||
- !(params[i] instanceof Number)) {
+ !(params[i] instanceof Date) ||
+ !(params[i] instanceof Number)) {
if (localizedParams == params) {
// only done once
- // NB if the following variant of cloning code is used
- // localizedParams = (Object [])mParams.clone();
+ // NB if the following variant of cloning code is
+ // used
+ // localizedParams = (Object [])mParams.clone();
// it causes ArrayStoreException in
- // localizedParams[i] = params[i].toString();
+ // localizedParams[i] = params[i].toString();
// below
localizedParams = new Object[params.length];
System.arraycopy(params, 0, localizedParams, 0,
- params.length);
+ params.length);
}
try {
Method toStringMethod = params[i].getClass().getMethod(
@@ -141,7 +140,8 @@ public class MessageFormatter {
}
}
try {
- // XXX - runtime exception may be raised by the following function
+ // XXX - runtime exception may be raised by the following
+ // function
MessageFormat format = new MessageFormat(localizedFormat);
return format.format(localizedParams);
diff --git a/pki/base/common/src/com/netscape/certsrv/base/MetaAttributeDef.java b/pki/base/common/src/com/netscape/certsrv/base/MetaAttributeDef.java
index 93dd2502..f68959db 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/MetaAttributeDef.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/MetaAttributeDef.java
@@ -17,17 +17,15 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.base;
-
import java.util.Enumeration;
import java.util.Hashtable;
import netscape.security.util.ObjectIdentifier;
-
/**
* A class representing a meta attribute defintion.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class MetaAttributeDef {
@@ -40,66 +38,65 @@ public class MetaAttributeDef {
private MetaAttributeDef() {
}
-
+
/**
* Constructs a MetaAttribute defintion
* <P>
- *
+ *
* @param name attribute name
* @param valueClass attribute value class
* @param oid attribute object identifier
*/
private MetaAttributeDef(String name, Class<?> valueClass,
- ObjectIdentifier oid) {
+ ObjectIdentifier oid) {
mName = name;
mValueClass = valueClass;
mOid = oid;
}
-
+
/**
* Gets an attribute OID.
* <P>
- *
+ *
* @return returns attribute OID or null if not defined.
*/
- public ObjectIdentifier getOID() {
- return mOid;
+ public ObjectIdentifier getOID() {
+ return mOid;
}
/**
* Gets an Java class for the attribute values
* <P>
- *
+ *
* @return returns Java class for the attribute values
*/
public Class<?> getValueClass() {
- return mValueClass;
+ return mValueClass;
}
/**
* Gets attribute name
* <P>
- *
- * @return returns attribute name
+ *
+ * @return returns attribute name
*/
- public String getName() {
- return mName;
+ public String getName() {
+ return mName;
}
-
+
/**
- * Registers new MetaAttribute defintion
- * Attribute is defined by name, Java class for attribute values and
- * optional object identifier
+ * Registers new MetaAttribute defintion Attribute is defined by name, Java
+ * class for attribute values and optional object identifier
* <P>
- *
+ *
* @param name attribute name
* @param valueClass attribute value class
* @param oid attribute object identifier
* @exception IllegalArgumentException if name or valueClass are null, or
- * conflicting attribute definition already exists
+ * conflicting attribute definition already exists
*/
public static MetaAttributeDef register(String name, Class<?> valueClass,
- ObjectIdentifier oid) {
+ ObjectIdentifier oid) {
if (name == null) {
throw new IllegalArgumentException(
"Attribute name must not be null");
@@ -113,13 +110,13 @@ public class MetaAttributeDef {
MetaAttributeDef oldDef;
if ((oldDef = (MetaAttributeDef) mNameToAttrDef.get(name)) != null &&
- !oldDef.equals(newDef)) {
+ !oldDef.equals(newDef)) {
throw new IllegalArgumentException(
"Attribute \'" + name + "\' is already defined");
}
if (oid != null &&
- (oldDef = (MetaAttributeDef) mOidToAttrDef.get(oid)) != null &&
- !oldDef.equals(newDef)) {
+ (oldDef = (MetaAttributeDef) mOidToAttrDef.get(oid)) != null &&
+ !oldDef.equals(newDef)) {
throw new IllegalArgumentException(
"OID \'" + oid + "\' is already in use");
}
@@ -128,37 +125,37 @@ public class MetaAttributeDef {
mOidToAttrDef.put(oid, newDef);
}
return newDef;
- }
-
+ }
+
/**
* Compares this attribute definition with another, for equality.
* <P>
- *
- * @return true iff names, valueClasses and object identifiers
- * are identical.
+ *
+ * @return true iff names, valueClasses and object identifiers are
+ * identical.
*/
public boolean equals(Object other) {
if (other == this)
return true;
-
+
if (other instanceof MetaAttributeDef) {
MetaAttributeDef otherDef = (MetaAttributeDef) other;
- if ((mOid != null && otherDef.mOid != null &&
- !mOid.equals(otherDef.mOid)) ||
- (mOid == null && otherDef.mOid != null) ||
- !mName.equals(otherDef.mName) ||
- !mValueClass.equals(otherDef.mValueClass)) {
+ if ((mOid != null && otherDef.mOid != null &&
+ !mOid.equals(otherDef.mOid)) ||
+ (mOid == null && otherDef.mOid != null) ||
+ !mName.equals(otherDef.mName) ||
+ !mValueClass.equals(otherDef.mValueClass)) {
return false;
}
}
return false;
}
-
+
/**
* Retrieves attribute definition by name
* <P>
- *
+ *
* @param name attribute name
* @return attribute definition or null if not found
*/
@@ -169,7 +166,7 @@ public class MetaAttributeDef {
/**
* Retrieves attribute definition by object identifier
* <P>
- *
+ *
* @param oid attribute object identifier
* @return attribute definition or null if not found
*/
@@ -180,7 +177,7 @@ public class MetaAttributeDef {
/**
* Returns enumeration of the registered attribute names
* <P>
- *
+ *
* @return returns enumeration of the registered attribute names
*/
public static Enumeration<String> getAttributeNames() {
@@ -190,7 +187,7 @@ public class MetaAttributeDef {
/**
* Returns enumeration of the registered attribute object identifiers
* <P>
- *
+ *
* @return returns enumeration of the attribute object identifiers
*/
public static Enumeration<ObjectIdentifier> getAttributeNameOids() {
diff --git a/pki/base/common/src/com/netscape/certsrv/base/MetaInfo.java b/pki/base/common/src/com/netscape/certsrv/base/MetaInfo.java
index 65e40174..ba4a3412 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/MetaInfo.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/MetaInfo.java
@@ -17,17 +17,14 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.base;
-
import java.util.Enumeration;
import java.util.Hashtable;
-
/**
- * A class represents meta information. A meta information
- * object is just a generic hashtable that is embedded into
- * a request object.
+ * A class represents meta information. A meta information object is just a
+ * generic hashtable that is embedded into a request object.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class MetaInfo implements IAttrSet {
@@ -41,7 +38,7 @@ public class MetaInfo implements IAttrSet {
private Hashtable<String, Object> content = new Hashtable<String, Object>();
- /**
+ /**
* Constructs a meta information.
* <P>
*/
@@ -51,7 +48,7 @@ public class MetaInfo implements IAttrSet {
/**
* Returns a short string describing this certificate attribute.
* <P>
- *
+ *
* @return information about this certificate attribute.
*/
public String toString() {
@@ -69,11 +66,11 @@ public class MetaInfo implements IAttrSet {
sb.append("]\n");
return sb.toString();
}
-
+
/**
* Gets an attribute value.
* <P>
- *
+ *
* @param name the name of the attribute to return.
* @exception EBaseException on attribute handling errors.
*/
@@ -83,8 +80,8 @@ public class MetaInfo implements IAttrSet {
/**
* Sets an attribute value.
- *
- * @param name the name of the attribute
+ *
+ * @param name the name of the attribute
* @param obj the attribute object.
*
* @exception EBaseException on attribute handling errors.
@@ -92,18 +89,18 @@ public class MetaInfo implements IAttrSet {
public void set(String name, Object obj) throws EBaseException {
content.put(name, obj);
}
-
+
/**
* Deletes an attribute value from this CertAttrSet.
* <P>
- *
+ *
* @param name the name of the attribute to delete.
* @exception EBaseException on attribute handling errors.
*/
public void delete(String name) throws EBaseException {
content.remove(name);
}
-
+
/**
* Returns an enumeration of the names of the attributes existing within
* this attribute.
diff --git a/pki/base/common/src/com/netscape/certsrv/base/Nonces.java b/pki/base/common/src/com/netscape/certsrv/base/Nonces.java
index fde20933..cc0231ac 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/Nonces.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/Nonces.java
@@ -21,14 +21,13 @@ import java.security.cert.X509Certificate;
import java.util.Hashtable;
import java.util.Vector;
-
/**
* This class manages nonces sometimes used to control request state flow.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
-public class Nonces {
+public class Nonces {
private Hashtable<Long, X509Certificate> mNonces = new Hashtable<Long, X509Certificate>();
private Vector<Long> mNonceList = new Vector<Long>();
@@ -49,17 +48,17 @@ public class Nonces {
long i;
long k = 0;
long n = nonce;
- long m = (long)((mNonceLimit / 2) + 1);
+ long m = (long) ((mNonceLimit / 2) + 1);
for (i = 0; i < m; i++) {
k = n + i;
// avoid collisions
- if (!mNonceList.contains((Object)k)) {
+ if (!mNonceList.contains((Object) k)) {
break;
}
k = n - i;
// avoid collisions
- if (!mNonceList.contains((Object)k)) {
+ if (!mNonceList.contains((Object) k)) {
break;
}
}
@@ -67,9 +66,9 @@ public class Nonces {
mNonceList.add(k);
mNonces.put(k, cert);
if (mNonceList.size() > mNonceLimit) {
- n = ((Long)(mNonceList.firstElement())).longValue();
+ n = ((Long) (mNonceList.firstElement())).longValue();
mNonceList.remove(0);
- mNonces.remove((Object)n);
+ mNonces.remove((Object) n);
}
} else {
// failed to resolved collision
@@ -79,15 +78,15 @@ public class Nonces {
}
public X509Certificate getCertificate(long nonce) {
- X509Certificate cert = (X509Certificate)mNonces.get(nonce);
+ X509Certificate cert = (X509Certificate) mNonces.get(nonce);
return cert;
}
public X509Certificate getCertificate(int index) {
X509Certificate cert = null;
if (index >= 0 && index < mNonceList.size()) {
- long nonce = ((Long)(mNonceList.elementAt(index))).longValue();
- cert = (X509Certificate)mNonces.get(nonce);
+ long nonce = ((Long) (mNonceList.elementAt(index))).longValue();
+ cert = (X509Certificate) mNonces.get(nonce);
}
return cert;
}
@@ -95,17 +94,16 @@ public class Nonces {
public long getNonce(int index) {
long nonce = 0;
if (index >= 0 && index < mNonceList.size()) {
- nonce = ((Long)(mNonceList.elementAt(index))).longValue();
+ nonce = ((Long) (mNonceList.elementAt(index))).longValue();
}
return nonce;
}
public void removeNonce(long nonce) {
- mNonceList.remove((Object)nonce);
- mNonces.remove((Object)nonce);
+ mNonceList.remove((Object) nonce);
+ mNonces.remove((Object) nonce);
}
-
public int size() {
return mNonceList.size();
}
diff --git a/pki/base/common/src/com/netscape/certsrv/base/PasswordResources.java b/pki/base/common/src/com/netscape/certsrv/base/PasswordResources.java
index 287ce795..c3309c5f 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/PasswordResources.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/PasswordResources.java
@@ -17,14 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.base;
-
import java.util.ListResourceBundle;
-
/**
* A class represents a resource bundle for the password checker.
* <p>
- *
+ *
* @version $Revision$, $Date$
* @see java.util.ListResourceBundle
*/
@@ -42,4 +40,3 @@ public class PasswordResources extends ListResourceBundle {
*/
static final Object[][] contents = {};
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/base/Plugin.java b/pki/base/common/src/com/netscape/certsrv/base/Plugin.java
index e7001ce5..79fae88a 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/Plugin.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/Plugin.java
@@ -17,9 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.base;
-
-
-
/**
* This represents a generici CMS plugin.
* <p>
@@ -41,10 +38,10 @@ public class Plugin {
mId = id;
mClassPath = classPath;
}
-
+
/**
* Returns the plugin identifier.
- *
+ *
* @return plugin id
*/
public String getId() {
@@ -53,7 +50,7 @@ public class Plugin {
/**
* Returns the plugin classpath.
- *
+ *
* @return plugin classpath
*/
public String getClassPath() {
diff --git a/pki/base/common/src/com/netscape/certsrv/base/SessionContext.java b/pki/base/common/src/com/netscape/certsrv/base/SessionContext.java
index 151c2420..704e46b8 100644
--- a/pki/base/common/src/com/netscape/certsrv/base/SessionContext.java
+++ b/pki/base/common/src/com/netscape/certsrv/base/SessionContext.java
@@ -17,22 +17,19 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.base;
-
import java.util.Hashtable;
-
/**
- * This class specifies the context object that includes
- * authentication environment and connection information.
- * This object is later used in access control evaluation.
- * This is a global object that can be accessible
- * throughout the server. It is useful for passing
- * global and per-thread infomration in methods.
+ * This class specifies the context object that includes authentication
+ * environment and connection information. This object is later used in access
+ * control evaluation. This is a global object that can be accessible throughout
+ * the server. It is useful for passing global and per-thread infomration in
+ * methods.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
-public class SessionContext extends Hashtable<Object,Object> {
+public class SessionContext extends Hashtable<Object, Object> {
/**
*
@@ -67,7 +64,7 @@ public class SessionContext extends Hashtable<Object,Object> {
/**
* Group ID of the authenticated user in the current thread.
*/
- public static final String GROUP_ID = "groupid"; //String
+ public static final String GROUP_ID = "groupid"; // String
/**
* ID of the processing request in the current thread.
@@ -94,10 +91,9 @@ public class SessionContext extends Hashtable<Object,Object> {
}
/**
- * Creates a new context and associates it with
- * the current thread. If the current thread is
- * also associated with a old context, the old
- * context will be replaced.
+ * Creates a new context and associates it with the current thread. If the
+ * current thread is also associated with a old context, the old context
+ * will be replaced.
*/
private static SessionContext createContext() {
SessionContext sc = new SessionContext();
@@ -107,12 +103,10 @@ public class SessionContext extends Hashtable<Object,Object> {
}
/**
- * Sets the current context. This allows the
- * caller to associate a specific session context
- * with the current thread.
- * This methods makes custom session context
- * possible.
- *
+ * Sets the current context. This allows the caller to associate a specific
+ * session context with the current thread. This methods makes custom
+ * session context possible.
+ *
* @param sc session context
*/
public static void setContext(SessionContext sc) {
@@ -120,10 +114,9 @@ public class SessionContext extends Hashtable<Object,Object> {
}
/**
- * Retrieves the session context associated with
- * the current thread. If no context is associated,
- * a context is created.
- *
+ * Retrieves the session context associated with the current thread. If no
+ * context is associated, a context is created.
+ *
* @return sesssion context
*/
public static SessionContext getContext() {
@@ -137,15 +130,14 @@ public class SessionContext extends Hashtable<Object,Object> {
}
/**
- * Retrieves the session context associated with
- * the current thread. If no context is associated,
- * null is returned.
- *
+ * Retrieves the session context associated with the current thread. If no
+ * context is associated, null is returned.
+ *
* @return sesssion context
*/
public static SessionContext getExistingContext() {
SessionContext sc = (SessionContext)
- mContexts.get(Thread.currentThread());
+ mContexts.get(Thread.currentThread());
if (sc == null) {
return null;
diff --git a/pki/base/common/src/com/netscape/certsrv/ca/CAResources.java b/pki/base/common/src/com/netscape/certsrv/ca/CAResources.java
index 4510c46b..162a8832 100644
--- a/pki/base/common/src/com/netscape/certsrv/ca/CAResources.java
+++ b/pki/base/common/src/com/netscape/certsrv/ca/CAResources.java
@@ -17,14 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.ca;
-
import java.util.ListResourceBundle;
-
/**
* A class represents a resource bundle for CA subsystem.
* <P>
- *
+ *
* @version $Revision$ $Date$
*/
public class CAResources extends ListResourceBundle {
@@ -37,8 +35,7 @@ public class CAResources extends ListResourceBundle {
}
/**
- * Constants. The suffix represents the number of
- * possible parameters.
+ * Constants. The suffix represents the number of possible parameters.
*/
static final Object[][] contents = {};
}
diff --git a/pki/base/common/src/com/netscape/certsrv/ca/ECAException.java b/pki/base/common/src/com/netscape/certsrv/ca/ECAException.java
index 59d8847c..a530b08a 100644
--- a/pki/base/common/src/com/netscape/certsrv/ca/ECAException.java
+++ b/pki/base/common/src/com/netscape/certsrv/ca/ECAException.java
@@ -17,14 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.ca;
-
import com.netscape.certsrv.base.EBaseException;
-
/**
* A class represents a CA exception.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class ECAException extends EBaseException {
@@ -36,11 +34,12 @@ public class ECAException extends EBaseException {
/**
* CA resource class name.
*/
- private static final String CA_RESOURCES = CAResources.class.getName();
+ private static final String CA_RESOURCES = CAResources.class.getName();
/**
* Constructs a CA exception.
* <P>
+ *
* @param msgFormat constant from CAResources.
*/
public ECAException(String msgFormat) {
@@ -50,6 +49,7 @@ public class ECAException extends EBaseException {
/**
* Constructs a CA exception.
* <P>
+ *
* @param msgFormat constant from CAResources.
* @param param additional parameters to the message.
*/
@@ -60,6 +60,7 @@ public class ECAException extends EBaseException {
/**
* Constructs a CA exception.
* <P>
+ *
* @param msgFormat constant from CAResources.
* @param e embedded exception.
*/
@@ -70,6 +71,7 @@ public class ECAException extends EBaseException {
/**
* Constructs a CA exception.
* <P>
+ *
* @param msgFormat constant from CAResources.
* @param params additional parameters to the message.
*/
@@ -80,6 +82,7 @@ public class ECAException extends EBaseException {
/**
* Returns the bundle file name.
* <P>
+ *
* @return name of bundle class associated with this exception.
*/
protected String getBundleName() {
diff --git a/pki/base/common/src/com/netscape/certsrv/ca/EErrorPublishCRL.java b/pki/base/common/src/com/netscape/certsrv/ca/EErrorPublishCRL.java
index 0e271c21..b4c10a0c 100644
--- a/pki/base/common/src/com/netscape/certsrv/ca/EErrorPublishCRL.java
+++ b/pki/base/common/src/com/netscape/certsrv/ca/EErrorPublishCRL.java
@@ -17,11 +17,10 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.ca;
-
/**
* A class represents a CA exception associated with publishing error.
* <P>
- *
+ *
* @version $Revision$ $Date$
*/
public class EErrorPublishCRL extends ECAException {
@@ -34,9 +33,10 @@ public class EErrorPublishCRL extends ECAException {
/**
* Constructs a CA exception caused by publishing error.
* <P>
+ *
* @param errorString Detailed error message.
*/
public EErrorPublishCRL(String errorString) {
- super(errorString);
+ super(errorString);
}
}
diff --git a/pki/base/common/src/com/netscape/certsrv/ca/ICAService.java b/pki/base/common/src/com/netscape/certsrv/ca/ICAService.java
index cac6fc75..ad980384 100644
--- a/pki/base/common/src/com/netscape/certsrv/ca/ICAService.java
+++ b/pki/base/common/src/com/netscape/certsrv/ca/ICAService.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.ca;
-
import netscape.security.x509.RevokedCertImpl;
import netscape.security.x509.X509CertImpl;
import netscape.security.x509.X509CertInfo;
@@ -27,11 +26,10 @@ import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.connector.IConnector;
import com.netscape.certsrv.request.IRequest;
-
/**
* An interface representing a CA request services.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public interface ICAService {
@@ -39,54 +37,55 @@ public interface ICAService {
/**
* Marks certificate record as revoked by adding revocation information.
* Updates CRL cache.
- *
+ *
* @param crlentry revocation information obtained from revocation request
* @exception EBaseException failed to mark certificate record as revoked
*/
public void revokeCert(RevokedCertImpl crlentry)
- throws EBaseException;
+ throws EBaseException;
/**
* Marks certificate record as revoked by adding revocation information.
* Updates CRL cache.
- *
+ *
* @param crlentry revocation information obtained from revocation request
* @param requestId revocation request id
* @exception EBaseException failed to mark certificate record as revoked
*/
public void revokeCert(RevokedCertImpl crlentry, String requestId)
- throws EBaseException;
+ throws EBaseException;
/**
- * Issues certificate base on enrollment information,
- * creates certificate record, and stores all necessary data.
- *
+ * Issues certificate base on enrollment information, creates certificate
+ * record, and stores all necessary data.
+ *
* @param certi information obtain from revocation request
- * @exception EBaseException failed to issue certificate or create certificate record
+ * @exception EBaseException failed to issue certificate or create
+ * certificate record
*/
public X509CertImpl issueX509Cert(X509CertInfo certi)
- throws EBaseException;
+ throws EBaseException;
public X509CertImpl issueX509Cert(X509CertInfo certi, String profileId, String rid)
- throws EBaseException;
+ throws EBaseException;
/**
* Services profile request.
- *
+ *
* @param request profile enrollment request information
* @exception EBaseException failed to service profile enrollment request
*/
public void serviceProfileRequest(IRequest request)
- throws EBaseException;
+ throws EBaseException;
/**
* Returns KRA-CA connector.
- *
+ *
* @return KRA-CA connector
*/
public IConnector getKRAConnector();
public void setKRAConnector(IConnector c);
- public IConnector getConnector(IConfigStore cs) throws EBaseException;
+ public IConnector getConnector(IConfigStore cs) throws EBaseException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/ca/ICMSCRLExtension.java b/pki/base/common/src/com/netscape/certsrv/ca/ICMSCRLExtension.java
index edaea59c..afc7bb3f 100644
--- a/pki/base/common/src/com/netscape/certsrv/ca/ICMSCRLExtension.java
+++ b/pki/base/common/src/com/netscape/certsrv/ca/ICMSCRLExtension.java
@@ -17,58 +17,55 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.ca;
-
import netscape.security.x509.Extension;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.common.NameValuePairs;
-
/**
* An interface representing a CRL extension plugin.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public interface ICMSCRLExtension {
/**
* Returns CRL extension OID string.
- *
+ *
* @return OID of CRL extension
*/
public String getCRLExtOID();
/**
- * Sets extension criticality and returns extension
- * with new criticality.
- *
+ * Sets extension criticality and returns extension with new criticality.
+ *
* @param ext CRL extension that will change criticality
* @param critical new criticality to be assigned to CRL extension
* @return extension with new criticality
*/
Extension setCRLExtensionCriticality(Extension ext,
- boolean critical);
+ boolean critical);
/**
- * Builds new CRL extension based on configuration data,
- * issuing point information, and criticality.
- *
+ * Builds new CRL extension based on configuration data, issuing point
+ * information, and criticality.
+ *
* @param config configuration store
* @param crlIssuingPoint CRL issuing point
* @param critical criticality to be assigned to CRL extension
* @return extension new CRL extension
*/
Extension getCRLExtension(IConfigStore config,
- Object crlIssuingPoint,
- boolean critical);
+ Object crlIssuingPoint,
+ boolean critical);
/**
* Reads configuration data and converts them to name value pairs.
- *
+ *
* @param config configuration store
- * @param nvp name value pairs obtained from configuration data
+ * @param nvp name value pairs obtained from configuration data
*/
public void getConfigParams(IConfigStore config,
- NameValuePairs nvp);
-}
+ NameValuePairs nvp);
+}
diff --git a/pki/base/common/src/com/netscape/certsrv/ca/ICMSCRLExtensions.java b/pki/base/common/src/com/netscape/certsrv/ca/ICMSCRLExtensions.java
index f6df2226..f5d3ab7f 100644
--- a/pki/base/common/src/com/netscape/certsrv/ca/ICMSCRLExtensions.java
+++ b/pki/base/common/src/com/netscape/certsrv/ca/ICMSCRLExtensions.java
@@ -17,23 +17,21 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.ca;
-
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.common.NameValuePairs;
-
/**
* An interface representing a list of CRL extensions.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public interface ICMSCRLExtensions {
/**
- * Updates configuration store for extension identified by id
- * with data delivered in name value pairs.
- *
+ * Updates configuration store for extension identified by id with data
+ * delivered in name value pairs.
+ *
* @param id extension id
* @param nvp name value pairs with new configuration data
* @param config configuration store
@@ -42,7 +40,7 @@ public interface ICMSCRLExtensions {
/**
* Reads configuration data and returns them as name value pairs.
- *
+ *
* @param id extension id
* @return name value pairs with configuration data
*/
@@ -50,10 +48,9 @@ public interface ICMSCRLExtensions {
/**
* Returns class name with its path.
- *
+ *
* @param name extension id
* @return class name with its path
*/
public String getClassPath(String name);
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/ca/ICRLIssuingPoint.java b/pki/base/common/src/com/netscape/certsrv/ca/ICRLIssuingPoint.java
index dab45fdb..e4ca5d6e 100644
--- a/pki/base/common/src/com/netscape/certsrv/ca/ICRLIssuingPoint.java
+++ b/pki/base/common/src/com/netscape/certsrv/ca/ICRLIssuingPoint.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.ca;
-
import java.math.BigInteger;
import java.util.Date;
import java.util.Set;
@@ -34,19 +33,17 @@ import com.netscape.certsrv.base.ISubsystem;
import com.netscape.certsrv.common.NameValuePairs;
import com.netscape.certsrv.dbs.IElementProcessor;
-
/**
- * This class encapsulates CRL issuing mechanism. CertificateAuthority
- * contains a map of CRLIssuingPoint indexed by string ids. Each issuing
- * point contains information about CRL issuing and publishing parameters
- * as well as state information which includes last issued CRL, next CRL
- * serial number, time of the next update etc.
- * If autoUpdateInterval is set to non-zero value then worker thread
- * is created that will perform CRL update at scheduled intervals. Update
- * can also be triggered by invoking updateCRL method directly. Another
- * parameter minUpdateInterval can be used to prevent CRL
- * from being updated too often
- *
+ * This class encapsulates CRL issuing mechanism. CertificateAuthority contains
+ * a map of CRLIssuingPoint indexed by string ids. Each issuing point contains
+ * information about CRL issuing and publishing parameters as well as state
+ * information which includes last issued CRL, next CRL serial number, time of
+ * the next update etc. If autoUpdateInterval is set to non-zero value then
+ * worker thread is created that will perform CRL update at scheduled intervals.
+ * Update can also be triggered by invoking updateCRL method directly. Another
+ * parameter minUpdateInterval can be used to prevent CRL from being updated too
+ * often
+ *
* @version $Revision$, $Date$
*/
@@ -75,151 +72,151 @@ public interface ICRLIssuingPoint {
/**
* Returns true if CRL issuing point is enabled.
- *
+ *
* @return true if CRL issuing point is enabled
*/
public boolean isCRLIssuingPointEnabled();
/**
* Returns true if CRL generation is enabled.
- *
+ *
* @return true if CRL generation is enabled
*/
public boolean isCRLGenerationEnabled();
/**
* Enables or disables CRL issuing point according to parameter.
- *
+ *
* @param enable if true enables CRL issuing point
*/
public void enableCRLIssuingPoint(boolean enable);
/**
* Returns CRL update status.
- *
+ *
* @return CRL update status
*/
public String getCrlUpdateStatusStr();
/**
* Returns CRL update error.
- *
+ *
* @return CRL update error
*/
public String getCrlUpdateErrorStr();
/**
* Returns CRL publishing status.
- *
+ *
* @return CRL publishing status
*/
public String getCrlPublishStatusStr();
/**
* Returns CRL publishing error.
- *
+ *
* @return CRL publishing error
*/
public String getCrlPublishErrorStr();
/**
* Returns CRL issuing point initialization status.
- *
+ *
* @return status of CRL issuing point initialization
*/
public int isCRLIssuingPointInitialized();
/**
* Checks if manual update is set.
- *
+ *
* @return true if manual update is set
*/
public boolean isManualUpdateSet();
/**
* Checks if expired certificates are included in CRL.
- *
+ *
* @return true if expired certificates are included in CRL
*/
public boolean areExpiredCertsIncluded();
/**
* Checks if CRL includes CA certificates only.
- *
+ *
* @return true if CRL includes CA certificates only
*/
public boolean isCACertsOnly();
/**
* Checks if CRL includes profile certificates only.
- *
+ *
* @return true if CRL includes profile certificates only
*/
public boolean isProfileCertsOnly();
/**
* Checks if CRL issuing point includes this profile.
- *
+ *
* @return true if CRL issuing point includes this profile
*/
public boolean checkCurrentProfile(String id);
/**
* Initializes CRL issuing point.
- *
- * @param ca certificate authority that holds CRL issuing point
+ *
+ * @param ca certificate authority that holds CRL issuing point
* @param id CRL issuing point id
* @param config configuration sub-store for CRL issuing point
* @exception EBaseException thrown if initialization failed
*/
- public void init(ISubsystem ca, String id, IConfigStore config)
- throws EBaseException;
+ public void init(ISubsystem ca, String id, IConfigStore config)
+ throws EBaseException;
/**
- * This method is called during shutdown.
- * It updates CRL cache and stops thread controlling CRL updates.
+ * This method is called during shutdown. It updates CRL cache and stops
+ * thread controlling CRL updates.
*/
public void shutdown();
/**
* Returns internal id of this CRL issuing point.
- *
+ *
* @return internal id of this CRL issuing point
*/
public String getId();
/**
* Returns internal description of this CRL issuing point.
- *
+ *
* @return internal description of this CRL issuing point
*/
public String getDescription();
/**
* Sets internal description of this CRL issuing point.
- *
+ *
* @param description description for this CRL issuing point.
*/
public void setDescription(String description);
/**
- * Returns DN of the directory entry where CRLs from this issuing point
- * are published.
- *
+ * Returns DN of the directory entry where CRLs from this issuing point are
+ * published.
+ *
* @return DN of the directory entry where CRLs are published.
*/
public String getPublishDN();
/**
* Returns signing algorithm.
- *
+ *
* @return signing algorithm
*/
public String getSigningAlgorithm();
/**
* Returns signing algorithm used in last signing operation..
- *
+ *
* @return last signing algorithm
*/
public String getLastSigningAlgorithm();
@@ -227,14 +224,14 @@ public interface ICRLIssuingPoint {
/**
* Returns current CRL generation schema for this CRL issuing point.
* <P>
- *
+ *
* @return current CRL generation schema for this CRL issuing point
*/
public int getCRLSchema();
/**
* Returns current CRL number of this CRL issuing point.
- *
+ *
* @return current CRL number of this CRL issuing point
*/
public BigInteger getCRLNumber();
@@ -242,56 +239,56 @@ public interface ICRLIssuingPoint {
/**
* Returns current delta CRL number of this CRL issuing point.
* <P>
- *
+ *
* @return current delta CRL number of this CRL issuing point
*/
public BigInteger getDeltaCRLNumber();
/**
* Returns next CRL number of this CRL issuing point.
- *
+ *
* @return next CRL number of this CRL issuing point
*/
public BigInteger getNextCRLNumber();
/**
* Returns number of entries in the current CRL.
- *
+ *
* @return number of entries in the current CRL
*/
public long getCRLSize();
/**
* Returns number of entries in delta CRL
- *
+ *
* @return number of entries in delta CRL
*/
public long getDeltaCRLSize();
/**
* Returns time of the last update.
- *
+ *
* @return last CRL update time
*/
public Date getLastUpdate();
/**
* Returns time of the next update.
- *
+ *
* @return next CRL update time
*/
public Date getNextUpdate();
/**
* Returns time of the next delta CRL update.
- *
+ *
* @return next delta CRL update time
*/
public Date getNextDeltaUpdate();
/**
* Returns all the revoked certificates from the CRL cache.
- *
+ *
* @param start first requested CRL entry
* @param end next after last requested CRL entry
* @return set of all the revoked certificates or null if there are none.
@@ -300,92 +297,92 @@ public interface ICRLIssuingPoint {
/**
* Returns certificate authority.
- *
+ *
* @return certificate authority
*/
public ISubsystem getCertificateAuthority();
/**
- * Schedules immediate CRL manual-update
- * and sets signature algorithm to be used for signing.
- *
+ * Schedules immediate CRL manual-update and sets signature algorithm to be
+ * used for signing.
+ *
* @param signatureAlgorithm signature algorithm to be used for signing
*/
- public void setManualUpdate(String signatureAlgorithm);
+ public void setManualUpdate(String signatureAlgorithm);
/**
* Returns auto update interval in milliseconds.
- *
+ *
* @return auto update interval in milliseconds
*/
public long getAutoUpdateInterval();
/**
- * Returns true if CRL is updated for every change
- * of revocation status of any certificate.
- *
+ * Returns true if CRL is updated for every change of revocation status of
+ * any certificate.
+ *
* @return true if CRL update is always triggered by revocation operation
*/
public boolean getAlwaysUpdate();
/**
* Returns next update grace period in minutes.
- *
+ *
* @return next update grace period in minutes
*/
public long getNextUpdateGracePeriod();
/**
- * Returns filter used to build CRL based on information stored
- * in local directory.
- *
+ * Returns filter used to build CRL based on information stored in local
+ * directory.
+ *
* @return filter used to search local directory
*/
public String getFilter();
/**
- * Builds a list of revoked certificates to put them into CRL.
- * Calls certificate record processor to get necessary data
- * from certificate records.
- * This also regenerates CRL cache.
- *
+ * Builds a list of revoked certificates to put them into CRL. Calls
+ * certificate record processor to get necessary data from certificate
+ * records. This also regenerates CRL cache.
+ *
* @param cp certificate record processor
* @exception EBaseException if an error occurred in the database.
*/
public void processRevokedCerts(IElementProcessor cp)
- throws EBaseException;
+ throws EBaseException;
/**
- * Returns date of revoked certificate or null
- * if certificated is not listed as revoked.
- *
+ * Returns date of revoked certificate or null if certificated is not listed
+ * as revoked.
+ *
* @param serialNumber serial number of certificate to be checked
- * @param checkDeltaCache true if delta CRL cache suppose to be
- * included in checking process
+ * @param checkDeltaCache true if delta CRL cache suppose to be included in
+ * checking process
* @param includeExpiredCerts true if delta CRL cache with expired
- * certificates suppose to be included in checking process
+ * certificates suppose to be included in checking process
* @return date of revoked certificate or null
*/
public Date getRevocationDateFromCache(BigInteger serialNumber,
boolean checkDeltaCache,
boolean includeExpiredCerts);
+
/**
* Returns split times from CRL generation.
- *
+ *
* @return split times from CRL generation in milliseconds
*/
public Vector<Long> getSplitTimes();
/**
- * Generates CRL now based on cache or local directory if cache
- * is not available. It also publishes CRL if it is required.
- *
+ * Generates CRL now based on cache or local directory if cache is not
+ * available. It also publishes CRL if it is required.
+ *
* @param signingAlgorithm signing algorithm to be used for CRL signing
- * @exception EBaseException if an error occurred during
- * CRL generation or publishing
+ * @exception EBaseException if an error occurred during CRL generation or
+ * publishing
*/
- public void updateCRLNow(String signingAlgorithm)
- throws EBaseException;
+ public void updateCRLNow(String signingAlgorithm)
+ throws EBaseException;
/**
* Clears CRL cache
@@ -399,29 +396,29 @@ public interface ICRLIssuingPoint {
/**
* Returns number of recently revoked certificates.
- *
+ *
* @return number of recently revoked certificates
*/
public int getNumberOfRecentlyRevokedCerts();
/**
* Returns number of recently unrevoked certificates.
- *
+ *
* @return number of recently unrevoked certificates
*/
public int getNumberOfRecentlyUnrevokedCerts();
/**
* Returns number of recently expired and revoked certificates.
- *
+ *
* @return number of recently expired and revoked certificates
*/
public int getNumberOfRecentlyExpiredCerts();
/**
- * Converts list of extensions supplied by revocation request
- * to list of extensions required to be placed in CRL.
- *
+ * Converts list of extensions supplied by revocation request to list of
+ * extensions required to be placed in CRL.
+ *
* @param exts list of extensions supplied by revocation request
* @return list of extensions required to be placed in CRL
*/
@@ -429,7 +426,7 @@ public interface ICRLIssuingPoint {
/**
* Adds revoked certificate to delta-CRL cache.
- *
+ *
* @param serialNumber serial number of revoked certificate
* @param revokedCert revocation information supplied by revocation request
*/
@@ -437,7 +434,7 @@ public interface ICRLIssuingPoint {
/**
* Adds revoked certificate to delta-CRL cache.
- *
+ *
* @param serialNumber serial number of revoked certificate
* @param revokedCert revocation information supplied by revocation request
* @param requestId revocation request id
@@ -447,14 +444,14 @@ public interface ICRLIssuingPoint {
/**
* Adds unrevoked certificate to delta-CRL cache.
- *
+ *
* @param serialNumber serial number of unrevoked certificate
*/
public void addUnrevokedCert(BigInteger serialNumber);
/**
* Adds unrevoked certificate to delta-CRL cache.
- *
+ *
* @param serialNumber serial number of unrevoked certificate
* @param requestId unrevocation request id
*/
@@ -462,7 +459,7 @@ public interface ICRLIssuingPoint {
/**
* Adds expired and revoked certificate to delta-CRL cache.
- *
+ *
* @param serialNumber serial number of expired and revoked certificate
*/
public void addExpiredCert(BigInteger serialNumber);
@@ -473,9 +470,9 @@ public interface ICRLIssuingPoint {
public void updateCRLCacheRepository();
/**
- * Updates issuing point configuration according to supplied data
- * in name value pairs.
- *
+ * Updates issuing point configuration according to supplied data in name
+ * value pairs.
+ *
* @param params name value pairs defining new issuing point configuration
* @return true if configuration is updated successfully
*/
@@ -483,35 +480,35 @@ public interface ICRLIssuingPoint {
/**
* Returns true if delta-CRL is enabled.
- *
+ *
* @return true if delta-CRL is enabled
*/
public boolean isDeltaCRLEnabled();
/**
* Returns true if CRL cache is enabled.
- *
+ *
* @return true if CRL cache is enabled
*/
public boolean isCRLCacheEnabled();
/**
* Returns true if CRL cache is empty.
- *
+ *
* @return true if CRL cache is empty
*/
public boolean isCRLCacheEmpty();
/**
* Returns true if CRL cache testing is enabled.
- *
+ *
* @return true if CRL cache testing is enabled
*/
public boolean isCRLCacheTestingEnabled();
/**
* Returns true if supplied delta-CRL is matching current delta-CRL.
- *
+ *
* @param deltaCRL delta-CRL to verify against current delta-CRL
* @return true if supplied delta-CRL is matching current delta-CRL
*/
@@ -519,27 +516,26 @@ public interface ICRLIssuingPoint {
/**
* Returns status of CRL generation.
- *
+ *
* @return one of the following according to CRL generation status:
* CRL_UPDATE_DONE, CRL_UPDATE_STARTED, and CRL_PUBLISHING_STARTED
*/
public int isCRLUpdateInProgress();
/**
- * Generates CRL now based on cache or local directory if cache
- * is not available. It also publishes CRL if it is required.
- * CRL is signed by default signing algorithm.
- *
- * @exception EBaseException if an error occurred during
- * CRL generation or publishing
+ * Generates CRL now based on cache or local directory if cache is not
+ * available. It also publishes CRL if it is required. CRL is signed by
+ * default signing algorithm.
+ *
+ * @exception EBaseException if an error occurred during CRL generation or
+ * publishing
*/
- public void updateCRLNow() throws EBaseException;
+ public void updateCRLNow() throws EBaseException;
/**
* Returns list of CRL extensions.
- *
+ *
* @return list of CRL extensions
*/
public ICMSCRLExtensions getCRLExtensions();
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/ca/ICertificateAuthority.java b/pki/base/common/src/com/netscape/certsrv/ca/ICertificateAuthority.java
index d86a37dd..9429d1c3 100644
--- a/pki/base/common/src/com/netscape/certsrv/ca/ICertificateAuthority.java
+++ b/pki/base/common/src/com/netscape/certsrv/ca/ICertificateAuthority.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.ca;
-
import java.util.Enumeration;
import netscape.security.x509.CertificateChain;
@@ -29,7 +28,6 @@ import netscape.security.x509.X509CertInfo;
import org.mozilla.jss.crypto.SignatureAlgorithm;
-
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.base.ISubsystem;
@@ -45,12 +43,11 @@ import com.netscape.certsrv.request.IRequestQueue;
import com.netscape.certsrv.request.IService;
import com.netscape.certsrv.security.ISigningUnit;
-
/**
- * An interface represents a Certificate Authority that is
- * responsible for certificate specific operations.
+ * An interface represents a Certificate Authority that is responsible for
+ * certificate specific operations.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public interface ICertificateAuthority extends ISubsystem {
@@ -78,7 +75,7 @@ public interface ICertificateAuthority extends ISubsystem {
public final static String PROP_DEF_VALIDITY = "DefaultIssueValidity";
public final static String PROP_FAST_SIGNING = "fastSigning";
public static final String PROP_ENABLE_ADMIN_ENROLL =
- "enableAdminEnroll";
+ "enableAdminEnroll";
public final static String PROP_CRL_SUBSTORE = "crl";
// make this public so agent gateway can access for now.
@@ -86,9 +83,9 @@ public interface ICertificateAuthority extends ISubsystem {
public final static String PROP_MASTER_CRL = "MasterCRL";
public final static String PROP_CRLEXT_SUBSTORE = "extension";
public final static String PROP_ISSUING_CLASS =
- "com.netscape.cmscore.ca.CRLIssuingPoint";
+ "com.netscape.cmscore.ca.CRLIssuingPoint";
public final static String PROP_EXPIREDCERTS_CLASS =
- "com.netscape.cmscore.ca.CRLWithExpiredCerts";
+ "com.netscape.cmscore.ca.CRLWithExpiredCerts";
public final static String PROP_NOTIFY_SUBSTORE = "notification";
public final static String PROP_CERT_ISSUED_SUBSTORE = "certIssued";
@@ -109,67 +106,68 @@ public interface ICertificateAuthority extends ISubsystem {
public final static String PROP_ID = "id";
public final static String PROP_CERTDB_TRANS_MAXRECORDS = "transitMaxRecords";
- public final static String PROP_CERTDB_TRANS_PAGESIZE = "transitRecordPageSize";
+ public final static String PROP_CERTDB_TRANS_PAGESIZE = "transitRecordPageSize";
/**
- * Retrieves the certificate repository where all the locally
- * issued certificates are kept.
- *
+ * Retrieves the certificate repository where all the locally issued
+ * certificates are kept.
+ *
* @return CA's certificate repository
*/
public ICertificateRepository getCertificateRepository();
/**
* Retrieves the request queue of this certificate authority.
- *
+ *
* @return CA's request queue
*/
public IRequestQueue getRequestQueue();
/**
* Retrieves the policy processor of this certificate authority.
- *
+ *
* @return CA's policy processor
*/
public IPolicyProcessor getPolicyProcessor();
public boolean noncesEnabled();
- public Nonces getNonces();
+
+ public Nonces getNonces();
/**
* Retrieves the publishing processor of this certificate authority.
- *
+ *
* @return CA's publishing processor
*/
public IPublisherProcessor getPublisherProcessor();
/**
* Retrieves the next available serial number.
- *
+ *
* @return next available serial number
*/
public String getStartSerial();
/**
* Sets the next available serial number.
- *
+ *
* @param serial next available serial number
* @exception EBaseException failed to set next available serial number
*/
public void setStartSerial(String serial) throws EBaseException;
/**
- * Retrieves the last serial number that can be used for
- * certificate issuance in this certificate authority.
- *
+ * Retrieves the last serial number that can be used for certificate
+ * issuance in this certificate authority.
+ *
* @return the last serial number
*/
public String getMaxSerial();
/**
- * Sets the last serial number that can be used for
- * certificate issuance in this certificate authority.
- *
+ * Sets the last serial number that can be used for certificate issuance in
+ * this certificate authority.
+ *
* @param serial the last serial number
* @exception EBaseException failed to set the last serial number
*/
@@ -177,21 +175,21 @@ public interface ICertificateAuthority extends ISubsystem {
/**
* Retrieves the default signature algorithm of this certificate authority.
- *
+ *
* @return the default signature algorithm of this CA
*/
public SignatureAlgorithm getDefaultSignatureAlgorithm();
/**
* Retrieves the default signing algorithm of this certificate authority.
- *
+ *
* @return the default signing algorithm of this CA
*/
public String getDefaultAlgorithm();
/**
* Sets the default signing algorithm of this certificate authority.
- *
+ *
* @param algorithm new default signing algorithm
* @exception EBaseException failed to set the default signing algorithm
*/
@@ -199,38 +197,38 @@ public interface ICertificateAuthority extends ISubsystem {
/**
* Retrieves the supported signing algorithms of this certificate authority.
- *
+ *
* @return the supported signing algorithms of this CA
*/
public String[] getCASigningAlgorithms();
/**
- * Allows certificates to have validities that are longer
- * than this certificate authority's.
- *
- * @param enableCAPast if equals "true", it allows certificates
- * to have validity longer than CA's certificate validity
+ * Allows certificates to have validities that are longer than this
+ * certificate authority's.
+ *
+ * @param enableCAPast if equals "true", it allows certificates to have
+ * validity longer than CA's certificate validity
* @exception EBaseException failed to set above option
*/
- public void setValidity(String enableCAPast) throws EBaseException;
+ public void setValidity(String enableCAPast) throws EBaseException;
/**
* Retrieves the default validity period.
- *
+ *
* @return the default validity length in days
*/
public long getDefaultValidity();
/**
* Retrieves all the CRL issuing points.
- *
+ *
* @return enumeration of all the CRL issuing points
*/
public Enumeration<ICRLIssuingPoint> getCRLIssuingPoints();
/**
* Retrieves CRL issuing point with the given identifier.
- *
+ *
* @param id CRL issuing point id
* @return CRL issuing point with given id
*/
@@ -238,7 +236,7 @@ public interface ICertificateAuthority extends ISubsystem {
/**
* Adds CRL issuing point with the given identifier and description.
- *
+ *
* @param crlSubStore sub-store with all CRL issuing points
* @param id CRL issuing point id
* @param description CRL issuing point description
@@ -249,7 +247,7 @@ public interface ICertificateAuthority extends ISubsystem {
/**
* Deletes CRL issuing point with the given identifier.
- *
+ *
* @param crlSubStore sub-store with all CRL issuing points
* @param id CRL issuing point id
*/
@@ -257,122 +255,122 @@ public interface ICertificateAuthority extends ISubsystem {
/**
* Retrieves the CRL repository.
- *
+ *
* @return CA's CRL repository
*/
public ICRLRepository getCRLRepository();
/**
* Retrieves the Replica ID repository.
- *
+ *
* @return CA's Replica ID repository
*/
public IReplicaIDRepository getReplicaRepository();
/**
* Retrieves the request in queue listener.
- *
+ *
* @return the request in queue listener
*/
public IRequestListener getRequestInQListener();
/**
* Retrieves all request listeners.
- *
+ *
* @return name enumeration of all request listeners
*/
- public Enumeration<String> getRequestListenerNames();
+ public Enumeration<String> getRequestListenerNames();
/**
* Retrieves the request listener for issued certificates.
- *
+ *
* @return the request listener for issued certificates
*/
public IRequestListener getCertIssuedListener();
/**
* Retrieves the request listener for revoked certificates.
- *
+ *
* @return the request listener for revoked certificates
*/
public IRequestListener getCertRevokedListener();
/**
* Retrieves the CA certificate chain.
- *
+ *
* @return the CA certificate chain
*/
- public CertificateChain getCACertChain();
+ public CertificateChain getCACertChain();
/**
* Retrieves the CA certificate.
- *
+ *
* @return the CA certificate
*/
public org.mozilla.jss.crypto.X509Certificate getCaX509Cert();
/**
* Retrieves the CA certificate.
- *
+ *
* @return the CA certificate
*/
public X509CertImpl getCACert();
/**
* Updates the CRL immediately for MasterCRL issuing point if it exists.
- *
+ *
* @exception EBaseException failed to create or publish CRL
*/
public void updateCRLNow() throws EBaseException;
/**
* Publishes the CRL immediately for MasterCRL issuing point if it exists.
- *
+ *
* @exception EBaseException failed to publish CRL
*/
public void publishCRLNow() throws EBaseException;
/**
- * Retrieves the signing unit that manages the CA signing key for
- * signing certificates.
- *
+ * Retrieves the signing unit that manages the CA signing key for signing
+ * certificates.
+ *
* @return the CA signing unit for certificates
*/
public ISigningUnit getSigningUnit();
/**
- * Retrieves the signing unit that manages the CA signing key for
- * signing CRL.
- *
+ * Retrieves the signing unit that manages the CA signing key for signing
+ * CRL.
+ *
* @return the CA signing unit for CRLs
*/
public ISigningUnit getCRLSigningUnit();
/**
- * Retrieves the signing unit that manages the CA signing key for
- * signing OCSP response.
- *
+ * Retrieves the signing unit that manages the CA signing key for signing
+ * OCSP response.
+ *
* @return the CA signing unit for OCSP responses
*/
public ISigningUnit getOCSPSigningUnit();
/**
* Sets the maximium path length in the basic constraint extension.
- *
+ *
* @param num the maximium path length
*/
public void setBasicConstraintMaxLen(int num);
/**
* Is this a clone CA?
- *
+ *
* @return true if this is a clone CA
*/
public boolean isClone();
/**
* Retrieves the request listener by name.
- *
+ *
* @param name request listener name
* @return the request listener
*/
@@ -382,17 +380,17 @@ public interface ICertificateAuthority extends ISubsystem {
* get request notifier
*/
public IRequestNotifier getRequestNotifier();
-
+
/**
* Registers a request listener.
- *
+ *
* @param listener request listener to be registered
*/
public void registerRequestListener(IRequestListener listener);
/**
* Registers a request listener.
- *
+ *
* @param name under request listener is going to be registered
* @param listener request listener to be registered
*/
@@ -400,32 +398,32 @@ public interface ICertificateAuthority extends ISubsystem {
/**
* Retrieves the issuer name of this certificate authority.
- *
+ *
* @return the issuer name of this certificate authority
*/
public X500Name getX500Name();
/**
* Retrieves the issuer name of this certificate authority issuing point.
- *
+ *
* @return the issuer name of this certificate authority issuing point
*/
- public X500Name getCRLX500Name();
+ public X500Name getCRLX500Name();
/**
* Signs the given CRL with the specific algorithm.
- *
+ *
* @param crl CRL to be signed
* @param algname algorithm used for signing
* @return signed CRL
* @exception EBaseException failed to sign CRL
*/
public X509CRLImpl sign(X509CRLImpl crl, String algname)
- throws EBaseException;
+ throws EBaseException;
/**
* Logs a message to this certificate authority.
- *
+ *
* @param level logging level
* @param msg logged message
*/
@@ -433,72 +431,71 @@ public interface ICertificateAuthority extends ISubsystem {
/**
* Returns the nickname for the CA signing certificate.
- *
+ *
* @return the nickname for the CA signing certificate
*/
public String getNickname();
/**
* Signs a X.509 certificate template.
- *
+ *
* @param certInfo X.509 certificate template
* @param algname algorithm used for signing
* @return signed certificate
* @exception EBaseException failed to sign certificate
*/
public X509CertImpl sign(X509CertInfo certInfo, String algname)
- throws EBaseException;
+ throws EBaseException;
/**
* Retrieves the default certificate version.
- *
+ *
* @return the default version certificate
*/
public CertificateVersion getDefaultCertVersion();
/**
- * Is this CA allowed to issue certificate that has longer
- * validty than the CA's.
- *
+ * Is this CA allowed to issue certificate that has longer validty than the
+ * CA's.
+ *
* @return true if allows certificates to have validity longer than CA's
*/
public boolean isEnablePastCATime();
/**
- * Retrieves the CA service object that is responsible for
- * processing requests.
- *
+ * Retrieves the CA service object that is responsible for processing
+ * requests.
+ *
* @return CA service object
*/
public IService getCAService();
/**
* Returns the in-memory count of the processed OCSP requests.
- *
+ *
* @return number of processed OCSP requests in memory
*/
public long getNumOCSPRequest();
/**
- * Returns the in-memory time (in mini-second) of
- * the processed time for OCSP requests.
- *
+ * Returns the in-memory time (in mini-second) of the processed time for
+ * OCSP requests.
+ *
* @return processed times for OCSP requests
*/
public long getOCSPRequestTotalTime();
/**
- * Returns the in-memory time (in mini-second) of
- * the signing time for OCSP requests.
- *
+ * Returns the in-memory time (in mini-second) of the signing time for OCSP
+ * requests.
+ *
* @return processed times for OCSP requests
*/
public long getOCSPTotalSignTime();
/**
- * Returns the total data signed
- * for OCSP requests.
- *
+ * Returns the total data signed for OCSP requests.
+ *
* @return processed times for OCSP requests
*/
public long getOCSPTotalData();
diff --git a/pki/base/common/src/com/netscape/certsrv/cert/ICrossCertPairSubsystem.java b/pki/base/common/src/com/netscape/certsrv/cert/ICrossCertPairSubsystem.java
index 653c684f..c4cea76e 100644
--- a/pki/base/common/src/com/netscape/certsrv/cert/ICrossCertPairSubsystem.java
+++ b/pki/base/common/src/com/netscape/certsrv/cert/ICrossCertPairSubsystem.java
@@ -17,45 +17,44 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.cert;
-
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.ISubsystem;
-
/**
* Interface for handling cross certs
- *
+ *
* @version $Revision$, $Date$
*/
public interface ICrossCertPairSubsystem extends ISubsystem {
/**
- * "import" the CA cert cross-signed by another CA (potentially a
- * bridge CA) into internal ldap db.
- * If publishing is turned on, and
- * if matches up a pair, then publish to publishing directory
- * otherwise, leave in internal ldap db and wait for it's matching
- * pair
+ * "import" the CA cert cross-signed by another CA (potentially a bridge CA)
+ * into internal ldap db. If publishing is turned on, and if matches up a
+ * pair, then publish to publishing directory otherwise, leave in internal
+ * ldap db and wait for it's matching pair
+ *
* @param certBytes binary byte array of the cert
- * @exception EBaseException when certBytes conversion to X509
- * certificate fails
+ * @exception EBaseException when certBytes conversion to X509 certificate
+ * fails
*/
public void importCert(byte[] certBytes) throws EBaseException;
/**
* publish all cert pairs, if publisher is on
- * @exception EBaseException when publishing fails
+ *
+ * @exception EBaseException when publishing fails
*/
public void publishCertPairs() throws EBaseException;
- /**
- * convert byte array to X509Certificate
- * @return X509Certificate the X509Certificate class
- * representation of the certificate byte array
- * @exception CertificateException when conversion fails
- */
+ /**
+ * convert byte array to X509Certificate
+ *
+ * @return X509Certificate the X509Certificate class representation of the
+ * certificate byte array
+ * @exception CertificateException when conversion fails
+ */
public X509Certificate byteArray2X509Cert(byte[] certBytes) throws CertificateException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/client/IDataProcessor.java b/pki/base/common/src/com/netscape/certsrv/client/IDataProcessor.java
index 3bce367d..7f78b97e 100644
--- a/pki/base/common/src/com/netscape/certsrv/client/IDataProcessor.java
+++ b/pki/base/common/src/com/netscape/certsrv/client/IDataProcessor.java
@@ -17,18 +17,18 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.client;
-
/**
- * this class represents the callback interface between
- * the client package and the data storage object (data model)
- *
+ * this class represents the callback interface between the client package and
+ * the data storage object (data model)
+ *
* @version $Revision$, $Date$
*/
public interface IDataProcessor {
/**
- * This method will be callby the client package each time
- * data object arrived from the server side.
+ * This method will be callby the client package each time data object
+ * arrived from the server side.
+ *
* @param data data object expected by the interface implementor
*/
public void processData(Object data);
diff --git a/pki/base/common/src/com/netscape/certsrv/client/connection/IAuthenticator.java b/pki/base/common/src/com/netscape/certsrv/client/connection/IAuthenticator.java
index ff83cadd..0a96ee69 100644
--- a/pki/base/common/src/com/netscape/certsrv/client/connection/IAuthenticator.java
+++ b/pki/base/common/src/com/netscape/certsrv/client/connection/IAuthenticator.java
@@ -17,10 +17,9 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.client.connection;
-
/**
* An interface represents authentiator.
- *
+ *
* @version $Revision$, $Date$
*/
public interface IAuthenticator {
diff --git a/pki/base/common/src/com/netscape/certsrv/client/connection/IConnection.java b/pki/base/common/src/com/netscape/certsrv/client/connection/IConnection.java
index 18bd3518..4a8166b0 100644
--- a/pki/base/common/src/com/netscape/certsrv/client/connection/IConnection.java
+++ b/pki/base/common/src/com/netscape/certsrv/client/connection/IConnection.java
@@ -22,13 +22,13 @@ import java.net.SocketException;
/**
* Interface for all connection objects.
- *
+ *
* @version $Revision$, $Date$
*/
public interface IConnection {
/**
- * Send request to the server using this connection
+ * Send request to the server using this connection
*/
public int sendRequest(String req) throws IOException;
@@ -41,11 +41,10 @@ public interface IConnection {
* Close the connection
*/
public void disconnect();
-
+
/**
* SetTimeout
*/
public void setSoTimeout(int timeout) throws SocketException;
-
-
+
}
diff --git a/pki/base/common/src/com/netscape/certsrv/client/connection/IConnectionFactory.java b/pki/base/common/src/com/netscape/certsrv/client/connection/IConnectionFactory.java
index 1542d5fa..59f06a4c 100644
--- a/pki/base/common/src/com/netscape/certsrv/client/connection/IConnectionFactory.java
+++ b/pki/base/common/src/com/netscape/certsrv/client/connection/IConnectionFactory.java
@@ -21,23 +21,23 @@ import java.io.IOException;
import java.net.UnknownHostException;
/**
- * Interface for all connection factory. Primarily act as
- * the abstraction layer for different kind of connection factory.
- *
+ * Interface for all connection factory. Primarily act as the abstraction layer
+ * for different kind of connection factory.
+ *
* @version $Revision$, $Date$
*/
public interface IConnectionFactory {
/**
* Creates connection using the host and port
- * @param host The host to connect to
- * @param port The port to connect to
- * @return The created connection
- * @throws IOException On an IO Error
- * @throws UnknownHostException If the host can't be resolved
+ *
+ * @param host The host to connect to
+ * @param port The port to connect to
+ * @return The created connection
+ * @throws IOException On an IO Error
+ * @throws UnknownHostException If the host can't be resolved
*/
public IConnection create(String host, int port)
- throws IOException, UnknownHostException;
+ throws IOException, UnknownHostException;
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/common/ConfigConstants.java b/pki/base/common/src/com/netscape/certsrv/common/ConfigConstants.java
index 9f892cd2..65c170ee 100644
--- a/pki/base/common/src/com/netscape/certsrv/common/ConfigConstants.java
+++ b/pki/base/common/src/com/netscape/certsrv/common/ConfigConstants.java
@@ -17,12 +17,10 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.common;
-
/**
- * This interface contains constants that are used
- * in the protocol between the configuration daemon
- * and UI configuration wizard.
- *
+ * This interface contains constants that are used in the protocol between the
+ * configuration daemon and UI configuration wizard.
+ *
* @version $Revision$, $Date$
*/
public interface ConfigConstants {
@@ -30,8 +28,8 @@ public interface ConfigConstants {
public static final String TRUE = "true";
public static final String FALSE = "false";
public static final String OPTYPE = "opType";
- public static final String TASKID = "taskID";
-
+ public static final String TASKID = "taskID";
+
// Stages
public static final String STAGES = "stages";
public static final String STAGE_INTERNAL_DB = "stageInternalDB";
@@ -135,7 +133,7 @@ public interface ConfigConstants {
public static final String PR_EE_SECURE_PORT = "eeGateway.https.port";
public static final String PR_AGENT_PORT = "agentGateway.https.port";
public static final String PR_RADM_PORT = "radm.https.port";
- public static final String PR_RADM_PORT_SETUP="radm.port";
+ public static final String PR_RADM_PORT_SETUP = "radm.port";
public static final String PR_EE_PORT_ENABLE = "eeGateway.http.enable";
public static final String PR_EE_PORTS_ENABLE = "eePortsEnable";
@@ -173,27 +171,27 @@ public interface ConfigConstants {
public static final String PR_ADD_LDIF_PATH = "addLdifPath";
public static final String PR_MOD_LDIF_PATH = "modLdifPath";
public static final String PR_SIGNING_KEY_MIGRATION_TOKEN =
- "signingKeyMigrationToken";
+ "signingKeyMigrationToken";
public static final String PR_SSL_KEY_MIGRATION_TOKEN =
- "sslKeyMigrationToken";
+ "sslKeyMigrationToken";
public static final String PR_SIGNING_KEY_MIGRATION_TOKEN_PASSWD =
- "signingKeyMigrationTokenPasswd";
+ "signingKeyMigrationTokenPasswd";
public static final String PR_SIGNING_KEY_MIGRATION_TOKEN_SOPPASSWD =
- "signingKeyMigrationTokenSOPPasswd";
+ "signingKeyMigrationTokenSOPPasswd";
public static final String PR_SSL_KEY_MIGRATION_TOKEN_PASSWD =
- "sslKeyMigrationTokenPasswd";
+ "sslKeyMigrationTokenPasswd";
public static final String PR_SSL_KEY_MIGRATION_TOKEN_SOPPASSWD =
- "sslKeyMigrationTokenSOPPasswd";
+ "sslKeyMigrationTokenSOPPasswd";
public static final String PR_NUM_MIGRATION_WARNINGS =
- "numMigrationWarnings";
+ "numMigrationWarnings";
public static final String PR_MIGRATION_WARNING = "migrationWarning";
public static final String PR_CA_KEY_TYPE = "caKeyType";
public static final String PR_LDAP_PASSWORD = "ldapPassword";
public static final String PR_MIGRATION_PASSWORD = "migrationPassword";
// Key and Cert
- public static final String PR_HARDWARE_SPLIT = "hardwareSplit";
- public static final String PR_TOKEN_LIST = "tokenList";
+ public static final String PR_HARDWARE_SPLIT = "hardwareSplit";
+ public static final String PR_TOKEN_LIST = "tokenList";
public static final String PR_TOKEN_NAME = "tokenName";
public static final String PR_SUBJECT_NAME = "subjectName";
public static final String PR_CA_SUBJECT_NAME = "caSubjectName";
@@ -269,7 +267,7 @@ public interface ConfigConstants {
public static final String PR_RA_TOKEN = "raToken";
public static final String PR_KRA_TOKEN = "kraToken";
public static final String PR_SSL_TOKEN = "sslToken";
- //public static final String PR_SUBSYSTEMS = "subsystems";
+ // public static final String PR_SUBSYSTEMS = "subsystems";
// Key Length
public static final String PR_RSA_MIN_KEYLENGTH = "RSAMinKeyLength";
@@ -293,8 +291,8 @@ public interface ConfigConstants {
// CA serial number
public static final String PR_CA_SERIAL_NUMBER = "caSerialNumber";
public static final String PR_CA_ENDSERIAL_NUMBER = "caEndSerialNumber";
-
- // KRA number
+
+ // KRA number
public static final String PR_REQUEST_NUMBER = "requestNumber";
public static final String PR_ENDREQUEST_NUMBER = "endRequestNumber";
public static final String PR_SERIAL_REQUEST_NUMBER = "serialRequestNumber";
@@ -331,4 +329,3 @@ public interface ConfigConstants {
public static final String PR_AGREEMENT_NAME_2 = "agreementName2";
public static final String PR_REPLICATION_MANAGER_PASSWD_2 = "replicationManagerPwd2";
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/common/Constants.java b/pki/base/common/src/com/netscape/certsrv/common/Constants.java
index c8503491..e2f5c5af 100644
--- a/pki/base/common/src/com/netscape/certsrv/common/Constants.java
+++ b/pki/base/common/src/com/netscape/certsrv/common/Constants.java
@@ -17,18 +17,18 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.common;
-
/**
- * This interface contains constants that are shared
- * by certificate server and its client SDK.
- *
+ * This interface contains constants that are shared by certificate server and
+ * its client SDK.
+ *
* @version $Revision$, $Date$
*/
public interface Constants {
- /*=======================================================
- * MESSAGE FORMAT CONSTANTS
- *=======================================================*/
+ /*
+ * ======================================================= MESSAGE FORMAT
+ * CONSTANTS=======================================================
+ */
public static final String PASSWORDTYPE = "PasswordField";
public static final String TEXTTYPE = "TextField";
public static final String CHECKBOXTYPE = "CheckBox";
@@ -41,34 +41,37 @@ public interface Constants {
public final static String OP_TYPE = "OP_TYPE";
public final static String OP_SCOPE = "OP_SCOPE";
- //STATIC RESOURCE IDENTIFIERS
+ // STATIC RESOURCE IDENTIFIERS
public final static String RS_ID = "RS_ID";
public final static String RS_ID_CONFIG = "RS_ID_CONFIG";
public final static String RS_ID_ORDER = "RS_ID_ORDER";
- //STATIC UI TYPE
+ // STATIC UI TYPE
public final static String TYPE_PASSWORD = "password";
-
+
/**********************************************************
* PROPERTY NAME LISTED BELOW
**********************************************************/
-
- /*========================================================
- * General
- *========================================================*/
+
+ /*
+ * ======================================================== General
+ * ========================================================
+ */
public final static String PR_PORT = "port";
public final static String PR_SSLPORT = "sslPort";
-
- /*========================================================
- * Tasks
- *========================================================*/
+
+ /*
+ * ======================================================== Tasks
+ * ========================================================
+ */
public final static String PR_SERVER_START = "start";
public final static String PR_SERVER_STOP = "stop";
public final static String PR_SERVER_RESTART = "restart";
-
- /*========================================================
- * Networks
- *========================================================*/
+
+ /*
+ * ======================================================== Networks
+ * ========================================================
+ */
public final static String PR_ADMIN_S_PORT = "admin.https.port";
public final static String PR_AGENT_S_PORT = "agent.https.port";
public final static String PR_GATEWAY_S_PORT = "gateway.https.port";
@@ -79,18 +82,20 @@ public interface Constants {
public final static String PR_GATEWAY_S_BACKLOG = "gateway.https.backlog";
public final static String PR_GATEWAY_BACKLOG = "gateway.http.backlog";
public final static String PR_GATEWAY_PORT_ENABLED =
- "gateway.http.enable";
+ "gateway.http.enable";
public final static String PR_MASTER_AGENT_PORT = "master.ca.agent.port";
public final static String PR_MASTER_AGENT_HOST = "master.ca.agent.host";
-
- /*========================================================
- * SMTP
- *========================================================*/
+
+ /*
+ * ======================================================== SMTP
+ * ========================================================
+ */
public final static String PR_SERVER_NAME = "server";
-
- /*========================================================
- * SNMP
- *========================================================*/
+
+ /*
+ * ======================================================== SNMP
+ * ========================================================
+ */
public final static String PR_SNMP_ENABLED = "on";
public final static String PR_SNMP_MASTER_HOST = "master.host";
public final static String PR_SNMP_MASTER_PORT = "master.port";
@@ -99,23 +104,25 @@ public interface Constants {
public final static String PR_SNMP_LOC = "loc";
public final static String PR_SNMP_CONTACT = "contact";
- /*========================================================
- * Self Tests
- *========================================================*/
+ /*
+ * ======================================================== Self Tests
+ * ========================================================
+ */
public final static String PR_RUN_SELFTESTS_ON_DEMAND = "run";
public final static String PR_RUN_SELFTESTS_ON_DEMAND_CLASS = "class";
public final static String PR_RUN_SELFTESTS_ON_DEMAND_CONTENT = "runContent";
- /*========================================================
- * Users and Groups
- *========================================================*/
-
- //group properties
+ /*
+ * ======================================================== Users and Groups
+ * ========================================================
+ */
+
+ // group properties
public final static String PR_GROUP_DESC = "desc";
public final static String PR_GROUP_USER = "user";
public final static String PR_GROUP_GROUP = "group";
- //user properties
+ // user properties
public final static String PR_USER_FULLNAME = "fullname";
public final static String PR_USER_PASSWORD = "password";
public final static String PR_USER_EMAIL = "email";
@@ -125,9 +132,10 @@ public interface Constants {
public final static String PR_USER_GROUP = "groups";
public final static String PR_MULTIROLES = "multiroles";
- /*========================================================
- * Authentication
- *========================================================*/
+ /*
+ * ======================================================== Authentication
+ * ========================================================
+ */
public final static String PR_PING = "ping";
public final static String PR_AUTH_CLASS = "class";
public final static String PR_AUTH_IMPL_NAME = "implName";
@@ -137,25 +145,28 @@ public interface Constants {
public final static String PR_AUTH_ADMIN_DN = "ldapauth.bindDN";
public final static String PR_AUTH_ADMIN_PWD = "ldapauth.bindPassword";
- /*========================================================
- * Job Scheduler
- *========================================================*/
+ /*
+ * ======================================================== Job Scheduler
+ * ========================================================
+ */
public final static String PR_JOBS_CLASS = "class";
public final static String PR_JOBS_IMPL_NAME = "implName";
public final static String PR_JOBS_FREQUENCY = "frequency";
- /*========================================================
- * Notification
- *========================================================*/
+ /*
+ * ======================================================== Notification
+ * ========================================================
+ */
public final static String PR_NOTIFICATION_FORM_NAME = "emailTemplate";
public final static String PR_NOTIFICATION_SUBJECT =
- "emailSubject";
+ "emailSubject";
public final static String PR_NOTIFICATION_SENDER = "senderEmail";
public final static String PR_NOTIFICATION_RECEIVER = "recipientEmail";
- /*========================================================
- * Logs
- *========================================================*/
+ /*
+ * ======================================================== Logs
+ * ========================================================
+ */
public static final String PR_LOG_IMPL_NAME = "implName";
public static final String PR_EXT_PLUGIN_IMPLTYPE_LOG = "log";
public final static String PR_LOG_CLASS = "class";
@@ -191,10 +202,11 @@ public interface Constants {
public static final String PR_DEBUG_LOG_ENABLE = "debug.enabled";
public static final String PR_DEBUG_LOG_LEVEL = "debug.level";
- /*========================================================
- * LDAP Publishing
- *========================================================*/
-
+ /*
+ * ======================================================== LDAP Publishing
+ * ========================================================
+ */
+
// publishing properties
public final static String PR_BASIC_AUTH = "BasicAuth";
public final static String PR_SSL_AUTH = "SslClientAuth";
@@ -253,7 +265,7 @@ public interface Constants {
public final static String PR_BASE_DN = "baseDN";
public final static String PR_DNCOMPS = "dnComps";
public final static String PR_FILTERCOMPS = "filterComps";
-
+
// ldap connection test
public final static String PR_CONN_INITED = "connInited";
public final static String PR_CONN_INIT_FAIL = "connInitFail";
@@ -264,15 +276,17 @@ public interface Constants {
public final static String PR_SAVE_OK = "saveOk";
public final static String PR_SAVE_NOT = "saveOrNot";
- /*========================================================
- * Plugin
- *========================================================*/
+ /*
+ * ======================================================== Plugin
+ * ========================================================
+ */
public final static String PR_PLUGIN_IMP = "imp";
public final static String PR_PLUGIN_INSTANCE = "instance";
- /*========================================================
- * Policy
- *========================================================*/
+ /*
+ * ======================================================== Policy
+ * ========================================================
+ */
public final static String PR_POLICY_CLASS = "class";
public final static String PR_POLICY_IMPL_NAME = "implName";
public final static String PR_CRLDP_NAME = "crldpName";
@@ -281,9 +295,10 @@ public interface Constants {
public final static String PR_POLICY_ENABLE = "enable";
public final static String PR_POLICY_PREDICATE = "predicate";
- /*========================================================
- * Publish
- *========================================================*/
+ /*
+ * ======================================================== Publish
+ * ========================================================
+ */
public final static String PR_PUBLISHER = "publisher";
public final static String PR_PUBLISHER_CLASS = "class";
public final static String PR_PUBLISHER_IMPL_NAME = "implName";
@@ -314,19 +329,20 @@ public interface Constants {
public final static String PR_OCSPSTORE_IMPL_NAME = "implName";
- /*========================================================
- * Registration Authority
- *========================================================*/
+ /*
+ * ======================================================== Registration
+ * Authority========================================================
+ */
public final static String PR_EE_ENABLED = "eeEnabled";
public final static String PR_OCSP_ENABLED = "ocspEnabled";
public final static String PR_RA_ENABLED = "raEnabled";
public final static String PR_RENEWAL_ENABLED = "renewal.enabled";
public final static String PR_RENEWAL_VALIDITY = "renewal.validity";
public final static String PR_RENEWAL_EMAIL = "renewal.email";
- public final static String PR_RENEWAL_EXPIREDNOTIFIEDENABLED =
- "renewal.expired.notification.enabled";
- public final static String PR_RENEWAL_NUMNOTIFICATION =
- "renewal.numNotification";
+ public final static String PR_RENEWAL_EXPIREDNOTIFIEDENABLED =
+ "renewal.expired.notification.enabled";
+ public final static String PR_RENEWAL_NUMNOTIFICATION =
+ "renewal.numNotification";
public final static String PR_RENEWAL_INTERVAL = "renewal.interval";
public final static String PR_SERVLET_CLASS = "class";
public final static String PR_SERVLET_URI = "uri";
@@ -337,27 +353,30 @@ public interface Constants {
public final static String PR_URI = "uri";
public final static String PR_ENABLED = "enable";
- /*========================================================
- * Certificate Authority
- *========================================================*/
+ /*
+ * ======================================================== Certificate
+ * Authority========================================================
+ */
public final static String PR_VALIDITY = "validity";
public final static String PR_DEFAULT_ALGORITHM = "defaultSigningAlgorithm";
public final static String PR_ALL_ALGORITHMS = "allSigningAlgorithms";
public final static String PR_SERIAL = "startSerialNumber";
public final static String PR_MAXSERIAL = "maxSerialNumber";
- /*========================================================
- * Access Control
- *========================================================*/
+ /*
+ * ======================================================== Access Control
+ * ========================================================
+ */
public final static String PR_ACL_OPS = "aclOperations";
public final static String PR_ACI = "aci";
public final static String PR_ACL_CLASS = "class";
public final static String PR_ACL_DESC = "desc";
public final static String PR_ACL_RIGHTS = "rights";
-
- /*========================================================
- * Key Recovery
- *========================================================*/
+
+ /*
+ * ======================================================== Key Recovery
+ * ========================================================
+ */
public final static String PR_AUTO_RECOVERY_ON = "autoRecoveryOn";
public final static String PR_RECOVERY_N = "recoveryN";
public final static String PR_RECOVERY_M = "recoveryM";
@@ -367,18 +386,20 @@ public interface Constants {
public final static String PR_AGENT_PWD = "agentPwd";
public final static String PR_NO_OF_REQUIRED_RECOVERY_AGENTS = "noOfRequiredRecoveryAgents";
- /*========================================================
- * Status
- *========================================================*/
+ /*
+ * ======================================================== Status
+ * ========================================================
+ */
public final static String PR_STAT_STARTUP = "startup";
public final static String PR_STAT_TIME = "time";
public final static String PR_STAT_VERSION = "cms.version";
public final static String PR_STAT_INSTALLDATE = "installDate";
public final static String PR_STAT_INSTANCEID = "instanceId";
- /*========================================================
- * Server Instance
- *========================================================*/
+ /*
+ * ======================================================== Server Instance
+ * ========================================================
+ */
public final static String PR_INSTALL = "install";
public final static String PR_INSTANCES_INSTALL = "instancesInstall";
public final static String PR_CA_INSTANCE = "ca";
@@ -386,7 +407,7 @@ public interface Constants {
public final static String PR_RA_INSTANCE = "ra";
public final static String PR_KRA_INSTANCE = "kra";
public final static String PR_TKS_INSTANCE = "tks";
-
+
/*
* Certificate info
*/
@@ -464,11 +485,12 @@ public interface Constants {
*/
public final static String PR_TRUST = "trust";
- /*========================================================
- * Security
- *========================================================*/
-
- //functionality
+ /*
+ * ======================================================== Security
+ * ========================================================
+ */
+
+ // functionality
public final static String PR_CERT_SERVER = "SERVER";
public final static String PR_CERT_ADMIN = "ADMIN";
public final static String PR_CERT_AGENT = "AGENT";
@@ -477,17 +499,17 @@ public interface Constants {
public final static String PR_CERT_RA = "RA";
public final static String PR_CERT_POA = "POA";
public final static String PR_CERT_TRANS = "TRANS";
-
+
// key and certificate management
public final static String PR_OPERATION_TYPE = "operationtype";
public final static String PR_INSTALL_TYPE = "install";
public final static String PR_REQUEST_TYPE = "request";
- //public final static String PR_CA_SIGNING_CERT = "cacert";
- //public final static String PR_SERVER_CERT = "servercert";
+ // public final static String PR_CA_SIGNING_CERT = "cacert";
+ // public final static String PR_SERVER_CERT = "servercert";
public final static String PR_CLIENT_CERT = "clientcert";
- public final static String PR_FULL_INTERNAL_TOKEN_NAME="Internal Key Storage Token";
- public final static String PR_INTERNAL_TOKEN_NAME =
- "internal";
+ public final static String PR_FULL_INTERNAL_TOKEN_NAME = "Internal Key Storage Token";
+ public final static String PR_INTERNAL_TOKEN_NAME =
+ "internal";
public final static String PR_TOKEN_NAME = "tokenName";
public final static String PR_TOKEN_PASSWD = "tokenPwd";
public final static String PR_KEY_LENGTH = "keyLength";
@@ -502,16 +524,16 @@ public interface Constants {
public final static String PR_SUBJECT_NAME = "subjectName";
public final static String PR_CSR = "csr";
- //encryption
-
+ // encryption
+
/* Cipher Version: domestic or export */
public final static String PR_CIPHER_VERSION = "cipherversion";
public final static String PR_CIPHER_VERSION_DOMESTIC = "cipherdomestic";
public final static String PR_CIPHER_VERSION_EXPORT = "cipherexport";
-
+
/* Cipher Fortezza: true, false */
public final static String PR_CIPHER_FORTEZZA = "cipherfortezza";
-
+
/* Token and Certificates */
public final static String PR_TOKEN_LIST = "tokenlist";
public final static String PR_TOKEN_PREFIX = "token_";
@@ -525,46 +547,30 @@ public interface Constants {
public final static String PR_ECTYPE = "ectype";
/* values for SSL cipher preferences */
- public final static String
- PR_SSL2_RC4_128_WITH_MD5 = "rc4";
- public final static String
- PR_SSL2_RC4_128_EXPORT40_WITH_MD5 = "rc4export";
- public final static String
- PR_SSL2_RC2_128_CBC_WITH_MD5 = "rc2";
- public final static String
- PR_SSL2_RC2_128_CBC_EXPORT40_WITH_MD5 = "rc2export";
- public final static String
- PR_SSL2_DES_64_CBC_WITH_MD5 = "des";
- public final static String
- PR_SSL2_DES_192_EDE3_CBC_WITH_MD5 = "desede3";
- public final static String
- PR_SSL3_RSA_WITH_NULL_MD5 = "rsa_null_md5";
- public final static String
- PR_SSL3_RSA_EXPORT_WITH_RC4_40_MD5 = "rsa_rc4_40_md5";
- public final static String
- PR_SSL3_RSA_WITH_RC4_128_MD5 = "rsa_rc4_128_md5";
- public final static String
- PR_SSL3_RSA_EXPORT_WITH_RC2_CBC_40_MD5 = "rsa_rc2_40_md5";
- public final static String
- PR_SSL3_RSA_WITH_DES_CBC_SHA = "rsa_des_sha";
- public final static String
- PR_SSL3_RSA_WITH_3DES_EDE_CBC_SHA = "rsa_3des_sha";
- public final static String
- PR_SSL3_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA = "fortezza";
- public final static String
- PR_SSL3_FORTEZZA_DMS_WITH_RC4_128_SHA = "fortezza_rc4_128_sha";
- public final static String
- PR_SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA = "rsa_fips_3des_sha";
- public final static String
- PR_SSL_RSA_FIPS_WITH_DES_CBC_SHA = "rsa_fips_des_sha";
- public final static String
- PR_TLS_RSA_EXPORT1024_WITH_RC4_56_SHA = "tls_rsa_rc4_56_sha";
- public final static String
- PR_TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA = "tls_rsa_des_sha";
-
- /*========================================================
- * Watchdog and Server State Messages
- *========================================================*/
+ public final static String PR_SSL2_RC4_128_WITH_MD5 = "rc4";
+ public final static String PR_SSL2_RC4_128_EXPORT40_WITH_MD5 = "rc4export";
+ public final static String PR_SSL2_RC2_128_CBC_WITH_MD5 = "rc2";
+ public final static String PR_SSL2_RC2_128_CBC_EXPORT40_WITH_MD5 = "rc2export";
+ public final static String PR_SSL2_DES_64_CBC_WITH_MD5 = "des";
+ public final static String PR_SSL2_DES_192_EDE3_CBC_WITH_MD5 = "desede3";
+ public final static String PR_SSL3_RSA_WITH_NULL_MD5 = "rsa_null_md5";
+ public final static String PR_SSL3_RSA_EXPORT_WITH_RC4_40_MD5 = "rsa_rc4_40_md5";
+ public final static String PR_SSL3_RSA_WITH_RC4_128_MD5 = "rsa_rc4_128_md5";
+ public final static String PR_SSL3_RSA_EXPORT_WITH_RC2_CBC_40_MD5 = "rsa_rc2_40_md5";
+ public final static String PR_SSL3_RSA_WITH_DES_CBC_SHA = "rsa_des_sha";
+ public final static String PR_SSL3_RSA_WITH_3DES_EDE_CBC_SHA = "rsa_3des_sha";
+ public final static String PR_SSL3_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA = "fortezza";
+ public final static String PR_SSL3_FORTEZZA_DMS_WITH_RC4_128_SHA = "fortezza_rc4_128_sha";
+ public final static String PR_SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA = "rsa_fips_3des_sha";
+ public final static String PR_SSL_RSA_FIPS_WITH_DES_CBC_SHA = "rsa_fips_des_sha";
+ public final static String PR_TLS_RSA_EXPORT1024_WITH_RC4_56_SHA = "tls_rsa_rc4_56_sha";
+ public final static String PR_TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA = "tls_rsa_des_sha";
+
+ /*
+ * ======================================================== Watchdog and
+ * Server State Messages
+ * ========================================================
+ */
public final static String SERVER_STARTUP_WARNING_MESSAGE = "CMS Warning: ";
public final static String SERVER_STARTUP_MESSAGE = "Server is started.";
@@ -572,9 +578,11 @@ public interface Constants {
public final static String SERVER_SHUTDOWN_ERROR_MESSAGE = "Error Starting CMS: ";
public final static String SERVER_SHUTDOWN_EXTENDED_ERROR_MESSAGE = "Extended error information: ";
- /*============================================================
- * THE FOLLOWING LIST WILL BE REMOVED
- *============================================================*/
+ /*
+ * ============================================================ THE
+ * FOLLOWING LIST WILL BE REMOVED
+ * ============================================================
+ */
// parameter types
public final static String PT_OP = "op";
@@ -599,9 +607,9 @@ public interface Constants {
public final static String PT_DN = "dn";
public final static String PV_SYSTEM_ADMINISTRATORS =
- "SystemAdministrators";
+ "SystemAdministrators";
public final static String PV_CERTIFICATE_ADMINISTRATORS =
- "CertificateAdministrators";
+ "CertificateAdministrators";
public final static String OP_AUTHENTICATE = "authenticate";
public final static String OP_RESTART = "restart";
@@ -636,9 +644,9 @@ public interface Constants {
// certificate authority operations
public final static String PT_PUBLISH_DN = "ldappublish.ldap.admin-dn";
public final static String PT_PUBLISH_PWD =
- "ldappublish.ldap.admin-password";
+ "ldappublish.ldap.admin-password";
public final static String PT_PUBLISH_FREQ =
- "crl.crl0.autoUpdateInterval";
+ "crl.crl0.autoUpdateInterval";
public final static String PT_SERIALNO = "serialno";
public final static String PT_NAMES = "names";
public final static String PT_CERTIFICATES = "certificates";
@@ -732,10 +740,10 @@ public interface Constants {
public final static String PR_REQUEST_SVC_PENDING = "4";
public final static String PR_REQUEST_REJECTED = "5";
- //Profile
+ // Profile
public final static String PR_CONSTRAINTS_LIST = "constraintPolicy";
- //Replication
+ // Replication
public final static String PR_REPLICATION_ENABLED = "replication.enabled";
public final static String PR_REPLICATION_AGREEMENT_NAME_1 = "replication.master1.name";
public final static String PR_REPLICATION_HOST_1 = "replication.master1.hostname";
diff --git a/pki/base/common/src/com/netscape/certsrv/common/DestDef.java b/pki/base/common/src/com/netscape/certsrv/common/DestDef.java
index 1d3eaff1..5c90d307 100644
--- a/pki/base/common/src/com/netscape/certsrv/common/DestDef.java
+++ b/pki/base/common/src/com/netscape/certsrv/common/DestDef.java
@@ -17,12 +17,10 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.common;
-
/**
- * This interface defines all the operation destination
- * used in the administration protocol between the
- * console and the server.
- *
+ * This interface defines all the operation destination used in the
+ * administration protocol between the console and the server.
+ *
* @version $Revision$, $Date$
*/
public interface DestDef {
diff --git a/pki/base/common/src/com/netscape/certsrv/common/NameValuePair.java b/pki/base/common/src/com/netscape/certsrv/common/NameValuePair.java
index 44d55e32..1e513c30 100644
--- a/pki/base/common/src/com/netscape/certsrv/common/NameValuePair.java
+++ b/pki/base/common/src/com/netscape/certsrv/common/NameValuePair.java
@@ -17,13 +17,10 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.common;
-
-
-
/**
- * A class represents a name value pair. A name value
- * pair consists of a name and a value.
- *
+ * A class represents a name value pair. A name value pair consists of a name
+ * and a value.
+ *
* @version $Revision$, $Date$
*/
public class NameValuePair {
@@ -33,7 +30,7 @@ public class NameValuePair {
/**
* Constructs value pair object.
- *
+ *
* @param name name
* @param value value
*/
@@ -44,7 +41,7 @@ public class NameValuePair {
/**
* Retrieves the name.
- *
+ *
* @return name
*/
public String getName() {
@@ -53,19 +50,19 @@ public class NameValuePair {
/**
* Retrieves the value.
- *
+ *
* @return value
*/
public String getValue() {
return mValue;
}
-
+
/**
* Sets the value
- *
+ *
* @param value value
*/
public void setValue(String value) {
mValue = value;
}
-}
+}
diff --git a/pki/base/common/src/com/netscape/certsrv/common/NameValuePairs.java b/pki/base/common/src/com/netscape/certsrv/common/NameValuePairs.java
index 651de782..f175a8de 100644
--- a/pki/base/common/src/com/netscape/certsrv/common/NameValuePairs.java
+++ b/pki/base/common/src/com/netscape/certsrv/common/NameValuePairs.java
@@ -17,17 +17,14 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.common;
-
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.Vector;
-
/**
- * A class represents an ordered list of name
- * value pairs.
- *
+ * A class represents an ordered list of name value pairs.
+ *
* @version $Revision$, $Date$
*/
public class NameValuePairs {
@@ -35,20 +32,19 @@ public class NameValuePairs {
private Vector<NameValuePair> mPairs = new Vector<NameValuePair>();
// an index to speed up searching
- // The key is the name. The element is the NameValuePair.
+ // The key is the name. The element is the NameValuePair.
private Hashtable<String, NameValuePair> index = new Hashtable<String, NameValuePair>();
/**
* Constructs name value pairs.
- */
+ */
public NameValuePairs() {
}
/**
- * Adds a name value pair into this set.
- * if the name already exist, the value will
- * be replaced.
- *
+ * Adds a name value pair into this set. if the name already exist, the
+ * value will be replaced.
+ *
* @param name name
* @param value value
*/
@@ -66,7 +62,7 @@ public class NameValuePairs {
/**
* Retrieves name value pair from this set.
- *
+ *
* @param name name
* @return name value pair
*/
@@ -76,7 +72,7 @@ public class NameValuePairs {
/**
* Returns number of pairs in this set.
- *
+ *
* @return size
*/
public int size() {
@@ -85,7 +81,7 @@ public class NameValuePairs {
/**
* Retrieves name value pairs in specific position.
- *
+ *
* @param pos position of the value
* @return name value pair
*/
@@ -102,9 +98,8 @@ public class NameValuePairs {
}
/**
- * Retrieves value of the name value pairs that matches
- * the given name.
- *
+ * Retrieves value of the name value pairs that matches the given name.
+ *
* @param name name
* @return value
*/
@@ -119,26 +114,25 @@ public class NameValuePairs {
/**
* Retrieves a list of names.
- *
+ *
* @return a list of names
*/
public Enumeration<String> getNames() {
Vector<String> v = new Vector<String>();
- int size = mPairs.size();
+ int size = mPairs.size();
- for (int i = 0; i < size; i++) {
+ for (int i = 0; i < size; i++) {
NameValuePair p = (NameValuePair) mPairs.elementAt(i);
v.addElement(p.getName());
}
- //System.out.println("getNames: "+v.size());
+ // System.out.println("getNames: "+v.size());
return v.elements();
}
-
+
/**
- * Show the content of this name value container as
- * string representation.
- *
+ * Show the content of this name value container as string representation.
+ *
* @return string representation
*/
public String toString() {
@@ -155,7 +149,7 @@ public class NameValuePairs {
/**
* Parses a string into name value pairs.
- *
+ *
* @param s string
* @param nvp name value pairs
* @return true if successful
@@ -174,16 +168,16 @@ public class NameValuePairs {
String v = t.substring(i + 1);
nvp.add(n, v);
- }
+ }
return true;
}
/**
* Returns a list of name value pair object.
- *
+ *
* @return name value objects
*/
public Enumeration<NameValuePair> elements() {
return mPairs.elements();
}
-}
+}
diff --git a/pki/base/common/src/com/netscape/certsrv/common/OpDef.java b/pki/base/common/src/com/netscape/certsrv/common/OpDef.java
index 9cfcab4a..6b6b3a1b 100644
--- a/pki/base/common/src/com/netscape/certsrv/common/OpDef.java
+++ b/pki/base/common/src/com/netscape/certsrv/common/OpDef.java
@@ -17,12 +17,10 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.common;
-
/**
- * This interface defines all the administration operations
- * used in the administration protocol between the console
- * and the server.
- *
+ * This interface defines all the administration operations used in the
+ * administration protocol between the console and the server.
+ *
* @version $Revision$, $Date$
*/
public interface OpDef {
diff --git a/pki/base/common/src/com/netscape/certsrv/common/PrefixDef.java b/pki/base/common/src/com/netscape/certsrv/common/PrefixDef.java
index 11a58c5d..405544ab 100644
--- a/pki/base/common/src/com/netscape/certsrv/common/PrefixDef.java
+++ b/pki/base/common/src/com/netscape/certsrv/common/PrefixDef.java
@@ -17,25 +17,23 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.common;
-
/**
- * This interface defines all the prefix tags
- * used in the administration protocol between
- * the console and the server.
- *
+ * This interface defines all the prefix tags used in the administration
+ * protocol between the console and the server.
+ *
* @version $Revision$, $Date$
*/
public interface PrefixDef {
- //user and group
+ // user and group
public final static String PX_GROUP = "group";
public final static String PX_USER = "user";
public final static String PX_CERT = "cert";
public final static String PX_SYS = "SYS_";
public final static String PX_DEF = "DEF_";
public final static String PX_PP = "CERT_PP";
-
- //log content
+
+ // log content
public final static String PX_LOG = "log";
-
+
}
diff --git a/pki/base/common/src/com/netscape/certsrv/common/ScopeDef.java b/pki/base/common/src/com/netscape/certsrv/common/ScopeDef.java
index 0be3fdf0..0c8053d0 100644
--- a/pki/base/common/src/com/netscape/certsrv/common/ScopeDef.java
+++ b/pki/base/common/src/com/netscape/certsrv/common/ScopeDef.java
@@ -17,12 +17,10 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.common;
-
/**
- * This interface defines all the operation scope
- * used in the administration protocol between the
- * console and the server.
- *
+ * This interface defines all the operation scope used in the administration
+ * protocol between the console and the server.
+ *
* @version $Revision$, $Date$
*/
public interface ScopeDef {
@@ -31,7 +29,7 @@ public interface ScopeDef {
public final static String SC_GROUPS = "groups";
public final static String SC_USERS = "users";
public final static String SC_USER_CERTS = "certs";
-
+
public final static String SC_SNMP = "snmp";
public final static String SC_SMTP = "smtp";
public final static String SC_SUBSYSTEM = "subsystem";
@@ -39,12 +37,12 @@ public interface ScopeDef {
public final static String SC_GATEWAY = "gateway";
public final static String SC_ADMIN = "admin";
public final static String SC_NETWORK = "network";
-
+
// profile
public final static String SC_PROFILE_IMPLS = "profile";
public final static String SC_PROFILE_RULES = "rules";
public final static String SC_PROFILE_DEFAULT_POLICY = "defaultPolicy";
- public final static String SC_PROFILE_CONSTRAINT_POLICY = "constraintPolicy";
+ public final static String SC_PROFILE_CONSTRAINT_POLICY = "constraintPolicy";
public final static String SC_PROFILE_POLICIES = "policies";
public final static String SC_PROFILE_POLICY_CONFIG = "config";
public final static String SC_PROFILE_INPUT = "profileInput";
@@ -83,9 +81,9 @@ public interface ScopeDef {
public final static String SC_LOG_CONTENT = "log_content";
public final static String SC_AUDITLOG_CONTENT = "transactionsLog_content";
public final static String SC_ERRORLOG_CONTENT = "errorLog_content";
- public final static String SC_SYSTEMLOG_CONTENT = "systemLog_content";
+ public final static String SC_SYSTEMLOG_CONTENT = "systemLog_content";
- //LDAP publishing
+ // LDAP publishing
public final static String SC_LDAP = "ldap";
public final static String SC_CRL = "crl";
public final static String SC_USERCERT = "userCert";
@@ -109,9 +107,9 @@ public interface ScopeDef {
public final static String SC_RECOVERY = "recovery";
public final static String SC_AGENT_PWD = "agentPwd";
public final static String SC_MNSCHEME = "mnScheme";
-
- //stat
- public final static String SC_STAT = "stat";
+
+ // stat
+ public final static String SC_STAT = "stat";
// RA
public final static String SC_GENERAL = "general";
@@ -119,27 +117,27 @@ public interface ScopeDef {
public final static String SC_PKIGW = "pkigw";
public final static String SC_SERVLET = "servlet";
public final static String SC_CONNECTOR = "connector";
-
- //tasks
+
+ // tasks
public final static String SC_TASKS = "tasks";
-
- //authentication
+
+ // authentication
public final static String SC_AUTH = "auths";
public final static String SC_AUTHTYPE = "authType";
public final static String SC_AUTH_IMPLS = "impl";
public final static String SC_AUTH_MGR_INSTANCE = "instance";
- //jobs scheduler
+ // jobs scheduler
public final static String SC_JOBS = "jobScheduler";
public final static String SC_JOBS_IMPLS = "impl";
public final static String SC_JOBS_INSTANCE = "job";
public final static String SC_JOBS_RULES = "rules";
- //notification
+ // notification
public final static String SC_NOTIFICATION_REQ_COMP = "notificationREQC";
public final static String SC_NOTIFICATION_REV_COMP = "notificationREVC";
public final static String SC_NOTIFICATION_RIQ = "notificationRIQ";
-
+
// acl
public final static String SC_ACL_IMPLS = "impl";
public final static String SC_ACL = "acls";
@@ -181,7 +179,7 @@ public interface ScopeDef {
public final static String SC_PLATFORM = "platform";
public final static String SC_GET_NICKNAMES = "getNicknames";
-
+
// Profile
public final static String SC_SUPPORTED_CONSTRAINTPOLICIES = "supportedConstraintPolicies";
diff --git a/pki/base/common/src/com/netscape/certsrv/common/TaskId.java b/pki/base/common/src/com/netscape/certsrv/common/TaskId.java
index 458822ff..1f5c5213 100644
--- a/pki/base/common/src/com/netscape/certsrv/common/TaskId.java
+++ b/pki/base/common/src/com/netscape/certsrv/common/TaskId.java
@@ -17,13 +17,10 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.common;
-
/**
- * This interface defines all the tasks used in
- * the configuration protocol between the
- * configuration wizard and the configuration
- * daemon.
- *
+ * This interface defines all the tasks used in the configuration protocol
+ * between the configuration wizard and the configuration daemon.
+ *
* @version $Revision$, $Date$
*/
public interface TaskId {
@@ -66,7 +63,7 @@ public interface TaskId {
// get information about all cryptotokens
public final static String TASK_TOKEN_INFO = "tokenInfo";
-
+
// server get master or clone setting
public final static String TASK_MASTER_OR_CLONE = "SetMasterOrClone";
// single signon
@@ -100,17 +97,18 @@ public interface TaskId {
// set CA starting serial number
public final static String TASK_SET_CA_SERIAL = "setCASerial";
- // set CA starting serial number
+ // set CA starting serial number
public final static String TASK_SET_KRA_NUMBER = "setKRANumber";
- // check key length
+ // check key length
public final static String TASK_CHECK_KEYLENGTH = "checkKeyLength";
// check certificate extension
public final static String TASK_CHECK_EXTENSION = "checkExtension";
- // check validity period: make sure the notAfterDate of the certificate
- // will not go beyond the notAfterDate of the CA cert which signs the certificate.
+ // check validity period: make sure the notAfterDate of the certificate
+ // will not go beyond the notAfterDate of the CA cert which signs the
+ // certificate.
public final static String TASK_VALIDITY_PERIOD = "checkValidityPeriod";
public final static String TASK_CLONING = "taskCloning";
diff --git a/pki/base/common/src/com/netscape/certsrv/connector/IConnector.java b/pki/base/common/src/com/netscape/certsrv/connector/IConnector.java
index 6dcca9d2..c5e455c5 100644
--- a/pki/base/common/src/com/netscape/certsrv/connector/IConnector.java
+++ b/pki/base/common/src/com/netscape/certsrv/connector/IConnector.java
@@ -17,20 +17,17 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.connector;
-
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This interface represents a connector that forwards
- * CMS requests to a remote authority.
- *
- * To register a connector, one can add the following
- * to the CMS.cfg:
- *
+ * This interface represents a connector that forwards CMS requests to a remote
+ * authority.
+ *
+ * To register a connector, one can add the following to the CMS.cfg:
+ *
* <pre>
- *
+ *
* Example for KRA type connector.
* ca.connector.KRA.enable=true
* ca.connector.KRA.host=thehost.netscape.com #Remote host.
@@ -39,21 +36,22 @@ import com.netscape.certsrv.request.IRequest;
* ca.connector.KRA.uri="/kra/connector" #Uri of the KRA server.
* ca.connector.KRA.id="kra"
* ca.connector.KRA.minHttpConns=1 #Min connection pool connections.
- * ca.connector.KRA.maxHttpConns=10 #Max connection pool connections.
+ * ca.connector.KRA.maxHttpConns=10 #Max connection pool connections.
* </pre>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IConnector {
/**
* Sends the request to a remote authority.
+ *
* @param req Request to be forwarded to remote authority.
* @return true for success, otherwise false.
- * @exception EBaseException Failure to send request to remote authority.
+ * @exception EBaseException Failure to send request to remote authority.
*/
public boolean send(IRequest req)
- throws EBaseException;
+ throws EBaseException;
/**
* Starts this connector.
diff --git a/pki/base/common/src/com/netscape/certsrv/connector/IHttpConnFactory.java b/pki/base/common/src/com/netscape/certsrv/connector/IHttpConnFactory.java
index c53c6f09..2fa04053 100644
--- a/pki/base/common/src/com/netscape/certsrv/connector/IHttpConnFactory.java
+++ b/pki/base/common/src/com/netscape/certsrv/connector/IHttpConnFactory.java
@@ -17,35 +17,34 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.connector;
-
import com.netscape.certsrv.base.EBaseException;
/**
- * Maintains a pool of connections to to a Remote Authority.
- * Utilized by the IHttpConnector interface.
- * Multiple threads use this interface to utilize and release
- * the Ldap connection resources. This factory will maintain a
- * list of Http type connections to the remote host.
- *
+ * Maintains a pool of connections to to a Remote Authority. Utilized by the
+ * IHttpConnector interface. Multiple threads use this interface to utilize and
+ * release the Ldap connection resources. This factory will maintain a list of
+ * Http type connections to the remote host.
+ *
* @version $Revision$, $Date$
*/
public interface IHttpConnFactory {
-
/**
* Request access to a Ldap connection from the pool.
+ *
* @exception EBaseException if any error occurs, such as a
- * @return Ldap connection object.
- * connection is not available
+ * @return Ldap connection object. connection is not available
*/
public IHttpConnection getConn()
- throws EBaseException;
+ throws EBaseException;
/**
* Return connection to the factory. mandatory after a getConn().
- * @param conn Ldap connection object to be returned to the free list of the pool.
+ *
+ * @param conn Ldap connection object to be returned to the free list of the
+ * pool.
* @exception EBaseException On any failure to return the connection.
*/
public void returnConn(IHttpConnection conn)
- throws EBaseException;
+ throws EBaseException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/connector/IHttpConnection.java b/pki/base/common/src/com/netscape/certsrv/connector/IHttpConnection.java
index 6ee57059..49bccc37 100644
--- a/pki/base/common/src/com/netscape/certsrv/connector/IHttpConnection.java
+++ b/pki/base/common/src/com/netscape/certsrv/connector/IHttpConnection.java
@@ -17,26 +17,24 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.connector;
-
import com.netscape.certsrv.base.EBaseException;
-
/**
- * This represents a HTTP connection to a remote authority.
- * Http connection is used by the connector to send
- * PKI messages to a remote authority. The remote authority
- * will reply with a PKI message as well. An example would
- * be the communication between a CA and a KRA.
- *
+ * This represents a HTTP connection to a remote authority. Http connection is
+ * used by the connector to send PKI messages to a remote authority. The remote
+ * authority will reply with a PKI message as well. An example would be the
+ * communication between a CA and a KRA.
+ *
* @version $Revision$, $Date$
*/
public interface IHttpConnection {
/**
* Sends the PKI message to the remote authority.
+ *
* @param tomsg Message to forward to authority.
* @exception EBaseException Failed to send message.
*/
- public IPKIMessage send(IPKIMessage tomsg)
- throws EBaseException;
+ public IPKIMessage send(IPKIMessage tomsg)
+ throws EBaseException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/connector/IHttpPKIMessage.java b/pki/base/common/src/com/netscape/certsrv/connector/IHttpPKIMessage.java
index 5cb53e25..a6c47a86 100644
--- a/pki/base/common/src/com/netscape/certsrv/connector/IHttpPKIMessage.java
+++ b/pki/base/common/src/com/netscape/certsrv/connector/IHttpPKIMessage.java
@@ -17,39 +17,40 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.connector;
-
import com.netscape.certsrv.request.IRequest;
-
/**
- * This represents a Http PKI message. It contains
- * simple name/value pair values. Also maintains information
- * about the status and type of the message.
- *
+ * This represents a Http PKI message. It contains simple name/value pair
+ * values. Also maintains information about the status and type of the message.
+ *
* @version $Revision$, $Date$
*/
public interface IHttpPKIMessage extends IPKIMessage {
/**
* Retrieves the request type.
+ *
* @return String with the type of request.
*/
public String getReqType();
/**
* Retrieves the request identifier.
+ *
* @return String of name of request.
*/
public String getReqId();
/**
* Copies contents of request to make a simple name/value message.
+ *
* @param r Instance of IRequest to be copied from.
*/
public void fromRequest(IRequest r);
/**
* Copies contents to request.
+ *
* @param r Instance of IRequest to be copied to.
*/
public void toRequest(IRequest r);
diff --git a/pki/base/common/src/com/netscape/certsrv/connector/IPKIMessage.java b/pki/base/common/src/com/netscape/certsrv/connector/IPKIMessage.java
index 57ce9700..50b447a2 100644
--- a/pki/base/common/src/com/netscape/certsrv/connector/IPKIMessage.java
+++ b/pki/base/common/src/com/netscape/certsrv/connector/IPKIMessage.java
@@ -17,53 +17,52 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.connector;
-
import java.io.Serializable;
import com.netscape.certsrv.request.IRequest;
-
/**
- * Messages that are serialized and go over the wire.
- * It must be serializable, and
- * later will be inherited by CRMF message.
- *
+ * Messages that are serialized and go over the wire. It must be serializable,
+ * and later will be inherited by CRMF message.
+ *
* @version $Revision$, $Date$
*/
public interface IPKIMessage extends Serializable {
/**
- *
- * Returns status of request.
- * @return String of request status.
- */
+ *
+ * Returns status of request.
+ *
+ * @return String of request status.
+ */
public String getReqStatus();
/**
* Retrieves the request type.
+ *
* @return String of type of request.
*/
public String getReqType();
-
/**
* Retrieves the request identifer.
+ *
* @return String of name of request.
*/
public String getReqId();
/**
- * Makes a PKIMessage from a request
- * PKIMessage will be sent to wire.
+ * Makes a PKIMessage from a request PKIMessage will be sent to wire.
+ *
* @param r Request to copy from.
*/
public void fromRequest(IRequest r);
/**
- * Copies contents of PKIMessage to the request
- * PKIMessage is from the wire.
+ * Copies contents of PKIMessage to the request PKIMessage is from the wire.
+ *
* @param r Request to copy to.
*/
public void toRequest(IRequest r);
-
+
}
diff --git a/pki/base/common/src/com/netscape/certsrv/connector/IRemoteAuthority.java b/pki/base/common/src/com/netscape/certsrv/connector/IRemoteAuthority.java
index a97936aa..8353ef27 100644
--- a/pki/base/common/src/com/netscape/certsrv/connector/IRemoteAuthority.java
+++ b/pki/base/common/src/com/netscape/certsrv/connector/IRemoteAuthority.java
@@ -17,38 +17,38 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.connector;
-
-
-
/**
- * This represents a remote authority that can be
- * a certificate manager, or key recovery manager or
- * some other manager.
- *
+ * This represents a remote authority that can be a certificate manager, or key
+ * recovery manager or some other manager.
+ *
* @version $Revision$, $Date$
*/
public interface IRemoteAuthority {
/**
* Retrieves the host name of the remote Authority.
+ *
* @return String with the name of host of remote Authority.
*/
public String getHost();
/**
* Retrieves the port number of the remote Authority.
+ *
* @return Int with port number of remote Authority.
*/
public int getPort();
/**
* Retrieves the URI of the remote Authority.
+ *
* @return String with URI of remote Authority.
*/
public String getURI();
/**
* Retrieves the timeout value for the connection to the remote Authority.
+ *
* @return In with remote Authority timeout value.
*/
public int getTimeout();
diff --git a/pki/base/common/src/com/netscape/certsrv/connector/IRequestEncoder.java b/pki/base/common/src/com/netscape/certsrv/connector/IRequestEncoder.java
index 7838aa5e..80975462 100644
--- a/pki/base/common/src/com/netscape/certsrv/connector/IRequestEncoder.java
+++ b/pki/base/common/src/com/netscape/certsrv/connector/IRequestEncoder.java
@@ -17,34 +17,32 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.connector;
-
import java.io.IOException;
-
/**
- * This represents a rquest encoder that serializes and
- * deserializes a request to a Remote Authority so that it can be sent through
- * the connector.
- *
+ * This represents a rquest encoder that serializes and deserializes a request
+ * to a Remote Authority so that it can be sent through the connector.
+ *
* @version $Revision$, $Date$
*/
public interface IRequestEncoder {
/**
* Encodes a request object.
+ *
* @param r Object to serve as the source of the message.
* @return String containing encoded message.
* @exception IOException Failure of the encoding operation due to IO error.
*/
String encode(Object r)
- throws IOException;
+ throws IOException;
/**
- * Dncodes a String into an object.
+ * Dncodes a String into an object.
+ *
* @return Object which is the result of the decoded message.
* @exception IOException Failure of the decoding operation due to IO error.
*/
Object decode(String s)
- throws IOException;
+ throws IOException;
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/connector/IResender.java b/pki/base/common/src/com/netscape/certsrv/connector/IResender.java
index 3574c3a5..fad3c2a8 100644
--- a/pki/base/common/src/com/netscape/certsrv/connector/IResender.java
+++ b/pki/base/common/src/com/netscape/certsrv/connector/IResender.java
@@ -17,25 +17,22 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.connector;
-
import com.netscape.certsrv.request.IRequest;
-
/**
- * Resend requests at intervals to the server to ensure completion of requests.
- * Default interval is 5 minutes. The need to resend a message could arise
- * due to an error or the fact that the message could not be serviced
- * immediately.
- *
+ * Resend requests at intervals to the server to ensure completion of requests.
+ * Default interval is 5 minutes. The need to resend a message could arise due
+ * to an error or the fact that the message could not be serviced immediately.
+ *
* @version $Revision$, $Date$
*/
public interface IResender extends Runnable {
/**
* Adds the request to the resend queue.
+ *
* @param r Request to be placed on the resend queue.
*/
public void addRequest(IRequest r);
-
-}
+}
diff --git a/pki/base/common/src/com/netscape/certsrv/dbs/DBResources.java b/pki/base/common/src/com/netscape/certsrv/dbs/DBResources.java
index 4bfb14fb..a2201b8e 100644
--- a/pki/base/common/src/com/netscape/certsrv/dbs/DBResources.java
+++ b/pki/base/common/src/com/netscape/certsrv/dbs/DBResources.java
@@ -17,14 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.dbs;
-
import java.util.ListResourceBundle;
-
/**
* A class represents a resource bundle for DBS subsystem.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class DBResources extends ListResourceBundle {
@@ -38,4 +36,3 @@ public class DBResources extends ListResourceBundle {
static final Object[][] contents = {};
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/dbs/EDBException.java b/pki/base/common/src/com/netscape/certsrv/dbs/EDBException.java
index 14f653d6..77508dca 100644
--- a/pki/base/common/src/com/netscape/certsrv/dbs/EDBException.java
+++ b/pki/base/common/src/com/netscape/certsrv/dbs/EDBException.java
@@ -17,14 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.dbs;
-
import com.netscape.certsrv.base.EBaseException;
-
/**
* A class represents a database exception.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class EDBException extends EBaseException {
@@ -36,12 +34,12 @@ public class EDBException extends EBaseException {
/**
* Resource class name.
*/
- private static final String DB_RESOURCES = DBResources.class.getName();
+ private static final String DB_RESOURCES = DBResources.class.getName();
/**
* Constructs a database exception.
* <P>
- *
+ *
* @param msgFormat message format
*/
public EDBException(String msgFormat) {
@@ -51,7 +49,7 @@ public class EDBException extends EBaseException {
/**
* Constructs a database exception.
* <P>
- *
+ *
* @param msgFormat message format
* @param param parameter
*/
@@ -62,7 +60,7 @@ public class EDBException extends EBaseException {
/**
* Constructs a database exception.
* <P>
- *
+ *
* @param msgFormat message format
* @param e exception as parameter
*/
@@ -73,7 +71,7 @@ public class EDBException extends EBaseException {
/**
* Constructs a database exception.
* <P>
- *
+ *
* @param msgFormat message format
* @param params list of parameters
*/
diff --git a/pki/base/common/src/com/netscape/certsrv/dbs/EDBNotAvailException.java b/pki/base/common/src/com/netscape/certsrv/dbs/EDBNotAvailException.java
index 170a8ee8..6afb2dcc 100644
--- a/pki/base/common/src/com/netscape/certsrv/dbs/EDBNotAvailException.java
+++ b/pki/base/common/src/com/netscape/certsrv/dbs/EDBNotAvailException.java
@@ -17,10 +17,9 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.dbs;
-
/**
* Indicates internal db is down.
- *
+ *
* @version $Revision$, $Date$
*/
public class EDBNotAvailException extends EDBException {
@@ -32,7 +31,7 @@ public class EDBNotAvailException extends EDBException {
/**
* Constructs a ldap server down exception with host & port info.
- *
+ *
* @param errorString Detailed error message.
*/
public EDBNotAvailException(String errorString) {
diff --git a/pki/base/common/src/com/netscape/certsrv/dbs/EDBRecordNotFoundException.java b/pki/base/common/src/com/netscape/certsrv/dbs/EDBRecordNotFoundException.java
index 1640fc78..dd3880c1 100644
--- a/pki/base/common/src/com/netscape/certsrv/dbs/EDBRecordNotFoundException.java
+++ b/pki/base/common/src/com/netscape/certsrv/dbs/EDBRecordNotFoundException.java
@@ -17,10 +17,9 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.dbs;
-
/**
* Indicates internal db is down.
- *
+ *
* @version $Revision$, $Date$
*/
public class EDBRecordNotFoundException extends EDBException {
@@ -32,7 +31,7 @@ public class EDBRecordNotFoundException extends EDBException {
/**
* Constructs a ldap server down exception with host & port info.
- *
+ *
* @param errorString Detailed error message.
*/
public EDBRecordNotFoundException(String errorString) {
diff --git a/pki/base/common/src/com/netscape/certsrv/dbs/IDBAttrMapper.java b/pki/base/common/src/com/netscape/certsrv/dbs/IDBAttrMapper.java
index 173537d6..8e109f20 100644
--- a/pki/base/common/src/com/netscape/certsrv/dbs/IDBAttrMapper.java
+++ b/pki/base/common/src/com/netscape/certsrv/dbs/IDBAttrMapper.java
@@ -17,66 +17,61 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.dbs;
-
import java.util.Enumeration;
import netscape.ldap.LDAPAttributeSet;
import com.netscape.certsrv.base.EBaseException;
-
/**
- * An interface represents an attribute mapper. A mapper
- * has knowledge on how to convert a db attribute into
- * zero or more LDAP attribute, and vice versa.
+ * An interface represents an attribute mapper. A mapper has knowledge on how to
+ * convert a db attribute into zero or more LDAP attribute, and vice versa.
* <P>
- *
- * @version $Revision$, $Date$
+ *
+ * @version $Revision$, $Date$
*/
public interface IDBAttrMapper {
/**
- * Retrieves a list of LDAP attributes that are used
- * in the mapper. By having this, the framework can
- * provide search on selective attributes.
- *
+ * Retrieves a list of LDAP attributes that are used in the mapper. By
+ * having this, the framework can provide search on selective attributes.
+ *
* @return a list of supported attribute names
*/
public Enumeration<String> getSupportedLDAPAttributeNames();
/**
* Maps object attribute into LDAP attributes.
- *
+ *
* @param parent parent object where the object comes from
* @param name name of db attribute
* @param obj object itself
* @param attrs LDAP attribute set where the result should be stored
* @exception EBaseException failed to map object
*/
- public void mapObjectToLDAPAttributeSet(IDBObj parent,
- String name, Object obj, LDAPAttributeSet attrs)
- throws EBaseException;
+ public void mapObjectToLDAPAttributeSet(IDBObj parent,
+ String name, Object obj, LDAPAttributeSet attrs)
+ throws EBaseException;
/**
- * Maps LDAP attributes into object, and puts the object
- * into 'parent'.
- *
+ * Maps LDAP attributes into object, and puts the object into 'parent'.
+ *
* @param attrs LDAP attribute set
* @param name name of db attribute to be processed
* @param parent parent object where the object should be added
* @exception EBaseException failed to map object
*/
- public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
- String name, IDBObj parent) throws EBaseException;
+ public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
+ String name, IDBObj parent) throws EBaseException;
/**
* Maps search filters into LDAP search filter.
- *
+ *
* @param name name of db attribute
* @param op filte operation (i.e. "=", ">=")
* @param value attribute value
* @exception EBaseException failed to map filter
*/
- public String mapSearchFilter(String name, String op,
- String value) throws EBaseException;
+ public String mapSearchFilter(String name, String op,
+ String value) throws EBaseException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/dbs/IDBDynAttrMapper.java b/pki/base/common/src/com/netscape/certsrv/dbs/IDBDynAttrMapper.java
index c1c8c3b3..c564506c 100644
--- a/pki/base/common/src/com/netscape/certsrv/dbs/IDBDynAttrMapper.java
+++ b/pki/base/common/src/com/netscape/certsrv/dbs/IDBDynAttrMapper.java
@@ -1,20 +1,18 @@
package com.netscape.certsrv.dbs;
/**
- * An interface representing a dynamic attribute mapper.
- * A dynamic mapper has knowledge on how to convert a set of dynamically
- * assigned db attribute into zero or more dynamically assigned LDAP
- * attributes, and vice versa.
+ * An interface representing a dynamic attribute mapper. A dynamic mapper has
+ * knowledge on how to convert a set of dynamically assigned db attribute into
+ * zero or more dynamically assigned LDAP attributes, and vice versa.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IDBDynAttrMapper extends IDBAttrMapper {
/**
- * Returns true if the LDAP attribute can be mapped by this
- * dynamic mapper.
- *
+ * Returns true if the LDAP attribute can be mapped by this dynamic mapper.
+ *
* @param attrName LDAP attribute name to check
* @return a list of supported attribute names
*/
diff --git a/pki/base/common/src/com/netscape/certsrv/dbs/IDBObj.java b/pki/base/common/src/com/netscape/certsrv/dbs/IDBObj.java
index ab1ce0a4..1b9f818c 100644
--- a/pki/base/common/src/com/netscape/certsrv/dbs/IDBObj.java
+++ b/pki/base/common/src/com/netscape/certsrv/dbs/IDBObj.java
@@ -17,26 +17,21 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.dbs;
-
import java.util.Enumeration;
import com.netscape.certsrv.base.IAttrSet;
-
/**
- * An interface represents a database object
- * that is serializable.
- *
- * @version $Revision$, $Date$
+ * An interface represents a database object that is serializable.
+ *
+ * @version $Revision$, $Date$
*/
public interface IDBObj extends IAttrSet {
/**
- * Returns a list of serializable attribute
- * names. This method should return the
- * attribute name even if there is no attribute
- * value for the attribute.
- *
+ * Returns a list of serializable attribute names. This method should return
+ * the attribute name even if there is no attribute value for the attribute.
+ *
* @return a list of serializable attribute names
*/
public Enumeration<String> getSerializableAttrNames();
diff --git a/pki/base/common/src/com/netscape/certsrv/dbs/IDBRegistry.java b/pki/base/common/src/com/netscape/certsrv/dbs/IDBRegistry.java
index 4270c9ce..a52c0eb4 100644
--- a/pki/base/common/src/com/netscape/certsrv/dbs/IDBRegistry.java
+++ b/pki/base/common/src/com/netscape/certsrv/dbs/IDBRegistry.java
@@ -17,42 +17,37 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.dbs;
-
import netscape.ldap.LDAPAttributeSet;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.ISubsystem;
-
/**
- * A class represents a registry where all the
- * schema (object classes and attribute) information
- * is stored.
- *
- * Attribute mappers can be registered with this
- * registry.
- *
- * Given the schema information stored, this registry
- * has knowledge to convert a Java object into a
- * LDAPAttributeSet or vice versa.
- *
- * @version $Revision$, $Date$
+ * A class represents a registry where all the schema (object classes and
+ * attribute) information is stored.
+ *
+ * Attribute mappers can be registered with this registry.
+ *
+ * Given the schema information stored, this registry has knowledge to convert a
+ * Java object into a LDAPAttributeSet or vice versa.
+ *
+ * @version $Revision$, $Date$
*/
public interface IDBRegistry extends ISubsystem {
/**
* Registers object class.
- *
+ *
* @param className java class to create for the object classes
* @param ldapNames a list of LDAP object classes
* @exception EDBException failed to register
*/
public void registerObjectClass(String className, String ldapNames[])
- throws EDBException;
+ throws EDBException;
/**
* See if an object class is registered.
- *
+ *
* @param className java class to create
* @return true if object class is registered already
*/
@@ -60,17 +55,17 @@ public interface IDBRegistry extends ISubsystem {
/**
* Registers attribute mapper.
- *
+ *
* @param ufName LDAP attribute name
* @param mapper mapper to invoke for the attribute
* @exception EDBException failed to register
*/
- public void registerAttribute(String ufName, IDBAttrMapper mapper)
- throws EDBException;
+ public void registerAttribute(String ufName, IDBAttrMapper mapper)
+ throws EDBException;
/**
* See if an attribute is registered.
- *
+ *
* @param ufName attribute name
* @return true if attribute is registered already
*/
@@ -78,14 +73,15 @@ public interface IDBRegistry extends ISubsystem {
/**
* Registers a dynamic attribute mapper.
+ *
* @param mapper The dynamic mapper to register
*/
public void registerDynamicMapper(IDBDynAttrMapper mapper);
/**
- * Creates LDAP-based search filters with help of
- * registered mappers.
- * Parses filter from filter string specified in RFC1558.
+ * Creates LDAP-based search filters with help of registered mappers. Parses
+ * filter from filter string specified in RFC1558.
+ *
* <pre>
* <filter> ::= '(' <filtercomp> ')'
* <filtercomp> ::= <and> | <or> | <not> | <item>
@@ -107,7 +103,7 @@ public interface IDBRegistry extends ISubsystem {
* <starval> ::= NULL | <value> '*' <starval>
* <final> ::= NULL | <value>
* </pre>
- *
+ *
* @param filter CMS-based filter
* @return LDAP-based filter string
* @exception EBaseException failed to convert filter
@@ -115,57 +111,56 @@ public interface IDBRegistry extends ISubsystem {
public String getFilter(String filter) throws EBaseException;
/**
- * Creates LDAP-based search filters with help of
- * registered mappers.
- *
+ * Creates LDAP-based search filters with help of registered mappers.
+ *
* @param filter CMS-based filter
* @param c filter converter
* @return LDAP-based filter string
* @exception EBaseException failed to convert filter
*/
- public String getFilter(String filter, IFilterConverter c)
- throws EBaseException;
+ public String getFilter(String filter, IFilterConverter c)
+ throws EBaseException;
/**
* Maps object into LDAP attribute set.
- *
+ *
* @param parent object's parent
* @param name name of the object
* @param obj object to be mapped
* @param attrs LDAP attribute set
* @exception EBaseException failed to map object
*/
- public void mapObject(IDBObj parent, String name, Object obj,
- LDAPAttributeSet attrs) throws EBaseException;
+ public void mapObject(IDBObj parent, String name, Object obj,
+ LDAPAttributeSet attrs) throws EBaseException;
/**
- * Retrieves a list of LDAP attributes that are associated
- * with the given attributes.
- *
+ * Retrieves a list of LDAP attributes that are associated with the given
+ * attributes.
+ *
* @param attrs attributes
* @return LDAP-based attributes
* @exception EBaseException failed to map attributes
*/
- public String[] getLDAPAttributes(String attrs[])
- throws EBaseException;
+ public String[] getLDAPAttributes(String attrs[])
+ throws EBaseException;
/**
* Creates attribute set from object.
- *
+ *
* @param obj database object
* @return LDAP attribute set
* @exception EBaseException failed to create set
*/
- public LDAPAttributeSet createLDAPAttributeSet(IDBObj obj)
- throws EBaseException;
+ public LDAPAttributeSet createLDAPAttributeSet(IDBObj obj)
+ throws EBaseException;
/**
* Creates object from attribute set.
- *
+ *
* @param attrs LDAP attribute set
* @return database object
* @exception EBaseException failed to create object
*/
public IDBObj createObject(LDAPAttributeSet attrs)
- throws EBaseException;
+ throws EBaseException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/dbs/IDBSSession.java b/pki/base/common/src/com/netscape/certsrv/dbs/IDBSSession.java
index 7f4e4f8c..02ebb23f 100644
--- a/pki/base/common/src/com/netscape/certsrv/dbs/IDBSSession.java
+++ b/pki/base/common/src/com/netscape/certsrv/dbs/IDBSSession.java
@@ -17,45 +17,43 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.dbs;
-
import netscape.ldap.LDAPSearchResults;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.ISubsystem;
-
/**
- * An interface represents the database session. Operations
- * can be performed with a session.
- *
- * Transaction and Caching support can be integrated
- * into session.
- *
- * @version $Revision$, $Date$
+ * An interface represents the database session. Operations can be performed
+ * with a session.
+ *
+ * Transaction and Caching support can be integrated into session.
+ *
+ * @version $Revision$, $Date$
*/
public interface IDBSSession {
/**
* Returns database subsystem.
- *
+ *
* @return subsystem
*/
public ISubsystem getDBSubsystem();
/**
* Closes this session.
- *
+ *
* @exception EDBException failed to close session
*/
public void close() throws EDBException;
/**
* Adds object to backend database. For example,
+ *
* <PRE>
- * session.add("cn=123459,o=certificate repository,o=airius.com",
- * certRec);
+ * session.add(&quot;cn=123459,o=certificate repository,o=airius.com&quot;,
+ * certRec);
* </PRE>
- *
+ *
* @param name name of the object
* @param obj object to be added
* @exception EDBException failed to add object
@@ -64,7 +62,7 @@ public interface IDBSSession {
/**
* Reads an object from the database.
- *
+ *
* @param name name of the object that is to be read
* @return database object
* @exception EBaseException failed to read object
@@ -72,20 +70,20 @@ public interface IDBSSession {
public IDBObj read(String name) throws EBaseException;
/**
- * Reads an object from the database, and only populates
- * the selected attributes.
- *
+ * Reads an object from the database, and only populates the selected
+ * attributes.
+ *
* @param name name of the object that is to be read
* @param attrs selected attributes
* @return database object
* @exception EBaseException failed to read object
*/
- public IDBObj read(String name, String attrs[])
- throws EBaseException;
+ public IDBObj read(String name, String attrs[])
+ throws EBaseException;
/**
* Deletes object from database.
- *
+ *
* @param name name of the object that is to be deleted
* @exception EBaseException failed to delete object
*/
@@ -93,43 +91,40 @@ public interface IDBSSession {
/**
* Modify an object in the database.
- *
+ *
* @param name name of the object that is to be modified
* @param mods modifications
* @exception EBaseException failed to modify
*/
- public void modify(String name, ModificationSet mods)
- throws EBaseException;
+ public void modify(String name, ModificationSet mods)
+ throws EBaseException;
/**
- * Searchs for a list of objects that match the
- * filter.
- *
+ * Searchs for a list of objects that match the filter.
+ *
* @param base starting point of the search
* @param filter search filter
* @return search results
* @exception EBaseException failed to search
*/
- public IDBSearchResults search(String base, String filter)
- throws EBaseException;
+ public IDBSearchResults search(String base, String filter)
+ throws EBaseException;
/**
- * Searchs for a list of objects that match the
- * filter.
- *
+ * Searchs for a list of objects that match the filter.
+ *
* @param base starting point of the search
* @param filter search filter
* @param maxSize max number of entries
* @return search results
* @exception EBaseException failed to search
*/
- public IDBSearchResults search(String base, String filter, int maxSize)
- throws EBaseException;
+ public IDBSearchResults search(String base, String filter, int maxSize)
+ throws EBaseException;
/**
- * Searchs for a list of objects that match the
- * filter.
- *
+ * Searchs for a list of objects that match the filter.
+ *
* @param base starting point of the search
* @param filter search filter
* @param maxSize max number of entries
@@ -137,25 +132,24 @@ public interface IDBSSession {
* @return search results
* @exception EBaseException failed to search
*/
- public IDBSearchResults search(String base, String filter, int maxSize,
- int timeLimit) throws EBaseException;
+ public IDBSearchResults search(String base, String filter, int maxSize,
+ int timeLimit) throws EBaseException;
/**
- * Retrieves a list of object that satifies the given
- * filter.
- *
+ * Retrieves a list of object that satifies the given filter.
+ *
* @param base starting point of the search
* @param filter search filter
* @param attrs selected attributes
* @return search results
* @exception EBaseException failed to search
*/
- public IDBSearchResults search(String base, String filter,
- String attrs[]) throws EBaseException;
+ public IDBSearchResults search(String base, String filter,
+ String attrs[]) throws EBaseException;
/**
* Retrieves a list of objects.
- *
+ *
* @param base starting point of the search
* @param filter search filter
* @param attrs selected attributes
@@ -163,12 +157,11 @@ public interface IDBSSession {
* @exception EBaseException failed to search
*/
public <T> IDBVirtualList<T> createVirtualList(String base, String filter,
- String attrs[]) throws EBaseException;
+ String attrs[]) throws EBaseException;
/**
- * Sets persistent search to retrieve modified
- * certificate records.
- *
+ * Sets persistent search to retrieve modified certificate records.
+ *
* @param base starting point of the search
* @param filter search filter
* @param attrs selected attributes
@@ -176,11 +169,11 @@ public interface IDBSSession {
* @exception EBaseException failed to search
*/
public LDAPSearchResults persistentSearch(String base, String filter,
- String attrs[]) throws EBaseException;
+ String attrs[]) throws EBaseException;
/**
* Retrieves a list of objects.
- *
+ *
* @param base starting point of the search
* @param filter search filter
* @param attrs selected attributes
@@ -190,12 +183,12 @@ public interface IDBSSession {
* @exception EBaseException failed to search
*/
public <T> IDBVirtualList<T> createVirtualList(String base, String filter,
- String attrs[], String sortKey, int pageSize)
- throws EBaseException;
+ String attrs[], String sortKey, int pageSize)
+ throws EBaseException;
/**
* Retrieves a list of objects.
- *
+ *
* @param base starting point of the search
* @param filter search filter
* @param attrs selected attributes
@@ -206,7 +199,7 @@ public interface IDBSSession {
* @exception EBaseException failed to search
*/
public <T> IDBVirtualList<T> createVirtualList(String base, String filter,
- String attrs[], String startFrom,
- String sortKey, int pageSize)
- throws EBaseException;
+ String attrs[], String startFrom,
+ String sortKey, int pageSize)
+ throws EBaseException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/dbs/IDBSearchResults.java b/pki/base/common/src/com/netscape/certsrv/dbs/IDBSearchResults.java
index 9f15b808..6efd8473 100644
--- a/pki/base/common/src/com/netscape/certsrv/dbs/IDBSearchResults.java
+++ b/pki/base/common/src/com/netscape/certsrv/dbs/IDBSearchResults.java
@@ -17,29 +17,26 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.dbs;
-
import java.util.Enumeration;
-
/**
- * A class represents the search results. A search
- * results object contain a enumeration of
- * Java objects that are just read from the database.
- *
- * @version $Revision$, $Date$
+ * A class represents the search results. A search results object contain a
+ * enumeration of Java objects that are just read from the database.
+ *
+ * @version $Revision$, $Date$
*/
public interface IDBSearchResults extends Enumeration<Object> {
/**
* Checks if any element is available.
- *
+ *
* @return true if there is more elements
*/
public boolean hasMoreElements();
/**
* Retrieves next element.
- *
+ *
* @return next element
*/
public Object nextElement();
diff --git a/pki/base/common/src/com/netscape/certsrv/dbs/IDBSubsystem.java b/pki/base/common/src/com/netscape/certsrv/dbs/IDBSubsystem.java
index 350a29c4..d61e266b 100644
--- a/pki/base/common/src/com/netscape/certsrv/dbs/IDBSubsystem.java
+++ b/pki/base/common/src/com/netscape/certsrv/dbs/IDBSubsystem.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.dbs;
-
import java.math.BigInteger;
import netscape.ldap.LDAPConnection;
@@ -25,22 +24,19 @@ import netscape.ldap.LDAPConnection;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.ISubsystem;
-
/**
- * An interface represents certificate server
- * backend database.
+ * An interface represents certificate server backend database.
* <P>
- * This interface separate the database subsystem
- * functionalities from internal implementation.
+ * This interface separate the database subsystem functionalities from internal
+ * implementation.
* <P>
- *
- * @version $Revision$, $Date$
+ *
+ * @version $Revision$, $Date$
*/
public interface IDBSubsystem extends ISubsystem {
public static final String SUB_ID = "dbs";
-
// values for repos
public static final int CERTS = 0;
public static final int REQUESTS = 1;
@@ -49,21 +45,21 @@ public interface IDBSubsystem extends ISubsystem {
/**
* Retrieves the base DN.
- *
+ *
* @return base DN of the subsystem
*/
public String getBaseDN();
/**
* Retrieves the registry.
- *
+ *
* @return registry
*/
public IDBRegistry getRegistry();
/**
* Creates a database session.
- *
+ *
* @return database session
* @exception EDBException failed to create session
*/
@@ -71,145 +67,144 @@ public interface IDBSubsystem extends ISubsystem {
/**
* Avoids losing serial number.
- *
+ *
* @return true if serial number recovery option is enabled
*/
public boolean enableSerialNumberRecovery();
/**
* Records next serial number in config file
- *
+ *
* @param serial next serial number
- * @exception EBaseException failed to set
+ * @exception EBaseException failed to set
*/
public void setNextSerialConfig(BigInteger serial) throws EBaseException;
/**
* Gets the next serial number in config file
- *
+ *
* @return next serial number
*/
public BigInteger getNextSerialConfig();
/**
* Records maximum serial number limit in config file
- *
+ *
* @param serial max serial number
- * @param repo repo identifier
- * @exception EBaseException failed to set
+ * @param repo repo identifier
+ * @exception EBaseException failed to set
*/
public void setMaxSerialConfig(int repo, String serial) throws EBaseException;
/**
* Records minimum serial number limit in config file
- *
+ *
* @param serial min serial number
- * @param repo repo identifier
- * @exception EBaseException failed to set
+ * @param repo repo identifier
+ * @exception EBaseException failed to set
*/
public void setMinSerialConfig(int repo, String serial) throws EBaseException;
/**
* Records maximum serial number limit for the next range in config file
- *
+ *
* @param serial max serial number
- * @param repo repo identifier
- * @exception EBaseException failed to set
+ * @param repo repo identifier
+ * @exception EBaseException failed to set
*/
public void setNextMaxSerialConfig(int repo, String serial) throws EBaseException;
/**
* Records minimum serial number limit for the next range in config file
- *
+ *
* @param serial min serial number
- * @param repo repo identifier
- * @exception EBaseException failed to set
+ * @param repo repo identifier
+ * @exception EBaseException failed to set
*/
public void setNextMinSerialConfig(int repo, String serial) throws EBaseException;
/**
* Gets minimum serial number limit in config file
- *
- * @param repo repo identifier
+ *
+ * @param repo repo identifier
* @return min serial number
*/
public String getMinSerialConfig(int repo);
/**
* Gets the maximum serial number limit in config file
- *
- * @param repo repo identifier
+ *
+ * @param repo repo identifier
* @return max serial number
*/
public String getMaxSerialConfig(int repo);
/**
* Gets the maximum serial number limit for next range in config file
- *
- * @param repo repo identifier
+ *
+ * @param repo repo identifier
* @return max serial number
*/
public String getNextMaxSerialConfig(int repo);
/**
* Gets minimum serial number limit for next range in config file
- *
- * @param repo repo identifier
+ *
+ * @param repo repo identifier
* @return min serial number
*/
public String getNextMinSerialConfig(int repo);
-
+
/**
* Gets low water mark limit in config file
- *
- * @param repo repo identifier
+ *
+ * @param repo repo identifier
* @return low water mark
*/
public String getLowWaterMarkConfig(int repo);
-
+
/**
* Gets range increment limit for next range in config file
- *
- * @param repo repo identifier
+ *
+ * @param repo repo identifier
* @return range increment
*/
public String getIncrementConfig(int repo);
-
+
/**
* Gets number corresponding to start of next range from database
- *
- * @param repo repo identifier
+ *
+ * @param repo repo identifier
* @return start of next range
*/
public String getNextRange(int repo);
/**
* Determines if a range conflict has been observed in database
- *
- * @param repo repo identifier
+ *
+ * @param repo repo identifier
* @return true if range conflict, false otherwise
*/
public boolean hasRangeConflict(int repo);
/**
* Determines if serial number management has been enabled
- *
+ *
* @return true if enabled, false otherwise
*/
public boolean getEnableSerialMgmt();
- /**
- * Sets whether serial number management is enabled for certs
- * and requests.
- *
- * @param value true/false
- * @exception EBaseException failed to set
+ /**
+ * Sets whether serial number management is enabled for certs and requests.
+ *
+ * @param value true/false
+ * @exception EBaseException failed to set
*/
public void setEnableSerialMgmt(boolean value) throws EBaseException;
/**
* Returns LDAP connection to connection pool.
- *
+ *
* @param conn connection to be returned
*/
public void returnConn(LDAPConnection conn);
diff --git a/pki/base/common/src/com/netscape/certsrv/dbs/IDBVirtualList.java b/pki/base/common/src/com/netscape/certsrv/dbs/IDBVirtualList.java
index 7d175c45..ffd07fb0 100644
--- a/pki/base/common/src/com/netscape/certsrv/dbs/IDBVirtualList.java
+++ b/pki/base/common/src/com/netscape/certsrv/dbs/IDBVirtualList.java
@@ -17,24 +17,21 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.dbs;
-
import com.netscape.certsrv.base.EBaseException;
-
/**
- * A interface represents a virtual list of search results.
- * Note that this class must be used with DS4.0.
- *
+ * A interface represents a virtual list of search results. Note that this class
+ * must be used with DS4.0.
+ *
* @version $Revision$, $Date$
*/
-public interface IDBVirtualList<E> {
+public interface IDBVirtualList<E> {
/**
- * Sets the paging size of this virtual list.
- * The page size here is just a buffer size. A buffer is kept around
- * that is three times as large as the number of visible entries.
- * That way, you can scroll up/down several items(up to a page-full)
- * without refetching entries from the directory.
+ * Sets the paging size of this virtual list. The page size here is just a
+ * buffer size. A buffer is kept around that is three times as large as the
+ * number of visible entries. That way, you can scroll up/down several
+ * items(up to a page-full) without refetching entries from the directory.
*
* @param size the page size
*/
@@ -42,7 +39,7 @@ public interface IDBVirtualList<E> {
/**
* Sets the sort key
- *
+ *
* @param sortKey the attribute to sort by
* @exception EBaseException failed to set
*/
@@ -50,95 +47,93 @@ public interface IDBVirtualList<E> {
/**
* Sets the sort key
- *
+ *
* @param sortKeys the attributes to sort by
* @exception EBaseException failed to set
*/
public void setSortKey(String[] sortKeys) throws EBaseException;
/**
- * Retrieves the size of this virtual list.
- * Recommend to call getSize() before getElementAt() or getElements()
- * since you'd better check if the index is out of bound first.
- *
+ * Retrieves the size of this virtual list. Recommend to call getSize()
+ * before getElementAt() or getElements() since you'd better check if the
+ * index is out of bound first.
+ *
* @return current size in list
*/
public int getSize();
/**
* Returns current index.
- *
+ *
* @return current index
*/
public int getSizeBeforeJumpTo();
+
public int getSizeAfterJumpTo();
public int getCurrentIndex();
- /**
- * Get a page starting at "first" (although we may also fetch
- * some preceding entries)
- * Recommend to call getSize() before getElementAt() or getElements()
- * since you'd better check if the index is out of bound first.
- *
+ /**
+ * Get a page starting at "first" (although we may also fetch some preceding
+ * entries) Recommend to call getSize() before getElementAt() or
+ * getElements() since you'd better check if the index is out of bound
+ * first.
+ *
* @param first the index of the first entry of the page you want to fetch
*/
public boolean getPage(int first);
- /**
- * Called by application to scroll the list with initial letters.
- * Consider text to be an initial substring of the attribute of the
- * primary sorting key(the first one specified in the sort key array)
- * of an entry.
- * If no entries match, the one just before(or after, if none before)
- * will be returned as mSelectedIndex
- *
+ /**
+ * Called by application to scroll the list with initial letters. Consider
+ * text to be an initial substring of the attribute of the primary sorting
+ * key(the first one specified in the sort key array) of an entry. If no
+ * entries match, the one just before(or after, if none before) will be
+ * returned as mSelectedIndex
+ *
* @param text the prefix of the first entry of the page you want to fetch
*/
public boolean getPage(String text);
- /**
- * Fetchs data of a single list item
- * Recommend to call getSize() before getElementAt() or getElements()
- * since you'd better check if the index is out of bound first.
- * If the index is out of range of the virtual list, an exception
- * will be thrown and return null
- *
+ /**
+ * Fetchs data of a single list item Recommend to call getSize() before
+ * getElementAt() or getElements() since you'd better check if the index is
+ * out of bound first. If the index is out of range of the virtual list, an
+ * exception will be thrown and return null
+ *
* @param index the index of the element to fetch
*/
public E getElementAt(int index);
/**
* Retrieves and jumps to element in the given position.
- *
+ *
* @param i position
* @return object
*/
public E getJumpToElementAt(int i);
/**
- * Processes elements as soon as it arrives. It is
- * more memory-efficient.
- *
+ * Processes elements as soon as it arrives. It is more memory-efficient.
+ *
* @param startidx starting index
* @param endidx ending index
* @param ep object to call
* @exception EBaseException failed to process elements
*/
public void processElements(int startidx, int endidx, IElementProcessor ep)
- throws EBaseException;
+ throws EBaseException;
- /**
+ /**
* Gets the virutal selected index
- *
+ *
* @return selected index
*/
public int getSelectedIndex();
- /**
+ /**
* Gets the top of the buffer
- *
+ *
* @return first index
*/
public int getFirstIndex();
diff --git a/pki/base/common/src/com/netscape/certsrv/dbs/IElementProcessor.java b/pki/base/common/src/com/netscape/certsrv/dbs/IElementProcessor.java
index 75702199..648a13ae 100644
--- a/pki/base/common/src/com/netscape/certsrv/dbs/IElementProcessor.java
+++ b/pki/base/common/src/com/netscape/certsrv/dbs/IElementProcessor.java
@@ -17,20 +17,18 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.dbs;
-
import com.netscape.certsrv.base.EBaseException;
-
/**
* Processor handles object read from the session.
- *
+ *
* @version $Revision$, $Date$
*/
public interface IElementProcessor {
/**
* Handles object
- *
+ *
* @param o object to be processed
* @exception EBaseException failed to process object
*/
diff --git a/pki/base/common/src/com/netscape/certsrv/dbs/IFilterConverter.java b/pki/base/common/src/com/netscape/certsrv/dbs/IFilterConverter.java
index 1a078365..0cf293ce 100644
--- a/pki/base/common/src/com/netscape/certsrv/dbs/IFilterConverter.java
+++ b/pki/base/common/src/com/netscape/certsrv/dbs/IFilterConverter.java
@@ -17,14 +17,10 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.dbs;
-
-
-
/**
- * An interface represents a filter converter
- * that understands how to convert a attribute
- * type from one defintion to another.
- * For example,
+ * An interface represents a filter converter that understands how to convert a
+ * attribute type from one defintion to another. For example,
+ *
* <PRE>
* (1) database layer need to convert
* registered attribute type to ldap attribute
@@ -34,13 +30,13 @@ package com.netscape.certsrv.dbs;
* attribute type.
* </PRE>
*
- * @version $Revision$, $Date$
+ * @version $Revision$, $Date$
*/
public interface IFilterConverter {
/**
* Converts attribute into LDAP attribute.
- *
+ *
* @param attr attribute name
* @param op attribute operation
* @param value attribute value
diff --git a/pki/base/common/src/com/netscape/certsrv/dbs/Modification.java b/pki/base/common/src/com/netscape/certsrv/dbs/Modification.java
index 9be75f0b..00456711 100644
--- a/pki/base/common/src/com/netscape/certsrv/dbs/Modification.java
+++ b/pki/base/common/src/com/netscape/certsrv/dbs/Modification.java
@@ -17,14 +17,11 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.dbs;
-
-
-
/**
- * A class represents a modification. This is used by the
- * database (dbs) framework for modification operations.
- * It specifices the modification type and values.
- *
+ * A class represents a modification. This is used by the database (dbs)
+ * framework for modification operations. It specifices the modification type
+ * and values.
+ *
* @version $Revision$, $Date$
*/
public class Modification {
@@ -50,7 +47,7 @@ public class Modification {
/**
* Constructs a role modification.
- *
+ *
* @param name attribute name
* @param op attribute operation (i.e. MOD_ADD, MOD_DELETE, or MOD_REPLACE)
* @param value attribute value
@@ -63,7 +60,7 @@ public class Modification {
/**
* Retrieves attribute name.
- *
+ *
* @return attribute name
*/
public String getName() {
@@ -72,7 +69,7 @@ public class Modification {
/**
* Retrieves modification operation type.
- *
+ *
* @return modification type
*/
public int getOp() {
@@ -81,7 +78,7 @@ public class Modification {
/**
* Retrieves attribute value.
- *
+ *
* @return attribute value
*/
public Object getValue() {
diff --git a/pki/base/common/src/com/netscape/certsrv/dbs/ModificationSet.java b/pki/base/common/src/com/netscape/certsrv/dbs/ModificationSet.java
index b737f861..feda8d91 100644
--- a/pki/base/common/src/com/netscape/certsrv/dbs/ModificationSet.java
+++ b/pki/base/common/src/com/netscape/certsrv/dbs/ModificationSet.java
@@ -17,15 +17,13 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.dbs;
-
import java.util.Enumeration;
import java.util.Vector;
-
/**
- * A class represents a modification set. A modification
- * set contains zero or more modifications.
- *
+ * A class represents a modification set. A modification set contains zero or
+ * more modifications.
+ *
* @version $Revision$, $Date$
*/
public class ModificationSet {
@@ -43,7 +41,7 @@ public class ModificationSet {
/**
* Adds modification to this set.
- *
+ *
* @param name attribute name
* @param op modification operation
* @param value attribute value
@@ -54,7 +52,7 @@ public class ModificationSet {
/**
* Retrieves a list of modifications.
- *
+ *
* @return a list of Modifications
*/
public Enumeration<Modification> getModifications() {
diff --git a/pki/base/common/src/com/netscape/certsrv/dbs/certdb/ICertRecord.java b/pki/base/common/src/com/netscape/certsrv/dbs/certdb/ICertRecord.java
index 681e586b..d05c9ed5 100644
--- a/pki/base/common/src/com/netscape/certsrv/dbs/certdb/ICertRecord.java
+++ b/pki/base/common/src/com/netscape/certsrv/dbs/certdb/ICertRecord.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.dbs.certdb;
-
import java.math.BigInteger;
import java.util.Date;
@@ -26,10 +25,9 @@ import netscape.security.x509.X509CertImpl;
import com.netscape.certsrv.base.MetaInfo;
import com.netscape.certsrv.dbs.IDBObj;
-
/**
* An interface contains constants for certificate record.
- *
+ *
* @version $Revision$, $Date$
*/
public interface ICertRecord extends IDBObj {
@@ -71,108 +69,108 @@ public interface ICertRecord extends IDBObj {
public final static String X509CERT_DURATION = "duration";
public final static String X509CERT_EXTENSION = "extension";
public final static String X509CERT_SUBJECT = "subject";
- public final static String X509CERT_PUBLIC_KEY_DATA ="publicKeyData";
+ public final static String X509CERT_PUBLIC_KEY_DATA = "publicKeyData";
public final static String X509CERT_VERSION = "version";
public final static String X509CERT_ALGORITHM = "algorithm";
public final static String X509CERT_SIGNING_ALGORITHM = "signingAlgorithm";
public final static String X509CERT_SERIAL_NUMBER = "serialNumber";
/* attribute type used the following with search filter */
- public final static String ATTR_X509CERT_NOT_BEFORE =
- ATTR_X509CERT + "." + X509CERT_NOT_BEFORE;
- public final static String ATTR_X509CERT_NOT_AFTER =
- ATTR_X509CERT + "." + X509CERT_NOT_AFTER;
- public final static String ATTR_X509CERT_DURATION =
- ATTR_X509CERT + "." + X509CERT_DURATION;
- public final static String ATTR_X509CERT_EXTENSION =
- ATTR_X509CERT + "." + X509CERT_EXTENSION;
- public final static String ATTR_X509CERT_SUBJECT =
- ATTR_X509CERT + "." + X509CERT_SUBJECT;
- public final static String ATTR_X509CERT_VERSION =
- ATTR_X509CERT + "." + X509CERT_VERSION;
- public final static String ATTR_X509CERT_ALGORITHM =
- ATTR_X509CERT + "." + X509CERT_ALGORITHM;
- public final static String ATTR_X509CERT_SIGNING_ALGORITHM =
- ATTR_X509CERT + "." + X509CERT_SIGNING_ALGORITHM;
- public final static String ATTR_X509CERT_SERIAL_NUMBER =
- ATTR_X509CERT + "." + X509CERT_SERIAL_NUMBER;
- public final static String ATTR_X509CERT_PUBLIC_KEY_DATA =
- ATTR_X509CERT + "." + X509CERT_PUBLIC_KEY_DATA;
+ public final static String ATTR_X509CERT_NOT_BEFORE =
+ ATTR_X509CERT + "." + X509CERT_NOT_BEFORE;
+ public final static String ATTR_X509CERT_NOT_AFTER =
+ ATTR_X509CERT + "." + X509CERT_NOT_AFTER;
+ public final static String ATTR_X509CERT_DURATION =
+ ATTR_X509CERT + "." + X509CERT_DURATION;
+ public final static String ATTR_X509CERT_EXTENSION =
+ ATTR_X509CERT + "." + X509CERT_EXTENSION;
+ public final static String ATTR_X509CERT_SUBJECT =
+ ATTR_X509CERT + "." + X509CERT_SUBJECT;
+ public final static String ATTR_X509CERT_VERSION =
+ ATTR_X509CERT + "." + X509CERT_VERSION;
+ public final static String ATTR_X509CERT_ALGORITHM =
+ ATTR_X509CERT + "." + X509CERT_ALGORITHM;
+ public final static String ATTR_X509CERT_SIGNING_ALGORITHM =
+ ATTR_X509CERT + "." + X509CERT_SIGNING_ALGORITHM;
+ public final static String ATTR_X509CERT_SERIAL_NUMBER =
+ ATTR_X509CERT + "." + X509CERT_SERIAL_NUMBER;
+ public final static String ATTR_X509CERT_PUBLIC_KEY_DATA =
+ ATTR_X509CERT + "." + X509CERT_PUBLIC_KEY_DATA;
/**
* Retrieves serial number from stored certificate.
- *
+ *
* @return certificate serial number
*/
public BigInteger getCertificateSerialNumber();
/**
* Retrieves serial number from certificate record.
- *
+ *
* @return certificate serial number
*/
public BigInteger getSerialNumber();
/**
* Retrieves certificate from certificate record.
- *
+ *
* @return certificate
*/
public X509CertImpl getCertificate();
/**
* Retrieves name of who issued this certificate.
- *
+ *
* @return name of who issued this certificate
*/
public String getIssuedBy();
/**
* Retrieves name of who revoked this certificate.
- *
+ *
* @return name of who revoked this certificate
*/
public String getRevokedBy();
/**
* Retrieves date when this certificate was revoked.
- *
+ *
* @return date when this certificate was revoked
*/
public Date getRevokedOn();
/**
* Retrieves meta info.
- *
+ *
* @return meta info
*/
public MetaInfo getMetaInfo();
/**
* Retrieves certificate status.
- *
+ *
* @return certificate status
*/
public String getStatus();
/**
* Retrieves time of creation of this certificate record.
- *
+ *
* @return time of creation of this certificate record
*/
public Date getCreateTime();
/**
* Retrieves time of modification of this certificate record.
- *
+ *
* @return time of modification of this certificate record
*/
public Date getModifyTime();
/**
* Retrieves revocation info.
- *
+ *
* @return revocation info
*/
public IRevocationInfo getRevocationInfo();
-}
+}
diff --git a/pki/base/common/src/com/netscape/certsrv/dbs/certdb/ICertRecordList.java b/pki/base/common/src/com/netscape/certsrv/dbs/certdb/ICertRecordList.java
index 616bd5db..438d3a05 100644
--- a/pki/base/common/src/com/netscape/certsrv/dbs/certdb/ICertRecordList.java
+++ b/pki/base/common/src/com/netscape/certsrv/dbs/certdb/ICertRecordList.java
@@ -17,80 +17,77 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.dbs.certdb;
-
import java.util.Enumeration;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.dbs.IElementProcessor;
-
/**
* A class represents a list of certificate records.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public interface ICertRecordList {
/**
* Gets the current index.
- *
+ *
* @return current index
*/
public int getCurrentIndex();
/**
* Retrieves the size of request list.
- *
+ *
* @return size
*/
public int getSize();
/**
* Gets size before jump to index.
- *
+ *
* @return size
*/
public int getSizeBeforeJumpTo();
/**
* Gets size after jump to index.
- *
+ *
* @return size
*/
public int getSizeAfterJumpTo();
/**
* Process certificate record as soon as it is returned.
- *
+ *
* @param startidx starting index
* @param endidx ending index
* @param ep element processor
* @exception EBaseException failed to process cert records
*/
public void processCertRecords(int startidx, int endidx,
- IElementProcessor ep) throws EBaseException;
+ IElementProcessor ep) throws EBaseException;
/**
- * Retrieves requests.
- * It's no good to call this if you didnt check
- * if the startidx, endidx are valid.
- *
+ * Retrieves requests. It's no good to call this if you didnt check if the
+ * startidx, endidx are valid.
+ *
* @param startidx starting index
* @param endidx ending index
* @exception EBaseException failed to retrieve
*/
public Enumeration getCertRecords(int startidx, int endidx)
- throws EBaseException;
+ throws EBaseException;
/**
- * Gets one single record at a time similar to
- * processCertRecords but no extra class needed.
+ * Gets one single record at a time similar to processCertRecords but no
+ * extra class needed.
*
* @param index position of the record to be retrieved
* @return object
* @exception EBaseException failed to retrieve
*/
public ICertRecord getCertRecord(int index)
- throws EBaseException;
+ throws EBaseException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/dbs/certdb/ICertificateRepository.java b/pki/base/common/src/com/netscape/certsrv/dbs/certdb/ICertificateRepository.java
index b913a18c..c4e5ee99 100644
--- a/pki/base/common/src/com/netscape/certsrv/dbs/certdb/ICertificateRepository.java
+++ b/pki/base/common/src/com/netscape/certsrv/dbs/certdb/ICertificateRepository.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.dbs.certdb;
-
import java.math.BigInteger;
import java.security.cert.Certificate;
import java.util.Date;
@@ -32,157 +31,154 @@ import com.netscape.certsrv.base.MetaInfo;
import com.netscape.certsrv.dbs.ModificationSet;
import com.netscape.certsrv.dbs.repository.IRepository;
-
/**
- * An interface represents a CMS certificate repository.
- * It stores all the issued certificate.
+ * An interface represents a CMS certificate repository. It stores all the
+ * issued certificate.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public interface ICertificateRepository extends IRepository {
/**
- * Adds a certificate record to the repository. Each certificate
- * record contains four parts: certificate, meta-attributes,
- * issue information and reovcation information.
+ * Adds a certificate record to the repository. Each certificate record
+ * contains four parts: certificate, meta-attributes, issue information and
+ * reovcation information.
* <P>
- *
+ *
* @param record X.509 certificate
- * @exception EBaseException failed to add new certificate to
- * the repository
+ * @exception EBaseException failed to add new certificate to the repository
*/
public void addCertificateRecord(ICertRecord record)
- throws EBaseException;
+ throws EBaseException;
/**
* Reads the certificate identified by the given serial no.
- *
+ *
* @param serialNo serial number of certificate
* @return certificate
* @exception EBaseException failed to retrieve certificate
*/
public X509CertImpl getX509Certificate(BigInteger serialNo)
- throws EBaseException;
+ throws EBaseException;
/**
* Reads certificate from repository.
- *
+ *
* @param serialNo serial number of certificate
* @return certificate record
* @exception EBaseException failed to retrieve certificate
*/
public ICertRecord readCertificateRecord(BigInteger serialNo)
- throws EBaseException;
+ throws EBaseException;
/**
* Sets certificate status update internal
- *
+ *
* @param requestRepo request repository
* @param interval update interval
* @param listenToCloneModifications enable listening to clone modifications
*/
- public void setCertStatusUpdateInterval(IRepository requestRepo,
- int interval,
- boolean listenToCloneModifications);
+ public void setCertStatusUpdateInterval(IRepository requestRepo,
+ int interval,
+ boolean listenToCloneModifications);
/**
* Updates certificate status now. This is a blocking method.
- *
+ *
* @exception EBaseException failed to update
*/
public void updateCertStatus() throws EBaseException;
/**
* Modifies certificate record.
- *
+ *
* @param serialNo serial number of record
* @param mods modifications
* @exception EBaseException failed to modify
*/
public void modifyCertificateRecord(BigInteger serialNo,
- ModificationSet mods) throws EBaseException;
+ ModificationSet mods) throws EBaseException;
/**
* Checks if the certificate exists in this repository.
- *
+ *
* @param serialNo serial number of certificate
* @return true if it exists
* @exception EBaseException failed to check
*/
public boolean containsCertificate(BigInteger serialNo)
- throws EBaseException;
+ throws EBaseException;
/**
* Deletes certificate from this repository.
- *
+ *
* @param serialNo serial number of certificate
* @exception EBaseException failed to delete
*/
public void deleteCertificateRecord(BigInteger serialNo)
- throws EBaseException;
+ throws EBaseException;
/**
* Marks certificate as revoked.
- *
+ *
* @param id serial number
* @param info revocation information
* @exception EBaseException failed to mark
*/
public void markAsRevoked(BigInteger id, IRevocationInfo info)
- throws EBaseException;
+ throws EBaseException;
/**
* Updates certificate status.
- *
+ *
* @param id serial number
* @param status certificate status
* @exception EBaseException failed to update status
*/
public void updateStatus(BigInteger id, String status)
- throws EBaseException;
+ throws EBaseException;
/**
* Marks certificate as renewable.
- *
+ *
* @param record certificate record to modify
* @exception EBaseException failed to update
*/
public void markCertificateAsRenewable(ICertRecord record)
- throws EBaseException;
+ throws EBaseException;
/**
* Marks certificate as not renewable.
- *
+ *
* @param record certificate record to modify
* @exception EBaseException failed to update
*/
public void markCertificateAsNotRenewable(ICertRecord record)
- throws EBaseException;
+ throws EBaseException;
/**
* Marks certificate as renewed.
- *
+ *
* @param serialNo certificate record to modify
* @exception EBaseException failed to update
*/
public void markCertificateAsRenewed(String serialNo)
- throws EBaseException;
+ throws EBaseException;
/**
* Marks certificate as renewed and notified.
- *
+ *
* @param serialNo certificate record to modify
* @exception EBaseException failed to update
*/
public void markCertificateAsRenewalNotified(String serialNo)
- throws EBaseException;
+ throws EBaseException;
/**
- * Finds a list of certificate records that satisifies
- * the filter.
- * Here is a list of filter
- * attribute can be used:
+ * Finds a list of certificate records that satisifies the filter. Here is a
+ * list of filter attribute can be used:
+ *
* <pre>
* certRecordId
* certMetaInfo
@@ -193,37 +189,36 @@ public interface ICertificateRepository extends IRepository {
* x509Cert.notAfter
* x509Cert.subject
* </pre>
- * The filter should follow RFC1558 LDAP filter syntax.
- * For example,
+ *
+ * The filter should follow RFC1558 LDAP filter syntax. For example,
+ *
* <pre>
* (&(certRecordId=5)(x509Cert.notBefore=934398398))
* </pre>
- *
+ *
* @param filter search filter
* @param maxSize max size to return
* @return a list of certificates
* @exception EBaseException failed to search
*/
public Enumeration searchCertificates(String filter, int maxSize)
- throws EBaseException;
+ throws EBaseException;
/**
- * Finds a list of certificate records that satisifies
- * the filter.
- *
+ * Finds a list of certificate records that satisifies the filter.
+ *
* @param filter search filter
* @param maxSize max size to return
* @param timeLimit timeout value
* @return a list of certificates
* @exception EBaseException failed to search
*/
- public Enumeration searchCertificates(String filter, int maxSize,
- int timeLimit) throws EBaseException;
+ public Enumeration searchCertificates(String filter, int maxSize,
+ int timeLimit) throws EBaseException;
/**
- * Finds a list of certificate records that satisifies
- * the filter.
- *
+ * Finds a list of certificate records that satisifies the filter.
+ *
* @param filter search filter
* @param attrs selected attribute
* @param pageSize page size
@@ -231,12 +226,11 @@ public interface ICertificateRepository extends IRepository {
* @exception EBaseException failed to search
*/
public ICertRecordList findCertRecordsInList(String filter,
- String attrs[], int pageSize) throws EBaseException;
+ String attrs[], int pageSize) throws EBaseException;
/**
- * Finds a list of certificate records that satisifies
- * the filter.
- *
+ * Finds a list of certificate records that satisifies the filter.
+ *
* @param filter search filter
* @param attrs selected attribute
* @param sortKey key to use for sorting the returned elements
@@ -245,13 +239,12 @@ public interface ICertificateRepository extends IRepository {
* @exception EBaseException failed to search
*/
public ICertRecordList findCertRecordsInList(String filter,
- String attrs[], String sortKey, int pageSize)
- throws EBaseException;
+ String attrs[], String sortKey, int pageSize)
+ throws EBaseException;
/**
- * Finds a list of certificate records that satisifies
- * the filter.
- *
+ * Finds a list of certificate records that satisifies the filter.
+ *
* @param filter search filter
* @param attrs selected attribute
* @param jumpTo jump to index
@@ -261,17 +254,16 @@ public interface ICertificateRepository extends IRepository {
* @exception EBaseException failed to search
*/
public ICertRecordList findCertRecordsInList(String filter,
- String attrs[], String jumpTo, String sortKey, int pageSize)
- throws EBaseException;
+ String attrs[], String jumpTo, String sortKey, int pageSize)
+ throws EBaseException;
public ICertRecordList findCertRecordsInList(String filter,
- String attrs[], String jumpTo, boolean hardJumpTo, String sortKey, int pageSize)
- throws EBaseException;
+ String attrs[], String jumpTo, boolean hardJumpTo, String sortKey, int pageSize)
+ throws EBaseException;
/**
- * Finds a list of certificate records that satisifies
- * the filter.
- *
+ * Finds a list of certificate records that satisifies the filter.
+ *
* @param filter search filter
* @param attrs selected attribute
* @param jumpTo jump to index
@@ -281,120 +273,119 @@ public interface ICertificateRepository extends IRepository {
* @exception EBaseException failed to search
*/
public ICertRecordList findCertRecordsInListRawJumpto(String filter,
- String attrs[], String jumpTo, String sortKey, int pageSize)
- throws EBaseException;
+ String attrs[], String jumpTo, String sortKey, int pageSize)
+ throws EBaseException;
public static final int ALL_CERTS = 0;
public static final int ALL_VALID_CERTS = 1;
public static final int ALL_UNREVOKED_CERTS = 2;
/**
- * Gets all valid and unexpired certificates pertaining
- * to a subject DN.
- *
- * @param subjectDN The distinguished name of the subject.
- * @param validityType The type of certificatese to retrieve.
+ * Gets all valid and unexpired certificates pertaining to a subject DN.
+ *
+ * @param subjectDN The distinguished name of the subject.
+ * @param validityType The type of certificatese to retrieve.
* @return An array of certificates.
* @throws EBaseException on error.
*/
public X509CertImpl[] getX509Certificates(String subjectDN,
- int validityType) throws EBaseException;
+ int validityType) throws EBaseException;
/**
* Retrieves all the revoked certificates that have not expired.
- *
+ *
* @param asOfDate as of date
* @return a list of revoked certificates
* @exception EBaseException failed to retrieve
*/
public Enumeration getRevokedCertificates(Date asOfDate)
- throws EBaseException;
+ throws EBaseException;
/**
- * Retrieves all revoked certificates including ones that have expired
- * or that are not yet valid.
- *
+ * Retrieves all revoked certificates including ones that have expired or
+ * that are not yet valid.
+ *
* @return a list of revoked certificates
* @exception EBaseException failed to search
*/
public Enumeration getAllRevokedCertificates()
- throws EBaseException;
+ throws EBaseException;
/**
* Retrieves all revoked but not expired certificates.
- *
+ *
* @return a list of revoked certificates
* @exception EBaseException failed to search
*/
public Enumeration getAllRevokedNonExpiredCertificates()
- throws EBaseException;
+ throws EBaseException;
/**
- * Finds all certificates given a filter.
- *
+ * Finds all certificates given a filter.
+ *
* @param filter search filter
* @return a list of certificates
* @exception EBaseException failed to search
*/
public Enumeration findCertificates(String filter)
- throws EBaseException;
+ throws EBaseException;
/**
* Finds all certificate records given a filter.
- *
+ *
* @param filter search filter
* @return a list of certificates
* @exception EBaseException failed to search
*/
public Enumeration findCertRecords(String filter)
- throws EBaseException;
+ throws EBaseException;
/**
- * Gets Revoked certs orderes by noAfter date, jumps to records
- * where notAfter date is greater than current.
- *
+ * Gets Revoked certs orderes by noAfter date, jumps to records where
+ * notAfter date is greater than current.
+ *
* @param date reference date
* @param pageSize page size
* @return a list of certificate records
* @exception EBaseException failed to retrieve
*/
- public ICertRecordList getRevokedCertsByNotAfterDate(Date date,
- int pageSize) throws EBaseException;
+ public ICertRecordList getRevokedCertsByNotAfterDate(Date date,
+ int pageSize) throws EBaseException;
/**
- * Gets Invalid certs orderes by noAfter date, jumps to records
- * where notAfter date is greater than current.
- *
+ * Gets Invalid certs orderes by noAfter date, jumps to records where
+ * notAfter date is greater than current.
+ *
* @param date reference date
* @param pageSize page size
* @return a list of certificate records
* @exception EBaseException failed to retrieve
*/
- public ICertRecordList getInvalidCertsByNotBeforeDate(Date date,
- int pageSize) throws EBaseException;
+ public ICertRecordList getInvalidCertsByNotBeforeDate(Date date,
+ int pageSize) throws EBaseException;
/**
- * Gets valid certs orderes by noAfter date, jumps to records
- * where notAfter date is greater than current.
- *
+ * Gets valid certs orderes by noAfter date, jumps to records where notAfter
+ * date is greater than current.
+ *
* @param date reference date
* @param pageSize page size
* @return a list of certificate records
* @exception EBaseException failed to retrieve
*/
- public ICertRecordList getValidCertsByNotAfterDate(Date date,
- int pageSize) throws EBaseException;
+ public ICertRecordList getValidCertsByNotAfterDate(Date date,
+ int pageSize) throws EBaseException;
/**
* Creates certificate record.
- *
+ *
* @param id serial number
* @param cert certificate
* @param meta meta information
* @return certificate record
*/
- public ICertRecord createCertRecord(BigInteger id,
- Certificate cert, MetaInfo meta);
+ public ICertRecord createCertRecord(BigInteger id,
+ Certificate cert, MetaInfo meta);
/**
* Finds certificate records.
@@ -404,21 +395,21 @@ public interface ICertificateRepository extends IRepository {
* @exception EBaseException failed to retrieve cert records
*/
public Enumeration findCertRecs(String filter)
- throws EBaseException;
+ throws EBaseException;
/**
* Retrieves renewable certificates.
- *
+ *
* @param renewalTime renewal time
* @return certificates
* @exception EBaseException failed to retrieve
*/
public Hashtable getRenewableCertificates(String renewalTime)
- throws EBaseException;
+ throws EBaseException;
/**
* Unmark a revoked certificates.
- *
+ *
* @param id serial number
* @param info revocation information
* @param revokedOn revocation date
@@ -426,85 +417,85 @@ public interface ICertificateRepository extends IRepository {
* @exception EBaseException failed to unmark
*/
public void unmarkRevoked(BigInteger id, IRevocationInfo info,
- Date revokedOn, String revokedBy)
- throws EBaseException;
+ Date revokedOn, String revokedBy)
+ throws EBaseException;
/**
* Retrieves valid and not published certificates.
- *
+ *
* @param from starting serial number
* @param to ending serial number
* @return a list of certificates
* @exception EBaseException failed to retrieve
*/
public Enumeration getValidNotPublishedCertificates(String from, String to)
- throws EBaseException;
+ throws EBaseException;
/**
* Retrieves expired and published certificates.
- *
+ *
* @param from starting serial number
* @param to ending serial number
* @return a list of certificates
* @exception EBaseException failed to retrieve
*/
public Enumeration getExpiredPublishedCertificates(String from, String to)
- throws EBaseException;
+ throws EBaseException;
/**
* Retrieves revoked and published certificates.
- *
+ *
* @param from starting serial number
* @param to ending serial number
* @return a list of certificates
* @exception EBaseException failed to retrieve
*/
public Enumeration getRevokedPublishedCertificates(String from, String to)
- throws EBaseException;
+ throws EBaseException;
/**
* Retrieves valid certificates.
- *
+ *
* @param from starting serial number
* @param to ending serial number
* @return a list of certificates
* @exception EBaseException failed to retrieve
*/
public Enumeration getValidCertificates(String from, String to)
- throws EBaseException;
+ throws EBaseException;
/**
* Retrieves expired certificates.
- *
+ *
* @param from starting serial number
* @param to ending serial number
* @return a list of certificates
* @exception EBaseException failed to retrieve
*/
public Enumeration getExpiredCertificates(String from, String to)
- throws EBaseException;
+ throws EBaseException;
/**
* Retrieves revoked certificates.
- *
+ *
* @param from starting serial number
* @param to ending serial number
* @return a list of certificates
* @exception EBaseException failed to retrieve
*/
public Enumeration getRevokedCertificates(String from, String to)
- throws EBaseException;
+ throws EBaseException;
/**
* Retrieves modified certificate records.
- *
+ *
* @param entry LDAPEntry with modified data
*/
- public void getModifications(LDAPEntry entry);
+ public void getModifications(LDAPEntry entry);
/**
* Removes certificate records with this repository.
- *
+ *
* @param beginS BigInteger with radix 16
* @param endS BigInteger with radix 16
*/
diff --git a/pki/base/common/src/com/netscape/certsrv/dbs/certdb/IRevocationInfo.java b/pki/base/common/src/com/netscape/certsrv/dbs/certdb/IRevocationInfo.java
index 2086cacb..b2a08087 100644
--- a/pki/base/common/src/com/netscape/certsrv/dbs/certdb/IRevocationInfo.java
+++ b/pki/base/common/src/com/netscape/certsrv/dbs/certdb/IRevocationInfo.java
@@ -17,32 +17,30 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.dbs.certdb;
-
import java.util.Date;
import netscape.security.x509.CRLExtensions;
-
/**
- * A class represents a certificate revocation info. This
- * object is written as an attribute of certificate record
- * which essentially signifies a revocation act.
+ * A class represents a certificate revocation info. This object is written as
+ * an attribute of certificate record which essentially signifies a revocation
+ * act.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IRevocationInfo {
/**
* Retrieves revocation date.
- *
+ *
* @return revocation date
*/
public Date getRevocationDate();
/**
* Retrieves CRL entry extensions.
- *
+ *
* @return CRL entry extensions
*/
public CRLExtensions getCRLEntryExtensions();
diff --git a/pki/base/common/src/com/netscape/certsrv/dbs/crldb/ICRLIssuingPointRecord.java b/pki/base/common/src/com/netscape/certsrv/dbs/crldb/ICRLIssuingPointRecord.java
index 78acced0..f1093d2b 100644
--- a/pki/base/common/src/com/netscape/certsrv/dbs/crldb/ICRLIssuingPointRecord.java
+++ b/pki/base/common/src/com/netscape/certsrv/dbs/crldb/ICRLIssuingPointRecord.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.dbs.crldb;
-
import java.math.BigInteger;
import java.util.Date;
import java.util.Hashtable;
@@ -26,11 +25,9 @@ import netscape.security.x509.RevokedCertificate;
import com.netscape.certsrv.dbs.IDBObj;
-
/**
- * An interface that defines abilities of
- * a CRL issuing point record.
- *
+ * An interface that defines abilities of a CRL issuing point record.
+ *
* @version $Revision$, $Date$
*/
public interface ICRLIssuingPointRecord extends IDBObj {
@@ -52,111 +49,112 @@ public interface ICRLIssuingPointRecord extends IDBObj {
public static final String ATTR_DELTA_CRL = "deltaRevocationList";
public static final String CLEAN_CACHE = "-1";
- public static final String NEW_CACHE = "-2";
+ public static final String NEW_CACHE = "-2";
/**
* Retrieve unique CRL identifier.
- *
+ *
* @return unique CRL identifier
*/
public String getId();
/**
* Retrieves current CRL number out of CRL issuing point record.
- *
+ *
* @return current CRL number
*/
public BigInteger getCRLNumber();
/**
* Retrieves CRL size measured by the number of entries.
- *
+ *
* @return CRL size
*/
public Long getCRLSize();
/**
* Retrieves this update time.
- *
+ *
* @return time of this update
*/
public Date getThisUpdate();
/**
* Retrieves next update time.
- *
+ *
* @return time of next update
*/
public Date getNextUpdate();
/**
* Retrieves current delta CRL number out of CRL issuing point record.
- *
+ *
* @return current delta CRL number
*/
public BigInteger getDeltaCRLNumber();
/**
* Retrieves delta CRL size measured by the number of entries.
- *
+ *
* @return delta CRL size
*/
public Long getDeltaCRLSize();
/**
* Retrieve Retrieve reference to the first unsaved data.
- *
+ *
* @return reference to the first unsaved data
*/
public String getFirstUnsaved();
/**
* Retrieves encoded CRL.
- *
+ *
* @return encoded CRL
*/
public byte[] getCRL();
/**
* Retrieves encoded delta CRL.
- *
+ *
* @return encoded delta CRL
*/
public byte[] getDeltaCRL();
/**
* Retrieves encoded CA certificate.
- *
+ *
* @return encoded CA certificate
*/
public byte[] getCACert();
/**
* Retrieves cache information about CRL.
- *
+ *
* @return list of recently revoked certificates
*/
- public Hashtable<BigInteger,RevokedCertificate> getCRLCacheNoClone();
- public Hashtable<BigInteger,RevokedCertificate> getCRLCache();
+ public Hashtable<BigInteger, RevokedCertificate> getCRLCacheNoClone();
+
+ public Hashtable<BigInteger, RevokedCertificate> getCRLCache();
/**
* Retrieves cache information about revoked certificates.
- *
+ *
* @return list of recently revoked certificates
*/
- public Hashtable<BigInteger,RevokedCertificate> getRevokedCerts();
+ public Hashtable<BigInteger, RevokedCertificate> getRevokedCerts();
/**
* Retrieves cache information about certificates released from hold.
- *
+ *
* @return list of certificates recently released from hold
*/
- public Hashtable<BigInteger,RevokedCertificate> getUnrevokedCerts();
+ public Hashtable<BigInteger, RevokedCertificate> getUnrevokedCerts();
/**
* Retrieves cache information about expired certificates.
- *
+ *
* @return list of recently expired certificates
*/
- public Hashtable<BigInteger,RevokedCertificate> getExpiredCerts();
+ public Hashtable<BigInteger, RevokedCertificate> getExpiredCerts();
}
diff --git a/pki/base/common/src/com/netscape/certsrv/dbs/crldb/ICRLRepository.java b/pki/base/common/src/com/netscape/certsrv/dbs/crldb/ICRLRepository.java
index ba245bcf..b685bca0 100644
--- a/pki/base/common/src/com/netscape/certsrv/dbs/crldb/ICRLRepository.java
+++ b/pki/base/common/src/com/netscape/certsrv/dbs/crldb/ICRLRepository.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.dbs.crldb;
-
import java.math.BigInteger;
import java.util.Date;
import java.util.Hashtable;
@@ -26,63 +25,63 @@ import java.util.Vector;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.dbs.ModificationSet;
-
/**
- * An interface represents a CMS CRL repository. It stores
- * all the CRL issuing points.
- *
+ * An interface represents a CMS CRL repository. It stores all the CRL issuing
+ * points.
+ *
* @version $Revision$, $Date$
*/
public interface ICRLRepository {
/**
* Adds CRL issuing point record.
- *
+ *
* @param rec issuing point record
* @exception EBaseException failed to add new issuing point record
*/
public void addCRLIssuingPointRecord(ICRLIssuingPointRecord rec)
- throws EBaseException;
+ throws EBaseException;
/**
* Retrieves all the issuing points' names.
- *
+ *
* @return A list of issuing points' names.
- * @exception EBaseException failed to retrieve all the issuing points' names.
+ * @exception EBaseException failed to retrieve all the issuing points'
+ * names.
*/
public Vector getIssuingPointsNames() throws EBaseException;
/**
* Reads issuing point record.
- *
+ *
* @return issuing point record
* @exception EBaseException failed to read issuing point record
*/
public ICRLIssuingPointRecord readCRLIssuingPointRecord(String id)
- throws EBaseException;
+ throws EBaseException;
/**
* Deletes issuing point record.
- *
+ *
* @param id issuing point record id
* @exception EBaseException failed to delete issuing point record
*/
public void deleteCRLIssuingPointRecord(String id)
- throws EBaseException;
+ throws EBaseException;
/**
* Modifies issuing point record.
- *
+ *
* @param id issuing point record id
* @param mods set of modifications
* @exception EBaseException failed to modify issuing point record
*/
public void modifyCRLIssuingPointRecord(String id, ModificationSet mods)
- throws EBaseException;
+ throws EBaseException;
/**
* Updates CRL issuing point record.
- *
+ *
* @param id issuing point record id
* @param newCRL encoded binary CRL
* @param thisUpdate time of this update
@@ -92,12 +91,12 @@ public interface ICRLRepository {
* @exception EBaseException failed to update issuing point record
*/
public void updateCRLIssuingPointRecord(String id, byte[] newCRL,
- Date thisUpdate, Date nextUpdate, BigInteger crlNumber, Long crlSize)
- throws EBaseException;
+ Date thisUpdate, Date nextUpdate, BigInteger crlNumber, Long crlSize)
+ throws EBaseException;
/**
* Updates CRL issuing point record.
- *
+ *
* @param id issuing point record id
* @param newCRL encoded binary CRL
* @param thisUpdate time of this update
@@ -110,34 +109,34 @@ public interface ICRLRepository {
* @exception EBaseException failed to update issuing point record
*/
public void updateCRLIssuingPointRecord(String id, byte[] newCRL,
- Date thisUpdate, Date nextUpdate, BigInteger crlNumber, Long crlSize,
- Hashtable revokedCerts, Hashtable unrevokedCerts, Hashtable expiredCerts)
- throws EBaseException;
+ Date thisUpdate, Date nextUpdate, BigInteger crlNumber, Long crlSize,
+ Hashtable revokedCerts, Hashtable unrevokedCerts, Hashtable expiredCerts)
+ throws EBaseException;
/**
* Updates CRL issuing point record.
- *
+ *
* @param id issuing point record id
* @param revokedCerts list of revoked certificates
* @param unrevokedCerts list of released from hold certificates
* @exception EBaseException failed to update issuing point record
*/
public void updateRevokedCerts(String id, Hashtable revokedCerts, Hashtable unrevokedCerts)
- throws EBaseException;
+ throws EBaseException;
/**
* Updates CRL issuing point record.
- *
+ *
* @param id issuing point record id
* @param expiredCerts list of expired certificates
* @exception EBaseException failed to update issuing point record
*/
public void updateExpiredCerts(String id, Hashtable expiredCerts)
- throws EBaseException;
+ throws EBaseException;
/**
* Updates CRL issuing point record.
- *
+ *
* @param id issuing point record id
* @param crlSize CRL size
* @param revokedCerts list of revoked certificates
@@ -146,14 +145,14 @@ public interface ICRLRepository {
* @exception EBaseException failed to update issuing point record
*/
public void updateCRLCache(String id, Long crlSize,
- Hashtable revokedCerts,
- Hashtable unrevokedCerts,
- Hashtable expiredCerts)
- throws EBaseException;
+ Hashtable revokedCerts,
+ Hashtable unrevokedCerts,
+ Hashtable expiredCerts)
+ throws EBaseException;
/**
* Updates CRL issuing point record with delta-CRL.
- *
+ *
* @param id issuing point record id
* @param deltaCRLNumber delta CRL number
* @param deltaCRLSize delta CRL size
@@ -164,16 +163,16 @@ public interface ICRLRepository {
public void updateDeltaCRL(String id, BigInteger deltaCRLNumber,
Long deltaCRLSize, Date nextUpdate,
byte[] deltaCRL)
- throws EBaseException;
+ throws EBaseException;
/**
- * Updates CRL issuing point record with reference to the first
- * unsaved data.
- *
+ * Updates CRL issuing point record with reference to the first unsaved
+ * data.
+ *
* @param id issuing point record id
* @param firstUnsaved reference to the first unsaved data
* @exception EBaseException failed to update issuing point record
*/
public void updateFirstUnsaved(String id, String firstUnsaved)
- throws EBaseException;
+ throws EBaseException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/dbs/keydb/IKeyRecord.java b/pki/base/common/src/com/netscape/certsrv/dbs/keydb/IKeyRecord.java
index 0edcc187..010661d8 100644
--- a/pki/base/common/src/com/netscape/certsrv/dbs/keydb/IKeyRecord.java
+++ b/pki/base/common/src/com/netscape/certsrv/dbs/keydb/IKeyRecord.java
@@ -17,16 +17,14 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.dbs.keydb;
-
import java.math.BigInteger;
import java.util.Date;
import com.netscape.certsrv.base.EBaseException;
-
/**
* An interface contains constants for key record.
- *
+ *
* @version $Revision$, $Date$
*/
public interface IKeyRecord {
@@ -42,15 +40,15 @@ public interface IKeyRecord {
public static final String ATTR_MODIFY_TIME = "keyModifyTime";
public static final String ATTR_META_INFO = "keyMetaInfo";
public static final String ATTR_ARCHIVED_BY = "keyArchivedBy";
-
+
// key state
public static final String STATUS_ANY = "ANY";
public static final String STATUS_VALID = "VALID";
public static final String STATUS_INVALID = "INVALID";
-
+
/**
* Retrieves the state of the key.
- *
+ *
* @return key state
* @exception EBaseException failed to retrieve state of the key
*/
@@ -58,15 +56,15 @@ public interface IKeyRecord {
/**
* Retrieves key identifier.
- *
+ *
* @return key id
* @exception EBaseException failed to retrieve key id
*/
- public BigInteger getSerialNumber() throws EBaseException;
+ public BigInteger getSerialNumber() throws EBaseException;
/**
* Retrieves key owner name.
- *
+ *
* @return key owner name
* @exception EBaseException failed to retrieve key owner name
*/
@@ -74,53 +72,53 @@ public interface IKeyRecord {
/**
* Retrieves key algorithm.
- *
+ *
* @return key algorithm
*/
- public String getAlgorithm();
+ public String getAlgorithm();
/**
* Retrieves key length.
- *
+ *
* @return key length
* @exception EBaseException failed to retrieve key length
*/
- public Integer getKeySize() throws EBaseException;
+ public Integer getKeySize() throws EBaseException;
/**
* Retrieves archiver identifier.
- *
+ *
* @return archiver uid
*/
- public String getArchivedBy();
+ public String getArchivedBy();
/**
* Retrieves creation time.
- *
+ *
* @return creation time
*/
- public Date getCreateTime();
+ public Date getCreateTime();
/**
* Retrieves last modification time.
- *
+ *
* @return modification time
*/
- public Date getModifyTime();
+ public Date getModifyTime();
/**
* Retrieves dates of recovery.
- *
+ *
* @return recovery history
* @exception EBaseException failed to retrieve recovery history
*/
- public Date[] getDateOfRevocation() throws EBaseException;
+ public Date[] getDateOfRevocation() throws EBaseException;
/**
* Retrieves public key data.
- *
+ *
* @return public key data
* @exception EBaseException failed to retrieve public key data
*/
public byte[] getPublicKeyData() throws EBaseException;
-}
+}
diff --git a/pki/base/common/src/com/netscape/certsrv/dbs/keydb/IKeyRecordList.java b/pki/base/common/src/com/netscape/certsrv/dbs/keydb/IKeyRecordList.java
index 5da23945..75f83389 100644
--- a/pki/base/common/src/com/netscape/certsrv/dbs/keydb/IKeyRecordList.java
+++ b/pki/base/common/src/com/netscape/certsrv/dbs/keydb/IKeyRecordList.java
@@ -17,35 +17,33 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.dbs.keydb;
-
import java.util.Enumeration;
import com.netscape.certsrv.base.EBaseException;
-
/**
* A class represents a list of key records.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IKeyRecordList {
/**
- * Retrieves the size of key list.
- *
+ * Retrieves the size of key list.
+ *
* @return size of key list
*/
public int getSize();
/**
* Retrieves key records.
- *
+ *
* @param startidx start index
* @param endidx end index
* @return key records
* @exception EBaseException failed to retrieve key records
*/
public Enumeration<IKeyRecord> getKeyRecords(int startidx, int endidx)
- throws EBaseException;
+ throws EBaseException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/dbs/keydb/IKeyRepository.java b/pki/base/common/src/com/netscape/certsrv/dbs/keydb/IKeyRepository.java
index 093bea25..5feaf932 100644
--- a/pki/base/common/src/com/netscape/certsrv/dbs/keydb/IKeyRepository.java
+++ b/pki/base/common/src/com/netscape/certsrv/dbs/keydb/IKeyRepository.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.dbs.keydb;
-
import java.math.BigInteger;
import java.security.PublicKey;
import java.util.Enumeration;
@@ -28,12 +27,11 @@ import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.dbs.ModificationSet;
import com.netscape.certsrv.dbs.repository.IRepository;
-
/**
- * An interface represents a Key repository. This is the
- * container of archived keys.
+ * An interface represents a Key repository. This is the container of archived
+ * keys.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IKeyRepository extends IRepository {
@@ -41,7 +39,7 @@ public interface IKeyRepository extends IRepository {
/**
* Archives a key to the repository.
* <P>
- *
+ *
* @param record key record
* @exception EBaseException failed to archive key
*/
@@ -50,61 +48,60 @@ public interface IKeyRepository extends IRepository {
/**
* Reads an archived key by serial number.
* <P>
- *
+ *
* @param serialNo serial number
* @return key record
* @exception EBaseException failed to recover key
*/
public IKeyRecord readKeyRecord(BigInteger serialNo)
- throws EBaseException;
+ throws EBaseException;
/**
* Reads an archived key by b64 encoded cert.
* <P>
- *
+ *
* @param cert b64 encoded cert
* @return key record
* @exception EBaseException failed to recover key
*/
public IKeyRecord readKeyRecord(String cert)
- throws EBaseException;
+ throws EBaseException;
/**
* Reads an archived key by owner name.
* <P>
- *
+ *
* @param ownerName owner name
* @return key record
* @exception EBaseException failed to recover key
*/
public IKeyRecord readKeyRecord(X500Name ownerName)
- throws EBaseException;
+ throws EBaseException;
/**
* Reads archived key using public key.
- *
- * @param publicKey public key that is corresponding
- * to the private key
+ *
+ * @param publicKey public key that is corresponding to the private key
* @return key record
* @exception EBaseException failed to read key
*/
public IKeyRecord readKeyRecord(PublicKey publicKey)
- throws EBaseException;
+ throws EBaseException;
/**
* Searches for private keys.
- *
+ *
* @param filter LDAP filter for the search
* @param maxSize maximium number of entries to be returned
* @return a list of private key records
* @exception EBaseException failed to search keys
*/
public Enumeration searchKeys(String filter, int maxSize)
- throws EBaseException;
+ throws EBaseException;
/**
* Searches for private keys.
- *
+ *
* @param filter LDAP filter for the search
* @param maxSize maximium number of entries to be returned
* @param timeLimt timeout value
@@ -112,30 +109,31 @@ public interface IKeyRepository extends IRepository {
* @exception EBaseException failed to search keys
*/
public Enumeration searchKeys(String filter, int maxSize, int timeLimt)
- throws EBaseException;
+ throws EBaseException;
/**
* Deletes a key record.
- *
+ *
* @param serialno key identifier
* @exception EBaseException failed to delete key record
*/
public void deleteKeyRecord(BigInteger serialno)
- throws EBaseException;
+ throws EBaseException;
/**
* Modifies key record in this repository.
- *
+ *
* @param serialNo key identifier
* @param mods modification of key records
* @exception EBaseException failed to modify key record
*/
public void modifyKeyRecord(BigInteger serialNo,
- ModificationSet mods) throws EBaseException;
+ ModificationSet mods) throws EBaseException;
/**
- * Searchs for a list of key records.
- * Here is a list of supported filter attributes:
+ * Searchs for a list of key records. Here is a list of supported filter
+ * attributes:
+ *
* <pre>
* keySerialNumber
* keyState
@@ -149,7 +147,7 @@ public interface IKeyRepository extends IRepository {
* keyModifyTime
* keyMetaInfo
* </pre>
- *
+ *
* @param filter search filter
* @param attrs list of attributes to be returned
* @param pageSize virtual list page size
@@ -157,11 +155,11 @@ public interface IKeyRepository extends IRepository {
* @exception EBaseException failed to search key records
*/
public IKeyRecordList findKeyRecordsInList(String filter,
- String attrs[], int pageSize) throws EBaseException;
+ String attrs[], int pageSize) throws EBaseException;
/**
* Searchs for a list of key records.
- *
+ *
* @param filter search filter
* @param attrs list of attributes to be returned
* @param sortKey name of attribute that the list should be sorted by
@@ -170,6 +168,6 @@ public interface IKeyRepository extends IRepository {
* @exception EBaseException failed to search key records
*/
public IKeyRecordList findKeyRecordsInList(String filter,
- String attrs[], String sortKey, int pageSize)
- throws EBaseException;
+ String attrs[], String sortKey, int pageSize)
+ throws EBaseException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/dbs/keydb/KeyState.java b/pki/base/common/src/com/netscape/certsrv/dbs/keydb/KeyState.java
index e4baf91e..3ab0bd3a 100644
--- a/pki/base/common/src/com/netscape/certsrv/dbs/keydb/KeyState.java
+++ b/pki/base/common/src/com/netscape/certsrv/dbs/keydb/KeyState.java
@@ -17,15 +17,13 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.dbs.keydb;
-
import java.io.Serializable;
-
/**
- * A class represents key state. This object is to
- * encapsulate the life cycle of a key.
+ * A class represents key state. This object is to encapsulate the life cycle of
+ * a key.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public final class KeyState implements Serializable {
@@ -42,62 +40,67 @@ public final class KeyState implements Serializable {
private KeyState(int code) {
mStateCode = code;
}
-
+
/**
* Request state.
*/
- public final static KeyState ANY = new KeyState(-1);
+ public final static KeyState ANY = new KeyState(-1);
public final static KeyState VALID = new KeyState(0);
public final static KeyState INVALID = new KeyState(1);
-
+
/**
* Checks if the given object equals to this object.
- *
+ *
* @param other object to be compared
* @return true if both objects are the same
*/
public boolean equals(Object other) {
- if (this == other)
+ if (this == other)
return true;
else if (other instanceof KeyState)
return ((KeyState) other).mStateCode == mStateCode;
- else
+ else
return false;
}
/**
* Returns the hash code.
- *
+ *
* @return hash code
*/
public int hashCode() {
return mStateCode;
}
-
+
/**
* Return the string-representation of this object.
- *
+ *
* @return string value
*/
public String toString() {
- if (mStateCode == -1) return "ANY";
- if (mStateCode == 0) return "VALID";
- if (mStateCode == 1) return "INVAILD";
+ if (mStateCode == -1)
+ return "ANY";
+ if (mStateCode == 0)
+ return "VALID";
+ if (mStateCode == 1)
+ return "INVAILD";
return "[UNDEFINED]";
-
+
}
/**
* Converts a string into a key state object.
- *
+ *
* @param state state in string-representation
* @return key state object
*/
public static KeyState toKeyState(String state) {
- if (state.equalsIgnoreCase("ANY")) return ANY;
- if (state.equalsIgnoreCase("VALID")) return VALID;
- if (state.equalsIgnoreCase("INVALID")) return INVALID;
+ if (state.equalsIgnoreCase("ANY"))
+ return ANY;
+ if (state.equalsIgnoreCase("VALID"))
+ return VALID;
+ if (state.equalsIgnoreCase("INVALID"))
+ return INVALID;
return null;
}
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/dbs/replicadb/IReplicaIDRepository.java b/pki/base/common/src/com/netscape/certsrv/dbs/replicadb/IReplicaIDRepository.java
index 660b6e9e..25953c3d 100644
--- a/pki/base/common/src/com/netscape/certsrv/dbs/replicadb/IReplicaIDRepository.java
+++ b/pki/base/common/src/com/netscape/certsrv/dbs/replicadb/IReplicaIDRepository.java
@@ -19,12 +19,11 @@ package com.netscape.certsrv.dbs.replicadb;
import com.netscape.certsrv.dbs.repository.IRepository;
-
/**
- * An interface represents a ReplicaID Repository.
- * It provides unique managed replica IDs.
+ * An interface represents a ReplicaID Repository. It provides unique managed
+ * replica IDs.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IReplicaIDRepository extends IRepository {
diff --git a/pki/base/common/src/com/netscape/certsrv/dbs/repository/IRepository.java b/pki/base/common/src/com/netscape/certsrv/dbs/repository/IRepository.java
index 5ff90241..707eb813 100644
--- a/pki/base/common/src/com/netscape/certsrv/dbs/repository/IRepository.java
+++ b/pki/base/common/src/com/netscape/certsrv/dbs/repository/IRepository.java
@@ -22,18 +22,18 @@ import java.math.BigInteger;
import com.netscape.certsrv.base.EBaseException;
/**
- * An interface represents a generic repository. It maintains unique
- * serial number within repository.
+ * An interface represents a generic repository. It maintains unique serial
+ * number within repository.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IRepository {
/**
- * Retrieves the next serial number, and also increase the
- * serial number by one.
- *
+ * Retrieves the next serial number, and also increase the serial number by
+ * one.
+ *
* @return serial number
* @exception EBaseException failed to retrieve next serial number
*/
@@ -58,30 +58,30 @@ public interface IRepository {
* @param serial maximum number
* @exception EBaseException failed to set maximum serial number
*/
- public void setMaxSerial (String serial) throws EBaseException;
-
+ public void setMaxSerial(String serial) throws EBaseException;
+
/**
* Set the maximum serial number in next range.
*
* @param serial maximum number
- * @exception EBaseException failed to set maximum serial number in next range
+ * @exception EBaseException failed to set maximum serial number in next
+ * range
*/
public void setNextMaxSerial(String serial) throws EBaseException;
/**
- * Checks to see if a new range is needed, or if we have reached the end of the
- * current range, or if a range conflict has occurred.
+ * Checks to see if a new range is needed, or if we have reached the end of
+ * the current range, or if a range conflict has occurred.
*
* @exception EBaseException failed to check next range for conflicts
*/
public void checkRanges() throws EBaseException;
- /**
- * Sets whether serial number management is enabled for certs
- * and requests.
- *
- * @param value true/false
- * @exception EBaseException failed to set
+ /**
+ * Sets whether serial number management is enabled for certs and requests.
+ *
+ * @param value true/false
+ * @exception EBaseException failed to set
*/
public void setEnableSerialMgmt(boolean value) throws EBaseException;
diff --git a/pki/base/common/src/com/netscape/certsrv/dbs/repository/IRepositoryRecord.java b/pki/base/common/src/com/netscape/certsrv/dbs/repository/IRepositoryRecord.java
index 326ea466..7eac4173 100644
--- a/pki/base/common/src/com/netscape/certsrv/dbs/repository/IRepositoryRecord.java
+++ b/pki/base/common/src/com/netscape/certsrv/dbs/repository/IRepositoryRecord.java
@@ -22,23 +22,23 @@ import java.math.BigInteger;
import com.netscape.certsrv.dbs.IDBObj;
/**
- * An interface represents a generic repository record.
- * It maintains unique serial number within repository.
+ * An interface represents a generic repository record. It maintains unique
+ * serial number within repository.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IRepositoryRecord extends IDBObj {
- public final static String ATTR_SERIALNO = "serialNo";
- public final static String ATTR_PUB_STATUS = "publishingStatus";
+ public final static String ATTR_SERIALNO = "serialNo";
+ public final static String ATTR_PUB_STATUS = "publishingStatus";
- /**
- * Retrieves serial number.
- *
- * @return serial number
- */
- public BigInteger getSerialNumber();
+ /**
+ * Retrieves serial number.
+ *
+ * @return serial number
+ */
+ public BigInteger getSerialNumber();
- public String getPublishingStatus();
+ public String getPublishingStatus();
}
diff --git a/pki/base/common/src/com/netscape/certsrv/evaluators/IAccessEvaluator.java b/pki/base/common/src/com/netscape/certsrv/evaluators/IAccessEvaluator.java
index 8c291447..f2b25ab3 100644
--- a/pki/base/common/src/com/netscape/certsrv/evaluators/IAccessEvaluator.java
+++ b/pki/base/common/src/com/netscape/certsrv/evaluators/IAccessEvaluator.java
@@ -17,16 +17,14 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.evaluators;
-
import com.netscape.certsrv.authentication.IAuthToken;
-
/**
- * A class represents an evaluator. An evaluator is used to
- * evaluate an expression. For example, one can write an evaluator to
- * evaluate if a user belongs to a certain group. An evaluator is
- * generally used for access control expression evaluation, however, it
- * can be used for other evaluation-related operations.
+ * A class represents an evaluator. An evaluator is used to evaluate an
+ * expression. For example, one can write an evaluator to evaluate if a user
+ * belongs to a certain group. An evaluator is generally used for access control
+ * expression evaluation, however, it can be used for other evaluation-related
+ * operations.
* <P>
*
* @version $Revision$, $Date$
@@ -39,47 +37,50 @@ public interface IAccessEvaluator {
public void init();
/**
- * Gets the type of the evaluator. Type is defined by each
- * evaluator plugin. Each evaluator plugin should have a unique type.
+ * Gets the type of the evaluator. Type is defined by each evaluator plugin.
+ * Each evaluator plugin should have a unique type.
+ *
* @return type of the evaluator
*/
public String getType();
/**
* Gets the description of the evaluator
+ *
* @return a text description for this evaluator
*/
public String getDescription();
/**
- * Evaluates if the given value satisfies the access
- * control in current context.
+ * Evaluates if the given value satisfies the access control in current
+ * context.
+ *
* @param type Type of the evaluator, eg, user, group etc
* @param op Operator of the evaluator, eg, =, !=
- * @param value Part of the expression that can be used to
- * evaluate, e.g, value can be the name of the group if the
- * purpose of the evaluator is to evaluate if the user is a member
- * of the group.
+ * @param value Part of the expression that can be used to evaluate, e.g,
+ * value can be the name of the group if the purpose of the
+ * evaluator is to evaluate if the user is a member of the group.
* @return true if the evaluation expression is matched; false otherwise.
*/
public boolean evaluate(String type, String op, String value);
/**
- * Evaluates if the given value satisfies the access
- * control in authToken obtained from Authentication.
+ * Evaluates if the given value satisfies the access control in authToken
+ * obtained from Authentication.
+ *
* @param authToken Authentication token
* @param type Type of the evaluator, eg, user, group etc
* @param op Operator of the evaluator, eg, =, !=
- * @param value Part of the expression that can be used to
- * evaluate, e.g, value can be the name of the group if the
- * purpose of the evaluator is to evaluate if the user is a member
- * of the group.
+ * @param value Part of the expression that can be used to evaluate, e.g,
+ * value can be the name of the group if the purpose of the
+ * evaluator is to evaluate if the user is a member of the group.
* @return true if the evaluation expression is matched; false otherwise.
*/
public boolean evaluate(IAuthToken authToken, String type, String op, String value);
/**
* Get the supported operators for this evaluator
+ *
* @return Supported operators in string array
*/
public String[] getSupportedOperators();
diff --git a/pki/base/common/src/com/netscape/certsrv/extensions/EExtensionsException.java b/pki/base/common/src/com/netscape/certsrv/extensions/EExtensionsException.java
index df4c1444..40fe80f9 100644
--- a/pki/base/common/src/com/netscape/certsrv/extensions/EExtensionsException.java
+++ b/pki/base/common/src/com/netscape/certsrv/extensions/EExtensionsException.java
@@ -17,13 +17,11 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.extensions;
-
import com.netscape.certsrv.base.EBaseException;
-
/**
* This represents the extensions exception.
- *
+ *
* @version $Revision$, $Date$
*/
public class EExtensionsException extends EBaseException {
@@ -36,7 +34,7 @@ public class EExtensionsException extends EBaseException {
* Resource class name.
*/
private static final String EXTENSIONS_RESOURCES =
- ExtensionsResources.class.getName();
+ ExtensionsResources.class.getName();
public EExtensionsException(String msgFormat) {
super(msgFormat);
diff --git a/pki/base/common/src/com/netscape/certsrv/extensions/ExtensionsResources.java b/pki/base/common/src/com/netscape/certsrv/extensions/ExtensionsResources.java
index 4d7ee06c..ca1e4545 100644
--- a/pki/base/common/src/com/netscape/certsrv/extensions/ExtensionsResources.java
+++ b/pki/base/common/src/com/netscape/certsrv/extensions/ExtensionsResources.java
@@ -17,13 +17,11 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.extensions;
-
import java.util.ListResourceBundle;
-
/**
* This represents the resources for extensions.
- *
+ *
* @version $Revision$, $Date$
*/
public class ExtensionsResources extends ListResourceBundle {
diff --git a/pki/base/common/src/com/netscape/certsrv/extensions/ICMSExtension.java b/pki/base/common/src/com/netscape/certsrv/extensions/ICMSExtension.java
index fb4bb1f7..04086adc 100644
--- a/pki/base/common/src/com/netscape/certsrv/extensions/ICMSExtension.java
+++ b/pki/base/common/src/com/netscape/certsrv/extensions/ICMSExtension.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.extensions;
-
import netscape.security.util.ObjectIdentifier;
import netscape.security.x509.Extension;
@@ -26,11 +25,10 @@ import com.netscape.certsrv.base.IArgBlock;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.base.ISubsystem;
-
/**
- * CMS extension interface, for creating extensions from http input and
- * displaying extensions to html forms.
- *
+ * CMS extension interface, for creating extensions from http input and
+ * displaying extensions to html forms.
+ *
* @version $Revision$, $Date$
*/
public interface ICMSExtension {
@@ -42,11 +40,12 @@ public interface ICMSExtension {
* initialize from configuration file
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException;
+ throws EBaseException;
/**
- * Get name of this extension.
- * @return the name of this CMS extension, for
+ * Get name of this extension.
+ *
+ * @return the name of this CMS extension, for
*/
public String getName();
@@ -54,21 +53,22 @@ public interface ICMSExtension {
* Get object identifier associated with this extension.
*/
public ObjectIdentifier getOID();
-
+
/**
* Get an instance of the extension given http input.
+ *
* @return an instance of the extension.
*/
- public Extension getExtension(IArgBlock argblock)
- throws EBaseException;
+ public Extension getExtension(IArgBlock argblock)
+ throws EBaseException;
/**
- * Get Javascript name value pairs to put into the request processing
+ * Get Javascript name value pairs to put into the request processing
* template.
- * @return name value pairs
+ *
+ * @return name value pairs
*/
public IArgBlock getFormParams(Extension extension)
- throws EBaseException;
+ throws EBaseException;
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/jobs/EJobsException.java b/pki/base/common/src/com/netscape/certsrv/jobs/EJobsException.java
index 154cb4e4..cc0923ae 100644
--- a/pki/base/common/src/com/netscape/certsrv/jobs/EJobsException.java
+++ b/pki/base/common/src/com/netscape/certsrv/jobs/EJobsException.java
@@ -17,14 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.jobs;
-
import com.netscape.certsrv.base.EBaseException;
-
/**
* A class represents a jobs exception.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class EJobsException extends EBaseException {
diff --git a/pki/base/common/src/com/netscape/certsrv/jobs/IJob.java b/pki/base/common/src/com/netscape/certsrv/jobs/IJob.java
index 1c3842bf..3a154541 100644
--- a/pki/base/common/src/com/netscape/certsrv/jobs/IJob.java
+++ b/pki/base/common/src/com/netscape/certsrv/jobs/IJob.java
@@ -17,72 +17,76 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.jobs;
-
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.base.ISubsystem;
-
/**
- * An interface to be implemented from for a job to be scheduled by
- * the Jobs Scheduler.
- *
- * @version $Revision$, $Date$
+ * An interface to be implemented from for a job to be scheduled by the Jobs
+ * Scheduler.
+ *
+ * @version $Revision$, $Date$
*/
public interface IJob {
/**
* Initialize from the configuration file.
+ *
* @param id String name of this instance
* @param implName string name of this implementation
* @param config configuration store for this instance
* @exception EBaseException any initilization failure
*/
public void init(ISubsystem owner, String id, String implName,
- IConfigStore config) throws EBaseException;
+ IConfigStore config) throws EBaseException;
/**
* tells if the job is enabled
- * @return a boolean value indicating whether the job is enabled
- * or not
+ *
+ * @return a boolean value indicating whether the job is enabled or not
*/
public boolean isEnabled();
/**
* set instance id.
+ *
* @param id String id of the instance
*/
public void setId(String id);
/**
* get instance id.
+ *
* @return a String identifier
*/
public String getId();
/**
* get cron string associated with this job
+ *
* @return a JobCron object that represents the schedule of this job
*/
public IJobCron getJobCron();
/**
- * Returns a list of configuration parameter names.
- * The list is passed to the configuration console so instances of
- * this implementation can be configured through the console.
- *
+ * Returns a list of configuration parameter names. The list is passed to
+ * the configuration console so instances of this implementation can be
+ * configured through the console.
+ *
* @return String array of configuration parameter names.
*/
public String[] getConfigParams();
/**
* gets the plugin name of this job.
+ *
* @return a String that is the name of this implementation
*/
public String getImplName();
/**
* Gets the configuration substore used by this job
+ *
* @return configuration store
*/
public IConfigStore getConfigStore();
diff --git a/pki/base/common/src/com/netscape/certsrv/jobs/IJobCron.java b/pki/base/common/src/com/netscape/certsrv/jobs/IJobCron.java
index 1e238f60..3a841717 100644
--- a/pki/base/common/src/com/netscape/certsrv/jobs/IJobCron.java
+++ b/pki/base/common/src/com/netscape/certsrv/jobs/IJobCron.java
@@ -17,33 +17,26 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.jobs;
-
-
-
/**
* class representing one Job cron information
- * <p>here, an "item" refers to one of the 5 fields in a cron string;
- * "element" refers to any comma-deliminated element in an
- * "item"...which includes both numbers and '-' separated ranges.
- * A cron string in the configuration takes the following format:
- * <i>minute (0-59),
- * hour (0-23),
- * day of the month (1-31),
- * month of the year (1-12),
- * day of the week (0-6 with 0=Sunday)</i>
* <p>
- * e.g. jobsScheduler.job.rnJob1.cron=30 11,23 * * 1-5
- * In this example, the job "rnJob1" will be executed from Monday
- * through Friday, at 11:30am and 11:30pm.
+ * here, an "item" refers to one of the 5 fields in a cron string; "element"
+ * refers to any comma-deliminated element in an "item"...which includes both
+ * numbers and '-' separated ranges. A cron string in the configuration takes
+ * the following format: <i>minute (0-59), hour (0-23), day of the month (1-31),
+ * month of the year (1-12), day of the week (0-6 with 0=Sunday)</i>
+ * <p>
+ * e.g. jobsScheduler.job.rnJob1.cron=30 11,23 * * 1-5 In this example, the job
+ * "rnJob1" will be executed from Monday through Friday, at 11:30am and 11:30pm.
* <p>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IJobCron {
/**
- * constant that represents the configuration parameter
- * "cron" for the job that this JobCron is associated with. The
- * value of which should conform to the cron format specified above.
+ * constant that represents the configuration parameter "cron" for the job
+ * that this JobCron is associated with. The value of which should conform
+ * to the cron format specified above.
*/
public static final String PROP_CRON = "cron";
diff --git a/pki/base/common/src/com/netscape/certsrv/jobs/IJobsScheduler.java b/pki/base/common/src/com/netscape/certsrv/jobs/IJobsScheduler.java
index 844250de..00a3478f 100644
--- a/pki/base/common/src/com/netscape/certsrv/jobs/IJobsScheduler.java
+++ b/pki/base/common/src/com/netscape/certsrv/jobs/IJobsScheduler.java
@@ -17,32 +17,27 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.jobs;
-
import java.util.Hashtable;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.ISubsystem;
-
/**
- * An interface that represents the job scheduler component. A JobScheduler
- * is a daemon thread that handles scheduled jobs like cron would
- * do with different jobs. This daemon wakes up at a pre-configured
- * interval to see
- * if there is any job to be done, if so, a thread is created to execute
- * the job(s).
+ * An interface that represents the job scheduler component. A JobScheduler is a
+ * daemon thread that handles scheduled jobs like cron would do with different
+ * jobs. This daemon wakes up at a pre-configured interval to see if there is
+ * any job to be done, if so, a thread is created to execute the job(s).
* <p>
- * The interval <b>jobsScheduler.interval</b> in the configuration is
- * specified as number of minutes. If not set, the default is 1 minute.
- * Note that the cron specification for each job CAN NOT be finer than
- * the granularity of the Scheduler daemon interval. For example, if
- * the daemon interval is set to 5 minute, a job cron for every minute
- * at 7am on each Tuesday (e.g. * 7 * * 2) will result in the
- * execution of the job thread only once every 5 minutes during that
- * hour. <b>The inteval value is recommended at 1 minute, setting it
- * otherwise has the potential of forever missing the beat</b>. Use
- * with caution.
- *
+ * The interval <b>jobsScheduler.interval</b> in the configuration is specified
+ * as number of minutes. If not set, the default is 1 minute. Note that the cron
+ * specification for each job CAN NOT be finer than the granularity of the
+ * Scheduler daemon interval. For example, if the daemon interval is set to 5
+ * minute, a job cron for every minute at 7am on each Tuesday (e.g. * 7 * * 2)
+ * will result in the execution of the job thread only once every 5 minutes
+ * during that hour. <b>The inteval value is recommended at 1 minute, setting it
+ * otherwise has the potential of forever missing the beat</b>. Use with
+ * caution.
+ *
* @version $Revision$, $Date$
*/
public interface IJobsScheduler extends ISubsystem {
@@ -52,111 +47,114 @@ public interface IJobsScheduler extends ISubsystem {
public final static String ID = "jobsScheduler";
/**
- * constant that represents the configuration parameter
- * "enabled" for this component in CMS.cfg. The value of which
- * tells CMS whether the JobsScheduler is enabled or not
+ * constant that represents the configuration parameter "enabled" for this
+ * component in CMS.cfg. The value of which tells CMS whether the
+ * JobsScheduler is enabled or not
*/
public static final String PROP_ENABLED = "enabled";
/**
- * constant that represents the configuration parameter
- * "interval" for this component in CMS.cfg. The value of which
- * tells CMS the interval that the JobsScheduler thread should
- * wake up and look for jobs to execute
+ * constant that represents the configuration parameter "interval" for this
+ * component in CMS.cfg. The value of which tells CMS the interval that the
+ * JobsScheduler thread should wake up and look for jobs to execute
*/
public static final String PROP_INTERVAL = "interval";
/**
- * constant that represents the configuration parameter
- * "class" for this component in CMS.cfg. The values of which are
- * the actual implementation classes
+ * constant that represents the configuration parameter "class" for this
+ * component in CMS.cfg. The values of which are the actual implementation
+ * classes
*/
public static final String PROP_CLASS = "class";
/**
- * constant that represents the configuration parameter
- * "job" for this component in CMS.cfg. The values of which gives
- * configuration information specific to one single job instance.
- * There may be multiple jobs served by the jobsScheduler
+ * constant that represents the configuration parameter "job" for this
+ * component in CMS.cfg. The values of which gives configuration information
+ * specific to one single job instance. There may be multiple jobs served by
+ * the jobsScheduler
*/
public static final String PROP_JOB = "job";
/**
- * constant that represents the configuration parameter
- * "impl" for this component in CMS.cfg. The values of which are
- * actual plugin implementation(s)
+ * constant that represents the configuration parameter "impl" for this
+ * component in CMS.cfg. The values of which are actual plugin
+ * implementation(s)
*/
public static final String PROP_IMPL = "impl";
/**
- * constant that represents the configuration parameter
- * "pluginName" for this component in CMS.cfg. The value of which
- * gives the pluginName for the job it associates with
+ * constant that represents the configuration parameter "pluginName" for
+ * this component in CMS.cfg. The value of which gives the pluginName for
+ * the job it associates with
*/
public static final String PROP_PLUGIN = "pluginName";
/**
* Retrieves all the job implementations.
+ *
* @return a Hashtable of available job plugin implementations
*/
public Hashtable<String, JobPlugin> getPlugins();
/**
* Retrieves all the job instances.
+ *
* @return a Hashtable of job instances
*/
- public Hashtable<String, IJob> getInstances();
+ public Hashtable<String, IJob> getInstances();
/**
- * Retrieves the configuration parameters of the given
- * implementation. It is used to return to the Console for
- * configuration
+ * Retrieves the configuration parameters of the given implementation. It is
+ * used to return to the Console for configuration
+ *
* @param implName the pulubin implementation name
- * @return a String array of required configuration parameters of
- * the given implementation.
- * @exception EJobsException when job plugin implementation can
- * not be found, instantiation is impossible, permission problem
- * with the class.
+ * @return a String array of required configuration parameters of the given
+ * implementation.
+ * @exception EJobsException when job plugin implementation can not be
+ * found, instantiation is impossible, permission problem
+ * with the class.
*/
- public String[] getConfigParams(String implName)
- throws EJobsException;
+ public String[] getConfigParams(String implName)
+ throws EJobsException;
/**
* Writes a message to the system log.
- * @param level an integer representing the log message level.
- * Depending on the configuration set by the administrator, this
- * value is a determining factor for whether this message will be
- * actually logged or not. The lower the level, the higher the
- * priority, and the higher chance it will be logged.
- * @param msg the message to be written. Ideally should call
- * CMS.getLogMessage() to get the localizable message
- * from the log properties file.
+ *
+ * @param level an integer representing the log message level. Depending on
+ * the configuration set by the administrator, this value is a
+ * determining factor for whether this message will be actually
+ * logged or not. The lower the level, the higher the priority,
+ * and the higher chance it will be logged.
+ * @param msg the message to be written. Ideally should call
+ * CMS.getLogMessage() to get the localizable message from the
+ * log properties file.
*/
- public void log(int level, String msg);
+ public void log(int level, String msg);
/**
* Sets daemon's wakeup interval.
+ *
* @param minutes time in minutes that is to be the frequency of
- * JobsScheduler wakeup call.
+ * JobsScheduler wakeup call.
*/
- public void setInterval(int minutes);
+ public void setInterval(int minutes);
/**
- * Starts up the JobsScheduler daemon. Usually called from the
+ * Starts up the JobsScheduler daemon. Usually called from the
* initialization method when it's successfully initialized.
*/
public void startDaemon();
/**
- * Creates a job cron. Each job is associated with a "cron" which
- * specifies the rule of frequency that this job should be
- * executed (e.g. every Sunday at midnight). This method is
- * called by each job at initialization time.
- * @param cs the string that represents the cron. See IJobCron
- * for detail of the format.
+ * Creates a job cron. Each job is associated with a "cron" which specifies
+ * the rule of frequency that this job should be executed (e.g. every Sunday
+ * at midnight). This method is called by each job at initialization time.
+ *
+ * @param cs the string that represents the cron. See IJobCron for detail of
+ * the format.
* @return IJobCron an IJobCron
- * @exception EBaseException when the cron string, cs, can not be
- * parsed correctly
+ * @exception EBaseException when the cron string, cs, can not be parsed
+ * correctly
*/
public IJobCron createJobCron(String cs) throws EBaseException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/jobs/JobPlugin.java b/pki/base/common/src/com/netscape/certsrv/jobs/JobPlugin.java
index 33b7e7f2..95eae095 100644
--- a/pki/base/common/src/com/netscape/certsrv/jobs/JobPlugin.java
+++ b/pki/base/common/src/com/netscape/certsrv/jobs/JobPlugin.java
@@ -17,15 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.jobs;
-
-
-
/**
- * This class represents a job plugin registered with the
- * JobScheduler. A Job plugin can be instantiated into a Job instance
- * and scheduled by the JobScheduler to run at a scheduled interval
+ * This class represents a job plugin registered with the JobScheduler. A Job
+ * plugin can be instantiated into a Job instance and scheduled by the
+ * JobScheduler to run at a scheduled interval
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class JobPlugin {
@@ -34,18 +31,19 @@ public class JobPlugin {
*/
protected String mId = null;
/**
- * The Java class name of this job plugin.
- * e.g. com.netscape.cms.RenewalNotificationJob
+ * The Java class name of this job plugin. e.g.
+ * com.netscape.cms.RenewalNotificationJob
*/
protected String mClassPath = null;
/*
* Seems to be unused, should be removed
*/
- // protected Class mClass = null;
+ // protected Class mClass = null;
/**
* Constructor for a Job plugin.
+ *
* @param id job plugin name
* @param classPath the Java class name of this job plugin
*/
@@ -56,6 +54,7 @@ public class JobPlugin {
/**
* get the job plugin name
+ *
* @return the name of this job plugin
*/
public String getId() {
@@ -64,6 +63,7 @@ public class JobPlugin {
/**
* get the Java class name
+ *
* @return the Java class name of this plugin
*/
public String getClassPath() {
diff --git a/pki/base/common/src/com/netscape/certsrv/jobs/JobsResources.java b/pki/base/common/src/com/netscape/certsrv/jobs/JobsResources.java
index 9bc82826..ef3ec953 100644
--- a/pki/base/common/src/com/netscape/certsrv/jobs/JobsResources.java
+++ b/pki/base/common/src/com/netscape/certsrv/jobs/JobsResources.java
@@ -17,14 +17,11 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.jobs;
-
import java.util.ListResourceBundle;
-
/**
- * A class represents a resource bundle for the
- * Jobs package
- *
+ * A class represents a resource bundle for the Jobs package
+ *
* @version $Revision$, $Date$
*/
public class JobsResources extends ListResourceBundle {
@@ -37,8 +34,7 @@ public class JobsResources extends ListResourceBundle {
}
/**
- * Constants. The suffix represents the number of
- * possible parameters.
+ * Constants. The suffix represents the number of possible parameters.
*/
static final Object[][] contents = {};
diff --git a/pki/base/common/src/com/netscape/certsrv/kra/EKRAException.java b/pki/base/common/src/com/netscape/certsrv/kra/EKRAException.java
index 9ab4a238..869c8c60 100644
--- a/pki/base/common/src/com/netscape/certsrv/kra/EKRAException.java
+++ b/pki/base/common/src/com/netscape/certsrv/kra/EKRAException.java
@@ -17,16 +17,13 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.kra;
-
import com.netscape.certsrv.base.EBaseException;
-
/**
- * A class represents a KRA exception. This is the base
- * exception for all the KRA specific exceptions. It is
- * associated with <CODE>KRAResources</CODE>.
+ * A class represents a KRA exception. This is the base exception for all the
+ * KRA specific exceptions. It is associated with <CODE>KRAResources</CODE>.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class EKRAException extends EBaseException {
@@ -39,11 +36,12 @@ public class EKRAException extends EBaseException {
* KRA resource class name.
* <P>
*/
- private static final String KRA_RESOURCES = KRAResources.class.getName();
+ private static final String KRA_RESOURCES = KRAResources.class.getName();
/**
* Constructs a KRA exception.
* <P>
+ *
* @param msgFormat constant from KRAResources.
*/
public EKRAException(String msgFormat) {
@@ -53,6 +51,7 @@ public class EKRAException extends EBaseException {
/**
* Constructs a KRA exception.
* <P>
+ *
* @param msgFormat constant from KRAResources.
* @param param additional parameters to the message.
*/
@@ -63,6 +62,7 @@ public class EKRAException extends EBaseException {
/**
* Constructs a KRA exception.
* <P>
+ *
* @param msgFormat constant from KRAResources.
* @param e embedded exception.
*/
@@ -73,6 +73,7 @@ public class EKRAException extends EBaseException {
/**
* Constructs a KRA exception.
* <P>
+ *
* @param msgFormat constant from KRAResources.
* @param params additional parameters to the message.
*/
@@ -83,6 +84,7 @@ public class EKRAException extends EBaseException {
/**
* Returns the bundle file name.
* <P>
+ *
* @return name of bundle class associated with this exception.
*/
protected String getBundleName() {
diff --git a/pki/base/common/src/com/netscape/certsrv/kra/IJoinShares.java b/pki/base/common/src/com/netscape/certsrv/kra/IJoinShares.java
index e130b95c..35366c39 100644
--- a/pki/base/common/src/com/netscape/certsrv/kra/IJoinShares.java
+++ b/pki/base/common/src/com/netscape/certsrv/kra/IJoinShares.java
@@ -18,16 +18,19 @@
package com.netscape.certsrv.kra;
/**
- * Use Java's reflection API to leverage CMS's
- * old Share and JoinShares implementations.
- *
+ * Use Java's reflection API to leverage CMS's old Share and JoinShares
+ * implementations.
+ *
* @deprecated
* @version $Revision$ $Date$
*/
public interface IJoinShares {
public void initialize(int threshold) throws Exception;
+
public void addShare(int shareNum, byte[] share);
+
public int getShareCount();
+
public byte[] recoverSecret();
}
diff --git a/pki/base/common/src/com/netscape/certsrv/kra/IKeyRecoveryAuthority.java b/pki/base/common/src/com/netscape/certsrv/kra/IKeyRecoveryAuthority.java
index 7be3f165..77fb80be 100644
--- a/pki/base/common/src/com/netscape/certsrv/kra/IKeyRecoveryAuthority.java
+++ b/pki/base/common/src/com/netscape/certsrv/kra/IKeyRecoveryAuthority.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.kra;
-
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
@@ -38,13 +37,11 @@ import com.netscape.certsrv.security.Credential;
import com.netscape.certsrv.security.IStorageKeyUnit;
import com.netscape.certsrv.security.ITransportKeyUnit;
-
/**
- * An interface represents key recovery authority. The
- * key recovery authority is responsibile for archiving
- * and recovering user encryption private keys.
+ * An interface represents key recovery authority. The key recovery authority is
+ * responsibile for archiving and recovering user encryption private keys.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IKeyRecoveryAuthority extends ISubsystem {
@@ -71,7 +68,7 @@ public interface IKeyRecoveryAuthority extends ISubsystem {
/**
* Returns the name of this subsystem.
* <P>
- *
+ *
* @return KRA name
*/
public X500Name getX500Name();
@@ -79,30 +76,28 @@ public interface IKeyRecoveryAuthority extends ISubsystem {
/**
* Retrieves KRA request repository.
* <P>
- *
+ *
* @return request repository
*/
public IRequestQueue getRequestQueue();
/**
- * Retrieves the key repository. The key repository
- * stores archived keys.
+ * Retrieves the key repository. The key repository stores archived keys.
* <P>
*/
public IKeyRepository getKeyRepository();
/**
* Retrieves the Replica ID repository.
- *
+ *
* @return KRA's Replica ID repository
*/
public IReplicaIDRepository getReplicaRepository();
/**
- * Enables the auto recovery state. Once KRA is in the auto
- * recovery state, no recovery agents need to be present for
- * providing credentials. This feature is for enabling
- * user-based recovery operation.
+ * Enables the auto recovery state. Once KRA is in the auto recovery state,
+ * no recovery agents need to be present for providing credentials. This
+ * feature is for enabling user-based recovery operation.
* <p>
*
* @param cs list of agent credentials
@@ -113,17 +108,16 @@ public interface IKeyRecoveryAuthority extends ISubsystem {
/**
* Returns the current auto recovery state.
- *
+ *
* @return true if auto recvoery state is on
*/
public boolean getAutoRecoveryState();
/**
- * Adds credentials to the given authorizated recovery operation.
- * In distributed recovery mode, recovery agent login to the
- * agent interface and submit its credential for a particular
- * recovery operation.
- *
+ * Adds credentials to the given authorizated recovery operation. In
+ * distributed recovery mode, recovery agent login to the agent interface
+ * and submit its credential for a particular recovery operation.
+ *
* @param id authorization identifier
* @param creds list of credentials
*/
@@ -131,131 +125,129 @@ public interface IKeyRecoveryAuthority extends ISubsystem {
/**
* Removes a particular auto recovery operation.
- *
+ *
* @param id authorization identifier
*/
public void removeAutoRecovery(String id);
/**
- * Returns the number of required agents. In M-out-of-N
- * recovery schema, only M agents are required even there
- * are N agents. This method returns M.
- *
+ * Returns the number of required agents. In M-out-of-N recovery schema,
+ * only M agents are required even there are N agents. This method returns
+ * M.
+ *
* @return number of required agents
*/
public int getNoOfRequiredAgents() throws EBaseException;
/**
* Sets the number of required recovery agents
- *
+ *
* @param number number of agents
*/
public void setNoOfRequiredAgents(int number) throws EBaseException;
/**
* Returns the current recovery identifier.
- *
+ *
* @return recovery identifier
*/
public String getRecoveryID();
/**
* Returns a list of recovery identifiers.
- *
+ *
* @return list of auto recovery identifiers
*/
public Enumeration<String> getAutoRecoveryIDs();
/**
- * Returns the storage key unit that manages the
- * stoarge key.
- *
+ * Returns the storage key unit that manages the stoarge key.
+ *
* @return storage key unit
*/
public IStorageKeyUnit getStorageKeyUnit();
/**
- * Returns the transport key unit that manages the
- * transport key.
- *
+ * Returns the transport key unit that manages the transport key.
+ *
* @return transport key unit
*/
public ITransportKeyUnit getTransportKeyUnit();
/**
- * Returns the token that generates user key pairs for supporting server-side keygen
- *
+ * Returns the token that generates user key pairs for supporting
+ * server-side keygen
+ *
* @return keygen token
*/
public CryptoToken getKeygenToken();
/**
* Adds entropy to the token used for supporting server-side keygen
- * Parameters are set in the config file
- * @param logflag create log messages at info level to report entropy shortage
+ * Parameters are set in the config file
+ *
+ * @param logflag create log messages at info level to report entropy
+ * shortage
*/
- public void addEntropy(boolean logflag);
-
+ public void addEntropy(boolean logflag);
/**
- * Returns the request listener that listens on
- * the request completion event.
- *
+ * Returns the request listener that listens on the request completion
+ * event.
+ *
* @return request listener
*/
public IRequestListener getRequestInQListener();
/**
- * Returns policy processor of the key recovery
- * authority.
- *
+ * Returns policy processor of the key recovery authority.
+ *
* @return policy processor
*/
public IPolicyProcessor getPolicyProcessor();
/**
* Returns the nickname of the transport certificate.
- *
+ *
* @return transport certificate nickname.
*/
public String getNickname();
/**
* Sets the nickname of the transport certificate.
- *
+ *
* @param str nickname
*/
public void setNickname(String str);
/**
* Returns the new nickname of the transport certifiate.
- *
+ *
* @return new nickname
*/
public String getNewNickName() throws EBaseException;
/**
* Sets the new nickname of the transport certifiate.
- *
+ *
* @param name new nickname
*/
public void setNewNickName(String name);
/**
* Logs event into key recovery authority logging.
- *
+ *
* @param level log level
* @param msg log message
*/
public void log(int level, String msg);
/**
- * Creates a request object to store attributes that
- * will not be serialized. Currently, request queue
- * framework will try to serialize all the attribute into
- * persistent storage. Things like passwords are not
+ * Creates a request object to store attributes that will not be serialized.
+ * Currently, request queue framework will try to serialize all the
+ * attribute into persistent storage. Things like passwords are not
* desirable to be stored.
- *
+ *
* @param id request id
* @return volatile requests
*/
@@ -263,7 +255,7 @@ public interface IKeyRecoveryAuthority extends ISubsystem {
/**
* Retrieves the request object.
- *
+ *
* @param id request id
* @return volatile requests
*/
@@ -271,32 +263,32 @@ public interface IKeyRecoveryAuthority extends ISubsystem {
/**
* Destroys the request object.
- *
+ *
* @param id request id
*/
public void destroyVolatileRequest(RequestId id);
public Vector<Credential> getAppAgents(
- String recoveryID) throws EBaseException;
+ String recoveryID) throws EBaseException;
/**
* Creates error for a specific recovery operation.
- *
+ *
* @param recoveryID recovery id
* @param error error
* @exception EBaseException failed to create error
*/
public void createError(String recoveryID, String error)
- throws EBaseException;
+ throws EBaseException;
/**
* Retrieves error by recovery identifier.
- *
+ *
* @param recoveryID recovery id
* @return error message
*/
public String getError(String recoveryID)
- throws EBaseException;
+ throws EBaseException;
/**
* Retrieves PKCS12 package by recovery identifier.
@@ -305,16 +297,16 @@ public interface IKeyRecoveryAuthority extends ISubsystem {
* @return pkcs12 package in bytes
*/
public byte[] getPk12(String recoveryID)
- throws EBaseException;
+ throws EBaseException;
/**
* Creates PKCS12 package in memory.
- *
+ *
* @param recoveryID recovery id
* @param pk12 package in bytes
- */
+ */
public void createPk12(String recoveryID, byte[] pk12)
- throws EBaseException;
+ throws EBaseException;
/**
* Retrieves the transport certificate.
diff --git a/pki/base/common/src/com/netscape/certsrv/kra/IKeyService.java b/pki/base/common/src/com/netscape/certsrv/kra/IKeyService.java
index 5ed17453..c03599b8 100644
--- a/pki/base/common/src/com/netscape/certsrv/kra/IKeyService.java
+++ b/pki/base/common/src/com/netscape/certsrv/kra/IKeyService.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.kra;
-
import java.math.BigInteger;
import java.util.Hashtable;
@@ -26,63 +25,65 @@ import netscape.security.x509.X509CertImpl;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.security.Credential;
-
/**
* An interface representing a recovery service.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IKeyService {
/**
- * Retrieves number of agent required to perform
- * key recovery operation.
+ * Retrieves number of agent required to perform key recovery operation.
*
* @return number of required recovery agents
* @exception EBaseException failed to retrieve value
*/
public int getNoOfRequiredAgents() throws EBaseException;
- /**
- * is async recovery request status APPROVED -
- * i.e. all required # of recovery agents approved
- * @param reqID request id
- * @return true if # of recovery required agents approved; false otherwise
- */
+ /**
+ * is async recovery request status APPROVED - i.e. all required # of
+ * recovery agents approved
+ *
+ * @param reqID request id
+ * @return true if # of recovery required agents approved; false otherwise
+ */
public boolean isApprovedAsyncKeyRecovery(String reqID)
- throws EBaseException;
+ throws EBaseException;
- /**
- * get async recovery request initiating agent
- * @param reqID request id
- * @return agentUID
- */
+ /**
+ * get async recovery request initiating agent
+ *
+ * @param reqID request id
+ * @return agentUID
+ */
public String getInitAgentAsyncKeyRecovery(String reqID)
- throws EBaseException;
+ throws EBaseException;
/**
* Initiate asynchronous key recovery
+ *
* @param kid key identifier
* @param cert certificate embedded in PKCS12
* @return requestId
* @exception EBaseException failed to initiate async recovery
*/
public String initAsyncKeyRecovery(BigInteger kid, X509CertImpl cert, String agent)
- throws EBaseException;
+ throws EBaseException;
/**
* add approving agent in asynchronous key recovery
+ *
* @param reqID request id
* @param agentID agent id
* @exception EBaseException failed to initiate async recovery
*/
public void addAgentAsyncKeyRecovery(String reqID, String agentID)
- throws EBaseException;
+ throws EBaseException;
/**
* Performs administrator-initiated key recovery.
- *
+ *
* @param kid key identifier
* @param creds list of credentials (id and password)
* @param pwd password to protect PKCS12
@@ -92,87 +93,87 @@ public interface IKeyService {
* @exception EBaseException failed to perform recovery
*/
public byte[] doKeyRecovery(BigInteger kid,
- Credential creds[], String pwd, X509CertImpl cert,
- String delivery, String nickname, String agent) throws EBaseException;
+ Credential creds[], String pwd, X509CertImpl cert,
+ String delivery, String nickname, String agent) throws EBaseException;
- /**
- * Async Recovers key for administrators. This method is
- * invoked by the agent operation of the key recovery servlet.
+ /**
+ * Async Recovers key for administrators. This method is invoked by the
+ * agent operation of the key recovery servlet.
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST used whenever
* a user private key recovery request is made (this is when the DRM
* receives the request)
- * <li>signed.audit LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED used whenever
- * a user private key recovery request is processed (this is when the DRM
- * processes the request)
+ * <li>signed.audit LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED used
+ * whenever a user private key recovery request is processed (this is when
+ * the DRM processes the request)
* </ul>
- * @param reqID request id
- * @param password password of the PKCS12 package
- * subsystem
+ *
+ * @param reqID request id
+ * @param password password of the PKCS12 package subsystem
* @exception EBaseException failed to recover key
* @return a byte array containing the key
*/
public byte[] doKeyRecovery(
- String reqID,
- String password)
- throws EBaseException;
+ String reqID,
+ String password)
+ throws EBaseException;
/**
* Retrieves recovery identifier.
- *
+ *
* @return recovery id
*/
public String getRecoveryID();
/**
* Creates recovery parameters for the given recovery operation.
- *
+ *
* @param recoveryID recovery id
* @return recovery parameters
* @exception EBaseException failed to create
*/
public Hashtable<String, Object> createRecoveryParams(String recoveryID)
- throws EBaseException;
+ throws EBaseException;
/**
* Destroys recovery parameters for the given recovery operation.
- *
+ *
* @param recoveryID recovery id
* @exception EBaseException failed to destroy
*/
- public void destroyRecoveryParams(String recoveryID)
- throws EBaseException;
+ public void destroyRecoveryParams(String recoveryID)
+ throws EBaseException;
/**
* Retrieves recovery parameters for the given recovery operation.
- *
+ *
* @param recoveryID recovery id
* @return recovery parameters
* @exception EBaseException failed to retrieve
*/
public Hashtable<String, Object> getRecoveryParams(String recoveryID)
- throws EBaseException;
+ throws EBaseException;
/**
* Adds password in the distributed recovery operation.
- *
+ *
* @param recoveryID recovery id
* @param uid agent uid
* @param pwd agent password
* @exception EBaseException failed to add
*/
- public void addDistributedCredential(String recoveryID,
- String uid, String pwd) throws EBaseException;
+ public void addDistributedCredential(String recoveryID,
+ String uid, String pwd) throws EBaseException;
/**
* Retrieves credentials in the distributed recovery operation.
- *
+ *
* @param recoveryID recovery id
* @return agent's credentials
* @exception EBaseException failed to retrieve
*/
- public Credential[] getDistributedCredentials(String recoveryID)
- throws EBaseException;
+ public Credential[] getDistributedCredentials(String recoveryID)
+ throws EBaseException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/kra/IProofOfArchival.java b/pki/base/common/src/com/netscape/certsrv/kra/IProofOfArchival.java
index 1b484b66..20ac336e 100644
--- a/pki/base/common/src/com/netscape/certsrv/kra/IProofOfArchival.java
+++ b/pki/base/common/src/com/netscape/certsrv/kra/IProofOfArchival.java
@@ -17,15 +17,14 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.kra;
-
import java.math.BigInteger;
import java.util.Date;
-
/**
* An interface represents a proof of archival.
* <P>
* Here is the ASN1 definition of a proof of escrow:
+ *
* <PRE>
* ProofOfArchival ::= SIGNED {
* SEQUENCE {
@@ -46,35 +45,35 @@ public interface IProofOfArchival {
/**
* Retrieves version of this proof.
- *
+ *
* @return version
*/
public BigInteger getVersion();
/**
* Retrieves the serial number.
- *
+ *
* @return serial number
*/
public BigInteger getSerialNumber();
/**
* Retrieves the subject name.
- *
+ *
* @return subject name
*/
public String getSubjectName();
/**
* Retrieves the issuer name.
- *
+ *
* @return issuer name
*/
public String getIssuerName();
/**
* Returns the beginning of the escrowed perioid.
- *
+ *
* @return date of archival
*/
public Date getDateOfArchival();
diff --git a/pki/base/common/src/com/netscape/certsrv/kra/IShare.java b/pki/base/common/src/com/netscape/certsrv/kra/IShare.java
index c4d58f0a..92eaf319 100644
--- a/pki/base/common/src/com/netscape/certsrv/kra/IShare.java
+++ b/pki/base/common/src/com/netscape/certsrv/kra/IShare.java
@@ -18,15 +18,16 @@
package com.netscape.certsrv.kra;
/**
- * Use Java's reflection API to leverage CMS's
- * old Share and JoinShares implementations.
- *
+ * Use Java's reflection API to leverage CMS's old Share and JoinShares
+ * implementations.
+ *
* @deprecated
* @version $Revision$ $Date$
*/
public interface IShare {
public void initialize(byte[] secret, int threshold) throws Exception;
+
public byte[] createShare(int sharenumber);
}
diff --git a/pki/base/common/src/com/netscape/certsrv/kra/KRAResources.java b/pki/base/common/src/com/netscape/certsrv/kra/KRAResources.java
index 40e0ee17..14b686e6 100644
--- a/pki/base/common/src/com/netscape/certsrv/kra/KRAResources.java
+++ b/pki/base/common/src/com/netscape/certsrv/kra/KRAResources.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.kra;
-
import java.util.ListResourceBundle;
-
/**
* A class represents a resource bundle for KRA subsystem.
* <P>
diff --git a/pki/base/common/src/com/netscape/certsrv/kra/ProofOfArchival.java b/pki/base/common/src/com/netscape/certsrv/kra/ProofOfArchival.java
index ca575396..99c8cc5f 100644
--- a/pki/base/common/src/com/netscape/certsrv/kra/ProofOfArchival.java
+++ b/pki/base/common/src/com/netscape/certsrv/kra/ProofOfArchival.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.kra;
-
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
@@ -42,17 +41,15 @@ import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.dbs.IDBObj;
-
/**
- * A class represents a proof of escrow. It indicates a key
- * pairs have been escrowed by appropriate authority. The
- * structure of this object is very similar (if not exact) to
- * X.509 certificate. A proof of escrow is signed by an escrow
- * authority. It is possible to have a CMS policy to reject
- * the certificate issuance request if proof of escrow is not
- * presented.
+ * A class represents a proof of escrow. It indicates a key pairs have been
+ * escrowed by appropriate authority. The structure of this object is very
+ * similar (if not exact) to X.509 certificate. A proof of escrow is signed by
+ * an escrow authority. It is possible to have a CMS policy to reject the
+ * certificate issuance request if proof of escrow is not presented.
* <P>
* Here is the ASN1 definition of a proof of escrow:
+ *
* <PRE>
* ProofOfEscrow ::= SIGNED {
* SEQUENCE {
@@ -106,13 +103,14 @@ public class ProofOfArchival implements IDBObj, IProofOfArchival, Serializable {
/**
* Constructs a proof of escrow.
* <P>
+ *
* @param serialNo serial number of proof
* @param subject subject name
* @param issuer issuer name
* @param dateOfArchival date of archival
*/
public ProofOfArchival(BigInteger serialNo, String subject,
- String issuer, Date dateOfArchival) {
+ String issuer, Date dateOfArchival) {
mVersion = DEFAULT_VERSION;
mSerialNo = serialNo;
mSubject = subject;
@@ -123,6 +121,7 @@ public class ProofOfArchival implements IDBObj, IProofOfArchival, Serializable {
/**
* Constructs proof of escrow from input stream.
* <P>
+ *
* @param in encoding source
* @exception EBaseException failed to decode
*/
@@ -133,6 +132,7 @@ public class ProofOfArchival implements IDBObj, IProofOfArchival, Serializable {
/**
* Sets an attribute value.
* <P>
+ *
* @param name attribute name
* @param obj attribute value
* @exception EBaseException failed to set attribute
@@ -157,6 +157,7 @@ public class ProofOfArchival implements IDBObj, IProofOfArchival, Serializable {
/**
* Retrieves the value of an named attribute.
* <P>
+ *
* @param name attribute name
* @return attribute value
* @exception EBaseException failed to get attribute
@@ -177,10 +178,11 @@ public class ProofOfArchival implements IDBObj, IProofOfArchival, Serializable {
CMS.getUserMessage("CMS_BASE_INVALID_ATTRIBUTE", name));
}
}
-
+
/**
* Deletes an attribute.
* <P>
+ *
* @param name attribute name
* @exception EBaseException failed to get attribute
*/
@@ -188,11 +190,11 @@ public class ProofOfArchival implements IDBObj, IProofOfArchival, Serializable {
throw new EBaseException(
CMS.getUserMessage("CMS_BASE_INVALID_ATTRIBUTE", name));
}
-
+
/**
* Retrieves a list of possible attribute names.
* <P>
- *
+ *
* @return a list of names
*/
public Enumeration<String> getElements() {
@@ -207,11 +209,12 @@ public class ProofOfArchival implements IDBObj, IProofOfArchival, Serializable {
public Enumeration<String> getSerializableAttrNames() {
return mNames.elements();
}
-
+
/**
* Retrieves version of this proof.
* <P>
- * @return version
+ *
+ * @return version
*/
public BigInteger getVersion() {
return mVersion;
@@ -220,7 +223,8 @@ public class ProofOfArchival implements IDBObj, IProofOfArchival, Serializable {
/**
* Retrieves the serial number.
* <P>
- * @return serial number
+ *
+ * @return serial number
*/
public BigInteger getSerialNumber() {
return mSerialNo;
@@ -229,6 +233,7 @@ public class ProofOfArchival implements IDBObj, IProofOfArchival, Serializable {
/**
* Retrieves the subject name.
* <P>
+ *
* @return subject name
*/
public String getSubjectName() {
@@ -238,6 +243,7 @@ public class ProofOfArchival implements IDBObj, IProofOfArchival, Serializable {
/**
* Retrieves the issuer name.
* <P>
+ *
* @return issuer name
*/
public String getIssuerName() {
@@ -247,6 +253,7 @@ public class ProofOfArchival implements IDBObj, IProofOfArchival, Serializable {
/**
* Returns the beginning of the escrowed perioid.
* <P>
+ *
* @return date of archival
*/
public Date getDateOfArchival() {
@@ -254,8 +261,7 @@ public class ProofOfArchival implements IDBObj, IProofOfArchival, Serializable {
}
/**
- * Encodes this proof of escrow into the given
- * output stream.
+ * Encodes this proof of escrow into the given output stream.
* <P>
*/
public void encode(DerOutputStream out) throws EBaseException {
@@ -268,10 +274,10 @@ public class ProofOfArchival implements IDBObj, IProofOfArchival, Serializable {
version.putInteger(new BigInt(mVersion));
seq.write(DerValue.createTag(
- DerValue.TAG_CONTEXT, true, (byte) 0),
- version);
+ DerValue.TAG_CONTEXT, true, (byte) 0),
+ version);
}
-
+
// serial number
DerOutputStream serialno = new DerOutputStream();
@@ -289,7 +295,7 @@ public class ProofOfArchival implements IDBObj, IProofOfArchival, Serializable {
// issue date
seq.putUTCTime(mDateOfArchival);
- out.write(DerValue.tag_Sequence, seq);
+ out.write(DerValue.tag_Sequence, seq);
} catch (IOException e) {
throw new EKRAException(CMS.getUserMessage("CMS_KRA_POA_DECODE_FAILED", e.toString()));
@@ -300,9 +306,9 @@ public class ProofOfArchival implements IDBObj, IProofOfArchival, Serializable {
* Encodes and signs this proof of escrow.
* <P>
*/
- public void encodeAndSign(PrivateKey key, String algorithm,
- String provider, DerOutputStream out)
- throws EBaseException {
+ public void encodeAndSign(PrivateKey key, String algorithm,
+ String provider, DerOutputStream out)
+ throws EBaseException {
try {
Signature sigEngine = null;
@@ -310,7 +316,7 @@ public class ProofOfArchival implements IDBObj, IProofOfArchival, Serializable {
if (provider == null) {
sigEngine = Signature.getInstance(algorithm);
} else {
- sigEngine = Signature.getInstance(algorithm,
+ sigEngine = Signature.getInstance(algorithm,
provider);
}
@@ -357,7 +363,7 @@ public class ProofOfArchival implements IDBObj, IProofOfArchival, Serializable {
DerValue val = new DerValue(in);
- DerValue seq[] = new DerValue[3];
+ DerValue seq[] = new DerValue[3];
seq[0] = val.data.getDerValue();
if (seq[0].tag == DerValue.tag_Sequence) {
@@ -365,12 +371,12 @@ public class ProofOfArchival implements IDBObj, IProofOfArchival, Serializable {
seq[1] = val.data.getDerValue();
seq[2] = val.data.getDerValue();
if (seq[1].data.available() != 0) {
- throw new EKRAException(CMS.getUserMessage("CMS_KRA_POA_DECODE_FAILED_1",
+ throw new EKRAException(CMS.getUserMessage("CMS_KRA_POA_DECODE_FAILED_1",
"no algorithm found"));
}
if (seq[2].data.available() != 0) {
- throw new EKRAException(CMS.getUserMessage("CMS_KRA_POA_DECODE_FAILED_1",
+ throw new EKRAException(CMS.getUserMessage("CMS_KRA_POA_DECODE_FAILED_1",
"no signature found"));
}
@@ -391,14 +397,14 @@ public class ProofOfArchival implements IDBObj, IProofOfArchival, Serializable {
* Decodes proof of escrow.
* <P>
*/
- private void decodePOA(DerValue val, DerValue preprocessed)
- throws EBaseException {
+ private void decodePOA(DerValue val, DerValue preprocessed)
+ throws EBaseException {
try {
DerValue tmp = null;
if (preprocessed == null) {
if (val.tag != DerValue.tag_Sequence) {
- throw new EKRAException(CMS.getUserMessage("CMS_KRA_POA_DECODE_FAILED_1",
+ throw new EKRAException(CMS.getUserMessage("CMS_KRA_POA_DECODE_FAILED_1",
"not start with sequence"));
}
tmp = val.data.getDerValue();
@@ -429,7 +435,7 @@ public class ProofOfArchival implements IDBObj, IProofOfArchival, Serializable {
// mSubject = new X500Name(subject); // doesnt work
mSubject = new String(subject.toByteArray());
-
+
// issuer
DerValue issuer = val.data.getDerValue();
@@ -443,15 +449,14 @@ public class ProofOfArchival implements IDBObj, IProofOfArchival, Serializable {
}
/**
- * Retrieves the string reprensetation of this
- * proof of archival.
+ * Retrieves the string reprensetation of this proof of archival.
*/
public String toString() {
return "Version: " + mVersion.toString() + "\n" +
- "SerialNo: " + mSerialNo.toString() + "\n" +
- "Subject: " + mSubject + "\n" +
- "Issuer: " + mIssuer + "\n" +
- "DateOfArchival: " + mDateOfArchival.toString();
+ "SerialNo: " + mSerialNo.toString() + "\n" +
+ "Subject: " + mSubject + "\n" +
+ "Issuer: " + mIssuer + "\n" +
+ "DateOfArchival: " + mDateOfArchival.toString();
}
}
diff --git a/pki/base/common/src/com/netscape/certsrv/ldap/ELdapException.java b/pki/base/common/src/com/netscape/certsrv/ldap/ELdapException.java
index ab2d361b..0e0813ac 100644
--- a/pki/base/common/src/com/netscape/certsrv/ldap/ELdapException.java
+++ b/pki/base/common/src/com/netscape/certsrv/ldap/ELdapException.java
@@ -17,15 +17,13 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.ldap;
-
import com.netscape.certsrv.base.EBaseException;
-
/**
- * A class that represents a Ldap exception. Various
- * errors can occur when interacting with a Ldap directory server.
+ * A class that represents a Ldap exception. Various errors can occur when
+ * interacting with a Ldap directory server.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class ELdapException extends EBaseException {
@@ -37,23 +35,25 @@ public class ELdapException extends EBaseException {
/**
* Ldap resource class name.
*/
- private static final String LDAP_RESOURCES = LdapResources.class.getName();
+ private static final String LDAP_RESOURCES = LdapResources.class.getName();
/**
- * Constructs a Ldap exception.
+ * Constructs a Ldap exception.
+ *
* @param msgFormat Resource Key, if key not present, serves as the message.
- * <P>
+ * <P>
*/
public ELdapException(String msgFormat) {
super(msgFormat);
}
/**
- * Constructs a Ldap exception.
+ * Constructs a Ldap exception.
+ *
* @param msgFormat Resource Key, if key not present, serves as the message.
- * Include a message string parameter for variable content.
+ * Include a message string parameter for variable content.
* @param param Message string parameter.
- * <P>
+ * <P>
*/
public ELdapException(String msgFormat, String param) {
super(msgFormat, param);
@@ -61,19 +61,21 @@ public class ELdapException extends EBaseException {
/**
* Constructs a Ldap exception.
+ *
* @param msgFormat Resource Key, if key not present, serves as the message.
- * @param e Common exception.
- * <P>
+ * @param e Common exception.
+ * <P>
*/
public ELdapException(String msgFormat, Exception e) {
super(msgFormat, e);
}
/**
- * Constructs a Ldap exception.
+ * Constructs a Ldap exception.
+ *
* @param msgFormat Resource Key, if key not present, serves as the message.
* @param params Array of Message string parameters.
- * <P>
+ * <P>
*/
public ELdapException(String msgFormat, Object params[]) {
super(msgFormat, params);
@@ -81,8 +83,9 @@ public class ELdapException extends EBaseException {
/**
* Gets the resource bundle name
+ *
* @return Name of the Ldap Exception resource bundle name.
- * <p>
+ * <p>
*/
protected String getBundleName() {
return LDAP_RESOURCES;
diff --git a/pki/base/common/src/com/netscape/certsrv/ldap/ELdapServerDownException.java b/pki/base/common/src/com/netscape/certsrv/ldap/ELdapServerDownException.java
index ead1a020..f347b171 100644
--- a/pki/base/common/src/com/netscape/certsrv/ldap/ELdapServerDownException.java
+++ b/pki/base/common/src/com/netscape/certsrv/ldap/ELdapServerDownException.java
@@ -17,10 +17,9 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.ldap;
-
/**
* This represents exception which indicates Ldap server is down.
- *
+ *
* @version $Revision$, $Date$
*/
public class ELdapServerDownException extends ELdapException {
@@ -32,6 +31,7 @@ public class ELdapServerDownException extends ELdapException {
/**
* Constructs a ldap server down exception with host & port info.
+ *
* @param errorString Detailed error message.
*/
public ELdapServerDownException(String errorString) {
diff --git a/pki/base/common/src/com/netscape/certsrv/ldap/ILdapAuthInfo.java b/pki/base/common/src/com/netscape/certsrv/ldap/ILdapAuthInfo.java
index 46082c73..b62cf20b 100644
--- a/pki/base/common/src/com/netscape/certsrv/ldap/ILdapAuthInfo.java
+++ b/pki/base/common/src/com/netscape/certsrv/ldap/ILdapAuthInfo.java
@@ -17,11 +17,9 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.ldap;
-
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
-
/**
* Class for obtaining ldap authentication info from the configuration store.
* Two types of authentication is basic and SSL client authentication.
@@ -39,28 +37,30 @@ public interface ILdapAuthInfo {
static public final String LDAP_BASICAUTH_STR = "BasicAuth";
static public final String LDAP_SSLCLIENTAUTH_STR = "SslClientAuth";
- static public final int LDAP_AUTHTYPE_NONE = 0; // illegal
+ static public final int LDAP_AUTHTYPE_NONE = 0; // illegal
static public final int LDAP_AUTHTYPE_BASICAUTH = 1;
static public final int LDAP_AUTHTYPE_SSLCLIENTAUTH = 2;
/**
* Initialize this class from the config store.
+ *
* @param config The config store from which to initialize.
* @exception EBaseException Due to failure of the initialization process.
- *
+ *
*/
public void init(IConfigStore config) throws EBaseException;
/**
- * Initialize this class from the config store.
- * Based on host, port, and secure boolean info.
- * which allows an actual attempt on the server to verify credentials.
+ * Initialize this class from the config store. Based on host, port, and
+ * secure boolean info. which allows an actual attempt on the server to
+ * verify credentials.
+ *
* @param config The config store from which to initialize.
* @exception EBaseException Due to failure of the initialization process.
- *
+ *
*/
public void init(IConfigStore config, String host, int port, boolean secure)
- throws EBaseException;
+ throws EBaseException;
/**
* Reset the connection to the host
@@ -68,28 +68,33 @@ public interface ILdapAuthInfo {
public void reset();
/**
- * Get authentication type.
+ * Get authentication type.
+ *
* @return one of: <br>
- * LdapAuthInfo.LDAP_AUTHTYPE_BASICAUTH or
- * LdapAuthInfo.LDAP_AUTHTYPE_SSLCLIENTAUTH
+ * LdapAuthInfo.LDAP_AUTHTYPE_BASICAUTH or
+ * LdapAuthInfo.LDAP_AUTHTYPE_SSLCLIENTAUTH
*/
public int getAuthType();
/**
* Get params for authentication.
- * @return array of parameters for this authentication as an array of Strings.
+ *
+ * @return array of parameters for this authentication as an array of
+ * Strings.
*/
public String[] getParms();
/**
* Add password to private password data structure.
+ *
* @param prompt Password prompt.
- * @param pw Password itself.
+ * @param pw Password itself.
*/
public void addPassword(String prompt, String pw);
/**
* Remove password from private password data structure.
+ *
* @param prompt Identify password to remove with prompt.
*/
public void removePassword(String prompt);
diff --git a/pki/base/common/src/com/netscape/certsrv/ldap/ILdapBoundConnFactory.java b/pki/base/common/src/com/netscape/certsrv/ldap/ILdapBoundConnFactory.java
index ef3e1742..0fac8d35 100644
--- a/pki/base/common/src/com/netscape/certsrv/ldap/ILdapBoundConnFactory.java
+++ b/pki/base/common/src/com/netscape/certsrv/ldap/ILdapBoundConnFactory.java
@@ -17,18 +17,14 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.ldap;
-
-
-
/**
- * Maintains a pool of connections to the LDAP server.
- * CMS requests are processed on a multi threaded basis.
- * A pool of connections then must be be maintained so this
- * access to the Ldap server can be easily managed. The min and
- * max size of this connection pool should be configurable. Once
- * the maximum limit of connections is exceeded, the factory
- * should provide proper synchronization to resolve contention issues.
- *
+ * Maintains a pool of connections to the LDAP server. CMS requests are
+ * processed on a multi threaded basis. A pool of connections then must be be
+ * maintained so this access to the Ldap server can be easily managed. The min
+ * and max size of this connection pool should be configurable. Once the maximum
+ * limit of connections is exceeded, the factory should provide proper
+ * synchronization to resolve contention issues.
+ *
* @version $Revision$, $Date$
*/
public interface ILdapBoundConnFactory extends ILdapConnFactory {
diff --git a/pki/base/common/src/com/netscape/certsrv/ldap/ILdapConnFactory.java b/pki/base/common/src/com/netscape/certsrv/ldap/ILdapConnFactory.java
index f706c2ec..118e414d 100644
--- a/pki/base/common/src/com/netscape/certsrv/ldap/ILdapConnFactory.java
+++ b/pki/base/common/src/com/netscape/certsrv/ldap/ILdapConnFactory.java
@@ -17,76 +17,79 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.ldap;
-
import netscape.ldap.LDAPConnection;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
-
/**
- * Maintains a pool of connections to the LDAP server.
- * Multiple threads use this interface to utilize and release
- * the Ldap connection resources.
- *
+ * Maintains a pool of connections to the LDAP server. Multiple threads use this
+ * interface to utilize and release the Ldap connection resources.
+ *
* @version $Revision$, $Date$
*/
public interface ILdapConnFactory {
- /**
+ /**
* Initialize the poll from the config store.
+ *
* @param config The configuration substore.
* @exception EBaseException On configuration error.
- * @exception ELdapException On all other errors.
+ * @exception ELdapException On all other errors.
*/
- public void init(IConfigStore config)
- throws EBaseException, ELdapException;
+ public void init(IConfigStore config)
+ throws EBaseException, ELdapException;
/**
- *
- * Used for disconnecting all connections.
- * Used just before a subsystem
+ *
+ * Used for disconnecting all connections. Used just before a subsystem
* shutdown or process exit.
+ *
* @exception EldapException on Ldap failure when closing connections.
*/
- public void reset()
- throws ELdapException;
+ public void reset()
+ throws ELdapException;
/**
* Returns the number of free connections available from this pool.
- * @return Integer number of free connections.
- */
+ *
+ * @return Integer number of free connections.
+ */
public int freeConn();
/**
* Returns the number of total connections available from this pool.
* Includes sum of free and in use connections.
+ *
* @return Integer number of total connections.
*/
public int totalConn();
/**
* Returns the maximum number of connections available from this pool.
+ *
* @return Integer maximum number of connections.
*/
public int maxConn();
- /**
- * Request access to a Ldap connection from the pool.
- * @exception ELdapException if any error occurs, such as a
- * @return Ldap connection object.
- * connection is not available
+ /**
+ * Request access to a Ldap connection from the pool.
+ *
+ * @exception ELdapException if any error occurs, such as a
+ * @return Ldap connection object. connection is not available
*/
- public LDAPConnection getConn()
- throws ELdapException;
+ public LDAPConnection getConn()
+ throws ELdapException;
/**
* Return connection to the factory. mandatory after a getConn().
- * @param conn Ldap connection object to be returned to the free list of the pool.
+ *
+ * @param conn Ldap connection object to be returned to the free list of the
+ * pool.
* @exception ELdapException On any failure to return the connection.
*/
- public void returnConn(LDAPConnection conn)
- throws ELdapException;
+ public void returnConn(LDAPConnection conn)
+ throws ELdapException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/ldap/ILdapConnInfo.java b/pki/base/common/src/com/netscape/certsrv/ldap/ILdapConnInfo.java
index 4cffbe45..4eec994a 100644
--- a/pki/base/common/src/com/netscape/certsrv/ldap/ILdapConnInfo.java
+++ b/pki/base/common/src/com/netscape/certsrv/ldap/ILdapConnInfo.java
@@ -17,15 +17,14 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.ldap;
-
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
-
/**
- * Class for reading ldap connection information from the config store.
- * Ldap connection info: host name, port number,whether of not it is a secure connection.
- *
+ * Class for reading ldap connection information from the config store. Ldap
+ * connection info: host name, port number,whether of not it is a secure
+ * connection.
+ *
* @version $Revision$, $Date$
*/
public interface ILdapConnInfo {
@@ -42,23 +41,24 @@ public interface ILdapConnInfo {
/**
* Initializes an instance from a config store.
+ *
* @param config Configuration store.
* @exception ELdapException Ldap related error found.
- * @exception EBaseException Other errors and errors with params included in the config store.
+ * @exception EBaseException Other errors and errors with params included in
+ * the config store.
*/
public void init(IConfigStore config) throws EBaseException, ELdapException;
/**
- * Return the name of the Host.
- *
+ * Return the name of the Host.
+ *
*/
-
public String getHost();
/**
* Return the port number of the host.
- *
+ *
*/
public int getPort();
@@ -74,8 +74,8 @@ public interface ILdapConnInfo {
public boolean getSecure();
/**
- * Return whether or not the server is to follow referrals
- * to other servers when servicing a query.
+ * Return whether or not the server is to follow referrals to other servers
+ * when servicing a query.
*/
public boolean getFollowReferrals();
diff --git a/pki/base/common/src/com/netscape/certsrv/ldap/ILdapConnModule.java b/pki/base/common/src/com/netscape/certsrv/ldap/ILdapConnModule.java
index 8d912fc5..601bfde8 100644
--- a/pki/base/common/src/com/netscape/certsrv/ldap/ILdapConnModule.java
+++ b/pki/base/common/src/com/netscape/certsrv/ldap/ILdapConnModule.java
@@ -17,45 +17,44 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.ldap;
-
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.base.ISubsystem;
-
/**
- * Class on behalf of the Publishing system that controls an instance of an ILdapConnFactory.
- * Allows a factory to be intialized and grants access
- * to the factory to other interested parties.
- *
+ * Class on behalf of the Publishing system that controls an instance of an
+ * ILdapConnFactory. Allows a factory to be intialized and grants access to the
+ * factory to other interested parties.
+ *
* @version $Revision$, $Date$
*/
-
+
public interface ILdapConnModule {
/**
* Initialize ldap publishing module with config store.
+ *
* @param owner Entity that is interested in this instance of Publishing.
- * @param config Config store containing the info needed to set up Publishing.
+ * @param config Config store containing the info needed to set up
+ * Publishing.
* @exception ELdapException Due to Ldap error.
- * @exception EBaseException Due to config value errors and all other errors.
+ * @exception EBaseException Due to config value errors and all other
+ * errors.
*/
- public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException, ELdapException;
+ public void init(ISubsystem owner, IConfigStore config)
+ throws EBaseException, ELdapException;
/**
- * Returns the internal ldap connection factory.
- * This can be useful to get a ldap connection to the
- * ldap publishing directory without having to get it again from the
- * config file. Note that this means sharing a ldap connection pool
- * with the ldap publishing module so be sure to return connections to pool.
- * Use ILdapConnFactory.getConn() to get a Ldap connection to the ldap
- * publishing directory.
- * Use ILdapConnFactory.returnConn() to return the connection.
- *
+ * Returns the internal ldap connection factory. This can be useful to get a
+ * ldap connection to the ldap publishing directory without having to get it
+ * again from the config file. Note that this means sharing a ldap
+ * connection pool with the ldap publishing module so be sure to return
+ * connections to pool. Use ILdapConnFactory.getConn() to get a Ldap
+ * connection to the ldap publishing directory. Use
+ * ILdapConnFactory.returnConn() to return the connection.
+ *
* @return Instance of ILdapConnFactory.
*/
public ILdapConnFactory getLdapConnFactory();
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/ldap/LdapResources.java b/pki/base/common/src/com/netscape/certsrv/ldap/LdapResources.java
index 26149738..ee2d307c 100644
--- a/pki/base/common/src/com/netscape/certsrv/ldap/LdapResources.java
+++ b/pki/base/common/src/com/netscape/certsrv/ldap/LdapResources.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.ldap;
-
import java.util.ListResourceBundle;
-
/**
* A resource bundle for ldap subsystem.
*
@@ -36,8 +34,7 @@ public class LdapResources extends ListResourceBundle {
}
/**
- * Constants. The suffix represents the number of
- * possible parameters.
+ * Constants. The suffix represents the number of possible parameters.
*/
static final Object[][] contents = {};
diff --git a/pki/base/common/src/com/netscape/certsrv/listeners/EListenersException.java b/pki/base/common/src/com/netscape/certsrv/listeners/EListenersException.java
index c498ca3d..6aee21ff 100644
--- a/pki/base/common/src/com/netscape/certsrv/listeners/EListenersException.java
+++ b/pki/base/common/src/com/netscape/certsrv/listeners/EListenersException.java
@@ -17,13 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.listeners;
-
import com.netscape.certsrv.base.EBaseException;
-
/**
* A class represents a listener exception.
* <P>
+ *
* @version $Revision$, $Date$
*/
public class EListenersException extends EBaseException {
@@ -40,8 +39,9 @@ public class EListenersException extends EBaseException {
/**
* Constructs a listeners exception.
* <P>
+ *
* @param msgFormat The error message resource key.
- */
+ */
public EListenersException(String msgFormat) {
super(msgFormat);
}
@@ -49,6 +49,7 @@ public class EListenersException extends EBaseException {
/**
* Constructs a listeners exception.
* <P>
+ *
* @param msgFormat exception details in message string format.
* @param param message string parameter.
*/
@@ -59,27 +60,31 @@ public class EListenersException extends EBaseException {
/**
* Constructs a Listeners exception.
* <P>
+ *
* @param msgFormat The resource key.
* @param e The parameter as an exception.
*/
public EListenersException(String msgFormat, Exception e) {
super(msgFormat, e);
}
-
+
/**
* Constructs a Listeners exception.
* <P>
+ *
* @param msgFormat The resource key.
* @param params Array of params.
*/
public EListenersException(String msgFormat, Object params[]) {
super(msgFormat, params);
}
+
/**
* get the listener resource class name.
* <P>
+ *
* @return the class name of the resource.
- */
+ */
protected String getBundleName() {
return LISTENERS_RESOURCES;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/listeners/IRequestListenerPlugin.java b/pki/base/common/src/com/netscape/certsrv/listeners/IRequestListenerPlugin.java
index b0cb173c..6b2f794d 100644
--- a/pki/base/common/src/com/netscape/certsrv/listeners/IRequestListenerPlugin.java
+++ b/pki/base/common/src/com/netscape/certsrv/listeners/IRequestListenerPlugin.java
@@ -17,62 +17,72 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.listeners;
-
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
/**
- * This interface represents a plug-in listener. Implement this class to
- * add the listener to an ARequestNotifier of a subsystem.
+ * This interface represents a plug-in listener. Implement this class to add the
+ * listener to an ARequestNotifier of a subsystem.
* <P>
+ *
* @version $Revision$, $Date$
*/
public interface IRequestListenerPlugin {
-
+
/**
* get the registered class name set in the init() method.
* <P>
- * @return the Name.
+ *
+ * @return the Name.
*/
public String getName();
-
+
/**
* get the plugin implementaion name set in the init() method.
* <P>
+ *
* @return the plugin implementation name.
*/
public String getImplName();
-
+
/**
* the subsystem call this method to initialize the plug-in.
* <P>
+ *
* @param name the registered class name of the plug-in.
* @param implName the implemetnation name of the plug-in.
- * @param config the configuration store where the.
- * properties of the plug-in are stored.
- * @exception EBaseException throws base exception in the certificate server.
+ * @param config the configuration store where the. properties of the
+ * plug-in are stored.
+ * @exception EBaseException throws base exception in the certificate
+ * server.
*/
- public void init(String name, String implName, IConfigStore config)
- throws EBaseException;
+ public void init(String name, String implName, IConfigStore config)
+ throws EBaseException;
+
/**
* shutdown the plugin.
*/
public void shutdown();
+
/**
* get the configuration parameters of the plug-in.
* <P>
+ *
* @return the configuration parameters.
- * @exception EBaseException throws base exception in the certificate server.
+ * @exception EBaseException throws base exception in the certificate
+ * server.
*/
public String[] getConfigParams()
- throws EBaseException;
+ throws EBaseException;
+
/**
- * get the configuration store of the plugin where the
- * configuration parameters of the plug-in are stored.
+ * get the configuration store of the plugin where the configuration
+ * parameters of the plug-in are stored.
* <P>
+ *
* @return the configuration store.
*/
-
+
public IConfigStore getConfigStore();
-
+
}
diff --git a/pki/base/common/src/com/netscape/certsrv/listeners/ListenersResources.java b/pki/base/common/src/com/netscape/certsrv/listeners/ListenersResources.java
index 199941be..bd03bb40 100644
--- a/pki/base/common/src/com/netscape/certsrv/listeners/ListenersResources.java
+++ b/pki/base/common/src/com/netscape/certsrv/listeners/ListenersResources.java
@@ -17,13 +17,11 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.listeners;
-
import java.util.ListResourceBundle;
/**
- * A class represents a resource bundle for the
- * listeners package.
- *
+ * A class represents a resource bundle for the listeners package.
+ *
* @version $Revision$, $Date$
*/
public class ListenersResources extends ListResourceBundle {
@@ -31,11 +29,14 @@ public class ListenersResources extends ListResourceBundle {
/**
* get the content of the resource.
* <P>
- * @return the content of this resource is a value pairs array of keys and values.
+ *
+ * @return the content of this resource is a value pairs array of keys and
+ * values.
*/
public Object[][] getContents() {
return contents;
}
+
static final Object[][] contents = {
};
}
diff --git a/pki/base/common/src/com/netscape/certsrv/logging/AuditEvent.java b/pki/base/common/src/com/netscape/certsrv/logging/AuditEvent.java
index 4f7e64f2..39634f24 100644
--- a/pki/base/common/src/com/netscape/certsrv/logging/AuditEvent.java
+++ b/pki/base/common/src/com/netscape/certsrv/logging/AuditEvent.java
@@ -17,20 +17,18 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.logging;
-
import java.text.MessageFormat;
import java.util.Locale;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.MessageFormatter;
-
/**
- * The log event object that carries message detail of a log event
- * that goes into the Transaction log. Note that the name of this
- * class "AuditEvent" is legacy and has nothing to do with the signed
- * audit log events, whcih are represented by SignedAuditEvent.
- *
+ * The log event object that carries message detail of a log event that goes
+ * into the Transaction log. Note that the name of this class "AuditEvent" is
+ * legacy and has nothing to do with the signed audit log events, whcih are
+ * represented by SignedAuditEvent.
+ *
* @version $Revision$, $Date$
* @see java.text.MessageFormat
* @see com.netscape.certsrv.logging.LogResources
@@ -56,12 +54,12 @@ public class AuditEvent implements IBundleLogEvent {
* The bundle name for this event.
*/
private String mBundleName = LogResources.class.getName();
- private static final String INVALID_LOG_LEVEL="log level: {0} is invalid, should be 0-6";
+ private static final String INVALID_LOG_LEVEL = "log level: {0} is invalid, should be 0-6";
/**
* Constructs a message event
* <P>
- *
+ *
* @param msgFormat the message string
*/
public AuditEvent(String msgFormat) {
@@ -71,11 +69,12 @@ public class AuditEvent implements IBundleLogEvent {
/**
* Constructs a message with a parameter. For example,
+ *
* <PRE>
- * new AuditEvent("failed to load {0}", fileName);
+ * new AuditEvent(&quot;failed to load {0}&quot;, fileName);
* </PRE>
* <P>
- *
+ *
* @param msgFormat details in message string format
* @param param message string parameter
*/
@@ -86,9 +85,9 @@ public class AuditEvent implements IBundleLogEvent {
}
/**
- * Constructs a message from an exception. It can be used to carry
- * a system exception that may contain information about
- * the context. For example,
+ * Constructs a message from an exception. It can be used to carry a system
+ * exception that may contain information about the context. For example,
+ *
* <PRE>
* try {
* ...
@@ -97,7 +96,7 @@ public class AuditEvent implements IBundleLogEvent {
* }
* </PRE>
* <P>
- *
+ *
* @param msgFormat exception details in message string format
* @param exception system exception
*/
@@ -110,6 +109,7 @@ public class AuditEvent implements IBundleLogEvent {
/**
* Constructs a message from a base exception. This will use the msgFormat
* from the exception itself.
+ *
* <PRE>
* try {
* ...
@@ -118,7 +118,7 @@ public class AuditEvent implements IBundleLogEvent {
* }
* </PRE>
* <P>
- *
+ *
* @param e CMS exception
*/
public AuditEvent(Exception e) {
@@ -132,10 +132,10 @@ public class AuditEvent implements IBundleLogEvent {
}
/**
- * Constructs a message event with a list of parameters
- * that will be substituted into the message format.
+ * Constructs a message event with a list of parameters that will be
+ * substituted into the message format.
* <P>
- *
+ *
* @param msgFormat message string format
* @param params list of message format parameters
*/
@@ -147,7 +147,7 @@ public class AuditEvent implements IBundleLogEvent {
/**
* Returns the current message format string.
* <P>
- *
+ *
* @return details message
*/
public String getMessage() {
@@ -157,7 +157,7 @@ public class AuditEvent implements IBundleLogEvent {
/**
* Returns a list of parameters.
* <P>
- *
+ *
* @return list of message format parameters
*/
public Object[] getParameters() {
@@ -165,10 +165,10 @@ public class AuditEvent implements IBundleLogEvent {
}
/**
- * Returns localized message string. This method should
- * only be called if a localized string is necessary.
+ * Returns localized message string. This method should only be called if a
+ * localized string is necessary.
* <P>
- *
+ *
* @return details message
*/
public String toContent() {
@@ -178,7 +178,7 @@ public class AuditEvent implements IBundleLogEvent {
/**
* Returns the string based on the given locale.
* <P>
- *
+ *
* @param locale locale
* @return details message
*/
@@ -189,8 +189,9 @@ public class AuditEvent implements IBundleLogEvent {
}
/**
- * Gets the resource bundle name for this class instance. This should
- * be overridden by subclasses who have their own resource bundles.
+ * Gets the resource bundle name for this class instance. This should be
+ * overridden by subclasses who have their own resource bundles.
+ *
* @param bundle String that represents the resource bundle name to be set
*/
public void setBundleName(String bundle) {
@@ -199,6 +200,7 @@ public class AuditEvent implements IBundleLogEvent {
/**
* Retrieves bundle name.
+ *
* @return a String that represents the resource bundle name
*/
protected String getBundleName() {
@@ -207,8 +209,9 @@ public class AuditEvent implements IBundleLogEvent {
/**
* Retrieves log source.
- * @return an integer that indicates the component source
- * where this message event was triggered
+ *
+ * @return an integer that indicates the component source where this message
+ * event was triggered
*/
public int getSource() {
return mSource;
@@ -216,18 +219,18 @@ public class AuditEvent implements IBundleLogEvent {
/**
* Sets log source.
- * @param source an integer that represents the component source
- * where this message event was triggered
+ *
+ * @param source an integer that represents the component source where this
+ * message event was triggered
*/
public void setSource(int source) {
mSource = source;
}
-
/**
- * Retrieves log level.
- * The log level of an event represents its relative importance
- * or severity within CMS.
+ * Retrieves log level. The log level of an event represents its relative
+ * importance or severity within CMS.
+ *
* @return Integer log level value.
*/
public int getLevel() {
@@ -236,6 +239,7 @@ public class AuditEvent implements IBundleLogEvent {
/**
* Retrieves NT specific log event type.
+ *
* @return Integer NTEventType value.
*/
public int getNTEventType() {
@@ -243,9 +247,9 @@ public class AuditEvent implements IBundleLogEvent {
}
/**
- * Sets log level, NT log event type.
- * For certain log levels the NT log event type gets
- * set as well.
+ * Sets log level, NT log event type. For certain log levels the NT log
+ * event type gets set as well.
+ *
* @param level Integer log level value.
*/
public void setLevel(int level) {
@@ -273,19 +277,21 @@ public class AuditEvent implements IBundleLogEvent {
break;
}
}
-
+
/**
* Retrieves log multiline attribute.
- * @return Boolean whether or not this event is multiline.
- * A multiline message simply consists of more than one line.
- */
+ *
+ * @return Boolean whether or not this event is multiline. A multiline
+ * message simply consists of more than one line.
+ */
public boolean getMultiline() {
return mMultiline;
}
/**
- * Sets log multiline attribute. A multiline message consists of
- * more than one line.
+ * Sets log multiline attribute. A multiline message consists of more than
+ * one line.
+ *
* @param multiline Boolean multiline value.
*/
public void setMultiline(boolean multiline) {
@@ -294,26 +300,27 @@ public class AuditEvent implements IBundleLogEvent {
/**
* Retrieves event time stamp.
+ *
* @return Long integer of the time the event was created.
*/
public long getTimeStamp() {
return mTimeStamp;
}
-
/**
- * Retrieves log event type. Each type of event
- * has an associated String type value.
+ * Retrieves log event type. Each type of event has an associated String
+ * type value.
+ *
* @return String containing the type of event.
*/
public String getEventType() {
return mEventType;
}
-
/**
- * Sets log event type. Each type of event
- * has an associated String type value.
+ * Sets log event type. Each type of event has an associated String type
+ * value.
+ *
* @param eventType String containing the type of event.
*/
public void setEventType(String eventType) {
@@ -321,15 +328,16 @@ public class AuditEvent implements IBundleLogEvent {
}
/**
- * Return string representation of log message.
- * @return String containing log message.
- */
+ * Return string representation of log message.
+ *
+ * @return String containing log message.
+ */
public String toString() {
if (getBundleName() == null) {
MessageFormat detailMessage = new MessageFormat(mMessage);
return detailMessage.format(mParams);
- //return getMessage();
+ // return getMessage();
} else
return toContent();
}
diff --git a/pki/base/common/src/com/netscape/certsrv/logging/AuditFormat.java b/pki/base/common/src/com/netscape/certsrv/logging/AuditFormat.java
index 8d870ad9..1e4ae331 100644
--- a/pki/base/common/src/com/netscape/certsrv/logging/AuditFormat.java
+++ b/pki/base/common/src/com/netscape/certsrv/logging/AuditFormat.java
@@ -17,12 +17,11 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.logging;
-
/**
- * Define audit log message format. Note that the name of this
- * class "AuditFormat" is legacy and has nothing to do with the signed
- * audit log events format
- *
+ * Define audit log message format. Note that the name of this class
+ * "AuditFormat" is legacy and has nothing to do with the signed audit log
+ * events format
+ *
* @version $Revision$, $Date$
*/
public class AuditFormat {
@@ -40,18 +39,18 @@ public class AuditFormat {
/**
* initiative: the event is from agent
*/
- public static final String FROMAGENT = "fromAgent";
+ public static final String FROMAGENT = "fromAgent";
/**
* initiative: the event is from router
*/
- public static final String FROMROUTER = "fromRouter";
+ public static final String FROMROUTER = "fromRouter";
/**
* initiative: the event is from remote authority
*/
public static final String FROMRA = "fromRemoteAuthority";
-
+
/**
* authentication module: no Authentication manager
*/
@@ -59,54 +58,49 @@ public class AuditFormat {
// for ProcessCertReq.java ,kra
/**
- 0: request type
- 1: request ID
- 2: initiative
- 3: auth module
- 4: status
- 5: cert dn
- 6: other info. eg cert serial number, violation policies
+ * 0: request type 1: request ID 2: initiative 3: auth module 4: status 5:
+ * cert dn 6: other info. eg cert serial number, violation policies
*/
- public static final String FORMAT =
- "{0} reqID {1} {2} authenticated by {3} is {4} DN requested: {5} {6}";
- public static final String NODNFORMAT =
- "{0} reqID {1} {2} authenticated by {3} is {4}";
+ public static final String FORMAT =
+ "{0} reqID {1} {2} authenticated by {3} is {4} DN requested: {5} {6}";
+ public static final String NODNFORMAT =
+ "{0} reqID {1} {2} authenticated by {3} is {4}";
- public static final String ENROLLMENTFORMAT =
- "Enrollment request reqID {0} {1} authenticated by {2} is {3}. DN requested: {4} {5}";
- public static final String RENEWALFORMAT =
- "Renewal request reqID {0} {1} authenticated by {2} is {3}. DN requested: {4} old serial number: 0x{5} {6}";
- public static final String REVOCATIONFORMAT =
- "Revocation request reqID {0} {1} authenticated by {2} is {3}. DN requested: {4} serial number: 0x{5} revocation reason: {6} {7}";
+ public static final String ENROLLMENTFORMAT =
+ "Enrollment request reqID {0} {1} authenticated by {2} is {3}. DN requested: {4} {5}";
+ public static final String RENEWALFORMAT =
+ "Renewal request reqID {0} {1} authenticated by {2} is {3}. DN requested: {4} old serial number: 0x{5} {6}";
+ public static final String REVOCATIONFORMAT =
+ "Revocation request reqID {0} {1} authenticated by {2} is {3}. DN requested: {4} serial number: 0x{5} revocation reason: {6} {7}";
// 1: fromAgent AgentID: xxx authenticated by xxx
- public static final String DOREVOKEFORMAT =
- "Revocation request reqID {0} {1} is {2}. DN requested: {3} serial number: 0x{4} revocation reason: {5}";
+ public static final String DOREVOKEFORMAT =
+ "Revocation request reqID {0} {1} is {2}. DN requested: {3} serial number: 0x{4} revocation reason: {5}";
// 1: fromAgent AgentID: xxx authenticated by xxx
- public static final String DOUNREVOKEFORMAT =
- "Unrevocation request reqID {0} {1} is {2}. DN requested: {3} serial number: 0x{4}";
+ public static final String DOUNREVOKEFORMAT =
+ "Unrevocation request reqID {0} {1} is {2}. DN requested: {3} serial number: 0x{4}";
// 0:initiative
- public static final String CRLUPDATEFORMAT =
- "CRLUpdate request {0} authenticated by {1} is {2}. Id: {3}\ncrl Number: {4} last update time: {5} next update time: {6} number of entries in the CRL: {7}";
+ public static final String CRLUPDATEFORMAT =
+ "CRLUpdate request {0} authenticated by {1} is {2}. Id: {3}\ncrl Number: {4} last update time: {5} next update time: {6} number of entries in the CRL: {7}";
// audit user/group
public static final String ADDUSERFORMAT =
- "Admin UID: {0} added User UID: {1}";
+ "Admin UID: {0} added User UID: {1}";
public static final String REMOVEUSERFORMAT =
- "Admin UID: {0} removed User UID: {1} ";
+ "Admin UID: {0} removed User UID: {1} ";
public static final String MODIFYUSERFORMAT =
- "Admin UID: {0} modified User UID: {1}";
+ "Admin UID: {0} modified User UID: {1}";
public static final String ADDUSERCERTFORMAT =
- "Admin UID: {0} added cert for User UID: {1}. cert DN: {2} serial number: 0x{3}";
+ "Admin UID: {0} added cert for User UID: {1}. cert DN: {2} serial number: 0x{3}";
public static final String REMOVEUSERCERTFORMAT =
- "Admin UID: {0} removed cert of User UID: {1}. cert DN: {2} serial number: 0x{3}";
+ "Admin UID: {0} removed cert of User UID: {1}. cert DN: {2} serial number: 0x{3}";
public static final String ADDUSERGROUPFORMAT =
- "Admin UID: {0} added User UID: {1} to group: {2}";
+ "Admin UID: {0} added User UID: {1} to group: {2}";
public static final String REMOVEUSERGROUPFORMAT =
- "Admin UID: {0} removed User UID: {1} from group: {2}";
+ "Admin UID: {0} removed User UID: {1} from group: {2}";
// LDAP publishing
- public static final String LDAP_PUBLISHED_FORMAT =
- "{0} successfully published serial number: 0x{1} with DN: {2}";
+ public static final String LDAP_PUBLISHED_FORMAT =
+ "{0} successfully published serial number: 0x{1} with DN: {2}";
}
diff --git a/pki/base/common/src/com/netscape/certsrv/logging/ConsoleError.java b/pki/base/common/src/com/netscape/certsrv/logging/ConsoleError.java
index 146824ac..13e0f3d4 100644
--- a/pki/base/common/src/com/netscape/certsrv/logging/ConsoleError.java
+++ b/pki/base/common/src/com/netscape/certsrv/logging/ConsoleError.java
@@ -17,12 +17,9 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.logging;
-
-
-
/**
* A static class to log error messages to the Console
- *
+ *
* @version $Revision$, $Date$
*/
public class ConsoleError {
@@ -30,8 +27,8 @@ public class ConsoleError {
/**
* Send the given event to the Console.
- *
- * @param ev log event to be sent to the console
+ *
+ * @param ev log event to be sent to the console
*/
public static void send(ILogEvent ev) {
console.log(ev);
diff --git a/pki/base/common/src/com/netscape/certsrv/logging/ConsoleLog.java b/pki/base/common/src/com/netscape/certsrv/logging/ConsoleLog.java
index 8dee67ef..20ec08a0 100644
--- a/pki/base/common/src/com/netscape/certsrv/logging/ConsoleLog.java
+++ b/pki/base/common/src/com/netscape/certsrv/logging/ConsoleLog.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.logging;
-
import java.io.IOException;
import java.util.Hashtable;
import java.util.Vector;
@@ -29,64 +28,63 @@ import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.base.ISubsystem;
import com.netscape.certsrv.common.NameValuePairs;
-
/**
* A log event listener which sends all log events to the system console/tty
- *
+ *
* @version $Revision$, $Date$
*/
public class ConsoleLog implements ILogEventListener {
/**
- * Log the given event. Usually called from a log manager.
- *
- * @param ev log event
+ * Log the given event. Usually called from a log manager.
+ *
+ * @param ev log event
*/
public void log(ILogEvent ev) {
System.err.println(Thread.currentThread().getName() + ": " + ev);
}
/**
- * Flush the system output stream.
- *
+ * Flush the system output stream.
+ *
*/
public void flush() {
System.err.flush();
}
- /**
- * All operations need to be cleaned up for shutdown are done here
- */
+ /**
+ * All operations need to be cleaned up for shutdown are done here
+ */
public void shutdown() {
}
- /**
- * get the configuration store that is associated with this
- * log listener
- * @return the configuration store that is associated with this
- * log listener
- */
+ /**
+ * get the configuration store that is associated with this log listener
+ *
+ * @return the configuration store that is associated with this log listener
+ */
public IConfigStore getConfigStore() {
return null;
}
- public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ public void init(ISubsystem owner, IConfigStore config)
+ throws EBaseException {
}
public void startup() throws EBaseException {
}
/**
- * Retrieve last "maxLine" number of system log with log lever >"level"
- * and from source "source". If the parameter is omitted. All entries
- * are sent back.
- * @param req a Hashtable containing the required information such as
- * log entry, log level, log source, and log name
- * @return the content of the log that match the criteria in req
- * @exception servletException
- * @exception IOException
- * @exception EBaseException
+ * Retrieve last "maxLine" number of system log with log lever >"level" and
+ * from source "source". If the parameter is omitted. All entries are sent
+ * back.
+ *
+ * @param req a Hashtable containing the required information such as log
+ * entry, log level, log source, and log name
+ * @return the content of the log that match the criteria in req
+ * @exception servletException
+ * @exception IOException
+ * @exception EBaseException
*/
public synchronized NameValuePairs retrieveLogContent(Hashtable<String, String> req) throws ServletException,
IOException, EBaseException {
@@ -94,8 +92,8 @@ public class ConsoleLog implements ILogEventListener {
}
/**
- * Retrieve log file list.
- * <br> unimplemented
+ * Retrieve log file list. <br>
+ * unimplemented
*/
public synchronized NameValuePairs retrieveLogList(Hashtable<String, String> req) throws ServletException,
IOException, EBaseException {
diff --git a/pki/base/common/src/com/netscape/certsrv/logging/ELogException.java b/pki/base/common/src/com/netscape/certsrv/logging/ELogException.java
index 90a74ba4..ed36ea5f 100644
--- a/pki/base/common/src/com/netscape/certsrv/logging/ELogException.java
+++ b/pki/base/common/src/com/netscape/certsrv/logging/ELogException.java
@@ -17,16 +17,14 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.logging;
-
import java.util.Locale;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.MessageFormatter;
-
/**
- * This class implements a Log exception. LogExceptions
- * should be caught by LogSubsystem managers.
+ * This class implements a Log exception. LogExceptions should be caught by
+ * LogSubsystem managers.
* <P>
*
* @version $Revision$, $Date$
@@ -39,14 +37,14 @@ public class ELogException extends EBaseException {
*/
private static final long serialVersionUID = -8903703675126348145L;
/**
- * Resource bundle class name.
- */
+ * Resource bundle class name.
+ */
private static final String LOG_RESOURCES = LogResources.class.getName();
/**
* Constructs a log exception.
* <P>
- *
+ *
* @param msgFormat Exception details.
*/
public ELogException(String msgFormat) {
@@ -56,11 +54,12 @@ public class ELogException extends EBaseException {
/**
* Constructs a log exception with a parameter. For example,
+ *
* <PRE>
- * new ELogException("failed to load {0}", fileName);
+ * new ELogException(&quot;failed to load {0}&quot;, fileName);
* </PRE>
* <P>
- *
+ *
* @param msgFormat Exception details in message string format.
* @param param Message string parameter.
*/
@@ -71,9 +70,9 @@ public class ELogException extends EBaseException {
}
/**
- * Constructs a log exception. It can be used to carry
- * a system exception that may contain information about
- * the context. For example,
+ * Constructs a log exception. It can be used to carry a system exception
+ * that may contain information about the context. For example,
+ *
* <PRE>
* try {
* ...
@@ -82,7 +81,7 @@ public class ELogException extends EBaseException {
* }
* </PRE>
* <P>
- *
+ *
* @param msgFormat Exception details in message string format.
* @param param System exception.
*/
@@ -93,10 +92,10 @@ public class ELogException extends EBaseException {
}
/**
- * Constructs a log exception with a list of parameters
- * that will be substituted into the message format.
+ * Constructs a log exception with a list of parameters that will be
+ * substituted into the message format.
* <P>
- *
+ *
* @param msgFormat Exception details in message string format.
* @param params List of message format parameters.
*/
@@ -108,7 +107,7 @@ public class ELogException extends EBaseException {
/**
* Returns a list of parameters.
* <P>
- *
+ *
* @return list of message format parameters.
*/
public Object[] getParameters() {
@@ -116,10 +115,10 @@ public class ELogException extends EBaseException {
}
/**
- * Returns localized exception string. This method should
- * only be called if a localized string is necessary.
+ * Returns localized exception string. This method should only be called if
+ * a localized string is necessary.
* <P>
- *
+ *
* @return Details message.
*/
public String toString() {
@@ -129,7 +128,7 @@ public class ELogException extends EBaseException {
/**
* Returns the string based on the given locale.
* <P>
- *
+ *
* @param locale Locale.
* @return Details message.
*/
@@ -139,13 +138,14 @@ public class ELogException extends EBaseException {
}
/**
- * Retrieves resource bundle name.
- * Subclasses should override this as necessary
+ * Retrieves resource bundle name. Subclasses should override this as
+ * necessary
+ *
* @return String containing name of resource bundle.
*/
protected String getBundleName() {
return LOG_RESOURCES;
}
-
+
}
diff --git a/pki/base/common/src/com/netscape/certsrv/logging/ELogNotFound.java b/pki/base/common/src/com/netscape/certsrv/logging/ELogNotFound.java
index 2dad7aec..7de84733 100644
--- a/pki/base/common/src/com/netscape/certsrv/logging/ELogNotFound.java
+++ b/pki/base/common/src/com/netscape/certsrv/logging/ELogNotFound.java
@@ -17,10 +17,9 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.logging;
-
/**
* Exception for log not found.
- *
+ *
* @version $Revision$, $Date$
*/
public class ELogNotFound extends ELogException {
@@ -32,6 +31,7 @@ public class ELogNotFound extends ELogException {
/**
* Constructs a exception for a missing required log.
+ *
* @param errorString Detailed error message.
*/
public ELogNotFound(String errorString) {
diff --git a/pki/base/common/src/com/netscape/certsrv/logging/ELogPluginNotFound.java b/pki/base/common/src/com/netscape/certsrv/logging/ELogPluginNotFound.java
index efac65a2..6c434aff 100644
--- a/pki/base/common/src/com/netscape/certsrv/logging/ELogPluginNotFound.java
+++ b/pki/base/common/src/com/netscape/certsrv/logging/ELogPluginNotFound.java
@@ -17,10 +17,9 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.logging;
-
/**
* Exception for log plugin not found.
- *
+ *
* @version $Revision$, $Date$
*/
public class ELogPluginNotFound extends ELogException {
@@ -32,10 +31,10 @@ public class ELogPluginNotFound extends ELogException {
/**
* Constructs a exception for a missing log plugin.
+ *
* @param errorString Detailed error message.
*/
public ELogPluginNotFound(String errorString) {
super(errorString);
}
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/logging/IBundleLogEvent.java b/pki/base/common/src/com/netscape/certsrv/logging/IBundleLogEvent.java
index 44a4283b..a1a10304 100644
--- a/pki/base/common/src/com/netscape/certsrv/logging/IBundleLogEvent.java
+++ b/pki/base/common/src/com/netscape/certsrv/logging/IBundleLogEvent.java
@@ -17,23 +17,19 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.logging;
-
-
-
/**
- * An interface which all loggable events must implement.
- * See ILogEvent class.
- * This class maintains a resource bundle name for given
- * event type.
- *
+ * An interface which all loggable events must implement. See ILogEvent class.
+ * This class maintains a resource bundle name for given event type.
+ *
* @version $Revision$, $Date$
*/
public interface IBundleLogEvent extends ILogEvent {
/**
- * Sets the name of the resource bundle to be associated
- * with this event type.
- * @param bundle name of resource bundle.
- */
+ * Sets the name of the resource bundle to be associated with this event
+ * type.
+ *
+ * @param bundle name of resource bundle.
+ */
public void setBundleName(String bundle);
}
diff --git a/pki/base/common/src/com/netscape/certsrv/logging/ILogEvent.java b/pki/base/common/src/com/netscape/certsrv/logging/ILogEvent.java
index d0caca71..07bd67d0 100644
--- a/pki/base/common/src/com/netscape/certsrv/logging/ILogEvent.java
+++ b/pki/base/common/src/com/netscape/certsrv/logging/ILogEvent.java
@@ -17,80 +17,81 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.logging;
-
import java.io.Serializable;
import java.util.Locale;
-
/**
- * An interface which all loggable events must implement. CMS comes
- * with a limited set of ILogEvent types to implement: audit, system, and
- * signed audit. This is the base class of all the subsequent implemented types.
- * A log event represents a certain kind of log message designed for a specific purpose.
- * For instance, an audit type event represents messages having to do with auditable CMS
- * actions. The resulting message will ultimately appear into a specific log file.
- *
+ * An interface which all loggable events must implement. CMS comes with a
+ * limited set of ILogEvent types to implement: audit, system, and signed audit.
+ * This is the base class of all the subsequent implemented types. A log event
+ * represents a certain kind of log message designed for a specific purpose. For
+ * instance, an audit type event represents messages having to do with auditable
+ * CMS actions. The resulting message will ultimately appear into a specific log
+ * file.
+ *
* @version $Revision$, $Date$
*/
public interface ILogEvent extends Serializable {
/**
* Retrieves event time stamp.
+ *
* @return Long integer of the time the event was created.
*/
public long getTimeStamp();
/**
- * Retrieves log source.
- * This is an id of the subsystem responsible
- * for creating the log event.
+ * Retrieves log source. This is an id of the subsystem responsible for
+ * creating the log event.
+ *
* @return Integer source id.
*/
public int getSource();
-
/**
- * Retrieves log level.
- * The log level of an event represents its relative importance
- * or severity within CMS.
+ * Retrieves log level. The log level of an event represents its relative
+ * importance or severity within CMS.
+ *
* @return Integer log level value.
*/
public int getLevel();
/**
* Retrieves NT specific log event type.
+ *
* @return Integer NTEventType value.
*/
public int getNTEventType();
/**
- * Retrieves multiline attribute.
- * Does this message consiste of more than one line.
- * @return Boolean of multiline status.
- */
+ * Retrieves multiline attribute. Does this message consiste of more than
+ * one line.
+ *
+ * @return Boolean of multiline status.
+ */
public boolean getMultiline();
-
/**
- * Retrieves log event type. Each type of event
- * has an associated String type value.
+ * Retrieves log event type. Each type of event has an associated String
+ * type value.
+ *
* @return String containing the type of event.
*/
public String getEventType();
/**
- * Sets log event type. Each type of event
- * has an associated String type value.
+ * Sets log event type. Each type of event has an associated String type
+ * value.
+ *
* @param eventType String containing the type of event.
*/
public void setEventType(String eventType);
-
/**
- * Returns localized message string. This method should
- * only be called if a localized string is necessary.
+ * Returns localized message string. This method should only be called if a
+ * localized string is necessary.
* <P>
- *
+ *
* @return Details message.
*/
public String toContent();
@@ -98,7 +99,7 @@ public interface ILogEvent extends Serializable {
/**
* Returns the string based on the given locale.
* <P>
- *
+ *
* @param locale locale
* @return Details message.
*/
diff --git a/pki/base/common/src/com/netscape/certsrv/logging/ILogEventFactory.java b/pki/base/common/src/com/netscape/certsrv/logging/ILogEventFactory.java
index f94f20a9..0cf4c23e 100644
--- a/pki/base/common/src/com/netscape/certsrv/logging/ILogEventFactory.java
+++ b/pki/base/common/src/com/netscape/certsrv/logging/ILogEventFactory.java
@@ -17,22 +17,19 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.logging;
-
import java.util.Properties;
-
/**
- * An interface represents a log event factory. This
- * factory will be responsible for creating and returning ILogEvent objects
- * on demand.
- *
+ * An interface represents a log event factory. This factory will be responsible
+ * for creating and returning ILogEvent objects on demand.
+ *
* @version $Revision$, $Date$
*/
public interface ILogEventFactory {
/**
* Creates an event of a particular event type/class.
- *
+ *
* @param evtClass The event type.
* @param prop The resource bundle.
* @param source The subsystem ID who creates the log event.
@@ -43,11 +40,11 @@ public interface ILogEventFactory {
* @return The created ILogEvent object.
*/
public ILogEvent create(int evtClass, Properties prop, int source,
- int level, boolean multiline, String msg, Object params[]);
+ int level, boolean multiline, String msg, Object params[]);
/**
* Releases previously created event.
- *
+ *
* @param event The log event.
*/
public void release(ILogEvent event);
diff --git a/pki/base/common/src/com/netscape/certsrv/logging/ILogEventListener.java b/pki/base/common/src/com/netscape/certsrv/logging/ILogEventListener.java
index 80953ead..48aa11d6 100644
--- a/pki/base/common/src/com/netscape/certsrv/logging/ILogEventListener.java
+++ b/pki/base/common/src/com/netscape/certsrv/logging/ILogEventListener.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.logging;
-
import java.io.IOException;
import java.util.EventListener;
import java.util.Hashtable;
@@ -30,102 +29,105 @@ import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.base.ISubsystem;
import com.netscape.certsrv.common.NameValuePairs;
-
-
/**
- * An interface represents a log event listener.
- * A ILogEventListener is registered to a specific
- * ILogQueue to be notified of created ILogEvents.
- * the log queue will notify all its registered listeners
- * of the logged event. The listener will then proceed to
- * process the event accordingly which will result in a log
- * message existing in some file.
- *
+ * An interface represents a log event listener. A ILogEventListener is
+ * registered to a specific ILogQueue to be notified of created ILogEvents. the
+ * log queue will notify all its registered listeners of the logged event. The
+ * listener will then proceed to process the event accordingly which will result
+ * in a log message existing in some file.
+ *
* @version $Revision$, $Date$
*/
public interface ILogEventListener extends EventListener {
/**
- * The event notification method: Logs event.
- *
+ * The event notification method: Logs event.
+ *
* @param event The log event to be processed.
*/
public void log(ILogEvent event) throws ELogException;
/**
- * Flushes the log buffers (if any). Will result in the messages
- * being actually written to their destination.
+ * Flushes the log buffers (if any). Will result in the messages being
+ * actually written to their destination.
*/
public void flush();
/**
- * Closes the log file and destroys any associated threads.
+ * Closes the log file and destroys any associated threads.
*/
public void shutdown();
/**
* Get the configuration store for the log event listener.
+ *
* @return The configuration store of this log event listener.
*/
public IConfigStore getConfigStore();
/**
* Initialize this log listener
- * @param owner The subsystem.
- * @param config Configuration store for this log listener.
- * @exception initialization error.
+ *
+ * @param owner The subsystem.
+ * @param config Configuration store for this log listener.
+ * @exception initialization error.
*/
- public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException;
+ public void init(ISubsystem owner, IConfigStore config)
+ throws EBaseException;
/**
* Startup the instance.
*/
public void startup()
- throws EBaseException;
+ throws EBaseException;
/**
- * Retrieve last "maxLine" number of system logs with log level >"level"
- * and from source "source". If the parameter is omitted. All entries
- * are sent back.
- * @param req a Hashtable containing the required information such as
- * log entry, log level, log source, and log name.
- * @return NameValue pair list of log messages.
- * @exception ServletException For Servelet errros.
- * @exception IOException For input/output problems.
- * @exception EBaseException For other problems.
+ * Retrieve last "maxLine" number of system logs with log level >"level" and
+ * from source "source". If the parameter is omitted. All entries are sent
+ * back.
+ *
+ * @param req a Hashtable containing the required information such as log
+ * entry, log level, log source, and log name.
+ * @return NameValue pair list of log messages.
+ * @exception ServletException For Servelet errros.
+ * @exception IOException For input/output problems.
+ * @exception EBaseException For other problems.
*/
public NameValuePairs retrieveLogContent(Hashtable<String, String> req) throws ServletException,
IOException, EBaseException;
/**
- * Retrieve list of log files.
- *
- */
+ * Retrieve list of log files.
+ *
+ */
public NameValuePairs retrieveLogList(Hashtable<String, String> req) throws ServletException,
IOException, EBaseException;
/**
* Returns implementation name.
+ *
* @return String name of event listener implementation.
*/
public String getImplName();
/**
* Returns the description of this log event listener.
+ *
* @return String with listener description.
*/
public String getDescription();
/**
- * Return list of default config parameters for this log event listener.
- * @return Vector of default parameters.
- */
+ * Return list of default config parameters for this log event listener.
+ *
+ * @return Vector of default parameters.
+ */
public Vector<String> getDefaultParams();
/**
- * Return list of instance config parameters for this log event listener.
- * @return Vector of instance parameters.
- */
+ * Return list of instance config parameters for this log event listener.
+ *
+ * @return Vector of instance parameters.
+ */
public Vector<String> getInstanceParams();
}
diff --git a/pki/base/common/src/com/netscape/certsrv/logging/ILogQueue.java b/pki/base/common/src/com/netscape/certsrv/logging/ILogQueue.java
index 878b9ba1..5923d330 100644
--- a/pki/base/common/src/com/netscape/certsrv/logging/ILogQueue.java
+++ b/pki/base/common/src/com/netscape/certsrv/logging/ILogQueue.java
@@ -17,40 +17,35 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.logging;
-
-
-
/**
- * An interface represents a log queue. A log queue
- * is a queue of pending log events to be dispatched
- * to a set of registered ILogEventListeners.
- *
+ * An interface represents a log queue. A log queue is a queue of pending log
+ * events to be dispatched to a set of registered ILogEventListeners.
+ *
* @version $Revision$, $Date$
*/
public interface ILogQueue {
/**
* Dispatch the log event to all registered log event listeners.
- *
+ *
* @param evt the log event
*/
public void log(ILogEvent evt);
/**
- * Flushes log queue, flushes all registered listeners.
- * Messages should be written to their destination.
+ * Flushes log queue, flushes all registered listeners. Messages should be
+ * written to their destination.
*/
public void flush();
/**
* Registers an event listener.
- *
- * @param listener The log event listener to be registered
- * to this queue.
+ *
+ * @param listener The log event listener to be registered to this queue.
*/
public void addLogEventListener(ILogEventListener listener);
- /**
+ /**
* Removes an event listener.
*
* @param listener The log event listener to be removed from this queue.
@@ -60,7 +55,7 @@ public interface ILogQueue {
/**
* Initializes the log queue.
* <P>
- *
+ *
*/
public void init();
diff --git a/pki/base/common/src/com/netscape/certsrv/logging/ILogSubsystem.java b/pki/base/common/src/com/netscape/certsrv/logging/ILogSubsystem.java
index 2bdba0ab..13495b10 100644
--- a/pki/base/common/src/com/netscape/certsrv/logging/ILogSubsystem.java
+++ b/pki/base/common/src/com/netscape/certsrv/logging/ILogSubsystem.java
@@ -17,22 +17,19 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.logging;
-
import java.util.Hashtable;
import java.util.Vector;
import com.netscape.certsrv.base.ISubsystem;
-
/**
- * An interface that represents a logging component. The logging
- * component is a framework that handles different types of log types,
- * each represented by an ILogEventListener, and each implements a log
- * plugin. CMS comes
- * with three standard log types: "signedAudit", "system", and
- * "transaction". Each log plugin can be instantiated into log
- * instances. Each log instance can be individually configured and is
- * associated with its own configuration entries in the configuration file.
+ * An interface that represents a logging component. The logging component is a
+ * framework that handles different types of log types, each represented by an
+ * ILogEventListener, and each implements a log plugin. CMS comes with three
+ * standard log types: "signedAudit", "system", and "transaction". Each log
+ * plugin can be instantiated into log instances. Each log instance can be
+ * individually configured and is associated with its own configuration entries
+ * in the configuration file.
* <P>
*
* @version $Revision$, $Date$
@@ -45,15 +42,17 @@ public interface ILogSubsystem extends ISubsystem {
public static final String ID = "log";
/**
- * Retrieve plugin name (implementation name) of the log event
- * listener. If no plug name found, an empty string is returned
+ * Retrieve plugin name (implementation name) of the log event listener. If
+ * no plug name found, an empty string is returned
+ *
* @param log the log event listener
* @return the log event listener's plugin name
- */
+ */
public String getLogPluginName(ILogEventListener log);
/**
* Retrieve the log event listener by instance name
+ *
* @param insName the log instance name in String
* @return the log instance in ILogEventListener
*/
@@ -61,44 +60,47 @@ public interface ILogSubsystem extends ISubsystem {
/**
* get the list of log plugins that are available
- * @return log plugins in a Hashtable. Each entry in the
- * Hashtable contains the name/value pair of pluginName/LogPlugin
+ *
+ * @return log plugins in a Hashtable. Each entry in the Hashtable contains
+ * the name/value pair of pluginName/LogPlugin
* @see LogPlugin
*/
- public Hashtable<String, LogPlugin> getLogPlugins();
+ public Hashtable<String, LogPlugin> getLogPlugins();
/**
* get the list of log instances that are available
- * @return log instances in a Hashtable. Each entry in the
- * Hashtable contains the name/value pair of instName/ILogEventListener
+ *
+ * @return log instances in a Hashtable. Each entry in the Hashtable
+ * contains the name/value pair of instName/ILogEventListener
* @see LogPlugin
*/
public Hashtable<String, ILogEventListener> getLogInsts();
/**
- * Get the default configuration parameter names associated with a
- * plugin. It is used by
- * administration servlet to handle log configuration when a new
- * log instance is added.
- * @param implName The implementation name for which the
- * configuration parameters are to be configured
- * @return a Vector of default configuration paramter names
- * associated with this log plugin
- * @exception ELogException when instantiation of the plugin
- * implementation fails.
+ * Get the default configuration parameter names associated with a plugin.
+ * It is used by administration servlet to handle log configuration when a
+ * new log instance is added.
+ *
+ * @param implName The implementation name for which the configuration
+ * parameters are to be configured
+ * @return a Vector of default configuration paramter names associated with
+ * this log plugin
+ * @exception ELogException when instantiation of the plugin implementation
+ * fails.
*/
public Vector<String> getLogDefaultParams(String implName) throws
ELogException;
/**
- * Get the default configuration parameter names associated with a
- * log instance. It is used by administration servlet to handle
- * log instance configuration.
- * @param insName The instance name for which the configuration
- * parameters are to be configured
- * @return a Vector of default configuration paramter names
- * associated with this log instance.
+ * Get the default configuration parameter names associated with a log
+ * instance. It is used by administration servlet to handle log instance
+ * configuration.
+ *
+ * @param insName The instance name for which the configuration parameters
+ * are to be configured
+ * @return a Vector of default configuration paramter names associated with
+ * this log instance.
*/
public Vector<String> getLogInstanceParams(String insName)
- throws ELogException;
+ throws ELogException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/logging/ILogger.java b/pki/base/common/src/com/netscape/certsrv/logging/ILogger.java
index 01fbc6b9..d32386cc 100644
--- a/pki/base/common/src/com/netscape/certsrv/logging/ILogger.java
+++ b/pki/base/common/src/com/netscape/certsrv/logging/ILogger.java
@@ -17,23 +17,22 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.logging;
-
import java.util.Properties;
-
/**
- * An interface represents a logger for certificate server. This object is used to
- * issue log messages for the various types of logging event types. A log message results
- * in a ILogEvent being created. This event is then placed on a ILogQueue to be ultimately
- * written to the destination log file. This object also maintains a collection of ILogFactory objects
- * which are used to create the supported types of ILogEvents. CMS comes out of the box with three event
- * types: "signedAudit", "system", and "audit".
- *
+ * An interface represents a logger for certificate server. This object is used
+ * to issue log messages for the various types of logging event types. A log
+ * message results in a ILogEvent being created. This event is then placed on a
+ * ILogQueue to be ultimately written to the destination log file. This object
+ * also maintains a collection of ILogFactory objects which are used to create
+ * the supported types of ILogEvents. CMS comes out of the box with three event
+ * types: "signedAudit", "system", and "audit".
+ *
* @version $Revision$, $Date$
*/
public interface ILogger {
-
- //List of defined log classes.
+
+ // List of defined log classes.
/**
* log class: audit event.
*/
@@ -41,24 +40,24 @@ public interface ILogger {
public static final String PROP_AUDIT = "transaction";
/**
- * log class: system event.
- * System event with log level >= LL_FAILURE will also be logged in error log
+ * log class: system event. System event with log level >= LL_FAILURE will
+ * also be logged in error log
*/
public static final int EV_SYSTEM = 1;
public static final String PROP_SYSTEM = "system";
/**
- * log class: SignedAudit event.
+ * log class: SignedAudit event.
*/
public static final int EV_SIGNED_AUDIT = 2;
public static final String PROP_SIGNED_AUDIT = "signedAudit";
- //List of defined log sources.
-
+ // List of defined log sources.
+
/**
* log source: used by servlet to retrieve all logs
*/
- public static final int S_ALL = 0; //used by servlet only
+ public static final int S_ALL = 0; // used by servlet only
/**
* log source: identify the log entry is from KRA
@@ -136,30 +135,29 @@ public interface ILogger {
*/
public static final int S_TKS = 16;
-
+
/**
- * log source: identify the log entry is from other subsystem
- * eg. policy, security, connector,registration
+ * log source: identify the log entry is from other subsystem eg. policy,
+ * security, connector,registration
*/
public static final int S_OTHER = 20;
-
// List of defined log levels.
/**
* log level: used by servlet to retrieve all level logs
*/
- public static final int LL_ALL = -1; //used by servlet only
- public static final String LL_ALL_STRING = "All"; //used by servlet only
+ public static final int LL_ALL = -1; // used by servlet only
+ public static final String LL_ALL_STRING = "All"; // used by servlet only
/**
* log level: indicate this log entry is debug info
*/
-
+
/**
- * Debug level is depreciated since CMS6.1. Please use
- * CMS.debug() to output messages to debugging file.
+ * Debug level is depreciated since CMS6.1. Please use CMS.debug() to output
+ * messages to debugging file.
*/
- public static final int LL_DEBUG = 0; // depreciated
+ public static final int LL_DEBUG = 0; // depreciated
public static final String LL_DEBUG_STRING = "Debug";
/**
@@ -199,20 +197,20 @@ public interface ILogger {
public static final String LL_SECURITY_STRING = "Security";
/**
- * "SubjectID" for system-initiated events logged
- * in signed audit log messages
+ * "SubjectID" for system-initiated events logged in signed audit log
+ * messages
*/
public static final String SYSTEM_UID = "$System$";
/**
- * A constant string value used to denote a single "unknown" identity
- * in signed audit log messages
+ * A constant string value used to denote a single "unknown" identity in
+ * signed audit log messages
*/
public static final String UNIDENTIFIED = "$Unidentified$";
/**
- * A constant string value used to denote a single "non-role" identity
- * in signed audit log messages
+ * A constant string value used to denote a single "non-role" identity in
+ * signed audit log messages
*/
public static final String NONROLEUSER = "$NonRoleUser$";
@@ -221,23 +219,22 @@ public interface ILogger {
*/
public static final String SUCCESS = "Success";
public static final String FAILURE = "Failure";
-
+
/**
- * A constant string value used to denote a "non-applicable"
- * data value in signed audit log messages
+ * A constant string value used to denote a "non-applicable" data value in
+ * signed audit log messages
*/
public final static String SIGNED_AUDIT_NON_APPLICABLE = "N/A";
/**
- * A constant string value used to denote an "empty", or "null",
- * data value in signed audit log messages
+ * A constant string value used to denote an "empty", or "null", data value
+ * in signed audit log messages
*/
public final static String SIGNED_AUDIT_EMPTY_VALUE = "<null>";
/**
- * Constant string values associated with the type of certificate
- * processing stored in the "InfoName" field in certain signed
- * audit log messages
+ * Constant string values associated with the type of certificate processing
+ * stored in the "InfoName" field in certain signed audit log messages
*/
public final static String SIGNED_AUDIT_ACCEPTANCE = "certificate";
public final static String SIGNED_AUDIT_CANCELLATION = "cancelReason";
@@ -258,7 +255,7 @@ public interface ILogger {
* NT event type: correspont to log level LL_FAILURE and above
*/
public static final int NT_ERROR = 1;
-
+
// List of defined log multiline attribute.
/**
* indicate the log message has more than one line
@@ -272,8 +269,9 @@ public interface ILogger {
/**
* Logs an event to the log queue.
- *
- * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or EV_SIGNED_AUDIT.
+ *
+ * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or
+ * EV_SIGNED_AUDIT.
* @param source The source of the log event.
* @param msg The detail message to be logged.
*/
@@ -281,8 +279,9 @@ public interface ILogger {
/**
* Logs an event to the log queue.
- *
- * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or EV_SIGNED_AUDIT.
+ *
+ * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or
+ * EV_SIGNED_AUDIT.
* @param props The resource bundle used for the detailed message.
* @param source The source of the log event.
* @param msg The detail message to be logged.
@@ -291,8 +290,9 @@ public interface ILogger {
/**
* Logs an event to the log queue.
- *
- * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or EV_SIGNED_AUDIT.
+ *
+ * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or
+ * EV_SIGNED_AUDIT.
* @param source The source of the log event.
* @param level The level of the log event.
* @param msg The detail message to be logged.
@@ -301,8 +301,9 @@ public interface ILogger {
/**
* Logs an event to the log queue.
- *
- * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or EV_SIGNED_AUDIT.
+ *
+ * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or
+ * EV_SIGNED_AUDIT.
* @param props The resource bundle used for the detailed message.
* @param source The source of the log event.
* @param level The level of the log event.
@@ -312,8 +313,9 @@ public interface ILogger {
/**
* Logs an event to the log queue.
- *
- * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or EV_SIGNED_AUDIT.
+ *
+ * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or
+ * EV_SIGNED_AUDIT.
* @param source The source of the log event.
* @param level The level of the log event.
* @param msg The detail message to be logged.
@@ -323,8 +325,9 @@ public interface ILogger {
/**
* Logs an event to the log queue.
- *
- * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or EV_SIGNED_AUDIT.
+ *
+ * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or
+ * EV_SIGNED_AUDIT.
* @param source The source of the log event.
* @param level The level of the log event.
* @param msg The detail message to be logged.
@@ -334,8 +337,9 @@ public interface ILogger {
/**
* Logs an event to the log queue.
- *
- * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or EV_SIGNED_AUDIT.
+ *
+ * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or
+ * EV_SIGNED_AUDIT.
* @param props The resource bundle used for the detailed message.
* @param source The source of the log event.
* @param msg The detail message to be logged.
@@ -345,8 +349,9 @@ public interface ILogger {
/**
* Logs an event to the log queue.
- *
- * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or EV_SIGNED_AUDIT.
+ *
+ * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or
+ * EV_SIGNED_AUDIT.
* @param props The resource bundle used for the detailed message.
* @param source The source of the log event.
* @param level The level of the log event.
@@ -354,12 +359,13 @@ public interface ILogger {
* @param param The parameter in the detail message.
*/
public void log(int evtClass, Properties props, int source, int level, String msg,
- Object param);
+ Object param);
/**
* Logs an event to the log queue.
- *
- * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or EV_SIGNED_AUDIT.
+ *
+ * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or
+ * EV_SIGNED_AUDIT.
* @param prop The resource bundle used for the detailed message.
* @param source The source of the log event.
* @param level The level of the log event.
@@ -367,119 +373,145 @@ public interface ILogger {
* @param params The parameters in the detail message.
*/
public void log(int evtClass, Properties prop, int source, int level, String msg,
- Object params[]);
+ Object params[]);
- //multiline log
+ // multiline log
/**
* Logs an event to the log queue.
- *
- * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or EV_SIGNED_AUDIT.
+ *
+ * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or
+ * EV_SIGNED_AUDIT.
* @param source The source of the log event.
* @param msg The detail message to be logged.
- * @param multiline true If the message has more than one line, otherwise false.
+ * @param multiline true If the message has more than one line, otherwise
+ * false.
*/
public void log(int evtClass, int source, String msg, boolean multiline);
/**
* Logs an event to the log queue.
- *
- * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or EV_SIGNED_AUDIT.
+ *
+ * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or
+ * EV_SIGNED_AUDIT.
* @param props The resource bundle used for the detailed message.
* @param source The source of the log event.
* @param msg The detail message to be logged.
- * @param multiline True if the message has more than one line, otherwise false.
+ * @param multiline True if the message has more than one line, otherwise
+ * false.
*/
public void log(int evtClass, Properties props, int source, String msg, boolean multiline);
/**
* Logs an event to the log queue.
- *
- * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or EV_SIGNED_AUDIT.
+ *
+ * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or
+ * EV_SIGNED_AUDIT.
* @param source The source of the log event.
* @param level The level of the log event.
* @param msg The detail message to be logged.
- * @param multiline True if the message has more than one line, otherwise false.
+ * @param multiline True if the message has more than one line, otherwise
+ * false.
*/
public void log(int evtClass, int source, int level, String msg, boolean multiline);
/**
* Logs an event to the log queue.
- *
- * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or EV_SIGNED_AUDIT.
+ *
+ * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or
+ * EV_SIGNED_AUDIT.
* @param props The resource bundle used for the detailed message.
* @param source The source of the log event.
* @param level The level of the log event.
* @param msg The detail message to be logged.
- * @param multiline True if the message has more than one line, otherwise false.
+ * @param multiline True if the message has more than one line, otherwise
+ * false.
*/
public void log(int evtClass, Properties props, int source, int level, String msg, boolean multiline);
/**
* Logs an event to the log queue.
- *
- * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or EV_SIGNED_AUDIT.
+ *
+ * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or
+ * EV_SIGNED_AUDIT.
* @param source The source of the log event.
* @param level The level of the log event.
* @param msg The detail message to be logged.
* @param param The parameter in the detail message.
- * @param multiline True if the message has more than one line, otherwise false.
+ * @param multiline True if the message has more than one line, otherwise
+ * false.
*/
public void log(int evtClass, int source, int level, String msg, Object param, boolean multiline);
/**
* Logs an event to the log queue.
- *
- * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or EV_SIGNED_AUDIT.
+ *
+ * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or
+ * EV_SIGNED_AUDIT.
* @param props The resource bundle used for the detailed message.
* @param source TTTTsource of the log event.
* @param msg The detail message to be logged.
* @param param The parameter in the detail message.
- * @param multiline True if the message has more than one line, otherwise false.
+ * @param multiline True if the message has more than one line, otherwise
+ * false.
*/
public void log(int evtClass, Properties props, int source, String msg, Object param, boolean multiline);
/**
* Logs an event to the log queue.
- *
- * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or EV_SIGNED_AUDIT.
+ *
+ * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or
+ * EV_SIGNED_AUDIT.
* @param props The resource bundle used for the detailed message.
* @param source The source of the log event.
* @param level The level of the log event.
* @param msg The detail message to be logged.
* @param param The parameter in the detail message.
- * @param multiline True if the message has more than one line, otherwise false.
+ * @param multiline True if the message has more than one line, otherwise
+ * false.
*/
public void log(int evtClass, Properties props, int source, int level, String msg,
- Object param, boolean multiline);
+ Object param, boolean multiline);
/**
* Logs an event to the log queue.
- *
- * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or EV_SIGNED_AUDIT.
+ *
+ * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or
+ * EV_SIGNED_AUDIT.
* @param prop The resource bundle used for the detailed message.
* @param source The source of the log event.
* @param level The level of the log event.
* @param msg The detail message to be logged.
* @param params The parameters in the detail message.
- * @param multiline True if the message has more than one line, otherwise false.
+ * @param multiline True if the message has more than one line, otherwise
+ * false.
*/
public void log(int evtClass, Properties prop, int source, int level, String msg,
- Object params[], boolean multiline);
+ Object params[], boolean multiline);
/*
* Generates an ILogEvent
- * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or EV_SIGNED_AUDIT.
+ *
+ * @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM or
+ * EV_SIGNED_AUDIT.
+ *
* @param props The resource bundle used for the detailed message.
+ *
* @param source The source of the log event.
+ *
* @param level The level of the log event.
+ *
* @param msg The detail message to be logged.
+ *
* @param params The parameters in the detail message.
- * @param multiline True if the message has more than one line, otherwise false.
+ *
+ * @param multiline True if the message has more than one line, otherwise
+ * false.
+ *
* @return ILogEvent, a log event.
*/
public ILogEvent create(int evtClass, Properties prop, int source, int level,
- String msg, Object params[], boolean multiline);
+ String msg, Object params[], boolean multiline);
/**
* Register a log event factory. Which will create the desired ILogEvents.
@@ -487,8 +519,8 @@ public interface ILogger {
public void register(int evtClass, ILogEventFactory f);
/**
- * Retrieves the associated log queue. The log queue is where issued log events
- * are collected for later processing.
+ * Retrieves the associated log queue. The log queue is where issued log
+ * events are collected for later processing.
*/
public ILogQueue getLogQueue();
diff --git a/pki/base/common/src/com/netscape/certsrv/logging/LogPlugin.java b/pki/base/common/src/com/netscape/certsrv/logging/LogPlugin.java
index b8195eec..9d7a5cc4 100644
--- a/pki/base/common/src/com/netscape/certsrv/logging/LogPlugin.java
+++ b/pki/base/common/src/com/netscape/certsrv/logging/LogPlugin.java
@@ -17,18 +17,16 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.logging;
-
import com.netscape.certsrv.base.Plugin;
-
/**
* This class represents a registered logger plugin.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class LogPlugin extends Plugin {
- public LogPlugin (String id, String path) {
+ public LogPlugin(String id, String path) {
super(id, path);
}
}
diff --git a/pki/base/common/src/com/netscape/certsrv/logging/LogResources.java b/pki/base/common/src/com/netscape/certsrv/logging/LogResources.java
index 6a7472ff..33615443 100644
--- a/pki/base/common/src/com/netscape/certsrv/logging/LogResources.java
+++ b/pki/base/common/src/com/netscape/certsrv/logging/LogResources.java
@@ -17,17 +17,15 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.logging;
-
import java.util.ListResourceBundle;
import java.util.ResourceBundle;
import com.netscape.certsrv.base.BaseResources;
-
/**
* This is the fallback resource bundle for all log events.
* <P>
- *
+ *
* @version $Revision$, $Date$
* @see java.util.ListResourceBundle
*/
@@ -35,9 +33,9 @@ public class LogResources extends ListResourceBundle {
public static final String BASE_RESOURCES = BaseResources.class.getName();
/**
- * Contructs a log resource bundle and sets it's parent to the base
- * resource bundle.
- *
+ * Contructs a log resource bundle and sets it's parent to the base resource
+ * bundle.
+ *
* @see com.netscape.certsrv.base.BaseResources
*/
public LogResources() {
@@ -47,6 +45,7 @@ public class LogResources extends ListResourceBundle {
/**
* Returns the content of this resource.
+ *
* @return Array of objects making up the contents of this resource.
*/
public Object[][] getContents() {
diff --git a/pki/base/common/src/com/netscape/certsrv/logging/SignedAuditEvent.java b/pki/base/common/src/com/netscape/certsrv/logging/SignedAuditEvent.java
index ab86a4ce..099ab701 100644
--- a/pki/base/common/src/com/netscape/certsrv/logging/SignedAuditEvent.java
+++ b/pki/base/common/src/com/netscape/certsrv/logging/SignedAuditEvent.java
@@ -17,20 +17,18 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.logging;
-
import java.text.MessageFormat;
import java.util.Locale;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.MessageFormatter;
-
/**
- * The log event object that carries message detail of a log event
- * that goes into the Signed Audit Event log. This log has the
- * property of being digitally signed for security considerations.
- *
- *
+ * The log event object that carries message detail of a log event that goes
+ * into the Signed Audit Event log. This log has the property of being digitally
+ * signed for security considerations.
+ *
+ *
* @version $Revision$, $Date$
* @see java.text.MessageFormat
* @see com.netscape.certsrv.logging.LogResources
@@ -52,18 +50,18 @@ public class SignedAuditEvent implements IBundleLogEvent {
private boolean mMultiline = false;
private long mTimeStamp = System.currentTimeMillis();
- private static final String INVALID_LOG_LEVEL="log level: {0} is invalid, should be 0-6";
+ private static final String INVALID_LOG_LEVEL = "log level: {0} is invalid, should be 0-6";
/**
- * The bundle name for this event.
- * ....not anymore...keep for now and clean up later
+ * The bundle name for this event. ....not anymore...keep for now and clean
+ * up later
*/
private String mBundleName = LogResources.class.getName();
/**
* Constructs a SignedAuditEvent message event.
* <P>
- *
+ *
* @param msgFormat The message string.
*/
public SignedAuditEvent(String msgFormat) {
@@ -73,11 +71,12 @@ public class SignedAuditEvent implements IBundleLogEvent {
/**
* Constructs a message with a parameter. For example,
+ *
* <PRE>
- * new SignedAuditEvent("failed to load {0}", fileName);
+ * new SignedAuditEvent(&quot;failed to load {0}&quot;, fileName);
* </PRE>
* <P>
- *
+ *
* @param msgFormat Details in message string format.
* @param param Message string parameter.
*/
@@ -88,9 +87,10 @@ public class SignedAuditEvent implements IBundleLogEvent {
}
/**
- * Constructs a message from an exception. It can be used to carry
- * a signed audit exception that may contain information about
- * the context. For example,
+ * Constructs a message from an exception. It can be used to carry a signed
+ * audit exception that may contain information about the context. For
+ * example,
+ *
* <PRE>
* try {
* ...
@@ -99,7 +99,7 @@ public class SignedAuditEvent implements IBundleLogEvent {
* }
* </PRE>
* <P>
- *
+ *
* @param msgFormat Exception details in message string format.
* @param exception System exception.
*/
@@ -112,6 +112,7 @@ public class SignedAuditEvent implements IBundleLogEvent {
/**
* Constructs a message from a base exception. This will use the msgFormat
* from the exception itself.
+ *
* <PRE>
* try {
* ...
@@ -120,7 +121,7 @@ public class SignedAuditEvent implements IBundleLogEvent {
* }
* </PRE>
* <P>
- *
+ *
* @param e CMS exception.
*/
public SignedAuditEvent(Exception e) {
@@ -134,10 +135,10 @@ public class SignedAuditEvent implements IBundleLogEvent {
}
/**
- * Constructs a message event with a list of parameters
- * that will be substituted into the message format.
+ * Constructs a message event with a list of parameters that will be
+ * substituted into the message format.
* <P>
- *
+ *
* @param msgFormat Message string format.
* @param params List of message format parameters.
*/
@@ -149,7 +150,7 @@ public class SignedAuditEvent implements IBundleLogEvent {
/**
* Returns the current message format string.
* <P>
- *
+ *
* @return Details message.
*/
public String getMessage() {
@@ -157,10 +158,10 @@ public class SignedAuditEvent implements IBundleLogEvent {
}
/**
- * Returns a list of parameters. These parameters can be
- * used to assist in formatting the message.
+ * Returns a list of parameters. These parameters can be used to assist in
+ * formatting the message.
* <P>
- *
+ *
* @return List of message format parameters.
*/
public Object[] getParameters() {
@@ -168,10 +169,10 @@ public class SignedAuditEvent implements IBundleLogEvent {
}
/**
- * Returns localized message string. This method should
- * only be called if a localized string is necessary.
+ * Returns localized message string. This method should only be called if a
+ * localized string is necessary.
* <P>
- *
+ *
* @return Details message.
*/
public String toContent() {
@@ -181,7 +182,7 @@ public class SignedAuditEvent implements IBundleLogEvent {
/**
* Returns the string based on the given locale.
* <P>
- *
+ *
* @param locale Locale.
* @return Details message.
*/
@@ -192,8 +193,9 @@ public class SignedAuditEvent implements IBundleLogEvent {
}
/**
- * Sets the resource bundle name for this class instance. This should
- * be overridden by subclasses who have their own resource bundles.
+ * Sets the resource bundle name for this class instance. This should be
+ * overridden by subclasses who have their own resource bundles.
+ *
* @param bundle String with name of resource bundle.
*/
public void setBundleName(String bundle) {
@@ -202,6 +204,7 @@ public class SignedAuditEvent implements IBundleLogEvent {
/**
* Retrieves bundle name.
+ *
* @return String with name of resource bundle.
*/
protected String getBundleName() {
@@ -209,9 +212,9 @@ public class SignedAuditEvent implements IBundleLogEvent {
}
/**
- * Retrieves log source.
- * This is an id of the subsystem responsible
- * for creating the log event.
+ * Retrieves log source. This is an id of the subsystem responsible for
+ * creating the log event.
+ *
* @return Integer source id.
*/
public int getSource() {
@@ -220,6 +223,7 @@ public class SignedAuditEvent implements IBundleLogEvent {
/**
* Sets log source.
+ *
* @param source Integer id of log source.
*/
public void setSource(int source) {
@@ -227,18 +231,18 @@ public class SignedAuditEvent implements IBundleLogEvent {
}
/**
- * Retrieves log level.
- * The log level of an event represents its relative importance
- * or severity within CMS.
+ * Retrieves log level. The log level of an event represents its relative
+ * importance or severity within CMS.
+ *
* @return Integer log level value.
*/
public int getLevel() {
return mLevel;
}
-
/**
* Retrieves NT specific log event type.
+ *
* @return Integer NTEventType value.
*/
public int getNTEventType() {
@@ -246,9 +250,9 @@ public class SignedAuditEvent implements IBundleLogEvent {
}
/**
- * Sets log level, NT log event type.
- * For certain log levels the NT log event type gets
- * set as well.
+ * Sets log level, NT log event type. For certain log levels the NT log
+ * event type gets set as well.
+ *
* @param level Integer log level value.
*/
public void setLevel(int level) {
@@ -279,45 +283,47 @@ public class SignedAuditEvent implements IBundleLogEvent {
/**
* Retrieves log multiline attribute.
- * @return Boolean whether or not this event is multiline.
- * A multiline message simply consists of more than one line.
+ *
+ * @return Boolean whether or not this event is multiline. A multiline
+ * message simply consists of more than one line.
*/
public boolean getMultiline() {
return mMultiline;
}
/**
- * Sets log multiline attribute. A multiline message consists of
- * more than one line.
+ * Sets log multiline attribute. A multiline message consists of more than
+ * one line.
+ *
* @param multiline Boolean multiline value.
*/
public void setMultiline(boolean multiline) {
mMultiline = multiline;
}
-
/**
* Retrieves event time stamp.
+ *
* @return Long integer of the time the event was created.
*/
public long getTimeStamp() {
return mTimeStamp;
}
-
/**
- * Retrieves log event type. Each type of event
- * has an associated String type value.
+ * Retrieves log event type. Each type of event has an associated String
+ * type value.
+ *
* @return String containing the type of event.
*/
public String getEventType() {
return mEventType;
}
-
/**
- * Sets log event type. Each type of event
- * has an associated String type value.
+ * Sets log event type. Each type of event has an associated String type
+ * value.
+ *
* @param eventType String containing the type of event.
*/
public void setEventType(String eventType) {
@@ -325,9 +331,10 @@ public class SignedAuditEvent implements IBundleLogEvent {
}
/**
- * Return string representation of log message.
- * @return String containing log message.
- */
+ * Return string representation of log message.
+ *
+ * @return String containing log message.
+ */
public String toString() {
if (getBundleName() == null) {
MessageFormat detailMessage = new MessageFormat(mMessage);
diff --git a/pki/base/common/src/com/netscape/certsrv/logging/SystemEvent.java b/pki/base/common/src/com/netscape/certsrv/logging/SystemEvent.java
index 83026323..7e39e523 100644
--- a/pki/base/common/src/com/netscape/certsrv/logging/SystemEvent.java
+++ b/pki/base/common/src/com/netscape/certsrv/logging/SystemEvent.java
@@ -17,19 +17,16 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.logging;
-
import java.text.MessageFormat;
import java.util.Locale;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.MessageFormatter;
-
/**
- * The log event object that carries a log message.
- * This class represents System events which are CMS events
- * which need to be logged to a log file.
- *
+ * The log event object that carries a log message. This class represents System
+ * events which are CMS events which need to be logged to a log file.
+ *
* @version $Revision$, $Date$
* @see java.text.MessageFormat
* @see com.netscape.certsrv.logging.LogResources
@@ -56,12 +53,12 @@ public class SystemEvent implements IBundleLogEvent {
*/
private String mBundleName = LogResources.class.getName();
- private static final String INVALID_LOG_LEVEL="log level: {0} is invalid, should be 0-6";
+ private static final String INVALID_LOG_LEVEL = "log level: {0} is invalid, should be 0-6";
/**
* Constructs a SystemEvent message event.
* <P>
- *
+ *
* @param msgFormat The message string.
*/
public SystemEvent(String msgFormat) {
@@ -71,11 +68,12 @@ public class SystemEvent implements IBundleLogEvent {
/**
* Constructs a SystemEvent message with a parameter. For example,
+ *
* <PRE>
- * new SystemEvent("failed to load {0}", fileName);
+ * new SystemEvent(&quot;failed to load {0}&quot;, fileName);
* </PRE>
* <P>
- *
+ *
* @param msgFormat Details in message string format.
* @param param Message string parameter.
*/
@@ -86,9 +84,10 @@ public class SystemEvent implements IBundleLogEvent {
}
/**
- * Constructs a SystemEvent message from an exception. It can be used to carry
- * a system exception that may contain information about
- * the context. For example,
+ * Constructs a SystemEvent message from an exception. It can be used to
+ * carry a system exception that may contain information about the context.
+ * For example,
+ *
* <PRE>
* try {
* ...
@@ -97,7 +96,7 @@ public class SystemEvent implements IBundleLogEvent {
* }
* </PRE>
* <P>
- *
+ *
* @param msgFormat Exception details in message string format.
* @param exception System exception.
*/
@@ -108,8 +107,9 @@ public class SystemEvent implements IBundleLogEvent {
}
/**
- * Constructs a SystemEvent message from a base exception. This will use the msgFormat
- * from the exception itself.
+ * Constructs a SystemEvent message from a base exception. This will use the
+ * msgFormat from the exception itself.
+ *
* <PRE>
* try {
* ...
@@ -118,7 +118,7 @@ public class SystemEvent implements IBundleLogEvent {
* }
* </PRE>
* <P>
- *
+ *
* @param e CMS exception.
*/
public SystemEvent(Exception e) {
@@ -132,10 +132,10 @@ public class SystemEvent implements IBundleLogEvent {
}
/**
- * Constructs a SystemEvent message event with a list of parameters
- * that will be substituted into the message format.
+ * Constructs a SystemEvent message event with a list of parameters that
+ * will be substituted into the message format.
* <P>
- *
+ *
* @param msgFormat Message string format.
* @param params List of message format parameters.
*/
@@ -147,7 +147,7 @@ public class SystemEvent implements IBundleLogEvent {
/**
* Returns the current message format string.
* <P>
- *
+ *
* @return Details message.
*/
public String getMessage() {
@@ -155,10 +155,10 @@ public class SystemEvent implements IBundleLogEvent {
}
/**
- * Returns a list of parameters. These parameters can be
- * used to assist in formatting the message.
+ * Returns a list of parameters. These parameters can be used to assist in
+ * formatting the message.
* <P>
- *
+ *
* @return List of message format parameters.
*/
public Object[] getParameters() {
@@ -166,10 +166,10 @@ public class SystemEvent implements IBundleLogEvent {
}
/**
- * Returns localized message string. This method should
- * only be called if a localized string is necessary.
+ * Returns localized message string. This method should only be called if a
+ * localized string is necessary.
* <P>
- *
+ *
* @return Details message.
*/
public String toContent() {
@@ -179,7 +179,7 @@ public class SystemEvent implements IBundleLogEvent {
/**
* Returns the string based on the given locale.
* <P>
- *
+ *
* @param locale Locale.
* @return Details message.
*/
@@ -190,8 +190,9 @@ public class SystemEvent implements IBundleLogEvent {
}
/**
- * Sets the resource bundle name for this class instance. This should
- * be overridden by subclasses who have their own resource bundles.
+ * Sets the resource bundle name for this class instance. This should be
+ * overridden by subclasses who have their own resource bundles.
+ *
* @param bundle String with the name of resource bundle.
*/
public void setBundleName(String bundle) {
@@ -200,6 +201,7 @@ public class SystemEvent implements IBundleLogEvent {
/**
* Retrieves bundle name.
+ *
* @return String with name of resource bundle.
*/
protected String getBundleName() {
@@ -207,9 +209,9 @@ public class SystemEvent implements IBundleLogEvent {
}
/**
- * Retrieves log source.
- * This is an id of the subsystem responsible
- * for creating the log event.
+ * Retrieves log source. This is an id of the subsystem responsible for
+ * creating the log event.
+ *
* @return Integer source id.
*/
public int getSource() {
@@ -217,8 +219,8 @@ public class SystemEvent implements IBundleLogEvent {
}
/**
- * Sets log source.
- * Sets the id of the subsystem issuing the event.
+ * Sets log source. Sets the id of the subsystem issuing the event.
+ *
* @param source Integer source id.
*/
public void setSource(int source) {
@@ -226,9 +228,9 @@ public class SystemEvent implements IBundleLogEvent {
}
/**
- * Retrieves log level.
- * The log level of an event represents its relative importance
- * or severity within CMS.
+ * Retrieves log level. The log level of an event represents its relative
+ * importance or severity within CMS.
+ *
* @return Integer log level value.
*/
public int getLevel() {
@@ -237,6 +239,7 @@ public class SystemEvent implements IBundleLogEvent {
/**
* Retrieves NT specific log event type.
+ *
* @return Integer NTEventType value.
*/
public int getNTEventType() {
@@ -244,9 +247,9 @@ public class SystemEvent implements IBundleLogEvent {
}
/**
- * Sets log level, NT log event type.
- * For certain log levels the NT log event type gets
- * set as well.
+ * Sets log level, NT log event type. For certain log levels the NT log
+ * event type gets set as well.
+ *
* @param level Integer log level value.
*/
public void setLevel(int level) {
@@ -277,16 +280,18 @@ public class SystemEvent implements IBundleLogEvent {
/**
* Retrieves log multiline attribute.
- * @return Boolean whether or not this event is multiline.
- * A multiline message simply consists of more than one line.
+ *
+ * @return Boolean whether or not this event is multiline. A multiline
+ * message simply consists of more than one line.
*/
public boolean getMultiline() {
return mMultiline;
}
/**
- * Sets log multiline attribute. A multiline message consists of
- * more than one line.
+ * Sets log multiline attribute. A multiline message consists of more than
+ * one line.
+ *
* @param multiline Boolean multiline value.
*/
public void setMultiline(boolean multiline) {
@@ -295,6 +300,7 @@ public class SystemEvent implements IBundleLogEvent {
/**
* Retrieves event time stamp.
+ *
* @return Long integer of the time the event was created.
*/
public long getTimeStamp() {
@@ -302,18 +308,19 @@ public class SystemEvent implements IBundleLogEvent {
}
/**
- * Retrieves log event type. Each type of event
- * has an associated String type value.
+ * Retrieves log event type. Each type of event has an associated String
+ * type value.
+ *
* @return String containing the type of event.
*/
public String getEventType() {
return mEventType;
}
-
/**
- * Sets log event type. Each type of event
- * has an associated String type value.
+ * Sets log event type. Each type of event has an associated String type
+ * value.
+ *
* @param eventType String containing the type of event.
*/
public void setEventType(String eventType) {
@@ -321,9 +328,10 @@ public class SystemEvent implements IBundleLogEvent {
}
/**
- * Return string representation of log message.
- * @return String containing log message.
- */
+ * Return string representation of log message.
+ *
+ * @return String containing log message.
+ */
public String toString() {
if (getBundleName() == null) {
MessageFormat detailMessage = new MessageFormat(mMessage);
diff --git a/pki/base/common/src/com/netscape/certsrv/notification/ENotificationException.java b/pki/base/common/src/com/netscape/certsrv/notification/ENotificationException.java
index 4e34ded3..fffc8ede 100644
--- a/pki/base/common/src/com/netscape/certsrv/notification/ENotificationException.java
+++ b/pki/base/common/src/com/netscape/certsrv/notification/ENotificationException.java
@@ -17,14 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.notification;
-
import com.netscape.certsrv.base.EBaseException;
-
/**
* A class represents a notification exception.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class ENotificationException extends EBaseException {
diff --git a/pki/base/common/src/com/netscape/certsrv/notification/IEmailFormProcessor.java b/pki/base/common/src/com/netscape/certsrv/notification/IEmailFormProcessor.java
index ace09a8c..b0be4862 100644
--- a/pki/base/common/src/com/netscape/certsrv/notification/IEmailFormProcessor.java
+++ b/pki/base/common/src/com/netscape/certsrv/notification/IEmailFormProcessor.java
@@ -17,17 +17,15 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.notification;
-
import java.util.Hashtable;
import java.util.Vector;
-
/**
- * formulates the final email. Escape character '\' is understood.
- * '$' is used preceeding a token name. A token name should not be a
- * substring of any other token name
+ * formulates the final email. Escape character '\' is understood. '$' is used
+ * preceeding a token name. A token name should not be a substring of any other
+ * token name
* <p>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IEmailFormProcessor {
@@ -58,16 +56,19 @@ public interface IEmailFormProcessor {
public final static String TOKEN_REVOCATION_DATE = "RevocationDate";
/*
- * takes the form template, parse and replace all $tokens with the
- * right values. It handles escape character '\'
+ * takes the form template, parse and replace all $tokens with the right
+ * values. It handles escape character '\'
+ *
* @param form The locale specific form template,
- * @param tok2vals a hashtable containing one to one mapping
- * from $tokens used by the admins in the form template to the real
- * values corresponding to the $tokens
+ *
+ * @param tok2vals a hashtable containing one to one mapping from $tokens
+ * used by the admins in the form template to the real values corresponding
+ * to the $tokens
+ *
* @return mail content
*/
public String getEmailContent(String form,
- Hashtable<String, Object> tok2vals);
+ Hashtable<String, Object> tok2vals);
/**
* takes a vector of strings and concatenate them
@@ -79,4 +80,3 @@ public interface IEmailFormProcessor {
*/
public void log(int level, String msg);
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/notification/IEmailResolver.java b/pki/base/common/src/com/netscape/certsrv/notification/IEmailResolver.java
index 49d0851e..bb421858 100644
--- a/pki/base/common/src/com/netscape/certsrv/notification/IEmailResolver.java
+++ b/pki/base/common/src/com/netscape/certsrv/notification/IEmailResolver.java
@@ -17,25 +17,24 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.notification;
-
import com.netscape.certsrv.base.EBaseException;
-
/**
- * An email resolver that first checks the request email, if none,
- * then follows by checking the subjectDN of the certificate
+ * An email resolver that first checks the request email, if none, then follows
+ * by checking the subjectDN of the certificate
* <p>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IEmailResolver {
/**
- * returns an email address by using the resolver keys. The
- * return value can possibly be null
+ * returns an email address by using the resolver keys. The return value can
+ * possibly be null
+ *
* @param keys list of keys used for resolving the email address
*/
- public String getEmail(IEmailResolverKeys keys)
- throws EBaseException, ENotificationException;
+ public String getEmail(IEmailResolverKeys keys)
+ throws EBaseException, ENotificationException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/notification/IEmailResolverKeys.java b/pki/base/common/src/com/netscape/certsrv/notification/IEmailResolverKeys.java
index d1a6889c..8ba95fa5 100644
--- a/pki/base/common/src/com/netscape/certsrv/notification/IEmailResolverKeys.java
+++ b/pki/base/common/src/com/netscape/certsrv/notification/IEmailResolverKeys.java
@@ -17,16 +17,14 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.notification;
-
import com.netscape.certsrv.base.IAttrSet;
-
/**
- * An interface represents email resolver (ordered) keys for resolving
- * emails
- * e.g. request/cert, cert/request, request, request/cert/subjectalternatename etc.
+ * An interface represents email resolver (ordered) keys for resolving emails
+ * e.g. request/cert, cert/request, request, request/cert/subjectalternatename
+ * etc.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IEmailResolverKeys extends IAttrSet {
diff --git a/pki/base/common/src/com/netscape/certsrv/notification/IEmailTemplate.java b/pki/base/common/src/com/netscape/certsrv/notification/IEmailTemplate.java
index bcda466d..5320761f 100644
--- a/pki/base/common/src/com/netscape/certsrv/notification/IEmailTemplate.java
+++ b/pki/base/common/src/com/netscape/certsrv/notification/IEmailTemplate.java
@@ -17,13 +17,10 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.notification;
-
-
-
/**
- * Files to be processed and returned to the requested parties. It
- * is a template with $tokens to be used by the form/template processor.
- *
+ * Files to be processed and returned to the requested parties. It is a template
+ * with $tokens to be used by the form/template processor.
+ *
* @version $Revision$, $Date$
*/
@@ -36,7 +33,7 @@ public interface IEmailTemplate {
*/
public String getTemplateName();
- /**
+ /**
* @return true if template is an html file, false otherwise
*/
public boolean isHTML();
diff --git a/pki/base/common/src/com/netscape/certsrv/notification/IMailNotification.java b/pki/base/common/src/com/netscape/certsrv/notification/IMailNotification.java
index b537fbbd..0c141981 100644
--- a/pki/base/common/src/com/netscape/certsrv/notification/IMailNotification.java
+++ b/pki/base/common/src/com/netscape/certsrv/notification/IMailNotification.java
@@ -17,17 +17,14 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.notification;
-
import java.io.IOException;
import java.util.Vector;
-
/**
- * This class handles mail notification via SMTP.
- * This class uses <b>smtp.host</b> in the configuration for smtp
- * host. The port default (25) is used. If no smtp specified, local
- * host is used
- *
+ * This class handles mail notification via SMTP. This class uses
+ * <b>smtp.host</b> in the configuration for smtp host. The port default (25) is
+ * used. If no smtp specified, local host is used
+ *
* @version $Revision$, $Date$
*/
public interface IMailNotification {
@@ -39,36 +36,42 @@ public interface IMailNotification {
/**
* sets the "From" field
+ *
* @param from email address of the sender
*/
public void setFrom(String from);
/**
* sets the "Subject" field
+ *
* @param subject subject of the email
*/
public void setSubject(String subject);
/**
* sets the "Content-Type" field
+ *
* @param contentType content type of the email
*/
public void setContentType(String contentType);
/**
* sets the content of the email
+ *
* @param content the message content
*/
public void setContent(String content);
/**
* sets the recipients' email addresses
+ *
* @param addresses a list of email addresses of the recipients
*/
public void setTo(Vector<String> addresses);
/**
* sets the recipient's email address
+ *
* @param to address of the recipient email address
*/
public void setTo(String to);
diff --git a/pki/base/common/src/com/netscape/certsrv/notification/NotificationResources.java b/pki/base/common/src/com/netscape/certsrv/notification/NotificationResources.java
index 40d9e80e..e7a2be40 100644
--- a/pki/base/common/src/com/netscape/certsrv/notification/NotificationResources.java
+++ b/pki/base/common/src/com/netscape/certsrv/notification/NotificationResources.java
@@ -17,14 +17,11 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.notification;
-
import java.util.ListResourceBundle;
-
/**
- * A class represents a resource bundle for the
- * Mail Notification package
- *
+ * A class represents a resource bundle for the Mail Notification package
+ *
* @version $Revision$, $Date$
*/
public class NotificationResources extends ListResourceBundle {
@@ -37,8 +34,7 @@ public class NotificationResources extends ListResourceBundle {
}
/**
- * Constants. The suffix represents the number of
- * possible parameters.
+ * Constants. The suffix represents the number of possible parameters.
*/
static final Object[][] contents = {};
diff --git a/pki/base/common/src/com/netscape/certsrv/ocsp/IDefStore.java b/pki/base/common/src/com/netscape/certsrv/ocsp/IDefStore.java
index 82c5821b..bc62dabe 100644
--- a/pki/base/common/src/com/netscape/certsrv/ocsp/IDefStore.java
+++ b/pki/base/common/src/com/netscape/certsrv/ocsp/IDefStore.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.ocsp;
-
import java.math.BigInteger;
import java.security.cert.X509CRL;
import java.util.Date;
@@ -27,28 +26,26 @@ import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.dbs.crldb.ICRLIssuingPointRecord;
import com.netscape.certsrv.dbs.repository.IRepositoryRecord;
-
/**
* This class defines an Online Certificate Status Protocol (OCSP) store which
* has been extended to provide information from the internal database.
- * <P>
- *
+ * <P>
+ *
* @version $Revision$, $Date$
*/
-public interface IDefStore extends IOCSPStore
-{
+public interface IDefStore extends IOCSPStore {
/**
* This method retrieves the number of CRL updates since startup.
* <P>
- *
+ *
* @return count the number of OCSP default stores
*/
- public int getStateCount();
+ public int getStateCount();
/**
* This method retrieves the number of OCSP requests since startup.
* <P>
- *
+ *
* @param id a string associated with an OCSP request
* @return count the number of this type of OCSP requests
*/
@@ -57,30 +54,30 @@ public interface IDefStore extends IOCSPStore
/**
* This method creates a an OCSP default store repository record.
* <P>
- *
+ *
* @return IRepositoryRecord an instance of the repository record object
*/
- public IRepositoryRecord createRepositoryRecord();
+ public IRepositoryRecord createRepositoryRecord();
/**
* This method adds a request to the default OCSP store repository.
* <P>
- *
+ *
* @param name a string representing the name of this request
* @param thisUpdate the current request
* @param rec an instance of the repository record object
- * @exception EBaseException occurs when there is an error attempting to
- * add this request to the repository
+ * @exception EBaseException occurs when there is an error attempting to add
+ * this request to the repository
*/
public void addRepository(String name, String thisUpdate,
- IRepositoryRecord rec)
- throws EBaseException;
+ IRepositoryRecord rec)
+ throws EBaseException;
/**
* This method specifies whether or not to wait for the Certificate
* Revocation List (CRL) to be updated.
* <P>
- *
+ *
* @return boolean true or false
*/
public boolean waitOnCRLUpdate();
@@ -88,7 +85,7 @@ public interface IDefStore extends IOCSPStore
/**
* This method updates the specified CRL.
* <P>
- *
+ *
* @param crl the CRL to be updated
* @exception EBaseException occurs when the CRL cannot be updated
*/
@@ -97,44 +94,44 @@ public interface IDefStore extends IOCSPStore
/**
* This method attempts to read the CRL issuing point.
* <P>
- *
+ *
* @param name the name of the CRL to be read
* @return ICRLIssuingPointRecord the CRL issuing point
* @exception EBaseException occurs when the specified CRL cannot be located
*/
public ICRLIssuingPointRecord readCRLIssuingPoint(String name)
- throws EBaseException;
+ throws EBaseException;
/**
* This method searches all CRL issuing points.
* <P>
- *
+ *
* @param maxSize specifies the largest number of hits from the search
* @return Enumeration a list of the CRL issuing points
* @exception EBaseException occurs when no CRL issuing point exists
*/
public Enumeration searchAllCRLIssuingPointRecord(
- int maxSize)
- throws EBaseException;
+ int maxSize)
+ throws EBaseException;
/**
* This method searches all CRL issuing points constrained by the specified
* filtering mechanism.
* <P>
- *
+ *
* @param filter a string which constrains the search
* @param maxSize specifies the largest number of hits from the search
* @return Enumeration a list of the CRL issuing points
* @exception EBaseException occurs when no CRL issuing point exists
*/
public Enumeration searchCRLIssuingPointRecord(String filter,
- int maxSize)
- throws EBaseException;
+ int maxSize)
+ throws EBaseException;
/**
* This method creates a CRL issuing point record.
* <P>
- *
+ *
* @param name a string representation of this CRL issuing point record
* @param crlNumber the number of this CRL issuing point record
* @param crlSize the size of this CRL issuing point record
@@ -143,39 +140,38 @@ public interface IDefStore extends IOCSPStore
* @return ICRLIssuingPointRecord this CRL issuing point record
*/
public ICRLIssuingPointRecord createCRLIssuingPointRecord(
- String name, BigInteger crlNumber,
- Long crlSize, Date thisUpdate, Date nextUpdate);
+ String name, BigInteger crlNumber,
+ Long crlSize, Date thisUpdate, Date nextUpdate);
/**
* This method adds a CRL issuing point
* <P>
- *
+ *
* @param name a string representation of this CRL issuing point record
* @param rec this CRL issuing point record
* @exception EBaseException occurs when the specified CRL issuing point
- * record cannot be added
+ * record cannot be added
*/
public void addCRLIssuingPoint(String name, ICRLIssuingPointRecord rec)
- throws EBaseException;
+ throws EBaseException;
/**
* This method deletes a CRL issuing point record
* <P>
- *
+ *
* @param id a string representation of this CRL issuing point record
* @exception EBaseException occurs when the specified CRL issuing point
- * record cannot be deleted
+ * record cannot be deleted
*/
public void deleteCRLIssuingPointRecord(String id)
- throws EBaseException;
+ throws EBaseException;
/**
- * This method checks to see if the OCSP response should return good
- * when the certificate is not found.
+ * This method checks to see if the OCSP response should return good when
+ * the certificate is not found.
* <P>
- *
+ *
* @return boolean true or false
*/
public boolean isNotFoundGood();
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/ocsp/IOCSPAuthority.java b/pki/base/common/src/com/netscape/certsrv/ocsp/IOCSPAuthority.java
index b99f6241..71030bce 100644
--- a/pki/base/common/src/com/netscape/certsrv/ocsp/IOCSPAuthority.java
+++ b/pki/base/common/src/com/netscape/certsrv/ocsp/IOCSPAuthority.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.ocsp;
-
import netscape.security.x509.X500Name;
import org.mozilla.jss.asn1.OBJECT_IDENTIFIER;
@@ -30,16 +29,14 @@ import com.netscape.cmsutil.ocsp.BasicOCSPResponse;
import com.netscape.cmsutil.ocsp.ResponderID;
import com.netscape.cmsutil.ocsp.ResponseData;
-
/**
- * This class represents the primary interface for the Online Certificate
- * Status Protocol (OCSP) server.
- * <P>
- *
+ * This class represents the primary interface for the Online Certificate Status
+ * Protocol (OCSP) server.
+ * <P>
+ *
* @version $Revision$, $Date$
*/
-public interface IOCSPAuthority extends ISubsystem
-{
+public interface IOCSPAuthority extends ISubsystem {
public static final String ID = "ocsp";
public final static OBJECT_IDENTIFIER OCSP_NONCE = new OBJECT_IDENTIFIER("1.3.6.1.5.5.7.48.1.2");
@@ -53,16 +50,16 @@ public interface IOCSPAuthority extends ISubsystem
/**
* This method retrieves the OCSP store given its name.
* <P>
- *
+ *
* @param id the string representation of an OCSP store
* @return IOCSPStore an instance of an OCSP store object
*/
- public IOCSPStore getOCSPStore(String id);
+ public IOCSPStore getOCSPStore(String id);
/**
* This method retrieves the signing unit.
* <P>
- *
+ *
* @return ISigningUnit an instance of a signing unit object
*/
public ISigningUnit getSigningUnit();
@@ -70,7 +67,7 @@ public interface IOCSPAuthority extends ISubsystem
/**
* This method retrieves the responder ID by its name.
* <P>
- *
+ *
* @return ResponderID an instance of a responder ID
*/
public ResponderID getResponderIDByName();
@@ -78,16 +75,16 @@ public interface IOCSPAuthority extends ISubsystem
/**
* This method retrieves the responder ID by its hash.
* <P>
- *
+ *
* @return ResponderID an instance of a responder ID
*/
public ResponderID getResponderIDByHash();
/**
- * This method retrieves the default OCSP store
- * (i. e. - information from the internal database).
+ * This method retrieves the default OCSP store (i. e. - information from
+ * the internal database).
* <P>
- *
+ *
* @return IDefStore an instance of the default OCSP store
*/
public IDefStore getDefaultStore();
@@ -95,17 +92,17 @@ public interface IOCSPAuthority extends ISubsystem
/**
* This method sets the supplied algorithm as the default signing algorithm.
* <P>
- *
+ *
* @param algorithm a string representing the requested algorithm
* @exception EBaseException if the algorithm is unknown or disallowed
*/
public void setDefaultAlgorithm(String algorithm)
- throws EBaseException;
+ throws EBaseException;
/**
* This method retrieves the default signing algorithm.
* <P>
- *
+ *
* @return String the name of the default signing algorithm
*/
public String getDefaultAlgorithm();
@@ -113,7 +110,7 @@ public interface IOCSPAuthority extends ISubsystem
/**
* This method retrieves all potential OCSP signing algorithms.
* <P>
- *
+ *
* @return String[] the names of all potential OCSP signing algorithms
*/
public String[] getOCSPSigningAlgorithms();
@@ -121,17 +118,17 @@ public interface IOCSPAuthority extends ISubsystem
/**
* This method logs the specified message at the specified level.
* <P>
- *
+ *
* @param level the log level
* @param msg the log message
*/
public void log(int level, String msg);
/**
- * This method logs the specified message at the specified level given
- * the specified event.
+ * This method logs the specified message at the specified level given the
+ * specified event.
* <P>
- *
+ *
* @param event the log event
* @param level the log message
* @param msg the log message
@@ -141,7 +138,7 @@ public interface IOCSPAuthority extends ISubsystem
/**
* This method retrieves the X500Name of an OCSP server instance.
* <P>
- *
+ *
* @return X500Name an instance of the X500 name object
*/
public X500Name getName();
@@ -149,7 +146,7 @@ public interface IOCSPAuthority extends ISubsystem
/**
* This method retrieves an OCSP server instance digest name as a string.
* <P>
- *
+ *
* @param alg the signing algorithm
* @return String the digest name of the related OCSP server
*/
@@ -158,19 +155,19 @@ public interface IOCSPAuthority extends ISubsystem
/**
* This method signs the basic OCSP response data provided as a parameter.
* <P>
- *
+ *
* @param rd response data
* @return BasicOCSPResponse signed response data
- * @exception EBaseException error associated with an inability to sign
- * the specified response data
+ * @exception EBaseException error associated with an inability to sign the
+ * specified response data
*/
public BasicOCSPResponse sign(ResponseData rd)
- throws EBaseException;
+ throws EBaseException;
/**
* This method compares two byte arrays to see if they are equivalent.
* <P>
- *
+ *
* @param bytes the first byte array
* @param ints the second byte array
* @return boolean true or false
@@ -178,8 +175,10 @@ public interface IOCSPAuthority extends ISubsystem
public boolean arraysEqual(byte[] bytes, byte[] ints);
public void incTotalTime(long inc);
+
public void incSignTime(long inc);
+
public void incLookupTime(long inc);
+
public void incNumOCSPRequest(long inc);
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/ocsp/IOCSPService.java b/pki/base/common/src/com/netscape/certsrv/ocsp/IOCSPService.java
index 8ca8b2f0..cfed9f14 100644
--- a/pki/base/common/src/com/netscape/certsrv/ocsp/IOCSPService.java
+++ b/pki/base/common/src/com/netscape/certsrv/ocsp/IOCSPService.java
@@ -17,53 +17,50 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.ocsp;
-
import com.netscape.certsrv.base.EBaseException;
import com.netscape.cmsutil.ocsp.OCSPRequest;
import com.netscape.cmsutil.ocsp.OCSPResponse;
-
/**
- * This class represents the servlet that serves the Online Certificate
- * Status Protocol (OCSP) requests.
- *
+ * This class represents the servlet that serves the Online Certificate Status
+ * Protocol (OCSP) requests.
+ *
* @version $Revision$ $Date$
*/
-public interface IOCSPService
-{
+public interface IOCSPService {
/**
- * This method validates the information associated with the specified
- * OCSP request and returns an OCSP response.
+ * This method validates the information associated with the specified OCSP
+ * request and returns an OCSP response.
* <P>
- *
+ *
* @param r an OCSP request
- * @return OCSPResponse the OCSP response associated with the specified
- * OCSP request
+ * @return OCSPResponse the OCSP response associated with the specified OCSP
+ * request
* @exception EBaseException an error associated with the inability to
- * process the supplied OCSP request
+ * process the supplied OCSP request
*/
- public OCSPResponse validate(OCSPRequest r)
- throws EBaseException;
+ public OCSPResponse validate(OCSPRequest r)
+ throws EBaseException;
/**
* Returns the in-memory count of the processed OCSP requests.
- *
+ *
* @return number of processed OCSP requests in memory
*/
public long getNumOCSPRequest();
/**
- * Returns the in-memory time (in mini-second) of
- * the processed time for OCSP requests.
- *
+ * Returns the in-memory time (in mini-second) of the processed time for
+ * OCSP requests.
+ *
* @return processed times for OCSP requests
*/
public long getOCSPRequestTotalTime();
/**
- * Returns the in-memory time (in mini-second) of
- * the signing time for OCSP requests.
- *
+ * Returns the in-memory time (in mini-second) of the signing time for OCSP
+ * requests.
+ *
* @return processed times for OCSP requests
*/
public long getOCSPTotalSignTime();
@@ -71,11 +68,9 @@ public interface IOCSPService
public long getOCSPTotalLookupTime();
/**
- * Returns the total data signed
- * for OCSP requests.
- *
+ * Returns the total data signed for OCSP requests.
+ *
* @return processed times for OCSP requests
*/
public long getOCSPTotalData();
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/ocsp/IOCSPStore.java b/pki/base/common/src/com/netscape/certsrv/ocsp/IOCSPStore.java
index ee60105c..080d13de 100644
--- a/pki/base/common/src/com/netscape/certsrv/ocsp/IOCSPStore.java
+++ b/pki/base/common/src/com/netscape/certsrv/ocsp/IOCSPStore.java
@@ -17,46 +17,43 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.ocsp;
-
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.ISubsystem;
import com.netscape.certsrv.common.NameValuePairs;
import com.netscape.cmsutil.ocsp.OCSPRequest;
import com.netscape.cmsutil.ocsp.OCSPResponse;
-
/**
- * This class represents the generic interface for an Online Certificate
- * Status Protocol (OCSP) store. Users can plugin different OCSP stores
- * by extending this class. For example, imagine that if a user wants to
- * use the corporate LDAP server for revocation checking, then the user
- * would merely create a new class that extends this class (e. g. -
+ * This class represents the generic interface for an Online Certificate Status
+ * Protocol (OCSP) store. Users can plugin different OCSP stores by extending
+ * this class. For example, imagine that if a user wants to use the corporate
+ * LDAP server for revocation checking, then the user would merely create a new
+ * class that extends this class (e. g. -
* "public interface ICorporateLDAPStore extends IOCSPStore").
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
-public interface IOCSPStore extends ISubsystem
-{
+public interface IOCSPStore extends ISubsystem {
/**
- * This method validates the information associated with the specified
- * OCSP request and returns an OCSP response.
+ * This method validates the information associated with the specified OCSP
+ * request and returns an OCSP response.
* <P>
- *
+ *
* @param req an OCSP request
- * @return OCSPResponse the OCSP response associated with the specified
- * OCSP request
+ * @return OCSPResponse the OCSP response associated with the specified OCSP
+ * request
* @exception EBaseException an error associated with the inability to
- * process the supplied OCSP request
+ * process the supplied OCSP request
*/
- public OCSPResponse validate(OCSPRequest req)
- throws EBaseException;
+ public OCSPResponse validate(OCSPRequest req)
+ throws EBaseException;
/**
* This method retrieves the configuration parameters associated with this
* OCSP store.
* <P>
- *
+ *
* @return NameValuePairs all configuration items
*/
public NameValuePairs getConfigParameters();
@@ -65,11 +62,10 @@ public interface IOCSPStore extends ISubsystem
* This method stores the configuration parameters specified by the
* passed-in Name Value pairs object.
* <P>
- *
+ *
* @param pairs a name-value pair object
* @exception EBaseException an illegal name-value pair
*/
- public void setConfigParameters(NameValuePairs pairs)
- throws EBaseException;
+ public void setConfigParameters(NameValuePairs pairs)
+ throws EBaseException;
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/password/EPasswordCheckException.java b/pki/base/common/src/com/netscape/certsrv/password/EPasswordCheckException.java
index a99fd764..3dc028ff 100644
--- a/pki/base/common/src/com/netscape/certsrv/password/EPasswordCheckException.java
+++ b/pki/base/common/src/com/netscape/certsrv/password/EPasswordCheckException.java
@@ -23,7 +23,7 @@ import com.netscape.certsrv.base.PasswordResources;
/**
* A class represents a password checker exception.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class EPasswordCheckException extends EBaseException {
@@ -40,6 +40,7 @@ public class EPasswordCheckException extends EBaseException {
/**
* Constructs a password checker exception
* <P>
+ *
* @param msgFormat exception details
*/
public EPasswordCheckException(String msgFormat) {
@@ -49,6 +50,7 @@ public class EPasswordCheckException extends EBaseException {
/**
* Constructs a password checker exception.
* <P>
+ *
* @param msgFormat exception details in message string format
* @param param message string parameter
*/
@@ -59,6 +61,7 @@ public class EPasswordCheckException extends EBaseException {
/**
* Constructs a password checker exception.
* <P>
+ *
* @param msgFormat exception details in message string format
* @param exception system exception
*/
@@ -69,6 +72,7 @@ public class EPasswordCheckException extends EBaseException {
/**
* Constructs a password checker exception.
* <P>
+ *
* @param msgFormat the message format.
* @param params list of message format parameters
*/
@@ -78,6 +82,7 @@ public class EPasswordCheckException extends EBaseException {
/**
* Retrieves bundle name.
+ *
* @return resource bundle name.
*/
protected String getBundleName() {
diff --git a/pki/base/common/src/com/netscape/certsrv/password/IConfigPasswordCheck.java b/pki/base/common/src/com/netscape/certsrv/password/IConfigPasswordCheck.java
index ddf4325c..3abe5f21 100644
--- a/pki/base/common/src/com/netscape/certsrv/password/IConfigPasswordCheck.java
+++ b/pki/base/common/src/com/netscape/certsrv/password/IConfigPasswordCheck.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.password;
-
/**
* Configuration Wizard Password quality checker interface.
* <P>
@@ -28,16 +27,18 @@ public interface IConfigPasswordCheck {
/**
* Check if the password meets the quality requirement
+ *
* @param pwd the given password
- * @return true if the password meets the quality requirement; otherwise false
+ * @return true if the password meets the quality requirement; otherwise
+ * false
*/
public boolean isGoodConfigPassword(String pwd);
/**
* Returns a reason if the password doesnt meet the quality requirement.
+ *
* @param pwd the given password
* @return a reason if the password quality requirement is not met.
*/
public String getConfigReason(String pwd);
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/password/IPasswordCheck.java b/pki/base/common/src/com/netscape/certsrv/password/IPasswordCheck.java
index bb84a72f..3c1530fb 100644
--- a/pki/base/common/src/com/netscape/certsrv/password/IPasswordCheck.java
+++ b/pki/base/common/src/com/netscape/certsrv/password/IPasswordCheck.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.password;
-
/**
* Password quality checker interface.
* <P>
@@ -28,16 +27,18 @@ public interface IPasswordCheck {
/**
* Check if the password meets the quality requirement
+ *
* @param pwd the given password
- * @return true if the password meets the quality requirement; otherwise false
+ * @return true if the password meets the quality requirement; otherwise
+ * false
*/
public boolean isGoodPassword(String pwd);
/**
* Returns a reason if the password doesnt meet the quality requirement.
+ *
* @param pwd the given password
* @return a reason if the password quality requirement is not met.
*/
public String getReason(String pwd);
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/pattern/AttrSetCollection.java b/pki/base/common/src/com/netscape/certsrv/pattern/AttrSetCollection.java
index 22cfc232..90b39eab 100644
--- a/pki/base/common/src/com/netscape/certsrv/pattern/AttrSetCollection.java
+++ b/pki/base/common/src/com/netscape/certsrv/pattern/AttrSetCollection.java
@@ -17,15 +17,13 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.pattern;
-
import java.util.Hashtable;
import com.netscape.certsrv.base.IAttrSet;
/**
- * This class represents a collection of attribute
- * sets.
- *
+ * This class represents a collection of attribute sets.
+ *
* @version $Revision$, $Date$
*/
public class AttrSetCollection extends Hashtable<String, IAttrSet> {
@@ -44,7 +42,7 @@ public class AttrSetCollection extends Hashtable<String, IAttrSet> {
/**
* Retrieves a attribute set from this collection.
- *
+ *
* @param name name of the attribute set
* @return attribute set
*/
@@ -54,7 +52,7 @@ public class AttrSetCollection extends Hashtable<String, IAttrSet> {
/**
* Sets attribute set in this collection.
- *
+ *
* @param name set of the attribute set
* @param set attribute set
*/
diff --git a/pki/base/common/src/com/netscape/certsrv/pattern/Pattern.java b/pki/base/common/src/com/netscape/certsrv/pattern/Pattern.java
index 36cc7cb3..f90f7c6d 100644
--- a/pki/base/common/src/com/netscape/certsrv/pattern/Pattern.java
+++ b/pki/base/common/src/com/netscape/certsrv/pattern/Pattern.java
@@ -17,34 +17,30 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.pattern;
-
import java.util.Enumeration;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IAttrSet;
-
/**
- * This is a generic pattern subtitution engine. The
- * pattern format should be:
+ * This is a generic pattern subtitution engine. The pattern format should be:
* <p>
- * $[attribute set key].[attribute name]$
+ * $[attribute set key].[attribute name]$
* <p>
* For example,
* <p>
- * $request.requestor_email$
- * $ctx.user_id$
+ * $request.requestor_email$ $ctx.user_id$
* <p>
- *
+ *
* @version $Revision$, $Date$
*/
public class Pattern {
private String mS = null;
-
+
/**
* Constructs a pattern object with the given string.
- *
+ *
* @param s string with pattern (i.e. $request.requestor_email$)
*/
public Pattern(String s) {
@@ -53,7 +49,7 @@ public class Pattern {
/**
* Subtitutes this pattern with the given attribute set.
- *
+ *
* @param key key name of the given attribute set
* @param attrSet attribute set
* @return substituted string
@@ -64,7 +60,7 @@ public class Pattern {
/**
* Subtitutes this pattern with the given attribute set.
- *
+ *
* @param attrSetCollection attribute set collection
* @return substituted string
*/
@@ -76,24 +72,22 @@ public class Pattern {
String key = (String) keys.nextElement();
Pattern p = new Pattern(temp);
- temp = p.substitute(key,
+ temp = p.substitute(key,
attrSetCollection.getAttrSet(key));
-
+
}
return temp;
}
/**
* Subtitutes this pattern with the given attribute set.
- *
- * This is an extended version of the substitute() method.
- * It takes a more flexible pattern format that could have
- * non-token ($...$) format. e.g.
- * $request.screenname$@redhat.com
- * where "@redhat.com" is not in token pattern format, and will be
- * literally put in place. e.g.
- * TomRiddle@redhat.com
- *
+ *
+ * This is an extended version of the substitute() method. It takes a more
+ * flexible pattern format that could have non-token ($...$) format. e.g.
+ * $request.screenname$@redhat.com where "@redhat.com" is not in token
+ * pattern format, and will be literally put in place. e.g.
+ * TomRiddle@redhat.com
+ *
* @param key key name of the given attribute set
* @param attrSet attribute set
* @return substituted string
@@ -105,39 +99,39 @@ public class Pattern {
int lastPos;
do {
- // from startPos to right before '$' or end of string
- // need to be copied over
-
+ // from startPos to right before '$' or end of string
+ // need to be copied over
+
lastPos = mS.indexOf('$', startPos);
- // if no '$', return the entire string
+ // if no '$', return the entire string
if (lastPos == -1 && startPos == 0)
- return mS;
+ return mS;
- // no more '$' found, copy the rest of chars, done
+ // no more '$' found, copy the rest of chars, done
if (lastPos == -1) {
- sb.append(mS.substring(startPos)); //
- return sb.toString(); //
- // continue;
- }
+ sb.append(mS.substring(startPos)); //
+ return sb.toString(); //
+ // continue;
+ }
- // found '$'
+ // found '$'
if (startPos < lastPos) {
- sb.append(mS.substring(startPos, lastPos));
+ sb.append(mS.substring(startPos, lastPos));
}
- // look for the ending '$'
+ // look for the ending '$'
int endPos = mS.indexOf('$', lastPos + 1);
String token = mS.substring(lastPos + 1, endPos);
int dotPos = token.indexOf('.');
- // it's assuming there's always a '.'
+ // it's assuming there's always a '.'
String attrKey = token.substring(0, dotPos);
String attrName = token.substring(dotPos + 1);
if (!key.equals(attrKey)) {
startPos = endPos + 1;
- sb.append("$" + attrKey + "." + attrName + "$");
+ sb.append("$" + attrKey + "." + attrName + "$");
continue;
}
@@ -145,20 +139,19 @@ public class Pattern {
Object o = attrSet.get(attrName);
if (!(o instanceof String)) {
- startPos = endPos + 1;
- // if no such attrName, copy the token pattern over
- sb.append("$" + attrKey + "." + attrName + "$");
+ startPos = endPos + 1;
+ // if no such attrName, copy the token pattern over
+ sb.append("$" + attrKey + "." + attrName + "$");
continue;
}
String val = (String) o;
- sb.append(val);
+ sb.append(val);
} catch (EBaseException e) {
- sb.append("$" + attrKey + "." + attrName + "$");
+ sb.append("$" + attrKey + "." + attrName + "$");
}
- startPos = endPos + 1;
- }
- while (lastPos != -1);
+ startPos = endPos + 1;
+ } while (lastPos != -1);
return sb.toString();
}
diff --git a/pki/base/common/src/com/netscape/certsrv/policy/EPolicyException.java b/pki/base/common/src/com/netscape/certsrv/policy/EPolicyException.java
index c8431fcf..30c78939 100644
--- a/pki/base/common/src/com/netscape/certsrv/policy/EPolicyException.java
+++ b/pki/base/common/src/com/netscape/certsrv/policy/EPolicyException.java
@@ -17,25 +17,23 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.policy;
-
import java.util.Locale;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.MessageFormatter;
-
/**
- * This class represents Exceptions used by the policy package.
- * The policies themselves do not raise exceptions but use them
- * to format error messages.
- *
+ * This class represents Exceptions used by the policy package. The policies
+ * themselves do not raise exceptions but use them to format error messages.
+ *
* Adapted from EBasException
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
* @see java.text.MessageFormat
@@ -54,7 +52,7 @@ public class EPolicyException extends EBaseException {
/**
* Constructs a base exception.
* <P>
- *
+ *
* @param msgFormat exception details
*/
public EPolicyException(String msgFormat) {
@@ -64,11 +62,12 @@ public class EPolicyException extends EBaseException {
/**
* Constructs a base exception with a parameter. For example,
+ *
* <PRE>
- * new EPolicyException("failed to load {0}", fileName);
+ * new EPolicyException(&quot;failed to load {0}&quot;, fileName);
* </PRE>
* <P>
- *
+ *
* @param msgFormat exception details in message string format
* @param param message string parameter
*/
@@ -81,7 +80,7 @@ public class EPolicyException extends EBaseException {
/**
* Constructs a base exception with two String parameters. For example,
* <P>
- *
+ *
* @param msgFormat exception details in message string format
* @param param1 message string parameter
* @param param2 message string parameter
@@ -94,9 +93,9 @@ public class EPolicyException extends EBaseException {
}
/**
- * Constructs a base exception. It can be used to carry
- * a system exception that may contain information about
- * the context. For example,
+ * Constructs a base exception. It can be used to carry a system exception
+ * that may contain information about the context. For example,
+ *
* <PRE>
* try {
* ...
@@ -105,7 +104,7 @@ public class EPolicyException extends EBaseException {
* }
* </PRE>
* <P>
- *
+ *
* @param msgFormat exception details in message string format
* @param param system exception
*/
@@ -116,10 +115,10 @@ public class EPolicyException extends EBaseException {
}
/**
- * Constructs a base exception with a list of parameters
- * that will be substituted into the message format.
+ * Constructs a base exception with a list of parameters that will be
+ * substituted into the message format.
* <P>
- *
+ *
* @param msgFormat exception details in message string format
* @param params list of message format parameters
*/
@@ -131,7 +130,7 @@ public class EPolicyException extends EBaseException {
/**
* Returns a list of parameters.
* <P>
- *
+ *
* @return list of message format parameters
*/
public Object[] getParameters() {
@@ -139,10 +138,10 @@ public class EPolicyException extends EBaseException {
}
/**
- * Returns localized exception string. This method should
- * only be called if a localized string is necessary.
+ * Returns localized exception string. This method should only be called if
+ * a localized string is necessary.
* <P>
- *
+ *
* @return details message
*/
public String toString() {
@@ -152,7 +151,7 @@ public class EPolicyException extends EBaseException {
/**
* Returns the string based on the given locale.
* <P>
- *
+ *
* @param locale locale
* @return details message
*/
diff --git a/pki/base/common/src/com/netscape/certsrv/policy/IEnrollmentPolicy.java b/pki/base/common/src/com/netscape/certsrv/policy/IEnrollmentPolicy.java
index bfd0e7c2..04de3434 100644
--- a/pki/base/common/src/com/netscape/certsrv/policy/IEnrollmentPolicy.java
+++ b/pki/base/common/src/com/netscape/certsrv/policy/IEnrollmentPolicy.java
@@ -17,20 +17,18 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.policy;
-
/**
- * Interface for an enrollment policy rule. This provides general
- * typing for rules so that a policy processor can group rules
- * based on a particular type.
+ * Interface for an enrollment policy rule. This provides general typing for
+ * rules so that a policy processor can group rules based on a particular type.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public interface IEnrollmentPolicy extends IPolicyRule {
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/policy/IExpression.java b/pki/base/common/src/com/netscape/certsrv/policy/IExpression.java
index 6bed58c5..4075e868 100644
--- a/pki/base/common/src/com/netscape/certsrv/policy/IExpression.java
+++ b/pki/base/common/src/com/netscape/certsrv/policy/IExpression.java
@@ -17,18 +17,17 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.policy;
-
import com.netscape.certsrv.request.IRequest;
-
/**
* Interface for a policy expression.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
@@ -48,12 +47,12 @@ public interface IExpression {
/**
* Evaluate the Expression.
- *
- * @param req The PKIRequest on which we are applying the condition.
- * @return The return value.
+ *
+ * @param req The PKIRequest on which we are applying the condition.
+ * @return The return value.
*/
boolean evaluate(IRequest req)
- throws EPolicyException;
+ throws EPolicyException;
/**
* Convert to a string.
diff --git a/pki/base/common/src/com/netscape/certsrv/policy/IGeneralNameAsConstraintsConfig.java b/pki/base/common/src/com/netscape/certsrv/policy/IGeneralNameAsConstraintsConfig.java
index 757780d3..7746bfd9 100644
--- a/pki/base/common/src/com/netscape/certsrv/policy/IGeneralNameAsConstraintsConfig.java
+++ b/pki/base/common/src/com/netscape/certsrv/policy/IGeneralNameAsConstraintsConfig.java
@@ -17,21 +17,20 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.policy;
-
import java.util.Vector;
import netscape.security.x509.GeneralName;
-
-/**
- * Class that can be used to form general names from configuration file.
- * Used by policies and extension commands.
+/**
+ * Class that can be used to form general names from configuration file. Used by
+ * policies and extension commands.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
@@ -39,14 +38,14 @@ public interface IGeneralNameAsConstraintsConfig {
/**
* Retrieves instance parameters.
- *
+ *
* @param params parameters
*/
public void getInstanceParams(Vector<String> params);
/**
* Retrieves the general name.
- *
+ *
* @return general name
*/
public GeneralName getGeneralName();
diff --git a/pki/base/common/src/com/netscape/certsrv/policy/IGeneralNameConfig.java b/pki/base/common/src/com/netscape/certsrv/policy/IGeneralNameConfig.java
index 953bb41e..bc61e922 100644
--- a/pki/base/common/src/com/netscape/certsrv/policy/IGeneralNameConfig.java
+++ b/pki/base/common/src/com/netscape/certsrv/policy/IGeneralNameConfig.java
@@ -17,23 +17,22 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.policy;
-
import java.util.Vector;
import netscape.security.x509.GeneralName;
import com.netscape.certsrv.base.EBaseException;
-
-/**
- * Class that can be used to form general names from configuration file.
- * Used by policies and extension commands.
+/**
+ * Class that can be used to form general names from configuration file. Used by
+ * policies and extension commands.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
@@ -41,27 +40,27 @@ public interface IGeneralNameConfig {
/**
* Forms a general name from string.
- *
+ *
* @param value general name in string
* @return general name object
* @exception EBaseException failed to form general name
*/
- public GeneralName formGeneralName(String value)
- throws EBaseException;
+ public GeneralName formGeneralName(String value)
+ throws EBaseException;
/**
* Forms general names from the given value.
- *
+ *
* @param value general name in string
* @return a vector of general names
* @exception EBaseException failed to form general name
*/
public Vector<GeneralName> formGeneralNames(Object value)
- throws EBaseException;
+ throws EBaseException;
/**
* Retrieves the instance parameters.
- *
+ *
* @param params parameters
*/
public void getInstanceParams(Vector<String> params);
diff --git a/pki/base/common/src/com/netscape/certsrv/policy/IGeneralNameUtil.java b/pki/base/common/src/com/netscape/certsrv/policy/IGeneralNameUtil.java
index c1526284..e4218832 100644
--- a/pki/base/common/src/com/netscape/certsrv/policy/IGeneralNameUtil.java
+++ b/pki/base/common/src/com/netscape/certsrv/policy/IGeneralNameUtil.java
@@ -17,16 +17,16 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.policy;
-
-/**
- * Class that can be used to form general names from configuration file.
- * Used by policies and extension commands.
+/**
+ * Class that can be used to form general names from configuration file. Used by
+ * policies and extension commands.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
@@ -51,30 +51,26 @@ public interface IGeneralNameUtil {
*/
public static final int DEF_NUM_GENERALNAMES = 8;
- /**
+ /**
* Default extended plugin info.
*/
- public static String
- NUM_GENERALNAMES_INFO = "number;The total number of alternative names or identities permitted in the extension.";
- public static String GENNAME_CHOICE_INFO =
- "choice(" +
- IGeneralNameUtil.GENNAME_CHOICE_RFC822NAME + "," +
- IGeneralNameUtil.GENNAME_CHOICE_DIRECTORYNAME + "," +
- IGeneralNameUtil.GENNAME_CHOICE_DNSNAME + "," +
- IGeneralNameUtil.GENNAME_CHOICE_EDIPARTYNAME + "," +
- IGeneralNameUtil.GENNAME_CHOICE_URL + "," +
- IGeneralNameUtil.GENNAME_CHOICE_IPADDRESS + "," +
- IGeneralNameUtil.GENNAME_CHOICE_REGISTEREDID + "," +
- IGeneralNameUtil.GENNAME_CHOICE_OTHERNAME + ");" +
- "GeneralName choice. See RFC 2459 appendix B2 on GeneralName.";
- public static String GENNAME_VALUE_INFO =
- "string;Value according to the GeneralName choice.";
+ public static String NUM_GENERALNAMES_INFO = "number;The total number of alternative names or identities permitted in the extension.";
+ public static String GENNAME_CHOICE_INFO =
+ "choice(" +
+ IGeneralNameUtil.GENNAME_CHOICE_RFC822NAME + "," +
+ IGeneralNameUtil.GENNAME_CHOICE_DIRECTORYNAME + "," +
+ IGeneralNameUtil.GENNAME_CHOICE_DNSNAME + "," +
+ IGeneralNameUtil.GENNAME_CHOICE_EDIPARTYNAME + "," +
+ IGeneralNameUtil.GENNAME_CHOICE_URL + "," +
+ IGeneralNameUtil.GENNAME_CHOICE_IPADDRESS + "," +
+ IGeneralNameUtil.GENNAME_CHOICE_REGISTEREDID + "," +
+ IGeneralNameUtil.GENNAME_CHOICE_OTHERNAME + ");" +
+ "GeneralName choice. See RFC 2459 appendix B2 on GeneralName.";
+ public static String GENNAME_VALUE_INFO =
+ "string;Value according to the GeneralName choice.";
- public static String
- PROP_NUM_GENERALNAMES_INFO = PROP_NUM_GENERALNAMES + ";" + NUM_GENERALNAMES_INFO;
- public static String
- PROP_GENNAME_CHOICE_INFO = PROP_GENNAME_CHOICE + ";" + GENNAME_CHOICE_INFO;
- public static String
- PROP_GENNAME_VALUE_INFO = PROP_GENNAME_VALUE + ";" + GENNAME_VALUE_INFO;
+ public static String PROP_NUM_GENERALNAMES_INFO = PROP_NUM_GENERALNAMES + ";" + NUM_GENERALNAMES_INFO;
+ public static String PROP_GENNAME_CHOICE_INFO = PROP_GENNAME_CHOICE + ";" + GENNAME_CHOICE_INFO;
+ public static String PROP_GENNAME_VALUE_INFO = PROP_GENNAME_VALUE + ";" + GENNAME_VALUE_INFO;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/policy/IGeneralNamesAsConstraintsConfig.java b/pki/base/common/src/com/netscape/certsrv/policy/IGeneralNamesAsConstraintsConfig.java
index c461efd3..86447642 100644
--- a/pki/base/common/src/com/netscape/certsrv/policy/IGeneralNamesAsConstraintsConfig.java
+++ b/pki/base/common/src/com/netscape/certsrv/policy/IGeneralNamesAsConstraintsConfig.java
@@ -17,21 +17,20 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.policy;
-
import java.util.Vector;
import netscape.security.x509.GeneralNames;
-
-/**
- * Class that can be used to form general names from configuration file.
- * Used by policies and extension commands.
+/**
+ * Class that can be used to form general names from configuration file. Used by
+ * policies and extension commands.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
@@ -39,14 +38,14 @@ public interface IGeneralNamesAsConstraintsConfig {
/**
* Retrieves a list of configured general names.
- *
+ *
* @return a list of general names
*/
public GeneralNames getGeneralNames();
/**
* Retrieves instance parameters.
- *
+ *
* @param params instance parameters
*/
public void getInstanceParams(Vector<String> params);
diff --git a/pki/base/common/src/com/netscape/certsrv/policy/IGeneralNamesConfig.java b/pki/base/common/src/com/netscape/certsrv/policy/IGeneralNamesConfig.java
index 4c2330df..9b564ee7 100644
--- a/pki/base/common/src/com/netscape/certsrv/policy/IGeneralNamesConfig.java
+++ b/pki/base/common/src/com/netscape/certsrv/policy/IGeneralNamesConfig.java
@@ -17,21 +17,20 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.policy;
-
import java.util.Vector;
import netscape.security.x509.GeneralNames;
-
-/**
- * Class that can be used to form general names from configuration file.
- * Used by policies and extension commands.
+/**
+ * Class that can be used to form general names from configuration file. Used by
+ * policies and extension commands.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
@@ -39,14 +38,14 @@ public interface IGeneralNamesConfig {
/**
* Retrieves a list of configured general names.
- *
+ *
* @return general names
*/
public GeneralNames getGeneralNames();
/**
* Retrieves the instance parameters.
- *
+ *
* @param params instance parameters
*/
public void getInstanceParams(Vector<String> params);
diff --git a/pki/base/common/src/com/netscape/certsrv/policy/IKeyArchivalPolicy.java b/pki/base/common/src/com/netscape/certsrv/policy/IKeyArchivalPolicy.java
index 13ba5f61..14a29256 100644
--- a/pki/base/common/src/com/netscape/certsrv/policy/IKeyArchivalPolicy.java
+++ b/pki/base/common/src/com/netscape/certsrv/policy/IKeyArchivalPolicy.java
@@ -17,18 +17,17 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.policy;
-
/**
* Interface for a key recovery policy rule.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public interface IKeyArchivalPolicy extends IPolicyRule {
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/policy/IKeyRecoveryPolicy.java b/pki/base/common/src/com/netscape/certsrv/policy/IKeyRecoveryPolicy.java
index 1d173f28..6de61567 100644
--- a/pki/base/common/src/com/netscape/certsrv/policy/IKeyRecoveryPolicy.java
+++ b/pki/base/common/src/com/netscape/certsrv/policy/IKeyRecoveryPolicy.java
@@ -17,18 +17,17 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.policy;
-
/**
* Interface for a key recovery policy rule.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public interface IKeyRecoveryPolicy extends IPolicyRule {
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/policy/IPolicyPredicateParser.java b/pki/base/common/src/com/netscape/certsrv/policy/IPolicyPredicateParser.java
index 7b5f4465..0992beae 100644
--- a/pki/base/common/src/com/netscape/certsrv/policy/IPolicyPredicateParser.java
+++ b/pki/base/common/src/com/netscape/certsrv/policy/IPolicyPredicateParser.java
@@ -17,15 +17,15 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.policy;
-
/**
* Interface for policy predicate parsers.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
@@ -33,11 +33,11 @@ public interface IPolicyPredicateParser {
/**
* Parse the predicate expression and return a vector of expressions.
- *
- * @param predicateExpression The predicate expression as read from the
- * config file.
- * @return expVector The vector of expressions.
+ *
+ * @param predicateExpression The predicate expression as read from the
+ * config file.
+ * @return expVector The vector of expressions.
*/
IExpression parse(String predicateExpression)
- throws EPolicyException;
+ throws EPolicyException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/policy/IPolicyProcessor.java b/pki/base/common/src/com/netscape/certsrv/policy/IPolicyProcessor.java
index 09f2415a..d6cd7184 100644
--- a/pki/base/common/src/com/netscape/certsrv/policy/IPolicyProcessor.java
+++ b/pki/base/common/src/com/netscape/certsrv/policy/IPolicyProcessor.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.policy;
-
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
@@ -25,22 +24,22 @@ import java.util.Vector;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.ISubsystem;
-
/**
- * A generic interface for a policy processor. By making a processor
- * extend the policy interface, we make even the processor a rule -
- * which makes sense because a processor may be based on some rule
- * such as evaluate all policies before returning the final result or
- * return as soon as one of the policies return a failure and so on.
- *
- * By making both processor and policy rules implement a common
- * interface, one can write rules that are processors as well.
+ * A generic interface for a policy processor. By making a processor extend the
+ * policy interface, we make even the processor a rule - which makes sense
+ * because a processor may be based on some rule such as evaluate all policies
+ * before returning the final result or return as soon as one of the policies
+ * return a failure and so on.
+ *
+ * By making both processor and policy rules implement a common interface, one
+ * can write rules that are processors as well.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
@@ -61,42 +60,40 @@ public interface IPolicyProcessor extends ISubsystem,
/**
* Returns the policy substore id.
- *
- * @return storeID The policy store id used by this processor.
+ *
+ * @return storeID The policy store id used by this processor.
*/
String getPolicySubstoreId();
/**
* Returns information on Policy impls.
- *
- * @return An enumeration of strings describing the information
- * about policy implementations. Currently only the
- * the implementation id is expected.
+ *
+ * @return An enumeration of strings describing the information about policy
+ * implementations. Currently only the the implementation id is
+ * expected.
*/
Enumeration<String> getPolicyImplsInfo();
/**
* Returns the rule implementations registered with this processor.
- *
- * @return An Enumeration of uninitialized IPolicyRule
- * objects.
+ *
+ * @return An Enumeration of uninitialized IPolicyRule objects.
*/
Enumeration<IPolicyRule> getPolicyImpls();
/**
* Returns an implementation identified by a given id.
- *
- * @param id The implementation id.
+ *
+ * @param id The implementation id.
* @return The uninitialized instance of the policy rule.
*/
IPolicyRule getPolicyImpl(String id);
/**
- * Returns configuration for an implmentation.
- *
- * @param id The implementation id.
- * @return A vector of name/value pairs in the form of
- * name=value.
+ * Returns configuration for an implmentation.
+ *
+ * @param id The implementation id.
+ * @return A vector of name/value pairs in the form of name=value.
*/
Vector<String> getPolicyImplConfig(String id);
@@ -104,53 +101,50 @@ public interface IPolicyProcessor extends ISubsystem,
* Deletes a policy implementation identified by an impl id.
*
*
- * @param id The impl id of the policy to be deleted.
- * There shouldn't be any active instance for this
- * implementation.
+ * @param id The impl id of the policy to be deleted. There shouldn't be any
+ * active instance for this implementation.
* @exception EBaseException is thrown if an error occurs in deletion.
*/
void deletePolicyImpl(String id)
- throws EBaseException;
+ throws EBaseException;
/**
* Adds a policy implementation identified by an impl id.
*
- * @param id The impl id of the policy to be added.
- * The id should be unique.
- * @param classPath The fully qualified path for the implementation.
+ * @param id The impl id of the policy to be added. The id should be unique.
+ * @param classPath The fully qualified path for the implementation.
* @exception EBaseException is thrown if an error occurs in addition.
*/
void addPolicyImpl(String id, String classPath)
- throws EBaseException;
+ throws EBaseException;
/**
* Returns information on Policy instances.
- *
- * @return An Enumeration of Strings describing the information
- * about policy rule instances.
+ *
+ * @return An Enumeration of Strings describing the information about policy
+ * rule instances.
*/
Enumeration<String> getPolicyInstancesInfo();
/**
* Returns policy instances registered with this processor.
- *
+ *
* @return An Enumeration of policy instances.
*/
- Enumeration<IPolicyRule> getPolicyInstances();
+ Enumeration<IPolicyRule> getPolicyInstances();
/**
* Returns instance configuration for a given instance id.
- *
- * @param id The rule id.
- * @return A vector of name/value pairs in the form of
- * name=value.
+ *
+ * @param id The rule id.
+ * @return A vector of name/value pairs in the form of name=value.
*/
- Vector<String> getPolicyInstanceConfig(String id);
+ Vector<String> getPolicyInstanceConfig(String id);
/**
* Returns instance configuration for a given instance id.
- *
- * @param id The rule id.
+ *
+ * @param id The rule id.
* @return the policy instance identified by the id.
*/
IPolicyRule getPolicyInstance(String id);
@@ -158,41 +152,39 @@ public interface IPolicyProcessor extends ISubsystem,
/**
* Deletes a policy instance identified by an instance id.
*
- * @param id The instance id of the policy to be deleted.
+ * @param id The instance id of the policy to be deleted.
* @exception EBaseException is thrown if an error occurs in deletion.
*/
void deletePolicyInstance(String id)
- throws EBaseException;
+ throws EBaseException;
/**
- * Adds a policy instance
+ * Adds a policy instance
*
- * @param id The impl id of the policy to be added.
- * The id should be unique.
+ * @param id The impl id of the policy to be added. The id should be unique.
* @param ht a Hashtable of config params.
* @exception EBaseException is thrown if an error occurs in addition.
*/
void addPolicyInstance(String id, Hashtable<String, String> ht)
- throws EBaseException;
+ throws EBaseException;
/**
- * Modifies a policy instance
+ * Modifies a policy instance
*
- * @param id The impl id of the policy to be modified.
- * The policy instance with this id should be present.
+ * @param id The impl id of the policy to be modified. The policy instance
+ * with this id should be present.
* @param ht a Hashtable of config params.
* @exception EBaseException is thrown if an error occurs in addition.
*/
void modifyPolicyInstance(String id, Hashtable<String, String> ht)
- throws EBaseException;
+ throws EBaseException;
/**
* Modifies policy ordering.
- *
+ *
* @param policyOrderStr The comma separated list of instance ids.
- *
+ *
*/
void changePolicyInstanceOrdering(String policyOrderStr)
- throws EBaseException;
+ throws EBaseException;
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/policy/IPolicyRule.java b/pki/base/common/src/com/netscape/certsrv/policy/IPolicyRule.java
index 0babd48a..65b6f661 100644
--- a/pki/base/common/src/com/netscape/certsrv/policy/IPolicyRule.java
+++ b/pki/base/common/src/com/netscape/certsrv/policy/IPolicyRule.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.policy;
-
import java.util.Vector;
import com.netscape.certsrv.base.EBaseException;
@@ -26,20 +25,20 @@ import com.netscape.certsrv.base.ISubsystem;
import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
-
/**
* Interface for a policy rule.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public interface IPolicyRule
- extends com.netscape.certsrv.request.IPolicy {
+ extends com.netscape.certsrv.request.IPolicy {
public static final String PROP_ENABLE = "enable";
public static final String PROP_PREDICATE = "predicate";
public static final String PROP_IMPLNAME = "implName";
@@ -47,15 +46,16 @@ public interface IPolicyRule
/**
* Initializes the policy rule.
* <P>
- *
+ *
* @param config The config store reference
*/
void init(ISubsystem owner, IConfigStore config)
- throws EBaseException;
+ throws EBaseException;
/**
* Gets the description for this policy rule.
* <P>
+ *
* @return The Description for this rule.
*/
String getDescription();
@@ -63,7 +63,7 @@ public interface IPolicyRule
/**
* Returns the name of the policy rule class.
* <P>
- *
+ *
* @return The name of the policy class.
*/
String getName();
@@ -71,54 +71,54 @@ public interface IPolicyRule
/**
* Returns the name of the policy rule instance.
* <P>
- *
- * @return The name of the policy rule instance. If none
- * is set the name of the implementation will be returned.
- *
+ *
+ * @return The name of the policy rule instance. If none is set the name of
+ * the implementation will be returned.
+ *
*/
String getInstanceName();
/**
* Sets a predicate expression for rule matching.
* <P>
- *
- * @param exp The predicate expression for the rule.
+ *
+ * @param exp The predicate expression for the rule.
*/
void setPredicate(IExpression exp);
/**
* Returns the predicate expression for the rule.
* <P>
- *
+ *
* @return The predicate expression for the rule.
*/
IExpression getPredicate();
/**
- * Applies the policy on the given Request. This may modify
- * the request appropriately.
+ * Applies the policy on the given Request. This may modify the request
+ * appropriately.
* <P>
- *
- * @param req The request on which to apply policy.
+ *
+ * @param req The request on which to apply policy.
* @return The PolicyResult object.
*/
PolicyResult apply(IRequest req);
/**
* Return configured parameters for a policy rule instance.
- *
- * @return nvPairs A Vector of name/value pairs. Each name/value
- * pair is constructed as a String in name=value format.
+ *
+ * @return nvPairs A Vector of name/value pairs. Each name/value pair is
+ * constructed as a String in name=value format.
*/
public Vector<String> getInstanceParams();
/**
* Return default parameters for a policy implementation.
- *
- * @return nvPairs A Vector of name/value pairs. Each name/value
- * pair is constructed as a String in name=value.
+ *
+ * @return nvPairs A Vector of name/value pairs. Each name/value pair is
+ * constructed as a String in name=value.
*/
- public Vector<String> getDefaultParams();
+ public Vector<String> getDefaultParams();
public void setError(IRequest req, String format, Object[] params);
@@ -126,4 +126,3 @@ public interface IPolicyRule
public void setPolicyException(IRequest req, EBaseException ex);
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/policy/IPolicySet.java b/pki/base/common/src/com/netscape/certsrv/policy/IPolicySet.java
index dd5a36bc..d60baa25 100644
--- a/pki/base/common/src/com/netscape/certsrv/policy/IPolicySet.java
+++ b/pki/base/common/src/com/netscape/certsrv/policy/IPolicySet.java
@@ -17,28 +17,27 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.policy;
-
import java.util.Enumeration;
import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
-
/**
- * Represents a set of policy rules. Policy rules are ordered from
- * lowest priority to highest priority. The priority assignment for rules
- * is not enforced by this interface. Various implementation may
- * use different mechanisms such as a linear ordering of rules
- * in a configuration file or explicit assignment of priority levels ..etc.
- * The policy system initialization needs to deal with reading the rules, sorting
- * them in increasing order of priority and presenting an ordered vector of rules
- * via the IPolicySet interface.
+ * Represents a set of policy rules. Policy rules are ordered from lowest
+ * priority to highest priority. The priority assignment for rules is not
+ * enforced by this interface. Various implementation may use different
+ * mechanisms such as a linear ordering of rules in a configuration file or
+ * explicit assignment of priority levels ..etc. The policy system
+ * initialization needs to deal with reading the rules, sorting them in
+ * increasing order of priority and presenting an ordered vector of rules via
+ * the IPolicySet interface.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
@@ -47,7 +46,7 @@ public interface IPolicySet {
/**
* Returns the name of the rule set.
* <P>
- *
+ *
* @return The name of the rule set.
*/
String getName();
@@ -55,6 +54,7 @@ public interface IPolicySet {
/**
* Returns the no of rules in a set.
* <P>
+ *
* @return the no of rules.
*/
int count();
@@ -62,24 +62,24 @@ public interface IPolicySet {
/**
* Add a policy rule.
* <P>
- *
+ *
* @param ruleName The name of the rule to be added.
- * @param rule The rule to be added.
+ * @param rule The rule to be added.
*/
void addRule(String ruleName, IPolicyRule rule);
/**
* Removes a policy rule identified by the given name.
- *
- * @param ruleName The name of the rule to be removed.
+ *
+ * @param ruleName The name of the rule to be removed.
*/
void removeRule(String ruleName);
/**
* Returns the rule identified by a given name.
* <P>
- *
- * @param ruleName The name of the rule to be return.
+ *
+ * @param ruleName The name of the rule to be return.
* @return The rule identified by the given name or null if none exists.
*/
IPolicyRule getRule(String ruleName);
@@ -87,20 +87,19 @@ public interface IPolicySet {
/**
* Returns an enumeration of rules.
* <P>
- *
+ *
* @return An enumeration of rules.
*/
Enumeration<IPolicyRule> getRules();
/**
- * Apply policy rules on a request. This call may modify
- * the request content.
- *
- * @param req The request to apply policies on.
- *
- * <P>
+ * Apply policy rules on a request. This call may modify the request
+ * content.
+ *
+ * @param req The request to apply policies on.
+ *
+ * <P>
* @return The policy result.
*/
PolicyResult apply(IRequest req);
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/policy/IRenewalPolicy.java b/pki/base/common/src/com/netscape/certsrv/policy/IRenewalPolicy.java
index 7bf2026e..28f56fe7 100644
--- a/pki/base/common/src/com/netscape/certsrv/policy/IRenewalPolicy.java
+++ b/pki/base/common/src/com/netscape/certsrv/policy/IRenewalPolicy.java
@@ -17,18 +17,17 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.policy;
-
/**
* Interface for a renewal policy rule.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public interface IRenewalPolicy extends IPolicyRule {
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/policy/IRevocationPolicy.java b/pki/base/common/src/com/netscape/certsrv/policy/IRevocationPolicy.java
index e0ecfb16..7e6084c7 100644
--- a/pki/base/common/src/com/netscape/certsrv/policy/IRevocationPolicy.java
+++ b/pki/base/common/src/com/netscape/certsrv/policy/IRevocationPolicy.java
@@ -17,18 +17,17 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.policy;
-
/**
* Interface for a revocation policy rule.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public interface IRevocationPolicy extends IPolicyRule {
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/policy/ISubjAltNameConfig.java b/pki/base/common/src/com/netscape/certsrv/policy/ISubjAltNameConfig.java
index 75df22de..388bd405 100644
--- a/pki/base/common/src/com/netscape/certsrv/policy/ISubjAltNameConfig.java
+++ b/pki/base/common/src/com/netscape/certsrv/policy/ISubjAltNameConfig.java
@@ -17,18 +17,16 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.policy;
-
-
-
-/**
- * Class that can be used to form general names from configuration file.
- * Used by policies and extension commands.
+/**
+ * Class that can be used to form general names from configuration file. Used by
+ * policies and extension commands.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
@@ -36,14 +34,14 @@ public interface ISubjAltNameConfig extends IGeneralNameConfig {
/**
* Retrieves configuration prefix.
- *
+ *
* @return prefix
*/
public String getPfx();
/**
* Retrieves configuration attribute.
- *
+ *
* @return attribute
*/
public String getAttr();
diff --git a/pki/base/common/src/com/netscape/certsrv/policy/PolicyResources.java b/pki/base/common/src/com/netscape/certsrv/policy/PolicyResources.java
index c8bcec2c..d330b719 100644
--- a/pki/base/common/src/com/netscape/certsrv/policy/PolicyResources.java
+++ b/pki/base/common/src/com/netscape/certsrv/policy/PolicyResources.java
@@ -17,18 +17,17 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.policy;
-
import java.util.ListResourceBundle;
-
/**
* Error messages for Policies.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
* @see java.util.ListResourceBundle
diff --git a/pki/base/common/src/com/netscape/certsrv/profile/CertInfoProfile.java b/pki/base/common/src/com/netscape/certsrv/profile/CertInfoProfile.java
index 75f134c2..5c192e9c 100644
--- a/pki/base/common/src/com/netscape/certsrv/profile/CertInfoProfile.java
+++ b/pki/base/common/src/com/netscape/certsrv/profile/CertInfoProfile.java
@@ -26,8 +26,7 @@ import netscape.security.x509.X509CertInfo;
import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.base.IConfigStore;
-public class CertInfoProfile
-{
+public class CertInfoProfile {
private Vector<ICertInfoPolicyDefault> mDefaults = new Vector<ICertInfoPolicyDefault>();
private String mName = null;
private String mID = null;
@@ -35,8 +34,7 @@ public class CertInfoProfile
private String mProfileIDMapping = null;
private String mProfileSetIDMapping = null;
- public CertInfoProfile(String cfg) throws Exception
- {
+ public CertInfoProfile(String cfg) throws Exception {
IConfigStore config = CMS.createFileConfigStore(cfg);
mID = config.getString("id");
mName = config.getString("name");
@@ -45,67 +43,60 @@ public class CertInfoProfile
mProfileSetIDMapping = config.getString("profileSetIDMapping");
StringTokenizer st = new StringTokenizer(config.getString("list"), ",");
while (st.hasMoreTokens()) {
- String id = (String)st.nextToken();
+ String id = (String) st.nextToken();
String c = config.getString(id + ".default.class");
try {
- /* load defaults */
- ICertInfoPolicyDefault def = (ICertInfoPolicyDefault)
- Class.forName(c).newInstance();
- init(config.getSubStore(id + ".default"), def);
- mDefaults.addElement(def);
+ /* load defaults */
+ ICertInfoPolicyDefault def = (ICertInfoPolicyDefault)
+ Class.forName(c).newInstance();
+ init(config.getSubStore(id + ".default"), def);
+ mDefaults.addElement(def);
} catch (Exception e) {
- CMS.debug("CertInfoProfile: " + e.toString());
+ CMS.debug("CertInfoProfile: " + e.toString());
}
}
}
private void init(IConfigStore config, ICertInfoPolicyDefault def)
- throws Exception
- {
- try {
- def.init(null, config);
- } catch (Exception e) {
- CMS.debug("CertInfoProfile.init: " + e.toString());
- }
+ throws Exception {
+ try {
+ def.init(null, config);
+ } catch (Exception e) {
+ CMS.debug("CertInfoProfile.init: " + e.toString());
+ }
}
- public String getID()
- {
+ public String getID() {
return mID;
}
- public String getName()
- {
+ public String getName() {
return mName;
}
- public String getDescription()
- {
+ public String getDescription() {
return mDescription;
}
- public String getProfileIDMapping()
- {
+ public String getProfileIDMapping() {
return mProfileIDMapping;
}
- public String getProfileSetIDMapping()
- {
+ public String getProfileSetIDMapping() {
return mProfileSetIDMapping;
}
- public void populate(X509CertInfo info)
- {
+ public void populate(X509CertInfo info) {
Enumeration<ICertInfoPolicyDefault> e1 = mDefaults.elements();
while (e1.hasMoreElements()) {
- ICertInfoPolicyDefault def =
- (ICertInfoPolicyDefault)e1.nextElement();
- try {
- def.populate(null /* request */, info);
- } catch (Exception e) {
- CMS.debug(e);
- CMS.debug("CertInfoProfile.populate: " + e.toString());
- }
+ ICertInfoPolicyDefault def =
+ (ICertInfoPolicyDefault) e1.nextElement();
+ try {
+ def.populate(null /* request */, info);
+ } catch (Exception e) {
+ CMS.debug(e);
+ CMS.debug("CertInfoProfile.populate: " + e.toString());
+ }
}
}
}
diff --git a/pki/base/common/src/com/netscape/certsrv/profile/EDeferException.java b/pki/base/common/src/com/netscape/certsrv/profile/EDeferException.java
index f4af86b2..2717fabf 100644
--- a/pki/base/common/src/com/netscape/certsrv/profile/EDeferException.java
+++ b/pki/base/common/src/com/netscape/certsrv/profile/EDeferException.java
@@ -17,17 +17,14 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.profile;
-
/**
- * This represents a profile specific exception. The
- * framework raises this exception when a request is
- * deferred.
+ * This represents a profile specific exception. The framework raises this
+ * exception when a request is deferred.
* <p>
- * A deferred request will not be processed
- * immediately. Manual approval is required for
- * processing the request again.
+ * A deferred request will not be processed immediately. Manual approval is
+ * required for processing the request again.
* <p>
- *
+ *
* @version $Revision$, $Date$
*/
public class EDeferException extends EProfileException {
@@ -39,11 +36,9 @@ public class EDeferException extends EProfileException {
/**
* Creates a defer exception.
- *
- * @param msg localized message that will be
- * displayed to end user. This message
- * should indicate the reason why a request
- * is deferred.
+ *
+ * @param msg localized message that will be displayed to end user. This
+ * message should indicate the reason why a request is deferred.
*/
public EDeferException(String msg) {
super(msg);
diff --git a/pki/base/common/src/com/netscape/certsrv/profile/EProfileException.java b/pki/base/common/src/com/netscape/certsrv/profile/EProfileException.java
index d21d6edb..a7d1ca42 100644
--- a/pki/base/common/src/com/netscape/certsrv/profile/EProfileException.java
+++ b/pki/base/common/src/com/netscape/certsrv/profile/EProfileException.java
@@ -22,10 +22,9 @@ import com.netscape.certsrv.base.EBaseException;
/**
* This represents a generic profile exception.
* <p>
- * This is the base class for all profile-specific
- * exception.
+ * This is the base class for all profile-specific exception.
* <p>
- *
+ *
* @version $Revision$, $Date$
*/
public class EProfileException extends EBaseException {
@@ -37,10 +36,9 @@ public class EProfileException extends EBaseException {
/**
* Creates a profile exception.
- *
- * @param msg additional message for the handler
- * of the exception. The message may
- * or may not be localized.
+ *
+ * @param msg additional message for the handler of the exception. The
+ * message may or may not be localized.
*/
public EProfileException(String msg) {
super(msg);
diff --git a/pki/base/common/src/com/netscape/certsrv/profile/ERejectException.java b/pki/base/common/src/com/netscape/certsrv/profile/ERejectException.java
index ceea57f2..ca4bc9da 100644
--- a/pki/base/common/src/com/netscape/certsrv/profile/ERejectException.java
+++ b/pki/base/common/src/com/netscape/certsrv/profile/ERejectException.java
@@ -17,16 +17,14 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.profile;
-
/**
- * This represents a profile specific exception. This
- * exception is raised when a request is rejected.
+ * This represents a profile specific exception. This exception is raised when a
+ * request is rejected.
* <p>
- * A rejected request cannot be reprocessed. Rejected
- * request is considered as a request in its terminal
- * state.
+ * A rejected request cannot be reprocessed. Rejected request is considered as a
+ * request in its terminal state.
* <p>
- *
+ *
* @version $Revision$, $Date$
*/
public class ERejectException extends EProfileException {
@@ -37,10 +35,9 @@ public class ERejectException extends EProfileException {
private static final long serialVersionUID = -542393641391361342L;
/**
- * Creates a rejection exception.
- *
- * @param msg localized message that indicates
- * the reason why a request is
+ * Creates a rejection exception.
+ *
+ * @param msg localized message that indicates the reason why a request is
* rejected.
*/
public ERejectException(String msg) {
diff --git a/pki/base/common/src/com/netscape/certsrv/profile/ICertInfoPolicyDefault.java b/pki/base/common/src/com/netscape/certsrv/profile/ICertInfoPolicyDefault.java
index bfd9bdc9..69879129 100644
--- a/pki/base/common/src/com/netscape/certsrv/profile/ICertInfoPolicyDefault.java
+++ b/pki/base/common/src/com/netscape/certsrv/profile/ICertInfoPolicyDefault.java
@@ -27,6 +27,6 @@ public interface ICertInfoPolicyDefault extends IPolicyDefault {
/**
* Populates certificate info directly.
*/
- public void populate(IRequest request, X509CertInfo info)
+ public void populate(IRequest request, X509CertInfo info)
throws EBaseException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/profile/IEnrollProfile.java b/pki/base/common/src/com/netscape/certsrv/profile/IEnrollProfile.java
index fb92d53e..3207aede 100644
--- a/pki/base/common/src/com/netscape/certsrv/profile/IEnrollProfile.java
+++ b/pki/base/common/src/com/netscape/certsrv/profile/IEnrollProfile.java
@@ -22,28 +22,26 @@ import com.netscape.certsrv.request.IRequest;
/**
* This interface represents an enrollment profile.
* <p>
- * An enrollment profile contains a list of enrollment
- * specific input plugins, default policies, constriant
- * policies and output plugins.
+ * An enrollment profile contains a list of enrollment specific input plugins,
+ * default policies, constriant policies and output plugins.
* <p>
- * This interface also defines a set of enrollment specific
- * attribute names that can be used to retrieve values
- * from an enrollment request.
+ * This interface also defines a set of enrollment specific attribute names that
+ * can be used to retrieve values from an enrollment request.
* <p>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IEnrollProfile extends IProfile {
/**
- * Name of request attribute that stores the User
- * Supplied Certificate Request Type.
+ * Name of request attribute that stores the User Supplied Certificate
+ * Request Type.
*/
public static final String CTX_CERT_REQUEST_TYPE = "cert_request_type";
/**
- * Name of request attribute that stores the User
- * Supplied Certificate Request.
+ * Name of request attribute that stores the User Supplied Certificate
+ * Request.
*/
public static final String CTX_CERT_REQUEST = "cert_request";
@@ -56,17 +54,17 @@ public interface IEnrollProfile extends IProfile {
public static final String REQ_TYPE_KEYGEN = "keygen";
/**
- * Name of request attribute that stores the End-User Locale.
+ * Name of request attribute that stores the End-User Locale.
* <p>
* The value is of type java.util.Locale.
*/
public static final String REQUEST_LOCALE = "req_locale";
/**
- * Name of request attribute that stores the sequence number. Consider
- * a CRMF request that may contain multiple certificate request.
- * The first sub certificate certificate request has a sequence
- * number of 0, the next one has a sequence of 1, and so on.
+ * Name of request attribute that stores the sequence number. Consider a
+ * CRMF request that may contain multiple certificate request. The first sub
+ * certificate certificate request has a sequence number of 0, the next one
+ * has a sequence of 1, and so on.
* <p>
* The value is of type java.lang.Integer.
*/
@@ -86,57 +84,53 @@ public interface IEnrollProfile extends IProfile {
public static final String CTX_RENEWAL = "renewal";
/**
- * Name of request attribute that stores the End-User Supplied
- * Key.
+ * Name of request attribute that stores the End-User Supplied Key.
* <p>
* The value is of type netscape.security.x509.CertificateX509Key
*/
public static final String REQUEST_KEY = "req_key";
/**
- * Name of request attribute that stores the End-User Supplied
- * Subject Name.
+ * Name of request attribute that stores the End-User Supplied Subject Name.
* <p>
* The value is of type netscape.security.x509.CertificateSubjectName
*/
public static final String REQUEST_SUBJECT_NAME = "req_subject_name";
/**
- * Name of request attribute that stores the End-User Supplied
- * Validity.
+ * Name of request attribute that stores the End-User Supplied Validity.
* <p>
* The value is of type netscape.security.x509.CertificateValidity
*/
public static final String REQUEST_VALIDITY = "req_validity";
/**
- * Name of request attribute that stores the End-User Supplied
- * Signing Algorithm.
+ * Name of request attribute that stores the End-User Supplied Signing
+ * Algorithm.
* <p>
* The value is of type netscape.security.x509.CertificateAlgorithmId
*/
public static final String REQUEST_SIGNING_ALGORITHM = "req_signing_alg";
/**
- * Name of request attribute that stores the End-User Supplied
- * Extensions.
+ * Name of request attribute that stores the End-User Supplied Extensions.
* <p>
* The value is of type netscape.security.x509.CertificateExtensions
*/
public static final String REQUEST_EXTENSIONS = "req_extensions";
/**
- * Name of request attribute that stores the End-User Supplied
- * PKI Archive Option extension. This extension is extracted
- * from a CRMF request that has the user-provided private key.
+ * Name of request attribute that stores the End-User Supplied PKI Archive
+ * Option extension. This extension is extracted from a CRMF request that
+ * has the user-provided private key.
* <p>
* The value is of type byte []
*/
public static final String REQUEST_ARCHIVE_OPTIONS = "req_archive_options";
/**
- * Name of request attribute that stores the certificate template
- * that will be signed and then become a certificate.
+ * Name of request attribute that stores the certificate template that will
+ * be signed and then become a certificate.
* <p>
* The value is of type netscape.security.x509.X509CertInfo
*/
@@ -151,6 +145,7 @@ public interface IEnrollProfile extends IProfile {
/**
* Set Default X509CertInfo in the request.
+ *
* @param request profile-based certificate request.
* @exception EProfileException failed to set the X509CertInfo.
*/
diff --git a/pki/base/common/src/com/netscape/certsrv/profile/IPolicyConstraint.java b/pki/base/common/src/com/netscape/certsrv/profile/IPolicyConstraint.java
index 1af3ef19..21656cb3 100644
--- a/pki/base/common/src/com/netscape/certsrv/profile/IPolicyConstraint.java
+++ b/pki/base/common/src/com/netscape/certsrv/profile/IPolicyConstraint.java
@@ -17,55 +17,50 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.profile;
-
import java.util.Locale;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.property.IConfigTemplate;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This represents a constraint policy. A constraint policy
- * validates if the given request conforms to the set
- * rules.
+ * This represents a constraint policy. A constraint policy validates if the
+ * given request conforms to the set rules.
* <p>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IPolicyConstraint extends IConfigTemplate {
/**
* Initializes this constraint policy.
- *
+ *
* @param profile owner of this policy
* @param config configuration store for this constraint
* @exception EProfileException failed to initialize
*/
public void init(IProfile profile, IConfigStore config)
- throws EProfileException;
+ throws EProfileException;
/**
- * Returns the corresponding configuration store
- * of this constraint policy.
- *
+ * Returns the corresponding configuration store of this constraint policy.
+ *
* @return config store of this constraint
*/
public IConfigStore getConfigStore();
/**
- * Validates the request. The request is not modified
- * during the validation.
- *
+ * Validates the request. The request is not modified during the validation.
+ *
* @param request request to be validated
* @exception ERejectException reject the given request
*/
public void validate(IRequest request)
- throws ERejectException;
+ throws ERejectException;
/**
* Returns localized description of this constraint.
- *
+ *
* @param locale locale of the end-user
* @return localized description of this constraint
*/
@@ -73,19 +68,18 @@ public interface IPolicyConstraint extends IConfigTemplate {
/**
* Returns localized name of this constraint.
- *
+ *
* @param locale locale of the end-user
* @return localized name of this constraint
*/
public String getName(Locale locale);
/**
- * Checks if this constraint is applicable to the
- * given default policy.
- *
+ * Checks if this constraint is applicable to the given default policy.
+ *
* @param def default policy to be checked
- * @return true if this constraint can be applied to
- * the given default policy
+ * @return true if this constraint can be applied to the given default
+ * policy
*/
public boolean isApplicable(IPolicyDefault def);
}
diff --git a/pki/base/common/src/com/netscape/certsrv/profile/IPolicyDefault.java b/pki/base/common/src/com/netscape/certsrv/profile/IPolicyDefault.java
index 092b10fd..02504320 100644
--- a/pki/base/common/src/com/netscape/certsrv/profile/IPolicyDefault.java
+++ b/pki/base/common/src/com/netscape/certsrv/profile/IPolicyDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.profile;
-
import java.util.Enumeration;
import java.util.Locale;
@@ -27,36 +26,28 @@ import com.netscape.certsrv.property.IConfigTemplate;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This represents a default policy that populates
- * the request with additional values.
+ * This represents a default policy that populates the request with additional
+ * values.
* <p>
- *
- * During request submission process, a default
- * policy is invoked to populate the default values
- * in the request. The default values will later
- * on be used for execution. The default values
- * are like the parameters for the request.
+ *
+ * During request submission process, a default policy is invoked to populate
+ * the default values in the request. The default values will later on be used
+ * for execution. The default values are like the parameters for the request.
* <p>
- *
- * This policy is called in 2 places. For
- * automated enrollment request, this policy
- * is invoked to populate the HTTP parameters
- * into the request. For request that cannot
- * be executed immediately, this policy will be
- * invoked again right after the agent's
- * approval.
+ *
+ * This policy is called in 2 places. For automated enrollment request, this
+ * policy is invoked to populate the HTTP parameters into the request. For
+ * request that cannot be executed immediately, this policy will be invoked
+ * again right after the agent's approval.
* <p>
- *
- * Each default policy may contain zero or more
- * properties that describe the default value.
- * For example, a X509 Key can be described by
- * its key type, key length, and key data. The
- * properties help to describe the default value
- * into human readable values.
+ *
+ * Each default policy may contain zero or more properties that describe the
+ * default value. For example, a X509 Key can be described by its key type, key
+ * length, and key data. The properties help to describe the default value into
+ * human readable values.
* <p>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IPolicyDefault extends IConfigTemplate {
@@ -69,27 +60,27 @@ public interface IPolicyDefault extends IConfigTemplate {
* @exception EProfileException failed to initialize
*/
public void init(IProfile profile, IConfigStore config)
- throws EProfileException;
+ throws EProfileException;
/**
* Retrieves the configuration store of this default.
- *
+ *
* @return configuration store of this default policy
*/
public IConfigStore getConfigStore();
/**
* Populates the request with this policy default.
- *
+ *
* @param request request to be populated
* @exception EProfileException failed to populate
*/
public void populate(IRequest request)
- throws EProfileException;
-
+ throws EProfileException;
+
/**
* Retrieves the localizable name of this policy.
- *
+ *
* @param locale locale of the end user
* @return localized name of this default policy
*/
@@ -105,17 +96,15 @@ public interface IPolicyDefault extends IConfigTemplate {
/**
* Retrieves a list of names of the property.
- *
- * @return a list of property names. The values are
- * of type java.lang.String
+ *
+ * @return a list of property names. The values are of type java.lang.String
*/
public Enumeration<String> getValueNames();
/**
- * Retrieves the descriptor of the given property
- * by name. The descriptor contains syntax
- * information.
- *
+ * Retrieves the descriptor of the given property by name. The descriptor
+ * contains syntax information.
+ *
* @param locale locale of the end user
* @param name name of property
* @return descriptor of the property
@@ -124,25 +113,24 @@ public interface IPolicyDefault extends IConfigTemplate {
/**
* Sets the value of the given value property by name.
- *
+ *
* @param name name of property
* @param locale locale of the end user
* @param request request
* @param value value to be set in the given request
* @exception EPropertyException failed to set property
*/
- public void setValue(String name, Locale locale, IRequest request,
- String value) throws EPropertyException;
+ public void setValue(String name, Locale locale, IRequest request,
+ String value) throws EPropertyException;
/**
- * Retrieves the value of the given value
- * property by name.
- *
+ * Retrieves the value of the given value property by name.
+ *
* @param name name of property
* @param locale locale of the end user
* @param request request
* @exception EPropertyException failed to get property
*/
public String getValue(String name, Locale locale, IRequest request)
- throws EPropertyException;
+ throws EPropertyException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/profile/IProfile.java b/pki/base/common/src/com/netscape/certsrv/profile/IProfile.java
index cc6975cd..b6cdab6a 100644
--- a/pki/base/common/src/com/netscape/certsrv/profile/IProfile.java
+++ b/pki/base/common/src/com/netscape/certsrv/profile/IProfile.java
@@ -29,72 +29,67 @@ import com.netscape.certsrv.request.IRequestQueue;
import com.netscape.cms.profile.common.ProfilePolicy;
/**
- * This interface represents a profile. A profile contains
- * a list of input policies, default policies, constraint
- * policies and output policies.
+ * This interface represents a profile. A profile contains a list of input
+ * policies, default policies, constraint policies and output policies.
* <p>
- *
+ *
* The input policy is for building the enrollment page.
* <p>
- *
- * The default policy is for populating user-supplied and
- * system-supplied values into the request.
+ *
+ * The default policy is for populating user-supplied and system-supplied values
+ * into the request.
* <p>
- *
- * The constraint policy is for validating the request before
- * processing.
+ *
+ * The constraint policy is for validating the request before processing.
* <p>
- *
+ *
* The output policy is for building the result page.
* <p>
- *
- * Each profile can have multiple policy set. Each set
- * is composed of zero or more default policies and zero
- * or more constraint policies.
+ *
+ * Each profile can have multiple policy set. Each set is composed of zero or
+ * more default policies and zero or more constraint policies.
* <p>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IProfile {
/**
* Initializes this profile.
- *
+ *
* @param owner profile subsystem
* @param config configuration store for this profile
* @exception EBaseException failed to initialize
*/
public void init(IProfileSubsystem owner, IConfigStore config)
- throws EBaseException;
+ throws EBaseException;
/**
- * Retrieves the request queue that is associated with
- * this profile. The request queue is for creating
- * new requests.
- *
+ * Retrieves the request queue that is associated with this profile. The
+ * request queue is for creating new requests.
+ *
* @return request queue
*/
public IRequestQueue getRequestQueue();
/**
* Sets id of this profile.
- *
+ *
* @param id profile identifier
*/
public void setId(String id);
-
+
/**
* Returns the identifier of this profile.
- *
+ *
* @return profile id
*/
public String getId();
/**
- * Retrieves a localized string that represents
- * requestor's distinguished name. This string
- * displayed in the request listing user interface.
- *
+ * Retrieves a localized string that represents requestor's distinguished
+ * name. This string displayed in the request listing user interface.
+ *
* @param request request
* @return distringuished name of the request owner
*/
@@ -102,14 +97,14 @@ public interface IProfile {
/**
* Retrieves the configuration store of this profile.
- *
+ *
* @return configuration store
*/
public IConfigStore getConfigStore();
/**
* Retrieves the instance id of the authenticator for this profile.
- *
+ *
* @return authenticator instance id
*/
public String getAuthenticatorId();
@@ -118,31 +113,31 @@ public interface IProfile {
/**
* Sets the instance id of the authenticator for this profile.
- *
+ *
* @param id authenticator instance id
*/
public void setAuthenticatorId(String id);
/**
* Retrieves the associated authenticator instance.
- *
- * @return profile authenticator instance.
- * if no associated authenticator, null is returned
+ *
+ * @return profile authenticator instance. if no associated authenticator,
+ * null is returned
* @exception EProfileException failed to retrieve
*/
- public IProfileAuthenticator getAuthenticator()
- throws EProfileException;
+ public IProfileAuthenticator getAuthenticator()
+ throws EProfileException;
/**
* Retrieves a list of input policy IDs.
- *
+ *
* @return input policy id list
*/
public Enumeration<String> getProfileInputIds();
/**
* Retrieves input policy by id.
- *
+ *
* @param id input policy id
* @return input policy instance
*/
@@ -150,40 +145,38 @@ public interface IProfile {
/**
* Retrieves a list of output policy IDs.
- *
+ *
* @return output policy id list
*/
public Enumeration<String> getProfileOutputIds();
/**
* Retrieves output policy by id.
- *
+ *
* @param id output policy id
* @return output policy instance
*/
public IProfileOutput getProfileOutput(String id);
/**
- * Checks if this profile is end-user profile or not.
- * End-user profile will be displayed to the end user.
- * Non end-user profile mainly is for registration
- * manager.
- *
+ * Checks if this profile is end-user profile or not. End-user profile will
+ * be displayed to the end user. Non end-user profile mainly is for
+ * registration manager.
+ *
* @return end-user profile or not
*/
- public boolean isVisible();
+ public boolean isVisible();
/**
* Sets this profile end-user profile or not.
- *
+ *
* @param v end-user profile or not
*/
- public void setVisible(boolean v);
+ public void setVisible(boolean v);
/**
- * Retrieves the user id of the person who
- * approves this profile.
- *
+ * Retrieves the user id of the person who approves this profile.
+ *
* @return user id of the approver of this profile
*/
public String getApprovedBy();
@@ -200,7 +193,7 @@ public interface IProfile {
/**
* Returns the profile name.
- *
+ *
* @param locale end-user locale
* @param name profile name
*/
@@ -208,7 +201,7 @@ public interface IProfile {
/**
* Retrieves the profile name.
- *
+ *
* @param locale end-user locale
* @return localized profile name
*/
@@ -216,7 +209,7 @@ public interface IProfile {
/**
* Returns the profile description.
- *
+ *
* @param locale end-user locale
* @param desc profile description
*/
@@ -224,31 +217,30 @@ public interface IProfile {
/**
* Retrieves the profile description.
- *
+ *
* @param locale end-user locale
* @return localized profile description
*/
public String getDescription(Locale locale);
/**
- * Retrieves profile context. The context stores
- * information about the requestor before the
- * actual request is created.
- *
+ * Retrieves profile context. The context stores information about the
+ * requestor before the actual request is created.
+ *
* @return profile context.
*/
public IProfileContext createContext();
/**
* Returns the profile policy set identifiers.
- *
+ *
* @return a list of policy set id
*/
public Enumeration<String> getProfilePolicySetIds();
/**
* Creates a profile policy.
- *
+ *
* @param setId id of the policy set that owns this policy
* @param id policy id
* @param defaultClassId id of the registered default implementation
@@ -256,83 +248,82 @@ public interface IProfile {
* @exception EProfileException failed to create policy
* @return profile policy instance
*/
- public IProfilePolicy createProfilePolicy(String setId, String id,
- String defaultClassId, String constraintClassId)
- throws EProfileException;
+ public IProfilePolicy createProfilePolicy(String setId, String id,
+ String defaultClassId, String constraintClassId)
+ throws EProfileException;
/**
* Deletes input policy by id.
- *
+ *
* @param inputId id of the input policy
- * @exception EProfileException failed to delete
+ * @exception EProfileException failed to delete
*/
public void deleteProfileInput(String inputId) throws EProfileException;
/**
* Deletes output policy by id.
- *
+ *
* @param outputId id of the output policy
- * @exception EProfileException failed to delete
+ * @exception EProfileException failed to delete
*/
public void deleteProfileOutput(String outputId) throws EProfileException;
/**
* Creates a input policy.
- *
+ *
* @param id input policy id
* @param inputClassId id of the registered input implementation
* @param nvp default parameters
* @return input policy
* @exception EProfileException failed to create
*/
- public IProfileInput createProfileInput(String id, String inputClassId,
- NameValuePairs nvp)
- throws EProfileException;
+ public IProfileInput createProfileInput(String id, String inputClassId,
+ NameValuePairs nvp)
+ throws EProfileException;
/**
* Creates a output policy.
- *
+ *
* @param id output policy id
* @param outputClassId id of the registered output implementation
* @param nvp default parameters
* @return output policy
* @exception EProfileException failed to create
*/
- public IProfileOutput createProfileOutput(String id, String outputClassId,
- NameValuePairs nvp) throws EProfileException;
+ public IProfileOutput createProfileOutput(String id, String outputClassId,
+ NameValuePairs nvp) throws EProfileException;
/**
* Deletes a policy.
- *
+ *
* @param setId id of the policy set
* @param policyId id of policy to delete
* @exception EProfileException failed to delete
*/
- public void deleteProfilePolicy(String setId, String policyId)
- throws EProfileException;
+ public void deleteProfilePolicy(String setId, String policyId)
+ throws EProfileException;
/**
* Retrieves a policy.
- *
+ *
* @param setId set id
* @param id policy id
* @return profile policy
*/
- public IProfilePolicy getProfilePolicy(String setId, String id);
+ public IProfilePolicy getProfilePolicy(String setId, String id);
/**
* Retrieves all the policy id within a set.
- *
+ *
* @param setId set id
* @return a list of policy id
*/
public Enumeration<String> getProfilePolicyIds(String setId);
/**
- * Retrieves a default set id for the given request.
- * It is the profile's responsibility to return
- * an appropriate set id for the request.
- *
+ * Retrieves a default set id for the given request. It is the profile's
+ * responsibility to return an appropriate set id for the request.
+ *
* @param req request
* @return policy set id
*/
@@ -340,72 +331,72 @@ public interface IProfile {
/**
* Returns a list of profile policies.
- *
+ *
* @param setId set id
* @return a list of policies
*/
public Enumeration<ProfilePolicy> getProfilePolicies(String setId);
/**
- * Creates one or more requests. Normally, only one request will
- * be created. In case of CRMF request, multiple requests may be
- * created for one submission.
- *
+ * Creates one or more requests. Normally, only one request will be created.
+ * In case of CRMF request, multiple requests may be created for one
+ * submission.
+ *
* @param ctx profile context
* @param locale user locale
* @return a list of requests
* @exception EProfileException failed to create requests
*/
- public IRequest[] createRequests(IProfileContext ctx, Locale locale)
- throws EProfileException;
+ public IRequest[] createRequests(IProfileContext ctx, Locale locale)
+ throws EProfileException;
/**
* Populates user-supplied input values into the requests.
- *
+ *
* @param ctx profile context
* @param request request
* @exception EProfileException failed to populate
*/
- public void populateInput(IProfileContext ctx, IRequest request)
- throws EProfileException;
+ public void populateInput(IProfileContext ctx, IRequest request)
+ throws EProfileException;
/**
- * Passes the request to the set of default policies that
- * populate the profile information against the profile.
- *
+ * Passes the request to the set of default policies that populate the
+ * profile information against the profile.
+ *
* @param request request
* @exception EProfileException failed to populate default values
- */
- public void populate(IRequest request)
- throws EProfileException;
+ */
+ public void populate(IRequest request)
+ throws EProfileException;
/**
- * Passes the request to the set of constraint policies
- * that validate the request against the profile.
- *
+ * Passes the request to the set of constraint policies that validate the
+ * request against the profile.
+ *
* @param request request
* @exception ERejectException validation violation
- */
- public void validate(IRequest request)
- throws ERejectException;
+ */
+ public void validate(IRequest request)
+ throws ERejectException;
/**
* Process a request after validation.
- *
+ *
* @param request request to be processed
* @exception EProfileException failed to process
*/
- public void execute(IRequest request)
- throws EProfileException;
+ public void execute(IRequest request)
+ throws EProfileException;
/**
* Handles end-user request submission.
- *
+ *
* @param token authentication token
* @param request request to be processed
* @exception EDeferException defer request
* @exception EProfileException failed to submit
*/
public void submit(IAuthToken token, IRequest request)
- throws EDeferException, EProfileException;
+ throws EDeferException, EProfileException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/profile/IProfileAuthenticator.java b/pki/base/common/src/com/netscape/certsrv/profile/IProfileAuthenticator.java
index 476002e2..026f86b7 100644
--- a/pki/base/common/src/com/netscape/certsrv/profile/IProfileAuthenticator.java
+++ b/pki/base/common/src/com/netscape/certsrv/profile/IProfileAuthenticator.java
@@ -26,14 +26,12 @@ import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This interface represents an authenticator for profile.
- * An authenticator is responsibile for authenting
- * the end-user. If authentication is successful, request
- * can be processed immediately. Otherwise, the request will
- * be defered and manual approval is then required.
- *
+ * This interface represents an authenticator for profile. An authenticator is
+ * responsibile for authenting the end-user. If authentication is successful,
+ * request can be processed immediately. Otherwise, the request will be defered
+ * and manual approval is then required.
+ *
* @version $Revision$, $Date$
*/
public interface IProfileAuthenticator extends IAuthManager {
@@ -42,35 +40,35 @@ public interface IProfileAuthenticator extends IAuthManager {
/**
* Initializes this default policy.
- *
+ *
* @param profile owner of this authenticator
* @param config configuration store
* @exception EProfileException failed to initialize
*/
public void init(IProfile profile, IConfigStore config)
- throws EProfileException;
+ throws EProfileException;
/**
* Retrieves the configuration store.
- *
+ *
* @return configuration store
*/
public IConfigStore getConfigStore();
/**
- * Populates authentication specific information into the
- * request for auditing purposes.
- *
+ * Populates authentication specific information into the request for
+ * auditing purposes.
+ *
* @param token authentication token
* @param request request
* @exception EProfileException failed to populate
*/
public void populate(IAuthToken token, IRequest request)
- throws EProfileException;
+ throws EProfileException;
/**
* Retrieves the localizable name of this policy.
- *
+ *
* @param locale end user locale
* @return localized authenticator name
*/
@@ -78,7 +76,7 @@ public interface IProfileAuthenticator extends IAuthManager {
/**
* Retrieves the localizable description of this policy.
- *
+ *
* @param locale end user locale
* @return localized authenticator description
*/
@@ -86,26 +84,24 @@ public interface IProfileAuthenticator extends IAuthManager {
/**
* Retrieves a list of names of the property.
- *
+ *
* @return a list of property names
*/
public Enumeration<String> getValueNames();
/**
- * Checks if the value of the given property should be
- * serializable into the request. Passsword or other
- * security-related value may not be desirable for
- * storage.
- *
+ * Checks if the value of the given property should be serializable into the
+ * request. Passsword or other security-related value may not be desirable
+ * for storage.
+ *
* @param name property name
* @return true if the property is not security related
*/
public boolean isValueWriteable(String name);
/**
- * Retrieves the descriptor of the given value
- * property by name.
- *
+ * Retrieves the descriptor of the given value property by name.
+ *
* @param locale user locale
* @param name property name
* @return descriptor of the requested property
@@ -114,7 +110,7 @@ public interface IProfileAuthenticator extends IAuthManager {
/**
* Checks if this authenticator requires SSL client authentication.
- *
+ *
* @return client authentication required or not
*/
public boolean isSSLClientRequired();
diff --git a/pki/base/common/src/com/netscape/certsrv/profile/IProfileContext.java b/pki/base/common/src/com/netscape/certsrv/profile/IProfileContext.java
index 906c4816..8a569d17 100644
--- a/pki/base/common/src/com/netscape/certsrv/profile/IProfileContext.java
+++ b/pki/base/common/src/com/netscape/certsrv/profile/IProfileContext.java
@@ -17,19 +17,17 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.profile;
-
/**
- * This interface represents a profile context which
- * stores system-wide and user-provided information for
- * assisting request creation.
- *
+ * This interface represents a profile context which stores system-wide and
+ * user-provided information for assisting request creation.
+ *
* @version $Revision$, $Date$
*/
public interface IProfileContext {
/**
* Sets a value into the context.
- *
+ *
* @param name property name
* @param value property value
*/
@@ -37,7 +35,7 @@ public interface IProfileContext {
/**
* Retrieves a value from the context.
- *
+ *
* @param name property name
* @return property value
*/
diff --git a/pki/base/common/src/com/netscape/certsrv/profile/IProfileEx.java b/pki/base/common/src/com/netscape/certsrv/profile/IProfileEx.java
index 8ce3262e..dc8d782b 100644
--- a/pki/base/common/src/com/netscape/certsrv/profile/IProfileEx.java
+++ b/pki/base/common/src/com/netscape/certsrv/profile/IProfileEx.java
@@ -20,17 +20,16 @@ package com.netscape.certsrv.profile;
import com.netscape.certsrv.base.EBaseException;
/**
- * This interface represents the extension version of
- * profile.
+ * This interface represents the extension version of profile.
* <p>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IProfileEx extends IProfile {
/**
- * Called after initialization. It populates default
- * policies, inputs, and outputs.
+ * Called after initialization. It populates default policies, inputs, and
+ * outputs.
*/
public void populate() throws EBaseException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/profile/IProfileInput.java b/pki/base/common/src/com/netscape/certsrv/profile/IProfileInput.java
index 35453e7d..b2268ebb 100644
--- a/pki/base/common/src/com/netscape/certsrv/profile/IProfileInput.java
+++ b/pki/base/common/src/com/netscape/certsrv/profile/IProfileInput.java
@@ -27,9 +27,8 @@ import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
/**
- * This interface represents a input policy which
- * provides information on how to create the
- * end-user enrollment page.
+ * This interface represents a input policy which provides information on how to
+ * create the end-user enrollment page.
*
* @version $Revision$, $Date$
*/
@@ -37,34 +36,34 @@ public interface IProfileInput extends IConfigTemplate {
/**
* Initializes this default policy.
- *
+ *
* @param profile owner of this input
* @param config configuration store
* @exception EProfileException failed to initialize
*/
public void init(IProfile profile, IConfigStore config)
- throws EProfileException;
+ throws EProfileException;
/**
* Returns configuration store.
- *
+ *
* @return configuration store
*/
public IConfigStore getConfigStore();
/**
* Populates the request with this policy default.
- *
+ *
* @param ctx profile context
* @param request request
* @exception EProfileException failed to populate
*/
public void populate(IProfileContext ctx, IRequest request)
- throws EProfileException;
+ throws EProfileException;
/**
* Retrieves the localizable name of this policy.
- *
+ *
* @param locale user locale
* @return localized input name
*/
@@ -72,7 +71,7 @@ public interface IProfileInput extends IConfigTemplate {
/**
* Retrieves the localizable description of this policy.
- *
+ *
* @param locale user locale
* @return localized input description
*/
@@ -80,15 +79,14 @@ public interface IProfileInput extends IConfigTemplate {
/**
* Retrieves a list of names of the property.
- *
+ *
* @return a list of property names
*/
public Enumeration<String> getValueNames();
/**
- * Retrieves the descriptor of the given value
- * property by name.
- *
+ * Retrieves the descriptor of the given value property by name.
+ *
* @param locale user locale
* @param name property name
* @return descriptor of the property
@@ -97,24 +95,24 @@ public interface IProfileInput extends IConfigTemplate {
/**
* Retrieves value from the request.
- *
+ *
* @param name property name
* @param locale user locale
* @param request request
* @exception EProfileException failed to get value
*/
public String getValue(String name, Locale locale, IRequest request)
- throws EProfileException;
+ throws EProfileException;
/**
* Sets the value of the given property by name.
- *
+ *
* @param name property name
* @param locale user locale
* @param request request
* @param value value
* @exception EProfileException failed to get value
*/
- public void setValue(String name, Locale locale, IRequest request,
- String value) throws EPropertyException;
+ public void setValue(String name, Locale locale, IRequest request,
+ String value) throws EPropertyException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/profile/IProfileOutput.java b/pki/base/common/src/com/netscape/certsrv/profile/IProfileOutput.java
index 6dbfea51..f8fc9d6b 100644
--- a/pki/base/common/src/com/netscape/certsrv/profile/IProfileOutput.java
+++ b/pki/base/common/src/com/netscape/certsrv/profile/IProfileOutput.java
@@ -27,9 +27,8 @@ import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
/**
- * This interface represents a output policy which
- * provides information on how to build the result
- * page for the enrollment.
+ * This interface represents a output policy which provides information on how
+ * to build the result page for the enrollment.
*
* @version $Revision$, $Date$
*/
@@ -37,34 +36,34 @@ public interface IProfileOutput extends IConfigTemplate {
/**
* Initializes this default policy.
- *
+ *
* @param profile owner of this policy
* @param config configuration store
* @exception EProfileException failed to initialize
*/
public void init(IProfile profile, IConfigStore config)
- throws EProfileException;
+ throws EProfileException;
/**
* Retrieves configuration store.
- *
+ *
* @return configuration store
*/
public IConfigStore getConfigStore();
/**
* Populates the request with this policy default.
- *
+ *
* @param ctx profile context
* @param request request
* @exception EProfileException failed to populate
*/
public void populate(IProfileContext ctx, IRequest request)
- throws EProfileException;
+ throws EProfileException;
/**
* Retrieves the localizable name of this policy.
- *
+ *
* @param locale user locale
* @return output policy name
*/
@@ -72,7 +71,7 @@ public interface IProfileOutput extends IConfigTemplate {
/**
* Retrieves the localizable description of this policy.
- *
+ *
* @param locale user locale
* @return output policy description
*/
@@ -80,15 +79,14 @@ public interface IProfileOutput extends IConfigTemplate {
/**
* Retrieves a list of names of the value parameter.
- *
+ *
* @return a list of property names
*/
public Enumeration<String> getValueNames();
/**
- * Retrieves the descriptor of the given value
- * parameter by name.
- *
+ * Retrieves the descriptor of the given value parameter by name.
+ *
* @param locale user locale
* @param name property name
* @return property descriptor
@@ -97,7 +95,7 @@ public interface IProfileOutput extends IConfigTemplate {
/**
* Retrieves the value of the given value parameter by name.
- *
+ *
* @param name property name
* @param locale user locale
* @param request request
@@ -105,17 +103,17 @@ public interface IProfileOutput extends IConfigTemplate {
* @exception EProfileException failed to retrieve value
*/
public String getValue(String name, Locale locale, IRequest request)
- throws EProfileException;
+ throws EProfileException;
/**
* Sets the value of the given value parameter by name.
- *
+ *
* @param name property name
* @param locale user locale
* @param request request
* @param value property value
* @exception EProfileException failed to retrieve value
*/
- public void setValue(String name, Locale locale, IRequest request,
- String value) throws EPropertyException;
+ public void setValue(String name, Locale locale, IRequest request,
+ String value) throws EPropertyException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/profile/IProfilePolicy.java b/pki/base/common/src/com/netscape/certsrv/profile/IProfilePolicy.java
index 9577cb08..733a69b1 100644
--- a/pki/base/common/src/com/netscape/certsrv/profile/IProfilePolicy.java
+++ b/pki/base/common/src/com/netscape/certsrv/profile/IProfilePolicy.java
@@ -18,31 +18,30 @@
package com.netscape.certsrv.profile;
/**
- * This interface represents a profile policy
- * which consists a default policy and a
- * constraint policy.
- *
+ * This interface represents a profile policy which consists a default policy
+ * and a constraint policy.
+ *
* @version $Revision$, $Date$
*/
public interface IProfilePolicy {
/**
- * Retrieves the policy id
- *
+ * Retrieves the policy id
+ *
* @return policy id
*/
public String getId();
/**
* Retrieves the default policy.
- *
+ *
* @return default policy
*/
public IPolicyDefault getDefault();
/**
* Retrieves the constraint policy.
- *
+ *
* @return constraint policy
*/
public IPolicyConstraint getConstraint();
diff --git a/pki/base/common/src/com/netscape/certsrv/profile/IProfileSubsystem.java b/pki/base/common/src/com/netscape/certsrv/profile/IProfileSubsystem.java
index 6f2fef37..48162dd2 100644
--- a/pki/base/common/src/com/netscape/certsrv/profile/IProfileSubsystem.java
+++ b/pki/base/common/src/com/netscape/certsrv/profile/IProfileSubsystem.java
@@ -17,16 +17,13 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.profile;
-
import java.util.Enumeration;
import com.netscape.certsrv.base.ISubsystem;
-
/**
- * This represents the profile subsystem that manages
- * a list of profiles.
- *
+ * This represents the profile subsystem that manages a list of profiles.
+ *
* @version $Revision$, $Date$
*/
public interface IProfileSubsystem extends ISubsystem {
@@ -34,16 +31,16 @@ public interface IProfileSubsystem extends ISubsystem {
/**
* Retrieves a profile by id.
- *
+ *
* @return profile
* @exception EProfileException failed to retrieve
*/
public IProfile getProfile(String id)
- throws EProfileException;
+ throws EProfileException;
/**
* Checks if a profile is approved by an agent or not.
- *
+ *
* @param id profile id
* @return true if profile is approved
*/
@@ -51,7 +48,7 @@ public interface IProfileSubsystem extends ISubsystem {
/**
* Retrieves the approver of the given profile.
- *
+ *
* @param id profile id
* @return user id of the agent who has approved the profile
*/
@@ -59,76 +56,75 @@ public interface IProfileSubsystem extends ISubsystem {
/**
* Creates new profile.
- *
+ *
* @param id profile id
* @param classid implementation id
* @param className class Name
* @param configFile configuration file
* @exception EProfileException failed to create profile
*/
- public IProfile createProfile(String id, String classid,
- String className, String configFile)
- throws EProfileException;
+ public IProfile createProfile(String id, String classid,
+ String className, String configFile)
+ throws EProfileException;
/**
* Deletes profile.
- *
+ *
* @param id profile id
* @param configFile configuration file
* @exception EProfileException failed to delete profile
*/
- public void deleteProfile(String id, String configFile)
- throws EProfileException;
+ public void deleteProfile(String id, String configFile)
+ throws EProfileException;
/**
* Creates a new profile configuration file.
- *
+ *
* @param id profile id
* @param classId implementation id
* @param configPath location to create the configuration file
* @exception failed to create profile
*/
public void createProfileConfig(String id, String classId,
- String configPath) throws EProfileException;
+ String configPath) throws EProfileException;
/**
* Enables a profile.
- *
+ *
* @param id profile id
* @param enableBy agent's user id
* @exception EProfileException failed to enable profile
*/
public void enableProfile(String id, String enableBy)
- throws EProfileException;
+ throws EProfileException;
/**
* Disables a profile.
- *
+ *
* @param id profile id
* @exception EProfileException failed to disable
*/
public void disableProfile(String id)
- throws EProfileException;
+ throws EProfileException;
/**
* Retrieves the id of the implementation of the given profile.
- *
+ *
* @param id profile id
* @return implementation id managed by the registry
*/
public String getProfileClassId(String id);
/**
- * Retrieves a list of profile ids. The return
- * list is of type String.
- *
+ * Retrieves a list of profile ids. The return list is of type String.
+ *
* @return a list of profile ids
*/
- public Enumeration<String> getProfileIds();
+ public Enumeration<String> getProfileIds();
/**
* Checks if owner id should be enforced during profile approval.
- *
+ *
* @return true if approval should be checked
*/
public boolean checkOwner();
diff --git a/pki/base/common/src/com/netscape/certsrv/profile/IProfileUpdater.java b/pki/base/common/src/com/netscape/certsrv/profile/IProfileUpdater.java
index a36ee196..504acb0b 100644
--- a/pki/base/common/src/com/netscape/certsrv/profile/IProfileUpdater.java
+++ b/pki/base/common/src/com/netscape/certsrv/profile/IProfileUpdater.java
@@ -25,8 +25,8 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.RequestStatus;
/**
- * This interface represents an updater that will be
- * called when the request's state changes.
+ * This interface represents an updater that will be called when the request's
+ * state changes.
*
* @version $Revision$, $Date$
*/
@@ -34,34 +34,34 @@ public interface IProfileUpdater extends IConfigTemplate {
/**
* Initializes this default policy.
- *
+ *
* @param profile owner of this policy
* @param config configuration store
* @exception EProfileException failed to initialize
*/
public void init(IProfile profile, IConfigStore config)
- throws EProfileException;
+ throws EProfileException;
/**
* Retrieves configuration store.
- *
+ *
* @return configuration store
*/
public IConfigStore getConfigStore();
/**
* Notifies of state change.
- *
+ *
* @param req request
* @param status The status to check for.
* @exception EProfileException failed to populate
*/
- public void update(IRequest req, RequestStatus status)
- throws EProfileException;
+ public void update(IRequest req, RequestStatus status)
+ throws EProfileException;
/**
* Retrieves the localizable name of this policy.
- *
+ *
* @param locale user locale
* @return output policy name
*/
@@ -69,7 +69,7 @@ public interface IProfileUpdater extends IConfigTemplate {
/**
* Retrieves the localizable description of this policy.
- *
+ *
* @param locale user locale
* @return output policy description
*/
diff --git a/pki/base/common/src/com/netscape/certsrv/property/Descriptor.java b/pki/base/common/src/com/netscape/certsrv/property/Descriptor.java
index 92aeff18..a6f6cd83 100644
--- a/pki/base/common/src/com/netscape/certsrv/property/Descriptor.java
+++ b/pki/base/common/src/com/netscape/certsrv/property/Descriptor.java
@@ -19,10 +19,9 @@ package com.netscape.certsrv.property;
import java.util.Locale;
-
/**
- * This interface represents a property descriptor. A descriptor
- * includes information that describe a property.
+ * This interface represents a property descriptor. A descriptor includes
+ * information that describe a property.
*
* @version $Revision$, $Date$
*/
@@ -35,7 +34,7 @@ public class Descriptor implements IDescriptor {
/**
* Constructs a descriptor.
- *
+ *
* @param syntax syntax
* @param constraint constraint
* @param defValue default value
@@ -50,16 +49,16 @@ public class Descriptor implements IDescriptor {
/**
* Returns the syntax of the property.
- *
+ *
* @return syntax
*/
public String getSyntax() {
return mSyntax;
}
-
+
/**
* Returns the default value of the property.
- *
+ *
* @return default value
*/
public String getDefaultValue() {
@@ -69,14 +68,14 @@ public class Descriptor implements IDescriptor {
/**
* Constraint for the given syntax. For example,
* <p>
- * - number(1-5): 1-5 is the constraint, and it indicates
- * that the number must be in the range of 1 to 5.
+ * - number(1-5): 1-5 is the constraint, and it indicates that the number
+ * must be in the range of 1 to 5.
* <p>
- * - choice(cert,crl): cert,crl is the constraint
- * for choice
+ * - choice(cert,crl): cert,crl is the constraint for choice
* <p>
* If null, no constraint shall be enforced.
* <p>
+ *
* @return constraint
*/
public String getConstraint() {
@@ -85,6 +84,7 @@ public class Descriptor implements IDescriptor {
/**
* Retrieves the description of the property.
+ *
* @param locale user locale
* @return description
*/
diff --git a/pki/base/common/src/com/netscape/certsrv/property/EPropertyException.java b/pki/base/common/src/com/netscape/certsrv/property/EPropertyException.java
index a5847cb2..23f59a25 100644
--- a/pki/base/common/src/com/netscape/certsrv/property/EPropertyException.java
+++ b/pki/base/common/src/com/netscape/certsrv/property/EPropertyException.java
@@ -17,12 +17,11 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.property;
-
import com.netscape.certsrv.base.EBaseException;
/**
* This is the base exception for property handling.
- *
+ *
* @version $Revision$, $Date$
*/
public class EPropertyException extends EBaseException {
@@ -34,7 +33,7 @@ public class EPropertyException extends EBaseException {
/**
* Constructs property exception
- *
+ *
* @param msg exception message
*/
public EPropertyException(String msg) {
diff --git a/pki/base/common/src/com/netscape/certsrv/property/IConfigTemplate.java b/pki/base/common/src/com/netscape/certsrv/property/IConfigTemplate.java
index e40c98fa..5a972073 100644
--- a/pki/base/common/src/com/netscape/certsrv/property/IConfigTemplate.java
+++ b/pki/base/common/src/com/netscape/certsrv/property/IConfigTemplate.java
@@ -17,21 +17,17 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.property;
-
import java.util.Enumeration;
import java.util.Locale;
-
/**
- * This interface provides a standard way to describe
- * a set of configuration parameters and its associated syntax.
- * It provides programmatic methods for querying
- * template description.
+ * This interface provides a standard way to describe a set of configuration
+ * parameters and its associated syntax. It provides programmatic methods for
+ * querying template description.
* <p>
- * A plugin, for example, can be described as a
- * property template.
+ * A plugin, for example, can be described as a property template.
* <p>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IConfigTemplate {
@@ -45,7 +41,7 @@ public interface IConfigTemplate {
/**
* Returns the descriptors of configuration parameter.
- *
+ *
* @param locale user locale
* @param name configuration parameter name
* @return descriptor
@@ -54,17 +50,17 @@ public interface IConfigTemplate {
/**
* Sets configuration parameter.
- *
+ *
* @param name parameter name
* @param value parameter value
* @exception EPropertyException failed to set parameter
*/
public void setConfig(String name, String value)
- throws EPropertyException;
+ throws EPropertyException;
/**
* Retrieves configuration parameter by name.
- *
+ *
* @return parameter
*/
public String getConfig(String name);
diff --git a/pki/base/common/src/com/netscape/certsrv/property/IDescriptor.java b/pki/base/common/src/com/netscape/certsrv/property/IDescriptor.java
index 271c1808..d70156f7 100644
--- a/pki/base/common/src/com/netscape/certsrv/property/IDescriptor.java
+++ b/pki/base/common/src/com/netscape/certsrv/property/IDescriptor.java
@@ -17,13 +17,11 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.property;
-
import java.util.Locale;
-
/**
* This interface represents a property descriptor.
- *
+ *
* @version $Revision$, $Date$
*/
public interface IDescriptor {
@@ -54,26 +52,24 @@ public interface IDescriptor {
/**
* Returns the syntax of the property.
- *
+ *
* @return syntax
*/
public String getSyntax();
/**
- * Constraint for the given syntax. For example,
- * - number(1-5): 1-5 is the constraint, and it indicates
- * that the number must be in the range of 1 to 5.
- * - choice(cert,crl): cert,crl is the constraint
- * for choice
- * If null, no constraint shall be enforced.
- *
+ * Constraint for the given syntax. For example, - number(1-5): 1-5 is the
+ * constraint, and it indicates that the number must be in the range of 1 to
+ * 5. - choice(cert,crl): cert,crl is the constraint for choice If null, no
+ * constraint shall be enforced.
+ *
* @return constraint
*/
public String getConstraint();
/**
* Retrieves the description of the property.
- *
+ *
* @param locale user locale
* @return localized description
*/
@@ -81,7 +77,7 @@ public interface IDescriptor {
/**
* Retrieves the default value of the property.
- *
+ *
* @return default value
*/
public String getDefaultValue();
diff --git a/pki/base/common/src/com/netscape/certsrv/property/PropertySet.java b/pki/base/common/src/com/netscape/certsrv/property/PropertySet.java
index f308a3e7..dc839deb 100644
--- a/pki/base/common/src/com/netscape/certsrv/property/PropertySet.java
+++ b/pki/base/common/src/com/netscape/certsrv/property/PropertySet.java
@@ -20,40 +20,33 @@ package com.netscape.certsrv.property;
import java.util.Enumeration;
import java.util.Hashtable;
-
/**
* A set of properties.
*/
public class PropertySet {
- private Hashtable<String, IDescriptor> mProperties = new Hashtable<String, IDescriptor>();
+ private Hashtable<String, IDescriptor> mProperties = new Hashtable<String, IDescriptor>();
- public PropertySet()
- {
- }
+ public PropertySet() {
+ }
- public void add(String name, IDescriptor desc)
- {
- mProperties.put(name, desc);
- }
+ public void add(String name, IDescriptor desc) {
+ mProperties.put(name, desc);
+ }
- public Enumeration<String> getNames()
- {
- return mProperties.keys();
- }
+ public Enumeration<String> getNames() {
+ return mProperties.keys();
+ }
- public IDescriptor getDescriptor(String name)
- {
- return (IDescriptor)mProperties.get(name);
- }
+ public IDescriptor getDescriptor(String name) {
+ return (IDescriptor) mProperties.get(name);
+ }
- public void remove(String name)
- {
- mProperties.remove(name);
- }
+ public void remove(String name) {
+ mProperties.remove(name);
+ }
- public int size()
- {
- return mProperties.size();
- }
+ public int size() {
+ return mProperties.size();
+ }
}
diff --git a/pki/base/common/src/com/netscape/certsrv/publish/ECompSyntaxErr.java b/pki/base/common/src/com/netscape/certsrv/publish/ECompSyntaxErr.java
index 147bdd20..76b67cdc 100644
--- a/pki/base/common/src/com/netscape/certsrv/publish/ECompSyntaxErr.java
+++ b/pki/base/common/src/com/netscape/certsrv/publish/ECompSyntaxErr.java
@@ -17,16 +17,14 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.publish;
-
import com.netscape.certsrv.ldap.ELdapException;
-
/**
- * This type of exception is thrown in cases where an parsing
- * error is found while evaluating a PKI component. An example
- * would be in trying to evaluate a PKI authentication message and
- * the parsing operation fails due to a missing token.
- *
+ * This type of exception is thrown in cases where an parsing error is found
+ * while evaluating a PKI component. An example would be in trying to evaluate a
+ * PKI authentication message and the parsing operation fails due to a missing
+ * token.
+ *
* @version $Revision$ $Date$
*/
public class ECompSyntaxErr extends ELdapException {
@@ -37,8 +35,9 @@ public class ECompSyntaxErr extends ELdapException {
private static final long serialVersionUID = -2224290038321971845L;
/**
- * Construct a ECompSyntaxErr
- * @param errorString The descriptive error condition.
+ * Construct a ECompSyntaxErr
+ *
+ * @param errorString The descriptive error condition.
*/
public ECompSyntaxErr(String errorString) {
diff --git a/pki/base/common/src/com/netscape/certsrv/publish/EMapperNotFound.java b/pki/base/common/src/com/netscape/certsrv/publish/EMapperNotFound.java
index 8c482a4e..fdf4a1b9 100644
--- a/pki/base/common/src/com/netscape/certsrv/publish/EMapperNotFound.java
+++ b/pki/base/common/src/com/netscape/certsrv/publish/EMapperNotFound.java
@@ -17,13 +17,11 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.publish;
-
import com.netscape.certsrv.ldap.ELdapException;
-
/**
- * Exception for Publish Mapper not found.
- *
+ * Exception for Publish Mapper not found.
+ *
* @version $Revision$ $Date$
*/
public class EMapperNotFound extends ELdapException {
@@ -35,6 +33,7 @@ public class EMapperNotFound extends ELdapException {
/**
* Constructs a exception for a missing required mapper
+ *
* @param errorString Detailed error message.
*/
public EMapperNotFound(String errorString) {
diff --git a/pki/base/common/src/com/netscape/certsrv/publish/EMapperPluginNotFound.java b/pki/base/common/src/com/netscape/certsrv/publish/EMapperPluginNotFound.java
index d487488b..f8f18c5f 100644
--- a/pki/base/common/src/com/netscape/certsrv/publish/EMapperPluginNotFound.java
+++ b/pki/base/common/src/com/netscape/certsrv/publish/EMapperPluginNotFound.java
@@ -17,13 +17,11 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.publish;
-
import com.netscape.certsrv.ldap.ELdapException;
-
/**
* Exception for Mapper Plugin not found.
- *
+ *
* @version $Revision$ $Date$
*/
public class EMapperPluginNotFound extends ELdapException {
@@ -35,10 +33,10 @@ public class EMapperPluginNotFound extends ELdapException {
/**
* Constructs a exception for a missing mapper plugin
+ *
* @param errorString Detailed error message.
*/
public EMapperPluginNotFound(String errorString) {
super(errorString);
}
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/publish/EPublisherNotFound.java b/pki/base/common/src/com/netscape/certsrv/publish/EPublisherNotFound.java
index 12054dd1..176001e9 100644
--- a/pki/base/common/src/com/netscape/certsrv/publish/EPublisherNotFound.java
+++ b/pki/base/common/src/com/netscape/certsrv/publish/EPublisherNotFound.java
@@ -17,13 +17,11 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.publish;
-
import com.netscape.certsrv.ldap.ELdapException;
-
/**
* Exception for Publisher not found. Required for successful publishing.
- *
+ *
* @version $Revision$ $Date$
*/
public class EPublisherNotFound extends ELdapException {
@@ -35,6 +33,7 @@ public class EPublisherNotFound extends ELdapException {
/**
* Constructs a exception for a missing required publisher.
+ *
* @param errorString Detailed error message.
*/
public EPublisherNotFound(String errorString) {
diff --git a/pki/base/common/src/com/netscape/certsrv/publish/EPublisherPluginNotFound.java b/pki/base/common/src/com/netscape/certsrv/publish/EPublisherPluginNotFound.java
index 0a7fa1ca..ad47d0c7 100644
--- a/pki/base/common/src/com/netscape/certsrv/publish/EPublisherPluginNotFound.java
+++ b/pki/base/common/src/com/netscape/certsrv/publish/EPublisherPluginNotFound.java
@@ -17,13 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.publish;
-
import com.netscape.certsrv.ldap.ELdapException;
-
/**
- * Exception for Publisher Plugin not found. Plugin implementation is required to actually publish.
- *
+ * Exception for Publisher Plugin not found. Plugin implementation is required
+ * to actually publish.
+ *
* @version $Revision$ $Date$
*/
public class EPublisherPluginNotFound extends ELdapException {
@@ -35,10 +34,10 @@ public class EPublisherPluginNotFound extends ELdapException {
/**
* Constructs a exception for a missing publisher plugin.
+ *
* @param errorString Detailed error message.
*/
public EPublisherPluginNotFound(String errorString) {
super(errorString);
}
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/publish/ERuleNotFound.java b/pki/base/common/src/com/netscape/certsrv/publish/ERuleNotFound.java
index 2094967d..dba161dd 100644
--- a/pki/base/common/src/com/netscape/certsrv/publish/ERuleNotFound.java
+++ b/pki/base/common/src/com/netscape/certsrv/publish/ERuleNotFound.java
@@ -17,13 +17,11 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.publish;
-
import com.netscape.certsrv.ldap.ELdapException;
-
/**
* Exception for Ldap Publishing Rule not found.
- *
+ *
* @version $Revision$ $Date$
*/
public class ERuleNotFound extends ELdapException {
@@ -34,7 +32,9 @@ public class ERuleNotFound extends ELdapException {
private static final long serialVersionUID = 8442034769483263745L;
/**
- * Constructs a exception for a missing required rule, which links a publisher and mapper.
+ * Constructs a exception for a missing required rule, which links a
+ * publisher and mapper.
+ *
* @param errorString Detailed error message.
*/
public ERuleNotFound(String errorString) {
diff --git a/pki/base/common/src/com/netscape/certsrv/publish/ERulePluginNotFound.java b/pki/base/common/src/com/netscape/certsrv/publish/ERulePluginNotFound.java
index 24ffa11a..bfb41e14 100644
--- a/pki/base/common/src/com/netscape/certsrv/publish/ERulePluginNotFound.java
+++ b/pki/base/common/src/com/netscape/certsrv/publish/ERulePluginNotFound.java
@@ -17,13 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.publish;
-
import com.netscape.certsrv.ldap.ELdapException;
-
/**
- * Exception for Publisher Rule plugin not found. Plugin required to implement Ldap Rule.
- *
+ * Exception for Publisher Rule plugin not found. Plugin required to implement
+ * Ldap Rule.
+ *
* @version $Revision$ $Date$
*/
public class ERulePluginNotFound extends ELdapException {
@@ -35,10 +34,10 @@ public class ERulePluginNotFound extends ELdapException {
/**
* Constructs a exception for a missing rule plugin.
+ *
* @param errorString Detailed error message.
*/
public ERulePluginNotFound(String errorString) {
super(errorString);
}
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/publish/ICRLPublisher.java b/pki/base/common/src/com/netscape/certsrv/publish/ICRLPublisher.java
index cae75d2f..e426d931 100644
--- a/pki/base/common/src/com/netscape/certsrv/publish/ICRLPublisher.java
+++ b/pki/base/common/src/com/netscape/certsrv/publish/ICRLPublisher.java
@@ -17,50 +17,43 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.publish;
-
import netscape.security.x509.X509CRLImpl;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.base.ISubsystem;
-
/**
- * This interface represents a CRL publisher that is
- * invoked when CRL publishing is requested by CMS.
- * Note that CMS, by default, shipped with a LDAP-based
- * CRL publisher that can be configured via
- * Certificiate Manager/LDAP Publishing panel. This
- * interface provides administrator additional capability
- * of publishing CRL to different destinations.
- *
- * The CRL publishing frequency is configured via
- * Netscape Certificate Server Console's
- * Certificate Manager/Revocation List panel.
- * The CRL publishing may occur either everytime a
- * certificate is revoked or at a pre-defined interval.
+ * This interface represents a CRL publisher that is invoked when CRL publishing
+ * is requested by CMS. Note that CMS, by default, shipped with a LDAP-based CRL
+ * publisher that can be configured via Certificiate Manager/LDAP Publishing
+ * panel. This interface provides administrator additional capability of
+ * publishing CRL to different destinations.
*
- * To try out this new CRL publisher mechanism, do
- * the following:
- * (1) Write a sample CRL publisher class that implements
- * ICRLPublisher interface. For example,
+ * The CRL publishing frequency is configured via Netscape Certificate Server
+ * Console's Certificate Manager/Revocation List panel. The CRL publishing may
+ * occur either everytime a certificate is revoked or at a pre-defined interval.
+ *
+ * To try out this new CRL publisher mechanism, do the following: (1) Write a
+ * sample CRL publisher class that implements ICRLPublisher interface. For
+ * example,
*
* <code>
* public class CRLPublisher implements ICRLPublisher
* {
* public void init(ISubsystem owner, IConfigStore config)
- * throws EBaseException
+ * throws EBaseException
* {
- * log(ILogger.LL_DEBUG, "CRLPublisher: Initialized");
+ * log(ILogger.LL_DEBUG, "CRLPublisher: Initialized");
* }
- *
- * public void publish(String issuingPointId, X509CRLImpl crl)
+ *
+ * public void publish(String issuingPointId, X509CRLImpl crl)
* throws EBaseException
* {
* log(ILogger.LL_DEBUG, "CRLPublisher: " + issuingPointId +
* " crl=" + crl);
* }
- *
+ *
* public void log(int level, String msg)
* {
* Logger.getLogger().log(ILogger.EV_SYSTEM,
@@ -69,14 +62,12 @@ import com.netscape.certsrv.base.ISubsystem;
* }
* }
* </code>
- *
- * (2) Compile the class and place the class into
- * <server-root>\bin\cert\classes directory.
- * (3) Add the following parameter to CMS.cfg
- * ca.crlPublisher.class=<implementation class>
- * For example,
- * ca.crlPublisher.class=myCRLPublisher
- *
+ *
+ * (2) Compile the class and place the class into <server-root>\bin\cert\classes
+ * directory. (3) Add the following parameter to CMS.cfg
+ * ca.crlPublisher.class=<implementation class> For example,
+ * ca.crlPublisher.class=myCRLPublisher
+ *
* @version $Revision$, $Date$
*/
public interface ICRLPublisher {
@@ -84,26 +75,25 @@ public interface ICRLPublisher {
/**
* Initializes this CRL publisher.
*
- * @param owner parent of the publisher. An object of type
- * CertificateAuthority.
- * @param config config store for this publisher. If this
- * publisher requires configuration parameters for
- * initialization, the parameters should be placed
- * in CMS.cfg as ca.crlPublisher.<paramType>=<paramValue>
+ * @param owner parent of the publisher. An object of type
+ * CertificateAuthority.
+ * @param config config store for this publisher. If this publisher requires
+ * configuration parameters for initialization, the parameters
+ * should be placed in CMS.cfg as
+ * ca.crlPublisher.<paramType>=<paramValue>
* @exception EBaseException failed to initialize this publisher
*/
- public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException;
+ public void init(ISubsystem owner, IConfigStore config)
+ throws EBaseException;
/**
- * Publishes CRL. This method is invoked by CMS based
- * on the configured CRL publishing frequency.
- *
- * @param issuingPointId CRL issuing point identifier
- * (i.e. MasterCRL)
+ * Publishes CRL. This method is invoked by CMS based on the configured CRL
+ * publishing frequency.
+ *
+ * @param issuingPointId CRL issuing point identifier (i.e. MasterCRL)
* @param crl CRL that is publishing
* @exception EBaseException failed to publish
*/
- public void publish(String issuingPointId, X509CRLImpl crl)
- throws EBaseException;
-}
+ public void publish(String issuingPointId, X509CRLImpl crl)
+ throws EBaseException;
+}
diff --git a/pki/base/common/src/com/netscape/certsrv/publish/ILdapCertMapper.java b/pki/base/common/src/com/netscape/certsrv/publish/ILdapCertMapper.java
index cd4012a4..9ee48098 100644
--- a/pki/base/common/src/com/netscape/certsrv/publish/ILdapCertMapper.java
+++ b/pki/base/common/src/com/netscape/certsrv/publish/ILdapCertMapper.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.publish;
-
import java.security.cert.X509Certificate;
import java.util.Vector;
@@ -25,10 +24,9 @@ import netscape.ldap.LDAPConnection;
import com.netscape.certsrv.ldap.ELdapException;
-
-/**
- * Interface for mapping a X509 certificate to a LDAP entry.
- *
+/**
+ * Interface for mapping a X509 certificate to a LDAP entry.
+ *
* @version $Revision$ $Date$
*/
public interface ILdapCertMapper extends ILdapPlugin {
@@ -54,18 +52,18 @@ public interface ILdapCertMapper extends ILdapPlugin {
public Vector getInstanceParams();
/**
- * maps a certificate to a LDAP entry.
- * returns dn of the mapped LDAP entry.
+ * maps a certificate to a LDAP entry. returns dn of the mapped LDAP entry.
+ *
* @param conn the LDAP connection
* @param cert the certificate to map
* @param checkForCert whether to check for the presence of the cert
- * @exception ELdapException Failed to map.
- * @return LdapCertMapResult indicates whether a mapping was successful
- * and whether a certificate was found if checkForCert was true.
- * If checkForCert was not set the hasCert method in LdapCertMapResult
- * should be ignored.
+ * @exception ELdapException Failed to map.
+ * @return LdapCertMapResult indicates whether a mapping was successful and
+ * whether a certificate was found if checkForCert was true. If
+ * checkForCert was not set the hasCert method in LdapCertMapResult
+ * should be ignored.
*/
- public LdapCertMapResult map(LDAPConnection conn,
- X509Certificate cert, boolean checkForCert)
- throws ELdapException;
+ public LdapCertMapResult map(LDAPConnection conn,
+ X509Certificate cert, boolean checkForCert)
+ throws ELdapException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/publish/ILdapCrlMapper.java b/pki/base/common/src/com/netscape/certsrv/publish/ILdapCrlMapper.java
index a15ea0ab..51e86743 100644
--- a/pki/base/common/src/com/netscape/certsrv/publish/ILdapCrlMapper.java
+++ b/pki/base/common/src/com/netscape/certsrv/publish/ILdapCrlMapper.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.publish;
-
import netscape.ldap.LDAPConnection;
import netscape.security.x509.X509CRLImpl;
@@ -25,36 +24,36 @@ import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.ldap.ELdapException;
-
-/**
- * Interface for mapping a CRL to a LDAP entry.
- *
+/**
+ * Interface for mapping a CRL to a LDAP entry.
+ *
* @version $Revision$ $Date$
*/
public interface ILdapCrlMapper {
/**
- * maps a crl to a LDAP entry.
- * returns dn of the mapped LDAP entry.
+ * maps a crl to a LDAP entry. returns dn of the mapped LDAP entry.
+ *
* @param conn the LDAP connection
* @param crl the CRL to map
* @param checkForCrl whether to check for the presence of the CRL
- * @exception ELdapException Failed to map CRL to entry.
- * @return LdapCertMapResult indicates whether a mapping was successful
- * and whether a certificate was found if checkForCert was true.
- * If checkForCert was not set the hasCert method in LdapCertMapResult
- * should be ignored.
+ * @exception ELdapException Failed to map CRL to entry.
+ * @return LdapCertMapResult indicates whether a mapping was successful and
+ * whether a certificate was found if checkForCert was true. If
+ * checkForCert was not set the hasCert method in LdapCertMapResult
+ * should be ignored.
*/
- public LdapCertMapResult
- map(LDAPConnection conn, X509CRLImpl crl, boolean checkForCrl)
- throws ELdapException;
+ public LdapCertMapResult
+ map(LDAPConnection conn, X509CRLImpl crl, boolean checkForCrl)
+ throws ELdapException;
/**
* initialize from config store.
+ *
* @param config the configuration store to initialize from.
* @exception ELdapException Initialization failed due to Ldap error.
* @exception EBaseException Initialization failed.
*/
public void init(IConfigStore config)
- throws ELdapException, EBaseException;
+ throws ELdapException, EBaseException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/publish/ILdapExpression.java b/pki/base/common/src/com/netscape/certsrv/publish/ILdapExpression.java
index 26360fe8..4537636c 100644
--- a/pki/base/common/src/com/netscape/certsrv/publish/ILdapExpression.java
+++ b/pki/base/common/src/com/netscape/certsrv/publish/ILdapExpression.java
@@ -17,15 +17,13 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.publish;
-
import com.netscape.certsrv.base.SessionContext;
import com.netscape.certsrv.ldap.ELdapException;
import com.netscape.certsrv.request.IRequest;
-
/**
* Interface for a Ldap predicate expression.
- *
+ *
* @version $Revision$, $Date$
*/
public interface ILdapExpression {
@@ -44,28 +42,28 @@ public interface ILdapExpression {
/**
* Evaluate the Expression.
- *
- * @param sc The SessionContext on which we are applying the condition.
- * @return The return value.
- * @exception ELdapExeption Failed to evaluate expression.
+ *
+ * @param sc The SessionContext on which we are applying the condition.
+ * @return The return value.
+ * @exception ELdapExeption Failed to evaluate expression.
*/
boolean evaluate(SessionContext sc)
- throws ELdapException;
+ throws ELdapException;
/**
* Evaluate the Expression.
- *
- * @param req The PKIRequest on which we are applying the condition.
- * @return The return value.
- * @exception ELdapExeption Failed to evaluate expression.
+ *
+ * @param req The PKIRequest on which we are applying the condition.
+ * @return The return value.
+ * @exception ELdapExeption Failed to evaluate expression.
*/
boolean evaluate(IRequest req)
- throws ELdapException;
+ throws ELdapException;
/**
* Convert to a string.
+ *
* @return String representation of expression.
*/
public String toString();
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/publish/ILdapMapper.java b/pki/base/common/src/com/netscape/certsrv/publish/ILdapMapper.java
index c4afd039..edd0ae87 100644
--- a/pki/base/common/src/com/netscape/certsrv/publish/ILdapMapper.java
+++ b/pki/base/common/src/com/netscape/certsrv/publish/ILdapMapper.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.publish;
-
import java.util.Vector;
import netscape.ldap.LDAPConnection;
@@ -25,10 +24,9 @@ import netscape.ldap.LDAPConnection;
import com.netscape.certsrv.ldap.ELdapException;
import com.netscape.certsrv.request.IRequest;
-
-/**
- * Interface for mapping a X509 certificate to a LDAP entry.
- *
+/**
+ * Interface for mapping a X509 certificate to a LDAP entry.
+ *
* @version $Revision$ $Date$
*/
public interface ILdapMapper extends ILdapPlugin {
@@ -54,28 +52,27 @@ public interface ILdapMapper extends ILdapPlugin {
public Vector<String> getInstanceParams();
/**
- * maps a certificate to a LDAP entry.
- * returns dn of the mapped LDAP entry.
+ * maps a certificate to a LDAP entry. returns dn of the mapped LDAP entry.
+ *
* @param conn the LDAP connection
* @param obj the object to map
* @return dn indicates whether a mapping was successful
* @exception ELdapException Map operation failed.
*/
- public String
- map(LDAPConnection conn, Object obj)
- throws ELdapException;
+ public String
+ map(LDAPConnection conn, Object obj)
+ throws ELdapException;
/**
- * maps a certificate to a LDAP entry.
- * returns dn of the mapped LDAP entry.
+ * maps a certificate to a LDAP entry. returns dn of the mapped LDAP entry.
+ *
* @param conn the LDAP connection
- * @param r the request to map
- * @param obj the object to map
+ * @param r the request to map
+ * @param obj the object to map
* @return dn indicates whether a mapping was successful
* @exception ELdapException Map operation failed.
*/
- public String
- map(LDAPConnection conn, IRequest r, Object obj)
- throws ELdapException;
+ public String
+ map(LDAPConnection conn, IRequest r, Object obj)
+ throws ELdapException;
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/publish/ILdapPlugin.java b/pki/base/common/src/com/netscape/certsrv/publish/ILdapPlugin.java
index b73b5ae2..b0a9fe73 100644
--- a/pki/base/common/src/com/netscape/certsrv/publish/ILdapPlugin.java
+++ b/pki/base/common/src/com/netscape/certsrv/publish/ILdapPlugin.java
@@ -17,27 +17,26 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.publish;
-
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.ldap.ELdapException;
-
-/**
+/**
* Interface for any Ldap plugin.
- *
+ *
* @version $Revision$ $Date$
*/
public interface ILdapPlugin {
/**
* Initialize from config store.
+ *
* @param config the configuration store to initialize from.
* @exception ELdapException initialization failed due to Ldap error.
* @exception EBaseException initialization failed.
*/
public void init(IConfigStore config)
- throws EBaseException, ELdapException;
+ throws EBaseException, ELdapException;
/**
* Return config store.
diff --git a/pki/base/common/src/com/netscape/certsrv/publish/ILdapPluginImpl.java b/pki/base/common/src/com/netscape/certsrv/publish/ILdapPluginImpl.java
index e84b62fc..db52a910 100644
--- a/pki/base/common/src/com/netscape/certsrv/publish/ILdapPluginImpl.java
+++ b/pki/base/common/src/com/netscape/certsrv/publish/ILdapPluginImpl.java
@@ -17,37 +17,37 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.publish;
-
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.base.IPluginImpl;
import com.netscape.certsrv.base.ISubsystem;
import com.netscape.certsrv.ldap.ELdapException;
-
-/**
+/**
* Interface for any ldap plugin. Plugin implementation is defined here.
- *
+ *
* @version $Revision$ $Date$
*/
public interface ILdapPluginImpl extends IPluginImpl {
/**
* initialize from config store.
+ *
* @param config the configuration store to initialize from.
* @exception ELdapException initializtion failed due to Ldap error.
* @exception EBaseException initialization failed.
*/
public void init(ISubsystem sys, IConfigStore config)
- throws EBaseException, ELdapException;
+ throws EBaseException, ELdapException;
/**
* initialize from config store and Isubsystem.
+ *
* @param config the configuration store to initialize from.
* @exception ELdapException initializtion failed due to Ldap error.
* @exception EBaseException initialization failed.
*/
public void init(IConfigStore config)
- throws EBaseException, ELdapException;
+ throws EBaseException, ELdapException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/publish/ILdapPublishModule.java b/pki/base/common/src/com/netscape/certsrv/publish/ILdapPublishModule.java
index 001d472b..f31b3c60 100644
--- a/pki/base/common/src/com/netscape/certsrv/publish/ILdapPublishModule.java
+++ b/pki/base/common/src/com/netscape/certsrv/publish/ILdapPublishModule.java
@@ -17,14 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.publish;
-
import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.IRequestListener;
-
-/**
- * Handles requests to perform Ldap publishing.
- *
+/**
+ * Handles requests to perform Ldap publishing.
+ *
* @version $Revision$ $Date$
*/
public interface ILdapPublishModule extends IRequestListener {
@@ -32,14 +30,14 @@ public interface ILdapPublishModule extends IRequestListener {
/**
* initialize ldap publishing module with config store
*/
- // public void init(ICertAuthority owner, IConfigStore config)
- // throws EBaseException, ELdapException;
+ // public void init(ICertAuthority owner, IConfigStore config)
+ // throws EBaseException, ELdapException;
/**
- * Accepts completed requests from an authority and
- * performs ldap publishing.
- * @param request The publishing request.
+ * Accepts completed requests from an authority and performs ldap
+ * publishing.
+ *
+ * @param request The publishing request.
*/
public void accept(IRequest request);
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/publish/ILdapPublisher.java b/pki/base/common/src/com/netscape/certsrv/publish/ILdapPublisher.java
index 5a1197dc..5d6b8ca9 100644
--- a/pki/base/common/src/com/netscape/certsrv/publish/ILdapPublisher.java
+++ b/pki/base/common/src/com/netscape/certsrv/publish/ILdapPublisher.java
@@ -17,17 +17,15 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.publish;
-
import java.util.Vector;
import netscape.ldap.LDAPConnection;
import com.netscape.certsrv.ldap.ELdapException;
-
-/**
- * Interface for publishing certificate or crl to database store.
- *
+/**
+ * Interface for publishing certificate or crl to database store.
+ *
* @version $Revision$ $Date$
*/
public interface ILdapPublisher extends ILdapPlugin {
@@ -58,30 +56,25 @@ public interface ILdapPublisher extends ILdapPlugin {
/**
* Publish an object.
*
- * @param conn a Ldap connection
- * (null for non-LDAP publishing)
- * @param dn dn of the ldap entry to publish cert
- * (null for non-LDAP publishing)
- * @param object object to publish
- * (java.security.cert.X509Certificate or,
- * java.security.cert.X509CRL)
+ * @param conn a Ldap connection (null for non-LDAP publishing)
+ * @param dn dn of the ldap entry to publish cert (null for non-LDAP
+ * publishing)
+ * @param object object to publish (java.security.cert.X509Certificate or,
+ * java.security.cert.X509CRL)
* @exception ELdapException publish failed.
*/
public void publish(LDAPConnection conn, String dn, Object object)
- throws ELdapException;
+ throws ELdapException;
/**
* Unpublish an object.
- *
- * @param conn the Ldap connection
- * (null for non-LDAP publishing)
- * @param dn dn of the ldap entry to unpublish cert
- * (null for non-LDAP publishing)
- * @param object object to unpublish
- * (java.security.cert.X509Certificate)
+ *
+ * @param conn the Ldap connection (null for non-LDAP publishing)
+ * @param dn dn of the ldap entry to unpublish cert (null for non-LDAP
+ * publishing)
+ * @param object object to unpublish (java.security.cert.X509Certificate)
* @exception ELdapException unpublish failed.
*/
public void unpublish(LDAPConnection conn, String dn, Object object)
- throws ELdapException;
+ throws ELdapException;
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/publish/ILdapRule.java b/pki/base/common/src/com/netscape/certsrv/publish/ILdapRule.java
index 4c5699b1..7bf19b07 100644
--- a/pki/base/common/src/com/netscape/certsrv/publish/ILdapRule.java
+++ b/pki/base/common/src/com/netscape/certsrv/publish/ILdapRule.java
@@ -17,16 +17,14 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.publish;
-
import java.util.Vector;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
-
-/**
+/**
* Interface for publishing rule which associates a Publisher with a Mapper.
- *
+ *
* @version $Revision$ $Date$
*/
public interface ILdapRule extends ILdapPlugin {
@@ -36,10 +34,11 @@ public interface ILdapRule extends ILdapPlugin {
/**
* Initialize the plugin.
+ *
* @exception EBaseException Initialization failed.
*/
public void init(IPublisherProcessor processor, IConfigStore
- config) throws EBaseException;
+ config) throws EBaseException;
/**
* Returns the implementation name.
diff --git a/pki/base/common/src/com/netscape/certsrv/publish/IPublishRuleSet.java b/pki/base/common/src/com/netscape/certsrv/publish/IPublishRuleSet.java
index 6ff997a1..e6cd3756 100644
--- a/pki/base/common/src/com/netscape/certsrv/publish/IPublishRuleSet.java
+++ b/pki/base/common/src/com/netscape/certsrv/publish/IPublishRuleSet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.publish;
-
import java.util.Enumeration;
import netscape.ldap.LDAPConnection;
@@ -28,22 +27,20 @@ import com.netscape.certsrv.base.ISubsystem;
import com.netscape.certsrv.ldap.ELdapException;
import com.netscape.certsrv.request.IRequest;
-
/**
* Represents a set of publishing rules. Publishing rules are ordered from
- * lowest priority to highest priority. The priority assignment for publishing
- * rules is not enforced by this interface. Various implementation may
- * use different mechanisms such as a linear ordering of publishing rules
- * in a configuration file or explicit assignment of priority levels ..etc.
- * The publishing rule initialization needs to deal with reading the
- * publishing rules, sorting them in increasing order of priority and
- * presenting an ordered vector of publishing rules via the IPublishRuleSet
- * interface.
- * When a request comes, the predicates of the publishing rules will be
- * checked in the order to find the first matched publishing rule as the
- * mapping rule to (un)publish the object.
+ * lowest priority to highest priority. The priority assignment for publishing
+ * rules is not enforced by this interface. Various implementation may use
+ * different mechanisms such as a linear ordering of publishing rules in a
+ * configuration file or explicit assignment of priority levels ..etc. The
+ * publishing rule initialization needs to deal with reading the publishing
+ * rules, sorting them in increasing order of priority and presenting an ordered
+ * vector of publishing rules via the IPublishRuleSet interface. When a request
+ * comes, the predicates of the publishing rules will be checked in the order to
+ * find the first matched publishing rule as the mapping rule to (un)publish the
+ * object.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IPublishRuleSet {
@@ -52,7 +49,7 @@ public interface IPublishRuleSet {
/**
* Returns the name of the publishing rule set.
* <P>
- *
+ *
* @return The name of the publishing rule set.
*/
String getName();
@@ -60,6 +57,7 @@ public interface IPublishRuleSet {
/**
* Returns the no of publishing rules in a set.
* <P>
+ *
* @return the no of publishing rules.
*/
int count();
@@ -67,33 +65,34 @@ public interface IPublishRuleSet {
/**
* Add a publishing rule
* <P>
- *
- * @param aliasName The name of the publishing rule to be added.
- * @param rule rule The publishing rule to be added.
+ *
+ * @param aliasName The name of the publishing rule to be added.
+ * @param rule rule The publishing rule to be added.
*/
void addRule(String aliasName, ILdapRule rule);
/**
* Removes a publishing rule identified by the given name.
- *
- * @param ruleName The name of the publishing rule to be removed.
+ *
+ * @param ruleName The name of the publishing rule to be removed.
*/
void removeRule(String ruleName);
/**
* Get the publishing rule identified by a given name.
* <P>
- *
- * @param ruleName The name of the publishing rule to be return.
- * @return The publishing rule identified by the given name or null if none exists.
+ *
+ * @param ruleName The name of the publishing rule to be return.
+ * @return The publishing rule identified by the given name or null if none
+ * exists.
*/
ILdapRule getRule(String ruleName);
/**
* Get the publishing rule identified by a corresponding request.
* <P>
- *
- * @param req The request from which rule will be identified.
+ *
+ * @param req The request from which rule will be identified.
* @return The publishing rule or null if none exists.
*/
ILdapRule getRule(IRequest req);
@@ -101,24 +100,22 @@ public interface IPublishRuleSet {
/**
* Get an enumeration of publishing rules.
* <P>
- *
+ *
* @return An enumeration of publishing rules.
*/
Enumeration getRules();
/**
- * Apply publishing rules on a request.
- * The predicates of the publishing rules will be checked in the order
- * to find the first matched publishing rule.
- * Use the mapper to find the dn of the LDAP entry and use the publisher
- * to publish the object in the request.
+ * Apply publishing rules on a request. The predicates of the publishing
+ * rules will be checked in the order to find the first matched publishing
+ * rule. Use the mapper to find the dn of the LDAP entry and use the
+ * publisher to publish the object in the request.
* <P>
- *
- * @param conn The Ldap connection
- * @param req The request to apply policies on.
- * @exception ELdapException publish failed due to Ldap error.
+ *
+ * @param conn The Ldap connection
+ * @param req The request to apply policies on.
+ * @exception ELdapException publish failed due to Ldap error.
*/
public void publish(LDAPConnection conn, IRequest req)
- throws ELdapException;
+ throws ELdapException;
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/publish/IPublisherProcessor.java b/pki/base/common/src/com/netscape/certsrv/publish/IPublisherProcessor.java
index 1da2f346..bc908296 100644
--- a/pki/base/common/src/com/netscape/certsrv/publish/IPublisherProcessor.java
+++ b/pki/base/common/src/com/netscape/certsrv/publish/IPublisherProcessor.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.publish;
-
import java.math.BigInteger;
import java.security.cert.X509CRL;
import java.security.cert.X509Certificate;
@@ -32,11 +31,10 @@ import com.netscape.certsrv.ldap.ELdapException;
import com.netscape.certsrv.ldap.ILdapConnModule;
import com.netscape.certsrv.request.IRequest;
-
/**
- * Controls the publishing process from the top level. Maintains
- * a collection of Publishers , Mappers, and Publish Rules.
- *
+ * Controls the publishing process from the top level. Maintains a collection of
+ * Publishers , Mappers, and Publish Rules.
+ *
* @version $Revision$ $Date$
*/
@@ -64,63 +62,66 @@ public interface IPublisherProcessor extends ISubsystem {
public static final String PROP_TYPE = "type";
/**
- *
+ *
* Returns Hashtable of rule plugins.
*/
public Hashtable<String, RulePlugin> getRulePlugins();
/**
- *
- * Returns Hashtable of rule instances.
+ *
+ * Returns Hashtable of rule instances.
*/
public Hashtable<String, ILdapRule> getRuleInsts();
/**
- *
+ *
* Returns Hashtable of mapper plugins.
*/
public Hashtable<String, MapperPlugin> getMapperPlugins();
/**
- *
+ *
* Returns Hashtable of publisher plugins.
*/
public Hashtable<String, PublisherPlugin> getPublisherPlugins();
/**
- *
+ *
* Returns Hashtable of rule mapper instances.
*/
public Hashtable<String, MapperProxy> getMapperInsts();
/**
- *
+ *
* Returns Hashtable of rule publisher instances.
*/
public Hashtable<String, PublisherProxy> getPublisherInsts();
/**
- *
+ *
* Returns list of rules based on publishing type.
+ *
* @param publishingType Type for which to retrieve rule list.
*/
public Enumeration<ILdapRule> getRules(String publishingType);
/**
- *
+ *
* Returns list of rules based on publishing type and publishing request.
+ *
* @param publishingType Type for which to retrieve rule list.
- * @param req Corresponding publish request.
+ * @param req Corresponding publish request.
*/
public Enumeration<ILdapRule> getRules(String publishingType, IRequest req);
/**
- *
+ *
* Returns mapper initial default parameters.
+ *
* @param implName name of MapperPlugin.
*/
@@ -128,8 +129,9 @@ public interface IPublisherProcessor extends ISubsystem {
ELdapException;
/**
- *
- * Returns mapper current instance parameters.
+ *
+ * Returns mapper current instance parameters.
+ *
* @param insName name of MapperProxy.
* @exception ELdapException failed due to Ldap error.
*/
@@ -138,8 +140,9 @@ public interface IPublisherProcessor extends ISubsystem {
ELdapException;
/**
- *
+ *
* Returns publisher initial default parameters.
+ *
* @param implName name of PublisherPlugin.
* @exception ELdapException failed due to Ldap error.
*/
@@ -147,8 +150,9 @@ public interface IPublisherProcessor extends ISubsystem {
ELdapException;
/**
- *
+ *
* Returns true if MapperInstance is enabled.
+ *
* @param insName name of MapperProxy.
* @return true if enabled. false if disabled.
*/
@@ -156,48 +160,54 @@ public interface IPublisherProcessor extends ISubsystem {
public boolean isMapperInstanceEnable(String insName);
/**
- *
+ *
* Returns ILdapMapper instance that is currently active.
+ *
* @param insName name of MapperProxy.
* @return instance of ILdapMapper.
- */
+ */
public ILdapMapper getActiveMapperInstance(String insName);
/**
- *
+ *
* Returns ILdapMapper instance based on name of MapperProxy.
+ *
* @param insName name of MapperProxy.
* @return instance of ILdapMapper.
*/
public ILdapMapper getMapperInstance(String insName);
/**
- *
+ *
* Returns true publisher instance is currently enabled.
+ *
* @param insName name of PublisherProxy.
* @return true if enabled.
*/
public boolean isPublisherInstanceEnable(String insName);
/**
- *
+ *
* Returns ILdapPublisher instance that is currently active.
+ *
* @param insName name of PublisherProxy.
* @return instance of ILdapPublisher.
*/
public ILdapPublisher getActivePublisherInstance(String insName);
/**
- *
+ *
* Returns ILdapPublisher instance.
+ *
* @param insName name of PublisherProxy.
* @return instance of ILdapPublisher.
*/
public ILdapPublisher getPublisherInstance(String insName);
/**
- *
+ *
* Returns Vector of PublisherIntance's current instance parameters.
+ *
* @param insName name of PublisherProxy.
* @return Vector of current instance parameters.
*/
@@ -205,8 +215,9 @@ public interface IPublisherProcessor extends ISubsystem {
ELdapException;
/**
- *
+ *
* Returns Vector of RulePlugin's initial default parameters.
+ *
* @param implName name of RulePlugin.
* @return Vector of initial default parameters.
* @exception ELdapException failed due to Ldap error.
@@ -215,8 +226,9 @@ public interface IPublisherProcessor extends ISubsystem {
ELdapException;
/**
- *
+ *
* Returns Vector of RulePlugin's current instance parameters.
+ *
* @param implName name of RulePlugin.
* @return Vector of current instance parameters.
* @exception ELdapException failed due to Ldap error.
@@ -225,8 +237,9 @@ public interface IPublisherProcessor extends ISubsystem {
ELdapException;
/**
- * Set published flag - true when published, false when unpublished.
- * Not exist means not published.
+ * Set published flag - true when published, false when unpublished. Not
+ * exist means not published.
+ *
* @param serialNo serial number of publishable object.
* @param published true for published, false for not.
*/
@@ -234,102 +247,111 @@ public interface IPublisherProcessor extends ISubsystem {
/**
* Publish ca cert, UpdateDir.java, jobs, request listeners
+ *
* @param cert X509 certificate to be published.
* @exception ELdapException publish failed due to Ldap error.
*/
public void publishCACert(X509Certificate cert)
- throws ELdapException;
+ throws ELdapException;
/**
- * This function is never called. CMS does not unpublish
- * CA certificate.
+ * This function is never called. CMS does not unpublish CA certificate.
*/
public void unpublishCACert(X509Certificate cert)
- throws ELdapException;
+ throws ELdapException;
/**
- * Publishs regular user certificate based on the criteria
- * set in the request.
+ * Publishs regular user certificate based on the criteria set in the
+ * request.
+ *
* @param cert X509 certificate to be published.
- * @param req request which provides the criteria
+ * @param req request which provides the criteria
* @exception ELdapException publish failed due to Ldap error.
*/
public void publishCert(X509Certificate cert, IRequest req)
- throws ELdapException;
+ throws ELdapException;
/**
- * Unpublish user certificate. This is used by
- * UnpublishExpiredJob.
+ * Unpublish user certificate. This is used by UnpublishExpiredJob.
+ *
* @param cert X509 certificate to be unpublished.
- * @param req request which provides the criteria
+ * @param req request which provides the criteria
* @exception ELdapException unpublish failed due to Ldap error.
*/
public void unpublishCert(X509Certificate cert, IRequest req)
- throws ELdapException;
+ throws ELdapException;
/**
- * publishes a crl by mapping the issuer name in the crl to an entry
- * and publishing it there. entry must be a certificate authority.
- * Note that this is used by cmsgateway/cert/UpdateDir.java
+ * publishes a crl by mapping the issuer name in the crl to an entry and
+ * publishing it there. entry must be a certificate authority. Note that
+ * this is used by cmsgateway/cert/UpdateDir.java
+ *
* @param crl Certificate Revocation List
* @param crlIssuingPointId name of the issuing point.
- * @exception ELdapException publish failed due to Ldap error.
+ * @exception ELdapException publish failed due to Ldap error.
*/
- public void publishCRL(X509CRLImpl crl,String crlIssuingPointId)
- throws ELdapException;
+ public void publishCRL(X509CRLImpl crl, String crlIssuingPointId)
+ throws ELdapException;
/**
- * publishes a crl by mapping the issuer name in the crl to an entry
- * and publishing it there. entry must be a certificate authority.
- * @param dn Distinguished name to publish.
+ * publishes a crl by mapping the issuer name in the crl to an entry and
+ * publishing it there. entry must be a certificate authority.
+ *
+ * @param dn Distinguished name to publish.
* @param crl Certificate Revocation List
* @exception ELdapException publish failed due to Ldap error.
*/
- public void publishCRL(String dn, X509CRL crl)
- throws ELdapException;
+ public void publishCRL(String dn, X509CRL crl)
+ throws ELdapException;
/**
- *
+ *
* Return true if Ldap is enabled.
+ *
* @return true if Ldap is enabled,otherwise false.
*/
public boolean ldapEnabled();
/**
- *
+ *
* Return true of PublisherProcessor is enabled.
+ *
* @return true if is enabled, otherwise false.
- *
+ *
*/
public boolean enabled();
/**
- *
- * Return Authority for which this Processor operates.
+ *
+ * Return Authority for which this Processor operates.
+ *
* @return Authority.
*/
public ISubsystem getAuthority();
/**
- *
+ *
* Perform logging function for this Processor.
- * @param level Log level to be used for this message
- * @param msg Message to be logged.
+ *
+ * @param level Log level to be used for this message
+ * @param msg Message to be logged.
*/
public void log(int level, String msg);
/**
- *
+ *
* Returns LdapConnModule belonging to this Processor.
+ *
* @return LdapConnModule.
*/
public ILdapConnModule getLdapConnModule();
/**
* Sets the LdapConnModule belonging to this Processor.
+ *
* @param m ILdapConnModule.
*/
public void setLdapConnModule(ILdapConnModule m);
diff --git a/pki/base/common/src/com/netscape/certsrv/publish/IXcertPublisherProcessor.java b/pki/base/common/src/com/netscape/certsrv/publish/IXcertPublisherProcessor.java
index ce72ed8a..38842bb9 100644
--- a/pki/base/common/src/com/netscape/certsrv/publish/IXcertPublisherProcessor.java
+++ b/pki/base/common/src/com/netscape/certsrv/publish/IXcertPublisherProcessor.java
@@ -17,23 +17,21 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.publish;
-
import com.netscape.certsrv.ldap.ELdapException;
-
/**
- * Interface for a publisher that has the capability of publishing
- * cross certs
- *
+ * Interface for a publisher that has the capability of publishing cross certs
+ *
* @version $Revision$, $Date$
*/
public interface IXcertPublisherProcessor extends IPublisherProcessor {
/**
* Publish crossCertificatePair.
+ *
* @param pair Byte array representing cert pair.
* @exception EldapException publish failed due to Ldap error.
*/
public void publishXCertPair(byte[] pair)
- throws ELdapException;
+ throws ELdapException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/publish/LdapCertMapResult.java b/pki/base/common/src/com/netscape/certsrv/publish/LdapCertMapResult.java
index 559cd8c0..900a9854 100644
--- a/pki/base/common/src/com/netscape/certsrv/publish/LdapCertMapResult.java
+++ b/pki/base/common/src/com/netscape/certsrv/publish/LdapCertMapResult.java
@@ -17,14 +17,11 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.publish;
-
-
-
-/**
- * Class that represents the result of a Ldap Mapping operation.
- * certificate map result:
- * Represented by a mapped entry as a DN and whether entry has the certificate.
- *
+/**
+ * Class that represents the result of a Ldap Mapping operation. certificate map
+ * result: Represented by a mapped entry as a DN and whether entry has the
+ * certificate.
+ *
* @version $Revision$ $Date$
*/
public class LdapCertMapResult {
@@ -38,9 +35,10 @@ public class LdapCertMapResult {
mDn = dn;
mHasCert = hasCert;
}
-
+
/**
* Gets DN from the result.
+ *
* @return Distinguished Name.
*/
public String getDn() {
@@ -49,6 +47,7 @@ public class LdapCertMapResult {
/**
* Gets whether the ldap entry had a certificate from result.
+ *
* @return true if cert is present, false otherwise.
*/
public boolean hasCert() {
diff --git a/pki/base/common/src/com/netscape/certsrv/publish/MapperPlugin.java b/pki/base/common/src/com/netscape/certsrv/publish/MapperPlugin.java
index 282db3cd..b193e1b5 100644
--- a/pki/base/common/src/com/netscape/certsrv/publish/MapperPlugin.java
+++ b/pki/base/common/src/com/netscape/certsrv/publish/MapperPlugin.java
@@ -17,25 +17,23 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.publish;
-
import com.netscape.certsrv.base.Plugin;
-
/**
* This class represents a registered mapper plugin.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class MapperPlugin extends Plugin {
/**
* Constructs a MapperPlugin based on a name and a path.
+ *
* @param id Name of plugin.
* @param path Classpath of plugin.
*/
- public MapperPlugin (String id, String path) {
+ public MapperPlugin(String id, String path) {
super(id, path);
}
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/publish/MapperProxy.java b/pki/base/common/src/com/netscape/certsrv/publish/MapperProxy.java
index bd8ea741..95dc98d9 100644
--- a/pki/base/common/src/com/netscape/certsrv/publish/MapperProxy.java
+++ b/pki/base/common/src/com/netscape/certsrv/publish/MapperProxy.java
@@ -17,13 +17,10 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.publish;
-
-
-
/**
- *
- * Class representing a LdapMapper.
- *
+ *
+ * Class representing a LdapMapper.
+ *
* @version $Revision$ $Date$
*/
@@ -32,8 +29,9 @@ public class MapperProxy {
private ILdapMapper mMapper;
/**
- *
+ *
* Contructs MapperProxy .
+ *
* @param enable Enabled or not.
* @param mapper Corresponding ILdapMapper object.
*/
@@ -43,8 +41,9 @@ public class MapperProxy {
}
/**
- *
+ *
* Returns if enabled.
+ *
* @return true if enabled, otherwise false.
*/
public boolean isEnable() {
@@ -52,8 +51,9 @@ public class MapperProxy {
}
/**
- *
+ *
* Returns ILdapMapper object.
+ *
* @return Intance of ILdapMapper object.
*/
public ILdapMapper getMapper() {
diff --git a/pki/base/common/src/com/netscape/certsrv/publish/PublisherPlugin.java b/pki/base/common/src/com/netscape/certsrv/publish/PublisherPlugin.java
index d6864326..5a163b80 100644
--- a/pki/base/common/src/com/netscape/certsrv/publish/PublisherPlugin.java
+++ b/pki/base/common/src/com/netscape/certsrv/publish/PublisherPlugin.java
@@ -17,26 +17,24 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.publish;
-
import com.netscape.certsrv.base.Plugin;
-
/**
* This class represents a registered publisher plugin.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class PublisherPlugin extends Plugin {
/**
- *
- * Constructs a PublisherPlugin based on name and classpath.
- * @param id name of plugin.
- * @param path Classpath of plugin.
+ *
+ * Constructs a PublisherPlugin based on name and classpath.
+ *
+ * @param id name of plugin.
+ * @param path Classpath of plugin.
*/
- public PublisherPlugin (String id, String path) {
+ public PublisherPlugin(String id, String path) {
super(id, path);
}
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/publish/PublisherProxy.java b/pki/base/common/src/com/netscape/certsrv/publish/PublisherProxy.java
index 06e08c31..5a496d1d 100644
--- a/pki/base/common/src/com/netscape/certsrv/publish/PublisherProxy.java
+++ b/pki/base/common/src/com/netscape/certsrv/publish/PublisherProxy.java
@@ -17,24 +17,22 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.publish;
-
-
-
/**
- *
+ *
* Class representing a proxy for a ILdapPublisher.
- *
+ *
* @version $Revision$ $Date$
*/
-
public class PublisherProxy {
private boolean mEnable;
private ILdapPublisher mPublisher;
/**
- *
- * Constructs a PublisherProxy based on a ILdapPublisher object and enabled boolean.
+ *
+ * Constructs a PublisherProxy based on a ILdapPublisher object and enabled
+ * boolean.
+ *
* @param enable Proxy is enabled or not.
* @param publisher Corresponding ILdapPublisher object.
*/
@@ -45,6 +43,7 @@ public class PublisherProxy {
/**
* Return if enabled or not.
+ *
* @return true if enabled, otherwise false.
*/
public boolean isEnable() {
@@ -53,6 +52,7 @@ public class PublisherProxy {
/**
* Return ILdapPublisher object.
+ *
* @return Instance of ILdapPublisher.
*/
public ILdapPublisher getPublisher() {
diff --git a/pki/base/common/src/com/netscape/certsrv/publish/RulePlugin.java b/pki/base/common/src/com/netscape/certsrv/publish/RulePlugin.java
index 8e515726..b37a24d5 100644
--- a/pki/base/common/src/com/netscape/certsrv/publish/RulePlugin.java
+++ b/pki/base/common/src/com/netscape/certsrv/publish/RulePlugin.java
@@ -17,25 +17,24 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.publish;
-
import com.netscape.certsrv.base.Plugin;
-
/**
* This class represents a registered Publishing Rule plugin.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class RulePlugin extends Plugin {
/**
- *
+ *
* Constructs a RulePlugin based on name and classpath.
+ *
* @param id name of RulePlugin.
* @param path Classpath of RulePlugin.
*/
- public RulePlugin (String id, String path) {
+ public RulePlugin(String id, String path) {
super(id, path);
}
}
diff --git a/pki/base/common/src/com/netscape/certsrv/ra/IRAService.java b/pki/base/common/src/com/netscape/certsrv/ra/IRAService.java
index 92ccd558..4bab4745 100644
--- a/pki/base/common/src/com/netscape/certsrv/ra/IRAService.java
+++ b/pki/base/common/src/com/netscape/certsrv/ra/IRAService.java
@@ -17,47 +17,45 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.ra;
-
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.connector.IConnector;
import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.IService;
-
/**
* An interface representing a RA request services.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
-public interface IRAService extends IService {
+public interface IRAService extends IService {
/**
* Services request.
- *
+ *
* @param req request data
*/
public boolean serviceRequest(IRequest req);
/**
* Services profile request.
- *
+ *
* @param request profile enrollment request information
* @exception EBaseException failed to service profile enrollment request
*/
public void serviceProfileRequest(IRequest request)
- throws EBaseException;
+ throws EBaseException;
/**
* Returns CA connector.
- *
+ *
* @return CA connector
*/
public IConnector getCAConnector();
/**
* Returns KRA connector.
- *
+ *
* @return KRA connector
*/
public IConnector getKRAConnector();
diff --git a/pki/base/common/src/com/netscape/certsrv/ra/IRegistrationAuthority.java b/pki/base/common/src/com/netscape/certsrv/ra/IRegistrationAuthority.java
index 3ab3a084..95154af2 100644
--- a/pki/base/common/src/com/netscape/certsrv/ra/IRegistrationAuthority.java
+++ b/pki/base/common/src/com/netscape/certsrv/ra/IRegistrationAuthority.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.ra;
-
import java.util.Enumeration;
import netscape.security.x509.X500Name;
@@ -29,12 +28,11 @@ import com.netscape.certsrv.publish.IPublisherProcessor;
import com.netscape.certsrv.request.IRequestListener;
import com.netscape.certsrv.request.IRequestQueue;
-
/**
- * An interface represents a Registration Authority that is
- * responsible for certificate enrollment operations.
+ * An interface represents a Registration Authority that is responsible for
+ * certificate enrollment operations.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IRegistrationAuthority extends ISubsystem {
@@ -44,8 +42,8 @@ public interface IRegistrationAuthority extends ISubsystem {
public static final String PROP_REGISTRATION = "Registration";
public static final String PROP_GATEWAY = "gateway";
public static final String PROP_NICKNAME = "certNickname";
- //public final static String PROP_PUBLISH_SUBSTORE = "publish";
- //public final static String PROP_LDAP_PUBLISH_SUBSTORE = "ldappublish";
+ // public final static String PROP_PUBLISH_SUBSTORE = "publish";
+ // public final static String PROP_LDAP_PUBLISH_SUBSTORE = "ldappublish";
public final static String PROP_CONNECTOR = "connector";
public final static String PROP_NEW_NICKNAME = "newNickname";
@@ -57,63 +55,63 @@ public interface IRegistrationAuthority extends ISubsystem {
/**
* Retrieves the request queue of this registration authority.
- *
+ *
* @return RA's request queue
*/
public IRequestQueue getRequestQueue();
/**
* Retrieves the publishing processor of this registration authority.
- *
+ *
* @return RA's publishing processor
*/
public IPublisherProcessor getPublisherProcessor();
/**
* Retrieves the policy processor of this registration authority.
- *
+ *
* @return RA's policy processor
*/
public IPolicyProcessor getPolicyProcessor();
/**
* Retrieves the RA certificate.
- *
+ *
* @return the RA certificate
*/
public org.mozilla.jss.crypto.X509Certificate getRACert();
/**
* Retrieves the request in queue listener.
- *
+ *
* @return the request in queue listener
*/
public IRequestListener getRequestInQListener();
/**
* Retrieves the request listener for issued certificates.
- *
+ *
* @return the request listener for issued certificates
*/
public IRequestListener getCertIssuedListener();
/**
* Retrieves the request listener for revoked certificates.
- *
+ *
* @return the request listener for revoked certificates
*/
public IRequestListener getCertRevokedListener();
/**
* Returns the nickname of the RA certificate.
- *
+ *
* @return the nickname of the RA certificate
*/
public String getNickname();
/**
* Retrieves the nickname of the RA certificate from configuration store.
- *
+ *
* @return the nickname of the RA certificate
* @exception EBaseException failed to get nickname
*/
@@ -121,51 +119,51 @@ public interface IRegistrationAuthority extends ISubsystem {
/**
* Sets the new nickname of the RA certifiate.
- *
+ *
* @param name new nickname
*/
public void setNewNickName(String name);
/**
* Sets the nickname of the RA certifiate.
- *
+ *
* @param str nickname
*/
public void setNickname(String str);
/**
* Retrieves the default validity period.
- *
+ *
* @return the default validity length in days
*/
public long getDefaultValidity();
/**
* Retrieves the issuer name of this registration authority.
- *
+ *
* @return the issuer name of this registration authority
*/
public X500Name getX500Name();
/**
- * Retrieves the RA service object that is responsible for
- * processing requests.
- *
+ * Retrieves the RA service object that is responsible for processing
+ * requests.
+ *
* @return RA service object
*/
- public IRAService getRAService();
+ public IRAService getRAService();
/**
* Retrieves the request listener by name.
- *
+ *
* @param name request listener name
* @return the request listener
*/
- public IRequestListener getRequestListener(String name);
+ public IRequestListener getRequestListener(String name);
/**
* Retrieves all request listeners.
- *
+ *
* @return name enumeration of all request listeners
*/
public Enumeration<String> getRequestListenerNames();
diff --git a/pki/base/common/src/com/netscape/certsrv/registry/ERegistryException.java b/pki/base/common/src/com/netscape/certsrv/registry/ERegistryException.java
index a4574981..5d2e2c91 100644
--- a/pki/base/common/src/com/netscape/certsrv/registry/ERegistryException.java
+++ b/pki/base/common/src/com/netscape/certsrv/registry/ERegistryException.java
@@ -17,13 +17,11 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.registry;
-
import com.netscape.certsrv.base.EBaseException;
-
/**
* This represents a registry exception.
- *
+ *
* @version $Revision$, $Date$
*/
public class ERegistryException extends EBaseException {
@@ -35,7 +33,7 @@ public class ERegistryException extends EBaseException {
/**
* Constructs a registry exception.
- *
+ *
* @param msg message carried along with the exception
*/
public ERegistryException(String msg) {
diff --git a/pki/base/common/src/com/netscape/certsrv/registry/IPluginInfo.java b/pki/base/common/src/com/netscape/certsrv/registry/IPluginInfo.java
index 774b3f9b..31a24ab5 100644
--- a/pki/base/common/src/com/netscape/certsrv/registry/IPluginInfo.java
+++ b/pki/base/common/src/com/netscape/certsrv/registry/IPluginInfo.java
@@ -17,28 +17,23 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.registry;
-
import java.util.Locale;
-
/**
- * The plugin information includes name,
- * class name, and description. The localizable
- * name and description are information
- * for end-users.
+ * The plugin information includes name, class name, and description. The
+ * localizable name and description are information for end-users.
* <p>
- *
- * The class name can be used to create
- * an instance of the plugin.
+ *
+ * The class name can be used to create an instance of the plugin.
* <p>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IPluginInfo {
/**
* Retrieves the localized plugin name.
- *
+ *
* @param locale end-user locale
* @return plugin name
*/
@@ -46,18 +41,18 @@ public interface IPluginInfo {
/**
* Retrieves the localized plugin description.
- *
+ *
* @param locale end-user locale
* @return plugin description
*/
public String getDescription(Locale locale);
/**
- * Retrieves the class name of the plugin.
- * Instance of plugin can be created with
+ * Retrieves the class name of the plugin. Instance of plugin can be created
+ * with
* <p>
* Class.forName(info.getClassName());
- *
+ *
* @return java class name
*/
public String getClassName();
diff --git a/pki/base/common/src/com/netscape/certsrv/registry/IPluginRegistry.java b/pki/base/common/src/com/netscape/certsrv/registry/IPluginRegistry.java
index 7631f3ea..142f70c9 100644
--- a/pki/base/common/src/com/netscape/certsrv/registry/IPluginRegistry.java
+++ b/pki/base/common/src/com/netscape/certsrv/registry/IPluginRegistry.java
@@ -17,20 +17,17 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.registry;
-
import java.util.Enumeration;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.base.ISubsystem;
-
/**
- * This represents the registry subsystem that manages
- * mulitple types of plugin information.
- *
- * The plugin information includes id, name,
- * classname, and description.
- *
+ * This represents the registry subsystem that manages mulitple types of plugin
+ * information.
+ *
+ * The plugin information includes id, name, classname, and description.
+ *
* @version $Revision$, $Date$
*/
public interface IPluginRegistry extends ISubsystem {
@@ -39,21 +36,21 @@ public interface IPluginRegistry extends ISubsystem {
/**
* Returns handle to the registry configuration file.
- *
+ *
* @return configuration store of registry subsystem
*/
public IConfigStore getFileConfigStore();
/**
* Returns all type names.
- *
+ *
* @return a list of String-based names
*/
public Enumeration<String> getTypeNames();
/**
* Returns a list of plugin identifiers of the given type.
- *
+ *
* @param type plugin type
* @return a list of plugin IDs
*/
@@ -61,7 +58,7 @@ public interface IPluginRegistry extends ISubsystem {
/**
* Retrieves the plugin information.
- *
+ *
* @param type plugin type
* @param id plugin id
* @return plugin info
@@ -70,24 +67,24 @@ public interface IPluginRegistry extends ISubsystem {
/**
* Adds plugin info.
- *
+ *
* @param type plugin type
* @param id plugin id
* @param info plugin info
* @exception ERegistryException failed to add plugin
*/
public void addPluginInfo(String type, String id, IPluginInfo info)
- throws ERegistryException;
+ throws ERegistryException;
/**
* Removes plugin info.
*/
public void removePluginInfo(String type, String id)
- throws ERegistryException;
+ throws ERegistryException;
/**
* Creates a pluginInfo
*/
- public IPluginInfo createPluginInfo(String name, String desc,
- String classPath);
+ public IPluginInfo createPluginInfo(String name, String desc,
+ String classPath);
}
diff --git a/pki/base/common/src/com/netscape/certsrv/request/ARequestNotifier.java b/pki/base/common/src/com/netscape/certsrv/request/ARequestNotifier.java
index 65ddeac9..6fbbb8ba 100644
--- a/pki/base/common/src/com/netscape/certsrv/request/ARequestNotifier.java
+++ b/pki/base/common/src/com/netscape/certsrv/request/ARequestNotifier.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.request;
-
import java.math.BigInteger;
import java.util.Enumeration;
import java.util.Hashtable;
@@ -31,9 +30,9 @@ import com.netscape.certsrv.ldap.ILdapConnModule;
import com.netscape.certsrv.publish.IPublisherProcessor;
/**
- * The ARequestNotifier class implements the IRequestNotifier interface,
- * which notifies all registered request listeners.
- *
+ * The ARequestNotifier class implements the IRequestNotifier interface, which
+ * notifies all registered request listeners.
+ *
* @version $Revision$, $Date$
*/
public class ARequestNotifier implements IRequestNotifier {
@@ -52,31 +51,32 @@ public class ARequestNotifier implements IRequestNotifier {
private int mSavePublishingStatus = 0;
private int mSavePublishingCounter = 0;
-
public ARequestNotifier() {
mPublishingQueuePriority = Thread.currentThread().getPriority();
}
- public ARequestNotifier (ICertificateAuthority ca) {
+ public ARequestNotifier(ICertificateAuthority ca) {
mCA = ca;
- if (mCA != null) mRequestQueue = mCA.getRequestQueue();
+ if (mCA != null)
+ mRequestQueue = mCA.getRequestQueue();
}
- public void setPublishingQueue (boolean isPublishingQueueEnabled,
+ public void setPublishingQueue(boolean isPublishingQueueEnabled,
int publishingQueuePriorityLevel,
int maxNumberOfPublishingThreads,
int publishingQueuePageSize,
int savePublishingStatus) {
- CMS.debug("setPublishingQueue: Publishing Queue Enabled: " + isPublishingQueueEnabled+
- " Priority Level: " + publishingQueuePriorityLevel+
- " Maximum Number of Threads: " + maxNumberOfPublishingThreads+
- " Page Size: "+ publishingQueuePageSize);
+ CMS.debug("setPublishingQueue: Publishing Queue Enabled: " + isPublishingQueueEnabled +
+ " Priority Level: " + publishingQueuePriorityLevel +
+ " Maximum Number of Threads: " + maxNumberOfPublishingThreads +
+ " Page Size: " + publishingQueuePageSize);
mIsPublishingQueueEnabled = isPublishingQueueEnabled;
mMaxThreads = maxNumberOfPublishingThreads;
mMaxRequests = publishingQueuePageSize;
mSavePublishingStatus = savePublishingStatus;
- // Publishing Queue Priority Levels: 2 - maximum, 1 - higher, 0 - normal, -1 - lower, -2 - minimum
+ // Publishing Queue Priority Levels: 2 - maximum, 1 - higher, 0 -
+ // normal, -1 - lower, -2 - minimum
if (publishingQueuePriorityLevel > 1) {
mPublishingQueuePriority = Thread.MAX_PRIORITY;
} else if (publishingQueuePriorityLevel > 0) {
@@ -89,7 +89,8 @@ public class ARequestNotifier implements IRequestNotifier {
mPublishingQueuePriority = Thread.currentThread().getPriority();
}
- if (mCA != null && mRequestQueue == null) mRequestQueue = mCA.getRequestQueue();
+ if (mCA != null && mRequestQueue == null)
+ mRequestQueue = mCA.getRequestQueue();
if (mIsPublishingQueueEnabled && mSavePublishingStatus > 0 && mRequestQueue != null) {
mPublishingStatus = mRequestQueue.getPublishingStatus();
BigInteger status = new BigInteger("-2");
@@ -101,23 +102,23 @@ public class ARequestNotifier implements IRequestNotifier {
} catch (Exception e) {
}
}
-
+
}
/**
* Registers a request listener.
- *
+ *
* @param listener listener to be registered
*/
public void registerListener(IRequestListener listener) {
// XXX should check for duplicates here or allow listeners
- // to register twice and call twice ?
+ // to register twice and call twice ?
mListeners.put(listener.getClass().getName(), listener);
}
/**
* Registers a request listener.
- *
+ *
* @param name listener name
* @param listener listener to be registered
*/
@@ -127,18 +128,18 @@ public class ARequestNotifier implements IRequestNotifier {
/**
* Removes listener from the list of registered listeners.
- *
+ *
* @param listener listener to be removed from the list
*/
public void removeListener(IRequestListener listener) {
// XXX should check for duplicates here or allow listeners
- // to register twice and call twice ?
+ // to register twice and call twice ?
mListeners.remove(listener.getClass().getName());
}
/**
* Gets list of listener names.
- *
+ *
* @return enumeration of listener names
*/
public Enumeration<String> getListenerNames() {
@@ -147,7 +148,7 @@ public class ARequestNotifier implements IRequestNotifier {
/**
* Removes listener from the list of registered listeners.
- *
+ *
* @param name listener name to be removed from the list
*/
public void removeListener(String name) {
@@ -156,7 +157,7 @@ public class ARequestNotifier implements IRequestNotifier {
/**
* Gets listener from the list of registered listeners.
- *
+ *
* @param name listener name
* @return listener
*/
@@ -166,26 +167,25 @@ public class ARequestNotifier implements IRequestNotifier {
/**
* Gets list of listeners.
- *
+ *
* @return enumeration of listeners
*/
public Enumeration<IRequestListener> getListeners() {
return mListeners.elements();
}
-
private Object publishingCounterMonitor = new Object();
public void updatePublishingStatus(String id) {
if (mRequestQueue != null) {
synchronized (publishingCounterMonitor) {
if (mSavePublishingCounter == 0) {
- CMS.debug("updatePublishingStatus requestId: "+id);
+ CMS.debug("updatePublishingStatus requestId: " + id);
mRequestQueue.setPublishingStatus(id);
}
mSavePublishingCounter++;
- CMS.debug("updatePublishingStatus mSavePublishingCounter: "+mSavePublishingCounter+
- " mSavePublishingStatus: "+mSavePublishingStatus);
+ CMS.debug("updatePublishingStatus mSavePublishingCounter: " + mSavePublishingCounter +
+ " mSavePublishingStatus: " + mSavePublishingStatus);
if (mSavePublishingCounter >= mSavePublishingStatus) {
mSavePublishingCounter = 0;
}
@@ -197,24 +197,25 @@ public class ARequestNotifier implements IRequestNotifier {
/**
* Gets request from publishing queue.
- *
+ *
* @return request
*/
public synchronized IRequest getRequest() {
- IRequest r = null;
- String id = null;
+ IRequest r = null;
+ String id = null;
CMS.debug("getRequest mRequests=" + mRequests.size() + " mSearchForRequests=" + mSearchForRequests);
if (mSearchForRequests && mRequests.size() == 1) {
- id = (String)mRequests.elementAt(0);
- if (mCA != null && mRequestQueue == null) mRequestQueue = mCA.getRequestQueue();
+ id = (String) mRequests.elementAt(0);
+ if (mCA != null && mRequestQueue == null)
+ mRequestQueue = mCA.getRequestQueue();
if (id != null && mRequestQueue != null) {
CMS.debug("getRequest request id=" + id);
IRequestVirtualList list = mRequestQueue.getPagedRequestsByFilter(
new RequestId(id),
"(requeststate=complete)", mMaxRequests, "requestId");
int s = list.getSize() - list.getCurrentIndex();
- CMS.debug("getRequest list size: "+s);
+ CMS.debug("getRequest list size: " + s);
for (int i = 0; i < s; i++) {
r = null;
try {
@@ -230,10 +231,9 @@ public class ARequestNotifier implements IRequestNotifier {
continue;
}
if (!(requestType.equals(IRequest.ENROLLMENT_REQUEST) ||
- requestType.equals(IRequest.RENEWAL_REQUEST) ||
- requestType.equals(IRequest.REVOCATION_REQUEST) ||
- requestType.equals(IRequest.CMCREVOKE_REQUEST) ||
- requestType.equals(IRequest.UNREVOCATION_REQUEST))) {
+ requestType.equals(IRequest.RENEWAL_REQUEST) ||
+ requestType.equals(IRequest.REVOCATION_REQUEST) ||
+ requestType.equals(IRequest.CMCREVOKE_REQUEST) || requestType.equals(IRequest.UNREVOCATION_REQUEST))) {
continue;
}
if (i == 0 && id.equals(r.getRequestId().toString())) {
@@ -245,8 +245,8 @@ public class ARequestNotifier implements IRequestNotifier {
}
if (mRequests.size() < mMaxRequests) {
mRequests.addElement(r.getRequestId().toString());
- CMS.debug("getRequest added "+r.getRequestType()+" request "+r.getRequestId().toString()+
- " to mRequests: " + mRequests.size()+" ("+mMaxRequests+")");
+ CMS.debug("getRequest added " + r.getRequestType() + " request " + r.getRequestId().toString() +
+ " to mRequests: " + mRequests.size() + " (" + mMaxRequests + ")");
} else {
break;
}
@@ -257,16 +257,17 @@ public class ARequestNotifier implements IRequestNotifier {
}
}
if (mRequests.size() > 0) {
- id = (String)mRequests.elementAt(0);
+ id = (String) mRequests.elementAt(0);
if (id != null) {
CMS.debug("getRequest getting request: " + id);
- if (mCA != null && mRequestQueue == null) mRequestQueue = mCA.getRequestQueue();
+ if (mCA != null && mRequestQueue == null)
+ mRequestQueue = mCA.getRequestQueue();
if (mRequestQueue != null) {
try {
r = mRequestQueue.findRequest(new RequestId(id));
mRequests.remove(0);
- CMS.debug("getRequest request "+ id + ((r != null)?" found":" not found"));
- //updatePublishingStatus(id);
+ CMS.debug("getRequest request " + id + ((r != null) ? " found" : " not found"));
+ // updatePublishingStatus(id);
} catch (EBaseException e) {
CMS.debug("getRequest EBaseException " + e.toString());
}
@@ -285,7 +286,7 @@ public class ARequestNotifier implements IRequestNotifier {
/**
* Gets number of requests in publishing queue.
- *
+ *
* @return number of requests in publishing queue
*/
public int getNumberOfRequests() {
@@ -294,7 +295,7 @@ public class ARequestNotifier implements IRequestNotifier {
/**
* Checks if publishing queue is enabled.
- *
+ *
* @return true if publishing queue is enabled, false otherwise
*/
public boolean isPublishingQueueEnabled() {
@@ -303,7 +304,7 @@ public class ARequestNotifier implements IRequestNotifier {
/**
* Removes a notifier thread from the pool of publishing queue threads.
- *
+ *
* @param notifierThread Thread
*/
public void removeNotifierThread(Thread notifierThread) {
@@ -318,12 +319,12 @@ public class ARequestNotifier implements IRequestNotifier {
/**
* Notifies all registered listeners about request.
- *
+ *
* @param r request
*/
public void notify(IRequest r) {
- CMS.debug("ARequestNotifier notify mIsPublishingQueueEnabled="+mIsPublishingQueueEnabled+
- " mMaxThreads="+mMaxThreads);
+ CMS.debug("ARequestNotifier notify mIsPublishingQueueEnabled=" + mIsPublishingQueueEnabled +
+ " mMaxThreads=" + mMaxThreads);
if (mIsPublishingQueueEnabled) {
addToNotify(r);
} else if (mMaxThreads == 0) {
@@ -341,26 +342,27 @@ public class ARequestNotifier implements IRequestNotifier {
new Thread(new RunListeners(r, mListeners.elements())).start();
} catch (Throwable e) {
- /*
- CMS.getLogger().log(
- ILogger.EV_SYSTEM, ILogger.S_REQQUEUE, ILogger.LL_FAILURE,
- "Could not run listeners for request " + r.getRequestId() +
- ". Error " + e + ";" + e.getMessage());
- */
+ /*
+ * CMS.getLogger().log( ILogger.EV_SYSTEM, ILogger.S_REQQUEUE,
+ * ILogger.LL_FAILURE, "Could not run listeners for request " +
+ * r.getRequestId() + ". Error " + e + ";" + e.getMessage());
+ */
}
}
}
/**
* Checks for available publishing connections
- *
- * @return true if there are available publishing connections, false otherwise
+ *
+ * @return true if there are available publishing connections, false
+ * otherwise
*/
private boolean checkAvailablePublishingConnections() {
boolean availableConnections = false;
IPublisherProcessor pp = null;
- if (mCA != null) pp = mCA.getPublisherProcessor();
+ if (mCA != null)
+ pp = mCA.getPublisherProcessor();
if (pp != null && pp.enabled()) {
ILdapConnModule ldapConnModule = pp.getLdapConnModule();
if (ldapConnModule != null) {
@@ -378,8 +380,8 @@ public class ARequestNotifier implements IRequestNotifier {
CMS.debug("checkAvailablePublishingConnections ldapConnModule is not accessible");
}
} else {
- CMS.debug("checkAvailablePublishingConnections PublisherProcessor is not " +
- ((pp != null)?"enabled":"accessible"));
+ CMS.debug("checkAvailablePublishingConnections PublisherProcessor is not " +
+ ((pp != null) ? "enabled" : "accessible"));
}
return availableConnections;
@@ -387,7 +389,7 @@ public class ARequestNotifier implements IRequestNotifier {
/**
* Checks if more publishing threads can be added.
- *
+ *
* @return true if more publishing threads can be added, false otherwise
*/
private boolean morePublishingThreads() {
@@ -396,9 +398,9 @@ public class ARequestNotifier implements IRequestNotifier {
if (mNotifierThreads.size() == 0) {
moreThreads = true;
} else if (mNotifierThreads.size() < mMaxThreads) {
- CMS.debug("morePublishingThreads ("+mRequests.size()+">"+
- ((mMaxRequests * mNotifierThreads.size()) / mMaxThreads)+
- " "+"("+mMaxRequests+"*"+mNotifierThreads.size()+"):"+mMaxThreads);
+ CMS.debug("morePublishingThreads (" + mRequests.size() + ">" +
+ ((mMaxRequests * mNotifierThreads.size()) / mMaxThreads) +
+ " " + "(" + mMaxRequests + "*" + mNotifierThreads.size() + "):" + mMaxThreads);
// gradually add new publishing threads
if (mRequests.size() > ((mMaxRequests * mNotifierThreads.size()) / mMaxThreads)) {
// check for available publishing connections
@@ -412,21 +414,20 @@ public class ARequestNotifier implements IRequestNotifier {
return moreThreads;
}
-
/**
* Notifies all registered listeners about request.
- *
+ *
* @param r request
*/
public synchronized void addToNotify(IRequest r) {
if (!mSearchForRequests) {
if (mRequests.size() < mMaxRequests) {
mRequests.addElement(r.getRequestId().toString());
- CMS.debug("addToNotify extended buffer to "+mRequests.size()+"("+mMaxRequests+")"+
- " requests by adding request "+r.getRequestId().toString());
+ CMS.debug("addToNotify extended buffer to " + mRequests.size() + "(" + mMaxRequests + ")" +
+ " requests by adding request " + r.getRequestId().toString());
if (morePublishingThreads()) {
try {
- Thread notifierThread = new Thread(new RunListeners((IRequestNotifier)this));
+ Thread notifierThread = new Thread(new RunListeners((IRequestNotifier) this));
if (notifierThread != null) {
mNotifierThreads.addElement(notifierThread);
CMS.debug("Number of publishing threads: " + mNotifierThreads.size());
@@ -445,23 +446,22 @@ public class ARequestNotifier implements IRequestNotifier {
}
}
-
/**
* Recovers publishing queue.
- *
+ *
* @param id request request
*/
public void recoverPublishingQueue(String id) {
- CMS.debug("recoverPublishingQueue mRequests.size()="+mRequests.size()+"("+mMaxRequests+")"+
- " requests by adding request "+id);
+ CMS.debug("recoverPublishingQueue mRequests.size()=" + mRequests.size() + "(" + mMaxRequests + ")" +
+ " requests by adding request " + id);
if (mRequests.size() == 0) {
mRequests.addElement(id);
- CMS.debug("recoverPublishingQueue extended buffer to "+mRequests.size()+"("+mMaxRequests+")"+
- " requests by adding request "+id);
+ CMS.debug("recoverPublishingQueue extended buffer to " + mRequests.size() + "(" + mMaxRequests + ")" +
+ " requests by adding request " + id);
if (morePublishingThreads()) {
mSearchForRequests = true;
try {
- Thread notifierThread = new Thread(new RunListeners((IRequestNotifier)this));
+ Thread notifierThread = new Thread(new RunListeners((IRequestNotifier) this));
if (notifierThread != null) {
mNotifierThreads.addElement(notifierThread);
CMS.debug("Number of publishing threads: " + mNotifierThreads.size());
@@ -478,10 +478,9 @@ public class ARequestNotifier implements IRequestNotifier {
}
}
-
/**
- * The RunListeners class implements Runnable interface.
- * This class executes notification of registered listeners.
+ * The RunListeners class implements Runnable interface. This class executes
+ * notification of registered listeners.
*/
class RunListeners implements Runnable {
IRequest mRequest = null;
@@ -490,7 +489,7 @@ class RunListeners implements Runnable {
/**
* RunListeners class constructor.
- *
+ *
* @param r request
* @param listeners list of listeners
*/
@@ -501,7 +500,7 @@ class RunListeners implements Runnable {
/**
* RunListeners class constructor.
- *
+ *
* @param r request
* @param listeners list of listeners
*/
@@ -514,10 +513,11 @@ class RunListeners implements Runnable {
* RunListeners thread implementation.
*/
public void run() {
- CMS.debug("RunListeners::"+((mRequestNotifier != null && mRequestNotifier.getNumberOfRequests() > 0)?" Queue: "+mRequestNotifier.getNumberOfRequests():" noQueue")+
- " "+((mRequest != null)?" SingleRequest":" noSingleRequest"));
+ CMS.debug("RunListeners::" + ((mRequestNotifier != null && mRequestNotifier.getNumberOfRequests() > 0) ? " Queue: " + mRequestNotifier.getNumberOfRequests() : " noQueue") +
+ " " + ((mRequest != null) ? " SingleRequest" : " noSingleRequest"));
do {
- if (mRequestNotifier != null) mRequest = (IRequest)mRequestNotifier.getRequest();
+ if (mRequestNotifier != null)
+ mRequest = (IRequest) mRequestNotifier.getRequest();
if (mListeners != null && mRequest != null) {
while (mListeners.hasMoreElements()) {
IRequestListener l = (IRequestListener) mListeners.nextElement();
@@ -529,11 +529,13 @@ class RunListeners implements Runnable {
mRequestNotifier.updatePublishingStatus(mRequest.getRequestId().toString());
}
}
- CMS.debug("RunListeners: "+((mRequestNotifier != null && mRequestNotifier.getNumberOfRequests() > 0)?" Queue: "+mRequestNotifier.getNumberOfRequests():" noQueue")+
- " "+((mRequest != null)?" SingleRequest":" noSingleRequest"));
- if (mRequestNotifier != null) mListeners = mRequestNotifier.getListeners();
+ CMS.debug("RunListeners: " + ((mRequestNotifier != null && mRequestNotifier.getNumberOfRequests() > 0) ? " Queue: " + mRequestNotifier.getNumberOfRequests() : " noQueue") +
+ " " + ((mRequest != null) ? " SingleRequest" : " noSingleRequest"));
+ if (mRequestNotifier != null)
+ mListeners = mRequestNotifier.getListeners();
} while (mRequestNotifier != null && mRequestNotifier.getNumberOfRequests() > 0);
- if (mRequestNotifier != null) mRequestNotifier.removeNotifierThread(Thread.currentThread());
+ if (mRequestNotifier != null)
+ mRequestNotifier.removeNotifierThread(Thread.currentThread());
}
}
diff --git a/pki/base/common/src/com/netscape/certsrv/request/AgentApproval.java b/pki/base/common/src/com/netscape/certsrv/request/AgentApproval.java
index c884ebbf..681263b4 100644
--- a/pki/base/common/src/com/netscape/certsrv/request/AgentApproval.java
+++ b/pki/base/common/src/com/netscape/certsrv/request/AgentApproval.java
@@ -17,27 +17,25 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.request;
-
import java.io.Serializable;
import java.util.Date;
-
/**
- * The AgentApproval class contains the record of a
- * single agent approval.
- *
+ * The AgentApproval class contains the record of a single agent approval.
+ *
* @version $Revision$, $Date$
*/
public class AgentApproval
- implements Serializable {
+ implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3444654917454805225L;
+
/**
* Returns the approving agent's user name.
- *
+ *
* @return an identifier for the agent
*/
public String getUserName() {
@@ -46,7 +44,7 @@ public class AgentApproval
/**
* Returns the date of the approval
- *
+ *
* @return date and time of the approval
*/
public Date getDate() {
@@ -55,7 +53,7 @@ public class AgentApproval
/**
* AgentApproval class constructor
- *
+ *
* @param userName user name of the approving agent
*/
AgentApproval(String userName) {
diff --git a/pki/base/common/src/com/netscape/certsrv/request/AgentApprovals.java b/pki/base/common/src/com/netscape/certsrv/request/AgentApprovals.java
index 410e3b2c..bc2e60ac 100644
--- a/pki/base/common/src/com/netscape/certsrv/request/AgentApprovals.java
+++ b/pki/base/common/src/com/netscape/certsrv/request/AgentApprovals.java
@@ -17,21 +17,18 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.request;
-
import java.io.Serializable;
import java.util.Date;
import java.util.Enumeration;
import java.util.Vector;
-
/**
- * A collection of AgentApproval objects.
- * <single-threaded>
- *
+ * A collection of AgentApproval objects. <single-threaded>
+ *
* @version $Revision$, $Date$
*/
public class AgentApprovals
- implements Serializable {
+ implements Serializable {
/**
*
@@ -41,15 +38,14 @@ public class AgentApprovals
/**
* Adds an approval to approval's list.
* <p>
- * If an approval is already present for this user,
- * it is updated with a new date. Otherwise a new
- * value is inserted.
- *
+ * If an approval is already present for this user, it is updated with a new
+ * date. Otherwise a new value is inserted.
+ *
* @param userName user name of the approving agent
*/
public void addApproval(String userName) {
AgentApproval a = findApproval(userName);
-
+
// update existing approval
if (a != null) {
a.mDate = new Date(); /* CMS.getCurrentDate(); */
@@ -63,9 +59,8 @@ public class AgentApprovals
/**
* Removes an approval from approval's list.
* <p>
- * If there is no approval for this userName, this
- * call does nothing.
- *
+ * If there is no approval for this userName, this call does nothing.
+ *
* @param userName user name of the approving agent
*/
public void removeApproval(String userName) {
@@ -77,7 +72,7 @@ public class AgentApprovals
/**
* Finds an existing AgentApproval for the named user.
- *
+ *
* @param userName user name of the approving agent
* @return an AgentApproval object
*/
@@ -88,7 +83,8 @@ public class AgentApprovals
for (int i = 0; i < mVector.size(); i++) {
a = (AgentApproval) mVector.elementAt(i);
- if (a.mUserName.equals(userName)) break;
+ if (a.mUserName.equals(userName))
+ break;
}
return a;
@@ -96,7 +92,7 @@ public class AgentApprovals
/**
* Returns an enumeration of the agent approvals
- *
+ *
* @return an enumeration of the agent approvals
*/
public Enumeration elements() {
@@ -104,12 +100,11 @@ public class AgentApprovals
}
/**
- * Returns the AgentApprovals as a Vector of strings.
- * Each entry in the vector is of the format:
- * epoch;username
- * where epoch is the date.getTime()
+ * Returns the AgentApprovals as a Vector of strings. Each entry in the
+ * vector is of the format: epoch;username where epoch is the date.getTime()
* <p>
* This is used for serialization in Request.setExtData().
+ *
* @return The string vector.
*/
public Vector toStringVector() {
@@ -123,8 +118,9 @@ public class AgentApprovals
}
/**
- * Recreates an AgentApprovals instance from a Vector of strings that
- * was created by toStringVector().
+ * Recreates an AgentApprovals instance from a Vector of strings that was
+ * created by toStringVector().
+ *
* @param stringVector The vector of strings to translate
* @return the AgentApprovals instance or null if it can't be translated.
*/
@@ -135,7 +131,7 @@ public class AgentApprovals
AgentApprovals approvals = new AgentApprovals();
for (int i = 0; i < stringVector.size(); i++) {
try {
- String approvalString = (String)stringVector.get(i);
+ String approvalString = (String) stringVector.get(i);
String[] parts = approvalString.split(";", 2);
if (parts.length != 2) {
return null;
diff --git a/pki/base/common/src/com/netscape/certsrv/request/IEnrollmentRequest.java b/pki/base/common/src/com/netscape/certsrv/request/IEnrollmentRequest.java
index e7036d1e..01bc870f 100644
--- a/pki/base/common/src/com/netscape/certsrv/request/IEnrollmentRequest.java
+++ b/pki/base/common/src/com/netscape/certsrv/request/IEnrollmentRequest.java
@@ -17,15 +17,13 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.request;
-
/**
- * An example of a more specialized request interface.
- * This version (currently) doesn't supply any additional
- * data, but is implementated only for testing and
+ * An example of a more specialized request interface. This version (currently)
+ * doesn't supply any additional data, but is implementated only for testing and
* demonstration purposes.
- *
+ *
* @version $Revision$, $Date$
*/
public interface IEnrollmentRequest
- extends IRequest {
+ extends IRequest {
}
diff --git a/pki/base/common/src/com/netscape/certsrv/request/INotify.java b/pki/base/common/src/com/netscape/certsrv/request/INotify.java
index d4ff15b7..636eba7b 100644
--- a/pki/base/common/src/com/netscape/certsrv/request/INotify.java
+++ b/pki/base/common/src/com/netscape/certsrv/request/INotify.java
@@ -17,24 +17,22 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.request;
-
/**
- * The INotify interface defines operations that are invoked
- * when a request is completely processed. A class implementing
- * this interface may be registered with a IRequestQueue.
- * The interface will be invoked when a request is completely
- * serviced by the IService object.
- *
+ * The INotify interface defines operations that are invoked when a request is
+ * completely processed. A class implementing this interface may be registered
+ * with a IRequestQueue. The interface will be invoked when a request is
+ * completely serviced by the IService object.
+ *
* @version $Revision$ $Date$
*/
public interface INotify {
/**
- * Provides notification that a request has been completed.
- * The implementation may use values stored in the IRequest
- * object, and may implement any type publishing (such as email
- * or writing values into a directory)
- *
+ * Provides notification that a request has been completed. The
+ * implementation may use values stored in the IRequest object, and may
+ * implement any type publishing (such as email or writing values into a
+ * directory)
+ *
* @param request the request that is completed.
*/
public void notify(IRequest request);
diff --git a/pki/base/common/src/com/netscape/certsrv/request/IPolicy.java b/pki/base/common/src/com/netscape/certsrv/request/IPolicy.java
index d74a32a4..06262fee 100644
--- a/pki/base/common/src/com/netscape/certsrv/request/IPolicy.java
+++ b/pki/base/common/src/com/netscape/certsrv/request/IPolicy.java
@@ -17,37 +17,32 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.request;
-
/**
- * Interface to a policy. The policy evaluates the request for
- * correctness and completeness. It may change or add to values
- * stored in the request. The policy object also decides
- * whether a request should be queue to await approval by
- * an agent.
- * FUTURE: In this case, the policy should set the
- * 'agentGroup' entry in the request to indicate the group
- * of agents allowed to perform further processing. If none
- * is set, a default value ("defaultAgentGroup") will be
- * set instead.
- *
+ * Interface to a policy. The policy evaluates the request for correctness and
+ * completeness. It may change or add to values stored in the request. The
+ * policy object also decides whether a request should be queue to await
+ * approval by an agent. FUTURE: In this case, the policy should set the
+ * 'agentGroup' entry in the request to indicate the group of agents allowed to
+ * perform further processing. If none is set, a default value
+ * ("defaultAgentGroup") will be set instead.
+ *
* @version $Revision$, $Date$
*/
public interface IPolicy {
/**
- * Applies the policy check to the request. The policy should
- * determine whether the request can be processed immediately,
- * or should be held pending manual approval.
+ * Applies the policy check to the request. The policy should determine
+ * whether the request can be processed immediately, or should be held
+ * pending manual approval.
* <p>
- * The policy can update fields in the request, to add additional values
- * or to restrict the values to pre-determined ranges.
+ * The policy can update fields in the request, to add additional values or
+ * to restrict the values to pre-determined ranges.
* <p>
- * @param request
- * the request to check
- * @return
- * a result code indicating the result of the evaluation. The
- * processor will determine the next request processing step based
- * on this value
+ *
+ * @param request the request to check
+ * @return a result code indicating the result of the evaluation. The
+ * processor will determine the next request processing step based
+ * on this value
*/
PolicyResult apply(IRequest request);
}
diff --git a/pki/base/common/src/com/netscape/certsrv/request/IRequest.java b/pki/base/common/src/com/netscape/certsrv/request/IRequest.java
index 1174778a..6a731444 100644
--- a/pki/base/common/src/com/netscape/certsrv/request/IRequest.java
+++ b/pki/base/common/src/com/netscape/certsrv/request/IRequest.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.request;
-
//import java.io.Serializable;
import java.math.BigInteger;
@@ -36,10 +35,9 @@ import netscape.security.x509.X509CertInfo;
import com.netscape.certsrv.authentication.IAuthToken;
import com.netscape.certsrv.base.IAttrSet;
-
/**
* An interface that defines abilities of request objects,
- *
+ *
* @version $Revision$, $Date$
*/
public interface IRequest {
@@ -77,18 +75,19 @@ public interface IRequest {
public static final String REQUESTOR_EMAIL = "csrRequestorEmail";
public static final String REQUESTOR_COMMENTS = "csrRequestorComments";
- // request attributes for all
+ // request attributes for all
public static final String AUTH_TOKEN = "AUTH_TOKEN";
public static final String HTTP_PARAMS = "HTTP_PARAMS";
public static final String HTTP_HEADERS = "HTTP_HEADERS";
// Params added by agents on agent approval page
public static final String AGENT_PARAMS = "AGENT_PARAMS";
// server attributes: attributes generated by server modules.
- public static final String SERVER_ATTRS = "SERVER_ATTRS";
+ public static final String SERVER_ATTRS = "SERVER_ATTRS";
- public static final String RESULT = "Result"; // service result.
- public static final Integer RES_SUCCESS = Integer.valueOf(1); // result value
- public static final Integer RES_ERROR = Integer.valueOf(2); // result value
+ public static final String RESULT = "Result"; // service result.
+ public static final Integer RES_SUCCESS = Integer.valueOf(1); // result
+ // value
+ public static final Integer RES_ERROR = Integer.valueOf(2); // result value
public static final String REMOTE_SERVICE_AUTHORITY = "RemServiceAuthority";
public static final String SVCERRORS = "serviceErrors";
public static final String REMOTE_STATUS = "remoteStatus";
@@ -110,11 +109,10 @@ public interface IRequest {
// also used for renewal
public static final String CERT_INFO = "CERT_INFO";
public static final String ISSUED_CERTS = "issuedCerts";
- public static final String
- REQUEST_TRUSTEDMGR_PRIVILEGE = "requestTrustedManagerPrivilege";
+ public static final String REQUEST_TRUSTEDMGR_PRIVILEGE = "requestTrustedManagerPrivilege";
public static final String FINGERPRINTS = "fingerprints";
-
- // enrollment request values
+
+ // enrollment request values
public static final String SERVER_CERT = "server";
public static final String CLIENT_CERT = "client";
public static final String CA_CERT = "ca";
@@ -124,7 +122,7 @@ public interface IRequest {
public static final String OTHER_CERT = "other";
public static final String ROUTER_CERT = "router"; // deprecated
public static final String CEP_CERT = "CEP-Request";
-
+
// renewal request attributes. (internally set)
// also used for revocation
public static final String OLD_CERTS = "OLD_CERTS";
@@ -143,13 +141,13 @@ public interface IRequest {
public final static String CRL_PUBLISH_ERROR = "crlPublishError";
public static final String REQUESTOR_TYPE = "requestorType";
- // Netkey request attributes
+ // Netkey request attributes
public final static String NETKEY_ATTR_CUID = "CUID";
public final static String NETKEY_ATTR_USERID = "USERID";
public final static String NETKEY_ATTR_DRMTRANS_DES_KEY = "drm_trans_desKey";
- public final static String NETKEY_ATTR_ARCHIVE_FLAG ="archive";
- public final static String NETKEY_ATTR_SERVERSIDE_MUSCLE_FLAG ="serverSideMuscle";
- public final static String NETKEY_ATTR_ENC_PRIVKEY_FLAG ="encryptPrivKey";
+ public final static String NETKEY_ATTR_ARCHIVE_FLAG = "archive";
+ public final static String NETKEY_ATTR_SERVERSIDE_MUSCLE_FLAG = "serverSideMuscle";
+ public final static String NETKEY_ATTR_ENC_PRIVKEY_FLAG = "encryptPrivKey";
public final static String NETKEY_ATTR_USER_CERT = "cert";
public final static String NETKEY_ATTR_KEY_SIZE = "keysize";
@@ -160,7 +158,7 @@ public interface IRequest {
public static final String REQUESTOR_KRA = "KRA";
public static final String REQUESTOR_AGENT = "Agent";
- // others (internally set)
+ // others (internally set)
public final static String CACERTCHAIN = "CACertChain";
public final static String CRL = "CRL";
public final static String DOGETCACHAIN = "doGetCAChain";
@@ -174,90 +172,87 @@ public interface IRequest {
/**
* Gets the primary identifier for this request.
- *
+ *
* @return request id
*/
RequestId getRequestId();
/**
* Gets the current state of this request.
- *
+ *
* @return request status
*/
RequestStatus getRequestStatus();
/**
- * Gets the "sourceId" for the request. The sourceId is
- * assigned by the originator of the request (for example,
- * the EE servlet or the RA servlet.
+ * Gets the "sourceId" for the request. The sourceId is assigned by the
+ * originator of the request (for example, the EE servlet or the RA servlet.
* <p>
- * The sourceId should be unique so that it can be used
- * to retrieve request later without knowing the locally
- * assigned primary id (RequestID)
+ * The sourceId should be unique so that it can be used to retrieve request
+ * later without knowing the locally assigned primary id (RequestID)
* <p>
- * @return
- * the sourceId value (or null if none has been set)
+ *
+ * @return the sourceId value (or null if none has been set)
*/
public String getSourceId();
/**
- * Sets the "sourceId" for this request. The request must be updated
- * in the database for this change to take effect. This can be done
- * by calling IRequestQueue.update() or by performing one of the
- * other operations like processRequest or approveRequest.
- *
+ * Sets the "sourceId" for this request. The request must be updated in the
+ * database for this change to take effect. This can be done by calling
+ * IRequestQueue.update() or by performing one of the other operations like
+ * processRequest or approveRequest.
+ *
* @param id source id for this request
*/
public void setSourceId(String id);
/**
* Gets the current owner of this request.
- *
+ *
* @return request owner
*/
public String getRequestOwner();
/**
* Sets the current owner of this request.
- *
- * @param owner
- * The new owner of this request. If this value is set to null
- * there will be no current owner
+ *
+ * @param owner The new owner of this request. If this value is set to null
+ * there will be no current owner
*/
public void setRequestOwner(String owner);
/**
* Gets the type of this request.
- *
+ *
* @return request type
*/
public String getRequestType();
/**
* Sets the type or this request.
- *
+ *
* @param type request type
*/
public void setRequestType(String type);
/**
* Gets the version of this request.
- *
+ *
* @return request version
*/
public String getRequestVersion();
/**
* Gets the time this request was created.
- *
+ *
* @return request creation time
*/
Date getCreationTime();
/**
- * Gets the time this request was last modified (defined
- * as updated in the queue) (See IRequestQueue.update)
- *
+ * Gets the time this request was last modified (defined as updated in the
+ * queue) (See IRequestQueue.update)
+ *
* @return request last modification time
*/
Date getModificationTime();
@@ -278,83 +273,81 @@ public interface IRequest {
public static final String ERROR = "Error";
/**
- * Copies meta attributes (excluding request Id, etc.) of another request
- * to this request.
- *
+ * Copies meta attributes (excluding request Id, etc.) of another request to
+ * this request.
+ *
* @param req another request
*/
public void copyContents(IRequest req);
/**
* Gets context of this request.
- *
+ *
* @return request context
*/
public String getContext();
/**
* Sets context of this request.
- *
+ *
* @param ctx request context
*/
public void setContext(String ctx);
/**
* Sets status of this request.
- *
+ *
* @param s request status
*/
public void setRequestStatus(RequestStatus s);
/**
* Gets status of connector transfer.
- *
+ *
* @return status of connector transfer
*/
public boolean isSuccess();
/**
* Gets localized error message from connector transfer.
- *
+ *
* @param locale request locale
* @return error message from connector transfer
*/
public String getError(Locale locale);
-
/**************************************************************
* ExtData data methods:
- *
- * These methods should be used in place of the mAttrData methods
- * deprecated above.
- *
- * These methods all store Strings in LDAP. This means they can no longer
- * be used as a garbage dump for all sorts of objects. A limited number
- * of helper methods are provided for Vectors/Arrays/Hashtables but the
- * keys and values for all of these should be Strings.
- *
- * The keys are used in the LDAP attribute names, and so much obey LDAP
- * key syntax rules: A-Za-z0-9 and hyphen.
- */
-
- /**
- * Sets an Extended Data string-key string-value pair.
- * All keys are lower cased because LDAP does not preserve case.
- *
- * @param key The extended data key
+ *
+ * These methods should be used in place of the mAttrData methods deprecated
+ * above.
+ *
+ * These methods all store Strings in LDAP. This means they can no longer be
+ * used as a garbage dump for all sorts of objects. A limited number of
+ * helper methods are provided for Vectors/Arrays/Hashtables but the keys
+ * and values for all of these should be Strings.
+ *
+ * The keys are used in the LDAP attribute names, and so much obey LDAP key
+ * syntax rules: A-Za-z0-9 and hyphen.
+ */
+
+ /**
+ * Sets an Extended Data string-key string-value pair. All keys are lower
+ * cased because LDAP does not preserve case.
+ *
+ * @param key The extended data key
* @param value The extended data value
* @return false if key is invalid.
*/
public boolean setExtData(String key, String value);
/**
- * Sets an Extended Data string-key string-value pair.
- * The key and hashtable keys are all lowercased because LDAP does not
- * preserve case.
- *
- * @param key The extended data key
- * @param value The extended data value
- * the Hashtable contains an illegal key.
+ * Sets an Extended Data string-key string-value pair. The key and hashtable
+ * keys are all lowercased because LDAP does not preserve case.
+ *
+ * @param key The extended data key
+ * @param value The extended data value the Hashtable contains an illegal
+ * key.
* @return false if the key or hashtable keys are invalid
*/
public boolean setExtData(String key, Hashtable<String, ?> value);
@@ -362,65 +355,69 @@ public interface IRequest {
/**
* Checks whether the key is storing a simple String value, or a complex
* (Vector/hashtable) structure.
- * @param key The key to check for.
- * @return True if the key maps to a string. False if it maps to a
+ *
+ * @param key The key to check for.
+ * @return True if the key maps to a string. False if it maps to a
* hashtable.
*/
public boolean isSimpleExtDataValue(String key);
/**
- * Returns the String value stored for the String key. Returns null
- * if not found. Throws exception if key stores a complex data structure
+ * Returns the String value stored for the String key. Returns null if not
+ * found. Throws exception if key stores a complex data structure
* (Vector/Hashtable).
- * @param key The key to lookup (case-insensitive)
- * @return The value associated with the key. null if not found or if the
- * key is associated with a non-string value.
+ *
+ * @param key The key to lookup (case-insensitive)
+ * @return The value associated with the key. null if not found or if the
+ * key is associated with a non-string value.
*/
public String getExtDataInString(String key);
/**
- * Returns the Hashtable value for the String key. Returns null if not
- * found. Throws exception if the key stores a String value.
- *
+ * Returns the Hashtable value for the String key. Returns null if not
+ * found. Throws exception if the key stores a String value.
+ *
* The Hashtable returned is actually a subclass of Hashtable that
- * lowercases all keys used to access the hashtable. Its purpose is to
- * to make lookups seemless, but be aware it is not a normal hashtable and
+ * lowercases all keys used to access the hashtable. Its purpose is to to
+ * make lookups seemless, but be aware it is not a normal hashtable and
* might behave strangely in some cases (e.g., iterating keys)
- *
- * @param key The key to lookup (case-insensitive)
- * @return The hashtable value associated with the key. null if not found
- * or if the key is associated with a string-value.
+ *
+ * @param key The key to lookup (case-insensitive)
+ * @return The hashtable value associated with the key. null if not found or
+ * if the key is associated with a string-value.
*/
public <V> Hashtable<String, V> getExtDataInHashtable(String key);
-
/**
* Returns all the keys stored in ExtData
+ *
* @return Enumeration of all the keys.
*/
public Enumeration<String> getExtDataKeys();
/**
- * Stores an array of Strings in ExtData.
- * The indices of the array are used as subkeys.
- * @param key the ExtData key
- * @param values the array of string values to store
+ * Stores an array of Strings in ExtData. The indices of the array are used
+ * as subkeys.
+ *
+ * @param key the ExtData key
+ * @param values the array of string values to store
* @return False if the key is invalid
*/
public boolean setExtData(String key, String[] values);
/**
- * Retrieves an array of Strings stored with the key.
- * This only works if the data was stored as an array. If the data
- * is not correct, this method will return null.
- * @param key The ExtData key
- * @return The value. Null if not found or the data isn't an array.
+ * Retrieves an array of Strings stored with the key. This only works if the
+ * data was stored as an array. If the data is not correct, this method will
+ * return null.
+ *
+ * @param key The ExtData key
+ * @return The value. Null if not found or the data isn't an array.
*/
public String[] getExtDataInStringArray(String key);
/**
* Removes the value of an extdata attribute.
- *
+ *
* @param type key to delete
*/
void deleteExtData(String type);
@@ -430,237 +427,252 @@ public interface IRequest {
****************************/
/**
- * Helper method to add subkey/value pair to a ExtData hashtable.
- * If the hashtable it exists, the subkey/value are added to it. Otherwise
- * a new hashtable is created.
- *
+ * Helper method to add subkey/value pair to a ExtData hashtable. If the
+ * hashtable it exists, the subkey/value are added to it. Otherwise a new
+ * hashtable is created.
+ *
* The key and subkey are lowercased because LDAP does not preserve case.
- *
- * @param key The top level key
+ *
+ * @param key The top level key
* @param subkey The hashtable data key
- * @param value The hashtable value
+ * @param value The hashtable value
* @return False if the key or subkey are invalid
*/
public boolean setExtData(String key, String subkey, String value);
/**
* Helper method to retrieve an individual value from a Hashtable value.
- * @param key the ExtData key
- * @param subkey the key in the Hashtable value (case insensitive)
+ *
+ * @param key the ExtData key
+ * @param subkey the key in the Hashtable value (case insensitive)
* @return the value corresponding to the key/subkey
*/
public String getExtDataInString(String key, String subkey);
/**
- * Helper method to store an Integer value. It converts the integer value
- * to a String and stores it.
- *
- * @param key the ExtData key
- * @param value the Integer to store (as a String)
+ * Helper method to store an Integer value. It converts the integer value to
+ * a String and stores it.
+ *
+ * @param key the ExtData key
+ * @param value the Integer to store (as a String)
* @return False if the key or value are invalid
*/
public boolean setExtData(String key, Integer value);
/**
- * Retrieves an integer value. Returns null if not found or
- * the value can't be represented as an Integer.
- *
- * @param key The ExtData key to lookup
- * @return The integer value or null if not possible.
+ * Retrieves an integer value. Returns null if not found or the value can't
+ * be represented as an Integer.
+ *
+ * @param key The ExtData key to lookup
+ * @return The integer value or null if not possible.
*/
public Integer getExtDataInInteger(String key);
/**
* Stores an array of Integers
- * @param key The extdata key
- * @param values The array of Integers to store
- * @return false if the key is invalid
+ *
+ * @param key The extdata key
+ * @param values The array of Integers to store
+ * @return false if the key is invalid
*/
public boolean setExtData(String key, Integer[] values);
/**
* Retrieves an array of Integers
- * @param key The extdata key
+ *
+ * @param key The extdata key
* @return The array of Integers or null on error.
*/
public Integer[] getExtDataInIntegerArray(String key);
/**
- * Helper method to store a BigInteger value. It converts the integer value
+ * Helper method to store a BigInteger value. It converts the integer value
* to a String and stores it.
- *
- * @param key the ExtData key
- * @param value the BigInteger to store (as a String)
+ *
+ * @param key the ExtData key
+ * @param value the BigInteger to store (as a String)
* @return False if the key or value are invalid
*/
public boolean setExtData(String key, BigInteger value);
/**
- * Retrieves a BigInteger value. Returns null if not found or
- * the value can't be represented as a BigInteger.
- *
- * @param key The ExtData key to lookup
- * @return The integer value or null if not possible.
+ * Retrieves a BigInteger value. Returns null if not found or the value
+ * can't be represented as a BigInteger.
+ *
+ * @param key The ExtData key to lookup
+ * @return The integer value or null if not possible.
*/
public BigInteger getExtDataInBigInteger(String key);
/**
* Stores an array of BigIntegers
- * @param key The extdata key
- * @param values The array of BigIntegers to store
- * @return false if the key is invalid
+ *
+ * @param key The extdata key
+ * @param values The array of BigIntegers to store
+ * @return false if the key is invalid
*/
public boolean setExtData(String key, BigInteger[] values);
/**
* Retrieves an array of BigIntegers
- * @param key The extdata key
+ *
+ * @param key The extdata key
* @return The array of BigIntegers or null on error.
*/
public BigInteger[] getExtDataInBigIntegerArray(String key);
/**
- * Helper method to store an exception.
- * It actually stores the e.toString() value.
- *
- * @param key The ExtData key to store under
- * @param e The throwable to store
- * @return False if the key is invalid.
+ * Helper method to store an exception. It actually stores the e.toString()
+ * value.
+ *
+ * @param key The ExtData key to store under
+ * @param e The throwable to store
+ * @return False if the key is invalid.
*/
public boolean setExtData(String key, Throwable e);
/**
* Stores a byte array as base64 encoded text
- * @param key The ExtData key
- * @param data The byte array to store
- * @return False if the key is invalid.
+ *
+ * @param key The ExtData key
+ * @param data The byte array to store
+ * @return False if the key is invalid.
*/
public boolean setExtData(String key, byte[] data);
/**
* Retrieves the data, which should be base64 encoded as a byte array.
- * @param key The ExtData key
- * @return The data, or null if an error occurs.
+ *
+ * @param key The ExtData key
+ * @return The data, or null if an error occurs.
*/
public byte[] getExtDataInByteArray(String key);
/**
* Stores a X509CertImpl as base64 encoded text using the getEncode()
* method.
- * @param key The ExtData key
- * @param data certificate
- * @return False if the key is invalid.
+ *
+ * @param key The ExtData key
+ * @param data certificate
+ * @return False if the key is invalid.
*/
public boolean setExtData(String key, X509CertImpl data);
/**
* Retrieves the data, which should be base64 encoded as a byte array.
- * @param key The ExtData key
- * @return The data, or null if an error occurs.
+ *
+ * @param key The ExtData key
+ * @return The data, or null if an error occurs.
*/
public X509CertImpl getExtDataInCert(String key);
/**
* Stores an array of X509CertImpls as a base64 encoded text.
+ *
* @param key The ExtData key
- * @param data The array of certs to store
+ * @param data The array of certs to store
* @return False if the key or data is invalid.
*/
public boolean setExtData(String key, X509CertImpl[] data);
/**
* Retrieves an array of X509CertImpl.
- * @param key The ExtData key
- * @return Array of certs, or null if not found or invalid data.
+ *
+ * @param key The ExtData key
+ * @return Array of certs, or null if not found or invalid data.
*/
public X509CertImpl[] getExtDataInCertArray(String key);
/**
* Stores a X509CertInfo as base64 encoded text using the getEncodedInfo()
* method.
- * @param key The ExtData key
- * @param data certificate
- * @return False if the key is invalid.
+ *
+ * @param key The ExtData key
+ * @param data certificate
+ * @return False if the key is invalid.
*/
public boolean setExtData(String key, X509CertInfo data);
/**
* Retrieves the data, which should be base64 encoded as a byte array.
- * @param key The ExtData key
- * @return The data, or null if an error occurs.
+ *
+ * @param key The ExtData key
+ * @return The data, or null if an error occurs.
*/
public X509CertInfo getExtDataInCertInfo(String key);
/**
* Stores an array of X509CertInfos as a base64 encoded text.
+ *
* @param key The ExtData key
- * @param data The array of cert infos to store
+ * @param data The array of cert infos to store
* @return False if the key or data is invalid.
*/
public boolean setExtData(String key, X509CertInfo[] data);
/**
* Retrieves an array of X509CertInfo.
- * @param key The ExtData key
- * @return Array of cert infos, or null if not found or invalid data.
+ *
+ * @param key The ExtData key
+ * @return Array of cert infos, or null if not found or invalid data.
*/
public X509CertInfo[] getExtDataInCertInfoArray(String key);
/**
* Stores an array of RevokedCertImpls as a base64 encoded text.
+ *
* @param key The ExtData key
- * @param data The array of cert infos to store
+ * @param data The array of cert infos to store
* @return False if the key or data is invalid.
*/
public boolean setExtData(String key, RevokedCertImpl[] data);
/**
* Retrieves an array of RevokedCertImpl.
- * @param key The ExtData key
- * @return Array of cert infos, or null if not found or invalid data.
+ *
+ * @param key The ExtData key
+ * @return Array of cert infos, or null if not found or invalid data.
*/
public RevokedCertImpl[] getExtDataInRevokedCertArray(String key);
/**
- * Stores the contents of the String Vector in ExtData.
- * TODO - as soon as we're allowed to use JDK5 this should be changed
- * to use Vector<String> data.
- *
+ * Stores the contents of the String Vector in ExtData. TODO - as soon as
+ * we're allowed to use JDK5 this should be changed to use Vector<String>
+ * data.
+ *
* Note that modifications to the Vector are not automatically reflected
- * after it is stored. You must call set() again to make the changes.
- *
- * @param key The extdata key to store
+ * after it is stored. You must call set() again to make the changes.
+ *
+ * @param key The extdata key to store
* @param data A vector of Strings to store
- * @return False on key error or invalid data.
+ * @return False on key error or invalid data.
*/
public boolean setExtData(String key, Vector<?> data);
/**
- * Returns a vector of strings for the key.
- * Note that the returned vector, if modified, does not make changes
- * in ExtData. You must call setExtData() to propogate changes back
- * into ExtData.
- *
- * @param key The extdata key
- * @return A Vector of strings, or null on error.
+ * Returns a vector of strings for the key. Note that the returned vector,
+ * if modified, does not make changes in ExtData. You must call setExtData()
+ * to propogate changes back into ExtData.
+ *
+ * @param key The extdata key
+ * @return A Vector of strings, or null on error.
*/
public Vector<String> getExtDataInStringVector(String key);
/**
- * Gets boolean value for given type or default value
- * if attribute is absent.
- *
+ * Gets boolean value for given type or default value if attribute is
+ * absent.
+ *
* @param type attribute type
* @param defVal default attribute value
* @return attribute value
*/
boolean getExtDataInBoolean(String type, boolean defVal);
-
/**
- * Gets extdata boolean value for given type or default value
- * if attribute is absent for this request with this prefix.
- *
+ * Gets extdata boolean value for given type or default value if attribute
+ * is absent for this request with this prefix.
+ *
* @param prefix request prefix
* @param type attribute type
* @param defVal default attribute value
@@ -668,59 +680,64 @@ public interface IRequest {
*/
public boolean getExtDataInBoolean(String prefix, String type, boolean defVal);
-
/**
* Stores an AuthToken the same as a Hashtable.
+ *
* @param key The ExtData key
- * @param data The authtoken to store
+ * @param data The authtoken to store
* @return False if the key or data is invalid.
*/
public boolean setExtData(String key, IAuthToken data);
/**
* Retrieves an authtoken.
- * @param key The ExtData key
- * @return AuthToken, or null if not found or invalid data.
+ *
+ * @param key The ExtData key
+ * @return AuthToken, or null if not found or invalid data.
*/
public IAuthToken getExtDataInAuthToken(String key);
/**
* Stores a CertificateExtensions in extdata.
+ *
* @param key The ExtData key
- * @param data The CertificateExtensions to store
+ * @param data The CertificateExtensions to store
* @return False if the key or data is invalid.
*/
public boolean setExtData(String key, CertificateExtensions data);
/**
* Retrieves the CertificateExtensions associated with the key.
- * @param key The ExtData key
- * @return the object, or null if not found or invalid data.
+ *
+ * @param key The ExtData key
+ * @return the object, or null if not found or invalid data.
*/
public CertificateExtensions getExtDataInCertExts(String key);
/**
* Stores a CertificateSubjectName in extdata.
+ *
* @param key The ExtData key
- * @param data The CertificateSubjectName to store
+ * @param data The CertificateSubjectName to store
* @return False if the key or data is invalid.
*/
public boolean setExtData(String key, CertificateSubjectName data);
/**
* Retrieves the CertificateSubjectName associated with the key.
- * @param key The ExtData key
- * @return the object, or null if not found or invalid data.
+ *
+ * @param key The ExtData key
+ * @return the object, or null if not found or invalid data.
*/
public CertificateSubjectName getExtDataInCertSubjectName(String key);
/**
- * This method returns an IAttrSet wrapper for the IRequest.
- * Use of this method is strongly discouraged. It provides extremely
- * limited functionality, and is only provided for the two places IRequest
- * is being used as such in the code. If you are considering using this
- * method, please don't.
- *
+ * This method returns an IAttrSet wrapper for the IRequest. Use of this
+ * method is strongly discouraged. It provides extremely limited
+ * functionality, and is only provided for the two places IRequest is being
+ * used as such in the code. If you are considering using this method,
+ * please don't.
+ *
* @return IAttrSet wrapper with basic "get" functionality.
* @deprecated
*/
diff --git a/pki/base/common/src/com/netscape/certsrv/request/IRequestList.java b/pki/base/common/src/com/netscape/certsrv/request/IRequestList.java
index a01ceb8c..f1979398 100644
--- a/pki/base/common/src/com/netscape/certsrv/request/IRequestList.java
+++ b/pki/base/common/src/com/netscape/certsrv/request/IRequestList.java
@@ -17,41 +17,39 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.request;
-
import java.util.Enumeration;
-
/**
- * An interface providing a list of RequestIds that match
- * some criteria. It could be a list of all elements in a
- * queue, or just some defined sub-set.
- *
+ * An interface providing a list of RequestIds that match some criteria. It
+ * could be a list of all elements in a queue, or just some defined sub-set.
+ *
* @version $Revision$, $Date$
*/
public interface IRequestList
- extends Enumeration {
+ extends Enumeration {
/**
- * Gets the next RequestId from this list. null is
- * returned when there are no more elements in the list.
- * <p>
- * Callers should be sure there is another element in the
- * list by calling hasMoreElements first.
+ * Gets the next RequestId from this list. null is returned when there are
+ * no more elements in the list.
+ * <p>
+ * Callers should be sure there is another element in the list by calling
+ * hasMoreElements first.
* <p>
+ *
* @return next request id
*/
RequestId nextRequestId();
/**
* Gets next request from the list.
- *
+ *
* @return next request
*/
public Object nextRequest();
/**
* Gets next request Object from the list.
- *
+ *
* @return next request
*/
public IRequest nextRequestObject();
diff --git a/pki/base/common/src/com/netscape/certsrv/request/IRequestListener.java b/pki/base/common/src/com/netscape/certsrv/request/IRequestListener.java
index a98cd747..382ffc31 100644
--- a/pki/base/common/src/com/netscape/certsrv/request/IRequestListener.java
+++ b/pki/base/common/src/com/netscape/certsrv/request/IRequestListener.java
@@ -17,23 +17,21 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.request;
-
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.base.ISubsystem;
-
/**
* An interface that defines abilities of request listener,
- *
+ *
* @version $Revision$, $Date$
*/
public interface IRequestListener {
/**
- * Initializes request listener for the specific subsystem
- * and configuration store.
- *
+ * Initializes request listener for the specific subsystem and configuration
+ * store.
+ *
* @param sub subsystem
* @param config configuration store
*/
@@ -41,14 +39,14 @@ public interface IRequestListener {
/**
* Accepts request.
- *
+ *
* @param request request
*/
- public void accept(IRequest request);
+ public void accept(IRequest request);
/**
* Sets attribute.
- *
+ *
* @param name attribute name
* @param val attribute value
*/
diff --git a/pki/base/common/src/com/netscape/certsrv/request/IRequestNotifier.java b/pki/base/common/src/com/netscape/certsrv/request/IRequestNotifier.java
index ba06c626..66bd3543 100644
--- a/pki/base/common/src/com/netscape/certsrv/request/IRequestNotifier.java
+++ b/pki/base/common/src/com/netscape/certsrv/request/IRequestNotifier.java
@@ -17,27 +17,25 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.request;
-
import java.util.Enumeration;
-
/**
* IRequestNotifier interface defines methods to register listeners,
- *
+ *
* @version $Revision$, $Date$
*/
public interface IRequestNotifier extends INotify {
/**
* Registers a request listener.
- *
+ *
* @param listener listener to be registered
*/
public void registerListener(IRequestListener listener);
/**
* Registers a request listener.
- *
+ *
* @param name listener name
* @param listener listener to be registered
*/
@@ -45,28 +43,28 @@ public interface IRequestNotifier extends INotify {
/**
* Removes listener from the list of registered listeners.
- *
+ *
* @param listener listener to be removed from the list
*/
public void removeListener(IRequestListener listener);
/**
* Removes listener from the list of registered listeners.
- *
+ *
* @param name listener name to be removed from the list
*/
public void removeListener(String name);
/**
* Gets list of listener names.
- *
+ *
* @return enumeration of listener names
*/
- public Enumeration<String> getListenerNames();
+ public Enumeration<String> getListenerNames();
/**
* Gets listener from the list of registered listeners.
- *
+ *
* @param name listener name
* @return listener
*/
@@ -74,55 +72,55 @@ public interface IRequestNotifier extends INotify {
/**
* Gets list of listeners.
- *
+ *
* @return enumeration of listeners
*/
- public Enumeration<IRequestListener> getListeners();
+ public Enumeration<IRequestListener> getListeners();
/**
* Gets request from publishing queue.
- *
+ *
* @return request
*/
public IRequest getRequest();
/**
* Gets number of requests in publishing queue.
- *
+ *
* @return number of requests in publishing queue
*/
public int getNumberOfRequests();
/**
* Checks if publishing queue is enabled.
- *
+ *
* @return true if publishing queue is enabled, false otherwise
*/
public boolean isPublishingQueueEnabled();
/**
* Removes a notifier thread from the pool of publishing queue threads.
- *
+ *
* @param notifierThread Thread
*/
public void removeNotifierThread(Thread notifierThread);
/**
* Notifies all registered listeners about request.
- *
+ *
* @param r request
*/
public void addToNotify(IRequest r);
/**
* Sets publishing queue parameters.
- *
+ *
* @param isPublishingQueueEnabled publishing queue switch
* @param publishingQueuePriorityLevel publishing queue priority level
* @param maxNumberOfPublishingThreads maximum number of publishing threads
* @param publishingQueuePageSize publishing queue page size
*/
- public void setPublishingQueue (boolean isPublishingQueueEnabled,
+ public void setPublishingQueue(boolean isPublishingQueueEnabled,
int publishingQueuePriorityLevel,
int maxNumberOfPublishingThreads,
int publishingQueuePageSize,
diff --git a/pki/base/common/src/com/netscape/certsrv/request/IRequestQueue.java b/pki/base/common/src/com/netscape/certsrv/request/IRequestQueue.java
index 468336b4..943fd10a 100644
--- a/pki/base/common/src/com/netscape/certsrv/request/IRequestQueue.java
+++ b/pki/base/common/src/com/netscape/certsrv/request/IRequestQueue.java
@@ -22,242 +22,222 @@ import java.math.BigInteger;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.dbs.repository.IRepository;
-
/**
- * The IRequestQueue interface defines the operations on
- * a collection of requests within the certificate server.
- * There are may several collections, such as KRA, RA and CA
- * requests. Each of these request collection has a defined
- * set of policies, a notification service (for request
- * completion) and a service routine. The request queue
- * provides an interface for creating and viewing requests,
- * as well as performing operations on them.
+ * The IRequestQueue interface defines the operations on a collection of
+ * requests within the certificate server. There are may several collections,
+ * such as KRA, RA and CA requests. Each of these request collection has a
+ * defined set of policies, a notification service (for request completion) and
+ * a service routine. The request queue provides an interface for creating and
+ * viewing requests, as well as performing operations on them.
* <p>
+ *
* @version $Revision$ $Date$
*/
public interface IRequestQueue {
/**
- * Creates a new request object. A request id is
- * assigned to it - see IRequest.getRequestId, and
- * the status is set to RequestStatus.BEGIN
+ * Creates a new request object. A request id is assigned to it - see
+ * IRequest.getRequestId, and the status is set to RequestStatus.BEGIN
* <p>
- * The request is LOCKED. The caller MUST release the
- * request object by calling releaseRequest().
+ * The request is LOCKED. The caller MUST release the request object by
+ * calling releaseRequest().
* <p>
- * TODO: provide other required values (such as type
- * and sourceId)
- *
+ * TODO: provide other required values (such as type and sourceId)
+ *
* @param requestType request type
* @return new request
* @exception EBaseException failed to create new request
*/
public IRequest newRequest(String requestType)
- throws EBaseException;
+ throws EBaseException;
/**
- * Clones a request object. A new request id is assigned
- * and all attributes of the request is copied to cloned request,
- * except for the sourceID of the original request
- * (remote authority's request Id).
+ * Clones a request object. A new request id is assigned and all attributes
+ * of the request is copied to cloned request, except for the sourceID of
+ * the original request (remote authority's request Id).
* <p>
- * The cloned request that is returned is LOCKED. The caller MUST
- * release the request object by calling releaseRequest().
- *
+ * The cloned request that is returned is LOCKED. The caller MUST release
+ * the request object by calling releaseRequest().
+ *
* @param r request to be cloned
* @return cloned request
* @exception EBaseException failed to clone request
*/
- public IRequest cloneRequest(IRequest r)
- throws EBaseException;
+ public IRequest cloneRequest(IRequest r)
+ throws EBaseException;
/**
- * Gets the Request corresponding to id.
- * Returns null if the id does not correspond
- * to a valid request id.
+ * Gets the Request corresponding to id. Returns null if the id does not
+ * correspond to a valid request id.
* <p>
* Errors may be generated for other conditions.
- *
+ *
* @param id request id
* @return found request
* @exception EBaseException failed to access request queue
*/
public IRequest findRequest(RequestId id)
- throws EBaseException;
+ throws EBaseException;
/**
- * Begins processing for this request. This call
- * is valid only on requests with status BEGIN
- * An error is generated for other cases.
- *
+ * Begins processing for this request. This call is valid only on requests
+ * with status BEGIN An error is generated for other cases.
+ *
* @param req request to be processed
* @exception EBaseException failed to process request
*/
public void processRequest(IRequest req)
- throws EBaseException;
+ throws EBaseException;
/**
* Sets request scheduler.
- *
+ *
* @param scheduler request scheduler
*/
public void setRequestScheduler(IRequestScheduler scheduler);
/**
* Gets request scheduler.
- *
+ *
* @return request scheduler
*/
public IRequestScheduler getRequestScheduler();
/**
- * Puts a new request into the PENDING state. This call is
- * only valid for requests with status BEGIN. An error is
- * generated for other cases.
+ * Puts a new request into the PENDING state. This call is only valid for
+ * requests with status BEGIN. An error is generated for other cases.
* <p>
- * This call might be used by agent servlets that want to
- * copy a previous request, and resubmit it. By putting it
- * into PENDING state, the normal agent screens can be used
- * for further processing.
- *
- * @param req
- * the request to mark PENDING
+ * This call might be used by agent servlets that want to copy a previous
+ * request, and resubmit it. By putting it into PENDING state, the normal
+ * agent screens can be used for further processing.
+ *
+ * @param req the request to mark PENDING
* @exception EBaseException failed to mark request as pending
*/
public void markRequestPending(IRequest req)
- throws EBaseException;
+ throws EBaseException;
/**
- * Clones a request object and mark it pending. A new request id is assigned
- * and all attributes of the request is copied to cloned request,
- * except for the sourceID of the original request
- * (remote authority's request Id).
+ * Clones a request object and mark it pending. A new request id is assigned
+ * and all attributes of the request is copied to cloned request, except for
+ * the sourceID of the original request (remote authority's request Id).
* <p>
- * The cloned request that is returned is LOCKED. The caller MUST
- * release the request object by calling releaseRequest().
- *
+ * The cloned request that is returned is LOCKED. The caller MUST release
+ * the request object by calling releaseRequest().
+ *
* @param r request to be cloned
* @return cloned request mark PENDING
* @exception EBaseException failed to clone or mark request
*/
- public IRequest cloneAndMarkPending(IRequest r)
- throws EBaseException;
+ public IRequest cloneAndMarkPending(IRequest r)
+ throws EBaseException;
/**
- * Approves a request. The request must be locked.
+ * Approves a request. The request must be locked.
* <p>
- * This call will fail if:
- * the request is not in PENDING state
- * the policy modules do not accept the request
+ * This call will fail if: the request is not in PENDING state the policy
+ * modules do not accept the request
* <p>
- * If the policy modules reject the request, then the request
- * will remain in the PENDING state. Messages from the policy
- * module can be display to the agent to indicate the source
- * of the problem.
+ * If the policy modules reject the request, then the request will remain in
+ * the PENDING state. Messages from the policy module can be display to the
+ * agent to indicate the source of the problem.
* <p>
- * The request processing code adds an AgentApproval to this
- * request that contains the authentication id of the agent. This
- * data is retrieved from the Session object (qv).
- *
- * @param request
- * the request that is being approved
+ * The request processing code adds an AgentApproval to this request that
+ * contains the authentication id of the agent. This data is retrieved from
+ * the Session object (qv).
+ *
+ * @param request the request that is being approved
* @exception EBaseException failed to approve request
*/
public void approveRequest(IRequest request)
- throws EBaseException;
+ throws EBaseException;
/**
- * Rejects a request. The request must be locked.
+ * Rejects a request. The request must be locked.
* <p>
- * This call will fail if:
- * the request is not in PENDING state
+ * This call will fail if: the request is not in PENDING state
* <p>
- * The agent servlet (or other application) may wish to store
- * AgentMessage values to indicate the reason for the action
- *
- * @param request
- * the request that is being rejected
+ * The agent servlet (or other application) may wish to store AgentMessage
+ * values to indicate the reason for the action
+ *
+ * @param request the request that is being rejected
* @exception EBaseException failed to reject request
*/
public void rejectRequest(IRequest request)
- throws EBaseException;
+ throws EBaseException;
/**
- * Cancels a request. The request must be locked.
+ * Cancels a request. The request must be locked.
* <p>
- * This call will fail if:
- * the request is not in PENDING state
+ * This call will fail if: the request is not in PENDING state
* <p>
- * The agent servlet (or other application) may wish to store
- * AgentMessage values to indicate the reason for the action
- *
- * @param request
- * the request that is being canceled
+ * The agent servlet (or other application) may wish to store AgentMessage
+ * values to indicate the reason for the action
+ *
+ * @param request the request that is being canceled
* @exception EBaseException failed to cancel request
*/
public void cancelRequest(IRequest request)
- throws EBaseException;
+ throws EBaseException;
/**
* Updates the request in the permanent data store.
* <p>
- * This call can be made after changing a value like source
- * id or owner, to force the new value to be written.
+ * This call can be made after changing a value like source id or owner, to
+ * force the new value to be written.
* <p>
* The request must be locked to make this call.
- *
- * @param request
- * the request that is being updated
+ *
+ * @param request the request that is being updated
* @exception EBaseException failed to update request
*/
public void updateRequest(IRequest request)
- throws EBaseException;
+ throws EBaseException;
/**
- * Returns an enumerator that lists all RequestIds in the
- * queue. The caller should use the RequestIds to locate
- * each request by calling findRequest().
+ * Returns an enumerator that lists all RequestIds in the queue. The caller
+ * should use the RequestIds to locate each request by calling
+ * findRequest().
* <p>
- * NOTE: This interface will not be useful for large databases.
- * This needs to be replace by a VLV (paged) search object.
- *
+ * NOTE: This interface will not be useful for large databases. This needs
+ * to be replace by a VLV (paged) search object.
+ *
* @return request list
*/
public IRequestList listRequests();
/**
- * Returns an enumerator that lists all RequestIds for requests
- * that are in the given status. For example, all the PENDING
- * requests could be listed by specifying RequestStatus.PENDING
- * as the <i>status</i> argument
+ * Returns an enumerator that lists all RequestIds for requests that are in
+ * the given status. For example, all the PENDING requests could be listed
+ * by specifying RequestStatus.PENDING as the <i>status</i> argument
* <p>
- * NOTE: This interface will not be useful for large databases.
- * This needs to be replace by a VLV (paged) search object.
- *
+ * NOTE: This interface will not be useful for large databases. This needs
+ * to be replace by a VLV (paged) search object.
+ *
* @param status request status
* @return request list
*/
public IRequestList listRequestsByStatus(RequestStatus status);
/**
- * Returns an enumerator that lists all RequestIds for requests
- * that match the filter.
+ * Returns an enumerator that lists all RequestIds for requests that match
+ * the filter.
* <p>
- * NOTE: This interface will not be useful for large databases.
- * This needs to be replace by a VLV (paged) search object.
- *
+ * NOTE: This interface will not be useful for large databases. This needs
+ * to be replace by a VLV (paged) search object.
+ *
* @param filter search filter
* @return request list
*/
public IRequestList listRequestsByFilter(String filter);
/**
- * Returns an enumerator that lists all RequestIds for requests
- * that match the filter.
+ * Returns an enumerator that lists all RequestIds for requests that match
+ * the filter.
* <p>
- * NOTE: This interface will not be useful for large databases.
- * This needs to be replace by a VLV (paged) search object.
- *
+ * NOTE: This interface will not be useful for large databases. This needs
+ * to be replace by a VLV (paged) search object.
+ *
* @param filter search filter
* @param maxSize max size to return
* @return request list
@@ -265,12 +245,12 @@ public interface IRequestQueue {
public IRequestList listRequestsByFilter(String filter, int maxSize);
/**
- * Returns an enumerator that lists all RequestIds for requests
- * that match the filter.
+ * Returns an enumerator that lists all RequestIds for requests that match
+ * the filter.
* <p>
- * NOTE: This interface will not be useful for large databases.
- * This needs to be replace by a VLV (paged) search object.
- *
+ * NOTE: This interface will not be useful for large databases. This needs
+ * to be replace by a VLV (paged) search object.
+ *
* @param filter search filter
* @param maxSize max size to return
* @param timeLimit timeout value for the search
@@ -281,31 +261,30 @@ public interface IRequestQueue {
/**
* Gets requests that are pending on handling by the service
* <p>
+ *
* @return list of pending requests
*/
// public IRequestList listServicePendingRequests();
/**
* Locates a request from the SourceId.
- *
- * @param id
- * a unique identifier for the record that is based on the source
- * of the request, and possibly an identify assigned by the source.
- * @return
- * The requestid corresponding to this source id. null is
- * returned if the source id does not exist.
+ *
+ * @param id a unique identifier for the record that is based on the source
+ * of the request, and possibly an identify assigned by the
+ * source.
+ * @return The requestid corresponding to this source id. null is returned
+ * if the source id does not exist.
*/
public RequestId findRequestBySourceId(String id);
/**
* Locates all requests with a particular SourceId.
* <p>
- * @param id
- * an identifier for the record that is based on the source
- * of the request
- * @return
- * A list of requests corresponding to this source id. null is
- * returned if the source id does not exist.
+ *
+ * @param id an identifier for the record that is based on the source of the
+ * request
+ * @return A list of requests corresponding to this source id. null is
+ * returned if the source id does not exist.
*/
public IRequestList findRequestsBySourceId(String id);
@@ -313,26 +292,27 @@ public interface IRequestQueue {
* Releases the LOCK on a request obtained from findRequest() or
* newRequest()
* <p>
+ *
* @param r request
*/
public void releaseRequest(IRequest r);
/**
- * Marks as serviced after destination authority has serviced request.
- * Used by connector.
- *
+ * Marks as serviced after destination authority has serviced request. Used
+ * by connector.
+ *
* @param r request
*/
public void markAsServiced(IRequest r);
/**
- * Resends requests
+ * Resends requests
*/
public void recover();
/**
* Gets a pageable list of IRequest entries in this queue.
- *
+ *
* @param pageSize page size
* @return request list
*/
@@ -340,18 +320,19 @@ public interface IRequestQueue {
/**
* Gets a pageable list of IRequest entries in this queue.
- *
+ *
* @param filter search filter
* @param pageSize page size
* @param sortKey the attributes to sort by
* @return request list
*/
public IRequestVirtualList getPagedRequestsByFilter(String filter,
- int pageSize,
- String sortKey);
+ int pageSize,
+ String sortKey);
+
/**
* Gets a pageable list of IRequest entries in this queue.
- *
+ *
* @param fromId request id to start with
* @param filter search filter
* @param pageSize page size
@@ -359,14 +340,14 @@ public interface IRequestQueue {
* @return request list
*/
public IRequestVirtualList getPagedRequestsByFilter(RequestId fromId,
- String filter,
- int pageSize,
+ String filter,
+ int pageSize,
String sortKey);
/**
- * Gets a pageable list of IRequest entries in this queue. This
- * jumps right to the end of the list
- *
+ * Gets a pageable list of IRequest entries in this queue. This jumps right
+ * to the end of the list
+ *
* @param fromId request id to start with
* @param jumpToEnd jump to end of list (set fromId to null)
* @param filter search filter
@@ -375,26 +356,24 @@ public interface IRequestQueue {
* @return request list
*/
public IRequestVirtualList getPagedRequestsByFilter(RequestId fromId,
- boolean jumpToEnd, String filter,
- int pageSize,
+ boolean jumpToEnd, String filter,
+ int pageSize,
String sortKey);
-
/**
* Retrieves the notifier for pending request.
- *
+ *
* @return notifier for pending request
*/
public INotify getPendingNotify();
-
- public BigInteger getLastRequestIdInRange(BigInteger reqId_low_bound, BigInteger reqId_upper_bound);
+ public BigInteger getLastRequestIdInRange(BigInteger reqId_low_bound, BigInteger reqId_upper_bound);
/**
* Resets serial number.
*/
public void resetSerialNumber(BigInteger serial) throws EBaseException;
-
+
/**
* Removes all objects with this repository.
*/
@@ -402,7 +381,7 @@ public interface IRequestQueue {
/**
* Gets request repository.
- *
+ *
* @return request repository
*/
public IRepository getRequestRepository();
diff --git a/pki/base/common/src/com/netscape/certsrv/request/IRequestRecord.java b/pki/base/common/src/com/netscape/certsrv/request/IRequestRecord.java
index 53a3e37b..d4e11a4f 100644
--- a/pki/base/common/src/com/netscape/certsrv/request/IRequestRecord.java
+++ b/pki/base/common/src/com/netscape/certsrv/request/IRequestRecord.java
@@ -17,22 +17,21 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.request;
-
import java.util.Enumeration;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.dbs.IDBObj;
-
/**
- * A request record is the stored version of a request.
- * It has a set of attributes that are mapped into LDAP
- * attributes for actual directory operations.
+ * A request record is the stored version of a request. It has a set of
+ * attributes that are mapped into LDAP attributes for actual directory
+ * operations.
* <p>
+ *
* @version $Revision$ $Date$
*/
public interface IRequestRecord
- extends IDBObj {
+ extends IDBObj {
//
// The names of the attributes stored in this record
//
@@ -57,28 +56,28 @@ public interface IRequestRecord
public final static String ATTR_REQUEST_TYPE = "requestType";
- // Placeholder for ExtAttr data. this attribute is not in LDAP, but
+ // Placeholder for ExtAttr data. this attribute is not in LDAP, but
// is used to trigger the ExtAttrDynMapper during conversion between LDAP
// and the RequestRecord.
public final static String ATTR_EXT_DATA = "requestExtData";
/**
* Gets the request id.
- *
+ *
* @return request id
*/
public RequestId getRequestId();
/**
* Gets attribute names of the request.
- *
+ *
* @return list of attribute names
*/
public Enumeration<String> getAttrNames();
/**
* Gets the request attribute value by the name.
- *
+ *
* @param name attribute name
* @return attribute value
*/
@@ -86,7 +85,7 @@ public interface IRequestRecord
/**
* Sets new attribute for the request.
- *
+ *
* @param name attribute name
* @param o attribute value
*/
@@ -94,20 +93,20 @@ public interface IRequestRecord
/**
* Removes attribute from the request.
- *
+ *
* @param name attribute name
*/
public void delete(String name)
- throws EBaseException;
+ throws EBaseException;
/**
* Gets attribute list of the request.
- *
+ *
* @return attribute list
*/
public Enumeration<String> getElements();
// IDBObj.getSerializableAttrNames
- //public Enumeration getSerializableAttrNames();
+ // public Enumeration getSerializableAttrNames();
}
diff --git a/pki/base/common/src/com/netscape/certsrv/request/IRequestScheduler.java b/pki/base/common/src/com/netscape/certsrv/request/IRequestScheduler.java
index 198092fc..2d1cb89d 100644
--- a/pki/base/common/src/com/netscape/certsrv/request/IRequestScheduler.java
+++ b/pki/base/common/src/com/netscape/certsrv/request/IRequestScheduler.java
@@ -17,16 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.request;
-
//import java.io.Serializable;
-
-
/**
- * This is an interface to a request scheduler that prioritizes
- * the threads based on the request processing order.
- * The request that enters the request queue first should
- * be processed first.
+ * This is an interface to a request scheduler that prioritizes the threads
+ * based on the request processing order. The request that enters the request
+ * queue first should be processed first.
*
* @version $Revision$ $Date$
*/
@@ -34,14 +30,14 @@ public interface IRequestScheduler {
/**
* Request entered the request queue processing.
- *
+ *
* @param r request
*/
public void requestIn(IRequest r);
/**
* Request exited the request queue processing.
- *
+ *
* @param r request
*/
public void requestOut(IRequest r);
diff --git a/pki/base/common/src/com/netscape/certsrv/request/IRequestSubsystem.java b/pki/base/common/src/com/netscape/certsrv/request/IRequestSubsystem.java
index c32c6698..f7d0d80d 100644
--- a/pki/base/common/src/com/netscape/certsrv/request/IRequestSubsystem.java
+++ b/pki/base/common/src/com/netscape/certsrv/request/IRequestSubsystem.java
@@ -17,89 +17,78 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.request;
-
import com.netscape.certsrv.base.EBaseException;
-
/**
- * This interface defines storage of request objects
- * in the local database.
+ * This interface defines storage of request objects in the local database.
* <p>
+ *
* @version $Revision$, $Date$
*/
public interface IRequestSubsystem {
public static final String SUB_ID = "request";
/**
- * Creates a new request queue.
- * (Currently unimplemented. Just use getRequestQueue to create
- * an in-memory queue.)
+ * Creates a new request queue. (Currently unimplemented. Just use
+ * getRequestQueue to create an in-memory queue.)
* <p>
- * @param name The name of the queue object. This name can be used
- * in getRequestQueue to retrieve the queue later.
+ *
+ * @param name The name of the queue object. This name can be used in
+ * getRequestQueue to retrieve the queue later.
* @exception EBaseException failed to create request queue
*/
public void createRequestQueue(String name)
- throws EBaseException;
+ throws EBaseException;
/**
- * Retrieves a request queue. This operation should only be done
- * once on each queue. For example, the RA subsystem should retrieve
- * its queue, and store it somewhere for use by related services, and
- * servlets.
+ * Retrieves a request queue. This operation should only be done once on
+ * each queue. For example, the RA subsystem should retrieve its queue, and
+ * store it somewhere for use by related services, and servlets.
* <p>
- * WARNING: retrieving the same queue twice with result in multi-thread
- * race conditions.
+ * WARNING: retrieving the same queue twice with result in multi-thread race
+ * conditions.
* <p>
- * @param name
- * the name of the request queue. (Ex: "ca" "ra")
- * @param p
- * A policy enforcement module. This object is called to make
- * adjustments to the request, and decide whether it needs agent
- * approval.
- * @param s
- * The service object. This object actually performs the request
- * after it is finalized and approved.
- * @param n
- * A notifier object (optional). The notify() method of this object
- * is invoked when the request is completed (COMPLETE, REJECTED or
- * CANCELED states).
+ *
+ * @param name the name of the request queue. (Ex: "ca" "ra")
+ * @param p A policy enforcement module. This object is called to make
+ * adjustments to the request, and decide whether it needs agent
+ * approval.
+ * @param s The service object. This object actually performs the request
+ * after it is finalized and approved.
+ * @param n A notifier object (optional). The notify() method of this object
+ * is invoked when the request is completed (COMPLETE, REJECTED
+ * or CANCELED states).
* @exception EBaseException failed to retrieve request queue
*/
public IRequestQueue
- getRequestQueue(String name, int increment, IPolicy p, IService s, INotify n)
- throws EBaseException;
+ getRequestQueue(String name, int increment, IPolicy p, IService s, INotify n)
+ throws EBaseException;
/**
- * Retrieves a request queue. This operation should only be done
- * once on each queue. For example, the RA subsystem should retrieve
- * its queue, and store it somewhere for use by related services, and
- * servlets.
+ * Retrieves a request queue. This operation should only be done once on
+ * each queue. For example, the RA subsystem should retrieve its queue, and
+ * store it somewhere for use by related services, and servlets.
* <p>
- * WARNING: retrieving the same queue twice with result in multi-thread
- * race conditions.
+ * WARNING: retrieving the same queue twice with result in multi-thread race
+ * conditions.
* <p>
- * @param name
- * the name of the request queue. (Ex: "ca" "ra")
- * @param p
- * A policy enforcement module. This object is called to make
- * adjustments to the request, and decide whether it needs agent
- * approval.
- * @param s
- * The service object. This object actually performs the request
- * after it is finalized and approved.
- * @param n
- * A notifier object (optional). The notify() method of this object
- * is invoked when the request is completed (COMPLETE, REJECTED or
- * CANCELED states).
- * @param pendingNotifier
- * A notifier object (optional). Like the 'n' argument, except the
- * notification happens if the request is made PENDING. May be the
- * same as the 'n' argument if desired.
+ *
+ * @param name the name of the request queue. (Ex: "ca" "ra")
+ * @param p A policy enforcement module. This object is called to make
+ * adjustments to the request, and decide whether it needs agent
+ * approval.
+ * @param s The service object. This object actually performs the request
+ * after it is finalized and approved.
+ * @param n A notifier object (optional). The notify() method of this object
+ * is invoked when the request is completed (COMPLETE, REJECTED
+ * or CANCELED states).
+ * @param pendingNotifier A notifier object (optional). Like the 'n'
+ * argument, except the notification happens if the request is
+ * made PENDING. May be the same as the 'n' argument if desired.
* @exception EBaseException failed to retrieve request queue
*/
public IRequestQueue
- getRequestQueue(String name, int increment, IPolicy p, IService s, INotify n,
- INotify pendingNotifier)
- throws EBaseException;
+ getRequestQueue(String name, int increment, IPolicy p, IService s, INotify n,
+ INotify pendingNotifier)
+ throws EBaseException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/request/IRequestVirtualList.java b/pki/base/common/src/com/netscape/certsrv/request/IRequestVirtualList.java
index 4d877a77..faf8e07e 100644
--- a/pki/base/common/src/com/netscape/certsrv/request/IRequestVirtualList.java
+++ b/pki/base/common/src/com/netscape/certsrv/request/IRequestVirtualList.java
@@ -17,25 +17,25 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.request;
-
/**
* This interface defines access to request virtual list.
* <p>
+ *
* @version $Revision$, $Date$
*/
public interface IRequestVirtualList {
/**
- * Gets the total size of the result set. Elements of the
- * list are numbered from 0..(size-1)
- *
+ * Gets the total size of the result set. Elements of the list are numbered
+ * from 0..(size-1)
+ *
* @return size of the result set
*/
int getSize();
/**
* Gets the element at the specified index
- *
+ *
* @param index index of the element
* @return specified request
*/
@@ -43,7 +43,7 @@ public interface IRequestVirtualList {
/**
* Gets the current index
- *
+ *
* @return current index
*/
int getCurrentIndex();
diff --git a/pki/base/common/src/com/netscape/certsrv/request/IService.java b/pki/base/common/src/com/netscape/certsrv/request/IService.java
index aeaf757a..20e87f12 100644
--- a/pki/base/common/src/com/netscape/certsrv/request/IService.java
+++ b/pki/base/common/src/com/netscape/certsrv/request/IService.java
@@ -17,32 +17,29 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.request;
-
import com.netscape.certsrv.base.EBaseException;
-
/**
- * This interface defines how requests are serviced.
- * This covers certificate generation, revocation, renewals,
- * revocation checking, and much more.
+ * This interface defines how requests are serviced. This covers certificate
+ * generation, revocation, renewals, revocation checking, and much more.
* <p>
+ *
* @version $Revision$, $Date$
*/
public interface IService {
/**
- * Performs the service (such as certificate generation)
- * represented by this request.
+ * Performs the service (such as certificate generation) represented by this
+ * request.
* <p>
- * @param request
- * The request that needs service. The service may use
- * attributes stored in the request, and may update the
- * values, or store new ones.
- * @return
- * an indication of whether this request is still pending.
- * 'false' means the request will wait for further notification.
+ *
+ * @param request The request that needs service. The service may use
+ * attributes stored in the request, and may update the values,
+ * or store new ones.
+ * @return an indication of whether this request is still pending. 'false'
+ * means the request will wait for further notification.
* @exception EBaseException indicates major processing failure.
*/
boolean serviceRequest(IRequest request)
- throws EBaseException;
+ throws EBaseException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/request/PolicyMessage.java b/pki/base/common/src/com/netscape/certsrv/request/PolicyMessage.java
index 13cec161..dc0c6cbb 100644
--- a/pki/base/common/src/com/netscape/certsrv/request/PolicyMessage.java
+++ b/pki/base/common/src/com/netscape/certsrv/request/PolicyMessage.java
@@ -17,18 +17,17 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.request;
-
import com.netscape.certsrv.base.EBaseException;
-
/**
- * A (localizable) message recorded by a policy module that describes
- * the reason for rejecting a request.
+ * A (localizable) message recorded by a policy module that describes the reason
+ * for rejecting a request.
* <p>
+ *
* @version $Revision$, $Date$
*/
public class PolicyMessage
- extends EBaseException {
+ extends EBaseException {
/**
*
@@ -38,6 +37,7 @@ public class PolicyMessage
/**
* Class constructor that registers policy message.
* <p>
+ *
* @param message message string
*/
public PolicyMessage(String message) {
diff --git a/pki/base/common/src/com/netscape/certsrv/request/PolicyResult.java b/pki/base/common/src/com/netscape/certsrv/request/PolicyResult.java
index 2750e3d8..c7cad94f 100644
--- a/pki/base/common/src/com/netscape/certsrv/request/PolicyResult.java
+++ b/pki/base/common/src/com/netscape/certsrv/request/PolicyResult.java
@@ -17,10 +17,9 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.request;
-
/**
* This class defines results for policy actions.
- *
+ *
* @version $Revision$, $Date$
*/
public final class PolicyResult {
diff --git a/pki/base/common/src/com/netscape/certsrv/request/RequestId.java b/pki/base/common/src/com/netscape/certsrv/request/RequestId.java
index 01bd65d3..f8a4133d 100644
--- a/pki/base/common/src/com/netscape/certsrv/request/RequestId.java
+++ b/pki/base/common/src/com/netscape/certsrv/request/RequestId.java
@@ -17,32 +17,34 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.request;
-
/**
- * The RequestId class represents the identifier for a particular
- * request within a request queue. This identifier may be used to
- * retrieve the request object itself from the request queue.
+ * The RequestId class represents the identifier for a particular request within
+ * a request queue. This identifier may be used to retrieve the request object
+ * itself from the request queue.
* <p>
+ *
* @version $Revision$ $Date$
*/
public final class RequestId {
/**
- * Creates a new RequestId from its string representation.
+ * Creates a new RequestId from its string representation.
* <p>
- * @param id
- * a string containing the decimal (base 10) value for the identifier.
+ *
+ * @param id a string containing the decimal (base 10) value for the
+ * identifier.
*/
public RequestId(String id) {
mString = id;
}
/**
- * Converts the RequestId into its string representation. The string
- * form can be stored in a database (such as the LDAP directory)
+ * Converts the RequestId into its string representation. The string form
+ * can be stored in a database (such as the LDAP directory)
* <p>
- * @return
- * a string containing the decimal (base 10) value for the identifier.
+ *
+ * @return a string containing the decimal (base 10) value for the
+ * identifier.
*/
public String toString() {
return mString;
@@ -51,6 +53,7 @@ public final class RequestId {
/**
* Implements Object.hashCode.
* <p>
+ *
* @return hash code of the object
*/
public int hashCode() {
@@ -60,7 +63,8 @@ public final class RequestId {
/**
* Implements Object.equals.
* <p>
- * @param obj object to compare
+ *
+ * @param obj object to compare
* @return true if objects are equal
*/
public boolean equals(Object obj) {
diff --git a/pki/base/common/src/com/netscape/certsrv/request/RequestStatus.java b/pki/base/common/src/com/netscape/certsrv/request/RequestStatus.java
index ad3b91e7..059e2b0d 100644
--- a/pki/base/common/src/com/netscape/certsrv/request/RequestStatus.java
+++ b/pki/base/common/src/com/netscape/certsrv/request/RequestStatus.java
@@ -17,21 +17,19 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.request;
-
/**
- * The RequestStatus class represents the current state of a request
- * in a request queue. The state of the request changes as actions
- * are performed on it.
- *
- * The request is created in the BEGIN state, then general progresses
- * through the PENDING, APPROVED, SVC_PENDING, and COMPLETE states.
- * Some requests may bypass the PENDING state if no agent action is
- * required.
- *
- * Requests may be CANCELED (not implemented) or REJECTED. These are
- * error conditions, and usually result because the request was invalid
- * or was not approved by an agent.
- *
+ * The RequestStatus class represents the current state of a request in a
+ * request queue. The state of the request changes as actions are performed on
+ * it.
+ *
+ * The request is created in the BEGIN state, then general progresses through
+ * the PENDING, APPROVED, SVC_PENDING, and COMPLETE states. Some requests may
+ * bypass the PENDING state if no agent action is required.
+ *
+ * Requests may be CANCELED (not implemented) or REJECTED. These are error
+ * conditions, and usually result because the request was invalid or was not
+ * approved by an agent.
+ *
* @version $Revision$ $Date$
*/
public final class RequestStatus {
@@ -44,22 +42,22 @@ public final class RequestStatus {
public static String COMPLETE_STRING = "complete";
/**
- * The initial state of a request. Requests in this state have not
- * been review by policy.
- *
- * While in this state the source of the request (usually the servlet,
- * but it could be some other protocol module, such as email)
- * should populate the request with data need to service it.
+ * The initial state of a request. Requests in this state have not been
+ * review by policy.
+ *
+ * While in this state the source of the request (usually the servlet, but
+ * it could be some other protocol module, such as email) should populate
+ * the request with data need to service it.
*/
public static RequestStatus BEGIN = new RequestStatus(BEGIN_STRING);
/**
- * The state of a request that is waiting for action by an agent.
- * When the agent approves or rejects the request, process will
- * continue as appropriate.
- *
- * In this state there may be PolicyMessages present that indicate
- * the reason for the pending status.
+ * The state of a request that is waiting for action by an agent. When the
+ * agent approves or rejects the request, process will continue as
+ * appropriate.
+ *
+ * In this state there may be PolicyMessages present that indicate the
+ * reason for the pending status.
*/
public static RequestStatus PENDING = new RequestStatus(PENDING_STRING);
@@ -67,80 +65,84 @@ public final class RequestStatus {
* The state of a request that has been approved by an agent, or
* automatically by the policy engine, but have not been successfully
* transmitted to the service module.
- *
- * These requests are resent to the service during the recovery
- * process that runs at server startup.
+ *
+ * These requests are resent to the service during the recovery process that
+ * runs at server startup.
*/
public static RequestStatus APPROVED = new RequestStatus(APPROVED_STRING);
/**
- * The state of a request that has been sent to the service, but
- * has not been fully processed. The service will invoke the
- * serviceComplete() method to cause processing to continue.
+ * The state of a request that has been sent to the service, but has not
+ * been fully processed. The service will invoke the serviceComplete()
+ * method to cause processing to continue.
*/
public static RequestStatus SVC_PENDING =
- new RequestStatus(SVC_PENDING_STRING);
+ new RequestStatus(SVC_PENDING_STRING);
/**
- * Not implemented. This is intended to be a final state that is
- * reached when a request is removed from the processing queue without
- * normal notification occurring. (see REJECTED)
+ * Not implemented. This is intended to be a final state that is reached
+ * when a request is removed from the processing queue without normal
+ * notification occurring. (see REJECTED)
*/
public static RequestStatus CANCELED = new RequestStatus(CANCELED_STRING);
/**
- * The state of a request after it is rejected. When a request is
- * rejected, the notifier is called prior to making the finl status
- * change.
- *
- * Rejected requests may have PolicyMessages indicating the reason for
- * the rejection, or AgentMessages, which allow the agent to give
- * reasons for the action.
+ * The state of a request after it is rejected. When a request is rejected,
+ * the notifier is called prior to making the finl status change.
+ *
+ * Rejected requests may have PolicyMessages indicating the reason for the
+ * rejection, or AgentMessages, which allow the agent to give reasons for
+ * the action.
*/
public static RequestStatus REJECTED = new RequestStatus(REJECTED_STRING);
/**
- * The normal final state of a request. The completion status attribute
- * gives other information about the request. The request is not
- * necessarily successful, but may indicated that service processing
- * did not succeed.
+ * The normal final state of a request. The completion status attribute
+ * gives other information about the request. The request is not necessarily
+ * successful, but may indicated that service processing did not succeed.
*/
public static RequestStatus COMPLETE = new RequestStatus(COMPLETE_STRING);
/**
- * Converts a string name for a request status into the
- * request status enum object.
+ * Converts a string name for a request status into the request status enum
+ * object.
* <p>
- * @param s
- * The string representation of the state.
- * @return
- * request status
+ *
+ * @param s The string representation of the state.
+ * @return request status
*/
public static RequestStatus fromString(String s) {
- if (s.equals(BEGIN_STRING)) return BEGIN;
- if (s.equals(PENDING_STRING)) return PENDING;
- if (s.equals(APPROVED_STRING)) return APPROVED;
- if (s.equals(SVC_PENDING_STRING)) return SVC_PENDING;
- if (s.equals(CANCELED_STRING)) return CANCELED;
- if (s.equals(REJECTED_STRING)) return REJECTED;
- if (s.equals(COMPLETE_STRING)) return COMPLETE;
+ if (s.equals(BEGIN_STRING))
+ return BEGIN;
+ if (s.equals(PENDING_STRING))
+ return PENDING;
+ if (s.equals(APPROVED_STRING))
+ return APPROVED;
+ if (s.equals(SVC_PENDING_STRING))
+ return SVC_PENDING;
+ if (s.equals(CANCELED_STRING))
+ return CANCELED;
+ if (s.equals(REJECTED_STRING))
+ return REJECTED;
+ if (s.equals(COMPLETE_STRING))
+ return COMPLETE;
return null;
}
/**
- * Returns the string form of the RequestStatus, which may be used
- * to record the status in a database.
- *
+ * Returns the string form of the RequestStatus, which may be used to record
+ * the status in a database.
+ *
* @return request status
*/
public String toString() {
return mString;
}
-
+
/**
* Class constructor. Creates request status from the string.
- *
+ *
* @param string string describing request status
*/
private RequestStatus(String string) {
@@ -151,21 +153,25 @@ public final class RequestStatus {
/**
* Compares request status with specified string.
- *
+ *
* @param string string describing request status
*/
public boolean equals(String string) {
- if (string.equals(mString)) return true;
- else return false;
+ if (string.equals(mString))
+ return true;
+ else
+ return false;
}
-
+
/**
* Compares current request status with request status.
- *
+ *
* @param rs request status
*/
public boolean equals(RequestStatus rs) {
- if (mString.equals(rs.mString)) return true;
- else return false;
+ if (mString.equals(rs.mString))
+ return true;
+ else
+ return false;
}
}
diff --git a/pki/base/common/src/com/netscape/certsrv/request/ldap/IRequestMod.java b/pki/base/common/src/com/netscape/certsrv/request/ldap/IRequestMod.java
index 1fc0657f..c1e153a8 100644
--- a/pki/base/common/src/com/netscape/certsrv/request/ldap/IRequestMod.java
+++ b/pki/base/common/src/com/netscape/certsrv/request/ldap/IRequestMod.java
@@ -25,31 +25,31 @@ import com.netscape.certsrv.request.RequestStatus;
/**
* This interface defines how to update request record.
* <p>
+ *
* @version $Revision$, $Date$
*/
-public interface IRequestMod
-{
- /**
+public interface IRequestMod {
+ /**
* Modifies request status.
- *
+ *
* @param r request
* @param s request status
*/
- void modRequestStatus(IRequest r, RequestStatus s);
+ void modRequestStatus(IRequest r, RequestStatus s);
- /**
+ /**
* Modifies request creation time.
- *
+ *
* @param r request
* @param d date
*/
- void modCreationTime(IRequest r, Date d);
+ void modCreationTime(IRequest r, Date d);
- /**
+ /**
* Modifies request modification time.
- *
+ *
* @param r request
* @param d date
*/
- void modModificationTime(IRequest r, Date d);
+ void modModificationTime(IRequest r, Date d);
}
diff --git a/pki/base/common/src/com/netscape/certsrv/security/Credential.java b/pki/base/common/src/com/netscape/certsrv/security/Credential.java
index 9aff49ad..ea6ca400 100644
--- a/pki/base/common/src/com/netscape/certsrv/security/Credential.java
+++ b/pki/base/common/src/com/netscape/certsrv/security/Credential.java
@@ -17,12 +17,10 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.security;
-
/**
- * A class represents a credential. A credential contains
- * information that identifies a user. In this case,
- * identifier and password are used.
- *
+ * A class represents a credential. A credential contains information that
+ * identifies a user. In this case, identifier and password are used.
+ *
* @version $Revision$, $Date$
*/
public class Credential implements java.io.Serializable {
@@ -36,7 +34,7 @@ public class Credential implements java.io.Serializable {
/**
* Constructs credential object.
- *
+ *
* @param id user id
* @param password user password
*/
@@ -44,10 +42,10 @@ public class Credential implements java.io.Serializable {
mId = id;
mPassword = password;
}
-
+
/**
* Retrieves identifier.
- *
+ *
* @return user id
*/
public String getIdentifier() {
@@ -56,7 +54,7 @@ public class Credential implements java.io.Serializable {
/**
* Retrieves password.
- *
+ *
* @return user password
*/
public String getPassword() {
diff --git a/pki/base/common/src/com/netscape/certsrv/security/ICryptoSubsystem.java b/pki/base/common/src/com/netscape/certsrv/security/ICryptoSubsystem.java
index ab910b37..09ac7342 100644
--- a/pki/base/common/src/com/netscape/certsrv/security/ICryptoSubsystem.java
+++ b/pki/base/common/src/com/netscape/certsrv/security/ICryptoSubsystem.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.security;
-
import java.io.IOException;
import java.security.KeyPair;
import java.security.cert.CertificateException;
@@ -37,11 +36,10 @@ import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.base.ISubsystem;
import com.netscape.certsrv.common.NameValuePairs;
-
/**
- * This interface represents the cryptographics subsystem
- * that provides all the security related functions.
- *
+ * This interface represents the cryptographics subsystem that provides all the
+ * security related functions.
+ *
* @version $Revision$, $Date$
*/
public interface ICryptoSubsystem extends ISubsystem {
@@ -49,9 +47,9 @@ public interface ICryptoSubsystem extends ISubsystem {
public static final String ID = "jss";
/**
- * Retrieves a list of nicknames of certificates that are
- * in the installed tokens.
- *
+ * Retrieves a list of nicknames of certificates that are in the installed
+ * tokens.
+ *
* @return a list of comma-separated nicknames
* @exception EBaseException failed to retrieve nicknames
*/
@@ -59,7 +57,7 @@ public interface ICryptoSubsystem extends ISubsystem {
/**
* Retrieves certificate in pretty-print format by the nickname.
- *
+ *
* @param nickname nickname of certificate
* @param date not after of the returned certificate must be date
* @param locale user locale
@@ -67,50 +65,53 @@ public interface ICryptoSubsystem extends ISubsystem {
* @exception EBaseException failed to retrieve certificate
*/
public String getCertPrettyPrint(String nickname, String date,
- Locale locale) throws EBaseException;
+ Locale locale) throws EBaseException;
+
public String getRootCertTrustBit(String nickname, String serialno,
- String issuerName) throws EBaseException;
- public String getCertPrettyPrint(String nickname, String serialno,
- String issuername, Locale locale) throws EBaseException;
- public String getCertPrettyPrintAndFingerPrint(String nickname, String serialno,
- String issuername, Locale locale) throws EBaseException;
+ String issuerName) throws EBaseException;
+
+ public String getCertPrettyPrint(String nickname, String serialno,
+ String issuername, Locale locale) throws EBaseException;
+
+ public String getCertPrettyPrintAndFingerPrint(String nickname, String serialno,
+ String issuername, Locale locale) throws EBaseException;
/**
* Retrieves the certificate in the pretty print format.
- *
+ *
* @param b64E certificate in mime-64 encoded format
* @param locale end user locale
* @return certificate in pretty-print format
* @exception EBaseException failed to retrieve certificate
*/
- public String getCertPrettyPrint(String b64E, Locale locale)
- throws EBaseException;
+ public String getCertPrettyPrint(String b64E, Locale locale)
+ throws EBaseException;
/**
* Imports certificate into the server.
- *
+ *
* @param b64E certificate in mime-64 encoded format
* @param nickname nickname for the importing certificate
* @param certType certificate type
* @exception EBaseException failed to import certificate
*/
public void importCert(String b64E, String nickname, String certType)
- throws EBaseException;
+ throws EBaseException;
/**
* Imports certificate into the server.
- *
+ *
* @param signedCert certificate
* @param nickname nickname for the importing certificate
* @param certType certificate type
* @exception EBaseException failed to import certificate
*/
public void importCert(X509CertImpl signedCert, String nickname,
- String certType) throws EBaseException;
+ String certType) throws EBaseException;
/**
* Generates a key pair based on the given parameters.
- *
+ *
* @param properties key parameters
* @return key pair
* @exception EBaseException failed to generate key pair
@@ -119,7 +120,7 @@ public interface ICryptoSubsystem extends ISubsystem {
/**
* Retrieves the key pair based on the given nickname.
- *
+ *
* @param nickname nickname of the public key
* @exception EBaseException failed to retrieve key pair
*/
@@ -127,7 +128,7 @@ public interface ICryptoSubsystem extends ISubsystem {
/**
* Generates a key pair based on the given parameters.
- *
+ *
* @param tokenName name of token where key is generated
* @param alg key algorithm
* @param keySize key size
@@ -135,11 +136,11 @@ public interface ICryptoSubsystem extends ISubsystem {
* @exception EBaseException failed to generate key pair
*/
public KeyPair getKeyPair(String tokenName, String alg,
- int keySize) throws EBaseException;
+ int keySize) throws EBaseException;
/**
* Generates a key pair based on the given parameters.
- *
+ *
* @param tokenName name of token where key is generated
* @param alg key algorithm
* @param keySize key size
@@ -148,11 +149,11 @@ public interface ICryptoSubsystem extends ISubsystem {
* @exception EBaseException failed to generate key pair
*/
public KeyPair getKeyPair(String tokenName, String alg,
- int keySize, PQGParams pqg) throws EBaseException;
+ int keySize, PQGParams pqg) throws EBaseException;
/**
* Generates an ECC key pair based on the given parameters.
- *
+ *
* @param properties key parameters
* @return key pair
* @exception EBaseException failed to generate key pair
@@ -161,7 +162,7 @@ public interface ICryptoSubsystem extends ISubsystem {
/**
* Generates an ECC key pair based on the given parameters.
- *
+ *
* @param token token name
* @param curveName curve name
* @param certType type of cert(sslserver etc..)
@@ -171,28 +172,27 @@ public interface ICryptoSubsystem extends ISubsystem {
public KeyPair getECCKeyPair(String token, String curveName, String certType) throws EBaseException;
/**
- * Retrieves the signature algorithm of the certificate named
- * by the given nickname.
- *
+ * Retrieves the signature algorithm of the certificate named by the given
+ * nickname.
+ *
* @param nickname nickname of the certificate
* @return signature algorithm
- * @exception EBaseException failed to retrieve signature
+ * @exception EBaseException failed to retrieve signature
*/
public String getSignatureAlgorithm(String nickname) throws EBaseException;
/**
* Checks if the given dn is a valid distinguished name.
- *
+ *
* @param dn distinguished name
* @exception EBaseException failed to check
*/
public void isX500DN(String dn) throws EBaseException;
/**
- * Retrieves CA's signing algorithm id. If it is DSA algorithm,
- * algorithm is constructed by reading the parameters
- * ca.dsaP, ca.dsaQ, ca.dsaG.
- *
+ * Retrieves CA's signing algorithm id. If it is DSA algorithm, algorithm is
+ * constructed by reading the parameters ca.dsaP, ca.dsaQ, ca.dsaG.
+ *
* @param algname DSA or RSA
* @param store configuration store.
* @return algorithm id
@@ -201,59 +201,57 @@ public interface ICryptoSubsystem extends ISubsystem {
public AlgorithmId getAlgorithmId(String algname, IConfigStore store) throws EBaseException;
/**
- * Retrieves subject name of the certificate that is identified by
- * the given nickname.
- *
+ * Retrieves subject name of the certificate that is identified by the given
+ * nickname.
+ *
* @param tokenname name of token where the nickname is valid
* @param nickname nickname of the certificate
* @return subject name
* @exception EBaseException failed to get subject name
*/
public String getCertSubjectName(String tokenname, String nickname)
- throws EBaseException;
+ throws EBaseException;
/**
- * Retrieves extensions of the certificate that is identified by
- * the given nickname.
- *
+ * Retrieves extensions of the certificate that is identified by the given
+ * nickname.
+ *
* @param tokenname name of token where the nickname is valid
* @param nickname nickname of the certificate
* @return certificate extensions
* @exception EBaseException failed to get extensions
*/
public CertificateExtensions getExtensions(String tokenname, String nickname
- )
- throws EBaseException;
+ )
+ throws EBaseException;
/**
* Deletes certificate of the given nickname.
- *
+ *
* @param nickname nickname of the certificate
* @param pathname path where a copy of the deleted certificate is stored
* @exception EBaseException failed to delete certificate
*/
- public void deleteTokenCertificate(String nickname, String pathname)
- throws EBaseException;
+ public void deleteTokenCertificate(String nickname, String pathname)
+ throws EBaseException;
/**
* Delete certificate of the given nickname.
- *
+ *
* @param nickname nickname of the certificate
- * @param notAfterTime The notAfter of the certificate. It
- * is possible to ge t multiple certificates under
- * the same nickname. If one of the certificates match
- * the notAfterTime, then the certificate will get
- * deleted. The format of the notAfterTime has to be
- * in "MMMMM dd, yyyy HH:mm:ss" format.
+ * @param notAfterTime The notAfter of the certificate. It is possible to ge
+ * t multiple certificates under the same nickname. If one of the
+ * certificates match the notAfterTime, then the certificate will
+ * get deleted. The format of the notAfterTime has to be in
+ * "MMMMM dd, yyyy HH:mm:ss" format.
* @exception EBaseException failed to delete certificate
*/
- public void deleteCert(String nickname, String notAfterTime)
- throws EBaseException;
+ public void deleteCert(String nickname, String notAfterTime)
+ throws EBaseException;
/**
- * Retrieves the subject DN of the certificate identified by
- * the nickname.
- *
+ * Retrieves the subject DN of the certificate identified by the nickname.
+ *
* @param nickname nickname of the certificate
* @return subject distinguished name
* @exception EBaseException failed to retrieve subject DN
@@ -262,19 +260,19 @@ public interface ICryptoSubsystem extends ISubsystem {
/**
* Trusts a certificate for all available purposes.
- *
+ *
* @param nickname nickname of the certificate
* @param date certificate's not before
* @param trust "Trust" or other
* @exception EBaseException failed to trust certificate
*/
- public void trustCert(String nickname, String date, String trust)
- throws EBaseException;
+ public void trustCert(String nickname, String date, String trust)
+ throws EBaseException;
/**
- * Checks if the given base-64 encoded string contains an extension
- * or a sequence of extensions.
- *
+ * Checks if the given base-64 encoded string contains an extension or a
+ * sequence of extensions.
+ *
* @param ext extension or sequence of extension encoded in base-64
* @exception EBaseException failed to check encoding
*/
@@ -282,16 +280,17 @@ public interface ICryptoSubsystem extends ISubsystem {
/**
* Gets all certificates on all tokens for Certificate Database Management.
- *
+ *
* @return all certificates
* @exception EBaseException failed to retrieve certificates
*/
public NameValuePairs getAllCertsManage() throws EBaseException;
+
public NameValuePairs getUserCerts() throws EBaseException;
/**
* Gets all CA certificates on all tokens.
- *
+ *
* @return all CA certificates
* @exception EBaseException failed to retrieve certificates
*/
@@ -300,17 +299,17 @@ public interface ICryptoSubsystem extends ISubsystem {
public NameValuePairs getRootCerts() throws EBaseException;
public void setRootCertTrust(String nickname, String serialno,
- String issuername, String trust) throws EBaseException;
+ String issuername, String trust) throws EBaseException;
public void deleteRootCert(String nickname, String serialno,
- String issuername) throws EBaseException;
+ String issuername) throws EBaseException;
public void deleteUserCert(String nickname, String serialno,
- String issuername) throws EBaseException;
+ String issuername) throws EBaseException;
/**
* Retrieves PQG parameters based on key size.
- *
+ *
* @param keysize key size
* @return pqg parameters
*/
@@ -318,100 +317,100 @@ public interface ICryptoSubsystem extends ISubsystem {
/**
* Retrieves PQG parameters based on key size.
- *
+ *
* @param keysize key size
* @param store configuration store
* @return pqg parameters
*/
public PQGParams getCAPQG(int keysize, IConfigStore store)
- throws EBaseException;
+ throws EBaseException;
/**
- * Retrieves extensions of the certificate that is identified by
- * the given nickname.
- *
+ * Retrieves extensions of the certificate that is identified by the given
+ * nickname.
+ *
* @param tokenname token name
* @param nickname nickname
* @return certificate extensions
*/
public CertificateExtensions getCertExtensions(String tokenname, String nickname
- )
- throws NotInitializedException, TokenException, ObjectNotFoundException,
+ )
+ throws NotInitializedException, TokenException, ObjectNotFoundException,
- IOException, CertificateException;
+ IOException, CertificateException;
/**
* Checks if the given token is logged in.
- *
+ *
* @param name token name
* @return true if token is logged in
- * @exception EBaseException failed to login
+ * @exception EBaseException failed to login
*/
public boolean isTokenLoggedIn(String name) throws EBaseException;
/**
* Logs into token.
- *
+ *
* @param tokenName name of the token
* @param pwd token password
* @exception EBaseException failed to login
*/
- public void loggedInToken(String tokenName, String pwd)
- throws EBaseException;
+ public void loggedInToken(String tokenName, String pwd)
+ throws EBaseException;
/**
* Generates certificate request from the given key pair.
- *
+ *
* @param subjectName subject name to use in the request
* @param kp key pair that contains public key material
* @return certificate request in base-64 encoded format
* @exception EBaseException failed to generate request
*/
public String getCertRequest(String subjectName, KeyPair kp)
- throws EBaseException;
+ throws EBaseException;
/**
* Checks if fortezza is enabled.
- *
+ *
* @return "true" if fortezza is enabled
*/
public String isCipherFortezza() throws EBaseException;
/**
* Retrieves the SSL cipher version.
- *
+ *
* @return cipher version (i.e. "cipherdomestic")
*/
public String getCipherVersion() throws EBaseException;
/**
* Retrieves the cipher preferences.
- *
+ *
* @return cipher preferences (i.e. "rc4export,rc2export,...")
*/
public String getCipherPreferences() throws EBaseException;
/**
* Sets the current SSL cipher preferences.
- *
+ *
* @param cipherPrefs cipher preferences (i.e. "rc4export,rc2export,...")
* @exception EBaseException failed to set cipher preferences
*/
public void setCipherPreferences(String cipherPrefs)
- throws EBaseException;
+ throws EBaseException;
/**
* Retrieves a list of currently registered token names.
- *
+ *
* @return list of token names
* @exception EBaseException failed to retrieve token list
*/
public String getTokenList() throws EBaseException;
/**
- * Retrieves all certificates. The result list will not
- * contain the token tag.
- *
+ * Retrieves all certificates. The result list will not contain the token
+ * tag.
+ *
* @param name token name
* @return list of certificates without token tag
* @exception EBaseException failed to retrieve
@@ -420,16 +419,16 @@ public interface ICryptoSubsystem extends ISubsystem {
/**
* Retrieves the token name of the internal (software) token.
- *
+ *
* @return the token name
* @exception EBaseException failed to retrieve token name
*/
public String getInternalTokenName() throws EBaseException;
/**
- * Checks to see if the certificate of the given nickname is a
- * CA certificate.
- *
+ * Checks to see if the certificate of the given nickname is a CA
+ * certificate.
+ *
* @param fullNickname nickname of the certificate to check
* @return true if it is a CA certificate
* @exception EBaseException failed to check
@@ -437,28 +436,29 @@ public interface ICryptoSubsystem extends ISubsystem {
public boolean isCACert(String fullNickname) throws EBaseException;
/**
- * Adds the specified number of bits of entropy from the system
- * entropy generator to the RNG of the default PKCS#11 RNG token.
- * The default token is set using the modutil command.
- * Note that the system entropy generator (usually /dev/random)
- * will block until sufficient entropy is collected.
- *
+ * Adds the specified number of bits of entropy from the system entropy
+ * generator to the RNG of the default PKCS#11 RNG token. The default token
+ * is set using the modutil command. Note that the system entropy generator
+ * (usually /dev/random) will block until sufficient entropy is collected.
+ *
* @param bits number of bits of entropy
- * @exception org.mozilla.jss.util.NotImplementedException If the Crypto device does not support
- * adding entropy
- * @exception TokenException If there was some other problem with the Crypto device
- * @exception IOException If there was a problem reading from the /dev/random
+ * @exception org.mozilla.jss.util.NotImplementedException If the Crypto
+ * device does not support adding entropy
+ * @exception TokenException If there was some other problem with the Crypto
+ * device
+ * @exception IOException If there was a problem reading from the
+ * /dev/random
*/
public void addEntropy(int bits)
- throws org.mozilla.jss.util.NotImplementedException,
+ throws org.mozilla.jss.util.NotImplementedException,
IOException,
TokenException;
/**
- * Signs the certificate template into the given data and returns
- * a signed certificate.
- *
+ * Signs the certificate template into the given data and returns a signed
+ * certificate.
+ *
* @param data data that contains certificate template
* @param certType certificate type
* @param priKey CA signing key
diff --git a/pki/base/common/src/com/netscape/certsrv/security/IEncryptionUnit.java b/pki/base/common/src/com/netscape/certsrv/security/IEncryptionUnit.java
index 984425a5..c98a1821 100644
--- a/pki/base/common/src/com/netscape/certsrv/security/IEncryptionUnit.java
+++ b/pki/base/common/src/com/netscape/certsrv/security/IEncryptionUnit.java
@@ -17,41 +17,39 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.security;
-
import java.security.PublicKey;
import org.mozilla.jss.crypto.PrivateKey;
import com.netscape.certsrv.base.EBaseException;
-
/**
* An interface represents a encryption unit.
- *
+ *
* @version $Revision$, $Date$
*/
public interface IEncryptionUnit extends IToken {
/**
* Retrieves the public key in this unit.
- *
+ *
* @return public key
*/
public PublicKey getPublicKey();
/**
- * Wraps data. The given key will be wrapped by the
- * private key in this unit.
- *
+ * Wraps data. The given key will be wrapped by the private key in this
+ * unit.
+ *
* @param priKey private key to be wrapped
- * @return wrapped data
+ * @return wrapped data
* @exception EBaseException failed to wrap
*/
public byte[] wrap(PrivateKey priKey) throws EBaseException;
/**
- * Verifies the given key pair.
- *
+ * Verifies the given key pair.
+ *
* @param publicKey public key
* @param privateKey private key
*/
@@ -59,11 +57,11 @@ public interface IEncryptionUnit extends IToken {
EBaseException;
/**
- * Unwraps data. This method rebuilds the private key by
- * unwrapping the private key data.
- *
+ * Unwraps data. This method rebuilds the private key by unwrapping the
+ * private key data.
+ *
* @param sessionKey session key that unwrap the private key
- * @param symmAlgOID symmetric algorithm
+ * @param symmAlgOID symmetric algorithm
* @param symmAlgParams symmetric algorithm parameters
* @param privateKey private key data
* @param pubKey public key
@@ -71,56 +69,57 @@ public interface IEncryptionUnit extends IToken {
* @exception EBaseException failed to unwrap
*/
public PrivateKey unwrap(byte sessionKey[], String symmAlgOID,
- byte symmAlgParams[], byte privateKey[],
- PublicKey pubKey)
- throws EBaseException;
+ byte symmAlgParams[], byte privateKey[],
+ PublicKey pubKey)
+ throws EBaseException;
/**
- * Unwraps data. This method rebuilds the private key by
- * unwrapping the private key data.
- *
+ * Unwraps data. This method rebuilds the private key by unwrapping the
+ * private key data.
+ *
* @param privateKey private key data
* @param pubKey public key object
* @return private key object
* @exception EBaseException failed to unwrap
*/
public PrivateKey unwrap(byte privateKey[], PublicKey pubKey)
- throws EBaseException;
-
+ throws EBaseException;
+
/**
- * Encrypts the internal private key (private key to the KRA's
- * internal storage).
- *
+ * Encrypts the internal private key (private key to the KRA's internal
+ * storage).
+ *
* @param rawPrivate user's private key (key to be archived)
* @return encrypted data
* @exception EBaseException failed to encrypt
*/
public byte[] encryptInternalPrivate(byte rawPrivate[])
- throws EBaseException;
+ throws EBaseException;
/**
- * Decrypts the internal private key (private key from the KRA's
- * internal storage).
- *
- * @param wrappedPrivateData unwrapped private key data (key to be recovered)
+ * Decrypts the internal private key (private key from the KRA's internal
+ * storage).
+ *
+ * @param wrappedPrivateData unwrapped private key data (key to be
+ * recovered)
* @return raw private key
* @exception EBaseException failed to decrypt
*/
public byte[] decryptInternalPrivate(byte wrappedPrivateData[])
- throws EBaseException;
+ throws EBaseException;
/**
* Decrypts the external private key (private key from the end-user).
- *
+ *
* @param sessionKey session key that protects the user private
- * @param symmAlgOID symmetric algorithm
+ * @param symmAlgOID symmetric algorithm
* @param symmAlgParams symmetric algorithm parameters
* @param privateKey private key data
* @return private key data
* @exception EBaseException failed to decrypt
*/
- public byte[] decryptExternalPrivate(byte sessionKey[],
- String symmAlgOID,
- byte symmAlgParams[], byte privateKey[])
- throws EBaseException;
+ public byte[] decryptExternalPrivate(byte sessionKey[],
+ String symmAlgOID,
+ byte symmAlgParams[], byte privateKey[])
+ throws EBaseException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/security/ISigningUnit.java b/pki/base/common/src/com/netscape/certsrv/security/ISigningUnit.java
index 664d5c1f..0cc245f1 100644
--- a/pki/base/common/src/com/netscape/certsrv/security/ISigningUnit.java
+++ b/pki/base/common/src/com/netscape/certsrv/security/ISigningUnit.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.security;
-
import java.security.PublicKey;
import netscape.security.x509.X509CertImpl;
@@ -28,9 +27,8 @@ import org.mozilla.jss.crypto.X509Certificate;
import com.netscape.certsrv.base.EBaseException;
/**
- * A class represents the signing unit which is
- * capable of signing data.
- *
+ * A class represents the signing unit which is capable of signing data.
+ *
* @version $Revision$, $Date$
*/
public interface ISigningUnit {
@@ -46,11 +44,11 @@ public interface ISigningUnit {
/**
* Retrieves the nickname of the signing certificate.
*/
- public String getNickname();
+ public String getNickname();
/**
* Retrieves the new nickname in the renewal process.
- *
+ *
* @return new nickname
* @exception EBaseException failed to get new nickname
*/
@@ -58,39 +56,39 @@ public interface ISigningUnit {
/**
* Sets new nickname of the signing certificate.
- *
+ *
* @param name nickname
*/
public void setNewNickName(String name);
/**
* Retrieves the signing certificate.
- *
+ *
* @return signing certificate
*/
public X509Certificate getCert();
/**
* Retrieves the signing certificate.
- *
+ *
* @return signing certificate
*/
public X509CertImpl getCertImpl();
/**
* Signs the given data in specific algorithm.
- *
+ *
* @param data data to be signed
* @param algname signing algorithm to be used
* @return signed data
* @exception EBaseException failed to sign
*/
public byte[] sign(byte[] data, String algname)
- throws EBaseException;
-
+ throws EBaseException;
+
/**
* Verifies the signed data.
- *
+ *
* @param data signed data
* @param signature signature
* @param algname signing algorithm
@@ -98,18 +96,18 @@ public interface ISigningUnit {
* @exception EBaseException failed to verify
*/
public boolean verify(byte[] data, byte[] signature, String algname)
- throws EBaseException;
+ throws EBaseException;
/**
* Retrieves the default algorithm.
- *
+ *
* @return default signing algorithm
*/
public SignatureAlgorithm getDefaultSignatureAlgorithm();
/**
* Retrieves the default algorithm name.
- *
+ *
* @return default signing algorithm name
*/
public String getDefaultAlgorithm();
@@ -124,15 +122,15 @@ public interface ISigningUnit {
/**
* Retrieves all supported signing algorithm of this unit.
- *
+ *
* @return a list of signing algorithms
* @exception EBaseException failed to list
- */
+ */
public String[] getAllAlgorithms() throws EBaseException;
/**
* Retrieves the token name of this unit.
- *
+ *
* @return token name
* @exception EBaseException failed to retrieve name
*/
@@ -140,7 +138,7 @@ public interface ISigningUnit {
/**
* Updates new nickname and tokename in the configuration file.
- *
+ *
* @param nickname new nickname
* @param tokenname new tokenname
*/
@@ -148,19 +146,18 @@ public interface ISigningUnit {
/**
* Checks if the given algorithm name is supported.
- *
+ *
* @param algname algorithm name
* @return signing algorithm
* @exception EBaseException failed to check signing algorithm
*/
public SignatureAlgorithm checkSigningAlgorithmFromName(String algname)
- throws EBaseException;
+ throws EBaseException;
/**
* Retrieves the public key associated in this unit.
- *
+ *
* @return public key
*/
public PublicKey getPublicKey();
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/security/IStorageKeyUnit.java b/pki/base/common/src/com/netscape/certsrv/security/IStorageKeyUnit.java
index 02ebc616..008d6384 100644
--- a/pki/base/common/src/com/netscape/certsrv/security/IStorageKeyUnit.java
+++ b/pki/base/common/src/com/netscape/certsrv/security/IStorageKeyUnit.java
@@ -17,33 +17,31 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.security;
-
import java.util.Enumeration;
import org.mozilla.jss.crypto.CryptoToken;
import com.netscape.certsrv.base.EBaseException;
-
/**
- * An interface represents a storage key unit. This storage
- * unit contains a storage key pair that is used for
- * encrypting the user private key for long term storage.
- *
+ * An interface represents a storage key unit. This storage unit contains a
+ * storage key pair that is used for encrypting the user private key for long
+ * term storage.
+ *
* @version $Revision$, $Date$
*/
public interface IStorageKeyUnit extends IEncryptionUnit {
/**
* Retrieves total number of recovery agents.
- *
+ *
* @return total number of recovery agents
*/
public int getNoOfAgents() throws EBaseException;
/**
- * Retrieves number of recovery agents required to
- * perform recovery operation.
+ * Retrieves number of recovery agents required to perform recovery
+ * operation.
*
* @return required number of recovery agents for recovery operation
*/
@@ -51,33 +49,33 @@ public interface IStorageKeyUnit extends IEncryptionUnit {
/**
* Sets the numer of required recovery agents
- *
+ *
* @param number number of required agents
*/
public void setNoOfRequiredAgents(int number);
/**
* Retrieves a list of agents in this unit.
- *
+ *
* @return a list of string-based agent identifiers
*/
public Enumeration getAgentIdentifiers();
/**
* Changes agent password.
- *
+ *
* @param id agent id
* @param oldpwd old password
* @param newpwd new password
* @return true if operation successful
* @exception EBaseException failed to change password
*/
- public boolean changeAgentPassword(String id, String oldpwd,
- String newpwd) throws EBaseException;
+ public boolean changeAgentPassword(String id, String oldpwd,
+ String newpwd) throws EBaseException;
/**
* Changes M-N recovery scheme.
- *
+ *
* @param n total number of agents
* @param m required number of agents for recovery operation
* @param oldcreds all old credentials
@@ -86,11 +84,11 @@ public interface IStorageKeyUnit extends IEncryptionUnit {
* @exception EBaseException failed to change schema
*/
public boolean changeAgentMN(int n, int m, Credential oldcreds[],
- Credential newcreds[]) throws EBaseException;
-
+ Credential newcreds[]) throws EBaseException;
+
/**
* Logins to this unit.
- *
+ *
* @param ac agent's credentials
* @exception EBaseException failed to login
*/
diff --git a/pki/base/common/src/com/netscape/certsrv/security/IToken.java b/pki/base/common/src/com/netscape/certsrv/security/IToken.java
index 0b79cfcf..05aff64f 100644
--- a/pki/base/common/src/com/netscape/certsrv/security/IToken.java
+++ b/pki/base/common/src/com/netscape/certsrv/security/IToken.java
@@ -17,20 +17,18 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.security;
-
import com.netscape.certsrv.base.EBaseException;
-
/**
* An interface represents a generic token unit.
- *
+ *
* @version $Revision$, $Date$
*/
public interface IToken {
/**
* Logins to the token unit.
- *
+ *
* @param pin password to access the token
* @exception EBaseException failed to login to this token
*/
diff --git a/pki/base/common/src/com/netscape/certsrv/security/ITransportKeyUnit.java b/pki/base/common/src/com/netscape/certsrv/security/ITransportKeyUnit.java
index 2edfa12a..dc09c885 100644
--- a/pki/base/common/src/com/netscape/certsrv/security/ITransportKeyUnit.java
+++ b/pki/base/common/src/com/netscape/certsrv/security/ITransportKeyUnit.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.security;
-
import java.security.PublicKey;
import org.mozilla.jss.crypto.CryptoToken;
@@ -26,27 +25,31 @@ import org.mozilla.jss.crypto.SymmetricKey;
import com.netscape.certsrv.base.EBaseException;
-
/**
- * An interface represents the transport key pair.
- * This key pair is used to protected EE's private
- * key in transit.
- *
+ * An interface represents the transport key pair. This key pair is used to
+ * protected EE's private key in transit.
+ *
* @version $Revision$, $Date$
*/
public interface ITransportKeyUnit extends IEncryptionUnit {
/**
* Retrieves public key.
- *
+ *
* @return certificate
*/
public org.mozilla.jss.crypto.X509Certificate getCertificate();
+
public SymmetricKey unwrap_sym(byte encSymmKey[]);
+
public SymmetricKey unwrap_encrypt_sym(byte encSymmKey[]);
+
public PrivateKey unwrap_temp(byte wrappedKeyData[], PublicKey
- pubKey) throws EBaseException;
+ pubKey) throws EBaseException;
+
public CryptoToken getToken();
- public String getSigningAlgorithm() throws EBaseException;
- public void setSigningAlgorithm(String str) throws EBaseException;
+
+ public String getSigningAlgorithm() throws EBaseException;
+
+ public void setSigningAlgorithm(String str) throws EBaseException;
}
diff --git a/pki/base/common/src/com/netscape/certsrv/security/KeyCertData.java b/pki/base/common/src/com/netscape/certsrv/security/KeyCertData.java
index 484e5e73..18cc98be 100644
--- a/pki/base/common/src/com/netscape/certsrv/security/KeyCertData.java
+++ b/pki/base/common/src/com/netscape/certsrv/security/KeyCertData.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.security;
-
import java.math.BigInteger;
import java.security.KeyPair;
import java.util.Properties;
@@ -32,8 +31,7 @@ import com.netscape.certsrv.common.ConfigConstants;
import com.netscape.certsrv.common.Constants;
/**
- * This class represents a container for storaging
- * data in the security package.
+ * This class represents a container for storaging data in the security package.
*
* @version $Revision$, $Date$
*/
@@ -53,7 +51,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves the key pair from this container.
- *
+ *
* @return key pair
*/
public KeyPair getKeyPair() {
@@ -62,7 +60,7 @@ public class KeyCertData extends Properties {
/**
* Sets key pair into this container.
- *
+ *
* @param keypair key pair
*/
public void setKeyPair(KeyPair keypair) {
@@ -71,7 +69,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves the issuer name from this container.
- *
+ *
* @return issuer name
*/
public String getIssuerName() {
@@ -80,7 +78,7 @@ public class KeyCertData extends Properties {
/**
* Sets the issuer name in this container.
- *
+ *
* @param name issuer name
*/
public void setIssuerName(String name) {
@@ -89,7 +87,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves certificate server instance name.
- *
+ *
* @return instance name
*/
public String getCertInstanceName() {
@@ -98,7 +96,7 @@ public class KeyCertData extends Properties {
/**
* Sets certificate server instance name.
- *
+ *
* @param name instance name
*/
public void setCertInstanceName(String name) {
@@ -107,16 +105,16 @@ public class KeyCertData extends Properties {
/**
* Retrieves certificate nickname.
- *
+ *
* @return certificate nickname
*/
public String getCertNickname() {
return (String) get(Constants.PR_NICKNAME);
}
-
+
/**
* Sets certificate nickname.
- *
+ *
* @param nickname certificate nickname
*/
public void setCertNickname(String nickname) {
@@ -125,7 +123,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves key length.
- *
+ *
* @return key length
*/
public String getKeyLength() {
@@ -134,7 +132,7 @@ public class KeyCertData extends Properties {
/**
* Sets key length.
- *
+ *
* @param len key length
*/
public void setKeyLength(String len) {
@@ -143,7 +141,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves key type.
- *
+ *
* @return key type
*/
public String getKeyType() {
@@ -152,7 +150,7 @@ public class KeyCertData extends Properties {
/**
* Sets key type.
- *
+ *
* @param type key type
*/
public void setKeyType(String type) {
@@ -161,7 +159,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves key curve name.
- *
+ *
* @return key curve name
*/
public String getKeyCurveName() {
@@ -170,7 +168,7 @@ public class KeyCertData extends Properties {
/**
* Sets key curvename.
- *
+ *
* @param len key curvename
*/
public void setKeyCurveName(String len) {
@@ -179,7 +177,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves signature algorithm.
- *
+ *
* @return signature algorithm
*/
public SignatureAlgorithm getSignatureAlgorithm() {
@@ -188,7 +186,7 @@ public class KeyCertData extends Properties {
/**
* Sets signature algorithm
- *
+ *
* @param alg signature algorithm
*/
public void setSignatureAlgorithm(SignatureAlgorithm alg) {
@@ -197,7 +195,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves algorithm used to sign the root CA Cert.
- *
+ *
* @return signature algorithm
*/
public String getSignedBy() {
@@ -206,7 +204,7 @@ public class KeyCertData extends Properties {
/**
* Sets signature algorithm used to sign root CA cert
- *
+ *
* @param alg signature algorithm
*/
public void setSignedBy(String alg) {
@@ -215,7 +213,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves signature algorithm.
- *
+ *
* @return signature algorithm
*/
public AlgorithmId getAlgorithmId() {
@@ -224,7 +222,7 @@ public class KeyCertData extends Properties {
/**
* Sets algorithm identifier
- *
+ *
* @param id signature algorithm
*/
public void setAlgorithmId(AlgorithmId id) {
@@ -233,7 +231,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves serial number.
- *
+ *
* @return serial number
*/
public BigInteger getSerialNumber() {
@@ -242,7 +240,7 @@ public class KeyCertData extends Properties {
/**
* Sets serial number.
- *
+ *
* @param num serial number
*/
public void setSerialNumber(BigInteger num) {
@@ -251,16 +249,16 @@ public class KeyCertData extends Properties {
/**
* Retrieves configuration file.
- *
+ *
* @return configuration file
*/
public IConfigStore getConfigFile() {
- return (IConfigStore)(get("cmsFile"));
+ return (IConfigStore) (get("cmsFile"));
}
/**
* Sets configuration file.
- *
+ *
* @param file configuration file
*/
public void setConfigFile(IConfigStore file) {
@@ -269,7 +267,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves begining year of validity.
- *
+ *
* @return begining year
*/
public String getBeginYear() {
@@ -278,7 +276,7 @@ public class KeyCertData extends Properties {
/**
* Sets begining year of validity.
- *
+ *
* @param year begining year
*/
public void setBeginYear(String year) {
@@ -287,7 +285,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves ending year of validity.
- *
+ *
* @return ending year
*/
public String getAfterYear() {
@@ -296,7 +294,7 @@ public class KeyCertData extends Properties {
/**
* Sets ending year of validity.
- *
+ *
* @param year ending year
*/
public void setAfterYear(String year) {
@@ -305,7 +303,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves begining month of validity.
- *
+ *
* @return begining month
*/
public String getBeginMonth() {
@@ -314,7 +312,7 @@ public class KeyCertData extends Properties {
/**
* Sets begining month of validity.
- *
+ *
* @param month begining month
*/
public void setBeginMonth(String month) {
@@ -323,7 +321,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves ending month of validity.
- *
+ *
* @return ending month
*/
public String getAfterMonth() {
@@ -332,7 +330,7 @@ public class KeyCertData extends Properties {
/**
* Sets ending month of validity.
- *
+ *
* @param month ending month
*/
public void setAfterMonth(String month) {
@@ -341,7 +339,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves begining date of validity.
- *
+ *
* @return begining date
*/
public String getBeginDate() {
@@ -350,7 +348,7 @@ public class KeyCertData extends Properties {
/**
* Sets begining date of validity.
- *
+ *
* @param date begining date
*/
public void setBeginDate(String date) {
@@ -359,7 +357,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves ending date of validity.
- *
+ *
* @return ending date
*/
public String getAfterDate() {
@@ -368,7 +366,7 @@ public class KeyCertData extends Properties {
/**
* Sets ending date of validity.
- *
+ *
* @param date ending date
*/
public void setAfterDate(String date) {
@@ -377,7 +375,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves starting hour of validity.
- *
+ *
* @return starting hour
*/
public String getBeginHour() {
@@ -386,7 +384,7 @@ public class KeyCertData extends Properties {
/**
* Sets starting hour of validity.
- *
+ *
* @param hour starting hour
*/
public void setBeginHour(String hour) {
@@ -395,7 +393,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves ending hour of validity.
- *
+ *
* @return ending hour
*/
public String getAfterHour() {
@@ -404,7 +402,7 @@ public class KeyCertData extends Properties {
/**
* Sets ending hour of validity.
- *
+ *
* @param hour ending hour
*/
public void setAfterHour(String hour) {
@@ -413,16 +411,16 @@ public class KeyCertData extends Properties {
/**
* Retrieves starting minute of validity.
- *
+ *
* @return starting minute
*/
public String getBeginMin() {
return (String) get(Constants.PR_BEGIN_MIN);
}
-
+
/**
* Sets starting minute of validity.
- *
+ *
* @param min starting minute
*/
public void setBeginMin(String min) {
@@ -431,7 +429,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves ending minute of validity.
- *
+ *
* @return ending minute
*/
public String getAfterMin() {
@@ -440,7 +438,7 @@ public class KeyCertData extends Properties {
/**
* Sets ending minute of validity.
- *
+ *
* @param min ending minute
*/
public void setAfterMin(String min) {
@@ -449,7 +447,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves starting second of validity.
- *
+ *
* @return starting second
*/
public String getBeginSec() {
@@ -458,7 +456,7 @@ public class KeyCertData extends Properties {
/**
* Sets starting second of validity.
- *
+ *
* @param sec starting second
*/
public void setBeginSec(String sec) {
@@ -467,7 +465,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves ending second of validity.
- *
+ *
* @return ending second
*/
public String getAfterSec() {
@@ -476,7 +474,7 @@ public class KeyCertData extends Properties {
/**
* Sets ending second of validity.
- *
+ *
* @param sec ending second
*/
public void setAfterSec(String sec) {
@@ -485,7 +483,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves CA key pair
- *
+ *
* @return CA key pair
*/
public KeyPair getCAKeyPair() {
@@ -494,7 +492,7 @@ public class KeyCertData extends Properties {
/**
* Sets CA key pair
- *
+ *
* @param keypair key pair
*/
public void setCAKeyPair(KeyPair keypair) {
@@ -503,7 +501,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves extensions
- *
+ *
* @return extensions
*/
public String getDerExtension() {
@@ -512,7 +510,7 @@ public class KeyCertData extends Properties {
/**
* Sets extensions
- *
+ *
* @param ext extensions
*/
public void setDerExtension(String ext) {
@@ -521,7 +519,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves isCA
- *
+ *
* @return "true" if it is CA
*/
public String isCA() {
@@ -530,7 +528,7 @@ public class KeyCertData extends Properties {
/**
* Sets isCA
- *
+ *
* @param ext "true" if it is CA
*/
public void setCA(String ext) {
@@ -539,7 +537,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves key length
- *
+ *
* @return certificate's key length
*/
public String getCertLen() {
@@ -548,7 +546,7 @@ public class KeyCertData extends Properties {
/**
* Sets key length
- *
+ *
* @param len certificate's key length
*/
public void setCertLen(String len) {
@@ -557,7 +555,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves SSL Client bit
- *
+ *
* @return SSL Client bit
*/
public String getSSLClientBit() {
@@ -566,7 +564,7 @@ public class KeyCertData extends Properties {
/**
* Sets SSL Client bit
- *
+ *
* @param sslClientBit SSL Client bit
*/
public void setSSLClientBit(String sslClientBit) {
@@ -575,7 +573,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves SSL Server bit
- *
+ *
* @return SSL Server bit
*/
public String getSSLServerBit() {
@@ -584,7 +582,7 @@ public class KeyCertData extends Properties {
/**
* Sets SSL Server bit
- *
+ *
* @param sslServerBit SSL Server bit
*/
public void setSSLServerBit(String sslServerBit) {
@@ -593,7 +591,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves SSL Mail bit
- *
+ *
* @return SSL Mail bit
*/
public String getSSLMailBit() {
@@ -602,7 +600,7 @@ public class KeyCertData extends Properties {
/**
* Sets SSL Mail bit
- *
+ *
* @param sslMailBit SSL Mail bit
*/
public void setSSLMailBit(String sslMailBit) {
@@ -611,7 +609,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves SSL CA bit
- *
+ *
* @return SSL CA bit
*/
public String getSSLCABit() {
@@ -620,7 +618,7 @@ public class KeyCertData extends Properties {
/**
* Sets SSL CA bit
- *
+ *
* @param cabit SSL CA bit
*/
public void setSSLCABit(String cabit) {
@@ -629,16 +627,16 @@ public class KeyCertData extends Properties {
/**
* Retrieves SSL Signing bit
- *
+ *
* @return SSL Signing bit
*/
public String getObjectSigningBit() {
return (String) get(Constants.PR_OBJECT_SIGNING_BIT);
}
- /**
+ /**
* Retrieves Time Stamping bit
- *
+ *
* @return Time Stamping bit
*/
public String getTimeStampingBit() {
@@ -647,7 +645,7 @@ public class KeyCertData extends Properties {
/**
* Sets SSL Signing bit
- *
+ *
* @param objectSigningBit SSL Signing bit
*/
public void setObjectSigningBit(String objectSigningBit) {
@@ -656,7 +654,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves SSL Mail CA bit
- *
+ *
* @return SSL Mail CA bit
*/
public String getMailCABit() {
@@ -665,7 +663,7 @@ public class KeyCertData extends Properties {
/**
* Sets SSL Mail CA bit
- *
+ *
* @param mailCABit SSL Mail CA bit
*/
public void setMailCABit(String mailCABit) {
@@ -674,7 +672,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves SSL Object Signing bit
- *
+ *
* @return SSL Object Signing bit
*/
public String getObjectSigningCABit() {
@@ -683,7 +681,7 @@ public class KeyCertData extends Properties {
/**
* Sets SSL Object Signing bit
- *
+ *
* @param bit SSL Object Signing bit
*/
public void setObjectSigningCABit(String bit) {
@@ -692,7 +690,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves OCSP Signing flag
- *
+ *
* @return OCSP Signing flag
*/
public String getOCSPSigning() {
@@ -701,7 +699,7 @@ public class KeyCertData extends Properties {
/**
* Sets OCSP Signing flag
- *
+ *
* @param aki OCSP Signing flag
*/
public void setOCSPSigning(String aki) {
@@ -710,7 +708,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves OCSP No Check flag
- *
+ *
* @return OCSP No Check flag
*/
public String getOCSPNoCheck() {
@@ -719,7 +717,7 @@ public class KeyCertData extends Properties {
/**
* Sets OCSP No Check flag
- *
+ *
* @param noCheck OCSP No Check flag
*/
public void setOCSPNoCheck(String noCheck) {
@@ -728,7 +726,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves Authority Information Access flag
- *
+ *
* @return Authority Information Access flag
*/
public String getAIA() {
@@ -737,7 +735,7 @@ public class KeyCertData extends Properties {
/**
* Sets Authority Information Access flag
- *
+ *
* @param aia Authority Information Access flag
*/
public void setAIA(String aia) {
@@ -746,7 +744,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves Authority Key Identifier flag
- *
+ *
* @return Authority Key Identifier flag
*/
public String getAKI() {
@@ -755,7 +753,7 @@ public class KeyCertData extends Properties {
/**
* Sets Authority Key Identifier flag
- *
+ *
* @param aki Authority Key Identifier flag
*/
public void setAKI(String aki) {
@@ -764,7 +762,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves Subject Key Identifier flag
- *
+ *
* @return Subject Key Identifier flag
*/
public String getSKI() {
@@ -773,7 +771,7 @@ public class KeyCertData extends Properties {
/**
* Sets Subject Key Identifier flag
- *
+ *
* @param ski Subject Key Identifier flag
*/
public void setSKI(String ski) {
@@ -782,7 +780,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves key usage extension
- *
+ *
* @return true if key usage extension set
*/
public boolean getKeyUsageExtension() {
@@ -795,7 +793,7 @@ public class KeyCertData extends Properties {
/**
* Sets CA extensions
- *
+ *
* @param ext CA extensions
*/
public void setCAExtensions(CertificateExtensions ext) {
@@ -804,7 +802,7 @@ public class KeyCertData extends Properties {
/**
* Retrieves CA extensions
- *
+ *
* @return CA extensions
*/
public CertificateExtensions getCAExtensions() {
@@ -813,11 +811,10 @@ public class KeyCertData extends Properties {
/**
* Retrieves hash type
- *
+ *
* @return hash type
*/
public String getHashType() {
return (String) get(ConfigConstants.PR_HASH_TYPE);
}
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/selftests/EDuplicateSelfTestException.java b/pki/base/common/src/com/netscape/certsrv/selftests/EDuplicateSelfTestException.java
index d0f6b4c3..1ace7097 100644
--- a/pki/base/common/src/com/netscape/certsrv/selftests/EDuplicateSelfTestException.java
+++ b/pki/base/common/src/com/netscape/certsrv/selftests/EDuplicateSelfTestException.java
@@ -20,38 +20,33 @@
package com.netscape.certsrv.selftests;
-
///////////////////////
// import statements //
///////////////////////
-
-
//////////////////////
// class definition //
//////////////////////
/**
* This class implements a duplicate self test exception.
- * EDuplicateSelfTestExceptions are derived from ESelfTestExceptions
- * in order to allow users to easily do self tests without try-catch clauses.
- *
+ * EDuplicateSelfTestExceptions are derived from ESelfTestExceptions in order to
+ * allow users to easily do self tests without try-catch clauses.
+ *
* EDuplicateSelfTestExceptions should be caught by SelfTestSubsystem managers.
* <P>
*
* @version $Revision$, $Date$
*/
public class EDuplicateSelfTestException
- extends ESelfTestException {
- ////////////////////////
+ extends ESelfTestException {
+ // //////////////////////
// default parameters //
- ////////////////////////
-
-
+ // //////////////////////
- ///////////////////////
+ // /////////////////////
// helper parameters //
- ///////////////////////
+ // /////////////////////
/**
*
@@ -62,32 +57,28 @@ public class EDuplicateSelfTestException
private String mInstanceParameter = null;
private String mInstanceValue = null;
- ////////////////////////////////////////////
+ // //////////////////////////////////////////
// EDuplicateSelfTestException parameters //
- ////////////////////////////////////////////
+ // //////////////////////////////////////////
-
-
- ///////////////////////////////////////////////
+ // /////////////////////////////////////////////
// ESelfTestException parameters (inherited) //
- ///////////////////////////////////////////////
-
+ // /////////////////////////////////////////////
-
- /////////////////////
+ // ///////////////////
// default methods //
- /////////////////////
+ // ///////////////////
/**
* Constructs a "duplicate" self test exception.
* <P>
- *
+ *
* @param instanceName duplicate "instanceName" exception details
*/
public EDuplicateSelfTestException(String instanceName) {
super("The self test plugin property named "
- + instanceName
- + " already exists.");
+ + instanceName
+ + " already exists.");
// strip preceding/trailing whitespace
// from passed-in String parameters
@@ -100,20 +91,20 @@ public class EDuplicateSelfTestException
}
/**
- * Constructs a "duplicate" self test exception where the value is always
- * a duplicate from a name/value pair
+ * Constructs a "duplicate" self test exception where the value is always a
+ * duplicate from a name/value pair
* <P>
- *
+ *
* @param instanceName duplicate "instanceName" exception details
* @param instanceValue duplicate "instanceValue" exception details
*/
public EDuplicateSelfTestException(String instanceName,
- String instanceValue) {
+ String instanceValue) {
super("The self test plugin property named "
- + instanceName
- + " contains a value of "
- + instanceValue
- + " which already exists.");
+ + instanceName
+ + " contains a value of "
+ + instanceValue
+ + " which already exists.");
// strip preceding/trailing whitespace
// from passed-in String parameters
@@ -134,18 +125,18 @@ public class EDuplicateSelfTestException
* duplicate from a substore.parameter/value pair; (the value passed in may
* be null).
* <P>
- *
+ *
* @param instanceStore duplicate "instanceStore" exception details
* @param instanceParameter duplicate "instanceParameter" exception details
- * @param instanceValue duplicate "instanceValue" exception details
- * (may be null)
+ * @param instanceValue duplicate "instanceValue" exception details (may be
+ * null)
*/
public EDuplicateSelfTestException(String instanceStore,
- String instanceParameter,
- String instanceValue) {
+ String instanceParameter,
+ String instanceValue) {
super("The self test plugin property named "
- + instanceStore + "." + instanceParameter
- + " is a duplicate.");
+ + instanceStore + "." + instanceParameter
+ + " is a duplicate.");
// strip preceding/trailing whitespace
// from passed-in String parameters
@@ -165,14 +156,14 @@ public class EDuplicateSelfTestException
mInstanceValue = instanceValue;
}
- ////////////////////
+ // //////////////////
// helper methods //
- ////////////////////
+ // //////////////////
/**
* Returns the instance name associated with this self test.
* <P>
- *
+ *
* @return name portion of the name/value pair
*/
public String getInstanceName() {
@@ -182,7 +173,7 @@ public class EDuplicateSelfTestException
/**
* Returns the store associated with this self test.
* <P>
- *
+ *
* @return substore portion of the substore.parameter/value pair
*/
public String getInstanceStore() {
@@ -192,7 +183,7 @@ public class EDuplicateSelfTestException
/**
* Returns the parameter associated with this self test.
* <P>
- *
+ *
* @return parameter portion of the substore.parameter/value pair
*/
public String getInstanceParameter() {
@@ -202,27 +193,25 @@ public class EDuplicateSelfTestException
/**
* Returns the value associated with this self test.
* <P>
- *
+ *
* @return value portion of the name/value pair
*/
public String getInstanceValue() {
return mInstanceValue;
}
- /////////////////////////////////////////
+ // ///////////////////////////////////////
// EDuplicateSelfTestException methods //
- /////////////////////////////////////////
-
-
+ // ///////////////////////////////////////
- ////////////////////////////////////////////
+ // //////////////////////////////////////////
// ESelfTestException methods (inherited) //
- ////////////////////////////////////////////
+ // //////////////////////////////////////////
- /* Note that all of the following ESelfTestException methods
- * are inherited from the ESelfTestException class:
- *
+ /*
+ * Note that all of the following ESelfTestException methods are inherited
+ * from the ESelfTestException class:
+ *
* public ESelfTestException( String msg );
*/
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/selftests/EInvalidSelfTestException.java b/pki/base/common/src/com/netscape/certsrv/selftests/EInvalidSelfTestException.java
index 11907695..c8b40c66 100644
--- a/pki/base/common/src/com/netscape/certsrv/selftests/EInvalidSelfTestException.java
+++ b/pki/base/common/src/com/netscape/certsrv/selftests/EInvalidSelfTestException.java
@@ -20,38 +20,33 @@
package com.netscape.certsrv.selftests;
-
///////////////////////
// import statements //
///////////////////////
-
-
//////////////////////
// class definition //
//////////////////////
/**
* This class implements an invalid self test exception.
- * EInvalidSelfTestExceptions are derived from ESelfTestExceptions
- * in order to allow users to easily do self tests without try-catch clauses.
- *
+ * EInvalidSelfTestExceptions are derived from ESelfTestExceptions in order to
+ * allow users to easily do self tests without try-catch clauses.
+ *
* EInvalidSelfTestExceptions should be caught by SelfTestSubsystem managers.
* <P>
*
* @version $Revision$, $Date$
*/
public class EInvalidSelfTestException
- extends ESelfTestException {
- ////////////////////////
+ extends ESelfTestException {
+ // //////////////////////
// default parameters //
- ////////////////////////
-
-
+ // //////////////////////
- ///////////////////////
+ // /////////////////////
// helper parameters //
- ///////////////////////
+ // /////////////////////
/**
*
@@ -62,32 +57,28 @@ public class EInvalidSelfTestException
private String mInstanceParameter = null;
private String mInstanceValue = null;
- //////////////////////////////////////////
+ // ////////////////////////////////////////
// EInvalidSelfTestException parameters //
- //////////////////////////////////////////
+ // ////////////////////////////////////////
-
-
- ///////////////////////////////////////////////
+ // /////////////////////////////////////////////
// ESelfTestException parameters (inherited) //
- ///////////////////////////////////////////////
-
+ // /////////////////////////////////////////////
-
- /////////////////////
+ // ///////////////////
// default methods //
- /////////////////////
+ // ///////////////////
/**
* Constructs an "invalid" self test exception.
* <P>
- *
+ *
* @param instanceName invalid "instanceName" exception details
*/
public EInvalidSelfTestException(String instanceName) {
super("The self test plugin named "
- + instanceName
- + " is invalid.");
+ + instanceName
+ + " is invalid.");
// strip preceding/trailing whitespace
// from passed-in String parameters
@@ -103,17 +94,17 @@ public class EInvalidSelfTestException
* Constructs a "invalid" self test exception where the value is always
* invalid from a name/value pair
* <P>
- *
+ *
* @param instanceName invalid "instanceName" exception details
* @param instanceValue invalid "instanceValue" exception details
*/
public EInvalidSelfTestException(String instanceName,
- String instanceValue) {
+ String instanceValue) {
super("The self test plugin named "
- + instanceName
- + " contains a value "
- + instanceValue
- + " which is invalid.");
+ + instanceName
+ + " contains a value "
+ + instanceValue
+ + " which is invalid.");
// strip preceding/trailing whitespace
// from passed-in String parameters
@@ -131,21 +122,21 @@ public class EInvalidSelfTestException
/**
* Constructs an "invalid" self test exception where the parameter is always
- * invalid from a substore.parameter/value pair; (the value passed in may
- * be null).
+ * invalid from a substore.parameter/value pair; (the value passed in may be
+ * null).
* <P>
- *
+ *
* @param instanceStore invalid "instanceStore" exception details
* @param instanceParameter invalid "instanceParameter" exception details
- * @param instanceValue invalid "instanceValue" exception details
- * (may be null)
+ * @param instanceValue invalid "instanceValue" exception details (may be
+ * null)
*/
public EInvalidSelfTestException(String instanceStore,
- String instanceParameter,
- String instanceValue) {
+ String instanceParameter,
+ String instanceValue) {
super("The self test plugin parameter named "
- + instanceStore + "." + instanceParameter
- + " is invalid.");
+ + instanceStore + "." + instanceParameter
+ + " is invalid.");
// strip preceding/trailing whitespace
// from passed-in String parameters
@@ -165,14 +156,14 @@ public class EInvalidSelfTestException
mInstanceValue = instanceValue;
}
- ////////////////////
+ // //////////////////
// helper methods //
- ////////////////////
+ // //////////////////
/**
* Returns the instance name associated with this self test.
* <P>
- *
+ *
* @return name portion of the name/value pair
*/
public String getInstanceName() {
@@ -182,7 +173,7 @@ public class EInvalidSelfTestException
/**
* Returns the store associated with this self test.
* <P>
- *
+ *
* @return substore portion of the substore.parameter/value pair
*/
public String getInstanceStore() {
@@ -192,7 +183,7 @@ public class EInvalidSelfTestException
/**
* Returns the parameter associated with this self test.
* <P>
- *
+ *
* @return parameter portion of the substore.parameter/value pair
*/
public String getInstanceParameter() {
@@ -202,27 +193,25 @@ public class EInvalidSelfTestException
/**
* Returns the value associated with this self test.
* <P>
- *
+ *
* @return value portion of the name/value pair
*/
public String getInstanceValue() {
return mInstanceValue;
}
- ///////////////////////////////////////
+ // /////////////////////////////////////
// EInvalidSelfTestException methods //
- ///////////////////////////////////////
-
-
+ // /////////////////////////////////////
- ////////////////////////////////////////////
+ // //////////////////////////////////////////
// ESelfTestException methods (inherited) //
- ////////////////////////////////////////////
+ // //////////////////////////////////////////
- /* Note that all of the following ESelfTestException methods
- * are inherited from the ESelfTestException class:
- *
+ /*
+ * Note that all of the following ESelfTestException methods are inherited
+ * from the ESelfTestException class:
+ *
* public ESelfTestException( String msg );
*/
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/selftests/EMissingSelfTestException.java b/pki/base/common/src/com/netscape/certsrv/selftests/EMissingSelfTestException.java
index 88fa14cb..70876c5c 100644
--- a/pki/base/common/src/com/netscape/certsrv/selftests/EMissingSelfTestException.java
+++ b/pki/base/common/src/com/netscape/certsrv/selftests/EMissingSelfTestException.java
@@ -20,38 +20,33 @@
package com.netscape.certsrv.selftests;
-
///////////////////////
// import statements //
///////////////////////
-
-
//////////////////////
// class definition //
//////////////////////
/**
* This class implements a missing self test exception.
- * EMissingSelfTestExceptions are derived from ESelfTestExceptions
- * in order to allow users to easily do self tests without try-catch clauses.
- *
+ * EMissingSelfTestExceptions are derived from ESelfTestExceptions in order to
+ * allow users to easily do self tests without try-catch clauses.
+ *
* EMissingSelfTestExceptions should be caught by SelfTestSubsystem managers.
* <P>
*
* @version $Revision$, $Date$
*/
public class EMissingSelfTestException
- extends ESelfTestException {
- ////////////////////////
+ extends ESelfTestException {
+ // //////////////////////
// default parameters //
- ////////////////////////
-
-
+ // //////////////////////
- ///////////////////////
+ // /////////////////////
// helper parameters //
- ///////////////////////
+ // /////////////////////
/**
*
@@ -62,26 +57,22 @@ public class EMissingSelfTestException
private String mInstanceParameter = null;
private String mInstanceValue = null;
- //////////////////////////////////////////
+ // ////////////////////////////////////////
// EMissingSelfTestException parameters //
- //////////////////////////////////////////
+ // ////////////////////////////////////////
-
-
- ///////////////////////////////////////////////
+ // /////////////////////////////////////////////
// ESelfTestException parameters (inherited) //
- ///////////////////////////////////////////////
-
+ // /////////////////////////////////////////////
-
- /////////////////////
+ // ///////////////////
// default methods //
- /////////////////////
+ // ///////////////////
/**
* Constructs a "missing" self test exception where the name is null
* <P>
- *
+ *
*/
public EMissingSelfTestException() {
super("The self test plugin property name is null.");
@@ -91,13 +82,13 @@ public class EMissingSelfTestException
* Constructs a "missing" self test exception where the name is always
* missing from a name/value pair.
* <P>
- *
+ *
* @param instanceName missing "instanceName" exception details
*/
public EMissingSelfTestException(String instanceName) {
super("The self test plugin property named "
- + instanceName
- + " does not exist.");
+ + instanceName
+ + " does not exist.");
// strip preceding/trailing whitespace
// from passed-in String parameters
@@ -113,16 +104,16 @@ public class EMissingSelfTestException
* Constructs a "missing" self test exception where the value is always
* missing from a name/value pair; (the value passed in is always null).
* <P>
- *
+ *
* @param instanceName missing "instanceName" exception details
- * @param instanceValue missing "instanceValue" exception details
- * (always null)
+ * @param instanceValue missing "instanceValue" exception details (always
+ * null)
*/
public EMissingSelfTestException(String instanceName,
- String instanceValue) {
+ String instanceValue) {
super("The self test plugin property named "
- + instanceName
- + " contains no values.");
+ + instanceName
+ + " contains no values.");
// strip preceding/trailing whitespace
// from passed-in String parameters
@@ -140,21 +131,21 @@ public class EMissingSelfTestException
/**
* Constructs a "missing" self test exception where the parameter is always
- * missing from a substore.parameter/value pair; (the value passed in may
- * be null).
+ * missing from a substore.parameter/value pair; (the value passed in may be
+ * null).
* <P>
- *
+ *
* @param instanceStore missing "instanceStore" exception details
* @param instanceParameter missing "instanceParameter" exception details
- * @param instanceValue missing "instanceValue" exception details
- * (may be null)
+ * @param instanceValue missing "instanceValue" exception details (may be
+ * null)
*/
public EMissingSelfTestException(String instanceStore,
- String instanceParameter,
- String instanceValue) {
+ String instanceParameter,
+ String instanceValue) {
super("The self test plugin property named "
- + instanceStore + "." + instanceParameter
- + " is missing.");
+ + instanceStore + "." + instanceParameter
+ + " is missing.");
// strip preceding/trailing whitespace
// from passed-in String parameters
@@ -174,14 +165,14 @@ public class EMissingSelfTestException
mInstanceValue = instanceValue;
}
- ////////////////////
+ // //////////////////
// helper methods //
- ////////////////////
+ // //////////////////
/**
* Returns the instance name associated with this self test.
* <P>
- *
+ *
* @return name portion of the name/value pair
*/
public String getInstanceName() {
@@ -191,7 +182,7 @@ public class EMissingSelfTestException
/**
* Returns the store associated with this self test.
* <P>
- *
+ *
* @return substore portion of the substore.parameter/value pair
*/
public String getInstanceStore() {
@@ -201,7 +192,7 @@ public class EMissingSelfTestException
/**
* Returns the parameter associated with this self test.
* <P>
- *
+ *
* @return parameter portion of the substore.parameter/value pair
*/
public String getInstanceParameter() {
@@ -211,27 +202,25 @@ public class EMissingSelfTestException
/**
* Returns the value associated with this self test.
* <P>
- *
+ *
* @return value portion of the name/value pair
*/
public String getInstanceValue() {
return mInstanceValue;
}
- ///////////////////////////////////////
+ // /////////////////////////////////////
// EMissingSelfTestException methods //
- ///////////////////////////////////////
-
-
+ // /////////////////////////////////////
- ////////////////////////////////////////////
+ // //////////////////////////////////////////
// ESelfTestException methods (inherited) //
- ////////////////////////////////////////////
+ // //////////////////////////////////////////
- /* Note that all of the following ESelfTestException methods
- * are inherited from the ESelfTestException class:
- *
+ /*
+ * Note that all of the following ESelfTestException methods are inherited
+ * from the ESelfTestException class:
+ *
* public ESelfTestException( String msg );
*/
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/selftests/ESelfTestException.java b/pki/base/common/src/com/netscape/certsrv/selftests/ESelfTestException.java
index e465517c..8ee7b8c0 100644
--- a/pki/base/common/src/com/netscape/certsrv/selftests/ESelfTestException.java
+++ b/pki/base/common/src/com/netscape/certsrv/selftests/ESelfTestException.java
@@ -20,39 +20,35 @@
package com.netscape.certsrv.selftests;
-
///////////////////////
// import statements //
///////////////////////
import com.netscape.certsrv.base.EBaseException;
-
//////////////////////
// class definition //
//////////////////////
/**
- * This class implements a self test exception. ESelfTestExceptions
- * are derived from EBaseExceptions in order to allow users
- * to easily do self tests without try-catch clauses.
- *
+ * This class implements a self test exception. ESelfTestExceptions are derived
+ * from EBaseExceptions in order to allow users to easily do self tests without
+ * try-catch clauses.
+ *
* ESelfTestExceptions should be caught by SelfTestSubsystem managers.
* <P>
*
* @version $Revision$, $Date$
*/
public class ESelfTestException
- extends EBaseException {
- ////////////////////////
+ extends EBaseException {
+ // //////////////////////
// default parameters //
- ////////////////////////
-
-
+ // //////////////////////
- ///////////////////////////////////
+ // /////////////////////////////////
// ESelfTestException parameters //
- ///////////////////////////////////
+ // /////////////////////////////////
/**
*
@@ -60,68 +56,65 @@ public class ESelfTestException
private static final long serialVersionUID = -8001373369705595891L;
private static final String SELFTEST_RESOURCES = SelfTestResources.class.getName();
-
- ///////////////////////////////////////////
+ // /////////////////////////////////////////
// EBaseException parameters (inherited) //
- ///////////////////////////////////////////
+ // /////////////////////////////////////////
- /* Note that all of the following EBaseException parameters
- * are inherited from the EBaseException class:
- *
+ /*
+ * Note that all of the following EBaseException parameters are inherited
+ * from the EBaseException class:
+ *
* public Object mParams[];
*/
-
-
- /////////////////////
+ // ///////////////////
// default methods //
- /////////////////////
+ // ///////////////////
/**
* Constructs a self test exception.
* <P>
- *
+ *
* @param msg exception details
*/
public ESelfTestException(String msg) {
super(msg);
}
-
- ////////////////////////////////
+ // //////////////////////////////
// ESelfTestException methods //
- ////////////////////////////////
+ // //////////////////////////////
/**
* Returns the bundle file name.
* <P>
+ *
* @return name of bundle class associated with this exception.
*/
protected String getBundleName() {
return SELFTEST_RESOURCES;
}
-
- ////////////////////////////////////////
+ // //////////////////////////////////////
// EBaseException methods (inherited) //
- ////////////////////////////////////////
+ // //////////////////////////////////////
- /* Note that all of the following EBaseException methods
- * are inherited from the EBaseException class:
- *
+ /*
+ * Note that all of the following EBaseException methods are inherited from
+ * the EBaseException class:
+ *
* public EBaseException( String msgFormat );
- *
+ *
* public EBaseException( String msgFormat, String param );
- *
+ *
* public EBaseException( String msgFormat, Exception param );
- *
+ *
* public EBaseException( String msgFormat, Object params[] );
- *
+ *
* public Object[] getParameters();
- *
+ *
* public String toString();
- *
+ *
* public String toString( Locale locale );
*/
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/selftests/ISelfTest.java b/pki/base/common/src/com/netscape/certsrv/selftests/ISelfTest.java
index f881a285..357544f7 100644
--- a/pki/base/common/src/com/netscape/certsrv/selftests/ISelfTest.java
+++ b/pki/base/common/src/com/netscape/certsrv/selftests/ISelfTest.java
@@ -20,7 +20,6 @@
package com.netscape.certsrv.selftests;
-
///////////////////////
// import statements //
///////////////////////
@@ -30,7 +29,6 @@ import java.util.Locale;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.logging.ILogEventListener;
-
//////////////////////
// class definition //
//////////////////////
@@ -42,86 +40,82 @@ import com.netscape.certsrv.logging.ILogEventListener;
* @version $Revision$, $Date$
*/
public interface ISelfTest {
- ////////////////////////
+ // //////////////////////
// default parameters //
- ////////////////////////
-
-
+ // //////////////////////
- //////////////////////////
+ // ////////////////////////
// ISelfTest parameters //
- //////////////////////////
+ // ////////////////////////
public static final String PROP_PLUGIN = "plugin";
- /////////////////////
+ // ///////////////////
// default methods //
- /////////////////////
+ // ///////////////////
-
-
- ///////////////////////
+ // /////////////////////
// ISelfTest methods //
- ///////////////////////
+ // /////////////////////
/**
- * Initializes this subsystem with the configuration store
- * associated with this instance name.
+ * Initializes this subsystem with the configuration store associated with
+ * this instance name.
* <P>
- *
+ *
* @param subsystem the associated subsystem
- * @param instanceName the name of this self test instance
+ * @param instanceName the name of this self test instance
* @param parameters configuration store (self test parameters)
* @exception EDuplicateSelfTestException subsystem has duplicate name/value
* @exception EInvalidSelfTestException subsystem has invalid name/value
* @exception EMissingSelfTestException subsystem has missing name/value
*/
public void initSelfTest(ISelfTestSubsystem subsystem,
- String instanceName,
- IConfigStore parameters)
- throws EDuplicateSelfTestException,
+ String instanceName,
+ IConfigStore parameters)
+ throws EDuplicateSelfTestException,
EInvalidSelfTestException,
EMissingSelfTestException;
/**
* Notifies this subsystem if it is in execution mode.
* <P>
- *
+ *
* @exception ESelfTestException failed to start
*/
public void startupSelfTest()
- throws ESelfTestException;
+ throws ESelfTestException;
/**
- * Stops this subsystem. The subsystem may call shutdownSelfTest
- * anytime after initialization.
+ * Stops this subsystem. The subsystem may call shutdownSelfTest anytime
+ * after initialization.
* <P>
*/
public void shutdownSelfTest();
/**
- * Returns the name associated with this self test. This method may
- * return null if the self test has not been intialized.
+ * Returns the name associated with this self test. This method may return
+ * null if the self test has not been intialized.
* <P>
- *
+ *
* @return instanceName of this self test
*/
public String getSelfTestName();
/**
- * Returns the root configuration storage (self test parameters)
- * associated with this subsystem.
+ * Returns the root configuration storage (self test parameters) associated
+ * with this subsystem.
* <P>
- *
+ *
* @return configuration store (self test parameters) of this subsystem
*/
public IConfigStore getSelfTestConfigStore();
/**
- * Retrieves description associated with an individual self test.
- * This method may return null.
+ * Retrieves description associated with an individual self test. This
+ * method may return null.
* <P>
- *
+ *
* @param locale locale of the client that requests the description
* @return description of self test
*/
@@ -130,11 +124,10 @@ public interface ISelfTest {
/**
* Execute an individual self test.
* <P>
- *
+ *
* @param logger specifies logging subsystem
* @exception ESelfTestException self test exception
*/
public void runSelfTest(ILogEventListener logger)
- throws ESelfTestException;
+ throws ESelfTestException;
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/selftests/ISelfTestSubsystem.java b/pki/base/common/src/com/netscape/certsrv/selftests/ISelfTestSubsystem.java
index 3391bdd1..392a80e5 100644
--- a/pki/base/common/src/com/netscape/certsrv/selftests/ISelfTestSubsystem.java
+++ b/pki/base/common/src/com/netscape/certsrv/selftests/ISelfTestSubsystem.java
@@ -20,7 +20,6 @@
package com.netscape.certsrv.selftests;
-
///////////////////////
// import statements //
///////////////////////
@@ -28,7 +27,6 @@ package com.netscape.certsrv.selftests;
import com.netscape.certsrv.base.ISubsystem;
import com.netscape.certsrv.logging.ILogEventListener;
-
//////////////////////
// class definition //
//////////////////////
@@ -40,16 +38,14 @@ import com.netscape.certsrv.logging.ILogEventListener;
* @version $Revision$, $Date$
*/
public interface ISelfTestSubsystem
- extends ISubsystem {
- ////////////////////////
+ extends ISubsystem {
+ // //////////////////////
// default parameters //
- ////////////////////////
-
+ // //////////////////////
-
- //////////////////////////////////
+ // ////////////////////////////////
// ISelfTestSubsystem constants //
- //////////////////////////////////
+ // ////////////////////////////////
public static final String ID = "selftests";
public static final String PROP_CONTAINER = "container";
@@ -60,21 +56,17 @@ public interface ISelfTestSubsystem
public static final String PROP_ON_DEMAND = "onDemand";
public static final String PROP_STARTUP = "startup";
- ///////////////////////////////////////
+ // /////////////////////////////////////
// ISubsystem parameters (inherited) //
- ///////////////////////////////////////
-
+ // /////////////////////////////////////
-
- /////////////////////
+ // ///////////////////
// default methods //
- /////////////////////
-
+ // ///////////////////
-
- ////////////////////////////////
+ // //////////////////////////////
// ISelfTestSubsystem methods //
- ////////////////////////////////
+ // //////////////////////////////
//
// methods associated with the list of on demand self tests
@@ -84,7 +76,7 @@ public interface ISelfTestSubsystem
* List the instance names of all the self tests enabled to run on demand
* (in execution order); may return null.
* <P>
- *
+ *
* @return list of self test instance names run on demand
*/
public String[] listSelfTestsEnabledOnDemand();
@@ -92,72 +84,70 @@ public interface ISelfTestSubsystem
/**
* Enable the specified self test to be executed on demand.
* <P>
- *
+ *
* @param instanceName instance name of self test
- * @param isCritical isCritical is either a critical failure (true) or
- * a non-critical failure (false)
+ * @param isCritical isCritical is either a critical failure (true) or a
+ * non-critical failure (false)
* @exception EInvalidSelfTestException subsystem has invalid name/value
* @exception EMissingSelfTestException subsystem has missing name/value
*/
- // public void enableSelfTestOnDemand( String instanceName,
- // boolean isCritical )
- // throws EInvalidSelfTestException, EMissingSelfTestException;
-
+ // public void enableSelfTestOnDemand( String instanceName,
+ // boolean isCritical )
+ // throws EInvalidSelfTestException, EMissingSelfTestException;
/**
* Disable the specified self test from being able to be executed on demand.
* <P>
- *
+ *
* @param instanceName instance name of self test
* @exception EMissingSelfTestException subsystem has missing name
*/
- // public void disableSelfTestOnDemand( String instanceName )
- // throws EMissingSelfTestException;
-
+ // public void disableSelfTestOnDemand( String instanceName )
+ // throws EMissingSelfTestException;
/**
* Determine if the specified self test is enabled to be executed on demand.
* <P>
- *
+ *
* @param instanceName instance name of self test
* @return true if the specified self test is enabled on demand
* @exception EMissingSelfTestException subsystem has missing name
*/
public boolean isSelfTestEnabledOnDemand(String instanceName)
- throws EMissingSelfTestException;
+ throws EMissingSelfTestException;
/**
- * Determine if failure of the specified self test is fatal when
- * it is executed on demand.
+ * Determine if failure of the specified self test is fatal when it is
+ * executed on demand.
* <P>
- *
+ *
* @param instanceName instance name of self test
- * @return true if failure of the specified self test is fatal when
- * it is executed on demand
+ * @return true if failure of the specified self test is fatal when it is
+ * executed on demand
* @exception EMissingSelfTestException subsystem has missing name
*/
public boolean isSelfTestCriticalOnDemand(String instanceName)
- throws EMissingSelfTestException;
+ throws EMissingSelfTestException;
/**
* Execute all self tests specified to be run on demand.
* <P>
- *
+ *
* @exception EMissingSelfTestException subsystem has missing name
* @exception ESelfTestException self test exception
*/
public void runSelfTestsOnDemand()
- throws EMissingSelfTestException, ESelfTestException;
+ throws EMissingSelfTestException, ESelfTestException;
//
// methods associated with the list of startup self tests
//
/**
- * List the instance names of all the self tests enabled to run
- * at server startup (in execution order); may return null.
+ * List the instance names of all the self tests enabled to run at server
+ * startup (in execution order); may return null.
* <P>
- *
+ *
* @return list of self test instance names run at server startup
*/
public String[] listSelfTestsEnabledAtStartup();
@@ -165,73 +155,71 @@ public interface ISelfTestSubsystem
/**
* Enable the specified self test at server startup.
* <P>
- *
+ *
* @param instanceName instance name of self test
- * @param isCritical isCritical is either a critical failure (true) or
- * a non-critical failure (false)
+ * @param isCritical isCritical is either a critical failure (true) or a
+ * non-critical failure (false)
* @exception EInvalidSelfTestException subsystem has invalid name/value
* @exception EMissingSelfTestException subsystem has missing name/value
*/
- // public void enableSelfTestAtStartup( String instanceName,
- // boolean isCritical )
- // throws EInvalidSelfTestException, EMissingSelfTestException;
-
+ // public void enableSelfTestAtStartup( String instanceName,
+ // boolean isCritical )
+ // throws EInvalidSelfTestException, EMissingSelfTestException;
/**
* Disable the specified self test at server startup.
* <P>
- *
+ *
* @param instanceName instance name of self test
* @exception EMissingSelfTestException subsystem has missing name
*/
- // public void disableSelfTestAtStartup( String instanceName )
- // throws EMissingSelfTestException;
-
+ // public void disableSelfTestAtStartup( String instanceName )
+ // throws EMissingSelfTestException;
/**
- * Determine if the specified self test is executed automatically
- * at server startup.
+ * Determine if the specified self test is executed automatically at server
+ * startup.
* <P>
- *
+ *
* @param instanceName instance name of self test
* @return true if the specified self test is executed at server startup
* @exception EMissingSelfTestException subsystem has missing name
*/
public boolean isSelfTestEnabledAtStartup(String instanceName)
- throws EMissingSelfTestException;
+ throws EMissingSelfTestException;
/**
- * Determine if failure of the specified self test is fatal to
- * server startup.
+ * Determine if failure of the specified self test is fatal to server
+ * startup.
* <P>
- *
+ *
* @param instanceName instance name of self test
- * @return true if failure of the specified self test is fatal to
- * server startup
+ * @return true if failure of the specified self test is fatal to server
+ * startup
* @exception EMissingSelfTestException subsystem has missing name
*/
public boolean isSelfTestCriticalAtStartup(String instanceName)
- throws EMissingSelfTestException;
+ throws EMissingSelfTestException;
/**
* Execute all self tests specified to be run at server startup.
* <P>
- *
+ *
* @exception EMissingSelfTestException subsystem has missing name
* @exception ESelfTestException self test exception
*/
public void runSelfTestsAtStartup()
- throws EMissingSelfTestException, ESelfTestException;
+ throws EMissingSelfTestException, ESelfTestException;
//
// methods associated with the list of self test instances
//
/**
- * Retrieve an individual self test from the instances list
- * given its instance name.
+ * Retrieve an individual self test from the instances list given its
+ * instance name.
* <P>
- *
+ *
* @param instanceName instance name of self test
* @return individual self test
*/
@@ -242,10 +230,10 @@ public interface ISelfTestSubsystem
//
/**
- * Returns the ILogEventListener of this subsystem.
- * This method may return null.
+ * Returns the ILogEventListener of this subsystem. This method may return
+ * null.
* <P>
- *
+ *
* @return ILogEventListener of this subsystem
*/
public ILogEventListener getSelfTestLogger();
@@ -253,104 +241,97 @@ public interface ISelfTestSubsystem
/**
* This method represents the log interface for the self test subsystem.
* <P>
- *
+ *
* @param logger log event listener
* @param msg self test log message
*/
public void log(ILogEventListener logger, String msg);
/**
- * Register an individual self test on the instances list AND
- * on the "on demand" list (note that the specified self test
- * will be appended to the end of each list).
+ * Register an individual self test on the instances list AND on the
+ * "on demand" list (note that the specified self test will be appended to
+ * the end of each list).
* <P>
- *
+ *
* @param instanceName instance name of self test
- * @param isCritical isCritical is either a critical failure (true) or
- * a non-critical failure (false)
+ * @param isCritical isCritical is either a critical failure (true) or a
+ * non-critical failure (false)
* @param instance individual self test
* @exception EDuplicateSelfTestException subsystem has duplicate name
* @exception EInvalidSelfTestException subsystem has invalid name/value
* @exception EMissingSelfTestException subsystem has missing name/value
*/
- // public void registerSelfTestOnDemand( String instanceName,
- // boolean isCritical,
- // ISelfTest instance )
- // throws EDuplicateSelfTestException,
- // EInvalidSelfTestException,
- // EMissingSelfTestException;
-
+ // public void registerSelfTestOnDemand( String instanceName,
+ // boolean isCritical,
+ // ISelfTest instance )
+ // throws EDuplicateSelfTestException,
+ // EInvalidSelfTestException,
+ // EMissingSelfTestException;
/**
- * Deregister an individual self test on the instances list AND
- * on the "on demand" list (note that the specified self test
- * will be removed from each list).
+ * Deregister an individual self test on the instances list AND on the
+ * "on demand" list (note that the specified self test will be removed from
+ * each list).
* <P>
- *
+ *
* @param instanceName instance name of self test
* @exception EMissingSelfTestException subsystem has missing name
*/
- // public void deregisterSelfTestOnDemand( String instanceName )
- // throws EMissingSelfTestException;
-
+ // public void deregisterSelfTestOnDemand( String instanceName )
+ // throws EMissingSelfTestException;
/**
- * Register an individual self test on the instances list AND
- * on the "startup" list (note that the specified self test
- * will be appended to the end of each list).
+ * Register an individual self test on the instances list AND on the
+ * "startup" list (note that the specified self test will be appended to the
+ * end of each list).
* <P>
- *
+ *
* @param instanceName instance name of self test
- * @param isCritical isCritical is either a critical failure (true) or
- * a non-critical failure (false)
+ * @param isCritical isCritical is either a critical failure (true) or a
+ * non-critical failure (false)
* @param instance individual self test
* @exception EDuplicateSelfTestException subsystem has duplicate name
* @exception EInvalidSelfTestException subsystem has invalid name/value
* @exception EMissingSelfTestException subsystem has missing name/value
*/
- // public void registerSelfTestAtStartup( String instanceName,
- // boolean isCritical,
- // ISelfTest instance )
- // throws EDuplicateSelfTestException,
- // EInvalidSelfTestException,
- // EMissingSelfTestException;
-
+ // public void registerSelfTestAtStartup( String instanceName,
+ // boolean isCritical,
+ // ISelfTest instance )
+ // throws EDuplicateSelfTestException,
+ // EInvalidSelfTestException,
+ // EMissingSelfTestException;
/**
- * Deregister an individual self test on the instances list AND
- * on the "startup" list (note that the specified self test
- * will be removed from each list).
+ * Deregister an individual self test on the instances list AND on the
+ * "startup" list (note that the specified self test will be removed from
+ * each list).
* <P>
- *
+ *
* @param instanceName instance name of self test
* @exception EMissingSelfTestException subsystem has missing name
*/
- // public void deregisterSelfTestAtStartup( String instanceName )
- // throws EMissingSelfTestException;
-
+ // public void deregisterSelfTestAtStartup( String instanceName )
+ // throws EMissingSelfTestException;
-
- ////////////////////////////////////
+ // //////////////////////////////////
// ISubsystem methods (inherited) //
- ////////////////////////////////////
-
- /* Note that all of the following ISubsystem methods
- * are inherited from the ISubsystem class:
- *
- * public String getId();
- *
- * public void setId( String id )
- * throws EBaseException;
- *
- * public void init( ISubsystem owner, IConfigStore config )
- * throws EBaseException;
- *
- * public void startup()
- * throws EBaseException;
- *
- * public void shutdown();
- *
- * public IConfigStore getConfigStore();
+ // //////////////////////////////////
+
+ /*
+ * Note that all of the following ISubsystem methods are inherited from the
+ * ISubsystem class:
+ *
+ * public String getId();
+ *
+ * public void setId( String id ) throws EBaseException;
+ *
+ * public void init( ISubsystem owner, IConfigStore config ) throws
+ * EBaseException;
+ *
+ * public void startup() throws EBaseException;
+ *
+ * public void shutdown();
+ *
+ * public IConfigStore getConfigStore();
*/
}
-
diff --git a/pki/base/common/src/com/netscape/certsrv/selftests/SelfTestResources.java b/pki/base/common/src/com/netscape/certsrv/selftests/SelfTestResources.java
index c396c14b..c7c4d372 100644
--- a/pki/base/common/src/com/netscape/certsrv/selftests/SelfTestResources.java
+++ b/pki/base/common/src/com/netscape/certsrv/selftests/SelfTestResources.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.selftests;
-
import java.util.ListResourceBundle;
-
/**
* A class represents a resource bundle for Self Tests.
* <P>
diff --git a/pki/base/common/src/com/netscape/certsrv/template/ArgList.java b/pki/base/common/src/com/netscape/certsrv/template/ArgList.java
index 72288a73..4ea2fb48 100644
--- a/pki/base/common/src/com/netscape/certsrv/template/ArgList.java
+++ b/pki/base/common/src/com/netscape/certsrv/template/ArgList.java
@@ -20,11 +20,10 @@ package com.netscape.certsrv.template;
import java.util.Vector;
/**
- * This class represents a list of arguments
- * that will be returned to the end-user via
- * the template framework.
+ * This class represents a list of arguments that will be returned to the
+ * end-user via the template framework.
* <p>
- *
+ *
* @version $Revision$, $Date$
*/
public class ArgList implements IArgValue {
@@ -39,16 +38,16 @@ public class ArgList implements IArgValue {
/**
* Adds an argument to the list.
- *
+ *
* @param arg argument to be added
*/
public void add(IArgValue arg) {
mList.addElement(arg);
}
- /**
+ /**
* Returns the number of arguments in the list.
- *
+ *
* @return size of the list
*/
public int size() {
@@ -56,9 +55,8 @@ public class ArgList implements IArgValue {
}
/**
- * Returns the argument at the given position
- * Position starts from 0.
- *
+ * Returns the argument at the given position Position starts from 0.
+ *
* @param pos position
* @return argument
*/
diff --git a/pki/base/common/src/com/netscape/certsrv/template/ArgSet.java b/pki/base/common/src/com/netscape/certsrv/template/ArgSet.java
index 471371f9..f5e1badd 100644
--- a/pki/base/common/src/com/netscape/certsrv/template/ArgSet.java
+++ b/pki/base/common/src/com/netscape/certsrv/template/ArgSet.java
@@ -21,12 +21,10 @@ import java.util.Enumeration;
import java.util.Hashtable;
/**
- * This class represents a set of arguments.
- * Unlike ArgList, this set of arguments is
- * not ordered.
+ * This class represents a set of arguments. Unlike ArgList, this set of
+ * arguments is not ordered.
* <p>
- * Each argument in the set is tagged with
- * a name (key).
+ * Each argument in the set is tagged with a name (key).
* <p>
*
* @version $Revision$, $Date$
@@ -36,7 +34,7 @@ public class ArgSet implements IArgValue {
/**
* Returns a list of argument names.
- *
+ *
* @return list of argument names
*/
public Enumeration<String> getNames() {
@@ -45,17 +43,17 @@ public class ArgSet implements IArgValue {
/**
* Sets string argument into the set with the given name.
- *
+ *
* @param name argument name
* @param arg argument in string
*/
public void set(String name, String arg) {
- mArgs.put(name, new ArgString (arg));
+ mArgs.put(name, new ArgString(arg));
}
/**
* Sets argument into the set with the given name.
- *
+ *
* @param name argument name
* @param arg argument value
*/
@@ -65,7 +63,7 @@ public class ArgSet implements IArgValue {
/**
* Retrieves argument from the set.
- *
+ *
* @param name argument name
* @return argument value
*/
diff --git a/pki/base/common/src/com/netscape/certsrv/template/ArgString.java b/pki/base/common/src/com/netscape/certsrv/template/ArgString.java
index 385338ca..4fb982eb 100644
--- a/pki/base/common/src/com/netscape/certsrv/template/ArgString.java
+++ b/pki/base/common/src/com/netscape/certsrv/template/ArgString.java
@@ -17,11 +17,9 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.template;
-
-
/**
* This class represents a string-based argument.
- *
+ *
* @version $Revision$, $Date$
*/
public class ArgString implements IArgValue {
@@ -29,7 +27,7 @@ public class ArgString implements IArgValue {
/**
* Constructs a string-based argument value.
- *
+ *
* @param value argument value
*/
public ArgString(String value) {
@@ -38,7 +36,7 @@ public class ArgString implements IArgValue {
/**
* Returns the argument value.
- *
+ *
* @return argument value
*/
public String getValue() {
diff --git a/pki/base/common/src/com/netscape/certsrv/template/IArgValue.java b/pki/base/common/src/com/netscape/certsrv/template/IArgValue.java
index d679f0a1..27694a06 100644
--- a/pki/base/common/src/com/netscape/certsrv/template/IArgValue.java
+++ b/pki/base/common/src/com/netscape/certsrv/template/IArgValue.java
@@ -18,10 +18,9 @@
package com.netscape.certsrv.template;
/**
- * This interface presents a generic argument value.
- * Argument value can be in string, in a list, or
- * in a set.
- *
+ * This interface presents a generic argument value. Argument value can be in
+ * string, in a list, or in a set.
+ *
* @version $Revision$, $Date$
*/
public interface IArgValue {
diff --git a/pki/base/common/src/com/netscape/certsrv/tks/ITKSAuthority.java b/pki/base/common/src/com/netscape/certsrv/tks/ITKSAuthority.java
index 0fec3043..4806da66 100644
--- a/pki/base/common/src/com/netscape/certsrv/tks/ITKSAuthority.java
+++ b/pki/base/common/src/com/netscape/certsrv/tks/ITKSAuthority.java
@@ -17,16 +17,14 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.tks;
-
import com.netscape.certsrv.base.ISubsystem;
import com.netscape.certsrv.request.IRequestQueue;
-
/**
- * An interface represents a Registration Authority that is
- * responsible for certificate enrollment operations.
+ * An interface represents a Registration Authority that is responsible for
+ * certificate enrollment operations.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public interface ITKSAuthority extends ISubsystem {
@@ -36,23 +34,21 @@ public interface ITKSAuthority extends ISubsystem {
public static final String PROP_REGISTRATION = "Registration";
public static final String PROP_GATEWAY = "gateway";
public static final String PROP_NICKNAME = "certNickname";
- //public final static String PROP_PUBLISH_SUBSTORE = "publish";
- //public final static String PROP_LDAP_PUBLISH_SUBSTORE = "ldappublish";
+ // public final static String PROP_PUBLISH_SUBSTORE = "publish";
+ // public final static String PROP_LDAP_PUBLISH_SUBSTORE = "ldappublish";
public final static String PROP_CONNECTOR = "connector";
public final static String PROP_NEW_NICKNAME = "newNickname";
-
-
/**
* Retrieves the request queue of this registration authority.
- *
+ *
* @return RA's request queue
*/
public IRequestQueue getRequestQueue();
/**
* Returns the nickname of the RA certificate.
- *
+ *
* @return the nickname of the RA certificate
*/
public String getNickname();
diff --git a/pki/base/common/src/com/netscape/certsrv/usrgrp/Certificates.java b/pki/base/common/src/com/netscape/certsrv/usrgrp/Certificates.java
index c5711725..1251eca6 100644
--- a/pki/base/common/src/com/netscape/certsrv/usrgrp/Certificates.java
+++ b/pki/base/common/src/com/netscape/certsrv/usrgrp/Certificates.java
@@ -17,14 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.usrgrp;
-
import java.security.cert.X509Certificate;
-
/**
- * This class defines the strong authentication basic elements,
- * the X509 certificates.
- *
+ * This class defines the strong authentication basic elements, the X509
+ * certificates.
+ *
* @version $Revision$, $Date$
*/
public class Certificates {
@@ -33,6 +31,7 @@ public class Certificates {
/**
* Constructs strong authenticator.
+ *
* @param certs a list of X509Certificates
*/
public Certificates(X509Certificate certs[]) {
@@ -41,6 +40,7 @@ public class Certificates {
/**
* Retrieves certificates.
+ *
* @return a list of X509Certificates
*/
public X509Certificate[] getCertificates() {
diff --git a/pki/base/common/src/com/netscape/certsrv/usrgrp/EUsrGrpException.java b/pki/base/common/src/com/netscape/certsrv/usrgrp/EUsrGrpException.java
index ca4634a6..a25a1a6b 100644
--- a/pki/base/common/src/com/netscape/certsrv/usrgrp/EUsrGrpException.java
+++ b/pki/base/common/src/com/netscape/certsrv/usrgrp/EUsrGrpException.java
@@ -17,14 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.usrgrp;
-
import com.netscape.certsrv.base.EBaseException;
-
/**
* A class represents a Identity exception.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class EUsrGrpException extends EBaseException {
@@ -40,8 +38,9 @@ public class EUsrGrpException extends EBaseException {
/**
* Constructs a usr/grp management exception
+ *
* @param msgFormat exception details in message string format
- * <P>
+ * <P>
*/
public EUsrGrpException(String msgFormat) {
super(msgFormat);
@@ -49,9 +48,10 @@ public class EUsrGrpException extends EBaseException {
/**
* Constructs a Identity exception.
+ *
* @param msgFormat exception details in message string format
* @param param message string parameter
- * <P>
+ * <P>
*/
public EUsrGrpException(String msgFormat, String param) {
super(msgFormat, param);
@@ -59,8 +59,9 @@ public class EUsrGrpException extends EBaseException {
/**
* Constructs a Identity exception.
+ *
* @param e system exception
- * <P>
+ * <P>
*/
public EUsrGrpException(String msgFormat, Exception e) {
super(msgFormat, e);
@@ -68,9 +69,10 @@ public class EUsrGrpException extends EBaseException {
/**
* Constructs a Identity exception.
+ *
* @param msgFormat exception details in message string format
* @param params list of message format parameters
- * <P>
+ * <P>
*/
public EUsrGrpException(String msgFormat, Object params[]) {
super(msgFormat, params);
diff --git a/pki/base/common/src/com/netscape/certsrv/usrgrp/ICertUserLocator.java b/pki/base/common/src/com/netscape/certsrv/usrgrp/ICertUserLocator.java
index a9d789e6..4c40c69a 100644
--- a/pki/base/common/src/com/netscape/certsrv/usrgrp/ICertUserLocator.java
+++ b/pki/base/common/src/com/netscape/certsrv/usrgrp/ICertUserLocator.java
@@ -17,25 +17,24 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.usrgrp;
-
import netscape.ldap.LDAPException;
import com.netscape.certsrv.ldap.ELdapException;
-
/**
- * This interface defines a certificate mapping strategy to locate
- * a user
- *
+ * This interface defines a certificate mapping strategy to locate a user
+ *
* @version $Revision$, $Date$
*/
public interface ICertUserLocator {
/**
* Returns a user whose certificates match with the given certificates
+ *
* @return an user interface
- * @exception EUsrGrpException thrown when failed to build user
- * @exception LDAPException thrown when LDAP internal database is not available
+ * @exception EUsrGrpException thrown when failed to build user
+ * @exception LDAPException thrown when LDAP internal database is not
+ * available
* @exception ELdapException thrown when the LDAP search failed
*/
public IUser locateUser(Certificates certs) throws
@@ -43,6 +42,7 @@ public interface ICertUserLocator {
/**
* Retrieves description.
+ *
* @return description
*/
public String getDescription();
diff --git a/pki/base/common/src/com/netscape/certsrv/usrgrp/IGroup.java b/pki/base/common/src/com/netscape/certsrv/usrgrp/IGroup.java
index 778b9aab..cddb649c 100644
--- a/pki/base/common/src/com/netscape/certsrv/usrgrp/IGroup.java
+++ b/pki/base/common/src/com/netscape/certsrv/usrgrp/IGroup.java
@@ -17,53 +17,58 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.usrgrp;
-
import java.util.Enumeration;
import com.netscape.certsrv.base.IAttrSet;
-
/**
- * This interface defines the basic interfaces for
- * an identity group. (get/set methods for a group entry attributes)
- *
+ * This interface defines the basic interfaces for an identity group. (get/set
+ * methods for a group entry attributes)
+ *
* @version $Revision$, $Date$
*/
public interface IGroup extends IAttrSet, IGroupConstants {
/**
* Retrieves the group name.
+ *
* @return the group name
*/
public String getName();
/**
* Retrieves group identifier.
+ *
* @return the group id
*/
public String getGroupID();
/**
* Retrieves group description.
+ *
* @return description
*/
public String getDescription();
/**
* Checks if the given name is member of this group.
+ *
* @param name the given name
- * @return true if the given name is the member of this group; otherwise false.
+ * @return true if the given name is the member of this group; otherwise
+ * false.
*/
public boolean isMember(String name);
/**
* Adds new member.
+ *
* @param name the given name.
*/
public void addMemberName(String name);
/**
* Retrieves a list of member names.
+ *
* @return a list of member names for this group.
*/
public Enumeration getMemberNames();
diff --git a/pki/base/common/src/com/netscape/certsrv/usrgrp/IGroupConstants.java b/pki/base/common/src/com/netscape/certsrv/usrgrp/IGroupConstants.java
index 2f8711ce..22d89455 100644
--- a/pki/base/common/src/com/netscape/certsrv/usrgrp/IGroupConstants.java
+++ b/pki/base/common/src/com/netscape/certsrv/usrgrp/IGroupConstants.java
@@ -17,12 +17,9 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.usrgrp;
-
-
-
/**
* This interface defines the attribute names for a group entry
- *
+ *
* @version $Revision$, $Date$
*/
public interface IGroupConstants {
diff --git a/pki/base/common/src/com/netscape/certsrv/usrgrp/IIdEvaluator.java b/pki/base/common/src/com/netscape/certsrv/usrgrp/IIdEvaluator.java
index 94bdf885..103b1026 100644
--- a/pki/base/common/src/com/netscape/certsrv/usrgrp/IIdEvaluator.java
+++ b/pki/base/common/src/com/netscape/certsrv/usrgrp/IIdEvaluator.java
@@ -17,9 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.usrgrp;
-
-
-
/**
* A class represents an ID evaluator.
* <P>
@@ -29,8 +26,9 @@ package com.netscape.certsrv.usrgrp;
public interface IIdEvaluator {
/**
- * Evaluates if the given value satisfies the ID evaluation:
- * is a user a member of a group
+ * Evaluates if the given value satisfies the ID evaluation: is a user a
+ * member of a group
+ *
* @param type the type of evaluator, in this case, it is group
* @param id the user id for the given user
* @param op operator, only "=" and "!=" are supported
diff --git a/pki/base/common/src/com/netscape/certsrv/usrgrp/IUGSubsystem.java b/pki/base/common/src/com/netscape/certsrv/usrgrp/IUGSubsystem.java
index ff6f7be6..5857e3e9 100644
--- a/pki/base/common/src/com/netscape/certsrv/usrgrp/IUGSubsystem.java
+++ b/pki/base/common/src/com/netscape/certsrv/usrgrp/IUGSubsystem.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.usrgrp;
-
import java.security.cert.X509Certificate;
import java.util.Enumeration;
@@ -25,12 +24,10 @@ import netscape.ldap.LDAPException;
import com.netscape.certsrv.base.ISubsystem;
-
/**
- * This class defines low-level LDAP usr/grp management
- * usr/grp information is located remotely on another
- * LDAP server.
- *
+ * This class defines low-level LDAP usr/grp management usr/grp information is
+ * located remotely on another LDAP server.
+ *
* @version $Revision$, $Date$
*/
public interface IUGSubsystem extends ISubsystem, IUsrGrp {
@@ -47,6 +44,7 @@ public interface IUGSubsystem extends ISubsystem, IUsrGrp {
/**
* Retrieves a user from LDAP
+ *
* @param userid the given user id
* @exception EUsrGrpException thrown when failed to find the user
*/
@@ -54,6 +52,7 @@ public interface IUGSubsystem extends ISubsystem, IUsrGrp {
/**
* Searches for users that matches the filter.
+ *
* @param filter search filter for efficiency
* @return list of users
* @exception EUsrGrpException thrown when any internal error occurs
@@ -62,48 +61,57 @@ public interface IUGSubsystem extends ISubsystem, IUsrGrp {
/**
* Adds the given user to the internal database
+ *
* @param identity the given user
* @exception EUsrGrpException thrown when failed to add user to the group
- * @exception LDAPException thrown when the LDAP internal database is not available
+ * @exception LDAPException thrown when the LDAP internal database is not
+ * available
*/
public void addUser(IUser identity) throws EUsrGrpException, LDAPException;
/**
* Adds a user certificate to user
+ *
* @param identity user interface
- * @exception EUsrGrpException thrown when failed to add the user certificate to the given user
- * @exception LDAPException thrown when the LDAP internal database is not available
+ * @exception EUsrGrpException thrown when failed to add the user
+ * certificate to the given user
+ * @exception LDAPException thrown when the LDAP internal database is not
+ * available
*/
public void addUserCert(IUser identity) throws EUsrGrpException,
LDAPException;
/**
- * Removes a user certificate for a user entry
- * given a user certificate DN (actually, a combination of version,
- * serialNumber, issuerDN, and SubjectDN), and it gets removed
- * @param identity the given user whose user certificate is going to be
- * be removed.
+ * Removes a user certificate for a user entry given a user certificate DN
+ * (actually, a combination of version, serialNumber, issuerDN, and
+ * SubjectDN), and it gets removed
+ *
+ * @param identity the given user whose user certificate is going to be be
+ * removed.
* @exception EUsrGrpException thrown when failed to remove user certificate
*/
public void removeUserCert(IUser identity) throws EUsrGrpException;
/**
* Removes identity.
+ *
* @param userid the given user id
* @exception EUsrGrpException thrown when failed to remove user
*/
public void removeUser(String userid) throws EUsrGrpException;
/**
- * Modifies user attributes. Certs are handled separately
- * @param identity the given identity which contains all the user
- * attributes being modified
+ * Modifies user attributes. Certs are handled separately
+ *
+ * @param identity the given identity which contains all the user attributes
+ * being modified
* @exception EUsrGrpException thrown when modification failed
*/
public void modifyUser(IUser identity) throws EUsrGrpException;
/**
* Finds groups that match the filter.
+ *
* @param filter the search filter
* @return a list of groups that match the given search filter
*/
@@ -111,24 +119,27 @@ public interface IUGSubsystem extends ISubsystem, IUsrGrp {
/**
* Find a group for the given name
+ *
* @param name the given name
* @return a group that matched the given name
*/
public IGroup findGroup(String name);
/**
- * List groups. This method is more efficient than findGroups because
- * this method retrieves group names and description only. Each
- * retrieved group just contains group name and description.
+ * List groups. This method is more efficient than findGroups because this
+ * method retrieves group names and description only. Each retrieved group
+ * just contains group name and description.
+ *
* @param filter the search filter
- * @return a list of groups, each group just contains group name and
- * its description.
+ * @return a list of groups, each group just contains group name and its
+ * description.
* @exception EUsrGrpException thrown when failed to list groups
*/
public Enumeration<IGroup> listGroups(String filter) throws EUsrGrpException;
/**
* Retrieves a group from LDAP for the given group name
+ *
* @param name the given group name
* @return a group interface
*/
@@ -136,37 +147,44 @@ public interface IUGSubsystem extends ISubsystem, IUsrGrp {
/**
* Retrieves a group from LDAP for the given DN.
- * @param DN the given DN
+ *
+ * @param DN the given DN
* @return a group interface for the given DN.
*/
public IGroup getGroup(String DN);
/**
* Checks if the given group exists.
+ *
* @param name the given group name
- * @return true if the given group exists in the internal database; otherwise false.
+ * @return true if the given group exists in the internal database;
+ * otherwise false.
*/
public boolean isGroupPresent(String name);
/**
* Checks if the given context is a member of the given group
+ *
* @param uid the given user id
* @param name the given group name
- * @return true if the user with the given user id is a member of the given
- * group
+ * @return true if the user with the given user id is a member of the given
+ * group
*/
public boolean isMemberOf(String uid, String name);
+
public boolean isMemberOf(IUser id, String name);
/**
* Adds a group of identities.
+ *
* @param group the given group
* @exception EUsrGrpException thrown when failed to add group.
*/
public void addGroup(IGroup group) throws EUsrGrpException;
/**
- * Removes a group. Can't remove SUPER_CERT_ADMINS
+ * Removes a group. Can't remove SUPER_CERT_ADMINS
+ *
* @param name the given group name
* @exception EUsrGrpException thrown when the given group failed to remove
*/
@@ -174,24 +192,27 @@ public interface IUGSubsystem extends ISubsystem, IUsrGrp {
/**
* Modifies a group.
+ *
* @param group the given group which contain all group attributes being
- * modified.
+ * modified.
* @exception EUsrGrpException thrown when failed to modify group.
*/
public void modifyGroup(IGroup group) throws EUsrGrpException;
/**
* Removes the user with the given id from the given group
+ *
* @param grp the given group
* @param userid the given user id
* @exception EUsrGrpException thrown when failed to remove the user from
- * the given group
+ * the given group
*/
public void removeUserFromGroup(IGroup grp, String userid)
- throws EUsrGrpException;
+ throws EUsrGrpException;
/**
* Create user with the given id.
+ *
* @param id the user with the given id.
* @return a new user
*/
@@ -199,6 +220,7 @@ public interface IUGSubsystem extends ISubsystem, IUsrGrp {
/**
* Create group with the given id.
+ *
* @param id the group with the given id.
* @return a new group
*/
@@ -206,24 +228,29 @@ public interface IUGSubsystem extends ISubsystem, IUsrGrp {
/**
* Get string representation of the given certificate
+ *
* @param cert given certificate
* @return the string representation of the given certificate
*/
public String getCertificateString(X509Certificate cert);
/**
- * Searchs for identities that matches the certificate locater
- * generated filter.
+ * Searchs for identities that matches the certificate locater generated
+ * filter.
+ *
* @param filter search filter
* @return an user
* @exception EUsrGrpException thrown when failed to find user
- * @exception LDAPException thrown when the internal database is not available
+ * @exception LDAPException thrown when the internal database is not
+ * available
*/
public IUser findUsersByCert(String filter) throws
EUsrGrpException, LDAPException;
/**
- * Get user locator which does the mapping between the user and the certificate.
+ * Get user locator which does the mapping between the user and the
+ * certificate.
+ *
* @return CertUserLocator
*/
public ICertUserLocator getCertUserLocator();
diff --git a/pki/base/common/src/com/netscape/certsrv/usrgrp/IUser.java b/pki/base/common/src/com/netscape/certsrv/usrgrp/IUser.java
index 398ccb71..fea2f56a 100644
--- a/pki/base/common/src/com/netscape/certsrv/usrgrp/IUser.java
+++ b/pki/base/common/src/com/netscape/certsrv/usrgrp/IUser.java
@@ -17,136 +17,154 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.usrgrp;
-
import java.security.cert.X509Certificate;
import com.netscape.certsrv.base.IAttrSet;
-
/**
- * This interface defines the basic interfaces for
- * a user identity. (get/set methods for a user entry attributes)
- *
+ * This interface defines the basic interfaces for a user identity. (get/set
+ * methods for a user entry attributes)
+ *
* @version $Revision$, $Date$
*/
public interface IUser extends IAttrSet, IUserConstants {
/**
* Retrieves name.
+ *
* @return user name
*/
public String getName();
/**
* Retrieves user identifier.
+ *
* @return user id
*/
public String getUserID();
/**
* Retrieves user full name.
+ *
* @return user fullname
*/
public String getFullName();
/**
* Retrieves user phonenumber.
+ *
* @return user phonenumber
*/
public String getPhone();
/**
* Retrieves user state
+ *
* @return user state
*/
public String getState();
/**
* Sets user full name.
+ *
* @param name the given full name
*/
public void setFullName(String name);
/**
* Sets user ldap DN.
+ *
* @param userdn the given user DN
*/
public void setUserDN(String userdn);
/**
* Gets user ldap dn
+ *
* @return user DN
*/
public String getUserDN();
/**
* Retrieves user password.
+ *
* @return user password
*/
public String getPassword();
/**
* Sets user password.
+ *
* @param p the given password
*/
public void setPassword(String p);
/**
* Sets user phonenumber
- * @param p user phonenumber
+ *
+ * @param p user phonenumber
*/
public void setPhone(String p);
/**
* Sets user state
+ *
* @param p the given user state
*/
public void setState(String p);
/**
* Sets user type
+ *
* @param userType the given user type
*/
public void setUserType(String userType);
/**
* Gets user email address.
+ *
* @return email address
*/
public String getEmail();
/**
* Sets user email address.
+ *
* @param email the given email address
*/
public void setEmail(String email);
/**
* Gets list of certificates from this user
+ *
* @return list of certificates
*/
public X509Certificate[] getX509Certificates();
/**
* Sets list of certificates in this user
+ *
* @param certs list of certificates
*/
public void setX509Certificates(X509Certificate certs[]);
/**
* Get certificate DN
+ *
* @return certificate DN
*/
public String getCertDN();
/**
* Set certificate DN
+ *
* @param userdn the given DN
*/
public void setCertDN(String userdn);
/**
* Get user type
+ *
* @return user type.
*/
public String getUserType();
diff --git a/pki/base/common/src/com/netscape/certsrv/usrgrp/IUserConstants.java b/pki/base/common/src/com/netscape/certsrv/usrgrp/IUserConstants.java
index f24e9fb4..f66f01c7 100644
--- a/pki/base/common/src/com/netscape/certsrv/usrgrp/IUserConstants.java
+++ b/pki/base/common/src/com/netscape/certsrv/usrgrp/IUserConstants.java
@@ -17,12 +17,9 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.usrgrp;
-
-
-
/**
* This interface defines the attribute names for a user entry
- *
+ *
* @version $Revision$, $Date$
*/
public interface IUserConstants {
diff --git a/pki/base/common/src/com/netscape/certsrv/usrgrp/IUsrGrp.java b/pki/base/common/src/com/netscape/certsrv/usrgrp/IUsrGrp.java
index 17b00c88..af842ff6 100644
--- a/pki/base/common/src/com/netscape/certsrv/usrgrp/IUsrGrp.java
+++ b/pki/base/common/src/com/netscape/certsrv/usrgrp/IUsrGrp.java
@@ -20,50 +20,54 @@ package com.netscape.certsrv.usrgrp;
import netscape.ldap.LDAPException;
/**
- * This interface defines the basic capabilities of
- * a usr/group manager. (get/add/modify/remove users or groups)
- *
+ * This interface defines the basic capabilities of a usr/group manager.
+ * (get/add/modify/remove users or groups)
+ *
* @version $Revision$, $Date$
*/
public interface IUsrGrp extends IIdEvaluator {
/**
* Retrieves usr/grp manager identifier.
+ *
* @return id
*/
public String getId();
/**
* Retrieves the description
+ *
* @return description
*/
public String getDescription();
/**
* Retrieves an identity
+ *
* @param userid the user id for the given user
* @return user interface
*/
public IUser getUser(String userid) throws EUsrGrpException;
/**
- * Adds a user identity to the LDAP server. For example,
- * <code>
+ * Adds a user identity to the LDAP server. For example, <code>
* User user = new User("joe");
* user.setFullName("joe doe");
* user.setPassword("secret");
* usrgrp.addUser(user);
* </code>
+ *
* @param user an user interface
* @exception EUsrGrpException thrown when some of the user attribute values
- * are null
+ * are null
* @exception LDAPException thrown when the LDAP internal database is not
- * available, or the add operation failed
+ * available, or the add operation failed
*/
public void addUser(IUser user) throws EUsrGrpException, LDAPException;
/**
* Removes a user.
+ *
* @param userid the user id for the given user
* @exception EUsrGrpException thrown when failed to remove user
*/
@@ -71,6 +75,7 @@ public interface IUsrGrp extends IIdEvaluator {
/**
* Modifies user.
+ *
* @param user the user interface which contains the modified information
* @exception EUsrGrpException thrown when failed to modify user
*/
@@ -78,6 +83,7 @@ public interface IUsrGrp extends IIdEvaluator {
/**
* Retrieves an identity group
+ *
* @param groupid the given group id.
* @return the group interface
*/
@@ -85,6 +91,7 @@ public interface IUsrGrp extends IIdEvaluator {
/**
* Adds a group
+ *
* @param group the given group
* @exception EUsrGrpException thrown when failed to add the group.
*/
@@ -92,16 +99,18 @@ public interface IUsrGrp extends IIdEvaluator {
/**
* Modifies a group
- * @param group the given group contains the new information for modification.
+ *
+ * @param group the given group contains the new information for
+ * modification.
* @exception EUsrGrpException thrown when failed to modify the group.
*/
public void modifyGroup(IGroup group) throws EUsrGrpException;
/**
* Removes a group
+ *
* @param name the group name
- * @exception EUsrGrpException thrown when failed to remove the given
- * group.
+ * @exception EUsrGrpException thrown when failed to remove the given group.
*/
public void removeGroup(String name) throws EUsrGrpException;
diff --git a/pki/base/common/src/com/netscape/certsrv/usrgrp/UsrGrpResources.java b/pki/base/common/src/com/netscape/certsrv/usrgrp/UsrGrpResources.java
index ed4f28b8..7e04ff9a 100644
--- a/pki/base/common/src/com/netscape/certsrv/usrgrp/UsrGrpResources.java
+++ b/pki/base/common/src/com/netscape/certsrv/usrgrp/UsrGrpResources.java
@@ -20,9 +20,8 @@ package com.netscape.certsrv.usrgrp;
import java.util.ListResourceBundle;
/**
- * A class represents a resource bundle for the
- * user/group manager
- *
+ * A class represents a resource bundle for the user/group manager
+ *
* @deprecated
* @version $Revision$, $Date$
*/
@@ -30,6 +29,7 @@ public class UsrGrpResources extends ListResourceBundle {
/**
* Returns the content of this resource.
+ *
* @return the content of this resource.
*/
public Object[][] getContents() {
@@ -37,8 +37,7 @@ public class UsrGrpResources extends ListResourceBundle {
}
/**
- * Constants. The suffix represents the number of
- * possible parameters.
+ * Constants. The suffix represents the number of possible parameters.
*/
static final Object[][] contents = {};
diff --git a/pki/base/common/src/com/netscape/certsrv/util/HttpInput.java b/pki/base/common/src/com/netscape/certsrv/util/HttpInput.java
index 4f68bf63..2c4581f8 100644
--- a/pki/base/common/src/com/netscape/certsrv/util/HttpInput.java
+++ b/pki/base/common/src/com/netscape/certsrv/util/HttpInput.java
@@ -26,19 +26,16 @@ import javax.servlet.http.HttpServletRequest;
import netscape.ldap.LDAPDN;
-public class HttpInput
-{
- public static int getPortNumberInInt(HttpServletRequest request, String name)
- throws IOException
- {
+public class HttpInput {
+ public static int getPortNumberInInt(HttpServletRequest request, String name)
+ throws IOException {
String val = request.getParameter(name);
int p = Integer.parseInt(val);
return p;
}
-
+
public static String getBoolean(HttpServletRequest request, String name)
- throws IOException
- {
+ throws IOException {
String val = request.getParameter(name);
if (val.equals("true") || val.equals("false")) {
return val;
@@ -47,8 +44,7 @@ public class HttpInput
}
public static String getCheckbox(HttpServletRequest request, String name)
- throws IOException
- {
+ throws IOException {
String val = request.getParameter(name);
if (val == null || val.equals("")) {
return "off";
@@ -59,8 +55,7 @@ public class HttpInput
}
public static String getInteger(HttpServletRequest request, String name)
- throws IOException
- {
+ throws IOException {
String val = request.getParameter(name);
int p = 0;
try {
@@ -75,9 +70,8 @@ public class HttpInput
return val;
}
- public static String getInteger(HttpServletRequest request, String name,
- int min, int max) throws IOException
- {
+ public static String getInteger(HttpServletRequest request, String name,
+ int min, int max) throws IOException {
String val = getInteger(request, name);
int p = Integer.parseInt(val);
if (p < min || p > max) {
@@ -85,41 +79,36 @@ public class HttpInput
}
return val;
}
-
+
public static String getPortNumber(HttpServletRequest request, String name)
- throws IOException
- {
- String v = getInteger(request, name);
+ throws IOException {
+ String v = getInteger(request, name);
return v;
}
-
+
public static String getString(HttpServletRequest request, String name)
- throws IOException
- {
+ throws IOException {
String val = request.getParameter(name);
return val;
}
public static String getString(HttpServletRequest request, String name,
- int minlen, int maxlen) throws IOException
- {
+ int minlen, int maxlen) throws IOException {
String val = request.getParameter(name);
if (val.length() < minlen || val.length() > maxlen) {
- throw new IOException("String length of '" + val +
- "' is out of range");
+ throw new IOException("String length of '" + val +
+ "' is out of range");
}
return val;
}
-
+
public static String getLdapDatabase(HttpServletRequest request, String name)
- throws IOException
- {
+ throws IOException {
return getString(request, name);
}
-
+
public static String getURL(HttpServletRequest request, String name)
- throws IOException
- {
+ throws IOException {
String v = getString(request, name);
try {
URL u = new URL(v);
@@ -128,163 +117,144 @@ public class HttpInput
}
return v;
}
-
+
public static String getUID(HttpServletRequest request, String name)
- throws IOException
- {
+ throws IOException {
return getString(request, name);
}
-
+
public static String getPassword(HttpServletRequest request, String name)
- throws IOException
- {
+ throws IOException {
return getString(request, name);
}
public static String getKeyType(HttpServletRequest request, String name)
- throws IOException
- {
+ throws IOException {
String v = getString(request, name);
if (v.equals("rsa")) {
- return v;
+ return v;
}
if (v.equals("ecc")) {
- return v;
+ return v;
}
throw new IOException("Invalid key type '" + v + "' not supported.");
}
-
+
public static String getKeySize(HttpServletRequest request, String name)
- throws IOException
- {
+ throws IOException {
String i = getInteger(request, name);
if (i.equals("256") || i.equals("512") || i.equals("1024") ||
- i.equals("2048") || i.equals("4096")) {
- return i;
+ i.equals("2048") || i.equals("4096")) {
+ return i;
}
throw new IOException("Invalid key length '" + i + "'. Currently supported key lengths are 256, 512, 1024, 2048, 4096.");
}
public static String getKeySize(HttpServletRequest request, String name, String keyType)
- throws IOException
- {
+ throws IOException {
String i = getInteger(request, name);
if (keyType.equals("rsa")) {
- if (i.equals("256") || i.equals("512") || i.equals("1024") ||
- i.equals("2048") || i.equals("4096")) {
- return i;
- } else {
- throw new IOException("Invalid key length '" + i + "'. Currently supported RSA key lengths are 256, 512, 1024, 2048, 4096.");
- }
+ if (i.equals("256") || i.equals("512") || i.equals("1024") ||
+ i.equals("2048") || i.equals("4096")) {
+ return i;
+ } else {
+ throw new IOException("Invalid key length '" + i + "'. Currently supported RSA key lengths are 256, 512, 1024, 2048, 4096.");
+ }
}
if (keyType.equals("ecc")) {
- int p = 0;
- try {
- p = Integer.parseInt(i);
- } catch (NumberFormatException e) {
- throw new IOException("Input '" + i + "' is not an integer");
- }
- if ((p >= 112) && (p <= 571))
- return i;
- else {
- throw new IOException("Invalid key length '" + i + "'. Please consult your security officer for a proper length, or take the default value. Here are examples of some commonly used key lengths: 256, 384, 521.");
- }
-/*
-
- if (i.equals("256") || i.equals("384") || i.equals("521")) {
- return i;
- } else {
- throw new IOException("Invalid key length '" + i + "'. Currently supported ECC key lengths are 256, 384, 521.");
- }
-*/
+ int p = 0;
+ try {
+ p = Integer.parseInt(i);
+ } catch (NumberFormatException e) {
+ throw new IOException("Input '" + i + "' is not an integer");
+ }
+ if ((p >= 112) && (p <= 571))
+ return i;
+ else {
+ throw new IOException("Invalid key length '" + i + "'. Please consult your security officer for a proper length, or take the default value. Here are examples of some commonly used key lengths: 256, 384, 521.");
+ }
+ /*
+ *
+ * if (i.equals("256") || i.equals("384") || i.equals("521")) {
+ * return i; } else { throw new IOException("Invalid key length '" +
+ * i + "'. Currently supported ECC key lengths are 256, 384, 521.");
+ * }
+ */
}
throw new IOException("Invalid key type '" + keyType + "'");
}
-
+
public static String getDN(HttpServletRequest request, String name)
- throws IOException
- {
+ throws IOException {
String v = getString(request, name);
String dn[] = LDAPDN.explodeDN(v, true);
if (dn == null || dn.length <= 0) {
- throw new IOException("Invalid DN " + v + " in " + name);
+ throw new IOException("Invalid DN " + v + " in " + name);
}
return v;
}
-
+
public static String getID(HttpServletRequest request, String name)
- throws IOException
- {
+ throws IOException {
return getString(request, name);
}
-
+
public static String getName(HttpServletRequest request, String name)
- throws IOException
- {
+ throws IOException {
return getString(request, name);
}
-
+
public static String getCertRequest(HttpServletRequest request, String name)
- throws IOException
- {
+ throws IOException {
return getString(request, name);
}
-
+
public static String getCertChain(HttpServletRequest request, String name)
- throws IOException
- {
+ throws IOException {
return getString(request, name);
}
-
+
public static String getCert(HttpServletRequest request, String name)
- throws IOException
- {
+ throws IOException {
return getString(request, name);
}
public static String getNickname(HttpServletRequest request, String name)
- throws IOException
- {
+ throws IOException {
return getString(request, name);
}
-
+
public static String getHostname(HttpServletRequest request, String name)
- throws IOException
- {
+ throws IOException {
return getString(request, name);
}
-
+
public static String getTokenName(HttpServletRequest request, String name)
- throws IOException
- {
+ throws IOException {
return getString(request, name);
}
public static String getReplicationAgreementName(HttpServletRequest request, String name)
- throws IOException
- {
+ throws IOException {
return getString(request, name);
}
-
+
public static String getEmail(HttpServletRequest request, String name)
- throws IOException
- {
+ throws IOException {
String v = getString(request, name);
if (v.indexOf('@') == -1) {
- throw new IOException("Invalid email " + v);
+ throw new IOException("Invalid email " + v);
}
return v;
}
-
+
public static String getDomainName(HttpServletRequest request, String name)
- throws IOException
- {
+ throws IOException {
return getString(request, name);
}
-
- public static String getSecurityDomainName(HttpServletRequest request, String name)
- throws IOException
- {
+
+ public static String getSecurityDomainName(HttpServletRequest request, String name)
+ throws IOException {
String v = getName(request, name);
Pattern p = Pattern.compile("[A-Za-z0-9]+[A-Za-z0-9 -]*");
Matcher m = p.matcher(v);
diff --git a/pki/base/common/src/com/netscape/certsrv/util/IStatsSubsystem.java b/pki/base/common/src/com/netscape/certsrv/util/IStatsSubsystem.java
index c9881236..8846a99a 100644
--- a/pki/base/common/src/com/netscape/certsrv/util/IStatsSubsystem.java
+++ b/pki/base/common/src/com/netscape/certsrv/util/IStatsSubsystem.java
@@ -17,26 +17,21 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.util;
-
import java.util.Date;
import com.netscape.certsrv.base.ISubsystem;
-
/**
- * A class represents a internal subsystem. This subsystem
- * can be loaded into cert server kernel to perform
- * statistics collection.
+ * A class represents a internal subsystem. This subsystem can be loaded into
+ * cert server kernel to perform statistics collection.
* <P>
*
* @author thomask
* @version $Revision$, $Date$
*/
-public interface IStatsSubsystem extends ISubsystem
-{
+public interface IStatsSubsystem extends ISubsystem {
/**
- * Retrieves the start time since startup or
- * clearing of statistics.
+ * Retrieves the start time since startup or clearing of statistics.
*/
public Date getStartTime();
diff --git a/pki/base/common/src/com/netscape/certsrv/util/StatsEvent.java b/pki/base/common/src/com/netscape/certsrv/util/StatsEvent.java
index 7c510b88..9e004b62 100644
--- a/pki/base/common/src/com/netscape/certsrv/util/StatsEvent.java
+++ b/pki/base/common/src/com/netscape/certsrv/util/StatsEvent.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.util;
-
import java.util.Enumeration;
import java.util.Vector;
@@ -28,167 +27,149 @@ import java.util.Vector;
* @author thomask
* @version $Revision$, $Date$
*/
-public class StatsEvent
-{
- private String mName = null;
- private long mMin = -1;
- private long mMax = -1;
- private long mTimeTaken = 0;
- private long mTimeTakenSqSum = 0;
- private long mNoOfOperations = 0;
- private Vector mSubEvents = new Vector();
- private StatsEvent mParent = null;
-
- public StatsEvent(StatsEvent parent)
- {
- mParent = parent;
- }
-
- public void setName(String name)
- {
- mName = name;
- }
-
- /**
- * Retrieves Transaction name.
- */
- public String getName()
- {
- return mName;
- }
-
- public void addSubEvent(StatsEvent st)
- {
- mSubEvents.addElement(st);
- }
-
- /**
- * Retrieves a list of sub transaction names.
- */
- public Enumeration getSubEventNames()
- {
- Vector names = new Vector();
- Enumeration e = mSubEvents.elements();
- while (e.hasMoreElements()) {
- StatsEvent st = (StatsEvent)e.nextElement();
- names.addElement(st.getName());
- }
- return names.elements();
- }
-
- /**
- * Retrieves a sub transaction.
- */
- public StatsEvent getSubEvent(String name)
- {
- Enumeration e = mSubEvents.elements();
- while (e.hasMoreElements()) {
- StatsEvent st = (StatsEvent)e.nextElement();
- if (st.getName().equals(name)) {
- return st;
- }
- }
- return null;
- }
-
- public void resetCounters()
- {
- mMin = -1;
- mMax = -1;
- mNoOfOperations = 0;
- mTimeTaken = 0;
- mTimeTakenSqSum = 0;
- Enumeration e = getSubEventNames();
- while (e.hasMoreElements()) {
- String n = (String)e.nextElement();
- StatsEvent c = getSubEvent(n);
- c.resetCounters();
- }
- }
-
- public long getMax()
- {
- return mMax;
- }
-
- public long getMin()
- {
- return mMin;
- }
-
- public void incNoOfOperations(long c)
- {
- mNoOfOperations += c;
- }
-
- public long getTimeTakenSqSum()
- {
- return mTimeTakenSqSum;
- }
-
- public long getPercentage()
- {
- if (mParent == null || mParent.getTimeTaken() == 0) {
- return 100;
- } else {
- return (mTimeTaken * 100 / mParent.getTimeTaken());
- }
- }
-
- public long getStdDev()
- {
- if (getNoOfOperations() == 0) {
- return 0;
- } else {
- long a = getTimeTakenSqSum();
- long b = (-2 * getAvg() *getTimeTaken());
- long c = getAvg() * getAvg() * getNoOfOperations();
- return (long)Math.sqrt((a + b + c)/getNoOfOperations());
- }
- }
-
- public long getAvg()
- {
- if (mNoOfOperations == 0) {
- return -1;
- } else {
- return mTimeTaken/mNoOfOperations;
- }
- }
-
- /**
- * Retrieves number of operations performed.
- */
- public long getNoOfOperations()
- {
- return mNoOfOperations;
- }
-
- public void incTimeTaken(long c)
- {
- if (mMin == -1) {
- mMin = c;
- } else {
- if (c < mMin) {
- mMin = c;
- }
- }
- if (mMax == -1) {
- mMax = c;
- } else {
- if (c > mMax) {
- mMax = c;
- }
- }
- mTimeTaken += c;
- mTimeTakenSqSum += (c * c);
- }
-
- /**
- * Retrieves total time token in msec.
- */
- public long getTimeTaken()
- {
- return mTimeTaken;
- }
+public class StatsEvent {
+ private String mName = null;
+ private long mMin = -1;
+ private long mMax = -1;
+ private long mTimeTaken = 0;
+ private long mTimeTakenSqSum = 0;
+ private long mNoOfOperations = 0;
+ private Vector mSubEvents = new Vector();
+ private StatsEvent mParent = null;
+
+ public StatsEvent(StatsEvent parent) {
+ mParent = parent;
+ }
+
+ public void setName(String name) {
+ mName = name;
+ }
+
+ /**
+ * Retrieves Transaction name.
+ */
+ public String getName() {
+ return mName;
+ }
+
+ public void addSubEvent(StatsEvent st) {
+ mSubEvents.addElement(st);
+ }
+
+ /**
+ * Retrieves a list of sub transaction names.
+ */
+ public Enumeration getSubEventNames() {
+ Vector names = new Vector();
+ Enumeration e = mSubEvents.elements();
+ while (e.hasMoreElements()) {
+ StatsEvent st = (StatsEvent) e.nextElement();
+ names.addElement(st.getName());
+ }
+ return names.elements();
+ }
+
+ /**
+ * Retrieves a sub transaction.
+ */
+ public StatsEvent getSubEvent(String name) {
+ Enumeration e = mSubEvents.elements();
+ while (e.hasMoreElements()) {
+ StatsEvent st = (StatsEvent) e.nextElement();
+ if (st.getName().equals(name)) {
+ return st;
+ }
+ }
+ return null;
+ }
+
+ public void resetCounters() {
+ mMin = -1;
+ mMax = -1;
+ mNoOfOperations = 0;
+ mTimeTaken = 0;
+ mTimeTakenSqSum = 0;
+ Enumeration e = getSubEventNames();
+ while (e.hasMoreElements()) {
+ String n = (String) e.nextElement();
+ StatsEvent c = getSubEvent(n);
+ c.resetCounters();
+ }
+ }
+
+ public long getMax() {
+ return mMax;
+ }
+
+ public long getMin() {
+ return mMin;
+ }
+
+ public void incNoOfOperations(long c) {
+ mNoOfOperations += c;
+ }
+
+ public long getTimeTakenSqSum() {
+ return mTimeTakenSqSum;
+ }
+
+ public long getPercentage() {
+ if (mParent == null || mParent.getTimeTaken() == 0) {
+ return 100;
+ } else {
+ return (mTimeTaken * 100 / mParent.getTimeTaken());
+ }
+ }
+
+ public long getStdDev() {
+ if (getNoOfOperations() == 0) {
+ return 0;
+ } else {
+ long a = getTimeTakenSqSum();
+ long b = (-2 * getAvg() * getTimeTaken());
+ long c = getAvg() * getAvg() * getNoOfOperations();
+ return (long) Math.sqrt((a + b + c) / getNoOfOperations());
+ }
+ }
+
+ public long getAvg() {
+ if (mNoOfOperations == 0) {
+ return -1;
+ } else {
+ return mTimeTaken / mNoOfOperations;
+ }
+ }
+
+ /**
+ * Retrieves number of operations performed.
+ */
+ public long getNoOfOperations() {
+ return mNoOfOperations;
+ }
+
+ public void incTimeTaken(long c) {
+ if (mMin == -1) {
+ mMin = c;
+ } else {
+ if (c < mMin) {
+ mMin = c;
+ }
+ }
+ if (mMax == -1) {
+ mMax = c;
+ } else {
+ if (c > mMax) {
+ mMax = c;
+ }
+ }
+ mTimeTaken += c;
+ mTimeTakenSqSum += (c * c);
+ }
+
+ /**
+ * Retrieves total time token in msec.
+ */
+ public long getTimeTaken() {
+ return mTimeTaken;
+ }
}
diff --git a/pki/base/common/src/com/netscape/cms/authentication/AVAPattern.java b/pki/base/common/src/com/netscape/cms/authentication/AVAPattern.java
index 4cfe9a45..f53e65ea 100644
--- a/pki/base/common/src/com/netscape/cms/authentication/AVAPattern.java
+++ b/pki/base/common/src/com/netscape/cms/authentication/AVAPattern.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.authentication;
-
import java.io.IOException;
import java.io.PushbackReader;
import java.io.StringReader;
@@ -36,24 +35,27 @@ import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.authentication.EAuthException;
import com.netscape.certsrv.authentication.ECompSyntaxErr;
-
/**
- * class for parsing a DN pattern used to construct a certificate
- * subject name from ldap attributes and dn.<p>
+ * class for parsing a DN pattern used to construct a certificate subject name
+ * from ldap attributes and dn.
+ * <p>
+ *
+ * dnpattern is a string representing a subject name pattern to formulate from
+ * the directory attributes and entry dn. If empty or not set, the ldap entry DN
+ * will be used as the certificate subject name.
+ * <p>
*
- * dnpattern is a string representing a subject name pattern to formulate from
- * the directory attributes and entry dn. If empty or not set, the
- * ldap entry DN will be used as the certificate subject name. <p>
+ * The syntax is
*
- * The syntax is
* <pre>
- * dnPattern := rdnPattern *[ "," rdnPattern ]
- * rdnPattern := avaPattern *[ "+" avaPattern ]
+ * dnPattern := rdnPattern *[ "," rdnPattern ]
+ * rdnPattern := avaPattern *[ "+" avaPattern ]
* avaPattern := name "=" value |
- * name "=" "$attr" "." attrName [ "." attrNumber ] |
- * name "=" "$dn" "." attrName [ "." attrNumber ] |
- * "$dn" "." "$rdn" "." number
+ * name "=" "$attr" "." attrName [ "." attrNumber ] |
+ * name "=" "$dn" "." attrName [ "." attrNumber ] |
+ * "$dn" "." "$rdn" "." number
* </pre>
+ *
* <pre>
* Example1: <i>E=$attr.mail.1, CN=$attr.cn, OU=$dn.ou.2, O=$dn.o, C=US </i>
* Ldap entry: dn: UID=jjames, OU=IS, OU=people, O=acme.org
@@ -80,11 +82,12 @@ import com.netscape.certsrv.authentication.ECompSyntaxErr;
* E = the first 'mail' ldap attribute value in user's entry. <br>
* CN = the (first) 'cn' ldap attribute value in the user's entry. <br>
* OU = the second 'ou' value in the user's entry DN. note multiple AVAs
- * in a RDN in this example. <br>
+ * in a RDN in this example. <br>
* O = the (first) 'o' value in the user's entry DN. <br>
* C = the string "US"
* <p>
* </pre>
+ *
* <pre>
* Example3: <i>CN=$attr.cn, $rdn.2, O=$dn.o, C=US</i>
* Ldap entry: dn: UID=jjames, OU=IS+OU=people, O=acme.org
@@ -109,15 +112,16 @@ import com.netscape.certsrv.authentication.ECompSyntaxErr;
* <p>
* CN = the (first) 'cn' ldap attribute value in the user's entry. <br>
* OU = the second 'ou' value in the user's entry DN followed by the
- * first 'ou' value in the user's entry. note multiple AVAs
- * in a RDN in this example. <br>
+ * first 'ou' value in the user's entry. note multiple AVAs
+ * in a RDN in this example. <br>
* O = the (first) 'o' value in the user's entry DN. <br>
* C = the string "US"
* <p>
* </pre>
- * If an attribute or subject DN component does not exist the attribute
- * is skipped.
- *
+ *
+ * If an attribute or subject DN component does not exist the attribute is
+ * skipped.
+ *
* @version $Revision$, $Date$
*/
class AVAPattern {
@@ -130,8 +134,8 @@ class AVAPattern {
private static final char[] endChars = new char[] { '+', ',' };
- private static final LdapV3DNStrConverter mLdapDNStrConverter =
- new LdapV3DNStrConverter();
+ private static final LdapV3DNStrConverter mLdapDNStrConverter =
+ new LdapV3DNStrConverter();
/* ldap attributes needed by this AVA (to retrieve from ldap) */
protected String[] mLdapAttrs = null;
@@ -140,7 +144,7 @@ class AVAPattern {
protected String mType = null;
/* the attribute in the AVA pair */
- protected String mAttr = null;
+ protected String mAttr = null;
/* value - could be name of an ldap attribute or entry dn attribute. */
protected String mValue = null;
@@ -151,47 +155,47 @@ class AVAPattern {
protected String mTestDN = null;
public AVAPattern(String component)
- throws EAuthException {
- if (component == null || component.length() == 0)
+ throws EAuthException {
+ if (component == null || component.length() == 0)
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX", component));
parse(new PushbackReader(new StringReader(component)));
}
- public AVAPattern(PushbackReader in)
- throws EAuthException {
+ public AVAPattern(PushbackReader in)
+ throws EAuthException {
parse(in);
}
private void parse(PushbackReader in)
- throws EAuthException {
+ throws EAuthException {
int c;
// mark ava beginning.
// skip spaces
- //System.out.println("============ AVAPattern Begin ===========");
- //System.out.println("skip spaces");
+ // System.out.println("============ AVAPattern Begin ===========");
+ // System.out.println("skip spaces");
try {
- while ((c = in.read()) == ' ' || c == '\t') {//System.out.println("spaces read "+(char)c);
+ while ((c = in.read()) == ' ' || c == '\t') {// System.out.println("spaces read "+(char)c);
;
}
} catch (IOException e) {
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX", "All blank"));
}
- if (c == -1)
+ if (c == -1)
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX", "All blank"));
- // $rdn "." number syntax.
+ // $rdn "." number syntax.
if (c == '$') {
- //System.out.println("$rdn syntax");
+ // System.out.println("$rdn syntax");
mType = TYPE_RDN;
try {
- if (in.read() != 'r' ||
- in.read() != 'd' ||
- in.read() != 'n' ||
- in.read() != '.')
+ if (in.read() != 'r' ||
+ in.read() != 'd' ||
+ in.read() != 'n' ||
+ in.read() != '.')
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX", "Invalid $ syntax, expecting $rdn"));
} catch (IOException e) {
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX", "Invalid $ syntax, expecting $rdn"));
@@ -201,7 +205,7 @@ class AVAPattern {
try {
while ((c = in.read()) != ',' && c != -1 && c != '+') {
- //System.out.println("rdnNumber read "+(char)c);
+ // System.out.println("rdnNumber read "+(char)c);
rdnNumberBuf.append((char) c);
}
if (c != -1) // either ',' or '+'
@@ -212,7 +216,7 @@ class AVAPattern {
String rdnNumber = rdnNumberBuf.toString().trim();
- if (rdnNumber.length() == 0)
+ if (rdnNumber.length() == 0)
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX", "$rdn number not set in ava pattern"));
try {
mElement = Integer.parseInt(rdnNumber) - 1;
@@ -222,20 +226,20 @@ class AVAPattern {
return;
}
- // name "=" ... syntax.
+ // name "=" ... syntax.
- // read name
- //System.out.println("reading name");
+ // read name
+ // System.out.println("reading name");
- StringBuffer attrBuf = new StringBuffer();
+ StringBuffer attrBuf = new StringBuffer();
try {
while (c != '=' && c != -1 && c != ',' && c != '+') {
attrBuf.append((char) c);
c = in.read();
- //System.out.println("name read "+(char)c);
- }
- if (c == ',' || c == '+')
+ // System.out.println("name read "+(char)c);
+ }
+ if (c == ',' || c == '+')
in.unread(c);
} catch (IOException e) {
throw new EAuthException(CMS.getUserMessage("CMS_AUTHENTICATION_INTERNAL_ERROR", e.toString()));
@@ -243,73 +247,73 @@ class AVAPattern {
if (c != '=')
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX", "Missing \"=\" in ava pattern"));
- // read value
- //System.out.println("reading value");
+ // read value
+ // System.out.println("reading value");
- // skip spaces
- //System.out.println("skip spaces for value");
+ // skip spaces
+ // System.out.println("skip spaces for value");
try {
- while ((c = in.read()) == ' ' || c == '\t') {//System.out.println("spaces2 read "+(char)c);
+ while ((c = in.read()) == ' ' || c == '\t') {// System.out.println("spaces2 read "+(char)c);
;
}
} catch (IOException e) {
throw new EAuthException(CMS.getUserMessage("CMS_AUTHENTICATION_INTERNAL_ERROR", e.toString()));
}
- if (c == -1)
+ if (c == -1)
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX", "no value after = in ava pattern"));
if (c == '$') {
- // check for $dn or $attr
+ // check for $dn or $attr
try {
c = in.read();
- //System.out.println("check $dn or $attr read "+(char)c);
+ // System.out.println("check $dn or $attr read "+(char)c);
} catch (IOException e) {
throw new EAuthException(CMS.getUserMessage("CMS_AUTHENTICATION_INTERNAL_ERROR", e.toString()));
}
- if (c == -1)
- throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX",
+ if (c == -1)
+ throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX",
"expecting $dn or $attr in ava pattern"));
if (c == 'a') {
try {
- if (in.read() != 't' ||
- in.read() != 't' ||
- in.read() != 'r' ||
- in.read() != '.')
- throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX",
+ if (in.read() != 't' ||
+ in.read() != 't' ||
+ in.read() != 'r' ||
+ in.read() != '.')
+ throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX",
"expecting $attr in ava pattern"));
} catch (IOException e) {
throw new EAuthException(CMS.getUserMessage("CMS_AUTHENTICATION_INTERNAL_ERROR", e.toString()));
}
mType = TYPE_ATTR;
- //System.out.println("---- mtype $attr");
+ // System.out.println("---- mtype $attr");
} else if (c == 'd') {
try {
- if (in.read() != 'n' ||
- in.read() != '.')
+ if (in.read() != 'n' ||
+ in.read() != '.')
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX",
"expecting $dn in ava pattern"));
} catch (IOException e) {
throw new EAuthException(CMS.getUserMessage("CMS_AUTHENTICATION_INTERNAL_ERROR", e.toString()));
}
mType = TYPE_DN;
- //System.out.println("----- mtype $dn");
+ // System.out.println("----- mtype $dn");
} else {
- throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX",
- "unknown keyword. expecting $dn or $attr."));
+ throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX",
+ "unknown keyword. expecting $dn or $attr."));
}
- // get attr name of dn pattern from above.
+ // get attr name of dn pattern from above.
String attrName = attrBuf.toString().trim();
- //System.out.println("----- attrName "+attrName);
- if (attrName.length() == 0)
+ // System.out.println("----- attrName "+attrName);
+ if (attrName.length() == 0)
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX", "attribute name expected"));
- try {
- ObjectIdentifier attrOid =
- mLdapDNStrConverter.parseAVAKeyword(attrName);
+ try {
+ ObjectIdentifier attrOid =
+ mLdapDNStrConverter.parseAVAKeyword(attrName);
- mAttr = mLdapDNStrConverter.encodeOID(attrOid);
- //System.out.println("----- mAttr "+mAttr);
+ mAttr = mLdapDNStrConverter.encodeOID(attrOid);
+ // System.out.println("----- mAttr "+mAttr);
} catch (IOException e) {
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX", e.getMessage()));
}
@@ -318,40 +322,40 @@ class AVAPattern {
StringBuffer valueBuf = new StringBuffer();
try {
- while ((c = in.read()) != ',' &&
- c != -1 && c != '.' && c != '+') {
- //System.out.println("mValue read "+(char)c);
+ while ((c = in.read()) != ',' &&
+ c != -1 && c != '.' && c != '+') {
+ // System.out.println("mValue read "+(char)c);
valueBuf.append((char) c);
}
if (c == '+' || c == ',') // either ',' or '+'
- in.unread(c); // pushback last , or +
+ in.unread(c); // pushback last , or +
} catch (IOException e) {
throw new EAuthException(CMS.getUserMessage("CMS_AUTHENTICATION_INTERNAL_ERROR", e.toString()));
}
mValue = valueBuf.toString().trim();
- if (mValue.length() == 0)
+ if (mValue.length() == 0)
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX",
"$dn or $attr attribute name expected"));
- //System.out.println("----- mValue "+mValue);
+ // System.out.println("----- mValue "+mValue);
- // get nth dn or attribute from ldap search.
+ // get nth dn or attribute from ldap search.
if (c == '.') {
StringBuffer attrNumberBuf = new StringBuffer();
try {
while ((c = in.read()) != ',' && c != -1 && c != '+') {
- //System.out.println("mElement read "+(char)c);
+ // System.out.println("mElement read "+(char)c);
attrNumberBuf.append((char) c);
}
if (c != -1) // either ',' or '+'
- in.unread(c); // pushback last , or +
+ in.unread(c); // pushback last , or +
} catch (IOException e) {
throw new EAuthException(CMS.getUserMessage("CMS_AUTHENTICATION_INTERNAL_ERROR", e.toString()));
}
String attrNumber = attrNumberBuf.toString().trim();
- if (attrNumber.length() == 0)
+ if (attrNumber.length() == 0)
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX",
"nth element $dn or $attr expected"));
try {
@@ -361,18 +365,18 @@ class AVAPattern {
"Invalid format in nth element $dn or $attr"));
}
}
- //System.out.println("----- mElement "+mElement);
+ // System.out.println("----- mElement "+mElement);
} else {
// value is constant. treat as regular ava.
mType = TYPE_CONSTANT;
- //System.out.println("----- mType constant");
- // parse ava value.
+ // System.out.println("----- mType constant");
+ // parse ava value.
StringBuffer valueBuf = new StringBuffer();
valueBuf.append((char) c);
try {
while ((c = in.read()) != ',' &&
- c != -1) {
+ c != -1) {
valueBuf.append((char) c);
}
if (c == '+' || c == ',') { // either ',' or '+'
@@ -381,11 +385,11 @@ class AVAPattern {
} catch (IOException e) {
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX", e.getMessage()));
}
- try {
- AVA ava = mLdapDNStrConverter.parseAVA(attrBuf + "=" + valueBuf);
+ try {
+ AVA ava = mLdapDNStrConverter.parseAVA(attrBuf + "=" + valueBuf);
mValue = ava.toLdapDNString();
- //System.out.println("----- mValue "+mValue);
+ // System.out.println("----- mValue "+mValue);
} catch (IOException e) {
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX", e.getMessage()));
}
@@ -393,19 +397,19 @@ class AVAPattern {
}
public String formAVA(LDAPEntry entry)
- throws EAuthException {
- if (mType == TYPE_CONSTANT)
+ throws EAuthException {
+ if (mType == TYPE_CONSTANT)
return mValue;
if (mType == TYPE_RDN) {
String dn = entry.getDN();
- if (mTestDN != null)
+ if (mTestDN != null)
dn = mTestDN;
- //System.out.println("AVAPattern Using dn "+mTestDN);
+ // System.out.println("AVAPattern Using dn "+mTestDN);
String[] rdns = LDAPDN.explodeDN(dn, false);
- if (mElement >= rdns.length)
+ if (mElement >= rdns.length)
return null;
return rdns[mElement];
}
@@ -413,9 +417,9 @@ class AVAPattern {
if (mType == TYPE_DN) {
String dn = entry.getDN();
- if (mTestDN != null)
+ if (mTestDN != null)
dn = mTestDN;
- //System.out.println("AVAPattern Using dn "+mTestDN);
+ // System.out.println("AVAPattern Using dn "+mTestDN);
String[] rdns = LDAPDN.explodeDN(dn, false);
String value = null;
int nFound = -1;
@@ -426,14 +430,14 @@ class AVAPattern {
for (int j = 0; j < avas.length; j++) {
String[] exploded = explodeAVA(avas[j]);
- if (exploded[0].equalsIgnoreCase(mValue) &&
- ++nFound == mElement) {
+ if (exploded[0].equalsIgnoreCase(mValue) &&
+ ++nFound == mElement) {
value = exploded[1];
break;
}
}
}
- if (value == null)
+ if (value == null)
return null;
return mAttr + "=" + value;
}
@@ -441,11 +445,11 @@ class AVAPattern {
if (mType == TYPE_ATTR) {
LDAPAttribute ldapAttr = entry.getAttribute(mValue);
- if (ldapAttr == null)
+ if (ldapAttr == null)
return null;
String value = null;
@SuppressWarnings("unchecked")
- Enumeration<String> ldapValues = ldapAttr.getStringValues();
+ Enumeration<String> ldapValues = ldapAttr.getStringValues();
for (int i = 0; ldapValues.hasMoreElements(); i++) {
String val = (String) ldapValues.nextElement();
@@ -455,7 +459,7 @@ class AVAPattern {
break;
}
}
- if (value == null)
+ if (value == null)
return null;
String v = escapeLdapString(value);
@@ -486,16 +490,16 @@ class AVAPattern {
int k = i + 1;
if (i == len - 1 ||
- (c[k] == ',' || c[k] == '=' || c[k] == '+' || c[k] == '<' ||
- c[k] == '>' || c[k] == '#' || c[k] == ';')) {
+ (c[k] == ',' || c[k] == '=' || c[k] == '+' || c[k] == '<' ||
+ c[k] == '>' || c[k] == '#' || c[k] == ';')) {
newc[j++] = '\\';
newc[j++] = c[i];
}
} // escape QUOTATION
else if (c[i] == '"') {
- if ((i == 0 && c[len - 1] != '"') ||
- (i == len - 1 && c[0] != '"') ||
- (i > 0 && i < len - 1)) {
+ if ((i == 0 && c[len - 1] != '"') ||
+ (i == len - 1 && c[0] != '"') ||
+ (i > 0 && i < len - 1)) {
newc[j++] = '\\';
newc[j++] = c[i];
}
@@ -513,20 +517,19 @@ class AVAPattern {
}
/**
- * Explode RDN into AVAs.
- * Does not handle escaped '+'
- * Java ldap library does not yet support multiple avas per rdn.
- * If RDN is malformed returns empty array.
+ * Explode RDN into AVAs. Does not handle escaped '+' Java ldap library does
+ * not yet support multiple avas per rdn. If RDN is malformed returns empty
+ * array.
*/
public static String[] explodeRDN(String rdn) {
int plus = rdn.indexOf('+');
- if (plus == -1)
+ if (plus == -1)
return new String[] { rdn };
Vector<String> avas = new Vector<String>();
StringTokenizer token = new StringTokenizer(rdn, "+");
- while (token.hasMoreTokens())
+ while (token.hasMoreTokens())
avas.addElement(token.nextToken());
String[] theAvas = new String[avas.size()];
@@ -535,17 +538,15 @@ class AVAPattern {
}
/**
- * Explode AVA into name and value.
- * Does not handle escaped '='
- * If AVA is malformed empty array is returned.
+ * Explode AVA into name and value. Does not handle escaped '=' If AVA is
+ * malformed empty array is returned.
*/
public static String[] explodeAVA(String ava) {
int equals = ava.indexOf('=');
- if (equals == -1)
+ if (equals == -1)
return null;
return new String[] {
- ava.substring(0, equals).trim(), ava.substring(equals + 1).trim()};
+ ava.substring(0, equals).trim(), ava.substring(equals + 1).trim() };
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/authentication/AgentCertAuthentication.java b/pki/base/common/src/com/netscape/cms/authentication/AgentCertAuthentication.java
index 270d1fa2..d248c476 100644
--- a/pki/base/common/src/com/netscape/cms/authentication/AgentCertAuthentication.java
+++ b/pki/base/common/src/com/netscape/cms/authentication/AgentCertAuthentication.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.authentication;
-
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
@@ -48,16 +47,14 @@ import com.netscape.certsrv.usrgrp.ICertUserLocator;
import com.netscape.certsrv.usrgrp.IUGSubsystem;
import com.netscape.certsrv.usrgrp.IUser;
-
/**
- * Certificate server agent authentication.
- * Maps a SSL client authenticate certificate to a user (agent) entry in the
- * internal database.
+ * Certificate server agent authentication. Maps a SSL client authenticate
+ * certificate to a user (agent) entry in the internal database.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
-public class AgentCertAuthentication implements IAuthManager,
+public class AgentCertAuthentication implements IAuthManager,
IProfileAuthenticator {
/* result auth token attributes */
@@ -91,14 +88,15 @@ public class AgentCertAuthentication implements IAuthManager,
/**
* initializes the CertUserDBAuthentication auth manager
* <p>
- * called by AuthSubsystem init() method, when initializing
- * all available authentication managers.
+ * called by AuthSubsystem init() method, when initializing all available
+ * authentication managers.
+ *
* @param name The name of this authentication manager instance.
* @param implName The name of the authentication manager plugin.
* @param config The configuration store for this authentication manager.
*/
public void init(String name, String implName, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mName = name;
mImplName = implName;
mConfig = config;
@@ -106,7 +104,7 @@ public class AgentCertAuthentication implements IAuthManager,
mUGSub = (IUGSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_UG);
mCULocator = mUGSub.getCertUserLocator();
}
-
+
/**
* Gets the name of this authentication manager.
*/
@@ -120,7 +118,7 @@ public class AgentCertAuthentication implements IAuthManager,
public String getImplName() {
return mImplName;
}
-
+
public boolean isSSLClientRequired() {
return true;
}
@@ -128,29 +126,30 @@ public class AgentCertAuthentication implements IAuthManager,
/**
* authenticates user(agent) by certificate
* <p>
- * called by other subsystems or their servlets to authenticate
- * users (agents)
- * @param authCred - authentication credential that contains
- * an usrgrp.Certificates of the user (agent)
+ * called by other subsystems or their servlets to authenticate users
+ * (agents)
+ *
+ * @param authCred - authentication credential that contains an
+ * usrgrp.Certificates of the user (agent)
* @return the authentication token that contains the following
- *
+ *
* @exception EMissingCredential If a required credential for this
- * authentication manager is missing.
+ * authentication manager is missing.
* @exception EInvalidCredentials If credentials cannot be authenticated.
* @exception EBaseException If an internal error occurred.
* @see com.netscape.certsrv.authentication.AuthToken
* @see com.netscape.certsrv.usrgrp.Certificates
*/
public IAuthToken authenticate(IAuthCredentials authCred)
- throws EMissingCredential, EInvalidCredentials, EBaseException {
-
+ throws EMissingCredential, EInvalidCredentials, EBaseException {
+
CMS.debug("AgentCertAuthentication: start");
- CMS.debug("authenticator instance name is "+getName());
+ CMS.debug("authenticator instance name is " + getName());
// force SSL handshake
SessionContext context = SessionContext.getExistingContext();
ISSLClientCertProvider provider = (ISSLClientCertProvider)
- context.get("sslClientCertProvider");
+ context.get("sslClientCertProvider");
if (provider == null) {
CMS.debug("AgentCertAuthentication: No SSL Client Cert Provider Found");
@@ -185,15 +184,15 @@ public class AgentCertAuthentication implements IAuthManager,
// check if certificate(s) is revoked
boolean checkRevocation = true;
try {
- checkRevocation = mConfig.getBoolean("checkRevocation", true);
+ checkRevocation = mConfig.getBoolean("checkRevocation", true);
} catch (EBaseException e) {
- // do nothing; default to true
+ // do nothing; default to true
}
if (checkRevocation) {
- if (CMS.isRevoked(ci)) {
- CMS.debug("AgentCertAuthentication: certificate revoked");
- throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
- }
+ if (CMS.isRevoked(ci)) {
+ CMS.debug("AgentCertAuthentication: certificate revoked");
+ throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
+ }
}
// map cert to user
@@ -205,11 +204,11 @@ public class AgentCertAuthentication implements IAuthManager,
} catch (EUsrGrpException e) {
throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
} catch (netscape.ldap.LDAPException e) {
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR",
e.toString()));
}
- // any unexpected error occurs like internal db down,
+ // any unexpected error occurs like internal db down,
// UGSubsystem only returns null for user.
if (user == null) {
throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
@@ -219,16 +218,16 @@ public class AgentCertAuthentication implements IAuthManager,
IConfigStore sconfig = CMS.getConfigStore();
String groupname = "";
try {
- groupname = sconfig.getString("auths.instance."+ getName() +".agentGroup",
- "");
+ groupname = sconfig.getString("auths.instance." + getName() + ".agentGroup",
+ "");
} catch (EBaseException ee) {
}
if (!groupname.equals("")) {
- CMS.debug("check if "+user.getUserID()+" is in group "+groupname);
- IUGSubsystem uggroup = (IUGSubsystem)CMS.getSubsystem(CMS.SUBSYSTEM_UG);
+ CMS.debug("check if " + user.getUserID() + " is in group " + groupname);
+ IUGSubsystem uggroup = (IUGSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_UG);
if (!uggroup.isMemberOf(user, groupname)) {
- CMS.debug(user.getUserID()+" is not in this group "+groupname);
+ CMS.debug(user.getUserID() + " is not in this group " + groupname);
throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHORIZATION_ERROR"));
}
}
@@ -237,7 +236,7 @@ public class AgentCertAuthentication implements IAuthManager,
authToken.set(TOKEN_USERID, user.getUserID());
authToken.set(TOKEN_UID, user.getUserID());
authToken.set(TOKEN_GROUP, groupname);
- authToken.set(CRED_CERT, certs);
+ authToken.set(CRED_CERT, certs);
CMS.debug("AgentCertAuthentication: authenticated " + user.getUserDN());
@@ -245,11 +244,12 @@ public class AgentCertAuthentication implements IAuthManager,
}
/**
- * get the list of authentication credential attribute names
- * required by this authentication manager. Generally used by
- * the servlets that handle agent operations to authenticate its
- * users. It calls this method to know which are the
- * required credentials from the user (e.g. Javascript form data)
+ * get the list of authentication credential attribute names required by
+ * this authentication manager. Generally used by the servlets that handle
+ * agent operations to authenticate its users. It calls this method to know
+ * which are the required credentials from the user (e.g. Javascript form
+ * data)
+ *
* @return attribute names in Vector
*/
public String[] getRequiredCreds() {
@@ -257,15 +257,15 @@ public class AgentCertAuthentication implements IAuthManager,
}
/**
- * get the list of configuration parameter names
- * required by this authentication manager. Generally used by
- * the Certificate Server Console to display the table for
- * configuration purposes. CertUserDBAuthentication is currently not
- * exposed in this case, so this method is not to be used.
- * @return configuration parameter names in Hashtable of Vectors
- * where each hashtable entry's key is the substore name, value is a
- * Vector of parameter names. If no substore, the parameter name
- * is the Hashtable key itself, with value same as key.
+ * get the list of configuration parameter names required by this
+ * authentication manager. Generally used by the Certificate Server Console
+ * to display the table for configuration purposes. CertUserDBAuthentication
+ * is currently not exposed in this case, so this method is not to be used.
+ *
+ * @return configuration parameter names in Hashtable of Vectors where each
+ * hashtable entry's key is the substore name, value is a Vector of
+ * parameter names. If no substore, the parameter name is the
+ * Hashtable key itself, with value same as key.
*/
public String[] getConfigParams() {
return (mConfigParams);
@@ -278,8 +278,8 @@ public class AgentCertAuthentication implements IAuthManager,
}
/**
- * gets the configuretion substore used by this authentication
- * manager
+ * gets the configuretion substore used by this authentication manager
+ *
* @return configuration store
*/
public IConfigStore getConfigStore() {
@@ -289,7 +289,7 @@ public class AgentCertAuthentication implements IAuthManager,
// Profile-related methods
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
}
/**
@@ -318,14 +318,13 @@ public class AgentCertAuthentication implements IAuthManager,
}
/**
- * Retrieves the descriptor of the given value
- * parameter by name.
+ * Retrieves the descriptor of the given value parameter by name.
*/
public IDescriptor getValueDescriptor(Locale locale, String name) {
return null;
}
public void populate(IAuthToken token, IRequest request)
- throws EProfileException {
+ throws EProfileException {
}
}
diff --git a/pki/base/common/src/com/netscape/cms/authentication/CMCAuth.java b/pki/base/common/src/com/netscape/cms/authentication/CMCAuth.java
index fef68c1c..a499796a 100644
--- a/pki/base/common/src/com/netscape/cms/authentication/CMCAuth.java
+++ b/pki/base/common/src/com/netscape/cms/authentication/CMCAuth.java
@@ -20,7 +20,6 @@
package com.netscape.cms.authentication;
-
///////////////////////
// import statements //
///////////////////////
@@ -101,142 +100,137 @@ import com.netscape.cmsutil.util.Utils;
/**
* UID/CMC authentication plug-in
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class CMCAuth implements IAuthManager, IExtendedPluginInfo,
IProfileAuthenticator {
- ////////////////////////
+ // //////////////////////
// default parameters //
- ////////////////////////
-
-
-
- /////////////////////////////
+ // //////////////////////
+
+ // ///////////////////////////
// IAuthManager parameters //
- /////////////////////////////
-
+ // ///////////////////////////
+
/* authentication plug-in configuration store */
private IConfigStore mConfig;
private static final String HEADER = "-----BEGIN NEW CERTIFICATE REQUEST-----";
private static final String TRAILER = "-----END NEW CERTIFICATE REQUEST-----";
- public static final String TOKEN_CERT_SERIAL = "certSerialToRevoke";
+ public static final String TOKEN_CERT_SERIAL = "certSerialToRevoke";
public static final String REASON_CODE = "reasonCode";
/* authentication plug-in name */
private String mImplName = null;
-
+
/* authentication plug-in instance name */
private String mName = null;
-
+
/* authentication plug-in fields */
-
-
-
- /* Holds authentication plug-in fields accepted by this implementation.
- * This list is passed to the configuration console so configuration
- * for instances of this implementation can be configured through the
- * console.
+
+ /*
+ * Holds authentication plug-in fields accepted by this implementation. This
+ * list is passed to the configuration console so configuration for
+ * instances of this implementation can be configured through the console.
*/
protected static String[] mConfigParams =
- new String[] {};
-
+ new String[] {};
+
/* authentication plug-in values */
-
+
/* authentication plug-in properties */
-
-
+
/* required credentials to authenticate. UID and CMC are strings. */
public static final String CRED_CMC = "cmcRequest";
-
+
protected static String[] mRequiredCreds = {};
-
- ////////////////////////////////////
+
+ // //////////////////////////////////
// IExtendedPluginInfo parameters //
- ////////////////////////////////////
-
+ // //////////////////////////////////
+
/* Vector of extendedPluginInfo strings */
protected static Vector mExtendedPluginInfo = null;
- //public static final String AGENT_AUTHMGR_ID = "agentAuthMgr";
- //public static final String AGENT_PLUGIN_ID = "agentAuthPlugin";
-
-
+ // public static final String AGENT_AUTHMGR_ID = "agentAuthMgr";
+ // public static final String AGENT_PLUGIN_ID = "agentAuthPlugin";
+
/* actual help messages */
static {
mExtendedPluginInfo = new Vector();
-
+
mExtendedPluginInfo.add(IExtendedPluginInfo.HELP_TEXT +
- ";Authenticate the CMC request. The signer must be an agent. The \"Authentication Instance ID\" must be named \"CMCAuth\"");
+ ";Authenticate the CMC request. The signer must be an agent. The \"Authentication Instance ID\" must be named \"CMCAuth\"");
mExtendedPluginInfo.add(IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-authentication");
+ ";configuration-authentication");
}
-
- ///////////////////////
+
+ // /////////////////////
// Logger parameters //
- ///////////////////////
-
+ // /////////////////////
+
/* the system's logger */
private ILogger mLogger = CMS.getLogger();
-
+
/* signed audit parameters */
private ILogger mSignedAuditLogger = CMS.getSignedAuditLogger();
private final static String SIGNED_AUDIT_ENROLLMENT_REQUEST_TYPE =
- "enrollment";
+ "enrollment";
private final static String SIGNED_AUDIT_REVOCATION_REQUEST_TYPE =
- "revocation";
- private final static String
- LOGGING_SIGNED_AUDIT_CMC_SIGNED_REQUEST_SIG_VERIFY =
- "LOGGING_SIGNED_AUDIT_CMC_SIGNED_REQUEST_SIG_VERIFY_5";
+ "revocation";
+ private final static String LOGGING_SIGNED_AUDIT_CMC_SIGNED_REQUEST_SIG_VERIFY =
+ "LOGGING_SIGNED_AUDIT_CMC_SIGNED_REQUEST_SIG_VERIFY_5";
- /////////////////////
+ // ///////////////////
// default methods //
- /////////////////////
-
+ // ///////////////////
+
/**
* Default constructor, initialization must follow.
*/
public CMCAuth() {
}
-
- //////////////////////////
+
+ // ////////////////////////
// IAuthManager methods //
- //////////////////////////
-
+ // ////////////////////////
+
/**
* Initializes the CMCAuth authentication plug-in.
* <p>
+ *
* @param name The name for this authentication plug-in instance.
* @param implName The name of the authentication plug-in.
* @param config - The configuration store for this instance.
* @exception EBaseException If an error occurs during initialization.
*/
public void init(String name, String implName, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mName = name;
mImplName = implName;
mConfig = config;
-
+
log(ILogger.LL_INFO, "Initialization complete!");
}
-
+
/**
- * Authenticates user by their CMC;
- * resulting AuthToken sets a TOKEN_SUBJECT for the subject name.
+ * Authenticates user by their CMC; resulting AuthToken sets a TOKEN_SUBJECT
+ * for the subject name.
* <P>
- *
+ *
* <ul>
- * <li>signed.audit LOGGING_SIGNED_AUDIT_CMC_SIGNED_REQUEST_SIG_VERIFY
- * used when CMC (agent-pre-signed) cert requests or revocation requests
- * are submitted and signature is verified
+ * <li>signed.audit LOGGING_SIGNED_AUDIT_CMC_SIGNED_REQUEST_SIG_VERIFY used
+ * when CMC (agent-pre-signed) cert requests or revocation requests are
+ * submitted and signature is verified
* </ul>
+ *
* @param authCred Authentication credentials, CRED_UID and CRED_CMC.
* @return an AuthToken
- * @exception com.netscape.certsrv.authentication.EMissingCredential
- * If a required authentication credential is missing.
- * @exception com.netscape.certsrv.authentication.EInvalidCredentials
- * If credentials failed authentication.
- * @exception com.netscape.certsrv.base.EBaseException
- * If an internal error occurred.
+ * @exception com.netscape.certsrv.authentication.EMissingCredential If a
+ * required authentication credential is missing.
+ * @exception com.netscape.certsrv.authentication.EInvalidCredentials If
+ * credentials failed authentication.
+ * @exception com.netscape.certsrv.base.EBaseException If an internal error
+ * occurred.
* @see com.netscape.certsrv.authentication.AuthToken
*/
public IAuthToken authenticate(IAuthCredentials authCred) throws EMissingCredential, EInvalidCredentials, EBaseException {
@@ -245,13 +239,13 @@ public class CMCAuth implements IAuthManager, IExtendedPluginInfo,
String auditReqType = ILogger.UNIDENTIFIED;
String auditCertSubject = ILogger.UNIDENTIFIED;
String auditSignerInfo = ILogger.UNIDENTIFIED;
-
+
// ensure that any low-level exceptions are reported
// to the signed audit log and stored as failures
try {
// get the CMC.
- Object argblock = (Object)(authCred.getArgBlock());
+ Object argblock = (Object) (authCred.getArgBlock());
Object returnVal = null;
if (argblock == null) {
returnVal = authCred.get("cert_request");
@@ -266,140 +260,139 @@ public class CMCAuth implements IAuthManager, IExtendedPluginInfo,
if (cmc == null) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CMC_SIGNED_REQUEST_SIG_VERIFY,
- auditSubjectID,
- ILogger.FAILURE,
- auditReqType,
- auditCertSubject,
- auditSignerInfo );
+ LOGGING_SIGNED_AUDIT_CMC_SIGNED_REQUEST_SIG_VERIFY,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditReqType,
+ auditCertSubject,
+ auditSignerInfo);
- audit( auditMessage );
+ audit(auditMessage);
throw new EMissingCredential(CMS.getUserMessage(
- "CMS_AUTHENTICATION_NULL_CREDENTIAL",CRED_CMC));
+ "CMS_AUTHENTICATION_NULL_CREDENTIAL", CRED_CMC));
}
if (cmc.equals("")) {
log(ILogger.LL_FAILURE,
- "cmc : attempted login with empty CMC.");
+ "cmc : attempted login with empty CMC.");
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CMC_SIGNED_REQUEST_SIG_VERIFY,
- auditSubjectID,
- ILogger.FAILURE,
- auditReqType,
- auditCertSubject,
- auditSignerInfo );
+ LOGGING_SIGNED_AUDIT_CMC_SIGNED_REQUEST_SIG_VERIFY,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditReqType,
+ auditCertSubject,
+ auditSignerInfo);
- audit( auditMessage );
+ audit(auditMessage);
throw new EInvalidCredentials(CMS.getUserMessage(
- "CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
+ "CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
}
-
+
// authenticate by checking CMC.
-
+
// everything OK.
// now formulate the certificate info.
// set the subject name at a minimum.
// set anything else like version, extensions, etc.
// if nothing except subject name is set the rest of
// cert info will be filled in by policies and CA defaults.
-
+
AuthToken authToken = new AuthToken(this);
-
+
try {
String asciiBASE64Blob;
-
+
int startIndex = cmc.indexOf(HEADER);
int endIndex = cmc.indexOf(TRAILER);
- if (startIndex!= -1 && endIndex!=-1) {
+ if (startIndex != -1 && endIndex != -1) {
startIndex = startIndex + HEADER.length();
- asciiBASE64Blob=cmc.substring(startIndex, endIndex);
- }else
+ asciiBASE64Blob = cmc.substring(startIndex, endIndex);
+ } else
asciiBASE64Blob = cmc;
-
byte[] cmcBlob = CMS.AtoB(asciiBASE64Blob);
- ByteArrayInputStream cmcBlobIn= new
+ ByteArrayInputStream cmcBlobIn = new
ByteArrayInputStream(cmcBlob);
-
+
org.mozilla.jss.pkix.cms.ContentInfo cmcReq =
- (org.mozilla.jss.pkix.cms.ContentInfo)
- org.mozilla.jss.pkix.cms.ContentInfo.getTemplate().decode(
- cmcBlobIn);
+ (org.mozilla.jss.pkix.cms.ContentInfo)
+ org.mozilla.jss.pkix.cms.ContentInfo.getTemplate().decode(
+ cmcBlobIn);
- if(!cmcReq.getContentType().equals(
- org.mozilla.jss.pkix.cms.ContentInfo.SIGNED_DATA) ||
- !cmcReq.hasContent()) {
+ if (!cmcReq.getContentType().equals(
+ org.mozilla.jss.pkix.cms.ContentInfo.SIGNED_DATA) ||
+ !cmcReq.hasContent()) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CMC_SIGNED_REQUEST_SIG_VERIFY,
- auditSubjectID,
- ILogger.FAILURE,
- auditReqType,
- auditCertSubject,
- auditSignerInfo );
+ LOGGING_SIGNED_AUDIT_CMC_SIGNED_REQUEST_SIG_VERIFY,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditReqType,
+ auditCertSubject,
+ auditSignerInfo);
- audit( auditMessage );
+ audit(auditMessage);
// throw new ECMSGWException(CMSGWResources.NO_CMC_CONTENT);
throw new EBaseException("NO_CMC_CONTENT");
}
-
+
SignedData cmcFullReq = (SignedData)
cmcReq.getInterpretedContent();
-
+
IConfigStore cmc_config = CMS.getConfigStore();
boolean checkSignerInfo =
- cmc_config.getBoolean("cmc.signerInfo.verify", true);
+ cmc_config.getBoolean("cmc.signerInfo.verify", true);
String userid = "defUser";
String uid = "defUser";
if (checkSignerInfo) {
- IAuthToken agentToken = verifySignerInfo(authToken,cmcFullReq);
+ IAuthToken agentToken = verifySignerInfo(authToken, cmcFullReq);
userid = agentToken.getInString("userid");
uid = agentToken.getInString("cn");
} else {
CMS.debug("CMCAuth: authenticate() signerInfo verification bypassed");
}
// reset value of auditSignerInfo
- if( uid != null ) {
+ if (uid != null) {
auditSignerInfo = uid.trim();
}
EncapsulatedContentInfo ci = cmcFullReq.getContentInfo();
-
+
OBJECT_IDENTIFIER id = ci.getContentType();
if (!id.equals(OBJECT_IDENTIFIER.id_cct_PKIData) ||
- !ci.hasContent()) {
+ !ci.hasContent()) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CMC_SIGNED_REQUEST_SIG_VERIFY,
- auditSubjectID,
- ILogger.FAILURE,
- auditReqType,
- auditCertSubject,
- auditSignerInfo );
+ LOGGING_SIGNED_AUDIT_CMC_SIGNED_REQUEST_SIG_VERIFY,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditReqType,
+ auditCertSubject,
+ auditSignerInfo);
- audit( auditMessage );
+ audit(auditMessage);
- // throw new ECMSGWException(
+ // throw new ECMSGWException(
// CMSGWResources.NO_PKIDATA);
throw new EBaseException("NO_PKIDATA");
}
-
+
OCTET_STRING content = ci.getContent();
-
+
ByteArrayInputStream s = new
- ByteArrayInputStream(content.toByteArray());
+ ByteArrayInputStream(content.toByteArray());
PKIData pkiData = (PKIData) (new PKIData.Template()).decode(s);
-
+
SEQUENCE reqSequence = pkiData.getReqSequence();
-
+
int numReqs = reqSequence.size();
if (numReqs == 0) {
@@ -414,14 +407,14 @@ public class CMCAuth implements IAuthManager, IExtendedPluginInfo,
if (controlSize > 0) {
for (int i = 0; i < controlSize; i++) {
TaggedAttribute taggedAttribute =
- (TaggedAttribute) controlSequence.elementAt(i);
+ (TaggedAttribute) controlSequence.elementAt(i);
OBJECT_IDENTIFIER type = taggedAttribute.getType();
- if( type.equals(
- OBJECT_IDENTIFIER.id_cmc_revokeRequest)) {
+ if (type.equals(
+ OBJECT_IDENTIFIER.id_cmc_revokeRequest)) {
// if( i ==1 ) {
- // taggedAttribute.getType() ==
- // OBJECT_IDENTIFIER.id_cmc_revokeRequest
+ // taggedAttribute.getType() ==
+ // OBJECT_IDENTIFIER.id_cmc_revokeRequest
// }
SET values = taggedAttribute.getValues();
@@ -430,50 +423,48 @@ public class CMCAuth implements IAuthManager, IExtendedPluginInfo,
bigIntArray = new BigInteger[numVals];
for (int j = 0; j < numVals; j++) {
- // serialNumber INTEGER
-
+ // serialNumber INTEGER
+
// SEQUENCE RevRequest = (SEQUENCE)
- // values.elementAt(j);
+ // values.elementAt(j);
byte[] encoded = ASN1Util.encode(
- values.elementAt(j));
- org.mozilla.jss.asn1.ASN1Template
- template = new
- org.mozilla.jss.pkix.cmmf.RevRequest.Template();
- org.mozilla.jss.pkix.cmmf.RevRequest
- revRequest =
- (org.mozilla.jss.pkix.cmmf.RevRequest)
- ASN1Util.decode(template, encoded);
-
+ values.elementAt(j));
+ org.mozilla.jss.asn1.ASN1Template template = new
+ org.mozilla.jss.pkix.cmmf.RevRequest.Template();
+ org.mozilla.jss.pkix.cmmf.RevRequest revRequest =
+ (org.mozilla.jss.pkix.cmmf.RevRequest)
+ ASN1Util.decode(template, encoded);
+
// SEQUENCE RevRequest = (SEQUENCE)
- // ASN1Util.decode(
- // SEQUENCE.getTemplate(),
- // ASN1Util.encode(
- // values.elementAt(j)));
+ // ASN1Util.decode(
+ // SEQUENCE.getTemplate(),
+ // ASN1Util.encode(
+ // values.elementAt(j)));
// SEQUENCE RevRequest =
- // values.elementAt(j);
+ // values.elementAt(j);
// int revReqSize = RevRequest.size();
// if( revReqSize > 3 ) {
- // INTEGER serialNumber =
- // new INTEGER((long)0);
+ // INTEGER serialNumber =
+ // new INTEGER((long)0);
// }
INTEGER temp = revRequest.getSerialNumber();
int temp2 = temp.intValue();
-
+
bigIntArray[j] = temp;
- authToken.set(TOKEN_CERT_SERIAL,bigIntArray);
-
+ authToken.set(TOKEN_CERT_SERIAL, bigIntArray);
+
long reasonCode = revRequest.getReason().getValue();
- Integer IntObject = Integer.valueOf((int)reasonCode);
- authToken.set(REASON_CODE,IntObject);
-
- authToken.set("uid",uid);
- authToken.set("userid",userid);
+ Integer IntObject = Integer.valueOf((int) reasonCode);
+ authToken.set(REASON_CODE, IntObject);
+
+ authToken.set("uid", uid);
+ authToken.set("userid", userid);
}
}
}
-
+
}
} else {
// enrollment request
@@ -487,48 +478,48 @@ public class CMCAuth implements IAuthManager, IExtendedPluginInfo,
for (int i = 0; i < numReqs; i++) {
// decode message.
TaggedRequest taggedRequest =
- (TaggedRequest) reqSequence.elementAt(i);
+ (TaggedRequest) reqSequence.elementAt(i);
TaggedRequest.Type type = taggedRequest.getType();
if (type.equals(TaggedRequest.PKCS10)) {
CMS.debug("CMCAuth: in PKCS10");
TaggedCertificationRequest tcr =
- taggedRequest.getTcr();
+ taggedRequest.getTcr();
int p10Id = tcr.getBodyPartID().intValue();
reqIdArray[i] = String.valueOf(p10Id);
CertificationRequest p10 =
- tcr.getCertificationRequest();
+ tcr.getCertificationRequest();
// transfer to sun class
ByteArrayOutputStream ostream =
- new ByteArrayOutputStream();
+ new ByteArrayOutputStream();
p10.encode(ostream);
try {
PKCS10 pkcs10 =
- new PKCS10(ostream.toByteArray());
+ new PKCS10(ostream.toByteArray());
// xxx do we need to do anything else?
X509CertInfo certInfo =
- CMS.getDefaultX509CertInfo();
+ CMS.getDefaultX509CertInfo();
// fillPKCS10(certInfo,pkcs10,authToken,null);
// authToken.set(
- // pkcs10.getSubjectPublicKeyInfo());
+ // pkcs10.getSubjectPublicKeyInfo());
X500Name tempName = pkcs10.getSubjectName();
// reset value of auditCertSubject
- if( tempName != null ) {
+ if (tempName != null) {
auditCertSubject =
- tempName.toString().trim();
- if( auditCertSubject.equals( "" ) ) {
+ tempName.toString().trim();
+ if (auditCertSubject.equals("")) {
auditCertSubject =
- ILogger.SIGNED_AUDIT_EMPTY_VALUE;
+ ILogger.SIGNED_AUDIT_EMPTY_VALUE;
}
authToken.set(AuthToken.TOKEN_CERT_SUBJECT,
tempName.toString());
@@ -541,19 +532,19 @@ public class CMCAuth implements IAuthManager, IExtendedPluginInfo,
} catch (Exception e) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CMC_SIGNED_REQUEST_SIG_VERIFY,
- auditSubjectID,
- ILogger.FAILURE,
- auditReqType,
- auditCertSubject,
- auditSignerInfo );
+ LOGGING_SIGNED_AUDIT_CMC_SIGNED_REQUEST_SIG_VERIFY,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditReqType,
+ auditCertSubject,
+ auditSignerInfo);
- audit( auditMessage );
+ audit(auditMessage);
- //throw new ECMSGWException(
- //CMSGWResources.ERROR_PKCS101, e.toString());
+ // throw new ECMSGWException(
+ // CMSGWResources.ERROR_PKCS101, e.toString());
- e.printStackTrace();
+ e.printStackTrace();
throw new EBaseException(e.toString());
}
} else if (type.equals(TaggedRequest.CRMF)) {
@@ -561,7 +552,7 @@ public class CMCAuth implements IAuthManager, IExtendedPluginInfo,
CMS.debug("CMCAuth: in CRMF");
try {
CertReqMsg crm =
- taggedRequest.getCrm();
+ taggedRequest.getCrm();
CertRequest certReq = crm.getCertReq();
INTEGER reqID = certReq.getCertReqId();
reqIdArray[i] = reqID.toString();
@@ -570,16 +561,16 @@ public class CMCAuth implements IAuthManager, IExtendedPluginInfo,
// xxx do we need to do anything else?
X509CertInfo certInfo =
- CMS.getDefaultX509CertInfo();
+ CMS.getDefaultX509CertInfo();
// reset value of auditCertSubject
- if( name != null ) {
+ if (name != null) {
String ss = name.getRFC1485();
auditCertSubject = ss;
- if( auditCertSubject.equals( "" ) ) {
+ if (auditCertSubject.equals("")) {
auditCertSubject =
- ILogger.SIGNED_AUDIT_EMPTY_VALUE;
+ ILogger.SIGNED_AUDIT_EMPTY_VALUE;
}
authToken.set(AuthToken.TOKEN_CERT_SUBJECT, ss);
@@ -590,17 +581,17 @@ public class CMCAuth implements IAuthManager, IExtendedPluginInfo,
} catch (Exception e) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CMC_SIGNED_REQUEST_SIG_VERIFY,
- auditSubjectID,
- ILogger.FAILURE,
- auditReqType,
- auditCertSubject,
- auditSignerInfo );
+ LOGGING_SIGNED_AUDIT_CMC_SIGNED_REQUEST_SIG_VERIFY,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditReqType,
+ auditCertSubject,
+ auditSignerInfo);
- audit( auditMessage );
+ audit(auditMessage);
- //throw new ECMSGWException(
- //CMSGWResources.ERROR_PKCS101, e.toString());
+ // throw new ECMSGWException(
+ // CMSGWResources.ERROR_PKCS101, e.toString());
e.printStackTrace();
throw new EBaseException(e.toString());
@@ -608,141 +599,144 @@ public class CMCAuth implements IAuthManager, IExtendedPluginInfo,
}
// authToken.set(AgentAuthentication.CRED_CERT, new
- // com.netscape.certsrv.usrgrp.Certificates(
- // x509Certs));
+ // com.netscape.certsrv.usrgrp.Certificates(
+ // x509Certs));
}
}
} catch (Exception e) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CMC_SIGNED_REQUEST_SIG_VERIFY,
- auditSubjectID,
- ILogger.FAILURE,
- auditReqType,
- auditCertSubject,
- auditSignerInfo );
+ LOGGING_SIGNED_AUDIT_CMC_SIGNED_REQUEST_SIG_VERIFY,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditReqType,
+ auditCertSubject,
+ auditSignerInfo);
- audit( auditMessage );
+ audit(auditMessage);
- //Debug.printStackTrace(e);
+ // Debug.printStackTrace(e);
throw new EInvalidCredentials(CMS.getUserMessage(
- "CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
+ "CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
}
-
+
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CMC_SIGNED_REQUEST_SIG_VERIFY,
- auditSubjectID,
- ILogger.SUCCESS,
- auditReqType,
- auditCertSubject,
- auditSignerInfo );
+ LOGGING_SIGNED_AUDIT_CMC_SIGNED_REQUEST_SIG_VERIFY,
+ auditSubjectID,
+ ILogger.SUCCESS,
+ auditReqType,
+ auditCertSubject,
+ auditSignerInfo);
- audit( auditMessage );
+ audit(auditMessage);
return authToken;
- } catch( EMissingCredential eAudit1 ) {
+ } catch (EMissingCredential eAudit1) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CMC_SIGNED_REQUEST_SIG_VERIFY,
- auditSubjectID,
- ILogger.FAILURE,
- auditReqType,
- auditCertSubject,
- auditSignerInfo );
+ LOGGING_SIGNED_AUDIT_CMC_SIGNED_REQUEST_SIG_VERIFY,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditReqType,
+ auditCertSubject,
+ auditSignerInfo);
- audit( auditMessage );
+ audit(auditMessage);
// rethrow the specific exception to be handled later
throw eAudit1;
- } catch( EInvalidCredentials eAudit2 ) {
+ } catch (EInvalidCredentials eAudit2) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CMC_SIGNED_REQUEST_SIG_VERIFY,
- auditSubjectID,
- ILogger.FAILURE,
- auditReqType,
- auditCertSubject,
- auditSignerInfo );
+ LOGGING_SIGNED_AUDIT_CMC_SIGNED_REQUEST_SIG_VERIFY,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditReqType,
+ auditCertSubject,
+ auditSignerInfo);
- audit( auditMessage );
+ audit(auditMessage);
// rethrow the specific exception to be handled later
throw eAudit2;
- } catch( EBaseException eAudit3 ) {
+ } catch (EBaseException eAudit3) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CMC_SIGNED_REQUEST_SIG_VERIFY,
- auditSubjectID,
- ILogger.FAILURE,
- auditReqType,
- auditCertSubject,
- auditSignerInfo );
+ LOGGING_SIGNED_AUDIT_CMC_SIGNED_REQUEST_SIG_VERIFY,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditReqType,
+ auditCertSubject,
+ auditSignerInfo);
- audit( auditMessage );
+ audit(auditMessage);
// rethrow the specific exception to be handled later
throw eAudit3;
}
}
-
+
/**
- * Returns a list of configuration parameter names.
- * The list is passed to the configuration console so instances of
- * this implementation can be configured through the console.
+ * Returns a list of configuration parameter names. The list is passed to
+ * the configuration console so instances of this implementation can be
+ * configured through the console.
* <p>
+ *
* @return String array of configuration parameter names.
*/
public String[] getConfigParams() {
return (mConfigParams);
}
-
+
/**
- * gets the configuration substore used by this authentication
- * plug-in
+ * gets the configuration substore used by this authentication plug-in
* <p>
+ *
* @return configuration store
*/
public IConfigStore getConfigStore() {
return mConfig;
}
-
+
/**
* gets the plug-in name of this authentication plug-in.
*/
public String getImplName() {
return mImplName;
}
-
+
/**
* gets the name of this authentication plug-in instance
*/
public String getName() {
return mName;
}
-
+
/**
* get the list of required credentials.
* <p>
+ *
* @return list of required credentials as strings.
*/
public String[] getRequiredCreds() {
return (mRequiredCreds);
}
-
+
/**
* prepares for shutdown.
*/
public void shutdown() {
}
-
- /////////////////////////////////
+
+ // ///////////////////////////////
// IExtendedPluginInfo methods //
- /////////////////////////////////
-
+ // ///////////////////////////////
+
/**
* Activate the help system.
* <p>
+ *
* @return help messages
*/
public String[] getExtendedPluginInfo() {
@@ -755,14 +749,15 @@ public class CMCAuth implements IAuthManager, IExtendedPluginInfo,
}
return s;
}
-
- ////////////////////
+
+ // //////////////////
// Logger methods //
- ////////////////////
-
+ // //////////////////
+
/**
* Logs a message for this class in the system log file.
* <p>
+ *
* @param level The log level.
* @param msg The message to log.
* @see com.netscape.certsrv.logging.ILogger
@@ -771,45 +766,46 @@ public class CMCAuth implements IAuthManager, IExtendedPluginInfo,
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_AUTHENTICATION,
- level, "CMC Authentication: " + msg);
+ level, "CMC Authentication: " + msg);
}
-
- protected IAuthToken verifySignerInfo(AuthToken authToken,SignedData cmcFullReq) throws EInvalidCredentials {
-
+
+ protected IAuthToken verifySignerInfo(AuthToken authToken, SignedData cmcFullReq) throws EInvalidCredentials {
+
EncapsulatedContentInfo ci = cmcFullReq.getContentInfo();
OBJECT_IDENTIFIER id = ci.getContentType();
OCTET_STRING content = ci.getContent();
-
+
try {
ByteArrayInputStream s = new ByteArrayInputStream(content.toByteArray());
PKIData pkiData = (PKIData) (new PKIData.Template()).decode(s);
-
+
SET dais = cmcFullReq.getDigestAlgorithmIdentifiers();
int numDig = dais.size();
Hashtable digs = new Hashtable();
- //if request key is used for signing, there MUST be only one signerInfo
- //object in the signedData object.
+ // if request key is used for signing, there MUST be only one
+ // signerInfo
+ // object in the signedData object.
for (int i = 0; i < numDig; i++) {
AlgorithmIdentifier dai =
- (AlgorithmIdentifier) dais.elementAt(i);
+ (AlgorithmIdentifier) dais.elementAt(i);
String name =
- DigestAlgorithm.fromOID(dai.getOID()).toString();
-
+ DigestAlgorithm.fromOID(dai.getOID()).toString();
+
MessageDigest md =
- MessageDigest.getInstance(name);
-
+ MessageDigest.getInstance(name);
+
byte[] digest = md.digest(content.toByteArray());
digs.put(name, digest);
}
-
+
SET sis = cmcFullReq.getSignerInfos();
int numSis = sis.size();
-
+
for (int i = 0; i < numSis; i++) {
org.mozilla.jss.pkix.cms.SignerInfo si = (org.mozilla.jss.pkix.cms.SignerInfo) sis.elementAt(i);
-
+
String name = si.getDigestAlgorithm().toString();
byte[] digest = (byte[]) digs.get(name);
@@ -819,9 +815,9 @@ public class CMCAuth implements IAuthManager, IExtendedPluginInfo,
pkiData.encode((OutputStream) ostream);
digest = md.digest(ostream.toByteArray());
-
+
}
- // signed by previously certified signature key
+ // signed by previously certified signature key
SignerIdentifier sid = si.getSignerIdentifier();
if (sid.getType().equals(SignerIdentifier.ISSUER_AND_SERIALNUMBER)) {
@@ -833,30 +829,30 @@ public class CMCAuth implements IAuthManager, IExtendedPluginInfo,
SET certs = cmcFullReq.getCertificates();
int numCerts = certs.size();
java.security.cert.X509Certificate[] x509Certs = new java.security.cert.X509Certificate[1];
- byte[] certByteArray = new byte[0];
- for (int j = 0; j < numCerts; j++) {
+ byte[] certByteArray = new byte[0];
+ for (int j = 0; j < numCerts; j++) {
Certificate certJss = (Certificate) certs.elementAt(j);
CertificateInfo certI = certJss.getInfo();
Name issuer = certI.getIssuer();
-
+
byte[] issuerB = ASN1Util.encode(issuer);
- INTEGER sn = certI.getSerialNumber();
- // if this cert is the signer cert, not a cert in the chain
+ INTEGER sn = certI.getSerialNumber();
+ // if this cert is the signer cert, not a cert in
+ // the chain
if (new String(issuerB).equals(new String(ASN1Util.encode(issuerAndSerialNumber.getIssuer())))
- && sn.toString().equals(issuerAndSerialNumber.getSerialNumber().toString()) )
- {
+ && sn.toString().equals(issuerAndSerialNumber.getSerialNumber().toString())) {
ByteArrayOutputStream os = new
- ByteArrayOutputStream();
+ ByteArrayOutputStream();
certJss.encode(os);
- certByteArray = os.toByteArray();
-
+ certByteArray = os.toByteArray();
+
X509CertImpl tempcert = new X509CertImpl(os.toByteArray());
cert = tempcert;
x509Certs[0] = cert;
- // xxx validate the cert length
-
+ // xxx validate the cert length
+
}
}
CMS.debug("CMCAuth: start checking signature");
@@ -880,38 +876,38 @@ public class CMCAuth implements IAuthManager, IExtendedPluginInfo,
si.verify(digest, id, pubK);
}
CMS.debug("CMCAuth: finished checking signature");
- // verify signer's certificate using the revocator
- CryptoManager cm = CryptoManager.getInstance();
- if( ! cm.isCertValid( certByteArray, true,CryptoManager.CertUsage.SSLClient) )
+ // verify signer's certificate using the revocator
+ CryptoManager cm = CryptoManager.getInstance();
+ if (!cm.isCertValid(certByteArray, true, CryptoManager.CertUsage.SSLClient))
throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
- // authenticate signer's certificate using the userdb
+ // authenticate signer's certificate using the userdb
IAuthSubsystem authSS = (IAuthSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_AUTH);
-
- IAuthManager agentAuth = authSS.getAuthManager(IAuthSubsystem.CERTUSERDB_AUTHMGR_ID);//AGENT_AUTHMGR_ID);
- IAuthCredentials agentCred = new com.netscape.certsrv.authentication.AuthCredentials();
-
+
+ IAuthManager agentAuth = authSS.getAuthManager(IAuthSubsystem.CERTUSERDB_AUTHMGR_ID);// AGENT_AUTHMGR_ID);
+ IAuthCredentials agentCred = new com.netscape.certsrv.authentication.AuthCredentials();
+
agentCred.set(IAuthManager.CRED_SSL_CLIENT_CERT, x509Certs);
-
+
IAuthToken tempToken = agentAuth.authenticate(agentCred);
netscape.security.x509.X500Name tempPrincipal = (X500Name) x509Certs[0].getSubjectDN();
- String CN = (String) tempPrincipal.getCommonName();//tempToken.get("userid");
-
- BigInteger agentCertSerial = x509Certs[0].getSerialNumber();
- authToken.set(IAuthManager.CRED_SSL_CLIENT_CERT,agentCertSerial.toString());
- tempToken.set("cn",CN);
+ String CN = (String) tempPrincipal.getCommonName();// tempToken.get("userid");
+
+ BigInteger agentCertSerial = x509Certs[0].getSerialNumber();
+ authToken.set(IAuthManager.CRED_SSL_CLIENT_CERT, agentCertSerial.toString());
+ tempToken.set("cn", CN);
return tempToken;
-
+
}
// find from internaldb if it's ca. (ra does not have that.)
// find from internaldb usrgrp info
-
+
// find from certDB
- si.verify(digest, id);
-
- } //
+ si.verify(digest, id);
+
+ } //
}
- }catch (InvalidBERException e) {
+ } catch (InvalidBERException e) {
CMS.debug("CMCAuth: " + e.toString());
} catch (IOException e) {
CMS.debug("CMCAuth: " + e.toString());
@@ -919,7 +915,7 @@ public class CMCAuth implements IAuthManager, IExtendedPluginInfo,
throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
}
return (IAuthToken) null;
-
+
}
public String[] getExtendedPluginInfo(Locale locale) {
@@ -929,22 +925,20 @@ public class CMCAuth implements IAuthManager, IExtendedPluginInfo,
// Profile-related methods
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
}
/**
* Retrieves the localizable name of this policy.
*/
- public String getName(Locale locale)
- {
+ public String getName(Locale locale) {
return CMS.getUserMessage(locale, "CMS_AUTHENTICATION_CMS_SIGN_NAME");
}
/**
* Retrieves the localizable description of this policy.
*/
- public String getText(Locale locale)
- {
+ public String getText(Locale locale) {
return CMS.getUserMessage(locale, "CMS_AUTHENTICATION_CMS_SIGN_TEXT");
}
@@ -962,19 +956,18 @@ public class CMCAuth implements IAuthManager, IExtendedPluginInfo,
}
/**
- * Retrieves the descriptor of the given value
- * parameter by name.
+ * Retrieves the descriptor of the given value parameter by name.
*/
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(CRED_CMC)) {
return new Descriptor(IDescriptor.STRING_LIST, null, null,
- "CMC request");
+ "CMC request");
}
return null;
}
public void populate(IAuthToken token, IRequest request)
- throws EProfileException {
+ throws EProfileException {
request.setExtData(IProfileAuthenticator.AUTHENTICATED_NAME,
token.getInString(AuthToken.TOKEN_CERT_SUBJECT));
}
@@ -985,10 +978,10 @@ public class CMCAuth implements IAuthManager, IExtendedPluginInfo,
/**
* Signed Audit Log
- *
+ *
* This method is called to store messages to the signed audit log.
* <P>
- *
+ *
* @param msg signed audit log message
*/
private void audit(String msg) {
@@ -1000,19 +993,19 @@ public class CMCAuth implements IAuthManager, IExtendedPluginInfo,
}
mSignedAuditLogger.log(ILogger.EV_SIGNED_AUDIT,
- null,
- ILogger.S_SIGNED_AUDIT,
- ILogger.LL_SECURITY,
- msg);
+ null,
+ ILogger.S_SIGNED_AUDIT,
+ ILogger.LL_SECURITY,
+ msg);
}
/**
* Signed Audit Log Subject ID
- *
- * This method is called to obtain the "SubjectID" for
- * a signed audit log message.
+ *
+ * This method is called to obtain the "SubjectID" for a signed audit log
+ * message.
* <P>
- *
+ *
* @return id string containing the signed audit log message SubjectID
*/
private String auditSubjectID() {
@@ -1042,4 +1035,3 @@ public class CMCAuth implements IAuthManager, IExtendedPluginInfo,
return subjectID;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/authentication/Crypt.java b/pki/base/common/src/com/netscape/cms/authentication/Crypt.java
index 95012039..db4fda5f 100644
--- a/pki/base/common/src/com/netscape/cms/authentication/Crypt.java
+++ b/pki/base/common/src/com/netscape/cms/authentication/Crypt.java
@@ -17,151 +17,150 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.authentication;
-
public class Crypt {
// Static data:
static byte[]
- IP = // Initial permutation
- {
- 58, 50, 42, 34, 26, 18, 10, 2,
- 60, 52, 44, 36, 28, 20, 12, 4,
- 62, 54, 46, 38, 30, 22, 14, 6,
- 64, 56, 48, 40, 32, 24, 16, 8,
- 57, 49, 41, 33, 25, 17, 9, 1,
- 59, 51, 43, 35, 27, 19, 11, 3,
- 61, 53, 45, 37, 29, 21, 13, 5,
- 63, 55, 47, 39, 31, 23, 15, 7
+ IP = // Initial permutation
+ {
+ 58, 50, 42, 34, 26, 18, 10, 2,
+ 60, 52, 44, 36, 28, 20, 12, 4,
+ 62, 54, 46, 38, 30, 22, 14, 6,
+ 64, 56, 48, 40, 32, 24, 16, 8,
+ 57, 49, 41, 33, 25, 17, 9, 1,
+ 59, 51, 43, 35, 27, 19, 11, 3,
+ 61, 53, 45, 37, 29, 21, 13, 5,
+ 63, 55, 47, 39, 31, 23, 15, 7
},
- FP = // Final permutation, FP = IP^(-1)
- {
- 40, 8, 48, 16, 56, 24, 64, 32,
- 39, 7, 47, 15, 55, 23, 63, 31,
- 38, 6, 46, 14, 54, 22, 62, 30,
- 37, 5, 45, 13, 53, 21, 61, 29,
- 36, 4, 44, 12, 52, 20, 60, 28,
- 35, 3, 43, 11, 51, 19, 59, 27,
- 34, 2, 42, 10, 50, 18, 58, 26,
- 33, 1, 41, 9, 49, 17, 57, 25
+ FP = // Final permutation, FP = IP^(-1)
+ {
+ 40, 8, 48, 16, 56, 24, 64, 32,
+ 39, 7, 47, 15, 55, 23, 63, 31,
+ 38, 6, 46, 14, 54, 22, 62, 30,
+ 37, 5, 45, 13, 53, 21, 61, 29,
+ 36, 4, 44, 12, 52, 20, 60, 28,
+ 35, 3, 43, 11, 51, 19, 59, 27,
+ 34, 2, 42, 10, 50, 18, 58, 26,
+ 33, 1, 41, 9, 49, 17, 57, 25
},
- // Permuted-choice 1 from the key bits to yield C and D.
- // Note that bits 8,16... are left out:
- // They are intended for a parity check.
- PC1_C =
+ // Permuted-choice 1 from the key bits to yield C and D.
+ // Note that bits 8,16... are left out:
+ // They are intended for a parity check.
+ PC1_C =
{
- 57, 49, 41, 33, 25, 17, 9,
- 1, 58, 50, 42, 34, 26, 18,
- 10, 2, 59, 51, 43, 35, 27,
- 19, 11, 3, 60, 52, 44, 36
+ 57, 49, 41, 33, 25, 17, 9,
+ 1, 58, 50, 42, 34, 26, 18,
+ 10, 2, 59, 51, 43, 35, 27,
+ 19, 11, 3, 60, 52, 44, 36
},
- PC1_D =
+ PC1_D =
{
- 63, 55, 47, 39, 31, 23, 15,
- 7, 62, 54, 46, 38, 30, 22,
- 14, 6, 61, 53, 45, 37, 29,
- 21, 13, 5, 28, 20, 12, 4
+ 63, 55, 47, 39, 31, 23, 15,
+ 7, 62, 54, 46, 38, 30, 22,
+ 14, 6, 61, 53, 45, 37, 29,
+ 21, 13, 5, 28, 20, 12, 4
},
- shifts = // Sequence of shifts used for the key schedule.
- {
- 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1
+ shifts = // Sequence of shifts used for the key schedule.
+ {
+ 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1
},
- // Permuted-choice 2, to pick out the bits from
- // the CD array that generate the key schedule.
- PC2_C =
+ // Permuted-choice 2, to pick out the bits from
+ // the CD array that generate the key schedule.
+ PC2_C =
{
- 14, 17, 11, 24, 1, 5,
- 3, 28, 15, 6, 21, 10,
- 23, 19, 12, 4, 26, 8,
- 16, 7, 27, 20, 13, 2
+ 14, 17, 11, 24, 1, 5,
+ 3, 28, 15, 6, 21, 10,
+ 23, 19, 12, 4, 26, 8,
+ 16, 7, 27, 20, 13, 2
},
- PC2_D =
+ PC2_D =
{
- 41, 52, 31, 37, 47, 55,
- 30, 40, 51, 45, 33, 48,
- 44, 49, 39, 56, 34, 53,
- 46, 42, 50, 36, 29, 32
+ 41, 52, 31, 37, 47, 55,
+ 30, 40, 51, 45, 33, 48,
+ 44, 49, 39, 56, 34, 53,
+ 46, 42, 50, 36, 29, 32
},
- e2 = // The E-bit selection table. (see E below)
- {
- 32, 1, 2, 3, 4, 5,
- 4, 5, 6, 7, 8, 9,
- 8, 9, 10, 11, 12, 13,
- 12, 13, 14, 15, 16, 17,
- 16, 17, 18, 19, 20, 21,
- 20, 21, 22, 23, 24, 25,
- 24, 25, 26, 27, 28, 29,
- 28, 29, 30, 31, 32, 1
+ e2 = // The E-bit selection table. (see E below)
+ {
+ 32, 1, 2, 3, 4, 5,
+ 4, 5, 6, 7, 8, 9,
+ 8, 9, 10, 11, 12, 13,
+ 12, 13, 14, 15, 16, 17,
+ 16, 17, 18, 19, 20, 21,
+ 20, 21, 22, 23, 24, 25,
+ 24, 25, 26, 27, 28, 29,
+ 28, 29, 30, 31, 32, 1
},
- // P is a permutation on the selected combination of
- // the current L and key.
- P =
+ // P is a permutation on the selected combination of
+ // the current L and key.
+ P =
{
- 16, 7, 20, 21,
- 29, 12, 28, 17,
- 1, 15, 23, 26,
- 5, 18, 31, 10,
- 2, 8, 24, 14,
- 32, 27, 3, 9,
- 19, 13, 30, 6,
- 22, 11, 4, 25
+ 16, 7, 20, 21,
+ 29, 12, 28, 17,
+ 1, 15, 23, 26,
+ 5, 18, 31, 10,
+ 2, 8, 24, 14,
+ 32, 27, 3, 9,
+ 19, 13, 30, 6,
+ 22, 11, 4, 25
};
- // The 8 selection functions. For some reason, they gave a 0-origin
+ // The 8 selection functions. For some reason, they gave a 0-origin
// index, unlike everything else.
static byte[][] S =
{
- {
- 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7,
- 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8,
- 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0,
- 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13
- }, {
- 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10,
- 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5,
- 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15,
- 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9
- }, {
- 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8,
- 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1,
- 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7,
- 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12
- }, {
- 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15,
- 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9,
- 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4,
- 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14
- }, {
- 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9,
- 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6,
- 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14,
- 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3
- }, {
- 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11,
- 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8,
- 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6,
- 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13
- }, {
- 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1,
- 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6,
- 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2,
- 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12
- }, {
- 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7,
- 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2,
- 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8,
- 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11
- }
+ {
+ 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7,
+ 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8,
+ 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0,
+ 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13
+ }, {
+ 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10,
+ 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5,
+ 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15,
+ 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9
+ }, {
+ 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8,
+ 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1,
+ 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7,
+ 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12
+ }, {
+ 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15,
+ 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9,
+ 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4,
+ 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14
+ }, {
+ 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9,
+ 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6,
+ 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14,
+ 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3
+ }, {
+ 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11,
+ 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8,
+ 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6,
+ 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13
+ }, {
+ 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1,
+ 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6,
+ 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2,
+ 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12
+ }, {
+ 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7,
+ 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2,
+ 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8,
+ 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11
+ }
};
// Dynamic data:
- byte[] C = new byte[28], // The C and D arrays used to
- D = new byte[28], // calculate the key schedule.
- E = new byte[48], // The E bit-selection table.
- L = new byte[32], // The current block,
- R = new byte[32], // divided into two halves.
- tempL = new byte[32],
- f = new byte[32],
- preS = new byte[48]; // The combination of the key and
+ byte[] C = new byte[28], // The C and D arrays used to
+ D = new byte[28], // calculate the key schedule.
+ E = new byte[48], // The E bit-selection table.
+ L = new byte[32], // The current block,
+ R = new byte[32], // divided into two halves.
+ tempL = new byte[32],
+ f = new byte[32],
+ preS = new byte[48]; // The combination of the key and
// the input, before selection.
- // The key schedule. Generated from the key.
+ // The key schedule. Generated from the key.
byte[][] KS = new byte[16][48];
// Object fields:
@@ -169,17 +168,17 @@ public class Crypt {
// Public methods:
/**
- * Create Crypt object with no passwd or salt set. Must use setPasswd()
- * and setSalt() before getEncryptedPasswd().
+ * Create Crypt object with no passwd or salt set. Must use setPasswd() and
+ * setSalt() before getEncryptedPasswd().
*/
public Crypt() {
Passwd = Salt = Encrypt = "";
}
/**
- * Create a Crypt object with specified salt. Use setPasswd() before
+ * Create a Crypt object with specified salt. Use setPasswd() before
* getEncryptedPasswd().
- *
+ *
* @param salt the salt string for encryption
*/
public Crypt(String salt) {
@@ -189,10 +188,9 @@ public class Crypt {
}
/**
- * Create a Crypt object with specified passwd and salt (often the
- * already encypted passwd). Get the encrypted result with
- * getEncryptedPasswd().
- *
+ * Create a Crypt object with specified passwd and salt (often the already
+ * encypted passwd). Get the encrypted result with getEncryptedPasswd().
+ *
* @param passwd the passwd to encrypt
* @param salt the salt string for encryption
*/
@@ -204,7 +202,7 @@ public class Crypt {
/**
* Retrieve the passwd string currently being encrypted.
- *
+ *
* @return the current passwd string
*/
public String getPasswd() {
@@ -213,7 +211,7 @@ public class Crypt {
/**
* Retrieve the salt string currently being used for encryption.
- *
+ *
* @return the current salt string
*/
public String getSalt() {
@@ -221,9 +219,9 @@ public class Crypt {
}
/**
- * Retrieve the resulting encrypted string from the current passwd and
- * salt settings.
- *
+ * Retrieve the resulting encrypted string from the current passwd and salt
+ * settings.
+ *
* @return the encrypted passwd
*/
public String getEncryptedPasswd() {
@@ -231,9 +229,9 @@ public class Crypt {
}
/**
- * Set a new passwd string for encryption. Use getEncryptedPasswd() to
+ * Set a new passwd string for encryption. Use getEncryptedPasswd() to
* retrieve the new result.
- *
+ *
* @param passwd the new passwd string
*/
public void setPasswd(String passwd) {
@@ -242,9 +240,9 @@ public class Crypt {
}
/**
- * Set a new salt string for encryption. Use getEncryptedPasswd() to
+ * Set a new salt string for encryption. Use getEncryptedPasswd() to
* retrieve the new result.
- *
+ *
* @param salt the new salt string
*/
public void setSalt(String salt) {
@@ -254,19 +252,17 @@ public class Crypt {
// Internal crypt methods:
String crypt() {
- if (Salt.length() == 0) return "";
+ if (Salt.length() == 0)
+ return "";
int i, j, pwi;
byte c, temp;
- byte[] block = new byte[66],
- iobuf = new byte[16],
- salt = new byte[2],
- pw = Passwd.getBytes(), //jdk1.1
- saltbytes = Salt.getBytes(); //jdk1.1
+ byte[] block = new byte[66], iobuf = new byte[16], salt = new byte[2], pw = Passwd.getBytes(), // jdk1.1
+ saltbytes = Salt.getBytes(); // jdk1.1
- // pw = new byte[Passwd.length()], //jdk1.0.2
- // saltbytes = new byte[Salt.length()]; //jdk1.0.2
- //Passwd.getBytes(0,Passwd.length(),pw,0); //jdk1.0.2
- //Salt.getBytes(0,Salt.length(),saltbytes,0); //jdk1.0.2
+ // pw = new byte[Passwd.length()], //jdk1.0.2
+ // saltbytes = new byte[Salt.length()]; //jdk1.0.2
+ // Passwd.getBytes(0,Passwd.length(),pw,0); //jdk1.0.2
+ // Salt.getBytes(0,Salt.length(),saltbytes,0); //jdk1.0.2
salt[0] = saltbytes[0];
salt[1] = (saltbytes.length > 1) ? saltbytes[1] : 0;
@@ -288,8 +284,10 @@ public class Crypt {
for (i = 0; i < 2; i++) {
c = salt[i];
iobuf[i] = c;
- if (c > 'Z') c -= 6;
- if (c > '9') c -= 7;
+ if (c > 'Z')
+ c -= 6;
+ if (c > '9')
+ c -= 7;
c -= '.';
for (j = 0; j < 6; j++) {
if (((c >> j) & 1) != 0) {
@@ -311,8 +309,10 @@ public class Crypt {
c |= block[6 * i + j];
}
c += '.';
- if (c > '9') c += 7;
- if (c > 'Z') c += 6;
+ if (c > '9')
+ c += 7;
+ if (c > 'Z')
+ c += 6;
iobuf[i + 2] = c;
}
@@ -320,16 +320,16 @@ public class Crypt {
if (iobuf[1] == 0)
iobuf[1] = iobuf[0];
- return new String(iobuf); //jdk1.1
- //return new String(iobuf,0); //jdk1.0.2
+ return new String(iobuf); // jdk1.1
+ // return new String(iobuf,0); //jdk1.0.2
}
- void setkey(byte[] key) // Set up the key schedule from the key.
+ void setkey(byte[] key) // Set up the key schedule from the key.
{
int i, j, k;
byte t;
- // First, generate C and D by permuting the key. The low order bit
+ // First, generate C and D by permuting the key. The low order bit
// of each 8-bit char is not used, so C and D are only 28 bits apiece.
for (i = 0; i < 28; i++) {
C[i] = key[PC1_C[i] - 1];
@@ -369,41 +369,41 @@ public class Crypt {
byte k;
// First, permute the bits in the input
- //for (j = 0; j < 64; j++)
- //{
- // L[j] = block[IP[j]-1];
- //}
+ // for (j = 0; j < 64; j++)
+ // {
+ // L[j] = block[IP[j]-1];
+ // }
for (j = 0; j < 32; j++)
L[j] = block[IP[j] - 1];
for (j = 32; j < 64; j++)
R[j - 32] = block[IP[j] - 1];
- // Perform an encryption operation 16 times.
+ // Perform an encryption operation 16 times.
for (ii = 0; ii < 16; ii++) {
i = ii;
// Save the R array, which will be the new L.
for (j = 0; j < 32; j++)
tempL[j] = R[j];
- // Expand R to 48 bits using the E selector;
- // exclusive-or with the current key bits.
+ // Expand R to 48 bits using the E selector;
+ // exclusive-or with the current key bits.
for (j = 0; j < 48; j++)
preS[j] = (byte) (R[E[j] - 1] ^ KS[i][j]);
- // The pre-select bits are now considered in 8 groups of
- // 6 bits each. The 8 selection functions map these 6-bit
- // quantities into 4-bit quantities and the results permuted
- // to make an f(R, K). The indexing into the selection functions
- // is peculiar; it could be simplified by rewriting the tables.
+ // The pre-select bits are now considered in 8 groups of
+ // 6 bits each. The 8 selection functions map these 6-bit
+ // quantities into 4-bit quantities and the results permuted
+ // to make an f(R, K). The indexing into the selection functions
+ // is peculiar; it could be simplified by rewriting the tables.
for (j = 0; j < 8; j++) {
t = 6 * j;
- k = S[j][ (preS[t ] << 5) +
+ k = S[j][(preS[t] << 5) +
(preS[t + 1] << 3) +
(preS[t + 2] << 2) +
(preS[t + 3] << 1) +
(preS[t + 4]) +
- (preS[t + 5] << 4) ];
+ (preS[t + 5] << 4)];
t = 4 * j;
- f[t ] = (byte) ((k >> 3) & 1);
+ f[t] = (byte) ((k >> 3) & 1);
f[t + 1] = (byte) ((k >> 2) & 1);
f[t + 2] = (byte) ((k >> 1) & 1);
f[t + 3] = (byte) ((k) & 1);
@@ -430,7 +430,7 @@ public class Crypt {
// The final output gets the inverse permutation of the very original.
for (j = 0; j < 64; j++) {
- //block[j] = L[FP[j]-1];
+ // block[j] = L[FP[j]-1];
block[j] = (FP[j] > 32) ? R[FP[j] - 33] : L[FP[j] - 1];
}
}
diff --git a/pki/base/common/src/com/netscape/cms/authentication/DNPattern.java b/pki/base/common/src/com/netscape/cms/authentication/DNPattern.java
index 1f2eb69a..a221f68f 100644
--- a/pki/base/common/src/com/netscape/cms/authentication/DNPattern.java
+++ b/pki/base/common/src/com/netscape/cms/authentication/DNPattern.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.authentication;
-
import java.io.IOException;
import java.io.PushbackReader;
import java.io.StringReader;
@@ -28,24 +27,27 @@ import netscape.ldap.LDAPEntry;
import com.netscape.certsrv.authentication.EAuthException;
import com.netscape.certsrv.base.EBaseException;
-
/**
- * class for parsing a DN pattern used to construct a certificate
- * subject name from ldap attributes and dn.<p>
+ * class for parsing a DN pattern used to construct a certificate subject name
+ * from ldap attributes and dn.
+ * <p>
*
- * dnpattern is a string representing a subject name pattern to formulate from
- * the directory attributes and entry dn. If empty or not set, the
- * ldap entry DN will be used as the certificate subject name. <p>
+ * dnpattern is a string representing a subject name pattern to formulate from
+ * the directory attributes and entry dn. If empty or not set, the ldap entry DN
+ * will be used as the certificate subject name.
+ * <p>
+ *
+ * The syntax is
*
- * The syntax is
* <pre>
- * dnPattern := rdnPattern *[ "," rdnPattern ]
- * rdnPattern := avaPattern *[ "+" avaPattern ]
+ * dnPattern := rdnPattern *[ "," rdnPattern ]
+ * rdnPattern := avaPattern *[ "+" avaPattern ]
* avaPattern := name "=" value |
- * name "=" "$attr" "." attrName [ "." attrNumber ] |
- * name "=" "$dn" "." attrName [ "." attrNumber ] |
- * "$dn" "." "$rdn" "." number
+ * name "=" "$attr" "." attrName [ "." attrNumber ] |
+ * name "=" "$dn" "." attrName [ "." attrNumber ] |
+ * "$dn" "." "$rdn" "." number
* </pre>
+ *
* <pre>
* Example1: <i>E=$attr.mail.1, CN=$attr.cn, OU=$dn.ou.2, O=$dn.o, C=US </i>
* Ldap entry: dn: UID=jjames, OU=IS, OU=people, O=acme.org
@@ -72,11 +74,12 @@ import com.netscape.certsrv.base.EBaseException;
* E = the first 'mail' ldap attribute value in user's entry. <br>
* CN = the (first) 'cn' ldap attribute value in the user's entry. <br>
* OU = the second 'ou' value in the user's entry DN. note multiple AVAs
- * in a RDN in this example. <br>
+ * in a RDN in this example. <br>
* O = the (first) 'o' value in the user's entry DN. <br>
* C = the string "US"
* <p>
* </pre>
+ *
* <pre>
* Example3: <i>CN=$attr.cn, $rdn.2, O=$dn.o, C=US</i>
* Ldap entry: dn: UID=jjames, OU=IS+OU=people, O=acme.org
@@ -101,15 +104,16 @@ import com.netscape.certsrv.base.EBaseException;
* <p>
* CN = the (first) 'cn' ldap attribute value in the user's entry. <br>
* OU = the second 'ou' value in the user's entry DN followed by the
- * first 'ou' value in the user's entry. note multiple AVAs
- * in a RDN in this example. <br>
+ * first 'ou' value in the user's entry. note multiple AVAs
+ * in a RDN in this example. <br>
* O = the (first) 'o' value in the user's entry DN. <br>
* C = the string "US"
* <p>
* </pre>
- * If an attribute or subject DN component does not exist the attribute
- * is skipped.
- *
+ *
+ * If an attribute or subject DN component does not exist the attribute is
+ * skipped.
+ *
* @version $Revision$, $Date$
*/
public class DNPattern {
@@ -125,15 +129,16 @@ public class DNPattern {
protected String mTestDN = null;
- /**
+ /**
* Construct a DN pattern by parsing a pattern string.
+ *
* @param pattern the DN pattern
- * @exception EBaseException If parsing error occurs.
+ * @exception EBaseException If parsing error occurs.
*/
public DNPattern(String pattern)
- throws EAuthException {
+ throws EAuthException {
if (pattern == null || pattern.equals("")) {
- // create an attribute list that is the dn.
+ // create an attribute list that is the dn.
mLdapAttrs = new String[] { "dn" };
} else {
mPatternString = pattern;
@@ -143,13 +148,13 @@ public class DNPattern {
}
}
- public DNPattern(PushbackReader in)
- throws EAuthException {
+ public DNPattern(PushbackReader in)
+ throws EAuthException {
parse(in);
}
private void parse(PushbackReader in)
- throws EAuthException {
+ throws EAuthException {
Vector rdnPatterns = new Vector();
RDNPattern rdnPattern = null;
int lastChar = -1;
@@ -162,8 +167,7 @@ public class DNPattern {
} catch (IOException e) {
throw new EAuthException("CMS_AUTHENTICATION_INTERNAL_ERROR", e.toString());
}
- }
- while (lastChar == ',');
+ } while (lastChar == ',');
mRDNPatterns = new RDNPattern[rdnPatterns.size()];
rdnPatterns.copyInto(mRDNPatterns);
@@ -173,8 +177,8 @@ public class DNPattern {
for (int i = 0; i < mRDNPatterns.length; i++) {
String[] rdnAttrs = mRDNPatterns[i].getLdapAttrs();
- if (rdnAttrs != null && rdnAttrs.length > 0)
- for (int j = 0; j < rdnAttrs.length; j++)
+ if (rdnAttrs != null && rdnAttrs.length > 0)
+ for (int j = 0; j < rdnAttrs.length; j++)
ldapAttrs.addElement(rdnAttrs[j]);
}
mLdapAttrs = new String[ldapAttrs.size()];
@@ -183,11 +187,12 @@ public class DNPattern {
/**
* Form a Ldap v3 DN string from results of a ldap search.
+ *
* @param entry LDAPentry from a ldap search
- * @return Ldap v3 DN string to use for a subject name.
+ * @return Ldap v3 DN string to use for a subject name.
*/
public String formDN(LDAPEntry entry)
- throws EAuthException {
+ throws EAuthException {
StringBuffer formedDN = new StringBuffer();
for (int i = 0; i < mRDNPatterns.length; i++) {
@@ -197,13 +202,13 @@ public class DNPattern {
if (rdn != null) {
if (rdn != null && rdn.length() != 0) {
- if (formedDN.length() != 0)
+ if (formedDN.length() != 0)
formedDN.append(",");
formedDN.append(rdn);
}
}
}
- //System.out.println("formed DN "+formedDN.toString());
+ // System.out.println("formed DN "+formedDN.toString());
return formedDN.toString();
}
diff --git a/pki/base/common/src/com/netscape/cms/authentication/DirBasedAuthentication.java b/pki/base/common/src/com/netscape/cms/authentication/DirBasedAuthentication.java
index c9b64fca..41fb9699 100644
--- a/pki/base/common/src/com/netscape/cms/authentication/DirBasedAuthentication.java
+++ b/pki/base/common/src/com/netscape/cms/authentication/DirBasedAuthentication.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.authentication;
-
// ldap java sdk
import java.io.IOException;
import java.security.cert.CertificateException;
@@ -57,29 +56,28 @@ import com.netscape.certsrv.ldap.ILdapConnFactory;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.cmsutil.util.Utils;
-
/**
- * Abstract class for directory based authentication managers
- * Uses a pattern for formulating subject names.
- * The pattern is read from configuration file.
+ * Abstract class for directory based authentication managers Uses a pattern for
+ * formulating subject names. The pattern is read from configuration file.
* Syntax of the pattern is described in the init() method.
*
* <P>
+ *
* @version $Revision$, $Date$
*/
-public abstract class DirBasedAuthentication
- implements IAuthManager, IExtendedPluginInfo {
+public abstract class DirBasedAuthentication
+ implements IAuthManager, IExtendedPluginInfo {
- protected static final String USER_DN = "userDN";
+ protected static final String USER_DN = "userDN";
/* configuration parameter keys */
- protected static final String PROP_LDAP = "ldap";
- protected static final String PROP_BASEDN = "basedn";
- protected static final String PROP_DNPATTERN = "dnpattern";
+ protected static final String PROP_LDAP = "ldap";
+ protected static final String PROP_BASEDN = "basedn";
+ protected static final String PROP_DNPATTERN = "dnpattern";
protected static final String PROP_LDAPSTRINGATTRS = "ldapStringAttributes";
protected static final String PROP_LDAPBYTEATTRS = "ldapByteAttributes";
- // members
+ // members
/* name of this authentication manager instance */
protected String mName = null;
@@ -105,20 +103,24 @@ public abstract class DirBasedAuthentication
/* the subject DN pattern */
protected DNPattern mPattern = null;
- /* the list of LDAP attributes with string values to retrieve to
- * save in the auth token including ones from the dn pattern. */
+ /*
+ * the list of LDAP attributes with string values to retrieve to save in the
+ * auth token including ones from the dn pattern.
+ */
protected String[] mLdapStringAttrs = null;
- /* the list of LDAP attributes with byte[] values to retrive to save
- * in authtoken. */
+ /*
+ * the list of LDAP attributes with byte[] values to retrive to save in
+ * authtoken.
+ */
protected String[] mLdapByteAttrs = null;
- /* the combined list of LDAP attriubutes to retrieve*/
+ /* the combined list of LDAP attriubutes to retrieve */
protected String[] mLdapAttrs = null;
/* default dn pattern if left blank or not set in the config */
- protected static String DEFAULT_DNPATTERN =
- "E=$attr.mail, CN=$attr.cn, O=$dn.o, C=$dn.c";
+ protected static String DEFAULT_DNPATTERN =
+ "E=$attr.mail, CN=$attr.cn, O=$dn.o, C=$dn.c";
/* Vector of extendedPluginInfo strings */
protected static Vector<String> mExtendedPluginInfo = null;
@@ -126,31 +128,31 @@ public abstract class DirBasedAuthentication
static {
mExtendedPluginInfo = new Vector<String>();
mExtendedPluginInfo.add(PROP_DNPATTERN + ";string;Template for cert" +
- " Subject Name. ($dn.xxx - get value from user's LDAP " +
- "DN. $attr.yyy - get value from LDAP attributes in " +
- "user's entry.) Default: " + DEFAULT_DNPATTERN);
+ " Subject Name. ($dn.xxx - get value from user's LDAP " +
+ "DN. $attr.yyy - get value from LDAP attributes in " +
+ "user's entry.) Default: " + DEFAULT_DNPATTERN);
mExtendedPluginInfo.add(PROP_LDAPSTRINGATTRS + ";string;" +
- "Comma-separated list of LDAP attributes to copy from " +
- "the user's LDAP entry into the AuthToken. e.g use " +
- "'mail' to copy user's email address for subjectAltName");
+ "Comma-separated list of LDAP attributes to copy from " +
+ "the user's LDAP entry into the AuthToken. e.g use " +
+ "'mail' to copy user's email address for subjectAltName");
mExtendedPluginInfo.add(PROP_LDAPBYTEATTRS + ";string;" +
- "Comma-separated list of binary LDAP attributes to copy" +
- " from the user's LDAP entry into the AuthToken");
+ "Comma-separated list of binary LDAP attributes to copy" +
+ " from the user's LDAP entry into the AuthToken");
mExtendedPluginInfo.add("ldap.ldapconn.host;string,required;" +
- "LDAP host to connect to");
+ "LDAP host to connect to");
mExtendedPluginInfo.add("ldap.ldapconn.port;number,required;" +
- "LDAP port number (use 389, or 636 if SSL)");
+ "LDAP port number (use 389, or 636 if SSL)");
mExtendedPluginInfo.add("ldap.ldapconn.secureConn;boolean;" +
- "Use SSL to connect to directory?");
+ "Use SSL to connect to directory?");
mExtendedPluginInfo.add("ldap.ldapconn.version;choice(3,2);" +
- "LDAP protocol version");
+ "LDAP protocol version");
mExtendedPluginInfo.add("ldap.basedn;string,required;Base DN to start searching " +
- "under. If your user's DN is 'uid=jsmith, o=company', you " +
- "might want to use 'o=company' here");
+ "under. If your user's DN is 'uid=jsmith, o=company', you " +
+ "might want to use 'o=company' here");
mExtendedPluginInfo.add("ldap.minConns;number;number of connections " +
- "to keep open to directory server. Default 5.");
+ "to keep open to directory server. Default 5.");
mExtendedPluginInfo.add("ldap.maxConns;number;when needed, connection " +
- "pool can grow to this many (multiplexed) connections. Default 1000.");
+ "pool can grow to this many (multiplexed) connections. Default 1000.");
}
/**
@@ -163,24 +165,26 @@ public abstract class DirBasedAuthentication
* Initializes the UidPwdDirBasedAuthentication auth manager.
*
* Takes the following configuration parameters: <br>
+ *
* <pre>
- * ldap.basedn - the ldap base dn.
- * ldap.ldapconn.host - the ldap host.
- * ldap.ldapconn.port - the ldap port
- * ldap.ldapconn.secureConn - whether port should be secure
- * ldap.minConns - minimum connections
- * ldap.maxConns - max connections
- * dnpattern - dn pattern.
+ * ldap.basedn - the ldap base dn.
+ * ldap.ldapconn.host - the ldap host.
+ * ldap.ldapconn.port - the ldap port
+ * ldap.ldapconn.secureConn - whether port should be secure
+ * ldap.minConns - minimum connections
+ * ldap.maxConns - max connections
+ * dnpattern - dn pattern.
* </pre>
* <p>
- * <i><b>dnpattern</b></i> is a string representing a subject name pattern
- * to formulate from the directory attributes and entry dn. If empty or
- * not set, the ldap entry DN will be used as the certificate subject name.
+ * <i><b>dnpattern</b></i> is a string representing a subject name pattern
+ * to formulate from the directory attributes and entry dn. If empty or not
+ * set, the ldap entry DN will be used as the certificate subject name.
* <p>
- * The syntax is
+ * The syntax is
+ *
* <pre>
* dnpattern = SubjectNameComp *[ "," SubjectNameComp ]
- *
+ *
* SubjectNameComponent = DnComp | EntryComp | ConstantComp
* DnComp = CertAttr "=" "$dn" "." DnAttr "." Num
* EntryComp = CertAttr "=" "$attr" "." EntryAttr "." Num
@@ -190,11 +194,12 @@ public abstract class DirBasedAuthentication
* CertAttr = a Component in the Certificate Subject Name
* (multiple AVA in one RDN not supported)
* Num = the nth value of tha attribute in the dn or entry.
- * Constant = Constant String, with any accepted ldap string value.
+ * Constant = Constant String, with any accepted ldap string value.
*
* </pre>
* <p>
* <b>Example:</b>
+ *
* <pre>
* dnpattern:
* E=$attr.mail.1, CN=$attr.cn, OU=$attr.ou.2, O=$dn.o, C=US
@@ -213,6 +218,7 @@ public abstract class DirBasedAuthentication
* </pre>
* <p>
* The subject name formulated in the cert will be : <br>
+ *
* <pre>
* E=joesmith@acme.com, CN=Joe Smith, OU=Human Resources, O=Acme.com, C=US
*
@@ -229,19 +235,20 @@ public abstract class DirBasedAuthentication
* @exception EBaseException If an error occurs during initialization.
*/
public void init(String name, String implName, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
init(name, implName, config, true);
}
public void init(String name, String implName, IConfigStore config, boolean needBaseDN)
- throws EBaseException {
+ throws EBaseException {
mName = name;
mImplName = implName;
mConfig = config;
/* initialize ldap server configuration */
mLdapConfig = mConfig.getSubStore(PROP_LDAP);
- if (needBaseDN) mBaseDN = mLdapConfig.getString(PROP_BASEDN);
+ if (needBaseDN)
+ mBaseDN = mLdapConfig.getString(PROP_BASEDN);
if (needBaseDN && ((mBaseDN == null) || (mBaseDN.length() == 0) || (mBaseDN.trim().equals(""))))
throw new EPropertyNotFound(CMS.getUserMessage("CMS_BASE_GET_PROPERTY_FAILED", "basedn"));
mConnFactory = CMS.getLdapAnonConnFactory();
@@ -250,7 +257,7 @@ public abstract class DirBasedAuthentication
/* initialize dn pattern */
String pattern = mConfig.getString(PROP_DNPATTERN, null);
- if (pattern == null || pattern.length() == 0)
+ if (pattern == null || pattern.length() == 0)
pattern = DEFAULT_DNPATTERN;
mPattern = new DNPattern(pattern);
String[] patternLdapAttrs = mPattern.getLdapAttrs();
@@ -261,15 +268,15 @@ public abstract class DirBasedAuthentication
if (ldapStringAttrs == null) {
mLdapStringAttrs = patternLdapAttrs;
} else {
- StringTokenizer pAttrs =
- new StringTokenizer(ldapStringAttrs, ",", false);
+ StringTokenizer pAttrs =
+ new StringTokenizer(ldapStringAttrs, ",", false);
int begin = 0;
if (patternLdapAttrs != null && patternLdapAttrs.length > 0) {
- mLdapStringAttrs = new String[
+ mLdapStringAttrs = new String[
patternLdapAttrs.length + pAttrs.countTokens()];
- System.arraycopy(patternLdapAttrs, 0,
- mLdapStringAttrs, 0, patternLdapAttrs.length);
+ System.arraycopy(patternLdapAttrs, 0,
+ mLdapStringAttrs, 0, patternLdapAttrs.length);
begin = patternLdapAttrs.length;
} else {
mLdapStringAttrs = new String[pAttrs.countTokens()];
@@ -285,11 +292,11 @@ public abstract class DirBasedAuthentication
if (ldapByteAttrs == null) {
mLdapByteAttrs = new String[0];
} else {
- StringTokenizer byteAttrs =
- new StringTokenizer(ldapByteAttrs, ",", false);
+ StringTokenizer byteAttrs =
+ new StringTokenizer(ldapByteAttrs, ",", false);
mLdapByteAttrs = new String[byteAttrs.countTokens()];
- for (int j = 0; j < mLdapByteAttrs.length; j++) {
+ for (int j = 0; j < mLdapByteAttrs.length; j++) {
mLdapByteAttrs[j] = ((String) byteAttrs.nextElement()).trim();
}
}
@@ -297,10 +304,10 @@ public abstract class DirBasedAuthentication
/* make the combined list */
mLdapAttrs =
new String[mLdapStringAttrs.length + mLdapByteAttrs.length];
- System.arraycopy(mLdapStringAttrs, 0, mLdapAttrs,
- 0, mLdapStringAttrs.length);
- System.arraycopy(mLdapByteAttrs, 0, mLdapAttrs,
- mLdapStringAttrs.length, mLdapByteAttrs.length);
+ System.arraycopy(mLdapStringAttrs, 0, mLdapAttrs,
+ 0, mLdapStringAttrs.length);
+ System.arraycopy(mLdapByteAttrs, 0, mLdapAttrs,
+ mLdapStringAttrs.length, mLdapByteAttrs.length);
log(ILogger.LL_INFO, CMS.getLogMessage("CMS_AUTH_INIT_DONE"));
}
@@ -320,21 +327,22 @@ public abstract class DirBasedAuthentication
}
/**
- * Authenticates user through LDAP by a set of credentials.
- * Resulting AuthToken a TOKEN_CERTINFO field of a X509CertInfo
+ * Authenticates user through LDAP by a set of credentials. Resulting
+ * AuthToken a TOKEN_CERTINFO field of a X509CertInfo
* <p>
+ *
* @param authCred Authentication credentials, CRED_UID and CRED_PWD.
* @return A AuthToken with a TOKEN_SUBJECT of X500name type.
- * @exception com.netscape.certsrv.authentication.EMissingCredential
- * If a required authentication credential is missing.
- * @exception com.netscape.certsrv.authentication.EInvalidCredentials
- * If credentials failed authentication.
- * @exception com.netscape.certsrv.base.EBaseException
- * If an internal error occurred.
+ * @exception com.netscape.certsrv.authentication.EMissingCredential If a
+ * required authentication credential is missing.
+ * @exception com.netscape.certsrv.authentication.EInvalidCredentials If
+ * credentials failed authentication.
+ * @exception com.netscape.certsrv.base.EBaseException If an internal error
+ * occurred.
* @see com.netscape.certsrv.authentication.AuthToken
*/
public IAuthToken authenticate(IAuthCredentials authCred)
- throws EMissingCredential, EInvalidCredentials, EBaseException {
+ throws EMissingCredential, EInvalidCredentials, EBaseException {
String userdn = null;
LDAPConnection conn = null;
AuthToken authToken = new AuthToken(this);
@@ -360,28 +368,28 @@ public abstract class DirBasedAuthentication
// set subject name.
try {
CertificateSubjectName subjectname = (CertificateSubjectName)
- certInfo.get(X509CertInfo.SUBJECT);
+ certInfo.get(X509CertInfo.SUBJECT);
if (subjectname != null)
- authToken.set(AuthToken.TOKEN_CERT_SUBJECT,
- subjectname.toString());
+ authToken.set(AuthToken.TOKEN_CERT_SUBJECT,
+ subjectname.toString());
} // error means it's not set.
catch (CertificateException e) {
} catch (IOException e) {
}
- // set validity if any
+ // set validity if any
try {
CertificateValidity validity = (CertificateValidity)
- certInfo.get(X509CertInfo.VALIDITY);
+ certInfo.get(X509CertInfo.VALIDITY);
if (validity != null) {
- // the gets throws IOException but only if attribute
- // not recognized. In these cases they are always.
- authToken.set(AuthToken.TOKEN_CERT_NOTBEFORE,
- (Date)validity.get(CertificateValidity.NOT_BEFORE));
- authToken.set(AuthToken.TOKEN_CERT_NOTAFTER,
- (Date)validity.get(CertificateValidity.NOT_AFTER));
+ // the gets throws IOException but only if attribute
+ // not recognized. In these cases they are always.
+ authToken.set(AuthToken.TOKEN_CERT_NOTBEFORE,
+ (Date) validity.get(CertificateValidity.NOT_BEFORE));
+ authToken.set(AuthToken.TOKEN_CERT_NOTAFTER,
+ (Date) validity.get(CertificateValidity.NOT_AFTER));
}
} // error means it's not set.
catch (CertificateException e) {
@@ -391,7 +399,7 @@ public abstract class DirBasedAuthentication
// set extensions if any.
try {
CertificateExtensions extensions = (CertificateExtensions)
- certInfo.get(X509CertInfo.EXTENSIONS);
+ certInfo.get(X509CertInfo.EXTENSIONS);
if (extensions != null)
authToken.set(AuthToken.TOKEN_CERT_EXTENSIONS, extensions);
@@ -401,7 +409,7 @@ public abstract class DirBasedAuthentication
}
} finally {
- if (conn != null)
+ if (conn != null)
mConnFactory.returnConn(conn);
}
@@ -410,15 +418,16 @@ public abstract class DirBasedAuthentication
/**
* get the list of required credentials.
+ *
* @return list of required credentials as strings.
*/
public abstract String[] getRequiredCreds();
/**
- * Returns a list of configuration parameter names.
- * The list is passed to the configuration console so instances of
- * this implementation can be configured through the console.
- *
+ * Returns a list of configuration parameter names. The list is passed to
+ * the configuration console so instances of this implementation can be
+ * configured through the console.
+ *
* @return String array of configuration parameter names.
*/
public abstract String[] getConfigParams();
@@ -440,6 +449,7 @@ public abstract class DirBasedAuthentication
/**
* Gets the configuration substore used by this authentication manager
+ *
* @return configuration store
*/
public IConfigStore getConfigStore() {
@@ -452,11 +462,11 @@ public abstract class DirBasedAuthentication
* @param authCreds The authentication credentials.
* @return The user's ldap entry dn.
* @exception EInvalidCredentials If the uid and password are not valid
- * @exception EBaseException If an internal error occurs.
+ * @exception EBaseException If an internal error occurs.
*/
protected abstract String authenticate(
- LDAPConnection conn, IAuthCredentials authCreds, AuthToken token)
- throws EBaseException;
+ LDAPConnection conn, IAuthCredentials authCreds, AuthToken token)
+ throws EBaseException;
/**
* Formulate the cert info.
@@ -465,24 +475,24 @@ public abstract class DirBasedAuthentication
* @param userdn The user's dn.
* @param certinfo A certinfo object to fill.
* @param token A authentication token to fill.
- * @exception EBaseException If an internal error occurs.
+ * @exception EBaseException If an internal error occurs.
*/
- protected void formCertInfo(LDAPConnection conn,
- String userdn,
- X509CertInfo certinfo,
- AuthToken token)
- throws EBaseException {
+ protected void formCertInfo(LDAPConnection conn,
+ String userdn,
+ X509CertInfo certinfo,
+ AuthToken token)
+ throws EBaseException {
String dn = null;
// get ldap attributes to retrieve.
String[] attrs = getLdapAttrs();
- // retrieve the attributes.
+ // retrieve the attributes.
try {
if (conn != null) {
LDAPEntry entry = null;
- LDAPSearchResults results =
- conn.search(userdn, LDAPv2.SCOPE_BASE, "objectclass=*",
- attrs, false);
+ LDAPSearchResults results =
+ conn.search(userdn, LDAPv2.SCOPE_BASE, "objectclass=*",
+ attrs, false);
if (!results.hasMoreElements()) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMS_AUTH_NO_ATTR_ERROR"));
@@ -490,11 +500,11 @@ public abstract class DirBasedAuthentication
}
entry = results.next();
- // formulate the subject dn
+ // formulate the subject dn
try {
dn = formSubjectName(entry);
} catch (EBaseException e) {
- //e.printStackTrace();
+ // e.printStackTrace();
throw e;
}
// Put selected values from the entry into the token
@@ -504,23 +514,23 @@ public abstract class DirBasedAuthentication
}
// add anything else in cert info such as validity, extensions
- // (nothing now)
+ // (nothing now)
// pack the dn into X500name and set subject name.
if (dn.length() == 0) {
- EBaseException ex =
- new EAuthException(CMS.getUserMessage("CMS_AUTHENTICATION_EMPTY_DN_FORMED", mName));
+ EBaseException ex =
+ new EAuthException(CMS.getUserMessage("CMS_AUTHENTICATION_EMPTY_DN_FORMED", mName));
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMS_AUTH_NO_DN_ERROR", ex.toString()));
throw ex;
}
X500Name subjectdn = new X500Name(dn);
- certinfo.set(X509CertInfo.SUBJECT,
- new CertificateSubjectName(subjectdn));
+ certinfo.set(X509CertInfo.SUBJECT,
+ new CertificateSubjectName(subjectdn));
} catch (LDAPException e) {
switch (e.getLDAPResultCode()) {
- case LDAPException.SERVER_DOWN:
+ case LDAPException.SERVER_DOWN:
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMS_AUTH_NO_AUTH_ATTR_ERROR"));
throw new ELdapException(
CMS.getUserMessage("CMS_LDAP_SERVER_UNAVAILABLE", conn.getHost(), "" + conn.getPort()));
@@ -534,7 +544,7 @@ public abstract class DirBasedAuthentication
log(ILogger.LL_FAILURE, CMS.getLogMessage("LDAP_ERROR", e.toString()));
throw new ELdapException(
CMS.getUserMessage("CMS_LDAP_OTHER_LDAP_EXCEPTION",
- e.errorCodeToString()));
+ e.errorCodeToString()));
}
} catch (IOException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMS_AUTH_CREATE_SUBJECT_ERROR", userdn, e.getMessage()));
@@ -546,26 +556,27 @@ public abstract class DirBasedAuthentication
}
/**
- * Copy values from the LDAPEntry into the AuthToken. The
- * list of values that should be store this way is given in
- * a the ldapAttributes configuration parameter.
+ * Copy values from the LDAPEntry into the AuthToken. The list of values
+ * that should be store this way is given in a the ldapAttributes
+ * configuration parameter.
*/
protected void setAuthTokenValues(LDAPEntry e, AuthToken tok) {
for (int i = 0; i < mLdapStringAttrs.length; i++)
setAuthTokenStringValue(mLdapStringAttrs[i], e, tok);
- for (int j = 0; j < mLdapByteAttrs.length; j++)
+ for (int j = 0; j < mLdapByteAttrs.length; j++)
setAuthTokenByteValue(mLdapByteAttrs[j], e, tok);
}
protected void setAuthTokenStringValue(
- String name, LDAPEntry entry, AuthToken tok) {
+ String name, LDAPEntry entry, AuthToken tok) {
LDAPAttribute values = entry.getAttribute(name);
- if (values == null) return;
+ if (values == null)
+ return;
Vector<String> v = new Vector<String>();
@SuppressWarnings("unchecked")
- Enumeration<String> e = values.getStringValues();
+ Enumeration<String> e = values.getStringValues();
while (e.hasMoreElements()) {
v.addElement(e.nextElement());
@@ -579,14 +590,15 @@ public abstract class DirBasedAuthentication
}
protected void setAuthTokenByteValue(
- String name, LDAPEntry entry, AuthToken tok) {
+ String name, LDAPEntry entry, AuthToken tok) {
LDAPAttribute values = entry.getAttribute(name);
- if (values == null) return;
+ if (values == null)
+ return;
Vector<byte[]> v = new Vector<byte[]>();
@SuppressWarnings("unchecked")
- Enumeration<byte[]> e = values.getByteValues();
+ Enumeration<byte[]> e = values.getByteValues();
while (e.hasMoreElements()) {
v.addElement(e.nextElement());
@@ -602,6 +614,7 @@ public abstract class DirBasedAuthentication
/**
* Return a list of LDAP attributes with String values to retrieve.
* Subclasses can override to return any set of attributes.
+ *
* @return Array of LDAP attributes to retrieve from the directory.
*/
protected String[] getLdapAttrs() {
@@ -611,6 +624,7 @@ public abstract class DirBasedAuthentication
/**
* Return a list of LDAP attributes with byte[] values to retrieve.
* Subclasses can override to return any set of attributes.
+ *
* @return Array of LDAP attributes to retrieve from the directory.
*/
protected String[] getLdapByteAttrs() {
@@ -618,22 +632,21 @@ public abstract class DirBasedAuthentication
}
/**
- * Formulate the subject name
+ * Formulate the subject name
+ *
* @param entry The LDAP entry
* @return The subject name string.
* @exception EBaseException If an internal error occurs.
*/
protected String formSubjectName(LDAPEntry entry)
- throws EAuthException {
- if (mPattern.mPatternString == null)
+ throws EAuthException {
+ if (mPattern.mPatternString == null)
return entry.getDN();
-
- /*
- if (mTestDNString != null) {
- mPattern.mTestDN = mTestDNString;
- //System.out.println("Set DNPattern.mTestDN to "+mPattern.mTestDN);
- }
- */
+
+ /*
+ * if (mTestDNString != null) { mPattern.mTestDN = mTestDNString;
+ * //System.out.println("Set DNPattern.mTestDN to "+mPattern.mTestDN); }
+ */
String dn = mPattern.formDN(entry);
@@ -643,6 +656,7 @@ public abstract class DirBasedAuthentication
/**
* Logs a message for this class in the system log file.
+ *
* @param level The log level.
* @param msg The message to log.
* @see com.netscape.certsrv.logging.ILogger
@@ -651,15 +665,14 @@ public abstract class DirBasedAuthentication
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_AUTHENTICATION,
- level, msg);
+ level, msg);
}
public String[] getExtendedPluginInfo(Locale locale) {
String[] s = Utils.getStringArrayFromVector(mExtendedPluginInfo);
return s;
-
+
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/authentication/FlatFileAuth.java b/pki/base/common/src/com/netscape/cms/authentication/FlatFileAuth.java
index ab59c499..2bfc29c2 100644
--- a/pki/base/common/src/com/netscape/cms/authentication/FlatFileAuth.java
+++ b/pki/base/common/src/com/netscape/cms/authentication/FlatFileAuth.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.authentication;
-
// ldap java sdk
import java.io.BufferedReader;
import java.io.BufferedWriter;
@@ -49,15 +48,14 @@ import com.netscape.certsrv.profile.IProfileAuthenticator;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This represents the authentication manager that authenticates
- * user against a file where id, and password are stored.
+ * This represents the authentication manager that authenticates user against a
+ * file where id, and password are stored.
*
* @version $Revision$, $Date$
*/
-public class FlatFileAuth
- implements IProfileAuthenticator, IExtendedPluginInfo {
+public class FlatFileAuth
+ implements IProfileAuthenticator, IExtendedPluginInfo {
/* configuration parameter keys */
protected static final String PROP_FILENAME = "fileName";
@@ -66,39 +64,39 @@ public class FlatFileAuth
protected static final String PROP_DEFERONFAILURE = "deferOnFailure";
protected String mFilename = "config/pwfile";
- protected long mFileLastRead = 0;
+ protected long mFileLastRead = 0;
protected String mKeyAttributes = "UID";
protected String mAuthAttrs = "PWD";
protected boolean mDeferOnFailure = true;
private static final String DATE_PATTERN = "yyyy-MM-dd-HH-mm-ss";
private static SimpleDateFormat mDateFormat = new SimpleDateFormat(DATE_PATTERN);
- protected static String[] mConfigParams =
- new String[] {
- PROP_FILENAME,
- PROP_KEYATTRIBUTES,
- PROP_AUTHATTRS,
- PROP_DEFERONFAILURE
+ protected static String[] mConfigParams =
+ new String[] {
+ PROP_FILENAME,
+ PROP_KEYATTRIBUTES,
+ PROP_AUTHATTRS,
+ PROP_DEFERONFAILURE
};
public String[] getExtendedPluginInfo(Locale locale) {
String s[] = {
PROP_FILENAME + ";string;Pathname of password file",
PROP_KEYATTRIBUTES + ";string;Comma-separated list of attributes" +
- " which together form a unique identifier for the user",
+ " which together form a unique identifier for the user",
PROP_AUTHATTRS + ";string;Comma-separated list of attributes" +
- " which are used for further authentication",
+ " which are used for further authentication",
PROP_DEFERONFAILURE + ";boolean;if user is not found, defer the " +
- "request to the queue for manual-authentication (true), or " +
- "simply rejected the request (false)"
+ "request to the queue for manual-authentication (true), or " +
+ "simply rejected the request (false)"
};
return s;
}
-
+
/** name of this authentication manager instance */
protected String mName = null;
-
+
protected String FFAUTH = "FlatFileAuth";
/** name of the authentication manager plugin */
@@ -109,30 +107,31 @@ public class FlatFileAuth
/** system logger */
protected ILogger mLogger = CMS.getLogger();
-
- /** This array is created as to include all the requested attributes
- *
+
+ /**
+ * This array is created as to include all the requested attributes
+ *
*/
String[] reqCreds = null;
String[] authAttrs = null;
String[] keyAttrs = null;
- /** Hashtable of entries from Auth File. Hash index is the
- * concatenation of the attributes from matchAttributes property
+ /**
+ * Hashtable of entries from Auth File. Hash index is the concatenation of
+ * the attributes from matchAttributes property
*/
protected Hashtable entries = null;
/**
- * Get the named property
- * If the property is not set, use s as the default, and create
- * a new value for the property in the config file.
+ * Get the named property If the property is not set, use s as the default,
+ * and create a new value for the property in the config file.
*
* @param propertyName Property name
* @param s The default value of the property
*/
protected String getPropertyS(String propertyName, String s)
- throws EBaseException {
+ throws EBaseException {
String p;
try {
@@ -149,15 +148,14 @@ public class FlatFileAuth
}
/**
- * Get the named property,
- * If the property is not set, use b as the default, and create
- * a new value for the property in the config file.
+ * Get the named property, If the property is not set, use b as the default,
+ * and create a new value for the property in the config file.
*
* @param propertyName Property name
* @param b The default value of the property
*/
protected boolean getPropertyB(String propertyName, boolean b)
- throws EBaseException {
+ throws EBaseException {
boolean p;
try {
@@ -170,7 +168,7 @@ public class FlatFileAuth
}
public void init(String name, String implName, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mName = name;
mImplName = implName;
mConfig = config;
@@ -219,6 +217,7 @@ public class FlatFileAuth
/**
* Log a message.
+ *
* @param level The logging level.
* @param msg The message to log.
*/
@@ -226,16 +225,16 @@ public class FlatFileAuth
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_AUTHENTICATION,
- level, msg);
+ level, msg);
}
-
+
void print(String s) {
CMS.debug("FlatFileAuth: " + s);
}
/**
- * Return a string array which is the union of all the string arrays
- * passed in. The strings are treated as case sensitive
+ * Return a string array which is the union of all the string arrays passed
+ * in. The strings are treated as case sensitive
*/
public String[] unionOfStrings(String[][] stringArrays) {
@@ -257,12 +256,11 @@ public class FlatFileAuth
s[i] = (String) e.nextElement();
}
return s;
-
+
}
-
+
/**
- * Split a comma-delimited String into an array of individual
- * Strings.
+ * Split a comma-delimited String into an array of individual Strings.
*/
private String[] splitOnComma(String s) {
print("Splitting String: " + s + " on commas");
@@ -282,8 +280,8 @@ public class FlatFileAuth
}
/**
- * Join an array of Strings into one string, with
- * the specified string between each string
+ * Join an array of Strings into one string, with the specified string
+ * between each string
*/
private String joinStringArray(String[] s, String sep) {
@@ -298,9 +296,9 @@ public class FlatFileAuth
return sb.toString();
}
- private synchronized void updateFile (String key) {
+ private synchronized void updateFile(String key) {
try {
- String name = writeFile (key);
+ String name = writeFile(key);
if (name != null) {
File orgFile = new File(mFilename);
long lastModified = orgFile.lastModified();
@@ -310,15 +308,15 @@ public class FlatFileAuth
} else {
mFileLastRead = newFile.lastModified();
}
- if (orgFile.renameTo(new File(name.substring(0, name.length()-1)))) {
+ if (orgFile.renameTo(new File(name.substring(0, name.length() - 1)))) {
if (!newFile.renameTo(new File(mFilename))) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("RENAME_FILE_ERROR", name, mFilename));
- File file = new File(name.substring(0, name.length()-1));
+ File file = new File(name.substring(0, name.length() - 1));
file.renameTo(new File(mFilename));
}
} else {
log(ILogger.LL_FAILURE, CMS.getLogMessage("RENAME_FILE_ERROR", mFilename,
- name.substring(0, name.length()-1)));
+ name.substring(0, name.length() - 1)));
}
}
} catch (Exception e) {
@@ -326,7 +324,7 @@ public class FlatFileAuth
}
}
- private String writeFile (String key) {
+ private String writeFile(String key) {
BufferedReader reader = null;
BufferedWriter writer = null;
String name = null;
@@ -334,9 +332,9 @@ public class FlatFileAuth
boolean done = false;
String line = null;
try {
- reader = new BufferedReader (new FileReader (mFilename));
- name = mFilename+"."+mDateFormat.format(new Date())+"~";
- writer = new BufferedWriter (new FileWriter(name));
+ reader = new BufferedReader(new FileReader(mFilename));
+ name = mFilename + "." + mDateFormat.format(new Date()) + "~";
+ writer = new BufferedWriter(new FileWriter(name));
if (reader != null && writer != null) {
while ((line = reader.readLine()) != null) {
if (commentOutNextLine) {
@@ -374,12 +372,15 @@ public class FlatFileAuth
long s2 = 0;
File f1 = new File(mFilename);
File f2 = new File(name);
- if (f1.exists()) s1 = f1.length();
- if (f2.exists()) s2 = f2.length();
+ if (f1.exists())
+ s1 = f1.length();
+ if (f2.exists())
+ s2 = f2.length();
if (s1 > 0 && s2 > 0 && s2 > s1) {
done = true;
} else {
- if (f2.exists()) f2.delete();
+ if (f2.exists())
+ f2.delete();
name = null;
}
}
@@ -390,27 +391,28 @@ public class FlatFileAuth
return name;
}
-
/**
- * Read a file with the following format: <p><pre>
+ * Read a file with the following format:
+ * <p>
+ *
+ * <pre>
* param1: valuea
* param2: valueb
* -blank-line-
* param1: valuec
* param2: valued
* </pre>
- *
+ *
* @param f The file to read
- * @param keys The parameters to concat together to form the hash
- * key
+ * @param keys The parameters to concat together to form the hash key
* @return a hashtable of hashtables.
*/
protected Hashtable readFile(File f, String[] keys)
- throws IOException {
+ throws IOException {
log(ILogger.LL_INFO, "Reading file: " + f.getName());
BufferedReader file = new BufferedReader(
new FileReader(f)
- );
+ );
String line;
Hashtable allusers = new Hashtable();
@@ -429,7 +431,7 @@ public class FlatFileAuth
entry = new Hashtable();
}
- if (colon == -1) { // no colon -> empty line signifies end of record
+ if (colon == -1) { // no colon -> empty line signifies end of record
if (!line.trim().equals("")) {
if (file != null) {
file.close();
@@ -458,8 +460,8 @@ public class FlatFileAuth
}
private void putEntry(Hashtable allUsers,
- Hashtable entry,
- String[] keys) {
+ Hashtable entry,
+ String[] keys) {
if (entry == null) {
return;
}
@@ -497,20 +499,20 @@ public class FlatFileAuth
}
/**
- * Compare attributes provided by the user with those in
- * in flat file.
- *
+ * Compare attributes provided by the user with those in in flat file.
+ *
*/
private IAuthToken doAuthentication(Hashtable user, IAuthCredentials authCred)
- throws EMissingCredential, EInvalidCredentials, EBaseException {
+ throws EMissingCredential, EInvalidCredentials, EBaseException {
AuthToken authToken = new AuthToken(this);
for (int i = 0; i < authAttrs.length; i++) {
String ffvalue = (String) user.get(authAttrs[i]);
String uservalue = (String) authCred.get(authAttrs[i]);
- // print("checking authentication token (" + authAttrs[i] + ": " + uservalue + " against ff value: " + ffvalue);
+ // print("checking authentication token (" + authAttrs[i] + ": " +
+ // uservalue + " against ff value: " + ffvalue);
if (!ffvalue.equals(uservalue)) {
throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
}
@@ -536,10 +538,10 @@ public class FlatFileAuth
/**
* Authenticate the request
- *
+ *
*/
public IAuthToken authenticate(IAuthCredentials authCred)
- throws EMissingCredential, EInvalidCredentials, EBaseException {
+ throws EMissingCredential, EInvalidCredentials, EBaseException {
IAuthToken authToken = null;
String keyForUser = "";
@@ -579,7 +581,7 @@ public class FlatFileAuth
}
}
- // if a dn was specified in the password file for this user,
+ // if a dn was specified in the password file for this user,
// replace the requested dn with the one in the pwfile
if (user != null) {
String dn = (String) user.get("dn");
@@ -601,21 +603,21 @@ public class FlatFileAuth
}
/**
- * Return a list of HTTP parameters which will be taken from the
- * request posting and placed into the AuthCredentials block
- *
- * Note that this method will not be called until after the
- * init() method is called
+ * Return a list of HTTP parameters which will be taken from the request
+ * posting and placed into the AuthCredentials block
+ *
+ * Note that this method will not be called until after the init() method is
+ * called
*/
public String[] getRequiredCreds() {
print("getRequiredCreds returning: " + joinStringArray(reqCreds, ","));
return reqCreds;
-
+
}
/**
- * Returns a list of configuration parameters, so the console
- * can prompt the user when configuring.
+ * Returns a list of configuration parameters, so the console can prompt the
+ * user when configuring.
*/
public String[] getConfigParams() {
return mConfigParams;
@@ -640,7 +642,7 @@ public class FlatFileAuth
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
}
/**
@@ -666,7 +668,7 @@ public class FlatFileAuth
}
public void populate(IAuthToken token, IRequest request)
- throws EProfileException {
+ throws EProfileException {
}
/**
diff --git a/pki/base/common/src/com/netscape/cms/authentication/HashAuthData.java b/pki/base/common/src/com/netscape/cms/authentication/HashAuthData.java
index 19bfab69..19e4f0e3 100644
--- a/pki/base/common/src/com/netscape/cms/authentication/HashAuthData.java
+++ b/pki/base/common/src/com/netscape/cms/authentication/HashAuthData.java
@@ -17,17 +17,16 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.authentication;
-
// java sdk imports.
import java.util.Hashtable;
import java.util.Vector;
-
/**
- * The structure stores the information of which machine is enabled for
- * the agent-initiated user enrollment, and whom agents enable this feature,
- * and the value of the timeout.
+ * The structure stores the information of which machine is enabled for the
+ * agent-initiated user enrollment, and whom agents enable this feature, and the
+ * value of the timeout.
* <P>
+ *
* @version $Revision$, $Date$
*/
public class HashAuthData extends Hashtable {
@@ -54,7 +53,7 @@ public class HashAuthData extends Hashtable {
Vector val = (Vector) get(hostname);
if (val == null) {
- val = new Vector();
+ val = new Vector();
put(hostname, val);
}
val.setElementAt(agentName, 0);
@@ -117,4 +116,3 @@ public class HashAuthData extends Hashtable {
val.setElementAt(Long.valueOf(lastLogin), 3);
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/authentication/HashAuthentication.java b/pki/base/common/src/com/netscape/cms/authentication/HashAuthentication.java
index 24a10e0a..4ef160ab 100644
--- a/pki/base/common/src/com/netscape/cms/authentication/HashAuthentication.java
+++ b/pki/base/common/src/com/netscape/cms/authentication/HashAuthentication.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.authentication;
-
// ldap java sdk
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@@ -40,11 +39,10 @@ import com.netscape.certsrv.base.IExtendedPluginInfo;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.cmsutil.util.Utils;
-
/**
* Hash uid/pwd directory based authentication manager
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class HashAuthentication implements IAuthManager, IExtendedPluginInfo {
@@ -71,18 +69,18 @@ public class HashAuthentication implements IAuthManager, IExtendedPluginInfo {
private ILogger mLogger = CMS.getLogger();
private static Vector mExtendedPluginInfo = null;
private HashAuthData mHosts = null;
-
+
static String[] mConfigParams =
- new String[] {};
+ new String[] {};
static {
mExtendedPluginInfo = new Vector();
mExtendedPluginInfo.add(IExtendedPluginInfo.HELP_TEXT +
- ";Authenticate the username and password provided " +
- "by the user against an LDAP directory. Works with the " +
- "Dir Based Enrollment HTML form");
+ ";Authenticate the username and password provided " +
+ "by the user against an LDAP directory. Works with the " +
+ "Dir Based Enrollment HTML form");
mExtendedPluginInfo.add(IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-authrules-uidpwddirauth");
+ ";configuration-authrules-uidpwddirauth");
};
/**
@@ -91,8 +89,8 @@ public class HashAuthentication implements IAuthManager, IExtendedPluginInfo {
public HashAuthentication() {
}
- public void init(String name, String implName, IConfigStore config)
- throws EBaseException {
+ public void init(String name, String implName, IConfigStore config)
+ throws EBaseException {
mName = name;
mImplName = implName;
mConfig = config;
@@ -124,7 +122,7 @@ public class HashAuthentication implements IAuthManager, IExtendedPluginInfo {
}
public void createEntry(String host, String dn, long timeout,
- String secret, long lastLogin) {
+ String secret, long lastLogin) {
Vector v = new Vector();
v.addElement(dn);
@@ -141,7 +139,7 @@ public class HashAuthentication implements IAuthManager, IExtendedPluginInfo {
public String getAgentName(String hostname) {
return mHosts.getAgentName(hostname);
}
-
+
public void setAgentName(String hostname, String agentName) {
mHosts.setAgentName(hostname, agentName);
}
@@ -184,7 +182,7 @@ public class HashAuthentication implements IAuthManager, IExtendedPluginInfo {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_AUTHENTICATION,
- level, msg);
+ level, msg);
}
public boolean validFingerprint(String host, String pageID, String uid, String fingerprint) {
@@ -192,7 +190,7 @@ public class HashAuthentication implements IAuthManager, IExtendedPluginInfo {
if (val.equals(fingerprint))
return true;
- return false;
+ return false;
}
public Enumeration getHosts() {
@@ -200,8 +198,8 @@ public class HashAuthentication implements IAuthManager, IExtendedPluginInfo {
}
public String hashFingerprint(String host, String pageID, String uid) {
- byte[] hash =
- mSHADigest.digest((SALT + pageID + getSecret(host) + uid).getBytes());
+ byte[] hash =
+ mSHADigest.digest((SALT + pageID + getSecret(host) + uid).getBytes());
String b64E = com.netscape.osutil.OSUtil.BtoA(hash);
return "{SHA}" + b64E;
@@ -216,18 +214,18 @@ public class HashAuthentication implements IAuthManager, IExtendedPluginInfo {
* @param authCreds The authentication credentials.
* @return The user's ldap entry dn.
* @exception EInvalidCredentials If the uid and password are not valid
- * @exception EBaseException If an internal error occurs.
+ * @exception EBaseException If an internal error occurs.
*/
public IAuthToken authenticate(IAuthCredentials authCreds)
- throws EBaseException {
+ throws EBaseException {
AuthToken token = new AuthToken(this);
String fingerprint = (String) authCreds.get(CRED_FINGERPRINT);
String pageID = (String) authCreds.get(CRED_PAGEID);
String uid = (String) authCreds.get(CRED_UID);
String host = (String) authCreds.get(CRED_HOST);
- if (fingerprint.equals("") ||
- !validFingerprint(host, pageID, uid, fingerprint)) {
+ if (fingerprint.equals("") ||
+ !validFingerprint(host, pageID, uid, fingerprint)) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMS_AUTH_INVALID_FINGER_PRINT"));
throw new EAuthException("Invalid Fingerprint");
}
@@ -240,6 +238,7 @@ public class HashAuthentication implements IAuthManager, IExtendedPluginInfo {
/**
* Returns array of required credentials for this authentication manager.
+ *
* @return Array of required credentials.
*/
public String[] getRequiredCreds() {
@@ -248,6 +247,7 @@ public class HashAuthentication implements IAuthManager, IExtendedPluginInfo {
/**
* Gets the configuration substore used by this authentication manager
+ *
* @return configuration store
*/
public IConfigStore getConfigStore() {
@@ -276,14 +276,13 @@ public class HashAuthentication implements IAuthManager, IExtendedPluginInfo {
}
/**
- * Returns a list of configuration parameter names.
- * The list is passed to the configuration console so instances of
- * this implementation can be configured through the console.
- *
+ * Returns a list of configuration parameter names. The list is passed to
+ * the configuration console so instances of this implementation can be
+ * configured through the console.
+ *
* @return String array of configuration parameter names.
*/
public String[] getConfigParams() {
return (mConfigParams);
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/authentication/PortalEnroll.java b/pki/base/common/src/com/netscape/cms/authentication/PortalEnroll.java
index 56c8739a..491151bb 100644
--- a/pki/base/common/src/com/netscape/cms/authentication/PortalEnroll.java
+++ b/pki/base/common/src/com/netscape/cms/authentication/PortalEnroll.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.authentication;
-
// ldap java sdk
import java.util.Enumeration;
import java.util.Locale;
@@ -49,26 +48,25 @@ import com.netscape.certsrv.ldap.ELdapException;
import com.netscape.certsrv.ldap.ILdapConnFactory;
import com.netscape.certsrv.logging.ILogger;
-
/**
* uid/pwd directory based authentication manager
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class PortalEnroll extends DirBasedAuthentication {
/* configuration parameter keys */
- protected static final String PROP_LDAPAUTH = "ldapauth";
- protected static final String PROP_AUTHTYPE = "authtype";
- protected static final String PROP_BINDDN = "bindDN";
- protected static final String PROP_BINDPW = "bindPW";
- protected static final String PROP_LDAPCONN = "ldapconn";
- protected static final String PROP_HOST = "host";
- protected static final String PROP_PORT = "port";
- protected static final String PROP_SECURECONN = "secureConn";
- protected static final String PROP_VERSION = "version";
- protected static final String PROP_OBJECTCLASS = "objectclass";
+ protected static final String PROP_LDAPAUTH = "ldapauth";
+ protected static final String PROP_AUTHTYPE = "authtype";
+ protected static final String PROP_BINDDN = "bindDN";
+ protected static final String PROP_BINDPW = "bindPW";
+ protected static final String PROP_LDAPCONN = "ldapconn";
+ protected static final String PROP_HOST = "host";
+ protected static final String PROP_PORT = "port";
+ protected static final String PROP_SECURECONN = "secureConn";
+ protected static final String PROP_VERSION = "version";
+ protected static final String PROP_OBJECTCLASS = "objectclass";
/* required credentials to authenticate. uid and pwd are strings. */
public static final String CRED_UID = "uid";
@@ -80,83 +78,84 @@ public class PortalEnroll extends DirBasedAuthentication {
private String mObjectClass = null;
private String mBindDN = null;
private String mBaseDN = null;
- private ILdapConnFactory mLdapFactory = null;
- private LDAPConnection mLdapConn = null;
+ private ILdapConnFactory mLdapFactory = null;
+ private LDAPConnection mLdapConn = null;
// contains all nested superiors' required attrs in the form of a
- // vector of "required" attributes in Enumeration
+ // vector of "required" attributes in Enumeration
Vector mRequiredAttrs = null;
-
+
// contains all nested superiors' optional attrs in the form of a
- // vector of "optional" attributes in Enumeration
+ // vector of "optional" attributes in Enumeration
Vector mOptionalAttrs = null;
// contains all the objclasses, including superiors and itself
Vector mObjClasses = null;
-
- /* Holds configuration parameters accepted by this implementation.
- * This list is passed to the configuration console so configuration
- * for instances of this implementation can be configured through the
- * console.
+
+ /*
+ * Holds configuration parameters accepted by this implementation. This list
+ * is passed to the configuration console so configuration for instances of
+ * this implementation can be configured through the console.
*/
- protected static String[] mConfigParams =
- new String[] {
- PROP_DNPATTERN,
- "ldap.ldapconn.host",
- "ldap.ldapconn.port",
- "ldap.ldapconn.secureConn",
- "ldap.ldapconn.version",
- "ldap.ldapauth.bindDN",
- "ldap.ldapauth.bindPWPrompt",
- "ldap.ldapauth.clientCertNickname",
- "ldap.ldapauth.authtype",
- "ldap.basedn",
- "ldap.objectclass",
- "ldap.minConns",
- "ldap.maxConns",
+ protected static String[] mConfigParams =
+ new String[] {
+ PROP_DNPATTERN,
+ "ldap.ldapconn.host",
+ "ldap.ldapconn.port",
+ "ldap.ldapconn.secureConn",
+ "ldap.ldapconn.version",
+ "ldap.ldapauth.bindDN",
+ "ldap.ldapauth.bindPWPrompt",
+ "ldap.ldapauth.clientCertNickname",
+ "ldap.ldapauth.authtype",
+ "ldap.basedn",
+ "ldap.objectclass",
+ "ldap.minConns",
+ "ldap.maxConns",
};
-
+
/**
* Default constructor, initialization must follow.
*/
- public PortalEnroll()
- throws EBaseException {
+ public PortalEnroll()
+ throws EBaseException {
super();
}
/**
* Initializes the PortalEnrollment auth manager.
* <p>
+ *
* @param name - The name for this authentication manager instance.
* @param implName - The name of the authentication manager plugin.
* @param config - The configuration store for this instance.
* @exception EBaseException If an error occurs during initialization.
*/
public void init(String name, String implName, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
super.init(name, implName, config);
-
+
/* Get Bind DN for directory server */
mConfig = mLdapConfig.getSubStore(PROP_LDAPAUTH);
mBindDN = mConfig.getString(PROP_BINDDN);
- if ( (mBindDN == null) || (mBindDN.length() == 0) || (mBindDN == ""))
+ if ((mBindDN == null) || (mBindDN.length() == 0) || (mBindDN == ""))
throw new EPropertyNotFound(CMS.getUserMessage("CMS_BASE_GET_PROPERTY_FAILED", "binddn"));
-
- /* Get Bind DN for directory server */
+
+ /* Get Bind DN for directory server */
mBaseDN = mLdapConfig.getString(PROP_BASEDN);
if ((mBaseDN == null) || (mBaseDN.length() == 0) || (mBaseDN == ""))
throw new EPropertyNotFound(CMS.getUserMessage("CMS_BASE_GET_PROPERTY_FAILED", "basedn"));
-
- /* Get Object clase name for enrollment */
+
+ /* Get Object clase name for enrollment */
mObjectClass = mLdapConfig.getString(PROP_OBJECTCLASS);
- if (mObjectClass == null || mObjectClass.length() == 0)
+ if (mObjectClass == null || mObjectClass.length() == 0)
throw new EPropertyNotFound(CMS.getUserMessage("CMS_BASE_GET_PROPERTY_FAILED", "objectclass"));
- /* Get connect parameter */
+ /* Get connect parameter */
mLdapFactory = CMS.getLdapBoundConnFactory();
mLdapFactory.init(mLdapConfig);
mLdapConn = mLdapFactory.getConn();
-
+
log(ILogger.LL_INFO, CMS.getLogMessage("CMS_AUTH_PORTAL_INIT"));
}
@@ -166,18 +165,18 @@ public class PortalEnroll extends DirBasedAuthentication {
* @param authCreds The authentication credentials.
* @return The user's ldap entry dn.
* @exception EInvalidCredentials If the uid and password are not valid
- * @exception EBaseException If an internal error occurs.
+ * @exception EBaseException If an internal error occurs.
*/
- protected String authenticate(LDAPConnection conn,
- IAuthCredentials authCreds,
- AuthToken token)
- throws EBaseException {
+ protected String authenticate(LDAPConnection conn,
+ IAuthCredentials authCreds,
+ AuthToken token)
+ throws EBaseException {
String uid = null;
String pwd = null;
String dn = null;
argblk = authCreds.getArgBlock();
-
+
// authenticate by binding to ldap server with password.
try {
// get the uid.
@@ -185,7 +184,7 @@ public class PortalEnroll extends DirBasedAuthentication {
if (uid == null) {
throw new EMissingCredential(CMS.getUserMessage("CMS_AUTHENTICATION_NULL_CREDENTIAL", CRED_UID));
}
-
+
// get the password.
pwd = (String) authCreds.get(CRED_PWD);
if (pwd == null) {
@@ -206,8 +205,8 @@ public class PortalEnroll extends DirBasedAuthentication {
throw new EAuthUserError(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_ATTRIBUTE_VALUE", "UID already exists."));
} else {
dn = regist(token, uid);
- if (dn == null)
- throw new EAuthUserError(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_ATTRIBUTE_VALUE","Could not add user " + uid + "."));
+ if (dn == null)
+ throw new EAuthUserError(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_ATTRIBUTE_VALUE", "Could not add user " + uid + "."));
}
// bind as user dn and pwd - authenticates user with pwd.
@@ -217,22 +216,21 @@ public class PortalEnroll extends DirBasedAuthentication {
token.set(CRED_UID, uid);
log(ILogger.LL_INFO, "portal authentication is done");
-
+
return dn;
} catch (ELdapException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("LDAP_ERROR", e.toString()));
throw e;
} catch (LDAPException e) {
switch (e.getLDAPResultCode()) {
- case LDAPException.NO_SUCH_OBJECT:
- case LDAPException.LDAP_PARTIAL_RESULTS:
+ case LDAPException.NO_SUCH_OBJECT:
+ case LDAPException.LDAP_PARTIAL_RESULTS:
log(ILogger.LL_SECURITY, CMS.getLogMessage("CMS_AUTH_ADD_USER_ERROR", conn.getHost(), Integer.toString(conn.getPort())));
- throw new
- EAuthInternalError(CMS.getUserMessage("CMS_AUTHENTICATION_INTERNAL_ERROR", "Check Configuration detail."));
+ throw new EAuthInternalError(CMS.getUserMessage("CMS_AUTHENTICATION_INTERNAL_ERROR", "Check Configuration detail."));
case LDAPException.INVALID_CREDENTIALS:
- log(ILogger.LL_SECURITY,
- CMS.getLogMessage("CMS_AUTH_BAD_PASSWORD", uid));
+ log(ILogger.LL_SECURITY,
+ CMS.getLogMessage("CMS_AUTH_BAD_PASSWORD", uid));
throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
case LDAPException.SERVER_DOWN:
@@ -240,24 +238,24 @@ public class PortalEnroll extends DirBasedAuthentication {
throw new ELdapException(
CMS.getUserMessage("CMS_LDAP_SERVER_UNAVAILABLE", conn.getHost(), "" + conn.getPort()));
- default:
+ default:
log(ILogger.LL_FAILURE, CMS.getLogMessage("LDAP_ERROR", e.getMessage()));
throw new ELdapException(
- CMS.getUserMessage("CMS_LDAP_OTHER_LDAP_EXCEPTION",
- e.errorCodeToString()));
+ CMS.getUserMessage("CMS_LDAP_OTHER_LDAP_EXCEPTION",
+ e.errorCodeToString()));
}
} catch (EBaseException e) {
if (e.getMessage().equalsIgnoreCase(CMS.getUserMessage("CMS_BASE_ATTRIBUTE_NOT_FOUND")) == true)
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMS_AUTH_MAKE_DN_ERROR", e.toString()));
throw e;
- }
+ }
}
/**
- * Returns a list of configuration parameter names.
- * The list is passed to the configuration console so instances of
- * this implementation can be configured through the console.
- *
+ * Returns a list of configuration parameter names. The list is passed to
+ * the configuration console so instances of this implementation can be
+ * configured through the console.
+ *
* @return String array of configuration parameter names.
*/
public String[] getConfigParams() {
@@ -267,43 +265,44 @@ public class PortalEnroll extends DirBasedAuthentication {
public String[] getExtendedPluginInfo(Locale locale) {
String[] s = {
PROP_DNPATTERN + ";string;Template for cert" +
- " Subject Name. ($dn.xxx - get value from user's LDAP " +
- "DN. $attr.yyy - get value from LDAP attributes in " +
- "user's entry.) Default: " + DEFAULT_DNPATTERN,
+ " Subject Name. ($dn.xxx - get value from user's LDAP " +
+ "DN. $attr.yyy - get value from LDAP attributes in " +
+ "user's entry.) Default: " + DEFAULT_DNPATTERN,
"ldap.ldapconn.host;string,required;" + "LDAP host to connect to",
"ldap.ldapconn.port;number,required;" + "LDAP port number (default 389, or 636 if SSL)",
"ldap.objectclass;string,required;SEE DOCUMENTATION for Object Class. "
- + "Default is inetOrgPerson.",
+ + "Default is inetOrgPerson.",
"ldap.ldapconn.secureConn;boolean;" + "Use SSL to connect to directory?",
"ldap.ldapconn.version;choice(3,2);" + "LDAP protocol version",
"ldap.ldapauth.bindDN;string,required;DN to bind as for Directory Manager. "
- + "For example 'CN=Directory Manager'",
+ + "For example 'CN=Directory Manager'",
"ldap.ldapauth.bindPWPrompt;password;Enter password used to bind as " +
- "the above user",
+ "the above user",
"ldap.ldapauth.authtype;choice(BasicAuth,SslClientAuth);"
- + "How to bind to the directory (for pin removal only)",
+ + "How to bind to the directory (for pin removal only)",
"ldap.ldapauth.clientCertNickname;string;If you want to use "
- + "SSL client auth to the directory, set the client "
- + "cert nickname here",
+ + "SSL client auth to the directory, set the client "
+ + "cert nickname here",
"ldap.basedn;string,required;Base DN to start searching " +
- "under. If your user's DN is 'uid=jsmith, o=company', you " +
- "might want to use 'o=company' here",
+ "under. If your user's DN is 'uid=jsmith, o=company', you " +
+ "might want to use 'o=company' here",
"ldap.minConns;number;number of connections " +
- "to keep open to directory server",
+ "to keep open to directory server",
"ldap.maxConns;number;when needed, connection " +
- "pool can grow to this many connections",
+ "pool can grow to this many connections",
IExtendedPluginInfo.HELP_TEXT +
- ";This authentication plugin checks to see if a user " +
- "exists in the directory. If not, then the user is created " +
- "with the requested password.",
+ ";This authentication plugin checks to see if a user " +
+ "exists in the directory. If not, then the user is created " +
+ "with the requested password.",
IExtendedPluginInfo.HELP_TOKEN + ";configuration-authrules-portalauth"
};
-
+
return s;
}
/**
* Returns array of required credentials for this authentication manager.
+ *
* @return Array of required credentials.
*/
public String[] getRequiredCreds() {
@@ -312,6 +311,7 @@ public class PortalEnroll extends DirBasedAuthentication {
/**
* adds a user to the directory.
+ *
* @return dn upon success and null upon failure.
* @param token authentication token
* @param uid the user's id.
@@ -321,7 +321,7 @@ public class PortalEnroll extends DirBasedAuthentication {
/* Specify the attributes of the entry */
Vector objectclass_values = null;
-
+
LDAPAttributeSet attrs = new LDAPAttributeSet();
LDAPAttribute attr = new LDAPAttribute("objectclass");
@@ -334,8 +334,10 @@ public class PortalEnroll extends DirBasedAuthentication {
try {
- /* Construct a new LDAPSchema object to hold
- the schema that you want to retrieve. */
+ /*
+ * Construct a new LDAPSchema object to hold the schema that you
+ * want to retrieve.
+ */
dirSchema = new LDAPSchema();
/* Get the schema from the Directory. Anonymous access okay. */
@@ -369,7 +371,7 @@ public class PortalEnroll extends DirBasedAuthentication {
} catch (EBaseException e) {
if (e.getMessage().equalsIgnoreCase(CMS.getUserMessage("CMS_BASE_ATTRIBUTE_NOT_FOUND")) == true)
continue;
- }
+ }
CMS.debug("PortalEnroll: " + attrname + " = " + attrval);
attrs.add(new LDAPAttribute(attrname, attrval));
@@ -386,17 +388,17 @@ public class PortalEnroll extends DirBasedAuthentication {
while (attrnames.hasMoreElements()) {
String attrname = (String) attrnames.nextElement();
String attrval = null;
-
+
CMS.debug("PortalEnroll: attrname is: " + attrname);
try {
attrval = (String) argblk.getValueAsString(attrname);
} catch (EBaseException e) {
if (e.getMessage().equalsIgnoreCase(CMS.getUserMessage("CMS_BASE_ATTRIBUTE_NOT_FOUND")) == true)
continue;
- }
+ }
CMS.debug("PortalEnroll: " + attrname + " = " + attrval);
if (attrval != null) {
- attrs.add(new LDAPAttribute(attrname, attrval));
+ attrs.add(new LDAPAttribute(attrname, attrval));
}
}
}
@@ -417,15 +419,15 @@ public class PortalEnroll extends DirBasedAuthentication {
}
log(ILogger.LL_INFO, CMS.getLogMessage("CMS_AUTH_REGISTRATION_DONE"));
-
+
return dn;
}
/*
- * get the superiors of "inetOrgPerson" so the "required
- * attributes", "optional qttributes", and "object classes" are complete;
- * should build up
- * mRequiredAttrs, mOptionalAttrs, and mObjClasses when returned
+ * get the superiors of "inetOrgPerson" so the "required
+ * attributes", "optional qttributes", and "object classes" are complete;
+ * should build up mRequiredAttrs, mOptionalAttrs, and mObjClasses when
+ * returned
*/
public void initLdapAttrs(LDAPSchema dirSchema, String oclass) {
CMS.debug("PortalEnroll: in initLdapAttrsAttrs");
@@ -461,4 +463,3 @@ public class PortalEnroll extends DirBasedAuthentication {
}
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/authentication/RDNPattern.java b/pki/base/common/src/com/netscape/cms/authentication/RDNPattern.java
index 1f21bc1d..cb028216 100644
--- a/pki/base/common/src/com/netscape/cms/authentication/RDNPattern.java
+++ b/pki/base/common/src/com/netscape/cms/authentication/RDNPattern.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.authentication;
-
import java.io.IOException;
import java.io.PushbackReader;
import java.io.StringReader;
@@ -29,24 +28,27 @@ import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.authentication.EAuthException;
import com.netscape.certsrv.base.EBaseException;
-
/**
- * class for parsing a DN pattern used to construct a certificate
- * subject name from ldap attributes and dn.<p>
+ * class for parsing a DN pattern used to construct a certificate subject name
+ * from ldap attributes and dn.
+ * <p>
*
- * dnpattern is a string representing a subject name pattern to formulate from
- * the directory attributes and entry dn. If empty or not set, the
- * ldap entry DN will be used as the certificate subject name. <p>
+ * dnpattern is a string representing a subject name pattern to formulate from
+ * the directory attributes and entry dn. If empty or not set, the ldap entry DN
+ * will be used as the certificate subject name.
+ * <p>
+ *
+ * The syntax is
*
- * The syntax is
* <pre>
- * dnPattern := rdnPattern *[ "," rdnPattern ]
- * rdnPattern := avaPattern *[ "+" avaPattern ]
+ * dnPattern := rdnPattern *[ "," rdnPattern ]
+ * rdnPattern := avaPattern *[ "+" avaPattern ]
* avaPattern := name "=" value |
- * name "=" "$attr" "." attrName [ "." attrNumber ] |
- * name "=" "$dn" "." attrName [ "." attrNumber ] |
- * "$dn" "." "$rdn" "." number
+ * name "=" "$attr" "." attrName [ "." attrNumber ] |
+ * name "=" "$dn" "." attrName [ "." attrNumber ] |
+ * "$dn" "." "$rdn" "." number
* </pre>
+ *
* <pre>
* Example1: <i>E=$attr.mail.1, CN=$attr.cn, OU=$dn.ou.2, O=$dn.o, C=US </i>
* Ldap entry: dn: UID=jjames, OU=IS, OU=people, O=acme.org
@@ -73,11 +75,12 @@ import com.netscape.certsrv.base.EBaseException;
* E = the first 'mail' ldap attribute value in user's entry. <br>
* CN = the (first) 'cn' ldap attribute value in the user's entry. <br>
* OU = the second 'ou' value in the user's entry DN. note multiple AVAs
- * in a RDN in this example. <br>
+ * in a RDN in this example. <br>
* O = the (first) 'o' value in the user's entry DN. <br>
* C = the string "US"
* <p>
* </pre>
+ *
* <pre>
* Example3: <i>CN=$attr.cn, $rdn.2, O=$dn.o, C=US</i>
* Ldap entry: dn: UID=jjames, OU=IS+OU=people, O=acme.org
@@ -102,15 +105,16 @@ import com.netscape.certsrv.base.EBaseException;
* <p>
* CN = the (first) 'cn' ldap attribute value in the user's entry. <br>
* OU = the second 'ou' value in the user's entry DN followed by the
- * first 'ou' value in the user's entry. note multiple AVAs
- * in a RDN in this example. <br>
+ * first 'ou' value in the user's entry. note multiple AVAs
+ * in a RDN in this example. <br>
* O = the (first) 'o' value in the user's entry DN. <br>
* C = the string "US"
* <p>
* </pre>
- * If an attribute or subject DN component does not exist the attribute
- * is skipped.
- *
+ *
+ * If an attribute or subject DN component does not exist the attribute is
+ * skipped.
+ *
* @version $Revision$, $Date$
*/
class RDNPattern {
@@ -126,15 +130,16 @@ class RDNPattern {
protected String mTestDN = null;
- /**
+ /**
* Construct a DN pattern by parsing a pattern string.
+ *
* @param pattenr the DN pattern
- * @exception EBaseException If parsing error occurs.
+ * @exception EBaseException If parsing error occurs.
*/
public RDNPattern(String pattern)
- throws EAuthException {
+ throws EAuthException {
if (pattern == null || pattern.equals("")) {
- // create an attribute list that is the dn.
+ // create an attribute list that is the dn.
mLdapAttrs = new String[] { "dn" };
} else {
mPatternString = pattern;
@@ -145,16 +150,16 @@ class RDNPattern {
}
/**
- * Construct a DN pattern from a input stream of pattern
+ * Construct a DN pattern from a input stream of pattern
*/
- public RDNPattern(PushbackReader in)
- throws EAuthException {
+ public RDNPattern(PushbackReader in)
+ throws EAuthException {
parse(in);
}
private void parse(PushbackReader in)
- throws EAuthException {
- //System.out.println("_________ begin rdn _________");
+ throws EAuthException {
+ // System.out.println("_________ begin rdn _________");
Vector avaPatterns = new Vector();
AVAPattern avaPattern = null;
int lastChar;
@@ -162,22 +167,21 @@ class RDNPattern {
do {
avaPattern = new AVAPattern(in);
avaPatterns.addElement(avaPattern);
- //System.out.println("added AVAPattern"+
- //" mType "+avaPattern.mType+
- //" mAttr "+avaPattern.mAttr+
- //" mValue "+avaPattern.mValue+
- //" mElement "+avaPattern.mElement);
- try {
- lastChar = in.read();
+ // System.out.println("added AVAPattern"+
+ // " mType "+avaPattern.mType+
+ // " mAttr "+avaPattern.mAttr+
+ // " mValue "+avaPattern.mValue+
+ // " mElement "+avaPattern.mElement);
+ try {
+ lastChar = in.read();
} catch (IOException e) {
throw new EAuthException(CMS.getUserMessage("CMS_AUTHENTICATION_INTERNAL_ERROR", e.toString()));
}
- }
- while (lastChar == '+');
+ } while (lastChar == '+');
if (lastChar != -1) {
try {
- in.unread(lastChar); // pushback last ,
+ in.unread(lastChar); // pushback last ,
} catch (IOException e) {
throw new EAuthException(CMS.getUserMessage("CMS_AUTHENTICATION_INTERNAL_ERROR", e.toString()));
}
@@ -191,7 +195,7 @@ class RDNPattern {
for (int i = 0; i < mAVAPatterns.length; i++) {
String avaAttr = mAVAPatterns[i].getLdapAttr();
- if (avaAttr == null || avaAttr.length() == 0)
+ if (avaAttr == null || avaAttr.length() == 0)
continue;
ldapAttrs.addElement(avaAttr);
}
@@ -201,15 +205,16 @@ class RDNPattern {
/**
* Form a Ldap v3 DN string from results of a ldap search.
+ *
* @param entry LDAPentry from a ldap search
- * @return Ldap v3 DN string to use for a subject name.
+ * @return Ldap v3 DN string to use for a subject name.
*/
public String formRDN(LDAPEntry entry)
- throws EAuthException {
+ throws EAuthException {
StringBuffer formedRDN = new StringBuffer();
for (int i = 0; i < mAVAPatterns.length; i++) {
- if (mTestDN != null)
+ if (mTestDN != null)
mAVAPatterns[i].mTestDN = mTestDN;
String ava = mAVAPatterns[i].formAVA(entry);
@@ -219,7 +224,7 @@ class RDNPattern {
formedRDN.append(ava);
}
}
- //System.out.println("formed RDN "+formedRDN.toString());
+ // System.out.println("formed RDN "+formedRDN.toString());
return formedRDN.toString();
}
diff --git a/pki/base/common/src/com/netscape/cms/authentication/SSLclientCertAuthentication.java b/pki/base/common/src/com/netscape/cms/authentication/SSLclientCertAuthentication.java
index e73a112c..50bdeab0 100644
--- a/pki/base/common/src/com/netscape/cms/authentication/SSLclientCertAuthentication.java
+++ b/pki/base/common/src/com/netscape/cms/authentication/SSLclientCertAuthentication.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.authentication;
-
import java.security.Principal;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
@@ -47,15 +46,14 @@ import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.usrgrp.Certificates;
-
/**
- * Certificate server SSL client authentication.
- *
+ * Certificate server SSL client authentication.
+ *
* @author Christina Fu
- * <P>
- *
+ * <P>
+ *
*/
-public class SSLclientCertAuthentication implements IAuthManager,
+public class SSLclientCertAuthentication implements IAuthManager,
IProfileAuthenticator {
/* result auth token attributes */
@@ -86,19 +84,20 @@ public class SSLclientCertAuthentication implements IAuthManager,
/**
* initializes the SSLClientCertAuthentication auth manager
* <p>
- * called by AuthSubsystem init() method, when initializing
- * all available authentication managers.
+ * called by AuthSubsystem init() method, when initializing all available
+ * authentication managers.
+ *
* @param name The name of this authentication manager instance.
* @param implName The name of the authentication manager plugin.
* @param config The configuration store for this authentication manager.
*/
public void init(String name, String implName, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mName = name;
mImplName = implName;
mConfig = config;
}
-
+
/**
* Gets the name of this authentication manager.
*/
@@ -112,7 +111,7 @@ public class SSLclientCertAuthentication implements IAuthManager,
public String getImplName() {
return mImplName;
}
-
+
public boolean isSSLClientRequired() {
return true;
}
@@ -120,29 +119,29 @@ public class SSLclientCertAuthentication implements IAuthManager,
/**
* authenticates user by certificate
* <p>
- * called by other subsystems or their servlets to authenticate
- * users
- * @param authCred - authentication credential that contains
- * an usrgrp.Certificates of the user (agent)
+ * called by other subsystems or their servlets to authenticate users
+ *
+ * @param authCred - authentication credential that contains an
+ * usrgrp.Certificates of the user (agent)
* @return the authentication token that contains the following
- *
+ *
* @exception EMissingCredential If a required credential for this
- * authentication manager is missing.
+ * authentication manager is missing.
* @exception EInvalidCredentials If credentials cannot be authenticated.
* @exception EBaseException If an internal error occurred.
* @see com.netscape.certsrv.authentication.AuthToken
* @see com.netscape.certsrv.usrgrp.Certificates
*/
public IAuthToken authenticate(IAuthCredentials authCred)
- throws EMissingCredential, EInvalidCredentials, EBaseException {
-
+ throws EMissingCredential, EInvalidCredentials, EBaseException {
+
CMS.debug("SSLclientCertAuthentication: start");
- CMS.debug("authenticator instance name is "+getName());
+ CMS.debug("authenticator instance name is " + getName());
// force SSL handshake
SessionContext context = SessionContext.getExistingContext();
ISSLClientCertProvider provider = (ISSLClientCertProvider)
- context.get("sslClientCertProvider");
+ context.get("sslClientCertProvider");
if (provider == null) {
CMS.debug("SSLclientCertAuthentication: No SSL Client Cert Provider Found");
@@ -173,7 +172,7 @@ public class SSLclientCertAuthentication implements IAuthManager,
// find out which one is the leaf cert
clientCert = ci[i];
- byte [] extBytes = clientCert.getExtensionValue("2.5.29.19");
+ byte[] extBytes = clientCert.getExtensionValue("2.5.29.19");
// try to see if this is a leaf cert
// look for BasicConstraint extension
if (extBytes == null) {
@@ -186,24 +185,24 @@ public class SSLclientCertAuthentication implements IAuthManager,
// so it's not likely to be a leaf cert,
// however, check the isCA field regardless
try {
- BasicConstraintsExtension bce =
- new BasicConstraintsExtension(true, extBytes);
- if (bce != null) {
- if (!(Boolean)bce.get("is_ca")) {
- CMS.debug("SSLclientCertAuthentication: authenticate: found CA cert in chain");
- break;
- } // else found a ca cert, continue
- }
- } catch (Exception e) {
- CMS.debug("SSLclientCertAuthentication: authenticate: exception:"+
+ BasicConstraintsExtension bce =
+ new BasicConstraintsExtension(true, extBytes);
+ if (bce != null) {
+ if (!(Boolean) bce.get("is_ca")) {
+ CMS.debug("SSLclientCertAuthentication: authenticate: found CA cert in chain");
+ break;
+ } // else found a ca cert, continue
+ }
+ } catch (Exception e) {
+ CMS.debug("SSLclientCertAuthentication: authenticate: exception:" +
e.toString());
- throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
- }
- }
+ throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
+ }
+ }
}
if (clientCert == null) {
- CMS.debug("SSLclientCertAuthentication: authenticate: client cert not found");
- throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
+ CMS.debug("SSLclientCertAuthentication: authenticate: client cert not found");
+ throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
}
} catch (CertificateException e) {
CMS.debug(e.toString());
@@ -213,15 +212,15 @@ public class SSLclientCertAuthentication implements IAuthManager,
// check if certificate(s) is revoked
boolean checkRevocation = true;
try {
- checkRevocation = mConfig.getBoolean("checkRevocation", true);
+ checkRevocation = mConfig.getBoolean("checkRevocation", true);
} catch (EBaseException e) {
- // do nothing; default to true
+ // do nothing; default to true
}
if (checkRevocation) {
- if (CMS.isRevoked(ci)) {
- CMS.debug("SSLclientCertAuthentication: certificate revoked");
- throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
- }
+ if (CMS.isRevoked(ci)) {
+ CMS.debug("SSLclientCertAuthentication: certificate revoked");
+ throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
+ }
}
Certificates certs = new Certificates(ci);
Principal p_dn = clientCert.getSubjectDN();
@@ -232,13 +231,13 @@ public class SSLclientCertAuthentication implements IAuthManager,
authToken.set(TOKEN_UID, uid);
authToken.set(TOKEN_USERID, uid);
}
-/*
- authToken.set(TOKEN_USER_DN, user.getUserDN());
- authToken.set(TOKEN_USERID, user.getUserID());
- authToken.set(TOKEN_UID, user.getUserID());
- authToken.set(TOKEN_GROUP, groupname);
-*/
- authToken.set(CRED_CERT, certs);
+ /*
+ * authToken.set(TOKEN_USER_DN, user.getUserDN());
+ * authToken.set(TOKEN_USERID, user.getUserID());
+ * authToken.set(TOKEN_UID, user.getUserID());
+ * authToken.set(TOKEN_GROUP, groupname);
+ */
+ authToken.set(CRED_CERT, certs);
CMS.debug("SSLclientCertAuthentication: authenticated ");
@@ -257,7 +256,7 @@ public class SSLclientCertAuthentication implements IAuthManager,
String n = t.substring(0, i);
if (n.equalsIgnoreCase("uid")) {
String v = t.substring(i + 1);
- CMS.debug("SSLclientCertAuthentication: getUidFromDN(): uid found:"+v);
+ CMS.debug("SSLclientCertAuthentication: getUidFromDN(): uid found:" + v);
return v;
} else {
continue;
@@ -267,11 +266,12 @@ public class SSLclientCertAuthentication implements IAuthManager,
}
/**
- * get the list of authentication credential attribute names
- * required by this authentication manager. Generally used by
- * the servlets that handle agent operations to authenticate its
- * users. It calls this method to know which are the
- * required credentials from the user (e.g. Javascript form data)
+ * get the list of authentication credential attribute names required by
+ * this authentication manager. Generally used by the servlets that handle
+ * agent operations to authenticate its users. It calls this method to know
+ * which are the required credentials from the user (e.g. Javascript form
+ * data)
+ *
* @return attribute names in Vector
*/
public String[] getRequiredCreds() {
@@ -279,15 +279,15 @@ public class SSLclientCertAuthentication implements IAuthManager,
}
/**
- * get the list of configuration parameter names
- * required by this authentication manager. Generally used by
- * the Certificate Server Console to display the table for
- * configuration purposes. CertUserDBAuthentication is currently not
- * exposed in this case, so this method is not to be used.
- * @return configuration parameter names in Hashtable of Vectors
- * where each hashtable entry's key is the substore name, value is a
- * Vector of parameter names. If no substore, the parameter name
- * is the Hashtable key itself, with value same as key.
+ * get the list of configuration parameter names required by this
+ * authentication manager. Generally used by the Certificate Server Console
+ * to display the table for configuration purposes. CertUserDBAuthentication
+ * is currently not exposed in this case, so this method is not to be used.
+ *
+ * @return configuration parameter names in Hashtable of Vectors where each
+ * hashtable entry's key is the substore name, value is a Vector of
+ * parameter names. If no substore, the parameter name is the
+ * Hashtable key itself, with value same as key.
*/
public String[] getConfigParams() {
return (mConfigParams);
@@ -300,8 +300,8 @@ public class SSLclientCertAuthentication implements IAuthManager,
}
/**
- * gets the configuretion substore used by this authentication
- * manager
+ * gets the configuretion substore used by this authentication manager
+ *
* @return configuration store
*/
public IConfigStore getConfigStore() {
@@ -311,7 +311,7 @@ public class SSLclientCertAuthentication implements IAuthManager,
// Profile-related methods
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
}
/**
@@ -340,15 +340,14 @@ public class SSLclientCertAuthentication implements IAuthManager,
}
/**
- * Retrieves the descriptor of the given value
- * parameter by name.
+ * Retrieves the descriptor of the given value parameter by name.
*/
public IDescriptor getValueDescriptor(Locale locale, String name) {
return null;
}
public void populate(IAuthToken token, IRequest request)
- throws EProfileException {
+ throws EProfileException {
request.setExtData(IProfileAuthenticator.AUTHENTICATED_NAME,
token.getInString(TOKEN_USERDN));
request.setExtData(IProfileAuthenticator.AUTHENTICATED_NAME,
diff --git a/pki/base/common/src/com/netscape/cms/authentication/SharedSecret.java b/pki/base/common/src/com/netscape/cms/authentication/SharedSecret.java
index 8b0a7b9b..7a0784c5 100644
--- a/pki/base/common/src/com/netscape/cms/authentication/SharedSecret.java
+++ b/pki/base/common/src/com/netscape/cms/authentication/SharedSecret.java
@@ -26,7 +26,7 @@ import com.netscape.certsrv.authentication.ISharedToken;
public class SharedSecret implements ISharedToken {
public SharedSecret() {
- }
+ }
public String getSharedToken(PKIData cmcdata) {
return "testing";
diff --git a/pki/base/common/src/com/netscape/cms/authentication/TokenAuthentication.java b/pki/base/common/src/com/netscape/cms/authentication/TokenAuthentication.java
index bb393767..001415be 100644
--- a/pki/base/common/src/com/netscape/cms/authentication/TokenAuthentication.java
+++ b/pki/base/common/src/com/netscape/cms/authentication/TokenAuthentication.java
@@ -46,13 +46,12 @@ import com.netscape.cmsutil.http.JssSSLSocketFactory;
import com.netscape.cmsutil.xml.XMLObject;
/**
- * Token authentication.
- * Checked if the given token is valid.
+ * Token authentication. Checked if the given token is valid.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
-public class TokenAuthentication implements IAuthManager,
+public class TokenAuthentication implements IAuthManager,
IProfileAuthenticator {
/* result auth token attributes */
@@ -79,21 +78,22 @@ public class TokenAuthentication implements IAuthManager,
/**
* initializes the TokenAuthentication auth manager
* <p>
- * called by AuthSubsystem init() method, when initializing
- * all available authentication managers.
+ * called by AuthSubsystem init() method, when initializing all available
+ * authentication managers.
+ *
* @param name The name of this authentication manager instance.
* @param implName The name of the authentication manager plugin.
* @param config The configuration store for this authentication manager.
*/
public void init(String name, String implName, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mName = name;
mImplName = implName;
mConfig = config;
mUGSub = (IUGSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_UG);
}
-
+
/**
* Gets the name of this authentication manager.
*/
@@ -107,7 +107,7 @@ public class TokenAuthentication implements IAuthManager,
public String getImplName() {
return mImplName;
}
-
+
public boolean isSSLClientRequired() {
return false;
}
@@ -115,21 +115,22 @@ public class TokenAuthentication implements IAuthManager,
/**
* authenticates user(agent) by certificate
* <p>
- * called by other subsystems or their servlets to authenticate
- * users (agents)
- * @param authCred - authentication credential that contains
- * an usrgrp.Certificates of the user (agent)
+ * called by other subsystems or their servlets to authenticate users
+ * (agents)
+ *
+ * @param authCred - authentication credential that contains an
+ * usrgrp.Certificates of the user (agent)
* @return the authentication token that contains the following
- * @exception EMissingCredential If a required credential for this
- * authentication manager is missing.
+ * @exception EMissingCredential If a required credential for this
+ * authentication manager is missing.
* @exception EInvalidCredentials If credentials cannot be authenticated.
* @exception EBaseException If an internal error occurred.
* @see com.netscape.certsrv.authentication.AuthToken
* @see com.netscape.certsrv.usrgrp.Certificates
*/
public IAuthToken authenticate(IAuthCredentials authCred)
- throws EMissingCredential, EInvalidCredentials, EBaseException {
-
+ throws EMissingCredential, EInvalidCredentials, EBaseException {
+
CMS.debug("TokenAuthentication: start");
// force SSL handshake
@@ -141,8 +142,8 @@ public class TokenAuthentication implements IAuthManager,
// get group name from configuration file
IConfigStore sconfig = CMS.getConfigStore();
- String sessionId = (String)authCred.get(CRED_SESSION_ID);
- String givenHost = (String)authCred.get("clientHost");
+ String sessionId = (String) authCred.get(CRED_SESSION_ID);
+ String givenHost = (String) authCred.get("clientHost");
String auth_host = sconfig.getString("securitydomain.host");
int auth_port = sconfig.getInteger("securitydomain.httpseeport");
@@ -151,7 +152,7 @@ public class TokenAuthentication implements IAuthManager,
try {
JssSSLSocketFactory factory = new JssSSLSocketFactory();
httpclient = new HttpClient(factory);
- String content = CRED_SESSION_ID+"="+sessionId+"&hostname="+givenHost;
+ String content = CRED_SESSION_ID + "=" + sessionId + "&hostname=" + givenHost;
CMS.debug("TokenAuthentication: content=" + content);
httpclient.connect(auth_host, auth_port);
HttpRequest httprequest = new HttpRequest();
@@ -165,8 +166,8 @@ public class TokenAuthentication implements IAuthManager,
HttpResponse httpresponse = httpclient.send(httprequest);
c = httpresponse.getContent();
- } catch (Exception e) {
- CMS.debug("TokenAuthentication authenticate Exception="+e.toString());
+ } catch (Exception e) {
+ CMS.debug("TokenAuthentication authenticate Exception=" + e.toString());
}
if (c != null) {
@@ -177,9 +178,9 @@ public class TokenAuthentication implements IAuthManager,
try {
parser = new XMLObject(bis);
} catch (Exception e) {
- CMS.debug( "TokenAuthentication::authenticate() - "
- + "Exception="+e.toString() );
- throw new EBaseException( e.toString() );
+ CMS.debug("TokenAuthentication::authenticate() - "
+ + "Exception=" + e.toString());
+ throw new EBaseException(e.toString());
}
String status = parser.getValue("Status");
@@ -195,13 +196,13 @@ public class TokenAuthentication implements IAuthManager,
authToken.set(TOKEN_UID, uid);
authToken.set(TOKEN_GID, gid);
- if(context != null) {
+ if (context != null) {
CMS.debug("SessionContext.USER_ID " + uid + " SessionContext.GROUP_ID " + gid);
- context.put(SessionContext.USER_ID, uid );
- context.put(SessionContext.GROUP_ID, gid );
+ context.put(SessionContext.USER_ID, uid);
+ context.put(SessionContext.GROUP_ID, gid);
}
- CMS.debug("TokenAuthentication: authenticated uid="+uid+", gid="+gid);
+ CMS.debug("TokenAuthentication: authenticated uid=" + uid + ", gid=" + gid);
} catch (EBaseException e) {
throw e;
} catch (Exception e) {
@@ -212,11 +213,12 @@ public class TokenAuthentication implements IAuthManager,
}
/**
- * get the list of authentication credential attribute names
- * required by this authentication manager. Generally used by
- * the servlets that handle agent operations to authenticate its
- * users. It calls this method to know which are the
- * required credentials from the user (e.g. Javascript form data)
+ * get the list of authentication credential attribute names required by
+ * this authentication manager. Generally used by the servlets that handle
+ * agent operations to authenticate its users. It calls this method to know
+ * which are the required credentials from the user (e.g. Javascript form
+ * data)
+ *
* @return attribute names in Vector
*/
public String[] getRequiredCreds() {
@@ -224,15 +226,15 @@ public class TokenAuthentication implements IAuthManager,
}
/**
- * get the list of configuration parameter names
- * required by this authentication manager. Generally used by
- * the Certificate Server Console to display the table for
- * configuration purposes. CertUserDBAuthentication is currently not
- * exposed in this case, so this method is not to be used.
- * @return configuration parameter names in Hashtable of Vectors
- * where each hashtable entry's key is the substore name, value is a
- * Vector of parameter names. If no substore, the parameter name
- * is the Hashtable key itself, with value same as key.
+ * get the list of configuration parameter names required by this
+ * authentication manager. Generally used by the Certificate Server Console
+ * to display the table for configuration purposes. CertUserDBAuthentication
+ * is currently not exposed in this case, so this method is not to be used.
+ *
+ * @return configuration parameter names in Hashtable of Vectors where each
+ * hashtable entry's key is the substore name, value is a Vector of
+ * parameter names. If no substore, the parameter name is the
+ * Hashtable key itself, with value same as key.
*/
public String[] getConfigParams() {
return (mConfigParams);
@@ -245,8 +247,8 @@ public class TokenAuthentication implements IAuthManager,
}
/**
- * gets the configuretion substore used by this authentication
- * manager
+ * gets the configuretion substore used by this authentication manager
+ *
* @return configuration store
*/
public IConfigStore getConfigStore() {
@@ -256,7 +258,7 @@ public class TokenAuthentication implements IAuthManager,
// Profile-related methods
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
}
/**
@@ -288,14 +290,13 @@ public class TokenAuthentication implements IAuthManager,
}
/**
- * Retrieves the descriptor of the given value
- * parameter by name.
+ * Retrieves the descriptor of the given value parameter by name.
*/
public IDescriptor getValueDescriptor(Locale locale, String name) {
return null;
}
public void populate(IAuthToken token, IRequest request)
- throws EProfileException {
+ throws EProfileException {
}
}
diff --git a/pki/base/common/src/com/netscape/cms/authentication/UdnPwdDirAuthentication.java b/pki/base/common/src/com/netscape/cms/authentication/UdnPwdDirAuthentication.java
index 565bca1a..3a20a994 100644
--- a/pki/base/common/src/com/netscape/cms/authentication/UdnPwdDirAuthentication.java
+++ b/pki/base/common/src/com/netscape/cms/authentication/UdnPwdDirAuthentication.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.authentication;
-
// ldap java sdk
import netscape.ldap.LDAPConnection;
import netscape.ldap.LDAPException;
@@ -33,11 +32,10 @@ import com.netscape.certsrv.base.IExtendedPluginInfo;
import com.netscape.certsrv.ldap.ELdapException;
import com.netscape.certsrv.logging.ILogger;
-
/**
* udn/pwd directory based authentication manager
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class UdnPwdDirAuthentication extends DirBasedAuthentication {
@@ -47,30 +45,30 @@ public class UdnPwdDirAuthentication extends DirBasedAuthentication {
public static final String CRED_PWD = "pwd";
protected static String[] mRequiredCreds = { CRED_UDN, CRED_PWD };
- /* Holds configuration parameters accepted by this implementation.
- * This list is passed to the configuration console so configuration
- * for instances of this implementation can be configured through the
- * console.
+ /*
+ * Holds configuration parameters accepted by this implementation. This list
+ * is passed to the configuration console so configuration for instances of
+ * this implementation can be configured through the console.
*/
- protected static String[] mConfigParams =
- new String[] { PROP_DNPATTERN,
- PROP_LDAPSTRINGATTRS,
- PROP_LDAPBYTEATTRS,
- "ldap.ldapconn.host",
- "ldap.ldapconn.port",
- "ldap.ldapconn.secureConn",
- "ldap.ldapconn.version",
- "ldap.minConns",
- "ldap.maxConns",
+ protected static String[] mConfigParams =
+ new String[] { PROP_DNPATTERN,
+ PROP_LDAPSTRINGATTRS,
+ PROP_LDAPBYTEATTRS,
+ "ldap.ldapconn.host",
+ "ldap.ldapconn.port",
+ "ldap.ldapconn.secureConn",
+ "ldap.ldapconn.version",
+ "ldap.minConns",
+ "ldap.maxConns",
};
static {
mExtendedPluginInfo.add(IExtendedPluginInfo.HELP_TEXT +
- ";Authenticate the user distinguished name and password provided " +
- "by the user against an LDAP directory. Works with the " +
- "Dir Based Enrollment HTML form");
+ ";Authenticate the user distinguished name and password provided " +
+ "by the user against an LDAP directory. Works with the " +
+ "Dir Based Enrollment HTML form");
mExtendedPluginInfo.add(IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-authentication");
+ ";configuration-authentication");
};
/**
@@ -83,13 +81,14 @@ public class UdnPwdDirAuthentication extends DirBasedAuthentication {
/**
* Initializes the UdnPwdDirAuthentication auth manager.
* <p>
+ *
* @param name - The name for this authentication manager instance.
* @param implName - The name of the authentication manager plugin.
* @param config - The configuration store for this instance.
* @exception EBaseException If an error occurs during initialization.
*/
public void init(String name, String implName, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
super.init(name, implName, config, false);
}
@@ -99,12 +98,12 @@ public class UdnPwdDirAuthentication extends DirBasedAuthentication {
* @param authCreds The authentication credentials.
* @return The user's ldap entry dn.
* @exception EInvalidCredentials If the udn and password are not valid
- * @exception EBaseException If an internal error occurs.
+ * @exception EBaseException If an internal error occurs.
*/
- protected String authenticate(LDAPConnection conn,
- IAuthCredentials authCreds,
- AuthToken token)
- throws EBaseException {
+ protected String authenticate(LDAPConnection conn,
+ IAuthCredentials authCreds,
+ AuthToken token)
+ throws EBaseException {
String userdn = null;
// authenticate by binding to ldap server with password.
@@ -114,7 +113,7 @@ public class UdnPwdDirAuthentication extends DirBasedAuthentication {
if (userdn == null) {
throw new EMissingCredential(CMS.getUserMessage("CMS_AUTHENTICATION_NULL_CREDENTIAL", CRED_UDN));
}
-
+
// get the password.
String pwd = (String) authCreds.get(CRED_PWD);
@@ -123,8 +122,8 @@ public class UdnPwdDirAuthentication extends DirBasedAuthentication {
}
if (pwd.equals("")) {
// anonymous binding not allowed
- log(ILogger.LL_FAILURE,
- "user " + userdn + " attempted login with empty password.");
+ log(ILogger.LL_FAILURE,
+ "user " + userdn + " attempted login with empty password.");
throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
}
@@ -135,21 +134,21 @@ public class UdnPwdDirAuthentication extends DirBasedAuthentication {
return userdn;
} catch (ELdapException e) {
- log(ILogger.LL_FAILURE,
- "Couldn't get ldap connection. Error: " + e.toString());
+ log(ILogger.LL_FAILURE,
+ "Couldn't get ldap connection. Error: " + e.toString());
throw e;
} catch (LDAPException e) {
switch (e.getLDAPResultCode()) {
- case LDAPException.NO_SUCH_OBJECT:
- case LDAPException.LDAP_PARTIAL_RESULTS:
- log(ILogger.LL_SECURITY,
- "user " + userdn + " does not exist in ldap server host " +
- conn.getHost() + ", port " + conn.getPort() + ".");
+ case LDAPException.NO_SUCH_OBJECT:
+ case LDAPException.LDAP_PARTIAL_RESULTS:
+ log(ILogger.LL_SECURITY,
+ "user " + userdn + " does not exist in ldap server host " +
+ conn.getHost() + ", port " + conn.getPort() + ".");
throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
case LDAPException.INVALID_CREDENTIALS:
- log(ILogger.LL_SECURITY,
- "authenticate user " + userdn + " with bad password.");
+ log(ILogger.LL_SECURITY,
+ "authenticate user " + userdn + " with bad password.");
throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
case LDAPException.SERVER_DOWN:
@@ -157,21 +156,21 @@ public class UdnPwdDirAuthentication extends DirBasedAuthentication {
throw new ELdapException(
CMS.getUserMessage("CMS_LDAP_SERVER_UNAVAILABLE", conn.getHost(), "" + conn.getPort()));
- default:
- log(ILogger.LL_FAILURE,
- "Ldap error encountered. " + e.getMessage());
+ default:
+ log(ILogger.LL_FAILURE,
+ "Ldap error encountered. " + e.getMessage());
throw new ELdapException(
- CMS.getUserMessage("CMS_LDAP_OTHER_LDAP_EXCEPTION",
- e.errorCodeToString()));
+ CMS.getUserMessage("CMS_LDAP_OTHER_LDAP_EXCEPTION",
+ e.errorCodeToString()));
}
- }
+ }
}
/**
- * Returns a list of configuration parameter names.
- * The list is passed to the configuration console so instances of
- * this implementation can be configured through the console.
- *
+ * Returns a list of configuration parameter names. The list is passed to
+ * the configuration console so instances of this implementation can be
+ * configured through the console.
+ *
* @return String array of configuration parameter names.
*/
public String[] getConfigParams() {
@@ -180,6 +179,7 @@ public class UdnPwdDirAuthentication extends DirBasedAuthentication {
/**
* Returns array of required credentials for this authentication manager.
+ *
* @return Array of required credentials.
*/
public String[] getRequiredCreds() {
@@ -187,4 +187,3 @@ public class UdnPwdDirAuthentication extends DirBasedAuthentication {
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/authentication/UidPwdDirAuthentication.java b/pki/base/common/src/com/netscape/cms/authentication/UidPwdDirAuthentication.java
index e97fee8b..61333345 100644
--- a/pki/base/common/src/com/netscape/cms/authentication/UidPwdDirAuthentication.java
+++ b/pki/base/common/src/com/netscape/cms/authentication/UidPwdDirAuthentication.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.authentication;
-
// ldap java sdk
import java.util.Enumeration;
import java.util.Locale;
@@ -47,46 +46,45 @@ import com.netscape.certsrv.property.Descriptor;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
* uid/pwd directory based authentication manager
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
-public class UidPwdDirAuthentication extends DirBasedAuthentication
- implements IProfileAuthenticator {
+public class UidPwdDirAuthentication extends DirBasedAuthentication
+ implements IProfileAuthenticator {
/* required credentials to authenticate. uid and pwd are strings. */
public static final String CRED_UID = "uid";
public static final String CRED_PWD = "pwd";
protected static String[] mRequiredCreds = { CRED_UID, CRED_PWD };
- /* Holds configuration parameters accepted by this implementation.
- * This list is passed to the configuration console so configuration
- * for instances of this implementation can be configured through the
- * console.
+ /*
+ * Holds configuration parameters accepted by this implementation. This list
+ * is passed to the configuration console so configuration for instances of
+ * this implementation can be configured through the console.
*/
- protected static String[] mConfigParams =
- new String[] { PROP_DNPATTERN,
- PROP_LDAPSTRINGATTRS,
- PROP_LDAPBYTEATTRS,
- "ldap.ldapconn.host",
- "ldap.ldapconn.port",
- "ldap.ldapconn.secureConn",
- "ldap.ldapconn.version",
- "ldap.basedn",
- "ldap.minConns",
- "ldap.maxConns",
+ protected static String[] mConfigParams =
+ new String[] { PROP_DNPATTERN,
+ PROP_LDAPSTRINGATTRS,
+ PROP_LDAPBYTEATTRS,
+ "ldap.ldapconn.host",
+ "ldap.ldapconn.port",
+ "ldap.ldapconn.secureConn",
+ "ldap.ldapconn.version",
+ "ldap.basedn",
+ "ldap.minConns",
+ "ldap.maxConns",
};
static {
mExtendedPluginInfo.add(IExtendedPluginInfo.HELP_TEXT +
- ";Authenticate the username and password provided " +
- "by the user against an LDAP directory. Works with the " +
- "Dir Based Enrollment HTML form");
+ ";Authenticate the username and password provided " +
+ "by the user against an LDAP directory. Works with the " +
+ "Dir Based Enrollment HTML form");
mExtendedPluginInfo.add(IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-authrules-uidpwddirauth");
+ ";configuration-authrules-uidpwddirauth");
};
/**
@@ -102,12 +100,12 @@ public class UidPwdDirAuthentication extends DirBasedAuthentication
* @param authCreds The authentication credentials.
* @return The user's ldap entry dn.
* @exception EInvalidCredentials If the uid and password are not valid
- * @exception EBaseException If an internal error occurs.
+ * @exception EBaseException If an internal error occurs.
*/
- protected String authenticate(LDAPConnection conn,
- IAuthCredentials authCreds,
- AuthToken token)
- throws EBaseException {
+ protected String authenticate(LDAPConnection conn,
+ IAuthCredentials authCreds,
+ AuthToken token)
+ throws EBaseException {
String userdn = null;
String uid = null;
@@ -119,12 +117,12 @@ public class UidPwdDirAuthentication extends DirBasedAuthentication
if (uid == null) {
throw new EMissingCredential(CMS.getUserMessage("CMS_AUTHENTICATION_NULL_CREDENTIAL", CRED_UID));
}
-
+
// get the password.
String pwd = (String) authCreds.get(CRED_PWD);
if (pwd == null) {
- throw new EMissingCredential(CMS.getUserMessage("CMS_AUTHENTICATION_NULL_CREDENTIAL",CRED_PWD));
+ throw new EMissingCredential(CMS.getUserMessage("CMS_AUTHENTICATION_NULL_CREDENTIAL", CRED_PWD));
}
if (pwd.equals("")) {
// anonymous binding not allowed
@@ -133,13 +131,13 @@ public class UidPwdDirAuthentication extends DirBasedAuthentication
}
// get user dn.
- CMS.debug("Authenticating: Searching for UID=" + uid +
+ CMS.debug("Authenticating: Searching for UID=" + uid +
" base DN=" + mBaseDN);
LDAPSearchResults res = conn.search(mBaseDN,
LDAPv2.SCOPE_SUB, "(uid=" + uid + ")", null, false);
if (res.hasMoreElements()) {
- //LDAPEntry entry = (LDAPEntry)res.nextElement();
+ // LDAPEntry entry = (LDAPEntry)res.nextElement();
LDAPEntry entry = res.next();
userdn = entry.getDN();
@@ -160,8 +158,8 @@ public class UidPwdDirAuthentication extends DirBasedAuthentication
throw e;
} catch (LDAPException e) {
switch (e.getLDAPResultCode()) {
- case LDAPException.NO_SUCH_OBJECT:
- case LDAPException.LDAP_PARTIAL_RESULTS:
+ case LDAPException.NO_SUCH_OBJECT:
+ case LDAPException.LDAP_PARTIAL_RESULTS:
log(ILogger.LL_SECURITY, CMS.getLogMessage("USER_NOT_EXIST", uid));
throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
@@ -174,20 +172,20 @@ public class UidPwdDirAuthentication extends DirBasedAuthentication
throw new ELdapException(
CMS.getUserMessage("CMS_LDAP_SERVER_UNAVAILABLE", conn.getHost(), "" + conn.getPort()));
- default:
+ default:
log(ILogger.LL_FAILURE, CMS.getLogMessage("OPERATION_ERROR", e.getMessage()));
throw new ELdapException(
- CMS.getUserMessage("CMS_LDAP_OTHER_LDAP_EXCEPTION",
- e.errorCodeToString()));
+ CMS.getUserMessage("CMS_LDAP_OTHER_LDAP_EXCEPTION",
+ e.errorCodeToString()));
}
- }
+ }
}
/**
- * Returns a list of configuration parameter names.
- * The list is passed to the configuration console so instances of
- * this implementation can be configured through the console.
- *
+ * Returns a list of configuration parameter names. The list is passed to
+ * the configuration console so instances of this implementation can be
+ * configured through the console.
+ *
* @return String array of configuration parameter names.
*/
public String[] getConfigParams() {
@@ -196,6 +194,7 @@ public class UidPwdDirAuthentication extends DirBasedAuthentication
/**
* Returns array of required credentials for this authentication manager.
+ *
* @return Array of required credentials.
*/
public String[] getRequiredCreds() {
@@ -203,9 +202,9 @@ public class UidPwdDirAuthentication extends DirBasedAuthentication
}
// Profile-related methods
-
+
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
}
/**
@@ -243,23 +242,22 @@ public class UidPwdDirAuthentication extends DirBasedAuthentication
}
/**
- * Retrieves the descriptor of the given value
- * parameter by name.
+ * Retrieves the descriptor of the given value parameter by name.
*/
public IDescriptor getValueDescriptor(Locale locale, String name) {
- if (name.equals(CRED_UID)) {
+ if (name.equals(CRED_UID)) {
return new Descriptor(IDescriptor.STRING, null, null,
CMS.getUserMessage(locale, "CMS_AUTHENTICATION_LDAP_UID"));
} else if (name.equals(CRED_PWD)) {
return new Descriptor(IDescriptor.PASSWORD, null, null,
CMS.getUserMessage(locale, "CMS_AUTHENTICATION_LDAP_PWD"));
-
+
}
return null;
}
- public void populate(IAuthToken token, IRequest request)
- throws EProfileException {
+ public void populate(IAuthToken token, IRequest request)
+ throws EProfileException {
request.setExtData(IProfileAuthenticator.AUTHENTICATED_NAME,
token.getInString(USER_DN));
}
diff --git a/pki/base/common/src/com/netscape/cms/authentication/UidPwdPinDirAuthentication.java b/pki/base/common/src/com/netscape/cms/authentication/UidPwdPinDirAuthentication.java
index ce60bf8d..f305648b 100644
--- a/pki/base/common/src/com/netscape/cms/authentication/UidPwdPinDirAuthentication.java
+++ b/pki/base/common/src/com/netscape/cms/authentication/UidPwdPinDirAuthentication.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.authentication;
-
// ldap java sdk
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@@ -53,15 +52,14 @@ import com.netscape.certsrv.property.Descriptor;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
* uid/pwd/pin directory based authentication manager
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class UidPwdPinDirAuthentication extends DirBasedAuthentication
- implements IExtendedPluginInfo, IProfileAuthenticator {
+ implements IExtendedPluginInfo, IProfileAuthenticator {
/* required credentials to authenticate. uid and pwd are strings. */
public static final String CRED_UID = "uid";
@@ -79,54 +77,54 @@ public class UidPwdPinDirAuthentication extends DirBasedAuthentication
protected static final byte SENTINEL_MD5 = 1;
protected static final byte SENTINEL_NONE = 0x2d;
- /* Holds configuration parameters accepted by this implementation.
- * This list is passed to the configuration console so configuration
- * for instances of this implementation can be configured through the
- * console.
+ /*
+ * Holds configuration parameters accepted by this implementation. This list
+ * is passed to the configuration console so configuration for instances of
+ * this implementation can be configured through the console.
*/
- protected static String[] mConfigParams =
- new String[] { PROP_REMOVE_PIN,
- PROP_PIN_ATTR,
- PROP_DNPATTERN,
- PROP_LDAPSTRINGATTRS,
- PROP_LDAPBYTEATTRS,
- "ldap.ldapconn.host",
- "ldap.ldapconn.port",
- "ldap.ldapconn.secureConn",
- "ldap.ldapconn.version",
- "ldap.ldapauth.bindDN",
- "ldap.ldapauth.bindPWPrompt",
- "ldap.ldapauth.clientCertNickname",
- "ldap.ldapauth.authtype",
- "ldap.basedn",
- "ldap.minConns",
- "ldap.maxConns",
+ protected static String[] mConfigParams =
+ new String[] { PROP_REMOVE_PIN,
+ PROP_PIN_ATTR,
+ PROP_DNPATTERN,
+ PROP_LDAPSTRINGATTRS,
+ PROP_LDAPBYTEATTRS,
+ "ldap.ldapconn.host",
+ "ldap.ldapconn.port",
+ "ldap.ldapconn.secureConn",
+ "ldap.ldapconn.version",
+ "ldap.ldapauth.bindDN",
+ "ldap.ldapauth.bindPWPrompt",
+ "ldap.ldapauth.clientCertNickname",
+ "ldap.ldapauth.authtype",
+ "ldap.basedn",
+ "ldap.minConns",
+ "ldap.maxConns",
};
static {
mExtendedPluginInfo.add(
- PROP_REMOVE_PIN + ";boolean;SEE DOCUMENTATION for pin removal");
+ PROP_REMOVE_PIN + ";boolean;SEE DOCUMENTATION for pin removal");
mExtendedPluginInfo.add(
- PROP_PIN_ATTR + ";string;directory attribute to use for pin (default 'pin')");
+ PROP_PIN_ATTR + ";string;directory attribute to use for pin (default 'pin')");
mExtendedPluginInfo.add(
- "ldap.ldapauth.bindDN;string;DN to bind as for pin removal. "
- + "For example 'CN=PinRemoval User'");
+ "ldap.ldapauth.bindDN;string;DN to bind as for pin removal. "
+ + "For example 'CN=PinRemoval User'");
mExtendedPluginInfo.add(
- "ldap.ldapauth.bindPWPrompt;password;Enter password used to bind as " +
- "the above user");
+ "ldap.ldapauth.bindPWPrompt;password;Enter password used to bind as " +
+ "the above user");
mExtendedPluginInfo.add(
- "ldap.ldapauth.clientCertNickname;string;If you want to use "
- + "SSL client auth to the directory, set the client "
- + "cert nickname here");
+ "ldap.ldapauth.clientCertNickname;string;If you want to use "
+ + "SSL client auth to the directory, set the client "
+ + "cert nickname here");
mExtendedPluginInfo.add(
- "ldap.ldapauth.authtype;choice(BasicAuth,SslClientAuth),required;"
- + "How to bind to the directory (for pin removal only)");
+ "ldap.ldapauth.authtype;choice(BasicAuth,SslClientAuth),required;"
+ + "How to bind to the directory (for pin removal only)");
mExtendedPluginInfo.add(IExtendedPluginInfo.HELP_TEXT
- + ";Authenticate the username, password and pin provided "
- + "by the user against an LDAP directory. Works with the "
- + "Dir/Pin Based Enrollment HTML form");
+ + ";Authenticate the username, password and pin provided "
+ + "by the user against an LDAP directory. Works with the "
+ + "Dir/Pin Based Enrollment HTML form");
mExtendedPluginInfo.add(IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-authrules-uidpwdpindirauth");
+ ";configuration-authrules-uidpwdpindirauth");
}
@@ -135,12 +133,12 @@ public class UidPwdPinDirAuthentication extends DirBasedAuthentication
protected MessageDigest mSHADigest = null;
protected MessageDigest mMD5Digest = null;
- private String mBindDN = null;
- private String mBindPassword = null;
+ private String mBindDN = null;
+ private String mBindPassword = null;
- private ILdapConnFactory removePinLdapFactory = null;
- private LDAPConnection removePinLdapConnection = null;
- private IConfigStore removePinLdapConfigStore = null;
+ private ILdapConnFactory removePinLdapFactory = null;
+ private LDAPConnection removePinLdapConnection = null;
+ private IConfigStore removePinLdapConfigStore = null;
/**
* Default constructor, initialization must follow.
@@ -149,12 +147,12 @@ public class UidPwdPinDirAuthentication extends DirBasedAuthentication
super();
}
- public void init(String name, String implName, IConfigStore config)
- throws EBaseException {
+ public void init(String name, String implName, IConfigStore config)
+ throws EBaseException {
super.init(name, implName, config);
- mRemovePin =
+ mRemovePin =
config.getBoolean(PROP_REMOVE_PIN, DEF_REMOVE_PIN);
- mPinAttr =
+ mPinAttr =
config.getString(PROP_PIN_ATTR, DEF_PIN_ATTR);
if (mPinAttr.equals("")) {
mPinAttr = DEF_PIN_ATTR;
@@ -166,7 +164,7 @@ public class UidPwdPinDirAuthentication extends DirBasedAuthentication
removePinLdapFactory.init(removePinLdapConfigStore);
removePinLdapConnection = removePinLdapFactory.getConn();
}
-
+
try {
mSHADigest = MessageDigest.getInstance("SHA1");
mMD5Digest = MessageDigest.getInstance("MD5");
@@ -177,7 +175,7 @@ public class UidPwdPinDirAuthentication extends DirBasedAuthentication
}
protected void verifyPassword(String Password) {
- }
+ }
/**
* Authenticates a user based on its uid, pwd, pin in the directory.
@@ -185,16 +183,16 @@ public class UidPwdPinDirAuthentication extends DirBasedAuthentication
* @param authCreds The authentication credentials with uid, pwd, pin.
* @return The user's ldap entry dn.
* @exception EInvalidCredentials If the uid and password are not valid
- * @exception EBaseException If an internal error occurs.
+ * @exception EBaseException If an internal error occurs.
*/
- protected String authenticate(LDAPConnection conn,
- IAuthCredentials authCreds,
- AuthToken token)
- throws EBaseException {
+ protected String authenticate(LDAPConnection conn,
+ IAuthCredentials authCreds,
+ AuthToken token)
+ throws EBaseException {
String userdn = null;
- String uid = null;
- String pwd = null;
- String pin = null;
+ String uid = null;
+ String pwd = null;
+ String pin = null;
try {
// get the uid.
@@ -202,7 +200,7 @@ public class UidPwdPinDirAuthentication extends DirBasedAuthentication
if (uid == null) {
throw new EMissingCredential(CMS.getUserMessage("CMS_AUTHENTICATION_NULL_CREDENTIAL", CRED_UID));
}
-
+
// get the password.
pwd = (String) authCreds.get(CRED_PWD);
if (pwd == null) {
@@ -244,7 +242,7 @@ public class UidPwdPinDirAuthentication extends DirBasedAuthentication
log(ILogger.LL_SECURITY, CMS.getLogMessage("CMS_AUTH_AUTHENTICATED", uid));
// log(ILogger.LL_SECURITY, "found user : " + userdn);
- // check pin.
+ // check pin.
checkpin(conn, userdn, uid, pin);
// set uid in the token.
@@ -256,8 +254,8 @@ public class UidPwdPinDirAuthentication extends DirBasedAuthentication
throw e;
} catch (LDAPException e) {
switch (e.getLDAPResultCode()) {
- case LDAPException.NO_SUCH_OBJECT:
- case LDAPException.LDAP_PARTIAL_RESULTS:
+ case LDAPException.NO_SUCH_OBJECT:
+ case LDAPException.LDAP_PARTIAL_RESULTS:
log(ILogger.LL_SECURITY, CMS.getLogMessage("CMS_AUTH_USER_NOT_EXIST", uid));
throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
@@ -270,24 +268,24 @@ public class UidPwdPinDirAuthentication extends DirBasedAuthentication
throw new ELdapException(
CMS.getUserMessage("CMS_LDAP_SERVER_UNAVAILABLE", conn.getHost(), "" + conn.getPort()));
- default:
+ default:
log(ILogger.LL_FAILURE, CMS.getLogMessage("OPERATION_ERROR", e.getMessage()));
throw new ELdapException(
- CMS.getUserMessage("CMS_LDAP_OTHER_LDAP_EXCEPTION",
- e.errorCodeToString()));
+ CMS.getUserMessage("CMS_LDAP_OTHER_LDAP_EXCEPTION",
+ e.errorCodeToString()));
}
- }
+ }
}
- protected void checkpin(LDAPConnection conn, String userdn,
- String uid, String pin)
- throws EBaseException, LDAPException {
+ protected void checkpin(LDAPConnection conn, String userdn,
+ String uid, String pin)
+ throws EBaseException, LDAPException {
LDAPSearchResults res = null;
LDAPEntry entry = null;
// get pin.
- res = conn.search(userdn, LDAPv2.SCOPE_BASE,
+ res = conn.search(userdn, LDAPv2.SCOPE_BASE,
"(objectclass=*)", new String[] { mPinAttr }, false);
if (res.hasMoreElements()) {
entry = (LDAPEntry) res.nextElement();
@@ -309,7 +307,7 @@ public class UidPwdPinDirAuthentication extends DirBasedAuthentication
log(ILogger.LL_SECURITY, CMS.getLogMessage("CMS_AUTH_NO_PIN_FOUND", uid));
throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
}
- byte[] entrypin = (byte[]) pinValues.nextElement();
+ byte[] entrypin = (byte[]) pinValues.nextElement();
// compare value digest.
@@ -317,14 +315,14 @@ public class UidPwdPinDirAuthentication extends DirBasedAuthentication
log(ILogger.LL_SECURITY, CMS.getLogMessage("CMS_AUTH_NO_PIN_FOUND", uid));
throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
}
-
+
byte hashtype = entrypin[0];
byte[] pinDigest = null;
String toBeDigested = userdn + pin;
if (hashtype == SENTINEL_SHA) {
-
+
pinDigest = mSHADigest.digest(toBeDigested.getBytes());
} else if (hashtype == SENTINEL_MD5) {
pinDigest = mMD5Digest.digest(toBeDigested.getBytes());
@@ -343,7 +341,7 @@ public class UidPwdPinDirAuthentication extends DirBasedAuthentication
int i;
for (i = 0; i < (entrypin.length - 1); i++) {
- if (pinDigest[i] != entrypin[i + 1])
+ if (pinDigest[i] != entrypin[i + 1])
break;
}
if (i != (entrypin.length - 1)) {
@@ -354,17 +352,17 @@ public class UidPwdPinDirAuthentication extends DirBasedAuthentication
// pin ok. remove pin if so configured
// Note that this means that a policy may reject this request later,
// but the user will not be able to enroll again as his pin is gone.
-
+
// We remove the pin using a different connection which is bound as
// a more privileged user.
if (mRemovePin) {
try {
- removePinLdapConnection.modify(userdn,
- new LDAPModification(
- LDAPModification.DELETE,
- new LDAPAttribute(mPinAttr, entrypin)));
+ removePinLdapConnection.modify(userdn,
+ new LDAPModification(
+ LDAPModification.DELETE,
+ new LDAPAttribute(mPinAttr, entrypin)));
} catch (LDAPException e) {
log(ILogger.LL_SECURITY, CMS.getLogMessage("CMS_AUTH_CANT_REMOVE_PIN", userdn));
@@ -374,10 +372,10 @@ public class UidPwdPinDirAuthentication extends DirBasedAuthentication
}
/**
- * Returns a list of configuration parameter names.
- * The list is passed to the configuration console so instances of
- * this implementation can be configured through the console.
- *
+ * Returns a list of configuration parameter names. The list is passed to
+ * the configuration console so instances of this implementation can be
+ * configured through the console.
+ *
* @return String array of configuration parameter names.
*/
public String[] getConfigParams() {
@@ -386,6 +384,7 @@ public class UidPwdPinDirAuthentication extends DirBasedAuthentication
/**
* Returns array of required credentials for this authentication manager.
+ *
* @return Array of required credentials.
*/
public String[] getRequiredCreds() {
@@ -395,7 +394,7 @@ public class UidPwdPinDirAuthentication extends DirBasedAuthentication
// Profile-related methods
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
}
/**
@@ -434,8 +433,7 @@ public class UidPwdPinDirAuthentication extends DirBasedAuthentication
}
/**
- * Retrieves the descriptor of the given value
- * parameter by name.
+ * Retrieves the descriptor of the given value parameter by name.
*/
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(CRED_UID)) {
@@ -453,7 +451,7 @@ public class UidPwdPinDirAuthentication extends DirBasedAuthentication
}
public void populate(IAuthToken token, IRequest request)
- throws EProfileException {
+ throws EProfileException {
request.setExtData(IProfileAuthenticator.AUTHENTICATED_NAME,
token.getInString(USER_DN));
}
@@ -462,4 +460,3 @@ public class UidPwdPinDirAuthentication extends DirBasedAuthentication
return false;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/authorization/AAclAuthz.java b/pki/base/common/src/com/netscape/cms/authorization/AAclAuthz.java
index 0bb36f28..df15dd1c 100644
--- a/pki/base/common/src/com/netscape/cms/authorization/AAclAuthz.java
+++ b/pki/base/common/src/com/netscape/cms/authorization/AAclAuthz.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.authorization;
-
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Locale;
@@ -37,30 +36,32 @@ import com.netscape.certsrv.evaluators.IAccessEvaluator;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.cmsutil.util.Utils;
-
/**
- * An abstract class represents an authorization manager that governs the
- * access of internal resources such as servlets.
- * It parses in the ACLs associated with each protected
- * resources, and provides protected method <CODE>checkPermission</CODE>
- * for code that needs to verify access before performing
- * actions.
+ * An abstract class represents an authorization manager that governs the access
+ * of internal resources such as servlets. It parses in the ACLs associated with
+ * each protected resources, and provides protected method
+ * <CODE>checkPermission</CODE> for code that needs to verify access before
+ * performing actions.
* <P>
* Here is a sample resourceACLS for a resource
+ *
* <PRE>
* certServer.UsrGrpAdminServlet:
* execute:
* deny (execute) user="tempAdmin";
* allow (execute) group="Administrators";
* </PRE>
- * To perform permission checking, code call authz mgr authorize()
- * method to verify access. See AuthzMgr for calling example.
+ *
+ * To perform permission checking, code call authz mgr authorize() method to
+ * verify access. See AuthzMgr for calling example.
* <P>
- * default "evaluators" are used to evaluate the "group=.." or "user=.."
- * rules. See evaluator for more info
+ * default "evaluators" are used to evaluate the "group=.." or "user=.." rules.
+ * See evaluator for more info
*
* @version $Revision$, $Date$
- * @see <A HREF="http://developer.netscape.com/library/documentation/enterprise/admnunix/aclfiles.htm">ACL Files</A>
+ * @see <A
+ * HREF="http://developer.netscape.com/library/documentation/enterprise/admnunix/aclfiles.htm">ACL
+ * Files</A>
*/
public abstract class AAclAuthz {
@@ -92,10 +93,10 @@ public abstract class AAclAuthz {
}
/**
- * Initializes
+ * Initializes
*/
- protected void init(IConfigStore config)
- throws EBaseException {
+ protected void init(IConfigStore config)
+ throws EBaseException {
mLogger = CMS.getLogger();
CMS.debug("AAclAuthz: init begins");
@@ -123,16 +124,15 @@ public abstract class AAclAuthz {
type + "." + PROP_CLASS));
}
- // instantiate evaluator
+ // instantiate evaluator
try {
evaluator =
(IAccessEvaluator) Class.forName(evalClassPath).newInstance();
} catch (Exception e) {
String errMsg = "init(): failed to load class: " +
- evalClassPath + ":" + e.toString();
+ evalClassPath + ":" + e.toString();
- throw new
- EACLsException(CMS.getUserMessage("CMS_ACL_CLASS_LOAD_FAIL",
+ throw new EACLsException(CMS.getUserMessage("CMS_ACL_CLASS_LOAD_FAIL",
evalClassPath));
}
@@ -151,16 +151,18 @@ public abstract class AAclAuthz {
}
/**
- * Parse ACL resource attributes, then update the ACLs memory store
- * This is intended to be used if storing ACLs on ldap is not desired,
- * and the caller is expected to call this method to add resource
- * and acl info into acls memory store. The resACLs format should conform
- * to the following:
- * <resource ID>:right-1[,right-n]:[allow,deny](right(s))<evaluatorType>=<value>:<comment for this resource acl
+ * Parse ACL resource attributes, then update the ACLs memory store This is
+ * intended to be used if storing ACLs on ldap is not desired, and the
+ * caller is expected to call this method to add resource and acl info into
+ * acls memory store. The resACLs format should conform to the following:
+ * <resource
+ * ID>:right-1[,right-n]:[allow,deny](right(s))<evaluatorType>=<value
+ * >:<comment for this resource acl
* <P>
- * Example:
- * resTurnKnob:left,right:allow(left) group="lefties":door knobs for lefties
- * @param resACLs same format as the resourceACLs attribute
+ * Example: resTurnKnob:left,right:allow(left) group="lefties":door knobs
+ * for lefties
+ *
+ * @param resACLs same format as the resourceACLs attribute
* @throws EBaseException parsing error from <code>parseACL</code>
*/
public void addACLs(String resACLs) throws EBaseException {
@@ -180,7 +182,7 @@ public abstract class AAclAuthz {
public IACL getACL(String target) {
return (ACL) mACLs.get(target);
}
-
+
protected Enumeration<String> getTargetNames() {
return mACLs.keys();
}
@@ -204,10 +206,10 @@ public abstract class AAclAuthz {
}
/**
- * Returns a list of configuration parameter names.
- * The list is passed to the configuration console so instances of
- * this implementation can be configured through the console.
- *
+ * Returns a list of configuration parameter names. The list is passed to
+ * the configuration console so instances of this implementation can be
+ * configured through the console.
+ *
* @return String array of configuration parameter names.
*/
public String[] getConfigParams() {
@@ -220,8 +222,7 @@ public abstract class AAclAuthz {
public abstract void shutdown();
/**
- * Registers new handler for the given attribute type
- * in the expressions.
+ * Registers new handler for the given attribute type in the expressions.
*/
public void registerEvaluator(String type, IAccessEvaluator evaluator) {
mEvaluators.put(type, evaluator);
@@ -233,45 +234,42 @@ public abstract class AAclAuthz {
*******************************************************/
/**
- * Checks if the permission is granted or denied in
- * the current execution context. If the code is
- * marked as privileged, this methods will simply
+ * Checks if the permission is granted or denied in the current execution
+ * context. If the code is marked as privileged, this methods will simply
* return.
* <P>
- * note that if a resource does not exist in the aclResources
- * entry, but a higher level node exist, it will still be
- * evaluated. The highest level node's acl determines the
- * permission. If the higher level node doesn't contain any acl
- * information, then it's passed down to the lower node. If
- * a node has no aci in its resourceACLs, then it's considered
- * passed.
+ * note that if a resource does not exist in the aclResources entry, but a
+ * higher level node exist, it will still be evaluated. The highest level
+ * node's acl determines the permission. If the higher level node doesn't
+ * contain any acl information, then it's passed down to the lower node. If
+ * a node has no aci in its resourceACLs, then it's considered passed.
* <p>
* example: certServer.common.users, if failed permission check for
- * "certServer", then it's considered failed, and there is no need to
- * continue the check. If passed permission check for "certServer",
- * then it's considered passed, and no need to continue the
- * check. If certServer contains no aci then "certServer.common" will be
- * checked for permission instead. If down to the leaf level,
- * the node still contains no aci, then it's considered passed.
- * If at the leaf level, no such resource exist, or no acis, it's
- * considered passed.
+ * "certServer", then it's considered failed, and there is no need to
+ * continue the check. If passed permission check for "certServer", then
+ * it's considered passed, and no need to continue the check. If certServer
+ * contains no aci then "certServer.common" will be checked for permission
+ * instead. If down to the leaf level, the node still contains no aci, then
+ * it's considered passed. If at the leaf level, no such resource exist, or
+ * no acis, it's considered passed.
* <p>
- * If there are multiple aci's for a resource, ALL aci's will be
- * checked, and only if all passed permission checks, will the
- * eventual access be granted.
+ * If there are multiple aci's for a resource, ALL aci's will be checked,
+ * and only if all passed permission checks, will the eventual access be
+ * granted.
+ *
* @param name resource name
* @param perm permission requested
* @exception EACLsException access permission denied
*/
- protected synchronized void checkPermission(String name, String perm)
- throws EACLsException {
+ protected synchronized void checkPermission(String name, String perm)
+ throws EACLsException {
String resource = "";
StringTokenizer st = new StringTokenizer(name, ".");
while (st.hasMoreTokens()) {
String node = st.nextToken();
- if (! "".equals(resource)) {
+ if (!"".equals(resource)) {
resource = resource + "." + node;
} else {
resource = node;
@@ -288,18 +286,17 @@ public abstract class AAclAuthz {
params[1] = perm;
String errMsg = "checkPermission(): permission denied for the resource " +
- name + " on operation " + perm;
+ name + " on operation " + perm;
log(ILogger.LL_SECURITY, CMS.getLogMessage("AUTHZ_EVALUATOR_ACCESS_DENIED", name, perm));
- throw new
- EACLsException(CMS.getUserMessage("CMS_ACL_NO_PERMISSION",
+ throw new EACLsException(CMS.getUserMessage("CMS_ACL_NO_PERMISSION",
(String[]) params));
}
if (passed) {
String infoMsg = "checkPermission(): permission granted for the resource " +
- name + " on operation " + perm;
+ name + " on operation " + perm;
log(ILogger.LL_INFO, infoMsg);
@@ -309,38 +306,37 @@ public abstract class AAclAuthz {
}
/**
- * Checks if the permission is granted or denied in
- * the current execution context.
+ * Checks if the permission is granted or denied in the current execution
+ * context.
* <P>
* An <code>ACL</code> may contain one or more <code>ACLEntry</code>.
- * However, in case of multiple <code>ACLEntry</code>, a subject must
- * pass ALL of the <code>ACLEntry</code> evaluation for permission
- * to be granted
+ * However, in case of multiple <code>ACLEntry</code>, a subject must pass
+ * ALL of the <code>ACLEntry</code> evaluation for permission to be granted
* <P>
- * negative ("deny") aclEntries are treated differently than
- * positive ("allow") statements. If a negative aclEntries
- * fails the acl check, the permission check will return "false"
- * right away; while in the case of a positive aclEntry, if the
- * the aclEntry fails the acl check, the next aclEntry will be
- * evaluated.
+ * negative ("deny") aclEntries are treated differently than positive
+ * ("allow") statements. If a negative aclEntries fails the acl check, the
+ * permission check will return "false" right away; while in the case of a
+ * positive aclEntry, if the the aclEntry fails the acl check, the next
+ * aclEntry will be evaluated.
+ *
* @param name resource name
* @param perm permission requested
- * @return true if access allowed
- * false if should be passed down to the next node
+ * @return true if access allowed false if should be passed down to the next
+ * node
* @exception EACLsException if access disallowed
*/
- private boolean checkACLs(String name, String perm)
- throws EACLsException {
+ private boolean checkACLs(String name, String perm)
+ throws EACLsException {
ACL acl = (ACL) mACLs.get(name);
// no such resource, pass it down
if (acl == null) {
String infoMsg = "checkACLs(): no acl for" +
- name + "...pass down to next node";
+ name + "...pass down to next node";
log(ILogger.LL_INFO, infoMsg);
- return false;
+ return false;
}
Enumeration<ACLEntry> e = acl.entries();
@@ -348,7 +344,7 @@ public abstract class AAclAuthz {
if ((e == null) || (e.hasMoreElements() == false)) {
// no acis for node, pass down to next node
String infoMsg = " AAclAuthz.checkACLs(): no acis for " +
- name + " acl entry...pass down to next node";
+ name + " acl entry...pass down to next node";
log(ILogger.LL_INFO, infoMsg);
@@ -380,10 +376,8 @@ public abstract class AAclAuthz {
}
/**
- * Resolves the given expressions.
- * expression || expression || ...
- * example:
- * group="Administrators" || group="Operators"
+ * Resolves the given expressions. expression || expression || ... example:
+ * group="Administrators" || group="Operators"
*/
private boolean evaluateExpressions(String s) {
// XXX - just handle "||" (or) among multiple expressions for now
@@ -449,8 +443,8 @@ public abstract class AAclAuthz {
private boolean evaluateExpression(String expression) {
// XXX - just recognize "=" for now!!
int i = expression.indexOf("=");
- String type = expression.substring(0, i);
- String value = expression.substring(i + 1);
+ String type = expression.substring(0, i);
+ String value = expression.substring(i + 1);
IAccessEvaluator evaluator = (IAccessEvaluator) mEvaluators.get(type);
if (evaluator == null) {
@@ -468,76 +462,73 @@ public abstract class AAclAuthz {
*******************************************************/
/**
- * Checks if the permission is granted or denied with id from authtoken
+ * Checks if the permission is granted or denied with id from authtoken
* gotten from authentication that precedes authorization. If the code is
- * marked as privileged, this methods will simply
- * return.
+ * marked as privileged, this methods will simply return.
* <P>
- * note that if a resource does not exist in the aclResources
- * entry, but a higher level node exist, it will still be
- * evaluated. The highest level node's acl determines the
- * permission. If the higher level node doesn't contain any acl
- * information, then it's passed down to the lower node. If
- * a node has no aci in its resourceACLs, then it's considered
- * passed.
+ * note that if a resource does not exist in the aclResources entry, but a
+ * higher level node exist, it will still be evaluated. The highest level
+ * node's acl determines the permission. If the higher level node doesn't
+ * contain any acl information, then it's passed down to the lower node. If
+ * a node has no aci in its resourceACLs, then it's considered passed.
* <p>
* example: certServer.common.users, if failed permission check for
- * "certServer", then it's considered failed, and there is no need to
- * continue the check. If passed permission check for "certServer",
- * then it's considered passed, and no need to continue the
- * check. If certServer contains no aci then "certServer.common" will be
- * checked for permission instead. If down to the leaf level,
- * the node still contains no aci, then it's considered passed.
- * If at the leaf level, no such resource exist, or no acis, it's
- * considered passed.
+ * "certServer", then it's considered failed, and there is no need to
+ * continue the check. If passed permission check for "certServer", then
+ * it's considered passed, and no need to continue the check. If certServer
+ * contains no aci then "certServer.common" will be checked for permission
+ * instead. If down to the leaf level, the node still contains no aci, then
+ * it's considered passed. If at the leaf level, no such resource exist, or
+ * no acis, it's considered passed.
* <p>
- * If there are multiple aci's for a resource, ALL aci's will be
- * checked, and only if all passed permission checks, will the
- * eventual access be granted.
+ * If there are multiple aci's for a resource, ALL aci's will be checked,
+ * and only if all passed permission checks, will the eventual access be
+ * granted.
+ *
* @param authToken authentication token gotten from authentication
* @param name resource name
* @param perm permission requested
* @exception EACLsException access permission denied
*/
- public synchronized void checkPermission(IAuthToken authToken, String name,
- String perm)
- throws EACLsException {
-
+ public synchronized void checkPermission(IAuthToken authToken, String name,
+ String perm)
+ throws EACLsException {
+
Vector<String> nodev = getNodes(name);
Enumeration<String> nodes = nodev.elements();
String order = getOrder();
Enumeration<ACLEntry> entries = null;
- if (order.equals("deny"))
+ if (order.equals("deny"))
entries = getDenyEntries(nodes, perm);
- else
+ else
entries = getAllowEntries(nodes, perm);
-
+
boolean permitted = false;
while (entries.hasMoreElements()) {
ACLEntry entry = (ACLEntry) entries.nextElement();
CMS.debug("checkACLS(): ACLEntry expressions= " +
- entry.getAttributeExpressions());
+ entry.getAttributeExpressions());
if (evaluateExpressions(authToken, entry.getAttributeExpressions())) {
- log(ILogger.LL_SECURITY,
- " checkACLs(): permission denied");
+ log(ILogger.LL_SECURITY,
+ " checkACLs(): permission denied");
throw new EACLsException(CMS.getUserMessage("CMS_ACL_PERMISSION_DENIED"));
}
}
nodes = nodev.elements();
- if (order.equals("deny"))
+ if (order.equals("deny"))
entries = getAllowEntries(nodes, perm);
- else
+ else
entries = getDenyEntries(nodes, perm);
- while (entries.hasMoreElements()) {
+ while (entries.hasMoreElements()) {
ACLEntry entry = (ACLEntry) entries.nextElement();
CMS.debug("checkACLS(): ACLEntry expressions= " +
- entry.getAttributeExpressions());
+ entry.getAttributeExpressions());
if (evaluateExpressions(authToken, entry.getAttributeExpressions())) {
permitted = true;
}
@@ -546,7 +537,7 @@ public abstract class AAclAuthz {
nodev = null;
if (permitted) {
String infoMsg = "checkPermission(): permission granted for the resource " +
- name + " on operation " + perm;
+ name + " on operation " + perm;
log(ILogger.LL_INFO, infoMsg);
return;
@@ -557,10 +548,10 @@ public abstract class AAclAuthz {
params[1] = perm;
String errMsg = "checkPermission(): permission denied for the resource " +
- name + " on operation " + perm;
+ name + " on operation " + perm;
- log(ILogger.LL_SECURITY,
- CMS.getLogMessage("AUTHZ_EVALUATOR_ACCESS_DENIED", name, perm));
+ log(ILogger.LL_SECURITY,
+ CMS.getLogMessage("AUTHZ_EVALUATOR_ACCESS_DENIED", name, perm));
throw new EACLsException(CMS.getUserMessage("CMS_ACL_NO_PERMISSION",
(String[]) params));
@@ -582,13 +573,13 @@ public abstract class AAclAuthz {
while (e.hasMoreElements()) {
ACLEntry entry = (ACLEntry) e.nextElement();
- if (!entry.isNegative() &&
- entry.containPermission(operation)) {
+ if (!entry.isNegative() &&
+ entry.containPermission(operation)) {
v.addElement(entry);
}
}
}
-
+
return v.elements();
}
@@ -607,21 +598,19 @@ public abstract class AAclAuthz {
while (e.hasMoreElements()) {
ACLEntry entry = e.nextElement();
- if (entry.isNegative() &&
- entry.containPermission(operation)) {
+ if (entry.isNegative() &&
+ entry.containPermission(operation)) {
v.addElement(entry);
}
}
}
-
+
return v.elements();
}
/**
- * Resolves the given expressions.
- * expression || expression || ...
- * example:
- * group="Administrators" || group="Operators"
+ * Resolves the given expressions. expression || expression || ... example:
+ * group="Administrators" || group="Operators"
*/
private boolean evaluateExpressions(IAuthToken authToken, String s) {
// XXX - just handle "||" (or) among multiple expressions for now
@@ -703,7 +692,7 @@ public abstract class AAclAuthz {
while (index != -1) {
name = name.substring(0, index);
v.addElement(name);
- index = name.lastIndexOf(".");
+ index = name.lastIndexOf(".");
}
return v;
@@ -745,7 +734,7 @@ public abstract class AAclAuthz {
i = exp.indexOf(">");
if (i == -1) {
i = exp.indexOf("<");
- if (i == -1) {
+ if (i == -1) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("AUTHZ_OP_NOT_SUPPORTED", exp));
} else {
return "<";
@@ -780,19 +769,19 @@ public abstract class AAclAuthz {
*******************************************************/
/**
- * This one only updates the memory. Classes extend this class should
- * also update to a permanent storage
+ * This one only updates the memory. Classes extend this class should also
+ * update to a permanent storage
*/
- public void updateACLs(String id, String rights, String strACLs,
- String desc) throws EACLsException {
+ public void updateACLs(String id, String rights, String strACLs,
+ String desc) throws EACLsException {
ACL acl = (ACL) getACL(id);
-
+
String resourceACLs = id;
if (rights != null)
resourceACLs = id + ":" + rights + ":" + strACLs + ":" + desc;
- // memory update
+ // memory update
ACL ac = null;
try {
@@ -806,6 +795,7 @@ public abstract class AAclAuthz {
/**
* gets an enumeration of resources
+ *
* @return an enumeration of resources contained in the ACL table
*/
public Enumeration<ACL> aclResElements() {
@@ -814,6 +804,7 @@ public abstract class AAclAuthz {
/**
* gets an enumeration of access evaluators
+ *
* @return an enumeraton of access evaluators
*/
public Enumeration<IAccessEvaluator> aclEvaluatorElements() {
@@ -822,6 +813,7 @@ public abstract class AAclAuthz {
/**
* gets the access evaluators
+ *
* @return handle to the access evaluators table
*/
public Hashtable<String, IAccessEvaluator> getAccessEvaluators() {
@@ -830,6 +822,7 @@ public abstract class AAclAuthz {
/**
* is this resource name unique
+ *
* @return true if unique; false otherwise
*/
public boolean isTypeUnique(String type) {
@@ -844,7 +837,7 @@ public abstract class AAclAuthz {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_AUTHORIZATION,
- level, msg);
+ level, msg);
}
/*********************************
@@ -852,17 +845,16 @@ public abstract class AAclAuthz {
**********************************/
/**
- * update acls. called after memory upate is done to flush to permanent
+ * update acls. called after memory upate is done to flush to permanent
* storage.
* <p>
*/
protected abstract void flushResourceACLs() throws EACLsException;
/**
- * an abstract class that enforces implementation of the
- * authorize() method that will authorize an operation on a
- * particular resource
- *
+ * an abstract class that enforces implementation of the authorize() method
+ * that will authorize an operation on a particular resource
+ *
* @param authToken the authToken associated with a user
* @param resource - the protected resource name
* @param operation - the protected resource operation name
diff --git a/pki/base/common/src/com/netscape/cms/authorization/BasicAclAuthz.java b/pki/base/common/src/com/netscape/cms/authorization/BasicAclAuthz.java
index 29cb671e..d2d29996 100644
--- a/pki/base/common/src/com/netscape/cms/authorization/BasicAclAuthz.java
+++ b/pki/base/common/src/com/netscape/cms/authorization/BasicAclAuthz.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.authorization;
-
// cert server imports.
import com.netscape.certsrv.acls.EACLsException;
import com.netscape.certsrv.apps.CMS;
@@ -31,14 +30,13 @@ import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.base.IExtendedPluginInfo;
import com.netscape.certsrv.logging.ILogger;
-
/**
* A class for basic acls authorization manager
- *
+ *
* @version $Revision$, $Date$
*/
public class BasicAclAuthz extends AAclAuthz
- implements IAuthzManager, IExtendedPluginInfo {
+ implements IAuthzManager, IExtendedPluginInfo {
// members
@@ -67,13 +65,14 @@ public class BasicAclAuthz extends AAclAuthz
*/
public BasicAclAuthz() {
- /* Holds configuration parameters accepted by this implementation.
- * This list is passed to the configuration console so configuration
- * for instances of this implementation can be configured through the
+ /*
+ * Holds configuration parameters accepted by this implementation. This
+ * list is passed to the configuration console so configuration for
+ * instances of this implementation can be configured through the
* console.
*/
mConfigParams =
- new String[] {
+ new String[] {
"dummy"
};
}
@@ -82,7 +81,7 @@ public class BasicAclAuthz extends AAclAuthz
*
*/
public void init(String name, String implName, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mName = name;
mImplName = implName;
mConfig = config;
@@ -108,20 +107,22 @@ public class BasicAclAuthz extends AAclAuthz
}
/**
- * check the authorization permission for the user associated with
- * authToken on operation
+ * check the authorization permission for the user associated with authToken
+ * on operation
* <p>
* Example:
* <p>
- * For example, if UsrGrpAdminServlet needs to authorize the caller
- * it would do be done in the following fashion:
+ * For example, if UsrGrpAdminServlet needs to authorize the caller it would
+ * do be done in the following fashion:
+ *
* <PRE>
- * try {
- * authzTok = mAuthz.authorize("DirACLBasedAuthz", authToken, RES_GROUP, "read");
- * } catch (EBaseException e) {
- * log(ILogger.LL_FAILURE, "authorize call: "+ e.toString());
- * }
- * </PRE>
+ * try {
+ * authzTok = mAuthz.authorize(&quot;DirACLBasedAuthz&quot;, authToken, RES_GROUP, &quot;read&quot;);
+ * } catch (EBaseException e) {
+ * log(ILogger.LL_FAILURE, &quot;authorize call: &quot; + e.toString());
+ * }
+ * </PRE>
+ *
* @param authToken the authToken associated with a user
* @param resource - the protected resource name
* @param operation - the protected resource operation name
@@ -130,7 +131,7 @@ public class BasicAclAuthz extends AAclAuthz
* @return authzToken if success
*/
public AuthzToken authorize(IAuthToken authToken, String resource, String operation)
- throws EAuthzInternalError, EAuthzAccessDenied {
+ throws EAuthzInternalError, EAuthzAccessDenied {
AuthzToken authzToken = new AuthzToken(this);
try {
@@ -142,11 +143,11 @@ public class BasicAclAuthz extends AAclAuthz
authzToken.set(AuthzToken.TOKEN_AUTHZ_RESOURCE, resource);
authzToken.set(AuthzToken.TOKEN_AUTHZ_OPERATION, operation);
authzToken.set(AuthzToken.TOKEN_AUTHZ_STATUS,
- AuthzToken.AUTHZ_STATUS_SUCCESS);
+ AuthzToken.AUTHZ_STATUS_SUCCESS);
} catch (EACLsException e) {
- // audit here later
+ // audit here later
log(ILogger.LL_FAILURE, CMS.getLogMessage("AUTHZ_EVALUATOR_AUTHORIZATION_FAILED"));
- String params[] = {resource, operation};
+ String params[] = { resource, operation };
throw new EAuthzAccessDenied(CMS.getUserMessage("CMS_AUTHORIZATION_AUTHZ_ACCESS_DENIED", params));
}
@@ -155,32 +156,33 @@ public class BasicAclAuthz extends AAclAuthz
}
public AuthzToken authorize(IAuthToken authToken, String expression)
- throws EAuthzAccessDenied {
+ throws EAuthzAccessDenied {
if (evaluateACLs(authToken, expression)) {
return (new AuthzToken(this));
} else {
- String params[] = {expression};
+ String params[] = { expression };
throw new EAuthzAccessDenied(CMS.getUserMessage("CMS_AUTHORIZATION_AUTHZ_ACCESS_DENIED", params));
}
}
/**
* This currently does not flush to permanent storage
+ *
* @param id is the resource id
- * @param strACLs
+ * @param strACLs
*/
public void updateACLs(String id, String rights, String strACLs,
- String desc) throws EACLsException {
+ String desc) throws EACLsException {
try {
super.updateACLs(id, rights, strACLs, desc);
- // flushResourceACLs();
+ // flushResourceACLs();
needsFlush = false;
} catch (EACLsException ex) {
// flushing failed, set flag
needsFlush = true;
String errMsg = "updateACLs: failed to flushResourceACLs(): "
- + ex.toString();
+ + ex.toString();
log(ILogger.LL_FAILURE, CMS.getLogMessage("AUTHZ_EVALUATOR_FLUSH_RESOURCES", ex.toString()));
@@ -189,8 +191,8 @@ public class BasicAclAuthz extends AAclAuthz
}
/**
- * updates resourceACLs to permanent storage.
- * currently not implemented for this authzMgr
+ * updates resourceACLs to permanent storage. currently not implemented for
+ * this authzMgr
*/
protected void flushResourceACLs() throws EACLsException {
log(ILogger.LL_FAILURE, "flushResourceACL() is not implemented");
@@ -198,7 +200,7 @@ public class BasicAclAuthz extends AAclAuthz
}
/**
- * graceful shutdown
+ * graceful shutdown
*/
public void shutdown() {
log(ILogger.LL_INFO, "shutting down");
@@ -206,6 +208,7 @@ public class BasicAclAuthz extends AAclAuthz
/**
* Logs a message for this class in the system log file.
+ *
* @param level The log level.
* @param msg The message to log.
* @see com.netscape.certsrv.logging.ILogger
@@ -214,6 +217,6 @@ public class BasicAclAuthz extends AAclAuthz
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_AUTHORIZATION,
- level, msg);
+ level, msg);
}
}
diff --git a/pki/base/common/src/com/netscape/cms/authorization/DirAclAuthz.java b/pki/base/common/src/com/netscape/cms/authorization/DirAclAuthz.java
index 820bf97b..0938b498 100644
--- a/pki/base/common/src/com/netscape/cms/authorization/DirAclAuthz.java
+++ b/pki/base/common/src/com/netscape/cms/authorization/DirAclAuthz.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.authorization;
-
import java.util.Enumeration;
import netscape.ldap.LDAPAttribute;
@@ -44,15 +43,14 @@ import com.netscape.certsrv.ldap.ELdapException;
import com.netscape.certsrv.ldap.ILdapConnFactory;
import com.netscape.certsrv.logging.ILogger;
-
/**
- * A class for ldap acls based authorization manager
- * The ldap server used for acls is the cms internal ldap db.
- *
+ * A class for ldap acls based authorization manager The ldap server used for
+ * acls is the cms internal ldap db.
+ *
* @version $Revision$, $Date$
*/
public class DirAclAuthz extends AAclAuthz
- implements IAuthzManager, IExtendedPluginInfo {
+ implements IAuthzManager, IExtendedPluginInfo {
// members
@@ -76,21 +74,21 @@ public class DirAclAuthz extends AAclAuthz
static {
mExtendedPluginInfo.add("ldap.ldapconn.host;string,required;" +
- "LDAP host to connect to");
+ "LDAP host to connect to");
mExtendedPluginInfo.add("ldap.ldapconn.port;number,required;" +
- "LDAP port number (use 389, or 636 if SSL)");
+ "LDAP port number (use 389, or 636 if SSL)");
mExtendedPluginInfo.add("ldap.ldapconn.secureConn;boolean;" +
- "Use SSL to connect to directory?");
+ "Use SSL to connect to directory?");
mExtendedPluginInfo.add("ldap.ldapconn.version;choice(3,2);" +
- "LDAP protocol version");
+ "LDAP protocol version");
mExtendedPluginInfo.add("ldap.basedn;string,required;Base DN to start sarching " +
- "under. If the ACL's DN is 'cn=resourceACL, o=NetscapeCertificateServer' you " +
- "might want to use 'o=NetscapeCertificateServer' here");
+ "under. If the ACL's DN is 'cn=resourceACL, o=NetscapeCertificateServer' you " +
+ "might want to use 'o=NetscapeCertificateServer' here");
mExtendedPluginInfo.add("ldap.minConns;number;number of connections " +
- "to keep open to directory server. Default 5.");
+ "to keep open to directory server. Default 5.");
mExtendedPluginInfo.add("ldap.maxConns;number;when needed, connection "
- +
- "pool can grow to this many (multiplexed) connections. Default 1000");
+ +
+ "pool can grow to this many (multiplexed) connections. Default 1000");
}
/**
@@ -98,20 +96,21 @@ public class DirAclAuthz extends AAclAuthz
*/
public DirAclAuthz() {
- /* Holds configuration parameters accepted by this implementation.
- * This list is passed to the configuration console so configuration
- * for instances of this implementation can be configured through the
+ /*
+ * Holds configuration parameters accepted by this implementation. This
+ * list is passed to the configuration console so configuration for
+ * instances of this implementation can be configured through the
* console.
*/
mConfigParams =
- new String[] {
- "ldap.ldapconn.host",
- "ldap.ldapconn.port",
- "ldap.ldapconn.secureConn",
- "ldap.ldapconn.version",
- "ldap.basedn",
- "ldap.minConns",
- "ldap.maxConns",
+ new String[] {
+ "ldap.ldapconn.host",
+ "ldap.ldapconn.port",
+ "ldap.ldapconn.secureConn",
+ "ldap.ldapconn.version",
+ "ldap.basedn",
+ "ldap.minConns",
+ "ldap.maxConns",
};
}
@@ -119,7 +118,7 @@ public class DirAclAuthz extends AAclAuthz
*
*/
public void init(String name, String implName, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mName = name;
mImplName = implName;
mConfig = config;
@@ -154,7 +153,7 @@ public class DirAclAuthz extends AAclAuthz
CMS.debug("DirAclAuthz: about to ldap search aclResources");
try {
conn = getConn();
- LDAPSearchResults res = conn.search(mBaseDN, LDAPv2.SCOPE_SUB,
+ LDAPSearchResults res = conn.search(mBaseDN, LDAPv2.SCOPE_SUB,
"cn=aclResources", null, false);
returnConn(conn);
@@ -165,7 +164,7 @@ public class DirAclAuthz extends AAclAuthz
LDAPAttribute aclRes = entry.getAttribute("resourceACLS");
@SuppressWarnings("unchecked")
- Enumeration<String> en = (Enumeration<String> )aclRes.getStringValues();
+ Enumeration<String> en = (Enumeration<String>) aclRes.getStringValues();
for (; en != null && en.hasMoreElements();) {
addACLs(en.nextElement());
@@ -200,20 +199,22 @@ public class DirAclAuthz extends AAclAuthz
}
/**
- * check the authorization permission for the user associated with
- * authToken on operation
+ * check the authorization permission for the user associated with authToken
+ * on operation
* <p>
* Example:
* <p>
- * For example, if UsrGrpAdminServlet needs to authorize the caller
- * it would do be done in the following fashion:
+ * For example, if UsrGrpAdminServlet needs to authorize the caller it would
+ * do be done in the following fashion:
+ *
* <PRE>
- * try {
- * authzTok = mAuthz.authorize("DirAclAuthz", authToken, RES_GROUP, "read");
- * } catch (EBaseException e) {
- * log(ILogger.LL_FAILURE, "authorize call: "+ e.toString());
- * }
- * </PRE>
+ * try {
+ * authzTok = mAuthz.authorize(&quot;DirAclAuthz&quot;, authToken, RES_GROUP, &quot;read&quot;);
+ * } catch (EBaseException e) {
+ * log(ILogger.LL_FAILURE, &quot;authorize call: &quot; + e.toString());
+ * }
+ * </PRE>
+ *
* @param authToken the authToken associated with a user
* @param resource - the protected resource name
* @param operation - the protected resource operation name
@@ -221,7 +222,7 @@ public class DirAclAuthz extends AAclAuthz
* @return authzToken
*/
public AuthzToken authorize(IAuthToken authToken, String resource, String operation)
- throws EAuthzInternalError, EAuthzAccessDenied {
+ throws EAuthzInternalError, EAuthzAccessDenied {
AuthzToken authzToken = new AuthzToken(this);
try {
@@ -232,42 +233,42 @@ public class DirAclAuthz extends AAclAuthz
authzToken.set(AuthzToken.TOKEN_AUTHZ_STATUS, AuthzToken.AUTHZ_STATUS_SUCCESS);
CMS.debug("DirAclAuthz: authorization passed");
} catch (EACLsException e) {
- // audit here later
+ // audit here later
log(ILogger.LL_FAILURE, CMS.getLogMessage("AUTHZ_EVALUATOR_AUTHORIZATION_FAILED"));
- String params[] = {resource, operation};
+ String params[] = { resource, operation };
throw new EAuthzAccessDenied(CMS.getUserMessage("CMS_AUTHORIZATION_AUTHZ_ACCESS_DENIED", params));
}
-
+
return authzToken;
}
public AuthzToken authorize(IAuthToken authToken, String expression)
- throws EAuthzAccessDenied {
+ throws EAuthzAccessDenied {
if (evaluateACLs(authToken, expression)) {
return (new AuthzToken(this));
} else {
- String params[] = {expression};
+ String params[] = { expression };
throw new EAuthzAccessDenied(CMS.getUserMessage("CMS_AUTHORIZATION_AUTHZ_ACCESS_DENIED", params));
}
}
/**
- * update acls. when memory update is done, flush to ldap.
+ * update acls. when memory update is done, flush to ldap.
* <p>
- * Currently, it is possible that when the memory is updated
- * successfully, and the ldap isn't, the memory upates lingers.
- * The result is that the changes will only be done on ldap at the
- * next update, or when the system shuts down, another flush will be
- * attempted.
+ * Currently, it is possible that when the memory is updated successfully,
+ * and the ldap isn't, the memory upates lingers. The result is that the
+ * changes will only be done on ldap at the next update, or when the system
+ * shuts down, another flush will be attempted.
+ *
* @param id is the resource id
* @param rights The allowable rights for this resource
- * @param strACLs has the same format as a resourceACLs entry acis
- * on the ldap server
+ * @param strACLs has the same format as a resourceACLs entry acis on the
+ * ldap server
* @param desc The description for this resource
*/
public void updateACLs(String id, String rights, String strACLs,
- String desc) throws EACLsException {
+ String desc) throws EACLsException {
try {
super.updateACLs(id, rights, strACLs, desc);
flushResourceACLs();
@@ -277,7 +278,7 @@ public class DirAclAuthz extends AAclAuthz
needsFlush = true;
String errMsg = "updateACLs: failed to flushResourceACLs(): "
- + ex.toString();
+ + ex.toString();
log(ILogger.LL_FAILURE, CMS.getLogMessage("AUTHZ_EVALUATOR_FLUSH_RESOURCES", ex.toString()));
@@ -335,7 +336,7 @@ public class DirAclAuthz extends AAclAuthz
}
/**
- * graceful shutdown
+ * graceful shutdown
*/
public void shutdown() {
if (needsFlush) {
@@ -351,13 +352,14 @@ public class DirAclAuthz extends AAclAuthz
try {
mLdapConnFactory.reset();
mLdapConnFactory = null;
- } catch (ELdapException e) {
+ } catch (ELdapException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("AUTHZ_EVALUATOR_LDAP_ERROR", e.toString()));
}
}
/**
* Logs a message for this class in the system log file.
+ *
* @param level The log level.
* @param msg The message to log.
* @see com.netscape.certsrv.logging.ILogger
@@ -366,6 +368,6 @@ public class DirAclAuthz extends AAclAuthz
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_AUTHORIZATION,
- level, msg);
+ level, msg);
}
}
diff --git a/pki/base/common/src/com/netscape/cms/crl/CMSAuthInfoAccessExtension.java b/pki/base/common/src/com/netscape/cms/crl/CMSAuthInfoAccessExtension.java
index 6fe802e7..19b6180d 100644
--- a/pki/base/common/src/com/netscape/cms/crl/CMSAuthInfoAccessExtension.java
+++ b/pki/base/common/src/com/netscape/cms/crl/CMSAuthInfoAccessExtension.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.crl;
-
import java.io.IOException;
import java.util.Locale;
@@ -38,14 +37,13 @@ import com.netscape.certsrv.ca.ICRLIssuingPoint;
import com.netscape.certsrv.common.NameValuePairs;
import com.netscape.certsrv.logging.ILogger;
-
/**
* This represents a Authority Information Access CRL extension.
- *
+ *
* @version $Revision$, $Date$
*/
public class CMSAuthInfoAccessExtension
- implements ICMSCRLExtension, IExtendedPluginInfo {
+ implements ICMSCRLExtension, IExtendedPluginInfo {
public static final String PROP_NUM_ADS = "numberOfAccessDescriptions";
public static final String PROP_ACCESS_METHOD = "accessMethod";
public static final String PROP_ACCESS_LOCATION_TYPE = "accessLocationType";
@@ -62,7 +60,7 @@ public class CMSAuthInfoAccessExtension
}
public Extension setCRLExtensionCriticality(Extension ext,
- boolean critical) {
+ boolean critical) {
AuthInfoAccessExtension authInfoAccessExt = (AuthInfoAccessExtension) ext;
authInfoAccessExt.setCritical(critical);
@@ -71,7 +69,7 @@ public class CMSAuthInfoAccessExtension
}
public Extension getCRLExtension(IConfigStore config, Object ip,
- boolean critical) {
+ boolean critical) {
ICRLIssuingPoint crlIssuingPoint = (ICRLIssuingPoint) ip;
AuthInfoAccessExtension authInfoAccessExt = new AuthInfoAccessExtension(critical);
@@ -138,7 +136,7 @@ public class CMSAuthInfoAccessExtension
String hostname = CMS.getEENonSSLHost();
String port = CMS.getEENonSSLPort();
if (hostname != null && port != null) {
- accessLocation = "http://"+hostname+":"+port+"/ca/ee/ca/getCAChain?op=downloadBIN";
+ accessLocation = "http://" + hostname + ":" + port + "/ca/ee/ca/getCAChain?op=downloadBIN";
}
URIName uriName = new URIName(accessLocation);
authInfoAccessExt.addAccessDescription(AuthInfoAccessExtension.METHOD_CA_ISSUERS, new GeneralName(uriName));
@@ -211,7 +209,7 @@ public class CMSAuthInfoAccessExtension
String hostname = CMS.getEENonSSLHost();
String port = CMS.getEENonSSLPort();
if (hostname != null && port != null) {
- accessLocation = "http://"+hostname+":"+port+"/ca/ee/ca/getCAChain?op=downloadBIN";
+ accessLocation = "http://" + hostname + ":" + port + "/ca/ee/ca/getCAChain?op=downloadBIN";
}
nvp.add(PROP_ACCESS_LOCATION + i, accessLocation);
}
@@ -224,32 +222,32 @@ public class CMSAuthInfoAccessExtension
"critical;boolean;Set criticality for Authority Information Access extension.",
PROP_NUM_ADS + ";number;Set number of Access Descriptions.",
PROP_ACCESS_METHOD + "0;choice(" + PROP_ACCESS_METHOD_CAISSUERS + "," +
- PROP_ACCESS_METHOD_OCSP +");Select access description method.",
+ PROP_ACCESS_METHOD_OCSP + ");Select access description method.",
PROP_ACCESS_LOCATION_TYPE + "0;choice(" + PROP_URINAME + "," +
- PROP_DIRNAME + ");Select access location type.",
+ PROP_DIRNAME + ");Select access location type.",
PROP_ACCESS_LOCATION + "0;string;Enter access location " +
- "corresponding to the selected access location type.",
+ "corresponding to the selected access location type.",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-ca-edit-crlextension-authorityinformationaccess",
+ ";configuration-ca-edit-crlextension-authorityinformationaccess",
PROP_ACCESS_METHOD + "1;choice(" + PROP_ACCESS_METHOD_CAISSUERS + "," +
- PROP_ACCESS_METHOD_OCSP +");Select access description method.",
+ PROP_ACCESS_METHOD_OCSP + ");Select access description method.",
PROP_ACCESS_LOCATION_TYPE + "1;choice(" + PROP_URINAME + "," +
- PROP_DIRNAME + ");Select access location type.",
+ PROP_DIRNAME + ");Select access location type.",
PROP_ACCESS_LOCATION + "1;string;Enter access location " +
- "corresponding to the selected access location type.",
+ "corresponding to the selected access location type.",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-ca-edit-crlextension-authorityinformationaccess",
+ ";configuration-ca-edit-crlextension-authorityinformationaccess",
PROP_ACCESS_METHOD + "2;choice(" + PROP_ACCESS_METHOD_CAISSUERS + "," +
- PROP_ACCESS_METHOD_OCSP +");Select access description method.",
+ PROP_ACCESS_METHOD_OCSP + ");Select access description method.",
PROP_ACCESS_LOCATION_TYPE + "2;choice(" + PROP_URINAME + "," +
- PROP_DIRNAME + ");Select access location type.",
+ PROP_DIRNAME + ");Select access location type.",
PROP_ACCESS_LOCATION + "2;string;Enter access location " +
- "corresponding to the selected access location type.",
+ "corresponding to the selected access location type.",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-ca-edit-crlextension-authorityinformationaccess",
+ ";configuration-ca-edit-crlextension-authorityinformationaccess",
IExtendedPluginInfo.HELP_TEXT +
- ";The Freshest CRL is a non critical CRL extension " +
- "that identifies the delta CRL distribution points for a particular CRL."
+ ";The Freshest CRL is a non critical CRL extension " +
+ "that identifies the delta CRL distribution points for a particular CRL."
};
return params;
@@ -257,6 +255,6 @@ public class CMSAuthInfoAccessExtension
private void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_CA, level,
- "CMSAuthInfoAccessExtension - " + msg);
+ "CMSAuthInfoAccessExtension - " + msg);
}
-}
+}
diff --git a/pki/base/common/src/com/netscape/cms/crl/CMSAuthorityKeyIdentifierExtension.java b/pki/base/common/src/com/netscape/cms/crl/CMSAuthorityKeyIdentifierExtension.java
index 4cdb0bdc..4981702a 100644
--- a/pki/base/common/src/com/netscape/cms/crl/CMSAuthorityKeyIdentifierExtension.java
+++ b/pki/base/common/src/com/netscape/cms/crl/CMSAuthorityKeyIdentifierExtension.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.crl;
-
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateParsingException;
@@ -43,21 +42,20 @@ import com.netscape.certsrv.ca.ICertificateAuthority;
import com.netscape.certsrv.common.NameValuePairs;
import com.netscape.certsrv.logging.ILogger;
-
/**
* This represents an authority key identifier extension.
- *
+ *
* @version $Revision$, $Date$
*/
public class CMSAuthorityKeyIdentifierExtension
- implements ICMSCRLExtension, IExtendedPluginInfo {
+ implements ICMSCRLExtension, IExtendedPluginInfo {
private ILogger mLogger = CMS.getLogger();
public CMSAuthorityKeyIdentifierExtension() {
}
public Extension setCRLExtensionCriticality(Extension ext,
- boolean critical) {
+ boolean critical) {
AuthorityKeyIdentifierExtension authKeyIdExt = null;
KeyIdentifier keyId = null;
GeneralNames names = null;
@@ -78,8 +76,8 @@ public class CMSAuthorityKeyIdentifierExtension
}
public Extension getCRLExtension(IConfigStore config,
- Object ip,
- boolean critical) {
+ Object ip,
+ boolean critical) {
AuthorityKeyIdentifierExtension authKeyIdExt = null;
ICRLIssuingPoint crlIssuingPoint = (ICRLIssuingPoint) ip;
@@ -88,12 +86,12 @@ public class CMSAuthorityKeyIdentifierExtension
try {
X509CertInfo info = (X509CertInfo)
- ((ICertificateAuthority) crlIssuingPoint.getCertificateAuthority()).getCACert().get(
- X509CertImpl.NAME + "." + X509CertImpl.INFO);
+ ((ICertificateAuthority) crlIssuingPoint.getCertificateAuthority()).getCACert().get(
+ X509CertImpl.NAME + "." + X509CertImpl.INFO);
if (info != null) {
- CertificateExtensions caCertExtensions = (CertificateExtensions)
- info.get(X509CertInfo.EXTENSIONS);
+ CertificateExtensions caCertExtensions = (CertificateExtensions)
+ info.get(X509CertInfo.EXTENSIONS);
if (caCertExtensions != null) {
for (int i = 0; i < caCertExtensions.size(); i++) {
@@ -101,7 +99,7 @@ public class CMSAuthorityKeyIdentifierExtension
if (caCertExt instanceof SubjectKeyIdentifierExtension) {
SubjectKeyIdentifierExtension id =
- (SubjectKeyIdentifierExtension) caCertExt;
+ (SubjectKeyIdentifierExtension) caCertExt;
keyId = (KeyIdentifier)
id.get(SubjectKeyIdentifierExtension.KEY_ID);
@@ -143,16 +141,16 @@ public class CMSAuthorityKeyIdentifierExtension
public String[] getExtendedPluginInfo(Locale locale) {
String[] params = {
- //"type;choice(CRLExtension,CRLEntryExtension);CRL Extension Type. "+
- //"This field is not editable.",
+ // "type;choice(CRLExtension,CRLEntryExtension);CRL Extension Type. "+
+ // "This field is not editable.",
"enable;boolean;Check to enable Authority Key Identifier CRL extension.",
"critical;boolean;Set criticality for Authority Key Identifier CRL extension.",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-ca-edit-crlextension-authoritykeyidentifier",
+ ";configuration-ca-edit-crlextension-authoritykeyidentifier",
IExtendedPluginInfo.HELP_TEXT +
- ";The authority key identifier extension provides a means " +
- "of identifying the public key corresponding to the private " +
- "key used to sign a CRL."
+ ";The authority key identifier extension provides a means " +
+ "of identifying the public key corresponding to the private " +
+ "key used to sign a CRL."
};
return params;
@@ -160,6 +158,6 @@ public class CMSAuthorityKeyIdentifierExtension
private void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_CA, level,
- "CMSAuthorityKeyIdentifierExtension - " + msg);
+ "CMSAuthorityKeyIdentifierExtension - " + msg);
}
-}
+}
diff --git a/pki/base/common/src/com/netscape/cms/crl/CMSCRLNumberExtension.java b/pki/base/common/src/com/netscape/cms/crl/CMSCRLNumberExtension.java
index e4bb4cb6..958a4d56 100644
--- a/pki/base/common/src/com/netscape/cms/crl/CMSCRLNumberExtension.java
+++ b/pki/base/common/src/com/netscape/cms/crl/CMSCRLNumberExtension.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.crl;
-
import java.io.IOException;
import java.math.BigInteger;
import java.util.Locale;
@@ -34,21 +33,20 @@ import com.netscape.certsrv.ca.ICRLIssuingPoint;
import com.netscape.certsrv.common.NameValuePairs;
import com.netscape.certsrv.logging.ILogger;
-
/**
* This represents a CRL number extension.
- *
+ *
* @version $Revision$, $Date$
*/
public class CMSCRLNumberExtension
- implements ICMSCRLExtension, IExtendedPluginInfo {
+ implements ICMSCRLExtension, IExtendedPluginInfo {
private ILogger mLogger = CMS.getLogger();
public CMSCRLNumberExtension() {
}
public Extension setCRLExtensionCriticality(Extension ext,
- boolean critical) {
+ boolean critical) {
BigInteger crlNumber = null;
CRLNumberExtension crlNumberExt = null;
@@ -64,8 +62,8 @@ public class CMSCRLNumberExtension
}
public Extension getCRLExtension(IConfigStore config,
- Object ip,
- boolean critical) {
+ Object ip,
+ boolean critical) {
CRLNumberExtension crlNumberExt = null;
ICRLIssuingPoint crlIssuingPoint = (ICRLIssuingPoint) ip;
@@ -87,16 +85,16 @@ public class CMSCRLNumberExtension
public String[] getExtendedPluginInfo(Locale locale) {
String[] params = {
- //"type;choice(CRLExtension,CRLEntryExtension);"+
- //"CRL Extension type. This field is not editable.",
+ // "type;choice(CRLExtension,CRLEntryExtension);"+
+ // "CRL Extension type. This field is not editable.",
"enable;boolean;Check to enable CRL Number extension.",
"critical;boolean;Set criticality for CRL Number extension.",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-ca-edit-crlextension-crlnumber",
+ ";configuration-ca-edit-crlextension-crlnumber",
IExtendedPluginInfo.HELP_TEXT +
- ";The CRL number is a non-critical CRL extension " +
- "which conveys a monotonically increasing sequence number " +
- "for each CRL issued by a CA"
+ ";The CRL number is a non-critical CRL extension " +
+ "which conveys a monotonically increasing sequence number " +
+ "for each CRL issued by a CA"
};
return params;
@@ -104,6 +102,6 @@ public class CMSCRLNumberExtension
private void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_CA, level,
- "CMSCRLNumberExtension - " + msg);
+ "CMSCRLNumberExtension - " + msg);
}
-}
+}
diff --git a/pki/base/common/src/com/netscape/cms/crl/CMSCRLReasonExtension.java b/pki/base/common/src/com/netscape/cms/crl/CMSCRLReasonExtension.java
index 245428a6..614d672d 100644
--- a/pki/base/common/src/com/netscape/cms/crl/CMSCRLReasonExtension.java
+++ b/pki/base/common/src/com/netscape/cms/crl/CMSCRLReasonExtension.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.crl;
-
import java.io.IOException;
import java.util.Locale;
@@ -33,21 +32,20 @@ import com.netscape.certsrv.ca.ICMSCRLExtension;
import com.netscape.certsrv.common.NameValuePairs;
import com.netscape.certsrv.logging.ILogger;
-
/**
* This represents a CRL reason extension.
- *
+ *
* @version $Revision$, $Date$
*/
public class CMSCRLReasonExtension
- implements ICMSCRLExtension, IExtendedPluginInfo {
+ implements ICMSCRLExtension, IExtendedPluginInfo {
private ILogger mLogger = CMS.getLogger();
public CMSCRLReasonExtension() {
}
public Extension setCRLExtensionCriticality(Extension ext,
- boolean critical) {
+ boolean critical) {
RevocationReason reason = null;
CRLReasonExtension crlReasonExt = null;
@@ -61,8 +59,8 @@ public class CMSCRLReasonExtension
}
public Extension getCRLExtension(IConfigStore config,
- Object crlIssuingPoint,
- boolean critical) {
+ Object crlIssuingPoint,
+ boolean critical) {
CRLReasonExtension crlReasonExt = null;
return crlReasonExt;
@@ -77,15 +75,15 @@ public class CMSCRLReasonExtension
public String[] getExtendedPluginInfo(Locale locale) {
String[] params = {
- //"type;choice(CRLExtension,CRLEntryExtension);"+
- //"CRL Entry Extension type. This field is not editable.",
+ // "type;choice(CRLExtension,CRLEntryExtension);"+
+ // "CRL Entry Extension type. This field is not editable.",
"enable;boolean;Check to enable reason code CRL entry extension.",
"critical;boolean;Set criticality for reason code CRL entry extension.",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-ca-edit-crlextension-crlreason",
+ ";configuration-ca-edit-crlextension-crlreason",
IExtendedPluginInfo.HELP_TEXT +
- ";The CRL reason code is a non-critical CRL entry extension " +
- "that identifies the reason for the certificate revocation."
+ ";The CRL reason code is a non-critical CRL entry extension " +
+ "that identifies the reason for the certificate revocation."
};
return params;
@@ -93,6 +91,6 @@ public class CMSCRLReasonExtension
private void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_CA, level,
- "CMSCRLReasonExtension - " + msg);
+ "CMSCRLReasonExtension - " + msg);
}
-}
+}
diff --git a/pki/base/common/src/com/netscape/cms/crl/CMSCertificateIssuerExtension.java b/pki/base/common/src/com/netscape/cms/crl/CMSCertificateIssuerExtension.java
index 601e15d2..4d8fc8b9 100644
--- a/pki/base/common/src/com/netscape/cms/crl/CMSCertificateIssuerExtension.java
+++ b/pki/base/common/src/com/netscape/cms/crl/CMSCertificateIssuerExtension.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.crl;
-
import java.io.IOException;
import java.util.Locale;
@@ -40,18 +39,18 @@ import com.netscape.certsrv.logging.ILogger;
/**
* This represents a certificate issuer extension.
- *
+ *
* @version $Revision$, $Date$
*/
public class CMSCertificateIssuerExtension
- implements ICMSCRLExtension, IExtendedPluginInfo {
+ implements ICMSCRLExtension, IExtendedPluginInfo {
private ILogger mLogger = CMS.getLogger();
public CMSCertificateIssuerExtension() {
}
public Extension setCRLExtensionCriticality(Extension ext,
- boolean critical) {
+ boolean critical) {
CertificateIssuerExtension certIssuerExt = null;
GeneralNames names = null;
@@ -67,8 +66,8 @@ public class CMSCertificateIssuerExtension
}
public Extension getCRLExtension(IConfigStore config,
- Object ip,
- boolean critical) {
+ Object ip,
+ boolean critical) {
CertificateIssuerExtension certIssuerExt = null;
int numNames = 0;
@@ -195,8 +194,8 @@ public class CMSCertificateIssuerExtension
public String[] getExtendedPluginInfo(Locale locale) {
String[] params = {
- //"type;choice(CRLExtension,CRLEntryExtension);CRL Entry Extension type."+
- //" This field is not editable.",
+ // "type;choice(CRLExtension,CRLEntryExtension);CRL Entry Extension type."+
+ // " This field is not editable.",
"enable;boolean;Check to enable Certificate Issuer CRL entry extension.",
"critical;boolean;Set criticality for Certificate Issuer CRL entry extension.",
"numNames;number;Set number of certificate issuer names for the CRL entry.",
@@ -207,10 +206,10 @@ public class CMSCertificateIssuerExtension
"nameType2;choice(DirectoryName,URI);Select Certificate Issuer name type.",
"name2;string;Enter Certificate Issuer name corresponding to the selected name type.",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-ca-edit-crlextension-certificateissuer",
+ ";configuration-ca-edit-crlextension-certificateissuer",
IExtendedPluginInfo.HELP_TEXT +
- ";This CRL entry extension identifies the certificate issuer" +
- " associated with an entry in an indirect CRL."
+ ";This CRL entry extension identifies the certificate issuer" +
+ " associated with an entry in an indirect CRL."
};
return params;
@@ -219,4 +218,4 @@ public class CMSCertificateIssuerExtension
private void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_CA, level, msg);
}
-}
+}
diff --git a/pki/base/common/src/com/netscape/cms/crl/CMSDeltaCRLIndicatorExtension.java b/pki/base/common/src/com/netscape/cms/crl/CMSDeltaCRLIndicatorExtension.java
index 35d21e5c..e3290c34 100644
--- a/pki/base/common/src/com/netscape/cms/crl/CMSDeltaCRLIndicatorExtension.java
+++ b/pki/base/common/src/com/netscape/cms/crl/CMSDeltaCRLIndicatorExtension.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.crl;
-
import java.io.IOException;
import java.math.BigInteger;
import java.util.Locale;
@@ -34,21 +33,20 @@ import com.netscape.certsrv.ca.ICRLIssuingPoint;
import com.netscape.certsrv.common.NameValuePairs;
import com.netscape.certsrv.logging.ILogger;
-
/**
* This represents a delta CRL indicator extension.
- *
+ *
* @version $Revision$, $Date$
*/
public class CMSDeltaCRLIndicatorExtension
- implements ICMSCRLExtension, IExtendedPluginInfo {
+ implements ICMSCRLExtension, IExtendedPluginInfo {
private ILogger mLogger = CMS.getLogger();
public CMSDeltaCRLIndicatorExtension() {
}
public Extension setCRLExtensionCriticality(Extension ext,
- boolean critical) {
+ boolean critical) {
BigInteger baseCRLNumber = null;
DeltaCRLIndicatorExtension deltaCRLIndicatorExt = null;
@@ -65,8 +63,8 @@ public class CMSDeltaCRLIndicatorExtension
}
public Extension getCRLExtension(IConfigStore config,
- Object ip,
- boolean critical) {
+ Object ip,
+ boolean critical) {
DeltaCRLIndicatorExtension deltaCRLIndicatorExt = null;
ICRLIssuingPoint crlIssuingPoint = (ICRLIssuingPoint) ip;
@@ -89,15 +87,15 @@ public class CMSDeltaCRLIndicatorExtension
public String[] getExtendedPluginInfo(Locale locale) {
String[] params = {
- //"type;choice(CRLExtension,CRLEntryExtension);"+
- //"CRL Extension type. This field is not editable.",
+ // "type;choice(CRLExtension,CRLEntryExtension);"+
+ // "CRL Extension type. This field is not editable.",
"enable;boolean;Check to enable Delta CRL Indicator extension.",
"critical;boolean;Set criticality for Delta CRL Indicator extension.",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-ca-edit-crlextension-crlnumber",
+ ";configuration-ca-edit-crlextension-crlnumber",
IExtendedPluginInfo.HELP_TEXT +
- ";The Delta CRL Indicator is a critical CRL extension " +
- "which identifies a delta-CRL."
+ ";The Delta CRL Indicator is a critical CRL extension " +
+ "which identifies a delta-CRL."
};
return params;
@@ -105,7 +103,6 @@ public class CMSDeltaCRLIndicatorExtension
private void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_CA, level,
- "CMSDeltaCRLIndicatorExtension - " + msg);
+ "CMSDeltaCRLIndicatorExtension - " + msg);
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/crl/CMSFreshestCRLExtension.java b/pki/base/common/src/com/netscape/cms/crl/CMSFreshestCRLExtension.java
index 86bdd05e..38eb7a1c 100644
--- a/pki/base/common/src/com/netscape/cms/crl/CMSFreshestCRLExtension.java
+++ b/pki/base/common/src/com/netscape/cms/crl/CMSFreshestCRLExtension.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.crl;
-
import java.io.IOException;
import java.util.Locale;
@@ -40,14 +39,13 @@ import com.netscape.certsrv.ca.ICRLIssuingPoint;
import com.netscape.certsrv.common.NameValuePairs;
import com.netscape.certsrv.logging.ILogger;
-
/**
* This represents a freshest CRL extension.
- *
+ *
* @version $Revision$, $Date$
*/
public class CMSFreshestCRLExtension
- implements ICMSCRLExtension, IExtendedPluginInfo {
+ implements ICMSCRLExtension, IExtendedPluginInfo {
public static final String PROP_NUM_POINTS = "numPoints";
public static final String PROP_POINTTYPE = "pointType";
public static final String PROP_POINTNAME = "pointName";
@@ -60,7 +58,7 @@ public class CMSFreshestCRLExtension
}
public Extension setCRLExtensionCriticality(Extension ext,
- boolean critical) {
+ boolean critical) {
FreshestCRLExtension freshestCRLExt = (FreshestCRLExtension) ext;
freshestCRLExt.setCritical(critical);
@@ -69,7 +67,7 @@ public class CMSFreshestCRLExtension
}
public Extension getCRLExtension(IConfigStore config, Object ip,
- boolean critical) {
+ boolean critical) {
ICRLIssuingPoint crlIssuingPoint = (ICRLIssuingPoint) ip;
FreshestCRLExtension freshestCRLExt = null;
@@ -159,7 +157,7 @@ public class CMSFreshestCRLExtension
numPoints = config.getInteger(PROP_NUM_POINTS, 0);
} catch (EBaseException e) {
log(ILogger.LL_FAILURE, "Invalid numPoints property for CRL " +
- "Freshest CRL extension - " + e);
+ "Freshest CRL extension - " + e);
}
nvp.add(PROP_NUM_POINTS, String.valueOf(numPoints));
@@ -204,26 +202,26 @@ public class CMSFreshestCRLExtension
"critical;boolean;Set criticality for Freshest CRL extension.",
PROP_NUM_POINTS + ";number;Set number of CRL distribution points.",
PROP_POINTTYPE + "0;choice(" + PROP_DIRNAME + "," + PROP_URINAME +
- ");Select CRL distribution point name type.",
+ ");Select CRL distribution point name type.",
PROP_POINTNAME + "0;string;Enter CRL distribution point name " +
- "corresponding to the selected point type.",
+ "corresponding to the selected point type.",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-ca-edit-crlextension-issuingdistributionpoint",
+ ";configuration-ca-edit-crlextension-issuingdistributionpoint",
PROP_POINTTYPE + "1;choice(" + PROP_DIRNAME + "," + PROP_URINAME +
- ");Select CRL distribution point name type.",
+ ");Select CRL distribution point name type.",
PROP_POINTNAME + "1;string;Enter CRL distribution point name " +
- "corresponding to the selected point type.",
+ "corresponding to the selected point type.",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-ca-edit-crlextension-issuingdistributionpoint",
+ ";configuration-ca-edit-crlextension-issuingdistributionpoint",
PROP_POINTTYPE + "2;choice(" + PROP_DIRNAME + "," + PROP_URINAME +
- ");Select CRL distribution point name type.",
+ ");Select CRL distribution point name type.",
PROP_POINTNAME + "2;string;Enter CRL distribution point name " +
- "corresponding to the selected point type.",
+ "corresponding to the selected point type.",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-ca-edit-crlextension-issuingdistributionpoint",
+ ";configuration-ca-edit-crlextension-issuingdistributionpoint",
IExtendedPluginInfo.HELP_TEXT +
- ";The Freshest CRL is a non critical CRL extension " +
- "that identifies the delta CRL distribution points for a particular CRL."
+ ";The Freshest CRL is a non critical CRL extension " +
+ "that identifies the delta CRL distribution points for a particular CRL."
};
return params;
@@ -231,6 +229,6 @@ public class CMSFreshestCRLExtension
private void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_CA, level,
- "CMSFreshestCRLExtension - " + msg);
+ "CMSFreshestCRLExtension - " + msg);
}
-}
+}
diff --git a/pki/base/common/src/com/netscape/cms/crl/CMSHoldInstructionExtension.java b/pki/base/common/src/com/netscape/cms/crl/CMSHoldInstructionExtension.java
index e0e39b8a..04e5468d 100644
--- a/pki/base/common/src/com/netscape/cms/crl/CMSHoldInstructionExtension.java
+++ b/pki/base/common/src/com/netscape/cms/crl/CMSHoldInstructionExtension.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.crl;
-
import java.io.IOException;
import java.util.Locale;
@@ -36,14 +35,13 @@ import com.netscape.certsrv.ca.ICRLIssuingPoint;
import com.netscape.certsrv.common.NameValuePairs;
import com.netscape.certsrv.logging.ILogger;
-
/**
* This represents a hold instruction extension.
- *
+ *
* @version $Revision$, $Date$
*/
public class CMSHoldInstructionExtension
- implements ICMSCRLExtension, IExtendedPluginInfo {
+ implements ICMSCRLExtension, IExtendedPluginInfo {
public static final String PROP_INSTR = "instruction";
public static final String PROP_INSTR_NONE = "none";
public static final String PROP_INSTR_CALLISSUER = "callissuer";
@@ -55,12 +53,12 @@ public class CMSHoldInstructionExtension
}
public Extension setCRLExtensionCriticality(Extension ext,
- boolean critical) {
+ boolean critical) {
HoldInstructionExtension holdInstrExt = null;
try {
ObjectIdentifier holdInstr =
- ((HoldInstructionExtension) ext).getHoldInstructionCode();
+ ((HoldInstructionExtension) ext).getHoldInstructionCode();
holdInstrExt = new HoldInstructionExtension(Boolean.valueOf(critical),
holdInstr);
@@ -71,8 +69,8 @@ public class CMSHoldInstructionExtension
}
public Extension getCRLExtension(IConfigStore config,
- Object ip,
- boolean critical) {
+ Object ip,
+ boolean critical) {
HoldInstructionExtension holdInstrExt = null;
String instruction = null;
@@ -121,8 +119,7 @@ public class CMSHoldInstructionExtension
}
if (instruction != null) {
if (!(instruction.equalsIgnoreCase(PROP_INSTR_NONE) ||
- instruction.equalsIgnoreCase(PROP_INSTR_CALLISSUER) ||
- instruction.equalsIgnoreCase(PROP_INSTR_REJECT))) {
+ instruction.equalsIgnoreCase(PROP_INSTR_CALLISSUER) || instruction.equalsIgnoreCase(PROP_INSTR_REJECT))) {
instruction = PROP_INSTR_NONE;
}
} else {
@@ -133,19 +130,19 @@ public class CMSHoldInstructionExtension
public String[] getExtendedPluginInfo(Locale locale) {
String[] params = {
- //"type;choice(CRLExtension,CRLEntryExtension);"+
- //"CRL Entry Extension type. This field is not editable.",
+ // "type;choice(CRLExtension,CRLEntryExtension);"+
+ // "CRL Entry Extension type. This field is not editable.",
"enable;boolean;Check to enable Hold Instruction CRL entry extension.",
"critical;boolean;Set criticality for Hold Instruction CRL entry extension.",
PROP_INSTR + ";choice(" + PROP_INSTR_NONE + "," + PROP_INSTR_CALLISSUER + "," +
- PROP_INSTR_REJECT + ");Select hold instruction code.",
+ PROP_INSTR_REJECT + ");Select hold instruction code.",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-ca-edit-crlextension-holdinstruction",
+ ";configuration-ca-edit-crlextension-holdinstruction",
IExtendedPluginInfo.HELP_TEXT +
- ";The hold instruction code is a non-critical CRL entry " +
- "extension that provides a registered instruction identifier " +
- "which indicates the action to be taken after encountering " +
- "a certificate that has been placed on hold."
+ ";The hold instruction code is a non-critical CRL entry " +
+ "extension that provides a registered instruction identifier " +
+ "which indicates the action to be taken after encountering " +
+ "a certificate that has been placed on hold."
};
return params;
@@ -153,6 +150,6 @@ public class CMSHoldInstructionExtension
private void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_CA, level,
- "CMSHoldInstructionExtension - " + msg);
+ "CMSHoldInstructionExtension - " + msg);
}
-}
+}
diff --git a/pki/base/common/src/com/netscape/cms/crl/CMSInvalidityDateExtension.java b/pki/base/common/src/com/netscape/cms/crl/CMSInvalidityDateExtension.java
index c0c62244..2f885262 100644
--- a/pki/base/common/src/com/netscape/cms/crl/CMSInvalidityDateExtension.java
+++ b/pki/base/common/src/com/netscape/cms/crl/CMSInvalidityDateExtension.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.crl;
-
import java.io.IOException;
import java.util.Date;
import java.util.Locale;
@@ -33,21 +32,20 @@ import com.netscape.certsrv.ca.ICMSCRLExtension;
import com.netscape.certsrv.common.NameValuePairs;
import com.netscape.certsrv.logging.ILogger;
-
/**
* This represents a invalidity date extension.
- *
+ *
* @version $Revision$, $Date$
*/
public class CMSInvalidityDateExtension
- implements ICMSCRLExtension, IExtendedPluginInfo {
+ implements ICMSCRLExtension, IExtendedPluginInfo {
private ILogger mLogger = CMS.getLogger();
public CMSInvalidityDateExtension() {
}
public Extension setCRLExtensionCriticality(Extension ext,
- boolean critical) {
+ boolean critical) {
InvalidityDateExtension invalidityDateExt = null;
try {
@@ -62,8 +60,8 @@ public class CMSInvalidityDateExtension
}
public Extension getCRLExtension(IConfigStore config,
- Object crlIssuingPoint,
- boolean critical) {
+ Object crlIssuingPoint,
+ boolean critical) {
InvalidityDateExtension invalidityDateExt = null;
return invalidityDateExt;
@@ -78,17 +76,17 @@ public class CMSInvalidityDateExtension
public String[] getExtendedPluginInfo(Locale locale) {
String[] params = {
- //"type;choice(CRLExtension,CRLEntryExtension);"+
- //"CRL Entry Extension type. This field is not editable.",
+ // "type;choice(CRLExtension,CRLEntryExtension);"+
+ // "CRL Entry Extension type. This field is not editable.",
"enable;boolean;Check to enable Invalidity Date CRL entry extension.",
"critical;boolean;Set criticality for Invalidity Date CRL entry extension.",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-ca-edit-crlextension-invaliditydate",
+ ";configuration-ca-edit-crlextension-invaliditydate",
IExtendedPluginInfo.HELP_TEXT +
- ";The invalidity date is a non-critical CRL entry extension " +
- "that provides the date on which it is known or suspected " +
- "that the private key was compromised or that the certificate" +
- " otherwise became invalid."
+ ";The invalidity date is a non-critical CRL entry extension " +
+ "that provides the date on which it is known or suspected " +
+ "that the private key was compromised or that the certificate" +
+ " otherwise became invalid."
};
return params;
@@ -96,6 +94,6 @@ public class CMSInvalidityDateExtension
private void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_CA, level,
- "CMSInvalidityDateExtension - " + msg);
+ "CMSInvalidityDateExtension - " + msg);
}
-}
+}
diff --git a/pki/base/common/src/com/netscape/cms/crl/CMSIssuerAlternativeNameExtension.java b/pki/base/common/src/com/netscape/cms/crl/CMSIssuerAlternativeNameExtension.java
index 9ca9d5d2..428fb447 100644
--- a/pki/base/common/src/com/netscape/cms/crl/CMSIssuerAlternativeNameExtension.java
+++ b/pki/base/common/src/com/netscape/cms/crl/CMSIssuerAlternativeNameExtension.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.crl;
-
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Locale;
@@ -47,14 +46,13 @@ import com.netscape.certsrv.ca.ICRLIssuingPoint;
import com.netscape.certsrv.common.NameValuePairs;
import com.netscape.certsrv.logging.ILogger;
-
/**
* This represents a issuer alternative name extension.
- *
+ *
* @version $Revision$, $Date$
*/
public class CMSIssuerAlternativeNameExtension
- implements ICMSCRLExtension, IExtendedPluginInfo {
+ implements ICMSCRLExtension, IExtendedPluginInfo {
private static final String PROP_RFC822_NAME = "rfc822Name";
private static final String PROP_DNS_NAME = "dNSName";
private static final String PROP_DIR_NAME = "directoryName";
@@ -70,7 +68,7 @@ public class CMSIssuerAlternativeNameExtension
}
public Extension setCRLExtensionCriticality(Extension ext,
- boolean critical) {
+ boolean critical) {
IssuerAlternativeNameExtension issuerAltNameExt = null;
GeneralNames names = null;
@@ -84,8 +82,8 @@ public class CMSIssuerAlternativeNameExtension
}
public Extension getCRLExtension(IConfigStore config,
- Object ip,
- boolean critical) {
+ Object ip,
+ boolean critical) {
ICRLIssuingPoint crlIssuingPoint = (ICRLIssuingPoint) ip;
IssuerAlternativeNameExtension issuerAltNameExt = null;
int numNames = 0;
@@ -196,7 +194,7 @@ public class CMSIssuerAlternativeNameExtension
numNames = config.getInteger("numNames", 0);
} catch (EBaseException e) {
log(ILogger.LL_FAILURE, "Invalid numNames property for CRL " +
- "IssuerAlternativeName extension - " + e);
+ "IssuerAlternativeName extension - " + e);
}
nvp.add("numNames", String.valueOf(numNames));
@@ -207,10 +205,10 @@ public class CMSIssuerAlternativeNameExtension
nameType = config.getString("nameType" + i);
} catch (EPropertyNotFound e) {
log(ILogger.LL_FAILURE, "Undefined nameType" + i + " property for " +
- "CRL IssuerAlternativeName extension - " + e);
+ "CRL IssuerAlternativeName extension - " + e);
} catch (EBaseException e) {
log(ILogger.LL_FAILURE, "Invalid nameType" + i + " property for " +
- "CRL IssuerAlternativeName extension - " + e);
+ "CRL IssuerAlternativeName extension - " + e);
}
if (nameType != null && nameType.length() > 0) {
@@ -225,10 +223,10 @@ public class CMSIssuerAlternativeNameExtension
name = config.getString("name" + i);
} catch (EPropertyNotFound e) {
log(ILogger.LL_FAILURE, "Undefined name" + i + " property for " +
- "CRL IssuerAlternativeName extension - " + e);
+ "CRL IssuerAlternativeName extension - " + e);
} catch (EBaseException e) {
log(ILogger.LL_FAILURE, "Invalid name" + i + " property for " +
- "CRL IssuerAlternativeName extension - " + e);
+ "CRL IssuerAlternativeName extension - " + e);
}
if (name != null && name.length() > 0) {
@@ -248,28 +246,28 @@ public class CMSIssuerAlternativeNameExtension
public String[] getExtendedPluginInfo(Locale locale) {
String[] params = {
- //"type;choice(CRLExtension,CRLEntryExtension);"+
- //"CRL Extension type. This field is not editable.",
+ // "type;choice(CRLExtension,CRLEntryExtension);"+
+ // "CRL Extension type. This field is not editable.",
"enable;boolean;Check to enable Issuer Alternative Name CRL extension.",
"critical;boolean;Set criticality for Issuer Alternative Name CRL extension.",
"numNames;number;Set number of alternative names for the CRL issuer.",
"nameType0;choice(" + PROP_RFC822_NAME + "," + PROP_DIR_NAME + "," + PROP_DNS_NAME + "," +
- PROP_EDI_NAME + "," + PROP_URI_NAME + "," + PROP_IP_NAME + "," + PROP_OID_NAME + "," +
- PROP_OTHER_NAME + ");Select Issuer Alternative Name type.",
+ PROP_EDI_NAME + "," + PROP_URI_NAME + "," + PROP_IP_NAME + "," + PROP_OID_NAME + "," +
+ PROP_OTHER_NAME + ");Select Issuer Alternative Name type.",
"name0;string;Enter Issuer Alternative Name corresponding to the selected name type.",
"nameType1;choice(" + PROP_RFC822_NAME + "," + PROP_DIR_NAME + "," + PROP_DNS_NAME + "," +
- PROP_EDI_NAME + "," + PROP_URI_NAME + "," + PROP_IP_NAME + "," + PROP_OID_NAME + "," +
- PROP_OTHER_NAME + ");Select Issuer Alternative Name type.",
+ PROP_EDI_NAME + "," + PROP_URI_NAME + "," + PROP_IP_NAME + "," + PROP_OID_NAME + "," +
+ PROP_OTHER_NAME + ");Select Issuer Alternative Name type.",
"name1;string;Enter Issuer Alternative Name corresponding to the selected name type.",
"nameType2;choice(" + PROP_RFC822_NAME + "," + PROP_DIR_NAME + "," + PROP_DNS_NAME + "," +
- PROP_EDI_NAME + "," + PROP_URI_NAME + "," + PROP_IP_NAME + "," + PROP_OID_NAME + "," +
- PROP_OTHER_NAME + ");Select Issuer Alternative Name type.",
+ PROP_EDI_NAME + "," + PROP_URI_NAME + "," + PROP_IP_NAME + "," + PROP_OID_NAME + "," +
+ PROP_OTHER_NAME + ");Select Issuer Alternative Name type.",
"name2;string;Enter Issuer Alternative Name corresponding to the selected name type.",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-ca-edit-crlextension-issueralternativename",
+ ";configuration-ca-edit-crlextension-issueralternativename",
IExtendedPluginInfo.HELP_TEXT +
- ";The issuer alternative names extension allows additional" +
- " identities to be associated with the issuer of the CRL."
+ ";The issuer alternative names extension allows additional" +
+ " identities to be associated with the issuer of the CRL."
};
return params;
@@ -277,6 +275,6 @@ public class CMSIssuerAlternativeNameExtension
private void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_CA, level,
- "CMSIssuerAlternativeNameExtension - " + msg);
+ "CMSIssuerAlternativeNameExtension - " + msg);
}
-}
+}
diff --git a/pki/base/common/src/com/netscape/cms/crl/CMSIssuingDistributionPointExtension.java b/pki/base/common/src/com/netscape/cms/crl/CMSIssuingDistributionPointExtension.java
index ccc5b64d..498e358c 100644
--- a/pki/base/common/src/com/netscape/cms/crl/CMSIssuingDistributionPointExtension.java
+++ b/pki/base/common/src/com/netscape/cms/crl/CMSIssuingDistributionPointExtension.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.crl;
-
import java.io.IOException;
import java.util.Locale;
import java.util.StringTokenizer;
@@ -43,14 +42,13 @@ import com.netscape.certsrv.ca.ICRLIssuingPoint;
import com.netscape.certsrv.common.NameValuePairs;
import com.netscape.certsrv.logging.ILogger;
-
/**
* This represents a issuing distribution point extension.
- *
+ *
* @version $Revision$, $Date$
*/
public class CMSIssuingDistributionPointExtension
- implements ICMSCRLExtension, IExtendedPluginInfo {
+ implements ICMSCRLExtension, IExtendedPluginInfo {
public static final String PROP_POINTTYPE = "pointType";
public static final String PROP_POINTNAME = "pointName";
public static final String PROP_DIRNAME = "DirectoryName";
@@ -61,14 +59,14 @@ public class CMSIssuingDistributionPointExtension
public static final String PROP_INDIRECT = "indirectCRL";
public static final String PROP_REASONS = "onlySomeReasons";
- private static final String[] reasonFlags = {"unused",
+ private static final String[] reasonFlags = { "unused",
"keyCompromise",
"cACompromise",
"affiliationChanged",
"superseded",
"cessationOfOperation",
"certificateHold",
- "privilegeWithdrawn"};
+ "privilegeWithdrawn" };
private ILogger mLogger = CMS.getLogger();
@@ -76,9 +74,9 @@ public class CMSIssuingDistributionPointExtension
}
public Extension setCRLExtensionCriticality(Extension ext,
- boolean critical) {
+ boolean critical) {
IssuingDistributionPointExtension issuingDPointExt =
- (IssuingDistributionPointExtension) ext;
+ (IssuingDistributionPointExtension) ext;
issuingDPointExt.setCritical(critical);
@@ -86,8 +84,8 @@ public class CMSIssuingDistributionPointExtension
}
public Extension getCRLExtension(IConfigStore config,
- Object ip,
- boolean critical) {
+ Object ip,
+ boolean critical) {
CMS.debug("in CMSIssuingDistributionPointExtension::getCRLExtension.");
ICRLIssuingPoint crlIssuingPoint = (ICRLIssuingPoint) ip;
@@ -164,7 +162,7 @@ public class CMSIssuingDistributionPointExtension
}
if (reasons != null && reasons.length() > 0) {
- boolean[] bits = {false, false, false, false, false, false, false};
+ boolean[] bits = { false, false, false, false, false, false, false };
int k = 0;
StringTokenizer st = new StringTokenizer(reasons, ",");
@@ -275,25 +273,22 @@ public class CMSIssuingDistributionPointExtension
log(ILogger.LL_FAILURE, CMS.getLogMessage("CRL_INVALID_PROPERTY", "caCertsOnly", e.toString()));
}
// Disable these for now unitl we support them fully
-/*
- try {
- boolean userCertsOnly = config.getBoolean(PROP_USERCERTS, false);
-
- nvp.add(PROP_USERCERTS, String.valueOf(userCertsOnly));
- } catch (EBaseException e) {
- nvp.add(PROP_USERCERTS, "false");
- log(ILogger.LL_FAILURE, CMS.getLogMessage("CRL_INVALID_PROPERTY", "userCertsOnly", e.toString()));
- }
-
- try {
- boolean indirectCRL = config.getBoolean(PROP_INDIRECT, false);
-
- nvp.add(PROP_INDIRECT, String.valueOf(indirectCRL));
- } catch (EBaseException e) {
- nvp.add(PROP_INDIRECT, "false");
- log(ILogger.LL_FAILURE, CMS.getLogMessage("CRL_INVALID_PROPERTY", "indirectCRL", e.toString()));
- }
-*/
+ /*
+ * try { boolean userCertsOnly = config.getBoolean(PROP_USERCERTS,
+ * false);
+ *
+ * nvp.add(PROP_USERCERTS, String.valueOf(userCertsOnly)); } catch
+ * (EBaseException e) { nvp.add(PROP_USERCERTS, "false");
+ * log(ILogger.LL_FAILURE, CMS.getLogMessage("CRL_INVALID_PROPERTY",
+ * "userCertsOnly", e.toString())); }
+ *
+ * try { boolean indirectCRL = config.getBoolean(PROP_INDIRECT, false);
+ *
+ * nvp.add(PROP_INDIRECT, String.valueOf(indirectCRL)); } catch
+ * (EBaseException e) { nvp.add(PROP_INDIRECT, "false");
+ * log(ILogger.LL_FAILURE, CMS.getLogMessage("CRL_INVALID_PROPERTY",
+ * "indirectCRL", e.toString())); }
+ */
}
public String[] getExtendedPluginInfo(Locale locale) {
@@ -305,25 +300,26 @@ public class CMSIssuingDistributionPointExtension
sb_reasons.append(reasonFlags[i]);
}
String[] params = {
- //"type;choice(CRLExtension,CRLEntryExtension);"+
- //"CRL Extension type. This field is not editable.",
+ // "type;choice(CRLExtension,CRLEntryExtension);"+
+ // "CRL Extension type. This field is not editable.",
"enable;boolean;Check to enable Issuing Distribution Point CRL extension.",
"critical;boolean;Set criticality for Issuing Distribution Point CRL extension.",
PROP_POINTTYPE + ";choice(" + PROP_DIRNAME + "," + PROP_URINAME + "," +
- PROP_RDNNAME + ");Select Issuing Distribution Point name type.",
+ PROP_RDNNAME + ");Select Issuing Distribution Point name type.",
PROP_POINTNAME + ";string;Enter Issuing Distribution Point name " +
- "corresponding to the selected point type.",
+ "corresponding to the selected point type.",
PROP_REASONS + ";string;Select any combination of the following reasons: " +
- sb_reasons.toString(),
+ sb_reasons.toString(),
PROP_CACERTS + ";boolean;Check if CRL contains CA certificates only",
- // Remove these from the UI until they can be supported fully.
- // PROP_USERCERTS + ";boolean;Check if CRL contains user certificates only",
- // PROP_INDIRECT + ";boolean;Check if CRL is built indirectly.",
+ // Remove these from the UI until they can be supported fully.
+ // PROP_USERCERTS +
+ // ";boolean;Check if CRL contains user certificates only",
+ // PROP_INDIRECT + ";boolean;Check if CRL is built indirectly.",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-ca-edit-crlextension-issuingdistributionpoint",
+ ";configuration-ca-edit-crlextension-issuingdistributionpoint",
IExtendedPluginInfo.HELP_TEXT +
- ";The issuing distribution point is a critical CRL extension " +
- "that identifies the CRL distribution point for a particular CRL."
+ ";The issuing distribution point is a critical CRL extension " +
+ "that identifies the CRL distribution point for a particular CRL."
};
return params;
@@ -331,6 +327,6 @@ public class CMSIssuingDistributionPointExtension
private void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_CA, level,
- "CMSIssuingDistributionPointExtension - " + msg);
+ "CMSIssuingDistributionPointExtension - " + msg);
}
-}
+}
diff --git a/pki/base/common/src/com/netscape/cms/evaluators/GroupAccessEvaluator.java b/pki/base/common/src/com/netscape/cms/evaluators/GroupAccessEvaluator.java
index d026cdba..9411d2b7 100644
--- a/pki/base/common/src/com/netscape/cms/evaluators/GroupAccessEvaluator.java
+++ b/pki/base/common/src/com/netscape/cms/evaluators/GroupAccessEvaluator.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.evaluators;
-
import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.authentication.IAuthToken;
import com.netscape.certsrv.base.EBaseException;
@@ -28,7 +27,6 @@ import com.netscape.certsrv.usrgrp.IUGSubsystem;
import com.netscape.certsrv.usrgrp.IUser;
import com.netscape.cmsutil.util.Utils;
-
/**
* A class represents a group acls evaluator.
* <P>
@@ -54,7 +52,7 @@ public class GroupAccessEvaluator implements IAccessEvaluator {
}
/**
- * initialization. nothing for now.
+ * initialization. nothing for now.
*/
public void init() {
CMS.debug("GroupAccessEvaluator: init");
@@ -62,6 +60,7 @@ public class GroupAccessEvaluator implements IAccessEvaluator {
/**
* gets the type name for this acl evaluator
+ *
* @return type for this acl evaluator: "group" or "at_group"
*/
public String getType() {
@@ -70,6 +69,7 @@ public class GroupAccessEvaluator implements IAccessEvaluator {
/**
* gets the description for this acl evaluator
+ *
* @return description for this acl evaluator
*/
public String getDescription() {
@@ -85,14 +85,13 @@ public class GroupAccessEvaluator implements IAccessEvaluator {
}
/**
- * evaluates uid in AuthToken to see if it has membership in
- * group value
+ * evaluates uid in AuthToken to see if it has membership in group value
+ *
* @param authToken authentication token
* @param type must be "at_group"
* @param op must be "="
* @param value the group name
- * @return true if AuthToken uid belongs to the group value,
- * false otherwise
+ * @return true if AuthToken uid belongs to the group value, false otherwise
*/
public boolean evaluate(IAuthToken authToken, String type, String op, String value) {
@@ -104,17 +103,17 @@ public class GroupAccessEvaluator implements IAccessEvaluator {
if (uid == null) {
uid = authToken.getInString("uid");
if (uid == null) {
- CMS.debug("GroupAccessEvaluator: evaluate: uid null");
- log(ILogger.LL_FAILURE, CMS.getLogMessage("EVALUTOR_UID_NULL"));
- return false;
+ CMS.debug("GroupAccessEvaluator: evaluate: uid null");
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("EVALUTOR_UID_NULL"));
+ return false;
}
}
- CMS.debug("GroupAccessEvaluator: evaluate: uid="+uid +" value="+value);
+ CMS.debug("GroupAccessEvaluator: evaluate: uid=" + uid + " value=" + value);
String groupname = authToken.getInString("gid");
if (groupname != null) {
- CMS.debug("GroupAccessEvaluator: evaluate: authToken gid="+groupname);
+ CMS.debug("GroupAccessEvaluator: evaluate: authToken gid=" + groupname);
if (op.equals("=")) {
return groupname.equals(Utils.stripQuotes(value));
} else if (op.equals("!=")) {
@@ -123,12 +122,12 @@ public class GroupAccessEvaluator implements IAccessEvaluator {
} else {
CMS.debug("GroupAccessEvaluator: evaluate: no gid in authToken");
IUser id = null;
- try {
- id = mUG.getUser(uid);
- } catch (EBaseException e) {
+ try {
+ id = mUG.getUser(uid);
+ } catch (EBaseException e) {
CMS.debug("GroupAccessEvaluator: " + e.toString());
return false;
- }
+ }
if (op.equals("=")) {
return mUG.isMemberOf(id, Utils.stripQuotes(value));
@@ -142,13 +141,14 @@ public class GroupAccessEvaluator implements IAccessEvaluator {
}
/**
- * evaluates uid in SessionContext to see if it has membership in
- * group value
+ * evaluates uid in SessionContext to see if it has membership in group
+ * value
+ *
* @param type must be "group"
* @param op must be "="
* @param value the group name
- * @return true if SessionContext uid belongs to the group value,
- * false otherwise
+ * @return true if SessionContext uid belongs to the group value, false
+ * otherwise
*/
public boolean evaluate(String type, String op, String value) {
@@ -161,12 +161,12 @@ public class GroupAccessEvaluator implements IAccessEvaluator {
log(ILogger.LL_FAILURE, CMS.getLogMessage("EVALUTOR_UID_NULL"));
return false;
}
- if (op.equals("="))
+ if (op.equals("="))
return mUG.isMemberOf(id, Utils.stripQuotes(value));
else
return !(mUG.isMemberOf(id, Utils.stripQuotes(value)));
-
- }
+
+ }
return false;
}
@@ -175,7 +175,7 @@ public class GroupAccessEvaluator implements IAccessEvaluator {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_ACLS,
- level, "GroupAccessEvaluator: " + msg);
+ level, "GroupAccessEvaluator: " + msg);
}
}
diff --git a/pki/base/common/src/com/netscape/cms/evaluators/IPAddressAccessEvaluator.java b/pki/base/common/src/com/netscape/cms/evaluators/IPAddressAccessEvaluator.java
index a5c99eeb..3d512c98 100644
--- a/pki/base/common/src/com/netscape/cms/evaluators/IPAddressAccessEvaluator.java
+++ b/pki/base/common/src/com/netscape/cms/evaluators/IPAddressAccessEvaluator.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.evaluators;
-
import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.authentication.IAuthToken;
import com.netscape.certsrv.base.SessionContext;
@@ -25,7 +24,6 @@ import com.netscape.certsrv.evaluators.IAccessEvaluator;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.cmsutil.util.Utils;
-
/**
* A class represents a IP address acls evaluator.
* <P>
@@ -44,13 +42,14 @@ public class IPAddressAccessEvaluator implements IAccessEvaluator {
}
/**
- * initialization. nothing for now.
+ * initialization. nothing for now.
*/
public void init() {
}
/**
* gets the type name for this acl evaluator
+ *
* @return type for this acl evaluator: ipaddress
*/
public String getType() {
@@ -59,6 +58,7 @@ public class IPAddressAccessEvaluator implements IAccessEvaluator {
/**
* gets the description for this acl evaluator
+ *
* @return description for this acl evaluator
*/
public String getDescription() {
@@ -75,6 +75,7 @@ public class IPAddressAccessEvaluator implements IAccessEvaluator {
/**
* Gets the IP address from session context
+ *
* @param authToken authentication token
* @param type must be "ipaddress"
* @param op must be "=" or "!="
@@ -86,13 +87,14 @@ public class IPAddressAccessEvaluator implements IAccessEvaluator {
}
/**
- * evaluates uid in SessionContext to see if it has membership in
- * group value
+ * evaluates uid in SessionContext to see if it has membership in group
+ * value
+ *
* @param type must be "group"
* @param op must be "="
* @param value the group name
- * @return true if SessionContext uid belongs to the group value,
- * false otherwise
+ * @return true if SessionContext uid belongs to the group value, false
+ * otherwise
*/
public boolean evaluate(String type, String op, String value) {
@@ -106,13 +108,13 @@ public class IPAddressAccessEvaluator implements IAccessEvaluator {
log(ILogger.LL_FAILURE, CMS.getLogMessage("EVALUATOR_IPADDRESS_NULL"));
return false;
}
- if (op.equals("=")) {
+ if (op.equals("=")) {
return ipaddress.matches(value);
} else {
return !(ipaddress.matches(value));
}
-
- }
+
+ }
return false;
}
@@ -121,6 +123,6 @@ public class IPAddressAccessEvaluator implements IAccessEvaluator {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_ACLS,
- level, "GroupAccessEvaluator: " + msg);
+ level, "GroupAccessEvaluator: " + msg);
}
}
diff --git a/pki/base/common/src/com/netscape/cms/evaluators/UserAccessEvaluator.java b/pki/base/common/src/com/netscape/cms/evaluators/UserAccessEvaluator.java
index 4b6b5677..bf7727c9 100644
--- a/pki/base/common/src/com/netscape/cms/evaluators/UserAccessEvaluator.java
+++ b/pki/base/common/src/com/netscape/cms/evaluators/UserAccessEvaluator.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.evaluators;
-
import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.authentication.IAuthToken;
import com.netscape.certsrv.base.SessionContext;
@@ -26,7 +25,6 @@ import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.usrgrp.IUser;
import com.netscape.cmsutil.util.Utils;
-
/**
* A class represents a user acls evaluator.
* <P>
@@ -48,7 +46,7 @@ public class UserAccessEvaluator implements IAccessEvaluator {
}
/**
- * initialization. nothing for now.
+ * initialization. nothing for now.
*/
public void init() {
CMS.debug("UserAccessEvaluator: init");
@@ -56,6 +54,7 @@ public class UserAccessEvaluator implements IAccessEvaluator {
/**
* gets the type name for this acl evaluator
+ *
* @return type for this acl evaluator: "user" or "at_user"
*/
public String getType() {
@@ -64,6 +63,7 @@ public class UserAccessEvaluator implements IAccessEvaluator {
/**
* gets the description for this acl evaluator
+ *
* @return description for this acl evaluator
*/
public String getDescription() {
@@ -80,6 +80,7 @@ public class UserAccessEvaluator implements IAccessEvaluator {
/**
* Evaluates the user in AuthToken to see if it's equal to value
+ *
* @param authToken AuthToken from authentication
* @param type must be "at_user"
* @param op must be "="
@@ -92,9 +93,9 @@ public class UserAccessEvaluator implements IAccessEvaluator {
String s = Utils.stripQuotes(value);
if ((s.equals(ANYBODY) || s.equals(EVERYBODY)) && op.equals("="))
- return true;
-
- // should define "uid" at a common place
+ return true;
+
+ // should define "uid" at a common place
String uid = null;
uid = authToken.getInString("uid");
@@ -108,13 +109,14 @@ public class UserAccessEvaluator implements IAccessEvaluator {
return s.equalsIgnoreCase(uid);
else if (op.equals("!="))
return !(s.equalsIgnoreCase(uid));
- }
+ }
return false;
}
/**
* Evaluates the user in session context to see if it's equal to value
+ *
* @param type must be "user"
* @param op must be "="
* @param value the user id
@@ -145,7 +147,7 @@ public class UserAccessEvaluator implements IAccessEvaluator {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_ACLS,
- level, "UserAccessEvaluator: " + msg);
+ level, "UserAccessEvaluator: " + msg);
}
}
diff --git a/pki/base/common/src/com/netscape/cms/evaluators/UserOrigReqAccessEvaluator.java b/pki/base/common/src/com/netscape/cms/evaluators/UserOrigReqAccessEvaluator.java
index b1b406c0..4687b709 100644
--- a/pki/base/common/src/com/netscape/cms/evaluators/UserOrigReqAccessEvaluator.java
+++ b/pki/base/common/src/com/netscape/cms/evaluators/UserOrigReqAccessEvaluator.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.evaluators;
-
import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.authentication.IAuthToken;
import com.netscape.certsrv.base.SessionContext;
@@ -26,12 +25,11 @@ import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.usrgrp.IUser;
import com.netscape.cmsutil.util.Utils;
-
/**
- * A class represents a user-origreq uid mapping acls evaluator.
- * This is primarily used for renewal. During renewal, the orig_req
- * uid is placed in the SessionContext of the renewal session context
- * to be evaluated by this evaluator
+ * A class represents a user-origreq uid mapping acls evaluator. This is
+ * primarily used for renewal. During renewal, the orig_req uid is placed in the
+ * SessionContext of the renewal session context to be evaluated by this
+ * evaluator
* <P>
*
* @author Christina Fu
@@ -52,7 +50,7 @@ public class UserOrigReqAccessEvaluator implements IAccessEvaluator {
}
/**
- * initialization. nothing for now.
+ * initialization. nothing for now.
*/
public void init() {
CMS.debug("UserOrigReqAccessEvaluator: init");
@@ -60,6 +58,7 @@ public class UserOrigReqAccessEvaluator implements IAccessEvaluator {
/**
* gets the type name for this acl evaluator
+ *
* @return type for this acl evaluator: "user_origreq" or "at_user_origreq"
*/
public String getType() {
@@ -68,6 +67,7 @@ public class UserOrigReqAccessEvaluator implements IAccessEvaluator {
/**
* gets the description for this acl evaluator
+ *
* @return description for this acl evaluator
*/
public String getDescription() {
@@ -84,6 +84,7 @@ public class UserOrigReqAccessEvaluator implements IAccessEvaluator {
/**
* Evaluates the user in AuthToken to see if it's equal to value
+ *
* @param authToken AuthToken from authentication
* @param type must be "at_userreq"
* @param op must be "="
@@ -96,9 +97,9 @@ public class UserOrigReqAccessEvaluator implements IAccessEvaluator {
String s = Utils.stripQuotes(value);
if ((s.equals(ANYBODY) || s.equals(EVERYBODY)) && op.equals("="))
- return true;
-
- // should define "uid" at a common place
+ return true;
+
+ // should define "uid" at a common place
String uid = null;
uid = authToken.getInString("uid");
@@ -107,30 +108,31 @@ public class UserOrigReqAccessEvaluator implements IAccessEvaluator {
CMS.debug("UserOrigReqAccessEvaluator: evaluate() uid in authtoken null");
return false;
} else
- CMS.debug("UserOrigReqAccessEvaluator: evaluate() uid in authtoken ="+ uid);
+ CMS.debug("UserOrigReqAccessEvaluator: evaluate() uid in authtoken =" + uid);
// find value of param in request
SessionContext mSC = SessionContext.getContext();
- CMS.debug("UserOrigReqAccessEvaluator: evaluate() getting "+"orig_req."+s+ " in SessionContext");
+ CMS.debug("UserOrigReqAccessEvaluator: evaluate() getting " + "orig_req." + s + " in SessionContext");
// "orig_req.auth_token.uid"
- String orig_id = (String) mSC.get("orig_req."+s);
+ String orig_id = (String) mSC.get("orig_req." + s);
if (orig_id == null) {
CMS.debug("UserOrigReqAccessEvaluator: evaluate() orig_id null");
return false;
}
- CMS.debug("UserOrigReqAccessEvaluator: evaluate() orig_id ="+ orig_id);
+ CMS.debug("UserOrigReqAccessEvaluator: evaluate() orig_id =" + orig_id);
if (op.equals("="))
return uid.equalsIgnoreCase(orig_id);
else if (op.equals("!="))
return !(uid.equalsIgnoreCase(orig_id));
- }
+ }
return false;
}
/**
* Evaluates the user in session context to see if it's equal to value
+ *
* @param type must be "user_origreq"
* @param op must be "="
* @param value the user id
@@ -141,7 +143,7 @@ public class UserOrigReqAccessEvaluator implements IAccessEvaluator {
SessionContext mSC = SessionContext.getContext();
if (type.equals(mType)) {
-// what do I do with s here?
+ // what do I do with s here?
String s = Utils.stripQuotes(value);
if (s.equals(ANYBODY) && op.equals("="))
@@ -149,7 +151,7 @@ public class UserOrigReqAccessEvaluator implements IAccessEvaluator {
IUser id = (IUser) mSC.get(SessionContext.USER);
// "orig_req.auth_token.uid"
- String orig_id = (String) mSC.get("orig_req"+s);
+ String orig_id = (String) mSC.get("orig_req" + s);
if (op.equals("="))
return id.getName().equalsIgnoreCase(orig_id);
diff --git a/pki/base/common/src/com/netscape/cms/jobs/AJobBase.java b/pki/base/common/src/com/netscape/cms/jobs/AJobBase.java
index 8488ec2d..bf875162 100644
--- a/pki/base/common/src/com/netscape/cms/jobs/AJobBase.java
+++ b/pki/base/common/src/com/netscape/cms/jobs/AJobBase.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.jobs;
-
import java.io.IOException;
import java.util.Hashtable;
@@ -36,11 +35,10 @@ import com.netscape.certsrv.notification.IEmailTemplate;
import com.netscape.certsrv.notification.IMailNotification;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This abstract class is a base job for real job extentions for the
- * Jobs Scheduler.
- *
+ * This abstract class is a base job for real job extentions for the Jobs
+ * Scheduler.
+ *
* @version $Revision$, $Date$
* @see com.netscape.certsrv.jobs.IJob
*/
@@ -57,7 +55,7 @@ public abstract class AJobBase implements IJob, Runnable {
protected static final String STATUS_FAILURE = "failed";
protected static final String STATUS_SUCCESS = "succeeded";
- // variables used by the Job Scheduler Daemon
+ // variables used by the Job Scheduler Daemon
protected String mImplName = null;
protected IConfigStore mConfig;
protected String mId = null;
@@ -81,8 +79,8 @@ public abstract class AJobBase implements IJob, Runnable {
/**
* tells if the job is enabled
- * @return a boolean value indicating whether the job is enabled
- * or not
+ *
+ * @return a boolean value indicating whether the job is enabled or not
*/
public boolean isEnabled() {
boolean enabled = false;
@@ -98,16 +96,17 @@ public abstract class AJobBase implements IJob, Runnable {
* abstract methods
***********************/
public abstract void init(ISubsystem owner, String id, String implName, IConfigStore
- config) throws EBaseException;
+ config) throws EBaseException;
public abstract void run();
/***********************
* public methods
***********************/
-
+
/**
* get instance id.
+ *
* @return a String identifier
*/
public String getId() {
@@ -116,6 +115,7 @@ public abstract class AJobBase implements IJob, Runnable {
/**
* set instance id.
+ *
* @param id String id of the instance
*/
public void setId(String id) {
@@ -124,6 +124,7 @@ public abstract class AJobBase implements IJob, Runnable {
/**
* get cron string associated with this job
+ *
* @return a JobCron object that represents the schedule of this job
*/
public IJobCron getJobCron() {
@@ -132,6 +133,7 @@ public abstract class AJobBase implements IJob, Runnable {
/**
* gets the plugin name of this job.
+ *
* @return a String that is the name of this implementation
*/
public String getImplName() {
@@ -140,6 +142,7 @@ public abstract class AJobBase implements IJob, Runnable {
/**
* Gets the configuration substore used by this job
+ *
* @return configuration store
*/
public IConfigStore getConfigStore() {
@@ -193,29 +196,29 @@ public abstract class AJobBase implements IJob, Runnable {
} catch (ENotificationException e) {
// already logged, lets audit
mLogger.log(ILogger.EV_AUDIT, null,
- ILogger.S_OTHER,
- ILogger.LL_FAILURE, CMS.getLogMessage("JOBS_SEND_NOTIFICATION", e.toString()));
+ ILogger.S_OTHER,
+ ILogger.LL_FAILURE, CMS.getLogMessage("JOBS_SEND_NOTIFICATION", e.toString()));
} catch (IOException e) {
// already logged, lets audit
mLogger.log(ILogger.EV_AUDIT, null,
- ILogger.S_OTHER,
- ILogger.LL_FAILURE, CMS.getLogMessage("JOBS_SEND_NOTIFICATION", e.toString()));
+ ILogger.S_OTHER,
+ ILogger.LL_FAILURE, CMS.getLogMessage("JOBS_SEND_NOTIFICATION", e.toString()));
}
}
protected void buildItemParams(X509CertImpl cert) {
mItemParams.put(IEmailFormProcessor.TOKEN_SERIAL_NUM,
- (Object) cert.getSerialNumber().toString());
+ (Object) cert.getSerialNumber().toString());
mItemParams.put(IEmailFormProcessor.TOKEN_HEX_SERIAL_NUM,
- (Object) cert.getSerialNumber().toString(16));
+ (Object) cert.getSerialNumber().toString(16));
mItemParams.put(IEmailFormProcessor.TOKEN_ISSUER_DN,
- (Object) cert.getIssuerDN().toString());
+ (Object) cert.getIssuerDN().toString());
mItemParams.put(IEmailFormProcessor.TOKEN_SUBJECT_DN,
- (Object) cert.getSubjectDN().toString());
+ (Object) cert.getSubjectDN().toString());
mItemParams.put(IEmailFormProcessor.TOKEN_NOT_AFTER,
- (Object) cert.getNotAfter().toString());
+ (Object) cert.getNotAfter().toString());
mItemParams.put(IEmailFormProcessor.TOKEN_NOT_BEFORE,
- (Object) cert.getNotBefore().toString());
+ (Object) cert.getNotBefore().toString());
// ... and more
}
@@ -258,7 +261,8 @@ public abstract class AJobBase implements IJob, Runnable {
}
/**
- * logs an entry in the log file. Used by classes extending this class.
+ * logs an entry in the log file. Used by classes extending this class.
+ *
* @param level log level
* @param msg log message in String
*/
@@ -266,21 +270,22 @@ public abstract class AJobBase implements IJob, Runnable {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_OTHER,
- level, mId + ": " + msg);
+ level, mId + ": " + msg);
}
/**
- * capable of logging multiline entry in the log file. Used by classes extending this class.
+ * capable of logging multiline entry in the log file. Used by classes
+ * extending this class.
+ *
* @param level log level
* @param msg log message in String
- * @param multiline boolean indicating whether the message is a
- * multi-lined message.
+ * @param multiline boolean indicating whether the message is a multi-lined
+ * message.
*/
public void log(int level, String msg, boolean multiline) {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_OTHER,
- level, mId + ": " + msg, multiline);
+ level, mId + ": " + msg, multiline);
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/jobs/PublishCertsJob.java b/pki/base/common/src/com/netscape/cms/jobs/PublishCertsJob.java
index a23cc1f3..ba8bffad 100644
--- a/pki/base/common/src/com/netscape/cms/jobs/PublishCertsJob.java
+++ b/pki/base/common/src/com/netscape/cms/jobs/PublishCertsJob.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.jobs;
-
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.util.Date;
@@ -46,59 +45,47 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.IRequestQueue;
import com.netscape.certsrv.request.RequestId;
-
/**
- * a job for the Jobs Scheduler. This job checks in the internal ldap
- * db for valid certs that have not been published to the
- * publishing directory.
+ * a job for the Jobs Scheduler. This job checks in the internal ldap db for
+ * valid certs that have not been published to the publishing directory.
* <p>
* the $TOKENS that are available for the this jobs's summary outer form are:<br>
* <UL>
- * $Status
- * $InstanceID
- * $SummaryItemList
- * $SummaryTotalNum
- * $SummaryTotalSuccess
- * $SummaryTotalfailure
- * $ExecutionTime
+ * $Status $InstanceID $SummaryItemList $SummaryTotalNum $SummaryTotalSuccess
+ * $SummaryTotalfailure $ExecutionTime
* </UL>
* and for the inner list items:
* <UL>
- * $SerialNumber
- * $IssuerDN
- * $SubjectDN
- * $NotAfter
- * $NotBefore
- * $RequestorEmail
+ * $SerialNumber $IssuerDN $SubjectDN $NotAfter $NotBefore $RequestorEmail
* $CertType
* </UL>
- *
+ *
* @version $Revision$, $Date$
*/
public class PublishCertsJob extends AJobBase
- implements IJob, Runnable, IExtendedPluginInfo {
-
+ implements IJob, Runnable, IExtendedPluginInfo {
+
ICertificateAuthority mCa = null;
IRequestQueue mReqQ = null;
ICertificateRepository mRepository = null;
IPublisherProcessor mPublisherProcessor = null;
private boolean mSummary = false;
- /* Holds configuration parameters accepted by this implementation.
- * This list is passed to the configuration console so configuration
- * for instances of this implementation can be configured through the
- * console.
+ /*
+ * Holds configuration parameters accepted by this implementation. This list
+ * is passed to the configuration console so configuration for instances of
+ * this implementation can be configured through the console.
*/
protected static String[] mConfigParams =
- new String[] {
- "enabled",
- "cron",
- "summary.enabled",
- "summary.emailSubject",
- "summary.emailTemplate",
- "summary.itemTemplate",
- "summary.senderEmail",
- "summary.recipientEmail"
+ new String[] {
+ "enabled",
+ "cron",
+ "summary.enabled",
+ "summary.emailSubject",
+ "summary.emailTemplate",
+ "summary.itemTemplate",
+ "summary.senderEmail",
+ "summary.recipientEmail"
};
/* Vector of extendedPluginInfo strings */
@@ -110,24 +97,24 @@ public class PublishCertsJob extends AJobBase
public String[] getExtendedPluginInfo(Locale locale) {
String s[] = {
IExtendedPluginInfo.HELP_TEXT +
- "; A job that checks for valid certificates in the " +
- "database, that have not been published and publish them to " +
- "the publishing directory",
+ "; A job that checks for valid certificates in the " +
+ "database, that have not been published and publish them to " +
+ "the publishing directory",
"cron;string;Format: minute hour dayOfMonth month " +
- "dayOfWeek. Use '*' for 'every'. For dayOfWeek, 0 is Sunday",
+ "dayOfWeek. Use '*' for 'every'. For dayOfWeek, 0 is Sunday",
"summary.senderEmail;string;Specify the address to be used " +
- "as the email's 'sender'. Bounces go to this address.",
+ "as the email's 'sender'. Bounces go to this address.",
"summary.recipientEmail;string;Who should receive summaries",
"enabled;boolean;Enable this plugin",
"summary.enabled;boolean;Enable the summary. You must enabled " +
- "this for the job to work.",
+ "this for the job to work.",
"summary.emailSubject;string;Subject of summary email",
"summary.emailTemplate;string;Fully qualified pathname of " +
- "template file of email to be sent",
+ "template file of email to be sent",
"summary.itemTemplate;string;Fully qualified pathname of " +
- "file containing template for each item",
+ "file containing template for each item",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-jobrules-unpublishexpiredjobs",
+ ";configuration-jobrules-unpublishexpiredjobs",
};
return s;
@@ -151,13 +138,13 @@ public class PublishCertsJob extends AJobBase
mReqQ = mCa.getRequestQueue();
mRepository = (ICertificateRepository) mCa.getCertificateRepository();
mPublisherProcessor = mCa.getPublisherProcessor();
-
+
// read from the configuration file
mCron = mConfig.getString(IJobCron.PROP_CRON);
if (mCron == null) {
return;
}
-
+
// parse cron string into a JobCron class
IJobsScheduler scheduler = (IJobsScheduler) owner;
@@ -179,15 +166,14 @@ public class PublishCertsJob extends AJobBase
}
/**
- * look in the internal db for certificateRecords that are
- * valid but not published
- * The publish() method should set <b>InLdapPublishDir</b> flag accordingly.
- * if publish unsuccessfully, log it -- unsuccessful certs should be
- * picked up and attempted again at the next scheduled run
+ * look in the internal db for certificateRecords that are valid but not
+ * published The publish() method should set <b>InLdapPublishDir</b> flag
+ * accordingly. if publish unsuccessfully, log it -- unsuccessful certs
+ * should be picked up and attempted again at the next scheduled run
*/
public void run() {
- CMS.debug("in PublishCertsJob "+
- getId()+ " : run()");
+ CMS.debug("in PublishCertsJob " +
+ getId() + " : run()");
// get time now..."now" is before the loop
Date date = CMS.getCurrentDate();
long now = date.getTime();
@@ -196,8 +182,8 @@ public class PublishCertsJob extends AJobBase
// form filter
String filter = // might need to use "metaInfo"
- "(!(certMetainfo=" + ICertRecord.META_LDAPPUBLISH +
- ":true))";
+ "(!(certMetainfo=" + ICertRecord.META_LDAPPUBLISH +
+ ":true))";
Enumeration unpublishedCerts = null;
@@ -205,10 +191,10 @@ public class PublishCertsJob extends AJobBase
unpublishedCerts = mRepository.findCertRecs(filter);
// bug 399150
/*
- CertRecordList list = null;
- list = mRepository.findCertRecordsInList(filter, null, "serialno", 5);
- int size = list.getSize();
- expired = list.getCertRecords(0, size - 1);
+ * CertRecordList list = null; list =
+ * mRepository.findCertRecordsInList(filter, null, "serialno", 5);
+ * int size = list.getSize(); expired = list.getCertRecords(0, size
+ * - 1);
*/
} catch (EBaseException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("OPERATION_ERROR", e.toString()));
@@ -225,28 +211,29 @@ public class PublishCertsJob extends AJobBase
itemForm = getTemplateContent(mItemForm);
}
- // filter out the invalid ones and publish them
+ // filter out the invalid ones and publish them
// publish() will set inLdapPublishDir flag
while (unpublishedCerts != null && unpublishedCerts.hasMoreElements()) {
ICertRecord rec = (ICertRecord) unpublishedCerts.nextElement();
- if (rec == null) break;
+ if (rec == null)
+ break;
X509CertImpl cert = rec.getCertificate();
- Date notBefore = cert.getNotBefore();
- Date notAfter = cert.getNotAfter();
+ Date notBefore = cert.getNotBefore();
+ Date notAfter = cert.getNotAfter();
- // skip CA certs
- if (cert.getBasicConstraintsIsCA() == true)
- continue;
+ // skip CA certs
+ if (cert.getBasicConstraintsIsCA() == true)
+ continue;
- // skip the expired certs
- if (notAfter.before(date))
- continue;
+ // skip the expired certs
+ if (notAfter.before(date))
+ continue;
if (mSummary == true)
buildItemParams(cert);
- // get request id from cert record MetaInfo
+ // get request id from cert record MetaInfo
MetaInfo minfo = null;
try {
@@ -255,42 +242,42 @@ public class PublishCertsJob extends AJobBase
negCount += 1;
if (mSummary == true)
buildItemParams(IEmailFormProcessor.TOKEN_STATUS,
- STATUS_FAILURE);
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("JOBS_META_INFO_ERROR",
- cert.getSerialNumber().toString(16) +
- e.toString()));
+ STATUS_FAILURE);
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("JOBS_META_INFO_ERROR",
+ cert.getSerialNumber().toString(16) +
+ e.toString()));
}
String ridString = null;
try {
if (minfo != null)
- ridString = (String) minfo.get(ICertRecord.META_REQUEST_ID);
+ ridString = (String) minfo.get(ICertRecord.META_REQUEST_ID);
} catch (EBaseException e) {
negCount += 1;
if (mSummary == true)
buildItemParams(IEmailFormProcessor.TOKEN_STATUS,
- STATUS_FAILURE);
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("JOBS_META_REQUEST_ERROR",
- cert.getSerialNumber().toString(16) +
- e.toString()));
+ STATUS_FAILURE);
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("JOBS_META_REQUEST_ERROR",
+ cert.getSerialNumber().toString(16) +
+ e.toString()));
} catch (NullPointerException e) {
// no requestId in MetaInfo...skip to next record
negCount += 1;
if (mSummary == true)
buildItemParams(IEmailFormProcessor.TOKEN_STATUS,
- STATUS_FAILURE);
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("JOBS_META_REQUEST_ERROR",
- cert.getSerialNumber().toString(16) +
- e.toString()));
+ STATUS_FAILURE);
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("JOBS_META_REQUEST_ERROR",
+ cert.getSerialNumber().toString(16) +
+ e.toString()));
}
if (ridString != null) {
RequestId rid = new RequestId(ridString);
-
+
// get request from request id
IRequest req = null;
@@ -304,19 +291,19 @@ public class PublishCertsJob extends AJobBase
negCount += 1;
if (mSummary == true)
buildItemParams(IEmailFormProcessor.TOKEN_STATUS,
- STATUS_FAILURE);
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("JOBS_FIND_REQUEST_ERROR",
- cert.getSerialNumber().toString(16) +
- e.toString()));
+ STATUS_FAILURE);
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("JOBS_FIND_REQUEST_ERROR",
+ cert.getSerialNumber().toString(16) +
+ e.toString()));
}
try {
if ((mPublisherProcessor != null) &&
- mPublisherProcessor.enabled()) {
+ mPublisherProcessor.enabled()) {
mPublisherProcessor.publishCert((X509Certificate) cert, req);
if (mSummary == true)
buildItemParams(IEmailFormProcessor.TOKEN_STATUS,
- STATUS_SUCCESS);
+ STATUS_SUCCESS);
count += 1;
} else {
negCount += 1;
@@ -325,22 +312,22 @@ public class PublishCertsJob extends AJobBase
negCount += 1;
if (mSummary == true)
buildItemParams(IEmailFormProcessor.TOKEN_STATUS,
- STATUS_FAILURE);
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("JOBS_PUBLISH_ERROR",
- cert.getSerialNumber().toString(16) +
- e.toString()));
+ STATUS_FAILURE);
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("JOBS_PUBLISH_ERROR",
+ cert.getSerialNumber().toString(16) +
+ e.toString()));
}
} // ridString != null
else {
try {
if ((mPublisherProcessor != null) &&
- mPublisherProcessor.enabled()) {
+ mPublisherProcessor.enabled()) {
mPublisherProcessor.publishCert((X509Certificate) cert, null);
if (mSummary == true)
buildItemParams(IEmailFormProcessor.TOKEN_STATUS,
- STATUS_SUCCESS);
+ STATUS_SUCCESS);
count += 1;
} else {
negCount += 1;
@@ -350,12 +337,12 @@ public class PublishCertsJob extends AJobBase
if (mSummary == true)
buildItemParams(IEmailFormProcessor.TOKEN_STATUS,
- STATUS_FAILURE);
+ STATUS_FAILURE);
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("JOBS_PUBLISH_ERROR",
- cert.getSerialNumber().toString(16) +
- e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("JOBS_PUBLISH_ERROR",
+ cert.getSerialNumber().toString(16) +
+ e.toString()));
}
} // ridString == null
@@ -365,7 +352,7 @@ public class PublishCertsJob extends AJobBase
// if summary is enabled, form the item content
if (mSummary) {
IEmailFormProcessor emailItemFormProcessor =
- CMS.getEmailFormProcessor();
+ CMS.getEmailFormProcessor();
String c = emailItemFormProcessor.getEmailContent(itemForm,
mItemParams);
@@ -381,36 +368,35 @@ public class PublishCertsJob extends AJobBase
// time for summary
if (mSummary == true) {
buildContentParams(IEmailFormProcessor.TOKEN_ID,
- mId);
+ mId);
buildContentParams(IEmailFormProcessor.TOKEN_SUMMARY_ITEM_LIST,
- itemListContent);
+ itemListContent);
buildContentParams(IEmailFormProcessor.TOKEN_SUMMARY_TOTAL_NUM,
- String.valueOf(count + negCount));
+ String.valueOf(count + negCount));
buildContentParams(IEmailFormProcessor.TOKEN_SUMMARY_SUCCESS_NUM,
- String.valueOf(count));
+ String.valueOf(count));
buildContentParams(IEmailFormProcessor.TOKEN_SUMMARY_FAILURE_NUM,
- String.valueOf(negCount));
+ String.valueOf(negCount));
buildContentParams(IEmailFormProcessor.TOKEN_EXECUTION_TIME,
- nowString);
+ nowString);
IEmailFormProcessor emailFormProcessor = CMS.getEmailFormProcessor();
String mailContent =
- emailFormProcessor.getEmailContent(contentForm,
- mContentParams);
+ emailFormProcessor.getEmailContent(contentForm,
+ mContentParams);
mailSummary(mailContent);
}
}
/**
- * Returns a list of configuration parameter names.
- * The list is passed to the configuration console so instances of
- * this implementation can be configured through the console.
- *
+ * Returns a list of configuration parameter names. The list is passed to
+ * the configuration console so instances of this implementation can be
+ * configured through the console.
+ *
* @return String array of configuration parameter names.
*/
public String[] getConfigParams() {
return (mConfigParams);
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/jobs/RenewalNotificationJob.java b/pki/base/common/src/com/netscape/cms/jobs/RenewalNotificationJob.java
index 8649cf23..0ffcc636 100644
--- a/pki/base/common/src/com/netscape/cms/jobs/RenewalNotificationJob.java
+++ b/pki/base/common/src/com/netscape/cms/jobs/RenewalNotificationJob.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.jobs;
-
import java.io.IOException;
import java.text.DateFormat;
import java.util.Calendar;
@@ -49,12 +48,11 @@ import com.netscape.certsrv.notification.IMailNotification;
import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.RequestId;
-
/**
- * A job for the Jobs Scheduler. This job checks in the internal ldap
- * db for certs about to expire within the next configurable days and
- * sends email notifications to the appropriate recipients.
- *
+ * A job for the Jobs Scheduler. This job checks in the internal ldap db for
+ * certs about to expire within the next configurable days and sends email
+ * notifications to the appropriate recipients.
+ *
* the $TOKENS that are available for the this jobs's summary outer form are:<br
>
* <UL>
@@ -79,14 +77,14 @@ import com.netscape.certsrv.request.RequestId;
* <LI>$HttpHost
* <LI>$HttpPort
* </UL>
- *
+ *
* @version $Revision$, $Date$
* @see com.netscape.certsrv.jobs.IJob
* @see com.netscape.cms.jobs.AJobBase
*/
-public class RenewalNotificationJob
- extends AJobBase
- implements IJob, Runnable, IExtendedPluginInfo {
+public class RenewalNotificationJob
+ extends AJobBase
+ implements IJob, Runnable, IExtendedPluginInfo {
// config parameters...
public static final String PROP_CRON = "cron";
@@ -97,15 +95,15 @@ public class RenewalNotificationJob
public static final String PROP_PROFILE_ID = "profileId";
/**
- * This job will send notification at this much time before the
- * enpiration date
+ * This job will send notification at this much time before the enpiration
+ * date
*/
public static final String PROP_NOTIFYTRIGGEROFFSET =
- "notifyTriggerOffset";
+ "notifyTriggerOffset";
/**
- * This job will stop sending notification this much time after
- * the expiration date
+ * This job will stop sending notification this much time after the
+ * expiration date
*/
public static final String PROP_NOTIFYENDOFFSET = "notifyEndOffset";
@@ -113,13 +111,13 @@ public class RenewalNotificationJob
* sender email address as appeared on the notification email
*/
public static final String PROP_SENDEREMAIL =
- "senderEmail";
+ "senderEmail";
/**
* email subject line as appeared on the notification email
*/
public static final String PROP_EMAILSUBJECT =
- "emailSubject";
+ "emailSubject";
/**
* location of the template file used for email notification
@@ -148,55 +146,54 @@ public class RenewalNotificationJob
public static final String PROP_SUMMARY_TEMPLATE = "summary.emailTemplate";
/**
- * location of the template file for each item appeared on the
- * notification summary
+ * location of the template file for each item appeared on the notification
+ * summary
*/
public static final String PROP_SUMMARY_ITEMTEMPLATE = "summary.itemTemplate";
/*
- * Holds configuration parameters accepted by this implementation.
- * This list is passed to the configuration console so configuration
- * for instances of this implementation can be configured through the
- * console.
+ * Holds configuration parameters accepted by this implementation. This list
+ * is passed to the configuration console so configuration for instances of
+ * this implementation can be configured through the console.
*/
- protected static String[] mConfigParams =
- new String[] {
- "enabled",
- PROP_CRON,
- PROP_PROFILE_ID,
- PROP_NOTIFYTRIGGEROFFSET,
- PROP_NOTIFYENDOFFSET,
- PROP_SENDEREMAIL,
- PROP_EMAILSUBJECT,
- PROP_EMAILTEMPLATE,
- "summary.enabled",
- PROP_SUMMARY_RECIPIENTEMAIL,
- PROP_SUMMARY_SENDEREMAIL,
- PROP_SUMMARY_SUBJECT,
- PROP_SUMMARY_ITEMTEMPLATE,
- PROP_SUMMARY_TEMPLATE,
+ protected static String[] mConfigParams =
+ new String[] {
+ "enabled",
+ PROP_CRON,
+ PROP_PROFILE_ID,
+ PROP_NOTIFYTRIGGEROFFSET,
+ PROP_NOTIFYENDOFFSET,
+ PROP_SENDEREMAIL,
+ PROP_EMAILSUBJECT,
+ PROP_EMAILTEMPLATE,
+ "summary.enabled",
+ PROP_SUMMARY_RECIPIENTEMAIL,
+ PROP_SUMMARY_SENDEREMAIL,
+ PROP_SUMMARY_SUBJECT,
+ PROP_SUMMARY_ITEMTEMPLATE,
+ PROP_SUMMARY_TEMPLATE,
};
-
+
protected ICertificateRepository mCertDB = null;
protected ICertificateAuthority mCA = null;
protected boolean mSummary = false;
protected String mEmailSender = null;
protected String mEmailSubject = null;
protected String mEmailTemplateName = null;
- protected String mSummaryItemTemplateName = null;
- protected String mSummaryTemplateName = null;
+ protected String mSummaryItemTemplateName = null;
+ protected String mSummaryTemplateName = null;
protected boolean mSummaryHTML = false;
protected boolean mHTML = false;
protected String mHttpHost = null;
protected String mHttpPort = null;
- private int mPreDays = 0;
- private long mPreMS = 0;
- private int mPostDays = 0;
- private long mPostMS = 0;
- private int mMaxNotifyCount = 1;
- private String[] mProfileId = null;
+ private int mPreDays = 0;
+ private long mPreMS = 0;
+ private int mPostDays = 0;
+ private long mPostMS = 0;
+ private int mMaxNotifyCount = 1;
+ private String[] mProfileId = null;
/* Vector of extendedPluginInfo strings */
protected static Vector mExtendedPluginInfo = null;
@@ -207,8 +204,8 @@ public class RenewalNotificationJob
/**
* class constructor
- */
- public RenewalNotificationJob () {
+ */
+ public RenewalNotificationJob() {
}
/**
@@ -217,48 +214,49 @@ public class RenewalNotificationJob
public String[] getExtendedPluginInfo(Locale locale) {
String s[] = {
IExtendedPluginInfo.HELP_TEXT +
- "; A job that checks for expiring or expired certs" +
- "notifyTriggerOffset before and notifyEndOffset after " +
- "the expiration date",
-
- PROP_PROFILE_ID + ";string;Specify the ID of the profile which "+
- "approved the certificates that are about to expire. For multiple "+
- "profiles, each entry is separated by white space. For example, " +
- "if the administrator just wants to give automated notification " +
- "when the SSL server certificates are about to expire, then "+
- "he should enter \"caServerCert caAgentServerCert\" in the profileId textfield. "+
- "Blank field means all profiles.",
+ "; A job that checks for expiring or expired certs" +
+ "notifyTriggerOffset before and notifyEndOffset after " +
+ "the expiration date",
+
+ PROP_PROFILE_ID + ";string;Specify the ID of the profile which " +
+ "approved the certificates that are about to expire. For multiple " +
+ "profiles, each entry is separated by white space. For example, " +
+ "if the administrator just wants to give automated notification " +
+ "when the SSL server certificates are about to expire, then " +
+ "he should enter \"caServerCert caAgentServerCert\" in the profileId textfield. " +
+ "Blank field means all profiles.",
PROP_NOTIFYTRIGGEROFFSET + ";number,required;How long (in days) before " +
- "certificate expiration will the first notification " +
- "be sent",
+ "certificate expiration will the first notification " +
+ "be sent",
PROP_NOTIFYENDOFFSET + ";number,required;How long (in days) after " +
- "certificate expiration will notifications " +
- "continue to be resent if certificate is not renewed",
+ "certificate expiration will notifications " +
+ "continue to be resent if certificate is not renewed",
PROP_CRON + ";string,required;Format: minute hour dayOfMonth Mmonth " +
- "dayOfWeek. Use '*' for 'every'. For dayOfWeek, 0 is Sunday",
+ "dayOfWeek. Use '*' for 'every'. For dayOfWeek, 0 is Sunday",
PROP_SENDEREMAIL + ";string,required;Specify the address to be used " +
- "as the email's 'sender'. Bounces go to this address.",
+ "as the email's 'sender'. Bounces go to this address.",
PROP_EMAILSUBJECT + ";string,required;Email subject",
PROP_EMAILTEMPLATE + ";string,required;Fully qualified pathname of " +
- "template file of email to be sent",
+ "template file of email to be sent",
"enabled;boolean;Enable this plugin",
"summary.enabled;boolean;Enabled sending of summaries",
PROP_SUMMARY_SENDEREMAIL + ";string,required;Sender email address of summary",
PROP_SUMMARY_RECIPIENTEMAIL + ";string,required;Who should receive summaries",
PROP_SUMMARY_SUBJECT + ";string,required;Subject of summary email",
PROP_SUMMARY_TEMPLATE + ";string,required;Fully qualified pathname of " +
- "template file of email to be sent",
+ "template file of email to be sent",
PROP_SUMMARY_ITEMTEMPLATE + ";string,required;Fully qualified pathname of " +
- "file with template to be used for each summary item",
+ "file with template to be used for each summary item",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-jobrules-renewalnotification",
+ ";configuration-jobrules-renewalnotification",
};
return s;
}
-
+
/**
* Initialize from the configuration file.
+ *
* @param id String name of this instance
* @param implName string name of this implementation
* @param config configuration store for this instance
@@ -289,19 +287,20 @@ public class RenewalNotificationJob
mJobCron = scheduler.createJobCron(mCron);
}
-
+
/**
- * finds out which cert needs notification and notifies the
- * responsible parties
+ * finds out which cert needs notification and notifies the responsible
+ * parties
*/
public void run() {
// for forming renewal URL at template
mHttpHost = CMS.getEEHost();
mHttpPort = CMS.getEESSLPort();
- // read from the configuration file
+ // read from the configuration file
try {
- mPreDays = mConfig.getInteger(PROP_NOTIFYTRIGGEROFFSET, 30); // in days
+ mPreDays = mConfig.getInteger(PROP_NOTIFYTRIGGEROFFSET, 30); // in
+ // days
mPostDays = mConfig.getInteger(PROP_NOTIFYENDOFFSET, 15); // in days
mEmailSender = mConfig.getString(PROP_SENDEREMAIL);
@@ -314,19 +313,19 @@ public class RenewalNotificationJob
if (sc.getBoolean(PROP_ENABLED, false)) {
mSummary = true;
mSummaryItemTemplateName =
- mConfig.getString(PROP_SUMMARY_ITEMTEMPLATE);
+ mConfig.getString(PROP_SUMMARY_ITEMTEMPLATE);
mSummarySenderEmail =
- mConfig.getString(PROP_SUMMARY_SENDEREMAIL);
+ mConfig.getString(PROP_SUMMARY_SENDEREMAIL);
mSummaryReceiverEmail =
- mConfig.getString(PROP_SUMMARY_RECIPIENTEMAIL);
+ mConfig.getString(PROP_SUMMARY_RECIPIENTEMAIL);
mSummaryMailSubject =
- mConfig.getString(PROP_SUMMARY_SUBJECT);
+ mConfig.getString(PROP_SUMMARY_SUBJECT);
mSummaryTemplateName =
- mConfig.getString(PROP_SUMMARY_TEMPLATE);
+ mConfig.getString(PROP_SUMMARY_TEMPLATE);
} else {
mSummary = false;
}
-
+
long msperday = 86400 * 1000;
long mspredays = mPreDays;
long mspostdays = mPostDays;
@@ -339,17 +338,15 @@ public class RenewalNotificationJob
String nowString = dateFormat.format(now);
/*
- * look in the internal db for certificateRecords that are
- * 1. within the expiration notification period
- * 2. has not yet been renewed
- * 3. notify - use EmailTemplateProcessor to formulate
- * content, then send
- * if notified successfully, mark "STATUS_SUCCESS",
- * else, if notified unsuccessfully, mark "STATUS_FAILURE".
+ * look in the internal db for certificateRecords that are 1. within
+ * the expiration notification period 2. has not yet been renewed 3.
+ * notify - use EmailTemplateProcessor to formulate content, then
+ * send if notified successfully, mark "STATUS_SUCCESS", else, if
+ * notified unsuccessfully, mark "STATUS_FAILURE".
*/
-
+
/* 1) make target notAfter string */
-
+
Date expiryDate = null;
Date stopDate = null;
@@ -360,13 +357,14 @@ public class RenewalNotificationJob
expiryDate = new Date(expiryMS);
stopDate = new Date(stopMS);
-
+
// All cert records which:
- // 1) expire before the deadline
- // 2) have not already been renewed
- // filter format:
- // (& (notafter<='time')(!(certAutoRenew=DONE))(!certAutoRenew=DISABLED))
-
+ // 1) expire before the deadline
+ // 2) have not already been renewed
+ // filter format:
+ // (&
+ // (notafter<='time')(!(certAutoRenew=DONE))(!certAutoRenew=DISABLED))
+
StringBuffer f = new StringBuffer();
String profileId = "";
try {
@@ -374,24 +372,24 @@ public class RenewalNotificationJob
} catch (EBaseException ee) {
}
- if (profileId != null && profileId.length() > 0) {
+ if (profileId != null && profileId.length() > 0) {
StringTokenizer tokenizer = new StringTokenizer(profileId);
int num = tokenizer.countTokens();
mProfileId = new String[num];
- for (int i=0; i<num; i++)
+ for (int i = 0; i < num; i++)
mProfileId[i] = tokenizer.nextToken();
}
f.append("(&");
if (mProfileId != null) {
if (mProfileId.length == 1)
- f.append("("+ICertRecord.ATTR_META_INFO+ "=" +
- ICertRecord.META_PROFILE_ID +":"+mProfileId[0]+")");
+ f.append("(" + ICertRecord.ATTR_META_INFO + "=" +
+ ICertRecord.META_PROFILE_ID + ":" + mProfileId[0] + ")");
else {
f.append("(|");
- for (int i=0; i<mProfileId.length; i++) {
- f.append("("+ICertRecord.ATTR_META_INFO+ "=" +
- ICertRecord.META_PROFILE_ID +":"+mProfileId[i]+")");
+ for (int i = 0; i < mProfileId.length; i++) {
+ f.append("(" + ICertRecord.ATTR_META_INFO + "=" +
+ ICertRecord.META_PROFILE_ID + ":" + mProfileId[i] + ")");
}
f.append(")");
}
@@ -407,7 +405,7 @@ public class RenewalNotificationJob
String filter = f.toString();
String emailTemplate =
- getTemplateContent(mEmailTemplateName);
+ getTemplateContent(mEmailTemplateName);
mHTML = mMailHTML;
@@ -415,15 +413,16 @@ public class RenewalNotificationJob
String summaryItemTemplate = null;
if (mSummary == true) {
- summaryItemTemplate =
+ summaryItemTemplate =
getTemplateContent(mSummaryItemTemplateName);
}
ItemCounter ic = new ItemCounter();
CertRecProcessor cp = new CertRecProcessor(this, emailTemplate, summaryItemTemplate, ic);
- //CertRecordList list = mCertDB.findCertRecordsInList(filter, null, "serialno", 5);
- //list.processCertRecords(0, list.getSize() - 1, cp);
-
+ // CertRecordList list = mCertDB.findCertRecordsInList(filter,
+ // null, "serialno", 5);
+ // list.processCertRecords(0, list.getSize() - 1, cp);
+
Enumeration en = mCertDB.findCertRecs(filter);
while (en.hasMoreElements()) {
@@ -432,40 +431,41 @@ public class RenewalNotificationJob
try {
cp.process(element);
} catch (Exception e) {
- //Don't abort the entire operation. The error should already be logged
+ // Don't abort the entire operation. The error should
+ // already be logged
log(ILogger.LL_FAILURE, CMS.getLogMessage("JOBS_FAILED_PROCESS", e.toString()));
}
}
-
+
// Now send the summary
if (mSummary == true) {
try {
String summaryTemplate =
- getTemplateContent(mSummaryTemplateName);
+ getTemplateContent(mSummaryTemplateName);
mSummaryHTML = mMailHTML;
buildContentParams(IEmailFormProcessor.TOKEN_ID,
- mId);
+ mId);
buildContentParams(IEmailFormProcessor.TOKEN_SUMMARY_ITEM_LIST,
- ic.mItemListContent);
+ ic.mItemListContent);
buildContentParams(IEmailFormProcessor.TOKEN_SUMMARY_TOTAL_NUM,
- String.valueOf(ic.mNumFail + ic.mNumSuccessful));
- buildContentParams(IEmailFormProcessor.TOKEN_SUMMARY_SUCCESS_NUM,
- String.valueOf(ic.mNumSuccessful));
+ String.valueOf(ic.mNumFail + ic.mNumSuccessful));
+ buildContentParams(IEmailFormProcessor.TOKEN_SUMMARY_SUCCESS_NUM,
+ String.valueOf(ic.mNumSuccessful));
buildContentParams(IEmailFormProcessor.TOKEN_SUMMARY_FAILURE_NUM,
- String.valueOf(ic.mNumFail));
+ String.valueOf(ic.mNumFail));
buildContentParams(IEmailFormProcessor.TOKEN_EXECUTION_TIME,
- nowString);
-
+ nowString);
+
IEmailFormProcessor summaryEmfp = CMS.getEmailFormProcessor();
- String summaryContent =
- summaryEmfp.getEmailContent(summaryTemplate,
- mContentParams);
+ String summaryContent =
+ summaryEmfp.getEmailContent(summaryTemplate,
+ mContentParams);
if (summaryContent == null) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("JOBS_SUMMARY_CONTENT_NULL"));
@@ -490,38 +490,43 @@ public class RenewalNotificationJob
/**
* get instance id.
+ *
* @return a String identifier
*/
public String getId() {
return mId;
}
-
+
/**
* set instance id.
+ *
* @param id String id of the instance
*/
public void setId(String id) {
mId = id;
}
-
+
/**
* get cron string associated with this job
+ *
* @return a JobCron object that represents the schedule of this job
*/
public IJobCron getJobCron() {
return mJobCron;
}
-
+
/**
* gets the plugin name of this job.
+ *
* @return a String that is the name of this implementation
*/
public String getImplName() {
return mImplName;
}
-
+
/**
* Gets the configuration substore used by this job
+ *
* @return configuration store
*/
public IConfigStore getConfigStore() {
@@ -529,16 +534,16 @@ public class RenewalNotificationJob
}
protected void mailUser(String subject,
- String msg,
- String sender,
- IRequest req,
- ICertRecord cr)
- throws IOException, ENotificationException, EBaseException {
+ String msg,
+ String sender,
+ IRequest req,
+ ICertRecord cr)
+ throws IOException, ENotificationException, EBaseException {
IMailNotification mn = CMS.getMailNotification();
String rcp = null;
- // boolean sendFailed = false;
+ // boolean sendFailed = false;
Exception sendFailedException = null;
IEmailResolverKeys keys = CMS.getEmailResolverKeys();
@@ -561,20 +566,25 @@ public class RenewalNotificationJob
} catch (Exception e) {
// already logged by the resolver
- // sendFailed = true;
+ // sendFailed = true;
sendFailedException = e;
throw (ENotificationException) sendFailedException;
}
mn.setTo(rcp);
- if (sender != null) mn.setFrom(sender);
- else mn.setFrom("nobody");
+ if (sender != null)
+ mn.setFrom(sender);
+ else
+ mn.setFrom("nobody");
- if (subject != null) mn.setSubject(subject);
- else mn.setFrom("Important message from Certificate Authority");
+ if (subject != null)
+ mn.setSubject(subject);
+ else
+ mn.setFrom("Important message from Certificate Authority");
- if (mHTML == true) mn.setContentType("text/html");
+ if (mHTML == true)
+ mn.setContentType("text/html");
String failedString = null;
@@ -584,10 +594,10 @@ public class RenewalNotificationJob
}
/**
- * Returns a list of configuration parameter names.
- * The list is passed to the configuration console so instances of
- * this implementation can be configured through the console.
- *
+ * Returns a list of configuration parameter names. The list is passed to
+ * the configuration console so instances of this implementation can be
+ * configured through the console.
+ *
* @return String array of configuration parameter names.
*/
public String[] getConfigParams() {
@@ -595,15 +605,14 @@ public class RenewalNotificationJob
}
}
-
class CertRecProcessor implements IElementProcessor {
protected RenewalNotificationJob mJob;
protected String mEmailTemplate;
protected String mSummaryItemTemplate;
protected ItemCounter mIC;
- public CertRecProcessor(RenewalNotificationJob job, String emailTemplate,
- String summaryItemTemplate, ItemCounter ic) {
+ public CertRecProcessor(RenewalNotificationJob job, String emailTemplate,
+ String summaryItemTemplate, ItemCounter ic) {
mJob = job;
mEmailTemplate = emailTemplate;
mSummaryItemTemplate = summaryItemTemplate;
@@ -621,9 +630,9 @@ class CertRecProcessor implements IElementProcessor {
if (cr != null) {
mJob.buildItemParams(cr.getCertificate());
mJob.buildItemParams(IEmailFormProcessor.TOKEN_HTTP_HOST,
- mJob.mHttpHost);
+ mJob.mHttpHost);
mJob.buildItemParams(IEmailFormProcessor.TOKEN_HTTP_PORT, mJob.mHttpPort);
-
+
MetaInfo metaInfo = null;
metaInfo = (MetaInfo) cr.get(ICertRecord.ATTR_META_INFO);
@@ -632,10 +641,10 @@ class CertRecProcessor implements IElementProcessor {
numFailCounted = true;
if (mJob.mSummary == true)
mJob.buildItemParams(IEmailFormProcessor.TOKEN_STATUS,
- AJobBase.STATUS_FAILURE);
- mJob.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("JOBS_GET_CERT_ERROR",
- cr.getCertificate().getSerialNumber().toString(16)));
+ AJobBase.STATUS_FAILURE);
+ mJob.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("JOBS_GET_CERT_ERROR",
+ cr.getCertificate().getSerialNumber().toString(16)));
} else {
ridString = (String) metaInfo.get(ICertRecord.META_REQUEST_ID);
}
@@ -645,54 +654,54 @@ class CertRecProcessor implements IElementProcessor {
if (ridString != null) {
RequestId rid = new RequestId(ridString);
-
+
try {
req = mJob.mCA.getRequestQueue().findRequest(rid);
} catch (Exception e) {
// it is ok not to be able to get the request. The main reason
// to get the request is to retrieve the requestor's email.
// We can retrieve the email from the CertRecord.
- CMS.debug("huh RenewalNotificationJob Exception: "+e.toString());
+ CMS.debug("huh RenewalNotificationJob Exception: " + e.toString());
}
if (req != null)
mJob.buildItemParams(req);
} // ridString != null
- try {
+ try {
// send mail to user
-
+
IEmailFormProcessor emfp = CMS.getEmailFormProcessor();
String message = emfp.getEmailContent(mEmailTemplate,
mJob.mItemParams);
mJob.mailUser(mJob.mEmailSubject,
- message,
- mJob.mEmailSender,
- req,
- cr);
-
+ message,
+ mJob.mEmailSender,
+ req,
+ cr);
+
mJob.buildItemParams(IEmailFormProcessor.TOKEN_STATUS,
- AJobBase.STATUS_SUCCESS);
-
+ AJobBase.STATUS_SUCCESS);
+
mIC.mNumSuccessful++;
-
+
} catch (Exception e) {
- CMS.debug("RenewalNotificationJob Exception: "+e.toString());
+ CMS.debug("RenewalNotificationJob Exception: " + e.toString());
mJob.buildItemParams(IEmailFormProcessor.TOKEN_STATUS, AJobBase.STATUS_FAILURE);
mJob.log(ILogger.LL_FAILURE, e.toString(), ILogger.L_MULTILINE);
if (numFailCounted == false) {
mIC.mNumFail++;
}
}
-
+
if (mJob.mSummary == true) {
IEmailFormProcessor summaryItemEmfp =
- CMS.getEmailFormProcessor();
- String c =
- summaryItemEmfp.getEmailContent(mSummaryItemTemplate,
- mJob.mItemParams);
-
+ CMS.getEmailFormProcessor();
+ String c =
+ summaryItemEmfp.getEmailContent(mSummaryItemTemplate,
+ mJob.mItemParams);
+
if (mIC.mItemListContent == null) {
mIC.mItemListContent = c;
} else {
@@ -702,7 +711,6 @@ class CertRecProcessor implements IElementProcessor {
}
}
-
class ItemCounter {
public int mNumSuccessful = 0;
public int mNumFail = 0;
diff --git a/pki/base/common/src/com/netscape/cms/jobs/RequestInQueueJob.java b/pki/base/common/src/com/netscape/cms/jobs/RequestInQueueJob.java
index 07a35a9d..4888d301 100644
--- a/pki/base/common/src/com/netscape/cms/jobs/RequestInQueueJob.java
+++ b/pki/base/common/src/com/netscape/cms/jobs/RequestInQueueJob.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.jobs;
-
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
@@ -37,46 +36,43 @@ import com.netscape.certsrv.request.IRequestQueue;
import com.netscape.certsrv.request.RequestId;
import com.netscape.certsrv.request.RequestStatus;
-
/**
- * A job for the Jobs Scheduler. This job checks in the internal ldap
- * db for requests currently in the request queue and send a summary
- * report to the administrator
+ * A job for the Jobs Scheduler. This job checks in the internal ldap db for
+ * requests currently in the request queue and send a summary report to the
+ * administrator
* <p>
* the $TOKENS that are available for the this jobs's summary outer form are:<br>
* <UL>
- * $InstanceID
- * $SummaryTotalNum
- * $ExecutionTime
+ * $InstanceID $SummaryTotalNum $ExecutionTime
* </UL>
- *
+ *
* @version $Revision$, $Date$
* @see com.netscape.certsrv.jobs.IJob
* @see com.netscape.cms.jobs.AJobBase
*/
public class RequestInQueueJob extends AJobBase
- implements IJob, Runnable, IExtendedPluginInfo {
+ implements IJob, Runnable, IExtendedPluginInfo {
protected static final String PROP_SUBSYSTEM_ID = "subsystemId";
IAuthority mSub = null;
IRequestQueue mReqQ = null;
private boolean mSummary = false;
- /* Holds configuration parameters accepted by this implementation.
- * This list is passed to the configuration console so configuration
- * for instances of this implementation can be configured through the
- * console.
+ /*
+ * Holds configuration parameters accepted by this implementation. This list
+ * is passed to the configuration console so configuration for instances of
+ * this implementation can be configured through the console.
*/
protected static String[] mConfigParams =
- new String[] {
- "enabled",
- "cron",
- "subsystemId",
- "summary.enabled",
- "summary.emailSubject",
- "summary.emailTemplate",
- "summary.senderEmail",
- "summary.recipientEmail"
+ new String[] {
+ "enabled",
+ "cron",
+ "subsystemId",
+ "summary.enabled",
+ "summary.emailSubject",
+ "summary.emailTemplate",
+ "summary.senderEmail",
+ "summary.recipientEmail"
};
/**
@@ -85,30 +81,31 @@ public class RequestInQueueJob extends AJobBase
public String[] getExtendedPluginInfo(Locale locale) {
String s[] = {
IExtendedPluginInfo.HELP_TEXT +
- "; A job that checks for enrollment requests in the " +
- "queue, and reports to recipientEmail",
+ "; A job that checks for enrollment requests in the " +
+ "queue, and reports to recipientEmail",
"cron;string;Format: minute hour dayOfMonth month " +
- "dayOfWeek. Use '*' for 'every'. For dayOfWeek, 0 is Sunday",
+ "dayOfWeek. Use '*' for 'every'. For dayOfWeek, 0 is Sunday",
"summary.senderEmail;string;Specify the address to be used " +
- "as the email's 'sender'. Bounces go to this address.",
+ "as the email's 'sender'. Bounces go to this address.",
"summary.recipientEmail;string;Who should receive summaries",
"enabled;boolean;Enable this plugin",
"summary.enabled;boolean;Enable the summary. You must enabled " +
- "this for the job to work.",
+ "this for the job to work.",
"summary.emailSubject;string;Subject of summary email",
"summary.emailTemplate;string;Fully qualified pathname of " +
- "template file of email to be sent",
+ "template file of email to be sent",
"subsystemId;choice(ca,ra);The type of subsystem this job is " +
- "for",
+ "for",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-jobrules-requestinqueuejob",
+ ";configuration-jobrules-requestinqueuejob",
};
return s;
}
-
+
/**
* initialize from the configuration file
+ *
* @param id String name of this instance
* @param implName string name of this implementation
* @param config configuration store for this instance
@@ -137,7 +134,7 @@ public class RequestInQueueJob extends AJobBase
if (mCron == null) {
return;
}
-
+
// parse cron string into a JobCron class
IJobsScheduler scheduler = (IJobsScheduler) owner;
@@ -150,7 +147,7 @@ public class RequestInQueueJob extends AJobBase
mSummary = true;
mSummaryMailSubject = sc.getString(PROP_EMAIL_SUBJECT);
mMailForm = sc.getString(PROP_EMAIL_TEMPLATE);
- // mItemForm = sc.getString(PROP_ITEM_TEMPLATE);
+ // mItemForm = sc.getString(PROP_ITEM_TEMPLATE);
mSummarySenderEmail = sc.getString(PROP_SENDER_EMAIL);
mSummaryReceiverEmail = sc.getString(PROP_RECEIVER_EMAIL);
} else {
@@ -162,7 +159,8 @@ public class RequestInQueueJob extends AJobBase
* summarize the queue status and mail it
*/
public void run() {
- if (mSummary == false) return;
+ if (mSummary == false)
+ return;
Date date = CMS.getCurrentDate();
long now = date.getTime();
@@ -171,24 +169,20 @@ public class RequestInQueueJob extends AJobBase
int count = 0;
IRequestList list =
- mReqQ.listRequestsByStatus(RequestStatus.PENDING);
+ mReqQ.listRequestsByStatus(RequestStatus.PENDING);
while (list != null && list.hasMoreElements()) {
RequestId rid = list.nextRequestId();
- /* This is way too slow
- // get request from request id
- IRequest req = null;
- try {
- req = mReqQ.findRequest(rid);
- } catch (EBaseException e) {
- System.out.println(e.toString());
- }
+ /*
+ * This is way too slow // get request from request id IRequest req
+ * = null; try { req = mReqQ.findRequest(rid); } catch
+ * (EBaseException e) { System.out.println(e.toString()); }
*/
count++;
}
- // if (count == 0) return;
+ // if (count == 0) return;
String contentForm = null;
@@ -196,23 +190,23 @@ public class RequestInQueueJob extends AJobBase
buildContentParams(IEmailFormProcessor.TOKEN_ID, mId);
buildContentParams(IEmailFormProcessor.TOKEN_SUMMARY_TOTAL_NUM,
- String.valueOf(count));
+ String.valueOf(count));
buildContentParams(IEmailFormProcessor.TOKEN_EXECUTION_TIME,
- nowString);
+ nowString);
IEmailFormProcessor emailFormProcessor = CMS.getEmailFormProcessor();
String mailContent =
- emailFormProcessor.getEmailContent(contentForm,
- mContentParams);
+ emailFormProcessor.getEmailContent(contentForm,
+ mContentParams);
mailSummary(mailContent);
}
/**
- * Returns a list of configuration parameter names.
- * The list is passed to the configuration console so instances of
- * this implementation can be configured through the console.
- *
+ * Returns a list of configuration parameter names. The list is passed to
+ * the configuration console so instances of this implementation can be
+ * configured through the console.
+ *
* @return String array of configuration parameter names.
*/
public String[] getConfigParams() {
diff --git a/pki/base/common/src/com/netscape/cms/jobs/UnpublishExpiredJob.java b/pki/base/common/src/com/netscape/cms/jobs/UnpublishExpiredJob.java
index 6a0a6d03..2419b9b7 100644
--- a/pki/base/common/src/com/netscape/cms/jobs/UnpublishExpiredJob.java
+++ b/pki/base/common/src/com/netscape/cms/jobs/UnpublishExpiredJob.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.jobs;
-
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.util.Date;
@@ -46,59 +45,47 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.IRequestQueue;
import com.netscape.certsrv.request.RequestId;
-
/**
- * a job for the Jobs Scheduler. This job checks in the internal ldap
- * db for certs that have expired and remove them from the ldap
- * publishing directory.
+ * a job for the Jobs Scheduler. This job checks in the internal ldap db for
+ * certs that have expired and remove them from the ldap publishing directory.
* <p>
* the $TOKENS that are available for the this jobs's summary outer form are:<br>
* <UL>
- * $Status
- * $InstanceID
- * $SummaryItemList
- * $SummaryTotalNum
- * $SummaryTotalSuccess
- * $SummaryTotalfailure
- * $ExecutionTime
+ * $Status $InstanceID $SummaryItemList $SummaryTotalNum $SummaryTotalSuccess
+ * $SummaryTotalfailure $ExecutionTime
* </UL>
* and for the inner list items:
* <UL>
- * $SerialNumber
- * $IssuerDN
- * $SubjectDN
- * $NotAfter
- * $NotBefore
- * $RequestorEmail
+ * $SerialNumber $IssuerDN $SubjectDN $NotAfter $NotBefore $RequestorEmail
* $CertType
* </UL>
- *
+ *
* @version $Revision$, $Date$
*/
public class UnpublishExpiredJob extends AJobBase
- implements IJob, Runnable, IExtendedPluginInfo {
-
+ implements IJob, Runnable, IExtendedPluginInfo {
+
ICertificateAuthority mCa = null;
IRequestQueue mReqQ = null;
ICertificateRepository mRepository = null;
IPublisherProcessor mPublisherProcessor = null;
private boolean mSummary = false;
- /* Holds configuration parameters accepted by this implementation.
- * This list is passed to the configuration console so configuration
- * for instances of this implementation can be configured through the
- * console.
+ /*
+ * Holds configuration parameters accepted by this implementation. This list
+ * is passed to the configuration console so configuration for instances of
+ * this implementation can be configured through the console.
*/
protected static String[] mConfigParams =
- new String[] {
- "enabled",
- "cron",
- "summary.enabled",
- "summary.emailSubject",
- "summary.emailTemplate",
- "summary.itemTemplate",
- "summary.senderEmail",
- "summary.recipientEmail"
+ new String[] {
+ "enabled",
+ "cron",
+ "summary.enabled",
+ "summary.emailSubject",
+ "summary.emailTemplate",
+ "summary.itemTemplate",
+ "summary.senderEmail",
+ "summary.recipientEmail"
};
/* Vector of extendedPluginInfo strings */
@@ -110,24 +97,24 @@ public class UnpublishExpiredJob extends AJobBase
public String[] getExtendedPluginInfo(Locale locale) {
String s[] = {
IExtendedPluginInfo.HELP_TEXT +
- "; A job that checks for expired certificates in the " +
- "database, and removes them from the publishing " +
- "directory",
+ "; A job that checks for expired certificates in the " +
+ "database, and removes them from the publishing " +
+ "directory",
"cron;string;Format: minute hour dayOfMonth month " +
- "dayOfWeek. Use '*' for 'every'. For dayOfWeek, 0 is Sunday",
+ "dayOfWeek. Use '*' for 'every'. For dayOfWeek, 0 is Sunday",
"summary.senderEmail;string;Specify the address to be used " +
- "as the email's 'sender'. Bounces go to this address.",
+ "as the email's 'sender'. Bounces go to this address.",
"summary.recipientEmail;string;Who should receive summaries",
"enabled;boolean;Enable this plugin",
"summary.enabled;boolean;Enable the summary. You must enabled " +
- "this for the job to work.",
+ "this for the job to work.",
"summary.emailSubject;string;Subject of summary email",
"summary.emailTemplate;string;Fully qualified pathname of " +
- "template file of email to be sent",
+ "template file of email to be sent",
"summary.itemTemplate;string;Fully qualified pathname of " +
- "file containing template for each item",
+ "file containing template for each item",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-jobrules-unpublishexpiredjobs",
+ ";configuration-jobrules-unpublishexpiredjobs",
};
return s;
@@ -151,13 +138,13 @@ public class UnpublishExpiredJob extends AJobBase
mReqQ = mCa.getRequestQueue();
mRepository = (ICertificateRepository) mCa.getCertificateRepository();
mPublisherProcessor = mCa.getPublisherProcessor();
-
+
// read from the configuration file
mCron = mConfig.getString(IJobCron.PROP_CRON);
if (mCron == null) {
return;
}
-
+
// parse cron string into a JobCron class
IJobsScheduler scheduler = (IJobsScheduler) owner;
@@ -179,16 +166,14 @@ public class UnpublishExpiredJob extends AJobBase
}
/**
- * look in the internal db for certificateRecords that are
- * expired.
- * remove them from ldap publishing directory
- * if remove successfully, mark <i>false</i> on the
- * <b>InLdapPublishDir</b> flag,
- * else, if remove unsuccessfully, log it
+ * look in the internal db for certificateRecords that are expired. remove
+ * them from ldap publishing directory if remove successfully, mark
+ * <i>false</i> on the <b>InLdapPublishDir</b> flag, else, if remove
+ * unsuccessfully, log it
*/
public void run() {
- // System.out.println("in ExpiredUnpublishJob "+
- // getId()+ " : run()");
+ // System.out.println("in ExpiredUnpublishJob "+
+ // getId()+ " : run()");
// get time now..."now" is before the loop
Date date = CMS.getCurrentDate();
long now = date.getTime();
@@ -197,11 +182,11 @@ public class UnpublishExpiredJob extends AJobBase
// form filter
String filter = "(&(x509Cert.notAfter<=" + now +
- ")(!(x509Cert.notAfter=" + now + "))" +
- "(" + "certMetainfo=" + ICertRecord.META_LDAPPUBLISH +
- ":true))";
+ ")(!(x509Cert.notAfter=" + now + "))" +
+ "(" + "certMetainfo=" + ICertRecord.META_LDAPPUBLISH +
+ ":true))";
// a test for without CertRecord.META_LDAPPUBLISH
- //String filter = "(x509Cert.notAfter<="+ now +")";
+ // String filter = "(x509Cert.notAfter<="+ now +")";
Enumeration expired = null;
@@ -209,10 +194,10 @@ public class UnpublishExpiredJob extends AJobBase
expired = mRepository.findCertRecs(filter);
// bug 399150
/*
- CertRecordList list = null;
- list = mRepository.findCertRecordsInList(filter, null, "serialno", 5);
- int size = list.getSize();
- expired = list.getCertRecords(0, size - 1);
+ * CertRecordList list = null; list =
+ * mRepository.findCertRecordsInList(filter, null, "serialno", 5);
+ * int size = list.getSize(); expired = list.getCertRecords(0, size
+ * - 1);
*/
} catch (EBaseException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("OPERATION_ERROR", e.toString()));
@@ -233,13 +218,14 @@ public class UnpublishExpiredJob extends AJobBase
while (expired != null && expired.hasMoreElements()) {
ICertRecord rec = (ICertRecord) expired.nextElement();
- if (rec == null) break;
+ if (rec == null)
+ break;
X509CertImpl cert = rec.getCertificate();
if (mSummary == true)
buildItemParams(cert);
- // get request id from cert record MetaInfo
+ // get request id from cert record MetaInfo
MetaInfo minfo = null;
try {
@@ -248,42 +234,42 @@ public class UnpublishExpiredJob extends AJobBase
negCount += 1;
if (mSummary == true)
buildItemParams(IEmailFormProcessor.TOKEN_STATUS,
- STATUS_FAILURE);
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("JOBS_META_INFO_ERROR",
- cert.getSerialNumber().toString(16) +
- e.toString()));
+ STATUS_FAILURE);
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("JOBS_META_INFO_ERROR",
+ cert.getSerialNumber().toString(16) +
+ e.toString()));
}
String ridString = null;
try {
if (minfo != null)
- ridString = (String) minfo.get(ICertRecord.META_REQUEST_ID);
+ ridString = (String) minfo.get(ICertRecord.META_REQUEST_ID);
} catch (EBaseException e) {
negCount += 1;
if (mSummary == true)
buildItemParams(IEmailFormProcessor.TOKEN_STATUS,
- STATUS_FAILURE);
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("JOBS_META_REQUEST_ERROR",
- cert.getSerialNumber().toString(16) +
- e.toString()));
+ STATUS_FAILURE);
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("JOBS_META_REQUEST_ERROR",
+ cert.getSerialNumber().toString(16) +
+ e.toString()));
} catch (NullPointerException e) {
// no requestId in MetaInfo...skip to next record
negCount += 1;
if (mSummary == true)
buildItemParams(IEmailFormProcessor.TOKEN_STATUS,
- STATUS_FAILURE);
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("JOBS_META_REQUEST_ERROR",
- cert.getSerialNumber().toString(16) +
- e.toString()));
+ STATUS_FAILURE);
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("JOBS_META_REQUEST_ERROR",
+ cert.getSerialNumber().toString(16) +
+ e.toString()));
}
if (ridString != null) {
RequestId rid = new RequestId(ridString);
-
+
// get request from request id
IRequest req = null;
@@ -297,19 +283,19 @@ public class UnpublishExpiredJob extends AJobBase
negCount += 1;
if (mSummary == true)
buildItemParams(IEmailFormProcessor.TOKEN_STATUS,
- STATUS_FAILURE);
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("JOBS_FIND_REQUEST_ERROR",
- cert.getSerialNumber().toString(16) +
- e.toString()));
+ STATUS_FAILURE);
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("JOBS_FIND_REQUEST_ERROR",
+ cert.getSerialNumber().toString(16) +
+ e.toString()));
}
try {
if ((mPublisherProcessor != null) &&
- mPublisherProcessor.enabled()) {
+ mPublisherProcessor.enabled()) {
mPublisherProcessor.unpublishCert((X509Certificate) cert, req);
if (mSummary == true)
buildItemParams(IEmailFormProcessor.TOKEN_STATUS,
- STATUS_SUCCESS);
+ STATUS_SUCCESS);
count += 1;
} else {
negCount += 1;
@@ -318,21 +304,21 @@ public class UnpublishExpiredJob extends AJobBase
negCount += 1;
if (mSummary == true)
buildItemParams(IEmailFormProcessor.TOKEN_STATUS,
- STATUS_FAILURE);
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("JOBS_UNPUBLISH_ERROR",
- cert.getSerialNumber().toString(16) +
- e.toString()));
+ STATUS_FAILURE);
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("JOBS_UNPUBLISH_ERROR",
+ cert.getSerialNumber().toString(16) +
+ e.toString()));
}
} // ridString != null
else {
try {
if ((mPublisherProcessor != null) &&
- mPublisherProcessor.enabled()) {
+ mPublisherProcessor.enabled()) {
mPublisherProcessor.unpublishCert((X509Certificate) cert, null);
if (mSummary == true)
buildItemParams(IEmailFormProcessor.TOKEN_STATUS,
- STATUS_SUCCESS);
+ STATUS_SUCCESS);
count += 1;
} else {
negCount += 1;
@@ -341,11 +327,11 @@ public class UnpublishExpiredJob extends AJobBase
negCount += 1;
if (mSummary == true)
buildItemParams(IEmailFormProcessor.TOKEN_STATUS,
- STATUS_FAILURE);
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("JOBS_UNPUBLISH_ERROR",
- cert.getSerialNumber().toString(16) +
- e.toString()));
+ STATUS_FAILURE);
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("JOBS_UNPUBLISH_ERROR",
+ cert.getSerialNumber().toString(16) +
+ e.toString()));
}
} // ridString == null
@@ -355,7 +341,7 @@ public class UnpublishExpiredJob extends AJobBase
// if summary is enabled, form the item content
if (mSummary) {
IEmailFormProcessor emailItemFormProcessor =
- CMS.getEmailFormProcessor();
+ CMS.getEmailFormProcessor();
String c = emailItemFormProcessor.getEmailContent(itemForm,
mItemParams);
@@ -371,36 +357,35 @@ public class UnpublishExpiredJob extends AJobBase
// time for summary
if (mSummary == true) {
buildContentParams(IEmailFormProcessor.TOKEN_ID,
- mId);
+ mId);
buildContentParams(IEmailFormProcessor.TOKEN_SUMMARY_ITEM_LIST,
- itemListContent);
+ itemListContent);
buildContentParams(IEmailFormProcessor.TOKEN_SUMMARY_TOTAL_NUM,
- String.valueOf(count + negCount));
+ String.valueOf(count + negCount));
buildContentParams(IEmailFormProcessor.TOKEN_SUMMARY_SUCCESS_NUM,
- String.valueOf(count));
+ String.valueOf(count));
buildContentParams(IEmailFormProcessor.TOKEN_SUMMARY_FAILURE_NUM,
- String.valueOf(negCount));
+ String.valueOf(negCount));
buildContentParams(IEmailFormProcessor.TOKEN_EXECUTION_TIME,
- nowString);
+ nowString);
IEmailFormProcessor emailFormProcessor = CMS.getEmailFormProcessor();
String mailContent =
- emailFormProcessor.getEmailContent(contentForm,
- mContentParams);
+ emailFormProcessor.getEmailContent(contentForm,
+ mContentParams);
mailSummary(mailContent);
}
}
/**
- * Returns a list of configuration parameter names.
- * The list is passed to the configuration console so instances of
- * this implementation can be configured through the console.
- *
+ * Returns a list of configuration parameter names. The list is passed to
+ * the configuration console so instances of this implementation can be
+ * configured through the console.
+ *
* @return String array of configuration parameter names.
*/
public String[] getConfigParams() {
return (mConfigParams);
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/listeners/CertificateIssuedListener.java b/pki/base/common/src/com/netscape/cms/listeners/CertificateIssuedListener.java
index d238c279..d2fefa24 100644
--- a/pki/base/common/src/com/netscape/cms/listeners/CertificateIssuedListener.java
+++ b/pki/base/common/src/com/netscape/cms/listeners/CertificateIssuedListener.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.listeners;
-
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
@@ -45,12 +44,11 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.IRequestListener;
import com.netscape.certsrv.request.RequestId;
-
/**
* a listener for every completed enrollment request
* <p>
- * Here is a list of available $TOKENs for email notification
- templates if certificate is successfully issued:
+ * Here is a list of available $TOKENs for email notification templates if
+ * certificate is successfully issued:
* <UL>
* <LI>$InstanceID
* <LI>$SerialNumber
@@ -66,13 +64,13 @@ import com.netscape.certsrv.request.RequestId;
* <LI>$RecipientEmail
* </UL>
* <p>
- * Here is a list of available $TOKENs for email notification
- templates if certificate request is rejected:
+ * Here is a list of available $TOKENs for email notification templates if
+ * certificate request is rejected:
* <UL>
* <LI>$RequestId
* <LI>$InstanceID
* </UL>
- *
+ *
* @version $Revision$, $Date$
*/
public class CertificateIssuedListener implements IRequestListener {
@@ -107,7 +105,7 @@ public class CertificateIssuedListener implements IRequestListener {
}
public void init(ISubsystem sub, IConfigStore config)
- throws EListenersException, EPropertyNotFound, EBaseException {
+ throws EListenersException, EPropertyNotFound, EBaseException {
mSubsystem = (ICertAuthority) sub;
mConfig = mSubsystem.getConfigStore();
@@ -125,13 +123,13 @@ public class CertificateIssuedListener implements IRequestListener {
String mDir = null;
// figure out the reject email path: same dir as form path,
- // same ending as form path
+ // same ending as form path
int ridx = mFormPath.lastIndexOf(File.separator);
if (ridx == -1) {
CMS.debug("CertificateIssuedListener: file separator: " + File.separator
- +
- " not found. Use default /");
+ +
+ " not found. Use default /");
ridx = mFormPath.lastIndexOf("/");
mDir = mFormPath.substring(0, ridx + 1);
} else {
@@ -166,9 +164,10 @@ public class CertificateIssuedListener implements IRequestListener {
}
public void accept(IRequest r) {
- CMS.debug("CertificateIssuedListener: accept " +
- r.getRequestId().toString());
- if (mEnabled != true) return;
+ CMS.debug("CertificateIssuedListener: accept " +
+ r.getRequestId().toString());
+ if (mEnabled != true)
+ return;
mSubject = mSubject_Success;
mReqId = r.getRequestId();
@@ -192,15 +191,15 @@ public class CertificateIssuedListener implements IRequestListener {
return;
if ((r.getExtDataInInteger(IRequest.RESULT)).equals(IRequest.RES_ERROR)) {
CMS.debug("CertificateIssuedListener: Request errored. " +
- "No need to email notify for enrollment request id " +
- mReqId);
+ "No need to email notify for enrollment request id " +
+ mReqId);
return;
}
}
String requestType = r.getRequestType();
if (requestType.equals(IRequest.ENROLLMENT_REQUEST) ||
- requestType.equals(IRequest.RENEWAL_REQUEST)) {
+ requestType.equals(IRequest.RENEWAL_REQUEST)) {
CMS.debug("accept() enrollment/renewal request...");
// Get the certificate from the request
X509CertImpl issuedCert[] = null;
@@ -224,10 +223,10 @@ public class CertificateIssuedListener implements IRequestListener {
try {
keys.set(IEmailResolverKeys.KEY_REQUEST, r);
keys.set(IEmailResolverKeys.KEY_CERT,
- issuedCert[0]);
+ issuedCert[0]);
} catch (EBaseException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("LISTENERS_CERT_ISSUED_SET_RESOLVER", e.toString()));
+ CMS.getLogMessage("LISTENERS_CERT_ISSUED_SET_RESOLVER", e.toString()));
}
IEmailResolver er = CMS.getReqCertSANameEmailResolver();
@@ -236,30 +235,30 @@ public class CertificateIssuedListener implements IRequestListener {
mEmail = er.getEmail(keys);
} catch (ENotificationException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("LISTENERS_CERT_ISSUED_EXCEPTION",
- e.toString()));
+ CMS.getLogMessage("LISTENERS_CERT_ISSUED_EXCEPTION",
+ e.toString()));
} catch (EBaseException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("LISTENERS_CERT_ISSUED_EXCEPTION",
- e.toString()));
+ CMS.getLogMessage("LISTENERS_CERT_ISSUED_EXCEPTION",
+ e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("LISTENERS_CERT_ISSUED_EXCEPTION",
- e.toString()));
+ CMS.getLogMessage("LISTENERS_CERT_ISSUED_EXCEPTION",
+ e.toString()));
}
-
+
// now we can mail
if ((mEmail != null) && (!mEmail.equals(""))) {
mailIt(mEmail, issuedCert);
} else {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("LISTENERS_CERT_ISSUED_NOTIFY_ERROR",
- issuedCert[0].getSerialNumber().toString(), mReqId.toString()));
+ CMS.getLogMessage("LISTENERS_CERT_ISSUED_NOTIFY_ERROR",
+ issuedCert[0].getSerialNumber().toString(), mReqId.toString()));
// send failure notification to "sender"
mSubject = "Certificate Issued notification undeliverable";
mailIt(mSenderEmail, issuedCert);
}
- }
+ }
}
}
@@ -282,7 +281,7 @@ public class CertificateIssuedListener implements IRequestListener {
if (!template.init()) {
return;
}
-
+
buildContentParams(issuedCert, mEmail);
IEmailFormProcessor et = CMS.getEmailFormProcessor();
String c = et.getEmailContent(template.toString(), mContentParams);
@@ -293,19 +292,19 @@ public class CertificateIssuedListener implements IRequestListener {
mn.setContent(c);
} else {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("LISTENERS_CERT_ISSUED_TEMPLATE_ERROR",
- issuedCert[0].getSerialNumber().toString(), mReqId.toString()));
+ CMS.getLogMessage("LISTENERS_CERT_ISSUED_TEMPLATE_ERROR",
+ issuedCert[0].getSerialNumber().toString(), mReqId.toString()));
mn.setContent("Serial Number = " +
- issuedCert[0].getSerialNumber() +
- "; Request ID = " + mReqId);
+ issuedCert[0].getSerialNumber() +
+ "; Request ID = " + mReqId);
}
-
+
try {
mn.sendNotification();
} catch (ENotificationException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("OPERATION_ERROR", e.toString()));
-
+
} catch (IOException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("OPERATION_ERROR", e.toString()));
}
@@ -320,7 +319,7 @@ public class CertificateIssuedListener implements IRequestListener {
keys.set(IEmailResolverKeys.KEY_REQUEST, r);
} catch (EBaseException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("LISTENERS_CERT_ISSUED_SET_RESOLVER", e.toString()));
+ CMS.getLogMessage("LISTENERS_CERT_ISSUED_SET_RESOLVER", e.toString()));
}
IEmailResolver er = CMS.getReqCertSANameEmailResolver();
@@ -352,17 +351,17 @@ public class CertificateIssuedListener implements IRequestListener {
if (!template.init()) {
return;
}
-
+
if (template.isHTML()) {
mn.setContentType("text/html");
}
// build some token data
mContentParams.put(IEmailFormProcessor.TOKEN_ID,
- mConfig.getName());
+ mConfig.getName());
mReqId = r.getRequestId();
mContentParams.put(IEmailFormProcessor.TOKEN_REQUEST_ID,
- (Object) mReqId.toString());
+ (Object) mReqId.toString());
IEmailFormProcessor et = CMS.getEmailFormProcessor();
String c = et.getEmailContent(template.toString(), mContentParams);
@@ -377,48 +376,48 @@ public class CertificateIssuedListener implements IRequestListener {
} catch (ENotificationException e) {
// already logged, lets audit
log(ILogger.LL_FAILURE, CMS.getLogMessage("OPERATION_ERROR", e.toString()));
-
+
} catch (IOException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("OPERATION_ERROR", e.toString()));
}
} else {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("LISTENERS_CERT_ISSUED_REJECTION_NOTIFICATION", mReqId.toString()));
+ CMS.getLogMessage("LISTENERS_CERT_ISSUED_REJECTION_NOTIFICATION", mReqId.toString()));
}
}
private void buildContentParams(X509CertImpl issuedCert[], String mEmail) {
mContentParams.put(IEmailFormProcessor.TOKEN_ID,
- mConfig.getName());
+ mConfig.getName());
mContentParams.put(IEmailFormProcessor.TOKEN_SERIAL_NUM,
- (Object) issuedCert[0].getSerialNumber().toString());
+ (Object) issuedCert[0].getSerialNumber().toString());
mContentParams.put(IEmailFormProcessor.TOKEN_HEX_SERIAL_NUM,
- (Object) Long.toHexString(issuedCert[0].getSerialNumber().longValue()));
+ (Object) Long.toHexString(issuedCert[0].getSerialNumber().longValue()));
mContentParams.put(IEmailFormProcessor.TOKEN_REQUEST_ID,
- (Object) mReqId.toString());
+ (Object) mReqId.toString());
mContentParams.put(IEmailFormProcessor.TOKEN_HTTP_HOST,
- (Object) mHttpHost);
+ (Object) mHttpHost);
mContentParams.put(IEmailFormProcessor.TOKEN_HTTP_PORT,
- (Object) mHttpPort);
+ (Object) mHttpPort);
mContentParams.put(IEmailFormProcessor.TOKEN_ISSUER_DN,
- (Object) issuedCert[0].getIssuerDN().toString());
+ (Object) issuedCert[0].getIssuerDN().toString());
mContentParams.put(IEmailFormProcessor.TOKEN_SUBJECT_DN,
- (Object) issuedCert[0].getSubjectDN().toString());
+ (Object) issuedCert[0].getSubjectDN().toString());
Date date = (Date) issuedCert[0].getNotAfter();
mContentParams.put(IEmailFormProcessor.TOKEN_NOT_AFTER,
- mDateFormat.format(date));
+ mDateFormat.format(date));
date = (Date) issuedCert[0].getNotBefore();
mContentParams.put(IEmailFormProcessor.TOKEN_NOT_BEFORE,
- mDateFormat.format(date));
+ mDateFormat.format(date));
mContentParams.put(IEmailFormProcessor.TOKEN_SENDER_EMAIL,
- (Object) mSenderEmail);
+ (Object) mSenderEmail);
mContentParams.put(IEmailFormProcessor.TOKEN_RECIPIENT_EMAIL,
- (Object) mEmail);
+ (Object) mEmail);
// ... and more
}
@@ -448,7 +447,7 @@ public class CertificateIssuedListener implements IRequestListener {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_OTHER,
- level, msg);
+ level, msg);
}
}
diff --git a/pki/base/common/src/com/netscape/cms/listeners/CertificateRevokedListener.java b/pki/base/common/src/com/netscape/cms/listeners/CertificateRevokedListener.java
index ca62af5f..a67c1c92 100644
--- a/pki/base/common/src/com/netscape/cms/listeners/CertificateRevokedListener.java
+++ b/pki/base/common/src/com/netscape/cms/listeners/CertificateRevokedListener.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.listeners;
-
import java.io.File;
import java.io.IOException;
import java.security.cert.X509Certificate;
@@ -47,12 +46,11 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.IRequestListener;
import com.netscape.certsrv.request.RequestId;
-
/**
* a listener for every completed enrollment request
* <p>
- * Here is a list of available $TOKENs for email notification
- templates if certificate is successfully issued:
+ * Here is a list of available $TOKENs for email notification templates if
+ * certificate is successfully issued:
* <UL>
* <LI>$InstanceID
* <LI>$SerialNumber
@@ -68,13 +66,13 @@ import com.netscape.certsrv.request.RequestId;
* <LI>$RecipientEmail
* </UL>
* <p>
- * Here is a list of available $TOKENs for email notification
- templates if certificate request is revoked:
+ * Here is a list of available $TOKENs for email notification templates if
+ * certificate request is revoked:
* <UL>
* <LI>$RequestId
* <LI>$InstanceID
* </UL>
- *
+ *
* @version $Revision$, $Date$
*/
public class CertificateRevokedListener implements IRequestListener {
@@ -109,7 +107,7 @@ public class CertificateRevokedListener implements IRequestListener {
}
public void init(ISubsystem sub, IConfigStore config)
- throws EListenersException, EPropertyNotFound, EBaseException {
+ throws EListenersException, EPropertyNotFound, EBaseException {
mSubsystem = (ICertAuthority) sub;
mConfig = mSubsystem.getConfigStore();
@@ -127,13 +125,13 @@ public class CertificateRevokedListener implements IRequestListener {
String mDir = null;
// figure out the reject email path: same dir as form path,
- // same ending as form path
+ // same ending as form path
int ridx = mFormPath.lastIndexOf(File.separator);
if (ridx == -1) {
CMS.debug("CertificateRevokedListener: file separator: " + File.separator
- +
- " not found. Use default /");
+ +
+ " not found. Use default /");
ridx = mFormPath.lastIndexOf("/");
mDir = mFormPath.substring(0, ridx + 1);
} else {
@@ -168,7 +166,8 @@ public class CertificateRevokedListener implements IRequestListener {
}
public void accept(IRequest r) {
- if (mEnabled != true) return;
+ if (mEnabled != true)
+ return;
mSubject = mSubject_Success;
mReqId = r.getRequestId();
@@ -180,7 +179,7 @@ public class CertificateRevokedListener implements IRequestListener {
return;
if (rs.equals("complete") == false) {
CMS.debug("CertificateRevokedListener: Request status: " + rs);
- //revoked(r);
+ // revoked(r);
return;
}
@@ -190,18 +189,18 @@ public class CertificateRevokedListener implements IRequestListener {
if ((r.getExtDataInInteger(IRequest.RESULT)).equals(IRequest.RES_ERROR)) {
CMS.debug("CertificateRevokedListener: Request errored. " +
- "No need to email notify for enrollment request id " +
- mReqId);
+ "No need to email notify for enrollment request id " +
+ mReqId);
return;
}
-
+
if (requestType.equals(IRequest.REVOCATION_REQUEST)) {
CMS.debug("CertificateRevokedListener: accept() revocation request...");
// Get the certificate from the request
- //X509CertImpl issuedCert[] =
- // (X509CertImpl[])
+ // X509CertImpl issuedCert[] =
+ // (X509CertImpl[])
RevokedCertImpl crlentries[] =
- r.getExtDataInRevokedCertArray(IRequest.CERT_INFO);
+ r.getExtDataInRevokedCertArray(IRequest.CERT_INFO);
if (crlentries != null) {
CMS.debug("CertificateRevokedListener: Sending email notification..");
@@ -213,10 +212,10 @@ public class CertificateRevokedListener implements IRequestListener {
try {
keys.set(IEmailResolverKeys.KEY_REQUEST, r);
keys.set(IEmailResolverKeys.KEY_CERT,
- crlentries[0]);
+ crlentries[0]);
} catch (EBaseException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("LISTENERS_CERT_ISSUED_SET_RESOLVER", e.toString()));
+ CMS.getLogMessage("LISTENERS_CERT_ISSUED_SET_RESOLVER", e.toString()));
}
IEmailResolver er = CMS.getReqCertSANameEmailResolver();
@@ -225,30 +224,30 @@ public class CertificateRevokedListener implements IRequestListener {
mEmail = er.getEmail(keys);
} catch (ENotificationException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("LISTENERS_CERT_ISSUED_EXCEPTION",
- e.toString()));
+ CMS.getLogMessage("LISTENERS_CERT_ISSUED_EXCEPTION",
+ e.toString()));
} catch (EBaseException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("LISTENERS_CERT_ISSUED_EXCEPTION",
- e.toString()));
+ CMS.getLogMessage("LISTENERS_CERT_ISSUED_EXCEPTION",
+ e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("LISTENERS_CERT_ISSUED_EXCEPTION",
- e.toString()));
+ CMS.getLogMessage("LISTENERS_CERT_ISSUED_EXCEPTION",
+ e.toString()));
}
-
+
// now we can mail
if ((mEmail != null) && (!mEmail.equals(""))) {
mailIt(mEmail, crlentries);
} else {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("LISTENERS_CERT_ISSUED_NOTIFY_ERROR",
- crlentries[0].getSerialNumber().toString(), mReqId.toString()));
+ CMS.getLogMessage("LISTENERS_CERT_ISSUED_NOTIFY_ERROR",
+ crlentries[0].getSerialNumber().toString(), mReqId.toString()));
// send failure notification to "sender"
mSubject = "Certificate Issued notification undeliverable";
mailIt(mSenderEmail, crlentries);
}
- }
+ }
}
}
@@ -271,7 +270,7 @@ public class CertificateRevokedListener implements IRequestListener {
if (!template.init()) {
return;
}
-
+
buildContentParams(crlentries, mEmail);
IEmailFormProcessor et = CMS.getEmailFormProcessor();
String c = et.getEmailContent(template.toString(), mContentParams);
@@ -282,19 +281,19 @@ public class CertificateRevokedListener implements IRequestListener {
mn.setContent(c);
} else {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("LISTENERS_CERT_ISSUED_TEMPLATE_ERROR",
- crlentries[0].getSerialNumber().toString(), mReqId.toString()));
+ CMS.getLogMessage("LISTENERS_CERT_ISSUED_TEMPLATE_ERROR",
+ crlentries[0].getSerialNumber().toString(), mReqId.toString()));
mn.setContent("Serial Number = " +
- crlentries[0].getSerialNumber() +
- "; Request ID = " + mReqId);
+ crlentries[0].getSerialNumber() +
+ "; Request ID = " + mReqId);
}
-
+
try {
mn.sendNotification();
} catch (ENotificationException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("OPERATION_ERROR", e.toString()));
-
+
} catch (IOException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("OPERATION_ERROR", e.toString()));
}
@@ -302,18 +301,18 @@ public class CertificateRevokedListener implements IRequestListener {
private void buildContentParams(RevokedCertImpl crlentries[], String mEmail) {
mContentParams.put(IEmailFormProcessor.TOKEN_ID,
- mConfig.getName());
+ mConfig.getName());
mContentParams.put(IEmailFormProcessor.TOKEN_SERIAL_NUM,
- (Object) crlentries[0].getSerialNumber().toString());
+ (Object) crlentries[0].getSerialNumber().toString());
mContentParams.put(IEmailFormProcessor.TOKEN_HEX_SERIAL_NUM,
- (Object) Long.toHexString(crlentries[0].getSerialNumber().longValue()));
+ (Object) Long.toHexString(crlentries[0].getSerialNumber().longValue()));
mContentParams.put(IEmailFormProcessor.TOKEN_REQUEST_ID,
- (Object) mReqId.toString());
+ (Object) mReqId.toString());
mContentParams.put(IEmailFormProcessor.TOKEN_HTTP_HOST,
- (Object) mHttpHost);
+ (Object) mHttpHost);
mContentParams.put(IEmailFormProcessor.TOKEN_HTTP_PORT,
- (Object) mHttpPort);
-
+ (Object) mHttpPort);
+
try {
RevokedCertImpl revCert = (RevokedCertImpl) crlentries[0];
ICertificateAuthority ca = (ICertificateAuthority) CMS.getSubsystem(CMS.SUBSYSTEM_CA);
@@ -321,22 +320,22 @@ public class CertificateRevokedListener implements IRequestListener {
X509Certificate cert = certDB.getX509Certificate(revCert.getSerialNumber());
mContentParams.put(IEmailFormProcessor.TOKEN_ISSUER_DN,
- (Object) cert.getIssuerDN().toString());
+ (Object) cert.getIssuerDN().toString());
mContentParams.put(IEmailFormProcessor.TOKEN_SUBJECT_DN,
- (Object) cert.getSubjectDN().toString());
+ (Object) cert.getSubjectDN().toString());
Date date = (Date) crlentries[0].getRevocationDate();
-
+
mContentParams.put(IEmailFormProcessor.TOKEN_REVOCATION_DATE,
- mDateFormat.format(date));
+ mDateFormat.format(date));
} catch (EBaseException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("LISTENERS_CERT_ISSUED_SET_RESOLVER", e.toString()));
+ CMS.getLogMessage("LISTENERS_CERT_ISSUED_SET_RESOLVER", e.toString()));
}
mContentParams.put(IEmailFormProcessor.TOKEN_SENDER_EMAIL,
- (Object) mSenderEmail);
+ (Object) mSenderEmail);
mContentParams.put(IEmailFormProcessor.TOKEN_RECIPIENT_EMAIL,
- (Object) mEmail);
+ (Object) mEmail);
// ... and more
}
@@ -366,7 +365,7 @@ public class CertificateRevokedListener implements IRequestListener {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_OTHER,
- level, msg);
+ level, msg);
}
}
diff --git a/pki/base/common/src/com/netscape/cms/listeners/PinRemovalListener.java b/pki/base/common/src/com/netscape/cms/listeners/PinRemovalListener.java
index 2f02774d..c71b9c60 100644
--- a/pki/base/common/src/com/netscape/cms/listeners/PinRemovalListener.java
+++ b/pki/base/common/src/com/netscape/cms/listeners/PinRemovalListener.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.listeners;
-
import java.util.Hashtable;
import netscape.ldap.LDAPAttribute;
@@ -39,10 +38,9 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.IRequestListener;
import com.netscape.certsrv.request.RequestId;
-
/**
* This represnets a listener that removes pin from LDAP directory.
- *
+ *
* @version $Revision$, $Date$
*/
public class PinRemovalListener implements IRequestListener {
@@ -87,18 +85,18 @@ public class PinRemovalListener implements IRequestListener {
protected String[] configParams = { "a" };
- public String[] getConfigParams()
- throws EBaseException {
+ public String[] getConfigParams()
+ throws EBaseException {
return configParams;
}
public void init(ISubsystem sub, IConfigStore config) throws EBaseException {
- init(null, null, config);
+ init(null, null, config);
}
public void init(String name, String ImplName, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mName = name;
mImplName = ImplName;
mConfig = config;
@@ -115,7 +113,8 @@ public class PinRemovalListener implements IRequestListener {
}
public void accept(IRequest r) {
- if (mEnabled != true) return;
+ if (mEnabled != true)
+ return;
mReqId = r.getRequestId();
@@ -129,7 +128,7 @@ public class PinRemovalListener implements IRequestListener {
String requestType = r.getRequestType();
if (requestType.equals(IRequest.ENROLLMENT_REQUEST) ||
- requestType.equals(IRequest.RENEWAL_REQUEST)) {
+ requestType.equals(IRequest.RENEWAL_REQUEST)) {
String uid = r.getExtDataInString(
IRequest.HTTP_PARAMS, "uid");
@@ -144,21 +143,21 @@ public class PinRemovalListener implements IRequestListener {
try {
LDAPSearchResults res = mRemovePinLdapConnection.search(mBaseDN,
LDAPv2.SCOPE_SUB, "(uid=" + uid + ")", null, false);
-
+
if (!res.hasMoreElements()) {
log(ILogger.LL_SECURITY, "uid " + uid + " does not exist in the ldap " +
- " server. Could not remove pin");
+ " server. Could not remove pin");
return;
}
LDAPEntry entry = (LDAPEntry) res.nextElement();
userdn = entry.getDN();
-
+
mRemovePinLdapConnection.modify(userdn,
- new LDAPModification(
- LDAPModification.DELETE,
- new LDAPAttribute(mPinAttr)));
+ new LDAPModification(
+ LDAPModification.DELETE,
+ new LDAPAttribute(mPinAttr)));
log(ILogger.LL_INFO, "Removed pin for user \"" + userdn + "\"");
@@ -173,10 +172,9 @@ public class PinRemovalListener implements IRequestListener {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_OTHER,
- level, "PinRemovalListener: " + msg);
+ level, "PinRemovalListener: " + msg);
}
public void set(String name, String val) {
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/listeners/RequestInQListener.java b/pki/base/common/src/com/netscape/cms/listeners/RequestInQListener.java
index f5810a46..18887f88 100644
--- a/pki/base/common/src/com/netscape/cms/listeners/RequestInQListener.java
+++ b/pki/base/common/src/com/netscape/cms/listeners/RequestInQListener.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.listeners;
-
import java.io.IOException;
import java.util.Hashtable;
@@ -39,7 +38,6 @@ import com.netscape.certsrv.request.RequestId;
import com.netscape.cms.profile.input.SubjectNameInput;
import com.netscape.cms.profile.input.SubmitterInfoInput;
-
/**
* a listener for every request gets into the request queue.
* <p>
@@ -54,7 +52,7 @@ import com.netscape.cms.profile.input.SubmitterInfoInput;
* <LI>$SenderEmail
* <LI>$RecipientEmail
* </UL>
- *
+ *
*/
public class RequestInQListener implements IRequestListener {
protected static final String PROP_ENABLED = "enabled";
@@ -89,8 +87,8 @@ public class RequestInQListener implements IRequestListener {
* initializes the listener from the configuration
*/
public void init(ISubsystem sub, IConfigStore config)
- throws EListenersException, EPropertyNotFound, EBaseException {
-
+ throws EListenersException, EPropertyNotFound, EBaseException {
+
mSubsystem = (ICertAuthority) sub;
mConfig = mSubsystem.getConfigStore();
@@ -118,32 +116,34 @@ public class RequestInQListener implements IRequestListener {
// make available http host and port for forming url in templates
mHttpHost = CMS.getAgentHost();
mAgentPort = CMS.getAgentPort();
- if (mAgentPort == null)
+ if (mAgentPort == null)
log(ILogger.LL_FAILURE, CMS.getLogMessage("LISTENERS_REQUEST_PORT_NOT_FOUND"));
else
CMS.debug("RequestInQuListener: agentport = " + mAgentPort);
- // register for this event listener
+ // register for this event listener
mSubsystem.registerPendingListener(this);
}
/**
* carries out the operation when the listener is triggered.
+ *
* @param r IRequest structure holding the request information
* @see com.netscape.certsrv.request.IRequest
*/
public void accept(IRequest r) {
- if (mEnabled != true) return;
+ if (mEnabled != true)
+ return;
- // regardless of type of request...notify for everything
- // no need for email resolver here...
+ // regardless of type of request...notify for everything
+ // no need for email resolver here...
IMailNotification mn = CMS.getMailNotification();
mn.setFrom(mSenderEmail);
mn.setTo(mRecipientEmail);
mn.setSubject(mEmailSubject + " (request id: " +
- r.getRequestId() + ")");
+ r.getRequestId() + ")");
/*
* get form file from disk
@@ -158,7 +158,7 @@ public class RequestInQListener implements IRequestListener {
log(ILogger.LL_FAILURE, CMS.getLogMessage("LISTENERS_TEMPLATE_NOT_INIT"));
return;
}
-
+
buildContentParams(r);
IEmailFormProcessor et = CMS.getEmailFormProcessor();
String c = et.getEmailContent(template.toString(), mContentParams);
@@ -169,8 +169,8 @@ public class RequestInQListener implements IRequestListener {
mn.setContent(c);
} else {
// log and mail
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("LISTENERS_TEMPLATE_NOT_GET"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("LISTENERS_TEMPLATE_NOT_GET"));
mn.setContent("Template not retrievable for Request in Queue notification");
}
@@ -179,78 +179,80 @@ public class RequestInQListener implements IRequestListener {
} catch (ENotificationException e) {
// already logged, lets audit
mLogger.log(ILogger.EV_AUDIT, null,
- ILogger.S_OTHER,
- ILogger.LL_FAILURE, CMS.getLogMessage("OPERATION_ERROR", e.toString()));
-
+ ILogger.S_OTHER,
+ ILogger.LL_FAILURE, CMS.getLogMessage("OPERATION_ERROR", e.toString()));
+
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- ILogger.LL_FAILURE,
- CMS.getLogMessage("LISTENERS_SEND_FAILED", e.toString()));
+ ILogger.LL_FAILURE,
+ CMS.getLogMessage("LISTENERS_SEND_FAILED", e.toString()));
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("LISTENERS_SEND_FAILED", e.toString()));
+ CMS.getLogMessage("LISTENERS_SEND_FAILED", e.toString()));
}
}
private void buildContentParams(IRequest r) {
mContentParams.clear();
mContentParams.put(IEmailFormProcessor.TOKEN_ID,
- mConfig.getName());
+ mConfig.getName());
Object val = null;
String profileId = r.getExtDataInString("profileId");
if (profileId == null) {
- val = r.getExtDataInString(IRequest.HTTP_PARAMS, "csrRequestorEmail");
+ val = r.getExtDataInString(IRequest.HTTP_PARAMS, "csrRequestorEmail");
} else {
- // use the submitter info if available, otherwise, use the
- // subject name input email
- val = r.getExtDataInString(SubmitterInfoInput.EMAIL);
+ // use the submitter info if available, otherwise, use the
+ // subject name input email
+ val = r.getExtDataInString(SubmitterInfoInput.EMAIL);
- if ((val == null) || (((String) val).compareTo("") == 0)) {
- val = r.getExtDataInString(SubjectNameInput.VAL_EMAIL);
- }
+ if ((val == null) || (((String) val).compareTo("") == 0)) {
+ val = r.getExtDataInString(SubjectNameInput.VAL_EMAIL);
+ }
}
if (val != null)
mContentParams.put(IEmailFormProcessor.TOKEN_REQUESTOR_EMAIL,
- val);
+ val);
if (profileId == null) {
- val = r.getExtDataInString(IRequest.HTTP_PARAMS, IRequest.CERT_TYPE);
+ val = r.getExtDataInString(IRequest.HTTP_PARAMS, IRequest.CERT_TYPE);
} else {
- val = profileId;
+ val = profileId;
}
if (val != null) {
mContentParams.put(IEmailFormProcessor.TOKEN_CERT_TYPE,
- val);
+ val);
}
RequestId reqId = r.getRequestId();
mContentParams.put(IEmailFormProcessor.TOKEN_REQUEST_ID,
- (Object) reqId.toString());
+ (Object) reqId.toString());
mContentParams.put(IEmailFormProcessor.TOKEN_ID, mId);
val = r.getRequestType();
if (val != null)
mContentParams.put(IEmailFormProcessor.TOKEN_REQUEST_TYPE,
- val);
+ val);
mContentParams.put(IEmailFormProcessor.TOKEN_HTTP_HOST,
- (Object) mHttpHost);
+ (Object) mHttpHost);
mContentParams.put(IEmailFormProcessor.TOKEN_HTTP_PORT,
- (Object) mAgentPort);
+ (Object) mAgentPort);
mContentParams.put(IEmailFormProcessor.TOKEN_SENDER_EMAIL,
- (Object) mSenderEmail);
+ (Object) mSenderEmail);
mContentParams.put(IEmailFormProcessor.TOKEN_RECIPIENT_EMAIL,
- (Object) mRecipientEmail);
+ (Object) mRecipientEmail);
}
/**
* sets the configurable parameters
- * @param name a String represents the name of the configuration parameter to be set
+ *
+ * @param name a String represents the name of the configuration parameter
+ * to be set
* @param val a String containing the value to be set for name
*/
public void set(String name, String val) {
@@ -277,7 +279,6 @@ public class RequestInQListener implements IRequestListener {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_OTHER,
- level, msg);
+ level, msg);
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/logging/LogEntry.java b/pki/base/common/src/com/netscape/cms/logging/LogEntry.java
index 4ab9f281..b95f2687 100644
--- a/pki/base/common/src/com/netscape/cms/logging/LogEntry.java
+++ b/pki/base/common/src/com/netscape/cms/logging/LogEntry.java
@@ -17,17 +17,15 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.logging;
-
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;
-
/**
* A log entry of LogFile
- *
+ *
* @version $Revision$, $Date$
*/
public class LogEntry {
@@ -43,7 +41,7 @@ public class LogEntry {
/**
* Constructor for a LogEntry.
- *
+ *
*/
public LogEntry(String entry) throws ParseException {
mEntry = entry;
@@ -52,10 +50,10 @@ public class LogEntry {
/**
* parse a log entry
- *
+ *
* return a vector of the segments of the entry
*/
-
+
public Vector parse() throws ParseException {
int x = mEntry.indexOf("[");
@@ -96,7 +94,8 @@ public class LogEntry {
row.addElement(mTime);
row.addElement(mDetail);
- //System.out.println(mSource +"," + mLevel +","+ mDate+","+mTime+","+mDetail);
+ // System.out.println(mSource +"," + mLevel +","+
+ // mDate+","+mTime+","+mDetail);
return row;
}
diff --git a/pki/base/common/src/com/netscape/cms/logging/LogFile.java b/pki/base/common/src/com/netscape/cms/logging/LogFile.java
index c2dd7b33..1e4bdc6c 100644
--- a/pki/base/common/src/com/netscape/cms/logging/LogFile.java
+++ b/pki/base/common/src/com/netscape/cms/logging/LogFile.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.logging;
-
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
@@ -81,7 +80,7 @@ import com.netscape.cmsutil.util.Utils;
/**
* A log event listener which write logs to log files
- *
+ *
* @version $Revision$, $Date$
**/
public class LogFile implements ILogEventListener, IExtendedPluginInfo {
@@ -108,7 +107,7 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
private final static String LOG_SIGNED_AUDIT_EXCEPTION =
"LOG_SIGNED_AUDIT_EXCEPTION_1";
- protected ILogger mSignedAuditLogger = CMS.getSignedAuditLogger();
+ protected ILogger mSignedAuditLogger = CMS.getSignedAuditLogger();
protected IConfigStore mConfig = null;
/**
@@ -116,7 +115,7 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
*/
static final String DATE_PATTERN = "yyyyMMddHHmmss";
- //It may be interesting to make this flexable someday....
+ // It may be interesting to make this flexable someday....
protected SimpleDateFormat mLogFileDateFormat = new SimpleDateFormat(DATE_PATTERN);
/**
@@ -152,7 +151,7 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
/**
* The log date entry format
*/
- protected SimpleDateFormat mLogDateFormat = new SimpleDateFormat(mDatePattern);
+ protected SimpleDateFormat mLogDateFormat = new SimpleDateFormat(mDatePattern);
/**
* The date object used for log entries
@@ -228,20 +227,20 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
static final String CRYPTO_PROVIDER = "Mozilla-JSS";
/**
- * The log level threshold
- * Only logs with level greater or equal than this value will be written
+ * The log level threshold Only logs with level greater or equal than this
+ * value will be written
*/
protected long mLevel = 1;
/**
* Constructor for a LogFile.
- *
+ *
*/
public LogFile() {
}
- public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ public void init(ISubsystem owner, IConfigStore config)
+ throws EBaseException {
mConfig = config;
try {
@@ -263,7 +262,7 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
try {
mSAuditCertNickName = config.getString(
PROP_SIGNED_AUDIT_CERT_NICKNAME);
- CMS.debug("LogFile: init(): audit log signing enabled. signedAuditCertNickname="+ mSAuditCertNickName);
+ CMS.debug("LogFile: init(): audit log signing enabled. signedAuditCertNickname=" + mSAuditCertNickName);
} catch (EBaseException e) {
throw new ELogException(CMS.getUserMessage("CMS_BASE_GET_PROPERTY_FAILED",
config.getName() + "."
@@ -272,9 +271,9 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
if (mSAuditCertNickName == null ||
mSAuditCertNickName.trim().equals("")) {
throw new ELogException(CMS.getUserMessage(
- "CMS_BASE_GET_PROPERTY_FAILED",
- config.getName() + "."
- + PROP_SIGNED_AUDIT_CERT_NICKNAME));
+ "CMS_BASE_GET_PROPERTY_FAILED",
+ config.getName() + "."
+ + PROP_SIGNED_AUDIT_CERT_NICKNAME));
}
}
@@ -309,13 +308,14 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
String eventId = tokens.nextToken().trim();
theVector.addElement(eventId);
- CMS.debug("LogFile: log event type selected: "+eventId);
+ CMS.debug("LogFile: log event type selected: " + eventId);
}
return theVector;
}
/**
* add the event to the selected events list
+ *
* @param event to be selected
*/
public void selectEvent(String event) {
@@ -325,6 +325,7 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
/**
* remove the event from the selected events list
+ *
* @param event to be de-selected
*/
public void deselectEvent(String event) {
@@ -334,6 +335,7 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
/**
* replace the selected events list
+ *
* @param events comma-separated event list
*/
public void replaceEvents(String events) {
@@ -348,9 +350,9 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
ByteArrayOutputStream output = new ByteArrayOutputStream();
Base64OutputStream b64 = new Base64OutputStream(new
PrintStream(new
- FilterOutputStream(output)
+ FilterOutputStream(output)
)
- );
+ );
b64.write(bytes);
b64.flush();
@@ -363,7 +365,7 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
private static boolean mInSignedAuditLogFailureMode = false;
private static synchronized void shutdownCMS() {
- if( mInSignedAuditLogFailureMode == false ) {
+ if (mInSignedAuditLogFailureMode == false) {
// Set signed audit log failure mode true
// No, this isn't a race condition, because the method is
@@ -371,7 +373,7 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
mInSignedAuditLogFailureMode = true;
// Block all new incoming requests
- if( CMS.areRequestsDisabled() == false ) {
+ if (CMS.areRequestsDisabled() == false) {
// XXX is this a race condition?
CMS.disableRequests();
}
@@ -389,7 +391,7 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
/**
* Initialize and open the log using the parameters from a config store
- *
+ *
* @param config The property config store to find values in
*/
public void init(IConfigStore config) throws IOException,
@@ -445,51 +447,51 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
// retrieve the subsystem
String subsystem = "";
- ISubsystem caSubsystem = CMS.getSubsystem( "ca" );
- if( caSubsystem != null ) {
+ ISubsystem caSubsystem = CMS.getSubsystem("ca");
+ if (caSubsystem != null) {
subsystem = "ca";
}
- ISubsystem raSubsystem = CMS.getSubsystem( "ra" );
- if( raSubsystem != null ) {
+ ISubsystem raSubsystem = CMS.getSubsystem("ra");
+ if (raSubsystem != null) {
subsystem = "ra";
}
- ISubsystem kraSubsystem = CMS.getSubsystem( "kra" );
- if( kraSubsystem != null ) {
+ ISubsystem kraSubsystem = CMS.getSubsystem("kra");
+ if (kraSubsystem != null) {
subsystem = "kra";
}
- ISubsystem ocspSubsystem = CMS.getSubsystem( "ocsp" );
- if( ocspSubsystem != null ) {
+ ISubsystem ocspSubsystem = CMS.getSubsystem("ocsp");
+ if (ocspSubsystem != null) {
subsystem = "ocsp";
}
// retrieve the instance name
String instIDPath = CMS.getInstanceDir();
- int index = instIDPath.lastIndexOf( "/" );
- String instID = instIDPath.substring( index + 1 );
+ int index = instIDPath.lastIndexOf("/");
+ String instID = instIDPath.substring(index + 1);
// build the default signedAudit file name
signedAuditDefaultFileName = subsystem + "_"
+ instID + "_" + "audit";
- } catch( Exception e2 ) {
+ } catch (Exception e2) {
throw new ELogException(
- CMS.getUserMessage( "CMS_BASE_GET_PROPERTY_FAILED",
+ CMS.getUserMessage("CMS_BASE_GET_PROPERTY_FAILED",
config.getName() + "." +
- PROP_FILE_NAME ) );
+ PROP_FILE_NAME));
}
// the default value is determined by the eventType.
if (mType.equals(ILogger.PROP_SIGNED_AUDIT)) {
defaultFileName = "logs/signedAudit/" + signedAuditDefaultFileName;
- }else if (mType.equals(ILogger.PROP_SYSTEM)) {
+ } else if (mType.equals(ILogger.PROP_SYSTEM)) {
defaultFileName = "logs/system";
- }else if (mType.equals(ILogger.PROP_AUDIT)) {
+ } else if (mType.equals(ILogger.PROP_AUDIT)) {
defaultFileName = "logs/transactions";
- }else {
- //wont get here
+ } else {
+ // wont get here
throw new ELogException(CMS.getUserMessage("CMS_LOG_INVALID_LOG_TYPE",
config.getName()));
}
@@ -502,29 +504,29 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
}
if (mOn) {
- init(fileName, config.getInteger(PROP_BUFFER_SIZE, BUFFER_SIZE),
- config.getInteger(PROP_FLUSH_INTERVAL, FLUSH_INTERVAL));
+ init(fileName, config.getInteger(PROP_BUFFER_SIZE, BUFFER_SIZE),
+ config.getInteger(PROP_FLUSH_INTERVAL, FLUSH_INTERVAL));
}
}
/**
* Initialize and open the log
- *
- * @param bufferSize The buffer size for the output stream in bytes
- * @param flushInterval The interval in seconds to flush the log
+ *
+ * @param bufferSize The buffer size for the output stream in bytes
+ * @param flushInterval The interval in seconds to flush the log
*/
- public void init(String fileName, int bufferSize, int flushInterval) throws IOException,ELogException {
+ public void init(String fileName, int bufferSize, int flushInterval) throws IOException, ELogException {
if (fileName == null)
throw new ELogException(CMS.getUserMessage("CMS_LOG_INVALID_FILE_NAME", "null"));
- //If we want to reuse the old log files
- //mFileName = fileName + "." + mLogFileDateFormat.format(mDate);
+ // If we want to reuse the old log files
+ // mFileName = fileName + "." + mLogFileDateFormat.format(mDate);
mFileName = fileName;
- if( !Utils.isNT() ) {
+ if (!Utils.isNT()) {
// Always insure that a physical file exists!
- Utils.exec( "touch " + mFileName );
- Utils.exec( "chmod 00640 " + mFileName );
+ Utils.exec("touch " + mFileName);
+ Utils.exec("chmod 00640 " + mFileName);
}
mFile = new File(mFileName);
mBufferSize = bufferSize;
@@ -540,25 +542,25 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
Provider[] providers = java.security.Security.getProviders();
int ps = providers.length;
- for (int i = 0; i<ps; i++) {
- CMS.debug("LogFile: provider "+i+"= "+providers[i].getName());
+ for (int i = 0; i < ps; i++) {
+ CMS.debug("LogFile: provider " + i + "= " + providers[i].getName());
}
CryptoManager cm = CryptoManager.getInstance();
// find CertServer's private key
- X509Certificate cert = cm.findCertByNickname( mSAuditCertNickName );
+ X509Certificate cert = cm.findCertByNickname(mSAuditCertNickName);
if (cert != null) {
- CMS.debug("LogFile: setupSignig(): found cert:"+mSAuditCertNickName);
+ CMS.debug("LogFile: setupSignig(): found cert:" + mSAuditCertNickName);
} else {
- CMS.debug("LogFile: setupSignig(): cert not found:"+mSAuditCertNickName);
+ CMS.debug("LogFile: setupSignig(): cert not found:" + mSAuditCertNickName);
}
mSigningKey = cm.findPrivKeyByCert(cert);
String sigAlgorithm;
- if( mSigningKey instanceof RSAPrivateKey ) {
+ if (mSigningKey instanceof RSAPrivateKey) {
sigAlgorithm = "SHA-256/RSA";
- } else if( mSigningKey instanceof DSAPrivateKey ) {
+ } else if (mSigningKey instanceof DSAPrivateKey) {
sigAlgorithm = "SHA-256/DSA";
} else {
throw new NoSuchAlgorithmException("Unknown private key type");
@@ -567,11 +569,11 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
CryptoToken savedToken = cm.getThreadToken();
try {
CryptoToken keyToken =
- ((org.mozilla.jss.pkcs11.PK11PrivKey)mSigningKey)
- .getOwningToken();
+ ((org.mozilla.jss.pkcs11.PK11PrivKey) mSigningKey)
+ .getOwningToken();
cm.setThreadToken(keyToken);
mSignature = java.security.Signature.getInstance(sigAlgorithm,
- CRYPTO_PROVIDER);
+ CRYPTO_PROVIDER);
} finally {
cm.setThreadToken(savedToken);
}
@@ -580,7 +582,7 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
// get the last signature from the currently-opened file
String entry = getLastSignature(mFile);
- if( entry != null ) {
+ if (entry != null) {
mSignature.update(entry.getBytes("UTF-8"));
mSignature.update(LINE_SEP_BYTE);
}
@@ -614,12 +616,11 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
}
private static void setupSigningFailure(String logMessageCode, Exception e)
- throws EBaseException
- {
+ throws EBaseException {
try {
- ConsoleError.send( new SystemEvent(
- CMS.getLogMessage(logMessageCode)));
- } catch(Exception e2) {
+ ConsoleError.send(new SystemEvent(
+ CMS.getLogMessage(logMessageCode)));
+ } catch (Exception e2) {
// don't allow an exception while printing to the console
// prevent us from running the rest of this function.
e2.printStackTrace();
@@ -632,36 +633,36 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
/**
* Startup the instance
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_AUDIT_LOG_STARTUP used at audit
* function startup
* </ul>
+ *
* @exception EBaseException if an internal error occurred
*/
public void startup() throws EBaseException {
// ensure that any low-level exceptions are reported
// to the signed audit log and stored as failures
CMS.debug("LogFile: entering LogFile.startup()");
- if( mOn && mLogSigning ) {
+ if (mOn && mLogSigning) {
try {
setupSigning();
- audit( CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_AUDIT_LOG_STARTUP,
- ILogger.SYSTEM_UID,
- ILogger.SUCCESS) );
- } catch(EBaseException e) {
- audit( CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_AUDIT_LOG_STARTUP,
- ILogger.SYSTEM_UID,
- ILogger.FAILURE) );
+ audit(CMS.getLogMessage(
+ LOGGING_SIGNED_AUDIT_AUDIT_LOG_STARTUP,
+ ILogger.SYSTEM_UID,
+ ILogger.SUCCESS));
+ } catch (EBaseException e) {
+ audit(CMS.getLogMessage(
+ LOGGING_SIGNED_AUDIT_AUDIT_LOG_STARTUP,
+ ILogger.SYSTEM_UID,
+ ILogger.FAILURE));
throw e;
}
}
}
-
/**
* Retrieves the eventType this log is triggered.
*/
@@ -673,7 +674,7 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
* Retrieves the log on/off.
*/
public String getOn() {
- return String.valueOf( mOn );
+ return String.valueOf(mOn);
}
/**
@@ -695,22 +696,22 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
/**
* Record that the signed audit log has been signed
* <P>
- *
+ *
* <ul>
- * <li>signed.audit LOGGING_SIGNED_AUDIT_SIGNING used when a signature on the
- * audit log is generated (same as "flush" time)
+ * <li>signed.audit LOGGING_SIGNED_AUDIT_SIGNING used when a signature on
+ * the audit log is generated (same as "flush" time)
* </ul>
+ *
* @exception IOException for input/output problems
* @exception ELogException when plugin implementation fails
* @exception SignatureException when signing fails
* @exception InvalidKeyException when an invalid key is utilized
*/
private void pushSignature() throws IOException, ELogException,
- SignatureException, InvalidKeyException
- {
+ SignatureException, InvalidKeyException {
byte[] sigBytes = null;
- if( mSignature == null ) {
+ if (mSignature == null) {
return;
}
@@ -727,31 +728,31 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
LOGGING_SIGNED_AUDIT_SIGNING,
ILogger.SYSTEM_UID,
ILogger.SUCCESS,
- base64Encode( sigBytes ) );
+ base64Encode(sigBytes));
- if( mSignedAuditLogger == null ) {
+ if (mSignedAuditLogger == null) {
return;
}
ILogEvent ev = mSignedAuditLogger.create(
ILogger.EV_SIGNED_AUDIT,
- ( Properties ) null,
+ (Properties) null,
ILogger.S_SIGNED_AUDIT,
ILogger.LL_SECURITY,
auditMessage,
o,
- ILogger.L_SINGLELINE );
+ ILogger.L_SINGLELINE);
- String logMesg = logEvt2String(ev);
+ String logMesg = logEvt2String(ev);
doLog(logMesg, true);
}
private static String getLastSignature(File f) throws IOException {
- BufferedReader r = new BufferedReader( new FileReader(f) );
+ BufferedReader r = new BufferedReader(new FileReader(f));
String lastSig = null;
String curLine = null;
- while( (curLine = r.readLine()) != null ) {
- if( curLine.indexOf("AUDIT_LOG_SIGNING") != -1 ) {
+ while ((curLine = r.readLine()) != null) {
+ if (curLine.indexOf("AUDIT_LOG_SIGNING") != -1) {
lastSig = curLine;
}
}
@@ -760,8 +761,8 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
}
/**
- * Open the log file. This creates the buffered FileWriter
- *
+ * Open the log file. This creates the buffered FileWriter
+ *
*/
protected synchronized void open() throws IOException {
RandomAccessFile out;
@@ -769,14 +770,14 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
try {
out = new RandomAccessFile(mFile, "rw");
out.seek(out.length());
- //XXX int or long?
+ // XXX int or long?
mBytesWritten = (int) out.length();
- if( !Utils.isNT() ) {
+ if (!Utils.isNT()) {
try {
- Utils.exec( "chmod 00640 " + mFile.getCanonicalPath() );
- } catch( IOException e ) {
- CMS.debug( "Unable to change file permissions on "
- + mFile.toString() );
+ Utils.exec("chmod 00640 " + mFile.getCanonicalPath());
+ } catch (IOException e) {
+ CMS.debug("Unable to change file permissions on "
+ + mFile.toString());
}
}
mLogWriter = new BufferedWriter(
@@ -785,20 +786,20 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
// The first time we open, mSignature will not have been
// initialized yet. That's ok, we will push our first signature
// in setupSigning().
- if( mLogSigning && (mSignature != null)) {
+ if (mLogSigning && (mSignature != null)) {
try {
pushSignature();
} catch (ELogException le) {
ConsoleError.send(
- new SystemEvent(CMS.getUserMessage("CMS_LOG_ILLEGALARGUMENT",
- mFileName)));
+ new SystemEvent(CMS.getUserMessage("CMS_LOG_ILLEGALARGUMENT",
+ mFileName)));
}
}
} catch (IllegalArgumentException iae) {
ConsoleError.send(
- new SystemEvent(CMS.getUserMessage("CMS_LOG_ILLEGALARGUMENT",
- mFileName)));
- } catch(GeneralSecurityException gse) {
+ new SystemEvent(CMS.getUserMessage("CMS_LOG_ILLEGALARGUMENT",
+ mFileName)));
+ } catch (GeneralSecurityException gse) {
// error with signed audit log, shutdown CMS
gse.printStackTrace();
shutdownCMS();
@@ -808,12 +809,12 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
}
/**
- * Flush the log file. Also update the MAC for hash protected logs
- *
+ * Flush the log file. Also update the MAC for hash protected logs
+ *
*/
public synchronized void flush() {
try {
- if( mLogSigning ) {
+ if (mLogSigning) {
try {
pushSignature();
} catch (ELogException le) {
@@ -827,11 +828,11 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
} catch (IOException e) {
ConsoleError.send(new SystemEvent(CMS.getUserMessage("CMS_LOG_FLUSH_LOG_FAILED", mFileName, e.toString())));
if (mLogSigning) {
- //error in writing to signed audit log, shut down CMS
+ // error in writing to signed audit log, shut down CMS
e.printStackTrace();
shutdownCMS();
}
- } catch(GeneralSecurityException gse) {
+ } catch (GeneralSecurityException gse) {
// error with signed audit log, shutdown CMS
gse.printStackTrace();
shutdownCMS();
@@ -842,7 +843,7 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
/**
* Close the log file
- *
+ *
*/
protected synchronized void close() {
try {
@@ -859,7 +860,7 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
/**
* Shutdown this log file.
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_AUDIT_LOG_SHUTDOWN used at audit
* function shutdown
@@ -876,9 +877,9 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_AUDIT_LOG_SHUTDOWN,
ILogger.SYSTEM_UID,
- ILogger.SUCCESS );
+ ILogger.SUCCESS);
- audit( auditMessage );
+ audit(auditMessage);
close();
}
@@ -886,9 +887,10 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
/**
* Set the flush interval
* <P>
- * @param flushInterval The amount of time in seconds until the log
- * is flush. A value of 0 will disable autoflush. This will also set
- * the update period for hash protected logs.
+ *
+ * @param flushInterval The amount of time in seconds until the log is
+ * flush. A value of 0 will disable autoflush. This will also set
+ * the update period for hash protected logs.
**/
public synchronized void setFlushInterval(int flushInterval) {
mFlushInterval = flushInterval * 1000;
@@ -903,8 +905,8 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
}
/**
- * Log flush thread. Sleep for the flush interval and flush the
- * log. Changing flush interval to 0 will cause this thread to exit.
+ * Log flush thread. Sleep for the flush interval and flush the log.
+ * Changing flush interval to 0 will cause this thread to exit.
*/
final class FlushThread extends Thread {
@@ -925,7 +927,7 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
} catch (InterruptedException e) {
// This shouldn't happen very often
ConsoleError.send(new
- SystemEvent(CMS.getUserMessage("CMS_LOG_THREAD_INTERRUPT", "flush")));
+ SystemEvent(CMS.getUserMessage("CMS_LOG_THREAD_INTERRUPT", "flush")));
}
}
@@ -942,10 +944,10 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
}
/**
- * Synchronized method to write a string to the log file. All I18N
- * should take place before this call.
- *
- * @param entry The log entry string
+ * Synchronized method to write a string to the log file. All I18N should
+ * take place before this call.
+ *
+ * @param entry The log entry string
*/
protected synchronized void log(String entry) throws ELogException {
doLog(entry, false);
@@ -957,9 +959,9 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
private static final byte LINE_SEP_BYTE = 0x0a;
/**
- * This method actually does the logging, and is not overridden
- * by subclasses, so you can call it and know that it will do exactly
- * what you see below.
+ * This method actually does the logging, and is not overridden by
+ * subclasses, so you can call it and know that it will do exactly what you
+ * see below.
*/
private synchronized void doLog(String entry, boolean noFlush)
throws ELogException {
@@ -969,51 +971,51 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
throw new ELogException(CMS.getUserMessage("CMS_LOG_LOGFILE_CLOSED", params));
} else {
try {
- mLogWriter.write(entry, 0/*offset*/, entry.length());
+ mLogWriter.write(entry, 0/* offset */, entry.length());
- if (mLogSigning==true) {
- if(mSignature != null) {
+ if (mLogSigning == true) {
+ if (mSignature != null) {
// include newline for calculating MAC
mSignature.update(entry.getBytes("UTF-8"));
} else {
CMS.debug("LogFile: mSignature is not yet ready... null in log()");
}
}
- if (mTrace) {
- CharArrayWriter cw = new CharArrayWriter(200);
+ if (mTrace) {
+ CharArrayWriter cw = new CharArrayWriter(200);
PrintWriter pw = new PrintWriter(cw);
Exception e = new Exception();
- e.printStackTrace(pw);
- char[] c = cw.toCharArray();
- cw.close();
+ e.printStackTrace(pw);
+ char[] c = cw.toCharArray();
+ cw.close();
pw.close();
- CharArrayReader cr = new CharArrayReader(c);
+ CharArrayReader cr = new CharArrayReader(c);
LineNumberReader lr = new LineNumberReader(cr);
- String text = null;
- String method = null;
+ String text = null;
+ String method = null;
String fileAndLine = null;
- if (lr.ready()) {
- text = lr.readLine();
- do {
- text = lr.readLine();
+ if (lr.ready()) {
+ text = lr.readLine();
+ do {
+ text = lr.readLine();
} while (text.indexOf("logging") != -1);
- int p = text.indexOf("(");
+ int p = text.indexOf("(");
fileAndLine = text.substring(p);
- String classandmethod = text.substring(0, p);
- int q = classandmethod.lastIndexOf(".");
- method = classandmethod.substring(q + 1);
- mLogWriter.write(fileAndLine, 0/*offset*/, fileAndLine.length());
- mLogWriter.write(" ", 0/*offset*/, " ".length());
- mLogWriter.write(method, 0/*offset*/, method.length());
+ String classandmethod = text.substring(0, p);
+ int q = classandmethod.lastIndexOf(".");
+ method = classandmethod.substring(q + 1);
+ mLogWriter.write(fileAndLine, 0/* offset */, fileAndLine.length());
+ mLogWriter.write(" ", 0/* offset */, " ".length());
+ mLogWriter.write(method, 0/* offset */, method.length());
}
}
mLogWriter.newLine();
- if (mLogSigning==true){
- if(mSignature != null) {
+ if (mLogSigning == true) {
+ if (mSignature != null) {
mSignature.update(LINE_SEP_BYTE);
} else {
CMS.debug("LogFile: mSignature is null in log() 2");
@@ -1027,23 +1029,22 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
shutdownCMS();
}
} catch (IllegalStateException e) {
- CMS.debug("LogFile: exception thrown in log(): "+e.toString());
- ConsoleError.send(new SignedAuditEvent(CMS.getLogMessage(LOG_SIGNED_AUDIT_EXCEPTION,e.toString())));
- } catch( GeneralSecurityException gse ) {
+ CMS.debug("LogFile: exception thrown in log(): " + e.toString());
+ ConsoleError.send(new SignedAuditEvent(CMS.getLogMessage(LOG_SIGNED_AUDIT_EXCEPTION, e.toString())));
+ } catch (GeneralSecurityException gse) {
// DJN: handle error
CMS.debug("LogFile: exception thrown in log(): "
- + gse.toString());
+ + gse.toString());
gse.printStackTrace();
ConsoleError.send(new SignedAuditEvent(CMS.getLogMessage(
- LOG_SIGNED_AUDIT_EXCEPTION,gse.toString())));
+ LOG_SIGNED_AUDIT_EXCEPTION, gse.toString())));
}
-
// XXX
// Although length will be in Unicode dual-bytes, the PrintWriter
- // will only print out 1 byte per character. I suppose this could
+ // will only print out 1 byte per character. I suppose this could
// be dependent on the encoding of your log file, but it ain't that
- // smart yet. Also, add one for the newline. (hmm, on NT, CR+LF)
+ // smart yet. Also, add one for the newline. (hmm, on NT, CR+LF)
int nBytes = entry.length() + 1;
mBytesWritten += nBytes;
@@ -1057,8 +1058,8 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
/**
* Write an event to the log file
- *
- * @param ev The event to be logged.
+ *
+ * @param ev The event to be logged.
*/
public void log(ILogEvent ev) throws ELogException {
if (ev instanceof AuditEvent) {
@@ -1069,7 +1070,7 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
if (!mType.equals("system") || (!mOn) || mLevel > ev.getLevel()) {
return;
}
- } else if (ev instanceof SignedAuditEvent) {
+ } else if (ev instanceof SignedAuditEvent) {
if (!mType.equals("signedAudit") || (!mOn) || mLevel > ev.getLevel()) {
return;
}
@@ -1082,7 +1083,7 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
String type = ev.getEventType();
if (type != null) {
if (!mSelectedEvents.contains(type)) {
- CMS.debug("LogFile: event type not selected: "+type);
+ CMS.debug("LogFile: event type not selected: " + type);
return;
}
}
@@ -1120,13 +1121,13 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
/**
* change multi-line log entry by replace "\n" with "\n "
- *
- * @param original The original multi-line log entry.
+ *
+ * @param original The original multi-line log entry.
*/
private String prepareMultiline(String original) {
int i, last = 0;
- //NT: \r\n, unix: \n
+ // NT: \r\n, unix: \n
while ((i = original.indexOf("\n", last)) != -1) {
last = i + 1;
original = original.substring(0, i + 1) + " " + original.substring(i + 1);
@@ -1135,15 +1136,15 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
}
/**
- * Read all entries whose logLevel>=lowLevel && log source = source
- * to at most maxLine entries(from end)
- * If the parameter is -1, it's ignored and return all entries
- *
+ * Read all entries whose logLevel>=lowLevel && log source = source to at
+ * most maxLine entries(from end) If the parameter is -1, it's ignored and
+ * return all entries
+ *
* @param maxLine The maximum lines to be returned
* @param lowLevel The lowest log level to be returned
* @param source The particular log source to be returned
* @param fName The log file name to be read. If it's null, read the current
- * log file
+ * log file
*/
public Vector<LogEntry> readEntry(int maxLine, int lowLevel, int source, String fName) {
Vector<LogEntry> mEntries = new Vector<LogEntry>();
@@ -1152,23 +1153,23 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
int lineNo = 0; // lineNo of the current entry in the log file
int line = 0; // line of readed valid entries
String firstLine = null; // line buffer
- String nextLine = null;
+ String nextLine = null;
String entry = null;
LogEntry logEntry = null;
/*
- this variable is added to accormodate misplaced multiline entries
- write out buffered log entry when next entry is parsed successfully
- this implementation is assuming parsing is more time consuming than
- condition check
+ * this variable is added to accormodate misplaced multiline entries
+ * write out buffered log entry when next entry is parsed successfully
+ * this implementation is assuming parsing is more time consuming than
+ * condition check
*/
- LogEntry preLogEntry = null;
+ LogEntry preLogEntry = null;
if (fName != null) {
fileName = fName;
}
try {
- //XXX think about this
+ // XXX think about this
fBuffer = new BufferedReader(new FileReader(fileName));
do {
try {
@@ -1194,9 +1195,9 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
// if parse succeed, write out previous entry
if (preLogEntry != null) {
if ((Integer.parseInt(preLogEntry.getLevel()) >= lowLevel) &&
- ((Integer.parseInt(preLogEntry.getSource()) == source) ||
+ ((Integer.parseInt(preLogEntry.getSource()) == source) ||
(source == ILogger.S_ALL)
- )) {
+ )) {
mEntries.addElement(preLogEntry);
if (maxLine == -1) {
line++;
@@ -1223,13 +1224,12 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
} catch (IOException e) {
CMS.getLogger().log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- ILogger.LL_FAILURE,
- CMS.getLogMessage("LOGGING_READ_ERROR", fileName,
- Integer.toString(lineNo)));
+ ILogger.LL_FAILURE,
+ CMS.getLogMessage("LOGGING_READ_ERROR", fileName,
+ Integer.toString(lineNo)));
}
- }
- while (nextLine != null);
+ } while (nextLine != null);
// need to process the last 2 entries of the file
if (firstLine != null) {
@@ -1240,17 +1240,18 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
try {
logEntry = new LogEntry(entry);
- /* System.out.println(
- Integer.toString(Integer.parseInt(logEntry.getLevel()))
- +","+Integer.toString(lowLevel)+","+
- Integer.toString(Integer.parseInt(logEntry.getSource()))
- +","+Integer.toString(source) );
+ /*
+ * System.out.println(
+ * Integer.toString(Integer.parseInt(logEntry.getLevel()))
+ * +","+Integer.toString(lowLevel)+","+
+ * Integer.toString(Integer.parseInt(logEntry.getSource()))
+ * +","+Integer.toString(source) );
*/
if (preLogEntry != null) {
if ((Integer.parseInt(preLogEntry.getLevel()) >= lowLevel) &&
- ((Integer.parseInt(preLogEntry.getSource()) == source) ||
+ ((Integer.parseInt(preLogEntry.getSource()) == source) ||
(source == ILogger.S_ALL)
- )) {
+ )) {
mEntries.addElement(preLogEntry);
if (maxLine == -1) {
line++;
@@ -1268,11 +1269,11 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
if (preLogEntry != null) {
if ((Integer.parseInt(preLogEntry.getLevel()) >= lowLevel)
- &&
- ((Integer.parseInt(preLogEntry.getSource()) == source)
+ &&
+ ((Integer.parseInt(preLogEntry.getSource()) == source)
||
(source == ILogger.S_ALL)
- )) {
+ )) {
// parse the entry, pass to UI
mEntries.addElement(preLogEntry);
if (maxLine == -1) {
@@ -1291,15 +1292,15 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
fBuffer.close();
} catch (IOException e) {
CMS.getLogger().log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- ILogger.LL_FAILURE, "logging:" + fileName +
- " failed to close for reading");
+ ILogger.LL_FAILURE, "logging:" + fileName +
+ " failed to close for reading");
}
} catch (FileNotFoundException e) {
CMS.getLogger().log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- ILogger.LL_FAILURE,
- CMS.getLogMessage("LOGGING_FILE_NOT_FOUND",
- fileName));
+ ILogger.LL_FAILURE,
+ CMS.getLogMessage("LOGGING_FILE_NOT_FOUND",
+ fileName));
}
return mEntries;
}
@@ -1307,7 +1308,7 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
/**
* Retrieves the configuration store of this subsystem.
* <P>
- *
+ *
* @return configuration store
*/
public IConfigStore getConfigStore() {
@@ -1315,27 +1316,27 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
}
/**
- * Retrieve last "maxLine" number of system log with log lever >"level"
- * and from source "source". If the parameter is omitted. All entries
- * are sent back.
+ * Retrieve last "maxLine" number of system log with log lever >"level" and
+ * from source "source". If the parameter is omitted. All entries are sent
+ * back.
*/
public synchronized NameValuePairs retrieveLogContent(Hashtable<String, String> req) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
String tmp, fName = null;
int maxLine = -1, level = -1, source = -1;
- Vector<LogEntry> entries = null;
+ Vector<LogEntry> entries = null;
- if ((tmp = (String)req.get(Constants.PR_LOG_ENTRY)) != null) {
+ if ((tmp = (String) req.get(Constants.PR_LOG_ENTRY)) != null) {
maxLine = Integer.parseInt(tmp);
}
- if ((tmp = (String)req.get(Constants.PR_LOG_LEVEL)) != null) {
+ if ((tmp = (String) req.get(Constants.PR_LOG_LEVEL)) != null) {
level = Integer.parseInt(tmp);
}
- if ((tmp = (String)req.get(Constants.PR_LOG_SOURCE)) != null) {
+ if ((tmp = (String) req.get(Constants.PR_LOG_SOURCE)) != null) {
source = Integer.parseInt(tmp);
}
- tmp = (String)req.get(Constants.PR_LOG_NAME);
+ tmp = (String) req.get(Constants.PR_LOG_NAME);
if (!(tmp.equals(Constants.PR_CURRENT_LOG))) {
fName = tmp;
} else {
@@ -1346,12 +1347,12 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
entries = readEntry(maxLine, level, source, fName);
for (int i = 0; i < entries.size(); i++) {
params.add(Integer.toString(i) +
- ((LogEntry) entries.elementAt(i)).getEntry(), "");
+ ((LogEntry) entries.elementAt(i)).getEntry(), "");
}
} catch (Exception e) {
CMS.getLogger().log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- ILogger.LL_WARN,
- "System log parse error");
+ ILogger.LL_WARN,
+ "System log parse error");
}
return params;
}
@@ -1385,11 +1386,11 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
// needs to find a way to determine what type you want. if this
// is not for the signed audit type, then we should not show the
// following parameters.
- //if( mType.equals( ILogger.PROP_SIGNED_AUDIT ) ) {
- v.addElement( PROP_SIGNED_AUDIT_LOG_SIGNING + "=" );
- v.addElement( PROP_SIGNED_AUDIT_CERT_NICKNAME + "=" );
- v.addElement( PROP_SIGNED_AUDIT_EVENTS + "=" );
- //}
+ // if( mType.equals( ILogger.PROP_SIGNED_AUDIT ) ) {
+ v.addElement(PROP_SIGNED_AUDIT_LOG_SIGNING + "=");
+ v.addElement(PROP_SIGNED_AUDIT_CERT_NICKNAME + "=");
+ v.addElement(PROP_SIGNED_AUDIT_EVENTS + "=");
+ // }
return v;
}
@@ -1401,11 +1402,11 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
if (mType == null) {
v.addElement(PROP_TYPE + "=");
- }else {
+ } else {
v.addElement(PROP_TYPE + "=" +
- mConfig.getString(PROP_TYPE));
+ mConfig.getString(PROP_TYPE));
}
- v.addElement(PROP_ON + "=" + String.valueOf( mOn ) );
+ v.addElement(PROP_ON + "=" + String.valueOf(mOn));
if (mLevel == 0)
v.addElement(PROP_LEVEL + "=" + ILogger.LL_DEBUG_STRING);
else if (mLevel == 1)
@@ -1423,29 +1424,29 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
if (mFileName == null) {
v.addElement(PROP_FILE_NAME + "=");
- }else {
+ } else {
v.addElement(PROP_FILE_NAME + "=" +
- mFileName);
+ mFileName);
}
v.addElement(PROP_BUFFER_SIZE + "=" + mBufferSize);
v.addElement(PROP_FLUSH_INTERVAL + "=" + mFlushInterval / 1000);
- if( (mType != null) && mType.equals( ILogger.PROP_SIGNED_AUDIT ) ) {
- v.addElement( PROP_SIGNED_AUDIT_LOG_SIGNING + "="
- + String.valueOf( mLogSigning ) );
+ if ((mType != null) && mType.equals(ILogger.PROP_SIGNED_AUDIT)) {
+ v.addElement(PROP_SIGNED_AUDIT_LOG_SIGNING + "="
+ + String.valueOf(mLogSigning));
- if( mSAuditCertNickName == null ) {
- v.addElement( PROP_SIGNED_AUDIT_CERT_NICKNAME + "=" );
+ if (mSAuditCertNickName == null) {
+ v.addElement(PROP_SIGNED_AUDIT_CERT_NICKNAME + "=");
} else {
- v.addElement( PROP_SIGNED_AUDIT_CERT_NICKNAME + "="
- + mSAuditCertNickName );
+ v.addElement(PROP_SIGNED_AUDIT_CERT_NICKNAME + "="
+ + mSAuditCertNickName);
}
- if( mSelectedEventsList == null ) {
- v.addElement( PROP_SIGNED_AUDIT_EVENTS + "=" );
+ if (mSelectedEventsList == null) {
+ v.addElement(PROP_SIGNED_AUDIT_EVENTS + "=");
} else {
- v.addElement( PROP_SIGNED_AUDIT_EVENTS + "="
- + mSelectedEventsList );
+ v.addElement(PROP_SIGNED_AUDIT_EVENTS + "="
+ + mSelectedEventsList);
}
}
} catch (Exception e) {
@@ -1454,53 +1455,53 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
}
public String[] getExtendedPluginInfo(Locale locale) {
- if( mType.equals( ILogger.PROP_SIGNED_AUDIT ) ) {
+ if (mType.equals(ILogger.PROP_SIGNED_AUDIT)) {
String[] params = {
- PROP_TYPE + ";choice(transaction,signedAudit,system);The log event type this instance is listening to",
- PROP_ON + ";boolean;Turn on the listener",
- PROP_LEVEL + ";choice(" + ILogger.LL_DEBUG_STRING + "," +
- ILogger.LL_INFO_STRING + "," +
- ILogger.LL_WARN_STRING + "," +
- ILogger.LL_FAILURE_STRING + "," +
- ILogger.LL_MISCONF_STRING + "," +
- ILogger.LL_CATASTRPHE_STRING + "," +
- ILogger.LL_SECURITY_STRING + ");Only log message with level higher than this filter will be written by this listener",
- PROP_FILE_NAME + ";string;The name of the file the log is written to",
- PROP_BUFFER_SIZE + ";integer;The size of the buffer to receive log messages in kilobytes(KB)",
- PROP_FLUSH_INTERVAL + ";integer;The maximum time in seconds before the buffer is flushed to the file",
- IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-logrules-logfile",
- IExtendedPluginInfo.HELP_TEXT +
- ";Write the log messages to a file",
- PROP_SIGNED_AUDIT_LOG_SIGNING +
- ";boolean;Enable audit logs to be signed",
- PROP_SIGNED_AUDIT_CERT_NICKNAME +
- ";string;The nickname of the certificate to be used to sign audit logs",
- PROP_SIGNED_AUDIT_EVENTS +
- ";string;A comma-separated list of strings used to specify particular signed audit log events",
+ PROP_TYPE + ";choice(transaction,signedAudit,system);The log event type this instance is listening to",
+ PROP_ON + ";boolean;Turn on the listener",
+ PROP_LEVEL + ";choice(" + ILogger.LL_DEBUG_STRING + "," +
+ ILogger.LL_INFO_STRING + "," +
+ ILogger.LL_WARN_STRING + "," +
+ ILogger.LL_FAILURE_STRING + "," +
+ ILogger.LL_MISCONF_STRING + "," +
+ ILogger.LL_CATASTRPHE_STRING + "," +
+ ILogger.LL_SECURITY_STRING + ");Only log message with level higher than this filter will be written by this listener",
+ PROP_FILE_NAME + ";string;The name of the file the log is written to",
+ PROP_BUFFER_SIZE + ";integer;The size of the buffer to receive log messages in kilobytes(KB)",
+ PROP_FLUSH_INTERVAL + ";integer;The maximum time in seconds before the buffer is flushed to the file",
+ IExtendedPluginInfo.HELP_TOKEN +
+ ";configuration-logrules-logfile",
+ IExtendedPluginInfo.HELP_TEXT +
+ ";Write the log messages to a file",
+ PROP_SIGNED_AUDIT_LOG_SIGNING +
+ ";boolean;Enable audit logs to be signed",
+ PROP_SIGNED_AUDIT_CERT_NICKNAME +
+ ";string;The nickname of the certificate to be used to sign audit logs",
+ PROP_SIGNED_AUDIT_EVENTS +
+ ";string;A comma-separated list of strings used to specify particular signed audit log events",
};
return params;
} else {
- // mType.equals( ILogger.PROP_AUDIT ) ||
+ // mType.equals( ILogger.PROP_AUDIT ) ||
// mType.equals( ILogger.PROP_SYSTEM )
String[] params = {
- PROP_TYPE + ";choice(transaction,signedAudit,system);The log event type this instance is listening to",
- PROP_ON + ";boolean;Turn on the listener",
- PROP_LEVEL + ";choice(" + ILogger.LL_DEBUG_STRING + "," +
- ILogger.LL_INFO_STRING + "," +
- ILogger.LL_WARN_STRING + "," +
- ILogger.LL_FAILURE_STRING + "," +
- ILogger.LL_MISCONF_STRING + "," +
- ILogger.LL_CATASTRPHE_STRING + "," +
- ILogger.LL_SECURITY_STRING + ");Only log message with level higher than this filter will be written by this listener",
- PROP_FILE_NAME + ";string;The name of the file the log is written to",
- PROP_BUFFER_SIZE + ";integer;The size of the buffer to receive log messages in kilobytes(KB)",
- PROP_FLUSH_INTERVAL + ";integer;The maximum time in seconds before the buffer is flushed to the file",
- IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-logrules-logfile",
- IExtendedPluginInfo.HELP_TEXT +
- ";Write the log messages to a file"
+ PROP_TYPE + ";choice(transaction,signedAudit,system);The log event type this instance is listening to",
+ PROP_ON + ";boolean;Turn on the listener",
+ PROP_LEVEL + ";choice(" + ILogger.LL_DEBUG_STRING + "," +
+ ILogger.LL_INFO_STRING + "," +
+ ILogger.LL_WARN_STRING + "," +
+ ILogger.LL_FAILURE_STRING + "," +
+ ILogger.LL_MISCONF_STRING + "," +
+ ILogger.LL_CATASTRPHE_STRING + "," +
+ ILogger.LL_SECURITY_STRING + ");Only log message with level higher than this filter will be written by this listener",
+ PROP_FILE_NAME + ";string;The name of the file the log is written to",
+ PROP_BUFFER_SIZE + ";integer;The size of the buffer to receive log messages in kilobytes(KB)",
+ PROP_FLUSH_INTERVAL + ";integer;The maximum time in seconds before the buffer is flushed to the file",
+ IExtendedPluginInfo.HELP_TOKEN +
+ ";configuration-logrules-logfile",
+ IExtendedPluginInfo.HELP_TEXT +
+ ";Write the log messages to a file"
};
return params;
@@ -1509,27 +1510,25 @@ public class LogFile implements ILogEventListener, IExtendedPluginInfo {
/**
* Signed Audit Log
- *
- * This method is inherited by all classes that extend this "LogFile"
- * class, and is called to store messages to the signed audit log.
+ *
+ * This method is inherited by all classes that extend this "LogFile" class,
+ * and is called to store messages to the signed audit log.
* <P>
- *
+ *
* @param msg signed audit log message
*/
- protected void audit( String msg )
- {
+ protected void audit(String msg) {
// in this case, do NOT strip preceding/trailing whitespace
// from passed-in String parameters
- if( mSignedAuditLogger == null ) {
+ if (mSignedAuditLogger == null) {
return;
}
- mSignedAuditLogger.log( ILogger.EV_SIGNED_AUDIT,
+ mSignedAuditLogger.log(ILogger.EV_SIGNED_AUDIT,
null,
ILogger.S_SIGNED_AUDIT,
ILogger.LL_SECURITY,
- msg );
+ msg);
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/logging/RollingLogFile.java b/pki/base/common/src/com/netscape/cms/logging/RollingLogFile.java
index d2dab395..e4678bb7 100644
--- a/pki/base/common/src/com/netscape/cms/logging/RollingLogFile.java
+++ b/pki/base/common/src/com/netscape/cms/logging/RollingLogFile.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.logging;
-
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
@@ -41,12 +40,11 @@ import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.logging.SystemEvent;
import com.netscape.cmsutil.util.Utils;
-
/**
* A rotating log file for Certificate log events. This class loosely follows
* the Netscape Common Log API implementing rollover interval, size and file
* naming conventions. It does not yet implement Disk Usage.
- *
+ *
* @version $Revision$, $Date$
*/
public class RollingLogFile extends LogFile {
@@ -105,7 +103,7 @@ public class RollingLogFile extends LogFile {
private Object mExpLock = new Object();
private final static String LOGGING_SIGNED_AUDIT_LOG_DELETE =
- "LOGGING_SIGNED_AUDIT_LOG_DELETE_3";
+ "LOGGING_SIGNED_AUDIT_LOG_DELETE_3";
/**
* Construct a RollingLogFile
@@ -115,7 +113,7 @@ public class RollingLogFile extends LogFile {
/**
* Initialize and open a RollingLogFile using the prop config store
- *
+ *
* @param config The property config store to find values in
*/
public void init(IConfigStore config) throws IOException,
@@ -123,8 +121,8 @@ public class RollingLogFile extends LogFile {
super.init(config);
rl_init(config.getInteger(PROP_MAX_FILE_SIZE, MAX_FILE_SIZE),
- config.getString(PROP_ROLLOVER_INTERVAL, ROLLOVER_INTERVAL),
- config.getString(PROP_EXPIRATION_TIME, EXPIRATION_TIME));
+ config.getString(PROP_ROLLOVER_INTERVAL, ROLLOVER_INTERVAL),
+ config.getString(PROP_EXPIRATION_TIME, EXPIRATION_TIME));
}
/**
@@ -132,7 +130,7 @@ public class RollingLogFile extends LogFile {
* attributes.
*/
protected void rl_init(int maxFileSize, String rolloverInterval,
- String expirationTime) {
+ String expirationTime) {
mMaxFileSize = maxFileSize * 1024;
setRolloverTime(rolloverInterval);
setExpirationTime(expirationTime);
@@ -153,9 +151,9 @@ public class RollingLogFile extends LogFile {
/**
* Set the rollover interval
- *
- * @param rolloverSeconds The amount of time in seconds until the log
- * is rotated. A value of 0 will disable log rollover.
+ *
+ * @param rolloverSeconds The amount of time in seconds until the log is
+ * rotated. A value of 0 will disable log rollover.
**/
public synchronized void setRolloverTime(String rolloverSeconds) {
mRolloverInterval = Long.valueOf(rolloverSeconds).longValue() * 1000;
@@ -171,8 +169,8 @@ public class RollingLogFile extends LogFile {
/**
* Get the rollover interval
- *
- * @return The interval in seconds in which the log is rotated
+ *
+ * @return The interval in seconds in which the log is rotated
**/
public synchronized int getRolloverTime() {
return (int) (mRolloverInterval / 1000);
@@ -180,9 +178,9 @@ public class RollingLogFile extends LogFile {
/**
* Set the file expiration time
- *
- * @param expirationSeconds The amount of time in seconds until log files
- * are deleted
+ *
+ * @param expirationSeconds The amount of time in seconds until log files
+ * are deleted
**/
public void setExpirationTime(String expirationSeconds) {
@@ -205,8 +203,8 @@ public class RollingLogFile extends LogFile {
/**
* Get the expiration time
- *
- * @return The age in seconds in which log files are delete
+ *
+ * @return The age in seconds in which log files are delete
**/
public int getExpirationTime() {
return (int) (mExpirationTime / 1000);
@@ -217,82 +215,82 @@ public class RollingLogFile extends LogFile {
* extension
**/
public synchronized void rotate()
- throws IOException {
+ throws IOException {
- //File backupFile = new File(mFileName + "." + mFileNumber);
+ // File backupFile = new File(mFileName + "." + mFileNumber);
File backupFile = new File(mFileName + "." + mLogFileDateFormat.format(mDate));
// close, backup, and reopen the log file zeroizing its contents
super.close();
try {
- if( Utils.isNT() ) {
+ if (Utils.isNT()) {
// NT is very picky on the path
- Utils.exec( "copy " +
- mFile.getCanonicalPath().replace( '/', '\\' ) +
+ Utils.exec("copy " +
+ mFile.getCanonicalPath().replace('/', '\\') +
" " +
- backupFile.getCanonicalPath().replace( '/',
- '\\' ) );
+ backupFile.getCanonicalPath().replace('/',
+ '\\'));
} else {
// Create a copy of the original file which
// preserves the original file permissions.
- Utils.exec( "cp -p " + mFile.getCanonicalPath() + " " +
- backupFile.getCanonicalPath() );
+ Utils.exec("cp -p " + mFile.getCanonicalPath() + " " +
+ backupFile.getCanonicalPath());
}
// Zeroize the original file if and only if
// the backup copy was successful.
- if( backupFile.exists() ) {
+ if (backupFile.exists()) {
// Make certain that the backup file has
// the correct permissions.
- if( !Utils.isNT() ) {
- Utils.exec( "chmod 00640 " + backupFile.getCanonicalPath() );
+ if (!Utils.isNT()) {
+ Utils.exec("chmod 00640 " + backupFile.getCanonicalPath());
}
try {
// Open and close the original file
// to zeroize its contents.
- PrintWriter pw = new PrintWriter( mFile );
+ PrintWriter pw = new PrintWriter(mFile);
pw.close();
// Make certain that the original file retains
// the correct permissions.
- if( !Utils.isNT() ) {
- Utils.exec( "chmod 00640 " + mFile.getCanonicalPath() );
+ if (!Utils.isNT()) {
+ Utils.exec("chmod 00640 " + mFile.getCanonicalPath());
}
- } catch ( FileNotFoundException e ) {
- CMS.debug( "Unable to zeroize "
- + mFile.toString() );
+ } catch (FileNotFoundException e) {
+ CMS.debug("Unable to zeroize "
+ + mFile.toString());
}
} else {
- CMS.debug( "Unable to backup "
+ CMS.debug("Unable to backup "
+ mFile.toString() + " to "
- + backupFile.toString() );
+ + backupFile.toString());
}
- } catch( Exception e ) {
- CMS.debug( "Unable to backup "
+ } catch (Exception e) {
+ CMS.debug("Unable to backup "
+ mFile.toString() + " to "
- + backupFile.toString() );
+ + backupFile.toString());
}
super.open(); // will reset mBytesWritten
mFileNumber++;
}
/**
- * Remove any log files which have not been modified in the specified
- * time
+ * Remove any log files which have not been modified in the specified time
* <P>
- *
- * NOTE: automatic removal of log files is currently NOT supported!
+ *
+ * NOTE: automatic removal of log files is currently NOT supported!
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_LOG_DELETE used AFTER audit log
* expires (authorization should not allow, but in case authorization gets
* compromised make sure it is written AFTER the log expiration happens)
* </ul>
+ *
* @param expirationSeconds The number of seconds since the expired files
- * have been modified.
+ * have been modified.
* @return the time in milliseconds when the next file expires
**/
public long expire(long expirationSeconds) throws ELogException {
@@ -312,26 +310,26 @@ public class RollingLogFile extends LogFile {
File dir = new File(dirName);
// Get just the base name, minus the .date extension
- //int len = mFile.getName().length() - LogFile.DATE_PATTERN.length() - 1;
- //String baseName = mFile.getName().substring(0, len);
+ // int len = mFile.getName().length() - LogFile.DATE_PATTERN.length() -
+ // 1;
+ // String baseName = mFile.getName().substring(0, len);
String fileName = mFile.getName();
String baseName = null, pathName = null;
int index = fileName.lastIndexOf("/");
- if (index != -1) { // "/" exist in fileName
+ if (index != -1) { // "/" exist in fileName
pathName = fileName.substring(0, index);
baseName = fileName.substring(index + 1);
dirName = dirName.concat("/" + pathName);
- }else { // "/" NOT exist in fileName
+ } else { // "/" NOT exist in fileName
baseName = fileName;
}
fileFilter ff = new fileFilter(baseName + ".");
String[] filelist = dir.list(ff);
- if (filelist == null) { // Crap! Something is wrong.
- throw new
- ELogException(CMS.getUserMessage("CMS_LOG_DIRECTORY_LIST_FAILED",
+ if (filelist == null) { // Crap! Something is wrong.
+ throw new ELogException(CMS.getUserMessage("CMS_LOG_DIRECTORY_LIST_FAILED",
dirName, ff.toString()));
}
@@ -340,16 +338,16 @@ public class RollingLogFile extends LogFile {
for (int i = 0; i < filelist.length; i++) {
if (pathName != null) {
filelist[i] = pathName + "/" + filelist[i];
- }else {
+ } else {
filelist[i] = dirName + "/" + filelist[i];
}
-
+
String fullname = dirName + File.separatorChar + filelist[i];
File file = new File(fullname);
long fileTime = file.lastModified();
// Java documentation on File says lastModified() should not
- // be interpeted. The doc is wrong. See JavaSoft bug #4094538
+ // be interpeted. The doc is wrong. See JavaSoft bug #4094538
if ((currentTime - fileTime) > expirationTime) {
file.delete();
@@ -382,7 +380,7 @@ public class RollingLogFile extends LogFile {
//
// At first glance you may think it's a waste of thread resources to have
// two threads for every log file, but the truth is that these threads are
- // sleeping 99% of the time. NxN thread implementations (Solaris, NT,
+ // sleeping 99% of the time. NxN thread implementations (Solaris, NT,
// IRIX 6.4, Unixware, etc...) will handle these in user space.
//
// You may be able to join these into one thread, and deal with
@@ -392,8 +390,8 @@ public class RollingLogFile extends LogFile {
//
/**
- * Log rotation thread. Sleep for the rollover interval and rotate the
- * log. Changing rollover interval to 0 will cause this thread to exit.
+ * Log rotation thread. Sleep for the rollover interval and rotate the log.
+ * Changing rollover interval to 0 will cause this thread to exit.
*/
final class RolloverThread extends Thread {
@@ -414,7 +412,7 @@ public class RollingLogFile extends LogFile {
} catch (InterruptedException e) {
// This shouldn't happen very often
CMS.getLogger().getLogQueue().log(new
- SystemEvent(CMS.getUserMessage("CMS_LOG_THREAD_INTERRUPT", "rollover")));
+ SystemEvent(CMS.getUserMessage("CMS_LOG_THREAD_INTERRUPT", "rollover")));
}
}
@@ -427,23 +425,22 @@ public class RollingLogFile extends LogFile {
rotate();
} catch (IOException e) {
ConsoleError.send(new
- SystemEvent(CMS.getUserMessage("CMS_LOG_ROTATE_LOG_FAILED", mFile.getName(), e.toString())));
+ SystemEvent(CMS.getUserMessage("CMS_LOG_ROTATE_LOG_FAILED", mFile.getName(), e.toString())));
break;
}
}
// else
- // Don't rotate empty logs
- // flag in log summary file?
+ // Don't rotate empty logs
+ // flag in log summary file?
}
mRolloverThread = null;
}
}
-
/**
- * Log expiration thread. Sleep for the expiration interval and
- * delete any files which are too old.
- * Changing expiration interval to 0 will cause this thread to exit.
+ * Log expiration thread. Sleep for the expiration interval and delete any
+ * files which are too old. Changing expiration interval to 0 will cause
+ * this thread to exit.
*/
final class ExpirationThread extends Thread {
@@ -467,18 +464,18 @@ public class RollingLogFile extends LogFile {
wakeupTime = expire((long) (mExpirationTime / 1000));
} catch (SecurityException e) {
ConsoleError.send(new
- SystemEvent(CMS.getUserMessage("CMS_LOG_EXPIRE_LOG_FAILED", e.toString())));
+ SystemEvent(CMS.getUserMessage("CMS_LOG_EXPIRE_LOG_FAILED", e.toString())));
break;
} catch (ELogException e) {
ConsoleError.send(new
- SystemEvent(CMS.getUserMessage("CMS_LOG_EXPIRE_LOG_FAILED", e.toString())));
+ SystemEvent(CMS.getUserMessage("CMS_LOG_EXPIRE_LOG_FAILED", e.toString())));
break;
}
sleepTime = wakeupTime - System.currentTimeMillis();
- //System.out.println("wakeup " + wakeupTime);
- //System.out.println("current "+System.currentTimeMillis());
- //System.out.println("sleep " + sleepTime);
+ // System.out.println("wakeup " + wakeupTime);
+ // System.out.println("current "+System.currentTimeMillis());
+ // System.out.println("sleep " + sleepTime);
// Sleep for the interval and then check the directory
// Note: mExpirationTime can only change while we're
// sleeping
@@ -488,7 +485,7 @@ public class RollingLogFile extends LogFile {
} catch (InterruptedException e) {
// This shouldn't happen very often
ConsoleError.send(new
- SystemEvent(CMS.getUserMessage("CMS_LOG_THREAD_INTERRUPT", "expiration")));
+ SystemEvent(CMS.getUserMessage("CMS_LOG_THREAD_INTERRUPT", "expiration")));
}
}
}
@@ -499,11 +496,11 @@ public class RollingLogFile extends LogFile {
/**
* Write an event to the log file
- *
- * @param ev The event to be logged.
+ *
+ * @param ev The event to be logged.
**/
public synchronized void log(ILogEvent ev) throws ELogException {
- //xxx, Shall we log first without checking if it exceed the maximum?
+ // xxx, Shall we log first without checking if it exceed the maximum?
super.log(ev); // Will increment mBytesWritten
if ((0 != mMaxFileSize) && (mBytesWritten > mMaxFileSize)) {
@@ -519,9 +516,9 @@ public class RollingLogFile extends LogFile {
/**
* Retrieve log file list.
*/
- public synchronized NameValuePairs retrieveLogList(Hashtable<String, String> req
- ) throws ServletException,
- IOException, EBaseException {
+ public synchronized NameValuePairs retrieveLogList(Hashtable<String, String> req
+ ) throws ServletException,
+ IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
String[] files = null;
@@ -534,7 +531,7 @@ public class RollingLogFile extends LogFile {
/**
* Get the log file list in the log directory
- *
+ *
* @return an array of filenames with related path to cert server root
*/
protected String[] fileList() {
@@ -544,7 +541,7 @@ public class RollingLogFile extends LogFile {
String fileName = mFile.getName();
int index = fileName.lastIndexOf("/");
- if (index != -1) { // "/" exist in fileName
+ if (index != -1) { // "/" exist in fileName
pathName = fileName.substring(0, index);
baseName = fileName.substring(index + 1);
if (dirName == null) {
@@ -552,24 +549,25 @@ public class RollingLogFile extends LogFile {
} else {
dirName = dirName.concat("/" + pathName);
}
- }else { // "/" NOT exist in fileName
+ } else { // "/" NOT exist in fileName
baseName = fileName;
}
-
+
File dir = new File(dirName);
fileFilter ff = new fileFilter(baseName + ".");
- //There are some difference here. both should work
- //error,logs,logs/error jdk115
- //logs/system,., logs/system jdk116
- //System.out.println(mFile.getName()+","+dirName+","+mFile.getPath()); //log/system,.
-
+ // There are some difference here. both should work
+ // error,logs,logs/error jdk115
+ // logs/system,., logs/system jdk116
+ // System.out.println(mFile.getName()+","+dirName+","+mFile.getPath());
+ // //log/system,.
+
String[] filelist = dir.list(ff);
for (int i = 0; i < filelist.length; i++) {
if (pathName != null) {
filelist[i] = pathName + "/" + filelist[i];
- }else {
+ } else {
filelist[i] = dirName + "/" + filelist[i];
}
}
@@ -589,7 +587,7 @@ public class RollingLogFile extends LogFile {
v.addElement(PROP_MAX_FILE_SIZE + "=");
v.addElement(PROP_ROLLOVER_INTERVAL + "=");
- //v.addElement(PROP_EXPIRATION_TIME + "=");
+ // v.addElement(PROP_EXPIRATION_TIME + "=");
return v;
}
@@ -609,7 +607,8 @@ public class RollingLogFile extends LogFile {
else if (mRolloverInterval / 1000 <= 60 * 60 * 24 * 366)
v.addElement(PROP_ROLLOVER_INTERVAL + "=" + "Yearly");
- //v.addElement(PROP_EXPIRATION_TIME + "=" + mExpirationTime / 1000);
+ // v.addElement(PROP_EXPIRATION_TIME + "=" + mExpirationTime /
+ // 1000);
} catch (Exception e) {
}
return v;
@@ -627,10 +626,10 @@ public class RollingLogFile extends LogFile {
info.addElement(PROP_ROLLOVER_INTERVAL + ";choice(Hourly,Daily,Weekly,Monthly,Yearly);The frequency of the log being rotated.");
info.addElement(PROP_EXPIRATION_TIME + ";integer;The amount of time before a backed up log is removed in seconds");
info.addElement(IExtendedPluginInfo.HELP_TOKEN +
- //";configuration-logrules-rollinglogfile");
- ";configuration-adminbasics");
+ // ";configuration-logrules-rollinglogfile");
+ ";configuration-adminbasics");
info.addElement(IExtendedPluginInfo.HELP_TEXT +
- ";Write the log messages to a file which will be rotated automatically.");
+ ";Write the log messages to a file which will be rotated automatically.");
String[] params = new String[info.size()];
info.copyInto(params);
@@ -639,14 +638,13 @@ public class RollingLogFile extends LogFile {
}
}
-
/**
* A file filter to select the file with a given prefix
*/
class fileFilter implements FilenameFilter {
String patternToMatch = null;
- public fileFilter (String pattern) {
+ public fileFilter(String pattern) {
patternToMatch = pattern;
}
diff --git a/pki/base/common/src/com/netscape/cms/notification/MailNotification.java b/pki/base/common/src/com/netscape/cms/notification/MailNotification.java
index af651584..9d3bd4f0 100644
--- a/pki/base/common/src/com/netscape/cms/notification/MailNotification.java
+++ b/pki/base/common/src/com/netscape/cms/notification/MailNotification.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.notification;
-
import java.io.IOException;
import java.io.PrintStream;
import java.util.Vector;
@@ -30,13 +29,11 @@ import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.notification.ENotificationException;
import com.netscape.certsrv.notification.IMailNotification;
-
/**
- * This class handles mail notification via SMTP.
- * This class uses <b>smtp.host</b> in the configuration for smtp
- * host. The port default (25) is used. If no smtp specified, local
- * host is used
- *
+ * This class handles mail notification via SMTP. This class uses
+ * <b>smtp.host</b> in the configuration for smtp host. The port default (25) is
+ * used. If no smtp specified, local host is used
+ *
* @version $Revision$, $Date$
*/
public class MailNotification implements IMailNotification {
@@ -56,10 +53,10 @@ public class MailNotification implements IMailNotification {
if (mHost == null) {
try {
IConfigStore mConfig =
- CMS.getConfigStore();
+ CMS.getConfigStore();
IConfigStore c =
- mConfig.getSubStore(PROP_SMTP_SUBSTORE);
+ mConfig.getSubStore(PROP_SMTP_SUBSTORE);
if (c == null) {
return;
@@ -67,10 +64,10 @@ public class MailNotification implements IMailNotification {
mHost = c.getString(PROP_HOST);
// log it
- // if (mHost !=null) {
- // String msg =" using external SMTP host: "+mHost;
- // CMS.debug("MailNotification: " + msg);
- //}
+ // if (mHost !=null) {
+ // String msg =" using external SMTP host: "+mHost;
+ // CMS.debug("MailNotification: " + msg);
+ // }
} catch (Exception e) {
// don't care
}
@@ -94,7 +91,7 @@ public class MailNotification implements IMailNotification {
if ((mFrom != null) && (!mFrom.equals("")))
sc.from(mFrom);
else {
- throw new ENotificationException (
+ throw new ENotificationException(
CMS.getUserMessage("CMS_NOTIFICATION_NO_SMTP_SENDER"));
}
@@ -103,7 +100,7 @@ public class MailNotification implements IMailNotification {
log(ILogger.LL_INFO, "mail to be sent to " + mTo);
sc.to(mTo);
} else {
- throw new ENotificationException (
+ throw new ENotificationException(
CMS.getUserMessage("CMS_NOTIFICATION_NO_SMTP_RECEIVER"));
}
@@ -129,13 +126,14 @@ public class MailNotification implements IMailNotification {
sc.closeServer();
} catch (IOException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("OPERATION_ERROR", e.toString()));
- throw new ENotificationException (
+ throw new ENotificationException(
CMS.getUserMessage("CMS_NOTIFICATION_SMTP_SEND_FAILED", mTo));
}
}
/**
* sets the "From" field
+ *
* @param from email address of the sender
*/
public void setFrom(String from) {
@@ -144,6 +142,7 @@ public class MailNotification implements IMailNotification {
/**
* sets the "Subject" field
+ *
* @param subject subject of the email
*/
public void setSubject(String subject) {
@@ -152,6 +151,7 @@ public class MailNotification implements IMailNotification {
/**
* sets the "Content-Type" field
+ *
* @param contentType content type of the email
*/
public void setContentType(String contentType) {
@@ -160,6 +160,7 @@ public class MailNotification implements IMailNotification {
/**
* sets the content of the email
+ *
* @param content the message content
*/
public void setContent(String content) {
@@ -168,6 +169,7 @@ public class MailNotification implements IMailNotification {
/**
* sets the recipients' email addresses
+ *
* @param addresses a list of email addresses of the recipients
*/
public void setTo(Vector<String> addresses) {
@@ -177,6 +179,7 @@ public class MailNotification implements IMailNotification {
/**
* sets the recipient's email address
+ *
* @param to address of the recipient email address
*/
public void setTo(String to) {
@@ -187,7 +190,7 @@ public class MailNotification implements IMailNotification {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_OTHER,
- level, "MailNotification: " + msg);
+ level, "MailNotification: " + msg);
}
}
diff --git a/pki/base/common/src/com/netscape/cms/ocsp/DefStore.java b/pki/base/common/src/com/netscape/cms/ocsp/DefStore.java
index 0468e13f..dfe5eb53 100644
--- a/pki/base/common/src/com/netscape/cms/ocsp/DefStore.java
+++ b/pki/base/common/src/com/netscape/cms/ocsp/DefStore.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.ocsp;
-
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.cert.X509CRL;
@@ -75,33 +74,32 @@ import com.netscape.cmsutil.ocsp.SingleResponse;
import com.netscape.cmsutil.ocsp.TBSRequest;
import com.netscape.cmsutil.ocsp.UnknownInfo;
-
/**
- * This is the default OCSP store that stores revocation information
- * as certificate record (CMS internal data structure).
- *
+ * This is the default OCSP store that stores revocation information as
+ * certificate record (CMS internal data structure).
+ *
* @version $Revision$, $Date$
*/
public class DefStore implements IDefStore, IExtendedPluginInfo {
// refreshInSec is useful in the master-clone situation.
- // clone does not know that the CRL has been updated in
+ // clone does not know that the CRL has been updated in
// the master (by default no refresh)
private static final String PROP_USE_CACHE = "useCache";
private static final String PROP_REFRESH_IN_SEC = "refreshInSec";
- private static final int DEF_REFRESH_IN_SEC = 0;
+ private static final int DEF_REFRESH_IN_SEC = 0;
public static final BigInteger BIG_ZERO = new BigInteger("0");
public static final Long MINUS_ONE = Long.valueOf(-1);
- private final static String PROP_BY_NAME =
- "byName";
- private final static String PROP_WAIT_ON_CRL_UPDATE =
- "waitOnCRLUpdate";
+ private final static String PROP_BY_NAME =
+ "byName";
+ private final static String PROP_WAIT_ON_CRL_UPDATE =
+ "waitOnCRLUpdate";
private final static String PROP_NOT_FOUND_GOOD = "notFoundAsGood";
private final static String PROP_INCLUDE_NEXT_UPDATE =
- "includeNextUpdate";
+ "includeNextUpdate";
protected Hashtable<String, Long> mReqCounts = new Hashtable<String, Long>();
protected boolean mNotFoundGood = true;
@@ -123,19 +121,19 @@ public class DefStore implements IDefStore, IExtendedPluginInfo {
public DefStore() {
}
- public String[] getExtendedPluginInfo(Locale locale) {
- Vector<String> v = new Vector<String>();
+ public String[] getExtendedPluginInfo(Locale locale) {
+ Vector<String> v = new Vector<String>();
v.addElement(PROP_NOT_FOUND_GOOD + ";boolean; " + CMS.getUserMessage(locale, "CMS_OCSP_DEFSTORE_PROP_NOT_FOUND_GOOD"));
v.addElement(PROP_BY_NAME + ";boolean; " + CMS.getUserMessage(locale, "CMS_OCSP_DEFSTORE_PROP_BY_NAME"));
v.addElement(PROP_INCLUDE_NEXT_UPDATE + ";boolean; " + CMS.getUserMessage(locale, "CMS_OCSP_DEFSTORE_PROP_INCLUDE_NEXT_UPDATE"));
v.addElement(IExtendedPluginInfo.HELP_TEXT + "; " + CMS.getUserMessage(locale, "CMS_OCSP_DEFSTORE_DESC"));
- v.addElement(IExtendedPluginInfo.HELP_TOKEN + ";configuration-ocspstores-defstore");
+ v.addElement(IExtendedPluginInfo.HELP_TOKEN + ";configuration-ocspstores-defstore");
return com.netscape.cmsutil.util.Utils.getStringArrayFromVector(v);
}
- public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ public void init(ISubsystem owner, IConfigStore config)
+ throws EBaseException {
mOCSPAuthority = (IOCSPAuthority) owner;
mConfig = config;
@@ -170,8 +168,7 @@ public class DefStore implements IDefStore, IExtendedPluginInfo {
initWebGateway();
/**
- DeleteOldCRLsThread t = new DeleteOldCRLsThread(this);
- t.start();
+ * DeleteOldCRLsThread t = new DeleteOldCRLsThread(this); t.start();
**/
// deleteOldCRLs();
}
@@ -180,7 +177,7 @@ public class DefStore implements IDefStore, IExtendedPluginInfo {
* init web gateway - just gets the ee gateway for this CA.
*/
private void initWebGateway()
- throws EBaseException {
+ throws EBaseException {
}
public IRepositoryRecord createRepositoryRecord() {
@@ -222,20 +219,20 @@ public class DefStore implements IDefStore, IExtendedPluginInfo {
}
/**
- * This store will not delete the old CRL until the
- * new one is totally committed.
+ * This store will not delete the old CRL until the new one is totally
+ * committed.
*/
public void deleteOldCRLs() throws EBaseException {
Enumeration<ICRLIssuingPointRecord> recs = searchCRLIssuingPointRecord(
"objectclass=" +
- CMS.getCRLIssuingPointRecordName(),
+ CMS.getCRLIssuingPointRecordName(),
100);
X509CertImpl theCert = null;
ICRLIssuingPointRecord theRec = null;
while (recs.hasMoreElements()) {
- ICRLIssuingPointRecord rec =
- recs.nextElement();
+ ICRLIssuingPointRecord rec =
+ recs.nextElement();
deleteOldCRLsInCA(rec.getId());
}
@@ -246,7 +243,7 @@ public class DefStore implements IDefStore, IExtendedPluginInfo {
try {
ICRLIssuingPointRecord cp = (ICRLIssuingPointRecord)
- readCRLIssuingPoint(caName);
+ readCRLIssuingPoint(caName);
if (cp == null)
return; // nothing to do
@@ -257,34 +254,35 @@ public class DefStore implements IDefStore, IExtendedPluginInfo {
Enumeration<IRepositoryRecord> e = searchRepository(
caName,
"(!" + IRepositoryRecord.ATTR_SERIALNO + "=" +
- thisUpdate + ")");
+ thisUpdate + ")");
while (e != null && e.hasMoreElements()) {
IRepositoryRecord r = e.nextElement();
- Enumeration<ICertRecord> recs =
- searchCertRecord(caName,
- r.getSerialNumber().toString(),
- ICertRecord.ATTR_ID + "=*");
-
- log(ILogger.LL_INFO, "remove CRL 0x" +
- r.getSerialNumber().toString(16) +
- " of " + caName);
- String rep_dn = "ou=" +
- r.getSerialNumber().toString() +
- ",cn=" + transformDN(caName) + "," +
- getBaseDN();
+ Enumeration<ICertRecord> recs =
+ searchCertRecord(caName,
+ r.getSerialNumber().toString(),
+ ICertRecord.ATTR_ID + "=*");
+
+ log(ILogger.LL_INFO, "remove CRL 0x" +
+ r.getSerialNumber().toString(16) +
+ " of " + caName);
+ String rep_dn = "ou=" +
+ r.getSerialNumber().toString() +
+ ",cn=" + transformDN(caName) + "," +
+ getBaseDN();
while (recs != null && recs.hasMoreElements()) {
- ICertRecord rec = recs.nextElement();
- String cert_dn = "cn=" +
- rec.getSerialNumber().toString() + "," + rep_dn;
+ ICertRecord rec = recs.nextElement();
+ String cert_dn = "cn=" +
+ rec.getSerialNumber().toString() + "," + rep_dn;
s.delete(cert_dn);
}
s.delete(rep_dn);
}
} finally {
- if (s != null) s.close();
+ if (s != null)
+ s.close();
}
}
@@ -297,12 +295,12 @@ public class DefStore implements IDefStore, IExtendedPluginInfo {
}
public void startup() throws EBaseException {
- int refresh = mConfig.getInteger(PROP_REFRESH_IN_SEC,
- DEF_REFRESH_IN_SEC);
+ int refresh = mConfig.getInteger(PROP_REFRESH_IN_SEC,
+ DEF_REFRESH_IN_SEC);
if (refresh > 0) {
- DefStoreCRLUpdater updater =
- new DefStoreCRLUpdater(mCacheCRLIssuingPoints, refresh);
- updater.start();
+ DefStoreCRLUpdater updater =
+ new DefStoreCRLUpdater(mCacheCRLIssuingPoints, refresh);
+ updater.start();
}
}
@@ -324,10 +322,10 @@ public class DefStore implements IDefStore, IExtendedPluginInfo {
/**
* Validate an OCSP request.
*/
- public OCSPResponse validate(OCSPRequest request)
- throws EBaseException {
+ public OCSPResponse validate(OCSPRequest request)
+ throws EBaseException {
- IStatsSubsystem statsSub = (IStatsSubsystem)CMS.getSubsystem("stats");
+ IStatsSubsystem statsSub = (IStatsSubsystem) CMS.getSubsystem("stats");
mOCSPAuthority.incNumOCSPRequest(1);
long startTime = CMS.getCurrentDate().getTime();
@@ -336,16 +334,16 @@ public class DefStore implements IDefStore, IExtendedPluginInfo {
TBSRequest tbsReq = request.getTBSRequest();
// (3) look into database to check the
- // certificate's status
+ // certificate's status
Vector<SingleResponse> singleResponses = new Vector<SingleResponse>();
if (statsSub != null) {
- statsSub.startTiming("lookup");
+ statsSub.startTiming("lookup");
}
long lookupStartTime = CMS.getCurrentDate().getTime();
for (int i = 0; i < tbsReq.getRequestCount(); i++) {
com.netscape.cmsutil.ocsp.Request req =
- tbsReq.getRequestAt(i);
+ tbsReq.getRequestAt(i);
CertID cid = req.getCertID();
SingleResponse sr = processRequest(cid);
@@ -353,17 +351,17 @@ public class DefStore implements IDefStore, IExtendedPluginInfo {
}
long lookupEndTime = CMS.getCurrentDate().getTime();
if (statsSub != null) {
- statsSub.endTiming("lookup");
+ statsSub.endTiming("lookup");
}
mOCSPAuthority.incLookupTime(lookupEndTime - lookupStartTime);
- if (singleResponses.size() <= 0) {
+ if (singleResponses.size() <= 0) {
CMS.debug("DefStore: No Request Found");
log(ILogger.LL_FAILURE, CMS.getLogMessage("OCSP_REQUEST_FAILURE", "No Request Found"));
return null;
}
if (statsSub != null) {
- statsSub.startTiming("build_response");
+ statsSub.startTiming("build_response");
}
SingleResponse res[] = new SingleResponse[singleResponses.size()];
@@ -391,24 +389,24 @@ public class DefStore implements IDefStore, IExtendedPluginInfo {
ResponseData rd = new ResponseData(rid,
new GeneralizedTime(CMS.getCurrentDate()), res, nonce);
if (statsSub != null) {
- statsSub.endTiming("build_response");
+ statsSub.endTiming("build_response");
}
if (statsSub != null) {
- statsSub.startTiming("signing");
+ statsSub.startTiming("signing");
}
long signStartTime = CMS.getCurrentDate().getTime();
BasicOCSPResponse basicRes = mOCSPAuthority.sign(rd);
long signEndTime = CMS.getCurrentDate().getTime();
if (statsSub != null) {
- statsSub.endTiming("signing");
+ statsSub.endTiming("signing");
}
mOCSPAuthority.incSignTime(signEndTime - signStartTime);
OCSPResponse response = new OCSPResponse(
OCSPResponseStatus.SUCCESSFUL,
new ResponseBytes(ResponseBytes.OCSP_BASIC,
- new OCTET_STRING(ASN1Util.encode(basicRes))));
+ new OCTET_STRING(ASN1Util.encode(basicRes))));
log(ILogger.LL_INFO, "done OCSP request");
long endTime = CMS.getCurrentDate().getTime();
@@ -435,17 +433,17 @@ public class DefStore implements IDefStore, IExtendedPluginInfo {
ICRLIssuingPointRecord theRec = null;
byte keyhsh[] = cid.getIssuerKeyHash().toByteArray();
CRLIPContainer matched = (CRLIPContainer)
- mCacheCRLIssuingPoints.get(new String(keyhsh));
+ mCacheCRLIssuingPoints.get(new String(keyhsh));
if (matched == null) {
Enumeration<ICRLIssuingPointRecord> recs = searchCRLIssuingPointRecord(
"objectclass=" +
- CMS.getCRLIssuingPointRecordName(),
+ CMS.getCRLIssuingPointRecordName(),
100);
while (recs.hasMoreElements()) {
ICRLIssuingPointRecord rec = (ICRLIssuingPointRecord)
- recs.nextElement();
+ recs.nextElement();
byte certdata[] = rec.getCACert();
X509CertImpl cert = null;
@@ -468,15 +466,15 @@ public class DefStore implements IDefStore, IExtendedPluginInfo {
byte crldata[] = rec.getCRL();
if (rec.getCRLCache() == null) {
- CMS.debug("DefStore: start building x509 crl impl");
- try {
- theCRL = new X509CRLImpl(crldata);
- } catch (Exception e) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("OCSP_DECODE_CRL", e.toString()));
- }
- CMS.debug("DefStore: done building x509 crl impl");
+ CMS.debug("DefStore: start building x509 crl impl");
+ try {
+ theCRL = new X509CRLImpl(crldata);
+ } catch (Exception e) {
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("OCSP_DECODE_CRL", e.toString()));
+ }
+ CMS.debug("DefStore: done building x509 crl impl");
} else {
- CMS.debug("DefStore: using crl cache");
+ CMS.debug("DefStore: using crl cache");
}
mCacheCRLIssuingPoints.put(new String(digest), new CRLIPContainer(theRec, theCert, theCRL));
break;
@@ -524,25 +522,25 @@ public class DefStore implements IDefStore, IExtendedPluginInfo {
CMS.debug("DefStore: evaluating crl cache");
Hashtable<BigInteger, RevokedCertificate> cache = theRec.getCRLCacheNoClone();
if (cache != null) {
- RevokedCertificate rc = (RevokedCertificate)
- cache.get(new BigInteger(serialNo.toString()));
- if (rc == null) {
- if (isNotFoundGood()) {
- certStatus = new GoodInfo();
- } else {
- certStatus = new UnknownInfo();
+ RevokedCertificate rc = (RevokedCertificate)
+ cache.get(new BigInteger(serialNo.toString()));
+ if (rc == null) {
+ if (isNotFoundGood()) {
+ certStatus = new GoodInfo();
+ } else {
+ certStatus = new UnknownInfo();
}
- } else {
-
+ } else {
+
certStatus = new RevokedInfo(
- new GeneralizedTime(
- rc.getRevocationDate()));
- }
+ new GeneralizedTime(
+ rc.getRevocationDate()));
+ }
}
}
-
+
} else {
- CMS.debug("DefStore: evaluating x509 crl impl");
+ CMS.debug("DefStore: evaluating x509 crl impl");
X509CRLEntry crlentry = theCRL.getRevokedCertificate(new BigInteger(serialNo.toString()));
if (crlentry == null) {
@@ -555,7 +553,7 @@ public class DefStore implements IDefStore, IExtendedPluginInfo {
} else {
certStatus = new RevokedInfo(new GeneralizedTime(
crlentry.getRevocationDate()));
-
+
}
}
return new SingleResponse(cid, certStatus, thisUpdate,
@@ -580,17 +578,17 @@ public class DefStore implements IDefStore, IExtendedPluginInfo {
return mDBService.getBaseDN();
}
- public Enumeration<ICRLIssuingPointRecord > searchAllCRLIssuingPointRecord(int maxSize)
- throws EBaseException {
+ public Enumeration<ICRLIssuingPointRecord> searchAllCRLIssuingPointRecord(int maxSize)
+ throws EBaseException {
return searchCRLIssuingPointRecord(
"objectclass=" +
- CMS.getCRLIssuingPointRecordName(),
+ CMS.getCRLIssuingPointRecordName(),
maxSize);
}
public Enumeration<ICRLIssuingPointRecord> searchCRLIssuingPointRecord(String filter,
- int maxSize)
- throws EBaseException {
+ int maxSize)
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
Enumeration<ICRLIssuingPointRecord> e = null;
@@ -604,20 +602,21 @@ public class DefStore implements IDefStore, IExtendedPluginInfo {
}
public synchronized void modifyCRLIssuingPointRecord(String name,
- ModificationSet mods) throws EBaseException {
+ ModificationSet mods) throws EBaseException {
IDBSSession s = mDBService.createSession();
try {
String dn = "cn=" +
- transformDN(name) + "," + getBaseDN();
+ transformDN(name) + "," + getBaseDN();
s.modify(dn, mods);
} catch (EBaseException e) {
- CMS.debug("modifyCRLIssuingPointRecord: error=" + e);
- CMS.debug(e);
- throw e;
+ CMS.debug("modifyCRLIssuingPointRecord: error=" + e);
+ CMS.debug(e);
+ throw e;
} finally {
- if (s != null) s.close();
+ if (s != null)
+ s.close();
}
}
@@ -625,42 +624,45 @@ public class DefStore implements IDefStore, IExtendedPluginInfo {
* Returns an issuing point.
*/
public ICRLIssuingPointRecord readCRLIssuingPoint(String name)
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
ICRLIssuingPointRecord rec = null;
try {
String dn = "cn=" +
- transformDN(name) + "," + getBaseDN();
+ transformDN(name) + "," + getBaseDN();
if (s != null) {
rec = (ICRLIssuingPointRecord) s.read(dn);
}
} finally {
- if (s != null) s.close();
+ if (s != null)
+ s.close();
}
return rec;
}
public ICRLIssuingPointRecord createCRLIssuingPointRecord(
- String name, BigInteger crlNumber,
- Long crlSize, Date thisUpdate, Date nextUpdate) {
+ String name, BigInteger crlNumber,
+ Long crlSize, Date thisUpdate, Date nextUpdate) {
return CMS.createCRLIssuingPointRecord(
name, crlNumber, crlSize, thisUpdate, nextUpdate);
}
- public void deleteCRLIssuingPointRecord(String id)
- throws EBaseException {
+ public void deleteCRLIssuingPointRecord(String id)
+ throws EBaseException {
IDBSSession s = null;
try {
s = mDBService.createSession();
- String name = "cn=" + transformDN(id) + "," + getBaseDN();
+ String name = "cn=" + transformDN(id) + "," + getBaseDN();
CMS.debug("DefStore::deleteCRLIssuingPointRecord: Attempting to delete: " + name);
- if (s != null) s.delete(name);
+ if (s != null)
+ s.delete(name);
} finally {
- if (s != null) s.close();
+ if (s != null)
+ s.close();
}
}
@@ -668,12 +670,12 @@ public class DefStore implements IDefStore, IExtendedPluginInfo {
* Creates a new issuing point in OCSP.
*/
public void addCRLIssuingPoint(String name, ICRLIssuingPointRecord rec)
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
try {
String dn = "cn=" +
- transformDN(name) + "," + getBaseDN();
+ transformDN(name) + "," + getBaseDN();
s.add(dn, (ICRLIssuingPointRecord) rec);
} finally {
@@ -683,7 +685,7 @@ public class DefStore implements IDefStore, IExtendedPluginInfo {
}
public Enumeration<IRepositoryRecord> searchRepository(String name, String filter)
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
Enumeration<IRepositoryRecord> e = null;
@@ -701,13 +703,13 @@ public class DefStore implements IDefStore, IExtendedPluginInfo {
* Creates a new issuing point in OCSP.
*/
public void addRepository(String name, String thisUpdate,
- IRepositoryRecord rec)
- throws EBaseException {
+ IRepositoryRecord rec)
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
try {
String dn = "ou=" + thisUpdate + ",cn=" +
- transformDN(name) + "," + getBaseDN();
+ transformDN(name) + "," + getBaseDN();
s.add(dn, rec);
} finally {
@@ -717,22 +719,24 @@ public class DefStore implements IDefStore, IExtendedPluginInfo {
}
public void modifyCertRecord(String name, String thisUpdate,
- String sno,
- ModificationSet mods) throws EBaseException {
+ String sno,
+ ModificationSet mods) throws EBaseException {
IDBSSession s = mDBService.createSession();
try {
String dn = "cn=" + sno + ",ou=" + thisUpdate +
- ",cn=" + transformDN(name) + "," + getBaseDN();
+ ",cn=" + transformDN(name) + "," + getBaseDN();
- if (s != null) s.modify(dn, mods);
+ if (s != null)
+ s.modify(dn, mods);
} finally {
- if (s != null) s.close();
+ if (s != null)
+ s.close();
}
}
public Enumeration<ICertRecord> searchCertRecord(String name, String thisUpdate,
- String filter) throws EBaseException {
+ String filter) throws EBaseException {
IDBSSession s = mDBService.createSession();
Enumeration<ICertRecord> e = null;
@@ -748,20 +752,21 @@ public class DefStore implements IDefStore, IExtendedPluginInfo {
}
public ICertRecord readCertRecord(String name, String thisUpdate,
- String sno)
- throws EBaseException {
+ String sno)
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
ICertRecord rec = null;
try {
String dn = "cn=" + sno + ",ou=" + thisUpdate +
- ",cn=" + transformDN(name) + "," + getBaseDN();
+ ",cn=" + transformDN(name) + "," + getBaseDN();
if (s != null) {
rec = (ICertRecord) s.read(dn);
}
} finally {
- if (s != null) s.close();
+ if (s != null)
+ s.close();
}
return rec;
}
@@ -770,13 +775,13 @@ public class DefStore implements IDefStore, IExtendedPluginInfo {
* Creates a new issuing point in OCSP.
*/
public void addCertRecord(String name, String thisUpdate,
- String sno, ICertRecord rec)
- throws EBaseException {
+ String sno, ICertRecord rec)
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
try {
String dn = "cn=" + sno + ",ou=" + thisUpdate +
- ",cn=" + transformDN(name) + "," + getBaseDN();
+ ",cn=" + transformDN(name) + "," + getBaseDN();
s.add(dn, rec);
} finally {
@@ -785,26 +790,26 @@ public class DefStore implements IDefStore, IExtendedPluginInfo {
}
}
- public NameValuePairs getConfigParameters() {
+ public NameValuePairs getConfigParameters() {
try {
- NameValuePairs params = new NameValuePairs();
+ NameValuePairs params = new NameValuePairs();
params.add(Constants.PR_OCSPSTORE_IMPL_NAME,
- mConfig.getString("class"));
- params.add(PROP_NOT_FOUND_GOOD,
- mConfig.getString(PROP_NOT_FOUND_GOOD, "true"));
- params.add(PROP_BY_NAME,
- mConfig.getString(PROP_BY_NAME, "true"));
- params.add(PROP_INCLUDE_NEXT_UPDATE,
- mConfig.getString(PROP_INCLUDE_NEXT_UPDATE, "false"));
- return params;
+ mConfig.getString("class"));
+ params.add(PROP_NOT_FOUND_GOOD,
+ mConfig.getString(PROP_NOT_FOUND_GOOD, "true"));
+ params.add(PROP_BY_NAME,
+ mConfig.getString(PROP_BY_NAME, "true"));
+ params.add(PROP_INCLUDE_NEXT_UPDATE,
+ mConfig.getString(PROP_INCLUDE_NEXT_UPDATE, "false"));
+ return params;
} catch (Exception e) {
return null;
}
}
- public void setConfigParameters(NameValuePairs pairs)
- throws EBaseException {
+ public void setConfigParameters(NameValuePairs pairs)
+ throws EBaseException {
Enumeration<String> k = pairs.getNames();
while (k.hasMoreElements()) {
@@ -821,8 +826,8 @@ public class DefStore implements IDefStore, IExtendedPluginInfo {
CMS.debug("DefStore: Ready to update Issuer");
try {
- if (!((X509CRLImpl)crl).areEntriesIncluded())
- crl = new X509CRLImpl(((X509CRLImpl)crl).getEncoded());
+ if (!((X509CRLImpl) crl).areEntriesIncluded())
+ crl = new X509CRLImpl(((X509CRLImpl) crl).getEncoded());
} catch (Exception e) {
CMS.debug(e);
}
@@ -832,51 +837,51 @@ public class DefStore implements IDefStore, IExtendedPluginInfo {
if (crl.getThisUpdate() != null)
mods.add(ICRLIssuingPointRecord.ATTR_THIS_UPDATE,
- Modification.MOD_REPLACE, crl.getThisUpdate());
+ Modification.MOD_REPLACE, crl.getThisUpdate());
if (crl.getNextUpdate() != null)
mods.add(ICRLIssuingPointRecord.ATTR_NEXT_UPDATE,
- Modification.MOD_REPLACE, crl.getNextUpdate());
+ Modification.MOD_REPLACE, crl.getNextUpdate());
if (mUseCache) {
- if (((X509CRLImpl)crl).getListOfRevokedCertificates() != null) {
- mods.add(ICRLIssuingPointRecord.ATTR_CRL_CACHE,
- Modification.MOD_REPLACE,
- ((X509CRLImpl)crl).getListOfRevokedCertificates());
- }
+ if (((X509CRLImpl) crl).getListOfRevokedCertificates() != null) {
+ mods.add(ICRLIssuingPointRecord.ATTR_CRL_CACHE,
+ Modification.MOD_REPLACE,
+ ((X509CRLImpl) crl).getListOfRevokedCertificates());
+ }
}
if (((X509CRLImpl) crl).getNumberOfRevokedCertificates() < 0) {
mods.add(ICRLIssuingPointRecord.ATTR_CRL_SIZE,
- Modification.MOD_REPLACE, Long.valueOf(0));
+ Modification.MOD_REPLACE, Long.valueOf(0));
} else {
mods.add(ICRLIssuingPointRecord.ATTR_CRL_SIZE,
- Modification.MOD_REPLACE, Long.valueOf(((X509CRLImpl) crl).getNumberOfRevokedCertificates()));
+ Modification.MOD_REPLACE, Long.valueOf(((X509CRLImpl) crl).getNumberOfRevokedCertificates()));
}
- BigInteger crlNumber = ((X509CRLImpl)crl).getCRLNumber();
+ BigInteger crlNumber = ((X509CRLImpl) crl).getCRLNumber();
if (crlNumber == null) {
mods.add(ICRLIssuingPointRecord.ATTR_CRL_NUMBER,
- Modification.MOD_REPLACE, new BigInteger("-1"));
+ Modification.MOD_REPLACE, new BigInteger("-1"));
} else {
mods.add(ICRLIssuingPointRecord.ATTR_CRL_NUMBER,
- Modification.MOD_REPLACE, crlNumber);
+ Modification.MOD_REPLACE, crlNumber);
}
try {
mods.add(ICRLIssuingPointRecord.ATTR_CRL,
- Modification.MOD_REPLACE, crl.getEncoded());
+ Modification.MOD_REPLACE, crl.getEncoded());
} catch (Exception e) {
// ignore
}
- CMS.debug("DefStore: ready to CRL update " +
- crl.getIssuerDN().getName());
+ CMS.debug("DefStore: ready to CRL update " +
+ crl.getIssuerDN().getName());
modifyCRLIssuingPointRecord(
- crl.getIssuerDN().getName(), mods);
- CMS.debug("DefStore: done CRL update " +
- crl.getIssuerDN().getName());
+ crl.getIssuerDN().getName(), mods);
+ CMS.debug("DefStore: done CRL update " +
+ crl.getIssuerDN().getName());
// update cache
mCacheCRLIssuingPoints.clear();
- log(ILogger.LL_INFO, "AddCRLServlet: Finish Committing CRL." +
- " thisUpdate=" + crl.getThisUpdate() +
- " nextUpdate=" + crl.getNextUpdate());
+ log(ILogger.LL_INFO, "AddCRLServlet: Finish Committing CRL." +
+ " thisUpdate=" + crl.getThisUpdate() +
+ " nextUpdate=" + crl.getNextUpdate());
} finally {
mStateCount--;
@@ -889,7 +894,6 @@ public class DefStore implements IDefStore, IExtendedPluginInfo {
}
-
class DeleteOldCRLsThread extends Thread {
private DefStore mDefStore = null;
@@ -905,7 +909,6 @@ class DeleteOldCRLsThread extends Thread {
}
}
-
class CRLIPContainer {
private ICRLIssuingPointRecord mRec = null;
private X509CertImpl mCert = null;
diff --git a/pki/base/common/src/com/netscape/cms/ocsp/LDAPStore.java b/pki/base/common/src/com/netscape/cms/ocsp/LDAPStore.java
index 5e4e6566..2f18d6ab 100644
--- a/pki/base/common/src/com/netscape/cms/ocsp/LDAPStore.java
+++ b/pki/base/common/src/com/netscape/cms/ocsp/LDAPStore.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.ocsp;
-
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.cert.X509CRL;
@@ -71,11 +70,10 @@ import com.netscape.cmsutil.ocsp.SingleResponse;
import com.netscape.cmsutil.ocsp.TBSRequest;
import com.netscape.cmsutil.ocsp.UnknownInfo;
-
/**
- * This is the LDAP OCSP store. It reads CA certificate and
- * revocation list attributes from the CA entry.
- *
+ * This is the LDAP OCSP store. It reads CA certificate and revocation list
+ * attributes from the CA entry.
+ *
* @version $Revision$, $Date$
*/
public class LDAPStore implements IDefStore, IExtendedPluginInfo {
@@ -93,8 +91,8 @@ public class LDAPStore implements IDefStore, IExtendedPluginInfo {
private static final String PROP_PORT = "port";
private final static String PROP_NOT_FOUND_GOOD = "notFoundAsGood";
- private final static String PROP_INCLUDE_NEXT_UPDATE =
- "includeNextUpdate";
+ private final static String PROP_INCLUDE_NEXT_UPDATE =
+ "includeNextUpdate";
private IOCSPAuthority mOCSPAuthority = null;
private IConfigStore mConfig = null;
@@ -111,8 +109,8 @@ public class LDAPStore implements IDefStore, IExtendedPluginInfo {
public LDAPStore() {
}
- public String[] getExtendedPluginInfo(Locale locale) {
- Vector v = new Vector();
+ public String[] getExtendedPluginInfo(Locale locale) {
+ Vector v = new Vector();
v.addElement(PROP_NOT_FOUND_GOOD + ";boolean; " + CMS.getUserMessage(locale, "CMS_OCSP_LDAPSTORE_PROP_NOT_FOUND_GOOD"));
v.addElement(PROP_INCLUDE_NEXT_UPDATE + ";boolean; " + CMS.getUserMessage(locale, "CMS_OCSP_LDAPSTORE_PROP_INCLUDE_NEXT_UPDATE"));
@@ -121,33 +119,33 @@ public class LDAPStore implements IDefStore, IExtendedPluginInfo {
v.addElement(PROP_CRL_ATTR + ";string; " + CMS.getUserMessage(locale, "CMS_OCSP_LDAPSTORE_PROP_CRL_ATTR"));
v.addElement(PROP_CA_CERT_ATTR + ";string; " + CMS.getUserMessage(locale, "CMS_OCSP_LDAPSTORE_PROP_CA_CERT_ATTR"));
v.addElement(IExtendedPluginInfo.HELP_TEXT + "; " + CMS.getUserMessage(locale, "CMS_OCSP_LDAPSTORE_DESC"));
- v.addElement(IExtendedPluginInfo.HELP_TOKEN + ";configuration-ocspstores-ldapstore");
- return com.netscape.cmsutil.util.Utils.getStringArrayFromVector(v);
+ v.addElement(IExtendedPluginInfo.HELP_TOKEN + ";configuration-ocspstores-ldapstore");
+ return com.netscape.cmsutil.util.Utils.getStringArrayFromVector(v);
}
/**
* Fetch CA certificate and CRL from LDAP server.
*/
- public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ public void init(ISubsystem owner, IConfigStore config)
+ throws EBaseException {
mOCSPAuthority = (IOCSPAuthority) owner;
mConfig = config;
mCRLAttr = mConfig.getString(PROP_CRL_ATTR, DEF_CRL_ATTR);
- mCACertAttr = mConfig.getString(PROP_CA_CERT_ATTR,
+ mCACertAttr = mConfig.getString(PROP_CA_CERT_ATTR,
DEF_CA_CERT_ATTR);
mByName = mConfig.getBoolean(PROP_BY_NAME, true);
-
+
}
/**
* Locates the CA certificate.
*/
- public X509CertImpl locateCACert(LDAPConnection conn, String baseDN)
- throws EBaseException {
+ public X509CertImpl locateCACert(LDAPConnection conn, String baseDN)
+ throws EBaseException {
try {
- LDAPSearchResults results = conn.search(baseDN,
- LDAPv2.SCOPE_SUB, mCACertAttr + "=*",
+ LDAPSearchResults results = conn.search(baseDN,
+ LDAPv2.SCOPE_SUB, mCACertAttr + "=*",
null, false);
if (!results.hasMoreElements()) {
@@ -166,8 +164,8 @@ public class LDAPStore implements IDefStore, IExtendedPluginInfo {
return caCert;
} catch (Exception e) {
CMS.debug("LDAPStore: locateCACert " + e.toString());
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("OCSP_LOCATE_CA", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("OCSP_LOCATE_CA", e.toString()));
}
return null;
}
@@ -175,11 +173,11 @@ public class LDAPStore implements IDefStore, IExtendedPluginInfo {
/**
* Locates the CRL.
*/
- public X509CRLImpl locateCRL(LDAPConnection conn, String baseDN)
- throws EBaseException {
+ public X509CRLImpl locateCRL(LDAPConnection conn, String baseDN)
+ throws EBaseException {
try {
- LDAPSearchResults results = conn.search(baseDN,
- LDAPv2.SCOPE_SUB, mCRLAttr + "=*",
+ LDAPSearchResults results = conn.search(baseDN,
+ LDAPv2.SCOPE_SUB, mCRLAttr + "=*",
null, false);
if (!results.hasMoreElements()) {
@@ -198,21 +196,20 @@ public class LDAPStore implements IDefStore, IExtendedPluginInfo {
return crl;
} catch (Exception e) {
CMS.debug("LDAPStore: locateCRL " + e.toString());
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("OCSP_LOCATE_CRL", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("OCSP_LOCATE_CRL", e.toString()));
}
return null;
}
- public void updateCRLHash(X509CertImpl caCert, X509CRLImpl crl)
- throws EBaseException {
+ public void updateCRLHash(X509CertImpl caCert, X509CRLImpl crl)
+ throws EBaseException {
X509CRLImpl oldCRL = (X509CRLImpl) mCRLs.get(caCert);
if (oldCRL != null) {
- if (oldCRL.getThisUpdate().getTime() >=
- crl.getThisUpdate().getTime()) {
- log(ILogger.LL_INFO,
- "LDAPStore: no update, received CRL is older than current CRL");
+ if (oldCRL.getThisUpdate().getTime() >= crl.getThisUpdate().getTime()) {
+ log(ILogger.LL_INFO,
+ "LDAPStore: no update, received CRL is older than current CRL");
return; // no update
}
}
@@ -240,8 +237,8 @@ public class LDAPStore implements IDefStore, IExtendedPluginInfo {
String baseDN = mConfig.getString(PROP_BASE_DN + Integer.toString(i), null);
CRLUpdater updater = new CRLUpdater(
this, c, baseDN,
- mConfig.getInteger(PROP_REFRESH_IN_SEC + Integer.toString(i),
- DEF_REFRESH_IN_SEC));
+ mConfig.getInteger(PROP_REFRESH_IN_SEC + Integer.toString(i),
+ DEF_REFRESH_IN_SEC));
updater.start();
}
@@ -265,10 +262,10 @@ public class LDAPStore implements IDefStore, IExtendedPluginInfo {
/**
* Validate an OCSP request.
*/
- public OCSPResponse validate(OCSPRequest request)
- throws EBaseException {
+ public OCSPResponse validate(OCSPRequest request)
+ throws EBaseException {
- IStatsSubsystem statsSub = (IStatsSubsystem)CMS.getSubsystem("stats");
+ IStatsSubsystem statsSub = (IStatsSubsystem) CMS.getSubsystem("stats");
mOCSPAuthority.incNumOCSPRequest(1);
long startTime = CMS.getCurrentDate().getTime();
@@ -279,13 +276,13 @@ public class LDAPStore implements IDefStore, IExtendedPluginInfo {
Vector singleResponses = new Vector();
if (statsSub != null) {
- statsSub.startTiming("lookup");
+ statsSub.startTiming("lookup");
}
long lookupStartTime = CMS.getCurrentDate().getTime();
for (int i = 0; i < tbsReq.getRequestCount(); i++) {
- com.netscape.cmsutil.ocsp.Request req =
- tbsReq.getRequestAt(i);
+ com.netscape.cmsutil.ocsp.Request req =
+ tbsReq.getRequestAt(i);
CertID cid = req.getCertID();
SingleResponse sr = processRequest(cid);
@@ -293,12 +290,12 @@ public class LDAPStore implements IDefStore, IExtendedPluginInfo {
}
long lookupEndTime = CMS.getCurrentDate().getTime();
if (statsSub != null) {
- statsSub.endTiming("lookup");
+ statsSub.endTiming("lookup");
}
mOCSPAuthority.incLookupTime(lookupEndTime - lookupStartTime);
if (statsSub != null) {
- statsSub.startTiming("build_response");
+ statsSub.startTiming("build_response");
}
SingleResponse res[] = new SingleResponse[singleResponses.size()];
@@ -323,14 +320,14 @@ public class LDAPStore implements IDefStore, IExtendedPluginInfo {
}
}
- ResponseData rd = new ResponseData(rid,
+ ResponseData rd = new ResponseData(rid,
new GeneralizedTime(CMS.getCurrentDate()), res, nonce);
if (statsSub != null) {
- statsSub.endTiming("build_response");
+ statsSub.endTiming("build_response");
}
if (statsSub != null) {
- statsSub.startTiming("signing");
+ statsSub.startTiming("signing");
}
long signStartTime = CMS.getCurrentDate().getTime();
@@ -338,13 +335,13 @@ public class LDAPStore implements IDefStore, IExtendedPluginInfo {
long signEndTime = CMS.getCurrentDate().getTime();
mOCSPAuthority.incSignTime(signEndTime - signStartTime);
if (statsSub != null) {
- statsSub.endTiming("signing");
+ statsSub.endTiming("signing");
}
OCSPResponse response = new OCSPResponse(
- OCSPResponseStatus.SUCCESSFUL,
- new ResponseBytes(ResponseBytes.OCSP_BASIC,
- new OCTET_STRING(ASN1Util.encode(basicRes))));
+ OCSPResponseStatus.SUCCESSFUL,
+ new ResponseBytes(ResponseBytes.OCSP_BASIC,
+ new OCTET_STRING(ASN1Util.encode(basicRes))));
log(ILogger.LL_INFO, "done OCSP request");
long endTime = CMS.getCurrentDate().getTime();
@@ -375,8 +372,8 @@ public class LDAPStore implements IDefStore, IExtendedPluginInfo {
}
public void addRepository(String name, String thisUpdate,
- IRepositoryRecord rec)
- throws EBaseException {
+ IRepositoryRecord rec)
+ throws EBaseException {
throw new EBaseException("NOT SUPPORTED");
}
@@ -389,12 +386,12 @@ public class LDAPStore implements IDefStore, IExtendedPluginInfo {
}
public ICRLIssuingPointRecord readCRLIssuingPoint(String name)
- throws EBaseException {
+ throws EBaseException {
throw new EBaseException("NOT SUPPORTED");
}
public Enumeration searchAllCRLIssuingPointRecord(int maxSize)
- throws EBaseException {
+ throws EBaseException {
Vector recs = new Vector();
Enumeration keys = mCRLs.keys();
@@ -408,25 +405,25 @@ public class LDAPStore implements IDefStore, IExtendedPluginInfo {
}
public Enumeration searchCRLIssuingPointRecord(String filter,
- int maxSize)
- throws EBaseException {
+ int maxSize)
+ throws EBaseException {
return null;
}
public ICRLIssuingPointRecord createCRLIssuingPointRecord(
- String name, BigInteger crlNumber,
- Long crlSize, Date thisUpdate, Date nextUpdate) {
+ String name, BigInteger crlNumber,
+ Long crlSize, Date thisUpdate, Date nextUpdate) {
return null;
}
public void addCRLIssuingPoint(String name, ICRLIssuingPointRecord rec)
- throws EBaseException {
+ throws EBaseException {
throw new EBaseException("NOT SUPPORTED");
}
public void deleteCRLIssuingPointRecord(String id)
- throws EBaseException {
- throw new EBaseException("NOT SUPPORTED");
+ throws EBaseException {
+ throw new EBaseException("NOT SUPPORTED");
}
public boolean isNotFoundGood() {
@@ -439,7 +436,7 @@ public class LDAPStore implements IDefStore, IExtendedPluginInfo {
public boolean includeNextUpdate() throws EBaseException {
return mConfig.getBoolean(PROP_INCLUDE_NEXT_UPDATE, false);
- }
+ }
public boolean isNotFoundGood1() throws EBaseException {
return mConfig.getBoolean(PROP_NOT_FOUND_GOOD, true);
@@ -470,7 +467,7 @@ public class LDAPStore implements IDefStore, IExtendedPluginInfo {
}
X509Key key = (X509Key) caCert.getPublicKey();
- if( key == null ) {
+ if (key == null) {
System.out.println("LDAPStore::processRequest - key is null!");
return null;
}
@@ -508,55 +505,55 @@ public class LDAPStore implements IDefStore, IExtendedPluginInfo {
cid.getSerialNumber());
if (entry == null) {
- if (isNotFoundGood1()) {
- certStatus = new GoodInfo();
- } else {
- certStatus = new UnknownInfo();
+ if (isNotFoundGood1()) {
+ certStatus = new GoodInfo();
+ } else {
+ certStatus = new UnknownInfo();
}
} else {
certStatus = new RevokedInfo(new GeneralizedTime(
entry.getRevocationDate()));
}
-
+
return new SingleResponse(cid, certStatus, thisUpdate, nextUpdate);
}
/**
* Provides configuration parameters.
*/
- public NameValuePairs getConfigParameters() {
+ public NameValuePairs getConfigParameters() {
try {
- NameValuePairs params = new NameValuePairs();
+ NameValuePairs params = new NameValuePairs();
- params.add(Constants.PR_OCSPSTORE_IMPL_NAME,
- mConfig.getString("class"));
+ params.add(Constants.PR_OCSPSTORE_IMPL_NAME,
+ mConfig.getString("class"));
int num = mConfig.getInteger(PROP_NUM_CONNS, 0);
params.add(PROP_NUM_CONNS, Integer.toString(num));
for (int i = 0; i < num; i++) {
- params.add(PROP_HOST + Integer.toString(i),
- mConfig.getString(PROP_HOST +
- Integer.toString(i), ""));
- params.add(PROP_PORT + Integer.toString(i),
- mConfig.getString(PROP_PORT +
- Integer.toString(i), "389"));
- params.add(PROP_BASE_DN + Integer.toString(i),
- mConfig.getString(PROP_BASE_DN +
- Integer.toString(i), ""));
- params.add(PROP_REFRESH_IN_SEC + Integer.toString(i),
- mConfig.getString(PROP_REFRESH_IN_SEC +
- Integer.toString(i), Integer.toString(DEF_REFRESH_IN_SEC)));
+ params.add(PROP_HOST + Integer.toString(i),
+ mConfig.getString(PROP_HOST +
+ Integer.toString(i), ""));
+ params.add(PROP_PORT + Integer.toString(i),
+ mConfig.getString(PROP_PORT +
+ Integer.toString(i), "389"));
+ params.add(PROP_BASE_DN + Integer.toString(i),
+ mConfig.getString(PROP_BASE_DN +
+ Integer.toString(i), ""));
+ params.add(PROP_REFRESH_IN_SEC + Integer.toString(i),
+ mConfig.getString(PROP_REFRESH_IN_SEC +
+ Integer.toString(i), Integer.toString(DEF_REFRESH_IN_SEC)));
}
- params.add(PROP_BY_NAME,
- mConfig.getString(PROP_BY_NAME, "true"));
- params.add(PROP_CA_CERT_ATTR,
- mConfig.getString(PROP_CA_CERT_ATTR, DEF_CA_CERT_ATTR));
+ params.add(PROP_BY_NAME,
+ mConfig.getString(PROP_BY_NAME, "true"));
+ params.add(PROP_CA_CERT_ATTR,
+ mConfig.getString(PROP_CA_CERT_ATTR, DEF_CA_CERT_ATTR));
params.add(PROP_CRL_ATTR,
- mConfig.getString(PROP_CRL_ATTR, DEF_CRL_ATTR));
+ mConfig.getString(PROP_CRL_ATTR, DEF_CRL_ATTR));
params.add(PROP_NOT_FOUND_GOOD,
- mConfig.getString(PROP_NOT_FOUND_GOOD, "true"));
+ mConfig.getString(PROP_NOT_FOUND_GOOD, "true"));
params.add(PROP_INCLUDE_NEXT_UPDATE,
- mConfig.getString(PROP_INCLUDE_NEXT_UPDATE, "false"));
+ mConfig.getString(PROP_INCLUDE_NEXT_UPDATE, "false"));
return params;
} catch (Exception e) {
return null;
@@ -564,7 +561,7 @@ public class LDAPStore implements IDefStore, IExtendedPluginInfo {
}
public void setConfigParameters(NameValuePairs pairs)
- throws EBaseException {
+ throws EBaseException {
Enumeration k = pairs.getNames();
while (k.hasMoreElements()) {
@@ -575,15 +572,14 @@ public class LDAPStore implements IDefStore, IExtendedPluginInfo {
}
}
-
class CRLUpdater extends Thread {
private LDAPConnection mC = null;
private String mBaseDN = null;
private int mSec = 0;
private LDAPStore mStore = null;
- public CRLUpdater(LDAPStore store, LDAPConnection c,
- String baseDN, int sec) {
+ public CRLUpdater(LDAPStore store, LDAPConnection c,
+ String baseDN, int sec) {
mC = c;
mSec = sec;
mBaseDN = baseDN;
@@ -608,7 +604,6 @@ class CRLUpdater extends Thread {
}
}
-
class TempCRLIssuingPointRecord implements ICRLIssuingPointRecord {
/**
*
@@ -739,7 +734,7 @@ class TempCRLIssuingPointRecord implements ICRLIssuingPointRecord {
return null;
}
- public void set(String name, Object obj)throws EBaseException {
+ public void set(String name, Object obj) throws EBaseException {
}
public Object get(String name) throws EBaseException {
@@ -747,7 +742,7 @@ class TempCRLIssuingPointRecord implements ICRLIssuingPointRecord {
}
public void delete(String name) throws EBaseException {
-
+
}
public Enumeration getElements() {
diff --git a/pki/base/common/src/com/netscape/cms/password/PasswordChecker.java b/pki/base/common/src/com/netscape/cms/password/PasswordChecker.java
index 4d59f34e..2bdf4066 100644
--- a/pki/base/common/src/com/netscape/cms/password/PasswordChecker.java
+++ b/pki/base/common/src/com/netscape/cms/password/PasswordChecker.java
@@ -17,17 +17,15 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.password;
-
import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.password.EPasswordCheckException;
import com.netscape.certsrv.password.IConfigPasswordCheck;
import com.netscape.certsrv.password.IPasswordCheck;
-
/**
* This class checks the given password if it meets the specific requirements.
- * For example, it can also specify the format of the password which has to
- * be 8 characters long and must be in alphanumeric.
+ * For example, it can also specify the format of the password which has to be 8
+ * characters long and must be in alphanumeric.
* <P>
*
* @version $Revision$, $Date$
@@ -75,9 +73,10 @@ public class PasswordChecker implements IPasswordCheck, IConfigPasswordCheck {
/**
* Returns true if the given password meets the quality requirement;
* otherwise returns false.
+ *
* @param mPassword The given password being checked.
* @return true if the password meets the quality requirement; otherwise
- * returns false.
+ * returns false.
*/
public boolean isGoodPassword(String mPassword) {
if (mPassword == null || mPassword.length() == 0) {
@@ -96,7 +95,9 @@ public class PasswordChecker implements IPasswordCheck, IConfigPasswordCheck {
/**
* Returns a reason if the password doesnt meet the quality requirement.
- * @return string as a reason if the password quality requirement is not met.
+ *
+ * @return string as a reason if the password quality requirement is not
+ * met.
*/
public String getReason(String mPassword) {
if (mPassword == null || mPassword.length() == 0) {
@@ -113,4 +114,3 @@ public class PasswordChecker implements IPasswordCheck, IConfigPasswordCheck {
return null;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/policy/APolicyRule.java b/pki/base/common/src/com/netscape/cms/policy/APolicyRule.java
index d9a527d6..9c050b2b 100644
--- a/pki/base/common/src/com/netscape/cms/policy/APolicyRule.java
+++ b/pki/base/common/src/com/netscape/cms/policy/APolicyRule.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy;
-
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
@@ -42,16 +41,15 @@ import com.netscape.certsrv.request.AgentApprovals;
import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
-
/**
- * The abstract policy rule that concrete implementations will
- * extend.
+ * The abstract policy rule that concrete implementations will extend.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
@@ -68,15 +66,16 @@ public abstract class APolicyRule implements IPolicyRule {
/**
* Initializes the policy rule.
* <P>
- *
- * @param config The config store reference
+ *
+ * @param config The config store reference
*/
public abstract void init(ISubsystem owner, IConfigStore config)
- throws EBaseException;
+ throws EBaseException;
/**
* Gets the description for this policy rule.
* <P>
+ *
* @return The Description for this rule.
*/
public String getDescription() {
@@ -86,8 +85,8 @@ public abstract class APolicyRule implements IPolicyRule {
/**
* Sets a predicate expression for rule matching.
* <P>
- *
- * @param exp The predicate expression for the rule.
+ *
+ * @param exp The predicate expression for the rule.
*/
public void setPredicate(IExpression exp) {
mFilterExp = exp;
@@ -96,7 +95,7 @@ public abstract class APolicyRule implements IPolicyRule {
/**
* Returns the predicate expression for the rule.
* <P>
- *
+ *
* @return The predicate expression for the rule.
*/
public IExpression getPredicate() {
@@ -106,7 +105,7 @@ public abstract class APolicyRule implements IPolicyRule {
/**
* Returns the name of the policy rule.
* <P>
- *
+ *
* @return The name of the policy class.
*/
public String getName() {
@@ -114,45 +113,45 @@ public abstract class APolicyRule implements IPolicyRule {
}
/**
- * Sets the instance name for a policy rule.
+ * Sets the instance name for a policy rule.
* <P>
- *
- * @param instanceName The name of the rule instance.
+ *
+ * @param instanceName The name of the rule instance.
*/
- public void setInstanceName(String instanceName) {
+ public void setInstanceName(String instanceName) {
mInstanceName = instanceName;
}
/**
* Returns the name of the policy rule instance.
* <P>
- *
- * @return The name of the policy rule instance if set, else
- * the name of the rule class.
+ *
+ * @return The name of the policy rule instance if set, else the name of the
+ * rule class.
*/
- public String getInstanceName() {
+ public String getInstanceName() {
return mInstanceName != null ? mInstanceName : NAME;
}
/**
* Applies the policy on the given Request.
* <P>
- *
- * @param req The request on which to apply policy.
+ *
+ * @param req The request on which to apply policy.
* @return The policy result object.
*/
public abstract PolicyResult apply(IRequest req);
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
public abstract Vector getInstanceParams();
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
public abstract Vector getDefaultParams();
@@ -161,8 +160,8 @@ public abstract class APolicyRule implements IPolicyRule {
setPolicyException(req, format, params);
}
- public void setError(IRequest req, String format, String arg1,
- String arg2) {
+ public void setError(IRequest req, String format, String arg1,
+ String arg2) {
Object[] np = new Object[2];
np[0] = arg1;
@@ -188,10 +187,10 @@ public abstract class APolicyRule implements IPolicyRule {
}
/**
- * determines whether a DEFERRED policy result should be returned
- * by checking the contents of the AgentApprovals attribute. This
- * call should be used by policy modules instead of returning
- * PolicyResult.DEFERRED directly.
+ * determines whether a DEFERRED policy result should be returned by
+ * checking the contents of the AgentApprovals attribute. This call should
+ * be used by policy modules instead of returning PolicyResult.DEFERRED
+ * directly.
* <p>
*/
protected PolicyResult deferred(IRequest req) {
@@ -223,12 +222,12 @@ public abstract class APolicyRule implements IPolicyRule {
}
}
- public void setPolicyException(IRequest req, String format,
- Object[] params) {
- if (format == null)
+ public void setPolicyException(IRequest req, String format,
+ Object[] params) {
+ if (format == null)
return;
- EPolicyException ex;
+ EPolicyException ex;
if (params == null)
ex = new EPolicyException(format);
@@ -247,12 +246,12 @@ public abstract class APolicyRule implements IPolicyRule {
* log a message for this policy rule.
*/
protected void log(int level, String msg) {
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, level,
- "APolicyRule " + NAME + ": " + msg);
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, level,
+ "APolicyRule " + NAME + ": " + msg);
}
- public static KeyIdentifier createKeyIdentifier(X509Key key)
- throws NoSuchAlgorithmException, InvalidKeyException {
+ public static KeyIdentifier createKeyIdentifier(X509Key key)
+ throws NoSuchAlgorithmException, InvalidKeyException {
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(key.getEncoded());
@@ -260,19 +259,20 @@ public abstract class APolicyRule implements IPolicyRule {
}
/**
- * Form a byte array of octet string key identifier from the sha-1 hash of
+ * Form a byte array of octet string key identifier from the sha-1 hash of
* the Subject Public Key INFO. (including algorithm ID, etc.)
* <p>
+ *
* @param certInfo cert info of the certificate.
* @return A Key identifier with the sha-1 hash of subject public key.
*/
protected KeyIdentifier formSpkiSHA1KeyId(X509CertInfo certInfo)
- throws EBaseException {
+ throws EBaseException {
KeyIdentifier keyId = null;
try {
CertificateX509Key certKey =
- (CertificateX509Key) certInfo.get(X509CertInfo.KEY);
+ (CertificateX509Key) certInfo.get(X509CertInfo.KEY);
if (certKey == null) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("POLICY_MISSING_KEY_1", ""));
@@ -286,23 +286,23 @@ public abstract class APolicyRule implements IPolicyRule {
}
keyId = createKeyIdentifier(key);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("POLICY_ERROR_SUBJECT_KEY_ID_1", NAME));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("POLICY_ERROR_SUBJECT_KEY_ID_1", NAME));
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_SUBJECT_KEY_ID_ERROR", NAME));
} catch (CertificateException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("POLICY_ERROR_SUBJECT_KEY_ID_1", NAME));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("POLICY_ERROR_SUBJECT_KEY_ID_1", NAME));
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_SUBJECT_KEY_ID_ERROR", NAME));
} catch (NoSuchAlgorithmException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("POLICY_ERROR_SUBJECT_KEY_ID_1", NAME));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("POLICY_ERROR_SUBJECT_KEY_ID_1", NAME));
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_SUBJECT_KEY_ID_ERROR", NAME));
} catch (InvalidKeyException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("POLICY_ERROR_SUBJECT_KEY_ID_1", NAME));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("POLICY_ERROR_SUBJECT_KEY_ID_1", NAME));
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_SUBJECT_KEY_ID_ERROR", NAME));
}
@@ -310,19 +310,20 @@ public abstract class APolicyRule implements IPolicyRule {
}
/**
- * Form a byte array of octet string key identifier from the sha-1 hash of
+ * Form a byte array of octet string key identifier from the sha-1 hash of
* the Subject Public Key BIT STRING.
* <p>
+ *
* @param certInfo cert info of the certificate.
* @return A Key identifier with the sha-1 hash of subject public key.
*/
protected KeyIdentifier formSHA1KeyId(X509CertInfo certInfo)
- throws EBaseException {
+ throws EBaseException {
KeyIdentifier keyId = null;
try {
CertificateX509Key certKey =
- (CertificateX509Key) certInfo.get(X509CertInfo.KEY);
+ (CertificateX509Key) certInfo.get(X509CertInfo.KEY);
if (certKey == null) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("POLICY_MISSING_KEY_1", ""));
@@ -341,22 +342,21 @@ public abstract class APolicyRule implements IPolicyRule {
md.update(rawKey);
keyId = new KeyIdentifier(md.digest());
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("POLICY_ERROR_SUBJECT_KEY_ID_1", NAME));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("POLICY_ERROR_SUBJECT_KEY_ID_1", NAME));
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_SUBJECT_KEY_ID_ERROR", NAME));
} catch (CertificateException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("POLICY_ERROR_SUBJECT_KEY_ID_1", NAME));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("POLICY_ERROR_SUBJECT_KEY_ID_1", NAME));
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_SUBJECT_KEY_ID_ERROR", NAME));
} catch (NoSuchAlgorithmException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("POLICY_ERROR_SUBJECT_KEY_ID_1", NAME));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("POLICY_ERROR_SUBJECT_KEY_ID_1", NAME));
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_SUBJECT_KEY_ID_ERROR", NAME));
}
return keyId;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/policy/constraints/AgentPolicy.java b/pki/base/common/src/com/netscape/cms/policy/constraints/AgentPolicy.java
index 3aeadabe..d203e904 100644
--- a/pki/base/common/src/com/netscape/cms/policy/constraints/AgentPolicy.java
+++ b/pki/base/common/src/com/netscape/cms/policy/constraints/AgentPolicy.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.constraints;
-
import java.util.Vector;
import com.netscape.certsrv.apps.CMS;
@@ -30,24 +29,23 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
- * AgentPolicy is an enrollment policy wraps another policy module.
- * Requests are sent first to the contained module, but if the
- * policy indicates that the request should be deferred, a check
- * for agent approvals is done. If any are found, the request
- * is approved.
+ * AgentPolicy is an enrollment policy wraps another policy module. Requests are
+ * sent first to the contained module, but if the policy indicates that the
+ * request should be deferred, a check for agent approvals is done. If any are
+ * found, the request is approved.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public class AgentPolicy extends APolicyRule
- implements IEnrollmentPolicy {
+ implements IEnrollmentPolicy {
public AgentPolicy() {
NAME = "AgentPolicy";
DESC = "Agent Approval Policy";
@@ -56,19 +54,19 @@ public class AgentPolicy extends APolicyRule
/**
* Initializes this policy rule.
* <P>
- *
+ *
* The entries may be of the form:
- *
- * ra.Policy.rule.<ruleName>.implName=AgentPolicy
- * ra.Policy.rule.<ruleName>.enable=true
- * ra.Policy.rule.<ruleName>.predicate= ou == engineering AND o == netscape.com
- * ra.Policy.rule.<ruleName>.class=xxxx
- * ra.Policy.rule.<ruleName>.params.*
- *
- * @param config The config store reference
+ *
+ * ra.Policy.rule.<ruleName>.implName=AgentPolicy
+ * ra.Policy.rule.<ruleName>.enable=true
+ * ra.Policy.rule.<ruleName>.predicate= ou == engineering AND o ==
+ * netscape.com ra.Policy.rule.<ruleName>.class=xxxx
+ * ra.Policy.rule.<ruleName>.params.*
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EPolicyException {
+ throws EPolicyException {
// Create subordinate object
String className = (String) config.get("class");
@@ -79,14 +77,14 @@ public class AgentPolicy extends APolicyRule
try {
@SuppressWarnings("unchecked")
- Class<APolicyRule> c = (Class<APolicyRule>) Class.forName(className);
+ Class<APolicyRule> c = (Class<APolicyRule>) Class.forName(className);
Object o = c.newInstance();
if (!(o instanceof APolicyRule)) {
throw new EPolicyException(
- CMS.getUserMessage("CMS_POLICY_INVALID_POLICY_CLASS",
- getInstanceName(), className));
+ CMS.getUserMessage("CMS_POLICY_INVALID_POLICY_CLASS",
+ getInstanceName(), className));
}
APolicyRule pr = (APolicyRule) o;
@@ -100,7 +98,7 @@ public class AgentPolicy extends APolicyRule
System.err.println("Agent Policy Error: " + e);
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_LOADING_POLICY_ERROR",
- getInstanceName(), className));
+ getInstanceName(), className));
}
}
}
@@ -108,8 +106,8 @@ public class AgentPolicy extends APolicyRule
/**
* Applies the policy on the given Request.
* <P>
- *
- * @param req The request on which to apply policy.
+ *
+ * @param req The request on which to apply policy.
* @return The policy result object.
*/
public PolicyResult apply(IRequest req) {
@@ -129,10 +127,10 @@ public class AgentPolicy extends APolicyRule
AgentApprovals aa = AgentApprovals.fromStringVector(
req.getExtDataInStringVector(AgentApprovals.class.getName()));
- //Object o = req.get("agentApprovals");
+ // Object o = req.get("agentApprovals");
// Any approvals causes success
- if (aa != null && aa.elements().hasMoreElements()) //if (o != null)
+ if (aa != null && aa.elements().hasMoreElements()) // if (o != null)
{
System.err.println("Agent approval found");
result = PolicyResult.ACCEPTED;
@@ -144,7 +142,7 @@ public class AgentPolicy extends APolicyRule
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
public Vector<String> getInstanceParams() {
@@ -153,13 +151,12 @@ public class AgentPolicy extends APolicyRule
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
public Vector<String> getDefaultParams() {
return null;
}
- APolicyRule mPolicy = null;
+ APolicyRule mPolicy = null;
}
-
diff --git a/pki/base/common/src/com/netscape/cms/policy/constraints/AttributePresentConstraints.java b/pki/base/common/src/com/netscape/cms/policy/constraints/AttributePresentConstraints.java
index 90e81ed4..ebf111cb 100644
--- a/pki/base/common/src/com/netscape/cms/policy/constraints/AttributePresentConstraints.java
+++ b/pki/base/common/src/com/netscape/cms/policy/constraints/AttributePresentConstraints.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.constraints;
-
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Locale;
@@ -44,20 +43,20 @@ import com.netscape.certsrv.request.PolicyResult;
import com.netscape.certsrv.request.RequestId;
import com.netscape.cms.policy.APolicyRule;
-
/**
* This checks if attribute present.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
-public class AttributePresentConstraints extends APolicyRule
- implements IEnrollmentPolicy, IExtendedPluginInfo {
+public class AttributePresentConstraints extends APolicyRule
+ implements IEnrollmentPolicy, IExtendedPluginInfo {
protected static final String PROP_ENABLED = "enabled";
protected static final String PROP_LDAP = "ldap";
@@ -82,42 +81,42 @@ public class AttributePresentConstraints extends APolicyRule
public String[] getExtendedPluginInfo(Locale locale) {
String params[] = {
PROP_ATTR + ";string,required;Ldap attribute to check presence of (default " +
- DEF_ATTR + ")",
+ DEF_ATTR + ")",
PROP_VALUE + ";string;if this parameter is non-empty, the attribute must " +
- "match this value for the request to proceed ",
+ "match this value for the request to proceed ",
PROP_LDAP_BASE + ";string,required;Base DN to start searching " +
- "under. If your user's DN is 'uid=jsmith, o=company', you " +
- "might want to use 'o=company' here",
+ "under. If your user's DN is 'uid=jsmith, o=company', you " +
+ "might want to use 'o=company' here",
PROP_LDAP_HOST + ";string,required;" +
- "LDAP host to connect to",
+ "LDAP host to connect to",
PROP_LDAP_PORT + ";number,required;" +
- "LDAP port number (use 389, or 636 if SSL)",
+ "LDAP port number (use 389, or 636 if SSL)",
PROP_LDAP_SSL + ";boolean;" +
- "Use SSL to connect to directory?",
+ "Use SSL to connect to directory?",
PROP_LDAP_VER + ";choice(3,2),required;" +
- "LDAP protocol version",
+ "LDAP protocol version",
PROP_LDAP_BIND + ";string;DN to bind as for attribute checking. " +
- "For example 'CN=Pincheck User'",
+ "For example 'CN=Pincheck User'",
PROP_LDAP_PW + ";password;Enter password used to bind as " +
- "the above user",
+ "the above user",
PROP_LDAP_AUTH + ";choice(BasicAuth,SslClientAuth),required;" +
- "How to bind to the directory",
+ "How to bind to the directory",
PROP_LDAP_CERT + ";string;If you want to use " +
- "SSL client auth to the directory, set the client " +
- "cert nickname here",
+ "SSL client auth to the directory, set the client " +
+ "cert nickname here",
PROP_LDAP_BASE + ";string,required;Base DN to start searching " +
- "under. If your user's DN is 'uid=jsmith, o=company', you " +
- "might want to use 'o=company' here",
+ "under. If your user's DN is 'uid=jsmith, o=company', you " +
+ "might want to use 'o=company' here",
PROP_LDAP_MINC + ";number;number of connections " +
- "to keep open to directory server. Default " + DEF_LDAP_MINC,
+ "to keep open to directory server. Default " + DEF_LDAP_MINC,
PROP_LDAP_MAXC + ";number;when needed, connection " +
- "pool can grow to this many (multiplexed) connections. Default " + DEF_LDAP_MAXC,
+ "pool can grow to this many (multiplexed) connections. Default " + DEF_LDAP_MAXC,
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-pinpresent",
+ ";configuration-policyrules-pinpresent",
IExtendedPluginInfo.HELP_TEXT +
- ";" + DESC + " This plugin can be used to " +
- "check the presence (and, optionally, the value) of any LDAP " +
- "attribute for the user. "
+ ";" + DESC + " This plugin can be used to " +
+ "check the presence (and, optionally, the value) of any LDAP " +
+ "attribute for the user. "
};
return params;
@@ -179,9 +178,9 @@ public class AttributePresentConstraints extends APolicyRule
protected static final String PROP_VALUE = "value";
protected static final String DEF_VALUE = "";
- protected static Vector<String> mParamNames;
+ protected static Vector<String> mParamNames;
protected static Hashtable<String, Object> mParamDefault;
- protected Hashtable<String, Object> mParamValue = null;
+ protected Hashtable<String, Object> mParamValue = null;
static {
mParamNames = new Vector<String>();
@@ -200,7 +199,7 @@ public class AttributePresentConstraints extends APolicyRule
addParam(PROP_ATTR, DEF_ATTR);
addParam(PROP_VALUE, DEF_VALUE);
};
-
+
protected static void addParam(String name, Object value) {
mParamNames.addElement(name);
mParamDefault.put(name, value);
@@ -209,8 +208,8 @@ public class AttributePresentConstraints extends APolicyRule
protected void getStringConfigParam(IConfigStore config, String paramName) {
try {
mParamValue.put(
- paramName, config.getString(paramName, (String) mParamDefault.get(paramName))
- );
+ paramName, config.getString(paramName, (String) mParamDefault.get(paramName))
+ );
} catch (Exception e) {
}
}
@@ -218,12 +217,12 @@ public class AttributePresentConstraints extends APolicyRule
protected void getIntConfigParam(IConfigStore config, String paramName) {
try {
mParamValue.put(
- paramName, Integer.valueOf(
- config.getInteger(paramName,
- ((Integer) mParamDefault.get(paramName)).intValue()
- )
- )
- );
+ paramName, Integer.valueOf(
+ config.getInteger(paramName,
+ ((Integer) mParamDefault.get(paramName)).intValue()
+ )
+ )
+ );
} catch (Exception e) {
}
}
@@ -231,18 +230,18 @@ public class AttributePresentConstraints extends APolicyRule
protected void getBooleanConfigParam(IConfigStore config, String paramName) {
try {
mParamValue.put(
- paramName, Boolean.valueOf(
- config.getBoolean(paramName,
- ((Boolean) mParamDefault.get(paramName)).booleanValue()
- )
- )
- );
+ paramName, Boolean.valueOf(
+ config.getBoolean(paramName,
+ ((Boolean) mParamDefault.get(paramName)).booleanValue()
+ )
+ )
+ );
} catch (Exception e) {
}
}
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mConfig = config;
mParamValue = new Hashtable<String, Object>();
@@ -277,7 +276,7 @@ public class AttributePresentConstraints extends APolicyRule
String requestType = r.getRequestType();
if (requestType.equals(IRequest.ENROLLMENT_REQUEST) ||
- requestType.equals(IRequest.RENEWAL_REQUEST)) {
+ requestType.equals(IRequest.RENEWAL_REQUEST)) {
String uid = r.getExtDataInString(IRequest.HTTP_PARAMS, "uid");
@@ -291,10 +290,10 @@ public class AttributePresentConstraints extends APolicyRule
try {
String[] attrs = { (String) mParamValue.get(PROP_ATTR) };
- LDAPSearchResults searchResult =
- mCheckAttrLdapConnection.search((String) mParamValue.get(PROP_LDAP_BASE),
- LDAPv2.SCOPE_SUB, "(uid=" + uid + ")", attrs, false);
-
+ LDAPSearchResults searchResult =
+ mCheckAttrLdapConnection.search((String) mParamValue.get(PROP_LDAP_BASE),
+ LDAPv2.SCOPE_SUB, "(uid=" + uid + ")", attrs, false);
+
if (!searchResult.hasMoreElements()) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMS_AUTH_NO_PIN_FOUND", uid));
setError(r, CMS.getUserMessage("CMS_POLICY_PIN_UNAUTHORIZED"), "");
@@ -304,12 +303,12 @@ public class AttributePresentConstraints extends APolicyRule
LDAPEntry entry = (LDAPEntry) searchResult.nextElement();
userdn = entry.getDN();
-
+
LDAPAttribute attr = entry.getAttribute((String) mParamValue.get(PROP_ATTR));
/* if attribute not present, reject the request */
if (attr == null) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("CMS_AUTH_NO_PIN_FOUND", userdn));
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("CMS_AUTH_NO_PIN_FOUND", userdn));
setError(r, CMS.getUserMessage("CMS_POLICY_PIN_UNAUTHORIZED"), "");
return PolicyResult.REJECTED;
}
@@ -331,7 +330,7 @@ public class AttributePresentConstraints extends APolicyRule
return PolicyResult.REJECTED;
}
}
-
+
CMS.debug("AttributePresentConstraints: Attribute is present for user: \"" + userdn + "\"");
} catch (LDAPException e) {
@@ -344,7 +343,7 @@ public class AttributePresentConstraints extends APolicyRule
return res;
}
- public Vector<String> getInstanceParams() {
+ public Vector<String> getInstanceParams() {
Vector<String> params = new Vector<String>();
Enumeration<String> e = mParamNames.elements();
@@ -382,25 +381,26 @@ public class AttributePresentConstraints extends APolicyRule
return params;
/*
- params.addElement("ldap.ldapconn.host=localhost");
- params.addElement("ldap.ldapconn.port=389");
- params.addElement("ldap.ldapconn.secureConn=false");
- params.addElement("ldap.ldapconn.version=3");
- params.addElement("ldap.ldapauth.bindDN=CN=Directory Manager");
- params.addElement("ldap.ldapauth.bindPWPrompt=");
- params.addElement("ldap.ldapauth.clientCertNickname=");
- params.addElement("ldap.ldapauth.authtype=BasicAuth");
- params.addElement("ldap.basedn=");
- params.addElement("ldap.minConns=1");
- params.addElement("ldap.maxConns=5");
+ * params.addElement("ldap.ldapconn.host=localhost");
+ * params.addElement("ldap.ldapconn.port=389");
+ * params.addElement("ldap.ldapconn.secureConn=false");
+ * params.addElement("ldap.ldapconn.version=3");
+ * params.addElement("ldap.ldapauth.bindDN=CN=Directory Manager");
+ * params.addElement("ldap.ldapauth.bindPWPrompt=");
+ * params.addElement("ldap.ldapauth.clientCertNickname=");
+ * params.addElement("ldap.ldapauth.authtype=BasicAuth");
+ * params.addElement("ldap.basedn=");
+ * params.addElement("ldap.minConns=1");
+ * params.addElement("ldap.maxConns=5");
*/
}
protected void log(int level, String msg) {
- if (mLogger == null) return;
+ if (mLogger == null)
+ return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_OTHER,
- level, "AttributePresentConstraints: " + msg);
+ level, "AttributePresentConstraints: " + msg);
}
}
diff --git a/pki/base/common/src/com/netscape/cms/policy/constraints/DSAKeyConstraints.java b/pki/base/common/src/com/netscape/cms/policy/constraints/DSAKeyConstraints.java
index 3caee615..c8f96409 100644
--- a/pki/base/common/src/com/netscape/cms/policy/constraints/DSAKeyConstraints.java
+++ b/pki/base/common/src/com/netscape/cms/policy/constraints/DSAKeyConstraints.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.constraints;
-
import java.math.BigInteger;
import java.security.interfaces.DSAParams;
import java.util.Locale;
@@ -40,20 +39,20 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
* DSAKeyConstraints policy enforces min and max size of the key.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public class DSAKeyConstraints extends APolicyRule
- implements IEnrollmentPolicy, IExtendedPluginInfo {
+ implements IEnrollmentPolicy, IExtendedPluginInfo {
private int mMinSize;
private int mMaxSize;
@@ -73,7 +72,7 @@ public class DSAKeyConstraints extends APolicyRule
defConfParams.addElement(PROP_MIN_SIZE + "=" + DEF_MIN_SIZE);
defConfParams.addElement(PROP_MAX_SIZE + "=" + DEF_MAX_SIZE);
}
-
+
public DSAKeyConstraints() {
NAME = "DSAKeyConstraints";
DESC = "Enforces DSA Key Constraints.";
@@ -84,9 +83,9 @@ public class DSAKeyConstraints extends APolicyRule
PROP_MIN_SIZE + ";number;Minimum key size",
PROP_MAX_SIZE + ";number;Maximum key size",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-dsakeyconstraints",
+ ";configuration-policyrules-dsakeyconstraints",
IExtendedPluginInfo.HELP_TEXT +
- ";Rejects request if DSA key size is out of range"
+ ";Rejects request if DSA key size is out of range"
};
return params;
@@ -95,18 +94,19 @@ public class DSAKeyConstraints extends APolicyRule
/**
* Initializes this policy rule.
* <P>
- *
+ *
* The entries probably are of the form
- * ra.Policy.rule.<ruleName>.implName=DSAKeyConstraints
- * ra.Policy.rule.<ruleName>.enable=true
- * ra.Policy.rule.<ruleName>.minSize=512
- * ra.Policy.rule.<ruleName>.maxSize=1024
- * ra.Policy.rule.<ruleName>.predicate= ou == engineering AND o == netscape.com
- *
- * @param config The config store reference
+ * ra.Policy.rule.<ruleName>.implName=DSAKeyConstraints
+ * ra.Policy.rule.<ruleName>.enable=true
+ * ra.Policy.rule.<ruleName>.minSize=512
+ * ra.Policy.rule.<ruleName>.maxSize=1024
+ * ra.Policy.rule.<ruleName>.predicate= ou == engineering AND o ==
+ * netscape.com
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EPolicyException {
+ throws EPolicyException {
// Get Min and Max sizes
mConfig = config;
@@ -120,34 +120,34 @@ public class DSAKeyConstraints extends APolicyRule
log(ILogger.LL_FAILURE, PROP_MAX_SIZE + " " + msg);
throw new EBaseException(
- CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
- PROP_MAX_SIZE, msg));
+ CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
+ PROP_MAX_SIZE, msg));
}
if (mMinSize < DEF_MIN_SIZE) {
String msg = "cannot be less than " + DEF_MIN_SIZE;
log(ILogger.LL_FAILURE, PROP_MIN_SIZE + " " + msg);
throw new EBaseException(
- CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
- PROP_MIN_SIZE, msg));
+ CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
+ PROP_MIN_SIZE, msg));
}
if (mMaxSize % INCREMENT != 0) {
String msg = "must be in increments of " + INCREMENT;
log(ILogger.LL_FAILURE, PROP_MAX_SIZE + " " + msg);
throw new EBaseException(
- CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
- PROP_MIN_SIZE, msg));
+ CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
+ PROP_MIN_SIZE, msg));
}
if (mMaxSize % INCREMENT != 0) {
String msg = "must be in increments of " + INCREMENT;
log(ILogger.LL_FAILURE, PROP_MIN_SIZE + " " + msg);
throw new EBaseException(
- CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
- PROP_MIN_SIZE, msg));
+ CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
+ PROP_MIN_SIZE, msg));
}
-
+
config.putInteger(PROP_MIN_SIZE, mMinSize);
config.putInteger(PROP_MAX_SIZE, mMaxSize);
@@ -160,8 +160,8 @@ public class DSAKeyConstraints extends APolicyRule
/**
* Applies the policy on the given Request.
* <P>
- *
- * @param req The request on which to apply policy.
+ *
+ * @param req The request on which to apply policy.
* @return The policy result object.
*/
public PolicyResult apply(IRequest req) {
@@ -171,7 +171,7 @@ public class DSAKeyConstraints extends APolicyRule
try {
// Get the certificate info from the request
X509CertInfo ci[] =
- req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
+ req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
// There should be a certificate info set.
if (ci == null || ci[0] == null) {
@@ -182,19 +182,19 @@ public class DSAKeyConstraints extends APolicyRule
// Else check if the key size(s) are within the limit.
for (int i = 0; i < ci.length; i++) {
CertificateX509Key certKey = (CertificateX509Key)
- ci[i].get(X509CertInfo.KEY);
+ ci[i].get(X509CertInfo.KEY);
X509Key key = (X509Key) certKey.get(CertificateX509Key.KEY);
String alg = key.getAlgorithmId().toString();
if (!alg.equalsIgnoreCase(DSA))
continue;
- // Check DSAKey parameters.
- // size refers to the p parameter.
+ // Check DSAKey parameters.
+ // size refers to the p parameter.
DSAPublicKey dsaKey = new DSAPublicKey(key.getEncoded());
DSAParams keyParams = dsaKey.getParams();
- if (keyParams == null) {
+ if (keyParams == null) {
// key parameters could not be parsed.
Object[] params = new Object[] {
getInstanceName(), String.valueOf(i + 1) };
@@ -205,11 +205,11 @@ public class DSAKeyConstraints extends APolicyRule
BigInteger p = keyParams.getP();
int len = p.bitLength();
- if (len < mMinSize || len > mMaxSize ||
- (len % INCREMENT) != 0) {
- String[] parms = new String[] {
- getInstanceName(),
- String.valueOf(len),
+ if (len < mMinSize || len > mMaxSize ||
+ (len % INCREMENT) != 0) {
+ String[] parms = new String[] {
+ getInstanceName(),
+ String.valueOf(len),
String.valueOf(mMinSize),
String.valueOf(mMaxSize),
String.valueOf(INCREMENT) };
@@ -220,7 +220,7 @@ public class DSAKeyConstraints extends APolicyRule
}
} catch (Exception e) {
// e.printStackTrace();
- String[] params = { getInstanceName(), e.toString()};
+ String[] params = { getInstanceName(), e.toString() };
setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR", params), "");
result = PolicyResult.REJECTED;
@@ -230,27 +230,27 @@ public class DSAKeyConstraints extends APolicyRule
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector getInstanceParams() {
+ public Vector getInstanceParams() {
Vector confParams = new Vector();
try {
confParams.addElement(PROP_MIN_SIZE + "=" + mConfig.getInteger(PROP_MIN_SIZE, DEF_MIN_SIZE));
confParams.addElement(PROP_MAX_SIZE + "=" + mConfig.getInteger(PROP_MAX_SIZE, DEF_MAX_SIZE));
- } catch (EBaseException e) {;
+ } catch (EBaseException e) {
+ ;
}
return confParams;
}
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
public Vector getDefaultParams() {
return defConfParams;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/policy/constraints/DefaultRevocation.java b/pki/base/common/src/com/netscape/cms/policy/constraints/DefaultRevocation.java
index 3d4aedc3..4fc40036 100644
--- a/pki/base/common/src/com/netscape/cms/policy/constraints/DefaultRevocation.java
+++ b/pki/base/common/src/com/netscape/cms/policy/constraints/DefaultRevocation.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.constraints;
-
import java.util.Locale;
import java.util.Vector;
@@ -30,22 +29,21 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
- * This is the default revocation policy. Currently this does
- * nothing. We can later add checks like whether or not to
- * revoke expired certs ..etc here.
+ * This is the default revocation policy. Currently this does nothing. We can
+ * later add checks like whether or not to revoke expired certs ..etc here.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public class DefaultRevocation extends APolicyRule
- implements IRevocationPolicy, IExtendedPluginInfo {
+ implements IRevocationPolicy, IExtendedPluginInfo {
public DefaultRevocation() {
NAME = "DefaultRevocation";
DESC = "Default Revocation Policy";
@@ -54,24 +52,25 @@ public class DefaultRevocation extends APolicyRule
/**
* Initializes this policy rule.
* <P>
- *
+ *
* The entries may be of the form:
- *
- * ra.Policy.rule.<ruleName>.implName=DefaultRevocation
- * ra.Policy.rule.<ruleName>.enable=true
- * ra.Policy.rule.<ruleName>.predicate= ou == engineering AND o == netscape.com
- *
- * @param config The config store reference
+ *
+ * ra.Policy.rule.<ruleName>.implName=DefaultRevocation
+ * ra.Policy.rule.<ruleName>.enable=true
+ * ra.Policy.rule.<ruleName>.predicate= ou == engineering AND o ==
+ * netscape.com
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EPolicyException {
+ throws EPolicyException {
}
/**
* Applies the policy on the given Request.
* <P>
- *
- * @param req The request on which to apply policy.
+ *
+ * @param req The request on which to apply policy.
* @return The policy result object.
*/
public PolicyResult apply(IRequest req) {
@@ -80,7 +79,7 @@ public class DefaultRevocation extends APolicyRule
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
public Vector getInstanceParams() {
@@ -89,7 +88,7 @@ public class DefaultRevocation extends APolicyRule
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
public Vector getDefaultParams() {
@@ -104,4 +103,3 @@ public class DefaultRevocation extends APolicyRule
return params;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/policy/constraints/IssuerConstraints.java b/pki/base/common/src/com/netscape/cms/policy/constraints/IssuerConstraints.java
index aed75bcd..8e10d3b6 100644
--- a/pki/base/common/src/com/netscape/cms/policy/constraints/IssuerConstraints.java
+++ b/pki/base/common/src/com/netscape/cms/policy/constraints/IssuerConstraints.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.constraints;
-
import java.util.Locale;
import java.util.Vector;
@@ -35,29 +34,29 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
- * IssuerConstraints is a rule for restricting the issuers of the
- * certificates used for certificate-based enrollments.
+ * IssuerConstraints is a rule for restricting the issuers of the certificates
+ * used for certificate-based enrollments.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$ $Date$
*/
public class IssuerConstraints extends APolicyRule
- implements IEnrollmentPolicy, IExtendedPluginInfo {
+ implements IEnrollmentPolicy, IExtendedPluginInfo {
private final static String PROP_ISSUER_DN = "issuerDN";
private static final String CLIENT_ISSUER = "clientIssuer";
private X500Name mIssuerDN = null;
private String mIssuerDNString;
/**
- * checks the issuer of the ssl client-auth cert. Only one issuer
- * is allowed for now
+ * checks the issuer of the ssl client-auth cert. Only one issuer is allowed
+ * for now
*/
public IssuerConstraints() {
NAME = "IssuerConstraints";
@@ -68,10 +67,10 @@ public class IssuerConstraints extends APolicyRule
String[] params = {
PROP_ISSUER_DN + ";string;Subject DN of the Issuer. The IssuerDN of the authenticating cert must match what's specified here",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-issuerconstraints",
+ ";configuration-policyrules-issuerconstraints",
IExtendedPluginInfo.HELP_TEXT +
- ";Rejects the request if the issuer in the certificate is" +
- "not of the one specified"
+ ";Rejects the request if the issuer in the certificate is" +
+ "not of the one specified"
};
return params;
@@ -81,34 +80,35 @@ public class IssuerConstraints extends APolicyRule
/**
* Initializes this policy rule.
* <P>
- * @param config The config store reference
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EPolicyException {
+ throws EPolicyException {
try {
mIssuerDNString = config.getString(PROP_ISSUER_DN, null);
- if ((mIssuerDNString != null) &&
- !mIssuerDNString.equals("")) {
+ if ((mIssuerDNString != null) &&
+ !mIssuerDNString.equals("")) {
mIssuerDN = new X500Name(mIssuerDNString);
}
} catch (Exception e) {
- log(ILogger.LL_FAILURE,
- NAME + CMS.getLogMessage("CA_GET_ISSUER_NAME_FAILED"));
+ log(ILogger.LL_FAILURE,
+ NAME + CMS.getLogMessage("CA_GET_ISSUER_NAME_FAILED"));
- String[] params = {getInstanceName(), e.toString()};
+ String[] params = { getInstanceName(), e.toString() };
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_INVALID_POLICY_CONFIG", params));
}
CMS.debug(
- NAME + ": init() done");
+ NAME + ": init() done");
}
/**
* Applies the policy on the given Request.
* <P>
- *
- * @param req The request on which to apply policy.
+ *
+ * @param req The request on which to apply policy.
* @return The policy result object.
*/
public PolicyResult apply(IRequest req) {
@@ -125,82 +125,82 @@ public class IssuerConstraints extends APolicyRule
if (!ci_name.equals(mIssuerDN)) {
setError(req,
- CMS.getUserMessage("CMS_POLICY_INVALID_ISSUER",
- getInstanceName()), "");
+ CMS.getUserMessage("CMS_POLICY_INVALID_ISSUER",
+ getInstanceName()), "");
result = PolicyResult.REJECTED;
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CA_GET_ISSUER_NAME_FAILED"));
+ CMS.getLogMessage("CA_GET_ISSUER_NAME_FAILED"));
CMS.debug(
- NAME + ": apply() - issuerDN mismatch: client issuerDN = " + clientIssuerDN + "; expected issuerDN = " + mIssuerDNString);
+ NAME + ": apply() - issuerDN mismatch: client issuerDN = " + clientIssuerDN + "; expected issuerDN = " + mIssuerDNString);
}
} else {
// Get the certificate info from the request
X509CertInfo certInfo[] =
- req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
+ req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
if (certInfo == null) {
- log(ILogger.LL_FAILURE,
- NAME + ": apply() - missing certInfo");
- setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO",
+ log(ILogger.LL_FAILURE,
+ NAME + ": apply() - missing certInfo");
+ setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO",
getInstanceName()), "");
return PolicyResult.REJECTED;
}
-
+
for (int i = 0; i < certInfo.length; i++) {
String oldIssuer = (String)
- certInfo[i].get(X509CertInfo.ISSUER).toString();
-
+ certInfo[i].get(X509CertInfo.ISSUER).toString();
+
if (oldIssuer == null) {
setError(req,
- CMS.getUserMessage("CMS_POLICY_CLIENT_ISSUER_NOT_FOUND",
- getInstanceName()), "");
+ CMS.getUserMessage("CMS_POLICY_CLIENT_ISSUER_NOT_FOUND",
+ getInstanceName()), "");
result = PolicyResult.REJECTED;
- log(ILogger.LL_FAILURE,
- NAME + ": apply() - client issuerDN not found");
+ log(ILogger.LL_FAILURE,
+ NAME + ": apply() - client issuerDN not found");
}
X500Name oi_name = new X500Name(oldIssuer);
if (!oi_name.equals(mIssuerDN)) {
setError(req,
- CMS.getUserMessage("CMS_POLICY_INVALID_ISSUER",
- getInstanceName()), "");
+ CMS.getUserMessage("CMS_POLICY_INVALID_ISSUER",
+ getInstanceName()), "");
result = PolicyResult.REJECTED;
- log(ILogger.LL_FAILURE,
- NAME + ": apply() - cert issuerDN mismatch: client issuerDN = " + oldIssuer + "; expected issuerDN = " + mIssuerDNString);
+ log(ILogger.LL_FAILURE,
+ NAME + ": apply() - cert issuerDN mismatch: client issuerDN = " + oldIssuer + "; expected issuerDN = " + mIssuerDNString);
}
}
}
} catch (Exception e) {
- String params[] = {getInstanceName(), e.toString()};
+ String params[] = { getInstanceName(), e.toString() };
setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR", params), "");
result = PolicyResult.REJECTED;
}
if (result.equals(PolicyResult.ACCEPTED)) {
- log(ILogger.LL_INFO,
- NAME + ": apply() - accepted");
+ log(ILogger.LL_INFO,
+ NAME + ": apply() - accepted");
}
return result;
}
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
public Vector getInstanceParams() {
Vector confParams = new Vector();
confParams.addElement(PROP_ISSUER_DN + "=" +
- mIssuerDNString);
+ mIssuerDNString);
return confParams;
}
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
public Vector getDefaultParams() {
diff --git a/pki/base/common/src/com/netscape/cms/policy/constraints/KeyAlgorithmConstraints.java b/pki/base/common/src/com/netscape/cms/policy/constraints/KeyAlgorithmConstraints.java
index 8286cf31..7c79ced7 100644
--- a/pki/base/common/src/com/netscape/cms/policy/constraints/KeyAlgorithmConstraints.java
+++ b/pki/base/common/src/com/netscape/cms/policy/constraints/KeyAlgorithmConstraints.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.constraints;
-
import java.util.Enumeration;
import java.util.Locale;
import java.util.StringTokenizer;
@@ -37,43 +36,43 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
- * KeyAlgorithmConstraints enforces a constraint that the RA or a CA
- * honor only the keys generated using one of the permitted algorithms
- * such as RSA, DSA or DH.
+ * KeyAlgorithmConstraints enforces a constraint that the RA or a CA honor only
+ * the keys generated using one of the permitted algorithms such as RSA, DSA or
+ * DH.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public class KeyAlgorithmConstraints extends APolicyRule
- implements IEnrollmentPolicy, IExtendedPluginInfo {
+ implements IEnrollmentPolicy, IExtendedPluginInfo {
private Vector mAlgorithms;
private final static String DEF_KEY_ALGORITHM = "RSA,DSA";
private final static String PROP_ALGORITHMS = "algorithms";
private final static String[] supportedAlgorithms =
- {"RSA", "DSA", "DH" };
+ { "RSA", "DSA", "DH" };
private final static Vector defConfParams = new Vector();
static {
- defConfParams.addElement(PROP_ALGORITHMS + "=" +
- DEF_KEY_ALGORITHM);
+ defConfParams.addElement(PROP_ALGORITHMS + "=" +
+ DEF_KEY_ALGORITHM);
}
public String[] getExtendedPluginInfo(Locale locale) {
String params[] = {
"algorithms;choice(RSA\\,DSA,RSA,DSA);Certificate's key can be one of these algorithms",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-keyalgorithmconstraints",
+ ";configuration-policyrules-keyalgorithmconstraints",
IExtendedPluginInfo.HELP_TEXT +
- ";Rejects the request if the key in the certificate is " +
- "not of the type specified"
+ ";Rejects the request if the key in the certificate is " +
+ "not of the type specified"
};
return params;
@@ -87,17 +86,17 @@ public class KeyAlgorithmConstraints extends APolicyRule
/**
* Initializes this policy rule.
* <P>
- *
+ *
* The entries probably are of the form
- * ra.Policy.rule.<ruleName>.implName=KeyAlgorithmConstraints
- * ra.Policy.rule.<ruleName>.algorithms=RSA,DSA
- * ra.Policy.rule.<ruleName>.enable=true
- * ra.Policy.rule.<ruleName>.predicate=ou==Sales
- *
- * @param config The config store reference
+ * ra.Policy.rule.<ruleName>.implName=KeyAlgorithmConstraints
+ * ra.Policy.rule.<ruleName>.algorithms=RSA,DSA
+ * ra.Policy.rule.<ruleName>.enable=true
+ * ra.Policy.rule.<ruleName>.predicate=ou==Sales
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EPolicyException {
+ throws EPolicyException {
mAlgorithms = new Vector();
@@ -112,7 +111,7 @@ public class KeyAlgorithmConstraints extends APolicyRule
try {
algNames = config.getString(PROP_ALGORITHMS, null);
} catch (Exception e) {
- String[] params = {getInstanceName(), e.toString()};
+ String[] params = { getInstanceName(), e.toString() };
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_INVALID_POLICY_CONFIG", params));
@@ -133,11 +132,10 @@ public class KeyAlgorithmConstraints extends APolicyRule
}
// Check if configured algorithms are supported.
- for (Enumeration e = mAlgorithms.elements();
- e.hasMoreElements();) {
+ for (Enumeration e = mAlgorithms.elements(); e.hasMoreElements();) {
int i;
String configuredAlg = (String) e.nextElement();
-
+
// See if it is a supported algorithm.
for (i = 0; i < supportedAlgorithms.length; i++) {
if (configuredAlg.equals(supportedAlgorithms[i]))
@@ -148,15 +146,15 @@ public class KeyAlgorithmConstraints extends APolicyRule
if (i == supportedAlgorithms.length)
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_UNSUPPORTED_KEY_ALG",
- getInstanceName(), configuredAlg));
+ getInstanceName(), configuredAlg));
}
}
/**
* Applies the policy on the given Request.
* <P>
- *
- * @param req The request on which to apply policy.
+ *
+ * @param req The request on which to apply policy.
* @return The policy result object.
*/
public PolicyResult apply(IRequest req) {
@@ -166,7 +164,7 @@ public class KeyAlgorithmConstraints extends APolicyRule
try {
// Get the certificate info from the request
// X509CertInfo certInfo[] = (X509CertInfo[])
- // req.get(IRequest.CERT_INFO);
+ // req.get(IRequest.CERT_INFO);
X509CertInfo certInfo[] = req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
// We need to have a certificate info set
@@ -179,18 +177,18 @@ public class KeyAlgorithmConstraints extends APolicyRule
// Else check if the key algorithm is supported.
for (int i = 0; i < certInfo.length; i++) {
CertificateX509Key certKey = (CertificateX509Key)
- certInfo[i].get(X509CertInfo.KEY);
+ certInfo[i].get(X509CertInfo.KEY);
X509Key key = (X509Key) certKey.get(CertificateX509Key.KEY);
String alg = key.getAlgorithmId().getName().toUpperCase();
if (!mAlgorithms.contains(alg)) {
- setError(req, CMS.getUserMessage("CMS_POLICY_KEY_ALG_VIOLATION",
+ setError(req, CMS.getUserMessage("CMS_POLICY_KEY_ALG_VIOLATION",
getInstanceName(), alg), "");
result = PolicyResult.REJECTED;
}
}
} catch (Exception e) {
- String params[] = {getInstanceName(), e.toString()};
+ String params[] = { getInstanceName(), e.toString() };
setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR",
params), "");
@@ -201,10 +199,10 @@ public class KeyAlgorithmConstraints extends APolicyRule
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector getInstanceParams() {
+ public Vector getInstanceParams() {
Vector v = new Vector();
StringBuffer sb = new StringBuffer();
@@ -217,14 +215,13 @@ public class KeyAlgorithmConstraints extends APolicyRule
v.addElement(PROP_ALGORITHMS + "=" + sb.toString());
return v;
}
-
+
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
public Vector getDefaultParams() {
return defConfParams;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/policy/constraints/ManualAuthentication.java b/pki/base/common/src/com/netscape/cms/policy/constraints/ManualAuthentication.java
index a2bf9437..8526c77b 100644
--- a/pki/base/common/src/com/netscape/cms/policy/constraints/ManualAuthentication.java
+++ b/pki/base/common/src/com/netscape/cms/policy/constraints/ManualAuthentication.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.constraints;
-
import java.util.Vector;
import com.netscape.certsrv.authentication.IAuthToken;
@@ -29,23 +28,22 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
- * ManualAuthentication is an enrollment policy that queues
- * all requests for issuing agent's approval if no authentication
- * is present. The policy rejects a request if any of the auth tokens
- * indicates authentication failure.
+ * ManualAuthentication is an enrollment policy that queues all requests for
+ * issuing agent's approval if no authentication is present. The policy rejects
+ * a request if any of the auth tokens indicates authentication failure.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public class ManualAuthentication extends APolicyRule
- implements IEnrollmentPolicy {
+ implements IEnrollmentPolicy {
public ManualAuthentication() {
NAME = "ManualAuthentication";
DESC = "Manual Authentication Policy";
@@ -54,30 +52,31 @@ public class ManualAuthentication extends APolicyRule
/**
* Initializes this policy rule.
* <P>
- *
+ *
* The entries may be of the form:
- *
- * ra.Policy.rule.<ruleName>.implName=ManualAuthentication
- * ra.Policy.rule.<ruleName>.enable=true
- * ra.Policy.rule.<ruleName>.predicate= ou == engineering AND o == netscape.com
- *
- * @param config The config store reference
+ *
+ * ra.Policy.rule.<ruleName>.implName=ManualAuthentication
+ * ra.Policy.rule.<ruleName>.enable=true
+ * ra.Policy.rule.<ruleName>.predicate= ou == engineering AND o ==
+ * netscape.com
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EPolicyException {
+ throws EPolicyException {
}
/**
* Applies the policy on the given Request.
* <P>
- *
- * @param req The request on which to apply policy.
+ *
+ * @param req The request on which to apply policy.
* @return The policy result object.
*/
public PolicyResult apply(IRequest req) {
IAuthToken authToken = req.getExtDataInAuthToken(IRequest.AUTH_TOKEN);
- if (authToken == null)
+ if (authToken == null)
return deferred(req);
return PolicyResult.ACCEPTED;
@@ -85,7 +84,7 @@ public class ManualAuthentication extends APolicyRule
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
public Vector getInstanceParams() {
@@ -94,11 +93,10 @@ public class ManualAuthentication extends APolicyRule
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
public Vector getDefaultParams() {
return null;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/policy/constraints/RSAKeyConstraints.java b/pki/base/common/src/com/netscape/cms/policy/constraints/RSAKeyConstraints.java
index 7f7537bf..ccfa3ec0 100644
--- a/pki/base/common/src/com/netscape/cms/policy/constraints/RSAKeyConstraints.java
+++ b/pki/base/common/src/com/netscape/cms/policy/constraints/RSAKeyConstraints.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.constraints;
-
import java.util.Enumeration;
import java.util.Locale;
import java.util.StringTokenizer;
@@ -41,21 +40,21 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
- * RSAKeyConstraints policy enforces min and max size of the key.
- * Optionally checks the exponents.
+ * RSAKeyConstraints policy enforces min and max size of the key. Optionally
+ * checks the exponents.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public class RSAKeyConstraints extends APolicyRule
- implements IEnrollmentPolicy, IExtendedPluginInfo {
+ implements IEnrollmentPolicy, IExtendedPluginInfo {
private Vector mExponents;
private int mMinSize;
private int mMaxSize;
@@ -81,10 +80,10 @@ public class RSAKeyConstraints extends APolicyRule
PROP_MAX_SIZE + ";number;Maximum size of user's RSA key (bits)",
PROP_EXPONENTS + ";string;Comma-separated list of permissible exponents",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-rsakeyconstraints",
+ ";configuration-policyrules-rsakeyconstraints",
IExtendedPluginInfo.HELP_TEXT +
- ";Reject request if RSA key length is not within the " +
- "specified constraints"
+ ";Reject request if RSA key length is not within the " +
+ "specified constraints"
};
return params;
@@ -98,38 +97,38 @@ public class RSAKeyConstraints extends APolicyRule
/**
* Initializes this policy rule.
* <P>
- *
+ *
* The entries probably are of the form:
- *
- * ra.Policy.rule.<ruleName>.implName=RSAKeyConstraints
- * ra.Policy.rule.<ruleName>.enable=true
- * ra.Policy.rule.<ruleName>.minSize=512
- * ra.Policy.rule.<ruleName>.maxSize=2048
- * ra.Policy.rule.<ruleName>.predicate=ou==Marketing
- *
- * @param config The config store reference
+ *
+ * ra.Policy.rule.<ruleName>.implName=RSAKeyConstraints
+ * ra.Policy.rule.<ruleName>.enable=true
+ * ra.Policy.rule.<ruleName>.minSize=512
+ * ra.Policy.rule.<ruleName>.maxSize=2048
+ * ra.Policy.rule.<ruleName>.predicate=ou==Marketing
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
if (config == null || config.size() == 0)
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_MISSING_POLICY_CONFIG",
- getInstanceName()));
+ getInstanceName()));
String exponents = null;
// Get Min and Max sizes
mMinSize = config.getInteger(PROP_MIN_SIZE, DEF_MIN_SIZE);
mMaxSize = config.getInteger(PROP_MAX_SIZE, DEF_MAX_SIZE);
- if (mMinSize <= 0)
+ if (mMinSize <= 0)
throw new EBaseException(
CMS.getUserMessage("CMS_BASE_MUST_BE_POSITIVE_NUMBER", PROP_MIN_SIZE));
- if (mMaxSize <= 0)
+ if (mMaxSize <= 0)
throw new EBaseException(
CMS.getUserMessage("CMS_BASE_MUST_BE_POSITIVE_NUMBER", PROP_MAX_SIZE));
- if (mMinSize > mMaxSize)
+ if (mMinSize > mMaxSize)
throw new EBaseException(
CMS.getUserMessage("CMS_BASE_A_GREATER_THAN_EQUAL_B", PROP_MIN_SIZE, PROP_MAX_SIZE));
@@ -149,8 +148,8 @@ public class RSAKeyConstraints extends APolicyRule
}
} catch (Exception e) {
// e.printStackTrace();
- String[] params = {getInstanceName(), exponents,
- PROP_EXPONENTS};
+ String[] params = { getInstanceName(), exponents,
+ PROP_EXPONENTS };
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_INVALID_CONFIG_PARAM", params));
@@ -161,8 +160,8 @@ public class RSAKeyConstraints extends APolicyRule
/**
* Applies the policy on the given Request.
* <P>
- *
- * @param req The request on which to apply policy.
+ *
+ * @param req The request on which to apply policy.
* @return The policy result object.
*/
public PolicyResult apply(IRequest req) {
@@ -172,11 +171,11 @@ public class RSAKeyConstraints extends APolicyRule
try {
// Get the certificate info from the request
X509CertInfo certInfo[] =
- req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
+ req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
// There should be a certificate info set.
if (certInfo == null) {
- setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO",
+ setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO",
getInstanceName()), "");
return PolicyResult.REJECTED;
}
@@ -184,7 +183,7 @@ public class RSAKeyConstraints extends APolicyRule
// Else check if the key size(s) are within the limit.
for (int i = 0; i < certInfo.length; i++) {
CertificateX509Key certKey = (CertificateX509Key)
- certInfo[i].get(X509CertInfo.KEY);
+ certInfo[i].get(X509CertInfo.KEY);
X509Key key = (X509Key) certKey.get(CertificateX509Key.KEY);
String alg = key.getAlgorithmId().toString();
@@ -196,22 +195,22 @@ public class RSAKeyConstraints extends APolicyRule
newkey = new X509Key(AlgorithmId.get("RSA"),
key.getKey());
} catch (Exception e) {
- CMS.debug( "RSAKeyConstraints::apply() - "
- + "Exception="+e.toString() );
- setError( req,
- CMS.getUserMessage( "CMS_POLICY_KEY_SIZE_VIOLATION",
- getInstanceName() ),
- "" );
+ CMS.debug("RSAKeyConstraints::apply() - "
+ + "Exception=" + e.toString());
+ setError(req,
+ CMS.getUserMessage("CMS_POLICY_KEY_SIZE_VIOLATION",
+ getInstanceName()),
+ "");
return PolicyResult.REJECTED;
}
RSAPublicKey rsaKey = new RSAPublicKey(newkey.getEncoded());
int keySize = rsaKey.getKeySize();
if (keySize < mMinSize || keySize > mMaxSize) {
- String[] params = {getInstanceName(),
- String.valueOf(keySize),
+ String[] params = { getInstanceName(),
+ String.valueOf(keySize),
String.valueOf(mMinSize),
- String.valueOf(mMaxSize)};
+ String.valueOf(mMaxSize) };
setError(req, CMS.getUserMessage("CMS_POLICY_KEY_SIZE_VIOLATION",
params), "");
@@ -226,15 +225,14 @@ public class RSAKeyConstraints extends APolicyRule
if (!mExponents.contains(exp)) {
StringBuffer sb = new StringBuffer();
- for (Enumeration e = mExponents.elements();
- e.hasMoreElements();) {
+ for (Enumeration e = mExponents.elements(); e.hasMoreElements();) {
BigInt bi = (BigInt) e.nextElement();
sb.append(bi.toBigInteger().toString());
sb.append(" ");
}
- String[] params = {getInstanceName(),
- exp.toBigInteger().toString(), new String(sb)};
+ String[] params = { getInstanceName(),
+ exp.toBigInteger().toString(), new String(sb) };
setError(req, CMS.getUserMessage("CMS_POLICY_EXPONENT_VIOLATION", params), "");
result = PolicyResult.REJECTED;
@@ -243,7 +241,7 @@ public class RSAKeyConstraints extends APolicyRule
}
} catch (Exception e) {
// e.printStackTrace();
- String params[] = {getInstanceName(), e.toString()};
+ String params[] = { getInstanceName(), e.toString() };
setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR", params), "");
result = PolicyResult.REJECTED;
@@ -253,10 +251,10 @@ public class RSAKeyConstraints extends APolicyRule
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector getInstanceParams() {
+ public Vector getInstanceParams() {
Vector confParams = new Vector();
confParams.addElement(PROP_MIN_SIZE + "=" + mMinSize);
@@ -275,11 +273,10 @@ public class RSAKeyConstraints extends APolicyRule
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
public Vector getDefaultParams() {
return defConfParams;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/policy/constraints/RenewalConstraints.java b/pki/base/common/src/com/netscape/cms/policy/constraints/RenewalConstraints.java
index 08e479b8..763c7713 100644
--- a/pki/base/common/src/com/netscape/cms/policy/constraints/RenewalConstraints.java
+++ b/pki/base/common/src/com/netscape/cms/policy/constraints/RenewalConstraints.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.constraints;
-
import java.util.Date;
import java.util.Locale;
import java.util.Vector;
@@ -37,21 +36,22 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
* Whether to allow renewal of an expired cert.
+ *
* @version $Revision$, $Date$
- * <P>
- * <PRE>
+ * <P>
+ *
+ * <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
- * <P>
- *
+ * <P>
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public class RenewalConstraints extends APolicyRule
- implements IRenewalPolicy, IExtendedPluginInfo {
+ implements IRenewalPolicy, IExtendedPluginInfo {
private static final String PROP_ALLOW_EXPIRED_CERTS = "allowExpiredCerts";
private static final String PROP_RENEWAL_NOT_AFTER = "renewalNotAfter";
@@ -66,7 +66,7 @@ public class RenewalConstraints extends APolicyRule
static {
defConfParams.addElement(PROP_ALLOW_EXPIRED_CERTS + "=" + true);
defConfParams.addElement(PROP_RENEWAL_NOT_AFTER + "=" +
- DEF_RENEWAL_NOT_AFTER);
+ DEF_RENEWAL_NOT_AFTER);
}
public RenewalConstraints() {
@@ -79,10 +79,10 @@ public class RenewalConstraints extends APolicyRule
PROP_ALLOW_EXPIRED_CERTS + ";boolean;Allow a user to renew an already-expired certificate",
PROP_RENEWAL_NOT_AFTER + ";number;Number of days since certificate expiry after which renewal request would be rejected",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-renewalconstraints",
+ ";configuration-policyrules-renewalconstraints",
IExtendedPluginInfo.HELP_TEXT +
- ";Permit administrator to decide policy on whether to " +
- "permit renewals for already-expired certificates"
+ ";Permit administrator to decide policy on whether to " +
+ "permit renewals for already-expired certificates"
};
return params;
@@ -92,24 +92,24 @@ public class RenewalConstraints extends APolicyRule
/**
* Initializes this policy rule.
* <P>
- *
+ *
* The entries probably are of the form:
- *
- * ra.Policy.rule.<ruleName>.implName=ValidityConstraints
- * ra.Policy.rule.<ruleName>.enable=true
- * ra.Policy.rule.<ruleName>.allowExpiredCerts=true
- *
- * @param config The config store reference
+ *
+ * ra.Policy.rule.<ruleName>.implName=ValidityConstraints
+ * ra.Policy.rule.<ruleName>.enable=true
+ * ra.Policy.rule.<ruleName>.allowExpiredCerts=true
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EPolicyException {
+ throws EPolicyException {
// Get min and max validity in days and configure them.
try {
- mAllowExpiredCerts =
+ mAllowExpiredCerts =
config.getBoolean(PROP_ALLOW_EXPIRED_CERTS, true);
String val = config.getString(PROP_RENEWAL_NOT_AFTER, null);
- if (val == null)
+ if (val == null)
mRenewalNotAfter = DEF_RENEWAL_NOT_AFTER * DAYS_TO_MS_FACTOR;
else {
mRenewalNotAfter = Long.parseLong(val) * DAYS_TO_MS_FACTOR;
@@ -125,8 +125,8 @@ public class RenewalConstraints extends APolicyRule
/**
* Applies the policy on the given Request.
* <P>
- *
- * @param req The request on which to apply policy.
+ *
+ * @param req The request on which to apply policy.
* @return The policy result object.
*/
public PolicyResult apply(IRequest req) {
@@ -135,25 +135,26 @@ public class RenewalConstraints extends APolicyRule
try {
// Get the certificates being renwed.
X509CertImpl[] oldCerts =
- req.getExtDataInCertArray(IRequest.OLD_CERTS);
+ req.getExtDataInCertArray(IRequest.OLD_CERTS);
if (oldCerts == null) {
setError(req, CMS.getUserMessage("CMS_POLICY_NO_OLD_CERT",
getInstanceName()), "");
return PolicyResult.REJECTED;
}
-
+
if (mAllowExpiredCerts) {
CMS.debug("checking validity of each cert");
- // check if each cert to be renewed is expired for more than // allowed days.
+ // check if each cert to be renewed is expired for more than //
+ // allowed days.
for (int i = 0; i < oldCerts.length; i++) {
X509CertInfo oldCertInfo = (X509CertInfo)
- oldCerts[i].get(X509CertImpl.NAME + "." +
- X509CertImpl.INFO);
- CertificateValidity oldValidity = (CertificateValidity)
- oldCertInfo.get(X509CertInfo.VALIDITY);
+ oldCerts[i].get(X509CertImpl.NAME + "." +
+ X509CertImpl.INFO);
+ CertificateValidity oldValidity = (CertificateValidity)
+ oldCertInfo.get(X509CertInfo.VALIDITY);
Date notAfter = (Date)
- oldValidity.get(CertificateValidity.NOT_AFTER);
+ oldValidity.get(CertificateValidity.NOT_AFTER);
// Is the Certificate eligible for renewal ?
@@ -166,12 +167,12 @@ public class RenewalConstraints extends APolicyRule
if (renewedNotAfter.before(now)) {
CMS.debug(
- "One or more certificates is expired for more than " + (mRenewalNotAfter / DAYS_TO_MS_FACTOR) + " days");
+ "One or more certificates is expired for more than " + (mRenewalNotAfter / DAYS_TO_MS_FACTOR) + " days");
String params[] = { getInstanceName(), Long.toString(mRenewalNotAfter / DAYS_TO_MS_FACTOR) };
- setError(req,
- CMS.getUserMessage("CMS_POLICY_CANNOT_RENEW_EXPIRED_CERTS_AFTER_ALLOWED_PERIOD",
- params), "");
+ setError(req,
+ CMS.getUserMessage("CMS_POLICY_CANNOT_RENEW_EXPIRED_CERTS_AFTER_ALLOWED_PERIOD",
+ params), "");
return PolicyResult.REJECTED;
}
}
@@ -182,12 +183,12 @@ public class RenewalConstraints extends APolicyRule
// check if each cert to be renewed is expired.
for (int i = 0; i < oldCerts.length; i++) {
X509CertInfo oldCertInfo = (X509CertInfo)
- oldCerts[i].get(
- X509CertImpl.NAME + "." + X509CertImpl.INFO);
- CertificateValidity oldValidity = (CertificateValidity)
- oldCertInfo.get(X509CertInfo.VALIDITY);
+ oldCerts[i].get(
+ X509CertImpl.NAME + "." + X509CertImpl.INFO);
+ CertificateValidity oldValidity = (CertificateValidity)
+ oldCertInfo.get(X509CertInfo.VALIDITY);
Date notAfter = (Date)
- oldValidity.get(CertificateValidity.NOT_AFTER);
+ oldValidity.get(CertificateValidity.NOT_AFTER);
// Is the Certificate still valid?
Date now = CMS.getCurrentDate();
@@ -195,19 +196,19 @@ public class RenewalConstraints extends APolicyRule
CMS.debug("RenewalConstraints: cert " + i + " notAfter " + notAfter + " now=" + now);
if (notAfter.before(now)) {
CMS.debug(
- "RenewalConstraints: One or more certificates is expired.");
+ "RenewalConstraints: One or more certificates is expired.");
String params[] = { getInstanceName() };
- setError(req,
- CMS.getUserMessage("CMS_POLICY_CANNOT_RENEW_EXPIRED_CERTS",
- params), "");
+ setError(req,
+ CMS.getUserMessage("CMS_POLICY_CANNOT_RENEW_EXPIRED_CERTS",
+ params), "");
result = PolicyResult.REJECTED;
break;
}
}
} catch (Exception e) {
- String params[] = {getInstanceName(), e.toString()};
+ String params[] = { getInstanceName(), e.toString() };
setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR", params), "");
result = PolicyResult.REJECTED;
@@ -217,22 +218,22 @@ public class RenewalConstraints extends APolicyRule
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
public Vector getInstanceParams() {
Vector confParams = new Vector();
confParams.addElement(
- PROP_ALLOW_EXPIRED_CERTS + "=" + mAllowExpiredCerts);
+ PROP_ALLOW_EXPIRED_CERTS + "=" + mAllowExpiredCerts);
confParams.addElement(PROP_RENEWAL_NOT_AFTER + "=" +
- mRenewalNotAfter / DAYS_TO_MS_FACTOR);
+ mRenewalNotAfter / DAYS_TO_MS_FACTOR);
return confParams;
}
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
public Vector getDefaultParams() {
diff --git a/pki/base/common/src/com/netscape/cms/policy/constraints/RenewalValidityConstraints.java b/pki/base/common/src/com/netscape/cms/policy/constraints/RenewalValidityConstraints.java
index 3d98f3c2..b4131ea9 100644
--- a/pki/base/common/src/com/netscape/cms/policy/constraints/RenewalValidityConstraints.java
+++ b/pki/base/common/src/com/netscape/cms/policy/constraints/RenewalValidityConstraints.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.constraints;
-
import java.util.Date;
import java.util.Locale;
import java.util.Vector;
@@ -36,30 +35,29 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
- * RenewalValidityConstraints is a default rule for Certificate
- * Renewal. This policy enforces the no of days before which a
- * currently active certificate can be renewed and sets new validity
- * period for the renewed certificate starting from the the ending
- * period in the old certificate.
- *
+ * RenewalValidityConstraints is a default rule for Certificate Renewal. This
+ * policy enforces the no of days before which a currently active certificate
+ * can be renewed and sets new validity period for the renewed certificate
+ * starting from the the ending period in the old certificate.
+ *
* The main parameters are:
- *
- * The renewal leadtime in days: - i.e how many days before the
- * expiry of the current certificate can one request the renewal.
- * min and max validity duration.
+ *
+ * The renewal leadtime in days: - i.e how many days before the expiry of the
+ * current certificate can one request the renewal. min and max validity
+ * duration.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public class RenewalValidityConstraints extends APolicyRule
- implements IRenewalPolicy, IExtendedPluginInfo {
+ implements IRenewalPolicy, IExtendedPluginInfo {
private long mMinValidity;
private long mMaxValidity;
private long mRenewalInterval;
@@ -78,11 +76,11 @@ public class RenewalValidityConstraints extends APolicyRule
static {
defConfParams.addElement(PROP_MIN_VALIDITY + "=" +
- DEF_MIN_VALIDITY);
+ DEF_MIN_VALIDITY);
defConfParams.addElement(PROP_MAX_VALIDITY + "=" +
- DEF_MAX_VALIDITY);
+ DEF_MAX_VALIDITY);
defConfParams.addElement(PROP_RENEWAL_INTERVAL + "=" +
- DEF_RENEWAL_INTERVAL);
+ DEF_RENEWAL_INTERVAL);
}
public String[] getExtendedPluginInfo(Locale locale) {
@@ -91,10 +89,10 @@ public class RenewalValidityConstraints extends APolicyRule
PROP_MAX_VALIDITY + ";number;Specifies the maximum validity period, in days, for renewed certificates.",
PROP_RENEWAL_INTERVAL + ";number;Specifies how many days before its expiration that a certificate can be renewed.",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-renewalvalidityconstraints",
+ ";configuration-policyrules-renewalvalidityconstraints",
IExtendedPluginInfo.HELP_TEXT +
- ";Reject renewal request if the certificate is too far " +
- "before it's expiry date"
+ ";Reject renewal request if the certificate is too far " +
+ "before it's expiry date"
};
return params;
@@ -109,20 +107,20 @@ public class RenewalValidityConstraints extends APolicyRule
/**
* Initializes this policy rule.
* <P>
- *
+ *
* The entries probably are of the form:
- *
- * ra.Policy.rule.<ruleName>.implName=ValidityConstraints
- * ra.Policy.rule.<ruleName>.enable=true
- * ra.Policy.rule.<ruleName>.minValidity=30
- * ra.Policy.rule.<ruleName>.maxValidity=180
- * ra.Policy.rule.<ruleName>.renewalInterval=15
- * ra.Policy.rule.<ruleName>.predicate=ou==Sales
- *
- * @param config The config store reference
+ *
+ * ra.Policy.rule.<ruleName>.implName=ValidityConstraints
+ * ra.Policy.rule.<ruleName>.enable=true
+ * ra.Policy.rule.<ruleName>.minValidity=30
+ * ra.Policy.rule.<ruleName>.maxValidity=180
+ * ra.Policy.rule.<ruleName>.renewalInterval=15
+ * ra.Policy.rule.<ruleName>.predicate=ou==Sales
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EPolicyException {
+ throws EPolicyException {
// Get min and max validity in days and onfigure them.
try {
@@ -148,7 +146,7 @@ public class RenewalValidityConstraints extends APolicyRule
// minValidity can't be bigger than maxValidity.
if (mMinValidity > mMaxValidity) {
- String params[] = {getInstanceName(),
+ String params[] = { getInstanceName(),
String.valueOf(mMinValidity / DAYS_TO_MS_FACTOR),
String.valueOf(mMaxValidity / DAYS_TO_MS_FACTOR) };
@@ -158,7 +156,7 @@ public class RenewalValidityConstraints extends APolicyRule
// Renewal interval can't be more than maxValidity.
if (mRenewalInterval > mMaxValidity) {
- String params[] = {getInstanceName(),
+ String params[] = { getInstanceName(),
String.valueOf(mRenewalInterval / DAYS_TO_MS_FACTOR),
String.valueOf(mMaxValidity / DAYS_TO_MS_FACTOR) };
@@ -167,7 +165,7 @@ public class RenewalValidityConstraints extends APolicyRule
}
} catch (Exception e) {
// e.printStackTrace();
- String[] params = {getInstanceName(), e.toString()};
+ String[] params = { getInstanceName(), e.toString() };
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_INVALID_POLICY_CONFIG", params));
@@ -177,8 +175,8 @@ public class RenewalValidityConstraints extends APolicyRule
/**
* Applies the policy on the given Request.
* <P>
- *
- * @param req The request on which to apply policy.
+ *
+ * @param req The request on which to apply policy.
* @return The policy result object.
*/
public PolicyResult apply(IRequest req) {
@@ -191,15 +189,15 @@ public class RenewalValidityConstraints extends APolicyRule
try {
// Get the certificate info from the request
X509CertInfo certInfo[] =
- req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
+ req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
// Get the certificates being renwed.
X509CertImpl currentCerts[] =
- req.getExtDataInCertArray(IRequest.OLD_CERTS);
+ req.getExtDataInCertArray(IRequest.OLD_CERTS);
// Both certificate info and current certs should be set
if (certInfo == null) {
- setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO",
+ setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO",
getInstanceName()), "");
return PolicyResult.REJECTED;
}
@@ -218,12 +216,12 @@ public class RenewalValidityConstraints extends APolicyRule
// set the validity.
for (int i = 0; i < certInfo.length; i++) {
X509CertInfo oldCertInfo = (X509CertInfo)
- currentCerts[i].get(X509CertImpl.NAME +
- "." + X509CertImpl.INFO);
- CertificateValidity oldValidity = (CertificateValidity)
- oldCertInfo.get(X509CertInfo.VALIDITY);
+ currentCerts[i].get(X509CertImpl.NAME +
+ "." + X509CertImpl.INFO);
+ CertificateValidity oldValidity = (CertificateValidity)
+ oldCertInfo.get(X509CertInfo.VALIDITY);
Date notAfter = (Date)
- oldValidity.get(CertificateValidity.NOT_AFTER);
+ oldValidity.get(CertificateValidity.NOT_AFTER);
// Is the Certificate still valid?
Date now = CMS.getCurrentDate();
@@ -233,14 +231,14 @@ public class RenewalValidityConstraints extends APolicyRule
long interval = notAfter.getTime() - now.getTime();
if (interval > mRenewalInterval) {
- setError(req,
- CMS.getUserMessage("CMS_POLICY_LONG_RENEWAL_LEAD_TIME",
- getInstanceName(),
- String.valueOf(mRenewalInterval / DAYS_TO_MS_FACTOR)), "");
- setError(req,
- CMS.getUserMessage("CMS_POLICY_EXISTING_CERT_DETAILS",
- getInstanceName(),
- getCertDetails(req, currentCerts[i])), "");
+ setError(req,
+ CMS.getUserMessage("CMS_POLICY_LONG_RENEWAL_LEAD_TIME",
+ getInstanceName(),
+ String.valueOf(mRenewalInterval / DAYS_TO_MS_FACTOR)), "");
+ setError(req,
+ CMS.getUserMessage("CMS_POLICY_EXISTING_CERT_DETAILS",
+ getInstanceName(),
+ getCertDetails(req, currentCerts[i])), "");
result = PolicyResult.REJECTED;
setDummyValidity(certInfo[i]);
@@ -248,27 +246,27 @@ public class RenewalValidityConstraints extends APolicyRule
}
}
- // Else compute new validity.
+ // Else compute new validity.
Date renewedNotBef = notAfter;
Date renewedNotAfter = new Date(notAfter.getTime() +
mMaxValidity);
- // If the new notAfter is within renewal interval days from
+ // If the new notAfter is within renewal interval days from
// today or already expired, set the notBefore to today.
if (renewedNotAfter.before(now) ||
- (renewedNotAfter.getTime() - now.getTime()) <=
- mRenewalInterval) {
+ (renewedNotAfter.getTime() - now.getTime()) <=
+ mRenewalInterval) {
renewedNotBef = now;
renewedNotAfter = new Date(now.getTime() +
mMaxValidity);
}
CertificateValidity newValidity =
- new CertificateValidity(renewedNotBef, renewedNotAfter);
+ new CertificateValidity(renewedNotBef, renewedNotAfter);
certInfo[i].set(X509CertInfo.VALIDITY, newValidity);
}
} catch (Exception e) {
- String params[] = {getInstanceName(), e.toString()};
+ String params[] = { getInstanceName(), e.toString() };
setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR", params), "");
result = PolicyResult.REJECTED;
@@ -278,24 +276,24 @@ public class RenewalValidityConstraints extends APolicyRule
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
public Vector getInstanceParams() {
Vector confParams = new Vector();
confParams.addElement(PROP_MIN_VALIDITY + "=" +
- mMinValidity / DAYS_TO_MS_FACTOR);
+ mMinValidity / DAYS_TO_MS_FACTOR);
confParams.addElement(PROP_MAX_VALIDITY + "=" +
- mMaxValidity / DAYS_TO_MS_FACTOR);
+ mMaxValidity / DAYS_TO_MS_FACTOR);
confParams.addElement(PROP_RENEWAL_INTERVAL + "=" +
- mRenewalInterval / DAYS_TO_MS_FACTOR);
+ mRenewalInterval / DAYS_TO_MS_FACTOR);
return confParams;
}
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
public Vector getDefaultParams() {
@@ -306,7 +304,7 @@ public class RenewalValidityConstraints extends APolicyRule
private void setDummyValidity(X509CertInfo certInfo) {
try {
certInfo.set(X509CertInfo.VALIDITY,
- new CertificateValidity(CMS.getCurrentDate(), new Date()));
+ new CertificateValidity(CMS.getCurrentDate(), new Date()));
} catch (Exception e) {
}
}
@@ -317,8 +315,8 @@ public class RenewalValidityConstraints extends APolicyRule
sb.append("\n");
sb.append("Serial No: " + cert.getSerialNumber().toString(16));
sb.append("\n");
- sb.append("Validity: " + cert.getNotBefore().toString() +
- " - " + cert.getNotAfter().toString());
+ sb.append("Validity: " + cert.getNotBefore().toString() +
+ " - " + cert.getNotAfter().toString());
sb.append("\n");
String certType = req.getExtDataInString(IRequest.CERT_TYPE);
@@ -326,11 +324,12 @@ public class RenewalValidityConstraints extends APolicyRule
certType = IRequest.SERVER_CERT;
if (certType.equals(IRequest.CLIENT_CERT)) {
- /*** Take this our - URL formulation hard to do here.
- sb.append("Use the following url with your CA/RA gateway spec to download the certificate.");
- sb.append("\n");
- sb.append("/query/certImport?op=displayByserial&serialNumber=");
- sb.append(cert.getSerialNumber().toString(16));
+ /***
+ * Take this our - URL formulation hard to do here. sb.append(
+ * "Use the following url with your CA/RA gateway spec to download the certificate."
+ * ); sb.append("\n");
+ * sb.append("/query/certImport?op=displayByserial&serialNumber=");
+ * sb.append(cert.getSerialNumber().toString(16));
***/
sb.append("\n");
} else {
@@ -342,7 +341,7 @@ public class RenewalValidityConstraints extends APolicyRule
sb.append(CERT_HEADER + encodedCert + CERT_TRAILER);
} catch (Exception e) {
- //throw new AssertionException(e.toString());
+ // throw new AssertionException(e.toString());
}
}
return sb.toString();
diff --git a/pki/base/common/src/com/netscape/cms/policy/constraints/RevocationConstraints.java b/pki/base/common/src/com/netscape/cms/policy/constraints/RevocationConstraints.java
index 686529f4..046ebd35 100644
--- a/pki/base/common/src/com/netscape/cms/policy/constraints/RevocationConstraints.java
+++ b/pki/base/common/src/com/netscape/cms/policy/constraints/RevocationConstraints.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.constraints;
-
import java.util.Date;
import java.util.Locale;
import java.util.Vector;
@@ -38,20 +37,20 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
* Whether to allow revocation of an expired cert.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public class RevocationConstraints extends APolicyRule
- implements IRevocationPolicy, IExtendedPluginInfo {
+ implements IRevocationPolicy, IExtendedPluginInfo {
private static final String PROP_ALLOW_EXPIRED_CERTS = "allowExpiredCerts";
private static final String PROP_ALLOW_ON_HOLD = "allowOnHold";
@@ -74,13 +73,13 @@ public class RevocationConstraints extends APolicyRule
PROP_ALLOW_EXPIRED_CERTS + ";boolean;Allow a user to revoke an already-expired certificate",
PROP_ALLOW_ON_HOLD + ";boolean;Allow a user to set reason to On-Hold",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-revocationconstraints",
+ ";configuration-policyrules-revocationconstraints",
IExtendedPluginInfo.HELP_TEXT +
- ";Allow administrator to decide policy on whether to allow " +
- "recovation of expired certificates" +
- "and set reason to On-Hold"
+ ";Allow administrator to decide policy on whether to allow " +
+ "recovation of expired certificates" +
+ "and set reason to On-Hold"
- };
+ };
return params;
@@ -89,20 +88,20 @@ public class RevocationConstraints extends APolicyRule
/**
* Initializes this policy rule.
* <P>
- *
+ *
* The entries probably are of the form:
- *
- * ra.Policy.rule.<ruleName>.implName=ValidityConstraints
- * ra.Policy.rule.<ruleName>.enable=true
- * ra.Policy.rule.<ruleName>.allowExpiredCerts=true
- *
- * @param config The config store reference
+ *
+ * ra.Policy.rule.<ruleName>.implName=ValidityConstraints
+ * ra.Policy.rule.<ruleName>.enable=true
+ * ra.Policy.rule.<ruleName>.allowExpiredCerts=true
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EPolicyException {
+ throws EPolicyException {
// Get min and max validity in days and onfigure them.
try {
- mAllowExpiredCerts =
+ mAllowExpiredCerts =
config.getBoolean(PROP_ALLOW_EXPIRED_CERTS, true);
mAllowOnHold =
config.getBoolean(PROP_ALLOW_ON_HOLD, true);
@@ -117,8 +116,8 @@ public class RevocationConstraints extends APolicyRule
/**
* Applies the policy on the given Request.
* <P>
- *
- * @param req The request on which to apply policy.
+ *
+ * @param req The request on which to apply policy.
* @return The policy result object.
*/
public PolicyResult apply(IRequest req) {
@@ -138,35 +137,35 @@ public class RevocationConstraints extends APolicyRule
setError(req, CMS.getUserMessage("CMS_POLICY_NO_ON_HOLD_ALLOWED", params), "");
return PolicyResult.REJECTED;
- }
+ }
}
if (mAllowExpiredCerts)
// nothing to check.
return PolicyResult.ACCEPTED;
-
+
PolicyResult result = PolicyResult.ACCEPTED;
try {
// Get the certificates being renwed.
X509CertImpl[] oldCerts =
- req.getExtDataInCertArray(IRequest.OLD_CERTS);
+ req.getExtDataInCertArray(IRequest.OLD_CERTS);
if (oldCerts == null) {
setError(req, CMS.getUserMessage("CMS_POLICY_NO_OLD_CERT"),
- getInstanceName());
+ getInstanceName());
return PolicyResult.REJECTED;
}
// check if each cert to be renewed is expired.
for (int i = 0; i < oldCerts.length; i++) {
X509CertInfo oldCertInfo = (X509CertInfo)
- oldCerts[i].get(
- X509CertImpl.NAME + "." + X509CertImpl.INFO);
- CertificateValidity oldValidity = (CertificateValidity)
- oldCertInfo.get(X509CertInfo.VALIDITY);
+ oldCerts[i].get(
+ X509CertImpl.NAME + "." + X509CertImpl.INFO);
+ CertificateValidity oldValidity = (CertificateValidity)
+ oldCertInfo.get(X509CertInfo.VALIDITY);
Date notAfter = (Date)
- oldValidity.get(CertificateValidity.NOT_AFTER);
+ oldValidity.get(CertificateValidity.NOT_AFTER);
// Is the Certificate still valid?
Date now = CMS.getCurrentDate();
@@ -174,16 +173,16 @@ public class RevocationConstraints extends APolicyRule
if (notAfter.before(now)) {
String params[] = { getInstanceName() };
- setError(req,
- CMS.getUserMessage("CMS_POLICY_CANNOT_REVOKE_EXPIRED_CERTS",
- params), "");
+ setError(req,
+ CMS.getUserMessage("CMS_POLICY_CANNOT_REVOKE_EXPIRED_CERTS",
+ params), "");
result = PolicyResult.REJECTED;
break;
}
}
} catch (Exception e) {
- String params[] = {getInstanceName(), e.toString()};
+ String params[] = { getInstanceName(), e.toString() };
setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR", params), "");
result = PolicyResult.REJECTED;
@@ -193,22 +192,22 @@ public class RevocationConstraints extends APolicyRule
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
public Vector getInstanceParams() {
Vector confParams = new Vector();
confParams.addElement(
- PROP_ALLOW_EXPIRED_CERTS + "=" + mAllowExpiredCerts);
+ PROP_ALLOW_EXPIRED_CERTS + "=" + mAllowExpiredCerts);
confParams.addElement(
- PROP_ALLOW_ON_HOLD + "=" + mAllowOnHold);
+ PROP_ALLOW_ON_HOLD + "=" + mAllowOnHold);
return confParams;
}
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
public Vector getDefaultParams() {
diff --git a/pki/base/common/src/com/netscape/cms/policy/constraints/SigningAlgorithmConstraints.java b/pki/base/common/src/com/netscape/cms/policy/constraints/SigningAlgorithmConstraints.java
index 9d519284..8f974aee 100644
--- a/pki/base/common/src/com/netscape/cms/policy/constraints/SigningAlgorithmConstraints.java
+++ b/pki/base/common/src/com/netscape/cms/policy/constraints/SigningAlgorithmConstraints.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.constraints;
-
import java.util.Locale;
import java.util.StringTokenizer;
import java.util.Vector;
@@ -41,23 +40,24 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
- * SigningAlgorithmConstraints enforces that only a supported
- * signing algorithm be requested.
+ * SigningAlgorithmConstraints enforces that only a supported signing algorithm
+ * be requested.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public class SigningAlgorithmConstraints extends APolicyRule
- implements IEnrollmentPolicy, IExtendedPluginInfo {
+ implements IEnrollmentPolicy, IExtendedPluginInfo {
private String[] mAllowedAlgs = null; // algs allowed by this policy
- static String[] mDefaultAllowedAlgs = null; // default algs allowed by this policy based on CA's key
+ static String[] mDefaultAllowedAlgs = null; // default algs allowed by this
+ // policy based on CA's key
private String[] mConfigAlgs = null; // algs listed in config file
private boolean winnowedByKey = false;
IAuthority mAuthority = null;
@@ -94,17 +94,17 @@ public class SigningAlgorithmConstraints extends APolicyRule
/**
* Initializes this policy rule.
* <P>
- *
+ *
* The entries probably are of the form
- * ra.Policy.rule.<ruleName>.implName=SigningAlgorithmConstraints
- * ra.Policy.rule.<ruleName>.algorithms=SHA-1WithRSA, SHA-1WithDSA
- * ra.Policy.rule.<ruleName>.enable=true
- * ra.Policy.rule.<ruleName>.predicate=ou==Sales
- *
- * @param config The config store reference
+ * ra.Policy.rule.<ruleName>.implName=SigningAlgorithmConstraints
+ * ra.Policy.rule.<ruleName>.algorithms=SHA-1WithRSA, SHA-1WithDSA
+ * ra.Policy.rule.<ruleName>.enable=true
+ * ra.Policy.rule.<ruleName>.predicate=ou==Sales
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mAuthority = (IAuthority) ((IPolicyProcessor) owner).getAuthority();
// Get allowed algorithms from config file
@@ -114,7 +114,7 @@ public class SigningAlgorithmConstraints extends APolicyRule
try {
algNames = config.getString(PROP_ALGORITHMS, null);
} catch (Exception e) {
- String[] params = {getInstanceName(), e.toString(), PROP_ALGORITHMS};
+ String[] params = { getInstanceName(), e.toString(), PROP_ALGORITHMS };
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_PARAM_CONFIG_ERROR", params));
@@ -136,7 +136,7 @@ public class SigningAlgorithmConstraints extends APolicyRule
for (int i = 0; i < itemCount; i++) {
mAllowedAlgs[i] = (String) algs.elementAt(i);
}
-
+
}
}
@@ -149,8 +149,8 @@ public class SigningAlgorithmConstraints extends APolicyRule
if (mAllowedAlgs != null) {
// winnow out unknown algorithms
- winnowAlgs(AlgorithmId.ALL_SIGNING_ALGORITHMS,
- "CMS_POLICY_UNKNOWN_SIGNING_ALG", true);
+ winnowAlgs(AlgorithmId.ALL_SIGNING_ALGORITHMS,
+ "CMS_POLICY_UNKNOWN_SIGNING_ALG", true);
} else {
// if nothing was in the config file, allow all known algs
mAllowedAlgs = AlgorithmId.ALL_SIGNING_ALGORITHMS;
@@ -183,19 +183,19 @@ public class SigningAlgorithmConstraints extends APolicyRule
// get list of algorithms allowed for the key
String[] allowedByKey =
- ((ICertAuthority) mAuthority).getCASigningAlgorithms();
+ ((ICertAuthority) mAuthority).getCASigningAlgorithms();
if (allowedByKey != null) {
- // don't show algorithms that don't match CA's key in UI.
+ // don't show algorithms that don't match CA's key in UI.
mDefaultAllowedAlgs = new String[allowedByKey.length];
for (int i = 0; i < allowedByKey.length; i++)
mDefaultAllowedAlgs[i] = allowedByKey[i];
- // winnow out algorithms that don't match CA's signing key
+ // winnow out algorithms that don't match CA's signing key
winnowAlgs(allowedByKey,
- "CMS_POLICY_SIGNALG_NOT_MATCH_CAKEY_1", false);
+ "CMS_POLICY_SIGNALG_NOT_MATCH_CAKEY_1", false);
winnowedByKey = true;
} else {
- // We don't know the CA's signing algorithms. Maybe we're
+ // We don't know the CA's signing algorithms. Maybe we're
// an RA that hasn't talked to the CA yet? Try again later.
}
}
@@ -203,14 +203,15 @@ public class SigningAlgorithmConstraints extends APolicyRule
/**
* Winnows out of mAllowedAlgorithms those algorithms that aren't allowed
* for some reason.
- *
- * @param allowed An array of allowed algorithms. Only algorithms in this
- * list will survive the winnowing process.
- * @param reason A string describing the problem with an algorithm
- * that is not allowed by this list. Must be a predefined string in PolicyResources.
+ *
+ * @param allowed An array of allowed algorithms. Only algorithms in this
+ * list will survive the winnowing process.
+ * @param reason A string describing the problem with an algorithm that is
+ * not allowed by this list. Must be a predefined string in
+ * PolicyResources.
*/
- private void winnowAlgs(String[] allowed, String reason, boolean isError)
- throws EBaseException {
+ private void winnowAlgs(String[] allowed, String reason, boolean isError)
+ throws EBaseException {
int i, j, goodSize;
// validate the currently-allowed algorithms
@@ -240,7 +241,7 @@ public class SigningAlgorithmConstraints extends APolicyRule
// convert back into an array
goodSize = goodAlgs.size();
if (mAllowedAlgs.length != goodSize) {
- mAllowedAlgs = new String[ goodSize ];
+ mAllowedAlgs = new String[goodSize];
for (i = 0; i < goodSize; i++) {
mAllowedAlgs[i] = (String) goodAlgs.elementAt(i);
}
@@ -250,8 +251,8 @@ public class SigningAlgorithmConstraints extends APolicyRule
/**
* Applies the policy on the given Request.
* <P>
- *
- * @param req The request on which to apply policy.
+ *
+ * @param req The request on which to apply policy.
* @return The policy result object.
*/
public PolicyResult apply(IRequest req) {
@@ -262,8 +263,8 @@ public class SigningAlgorithmConstraints extends APolicyRule
try {
// Get the certificate info from the request
- //X509CertInfo certInfo[] = (X509CertInfo[])
- // req.get(IRequest.CERT_INFO);
+ // X509CertInfo certInfo[] = (X509CertInfo[])
+ // req.get(IRequest.CERT_INFO);
X509CertInfo certInfo[] = req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
// We need to have a certificate info set
@@ -282,10 +283,10 @@ public class SigningAlgorithmConstraints extends APolicyRule
}
CertificateAlgorithmId certAlgId = (CertificateAlgorithmId)
- certInfo[i].get(X509CertInfo.ALGORITHM_ID);
+ certInfo[i].get(X509CertInfo.ALGORITHM_ID);
AlgorithmId algId = (AlgorithmId)
- certAlgId.get(CertificateAlgorithmId.ALGORITHM);
+ certAlgId.get(CertificateAlgorithmId.ALGORITHM);
String alg = algId.getName();
// test against the list of allowed algorithms
@@ -298,10 +299,10 @@ public class SigningAlgorithmConstraints extends APolicyRule
// if the algor doesn't match the CA's key replace
// it with one that does.
if (mAllowedAlgs[0].equals("SHA1withDSA") ||
- alg.equals("SHA1withDSA")) {
+ alg.equals("SHA1withDSA")) {
certInfo[i].set(X509CertInfo.ALGORITHM_ID,
- new CertificateAlgorithmId(
- AlgorithmId.get(mAllowedAlgs[0])));
+ new CertificateAlgorithmId(
+ AlgorithmId.get(mAllowedAlgs[0])));
return PolicyResult.ACCEPTED;
}
@@ -313,9 +314,9 @@ public class SigningAlgorithmConstraints extends APolicyRule
}
} catch (Exception e) {
// e.printStackTrace();
- String params[] = {getInstanceName(), e.toString()};
+ String params[] = { getInstanceName(), e.toString() };
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR",
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR",
params), "");
result = PolicyResult.REJECTED;
}
@@ -324,10 +325,10 @@ public class SigningAlgorithmConstraints extends APolicyRule
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector getInstanceParams() {
+ public Vector getInstanceParams() {
Vector confParams = new Vector();
StringBuffer sb = new StringBuffer();
@@ -343,10 +344,10 @@ public class SigningAlgorithmConstraints extends APolicyRule
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector getDefaultParams() {
+ public Vector getDefaultParams() {
StringBuffer sb = new StringBuffer();
sb.append(PROP_ALGORITHMS);
sb.append("=");
@@ -365,14 +366,14 @@ public class SigningAlgorithmConstraints extends APolicyRule
}
defConfParams.addElement(sb.toString());
- return defConfParams;
+ return defConfParams;
}
public String[] getExtendedPluginInfo(Locale locale) {
if (!winnowedByKey) {
- try {
- winnowByKey();
- } catch (Exception e) {
+ try {
+ winnowByKey();
+ } catch (Exception e) {
}
}
@@ -380,51 +381,51 @@ public class SigningAlgorithmConstraints extends APolicyRule
String[] params_BOTH = {
PROP_ALGORITHMS + ";" + "choice(MD2withRSA\\,MD5withRSA\\,SHA1withRSA\\,SHA256withRSA\\,SHA512withRSA\\,SHA1withDSA," +
- "MD2withRSA\\,MD5withRSA\\,SHA1withRSA\\,SHA1withDSA,"+
- "MD2withRSA\\,MD5withRSA\\,SHA1withRSA," +
- "MD2withRSA\\,SHA1withRSA\\,SHA1withDSA," +
- "MD5withRSA\\,SHA1withRSA\\,SHA1withDSA," +
- "MD2withRSA\\,MD5withRSA\\,SHA1withDSA," +
- "MD2withRSA\\,MD5withRSA," +
- "MD2withRSA\\,SHA1withRSA," +
- "MD2withRSA\\,SHA1withDSA," +
- "MD5withRSA\\,SHA1withRSA," +
- "MD5withRSA\\,SHA1withDSA," +
- "SHA1withRSA\\,SHA1withDSA," +
- "MD2withRSA," +
- "MD5withRSA," +
- "SHA1withRSA," +
- "SHA1withDSA);List of algorithms to restrict the requested signing algorithm " +
- "to be one of the algorithms supported by Certificate System",
+ "MD2withRSA\\,MD5withRSA\\,SHA1withRSA\\,SHA1withDSA," +
+ "MD2withRSA\\,MD5withRSA\\,SHA1withRSA," +
+ "MD2withRSA\\,SHA1withRSA\\,SHA1withDSA," +
+ "MD5withRSA\\,SHA1withRSA\\,SHA1withDSA," +
+ "MD2withRSA\\,MD5withRSA\\,SHA1withDSA," +
+ "MD2withRSA\\,MD5withRSA," +
+ "MD2withRSA\\,SHA1withRSA," +
+ "MD2withRSA\\,SHA1withDSA," +
+ "MD5withRSA\\,SHA1withRSA," +
+ "MD5withRSA\\,SHA1withDSA," +
+ "SHA1withRSA\\,SHA1withDSA," +
+ "MD2withRSA," +
+ "MD5withRSA," +
+ "SHA1withRSA," +
+ "SHA1withDSA);List of algorithms to restrict the requested signing algorithm " +
+ "to be one of the algorithms supported by Certificate System",
IExtendedPluginInfo.HELP_TOKEN + ";configuration-policyrules-signingalgconstraints",
IExtendedPluginInfo.HELP_TEXT +
- ";Restricts the requested signing algorithm to be one of" +
- " the algorithms supported by Certificate System"
+ ";Restricts the requested signing algorithm to be one of" +
+ " the algorithms supported by Certificate System"
};
String[] params_RSA = {
PROP_ALGORITHMS + ";" + "choice(MD2withRSA\\,MD5withRSA\\,SHA1withRSA," +
- "MD2withRSA\\,MD5withRSA," +
- "MD2withRSA\\,SHA1withRSA," +
- "MD5withRSA\\,SHA1withRSA," +
- "MD2withRSA," +
- "MD5withRSA," +
- "SHA1withRSA);Restrict the requested signing algorithm to be " +
- "one of the algorithms supported by Certificate System",
+ "MD2withRSA\\,MD5withRSA," +
+ "MD2withRSA\\,SHA1withRSA," +
+ "MD5withRSA\\,SHA1withRSA," +
+ "MD2withRSA," +
+ "MD5withRSA," +
+ "SHA1withRSA);Restrict the requested signing algorithm to be " +
+ "one of the algorithms supported by Certificate System",
IExtendedPluginInfo.HELP_TOKEN + ";configuration-policyrules-signingalgconstraints",
IExtendedPluginInfo.HELP_TEXT +
- ";Restricts the requested signing algorithm to be one of" +
- " the algorithms supported by Certificate System"
+ ";Restricts the requested signing algorithm to be one of" +
+ " the algorithms supported by Certificate System"
};
String[] params_DSA = {
PROP_ALGORITHMS + ";" + "choice(SHA1withDSA);Restrict the requested signing " +
- "algorithm to be one of the algorithms supported by Certificate " +
- "System",
+ "algorithm to be one of the algorithms supported by Certificate " +
+ "System",
IExtendedPluginInfo.HELP_TOKEN + ";configuration-policyrules-signingalgconstraints",
IExtendedPluginInfo.HELP_TEXT +
- ";Restricts the requested signing algorithm to be one of" +
- " the algorithms supported by Certificate System"
+ ";Restricts the requested signing algorithm to be one of" +
+ " the algorithms supported by Certificate System"
};
switch (mDefaultAllowedAlgs.length) {
@@ -447,4 +448,3 @@ public class SigningAlgorithmConstraints extends APolicyRule
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/policy/constraints/SubCANameConstraints.java b/pki/base/common/src/com/netscape/cms/policy/constraints/SubCANameConstraints.java
index 8e8cd4a7..81862cfe 100644
--- a/pki/base/common/src/com/netscape/cms/policy/constraints/SubCANameConstraints.java
+++ b/pki/base/common/src/com/netscape/cms/policy/constraints/SubCANameConstraints.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.constraints;
-
import java.util.Locale;
import java.util.Vector;
@@ -41,16 +40,16 @@ import com.netscape.certsrv.request.PolicyResult;
import com.netscape.certsrv.security.ISigningUnit;
import com.netscape.cms.policy.APolicyRule;
-
/**
- * This simple policy checks the subordinate CA CSR to see
- * if it is the same as the local CA.
+ * This simple policy checks the subordinate CA CSR to see if it is the same as
+ * the local CA.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
@@ -66,32 +65,32 @@ public class SubCANameConstraints extends APolicyRule implements IEnrollmentPoli
public String[] getExtendedPluginInfo(Locale locale) {
String[] params = {
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-subcanamecheck",
+ ";configuration-policyrules-subcanamecheck",
IExtendedPluginInfo.HELP_TEXT +
- ";Checks if subordinate CA request matches the local CA. There are no parameters to change"
+ ";Checks if subordinate CA request matches the local CA. There are no parameters to change"
};
return params;
}
-
+
/**
* Initializes this policy rule.
* <P>
- *
+ *
* The entries probably are of the form
- * ra.Policy.rule.<ruleName>.implName=KeyAlgorithmConstraints
- * ra.Policy.rule.<ruleName>.algorithms=RSA,DSA
- * ra.Policy.rule.<ruleName>.enable=true
- * ra.Policy.rule.<ruleName>.predicate=ou==Sales
- *
- * @param config The config store reference
+ * ra.Policy.rule.<ruleName>.implName=KeyAlgorithmConstraints
+ * ra.Policy.rule.<ruleName>.algorithms=RSA,DSA
+ * ra.Policy.rule.<ruleName>.enable=true
+ * ra.Policy.rule.<ruleName>.predicate=ou==Sales
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
// get CA's public key to create authority key id.
- ICertAuthority certAuthority = (ICertAuthority)
- ((IPolicyProcessor) owner).getAuthority();
+ ICertAuthority certAuthority = (ICertAuthority)
+ ((IPolicyProcessor) owner).getAuthority();
if (certAuthority == null) {
// should never get here.
@@ -106,7 +105,7 @@ public class SubCANameConstraints extends APolicyRule implements IEnrollmentPoli
}
mCA = (ICertificateAuthority) certAuthority;
ISigningUnit su = mCA.getSigningUnit();
- if( su == null || CMS.isPreOpMode() ) {
+ if (su == null || CMS.isPreOpMode()) {
return;
}
@@ -124,8 +123,8 @@ public class SubCANameConstraints extends APolicyRule implements IEnrollmentPoli
/**
* Applies the policy on the given Request.
* <P>
- *
- * @param req The request on which to apply policy.
+ *
+ * @param req The request on which to apply policy.
* @return The policy result object.
*/
public PolicyResult apply(IRequest req) {
@@ -136,7 +135,7 @@ public class SubCANameConstraints extends APolicyRule implements IEnrollmentPoli
// Get the certificate templates
X509CertInfo[] certInfos = req.getExtDataInCertInfoArray(
IRequest.CERT_INFO);
-
+
if (certInfos == null) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("POLICY_NO_CERT_INFO", getInstanceName()));
setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO", NAME + ":" + getInstanceName()), "");
@@ -163,7 +162,7 @@ public class SubCANameConstraints extends APolicyRule implements IEnrollmentPoli
}
} catch (Exception e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("POLICY_NO_SUBJECT_NAME_1", getInstanceName()));
- String params[] = {getInstanceName(), e.toString()};
+ String params[] = { getInstanceName(), e.toString() };
setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR",
params), "");
@@ -174,24 +173,23 @@ public class SubCANameConstraints extends APolicyRule implements IEnrollmentPoli
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector getInstanceParams() {
+ public Vector getInstanceParams() {
Vector v = new Vector();
return v;
}
-
+
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector getDefaultParams() {
+ public Vector getDefaultParams() {
Vector v = new Vector();
return v;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/policy/constraints/UniqueSubjectName.java b/pki/base/common/src/com/netscape/cms/policy/constraints/UniqueSubjectName.java
index dc8ecd79..9afbf765 100644
--- a/pki/base/common/src/com/netscape/cms/policy/constraints/UniqueSubjectName.java
+++ b/pki/base/common/src/com/netscape/cms/policy/constraints/UniqueSubjectName.java
@@ -17,17 +17,15 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.constraints;
-
-
-
/**
* This class is used to help migrate CMS4.1 to CMS4.2.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
diff --git a/pki/base/common/src/com/netscape/cms/policy/constraints/UniqueSubjectNameConstraints.java b/pki/base/common/src/com/netscape/cms/policy/constraints/UniqueSubjectNameConstraints.java
index 2cff24d3..48663f61 100644
--- a/pki/base/common/src/com/netscape/cms/policy/constraints/UniqueSubjectNameConstraints.java
+++ b/pki/base/common/src/com/netscape/cms/policy/constraints/UniqueSubjectNameConstraints.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.constraints;
-
import java.io.IOException;
import java.util.Enumeration;
import java.util.Locale;
@@ -44,35 +43,33 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
- * Checks the uniqueness of the subject name. This policy
- * can only be used (installed) in Certificate Authority
- * subsystem.
- *
- * This policy can perform pre-agent-approval checking or
- * post-agent-approval checking based on configuration
- * setting.
- *
- * In some situations, user may want to have 2 certificates with
- * the same subject name. For example, one key for encryption,
- * and one for signing. This policy does not deal with this case
- * directly. But it can be easily extended to do that.
+ * Checks the uniqueness of the subject name. This policy can only be used
+ * (installed) in Certificate Authority subsystem.
+ *
+ * This policy can perform pre-agent-approval checking or post-agent-approval
+ * checking based on configuration setting.
+ *
+ * In some situations, user may want to have 2 certificates with the same
+ * subject name. For example, one key for encryption, and one for signing. This
+ * policy does not deal with this case directly. But it can be easily extended
+ * to do that.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
-public class UniqueSubjectNameConstraints extends APolicyRule
- implements IEnrollmentPolicy, IExtendedPluginInfo {
- protected static final String PROP_PRE_AGENT_APPROVAL_CHECKING =
- "enablePreAgentApprovalChecking";
- protected static final String PROP_KEY_USAGE_EXTENSION_CHECKING =
- "enableKeyUsageExtensionChecking";
+public class UniqueSubjectNameConstraints extends APolicyRule
+ implements IEnrollmentPolicy, IExtendedPluginInfo {
+ protected static final String PROP_PRE_AGENT_APPROVAL_CHECKING =
+ "enablePreAgentApprovalChecking";
+ protected static final String PROP_KEY_USAGE_EXTENSION_CHECKING =
+ "enableKeyUsageExtensionChecking";
public ICertificateAuthority mCA = null;
@@ -82,17 +79,17 @@ public class UniqueSubjectNameConstraints extends APolicyRule
public UniqueSubjectNameConstraints() {
NAME = "UniqueSubjectName";
DESC = "Ensure the uniqueness of the subject name.";
- }
+ }
public String[] getExtendedPluginInfo(Locale locale) {
String[] params = {
PROP_PRE_AGENT_APPROVAL_CHECKING + ";boolean;If checked, check subject name uniqueness BEFORE agent approves, (else checks AFTER approval)",
PROP_KEY_USAGE_EXTENSION_CHECKING + ";boolean;If checked, allow non-unique subject names if Key Usage Extension differs",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-uniquesubjectname",
+ ";configuration-policyrules-uniquesubjectname",
IExtendedPluginInfo.HELP_TEXT +
- ";Rejects a request if there exists an unrevoked, unexpired " +
- "certificate with the same subject name"
+ ";Rejects a request if there exists an unrevoked, unexpired " +
+ "certificate with the same subject name"
};
return params;
@@ -102,22 +99,22 @@ public class UniqueSubjectNameConstraints extends APolicyRule
/**
* Initializes this policy rule.
* <P>
- *
+ *
* The entries probably are of the form:
- *
- * ca.Policy.rule.<ruleName>.implName=UniqueSubjectName
- * ca.Policy.rule.<ruleName>.enable=true
- * ca.Policy.rule.<ruleName>.enable=true
- * ca.Policy.rule.<ruleName>.enablePreAgentApprovalChecking=true
- * ca.Policy.rule.<ruleName>.enableKeyUsageExtensionChecking=true
- *
- * @param config The config store reference
+ *
+ * ca.Policy.rule.<ruleName>.implName=UniqueSubjectName
+ * ca.Policy.rule.<ruleName>.enable=true
+ * ca.Policy.rule.<ruleName>.enable=true
+ * ca.Policy.rule.<ruleName>.enablePreAgentApprovalChecking=true
+ * ca.Policy.rule.<ruleName>.enableKeyUsageExtensionChecking=true
+ *
+ * @param config The config store reference
*/
- public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ public void init(ISubsystem owner, IConfigStore config)
+ throws EBaseException {
// get CA's public key to create authority key id.
ICertAuthority certAuthority = (ICertAuthority)
- ((IPolicyProcessor) owner).getAuthority();
+ ((IPolicyProcessor) owner).getAuthority();
if (certAuthority == null) {
// should never get here.
@@ -131,12 +128,12 @@ public class UniqueSubjectNameConstraints extends APolicyRule
mCA = (ICertificateAuthority) certAuthority;
try {
- mPreAgentApprovalChecking =
+ mPreAgentApprovalChecking =
config.getBoolean(PROP_PRE_AGENT_APPROVAL_CHECKING, false);
} catch (EBaseException e) {
}
try {
- mKeyUsageExtensionChecking =
+ mKeyUsageExtensionChecking =
config.getBoolean(PROP_KEY_USAGE_EXTENSION_CHECKING, true);
} catch (EBaseException e) {
}
@@ -145,8 +142,8 @@ public class UniqueSubjectNameConstraints extends APolicyRule
/**
* Applies the policy on the given Request.
* <P>
- *
- * @param req The request on which to apply policy.
+ *
+ * @param req The request on which to apply policy.
* @return The policy result object.
*/
public PolicyResult apply(IRequest req) {
@@ -162,9 +159,9 @@ public class UniqueSubjectNameConstraints extends APolicyRule
// Get the certificate templates
X509CertInfo[] certInfos = req.getExtDataInCertInfoArray(
IRequest.CERT_INFO);
-
+
if (certInfos == null) {
- setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO",
+ setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO",
getInstanceName()), "");
return PolicyResult.REJECTED;
}
@@ -172,11 +169,11 @@ public class UniqueSubjectNameConstraints extends APolicyRule
// retrieve the subject name and check its unqiueness
for (int i = 0; i < certInfos.length; i++) {
CertificateSubjectName subName = (CertificateSubjectName)
- certInfos[i].get(X509CertInfo.SUBJECT);
+ certInfos[i].get(X509CertInfo.SUBJECT);
// if there is no name set, set one here.
if (subName == null) {
- setError(req, CMS.getUserMessage("CMS_POLICY_NO_SUBJECT_NAME",
+ setError(req, CMS.getUserMessage("CMS_POLICY_NO_SUBJECT_NAME",
getInstanceName()), "");
return PolicyResult.REJECTED;
}
@@ -184,23 +181,24 @@ public class UniqueSubjectNameConstraints extends APolicyRule
String filter = "x509Cert.subject=" + certSubjectName;
// subject name is indexed, so we only use subject name
// in the filter
- Enumeration<ICertRecord> matched =
- mCA.getCertificateRepository().findCertRecords(filter);
+ Enumeration<ICertRecord> matched =
+ mCA.getCertificateRepository().findCertRecords(filter);
while (matched.hasMoreElements()) {
- ICertRecord rec = matched.nextElement();
+ ICertRecord rec = matched.nextElement();
String status = rec.getStatus();
if (status.equals(ICertRecord.STATUS_REVOKED) || status.equals(ICertRecord.STATUS_EXPIRED) || status.equals(ICertRecord.STATUS_REVOKED_EXPIRED)) {
- // accept this only if we have a REVOKED,
+ // accept this only if we have a REVOKED,
// EXPIRED or REVOKED_EXPIRED certificate
continue;
-
+
}
- // you already have an VALID or INVALID (not yet valid) certificate
+ // you already have an VALID or INVALID (not yet valid)
+ // certificate
if (mKeyUsageExtensionChecking && agentApproved(req)) {
- // This request is agent approved which
- // means all requested extensions are finalized
+ // This request is agent approved which
+ // means all requested extensions are finalized
// to the request,
// We will accept duplicated subject name with
// different keyUsage extension if
@@ -210,15 +208,15 @@ public class UniqueSubjectNameConstraints extends APolicyRule
}
}
- setError(req, CMS.getUserMessage("CMS_POLICY_SUBJECT_NAME_EXIST",
+ setError(req, CMS.getUserMessage("CMS_POLICY_SUBJECT_NAME_EXIST",
getInstanceName() + " " + certSubjectName), "");
return PolicyResult.REJECTED;
}
}
} catch (Exception e) {
- String params[] = {getInstanceName(), e.toString()};
+ String params[] = { getInstanceName(), e.toString() };
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR",
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR",
params), "");
result = PolicyResult.REJECTED;
}
@@ -226,11 +224,11 @@ public class UniqueSubjectNameConstraints extends APolicyRule
}
/**
- * Checks if the key extension in the issued certificate
- * is the same as the one in the certificate template.
+ * Checks if the key extension in the issued certificate is the same as the
+ * one in the certificate template.
*/
- private boolean sameKeyUsageExtension(ICertRecord rec,
- X509CertInfo certInfo) {
+ private boolean sameKeyUsageExtension(ICertRecord rec,
+ X509CertInfo certInfo) {
X509CertImpl impl = rec.getCertificate();
boolean bits[] = impl.getKeyUsage();
@@ -282,25 +280,25 @@ public class UniqueSubjectNameConstraints extends APolicyRule
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
public Vector<String> getInstanceParams() {
Vector<String> confParams = new Vector<String>();
confParams.addElement(PROP_PRE_AGENT_APPROVAL_CHECKING +
- "=" + mPreAgentApprovalChecking);
+ "=" + mPreAgentApprovalChecking);
confParams.addElement(PROP_KEY_USAGE_EXTENSION_CHECKING +
- "=" + mKeyUsageExtensionChecking);
+ "=" + mKeyUsageExtensionChecking);
return confParams;
}
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getDefaultParams() {
+ public Vector<String> getDefaultParams() {
Vector<String> defParams = new Vector<String>();
defParams.addElement(PROP_PRE_AGENT_APPROVAL_CHECKING + "=");
diff --git a/pki/base/common/src/com/netscape/cms/policy/constraints/ValidityConstraints.java b/pki/base/common/src/com/netscape/cms/policy/constraints/ValidityConstraints.java
index 62c49450..d8578633 100644
--- a/pki/base/common/src/com/netscape/cms/policy/constraints/ValidityConstraints.java
+++ b/pki/base/common/src/com/netscape/cms/policy/constraints/ValidityConstraints.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.constraints;
-
import java.util.Date;
import java.util.Locale;
import java.util.Vector;
@@ -35,26 +34,24 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
- * ValidityConstraints is a default rule for Enrollment and
- * Renewal that enforces minimum and maximum validity periods
- * and changes them if not met.
- *
- * Optionally the lead and lag times - i.e how far back into the
- * front or back the notBefore date could go in minutes can also
- * be specified.
+ * ValidityConstraints is a default rule for Enrollment and Renewal that
+ * enforces minimum and maximum validity periods and changes them if not met.
+ *
+ * Optionally the lead and lag times - i.e how far back into the front or back
+ * the notBefore date could go in minutes can also be specified.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public class ValidityConstraints extends APolicyRule
- implements IEnrollmentPolicy, IExtendedPluginInfo {
+ implements IEnrollmentPolicy, IExtendedPluginInfo {
protected long mMinValidity;
protected long mMaxValidity;
protected long mLeadTime;
@@ -78,15 +75,15 @@ public class ValidityConstraints extends APolicyRule
static {
defConfParams.addElement(PROP_MIN_VALIDITY + "=" +
- DEF_MIN_VALIDITY);
+ DEF_MIN_VALIDITY);
defConfParams.addElement(PROP_MAX_VALIDITY + "=" +
- DEF_MAX_VALIDITY);
+ DEF_MAX_VALIDITY);
defConfParams.addElement(PROP_LEAD_TIME + "=" +
- DEF_LEAD_TIME);
+ DEF_LEAD_TIME);
defConfParams.addElement(PROP_LAG_TIME + "=" +
- DEF_LAG_TIME);
+ DEF_LAG_TIME);
defConfParams.addElement(PROP_NOT_BEFORE_SKEW + "=" +
- DEF_NOT_BEFORE_SKEW);
+ DEF_NOT_BEFORE_SKEW);
}
public String[] getExtendedPluginInfo(Locale locale) {
@@ -97,11 +94,11 @@ public class ValidityConstraints extends APolicyRule
PROP_LAG_TIME + ";number;NOT CURRENTLY IN USE",
PROP_NOT_BEFORE_SKEW + ";number;Number of minutes a cert's notBefore should be in the past",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-validityconstraints",
+ ";configuration-policyrules-validityconstraints",
IExtendedPluginInfo.HELP_TEXT +
- ";Ensures that the user's requested validity period is " +
- "acceptable. If not specified, as is usually the case, " +
- "this policy will set the validity. See RFC 2459."
+ ";Ensures that the user's requested validity period is " +
+ "acceptable. If not specified, as is usually the case, " +
+ "this policy will set the validity. See RFC 2459."
};
return params;
@@ -116,19 +113,19 @@ public class ValidityConstraints extends APolicyRule
/**
* Initializes this policy rule.
* <P>
- *
+ *
* The entries probably are of the form:
- *
- * ra.Policy.rule.<ruleName>.implName=ValidityConstraints
- * ra.Policy.rule.<ruleName>.enable=true
- * ra.Policy.rule.<ruleName>.minValidity=30
- * ra.Policy.rule.<ruleName>.maxValidity=180
- * ra.Policy.rule.<ruleName>.predicate=ou==Sales
- *
- * @param config The config store reference
+ *
+ * ra.Policy.rule.<ruleName>.implName=ValidityConstraints
+ * ra.Policy.rule.<ruleName>.enable=true
+ * ra.Policy.rule.<ruleName>.minValidity=30
+ * ra.Policy.rule.<ruleName>.maxValidity=180
+ * ra.Policy.rule.<ruleName>.predicate=ou==Sales
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EPolicyException {
+ throws EPolicyException {
// Get min and max validity in days and configure them.
try {
@@ -164,7 +161,7 @@ public class ValidityConstraints extends APolicyRule
mNotBeforeSkew = DEF_NOT_BEFORE_SKEW * MINS_TO_MS_FACTOR;
} catch (Exception e) {
// e.printStackTrace();
- String[] params = {getInstanceName(), e.toString()};
+ String[] params = { getInstanceName(), e.toString() };
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_INVALID_POLICY_CONFIG", params));
@@ -174,8 +171,8 @@ public class ValidityConstraints extends APolicyRule
/**
* Applies the policy on the given Request.
* <P>
- *
- * @param req The request on which to apply policy.
+ *
+ * @param req The request on which to apply policy.
* @return The policy result object.
*/
public PolicyResult apply(IRequest req) {
@@ -184,8 +181,8 @@ public class ValidityConstraints extends APolicyRule
try {
// Get the certificate info from the request
- //X509CertInfo certInfo[] = (X509CertInfo[])
- // req.get(IRequest.CERT_INFO);
+ // X509CertInfo certInfo[] = (X509CertInfo[])
+ // req.get(IRequest.CERT_INFO);
X509CertInfo certInfo[] = req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
// There should be a certificate info set.
@@ -198,7 +195,7 @@ public class ValidityConstraints extends APolicyRule
// Else check if validity is within the limit
for (int i = 0; i < certInfo.length; i++) {
CertificateValidity validity = (CertificateValidity)
- certInfo[i].get(X509CertInfo.VALIDITY);
+ certInfo[i].get(X509CertInfo.VALIDITY);
Date notBefore = null, notAfter = null;
@@ -209,15 +206,15 @@ public class ValidityConstraints extends APolicyRule
validity.get(CertificateValidity.NOT_AFTER);
}
- // If no validity is supplied yet, make one. The default
+ // If no validity is supplied yet, make one. The default
// validity is supposed to pass the following checks, so
// bypass further checking.
// (date = 0 is hack for serialization)
if (validity == null ||
- (notBefore.getTime() == 0 && notAfter.getTime() == 0)) {
+ (notBefore.getTime() == 0 && notAfter.getTime() == 0)) {
certInfo[i].set(X509CertInfo.VALIDITY,
- makeDefaultValidity(req));
+ makeDefaultValidity(req));
continue;
}
@@ -228,22 +225,20 @@ public class ValidityConstraints extends APolicyRule
getInstanceName()), "");
result = PolicyResult.REJECTED;
}
- if ((notAfter.getTime() - notBefore.getTime()) >
- mMaxValidity) {
- String params[] = {getInstanceName(),
+ if ((notAfter.getTime() - notBefore.getTime()) > mMaxValidity) {
+ String params[] = { getInstanceName(),
String.valueOf(
- ((notAfter.getTime() - notBefore.getTime()) / DAYS_TO_MS_FACTOR)),
- String.valueOf(mMaxValidity / DAYS_TO_MS_FACTOR)};
+ ((notAfter.getTime() - notBefore.getTime()) / DAYS_TO_MS_FACTOR)),
+ String.valueOf(mMaxValidity / DAYS_TO_MS_FACTOR) };
setError(req, CMS.getUserMessage("CMS_POLICY_MORE_THAN_MAX_VALIDITY", params), "");
result = PolicyResult.REJECTED;
}
- if ((notAfter.getTime() - notBefore.getTime()) <
- mMinValidity) {
- String params[] = {getInstanceName(),
+ if ((notAfter.getTime() - notBefore.getTime()) < mMinValidity) {
+ String params[] = { getInstanceName(),
String.valueOf(
- ((notAfter.getTime() - notBefore.getTime()) / DAYS_TO_MS_FACTOR)),
- String.valueOf(mMinValidity / DAYS_TO_MS_FACTOR)};
+ ((notAfter.getTime() - notBefore.getTime()) / DAYS_TO_MS_FACTOR)),
+ String.valueOf(mMinValidity / DAYS_TO_MS_FACTOR) };
setError(req, CMS.getUserMessage("CMS_POLICY_LESS_THAN_MIN_VALIDITY", params), "");
result = PolicyResult.REJECTED;
@@ -251,7 +246,7 @@ public class ValidityConstraints extends APolicyRule
}
} catch (Exception e) {
// e.printStackTrace();
- String params[] = {getInstanceName(), e.toString()};
+ String params[] = { getInstanceName(), e.toString() };
setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR",
params), "");
@@ -262,28 +257,28 @@ public class ValidityConstraints extends APolicyRule
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
public Vector getInstanceParams() {
Vector confParams = new Vector();
confParams.addElement(PROP_MIN_VALIDITY + "=" +
- mMinValidity / DAYS_TO_MS_FACTOR);
+ mMinValidity / DAYS_TO_MS_FACTOR);
confParams.addElement(PROP_MAX_VALIDITY + "=" +
- mMaxValidity / DAYS_TO_MS_FACTOR);
- confParams.addElement(PROP_LEAD_TIME + "="
- + mLeadTime / MINS_TO_MS_FACTOR);
- confParams.addElement(PROP_LAG_TIME + "=" +
- mLagTime / MINS_TO_MS_FACTOR);
- confParams.addElement(PROP_NOT_BEFORE_SKEW + "=" +
- mNotBeforeSkew / MINS_TO_MS_FACTOR);
+ mMaxValidity / DAYS_TO_MS_FACTOR);
+ confParams.addElement(PROP_LEAD_TIME + "="
+ + mLeadTime / MINS_TO_MS_FACTOR);
+ confParams.addElement(PROP_LAG_TIME + "=" +
+ mLagTime / MINS_TO_MS_FACTOR);
+ confParams.addElement(PROP_NOT_BEFORE_SKEW + "=" +
+ mNotBeforeSkew / MINS_TO_MS_FACTOR);
return confParams;
}
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
public Vector getDefaultParams() {
@@ -292,12 +287,12 @@ public class ValidityConstraints extends APolicyRule
/**
* Create a default validity value for a request
- *
+ *
* This code can be easily overridden in a derived class, if the
* calculations here aren't accepatble.
- *
- * TODO: it might be good to base this calculation on the creation
- * time of the request.
+ *
+ * TODO: it might be good to base this calculation on the creation time of
+ * the request.
*/
protected CertificateValidity makeDefaultValidity(IRequest req) {
long now = roundTimeToSecond((CMS.getCurrentDate()).getTime());
@@ -311,13 +306,11 @@ public class ValidityConstraints extends APolicyRule
}
/**
- * convert a millisecond resolution time into one with 1 second
- * resolution. Most times in certificates are storage at 1
- * second resolution, so its better if we deal with things at
- * that level.
+ * convert a millisecond resolution time into one with 1 second resolution.
+ * Most times in certificates are storage at 1 second resolution, so its
+ * better if we deal with things at that level.
*/
protected long roundTimeToSecond(long input) {
return (input / 1000) * 1000;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/policy/extensions/AuthInfoAccessExt.java b/pki/base/common/src/com/netscape/cms/policy/extensions/AuthInfoAccessExt.java
index 4f8aaa29..79679f0c 100644
--- a/pki/base/common/src/com/netscape/cms/policy/extensions/AuthInfoAccessExt.java
+++ b/pki/base/common/src/com/netscape/cms/policy/extensions/AuthInfoAccessExt.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.extensions;
-
import java.io.IOException;
import java.io.Serializable;
import java.security.cert.CertificateException;
@@ -44,57 +43,51 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
- * Authority Information Access extension policy.
- * If this policy is enabled, it adds an authority
- * information access extension to the certificate.
- *
+ * Authority Information Access extension policy. If this policy is enabled, it
+ * adds an authority information access extension to the certificate.
+ *
* The following listed sample configuration parameters:
*
- * ca.Policy.impl.AuthInfoAccess.class=com.netscape.certsrv.policy.AuthInfoAccessExt
+ * ca.Policy.impl.AuthInfoAccess.class=com.netscape.certsrv.policy.
+ * AuthInfoAccessExt
* ca.Policy.rule.aia.ad0_location=uriName:http://ocsp1.netscape.com
- * ca.Policy.rule.aia.ad0_method=ocsp
- * ca.Policy.rule.aia.ad1_location_type=URI
+ * ca.Policy.rule.aia.ad0_method=ocsp ca.Policy.rule.aia.ad1_location_type=URI
* ca.Policy.rule.aia.ad1_location=http://ocsp2.netscape.com
- * ca.Policy.rule.aia.ad1_method=ocsp
- * ca.Policy.rule.aia.ad2_location=
- * ca.Policy.rule.aia.ad2_method=
- * ca.Policy.rule.aia.ad3_location=
- * ca.Policy.rule.aia.ad3_method=
- * ca.Policy.rule.aia.ad4_location=
- * ca.Policy.rule.aia.ad4_method=
- * ca.Policy.rule.aia.critical=true
- * ca.Policy.rule.aia.enable=true
- * ca.Policy.rule.aia.implName=AuthInfoAccess
+ * ca.Policy.rule.aia.ad1_method=ocsp ca.Policy.rule.aia.ad2_location=
+ * ca.Policy.rule.aia.ad2_method= ca.Policy.rule.aia.ad3_location=
+ * ca.Policy.rule.aia.ad3_method= ca.Policy.rule.aia.ad4_location=
+ * ca.Policy.rule.aia.ad4_method= ca.Policy.rule.aia.critical=true
+ * ca.Policy.rule.aia.enable=true ca.Policy.rule.aia.implName=AuthInfoAccess
* ca.Policy.rule.aia.predicate=
- *
- * Currently, this policy only supports the following location:
- * uriName:[URI], dirName:[DN]
+ *
+ * Currently, this policy only supports the following location: uriName:[URI],
+ * dirName:[DN]
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
-public class AuthInfoAccessExt extends APolicyRule implements
+public class AuthInfoAccessExt extends APolicyRule implements
IEnrollmentPolicy, IExtendedPluginInfo {
protected static final String PROP_CRITICAL =
- "critical";
+ "critical";
protected static final String PROP_AD =
- "ad";
+ "ad";
protected static final String PROP_METHOD =
- "method";
+ "method";
protected static final String PROP_LOCATION =
- "location";
+ "location";
protected static final String PROP_LOCATION_TYPE =
- "location_type";
+ "location_type";
protected static final String PROP_NUM_ADS =
- "numADs";
+ "numADs";
public static final int MAX_AD = 5;
@@ -109,13 +102,13 @@ public class AuthInfoAccessExt extends APolicyRule implements
Vector<String> v = new Vector<String>();
v.addElement(PROP_CRITICAL +
- ";boolean;RFC 2459 recommendation: This extension MUST be non-critical.");
+ ";boolean;RFC 2459 recommendation: This extension MUST be non-critical.");
v.addElement(PROP_NUM_ADS +
- ";number;The total number of access descriptions.");
+ ";number;The total number of access descriptions.");
v.addElement(IExtendedPluginInfo.HELP_TEXT +
- ";Adds Authority Info Access Extension. Defined in RFC 2459 " + "(4.2.2.1)");
+ ";Adds Authority Info Access Extension. Defined in RFC 2459 " + "(4.2.2.1)");
v.addElement(IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-authinfoaccess");
+ ";configuration-policyrules-authinfoaccess");
for (int i = 0; i < MAX_AD; i++) {
v.addElement(PROP_AD + Integer.toString(i) + "_" + PROP_METHOD + ";string;" + "A unique,valid OID specified in dot-separated numeric component notation. e.g. 1.3.6.1.5.5.7.48.1 (ocsp), 1.3.6.1.5.5.7.48.2 (caIssuers), 2.16.840.1.113730.1.16.1 (renewal)");
@@ -128,17 +121,17 @@ public class AuthInfoAccessExt extends APolicyRule implements
/**
* Initializes this policy rule.
* <P>
- *
+ *
* The entries may be of the form:
- *
- * ca.Policy.rule.<ruleName>.implName=AuthInfoAccessExt
- * ca.Policy.rule.<ruleName>.enable=true
- * ca.Policy.rule.<ruleName>.predicate=
- *
- * @param config The config store reference
+ *
+ * ca.Policy.rule.<ruleName>.implName=AuthInfoAccessExt
+ * ca.Policy.rule.<ruleName>.enable=true
+ * ca.Policy.rule.<ruleName>.predicate=
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mConfig = config;
}
@@ -153,7 +146,7 @@ public class AuthInfoAccessExt extends APolicyRule implements
//
for (int i = 0;; i++) {
ObjectIdentifier methodOID = null;
- String method = mConfig.getString(PROP_AD +
+ String method = mConfig.getString(PROP_AD +
Integer.toString(i) + "_" + PROP_METHOD, null);
if (method == null)
@@ -162,10 +155,10 @@ public class AuthInfoAccessExt extends APolicyRule implements
if (method.equals(""))
break;
- //
- // method ::= ocsp | caIssuers | <OID>
- // OID ::= [object identifier]
- //
+ //
+ // method ::= ocsp | caIssuers | <OID>
+ // OID ::= [object identifier]
+ //
try {
if (method.equalsIgnoreCase("ocsp")) {
methodOID = ObjectIdentifier.getObjectIdentifier("1.3.6.1.5.5.7.48.1");
@@ -186,17 +179,17 @@ public class AuthInfoAccessExt extends APolicyRule implements
// TAG ::= uriName | dirName
// VALUE ::= [value defined by TAG]
//
- String location_type = mConfig.getString(PROP_AD +
- Integer.toString(i) +
+ String location_type = mConfig.getString(PROP_AD +
+ Integer.toString(i) +
"_" + PROP_LOCATION_TYPE, null);
- String location = mConfig.getString(PROP_AD +
- Integer.toString(i) +
+ String location = mConfig.getString(PROP_AD +
+ Integer.toString(i) +
"_" + PROP_LOCATION, null);
if (location == null)
break;
GeneralName gn = CMS.form_GeneralName(location_type, location);
- Vector<Serializable> e = new Vector<Serializable>();
+ Vector<Serializable> e = new Vector<Serializable>();
e.addElement(methodOID);
e.addElement(gn);
@@ -206,10 +199,10 @@ public class AuthInfoAccessExt extends APolicyRule implements
}
/**
- * If this policy is enabled, add the authority information
- * access extension to the certificate.
+ * If this policy is enabled, add the authority information access extension
+ * to the certificate.
* <P>
- *
+ *
* @param req The request on which to apply policy.
* @return The policy result object.
*/
@@ -221,7 +214,7 @@ public class AuthInfoAccessExt extends APolicyRule implements
IRequest.CERT_INFO);
if (ci == null) {
- setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO", NAME), "");
+ setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO", NAME), "");
return PolicyResult.REJECTED; // unrecoverable error.
}
@@ -229,8 +222,8 @@ public class AuthInfoAccessExt extends APolicyRule implements
certInfo = ci[j];
if (certInfo == null) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("POLICY_UNEXPECTED_POLICY_ERROR", NAME, ""));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR",
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("POLICY_UNEXPECTED_POLICY_ERROR", NAME, ""));
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR",
NAME, "Configuration Info Error"), "");
return PolicyResult.REJECTED; // unrecoverable error.
}
@@ -238,19 +231,19 @@ public class AuthInfoAccessExt extends APolicyRule implements
try {
// Find the extensions in the certInfo
CertificateExtensions extensions = (CertificateExtensions)
- certInfo.get(X509CertInfo.EXTENSIONS);
+ certInfo.get(X509CertInfo.EXTENSIONS);
// add access descriptions
Enumeration<Vector<Serializable>> e = getAccessDescriptions();
if (!e.hasMoreElements()) {
return res;
- }
-
+ }
+
if (extensions == null) {
// create extension if not exist
certInfo.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ new CertificateVersion(CertificateVersion.V3));
extensions = new CertificateExtensions();
certInfo.set(X509CertInfo.EXTENSIONS, extensions);
} else {
@@ -263,12 +256,12 @@ public class AuthInfoAccessExt extends APolicyRule implements
}
// Create the extension
- AuthInfoAccessExtension aiaExt = new
- AuthInfoAccessExtension(mConfig.getBoolean(
- PROP_CRITICAL, false));
+ AuthInfoAccessExtension aiaExt = new
+ AuthInfoAccessExtension(mConfig.getBoolean(
+ PROP_CRITICAL, false));
while (e.hasMoreElements()) {
- Vector<Serializable> ad = e.nextElement();
+ Vector<Serializable> ad = e.nextElement();
ObjectIdentifier oid = (ObjectIdentifier) ad.elementAt(0);
GeneralName gn = (GeneralName) ad.elementAt(1);
@@ -278,17 +271,17 @@ public class AuthInfoAccessExt extends APolicyRule implements
} catch (IOException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("POLICY_UNEXPECTED_POLICY_ERROR", NAME, e.getMessage()));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR",
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR",
NAME, e.getMessage()), "");
return PolicyResult.REJECTED; // unrecoverable error.
} catch (EBaseException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("POLICY_UNEXPECTED_POLICY_ERROR", NAME, e.getMessage()));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR",
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR",
NAME, "Configuration Info Error"), "");
return PolicyResult.REJECTED; // unrecoverable error.
} catch (CertificateException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("POLICY_UNEXPECTED_POLICY_ERROR", NAME, e.getMessage()));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR",
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR",
NAME, "Certificate Info Error"), "");
return PolicyResult.REJECTED; // unrecoverable error.
}
@@ -299,15 +292,15 @@ public class AuthInfoAccessExt extends APolicyRule implements
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getInstanceParams() {
+ public Vector<String> getInstanceParams() {
Vector<String> params = new Vector<String>();
try {
- params.addElement(PROP_CRITICAL + "=" +
- mConfig.getBoolean(PROP_CRITICAL, false));
+ params.addElement(PROP_CRITICAL + "=" +
+ mConfig.getBoolean(PROP_CRITICAL, false));
} catch (EBaseException e) {
params.addElement(PROP_CRITICAL + "=false");
}
@@ -325,46 +318,46 @@ public class AuthInfoAccessExt extends APolicyRule implements
String method = null;
try {
- method = mConfig.getString(PROP_AD +
+ method = mConfig.getString(PROP_AD +
Integer.toString(i) + "_" + PROP_METHOD,
"");
} catch (EBaseException e) {
}
- params.addElement(PROP_AD +
- Integer.toString(i) +
- "_" + PROP_METHOD + "=" + method);
+ params.addElement(PROP_AD +
+ Integer.toString(i) +
+ "_" + PROP_METHOD + "=" + method);
String location_type = null;
try {
- location_type = mConfig.getString(PROP_AD +
- Integer.toString(i) + "_" + PROP_LOCATION_TYPE,
+ location_type = mConfig.getString(PROP_AD +
+ Integer.toString(i) + "_" + PROP_LOCATION_TYPE,
IGeneralNameUtil.GENNAME_CHOICE_URL);
} catch (EBaseException e) {
}
- params.addElement(PROP_AD +
- Integer.toString(i) +
- "_" + PROP_LOCATION_TYPE + "=" + location_type);
+ params.addElement(PROP_AD +
+ Integer.toString(i) +
+ "_" + PROP_LOCATION_TYPE + "=" + location_type);
String location = null;
try {
- location = mConfig.getString(PROP_AD +
- Integer.toString(i) + "_" + PROP_LOCATION,
+ location = mConfig.getString(PROP_AD +
+ Integer.toString(i) + "_" + PROP_LOCATION,
"");
} catch (EBaseException e) {
}
- params.addElement(PROP_AD +
- Integer.toString(i) +
- "_" + PROP_LOCATION + "=" + location);
+ params.addElement(PROP_AD +
+ Integer.toString(i) +
+ "_" + PROP_LOCATION + "=" + location);
}
return params;
}
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getDefaultParams() {
+ public Vector<String> getDefaultParams() {
Vector<String> defParams = new Vector<String>();
defParams.addElement(PROP_CRITICAL + "=false");
@@ -376,14 +369,13 @@ public class AuthInfoAccessExt extends APolicyRule implements
// the CMS.cfg
//
for (int i = 0; i < MAX_AD; i++) {
- defParams.addElement(PROP_AD + Integer.toString(i) +
- "_" + PROP_METHOD + "=");
- defParams.addElement(PROP_AD + Integer.toString(i) +
- "_" + PROP_LOCATION_TYPE + "=" + IGeneralNameUtil.GENNAME_CHOICE_URL);
- defParams.addElement(PROP_AD + Integer.toString(i) +
- "_" + PROP_LOCATION + "=");
+ defParams.addElement(PROP_AD + Integer.toString(i) +
+ "_" + PROP_METHOD + "=");
+ defParams.addElement(PROP_AD + Integer.toString(i) +
+ "_" + PROP_LOCATION_TYPE + "=" + IGeneralNameUtil.GENNAME_CHOICE_URL);
+ defParams.addElement(PROP_AD + Integer.toString(i) +
+ "_" + PROP_LOCATION + "=");
}
return defParams;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/policy/extensions/AuthorityKeyIdentifierExt.java b/pki/base/common/src/com/netscape/cms/policy/extensions/AuthorityKeyIdentifierExt.java
index 7ec05fec..3a651d58 100644
--- a/pki/base/common/src/com/netscape/cms/policy/extensions/AuthorityKeyIdentifierExt.java
+++ b/pki/base/common/src/com/netscape/cms/policy/extensions/AuthorityKeyIdentifierExt.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.extensions;
-
import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.Locale;
@@ -45,21 +44,21 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
- * Authority Public Key Extension Policy
- * Adds the subject public key id extension to certificates.
+ * Authority Public Key Extension Policy Adds the subject public key id
+ * extension to certificates.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public class AuthorityKeyIdentifierExt extends APolicyRule
- implements IEnrollmentPolicy, IExtendedPluginInfo {
+ implements IEnrollmentPolicy, IExtendedPluginInfo {
protected static final String PROP_CRITICAL = "critical";
protected static final String PROP_ALT_KEYID_TYPE = "AltKeyIdType";
@@ -77,7 +76,7 @@ public class AuthorityKeyIdentifierExt extends APolicyRule
protected boolean mCritical = DEF_CRITICAL;
protected String mAltKeyIdType = DEF_ALT_KEYID_TYPE;
- // the extension to add to certs.
+ // the extension to add to certs.
protected AuthorityKeyIdentifierExtension mTheExtension = null;
// instance params for console
@@ -97,28 +96,25 @@ public class AuthorityKeyIdentifierExt extends APolicyRule
}
/**
- * Initializes this policy rule.
- * Reads configuration file and creates a authority key identifier
- * extension to add. Key identifier inside the extension is constructed as
- * the CA's subject key identifier extension if it exists.
- * If it does not exist this can be configured to use:
- * (1) sha-1 hash of the CA's subject public key info
- * (what communicator expects if the CA does not have a subject key
- * identifier extension) or (2) No extension set (3) Empty sequence
- * in Authority Key Identifier extension.
- *
+ * Initializes this policy rule. Reads configuration file and creates a
+ * authority key identifier extension to add. Key identifier inside the
+ * extension is constructed as the CA's subject key identifier extension if
+ * it exists. If it does not exist this can be configured to use: (1) sha-1
+ * hash of the CA's subject public key info (what communicator expects if
+ * the CA does not have a subject key identifier extension) or (2) No
+ * extension set (3) Empty sequence in Authority Key Identifier extension.
+ *
* <P>
- *
+ *
* The entries may be of the form:
- *
- * ca.Policy.rule.<ruleName>.predicate=
- * ca.Policy.rule.<ruleName>.implName=
- * ca.Policy.rule.<ruleName>.enable=true
- *
- * @param config The config store reference
+ *
+ * ca.Policy.rule.<ruleName>.predicate= ca.Policy.rule.<ruleName>.implName=
+ * ca.Policy.rule.<ruleName>.enable=true
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mConfig = config;
mEnabled = mConfig.getBoolean(
@@ -131,44 +127,44 @@ public class AuthorityKeyIdentifierExt extends APolicyRule
if (mAltKeyIdType.equalsIgnoreCase(ALT_KEYID_TYPE_SPKISHA1))
mAltKeyIdType = ALT_KEYID_TYPE_SPKISHA1;
- /*
- else if (mAltKeyIdType.equalsIgnoreCase(ALT_KEYID_TYPE_EMPTY))
- mAltKeyIdType = ALT_KEYID_TYPE_EMPTY;
- */
+ /*
+ * else if (mAltKeyIdType.equalsIgnoreCase(ALT_KEYID_TYPE_EMPTY))
+ * mAltKeyIdType = ALT_KEYID_TYPE_EMPTY;
+ */
else if (mAltKeyIdType.equalsIgnoreCase(ALT_KEYID_TYPE_NONE))
mAltKeyIdType = ALT_KEYID_TYPE_NONE;
else {
log(ILogger.LL_FAILURE, NAME +
- CMS.getLogMessage("CA_UNKNOWN_ALT_KEY_ID_TYPE", mAltKeyIdType));
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE", PROP_ALT_KEYID_TYPE,
+ CMS.getLogMessage("CA_UNKNOWN_ALT_KEY_ID_TYPE", mAltKeyIdType));
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE", PROP_ALT_KEYID_TYPE,
"value must be one of " + ALT_KEYID_TYPE_SPKISHA1 + ", " + ALT_KEYID_TYPE_NONE));
}
// create authority key id extension.
ICertAuthority certAuthority = (ICertAuthority)
- ((IPolicyProcessor) owner).getAuthority();
+ ((IPolicyProcessor) owner).getAuthority();
if (certAuthority == null) {
// should never get here.
String msg = NAME + ": " +
- "Cannot find the Certificate Manager or Registration Manager";
+ "Cannot find the Certificate Manager or Registration Manager";
log(ILogger.LL_FAILURE, CMS.getLogMessage("CA_CANT_FIND_MANAGER"));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR", msg));
}
if (!(certAuthority instanceof ICertificateAuthority)) {
log(ILogger.LL_FAILURE, NAME +
- CMS.getLogMessage("POLICY_INVALID_POLICY", NAME));
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR",
+ CMS.getLogMessage("POLICY_INVALID_POLICY", NAME));
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR",
NAME + " policy can only be used in a Certificate Authority."));
- }
- //CertificateChain caChain = certAuthority.getCACertChain();
- //X509Certificate caCert = caChain.getFirstCertificate();
+ }
+ // CertificateChain caChain = certAuthority.getCACertChain();
+ // X509Certificate caCert = caChain.getFirstCertificate();
X509CertImpl caCert = certAuthority.getCACert();
- if( caCert == null || CMS.isPreOpMode() ) {
+ if (caCert == null || CMS.isPreOpMode()) {
return;
}
- KeyIdentifier keyId = formKeyIdentifier(caCert);
+ KeyIdentifier keyId = formKeyIdentifier(caCert);
if (keyId != null) {
try {
@@ -176,7 +172,7 @@ public class AuthorityKeyIdentifierExt extends APolicyRule
mCritical, keyId, null, null);
} catch (IOException e) {
String msg = NAME + ": " +
- "Error forming Authority Key Identifier extension: " + e;
+ "Error forming Authority Key Identifier extension: " + e;
log(ILogger.LL_FAILURE, CMS.getLogMessage("POLICY_ERROR_AUTHORITY_KEY_ID_1", NAME));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR", msg));
@@ -184,33 +180,33 @@ public class AuthorityKeyIdentifierExt extends APolicyRule
} else {
}
- // form instance params
+ // form instance params
mInstanceParams.addElement(PROP_CRITICAL + "=" + mCritical);
mInstanceParams.addElement(PROP_ALT_KEYID_TYPE + "=" + mAltKeyIdType);
}
/**
- * Adds Authority Key Identifier Extension to a certificate.
- * If the extension is already there, accept it if it's from the agent,
- * else replace it.
- *
- * @param req The request on which to apply policy.
+ * Adds Authority Key Identifier Extension to a certificate. If the
+ * extension is already there, accept it if it's from the agent, else
+ * replace it.
+ *
+ * @param req The request on which to apply policy.
* @return The policy result object.
*/
public PolicyResult apply(IRequest req) {
// get certInfo from request.
- X509CertInfo[] ci =
- req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
+ X509CertInfo[] ci =
+ req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
if (ci == null || ci[0] == null) {
setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO", NAME), "");
- return PolicyResult.REJECTED;
+ return PolicyResult.REJECTED;
}
for (int i = 0; i < ci.length; i++) {
PolicyResult certResult = applyCert(req, ci[i]);
- if (certResult == PolicyResult.REJECTED)
+ if (certResult == PolicyResult.REJECTED)
return certResult;
}
return PolicyResult.ACCEPTED;
@@ -219,11 +215,11 @@ public class AuthorityKeyIdentifierExt extends APolicyRule
public PolicyResult applyCert(IRequest req, X509CertInfo certInfo) {
try {
- // if authority key id extension already exists, leave it if
+ // if authority key id extension already exists, leave it if
// from agent. else replace it.
AuthorityKeyIdentifierExtension authorityKeyIdExt = null;
CertificateExtensions extensions = (CertificateExtensions)
- certInfo.get(X509CertInfo.EXTENSIONS);
+ certInfo.get(X509CertInfo.EXTENSIONS);
try {
if (extensions != null) {
@@ -231,65 +227,66 @@ public class AuthorityKeyIdentifierExt extends APolicyRule
extensions.get(AuthorityKeyIdentifierExtension.class.getSimpleName());
}
} catch (IOException e) {
- // extension isn't there.
+ // extension isn't there.
}
if (authorityKeyIdExt != null) {
if (agentApproved(req)) {
CMS.debug(
- "AuthorityKeyIdentifierKeyExt: agent approved request id " + req.getRequestId() +
- " already has authority key id extension with value " +
- authorityKeyIdExt);
+ "AuthorityKeyIdentifierKeyExt: agent approved request id " + req.getRequestId() +
+ " already has authority key id extension with value " +
+ authorityKeyIdExt);
return PolicyResult.ACCEPTED;
} else {
CMS.debug(
- "AuthorityKeyIdentifierKeyExt: request id from user " + req.getRequestId() +
- " had authority key identifier - deleted");
+ "AuthorityKeyIdentifierKeyExt: request id from user " + req.getRequestId() +
+ " had authority key identifier - deleted");
extensions.delete(AuthorityKeyIdentifierExtension.class.getSimpleName());
}
}
- // if no authority key identifier should be set b/c CA does not
- // have a subject key identifier, return here.
- if (mTheExtension == null)
+ // if no authority key identifier should be set b/c CA does not
+ // have a subject key identifier, return here.
+ if (mTheExtension == null)
return PolicyResult.ACCEPTED;
- // add authority key id extension.
+ // add authority key id extension.
if (extensions == null) {
certInfo.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ new CertificateVersion(CertificateVersion.V3));
extensions = new CertificateExtensions();
certInfo.set(X509CertInfo.EXTENSIONS, extensions);
}
extensions.set(
- AuthorityKeyIdentifierExtension.class.getSimpleName(), mTheExtension);
+ AuthorityKeyIdentifierExtension.class.getSimpleName(), mTheExtension);
CMS.debug(
- "AuthorityKeyIdentifierKeyExt: added authority key id ext to request " + req.getRequestId());
+ "AuthorityKeyIdentifierKeyExt: added authority key id ext to request " + req.getRequestId());
return PolicyResult.ACCEPTED;
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("POLICY_UNEXPECTED_POLICY_ERROR", NAME, e.toString()));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR",
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("POLICY_UNEXPECTED_POLICY_ERROR", NAME, e.toString()));
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR",
NAME, e.getMessage()), "");
return PolicyResult.REJECTED;
} catch (CertificateException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("BASE_INVALID_CERT", e.getMessage()));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR",
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("BASE_INVALID_CERT", e.getMessage()));
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR",
NAME, "Certificate Info Error"), "");
return PolicyResult.REJECTED;
}
}
/**
- * Form the Key Identifier in the Authority Key Identifier extension.
- * from the CA's cert.
+ * Form the Key Identifier in the Authority Key Identifier extension. from
+ * the CA's cert.
* <p>
+ *
* @param caCertImpl Certificate Info
* @return A Key Identifier.
* @throws com.netscape.certsrv.base.EBaseException on error
*/
protected KeyIdentifier formKeyIdentifier(X509CertImpl caCertImpl)
- throws EBaseException {
+ throws EBaseException {
KeyIdentifier keyId = null;
// get CA's certInfo.
@@ -298,50 +295,50 @@ public class AuthorityKeyIdentifierExt extends APolicyRule
try {
certInfo = (X509CertInfo) caCertImpl.get(
X509CertImpl.NAME + "." + X509CertImpl.INFO);
- if (certInfo == null) {
+ if (certInfo == null) {
String msg = "Bad CA certificate encountered. " +
- "TBS Certificate missing.";
+ "TBS Certificate missing.";
log(ILogger.LL_FAILURE, CMS.getLogMessage("BASE_INVALID_CERT_FORMAT"));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR", NAME + ": " + msg));
}
} catch (CertificateException e) {
log(ILogger.LL_FAILURE, NAME + ": " +
- CMS.getLogMessage("BASE_DECODE_CERT_FAILED_1", e.toString()));
+ CMS.getLogMessage("BASE_DECODE_CERT_FAILED_1", e.toString()));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR",
NAME + " Error decoding the CA Certificate: " + e));
}
// get Key Id from CA's Subject Key Id extension in CA's CertInfo.
keyId = getKeyIdentifier(certInfo);
- if (keyId != null)
+ if (keyId != null)
return keyId;
- // if none exists use the configured alternate.
+ // if none exists use the configured alternate.
if (mAltKeyIdType == ALT_KEYID_TYPE_SPKISHA1) {
keyId = formSpkiSHA1KeyId(certInfo);
} /*
- else if (mAltKeyIdType == ALT_KEYID_TYPE_EMPTY) {
- keyId = formEmptyKeyId(certInfo);
- }
- */ else if (mAltKeyIdType == ALT_KEYID_TYPE_NONE) {
+ * else if (mAltKeyIdType == ALT_KEYID_TYPE_EMPTY) { keyId =
+ * formEmptyKeyId(certInfo); }
+ */else if (mAltKeyIdType == ALT_KEYID_TYPE_NONE) {
keyId = null;
} else {
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
- mAltKeyIdType,
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
+ mAltKeyIdType,
"Unknown Alternate Key Identifier type."));
}
return keyId;
}
/**
- * Get the Key Identifier in a subject key identifier extension from a
+ * Get the Key Identifier in a subject key identifier extension from a
* CertInfo.
+ *
* @param certInfo the CertInfo structure.
* @return Key Identifier in a Subject Key Identifier extension if any.
*/
- protected KeyIdentifier getKeyIdentifier(X509CertInfo certInfo)
- throws EBaseException {
+ protected KeyIdentifier getKeyIdentifier(X509CertInfo certInfo)
+ throws EBaseException {
CertificateExtensions exts = null;
SubjectKeyIdentifierExtension subjKeyIdExt = null;
KeyIdentifier keyId = null;
@@ -357,7 +354,7 @@ public class AuthorityKeyIdentifierExt extends APolicyRule
CMS.debug(NAME + ": " + "No extensions found. Error " + e);
return null;
}
- if (exts == null)
+ if (exts == null)
return null;
try {
@@ -366,7 +363,7 @@ public class AuthorityKeyIdentifierExt extends APolicyRule
} catch (IOException e) {
// extension isn't there.
CMS.debug(
- "AuthorityKeyIdentifierKeyExt: No Subject Key Identifier Extension found. Error: " + e);
+ "AuthorityKeyIdentifierKeyExt: No Subject Key Identifier Extension found. Error: " + e);
return null;
}
if (subjKeyIdExt == null)
@@ -376,9 +373,9 @@ public class AuthorityKeyIdentifierExt extends APolicyRule
keyId = (KeyIdentifier) subjKeyIdExt.get(
SubjectKeyIdentifierExtension.KEY_ID);
} catch (IOException e) {
- // no key identifier in subject key id extension.
+ // no key identifier in subject key id extension.
String msg = NAME + ": " +
- "Bad Subject Key Identifier Extension found. Error: " + e;
+ "Bad Subject Key Identifier Extension found. Error: " + e;
log(ILogger.LL_FAILURE, CMS.getLogMessage("POLICY_ERROR_AUTHORITY_KEY_ID_1", NAME));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR", msg));
@@ -388,40 +385,39 @@ public class AuthorityKeyIdentifierExt extends APolicyRule
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getInstanceParams() {
+ public Vector<String> getInstanceParams() {
return mInstanceParams;
}
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getDefaultParams() {
+ public Vector<String> getDefaultParams() {
return mDefaultParams;
}
public String[] getExtendedPluginInfo(Locale locale) {
String[] params = {
PROP_CRITICAL + ";boolean;" +
- "RFC 2459 recommendation: MUST NOT be marked critical.",
+ "RFC 2459 recommendation: MUST NOT be marked critical.",
PROP_ALT_KEYID_TYPE + ";" +
- "choice(" + ALT_KEYID_TYPE_SPKISHA1 + "," + ALT_KEYID_TYPE_NONE + ");" +
- "Specifies whether to use a SHA1 hash of the CA's subject " +
- "public key info for key identifier or leave out the " +
- "authority key identifier extension if the CA certificate " +
- "does not have a Subject Key Identifier extension.",
+ "choice(" + ALT_KEYID_TYPE_SPKISHA1 + "," + ALT_KEYID_TYPE_NONE + ");" +
+ "Specifies whether to use a SHA1 hash of the CA's subject " +
+ "public key info for key identifier or leave out the " +
+ "authority key identifier extension if the CA certificate " +
+ "does not have a Subject Key Identifier extension.",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-authkeyid",
+ ";configuration-policyrules-authkeyid",
IExtendedPluginInfo.HELP_TEXT +
- ";Adds Authority Key Identifier Extension. " +
- "See RFC 2459 (4.2.1.1)"
+ ";Adds Authority Key Identifier Extension. " +
+ "See RFC 2459 (4.2.1.1)"
};
return params;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/policy/extensions/BasicConstraintsExt.java b/pki/base/common/src/com/netscape/cms/policy/extensions/BasicConstraintsExt.java
index 1636902d..56062012 100644
--- a/pki/base/common/src/com/netscape/cms/policy/extensions/BasicConstraintsExt.java
+++ b/pki/base/common/src/com/netscape/cms/policy/extensions/BasicConstraintsExt.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.extensions;
-
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
@@ -47,48 +46,46 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
- * Basic Constraints policy.
- * Adds the Basic constraints extension.
+ * Basic Constraints policy. Adds the Basic constraints extension.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public class BasicConstraintsExt extends APolicyRule
- implements IEnrollmentPolicy, IExtendedPluginInfo {
+ implements IEnrollmentPolicy, IExtendedPluginInfo {
protected static final String PROP_MAXPATHLEN = "maxPathLen";
protected static final String PROP_IS_CA = "isCA";
protected static final String PROP_IS_CRITICAL = "critical";
protected static final String ARG_PATHLEN = "BasicConstraintsPathLen";
- protected int mMaxPathLen = 0; // < 0 means unlimited
+ protected int mMaxPathLen = 0; // < 0 means unlimited
protected String mOrigMaxPathLen = ""; // for UI display only
protected boolean mCritical = true;
- protected int mDefaultMaxPathLen = 0; // depends on the CA's path length.
- protected int mCAPathLen = 0;
+ protected int mDefaultMaxPathLen = 0; // depends on the CA's path length.
+ protected int mCAPathLen = 0;
protected boolean mRemoveExt = true;
protected boolean mIsCA = true;
public static final boolean DEFAULT_CRITICALITY = true;
/**
- * Adds the basic constraints extension as a critical extension in
- * CA certificates i.e. certype is ca, with either a requested
- * or configured path len.
- * The requested or configured path length cannot be greater than
- * or equal to the CA's basic constraints path length.
- * If the CA path length is 0, all requests for CA certs are rejected.
+ * Adds the basic constraints extension as a critical extension in CA
+ * certificates i.e. certype is ca, with either a requested or configured
+ * path len. The requested or configured path length cannot be greater than
+ * or equal to the CA's basic constraints path length. If the CA path length
+ * is 0, all requests for CA certs are rejected.
*/
public BasicConstraintsExt() {
NAME = "BasicConstraintsExt";
- DESC =
+ DESC =
"Sets critical basic constraints extension in subordinate CA certs";
}
@@ -96,54 +93,54 @@ public class BasicConstraintsExt extends APolicyRule
* Initializes this policy rule.
* <p>
* The entries may be of the form:
- *
- * ca.Policy.rule.<ruleName>.implName=BasicConstraintsExtImpl
- * ca.Policy.rule.<ruleName>.pathLen=<n>, -1 for undefined.
- * ca.Policy.rule.<ruleName>.enable=true
- *
- * @param config The config store reference
+ *
+ * ca.Policy.rule.<ruleName>.implName=BasicConstraintsExtImpl
+ * ca.Policy.rule.<ruleName>.pathLen=<n>, -1 for undefined.
+ * ca.Policy.rule.<ruleName>.enable=true
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
// get the CA's path len to check against configured max path len.
ICertAuthority certAuthority = (ICertAuthority)
- ((IPolicyProcessor) owner).getAuthority();
+ ((IPolicyProcessor) owner).getAuthority();
if (certAuthority == null) {
// should never get here.
log(ILogger.LL_FAILURE, CMS.getLogMessage("CA_CANT_FIND_MANAGER"));
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR",
"Cannot find the Certificate Manager or Registration Manager"));
}
if (certAuthority instanceof IRegistrationAuthority) {
- log(ILogger.LL_WARN,
- "default basic constraints extension path len to -1.");
+ log(ILogger.LL_WARN,
+ "default basic constraints extension path len to -1.");
mCAPathLen = -1;
} else {
CertificateChain caChain = certAuthority.getCACertChain();
- if( caChain == null || CMS.isPreOpMode() ) {
+ if (caChain == null || CMS.isPreOpMode()) {
return;
}
X509Certificate caCert = caChain.getFirstCertificate();
mCAPathLen = caCert.getBasicConstraints();
}
- // set default to one less than the CA's pathlen or 0 if CA's
- // pathlen is 0.
+ // set default to one less than the CA's pathlen or 0 if CA's
+ // pathlen is 0.
// If it's unlimited default the max pathlen also to unlimited.
- if (mCAPathLen < 0)
+ if (mCAPathLen < 0)
mDefaultMaxPathLen = -1;
- else if (mCAPathLen > 0)
+ else if (mCAPathLen > 0)
mDefaultMaxPathLen = mCAPathLen - 1;
- else // (mCAPathLen == 0)
+ else // (mCAPathLen == 0)
{
- log(ILogger.LL_WARN,
- CMS.getLogMessage("POLICY_PATHLEN_ZERO"));
- //return;
+ log(ILogger.LL_WARN,
+ CMS.getLogMessage("POLICY_PATHLEN_ZERO"));
+ // return;
}
- // get configured max path len, use defaults if not configured.
+ // get configured max path len, use defaults if not configured.
boolean pathLenConfigured = true;
try {
@@ -151,19 +148,19 @@ public class BasicConstraintsExt extends APolicyRule
mIsCA = config.getBoolean(PROP_IS_CA, true);
mMaxPathLen = config.getInteger(PROP_MAXPATHLEN);
if (mMaxPathLen < 0) {
- log(ILogger.LL_MISCONF,
- CMS.getLogMessage("POLICY_INVALID_MAXPATHLEN_4", "",
- String.valueOf(mMaxPathLen)));
+ log(ILogger.LL_MISCONF,
+ CMS.getLogMessage("POLICY_INVALID_MAXPATHLEN_4", "",
+ String.valueOf(mMaxPathLen)));
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_INVALID_MAXPATHLEN_1",
- NAME, String.valueOf(mMaxPathLen)));
+ NAME, String.valueOf(mMaxPathLen)));
}
mOrigMaxPathLen = Integer.toString(mMaxPathLen);
} catch (EBaseException e) {
- if (!(e instanceof EPropertyNotFound) &&
- !(e instanceof EPropertyNotDefined)) {
- log(ILogger.LL_MISCONF,
- CMS.getLogMessage("POLICY_INVALID_MAXPATHLEN"));
+ if (!(e instanceof EPropertyNotFound) &&
+ !(e instanceof EPropertyNotDefined)) {
+ log(ILogger.LL_MISCONF,
+ CMS.getLogMessage("POLICY_INVALID_MAXPATHLEN"));
throw e;
}
@@ -175,53 +172,53 @@ public class BasicConstraintsExt extends APolicyRule
// check if configured path len is valid.
if (pathLenConfigured) {
- // if CA's pathlen is unlimited, any max pathlen is ok.
- // else maxPathlen must be at most one less than the CA's
- // pathlen or 0 if CA's pathlen is 0.
-
- if (mCAPathLen > 0 &&
- (mMaxPathLen >= mCAPathLen || mMaxPathLen < 0)) {
- String maxStr = (mMaxPathLen < 0) ?
- String.valueOf(mMaxPathLen) + "(unlimited)" :
- String.valueOf(mMaxPathLen);
-
- log(ILogger.LL_MISCONF,
- CMS.getLogMessage("POLICY_MAXPATHLEN_TOO_BIG_3", "",
- maxStr,
- String.valueOf(mCAPathLen)));
+ // if CA's pathlen is unlimited, any max pathlen is ok.
+ // else maxPathlen must be at most one less than the CA's
+ // pathlen or 0 if CA's pathlen is 0.
+
+ if (mCAPathLen > 0 &&
+ (mMaxPathLen >= mCAPathLen || mMaxPathLen < 0)) {
+ String maxStr = (mMaxPathLen < 0) ?
+ String.valueOf(mMaxPathLen) + "(unlimited)" :
+ String.valueOf(mMaxPathLen);
+
+ log(ILogger.LL_MISCONF,
+ CMS.getLogMessage("POLICY_MAXPATHLEN_TOO_BIG_3", "",
+ maxStr,
+ String.valueOf(mCAPathLen)));
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_MAXPATHLEN_TOO_BIG_1",
- NAME, maxStr, Integer.toString(mCAPathLen)));
+ NAME, maxStr, Integer.toString(mCAPathLen)));
} else if (mCAPathLen == 0 && mMaxPathLen != 0) {
- log(ILogger.LL_MISCONF,
- CMS.getLogMessage("POLICY_INVALID_MAXPATHLEN_2", "", String.valueOf(mMaxPathLen)));
+ log(ILogger.LL_MISCONF,
+ CMS.getLogMessage("POLICY_INVALID_MAXPATHLEN_2", "", String.valueOf(mMaxPathLen)));
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_INVALID_MAXPATHLEN",
- NAME, String.valueOf(mMaxPathLen)));
+ NAME, String.valueOf(mMaxPathLen)));
}
}
}
/**
- * Checks if the basic contraints extension in certInfo is valid and
- * add the basic constraints extension for CA certs if none exists.
- * Non-CA certs do not get a basic constraints extension.
- *
- * @param req The request on which to apply policy.
+ * Checks if the basic contraints extension in certInfo is valid and add the
+ * basic constraints extension for CA certs if none exists. Non-CA certs do
+ * not get a basic constraints extension.
+ *
+ * @param req The request on which to apply policy.
* @return The policy result object.
*/
public PolicyResult apply(IRequest req) {
PolicyResult res = PolicyResult.ACCEPTED;
// get cert info.
- X509CertInfo[] ci =
- req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
+ X509CertInfo[] ci =
+ req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
X509CertInfo certInfo = null;
if (ci == null || (certInfo = ci[0]) == null) {
- setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO", NAME), "");
+ setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO", NAME), "");
return PolicyResult.REJECTED; // unrecoverable error.
}
@@ -229,24 +226,22 @@ public class BasicConstraintsExt extends APolicyRule
boolean isCA = mIsCA;
/**
- boolean isCA = false;
- String type = (String)req.get(IRequest.HTTP_PARAMS, IRequest.CERT_TYPE);
- if (type != null && type.equalsIgnoreCase(IRequest.CA_CERT)) {
- isCA = true;
- }
+ * boolean isCA = false; String type =
+ * (String)req.get(IRequest.HTTP_PARAMS, IRequest.CERT_TYPE); if (type
+ * != null && type.equalsIgnoreCase(IRequest.CA_CERT)) { isCA = true; }
**/
for (int i = 0; i < ci.length; i++) {
PolicyResult certResult = applyCert(req, isCA, certInfo);
- if (certResult == PolicyResult.REJECTED)
+ if (certResult == PolicyResult.REJECTED)
return certResult;
}
return PolicyResult.ACCEPTED;
}
public PolicyResult applyCert(
- IRequest req, boolean isCA, X509CertInfo certInfo) {
+ IRequest req, boolean isCA, X509CertInfo certInfo) {
// get basic constraints extension from cert info if any.
CertificateExtensions extensions = null;
@@ -266,19 +261,19 @@ public class BasicConstraintsExt extends APolicyRule
// no extensions or basic constraints extension.
}
- // for non-CA certs, pkix says it SHOULD NOT have the extension
+ // for non-CA certs, pkix says it SHOULD NOT have the extension
// so remove it.
if (!isCA) {
if (extensions == null) {
try {
// create extensions set if none.
- certInfo.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ certInfo.set(X509CertInfo.VERSION,
+ new CertificateVersion(CertificateVersion.V3));
extensions = new CertificateExtensions();
certInfo.set(X509CertInfo.EXTENSIONS, extensions);
} catch (CertificateException e) {
} catch (IOException e) {
- // not possible
+ // not possible
}
}
if (basicExt != null) {
@@ -293,54 +288,54 @@ public class BasicConstraintsExt extends APolicyRule
try {
critExt = new BasicConstraintsExtension(isCA, mCritical, mMaxPathLen);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("POLICY_ERROR_BASIC_CONSTRAINTS_2",
- e.toString()));
- setError(req,
- CMS.getUserMessage("CMS_POLICY_BASIC_CONSTRAINTS_ERROR", NAME), "");
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("POLICY_ERROR_BASIC_CONSTRAINTS_2",
+ e.toString()));
+ setError(req,
+ CMS.getUserMessage("CMS_POLICY_BASIC_CONSTRAINTS_ERROR", NAME), "");
return PolicyResult.REJECTED; // unrecoverable error.
}
-
+
try {
extensions.set(BasicConstraintsExtension.class.getSimpleName(), critExt);
} catch (IOException e) {
}
CMS.debug(
- "BasicConstraintsExt: PolicyRule BasicConstraintsExt: added the extension to request " +
- req.getRequestId());
+ "BasicConstraintsExt: PolicyRule BasicConstraintsExt: added the extension to request " +
+ req.getRequestId());
return PolicyResult.ACCEPTED;
}
// For CA certs, check if existing extension is valid, and adjust.
- // Extension must be marked critial and pathlen must be < CA's pathlen.
+ // Extension must be marked critial and pathlen must be < CA's pathlen.
// if CA's pathlen is 0 all ca certs are rejected.
if (mCAPathLen == 0) {
- // reject all subordinate CA cert requests because CA's
+ // reject all subordinate CA cert requests because CA's
// path length is 0.
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("POLICY_NO_SUB_CA_CERTS_ALLOWED_1", NAME));
- setError(req, CMS.getUserMessage("CMS_POLICY_NO_SUB_CA_CERTS_ALLOWED", NAME), "");
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("POLICY_NO_SUB_CA_CERTS_ALLOWED_1", NAME));
+ setError(req, CMS.getUserMessage("CMS_POLICY_NO_SUB_CA_CERTS_ALLOWED", NAME), "");
return PolicyResult.REJECTED;
}
- if (basicExt != null) {
+ if (basicExt != null) {
try {
- boolean extIsCA =
- ((Boolean) basicExt.get(BasicConstraintsExtension.IS_CA)).booleanValue();
- int pathLen =
- ((Integer) basicExt.get(BasicConstraintsExtension.PATH_LEN)).intValue();
+ boolean extIsCA =
+ ((Boolean) basicExt.get(BasicConstraintsExtension.IS_CA)).booleanValue();
+ int pathLen =
+ ((Integer) basicExt.get(BasicConstraintsExtension.PATH_LEN)).intValue();
if (mMaxPathLen > -1) {
if (pathLen > mMaxPathLen || pathLen < 0) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("POLICY_MAXPATHLEN_TOO_BIG_3", NAME, "unlimited", String.valueOf(pathLen)));
- if (pathLen < 0)
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("POLICY_MAXPATHLEN_TOO_BIG_3", NAME, "unlimited", String.valueOf(pathLen)));
+ if (pathLen < 0)
setError(req, CMS.getUserMessage("CMS_POLICY_MAXPATHLEN_TOO_BIG",
NAME, "unlimited", Integer.toString(mMaxPathLen)), "");
else
setError(req, CMS.getUserMessage("CMS_POLICY_MAXPATHLEN_TOO_BIG",
- NAME, Integer.toString(pathLen),
+ NAME, Integer.toString(pathLen),
Integer.toString(mMaxPathLen)), "");
return PolicyResult.REJECTED;
}
@@ -348,20 +343,20 @@ public class BasicConstraintsExt extends APolicyRule
// adjust isCA field
if (!extIsCA) {
- basicExt.set(BasicConstraintsExtension.IS_CA,
- Boolean.valueOf(true));
+ basicExt.set(BasicConstraintsExtension.IS_CA,
+ Boolean.valueOf(true));
}
// adjust path length field.
if (mMaxPathLen == 0) {
if (pathLen != 0) {
- basicExt.set(BasicConstraintsExtension.PATH_LEN,
- Integer.valueOf(0));
+ basicExt.set(BasicConstraintsExtension.PATH_LEN,
+ Integer.valueOf(0));
pathLen = 0;
}
} else if (mMaxPathLen > 0 && pathLen > mMaxPathLen) {
- basicExt.set(BasicConstraintsExtension.PATH_LEN,
- Integer.valueOf(mMaxPathLen));
+ basicExt.set(BasicConstraintsExtension.PATH_LEN,
+ Integer.valueOf(mMaxPathLen));
pathLen = mMaxPathLen;
}
@@ -372,10 +367,10 @@ public class BasicConstraintsExt extends APolicyRule
try {
critExt = new BasicConstraintsExtension(isCA, mCritical, pathLen);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("POLICY_ERROR_BASIC_CONSTRAINTS_1", NAME));
- setError(req,
- CMS.getUserMessage("CMS_POLICY_BASIC_CONSTRAINTS_ERROR", NAME), "");
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("POLICY_ERROR_BASIC_CONSTRAINTS_1", NAME));
+ setError(req,
+ CMS.getUserMessage("CMS_POLICY_BASIC_CONSTRAINTS_ERROR", NAME), "");
return PolicyResult.REJECTED; // unrecoverable error.
}
extensions.delete(BasicConstraintsExtension.class.getSimpleName());
@@ -385,8 +380,8 @@ public class BasicConstraintsExt extends APolicyRule
// not possible in these cases.
}
CMS.debug(
- "BasicConstraintsExt: PolicyRule BasicConstraintsExt: added the extension to request " +
- req.getRequestId());
+ "BasicConstraintsExt: PolicyRule BasicConstraintsExt: added the extension to request " +
+ req.getRequestId());
return PolicyResult.ACCEPTED;
}
@@ -394,14 +389,14 @@ public class BasicConstraintsExt extends APolicyRule
if (extensions == null) {
try {
// create extensions set if none.
- certInfo.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ certInfo.set(X509CertInfo.VERSION,
+ new CertificateVersion(CertificateVersion.V3));
extensions = new CertificateExtensions();
certInfo.set(X509CertInfo.EXTENSIONS, extensions);
} catch (CertificateException e) {
// not possible
} catch (IOException e) {
- // not possible
+ // not possible
}
}
@@ -413,29 +408,29 @@ public class BasicConstraintsExt extends APolicyRule
if (reqPathLenStr == null) {
reqPathLen = mMaxPathLen;
} else {
- try {
- reqPathLen = Integer.parseInt(reqPathLenStr);
+ try {
+ reqPathLen = Integer.parseInt(reqPathLenStr);
if ((mMaxPathLen == 0 && reqPathLen != 0) ||
- (mMaxPathLen > 0 &&
+ (mMaxPathLen > 0 &&
(reqPathLen > mMaxPathLen || reqPathLen < 0))) {
- String plenStr =
- ((reqPathLen < 0) ?
- reqPathLenStr + "(unlimited)" : reqPathLenStr);
-
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("POLICY_PATHLEN_TOO_BIG_3", plenStr,
- String.valueOf(mMaxPathLen)));
- setError(req,
- CMS.getUserMessage("CMS_POLICY_PATHLEN_TOO_BIG",
- NAME, plenStr, String.valueOf(mMaxPathLen)), "");
+ String plenStr =
+ ((reqPathLen < 0) ?
+ reqPathLenStr + "(unlimited)" : reqPathLenStr);
+
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("POLICY_PATHLEN_TOO_BIG_3", plenStr,
+ String.valueOf(mMaxPathLen)));
+ setError(req,
+ CMS.getUserMessage("CMS_POLICY_PATHLEN_TOO_BIG",
+ NAME, plenStr, String.valueOf(mMaxPathLen)), "");
return PolicyResult.REJECTED;
}
} catch (NumberFormatException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("POLICY_INVALID_PATHLEN_FORMAT_2", NAME, reqPathLenStr));
- setError(req, CMS.getUserMessage("CMS_POLICY_INVALID_PATHLEN_FORMAT",
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("POLICY_INVALID_PATHLEN_FORMAT_2", NAME, reqPathLenStr));
+ setError(req, CMS.getUserMessage("CMS_POLICY_INVALID_PATHLEN_FORMAT",
NAME, reqPathLenStr), "");
- return PolicyResult.REJECTED;
+ return PolicyResult.REJECTED;
}
}
BasicConstraintsExtension newExt;
@@ -443,29 +438,29 @@ public class BasicConstraintsExt extends APolicyRule
try {
newExt = new BasicConstraintsExtension(isCA, mCritical, reqPathLen);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("POLICY_ERROR_BASIC_CONSTRAINTS_2", e.toString()));
- setError(req,
- CMS.getUserMessage("CMS_POLICY_BASIC_CONSTRAINTS_ERROR", NAME), "");
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("POLICY_ERROR_BASIC_CONSTRAINTS_2", e.toString()));
+ setError(req,
+ CMS.getUserMessage("CMS_POLICY_BASIC_CONSTRAINTS_ERROR", NAME), "");
return PolicyResult.REJECTED; // unrecoverable error.
}
try {
extensions.set(BasicConstraintsExtension.class.getSimpleName(), newExt);
- }catch (IOException e) {
+ } catch (IOException e) {
// doesn't happen.
}
CMS.debug(
- "BasicConstraintsExt: added the extension to request " +
- req.getRequestId());
+ "BasicConstraintsExt: added the extension to request " +
+ req.getRequestId());
return PolicyResult.ACCEPTED;
}
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getInstanceParams() {
+ public Vector<String> getInstanceParams() {
Vector<String> params = new Vector<String>();
// Because of one of the UI bugs 385273, we should leave the empty space
@@ -478,10 +473,10 @@ public class BasicConstraintsExt extends APolicyRule
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getDefaultParams() {
+ public Vector<String> getDefaultParams() {
Vector<String> defParams = new Vector<String>();
defParams.addElement(PROP_IS_CRITICAL + "=true");
@@ -494,17 +489,16 @@ public class BasicConstraintsExt extends APolicyRule
String[] params = {
PROP_MAXPATHLEN + ";number;'0' means : no subordinates allowed, 'n' means : at most n subordinates allowed.",
PROP_IS_CRITICAL + ";boolean;" +
- "RFC 2459 recommendation: MUST be critical in CA certs, SHOULD NOT appear in EE certs.",
+ "RFC 2459 recommendation: MUST be critical in CA certs, SHOULD NOT appear in EE certs.",
PROP_IS_CA + ";boolean;" +
- "Identifies the subject of the certificate is a CA or not.",
+ "Identifies the subject of the certificate is a CA or not.",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-basicconstraints",
+ ";configuration-policyrules-basicconstraints",
IExtendedPluginInfo.HELP_TEXT +
- ";Adds the Basic Constraints extension. See RFC 2459 (4.2.1.10)"
+ ";Adds the Basic Constraints extension. See RFC 2459 (4.2.1.10)"
};
return params;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/policy/extensions/CRLDistributionPointsExt.java b/pki/base/common/src/com/netscape/cms/policy/extensions/CRLDistributionPointsExt.java
index 05d4a28e..688997df 100644
--- a/pki/base/common/src/com/netscape/cms/policy/extensions/CRLDistributionPointsExt.java
+++ b/pki/base/common/src/com/netscape/cms/policy/extensions/CRLDistributionPointsExt.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.extensions;
-
import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.Hashtable;
@@ -50,18 +49,18 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
- * The type of the distribution point or issuer name. The name is expressed
- * as a simple string in the configuration file, so this attribute is needed
- * to tell whether the simple string should be stored in an X.500 Name,
- * a URL, or an RDN.
+ * The type of the distribution point or issuer name. The name is expressed as a
+ * simple string in the configuration file, so this attribute is needed to tell
+ * whether the simple string should be stored in an X.500 Name, a URL, or an
+ * RDN.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
@@ -69,7 +68,7 @@ class NameType {
private NameType() {
} // no default constructor
- private String stringRep; // string representation of this type
+ private String stringRep; // string representation of this type
private NameType(String s) {
map.put(s, this);
@@ -79,8 +78,8 @@ class NameType {
private static Hashtable<String, NameType> map = new Hashtable<String, NameType>();
/**
- * Looks up a NameType from its string representation. Returns null
- * if no matching NameType was found.
+ * Looks up a NameType from its string representation. Returns null if no
+ * matching NameType was found.
*/
public static NameType fromString(String s) {
return map.get(s);
@@ -93,14 +92,13 @@ class NameType {
public static final NameType DIRECTORY_NAME = new NameType("DirectoryName");
public static final NameType URI = new NameType("URI");
public static final NameType RELATIVE_TO_ISSUER =
- new NameType("RelativeToIssuer");
+ new NameType("RelativeToIssuer");
}
-
/**
- * These are the parameters that may be given in the configuration file
- * for each distribution point. They are parsed by DPParamsToDP().
- * Any of them may be null.
+ * These are the parameters that may be given in the configuration file for each
+ * distribution point. They are parsed by DPParamsToDP(). Any of them may be
+ * null.
*/
class DistPointParams {
public String pointName;
@@ -124,13 +122,12 @@ class DistPointParams {
}
-
/**
- * CRL Distribution Points policy.
- * Adds the CRL Distribution Points extension to the certificate.
+ * CRL Distribution Points policy. Adds the CRL Distribution Points extension to
+ * the certificate.
*/
public class CRLDistributionPointsExt extends APolicyRule
- implements IEnrollmentPolicy, IExtendedPluginInfo {
+ implements IEnrollmentPolicy, IExtendedPluginInfo {
public static final String PROP_IS_CRITICAL = "critical";
public static final String PROP_NUM_POINTS = "numPoints";
@@ -173,29 +170,29 @@ public class CRLDistributionPointsExt extends APolicyRule
// should replace MAX_POINTS with mNumPoints if bug 385118 is fixed
for (int i = 0; i < MAX_POINTS; i++) {
v.addElement(PROP_POINT_TYPE + Integer.toString(i) + ";choice(" +
- "DirectoryName,URI,RelativeToIssuer);" +
- "The type of the CRL distribution point.");
+ "DirectoryName,URI,RelativeToIssuer);" +
+ "The type of the CRL distribution point.");
v.addElement(PROP_POINT_NAME + Integer.toString(i) + ";string;" +
- "The name of the CRL distribution point depending on the CRLDP type.");
+ "The name of the CRL distribution point depending on the CRLDP type.");
v.addElement(PROP_REASONS + Integer.toString(i) + ";string;" +
- "The revocation reasons for the CRL maintained at this distribution point. It's a comma-seperated list of the following constants: unused, keyCompromise, cACompromise, affiliationChanged, superseded, cessationOfOperation, certificateHold.");
+ "The revocation reasons for the CRL maintained at this distribution point. It's a comma-seperated list of the following constants: unused, keyCompromise, cACompromise, affiliationChanged, superseded, cessationOfOperation, certificateHold.");
v.addElement(PROP_ISSUER_TYPE + Integer.toString(i) + ";choice(" +
- "DirectoryName,URI);" +
- "The type of the issuer that has signed the CRL maintained at this distribution point.");
+ "DirectoryName,URI);" +
+ "The type of the issuer that has signed the CRL maintained at this distribution point.");
v.addElement(PROP_ISSUER_NAME + Integer.toString(i) + ";string;" +
- "The name of the issuer that has signed the CRL maintained at this distribution point. The value depends on the issuer type.");
+ "The name of the issuer that has signed the CRL maintained at this distribution point. The value depends on the issuer type.");
}
v.addElement(PROP_NUM_POINTS +
- ";number;The total number of CRL distribution points to be contained or allowed in the extension.");
+ ";number;The total number of CRL distribution points to be contained or allowed in the extension.");
v.addElement(PROP_IS_CRITICAL +
- ";boolean;RFC 2459 recommendation: SHOULD be non-critical. But recommends support for this extension by CAs and applications.");
+ ";boolean;RFC 2459 recommendation: SHOULD be non-critical. But recommends support for this extension by CAs and applications.");
v.addElement(IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-crldistributionpoints");
+ ";configuration-policyrules-crldistributionpoints");
v.addElement(IExtendedPluginInfo.HELP_TEXT +
- ";This policy inserts the CRL Distribution Points " +
- "Extension into the certificate. See RFC 2459 (4.2.1.14). "
- );
+ ";This policy inserts the CRL Distribution Points " +
+ "Extension into the certificate. See RFC 2459 (4.2.1.14). "
+ );
mExtParams = com.netscape.cmsutil.util.Utils.getStringArrayFromVector(v);
}
@@ -212,13 +209,13 @@ public class CRLDistributionPointsExt extends APolicyRule
* Performs one-time initialization of the policy.
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
// Register the CRL Distribution Points extension.
try {
netscape.security.x509.OIDMap.addAttribute(
- CRLDistributionPointsExtension.class.getName(),
- CRLDistributionPointsExtension.OID,
- CRLDistributionPointsExtension.class.getSimpleName());
+ CRLDistributionPointsExtension.class.getName(),
+ CRLDistributionPointsExtension.OID,
+ CRLDistributionPointsExtension.class.getSimpleName());
} catch (CertificateException e) {
// ignore, just means it has already been added
}
@@ -269,11 +266,11 @@ public class CRLDistributionPointsExt extends APolicyRule
}
/**
- * Parses the parameters in the config file to create an
- * actual CRL Distribution Point object.
+ * Parses the parameters in the config file to create an actual CRL
+ * Distribution Point object.
*/
private CRLDistributionPoint DPParamsToDP(DistPointParams params)
- throws EBaseException {
+ throws EBaseException {
CRLDistributionPoint crlDP = new CRLDistributionPoint();
try {
@@ -337,14 +334,14 @@ public class CRLDistributionPointsExt extends APolicyRule
if (r == null) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CA_UNKNOWN_REASON", s));
- throw new EBaseException("Unknown reason: " + s);
+ throw new EBaseException("Unknown reason: " + s);
} else {
reasonBits |= r.getBitMask();
}
}
if (reasonBits != 0) {
BitArray ba = new BitArray(8, new byte[] { reasonBits }
- );
+ );
crlDP.setReasons(ba);
}
@@ -421,15 +418,15 @@ public class CRLDistributionPointsExt extends APolicyRule
try {
// find the extensions in the certInfo
CertificateExtensions extensions = (CertificateExtensions)
- certInfo.get(X509CertInfo.EXTENSIONS);
+ certInfo.get(X509CertInfo.EXTENSIONS);
// prepare the extensions data structure
if (extensions == null) {
certInfo.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ new CertificateVersion(CertificateVersion.V3));
extensions = new CertificateExtensions();
certInfo.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ new CertificateVersion(CertificateVersion.V3));
certInfo.set(X509CertInfo.EXTENSIONS, extensions);
} else {
// remove any previously computed version of the extension
@@ -446,13 +443,13 @@ public class CRLDistributionPointsExt extends APolicyRule
} catch (IOException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("POLICY_UNEXPECTED_POLICY_ERROR", NAME, e.getMessage()));
setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"), NAME,
- e.getMessage());
+ e.getMessage());
return PolicyResult.REJECTED;
} catch (CertificateException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CA_CERT_INFO_ERROR",
e.getMessage()));
setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"), NAME,
- e.getMessage());
+ e.getMessage());
return PolicyResult.REJECTED;
}
}
@@ -471,7 +468,7 @@ public class CRLDistributionPointsExt extends APolicyRule
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
public Vector<String> getInstanceParams() {
diff --git a/pki/base/common/src/com/netscape/cms/policy/extensions/CertificatePoliciesExt.java b/pki/base/common/src/com/netscape/cms/policy/extensions/CertificatePoliciesExt.java
index 1e61c4ad..c4384e75 100644
--- a/pki/base/common/src/com/netscape/cms/policy/extensions/CertificatePoliciesExt.java
+++ b/pki/base/common/src/com/netscape/cms/policy/extensions/CertificatePoliciesExt.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.extensions;
-
import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.Locale;
@@ -50,21 +49,20 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
- * Certificate Policies.
- * Adds certificate policies extension.
+ * Certificate Policies. Adds certificate policies extension.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public class CertificatePoliciesExt extends APolicyRule
- implements IEnrollmentPolicy, IExtendedPluginInfo {
+ implements IEnrollmentPolicy, IExtendedPluginInfo {
protected static final String PROP_CRITICAL = "critical";
protected static final String PROP_NUM_CERTPOLICIES = "numCertPolicies";
@@ -91,17 +89,16 @@ public class CertificatePoliciesExt extends APolicyRule
/**
* Initializes this policy rule.
* <P>
- *
+ *
* The entries may be of the form:
- *
- * ca.Policy.rule.<ruleName>.predicate=certType==ca
- * ca.Policy.rule.<ruleName>.implName=
- * ca.Policy.rule.<ruleName>.enable=true
- *
- * @param config The config store reference
+ *
+ * ca.Policy.rule.<ruleName>.predicate=certType==ca
+ * ca.Policy.rule.<ruleName>.implName= ca.Policy.rule.<ruleName>.enable=true
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mConfig = config;
mEnabled = mConfig.getBoolean(
@@ -117,7 +114,7 @@ public class CertificatePoliciesExt extends APolicyRule
"value must be greater than or equal to 1"));
}
- // init Policy Mappings, check values if enabled.
+ // init Policy Mappings, check values if enabled.
mCertPolicies = new CertPolicy[mNumCertPolicies];
for (int i = 0; i < mNumCertPolicies; i++) {
String subtreeName = PROP_CERTPOLICY + i;
@@ -126,7 +123,7 @@ public class CertificatePoliciesExt extends APolicyRule
mCertPolicies[i] = new CertPolicy(subtreeName, mConfig, mEnabled);
} catch (EBaseException e) {
log(ILogger.LL_FAILURE, NAME + ": " +
- CMS.getLogMessage("POLICY_ERROR_CREATE_CERT_POLICY", e.toString()));
+ CMS.getLogMessage("POLICY_ERROR_CREATE_CERT_POLICY", e.toString()));
throw e;
}
}
@@ -138,21 +135,21 @@ public class CertificatePoliciesExt extends APolicyRule
for (int j = 0; j < mNumCertPolicies; j++) {
CertPolicies.addElement(
- mCertPolicies[j].mCertificatePolicyInfo);
+ mCertPolicies[j].mCertificatePolicyInfo);
}
- mCertificatePoliciesExtension =
+ mCertificatePoliciesExtension =
new CertificatePoliciesExtension(mCritical, CertPolicies);
} catch (IOException e) {
throw new EBaseException(
CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR",
- "Error initializing " + NAME + " Error: " + e));
+ "Error initializing " + NAME + " Error: " + e));
}
}
- // form instance params
+ // form instance params
mInstanceParams.addElement(PROP_CRITICAL + "=" + mCritical);
mInstanceParams.addElement(
- PROP_NUM_CERTPOLICIES + "=" + mNumCertPolicies);
+ PROP_NUM_CERTPOLICIES + "=" + mNumCertPolicies);
for (int i = 0; i < mNumCertPolicies; i++) {
mCertPolicies[i].getInstanceParams(mInstanceParams);
}
@@ -161,19 +158,19 @@ public class CertificatePoliciesExt extends APolicyRule
/**
* Applies the policy on the given Request.
* <p>
- *
- * @param req The request on which to apply policy.
+ *
+ * @param req The request on which to apply policy.
* @return The policy result object.
*/
public PolicyResult apply(IRequest req) {
// get certInfo from request.
- X509CertInfo[] ci =
- req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
-
+ X509CertInfo[] ci =
+ req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
+
if (ci == null || ci[0] == null) {
setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO"), NAME);
- return PolicyResult.REJECTED;
+ return PolicyResult.REJECTED;
}
for (int i = 0; i < ci.length; i++) {
@@ -194,8 +191,8 @@ public class CertificatePoliciesExt extends APolicyRule
if (extensions == null) {
extensions = new CertificateExtensions();
try {
- certInfo.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ certInfo.set(X509CertInfo.VERSION,
+ new CertificateVersion(CertificateVersion.V3));
certInfo.set(X509CertInfo.EXTENSIONS, extensions);
} catch (Exception e) {
}
@@ -204,8 +201,9 @@ public class CertificatePoliciesExt extends APolicyRule
try {
extensions.delete(CertificatePoliciesExtension.class.getSimpleName());
} catch (IOException e) {
- // this is the hack: for some reason, the key which is the name
- // of the policy has been converted into the OID
+ // this is the hack: for some reason, the key which is the
+ // name
+ // of the policy has been converted into the OID
try {
extensions.delete("2.5.29.32");
} catch (IOException ee) {
@@ -213,24 +211,24 @@ public class CertificatePoliciesExt extends APolicyRule
}
}
extensions.set(CertificatePoliciesExtension.class.getSimpleName(),
- mCertificatePoliciesExtension);
+ mCertificatePoliciesExtension);
} catch (IOException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("POLICY_ERROR_CERTIFICATE_POLICIES_1",
e.toString()));
setError(req,
- CMS.getUserMessage("CMS_POLICY_CERTIFICATE_POLICIES_ERROR"), NAME);
+ CMS.getUserMessage("CMS_POLICY_CERTIFICATE_POLICIES_ERROR"), NAME);
return PolicyResult.REJECTED;
} catch (CertificateException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("POLICY_ERROR_CERTIFICATE_POLICIES_1",
e.toString()));
setError(req,
- CMS.getUserMessage("CMS_POLICY_CERTIFICATE_POLICIES_ERROR"), NAME);
+ CMS.getUserMessage("CMS_POLICY_CERTIFICATE_POLICIES_ERROR"), NAME);
return PolicyResult.REJECTED;
} catch (Exception e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("POLICY_ERROR_CERTIFICATE_POLICIES_1",
e.toString()));
setError(req,
- CMS.getUserMessage("CMS_POLICY_CERTIFICATE_POLICIES_ERROR"), NAME);
+ CMS.getUserMessage("CMS_POLICY_CERTIFICATE_POLICIES_ERROR"), NAME);
return PolicyResult.REJECTED;
}
return PolicyResult.ACCEPTED;
@@ -238,51 +236,50 @@ public class CertificatePoliciesExt extends APolicyRule
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getInstanceParams() {
+ public Vector<String> getInstanceParams() {
return mInstanceParams;
}
/**
- * Default config parameters.
- * To add more permitted or excluded subtrees,
- * increase the num to greater than 0 and more configuration params
- * will show up in the console.
+ * Default config parameters. To add more permitted or excluded subtrees,
+ * increase the num to greater than 0 and more configuration params will
+ * show up in the console.
*/
private static Vector<String> mDefParams = new Vector<String>();
static {
mDefParams.addElement(PROP_CRITICAL + "=" + DEF_CRITICAL);
mDefParams.addElement(
- PROP_NUM_CERTPOLICIES + "=" + DEF_NUM_CERTPOLICIES);
+ PROP_NUM_CERTPOLICIES + "=" + DEF_NUM_CERTPOLICIES);
String certPolicy0Dot = PROP_CERTPOLICY + "0.";
mDefParams.addElement(
- certPolicy0Dot + CertPolicy.PROP_POLICY_IDENTIFIER + "=" + "");
+ certPolicy0Dot + CertPolicy.PROP_POLICY_IDENTIFIER + "=" + "");
mDefParams.addElement(
- certPolicy0Dot + CertPolicy.PROP_NOTICE_REF_ORG + "=" + "");
+ certPolicy0Dot + CertPolicy.PROP_NOTICE_REF_ORG + "=" + "");
mDefParams.addElement(
- certPolicy0Dot + CertPolicy.PROP_NOTICE_REF_NUMS + "=" + "");
+ certPolicy0Dot + CertPolicy.PROP_NOTICE_REF_NUMS + "=" + "");
mDefParams.addElement(
- certPolicy0Dot + CertPolicy.PROP_USER_NOTICE_TEXT + "=" + "");
+ certPolicy0Dot + CertPolicy.PROP_USER_NOTICE_TEXT + "=" + "");
mDefParams.addElement(
- certPolicy0Dot + CertPolicy.PROP_CPS_URI + "=" + "");
+ certPolicy0Dot + CertPolicy.PROP_CPS_URI + "=" + "");
}
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getDefaultParams() {
+ public Vector<String> getDefaultParams() {
return mDefParams;
}
public String[] getExtendedPluginInfo(Locale locale) {
Vector<String> theparams = new Vector<String>();
-
+
theparams.addElement(PROP_CRITICAL + ";boolean;RFC 3280 recommendation: MUST be non-critical.");
theparams.addElement(PROP_NUM_CERTPOLICIES + ";number; Number of certificate policies. The value must be greater than or equal to 1");
@@ -290,22 +287,22 @@ public class CertificatePoliciesExt extends APolicyRule
String certPolicykDot = PROP_CERTPOLICY + k + ".";
theparams.addElement(certPolicykDot +
- CertPolicy.PROP_POLICY_IDENTIFIER + ";string,required;An object identifier in the form n.n.n.n");
+ CertPolicy.PROP_POLICY_IDENTIFIER + ";string,required;An object identifier in the form n.n.n.n");
theparams.addElement(certPolicykDot +
- CertPolicy.PROP_NOTICE_REF_ORG + ";string;See RFC 3280 sec 4.2.1.5");
+ CertPolicy.PROP_NOTICE_REF_ORG + ";string;See RFC 3280 sec 4.2.1.5");
theparams.addElement(certPolicykDot +
- CertPolicy.PROP_NOTICE_REF_NUMS +
- ";string;comma-separated list of numbers. See RFC 3280 sec 4.2.1.5");
+ CertPolicy.PROP_NOTICE_REF_NUMS +
+ ";string;comma-separated list of numbers. See RFC 3280 sec 4.2.1.5");
theparams.addElement(certPolicykDot +
- CertPolicy.PROP_USER_NOTICE_TEXT + ";string;See RFC 3280 sec 4.2.1.5");
+ CertPolicy.PROP_USER_NOTICE_TEXT + ";string;See RFC 3280 sec 4.2.1.5");
theparams.addElement(certPolicykDot +
- CertPolicy.PROP_CPS_URI + ";string;See RFC 3280 sec 4.2.1.5");
+ CertPolicy.PROP_CPS_URI + ";string;See RFC 3280 sec 4.2.1.5");
}
theparams.addElement(IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-certificatepolicies");
+ ";configuration-policyrules-certificatepolicies");
theparams.addElement(IExtendedPluginInfo.HELP_TEXT +
- ";Adds Certificate Policies Extension. See RFC 3280 (4.2.1.5)");
+ ";Adds Certificate Policies Extension. See RFC 3280 (4.2.1.5)");
String[] params = new String[theparams.size()];
@@ -314,7 +311,6 @@ public class CertificatePoliciesExt extends APolicyRule
}
}
-
class CertPolicy {
protected static final String PROP_POLICY_IDENTIFIER = "policyId";
@@ -337,34 +333,35 @@ class CertPolicy {
/**
* forms policy map parameters.
+ *
* @param name name of this policy map, for example certPolicy0
* @param config parent's config from where we find this configuration.
* @param enabled whether policy was enabled.
*/
- protected CertPolicy(String name, IConfigStore config, boolean enabled)
- throws EBaseException {
+ protected CertPolicy(String name, IConfigStore config, boolean enabled)
+ throws EBaseException {
mName = name;
mConfig = config.getSubStore(mName);
mNameDot = mName + ".";
- if( mConfig == null ) {
- CMS.debug( "CertificatePoliciesExt::CertPolicy - mConfig is " +
- "null!" );
- throw new EBaseException( "mConfig is null" );
+ if (mConfig == null) {
+ CMS.debug("CertificatePoliciesExt::CertPolicy - mConfig is " +
+ "null!");
+ throw new EBaseException("mConfig is null");
}
// if there's no configuration for this policy put it there.
if (mConfig.size() == 0) {
- config.putString(mNameDot + PROP_POLICY_IDENTIFIER, "");
- config.putString(mNameDot + PROP_NOTICE_REF_ORG, "");
- config.putString(mNameDot + PROP_NOTICE_REF_NUMS, "");
- config.putString(mNameDot + PROP_USER_NOTICE_TEXT, "");
- config.putString(mNameDot + PROP_CPS_URI, "");
+ config.putString(mNameDot + PROP_POLICY_IDENTIFIER, "");
+ config.putString(mNameDot + PROP_NOTICE_REF_ORG, "");
+ config.putString(mNameDot + PROP_NOTICE_REF_NUMS, "");
+ config.putString(mNameDot + PROP_USER_NOTICE_TEXT, "");
+ config.putString(mNameDot + PROP_CPS_URI, "");
mConfig = config.getSubStore(mName);
- if(mConfig == null || mConfig.size() == 0) {
- CMS.debug( "CertificatePoliciesExt::CertPolicy - mConfig " +
- "is null or empty!" );
- throw new EBaseException( "mConfig is null or empty" );
+ if (mConfig == null || mConfig.size() == 0) {
+ CMS.debug("CertificatePoliciesExt::CertPolicy - mConfig " +
+ "is null or empty!");
+ throw new EBaseException("mConfig is null or empty");
}
}
@@ -376,28 +373,28 @@ class CertPolicy {
mCpsUri = mConfig.getString(PROP_CPS_URI, null);
// adjust for "" and console returning "null"
- if (mPolicyId != null &&
- (mPolicyId.length() == 0 ||
+ if (mPolicyId != null &&
+ (mPolicyId.length() == 0 ||
mPolicyId.equals("null"))) {
mPolicyId = null;
}
- if (mNoticeRefOrg != null &&
- (mNoticeRefOrg.length() == 0 ||
+ if (mNoticeRefOrg != null &&
+ (mNoticeRefOrg.length() == 0 ||
mNoticeRefOrg.equals("null"))) {
mNoticeRefOrg = null;
}
- if (mNoticeRefNums != null &&
- (mNoticeRefNums.length() == 0 ||
+ if (mNoticeRefNums != null &&
+ (mNoticeRefNums.length() == 0 ||
mNoticeRefNums.equals("null"))) {
mNoticeRefNums = null;
}
- if (mNoticeRefExplicitText != null &&
- (mNoticeRefExplicitText.length() == 0 ||
+ if (mNoticeRefExplicitText != null &&
+ (mNoticeRefExplicitText.length() == 0 ||
mNoticeRefExplicitText.equals("null"))) {
mNoticeRefExplicitText = null;
}
- if (mCpsUri != null &&
- (mCpsUri.length() == 0 ||
+ if (mCpsUri != null &&
+ (mCpsUri.length() == 0 ||
mCpsUri.equals("null"))) {
mCpsUri = null;
}
@@ -405,42 +402,44 @@ class CertPolicy {
// policy ids cannot be null if policy is enabled.
String msg = "value cannot be null.";
- if (mPolicyId == null && enabled)
+ if (mPolicyId == null && enabled)
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
mNameDot + PROP_POLICY_IDENTIFIER, msg));
msg = "NoticeReference is optional; If chosen to include, NoticeReference must at least has 'organization'";
- if (mNoticeRefOrg == null && mNoticeRefNums != null && enabled)
+ if (mNoticeRefOrg == null && mNoticeRefNums != null && enabled)
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
mNameDot + PROP_NOTICE_REF_ORG, msg));
-
- // if a policy id is not null check that it is a valid OID.
+
+ // if a policy id is not null check that it is a valid OID.
ObjectIdentifier policyId = null;
- if (mPolicyId != null)
+ if (mPolicyId != null)
policyId = CMS.checkOID(
mNameDot + PROP_POLICY_IDENTIFIER, mPolicyId);
-
- // if enabled, form CertificatePolicyInfo to be encoded in
- // extension. Policy ids should be all set.
+
+ // if enabled, form CertificatePolicyInfo to be encoded in
+ // extension. Policy ids should be all set.
if (enabled) {
- CMS.debug("CertPolicy: in CertPolicy");
+ CMS.debug("CertPolicy: in CertPolicy");
DisplayText displayText = null;
- if (mNoticeRefExplicitText != null &&
- !mNoticeRefExplicitText.equals(""))
+ if (mNoticeRefExplicitText != null &&
+ !mNoticeRefExplicitText.equals(""))
displayText = new DisplayText(DisplayText.tag_VisibleString, mNoticeRefExplicitText);
- // new DisplayText(DisplayText.tag_IA5String, mNoticeRefExplicitText);
+ // new DisplayText(DisplayText.tag_IA5String,
+ // mNoticeRefExplicitText);
DisplayText orgName = null;
- if (mNoticeRefOrg != null &&
- !mNoticeRefOrg.equals(""))
+ if (mNoticeRefOrg != null &&
+ !mNoticeRefOrg.equals(""))
orgName =
new DisplayText(DisplayText.tag_VisibleString, mNoticeRefOrg);
- // new DisplayText(DisplayText.tag_VisibleString, mNoticeRefOrg);
+ // new DisplayText(DisplayText.tag_VisibleString, mNoticeRefOrg);
- int[] nums = new int[0];;
- if (mNoticeRefNums != null &&
- !mNoticeRefNums.equals("")) {
+ int[] nums = new int[0];
+ ;
+ if (mNoticeRefNums != null &&
+ !mNoticeRefNums.equals("")) {
// should add a method to NoticeReference to take a
// Vector...but let's do this for now
@@ -468,24 +467,23 @@ class CertPolicy {
try {
cpolicyId = new CertificatePolicyId(ObjectIdentifier.getObjectIdentifier(mPolicyId));
} catch (Exception e) {
- throw new
- EBaseException(CMS.getUserMessage("CMS_POLICY_CERTIFICATE_POLICIES_ERROR", mPolicyId));
+ throw new EBaseException(CMS.getUserMessage("CMS_POLICY_CERTIFICATE_POLICIES_ERROR", mPolicyId));
}
PolicyQualifiers policyQualifiers = new PolicyQualifiers();
-
+
NoticeReference noticeReference = null;
-
+
if (orgName != null)
noticeReference = new NoticeReference(orgName, nums);
UserNotice userNotice = null;
if (displayText != null || noticeReference != null) {
- userNotice = new UserNotice (noticeReference, displayText);
-
+ userNotice = new UserNotice(noticeReference, displayText);
+
PolicyQualifierInfo policyQualifierInfo1 =
- new PolicyQualifierInfo(PolicyQualifierInfo.QT_UNOTICE, userNotice);
+ new PolicyQualifierInfo(PolicyQualifierInfo.QT_UNOTICE, userNotice);
policyQualifiers.add(policyQualifierInfo1);
}
@@ -493,25 +491,25 @@ class CertPolicy {
CPSuri cpsUri = null;
if (mCpsUri != null && mCpsUri.length() > 0) {
- cpsUri = new CPSuri (mCpsUri);
+ cpsUri = new CPSuri(mCpsUri);
PolicyQualifierInfo policyQualifierInfo2 =
- new PolicyQualifierInfo(PolicyQualifierInfo.QT_CPS, cpsUri);
-
+ new PolicyQualifierInfo(PolicyQualifierInfo.QT_CPS, cpsUri);
+
policyQualifiers.add(policyQualifierInfo2);
}
if ((mNoticeRefOrg == null || mNoticeRefOrg.equals("")) &&
- (mNoticeRefExplicitText == null || mNoticeRefExplicitText.equals("")) &&
- (mCpsUri == null || mCpsUri.equals(""))) {
- CMS.debug("CertPolicy mNoticeRefOrg = "+mNoticeRefOrg);
- CMS.debug("CertPolicy mNoticeRefExplicitText = "+mNoticeRefExplicitText);
- CMS.debug("CertPolicy mCpsUri = "+mCpsUri);
+ (mNoticeRefExplicitText == null || mNoticeRefExplicitText.equals("")) &&
+ (mCpsUri == null || mCpsUri.equals(""))) {
+ CMS.debug("CertPolicy mNoticeRefOrg = " + mNoticeRefOrg);
+ CMS.debug("CertPolicy mNoticeRefExplicitText = " + mNoticeRefExplicitText);
+ CMS.debug("CertPolicy mCpsUri = " + mCpsUri);
mCertificatePolicyInfo = new CertificatePolicyInfo(cpolicyId);
} else {
- CMS.debug("CertPolicy mNoticeRefOrg = "+mNoticeRefOrg);
- CMS.debug("CertPolicy mNoticeRefExplicitText = "+mNoticeRefExplicitText);
- CMS.debug("CertPolicy mCpsUri = "+mCpsUri);
+ CMS.debug("CertPolicy mNoticeRefOrg = " + mNoticeRefOrg);
+ CMS.debug("CertPolicy mNoticeRefExplicitText = " + mNoticeRefExplicitText);
+ CMS.debug("CertPolicy mCpsUri = " + mCpsUri);
mCertificatePolicyInfo = new CertificatePolicyInfo(cpolicyId, policyQualifiers);
}
}
@@ -519,20 +517,19 @@ class CertPolicy {
protected void getInstanceParams(Vector<String> instanceParams) {
instanceParams.addElement(
- mNameDot + PROP_POLICY_IDENTIFIER + "=" + (mPolicyId == null ? "" :
- mPolicyId));
+ mNameDot + PROP_POLICY_IDENTIFIER + "=" + (mPolicyId == null ? "" :
+ mPolicyId));
instanceParams.addElement(
- mNameDot + PROP_NOTICE_REF_ORG + "=" + (mNoticeRefOrg == null ? "" :
- mNoticeRefOrg));
+ mNameDot + PROP_NOTICE_REF_ORG + "=" + (mNoticeRefOrg == null ? "" :
+ mNoticeRefOrg));
instanceParams.addElement(
- mNameDot + PROP_NOTICE_REF_NUMS + "=" + (mNoticeRefNums == null ? "" :
- mNoticeRefNums));
+ mNameDot + PROP_NOTICE_REF_NUMS + "=" + (mNoticeRefNums == null ? "" :
+ mNoticeRefNums));
instanceParams.addElement(
- mNameDot + PROP_USER_NOTICE_TEXT + "=" + (mNoticeRefExplicitText == null ? "" :
- mNoticeRefExplicitText));
+ mNameDot + PROP_USER_NOTICE_TEXT + "=" + (mNoticeRefExplicitText == null ? "" :
+ mNoticeRefExplicitText));
instanceParams.addElement(
- mNameDot + PROP_CPS_URI + "=" + (mCpsUri == null ? "" :
- mCpsUri));
+ mNameDot + PROP_CPS_URI + "=" + (mCpsUri == null ? "" :
+ mCpsUri));
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/policy/extensions/CertificateRenewalWindowExt.java b/pki/base/common/src/com/netscape/cms/policy/extensions/CertificateRenewalWindowExt.java
index e3927502..7471a580 100644
--- a/pki/base/common/src/com/netscape/cms/policy/extensions/CertificateRenewalWindowExt.java
+++ b/pki/base/common/src/com/netscape/cms/policy/extensions/CertificateRenewalWindowExt.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.extensions;
-
import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.Date;
@@ -40,20 +39,20 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
* Certificate Renewal Window Extension Policy
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public class CertificateRenewalWindowExt extends APolicyRule
- implements IEnrollmentPolicy, IExtendedPluginInfo {
+ implements IEnrollmentPolicy, IExtendedPluginInfo {
protected static final String PROP_END_TIME = "relativeEndTime";
protected static final String PROP_BEGIN_TIME = "relativeBeginTime";
@@ -64,9 +63,8 @@ public class CertificateRenewalWindowExt extends APolicyRule
protected String mEndTime;
/**
- * Adds the Netscape comment in the end-entity certificates or
- * CA certificates. The policy is set to be non-critical with the
- * provided OID.
+ * Adds the Netscape comment in the end-entity certificates or CA
+ * certificates. The policy is set to be non-critical with the provided OID.
*/
public CertificateRenewalWindowExt() {
NAME = "CertificateRenewalWindowExt";
@@ -75,11 +73,11 @@ public class CertificateRenewalWindowExt extends APolicyRule
/**
* Initializes this policy rule.
- *
- * @param config The config store reference
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mCritical = config.getBoolean(PROP_CRITICAL, false);
mBeginTime = config.getString(PROP_BEGIN_TIME, null);
mEndTime = config.getString(PROP_END_TIME, null);
@@ -89,16 +87,16 @@ public class CertificateRenewalWindowExt extends APolicyRule
/**
* Applies the policy on the given Request.
* <p>
- *
- * @param req The request on which to apply policy.
+ *
+ * @param req The request on which to apply policy.
* @return The policy result object.
*/
public PolicyResult apply(IRequest req) {
PolicyResult res = PolicyResult.ACCEPTED;
// get cert info.
- X509CertInfo[] ci =
- req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
+ X509CertInfo[] ci =
+ req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
if (ci == null || ci[0] == null) {
setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO"), NAME);
@@ -128,8 +126,8 @@ public class CertificateRenewalWindowExt extends APolicyRule
if (extensions == null) {
extensions = new CertificateExtensions();
try {
- certInfo.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ certInfo.set(X509CertInfo.VERSION,
+ new CertificateVersion(CertificateVersion.V3));
certInfo.set(X509CertInfo.EXTENSIONS, extensions);
} catch (Exception e) {
}
@@ -137,10 +135,10 @@ public class CertificateRenewalWindowExt extends APolicyRule
// remove any previously computed version of the extension
try {
extensions.delete(CertificateRenewalWindowExtension.class.getSimpleName());
-
+
} catch (IOException e) {
// this is the hack: for some reason, the key which is the name
- // of the policy has been converted into the OID
+ // of the policy has been converted into the OID
try {
extensions.delete("2.16.840.1.113730.1.15");
} catch (IOException ee) {
@@ -154,22 +152,22 @@ public class CertificateRenewalWindowExt extends APolicyRule
if (mEndTime == null || mEndTime.equals("")) {
crwExt = new CertificateRenewalWindowExtension(
- mCritical,
+ mCritical,
getDateValue(now, mBeginTime),
null);
} else {
crwExt = new CertificateRenewalWindowExtension(
- mCritical,
+ mCritical,
getDateValue(now, mBeginTime),
getDateValue(now, mEndTime));
}
- extensions.set(CertificateRenewalWindowExtension.class.getSimpleName(),
- crwExt);
+ extensions.set(CertificateRenewalWindowExtension.class.getSimpleName(),
+ crwExt);
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("POLICY_ERROR_CERTIFICATE_POLICIES_1", NAME));
+ CMS.getLogMessage("POLICY_ERROR_CERTIFICATE_POLICIES_1", NAME));
setError(req,
- CMS.getUserMessage("CMS_POLICY_CERTIFICATE_POLICIES_ERROR"), NAME);
+ CMS.getUserMessage("CMS_POLICY_CERTIFICATE_POLICIES_ERROR"), NAME);
return PolicyResult.REJECTED;
}
return PolicyResult.ACCEPTED;
@@ -179,13 +177,13 @@ public class CertificateRenewalWindowExt extends APolicyRule
long time;
if (s.endsWith("s")) {
- time = 1000 * Long.parseLong(s.substring(0,
+ time = 1000 * Long.parseLong(s.substring(0,
s.length() - 1));
} else if (s.endsWith("m")) {
- time = 60 * 1000 * Long.parseLong(s.substring(0,
+ time = 60 * 1000 * Long.parseLong(s.substring(0,
s.length() - 1));
} else if (s.endsWith("h")) {
- time = 60 * 60 * 1000 * Long.parseLong(s.substring(0,
+ time = 60 * 60 * 1000 * Long.parseLong(s.substring(0,
s.length() - 1));
} else if (s.endsWith("D")) {
time = 24 * 60 * 60 * 1000 * Long.parseLong(
@@ -206,9 +204,9 @@ public class CertificateRenewalWindowExt extends APolicyRule
PROP_BEGIN_TIME + ";string;Start Time in seconds (Relative to the time of issuance). Optionally, time unit (s - seconds, m - minutes, h - hours, D - days, M - months) can be specified right after the value. For example, 5 days can be expressed as 5D.",
PROP_END_TIME + ";string;End Time in seconds (Optional, Relative to the time of issuance). Optionally, time unit (s - seconds, m - minutes, h - hours, D - days, M - months) can be specified right after the value. For example, 5 days can be expressed as 5D.",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-certificaterenewalwindow",
+ ";configuration-policyrules-certificaterenewalwindow",
IExtendedPluginInfo.HELP_TEXT +
- ";Adds 'Certificate Renewal Window' extension. See manual"
+ ";Adds 'Certificate Renewal Window' extension. See manual"
};
return params;
@@ -217,10 +215,10 @@ public class CertificateRenewalWindowExt extends APolicyRule
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getInstanceParams() {
+ public Vector<String> getInstanceParams() {
Vector<String> params = new Vector<String>();
params.addElement(PROP_CRITICAL + "=" + mCritical);
@@ -239,10 +237,10 @@ public class CertificateRenewalWindowExt extends APolicyRule
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getDefaultParams() {
+ public Vector<String> getDefaultParams() {
Vector<String> defParams = new Vector<String>();
defParams.addElement(PROP_CRITICAL + "=false");
diff --git a/pki/base/common/src/com/netscape/cms/policy/extensions/CertificateScopeOfUseExt.java b/pki/base/common/src/com/netscape/cms/policy/extensions/CertificateScopeOfUseExt.java
index 14ef4213..bf1bc8a4 100644
--- a/pki/base/common/src/com/netscape/cms/policy/extensions/CertificateScopeOfUseExt.java
+++ b/pki/base/common/src/com/netscape/cms/policy/extensions/CertificateScopeOfUseExt.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.extensions;
-
import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.Locale;
@@ -43,31 +42,31 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
- * Certificate Scope Of Use extension policy. This extension
- * is defined in draft-thayes-cert-scope-00.txt
+ * Certificate Scope Of Use extension policy. This extension is defined in
+ * draft-thayes-cert-scope-00.txt
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
-public class CertificateScopeOfUseExt extends APolicyRule implements
+public class CertificateScopeOfUseExt extends APolicyRule implements
IEnrollmentPolicy, IExtendedPluginInfo {
protected static final String PROP_CRITICAL =
- "critical";
+ "critical";
protected static final String PROP_ENTRY =
- "entry";
+ "entry";
protected static final String PROP_NAME =
- "name";
+ "name";
protected static final String PROP_NAME_TYPE =
- "name_type";
+ "name_type";
protected static final String PROP_PORT_NUMBER =
- "port_number";
+ "port_number";
public static final int MAX_ENTRY = 5;
@@ -82,11 +81,11 @@ public class CertificateScopeOfUseExt extends APolicyRule implements
Vector<String> v = new Vector<String>();
v.addElement(PROP_CRITICAL +
- ";boolean; This extension may be either critical or non-critical.");
+ ";boolean; This extension may be either critical or non-critical.");
v.addElement(IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-certificatescopeofuse");
+ ";configuration-policyrules-certificatescopeofuse");
v.addElement(IExtendedPluginInfo.HELP_TEXT +
- ";Adds Certificate Scope of Use Extension.");
+ ";Adds Certificate Scope of Use Extension.");
for (int i = 0; i < MAX_ENTRY; i++) {
v.addElement(PROP_ENTRY + Integer.toString(i) + "_" + PROP_NAME + ";" + IGeneralNameUtil.GENNAME_VALUE_INFO);
@@ -99,17 +98,17 @@ public class CertificateScopeOfUseExt extends APolicyRule implements
/**
* Initializes this policy rule.
* <P>
- *
+ *
* The entries may be of the form:
- *
- * ca.Policy.rule.<ruleName>.implName=AuthInfoAccessExt
- * ca.Policy.rule.<ruleName>.enable=true
- * ca.Policy.rule.<ruleName>.predicate=
- *
- * @param config The config store reference
+ *
+ * ca.Policy.rule.<ruleName>.implName=AuthInfoAccessExt
+ * ca.Policy.rule.<ruleName>.enable=true
+ * ca.Policy.rule.<ruleName>.predicate=
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mConfig = config;
}
@@ -124,7 +123,7 @@ public class CertificateScopeOfUseExt extends APolicyRule implements
//
for (int i = 0;; i++) {
// get port number (optional)
- String port = mConfig.getString(PROP_ENTRY +
+ String port = mConfig.getString(PROP_ENTRY +
Integer.toString(i) + "_" + PROP_PORT_NUMBER, null);
BigInt portNumber = null;
@@ -137,11 +136,11 @@ public class CertificateScopeOfUseExt extends APolicyRule implements
// TAG ::= uriName | dirName
// VALUE ::= [value defined by TAG]
//
- String name_type = mConfig.getString(PROP_ENTRY +
- Integer.toString(i) +
+ String name_type = mConfig.getString(PROP_ENTRY +
+ Integer.toString(i) +
"_" + PROP_NAME_TYPE, null);
- String name = mConfig.getString(PROP_ENTRY +
- Integer.toString(i) +
+ String name = mConfig.getString(PROP_ENTRY +
+ Integer.toString(i) +
"_" + PROP_NAME, null);
if (name == null || name.equals(""))
@@ -154,10 +153,10 @@ public class CertificateScopeOfUseExt extends APolicyRule implements
}
/**
- * If this policy is enabled, add the authority information
- * access extension to the certificate.
+ * If this policy is enabled, add the authority information access extension
+ * to the certificate.
* <P>
- *
+ *
* @param req The request on which to apply policy.
* @return The policy result object.
*/
@@ -169,7 +168,7 @@ public class CertificateScopeOfUseExt extends APolicyRule implements
IRequest.CERT_INFO);
if (ci == null) {
- setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO"), NAME);
+ setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO"), NAME);
return PolicyResult.REJECTED; // unrecoverable error.
}
@@ -177,29 +176,29 @@ public class CertificateScopeOfUseExt extends APolicyRule implements
certInfo = ci[j];
if (certInfo == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CA_CERT_INFO_ERROR", NAME));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
- NAME, "Configuration Info Error");
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CA_CERT_INFO_ERROR", NAME));
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
+ NAME, "Configuration Info Error");
return PolicyResult.REJECTED; // unrecoverable error.
}
try {
// Find the extensions in the certInfo
CertificateExtensions extensions = (CertificateExtensions)
- certInfo.get(X509CertInfo.EXTENSIONS);
+ certInfo.get(X509CertInfo.EXTENSIONS);
// add access descriptions
Vector<CertificateScopeEntry> entries = getScopeEntries();
if (entries.size() == 0) {
return res;
- }
-
+ }
+
if (extensions == null) {
// create extension if not exist
certInfo.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ new CertificateVersion(CertificateVersion.V3));
extensions = new CertificateExtensions();
certInfo.set(X509CertInfo.EXTENSIONS, extensions);
} else {
@@ -212,29 +211,29 @@ public class CertificateScopeOfUseExt extends APolicyRule implements
}
// Create the extension
- CertificateScopeOfUseExtension suExt = new
- CertificateScopeOfUseExtension(mConfig.getBoolean(
- PROP_CRITICAL, false), entries);
+ CertificateScopeOfUseExtension suExt = new
+ CertificateScopeOfUseExtension(mConfig.getBoolean(
+ PROP_CRITICAL, false), entries);
extensions.set(CertificateScopeOfUseExtension.NAME, suExt);
} catch (IOException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("BASE_IO_ERROR", e.getMessage()));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
- NAME, e.getMessage());
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
+ NAME, e.getMessage());
return PolicyResult.REJECTED; // unrecoverable error.
} catch (EBaseException e) {
- log(ILogger.LL_FAILURE,
- "Configuration Info Error encountered: " +
- e.getMessage());
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
- NAME, "Configuration Info Error");
+ log(ILogger.LL_FAILURE,
+ "Configuration Info Error encountered: " +
+ e.getMessage());
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
+ NAME, "Configuration Info Error");
return PolicyResult.REJECTED; // unrecoverable error.
} catch (CertificateException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CA_CERT_INFO_ERROR", e.getMessage()));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
- NAME, "Certificate Info Error");
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CA_CERT_INFO_ERROR", e.getMessage()));
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
+ NAME, "Certificate Info Error");
return PolicyResult.REJECTED; // unrecoverable error.
}
}
@@ -244,15 +243,15 @@ public class CertificateScopeOfUseExt extends APolicyRule implements
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getInstanceParams() {
+ public Vector<String> getInstanceParams() {
Vector<String> params = new Vector<String>();
try {
- params.addElement(PROP_CRITICAL + "=" +
- mConfig.getBoolean(PROP_CRITICAL, false));
+ params.addElement(PROP_CRITICAL + "=" +
+ mConfig.getBoolean(PROP_CRITICAL, false));
} catch (EBaseException e) {
}
@@ -260,50 +259,50 @@ public class CertificateScopeOfUseExt extends APolicyRule implements
String name_type = null;
try {
- name_type = mConfig.getString(PROP_ENTRY +
- Integer.toString(i) + "_" + PROP_NAME_TYPE,
+ name_type = mConfig.getString(PROP_ENTRY +
+ Integer.toString(i) + "_" + PROP_NAME_TYPE,
null);
} catch (EBaseException e) {
}
if (name_type == null)
break;
- params.addElement(PROP_ENTRY +
- Integer.toString(i) +
- "_" + PROP_NAME_TYPE + "=" + name_type);
+ params.addElement(PROP_ENTRY +
+ Integer.toString(i) +
+ "_" + PROP_NAME_TYPE + "=" + name_type);
String name = null;
try {
- name = mConfig.getString(PROP_ENTRY +
- Integer.toString(i) + "_" + PROP_NAME,
+ name = mConfig.getString(PROP_ENTRY +
+ Integer.toString(i) + "_" + PROP_NAME,
null);
} catch (EBaseException e) {
}
if (name == null)
break;
- params.addElement(PROP_ENTRY +
- Integer.toString(i) +
- "_" + PROP_NAME + "=" + name);
+ params.addElement(PROP_ENTRY +
+ Integer.toString(i) +
+ "_" + PROP_NAME + "=" + name);
String port = null;
try {
- port = mConfig.getString(PROP_ENTRY +
- Integer.toString(i) + "_" + PROP_PORT_NUMBER,
+ port = mConfig.getString(PROP_ENTRY +
+ Integer.toString(i) + "_" + PROP_PORT_NUMBER,
"");
} catch (EBaseException e) {
}
- params.addElement(PROP_ENTRY +
- Integer.toString(i) +
- "_" + PROP_PORT_NUMBER + "=" + port);
+ params.addElement(PROP_ENTRY +
+ Integer.toString(i) +
+ "_" + PROP_PORT_NUMBER + "=" + port);
}
return params;
}
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getDefaultParams() {
+ public Vector<String> getDefaultParams() {
Vector<String> defParams = new Vector<String>();
defParams.addElement(PROP_CRITICAL + "=false");
@@ -314,14 +313,13 @@ public class CertificateScopeOfUseExt extends APolicyRule implements
// the CMS.cfg
//
for (int i = 0; i < MAX_ENTRY; i++) {
- defParams.addElement(PROP_ENTRY + Integer.toString(i) +
- "_" + PROP_NAME_TYPE + "=");
- defParams.addElement(PROP_ENTRY + Integer.toString(i) +
- "_" + PROP_NAME + "=");
- defParams.addElement(PROP_ENTRY + Integer.toString(i) +
- "_" + PROP_PORT_NUMBER + "=");
+ defParams.addElement(PROP_ENTRY + Integer.toString(i) +
+ "_" + PROP_NAME_TYPE + "=");
+ defParams.addElement(PROP_ENTRY + Integer.toString(i) +
+ "_" + PROP_NAME + "=");
+ defParams.addElement(PROP_ENTRY + Integer.toString(i) +
+ "_" + PROP_PORT_NUMBER + "=");
}
return defParams;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/policy/extensions/ExtendedKeyUsageExt.java b/pki/base/common/src/com/netscape/cms/policy/extensions/ExtendedKeyUsageExt.java
index 94d7d8df..2684d02c 100644
--- a/pki/base/common/src/com/netscape/cms/policy/extensions/ExtendedKeyUsageExt.java
+++ b/pki/base/common/src/com/netscape/cms/policy/extensions/ExtendedKeyUsageExt.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.extensions;
-
import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.Locale;
@@ -40,20 +39,20 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
* This implements the extended key usage extension.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public class ExtendedKeyUsageExt extends APolicyRule
- implements IEnrollmentPolicy, IExtendedPluginInfo {
+ implements IEnrollmentPolicy, IExtendedPluginInfo {
public static final String PROP_CRITICAL = "critical";
protected static final String PROP_PURPOSE_ID = "id";
protected static final String PROP_NUM_IDS = "numIds";
@@ -63,7 +62,7 @@ public class ExtendedKeyUsageExt extends APolicyRule
private Vector<ObjectIdentifier> mUsages = null;
private String[] mParams = null;
-
+
// PKIX specifies the that the extension SHOULD NOT be critical
public static final boolean DEFAULT_CRITICALITY = false;
@@ -81,7 +80,7 @@ public class ExtendedKeyUsageExt extends APolicyRule
* Performs one-time initialization of the policy.
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mConfig = config;
setExtendedPluginInfo();
setupParams();
@@ -99,7 +98,7 @@ public class ExtendedKeyUsageExt extends APolicyRule
}
X509CertInfo[] ci =
- req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
+ req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
if (ci == null || ci[0] == null) {
setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO"), NAME);
@@ -119,15 +118,15 @@ public class ExtendedKeyUsageExt extends APolicyRule
try {
// find the extensions in the certInfo
CertificateExtensions extensions = (CertificateExtensions)
- certInfo.get(X509CertInfo.EXTENSIONS);
+ certInfo.get(X509CertInfo.EXTENSIONS);
// prepare the extensions data structure
if (extensions == null) {
certInfo.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ new CertificateVersion(CertificateVersion.V3));
extensions = new CertificateExtensions();
certInfo.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ new CertificateVersion(CertificateVersion.V3));
certInfo.set(X509CertInfo.EXTENSIONS, extensions);
} else {
try {
@@ -143,17 +142,17 @@ public class ExtendedKeyUsageExt extends APolicyRule
} catch (IOException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("BASE_IO_ERROR", e.getMessage()));
setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"), NAME,
- e.getMessage());
+ e.getMessage());
return PolicyResult.REJECTED;
} catch (CertificateException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CA_CERT_INFO_ERROR",
e.getMessage()));
setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"), NAME,
- e.getMessage());
+ e.getMessage());
return PolicyResult.REJECTED;
}
}
-
+
/**
* Returns instance specific parameters.
*/
@@ -172,16 +171,16 @@ public class ExtendedKeyUsageExt extends APolicyRule
for (int i = 0; i < numIds; i++) {
if (mUsages.size() <= i) {
- params.addElement(PROP_PURPOSE_ID +
- Integer.toString(i) + "=");
+ params.addElement(PROP_PURPOSE_ID +
+ Integer.toString(i) + "=");
} else {
usage = ((ObjectIdentifier) mUsages.elementAt(i)).toString();
if (usage == null) {
- params.addElement(PROP_PURPOSE_ID +
- Integer.toString(i) + "=");
+ params.addElement(PROP_PURPOSE_ID +
+ Integer.toString(i) + "=");
} else {
- params.addElement(PROP_PURPOSE_ID +
- Integer.toString(i) + "=" + usage);
+ params.addElement(PROP_PURPOSE_ID +
+ Integer.toString(i) + "=" + usage);
}
}
}
@@ -200,17 +199,17 @@ public class ExtendedKeyUsageExt extends APolicyRule
}
for (int i = 0; i < mNum; i++) {
v.addElement(PROP_PURPOSE_ID + Integer.toString(i) + ";string;" +
- "A unique,valid OID specified in dot-separated numeric component notation. e.g. 2.16.840.1.113730.1.99");
+ "A unique,valid OID specified in dot-separated numeric component notation. e.g. 2.16.840.1.113730.1.99");
}
v.addElement(PROP_NUM_IDS + ";number;The total number of policy IDs.");
v.addElement(PROP_CRITICAL +
- ";boolean;RFC 2459 recommendation: This extension may, at the option of the certificate issuer, be either critical or non-critical.");
+ ";boolean;RFC 2459 recommendation: This extension may, at the option of the certificate issuer, be either critical or non-critical.");
v.addElement(IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-extendedkeyusage");
+ ";configuration-policyrules-extendedkeyusage");
v.addElement(IExtendedPluginInfo.HELP_TEXT +
- ";Adds Extended Key Usage Extension. Defined in RFC 2459 " +
- "(4.2.1.13)");
+ ";Adds Extended Key Usage Extension. Defined in RFC 2459 " +
+ "(4.2.1.13)");
mParams = com.netscape.cmsutil.util.Utils.getStringArrayFromVector(v);
}
@@ -221,7 +220,7 @@ public class ExtendedKeyUsageExt extends APolicyRule
}
return mParams;
}
-
+
/**
* Returns default parameters.
*/
@@ -235,30 +234,32 @@ public class ExtendedKeyUsageExt extends APolicyRule
}
return defParams;
}
-
+
/**
* Setups parameters.
*/
private void setupParams() throws EBaseException {
-
+
mCritical = mConfig.getBoolean(PROP_CRITICAL, false);
if (mUsages == null) {
mUsages = new Vector<ObjectIdentifier>();
}
-
+
int mNum = mConfig.getInteger(PROP_NUM_IDS, MAX_PURPOSE_ID);
for (int i = 0; i < mNum; i++) {
ObjectIdentifier usageOID = null;
-
- String usage = mConfig.getString(PROP_PURPOSE_ID +
+
+ String usage = mConfig.getString(PROP_PURPOSE_ID +
Integer.toString(i), null);
try {
-
- if (usage == null) break;
+
+ if (usage == null)
+ break;
usage = usage.trim();
- if (usage.equals("")) break;
+ if (usage.equals(""))
+ break;
if (usage.equalsIgnoreCase("ocspsigning")) {
usageOID = ObjectIdentifier.getObjectIdentifier(ExtendedKeyUsageExtension.OID_OCSPSigning);
} else if (usage.equalsIgnoreCase("codesigning")) {
@@ -268,10 +269,10 @@ public class ExtendedKeyUsageExt extends APolicyRule
usageOID = ObjectIdentifier.getObjectIdentifier(usage);
}
} catch (IOException ex) {
- throw new EBaseException(this.getClass().getName() + ":" +
+ throw new EBaseException(this.getClass().getName() + ":" +
ex.getMessage());
} catch (NumberFormatException ex) {
- throw new EBaseException(this.getClass().getName() + ":" +
+ throw new EBaseException(this.getClass().getName() + ":" +
"OID '" + usage + "' format error");
}
mUsages.addElement(usageOID);
diff --git a/pki/base/common/src/com/netscape/cms/policy/extensions/GenericASN1Ext.java b/pki/base/common/src/com/netscape/cms/policy/extensions/GenericASN1Ext.java
index bdfdb14a..c382416f 100644
--- a/pki/base/common/src/com/netscape/cms/policy/extensions/GenericASN1Ext.java
+++ b/pki/base/common/src/com/netscape/cms/policy/extensions/GenericASN1Ext.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.extensions;
-
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
@@ -46,12 +45,10 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
- * Private Integer extension policy.
- * If this policy is enabled, it adds an Private Integer
- * extension to the certificate.
- *
+ * Private Integer extension policy. If this policy is enabled, it adds an
+ * Private Integer extension to the certificate.
+ *
* The following listed sample configuration parameters:
*
* ca.Policy.impl.privateInteger.class=com.netscape.certsrv.policy.genericASNExt
@@ -78,51 +75,52 @@ import com.netscape.cms.policy.APolicyRule;
* ca.Policy.rule.genericASNExt.implName=genericASNExt
* ca.Policy.rule.genericASNExt.predicate=
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
-public class GenericASN1Ext extends APolicyRule implements
+public class GenericASN1Ext extends APolicyRule implements
IEnrollmentPolicy, IExtendedPluginInfo {
protected static final int MAX_ATTR = 10;
protected static final String PROP_CRITICAL =
- "critical";
+ "critical";
protected static final String PROP_NAME =
- "name";
+ "name";
protected static final String PROP_OID =
- "oid";
+ "oid";
protected static final String PROP_PATTERN =
- "pattern";
+ "pattern";
protected static final String PROP_ATTRIBUTE =
- "attribute";
+ "attribute";
protected static final String PROP_TYPE =
- "type";
+ "type";
protected static final String PROP_SOURCE =
- "source";
+ "source";
protected static final String PROP_VALUE =
- "value";
+ "value";
protected static final String PROP_PREDICATE =
- "predicate";
+ "predicate";
protected static final String PROP_ENABLE =
- "enable";
+ "enable";
public IConfigStore mConfig = null;
private String pattern = null;
-
+
public String[] getExtendedPluginInfo(Locale locale) {
String s[] = {
"enable" + ";boolean;Enable this policy",
"predicate" + ";string;",
PROP_CRITICAL + ";boolean;",
- PROP_NAME + ";string;Name for this extension.",
- PROP_OID + ";string;OID number for this extension. It should be unique.",
+ PROP_NAME + ";string;Name for this extension.",
+ PROP_OID + ";string;OID number for this extension. It should be unique.",
PROP_PATTERN + ";string;Pattern for extension; {012}34",
// Attribute 0
PROP_ATTRIBUTE + "." + "0" + "." + PROP_TYPE + ";choice(Integer,IA5String,OctetString,PrintableString,VisibleString,UTCTime,OID,Boolean);Attribute type for extension",
@@ -165,14 +163,14 @@ public class GenericASN1Ext extends APolicyRule implements
PROP_ATTRIBUTE + "." + "9" + "." + PROP_SOURCE + ";choice(Value,File);Data Source for the extension. You can specify the value here or file name has value.",
PROP_ATTRIBUTE + "." + "9" + "." + PROP_VALUE + ";string;If data source is 'value', specity value here. If data source is 'file', specify the file name with full path.",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-genericasn1ext",
+ ";configuration-policyrules-genericasn1ext",
IExtendedPluginInfo.HELP_TEXT +
- ";Adds Private extension based on ASN1. See manual"
+ ";Adds Private extension based on ASN1. See manual"
};
return s;
}
-
+
public GenericASN1Ext() {
NAME = "GenericASN1Ext";
DESC = "Sets Generic extension for certificates";
@@ -181,17 +179,17 @@ public class GenericASN1Ext extends APolicyRule implements
/**
* Initializes this policy rule.
* <P>
- *
+ *
* The entries may be of the form:
- *
- * ca.Policy.rule.<ruleName>.implName=genericASNExt
- * ca.Policy.rule.<ruleName>.enable=true
- * ca.Policy.rule.<ruleName>.predicate=
- *
- * @param config The config store reference
+ *
+ * ca.Policy.rule.<ruleName>.implName=genericASNExt
+ * ca.Policy.rule.<ruleName>.enable=true
+ * ca.Policy.rule.<ruleName>.predicate=
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mConfig = config;
if (mConfig == null) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("POLICY_INIT_ERROR"));
@@ -202,33 +200,33 @@ public class GenericASN1Ext extends APolicyRule implements
if (enable == false)
return;
-
+
String oid = mConfig.getString(PROP_OID, null);
if ((oid == null) || (oid.length() == 0)) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("POLICY_INIT_ERROR"));
return;
}
-
+
String name = mConfig.getString(PROP_NAME, null);
if ((name == null) || (name.length() == 0)) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("POLICY_INIT_ERROR"));
return;
}
-
+
try {
if (File.separatorChar == '\\') {
pattern = mConfig.getString(PROP_PATTERN, null);
checkFilename(0);
- }
+ }
} catch (IOException e) {
log(ILogger.LL_FAILURE, "" + e.toString());
} catch (EBaseException e) {
log(ILogger.LL_FAILURE, "" + e.toString());
}
-
- // Check OID value
+
+ // Check OID value
CMS.checkOID(name, oid);
pattern = mConfig.getString(PROP_PATTERN, null);
checkOID(0);
@@ -241,14 +239,14 @@ public class GenericASN1Ext extends APolicyRule implements
} catch (CertificateException e) {
log(ILogger.LL_FAILURE, "" + e.toString());
}
-
+
}
// Check filename
- private int checkFilename(int index)
- throws IOException, EBaseException {
+ private int checkFilename(int index)
+ throws IOException, EBaseException {
String source = null;
-
+
while (index < pattern.length()) {
char ch = pattern.charAt(index);
@@ -262,28 +260,28 @@ public class GenericASN1Ext extends APolicyRule implements
return index;
default:
- source = mConfig.getString(PROP_ATTRIBUTE + "." + ch + "." + PROP_SOURCE, null);
+ source = mConfig.getString(PROP_ATTRIBUTE + "." + ch + "." + PROP_SOURCE, null);
if ((source != null) && (source.equalsIgnoreCase("file"))) {
- String oValue = mConfig.getString(PROP_ATTRIBUTE + "." + ch + "." + PROP_VALUE, null);
+ String oValue = mConfig.getString(PROP_ATTRIBUTE + "." + ch + "." + PROP_VALUE, null);
String nValue = oValue.replace('\\', '/');
- mConfig.putString(PROP_ATTRIBUTE + "." + ch + "." + PROP_VALUE, nValue);
+ mConfig.putString(PROP_ATTRIBUTE + "." + ch + "." + PROP_VALUE, nValue);
FileInputStream fis = new FileInputStream(nValue);
fis.close();
- }
+ }
}
index++;
- }
+ }
return index;
}
// Check oid
- private int checkOID(int index)
- throws EBaseException {
+ private int checkOID(int index)
+ throws EBaseException {
String type = null;
String oid = null;
-
+
while (index < pattern.length()) {
char ch = pattern.charAt(index);
@@ -297,23 +295,23 @@ public class GenericASN1Ext extends APolicyRule implements
return index;
default:
- type = mConfig.getString(PROP_ATTRIBUTE + "." + ch + "." + PROP_TYPE, null);
+ type = mConfig.getString(PROP_ATTRIBUTE + "." + ch + "." + PROP_TYPE, null);
if ((type != null) && (type.equalsIgnoreCase("OID"))) {
- oid = mConfig.getString(PROP_ATTRIBUTE + "." + ch + "." + PROP_VALUE, null);
+ oid = mConfig.getString(PROP_ATTRIBUTE + "." + ch + "." + PROP_VALUE, null);
CMS.checkOID(oid, oid);
- }
+ }
}
index++;
- }
+ }
return index;
}
-
+
/**
- * If this policy is enabled, add the private Integer
- * information extension to the certificate.
+ * If this policy is enabled, add the private Integer information extension
+ * to the certificate.
* <P>
- *
+ *
* @param req The request on which to apply policy.
* @return The policy result object.
*/
@@ -321,9 +319,9 @@ public class GenericASN1Ext extends APolicyRule implements
PolicyResult res = PolicyResult.ACCEPTED;
X509CertInfo certInfo;
X509CertInfo[] ci = req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
-
+
if (ci == null) {
- setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO"), NAME);
+ setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO"), NAME);
return PolicyResult.REJECTED; // unrecoverable error.
}
@@ -343,7 +341,7 @@ public class GenericASN1Ext extends APolicyRule implements
if (extensions == null) {
// create extension if not exist
certInfo.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ new CertificateVersion(CertificateVersion.V3));
extensions = new CertificateExtensions();
certInfo.set(X509CertInfo.EXTENSIONS, extensions);
} else {
@@ -358,35 +356,35 @@ public class GenericASN1Ext extends APolicyRule implements
// Create the extension
GenericASN1Extension priExt = mkExtension();
-
+
extensions.set(priExt.getName(), priExt);
} catch (IOException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("BASE_IO_ERROR", e.getMessage()));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
- NAME, e.getMessage());
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
+ NAME, e.getMessage());
return PolicyResult.REJECTED; // unrecoverable error.
} catch (EBaseException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CA_CERT_INFO_ERROR", e.getMessage()));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
- NAME, "Configuration Info Error");
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
+ NAME, "Configuration Info Error");
return PolicyResult.REJECTED; // unrecoverable error.
} catch (CertificateException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CA_CERT_INFO_ERROR", e.getMessage()));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
- NAME, "Certificate Info Error");
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
+ NAME, "Certificate Info Error");
return PolicyResult.REJECTED; // unrecoverable error.
} catch (ParseException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("BASE_EXTENSION_ERROR", e.getMessage()));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
- NAME, "Pattern parsing error");
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("BASE_EXTENSION_ERROR", e.getMessage()));
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
+ NAME, "Pattern parsing error");
return PolicyResult.REJECTED; // unrecoverable error.
} catch (Exception e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("BASE_UNKNOWN_EXCEPTION", e.getMessage()));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
- NAME, "Unknown Error");
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("BASE_UNKNOWN_EXCEPTION", e.getMessage()));
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
+ NAME, "Unknown Error");
return PolicyResult.REJECTED; // unrecoverable error.
}
}
@@ -397,7 +395,7 @@ public class GenericASN1Ext extends APolicyRule implements
* Construct GenericASN1Extension with value from CMS.cfg
*/
protected GenericASN1Extension mkExtension()
- throws IOException, EBaseException, ParseException {
+ throws IOException, EBaseException, ParseException {
GenericASN1Extension ext;
Hashtable<String, String> h = new Hashtable<String, String>();
@@ -413,21 +411,21 @@ public class GenericASN1Ext extends APolicyRule implements
String proptype = PROP_ATTRIBUTE + "." + idx + "." + PROP_TYPE;
String propsource = PROP_ATTRIBUTE + "." + idx + "." + PROP_SOURCE;
String propvalue = PROP_ATTRIBUTE + "." + idx + "." + PROP_VALUE;
-
+
h.put(proptype, mConfig.getString(proptype, null));
h.put(propsource, mConfig.getString(propsource, null));
h.put(propvalue, mConfig.getString(propvalue, null));
}
ext = new GenericASN1Extension(h);
return ext;
- }
-
+ }
+
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getInstanceParams() {
+ public Vector<String> getInstanceParams() {
int idx = 0;
Vector<String> params = new Vector<String>();
@@ -436,7 +434,7 @@ public class GenericASN1Ext extends APolicyRule implements
params.addElement(PROP_NAME + "=" + mConfig.getString(PROP_NAME, null));
params.addElement(PROP_OID + "=" + mConfig.getString(PROP_OID, null));
params.addElement(PROP_PATTERN + "=" + mConfig.getString(PROP_PATTERN, null));
-
+
for (idx = 0; idx < MAX_ATTR; idx++) {
String proptype = PROP_ATTRIBUTE + "." + idx + "." + PROP_TYPE;
String propsource = PROP_ATTRIBUTE + "." + idx + "." + PROP_SOURCE;
@@ -447,7 +445,8 @@ public class GenericASN1Ext extends APolicyRule implements
params.addElement(propvalue + "=" + mConfig.getString(propvalue, null));
}
params.addElement(PROP_PREDICATE + "=" + mConfig.getString(PROP_PREDICATE, null));
- } catch (EBaseException e) {;
+ } catch (EBaseException e) {
+ ;
}
return params;
@@ -455,26 +454,25 @@ public class GenericASN1Ext extends APolicyRule implements
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getDefaultParams() {
+ public Vector<String> getDefaultParams() {
int idx = 0;
-
+
Vector<String> defParams = new Vector<String>();
defParams.addElement(PROP_CRITICAL + "=false");
defParams.addElement(PROP_NAME + "=");
defParams.addElement(PROP_OID + "=");
defParams.addElement(PROP_PATTERN + "=");
-
+
for (idx = 0; idx < MAX_ATTR; idx++) {
defParams.addElement(PROP_ATTRIBUTE + "." + idx + "." + PROP_TYPE + "=");
defParams.addElement(PROP_ATTRIBUTE + "." + idx + "." + PROP_SOURCE + "=");
defParams.addElement(PROP_ATTRIBUTE + "." + idx + "." + PROP_VALUE + "=");
}
-
+
return defParams;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/policy/extensions/IssuerAltNameExt.java b/pki/base/common/src/com/netscape/cms/policy/extensions/IssuerAltNameExt.java
index 9524f689..fc975fd3 100644
--- a/pki/base/common/src/com/netscape/cms/policy/extensions/IssuerAltNameExt.java
+++ b/pki/base/common/src/com/netscape/cms/policy/extensions/IssuerAltNameExt.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.extensions;
-
import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.Locale;
@@ -41,23 +40,23 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
* Issuer Alt Name Extension policy.
*
- * This extension is used to associate Internet-style identities
- * with the Certificate issuer.
+ * This extension is used to associate Internet-style identities with the
+ * Certificate issuer.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public class IssuerAltNameExt extends APolicyRule
- implements IEnrollmentPolicy, IExtendedPluginInfo {
+ implements IEnrollmentPolicy, IExtendedPluginInfo {
public static final String PROP_CRITICAL = "critical";
// PKIX specifies the that the extension SHOULD NOT be critical
@@ -69,15 +68,15 @@ public class IssuerAltNameExt extends APolicyRule
static {
defaultParams.addElement(PROP_CRITICAL + "=" + DEFAULT_CRITICALITY);
CMS.getGeneralNamesConfigDefaultParams(null, true, defaultParams);
-
+
Vector<String> info = new Vector<String>();
info.addElement(PROP_CRITICAL + ";boolean;RFC 2459 recommendation: SHOULD NOT be marked critical.");
info.addElement(IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-issueraltname");
+ ";configuration-policyrules-issueraltname");
info.addElement(IExtendedPluginInfo.HELP_TEXT +
- ";This policy inserts the Issuer Alternative Name " +
- "Extension into the certificate. See RFC 2459 (4.2.1.8). ");
+ ";This policy inserts the Issuer Alternative Name " +
+ "Extension into the certificate. See RFC 2459 (4.2.1.8). ");
CMS.getGeneralNamesConfigExtendedPluginInfo(null, true, info);
@@ -102,10 +101,11 @@ public class IssuerAltNameExt extends APolicyRule
/**
* Initializes this policy rule.
- * @param config The config store reference
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mConfig = config;
// get criticality
@@ -120,43 +120,43 @@ public class IssuerAltNameExt extends APolicyRule
// form extension
try {
- if (mEnabled &&
- mGNs.getGeneralNames() != null && !mGNs.getGeneralNames().isEmpty()) {
- mExtension =
+ if (mEnabled &&
+ mGNs.getGeneralNames() != null && !mGNs.getGeneralNames().isEmpty()) {
+ mExtension =
new IssuerAlternativeNameExtension(
- Boolean.valueOf(mCritical), mGNs.getGeneralNames());
+ Boolean.valueOf(mCritical), mGNs.getGeneralNames());
}
} catch (Exception e) {
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR", e.toString()));
}
// init instance params
- mParams.addElement(PROP_CRITICAL + "=" + mCritical);
+ mParams.addElement(PROP_CRITICAL + "=" + mCritical);
mGNs.getInstanceParams(mParams);
return;
}
/**
- * Adds a extension if none exists.
- *
- * @param req The request on which to apply policy.
+ * Adds a extension if none exists.
+ *
+ * @param req The request on which to apply policy.
* @return The policy result object.
*/
public PolicyResult apply(IRequest req) {
PolicyResult res = PolicyResult.ACCEPTED;
- if (mEnabled == false || mExtension == null)
+ if (mEnabled == false || mExtension == null)
return res;
- // get cert info.
- X509CertInfo[] ci =
- req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
+ // get cert info.
+ X509CertInfo[] ci =
+ req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
X509CertInfo certInfo = null;
if (ci == null || (certInfo = ci[0]) == null) {
- setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO"), NAME);
+ setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO"), NAME);
return PolicyResult.REJECTED; // unrecoverable error.
}
@@ -188,7 +188,7 @@ public class IssuerAltNameExt extends APolicyRule
extensions = new CertificateExtensions();
try {
certInfo.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ new CertificateVersion(CertificateVersion.V3));
certInfo.set(X509CertInfo.EXTENSIONS, extensions);
} catch (CertificateException e) {
// not possible
@@ -214,10 +214,10 @@ public class IssuerAltNameExt extends APolicyRule
try {
extensions.set(IssuerAlternativeNameExtension.class.getSimpleName(), mExtension);
} catch (Exception e) {
- if (e instanceof RuntimeException)
+ if (e instanceof RuntimeException)
throw (RuntimeException) e;
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CRL_CREATE_ISSUER_ALT_NAME_EXT", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CRL_CREATE_ISSUER_ALT_NAME_EXT", e.toString()));
setError(req, CMS.getUserMessage("CMS_POLICY_SUBJECT_KEY_ID_ERROR"), NAME);
return PolicyResult.REJECTED;
}
@@ -226,21 +226,21 @@ public class IssuerAltNameExt extends APolicyRule
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return Empty Vector since this policy has no configuration parameters.
- * for this policy instance.
+ * for this policy instance.
*/
- public Vector<String> getInstanceParams() {
+ public Vector<String> getInstanceParams() {
return mParams;
}
/**
* Return default parameters for a policy implementation.
- *
- * @return Empty Vector since this policy implementation has no
- * configuration parameters.
+ *
+ * @return Empty Vector since this policy implementation has no
+ * configuration parameters.
*/
- public Vector<String> getDefaultParams() {
+ public Vector<String> getDefaultParams() {
return defaultParams;
}
@@ -249,4 +249,3 @@ public class IssuerAltNameExt extends APolicyRule
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/policy/extensions/KeyUsageExt.java b/pki/base/common/src/com/netscape/cms/policy/extensions/KeyUsageExt.java
index 4e9ef825..0988a636 100644
--- a/pki/base/common/src/com/netscape/cms/policy/extensions/KeyUsageExt.java
+++ b/pki/base/common/src/com/netscape/cms/policy/extensions/KeyUsageExt.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.extensions;
-
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
@@ -44,25 +43,25 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
- * Policy to add Key Usage Extension.
- * Adds the key usage extension based on what's requested.
+ * Policy to add Key Usage Extension. Adds the key usage extension based on
+ * what's requested.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public class KeyUsageExt extends APolicyRule
- implements IEnrollmentPolicy, IExtendedPluginInfo {
+ implements IEnrollmentPolicy, IExtendedPluginInfo {
private final static String HTTP_INPUT = "HTTP_INPUT";
- protected static final boolean[] DEF_BITS =
- new boolean[KeyUsageExtension.NBITS];
+ protected static final boolean[] DEF_BITS =
+ new boolean[KeyUsageExtension.NBITS];
protected int mCAPathLen = -1;
protected IConfigStore mConfig = null;
protected static final String PROP_CRITICAL = "critical";
@@ -97,25 +96,24 @@ public class KeyUsageExt extends APolicyRule
/**
* Initializes this policy rule.
* <P>
- *
+ *
* The entries may be of the form:
- *
- * ca.Policy.rule.<ruleName>.implName=KeyUsageExt
- * ca.Policy.rule.<ruleName>.enable=true
- * ca.Policy.rule.<ruleName>.
- *
- * @param config The config store reference
+ *
+ * ca.Policy.rule.<ruleName>.implName=KeyUsageExt
+ * ca.Policy.rule.<ruleName>.enable=true ca.Policy.rule.<ruleName>.
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mConfig = config;
ICertAuthority certAuthority = (ICertAuthority)
- ((IPolicyProcessor) owner).getAuthority();
+ ((IPolicyProcessor) owner).getAuthority();
if (certAuthority == null) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CA_CANT_FIND_MANAGER"));
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR",
"Cannot find the Certificate Manager or Registration Manager"));
}
@@ -123,9 +121,9 @@ public class KeyUsageExt extends APolicyRule
CertificateChain caChain = certAuthority.getCACertChain();
X509Certificate caCert = null;
- // Note that in RA the chain could be null if CA was not up when
- // RA was started. In that case just set the length to -1 and let
- // CA reject if it does not allow any subordinate CA certs.
+ // Note that in RA the chain could be null if CA was not up when
+ // RA was started. In that case just set the length to -1 and let
+ // CA reject if it does not allow any subordinate CA certs.
if (caChain != null) {
caCert = caChain.getFirstCertificate();
mCAPathLen = caCert.getBasicConstraints();
@@ -145,30 +143,29 @@ public class KeyUsageExt extends APolicyRule
}
/**
- * Adds the key usage extension if not set already.
- * (CRMF, agent, authentication (currently) or PKCS#10 (future)
- * or RA could have set the extension.)
- * If not set, set from http input parameters or use default if
+ * Adds the key usage extension if not set already. (CRMF, agent,
+ * authentication (currently) or PKCS#10 (future) or RA could have set the
+ * extension.) If not set, set from http input parameters or use default if
* no http input parameters are set.
*
- * Note: this allows any bits requested - does not check if user
- * authenticated is allowed to have a Key Usage Extension with
- * those bits. Unless the CA's certificate path length is 0, then
- * we do not allow CA sign or CRL sign bits in any request.
+ * Note: this allows any bits requested - does not check if user
+ * authenticated is allowed to have a Key Usage Extension with those bits.
+ * Unless the CA's certificate path length is 0, then we do not allow CA
+ * sign or CRL sign bits in any request.
*
* <P>
- *
- * @param req The request on which to apply policy.
+ *
+ * @param req The request on which to apply policy.
* @return The policy result object.
*/
public PolicyResult apply(IRequest req) {
PolicyResult res = PolicyResult.ACCEPTED;
- X509CertInfo[] ci =
- req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
+ X509CertInfo[] ci =
+ req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
if (ci == null || ci[0] == null) {
- setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO"), NAME);
+ setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO"), NAME);
return PolicyResult.REJECTED; // unrecoverable error.
}
@@ -184,7 +181,7 @@ public class KeyUsageExt extends APolicyRule
public PolicyResult applyCert(IRequest req, X509CertInfo certInfo) {
try {
CertificateExtensions extensions = (CertificateExtensions)
- certInfo.get(X509CertInfo.EXTENSIONS);
+ certInfo.get(X509CertInfo.EXTENSIONS);
KeyUsageExtension ext = null;
if (extensions != null) {
@@ -195,7 +192,7 @@ public class KeyUsageExt extends APolicyRule
// extension isn't there.
ext = null;
}
- // check if CA does not allow subordinate CA certs.
+ // check if CA does not allow subordinate CA certs.
// otherwise accept existing key usage extension.
if (ext != null) {
if (mCAPathLen == 0) {
@@ -203,11 +200,11 @@ public class KeyUsageExt extends APolicyRule
if ((bits.length > KeyUsageExtension.KEY_CERTSIGN_BIT &&
bits[KeyUsageExtension.KEY_CERTSIGN_BIT] == true) ||
- (bits.length > KeyUsageExtension.CRL_SIGN_BIT &&
+ (bits.length > KeyUsageExtension.CRL_SIGN_BIT &&
bits[KeyUsageExtension.CRL_SIGN_BIT] == true)) {
- setError(req,
- CMS.getUserMessage("CMS_POLICY_NO_SUB_CA_CERTS_ALLOWED"),
- NAME);
+ setError(req,
+ CMS.getUserMessage("CMS_POLICY_NO_SUB_CA_CERTS_ALLOWED"),
+ NAME);
return PolicyResult.REJECTED;
}
}
@@ -216,8 +213,8 @@ public class KeyUsageExt extends APolicyRule
} else {
// create extensions set if none.
if (extensions == null) {
- certInfo.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ certInfo.set(X509CertInfo.VERSION,
+ new CertificateVersion(CertificateVersion.V3));
extensions = new CertificateExtensions();
certInfo.set(X509CertInfo.EXTENSIONS, extensions);
}
@@ -225,41 +222,41 @@ public class KeyUsageExt extends APolicyRule
boolean[] bits = new boolean[KeyUsageExtension.NBITS];
- bits[KeyUsageExtension.DIGITAL_SIGNATURE_BIT] = getBit("digital_signature",
- mDigitalSignature, req);
- bits[KeyUsageExtension.NON_REPUDIATION_BIT] = getBit("non_repudiation",
+ bits[KeyUsageExtension.DIGITAL_SIGNATURE_BIT] = getBit("digital_signature",
+ mDigitalSignature, req);
+ bits[KeyUsageExtension.NON_REPUDIATION_BIT] = getBit("non_repudiation",
mNonRepudiation, req);
- bits[KeyUsageExtension.KEY_ENCIPHERMENT_BIT] = getBit("key_encipherment",
+ bits[KeyUsageExtension.KEY_ENCIPHERMENT_BIT] = getBit("key_encipherment",
mKeyEncipherment, req);
- bits[KeyUsageExtension.DATA_ENCIPHERMENT_BIT] = getBit("data_encipherment",
+ bits[KeyUsageExtension.DATA_ENCIPHERMENT_BIT] = getBit("data_encipherment",
mDataEncipherment, req);
- bits[KeyUsageExtension.KEY_AGREEMENT_BIT] = getBit("key_agreement",
- mKeyAgreement, req);
- bits[KeyUsageExtension.KEY_CERTSIGN_BIT] = getBit("key_certsign",
+ bits[KeyUsageExtension.KEY_AGREEMENT_BIT] = getBit("key_agreement",
+ mKeyAgreement, req);
+ bits[KeyUsageExtension.KEY_CERTSIGN_BIT] = getBit("key_certsign",
mKeyCertsign, req);
bits[KeyUsageExtension.CRL_SIGN_BIT] = getBit("crl_sign", mCrlSign, req);
bits[KeyUsageExtension.ENCIPHER_ONLY_BIT] = getBit("encipher_only",
mEncipherOnly, req);
- bits[KeyUsageExtension.DECIPHER_ONLY_BIT] = getBit("decipher_only",
+ bits[KeyUsageExtension.DECIPHER_ONLY_BIT] = getBit("decipher_only",
mDecipherOnly, req);
-
- // don't allow no bits set or the extension does not
+
+ // don't allow no bits set or the extension does not
// encode/decode properlly.
boolean bitset = false;
for (int i = 0; i < bits.length; i++) {
if (bits[i]) {
- bitset = true;
+ bitset = true;
break;
}
}
if (!bitset) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("POLICY_NO_KEYUSAGE_EXTENSION_BITS_SET", NAME));
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("POLICY_NO_KEYUSAGE_EXTENSION_BITS_SET", NAME));
setError(req, CMS.getUserMessage("CMS_POLICY_NO_KEYUSAGE_EXTENSION_BITS_SET"),
- NAME);
+ NAME);
return PolicyResult.REJECTED;
}
-
+
// create the extension.
try {
mKeyUsage = new KeyUsageExtension(mCritical, bits);
@@ -269,23 +266,23 @@ public class KeyUsageExt extends APolicyRule
return PolicyResult.ACCEPTED;
} catch (IOException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("BASE_IO_ERROR", e.getMessage()));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
- NAME, e.getMessage());
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
+ NAME, e.getMessage());
return PolicyResult.REJECTED; // unrecoverable error.
} catch (CertificateException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CA_CERT_INFO_ERROR", e.getMessage()));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
- NAME, "Certificate Info Error");
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
+ NAME, "Certificate Info Error");
return PolicyResult.REJECTED; // unrecoverable error.
}
}
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getInstanceParams() {
+ public Vector<String> getInstanceParams() {
Vector<String> params = new Vector<String>();
params.addElement(PROP_CRITICAL + "=" + mCritical);
@@ -328,21 +325,21 @@ public class KeyUsageExt extends APolicyRule
PROP_ENCIPHER_ONLY + ";choice(true,false,HTTP_INPUT);true means always set this bit, false means don't set this bit, HTTP_INPUT means get this bit from the HTTP input",
PROP_DECIPHER_ONLY + ";choice(true,false,HTTP_INPUT);true means always set this bit, false means don't set this bit, HTTP_INPUT means get this bit from the HTTP input",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-keyusage",
+ ";configuration-policyrules-keyusage",
IExtendedPluginInfo.HELP_TEXT +
- ";Adds Key Usage Extension; See in RFC 2459 (4.2.1.3)"
+ ";Adds Key Usage Extension; See in RFC 2459 (4.2.1.3)"
- };
+ };
return params;
}
-
+
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getDefaultParams() {
+ public Vector<String> getDefaultParams() {
return mDefParams;
}
@@ -355,4 +352,3 @@ public class KeyUsageExt extends APolicyRule
return Boolean.valueOf(choice).booleanValue();
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/policy/extensions/NSCCommentExt.java b/pki/base/common/src/com/netscape/cms/policy/extensions/NSCCommentExt.java
index 019e3e08..c453eb0d 100644
--- a/pki/base/common/src/com/netscape/cms/policy/extensions/NSCCommentExt.java
+++ b/pki/base/common/src/com/netscape/cms/policy/extensions/NSCCommentExt.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.extensions;
-
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
@@ -45,21 +44,20 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
- * Netscape comment
- * Adds Netscape comment policy
+ * Netscape comment Adds Netscape comment policy
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public class NSCCommentExt extends APolicyRule
- implements IEnrollmentPolicy, IExtendedPluginInfo {
+ implements IEnrollmentPolicy, IExtendedPluginInfo {
protected static final String PROP_USER_NOTICE_DISPLAY_TEXT = "displayText";
protected static final String PROP_COMMENT_FILE = "commentFile";
@@ -68,19 +66,18 @@ public class NSCCommentExt extends APolicyRule
protected static final String TEXT = "Text";
protected static final String FILE = "File";
- protected String mUserNoticeDisplayText;
- protected String mCommentFile;
- protected String mInputType;
+ protected String mUserNoticeDisplayText;
+ protected String mCommentFile;
+ protected String mInputType;
protected boolean mCritical;
private Vector<String> mParams = new Vector<String>();
- protected String tempCommentFile;
+ protected String tempCommentFile;
protected boolean certApplied = false;
/**
- * Adds the Netscape comment in the end-entity certificates or
- * CA certificates. The policy is set to be non-critical with the
- * provided OID.
+ * Adds the Netscape comment in the end-entity certificates or CA
+ * certificates. The policy is set to be non-critical with the provided OID.
*/
public NSCCommentExt() {
NAME = "NSCCommentExt";
@@ -91,16 +88,16 @@ public class NSCCommentExt extends APolicyRule
* Initializes this policy rule.
* <p>
* The entries may be of the form:
- *
- * ca.Policy.rule.<ruleName>.implName=NSCCommentExtImpl
- * ca.Policy.rule.<ruleName>.displayText=<n>
- * ca.Policy.rule.<ruleName>.commentFile=<n>
- * ca.Policy.rule.<ruleName>.enable=false
- *
- * @param config The config store reference
+ *
+ * ca.Policy.rule.<ruleName>.implName=NSCCommentExtImpl
+ * ca.Policy.rule.<ruleName>.displayText=<n>
+ * ca.Policy.rule.<ruleName>.commentFile=<n>
+ * ca.Policy.rule.<ruleName>.enable=false
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
FileInputStream fileStream = null;
@@ -138,11 +135,11 @@ public class NSCCommentExt extends APolicyRule
mParams.addElement(PROP_COMMENT_FILE + "=" + mCommentFile);
} catch (FileNotFoundException e) {
- Object[] params = {getInstanceName(), "File not found : " + tempCommentFile};
+ Object[] params = { getInstanceName(), "File not found : " + tempCommentFile };
throw new EPolicyException(CMS.getUserMessage("CMS_POLICY_INVALID_POLICY_CONFIG"), params);
} catch (Exception e) {
- Object[] params = {getInstanceName(), e.getMessage()};
+ Object[] params = { getInstanceName(), e.getMessage() };
throw new EPolicyException(CMS.getUserMessage("CMS_POLICY_INVALID_POLICY_CONFIG"), params);
}
@@ -151,16 +148,16 @@ public class NSCCommentExt extends APolicyRule
/**
* Applies the policy on the given Request.
* <p>
- *
- * @param req The request on which to apply policy.
+ *
+ * @param req The request on which to apply policy.
* @return The policy result object.
*/
public PolicyResult apply(IRequest req) {
PolicyResult res = PolicyResult.ACCEPTED;
// get cert info.
- X509CertInfo[] ci =
- req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
+ X509CertInfo[] ci =
+ req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
if (ci == null || ci[0] == null) {
setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO"), NAME);
@@ -191,8 +188,8 @@ public class NSCCommentExt extends APolicyRule
if (extensions == null) {
extensions = new CertificateExtensions();
try {
- certInfo.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ certInfo.set(X509CertInfo.VERSION,
+ new CertificateVersion(CertificateVersion.V3));
certInfo.set(X509CertInfo.EXTENSIONS, extensions);
} catch (Exception e) {
}
@@ -200,10 +197,10 @@ public class NSCCommentExt extends APolicyRule
// remove any previously computed version of the extension
try {
extensions.delete(NSCCommentExtension.class.getSimpleName());
-
+
} catch (IOException e) {
// this is the hack: for some reason, the key which is the name
- // of the policy has been converted into the OID
+ // of the policy has been converted into the OID
try {
extensions.delete("2.16.840.1.113730.1.13");
} catch (IOException ee) {
@@ -211,7 +208,8 @@ public class NSCCommentExt extends APolicyRule
}
}
if (mInputType.equals("File")) {
- // if ((mUserNoticeDisplayText.equals("")) && !(mCommentFile.equals(""))) {
+ // if ((mUserNoticeDisplayText.equals("")) &&
+ // !(mCommentFile.equals(""))) {
try {
// Read the comments file
BufferedReader fis = new BufferedReader(new FileReader(mCommentFile));
@@ -225,9 +223,9 @@ public class NSCCommentExt extends APolicyRule
fis.close();
} catch (IOException e) {
setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
- NAME, " Comment Text file not found : " + mCommentFile);
+ NAME, " Comment Text file not found : " + mCommentFile);
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("POLICY_COMMENT_FILE_NOT_FOUND", e.toString()));
+ CMS.getLogMessage("POLICY_COMMENT_FILE_NOT_FOUND", e.toString()));
return PolicyResult.REJECTED;
}
@@ -235,20 +233,20 @@ public class NSCCommentExt extends APolicyRule
}
certApplied = true;
-
+
DisplayText displayText =
- new DisplayText(DisplayText.tag_IA5String, mUserNoticeDisplayText);
+ new DisplayText(DisplayText.tag_IA5String, mUserNoticeDisplayText);
try {
- NSCCommentExtension cpExt =
- new NSCCommentExtension(mCritical, mUserNoticeDisplayText);
+ NSCCommentExtension cpExt =
+ new NSCCommentExtension(mCritical, mUserNoticeDisplayText);
extensions.set(NSCCommentExtension.class.getSimpleName(), cpExt);
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("POLICY_ERROR_CERTIFICATE_POLICIES_1", NAME));
+ CMS.getLogMessage("POLICY_ERROR_CERTIFICATE_POLICIES_1", NAME));
setError(req,
- CMS.getUserMessage("CMS_POLICY_CERTIFICATE_POLICIES_ERROR"), NAME);
+ CMS.getUserMessage("CMS_POLICY_CERTIFICATE_POLICIES_ERROR"), NAME);
return PolicyResult.REJECTED;
}
return PolicyResult.ACCEPTED;
@@ -258,16 +256,16 @@ public class NSCCommentExt extends APolicyRule
String[] params = {
PROP_CRITICAL + ";boolean;Netscape recommendation: non-critical.",
PROP_INPUT_TYPE + ";choice(Text,File);Whether the comments " +
- "would be entered in the displayText field or come from " +
- "a file.",
+ "would be entered in the displayText field or come from " +
+ "a file.",
PROP_USER_NOTICE_DISPLAY_TEXT + ";string;The comment that may be " +
- "displayed to the user when the certificate is viewed.",
+ "displayed to the user when the certificate is viewed.",
PROP_COMMENT_FILE + ";string; If data source is 'File', specify " +
- "the file name with full path.",
+ "the file name with full path.",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-nsccomment",
+ ";configuration-policyrules-nsccomment",
IExtendedPluginInfo.HELP_TEXT +
- ";Adds 'netscape comment' extension. See manual"
+ ";Adds 'netscape comment' extension. See manual"
};
return params;
@@ -276,19 +274,19 @@ public class NSCCommentExt extends APolicyRule
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getInstanceParams() {
+ public Vector<String> getInstanceParams() {
return mParams;
}
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getDefaultParams() {
+ public Vector<String> getDefaultParams() {
Vector<String> defParams = new Vector<String>();
defParams.addElement(PROP_CRITICAL + "=false");
diff --git a/pki/base/common/src/com/netscape/cms/policy/extensions/NSCertTypeExt.java b/pki/base/common/src/com/netscape/cms/policy/extensions/NSCertTypeExt.java
index 88c57d2e..c80f65e5 100644
--- a/pki/base/common/src/com/netscape/cms/policy/extensions/NSCertTypeExt.java
+++ b/pki/base/common/src/com/netscape/cms/policy/extensions/NSCertTypeExt.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.extensions;
-
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
@@ -46,45 +45,45 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
- * NS Cert Type policy.
- * Adds the ns cert type extension depending on cert type requested.
+ * NS Cert Type policy. Adds the ns cert type extension depending on cert type
+ * requested.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public class NSCertTypeExt extends APolicyRule
- implements IEnrollmentPolicy, IExtendedPluginInfo {
+ implements IEnrollmentPolicy, IExtendedPluginInfo {
protected static final String PROP_SET_DEFAULT_BITS = "setDefaultBits";
protected static final boolean DEF_SET_DEFAULT_BITS = true;
- protected static final String DEF_SET_DEFAULT_BITS_VAL =
- Boolean.valueOf(DEF_SET_DEFAULT_BITS).toString();
+ protected static final String DEF_SET_DEFAULT_BITS_VAL =
+ Boolean.valueOf(DEF_SET_DEFAULT_BITS).toString();
protected static final int DEF_PATHLEN = -1;
- protected static final boolean[] DEF_BITS =
- new boolean[NSCertTypeExtension.NBITS];
+ protected static final boolean[] DEF_BITS =
+ new boolean[NSCertTypeExtension.NBITS];
- // XXX for future use. currenlty always allow.
+ // XXX for future use. currenlty always allow.
protected static final String PROP_AGENT_OVERR = "allowAgentOverride";
protected static final String PROP_EE_OVERR = "AllowEEOverride";
- // XXX for future use. currently always critical
- // (standard says SHOULD be marked critical if included.)
+ // XXX for future use. currently always critical
+ // (standard says SHOULD be marked critical if included.)
protected static final String PROP_CRITICAL = "critical";
- // XXX for future use to allow overrides from forms.
+ // XXX for future use to allow overrides from forms.
// request must be agent approved or authenticated.
protected boolean mAllowAgentOverride = false;
protected boolean mAllowEEOverride = false;
- // XXX for future use. currently always non-critical
+ // XXX for future use. currently always non-critical
protected boolean mCritical = false;
protected int mCAPathLen = -1;
@@ -112,25 +111,25 @@ public class NSCertTypeExt extends APolicyRule
/**
* Initializes this policy rule.
* <P>
- *
+ *
* The entries may be of the form:
- *
- * ra.Policy.rule.<ruleName>.implName=nsCertTypeExt
- * ra.Policy.rule.<ruleName>.enable=true
- *
- * @param config The config store reference
+ *
+ * ra.Policy.rule.<ruleName>.implName=nsCertTypeExt
+ * ra.Policy.rule.<ruleName>.enable=true
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mConfig = config;
// XXX future use.
- //mAllowAgentOverride = config.getBoolean(PROP_AGENT_OVERR, false);
- //mAllowEEOverride = config.getBoolean(PROP_EE_OVERR, false);
+ // mAllowAgentOverride = config.getBoolean(PROP_AGENT_OVERR, false);
+ // mAllowEEOverride = config.getBoolean(PROP_EE_OVERR, false);
mCritical = config.getBoolean(PROP_CRITICAL, false);
ICertAuthority certAuthority = (ICertAuthority)
- ((IPolicyProcessor) owner).getAuthority();
+ ((IPolicyProcessor) owner).getAuthority();
if (certAuthority instanceof ICertificateAuthority) {
CertificateChain caChain = certAuthority.getCACertChain();
@@ -141,7 +140,7 @@ public class NSCertTypeExt extends APolicyRule
// CA reject if it does not allow any subordinate CA certs.
if (caChain != null) {
caCert = caChain.getFirstCertificate();
- if (caCert != null)
+ if (caCert != null)
mCAPathLen = caCert.getBasicConstraints();
}
}
@@ -151,25 +150,24 @@ public class NSCertTypeExt extends APolicyRule
}
/**
- * Adds the ns cert type if not set already.
- * reads ns cert type choices from form. If no choices from form
- * will defaults to all.
+ * Adds the ns cert type if not set already. reads ns cert type choices from
+ * form. If no choices from form will defaults to all.
* <P>
- *
- * @param req The request on which to apply policy.
+ *
+ * @param req The request on which to apply policy.
* @return The policy result object.
*/
public PolicyResult apply(IRequest req) {
CMS.debug("NSCertTypeExt: Impl: " + NAME + ", Instance: " + getInstanceName() + "::apply()");
PolicyResult res = PolicyResult.ACCEPTED;
- X509CertInfo[] ci =
- req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
-
+ X509CertInfo[] ci =
+ req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
+
X509CertInfo certInfo = null;
if (ci == null || (certInfo = ci[0]) == null) {
- setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO"), NAME);
+ setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO"), NAME);
return PolicyResult.REJECTED; // unrecoverable error.
}
@@ -184,10 +182,10 @@ public class NSCertTypeExt extends APolicyRule
public PolicyResult applyCert(IRequest req, X509CertInfo certInfo) {
try {
- String certType =
- req.getExtDataInString(IRequest.HTTP_PARAMS, IRequest.CERT_TYPE);
+ String certType =
+ req.getExtDataInString(IRequest.HTTP_PARAMS, IRequest.CERT_TYPE);
CertificateExtensions extensions = (CertificateExtensions)
- certInfo.get(X509CertInfo.EXTENSIONS);
+ certInfo.get(X509CertInfo.EXTENSIONS);
NSCertTypeExtension nsCertTypeExt = null;
if (extensions != null) {
@@ -201,13 +199,13 @@ public class NSCertTypeExt extends APolicyRule
}
// XXX agent servlet currently sets this. it should be
// delayed to here.
- if (nsCertTypeExt != null &&
- extensionIsGood(nsCertTypeExt, req)) {
+ if (nsCertTypeExt != null &&
+ extensionIsGood(nsCertTypeExt, req)) {
CMS.debug(
- "NSCertTypeExt: already has correct ns cert type ext");
+ "NSCertTypeExt: already has correct ns cert type ext");
return PolicyResult.ACCEPTED;
- } else if ((nsCertTypeExt != null) &&
- (certType.equals("ocspResponder"))) {
+ } else if ((nsCertTypeExt != null) &&
+ (certType.equals("ocspResponder"))) {
// Fix for #528732 : Always delete
// this extension from OCSP signing cert
extensions.delete(NSCertTypeExtension.class.getSimpleName());
@@ -216,12 +214,12 @@ public class NSCertTypeExt extends APolicyRule
} else {
// create extensions set if none.
if (extensions == null) {
- certInfo.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ certInfo.set(X509CertInfo.VERSION,
+ new CertificateVersion(CertificateVersion.V3));
extensions = new CertificateExtensions();
certInfo.set(X509CertInfo.EXTENSIONS, extensions);
CMS.debug(
- "NSCertTypeExt: Created extensions for adding ns cert type..");
+ "NSCertTypeExt: Created extensions for adding ns cert type..");
}
}
// add ns cert type extension if not set or not set correctly.
@@ -229,13 +227,13 @@ public class NSCertTypeExt extends APolicyRule
bits = getBitsFromRequest(req, mSetDefaultBits);
- // check if ca doesn't allow any subordinate ca
- if (mCAPathLen == 0 && bits != null) {
- if (bits[NSCertTypeExtension.SSL_CA_BIT] ||
- bits[NSCertTypeExtension.EMAIL_CA_BIT] ||
- bits[NSCertTypeExtension.OBJECT_SIGNING_CA_BIT]) {
- setError(req,
- CMS.getUserMessage("CMS_POLICY_NO_SUB_CA_CERTS_ALLOWED"), NAME);
+ // check if ca doesn't allow any subordinate ca
+ if (mCAPathLen == 0 && bits != null) {
+ if (bits[NSCertTypeExtension.SSL_CA_BIT] ||
+ bits[NSCertTypeExtension.EMAIL_CA_BIT] ||
+ bits[NSCertTypeExtension.OBJECT_SIGNING_CA_BIT]) {
+ setError(req,
+ CMS.getUserMessage("CMS_POLICY_NO_SUB_CA_CERTS_ALLOWED"), NAME);
return PolicyResult.REJECTED;
}
}
@@ -249,11 +247,12 @@ public class NSCertTypeExt extends APolicyRule
int j;
for (j = 0; bits != null && j < bits.length; j++)
- if (bits[j]) break;
+ if (bits[j])
+ break;
if (bits == null || j == bits.length) {
if (!mSetDefaultBits) {
CMS.debug(
- "NSCertTypeExt: no bits requested, not setting default.");
+ "NSCertTypeExt: no bits requested, not setting default.");
return PolicyResult.ACCEPTED;
} else
bits = DEF_BITS;
@@ -264,30 +263,29 @@ public class NSCertTypeExt extends APolicyRule
return PolicyResult.ACCEPTED;
} catch (IOException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("BASE_IO_ERROR", e.getMessage()));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
- NAME, e.getMessage());
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
+ NAME, e.getMessage());
return PolicyResult.REJECTED; // unrecoverable error.
} catch (CertificateException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CA_CERT_INFO_ERROR", e.getMessage()));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
- NAME, "Certificate Info Error");
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
+ NAME, "Certificate Info Error");
return PolicyResult.REJECTED; // unrecoverable error.
}
}
/**
- * check if ns cert type extension is set correctly,
- * correct bits if not.
- * if not authorized to set extension, bits will be replaced.
+ * check if ns cert type extension is set correctly, correct bits if not. if
+ * not authorized to set extension, bits will be replaced.
*/
protected boolean extensionIsGood(
- NSCertTypeExtension nsCertTypeExt, IRequest req)
- throws IOException, CertificateException {
+ NSCertTypeExtension nsCertTypeExt, IRequest req)
+ throws IOException, CertificateException {
// always return false for now to make sure minimum is set.
// agents and ee can add others.
- // must be agent approved or authenticated for allowing extensions
+ // must be agent approved or authenticated for allowing extensions
// which is always the case if we get to this point.
IAuthToken token = req.getExtDataInAuthToken(IRequest.AUTH_TOKEN);
@@ -295,7 +293,7 @@ public class NSCertTypeExt extends APolicyRule
// don't know where this came from.
// set all bits to false to reset.
CMS.debug(
- "NSCertTypeExt: unknown origin: setting ns cert type bits to false");
+ "NSCertTypeExt: unknown origin: setting ns cert type bits to false");
boolean[] bits = new boolean[8];
for (int i = bits.length - 1; i >= 0; i--) {
@@ -316,36 +314,36 @@ public class NSCertTypeExt extends APolicyRule
}
if (certType.equals(IRequest.CA_CERT)) {
if (!nsCertTypeExt.isSet(NSCertTypeExtension.SSL_CA_BIT) &&
- !nsCertTypeExt.isSet(NSCertTypeExtension.EMAIL_CA_BIT) &&
- !nsCertTypeExt.isSet(
- NSCertTypeExtension.OBJECT_SIGNING_CA_BIT)) {
+ !nsCertTypeExt.isSet(NSCertTypeExtension.EMAIL_CA_BIT) &&
+ !nsCertTypeExt.isSet(
+ NSCertTypeExtension.OBJECT_SIGNING_CA_BIT)) {
// min not set so set all.
CMS.debug(
- "NSCertTypeExt: is extension good: no ca bits set. set all");
+ "NSCertTypeExt: is extension good: no ca bits set. set all");
- nsCertTypeExt.set(NSCertTypeExtension.SSL_CA,
- Boolean.valueOf(true));
+ nsCertTypeExt.set(NSCertTypeExtension.SSL_CA,
+ Boolean.valueOf(true));
nsCertTypeExt.set(NSCertTypeExtension.EMAIL_CA,
- Boolean.valueOf(true));
+ Boolean.valueOf(true));
nsCertTypeExt.set(NSCertTypeExtension.OBJECT_SIGNING_CA,
- Boolean.valueOf(true));
+ Boolean.valueOf(true));
}
return true;
} else if (certType.equals(IRequest.CLIENT_CERT)) {
if (!nsCertTypeExt.isSet(NSCertTypeExtension.SSL_CLIENT_BIT) &&
- !nsCertTypeExt.isSet(NSCertTypeExtension.EMAIL_BIT) &&
- !nsCertTypeExt.isSet(NSCertTypeExtension.SSL_SERVER_BIT) &&
- !nsCertTypeExt.isSet(
- NSCertTypeExtension.OBJECT_SIGNING_BIT)) {
+ !nsCertTypeExt.isSet(NSCertTypeExtension.EMAIL_BIT) &&
+ !nsCertTypeExt.isSet(NSCertTypeExtension.SSL_SERVER_BIT) &&
+ !nsCertTypeExt.isSet(
+ NSCertTypeExtension.OBJECT_SIGNING_BIT)) {
// min not set so set all.
CMS.debug(
- "NSCertTypeExt: is extension good: no cl bits set. set all");
- nsCertTypeExt.set(NSCertTypeExtension.SSL_CLIENT,
- new Boolean(true));
+ "NSCertTypeExt: is extension good: no cl bits set. set all");
+ nsCertTypeExt.set(NSCertTypeExtension.SSL_CLIENT,
+ new Boolean(true));
nsCertTypeExt.set(NSCertTypeExtension.EMAIL,
- new Boolean(true));
+ new Boolean(true));
nsCertTypeExt.set(NSCertTypeExtension.OBJECT_SIGNING,
- new Boolean(true));
+ new Boolean(true));
}
return true;
} else if (certType.equals(IRequest.SERVER_CERT)) {
@@ -358,14 +356,13 @@ public class NSCertTypeExt extends APolicyRule
}
/**
- * Gets ns cert type bits from request.
- * If none set, use cert type to determine correct bits.
- * If no cert type, use default.
- */
+ * Gets ns cert type bits from request. If none set, use cert type to
+ * determine correct bits. If no cert type, use default.
+ */
protected boolean[] getBitsFromRequest(IRequest req, boolean setDefault) {
boolean[] bits = null;
-
+
CMS.debug("NSCertTypeExt: ns cert type getting ns cert type vars");
bits = getNSCertTypeBits(req);
if (bits == null && setDefault) {
@@ -440,23 +437,23 @@ public class NSCertTypeExt extends APolicyRule
*/
protected boolean[] getCertTypeBits(IRequest req) {
String certType =
- req.getExtDataInString(IRequest.HTTP_PARAMS, IRequest.CERT_TYPE);
+ req.getExtDataInString(IRequest.HTTP_PARAMS, IRequest.CERT_TYPE);
- if (certType == null || certType.length() == 0)
+ if (certType == null || certType.length() == 0)
return null;
boolean[] bits = new boolean[KeyUsageExtension.NBITS];
- for (int i = bits.length - 1; i >= 0; i--)
+ for (int i = bits.length - 1; i >= 0; i--)
bits[i] = false;
if (certType.equals(IRequest.CLIENT_CERT)) {
CMS.debug("NSCertTypeExt: setting bits for client cert");
- // we can only guess here when it's client.
+ // we can only guess here when it's client.
// sets all client bit for default.
bits[NSCertTypeExtension.SSL_CLIENT_BIT] = true;
bits[NSCertTypeExtension.EMAIL_BIT] = true;
- //bits[NSCertTypeExtension.OBJECT_SIGNING_BIT] = true;
+ // bits[NSCertTypeExtension.OBJECT_SIGNING_BIT] = true;
} else if (certType.equals(IRequest.SERVER_CERT)) {
CMS.debug("NSCertTypeExt: setting bits for server cert");
bits[NSCertTypeExtension.SSL_SERVER_BIT] = true;
@@ -477,9 +474,8 @@ public class NSCertTypeExt extends APolicyRule
}
/**
- * merge bits with those set from form.
- * make sure required minimum is set. Agent or auth can set others.
- * XXX form shouldn't set the extension
+ * merge bits with those set from form. make sure required minimum is set.
+ * Agent or auth can set others. XXX form shouldn't set the extension
*/
public void mergeBits(NSCertTypeExtension nsCertTypeExt, boolean[] bits) {
for (int i = bits.length - 1; i >= 0; i--) {
@@ -492,37 +488,37 @@ public class NSCertTypeExt extends APolicyRule
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getInstanceParams() {
+ public Vector<String> getInstanceParams() {
Vector<String> params = new Vector<String>();
params.addElement(PROP_CRITICAL + "=" + mCritical);
params.addElement(PROP_SET_DEFAULT_BITS + "=" + mSetDefaultBits);
- //new Boolean(mSetDefaultBits).toString());
+ // new Boolean(mSetDefaultBits).toString());
return params;
}
private static Vector<String> mDefParams = new Vector<String>();
static {
mDefParams.addElement(
- PROP_CRITICAL + "=false");
+ PROP_CRITICAL + "=false");
mDefParams.addElement(
- PROP_SET_DEFAULT_BITS + "=" + DEF_SET_DEFAULT_BITS);
+ PROP_SET_DEFAULT_BITS + "=" + DEF_SET_DEFAULT_BITS);
}
public String[] getExtendedPluginInfo(Locale locale) {
String[] params = {
PROP_CRITICAL + ";boolean;Netscape recommendation: non-critical.",
PROP_SET_DEFAULT_BITS + ";boolean;Specify whether to set the Netscape certificate " +
- "type extension with default bits ('ssl client' and 'email') in certificates " +
- "specified by the predicate " +
- "expression.",
+ "type extension with default bits ('ssl client' and 'email') in certificates " +
+ "specified by the predicate " +
+ "expression.",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-nscerttype",
+ ";configuration-policyrules-nscerttype",
IExtendedPluginInfo.HELP_TEXT +
- ";Adds Netscape Certificate Type extension."
+ ";Adds Netscape Certificate Type extension."
};
return params;
@@ -530,11 +526,10 @@ public class NSCertTypeExt extends APolicyRule
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getDefaultParams() {
+ public Vector<String> getDefaultParams() {
return mDefParams;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/policy/extensions/NameConstraintsExt.java b/pki/base/common/src/com/netscape/cms/policy/extensions/NameConstraintsExt.java
index 8b8001bb..e47cf978 100644
--- a/pki/base/common/src/com/netscape/cms/policy/extensions/NameConstraintsExt.java
+++ b/pki/base/common/src/com/netscape/cms/policy/extensions/NameConstraintsExt.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.extensions;
-
import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.Locale;
@@ -43,22 +42,21 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
- * Name Constraints Extension Policy
- * Adds the name constraints extension to a (CA) certificate.
- * Filtering of CA certificates is done through predicates.
+ * Name Constraints Extension Policy Adds the name constraints extension to a
+ * (CA) certificate. Filtering of CA certificates is done through predicates.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public class NameConstraintsExt extends APolicyRule
- implements IEnrollmentPolicy, IExtendedPluginInfo {
+ implements IEnrollmentPolicy, IExtendedPluginInfo {
protected static final String PROP_CRITICAL = "critical";
protected static final String PROP_NUM_PERMITTEDSUBTREES = "numPermittedSubtrees";
protected static final String PROP_NUM_EXCLUDEDSUBTREES = "numExcludedSubtrees";
@@ -90,37 +88,31 @@ public class NameConstraintsExt extends APolicyRule
/**
* Initializes this policy rule.
* <P>
- *
+ *
* The entries may be of the form:
- *
- * ca.Policy.rule.<ruleName>.predicate=certType==ca
- * ca.Policy.rule.<ruleName>.implName=
- * ca.Policy.rule.<ruleName>.enable=true
- *
- * @param config The config store reference
+ *
+ * ca.Policy.rule.<ruleName>.predicate=certType==ca
+ * ca.Policy.rule.<ruleName>.implName= ca.Policy.rule.<ruleName>.enable=true
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mConfig = config;
- // XXX should do do this ?
- // if CA does not allow subordinate CAs by way of basic constraints,
- // this policy always rejects
+ // XXX should do do this ?
+ // if CA does not allow subordinate CAs by way of basic constraints,
+ // this policy always rejects
/*****
- ICertAuthority certAuthority = (ICertAuthority)
- ((IPolicyProcessor)owner).getAuthority();
- if (certAuthority instanceof ICertificateAuthority) {
- CertificateChain caChain = certAuthority.getCACertChain();
- X509Certificate caCert = null;
- // Note that in RA the chain could be null if CA was not up when
- // RA was started. In that case just set the length to -1 and let
- // CA reject if it does not allow any subordinate CA certs.
- if (caChain != null) {
- caCert = caChain.getFirstCertificate();
- if (caCert != null)
- mCAPathLen = caCert.getBasicConstraints();
- }
- }
+ * ICertAuthority certAuthority = (ICertAuthority)
+ * ((IPolicyProcessor)owner).getAuthority(); if (certAuthority
+ * instanceof ICertificateAuthority) { CertificateChain caChain =
+ * certAuthority.getCACertChain(); X509Certificate caCert = null; //
+ * Note that in RA the chain could be null if CA was not up when // RA
+ * was started. In that case just set the length to -1 and let // CA
+ * reject if it does not allow any subordinate CA certs. if (caChain !=
+ * null) { caCert = caChain.getFirstCertificate(); if (caCert != null)
+ * mCAPathLen = caCert.getBasicConstraints(); } }
****/
mEnabled = mConfig.getBoolean(
@@ -133,25 +125,25 @@ public class NameConstraintsExt extends APolicyRule
if (mNumPermittedSubtrees < 0) {
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
- PROP_NUM_PERMITTEDSUBTREES,
+ PROP_NUM_PERMITTEDSUBTREES,
"value must be greater than or equal to 0"));
}
if (mNumExcludedSubtrees < 0) {
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
- PROP_NUM_EXCLUDEDSUBTREES,
+ PROP_NUM_EXCLUDEDSUBTREES,
"value must be greater than or equal to 0"));
}
// init permitted subtrees if any.
if (mNumPermittedSubtrees > 0) {
- mPermittedSubtrees =
+ mPermittedSubtrees =
form_subtrees(PROP_PERMITTEDSUBTREES, mNumPermittedSubtrees);
CMS.debug("NameConstraintsExt: formed permitted subtrees");
}
// init excluded subtrees if any.
if (mNumExcludedSubtrees > 0) {
- mExcludedSubtrees =
+ mExcludedSubtrees =
form_subtrees(PROP_EXCLUDEDSUBTREES, mNumExcludedSubtrees);
CMS.debug("NameConstraintsExt: formed excluded subtrees");
}
@@ -163,13 +155,13 @@ public class NameConstraintsExt extends APolicyRule
for (int i = 0; i < mNumPermittedSubtrees; i++) {
permittedSubtrees.addElement(
- mPermittedSubtrees[i].mGeneralSubtree);
+ mPermittedSubtrees[i].mGeneralSubtree);
}
Vector<GeneralSubtree> excludedSubtrees = new Vector<GeneralSubtree>();
for (int j = 0; j < mNumExcludedSubtrees; j++) {
excludedSubtrees.addElement(
- mExcludedSubtrees[j].mGeneralSubtree);
+ mExcludedSubtrees[j].mGeneralSubtree);
}
GeneralSubtrees psb = null;
@@ -181,44 +173,44 @@ public class NameConstraintsExt extends APolicyRule
if (excludedSubtrees.size() > 0) {
esb = new GeneralSubtrees(excludedSubtrees);
}
- mNameConstraintsExtension =
- new NameConstraintsExtension(mCritical,
- psb,
- esb);
+ mNameConstraintsExtension =
+ new NameConstraintsExtension(mCritical,
+ psb,
+ esb);
CMS.debug("NameConstraintsExt: formed Name Constraints Extension " +
- mNameConstraintsExtension);
+ mNameConstraintsExtension);
} catch (IOException e) {
throw new EBaseException(
CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR",
- "Error initializing Name Constraints Extension: " + e));
+ "Error initializing Name Constraints Extension: " + e));
}
}
- // form instance params
+ // form instance params
mInstanceParams.addElement(PROP_CRITICAL + "=" + mCritical);
mInstanceParams.addElement(
- PROP_NUM_PERMITTEDSUBTREES + "=" + mNumPermittedSubtrees);
+ PROP_NUM_PERMITTEDSUBTREES + "=" + mNumPermittedSubtrees);
mInstanceParams.addElement(
- PROP_NUM_EXCLUDEDSUBTREES + "=" + mNumExcludedSubtrees);
+ PROP_NUM_EXCLUDEDSUBTREES + "=" + mNumExcludedSubtrees);
if (mNumPermittedSubtrees > 0) {
- for (int i = 0; i < mPermittedSubtrees.length; i++)
+ for (int i = 0; i < mPermittedSubtrees.length; i++)
mPermittedSubtrees[i].getInstanceParams(mInstanceParams);
}
if (mNumExcludedSubtrees > 0) {
- for (int j = 0; j < mExcludedSubtrees.length; j++)
+ for (int j = 0; j < mExcludedSubtrees.length; j++)
mExcludedSubtrees[j].getInstanceParams(mInstanceParams);
}
}
- Subtree[] form_subtrees(String subtreesName, int numSubtrees)
- throws EBaseException {
+ Subtree[] form_subtrees(String subtreesName, int numSubtrees)
+ throws EBaseException {
Subtree[] subtrees = new Subtree[numSubtrees];
for (int i = 0; i < numSubtrees; i++) {
String subtreeName = subtreesName + i;
IConfigStore subtreeConfig = mConfig.getSubStore(subtreeName);
- Subtree subtree =
- new Subtree(subtreeName, subtreeConfig, mEnabled);
+ Subtree subtree =
+ new Subtree(subtreeName, subtreeConfig, mEnabled);
subtrees[i] = subtree;
}
@@ -228,28 +220,28 @@ public class NameConstraintsExt extends APolicyRule
/**
* Adds Name Constraints Extension to a (CA) certificate.
*
- * If a Name constraints Extension is already there, accept it if
- * it's been approved by agent, else replace it.
- *
- * @param req The request on which to apply policy.
+ * If a Name constraints Extension is already there, accept it if it's been
+ * approved by agent, else replace it.
+ *
+ * @param req The request on which to apply policy.
* @return The policy result object.
*/
public PolicyResult apply(IRequest req) {
- // if extension hasn't been properly configured reject requests until
+ // if extension hasn't been properly configured reject requests until
// it has been resolved (or disabled).
if (mNameConstraintsExtension == null) {
- //setError(req, PolicyResources.EXTENSION_NOT_INITED_1, NAME);
- //return PolicyResult.REJECTED;
+ // setError(req, PolicyResources.EXTENSION_NOT_INITED_1, NAME);
+ // return PolicyResult.REJECTED;
return PolicyResult.ACCEPTED;
}
// get certInfo from request.
- X509CertInfo[] ci =
- req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
+ X509CertInfo[] ci =
+ req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
if (ci == null || ci[0] == null) {
setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO"), NAME);
- return PolicyResult.REJECTED;
+ return PolicyResult.REJECTED;
}
for (int i = 0; i < ci.length; i++) {
@@ -269,7 +261,7 @@ public class NameConstraintsExt extends APolicyRule
try {
NameConstraintsExtension nameConstraintsExt = null;
CertificateExtensions extensions = (CertificateExtensions)
- certInfo.get(X509CertInfo.EXTENSIONS);
+ certInfo.get(X509CertInfo.EXTENSIONS);
try {
if (extensions != null) {
@@ -277,71 +269,70 @@ public class NameConstraintsExt extends APolicyRule
extensions.get(NameConstraintsExtension.class.getSimpleName());
}
} catch (IOException e) {
- // extension isn't there.
+ // extension isn't there.
}
if (nameConstraintsExt != null) {
if (agentApproved(req)) {
CMS.debug(
- "NameConstraintsExt: request id from agent " + req.getRequestId() +
- " already has name constraints - accepted");
+ "NameConstraintsExt: request id from agent " + req.getRequestId() +
+ " already has name constraints - accepted");
return PolicyResult.ACCEPTED;
} else {
CMS.debug(
- "NameConstraintsExt: request id " + req.getRequestId() + " from user " +
- " already has name constraints - deleted");
+ "NameConstraintsExt: request id " + req.getRequestId() + " from user " +
+ " already has name constraints - deleted");
extensions.delete(NameConstraintsExtension.class.getSimpleName());
}
}
if (extensions == null) {
certInfo.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ new CertificateVersion(CertificateVersion.V3));
extensions = new CertificateExtensions();
certInfo.set(X509CertInfo.EXTENSIONS, extensions);
}
extensions.set(
- NameConstraintsExtension.class.getSimpleName(), mNameConstraintsExtension);
+ NameConstraintsExtension.class.getSimpleName(), mNameConstraintsExtension);
CMS.debug(
- "NameConstraintsExt: added Name Constraints Extension to request " +
- req.getRequestId());
+ "NameConstraintsExt: added Name Constraints Extension to request " +
+ req.getRequestId());
return PolicyResult.ACCEPTED;
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("POLICY_ERROR_NAME_CONST_EXTENSION", e.getMessage()));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
- NAME, e.getMessage());
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("POLICY_ERROR_NAME_CONST_EXTENSION", e.getMessage()));
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
+ NAME, e.getMessage());
return PolicyResult.REJECTED;
} catch (CertificateException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CA_CERT_INFO_ERROR", e.toString()));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
- NAME, "Certificate Info Error");
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
+ NAME, "Certificate Info Error");
return PolicyResult.REJECTED;
}
}
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getInstanceParams() {
+ public Vector<String> getInstanceParams() {
return mInstanceParams;
}
/**
- * Default config parameters.
- * To add more permitted or excluded subtrees,
- * increase the num to greater than 0 and more configuration params
- * will show up in the console.
+ * Default config parameters. To add more permitted or excluded subtrees,
+ * increase the num to greater than 0 and more configuration params will
+ * show up in the console.
*/
private static Vector<String> mDefParams = new Vector<String>();
static {
mDefParams.addElement(PROP_CRITICAL + "=" + DEF_CRITICAL);
mDefParams.addElement(
- PROP_NUM_PERMITTEDSUBTREES + "=" + DEF_NUM_PERMITTEDSUBTREES);
+ PROP_NUM_PERMITTEDSUBTREES + "=" + DEF_NUM_PERMITTEDSUBTREES);
mDefParams.addElement(
- PROP_NUM_EXCLUDEDSUBTREES + "=" + DEF_NUM_EXCLUDEDSUBTREES);
+ PROP_NUM_EXCLUDEDSUBTREES + "=" + DEF_NUM_EXCLUDEDSUBTREES);
for (int k = 0; k < DEF_NUM_PERMITTEDSUBTREES; k++) {
Subtree.getDefaultParams(PROP_PERMITTEDSUBTREES + k, mDefParams);
}
@@ -352,10 +343,10 @@ public class NameConstraintsExt extends APolicyRule
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getDefaultParams() {
+ public Vector<String> getDefaultParams() {
return mDefParams;
}
@@ -364,9 +355,9 @@ public class NameConstraintsExt extends APolicyRule
theparams.addElement(PROP_CRITICAL + ";boolean;RFC 2459 recommendation: MUST be critical.");
theparams.addElement(
- PROP_NUM_PERMITTEDSUBTREES + ";number;See RFC 2459 sec 4.2.1.11");
+ PROP_NUM_PERMITTEDSUBTREES + ";number;See RFC 2459 sec 4.2.1.11");
theparams.addElement(
- PROP_NUM_EXCLUDEDSUBTREES + ";number;See RFC 2459 sec 4.2.1.11");
+ PROP_NUM_EXCLUDEDSUBTREES + ";number;See RFC 2459 sec 4.2.1.11");
// now do the subtrees.
for (int k = 0; k < DEF_NUM_PERMITTEDSUBTREES; k++) {
@@ -376,9 +367,9 @@ public class NameConstraintsExt extends APolicyRule
Subtree.getExtendedPluginInfo(PROP_EXCLUDEDSUBTREES + l, theparams);
}
theparams.addElement(IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-nameconstraints");
+ ";configuration-policyrules-nameconstraints");
theparams.addElement(IExtendedPluginInfo.HELP_TEXT +
- ";Adds Name Constraints Extension. See RFC 2459");
+ ";Adds Name Constraints Extension. See RFC 2459");
String[] info = new String[theparams.size()];
@@ -387,9 +378,8 @@ public class NameConstraintsExt extends APolicyRule
}
}
-
/**
- * subtree configuration
+ * subtree configuration
*/
class Subtree {
@@ -400,8 +390,7 @@ class Subtree {
protected static final int DEF_MIN = 0;
protected static final int DEF_MAX = -1; // -1 (less than 0) means not set.
- protected static final String
- MINMAX_INFO = "number;See RFC 2459 section 4.2.1.11";
+ protected static final String MINMAX_INFO = "number;See RFC 2459 section 4.2.1.11";
String mName = null;
IConfigStore mConfig = null;
@@ -414,13 +403,13 @@ class Subtree {
String mNameDotMax = null;
public Subtree(
- String subtreeName, IConfigStore config, boolean policyEnabled)
- throws EBaseException {
+ String subtreeName, IConfigStore config, boolean policyEnabled)
+ throws EBaseException {
mName = subtreeName;
mConfig = config;
if (mName != null) {
- mNameDot = mName + ".";
+ mNameDot = mName + ".";
mNameDotMin = mNameDot + PROP_MIN;
mNameDotMax = mNameDot + PROP_MAX;
} else {
@@ -439,13 +428,14 @@ class Subtree {
// if policy enabled get values to form the general subtree.
mMin = mConfig.getInteger(PROP_MIN, DEF_MIN);
mMax = mConfig.getInteger(PROP_MAX, DEF_MAX);
- if (mMax < -1) mMax = -1;
+ if (mMax < -1)
+ mMax = -1;
mBase = CMS.createGeneralNameAsConstraintsConfig(
- mNameDot + PROP_BASE, mConfig.getSubStore(PROP_BASE),
+ mNameDot + PROP_BASE, mConfig.getSubStore(PROP_BASE),
true, policyEnabled);
if (policyEnabled) {
- mGeneralSubtree =
+ mGeneralSubtree =
new GeneralSubtree(mBase.getGeneralName(), mMin, mMax);
}
}
@@ -476,4 +466,3 @@ class Subtree {
info.addElement(nameDot + PROP_MAX + ";" + MINMAX_INFO);
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/policy/extensions/OCSPNoCheckExt.java b/pki/base/common/src/com/netscape/cms/policy/extensions/OCSPNoCheckExt.java
index 9e36ae80..b57ff58a 100644
--- a/pki/base/common/src/com/netscape/cms/policy/extensions/OCSPNoCheckExt.java
+++ b/pki/base/common/src/com/netscape/cms/policy/extensions/OCSPNoCheckExt.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.extensions;
-
import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.Locale;
@@ -39,25 +38,25 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
- * This implements an OCSP Signing policy, it
- * adds the OCSP Signing extension to the certificate.
+ * This implements an OCSP Signing policy, it adds the OCSP Signing extension to
+ * the certificate.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$ $Date$
*/
public class OCSPNoCheckExt extends APolicyRule
- implements IEnrollmentPolicy, IExtendedPluginInfo {
-
+ implements IEnrollmentPolicy, IExtendedPluginInfo {
+
public static final String PROP_CRITICAL = "critical";
private boolean mCritical = false;
-
+
// PKIX specifies the that the extension SHOULD NOT be critical
public static final boolean DEFAULT_CRITICALITY = false;
@@ -75,9 +74,9 @@ public class OCSPNoCheckExt extends APolicyRule
String[] params = {
PROP_CRITICAL + ";boolean;RFC 2560 recommendation: SHOULD be non-critical.",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-ocspnocheck",
+ ";configuration-policyrules-ocspnocheck",
IExtendedPluginInfo.HELP_TEXT +
- ";Adds OCSP signing extension to certificate"
+ ";Adds OCSP signing extension to certificate"
};
return params;
@@ -88,9 +87,9 @@ public class OCSPNoCheckExt extends APolicyRule
* Performs one-time initialization of the policy.
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mOCSPNoCheck = new OCSPNoCheckExtension();
-
+
if (mOCSPNoCheck != null) {
// configure the extension itself
mCritical = config.getBoolean(PROP_CRITICAL,
@@ -110,7 +109,7 @@ public class OCSPNoCheckExt extends APolicyRule
}
X509CertInfo[] ci =
- req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
+ req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
if (ci == null || ci[0] == null) {
setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO"), NAME);
@@ -131,22 +130,23 @@ public class OCSPNoCheckExt extends APolicyRule
// find the extensions in the certInfo
CertificateExtensions extensions = (CertificateExtensions)
- certInfo.get(X509CertInfo.EXTENSIONS);
+ certInfo.get(X509CertInfo.EXTENSIONS);
// prepare the extensions data structure
if (extensions == null) {
certInfo.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ new CertificateVersion(CertificateVersion.V3));
extensions = new CertificateExtensions();
certInfo.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ new CertificateVersion(CertificateVersion.V3));
certInfo.set(X509CertInfo.EXTENSIONS, extensions);
} else {
try {
extensions.delete(OCSPNoCheckExtension.class.getSimpleName());
} catch (IOException ex) {
// OCSPNoCheck extension is not already there
- // log(ILogger.LL_FAILURE, "No previous extension: "+OCSPNoCheckExtension.NAME+" "+ex.getMessage());
+ // log(ILogger.LL_FAILURE,
+ // "No previous extension: "+OCSPNoCheckExtension.NAME+" "+ex.getMessage());
}
}
@@ -157,16 +157,16 @@ public class OCSPNoCheckExt extends APolicyRule
} catch (IOException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("BASE_IO_ERROR", e.getMessage()));
setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"), NAME,
- e.getMessage());
+ e.getMessage());
return PolicyResult.REJECTED;
} catch (CertificateException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CA_CERT_INFO_ERROR", e.getMessage()));
setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"), NAME,
- e.getMessage());
+ e.getMessage());
return PolicyResult.REJECTED;
}
}
-
+
/**
* Returns instance parameters.
*/
@@ -175,9 +175,9 @@ public class OCSPNoCheckExt extends APolicyRule
params.addElement(PROP_CRITICAL + "=" + mCritical);
return params;
-
+
}
-
+
/**
* Returns default parameters.
*/
@@ -186,6 +186,6 @@ public class OCSPNoCheckExt extends APolicyRule
defParams.addElement(PROP_CRITICAL + "=false");
return defParams;
-
+
}
}
diff --git a/pki/base/common/src/com/netscape/cms/policy/extensions/PolicyConstraintsExt.java b/pki/base/common/src/com/netscape/cms/policy/extensions/PolicyConstraintsExt.java
index 849036c7..f1a18cf4 100644
--- a/pki/base/common/src/com/netscape/cms/policy/extensions/PolicyConstraintsExt.java
+++ b/pki/base/common/src/com/netscape/cms/policy/extensions/PolicyConstraintsExt.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.extensions;
-
import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.Locale;
@@ -40,31 +39,28 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
- * Policy Constraints Extension Policy
- * Adds the policy constraints extension to (CA) certificates.
- * Filtering of CA certificates is done through predicates.
+ * Policy Constraints Extension Policy Adds the policy constraints extension to
+ * (CA) certificates. Filtering of CA certificates is done through predicates.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public class PolicyConstraintsExt extends APolicyRule
- implements IEnrollmentPolicy, IExtendedPluginInfo {
+ implements IEnrollmentPolicy, IExtendedPluginInfo {
protected static final String PROP_CRITICAL = "critical";
- protected static final String
- PROP_REQ_EXPLICIT_POLICY = "reqExplicitPolicy";
- protected static final String
- PROP_INHIBIT_POLICY_MAPPING = "inhibitPolicyMapping";
+ protected static final String PROP_REQ_EXPLICIT_POLICY = "reqExplicitPolicy";
+ protected static final String PROP_INHIBIT_POLICY_MAPPING = "inhibitPolicyMapping";
protected static final boolean DEF_CRITICAL = false;
- protected static final int DEF_REQ_EXPLICIT_POLICY = -1; // not set
- protected static final int DEF_INHIBIT_POLICY_MAPPING = -1; // not set
+ protected static final int DEF_REQ_EXPLICIT_POLICY = -1; // not set
+ protected static final int DEF_INHIBIT_POLICY_MAPPING = -1; // not set
protected boolean mEnabled = false;
protected IConfigStore mConfig = null;
@@ -80,9 +76,9 @@ public class PolicyConstraintsExt extends APolicyRule
static {
mDefaultParams.addElement(PROP_CRITICAL + "=" + DEF_CRITICAL);
mDefaultParams.addElement(
- PROP_REQ_EXPLICIT_POLICY + "=" + DEF_REQ_EXPLICIT_POLICY);
+ PROP_REQ_EXPLICIT_POLICY + "=" + DEF_REQ_EXPLICIT_POLICY);
mDefaultParams.addElement(
- PROP_INHIBIT_POLICY_MAPPING + "=" + DEF_INHIBIT_POLICY_MAPPING);
+ PROP_INHIBIT_POLICY_MAPPING + "=" + DEF_INHIBIT_POLICY_MAPPING);
}
public PolicyConstraintsExt() {
@@ -93,37 +89,31 @@ public class PolicyConstraintsExt extends APolicyRule
/**
* Initializes this policy rule.
* <P>
- *
+ *
* The entries may be of the form:
- *
- * ca.Policy.rule.<ruleName>.predicate=certType==ca
- * ca.Policy.rule.<ruleName>.implName=
- * ca.Policy.rule.<ruleName>.enable=true
- *
- * @param config The config store reference
+ *
+ * ca.Policy.rule.<ruleName>.predicate=certType==ca
+ * ca.Policy.rule.<ruleName>.implName= ca.Policy.rule.<ruleName>.enable=true
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mConfig = config;
- // XXX should do do this ?
- // if CA does not allow subordinate CAs by way of basic constraints,
- // this policy always rejects
+ // XXX should do do this ?
+ // if CA does not allow subordinate CAs by way of basic constraints,
+ // this policy always rejects
/*****
- ICertAuthority certAuthority = (ICertAuthority)
- ((GenericPolicyProcessor)owner).mAuthority;
- if (certAuthority instanceof ICertificateAuthority) {
- CertificateChain caChain = certAuthority.getCACertChain();
- X509Certificate caCert = null;
- // Note that in RA the chain could be null if CA was not up when
- // RA was started. In that case just set the length to -1 and let
- // CA reject if it does not allow any subordinate CA certs.
- if (caChain != null) {
- caCert = caChain.getFirstCertificate();
- if (caCert != null)
- mCAPathLen = caCert.getBasicConstraints();
- }
- }
+ * ICertAuthority certAuthority = (ICertAuthority)
+ * ((GenericPolicyProcessor)owner).mAuthority; if (certAuthority
+ * instanceof ICertificateAuthority) { CertificateChain caChain =
+ * certAuthority.getCACertChain(); X509Certificate caCert = null; //
+ * Note that in RA the chain could be null if CA was not up when // RA
+ * was started. In that case just set the length to -1 and let // CA
+ * reject if it does not allow any subordinate CA certs. if (caChain !=
+ * null) { caCert = caChain.getFirstCertificate(); if (caCert != null)
+ * mCAPathLen = caCert.getBasicConstraints(); } }
****/
mEnabled = mConfig.getBoolean(
@@ -135,58 +125,58 @@ public class PolicyConstraintsExt extends APolicyRule
mInhibitPolicyMapping = mConfig.getInteger(
PROP_INHIBIT_POLICY_MAPPING, DEF_INHIBIT_POLICY_MAPPING);
- if (mReqExplicitPolicy < -1)
+ if (mReqExplicitPolicy < -1)
mReqExplicitPolicy = -1;
- if (mInhibitPolicyMapping < -1)
+ if (mInhibitPolicyMapping < -1)
mInhibitPolicyMapping = -1;
-
- // create instance of policy constraings extension
+
+ // create instance of policy constraings extension
try {
- mPolicyConstraintsExtension =
- new PolicyConstraintsExtension(mCritical,
- mReqExplicitPolicy, mInhibitPolicyMapping);
+ mPolicyConstraintsExtension =
+ new PolicyConstraintsExtension(mCritical,
+ mReqExplicitPolicy, mInhibitPolicyMapping);
CMS.debug(
- "PolicyConstraintsExt: Created Policy Constraints Extension: " +
- mPolicyConstraintsExtension);
+ "PolicyConstraintsExt: Created Policy Constraints Extension: " +
+ mPolicyConstraintsExtension);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("POLICY_ERROR_CANT_INIT_POLICY_CONST_EXT", e.toString()));
+ CMS.getLogMessage("POLICY_ERROR_CANT_INIT_POLICY_CONST_EXT", e.toString()));
throw new EBaseException(
CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR",
- "Could not init Policy Constraints Extension. Error: " + e));
+ "Could not init Policy Constraints Extension. Error: " + e));
}
- // form instance params
+ // form instance params
mInstanceParams.addElement(PROP_CRITICAL + "=" + mCritical);
mInstanceParams.addElement(
- PROP_REQ_EXPLICIT_POLICY + "=" + mReqExplicitPolicy);
+ PROP_REQ_EXPLICIT_POLICY + "=" + mReqExplicitPolicy);
mInstanceParams.addElement(
- PROP_INHIBIT_POLICY_MAPPING + "=" + mInhibitPolicyMapping);
+ PROP_INHIBIT_POLICY_MAPPING + "=" + mInhibitPolicyMapping);
}
/**
* Adds Policy Constraints Extension to a (CA) certificate.
*
- * If a Policy constraints Extension is already there, accept it if
- * it's been approved by agent, else replace it.
- *
- * @param req The request on which to apply policy.
+ * If a Policy constraints Extension is already there, accept it if it's
+ * been approved by agent, else replace it.
+ *
+ * @param req The request on which to apply policy.
* @return The policy result object.
*/
public PolicyResult apply(IRequest req) {
- // if extension hasn't been properly configured reject requests until
+ // if extension hasn't been properly configured reject requests until
// it has been resolved (or disabled).
if (mPolicyConstraintsExtension == null) {
return PolicyResult.ACCEPTED;
}
// get certInfo from request.
- X509CertInfo[] ci =
- req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
+ X509CertInfo[] ci =
+ req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
if (ci == null || ci[0] == null) {
setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO"), NAME);
- return PolicyResult.REJECTED;
+ return PolicyResult.REJECTED;
}
for (int i = 0; i < ci.length; i++) {
@@ -206,7 +196,7 @@ public class PolicyConstraintsExt extends APolicyRule
try {
PolicyConstraintsExtension policyConstraintsExt = null;
CertificateExtensions extensions = (CertificateExtensions)
- certInfo.get(X509CertInfo.EXTENSIONS);
+ certInfo.get(X509CertInfo.EXTENSIONS);
try {
if (extensions != null) {
@@ -214,7 +204,7 @@ public class PolicyConstraintsExt extends APolicyRule
extensions.get(PolicyConstraintsExtension.class.getSimpleName());
}
} catch (IOException e) {
- // extension isn't there.
+ // extension isn't there.
}
if (policyConstraintsExt != null) {
@@ -227,55 +217,55 @@ public class PolicyConstraintsExt extends APolicyRule
if (extensions == null) {
certInfo.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ new CertificateVersion(CertificateVersion.V3));
extensions = new CertificateExtensions();
certInfo.set(X509CertInfo.EXTENSIONS, extensions);
}
extensions.set(
- "PolicyConstriantsExt", mPolicyConstraintsExtension);
+ "PolicyConstriantsExt", mPolicyConstraintsExtension);
CMS.debug("PolicyConstraintsExt: added our policy constraints extension");
return PolicyResult.ACCEPTED;
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("POLICY_ERROR_CANT_PROCESS_POLICY_CONST_EXT", e.toString()));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
- NAME, e.getMessage());
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("POLICY_ERROR_CANT_PROCESS_POLICY_CONST_EXT", e.toString()));
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
+ NAME, e.getMessage());
return PolicyResult.REJECTED;
} catch (CertificateException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CA_CERT_INFO_ERROR", e.toString()));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
- NAME, "Certificate Info Error");
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
+ NAME, "Certificate Info Error");
return PolicyResult.REJECTED;
}
}
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getInstanceParams() {
+ public Vector<String> getInstanceParams() {
return mInstanceParams;
}
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getDefaultParams() {
+ public Vector<String> getDefaultParams() {
return mDefaultParams;
}
/**
- * gets plugin info for pretty console edit displays.
+ * gets plugin info for pretty console edit displays.
*/
public String[] getExtendedPluginInfo(Locale locale) {
mInstanceParams.addElement(PROP_CRITICAL + "=" + mCritical);
mInstanceParams.addElement(
- PROP_REQ_EXPLICIT_POLICY + "=" + mReqExplicitPolicy);
+ PROP_REQ_EXPLICIT_POLICY + "=" + mReqExplicitPolicy);
mInstanceParams.addElement(
- PROP_INHIBIT_POLICY_MAPPING + "=" + mInhibitPolicyMapping);
+ PROP_INHIBIT_POLICY_MAPPING + "=" + mInhibitPolicyMapping);
String[] params = {
PROP_CRITICAL + ";boolean;RFC 2459 recommendation: may be critical or non-critical.",
@@ -287,4 +277,3 @@ public class PolicyConstraintsExt extends APolicyRule
return params;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/policy/extensions/PolicyMappingsExt.java b/pki/base/common/src/com/netscape/cms/policy/extensions/PolicyMappingsExt.java
index 1d901d57..80efc78f 100644
--- a/pki/base/common/src/com/netscape/cms/policy/extensions/PolicyMappingsExt.java
+++ b/pki/base/common/src/com/netscape/cms/policy/extensions/PolicyMappingsExt.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.extensions;
-
import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.Locale;
@@ -43,22 +42,21 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
- * Policy Mappings Extension Policy
- * Adds the Policy Mappings extension to a (CA) certificate.
- * Filtering of CA certificates is done through predicates.
+ * Policy Mappings Extension Policy Adds the Policy Mappings extension to a (CA)
+ * certificate. Filtering of CA certificates is done through predicates.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public class PolicyMappingsExt extends APolicyRule
- implements IEnrollmentPolicy, IExtendedPluginInfo {
+ implements IEnrollmentPolicy, IExtendedPluginInfo {
protected static final String PROP_CRITICAL = "critical";
protected static final String PROP_NUM_POLICYMAPPINGS = "numPolicyMappings";
@@ -85,37 +83,31 @@ public class PolicyMappingsExt extends APolicyRule
/**
* Initializes this policy rule.
* <P>
- *
+ *
* The entries may be of the form:
- *
- * ca.Policy.rule.<ruleName>.predicate=certType==ca
- * ca.Policy.rule.<ruleName>.implName=
- * ca.Policy.rule.<ruleName>.enable=true
- *
- * @param config The config store reference
+ *
+ * ca.Policy.rule.<ruleName>.predicate=certType==ca
+ * ca.Policy.rule.<ruleName>.implName= ca.Policy.rule.<ruleName>.enable=true
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mConfig = config;
- // XXX should do do this ?
- // if CA does not allow subordinate CAs by way of basic constraints,
- // this policy always rejects
+ // XXX should do do this ?
+ // if CA does not allow subordinate CAs by way of basic constraints,
+ // this policy always rejects
/*****
- ICertAuthority certAuthority = (ICertAuthority)
- ((IPolicyProcessor)owner).getAuthority();
- if (certAuthority instanceof ICertificateAuthority) {
- CertificateChain caChain = certAuthority.getCACertChain();
- X509Certificate caCert = null;
- // Note that in RA the chain could be null if CA was not up when
- // RA was started. In that case just set the length to -1 and let
- // CA reject if it does not allow any subordinate CA certs.
- if (caChain != null) {
- caCert = caChain.getFirstCertificate();
- if (caCert != null)
- mCAPathLen = caCert.getBasicConstraints();
- }
- }
+ * ICertAuthority certAuthority = (ICertAuthority)
+ * ((IPolicyProcessor)owner).getAuthority(); if (certAuthority
+ * instanceof ICertificateAuthority) { CertificateChain caChain =
+ * certAuthority.getCACertChain(); X509Certificate caCert = null; //
+ * Note that in RA the chain could be null if CA was not up when // RA
+ * was started. In that case just set the length to -1 and let // CA
+ * reject if it does not allow any subordinate CA certs. if (caChain !=
+ * null) { caCert = caChain.getFirstCertificate(); if (caCert != null)
+ * mCAPathLen = caCert.getBasicConstraints(); } }
****/
mEnabled = mConfig.getBoolean(
@@ -131,7 +123,7 @@ public class PolicyMappingsExt extends APolicyRule
"value must be greater than or equal to 1"));
}
- // init Policy Mappings, check values if enabled.
+ // init Policy Mappings, check values if enabled.
mPolicyMaps = new PolicyMap[mNumPolicyMappings];
for (int i = 0; i < mNumPolicyMappings; i++) {
String subtreeName = PROP_POLICYMAP + i;
@@ -140,7 +132,7 @@ public class PolicyMappingsExt extends APolicyRule
mPolicyMaps[i] = new PolicyMap(subtreeName, mConfig, mEnabled);
} catch (EBaseException e) {
log(ILogger.LL_FAILURE, NAME + ": " +
- CMS.getLogMessage("POLICY_ERROR_CREATE_MAP", e.toString()));
+ CMS.getLogMessage("POLICY_ERROR_CREATE_MAP", e.toString()));
throw e;
}
}
@@ -152,21 +144,21 @@ public class PolicyMappingsExt extends APolicyRule
for (int j = 0; j < mNumPolicyMappings; j++) {
certPolicyMaps.addElement(
- mPolicyMaps[j].mCertificatePolicyMap);
+ mPolicyMaps[j].mCertificatePolicyMap);
}
- mPolicyMappingsExtension =
+ mPolicyMappingsExtension =
new PolicyMappingsExtension(mCritical, certPolicyMaps);
} catch (IOException e) {
throw new EBaseException(
CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR",
- "Error initializing " + NAME + " Error: " + e));
+ "Error initializing " + NAME + " Error: " + e));
}
}
- // form instance params
+ // form instance params
mInstanceParams.addElement(PROP_CRITICAL + "=" + mCritical);
mInstanceParams.addElement(
- PROP_NUM_POLICYMAPPINGS + "=" + mNumPolicyMappings);
+ PROP_NUM_POLICYMAPPINGS + "=" + mNumPolicyMappings);
for (int i = 0; i < mNumPolicyMappings; i++) {
mPolicyMaps[i].getInstanceParams(mInstanceParams);
}
@@ -175,28 +167,28 @@ public class PolicyMappingsExt extends APolicyRule
/**
* Adds policy mappings Extension to a (CA) certificate.
*
- * If a policy mappings Extension is already there, accept it if
- * it's been approved by agent, else replace it.
- *
- * @param req The request on which to apply policy.
+ * If a policy mappings Extension is already there, accept it if it's been
+ * approved by agent, else replace it.
+ *
+ * @param req The request on which to apply policy.
* @return The policy result object.
*/
public PolicyResult apply(IRequest req) {
- // if extension hasn't been properly configured reject requests until
+ // if extension hasn't been properly configured reject requests until
// it has been resolved (or disabled).
if (mPolicyMappingsExtension == null) {
- //setError(req, PolicyResources.EXTENSION_NOT_INITED_1, NAME);
- //return PolicyResult.REJECTED;
+ // setError(req, PolicyResources.EXTENSION_NOT_INITED_1, NAME);
+ // return PolicyResult.REJECTED;
return PolicyResult.ACCEPTED;
}
// get certInfo from request.
- X509CertInfo[] ci =
- req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
-
+ X509CertInfo[] ci =
+ req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
+
if (ci == null || ci[0] == null) {
setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO"), NAME);
- return PolicyResult.REJECTED;
+ return PolicyResult.REJECTED;
}
for (int i = 0; i < ci.length; i++) {
@@ -215,7 +207,7 @@ public class PolicyMappingsExt extends APolicyRule
try {
PolicyMappingsExtension policyMappingsExt = null;
CertificateExtensions extensions = (CertificateExtensions)
- certInfo.get(X509CertInfo.EXTENSIONS);
+ certInfo.get(X509CertInfo.EXTENSIONS);
try {
if (extensions != null) {
@@ -223,7 +215,7 @@ public class PolicyMappingsExt extends APolicyRule
extensions.get(PolicyMappingsExtension.class.getSimpleName());
}
} catch (IOException e) {
- // extension isn't there.
+ // extension isn't there.
}
if (policyMappingsExt != null) {
@@ -236,87 +228,86 @@ public class PolicyMappingsExt extends APolicyRule
if (extensions == null) {
certInfo.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ new CertificateVersion(CertificateVersion.V3));
extensions = new CertificateExtensions();
certInfo.set(X509CertInfo.EXTENSIONS, extensions);
}
extensions.set(
- PolicyMappingsExtension.class.getSimpleName(), mPolicyMappingsExtension);
+ PolicyMappingsExtension.class.getSimpleName(), mPolicyMappingsExtension);
return PolicyResult.ACCEPTED;
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("POLICY_ERROR_PROCESS_POLICYMAP_EXT", e.getMessage()));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
- NAME, e.getMessage());
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("POLICY_ERROR_PROCESS_POLICYMAP_EXT", e.getMessage()));
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
+ NAME, e.getMessage());
return PolicyResult.REJECTED;
} catch (CertificateException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CA_CERT_INFO_ERROR", e.toString()));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
- NAME, "Certificate Info Error");
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
+ NAME, "Certificate Info Error");
return PolicyResult.REJECTED;
}
}
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getInstanceParams() {
+ public Vector<String> getInstanceParams() {
return mInstanceParams;
}
/**
- * Default config parameters.
- * To add more permitted or excluded subtrees,
- * increase the num to greater than 0 and more configuration params
- * will show up in the console.
+ * Default config parameters. To add more permitted or excluded subtrees,
+ * increase the num to greater than 0 and more configuration params will
+ * show up in the console.
*/
private static Vector<String> mDefParams = new Vector<String>();
static {
mDefParams.addElement(PROP_CRITICAL + "=" + DEF_CRITICAL);
mDefParams.addElement(
- PROP_NUM_POLICYMAPPINGS + "=" + DEF_NUM_POLICYMAPPINGS);
+ PROP_NUM_POLICYMAPPINGS + "=" + DEF_NUM_POLICYMAPPINGS);
String policyMap0Dot = PROP_POLICYMAP + "0.";
mDefParams.addElement(
- policyMap0Dot + PolicyMap.PROP_ISSUER_DOMAIN_POLICY + "=" + "");
+ policyMap0Dot + PolicyMap.PROP_ISSUER_DOMAIN_POLICY + "=" + "");
mDefParams.addElement(
- policyMap0Dot + PolicyMap.PROP_SUBJECT_DOMAIN_POLICY + "=" + "");
+ policyMap0Dot + PolicyMap.PROP_SUBJECT_DOMAIN_POLICY + "=" + "");
}
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getDefaultParams() {
+ public Vector<String> getDefaultParams() {
return mDefParams;
}
public String[] getExtendedPluginInfo(Locale locale) {
Vector<String> theparams = new Vector<String>();
-
+
theparams.addElement(PROP_CRITICAL + ";boolean;RFC 2459 recommendation: MUST be non-critical.");
theparams.addElement(PROP_NUM_POLICYMAPPINGS + ";number; Number of policy mappings. The value must be greater than or equal to 1");
- String policyInfo =
- ";string;An object identifier in the form n.n.n.n";
+ String policyInfo =
+ ";string;An object identifier in the form n.n.n.n";
for (int k = 0; k < 5; k++) {
String policyMapkDot = PROP_POLICYMAP + k + ".";
theparams.addElement(policyMapkDot +
- PolicyMap.PROP_ISSUER_DOMAIN_POLICY + policyInfo);
+ PolicyMap.PROP_ISSUER_DOMAIN_POLICY + policyInfo);
theparams.addElement(policyMapkDot +
- PolicyMap.PROP_SUBJECT_DOMAIN_POLICY + policyInfo);
+ PolicyMap.PROP_SUBJECT_DOMAIN_POLICY + policyInfo);
}
theparams.addElement(IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-policymappings");
+ ";configuration-policyrules-policymappings");
theparams.addElement(IExtendedPluginInfo.HELP_TEXT +
- ";Adds Policy Mappings Extension. See RFC 2459 (4.2.1.6)");
+ ";Adds Policy Mappings Extension. See RFC 2459 (4.2.1.6)");
String[] params = new String[theparams.size()];
@@ -325,7 +316,6 @@ public class PolicyMappingsExt extends APolicyRule
}
}
-
class PolicyMap {
protected static String PROP_ISSUER_DOMAIN_POLICY = "issuerDomainPolicy";
@@ -340,47 +330,48 @@ class PolicyMap {
/**
* forms policy map parameters.
+ *
* @param name name of this policy map, for example policyMap0
* @param config parent's config from where we find this configuration.
* @param enabled whether policy was enabled.
*/
- protected PolicyMap(String name, IConfigStore config, boolean enabled)
- throws EBaseException {
+ protected PolicyMap(String name, IConfigStore config, boolean enabled)
+ throws EBaseException {
mName = name;
mConfig = config.getSubStore(mName);
mNameDot = mName + ".";
- if( mConfig == null ) {
- CMS.debug( "PolicyMappingsExt::PolicyMap - mConfig is null!" );
+ if (mConfig == null) {
+ CMS.debug("PolicyMappingsExt::PolicyMap - mConfig is null!");
return;
}
// if there's no configuration for this map put it there.
if (mConfig.size() == 0) {
- config.putString(mNameDot + PROP_ISSUER_DOMAIN_POLICY, "");
- config.putString(mNameDot + PROP_SUBJECT_DOMAIN_POLICY, "");
+ config.putString(mNameDot + PROP_ISSUER_DOMAIN_POLICY, "");
+ config.putString(mNameDot + PROP_SUBJECT_DOMAIN_POLICY, "");
mConfig = config.getSubStore(mName);
if (mConfig == null || mConfig.size() == 0) {
- CMS.debug( "PolicyMappingsExt::PolicyMap - mConfig " +
- "is null or empty!" );
+ CMS.debug("PolicyMappingsExt::PolicyMap - mConfig " +
+ "is null or empty!");
return;
}
}
// get policy ids from configuration.
- mIssuerDomainPolicy =
+ mIssuerDomainPolicy =
mConfig.getString(PROP_ISSUER_DOMAIN_POLICY, null);
- mSubjectDomainPolicy =
+ mSubjectDomainPolicy =
mConfig.getString(PROP_SUBJECT_DOMAIN_POLICY, null);
// adjust for "" and console returning "null"
- if (mIssuerDomainPolicy != null &&
- (mIssuerDomainPolicy.length() == 0 ||
+ if (mIssuerDomainPolicy != null &&
+ (mIssuerDomainPolicy.length() == 0 ||
mIssuerDomainPolicy.equals("null"))) {
mIssuerDomainPolicy = null;
}
- if (mSubjectDomainPolicy != null &&
- (mSubjectDomainPolicy.length() == 0 ||
+ if (mSubjectDomainPolicy != null &&
+ (mSubjectDomainPolicy.length() == 0 ||
mSubjectDomainPolicy.equals("null"))) {
mSubjectDomainPolicy = null;
}
@@ -388,26 +379,26 @@ class PolicyMap {
// policy ids cannot be null if policy is enabled.
String msg = "value cannot be null.";
- if (mIssuerDomainPolicy == null && enabled)
+ if (mIssuerDomainPolicy == null && enabled)
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
mNameDot + PROP_ISSUER_DOMAIN_POLICY, msg));
- if (mSubjectDomainPolicy == null && enabled)
+ if (mSubjectDomainPolicy == null && enabled)
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
mNameDot + PROP_SUBJECT_DOMAIN_POLICY, msg));
- // if a policy id is not null check that it is a valid OID.
+ // if a policy id is not null check that it is a valid OID.
ObjectIdentifier issuerPolicyId = null;
ObjectIdentifier subjectPolicyId = null;
- if (mIssuerDomainPolicy != null)
+ if (mIssuerDomainPolicy != null)
issuerPolicyId = CMS.checkOID(
mNameDot + PROP_ISSUER_DOMAIN_POLICY, mIssuerDomainPolicy);
- if (mSubjectDomainPolicy != null)
+ if (mSubjectDomainPolicy != null)
subjectPolicyId = CMS.checkOID(
mNameDot + PROP_SUBJECT_DOMAIN_POLICY, mSubjectDomainPolicy);
-
- // if enabled, form CertificatePolicyMap to be encoded in extension.
- // policy ids should be all set.
+
+ // if enabled, form CertificatePolicyMap to be encoded in extension.
+ // policy ids should be all set.
if (enabled) {
mCertificatePolicyMap = new CertificatePolicyMap(
new CertificatePolicyId(issuerPolicyId),
@@ -417,12 +408,11 @@ class PolicyMap {
protected void getInstanceParams(Vector<String> instanceParams) {
instanceParams.addElement(
- mNameDot + PROP_ISSUER_DOMAIN_POLICY + "=" + (mIssuerDomainPolicy == null ? "" :
- mIssuerDomainPolicy));
+ mNameDot + PROP_ISSUER_DOMAIN_POLICY + "=" + (mIssuerDomainPolicy == null ? "" :
+ mIssuerDomainPolicy));
instanceParams.addElement(
- mNameDot + PROP_SUBJECT_DOMAIN_POLICY + "=" + (mSubjectDomainPolicy == null ? "" :
- mSubjectDomainPolicy));
+ mNameDot + PROP_SUBJECT_DOMAIN_POLICY + "=" + (mSubjectDomainPolicy == null ? "" :
+ mSubjectDomainPolicy));
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/policy/extensions/PresenceExt.java b/pki/base/common/src/com/netscape/cms/policy/extensions/PresenceExt.java
index 125555c4..a171a400 100644
--- a/pki/base/common/src/com/netscape/cms/policy/extensions/PresenceExt.java
+++ b/pki/base/common/src/com/netscape/cms/policy/extensions/PresenceExt.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.extensions;
-
import java.util.Locale;
import java.util.Vector;
@@ -32,11 +31,12 @@ import com.netscape.cms.policy.APolicyRule;
/**
* Checks extension presence.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
@@ -77,7 +77,7 @@ public class PresenceExt extends APolicyRule {
}
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mConfig = config;
mCritical = config.getBoolean(PROP_IS_CRITICAL, false);
@@ -97,19 +97,18 @@ public class PresenceExt extends APolicyRule {
PolicyResult res = PolicyResult.ACCEPTED;
/*
- PresenceServerExtension ext = new PresenceServerExtension(mCritical,
- mOID, mVersion, mStreetAddress,
- mTelephoneNumber, mRFC822Name, mID,
- mHostName, mPortNumber, mMaxUsers, mServiceLevel);
+ * PresenceServerExtension ext = new PresenceServerExtension(mCritical,
+ * mOID, mVersion, mStreetAddress, mTelephoneNumber, mRFC822Name, mID,
+ * mHostName, mPortNumber, mMaxUsers, mServiceLevel);
*/
-
+
return res;
}
- public Vector<String> getInstanceParams() {
- Vector<String> params = new Vector<String>();
+ public Vector<String> getInstanceParams() {
+ Vector<String> params = new Vector<String>();
- params.addElement(PROP_IS_CRITICAL + "=" + mCritical);
+ params.addElement(PROP_IS_CRITICAL + "=" + mCritical);
params.addElement(PROP_OID + "=" + mOID);
params.addElement(PROP_VERSION + "=" + mVersion);
params.addElement(PROP_STREET_ADDRESS + "=" + mStreetAddress);
@@ -137,21 +136,21 @@ public class PresenceExt extends APolicyRule {
PROP_MAX_USERS + ";string; max users",
PROP_SERVICE_LEVEL + ";string; service level",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-presenceext",
+ ";configuration-policyrules-presenceext",
IExtendedPluginInfo.HELP_TEXT +
- ";Adds Presence Server Extension;"
+ ";Adds Presence Server Extension;"
- };
+ };
return params;
}
-
+
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getDefaultParams() {
+ public Vector<String> getDefaultParams() {
return mDefParams;
}
}
diff --git a/pki/base/common/src/com/netscape/cms/policy/extensions/PrivateKeyUsagePeriodExt.java b/pki/base/common/src/com/netscape/cms/policy/extensions/PrivateKeyUsagePeriodExt.java
index 8b3ab40c..60c0dfbc 100644
--- a/pki/base/common/src/com/netscape/cms/policy/extensions/PrivateKeyUsagePeriodExt.java
+++ b/pki/base/common/src/com/netscape/cms/policy/extensions/PrivateKeyUsagePeriodExt.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.extensions;
-
import java.io.IOException;
import java.security.cert.CertificateException;
import java.text.SimpleDateFormat;
@@ -42,20 +41,20 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
* PrivateKeyUsagePeriod Identifier Extension policy.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public class PrivateKeyUsagePeriodExt extends APolicyRule
- implements IEnrollmentPolicy, IExtendedPluginInfo {
+ implements IEnrollmentPolicy, IExtendedPluginInfo {
private final static String PROP_NOT_BEFORE = "notBefore";
private final static String PROP_NOT_AFTER = "notAfter";
@@ -94,16 +93,16 @@ public class PrivateKeyUsagePeriodExt extends APolicyRule
public String[] getExtendedPluginInfo(Locale locale) {
String[] params = {
PROP_IS_CRITICAL + ";boolean;RFC 2459 recommendation: The profile " +
- "recommends against the use of this extension. CAs " +
- "conforming to the profile MUST NOT generate certs with " +
- "critical private key usage period extensions.",
+ "recommends against the use of this extension. CAs " +
+ "conforming to the profile MUST NOT generate certs with " +
+ "critical private key usage period extensions.",
PROP_NOT_BEFORE + ";string; Date before which the Private Key is invalid.",
PROP_NOT_AFTER + ";string; Date after which the Private Key is invalid.",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-privatekeyusageperiod",
+ ";configuration-policyrules-privatekeyusageperiod",
IExtendedPluginInfo.HELP_TEXT +
- ";Adds (deprecated) Private Key Usage Period Extension. " +
- "Defined in RFC 2459 (4.2.1.4)"
+ ";Adds (deprecated) Private Key Usage Period Extension. " +
+ "Defined in RFC 2459 (4.2.1.4)"
};
return params;
@@ -119,17 +118,17 @@ public class PrivateKeyUsagePeriodExt extends APolicyRule
/**
* Initializes this policy rule.
- * ra.Policy.rule.<ruleName>.implName=PrivateKeyUsageExtension
- * ra.Policy.rule.<ruleName>.enable=true
- * ra.Policy.rule.<ruleName>.notBefore=30
- * ra.Policy.rule.<ruleName>.notAfter=180
- * ra.Policy.rule.<ruleName>.critical=false
- * ra.Policy.rule.<ruleName>.predicate=ou==Sales
- *
- * @param config The config store reference
+ * ra.Policy.rule.<ruleName>.implName=PrivateKeyUsageExtension
+ * ra.Policy.rule.<ruleName>.enable=true
+ * ra.Policy.rule.<ruleName>.notBefore=30
+ * ra.Policy.rule.<ruleName>.notAfter=180
+ * ra.Policy.rule.<ruleName>.critical=false
+ * ra.Policy.rule.<ruleName>.predicate=ou==Sales
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
try {
// Get params.
@@ -145,7 +144,7 @@ public class PrivateKeyUsagePeriodExt extends APolicyRule
notAfter = formatter.format(formatter.parse(mNotAfter.trim()));
} catch (Exception e) {
// e.printStackTrace();
- Object[] params = {getInstanceName(), e};
+ Object[] params = { getInstanceName(), e };
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_INVALID_POLICY_CONFIG"), params);
@@ -154,20 +153,20 @@ public class PrivateKeyUsagePeriodExt extends APolicyRule
}
/**
- * Adds a private key usage extension if none exists.
- *
- * @param req The request on which to apply policy.
+ * Adds a private key usage extension if none exists.
+ *
+ * @param req The request on which to apply policy.
* @return The policy result object.
*/
public PolicyResult apply(IRequest req) {
PolicyResult res = PolicyResult.ACCEPTED;
// get cert info.
- X509CertInfo[] ci =
- req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
-
+ X509CertInfo[] ci =
+ req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
+
if (ci == null || ci[0] == null) {
- setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO"), NAME);
+ setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO"), NAME);
return PolicyResult.REJECTED; // unrecoverable error.
}
@@ -201,7 +200,7 @@ public class PrivateKeyUsagePeriodExt extends APolicyRule
// remove any previously computed version of the extension
try {
extensions.delete(PrivateKeyUsageExtension.class.getSimpleName());
-
+
} catch (IOException e) {
}
@@ -209,16 +208,16 @@ public class PrivateKeyUsagePeriodExt extends APolicyRule
try {
ext = new PrivateKeyUsageExtension(
- formatter.parse(mNotBefore),
+ formatter.parse(mNotBefore),
formatter.parse(mNotAfter));
certInfo.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ new CertificateVersion(CertificateVersion.V3));
extensions.set(PrivateKeyUsageExtension.class.getSimpleName(), ext);
} catch (Exception e) {
- if (e instanceof RuntimeException)
+ if (e instanceof RuntimeException)
throw (RuntimeException) e;
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("POLICY_ERROR_CREATE_PRIVATE_KEY_EXT", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("POLICY_ERROR_CREATE_PRIVATE_KEY_EXT", e.toString()));
setError(req, CMS.getUserMessage("CMS_POLICY_SUBJECT_KEY_ID_ERROR"), NAME);
return PolicyResult.REJECTED;
}
@@ -227,11 +226,11 @@ public class PrivateKeyUsagePeriodExt extends APolicyRule
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return Empty Vector since this policy has no configuration parameters.
- * for this policy instance.
+ * for this policy instance.
*/
- public Vector<String> getInstanceParams() {
+ public Vector<String> getInstanceParams() {
Vector<String> params = new Vector<String>();
params.addElement(PROP_IS_CRITICAL + "=" + mCritical);
@@ -242,11 +241,11 @@ public class PrivateKeyUsagePeriodExt extends APolicyRule
/**
* Return default parameters for a policy implementation.
- *
- * @return Empty Vector since this policy implementation has no
- * configuration parameters.
+ *
+ * @return Empty Vector since this policy implementation has no
+ * configuration parameters.
*/
- public Vector<String> getDefaultParams() {
+ public Vector<String> getDefaultParams() {
Vector<String> defParams = new Vector<String>();
defParams.addElement(PROP_IS_CRITICAL + "=" + DEFAULT_CRITICALITY);
@@ -255,4 +254,3 @@ public class PrivateKeyUsagePeriodExt extends APolicyRule
return defParams;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/policy/extensions/RemoveBasicConstraintsExt.java b/pki/base/common/src/com/netscape/cms/policy/extensions/RemoveBasicConstraintsExt.java
index 396afc97..08c88e97 100644
--- a/pki/base/common/src/com/netscape/cms/policy/extensions/RemoveBasicConstraintsExt.java
+++ b/pki/base/common/src/com/netscape/cms/policy/extensions/RemoveBasicConstraintsExt.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.extensions;
-
import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.Locale;
@@ -37,55 +36,54 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
- * Remove Basic Constraints policy.
- * Adds the Basic constraints extension.
+ * Remove Basic Constraints policy. Adds the Basic constraints extension.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public class RemoveBasicConstraintsExt extends APolicyRule
- implements IEnrollmentPolicy, IExtendedPluginInfo {
+ implements IEnrollmentPolicy, IExtendedPluginInfo {
public RemoveBasicConstraintsExt() {
NAME = "RemoveBasicConstraintsExt";
DESC = "Remove Basic Constraints extension";
}
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
}
public PolicyResult apply(IRequest req) {
PolicyResult res = PolicyResult.ACCEPTED;
// get cert info.
- X509CertInfo[] ci =
- req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
+ X509CertInfo[] ci =
+ req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
X509CertInfo certInfo = null;
if (ci == null || (certInfo = ci[0]) == null) {
- setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO"), NAME);
+ setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO"), NAME);
return PolicyResult.REJECTED; // unrecoverable error.
}
for (int i = 0; i < ci.length; i++) {
PolicyResult certResult = applyCert(req, certInfo);
- if (certResult == PolicyResult.REJECTED)
+ if (certResult == PolicyResult.REJECTED)
return certResult;
}
return PolicyResult.ACCEPTED;
}
public PolicyResult applyCert(
- IRequest req, X509CertInfo certInfo) {
+ IRequest req, X509CertInfo certInfo) {
// get basic constraints extension from cert info if any.
CertificateExtensions extensions = null;
@@ -110,10 +108,10 @@ public class RemoveBasicConstraintsExt extends APolicyRule
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getInstanceParams() {
+ public Vector<String> getInstanceParams() {
Vector<String> params = new Vector<String>();
return params;
@@ -121,10 +119,10 @@ public class RemoveBasicConstraintsExt extends APolicyRule
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getDefaultParams() {
+ public Vector<String> getDefaultParams() {
Vector<String> defParams = new Vector<String>();
return defParams;
@@ -133,13 +131,12 @@ public class RemoveBasicConstraintsExt extends APolicyRule
public String[] getExtendedPluginInfo(Locale locale) {
String[] params = {
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-removebasicconstraints",
+ ";configuration-policyrules-removebasicconstraints",
IExtendedPluginInfo.HELP_TEXT +
- ";Removes the Basic Constraints extension."
+ ";Removes the Basic Constraints extension."
};
return params;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/policy/extensions/SubjAltNameExt.java b/pki/base/common/src/com/netscape/cms/policy/extensions/SubjAltNameExt.java
index aab88ff3..8a91dca6 100644
--- a/pki/base/common/src/com/netscape/cms/policy/extensions/SubjAltNameExt.java
+++ b/pki/base/common/src/com/netscape/cms/policy/extensions/SubjAltNameExt.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.extensions;
-
import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.Locale;
@@ -42,56 +41,54 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
*
- * THIS POLICY HAS BEEN DEPRECATED SINCE CMS 4.2.
- * New Policy is com.netscape.certsrv.policy.SubjectAltNameExt.
+ * THIS POLICY HAS BEEN DEPRECATED SINCE CMS 4.2. New Policy is
+ * com.netscape.certsrv.policy.SubjectAltNameExt.
* <p>
*
* Subject Alternative Name extension policy in CMS 4.1.
- *
- * Adds the subject alternative name extension depending on the
- * certificate type requested.
- *
- * Two forms are supported. 1) For S/MIME certificates, email
- * addresses are copied from data stored in the request by the
- * authentication component. Both 'e' and 'altEmail' are supported
- * so that both the primary address and alternative forms may be
- * certified. Only the primary goes in the subjectName position (which
- * should be phased out).
- *
- * e
- * mailAlternateAddress
+ *
+ * Adds the subject alternative name extension depending on the certificate type
+ * requested.
+ *
+ * Two forms are supported. 1) For S/MIME certificates, email addresses are
+ * copied from data stored in the request by the authentication component. Both
+ * 'e' and 'altEmail' are supported so that both the primary address and
+ * alternative forms may be certified. Only the primary goes in the subjectName
+ * position (which should be phased out).
+ *
+ * e mailAlternateAddress
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public class SubjAltNameExt extends APolicyRule
- implements IEnrollmentPolicy, IExtendedPluginInfo {
- // for future use. currently always allow.
+ implements IEnrollmentPolicy, IExtendedPluginInfo {
+ // for future use. currently always allow.
protected static final String PROP_AGENT_OVERR = "allowAgentOverride";
protected static final String PROP_EE_OVERR = "AllowEEOverride";
protected static final String PROP_ENABLE_MANUAL_VALUES =
- "enableManualValues";
+ "enableManualValues";
- // for future use. currently always non-critical
- // (standard says SHOULD be marked critical if included.)
+ // for future use. currently always non-critical
+ // (standard says SHOULD be marked critical if included.)
protected static final String PROP_CRITICAL = "critical";
- // for future use to allow overrides from forms.
+ // for future use to allow overrides from forms.
// request must be agent approved or authenticated.
protected boolean mAllowAgentOverride = false;
protected boolean mAllowEEOverride = false;
protected boolean mEnableManualValues = false;
- // for future use. currently always critical
- // (standard says SHOULD be marked critical if included.)
+ // for future use. currently always critical
+ // (standard says SHOULD be marked critical if included.)
protected boolean mCritical = false;
public SubjAltNameExt() {
@@ -103,15 +100,15 @@ public class SubjAltNameExt extends APolicyRule
String[] params = {
PROP_CRITICAL + ";boolean;RFC 2459 recommendation: If the certificate subject field contains an empty sequence, the subjectAltName extension MUST be marked critical.",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-subjaltname",
+ ";configuration-policyrules-subjaltname",
IExtendedPluginInfo.HELP_TEXT +
- ";This policy inserts the Subject Alternative Name " +
- "Extension into the certificate. See RFC 2459 (4.2.1.7). " +
- "* Note: you probably want to use this policy in " +
- "conjunction with an authentication manager which sets " +
- "the 'mail' or 'mailalternateaddress' values in the authToken. " +
- "See the 'ldapStringAttrs' parameter in the Directory-based " +
- "authentication plugin"
+ ";This policy inserts the Subject Alternative Name " +
+ "Extension into the certificate. See RFC 2459 (4.2.1.7). " +
+ "* Note: you probably want to use this policy in " +
+ "conjunction with an authentication manager which sets " +
+ "the 'mail' or 'mailalternateaddress' values in the authToken. " +
+ "See the 'ldapStringAttrs' parameter in the Directory-based " +
+ "authentication plugin"
};
return params;
@@ -121,40 +118,41 @@ public class SubjAltNameExt extends APolicyRule
/**
* Initializes this policy rule.
* <P>
- *
+ *
* The entries may be of the form:
- *
- * ra.Policy.rule.<ruleName>.implName=SubjAltNameExt
- * ra.Policy.rule.<ruleName>.enable=true
- *
- * @param config The config store reference
+ *
+ * ra.Policy.rule.<ruleName>.implName=SubjAltNameExt
+ * ra.Policy.rule.<ruleName>.enable=true
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
// future use.
mAllowAgentOverride = config.getBoolean(PROP_AGENT_OVERR, false);
mAllowEEOverride = config.getBoolean(PROP_EE_OVERR, false);
mCritical = config.getBoolean(PROP_CRITICAL, false);
- // mEnableManualValues = config.getBoolean(PROP_ENABLE_MANUAL_VALUES, false);
+ // mEnableManualValues = config.getBoolean(PROP_ENABLE_MANUAL_VALUES,
+ // false);
}
/**
* Adds the subject alternative names extension if not set already.
- *
+ *
* <P>
- *
- * @param req The request on which to apply policy.
+ *
+ * @param req The request on which to apply policy.
* @return The policy result object.
*/
public PolicyResult apply(IRequest req) {
PolicyResult res = PolicyResult.ACCEPTED;
// Find the X509CertInfo object in the request
- X509CertInfo[] ci =
- req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
+ X509CertInfo[] ci =
+ req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
if (ci == null || ci[0] == null) {
- setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO"), NAME);
+ setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO"), NAME);
return PolicyResult.REJECTED; // unrecoverable error.
}
@@ -174,12 +172,11 @@ public class SubjAltNameExt extends APolicyRule
//
// General error handling block
//
- apply:
- try {
+ apply: try {
// Find the extensions in the certInfo
CertificateExtensions extensions = (CertificateExtensions)
- certInfo.get(X509CertInfo.EXTENSIONS);
+ certInfo.get(X509CertInfo.EXTENSIONS);
if (extensions != null) {
//
@@ -193,17 +190,17 @@ public class SubjAltNameExt extends APolicyRule
}
//
- // Determine the type of the request. For future expansion
+ // Determine the type of the request. For future expansion
// this test should dispatch to a specialized object to
- // handle each particular type. For now just return for
+ // handle each particular type. For now just return for
// non-client certs, and implement client certs directly here.
//
String certType =
- req.getExtDataInString(IRequest.HTTP_PARAMS, IRequest.CERT_TYPE);
+ req.getExtDataInString(IRequest.HTTP_PARAMS, IRequest.CERT_TYPE);
if (certType == null ||
- !certType.equals(IRequest.CLIENT_CERT) ||
- !req.getExtDataInBoolean(IRequest.SMIME, false)) {
+ !certType.equals(IRequest.CLIENT_CERT) ||
+ !req.getExtDataInBoolean(IRequest.SMIME, false)) {
break apply;
}
@@ -212,30 +209,32 @@ public class SubjAltNameExt extends APolicyRule
IAuthToken tok = findAuthToken(req, null);
- if (tok == null) break apply;
+ if (tok == null)
+ break apply;
Vector<String> emails = getEmailList(tok);
- if (emails == null) break apply;
+ if (emails == null)
+ break apply;
- // Create the extension
+ // Create the extension
SubjectAlternativeNameExtension subjAltNameExt = mkExt(emails);
if (extensions == null)
extensions = createCertificateExtensions(certInfo);
extensions.set(SubjectAlternativeNameExtension.class.getSimpleName(),
- subjAltNameExt);
+ subjAltNameExt);
} catch (IOException e) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("BASE_IO_ERROR", e.getMessage()));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
- NAME, e.getMessage());
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("BASE_IO_ERROR", e.getMessage()));
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
+ NAME, e.getMessage());
return PolicyResult.REJECTED; // unrecoverable error.
} catch (CertificateException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CA_CERT_INFO_ERROR", e.toString()));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
- NAME, "Certificate Info Error");
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
+ NAME, "Certificate Info Error");
return PolicyResult.REJECTED; // unrecoverable error.
}
@@ -243,28 +242,29 @@ public class SubjAltNameExt extends APolicyRule
}
/**
- * Find a particular authentication token by manager name.
- * If the token is not present return null
+ * Find a particular authentication token by manager name. If the token is
+ * not present return null
*/
protected IAuthToken
- findAuthToken(IRequest req, String authMgrName) {
+ findAuthToken(IRequest req, String authMgrName) {
return req.getExtDataInAuthToken(IRequest.AUTH_TOKEN);
}
/**
- * Generate a String Vector containing all the email addresses
- * found in this Authentication token
+ * Generate a String Vector containing all the email addresses found in this
+ * Authentication token
*/
protected Vector /* of String */<String>
- getEmailList(IAuthToken tok) {
+ getEmailList(IAuthToken tok) {
Vector<String> v = new Vector<String>();
addValues(tok, "mail", v);
addValues(tok, "mailalternateaddress", v);
- if (v.size() == 0) return null;
+ if (v.size() == 0)
+ return null;
return v;
}
@@ -273,10 +273,11 @@ public class SubjAltNameExt extends APolicyRule
* Add attribute values from an LDAP attribute to a vector
*/
protected void
- addValues(IAuthToken tok, String attrName, Vector<String> v) {
+ addValues(IAuthToken tok, String attrName, Vector<String> v) {
String attr[] = tok.getInStringArray(attrName);
- if (attr == null) return;
+ if (attr == null)
+ return;
for (int i = 0; i < attr.length; i++) {
v.addElement(attr[i]);
@@ -287,8 +288,8 @@ public class SubjAltNameExt extends APolicyRule
* Make a Subject name extension given a list of email addresses
*/
protected SubjectAlternativeNameExtension
- mkExt(Vector<String> emails)
- throws IOException {
+ mkExt(Vector<String> emails)
+ throws IOException {
SubjectAlternativeNameExtension sa;
GeneralNames gns = new GeneralNames();
@@ -304,19 +305,18 @@ public class SubjAltNameExt extends APolicyRule
}
/**
- * Create a new SET of extensions in the certificate info
- * object.
- *
+ * Create a new SET of extensions in the certificate info object.
+ *
* This should be a method in the X509CertInfo object
*/
- protected CertificateExtensions
- createCertificateExtensions(X509CertInfo certInfo)
- throws IOException, CertificateException {
+ protected CertificateExtensions
+ createCertificateExtensions(X509CertInfo certInfo)
+ throws IOException, CertificateException {
CertificateExtensions extensions;
// Force version to V3
- certInfo.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ certInfo.set(X509CertInfo.VERSION,
+ new CertificateVersion(CertificateVersion.V3));
extensions = new CertificateExtensions();
certInfo.set(X509CertInfo.EXTENSIONS, extensions);
@@ -326,34 +326,33 @@ public class SubjAltNameExt extends APolicyRule
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getInstanceParams() {
+ public Vector<String> getInstanceParams() {
Vector<String> params = new Vector<String>();
- //params.addElement("PROP_AGENT_OVERR = " + mAllowAgentOverride);
- //params.addElement("PROP_EE_OVERR = " + mAllowEEOverride);
+ // params.addElement("PROP_AGENT_OVERR = " + mAllowAgentOverride);
+ // params.addElement("PROP_EE_OVERR = " + mAllowEEOverride);
params.addElement(PROP_CRITICAL + "=" + mCritical);
// params.addElement(PROP_ENABLE_MANUAL_VALUES + " = " +
- // mEnableManualValues);
+ // mEnableManualValues);
return params;
}
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getDefaultParams() {
- Vector<String> defParams = new Vector<String> ();
+ public Vector<String> getDefaultParams() {
+ Vector<String> defParams = new Vector<String>();
- //defParams.addElement("PROP_AGENT_OVERR = " + DEF_AGENT_OVERR);
- //defParams.addElement("PROP_EE_OVERR = " + DEF_EE_OVERR);
+ // defParams.addElement("PROP_AGENT_OVERR = " + DEF_AGENT_OVERR);
+ // defParams.addElement("PROP_EE_OVERR = " + DEF_EE_OVERR);
defParams.addElement(PROP_CRITICAL + "=false");
// defParams.addElement(PROP_ENABLE_MANUAL_VALUES + "= false");
return defParams;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/policy/extensions/SubjectAltNameExt.java b/pki/base/common/src/com/netscape/cms/policy/extensions/SubjectAltNameExt.java
index b9bc6059..73ac5f0b 100644
--- a/pki/base/common/src/com/netscape/cms/policy/extensions/SubjectAltNameExt.java
+++ b/pki/base/common/src/com/netscape/cms/policy/extensions/SubjectAltNameExt.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.extensions;
-
import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.Enumeration;
@@ -45,33 +44,31 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
* Subject Alternative Name extension policy.
- *
+ *
* Adds the subject alternative name extension as configured.
- *
- * Two forms are supported. 1) For S/MIME certificates, email
- * addresses are copied from data stored in the request by the
- * authentication component. Both 'e' and 'altEmail' are supported
- * so that both the primary address and alternative forms may be
- * certified. Only the primary goes in the subjectName position (which
- * should be phased out).
- *
- * e
- * mailAlternateAddress
+ *
+ * Two forms are supported. 1) For S/MIME certificates, email addresses are
+ * copied from data stored in the request by the authentication component. Both
+ * 'e' and 'altEmail' are supported so that both the primary address and
+ * alternative forms may be certified. Only the primary goes in the subjectName
+ * position (which should be phased out).
+ *
+ * e mailAlternateAddress
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public class SubjectAltNameExt extends APolicyRule
- implements IEnrollmentPolicy, IExtendedPluginInfo {
- // (standard says SHOULD be marked critical if included.)
+ implements IEnrollmentPolicy, IExtendedPluginInfo {
+ // (standard says SHOULD be marked critical if included.)
protected static final String PROP_CRITICAL = "critical";
protected static final boolean DEF_CRITICAL = false;
@@ -89,11 +86,11 @@ public class SubjectAltNameExt extends APolicyRule
// default params.
mDefParams.addElement(PROP_CRITICAL + "=" + DEF_CRITICAL);
mDefParams.addElement(
- IGeneralNameUtil.PROP_NUM_GENERALNAMES + "=" +
- IGeneralNameUtil.DEF_NUM_GENERALNAMES);
+ IGeneralNameUtil.PROP_NUM_GENERALNAMES + "=" +
+ IGeneralNameUtil.DEF_NUM_GENERALNAMES);
for (int i = 0; i < IGeneralNameUtil.DEF_NUM_GENERALNAMES; i++) {
CMS.getSubjAltNameConfigDefaultParams(
- IGeneralNameUtil.PROP_GENERALNAME + i, mDefParams);
+ IGeneralNameUtil.PROP_GENERALNAME + i, mDefParams);
}
}
@@ -107,16 +104,16 @@ public class SubjectAltNameExt extends APolicyRule
/**
* Initializes this policy rule.
* <P>
- *
+ *
* The entries may be of the form:
- *
- * ra.Policy.rule.<ruleName>.implName=SubjectAltNameExt
- * ra.Policy.rule.<ruleName>.enable=true
- *
- * @param config The config store reference
+ *
+ * ra.Policy.rule.<ruleName>.implName=SubjectAltNameExt
+ * ra.Policy.rule.<ruleName>.enable=true
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mConfig = config;
// get criticality
@@ -127,11 +124,11 @@ public class SubjectAltNameExt extends APolicyRule
IPolicyProcessor.PROP_ENABLE, false);
// get general names configuration.
- mNumGNs = mConfig.getInteger(IGeneralNameUtil.PROP_NUM_GENERALNAMES);
+ mNumGNs = mConfig.getInteger(IGeneralNameUtil.PROP_NUM_GENERALNAMES);
if (mNumGNs <= 0) {
throw new EBaseException(
- CMS.getUserMessage("CMS_BASE_MUST_BE_POSITIVE_NUMBER",
- IGeneralNameUtil.PROP_NUM_GENERALNAMES));
+ CMS.getUserMessage("CMS_BASE_MUST_BE_POSITIVE_NUMBER",
+ IGeneralNameUtil.PROP_NUM_GENERALNAMES));
}
mGNs = new ISubjAltNameConfig[mNumGNs];
for (int i = 0; i < mNumGNs; i++) {
@@ -144,7 +141,7 @@ public class SubjectAltNameExt extends APolicyRule
// init instance params.
mInstanceParams.addElement(PROP_CRITICAL + "=" + mCritical);
mInstanceParams.addElement(
- IGeneralNameUtil.PROP_NUM_GENERALNAMES + "=" + mNumGNs);
+ IGeneralNameUtil.PROP_NUM_GENERALNAMES + "=" + mNumGNs);
for (int j = 0; j < mGNs.length; j++) {
mGNs[j].getInstanceParams(mInstanceParams);
}
@@ -152,21 +149,21 @@ public class SubjectAltNameExt extends APolicyRule
/**
* Adds the subject alternative names extension if not set already.
- *
+ *
* <P>
- *
- * @param req The request on which to apply policy.
+ *
+ * @param req The request on which to apply policy.
* @return The policy result object.
*/
public PolicyResult apply(IRequest req) {
PolicyResult res = PolicyResult.ACCEPTED;
// Find the X509CertInfo object in the request
- X509CertInfo[] ci =
- req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
+ X509CertInfo[] ci =
+ req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
if (ci == null || ci[0] == null) {
- setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO"), NAME);
+ setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO"), NAME);
return PolicyResult.REJECTED; // unrecoverable error.
}
@@ -186,15 +183,15 @@ public class SubjectAltNameExt extends APolicyRule
try {
// Find the extensions in the certInfo
CertificateExtensions extensions = (CertificateExtensions)
- certInfo.get(X509CertInfo.EXTENSIONS);
+ certInfo.get(X509CertInfo.EXTENSIONS);
// Remove any previously computed version of the extension
- // unless it is from RA. If from RA, accept what RA put in
+ // unless it is from RA. If from RA, accept what RA put in
// request and don't add our own.
if (extensions != null) {
String sourceId = req.getSourceId();
- if (sourceId != null && sourceId.length() > 0)
+ if (sourceId != null && sourceId.length() > 0)
return res; // accepted
try {
extensions.delete(SubjectAlternativeNameExtension.class.getSimpleName());
@@ -223,8 +220,8 @@ public class SubjectAltNameExt extends APolicyRule
}
// nothing was found in request to put into extension
- if (gns.size() == 0)
- return res; // accepted
+ if (gns.size() == 0)
+ return res; // accepted
String subject = certInfo.get(X509CertInfo.SUBJECT).toString();
@@ -233,10 +230,9 @@ public class SubjectAltNameExt extends APolicyRule
if (subject.equals("")) {
curCritical = true;
}
-
- // make the extension
- SubjectAlternativeNameExtension
- sa = new SubjectAlternativeNameExtension(curCritical, gns);
+
+ // make the extension
+ SubjectAlternativeNameExtension sa = new SubjectAlternativeNameExtension(curCritical, gns);
// add it to certInfo.
if (extensions == null)
@@ -248,37 +244,36 @@ public class SubjectAltNameExt extends APolicyRule
} catch (IOException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("BASE_IO_ERROR", e.getMessage()));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
- NAME, e.getMessage());
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
+ NAME, e.getMessage());
return PolicyResult.REJECTED; // unrecoverable error.
} catch (CertificateException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CA_CERT_INFO_ERROR", e.getMessage()));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
- NAME, "Certificate Info Error");
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
+ NAME, "Certificate Info Error");
return PolicyResult.REJECTED; // unrecoverable error.
} catch (Exception e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("BASE_INTERNAL_ERROR_1", e.getMessage()));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
- NAME, "Internal Error");
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("BASE_INTERNAL_ERROR_1", e.getMessage()));
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
+ NAME, "Internal Error");
return PolicyResult.REJECTED; // unrecoverable error.
}
}
/**
- * Create a new SET of extensions in the certificate info
- * object.
- *
+ * Create a new SET of extensions in the certificate info object.
+ *
* This should be a method in the X509CertInfo object
*/
- protected CertificateExtensions
- createCertificateExtensions(X509CertInfo certInfo)
- throws IOException, CertificateException {
+ protected CertificateExtensions
+ createCertificateExtensions(X509CertInfo certInfo)
+ throws IOException, CertificateException {
CertificateExtensions extensions;
// Force version to V3
- certInfo.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ certInfo.set(X509CertInfo.VERSION,
+ new CertificateVersion(CertificateVersion.V3));
extensions = new CertificateExtensions();
certInfo.set(X509CertInfo.EXTENSIONS, extensions);
@@ -288,19 +283,19 @@ public class SubjectAltNameExt extends APolicyRule
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getInstanceParams() {
+ public Vector<String> getInstanceParams() {
return mInstanceParams;
}
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getDefaultParams() {
+ public Vector<String> getDefaultParams() {
return mDefParams;
}
@@ -313,22 +308,21 @@ public class SubjectAltNameExt extends APolicyRule
info.addElement(IGeneralNameUtil.PROP_NUM_GENERALNAMES_INFO);
for (int i = 0; i < IGeneralNameUtil.DEF_NUM_GENERALNAMES; i++) {
CMS.getSubjAltNameConfigExtendedPluginInfo(
- IGeneralNameUtil.PROP_GENERALNAME + i, info);
+ IGeneralNameUtil.PROP_GENERALNAME + i, info);
}
info.addElement(IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-subjaltname");
+ ";configuration-policyrules-subjaltname");
info.addElement(IExtendedPluginInfo.HELP_TEXT +
- ";This policy inserts the Subject Alternative Name " +
- "Extension into the certificate. See RFC 2459 (4.2.1.7). " +
- "* Note: you probably want to use this policy in " +
- "conjunction with an authentication manager which sets " +
- "the 'mail' or 'mailalternateaddress' values in the authToken. " +
- "See the 'ldapStringAttrs' parameter in the Directory-based " +
- "authentication plugin");
+ ";This policy inserts the Subject Alternative Name " +
+ "Extension into the certificate. See RFC 2459 (4.2.1.7). " +
+ "* Note: you probably want to use this policy in " +
+ "conjunction with an authentication manager which sets " +
+ "the 'mail' or 'mailalternateaddress' values in the authToken. " +
+ "See the 'ldapStringAttrs' parameter in the Directory-based " +
+ "authentication plugin");
mExtendedPluginInfo = new String[info.size()];
info.copyInto(mExtendedPluginInfo);
return mExtendedPluginInfo;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/policy/extensions/SubjectDirectoryAttributesExt.java b/pki/base/common/src/com/netscape/cms/policy/extensions/SubjectDirectoryAttributesExt.java
index 34821fab..2f3812fe 100644
--- a/pki/base/common/src/com/netscape/cms/policy/extensions/SubjectDirectoryAttributesExt.java
+++ b/pki/base/common/src/com/netscape/cms/policy/extensions/SubjectDirectoryAttributesExt.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.extensions;
-
import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.Enumeration;
@@ -45,20 +44,20 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
* Policy to add the subject directory attributes extension.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
-public class SubjectDirectoryAttributesExt extends APolicyRule
- implements IEnrollmentPolicy, IExtendedPluginInfo {
+public class SubjectDirectoryAttributesExt extends APolicyRule
+ implements IEnrollmentPolicy, IExtendedPluginInfo {
protected static final String PROP_CRITICAL = "critical";
protected static final String PROP_ATTRIBUTE = "attribute";
protected static final String PROP_NUM_ATTRIBUTES = "numAttributes";
@@ -75,7 +74,7 @@ public class SubjectDirectoryAttributesExt extends APolicyRule
protected SubjectDirAttributesExtension mExt = null;
protected Vector<String> mParams = new Vector<String>();
- private String[] mEPI = null; // extended plugin info
+ private String[] mEPI = null; // extended plugin info
protected static Vector<String> mDefParams = new Vector<String>();
static {
@@ -85,16 +84,16 @@ public class SubjectDirectoryAttributesExt extends APolicyRule
public SubjectDirectoryAttributesExt() {
NAME = "SubjectDirectoryAttributesExtPolicy";
DESC = "Sets Subject Directory Attributes Extension in certificates.";
- setExtendedPluginInfo();
+ setExtendedPluginInfo();
}
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
boolean enabled = config.getBoolean("enabled", false);
mConfig = config;
- mCritical = mConfig.getBoolean(PROP_CRITICAL, false);
+ mCritical = mConfig.getBoolean(PROP_CRITICAL, false);
mNumAttributes = mConfig.getInteger(PROP_NUM_ATTRIBUTES, DEF_NUM_ATTRIBUTES);
if (mNumAttributes < 1) {
EBaseException ex = new EBaseException(
@@ -110,14 +109,14 @@ public class SubjectDirectoryAttributesExt extends APolicyRule
mAttributes[i] = new AttributeConfig(name, c, enabled);
}
- if (enabled) {
+ if (enabled) {
try {
mExt = formExt(null);
} catch (IOException e) {
log(ILogger.LL_FAILURE, NAME + " Error: " + e.getMessage());
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR",
"Error forming Subject Directory Attributes Extension. " +
- "See log file for details."));
+ "See log file for details."));
}
}
setInstanceParams();
@@ -126,7 +125,7 @@ public class SubjectDirectoryAttributesExt extends APolicyRule
public PolicyResult apply(IRequest req) {
PolicyResult res = PolicyResult.ACCEPTED;
X509CertInfo[] ci =
- req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
+ req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
if (ci == null || ci[0] == null) {
setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO"), NAME);
@@ -136,7 +135,7 @@ public class SubjectDirectoryAttributesExt extends APolicyRule
for (int i = 0; i < ci.length; i++) {
PolicyResult r = applyCert(req, ci[i]);
- if (r == PolicyResult.REJECTED)
+ if (r == PolicyResult.REJECTED)
return r;
}
return PolicyResult.ACCEPTED;
@@ -153,13 +152,14 @@ public class SubjectDirectoryAttributesExt extends APolicyRule
if (extensions == null) {
extensions = new CertificateExtensions();
certInfo.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ new CertificateVersion(CertificateVersion.V3));
certInfo.set(X509CertInfo.EXTENSIONS, extensions);
} else {
try {
extensions.delete(SubjectDirAttributesExtension.class.getSimpleName());
} catch (IOException ee) {
- // if name is not found, try deleting the extension using the OID
+ // if name is not found, try deleting the extension using
+ // the OID
try {
extensions.delete("2.5.29.9");
} catch (IOException eee) {
@@ -173,7 +173,7 @@ public class SubjectDirectoryAttributesExt extends APolicyRule
} else {
SubjectDirAttributesExtension ext = formExt(req);
- if (ext != null)
+ if (ext != null)
extensions.set(SubjectDirAttributesExtension.class.getSimpleName(), formExt(req));
}
return PolicyResult.ACCEPTED;
@@ -181,17 +181,16 @@ public class SubjectDirectoryAttributesExt extends APolicyRule
log(ILogger.LL_FAILURE, CMS.getLogMessage("CA_CERT_INFO_ERROR", e.getMessage()));
setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
- NAME, "Certificate Info Error");
+ NAME, "Certificate Info Error");
return PolicyResult.REJECTED; // unrecoverable error.
} catch (IOException e) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("BASE_IO_ERROR", e.getMessage()));
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("BASE_IO_ERROR", e.getMessage()));
setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
- NAME, "IOException Error");
+ NAME, "IOException Error");
return PolicyResult.REJECTED;
- }
+ }
}
-
public Vector<String> getInstanceParams() {
return mParams; // inited in init()
}
@@ -201,12 +200,12 @@ public class SubjectDirectoryAttributesExt extends APolicyRule
}
public String[] getExtendedPluginInfo(Locale locale) {
- return mEPI; // inited in the constructor.
+ return mEPI; // inited in the constructor.
}
private void setInstanceParams() {
- mParams.addElement(PROP_CRITICAL + "=" + mCritical);
- mParams.addElement(PROP_NUM_ATTRIBUTES + "=" + mNumAttributes);
+ mParams.addElement(PROP_CRITICAL + "=" + mCritical);
+ mParams.addElement(PROP_NUM_ATTRIBUTES + "=" + mNumAttributes);
for (int i = 0; i < mNumAttributes; i++) {
mAttributes[i].getInstanceParams(mParams);
}
@@ -217,8 +216,8 @@ public class SubjectDirectoryAttributesExt extends APolicyRule
}
private static void setDefaultParams() {
- mDefParams.addElement(PROP_CRITICAL + "=" + DEF_CRITICAL);
- mDefParams.addElement(PROP_NUM_ATTRIBUTES + "=" + DEF_NUM_ATTRIBUTES);
+ mDefParams.addElement(PROP_CRITICAL + "=" + DEF_CRITICAL);
+ mDefParams.addElement(PROP_NUM_ATTRIBUTES + "=" + DEF_NUM_ATTRIBUTES);
for (int i = 0; i < DEF_NUM_ATTRIBUTES; i++) {
AttributeConfig.getDefaultParams(PROP_ATTRIBUTE + i, mDefParams);
}
@@ -228,32 +227,31 @@ public class SubjectDirectoryAttributesExt extends APolicyRule
Vector<String> v = new Vector<String>();
v.addElement(PROP_CRITICAL + ";boolean;" +
- "RFC 2459 recommendation: MUST be non-critical.");
+ "RFC 2459 recommendation: MUST be non-critical.");
v.addElement(PROP_NUM_ATTRIBUTES + ";number;" +
- "Number of Attributes in the extension.");
+ "Number of Attributes in the extension.");
for (int i = 0; i < MAX_NUM_ATTRIBUTES; i++) {
AttributeConfig.getExtendedPluginInfo(PROP_ATTRIBUTE + i, v);
}
v.addElement(IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-subjectdirectoryattributes");
+ ";configuration-policyrules-subjectdirectoryattributes");
v.addElement(IExtendedPluginInfo.HELP_TEXT +
- ";Adds Subject Directory Attributes extension. See RFC 2459 (4.2.1.9). It's not recommended as an essential part of the profile, but may be used in local environments.");
+ ";Adds Subject Directory Attributes extension. See RFC 2459 (4.2.1.9). It's not recommended as an essential part of the profile, but may be used in local environments.");
mEPI = com.netscape.cmsutil.util.Utils.getStringArrayFromVector(v);
}
- private SubjectDirAttributesExtension formExt(IRequest req)
- throws IOException {
+ private SubjectDirAttributesExtension formExt(IRequest req)
+ throws IOException {
Vector<Attribute> attrs = new Vector<Attribute>();
// if we're called from init and one attribute is from request attribute
// the ext can't be formed yet.
if (req == null) {
for (int i = 0; i < mNumAttributes; i++) {
- if (mAttributes[i].mWhereToGetValue ==
- AttributeConfig.USE_REQUEST_ATTR)
+ if (mAttributes[i].mWhereToGetValue == AttributeConfig.USE_REQUEST_ATTR)
return null;
}
}
@@ -265,24 +263,23 @@ public class SubjectDirectoryAttributesExt extends APolicyRule
// skip attribute if request attribute doesn't exist.
Attribute a = mAttributes[i].formAttr(req);
- if (a == null)
+ if (a == null)
continue;
attrs.addElement(a);
}
}
- if (attrs.size() == 0)
+ if (attrs.size() == 0)
return null;
Attribute[] attrList = new Attribute[attrs.size()];
attrs.copyInto(attrList);
- SubjectDirAttributesExtension ext =
- new SubjectDirAttributesExtension(attrList);
+ SubjectDirAttributesExtension ext =
+ new SubjectDirAttributesExtension(attrList);
return ext;
}
}
-
class AttributeConfig {
protected static final String PROP_ATTRIBUTE_NAME = "attributeName";
@@ -305,21 +302,21 @@ class AttributeConfig {
protected Attribute mAttribute = null;
protected static final String ATTRIBUTE_NAME_INFO = "Attribute name.";
- protected static final String WTG_VALUE_INFO =
- PROP_WTG_VALUE + ";choice(" + USE_REQUEST_ATTR + "," + USE_FIXED + ");" +
- "Get value from a request attribute or use a fixed value specified below.";
- protected static final String VALUE_INFO =
- PROP_VALUE + ";string;" +
- "Request attribute name or a fixed value to put into the extension.";
-
- public AttributeConfig(String name, IConfigStore config, boolean enabled)
- throws EBaseException {
+ protected static final String WTG_VALUE_INFO =
+ PROP_WTG_VALUE + ";choice(" + USE_REQUEST_ATTR + "," + USE_FIXED + ");" +
+ "Get value from a request attribute or use a fixed value specified below.";
+ protected static final String VALUE_INFO =
+ PROP_VALUE + ";string;" +
+ "Request attribute name or a fixed value to put into the extension.";
+
+ public AttributeConfig(String name, IConfigStore config, boolean enabled)
+ throws EBaseException {
X500NameAttrMap map = X500NameAttrMap.getDefault();
mName = name;
mConfig = config;
if (enabled) {
- mAttributeName = mConfig.getString(PROP_ATTRIBUTE_NAME);
+ mAttributeName = mConfig.getString(PROP_ATTRIBUTE_NAME);
mWhereToGetValue = mConfig.getString(PROP_WTG_VALUE);
mValue = mConfig.getString(PROP_VALUE);
} else {
@@ -330,7 +327,7 @@ class AttributeConfig {
if (mAttributeName.length() > 0) {
mAttributeOID = map.getOid(mAttributeName);
- if (mAttributeOID == null)
+ if (mAttributeOID == null)
throw new EBaseException(
CMS.getUserMessage("CMS_BASE_INVALID_ATTRIBUTE", mAttributeName));
}
@@ -345,8 +342,8 @@ class AttributeConfig {
if (dot != -1) {
mPrefix = mValue.substring(0, dot);
mReqAttr = mValue.substring(dot + 1);
- if (mPrefix == null || mPrefix.length() == 0 ||
- mReqAttr == null || mReqAttr.length() == 0) {
+ if (mPrefix == null || mPrefix.length() == 0 ||
+ mReqAttr == null || mReqAttr.length() == 0) {
throw new EBaseException(
CMS.getUserMessage("CMS_BASE_INVALID_ATTRIBUTE", mValue));
}
@@ -357,17 +354,17 @@ class AttributeConfig {
} else if (mWhereToGetValue.equalsIgnoreCase(USE_FIXED)) {
mWhereToGetValue = USE_FIXED;
if (mAttributeOID != null) {
- try {
- checkValue(mAttributeOID, mValue);
- mAttribute = new Attribute(mAttributeOID, mValue);
+ try {
+ checkValue(mAttributeOID, mValue);
+ mAttribute = new Attribute(mAttributeOID, mValue);
} catch (Exception e) {
throw new EBaseException(
CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
- mAttributeName, e.getMessage()));
+ mAttributeName, e.getMessage()));
}
}
} else if (enabled || mWhereToGetValue.length() > 0) {
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_VALUE_FOR_TYPE", PROP_WTG_VALUE,
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_VALUE_FOR_TYPE", PROP_WTG_VALUE,
"Must be either '" + USE_REQUEST_ATTR + "' or '" + USE_FIXED + "'."));
}
}
@@ -385,7 +382,7 @@ class AttributeConfig {
String attrChoices = getAllNames();
v.addElement(nameDot + PROP_ATTRIBUTE_NAME + ";choice(" + attrChoices + ");" +
- ATTRIBUTE_NAME_INFO);
+ ATTRIBUTE_NAME_INFO);
v.addElement(nameDot + WTG_VALUE_INFO);
v.addElement(nameDot + VALUE_INFO);
}
@@ -398,21 +395,21 @@ class AttributeConfig {
v.addElement(nameDot + PROP_VALUE + "=" + mValue);
}
- public Attribute formAttr(IRequest req)
- throws IOException {
+ public Attribute formAttr(IRequest req)
+ throws IOException {
String val = req.getExtDataInString(mPrefix, mReqAttr);
if (val == null || val.length() == 0) {
return null;
}
- checkValue(mAttributeOID, val);
+ checkValue(mAttributeOID, val);
return new Attribute(mAttributeOID, val);
}
static private String getAllNames() {
Enumeration<String> n = X500NameAttrMap.getDefault().getAllNames();
StringBuffer sb = new StringBuffer();
- sb.append( n.nextElement());
+ sb.append(n.nextElement());
while (n.hasMoreElements()) {
sb.append(",");
@@ -421,8 +418,8 @@ class AttributeConfig {
return sb.toString();
}
- private static void checkValue(ObjectIdentifier oid, String val)
- throws IOException {
+ private static void checkValue(ObjectIdentifier oid, String val)
+ throws IOException {
AVAValueConverter c = X500NameAttrMap.getDefault().getValueConverter(oid);
DerValue derval;
diff --git a/pki/base/common/src/com/netscape/cms/policy/extensions/SubjectKeyIdentifierExt.java b/pki/base/common/src/com/netscape/cms/policy/extensions/SubjectKeyIdentifierExt.java
index 717a6482..08d72dcb 100644
--- a/pki/base/common/src/com/netscape/cms/policy/extensions/SubjectKeyIdentifierExt.java
+++ b/pki/base/common/src/com/netscape/cms/policy/extensions/SubjectKeyIdentifierExt.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.policy.extensions;
-
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@@ -46,21 +45,21 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;
-
/**
- * Subject Public Key Extension Policy
- * Adds the subject public key id extension to certificates.
+ * Subject Public Key Extension Policy Adds the subject public key id extension
+ * to certificates.
* <P>
+ *
* <PRE>
* NOTE: The Policy Framework has been replaced by the Profile Framework.
* </PRE>
* <P>
- *
+ *
* @deprecated
* @version $Revision$, $Date$
*/
public class SubjectKeyIdentifierExt extends APolicyRule
- implements IEnrollmentPolicy, IExtendedPluginInfo {
+ implements IEnrollmentPolicy, IExtendedPluginInfo {
protected static final String PROP_CRITICAL = "critical";
protected static final String PROP_KEYID_TYPE = "keyIdentifierType";
protected static final String PROP_REQATTR_NAME = "requestAttrName";
@@ -90,7 +89,7 @@ public class SubjectKeyIdentifierExt extends APolicyRule
mDefaultParams.addElement(PROP_KEYID_TYPE + "=" + DEF_KEYID_TYPE);
/*
- mDefaultParams.addElement(PROP_REQATTR_NAME+"="+DEF_REQATTR_NAME);
+ * mDefaultParams.addElement(PROP_REQATTR_NAME+"="+DEF_REQATTR_NAME);
*/
}
@@ -102,17 +101,16 @@ public class SubjectKeyIdentifierExt extends APolicyRule
/**
* Initializes this policy rule.
* <P>
- *
+ *
* The entries may be of the form:
- *
- * ca.Policy.rule.<ruleName>.predicate=
- * ca.Policy.rule.<ruleName>.implName=
- * ca.Policy.rule.<ruleName>.enable=true
- *
- * @param config The config store reference
+ *
+ * ca.Policy.rule.<ruleName>.predicate= ca.Policy.rule.<ruleName>.implName=
+ * ca.Policy.rule.<ruleName>.enable=true
+ *
+ * @param config The config store reference
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mConfig = config;
mEnabled = mConfig.getBoolean(
@@ -122,56 +120,57 @@ public class SubjectKeyIdentifierExt extends APolicyRule
mKeyIdType = mConfig.getString(PROP_KEYID_TYPE, DEF_KEYID_TYPE);
/*
- mReqAttrName = mConfig.getString(PROP_REQATTR_NAME, DEF_REQATTR_NAME);
+ * mReqAttrName = mConfig.getString(PROP_REQATTR_NAME,
+ * DEF_REQATTR_NAME);
*/
// parse key id type
- if (mKeyIdType.equalsIgnoreCase(KEYID_TYPE_SHA1))
+ if (mKeyIdType.equalsIgnoreCase(KEYID_TYPE_SHA1))
mKeyIdType = KEYID_TYPE_SHA1;
- else if (mKeyIdType.equalsIgnoreCase(KEYID_TYPE_TYPEFIELD))
+ else if (mKeyIdType.equalsIgnoreCase(KEYID_TYPE_TYPEFIELD))
mKeyIdType = KEYID_TYPE_TYPEFIELD;
- /*
- else if (mKeyIdType.equalsIgnoreCase(KEYID_TYPE_REQATTR)
- mKeyIdType = KEYID_TYPE_REQATTR;
- */
- else if (mKeyIdType.equalsIgnoreCase(KEYID_TYPE_SPKISHA1))
+ /*
+ * else if (mKeyIdType.equalsIgnoreCase(KEYID_TYPE_REQATTR) mKeyIdType =
+ * KEYID_TYPE_REQATTR;
+ */
+ else if (mKeyIdType.equalsIgnoreCase(KEYID_TYPE_SPKISHA1))
mKeyIdType = KEYID_TYPE_SPKISHA1;
else {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("KRA_UNKNOWN_KEY_ID_TYPE", mKeyIdType));
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
- PROP_KEYID_TYPE,
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("KRA_UNKNOWN_KEY_ID_TYPE", mKeyIdType));
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
+ PROP_KEYID_TYPE,
"value must be one of " +
- KEYID_TYPE_SHA1 + ", " +
- KEYID_TYPE_TYPEFIELD + ", " +
- KEYID_TYPE_SPKISHA1));
+ KEYID_TYPE_SHA1 + ", " +
+ KEYID_TYPE_TYPEFIELD + ", " +
+ KEYID_TYPE_SPKISHA1));
}
- // form instance params
+ // form instance params
mInstanceParams.addElement(PROP_CRITICAL + "=" + mCritical);
mInstanceParams.addElement(PROP_KEYID_TYPE + "=" + mKeyIdType);
/*
- mInstanceParams.addElement(PROP_REQATTR_NAME+"="+mReqAttrName);
+ * mInstanceParams.addElement(PROP_REQATTR_NAME+"="+mReqAttrName);
*/
}
/**
- * Adds Subject Key identifier Extension to a certificate.
- * If the extension is already there, accept it.
- *
- * @param req The request on which to apply policy.
+ * Adds Subject Key identifier Extension to a certificate. If the extension
+ * is already there, accept it.
+ *
+ * @param req The request on which to apply policy.
* @return The policy result object.
*/
public PolicyResult apply(IRequest req) {
// get certInfo from request.
- X509CertInfo[] ci =
- req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
-
+ X509CertInfo[] ci =
+ req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
+
if (ci == null || ci[0] == null) {
setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO"), NAME);
- return PolicyResult.REJECTED;
+ return PolicyResult.REJECTED;
}
for (int i = 0; i < ci.length; i++) {
@@ -189,7 +188,7 @@ public class SubjectKeyIdentifierExt extends APolicyRule
// if subject key id extension already exists, leave it if approved.
SubjectKeyIdentifierExtension subjectKeyIdExt = null;
CertificateExtensions extensions = (CertificateExtensions)
- certInfo.get(X509CertInfo.EXTENSIONS);
+ certInfo.get(X509CertInfo.EXTENSIONS);
try {
if (extensions != null) {
@@ -197,19 +196,19 @@ public class SubjectKeyIdentifierExt extends APolicyRule
extensions.get(SubjectKeyIdentifierExtension.class.getSimpleName());
}
} catch (IOException e) {
- // extension isn't there.
+ // extension isn't there.
}
if (subjectKeyIdExt != null) {
if (agentApproved(req)) {
CMS.debug(
- "SubjectKeyIdentifierExt: agent approved request id " + req.getRequestId() +
- " already has subject key id extension with value " +
- subjectKeyIdExt);
+ "SubjectKeyIdentifierExt: agent approved request id " + req.getRequestId() +
+ " already has subject key id extension with value " +
+ subjectKeyIdExt);
return PolicyResult.ACCEPTED;
} else {
CMS.debug(
- "SubjectKeyIdentifierExt: request id from user " + req.getRequestId() +
- " had subject key identifier - deleted to be replaced");
+ "SubjectKeyIdentifierExt: request id from user " + req.getRequestId() +
+ " had subject key identifier - deleted to be replaced");
extensions.delete(SubjectKeyIdentifierExtension.class.getSimpleName());
}
}
@@ -217,38 +216,38 @@ public class SubjectKeyIdentifierExt extends APolicyRule
// create subject key id extension.
KeyIdentifier keyId = null;
- try {
- keyId = formKeyIdentifier(certInfo, req);
+ try {
+ keyId = formKeyIdentifier(certInfo, req);
} catch (EBaseException e) {
setPolicyException(req, e);
return PolicyResult.REJECTED;
}
- subjectKeyIdExt =
+ subjectKeyIdExt =
new SubjectKeyIdentifierExtension(
- mCritical, keyId.getIdentifier());
+ mCritical, keyId.getIdentifier());
// add subject key id extension.
if (extensions == null) {
certInfo.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ new CertificateVersion(CertificateVersion.V3));
extensions = new CertificateExtensions();
certInfo.set(X509CertInfo.EXTENSIONS, extensions);
}
extensions.set(
- SubjectKeyIdentifierExtension.class.getSimpleName(), subjectKeyIdExt);
+ SubjectKeyIdentifierExtension.class.getSimpleName(), subjectKeyIdExt);
CMS.debug(
- "SubjectKeyIdentifierExt: added subject key id ext to request " + req.getRequestId());
+ "SubjectKeyIdentifierExt: added subject key id ext to request " + req.getRequestId());
return PolicyResult.ACCEPTED;
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("POLICY_UNEXPECTED_POLICY_ERROR,NAME", e.getMessage()));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
- NAME, e.getMessage());
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("POLICY_UNEXPECTED_POLICY_ERROR,NAME", e.getMessage()));
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
+ NAME, e.getMessage());
return PolicyResult.REJECTED;
} catch (CertificateException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CA_CERT_INFO_ERROR", e.getMessage()));
- setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
- NAME, "Certificate Info Error");
+ setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
+ NAME, "Certificate Info Error");
return PolicyResult.REJECTED;
}
}
@@ -256,12 +255,13 @@ public class SubjectKeyIdentifierExt extends APolicyRule
/**
* Form the Key Identifier in the Subject Key Identifier extension.
* <p>
+ *
* @param certInfo Certificate Info
* @param req request
* @return A Key Identifier.
*/
protected KeyIdentifier formKeyIdentifier(
- X509CertInfo certInfo, IRequest req) throws EBaseException {
+ X509CertInfo certInfo, IRequest req) throws EBaseException {
KeyIdentifier keyId = null;
if (mKeyIdType == KEYID_TYPE_SHA1) {
@@ -269,10 +269,9 @@ public class SubjectKeyIdentifierExt extends APolicyRule
} else if (mKeyIdType == KEYID_TYPE_TYPEFIELD) {
keyId = formTypeFieldKeyId(certInfo);
} /*
- else if (mKeyIdType == KEYID_TYPE_REQATTR) {
- keyId = formReqAttrKeyId(certInfo, req);
- }
- */ else if (mKeyIdType == KEYID_TYPE_SPKISHA1) {
+ * else if (mKeyIdType == KEYID_TYPE_REQATTR) { keyId =
+ * formReqAttrKeyId(certInfo, req); }
+ */else if (mKeyIdType == KEYID_TYPE_SPKISHA1) {
keyId = formSpkiSHA1KeyId(certInfo);
} else {
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
@@ -282,22 +281,23 @@ public class SubjectKeyIdentifierExt extends APolicyRule
}
/**
- * Form key identifier from a type field value of 0100 followed by
- * the least significate 60 bits of the sha-1 hash of the subject
- * public key BIT STRING in accordance with RFC 2459.
+ * Form key identifier from a type field value of 0100 followed by the least
+ * significate 60 bits of the sha-1 hash of the subject public key BIT
+ * STRING in accordance with RFC 2459.
* <p>
+ *
* @param certInfo - certificate info
* @return A Key Identifier with value formulatd as described.
*/
protected KeyIdentifier formTypeFieldKeyId(X509CertInfo certInfo)
- throws EBaseException {
+ throws EBaseException {
KeyIdentifier keyId = null;
X509Key key = null;
try {
CertificateX509Key certKey =
- (CertificateX509Key) certInfo.get(X509CertInfo.KEY);
+ (CertificateX509Key) certInfo.get(X509CertInfo.KEY);
if (certKey == null) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("POLICY_MISSING_KEY_1", NAME));
@@ -309,13 +309,13 @@ public class SubjectKeyIdentifierExt extends APolicyRule
throw new EPolicyException(CMS.getUserMessage("CMS_POLICY_MISSING_KEY", NAME));
}
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("POLICY_ERROR_GET_KEY_FROM_CERT", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("POLICY_ERROR_GET_KEY_FROM_CERT", e.toString()));
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_SUBJECT_KEY_ID_ERROR", NAME));
} catch (CertificateException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("POLICY_ERROR_GET_KEY_FROM_CERT", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("POLICY_ERROR_GET_KEY_FROM_CERT", e.toString()));
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_SUBJECT_KEY_ID_ERROR", NAME));
}
@@ -330,8 +330,8 @@ public class SubjectKeyIdentifierExt extends APolicyRule
octetString[0] &= (0x08f & octetString[0]);
keyId = new KeyIdentifier(octetString);
} catch (NoSuchAlgorithmException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("POLICY_ERROR_SUBJECT_KEY_ID_1", NAME));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("POLICY_ERROR_SUBJECT_KEY_ID_1", NAME));
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_SUBJECT_KEY_ID_ERROR", NAME));
}
@@ -340,40 +340,39 @@ public class SubjectKeyIdentifierExt extends APolicyRule
/**
* Return configured parameters for a policy rule instance.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getInstanceParams() {
+ public Vector<String> getInstanceParams() {
return mInstanceParams;
}
/**
* Return default parameters for a policy implementation.
- *
+ *
* @return nvPairs A Vector of name/value pairs.
*/
- public Vector<String> getDefaultParams() {
+ public Vector<String> getDefaultParams() {
return mDefaultParams;
}
/**
- * Gets extended plugin info for pretty Console displays.
+ * Gets extended plugin info for pretty Console displays.
*/
public String[] getExtendedPluginInfo(Locale locale) {
String[] params = {
PROP_CRITICAL + ";boolean;RFC 2459 recommendation: MUST NOT be marked critical.",
PROP_KEYID_TYPE + ";" +
- "choice(" + KEYID_TYPE_SHA1 + "," +
- KEYID_TYPE_TYPEFIELD + "," +
- KEYID_TYPE_SPKISHA1 + ");" +
- "Method to derive the Key Identifier.",
+ "choice(" + KEYID_TYPE_SHA1 + "," +
+ KEYID_TYPE_TYPEFIELD + "," +
+ KEYID_TYPE_SPKISHA1 + ");" +
+ "Method to derive the Key Identifier.",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-policyrules-subjectkeyidentifier",
+ ";configuration-policyrules-subjectkeyidentifier",
IExtendedPluginInfo.HELP_TEXT +
- ";Adds the Subject Key Identifier extension. See RFC 2459 (4.2.1.2)"
+ ";Adds the Subject Key Identifier extension. See RFC 2459 (4.2.1.2)"
};
return params;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/profile/common/BasicProfile.java b/pki/base/common/src/com/netscape/cms/profile/common/BasicProfile.java
index 68c706f5..63032d99 100644
--- a/pki/base/common/src/com/netscape/cms/profile/common/BasicProfile.java
+++ b/pki/base/common/src/com/netscape/cms/profile/common/BasicProfile.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.common;
-
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Locale;
@@ -49,10 +48,9 @@ import com.netscape.certsrv.registry.IPluginRegistry;
import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.RequestStatus;
-
/**
* This class implements a basic profile.
- *
+ *
* @version $Revision$, $Date$
*/
public abstract class BasicProfile implements IProfile {
@@ -76,8 +74,8 @@ public abstract class BasicProfile implements IProfile {
public static final String PROP_NAME = "name";
public static final String PROP_DESC = "desc";
public static final String PROP_NO_DEFAULT = "noDefaultImpl";
- public static final String PROP_NO_CONSTRAINT= "noConstraintImpl";
- public static final String PROP_GENERIC_EXT_DEFAULT= "genericExtDefaultImpl";
+ public static final String PROP_NO_CONSTRAINT = "noConstraintImpl";
+ public static final String PROP_GENERIC_EXT_DEFAULT = "genericExtDefaultImpl";
protected IProfileSubsystem mOwner = null;
protected IConfigStore mConfig = null;
@@ -145,19 +143,19 @@ public abstract class BasicProfile implements IProfile {
public IProfileAuthenticator getAuthenticator() throws EProfileException {
try {
IAuthSubsystem authSub = (IAuthSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_AUTH);
+ CMS.getSubsystem(CMS.SUBSYSTEM_AUTH);
IProfileAuthenticator auth = (IProfileAuthenticator)
- authSub.get(mAuthInstanceId);
+ authSub.get(mAuthInstanceId);
- if (mAuthInstanceId != null && mAuthInstanceId.length() > 0
- && auth == null) {
- throw new EProfileException("Cannot load " +
+ if (mAuthInstanceId != null && mAuthInstanceId.length() > 0
+ && auth == null) {
+ throw new EProfileException("Cannot load " +
mAuthInstanceId);
}
return auth;
} catch (Exception e) {
if (mAuthInstanceId != null) {
- throw new EProfileException("Cannot load " +
+ throw new EProfileException("Cannot load " +
mAuthInstanceId);
}
return null;
@@ -167,7 +165,7 @@ public abstract class BasicProfile implements IProfile {
public String getRequestorDN(IRequest request) {
return null;
}
-
+
public String getAuthenticatorId() {
return mAuthInstanceId;
}
@@ -185,7 +183,7 @@ public abstract class BasicProfile implements IProfile {
* Initializes this profile.
*/
public void init(IProfileSubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
CMS.debug("BasicProfile: start init");
mOwner = owner;
mConfig = config;
@@ -204,17 +202,18 @@ public abstract class BasicProfile implements IProfile {
// policy.p1.default.class=com.netscape.cms.profile.defaults.SubjectName
// policy.p1.default.params.x1=x1
// policy.p1.default.params.x2=x2
- // policy.p1.constraint.class= ... .cms.profile.constraints.ValidityRange
+ // policy.p1.constraint.class= ...
+ // .cms.profile.constraints.ValidityRange
// policy.p1.constraint.params.x1=x1
// policy.p1.constraint.params.x2=x2
- // handle profile authentication plugins
+ // handle profile authentication plugins
try {
mAuthInstanceId = config.getString("auth." + PROP_INSTANCE_ID, null);
mAuthzAcl = config.getString("authz.acl", "");
} catch (EBaseException e) {
CMS.debug("BasicProfile: authentication class not found " +
- e.toString());
+ e.toString());
}
// handle profile input plugins
@@ -224,7 +223,7 @@ public abstract class BasicProfile implements IProfile {
while (input_st.hasMoreTokens()) {
String input_id = (String) input_st.nextToken();
- String inputClassId = inputStore.getString(input_id + "." +
+ String inputClassId = inputStore.getString(input_id + "." +
PROP_CLASS_ID);
IPluginInfo inputInfo = mRegistry.getPluginInfo("profileInput",
inputClassId);
@@ -234,12 +233,12 @@ public abstract class BasicProfile implements IProfile {
try {
input = (IProfileInput)
- Class.forName(inputClass).newInstance();
+ Class.forName(inputClass).newInstance();
} catch (Exception e) {
// throw Exception
- CMS.debug("BasicProfile: input plugin Class.forName " +
- inputClass + " " + e.toString());
- throw new EBaseException( e.toString() );
+ CMS.debug("BasicProfile: input plugin Class.forName " +
+ inputClass + " " + e.toString());
+ throw new EBaseException(e.toString());
}
IConfigStore inputConfig = inputStore.getSubStore(input_id);
input.init(this, inputConfig);
@@ -255,7 +254,7 @@ public abstract class BasicProfile implements IProfile {
while (output_st.hasMoreTokens()) {
String output_id = (String) output_st.nextToken();
- String outputClassId = outputStore.getString(output_id + "." +
+ String outputClassId = outputStore.getString(output_id + "." +
PROP_CLASS_ID);
IPluginInfo outputInfo = mRegistry.getPluginInfo("profileOutput",
outputClassId);
@@ -265,12 +264,12 @@ public abstract class BasicProfile implements IProfile {
try {
output = (IProfileOutput)
- Class.forName(outputClass).newInstance();
+ Class.forName(outputClass).newInstance();
} catch (Exception e) {
// throw Exception
- CMS.debug("BasicProfile: output plugin Class.forName " +
- outputClass + " " + e.toString());
- throw new EBaseException( e.toString() );
+ CMS.debug("BasicProfile: output plugin Class.forName " +
+ outputClass + " " + e.toString());
+ throw new EBaseException(e.toString());
}
IConfigStore outputConfig = outputStore.getSubStore(output_id);
output.init(this, outputConfig);
@@ -286,7 +285,7 @@ public abstract class BasicProfile implements IProfile {
while (updater_st.hasMoreTokens()) {
String updater_id = (String) updater_st.nextToken();
- String updaterClassId = updaterStore.getString(updater_id + "." +
+ String updaterClassId = updaterStore.getString(updater_id + "." +
PROP_CLASS_ID);
IPluginInfo updaterInfo = mRegistry.getPluginInfo("profileUpdater",
updaterClassId);
@@ -296,12 +295,12 @@ public abstract class BasicProfile implements IProfile {
try {
updater = (IProfileUpdater)
- Class.forName(updaterClass).newInstance();
+ Class.forName(updaterClass).newInstance();
} catch (Exception e) {
// throw Exception
- CMS.debug("BasicProfile: updater plugin Class.forName " +
- updaterClass + " " + e.toString());
- throw new EBaseException( e.toString() );
+ CMS.debug("BasicProfile: updater plugin Class.forName " +
+ updaterClass + " " + e.toString());
+ throw new EBaseException(e.toString());
}
IConfigStore updaterConfig = updaterStore.getSubStore(updater_id);
updater.init(this, updaterConfig);
@@ -325,15 +324,15 @@ public abstract class BasicProfile implements IProfile {
String id = (String) st1.nextToken();
String defaultRoot = id + "." + PROP_DEFAULT;
- String defaultClassId = policyStore.getString(defaultRoot + "." +
+ String defaultClassId = policyStore.getString(defaultRoot + "." +
PROP_CLASS_ID);
String constraintRoot = id + "." + PROP_CONSTRAINT;
- String constraintClassId =
- policyStore.getString(constraintRoot + "." + PROP_CLASS_ID);
+ String constraintClassId =
+ policyStore.getString(constraintRoot + "." + PROP_CLASS_ID);
- createProfilePolicy(setId, id, defaultClassId,
- constraintClassId, false);
+ createProfilePolicy(setId, id, defaultClassId,
+ constraintClassId, false);
}
}
CMS.debug("BasicProfile: done init");
@@ -380,20 +379,20 @@ public abstract class BasicProfile implements IProfile {
}
public String getInput(String name, Locale locale, IRequest request)
- throws EProfileException {
+ throws EProfileException {
return null;
}
public void setInput(String name, Locale locale, IRequest request,
- String value) throws EProfileException {
+ String value) throws EProfileException {
}
public Enumeration<String> getProfilePolicySetIds() {
return mPolicySet.keys();
}
- public void deleteProfilePolicy(String setId, String policyId)
- throws EProfileException {
+ public void deleteProfilePolicy(String setId, String policyId)
+ throws EProfileException {
Vector<ProfilePolicy> policies = mPolicySet.get(setId);
if (policies == null) {
@@ -443,10 +442,10 @@ public abstract class BasicProfile implements IProfile {
while (st1.hasMoreTokens()) {
String e = st1.nextToken();
- if (!e.equals(setId))
+ if (!e.equals(setId))
newlist1 = newlist1 + e + ",";
}
- if (!newlist1.equals(""))
+ if (!newlist1.equals(""))
newlist1 = newlist1.substring(0, newlist1.length() - 1);
policySetSubStore.putString(PROP_POLICY_LIST, newlist1);
}
@@ -454,8 +453,8 @@ public abstract class BasicProfile implements IProfile {
}
}
- mConfig.putString("lastModified",
- Long.toString(CMS.getCurrentDate().getTime()));
+ mConfig.putString("lastModified",
+ Long.toString(CMS.getCurrentDate().getTime()));
mConfig.commit(false);
} catch (Exception e) {
}
@@ -496,8 +495,8 @@ public abstract class BasicProfile implements IProfile {
mInputs.remove(inputId);
mConfig.putString("input." + PROP_INPUT_LIST, newlist);
- mConfig.putString("lastModified",
- Long.toString(CMS.getCurrentDate().getTime()));
+ mConfig.putString("lastModified",
+ Long.toString(CMS.getCurrentDate().getTime()));
mConfig.commit(false);
} catch (Exception e) {
}
@@ -537,24 +536,23 @@ public abstract class BasicProfile implements IProfile {
mOutputs.remove(outputId);
mConfig.putString("output." + PROP_OUTPUT_LIST, newlist);
- mConfig.putString("lastModified",
- Long.toString(CMS.getCurrentDate().getTime()));
+ mConfig.putString("lastModified",
+ Long.toString(CMS.getCurrentDate().getTime()));
mConfig.commit(false);
} catch (Exception e) {
}
}
- public IProfileOutput createProfileOutput(String id, String outputId,
- NameValuePairs nvps)
- throws EProfileException {
- return createProfileOutput(id, outputId, nvps, true);
+ public IProfileOutput createProfileOutput(String id, String outputId,
+ NameValuePairs nvps)
+ throws EProfileException {
+ return createProfileOutput(id, outputId, nvps, true);
}
public IProfileOutput createProfileOutput(String id, String outputId,
- NameValuePairs nvps, boolean createConfig)
+ NameValuePairs nvps, boolean createConfig)
-
- throws EProfileException {
+ throws EProfileException {
IConfigStore outputStore = mConfig.getSubStore("output");
String output_list = null;
@@ -618,7 +616,7 @@ public abstract class BasicProfile implements IProfile {
String prefix = id + ".";
outputStore.putString(prefix + "name",
- outputInfo.getName(Locale.getDefault()));
+ outputInfo.getName(Locale.getDefault()));
outputStore.putString(prefix + "class_id", outputId);
Enumeration<String> enum1 = nvps.getNames();
@@ -628,17 +626,17 @@ public abstract class BasicProfile implements IProfile {
outputStore.putString(prefix + "params." + name, nvps.getValue(name));
try {
- if (output != null) {
- output.setConfig(name, nvps.getValue(name));
- }
+ if (output != null) {
+ output.setConfig(name, nvps.getValue(name));
+ }
} catch (EBaseException e) {
- CMS.debug(e.toString());
+ CMS.debug(e.toString());
}
}
try {
- mConfig.putString("lastModified",
- Long.toString(CMS.getCurrentDate().getTime()));
+ mConfig.putString("lastModified",
+ Long.toString(CMS.getCurrentDate().getTime()));
mConfig.commit(false);
} catch (EBaseException e) {
CMS.debug(e.toString());
@@ -648,15 +646,15 @@ public abstract class BasicProfile implements IProfile {
return output;
}
- public IProfileInput createProfileInput(String id, String inputId,
- NameValuePairs nvps)
- throws EProfileException {
- return createProfileInput(id, inputId, nvps, true);
+ public IProfileInput createProfileInput(String id, String inputId,
+ NameValuePairs nvps)
+ throws EProfileException {
+ return createProfileInput(id, inputId, nvps, true);
}
public IProfileInput createProfileInput(String id, String inputId,
- NameValuePairs nvps, boolean createConfig)
- throws EProfileException {
+ NameValuePairs nvps, boolean createConfig)
+ throws EProfileException {
IConfigStore inputStore = mConfig.getSubStore("input");
String input_list = null;
@@ -720,10 +718,10 @@ public abstract class BasicProfile implements IProfile {
}
String prefix = id + ".";
- inputStore.putString(prefix + "name",
- inputInfo.getName(Locale.getDefault()));
+ inputStore.putString(prefix + "name",
+ inputInfo.getName(Locale.getDefault()));
inputStore.putString(prefix + "class_id", inputId);
-
+
Enumeration<String> enum1 = nvps.getNames();
while (enum1.hasMoreElements()) {
@@ -731,17 +729,17 @@ public abstract class BasicProfile implements IProfile {
inputStore.putString(prefix + "params." + name, nvps.getValue(name));
try {
- if (input != null) {
- input.setConfig(name, nvps.getValue(name));
- }
+ if (input != null) {
+ input.setConfig(name, nvps.getValue(name));
+ }
} catch (EBaseException e) {
- CMS.debug(e.toString());
+ CMS.debug(e.toString());
}
}
try {
- mConfig.putString("lastModified",
- Long.toString(CMS.getCurrentDate().getTime()));
+ mConfig.putString("lastModified",
+ Long.toString(CMS.getCurrentDate().getTime()));
mConfig.commit(false);
} catch (EBaseException e) {
CMS.debug(e.toString());
@@ -754,33 +752,36 @@ public abstract class BasicProfile implements IProfile {
/**
* Creates a profile policy
*/
- public IProfilePolicy createProfilePolicy(String setId, String id,
- String defaultClassId, String constraintClassId)
- throws EProfileException {
- return createProfilePolicy(setId, id, defaultClassId,
+ public IProfilePolicy createProfilePolicy(String setId, String id,
+ String defaultClassId, String constraintClassId)
+ throws EProfileException {
+ return createProfilePolicy(setId, id, defaultClassId,
constraintClassId, true);
}
- public IProfilePolicy createProfilePolicy(String setId, String id,
- String defaultClassId, String constraintClassId,
- boolean createConfig)
- throws EProfileException {
-
+ public IProfilePolicy createProfilePolicy(String setId, String id,
+ String defaultClassId, String constraintClassId,
+ boolean createConfig)
+ throws EProfileException {
+
// String setId ex: policyset.set1
- // String id Id of policy : examples: p1,p2,p3
- // String defaultClassId : id of the default plugin ex: validityDefaultImpl
- // String constraintClassId : if of the constraint plugin ex: basicConstraintsExtConstraintImpl
- // boolean createConfig : true : being called from the console. false: being called from server startup code
+ // String id Id of policy : examples: p1,p2,p3
+ // String defaultClassId : id of the default plugin ex:
+ // validityDefaultImpl
+ // String constraintClassId : if of the constraint plugin ex:
+ // basicConstraintsExtConstraintImpl
+ // boolean createConfig : true : being called from the console. false:
+ // being called from server startup code
- Vector<ProfilePolicy> policies = mPolicySet.get(setId);
+ Vector<ProfilePolicy> policies = mPolicySet.get(setId);
IConfigStore policyStore = mConfig.getSubStore("policyset." + setId);
if (policies == null) {
policies = new Vector<ProfilePolicy>();
mPolicySet.put(setId, policies);
- if (createConfig) {
+ if (createConfig) {
// re-create policyset.list
- StringBuffer setlist =new StringBuffer();
+ StringBuffer setlist = new StringBuffer();
Enumeration<String> keys = mPolicySet.keys();
while (keys.hasMoreElements()) {
@@ -794,62 +795,62 @@ public abstract class BasicProfile implements IProfile {
mConfig.putString("policyset.list", setlist.toString());
}
} else {
- String ids = null;
+ String ids = null;
- try {
- ids = policyStore.getString(PROP_POLICY_LIST, "");
- } catch (Exception ee) {
- }
+ try {
+ ids = policyStore.getString(PROP_POLICY_LIST, "");
+ } catch (Exception ee) {
+ }
- if( ids == null ) {
- CMS.debug("BasicProfile::createProfilePolicy() - ids is null!" );
- return null;
- }
+ if (ids == null) {
+ CMS.debug("BasicProfile::createProfilePolicy() - ids is null!");
+ return null;
+ }
- StringTokenizer st1 = new StringTokenizer(ids, ",");
- int appearances = 0;
- int appearancesTooMany = 0;
- if (createConfig)
- appearancesTooMany = 1;
- else
- appearancesTooMany = 2;
+ StringTokenizer st1 = new StringTokenizer(ids, ",");
+ int appearances = 0;
+ int appearancesTooMany = 0;
+ if (createConfig)
+ appearancesTooMany = 1;
+ else
+ appearancesTooMany = 2;
- while (st1.hasMoreTokens()) {
- String pid = st1.nextToken();
- if (pid.equals(id)) {
- appearances++;
- if (appearances >= appearancesTooMany) {
- CMS.debug("WARNING detected duplicate policy id: " + id + " Profile: " + mId);
- if (createConfig) {
- throw new EProfileException("Duplicate policy id: " + id);
- }
+ while (st1.hasMoreTokens()) {
+ String pid = st1.nextToken();
+ if (pid.equals(id)) {
+ appearances++;
+ if (appearances >= appearancesTooMany) {
+ CMS.debug("WARNING detected duplicate policy id: " + id + " Profile: " + mId);
+ if (createConfig) {
+ throw new EProfileException("Duplicate policy id: " + id);
}
}
}
+ }
}
// Now make sure we aren't trying to add a policy that already exists
IConfigStore policySetStore = mConfig.getSubStore("policyset");
- String setlist = null;
+ String setlist = null;
try {
setlist = policySetStore.getString("list", "");
} catch (Exception e) {
}
StringTokenizer st = new StringTokenizer(setlist, ",");
- int matches = 0;
+ int matches = 0;
while (st.hasMoreTokens()) {
String sId = (String) st.nextToken();
- //Only search the setId set. Ex: encryptionCertSet
+ // Only search the setId set. Ex: encryptionCertSet
if (!sId.equals(setId)) {
continue;
}
IConfigStore pStore = policySetStore.getSubStore(sId);
-
+
String list = null;
try {
- list = pStore.getString(PROP_POLICY_LIST, "");
+ list = pStore.getString(PROP_POLICY_LIST, "");
} catch (Exception e) {
CMS.debug("WARNING, can't get policy id list!");
}
@@ -862,9 +863,9 @@ public abstract class BasicProfile implements IProfile {
String defaultRoot = curId + "." + PROP_DEFAULT;
String curDefaultClassId = null;
try {
- curDefaultClassId = pStore.getString(defaultRoot + "." +
- PROP_CLASS_ID);
- } catch(Exception e) {
+ curDefaultClassId = pStore.getString(defaultRoot + "." +
+ PROP_CLASS_ID);
+ } catch (Exception e) {
CMS.debug("WARNING, can't get default plugin id!");
}
@@ -876,24 +877,23 @@ public abstract class BasicProfile implements IProfile {
CMS.debug("WARNING, can't get constraint plugin id!");
}
- //Disallow duplicate defaults with the following exceptions:
+ // Disallow duplicate defaults with the following exceptions:
// noDefaultImpl, genericExtDefaultImpl
- if ((curDefaultClassId.equals(defaultClassId) &&
- !curDefaultClassId.equals(PROP_NO_DEFAULT) &&
- !curDefaultClassId.equals(PROP_GENERIC_EXT_DEFAULT)) ) {
+ if ((curDefaultClassId.equals(defaultClassId) &&
+ !curDefaultClassId.equals(PROP_NO_DEFAULT) && !curDefaultClassId.equals(PROP_GENERIC_EXT_DEFAULT))) {
matches++;
if (createConfig) {
if (matches == 1) {
- CMS.debug("WARNING attempt to add duplicate Policy " + defaultClassId + ":" + constraintClassId +
- " Contact System Administrator.");
- throw new EProfileException("Attempt to add duplicate Policy : " + defaultClassId + ":" + constraintClassId);
+ CMS.debug("WARNING attempt to add duplicate Policy " + defaultClassId + ":" + constraintClassId +
+ " Contact System Administrator.");
+ throw new EProfileException("Attempt to add duplicate Policy : " + defaultClassId + ":" + constraintClassId);
}
} else {
- if( matches > 1) {
- CMS.debug("WARNING attempt to add duplicate Policy " + defaultClassId + ":" + constraintClassId +
- " Contact System Administrator.");
+ if (matches > 1) {
+ CMS.debug("WARNING attempt to add duplicate Policy " + defaultClassId + ":" + constraintClassId +
+ " Contact System Administrator.");
}
}
}
@@ -919,8 +919,8 @@ public abstract class BasicProfile implements IProfile {
Class.forName(defaultClass).newInstance();
} catch (Exception e) {
// throw Exception
- CMS.debug("BasicProfile: default policy " +
- defaultClass + " " + e.toString());
+ CMS.debug("BasicProfile: default policy " +
+ defaultClass + " " + e.toString());
}
if (def == null) {
CMS.debug("BasicProfile: failed to create " + defaultClass);
@@ -931,7 +931,7 @@ public abstract class BasicProfile implements IProfile {
def.init(this, defStore);
}
- IPluginInfo conInfo = mRegistry.getPluginInfo("constraintPolicy",
+ IPluginInfo conInfo = mRegistry.getPluginInfo("constraintPolicy",
constraintClassId);
String constraintClass = conInfo.getClassName();
IPolicyConstraint constraint = null;
@@ -941,8 +941,8 @@ public abstract class BasicProfile implements IProfile {
Class.forName(constraintClass).newInstance();
} catch (Exception e) {
// throw Exception
- CMS.debug("BasicProfile: constraint policy " +
- constraintClass + " " + e.toString());
+ CMS.debug("BasicProfile: constraint policy " +
+ constraintClass + " " + e.toString());
}
ProfilePolicy policy = null;
if (constraint == null) {
@@ -968,21 +968,21 @@ public abstract class BasicProfile implements IProfile {
} else {
policyStore.putString(PROP_POLICY_LIST, list + "," + id);
}
- policyStore.putString(id + ".default.name",
- defInfo.getName(Locale.getDefault()));
- policyStore.putString(id + ".default.class_id",
- defaultClassId);
- policyStore.putString(id + ".constraint.name",
- conInfo.getName(Locale.getDefault()));
- policyStore.putString(id + ".constraint.class_id",
- constraintClassId);
+ policyStore.putString(id + ".default.name",
+ defInfo.getName(Locale.getDefault()));
+ policyStore.putString(id + ".default.class_id",
+ defaultClassId);
+ policyStore.putString(id + ".constraint.name",
+ conInfo.getName(Locale.getDefault()));
+ policyStore.putString(id + ".constraint.class_id",
+ constraintClassId);
try {
- mConfig.putString("lastModified",
- Long.toString(CMS.getCurrentDate().getTime()));
+ mConfig.putString("lastModified",
+ Long.toString(CMS.getCurrentDate().getTime()));
policyStore.commit(false);
} catch (EBaseException e) {
- CMS.debug("BasicProfile: commiting config store " +
- e.toString());
+ CMS.debug("BasicProfile: commiting config store " +
+ e.toString());
}
}
@@ -990,7 +990,7 @@ public abstract class BasicProfile implements IProfile {
}
public IProfilePolicy getProfilePolicy(String setId, String id) {
- Vector<ProfilePolicy> policies = mPolicySet.get(setId);
+ Vector<ProfilePolicy> policies = mPolicySet.get(setId);
if (policies == null)
return null;
@@ -1038,7 +1038,7 @@ public abstract class BasicProfile implements IProfile {
* Creates request.
*/
public abstract IRequest[] createRequests(IProfileContext ctx, Locale locale)
- throws EProfileException;
+ throws EProfileException;
/**
* Returns the profile description.
@@ -1056,54 +1056,54 @@ public abstract class BasicProfile implements IProfile {
}
public void populateInput(IProfileContext ctx, IRequest request)
- throws EProfileException {
+ throws EProfileException {
Enumeration<String> ids = getProfileInputIds();
while (ids.hasMoreElements()) {
String id = (String) ids.nextElement();
- IProfileInput input = getProfileInput(id);
+ IProfileInput input = getProfileInput(id);
input.populate(ctx, request);
}
}
public Vector<ProfilePolicy> getPolicies(String setId) {
- Vector<ProfilePolicy> policies = mPolicySet.get(setId);
+ Vector<ProfilePolicy> policies = mPolicySet.get(setId);
return policies;
}
/**
- * Passes the request to the set of default policies that
- * populate the profile information against the profile.
- */
+ * Passes the request to the set of default policies that populate the
+ * profile information against the profile.
+ */
public void populate(IRequest request)
- throws EProfileException {
+ throws EProfileException {
String setId = getPolicySetId(request);
Vector<ProfilePolicy> policies = getPolicies(setId);
- CMS.debug("BasicProfile: populate() policy setid ="+ setId);
+ CMS.debug("BasicProfile: populate() policy setid =" + setId);
for (int i = 0; i < policies.size(); i++) {
ProfilePolicy policy = (ProfilePolicy)
- policies.elementAt(i);
+ policies.elementAt(i);
policy.getDefault().populate(request);
}
}
/**
- * Passes the request to the set of constraint policies
- * that validate the request against the profile.
- */
+ * Passes the request to the set of constraint policies that validate the
+ * request against the profile.
+ */
public void validate(IRequest request)
- throws ERejectException {
+ throws ERejectException {
String setId = getPolicySetId(request);
- CMS.debug("BasicProfile: validate start on setId="+ setId);
+ CMS.debug("BasicProfile: validate start on setId=" + setId);
Vector<ProfilePolicy> policies = getPolicies(setId);
for (int i = 0; i < policies.size(); i++) {
ProfilePolicy policy = (ProfilePolicy)
- policies.elementAt(i);
+ policies.elementAt(i);
policy.getConstraint().validate(request);
}
@@ -1130,24 +1130,24 @@ public abstract class BasicProfile implements IProfile {
for (int i = 0; i < policies.size(); i++) {
ProfilePolicy policy = (ProfilePolicy)
- policies.elementAt(i);
+ policies.elementAt(i);
- v.addElement(policy.getId());
+ v.addElement(policy.getId());
}
return v.elements();
}
public void execute(IRequest request)
- throws EProfileException {
+ throws EProfileException {
}
/**
* Signed Audit Log
- *
- * This method is inherited by all extended "BasicProfile"s,
- * and is called to store messages to the signed audit log.
+ *
+ * This method is inherited by all extended "BasicProfile"s, and is called
+ * to store messages to the signed audit log.
* <P>
- *
+ *
* @param msg signed audit log message
*/
protected void audit(String msg) {
@@ -1159,20 +1159,19 @@ public abstract class BasicProfile implements IProfile {
}
mSignedAuditLogger.log(ILogger.EV_SIGNED_AUDIT,
- null,
- ILogger.S_SIGNED_AUDIT,
- ILogger.LL_SECURITY,
- msg);
+ null,
+ ILogger.S_SIGNED_AUDIT,
+ ILogger.LL_SECURITY,
+ msg);
}
/**
* Signed Audit Log Subject ID
- *
- * This method is inherited by all extended "BasicProfile"s,
- * and is called to obtain the "SubjectID" for
- * a signed audit log message.
+ *
+ * This method is inherited by all extended "BasicProfile"s, and is called
+ * to obtain the "SubjectID" for a signed audit log message.
* <P>
- *
+ *
* @return id string containing the signed audit log message SubjectID
*/
protected String auditSubjectID() {
@@ -1202,4 +1201,3 @@ public abstract class BasicProfile implements IProfile {
return subjectID;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/profile/common/CACertCAEnrollProfile.java b/pki/base/common/src/com/netscape/cms/profile/common/CACertCAEnrollProfile.java
index 681f2b4a..72c0aebe 100644
--- a/pki/base/common/src/com/netscape/cms/profile/common/CACertCAEnrollProfile.java
+++ b/pki/base/common/src/com/netscape/cms/profile/common/CACertCAEnrollProfile.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.common;
-
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.common.NameValuePairs;
@@ -28,103 +27,101 @@ import com.netscape.certsrv.profile.IProfileInput;
import com.netscape.certsrv.profile.IProfileOutput;
import com.netscape.certsrv.profile.IProfilePolicy;
-
/**
- * This class implements a Certificate Manager enrollment
- * profile for CA Certificates.
- *
+ * This class implements a Certificate Manager enrollment profile for CA
+ * Certificates.
+ *
* @version $Revision$, $Date$
*/
-public class CACertCAEnrollProfile extends CAEnrollProfile
- implements IProfileEx {
+public class CACertCAEnrollProfile extends CAEnrollProfile
+ implements IProfileEx {
/**
- * Called after initialization. It populates default
- * policies, inputs, and outputs.
+ * Called after initialization. It populates default policies, inputs, and
+ * outputs.
*/
- public void populate() throws EBaseException
- {
+ public void populate() throws EBaseException {
// create inputs
NameValuePairs inputParams1 = new NameValuePairs();
- IProfileInput input1 =
- createProfileInput("i1", "certReqInputImpl", inputParams1);
+ IProfileInput input1 =
+ createProfileInput("i1", "certReqInputImpl", inputParams1);
NameValuePairs inputParams2 = new NameValuePairs();
- IProfileInput input2 =
- createProfileInput("i2", "submitterInfoInputImpl", inputParams2);
+ IProfileInput input2 =
+ createProfileInput("i2", "submitterInfoInputImpl", inputParams2);
- // create outputs
+ // create outputs
NameValuePairs outputParams1 = new NameValuePairs();
- IProfileOutput output1 =
- createProfileOutput("o1", "certOutputImpl", outputParams1);
+ IProfileOutput output1 =
+ createProfileOutput("o1", "certOutputImpl", outputParams1);
// create policies
IProfilePolicy policy1 =
- createProfilePolicy("set1", "p1",
- "userSubjectNameDefaultImpl", "noConstraintImpl");
+ createProfilePolicy("set1", "p1",
+ "userSubjectNameDefaultImpl", "noConstraintImpl");
IPolicyDefault def1 = policy1.getDefault();
IConfigStore defConfig1 = def1.getConfigStore();
IPolicyConstraint con1 = policy1.getConstraint();
IConfigStore conConfig1 = con1.getConfigStore();
IProfilePolicy policy2 =
- createProfilePolicy("set1", "p2",
- "validityDefaultImpl", "noConstraintImpl");
+ createProfilePolicy("set1", "p2",
+ "validityDefaultImpl", "noConstraintImpl");
IPolicyDefault def2 = policy2.getDefault();
IConfigStore defConfig2 = def2.getConfigStore();
- defConfig2.putString("params.range","180");
- defConfig2.putString("params.startTime","0");
+ defConfig2.putString("params.range", "180");
+ defConfig2.putString("params.startTime", "0");
IPolicyConstraint con2 = policy2.getConstraint();
IConfigStore conConfig2 = con2.getConfigStore();
IProfilePolicy policy3 =
- createProfilePolicy("set1", "p3",
- "userKeyDefaultImpl", "noConstraintImpl");
+ createProfilePolicy("set1", "p3",
+ "userKeyDefaultImpl", "noConstraintImpl");
IPolicyDefault def3 = policy3.getDefault();
IConfigStore defConfig3 = def3.getConfigStore();
- defConfig3.putString("params.keyType","RSA");
- defConfig3.putString("params.keyMinLength","512");
- defConfig3.putString("params.keyMaxLength","4096");
+ defConfig3.putString("params.keyType", "RSA");
+ defConfig3.putString("params.keyMinLength", "512");
+ defConfig3.putString("params.keyMaxLength", "4096");
IPolicyConstraint con3 = policy3.getConstraint();
IConfigStore conConfig3 = con3.getConfigStore();
IProfilePolicy policy4 =
- createProfilePolicy("set1", "p4",
- "signingAlgDefaultImpl", "noConstraintImpl");
+ createProfilePolicy("set1", "p4",
+ "signingAlgDefaultImpl", "noConstraintImpl");
IPolicyDefault def4 = policy4.getDefault();
IConfigStore defConfig4 = def4.getConfigStore();
- defConfig4.putString("params.signingAlg","-");
+ defConfig4.putString("params.signingAlg", "-");
defConfig4.putString("params.signingAlgsAllowed",
- "SHA1withRSA,SHA256withRSA,SHA512withRSA,MD5withRSA,MD2withRSA,SHA256withEC,SHA384withEC,SHA512withEC");
+ "SHA1withRSA,SHA256withRSA,SHA512withRSA,MD5withRSA,MD2withRSA,SHA256withEC,SHA384withEC,SHA512withEC");
IPolicyConstraint con4 = policy4.getConstraint();
IConfigStore conConfig4 = con4.getConfigStore();
// extensions
IProfilePolicy policy5 =
- createProfilePolicy("set1", "p5",
- "keyUsageExtDefaultImpl", "noConstraintImpl");
+ createProfilePolicy("set1", "p5",
+ "keyUsageExtDefaultImpl", "noConstraintImpl");
IPolicyDefault def5 = policy5.getDefault();
IConfigStore defConfig5 = def5.getConfigStore();
- defConfig5.putString("params.keyUsageCritical","true");
- defConfig5.putString("params.keyUsageCrlSign","true");
- defConfig5.putString("params.keyUsageDataEncipherment","false");
- defConfig5.putString("params.keyUsageDecipherOnly","false");
- defConfig5.putString("params.keyUsageDigitalSignature","true");
- defConfig5.putString("params.keyUsageEncipherOnly","false");
- defConfig5.putString("params.keyUsageKeyAgreement","false");
- defConfig5.putString("params.keyUsageKeyCertSign","true");
- defConfig5.putString("params.keyUsageKeyEncipherment","false");
- defConfig5.putString("params.keyUsageNonRepudiation","true");
+ defConfig5.putString("params.keyUsageCritical", "true");
+ defConfig5.putString("params.keyUsageCrlSign", "true");
+ defConfig5.putString("params.keyUsageDataEncipherment", "false");
+ defConfig5.putString("params.keyUsageDecipherOnly", "false");
+ defConfig5.putString("params.keyUsageDigitalSignature", "true");
+ defConfig5.putString("params.keyUsageEncipherOnly", "false");
+ defConfig5.putString("params.keyUsageKeyAgreement", "false");
+ defConfig5.putString("params.keyUsageKeyCertSign", "true");
+ defConfig5.putString("params.keyUsageKeyEncipherment", "false");
+ defConfig5.putString("params.keyUsageNonRepudiation", "true");
IPolicyConstraint con5 = policy5.getConstraint();
IConfigStore conConfig5 = con5.getConfigStore();
IProfilePolicy policy6 =
- createProfilePolicy("set1", "p6",
- "basicConstraintsExtDefaultImpl", "noConstraintImpl");
+ createProfilePolicy("set1", "p6",
+ "basicConstraintsExtDefaultImpl", "noConstraintImpl");
IPolicyDefault def6 = policy6.getDefault();
IConfigStore defConfig6 = def6.getConfigStore();
- defConfig6.putString("params.basicConstraintsPathLen","-1");
- defConfig6.putString("params.basicConstraintsIsCA","true");
- defConfig6.putString("params.basicConstraintsPathLen","-1");
+ defConfig6.putString("params.basicConstraintsPathLen", "-1");
+ defConfig6.putString("params.basicConstraintsIsCA", "true");
+ defConfig6.putString("params.basicConstraintsPathLen", "-1");
IPolicyConstraint con6 = policy6.getConstraint();
IConfigStore conConfig6 = con6.getConfigStore();
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/common/CAEnrollProfile.java b/pki/base/common/src/com/netscape/cms/profile/common/CAEnrollProfile.java
index 32cd51b5..df558acb 100644
--- a/pki/base/common/src/com/netscape/cms/profile/common/CAEnrollProfile.java
+++ b/pki/base/common/src/com/netscape/cms/profile/common/CAEnrollProfile.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.common;
-
import java.util.Enumeration;
import netscape.security.x509.X500Name;
@@ -41,27 +40,23 @@ import com.netscape.certsrv.profile.IProfileUpdater;
import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.RequestStatus;
-
/**
- * This class implements a Certificate Manager enrollment
- * profile.
- *
+ * This class implements a Certificate Manager enrollment profile.
+ *
* @version $Revision$, $Date$
*/
public class CAEnrollProfile extends EnrollProfile {
- private final static String
- LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST =
- "LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST_4";
-
+ private final static String LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST =
+ "LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST_4";
public CAEnrollProfile() {
super();
}
public IAuthority getAuthority() {
- IAuthority authority = (IAuthority)
- CMS.getSubsystem(CMS.SUBSYSTEM_CA);
+ IAuthority authority = (IAuthority)
+ CMS.getSubsystem(CMS.SUBSYSTEM_CA);
if (authority == null)
return null;
@@ -70,17 +65,17 @@ public class CAEnrollProfile extends EnrollProfile {
public X500Name getIssuerName() {
ICertificateAuthority ca = (ICertificateAuthority)
- CMS.getSubsystem(CMS.SUBSYSTEM_CA);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CA);
X500Name issuerName = ca.getX500Name();
return issuerName;
}
public void execute(IRequest request)
- throws EProfileException {
+ throws EProfileException {
long startTime = CMS.getCurrentDate().getTime();
-
+
if (!isEnable()) {
CMS.debug("CAEnrollProfile: Profile Not Enabled");
throw new EProfileException("Profile Not Enabled");
@@ -91,14 +86,13 @@ public class CAEnrollProfile extends EnrollProfile {
String auditRequesterID = auditRequesterID(request);
String auditArchiveID = ILogger.UNIDENTIFIED;
-
String id = request.getRequestId().toString();
if (id != null) {
auditArchiveID = id.trim();
}
- CMS.debug("CAEnrollProfile: execute reqId=" +
- request.getRequestId().toString());
+ CMS.debug("CAEnrollProfile: execute reqId=" +
+ request.getRequestId().toString());
ICertificateAuthority ca = (ICertificateAuthority) getAuthority();
ICAService caService = (ICAService) ca.getCAService();
@@ -113,41 +107,39 @@ public class CAEnrollProfile extends EnrollProfile {
// do not archive keys for renewal requests
if ((optionsData != null) && (!request.getRequestType().equals(IRequest.RENEWAL_REQUEST))) {
PKIArchiveOptions options = (PKIArchiveOptions)
- toPKIArchiveOptions(optionsData);
+ toPKIArchiveOptions(optionsData);
if (options != null) {
CMS.debug("CAEnrollProfile: execute found " +
- "PKIArchiveOptions");
+ "PKIArchiveOptions");
try {
IConnector kraConnector = caService.getKRAConnector();
if (kraConnector == null) {
CMS.debug("CAEnrollProfile: KRA connector " +
- "not configured");
+ "not configured");
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST,
- auditSubjectID,
- ILogger.FAILURE,
- auditRequesterID,
- auditArchiveID);
+ LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditRequesterID,
+ auditArchiveID);
audit(auditMessage);
-
+
} else {
CMS.debug("CAEnrollProfile: execute send request");
kraConnector.send(request);
-
-
// check response
if (!request.isSuccess()) {
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST,
- auditSubjectID,
- ILogger.FAILURE,
- auditRequesterID,
- auditArchiveID);
+ LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditRequesterID,
+ auditArchiveID);
audit(auditMessage);
throw new ERejectException(
@@ -155,17 +147,16 @@ public class CAEnrollProfile extends EnrollProfile {
}
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST,
- auditSubjectID,
- ILogger.SUCCESS,
- auditRequesterID,
- auditArchiveID);
+ LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST,
+ auditSubjectID,
+ ILogger.SUCCESS,
+ auditRequesterID,
+ auditArchiveID);
audit(auditMessage);
}
} catch (Exception e) {
-
if (e instanceof ERejectException) {
throw (ERejectException) e;
}
@@ -189,17 +180,17 @@ public class CAEnrollProfile extends EnrollProfile {
X509CertInfo info = request.getExtDataInCertInfo(REQUEST_CERTINFO);
X509CertImpl theCert = null;
- // #615460 - added audit log (transaction)
+ // #615460 - added audit log (transaction)
SessionContext sc = SessionContext.getExistingContext();
sc.put("profileId", getId());
String setId = request.getExtDataInString("profileSetId");
if (setId != null) {
- sc.put("profileSetId", setId);
+ sc.put("profileSetId", setId);
}
try {
theCert = caService.issueX509Cert(info, getId() /* profileId */,
- id /* requestId */);
+ id /* requestId */);
} catch (EBaseException e) {
CMS.debug(e.toString());
@@ -211,24 +202,24 @@ public class CAEnrollProfile extends EnrollProfile {
String initiative = AuditFormat.FROMAGENT
+ " userID: "
- + (String)sc.get(SessionContext.USER_ID);
- String authMgr = (String)sc.get(SessionContext.AUTH_MANAGER_ID);
+ + (String) sc.get(SessionContext.USER_ID);
+ String authMgr = (String) sc.get(SessionContext.AUTH_MANAGER_ID);
ILogger logger = CMS.getLogger();
- if( logger != null ) {
- logger.log( ILogger.EV_AUDIT,
- ILogger.S_OTHER, AuditFormat.LEVEL, AuditFormat.FORMAT,
- new Object[] {
- request.getRequestType(),
- request.getRequestId(),
- initiative,
- authMgr,
- "completed",
- theCert.getSubjectDN(),
- "cert issued serial number: 0x" +
- theCert.getSerialNumber().toString(16) +
- " time: " + (endTime - startTime) }
- );
+ if (logger != null) {
+ logger.log(ILogger.EV_AUDIT,
+ ILogger.S_OTHER, AuditFormat.LEVEL, AuditFormat.FORMAT,
+ new Object[] {
+ request.getRequestType(),
+ request.getRequestId(),
+ initiative,
+ authMgr,
+ "completed",
+ theCert.getSubjectDN(),
+ "cert issued serial number: 0x" +
+ theCert.getSerialNumber().toString(16) +
+ " time: " + (endTime - startTime) }
+ );
}
request.setRequestStatus(RequestStatus.COMPLETE);
@@ -236,9 +227,9 @@ public class CAEnrollProfile extends EnrollProfile {
// notifies updater plugins
Enumeration updaterIds = getProfileUpdaterIds();
while (updaterIds.hasMoreElements()) {
- String updaterId = (String)updaterIds.nextElement();
- IProfileUpdater updater = getProfileUpdater(updaterId);
- updater.update(request, RequestStatus.COMPLETE);
+ String updaterId = (String) updaterIds.nextElement();
+ IProfileUpdater updater = getProfileUpdater(updaterId);
+ updater.update(request, RequestStatus.COMPLETE);
}
// set value for predicate value - checking in getRule
@@ -248,4 +239,3 @@ public class CAEnrollProfile extends EnrollProfile {
request.setExtData("isEncryptionCert", "false");
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/profile/common/EnrollProfile.java b/pki/base/common/src/com/netscape/cms/profile/common/EnrollProfile.java
index 8bc6f190..f56481d2 100644
--- a/pki/base/common/src/com/netscape/cms/profile/common/EnrollProfile.java
+++ b/pki/base/common/src/com/netscape/cms/profile/common/EnrollProfile.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.common;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -99,21 +98,21 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.IRequestQueue;
import com.netscape.cmsutil.util.HMACDigest;
-
/**
* This class implements a generic enrollment profile.
- *
+ *
* @version $Revision$, $Date$
*/
-public abstract class EnrollProfile extends BasicProfile
- implements IEnrollProfile {
+public abstract class EnrollProfile extends BasicProfile
+ implements IEnrollProfile {
private final static String LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST =
- "LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST_5";
+ "LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST_5";
private final static String LOGGING_SIGNED_AUDIT_PROOF_OF_POSSESSION =
- "LOGGING_SIGNED_AUDIT_PROOF_OF_POSSESSION_2";
+ "LOGGING_SIGNED_AUDIT_PROOF_OF_POSSESSION_2";
private PKIData mCMCData;
+
public EnrollProfile() {
super();
}
@@ -134,11 +133,11 @@ public abstract class EnrollProfile extends BasicProfile
* Creates request.
*/
public IRequest[] createRequests(IProfileContext context, Locale locale)
- throws EProfileException {
+ throws EProfileException {
EnrollProfileContext ctx = (EnrollProfileContext) context;
// determine how many requests should be created
- String cert_request_type = ctx.get(CTX_CERT_REQUEST_TYPE);
+ String cert_request_type = ctx.get(CTX_CERT_REQUEST_TYPE);
String cert_request = ctx.get(CTX_CERT_REQUEST);
String is_renewal = ctx.get(CTX_RENEWAL);
Integer renewal_seq_num = 0;
@@ -168,17 +167,16 @@ public abstract class EnrollProfile extends BasicProfile
num_requests = msgs.length;
}
- // only 1 request for renewal
+ // only 1 request for renewal
if ((is_renewal != null) && (is_renewal.equals("true"))) {
num_requests = 1;
String renewal_seq_num_str = ctx.get(CTX_RENEWAL_SEQ_NUM);
if (renewal_seq_num_str != null) {
renewal_seq_num = Integer.parseInt(renewal_seq_num_str);
} else {
- renewal_seq_num =0;
+ renewal_seq_num = 0;
}
}
-
// populate requests with appropriate content
IRequest result[] = new IRequest[num_requests];
@@ -186,7 +184,7 @@ public abstract class EnrollProfile extends BasicProfile
for (int i = 0; i < num_requests; i++) {
result[i] = createEnrollmentRequest();
if ((is_renewal != null) && (is_renewal.equals("true"))) {
- result[i].setExtData(REQUEST_SEQ_NUM,renewal_seq_num);
+ result[i].setExtData(REQUEST_SEQ_NUM, renewal_seq_num);
} else {
result[i].setExtData(REQUEST_SEQ_NUM, Integer.valueOf(i));
}
@@ -211,32 +209,32 @@ public abstract class EnrollProfile extends BasicProfile
48, 92, 48, 13, 6, 9, 42, -122, 72, -122, -9, 13, 1, 1, 1, 5,
0, 3, 75, 0, 48, 72, 2, 65, 0, -65, 121, -119, -59, 105, 66,
-122, -78, -30, -64, 63, -47, 44, -48, -104, 103, -47, -108,
- 42, -38, 46, -8, 32, 49, -29, -26, -112, -29, -86,71, 24,
+ 42, -38, 46, -8, 32, 49, -29, -26, -112, -29, -86, 71, 24,
-104, 78, -31, -75, -128, 90, -92, -34, -51, -125, -13, 80, 101,
-78, 39, -119, -38, 117, 28, 67, -19, -71, -124, -85, 105, -53,
- -103, -59, -67, -38, -83, 118, 65, 2, 3, 1, 0, 1};
+ -103, -59, -67, -38, -83, 118, 65, 2, 3, 1, 0, 1 };
// default values into x509 certinfo. This thing is
// not serializable by default
try {
- info.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
- info.set(X509CertInfo.SERIAL_NUMBER,
- new CertificateSerialNumber(new BigInteger("0")));
- info.set(X509CertInfo.ISSUER,
- new CertificateIssuerName(issuerName));
+ info.set(X509CertInfo.VERSION,
+ new CertificateVersion(CertificateVersion.V3));
+ info.set(X509CertInfo.SERIAL_NUMBER,
+ new CertificateSerialNumber(new BigInteger("0")));
+ info.set(X509CertInfo.ISSUER,
+ new CertificateIssuerName(issuerName));
info.set(X509CertInfo.KEY,
- new CertificateX509Key(X509Key.parse(new DerValue(dummykey))));
- info.set(X509CertInfo.SUBJECT,
- new CertificateSubjectName(issuerName));
- info.set(X509CertInfo.VALIDITY,
- new CertificateValidity(new Date(), new Date()));
- info.set(X509CertInfo.ALGORITHM_ID,
- new CertificateAlgorithmId(
- AlgorithmId.getAlgorithmId("MD5withRSA")));
+ new CertificateX509Key(X509Key.parse(new DerValue(dummykey))));
+ info.set(X509CertInfo.SUBJECT,
+ new CertificateSubjectName(issuerName));
+ info.set(X509CertInfo.VALIDITY,
+ new CertificateValidity(new Date(), new Date()));
+ info.set(X509CertInfo.ALGORITHM_ID,
+ new CertificateAlgorithmId(
+ AlgorithmId.getAlgorithmId("MD5withRSA")));
// add default extension container
- info.set(X509CertInfo.EXTENSIONS,
- new CertificateExtensions());
+ info.set(X509CertInfo.EXTENSIONS,
+ new CertificateExtensions());
} catch (Exception e) {
// throw exception - add key to template
CMS.debug("EnrollProfile: Building X509CertInfo - " + e.toString());
@@ -246,7 +244,7 @@ public abstract class EnrollProfile extends BasicProfile
}
public IRequest createEnrollmentRequest()
- throws EProfileException {
+ throws EProfileException {
IRequest req = null;
try {
@@ -270,7 +268,7 @@ public abstract class EnrollProfile extends BasicProfile
}
public abstract void execute(IRequest request)
- throws EProfileException;
+ throws EProfileException;
/**
* Perform simple policy set assignment.
@@ -298,7 +296,7 @@ public abstract class EnrollProfile extends BasicProfile
try {
CertificateSubjectName sn = (CertificateSubjectName)
- info.get(X509CertInfo.SUBJECT);
+ info.get(X509CertInfo.SUBJECT);
return sn.toString();
} catch (Exception e) {
@@ -308,35 +306,35 @@ public abstract class EnrollProfile extends BasicProfile
}
/**
- * This method is called after the user submits the
- * request from the end-entity page.
+ * This method is called after the user submits the request from the
+ * end-entity page.
*/
public void submit(IAuthToken token, IRequest request)
- throws EDeferException, EProfileException {
+ throws EDeferException, EProfileException {
// Request Submission Logic:
//
// if (Authentication Failed) {
- // return Error
+ // return Error
+ // } else {
+ // if (No Auth Token) {
+ // queue request
// } else {
- // if (No Auth Token) {
- // queue request
- // } else {
- // process request
- // }
+ // process request
+ // }
// }
- IAuthority authority = (IAuthority)
- getAuthority();
+ IAuthority authority = (IAuthority)
+ getAuthority();
IRequestQueue queue = authority.getRequestQueue();
- // this profile queues request that is authenticated
- // by NoAuth
- try {
- queue.updateRequest(request);
- } catch (EBaseException e) {
- // save request to disk
- CMS.debug("EnrollProfile: Update request " + e.toString());
- }
+ // this profile queues request that is authenticated
+ // by NoAuth
+ try {
+ queue.updateRequest(request);
+ } catch (EBaseException e) {
+ // save request to disk
+ CMS.debug("EnrollProfile: Update request " + e.toString());
+ }
if (token == null) {
CMS.debug("EnrollProfile: auth token is null");
@@ -359,7 +357,7 @@ public abstract class EnrollProfile extends BasicProfile
}
public TaggedRequest[] parseCMC(Locale locale, String certreq)
- throws EProfileException {
+ throws EProfileException {
/* cert request must not be null */
if (certreq == null) {
CMS.debug("EnrollProfile: parseCMC() certreq null");
@@ -374,21 +372,21 @@ public abstract class EnrollProfile extends BasicProfile
try {
byte data[] = CMS.AtoB(creq);
ByteArrayInputStream cmcBlobIn =
- new ByteArrayInputStream(data);
-
+ new ByteArrayInputStream(data);
+
org.mozilla.jss.pkix.cms.ContentInfo cmcReq = (org.mozilla.jss.pkix.cms.ContentInfo)
- org.mozilla.jss.pkix.cms.ContentInfo.getTemplate().decode(cmcBlobIn);
- org.mozilla.jss.pkix.cms.SignedData cmcFullReq = (org.mozilla.jss.pkix.cms.SignedData)cmcReq.getInterpretedContent();
- org.mozilla.jss.pkix.cms.EncapsulatedContentInfo ci = cmcFullReq.getContentInfo();
+ org.mozilla.jss.pkix.cms.ContentInfo.getTemplate().decode(cmcBlobIn);
+ org.mozilla.jss.pkix.cms.SignedData cmcFullReq = (org.mozilla.jss.pkix.cms.SignedData) cmcReq.getInterpretedContent();
+ org.mozilla.jss.pkix.cms.EncapsulatedContentInfo ci = cmcFullReq.getContentInfo();
OBJECT_IDENTIFIER id = ci.getContentType();
OCTET_STRING content = ci.getContent();
-
+
ByteArrayInputStream s = new ByteArrayInputStream(content.toByteArray());
PKIData pkiData = (PKIData) (new PKIData.Template()).decode(s);
mCMCData = pkiData;
- //PKIData pkiData = (PKIData)
- // (new PKIData.Template()).decode(cmcBlobIn);
+ // PKIData pkiData = (PKIData)
+ // (new PKIData.Template()).decode(cmcBlobIn);
SEQUENCE controlSeq = pkiData.getControlSequence();
int numcontrols = controlSeq.size();
SEQUENCE reqSeq = pkiData.getReqSequence();
@@ -398,22 +396,22 @@ public abstract class EnrollProfile extends BasicProfile
if (numcontrols > 0) {
context.put("numOfControls", Integer.valueOf(numcontrols));
TaggedAttribute[] attributes = new TaggedAttribute[numcontrols];
- for (int i=0; i<numcontrols; i++) {
- attributes[i] = (TaggedAttribute)controlSeq.elementAt(i);
+ for (int i = 0; i < numcontrols; i++) {
+ attributes[i] = (TaggedAttribute) controlSeq.elementAt(i);
OBJECT_IDENTIFIER oid = attributes[i].getType();
if (oid.equals(OBJECT_IDENTIFIER.id_cmc_identityProof)) {
- boolean valid = verifyIdentityProof(attributes[i],
- reqSeq);
+ boolean valid = verifyIdentityProof(attributes[i],
+ reqSeq);
if (!valid) {
- SEQUENCE bpids = getRequestBpids(reqSeq);
+ SEQUENCE bpids = getRequestBpids(reqSeq);
context.put("identityProof", bpids);
return null;
}
} else if (oid.equals(OBJECT_IDENTIFIER.id_cmc_idPOPLinkRandom)) {
SET vals = attributes[i].getValues();
- OCTET_STRING ostr =
- (OCTET_STRING)(ASN1Util.decode(OCTET_STRING.getTemplate(),
- ASN1Util.encode(vals.elementAt(0))));
+ OCTET_STRING ostr =
+ (OCTET_STRING) (ASN1Util.decode(OCTET_STRING.getTemplate(),
+ ASN1Util.encode(vals.elementAt(0))));
randomSeed = ostr.toByteArray();
} else {
context.put(attributes[i].getType(), attributes[i]);
@@ -421,18 +419,18 @@ public abstract class EnrollProfile extends BasicProfile
}
}
}
-
+
SEQUENCE otherMsgSeq = pkiData.getOtherMsgSequence();
int numOtherMsgs = otherMsgSeq.size();
if (!context.containsKey("numOfOtherMsgs")) {
context.put("numOfOtherMsgs", Integer.valueOf(numOtherMsgs));
- for (int i=0; i<numOtherMsgs; i++) {
- OtherMsg omsg =(OtherMsg)(ASN1Util.decode(OtherMsg.getTemplate(),
- ASN1Util.encode(otherMsgSeq.elementAt(i))));
- context.put("otherMsg"+i, omsg);
+ for (int i = 0; i < numOtherMsgs; i++) {
+ OtherMsg omsg = (OtherMsg) (ASN1Util.decode(OtherMsg.getTemplate(),
+ ASN1Util.encode(otherMsgSeq.elementAt(i))));
+ context.put("otherMsg" + i, omsg);
}
}
-
+
int nummsgs = reqSeq.size();
if (nummsgs > 0) {
msgs = new TaggedRequest[reqSeq.size()];
@@ -445,7 +443,7 @@ public abstract class EnrollProfile extends BasicProfile
valid = verifyPOPLinkWitness(randomSeed, msgs[i], bpids);
if (!valid || bpids.size() > 0) {
context.put("POPLinkWitness", bpids);
- return null;
+ return null;
}
}
}
@@ -462,7 +460,7 @@ public abstract class EnrollProfile extends BasicProfile
}
private boolean verifyPOPLinkWitness(byte[] randomSeed, TaggedRequest req,
- SEQUENCE bpids) {
+ SEQUENCE bpids) {
ISharedToken tokenClass = null;
boolean sharedSecretFound = true;
String name = null;
@@ -477,15 +475,15 @@ public abstract class EnrollProfile extends BasicProfile
}
try {
- tokenClass = (ISharedToken)Class.forName(name).newInstance();
+ tokenClass = (ISharedToken) Class.forName(name).newInstance();
} catch (ClassNotFoundException e) {
- CMS.debug("EnrollProfile: Failed to find class name: "+name);
+ CMS.debug("EnrollProfile: Failed to find class name: " + name);
sharedSecretFound = false;
} catch (InstantiationException e) {
- CMS.debug("EnrollProfile: Failed to instantiate class: "+name);
+ CMS.debug("EnrollProfile: Failed to instantiate class: " + name);
sharedSecretFound = false;
} catch (IllegalAccessException e) {
- CMS.debug("EnrollProfile: Illegal access: "+name);
+ CMS.debug("EnrollProfile: Illegal access: " + name);
sharedSecretFound = false;
}
@@ -494,7 +492,7 @@ public abstract class EnrollProfile extends BasicProfile
String sharedSecret = null;
if (tokenClass != null)
sharedSecret = tokenClass.getSharedToken(mCMCData);
- if (req.getType().equals(TaggedRequest.PKCS10)) {
+ if (req.getType().equals(TaggedRequest.PKCS10)) {
TaggedCertificationRequest tcr = req.getTcr();
if (!sharedSecretFound) {
bpids.addElement(tcr.getBodyPartID());
@@ -503,25 +501,25 @@ public abstract class EnrollProfile extends BasicProfile
CertificationRequest creq = tcr.getCertificationRequest();
CertificationRequestInfo cinfo = creq.getInfo();
SET attrs = cinfo.getAttributes();
- for (int j=0; j<attrs.size(); j++) {
- Attribute pkcs10Attr = (Attribute)attrs.elementAt(j);
+ for (int j = 0; j < attrs.size(); j++) {
+ Attribute pkcs10Attr = (Attribute) attrs.elementAt(j);
if (pkcs10Attr.getType().equals(OBJECT_IDENTIFIER.id_cmc_idPOPLinkWitness)) {
SET witnessVal = pkcs10Attr.getValues();
if (witnessVal.size() > 0) {
try {
OCTET_STRING str =
- (OCTET_STRING)(ASN1Util.decode(OCTET_STRING.getTemplate(),
- ASN1Util.encode(witnessVal.elementAt(0))));
+ (OCTET_STRING) (ASN1Util.decode(OCTET_STRING.getTemplate(),
+ ASN1Util.encode(witnessVal.elementAt(0))));
bv = str.toByteArray();
return verifyDigest(sharedSecret.getBytes(),
- randomSeed, bv);
+ randomSeed, bv);
} catch (InvalidBERException ex) {
return false;
}
}
- }
+ }
}
-
+
return false;
}
} else if (req.getType().equals(TaggedRequest.CRMF)) {
@@ -535,14 +533,14 @@ public abstract class EnrollProfile extends BasicProfile
for (int i = 0; i < certReq.numControls(); i++) {
AVA ava = certReq.controlAt(i);
- if (ava.getOID().equals(OBJECT_IDENTIFIER.id_cmc_idPOPLinkWitness)) {
+ if (ava.getOID().equals(OBJECT_IDENTIFIER.id_cmc_idPOPLinkWitness)) {
ASN1Value value = ava.getValue();
ByteArrayInputStream bis = new ByteArrayInputStream(
- ASN1Util.encode(value));
+ ASN1Util.encode(value));
OCTET_STRING ostr = null;
try {
ostr = (OCTET_STRING)
- (new OCTET_STRING.Template()).decode(bis);
+ (new OCTET_STRING.Template()).decode(bis);
bv = ostr.toByteArray();
} catch (Exception e) {
bpids.addElement(reqId);
@@ -550,7 +548,7 @@ public abstract class EnrollProfile extends BasicProfile
}
boolean valid = verifyDigest(sharedSecret.getBytes(),
- randomSeed, bv);
+ randomSeed, bv);
if (!valid) {
bpids.addElement(reqId);
return valid;
@@ -569,7 +567,7 @@ public abstract class EnrollProfile extends BasicProfile
MessageDigest SHA1Digest = MessageDigest.getInstance("SHA1");
key = SHA1Digest.digest(sharedSecret);
} catch (NoSuchAlgorithmException ex) {
- CMS.debug("EnrollProfile: No such algorithm for this message digest.");
+ CMS.debug("EnrollProfile: No such algorithm for this message digest.");
return false;
}
@@ -580,7 +578,7 @@ public abstract class EnrollProfile extends BasicProfile
hmacDigest.update(text);
finalDigest = hmacDigest.digest();
} catch (NoSuchAlgorithmException ex) {
- CMS.debug("EnrollProfile: No such algorithm for this message digest.");
+ CMS.debug("EnrollProfile: No such algorithm for this message digest.");
return false;
}
@@ -589,9 +587,9 @@ public abstract class EnrollProfile extends BasicProfile
return false;
}
- for (int j=0; j<bv.length; j++) {
+ for (int j = 0; j < bv.length; j++) {
if (bv[j] != finalDigest[j]) {
- CMS.debug("EnrollProfile: The content of two HMAC digest are not the same.");
+ CMS.debug("EnrollProfile: The content of two HMAC digest are not the same.");
return false;
}
}
@@ -633,23 +631,23 @@ public abstract class EnrollProfile extends BasicProfile
else {
ISharedToken tokenClass = null;
try {
- tokenClass = (ISharedToken)Class.forName(name).newInstance();
+ tokenClass = (ISharedToken) Class.forName(name).newInstance();
} catch (ClassNotFoundException e) {
- CMS.debug("EnrollProfile: Failed to find class name: "+name);
+ CMS.debug("EnrollProfile: Failed to find class name: " + name);
return false;
} catch (InstantiationException e) {
- CMS.debug("EnrollProfile: Failed to instantiate class: "+name);
+ CMS.debug("EnrollProfile: Failed to instantiate class: " + name);
return false;
} catch (IllegalAccessException e) {
- CMS.debug("EnrollProfile: Illegal access: "+name);
+ CMS.debug("EnrollProfile: Illegal access: " + name);
return false;
}
-
+
String token = tokenClass.getSharedToken(mCMCData);
OCTET_STRING ostr = null;
try {
- ostr = (OCTET_STRING)(ASN1Util.decode(OCTET_STRING.getTemplate(),
- ASN1Util.encode(vals.elementAt(0))));
+ ostr = (OCTET_STRING) (ASN1Util.decode(OCTET_STRING.getTemplate(),
+ ASN1Util.encode(vals.elementAt(0))));
} catch (InvalidBERException e) {
CMS.debug("EnrollProfile: Failed to decode the byte value.");
return false;
@@ -662,34 +660,34 @@ public abstract class EnrollProfile extends BasicProfile
}
public void fillTaggedRequest(Locale locale, TaggedRequest tagreq, X509CertInfo info,
- IRequest req)
- throws EProfileException {
+ IRequest req)
+ throws EProfileException {
TaggedRequest.Type type = tagreq.getType();
- if (type.equals(TaggedRequest.PKCS10)) {
+ if (type.equals(TaggedRequest.PKCS10)) {
try {
- TaggedCertificationRequest tcr = tagreq.getTcr();
- CertificationRequest p10 = tcr.getCertificationRequest();
- ByteArrayOutputStream ostream = new ByteArrayOutputStream();
+ TaggedCertificationRequest tcr = tagreq.getTcr();
+ CertificationRequest p10 = tcr.getCertificationRequest();
+ ByteArrayOutputStream ostream = new ByteArrayOutputStream();
- p10.encode(ostream);
+ p10.encode(ostream);
PKCS10 pkcs10 = new PKCS10(ostream.toByteArray());
req.setExtData("bodyPartId", tcr.getBodyPartID());
fillPKCS10(locale, pkcs10, info, req);
} catch (Exception e) {
- CMS.debug("EnrollProfile: fillTaggedRequest " +
- e.toString());
+ CMS.debug("EnrollProfile: fillTaggedRequest " +
+ e.toString());
}
- } else if (type.equals(TaggedRequest.CRMF)) {
- CertReqMsg crm = tagreq.getCrm();
+ } else if (type.equals(TaggedRequest.CRMF)) {
+ CertReqMsg crm = tagreq.getCrm();
SessionContext context = SessionContext.getContext();
- Integer nums = (Integer)(context.get("numOfControls"));
+ Integer nums = (Integer) (context.get("numOfControls"));
// check if the LRA POP Witness Control attribute exists
if (nums != null && nums.intValue() > 0) {
- TaggedAttribute attr =
- (TaggedAttribute)(context.get(OBJECT_IDENTIFIER.id_cmc_lraPOPWitness));
+ TaggedAttribute attr =
+ (TaggedAttribute) (context.get(OBJECT_IDENTIFIER.id_cmc_lraPOPWitness));
if (attr != null) {
parseLRAPopWitness(locale, crm, attr);
} else {
@@ -708,42 +706,42 @@ public abstract class EnrollProfile extends BasicProfile
}
}
- private void parseLRAPopWitness(Locale locale, CertReqMsg crm,
- TaggedAttribute attr) throws EProfileException {
+ private void parseLRAPopWitness(Locale locale, CertReqMsg crm,
+ TaggedAttribute attr) throws EProfileException {
SET vals = attr.getValues();
boolean donePOP = false;
INTEGER reqId = null;
if (vals.size() > 0) {
LraPopWitness lraPop = null;
try {
- lraPop = (LraPopWitness)(ASN1Util.decode(LraPopWitness.getTemplate(),
- ASN1Util.encode(vals.elementAt(0))));
+ lraPop = (LraPopWitness) (ASN1Util.decode(LraPopWitness.getTemplate(),
+ ASN1Util.encode(vals.elementAt(0))));
} catch (InvalidBERException e) {
throw new EProfileException(
- CMS.getUserMessage(locale, "CMS_PROFILE_ENCODING_ERROR"));
+ CMS.getUserMessage(locale, "CMS_PROFILE_ENCODING_ERROR"));
}
SEQUENCE bodyIds = lraPop.getBodyIds();
reqId = crm.getCertReq().getCertReqId();
- for (int i=0; i<bodyIds.size(); i++) {
- INTEGER num = (INTEGER)(bodyIds.elementAt(i));
+ for (int i = 0; i < bodyIds.size(); i++) {
+ INTEGER num = (INTEGER) (bodyIds.elementAt(i));
if (num.toString().equals(reqId.toString())) {
donePOP = true;
- CMS.debug("EnrollProfile: skip POP for request: "+reqId.toString()+ " because LRA POP Witness control is found.");
+ CMS.debug("EnrollProfile: skip POP for request: " + reqId.toString() + " because LRA POP Witness control is found.");
break;
}
}
}
if (!donePOP) {
- CMS.debug("EnrollProfile: not skip POP for request: "+reqId.toString()+" because this request id is not part of the body list in LRA Pop witness control.");
+ CMS.debug("EnrollProfile: not skip POP for request: " + reqId.toString() + " because this request id is not part of the body list in LRA Pop witness control.");
verifyPOP(locale, crm);
}
}
public CertReqMsg[] parseCRMF(Locale locale, String certreq)
- throws EProfileException {
+ throws EProfileException {
/* cert request must not be null */
if (certreq == null) {
@@ -758,10 +756,10 @@ public abstract class EnrollProfile extends BasicProfile
try {
byte data[] = CMS.AtoB(creq);
ByteArrayInputStream crmfBlobIn =
- new ByteArrayInputStream(data);
+ new ByteArrayInputStream(data);
SEQUENCE crmfMsgs = (SEQUENCE)
- new SEQUENCE.OF_Template(new
- CertReqMsg.Template()).decode(crmfBlobIn);
+ new SEQUENCE.OF_Template(new
+ CertReqMsg.Template()).decode(crmfBlobIn);
int nummsgs = crmfMsgs.size();
if (nummsgs <= 0)
@@ -779,17 +777,17 @@ public abstract class EnrollProfile extends BasicProfile
}
private static final OBJECT_IDENTIFIER PKIARCHIVEOPTIONS_OID =
- new OBJECT_IDENTIFIER(new long[] {1, 3, 6, 1, 5, 5, 7, 5, 1, 4}
- );
+ new OBJECT_IDENTIFIER(new long[] { 1, 3, 6, 1, 5, 5, 7, 5, 1, 4 }
+ );
- protected PKIArchiveOptions getPKIArchiveOptions(AVA ava) {
- ASN1Value archVal = ava.getValue();
+ protected PKIArchiveOptions getPKIArchiveOptions(AVA ava) {
+ ASN1Value archVal = ava.getValue();
ByteArrayInputStream bis = new ByteArrayInputStream(
- ASN1Util.encode(archVal));
+ ASN1Util.encode(archVal));
PKIArchiveOptions archOpts = null;
- try {
- archOpts = (PKIArchiveOptions)
+ try {
+ archOpts = (PKIArchiveOptions)
(new PKIArchiveOptions.Template()).decode(bis);
} catch (Exception e) {
CMS.debug("EnrollProfile: getPKIArchiveOptions " + e.toString());
@@ -801,8 +799,8 @@ public abstract class EnrollProfile extends BasicProfile
ByteArrayInputStream bis = new ByteArrayInputStream(options);
PKIArchiveOptions archOpts = null;
- try {
- archOpts = (PKIArchiveOptions)
+ try {
+ archOpts = (PKIArchiveOptions)
(new PKIArchiveOptions.Template()).decode(bis);
} catch (Exception e) {
CMS.debug("EnrollProfile: toPKIArchiveOptions " + e.toString());
@@ -810,13 +808,13 @@ public abstract class EnrollProfile extends BasicProfile
return archOpts;
}
- public byte[] toByteArray(PKIArchiveOptions options) {
+ public byte[] toByteArray(PKIArchiveOptions options) {
return ASN1Util.encode(options);
}
public void fillCertReqMsg(Locale locale, CertReqMsg certReqMsg, X509CertInfo info,
- IRequest req)
- throws EProfileException {
+ IRequest req)
+ throws EProfileException {
try {
CMS.debug("Start parseCertReqMsg ");
CertRequest certReq = certReqMsg.getCertReq();
@@ -825,12 +823,12 @@ public abstract class EnrollProfile extends BasicProfile
for (int i = 0; i < certReq.numControls(); i++) {
AVA ava = certReq.controlAt(i);
- if (ava.getOID().equals(PKIARCHIVEOPTIONS_OID)) {
+ if (ava.getOID().equals(PKIARCHIVEOPTIONS_OID)) {
PKIArchiveOptions opt = getPKIArchiveOptions(ava);
- //req.set(REQUEST_ARCHIVE_OPTIONS, opt);
- req.setExtData(REQUEST_ARCHIVE_OPTIONS,
- toByteArray(opt));
+ // req.set(REQUEST_ARCHIVE_OPTIONS, opt);
+ req.setExtData(REQUEST_ARCHIVE_OPTIONS,
+ toByteArray(opt));
}
}
@@ -847,8 +845,8 @@ public abstract class EnrollProfile extends BasicProfile
key.decode(keybytes);
// XXX - kmccarth - this may simply undo the decoding above
- // but for now it's unclear whether X509Key
- // changest the format when decoding.
+ // but for now it's unclear whether X509Key
+ // changest the format when decoding.
CertificateX509Key certKey = new CertificateX509Key(key);
ByteArrayOutputStream certKeyOut = new ByteArrayOutputStream();
certKey.encode(certKeyOut);
@@ -856,7 +854,7 @@ public abstract class EnrollProfile extends BasicProfile
// parse validity
if (certTemplate.getNotBefore() != null ||
- certTemplate.getNotAfter() != null) {
+ certTemplate.getNotAfter() != null) {
CMS.debug("EnrollProfile: requested notBefore: " + certTemplate.getNotBefore());
CMS.debug("EnrollProfile: requested notAfter: " + certTemplate.getNotAfter());
CMS.debug("EnrollProfile: current CA time: " + new Date());
@@ -874,30 +872,32 @@ public abstract class EnrollProfile extends BasicProfile
if (certTemplate.hasSubject()) {
Name subjectdn = certTemplate.getSubject();
ByteArrayOutputStream subjectEncStream =
- new ByteArrayOutputStream();
+ new ByteArrayOutputStream();
subjectdn.encode(subjectEncStream);
byte[] subjectEnc = subjectEncStream.toByteArray();
X500Name subject = new X500Name(subjectEnc);
- //info.set(X509CertInfo.SUBJECT,
- // new CertificateSubjectName(subject));
+ // info.set(X509CertInfo.SUBJECT,
+ // new CertificateSubjectName(subject));
req.setExtData(REQUEST_SUBJECT_NAME,
new CertificateSubjectName(subject));
try {
- String subjectCN = subject.getCommonName();
- if (subjectCN == null) subjectCN = "";
- req.setExtData(REQUEST_SUBJECT_NAME+".cn", subjectCN);
+ String subjectCN = subject.getCommonName();
+ if (subjectCN == null)
+ subjectCN = "";
+ req.setExtData(REQUEST_SUBJECT_NAME + ".cn", subjectCN);
} catch (Exception ee) {
- req.setExtData(REQUEST_SUBJECT_NAME+".cn", "");
+ req.setExtData(REQUEST_SUBJECT_NAME + ".cn", "");
}
try {
String subjectUID = subject.getUserID();
- if (subjectUID == null) subjectUID = "";
- req.setExtData(REQUEST_SUBJECT_NAME+".uid", subjectUID);
+ if (subjectUID == null)
+ subjectUID = "";
+ req.setExtData(REQUEST_SUBJECT_NAME + ".uid", subjectUID);
} catch (Exception ee) {
- req.setExtData(REQUEST_SUBJECT_NAME+".uid", "");
+ req.setExtData(REQUEST_SUBJECT_NAME + ".uid", "");
}
}
@@ -906,11 +906,11 @@ public abstract class EnrollProfile extends BasicProfile
// try {
extensions = req.getExtDataInCertExts(REQUEST_EXTENSIONS);
- // } catch (CertificateException e) {
- // extensions = null;
+ // } catch (CertificateException e) {
+ // extensions = null;
// } catch (IOException e) {
- // extensions = null;
- // }
+ // extensions = null;
+ // }
if (certTemplate.hasExtensions()) {
// put each extension from CRMF into CertInfo.
// index by extension name, consistent with
@@ -921,10 +921,10 @@ public abstract class EnrollProfile extends BasicProfile
for (int j = 0; j < numexts; j++) {
org.mozilla.jss.pkix.cert.Extension jssext =
- certTemplate.extensionAt(j);
+ certTemplate.extensionAt(j);
boolean isCritical = jssext.getCritical();
org.mozilla.jss.asn1.OBJECT_IDENTIFIER jssoid =
- jssext.getExtnId();
+ jssext.getExtnId();
long[] numbers = jssoid.getNumbers();
int[] oidNumbers = new int[numbers.length];
@@ -932,21 +932,21 @@ public abstract class EnrollProfile extends BasicProfile
oidNumbers[k] = (int) numbers[k];
}
ObjectIdentifier oid =
- new ObjectIdentifier(oidNumbers);
+ new ObjectIdentifier(oidNumbers);
org.mozilla.jss.asn1.OCTET_STRING jssvalue =
- jssext.getExtnValue();
+ jssext.getExtnValue();
ByteArrayOutputStream jssvalueout =
- new ByteArrayOutputStream();
+ new ByteArrayOutputStream();
jssvalue.encode(jssvalueout);
byte[] extValue = jssvalueout.toByteArray();
Extension ext =
- new Extension(oid, isCritical, extValue);
+ new Extension(oid, isCritical, extValue);
extensions.parseExtension(ext);
}
- // info.set(X509CertInfo.EXTENSIONS, extensions);
+ // info.set(X509CertInfo.EXTENSIONS, extensions);
req.setExtData(REQUEST_EXTENSIONS, extensions);
}
@@ -958,14 +958,14 @@ public abstract class EnrollProfile extends BasicProfile
CMS.debug("EnrollProfile: fillCertReqMsg " + e.toString());
throw new EProfileException(
CMS.getUserMessage(locale, "CMS_PROFILE_INVALID_REQUEST"));
- // } catch (CertificateException e) {
- // CMS.debug("EnrollProfile: fillCertReqMsg " + e.toString());
- // throw new EProfileException(e.toString());
+ // } catch (CertificateException e) {
+ // CMS.debug("EnrollProfile: fillCertReqMsg " + e.toString());
+ // throw new EProfileException(e.toString());
}
}
public PKCS10 parsePKCS10(Locale locale, String certreq)
- throws EProfileException {
+ throws EProfileException {
/* cert request must not be null */
if (certreq == null) {
CMS.debug("EnrollProfile:parsePKCS10() certreq null");
@@ -996,7 +996,7 @@ public abstract class EnrollProfile extends BasicProfile
CMS.debug("EnrollProfile: parsePKCS10: use internal token");
signToken = cm.getInternalCryptoToken();
} else {
- CMS.debug("EnrollProfile: parsePKCS10: tokenName="+ tokenName);
+ CMS.debug("EnrollProfile: parsePKCS10: tokenName=" + tokenName);
signToken = cm.getTokenByName(tokenName);
}
CMS.debug("EnrollProfile: parsePKCS10 setting thread token");
@@ -1021,7 +1021,7 @@ public abstract class EnrollProfile extends BasicProfile
}
public void fillPKCS10(Locale locale, PKCS10 pkcs10, X509CertInfo info, IRequest req)
- throws EProfileException {
+ throws EProfileException {
X509Key key = pkcs10.getSubjectPublicKeyInfo();
try {
@@ -1033,18 +1033,20 @@ public abstract class EnrollProfile extends BasicProfile
req.setExtData(EnrollProfile.REQUEST_SUBJECT_NAME,
new CertificateSubjectName(pkcs10.getSubjectName()));
try {
- String subjectCN = pkcs10.getSubjectName().getCommonName();
- if (subjectCN == null) subjectCN = "";
- req.setExtData(REQUEST_SUBJECT_NAME+".cn", subjectCN);
+ String subjectCN = pkcs10.getSubjectName().getCommonName();
+ if (subjectCN == null)
+ subjectCN = "";
+ req.setExtData(REQUEST_SUBJECT_NAME + ".cn", subjectCN);
} catch (Exception ee) {
- req.setExtData(REQUEST_SUBJECT_NAME+".cn", "");
+ req.setExtData(REQUEST_SUBJECT_NAME + ".cn", "");
}
try {
String subjectUID = pkcs10.getSubjectName().getUserID();
- if (subjectUID == null) subjectUID = "";
- req.setExtData(REQUEST_SUBJECT_NAME+".uid", subjectUID);
+ if (subjectUID == null)
+ subjectUID = "";
+ req.setExtData(REQUEST_SUBJECT_NAME + ".uid", subjectUID);
} catch (Exception ee) {
- req.setExtData(REQUEST_SUBJECT_NAME+".uid", "");
+ req.setExtData(REQUEST_SUBJECT_NAME + ".uid", "");
}
info.set(X509CertInfo.KEY, certKey);
@@ -1052,11 +1054,12 @@ public abstract class EnrollProfile extends BasicProfile
PKCS10Attributes p10Attrs = pkcs10.getAttributes();
if (p10Attrs != null) {
PKCS10Attribute p10Attr = (PKCS10Attribute)
- (p10Attrs.getAttribute(CertificateExtensions.NAME));
+ (p10Attrs.getAttribute(CertificateExtensions.NAME));
if (p10Attr != null && p10Attr.getAttributeId().equals(
- PKCS9Attribute.EXTENSION_REQUEST_OID)) { CMS.debug("Found PKCS10 extension");
+ PKCS9Attribute.EXTENSION_REQUEST_OID)) {
+ CMS.debug("Found PKCS10 extension");
Extensions exts0 = (Extensions)
- (p10Attr.getAttributeValue());
+ (p10Attr.getAttributeValue());
DerOutputStream extOut = new DerOutputStream();
exts0.encode(extOut);
@@ -1070,8 +1073,8 @@ public abstract class EnrollProfile extends BasicProfile
}
} else {
CMS.debug("PKCS10 extension Not Found");
- }
- }
+ }
+ }
CMS.debug("Finish parsePKCS10 - " + pkcs10.getSubjectName());
} catch (IOException e) {
@@ -1085,60 +1088,58 @@ public abstract class EnrollProfile extends BasicProfile
}
}
+ // for netkey
+ public void fillNSNKEY(Locale locale, String sn, String skey, X509CertInfo info, IRequest req)
+ throws EProfileException {
- // for netkey
- public void fillNSNKEY(Locale locale, String sn, String skey, X509CertInfo info, IRequest req)
- throws EProfileException {
+ try {
+ // cfu - is the algorithm going to be replaced by the policy?
+ X509Key key = new X509Key();
+ key.decode(CMS.AtoB(skey));
+
+ info.set(X509CertInfo.KEY, new CertificateX509Key(key));
+ // req.set(EnrollProfile.REQUEST_SUBJECT_NAME,
+ // new CertificateSubjectName(new
+ // X500Name("CN="+sn)));
+ req.setExtData("screenname", sn);
+ // keeping "aoluid" to be backward compatible
+ req.setExtData("aoluid", sn);
+ req.setExtData("uid", sn);
+ CMS.debug("EnrollPrifile: fillNSNKEY(): uid=" + sn);
- try {
- //cfu - is the algorithm going to be replaced by the policy?
- X509Key key = new X509Key();
- key.decode(CMS.AtoB(skey));
-
- info.set(X509CertInfo.KEY, new CertificateX509Key(key));
- // req.set(EnrollProfile.REQUEST_SUBJECT_NAME,
- // new CertificateSubjectName(new
- // X500Name("CN="+sn)));
- req.setExtData("screenname", sn);
- // keeping "aoluid" to be backward compatible
- req.setExtData("aoluid", sn);
- req.setExtData("uid", sn);
- CMS.debug("EnrollPrifile: fillNSNKEY(): uid="+sn);
-
- } catch (Exception e) {
- CMS.debug("EnrollProfile: fillNSNKEY(): "+e.toString());
+ } catch (Exception e) {
+ CMS.debug("EnrollProfile: fillNSNKEY(): " + e.toString());
throw new EProfileException(
CMS.getUserMessage(locale, "CMS_PROFILE_INVALID_REQUEST"));
- }
}
+ }
- // for house key
- public void fillNSHKEY(Locale locale, String tcuid, String skey, X509CertInfo info, IRequest req)
- throws EProfileException {
+ // for house key
+ public void fillNSHKEY(Locale locale, String tcuid, String skey, X509CertInfo info, IRequest req)
+ throws EProfileException {
- try {
- //cfu - is the algorithm going to be replaced by the policy?
- X509Key key = new X509Key();
- key.decode(CMS.AtoB(skey));
+ try {
+ // cfu - is the algorithm going to be replaced by the policy?
+ X509Key key = new X509Key();
+ key.decode(CMS.AtoB(skey));
- info.set(X509CertInfo.KEY, new CertificateX509Key(key));
- // req.set(EnrollProfile.REQUEST_SUBJECT_NAME,
- // new CertificateSubjectName(new
- // X500Name("CN="+sn)));
- req.setExtData("tokencuid", tcuid);
+ info.set(X509CertInfo.KEY, new CertificateX509Key(key));
+ // req.set(EnrollProfile.REQUEST_SUBJECT_NAME,
+ // new CertificateSubjectName(new
+ // X500Name("CN="+sn)));
+ req.setExtData("tokencuid", tcuid);
- CMS.debug("EnrollPrifile: fillNSNKEY(): tokencuid="+tcuid);
+ CMS.debug("EnrollPrifile: fillNSNKEY(): tokencuid=" + tcuid);
- } catch (Exception e) {
- CMS.debug("EnrollProfile: fillNSHKEY(): "+e.toString());
+ } catch (Exception e) {
+ CMS.debug("EnrollProfile: fillNSHKEY(): " + e.toString());
throw new EProfileException(
CMS.getUserMessage(locale, "CMS_PROFILE_INVALID_REQUEST"));
- }
}
-
+ }
public DerInputStream parseKeyGen(Locale locale, String certreq)
- throws EProfileException {
+ throws EProfileException {
byte data[] = CMS.AtoB(certreq);
DerInputStream derIn = new DerInputStream(data);
@@ -1147,8 +1148,8 @@ public abstract class EnrollProfile extends BasicProfile
}
public void fillKeyGen(Locale locale, DerInputStream derIn, X509CertInfo info, IRequest req
- )
- throws EProfileException {
+ )
+ throws EProfileException {
try {
/* get SPKAC Algorithm & Signature */
@@ -1229,37 +1230,38 @@ public abstract class EnrollProfile extends BasicProfile
/**
* Populate input
* <P>
- *
+ *
* (either all "agent" profile cert requests NOT made through a connector,
- * or all "EE" profile cert requests NOT made through a connector)
+ * or all "EE" profile cert requests NOT made through a connector)
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST used when a
* profile cert request is made (before approval process)
* </ul>
+ *
* @param ctx profile context
* @param request the certificate request
* @exception EProfileException an error related to this profile has
- * occurred
+ * occurred
*/
public void populateInput(IProfileContext ctx, IRequest request)
- throws EProfileException {
+ throws EProfileException {
super.populateInput(ctx, request);
}
public void populate(IRequest request)
- throws EProfileException {
+ throws EProfileException {
super.populate(request);
}
/**
- * Passes the request to the set of constraint policies
- * that validate the request against the profile.
+ * Passes the request to the set of constraint policies that validate the
+ * request against the profile.
*/
public void validate(IRequest request)
- throws ERejectException {
+ throws ERejectException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
String auditRequesterID = auditRequesterID(request);
@@ -1272,15 +1274,15 @@ public abstract class EnrollProfile extends BasicProfile
try {
CertificateSubjectName sn = (CertificateSubjectName)
- info.get(X509CertInfo.SUBJECT);
+ info.get(X509CertInfo.SUBJECT);
// if the cert subject name is NOT MISSING, retrieve the
// actual "auditCertificateSubjectName" and "normalize" it
if (sn != null) {
subject = sn.toString();
if (subject != null) {
- // NOTE: This is ok even if the cert subject name
- // is "" (empty)!
+ // NOTE: This is ok even if the cert subject name
+ // is "" (empty)!
auditCertificateSubjectName = subject.trim();
}
}
@@ -1348,12 +1350,11 @@ public abstract class EnrollProfile extends BasicProfile
/**
* Signed Audit Log Requester ID
- *
- * This method is inherited by all extended "EnrollProfile"s,
- * and is called to obtain the "RequesterID" for
- * a signed audit log message.
+ *
+ * This method is inherited by all extended "EnrollProfile"s, and is called
+ * to obtain the "RequesterID" for a signed audit log message.
* <P>
- *
+ *
* @param request the actual request
* @return id string containing the signed audit log message RequesterID
*/
@@ -1379,12 +1380,11 @@ public abstract class EnrollProfile extends BasicProfile
/**
* Signed Audit Log Profile ID
- *
- * This method is inherited by all extended "EnrollProfile"s,
- * and is called to obtain the "ProfileID" for
- * a signed audit log message.
+ *
+ * This method is inherited by all extended "EnrollProfile"s, and is called
+ * to obtain the "ProfileID" for a signed audit log message.
* <P>
- *
+ *
* @return id string containing the signed audit log message ProfileID
*/
protected String auditProfileID() {
@@ -1405,7 +1405,7 @@ public abstract class EnrollProfile extends BasicProfile
}
public void verifyPOP(Locale locale, CertReqMsg certReqMsg)
- throws EProfileException {
+ throws EProfileException {
CMS.debug("EnrollProfile ::in verifyPOP");
String auditMessage = null;
@@ -1429,32 +1429,31 @@ public abstract class EnrollProfile extends BasicProfile
CMS.debug("POP verification using internal token");
certReqMsg.verify();
} else {
- CMS.debug("POP verification using token:"+ tokenName);
+ CMS.debug("POP verification using token:" + tokenName);
verifyToken = cm.getTokenByName(tokenName);
certReqMsg.verify(verifyToken);
}
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_PROOF_OF_POSSESSION,
- auditSubjectID,
- ILogger.SUCCESS );
- audit( auditMessage );
+ LOGGING_SIGNED_AUDIT_PROOF_OF_POSSESSION,
+ auditSubjectID,
+ ILogger.SUCCESS);
+ audit(auditMessage);
} catch (Exception e) {
- CMS.debug("Failed POP verify! "+e.toString());
+ CMS.debug("Failed POP verify! " + e.toString());
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_PROOF_OF_POSSESSION,
- auditSubjectID,
- ILogger.FAILURE );
+ LOGGING_SIGNED_AUDIT_PROOF_OF_POSSESSION,
+ auditSubjectID,
+ ILogger.FAILURE);
- audit( auditMessage );
+ audit(auditMessage);
throw new EProfileException(CMS.getUserMessage(locale,
"CMS_POP_VERIFICATION_ERROR"));
}
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/profile/common/EnrollProfileContext.java b/pki/base/common/src/com/netscape/cms/profile/common/EnrollProfileContext.java
index 199aa794..06b05a44 100644
--- a/pki/base/common/src/com/netscape/cms/profile/common/EnrollProfileContext.java
+++ b/pki/base/common/src/com/netscape/cms/profile/common/EnrollProfileContext.java
@@ -17,17 +17,15 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.common;
-
import com.netscape.certsrv.profile.IProfileContext;
-
/**
- * This class implements an enrollment profile context
- * that carries information for request creation.
- *
+ * This class implements an enrollment profile context that carries information
+ * for request creation.
+ *
* @version $Revision$, $Date$
*/
-public class EnrollProfileContext extends ProfileContext
- implements IProfileContext {
+public class EnrollProfileContext extends ProfileContext
+ implements IProfileContext {
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/common/ProfileContext.java b/pki/base/common/src/com/netscape/cms/profile/common/ProfileContext.java
index 147d9c82..7a275b1e 100644
--- a/pki/base/common/src/com/netscape/cms/profile/common/ProfileContext.java
+++ b/pki/base/common/src/com/netscape/cms/profile/common/ProfileContext.java
@@ -17,15 +17,13 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.common;
-
import java.util.Hashtable;
import com.netscape.certsrv.profile.IProfileContext;
-
/**
* This class implements the profile context.
- *
+ *
* @version $Revision$, $Date$
*/
public class ProfileContext implements IProfileContext {
diff --git a/pki/base/common/src/com/netscape/cms/profile/common/ProfilePolicy.java b/pki/base/common/src/com/netscape/cms/profile/common/ProfilePolicy.java
index a0f0ed25..7021925a 100644
--- a/pki/base/common/src/com/netscape/cms/profile/common/ProfilePolicy.java
+++ b/pki/base/common/src/com/netscape/cms/profile/common/ProfilePolicy.java
@@ -17,17 +17,14 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.common;
-
import com.netscape.certsrv.profile.IPolicyConstraint;
import com.netscape.certsrv.profile.IPolicyDefault;
import com.netscape.certsrv.profile.IProfilePolicy;
-
/**
- * This class implements a profile policy that
- * contains a default policy and a constraint
- * policy.
- *
+ * This class implements a profile policy that contains a default policy and a
+ * constraint policy.
+ *
* @version $Revision$, $Date$
*/
public class ProfilePolicy implements IProfilePolicy {
diff --git a/pki/base/common/src/com/netscape/cms/profile/common/RAEnrollProfile.java b/pki/base/common/src/com/netscape/cms/profile/common/RAEnrollProfile.java
index f82e7313..ed6e6e48 100644
--- a/pki/base/common/src/com/netscape/cms/profile/common/RAEnrollProfile.java
+++ b/pki/base/common/src/com/netscape/cms/profile/common/RAEnrollProfile.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.common;
-
import java.util.Enumeration;
import netscape.security.x509.X500Name;
@@ -35,11 +34,9 @@ import com.netscape.certsrv.request.IRequestListener;
import com.netscape.certsrv.request.IRequestQueue;
import com.netscape.certsrv.request.RequestStatus;
-
/**
- * This class implements a Registration Manager
- * enrollment profile.
- *
+ * This class implements a Registration Manager enrollment profile.
+ *
* @version $Revision$, $Date$
*/
public class RAEnrollProfile extends EnrollProfile {
@@ -49,8 +46,8 @@ public class RAEnrollProfile extends EnrollProfile {
}
public IAuthority getAuthority() {
- IAuthority authority = (IAuthority)
- CMS.getSubsystem(CMS.SUBSYSTEM_RA);
+ IAuthority authority = (IAuthority)
+ CMS.getSubsystem(CMS.SUBSYSTEM_RA);
if (authority == null)
return null;
@@ -59,15 +56,14 @@ public class RAEnrollProfile extends EnrollProfile {
public X500Name getIssuerName() {
IRegistrationAuthority ra = (IRegistrationAuthority)
- CMS.getSubsystem(CMS.SUBSYSTEM_RA);
+ CMS.getSubsystem(CMS.SUBSYSTEM_RA);
X500Name issuerName = ra.getX500Name();
return issuerName;
}
public void execute(IRequest request)
- throws EProfileException {
-
+ throws EProfileException {
if (!isEnable()) {
CMS.debug("CAEnrollProfile: Profile Not Enabled");
@@ -75,14 +71,13 @@ public class RAEnrollProfile extends EnrollProfile {
}
IRegistrationAuthority ra =
- (IRegistrationAuthority) getAuthority();
+ (IRegistrationAuthority) getAuthority();
IRAService raService = (IRAService) ra.getRAService();
if (raService == null) {
throw new EProfileException("No RA Service");
}
-
IRequestQueue queue = ra.getRequestQueue();
// send request to CA
@@ -94,13 +89,13 @@ public class RAEnrollProfile extends EnrollProfile {
} else {
caConnector.send(request);
// check response
- if (!request.isSuccess()) {
+ if (!request.isSuccess()) {
CMS.debug("RAEnrollProfile error talking to CA setting req status to SVC_PENDING");
request.setRequestStatus(RequestStatus.SVC_PENDING);
try {
- queue.updateRequest(request);
+ queue.updateRequest(request);
} catch (EBaseException e) {
CMS.debug("RAEnrollProfile: Update request " + e.toString());
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/common/ServerCertCAEnrollProfile.java b/pki/base/common/src/com/netscape/cms/profile/common/ServerCertCAEnrollProfile.java
index 4a18ff14..4cb5644b 100644
--- a/pki/base/common/src/com/netscape/cms/profile/common/ServerCertCAEnrollProfile.java
+++ b/pki/base/common/src/com/netscape/cms/profile/common/ServerCertCAEnrollProfile.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.common;
-
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.common.NameValuePairs;
@@ -28,91 +27,89 @@ import com.netscape.certsrv.profile.IProfileInput;
import com.netscape.certsrv.profile.IProfileOutput;
import com.netscape.certsrv.profile.IProfilePolicy;
-
/**
- * This class implements a Certificate Manager enrollment
- * profile for Server Certificates.
- *
+ * This class implements a Certificate Manager enrollment profile for Server
+ * Certificates.
+ *
* @version $Revision$, $Date$
*/
-public class ServerCertCAEnrollProfile extends CAEnrollProfile
- implements IProfileEx {
+public class ServerCertCAEnrollProfile extends CAEnrollProfile
+ implements IProfileEx {
/**
- * Called after initialization. It populates default
- * policies, inputs, and outputs.
+ * Called after initialization. It populates default policies, inputs, and
+ * outputs.
*/
- public void populate() throws EBaseException
- {
+ public void populate() throws EBaseException {
// create inputs
NameValuePairs inputParams1 = new NameValuePairs();
IProfileInput input1 =
- createProfileInput("i1", "certReqInputImpl", inputParams1);
+ createProfileInput("i1", "certReqInputImpl", inputParams1);
NameValuePairs inputParams2 = new NameValuePairs();
IProfileInput input2 =
- createProfileInput("i2", "submitterInfoInputImpl", inputParams2);
+ createProfileInput("i2", "submitterInfoInputImpl", inputParams2);
// create outputs
NameValuePairs outputParams1 = new NameValuePairs();
IProfileOutput output1 =
- createProfileOutput("o1", "certOutputImpl", outputParams1);
+ createProfileOutput("o1", "certOutputImpl", outputParams1);
IProfilePolicy policy1 =
- createProfilePolicy("set1", "p1",
- "userSubjectNameDefaultImpl", "noConstraintImpl");
+ createProfilePolicy("set1", "p1",
+ "userSubjectNameDefaultImpl", "noConstraintImpl");
IPolicyDefault def1 = policy1.getDefault();
IConfigStore defConfig1 = def1.getConfigStore();
IPolicyConstraint con1 = policy1.getConstraint();
IConfigStore conConfig1 = con1.getConfigStore();
IProfilePolicy policy2 =
- createProfilePolicy("set1", "p2",
- "validityDefaultImpl", "noConstraintImpl");
+ createProfilePolicy("set1", "p2",
+ "validityDefaultImpl", "noConstraintImpl");
IPolicyDefault def2 = policy2.getDefault();
IConfigStore defConfig2 = def2.getConfigStore();
- defConfig2.putString("params.range","180");
- defConfig2.putString("params.startTime","0");
+ defConfig2.putString("params.range", "180");
+ defConfig2.putString("params.startTime", "0");
IPolicyConstraint con2 = policy2.getConstraint();
IConfigStore conConfig2 = con2.getConfigStore();
IProfilePolicy policy3 =
- createProfilePolicy("set1", "p3",
- "userKeyDefaultImpl", "noConstraintImpl");
+ createProfilePolicy("set1", "p3",
+ "userKeyDefaultImpl", "noConstraintImpl");
IPolicyDefault def3 = policy3.getDefault();
IConfigStore defConfig3 = def3.getConfigStore();
- defConfig3.putString("params.keyType","RSA");
- defConfig3.putString("params.keyMinLength","512");
- defConfig3.putString("params.keyMaxLength","4096");
+ defConfig3.putString("params.keyType", "RSA");
+ defConfig3.putString("params.keyMinLength", "512");
+ defConfig3.putString("params.keyMaxLength", "4096");
IPolicyConstraint con3 = policy3.getConstraint();
IConfigStore conConfig3 = con3.getConfigStore();
IProfilePolicy policy4 =
- createProfilePolicy("set1", "p4",
- "signingAlgDefaultImpl", "noConstraintImpl");
+ createProfilePolicy("set1", "p4",
+ "signingAlgDefaultImpl", "noConstraintImpl");
IPolicyDefault def4 = policy4.getDefault();
IConfigStore defConfig4 = def4.getConfigStore();
- defConfig4.putString("params.signingAlg","-");
+ defConfig4.putString("params.signingAlg", "-");
defConfig4.putString("params.signingAlgsAllowed",
- "SHA1withRSA,SHA256withRSA,SHA512withRSA,MD5withRSA,MD2withRSA,SHA1withEC,SHA256withEC,SHA384withEC,SHA512withEC");
+ "SHA1withRSA,SHA256withRSA,SHA512withRSA,MD5withRSA,MD2withRSA,SHA1withEC,SHA256withEC,SHA384withEC,SHA512withEC");
IPolicyConstraint con4 = policy4.getConstraint();
IConfigStore conConfig4 = con4.getConfigStore();
- IProfilePolicy policy5 =
- createProfilePolicy("set1", "p5",
- "keyUsageExtDefaultImpl", "noConstraintImpl");
- IPolicyDefault def5 = policy5.getDefault();
- IConfigStore defConfig5 = def5.getConfigStore();
- defConfig5.putString("params.keyUsageCritical","true");
- defConfig5.putString("params.keyUsageCrlSign","false");
- defConfig5.putString("params.keyUsageDataEncipherment","true");
- defConfig5.putString("params.keyUsageDecipherOnly","false");
- defConfig5.putString("params.keyUsageDigitalSignature","true");
- defConfig5.putString("params.keyUsageEncipherOnly","false");
- defConfig5.putString("params.keyUsageKeyAgreement","false");
- defConfig5.putString("params.keyUsageKeyCertSign","false");
- defConfig5.putString("params.keyUsageKeyEncipherment","true");
- defConfig5.putString("params.keyUsageNonRepudiation","true");
- IPolicyConstraint con5 = policy5.getConstraint();
+ IProfilePolicy policy5 =
+ createProfilePolicy("set1", "p5",
+ "keyUsageExtDefaultImpl", "noConstraintImpl");
+ IPolicyDefault def5 = policy5.getDefault();
+ IConfigStore defConfig5 = def5.getConfigStore();
+ defConfig5.putString("params.keyUsageCritical", "true");
+ defConfig5.putString("params.keyUsageCrlSign", "false");
+ defConfig5.putString("params.keyUsageDataEncipherment", "true");
+ defConfig5.putString("params.keyUsageDecipherOnly", "false");
+ defConfig5.putString("params.keyUsageDigitalSignature", "true");
+ defConfig5.putString("params.keyUsageEncipherOnly", "false");
+ defConfig5.putString("params.keyUsageKeyAgreement", "false");
+ defConfig5.putString("params.keyUsageKeyCertSign", "false");
+ defConfig5.putString("params.keyUsageKeyEncipherment", "true");
+ defConfig5.putString("params.keyUsageNonRepudiation", "true");
+ IPolicyConstraint con5 = policy5.getConstraint();
IConfigStore conConfig5 = con5.getConfigStore();
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/common/UserCertCAEnrollProfile.java b/pki/base/common/src/com/netscape/cms/profile/common/UserCertCAEnrollProfile.java
index 7d4254bf..24e92cfa 100644
--- a/pki/base/common/src/com/netscape/cms/profile/common/UserCertCAEnrollProfile.java
+++ b/pki/base/common/src/com/netscape/cms/profile/common/UserCertCAEnrollProfile.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.common;
-
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.common.NameValuePairs;
@@ -28,94 +27,92 @@ import com.netscape.certsrv.profile.IProfileInput;
import com.netscape.certsrv.profile.IProfileOutput;
import com.netscape.certsrv.profile.IProfilePolicy;
-
/**
- * This class implements a Certificate Manager enrollment
- * profile for User Certificates.
- *
+ * This class implements a Certificate Manager enrollment profile for User
+ * Certificates.
+ *
* @version $Revision$, $Date$
*/
-public class UserCertCAEnrollProfile extends CAEnrollProfile
- implements IProfileEx {
+public class UserCertCAEnrollProfile extends CAEnrollProfile
+ implements IProfileEx {
/**
- * Called after initialization. It populates default
- * policies, inputs, and outputs.
+ * Called after initialization. It populates default policies, inputs, and
+ * outputs.
*/
- public void populate() throws EBaseException
- {
+ public void populate() throws EBaseException {
// create inputs
NameValuePairs inputParams1 = new NameValuePairs();
IProfileInput input1 =
- createProfileInput("i1", "keyGenInputImpl", inputParams1);
+ createProfileInput("i1", "keyGenInputImpl", inputParams1);
NameValuePairs inputParams2 = new NameValuePairs();
IProfileInput input2 =
- createProfileInput("i2", "subjectNameInputImpl", inputParams2);
+ createProfileInput("i2", "subjectNameInputImpl", inputParams2);
NameValuePairs inputParams3 = new NameValuePairs();
IProfileInput input3 =
- createProfileInput("i3", "submitterInfoInputImpl", inputParams2);
+ createProfileInput("i3", "submitterInfoInputImpl", inputParams2);
// create outputs
NameValuePairs outputParams1 = new NameValuePairs();
IProfileOutput output1 =
- createProfileOutput("o1", "certOutputImpl", outputParams1);
+ createProfileOutput("o1", "certOutputImpl", outputParams1);
// create policies
IProfilePolicy policy1 =
- createProfilePolicy("set1", "p1",
- "userSubjectNameDefaultImpl", "noConstraintImpl");
- IPolicyDefault def1 = policy1.getDefault();
- IConfigStore defConfig1 = def1.getConfigStore();
- IPolicyConstraint con1 = policy1.getConstraint();
+ createProfilePolicy("set1", "p1",
+ "userSubjectNameDefaultImpl", "noConstraintImpl");
+ IPolicyDefault def1 = policy1.getDefault();
+ IConfigStore defConfig1 = def1.getConfigStore();
+ IPolicyConstraint con1 = policy1.getConstraint();
IConfigStore conConfig1 = con1.getConfigStore();
IProfilePolicy policy2 =
- createProfilePolicy("set1", "p2",
- "validityDefaultImpl", "noConstraintImpl");
- IPolicyDefault def2 = policy2.getDefault();
- IConfigStore defConfig2 = def2.getConfigStore();
- defConfig2.putString("params.range","180");
- defConfig2.putString("params.startTime","0");
- IPolicyConstraint con2 = policy2.getConstraint();
+ createProfilePolicy("set1", "p2",
+ "validityDefaultImpl", "noConstraintImpl");
+ IPolicyDefault def2 = policy2.getDefault();
+ IConfigStore defConfig2 = def2.getConfigStore();
+ defConfig2.putString("params.range", "180");
+ defConfig2.putString("params.startTime", "0");
+ IPolicyConstraint con2 = policy2.getConstraint();
IConfigStore conConfig2 = con2.getConfigStore();
IProfilePolicy policy3 =
- createProfilePolicy("set1", "p3",
- "userKeyDefaultImpl", "noConstraintImpl");
- IPolicyDefault def3 = policy3.getDefault();
- IConfigStore defConfig3 = def3.getConfigStore();
- defConfig3.putString("params.keyType","RSA");
- defConfig3.putString("params.keyMinLength","512");
- defConfig3.putString("params.keyMaxLength","4096");
- IPolicyConstraint con3 = policy3.getConstraint();
+ createProfilePolicy("set1", "p3",
+ "userKeyDefaultImpl", "noConstraintImpl");
+ IPolicyDefault def3 = policy3.getDefault();
+ IConfigStore defConfig3 = def3.getConfigStore();
+ defConfig3.putString("params.keyType", "RSA");
+ defConfig3.putString("params.keyMinLength", "512");
+ defConfig3.putString("params.keyMaxLength", "4096");
+ IPolicyConstraint con3 = policy3.getConstraint();
IConfigStore conConfig3 = con3.getConfigStore();
IProfilePolicy policy4 =
- createProfilePolicy("set1", "p4",
- "signingAlgDefaultImpl", "noConstraintImpl");
- IPolicyDefault def4 = policy4.getDefault();
- IConfigStore defConfig4 = def4.getConfigStore();
- defConfig4.putString("params.signingAlg","-");
+ createProfilePolicy("set1", "p4",
+ "signingAlgDefaultImpl", "noConstraintImpl");
+ IPolicyDefault def4 = policy4.getDefault();
+ IConfigStore defConfig4 = def4.getConfigStore();
+ defConfig4.putString("params.signingAlg", "-");
defConfig4.putString("params.signingAlgsAllowed",
- "SHA1withRSA,SHA256withRSA,SHA512withRSA,MD5withRSA,MD2withRSA,SHA1withEC,SHA256withEC,SHA384withEC,SHA512withEC");
- IPolicyConstraint con4 = policy4.getConstraint();
+ "SHA1withRSA,SHA256withRSA,SHA512withRSA,MD5withRSA,MD2withRSA,SHA1withEC,SHA256withEC,SHA384withEC,SHA512withEC");
+ IPolicyConstraint con4 = policy4.getConstraint();
IConfigStore conConfig4 = con4.getConfigStore();
IProfilePolicy policy5 =
- createProfilePolicy("set1", "p5",
- "keyUsageExtDefaultImpl", "noConstraintImpl");
+ createProfilePolicy("set1", "p5",
+ "keyUsageExtDefaultImpl", "noConstraintImpl");
IPolicyDefault def5 = policy5.getDefault();
IConfigStore defConfig5 = def5.getConfigStore();
- defConfig5.putString("params.keyUsageCritical","true");
- defConfig5.putString("params.keyUsageCrlSign","false");
- defConfig5.putString("params.keyUsageDataEncipherment","false");
- defConfig5.putString("params.keyUsageDecipherOnly","false");
- defConfig5.putString("params.keyUsageDigitalSignature","true");
- defConfig5.putString("params.keyUsageEncipherOnly","false");
- defConfig5.putString("params.keyUsageKeyAgreement","false");
- defConfig5.putString("params.keyUsageKeyCertSign","false");
- defConfig5.putString("params.keyUsageKeyEncipherment","true");
- defConfig5.putString("params.keyUsageNonRepudiation","true");
+ defConfig5.putString("params.keyUsageCritical", "true");
+ defConfig5.putString("params.keyUsageCrlSign", "false");
+ defConfig5.putString("params.keyUsageDataEncipherment", "false");
+ defConfig5.putString("params.keyUsageDecipherOnly", "false");
+ defConfig5.putString("params.keyUsageDigitalSignature", "true");
+ defConfig5.putString("params.keyUsageEncipherOnly", "false");
+ defConfig5.putString("params.keyUsageKeyAgreement", "false");
+ defConfig5.putString("params.keyUsageKeyCertSign", "false");
+ defConfig5.putString("params.keyUsageKeyEncipherment", "true");
+ defConfig5.putString("params.keyUsageNonRepudiation", "true");
IPolicyConstraint con5 = policy5.getConstraint();
IConfigStore conConfig5 = con5.getConfigStore();
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/constraint/BasicConstraintsExtConstraint.java b/pki/base/common/src/com/netscape/cms/profile/constraint/BasicConstraintsExtConstraint.java
index 4e4c2f60..a196d330 100644
--- a/pki/base/common/src/com/netscape/cms/profile/constraint/BasicConstraintsExtConstraint.java
+++ b/pki/base/common/src/com/netscape/cms/profile/constraint/BasicConstraintsExtConstraint.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.constraint;
-
import java.io.IOException;
import java.util.Locale;
@@ -40,24 +39,22 @@ import com.netscape.cms.profile.def.BasicConstraintsExtDefault;
import com.netscape.cms.profile.def.NoDefault;
import com.netscape.cms.profile.def.UserExtensionDefault;
-
/**
- * This class implements the basic constraints extension constraint.
- * It checks if the basic constraint in the certificate
- * template satisfies the criteria.
- *
+ * This class implements the basic constraints extension constraint. It checks
+ * if the basic constraint in the certificate template satisfies the criteria.
+ *
* @version $Revision$, $Date$
*/
public class BasicConstraintsExtConstraint extends EnrollConstraint {
- public static final String CONFIG_CRITICAL =
- "basicConstraintsCritical";
- public static final String CONFIG_IS_CA =
- "basicConstraintsIsCA";
- public static final String CONFIG_MIN_PATH_LEN =
- "basicConstraintsMinPathLen";
- public static final String CONFIG_MAX_PATH_LEN =
- "basicConstraintsMaxPathLen";
+ public static final String CONFIG_CRITICAL =
+ "basicConstraintsCritical";
+ public static final String CONFIG_IS_CA =
+ "basicConstraintsIsCA";
+ public static final String CONFIG_MIN_PATH_LEN =
+ "basicConstraintsMinPathLen";
+ public static final String CONFIG_MAX_PATH_LEN =
+ "basicConstraintsMaxPathLen";
public BasicConstraintsExtConstraint() {
super();
@@ -71,25 +68,25 @@ public class BasicConstraintsExtConstraint extends EnrollConstraint {
* Initializes this constraint plugin.
*/
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
- if (name.equals(CONFIG_CRITICAL)) {
- return new Descriptor(IDescriptor.CHOICE, "true,false,-",
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ if (name.equals(CONFIG_CRITICAL)) {
+ return new Descriptor(IDescriptor.CHOICE, "true,false,-",
"-",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.equals(CONFIG_IS_CA)) {
- return new Descriptor(IDescriptor.CHOICE, "true,false,-",
+ return new Descriptor(IDescriptor.CHOICE, "true,false,-",
"-",
CMS.getUserMessage(locale, "CMS_PROFILE_IS_CA"));
} else if (name.equals(CONFIG_MIN_PATH_LEN)) {
- return new Descriptor(IDescriptor.INTEGER, null,
+ return new Descriptor(IDescriptor.INTEGER, null,
"-1",
CMS.getUserMessage(locale, "CMS_PROFILE_MIN_PATH_LEN"));
} else if (name.equals(CONFIG_MAX_PATH_LEN)) {
- return new Descriptor(IDescriptor.INTEGER, null,
+ return new Descriptor(IDescriptor.INTEGER, null,
"100",
CMS.getUserMessage(locale, "CMS_PROFILE_MAX_PATH_LEN"));
}
@@ -97,24 +94,23 @@ public class BasicConstraintsExtConstraint extends EnrollConstraint {
}
/**
- * Validates the request. The request is not modified
- * during the validation.
+ * Validates the request. The request is not modified during the validation.
*/
public void validate(IRequest request, X509CertInfo info)
- throws ERejectException {
+ throws ERejectException {
CertificateExtensions exts = null;
try {
BasicConstraintsExtension ext = (BasicConstraintsExtension)
- getExtension(PKIXExtensions.BasicConstraints_Id.toString(),
- info);
+ getExtension(PKIXExtensions.BasicConstraints_Id.toString(),
+ info);
if (ext == null) {
throw new ERejectException(
CMS.getUserMessage(
- getLocale(request),
- "CMS_PROFILE_EXTENSION_NOT_FOUND",
- PKIXExtensions.BasicConstraints_Id.toString()));
+ getLocale(request),
+ "CMS_PROFILE_EXTENSION_NOT_FOUND",
+ PKIXExtensions.BasicConstraints_Id.toString()));
}
// check criticality
@@ -125,10 +121,10 @@ public class BasicConstraintsExtConstraint extends EnrollConstraint {
if (critical != ext.isCritical()) {
throw new ERejectException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_CRITICAL_NOT_MATCHED"));
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_CRITICAL_NOT_MATCHED"));
}
- }
+ }
value = getConfig(CONFIG_IS_CA);
if (!isOptional(value)) {
boolean isCA = getBoolean(value);
@@ -136,10 +132,10 @@ public class BasicConstraintsExtConstraint extends EnrollConstraint {
if (isCA != extIsCA.booleanValue()) {
throw new ERejectException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_CONSTRAINT_BASIC_CONSTRAINTS_EXT_IS_CA"));
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_CONSTRAINT_BASIC_CONSTRAINTS_EXT_IS_CA"));
}
- }
+ }
value = getConfig(CONFIG_MIN_PATH_LEN);
if (!isOptional(value)) {
int pathLen = getInt(value);
@@ -148,8 +144,8 @@ public class BasicConstraintsExtConstraint extends EnrollConstraint {
if (pathLen > extPathLen.intValue()) {
CMS.debug("BasicCOnstraintsExtConstraint: pathLen=" + pathLen + " > extPathLen=" + extPathLen);
throw new ERejectException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_CONSTRAINT_BASIC_CONSTRAINTS_EXT_MIN_PATH"));
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_CONSTRAINT_BASIC_CONSTRAINTS_EXT_MIN_PATH"));
}
}
value = getConfig(CONFIG_MAX_PATH_LEN);
@@ -160,17 +156,17 @@ public class BasicConstraintsExtConstraint extends EnrollConstraint {
if (pathLen < extPathLen.intValue()) {
CMS.debug("BasicCOnstraintsExtConstraint: pathLen=" + pathLen + " < extPathLen=" + extPathLen);
throw new ERejectException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_CONSTRAINT_BASIC_CONSTRAINTS_EXT_MAX_PATH"));
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_CONSTRAINT_BASIC_CONSTRAINTS_EXT_MAX_PATH"));
}
}
} catch (IOException e) {
CMS.debug("BasicConstraintsExt: validate " + e.toString());
throw new ERejectException(
CMS.getUserMessage(
- getLocale(request),
- "CMS_PROFILE_EXTENSION_NOT_FOUND",
- PKIXExtensions.BasicConstraints_Id.toString()));
+ getLocale(request),
+ "CMS_PROFILE_EXTENSION_NOT_FOUND",
+ PKIXExtensions.BasicConstraints_Id.toString()));
}
}
@@ -182,8 +178,8 @@ public class BasicConstraintsExtConstraint extends EnrollConstraint {
getConfig(CONFIG_MAX_PATH_LEN)
};
- return CMS.getUserMessage(locale,
- "CMS_PROFILE_CONSTRAINT_BASIC_CONSTRAINTS_EXT_TEXT",
+ return CMS.getUserMessage(locale,
+ "CMS_PROFILE_CONSTRAINT_BASIC_CONSTRAINTS_EXT_TEXT",
params);
}
@@ -198,8 +194,7 @@ public class BasicConstraintsExtConstraint extends EnrollConstraint {
}
public void setConfig(String name, String value)
- throws EPropertyException {
-
+ throws EPropertyException {
if (mConfig.getSubStore("params") == null) {
CMS.debug("BasicConstraintsExt: mConfig.getSubStore is null");
@@ -208,8 +203,7 @@ public class BasicConstraintsExtConstraint extends EnrollConstraint {
CMS.debug("BasicConstraintsExt: setConfig name " + name + " value " + value);
- if(name.equals(CONFIG_MAX_PATH_LEN))
- {
+ if (name.equals(CONFIG_MAX_PATH_LEN)) {
String minPathLen = getConfig(CONFIG_MIN_PATH_LEN);
@@ -217,13 +211,12 @@ public class BasicConstraintsExtConstraint extends EnrollConstraint {
int maxLen = getInt(value);
- if(minLen >= maxLen) {
+ if (minLen >= maxLen) {
CMS.debug("BasicConstraintExt: minPathLen >= maxPathLen!");
throw new EPropertyException("bad value");
}
-
}
mConfig.getSubStore("params").putString(name, value);
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/constraint/CAEnrollConstraint.java b/pki/base/common/src/com/netscape/cms/profile/constraint/CAEnrollConstraint.java
index 9759af73..94098024 100644
--- a/pki/base/common/src/com/netscape/cms/profile/constraint/CAEnrollConstraint.java
+++ b/pki/base/common/src/com/netscape/cms/profile/constraint/CAEnrollConstraint.java
@@ -17,16 +17,13 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.constraint;
-
import netscape.security.x509.X509CertImpl;
import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.ca.ICertificateAuthority;
-
/**
- * This class represents an abstract class for CA enrollment
- * constraint.
+ * This class represents an abstract class for CA enrollment constraint.
*/
public abstract class CAEnrollConstraint extends EnrollConstraint {
@@ -42,7 +39,7 @@ public abstract class CAEnrollConstraint extends EnrollConstraint {
*/
public X509CertImpl getCACert() {
ICertificateAuthority ca = (ICertificateAuthority)
- CMS.getSubsystem(CMS.SUBSYSTEM_CA);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CA);
X509CertImpl caCert = ca.getCACert();
return caCert;
diff --git a/pki/base/common/src/com/netscape/cms/profile/constraint/CAValidityConstraint.java b/pki/base/common/src/com/netscape/cms/profile/constraint/CAValidityConstraint.java
index 4d89e739..12150a87 100644
--- a/pki/base/common/src/com/netscape/cms/profile/constraint/CAValidityConstraint.java
+++ b/pki/base/common/src/com/netscape/cms/profile/constraint/CAValidityConstraint.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.constraint;
-
import java.io.IOException;
import java.util.Date;
import java.util.Locale;
@@ -38,12 +37,10 @@ import com.netscape.cms.profile.def.NoDefault;
import com.netscape.cms.profile.def.UserValidityDefault;
import com.netscape.cms.profile.def.ValidityDefault;
-
/**
- * This class implements the validity constraint.
- * It checks if the validity in the certificate
- * template is within the CA's validity.
- *
+ * This class implements the validity constraint. It checks if the validity in
+ * the certificate template is within the CA's validity.
+ *
* @version $Revision$, $Date$
*/
public class CAValidityConstraint extends CAEnrollConstraint {
@@ -56,7 +53,7 @@ public class CAValidityConstraint extends CAEnrollConstraint {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
X509CertImpl caCert = getCACert();
@@ -65,11 +62,10 @@ public class CAValidityConstraint extends CAEnrollConstraint {
}
/**
- * Validates the request. The request is not modified
- * during the validation.
+ * Validates the request. The request is not modified during the validation.
*/
public void validate(IRequest request, X509CertInfo info)
- throws ERejectException {
+ throws ERejectException {
CMS.debug("CAValidityConstraint: validate start");
CertificateValidity v = null;
@@ -99,15 +95,15 @@ public class CAValidityConstraint extends CAEnrollConstraint {
}
if (mDefNotBefore != null) {
- CMS.debug("ValidtyConstraint: notBefore=" + notBefore +
- " defNotBefore=" + mDefNotBefore);
+ CMS.debug("ValidtyConstraint: notBefore=" + notBefore +
+ " defNotBefore=" + mDefNotBefore);
if (notBefore.before(mDefNotBefore)) {
throw new ERejectException(CMS.getUserMessage(
getLocale(request), "CMS_PROFILE_INVALID_NOT_BEFORE"));
}
}
- CMS.debug("ValidtyConstraint: notAfter=" + notAfter +
- " defNotAfter=" + mDefNotAfter);
+ CMS.debug("ValidtyConstraint: notAfter=" + notAfter +
+ " defNotAfter=" + mDefNotAfter);
if (notAfter.after(mDefNotAfter)) {
throw new ERejectException(CMS.getUserMessage(
getLocale(request), "CMS_PROFILE_INVALID_NOT_AFTER"));
@@ -122,8 +118,8 @@ public class CAValidityConstraint extends CAEnrollConstraint {
mDefNotAfter.toString()
};
- return CMS.getUserMessage(locale,
- "CMS_PROFILE_CONSTRAINT_CA_VALIDITY_CONSTRAINT_TEXT",
+ return CMS.getUserMessage(locale,
+ "CMS_PROFILE_CONSTRAINT_CA_VALIDITY_CONSTRAINT_TEXT",
params);
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/constraint/EnrollConstraint.java b/pki/base/common/src/com/netscape/cms/profile/constraint/EnrollConstraint.java
index a03eadcd..0343c35f 100644
--- a/pki/base/common/src/com/netscape/cms/profile/constraint/EnrollConstraint.java
+++ b/pki/base/common/src/com/netscape/cms/profile/constraint/EnrollConstraint.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.constraint;
-
import java.util.Enumeration;
import java.util.Locale;
import java.util.Vector;
@@ -39,10 +38,9 @@ import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
import com.netscape.cms.profile.common.EnrollProfile;
-
/**
* This class implements the generic enrollment constraint.
- *
+ *
* @version $Revision$, $Date$
*/
public abstract class EnrollConstraint implements IPolicyConstraint {
@@ -81,7 +79,7 @@ public abstract class EnrollConstraint implements IPolicyConstraint {
}
public void setConfig(String name, String value)
- throws EPropertyException {
+ throws EPropertyException {
if (mConfig.getSubStore("params") == null) {
//
} else {
@@ -105,46 +103,43 @@ public abstract class EnrollConstraint implements IPolicyConstraint {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
mConfig = config;
}
public IConfigStore getConfigStore() {
return mConfig;
- }
+ }
/**
- * Validates the request. The request is not modified
- * during the validation.
- *
+ * Validates the request. The request is not modified during the validation.
+ *
* @param request enrollment request
* @param info certificate template
- * @exception ERejectException request is rejected due
- * to violation of constraint
+ * @exception ERejectException request is rejected due to violation of
+ * constraint
*/
public abstract void validate(IRequest request, X509CertInfo info)
- throws ERejectException;
+ throws ERejectException;
/**
- * Validates the request. The request is not modified
- * during the validation.
- *
- * The current implementation of this method calls
- * into the subclass's validate(request, info)
- * method for validation checking.
- *
+ * Validates the request. The request is not modified during the validation.
+ *
+ * The current implementation of this method calls into the subclass's
+ * validate(request, info) method for validation checking.
+ *
* @param request request
- * @exception ERejectException request is rejected due
- * to violation of constraint
+ * @exception ERejectException request is rejected due to violation of
+ * constraint
*/
public void validate(IRequest request)
- throws ERejectException {
+ throws ERejectException {
String name = getClass().getName();
name = name.substring(name.lastIndexOf('.') + 1);
CMS.debug(name + ": validate start");
X509CertInfo info =
- request.getExtDataInCertInfo(EnrollProfile.REQUEST_CERTINFO);
+ request.getExtDataInCertInfo(EnrollProfile.REQUEST_CERTINFO);
validate(request, info);
diff --git a/pki/base/common/src/com/netscape/cms/profile/constraint/ExtendedKeyUsageExtConstraint.java b/pki/base/common/src/com/netscape/cms/profile/constraint/ExtendedKeyUsageExtConstraint.java
index 539f4890..47e967c7 100644
--- a/pki/base/common/src/com/netscape/cms/profile/constraint/ExtendedKeyUsageExtConstraint.java
+++ b/pki/base/common/src/com/netscape/cms/profile/constraint/ExtendedKeyUsageExtConstraint.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.constraint;
-
import java.util.Enumeration;
import java.util.Locale;
import java.util.StringTokenizer;
@@ -40,19 +39,18 @@ import com.netscape.cms.profile.def.ExtendedKeyUsageExtDefault;
import com.netscape.cms.profile.def.NoDefault;
import com.netscape.cms.profile.def.UserExtensionDefault;
-
/**
- * This class implements the extended key usage extension constraint.
- * It checks if the extended key usage extension in the certificate
- * template satisfies the criteria.
- *
+ * This class implements the extended key usage extension constraint. It checks
+ * if the extended key usage extension in the certificate template satisfies the
+ * criteria.
+ *
* @version $Revision$, $Date$
*/
public class ExtendedKeyUsageExtConstraint extends EnrollConstraint {
public static final String CONFIG_CRITICAL = "exKeyUsageCritical";
public static final String CONFIG_OIDS =
- "exKeyUsageOIDs";
+ "exKeyUsageOIDs";
public ExtendedKeyUsageExtConstraint() {
super();
@@ -61,38 +59,37 @@ public class ExtendedKeyUsageExtConstraint extends EnrollConstraint {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
- if (name.equals(CONFIG_CRITICAL)) {
- return new Descriptor(IDescriptor.CHOICE, "true,false,-",
- "-",
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ if (name.equals(CONFIG_CRITICAL)) {
+ return new Descriptor(IDescriptor.CHOICE, "true,false,-",
+ "-",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.equals(CONFIG_OIDS)) {
- return new Descriptor(IDescriptor.STRING, null,
+ return new Descriptor(IDescriptor.STRING, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_OIDS"));
- }
+ }
return null;
}
/**
- * Validates the request. The request is not modified
- * during the validation.
+ * Validates the request. The request is not modified during the validation.
*/
public void validate(IRequest request, X509CertInfo info)
- throws ERejectException {
+ throws ERejectException {
ExtendedKeyUsageExtension ext = (ExtendedKeyUsageExtension)
- getExtension(ExtendedKeyUsageExtension.OID, info);
+ getExtension(ExtendedKeyUsageExtension.OID, info);
if (ext == null) {
throw new ERejectException(
CMS.getUserMessage(
- getLocale(request),
- "CMS_PROFILE_EXTENSION_NOT_FOUND",
- ExtendedKeyUsageExtension.OID));
+ getLocale(request),
+ "CMS_PROFILE_EXTENSION_NOT_FOUND",
+ ExtendedKeyUsageExtension.OID));
}
// check criticality
@@ -104,10 +101,10 @@ public class ExtendedKeyUsageExtConstraint extends EnrollConstraint {
if (critical != ext.isCritical()) {
throw new ERejectException(
CMS.getUserMessage(
- getLocale(request),
- "CMS_PROFILE_CRITICAL_NOT_MATCHED"));
+ getLocale(request),
+ "CMS_PROFILE_CRITICAL_NOT_MATCHED"));
}
- }
+ }
// Build local cache of configured OIDs
Vector mCache = new Vector();
@@ -122,15 +119,15 @@ public class ExtendedKeyUsageExtConstraint extends EnrollConstraint {
// check OIDs
Enumeration e = ext.getOIDs();
- while (e.hasMoreElements()) {
+ while (e.hasMoreElements()) {
ObjectIdentifier oid = (ObjectIdentifier) e.nextElement();
if (!mCache.contains(oid.toString())) {
throw new ERejectException(
CMS.getUserMessage(
- getLocale(request),
- "CMS_PROFILE_OID_NOT_MATCHED",
- oid.toString()));
+ getLocale(request),
+ "CMS_PROFILE_OID_NOT_MATCHED",
+ oid.toString()));
}
}
}
@@ -141,7 +138,7 @@ public class ExtendedKeyUsageExtConstraint extends EnrollConstraint {
getConfig(CONFIG_OIDS)
};
- return CMS.getUserMessage(locale,
+ return CMS.getUserMessage(locale,
"CMS_PROFILE_CONSTRAINT_EXTENDED_KEY_EXT_TEXT",
params);
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/constraint/ExtensionConstraint.java b/pki/base/common/src/com/netscape/cms/profile/constraint/ExtensionConstraint.java
index cda51a07..9413ce9b 100644
--- a/pki/base/common/src/com/netscape/cms/profile/constraint/ExtensionConstraint.java
+++ b/pki/base/common/src/com/netscape/cms/profile/constraint/ExtensionConstraint.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.constraint;
-
import java.util.Locale;
import netscape.security.x509.Extension;
@@ -37,12 +36,10 @@ import com.netscape.cms.profile.def.EnrollExtDefault;
import com.netscape.cms.profile.def.NoDefault;
import com.netscape.cms.profile.def.UserExtensionDefault;
-
/**
- * This class implements the general extension constraint.
- * It checks if the extension in the certificate
- * template satisfies the criteria.
- *
+ * This class implements the general extension constraint. It checks if the
+ * extension in the certificate template satisfies the criteria.
+ *
* @version $Revision$, $Date$
*/
public class ExtensionConstraint extends EnrollConstraint {
@@ -57,33 +54,32 @@ public class ExtensionConstraint extends EnrollConstraint {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
public void setConfig(String name, String value)
- throws EPropertyException {
+ throws EPropertyException {
if (mConfig.getSubStore("params") == null) {
CMS.debug("ExtensionConstraint: mConfig.getSubStore is null");
} else {
CMS.debug("ExtensionConstraint: setConfig name=" + name +
- " value=" + value);
-
- if(name.equals(CONFIG_OID))
- {
- try {
- CMS.checkOID("", value);
- } catch (Exception e) {
- throw new EPropertyException(
- CMS.getUserMessage("CMS_PROFILE_PROPERTY_ERROR", value));
- }
+ " value=" + value);
+
+ if (name.equals(CONFIG_OID)) {
+ try {
+ CMS.checkOID("", value);
+ } catch (Exception e) {
+ throw new EPropertyException(
+ CMS.getUserMessage("CMS_PROFILE_PROPERTY_ERROR", value));
+ }
}
mConfig.getSubStore("params").putString(name, value);
}
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
if (name.equals(CONFIG_CRITICAL)) {
return new Descriptor(IDescriptor.CHOICE, "true,false,-",
"-",
@@ -97,34 +93,33 @@ public class ExtensionConstraint extends EnrollConstraint {
}
/**
- * Validates the request. The request is not modified
- * during the validation.
+ * Validates the request. The request is not modified during the validation.
*/
public void validate(IRequest request, X509CertInfo info)
- throws ERejectException {
+ throws ERejectException {
- Extension ext = getExtension(getConfig(CONFIG_OID), info);
+ Extension ext = getExtension(getConfig(CONFIG_OID), info);
if (ext == null) {
throw new ERejectException(
CMS.getUserMessage(
- getLocale(request),
- "CMS_PROFILE_EXTENSION_NOT_FOUND",
- getConfig(CONFIG_OID)));
+ getLocale(request),
+ "CMS_PROFILE_EXTENSION_NOT_FOUND",
+ getConfig(CONFIG_OID)));
}
- // check criticality
+ // check criticality
String value = getConfig(CONFIG_CRITICAL);
if (!isOptional(value)) {
boolean critical = getBoolean(value);
- if (critical != ext.isCritical()) {
+ if (critical != ext.isCritical()) {
throw new ERejectException(
CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_CRITICAL_NOT_MATCHED"));
+ "CMS_PROFILE_CRITICAL_NOT_MATCHED"));
}
- }
+ }
}
public String getText(Locale locale) {
@@ -133,7 +128,7 @@ public class ExtensionConstraint extends EnrollConstraint {
getConfig(CONFIG_OID)
};
- return CMS.getUserMessage(locale,
+ return CMS.getUserMessage(locale,
"CMS_PROFILE_CONSTRAINT_EXTENSION_TEXT", params);
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/constraint/KeyConstraint.java b/pki/base/common/src/com/netscape/cms/profile/constraint/KeyConstraint.java
index 56ec0adf..5bdcbd51 100644
--- a/pki/base/common/src/com/netscape/cms/profile/constraint/KeyConstraint.java
+++ b/pki/base/common/src/com/netscape/cms/profile/constraint/KeyConstraint.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.constraint;
-
import java.math.BigInteger;
import java.security.interfaces.DSAParams;
import java.util.HashMap;
@@ -44,11 +43,9 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.cms.profile.def.NoDefault;
import com.netscape.cms.profile.def.UserKeyDefault;
-
/**
- * This constraint is to check the key type and
- * key length.
- *
+ * This constraint is to check the key type and key length.
+ *
* @version $Revision$, $Date$
*/
@SuppressWarnings("serial")
@@ -57,72 +54,299 @@ public class KeyConstraint extends EnrollConstraint {
public static final String CONFIG_KEY_TYPE = "keyType"; // (EC, RSA)
public static final String CONFIG_KEY_PARAMETERS = "keyParameters";
- private static final String[] ecCurves = {"nistp256","nistp384","nistp521","sect163k1","nistk163","sect163r1","sect163r2",
- "nistb163","sect193r1","sect193r2","sect233k1","nistk233","sect233r1","nistb233","sect239k1","sect283k1","nistk283",
- "sect283r1","nistb283","sect409k1","nistk409","sect409r1","nistb409","sect571k1","nistk571","sect571r1","nistb571",
- "secp160k1","secp160r1","secp160r2","secp192k1","secp192r1","nistp192","secp224k1","secp224r1","nistp224","secp256k1",
- "secp256r1","secp384r1","secp521r1","prime192v1","prime192v2","prime192v3","prime239v1","prime239v2","prime239v3","c2pnb163v1",
- "c2pnb163v2","c2pnb163v3","c2pnb176v1","c2tnb191v1","c2tnb191v2","c2tnb191v3","c2pnb208w1","c2tnb239v1","c2tnb239v2","c2tnb239v3",
- "c2pnb272w1","c2pnb304w1","c2tnb359w1","c2pnb368w1","c2tnb431r1","secp112r1","secp112r2","secp128r1","secp128r2","sect113r1","sect113r2",
- "sect131r1","sect131r2"
+ private static final String[] ecCurves = { "nistp256", "nistp384", "nistp521", "sect163k1", "nistk163", "sect163r1", "sect163r2",
+ "nistb163", "sect193r1", "sect193r2", "sect233k1", "nistk233", "sect233r1", "nistb233", "sect239k1", "sect283k1", "nistk283",
+ "sect283r1", "nistb283", "sect409k1", "nistk409", "sect409r1", "nistb409", "sect571k1", "nistk571", "sect571r1", "nistb571",
+ "secp160k1", "secp160r1", "secp160r2", "secp192k1", "secp192r1", "nistp192", "secp224k1", "secp224r1", "nistp224", "secp256k1",
+ "secp256r1", "secp384r1", "secp521r1", "prime192v1", "prime192v2", "prime192v3", "prime239v1", "prime239v2", "prime239v3", "c2pnb163v1",
+ "c2pnb163v2", "c2pnb163v3", "c2pnb176v1", "c2tnb191v1", "c2tnb191v2", "c2tnb191v3", "c2pnb208w1", "c2tnb239v1", "c2tnb239v2", "c2tnb239v3",
+ "c2pnb272w1", "c2pnb304w1", "c2tnb359w1", "c2pnb368w1", "c2tnb431r1", "secp112r1", "secp112r2", "secp128r1", "secp128r2", "sect113r1", "sect113r2",
+ "sect131r1", "sect131r2"
};
- private final static HashMap<String,Vector> ecOIDs = new HashMap<String,Vector>();
- static
- {
- ecOIDs.put( "1.2.840.10045.3.1.7", new Vector() {{add("nistp256");add("secp256r1");}});
- ecOIDs.put( "1.3.132.0.34", new Vector() {{add("nistp384");add("secp384r1");}});
- ecOIDs.put( "1.3.132.0.35", new Vector() {{add("nistp521");add("secp521r1");}});
- ecOIDs.put( "1.3.132.0.1", new Vector() {{add("sect163k1");add("nistk163");}});
- ecOIDs.put( "1.3.132.0.2", new Vector() {{add("sect163r1");}});
- ecOIDs.put( "1.3.132.0.15", new Vector() {{add("sect163r2");add("nistb163");}});
- ecOIDs.put( "1.3.132.0.24", new Vector() {{add("sect193r1");}});
- ecOIDs.put( "1.3.132.0.25", new Vector() {{add("sect193r2");}});
- ecOIDs.put( "1.3.132.0.26", new Vector() {{add("sect233k1");add("nistk233");}});
- ecOIDs.put( "1.3.132.0.27", new Vector() {{add("sect233r1");add("nistb233");}});
- ecOIDs.put( "1.3.132.0.3", new Vector() {{add("sect239k1");}});
- ecOIDs.put( "1.3.132.0.16", new Vector() {{add("sect283k1");add("nistk283");}});
- ecOIDs.put( "1.3.132.0.17", new Vector() {{add("sect283r1");add("nistb283");}});
- ecOIDs.put( "1.3.132.0.36", new Vector() {{add("sect409k1");add("nistk409");}});
- ecOIDs.put( "1.3.132.0.37", new Vector() {{add("sect409r1");add("nistb409");}});
- ecOIDs.put( "1.3.132.0.38", new Vector() {{add("sect571k1"); add("nistk571");}});
- ecOIDs.put( "1.3.132.0.39", new Vector() {{add("sect571r1");add("nistb571");}});
- ecOIDs.put( "1.3.132.0.9", new Vector() {{add("secp160k1");}});
- ecOIDs.put( "1.3.132.0.8", new Vector() {{add("secp160r1");}});
- ecOIDs.put( "1.3.132.0.30", new Vector() {{add("secp160r2");}});
- ecOIDs.put( "1.3.132.0.31", new Vector() {{add("secp192k1");}});
- ecOIDs.put( "1.2.840.10045.3.1.1", new Vector() {{add("secp192r1");add("nistp192");add("prime192v1");}});
- ecOIDs.put( "1.3.132.0.32", new Vector() {{add("secp224k1");}});
- ecOIDs.put( "1.3.132.0.33", new Vector() {{add("secp224r1");add("nistp224");}});
- ecOIDs.put( "1.3.132.0.10", new Vector() {{add("secp256k1");}});
- ecOIDs.put( "1.2.840.10045.3.1.2",new Vector() {{add("prime192v2");}});
- ecOIDs.put( "1.2.840.10045.3.1.3",new Vector() {{add("prime192v3");}});
- ecOIDs.put( "1.2.840.10045.3.1.4",new Vector() {{add("prime239v1");}});
- ecOIDs.put( "1.2.840.10045.3.1.5",new Vector() {{add("prime239v2");}});
- ecOIDs.put( "1.2.840.10045.3.1.6",new Vector() {{add("prime239v3");}});
- ecOIDs.put( "1.2.840.10045.3.0.1", new Vector() {{add("c2pnb163v1");}});
- ecOIDs.put( "1.2.840.10045.3.0.2", new Vector() {{add("c2pnb163v2");}});
- ecOIDs.put( "1.2.840.10045.3.0.3", new Vector() {{add("c2pnb163v3");}});
- ecOIDs.put( "1.2.840.10045.3.0.4", new Vector() {{add("c2pnb176v1");}});
- ecOIDs.put( "1.2.840.10045.3.0.5", new Vector() {{add("c2tnb191v1");}});
- ecOIDs.put( "1.2.840.10045.3.0.6", new Vector() {{add("c2tnb191v2");}});
- ecOIDs.put( "1.2.840.10045.3.0.7", new Vector() {{add("c2tnb191v3");}});
- ecOIDs.put( "1.2.840.10045.3.0.10", new Vector() {{add("c2pnb208w1");}});
- ecOIDs.put( "1.2.840.10045.3.0.11", new Vector() {{add("c2tnb239v1");}});
- ecOIDs.put( "1.2.840.10045.3.0.12", new Vector() {{add("c2tnb239v2");}});
- ecOIDs.put( "1.2.840.10045.3.0.13", new Vector() {{add("c2tnb239v3");}});
- ecOIDs.put( "1.2.840.10045.3.0.16", new Vector() {{add("c2pnb272w1");}});
- ecOIDs.put( "1.2.840.10045.3.0.17", new Vector() {{add("c2pnb304w1");}});
- ecOIDs.put( "1.2.840.10045.3.0.19", new Vector() {{add("c2pnb368w1");}});
- ecOIDs.put( "1.2.840.10045.3.0.20", new Vector() {{add("c2tnb431r1");}});
- ecOIDs.put( "1.3.132.0.6", new Vector() {{add("secp112r1");}});
- ecOIDs.put( "1.3.132.0.7", new Vector() {{add("secp112r2");}});
- ecOIDs.put( "1.3.132.0.28", new Vector() {{add("secp128r1");}});
- ecOIDs.put( "1.3.132.0.29", new Vector() {{add("secp128r2");}});
- ecOIDs.put( "1.3.132.0.4", new Vector() {{add("sect113r1");}});
- ecOIDs.put( "1.3.132.0.5", new Vector() {{add("sect113r2");}});
- ecOIDs.put( "1.3.132.0.22", new Vector() {{add("sect131r1");}});
- ecOIDs.put( "1.3.132.0.23", new Vector() {{add("sect131r2");}});
+ private final static HashMap<String, Vector> ecOIDs = new HashMap<String, Vector>();
+ static {
+ ecOIDs.put("1.2.840.10045.3.1.7", new Vector() {
+ {
+ add("nistp256");
+ add("secp256r1");
+ }
+ });
+ ecOIDs.put("1.3.132.0.34", new Vector() {
+ {
+ add("nistp384");
+ add("secp384r1");
+ }
+ });
+ ecOIDs.put("1.3.132.0.35", new Vector() {
+ {
+ add("nistp521");
+ add("secp521r1");
+ }
+ });
+ ecOIDs.put("1.3.132.0.1", new Vector() {
+ {
+ add("sect163k1");
+ add("nistk163");
+ }
+ });
+ ecOIDs.put("1.3.132.0.2", new Vector() {
+ {
+ add("sect163r1");
+ }
+ });
+ ecOIDs.put("1.3.132.0.15", new Vector() {
+ {
+ add("sect163r2");
+ add("nistb163");
+ }
+ });
+ ecOIDs.put("1.3.132.0.24", new Vector() {
+ {
+ add("sect193r1");
+ }
+ });
+ ecOIDs.put("1.3.132.0.25", new Vector() {
+ {
+ add("sect193r2");
+ }
+ });
+ ecOIDs.put("1.3.132.0.26", new Vector() {
+ {
+ add("sect233k1");
+ add("nistk233");
+ }
+ });
+ ecOIDs.put("1.3.132.0.27", new Vector() {
+ {
+ add("sect233r1");
+ add("nistb233");
+ }
+ });
+ ecOIDs.put("1.3.132.0.3", new Vector() {
+ {
+ add("sect239k1");
+ }
+ });
+ ecOIDs.put("1.3.132.0.16", new Vector() {
+ {
+ add("sect283k1");
+ add("nistk283");
+ }
+ });
+ ecOIDs.put("1.3.132.0.17", new Vector() {
+ {
+ add("sect283r1");
+ add("nistb283");
+ }
+ });
+ ecOIDs.put("1.3.132.0.36", new Vector() {
+ {
+ add("sect409k1");
+ add("nistk409");
+ }
+ });
+ ecOIDs.put("1.3.132.0.37", new Vector() {
+ {
+ add("sect409r1");
+ add("nistb409");
+ }
+ });
+ ecOIDs.put("1.3.132.0.38", new Vector() {
+ {
+ add("sect571k1");
+ add("nistk571");
+ }
+ });
+ ecOIDs.put("1.3.132.0.39", new Vector() {
+ {
+ add("sect571r1");
+ add("nistb571");
+ }
+ });
+ ecOIDs.put("1.3.132.0.9", new Vector() {
+ {
+ add("secp160k1");
+ }
+ });
+ ecOIDs.put("1.3.132.0.8", new Vector() {
+ {
+ add("secp160r1");
+ }
+ });
+ ecOIDs.put("1.3.132.0.30", new Vector() {
+ {
+ add("secp160r2");
+ }
+ });
+ ecOIDs.put("1.3.132.0.31", new Vector() {
+ {
+ add("secp192k1");
+ }
+ });
+ ecOIDs.put("1.2.840.10045.3.1.1", new Vector() {
+ {
+ add("secp192r1");
+ add("nistp192");
+ add("prime192v1");
+ }
+ });
+ ecOIDs.put("1.3.132.0.32", new Vector() {
+ {
+ add("secp224k1");
+ }
+ });
+ ecOIDs.put("1.3.132.0.33", new Vector() {
+ {
+ add("secp224r1");
+ add("nistp224");
+ }
+ });
+ ecOIDs.put("1.3.132.0.10", new Vector() {
+ {
+ add("secp256k1");
+ }
+ });
+ ecOIDs.put("1.2.840.10045.3.1.2", new Vector() {
+ {
+ add("prime192v2");
+ }
+ });
+ ecOIDs.put("1.2.840.10045.3.1.3", new Vector() {
+ {
+ add("prime192v3");
+ }
+ });
+ ecOIDs.put("1.2.840.10045.3.1.4", new Vector() {
+ {
+ add("prime239v1");
+ }
+ });
+ ecOIDs.put("1.2.840.10045.3.1.5", new Vector() {
+ {
+ add("prime239v2");
+ }
+ });
+ ecOIDs.put("1.2.840.10045.3.1.6", new Vector() {
+ {
+ add("prime239v3");
+ }
+ });
+ ecOIDs.put("1.2.840.10045.3.0.1", new Vector() {
+ {
+ add("c2pnb163v1");
+ }
+ });
+ ecOIDs.put("1.2.840.10045.3.0.2", new Vector() {
+ {
+ add("c2pnb163v2");
+ }
+ });
+ ecOIDs.put("1.2.840.10045.3.0.3", new Vector() {
+ {
+ add("c2pnb163v3");
+ }
+ });
+ ecOIDs.put("1.2.840.10045.3.0.4", new Vector() {
+ {
+ add("c2pnb176v1");
+ }
+ });
+ ecOIDs.put("1.2.840.10045.3.0.5", new Vector() {
+ {
+ add("c2tnb191v1");
+ }
+ });
+ ecOIDs.put("1.2.840.10045.3.0.6", new Vector() {
+ {
+ add("c2tnb191v2");
+ }
+ });
+ ecOIDs.put("1.2.840.10045.3.0.7", new Vector() {
+ {
+ add("c2tnb191v3");
+ }
+ });
+ ecOIDs.put("1.2.840.10045.3.0.10", new Vector() {
+ {
+ add("c2pnb208w1");
+ }
+ });
+ ecOIDs.put("1.2.840.10045.3.0.11", new Vector() {
+ {
+ add("c2tnb239v1");
+ }
+ });
+ ecOIDs.put("1.2.840.10045.3.0.12", new Vector() {
+ {
+ add("c2tnb239v2");
+ }
+ });
+ ecOIDs.put("1.2.840.10045.3.0.13", new Vector() {
+ {
+ add("c2tnb239v3");
+ }
+ });
+ ecOIDs.put("1.2.840.10045.3.0.16", new Vector() {
+ {
+ add("c2pnb272w1");
+ }
+ });
+ ecOIDs.put("1.2.840.10045.3.0.17", new Vector() {
+ {
+ add("c2pnb304w1");
+ }
+ });
+ ecOIDs.put("1.2.840.10045.3.0.19", new Vector() {
+ {
+ add("c2pnb368w1");
+ }
+ });
+ ecOIDs.put("1.2.840.10045.3.0.20", new Vector() {
+ {
+ add("c2tnb431r1");
+ }
+ });
+ ecOIDs.put("1.3.132.0.6", new Vector() {
+ {
+ add("secp112r1");
+ }
+ });
+ ecOIDs.put("1.3.132.0.7", new Vector() {
+ {
+ add("secp112r2");
+ }
+ });
+ ecOIDs.put("1.3.132.0.28", new Vector() {
+ {
+ add("secp128r1");
+ }
+ });
+ ecOIDs.put("1.3.132.0.29", new Vector() {
+ {
+ add("secp128r2");
+ }
+ });
+ ecOIDs.put("1.3.132.0.4", new Vector() {
+ {
+ add("sect113r1");
+ }
+ });
+ ecOIDs.put("1.3.132.0.5", new Vector() {
+ {
+ add("sect113r2");
+ }
+ });
+ ecOIDs.put("1.3.132.0.22", new Vector() {
+ {
+ add("sect131r1");
+ }
+ });
+ ecOIDs.put("1.3.132.0.23", new Vector() {
+ {
+ add("sect131r2");
+ }
+ });
}
private static String[] cfgECCurves = null;
@@ -136,7 +360,7 @@ public class KeyConstraint extends EnrollConstraint {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
String ecNames = "";
@@ -148,32 +372,31 @@ public class KeyConstraint extends EnrollConstraint {
CMS.debug("KeyConstraint.init ecNames: " + ecNames);
if (ecNames != null && ecNames.length() != 0) {
cfgECCurves = ecNames.split(",");
- }
+ }
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
if (name.equals(CONFIG_KEY_TYPE)) {
return new Descriptor(IDescriptor.CHOICE, "-,RSA,EC",
"RSA",
CMS.getUserMessage(locale, "CMS_PROFILE_KEY_TYPE"));
- } else if (name.equals(CONFIG_KEY_PARAMETERS)) {
- return new Descriptor(IDescriptor.STRING,null,"",
- CMS.getUserMessage(locale,"CMS_PROFILE_KEY_PARAMETERS"));
+ } else if (name.equals(CONFIG_KEY_PARAMETERS)) {
+ return new Descriptor(IDescriptor.STRING, null, "",
+ CMS.getUserMessage(locale, "CMS_PROFILE_KEY_PARAMETERS"));
}
return null;
}
/**
- * Validates the request. The request is not modified
- * during the validation.
+ * Validates the request. The request is not modified during the validation.
*/
public void validate(IRequest request, X509CertInfo info)
- throws ERejectException {
+ throws ERejectException {
try {
CertificateX509Key infokey = (CertificateX509Key)
- info.get(X509CertInfo.KEY);
- X509Key key = (X509Key) infokey.get(CertificateX509Key.KEY);
+ info.get(X509CertInfo.KEY);
+ X509Key key = (X509Key) infokey.get(CertificateX509Key.KEY);
String alg = key.getAlgorithmId().getName().toUpperCase();
String value = getConfig(CONFIG_KEY_TYPE);
@@ -183,27 +406,27 @@ public class KeyConstraint extends EnrollConstraint {
if (!alg.equals(value)) {
throw new ERejectException(
CMS.getUserMessage(
- getLocale(request),
- "CMS_PROFILE_KEY_TYPE_NOT_MATCHED",
- value));
+ getLocale(request),
+ "CMS_PROFILE_KEY_TYPE_NOT_MATCHED",
+ value));
}
}
int keySize = 0;
String ecCurve = "";
- if (alg.equals("RSA")) {
+ if (alg.equals("RSA")) {
keySize = getRSAKeyLen(key);
- } else if (alg.equals("DSA")) {
+ } else if (alg.equals("DSA")) {
keySize = getDSAKeyLen(key);
- } else if (alg.equals("EC")) {
- //EC key case.
+ } else if (alg.equals("EC")) {
+ // EC key case.
} else {
- throw new ERejectException(
+ throw new ERejectException(
CMS.getUserMessage(
- getLocale(request),
- "CMS_PROFILE_INVALID_KEY_TYPE",
- alg));
+ getLocale(request),
+ "CMS_PROFILE_INVALID_KEY_TYPE",
+ alg));
}
value = getConfig(CONFIG_KEY_PARAMETERS);
@@ -214,26 +437,26 @@ public class KeyConstraint extends EnrollConstraint {
if (!alg.equals(keyType) && !isOptional(keyType)) {
throw new ERejectException(
CMS.getUserMessage(
- getLocale(request),
- "CMS_PROFILE_KEY_PARAMS_NOT_MATCHED",
- value));
+ getLocale(request),
+ "CMS_PROFILE_KEY_PARAMS_NOT_MATCHED",
+ value));
}
AlgorithmId algid = key.getAlgorithmId();
CMS.debug("algId: " + algid);
- //Get raw string representation of alg parameters, will give
- //us the curve OID.
+ // Get raw string representation of alg parameters, will give
+ // us the curve OID.
- String params = null;
+ String params = null;
if (algid != null) {
params = algid.getParametersString();
}
if (params.startsWith("OID.")) {
params = params.substring(4);
- }
+ }
CMS.debug("EC key OID: " + params);
Vector vect = ecOIDs.get(params);
@@ -244,9 +467,10 @@ public class KeyConstraint extends EnrollConstraint {
CMS.debug("vect: " + vect.toString());
if (!isOptional(keyType)) {
- //Check the curve parameters only if explicit ECC or not optional
- for (int i = 0 ; i < keyParams.length ; i ++) {
- String ecParam = keyParams[i];
+ // Check the curve parameters only if explicit ECC or
+ // not optional
+ for (int i = 0; i < keyParams.length; i++) {
+ String ecParam = keyParams[i];
CMS.debug("keyParams[i]: " + i + " param: " + ecParam);
if (vect.contains(ecParam)) {
curveFound = true;
@@ -260,21 +484,21 @@ public class KeyConstraint extends EnrollConstraint {
}
if (!curveFound) {
- CMS.debug("KeyConstraint.validate: EC key constrainst failed.");
+ CMS.debug("KeyConstraint.validate: EC key constrainst failed.");
throw new ERejectException(
CMS.getUserMessage(
- getLocale(request),
- "CMS_PROFILE_KEY_PARAMS_NOT_MATCHED",
- value));
+ getLocale(request),
+ "CMS_PROFILE_KEY_PARAMS_NOT_MATCHED",
+ value));
}
- } else {
- if ( !arrayContainsString(keyParams,Integer.toString(keySize))) {
- throw new ERejectException(
+ } else {
+ if (!arrayContainsString(keyParams, Integer.toString(keySize))) {
+ throw new ERejectException(
CMS.getUserMessage(
- getLocale(request),
- "CMS_PROFILE_KEY_PARAMS_NOT_MATCHED",
- value));
+ getLocale(request),
+ "CMS_PROFILE_KEY_PARAMS_NOT_MATCHED",
+ value));
}
CMS.debug("KeyConstraint.validate: RSA key contraints passed.");
}
@@ -320,7 +544,7 @@ public class KeyConstraint extends EnrollConstraint {
getConfig(CONFIG_KEY_PARAMETERS)
};
- return CMS.getUserMessage(locale,
+ return CMS.getUserMessage(locale,
"CMS_PROFILE_CONSTRAINT_KEY_TEXT", params);
}
@@ -333,27 +557,27 @@ public class KeyConstraint extends EnrollConstraint {
}
public void setConfig(String name, String value)
- throws EPropertyException {
+ throws EPropertyException {
CMS.debug("KeyConstraint.setConfig name: " + name + " value: " + value);
- //establish keyType, we don't know which order these params will arrive
+ // establish keyType, we don't know which order these params will arrive
if (name.equals(CONFIG_KEY_TYPE)) {
keyType = value;
- if(keyParams.equals(""))
- return;
+ if (keyParams.equals(""))
+ return;
}
-
- //establish keyParams
+
+ // establish keyParams
if (name.equals(CONFIG_KEY_PARAMETERS)) {
CMS.debug("establish keyParams: " + value);
keyParams = value;
- if(keyType.equals(""))
+ if (keyType.equals(""))
return;
}
- // All the params we need for validation have been collected,
+ // All the params we need for validation have been collected,
// we don't know which order they will show up
- if (keyType.length() > 0 && keyParams.length() > 0) {
+ if (keyType.length() > 0 && keyParams.length() > 0) {
String[] params = keyParams.split(",");
boolean isECCurve = false;
int keySize = 0;
@@ -361,48 +585,50 @@ public class KeyConstraint extends EnrollConstraint {
for (int i = 0; i < params.length; i++) {
if (keyType.equals("EC")) {
if (cfgECCurves == null) {
- //Use the static array as a backup if the config values are not present.
- isECCurve = arrayContainsString(ecCurves,params[i]);
+ // Use the static array as a backup if the config values
+ // are not present.
+ isECCurve = arrayContainsString(ecCurves, params[i]);
} else {
- isECCurve = arrayContainsString(cfgECCurves,params[i]);
+ isECCurve = arrayContainsString(cfgECCurves, params[i]);
}
- if (isECCurve == false) { //Not a valid EC curve throw exception.
+ if (isECCurve == false) { // Not a valid EC curve throw
+ // exception.
keyType = "";
keyParams = "";
throw new EPropertyException(CMS.getUserMessage(
- "CMS_INVALID_PROPERTY", name));
+ "CMS_INVALID_PROPERTY", name));
}
- } else {
+ } else {
try {
keySize = Integer.parseInt(params[i]);
} catch (Exception e) {
keySize = 0;
}
- if (keySize <= 0) {
+ if (keySize <= 0) {
keyType = "";
keyParams = "";
throw new EPropertyException(CMS.getUserMessage(
- "CMS_INVALID_PROPERTY", name));
+ "CMS_INVALID_PROPERTY", name));
}
}
}
- }
- //Actually set the configuration in the profile
- super.setConfig(CONFIG_KEY_TYPE, keyType);
- super.setConfig(CONFIG_KEY_PARAMETERS, keyParams);
+ }
+ // Actually set the configuration in the profile
+ super.setConfig(CONFIG_KEY_TYPE, keyType);
+ super.setConfig(CONFIG_KEY_PARAMETERS, keyParams);
- //Reset the vars for next round.
- keyType = "";
- keyParams = "";
+ // Reset the vars for next round.
+ keyType = "";
+ keyParams = "";
}
private boolean arrayContainsString(String[] array, String value) {
if (array == null || value == null) {
- return false;
- }
+ return false;
+ }
- for (int i = 0 ; i < array.length; i++) {
+ for (int i = 0; i < array.length; i++) {
if (array[i].equals(value)) {
return true;
}
@@ -411,4 +637,3 @@ public class KeyConstraint extends EnrollConstraint {
return false;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/profile/constraint/KeyUsageExtConstraint.java b/pki/base/common/src/com/netscape/cms/profile/constraint/KeyUsageExtConstraint.java
index 4a483b43..fac28bf9 100644
--- a/pki/base/common/src/com/netscape/cms/profile/constraint/KeyUsageExtConstraint.java
+++ b/pki/base/common/src/com/netscape/cms/profile/constraint/KeyUsageExtConstraint.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.constraint;
-
import java.util.Locale;
import netscape.security.x509.KeyUsageExtension;
@@ -37,25 +36,23 @@ import com.netscape.cms.profile.def.KeyUsageExtDefault;
import com.netscape.cms.profile.def.NoDefault;
import com.netscape.cms.profile.def.UserExtensionDefault;
-
/**
- * This class implements the key usage extension constraint.
- * It checks if the key usage constraint in the certificate
- * template satisfies the criteria.
- *
+ * This class implements the key usage extension constraint. It checks if the
+ * key usage constraint in the certificate template satisfies the criteria.
+ *
* @version $Revision$, $Date$
*/
public class KeyUsageExtConstraint extends EnrollConstraint {
public static final String CONFIG_CRITICAL = "keyUsageCritical";
public static final String CONFIG_DIGITAL_SIGNATURE =
- "keyUsageDigitalSignature";
+ "keyUsageDigitalSignature";
public static final String CONFIG_NON_REPUDIATION =
- "keyUsageNonRepudiation";
+ "keyUsageNonRepudiation";
public static final String CONFIG_KEY_ENCIPHERMENT =
- "keyUsageKeyEncipherment";
+ "keyUsageKeyEncipherment";
public static final String CONFIG_DATA_ENCIPHERMENT =
- "keyUsageDataEncipherment";
+ "keyUsageDataEncipherment";
public static final String CONFIG_KEY_AGREEMENT = "keyUsageKeyAgreement";
public static final String CONFIG_KEY_CERTSIGN = "keyUsageKeyCertSign";
public static final String CONFIG_CRL_SIGN = "keyUsageCrlSign";
@@ -77,12 +74,12 @@ public class KeyUsageExtConstraint extends EnrollConstraint {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
if (name.equals(CONFIG_CRITICAL)) {
return new Descriptor(IDescriptor.CHOICE, "true,false,-",
"-",
@@ -134,20 +131,19 @@ public class KeyUsageExtConstraint extends EnrollConstraint {
}
/**
- * Validates the request. The request is not modified
- * during the validation.
+ * Validates the request. The request is not modified during the validation.
*/
public void validate(IRequest request, X509CertInfo info)
- throws ERejectException {
- KeyUsageExtension ext = (KeyUsageExtension)
- getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
+ throws ERejectException {
+ KeyUsageExtension ext = (KeyUsageExtension)
+ getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
if (ext == null) {
throw new ERejectException(
CMS.getUserMessage(
- getLocale(request),
- "CMS_PROFILE_EXTENSION_NOT_FOUND",
- PKIXExtensions.KeyUsage_Id.toString()));
+ getLocale(request),
+ "CMS_PROFILE_EXTENSION_NOT_FOUND",
+ PKIXExtensions.KeyUsage_Id.toString()));
}
boolean[] bits = ext.getBits();
@@ -156,10 +152,10 @@ public class KeyUsageExtConstraint extends EnrollConstraint {
if (!isOptional(value)) {
boolean critical = getBoolean(value);
- if (critical != ext.isCritical()) {
- throw new ERejectException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_CRITICAL_NOT_MATCHED"));
+ if (critical != ext.isCritical()) {
+ throw new ERejectException(
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_CRITICAL_NOT_MATCHED"));
}
}
value = getConfig(CONFIG_DIGITAL_SIGNATURE);
@@ -167,99 +163,99 @@ public class KeyUsageExtConstraint extends EnrollConstraint {
boolean bit = getBoolean(value);
if (bit != isSet(bits, 0)) {
- throw new ERejectException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_DIGITAL_SIGNATURE_NOT_MATCHED",
- value));
- }
+ throw new ERejectException(
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_DIGITAL_SIGNATURE_NOT_MATCHED",
+ value));
+ }
}
value = getConfig(CONFIG_NON_REPUDIATION);
if (!isOptional(value)) {
boolean bit = getBoolean(value);
if (bit != isSet(bits, 1)) {
- throw new ERejectException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_NON_REPUDIATION_NOT_MATCHED",
- value));
- }
+ throw new ERejectException(
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_NON_REPUDIATION_NOT_MATCHED",
+ value));
+ }
}
value = getConfig(CONFIG_KEY_ENCIPHERMENT);
if (!isOptional(value)) {
boolean bit = getBoolean(value);
if (bit != isSet(bits, 2)) {
- throw new ERejectException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_KEY_ENCIPHERMENT_NOT_MATCHED",
- value));
- }
+ throw new ERejectException(
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_KEY_ENCIPHERMENT_NOT_MATCHED",
+ value));
+ }
}
value = getConfig(CONFIG_DATA_ENCIPHERMENT);
if (!isOptional(value)) {
boolean bit = getBoolean(value);
if (bit != isSet(bits, 3)) {
- throw new ERejectException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_DATA_ENCIPHERMENT_NOT_MATCHED",
- value));
- }
+ throw new ERejectException(
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_DATA_ENCIPHERMENT_NOT_MATCHED",
+ value));
+ }
}
value = getConfig(CONFIG_KEY_AGREEMENT);
if (!isOptional(value)) {
boolean bit = getBoolean(value);
if (bit != isSet(bits, 4)) {
- throw new ERejectException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_KEY_AGREEMENT_NOT_MATCHED",
- value));
- }
+ throw new ERejectException(
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_KEY_AGREEMENT_NOT_MATCHED",
+ value));
+ }
}
value = getConfig(CONFIG_KEY_CERTSIGN);
if (!isOptional(value)) {
boolean bit = getBoolean(value);
if (bit != isSet(bits, 5)) {
- throw new ERejectException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_KEY_CERTSIGN_NOT_MATCHED",
- value));
- }
+ throw new ERejectException(
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_KEY_CERTSIGN_NOT_MATCHED",
+ value));
+ }
}
value = getConfig(CONFIG_CRL_SIGN);
if (!isOptional(value)) {
boolean bit = getBoolean(value);
if (bit != isSet(bits, 6)) {
- throw new ERejectException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_CRL_SIGN_NOT_MATCHED",
- value));
- }
+ throw new ERejectException(
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_CRL_SIGN_NOT_MATCHED",
+ value));
+ }
}
value = getConfig(CONFIG_ENCIPHER_ONLY);
if (!isOptional(value)) {
boolean bit = getBoolean(value);
if (bit != isSet(bits, 7)) {
- throw new ERejectException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_ENCIPHER_ONLY_NOT_MATCHED",
- value));
- }
+ throw new ERejectException(
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_ENCIPHER_ONLY_NOT_MATCHED",
+ value));
+ }
}
value = getConfig(CONFIG_DECIPHER_ONLY);
if (!isOptional(value)) {
boolean bit = getBoolean(value);
if (bit != isSet(bits, 8)) {
- throw new ERejectException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_DECIPHER_ONLY_NOT_MATCHED",
- value));
- }
+ throw new ERejectException(
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_DECIPHER_ONLY_NOT_MATCHED",
+ value));
+ }
}
}
@@ -277,7 +273,7 @@ public class KeyUsageExtConstraint extends EnrollConstraint {
getConfig(CONFIG_DECIPHER_ONLY)
};
- return CMS.getUserMessage(locale,
+ return CMS.getUserMessage(locale,
"CMS_PROFILE_CONSTRAINT_KEY_USAGE_EXT_TEXT", params);
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/constraint/NSCertTypeExtConstraint.java b/pki/base/common/src/com/netscape/cms/profile/constraint/NSCertTypeExtConstraint.java
index fe20b766..a49152df 100644
--- a/pki/base/common/src/com/netscape/cms/profile/constraint/NSCertTypeExtConstraint.java
+++ b/pki/base/common/src/com/netscape/cms/profile/constraint/NSCertTypeExtConstraint.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.constraint;
-
import java.util.Locale;
import netscape.security.extensions.NSCertTypeExtension;
@@ -36,12 +35,11 @@ import com.netscape.cms.profile.def.NSCertTypeExtDefault;
import com.netscape.cms.profile.def.NoDefault;
import com.netscape.cms.profile.def.UserExtensionDefault;
-
/**
- * This class implements the Netscape certificate type extension constraint.
- * It checks if the Netscape certificate type extension in the certificate
- * template satisfies the criteria.
- *
+ * This class implements the Netscape certificate type extension constraint. It
+ * checks if the Netscape certificate type extension in the certificate template
+ * satisfies the criteria.
+ *
* @version $Revision$, $Date$
*/
public class NSCertTypeExtConstraint extends EnrollConstraint {
@@ -68,11 +66,11 @@ public class NSCertTypeExtConstraint extends EnrollConstraint {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
if (name.equals(CONFIG_CRITICAL)) {
return new Descriptor(IDescriptor.CHOICE, "true,false,-",
"-",
@@ -104,27 +102,26 @@ public class NSCertTypeExtConstraint extends EnrollConstraint {
} else if (name.equals(CONFIG_OBJECT_SIGNING_CA)) {
return new Descriptor(IDescriptor.CHOICE, "true,false,-",
"-",
- CMS.getUserMessage(locale,
- "CMS_PROFILE_OBJECT_SIGNING_CA"));
+ CMS.getUserMessage(locale,
+ "CMS_PROFILE_OBJECT_SIGNING_CA"));
}
return null;
}
/**
- * Validates the request. The request is not modified
- * during the validation.
+ * Validates the request. The request is not modified during the validation.
*/
public void validate(IRequest request, X509CertInfo info)
- throws ERejectException {
+ throws ERejectException {
NSCertTypeExtension ext = (NSCertTypeExtension)
- getExtension(NSCertTypeExtension.CertType_Id.toString(), info);
+ getExtension(NSCertTypeExtension.CertType_Id.toString(), info);
if (ext == null) {
throw new ERejectException(
CMS.getUserMessage(
- getLocale(request),
- "CMS_PROFILE_EXTENSION_NOT_FOUND",
- NSCertTypeExtension.CertType_Id.toString()));
+ getLocale(request),
+ "CMS_PROFILE_EXTENSION_NOT_FOUND",
+ NSCertTypeExtension.CertType_Id.toString()));
}
String value = getConfig(CONFIG_CRITICAL);
@@ -132,10 +129,10 @@ public class NSCertTypeExtConstraint extends EnrollConstraint {
if (!isOptional(value)) {
boolean critical = getBoolean(value);
- if (critical != ext.isCritical()) {
- throw new ERejectException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_CRITICAL_NOT_MATCHED"));
+ if (critical != ext.isCritical()) {
+ throw new ERejectException(
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_CRITICAL_NOT_MATCHED"));
}
}
value = getConfig(CONFIG_SSL_CLIENT);
@@ -143,10 +140,10 @@ public class NSCertTypeExtConstraint extends EnrollConstraint {
boolean bit = getBoolean(value);
if (bit != ext.isSet(0)) {
- throw new ERejectException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_SSL_CLIENT_NOT_MATCHED",
- value));
+ throw new ERejectException(
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_SSL_CLIENT_NOT_MATCHED",
+ value));
}
}
value = getConfig(CONFIG_SSL_SERVER);
@@ -154,10 +151,10 @@ public class NSCertTypeExtConstraint extends EnrollConstraint {
boolean bit = getBoolean(value);
if (bit != ext.isSet(1)) {
- throw new ERejectException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_SSL_SERVER_NOT_MATCHED",
- value));
+ throw new ERejectException(
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_SSL_SERVER_NOT_MATCHED",
+ value));
}
}
value = getConfig(CONFIG_EMAIL);
@@ -165,10 +162,10 @@ public class NSCertTypeExtConstraint extends EnrollConstraint {
boolean bit = getBoolean(value);
if (bit != ext.isSet(2)) {
- throw new ERejectException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_EMAIL_NOT_MATCHED",
- value));
+ throw new ERejectException(
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_EMAIL_NOT_MATCHED",
+ value));
}
}
value = getConfig(CONFIG_OBJECT_SIGNING);
@@ -176,10 +173,10 @@ public class NSCertTypeExtConstraint extends EnrollConstraint {
boolean bit = getBoolean(value);
if (bit != ext.isSet(3)) {
- throw new ERejectException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_OBJECT_SIGNING_NOT_MATCHED",
- value));
+ throw new ERejectException(
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_OBJECT_SIGNING_NOT_MATCHED",
+ value));
}
}
value = getConfig(CONFIG_SSL_CA);
@@ -187,10 +184,10 @@ public class NSCertTypeExtConstraint extends EnrollConstraint {
boolean bit = getBoolean(value);
if (bit != ext.isSet(4)) {
- throw new ERejectException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_SSL_CA_NOT_MATCHED",
- value));
+ throw new ERejectException(
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_SSL_CA_NOT_MATCHED",
+ value));
}
}
value = getConfig(CONFIG_EMAIL_CA);
@@ -198,10 +195,10 @@ public class NSCertTypeExtConstraint extends EnrollConstraint {
boolean bit = getBoolean(value);
if (bit != ext.isSet(5)) {
- throw new ERejectException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_EMAIL_CA_NOT_MATCHED",
- value));
+ throw new ERejectException(
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_EMAIL_CA_NOT_MATCHED",
+ value));
}
}
value = getConfig(CONFIG_OBJECT_SIGNING_CA);
@@ -209,10 +206,10 @@ public class NSCertTypeExtConstraint extends EnrollConstraint {
boolean bit = getBoolean(value);
if (bit != ext.isSet(6)) {
- throw new ERejectException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_OBJECT_SIGNING_CA_NOT_MATCHED",
- value));
+ throw new ERejectException(
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_OBJECT_SIGNING_CA_NOT_MATCHED",
+ value));
}
}
}
@@ -229,7 +226,7 @@ public class NSCertTypeExtConstraint extends EnrollConstraint {
getConfig(CONFIG_OBJECT_SIGNING_CA)
};
- return CMS.getUserMessage(locale,
+ return CMS.getUserMessage(locale,
"CMS_PROFILE_CONSTRAINT_NS_CERT_EXT_TEXT", params);
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/constraint/NoConstraint.java b/pki/base/common/src/com/netscape/cms/profile/constraint/NoConstraint.java
index 108c32b1..01eeefca 100644
--- a/pki/base/common/src/com/netscape/cms/profile/constraint/NoConstraint.java
+++ b/pki/base/common/src/com/netscape/cms/profile/constraint/NoConstraint.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.constraint;
-
import java.util.Enumeration;
import java.util.Locale;
import java.util.Vector;
@@ -34,17 +33,16 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
* This class implements no constraint.
- *
+ *
* @version $Revision$, $Date$
*/
public class NoConstraint implements IPolicyConstraint {
public static final String CONFIG_NAME = "name";
- private IConfigStore mConfig = null;
+ private IConfigStore mConfig = null;
private Vector mNames = new Vector();
public Enumeration getConfigNames() {
@@ -56,7 +54,7 @@ public class NoConstraint implements IPolicyConstraint {
}
public void setConfig(String name, String value)
- throws EPropertyException {
+ throws EPropertyException {
}
public String getConfig(String name) {
@@ -68,7 +66,7 @@ public class NoConstraint implements IPolicyConstraint {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
mConfig = config;
}
@@ -77,15 +75,14 @@ public class NoConstraint implements IPolicyConstraint {
}
/**
- * Validates the request. The request is not modified
- * during the validation.
+ * Validates the request. The request is not modified during the validation.
*/
public void validate(IRequest request)
- throws ERejectException {
+ throws ERejectException {
}
public String getText(Locale locale) {
- return CMS.getUserMessage(locale,
+ return CMS.getUserMessage(locale,
"CMS_PROFILE_CONSTRAINT_NO_CONSTRAINT_TEXT");
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/constraint/RenewGracePeriodConstraint.java b/pki/base/common/src/com/netscape/cms/profile/constraint/RenewGracePeriodConstraint.java
index 91d5a46a..b41e1b2e 100644
--- a/pki/base/common/src/com/netscape/cms/profile/constraint/RenewGracePeriodConstraint.java
+++ b/pki/base/common/src/com/netscape/cms/profile/constraint/RenewGracePeriodConstraint.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.constraint;
-
import java.math.BigInteger;
import java.util.Date;
import java.util.Locale;
@@ -36,17 +35,16 @@ import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
import com.netscape.cms.profile.def.NoDefault;
-
/**
- * This class supports renewal grace period, which has two
- * parameters: graceBefore and graceAfter
- *
+ * This class supports renewal grace period, which has two parameters:
+ * graceBefore and graceAfter
+ *
* @author Christina Fu
* @version $Revision$, $Date$
*/
public class RenewGracePeriodConstraint extends EnrollConstraint {
- // for renewal: # of days before the orig cert expiration date
+ // for renewal: # of days before the orig cert expiration date
public static final String CONFIG_RENEW_GRACE_BEFORE = "renewal.graceBefore";
// for renewal: # of days after the orig cert expiration date
public static final String CONFIG_RENEW_GRACE_AFTER = "renewal.graceAfter";
@@ -58,20 +56,20 @@ public class RenewGracePeriodConstraint extends EnrollConstraint {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
public void setConfig(String name, String value)
- throws EPropertyException {
- if ( name.equals(CONFIG_RENEW_GRACE_BEFORE) ||
- name.equals(CONFIG_RENEW_GRACE_AFTER)) {
- try {
- Integer.parseInt(value);
- } catch (Exception e) {
+ throws EPropertyException {
+ if (name.equals(CONFIG_RENEW_GRACE_BEFORE) ||
+ name.equals(CONFIG_RENEW_GRACE_AFTER)) {
+ try {
+ Integer.parseInt(value);
+ } catch (Exception e) {
throw new EPropertyException(CMS.getUserMessage(
- "CMS_INVALID_PROPERTY", CONFIG_RENEW_GRACE_BEFORE +" or "+ CONFIG_RENEW_GRACE_AFTER));
- }
+ "CMS_INVALID_PROPERTY", CONFIG_RENEW_GRACE_BEFORE + " or " + CONFIG_RENEW_GRACE_AFTER));
+ }
}
super.setConfig(name, value);
}
@@ -88,75 +86,73 @@ public class RenewGracePeriodConstraint extends EnrollConstraint {
}
public void validate(IRequest req, X509CertInfo info)
- throws ERejectException {
- String origExpDate_s = req.getExtDataInString("origNotAfter");
- // probably not for renewal
- if (origExpDate_s == null) {
- return;
- } else {
- CMS.debug("validate RenewGracePeriod: original cert expiration date found... renewing");
- }
- CMS.debug("ValidilityConstraint: validateRenewGraceperiod begins");
- BigInteger origExpDate_BI = new BigInteger(origExpDate_s);
- Date origExpDate = new Date(origExpDate_BI.longValue());
- String renew_grace_before_s = getConfig(CONFIG_RENEW_GRACE_BEFORE);
- String renew_grace_after_s = getConfig(CONFIG_RENEW_GRACE_AFTER);
- int renew_grace_before = 0;
- int renew_grace_after = 0;
- BigInteger renew_grace_before_BI = new BigInteger(renew_grace_before_s);
- BigInteger renew_grace_after_BI= new BigInteger(renew_grace_after_s);
-
- // -1 means no limit
- if (renew_grace_before_s == "")
- renew_grace_before = -1;
- else
- renew_grace_before = Integer.parseInt(renew_grace_before_s);
-
- if (renew_grace_after_s == "")
- renew_grace_after = -1;
- else
- renew_grace_after = Integer.parseInt(renew_grace_after_s);
-
- if (renew_grace_before > 0)
- renew_grace_before_BI = renew_grace_before_BI.multiply(BigInteger.valueOf(1000 * 86400));
- if (renew_grace_after > 0)
- renew_grace_after_BI = renew_grace_after_BI.multiply(BigInteger.valueOf(1000 * 86400));
-
- Date current = CMS.getCurrentDate();
- long millisDiff = origExpDate.getTime() - current.getTime();
- CMS.debug("validateRenewGracePeriod: millisDiff=" + millisDiff + " origExpDate=" + origExpDate.getTime() + " current=" + current.getTime());
-
- /*
- * "days", if positive, has to be less than renew_grace_before
- * "days", if negative, means already past expiration date,
- * (abs value) has to be less than renew_grace_after
- * if renew_grace_before or renew_grace_after are negative
- * the one with negative value is ignored
- */
- if (millisDiff >= 0) {
- if ((renew_grace_before>0) && (millisDiff > renew_grace_before_BI.longValue())) {
- throw new ERejectException(CMS.getUserMessage(getLocale(req),
- "CMS_PROFILE_RENEW_OUTSIDE_GRACE_PERIOD",
- renew_grace_before+" days before and "+
- renew_grace_after+" days after original cert expiration date"));
- }
- } else {
- if ((renew_grace_after > 0) && ((0-millisDiff) > renew_grace_after_BI.longValue())) {
- throw new ERejectException(CMS.getUserMessage(getLocale(req),
- "CMS_PROFILE_RENEW_OUTSIDE_GRACE_PERIOD",
- renew_grace_before+" days before and "+
- renew_grace_after+" days after original cert expiration date"));
- }
- }
+ throws ERejectException {
+ String origExpDate_s = req.getExtDataInString("origNotAfter");
+ // probably not for renewal
+ if (origExpDate_s == null) {
+ return;
+ } else {
+ CMS.debug("validate RenewGracePeriod: original cert expiration date found... renewing");
+ }
+ CMS.debug("ValidilityConstraint: validateRenewGraceperiod begins");
+ BigInteger origExpDate_BI = new BigInteger(origExpDate_s);
+ Date origExpDate = new Date(origExpDate_BI.longValue());
+ String renew_grace_before_s = getConfig(CONFIG_RENEW_GRACE_BEFORE);
+ String renew_grace_after_s = getConfig(CONFIG_RENEW_GRACE_AFTER);
+ int renew_grace_before = 0;
+ int renew_grace_after = 0;
+ BigInteger renew_grace_before_BI = new BigInteger(renew_grace_before_s);
+ BigInteger renew_grace_after_BI = new BigInteger(renew_grace_after_s);
+
+ // -1 means no limit
+ if (renew_grace_before_s == "")
+ renew_grace_before = -1;
+ else
+ renew_grace_before = Integer.parseInt(renew_grace_before_s);
+
+ if (renew_grace_after_s == "")
+ renew_grace_after = -1;
+ else
+ renew_grace_after = Integer.parseInt(renew_grace_after_s);
+
+ if (renew_grace_before > 0)
+ renew_grace_before_BI = renew_grace_before_BI.multiply(BigInteger.valueOf(1000 * 86400));
+ if (renew_grace_after > 0)
+ renew_grace_after_BI = renew_grace_after_BI.multiply(BigInteger.valueOf(1000 * 86400));
+
+ Date current = CMS.getCurrentDate();
+ long millisDiff = origExpDate.getTime() - current.getTime();
+ CMS.debug("validateRenewGracePeriod: millisDiff=" + millisDiff + " origExpDate=" + origExpDate.getTime() + " current=" + current.getTime());
+
+ /*
+ * "days", if positive, has to be less than renew_grace_before "days",
+ * if negative, means already past expiration date, (abs value) has to
+ * be less than renew_grace_after if renew_grace_before or
+ * renew_grace_after are negative the one with negative value is ignored
+ */
+ if (millisDiff >= 0) {
+ if ((renew_grace_before > 0) && (millisDiff > renew_grace_before_BI.longValue())) {
+ throw new ERejectException(CMS.getUserMessage(getLocale(req),
+ "CMS_PROFILE_RENEW_OUTSIDE_GRACE_PERIOD",
+ renew_grace_before + " days before and " +
+ renew_grace_after + " days after original cert expiration date"));
+ }
+ } else {
+ if ((renew_grace_after > 0) && ((0 - millisDiff) > renew_grace_after_BI.longValue())) {
+ throw new ERejectException(CMS.getUserMessage(getLocale(req),
+ "CMS_PROFILE_RENEW_OUTSIDE_GRACE_PERIOD",
+ renew_grace_before + " days before and " +
+ renew_grace_after + " days after original cert expiration date"));
+ }
+ }
}
-
public String getText(Locale locale) {
String renew_grace_before_s = getConfig(CONFIG_RENEW_GRACE_BEFORE);
- String renew_grace_after_s= getConfig(CONFIG_RENEW_GRACE_AFTER);
- return CMS.getUserMessage(locale, "CMS_PROFILE_CONSTRAINT_VALIDITY_TEXT",
- renew_grace_before_s+" days before and "+
- renew_grace_after_s+" days after original cert expiration date");
+ String renew_grace_after_s = getConfig(CONFIG_RENEW_GRACE_AFTER);
+ return CMS.getUserMessage(locale, "CMS_PROFILE_CONSTRAINT_VALIDITY_TEXT",
+ renew_grace_before_s + " days before and " +
+ renew_grace_after_s + " days after original cert expiration date");
}
public boolean isApplicable(IPolicyDefault def) {
diff --git a/pki/base/common/src/com/netscape/cms/profile/constraint/SigningAlgConstraint.java b/pki/base/common/src/com/netscape/cms/profile/constraint/SigningAlgConstraint.java
index f570c26e..12261862 100644
--- a/pki/base/common/src/com/netscape/cms/profile/constraint/SigningAlgConstraint.java
+++ b/pki/base/common/src/com/netscape/cms/profile/constraint/SigningAlgConstraint.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.constraint;
-
import java.util.Locale;
import java.util.StringTokenizer;
import java.util.Vector;
@@ -40,12 +39,10 @@ import com.netscape.cms.profile.def.NoDefault;
import com.netscape.cms.profile.def.SigningAlgDefault;
import com.netscape.cms.profile.def.UserSigningAlgDefault;
-
/**
- * This class implements the signing algorithm constraint.
- * It checks if the signing algorithm in the certificate
- * template satisfies the criteria.
- *
+ * This class implements the signing algorithm constraint. It checks if the
+ * signing algorithm in the certificate template satisfies the criteria.
+ *
* @version $Revision$, $Date$
*/
public class SigningAlgConstraint extends EnrollConstraint {
@@ -69,29 +66,28 @@ public class SigningAlgConstraint extends EnrollConstraint {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
public void setConfig(String name, String value)
- throws EPropertyException {
+ throws EPropertyException {
if (mConfig.getSubStore("params") == null) {
CMS.debug("SigningAlgConstraint: mConfig.getSubStore is null");
} else {
- CMS.debug("SigningAlgConstraint: setConfig name=" + name +
- " value=" + value);
-
- if(name.equals(CONFIG_ALGORITHMS_ALLOWED))
- {
- StringTokenizer st = new StringTokenizer(value, ",");
- while (st.hasMoreTokens()) {
- String v = st.nextToken();
- if (DEF_CONFIG_ALGORITHMS.indexOf(v) == -1) {
- throw new EPropertyException(
- CMS.getUserMessage("CMS_PROFILE_PROPERTY_ERROR", v));
- }
- }
+ CMS.debug("SigningAlgConstraint: setConfig name=" + name +
+ " value=" + value);
+
+ if (name.equals(CONFIG_ALGORITHMS_ALLOWED)) {
+ StringTokenizer st = new StringTokenizer(value, ",");
+ while (st.hasMoreTokens()) {
+ String v = st.nextToken();
+ if (DEF_CONFIG_ALGORITHMS.indexOf(v) == -1) {
+ throw new EPropertyException(
+ CMS.getUserMessage("CMS_PROFILE_PROPERTY_ERROR", v));
+ }
+ }
}
mConfig.getSubStore("params").putString(name, value);
}
@@ -101,24 +97,23 @@ public class SigningAlgConstraint extends EnrollConstraint {
if (name.equals(CONFIG_ALGORITHMS_ALLOWED)) {
return new Descriptor(IDescriptor.STRING, null,
DEF_CONFIG_ALGORITHMS,
- CMS.getUserMessage(locale,
- "CMS_PROFILE_SIGNING_ALGORITHMS_ALLOWED"));
+ CMS.getUserMessage(locale,
+ "CMS_PROFILE_SIGNING_ALGORITHMS_ALLOWED"));
}
return null;
}
/**
- * Validates the request. The request is not modified
- * during the validation.
+ * Validates the request. The request is not modified during the validation.
*/
public void validate(IRequest request, X509CertInfo info)
- throws ERejectException {
+ throws ERejectException {
CertificateAlgorithmId algId = null;
try {
algId = (CertificateAlgorithmId) info.get(X509CertInfo.ALGORITHM_ID);
AlgorithmId id = (AlgorithmId)
- algId.get(CertificateAlgorithmId.ALGORITHM);
+ algId.get(CertificateAlgorithmId.ALGORITHM);
Vector mCache = new Vector();
StringTokenizer st = new StringTokenizer(
@@ -132,7 +127,7 @@ public class SigningAlgConstraint extends EnrollConstraint {
if (!mCache.contains(id.toString())) {
throw new ERejectException(CMS.getUserMessage(
- getLocale(request),
+ getLocale(request),
"CMS_PROFILE_SIGNING_ALGORITHM_NOT_MATCHED", id.toString()));
}
} catch (Exception e) {
diff --git a/pki/base/common/src/com/netscape/cms/profile/constraint/SubjectNameConstraint.java b/pki/base/common/src/com/netscape/cms/profile/constraint/SubjectNameConstraint.java
index 7ce32f00..9ca8d452 100644
--- a/pki/base/common/src/com/netscape/cms/profile/constraint/SubjectNameConstraint.java
+++ b/pki/base/common/src/com/netscape/cms/profile/constraint/SubjectNameConstraint.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.constraint;
-
import java.io.IOException;
import java.util.Locale;
@@ -38,12 +37,10 @@ import com.netscape.cms.profile.def.NoDefault;
import com.netscape.cms.profile.def.SubjectNameDefault;
import com.netscape.cms.profile.def.UserSubjectNameDefault;
-
/**
- * This class implements the subject name constraint.
- * It checks if the subject name in the certificate
- * template satisfies the criteria.
- *
+ * This class implements the subject name constraint. It checks if the subject
+ * name in the certificate template satisfies the criteria.
+ *
* @version $Revision$, $Date$
*/
public class SubjectNameConstraint extends EnrollConstraint {
@@ -56,13 +53,13 @@ public class SubjectNameConstraint extends EnrollConstraint {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
- if (name.equals(CONFIG_PATTERN)) {
- return new Descriptor(IDescriptor.STRING,
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ if (name.equals(CONFIG_PATTERN)) {
+ return new Descriptor(IDescriptor.STRING,
null, null,
CMS.getUserMessage(locale, "CMS_PROFILE_SUBJECT_NAME_PATTERN"));
} else {
@@ -75,22 +72,21 @@ public class SubjectNameConstraint extends EnrollConstraint {
}
/**
- * Validates the request. The request is not modified
- * during the validation.
+ * Validates the request. The request is not modified during the validation.
*/
public void validate(IRequest request, X509CertInfo info)
- throws ERejectException {
+ throws ERejectException {
CMS.debug("SubjectNameConstraint: validate start");
CertificateSubjectName sn = null;
try {
sn = (CertificateSubjectName) info.get(X509CertInfo.SUBJECT);
- CMS.debug("SubjectNameConstraint: validate cert subject ="+
+ CMS.debug("SubjectNameConstraint: validate cert subject =" +
sn.toString());
} catch (Exception e) {
throw new ERejectException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_SUBJECT_NAME_NOT_FOUND"));
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_SUBJECT_NAME_NOT_FOUND"));
}
X500Name sn500 = null;
@@ -98,31 +94,31 @@ public class SubjectNameConstraint extends EnrollConstraint {
sn500 = (X500Name) sn.get(CertificateSubjectName.DN_NAME);
} catch (IOException e) {
throw new ERejectException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_SUBJECT_NAME_NOT_FOUND"));
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_SUBJECT_NAME_NOT_FOUND"));
}
if (sn500 == null) {
CMS.debug("SubjectNameConstraint: validate() - sn500 is null");
throw new ERejectException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_SUBJECT_NAME_NOT_FOUND"));
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_SUBJECT_NAME_NOT_FOUND"));
} else {
- CMS.debug("SubjectNameConstraint: validate() - sn500 "+
- CertificateSubjectName.DN_NAME + " = "+
- sn500.toString());
+ CMS.debug("SubjectNameConstraint: validate() - sn500 " +
+ CertificateSubjectName.DN_NAME + " = " +
+ sn500.toString());
}
if (!sn500.toString().matches(getConfig(CONFIG_PATTERN))) {
- CMS.debug("SubjectNameConstraint: validate() - sn500 not matching pattern "+ getConfig(CONFIG_PATTERN));
+ CMS.debug("SubjectNameConstraint: validate() - sn500 not matching pattern " + getConfig(CONFIG_PATTERN));
throw new ERejectException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_SUBJECT_NAME_NOT_MATCHED",
- sn500.toString()));
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_SUBJECT_NAME_NOT_MATCHED",
+ sn500.toString()));
}
}
public String getText(Locale locale) {
- return CMS.getUserMessage(locale,
- "CMS_PROFILE_CONSTRAINT_SUBJECT_NAME_TEXT",
+ return CMS.getUserMessage(locale,
+ "CMS_PROFILE_CONSTRAINT_SUBJECT_NAME_TEXT",
getConfig(CONFIG_PATTERN));
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/constraint/UniqueKeyConstraint.java b/pki/base/common/src/com/netscape/cms/profile/constraint/UniqueKeyConstraint.java
index b47e2230..c242ffce 100644
--- a/pki/base/common/src/com/netscape/cms/profile/constraint/UniqueKeyConstraint.java
+++ b/pki/base/common/src/com/netscape/cms/profile/constraint/UniqueKeyConstraint.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.constraint;
-
import java.util.Enumeration;
import java.util.Locale;
@@ -43,57 +42,53 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.cms.profile.def.NoDefault;
/**
- * This constraint is to check for publickey uniqueness.
- * The config param "allowSameKeyRenewal" enables the
- * situation where if the publickey is not unique, and if
- * the subject DN is the same, that is a "renewal".
- *
- * Another "feature" that is quoted out of this code is the
- * "revokeDupKeyCert" option, which enables the revocation
- * of certs that bear the same publickey as the enrolling
- * request. Since this can potentially be abused, it is taken
- * out and preserved in comments to allow future refinement.
- *
+ * This constraint is to check for publickey uniqueness. The config param
+ * "allowSameKeyRenewal" enables the situation where if the publickey is not
+ * unique, and if the subject DN is the same, that is a "renewal".
+ *
+ * Another "feature" that is quoted out of this code is the "revokeDupKeyCert"
+ * option, which enables the revocation of certs that bear the same publickey as
+ * the enrolling request. Since this can potentially be abused, it is taken out
+ * and preserved in comments to allow future refinement.
+ *
* @version $Revision$, $Date$
*/
public class UniqueKeyConstraint extends EnrollConstraint {
- /*
- public static final String CONFIG_REVOKE_DUPKEY_CERT =
- "revokeDupKeyCert";
- boolean mRevokeDupKeyCert = false;
- */
- public static final String CONFIG_ALLOW_SAME_KEY_RENEWAL =
- "allowSameKeyRenewal";
- boolean mAllowSameKeyRenewal = false;
+ /*
+ * public static final String CONFIG_REVOKE_DUPKEY_CERT =
+ * "revokeDupKeyCert"; boolean mRevokeDupKeyCert = false;
+ */
+ public static final String CONFIG_ALLOW_SAME_KEY_RENEWAL =
+ "allowSameKeyRenewal";
+ boolean mAllowSameKeyRenewal = false;
public ICertificateAuthority mCA = null;
- public UniqueKeyConstraint() {
- super();
- /*
- addConfigName(CONFIG_REVOKE_DUPKEY_CERT);
- */
- addConfigName(CONFIG_ALLOW_SAME_KEY_RENEWAL);
- }
+ public UniqueKeyConstraint() {
+ super();
+ /*
+ * addConfigName(CONFIG_REVOKE_DUPKEY_CERT);
+ */
+ addConfigName(CONFIG_ALLOW_SAME_KEY_RENEWAL);
+ }
- public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ public void init(IProfile profile, IConfigStore config)
+ throws EProfileException {
super.init(profile, config);
mCA = (ICertificateAuthority)
- CMS.getSubsystem(CMS.SUBSYSTEM_CA);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CA);
}
- public IDescriptor getConfigDescriptor(Locale locale, String name)
- {
- /*
- if (name.equals(CONFIG_REVOKE_DUPKEY_CERT)) {
- return new Descriptor(IDescriptor.BOOLEAN, null, "false",
- CMS.getUserMessage(locale, "CMS_PROFILE_CONFIG_REVOKE_DUPKEY_CERT"));
- }
- */
- if (name.equals(CONFIG_ALLOW_SAME_KEY_RENEWAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null, "false",
- CMS.getUserMessage(locale, "CMS_PROFILE_CONFIG_ALLOW_SAME_KEY_RENEWAL"));
- }
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ /*
+ * if (name.equals(CONFIG_REVOKE_DUPKEY_CERT)) { return new
+ * Descriptor(IDescriptor.BOOLEAN, null, "false",
+ * CMS.getUserMessage(locale, "CMS_PROFILE_CONFIG_REVOKE_DUPKEY_CERT"));
+ * }
+ */
+ if (name.equals(CONFIG_ALLOW_SAME_KEY_RENEWAL)) {
+ return new Descriptor(IDescriptor.BOOLEAN, null, "false",
+ CMS.getUserMessage(locale, "CMS_PROFILE_CONFIG_ALLOW_SAME_KEY_RENEWAL"));
+ }
return null;
}
@@ -102,173 +97,159 @@ public class UniqueKeyConstraint extends EnrollConstraint {
}
/**
- * Validates the request. The request is not modified
- * during the validation.
+ * Validates the request. The request is not modified during the validation.
*/
public void validate(IRequest request, X509CertInfo info)
- throws ERejectException {
- boolean rejected = false;
- int size = 0;
- ICertRecordList list;
+ throws ERejectException {
+ boolean rejected = false;
+ int size = 0;
+ ICertRecordList list;
- /*
- mRevokeDupKeyCert =
- getConfigBoolean(CONFIG_REVOKE_DUPKEY_CERT);
- */
- mAllowSameKeyRenewal = getConfigBoolean(CONFIG_ALLOW_SAME_KEY_RENEWAL);
+ /*
+ * mRevokeDupKeyCert = getConfigBoolean(CONFIG_REVOKE_DUPKEY_CERT);
+ */
+ mAllowSameKeyRenewal = getConfigBoolean(CONFIG_ALLOW_SAME_KEY_RENEWAL);
try {
CertificateX509Key infokey = (CertificateX509Key)
- info.get(X509CertInfo.KEY);
+ info.get(X509CertInfo.KEY);
X509Key key = (X509Key)
- infokey.get(CertificateX509Key.KEY);
+ infokey.get(CertificateX509Key.KEY);
- // check for key uniqueness
- byte pub[] = key.getEncoded();
- String pub_s = escapeBinaryData(pub);
- String filter = "(" + ICertRecord.ATTR_X509CERT_PUBLIC_KEY_DATA +"=" + pub_s + ")";
- list =
- (ICertRecordList)
- mCA.getCertificateRepository().findCertRecordsInList(filter, null, 10);
- size = list.getSize();
+ // check for key uniqueness
+ byte pub[] = key.getEncoded();
+ String pub_s = escapeBinaryData(pub);
+ String filter = "(" + ICertRecord.ATTR_X509CERT_PUBLIC_KEY_DATA + "=" + pub_s + ")";
+ list =
+ (ICertRecordList)
+ mCA.getCertificateRepository().findCertRecordsInList(filter, null, 10);
+ size = list.getSize();
} catch (Exception e) {
- throw new ERejectException(
+ throw new ERejectException(
CMS.getUserMessage(
- getLocale(request),
- "CMS_PROFILE_INTERNAL_ERROR",e.toString()));
- }
-
- /*
- * It does not matter if the corresponding cert's status
- * is valid or not, we don't want a key that was once
- * generated before
- */
- if (size > 0) {
- CMS.debug("UniqueKeyConstraint: found existing cert with duplicate key.");
-
- /*
- The following code revokes the existing certs that have
- the same public key as the one submitted for enrollment
- request. However, it is not a good idea due to possible
- abuse. It is therefore commented out. It is still
- however still maintained for possible utilization at later
- time
-
- // if configured to revoke duplicated key
- // revoke cert
- if (mRevokeDupKeyCert) {
- try {
- Enumeration e = list.getCertRecords(0, size-1);
- while (e != null && e.hasMoreElements()) {
- ICertRecord rec = (ICertRecord) e.nextElement();
- X509CertImpl cert = rec.getCertificate();
-
- // revoke the cert
- BigInteger serialNum = cert.getSerialNumber();
- ICAService service = (ICAService) mCA.getCAService();
-
- RevokedCertImpl crlEntry =
- formCRLEntry(serialNum, RevocationReason.KEY_COMPROMISE);
- service.revokeCert(crlEntry);
- CMS.debug("UniqueKeyConstraint: certificate with duplicate publickey revoked successfully");
- }
- } catch (Exception ex) {
- CMS.debug("UniqueKeyConstraint: error in revoke dupkey cert");
- }
- } // revoke dupkey cert turned on
- */
-
- if (mAllowSameKeyRenewal == true) {
- X500Name sjname_in_db = null;
- X500Name sjname_in_req = null;
-
- try {
- // get subject of request
- CertificateSubjectName subName =
- (CertificateSubjectName) info.get(X509CertInfo.SUBJECT);
-
- if (subName != null) {
-
- sjname_in_req =
- (X500Name) subName.get(CertificateSubjectName.DN_NAME);
- CMS.debug("UniqueKeyConstraint: cert request subject DN ="+ sjname_in_req.toString());
- Enumeration e = list.getCertRecords(0, size-1);
- while (e != null && e.hasMoreElements()) {
- ICertRecord rec = (ICertRecord) e.nextElement();
- X509CertImpl cert = rec.getCertificate();
- String certDN =
- cert.getSubjectDN().toString();
- CMS.debug("UniqueKeyConstraint: cert retrieved from ldap has subject DN ="+ certDN);
-
- sjname_in_db = new X500Name(certDN);
-
- if (sjname_in_db.equals(sjname_in_req) == false) {
- rejected = true;
- break;
- } else {
- rejected = false;
- }
- } // while
- } else { //subName is null
- rejected = true;
- }
- } catch (Exception ex1) {
- CMS.debug("UniqueKeyConstraint: error in allowSameKeyRenewal: "+ex1.toString());
- rejected = true;
- } // try
-
- } else {
- rejected = true;
- }// allowSameKeyRenewal
- } // (size > 0)
+ getLocale(request),
+ "CMS_PROFILE_INTERNAL_ERROR", e.toString()));
+ }
- if (rejected == true) {
- CMS.debug("UniqueKeyConstraint: rejected");
- throw new ERejectException(
- CMS.getUserMessage(
- getLocale(request),
- "CMS_PROFILE_DUPLICATE_KEY"));
- } else {
- CMS.debug("UniqueKeyConstraint: approved");
- }
+ /*
+ * It does not matter if the corresponding cert's status is valid or
+ * not, we don't want a key that was once generated before
+ */
+ if (size > 0) {
+ CMS.debug("UniqueKeyConstraint: found existing cert with duplicate key.");
+
+ /*
+ * The following code revokes the existing certs that have the same
+ * public key as the one submitted for enrollment request. However,
+ * it is not a good idea due to possible abuse. It is therefore
+ * commented out. It is still however still maintained for possible
+ * utilization at later time
+ *
+ * // if configured to revoke duplicated key // revoke cert if
+ * (mRevokeDupKeyCert) { try { Enumeration e =
+ * list.getCertRecords(0, size-1); while (e != null &&
+ * e.hasMoreElements()) { ICertRecord rec = (ICertRecord)
+ * e.nextElement(); X509CertImpl cert = rec.getCertificate();
+ *
+ * // revoke the cert BigInteger serialNum = cert.getSerialNumber();
+ * ICAService service = (ICAService) mCA.getCAService();
+ *
+ * RevokedCertImpl crlEntry = formCRLEntry(serialNum,
+ * RevocationReason.KEY_COMPROMISE); service.revokeCert(crlEntry);
+ * CMS.debug(
+ * "UniqueKeyConstraint: certificate with duplicate publickey revoked successfully"
+ * ); } } catch (Exception ex) {
+ * CMS.debug("UniqueKeyConstraint: error in revoke dupkey cert"); }
+ * } // revoke dupkey cert turned on
+ */
+
+ if (mAllowSameKeyRenewal == true) {
+ X500Name sjname_in_db = null;
+ X500Name sjname_in_req = null;
+
+ try {
+ // get subject of request
+ CertificateSubjectName subName =
+ (CertificateSubjectName) info.get(X509CertInfo.SUBJECT);
+
+ if (subName != null) {
+
+ sjname_in_req =
+ (X500Name) subName.get(CertificateSubjectName.DN_NAME);
+ CMS.debug("UniqueKeyConstraint: cert request subject DN =" + sjname_in_req.toString());
+ Enumeration e = list.getCertRecords(0, size - 1);
+ while (e != null && e.hasMoreElements()) {
+ ICertRecord rec = (ICertRecord) e.nextElement();
+ X509CertImpl cert = rec.getCertificate();
+ String certDN =
+ cert.getSubjectDN().toString();
+ CMS.debug("UniqueKeyConstraint: cert retrieved from ldap has subject DN =" + certDN);
+
+ sjname_in_db = new X500Name(certDN);
+
+ if (sjname_in_db.equals(sjname_in_req) == false) {
+ rejected = true;
+ break;
+ } else {
+ rejected = false;
+ }
+ } // while
+ } else { // subName is null
+ rejected = true;
+ }
+ } catch (Exception ex1) {
+ CMS.debug("UniqueKeyConstraint: error in allowSameKeyRenewal: " + ex1.toString());
+ rejected = true;
+ } // try
+
+ } else {
+ rejected = true;
+ }// allowSameKeyRenewal
+ } // (size > 0)
+
+ if (rejected == true) {
+ CMS.debug("UniqueKeyConstraint: rejected");
+ throw new ERejectException(
+ CMS.getUserMessage(
+ getLocale(request),
+ "CMS_PROFILE_DUPLICATE_KEY"));
+ } else {
+ CMS.debug("UniqueKeyConstraint: approved");
+ }
}
- /**
+ /**
* make a CRL entry from a serial number and revocation reason.
+ *
* @return a RevokedCertImpl that can be entered in a CRL.
-
- protected RevokedCertImpl formCRLEntry(
- BigInteger serialNo, RevocationReason reason)
- throws EBaseException {
- CRLReasonExtension reasonExt = new CRLReasonExtension(reason);
- CRLExtensions crlentryexts = new CRLExtensions();
-
- try {
- crlentryexts.set(CRLReasonExtension.NAME, reasonExt);
- } catch (IOException e) {
- CMS.debug("CMSGW_ERR_CRL_REASON "+e.toString());
-
- // throw new ECMSGWException(
- // CMS.getLogMessage("CMSGW_ERROR_SETTING_CRLREASON"));
-
- }
- RevokedCertImpl crlentry =
- new RevokedCertImpl(serialNo, CMS.getCurrentDate(),
- crlentryexts);
-
- return crlentry;
- }
- */
+ *
+ * protected RevokedCertImpl formCRLEntry( BigInteger serialNo,
+ * RevocationReason reason) throws EBaseException {
+ * CRLReasonExtension reasonExt = new CRLReasonExtension(reason);
+ * CRLExtensions crlentryexts = new CRLExtensions();
+ *
+ * try { crlentryexts.set(CRLReasonExtension.NAME, reasonExt); }
+ * catch (IOException e) {
+ * CMS.debug("CMSGW_ERR_CRL_REASON "+e.toString());
+ *
+ * // throw new ECMSGWException( //
+ * CMS.getLogMessage("CMSGW_ERROR_SETTING_CRLREASON"));
+ *
+ * } RevokedCertImpl crlentry = new RevokedCertImpl(serialNo,
+ * CMS.getCurrentDate(), crlentryexts);
+ *
+ * return crlentry; }
+ */
public String getText(Locale locale) {
String params[] = {
-/*
- getConfig(CONFIG_REVOKE_DUPKEY_CERT),
-*/
- };
+ /*
+ * getConfig(CONFIG_REVOKE_DUPKEY_CERT),
+ */
+ };
- return CMS.getUserMessage(locale,
+ return CMS.getUserMessage(locale,
"CMS_PROFILE_CONSTRAINT_ALLOW_SAME_KEY_RENEWAL_TEXT", params);
}
@@ -285,12 +266,12 @@ public class UniqueKeyConstraint extends EnrollConstraint {
}
public boolean isApplicable(IPolicyDefault def) {
- if (def instanceof NoDefault)
- return true;
+ if (def instanceof NoDefault)
+ return true;
if (def instanceof UniqueKeyConstraint)
return true;
- return false;
+ return false;
}
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/constraint/UniqueSubjectNameConstraint.java b/pki/base/common/src/com/netscape/cms/profile/constraint/UniqueSubjectNameConstraint.java
index 72498d39..b59e6e30 100644
--- a/pki/base/common/src/com/netscape/cms/profile/constraint/UniqueSubjectNameConstraint.java
+++ b/pki/base/common/src/com/netscape/cms/profile/constraint/UniqueSubjectNameConstraint.java
@@ -51,17 +51,16 @@ import com.netscape.cms.profile.def.SubjectNameDefault;
import com.netscape.cms.profile.def.UserSubjectNameDefault;
/**
- * This class implements the unique subject name constraint.
- * It checks if the subject name in the certificate is
- * unique in the internal database, ie, no two certificates
- * have the same subject name.
- *
+ * This class implements the unique subject name constraint. It checks if the
+ * subject name in the certificate is unique in the internal database, ie, no
+ * two certificates have the same subject name.
+ *
* @version $Revision$, $Date$
*/
public class UniqueSubjectNameConstraint extends EnrollConstraint {
public static final String CONFIG_KEY_USAGE_EXTENSION_CHECKING =
- "enableKeyUsageExtensionChecking";
+ "enableKeyUsageExtensionChecking";
private boolean mKeyUsageExtensionChecking = true;
public UniqueSubjectNameConstraint() {
@@ -69,14 +68,14 @@ public class UniqueSubjectNameConstraint extends EnrollConstraint {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
if (name.equals(CONFIG_KEY_USAGE_EXTENSION_CHECKING)) {
return new Descriptor(IDescriptor.BOOLEAN, null, "true",
- CMS.getUserMessage(locale, "CMS_PROFILE_CONFIG_KEY_USAGE_EXTENSION_CHECKING"));
+ CMS.getUserMessage(locale, "CMS_PROFILE_CONFIG_KEY_USAGE_EXTENSION_CHECKING"));
}
return null;
}
@@ -85,12 +84,12 @@ public class UniqueSubjectNameConstraint extends EnrollConstraint {
return null;
}
- /**
- * Checks if the key extension in the issued certificate
- * is the same as the one in the certificate template.
- */
+ /**
+ * Checks if the key extension in the issued certificate is the same as the
+ * one in the certificate template.
+ */
private boolean sameKeyUsageExtension(ICertRecord rec,
- X509CertInfo certInfo) {
+ X509CertInfo certInfo) {
X509CertImpl impl = rec.getCertificate();
boolean bits[] = impl.getKeyUsage();
@@ -98,7 +97,7 @@ public class UniqueSubjectNameConstraint extends EnrollConstraint {
try {
extensions = (CertificateExtensions)
- certInfo.get(X509CertInfo.EXTENSIONS);
+ certInfo.get(X509CertInfo.EXTENSIONS);
} catch (IOException e) {
} catch (java.security.cert.CertificateException e) {
}
@@ -110,9 +109,9 @@ public class UniqueSubjectNameConstraint extends EnrollConstraint {
} else {
try {
ext = (KeyUsageExtension) extensions.get(
- KeyUsageExtension.class.getSimpleName());
+ KeyUsageExtension.class.getSimpleName());
} catch (IOException e) {
- // extension isn't there.
+ // extension isn't there.
}
if (ext == null) {
@@ -135,48 +134,46 @@ public class UniqueSubjectNameConstraint extends EnrollConstraint {
return false;
}
}
- }
+ }
}
- return true;
+ return true;
}
-
/**
- * Validates the request. The request is not modified
- * during the validation.
- *
- * Rules are as follows:
- * If the subject name is not unique, then the request will be rejected unless:
- * 1. the certificate is expired or expired_revoked
+ * Validates the request. The request is not modified during the validation.
+ *
+ * Rules are as follows: If the subject name is not unique, then the request
+ * will be rejected unless: 1. the certificate is expired or expired_revoked
* 2. the certificate is revoked and the revocation reason is not "on hold"
- * 3. the keyUsageExtension bits are different and enableKeyUsageExtensionChecking=true (default)
+ * 3. the keyUsageExtension bits are different and
+ * enableKeyUsageExtensionChecking=true (default)
*/
public void validate(IRequest request, X509CertInfo info)
- throws ERejectException {
+ throws ERejectException {
CMS.debug("UniqueSubjectNameConstraint: validate start");
CertificateSubjectName sn = null;
- IAuthority authority = (IAuthority)CMS.getSubsystem("ca");
-
+ IAuthority authority = (IAuthority) CMS.getSubsystem("ca");
+
mKeyUsageExtensionChecking = getConfigBoolean(CONFIG_KEY_USAGE_EXTENSION_CHECKING);
ICertificateRepository certdb = null;
if (authority != null && authority instanceof ICertificateAuthority) {
- ICertificateAuthority ca = (ICertificateAuthority)authority;
+ ICertificateAuthority ca = (ICertificateAuthority) authority;
certdb = ca.getCertificateRepository();
}
-
+
try {
sn = (CertificateSubjectName) info.get(X509CertInfo.SUBJECT);
} catch (Exception e) {
throw new ERejectException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_SUBJECT_NAME_NOT_FOUND"));
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_SUBJECT_NAME_NOT_FOUND"));
}
String certsubjectname = null;
if (sn == null)
throw new ERejectException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_SUBJECT_NAME_NOT_FOUND"));
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_SUBJECT_NAME_NOT_FOUND"));
else {
certsubjectname = sn.toString();
String filter = "x509Cert.subject=" + certsubjectname;
@@ -184,10 +181,10 @@ public class UniqueSubjectNameConstraint extends EnrollConstraint {
try {
sameSubjRecords = certdb.findCertRecords(filter);
} catch (EBaseException e) {
- CMS.debug("UniqueSubjectNameConstraint exception: "+e.toString());
+ CMS.debug("UniqueSubjectNameConstraint exception: " + e.toString());
}
while (sameSubjRecords != null && sameSubjRecords.hasMoreElements()) {
- ICertRecord rec = sameSubjRecords.nextElement();
+ ICertRecord rec = sameSubjRecords.nextElement();
String status = rec.getStatus();
IRevocationInfo revocationInfo = rec.getRevocationInfo();
@@ -200,7 +197,7 @@ public class UniqueSubjectNameConstraint extends EnrollConstraint {
Enumeration<Extension> enumx = crlExts.getElements();
while (enumx.hasMoreElements()) {
- Extension ext = enumx.nextElement();
+ Extension ext = enumx.nextElement();
if (ext instanceof CRLReasonExtension) {
reason = ((CRLReasonExtension) ext).getReason();
@@ -213,8 +210,8 @@ public class UniqueSubjectNameConstraint extends EnrollConstraint {
continue;
}
- if (status.equals(ICertRecord.STATUS_REVOKED) && reason != null &&
- (! reason.equals(RevocationReason.CERTIFICATE_HOLD))) {
+ if (status.equals(ICertRecord.STATUS_REVOKED) && reason != null &&
+ (!reason.equals(RevocationReason.CERTIFICATE_HOLD))) {
continue;
}
@@ -223,20 +220,20 @@ public class UniqueSubjectNameConstraint extends EnrollConstraint {
}
throw new ERejectException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_SUBJECT_NAME_NOT_UNIQUE",
- certsubjectname));
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_SUBJECT_NAME_NOT_UNIQUE",
+ certsubjectname));
}
}
- CMS.debug("UniqueSubjectNameConstraint: validate end");
+ CMS.debug("UniqueSubjectNameConstraint: validate end");
}
public String getText(Locale locale) {
String params[] = {
- getConfig(CONFIG_KEY_USAGE_EXTENSION_CHECKING)
+ getConfig(CONFIG_KEY_USAGE_EXTENSION_CHECKING)
};
- return CMS.getUserMessage(locale,
- "CMS_PROFILE_CONSTRAINT_UNIQUE_SUBJECT_NAME_TEXT",
+ return CMS.getUserMessage(locale,
+ "CMS_PROFILE_CONSTRAINT_UNIQUE_SUBJECT_NAME_TEXT",
params);
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/constraint/ValidityConstraint.java b/pki/base/common/src/com/netscape/cms/profile/constraint/ValidityConstraint.java
index 95c32221..c839cb5d 100644
--- a/pki/base/common/src/com/netscape/cms/profile/constraint/ValidityConstraint.java
+++ b/pki/base/common/src/com/netscape/cms/profile/constraint/ValidityConstraint.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.constraint;
-
import java.io.IOException;
import java.util.Date;
import java.util.Locale;
@@ -40,12 +39,10 @@ import com.netscape.cms.profile.def.NoDefault;
import com.netscape.cms.profile.def.UserValidityDefault;
import com.netscape.cms.profile.def.ValidityDefault;
-
/**
- * This class implements the validity constraint.
- * It checks if the validity in the certificate
- * template satisfies the criteria.
- *
+ * This class implements the validity constraint. It checks if the validity in
+ * the certificate template satisfies the criteria.
+ *
* @version $Revision$, $Date$
*/
public class ValidityConstraint extends EnrollConstraint {
@@ -68,20 +65,20 @@ public class ValidityConstraint extends EnrollConstraint {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
public void setConfig(String name, String value)
- throws EPropertyException {
+ throws EPropertyException {
if (name.equals(CONFIG_RANGE) ||
- name.equals(CONFIG_NOT_BEFORE_GRACE_PERIOD)) {
- try {
- Integer.parseInt(value);
- } catch (Exception e) {
+ name.equals(CONFIG_NOT_BEFORE_GRACE_PERIOD)) {
+ try {
+ Integer.parseInt(value);
+ } catch (Exception e) {
throw new EPropertyException(CMS.getUserMessage(
"CMS_INVALID_PROPERTY", name));
- }
+ }
}
super.setConfig(name, value);
}
@@ -104,11 +101,10 @@ public class ValidityConstraint extends EnrollConstraint {
}
/**
- * Validates the request. The request is not modified
- * during the validation.
+ * Validates the request. The request is not modified during the validation.
*/
public void validate(IRequest request, X509CertInfo info)
- throws ERejectException {
+ throws ERejectException {
CertificateValidity v = null;
try {
@@ -144,22 +140,22 @@ public class ValidityConstraint extends EnrollConstraint {
long millisDiff = notAfter.getTime() - notBefore.getTime();
CMS.debug("ValidityConstraint: millisDiff=" + millisDiff + " notAfter=" + notAfter.getTime() + " notBefore=" + notBefore.getTime());
- long long_days = (millisDiff / 1000 ) / 86400;
- CMS.debug("ValidityConstraint: long_days: "+long_days);
- int days = (int)long_days;
- CMS.debug("ValidityConstraint: days: "+days);
+ long long_days = (millisDiff / 1000) / 86400;
+ CMS.debug("ValidityConstraint: long_days: " + long_days);
+ int days = (int) long_days;
+ CMS.debug("ValidityConstraint: days: " + days);
if (days > Integer.parseInt(getConfig(CONFIG_RANGE))) {
throw new ERejectException(CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_VALIDITY_OUT_OF_RANGE",
+ "CMS_PROFILE_VALIDITY_OUT_OF_RANGE",
Integer.toString(days)));
}
- // 613828
- // The validity field shall specify a notBefore value
- // that does not precede the current time and a notAfter
- // value that does not precede the value specified in
- // notBefore (test can be automated; try entering violating
+ // 613828
+ // The validity field shall specify a notBefore value
+ // that does not precede the current time and a notAfter
+ // value that does not precede the value specified in
+ // notBefore (test can be automated; try entering violating
// time values and check result).
String notBeforeCheckStr = getConfig(CONFIG_CHECK_NOT_BEFORE);
boolean notBeforeCheck;
@@ -167,7 +163,7 @@ public class ValidityConstraint extends EnrollConstraint {
if (notBeforeCheckStr == null || notBeforeCheckStr.equals("")) {
notBeforeCheckStr = "false";
}
- notBeforeCheck = Boolean.valueOf(notBeforeCheckStr).booleanValue();
+ notBeforeCheck = Boolean.valueOf(notBeforeCheckStr).booleanValue();
String notAfterCheckStr = getConfig(CONFIG_CHECK_NOT_AFTER);
boolean notAfterCheck;
@@ -175,7 +171,7 @@ public class ValidityConstraint extends EnrollConstraint {
if (notAfterCheckStr == null || notAfterCheckStr.equals("")) {
notAfterCheckStr = "false";
}
- notAfterCheck = Boolean.valueOf(notAfterCheckStr).booleanValue();
+ notAfterCheck = Boolean.valueOf(notAfterCheckStr).booleanValue();
String notBeforeGracePeriodStr = getConfig(CONFIG_NOT_BEFORE_GRACE_PERIOD);
if (notBeforeGracePeriodStr == null || notBeforeGracePeriodStr.equals("")) {
@@ -186,7 +182,7 @@ public class ValidityConstraint extends EnrollConstraint {
Date current = CMS.getCurrentDate();
if (notBeforeCheck) {
if (notBefore.getTime() > (current.getTime() + notBeforeGracePeriod)) {
- CMS.debug("ValidityConstraint: notBefore (" + notBefore + ") > current + "+
+ CMS.debug("ValidityConstraint: notBefore (" + notBefore + ") > current + " +
"gracePeriod (" + new Date(current.getTime() + notBeforeGracePeriod) + ")");
throw new ERejectException(CMS.getUserMessage(getLocale(request),
"CMS_PROFILE_NOT_BEFORE_AFTER_CURRENT"));
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/AuthInfoAccessExtDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/AuthInfoAccessExtDefault.java
index 6f73cd52..732d4640 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/AuthInfoAccessExtDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/AuthInfoAccessExtDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.io.IOException;
import java.util.Enumeration;
import java.util.Locale;
@@ -40,11 +39,10 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements an enrollment default policy
- * that populates Authuority Info Access extension.
- *
+ * This class implements an enrollment default policy that populates Authuority
+ * Info Access extension.
+ *
* @version $Revision$, $Date$
*/
public class AuthInfoAccessExtDefault extends EnrollExtDefault {
@@ -89,30 +87,30 @@ public class AuthInfoAccessExtDefault extends EnrollExtDefault {
return num;
}
-
+
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
refreshConfigAndValueNames();
}
public void setConfig(String name, String value)
- throws EPropertyException {
+ throws EPropertyException {
int num = 0;
if (name.equals(CONFIG_NUM_ADS)) {
- try {
- num = Integer.parseInt(value);
+ try {
+ num = Integer.parseInt(value);
- if (num >= MAX_NUM_AD || num < 0) {
- throw new EPropertyException(CMS.getUserMessage(
+ if (num >= MAX_NUM_AD || num < 0) {
+ throw new EPropertyException(CMS.getUserMessage(
"CMS_INVALID_PROPERTY", CONFIG_NUM_ADS));
- }
-
- } catch (Exception e) {
+ }
+
+ } catch (Exception e) {
throw new EPropertyException(CMS.getUserMessage(
"CMS_INVALID_PROPERTY", CONFIG_NUM_ADS));
- }
- }
+ }
+ }
super.setConfig(name, value);
}
@@ -122,7 +120,7 @@ public class AuthInfoAccessExtDefault extends EnrollExtDefault {
}
protected void refreshConfigAndValueNames() {
- //refesh our config name list
+ // refesh our config name list
super.refreshConfigAndValueNames();
mConfigNames.removeAllElements();
@@ -142,42 +140,42 @@ public class AuthInfoAccessExtDefault extends EnrollExtDefault {
}
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
if (name.equals(CONFIG_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.startsWith(CONFIG_AD_METHOD)) {
- return new Descriptor(IDescriptor.STRING, null,
+ return new Descriptor(IDescriptor.STRING, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_AD_METHOD"));
} else if (name.startsWith(CONFIG_AD_LOCATIONTYPE)) {
- return new Descriptor(IDescriptor.CHOICE, "RFC822Name,DNSName,DirectoryName,EDIPartyName,URIName,IPAddress,OIDName",
+ return new Descriptor(IDescriptor.CHOICE, "RFC822Name,DNSName,DirectoryName,EDIPartyName,URIName,IPAddress,OIDName",
"URIName",
CMS.getUserMessage(locale, "CMS_PROFILE_AD_LOCATIONTYPE"));
} else if (name.startsWith(CONFIG_AD_LOCATION)) {
- return new Descriptor(IDescriptor.STRING, null,
+ return new Descriptor(IDescriptor.STRING, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_AD_LOCATION"));
} else if (name.startsWith(CONFIG_AD_ENABLE)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_AD_ENABLE"));
} else if (name.startsWith(CONFIG_NUM_ADS)) {
return new Descriptor(IDescriptor.INTEGER, null,
"1",
CMS.getUserMessage(locale, "CMS_PROFILE_NUM_ADS"));
- }
+ }
return null;
}
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.equals(VAL_GENERAL_NAMES)) {
- return new Descriptor(IDescriptor.STRING_LIST, null,
+ return new Descriptor(IDescriptor.STRING_LIST, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_GENERAL_NAMES"));
} else {
@@ -186,45 +184,42 @@ public class AuthInfoAccessExtDefault extends EnrollExtDefault {
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
try {
AuthInfoAccessExtension ext = null;
- if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ if (name == null) {
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
-
AuthInfoAccessExtension a = new AuthInfoAccessExtension(false);
ObjectIdentifier oid = a.getExtensionId();
ext = (AuthInfoAccessExtension)
- getExtension(oid.toString(), info);
+ getExtension(oid.toString(), info);
- if(ext == null) {
- populate(null,info);
+ if (ext == null) {
+ populate(null, info);
}
-
+
if (name.equals(VAL_CRITICAL)) {
ext = (AuthInfoAccessExtension)
getExtension(oid.toString(), info);
boolean val = Boolean.valueOf(value).booleanValue();
- if(ext == null)
- {
+ if (ext == null) {
return;
}
- ext.setCritical(val);
- } else if (name.equals(VAL_GENERAL_NAMES)) {
+ ext.setCritical(val);
+ } else if (name.equals(VAL_GENERAL_NAMES)) {
ext = (AuthInfoAccessExtension)
getExtension(oid.toString(), info);
- if(ext == null)
- {
+ if (ext == null) {
return;
}
boolean critical = ext.isCritical();
@@ -263,17 +258,17 @@ public class AuthInfoAccessExtDefault extends EnrollExtDefault {
GeneralNameInterface interface1 = parseGeneralName(locationType + ":" + location);
if (interface1 == null)
throw new EPropertyException(CMS.getUserMessage(
- locale, "CMS_INVALID_PROPERTY", locationType));
+ locale, "CMS_INVALID_PROPERTY", locationType));
gn = new GeneralName(interface1);
}
-
+
if (method != null) {
try {
- ext.addAccessDescription(new ObjectIdentifier(method), gn);
+ ext.addAccessDescription(new ObjectIdentifier(method), gn);
} catch (NumberFormatException ee) {
- CMS.debug("AuthInfoAccessExtDefault: "+ee.toString());
+ CMS.debug("AuthInfoAccessExtDefault: " + ee.toString());
throw new EPropertyException(CMS.getUserMessage(
- locale, "CMS_PROFILE_DEF_AIA_OID", method));
+ locale, "CMS_PROFILE_DEF_AIA_OID", method));
}
}
}
@@ -296,30 +291,29 @@ public class AuthInfoAccessExtDefault extends EnrollExtDefault {
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
+ X509CertInfo info)
+ throws EPropertyException {
AuthInfoAccessExtension ext = null;
- if (name == null) {
+ if (name == null) {
throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
AuthInfoAccessExtension a = new AuthInfoAccessExtension(false);
- ObjectIdentifier oid = a.getExtensionId();
+ ObjectIdentifier oid = a.getExtensionId();
ext = (AuthInfoAccessExtension)
getExtension(oid.toString(), info);
- if(ext == null)
- {
+ if (ext == null) {
try {
- populate(null,info);
+ populate(null, info);
} catch (EProfileException e) {
CMS.debug("AuthInfoAccessExtDefault: getValue " + e.toString());
- throw new EPropertyException(CMS.getUserMessage(
- locale, "CMS_INVALID_PROPERTY", name));
+ throw new EPropertyException(CMS.getUserMessage(
+ locale, "CMS_INVALID_PROPERTY", name));
}
}
@@ -336,7 +330,7 @@ public class AuthInfoAccessExtDefault extends EnrollExtDefault {
} else {
return "false";
}
- } else if (name.equals(VAL_GENERAL_NAMES)) {
+ } else if (name.equals(VAL_GENERAL_NAMES)) {
ext = (AuthInfoAccessExtension)
getExtension(oid.toString(), info);
@@ -345,11 +339,11 @@ public class AuthInfoAccessExtDefault extends EnrollExtDefault {
return "";
int num = getNumAds();
-
+
CMS.debug("AuthInfoAccess num=" + num);
Vector recs = new Vector();
- for (int i = 0; i < num; i++) {
+ for (int i = 0; i < num; i++) {
NameValuePairs np = new NameValuePairs();
AccessDescription des = null;
@@ -363,7 +357,7 @@ public class AuthInfoAccessExtDefault extends EnrollExtDefault {
np.add(AD_ENABLE, "false");
} else {
ObjectIdentifier methodOid = des.getMethod();
- GeneralName gn = des.getLocation();
+ GeneralName gn = des.getLocation();
np.add(AD_METHOD, methodOid.toString());
np.add(AD_LOCATION_TYPE, getGeneralNameType(gn));
@@ -402,7 +396,7 @@ public class AuthInfoAccessExtDefault extends EnrollExtDefault {
ads.append(getConfig(CONFIG_AD_ENABLE + i));
ads.append("}");
}
- return CMS.getUserMessage(locale, "CMS_PROFILE_DEF_AIA_TEXT",
+ return CMS.getUserMessage(locale, "CMS_PROFILE_DEF_AIA_TEXT",
getConfig(CONFIG_CRITICAL), ads.toString());
}
@@ -410,14 +404,14 @@ public class AuthInfoAccessExtDefault extends EnrollExtDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
AuthInfoAccessExtension ext = createExtension();
addExtension(ext.getExtensionId().toString(), ext, info);
}
public AuthInfoAccessExtension createExtension() {
- AuthInfoAccessExtension ext = null;
+ AuthInfoAccessExtension ext = null;
int num = getNumAds();
try {
@@ -439,22 +433,23 @@ public class AuthInfoAccessExtDefault extends EnrollExtDefault {
String hostname = CMS.getEENonSSLHost();
String port = CMS.getEENonSSLPort();
if (hostname != null && port != null)
- // location = "http://"+hostname+":"+port+"/ocsp/ee/ocsp";
- location = "http://"+hostname+":"+port+"/ca/ocsp";
+ // location =
+ // "http://"+hostname+":"+port+"/ocsp/ee/ocsp";
+ location = "http://" + hostname + ":" + port + "/ca/ocsp";
}
}
String s = locationType + ":" + location;
GeneralNameInterface gn = parseGeneralName(s);
if (gn != null) {
- ext.addAccessDescription(new ObjectIdentifier(method),
- new GeneralName(gn));
+ ext.addAccessDescription(new ObjectIdentifier(method),
+ new GeneralName(gn));
}
}
}
} catch (Exception e) {
- CMS.debug("AuthInfoAccessExtDefault: createExtension " +
- e.toString());
+ CMS.debug("AuthInfoAccessExtDefault: createExtension " +
+ e.toString());
}
return ext;
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/AuthTokenSubjectNameDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/AuthTokenSubjectNameDefault.java
index a308e2eb..9226bb4c 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/AuthTokenSubjectNameDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/AuthTokenSubjectNameDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.io.IOException;
import java.util.Locale;
@@ -35,11 +34,10 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements an enrollment default policy that
- * populates subject name based on the attribute values
- * in the authentication token (AuthToken) object.
+ * This class implements an enrollment default policy that populates subject
+ * name based on the attribute values in the authentication token (AuthToken)
+ * object.
*
* @version $Revision$, $Date$
*/
@@ -53,7 +51,7 @@ public class AuthTokenSubjectNameDefault extends EnrollDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
@@ -67,8 +65,8 @@ public class AuthTokenSubjectNameDefault extends EnrollDefault {
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
CMS.debug("AuthTokenSubjectNameDefault: begins");
if (name == null) {
throw new EPropertyException(CMS.getUserMessage(locale,
@@ -81,18 +79,18 @@ public class AuthTokenSubjectNameDefault extends EnrollDefault {
x500name = new X500Name(value);
CMS.debug("AuthTokenSubjectNameDefault: setValue x500name=" + x500name.toString());
} catch (IOException e) {
- CMS.debug("AuthTokenSubjectNameDefault: setValue " +
- e.toString());
+ CMS.debug("AuthTokenSubjectNameDefault: setValue " +
+ e.toString());
// failed to build x500 name
}
CMS.debug("AuthTokenSubjectNameDefault: setValue name=" + x500name.toString());
try {
- info.set(X509CertInfo.SUBJECT,
- new CertificateSubjectName(x500name));
+ info.set(X509CertInfo.SUBJECT,
+ new CertificateSubjectName(x500name));
} catch (Exception e) {
// failed to insert subject name
- CMS.debug("AuthTokenSubjectNameDefault: setValue " +
- e.toString());
+ CMS.debug("AuthTokenSubjectNameDefault: setValue " +
+ e.toString());
}
} else {
throw new EPropertyException(CMS.getUserMessage(locale,
@@ -101,8 +99,8 @@ public class AuthTokenSubjectNameDefault extends EnrollDefault {
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
+ X509CertInfo info)
+ throws EPropertyException {
if (name == null)
throw new EPropertyException("Invalid name " + name);
if (name.equals(VAL_NAME)) {
@@ -114,8 +112,8 @@ public class AuthTokenSubjectNameDefault extends EnrollDefault {
return sn.toString();
} catch (Exception e) {
// nothing
- CMS.debug("AuthTokenSubjectNameDefault: getValue " +
- e.toString());
+ CMS.debug("AuthTokenSubjectNameDefault: getValue " +
+ e.toString());
}
throw new EPropertyException(CMS.getUserMessage(locale,
"CMS_INVALID_PROPERTY", name));
@@ -126,7 +124,7 @@ public class AuthTokenSubjectNameDefault extends EnrollDefault {
}
public String getText(Locale locale) {
- return CMS.getUserMessage(locale,
+ return CMS.getUserMessage(locale,
"CMS_PROFILE_DEF_AUTHTOKEN_SUBJECT_NAME");
}
@@ -134,7 +132,7 @@ public class AuthTokenSubjectNameDefault extends EnrollDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
// authenticate the subject name and populate it
// to the certinfo
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/AuthorityKeyIdentifierExtDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/AuthorityKeyIdentifierExtDefault.java
index 869deed2..d6606c2b 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/AuthorityKeyIdentifierExtDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/AuthorityKeyIdentifierExtDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.io.IOException;
import java.util.Locale;
@@ -35,12 +34,10 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements an enrollment default policy
- * that populates Authority Key Identifier extension
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates Authority
+ * Key Identifier extension into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class AuthorityKeyIdentifierExtDefault extends CAEnrollDefault {
@@ -56,29 +53,29 @@ public class AuthorityKeyIdentifierExtDefault extends CAEnrollDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_CRITICAL)) {
- return new Descriptor(IDescriptor.STRING,
+ return new Descriptor(IDescriptor.STRING,
IDescriptor.READONLY, null, CMS.getUserMessage(locale,
- "CMS_PROFILE_CRITICAL"));
+ "CMS_PROFILE_CRITICAL"));
} else if (name.equals(VAL_KEY_ID)) {
- return new Descriptor(IDescriptor.STRING,
+ return new Descriptor(IDescriptor.STRING,
IDescriptor.READONLY, null, CMS.getUserMessage(locale,
- "CMS_PROFILE_KEY_ID"));
+ "CMS_PROFILE_KEY_ID"));
} else {
return null;
}
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
- if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ X509CertInfo info, String value)
+ throws EPropertyException {
+ if (name == null) {
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
if (name.equals(VAL_CRITICAL)) {
@@ -86,40 +83,38 @@ public class AuthorityKeyIdentifierExtDefault extends CAEnrollDefault {
} else if (name.equals(VAL_KEY_ID)) {
// do nothing for read only value
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
- if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ X509CertInfo info)
+ throws EPropertyException {
+ if (name == null) {
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
-
AuthorityKeyIdentifierExtension ext =
(AuthorityKeyIdentifierExtension) getExtension(
- PKIXExtensions.AuthorityKey_Id.toString(), info);
+ PKIXExtensions.AuthorityKey_Id.toString(), info);
- if(ext == null)
- {
+ if (ext == null) {
try {
- populate(null,info);
+ populate(null, info);
} catch (EProfileException e) {
CMS.debug("BasicConstraintsExtDefault: getValue " + e.toString());
- throw new EPropertyException(CMS.getUserMessage(
- locale, "CMS_INVALID_PROPERTY", name));
+ throw new EPropertyException(CMS.getUserMessage(
+ locale, "CMS_INVALID_PROPERTY", name));
}
}
if (name.equals(VAL_CRITICAL)) {
- ext =
- (AuthorityKeyIdentifierExtension) getExtension(
- PKIXExtensions.AuthorityKey_Id.toString(), info);
+ ext =
+ (AuthorityKeyIdentifierExtension) getExtension(
+ PKIXExtensions.AuthorityKey_Id.toString(), info);
if (ext == null) {
return null;
@@ -131,8 +126,8 @@ public class AuthorityKeyIdentifierExtDefault extends CAEnrollDefault {
}
} else if (name.equals(VAL_KEY_ID)) {
ext =
- (AuthorityKeyIdentifierExtension) getExtension(
- PKIXExtensions.AuthorityKey_Id.toString(), info);
+ (AuthorityKeyIdentifierExtension) getExtension(
+ PKIXExtensions.AuthorityKey_Id.toString(), info);
if (ext == null) {
// do something here
@@ -147,11 +142,11 @@ public class AuthorityKeyIdentifierExtDefault extends CAEnrollDefault {
//
CMS.debug(e.toString());
}
- if (kid == null)
+ if (kid == null)
return "";
return toHexString(kid.getIdentifier());
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
@@ -164,7 +159,7 @@ public class AuthorityKeyIdentifierExtDefault extends CAEnrollDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
AuthorityKeyIdentifierExtension ext = createExtension(info);
addExtension(PKIXExtensions.AuthorityKey_Id.toString(), ext, info);
@@ -174,9 +169,9 @@ public class AuthorityKeyIdentifierExtDefault extends CAEnrollDefault {
KeyIdentifier kid = null;
String localKey = getConfig("localKey");
if (localKey != null && localKey.equals("true")) {
- kid = getKeyIdentifier(info);
+ kid = getKeyIdentifier(info);
} else {
- kid = getCAKeyIdentifier();
+ kid = getCAKeyIdentifier();
}
if (kid == null)
@@ -186,8 +181,8 @@ public class AuthorityKeyIdentifierExtDefault extends CAEnrollDefault {
try {
ext = new AuthorityKeyIdentifierExtension(false, kid, null, null);
} catch (IOException e) {
- CMS.debug("AuthorityKeyIdentifierExtDefault: createExtension " +
- e.toString());
+ CMS.debug("AuthorityKeyIdentifierExtDefault: createExtension " +
+ e.toString());
}
return ext;
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/AutoAssignDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/AutoAssignDefault.java
index 7ab05d75..ddb9c4a8 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/AutoAssignDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/AutoAssignDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.util.Locale;
import netscape.security.x509.X509CertInfo;
@@ -31,11 +30,10 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements an enrollment default policy
- * that automatically assign request to agent.
- *
+ * This class implements an enrollment default policy that automatically assign
+ * request to agent.
+ *
* @version $Revision$, $Date$
*/
public class AutoAssignDefault extends EnrollDefault {
@@ -48,15 +46,15 @@ public class AutoAssignDefault extends EnrollDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
- if (name.equals(CONFIG_ASSIGN_TO)) {
- return new Descriptor(IDescriptor.STRING,
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ if (name.equals(CONFIG_ASSIGN_TO)) {
+ return new Descriptor(IDescriptor.STRING,
null, "admin", CMS.getUserMessage(locale,
- "CMS_PROFILE_AUTO_ASSIGN"));
+ "CMS_PROFILE_AUTO_ASSIGN"));
} else {
return null;
}
@@ -67,29 +65,29 @@ public class AutoAssignDefault extends EnrollDefault {
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
+ X509CertInfo info)
+ throws EPropertyException {
return null;
}
public String getText(Locale locale) {
return CMS.getUserMessage(locale, "CMS_PROFILE_DEF_AUTO_ASSIGN",
- getConfig(CONFIG_ASSIGN_TO));
+ getConfig(CONFIG_ASSIGN_TO));
}
/**
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
try {
- request.setRequestOwner(
- mapPattern(request, getConfig(CONFIG_ASSIGN_TO)));
+ request.setRequestOwner(
+ mapPattern(request, getConfig(CONFIG_ASSIGN_TO)));
} catch (Exception e) {
// failed to insert subject name
CMS.debug("AutoAssignDefault: populate " + e.toString());
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/BasicConstraintsExtDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/BasicConstraintsExtDefault.java
index 8c5d8094..2665fa2c 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/BasicConstraintsExtDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/BasicConstraintsExtDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.io.IOException;
import java.util.Locale;
@@ -34,12 +33,10 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements an enrollment default policy
- * that populates Basic Constraint extension
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates Basic
+ * Constraint extension into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class BasicConstraintsExtDefault extends EnrollExtDefault {
@@ -64,21 +61,21 @@ public class BasicConstraintsExtDefault extends EnrollExtDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
if (name.equals(CONFIG_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.equals(CONFIG_IS_CA)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"true",
CMS.getUserMessage(locale, "CMS_PROFILE_IS_CA"));
} else if (name.equals(CONFIG_PATH_LEN)) {
- return new Descriptor(IDescriptor.INTEGER, null,
+ return new Descriptor(IDescriptor.INTEGER, null,
"-1",
CMS.getUserMessage(locale, "CMS_PROFILE_PATH_LEN"));
}
@@ -87,15 +84,15 @@ public class BasicConstraintsExtDefault extends EnrollExtDefault {
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.equals(VAL_IS_CA)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"true",
CMS.getUserMessage(locale, "CMS_PROFILE_IS_CA"));
} else if (name.equals(VAL_PATH_LEN)) {
- return new Descriptor(IDescriptor.INTEGER, null,
+ return new Descriptor(IDescriptor.INTEGER, null,
"-1",
CMS.getUserMessage(locale, "CMS_PROFILE_PATH_LEN"));
} else {
@@ -104,39 +101,37 @@ public class BasicConstraintsExtDefault extends EnrollExtDefault {
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
try {
BasicConstraintsExtension ext = null;
- if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ if (name == null) {
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
ext = (BasicConstraintsExtension)
getExtension(PKIXExtensions.BasicConstraints_Id.toString(), info);
- if(ext == null)
- {
- populate(null,info);
+ if (ext == null) {
+ populate(null, info);
}
if (name.equals(VAL_CRITICAL)) {
ext = (BasicConstraintsExtension)
getExtension(PKIXExtensions.BasicConstraints_Id.toString(), info);
- boolean val = Boolean.valueOf(value).booleanValue();
-
+ boolean val = Boolean.valueOf(value).booleanValue();
- if(ext == null) {
+ if (ext == null) {
return;
}
ext.setCritical(val);
} else if (name.equals(VAL_IS_CA)) {
ext = (BasicConstraintsExtension)
getExtension(PKIXExtensions.BasicConstraints_Id.toString(), info);
- if(ext == null) {
+ if (ext == null) {
return;
}
Boolean isCA = Boolean.valueOf(value);
@@ -146,7 +141,7 @@ public class BasicConstraintsExtDefault extends EnrollExtDefault {
ext = (BasicConstraintsExtension)
getExtension(PKIXExtensions.BasicConstraints_Id.toString(), info);
- if(ext == null) {
+ if (ext == null) {
return;
}
Integer pathLen = Integer.valueOf(value);
@@ -156,8 +151,8 @@ public class BasicConstraintsExtDefault extends EnrollExtDefault {
throw new EPropertyException("Invalid name " + name);
}
replaceExtension(PKIXExtensions.BasicConstraints_Id.toString(),
- ext, info);
- } catch (IOException e) {
+ ext, info);
+ } catch (IOException e) {
CMS.debug("BasicConstraintsExtDefault: setValue " + e.toString());
throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
@@ -169,35 +164,34 @@ public class BasicConstraintsExtDefault extends EnrollExtDefault {
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
+ X509CertInfo info)
+ throws EPropertyException {
try {
- if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ if (name == null) {
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
BasicConstraintsExtension ext = (BasicConstraintsExtension)
getExtension(PKIXExtensions.BasicConstraints_Id.toString(), info);
- if(ext == null)
- {
+ if (ext == null) {
CMS.debug("BasicConstraintsExtDefault: getValue ext is null, populating a new one ");
-
- try {
- populate(null,info);
+
+ try {
+ populate(null, info);
} catch (EProfileException e) {
CMS.debug("BasicConstraintsExtDefault: getValue " + e.toString());
- throw new EPropertyException(CMS.getUserMessage(
- locale, "CMS_INVALID_PROPERTY", name));
+ throw new EPropertyException(CMS.getUserMessage(
+ locale, "CMS_INVALID_PROPERTY", name));
}
}
if (name.equals(VAL_CRITICAL)) {
- ext = (BasicConstraintsExtension)
- getExtension(PKIXExtensions.BasicConstraints_Id.toString(), info);
+ ext = (BasicConstraintsExtension)
+ getExtension(PKIXExtensions.BasicConstraints_Id.toString(), info);
if (ext == null) {
return null;
@@ -208,8 +202,8 @@ public class BasicConstraintsExtDefault extends EnrollExtDefault {
return "false";
}
} else if (name.equals(VAL_IS_CA)) {
- ext = (BasicConstraintsExtension)
- getExtension(PKIXExtensions.BasicConstraints_Id.toString(), info);
+ ext = (BasicConstraintsExtension)
+ getExtension(PKIXExtensions.BasicConstraints_Id.toString(), info);
if (ext == null) {
return null;
@@ -218,41 +212,41 @@ public class BasicConstraintsExtDefault extends EnrollExtDefault {
return isCA.toString();
} else if (name.equals(VAL_PATH_LEN)) {
- ext = (BasicConstraintsExtension)
- getExtension(PKIXExtensions.BasicConstraints_Id.toString(), info);
+ ext = (BasicConstraintsExtension)
+ getExtension(PKIXExtensions.BasicConstraints_Id.toString(), info);
if (ext == null) {
return null;
}
Integer pathLen = (Integer)
- ext.get(BasicConstraintsExtension.PATH_LEN);
-
+ ext.get(BasicConstraintsExtension.PATH_LEN);
String pLen = null;
pLen = pathLen.toString();
- if(pLen.equals("-2"))
- {
- //This is done for bug 621700. Profile constraints actually checks for -1
- //The low level security class for some reason sets this to -2
- //This will allow the request to be approved successfuly by the agent.
+ if (pLen.equals("-2")) {
+ // This is done for bug 621700. Profile constraints actually
+ // checks for -1
+ // The low level security class for some reason sets this to
+ // -2
+ // This will allow the request to be approved successfuly by
+ // the agent.
- pLen = "-1";
+ pLen = "-1";
}
-
+
CMS.debug("BasicConstriantsExtDefault getValue(pLen) " + pLen);
-
+
return pLen;
-
- } else {
- throw new EPropertyException(CMS.getUserMessage(
+ } else {
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
} catch (IOException e) {
CMS.debug("BasicConstraintsExtDefault: getValue " + e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
@@ -271,11 +265,11 @@ public class BasicConstraintsExtDefault extends EnrollExtDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
BasicConstraintsExtension ext = createExtension();
addExtension(PKIXExtensions.BasicConstraints_Id.toString(), ext,
- info);
+ info);
}
public BasicConstraintsExtension createExtension() {
@@ -287,8 +281,7 @@ public class BasicConstraintsExtDefault extends EnrollExtDefault {
int pathLen = -2;
-
- if(!pathLenStr.equals("") ) {
+ if (!pathLenStr.equals("")) {
pathLen = Integer.valueOf(pathLenStr).intValue();
}
@@ -296,8 +289,8 @@ public class BasicConstraintsExtDefault extends EnrollExtDefault {
try {
ext = new BasicConstraintsExtension(isCA, critical, pathLen);
} catch (Exception e) {
- CMS.debug("BasicConstraintsExtDefault: createExtension " +
- e.toString());
+ CMS.debug("BasicConstraintsExtDefault: createExtension " +
+ e.toString());
return null;
}
ext.setCritical(critical);
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/CAEnrollDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/CAEnrollDefault.java
index 4b883f7f..38a74bf0 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/CAEnrollDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/CAEnrollDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@@ -34,12 +33,10 @@ import netscape.security.x509.X509Key;
import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.ca.ICertificateAuthority;
-
/**
- * This class implements an abstract CA specific
- * Enrollment default. This policy can only be
- * used with CA subsystem.
- *
+ * This class implements an abstract CA specific Enrollment default. This policy
+ * can only be used with CA subsystem.
+ *
* @version $Revision$, $Date$
*/
public abstract class CAEnrollDefault extends EnrollDefault {
@@ -48,8 +45,8 @@ public abstract class CAEnrollDefault extends EnrollDefault {
public KeyIdentifier getKeyIdentifier(X509CertInfo info) {
try {
- CertificateX509Key ckey = (CertificateX509Key)
- info.get(X509CertInfo.KEY);
+ CertificateX509Key ckey = (CertificateX509Key)
+ info.get(X509CertInfo.KEY);
X509Key key = (X509Key) ckey.get(CertificateX509Key.KEY);
MessageDigest md = MessageDigest.getInstance("SHA-1");
@@ -59,35 +56,35 @@ public abstract class CAEnrollDefault extends EnrollDefault {
return new KeyIdentifier(hash);
} catch (IOException e) {
CMS.debug("AuthorityKeyIdentifierExtDefault: getKeyId " +
- e.toString());
+ e.toString());
} catch (CertificateException e) {
CMS.debug("AuthorityKeyIdentifierExtDefault: getKeyId " +
- e.toString());
+ e.toString());
} catch (NoSuchAlgorithmException e) {
CMS.debug("AuthorityKeyIdentifierExtDefault: getKeyId " +
- e.toString());
+ e.toString());
}
return null;
}
public KeyIdentifier getCAKeyIdentifier() {
ICertificateAuthority ca = (ICertificateAuthority)
- CMS.getSubsystem(CMS.SUBSYSTEM_CA);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CA);
X509CertImpl caCert = ca.getCACert();
if (caCert == null) {
- // during configuration, we dont have the CA certificate
- return null;
+ // during configuration, we dont have the CA certificate
+ return null;
}
X509Key key = (X509Key) caCert.getPublicKey();
SubjectKeyIdentifierExtension subjKeyIdExt =
- (SubjectKeyIdentifierExtension)
- caCert.getExtension(PKIXExtensions.SubjectKey_Id.toString());
+ (SubjectKeyIdentifierExtension)
+ caCert.getExtension(PKIXExtensions.SubjectKey_Id.toString());
if (subjKeyIdExt != null) {
try {
- KeyIdentifier keyId = (KeyIdentifier) subjKeyIdExt.get(
- SubjectKeyIdentifierExtension.KEY_ID);
- return keyId;
+ KeyIdentifier keyId = (KeyIdentifier) subjKeyIdExt.get(
+ SubjectKeyIdentifierExtension.KEY_ID);
+ return keyId;
} catch (IOException e) {
}
}
@@ -101,7 +98,7 @@ public abstract class CAEnrollDefault extends EnrollDefault {
return new KeyIdentifier(hash);
} catch (NoSuchAlgorithmException e) {
CMS.debug("AuthorityKeyIdentifierExtDefault: getKeyId " +
- e.toString());
+ e.toString());
}
return null;
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/CAValidityDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/CAValidityDefault.java
index 8bf4c75f..01f9bd65 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/CAValidityDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/CAValidityDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.io.IOException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
@@ -39,21 +38,19 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements a CA signing cert enrollment default policy
- * that populates a server-side configurable validity
- * into the certificate template.
+ * This class implements a CA signing cert enrollment default policy that
+ * populates a server-side configurable validity into the certificate template.
* It allows an agent to bypass the CA's signing cert's expiration constraint
*/
public class CAValidityDefault extends EnrollDefault {
public static final String CONFIG_RANGE = "range";
public static final String CONFIG_START_TIME = "startTime";
- public static final String CONFIG_BYPASS_CA_NOTAFTER= "bypassCAnotafter";
+ public static final String CONFIG_BYPASS_CA_NOTAFTER = "bypassCAnotafter";
public static final String VAL_NOT_BEFORE = "notBefore";
public static final String VAL_NOT_AFTER = "notAfter";
- public static final String VAL_BYPASS_CA_NOTAFTER= "bypassCAnotafter";
+ public static final String VAL_BYPASS_CA_NOTAFTER = "bypassCAnotafter";
public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
@@ -72,28 +69,28 @@ public class CAValidityDefault extends EnrollDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
mCA = (ICertificateAuthority)
- CMS.getSubsystem(CMS.SUBSYSTEM_CA);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CA);
}
public void setConfig(String name, String value)
- throws EPropertyException {
+ throws EPropertyException {
if (name.equals(CONFIG_RANGE)) {
- try {
- Integer.parseInt(value);
- } catch (Exception e) {
+ try {
+ Integer.parseInt(value);
+ } catch (Exception e) {
throw new EPropertyException(CMS.getUserMessage(
"CMS_INVALID_PROPERTY", CONFIG_RANGE));
- }
+ }
} else if (name.equals(CONFIG_START_TIME)) {
- try {
- Integer.parseInt(value);
- } catch (Exception e) {
+ try {
+ Integer.parseInt(value);
+ } catch (Exception e) {
throw new EPropertyException(CMS.getUserMessage(
"CMS_INVALID_PROPERTY", CONFIG_START_TIME));
- }
+ }
}
super.setConfig(name, value);
}
@@ -101,16 +98,16 @@ public class CAValidityDefault extends EnrollDefault {
public IDescriptor getConfigDescriptor(Locale locale, String name) {
if (name.equals(CONFIG_RANGE)) {
return new Descriptor(IDescriptor.STRING,
- null,
+ null,
"2922", /* 8 years */
CMS.getUserMessage(locale,
- "CMS_PROFILE_VALIDITY_RANGE"));
+ "CMS_PROFILE_VALIDITY_RANGE"));
} else if (name.equals(CONFIG_START_TIME)) {
return new Descriptor(IDescriptor.STRING,
- null,
+ null,
"60", /* 1 minute */
CMS.getUserMessage(locale,
- "CMS_PROFILE_VALIDITY_START_TIME"));
+ "CMS_PROFILE_VALIDITY_START_TIME"));
} else if (name.equals(CONFIG_BYPASS_CA_NOTAFTER)) {
return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
@@ -138,21 +135,21 @@ public class CAValidityDefault extends EnrollDefault {
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
- if (name == null) {
+ X509CertInfo info, String value)
+ throws EPropertyException {
+ if (name == null) {
throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
- if (value == null || value.equals("")) {
+ if (value == null || value.equals("")) {
throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
- CMS.debug("CAValidityDefault: setValue name= "+ name);
+ CMS.debug("CAValidityDefault: setValue name= " + name);
if (name.equals(VAL_NOT_BEFORE)) {
- SimpleDateFormat formatter =
- new SimpleDateFormat(DATE_FORMAT);
+ SimpleDateFormat formatter =
+ new SimpleDateFormat(DATE_FORMAT);
ParsePosition pos = new ParsePosition(0);
Date date = formatter.parse(value, pos);
CertificateValidity validity = null;
@@ -161,15 +158,15 @@ public class CAValidityDefault extends EnrollDefault {
validity = (CertificateValidity)
info.get(X509CertInfo.VALIDITY);
validity.set(CertificateValidity.NOT_BEFORE,
- date);
+ date);
} catch (Exception e) {
CMS.debug("CAValidityDefault: setValue " + e.toString());
throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
} else if (name.equals(VAL_NOT_AFTER)) {
- SimpleDateFormat formatter =
- new SimpleDateFormat(DATE_FORMAT);
+ SimpleDateFormat formatter =
+ new SimpleDateFormat(DATE_FORMAT);
ParsePosition pos = new ParsePosition(0);
Date date = formatter.parse(value, pos);
CertificateValidity validity = null;
@@ -178,7 +175,7 @@ public class CAValidityDefault extends EnrollDefault {
validity = (CertificateValidity)
info.get(X509CertInfo.VALIDITY);
validity.set(CertificateValidity.NOT_AFTER,
- date);
+ date);
} catch (Exception e) {
CMS.debug("CAValidityDefault: setValue " + e.toString());
throw new EPropertyException(CMS.getUserMessage(
@@ -186,23 +183,23 @@ public class CAValidityDefault extends EnrollDefault {
}
} else if (name.equals(VAL_BYPASS_CA_NOTAFTER)) {
boolean bypassCAvalidity = Boolean.valueOf(value).booleanValue();
- CMS.debug("CAValidityDefault: setValue: bypassCAvalidity="+ bypassCAvalidity);
+ CMS.debug("CAValidityDefault: setValue: bypassCAvalidity=" + bypassCAvalidity);
BasicConstraintsExtension ext = (BasicConstraintsExtension)
getExtension(PKIXExtensions.BasicConstraints_Id.toString(), info);
- if(ext == null) {
+ if (ext == null) {
CMS.debug("CAValidityDefault: setValue: this default cannot be applied to non-CA cert.");
return;
}
try {
Boolean isCA = (Boolean) ext.get(BasicConstraintsExtension.IS_CA);
- if(isCA.booleanValue() != true) {
+ if (isCA.booleanValue() != true) {
CMS.debug("CAValidityDefault: setValue: this default cannot be aplied to non-CA cert.");
return;
}
} catch (Exception e) {
- CMS.debug("CAValidityDefault: setValue: this default cannot be aplied to non-CA cert."+ e.toString());
+ CMS.debug("CAValidityDefault: setValue: this default cannot be aplied to non-CA cert." + e.toString());
return;
}
@@ -210,7 +207,7 @@ public class CAValidityDefault extends EnrollDefault {
Date notAfter = null;
try {
validity = (CertificateValidity)
- info.get(X509CertInfo.VALIDITY);
+ info.get(X509CertInfo.VALIDITY);
notAfter = (Date) validity.get(CertificateValidity.NOT_AFTER);
} catch (Exception e) {
CMS.debug("CAValidityDefault: setValue " + e.toString());
@@ -220,7 +217,7 @@ public class CAValidityDefault extends EnrollDefault {
// not to exceed CA's expiration
Date caNotAfter =
- mCA.getSigningUnit().getCertImpl().getNotAfter();
+ mCA.getSigningUnit().getCertImpl().getNotAfter();
if (notAfter.after(caNotAfter)) {
if (bypassCAvalidity == false) {
@@ -232,7 +229,7 @@ public class CAValidityDefault extends EnrollDefault {
}
try {
validity.set(CertificateValidity.NOT_AFTER,
- notAfter);
+ notAfter);
} catch (Exception e) {
CMS.debug("CAValidityDefault: setValue " + e.toString());
throw new EPropertyException(CMS.getUserMessage(
@@ -243,19 +240,19 @@ public class CAValidityDefault extends EnrollDefault {
locale, "CMS_INVALID_PROPERTY", name));
}
}
-
+
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
+ X509CertInfo info)
+ throws EPropertyException {
if (name == null)
throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
- CMS.debug("CAValidityDefault: getValue: name= "+ name);
+ CMS.debug("CAValidityDefault: getValue: name= " + name);
if (name.equals(VAL_NOT_BEFORE)) {
- SimpleDateFormat formatter =
- new SimpleDateFormat(DATE_FORMAT);
+ SimpleDateFormat formatter =
+ new SimpleDateFormat(DATE_FORMAT);
CertificateValidity validity = null;
try {
@@ -269,8 +266,8 @@ public class CAValidityDefault extends EnrollDefault {
locale, "CMS_INVALID_PROPERTY", name));
}
} else if (name.equals(VAL_NOT_AFTER)) {
- SimpleDateFormat formatter =
- new SimpleDateFormat(DATE_FORMAT);
+ SimpleDateFormat formatter =
+ new SimpleDateFormat(DATE_FORMAT);
CertificateValidity validity = null;
try {
@@ -298,19 +295,19 @@ public class CAValidityDefault extends EnrollDefault {
getConfig(CONFIG_BYPASS_CA_NOTAFTER)
};
- return CMS.getUserMessage(locale, "CMS_PROFILE_DEF_VALIDITY", params);
+ return CMS.getUserMessage(locale, "CMS_PROFILE_DEF_VALIDITY", params);
}
/**
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
// always + 60 seconds
String startTimeStr = getConfig(CONFIG_START_TIME);
try {
- startTimeStr = mapPattern(request, startTimeStr);
+ startTimeStr = mapPattern(request, startTimeStr);
} catch (IOException e) {
CMS.debug("CAValidityDefault: populate " + e.toString());
}
@@ -325,7 +322,7 @@ public class CAValidityDefault extends EnrollDefault {
try {
String rangeStr = getConfig(CONFIG_RANGE);
rangeStr = mapPattern(request, rangeStr);
- notAfterVal = notBefore.getTime() +
+ notAfterVal = notBefore.getTime() +
(mDefault * Integer.parseInt(rangeStr));
} catch (Exception e) {
// configured value is not correct
@@ -335,8 +332,8 @@ public class CAValidityDefault extends EnrollDefault {
}
Date notAfter = new Date(notAfterVal);
- CertificateValidity validity =
- new CertificateValidity(notBefore, notAfter);
+ CertificateValidity validity =
+ new CertificateValidity(notBefore, notAfter);
try {
info.set(X509CertInfo.VALIDITY, validity);
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/CRLDistributionPointsExtDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/CRLDistributionPointsExtDefault.java
index 5a551033..5b500c53 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/CRLDistributionPointsExtDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/CRLDistributionPointsExtDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.io.IOException;
import java.util.Enumeration;
import java.util.Locale;
@@ -45,12 +44,10 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements an enrollment default policy
- * that populates a CRL Distribution points extension
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates a CRL
+ * Distribution points extension into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class CRLDistributionPointsExtDefault extends EnrollExtDefault {
@@ -84,32 +81,31 @@ public class CRLDistributionPointsExtDefault extends EnrollExtDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
refreshConfigAndValueNames();
}
- public void setConfig(String name, String value)
- throws EPropertyException {
+ public void setConfig(String name, String value)
+ throws EPropertyException {
int num = 0;
if (name.equals(CONFIG_NUM_POINTS)) {
- try {
- num = Integer.parseInt(value);
+ try {
+ num = Integer.parseInt(value);
- if (num >= MAX_NUM_POINTS || num < 0) {
- throw new EPropertyException(CMS.getUserMessage(
+ if (num >= MAX_NUM_POINTS || num < 0) {
+ throw new EPropertyException(CMS.getUserMessage(
"CMS_INVALID_PROPERTY", CONFIG_NUM_POINTS));
- }
+ }
- } catch (Exception e) {
+ } catch (Exception e) {
throw new EPropertyException(CMS.getUserMessage(
"CMS_INVALID_PROPERTY", CONFIG_NUM_POINTS));
- }
+ }
}
super.setConfig(name, value);
}
-
public Enumeration<String> getConfigNames() {
refreshConfigAndValueNames();
return super.getConfigNames();
@@ -147,39 +143,39 @@ public class CRLDistributionPointsExtDefault extends EnrollExtDefault {
}
}
- if (num >= MAX_NUM_POINTS)
+ if (num >= MAX_NUM_POINTS)
num = DEF_NUM_POINTS;
return num;
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
- if (name.equals(CONFIG_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ if (name.equals(CONFIG_CRITICAL)) {
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.startsWith(CONFIG_POINT_TYPE)) {
- return new Descriptor(IDescriptor.STRING, null,
+ return new Descriptor(IDescriptor.STRING, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_POINT_TYPE"));
} else if (name.startsWith(CONFIG_POINT_NAME)) {
- return new Descriptor(IDescriptor.STRING, null,
+ return new Descriptor(IDescriptor.STRING, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_POINT_NAME"));
} else if (name.startsWith(CONFIG_REASONS)) {
- return new Descriptor(IDescriptor.STRING, null,
+ return new Descriptor(IDescriptor.STRING, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_REASONS"));
} else if (name.startsWith(CONFIG_ISSUER_TYPE)) {
- return new Descriptor(IDescriptor.STRING, null,
+ return new Descriptor(IDescriptor.STRING, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_ISSUER_TYPE"));
} else if (name.startsWith(CONFIG_ISSUER_NAME)) {
- return new Descriptor(IDescriptor.STRING, null,
+ return new Descriptor(IDescriptor.STRING, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_ISSUER_NAME"));
} else if (name.startsWith(CONFIG_ENABLE)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_ENABLE"));
} else if (name.startsWith(CONFIG_NUM_POINTS)) {
@@ -193,12 +189,12 @@ public class CRLDistributionPointsExtDefault extends EnrollExtDefault {
}
public IDescriptor getValueDescriptor(Locale locale, String name) {
- if (name.equals(VAL_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ if (name.equals(VAL_CRITICAL)) {
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.equals(VAL_CRL_DISTRIBUTION_POINTS)) {
- return new Descriptor(IDescriptor.STRING_LIST, null,
+ return new Descriptor(IDescriptor.STRING_LIST, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_CRL_DISTRIBUTION_POINTS"));
} else {
@@ -207,47 +203,45 @@ public class CRLDistributionPointsExtDefault extends EnrollExtDefault {
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
try {
CRLDistributionPointsExtension ext = null;
- if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ if (name == null) {
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
ext = (CRLDistributionPointsExtension)
getExtension(PKIXExtensions.CRLDistributionPoints_Id.toString(),
- info);
+ info);
- if(ext == null) {
- populate(locale,info);
+ if (ext == null) {
+ populate(locale, info);
}
if (name.equals(VAL_CRITICAL)) {
ext = (CRLDistributionPointsExtension)
- getExtension(PKIXExtensions.CRLDistributionPoints_Id.toString(),
- info);
+ getExtension(PKIXExtensions.CRLDistributionPoints_Id.toString(),
+ info);
boolean val = Boolean.valueOf(value).booleanValue();
- if(ext == null)
- {
+ if (ext == null) {
return;
}
- ext.setCritical(val);
- } else if (name.equals(VAL_CRL_DISTRIBUTION_POINTS)) {
+ ext.setCritical(val);
+ } else if (name.equals(VAL_CRL_DISTRIBUTION_POINTS)) {
ext = (CRLDistributionPointsExtension)
- getExtension(PKIXExtensions.CRLDistributionPoints_Id.toString(),
- info);
+ getExtension(PKIXExtensions.CRLDistributionPoints_Id.toString(),
+ info);
- if(ext == null)
- {
+ if (ext == null) {
return;
}
Vector<NameValuePairs> v = parseRecords(value);
int size = v.size();
-
+
boolean critical = ext.isCritical();
int i = 0;
@@ -285,7 +279,7 @@ public class CRLDistributionPointsExtDefault extends EnrollExtDefault {
if (issuerType != null)
addIssuer(locale, cdp, issuerType, issuerValue);
- // this is the first distribution point
+ // this is the first distribution point
if (i == 0) {
ext = new CRLDistributionPointsExtension(cdp);
ext.setCritical(critical);
@@ -295,51 +289,51 @@ public class CRLDistributionPointsExtDefault extends EnrollExtDefault {
}
}
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
replaceExtension(PKIXExtensions.CRLDistributionPoints_Id.toString(),
- ext, info);
+ ext, info);
} catch (EProfileException e) {
- CMS.debug("CRLDistributionPointsExtDefault: setValue " +
- e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ CMS.debug("CRLDistributionPointsExtDefault: setValue " +
+ e.toString());
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
private void addCRLPoint(Locale locale, CRLDistributionPoint cdp, String type,
- String value) throws EPropertyException {
+ String value) throws EPropertyException {
try {
if (value == null || value.length() == 0)
return;
-
+
if (type.equals(RELATIVETOISSUER)) {
cdp.setRelativeName(new RDN(value));
} else if (isGeneralNameType(type)) {
GeneralNames gen = new GeneralNames();
- gen.addElement(parseGeneralName(type,value));
+ gen.addElement(parseGeneralName(type, value));
cdp.setFullName(gen);
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", type));
}
} catch (IOException e) {
- CMS.debug("CRLDistributionPointsExtDefault: addCRLPoint " +
- e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ CMS.debug("CRLDistributionPointsExtDefault: addCRLPoint " +
+ e.toString());
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", type));
} catch (GeneralNamesException e) {
- CMS.debug("CRLDistributionPointsExtDefault: addCRLPoint " +
- e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ CMS.debug("CRLDistributionPointsExtDefault: addCRLPoint " +
+ e.toString());
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", type));
}
}
private void addIssuer(Locale locale, CRLDistributionPoint cdp, String type,
- String value) throws EPropertyException {
+ String value) throws EPropertyException {
if (value == null || value.length() == 0)
return;
try {
@@ -349,20 +343,20 @@ public class CRLDistributionPointsExtDefault extends EnrollExtDefault {
gen.addElement(parseGeneralName(type, value));
cdp.setCRLIssuer(gen);
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", type));
}
} catch (IOException e) {
- CMS.debug("CRLDistributionPointsExtDefault: addIssuer " +
- e.toString());
+ CMS.debug("CRLDistributionPointsExtDefault: addIssuer " +
+ e.toString());
} catch (GeneralNamesException e) {
- CMS.debug("CRLDistributionPointsExtDefault: addIssuer " +
- e.toString());
+ CMS.debug("CRLDistributionPointsExtDefault: addIssuer " +
+ e.toString());
}
}
- private void addReasons(Locale locale, CRLDistributionPoint cdp, String type,
- String value) throws EPropertyException {
+ private void addReasons(Locale locale, CRLDistributionPoint cdp, String type,
+ String value) throws EPropertyException {
if (value == null || value.length() == 0)
return;
if (type.equals(REASONS)) {
@@ -376,7 +370,7 @@ public class CRLDistributionPointsExtDefault extends EnrollExtDefault {
if (r == null) {
CMS.debug("CRLDistributeionPointsExtDefault: addReasons Unknown reason: " + s);
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", s));
} else {
reasonBits |= r.getBitMask();
@@ -384,47 +378,46 @@ public class CRLDistributionPointsExtDefault extends EnrollExtDefault {
}
if (reasonBits != 0) {
- BitArray ba = new BitArray(8, new byte[] {reasonBits}
- );
+ BitArray ba = new BitArray(8, new byte[] { reasonBits }
+ );
cdp.setReasons(ba);
}
}
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", type));
}
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
+ X509CertInfo info)
+ throws EPropertyException {
CRLDistributionPointsExtension ext = null;
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
ext = (CRLDistributionPointsExtension)
getExtension(PKIXExtensions.CRLDistributionPoints_Id.toString(),
- info);
+ info);
- if(ext == null)
- {
+ if (ext == null) {
try {
- populate(locale,info);
+ populate(locale, info);
} catch (EProfileException e) {
- throw new EPropertyException(CMS.getUserMessage(
- locale, "CMS_INVALID_PROPERTY", name));
+ throw new EPropertyException(CMS.getUserMessage(
+ locale, "CMS_INVALID_PROPERTY", name));
}
}
if (name.equals(VAL_CRITICAL)) {
ext = (CRLDistributionPointsExtension)
- getExtension(PKIXExtensions.CRLDistributionPoints_Id.toString(),
- info);
+ getExtension(PKIXExtensions.CRLDistributionPoints_Id.toString(),
+ info);
if (ext == null) {
return null;
@@ -434,10 +427,10 @@ public class CRLDistributionPointsExtDefault extends EnrollExtDefault {
} else {
return "false";
}
- } else if (name.equals(VAL_CRL_DISTRIBUTION_POINTS)) {
+ } else if (name.equals(VAL_CRL_DISTRIBUTION_POINTS)) {
ext = (CRLDistributionPointsExtension)
- getExtension(PKIXExtensions.CRLDistributionPoints_Id.toString(),
- info);
+ getExtension(PKIXExtensions.CRLDistributionPoints_Id.toString(),
+ info);
if (ext == null)
return "";
@@ -451,7 +444,7 @@ public class CRLDistributionPointsExtDefault extends EnrollExtDefault {
NameValuePairs pairs = null;
if (i < ext.getNumPoints()) {
- CRLDistributionPoint p = ext.getPointAt(i);
+ CRLDistributionPoint p = ext.getPointAt(i);
GeneralNames gns = p.getFullName();
pairs = buildGeneralNames(gns, p);
@@ -461,10 +454,10 @@ public class CRLDistributionPointsExtDefault extends EnrollExtDefault {
recs.addElement(pairs);
}
}
-
+
return buildRecords(recs);
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
@@ -482,7 +475,7 @@ public class CRLDistributionPointsExtDefault extends EnrollExtDefault {
}
protected NameValuePairs buildGeneralNames(GeneralNames gns, CRLDistributionPoint p)
- throws EPropertyException {
+ throws EPropertyException {
NameValuePairs pairs = new NameValuePairs();
@@ -551,14 +544,14 @@ public class CRLDistributionPointsExtDefault extends EnrollExtDefault {
if (reasons != null) {
byte[] b = reasons.toByteArray();
Reason[] reasonArray = Reason.bitArrayToReasonArray(b);
-
+
for (int i = 0; i < reasonArray.length; i++) {
if (sb.length() > 0)
sb.append(",");
sb.append(reasonArray[i].getName());
}
}
-
+
return sb.toString();
}
@@ -589,8 +582,8 @@ public class CRLDistributionPointsExtDefault extends EnrollExtDefault {
sb.append(getConfig(CONFIG_ENABLE + i));
sb.append("}");
}
- return CMS.getUserMessage(locale,
- "CMS_PROFILE_DEF_CRL_DIST_POINTS_EXT",
+ return CMS.getUserMessage(locale,
+ "CMS_PROFILE_DEF_CRL_DIST_POINTS_EXT",
getConfig(CONFIG_CRITICAL),
sb.toString());
}
@@ -599,29 +592,30 @@ public class CRLDistributionPointsExtDefault extends EnrollExtDefault {
* Populates the request with this policy default.
*/
private void populate(Locale locale, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
CRLDistributionPointsExtension ext = createExtension(locale);
if (ext == null)
return;
addExtension(PKIXExtensions.CRLDistributionPoints_Id.toString(),
- ext, info);
+ ext, info);
}
+
/**
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
CRLDistributionPointsExtension ext = createExtension(request);
if (ext == null)
return;
- addExtension(PKIXExtensions.CRLDistributionPoints_Id.toString(),
- ext, info);
+ addExtension(PKIXExtensions.CRLDistributionPoints_Id.toString(),
+ ext, info);
}
public CRLDistributionPointsExtension createExtension(IRequest request) {
- CRLDistributionPointsExtension ext = null;
+ CRLDistributionPointsExtension ext = null;
int num = 0;
try {
@@ -631,8 +625,8 @@ public class CRLDistributionPointsExtDefault extends EnrollExtDefault {
for (int i = 0; i < num; i++) {
CRLDistributionPoint cdp = new CRLDistributionPoint();
- String enable = getConfig(CONFIG_ENABLE + i);
- String pointType = getConfig(CONFIG_POINT_TYPE + i);
+ String enable = getConfig(CONFIG_ENABLE + i);
+ String pointType = getConfig(CONFIG_POINT_TYPE + i);
String pointName = getConfig(CONFIG_POINT_NAME + i);
String reasons = getConfig(CONFIG_REASONS + i);
String issuerType = getConfig(CONFIG_ISSUER_TYPE + i);
@@ -644,7 +638,7 @@ public class CRLDistributionPointsExtDefault extends EnrollExtDefault {
if (issuerType != null)
addIssuer(getLocale(request), cdp, issuerType, issuerName);
if (reasons != null)
- addReasons(getLocale(request), cdp, REASONS, reasons);
+ addReasons(getLocale(request), cdp, REASONS, reasons);
if (i == 0) {
ext = new CRLDistributionPointsExtension(cdp);
@@ -656,7 +650,7 @@ public class CRLDistributionPointsExtDefault extends EnrollExtDefault {
}
} catch (Exception e) {
CMS.debug("CRLDistribtionPointsExtDefault: createExtension " +
- e.toString());
+ e.toString());
CMS.debug(e);
}
@@ -698,7 +692,7 @@ public class CRLDistributionPointsExtDefault extends EnrollExtDefault {
}
} catch (Exception e) {
CMS.debug("CRLDistribtionPointsExtDefault: createExtension " +
- e.toString());
+ e.toString());
CMS.debug(e);
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/CertificatePoliciesExtDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/CertificatePoliciesExtDefault.java
index 63a4d303..416da61b 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/CertificatePoliciesExtDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/CertificatePoliciesExtDefault.java
@@ -1,4 +1,3 @@
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -18,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
@@ -49,10 +47,9 @@ import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
/**
- * This class implements an enrollment default policy
- * that populates a policy mappings extension
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates a policy
+ * mappings extension into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class CertificatePoliciesExtDefault extends EnrollExtDefault {
@@ -122,33 +119,32 @@ public class CertificatePoliciesExtDefault extends EnrollExtDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
refreshConfigAndValueNames();
}
public void setConfig(String name, String value)
- throws EPropertyException {
+ throws EPropertyException {
int num = 0;
if (name.equals(CONFIG_POLICY_NUM)) {
- try {
- num = Integer.parseInt(value);
+ try {
+ num = Integer.parseInt(value);
- if (num >= MAX_NUM_POLICIES || num < 0) {
- throw new EPropertyException(CMS.getUserMessage(
+ if (num >= MAX_NUM_POLICIES || num < 0) {
+ throw new EPropertyException(CMS.getUserMessage(
"CMS_INVALID_PROPERTY", CONFIG_POLICY_NUM));
- }
+ }
- } catch (Exception e) {
+ } catch (Exception e) {
throw new EPropertyException(CMS.getUserMessage(
"CMS_INVALID_PROPERTY", CONFIG_POLICY_NUM));
- }
+ }
}
super.setConfig(name, value);
}
-
public Enumeration<String> getConfigNames() {
refreshConfigAndValueNames();
return super.getConfigNames();
@@ -166,22 +162,22 @@ public class CertificatePoliciesExtDefault extends EnrollExtDefault {
int numQualifiers = getNumQualifiers();
addConfigName(CONFIG_POLICY_NUM);
-
+
for (int i = 0; i < num; i++) {
- addConfigName(CONFIG_PREFIX+i+SEPARATOR+CONFIG_POLICY_ID);
- addConfigName(CONFIG_PREFIX+i+SEPARATOR+CONFIG_POLICY_ENABLE);
- for (int j=0; j<numQualifiers; j++) {
- addConfigName(CONFIG_PREFIX+i+SEPARATOR+CONFIG_PREFIX1+j+SEPARATOR+CONFIG_CPSURI_ENABLE);
- addConfigName(CONFIG_PREFIX+i+SEPARATOR+CONFIG_PREFIX1+j+SEPARATOR+CONFIG_USERNOTICE_ENABLE);
- addConfigName(CONFIG_PREFIX+i+SEPARATOR+CONFIG_PREFIX1+j+SEPARATOR+CONFIG_CPSURI_VALUE);
- addConfigName(CONFIG_PREFIX+i+SEPARATOR+CONFIG_PREFIX1+j+SEPARATOR+CONFIG_USERNOTICE_ORG);
- addConfigName(CONFIG_PREFIX+i+SEPARATOR+CONFIG_PREFIX1+j+SEPARATOR+CONFIG_USERNOTICE_NUMBERS);
- addConfigName(CONFIG_PREFIX+i+SEPARATOR+CONFIG_PREFIX1+j+SEPARATOR+CONFIG_USERNOTICE_TEXT);
+ addConfigName(CONFIG_PREFIX + i + SEPARATOR + CONFIG_POLICY_ID);
+ addConfigName(CONFIG_PREFIX + i + SEPARATOR + CONFIG_POLICY_ENABLE);
+ for (int j = 0; j < numQualifiers; j++) {
+ addConfigName(CONFIG_PREFIX + i + SEPARATOR + CONFIG_PREFIX1 + j + SEPARATOR + CONFIG_CPSURI_ENABLE);
+ addConfigName(CONFIG_PREFIX + i + SEPARATOR + CONFIG_PREFIX1 + j + SEPARATOR + CONFIG_USERNOTICE_ENABLE);
+ addConfigName(CONFIG_PREFIX + i + SEPARATOR + CONFIG_PREFIX1 + j + SEPARATOR + CONFIG_CPSURI_VALUE);
+ addConfigName(CONFIG_PREFIX + i + SEPARATOR + CONFIG_PREFIX1 + j + SEPARATOR + CONFIG_USERNOTICE_ORG);
+ addConfigName(CONFIG_PREFIX + i + SEPARATOR + CONFIG_PREFIX1 + j + SEPARATOR + CONFIG_USERNOTICE_NUMBERS);
+ addConfigName(CONFIG_PREFIX + i + SEPARATOR + CONFIG_PREFIX1 + j + SEPARATOR + CONFIG_USERNOTICE_TEXT);
}
}
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
if (name.equals(CONFIG_CRITICAL)) {
return new Descriptor(IDescriptor.BOOLEAN, null,
@@ -189,16 +185,16 @@ public class CertificatePoliciesExtDefault extends EnrollExtDefault {
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.indexOf(CONFIG_POLICY_ID) >= 0) {
return new Descriptor(IDescriptor.STRING, null,
- null,
- CMS.getUserMessage(locale, "CMS_PROFILE_POLICY_ID"));
+ null,
+ CMS.getUserMessage(locale, "CMS_PROFILE_POLICY_ID"));
} else if (name.indexOf(CONFIG_CPSURI_ENABLE) >= 0) {
return new Descriptor(IDescriptor.BOOLEAN, null,
- "false",
- CMS.getUserMessage(locale, "CMS_PROFILE_POLICY_QUALIFIER_CPSURI_ENABLE"));
+ "false",
+ CMS.getUserMessage(locale, "CMS_PROFILE_POLICY_QUALIFIER_CPSURI_ENABLE"));
} else if (name.indexOf(CONFIG_USERNOTICE_ENABLE) >= 0) {
return new Descriptor(IDescriptor.BOOLEAN, null,
- "false",
- CMS.getUserMessage(locale, "CMS_PROFILE_POLICY_QUALIFIER_USERNOTICE_ENABLE"));
+ "false",
+ CMS.getUserMessage(locale, "CMS_PROFILE_POLICY_QUALIFIER_USERNOTICE_ENABLE"));
} else if (name.indexOf(CONFIG_POLICY_ENABLE) >= 0) {
return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
@@ -225,8 +221,8 @@ public class CertificatePoliciesExtDefault extends EnrollExtDefault {
CMS.getUserMessage(locale, "CMS_PROFILE_POLICY_CPSURI"));
} else if (name.indexOf(CONFIG_POLICY_NUM) >= 0) {
return new Descriptor(IDescriptor.INTEGER, null,
- "5",
- CMS.getUserMessage(locale, "CMS_PROFILE_NUM_POLICIES"));
+ "5",
+ CMS.getUserMessage(locale, "CMS_PROFILE_NUM_POLICIES"));
}
return null;
}
@@ -234,7 +230,7 @@ public class CertificatePoliciesExtDefault extends EnrollExtDefault {
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.equals(VAL_POLICY_QUALIFIERS)) {
@@ -253,126 +249,126 @@ public class CertificatePoliciesExtDefault extends EnrollExtDefault {
int index = token.indexOf(":");
if (index <= 0)
throw new EPropertyException(CMS.getUserMessage(
- "CMS_INVALID_PROPERTY", token));
+ "CMS_INVALID_PROPERTY", token));
String name = token.substring(0, index);
String val = "";
- if ((token.length()-1) > index) {
- val = token.substring(index+1);
+ if ((token.length() - 1) > index) {
+ val = token.substring(index + 1);
}
table.put(name, val);
- }
-
+ }
+
return table;
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
try {
CertificatePoliciesExtension ext = null;
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
if (name.equals(VAL_CRITICAL)) {
ext = (CertificatePoliciesExtension)
- getExtension(PKIXExtensions.CertificatePolicies_Id.toString(),
- info);
+ getExtension(PKIXExtensions.CertificatePolicies_Id.toString(),
+ info);
boolean val = Boolean.valueOf(value).booleanValue();
- ext.setCritical(val);
- } else if (name.equals(VAL_POLICY_QUALIFIERS)) {
+ ext.setCritical(val);
+ } else if (name.equals(VAL_POLICY_QUALIFIERS)) {
ext = (CertificatePoliciesExtension)
- getExtension(PKIXExtensions.CertificatePolicies_Id.toString(),
- info);
-
+ getExtension(PKIXExtensions.CertificatePolicies_Id.toString(),
+ info);
+
Hashtable<String, String> h = buildRecords(value);
- String numStr = (String)h.get(CONFIG_POLICY_NUM);
+ String numStr = (String) h.get(CONFIG_POLICY_NUM);
int size = Integer.parseInt(numStr);
Vector<CertificatePolicyInfo> certificatePolicies = new Vector<CertificatePolicyInfo>();
for (int i = 0; i < size; i++) {
- String enable = (String)h.get(CONFIG_PREFIX+i+SEPARATOR+CONFIG_POLICY_ENABLE);
+ String enable = (String) h.get(CONFIG_PREFIX + i + SEPARATOR + CONFIG_POLICY_ENABLE);
CertificatePolicyInfo cinfo = null;
if (enable != null && enable.equals("true")) {
- String policyId = (String)h.get(CONFIG_PREFIX+i+SEPARATOR+CONFIG_POLICY_ID);
+ String policyId = (String) h.get(CONFIG_PREFIX + i + SEPARATOR + CONFIG_POLICY_ID);
- if (policyId == null || policyId.length() == 0)
- throw new EPropertyException(CMS.getUserMessage(
+ if (policyId == null || policyId.length() == 0)
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_PROFILE_CERTIFICATE_POLICIES_EMPTY_POLICYID"));
CertificatePolicyId cpolicyId = getPolicyId(policyId);
- String qualifersNum = (String)h.get(CONFIG_PREFIX+i+SEPARATOR+CONFIG_POLICY_QUALIFIERS_NUM);
+ String qualifersNum = (String) h.get(CONFIG_PREFIX + i + SEPARATOR + CONFIG_POLICY_QUALIFIERS_NUM);
PolicyQualifiers policyQualifiers = new PolicyQualifiers();
int num = 0;
if (qualifersNum != null && qualifersNum.length() > 0)
num = Integer.parseInt(qualifersNum);
- for (int j=0; j<num; j++) {
- String cpsuriEnable = (String)h.get(CONFIG_PREFIX+i+SEPARATOR+CONFIG_PREFIX1+j+SEPARATOR+CONFIG_CPSURI_ENABLE);
- String usernoticeEnable = (String)h.get(CONFIG_PREFIX+i+SEPARATOR+CONFIG_PREFIX1+j+SEPARATOR+CONFIG_USERNOTICE_ENABLE);
+ for (int j = 0; j < num; j++) {
+ String cpsuriEnable = (String) h.get(CONFIG_PREFIX + i + SEPARATOR + CONFIG_PREFIX1 + j + SEPARATOR + CONFIG_CPSURI_ENABLE);
+ String usernoticeEnable = (String) h.get(CONFIG_PREFIX + i + SEPARATOR + CONFIG_PREFIX1 + j + SEPARATOR + CONFIG_USERNOTICE_ENABLE);
if (cpsuriEnable != null && cpsuriEnable.equals("true")) {
- String cpsuri = (String)h.get(CONFIG_PREFIX+i+SEPARATOR+CONFIG_PREFIX1+j+SEPARATOR+CONFIG_CPSURI_VALUE);
+ String cpsuri = (String) h.get(CONFIG_PREFIX + i + SEPARATOR + CONFIG_PREFIX1 + j + SEPARATOR + CONFIG_CPSURI_VALUE);
netscape.security.x509.PolicyQualifierInfo qualifierInfo = createCPSuri(cpsuri);
if (qualifierInfo != null)
- policyQualifiers.add(qualifierInfo);
+ policyQualifiers.add(qualifierInfo);
} else if (usernoticeEnable != null && enable.equals("true")) {
- String org = (String)h.get(CONFIG_PREFIX+i+SEPARATOR+CONFIG_PREFIX1+j+SEPARATOR+CONFIG_USERNOTICE_ORG);
- String noticenumbers = (String)h.get(CONFIG_PREFIX+i+SEPARATOR+CONFIG_PREFIX1+j+SEPARATOR+CONFIG_USERNOTICE_NUMBERS);
- String explicitText = (String)h.get(CONFIG_PREFIX+i+SEPARATOR+CONFIG_PREFIX1+j+SEPARATOR+CONFIG_USERNOTICE_TEXT);
+ String org = (String) h.get(CONFIG_PREFIX + i + SEPARATOR + CONFIG_PREFIX1 + j + SEPARATOR + CONFIG_USERNOTICE_ORG);
+ String noticenumbers = (String) h.get(CONFIG_PREFIX + i + SEPARATOR + CONFIG_PREFIX1 + j + SEPARATOR + CONFIG_USERNOTICE_NUMBERS);
+ String explicitText = (String) h.get(CONFIG_PREFIX + i + SEPARATOR + CONFIG_PREFIX1 + j + SEPARATOR + CONFIG_USERNOTICE_TEXT);
netscape.security.x509.PolicyQualifierInfo qualifierInfo = createUserNotice(org,
- noticenumbers, explicitText);
+ noticenumbers, explicitText);
if (qualifierInfo != null)
- policyQualifiers.add(qualifierInfo);
+ policyQualifiers.add(qualifierInfo);
}
}
if (policyQualifiers.size() <= 0) {
cinfo =
- new CertificatePolicyInfo(cpolicyId);
+ new CertificatePolicyInfo(cpolicyId);
} else {
cinfo =
- new CertificatePolicyInfo(cpolicyId, policyQualifiers);
+ new CertificatePolicyInfo(cpolicyId, policyQualifiers);
}
if (cinfo != null)
- certificatePolicies.addElement(cinfo);
+ certificatePolicies.addElement(cinfo);
}
}
ext.set(CertificatePoliciesExtension.INFOS, certificatePolicies);
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
replaceExtension(PKIXExtensions.CertificatePolicies_Id.toString(),
- ext, info);
+ ext, info);
} catch (EProfileException e) {
CMS.debug("CertificatePoliciesExtDefault: setValue " + e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
} catch (IOException e) {
CMS.debug("CertificatePoliciesExtDefault: setValue " + e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
- public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
+ public String getValue(String name, Locale locale,
+ X509CertInfo info)
+ throws EPropertyException {
CertificatePoliciesExtension ext = null;
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
if (name.equals(VAL_CRITICAL)) {
ext = (CertificatePoliciesExtension)
- getExtension(PKIXExtensions.CertificatePolicies_Id.toString(),
- info);
+ getExtension(PKIXExtensions.CertificatePolicies_Id.toString(),
+ info);
if (ext == null) {
return null;
@@ -382,10 +378,10 @@ public class CertificatePoliciesExtDefault extends EnrollExtDefault {
} else {
return "false";
}
- } else if (name.equals(VAL_POLICY_QUALIFIERS)) {
+ } else if (name.equals(VAL_POLICY_QUALIFIERS)) {
ext = (CertificatePoliciesExtension)
- getExtension(PKIXExtensions.CertificatePolicies_Id.toString(),
- info);
+ getExtension(PKIXExtensions.CertificatePolicies_Id.toString(),
+ info);
if (ext == null)
return "";
@@ -396,14 +392,14 @@ public class CertificatePoliciesExtDefault extends EnrollExtDefault {
sb.append(":");
sb.append(num_policies);
sb.append("\n");
-
- Vector<CertificatePolicyInfo> infos ;
+
+ Vector<CertificatePolicyInfo> infos;
try {
@SuppressWarnings("unchecked")
- Vector<CertificatePolicyInfo> certPolicyInfos = (Vector<CertificatePolicyInfo>)ext.get(CertificatePoliciesExtension.INFOS);
+ Vector<CertificatePolicyInfo> certPolicyInfos = (Vector<CertificatePolicyInfo>) ext.get(CertificatePoliciesExtension.INFOS);
infos = certPolicyInfos;
} catch (IOException ee) {
- infos =null;
+ infos = null;
}
for (int i = 0; i < num_policies; i++) {
@@ -411,70 +407,70 @@ public class CertificatePoliciesExtDefault extends EnrollExtDefault {
String policyId = "";
String policyEnable = "false";
PolicyQualifiers qualifiers = null;
- if (infos.size() > 0) {
- CertificatePolicyInfo cinfo =
- infos.elementAt(0);
-
- CertificatePolicyId id1 = cinfo.getPolicyIdentifier();
+ if (infos.size() > 0) {
+ CertificatePolicyInfo cinfo =
+ infos.elementAt(0);
+
+ CertificatePolicyId id1 = cinfo.getPolicyIdentifier();
policyId = id1.getIdentifier().toString();
policyEnable = "true";
qualifiers = cinfo.getPolicyQualifiers();
if (qualifiers != null)
- qSize = qualifiers.size();
+ qSize = qualifiers.size();
infos.removeElementAt(0);
}
- sb.append(CONFIG_PREFIX+i+SEPARATOR+CONFIG_POLICY_ENABLE);
+ sb.append(CONFIG_PREFIX + i + SEPARATOR + CONFIG_POLICY_ENABLE);
sb.append(":");
sb.append(policyEnable);
sb.append("\n");
- sb.append(CONFIG_PREFIX+i+SEPARATOR+CONFIG_POLICY_ID);
+ sb.append(CONFIG_PREFIX + i + SEPARATOR + CONFIG_POLICY_ID);
sb.append(":");
sb.append(policyId);
sb.append("\n");
-
+
if (qSize == 0) {
- sb.append(CONFIG_PREFIX+i+SEPARATOR+CONFIG_POLICY_QUALIFIERS_NUM);
+ sb.append(CONFIG_PREFIX + i + SEPARATOR + CONFIG_POLICY_QUALIFIERS_NUM);
sb.append(":");
sb.append(DEF_NUM_QUALIFIERS);
sb.append("\n");
} else {
- sb.append(CONFIG_PREFIX+i+SEPARATOR+CONFIG_POLICY_QUALIFIERS_NUM);
+ sb.append(CONFIG_PREFIX + i + SEPARATOR + CONFIG_POLICY_QUALIFIERS_NUM);
sb.append(":");
sb.append(qSize);
sb.append("\n");
}
if (qSize == 0) {
- sb.append(CONFIG_PREFIX+i+SEPARATOR+CONFIG_PREFIX1+"0"+SEPARATOR+CONFIG_CPSURI_ENABLE);
+ sb.append(CONFIG_PREFIX + i + SEPARATOR + CONFIG_PREFIX1 + "0" + SEPARATOR + CONFIG_CPSURI_ENABLE);
sb.append(":");
sb.append("false");
sb.append("\n");
- sb.append(CONFIG_PREFIX+i+SEPARATOR+CONFIG_PREFIX1+"0"+SEPARATOR+CONFIG_CPSURI_VALUE);
+ sb.append(CONFIG_PREFIX + i + SEPARATOR + CONFIG_PREFIX1 + "0" + SEPARATOR + CONFIG_CPSURI_VALUE);
sb.append(":");
sb.append("");
sb.append("\n");
- sb.append(CONFIG_PREFIX+i+SEPARATOR+CONFIG_PREFIX1+"0"+SEPARATOR+CONFIG_USERNOTICE_ENABLE);
+ sb.append(CONFIG_PREFIX + i + SEPARATOR + CONFIG_PREFIX1 + "0" + SEPARATOR + CONFIG_USERNOTICE_ENABLE);
sb.append(":");
sb.append("false");
sb.append("\n");
- sb.append(CONFIG_PREFIX+i+SEPARATOR+CONFIG_PREFIX1+"0"+SEPARATOR+CONFIG_USERNOTICE_ORG);
+ sb.append(CONFIG_PREFIX + i + SEPARATOR + CONFIG_PREFIX1 + "0" + SEPARATOR + CONFIG_USERNOTICE_ORG);
sb.append(":");
sb.append("");
sb.append("\n");
- sb.append(CONFIG_PREFIX+i+SEPARATOR+CONFIG_PREFIX1+"0"+SEPARATOR+CONFIG_USERNOTICE_NUMBERS);
+ sb.append(CONFIG_PREFIX + i + SEPARATOR + CONFIG_PREFIX1 + "0" + SEPARATOR + CONFIG_USERNOTICE_NUMBERS);
sb.append(":");
sb.append("");
sb.append("\n");
- sb.append(CONFIG_PREFIX+i+SEPARATOR+CONFIG_PREFIX1+"0"+SEPARATOR+CONFIG_USERNOTICE_TEXT);
+ sb.append(CONFIG_PREFIX + i + SEPARATOR + CONFIG_PREFIX1 + "0" + SEPARATOR + CONFIG_USERNOTICE_TEXT);
sb.append(":");
sb.append("");
sb.append("\n");
}
- for (int j=0; j<qSize; j++) {
+ for (int j = 0; j < qSize; j++) {
netscape.security.x509.PolicyQualifierInfo qinfo = qualifiers.getInfoAt(j);
ObjectIdentifier oid = qinfo.getId();
Qualifier qualifier = qinfo.getQualifier();
-
+
String cpsuriEnable = "false";
String usernoticeEnable = "false";
String cpsuri = "";
@@ -484,16 +480,16 @@ public class CertificatePoliciesExtDefault extends EnrollExtDefault {
if (oid.toString().equals(netscape.security.x509.PolicyQualifierInfo.QT_CPS.toString())) {
cpsuriEnable = "true";
- CPSuri content = (CPSuri)qualifier;
- cpsuri = content.getURI();
+ CPSuri content = (CPSuri) qualifier;
+ cpsuri = content.getURI();
} else if (oid.toString().equals(netscape.security.x509.PolicyQualifierInfo.QT_UNOTICE.toString())) {
usernoticeEnable = "true";
- UserNotice content = (UserNotice)qualifier;
+ UserNotice content = (UserNotice) qualifier;
NoticeReference ref = content.getNoticeReference();
if (ref != null) {
org = ref.getOrganization().getText();
int[] nums = ref.getNumbers();
- for (int k=0; k<nums.length; k++) {
+ for (int k = 0; k < nums.length; k++) {
if (k != 0) {
noticeNum.append(",");
noticeNum.append(nums[k]);
@@ -506,27 +502,27 @@ public class CertificatePoliciesExtDefault extends EnrollExtDefault {
explicitText = displayText.getText();
}
- sb.append(CONFIG_PREFIX+i+SEPARATOR+CONFIG_PREFIX1+j+SEPARATOR+CONFIG_CPSURI_ENABLE);
+ sb.append(CONFIG_PREFIX + i + SEPARATOR + CONFIG_PREFIX1 + j + SEPARATOR + CONFIG_CPSURI_ENABLE);
sb.append(":");
sb.append(cpsuriEnable);
sb.append("\n");
- sb.append(CONFIG_PREFIX+i+SEPARATOR+CONFIG_PREFIX1+j+SEPARATOR+CONFIG_CPSURI_VALUE);
+ sb.append(CONFIG_PREFIX + i + SEPARATOR + CONFIG_PREFIX1 + j + SEPARATOR + CONFIG_CPSURI_VALUE);
sb.append(":");
sb.append(cpsuri);
sb.append("\n");
- sb.append(CONFIG_PREFIX+i+SEPARATOR+CONFIG_PREFIX1+j+SEPARATOR+CONFIG_USERNOTICE_ENABLE);
+ sb.append(CONFIG_PREFIX + i + SEPARATOR + CONFIG_PREFIX1 + j + SEPARATOR + CONFIG_USERNOTICE_ENABLE);
sb.append(":");
sb.append(usernoticeEnable);
sb.append("\n");
- sb.append(CONFIG_PREFIX+i+SEPARATOR+CONFIG_PREFIX1+j+SEPARATOR+CONFIG_USERNOTICE_ORG);
+ sb.append(CONFIG_PREFIX + i + SEPARATOR + CONFIG_PREFIX1 + j + SEPARATOR + CONFIG_USERNOTICE_ORG);
sb.append(":");
sb.append(org);
sb.append("\n");
- sb.append(CONFIG_PREFIX+i+SEPARATOR+CONFIG_PREFIX1+j+SEPARATOR+CONFIG_USERNOTICE_NUMBERS);
+ sb.append(CONFIG_PREFIX + i + SEPARATOR + CONFIG_PREFIX1 + j + SEPARATOR + CONFIG_USERNOTICE_NUMBERS);
sb.append(":");
sb.append(noticeNum.toString());
sb.append("\n");
- sb.append(CONFIG_PREFIX+i+SEPARATOR+CONFIG_PREFIX1+j+SEPARATOR+CONFIG_USERNOTICE_TEXT);
+ sb.append(CONFIG_PREFIX + i + SEPARATOR + CONFIG_PREFIX1 + j + SEPARATOR + CONFIG_USERNOTICE_TEXT);
sb.append(":");
sb.append(explicitText);
sb.append("\n");
@@ -534,7 +530,7 @@ public class CertificatePoliciesExtDefault extends EnrollExtDefault {
} // end of for loop
return sb.toString();
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
@@ -552,7 +548,7 @@ public class CertificatePoliciesExtDefault extends EnrollExtDefault {
sb.append(",");
for (int i = 0; i < num; i++) {
sb.append("{");
- IConfigStore substore = basesubstore.getSubStore(CONFIG_PREFIX+i);
+ IConfigStore substore = basesubstore.getSubStore(CONFIG_PREFIX + i);
String enable = substore.getString(CONFIG_POLICY_ENABLE, "");
sb.append(POLICY_ID_ENABLE + ":");
sb.append(enable);
@@ -562,18 +558,18 @@ public class CertificatePoliciesExtDefault extends EnrollExtDefault {
sb.append(policyId);
sb.append(",");
String qualifiersNum = substore.getString(CONFIG_POLICY_QUALIFIERS_NUM, "");
- sb.append(CONFIG_POLICY_QUALIFIERS_NUM+":");
+ sb.append(CONFIG_POLICY_QUALIFIERS_NUM + ":");
sb.append(qualifiersNum);
sb.append(",");
- for (int j=0; j<num1; j++) {
- IConfigStore substore1 = substore.getSubStore(CONFIG_PREFIX1+j);
+ for (int j = 0; j < num1; j++) {
+ IConfigStore substore1 = substore.getSubStore(CONFIG_PREFIX1 + j);
sb.append("{");
String cpsuriEnable = substore1.getString(CONFIG_CPSURI_ENABLE, "");
sb.append(POLICY_QUALIFIER_CPSURI_ENABLE + ":");
sb.append(cpsuriEnable);
sb.append(",");
String usernoticeEnable = substore1.getString(CONFIG_USERNOTICE_ENABLE, "");
- sb.append(POLICY_QUALIFIER_USERNOTICE_ENABLE+ ":");
+ sb.append(POLICY_QUALIFIER_USERNOTICE_ENABLE + ":");
sb.append(usernoticeEnable);
sb.append(",");
String org = substore1.getString(CONFIG_USERNOTICE_ORG, "");
@@ -596,9 +592,9 @@ public class CertificatePoliciesExtDefault extends EnrollExtDefault {
sb.append("}");
}
sb.append("}");
- return CMS.getUserMessage(locale,
- "CMS_PROFILE_DEF_CERTIFICATE_POLICIES_EXT",
- getConfig(CONFIG_CRITICAL), sb.toString());
+ return CMS.getUserMessage(locale,
+ "CMS_PROFILE_DEF_CERTIFICATE_POLICIES_EXT",
+ getConfig(CONFIG_CRITICAL), sb.toString());
} catch (Exception e) {
return "";
}
@@ -608,72 +604,72 @@ public class CertificatePoliciesExtDefault extends EnrollExtDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
CertificatePoliciesExtension ext = createExtension();
if (ext == null)
return;
- addExtension(PKIXExtensions.CertificatePolicies_Id.toString(),
- ext, info);
+ addExtension(PKIXExtensions.CertificatePolicies_Id.toString(),
+ ext, info);
}
- public CertificatePoliciesExtension createExtension()
- throws EProfileException {
- CertificatePoliciesExtension ext = null;
+ public CertificatePoliciesExtension createExtension()
+ throws EProfileException {
+ CertificatePoliciesExtension ext = null;
try {
boolean critical = getConfigBoolean(CONFIG_CRITICAL);
Vector<CertificatePolicyInfo> certificatePolicies = new Vector<CertificatePolicyInfo>();
int num = getNumPolicies();
- CMS.debug("CertificatePoliciesExtension: createExtension: number of policies="+num);
+ CMS.debug("CertificatePoliciesExtension: createExtension: number of policies=" + num);
IConfigStore config = getConfigStore();
- for (int i = 0; i < num; i++) {
+ for (int i = 0; i < num; i++) {
IConfigStore basesubstore = config.getSubStore("params");
- IConfigStore substore = basesubstore.getSubStore(CONFIG_PREFIX+i);
+ IConfigStore substore = basesubstore.getSubStore(CONFIG_PREFIX + i);
String enable = substore.getString(CONFIG_POLICY_ENABLE);
- CMS.debug("CertificatePoliciesExtension: createExtension: CertificatePolicy "+i+" enable="+enable);
+ CMS.debug("CertificatePoliciesExtension: createExtension: CertificatePolicy " + i + " enable=" + enable);
if (enable != null && enable.equals("true")) {
String policyId = substore.getString(CONFIG_POLICY_ID);
CertificatePolicyId cpolicyId = getPolicyId(policyId);
- CMS.debug("CertificatePoliciesExtension: createExtension: CertificatePolicy "+i+" policyId="+policyId);
+ CMS.debug("CertificatePoliciesExtension: createExtension: CertificatePolicy " + i + " policyId=" + policyId);
int qualifierNum = getNumQualifiers();
PolicyQualifiers policyQualifiers = new PolicyQualifiers();
- for (int j=0; j<qualifierNum; j++) {
- IConfigStore substore1 = substore.getSubStore(CONFIG_PREFIX1+j);
+ for (int j = 0; j < qualifierNum; j++) {
+ IConfigStore substore1 = substore.getSubStore(CONFIG_PREFIX1 + j);
String cpsuriEnable = substore1.getString(CONFIG_CPSURI_ENABLE);
String usernoticeEnable = substore1.getString(CONFIG_USERNOTICE_ENABLE);
if (cpsuriEnable != null && cpsuriEnable.equals("true")) {
String cpsuri = substore1.getString(CONFIG_CPSURI_VALUE, "");
- netscape.security.x509.PolicyQualifierInfo qualifierInfo = createCPSuri(cpsuri);
+ netscape.security.x509.PolicyQualifierInfo qualifierInfo = createCPSuri(cpsuri);
if (qualifierInfo != null)
- policyQualifiers.add(qualifierInfo);
- } else if (usernoticeEnable != null &&
+ policyQualifiers.add(qualifierInfo);
+ } else if (usernoticeEnable != null &&
usernoticeEnable.equals("true")) {
String org = substore1.getString(CONFIG_USERNOTICE_ORG);
String noticenumbers = substore1.getString(CONFIG_USERNOTICE_NUMBERS);
String explicitText = substore1.getString(CONFIG_USERNOTICE_TEXT);
netscape.security.x509.PolicyQualifierInfo qualifierInfo = createUserNotice(org,
- noticenumbers, explicitText);
+ noticenumbers, explicitText);
if (qualifierInfo != null)
policyQualifiers.add(qualifierInfo);
}
}
-
+
CertificatePolicyInfo info = null;
if (policyQualifiers.size() <= 0) {
- info =
- new CertificatePolicyInfo(cpolicyId);
+ info =
+ new CertificatePolicyInfo(cpolicyId);
} else {
- info =
- new CertificatePolicyInfo(cpolicyId, policyQualifiers);
+ info =
+ new CertificatePolicyInfo(cpolicyId, policyQualifiers);
}
-
+
if (info != null)
- certificatePolicies.addElement(info);
+ certificatePolicies.addElement(info);
}
}
@@ -683,51 +679,51 @@ public class CertificatePoliciesExtDefault extends EnrollExtDefault {
} catch (EProfileException e) {
throw e;
} catch (Exception e) {
- CMS.debug("CertificatePoliciesExtDefault: createExtension " +
- e.toString());
+ CMS.debug("CertificatePoliciesExtDefault: createExtension " +
+ e.toString());
}
return ext;
}
- private CertificatePolicyId getPolicyId (String policyId) throws EPropertyException {
+ private CertificatePolicyId getPolicyId(String policyId) throws EPropertyException {
if (policyId == null || policyId.length() == 0)
throw new EPropertyException(CMS.getUserMessage(
- "CMS_PROFILE_CERTIFICATE_POLICIES_EMPTY_POLICYID"));
+ "CMS_PROFILE_CERTIFICATE_POLICIES_EMPTY_POLICYID"));
CertificatePolicyId cpolicyId = null;
try {
cpolicyId = new CertificatePolicyId(
- ObjectIdentifier.getObjectIdentifier(policyId));
+ ObjectIdentifier.getObjectIdentifier(policyId));
return cpolicyId;
} catch (Exception e) {
throw new EPropertyException(CMS.getUserMessage(
- "CMS_PROFILE_CERTIFICATE_POLICIES_POLICYID_ERROR", policyId));
+ "CMS_PROFILE_CERTIFICATE_POLICIES_POLICYID_ERROR", policyId));
}
}
private netscape.security.x509.PolicyQualifierInfo createCPSuri(String uri) throws EPropertyException {
- if (uri == null || uri.length() == 0)
+ if (uri == null || uri.length() == 0)
throw new EPropertyException(CMS.getUserMessage(
- "CMS_PROFILE_CERTIFICATE_POLICIES_EMPTY_CPSURI"));
+ "CMS_PROFILE_CERTIFICATE_POLICIES_EMPTY_CPSURI"));
- CPSuri cpsURI = new CPSuri(uri);
+ CPSuri cpsURI = new CPSuri(uri);
netscape.security.x509.PolicyQualifierInfo policyQualifierInfo2 =
- new netscape.security.x509.PolicyQualifierInfo(netscape.security.x509.PolicyQualifierInfo.QT_CPS, cpsURI);
-
+ new netscape.security.x509.PolicyQualifierInfo(netscape.security.x509.PolicyQualifierInfo.QT_CPS, cpsURI);
+
return policyQualifierInfo2;
}
- private netscape.security.x509.PolicyQualifierInfo createUserNotice(String organization,
- String noticeText, String noticeNums) throws EPropertyException {
-
- if ((organization == null || organization.length() == 0) &&
- (noticeNums == null || noticeNums.length() == 0) &&
- (noticeText == null || noticeText.length() == 0))
+ private netscape.security.x509.PolicyQualifierInfo createUserNotice(String organization,
+ String noticeText, String noticeNums) throws EPropertyException {
+
+ if ((organization == null || organization.length() == 0) &&
+ (noticeNums == null || noticeNums.length() == 0) &&
+ (noticeText == null || noticeText.length() == 0))
return null;
DisplayText explicitText = null;
- if (noticeText != null && noticeText.length() > 0)
+ if (noticeText != null && noticeText.length() > 0)
explicitText = new DisplayText(DisplayText.tag_VisibleString, noticeText);
int nums[] = null;
@@ -753,7 +749,7 @@ public class CertificatePoliciesExtDefault extends EnrollExtDefault {
DisplayText orgName = null;
if (organization != null && organization.length() > 0) {
orgName =
- new DisplayText(DisplayText.tag_VisibleString, organization);
+ new DisplayText(DisplayText.tag_VisibleString, organization);
}
NoticeReference noticeReference = null;
@@ -763,10 +759,10 @@ public class CertificatePoliciesExtDefault extends EnrollExtDefault {
UserNotice userNotice = null;
if (explicitText != null || noticeReference != null) {
- userNotice = new UserNotice (noticeReference, explicitText);
+ userNotice = new UserNotice(noticeReference, explicitText);
netscape.security.x509.PolicyQualifierInfo policyQualifierInfo1 =
- new netscape.security.x509.PolicyQualifierInfo(netscape.security.x509.PolicyQualifierInfo.QT_UNOTICE, userNotice);
+ new netscape.security.x509.PolicyQualifierInfo(netscape.security.x509.PolicyQualifierInfo.QT_UNOTICE, userNotice);
return policyQualifierInfo1;
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/CertificateVersionDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/CertificateVersionDefault.java
index f3b68594..f5b00970 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/CertificateVersionDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/CertificateVersionDefault.java
@@ -34,10 +34,9 @@ import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
/**
- * This class implements an enrollment default policy
- * that populates a Netscape comment extension
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates a Netscape
+ * comment extension into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class CertificateVersionDefault extends EnrollExtDefault {
@@ -54,11 +53,11 @@ public class CertificateVersionDefault extends EnrollExtDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
if (name.equals(CONFIG_VERSION)) {
return new Descriptor(IDescriptor.INTEGER, null,
"3",
@@ -69,14 +68,14 @@ public class CertificateVersionDefault extends EnrollExtDefault {
}
public void setConfig(String name, String value)
- throws EPropertyException {
+ throws EPropertyException {
if (name.equals(CONFIG_VERSION)) {
- try {
- Integer.parseInt(value);
- } catch (Exception e) {
+ try {
+ Integer.parseInt(value);
+ } catch (Exception e) {
throw new EPropertyException(CMS.getUserMessage(
"CMS_INVALID_PROPERTY", CONFIG_VERSION));
- }
+ }
}
super.setConfig(name, value);
}
@@ -92,32 +91,32 @@ public class CertificateVersionDefault extends EnrollExtDefault {
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
try {
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
- if (name.equals(VAL_VERSION)) {
+ if (name.equals(VAL_VERSION)) {
if (value == null || value.equals(""))
- throw new EPropertyException(name+" cannot be empty");
+ throw new EPropertyException(name + " cannot be empty");
else {
- int version = Integer.valueOf(value).intValue()-1;
-
+ int version = Integer.valueOf(value).intValue() - 1;
+
if (version == CertificateVersion.V1)
info.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V1));
+ new CertificateVersion(CertificateVersion.V1));
else if (version == CertificateVersion.V2)
info.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V2));
+ new CertificateVersion(CertificateVersion.V2));
else if (version == CertificateVersion.V3)
info.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ new CertificateVersion(CertificateVersion.V3));
}
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
} catch (IOException e) {
@@ -128,30 +127,30 @@ public class CertificateVersionDefault extends EnrollExtDefault {
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
+ X509CertInfo info)
+ throws EPropertyException {
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
- if (name.equals(VAL_VERSION)) {
+ if (name.equals(VAL_VERSION)) {
CertificateVersion v = null;
- try {
- v = (CertificateVersion)info.get(
- X509CertInfo.VERSION);
+ try {
+ v = (CertificateVersion) info.get(
+ X509CertInfo.VERSION);
} catch (Exception e) {
}
if (v == null)
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
int version = v.compare(0);
-
- return ""+(version+1);
+
+ return "" + (version + 1);
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
@@ -168,26 +167,26 @@ public class CertificateVersionDefault extends EnrollExtDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
String v = getConfig(CONFIG_VERSION);
- int version = Integer.valueOf(v).intValue()-1;
-
+ int version = Integer.valueOf(v).intValue() - 1;
+
try {
if (version == CertificateVersion.V1)
info.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V1));
+ new CertificateVersion(CertificateVersion.V1));
else if (version == CertificateVersion.V2)
info.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V2));
+ new CertificateVersion(CertificateVersion.V2));
else if (version == CertificateVersion.V3)
info.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ new CertificateVersion(CertificateVersion.V3));
else {
throw new EProfileException(CMS.getUserMessage(
- getLocale(request), "CMS_INVALID_PROPERTY", CONFIG_VERSION));
+ getLocale(request), "CMS_INVALID_PROPERTY", CONFIG_VERSION));
}
} catch (IOException e) {
} catch (CertificateException e) {
- }
+ }
}
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/EnrollDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/EnrollDefault.java
index 239765ab..81efbf90 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/EnrollDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/EnrollDefault.java
@@ -60,10 +60,9 @@ import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
import com.netscape.cms.profile.common.EnrollProfile;
-
/**
* This class implements an enrollment default policy.
- *
+ *
* @version $Revision$, $Date$
*/
public abstract class EnrollDefault implements IPolicyDefault, ICertInfoPolicyDefault {
@@ -99,7 +98,7 @@ public abstract class EnrollDefault implements IPolicyDefault, ICertInfoPolicyDe
}
public void setConfig(String name, String value)
- throws EPropertyException {
+ throws EPropertyException {
if (mConfig.getSubStore("params") == null) {
//
} else {
@@ -120,19 +119,18 @@ public abstract class EnrollDefault implements IPolicyDefault, ICertInfoPolicyDe
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
mConfig = config;
}
/**
* Retrieves the localizable description of this policy.
- *
+ *
* @param locale locale of the end user
* @return localized description of this default policy
*/
public abstract String getText(Locale locale);
-
public IConfigStore getConfigStore() {
return mConfig;
}
@@ -147,60 +145,57 @@ public abstract class EnrollDefault implements IPolicyDefault, ICertInfoPolicyDe
/**
* Populates attributes into the certificate template.
- *
+ *
* @param request enrollment request
* @param info certificate template
- * @exception EProfileException failed to populate attributes
- * into request
+ * @exception EProfileException failed to populate attributes into request
*/
public abstract void populate(IRequest request, X509CertInfo info)
- throws EProfileException;
+ throws EProfileException;
/**
* Sets values from the approval page into certificate template.
- *
+ *
* @param name name of the attribute
* @param locale user locale
* @param info certificate template
* @param value attribute value
- * @exception EProfileException failed to set attributes
- * into request
+ * @exception EProfileException failed to set attributes into request
*/
- public abstract void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException;
+ public abstract void setValue(String name, Locale locale,
+ X509CertInfo info, String value)
+ throws EPropertyException;
/**
- * Retrieves certificate template values and returns them to
- * the approval page.
- *
+ * Retrieves certificate template values and returns them to the approval
+ * page.
+ *
* @param name name of the attribute
* @param locale user locale
* @param info certificate template
- * @exception EProfileException failed to get attributes
- * from request
+ * @exception EProfileException failed to get attributes from request
*/
- public abstract String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException;
+ public abstract String getValue(String name, Locale locale,
+ X509CertInfo info)
+ throws EPropertyException;
/**
* Populates the request with this policy default.
- *
- * The current implementation extracts enrollment specific attributes
- * and calls the populate() method of the subclass.
- *
+ *
+ * The current implementation extracts enrollment specific attributes and
+ * calls the populate() method of the subclass.
+ *
* @param request request to be populated
* @exception EProfileException failed to populate
*/
public void populate(IRequest request)
- throws EProfileException {
+ throws EProfileException {
String name = getClass().getName();
name = name.substring(name.lastIndexOf('.') + 1);
CMS.debug(name + ": populate start");
X509CertInfo info =
- request.getExtDataInCertInfo(IEnrollProfile.REQUEST_CERTINFO);
+ request.getExtDataInCertInfo(IEnrollProfile.REQUEST_CERTINFO);
populate(request, info);
@@ -222,21 +217,21 @@ public abstract class EnrollDefault implements IPolicyDefault, ICertInfoPolicyDe
/**
* Sets the value of the given value property by name.
- *
- * The current implementation extracts enrollment specific attributes
- * and calls the setValue() method of the subclass.
- *
+ *
+ * The current implementation extracts enrollment specific attributes and
+ * calls the setValue() method of the subclass.
+ *
* @param name name of property
* @param locale locale of the end user
* @param request request
* @param value value to be set in the given request
* @exception EPropertyException failed to set property
*/
- public void setValue(String name, Locale locale, IRequest request,
- String value)
- throws EPropertyException {
+ public void setValue(String name, Locale locale, IRequest request,
+ String value)
+ throws EPropertyException {
X509CertInfo info =
- request.getExtDataInCertInfo(IEnrollProfile.REQUEST_CERTINFO);
+ request.getExtDataInCertInfo(IEnrollProfile.REQUEST_CERTINFO);
setValue(name, locale, info, value);
@@ -244,21 +239,20 @@ public abstract class EnrollDefault implements IPolicyDefault, ICertInfoPolicyDe
}
/**
- * Retrieves the value of the given value
- * property by name.
- *
- * The current implementation extracts enrollment specific attributes
- * and calls the getValue() method of the subclass.
- *
+ * Retrieves the value of the given value property by name.
+ *
+ * The current implementation extracts enrollment specific attributes and
+ * calls the getValue() method of the subclass.
+ *
* @param name name of property
* @param locale locale of the end user
* @param request request
* @exception EPropertyException failed to get property
*/
public String getValue(String name, Locale locale, IRequest request)
- throws EPropertyException {
+ throws EPropertyException {
X509CertInfo info =
- request.getExtDataInCertInfo(IEnrollProfile.REQUEST_CERTINFO);
+ request.getExtDataInCertInfo(IEnrollProfile.REQUEST_CERTINFO);
String value = getValue(name, locale, info);
request.setExtData(IEnrollProfile.REQUEST_CERTINFO, info);
@@ -279,8 +273,8 @@ public abstract class EnrollDefault implements IPolicyDefault, ICertInfoPolicyDe
}
protected void refreshConfigAndValueNames() {
- mConfigNames.removeAllElements();
- mValueNames.removeAllElements();
+ mConfigNames.removeAllElements();
+ mValueNames.removeAllElements();
}
protected void deleteExtension(String name, X509CertInfo info) {
@@ -294,7 +288,7 @@ public abstract class EnrollDefault implements IPolicyDefault, ICertInfoPolicyDe
Enumeration<String> e = exts.getNames();
while (e.hasMoreElements()) {
- String n = e.nextElement();
+ String n = e.nextElement();
Extension ext = (Extension) exts.get(n);
if (ext.getExtensionId().toString().equals(name)) {
@@ -336,18 +330,18 @@ public abstract class EnrollDefault implements IPolicyDefault, ICertInfoPolicyDe
}
protected void addExtension(String name, Extension ext, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
if (ext == null) {
throw new EProfileException("extension not found");
}
CertificateExtensions exts = null;
- Extension alreadyPresentExtension = getExtension(name,info);
+ Extension alreadyPresentExtension = getExtension(name, info);
if (alreadyPresentExtension != null) {
String eName = ext.toString();
CMS.debug("EnrollDefault.addExtension: duplicate extension attempted! Name: " + eName);
- throw new EProfileException(CMS.getUserMessage("CMS_PROFILE_DUPLICATE_EXTENSION",eName));
+ throw new EProfileException(CMS.getUserMessage("CMS_PROFILE_DUPLICATE_EXTENSION", eName));
}
try {
@@ -367,7 +361,7 @@ public abstract class EnrollDefault implements IPolicyDefault, ICertInfoPolicyDe
}
protected void replaceExtension(String name, Extension ext, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
deleteExtension(name, info);
addExtension(name, ext, info);
}
@@ -392,65 +386,62 @@ public abstract class EnrollDefault implements IPolicyDefault, ICertInfoPolicyDe
return getInt(getConfig(value));
}
- protected boolean isGeneralNameValid(String name)
- {
+ protected boolean isGeneralNameValid(String name) {
if (name == null)
- return false;
+ return false;
int pos = name.indexOf(':');
if (pos == -1)
- return false;
+ return false;
String nameType = name.substring(0, pos).trim();
String nameValue = name.substring(pos + 1).trim();
if (nameValue.equals(""))
- return false;
+ return false;
return true;
}
protected GeneralNameInterface parseGeneralName(String name)
- throws IOException {
+ throws IOException {
int pos = name.indexOf(':');
if (pos == -1)
- return null;
+ return null;
String nameType = name.substring(0, pos).trim();
String nameValue = name.substring(pos + 1).trim();
return parseGeneralName(nameType, nameValue);
}
- protected boolean isGeneralNameType(String nameType)
- {
+ protected boolean isGeneralNameType(String nameType) {
if (nameType.equalsIgnoreCase("RFC822Name")) {
- return true;
+ return true;
}
if (nameType.equalsIgnoreCase("DNSName")) {
- return true;
+ return true;
}
if (nameType.equalsIgnoreCase("x400")) {
- return true;
+ return true;
}
if (nameType.equalsIgnoreCase("DirectoryName")) {
- return true;
+ return true;
}
if (nameType.equalsIgnoreCase("EDIPartyName")) {
- return true;
+ return true;
}
if (nameType.equalsIgnoreCase("URIName")) {
- return true;
+ return true;
}
if (nameType.equalsIgnoreCase("IPAddress")) {
- return true;
+ return true;
}
if (nameType.equalsIgnoreCase("OIDName")) {
- return true;
+ return true;
}
if (nameType.equalsIgnoreCase("OtherName")) {
- return true;
+ return true;
}
return false;
}
protected GeneralNameInterface parseGeneralName(String nameType, String nameValue)
- throws IOException
- {
+ throws IOException {
if (nameType.equalsIgnoreCase("RFC822Name")) {
return new RFC822Name(nameValue);
}
@@ -458,7 +449,7 @@ public abstract class EnrollDefault implements IPolicyDefault, ICertInfoPolicyDe
return new DNSName(nameValue);
}
if (nameType.equalsIgnoreCase("x400")) {
- // XXX
+ // XXX
}
if (nameType.equalsIgnoreCase("DirectoryName")) {
return new X500Name(nameValue);
@@ -476,153 +467,153 @@ public abstract class EnrollDefault implements IPolicyDefault, ICertInfoPolicyDe
StringTokenizer st = new StringTokenizer(nameValue, "/");
String addr = st.nextToken();
String netmask = st.nextToken();
- CMS.debug("addr:" + addr +" netmask: "+netmask);
+ CMS.debug("addr:" + addr + " netmask: " + netmask);
return new IPAddressName(addr, netmask);
- } else {
+ } else {
return new IPAddressName(nameValue);
- }
+ }
}
if (nameType.equalsIgnoreCase("OIDName")) {
try {
- // check if OID
- ObjectIdentifier oid = new ObjectIdentifier(nameValue);
+ // check if OID
+ ObjectIdentifier oid = new ObjectIdentifier(nameValue);
} catch (Exception e) {
- return null;
+ return null;
}
return new OIDName(nameValue);
- }
+ }
if (nameType.equals("OtherName")) {
if (nameValue == null || nameValue.length() == 0)
nameValue = " ";
if (nameValue.startsWith("(PrintableString)")) {
- // format: OtherName: (PrintableString)oid,value
- int pos0 = nameValue.indexOf(')');
- int pos1 = nameValue.indexOf(',');
- if (pos1 == -1)
- return null;
- String on_oid = nameValue.substring(pos0 + 1, pos1).trim();
- String on_value = nameValue.substring(pos1 + 1).trim();
- if (isValidOID(on_oid)) {
- return new OtherName(new ObjectIdentifier(on_oid), DerValue.tag_PrintableString, on_value);
- } else {
- return null;
- }
+ // format: OtherName: (PrintableString)oid,value
+ int pos0 = nameValue.indexOf(')');
+ int pos1 = nameValue.indexOf(',');
+ if (pos1 == -1)
+ return null;
+ String on_oid = nameValue.substring(pos0 + 1, pos1).trim();
+ String on_value = nameValue.substring(pos1 + 1).trim();
+ if (isValidOID(on_oid)) {
+ return new OtherName(new ObjectIdentifier(on_oid), DerValue.tag_PrintableString, on_value);
+ } else {
+ return null;
+ }
} else if (nameValue.startsWith("(KerberosName)")) {
// Syntax: (KerberosName)Realm|NameType|NameString(s)
- int pos0 = nameValue.indexOf(')');
- int pos1 = nameValue.indexOf('|');
- int pos2 = nameValue.lastIndexOf('|');
- String realm = nameValue.substring(pos0 + 1, pos1).trim();
- String name_type = nameValue.substring(pos1 + 1, pos2).trim();
- String name_strings = nameValue.substring(pos2 + 1).trim();
- Vector<String> strings = new Vector<String>();
- StringTokenizer st = new StringTokenizer(name_strings, ",");
- while (st.hasMoreTokens()) {
- strings.addElement(st.nextToken());
- }
- KerberosName name = new KerberosName(realm,
- Integer.parseInt(name_type), strings);
- // krb5 OBJECT IDENTIFIER ::= { iso (1)
- // org (3)
- // dod (6)
- // internet (1)
- // security (5)
- // kerberosv5 (2) }
- // krb5PrincipalName OBJECT IDENTIFIER ::= { krb5 2 }
- return new OtherName(KerberosName.KRB5_PRINCIPAL_NAME,
- name.toByteArray());
+ int pos0 = nameValue.indexOf(')');
+ int pos1 = nameValue.indexOf('|');
+ int pos2 = nameValue.lastIndexOf('|');
+ String realm = nameValue.substring(pos0 + 1, pos1).trim();
+ String name_type = nameValue.substring(pos1 + 1, pos2).trim();
+ String name_strings = nameValue.substring(pos2 + 1).trim();
+ Vector<String> strings = new Vector<String>();
+ StringTokenizer st = new StringTokenizer(name_strings, ",");
+ while (st.hasMoreTokens()) {
+ strings.addElement(st.nextToken());
+ }
+ KerberosName name = new KerberosName(realm,
+ Integer.parseInt(name_type), strings);
+ // krb5 OBJECT IDENTIFIER ::= { iso (1)
+ // org (3)
+ // dod (6)
+ // internet (1)
+ // security (5)
+ // kerberosv5 (2) }
+ // krb5PrincipalName OBJECT IDENTIFIER ::= { krb5 2 }
+ return new OtherName(KerberosName.KRB5_PRINCIPAL_NAME,
+ name.toByteArray());
} else if (nameValue.startsWith("(IA5String)")) {
- int pos0 = nameValue.indexOf(')');
- int pos1 = nameValue.indexOf(',');
- if (pos1 == -1)
- return null;
- String on_oid = nameValue.substring(pos0 + 1, pos1).trim();
- String on_value = nameValue.substring(pos1 + 1).trim();
- if (isValidOID(on_oid)) {
- return new OtherName(new ObjectIdentifier(on_oid), DerValue.tag_IA5String, on_value);
- } else {
- return null;
- }
+ int pos0 = nameValue.indexOf(')');
+ int pos1 = nameValue.indexOf(',');
+ if (pos1 == -1)
+ return null;
+ String on_oid = nameValue.substring(pos0 + 1, pos1).trim();
+ String on_value = nameValue.substring(pos1 + 1).trim();
+ if (isValidOID(on_oid)) {
+ return new OtherName(new ObjectIdentifier(on_oid), DerValue.tag_IA5String, on_value);
+ } else {
+ return null;
+ }
} else if (nameValue.startsWith("(UTF8String)")) {
- int pos0 = nameValue.indexOf(')');
- int pos1 = nameValue.indexOf(',');
- if (pos1 == -1)
- return null;
- String on_oid = nameValue.substring(pos0 + 1, pos1).trim();
- String on_value = nameValue.substring(pos1 + 1).trim();
- if (isValidOID(on_oid)) {
- return new OtherName(new ObjectIdentifier(on_oid), DerValue.tag_UTF8String, on_value);
- } else {
- return null;
- }
+ int pos0 = nameValue.indexOf(')');
+ int pos1 = nameValue.indexOf(',');
+ if (pos1 == -1)
+ return null;
+ String on_oid = nameValue.substring(pos0 + 1, pos1).trim();
+ String on_value = nameValue.substring(pos1 + 1).trim();
+ if (isValidOID(on_oid)) {
+ return new OtherName(new ObjectIdentifier(on_oid), DerValue.tag_UTF8String, on_value);
+ } else {
+ return null;
+ }
} else if (nameValue.startsWith("(BMPString)")) {
- int pos0 = nameValue.indexOf(')');
- int pos1 = nameValue.indexOf(',');
- if (pos1 == -1)
- return null;
- String on_oid = nameValue.substring(pos0 + 1, pos1).trim();
- String on_value = nameValue.substring(pos1 + 1).trim();
- if (isValidOID(on_oid)) {
- return new OtherName(new ObjectIdentifier(on_oid), DerValue.tag_BMPString, on_value);
- } else {
- return null;
- }
+ int pos0 = nameValue.indexOf(')');
+ int pos1 = nameValue.indexOf(',');
+ if (pos1 == -1)
+ return null;
+ String on_oid = nameValue.substring(pos0 + 1, pos1).trim();
+ String on_value = nameValue.substring(pos1 + 1).trim();
+ if (isValidOID(on_oid)) {
+ return new OtherName(new ObjectIdentifier(on_oid), DerValue.tag_BMPString, on_value);
+ } else {
+ return null;
+ }
} else if (nameValue.startsWith("(Any)")) {
- int pos0 = nameValue.indexOf(')');
- int pos1 = nameValue.indexOf(',');
- if (pos1 == -1)
- return null;
- String on_oid = nameValue.substring(pos0 + 1, pos1).trim();
- String on_value = nameValue.substring(pos1 + 1).trim();
- if (isValidOID(on_oid)) {
- CMS.debug("OID: " + on_oid + " Value:" + on_value);
- return new OtherName(new ObjectIdentifier(on_oid), getBytes(on_value));
- } else {
- CMS.debug("Invalid OID " + on_oid);
- return null;
- }
+ int pos0 = nameValue.indexOf(')');
+ int pos1 = nameValue.indexOf(',');
+ if (pos1 == -1)
+ return null;
+ String on_oid = nameValue.substring(pos0 + 1, pos1).trim();
+ String on_value = nameValue.substring(pos1 + 1).trim();
+ if (isValidOID(on_oid)) {
+ CMS.debug("OID: " + on_oid + " Value:" + on_value);
+ return new OtherName(new ObjectIdentifier(on_oid), getBytes(on_value));
+ } else {
+ CMS.debug("Invalid OID " + on_oid);
+ return null;
+ }
} else {
- return null;
+ return null;
}
}
return null;
}
-/**
- * Converts string containing pairs of characters in the range of '0'
- * to '9', 'a' to 'f' to an array of bytes such that each pair of
- * characters in the string represents an individual byte
- */
+ /**
+ * Converts string containing pairs of characters in the range of '0' to
+ * '9', 'a' to 'f' to an array of bytes such that each pair of characters in
+ * the string represents an individual byte
+ */
public byte[] getBytes(String string) {
- if (string == null)
- return null;
- int stringLength = string.length();
- if ((stringLength == 0) || ((stringLength % 2) != 0))
- return null;
- byte[] bytes = new byte[ (stringLength / 2) ];
- for (int i = 0, b = 0; i < stringLength; i += 2, ++b) {
- String nextByte = string.substring(i, (i + 2));
- bytes[b] = (byte)Integer.parseInt(nextByte, 0x10);
- }
- return bytes;
+ if (string == null)
+ return null;
+ int stringLength = string.length();
+ if ((stringLength == 0) || ((stringLength % 2) != 0))
+ return null;
+ byte[] bytes = new byte[(stringLength / 2)];
+ for (int i = 0, b = 0; i < stringLength; i += 2, ++b) {
+ String nextByte = string.substring(i, (i + 2));
+ bytes[b] = (byte) Integer.parseInt(nextByte, 0x10);
+ }
+ return bytes;
}
/**
- * Check if a object identifier in string form is valid,
- * that is a string in the form n.n.n.n and der encode and decode-able.
+ * Check if a object identifier in string form is valid, that is a string in
+ * the form n.n.n.n and der encode and decode-able.
+ *
* @param oid object identifier string.
* @return true if the oid is valid
*/
- public boolean isValidOID(String oid)
- {
- ObjectIdentifier v = null;
+ public boolean isValidOID(String oid) {
+ ObjectIdentifier v = null;
try {
v = ObjectIdentifier.getObjectIdentifier(oid);
} catch (Exception e) {
- return false;
+ return false;
}
if (v == null)
- return false;
+ return false;
// if the OID isn't valid (ex. n.n) the error isn't caught til
// encoding time leaving a bad request in the request queue.
@@ -632,7 +623,7 @@ public abstract class EnrollDefault implements IPolicyDefault, ICertInfoPolicyDe
derOut.putOID(v);
new ObjectIdentifier(new DerInputStream(derOut.toByteArray()));
} catch (Exception e) {
- return false;
+ return false;
}
return true;
}
@@ -641,7 +632,7 @@ public abstract class EnrollDefault implements IPolicyDefault, ICertInfoPolicyDe
StringBuffer sb = new StringBuffer();
for (int i = 0; i < recs.size(); i++) {
- NameValuePairs pairs = recs.elementAt(i);
+ NameValuePairs pairs = recs.elementAt(i);
sb.append("Record #");
sb.append(i);
@@ -658,7 +649,7 @@ public abstract class EnrollDefault implements IPolicyDefault, ICertInfoPolicyDe
sb.append("\r\n");
}
sb.append("\r\n");
-
+
}
return sb.toString();
}
@@ -670,15 +661,15 @@ public abstract class EnrollDefault implements IPolicyDefault, ICertInfoPolicyDe
NameValuePairs nvps = null;
while (st.hasMoreTokens()) {
- String token = st.nextToken();
+ String token = st.nextToken();
if (token.equals("Record #" + num)) {
CMS.debug("parseRecords: Record" + num);
nvps = new NameValuePairs();
v.addElement(nvps);
try {
- token = st.nextToken();
- } catch (NoSuchElementException e) {
+ token = st.nextToken();
+ } catch (NoSuchElementException e) {
v.removeElementAt(num);
CMS.debug(e.toString());
return v;
@@ -688,7 +679,7 @@ public abstract class EnrollDefault implements IPolicyDefault, ICertInfoPolicyDe
if (nvps == null)
throw new EPropertyException("Bad Input Format");
-
+
int pos = token.indexOf(":");
if (pos <= 0) {
@@ -706,8 +697,8 @@ public abstract class EnrollDefault implements IPolicyDefault, ICertInfoPolicyDe
return v;
}
- protected String getGeneralNameType(GeneralName gn)
- throws EPropertyException {
+ protected String getGeneralNameType(GeneralName gn)
+ throws EPropertyException {
int type = gn.getType();
if (type == GeneralNameInterface.NAME_RFC822)
@@ -762,17 +753,17 @@ public abstract class EnrollDefault implements IPolicyDefault, ICertInfoPolicyDe
}
public String toGeneralNameString(GeneralNameInterface gn) {
- int type = gn.getType();
+ int type = gn.getType();
// Sun's General Name is not consistent, so we need
// to do a special case for directory string
if (type == GeneralNameInterface.NAME_DIRECTORY) {
- return "DirectoryName: " + gn.toString();
+ return "DirectoryName: " + gn.toString();
}
return gn.toString();
}
protected String mapPattern(IRequest request, String pattern)
- throws IOException {
+ throws IOException {
Pattern p = new Pattern(pattern);
IAttrSet attrSet = null;
if (request != null) {
@@ -781,30 +772,32 @@ public abstract class EnrollDefault implements IPolicyDefault, ICertInfoPolicyDe
return p.substitute2("request", attrSet);
}
- protected StringBuffer escapeValueRfc1779(String v, boolean doubleEscape)
- {
+ protected StringBuffer escapeValueRfc1779(String v, boolean doubleEscape) {
StringBuffer result = new StringBuffer();
// Do we need to escape any characters
for (int i = 0; i < v.length(); i++) {
int c = v.charAt(i);
if (c == ',' || c == '=' || c == '+' || c == '<' ||
- c == '>' || c == '#' || c == ';' || c == '\r' ||
- c == '\n' || c == '\\' || c == '"') {
- if ((c == 0x5c) && ((i+1) < v.length())) {
- int nextC = v.charAt(i+1);
+ c == '>' || c == '#' || c == ';' || c == '\r' ||
+ c == '\n' || c == '\\' || c == '"') {
+ if ((c == 0x5c) && ((i + 1) < v.length())) {
+ int nextC = v.charAt(i + 1);
if ((c == 0x5c) && (nextC == ',' || nextC == '=' || nextC == '+' ||
nextC == '<' || nextC == '>' || nextC == '#' ||
nextC == ';' || nextC == '\r' || nextC == '\n' ||
nextC == '\\' || nextC == '"')) {
- if (doubleEscape) result.append('\\');
+ if (doubleEscape)
+ result.append('\\');
} else {
result.append('\\');
- if (doubleEscape) result.append('\\');
+ if (doubleEscape)
+ result.append('\\');
}
} else {
result.append('\\');
- if (doubleEscape) result.append('\\');
+ if (doubleEscape)
+ result.append('\\');
}
}
if (c == '\r') {
@@ -812,10 +805,10 @@ public abstract class EnrollDefault implements IPolicyDefault, ICertInfoPolicyDe
} else if (c == '\n') {
result.append("0A");
} else {
- result.append((char)c);
+ result.append((char) c);
}
}
return result;
}
-
+
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/EnrollExtDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/EnrollExtDefault.java
index 7cf2a359..acdf98b4 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/EnrollExtDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/EnrollExtDefault.java
@@ -17,14 +17,10 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
-
-
/**
- * This class implements an enrollment extension
- * default policy that extension into the certificate
- * template.
- *
+ * This class implements an enrollment extension default policy that extension
+ * into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public abstract class EnrollExtDefault extends EnrollDefault {
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/ExtendedKeyUsageExtDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/ExtendedKeyUsageExtDefault.java
index 62d21cc8..4ea3679b 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/ExtendedKeyUsageExtDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/ExtendedKeyUsageExtDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.util.Enumeration;
import java.util.Locale;
import java.util.StringTokenizer;
@@ -35,12 +34,10 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements an enrollment default policy
- * that populates Extended Key Usage extension
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates Extended
+ * Key Usage extension into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class ExtendedKeyUsageExtDefault extends EnrollExtDefault {
@@ -60,17 +57,17 @@ public class ExtendedKeyUsageExtDefault extends EnrollExtDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
if (name.equals(CONFIG_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.equals(CONFIG_OIDS)) {
- return new Descriptor(IDescriptor.STRING, null,
+ return new Descriptor(IDescriptor.STRING, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_OIDS"));
}
@@ -91,51 +88,49 @@ public class ExtendedKeyUsageExtDefault extends EnrollExtDefault {
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
ExtendedKeyUsageExtension ext = null;
-
ext = (ExtendedKeyUsageExtension)
getExtension(ExtendedKeyUsageExtension.OID, info);
- if(ext == null)
- {
+ if (ext == null) {
try {
- populate(null,info);
+ populate(null, info);
} catch (EProfileException e) {
- throw new EPropertyException(CMS.getUserMessage(
- locale, "CMS_INVALID_PROPERTY", name));
+ throw new EPropertyException(CMS.getUserMessage(
+ locale, "CMS_INVALID_PROPERTY", name));
}
- }
- if (name == null) {
+ }
+ if (name == null) {
throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
if (name.equals(VAL_CRITICAL)) {
ext = (ExtendedKeyUsageExtension)
- getExtension(ExtendedKeyUsageExtension.OID, info);
- boolean val = Boolean.valueOf(value).booleanValue();
+ getExtension(ExtendedKeyUsageExtension.OID, info);
+ boolean val = Boolean.valueOf(value).booleanValue();
- if(ext == null) {
+ if (ext == null) {
return;
}
- ext.setCritical(val);
+ ext.setCritical(val);
} else if (name.equals(VAL_OIDS)) {
ext = (ExtendedKeyUsageExtension)
getExtension(ExtendedKeyUsageExtension.OID, info);
- // ext.deleteAllOIDs();
+ // ext.deleteAllOIDs();
StringTokenizer st = new StringTokenizer(value, ",");
- if(ext == null) {
+ if (ext == null) {
return;
}
while (st.hasMoreTokens()) {
String oid = st.nextToken();
- ext.addOID(new ObjectIdentifier(oid));
+ ext.addOID(new ObjectIdentifier(oid));
}
} else {
throw new EPropertyException(CMS.getUserMessage(
@@ -151,8 +146,8 @@ public class ExtendedKeyUsageExtDefault extends EnrollExtDefault {
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
+ X509CertInfo info)
+ throws EPropertyException {
if (name == null) {
throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
@@ -160,23 +155,21 @@ public class ExtendedKeyUsageExtDefault extends EnrollExtDefault {
ExtendedKeyUsageExtension ext = (ExtendedKeyUsageExtension)
getExtension(ExtendedKeyUsageExtension.OID, info);
-
- if(ext == null)
- {
+ if (ext == null) {
try {
- populate(null,info);
+ populate(null, info);
} catch (EProfileException e) {
- throw new EPropertyException(CMS.getUserMessage(
- locale, "CMS_INVALID_PROPERTY", name));
+ throw new EPropertyException(CMS.getUserMessage(
+ locale, "CMS_INVALID_PROPERTY", name));
}
}
if (name.equals(VAL_CRITICAL)) {
ext = (ExtendedKeyUsageExtension)
- getExtension(ExtendedKeyUsageExtension.OID, info);
+ getExtension(ExtendedKeyUsageExtension.OID, info);
if (ext == null) {
return null;
@@ -188,20 +181,20 @@ public class ExtendedKeyUsageExtDefault extends EnrollExtDefault {
}
} else if (name.equals(VAL_OIDS)) {
ext = (ExtendedKeyUsageExtension)
- getExtension(ExtendedKeyUsageExtension.OID, info);
+ getExtension(ExtendedKeyUsageExtension.OID, info);
StringBuffer sb = new StringBuffer();
- if(ext == null) {
+ if (ext == null) {
return "";
}
Enumeration e = ext.getOIDs();
while (e.hasMoreElements()) {
ObjectIdentifier oid = (ObjectIdentifier)
- e.nextElement();
+ e.nextElement();
if (!sb.toString().equals("")) {
sb.append(",");
- }
+ }
sb.append(oid.toString());
}
return sb.toString();
@@ -213,11 +206,11 @@ public class ExtendedKeyUsageExtDefault extends EnrollExtDefault {
public String getText(Locale locale) {
String params[] = {
- getConfig(CONFIG_CRITICAL),
+ getConfig(CONFIG_CRITICAL),
getConfig(CONFIG_OIDS)
};
- return CMS.getUserMessage(locale,
+ return CMS.getUserMessage(locale,
"CMS_PROFILE_DEF_EXTENDED_KEY_EXT", params);
}
@@ -225,20 +218,20 @@ public class ExtendedKeyUsageExtDefault extends EnrollExtDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
ExtendedKeyUsageExtension ext = createExtension();
addExtension(ExtendedKeyUsageExtension.OID, ext, info);
}
public ExtendedKeyUsageExtension createExtension() {
- ExtendedKeyUsageExtension ext = null;
+ ExtendedKeyUsageExtension ext = null;
try {
ext = new ExtendedKeyUsageExtension();
} catch (Exception e) {
CMS.debug("ExtendedKeyUsageExtDefault: createExtension " +
- e.toString());
+ e.toString());
}
if (ext == null)
return null;
@@ -250,7 +243,7 @@ public class ExtendedKeyUsageExtDefault extends EnrollExtDefault {
while (st.hasMoreTokens()) {
String oid = st.nextToken();
- ext.addOID(new ObjectIdentifier(oid));
+ ext.addOID(new ObjectIdentifier(oid));
}
return ext;
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/FreshestCRLExtDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/FreshestCRLExtDefault.java
index 13af0426..5824bbfd 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/FreshestCRLExtDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/FreshestCRLExtDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.io.IOException;
import java.util.Enumeration;
import java.util.Locale;
@@ -42,12 +41,10 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements an enrollment default policy
- * that populates Freshest CRL extension
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates Freshest
+ * CRL extension into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class FreshestCRLExtDefault extends EnrollExtDefault {
@@ -61,8 +58,8 @@ public class FreshestCRLExtDefault extends EnrollExtDefault {
public static final String CONFIG_ENABLE = "freshestCRLPointEnable_";
public static final String VAL_CRITICAL = "freshestCRLCritical";
- public static final String VAL_CRL_DISTRIBUTION_POINTS =
- "freshestCRLPointsValue";
+ public static final String VAL_CRL_DISTRIBUTION_POINTS =
+ "freshestCRLPointsValue";
private static final String POINT_TYPE = "Point Type";
private static final String POINT_NAME = "Point Name";
@@ -78,12 +75,11 @@ public class FreshestCRLExtDefault extends EnrollExtDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
refreshConfigAndValueNames();
}
-
protected int getNumPoints() {
int num = DEF_NUM_POINTS;
String val = getConfig(CONFIG_NUM_POINTS);
@@ -103,33 +99,32 @@ public class FreshestCRLExtDefault extends EnrollExtDefault {
}
public void setConfig(String name, String value)
- throws EPropertyException {
+ throws EPropertyException {
int num = 0;
if (name.equals(CONFIG_NUM_POINTS)) {
- try {
- num = Integer.parseInt(value);
+ try {
+ num = Integer.parseInt(value);
- if (num >= MAX_NUM_POINTS || num < 0) {
- throw new EPropertyException(CMS.getUserMessage(
+ if (num >= MAX_NUM_POINTS || num < 0) {
+ throw new EPropertyException(CMS.getUserMessage(
"CMS_INVALID_PROPERTY", CONFIG_NUM_POINTS));
- }
+ }
- } catch (Exception e) {
+ } catch (Exception e) {
throw new EPropertyException(CMS.getUserMessage(
"CMS_INVALID_PROPERTY", CONFIG_NUM_POINTS));
- }
+ }
}
super.setConfig(name, value);
}
-
public Enumeration<String> getConfigNames() {
refreshConfigAndValueNames();
return super.getConfigNames();
}
protected void refreshConfigAndValueNames() {
- //refesh our config name list
+ // refesh our config name list
super.refreshConfigAndValueNames();
addValueName(VAL_CRITICAL);
@@ -149,47 +144,47 @@ public class FreshestCRLExtDefault extends EnrollExtDefault {
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
- if (name.equals(CONFIG_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ if (name.equals(CONFIG_CRITICAL)) {
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.startsWith(CONFIG_POINT_TYPE)) {
- return new Descriptor(IDescriptor.STRING, null,
+ return new Descriptor(IDescriptor.STRING, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_POINT_TYPE"));
} else if (name.startsWith(CONFIG_POINT_NAME)) {
- return new Descriptor(IDescriptor.STRING, null,
+ return new Descriptor(IDescriptor.STRING, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_POINT_NAME"));
} else if (name.startsWith(CONFIG_ISSUER_TYPE)) {
- return new Descriptor(IDescriptor.STRING, null,
+ return new Descriptor(IDescriptor.STRING, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_ISSUER_TYPE"));
} else if (name.startsWith(CONFIG_ISSUER_NAME)) {
- return new Descriptor(IDescriptor.STRING, null,
+ return new Descriptor(IDescriptor.STRING, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_ISSUER_NAME"));
} else if (name.startsWith(CONFIG_ENABLE)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_ENABLE"));
} else if (name.startsWith(CONFIG_NUM_POINTS)) {
return new Descriptor(IDescriptor.INTEGER, null,
- "1",
- CMS.getUserMessage(locale, "CMS_PROFILE_NUM_DIST_POINTS"));
+ "1",
+ CMS.getUserMessage(locale, "CMS_PROFILE_NUM_DIST_POINTS"));
} else {
return null;
}
}
public IDescriptor getValueDescriptor(Locale locale, String name) {
- if (name.equals(VAL_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ if (name.equals(VAL_CRITICAL)) {
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.equals(VAL_CRL_DISTRIBUTION_POINTS)) {
- return new Descriptor(IDescriptor.STRING_LIST, null,
+ return new Descriptor(IDescriptor.STRING_LIST, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_CRL_DISTRIBUTION_POINTS"));
} else {
@@ -198,39 +193,39 @@ public class FreshestCRLExtDefault extends EnrollExtDefault {
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
try {
FreshestCRLExtension ext = null;
- if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ if (name == null) {
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
ext = (FreshestCRLExtension)
getExtension(FreshestCRLExtension.OID,
- info);
+ info);
- if(ext == null) {
- populate(locale,info);
+ if (ext == null) {
+ populate(locale, info);
}
-
+
if (name.equals(VAL_CRITICAL)) {
ext = (FreshestCRLExtension)
- getExtension(FreshestCRLExtension.OID,
- info);
+ getExtension(FreshestCRLExtension.OID,
+ info);
boolean val = Boolean.valueOf(value).booleanValue();
- ext.setCritical(val);
- } else if (name.equals(VAL_CRL_DISTRIBUTION_POINTS)) {
+ ext.setCritical(val);
+ } else if (name.equals(VAL_CRL_DISTRIBUTION_POINTS)) {
ext = (FreshestCRLExtension)
- getExtension(FreshestCRLExtension.OID,
- info);
+ getExtension(FreshestCRLExtension.OID,
+ info);
Vector<NameValuePairs> v = parseRecords(value);
int size = v.size();
-
+
boolean critical = ext.isCritical();
int i = 0;
@@ -266,7 +261,7 @@ public class FreshestCRLExtDefault extends EnrollExtDefault {
if (issuerType != null)
addIssuer(locale, cdp, issuerType, issuerValue);
- // this is the first distribution point
+ // this is the first distribution point
if (i == 0) {
ext = new FreshestCRLExtension(cdp);
ext.setCritical(critical);
@@ -276,100 +271,99 @@ public class FreshestCRLExtDefault extends EnrollExtDefault {
}
}
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
replaceExtension(PKIXExtensions.FreshestCRL_Id.toString(),
- ext, info);
+ ext, info);
} catch (EProfileException e) {
- CMS.debug("FreshestCRLExtDefault: setValue " +
- e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ CMS.debug("FreshestCRLExtDefault: setValue " +
+ e.toString());
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
private void addCRLPoint(Locale locale, CRLDistributionPoint cdp, String type,
- String value) throws EPropertyException {
+ String value) throws EPropertyException {
try {
if (value == null || value.length() == 0)
return;
-
+
if (isGeneralNameType(type)) {
GeneralNames gen = new GeneralNames();
- gen.addElement(parseGeneralName(type,value));
+ gen.addElement(parseGeneralName(type, value));
cdp.setFullName(gen);
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", type));
}
} catch (IOException e) {
- CMS.debug("FreshestCRLExtDefault: addCRLPoint " +
- e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ CMS.debug("FreshestCRLExtDefault: addCRLPoint " +
+ e.toString());
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", type));
} catch (GeneralNamesException e) {
- CMS.debug("FreshestCRLExtDefault: addCRLPoint " +
- e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ CMS.debug("FreshestCRLExtDefault: addCRLPoint " +
+ e.toString());
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", type));
}
}
private void addIssuer(Locale locale, CRLDistributionPoint cdp, String type,
- String value) throws EPropertyException {
+ String value) throws EPropertyException {
if (value == null || value.length() == 0)
return;
try {
if (isGeneralNameType(type)) {
GeneralNames gen = new GeneralNames();
- gen.addElement(parseGeneralName(type,value));
+ gen.addElement(parseGeneralName(type, value));
cdp.setCRLIssuer(gen);
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", type));
}
} catch (IOException e) {
- CMS.debug("FreshestCRLExtDefault: addIssuer " +
- e.toString());
+ CMS.debug("FreshestCRLExtDefault: addIssuer " +
+ e.toString());
} catch (GeneralNamesException e) {
- CMS.debug("FreshestCRLExtDefault: addIssuer " +
- e.toString());
+ CMS.debug("FreshestCRLExtDefault: addIssuer " +
+ e.toString());
}
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
+ X509CertInfo info)
+ throws EPropertyException {
FreshestCRLExtension ext = null;
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
ext = (FreshestCRLExtension)
getExtension(FreshestCRLExtension.OID,
- info);
- if(ext == null)
- {
+ info);
+ if (ext == null) {
try {
- populate(locale,info);
+ populate(locale, info);
} catch (EProfileException e) {
- throw new EPropertyException(CMS.getUserMessage(
- locale, "CMS_INVALID_PROPERTY", name));
+ throw new EPropertyException(CMS.getUserMessage(
+ locale, "CMS_INVALID_PROPERTY", name));
}
}
if (name.equals(VAL_CRITICAL)) {
ext = (FreshestCRLExtension)
- getExtension(FreshestCRLExtension.OID,
- info);
+ getExtension(FreshestCRLExtension.OID,
+ info);
if (ext == null) {
return null;
@@ -379,10 +373,10 @@ public class FreshestCRLExtDefault extends EnrollExtDefault {
} else {
return "false";
}
- } else if (name.equals(VAL_CRL_DISTRIBUTION_POINTS)) {
+ } else if (name.equals(VAL_CRL_DISTRIBUTION_POINTS)) {
ext = (FreshestCRLExtension)
- getExtension(FreshestCRLExtension.OID,
- info);
+ getExtension(FreshestCRLExtension.OID,
+ info);
if (ext == null)
return "";
@@ -395,7 +389,7 @@ public class FreshestCRLExtDefault extends EnrollExtDefault {
NameValuePairs pairs = null;
if (i < ext.getNumPoints()) {
- CRLDistributionPoint p = ext.getPointAt(i);
+ CRLDistributionPoint p = ext.getPointAt(i);
GeneralNames gns = p.getFullName();
pairs = buildGeneralNames(gns, p);
@@ -404,10 +398,10 @@ public class FreshestCRLExtDefault extends EnrollExtDefault {
}
recs.addElement(pairs);
}
-
+
return buildRecords(recs);
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
@@ -424,7 +418,7 @@ public class FreshestCRLExtDefault extends EnrollExtDefault {
}
protected NameValuePairs buildGeneralNames(GeneralNames gns, CRLDistributionPoint p)
- throws EPropertyException {
+ throws EPropertyException {
NameValuePairs pairs = new NameValuePairs();
@@ -495,8 +489,8 @@ public class FreshestCRLExtDefault extends EnrollExtDefault {
sb.append(getConfig(CONFIG_ENABLE + i));
sb.append("}");
}
- return CMS.getUserMessage(locale,
- "CMS_PROFILE_DEF_FRESHEST_CRL_EXT",
+ return CMS.getUserMessage(locale,
+ "CMS_PROFILE_DEF_FRESHEST_CRL_EXT",
getConfig(CONFIG_CRITICAL),
sb.toString());
}
@@ -505,7 +499,7 @@ public class FreshestCRLExtDefault extends EnrollExtDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
FreshestCRLExtension ext = createExtension(request);
if (ext == null)
@@ -519,14 +513,14 @@ public class FreshestCRLExtDefault extends EnrollExtDefault {
try {
boolean critical = getConfigBoolean(CONFIG_CRITICAL);
- ext.setCritical(critical);
+ ext.setCritical(critical);
num = getNumPoints();
for (int i = 0; i < num; i++) {
CRLDistributionPoint cdp = new CRLDistributionPoint();
- String enable = getConfig(CONFIG_ENABLE + i);
- String pointType = getConfig(CONFIG_POINT_TYPE + i);
+ String enable = getConfig(CONFIG_ENABLE + i);
+ String pointType = getConfig(CONFIG_POINT_TYPE + i);
String pointName = getConfig(CONFIG_POINT_NAME + i);
String issuerType = getConfig(CONFIG_ISSUER_TYPE + i);
String issuerName = getConfig(CONFIG_ISSUER_NAME + i);
@@ -537,12 +531,12 @@ public class FreshestCRLExtDefault extends EnrollExtDefault {
if (issuerType != null)
addIssuer(getLocale(request), cdp, issuerType, issuerName);
- ext.addPoint(cdp);
+ ext.addPoint(cdp);
}
}
} catch (Exception e) {
CMS.debug("FreshestCRLExtDefault: createExtension " +
- e.toString());
+ e.toString());
}
return ext;
@@ -552,7 +546,7 @@ public class FreshestCRLExtDefault extends EnrollExtDefault {
* Populates the request with this policy default.
*/
private void populate(Locale locale, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
FreshestCRLExtension ext = createExtension(locale);
if (ext == null)
@@ -589,7 +583,7 @@ public class FreshestCRLExtDefault extends EnrollExtDefault {
}
} catch (Exception e) {
CMS.debug("FreshestCRLExtDefault: createExtension " +
- e.toString());
+ e.toString());
}
return ext;
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/GenericExtDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/GenericExtDefault.java
index 4051f31a..c1e109d2 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/GenericExtDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/GenericExtDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.util.Locale;
import netscape.security.util.DerOutputStream;
@@ -34,12 +33,10 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements an enrollment default policy
- * that populates a Netscape comment extension
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates a Netscape
+ * comment extension into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class GenericExtDefault extends EnrollExtDefault {
@@ -62,13 +59,13 @@ public class GenericExtDefault extends EnrollExtDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
if (name.equals(CONFIG_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.equals(CONFIG_OID)) {
@@ -86,7 +83,7 @@ public class GenericExtDefault extends EnrollExtDefault {
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.equals(VAL_DATA)) {
@@ -99,13 +96,13 @@ public class GenericExtDefault extends EnrollExtDefault {
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
try {
Extension ext = null;
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
@@ -114,28 +111,28 @@ public class GenericExtDefault extends EnrollExtDefault {
ext = (Extension)
getExtension(oid.toString(), info);
- if(ext == null) {
- populate(null,info);
+ if (ext == null) {
+ populate(null, info);
}
if (name.equals(VAL_CRITICAL)) {
ext = (Extension)
getExtension(oid.toString(), info);
- if (ext == null) {
+ if (ext == null) {
return;
}
boolean val = Boolean.valueOf(value).booleanValue();
- ext.setCritical(val);
- } else if (name.equals(VAL_DATA)) {
+ ext.setCritical(val);
+ } else if (name.equals(VAL_DATA)) {
ext = (Extension)
getExtension(oid.toString(), info);
- if (ext == null) {
+ if (ext == null) {
return;
}
byte data[] = getBytes(value);
- ext.setExtensionValue(data);
+ ext.setExtensionValue(data);
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
@@ -146,12 +143,12 @@ public class GenericExtDefault extends EnrollExtDefault {
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
+ X509CertInfo info)
+ throws EPropertyException {
Extension ext = null;
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
@@ -160,14 +157,13 @@ public class GenericExtDefault extends EnrollExtDefault {
ext = (Extension)
getExtension(oid.toString(), info);
- if(ext == null)
- {
+ if (ext == null) {
try {
- populate(null,info);
+ populate(null, info);
} catch (EProfileException e) {
- throw new EPropertyException(CMS.getUserMessage(
- locale, "CMS_INVALID_PROPERTY", name));
+ throw new EPropertyException(CMS.getUserMessage(
+ locale, "CMS_INVALID_PROPERTY", name));
}
}
@@ -185,7 +181,7 @@ public class GenericExtDefault extends EnrollExtDefault {
} else {
return "false";
}
- } else if (name.equals(VAL_DATA)) {
+ } else if (name.equals(VAL_DATA)) {
ext = (Extension)
getExtension(oid.toString(), info);
@@ -197,17 +193,17 @@ public class GenericExtDefault extends EnrollExtDefault {
if (data == null)
return "";
-
+
return toStr(data);
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
public String getText(Locale locale) {
String params[] = {
- getConfig(CONFIG_CRITICAL),
+ getConfig(CONFIG_CRITICAL),
getConfig(CONFIG_OID),
getConfig(CONFIG_DATA)
};
@@ -218,10 +214,10 @@ public class GenericExtDefault extends EnrollExtDefault {
public String toStr(byte data[]) {
StringBuffer b = new StringBuffer();
for (int i = 0; i < data.length; i++) {
- if ((data[i] & 0xff) < 16) {
- b.append("0");
- }
- b.append(Integer.toString((int)(data[i] & 0xff), 0x10));
+ if ((data[i] & 0xff) < 16) {
+ b.append("0");
+ }
+ b.append(Integer.toString((int) (data[i] & 0xff), 0x10));
}
return b.toString();
}
@@ -230,14 +226,14 @@ public class GenericExtDefault extends EnrollExtDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
Extension ext = createExtension(request);
addExtension(ext.getExtensionId().toString(), ext, info);
}
public Extension createExtension(IRequest request) {
- Extension ext = null;
+ Extension ext = null;
try {
boolean critical = getConfigBoolean(CONFIG_CRITICAL);
@@ -250,13 +246,13 @@ public class GenericExtDefault extends EnrollExtDefault {
data = getBytes(mapPattern(request, getConfig(CONFIG_DATA)));
}
- DerOutputStream out = new DerOutputStream();
+ DerOutputStream out = new DerOutputStream();
out.putOctetString(data);
ext = new Extension(oid, critical, out.toByteArray());
} catch (Exception e) {
- CMS.debug("GenericExtDefault: createExtension " +
- e.toString());
+ CMS.debug("GenericExtDefault: createExtension " +
+ e.toString());
}
return ext;
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/ImageDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/ImageDefault.java
index 5bb8abd4..dc1fa33d 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/ImageDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/ImageDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.util.Locale;
import netscape.security.x509.X509CertInfo;
@@ -31,11 +30,10 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements an enrollment default policy
- * that shows an image in the approval page.
- *
+ * This class implements an enrollment default policy that shows an image in the
+ * approval page.
+ *
* @version $Revision$, $Date$
*/
public class ImageDefault extends EnrollDefault {
@@ -50,7 +48,7 @@ public class ImageDefault extends EnrollDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
@@ -68,12 +66,12 @@ public class ImageDefault extends EnrollDefault {
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
}
public String getValue(String name, Locale locale, IRequest request)
- throws EPropertyException {
+ throws EPropertyException {
if (name == null) {
throw new EPropertyException(CMS.getUserMessage(
@@ -89,19 +87,19 @@ public class ImageDefault extends EnrollDefault {
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
+ X509CertInfo info)
+ throws EPropertyException {
return null;
}
public String getText(Locale locale) {
- return CMS.getUserMessage(locale, "CMS_PROFILE_DEF_IMAGE" );
+ return CMS.getUserMessage(locale, "CMS_PROFILE_DEF_IMAGE");
}
/**
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
}
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/InhibitAnyPolicyExtDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/InhibitAnyPolicyExtDefault.java
index c6bbc7f7..c0a92ee7 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/InhibitAnyPolicyExtDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/InhibitAnyPolicyExtDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.math.BigInteger;
import java.util.Locale;
@@ -34,10 +33,9 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
* This class implements an inhibit Any-Policy extension
- *
+ *
* @version $Revision$, $Date$
*/
public class InhibitAnyPolicyExtDefault extends EnrollExtDefault {
@@ -61,31 +59,31 @@ public class InhibitAnyPolicyExtDefault extends EnrollExtDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
if (name.equals(CONFIG_CRITICAL)) {
return new Descriptor(IDescriptor.BOOLEAN, null, "true",
- CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
+ CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.startsWith(CONFIG_SKIP_CERTS)) {
return new Descriptor(IDescriptor.INTEGER, null, "0",
- CMS.getUserMessage(locale, "CMS_PROFILE_SKIP_CERTS"));
+ CMS.getUserMessage(locale, "CMS_PROFILE_SKIP_CERTS"));
} else {
return null;
}
}
public void setConfig(String name, String value)
- throws EPropertyException {
+ throws EPropertyException {
if (name.equals(CONFIG_SKIP_CERTS)) {
- try {
- Integer.parseInt(value);
- } catch (Exception e) {
+ try {
+ Integer.parseInt(value);
+ } catch (Exception e) {
throw new EPropertyException(CMS.getUserMessage(
"CMS_INVALID_PROPERTY", CONFIG_SKIP_CERTS));
- }
+ }
}
super.setConfig(name, value);
}
@@ -93,36 +91,36 @@ public class InhibitAnyPolicyExtDefault extends EnrollExtDefault {
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_CRITICAL)) {
return new Descriptor(IDescriptor.BOOLEAN, null, "true",
- CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
+ CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.equals(VAL_SKIP_CERTS)) {
return new Descriptor(IDescriptor.INTEGER, null, "0",
- CMS.getUserMessage(locale, "CMS_PROFILE_SKIP_CERTS"));
+ CMS.getUserMessage(locale, "CMS_PROFILE_SKIP_CERTS"));
} else {
return null;
}
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
try {
InhibitAnyPolicyExtension ext = null;
- if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ if (name == null) {
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
ext = (InhibitAnyPolicyExtension)
- getExtension(InhibitAnyPolicyExtension.OID, info);
+ getExtension(InhibitAnyPolicyExtension.OID, info);
- if(ext == null) {
- populate(null,info);
- }
+ if (ext == null) {
+ populate(null, info);
+ }
if (name.equals(VAL_CRITICAL)) {
ext = (InhibitAnyPolicyExtension)
- getExtension(InhibitAnyPolicyExtension.OID, info);
+ getExtension(InhibitAnyPolicyExtension.OID, info);
if (ext == null) {
// it is ok, the extension is never populated or delted
@@ -133,7 +131,7 @@ public class InhibitAnyPolicyExtDefault extends EnrollExtDefault {
ext.setCritical(critical);
} else if (name.equals(VAL_SKIP_CERTS)) {
ext = (InhibitAnyPolicyExtension)
- getExtension(InhibitAnyPolicyExtension.OID, info);
+ getExtension(InhibitAnyPolicyExtension.OID, info);
if (ext == null) {
// it is ok, the extension is never populated or delted
@@ -150,48 +148,47 @@ public class InhibitAnyPolicyExtDefault extends EnrollExtDefault {
BigInteger l = new BigInteger(value);
num = new BigInt(l);
} catch (Exception e) {
- throw new EPropertyException(CMS.getUserMessage(
- locale, "CMS_INVALID_PROPERTY", name));
+ throw new EPropertyException(CMS.getUserMessage(
+ locale, "CMS_INVALID_PROPERTY", name));
}
ext = new InhibitAnyPolicyExtension(critical,
- num);
+ num);
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
replaceExtension(InhibitAnyPolicyExtension.OID, ext, info);
} catch (EProfileException e) {
CMS.debug("InhibitAnyPolicyExtDefault: setValue " + e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
+ X509CertInfo info)
+ throws EPropertyException {
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
- locale, "CMS_INVALID_PROPERTY", name));
+ throw new EPropertyException(CMS.getUserMessage(
+ locale, "CMS_INVALID_PROPERTY", name));
}
InhibitAnyPolicyExtension ext =
- (InhibitAnyPolicyExtension)
- getExtension(InhibitAnyPolicyExtension.OID, info);
+ (InhibitAnyPolicyExtension)
+ getExtension(InhibitAnyPolicyExtension.OID, info);
- if(ext == null)
- {
+ if (ext == null) {
try {
- populate(null,info);
+ populate(null, info);
} catch (EProfileException e) {
throw new EPropertyException(CMS.getUserMessage(
- locale, "CMS_INVALID_PROPERTY", name));
+ locale, "CMS_INVALID_PROPERTY", name));
}
}
if (name.equals(VAL_CRITICAL)) {
ext = (InhibitAnyPolicyExtension)
- getExtension(InhibitAnyPolicyExtension.OID, info);
+ getExtension(InhibitAnyPolicyExtension.OID, info);
if (ext == null) {
return null;
@@ -203,38 +200,37 @@ public class InhibitAnyPolicyExtDefault extends EnrollExtDefault {
}
} else if (name.equals(VAL_SKIP_CERTS)) {
ext = (InhibitAnyPolicyExtension)
- getExtension(InhibitAnyPolicyExtension.OID, info);
+ getExtension(InhibitAnyPolicyExtension.OID, info);
if (ext == null) {
return null;
}
BigInt n = ext.getSkipCerts();
- return ""+n.toInt();
+ return "" + n.toInt();
} else {
- throw new EPropertyException(CMS.getUserMessage(
- locale, "CMS_INVALID_PROPERTY", name));
- }
+ throw new EPropertyException(CMS.getUserMessage(
+ locale, "CMS_INVALID_PROPERTY", name));
+ }
}
/*
- * returns text that goes into description for this extension on
- * a profile
+ * returns text that goes into description for this extension on a profile
*/
public String getText(Locale locale) {
- StringBuffer sb = new StringBuffer();
+ StringBuffer sb = new StringBuffer();
sb.append(SKIP_CERTS + ":");
sb.append(getConfig(CONFIG_SKIP_CERTS));
- return CMS.getUserMessage(locale,
- "CMS_PROFILE_DEF_INHIBIT_ANY_POLICY_EXT",
- getConfig(CONFIG_CRITICAL), sb.toString());
+ return CMS.getUserMessage(locale,
+ "CMS_PROFILE_DEF_INHIBIT_ANY_POLICY_EXT",
+ getConfig(CONFIG_CRITICAL), sb.toString());
}
/**
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
InhibitAnyPolicyExtension ext = null;
ext = createExtension(request);
@@ -242,7 +238,7 @@ public class InhibitAnyPolicyExtDefault extends EnrollExtDefault {
}
public InhibitAnyPolicyExtension createExtension(IRequest request)
- throws EProfileException {
+ throws EProfileException {
InhibitAnyPolicyExtension ext = null;
boolean critical = Boolean.valueOf(
@@ -259,7 +255,7 @@ public class InhibitAnyPolicyExtDefault extends EnrollExtDefault {
val = new BigInt(b);
} catch (NumberFormatException e) {
throw new EProfileException(
- CMS.getUserMessage("CMS_PROFILE_INHIBIT_ANY_POLICY_WRONG_SKIP_CERTS"));
+ CMS.getUserMessage("CMS_PROFILE_INHIBIT_ANY_POLICY_WRONG_SKIP_CERTS"));
}
try {
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/IssuerAltNameExtDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/IssuerAltNameExtDefault.java
index 40bd4876..00a05305 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/IssuerAltNameExtDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/IssuerAltNameExtDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.io.IOException;
import java.util.Enumeration;
import java.util.Locale;
@@ -39,12 +38,10 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements an enrollment default policy
- * that populates a issuer alternative name extension
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates a issuer
+ * alternative name extension into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class IssuerAltNameExtDefault extends EnrollExtDefault {
@@ -67,25 +64,25 @@ public class IssuerAltNameExtDefault extends EnrollExtDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
if (name.equals(CONFIG_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.equals(CONFIG_TYPE)) {
return new Descriptor(IDescriptor.CHOICE, "RFC822Name,DNSName,DirectoryName,EDIPartyName,URIName,IPAddress,OIDName",
"RFC822Name",
- CMS.getUserMessage(locale,
- "CMS_PROFILE_ISSUER_ALT_NAME_TYPE"));
+ CMS.getUserMessage(locale,
+ "CMS_PROFILE_ISSUER_ALT_NAME_TYPE"));
} else if (name.equals(CONFIG_PATTERN)) {
- return new Descriptor(IDescriptor.STRING, null,
+ return new Descriptor(IDescriptor.STRING, null,
null,
- CMS.getUserMessage(locale,
- "CMS_PROFILE_ISSUER_ALT_NAME_PATTERN"));
+ CMS.getUserMessage(locale,
+ "CMS_PROFILE_ISSUER_ALT_NAME_PATTERN"));
} else {
return null;
}
@@ -93,11 +90,11 @@ public class IssuerAltNameExtDefault extends EnrollExtDefault {
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.equals(VAL_GENERAL_NAMES)) {
- return new Descriptor(IDescriptor.STRING_LIST, null,
+ return new Descriptor(IDescriptor.STRING_LIST, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_GENERAL_NAMES"));
} else {
@@ -106,13 +103,13 @@ public class IssuerAltNameExtDefault extends EnrollExtDefault {
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
try {
IssuerAlternativeNameExtension ext = null;
- if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ if (name == null) {
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
@@ -120,20 +117,19 @@ public class IssuerAltNameExtDefault extends EnrollExtDefault {
(IssuerAlternativeNameExtension)
getExtension(PKIXExtensions.IssuerAlternativeName_Id.toString(), info);
- if(ext == null)
- {
+ if (ext == null) {
try {
- populate(null,info);
+ populate(null, info);
} catch (EProfileException e) {
- throw new EPropertyException(CMS.getUserMessage(
- locale, "CMS_INVALID_PROPERTY", name));
+ throw new EPropertyException(CMS.getUserMessage(
+ locale, "CMS_INVALID_PROPERTY", name));
}
}
-
+
if (name.equals(VAL_CRITICAL)) {
- ext =
+ ext =
(IssuerAlternativeNameExtension)
getExtension(PKIXExtensions.IssuerAlternativeName_Id.toString(), info);
@@ -145,7 +141,7 @@ public class IssuerAltNameExtDefault extends EnrollExtDefault {
ext.setCritical(critical);
} else if (name.equals(VAL_GENERAL_NAMES)) {
- ext =
+ ext =
(IssuerAlternativeNameExtension)
getExtension(PKIXExtensions.IssuerAlternativeName_Id.toString(), info);
@@ -166,34 +162,34 @@ public class IssuerAltNameExtDefault extends EnrollExtDefault {
GeneralNameInterface n = parseGeneralName(gname);
if (n != null) {
- gn.addElement(n);
+ gn.addElement(n);
}
}
ext.set(IssuerAlternativeNameExtension.ISSUER_NAME, gn);
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
replaceExtension(
- PKIXExtensions.IssuerAlternativeName_Id.toString(),
- ext, info);
+ PKIXExtensions.IssuerAlternativeName_Id.toString(),
+ ext, info);
} catch (IOException e) {
CMS.debug("IssuerAltNameExtDefault: setValue " + e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
} catch (EProfileException e) {
CMS.debug("IssuerAltNameExtDefault: setValue " + e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
+ X509CertInfo info)
+ throws EPropertyException {
try {
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
@@ -201,23 +197,22 @@ public class IssuerAltNameExtDefault extends EnrollExtDefault {
(IssuerAlternativeNameExtension)
getExtension(PKIXExtensions.IssuerAlternativeName_Id.toString(), info);
- if(ext == null)
- {
+ if (ext == null) {
try {
- populate(null,info);
+ populate(null, info);
} catch (EProfileException e) {
- throw new EPropertyException(CMS.getUserMessage(
- locale, "CMS_INVALID_PROPERTY", name));
+ throw new EPropertyException(CMS.getUserMessage(
+ locale, "CMS_INVALID_PROPERTY", name));
}
}
if (name.equals(VAL_CRITICAL)) {
- ext =
- (IssuerAlternativeNameExtension)
- getExtension(PKIXExtensions.IssuerAlternativeName_Id.toString(), info);
+ ext =
+ (IssuerAlternativeNameExtension)
+ getExtension(PKIXExtensions.IssuerAlternativeName_Id.toString(), info);
if (ext == null) {
return null;
@@ -228,16 +223,15 @@ public class IssuerAltNameExtDefault extends EnrollExtDefault {
return "false";
}
} else if (name.equals(VAL_GENERAL_NAMES)) {
- ext =
- (IssuerAlternativeNameExtension)
- getExtension(PKIXExtensions.IssuerAlternativeName_Id.toString(), info);
- if(ext == null)
- {
+ ext =
+ (IssuerAlternativeNameExtension)
+ getExtension(PKIXExtensions.IssuerAlternativeName_Id.toString(), info);
+ if (ext == null) {
return "";
}
GeneralNames names = (GeneralNames)
- ext.get(IssuerAlternativeNameExtension.ISSUER_NAME);
+ ext.get(IssuerAlternativeNameExtension.ISSUER_NAME);
StringBuffer sb = new StringBuffer();
Enumeration<GeneralNameInterface> e = names.elements();
@@ -246,17 +240,17 @@ public class IssuerAltNameExtDefault extends EnrollExtDefault {
if (!sb.toString().equals("")) {
sb.append("\r\n");
- }
+ }
sb.append(toGeneralNameString(gn));
}
return sb.toString();
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
} catch (IOException e) {
- CMS.debug("IssuerAltNameExtDefault: getValue " +
- e.toString());
+ CMS.debug("IssuerAltNameExtDefault: getValue " +
+ e.toString());
}
return null;
}
@@ -275,7 +269,7 @@ public class IssuerAltNameExtDefault extends EnrollExtDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
IssuerAlternativeNameExtension ext = null;
try {
@@ -284,35 +278,35 @@ public class IssuerAltNameExtDefault extends EnrollExtDefault {
} catch (IOException e) {
CMS.debug("IssuerAltNameExtDefault: populate " + e.toString());
}
- addExtension(PKIXExtensions.IssuerAlternativeName_Id.toString(),
- ext, info);
+ addExtension(PKIXExtensions.IssuerAlternativeName_Id.toString(),
+ ext, info);
}
- public IssuerAlternativeNameExtension createExtension(IRequest request)
- throws IOException {
- IssuerAlternativeNameExtension ext = null;
+ public IssuerAlternativeNameExtension createExtension(IRequest request)
+ throws IOException {
+ IssuerAlternativeNameExtension ext = null;
try {
ext = new IssuerAlternativeNameExtension();
} catch (Exception e) {
CMS.debug(e.toString());
- throw new IOException( e.toString() );
+ throw new IOException(e.toString());
}
boolean critical = Boolean.valueOf(
- getConfig(CONFIG_CRITICAL)).booleanValue();
+ getConfig(CONFIG_CRITICAL)).booleanValue();
String pattern = getConfig(CONFIG_PATTERN);
if (!pattern.equals("")) {
- GeneralNames gn = new GeneralNames();
+ GeneralNames gn = new GeneralNames();
String gname = "";
- if(request != null) {
+ if (request != null) {
gname = mapPattern(request, pattern);
}
gn.addElement(parseGeneralName(
- getConfig(CONFIG_TYPE) + ":" + gname));
+ getConfig(CONFIG_TYPE) + ":" + gname));
ext.set(IssuerAlternativeNameExtension.ISSUER_NAME, gn);
}
ext.setCritical(critical);
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/KeyUsageExtDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/KeyUsageExtDefault.java
index c8ed9281..4547a0f5 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/KeyUsageExtDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/KeyUsageExtDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.io.IOException;
import java.util.Locale;
@@ -34,25 +33,23 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements an enrollment default policy
- * that populates a Key Usage extension
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates a Key Usage
+ * extension into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class KeyUsageExtDefault extends EnrollExtDefault {
public static final String CONFIG_CRITICAL = "keyUsageCritical";
- public static final String CONFIG_DIGITAL_SIGNATURE =
- "keyUsageDigitalSignature";
- public static final String CONFIG_NON_REPUDIATION =
- "keyUsageNonRepudiation";
- public static final String CONFIG_KEY_ENCIPHERMENT =
- "keyUsageKeyEncipherment";
- public static final String CONFIG_DATA_ENCIPHERMENT =
- "keyUsageDataEncipherment";
+ public static final String CONFIG_DIGITAL_SIGNATURE =
+ "keyUsageDigitalSignature";
+ public static final String CONFIG_NON_REPUDIATION =
+ "keyUsageNonRepudiation";
+ public static final String CONFIG_KEY_ENCIPHERMENT =
+ "keyUsageKeyEncipherment";
+ public static final String CONFIG_DATA_ENCIPHERMENT =
+ "keyUsageDataEncipherment";
public static final String CONFIG_KEY_AGREEMENT = "keyUsageKeyAgreement";
public static final String CONFIG_KEY_CERTSIGN = "keyUsageKeyCertSign";
public static final String CONFIG_CRL_SIGN = "keyUsageCrlSign";
@@ -60,14 +57,14 @@ public class KeyUsageExtDefault extends EnrollExtDefault {
public static final String CONFIG_DECIPHER_ONLY = "keyUsageDecipherOnly";
public static final String VAL_CRITICAL = "keyUsageCritical";
- public static final String VAL_DIGITAL_SIGNATURE =
- "keyUsageDigitalSignature";
- public static final String VAL_NON_REPUDIATION =
- "keyUsageNonRepudiation";
- public static final String VAL_KEY_ENCIPHERMENT =
- "keyUsageKeyEncipherment";
- public static final String VAL_DATA_ENCIPHERMENT =
- "keyUsageDataEncipherment";
+ public static final String VAL_DIGITAL_SIGNATURE =
+ "keyUsageDigitalSignature";
+ public static final String VAL_NON_REPUDIATION =
+ "keyUsageNonRepudiation";
+ public static final String VAL_KEY_ENCIPHERMENT =
+ "keyUsageKeyEncipherment";
+ public static final String VAL_DATA_ENCIPHERMENT =
+ "keyUsageDataEncipherment";
public static final String VAL_KEY_AGREEMENT = "keyUsageKeyAgreement";
public static final String VAL_KEY_CERTSIGN = "keyUsageKeyCertSign";
public static final String VAL_CRL_SIGN = "keyUsageCrlSign";
@@ -100,21 +97,21 @@ public class KeyUsageExtDefault extends EnrollExtDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
if (name.equals(CONFIG_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.equals(CONFIG_DIGITAL_SIGNATURE)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_DIGITAL_SIGNATURE"));
} else if (name.equals(CONFIG_NON_REPUDIATION)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_NON_REPUDIATION"));
} else if (name.equals(CONFIG_KEY_ENCIPHERMENT)) {
@@ -152,15 +149,15 @@ public class KeyUsageExtDefault extends EnrollExtDefault {
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.equals(VAL_DIGITAL_SIGNATURE)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_DIGITAL_SIGNATURE"));
} else if (name.equals(VAL_NON_REPUDIATION)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_NON_REPUDIATION"));
} else if (name.equals(VAL_KEY_ENCIPHERMENT)) {
@@ -197,158 +194,157 @@ public class KeyUsageExtDefault extends EnrollExtDefault {
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
try {
KeyUsageExtension ext = null;
- if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ if (name == null) {
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
ext = (KeyUsageExtension)
- getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
+ getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
- if(ext == null) {
- populate(null,info);
+ if (ext == null) {
+ populate(null, info);
}
-
+
if (name.equals(VAL_CRITICAL)) {
ext = (KeyUsageExtension)
getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
- boolean val = Boolean.valueOf(value).booleanValue();
+ boolean val = Boolean.valueOf(value).booleanValue();
- if(ext == null) {
+ if (ext == null) {
return;
}
ext.setCritical(val);
- } else if (name.equals(VAL_DIGITAL_SIGNATURE)) {
+ } else if (name.equals(VAL_DIGITAL_SIGNATURE)) {
ext = (KeyUsageExtension)
getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
- if(ext == null) {
+ if (ext == null) {
return;
}
- Boolean val = Boolean.valueOf(value);
+ Boolean val = Boolean.valueOf(value);
ext.set(KeyUsageExtension.DIGITAL_SIGNATURE, val);
} else if (name.equals(VAL_NON_REPUDIATION)) {
ext = (KeyUsageExtension)
getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
- if(ext == null) {
+ if (ext == null) {
return;
}
- Boolean val = Boolean.valueOf(value);
+ Boolean val = Boolean.valueOf(value);
ext.set(KeyUsageExtension.NON_REPUDIATION, val);
} else if (name.equals(VAL_KEY_ENCIPHERMENT)) {
ext = (KeyUsageExtension)
getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
- if(ext == null) {
+ if (ext == null) {
return;
}
- Boolean val = Boolean.valueOf(value);
+ Boolean val = Boolean.valueOf(value);
ext.set(KeyUsageExtension.KEY_ENCIPHERMENT, val);
} else if (name.equals(VAL_DATA_ENCIPHERMENT)) {
ext = (KeyUsageExtension)
getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
- if(ext == null) {
+ if (ext == null) {
return;
}
- Boolean val = Boolean.valueOf(value);
+ Boolean val = Boolean.valueOf(value);
ext.set(KeyUsageExtension.DATA_ENCIPHERMENT, val);
} else if (name.equals(VAL_KEY_AGREEMENT)) {
ext = (KeyUsageExtension)
getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
- if(ext == null) {
+ if (ext == null) {
return;
}
- Boolean val = Boolean.valueOf(value);
+ Boolean val = Boolean.valueOf(value);
ext.set(KeyUsageExtension.KEY_AGREEMENT, val);
} else if (name.equals(VAL_KEY_CERTSIGN)) {
ext = (KeyUsageExtension)
getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
- if(ext == null) {
+ if (ext == null) {
return;
}
- Boolean val = Boolean.valueOf(value);
+ Boolean val = Boolean.valueOf(value);
ext.set(KeyUsageExtension.KEY_CERTSIGN, val);
} else if (name.equals(VAL_CRL_SIGN)) {
ext = (KeyUsageExtension)
getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
- if(ext == null) {
+ if (ext == null) {
return;
}
- Boolean val = Boolean.valueOf(value);
+ Boolean val = Boolean.valueOf(value);
ext.set(KeyUsageExtension.CRL_SIGN, val);
} else if (name.equals(VAL_ENCIPHER_ONLY)) {
ext = (KeyUsageExtension)
getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
- if(ext == null) {
+ if (ext == null) {
return;
}
- Boolean val = Boolean.valueOf(value);
+ Boolean val = Boolean.valueOf(value);
ext.set(KeyUsageExtension.ENCIPHER_ONLY, val);
} else if (name.equals(VAL_DECIPHER_ONLY)) {
ext = (KeyUsageExtension)
getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
- if(ext == null) {
+ if (ext == null) {
return;
}
- Boolean val = Boolean.valueOf(value);
+ Boolean val = Boolean.valueOf(value);
ext.set(KeyUsageExtension.DECIPHER_ONLY, val);
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
replaceExtension(PKIXExtensions.KeyUsage_Id.toString(), ext, info);
} catch (IOException e) {
CMS.debug("KeyUsageExtDefault: setValue " + e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
} catch (EProfileException e) {
CMS.debug("KeyUsageExtDefault: setValue " + e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
+ X509CertInfo info)
+ throws EPropertyException {
try {
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
KeyUsageExtension ext = (KeyUsageExtension)
getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
- if(ext == null)
- {
+ if (ext == null) {
try {
- populate(null,info);
+ populate(null, info);
} catch (EProfileException e) {
- throw new EPropertyException(CMS.getUserMessage(
- locale, "CMS_INVALID_PROPERTY", name));
+ throw new EPropertyException(CMS.getUserMessage(
+ locale, "CMS_INVALID_PROPERTY", name));
}
}
if (name.equals(VAL_CRITICAL)) {
ext = (KeyUsageExtension)
- getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
+ getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
if (ext == null) {
return null;
@@ -360,117 +356,117 @@ public class KeyUsageExtDefault extends EnrollExtDefault {
}
} else if (name.equals(VAL_DIGITAL_SIGNATURE)) {
ext = (KeyUsageExtension)
- getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
+ getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
if (ext == null) {
return null;
}
Boolean val = (Boolean)
- ext.get(KeyUsageExtension.DIGITAL_SIGNATURE);
+ ext.get(KeyUsageExtension.DIGITAL_SIGNATURE);
return val.toString();
} else if (name.equals(VAL_NON_REPUDIATION)) {
ext = (KeyUsageExtension)
- getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
+ getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
if (ext == null) {
return null;
}
Boolean val = (Boolean)
- ext.get(KeyUsageExtension.NON_REPUDIATION);
+ ext.get(KeyUsageExtension.NON_REPUDIATION);
return val.toString();
} else if (name.equals(VAL_KEY_ENCIPHERMENT)) {
ext = (KeyUsageExtension)
- getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
+ getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
if (ext == null) {
return null;
}
Boolean val = (Boolean)
- ext.get(KeyUsageExtension.KEY_ENCIPHERMENT);
+ ext.get(KeyUsageExtension.KEY_ENCIPHERMENT);
return val.toString();
} else if (name.equals(VAL_DATA_ENCIPHERMENT)) {
ext = (KeyUsageExtension)
- getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
+ getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
if (ext == null) {
return null;
}
Boolean val = (Boolean)
- ext.get(KeyUsageExtension.DATA_ENCIPHERMENT);
+ ext.get(KeyUsageExtension.DATA_ENCIPHERMENT);
return val.toString();
} else if (name.equals(VAL_KEY_AGREEMENT)) {
ext = (KeyUsageExtension)
- getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
+ getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
if (ext == null) {
return null;
}
Boolean val = (Boolean)
- ext.get(KeyUsageExtension.KEY_AGREEMENT);
+ ext.get(KeyUsageExtension.KEY_AGREEMENT);
return val.toString();
} else if (name.equals(VAL_KEY_CERTSIGN)) {
ext = (KeyUsageExtension)
- getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
+ getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
if (ext == null) {
return null;
}
Boolean val = (Boolean)
- ext.get(KeyUsageExtension.KEY_CERTSIGN);
+ ext.get(KeyUsageExtension.KEY_CERTSIGN);
return val.toString();
} else if (name.equals(VAL_CRL_SIGN)) {
ext = (KeyUsageExtension)
- getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
+ getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
if (ext == null) {
return null;
}
Boolean val = (Boolean)
- ext.get(KeyUsageExtension.CRL_SIGN);
+ ext.get(KeyUsageExtension.CRL_SIGN);
return val.toString();
} else if (name.equals(VAL_ENCIPHER_ONLY)) {
ext = (KeyUsageExtension)
- getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
+ getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
if (ext == null) {
return null;
}
Boolean val = (Boolean)
- ext.get(KeyUsageExtension.ENCIPHER_ONLY);
+ ext.get(KeyUsageExtension.ENCIPHER_ONLY);
return val.toString();
} else if (name.equals(VAL_DECIPHER_ONLY)) {
ext = (KeyUsageExtension)
- getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
+ getExtension(PKIXExtensions.KeyUsage_Id.toString(), info);
if (ext == null) {
return null;
}
Boolean val = (Boolean)
- ext.get(KeyUsageExtension.DECIPHER_ONLY);
+ ext.get(KeyUsageExtension.DECIPHER_ONLY);
return val.toString();
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
} catch (IOException e) {
CMS.debug("KeyUsageExtDefault: getValue " + e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
public String getText(Locale locale) {
String params[] = {
- getConfig(CONFIG_CRITICAL),
- getConfig(CONFIG_DIGITAL_SIGNATURE),
- getConfig(CONFIG_NON_REPUDIATION),
- getConfig(CONFIG_KEY_ENCIPHERMENT),
- getConfig(CONFIG_DATA_ENCIPHERMENT),
- getConfig(CONFIG_KEY_AGREEMENT),
- getConfig(CONFIG_KEY_CERTSIGN),
- getConfig(CONFIG_CRL_SIGN),
- getConfig(CONFIG_ENCIPHER_ONLY),
+ getConfig(CONFIG_CRITICAL),
+ getConfig(CONFIG_DIGITAL_SIGNATURE),
+ getConfig(CONFIG_NON_REPUDIATION),
+ getConfig(CONFIG_KEY_ENCIPHERMENT),
+ getConfig(CONFIG_DATA_ENCIPHERMENT),
+ getConfig(CONFIG_KEY_AGREEMENT),
+ getConfig(CONFIG_KEY_CERTSIGN),
+ getConfig(CONFIG_CRL_SIGN),
+ getConfig(CONFIG_ENCIPHER_ONLY),
getConfig(CONFIG_DECIPHER_ONLY)
};
@@ -482,14 +478,14 @@ public class KeyUsageExtDefault extends EnrollExtDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
KeyUsageExtension ext = createKeyUsageExtension();
addExtension(PKIXExtensions.KeyUsage_Id.toString(), ext, info);
}
public KeyUsageExtension createKeyUsageExtension() {
- KeyUsageExtension ext = null;
+ KeyUsageExtension ext = null;
boolean[] bits = new boolean[KeyUsageExtension.NBITS];
boolean critical = getConfigBoolean(CONFIG_CRITICAL);
@@ -506,8 +502,8 @@ public class KeyUsageExtDefault extends EnrollExtDefault {
try {
ext = new KeyUsageExtension(critical, bits);
} catch (Exception e) {
- CMS.debug("KeyUsageExtDefault: createKeyUsageExtension " +
- e.toString());
+ CMS.debug("KeyUsageExtDefault: createKeyUsageExtension " +
+ e.toString());
}
return ext;
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/NSCCommentExtDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/NSCCommentExtDefault.java
index 01e92d6a..19cd23fa 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/NSCCommentExtDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/NSCCommentExtDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.io.IOException;
import java.util.Locale;
@@ -34,12 +33,10 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements an enrollment default policy
- * that populates a Netscape comment extension
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates a Netscape
+ * comment extension into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class NSCCommentExtDefault extends EnrollExtDefault {
@@ -60,13 +57,13 @@ public class NSCCommentExtDefault extends EnrollExtDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
if (name.equals(CONFIG_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.equals(CONFIG_COMMENT)) {
@@ -80,7 +77,7 @@ public class NSCCommentExtDefault extends EnrollExtDefault {
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.equals(VAL_COMMENT)) {
@@ -93,13 +90,13 @@ public class NSCCommentExtDefault extends EnrollExtDefault {
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
try {
NSCCommentExtension ext = null;
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
@@ -108,8 +105,8 @@ public class NSCCommentExtDefault extends EnrollExtDefault {
ext = (NSCCommentExtension)
getExtension(oid.toString(), info);
- if(ext == null) {
- populate(null,info);
+ if (ext == null) {
+ populate(null, info);
}
if (name.equals(VAL_CRITICAL)) {
@@ -118,27 +115,27 @@ public class NSCCommentExtDefault extends EnrollExtDefault {
getExtension(oid.toString(), info);
boolean val = Boolean.valueOf(value).booleanValue();
- if (ext == null) {
+ if (ext == null) {
return;
}
- ext.setCritical(val);
- } else if (name.equals(VAL_COMMENT)) {
+ ext.setCritical(val);
+ } else if (name.equals(VAL_COMMENT)) {
ext = (NSCCommentExtension)
getExtension(oid.toString(), info);
- if (ext == null) {
+ if (ext == null) {
return;
}
boolean critical = ext.isCritical();
if (value == null || value.equals(""))
ext = new NSCCommentExtension(critical, "");
- // throw new EPropertyException(name+" cannot be empty");
+ // throw new EPropertyException(name+" cannot be empty");
else
ext = new NSCCommentExtension(critical, value);
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
@@ -151,12 +148,12 @@ public class NSCCommentExtDefault extends EnrollExtDefault {
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
+ X509CertInfo info)
+ throws EPropertyException {
NSCCommentExtension ext = null;
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
@@ -165,14 +162,13 @@ public class NSCCommentExtDefault extends EnrollExtDefault {
ext = (NSCCommentExtension)
getExtension(oid.toString(), info);
- if(ext == null)
- {
+ if (ext == null) {
try {
- populate(null,info);
+ populate(null, info);
} catch (EProfileException e) {
- throw new EPropertyException(CMS.getUserMessage(
- locale, "CMS_INVALID_PROPERTY", name));
+ throw new EPropertyException(CMS.getUserMessage(
+ locale, "CMS_INVALID_PROPERTY", name));
}
}
@@ -190,7 +186,7 @@ public class NSCCommentExtDefault extends EnrollExtDefault {
} else {
return "false";
}
- } else if (name.equals(VAL_COMMENT)) {
+ } else if (name.equals(VAL_COMMENT)) {
ext = (NSCCommentExtension)
getExtension(oid.toString(), info);
@@ -202,17 +198,17 @@ public class NSCCommentExtDefault extends EnrollExtDefault {
if (comment == null)
comment = "";
-
+
return comment;
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
public String getText(Locale locale) {
String params[] = {
- getConfig(CONFIG_CRITICAL),
+ getConfig(CONFIG_CRITICAL),
getConfig(CONFIG_COMMENT)
};
@@ -223,14 +219,14 @@ public class NSCCommentExtDefault extends EnrollExtDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
NSCCommentExtension ext = createExtension();
addExtension(ext.getExtensionId().toString(), ext, info);
}
public NSCCommentExtension createExtension() {
- NSCCommentExtension ext = null;
+ NSCCommentExtension ext = null;
try {
boolean critical = getConfigBoolean(CONFIG_CRITICAL);
@@ -241,8 +237,8 @@ public class NSCCommentExtDefault extends EnrollExtDefault {
else
ext = new NSCCommentExtension(critical, comment);
} catch (Exception e) {
- CMS.debug("NSCCommentExtension: createExtension " +
- e.toString());
+ CMS.debug("NSCCommentExtension: createExtension " +
+ e.toString());
}
return ext;
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/NSCertTypeExtDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/NSCertTypeExtDefault.java
index e3438ccf..68a12c28 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/NSCertTypeExtDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/NSCertTypeExtDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.security.cert.CertificateException;
import java.util.Locale;
@@ -33,12 +32,10 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements an enrollment default policy
- * that populates a Netscape Certificate Type extension
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates a Netscape
+ * Certificate Type extension into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class NSCertTypeExtDefault extends EnrollExtDefault {
@@ -83,11 +80,11 @@ public class NSCertTypeExtDefault extends EnrollExtDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
if (name.equals(CONFIG_CRITICAL)) {
return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
@@ -127,7 +124,7 @@ public class NSCertTypeExtDefault extends EnrollExtDefault {
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.equals(VAL_SSL_CLIENT)) {
@@ -135,7 +132,7 @@ public class NSCertTypeExtDefault extends EnrollExtDefault {
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_SSL_CLIENT"));
} else if (name.equals(VAL_SSL_SERVER)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_SSL_SERVER"));
} else if (name.equals(VAL_EMAIL)) {
@@ -155,7 +152,7 @@ public class NSCertTypeExtDefault extends EnrollExtDefault {
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_EMAIL_CA"));
} else if (name.equals(VAL_OBJECT_SIGNING_CA)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_OBJECT_SIGNING_CA"));
} else {
@@ -164,8 +161,8 @@ public class NSCertTypeExtDefault extends EnrollExtDefault {
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
try {
NSCertTypeExtension ext = null;
@@ -174,12 +171,11 @@ public class NSCertTypeExtDefault extends EnrollExtDefault {
locale, "CMS_INVALID_PROPERTY", name));
}
-
ext = (NSCertTypeExtension)
getExtension(NSCertTypeExtension.CertType_Id.toString(), info);
- if(ext == null) {
- populate(null,info);
+ if (ext == null) {
+ populate(null, info);
}
if (name.equals(VAL_CRITICAL)) {
@@ -187,69 +183,69 @@ public class NSCertTypeExtDefault extends EnrollExtDefault {
getExtension(NSCertTypeExtension.CertType_Id.toString(), info);
boolean val = Boolean.valueOf(value).booleanValue();
- if(ext == null) {
- return ;
+ if (ext == null) {
+ return;
}
- ext.setCritical(val);
- } else if (name.equals(VAL_SSL_CLIENT)) {
+ ext.setCritical(val);
+ } else if (name.equals(VAL_SSL_CLIENT)) {
ext = (NSCertTypeExtension)
getExtension(NSCertTypeExtension.CertType_Id.toString(), info);
- if(ext == null) {
- return ;
+ if (ext == null) {
+ return;
}
Boolean val = Boolean.valueOf(value);
ext.set(NSCertTypeExtension.SSL_CLIENT, val);
- } else if (name.equals(VAL_SSL_SERVER)) {
+ } else if (name.equals(VAL_SSL_SERVER)) {
ext = (NSCertTypeExtension)
getExtension(NSCertTypeExtension.CertType_Id.toString(), info);
- if(ext == null) {
- return ;
+ if (ext == null) {
+ return;
}
Boolean val = Boolean.valueOf(value);
ext.set(NSCertTypeExtension.SSL_SERVER, val);
- } else if (name.equals(VAL_EMAIL)) {
+ } else if (name.equals(VAL_EMAIL)) {
ext = (NSCertTypeExtension)
getExtension(NSCertTypeExtension.CertType_Id.toString(), info);
- if(ext == null) {
- return ;
+ if (ext == null) {
+ return;
}
Boolean val = Boolean.valueOf(value);
ext.set(NSCertTypeExtension.EMAIL, val);
- } else if (name.equals(VAL_OBJECT_SIGNING)) {
+ } else if (name.equals(VAL_OBJECT_SIGNING)) {
ext = (NSCertTypeExtension)
getExtension(NSCertTypeExtension.CertType_Id.toString(), info);
- if(ext == null) {
- return ;
+ if (ext == null) {
+ return;
}
Boolean val = Boolean.valueOf(value);
ext.set(NSCertTypeExtension.OBJECT_SIGNING, val);
- } else if (name.equals(VAL_SSL_CA)) {
+ } else if (name.equals(VAL_SSL_CA)) {
ext = (NSCertTypeExtension)
getExtension(NSCertTypeExtension.CertType_Id.toString(), info);
- if(ext == null) {
- return ;
+ if (ext == null) {
+ return;
}
Boolean val = Boolean.valueOf(value);
ext.set(NSCertTypeExtension.SSL_CA, val);
- } else if (name.equals(VAL_EMAIL_CA)) {
+ } else if (name.equals(VAL_EMAIL_CA)) {
ext = (NSCertTypeExtension)
getExtension(NSCertTypeExtension.CertType_Id.toString(), info);
- if(ext == null) {
- return ;
+ if (ext == null) {
+ return;
}
Boolean val = Boolean.valueOf(value);
ext.set(NSCertTypeExtension.EMAIL_CA, val);
- } else if (name.equals(VAL_OBJECT_SIGNING_CA)) {
+ } else if (name.equals(VAL_OBJECT_SIGNING_CA)) {
ext = (NSCertTypeExtension)
getExtension(NSCertTypeExtension.CertType_Id.toString(), info);
- if(ext == null) {
- return ;
+ if (ext == null) {
+ return;
}
Boolean val = Boolean.valueOf(value);
@@ -266,31 +262,30 @@ public class NSCertTypeExtDefault extends EnrollExtDefault {
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
+ X509CertInfo info)
+ throws EPropertyException {
try {
- if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ if (name == null) {
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
NSCertTypeExtension ext = (NSCertTypeExtension)
getExtension(NSCertTypeExtension.CertType_Id.toString(), info);
- if(ext == null)
- {
+ if (ext == null) {
try {
- populate(null,info);
+ populate(null, info);
} catch (EProfileException e) {
- throw new EPropertyException(CMS.getUserMessage(
- locale, "CMS_INVALID_PROPERTY", name));
+ throw new EPropertyException(CMS.getUserMessage(
+ locale, "CMS_INVALID_PROPERTY", name));
}
}
if (name.equals(VAL_CRITICAL)) {
ext = (NSCertTypeExtension)
- getExtension(NSCertTypeExtension.CertType_Id.toString(), info);
+ getExtension(NSCertTypeExtension.CertType_Id.toString(), info);
if (ext == null) {
return null;
@@ -300,63 +295,63 @@ public class NSCertTypeExtDefault extends EnrollExtDefault {
} else {
return "false";
}
- } else if (name.equals(VAL_SSL_CLIENT)) {
+ } else if (name.equals(VAL_SSL_CLIENT)) {
ext = (NSCertTypeExtension)
- getExtension(NSCertTypeExtension.CertType_Id.toString(), info);
+ getExtension(NSCertTypeExtension.CertType_Id.toString(), info);
if (ext == null) {
return null;
}
Boolean val = (Boolean) ext.get(NSCertTypeExtension.SSL_CLIENT);
return val.toString();
- } else if (name.equals(VAL_SSL_SERVER)) {
+ } else if (name.equals(VAL_SSL_SERVER)) {
ext = (NSCertTypeExtension)
- getExtension(NSCertTypeExtension.CertType_Id.toString(), info);
+ getExtension(NSCertTypeExtension.CertType_Id.toString(), info);
if (ext == null) {
return null;
}
Boolean val = (Boolean) ext.get(NSCertTypeExtension.SSL_SERVER);
return val.toString();
- } else if (name.equals(VAL_EMAIL)) {
+ } else if (name.equals(VAL_EMAIL)) {
ext = (NSCertTypeExtension)
- getExtension(NSCertTypeExtension.CertType_Id.toString(), info);
+ getExtension(NSCertTypeExtension.CertType_Id.toString(), info);
if (ext == null) {
return null;
}
Boolean val = (Boolean) ext.get(NSCertTypeExtension.EMAIL);
return val.toString();
- } else if (name.equals(VAL_OBJECT_SIGNING)) {
+ } else if (name.equals(VAL_OBJECT_SIGNING)) {
ext = (NSCertTypeExtension)
- getExtension(NSCertTypeExtension.CertType_Id.toString(), info);
+ getExtension(NSCertTypeExtension.CertType_Id.toString(), info);
if (ext == null) {
return null;
}
Boolean val = (Boolean) ext.get(NSCertTypeExtension.OBJECT_SIGNING);
return val.toString();
- } else if (name.equals(VAL_SSL_CA)) {
+ } else if (name.equals(VAL_SSL_CA)) {
ext = (NSCertTypeExtension)
- getExtension(NSCertTypeExtension.CertType_Id.toString(), info);
+ getExtension(NSCertTypeExtension.CertType_Id.toString(), info);
if (ext == null) {
return null;
}
Boolean val = (Boolean) ext.get(NSCertTypeExtension.SSL_CA);
return val.toString();
- } else if (name.equals(VAL_EMAIL_CA)) {
+ } else if (name.equals(VAL_EMAIL_CA)) {
ext = (NSCertTypeExtension)
- getExtension(NSCertTypeExtension.CertType_Id.toString(), info);
+ getExtension(NSCertTypeExtension.CertType_Id.toString(), info);
if (ext == null) {
return null;
}
Boolean val = (Boolean) ext.get(NSCertTypeExtension.EMAIL_CA);
return val.toString();
- } else if (name.equals(VAL_OBJECT_SIGNING_CA)) {
+ } else if (name.equals(VAL_OBJECT_SIGNING_CA)) {
ext = (NSCertTypeExtension)
- getExtension(NSCertTypeExtension.CertType_Id.toString(), info);
+ getExtension(NSCertTypeExtension.CertType_Id.toString(), info);
if (ext == null) {
return null;
}
@@ -364,7 +359,7 @@ public class NSCertTypeExtDefault extends EnrollExtDefault {
return val.toString();
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
} catch (CertificateException e) {
@@ -375,13 +370,13 @@ public class NSCertTypeExtDefault extends EnrollExtDefault {
public String getText(Locale locale) {
String params[] = {
- getConfig(CONFIG_CRITICAL),
- getConfig(CONFIG_SSL_CLIENT),
- getConfig(CONFIG_SSL_SERVER),
- getConfig(CONFIG_EMAIL),
- getConfig(CONFIG_OBJECT_SIGNING),
- getConfig(CONFIG_SSL_CA),
- getConfig(CONFIG_EMAIL_CA),
+ getConfig(CONFIG_CRITICAL),
+ getConfig(CONFIG_SSL_CLIENT),
+ getConfig(CONFIG_SSL_SERVER),
+ getConfig(CONFIG_EMAIL),
+ getConfig(CONFIG_OBJECT_SIGNING),
+ getConfig(CONFIG_SSL_CA),
+ getConfig(CONFIG_EMAIL_CA),
getConfig(CONFIG_OBJECT_SIGNING_CA)
};
@@ -393,14 +388,14 @@ public class NSCertTypeExtDefault extends EnrollExtDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
NSCertTypeExtension ext = createExtension();
addExtension(NSCertTypeExtension.CertType_Id.toString(), ext, info);
}
public NSCertTypeExtension createExtension() {
- NSCertTypeExtension ext = null;
+ NSCertTypeExtension ext = null;
boolean[] bits = new boolean[NSCertTypeExtension.NBITS];
boolean critical = getConfigBoolean(CONFIG_CRITICAL);
@@ -415,8 +410,8 @@ public class NSCertTypeExtDefault extends EnrollExtDefault {
try {
ext = new NSCertTypeExtension(critical, bits);
} catch (Exception e) {
- CMS.debug("NSCertTypeExtDefault: createExtension " +
- e.toString());
+ CMS.debug("NSCertTypeExtDefault: createExtension " +
+ e.toString());
}
return ext;
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/NameConstraintsExtDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/NameConstraintsExtDefault.java
index 7776238a..7471b0c7 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/NameConstraintsExtDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/NameConstraintsExtDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.io.IOException;
import java.util.Enumeration;
import java.util.Locale;
@@ -41,25 +40,23 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements an enrollment default policy
- * that populates a name constraint extension
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates a name
+ * constraint extension into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class NameConstraintsExtDefault extends EnrollExtDefault {
public static final String CONFIG_CRITICAL = "nameConstraintsCritical";
- public static final String CONFIG_NUM_PERMITTED_SUBTREES =
- "nameConstraintsNumPermittedSubtrees";
+ public static final String CONFIG_NUM_PERMITTED_SUBTREES =
+ "nameConstraintsNumPermittedSubtrees";
public static final String CONFIG_PERMITTED_MIN_VAL = "nameConstraintsPermittedSubtreeMinValue_";
public static final String CONFIG_PERMITTED_MAX_VAL = "nameConstraintsPermittedSubtreeMaxValue_";
public static final String CONFIG_PERMITTED_NAME_CHOICE = "nameConstraintsPermittedSubtreeNameChoice_";
public static final String CONFIG_PERMITTED_NAME_VAL = "nameConstraintsPermittedSubtreeNameValue_";
public static final String CONFIG_PERMITTED_ENABLE = "nameConstraintsPermittedSubtreeEnable_";
-
+
public static final String CONFIG_NUM_EXCLUDED_SUBTREES = "nameConstraintsNumExcludedSubtrees";
public static final String CONFIG_EXCLUDED_MIN_VAL = "nameConstraintsExcludedSubtreeMinValue_";
public static final String CONFIG_EXCLUDED_MAX_VAL = "nameConstraintsExcludedSubtreeMaxValue_";
@@ -87,7 +84,7 @@ public class NameConstraintsExtDefault extends EnrollExtDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
refreshConfigAndValueNames();
@@ -128,48 +125,47 @@ public class NameConstraintsExtDefault extends EnrollExtDefault {
return num;
}
- public void setConfig(String name, String value)
- throws EPropertyException {
+ public void setConfig(String name, String value)
+ throws EPropertyException {
int num = 0;
if (name.equals(CONFIG_NUM_PERMITTED_SUBTREES)) {
- try {
- num = Integer.parseInt(value);
+ try {
+ num = Integer.parseInt(value);
- if (num >= MAX_NUM_PERMITTED_SUBTREES || num < 0) {
- throw new EPropertyException(CMS.getUserMessage(
+ if (num >= MAX_NUM_PERMITTED_SUBTREES || num < 0) {
+ throw new EPropertyException(CMS.getUserMessage(
"CMS_INVALID_PROPERTY", CONFIG_NUM_PERMITTED_SUBTREES));
- }
+ }
- } catch (Exception e) {
+ } catch (Exception e) {
throw new EPropertyException(CMS.getUserMessage(
"CMS_INVALID_PROPERTY", CONFIG_NUM_PERMITTED_SUBTREES));
- }
- } else if(name.equals(CONFIG_NUM_EXCLUDED_SUBTREES)) {
+ }
+ } else if (name.equals(CONFIG_NUM_EXCLUDED_SUBTREES)) {
try {
- num = Integer.parseInt(value);
+ num = Integer.parseInt(value);
- if (num >= MAX_NUM_EXCLUDED_SUBTREES || num < 0) {
- throw new EPropertyException(CMS.getUserMessage(
+ if (num >= MAX_NUM_EXCLUDED_SUBTREES || num < 0) {
+ throw new EPropertyException(CMS.getUserMessage(
"CMS_INVALID_PROPERTY", CONFIG_NUM_EXCLUDED_SUBTREES));
- }
+ }
- } catch (Exception e) {
+ } catch (Exception e) {
throw new EPropertyException(CMS.getUserMessage(
"CMS_INVALID_PROPERTY", CONFIG_NUM_EXCLUDED_SUBTREES));
- }
+ }
}
super.setConfig(name, value);
}
-
public Enumeration<String> getConfigNames() {
refreshConfigAndValueNames();
return super.getConfigNames();
}
protected void refreshConfigAndValueNames() {
- //refesh our config name list
+ // refesh our config name list
super.refreshConfigAndValueNames();
@@ -203,50 +199,49 @@ public class NameConstraintsExtDefault extends EnrollExtDefault {
}
-
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
if (name.equals(CONFIG_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.startsWith(CONFIG_PERMITTED_MIN_VAL)) {
- return new Descriptor(IDescriptor.STRING, null,
+ return new Descriptor(IDescriptor.STRING, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_PERMITTED_MIN_VAL"));
} else if (name.startsWith(CONFIG_PERMITTED_MAX_VAL)) {
- return new Descriptor(IDescriptor.STRING, null,
+ return new Descriptor(IDescriptor.STRING, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_PERMITTED_MAX_VAL"));
} else if (name.startsWith(CONFIG_PERMITTED_NAME_CHOICE)) {
- return new Descriptor(IDescriptor.STRING, null,
+ return new Descriptor(IDescriptor.STRING, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_PERMITTED_NAME_CHOICE"));
} else if (name.startsWith(CONFIG_PERMITTED_NAME_VAL)) {
- return new Descriptor(IDescriptor.STRING, null,
+ return new Descriptor(IDescriptor.STRING, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_PERMITTED_NAME_VAL"));
} else if (name.startsWith(CONFIG_PERMITTED_ENABLE)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_ENABLE"));
} else if (name.startsWith(CONFIG_EXCLUDED_MIN_VAL)) {
- return new Descriptor(IDescriptor.STRING, null,
+ return new Descriptor(IDescriptor.STRING, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_EXCLUDED_MIN_VAL"));
} else if (name.startsWith(CONFIG_EXCLUDED_MAX_VAL)) {
- return new Descriptor(IDescriptor.STRING, null,
+ return new Descriptor(IDescriptor.STRING, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_EXCLUDED_MAX_VAL"));
} else if (name.startsWith(CONFIG_EXCLUDED_NAME_CHOICE)) {
- return new Descriptor(IDescriptor.STRING, null,
+ return new Descriptor(IDescriptor.STRING, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_EXCLUDED_NAME_CHOICE"));
} else if (name.startsWith(CONFIG_EXCLUDED_NAME_VAL)) {
- return new Descriptor(IDescriptor.STRING, null,
+ return new Descriptor(IDescriptor.STRING, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_EXCLUDED_NAME_VAL"));
} else if (name.startsWith(CONFIG_EXCLUDED_ENABLE)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_ENABLE"));
} else if (name.startsWith(CONFIG_NUM_EXCLUDED_SUBTREES)) {
@@ -255,23 +250,23 @@ public class NameConstraintsExtDefault extends EnrollExtDefault {
CMS.getUserMessage(locale, "CMS_PROFILE_NUM_EXCLUDED_SUBTREES"));
} else if (name.startsWith(CONFIG_NUM_PERMITTED_SUBTREES)) {
return new Descriptor(IDescriptor.INTEGER, null,
- "1",
- CMS.getUserMessage(locale, "CMS_PROFILE_NUM_PERMITTED_SUBTREES"));
+ "1",
+ CMS.getUserMessage(locale, "CMS_PROFILE_NUM_PERMITTED_SUBTREES"));
}
return null;
}
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.equals(VAL_PERMITTED_SUBTREES)) {
- return new Descriptor(IDescriptor.STRING_LIST, null,
+ return new Descriptor(IDescriptor.STRING_LIST, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_PERMITTED_SUBTREES"));
} else if (name.equals(VAL_EXCLUDED_SUBTREES)) {
- return new Descriptor(IDescriptor.STRING_LIST, null,
+ return new Descriptor(IDescriptor.STRING_LIST, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_EXCLUDED_SUBTREES"));
} else {
@@ -280,21 +275,21 @@ public class NameConstraintsExtDefault extends EnrollExtDefault {
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
try {
NameConstraintsExtension ext = null;
- if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ if (name == null) {
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
ext = (NameConstraintsExtension)
getExtension(PKIXExtensions.NameConstraints_Id.toString(), info);
- if(ext == null) {
- populate(null,info);
+ if (ext == null) {
+ populate(null, info);
}
if (name.equals(VAL_CRITICAL)) {
@@ -302,19 +297,19 @@ public class NameConstraintsExtDefault extends EnrollExtDefault {
getExtension(PKIXExtensions.NameConstraints_Id.toString(), info);
boolean val = Boolean.valueOf(value).booleanValue();
- if(ext == null) {
+ if (ext == null) {
return;
}
- ext.setCritical(val);
- } else if (name.equals(VAL_PERMITTED_SUBTREES)) {
+ ext.setCritical(val);
+ } else if (name.equals(VAL_PERMITTED_SUBTREES)) {
ext = (NameConstraintsExtension)
getExtension(PKIXExtensions.NameConstraints_Id.toString(), info);
- if(ext == null) {
+ if (ext == null) {
return;
}
if ((value == null) || (value.equals("null")) || (value.equals(""))) {
- CMS.debug("NameConstraintsExtDefault:setValue : " +
+ CMS.debug("NameConstraintsExtDefault:setValue : " +
"blank value for permitted subtrees ... returning");
return;
}
@@ -323,17 +318,17 @@ public class NameConstraintsExtDefault extends EnrollExtDefault {
Vector<GeneralSubtree> permittedSubtrees = createSubtrees(locale, v);
- ext.set(NameConstraintsExtension.PERMITTED_SUBTREES,
- new GeneralSubtrees(permittedSubtrees));
+ ext.set(NameConstraintsExtension.PERMITTED_SUBTREES,
+ new GeneralSubtrees(permittedSubtrees));
} else if (name.equals(VAL_EXCLUDED_SUBTREES)) {
ext = (NameConstraintsExtension)
getExtension(PKIXExtensions.NameConstraints_Id.toString(), info);
- if(ext == null) {
+ if (ext == null) {
return;
}
if ((value == null) || (value.equals("null")) || (value.equals(""))) {
- CMS.debug("NameConstraintsExtDefault:setValue : " +
+ CMS.debug("NameConstraintsExtDefault:setValue : " +
"blank value for excluded subtrees ... returning");
return;
}
@@ -341,21 +336,21 @@ public class NameConstraintsExtDefault extends EnrollExtDefault {
Vector<GeneralSubtree> excludedSubtrees = createSubtrees(locale, v);
- ext.set(NameConstraintsExtension.EXCLUDED_SUBTREES,
- new GeneralSubtrees(excludedSubtrees));
+ ext.set(NameConstraintsExtension.EXCLUDED_SUBTREES,
+ new GeneralSubtrees(excludedSubtrees));
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
replaceExtension(PKIXExtensions.NameConstraints_Id.toString(), ext, info);
} catch (IOException e) {
CMS.debug("NameConstraintsExtDefault: setValue " + e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
} catch (EProfileException e) {
CMS.debug("NameConstraintsExtDefault: setValue " + e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
@@ -385,16 +380,16 @@ public class NameConstraintsExtDefault extends EnrollExtDefault {
} else if (name1.equals(MAX_VALUE)) {
maxS = nvps.getValue(name1);
}
- }
+ }
if (choice == null || choice.length() == 0) {
throw new EPropertyException(CMS.getUserMessage(locale,
"CMS_PROFILE_GENERAL_NAME_NOT_FOUND"));
}
-
+
if (val == null)
val = "";
-
+
int min = 0;
int max = -1;
@@ -410,7 +405,7 @@ public class NameConstraintsExtDefault extends EnrollExtDefault {
gnI = parseGeneralName(choice + ":" + val);
} catch (IOException e) {
CMS.debug("NameConstraintsExtDefault: createSubtress " +
- e.toString());
+ e.toString());
}
if (gnI != null) {
@@ -423,32 +418,31 @@ public class NameConstraintsExtDefault extends EnrollExtDefault {
gn, min, max);
subtrees.addElement(subtree);
- }
+ }
return subtrees;
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
+ X509CertInfo info)
+ throws EPropertyException {
NameConstraintsExtension ext = null;
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
ext = (NameConstraintsExtension)
- getExtension(PKIXExtensions.NameConstraints_Id.toString(), info);
+ getExtension(PKIXExtensions.NameConstraints_Id.toString(), info);
- if(ext == null)
- {
+ if (ext == null) {
try {
- populate(null,info);
+ populate(null, info);
} catch (EProfileException e) {
- throw new EPropertyException(CMS.getUserMessage(
- locale, "CMS_INVALID_PROPERTY", name));
+ throw new EPropertyException(CMS.getUserMessage(
+ locale, "CMS_INVALID_PROPERTY", name));
}
}
@@ -465,7 +459,7 @@ public class NameConstraintsExtDefault extends EnrollExtDefault {
} else {
return "false";
}
- } else if (name.equals(VAL_PERMITTED_SUBTREES)) {
+ } else if (name.equals(VAL_PERMITTED_SUBTREES)) {
ext = (NameConstraintsExtension)
getExtension(PKIXExtensions.NameConstraints_Id.toString(), info);
@@ -475,19 +469,19 @@ public class NameConstraintsExtDefault extends EnrollExtDefault {
GeneralSubtrees subtrees = null;
try {
- subtrees = (GeneralSubtrees)
+ subtrees = (GeneralSubtrees)
ext.get(NameConstraintsExtension.PERMITTED_SUBTREES);
} catch (IOException e) {
CMS.debug("NameConstraintExtDefault: getValue " + e.toString());
}
- if( subtrees == null ) {
- CMS.debug( "NameConstraintsExtDefault::getValue() VAL_PERMITTED_SUBTREES is null!" );
- throw new EPropertyException( "subtrees is null" );
+ if (subtrees == null) {
+ CMS.debug("NameConstraintsExtDefault::getValue() VAL_PERMITTED_SUBTREES is null!");
+ throw new EPropertyException("subtrees is null");
}
return getSubtreesInfo(ext, subtrees);
- } else if (name.equals(VAL_EXCLUDED_SUBTREES)) {
+ } else if (name.equals(VAL_EXCLUDED_SUBTREES)) {
ext = (NameConstraintsExtension)
getExtension(PKIXExtensions.NameConstraints_Id.toString(), info);
@@ -497,26 +491,26 @@ public class NameConstraintsExtDefault extends EnrollExtDefault {
GeneralSubtrees subtrees = null;
try {
- subtrees = (GeneralSubtrees)
+ subtrees = (GeneralSubtrees)
ext.get(NameConstraintsExtension.EXCLUDED_SUBTREES);
} catch (IOException e) {
CMS.debug("NameConstraintExtDefault: getValue " + e.toString());
}
- if( subtrees == null ) {
- CMS.debug( "NameConstraintsExtDefault::getValue() VAL_EXCLUDED_SUBTREES is null!" );
- throw new EPropertyException( "subtrees is null" );
+ if (subtrees == null) {
+ CMS.debug("NameConstraintsExtDefault::getValue() VAL_EXCLUDED_SUBTREES is null!");
+ throw new EPropertyException("subtrees is null");
}
return getSubtreesInfo(ext, subtrees);
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
- private String getSubtreesInfo(NameConstraintsExtension ext,
- GeneralSubtrees subtrees) throws EPropertyException {
+ private String getSubtreesInfo(NameConstraintsExtension ext,
+ GeneralSubtrees subtrees) throws EPropertyException {
Vector<GeneralSubtree> trees = subtrees.getSubtrees();
int size = trees.size();
@@ -526,8 +520,8 @@ public class NameConstraintsExtDefault extends EnrollExtDefault {
GeneralSubtree tree = (GeneralSubtree) trees.elementAt(i);
GeneralName gn = tree.getGeneralName();
- String type = getGeneralNameType(gn);
- int max = tree.getMaxValue();
+ String type = getGeneralNameType(gn);
+ int max = tree.getMaxValue();
int min = tree.getMinValue();
NameValuePairs pairs = new NameValuePairs();
@@ -540,7 +534,7 @@ public class NameConstraintsExtDefault extends EnrollExtDefault {
recs.addElement(pairs);
}
-
+
return buildRecords(recs);
}
@@ -583,8 +577,8 @@ public class NameConstraintsExtDefault extends EnrollExtDefault {
sb.append(getConfig(CONFIG_EXCLUDED_MAX_VAL + i));
sb.append("}");
}
- return CMS.getUserMessage(locale,
- "CMS_PROFILE_DEF_NAME_CONSTRAINTS_EXT",
+ return CMS.getUserMessage(locale,
+ "CMS_PROFILE_DEF_NAME_CONSTRAINTS_EXT",
getConfig(CONFIG_CRITICAL), sb.toString());
}
@@ -592,14 +586,14 @@ public class NameConstraintsExtDefault extends EnrollExtDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
NameConstraintsExtension ext = createExtension();
addExtension(PKIXExtensions.NameConstraints_Id.toString(), ext, info);
}
public NameConstraintsExtension createExtension() {
- NameConstraintsExtension ext = null;
+ NameConstraintsExtension ext = null;
try {
int num = getNumPermitted();
@@ -637,18 +631,18 @@ public class NameConstraintsExtDefault extends EnrollExtDefault {
}
}
- ext = new NameConstraintsExtension(critical,
+ ext = new NameConstraintsExtension(critical,
new GeneralSubtrees(v), new GeneralSubtrees(v1));
} catch (Exception e) {
- CMS.debug("NameConstraintsExtDefault: createExtension " +
- e.toString());
+ CMS.debug("NameConstraintsExtDefault: createExtension " +
+ e.toString());
}
return ext;
}
- private GeneralSubtree createSubtree(String choice, String value,
- String minS, String maxS) {
+ private GeneralSubtree createSubtree(String choice, String value,
+ String minS, String maxS) {
GeneralName gn = null;
GeneralNameInterface gnI = null;
@@ -660,7 +654,7 @@ public class NameConstraintsExtDefault extends EnrollExtDefault {
if (gnI != null)
gn = new GeneralName(gnI);
else
- //throw new EPropertyException("GeneralName must not be null");
+ // throw new EPropertyException("GeneralName must not be null");
return null;
int min = 0;
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/NoDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/NoDefault.java
index 283f5083..8197d3de 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/NoDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/NoDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.util.Enumeration;
import java.util.Locale;
import java.util.Vector;
@@ -32,13 +31,12 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
* This class implements no default policy.
- *
+ *
* @version $Revision$, $Date$
*/
-public class NoDefault implements IPolicyDefault {
+public class NoDefault implements IPolicyDefault {
public static final String PROP_NAME = "name";
@@ -55,7 +53,7 @@ public class NoDefault implements IPolicyDefault {
}
public void setConfig(String name, String value)
- throws EPropertyException {
+ throws EPropertyException {
}
public String getDefaultConfig(String name) {
@@ -67,7 +65,7 @@ public class NoDefault implements IPolicyDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
mConfig = config;
}
@@ -79,7 +77,7 @@ public class NoDefault implements IPolicyDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request)
- throws EProfileException {
+ throws EProfileException {
}
public Enumeration getValueNames() {
@@ -90,9 +88,9 @@ public class NoDefault implements IPolicyDefault {
return null;
}
- public void setValue(String name, Locale locale, IRequest request,
- String value)
- throws EPropertyException {
+ public void setValue(String name, Locale locale, IRequest request,
+ String value)
+ throws EPropertyException {
}
public String getValue(String name, Locale locale, IRequest request) {
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/OCSPNoCheckExtDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/OCSPNoCheckExtDefault.java
index 28a25a6e..576d1a5d 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/OCSPNoCheckExtDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/OCSPNoCheckExtDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.util.Locale;
import netscape.security.extensions.OCSPNoCheckExtension;
@@ -32,12 +31,10 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements an enrollment default policy
- * that populates an OCSP No Check extension
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates an OCSP No
+ * Check extension into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class OCSPNoCheckExtDefault extends EnrollExtDefault {
@@ -53,13 +50,13 @@ public class OCSPNoCheckExtDefault extends EnrollExtDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
if (name.equals(CONFIG_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else {
@@ -69,7 +66,7 @@ public class OCSPNoCheckExtDefault extends EnrollExtDefault {
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else {
@@ -78,70 +75,67 @@ public class OCSPNoCheckExtDefault extends EnrollExtDefault {
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
- if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ X509CertInfo info, String value)
+ throws EPropertyException {
+ if (name == null) {
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
OCSPNoCheckExtension ext = (OCSPNoCheckExtension)
getExtension(OCSPNoCheckExtension.OID, info);
-
- if(ext == null)
- {
+ if (ext == null) {
try {
- populate(null,info);
+ populate(null, info);
} catch (EProfileException e) {
- throw new EPropertyException(CMS.getUserMessage(
- locale, "CMS_INVALID_PROPERTY", name));
+ throw new EPropertyException(CMS.getUserMessage(
+ locale, "CMS_INVALID_PROPERTY", name));
}
}
if (name.equals(VAL_CRITICAL)) {
ext = (OCSPNoCheckExtension)
- getExtension(OCSPNoCheckExtension.OID, info);
+ getExtension(OCSPNoCheckExtension.OID, info);
boolean val = Boolean.valueOf(value).booleanValue();
- if(ext == null) {
- return;
+ if (ext == null) {
+ return;
}
ext.setCritical(val);
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
+ X509CertInfo info)
+ throws EPropertyException {
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
OCSPNoCheckExtension ext = (OCSPNoCheckExtension)
getExtension(OCSPNoCheckExtension.OID, info);
- if(ext == null)
- {
+ if (ext == null) {
try {
- populate(null,info);
+ populate(null, info);
} catch (EProfileException e) {
- throw new EPropertyException(CMS.getUserMessage(
- locale, "CMS_INVALID_PROPERTY", name));
+ throw new EPropertyException(CMS.getUserMessage(
+ locale, "CMS_INVALID_PROPERTY", name));
}
}
if (name.equals(VAL_CRITICAL)) {
ext = (OCSPNoCheckExtension)
- getExtension(OCSPNoCheckExtension.OID, info);
+ getExtension(OCSPNoCheckExtension.OID, info);
if (ext == null) {
return null;
@@ -152,7 +146,7 @@ public class OCSPNoCheckExtDefault extends EnrollExtDefault {
return "false";
}
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
@@ -166,20 +160,20 @@ public class OCSPNoCheckExtDefault extends EnrollExtDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
OCSPNoCheckExtension ext = createExtension();
addExtension(OCSPNoCheckExtension.OID, ext, info);
}
public OCSPNoCheckExtension createExtension() {
- OCSPNoCheckExtension ext = null;
+ OCSPNoCheckExtension ext = null;
try {
ext = new OCSPNoCheckExtension();
} catch (Exception e) {
CMS.debug("OCSPNoCheckExtDefault: createExtension " +
- e.toString());
+ e.toString());
return null;
}
boolean critical = getConfigBoolean(CONFIG_CRITICAL);
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/PolicyConstraintsExtDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/PolicyConstraintsExtDefault.java
index 9a36f0cd..c8a4e675 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/PolicyConstraintsExtDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/PolicyConstraintsExtDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.io.IOException;
import java.util.Locale;
@@ -34,12 +33,10 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements an enrollment default policy
- * that populates a policy constraints extension
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates a policy
+ * constraints extension into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class PolicyConstraintsExtDefault extends EnrollExtDefault {
@@ -64,17 +61,17 @@ public class PolicyConstraintsExtDefault extends EnrollExtDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
if (name.equals(CONFIG_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.equals(CONFIG_REQ_EXPLICIT_POLICY)) {
- return new Descriptor(IDescriptor.INTEGER, null,
+ return new Descriptor(IDescriptor.INTEGER, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_REQUIRED_EXPLICIT_POLICY"));
} else if (name.equals(CONFIG_INHIBIT_POLICY_MAPPING)) {
@@ -87,11 +84,11 @@ public class PolicyConstraintsExtDefault extends EnrollExtDefault {
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.equals(VAL_REQ_EXPLICIT_POLICY)) {
- return new Descriptor(IDescriptor.INTEGER, null,
+ return new Descriptor(IDescriptor.INTEGER, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_REQUIRED_EXPLICIT_POLICY"));
} else if (name.equals(VAL_INHIBIT_POLICY_MAPPING)) {
@@ -103,104 +100,103 @@ public class PolicyConstraintsExtDefault extends EnrollExtDefault {
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
try {
PolicyConstraintsExtension ext = null;
- if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ if (name == null) {
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
ext = (PolicyConstraintsExtension)
getExtension(PKIXExtensions.PolicyConstraints_Id.toString(),
- info);
+ info);
- if(ext == null) {
- populate(null,info);
+ if (ext == null) {
+ populate(null, info);
}
if (name.equals(VAL_CRITICAL)) {
ext = (PolicyConstraintsExtension)
- getExtension(PKIXExtensions.PolicyConstraints_Id.toString(),
- info);
+ getExtension(PKIXExtensions.PolicyConstraints_Id.toString(),
+ info);
boolean val = Boolean.valueOf(value).booleanValue();
- if(ext == null) {
+ if (ext == null) {
return;
}
- ext.setCritical(val);
- } else if (name.equals(VAL_REQ_EXPLICIT_POLICY)) {
+ ext.setCritical(val);
+ } else if (name.equals(VAL_REQ_EXPLICIT_POLICY)) {
ext = (PolicyConstraintsExtension)
- getExtension(PKIXExtensions.PolicyConstraints_Id.toString(),
- info);
-
- if(ext == null) {
+ getExtension(PKIXExtensions.PolicyConstraints_Id.toString(),
+ info);
+
+ if (ext == null) {
return;
- }
+ }
Integer num = new Integer(value);
ext.set(PolicyConstraintsExtension.REQUIRE, num);
- } else if (name.equals(VAL_INHIBIT_POLICY_MAPPING)) {
+ } else if (name.equals(VAL_INHIBIT_POLICY_MAPPING)) {
ext = (PolicyConstraintsExtension)
- getExtension(PKIXExtensions.PolicyConstraints_Id.toString(),
- info);
+ getExtension(PKIXExtensions.PolicyConstraints_Id.toString(),
+ info);
- if(ext == null) {
+ if (ext == null) {
return;
}
Integer num = new Integer(value);
ext.set(PolicyConstraintsExtension.INHIBIT, num);
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
replaceExtension(PKIXExtensions.PolicyConstraints_Id.toString(),
- ext, info);
+ ext, info);
} catch (EProfileException e) {
CMS.debug("PolicyConstraintsExtDefault: setValue " + e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
} catch (IOException e) {
CMS.debug("PolicyConstraintsExtDefault: setValue " + e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
+ X509CertInfo info)
+ throws EPropertyException {
PolicyConstraintsExtension ext = null;
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
ext = (PolicyConstraintsExtension)
getExtension(PKIXExtensions.PolicyConstraints_Id.toString(),
- info);
- if(ext == null)
- {
+ info);
+ if (ext == null) {
try {
- populate(null,info);
+ populate(null, info);
} catch (EProfileException e) {
- throw new EPropertyException(CMS.getUserMessage(
- locale, "CMS_INVALID_PROPERTY", name));
+ throw new EPropertyException(CMS.getUserMessage(
+ locale, "CMS_INVALID_PROPERTY", name));
}
}
if (name.equals(VAL_CRITICAL)) {
ext = (PolicyConstraintsExtension)
- getExtension(PKIXExtensions.PolicyConstraints_Id.toString(),
- info);
+ getExtension(PKIXExtensions.PolicyConstraints_Id.toString(),
+ info);
if (ext == null) {
return null;
@@ -210,10 +206,10 @@ public class PolicyConstraintsExtDefault extends EnrollExtDefault {
} else {
return "false";
}
- } else if (name.equals(VAL_REQ_EXPLICIT_POLICY)) {
+ } else if (name.equals(VAL_REQ_EXPLICIT_POLICY)) {
ext = (PolicyConstraintsExtension)
- getExtension(PKIXExtensions.PolicyConstraints_Id.toString(),
- info);
+ getExtension(PKIXExtensions.PolicyConstraints_Id.toString(),
+ info);
if (ext == null)
return "";
@@ -223,8 +219,8 @@ public class PolicyConstraintsExtDefault extends EnrollExtDefault {
return "" + num;
} else if (name.equals(VAL_INHIBIT_POLICY_MAPPING)) {
ext = (PolicyConstraintsExtension)
- getExtension(PKIXExtensions.PolicyConstraints_Id.toString(),
- info);
+ getExtension(PKIXExtensions.PolicyConstraints_Id.toString(),
+ info);
if (ext == null)
return "";
@@ -233,15 +229,15 @@ public class PolicyConstraintsExtDefault extends EnrollExtDefault {
return "" + num;
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
public String getText(Locale locale) {
String params[] = {
- getConfig(CONFIG_CRITICAL),
- getConfig(CONFIG_REQ_EXPLICIT_POLICY),
+ getConfig(CONFIG_CRITICAL),
+ getConfig(CONFIG_REQ_EXPLICIT_POLICY),
getConfig(CONFIG_INHIBIT_POLICY_MAPPING)
};
@@ -252,17 +248,17 @@ public class PolicyConstraintsExtDefault extends EnrollExtDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
PolicyConstraintsExtension ext = createExtension();
if (ext == null)
return;
- addExtension(PKIXExtensions.PolicyConstraints_Id.toString(),
- ext, info);
+ addExtension(PKIXExtensions.PolicyConstraints_Id.toString(),
+ ext, info);
}
public PolicyConstraintsExtension createExtension() {
- PolicyConstraintsExtension ext = null;
+ PolicyConstraintsExtension ext = null;
try {
boolean critical = getConfigBoolean(CONFIG_CRITICAL);
@@ -281,8 +277,8 @@ public class PolicyConstraintsExtDefault extends EnrollExtDefault {
}
ext = new PolicyConstraintsExtension(critical, reqNum, inhibitNum);
} catch (Exception e) {
- CMS.debug("PolicyConstraintsExtDefault: createExtension " +
- e.toString());
+ CMS.debug("PolicyConstraintsExtDefault: createExtension " +
+ e.toString());
}
return ext;
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/PolicyMappingsExtDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/PolicyMappingsExtDefault.java
index 05899e2c..c186c453 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/PolicyMappingsExtDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/PolicyMappingsExtDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.io.IOException;
import java.util.Enumeration;
import java.util.Locale;
@@ -40,12 +39,10 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements an enrollment default policy
- * that populates a policy mappings extension
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates a policy
+ * mappings extension into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class PolicyMappingsExtDefault extends EnrollExtDefault {
@@ -85,27 +82,27 @@ public class PolicyMappingsExtDefault extends EnrollExtDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
refreshConfigAndValueNames();
}
- public void setConfig(String name, String value)
- throws EPropertyException {
+ public void setConfig(String name, String value)
+ throws EPropertyException {
int num = 0;
if (name.equals(CONFIG_NUM_POLICY_MAPPINGS)) {
- try {
- num = Integer.parseInt(value);
+ try {
+ num = Integer.parseInt(value);
- if (num >= MAX_NUM_MAPPINGS || num < 0) {
- throw new EPropertyException(CMS.getUserMessage(
+ if (num >= MAX_NUM_MAPPINGS || num < 0) {
+ throw new EPropertyException(CMS.getUserMessage(
"CMS_INVALID_PROPERTY", CONFIG_NUM_POLICY_MAPPINGS));
- }
+ }
- } catch (Exception e) {
+ } catch (Exception e) {
throw new EPropertyException(CMS.getUserMessage(
"CMS_INVALID_PROPERTY", CONFIG_NUM_POLICY_MAPPINGS));
- }
+ }
}
super.setConfig(name, value);
}
@@ -132,7 +129,7 @@ public class PolicyMappingsExtDefault extends EnrollExtDefault {
}
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
if (name.equals(CONFIG_CRITICAL)) {
return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
@@ -151,8 +148,8 @@ public class PolicyMappingsExtDefault extends EnrollExtDefault {
CMS.getUserMessage(locale, "CMS_PROFILE_ENABLE"));
} else if (name.startsWith(CONFIG_NUM_POLICY_MAPPINGS)) {
return new Descriptor(IDescriptor.INTEGER, null,
- "1",
- CMS.getUserMessage(locale, "CMS_PROFILE_NUM_POLICY_MAPPINGS"));
+ "1",
+ CMS.getUserMessage(locale, "CMS_PROFILE_NUM_POLICY_MAPPINGS"));
}
return null;
@@ -160,7 +157,7 @@ public class PolicyMappingsExtDefault extends EnrollExtDefault {
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.equals(VAL_DOMAINS)) {
@@ -172,43 +169,43 @@ public class PolicyMappingsExtDefault extends EnrollExtDefault {
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
try {
PolicyMappingsExtension ext = null;
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
ext = (PolicyMappingsExtension)
getExtension(PKIXExtensions.PolicyMappings_Id.toString(),
- info);
+ info);
- if(ext == null) {
- populate(null,info);
+ if (ext == null) {
+ populate(null, info);
}
if (name.equals(VAL_CRITICAL)) {
ext = (PolicyMappingsExtension)
- getExtension(PKIXExtensions.PolicyMappings_Id.toString(),
- info);
+ getExtension(PKIXExtensions.PolicyMappings_Id.toString(),
+ info);
boolean val = Boolean.valueOf(value).booleanValue();
- if(ext == null) {
+ if (ext == null) {
return;
}
- ext.setCritical(val);
- } else if (name.equals(VAL_DOMAINS)) {
+ ext.setCritical(val);
+ } else if (name.equals(VAL_DOMAINS)) {
ext = (PolicyMappingsExtension)
- getExtension(PKIXExtensions.PolicyMappings_Id.toString(),
- info);
-
- if(ext == null) {
+ getExtension(PKIXExtensions.PolicyMappings_Id.toString(),
+ info);
+
+ if (ext == null) {
return;
- }
+ }
Vector<NameValuePairs> v = parseRecords(value);
int size = v.size();
@@ -232,12 +229,12 @@ public class PolicyMappingsExtDefault extends EnrollExtDefault {
enable = nvps.getValue(name1);
}
}
-
+
if (enable != null && enable.equals("true")) {
- if (issuerPolicyId == null ||
- issuerPolicyId.length() == 0 || subjectPolicyId == null ||
- subjectPolicyId.length() == 0)
- throw new EPropertyException(CMS.getUserMessage(
+ if (issuerPolicyId == null ||
+ issuerPolicyId.length() == 0 || subjectPolicyId == null ||
+ subjectPolicyId.length() == 0)
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_PROFILE_POLICY_ID_NOT_FOUND"));
CertificatePolicyMap map = new CertificatePolicyMap(
new CertificatePolicyId(new ObjectIdentifier(issuerPolicyId)),
@@ -248,52 +245,51 @@ public class PolicyMappingsExtDefault extends EnrollExtDefault {
}
ext.set(PolicyMappingsExtension.MAP, policyMaps);
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
replaceExtension(PKIXExtensions.PolicyMappings_Id.toString(),
- ext, info);
+ ext, info);
} catch (EProfileException e) {
CMS.debug("PolicyMappingsExtDefault: setValue " + e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
} catch (IOException e) {
CMS.debug("PolicyMappingsExtDefault: setValue " + e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
+ X509CertInfo info)
+ throws EPropertyException {
PolicyMappingsExtension ext = null;
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
ext = (PolicyMappingsExtension)
getExtension(PKIXExtensions.PolicyMappings_Id.toString(),
- info);
- if(ext == null)
- {
+ info);
+ if (ext == null) {
try {
- populate(null,info);
+ populate(null, info);
} catch (EProfileException e) {
- throw new EPropertyException(CMS.getUserMessage(
- locale, "CMS_INVALID_PROPERTY", name));
+ throw new EPropertyException(CMS.getUserMessage(
+ locale, "CMS_INVALID_PROPERTY", name));
}
}
if (name.equals(VAL_CRITICAL)) {
ext = (PolicyMappingsExtension)
- getExtension(PKIXExtensions.PolicyMappings_Id.toString(),
- info);
+ getExtension(PKIXExtensions.PolicyMappings_Id.toString(),
+ info);
if (ext == null) {
return null;
@@ -303,10 +299,10 @@ public class PolicyMappingsExtDefault extends EnrollExtDefault {
} else {
return "false";
}
- } else if (name.equals(VAL_DOMAINS)) {
+ } else if (name.equals(VAL_DOMAINS)) {
ext = (PolicyMappingsExtension)
- getExtension(PKIXExtensions.PolicyMappings_Id.toString(),
- info);
+ getExtension(PKIXExtensions.PolicyMappings_Id.toString(),
+ info);
if (ext == null)
return "";
@@ -314,7 +310,7 @@ public class PolicyMappingsExtDefault extends EnrollExtDefault {
int num_mappings = getNumMappings();
Enumeration<CertificatePolicyMap> maps = ext.getMappings();
-
+
int num = 0;
StringBuffer sb = new StringBuffer();
@@ -323,12 +319,12 @@ public class PolicyMappingsExtDefault extends EnrollExtDefault {
for (int i = 0; i < num_mappings; i++) {
NameValuePairs pairs = new NameValuePairs();
- if (maps.hasMoreElements()) {
- CertificatePolicyMap map =
- (CertificatePolicyMap) maps.nextElement();
-
+ if (maps.hasMoreElements()) {
+ CertificatePolicyMap map =
+ (CertificatePolicyMap) maps.nextElement();
+
CertificatePolicyId i1 = map.getIssuerIdentifier();
- CertificatePolicyId s1 = map.getSubjectIdentifier();
+ CertificatePolicyId s1 = map.getSubjectIdentifier();
pairs.add(ISSUER_POLICY_ID, i1.getIdentifier().toString());
pairs.add(SUBJECT_POLICY_ID, s1.getIdentifier().toString());
@@ -337,14 +333,14 @@ public class PolicyMappingsExtDefault extends EnrollExtDefault {
pairs.add(ISSUER_POLICY_ID, "");
pairs.add(SUBJECT_POLICY_ID, "");
pairs.add(POLICY_ID_ENABLE, "false");
-
+
}
recs.addElement(pairs);
- }
-
+ }
+
return buildRecords(recs);
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
@@ -368,8 +364,8 @@ public class PolicyMappingsExtDefault extends EnrollExtDefault {
sb.append(getConfig(CONFIG_ENABLE + i));
sb.append("}");
}
- return CMS.getUserMessage(locale,
- "CMS_PROFILE_DEF_POLICY_MAPPINGS_EXT",
+ return CMS.getUserMessage(locale,
+ "CMS_PROFILE_DEF_POLICY_MAPPINGS_EXT",
getConfig(CONFIG_CRITICAL), sb.toString());
}
@@ -377,24 +373,24 @@ public class PolicyMappingsExtDefault extends EnrollExtDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
PolicyMappingsExtension ext = createExtension();
if (ext == null)
return;
- addExtension(PKIXExtensions.PolicyMappings_Id.toString(),
- ext, info);
+ addExtension(PKIXExtensions.PolicyMappings_Id.toString(),
+ ext, info);
}
public PolicyMappingsExtension createExtension() {
- PolicyMappingsExtension ext = null;
+ PolicyMappingsExtension ext = null;
try {
boolean critical = getConfigBoolean(CONFIG_CRITICAL);
Vector<CertificatePolicyMap> policyMaps = new Vector<CertificatePolicyMap>();
int num = getNumMappings();
- for (int i = 0; i < num; i++) {
+ for (int i = 0; i < num; i++) {
String enable = getConfig(CONFIG_ENABLE + i);
if (enable != null && enable.equals("true")) {
@@ -420,8 +416,8 @@ public class PolicyMappingsExtDefault extends EnrollExtDefault {
ext = new PolicyMappingsExtension(critical, policyMaps);
} catch (Exception e) {
- CMS.debug("PolicyMappingsExtDefault: createExtension " +
- e.toString());
+ CMS.debug("PolicyMappingsExtDefault: createExtension " +
+ e.toString());
}
return ext;
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/PrivateKeyUsagePeriodExtDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/PrivateKeyUsagePeriodExtDefault.java
index f1a71ff9..73d4df32 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/PrivateKeyUsagePeriodExtDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/PrivateKeyUsagePeriodExtDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
@@ -37,12 +36,10 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements an enrollment default policy
- * that populates a Private Key Usage Period extension
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates a Private
+ * Key Usage Period extension into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class PrivateKeyUsagePeriodExtDefault extends EnrollExtDefault {
@@ -70,13 +67,13 @@ public class PrivateKeyUsagePeriodExtDefault extends EnrollExtDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
if (name.equals(CONFIG_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.equals(CONFIG_START_TIME)) {
@@ -93,28 +90,28 @@ public class PrivateKeyUsagePeriodExtDefault extends EnrollExtDefault {
}
public void setConfig(String name, String value)
- throws EPropertyException {
+ throws EPropertyException {
if (name.equals(CONFIG_START_TIME)) {
- try {
- Integer.parseInt(value);
- } catch (Exception e) {
- throw new EPropertyException(CMS.getUserMessage(
+ try {
+ Integer.parseInt(value);
+ } catch (Exception e) {
+ throw new EPropertyException(CMS.getUserMessage(
"CMS_INVALID_PROPERTY", CONFIG_START_TIME));
- }
+ }
} else if (name.equals(CONFIG_DURATION)) {
- try {
- Integer.parseInt(value);
- } catch (Exception e) {
- throw new EPropertyException(CMS.getUserMessage(
+ try {
+ Integer.parseInt(value);
+ } catch (Exception e) {
+ throw new EPropertyException(CMS.getUserMessage(
"CMS_INVALID_PROPERTY", CONFIG_DURATION));
- }
+ }
}
super.setConfig(name, value);
}
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.equals(VAL_NOT_BEFORE)) {
@@ -131,13 +128,13 @@ public class PrivateKeyUsagePeriodExtDefault extends EnrollExtDefault {
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
try {
PrivateKeyUsageExtension ext = null;
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
@@ -146,8 +143,8 @@ public class PrivateKeyUsagePeriodExtDefault extends EnrollExtDefault {
ext = (PrivateKeyUsageExtension)
getExtension(oid.toString(), info);
- if(ext == null) {
- populate(null,info);
+ if (ext == null) {
+ populate(null, info);
}
if (name.equals(VAL_CRITICAL)) {
@@ -156,38 +153,38 @@ public class PrivateKeyUsagePeriodExtDefault extends EnrollExtDefault {
getExtension(oid.toString(), info);
boolean val = Boolean.valueOf(value).booleanValue();
- if (ext == null) {
+ if (ext == null) {
return;
}
- ext.setCritical(val);
- } else if (name.equals(VAL_NOT_BEFORE)) {
- SimpleDateFormat formatter =
- new SimpleDateFormat(DATE_FORMAT);
- ParsePosition pos = new ParsePosition(0);
+ ext.setCritical(val);
+ } else if (name.equals(VAL_NOT_BEFORE)) {
+ SimpleDateFormat formatter =
+ new SimpleDateFormat(DATE_FORMAT);
+ ParsePosition pos = new ParsePosition(0);
Date date = formatter.parse(value, pos);
ext = (PrivateKeyUsageExtension)
getExtension(oid.toString(), info);
- if (ext == null) {
+ if (ext == null) {
return;
}
ext.set(PrivateKeyUsageExtension.NOT_BEFORE, date);
- } else if (name.equals(VAL_NOT_AFTER)) {
- SimpleDateFormat formatter =
- new SimpleDateFormat(DATE_FORMAT);
- ParsePosition pos = new ParsePosition(0);
+ } else if (name.equals(VAL_NOT_AFTER)) {
+ SimpleDateFormat formatter =
+ new SimpleDateFormat(DATE_FORMAT);
+ ParsePosition pos = new ParsePosition(0);
Date date = formatter.parse(value, pos);
ext = (PrivateKeyUsageExtension)
getExtension(oid.toString(), info);
- if (ext == null) {
+ if (ext == null) {
return;
}
ext.set(PrivateKeyUsageExtension.NOT_AFTER, date);
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
@@ -200,12 +197,12 @@ public class PrivateKeyUsagePeriodExtDefault extends EnrollExtDefault {
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
+ X509CertInfo info)
+ throws EPropertyException {
PrivateKeyUsageExtension ext = null;
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
@@ -214,14 +211,13 @@ public class PrivateKeyUsagePeriodExtDefault extends EnrollExtDefault {
ext = (PrivateKeyUsageExtension)
getExtension(oid.toString(), info);
- if(ext == null)
- {
+ if (ext == null) {
try {
- populate(null,info);
+ populate(null, info);
} catch (EProfileException e) {
- throw new EPropertyException(CMS.getUserMessage(
- locale, "CMS_INVALID_PROPERTY", name));
+ throw new EPropertyException(CMS.getUserMessage(
+ locale, "CMS_INVALID_PROPERTY", name));
}
}
@@ -239,9 +235,9 @@ public class PrivateKeyUsagePeriodExtDefault extends EnrollExtDefault {
} else {
return "false";
}
- } else if (name.equals(VAL_NOT_BEFORE)) {
- SimpleDateFormat formatter =
- new SimpleDateFormat(DATE_FORMAT);
+ } else if (name.equals(VAL_NOT_BEFORE)) {
+ SimpleDateFormat formatter =
+ new SimpleDateFormat(DATE_FORMAT);
ext = (PrivateKeyUsageExtension)
getExtension(oid.toString(), info);
@@ -250,9 +246,9 @@ public class PrivateKeyUsagePeriodExtDefault extends EnrollExtDefault {
return "";
return formatter.format(ext.getNotBefore());
- } else if (name.equals(VAL_NOT_AFTER)) {
- SimpleDateFormat formatter =
- new SimpleDateFormat(DATE_FORMAT);
+ } else if (name.equals(VAL_NOT_AFTER)) {
+ SimpleDateFormat formatter =
+ new SimpleDateFormat(DATE_FORMAT);
ext = (PrivateKeyUsageExtension)
getExtension(oid.toString(), info);
@@ -262,14 +258,14 @@ public class PrivateKeyUsagePeriodExtDefault extends EnrollExtDefault {
return formatter.format(ext.getNotAfter());
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
public String getText(Locale locale) {
String params[] = {
- getConfig(CONFIG_CRITICAL),
+ getConfig(CONFIG_CRITICAL),
getConfig(CONFIG_START_TIME),
getConfig(CONFIG_DURATION)
};
@@ -281,27 +277,27 @@ public class PrivateKeyUsagePeriodExtDefault extends EnrollExtDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
PrivateKeyUsageExtension ext = createExtension();
addExtension(ext.getExtensionId().toString(), ext, info);
}
public PrivateKeyUsageExtension createExtension() {
- PrivateKeyUsageExtension ext = null;
+ PrivateKeyUsageExtension ext = null;
try {
boolean critical = getConfigBoolean(CONFIG_CRITICAL);
- // always + 60 seconds
+ // always + 60 seconds
String startTimeStr = getConfig(CONFIG_START_TIME);
- if (startTimeStr == null || startTimeStr.equals("")) {
- startTimeStr = "60";
- }
- int startTime = Integer.parseInt(startTimeStr);
- Date notBefore = new Date(CMS.getCurrentDate().getTime() +
- (1000 * startTime));
+ if (startTimeStr == null || startTimeStr.equals("")) {
+ startTimeStr = "60";
+ }
+ int startTime = Integer.parseInt(startTimeStr);
+ Date notBefore = new Date(CMS.getCurrentDate().getTime() +
+ (1000 * startTime));
long notAfterVal = 0;
notAfterVal = notBefore.getTime() +
@@ -309,10 +305,10 @@ public class PrivateKeyUsagePeriodExtDefault extends EnrollExtDefault {
Date notAfter = new Date(notAfterVal);
ext = new PrivateKeyUsageExtension(notBefore, notAfter);
- ext.setCritical(critical);
+ ext.setCritical(critical);
} catch (Exception e) {
- CMS.debug("PrivateKeyUsagePeriodExt: createExtension " +
- e.toString());
+ CMS.debug("PrivateKeyUsagePeriodExt: createExtension " +
+ e.toString());
}
return ext;
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/SigningAlgDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/SigningAlgDefault.java
index 4bca9350..29d1116c 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/SigningAlgDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/SigningAlgDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.util.Locale;
import netscape.security.x509.AlgorithmId;
@@ -34,12 +33,10 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements an enrollment default policy
- * that populates a signing algorithm
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates a signing
+ * algorithm into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class SigningAlgDefault extends EnrollDefault {
@@ -47,8 +44,8 @@ public class SigningAlgDefault extends EnrollDefault {
public static final String CONFIG_ALGORITHM = "signingAlg";
public static final String VAL_ALGORITHM = "signingAlg";
- public static final String DEF_CONFIG_ALGORITHMS =
- "-,MD5withRSA,MD2withRSA,SHA1withRSA,SHA256withRSA,SHA512withRSA";
+ public static final String DEF_CONFIG_ALGORITHMS =
+ "-,MD5withRSA,MD2withRSA,SHA1withRSA,SHA256withRSA,SHA512withRSA";
public SigningAlgDefault() {
super();
@@ -57,7 +54,7 @@ public class SigningAlgDefault extends EnrollDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
@@ -68,41 +65,39 @@ public class SigningAlgDefault extends EnrollDefault {
CMS.getUserMessage(locale, "CMS_PROFILE_SIGNING_ALGORITHM"));
} else {
return null;
- }
+ }
}
- public String getSigningAlg()
- {
- String signingAlg = getConfig(CONFIG_ALGORITHM);
- // if specified, use the specified one. Otherwise, pick
- // the best selection for the user
- if (signingAlg == null || signingAlg.equals("") ||
- signingAlg.equals("-")) {
- // best pick for the user
- ICertificateAuthority ca = (ICertificateAuthority)
- CMS.getSubsystem(CMS.SUBSYSTEM_CA);
- return ca.getDefaultAlgorithm();
- } else {
- return signingAlg;
- }
+ public String getSigningAlg() {
+ String signingAlg = getConfig(CONFIG_ALGORITHM);
+ // if specified, use the specified one. Otherwise, pick
+ // the best selection for the user
+ if (signingAlg == null || signingAlg.equals("") ||
+ signingAlg.equals("-")) {
+ // best pick for the user
+ ICertificateAuthority ca = (ICertificateAuthority)
+ CMS.getSubsystem(CMS.SUBSYSTEM_CA);
+ return ca.getDefaultAlgorithm();
+ } else {
+ return signingAlg;
+ }
}
- public String getDefSigningAlgorithms()
- {
- StringBuffer allowed = new StringBuffer();
- ICertificateAuthority ca = (ICertificateAuthority)
+ public String getDefSigningAlgorithms() {
+ StringBuffer allowed = new StringBuffer();
+ ICertificateAuthority ca = (ICertificateAuthority)
CMS.getSubsystem(CMS.SUBSYSTEM_CA);
- String algos[] = ca.getCASigningAlgorithms();
- for (int i = 0; i < algos.length; i++) {
- if (allowed.length()== 0) {
- allowed.append(algos[i]);
- } else {
- allowed.append(",");
- allowed.append(algos[i]);
+ String algos[] = ca.getCASigningAlgorithms();
+ for (int i = 0; i < algos.length; i++) {
+ if (allowed.length() == 0) {
+ allowed.append(algos[i]);
+ } else {
+ allowed.append(",");
+ allowed.append(algos[i]);
+ }
}
- }
- return allowed.toString();
- }
+ return allowed.toString();
+ }
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_ALGORITHM)) {
@@ -115,31 +110,31 @@ public class SigningAlgDefault extends EnrollDefault {
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
- if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ X509CertInfo info, String value)
+ throws EPropertyException {
+ if (name == null) {
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
if (name.equals(VAL_ALGORITHM)) {
try {
info.set(X509CertInfo.ALGORITHM_ID,
- new CertificateAlgorithmId(
- AlgorithmId.getAlgorithmId(value)));
+ new CertificateAlgorithmId(
+ AlgorithmId.getAlgorithmId(value)));
} catch (Exception e) {
CMS.debug("SigningAlgDefault: setValue " + e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
+ X509CertInfo info)
+ throws EPropertyException {
if (name == null)
throw new EPropertyException("Invalid name " + name);
@@ -151,23 +146,23 @@ public class SigningAlgDefault extends EnrollDefault {
algId = (CertificateAlgorithmId)
info.get(X509CertInfo.ALGORITHM_ID);
AlgorithmId id = (AlgorithmId)
- algId.get(CertificateAlgorithmId.ALGORITHM);
+ algId.get(CertificateAlgorithmId.ALGORITHM);
return id.toString();
} catch (Exception e) {
CMS.debug("SigningAlgDefault: getValue " + e.toString());
}
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
public String getText(Locale locale) {
- return CMS.getUserMessage(locale, "CMS_PROFILE_DEF_SIGNING_ALGORITHM",
+ return CMS.getUserMessage(locale, "CMS_PROFILE_DEF_SIGNING_ALGORITHM",
getSigningAlg());
}
@@ -175,11 +170,11 @@ public class SigningAlgDefault extends EnrollDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
try {
info.set(X509CertInfo.ALGORITHM_ID,
- new CertificateAlgorithmId(
- AlgorithmId.getAlgorithmId(getSigningAlg())));
+ new CertificateAlgorithmId(
+ AlgorithmId.getAlgorithmId(getSigningAlg())));
} catch (Exception e) {
CMS.debug("SigningAlgDefault: populate " + e.toString());
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/SubjectAltNameExtDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/SubjectAltNameExtDefault.java
index 8adc94dc..f02a65de 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/SubjectAltNameExtDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/SubjectAltNameExtDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.io.IOException;
import java.util.Enumeration;
import java.util.Locale;
@@ -42,12 +41,10 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements an enrollment default policy
- * that populates a subject alternative name extension
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates a subject
+ * alternative name extension into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class SubjectAltNameExtDefault extends EnrollExtDefault {
@@ -90,70 +87,69 @@ public class SubjectAltNameExtDefault extends EnrollExtDefault {
}
if (num >= MAX_NUM_GN)
- num = DEF_NUM_GN;
+ num = DEF_NUM_GN;
return num;
}
-
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
- super.init(profile,config);
- refreshConfigAndValueNames();
+ super.init(profile, config);
+ refreshConfigAndValueNames();
// migrate old parameters to new parameters
String old_type = null;
String old_pattern = null;
IConfigStore paramConfig = config.getSubStore("params");
try {
- if (paramConfig != null) {
- old_type = paramConfig.getString(CONFIG_OLD_TYPE);
- }
+ if (paramConfig != null) {
+ old_type = paramConfig.getString(CONFIG_OLD_TYPE);
+ }
} catch (EBaseException e) {
- // nothing to do here
+ // nothing to do here
}
CMS.debug("SubjectAltNameExtDefault: Upgrading old_type=" +
old_type);
try {
- if (paramConfig != null) {
- old_pattern = paramConfig.getString(CONFIG_OLD_PATTERN);
- }
+ if (paramConfig != null) {
+ old_pattern = paramConfig.getString(CONFIG_OLD_PATTERN);
+ }
} catch (EBaseException e) {
- // nothing to do here
+ // nothing to do here
}
CMS.debug("SubjectAltNameExtDefault: Upgrading old_pattern=" +
old_pattern);
- if (old_type != null && old_pattern != null) {
- CMS.debug("SubjectAltNameExtDefault: Upgrading");
- try {
- paramConfig.putString(CONFIG_NUM_GNS, "1");
- paramConfig.putString(CONFIG_GN_ENABLE + "0", "true");
- paramConfig.putString(CONFIG_TYPE + "0", old_type);
- paramConfig.putString(CONFIG_PATTERN + "0", old_pattern);
- paramConfig.remove(CONFIG_OLD_TYPE);
- paramConfig.remove(CONFIG_OLD_PATTERN);
- profile.getConfigStore().commit(true);
- } catch (Exception e) {
- CMS.debug("SubjectAltNameExtDefault: Failed to upgrade " + e);
- }
+ if (old_type != null && old_pattern != null) {
+ CMS.debug("SubjectAltNameExtDefault: Upgrading");
+ try {
+ paramConfig.putString(CONFIG_NUM_GNS, "1");
+ paramConfig.putString(CONFIG_GN_ENABLE + "0", "true");
+ paramConfig.putString(CONFIG_TYPE + "0", old_type);
+ paramConfig.putString(CONFIG_PATTERN + "0", old_pattern);
+ paramConfig.remove(CONFIG_OLD_TYPE);
+ paramConfig.remove(CONFIG_OLD_PATTERN);
+ profile.getConfigStore().commit(true);
+ } catch (Exception e) {
+ CMS.debug("SubjectAltNameExtDefault: Failed to upgrade " + e);
+ }
}
}
public void setConfig(String name, String value)
- throws EPropertyException {
+ throws EPropertyException {
int num = 0;
if (name.equals(CONFIG_NUM_GNS)) {
- try {
- num = Integer.parseInt(value);
+ try {
+ num = Integer.parseInt(value);
- if (num >= MAX_NUM_GN || num < 0) {
- throw new EPropertyException(CMS.getUserMessage(
+ if (num >= MAX_NUM_GN || num < 0) {
+ throw new EPropertyException(CMS.getUserMessage(
"CMS_INVALID_PROPERTY", CONFIG_NUM_GNS));
- }
+ }
- } catch (Exception e) {
+ } catch (Exception e) {
throw new EPropertyException(CMS.getUserMessage(
"CMS_INVALID_PROPERTY", CONFIG_NUM_GNS));
- }
+ }
}
super.setConfig(name, value);
}
@@ -173,29 +169,29 @@ public class SubjectAltNameExtDefault extends EnrollExtDefault {
int num = getNumGNs();
addConfigName(CONFIG_NUM_GNS);
for (int i = 0; i < num; i++) {
- addConfigName(CONFIG_TYPE + i);
- addConfigName(CONFIG_PATTERN + i);
- addConfigName(CONFIG_GN_ENABLE + i);
+ addConfigName(CONFIG_TYPE + i);
+ addConfigName(CONFIG_PATTERN + i);
+ addConfigName(CONFIG_GN_ENABLE + i);
}
}
-
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
+
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
if (name.equals(CONFIG_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.startsWith(CONFIG_TYPE)) {
return new Descriptor(IDescriptor.CHOICE, "RFC822Name,DNSName,DirectoryName,EDIPartyName,URIName,IPAddress,OIDName,OtherName",
"RFC822Name",
- CMS.getUserMessage(locale,
- "CMS_PROFILE_SUBJECT_ALT_NAME_TYPE"));
+ CMS.getUserMessage(locale,
+ "CMS_PROFILE_SUBJECT_ALT_NAME_TYPE"));
} else if (name.startsWith(CONFIG_PATTERN)) {
- return new Descriptor(IDescriptor.STRING, null,
+ return new Descriptor(IDescriptor.STRING, null,
null,
- CMS.getUserMessage(locale,
- "CMS_PROFILE_SUBJECT_ALT_NAME_PATTERN"));
+ CMS.getUserMessage(locale,
+ "CMS_PROFILE_SUBJECT_ALT_NAME_PATTERN"));
} else if (name.startsWith(CONFIG_GN_ENABLE)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_GN_ENABLE"));
} else if (name.startsWith(CONFIG_NUM_GNS)) {
@@ -209,11 +205,11 @@ public class SubjectAltNameExtDefault extends EnrollExtDefault {
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.equals(VAL_GENERAL_NAMES)) {
- return new Descriptor(IDescriptor.STRING_LIST, null,
+ return new Descriptor(IDescriptor.STRING_LIST, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_GENERAL_NAMES"));
} else {
@@ -222,13 +218,13 @@ public class SubjectAltNameExtDefault extends EnrollExtDefault {
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
try {
SubjectAlternativeNameExtension ext = null;
- if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ if (name == null) {
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
@@ -236,12 +232,12 @@ public class SubjectAltNameExtDefault extends EnrollExtDefault {
(SubjectAlternativeNameExtension)
getExtension(PKIXExtensions.SubjectAlternativeName_Id.toString(), info);
- if(ext == null) {
- populate(null,info);
- }
+ if (ext == null) {
+ populate(null, info);
+ }
if (name.equals(VAL_CRITICAL)) {
- ext =
+ ext =
(SubjectAlternativeNameExtension)
getExtension(PKIXExtensions.SubjectAlternativeName_Id.toString(), info);
@@ -253,7 +249,7 @@ public class SubjectAltNameExtDefault extends EnrollExtDefault {
ext.setCritical(critical);
} else if (name.equals(VAL_GENERAL_NAMES)) {
- ext =
+ ext =
(SubjectAlternativeNameExtension)
getExtension(PKIXExtensions.SubjectAlternativeName_Id.toString(), info);
@@ -278,41 +274,41 @@ public class SubjectAltNameExtDefault extends EnrollExtDefault {
}
GeneralNameInterface n = parseGeneralName(gname);
if (n != null) {
- gn.addElement(n);
+ gn.addElement(n);
}
}
if (gn.size() == 0) {
- CMS.debug("GN size is zero");
- deleteExtension(PKIXExtensions.SubjectAlternativeName_Id.toString(), info);
+ CMS.debug("GN size is zero");
+ deleteExtension(PKIXExtensions.SubjectAlternativeName_Id.toString(), info);
return;
} else {
- CMS.debug("GN size is non zero (" + gn.size() + ")");
- ext.set(SubjectAlternativeNameExtension.SUBJECT_NAME, gn);
+ CMS.debug("GN size is non zero (" + gn.size() + ")");
+ ext.set(SubjectAlternativeNameExtension.SUBJECT_NAME, gn);
}
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
replaceExtension(
- PKIXExtensions.SubjectAlternativeName_Id.toString(),
- ext, info);
+ PKIXExtensions.SubjectAlternativeName_Id.toString(),
+ ext, info);
} catch (IOException e) {
CMS.debug("SubjectAltNameExtDefault: setValue " + e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
} catch (EProfileException e) {
CMS.debug("SubjectAltNameExtDefault: setValue " + e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
+ X509CertInfo info)
+ throws EPropertyException {
try {
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
@@ -320,22 +316,21 @@ public class SubjectAltNameExtDefault extends EnrollExtDefault {
(SubjectAlternativeNameExtension)
getExtension(PKIXExtensions.SubjectAlternativeName_Id.toString(), info);
- if(ext == null)
- {
+ if (ext == null) {
try {
- populate(null,info);
+ populate(null, info);
} catch (EProfileException e) {
- throw new EPropertyException(CMS.getUserMessage(
- locale, "CMS_INVALID_PROPERTY", name));
+ throw new EPropertyException(CMS.getUserMessage(
+ locale, "CMS_INVALID_PROPERTY", name));
}
}
if (name.equals(VAL_CRITICAL)) {
- ext =
- (SubjectAlternativeNameExtension)
- getExtension(PKIXExtensions.SubjectAlternativeName_Id.toString(), info);
+ ext =
+ (SubjectAlternativeNameExtension)
+ getExtension(PKIXExtensions.SubjectAlternativeName_Id.toString(), info);
if (ext == null) {
return null;
@@ -346,15 +341,15 @@ public class SubjectAltNameExtDefault extends EnrollExtDefault {
return "false";
}
} else if (name.equals(VAL_GENERAL_NAMES)) {
- ext =
- (SubjectAlternativeNameExtension)
- getExtension(PKIXExtensions.SubjectAlternativeName_Id.toString(), info);
+ ext =
+ (SubjectAlternativeNameExtension)
+ getExtension(PKIXExtensions.SubjectAlternativeName_Id.toString(), info);
if (ext == null) {
return null;
}
GeneralNames names = (GeneralNames)
- ext.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
+ ext.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
StringBuffer sb = new StringBuffer();
Enumeration<GeneralNameInterface> e = names.elements();
@@ -369,39 +364,39 @@ public class SubjectAltNameExtDefault extends EnrollExtDefault {
}
return sb.toString();
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
} catch (IOException e) {
- CMS.debug("SubjectAltNameExtDefault: getValue " +
- e.toString());
+ CMS.debug("SubjectAltNameExtDefault: getValue " +
+ e.toString());
}
return null;
}
/*
- * returns text that goes into description for this extension on
- * a profile
+ * returns text that goes into description for this extension on a profile
*/
public String getText(Locale locale) {
StringBuffer sb = new StringBuffer();
String numGNs = getConfig(CONFIG_NUM_GNS);
int num = getNumGNs();
- for (int i= 0; i< num; i++) {
+ for (int i = 0; i < num; i++) {
sb.append("Record #");
sb.append(i);
sb.append("{");
sb.append(GN_PATTERN + ":");
sb.append(getConfig(CONFIG_PATTERN + i));
sb.append(",");
- sb.append(GN_TYPE +":");
- sb.append(getConfig(CONFIG_TYPE +i));
+ sb.append(GN_TYPE + ":");
+ sb.append(getConfig(CONFIG_TYPE + i));
sb.append(",");
sb.append(GN_ENABLE + ":");
sb.append(getConfig(CONFIG_GN_ENABLE + i));
sb.append("}");
- };
+ }
+ ;
return CMS.getUserMessage(locale, "CMS_PROFILE_DEF_SUBJECT_ALT_NAME_EXT", getConfig(CONFIG_CRITICAL), sb.toString());
}
@@ -410,26 +405,26 @@ public class SubjectAltNameExtDefault extends EnrollExtDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
SubjectAlternativeNameExtension ext = null;
try {
- /* read from config file*/
+ /* read from config file */
ext = createExtension(request);
} catch (IOException e) {
CMS.debug("SubjectAltNameExtDefault: populate " + e.toString());
}
if (ext != null) {
- addExtension(PKIXExtensions.SubjectAlternativeName_Id.toString(),
- ext, info);
+ addExtension(PKIXExtensions.SubjectAlternativeName_Id.toString(),
+ ext, info);
} else {
CMS.debug("SubjectAltNameExtDefault: populate sees no extension. get out");
}
}
public SubjectAlternativeNameExtension createExtension(IRequest request)
- throws IOException {
+ throws IOException {
SubjectAlternativeNameExtension ext = null;
int num = getNumGNs();
@@ -438,11 +433,11 @@ public class SubjectAltNameExtDefault extends EnrollExtDefault {
GeneralNames gn = new GeneralNames();
int count = 0; // # of actual gnames
- for (int i=0; i< num; i++) {
- String enable = getConfig(CONFIG_GN_ENABLE +i);
+ for (int i = 0; i < num; i++) {
+ String enable = getConfig(CONFIG_GN_ENABLE + i);
if (enable != null && enable.equals("true")) {
- CMS.debug("SubjectAltNameExtDefault: createExtension i=" +i);
-
+ CMS.debug("SubjectAltNameExtDefault: createExtension i=" + i);
+
String pattern = getConfig(CONFIG_PATTERN + i);
if (pattern == null || pattern.equals("")) {
pattern = " ";
@@ -453,28 +448,29 @@ public class SubjectAltNameExtDefault extends EnrollExtDefault {
// cfu - see if this is server-generated (e.g. UUID4)
// to use this feature, use $server.source$ in pattern
- String source = getConfig(CONFIG_SOURCE +i);
+ String source = getConfig(CONFIG_SOURCE + i);
String type = getConfig(CONFIG_TYPE + i);
if ((source != null) && (!source.equals(""))) {
if (type.equalsIgnoreCase("OtherName")) {
- CMS.debug("SubjectAlternativeNameExtension: using "+
- source+ " as gn");
+ CMS.debug("SubjectAlternativeNameExtension: using " +
+ source + " as gn");
if (source.equals(CONFIG_SOURCE_UUID4)) {
- UUID randUUID = UUID.randomUUID();
- // call the mapPattern that does server-side gen
- // request is not used, but needed for the substitute
- // function
- gname = mapPattern(randUUID.toString(), request, pattern);
- } else { //expand more server-gen types here
- CMS.debug("SubjectAltNameExtDefault: createExtension - unsupported server-generated type: "+source+". Supported: UUID4");
- continue;
+ UUID randUUID = UUID.randomUUID();
+ // call the mapPattern that does server-side gen
+ // request is not used, but needed for the
+ // substitute
+ // function
+ gname = mapPattern(randUUID.toString(), request, pattern);
+ } else { // expand more server-gen types here
+ CMS.debug("SubjectAltNameExtDefault: createExtension - unsupported server-generated type: " + source + ". Supported: UUID4");
+ continue;
}
} else {
- CMS.debug("SubjectAltNameExtDefault: createExtension - source is only supported for subjAltExtType OtherName");
- continue;
+ CMS.debug("SubjectAltNameExtDefault: createExtension - source is only supported for subjAltExtType OtherName");
+ continue;
}
} else {
- if (request != null) {
+ if (request != null) {
gname = mapPattern(request, pattern);
}
}
@@ -483,11 +479,11 @@ public class SubjectAltNameExtDefault extends EnrollExtDefault {
CMS.debug("gname is empty, not added");
continue;
}
- CMS.debug("SubjectAltNameExtDefault: createExtension got gname=" +gname);
+ CMS.debug("SubjectAltNameExtDefault: createExtension got gname=" + gname);
GeneralNameInterface n = parseGeneralName(type + ":" + gname);
- CMS.debug("adding gname: "+gname);
+ CMS.debug("adding gname: " + gname);
if (n != null) {
CMS.debug("SubjectAlternativeNameExtension: n not null");
gn.addElement(n);
@@ -496,26 +492,26 @@ public class SubjectAltNameExtDefault extends EnrollExtDefault {
CMS.debug("SubjectAlternativeNameExtension: n null");
}
}
- }
- } //for
+ }
+ } // for
if (count != 0) {
- try {
- ext = new SubjectAlternativeNameExtension();
- } catch (Exception e) {
- CMS.debug(e.toString());
- throw new IOException( e.toString() );
- }
- ext.set(SubjectAlternativeNameExtension.SUBJECT_NAME, gn);
- ext.setCritical(critical);
+ try {
+ ext = new SubjectAlternativeNameExtension();
+ } catch (Exception e) {
+ CMS.debug(e.toString());
+ throw new IOException(e.toString());
+ }
+ ext.set(SubjectAlternativeNameExtension.SUBJECT_NAME, gn);
+ ext.setCritical(critical);
} else {
- CMS.debug("count is 0");
- }
+ CMS.debug("count is 0");
+ }
return ext;
}
- public String mapPattern(IRequest request, String pattern)
- throws IOException {
+ public String mapPattern(IRequest request, String pattern)
+ throws IOException {
Pattern p = new Pattern(pattern);
IAttrSet attrSet = null;
if (request != null) {
@@ -525,8 +521,8 @@ public class SubjectAltNameExtDefault extends EnrollExtDefault {
}
// for server-side generated values
- public String mapPattern(String val, IRequest request, String pattern)
- throws IOException {
+ public String mapPattern(String val, IRequest request, String pattern)
+ throws IOException {
Pattern p = new Pattern(pattern);
IAttrSet attrSet = null;
if (request != null) {
@@ -535,7 +531,7 @@ public class SubjectAltNameExtDefault extends EnrollExtDefault {
try {
attrSet.set("source", val);
} catch (Exception e) {
- CMS.debug("SubjectAlternativeNameExtension: mapPattern source "+e.toString());
+ CMS.debug("SubjectAlternativeNameExtension: mapPattern source " + e.toString());
}
return p.substitute("server", attrSet);
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/SubjectDirAttributesExtDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/SubjectDirAttributesExtDefault.java
index 04ae8da3..37916e02 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/SubjectDirAttributesExtDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/SubjectDirAttributesExtDefault.java
@@ -43,10 +43,9 @@ import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
/**
- * This class implements an enrollment default policy
- * that populates a subject directory attributes extension
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates a subject
+ * directory attributes extension into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class SubjectDirAttributesExtDefault extends EnrollExtDefault {
@@ -71,7 +70,7 @@ public class SubjectDirAttributesExtDefault extends EnrollExtDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
refreshConfigAndValueNames();
}
@@ -95,26 +94,25 @@ public class SubjectDirAttributesExtDefault extends EnrollExtDefault {
}
public void setConfig(String name, String value)
- throws EPropertyException {
+ throws EPropertyException {
int num = 0;
if (name.equals(DEF_NUM_ATTRS)) {
- try {
- num = Integer.parseInt(value);
+ try {
+ num = Integer.parseInt(value);
- if (num >= MAX_NUM_ATTRS || num < 0) {
- throw new EPropertyException(CMS.getUserMessage(
+ if (num >= MAX_NUM_ATTRS || num < 0) {
+ throw new EPropertyException(CMS.getUserMessage(
"CMS_INVALID_PROPERTY", CONFIG_NUM_ATTRS));
- }
+ }
- } catch (Exception e) {
+ } catch (Exception e) {
throw new EPropertyException(CMS.getUserMessage(
"CMS_INVALID_PROPERTY", CONFIG_NUM_ATTRS));
- }
+ }
}
super.setConfig(name, value);
}
-
public Enumeration<String> getConfigNames() {
refreshConfigAndValueNames();
return super.getConfigNames();
@@ -136,43 +134,43 @@ public class SubjectDirAttributesExtDefault extends EnrollExtDefault {
}
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
- if (name.equals(CONFIG_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ if (name.equals(CONFIG_CRITICAL)) {
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.startsWith(CONFIG_ATTR_NAME)) {
- return new Descriptor(IDescriptor.STRING, null,
+ return new Descriptor(IDescriptor.STRING, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_NUM_ATTRS"));
} else if (name.startsWith(CONFIG_ATTR_NAME)) {
- return new Descriptor(IDescriptor.STRING, null,
+ return new Descriptor(IDescriptor.STRING, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_ATTR_NAME"));
} else if (name.startsWith(CONFIG_PATTERN)) {
- return new Descriptor(IDescriptor.STRING, null,
+ return new Descriptor(IDescriptor.STRING, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_ATTR_VALUE"));
} else if (name.startsWith(CONFIG_ENABLE)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_ENABLE"));
} else if (name.startsWith(CONFIG_NUM_ATTRS)) {
return new Descriptor(IDescriptor.INTEGER, null,
"1",
- CMS.getUserMessage(locale, "CMS_PROFILE_NUM_ATTRS"));
- }
+ CMS.getUserMessage(locale, "CMS_PROFILE_NUM_ATTRS"));
+ }
return null;
}
public IDescriptor getValueDescriptor(Locale locale, String name) {
- if (name.equals(VAL_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ if (name.equals(VAL_CRITICAL)) {
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.equals(VAL_ATTR)) {
- return new Descriptor(IDescriptor.STRING_LIST, null,
+ return new Descriptor(IDescriptor.STRING_LIST, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_SUBJDIR_ATTRS"));
} else {
@@ -181,55 +179,53 @@ public class SubjectDirAttributesExtDefault extends EnrollExtDefault {
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
try {
SubjectDirAttributesExtension ext = null;
- if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ if (name == null) {
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
ext = (SubjectDirAttributesExtension)
- getExtension(PKIXExtensions.SubjectDirectoryAttributes_Id.toString(),
- info);
+ getExtension(PKIXExtensions.SubjectDirectoryAttributes_Id.toString(),
+ info);
if (name.equals(VAL_CRITICAL)) {
ext = (SubjectDirAttributesExtension)
- getExtension(PKIXExtensions.SubjectDirectoryAttributes_Id.toString(),
- info);
+ getExtension(PKIXExtensions.SubjectDirectoryAttributes_Id.toString(),
+ info);
boolean val = Boolean.valueOf(value).booleanValue();
- if(ext == null)
- {
+ if (ext == null) {
return;
}
- ext.setCritical(val);
- } else if (name.equals(VAL_ATTR)) {
+ ext.setCritical(val);
+ } else if (name.equals(VAL_ATTR)) {
ext = (SubjectDirAttributesExtension)
- getExtension(PKIXExtensions.SubjectDirectoryAttributes_Id.toString(),
- info);
+ getExtension(PKIXExtensions.SubjectDirectoryAttributes_Id.toString(),
+ info);
- if(ext == null)
- {
+ if (ext == null) {
return;
}
Vector<NameValuePairs> v = parseRecords(value);
int size = v.size();
-
+
boolean critical = ext.isCritical();
X500NameAttrMap map = X500NameAttrMap.getDefault();
Vector<Attribute> attrV = new Vector<Attribute>();
- for (int i=0; i < size; i++) {
+ for (int i = 0; i < size; i++) {
NameValuePairs nvps = v.elementAt(i);
Enumeration<String> names = nvps.getNames();
String attrName = null;
String attrValue = null;
String enable = "false";
while (names.hasMoreElements()) {
- String name1 = names.nextElement();
+ String name1 = names.nextElement();
if (name1.equals(ATTR_NAME)) {
attrName = nvps.getValue(name1);
@@ -241,8 +237,8 @@ public class SubjectDirAttributesExtDefault extends EnrollExtDefault {
}
if (enable.equals("true")) {
- AttributeConfig attributeConfig =
- new AttributeConfig(attrName, attrValue);
+ AttributeConfig attributeConfig =
+ new AttributeConfig(attrName, attrValue);
Attribute attr = attributeConfig.mAttribute;
if (attr != null)
attrV.addElement(attr);
@@ -256,43 +252,43 @@ public class SubjectDirAttributesExtDefault extends EnrollExtDefault {
} else
return;
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
replaceExtension(PKIXExtensions.SubjectDirectoryAttributes_Id.toString(),
- ext, info);
+ ext, info);
} catch (EProfileException e) {
- CMS.debug("SubjectDirAttributesExtDefault: setValue " +
- e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ CMS.debug("SubjectDirAttributesExtDefault: setValue " +
+ e.toString());
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
} catch (IOException e) {
- CMS.debug("SubjectDirAttributesExtDefault: setValue " +
- e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ CMS.debug("SubjectDirAttributesExtDefault: setValue " +
+ e.toString());
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
+ X509CertInfo info)
+ throws EPropertyException {
SubjectDirAttributesExtension ext = null;
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
ext = (SubjectDirAttributesExtension)
- getExtension(PKIXExtensions.SubjectDirectoryAttributes_Id.toString(),
- info);
+ getExtension(PKIXExtensions.SubjectDirectoryAttributes_Id.toString(),
+ info);
if (name.equals(VAL_CRITICAL)) {
ext = (SubjectDirAttributesExtension)
- getExtension(PKIXExtensions.SubjectDirectoryAttributes_Id.toString(),
- info);
+ getExtension(PKIXExtensions.SubjectDirectoryAttributes_Id.toString(),
+ info);
if (ext == null) {
return null;
@@ -302,10 +298,10 @@ public class SubjectDirAttributesExtDefault extends EnrollExtDefault {
} else {
return "false";
}
- } else if (name.equals(VAL_ATTR)) {
+ } else if (name.equals(VAL_ATTR)) {
ext = (SubjectDirAttributesExtension)
- getExtension(PKIXExtensions.SubjectDirectoryAttributes_Id.toString(),
- info);
+ getExtension(PKIXExtensions.SubjectDirectoryAttributes_Id.toString(),
+ info);
if (ext == null)
return "";
@@ -315,42 +311,42 @@ public class SubjectDirAttributesExtDefault extends EnrollExtDefault {
Vector<NameValuePairs> recs = new Vector<NameValuePairs>();
int num = getNumAttrs();
Enumeration<Attribute> e = ext.getAttributesList();
- CMS.debug("SubjectDirAttributesExtDefault: getValue: attributesList="+e);
- int i=0;
+ CMS.debug("SubjectDirAttributesExtDefault: getValue: attributesList=" + e);
+ int i = 0;
while (e.hasMoreElements()) {
NameValuePairs pairs = new NameValuePairs();
pairs.add(ENABLE, "true");
Attribute attr = e.nextElement();
- CMS.debug("SubjectDirAttributesExtDefault: getValue: attribute="+attr);
+ CMS.debug("SubjectDirAttributesExtDefault: getValue: attribute=" + attr);
ObjectIdentifier oid = attr.getOid();
- CMS.debug("SubjectDirAttributesExtDefault: getValue: oid="+oid);
-
+ CMS.debug("SubjectDirAttributesExtDefault: getValue: oid=" + oid);
+
String vv = map.getName(oid);
- if (vv != null)
+ if (vv != null)
pairs.add(ATTR_NAME, vv);
else
pairs.add(ATTR_NAME, oid.toString());
Enumeration<String> v = attr.getValues();
-
+
// just support single value for now
StringBuffer ss = new StringBuffer();
while (v.hasMoreElements()) {
if (ss.length() == 0)
- ss.append((String)(v.nextElement()));
+ ss.append((String) (v.nextElement()));
else {
ss.append(",");
- ss.append((String)(v.nextElement()));
+ ss.append((String) (v.nextElement()));
}
}
- pairs .add(ATTR_VALUE, ss.toString());
+ pairs.add(ATTR_VALUE, ss.toString());
recs.addElement(pairs);
i++;
}
-
- for (;i < num; i++) {
+
+ for (; i < num; i++) {
NameValuePairs pairs = new NameValuePairs();
pairs.add(ENABLE, "false");
pairs.add(ATTR_NAME, "GENERATIONQUALIFIER");
@@ -360,7 +356,7 @@ public class SubjectDirAttributesExtDefault extends EnrollExtDefault {
return buildRecords(recs);
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
@@ -383,8 +379,8 @@ public class SubjectDirAttributesExtDefault extends EnrollExtDefault {
sb.append(getConfig(CONFIG_ENABLE + i));
sb.append("}");
}
- return CMS.getUserMessage(locale,
- "CMS_PROFILE_DEF_SUBJECT_DIR_ATTR_EXT",
+ return CMS.getUserMessage(locale,
+ "CMS_PROFILE_DEF_SUBJECT_DIR_ATTR_EXT",
getConfig(CONFIG_CRITICAL),
sb.toString());
}
@@ -393,42 +389,42 @@ public class SubjectDirAttributesExtDefault extends EnrollExtDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
SubjectDirAttributesExtension ext = createExtension(request);
if (ext == null)
return;
- addExtension(PKIXExtensions.SubjectDirectoryAttributes_Id.toString(),
- ext, info);
+ addExtension(PKIXExtensions.SubjectDirectoryAttributes_Id.toString(),
+ ext, info);
}
public SubjectDirAttributesExtension createExtension(IRequest request)
- throws EProfileException {
- SubjectDirAttributesExtension ext = null;
+ throws EProfileException {
+ SubjectDirAttributesExtension ext = null;
int num = 0;
boolean critical = getConfigBoolean(CONFIG_CRITICAL);
num = getNumAttrs();
-
+
AttributeConfig attributeConfig = null;
Vector<Attribute> attrs = new Vector<Attribute>();
for (int i = 0; i < num; i++) {
- String enable = getConfig(CONFIG_ENABLE + i);
+ String enable = getConfig(CONFIG_ENABLE + i);
if (enable != null && enable.equals("true")) {
String attrName = getConfig(CONFIG_ATTR_NAME + i);
- String pattern = getConfig(CONFIG_PATTERN + i);
+ String pattern = getConfig(CONFIG_PATTERN + i);
if (pattern == null || pattern.equals(""))
pattern = " ";
- //check pattern syntax
+ // check pattern syntax
int startpos = pattern.indexOf("$");
int lastpos = pattern.lastIndexOf("$");
String attrValue = pattern;
if (!pattern.equals("") && startpos != -1 &&
- startpos == 0 && lastpos != -1 &&
- lastpos == (pattern.length()-1)) {
+ startpos == 0 && lastpos != -1 &&
+ lastpos == (pattern.length() - 1)) {
if (request != null) {
try {
attrValue = mapPattern(request, pattern);
@@ -436,7 +432,7 @@ public class SubjectDirAttributesExtDefault extends EnrollExtDefault {
throw new EProfileException(e.toString());
}
}
- }
+ }
try {
attributeConfig = new AttributeConfig(attrName, attrValue);
} catch (EPropertyException e) {
@@ -454,7 +450,7 @@ public class SubjectDirAttributesExtDefault extends EnrollExtDefault {
attrs.copyInto(attrList);
try {
ext =
- new SubjectDirAttributesExtension(attrList, critical);
+ new SubjectDirAttributesExtension(attrList, critical);
} catch (IOException e) {
throw new EProfileException(e.toString());
}
@@ -470,50 +466,49 @@ class AttributeConfig {
protected Attribute mAttribute = null;
public AttributeConfig(String attrName, String attrValue)
- throws EPropertyException {
+ throws EPropertyException {
X500NameAttrMap map = X500NameAttrMap.getDefault();
-
+
if (attrName == null || attrName.length() == 0) {
throw new EPropertyException(
- CMS.getUserMessage("CMS_PROFILE_SUBJDIR_EMPTY_ATTRNAME", attrName));
+ CMS.getUserMessage("CMS_PROFILE_SUBJDIR_EMPTY_ATTRNAME", attrName));
}
-
+
if (attrValue == null || attrValue.length() == 0) {
throw new EPropertyException(
- CMS.getUserMessage("CMS_PROFILE_SUBJDIR_EMPTY_ATTRVAL", attrValue));
+ CMS.getUserMessage("CMS_PROFILE_SUBJDIR_EMPTY_ATTRVAL", attrValue));
}
try {
mAttributeOID = new ObjectIdentifier(attrName);
} catch (Exception e) {
- CMS.debug("SubjectDirAttributesExtDefault: invalid OID syntax: "+ attrName);
+ CMS.debug("SubjectDirAttributesExtDefault: invalid OID syntax: " + attrName);
}
if (mAttributeOID == null) {
mAttributeOID = map.getOid(attrName);
if (mAttributeOID == null)
throw new EPropertyException(
- CMS.getUserMessage("CMS_BASE_INVALID_ATTRIBUTE", attrName));
+ CMS.getUserMessage("CMS_BASE_INVALID_ATTRIBUTE", attrName));
try {
checkValue(mAttributeOID, attrValue);
} catch (IOException e) {
throw new EPropertyException(CMS.getUserMessage(
- "CMS_BASE_INVALID_ATTR_VALUE", e.getMessage()));
+ "CMS_BASE_INVALID_ATTR_VALUE", e.getMessage()));
}
}
-
try {
- mAttribute = new Attribute(mAttributeOID,
- str2MultiValues(attrValue));
+ mAttribute = new Attribute(mAttributeOID,
+ str2MultiValues(attrValue));
} catch (IOException e) {
throw new EPropertyException(CMS.getUserMessage(
- "CMS_BASE_INVALID_ATTR_VALUE", e.getMessage()));
+ "CMS_BASE_INVALID_ATTR_VALUE", e.getMessage()));
}
}
- private static void checkValue(ObjectIdentifier oid, String val)
- throws IOException {
+ private static void checkValue(ObjectIdentifier oid, String val)
+ throws IOException {
AVAValueConverter c = X500NameAttrMap.getDefault().getValueConverter(oid);
DerValue derval;
@@ -527,7 +522,7 @@ class AttributeConfig {
while (tokenizer.hasMoreTokens()) {
v.addElement(tokenizer.nextToken());
}
-
+
return v;
}
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/SubjectInfoAccessExtDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/SubjectInfoAccessExtDefault.java
index 8a3f2afc..309e7228 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/SubjectInfoAccessExtDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/SubjectInfoAccessExtDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.io.IOException;
import java.util.Enumeration;
import java.util.Locale;
@@ -40,11 +39,10 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements an enrollment default policy
- * that populates Subject Info Access extension.
- *
+ * This class implements an enrollment default policy that populates Subject
+ * Info Access extension.
+ *
* @version $Revision$, $Date$
*/
public class SubjectInfoAccessExtDefault extends EnrollExtDefault {
@@ -87,29 +85,29 @@ public class SubjectInfoAccessExtDefault extends EnrollExtDefault {
return num;
}
-
+
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
refreshConfigAndValueNames();
}
public void setConfig(String name, String value)
- throws EPropertyException {
+ throws EPropertyException {
int num = 0;
if (name.equals(CONFIG_NUM_ADS)) {
- try {
- num = Integer.parseInt(value);
+ try {
+ num = Integer.parseInt(value);
- if (num >= MAX_NUM_AD || num < 0) {
- throw new EPropertyException(CMS.getUserMessage(
+ if (num >= MAX_NUM_AD || num < 0) {
+ throw new EPropertyException(CMS.getUserMessage(
"CMS_INVALID_PROPERTY", CONFIG_NUM_ADS));
- }
+ }
- } catch (Exception e) {
+ } catch (Exception e) {
throw new EPropertyException(CMS.getUserMessage(
"CMS_INVALID_PROPERTY", CONFIG_NUM_ADS));
- }
+ }
}
super.setConfig(name, value);
}
@@ -137,28 +135,28 @@ public class SubjectInfoAccessExtDefault extends EnrollExtDefault {
}
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
if (name.equals(CONFIG_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.startsWith(CONFIG_AD_METHOD)) {
- return new Descriptor(IDescriptor.STRING, null,
+ return new Descriptor(IDescriptor.STRING, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_AD_METHOD"));
} else if (name.startsWith(CONFIG_AD_LOCATIONTYPE)) {
- return new Descriptor(IDescriptor.CHOICE, "RFC822Name,DNSName,DirectoryName,EDIPartyName,URIName,IPAddress,OIDName",
+ return new Descriptor(IDescriptor.CHOICE, "RFC822Name,DNSName,DirectoryName,EDIPartyName,URIName,IPAddress,OIDName",
"URIName",
CMS.getUserMessage(locale, "CMS_PROFILE_AD_LOCATIONTYPE"));
} else if (name.startsWith(CONFIG_AD_LOCATION)) {
- return new Descriptor(IDescriptor.STRING, null,
+ return new Descriptor(IDescriptor.STRING, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_AD_LOCATION"));
} else if (name.startsWith(CONFIG_AD_ENABLE)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_AD_ENABLE"));
- } else if (name.startsWith(CONFIG_NUM_ADS)) {
+ } else if (name.startsWith(CONFIG_NUM_ADS)) {
return new Descriptor(IDescriptor.INTEGER, null,
"1",
CMS.getUserMessage(locale, "CMS_PROFILE_NUM_ADS"));
@@ -168,11 +166,11 @@ public class SubjectInfoAccessExtDefault extends EnrollExtDefault {
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_CRITICAL)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
+ return new Descriptor(IDescriptor.BOOLEAN, null,
"false",
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.equals(VAL_GENERAL_NAMES)) {
- return new Descriptor(IDescriptor.STRING_LIST, null,
+ return new Descriptor(IDescriptor.STRING_LIST, null,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_GENERAL_NAMES"));
} else {
@@ -181,45 +179,42 @@ public class SubjectInfoAccessExtDefault extends EnrollExtDefault {
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
try {
SubjectInfoAccessExtension ext = null;
- if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ if (name == null) {
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
-
SubjectInfoAccessExtension a = new SubjectInfoAccessExtension(false);
ObjectIdentifier oid = a.getExtensionId();
ext = (SubjectInfoAccessExtension)
- getExtension(oid.toString(), info);
+ getExtension(oid.toString(), info);
- if(ext == null) {
- populate(null,info);
+ if (ext == null) {
+ populate(null, info);
}
-
+
if (name.equals(VAL_CRITICAL)) {
ext = (SubjectInfoAccessExtension)
getExtension(oid.toString(), info);
boolean val = Boolean.valueOf(value).booleanValue();
- if(ext == null)
- {
+ if (ext == null) {
return;
}
- ext.setCritical(val);
- } else if (name.equals(VAL_GENERAL_NAMES)) {
+ ext.setCritical(val);
+ } else if (name.equals(VAL_GENERAL_NAMES)) {
ext = (SubjectInfoAccessExtension)
getExtension(oid.toString(), info);
- if(ext == null)
- {
+ if (ext == null) {
return;
}
boolean critical = ext.isCritical();
@@ -258,17 +253,17 @@ public class SubjectInfoAccessExtDefault extends EnrollExtDefault {
GeneralNameInterface interface1 = parseGeneralName(locationType + ":" + location);
if (interface1 == null)
throw new EPropertyException(CMS.getUserMessage(
- locale, "CMS_INVALID_PROPERTY", locationType));
+ locale, "CMS_INVALID_PROPERTY", locationType));
gn = new GeneralName(interface1);
}
-
+
if (method != null) {
try {
- ext.addAccessDescription(new ObjectIdentifier(method), gn);
+ ext.addAccessDescription(new ObjectIdentifier(method), gn);
} catch (NumberFormatException ee) {
- CMS.debug("SubjectInfoAccessExtDefault: "+ee.toString());
+ CMS.debug("SubjectInfoAccessExtDefault: " + ee.toString());
throw new EPropertyException(CMS.getUserMessage(
- locale, "CMS_PROFILE_DEF_SIA_OID", method));
+ locale, "CMS_PROFILE_DEF_SIA_OID", method));
}
}
}
@@ -291,30 +286,29 @@ public class SubjectInfoAccessExtDefault extends EnrollExtDefault {
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
+ X509CertInfo info)
+ throws EPropertyException {
SubjectInfoAccessExtension ext = null;
- if (name == null) {
+ if (name == null) {
throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
SubjectInfoAccessExtension a = new SubjectInfoAccessExtension(false);
- ObjectIdentifier oid = a.getExtensionId();
+ ObjectIdentifier oid = a.getExtensionId();
ext = (SubjectInfoAccessExtension)
getExtension(oid.toString(), info);
- if(ext == null)
- {
+ if (ext == null) {
try {
- populate(null,info);
+ populate(null, info);
} catch (EProfileException e) {
CMS.debug("SubjectInfoAccessExtDefault: getValue " + e.toString());
- throw new EPropertyException(CMS.getUserMessage(
- locale, "CMS_INVALID_PROPERTY", name));
+ throw new EPropertyException(CMS.getUserMessage(
+ locale, "CMS_INVALID_PROPERTY", name));
}
}
@@ -331,7 +325,7 @@ public class SubjectInfoAccessExtDefault extends EnrollExtDefault {
} else {
return "false";
}
- } else if (name.equals(VAL_GENERAL_NAMES)) {
+ } else if (name.equals(VAL_GENERAL_NAMES)) {
ext = (SubjectInfoAccessExtension)
getExtension(oid.toString(), info);
@@ -340,11 +334,11 @@ public class SubjectInfoAccessExtDefault extends EnrollExtDefault {
return "";
int num = getNumAds();
-
+
CMS.debug("SubjectInfoAccess num=" + num);
Vector recs = new Vector();
- for (int i = 0; i < num; i++) {
+ for (int i = 0; i < num; i++) {
NameValuePairs np = new NameValuePairs();
AccessDescription des = null;
@@ -358,7 +352,7 @@ public class SubjectInfoAccessExtDefault extends EnrollExtDefault {
np.add(AD_ENABLE, "false");
} else {
ObjectIdentifier methodOid = des.getMethod();
- GeneralName gn = des.getLocation();
+ GeneralName gn = des.getLocation();
np.add(AD_METHOD, methodOid.toString());
np.add(AD_LOCATION_TYPE, getGeneralNameType(gn));
@@ -397,7 +391,7 @@ public class SubjectInfoAccessExtDefault extends EnrollExtDefault {
ads.append(getConfig(CONFIG_AD_ENABLE + i));
ads.append("}");
}
- return CMS.getUserMessage(locale, "CMS_PROFILE_DEF_SIA_TEXT",
+ return CMS.getUserMessage(locale, "CMS_PROFILE_DEF_SIA_TEXT",
getConfig(CONFIG_CRITICAL), ads.toString());
}
@@ -405,14 +399,14 @@ public class SubjectInfoAccessExtDefault extends EnrollExtDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
SubjectInfoAccessExtension ext = createExtension();
addExtension(ext.getExtensionId().toString(), ext, info);
}
public SubjectInfoAccessExtension createExtension() {
- SubjectInfoAccessExtension ext = null;
+ SubjectInfoAccessExtension ext = null;
int num = getNumAds();
try {
@@ -434,21 +428,21 @@ public class SubjectInfoAccessExtDefault extends EnrollExtDefault {
String hostname = CMS.getEENonSSLHost();
String port = CMS.getEENonSSLPort();
if (hostname != null && port != null)
- location = "http://"+hostname+":"+port+"/ocsp";
+ location = "http://" + hostname + ":" + port + "/ocsp";
}
}
String s = locationType + ":" + location;
GeneralNameInterface gn = parseGeneralName(s);
if (gn != null) {
- ext.addAccessDescription(new ObjectIdentifier(method),
- new GeneralName(gn));
+ ext.addAccessDescription(new ObjectIdentifier(method),
+ new GeneralName(gn));
}
}
}
} catch (Exception e) {
- CMS.debug("SubjectInfoAccessExtDefault: createExtension " +
- e.toString());
+ CMS.debug("SubjectInfoAccessExtDefault: createExtension " +
+ e.toString());
}
return ext;
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/SubjectKeyIdentifierExtDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/SubjectKeyIdentifierExtDefault.java
index d8b09f5d..4df905a0 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/SubjectKeyIdentifierExtDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/SubjectKeyIdentifierExtDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@@ -39,12 +38,10 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements an enrollment default policy
- * that populates a subject key identifier extension
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates a subject
+ * key identifier extension into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class SubjectKeyIdentifierExtDefault extends EnrollExtDefault {
@@ -61,19 +58,19 @@ public class SubjectKeyIdentifierExtDefault extends EnrollExtDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_CRITICAL)) {
- return new Descriptor(IDescriptor.STRING,
- IDescriptor.READONLY,
+ return new Descriptor(IDescriptor.STRING,
+ IDescriptor.READONLY,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
} else if (name.equals(VAL_KEY_ID)) {
- return new Descriptor(IDescriptor.STRING,
- IDescriptor.READONLY,
+ return new Descriptor(IDescriptor.STRING,
+ IDescriptor.READONLY,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_KEY_ID"));
} else {
@@ -82,8 +79,8 @@ public class SubjectKeyIdentifierExtDefault extends EnrollExtDefault {
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
if (name == null) {
throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
@@ -99,8 +96,8 @@ public class SubjectKeyIdentifierExtDefault extends EnrollExtDefault {
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
+ X509CertInfo info)
+ throws EPropertyException {
if (name == null) {
throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
@@ -108,24 +105,23 @@ public class SubjectKeyIdentifierExtDefault extends EnrollExtDefault {
SubjectKeyIdentifierExtension ext =
(SubjectKeyIdentifierExtension) getExtension(
- PKIXExtensions.SubjectKey_Id.toString(), info);
+ PKIXExtensions.SubjectKey_Id.toString(), info);
- if(ext == null)
- {
+ if (ext == null) {
try {
- populate(null,info);
+ populate(null, info);
} catch (EProfileException e) {
- throw new EPropertyException(CMS.getUserMessage(
- locale, "CMS_INVALID_PROPERTY", name));
+ throw new EPropertyException(CMS.getUserMessage(
+ locale, "CMS_INVALID_PROPERTY", name));
}
}
if (name.equals(VAL_CRITICAL)) {
- ext =
- (SubjectKeyIdentifierExtension) getExtension(
- PKIXExtensions.SubjectKey_Id.toString(), info);
+ ext =
+ (SubjectKeyIdentifierExtension) getExtension(
+ PKIXExtensions.SubjectKey_Id.toString(), info);
if (ext == null) {
return null;
@@ -136,9 +132,9 @@ public class SubjectKeyIdentifierExtDefault extends EnrollExtDefault {
return "false";
}
} else if (name.equals(VAL_KEY_ID)) {
- ext =
- (SubjectKeyIdentifierExtension) getExtension(
- PKIXExtensions.SubjectKey_Id.toString(), info);
+ ext =
+ (SubjectKeyIdentifierExtension) getExtension(
+ PKIXExtensions.SubjectKey_Id.toString(), info);
if (ext == null) {
return null;
@@ -149,11 +145,11 @@ public class SubjectKeyIdentifierExtDefault extends EnrollExtDefault {
kid = (KeyIdentifier)
ext.get(SubjectKeyIdentifierExtension.KEY_ID);
} catch (IOException e) {
- CMS.debug( "SubjectKeyIdentifierExtDefault::getValue() - " +
- "kid is null!" );
- throw new EPropertyException( CMS.getUserMessage( locale,
+ CMS.debug("SubjectKeyIdentifierExtDefault::getValue() - " +
+ "kid is null!");
+ throw new EPropertyException(CMS.getUserMessage(locale,
"CMS_INVALID_PROPERTY",
- name ) );
+ name));
}
return toHexString(kid.getIdentifier());
} else {
@@ -170,7 +166,7 @@ public class SubjectKeyIdentifierExtDefault extends EnrollExtDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
SubjectKeyIdentifierExtension ext = createExtension(info);
addExtension(PKIXExtensions.SubjectKey_Id.toString(), ext, info);
@@ -184,36 +180,36 @@ public class SubjectKeyIdentifierExtDefault extends EnrollExtDefault {
return null;
}
SubjectKeyIdentifierExtension ext = null;
-
+
boolean critical = Boolean.valueOf(getConfig(CONFIG_CRITICAL)).booleanValue();
try {
ext = new SubjectKeyIdentifierExtension(critical, kid.getIdentifier());
} catch (IOException e) {
- CMS.debug("SubjectKeyIdentifierExtDefault: createExtension " +
- e.toString());
+ CMS.debug("SubjectKeyIdentifierExtDefault: createExtension " +
+ e.toString());
//
}
return ext;
}
- public KeyIdentifier getKeyIdentifier(X509CertInfo info) {
- try {
- CertificateX509Key infokey = (CertificateX509Key)
- info.get(X509CertInfo.KEY);
+ public KeyIdentifier getKeyIdentifier(X509CertInfo info) {
+ try {
+ CertificateX509Key infokey = (CertificateX509Key)
+ info.get(X509CertInfo.KEY);
X509Key key = (X509Key) infokey.get(CertificateX509Key.KEY);
MessageDigest md = MessageDigest.getInstance("SHA-1");
- md.update(key.getKey());
+ md.update(key.getKey());
byte[] hash = md.digest();
return new KeyIdentifier(hash);
} catch (NoSuchAlgorithmException e) {
- CMS.debug("SubjectKeyIdentifierExtDefault: getKeyIdentifier " +
- e.toString());
+ CMS.debug("SubjectKeyIdentifierExtDefault: getKeyIdentifier " +
+ e.toString());
} catch (Exception e) {
- CMS.debug("SubjectKeyIdentifierExtDefault: getKeyIdentifier " +
- e.toString());
+ CMS.debug("SubjectKeyIdentifierExtDefault: getKeyIdentifier " +
+ e.toString());
}
return null;
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/SubjectNameDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/SubjectNameDefault.java
index 9f404e89..787c2358 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/SubjectNameDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/SubjectNameDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.io.IOException;
import java.util.Locale;
@@ -34,12 +33,10 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements an enrollment default policy
- * that populates server-side configurable subject name
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates server-side
+ * configurable subject name into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class SubjectNameDefault extends EnrollDefault {
@@ -55,15 +52,15 @@ public class SubjectNameDefault extends EnrollDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
- if (name.equals(CONFIG_NAME)) {
- return new Descriptor(IDescriptor.STRING,
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ if (name.equals(CONFIG_NAME)) {
+ return new Descriptor(IDescriptor.STRING,
null, "CN=TEST", CMS.getUserMessage(locale,
- "CMS_PROFILE_SUBJECT_NAME"));
+ "CMS_PROFILE_SUBJECT_NAME"));
} else {
return null;
}
@@ -72,18 +69,18 @@ public class SubjectNameDefault extends EnrollDefault {
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_NAME)) {
return new Descriptor(IDescriptor.STRING, null, null,
- CMS.getUserMessage(locale,
- "CMS_PROFILE_SUBJECT_NAME"));
+ CMS.getUserMessage(locale,
+ "CMS_PROFILE_SUBJECT_NAME"));
} else {
return null;
}
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
if (name.equals(VAL_NAME)) {
@@ -100,25 +97,25 @@ public class SubjectNameDefault extends EnrollDefault {
}
CMS.debug("SubjectNameDefault: setValue name=" + x500name.toString());
try {
- info.set(X509CertInfo.SUBJECT,
- new CertificateSubjectName(x500name));
+ info.set(X509CertInfo.SUBJECT,
+ new CertificateSubjectName(x500name));
} catch (Exception e) {
// failed to insert subject name
CMS.debug("SubjectNameDefault: setValue " + e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
+ X509CertInfo info)
+ throws EPropertyException {
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
if (name.equals(VAL_NAME)) {
@@ -133,18 +130,18 @@ public class SubjectNameDefault extends EnrollDefault {
} catch (Exception e) {
// nothing
CMS.debug("SubjectNameDefault: getValue " + e.toString());
-
+
}
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
public String getText(Locale locale) {
- return CMS.getUserMessage(locale, "CMS_PROFILE_DEF_SUBJECT_NAME",
+ return CMS.getUserMessage(locale, "CMS_PROFILE_DEF_SUBJECT_NAME",
getConfig(CONFIG_NAME));
}
@@ -152,13 +149,13 @@ public class SubjectNameDefault extends EnrollDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
X500Name name = null;
String subjectName = null;
try {
- subjectName = mapPattern(request, getConfig(CONFIG_NAME));
+ subjectName = mapPattern(request, getConfig(CONFIG_NAME));
} catch (IOException e) {
CMS.debug("SubjectNameDefault: mapPattern " + e.toString());
}
@@ -176,8 +173,8 @@ public class SubjectNameDefault extends EnrollDefault {
// failed to build x500 name
}
try {
- info.set(X509CertInfo.SUBJECT,
- new CertificateSubjectName(name));
+ info.set(X509CertInfo.SUBJECT,
+ new CertificateSubjectName(name));
} catch (Exception e) {
// failed to insert subject name
CMS.debug("SubjectNameDefault: populate " + e.toString());
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/UserExtensionDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/UserExtensionDefault.java
index c834eee1..19b2d345 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/UserExtensionDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/UserExtensionDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.util.Locale;
import netscape.security.x509.CertificateExtensions;
@@ -34,12 +33,10 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements an enrollment default policy
- * that populates a user-supplied extension
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates a
+ * user-supplied extension into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class UserExtensionDefault extends EnrollExtDefault {
@@ -57,11 +54,11 @@ public class UserExtensionDefault extends EnrollExtDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
if (name.equals(CONFIG_OID)) {
return new Descriptor(IDescriptor.STRING, null,
"Comment Here...",
@@ -83,16 +80,16 @@ public class UserExtensionDefault extends EnrollExtDefault {
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
// Nothing to do for read-only values
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
- if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ X509CertInfo info)
+ throws EPropertyException {
+ if (name == null) {
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
if (name.equals(VAL_OID)) {
@@ -104,7 +101,7 @@ public class UserExtensionDefault extends EnrollExtDefault {
}
return ext.getExtensionId().toString();
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
@@ -117,22 +114,22 @@ public class UserExtensionDefault extends EnrollExtDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
CertificateExtensions inExts = null;
String oid = getConfig(CONFIG_OID);
inExts = request.getExtDataInCertExts(IEnrollProfile.REQUEST_EXTENSIONS);
if (inExts == null)
- return;
+ return;
Extension ext = getExtension(getConfig(CONFIG_OID), inExts);
if (ext == null) {
- CMS.debug("UserExtensionDefault: no user ext supplied for "+ oid);
- return;
+ CMS.debug("UserExtensionDefault: no user ext supplied for " + oid);
+ return;
}
// user supplied the ext that's allowed, replace the def set by system
deleteExtension(oid, info);
- CMS.debug("UserExtensionDefault: using user supplied ext for "+ oid);
+ CMS.debug("UserExtensionDefault: using user supplied ext for " + oid);
addExtension(oid, ext, info);
}
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/UserKeyDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/UserKeyDefault.java
index 1cff57df..97046e5f 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/UserKeyDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/UserKeyDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.io.ByteArrayInputStream;
import java.math.BigInteger;
import java.security.interfaces.DSAParams;
@@ -40,12 +39,10 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements an enrollment default policy
- * that populates a user supplied key
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates a user
+ * supplied key into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class UserKeyDefault extends EnrollDefault {
@@ -62,24 +59,24 @@ public class UserKeyDefault extends EnrollDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_KEY)) {
- return new Descriptor(IDescriptor.STRING,
- IDescriptor.READONLY,
+ return new Descriptor(IDescriptor.STRING,
+ IDescriptor.READONLY,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_KEY"));
} else if (name.equals(VAL_LEN)) {
return new Descriptor(IDescriptor.STRING,
- IDescriptor.READONLY,
+ IDescriptor.READONLY,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_KEY_LEN"));
} else if (name.equals(VAL_TYPE)) {
return new Descriptor(IDescriptor.STRING,
- IDescriptor.READONLY,
+ IDescriptor.READONLY,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_KEY_TYPE"));
} else {
@@ -88,15 +85,15 @@ public class UserKeyDefault extends EnrollDefault {
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
// this default rule is readonly
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
- if (name == null) {
+ X509CertInfo info)
+ throws EPropertyException {
+ if (name == null) {
throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
@@ -116,7 +113,7 @@ public class UserKeyDefault extends EnrollDefault {
ck.get(CertificateX509Key.KEY);
} catch (Exception e) {
// nothing
- }
+ }
if (k == null) {
throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_PROFILE_KEY_NOT_FOUND"));
@@ -139,7 +136,7 @@ public class UserKeyDefault extends EnrollDefault {
} catch (Exception e) {
// nothing
}
- if (k == null) {
+ if (k == null) {
throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_PROFILE_KEY_NOT_FOUND"));
}
@@ -171,12 +168,12 @@ public class UserKeyDefault extends EnrollDefault {
} catch (Exception e) {
// nothing
}
- if (k == null) {
+ if (k == null) {
throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_PROFILE_KEY_NOT_FOUND"));
}
- return k.getAlgorithm() + " - " +
- k.getAlgorithmId().getOID().toString();
+ return k.getAlgorithm() + " - " +
+ k.getAlgorithmId().getOID().toString();
} else {
throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
@@ -217,7 +214,7 @@ public class UserKeyDefault extends EnrollDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
CertificateX509Key certKey = null;
// authenticate the certificate key, and move
// the key from request into x509 certinfo
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/UserSigningAlgDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/UserSigningAlgDefault.java
index 07e6c77e..b129e741 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/UserSigningAlgDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/UserSigningAlgDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.io.ByteArrayInputStream;
import java.util.Locale;
@@ -35,12 +34,10 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements an enrollment default policy
- * that populates a user-supplied signing algorithm
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates a
+ * user-supplied signing algorithm into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class UserSigningAlgDefault extends EnrollDefault {
@@ -53,30 +50,30 @@ public class UserSigningAlgDefault extends EnrollDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_ALG_ID)) {
- return new Descriptor(IDescriptor.STRING,
+ return new Descriptor(IDescriptor.STRING,
IDescriptor.READONLY, null,
CMS.getUserMessage(locale,
- "CMS_PROFILE_SIGNING_ALGORITHM"));
+ "CMS_PROFILE_SIGNING_ALGORITHM"));
} else {
return null;
}
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
// this default rule is readonly
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
+ X509CertInfo info)
+ throws EPropertyException {
if (name == null) {
throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
@@ -88,12 +85,12 @@ public class UserSigningAlgDefault extends EnrollDefault {
algID = (CertificateAlgorithmId)
info.get(X509CertInfo.ALGORITHM_ID);
AlgorithmId id = (AlgorithmId)
- algID.get(CertificateAlgorithmId.ALGORITHM);
+ algID.get(CertificateAlgorithmId.ALGORITHM);
return id.toString();
} catch (Exception e) {
CMS.debug("UserSigningAlgDefault: setValue " + e.toString());
- return ""; //XXX
+ return ""; // XXX
}
} else {
throw new EPropertyException(CMS.getUserMessage(
@@ -109,7 +106,7 @@ public class UserSigningAlgDefault extends EnrollDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
CertificateAlgorithmId certAlg = null;
// authenticate the certificate key, and move
// the key from request into x509 certinfo
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/UserSubjectNameDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/UserSubjectNameDefault.java
index f589b654..5f3ec298 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/UserSubjectNameDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/UserSubjectNameDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.io.IOException;
import java.util.Locale;
@@ -35,12 +34,10 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements an enrollment default policy
- * that populates a user-supplied subject name
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates a
+ * user-supplied subject name into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class UserSubjectNameDefault extends EnrollDefault {
@@ -53,7 +50,7 @@ public class UserSubjectNameDefault extends EnrollDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
@@ -67,8 +64,8 @@ public class UserSubjectNameDefault extends EnrollDefault {
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
if (name == null) {
throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
@@ -84,12 +81,12 @@ public class UserSubjectNameDefault extends EnrollDefault {
}
CMS.debug("SubjectNameDefault: setValue name=" + x500name);
try {
- info.set(X509CertInfo.SUBJECT,
- new CertificateSubjectName(x500name));
+ info.set(X509CertInfo.SUBJECT,
+ new CertificateSubjectName(x500name));
} catch (Exception e) {
// failed to insert subject name
CMS.debug("UserSubjectNameDefault: setValue " + e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
} else {
@@ -99,10 +96,10 @@ public class UserSubjectNameDefault extends EnrollDefault {
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
- if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ X509CertInfo info)
+ throws EPropertyException {
+ if (name == null) {
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
if (name.equals(VAL_NAME)) {
@@ -115,10 +112,10 @@ public class UserSubjectNameDefault extends EnrollDefault {
} catch (Exception e) {
// nothing
}
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
@@ -131,7 +128,7 @@ public class UserSubjectNameDefault extends EnrollDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
// authenticate the subject name and populate it
// to the certinfo
try {
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/UserValidityDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/UserValidityDefault.java
index 2d79b192..2d3e9245 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/UserValidityDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/UserValidityDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.io.ByteArrayInputStream;
import java.util.Date;
import java.util.Locale;
@@ -35,12 +34,10 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements an enrollment default policy
- * that populates a user-supplied validity
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates a
+ * user-supplied validity into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class UserValidityDefault extends EnrollDefault {
@@ -55,13 +52,13 @@ public class UserValidityDefault extends EnrollDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_NOT_BEFORE)) {
- return new Descriptor(IDescriptor.STRING,
+ return new Descriptor(IDescriptor.STRING,
IDescriptor.READONLY,
null,
CMS.getUserMessage(locale, "CMS_PROFILE_NOT_BEFORE"));
@@ -76,16 +73,16 @@ public class UserValidityDefault extends EnrollDefault {
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
// this default rule is readonly
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
- if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ X509CertInfo info)
+ throws EPropertyException {
+ if (name == null) {
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
if (name.equals(VAL_NOT_BEFORE)) {
@@ -93,32 +90,32 @@ public class UserValidityDefault extends EnrollDefault {
try {
validity = (CertificateValidity)
- info.get(X509CertInfo.VALIDITY);
+ info.get(X509CertInfo.VALIDITY);
Date notBefore = (Date)
- validity.get(CertificateValidity.NOT_BEFORE);
+ validity.get(CertificateValidity.NOT_BEFORE);
return notBefore.toString();
} catch (Exception e) {
CMS.debug("UserValidityDefault: getValue " + e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
} else if (name.equals(VAL_NOT_AFTER)) {
try {
CertificateValidity validity = null;
validity = (CertificateValidity)
- info.get(X509CertInfo.VALIDITY);
+ info.get(X509CertInfo.VALIDITY);
Date notAfter = (Date)
- validity.get(CertificateValidity.NOT_AFTER);
+ validity.get(CertificateValidity.NOT_AFTER);
return notAfter.toString();
} catch (Exception e) {
CMS.debug("UserValidityDefault: getValue " + e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
@@ -131,7 +128,7 @@ public class UserValidityDefault extends EnrollDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
CertificateValidity certValidity = null;
// authenticate the certificate key, and move
// the key from request into x509 certinfo
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/ValidityDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/ValidityDefault.java
index 6e9b08ab..ab118757 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/ValidityDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/ValidityDefault.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.def;
-
import java.io.IOException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
@@ -36,12 +35,10 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements an enrollment default policy
- * that populates a server-side configurable validity
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates a
+ * server-side configurable validity into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class ValidityDefault extends EnrollDefault {
@@ -64,26 +61,26 @@ public class ValidityDefault extends EnrollDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
public void setConfig(String name, String value)
- throws EPropertyException {
+ throws EPropertyException {
if (name.equals(CONFIG_RANGE)) {
- try {
- Integer.parseInt(value);
- } catch (Exception e) {
+ try {
+ Integer.parseInt(value);
+ } catch (Exception e) {
throw new EPropertyException(CMS.getUserMessage(
"CMS_INVALID_PROPERTY", CONFIG_RANGE));
- }
+ }
} else if (name.equals(CONFIG_START_TIME)) {
- try {
- Integer.parseInt(value);
- } catch (Exception e) {
+ try {
+ Integer.parseInt(value);
+ } catch (Exception e) {
throw new EPropertyException(CMS.getUserMessage(
"CMS_INVALID_PROPERTY", CONFIG_START_TIME));
- }
+ }
}
super.setConfig(name, value);
}
@@ -91,16 +88,16 @@ public class ValidityDefault extends EnrollDefault {
public IDescriptor getConfigDescriptor(Locale locale, String name) {
if (name.equals(CONFIG_RANGE)) {
return new Descriptor(IDescriptor.STRING,
- null,
+ null,
"2922",
CMS.getUserMessage(locale,
- "CMS_PROFILE_VALIDITY_RANGE"));
+ "CMS_PROFILE_VALIDITY_RANGE"));
} else if (name.equals(CONFIG_START_TIME)) {
return new Descriptor(IDescriptor.STRING,
- null,
+ null,
"60", /* 1 minute */
CMS.getUserMessage(locale,
- "CMS_PROFILE_VALIDITY_START_TIME"));
+ "CMS_PROFILE_VALIDITY_START_TIME"));
} else {
return null;
}
@@ -119,19 +116,19 @@ public class ValidityDefault extends EnrollDefault {
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
- if (name == null) {
+ X509CertInfo info, String value)
+ throws EPropertyException {
+ if (name == null) {
throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
- if (value == null || value.equals("")) {
+ if (value == null || value.equals("")) {
throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
if (name.equals(VAL_NOT_BEFORE)) {
- SimpleDateFormat formatter =
- new SimpleDateFormat(DATE_FORMAT);
+ SimpleDateFormat formatter =
+ new SimpleDateFormat(DATE_FORMAT);
ParsePosition pos = new ParsePosition(0);
Date date = formatter.parse(value, pos);
CertificateValidity validity = null;
@@ -140,15 +137,15 @@ public class ValidityDefault extends EnrollDefault {
validity = (CertificateValidity)
info.get(X509CertInfo.VALIDITY);
validity.set(CertificateValidity.NOT_BEFORE,
- date);
+ date);
} catch (Exception e) {
CMS.debug("ValidityDefault: setValue " + e.toString());
throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
} else if (name.equals(VAL_NOT_AFTER)) {
- SimpleDateFormat formatter =
- new SimpleDateFormat(DATE_FORMAT);
+ SimpleDateFormat formatter =
+ new SimpleDateFormat(DATE_FORMAT);
ParsePosition pos = new ParsePosition(0);
Date date = formatter.parse(value, pos);
CertificateValidity validity = null;
@@ -157,7 +154,7 @@ public class ValidityDefault extends EnrollDefault {
validity = (CertificateValidity)
info.get(X509CertInfo.VALIDITY);
validity.set(CertificateValidity.NOT_AFTER,
- date);
+ date);
} catch (Exception e) {
CMS.debug("ValidityDefault: setValue " + e.toString());
throw new EPropertyException(CMS.getUserMessage(
@@ -170,16 +167,16 @@ public class ValidityDefault extends EnrollDefault {
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
+ X509CertInfo info)
+ throws EPropertyException {
if (name == null)
throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
if (name.equals(VAL_NOT_BEFORE)) {
- SimpleDateFormat formatter =
- new SimpleDateFormat(DATE_FORMAT);
+ SimpleDateFormat formatter =
+ new SimpleDateFormat(DATE_FORMAT);
CertificateValidity validity = null;
try {
@@ -192,8 +189,8 @@ public class ValidityDefault extends EnrollDefault {
}
throw new EPropertyException("Invalid valie");
} else if (name.equals(VAL_NOT_AFTER)) {
- SimpleDateFormat formatter =
- new SimpleDateFormat(DATE_FORMAT);
+ SimpleDateFormat formatter =
+ new SimpleDateFormat(DATE_FORMAT);
CertificateValidity validity = null;
try {
@@ -214,7 +211,7 @@ public class ValidityDefault extends EnrollDefault {
}
public String getText(Locale locale) {
- return CMS.getUserMessage(locale, "CMS_PROFILE_DEF_VALIDITY",
+ return CMS.getUserMessage(locale, "CMS_PROFILE_DEF_VALIDITY",
getConfig(CONFIG_RANGE));
}
@@ -222,11 +219,11 @@ public class ValidityDefault extends EnrollDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
// always + 60 seconds
String startTimeStr = getConfig(CONFIG_START_TIME);
try {
- startTimeStr = mapPattern(request, startTimeStr);
+ startTimeStr = mapPattern(request, startTimeStr);
} catch (IOException e) {
CMS.debug("ValidityDefault: populate " + e.toString());
}
@@ -241,7 +238,7 @@ public class ValidityDefault extends EnrollDefault {
try {
String rangeStr = getConfig(CONFIG_RANGE);
rangeStr = mapPattern(request, rangeStr);
- notAfterVal = notBefore.getTime() +
+ notAfterVal = notBefore.getTime() +
(mDefault * Integer.parseInt(rangeStr));
} catch (Exception e) {
// configured value is not correct
@@ -250,8 +247,8 @@ public class ValidityDefault extends EnrollDefault {
getLocale(request), "CMS_INVALID_PROPERTY", CONFIG_RANGE));
}
Date notAfter = new Date(notAfterVal);
- CertificateValidity validity =
- new CertificateValidity(notBefore, notAfter);
+ CertificateValidity validity =
+ new CertificateValidity(notBefore, notAfter);
try {
info.set(X509CertInfo.VALIDITY, validity);
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/nsHKeySubjectNameDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/nsHKeySubjectNameDefault.java
index c8beca2f..ffe7012a 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/nsHKeySubjectNameDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/nsHKeySubjectNameDefault.java
@@ -34,22 +34,21 @@ import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
/**
- * This class implements an enrollment default policy
- * that populates server-side configurable subject name
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates server-side
+ * configurable subject name into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class nsHKeySubjectNameDefault extends EnrollDefault {
- public static final String PROP_PARAMS = "params";
+ public static final String PROP_PARAMS = "params";
public static final String CONFIG_DNPATTERN = "dnpattern";
public static final String VAL_NAME = "name";
/* default dn pattern if left blank or not set in the config */
- protected static String DEFAULT_DNPATTERN =
- "CN=SecureMember - $request.tokencuid$, OU=Subscriber, O=Red Hat, C=US";
+ protected static String DEFAULT_DNPATTERN =
+ "CN=SecureMember - $request.tokencuid$, OU=Subscriber, O=Red Hat, C=US";
protected IConfigStore mParamsConfig;
@@ -61,43 +60,43 @@ public class nsHKeySubjectNameDefault extends EnrollDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
- CMS.debug("nsHKeySubjectNameDefault: in getConfigDescriptor, name="+ name);
- if (name.equals(CONFIG_DNPATTERN)) {
- return new Descriptor(IDescriptor.STRING,
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ CMS.debug("nsHKeySubjectNameDefault: in getConfigDescriptor, name=" + name);
+ if (name.equals(CONFIG_DNPATTERN)) {
+ return new Descriptor(IDescriptor.STRING,
null, null, CMS.getUserMessage(locale,
- "CMS_PROFILE_SUBJECT_NAME"));
+ "CMS_PROFILE_SUBJECT_NAME"));
} else {
return null;
}
}
public IDescriptor getValueDescriptor(Locale locale, String name) {
- CMS.debug("nsHKeySubjectNameDefault: in getValueDescriptor name="+name);
+ CMS.debug("nsHKeySubjectNameDefault: in getValueDescriptor name=" + name);
if (name.equals(VAL_NAME)) {
return new Descriptor(IDescriptor.STRING,
- null,
- null,
- CMS.getUserMessage(locale,
- "CMS_PROFILE_SUBJECT_NAME"));
+ null,
+ null,
+ CMS.getUserMessage(locale,
+ "CMS_PROFILE_SUBJECT_NAME"));
} else {
return null;
}
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
- CMS.debug("nsHKeySubjectNameDefault: in setValue, value="+value);
+ CMS.debug("nsHKeySubjectNameDefault: in setValue, value=" + value);
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
if (name.equals(VAL_NAME)) {
@@ -111,26 +110,26 @@ public class nsHKeySubjectNameDefault extends EnrollDefault {
}
CMS.debug("nsHKeySubjectNameDefault: setValue name=" + x500name);
try {
- info.set(X509CertInfo.SUBJECT,
- new CertificateSubjectName(x500name));
+ info.set(X509CertInfo.SUBJECT,
+ new CertificateSubjectName(x500name));
} catch (Exception e) {
// failed to insert subject name
CMS.debug("nsHKeySubjectNameDefault: setValue " + e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
- CMS.debug("nsHKeySubjectNameDefault: in getValue, name="+name);
+ X509CertInfo info)
+ throws EPropertyException {
+ CMS.debug("nsHKeySubjectNameDefault: in getValue, name=" + name);
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
if (name.equals(VAL_NAME)) {
@@ -145,19 +144,19 @@ public class nsHKeySubjectNameDefault extends EnrollDefault {
} catch (Exception e) {
// nothing
CMS.debug("nsHKeySubjectNameDefault: getValue " + e.toString());
-
+
}
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
public String getText(Locale locale) {
- CMS.debug("nsHKeySubjectNameDefault: in getText");
- return CMS.getUserMessage(locale, "CMS_PROFILE_SUBJECT_NAME",
+ CMS.debug("nsHKeySubjectNameDefault: in getText");
+ return CMS.getUserMessage(locale, "CMS_PROFILE_SUBJECT_NAME",
getConfig(CONFIG_DNPATTERN));
}
@@ -165,15 +164,15 @@ public class nsHKeySubjectNameDefault extends EnrollDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
X500Name name = null;
- CMS.debug("nsHKeySubjectNameDefault: in populate");
+ CMS.debug("nsHKeySubjectNameDefault: in populate");
try {
- String subjectName = getSubjectName(request);
- CMS.debug("subjectName=" + subjectName);
- if (subjectName == null || subjectName.equals(""))
- return;
+ String subjectName = getSubjectName(request);
+ CMS.debug("subjectName=" + subjectName);
+ if (subjectName == null || subjectName.equals(""))
+ return;
name = new X500Name(subjectName);
} catch (IOException e) {
@@ -184,32 +183,32 @@ public class nsHKeySubjectNameDefault extends EnrollDefault {
// failed to build x500 name
}
try {
- info.set(X509CertInfo.SUBJECT,
- new CertificateSubjectName(name));
+ info.set(X509CertInfo.SUBJECT,
+ new CertificateSubjectName(name));
} catch (Exception e) {
// failed to insert subject name
CMS.debug("nsHKeySubjectNameDefault: populate " + e.toString());
}
}
- private String getSubjectName(IRequest request)
- throws EProfileException, IOException {
+ private String getSubjectName(IRequest request)
+ throws EProfileException, IOException {
+
+ CMS.debug("nsHKeySubjectNameDefault: in getSubjectName");
- CMS.debug("nsHKeySubjectNameDefault: in getSubjectName");
+ String pattern = getConfig(CONFIG_DNPATTERN);
+ if (pattern == null || pattern.equals("")) {
+ pattern = " ";
+ }
- String pattern = getConfig(CONFIG_DNPATTERN);
- if (pattern == null || pattern.equals("")) {
- pattern = " ";
- }
-
- String sbjname = "";
+ String sbjname = "";
- if (request != null) {
- CMS.debug("pattern = "+pattern);
- sbjname = mapPattern(request, pattern);
- CMS.debug("nsHKeySubjectNameDefault: getSubjectName(): subject name mapping done");
- }
+ if (request != null) {
+ CMS.debug("pattern = " + pattern);
+ sbjname = mapPattern(request, pattern);
+ CMS.debug("nsHKeySubjectNameDefault: getSubjectName(): subject name mapping done");
+ }
- return sbjname;
- }
+ return sbjname;
+ }
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/nsNKeySubjectNameDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/nsNKeySubjectNameDefault.java
index 3a1d1c6e..13e766fa 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/nsNKeySubjectNameDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/nsNKeySubjectNameDefault.java
@@ -42,16 +42,15 @@ import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
/**
- * This class implements an enrollment default policy
- * that populates server-side configurable subject name
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates server-side
+ * configurable subject name into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class nsNKeySubjectNameDefault extends EnrollDefault {
- public static final String PROP_LDAP = "ldap";
- public static final String PROP_PARAMS = "params";
+ public static final String PROP_LDAP = "ldap";
+ public static final String PROP_PARAMS = "params";
public static final String CONFIG_DNPATTERN = "dnpattern";
public static final String CONFIG_LDAP_STRING_ATTRS = "ldapStringAttributes";
public static final String CONFIG_LDAP_HOST = "ldap.ldapconn.host";
@@ -64,130 +63,132 @@ public class nsNKeySubjectNameDefault extends EnrollDefault {
public static final String VAL_NAME = "name";
- public static final String CONFIG_LDAP_VERS =
- "2,3";
+ public static final String CONFIG_LDAP_VERS =
+ "2,3";
/* default dn pattern if left blank or not set in the config */
- protected static String DEFAULT_DNPATTERN =
- "CN=$request.aoluid$, E=$request.mail$";
+ protected static String DEFAULT_DNPATTERN =
+ "CN=$request.aoluid$, E=$request.mail$";
/* ldap configuration sub-store */
- boolean mInitialized = false;
+ boolean mInitialized = false;
protected IConfigStore mInstConfig;
protected IConfigStore mLdapConfig;
protected IConfigStore mParamsConfig;
- /* ldap base dn */
+ /* ldap base dn */
protected String mBaseDN = null;
/* factory of anonymous ldap connections */
protected ILdapConnFactory mConnFactory = null;
- /* the list of LDAP attributes with string values to retrieve to
- * form the subject dn. */
+ /*
+ * the list of LDAP attributes with string values to retrieve to form the
+ * subject dn.
+ */
protected String[] mLdapStringAttrs = null;
public nsNKeySubjectNameDefault() {
super();
addConfigName(CONFIG_DNPATTERN);
- addConfigName(CONFIG_LDAP_STRING_ATTRS);
+ addConfigName(CONFIG_LDAP_STRING_ATTRS);
addConfigName(CONFIG_LDAP_HOST);
addConfigName(CONFIG_LDAP_PORT);
addConfigName(CONFIG_LDAP_SEC_CONN);
addConfigName(CONFIG_LDAP_VER);
addConfigName(CONFIG_LDAP_BASEDN);
- addConfigName(CONFIG_LDAP_MIN_CONN);
- addConfigName(CONFIG_LDAP_MAX_CONN);
+ addConfigName(CONFIG_LDAP_MIN_CONN);
+ addConfigName(CONFIG_LDAP_MAX_CONN);
addValueName(CONFIG_DNPATTERN);
- addValueName(CONFIG_LDAP_STRING_ATTRS);
+ addValueName(CONFIG_LDAP_STRING_ATTRS);
addValueName(CONFIG_LDAP_HOST);
addValueName(CONFIG_LDAP_PORT);
addValueName(CONFIG_LDAP_SEC_CONN);
addValueName(CONFIG_LDAP_VER);
addValueName(CONFIG_LDAP_BASEDN);
- addValueName(CONFIG_LDAP_MIN_CONN);
- addValueName(CONFIG_LDAP_MAX_CONN);
+ addValueName(CONFIG_LDAP_MIN_CONN);
+ addValueName(CONFIG_LDAP_MAX_CONN);
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
- mInstConfig = config;
+ throws EProfileException {
+ mInstConfig = config;
super.init(profile, config);
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
- CMS.debug("nsNKeySubjectNameDefault: in getConfigDescriptor, name="+ name);
- if (name.equals(CONFIG_DNPATTERN)) {
- return new Descriptor(IDescriptor.STRING,
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ CMS.debug("nsNKeySubjectNameDefault: in getConfigDescriptor, name=" + name);
+ if (name.equals(CONFIG_DNPATTERN)) {
+ return new Descriptor(IDescriptor.STRING,
null, null, CMS.getUserMessage(locale,
- "CMS_PROFILE_SUBJECT_NAME"));
- } else if (name.equals(CONFIG_LDAP_STRING_ATTRS)) {
- return new Descriptor(IDescriptor.STRING,
- null,
- null,
- CMS.getUserMessage(locale,"CMS_PROFILE_NSNKEY_LDAP_STRING_ATTRS"));
- } else if (name.equals(CONFIG_LDAP_HOST)) {
- return new Descriptor(IDescriptor.STRING,
- null,
- null,
- CMS.getUserMessage(locale,"CMS_PROFILE_NSNKEY_HOST_NAME"));
- } else if (name.equals(CONFIG_LDAP_PORT)) {
- return new Descriptor(IDescriptor.STRING,
- null,
- null,
- CMS.getUserMessage(locale,"CMS_PROFILE_NSNKEY_PORT_NUMBER"));
- } else if (name.equals(CONFIG_LDAP_SEC_CONN)) {
+ "CMS_PROFILE_SUBJECT_NAME"));
+ } else if (name.equals(CONFIG_LDAP_STRING_ATTRS)) {
+ return new Descriptor(IDescriptor.STRING,
+ null,
+ null,
+ CMS.getUserMessage(locale, "CMS_PROFILE_NSNKEY_LDAP_STRING_ATTRS"));
+ } else if (name.equals(CONFIG_LDAP_HOST)) {
+ return new Descriptor(IDescriptor.STRING,
+ null,
+ null,
+ CMS.getUserMessage(locale, "CMS_PROFILE_NSNKEY_HOST_NAME"));
+ } else if (name.equals(CONFIG_LDAP_PORT)) {
+ return new Descriptor(IDescriptor.STRING,
+ null,
+ null,
+ CMS.getUserMessage(locale, "CMS_PROFILE_NSNKEY_PORT_NUMBER"));
+ } else if (name.equals(CONFIG_LDAP_SEC_CONN)) {
return new Descriptor(IDescriptor.BOOLEAN,
- null,
- "false",
- CMS.getUserMessage(locale, "CMS_PROFILE_NSNKEY_SECURE_CONN"));
- } else if (name.equals(CONFIG_LDAP_VER)) {
+ null,
+ "false",
+ CMS.getUserMessage(locale, "CMS_PROFILE_NSNKEY_SECURE_CONN"));
+ } else if (name.equals(CONFIG_LDAP_VER)) {
return new Descriptor(IDescriptor.CHOICE, CONFIG_LDAP_VERS,
"3",
CMS.getUserMessage(locale, "CMS_PROFILE_NSNKEY_LDAP_VERSION"));
- } else if (name.equals(CONFIG_LDAP_BASEDN)) {
- return new Descriptor(IDescriptor.STRING,
- null,
- null,
- CMS.getUserMessage(locale,"CMS_PROFILE_NSNKEY_BASEDN"));
- } else if (name.equals(CONFIG_LDAP_MIN_CONN)) {
- return new Descriptor(IDescriptor.STRING,
- null,
- null,
- CMS.getUserMessage(locale,"CMS_PROFILE_NSNKEY_LDAP_MIN_CONN"));
- } else if (name.equals(CONFIG_LDAP_MAX_CONN)) {
- return new Descriptor(IDescriptor.STRING,
- null,
- null,
- CMS.getUserMessage(locale,"CMS_PROFILE_NSNKEY_LDAP_MAX_CONN"));
+ } else if (name.equals(CONFIG_LDAP_BASEDN)) {
+ return new Descriptor(IDescriptor.STRING,
+ null,
+ null,
+ CMS.getUserMessage(locale, "CMS_PROFILE_NSNKEY_BASEDN"));
+ } else if (name.equals(CONFIG_LDAP_MIN_CONN)) {
+ return new Descriptor(IDescriptor.STRING,
+ null,
+ null,
+ CMS.getUserMessage(locale, "CMS_PROFILE_NSNKEY_LDAP_MIN_CONN"));
+ } else if (name.equals(CONFIG_LDAP_MAX_CONN)) {
+ return new Descriptor(IDescriptor.STRING,
+ null,
+ null,
+ CMS.getUserMessage(locale, "CMS_PROFILE_NSNKEY_LDAP_MAX_CONN"));
} else {
return null;
}
}
public IDescriptor getValueDescriptor(Locale locale, String name) {
- CMS.debug("nsNKeySubjectNameDefault: in getValueDescriptor name="+name);
+ CMS.debug("nsNKeySubjectNameDefault: in getValueDescriptor name=" + name);
if (name.equals(VAL_NAME)) {
return new Descriptor(IDescriptor.STRING,
- null,
- null,
- CMS.getUserMessage(locale,
- "CMS_PROFILE_SUBJECT_NAME"));
+ null,
+ null,
+ CMS.getUserMessage(locale,
+ "CMS_PROFILE_SUBJECT_NAME"));
} else {
return null;
}
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
- CMS.debug("nsNKeySubjectNameDefault: in setValue, value="+value);
+ CMS.debug("nsNKeySubjectNameDefault: in setValue, value=" + value);
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
if (name.equals(VAL_NAME)) {
@@ -201,26 +202,26 @@ public class nsNKeySubjectNameDefault extends EnrollDefault {
}
CMS.debug("nsNKeySubjectNameDefault: setValue name=" + x500name);
try {
- info.set(X509CertInfo.SUBJECT,
- new CertificateSubjectName(x500name));
+ info.set(X509CertInfo.SUBJECT,
+ new CertificateSubjectName(x500name));
} catch (Exception e) {
// failed to insert subject name
CMS.debug("nsNKeySubjectNameDefault: setValue " + e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
- CMS.debug("nsNKeySubjectNameDefault: in getValue, name="+name);
+ X509CertInfo info)
+ throws EPropertyException {
+ CMS.debug("nsNKeySubjectNameDefault: in getValue, name=" + name);
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
if (name.equals(VAL_NAME)) {
@@ -235,79 +236,80 @@ public class nsNKeySubjectNameDefault extends EnrollDefault {
} catch (Exception e) {
// nothing
CMS.debug("nsNKeySubjectNameDefault: getValue " + e.toString());
-
+
}
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
public String getText(Locale locale) {
- CMS.debug("nsNKeySubjectNameDefault: in getText");
- return CMS.getUserMessage(locale, "CMS_PROFILE_SUBJECT_NAME",
+ CMS.debug("nsNKeySubjectNameDefault: in getText");
+ return CMS.getUserMessage(locale, "CMS_PROFILE_SUBJECT_NAME",
getConfig(CONFIG_DNPATTERN));
}
- public void ldapInit()
- throws EProfileException {
- if (mInitialized == true) return;
-
- CMS.debug("nsNKeySubjectNameDefault: ldapInit(): begin");
-
- try {
- // cfu - XXX do more error handling here later
- /* initialize ldap server configuration */
- mParamsConfig = mInstConfig.getSubStore(PROP_PARAMS);
- mLdapConfig = mParamsConfig.getSubStore(PROP_LDAP);
- mBaseDN = mParamsConfig.getString(CONFIG_LDAP_BASEDN, null);
- mConnFactory = CMS.getLdapAnonConnFactory();
- mConnFactory.init(mLdapConfig);
-
- /* initialize dn pattern */
- String pattern = mParamsConfig.getString(CONFIG_DNPATTERN, null);
-
- if (pattern == null || pattern.length() == 0)
- pattern = DEFAULT_DNPATTERN;
-
- /* initialize ldap string attribute list */
- String ldapStringAttrs = mParamsConfig.getString(CONFIG_LDAP_STRING_ATTRS, null);
-
- if ((ldapStringAttrs != null) && (ldapStringAttrs.length() != 0)) {
- StringTokenizer pAttrs =
- new StringTokenizer(ldapStringAttrs, ",", false);
-
- mLdapStringAttrs = new String[pAttrs.countTokens()];
-
- for (int i = 0; i < mLdapStringAttrs.length; i++) {
- mLdapStringAttrs[i] = ((String) pAttrs.nextElement()).trim();
- }
- }
- CMS.debug("nsNKeySubjectNameDefault: ldapInit(): done");
- mInitialized = true;
- } catch (Exception e) {
- CMS.debug("nsNKeySubjectNameDefault: ldapInit(): "+e.toString());
- // throw EProfileException...
- throw new EProfileException("ldap init failure: "+e.toString());
- }
- }
+ public void ldapInit()
+ throws EProfileException {
+ if (mInitialized == true)
+ return;
+
+ CMS.debug("nsNKeySubjectNameDefault: ldapInit(): begin");
+
+ try {
+ // cfu - XXX do more error handling here later
+ /* initialize ldap server configuration */
+ mParamsConfig = mInstConfig.getSubStore(PROP_PARAMS);
+ mLdapConfig = mParamsConfig.getSubStore(PROP_LDAP);
+ mBaseDN = mParamsConfig.getString(CONFIG_LDAP_BASEDN, null);
+ mConnFactory = CMS.getLdapAnonConnFactory();
+ mConnFactory.init(mLdapConfig);
+
+ /* initialize dn pattern */
+ String pattern = mParamsConfig.getString(CONFIG_DNPATTERN, null);
+
+ if (pattern == null || pattern.length() == 0)
+ pattern = DEFAULT_DNPATTERN;
+
+ /* initialize ldap string attribute list */
+ String ldapStringAttrs = mParamsConfig.getString(CONFIG_LDAP_STRING_ATTRS, null);
+
+ if ((ldapStringAttrs != null) && (ldapStringAttrs.length() != 0)) {
+ StringTokenizer pAttrs =
+ new StringTokenizer(ldapStringAttrs, ",", false);
+
+ mLdapStringAttrs = new String[pAttrs.countTokens()];
+
+ for (int i = 0; i < mLdapStringAttrs.length; i++) {
+ mLdapStringAttrs[i] = ((String) pAttrs.nextElement()).trim();
+ }
+ }
+ CMS.debug("nsNKeySubjectNameDefault: ldapInit(): done");
+ mInitialized = true;
+ } catch (Exception e) {
+ CMS.debug("nsNKeySubjectNameDefault: ldapInit(): " + e.toString());
+ // throw EProfileException...
+ throw new EProfileException("ldap init failure: " + e.toString());
+ }
+ }
/**
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
X500Name name = null;
- CMS.debug("nsNKeySubjectNameDefault: in populate");
- ldapInit();
+ CMS.debug("nsNKeySubjectNameDefault: in populate");
+ ldapInit();
try {
- // cfu - this goes to ldap
- String subjectName = getSubjectName(request);
- CMS.debug("subjectName=" + subjectName);
- if (subjectName == null || subjectName.equals(""))
- return;
+ // cfu - this goes to ldap
+ String subjectName = getSubjectName(request);
+ CMS.debug("subjectName=" + subjectName);
+ if (subjectName == null || subjectName.equals(""))
+ return;
name = new X500Name(subjectName);
} catch (IOException e) {
@@ -318,55 +320,55 @@ public class nsNKeySubjectNameDefault extends EnrollDefault {
// failed to build x500 name
}
try {
- info.set(X509CertInfo.SUBJECT,
- new CertificateSubjectName(name));
+ info.set(X509CertInfo.SUBJECT,
+ new CertificateSubjectName(name));
} catch (Exception e) {
// failed to insert subject name
CMS.debug("nsNKeySubjectNameDefault: populate " + e.toString());
}
}
- private String getSubjectName(IRequest request)
- throws EProfileException, IOException {
+ private String getSubjectName(IRequest request)
+ throws EProfileException, IOException {
- CMS.debug("nsNKeySubjectNameDefault: in getSubjectName");
+ CMS.debug("nsNKeySubjectNameDefault: in getSubjectName");
- String pattern = getConfig(CONFIG_DNPATTERN);
- if (pattern == null || pattern.equals("")) {
- pattern = " ";
- }
-
- LDAPConnection conn = null;
+ String pattern = getConfig(CONFIG_DNPATTERN);
+ if (pattern == null || pattern.equals("")) {
+ pattern = " ";
+ }
+
+ LDAPConnection conn = null;
String userdn = null;
- String sbjname = "";
- // get DN from ldap to fill request
- try {
- if (mConnFactory == null) {
+ String sbjname = "";
+ // get DN from ldap to fill request
+ try {
+ if (mConnFactory == null) {
conn = null;
CMS.debug("nsNKeySubjectNameDefault: getSubjectName(): no LDAP connection");
throw new EProfileException("no LDAP connection");
} else {
conn = mConnFactory.getConn();
- if( conn == null ) {
- CMS.debug( "nsNKeySubjectNameDefault::getSubjectName() - " +
- "no LDAP connection" );
- throw new EProfileException( "no LDAP connection" );
+ if (conn == null) {
+ CMS.debug("nsNKeySubjectNameDefault::getSubjectName() - " +
+ "no LDAP connection");
+ throw new EProfileException("no LDAP connection");
}
CMS.debug("nsNKeySubjectNameDefault: getSubjectName(): got LDAP connection");
}
- if (request != null) {
- CMS.debug("pattern = "+pattern);
- sbjname = mapPattern(request, pattern);
- CMS.debug("nsNKeySubjectNameDefault: getSubjectName(): subject name mapping done");
- } else {
- CMS.debug( "nsNKeySubjectNameDefault::getSubjectName() - " +
- "request is null!" );
- throw new EProfileException( "request is null" );
- }
- // retrieve the attributes
+ if (request != null) {
+ CMS.debug("pattern = " + pattern);
+ sbjname = mapPattern(request, pattern);
+ CMS.debug("nsNKeySubjectNameDefault: getSubjectName(): subject name mapping done");
+ } else {
+ CMS.debug("nsNKeySubjectNameDefault::getSubjectName() - " +
+ "request is null!");
+ throw new EProfileException("request is null");
+ }
+ // retrieve the attributes
// get user dn.
- CMS.debug("nsNKeySubjectNameDefault: getSubjectName(): about to search with basedn = "+ mBaseDN);
+ CMS.debug("nsNKeySubjectNameDefault: getSubjectName(): about to search with basedn = " + mBaseDN);
LDAPSearchResults res = conn.search(mBaseDN,
LDAPv2.SCOPE_SUB, "(aoluid=" + request.getExtDataInString("aoluid") + ")", null, false);
@@ -378,42 +380,43 @@ public class nsNKeySubjectNameDefault extends EnrollDefault {
CMS.debug("nsNKeySubjectNameDefault: getSubjectName(): screen name does not exist");
throw new EProfileException("screenname does not exist");
}
- CMS.debug("nsNKeySubjectNameDefault: getSubjectName(): retrieved entry for aoluid = "+request.getExtDataInString("aoluid"));;
-
- LDAPEntry entry = null;
- CMS.debug("nsNKeySubjectNameDefault: getSubjectName(): about to search with "+ mLdapStringAttrs.length +" attributes");
- LDAPSearchResults results =
- conn.search(userdn, LDAPv2.SCOPE_BASE, "objectclass=*",
- mLdapStringAttrs, false);
-
- if (!results.hasMoreElements()) {
- CMS.debug("nsNKeySubjectNameDefault: getSubjectName(): no attributes");
- throw new EProfileException("no ldap attributes found");
- }
- entry = results.next();
- // set attrs into request
+ CMS.debug("nsNKeySubjectNameDefault: getSubjectName(): retrieved entry for aoluid = " + request.getExtDataInString("aoluid"));
+ ;
+
+ LDAPEntry entry = null;
+ CMS.debug("nsNKeySubjectNameDefault: getSubjectName(): about to search with " + mLdapStringAttrs.length + " attributes");
+ LDAPSearchResults results =
+ conn.search(userdn, LDAPv2.SCOPE_BASE, "objectclass=*",
+ mLdapStringAttrs, false);
+
+ if (!results.hasMoreElements()) {
+ CMS.debug("nsNKeySubjectNameDefault: getSubjectName(): no attributes");
+ throw new EProfileException("no ldap attributes found");
+ }
+ entry = results.next();
+ // set attrs into request
for (int i = 0; i < mLdapStringAttrs.length; i++) {
- LDAPAttribute la =
- entry.getAttribute(mLdapStringAttrs[i]);
- if (la != null) {
- String[] sla = la.getStringValueArray();
- CMS.debug("nsNKeySubjectNameDefault: getSubjectName(): got attribute: "+sla[0]);
- request.setExtData(mLdapStringAttrs[i], sla[0]);
- }
+ LDAPAttribute la =
+ entry.getAttribute(mLdapStringAttrs[i]);
+ if (la != null) {
+ String[] sla = la.getStringValueArray();
+ CMS.debug("nsNKeySubjectNameDefault: getSubjectName(): got attribute: " + sla[0]);
+ request.setExtData(mLdapStringAttrs[i], sla[0]);
+ }
}
- CMS.debug("nsNKeySubjectNameDefault: getSubjectName(): attributes set in request");
- } catch (Exception e) {
- CMS.debug("nsNKeySubjectNameDefault: getSubjectName(): "+e.toString());
- throw new EProfileException("getSubjectName() failure: "+e.toString());
- } finally {
- try {
- if (conn != null)
- mConnFactory.returnConn(conn);
- } catch (Exception e) {
- throw new EProfileException("nsNKeySubjectNameDefault: getSubjectName(): connection return failure");
- }
- }
- return sbjname;
-
- }
+ CMS.debug("nsNKeySubjectNameDefault: getSubjectName(): attributes set in request");
+ } catch (Exception e) {
+ CMS.debug("nsNKeySubjectNameDefault: getSubjectName(): " + e.toString());
+ throw new EProfileException("getSubjectName() failure: " + e.toString());
+ } finally {
+ try {
+ if (conn != null)
+ mConnFactory.returnConn(conn);
+ } catch (Exception e) {
+ throw new EProfileException("nsNKeySubjectNameDefault: getSubjectName(): connection return failure");
+ }
+ }
+ return sbjname;
+
+ }
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/nsTokenDeviceKeySubjectNameDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/nsTokenDeviceKeySubjectNameDefault.java
index 030470b3..31744c59 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/nsTokenDeviceKeySubjectNameDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/nsTokenDeviceKeySubjectNameDefault.java
@@ -34,10 +34,9 @@ import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
/**
- * This class implements an enrollment default policy
- * that populates server-side configurable subject name
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates server-side
+ * configurable subject name into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class nsTokenDeviceKeySubjectNameDefault extends EnrollDefault {
@@ -49,7 +48,7 @@ public class nsTokenDeviceKeySubjectNameDefault extends EnrollDefault {
/* default dn pattern if left blank or not set in the config */
protected static String DEFAULT_DNPATTERN =
- "Token Key Device - $request.tokencuid$";
+ "Token Key Device - $request.tokencuid$";
protected IConfigStore mParamsConfig;
@@ -61,43 +60,43 @@ public class nsTokenDeviceKeySubjectNameDefault extends EnrollDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
- CMS.debug("nsTokenDeviceKeySubjectNameDefault: in getConfigDescriptor, name="+ name);
- if (name.equals(CONFIG_DNPATTERN)) {
- return new Descriptor(IDescriptor.STRING,
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ CMS.debug("nsTokenDeviceKeySubjectNameDefault: in getConfigDescriptor, name=" + name);
+ if (name.equals(CONFIG_DNPATTERN)) {
+ return new Descriptor(IDescriptor.STRING,
null, null, CMS.getUserMessage(locale,
- "CMS_PROFILE_SUBJECT_NAME"));
+ "CMS_PROFILE_SUBJECT_NAME"));
} else {
return null;
}
}
public IDescriptor getValueDescriptor(Locale locale, String name) {
- CMS.debug("nsTokenDeviceKeySubjectNameDefault: in getValueDescriptor name="+name);
+ CMS.debug("nsTokenDeviceKeySubjectNameDefault: in getValueDescriptor name=" + name);
if (name.equals(VAL_NAME)) {
return new Descriptor(IDescriptor.STRING,
- null,
- null,
- CMS.getUserMessage(locale,
- "CMS_PROFILE_SUBJECT_NAME"));
+ null,
+ null,
+ CMS.getUserMessage(locale,
+ "CMS_PROFILE_SUBJECT_NAME"));
} else {
return null;
}
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
- CMS.debug("nsTokenDeviceKeySubjectNameDefault: in setValue, value="+value);
+ CMS.debug("nsTokenDeviceKeySubjectNameDefault: in setValue, value=" + value);
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
if (name.equals(VAL_NAME)) {
@@ -111,27 +110,26 @@ public class nsTokenDeviceKeySubjectNameDefault extends EnrollDefault {
}
CMS.debug("nsTokenDeviceKeySubjectNameDefault: setValue name=" + x500name);
try {
- info.set(X509CertInfo.SUBJECT,
- new CertificateSubjectName(x500name));
+ info.set(X509CertInfo.SUBJECT,
+ new CertificateSubjectName(x500name));
} catch (Exception e) {
// failed to insert subject name
CMS.debug("nsTokenDeviceKeySubjectNameDefault: setValue " + e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException
- {
- CMS.debug("nsTokenDeviceKeySubjectNameDefault: in getValue, name="+name);
+ X509CertInfo info)
+ throws EPropertyException {
+ CMS.debug("nsTokenDeviceKeySubjectNameDefault: in getValue, name=" + name);
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
if (name.equals(VAL_NAME)) {
@@ -146,19 +144,19 @@ public class nsTokenDeviceKeySubjectNameDefault extends EnrollDefault {
} catch (Exception e) {
// nothing
CMS.debug("nsTokenDeviceKeySubjectNameDefault: getValue " + e.toString());
-
+
}
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
public String getText(Locale locale) {
- CMS.debug("nsTokenDeviceKeySubjectNameDefault: in getText");
- return CMS.getUserMessage(locale, "CMS_PROFILE_SUBJECT_NAME",
+ CMS.debug("nsTokenDeviceKeySubjectNameDefault: in getText");
+ return CMS.getUserMessage(locale, "CMS_PROFILE_SUBJECT_NAME",
getConfig(CONFIG_DNPATTERN));
}
@@ -166,15 +164,15 @@ public class nsTokenDeviceKeySubjectNameDefault extends EnrollDefault {
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
X500Name name = null;
- CMS.debug("nsTokenDeviceKeySubjectNameDefault: in populate");
+ CMS.debug("nsTokenDeviceKeySubjectNameDefault: in populate");
try {
- String subjectName = getSubjectName(request);
+ String subjectName = getSubjectName(request);
CMS.debug("subjectName=" + subjectName);
if (subjectName == null || subjectName.equals(""))
- return;
+ return;
name = new X500Name(subjectName);
} catch (IOException e) {
@@ -185,8 +183,8 @@ public class nsTokenDeviceKeySubjectNameDefault extends EnrollDefault {
// failed to build x500 name
}
try {
- info.set(X509CertInfo.SUBJECT,
- new CertificateSubjectName(name));
+ info.set(X509CertInfo.SUBJECT,
+ new CertificateSubjectName(name));
} catch (Exception e) {
// failed to insert subject name
CMS.debug("nsTokenDeviceKeySubjectNameDefault: populate " + e.toString());
@@ -194,23 +192,23 @@ public class nsTokenDeviceKeySubjectNameDefault extends EnrollDefault {
}
private String getSubjectName(IRequest request)
- throws EProfileException, IOException {
+ throws EProfileException, IOException {
- CMS.debug("nsTokenDeviceKeySubjectNameDefault: in getSubjectName");
+ CMS.debug("nsTokenDeviceKeySubjectNameDefault: in getSubjectName");
- String pattern = getConfig(CONFIG_DNPATTERN);
- if (pattern == null || pattern.equals("")) {
- pattern = " ";
- }
-
- String sbjname = "";
+ String pattern = getConfig(CONFIG_DNPATTERN);
+ if (pattern == null || pattern.equals("")) {
+ pattern = " ";
+ }
- if (request != null) {
- CMS.debug("pattern = "+pattern);
- sbjname = mapPattern(request, pattern);
- CMS.debug("nsTokenDeviceKeySubjectNameDefault: getSubjectName(): subject name mapping done");
- }
+ String sbjname = "";
+
+ if (request != null) {
+ CMS.debug("pattern = " + pattern);
+ sbjname = mapPattern(request, pattern);
+ CMS.debug("nsTokenDeviceKeySubjectNameDefault: getSubjectName(): subject name mapping done");
+ }
- return sbjname;
+ return sbjname;
}
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/def/nsTokenUserKeySubjectNameDefault.java b/pki/base/common/src/com/netscape/cms/profile/def/nsTokenUserKeySubjectNameDefault.java
index ac98a0cb..094317f9 100644
--- a/pki/base/common/src/com/netscape/cms/profile/def/nsTokenUserKeySubjectNameDefault.java
+++ b/pki/base/common/src/com/netscape/cms/profile/def/nsTokenUserKeySubjectNameDefault.java
@@ -42,10 +42,9 @@ import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
/**
- * This class implements an enrollment default policy
- * that populates server-side configurable subject name
- * into the certificate template.
- *
+ * This class implements an enrollment default policy that populates server-side
+ * configurable subject name into the certificate template.
+ *
* @version $Revision$, $Date$
*/
public class nsTokenUserKeySubjectNameDefault extends EnrollDefault {
@@ -66,12 +65,12 @@ public class nsTokenUserKeySubjectNameDefault extends EnrollDefault {
public static final String VAL_NAME = "name";
- public static final String CONFIG_LDAP_VERS =
- "2,3";
+ public static final String CONFIG_LDAP_VERS =
+ "2,3";
/* default dn pattern if left blank or not set in the config */
- protected static String DEFAULT_DNPATTERN =
- "CN=$request.uid$, E=$request.mail$";
+ protected static String DEFAULT_DNPATTERN =
+ "CN=$request.uid$, E=$request.mail$";
/* ldap configuration sub-store */
boolean mldapInitialized = false;
@@ -86,8 +85,10 @@ public class nsTokenUserKeySubjectNameDefault extends EnrollDefault {
/* factory of anonymous ldap connections */
protected ILdapConnFactory mConnFactory = null;
- /* the list of LDAP attributes with string values to retrieve to
- * form the subject dn. */
+ /*
+ * the list of LDAP attributes with string values to retrieve to form the
+ * subject dn.
+ */
protected String[] mLdapStringAttrs = null;
public nsTokenUserKeySubjectNameDefault() {
@@ -118,93 +119,93 @@ public class nsTokenUserKeySubjectNameDefault extends EnrollDefault {
}
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
mInstConfig = config;
super.init(profile, config);
}
- public IDescriptor getConfigDescriptor(Locale locale, String name) {
- CMS.debug("nsTokenUserKeySubjectNameDefault: in getConfigDescriptor, name="+ name);
- if (name.equals(CONFIG_DNPATTERN)) {
- return new Descriptor(IDescriptor.STRING,
+ public IDescriptor getConfigDescriptor(Locale locale, String name) {
+ CMS.debug("nsTokenUserKeySubjectNameDefault: in getConfigDescriptor, name=" + name);
+ if (name.equals(CONFIG_DNPATTERN)) {
+ return new Descriptor(IDescriptor.STRING,
null, null, CMS.getUserMessage(locale,
- "CMS_PROFILE_SUBJECT_NAME"));
+ "CMS_PROFILE_SUBJECT_NAME"));
} else if (name.equals(CONFIG_LDAP_STRING_ATTRS)) {
- return new Descriptor(IDescriptor.STRING,
- null,
- null,
- CMS.getUserMessage(locale,"CMS_PROFILE_TOKENKEY_LDAP_STRING_ATTRS"));
+ return new Descriptor(IDescriptor.STRING,
+ null,
+ null,
+ CMS.getUserMessage(locale, "CMS_PROFILE_TOKENKEY_LDAP_STRING_ATTRS"));
} else if (name.equals(CONFIG_LDAP_ENABLE)) {
- return new Descriptor(IDescriptor.STRING,
- null,
- null,
- CMS.getUserMessage(locale,"CMS_PROFILE_TOKENKEY_LDAP_ENABLE"));
+ return new Descriptor(IDescriptor.STRING,
+ null,
+ null,
+ CMS.getUserMessage(locale, "CMS_PROFILE_TOKENKEY_LDAP_ENABLE"));
} else if (name.equals(CONFIG_LDAP_SEARCH_NAME)) {
- return new Descriptor(IDescriptor.STRING,
- null,
- null,
- CMS.getUserMessage(locale,"CMS_PROFILE_TOKENKEY_LDAP_SEARCH_NAME"));
+ return new Descriptor(IDescriptor.STRING,
+ null,
+ null,
+ CMS.getUserMessage(locale, "CMS_PROFILE_TOKENKEY_LDAP_SEARCH_NAME"));
} else if (name.equals(CONFIG_LDAP_HOST)) {
- return new Descriptor(IDescriptor.STRING,
- null,
- null,
- CMS.getUserMessage(locale,"CMS_PROFILE_TOKENKEY_LDAP_HOST_NAME"));
+ return new Descriptor(IDescriptor.STRING,
+ null,
+ null,
+ CMS.getUserMessage(locale, "CMS_PROFILE_TOKENKEY_LDAP_HOST_NAME"));
} else if (name.equals(CONFIG_LDAP_PORT)) {
- return new Descriptor(IDescriptor.STRING,
- null,
- null,
- CMS.getUserMessage(locale,"CMS_PROFILE_TOKENKEY_LDAP_PORT_NUMBER"));
+ return new Descriptor(IDescriptor.STRING,
+ null,
+ null,
+ CMS.getUserMessage(locale, "CMS_PROFILE_TOKENKEY_LDAP_PORT_NUMBER"));
} else if (name.equals(CONFIG_LDAP_SEC_CONN)) {
return new Descriptor(IDescriptor.BOOLEAN,
- null,
- "false",
- CMS.getUserMessage(locale, "CMS_PROFILE_TOKENKEY_LDAP_SECURE_CONN"));
+ null,
+ "false",
+ CMS.getUserMessage(locale, "CMS_PROFILE_TOKENKEY_LDAP_SECURE_CONN"));
} else if (name.equals(CONFIG_LDAP_VER)) {
return new Descriptor(IDescriptor.CHOICE, CONFIG_LDAP_VERS,
"3",
CMS.getUserMessage(locale, "CMS_PROFILE_TOKENKEY_LDAP_VERSION"));
} else if (name.equals(CONFIG_LDAP_BASEDN)) {
- return new Descriptor(IDescriptor.STRING,
- null,
- null,
- CMS.getUserMessage(locale,"CMS_PROFILE_TOKENKEY_LDAP_BASEDN"));
+ return new Descriptor(IDescriptor.STRING,
+ null,
+ null,
+ CMS.getUserMessage(locale, "CMS_PROFILE_TOKENKEY_LDAP_BASEDN"));
} else if (name.equals(CONFIG_LDAP_MIN_CONN)) {
- return new Descriptor(IDescriptor.STRING,
- null,
- null,
- CMS.getUserMessage(locale,"CMS_PROFILE_TOKENKEY_LDAP_MIN_CONN"));
+ return new Descriptor(IDescriptor.STRING,
+ null,
+ null,
+ CMS.getUserMessage(locale, "CMS_PROFILE_TOKENKEY_LDAP_MIN_CONN"));
} else if (name.equals(CONFIG_LDAP_MAX_CONN)) {
- return new Descriptor(IDescriptor.STRING,
- null,
- null,
- CMS.getUserMessage(locale,"CMS_PROFILE_TOKENKEY_LDAP_MAX_CONN"));
+ return new Descriptor(IDescriptor.STRING,
+ null,
+ null,
+ CMS.getUserMessage(locale, "CMS_PROFILE_TOKENKEY_LDAP_MAX_CONN"));
} else {
return null;
}
}
public IDescriptor getValueDescriptor(Locale locale, String name) {
- CMS.debug("nsTokenUserKeySubjectNameDefault: in getValueDescriptor name="+name);
+ CMS.debug("nsTokenUserKeySubjectNameDefault: in getValueDescriptor name=" + name);
if (name.equals(VAL_NAME)) {
return new Descriptor(IDescriptor.STRING,
- null,
- null,
- CMS.getUserMessage(locale,
- "CMS_PROFILE_SUBJECT_NAME"));
+ null,
+ null,
+ CMS.getUserMessage(locale,
+ "CMS_PROFILE_SUBJECT_NAME"));
} else {
return null;
}
}
public void setValue(String name, Locale locale,
- X509CertInfo info, String value)
- throws EPropertyException {
+ X509CertInfo info, String value)
+ throws EPropertyException {
- CMS.debug("nsTokenUserKeySubjectNameDefault: in setValue, value="+value);
+ CMS.debug("nsTokenUserKeySubjectNameDefault: in setValue, value=" + value);
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
if (name.equals(VAL_NAME)) {
@@ -218,26 +219,26 @@ public class nsTokenUserKeySubjectNameDefault extends EnrollDefault {
}
CMS.debug("nsTokenUserKeySubjectNameDefault: setValue name=" + x500name);
try {
- info.set(X509CertInfo.SUBJECT,
- new CertificateSubjectName(x500name));
+ info.set(X509CertInfo.SUBJECT,
+ new CertificateSubjectName(x500name));
} catch (Exception e) {
// failed to insert subject name
CMS.debug("nsTokenUserKeySubjectNameDefault: setValue " + e.toString());
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
public String getValue(String name, Locale locale,
- X509CertInfo info)
- throws EPropertyException {
- CMS.debug("nsTokenUserKeySubjectNameDefault: in getValue, name="+name);
+ X509CertInfo info)
+ throws EPropertyException {
+ CMS.debug("nsTokenUserKeySubjectNameDefault: in getValue, name=" + name);
if (name == null) {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
if (name.equals(VAL_NAME)) {
@@ -254,76 +255,77 @@ public class nsTokenUserKeySubjectNameDefault extends EnrollDefault {
CMS.debug("nsTokenUserKeySubjectNameDefault: getValue " + e.toString());
}
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
} else {
- throw new EPropertyException(CMS.getUserMessage(
+ throw new EPropertyException(CMS.getUserMessage(
locale, "CMS_INVALID_PROPERTY", name));
}
}
public String getText(Locale locale) {
CMS.debug("nsTokenUserKeySubjectNameDefault: in getText");
- return CMS.getUserMessage(locale, "CMS_PROFILE_SUBJECT_NAME",
+ return CMS.getUserMessage(locale, "CMS_PROFILE_SUBJECT_NAME",
getConfig(CONFIG_DNPATTERN));
}
public void ldapInit()
- throws EProfileException {
- if (mldapInitialized == true) return;
+ throws EProfileException {
+ if (mldapInitialized == true)
+ return;
CMS.debug("nsTokenUserKeySubjectNameDefault: ldapInit(): begin");
try {
- // cfu - XXX do more error handling here later
- /* initialize ldap server configuration */
- mParamsConfig = mInstConfig.getSubStore(PROP_PARAMS);
- mLdapConfig = mParamsConfig.getSubStore(PROP_LDAP);
- mldapEnabled = mParamsConfig.getBoolean(CONFIG_LDAP_ENABLE,
- false);
- if (mldapEnabled == false)
- return;
+ // cfu - XXX do more error handling here later
+ /* initialize ldap server configuration */
+ mParamsConfig = mInstConfig.getSubStore(PROP_PARAMS);
+ mLdapConfig = mParamsConfig.getSubStore(PROP_LDAP);
+ mldapEnabled = mParamsConfig.getBoolean(CONFIG_LDAP_ENABLE,
+ false);
+ if (mldapEnabled == false)
+ return;
- mBaseDN = mParamsConfig.getString(CONFIG_LDAP_BASEDN, null);
- mConnFactory = CMS.getLdapAnonConnFactory();
- mConnFactory.init(mLdapConfig);
+ mBaseDN = mParamsConfig.getString(CONFIG_LDAP_BASEDN, null);
+ mConnFactory = CMS.getLdapAnonConnFactory();
+ mConnFactory.init(mLdapConfig);
- /* initialize dn pattern */
- String pattern = mParamsConfig.getString(CONFIG_DNPATTERN, null);
+ /* initialize dn pattern */
+ String pattern = mParamsConfig.getString(CONFIG_DNPATTERN, null);
- if (pattern == null || pattern.length() == 0)
- pattern = DEFAULT_DNPATTERN;
+ if (pattern == null || pattern.length() == 0)
+ pattern = DEFAULT_DNPATTERN;
- /* initialize ldap string attribute list */
- String ldapStringAttrs = mParamsConfig.getString(CONFIG_LDAP_STRING_ATTRS, null);
+ /* initialize ldap string attribute list */
+ String ldapStringAttrs = mParamsConfig.getString(CONFIG_LDAP_STRING_ATTRS, null);
- if ((ldapStringAttrs != null) && (ldapStringAttrs.length() != 0)) {
- StringTokenizer pAttrs =
- new StringTokenizer(ldapStringAttrs, ",", false);
+ if ((ldapStringAttrs != null) && (ldapStringAttrs.length() != 0)) {
+ StringTokenizer pAttrs =
+ new StringTokenizer(ldapStringAttrs, ",", false);
- mLdapStringAttrs = new String[pAttrs.countTokens()];
+ mLdapStringAttrs = new String[pAttrs.countTokens()];
- for (int i = 0; i < mLdapStringAttrs.length; i++) {
- mLdapStringAttrs[i] = ((String) pAttrs.nextElement()).trim();
+ for (int i = 0; i < mLdapStringAttrs.length; i++) {
+ mLdapStringAttrs[i] = ((String) pAttrs.nextElement()).trim();
+ }
}
- }
- CMS.debug("nsTokenUserKeySubjectNameDefault: ldapInit(): done");
- mldapInitialized = true;
+ CMS.debug("nsTokenUserKeySubjectNameDefault: ldapInit(): done");
+ mldapInitialized = true;
} catch (Exception e) {
- CMS.debug("nsTokenUserKeySubjectNameDefault: ldapInit(): "+e.toString());
- // throw EProfileException...
- throw new EProfileException("ldap init failure: "+e.toString());
+ CMS.debug("nsTokenUserKeySubjectNameDefault: ldapInit(): " + e.toString());
+ // throw EProfileException...
+ throw new EProfileException("ldap init failure: " + e.toString());
}
- }
+ }
/**
* Populates the request with this policy default.
*/
public void populate(IRequest request, X509CertInfo info)
- throws EProfileException {
+ throws EProfileException {
X500Name name = null;
CMS.debug("nsTokenUserKeySubjectNameDefault: in populate");
-ldapInit();
+ ldapInit();
try {
// cfu - this goes to ldap
String subjectName = getSubjectName(request);
@@ -340,8 +342,8 @@ ldapInit();
// failed to build x500 name
}
try {
- info.set(X509CertInfo.SUBJECT,
- new CertificateSubjectName(name));
+ info.set(X509CertInfo.SUBJECT,
+ new CertificateSubjectName(name));
} catch (Exception e) {
// failed to insert subject name
CMS.debug("nsTokenUserKeySubjectNameDefault: populate " + e.toString());
@@ -349,7 +351,7 @@ ldapInit();
}
private String getSubjectName(IRequest request)
- throws EProfileException, IOException {
+ throws EProfileException, IOException {
CMS.debug("nsTokenUserKeySubjectNameDefault: in getSubjectName");
@@ -360,10 +362,10 @@ ldapInit();
String sbjname = "";
if (mldapInitialized == false) {
- if (request != null) {
- CMS.debug("pattern = "+pattern);
- sbjname = mapPattern(request, pattern);
- CMS.debug("nsTokenUserKeySubjectNameDefault: getSubjectName(): subject name mapping done");
+ if (request != null) {
+ CMS.debug("pattern = " + pattern);
+ sbjname = mapPattern(request, pattern);
+ CMS.debug("nsTokenUserKeySubjectNameDefault: getSubjectName(): subject name mapping done");
}
return sbjname;
}
@@ -384,34 +386,34 @@ ldapInit();
throw new EProfileException("no LDAP connection");
} else {
conn = mConnFactory.getConn();
- if( conn == null ) {
- CMS.debug( "nsTokenUserKeySubjectNameDefault::getSubjectName() - " +
- "no LDAP connection" );
- throw new EProfileException( "no LDAP connection" );
+ if (conn == null) {
+ CMS.debug("nsTokenUserKeySubjectNameDefault::getSubjectName() - " +
+ "no LDAP connection");
+ throw new EProfileException("no LDAP connection");
}
CMS.debug("nsTokenUserKeySubjectNameDefault: getSubjectName(): got LDAP connection");
}
// retrieve the attributes
// get user dn.
- CMS.debug("nsTokenUserKeySubjectNameDefault: getSubjectName(): about to search with basedn = "+ mBaseDN);
+ CMS.debug("nsTokenUserKeySubjectNameDefault: getSubjectName(): about to search with basedn = " + mBaseDN);
LDAPSearchResults res = conn.search(mBaseDN,
- LDAPv2.SCOPE_SUB, "("+ searchName + "=" + request.getExtDataInString("uid") + ")", null, false);
+ LDAPv2.SCOPE_SUB, "(" + searchName + "=" + request.getExtDataInString("uid") + ")", null, false);
if (res.hasMoreElements()) {
LDAPEntry entry = res.next();
userdn = entry.getDN();
} else {// put into property file later - cfu
- CMS.debug("nsTokenUserKeySubjectNameDefault: getSubjectName(): "+ searchName + " does not exist");
+ CMS.debug("nsTokenUserKeySubjectNameDefault: getSubjectName(): " + searchName + " does not exist");
throw new EProfileException("id does not exist");
}
- CMS.debug("nsTokenUserKeySubjectNameDefault: getSubjectName(): retrieved entry for "+searchName + " = "+request.getExtDataInString("uid"));
+ CMS.debug("nsTokenUserKeySubjectNameDefault: getSubjectName(): retrieved entry for " + searchName + " = " + request.getExtDataInString("uid"));
LDAPEntry entry = null;
- CMS.debug("nsTokenUserKeySubjectNameDefault: getSubjectName(): about to search with "+ mLdapStringAttrs.length +" attributes");
- LDAPSearchResults results =
- conn.search(userdn, LDAPv2.SCOPE_BASE, "objectclass=*",
- mLdapStringAttrs, false);
+ CMS.debug("nsTokenUserKeySubjectNameDefault: getSubjectName(): about to search with " + mLdapStringAttrs.length + " attributes");
+ LDAPSearchResults results =
+ conn.search(userdn, LDAPv2.SCOPE_BASE, "objectclass=*",
+ mLdapStringAttrs, false);
if (!results.hasMoreElements()) {
CMS.debug("nsTokenUserKeySubjectNameDefault: getSubjectName(): no attributes");
@@ -420,28 +422,28 @@ ldapInit();
entry = results.next();
// set attrs into request
for (int i = 0; i < mLdapStringAttrs.length; i++) {
- LDAPAttribute la =
- entry.getAttribute(mLdapStringAttrs[i]);
- if (la != null) {
- String[] sla = la.getStringValueArray();
- CMS.debug("nsTokenUserKeySubjectNameDefault: getSubjectName(): got attribute: "+mLdapStringAttrs[i]+
- "=" + escapeValueRfc1779(sla[0], false).toString());
- request.setExtData(mLdapStringAttrs[i], escapeValueRfc1779(sla[0], false).toString());
- }
+ LDAPAttribute la =
+ entry.getAttribute(mLdapStringAttrs[i]);
+ if (la != null) {
+ String[] sla = la.getStringValueArray();
+ CMS.debug("nsTokenUserKeySubjectNameDefault: getSubjectName(): got attribute: " + mLdapStringAttrs[i] +
+ "=" + escapeValueRfc1779(sla[0], false).toString());
+ request.setExtData(mLdapStringAttrs[i], escapeValueRfc1779(sla[0], false).toString());
+ }
}
- CMS.debug("pattern = "+pattern);
- sbjname = mapPattern(request, pattern);
- CMS.debug("nsTokenUserKeySubjectNameDefault: getSubjectName(): subject name mapping done");
+ CMS.debug("pattern = " + pattern);
+ sbjname = mapPattern(request, pattern);
+ CMS.debug("nsTokenUserKeySubjectNameDefault: getSubjectName(): subject name mapping done");
CMS.debug("nsTokenUserKeySubjectNameDefault: getSubjectName(): attributes set in request");
} catch (Exception e) {
- CMS.debug("nsTokenUserKeySubjectNameDefault: getSubjectName(): "+e.toString());
- throw new EProfileException("getSubjectName() failure: "+e.toString());
+ CMS.debug("nsTokenUserKeySubjectNameDefault: getSubjectName(): " + e.toString());
+ throw new EProfileException("getSubjectName() failure: " + e.toString());
} finally {
try {
if (conn != null)
mConnFactory.returnConn(conn);
- } catch (Exception e) {
+ } catch (Exception e) {
throw new EProfileException("nsTokenUserKeySubjectNameDefault: getSubjectName(): connection return failure");
}
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/input/CMCCertReqInput.java b/pki/base/common/src/com/netscape/cms/profile/input/CMCCertReqInput.java
index d067f1e6..db3821e5 100644
--- a/pki/base/common/src/com/netscape/cms/profile/input/CMCCertReqInput.java
+++ b/pki/base/common/src/com/netscape/cms/profile/input/CMCCertReqInput.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.input;
-
import java.util.Locale;
import netscape.security.x509.X509CertInfo;
@@ -35,23 +34,21 @@ import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
import com.netscape.cms.profile.common.EnrollProfile;
-
/**
- * This class implements the certificate request input.
- * This input populates 2 main fields to the enrollment page:
- * 1/ Certificate Request Type, 2/ Certificate Request
+ * This class implements the certificate request input. This input populates 2
+ * main fields to the enrollment page: 1/ Certificate Request Type, 2/
+ * Certificate Request
* <p>
*
- * This input usually is used by an enrollment profile for
- * certificate requests.
- *
+ * This input usually is used by an enrollment profile for certificate requests.
+ *
* @version $Revision$, $Date$
*/
-public class CMCCertReqInput extends EnrollInput implements IProfileInput {
- public static final String VAL_CERT_REQUEST_TYPE =
- EnrollProfile.CTX_CERT_REQUEST_TYPE;
+public class CMCCertReqInput extends EnrollInput implements IProfileInput {
+ public static final String VAL_CERT_REQUEST_TYPE =
+ EnrollProfile.CTX_CERT_REQUEST_TYPE;
public static final String VAL_CERT_REQUEST =
- EnrollProfile.CTX_CERT_REQUEST;
+ EnrollProfile.CTX_CERT_REQUEST;
public EnrollProfile mEnrollProfile = null;
@@ -63,7 +60,7 @@ public class CMCCertReqInput extends EnrollInput implements IProfileInput {
* Initializes this default policy.
*/
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
mEnrollProfile = (EnrollProfile) profile;
@@ -87,22 +84,22 @@ public class CMCCertReqInput extends EnrollInput implements IProfileInput {
* Populates the request with this policy default.
*/
public void populate(IProfileContext ctx, IRequest request)
- throws EProfileException {
+ throws EProfileException {
String cert_request = ctx.get(VAL_CERT_REQUEST);
X509CertInfo info =
- request.getExtDataInCertInfo(EnrollProfile.REQUEST_CERTINFO);
+ request.getExtDataInCertInfo(EnrollProfile.REQUEST_CERTINFO);
TaggedRequest msgs[] = mEnrollProfile.parseCMC(getLocale(request), cert_request);
if (msgs == null) {
- return;
+ return;
}
// This profile only handle the first request in CRMF
Integer seqNum = request.getExtDataInInteger(EnrollProfile.REQUEST_SEQ_NUM);
if (seqNum == null) {
- throw new EProfileException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_UNKNOWN_SEQ_NUM"));
+ throw new EProfileException(
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_UNKNOWN_SEQ_NUM"));
}
mEnrollProfile.fillTaggedRequest(getLocale(request), msgs[seqNum.intValue()], info, request);
@@ -110,16 +107,15 @@ public class CMCCertReqInput extends EnrollInput implements IProfileInput {
}
/**
- * Retrieves the descriptor of the given value
- * parameter by name.
+ * Retrieves the descriptor of the given value parameter by name.
*/
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_CERT_REQUEST)) {
return new Descriptor(IDescriptor.CERT_REQUEST, null,
null,
CMS.getUserMessage(locale,
- "CMS_PROFILE_INPUT_CERT_REQ"));
- }
+ "CMS_PROFILE_INPUT_CERT_REQ"));
+ }
return null;
}
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/input/CertReqInput.java b/pki/base/common/src/com/netscape/cms/profile/input/CertReqInput.java
index 12a4f549..044ba9fa 100644
--- a/pki/base/common/src/com/netscape/cms/profile/input/CertReqInput.java
+++ b/pki/base/common/src/com/netscape/cms/profile/input/CertReqInput.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.input;
-
import java.util.Locale;
import netscape.security.pkcs.PKCS10;
@@ -38,23 +37,21 @@ import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
import com.netscape.cms.profile.common.EnrollProfile;
-
/**
- * This class implements the certificate request input.
- * This input populates 2 main fields to the enrollment page:
- * 1/ Certificate Request Type, 2/ Certificate Request
+ * This class implements the certificate request input. This input populates 2
+ * main fields to the enrollment page: 1/ Certificate Request Type, 2/
+ * Certificate Request
* <p>
*
- * This input usually is used by an enrollment profile for
- * certificate requests.
- *
+ * This input usually is used by an enrollment profile for certificate requests.
+ *
* @version $Revision$, $Date$
*/
-public class CertReqInput extends EnrollInput implements IProfileInput {
- public static final String VAL_CERT_REQUEST_TYPE =
- EnrollProfile.CTX_CERT_REQUEST_TYPE;
+public class CertReqInput extends EnrollInput implements IProfileInput {
+ public static final String VAL_CERT_REQUEST_TYPE =
+ EnrollProfile.CTX_CERT_REQUEST_TYPE;
public static final String VAL_CERT_REQUEST =
- EnrollProfile.CTX_CERT_REQUEST;
+ EnrollProfile.CTX_CERT_REQUEST;
public EnrollProfile mEnrollProfile = null;
@@ -67,7 +64,7 @@ public class CertReqInput extends EnrollInput implements IProfileInput {
* Initializes this default policy.
*/
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
mEnrollProfile = (EnrollProfile) profile;
@@ -91,19 +88,19 @@ public class CertReqInput extends EnrollInput implements IProfileInput {
* Populates the request with this policy default.
*/
public void populate(IProfileContext ctx, IRequest request)
- throws EProfileException {
+ throws EProfileException {
String cert_request_type = ctx.get(VAL_CERT_REQUEST_TYPE);
String cert_request = ctx.get(VAL_CERT_REQUEST);
X509CertInfo info =
- request.getExtDataInCertInfo(EnrollProfile.REQUEST_CERTINFO);
+ request.getExtDataInCertInfo(EnrollProfile.REQUEST_CERTINFO);
if (cert_request_type == null) {
- CMS.debug("CertReqInput: populate - invalid cert request type " +
- "");
+ CMS.debug("CertReqInput: populate - invalid cert request type " +
+ "");
throw new EProfileException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_UNKNOWN_CERT_REQ_TYPE",
- ""));
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_UNKNOWN_CERT_REQ_TYPE",
+ ""));
}
if (cert_request_type.equals(EnrollProfile.REQ_TYPE_PKCS10)) {
@@ -114,7 +111,7 @@ public class CertReqInput extends EnrollInput implements IProfileInput {
getLocale(request), "CMS_PROFILE_NO_CERT_REQ"));
}
- mEnrollProfile.fillPKCS10(getLocale(request), pkcs10, info, request);
+ mEnrollProfile.fillPKCS10(getLocale(request), pkcs10, info, request);
} else if (cert_request_type.startsWith(EnrollProfile.REQ_TYPE_KEYGEN)) {
DerInputStream keygen = mEnrollProfile.parseKeyGen(getLocale(request), cert_request);
@@ -138,7 +135,7 @@ public class CertReqInput extends EnrollInput implements IProfileInput {
Integer seqNum = request.getExtDataInInteger(EnrollProfile.REQUEST_SEQ_NUM);
mEnrollProfile.fillCertReqMsg(getLocale(request), msgs[seqNum.intValue()], info, request
- );
+ );
} else if (cert_request_type.startsWith(EnrollProfile.REQ_TYPE_CMC)) {
TaggedRequest msgs[] = mEnrollProfile.parseCMC(getLocale(request), cert_request);
@@ -148,40 +145,39 @@ public class CertReqInput extends EnrollInput implements IProfileInput {
}
// This profile only handle the first request in CRMF
Integer seqNum = request.getExtDataInInteger(EnrollProfile.REQUEST_SEQ_NUM);
- if (seqNum == null) {
- throw new EProfileException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_UNKNOWN_SEQ_NUM"));
+ if (seqNum == null) {
+ throw new EProfileException(
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_UNKNOWN_SEQ_NUM"));
}
mEnrollProfile.fillTaggedRequest(getLocale(request), msgs[seqNum.intValue()], info, request);
} else {
// error
- CMS.debug("CertReqInput: populate - invalid cert request type " +
- cert_request_type);
+ CMS.debug("CertReqInput: populate - invalid cert request type " +
+ cert_request_type);
throw new EProfileException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_UNKNOWN_CERT_REQ_TYPE",
- cert_request_type));
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_UNKNOWN_CERT_REQ_TYPE",
+ cert_request_type));
}
request.setExtData(EnrollProfile.REQUEST_CERTINFO, info);
}
/**
- * Retrieves the descriptor of the given value
- * parameter by name.
+ * Retrieves the descriptor of the given value parameter by name.
*/
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_CERT_REQUEST_TYPE)) {
return new Descriptor(IDescriptor.CERT_REQUEST_TYPE, null,
null,
CMS.getUserMessage(locale,
- "CMS_PROFILE_INPUT_CERT_REQ_TYPE"));
+ "CMS_PROFILE_INPUT_CERT_REQ_TYPE"));
} else if (name.equals(VAL_CERT_REQUEST)) {
return new Descriptor(IDescriptor.CERT_REQUEST, null,
null,
CMS.getUserMessage(locale,
- "CMS_PROFILE_INPUT_CERT_REQ"));
+ "CMS_PROFILE_INPUT_CERT_REQ"));
}
return null;
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/input/DualKeyGenInput.java b/pki/base/common/src/com/netscape/cms/profile/input/DualKeyGenInput.java
index b887807c..b898043d 100644
--- a/pki/base/common/src/com/netscape/cms/profile/input/DualKeyGenInput.java
+++ b/pki/base/common/src/com/netscape/cms/profile/input/DualKeyGenInput.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.input;
-
import java.util.Locale;
import netscape.security.pkcs.PKCS10;
@@ -37,26 +36,23 @@ import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
import com.netscape.cms.profile.common.EnrollProfile;
-
/**
- * This class implements the dual key generation input.
- * This input populates parameters to the enrollment
- * pages so that a CRMF request containing 2 certificate
- * requests will be generated.
+ * This class implements the dual key generation input. This input populates
+ * parameters to the enrollment pages so that a CRMF request containing 2
+ * certificate requests will be generated.
* <p>
- *
- * This input can only be used with Netscape 7.x or later
- * clients.
+ *
+ * This input can only be used with Netscape 7.x or later clients.
* <p>
- *
+ *
* @version $Revision$, $Date$
*/
-public class DualKeyGenInput extends EnrollInput implements IProfileInput {
+public class DualKeyGenInput extends EnrollInput implements IProfileInput {
- public static final String VAL_KEYGEN_REQUEST_TYPE =
- EnrollProfile.CTX_CERT_REQUEST_TYPE;
- public static final String VAL_KEYGEN_REQUEST =
- EnrollProfile.CTX_CERT_REQUEST;
+ public static final String VAL_KEYGEN_REQUEST_TYPE =
+ EnrollProfile.CTX_CERT_REQUEST_TYPE;
+ public static final String VAL_KEYGEN_REQUEST =
+ EnrollProfile.CTX_CERT_REQUEST;
public EnrollProfile mEnrollProfile = null;
@@ -69,7 +65,7 @@ public class DualKeyGenInput extends EnrollInput implements IProfileInput {
* Initializes this default policy.
*/
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
mEnrollProfile = (EnrollProfile) profile;
}
@@ -92,29 +88,29 @@ public class DualKeyGenInput extends EnrollInput implements IProfileInput {
* Populates the request with this policy default.
*/
public void populate(IProfileContext ctx, IRequest request)
- throws EProfileException {
+ throws EProfileException {
String keygen_request_type = ctx.get(VAL_KEYGEN_REQUEST_TYPE);
String keygen_request = ctx.get(VAL_KEYGEN_REQUEST);
X509CertInfo info =
- request.getExtDataInCertInfo(EnrollProfile.REQUEST_CERTINFO);
+ request.getExtDataInCertInfo(EnrollProfile.REQUEST_CERTINFO);
if (keygen_request_type == null) {
CMS.debug("DualKeyGenInput: populate - invalid cert request type " +
- "");
+ "");
throw new EProfileException(
CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_UNKNOWN_CERT_REQ_TYPE",
- ""));
+ "CMS_PROFILE_UNKNOWN_CERT_REQ_TYPE",
+ ""));
}
if (keygen_request_type.startsWith("pkcs10")) {
PKCS10 pkcs10 = mEnrollProfile.parsePKCS10(getLocale(request), keygen_request);
- mEnrollProfile.fillPKCS10(getLocale(request), pkcs10, info, request);
+ mEnrollProfile.fillPKCS10(getLocale(request), pkcs10, info, request);
} else if (keygen_request_type.startsWith("keygen")) {
DerInputStream keygen = mEnrollProfile.parseKeyGen(getLocale(request), keygen_request);
- mEnrollProfile.fillKeyGen(getLocale(request), keygen, info, request);
+ mEnrollProfile.fillKeyGen(getLocale(request), keygen, info, request);
} else if (keygen_request_type.startsWith("crmf")) {
CertReqMsg msgs[] = mEnrollProfile.parseCRMF(getLocale(request), keygen_request);
@@ -128,28 +124,27 @@ public class DualKeyGenInput extends EnrollInput implements IProfileInput {
// This profile only handle the first request in CRMF
Integer seqNum = request.getExtDataInInteger(EnrollProfile.REQUEST_SEQ_NUM);
- if (seqNum == null) {
- throw new EProfileException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_UNKNOWN_SEQ_NUM"));
+ if (seqNum == null) {
+ throw new EProfileException(
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_UNKNOWN_SEQ_NUM"));
}
mEnrollProfile.fillCertReqMsg(getLocale(request), msgs[seqNum.intValue()], info, request);
} else {
// error
- CMS.debug("DualKeyGenInput: populate - " +
- "invalid cert request type " + keygen_request_type);
+ CMS.debug("DualKeyGenInput: populate - " +
+ "invalid cert request type " + keygen_request_type);
throw new EProfileException(CMS.getUserMessage(
- getLocale(request),
- "CMS_PROFILE_UNKNOWN_CERT_REQ_TYPE",
+ getLocale(request),
+ "CMS_PROFILE_UNKNOWN_CERT_REQ_TYPE",
keygen_request_type));
}
request.setExtData(EnrollProfile.REQUEST_CERTINFO, info);
}
/**
- * Retrieves the descriptor of the given value
- * parameter by name.
+ * Retrieves the descriptor of the given value parameter by name.
*/
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_KEYGEN_REQUEST_TYPE)) {
diff --git a/pki/base/common/src/com/netscape/cms/profile/input/EnrollInput.java b/pki/base/common/src/com/netscape/cms/profile/input/EnrollInput.java
index 1eaf476b..35e83a8d 100644
--- a/pki/base/common/src/com/netscape/cms/profile/input/EnrollInput.java
+++ b/pki/base/common/src/com/netscape/cms/profile/input/EnrollInput.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.input;
-
import java.util.Enumeration;
import java.util.Locale;
import java.util.Vector;
@@ -41,16 +40,15 @@ import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
import com.netscape.cms.profile.common.EnrollProfile;
-
/**
* This class implements the base enrollment input.
- *
+ *
* @version $Revision$, $Date$
*/
-public abstract class EnrollInput implements IProfileInput {
+public abstract class EnrollInput implements IProfileInput {
private final static String LOGGING_SIGNED_AUDIT_PROOF_OF_POSSESSION =
- "LOGGING_SIGNED_AUDIT_PROOF_OF_POSSESSION_2";
+ "LOGGING_SIGNED_AUDIT_PROOF_OF_POSSESSION_2";
protected IConfigStore mConfig = null;
protected Vector mValueNames = new Vector();
@@ -58,12 +56,12 @@ public abstract class EnrollInput implements IProfileInput {
protected IProfile mProfile = null;
protected ILogger mSignedAuditLogger = CMS.getSignedAuditLogger();
-
+
/**
* Initializes this default policy.
*/
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
mConfig = config;
mProfile = profile;
}
@@ -74,17 +72,17 @@ public abstract class EnrollInput implements IProfileInput {
/**
* Populates the request with this policy default.
- *
+ *
* @param ctx profile context
* @param request request
* @exception EProfileException failed to populate
*/
public abstract void populate(IProfileContext ctx, IRequest request)
- throws EProfileException;
+ throws EProfileException;
/**
* Retrieves the localizable name of this policy.
- *
+ *
* @param locale user locale
* @return localized input name
*/
@@ -92,23 +90,21 @@ public abstract class EnrollInput implements IProfileInput {
/**
* Retrieves the localizable description of this policy.
- *
+ *
* @param locale user locale
* @return localized input description
*/
public abstract String getText(Locale locale);
/**
- * Retrieves the descriptor of the given value
- * property by name.
- *
+ * Retrieves the descriptor of the given value property by name.
+ *
* @param locale user locale
* @param name property name
* @return descriptor of the property
*/
public abstract IDescriptor getValueDescriptor(Locale locale, String name);
-
public void addValueName(String name) {
mValueNames.addElement(name);
}
@@ -129,7 +125,7 @@ public abstract class EnrollInput implements IProfileInput {
}
public void setConfig(String name, String value)
- throws EPropertyException {
+ throws EPropertyException {
if (mConfig.getSubStore("params") == null) {
//
} else {
@@ -141,7 +137,7 @@ public abstract class EnrollInput implements IProfileInput {
try {
if (mConfig == null) {
return null;
- }
+ }
if (mConfig.getSubStore("params") != null) {
return mConfig.getSubStore("params").getString(name);
}
@@ -155,7 +151,7 @@ public abstract class EnrollInput implements IProfileInput {
}
public String getValue(String name, Locale locale, IRequest request)
- throws EProfileException {
+ throws EProfileException {
return request.getExtDataInString(name);
}
@@ -163,7 +159,7 @@ public abstract class EnrollInput implements IProfileInput {
* Sets the value of the given value parameter by name.
*/
public void setValue(String name, Locale locale, IRequest request,
- String value) throws EPropertyException {
+ String value) throws EPropertyException {
request.setExtData(name, value);
}
@@ -181,16 +177,16 @@ public abstract class EnrollInput implements IProfileInput {
return null;
}
- public void verifyPOP(Locale locale, CertReqMsg certReqMsg)
- throws EProfileException {
- CMS.debug("EnrollInput ::in verifyPOP");
+ public void verifyPOP(Locale locale, CertReqMsg certReqMsg)
+ throws EProfileException {
+ CMS.debug("EnrollInput ::in verifyPOP");
String auditMessage = null;
String auditSubjectID = auditSubjectID();
- if (!certReqMsg.hasPop()) {
+ if (!certReqMsg.hasPop()) {
CMS.debug("CertReqMsg has not POP, return");
- return;
+ return;
}
ProofOfPossession pop = certReqMsg.getPop();
ProofOfPossession.Type popType = pop.getType();
@@ -202,8 +198,8 @@ public abstract class EnrollInput implements IProfileInput {
try {
if (CMS.getConfigStore().getBoolean("cms.skipPOPVerify", false)) {
- CMS.debug("skipPOPVerify on, return");
- return;
+ CMS.debug("skipPOPVerify on, return");
+ return;
}
CMS.debug("POP verification begins:");
CryptoManager cm = CryptoManager.getInstance();
@@ -214,42 +210,42 @@ public abstract class EnrollInput implements IProfileInput {
CMS.debug("POP verification using internal token");
certReqMsg.verify();
} else {
- CMS.debug("POP verification using token:"+ tokenName);
+ CMS.debug("POP verification using token:" + tokenName);
verifyToken = cm.getTokenByName(tokenName);
certReqMsg.verify(verifyToken);
}
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_PROOF_OF_POSSESSION,
- auditSubjectID,
- ILogger.SUCCESS );
- audit( auditMessage );
+ LOGGING_SIGNED_AUDIT_PROOF_OF_POSSESSION,
+ auditSubjectID,
+ ILogger.SUCCESS);
+ audit(auditMessage);
} catch (Exception e) {
- CMS.debug("Failed POP verify! "+e.toString());
+ CMS.debug("Failed POP verify! " + e.toString());
CMS.debug(e);
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_PROOF_OF_POSSESSION,
- auditSubjectID,
- ILogger.FAILURE );
+ LOGGING_SIGNED_AUDIT_PROOF_OF_POSSESSION,
+ auditSubjectID,
+ ILogger.FAILURE);
- audit( auditMessage );
+ audit(auditMessage);
- throw new EProfileException(CMS.getUserMessage(locale,
+ throw new EProfileException(CMS.getUserMessage(locale,
"CMS_POP_VERIFICATION_ERROR"));
}
}
/**
* Signed Audit Log
- *
- * This method is inherited by all extended "CMSServlet"s,
- * and is called to store messages to the signed audit log.
+ *
+ * This method is inherited by all extended "CMSServlet"s, and is called to
+ * store messages to the signed audit log.
* <P>
- *
+ *
* @param msg signed audit log message
*/
protected void audit(String msg) {
@@ -261,20 +257,19 @@ public abstract class EnrollInput implements IProfileInput {
}
mSignedAuditLogger.log(ILogger.EV_SIGNED_AUDIT,
- null,
- ILogger.S_SIGNED_AUDIT,
- ILogger.LL_SECURITY,
- msg);
+ null,
+ ILogger.S_SIGNED_AUDIT,
+ ILogger.LL_SECURITY,
+ msg);
}
/**
* Signed Audit Log Subject ID
- *
- * This method is inherited by all extended "CMSServlet"s,
- * and is called to obtain the "SubjectID" for
- * a signed audit log message.
+ *
+ * This method is inherited by all extended "CMSServlet"s, and is called to
+ * obtain the "SubjectID" for a signed audit log message.
* <P>
- *
+ *
* @return id string containing the signed audit log message SubjectID
*/
protected String auditSubjectID() {
diff --git a/pki/base/common/src/com/netscape/cms/profile/input/FileSigningInput.java b/pki/base/common/src/com/netscape/cms/profile/input/FileSigningInput.java
index 70ede1e2..7e497c64 100644
--- a/pki/base/common/src/com/netscape/cms/profile/input/FileSigningInput.java
+++ b/pki/base/common/src/com/netscape/cms/profile/input/FileSigningInput.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.input;
-
import java.io.BufferedInputStream;
import java.net.URL;
import java.net.URLConnection;
@@ -34,15 +33,13 @@ import com.netscape.certsrv.property.Descriptor;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements the image
- * input that collects a picture.
+ * This class implements the image input that collects a picture.
* <p>
- *
+ *
* @version $Revision$, $Date$
*/
-public class FileSigningInput extends EnrollInput implements IProfileInput {
+public class FileSigningInput extends EnrollInput implements IProfileInput {
public static final String URL = "file_signing_url";
public static final String TEXT = "file_signing_text";
@@ -59,7 +56,7 @@ public class FileSigningInput extends EnrollInput implements IProfileInput {
* Initializes this default policy.
*/
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
@@ -77,13 +74,12 @@ public class FileSigningInput extends EnrollInput implements IProfileInput {
return CMS.getUserMessage(locale, "CMS_PROFILE_INPUT_FILE_SIGNING_TEXT");
}
- public String toHexString(byte data[])
- {
+ public String toHexString(byte data[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < data.length; i++) {
int v = data[i] & 0xff;
if (v <= 9) {
- sb.append("0");
+ sb.append("0");
}
sb.append(Integer.toHexString(v));
}
@@ -94,42 +90,41 @@ public class FileSigningInput extends EnrollInput implements IProfileInput {
* Populates the request with this policy default.
*/
public void populate(IProfileContext ctx, IRequest request)
- throws EProfileException {
+ throws EProfileException {
request.setExtData(TEXT, ctx.get(TEXT));
request.setExtData(URL, ctx.get(URL));
request.setExtData(DIGEST_TYPE, "SHA256");
-
+
try {
- // retrieve file and calculate the hash
- URL url = new URL(ctx.get(URL));
- URLConnection c = url.openConnection();
- c.setAllowUserInteraction(false);
- c.setDoInput(true);
- c.setDoOutput(false);
- c.setUseCaches(false);
- c.connect();
- int len = c.getContentLength();
- request.setExtData(SIZE, Integer.toString(len));
- BufferedInputStream is = new BufferedInputStream(c.getInputStream());
- byte data[] = new byte[len];
- is.read(data, 0, len);
- is.close();
+ // retrieve file and calculate the hash
+ URL url = new URL(ctx.get(URL));
+ URLConnection c = url.openConnection();
+ c.setAllowUserInteraction(false);
+ c.setDoInput(true);
+ c.setDoOutput(false);
+ c.setUseCaches(false);
+ c.connect();
+ int len = c.getContentLength();
+ request.setExtData(SIZE, Integer.toString(len));
+ BufferedInputStream is = new BufferedInputStream(c.getInputStream());
+ byte data[] = new byte[len];
+ is.read(data, 0, len);
+ is.close();
- // calculate digest
- MessageDigest digester = MessageDigest.getInstance("SHA256");
- byte digest[] = digester.digest(data);
- request.setExtData(DIGEST, toHexString(digest));
- } catch (Exception e) {
- CMS.debug("FileSigningInput populate failure " + e);
- throw new EProfileException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_FILE_NOT_FOUND"));
+ // calculate digest
+ MessageDigest digester = MessageDigest.getInstance("SHA256");
+ byte digest[] = digester.digest(data);
+ request.setExtData(DIGEST, toHexString(digest));
+ } catch (Exception e) {
+ CMS.debug("FileSigningInput populate failure " + e);
+ throw new EProfileException(
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_FILE_NOT_FOUND"));
}
}
/**
- * Retrieves the descriptor of the given value
- * parameter by name.
+ * Retrieves the descriptor of the given value parameter by name.
*/
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(URL)) {
diff --git a/pki/base/common/src/com/netscape/cms/profile/input/GenericInput.java b/pki/base/common/src/com/netscape/cms/profile/input/GenericInput.java
index 5aa85e0e..d9ce1487 100644
--- a/pki/base/common/src/com/netscape/cms/profile/input/GenericInput.java
+++ b/pki/base/common/src/com/netscape/cms/profile/input/GenericInput.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.input;
-
import java.util.Enumeration;
import java.util.Locale;
import java.util.Vector;
@@ -32,14 +31,13 @@ import com.netscape.certsrv.property.Descriptor;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
* This class implements a generic input.
* <p>
- *
+ *
* @version $Revision$, $Date$
*/
-public class GenericInput extends EnrollInput implements IProfileInput {
+public class GenericInput extends EnrollInput implements IProfileInput {
public static final String CONFIG_NUM = "gi_num";
public static final String CONFIG_DISPLAY_NAME = "gi_display_name";
@@ -49,12 +47,12 @@ public class GenericInput extends EnrollInput implements IProfileInput {
public static final int DEF_NUM = 5;
public GenericInput() {
- int num = getNum();
- for (int i = 0; i < num; i++) {
- addConfigName(CONFIG_PARAM_NAME + i);
- addConfigName(CONFIG_DISPLAY_NAME + i);
- addConfigName(CONFIG_ENABLE + i);
- }
+ int num = getNum();
+ for (int i = 0; i < num; i++) {
+ addConfigName(CONFIG_PARAM_NAME + i);
+ addConfigName(CONFIG_DISPLAY_NAME + i);
+ addConfigName(CONFIG_ENABLE + i);
+ }
}
protected int getNum() {
@@ -75,7 +73,7 @@ public class GenericInput extends EnrollInput implements IProfileInput {
* Initializes this default policy.
*/
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
@@ -97,65 +95,64 @@ public class GenericInput extends EnrollInput implements IProfileInput {
* Returns selected value names based on the configuration.
*/
public Enumeration getValueNames() {
- Vector v = new Vector();
- int num = getNum();
- for (int i = 0; i < num; i++) {
- String enable = getConfig(CONFIG_ENABLE + i);
- if (enable != null && enable.equals("true")) {
- v.addElement(getConfig(CONFIG_PARAM_NAME + i));
- }
- }
- return v.elements();
+ Vector v = new Vector();
+ int num = getNum();
+ for (int i = 0; i < num; i++) {
+ String enable = getConfig(CONFIG_ENABLE + i);
+ if (enable != null && enable.equals("true")) {
+ v.addElement(getConfig(CONFIG_PARAM_NAME + i));
+ }
+ }
+ return v.elements();
}
/**
* Populates the request with this policy default.
*/
public void populate(IProfileContext ctx, IRequest request)
- throws EProfileException {
+ throws EProfileException {
int num = getNum();
for (int i = 0; i < num; i++) {
- String enable = getConfig(CONFIG_ENABLE + i);
- if (enable != null && enable.equals("true")) {
+ String enable = getConfig(CONFIG_ENABLE + i);
+ if (enable != null && enable.equals("true")) {
String param = getConfig(CONFIG_PARAM_NAME + i);
request.setExtData(param, ctx.get(param));
- }
+ }
}
}
public IDescriptor getConfigDescriptor(Locale locale, String name) {
int num = getNum();
for (int i = 0; i < num; i++) {
- if (name.equals(CONFIG_PARAM_NAME + i)) {
- return new Descriptor(IDescriptor.STRING, null,
- null,
- CMS.getUserMessage(locale, "CMS_PROFILE_GI_PARAM_NAME") + i);
- } else if (name.equals(CONFIG_DISPLAY_NAME + i)) {
- return new Descriptor(IDescriptor.STRING, null,
- null,
- CMS.getUserMessage(locale, "CMS_PROFILE_GI_DISPLAY_NAME") + i);
- } else if (name.equals(CONFIG_ENABLE + i)) {
- return new Descriptor(IDescriptor.BOOLEAN, null,
- "false",
- CMS.getUserMessage(locale, "CMS_PROFILE_GI_ENABLE") + i);
- }
+ if (name.equals(CONFIG_PARAM_NAME + i)) {
+ return new Descriptor(IDescriptor.STRING, null,
+ null,
+ CMS.getUserMessage(locale, "CMS_PROFILE_GI_PARAM_NAME") + i);
+ } else if (name.equals(CONFIG_DISPLAY_NAME + i)) {
+ return new Descriptor(IDescriptor.STRING, null,
+ null,
+ CMS.getUserMessage(locale, "CMS_PROFILE_GI_DISPLAY_NAME") + i);
+ } else if (name.equals(CONFIG_ENABLE + i)) {
+ return new Descriptor(IDescriptor.BOOLEAN, null,
+ "false",
+ CMS.getUserMessage(locale, "CMS_PROFILE_GI_ENABLE") + i);
+ }
} // for
return null;
}
/**
- * Retrieves the descriptor of the given value
- * parameter by name.
+ * Retrieves the descriptor of the given value parameter by name.
*/
public IDescriptor getValueDescriptor(Locale locale, String name) {
int num = getNum();
for (int i = 0; i < num; i++) {
- String param = getConfig(CONFIG_PARAM_NAME + i);
- if (param != null && param.equals(name)) {
- return new Descriptor(IDescriptor.STRING, null,
- null,
- getConfig(CONFIG_DISPLAY_NAME + i));
- }
+ String param = getConfig(CONFIG_PARAM_NAME + i);
+ if (param != null && param.equals(name)) {
+ return new Descriptor(IDescriptor.STRING, null,
+ null,
+ getConfig(CONFIG_DISPLAY_NAME + i));
+ }
}
return null;
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/input/ImageInput.java b/pki/base/common/src/com/netscape/cms/profile/input/ImageInput.java
index 265b958d..9c8f73d7 100644
--- a/pki/base/common/src/com/netscape/cms/profile/input/ImageInput.java
+++ b/pki/base/common/src/com/netscape/cms/profile/input/ImageInput.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.input;
-
import java.util.Locale;
import com.netscape.certsrv.apps.CMS;
@@ -30,15 +29,13 @@ import com.netscape.certsrv.property.Descriptor;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements the image
- * input that collects a picture.
+ * This class implements the image input that collects a picture.
* <p>
- *
+ *
* @version $Revision$, $Date$
*/
-public class ImageInput extends EnrollInput implements IProfileInput {
+public class ImageInput extends EnrollInput implements IProfileInput {
public static final String IMAGE_URL = "image_url";
@@ -50,7 +47,7 @@ public class ImageInput extends EnrollInput implements IProfileInput {
* Initializes this default policy.
*/
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
@@ -72,13 +69,12 @@ public class ImageInput extends EnrollInput implements IProfileInput {
* Populates the request with this policy default.
*/
public void populate(IProfileContext ctx, IRequest request)
- throws EProfileException {
+ throws EProfileException {
request.setExtData(IMAGE_URL, ctx.get(IMAGE_URL));
}
/**
- * Retrieves the descriptor of the given value
- * parameter by name.
+ * Retrieves the descriptor of the given value parameter by name.
*/
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(IMAGE_URL)) {
diff --git a/pki/base/common/src/com/netscape/cms/profile/input/KeyGenInput.java b/pki/base/common/src/com/netscape/cms/profile/input/KeyGenInput.java
index 00c0ffcf..4d7a3090 100644
--- a/pki/base/common/src/com/netscape/cms/profile/input/KeyGenInput.java
+++ b/pki/base/common/src/com/netscape/cms/profile/input/KeyGenInput.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.input;
-
import java.util.Locale;
import netscape.security.pkcs.PKCS10;
@@ -38,25 +37,23 @@ import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
import com.netscape.cms.profile.common.EnrollProfile;
-
/**
- * This class implements the key generation input that
- * populates parameters to the enrollment page for
- * key generation.
+ * This class implements the key generation input that populates parameters to
+ * the enrollment page for key generation.
* <p>
- *
- * This input normally is used with user-based or
- * non certificate request profile.
+ *
+ * This input normally is used with user-based or non certificate request
+ * profile.
* <p>
- *
+ *
* @version $Revision$, $Date$
*/
-public class KeyGenInput extends EnrollInput implements IProfileInput {
+public class KeyGenInput extends EnrollInput implements IProfileInput {
- public static final String VAL_KEYGEN_REQUEST_TYPE =
- EnrollProfile.CTX_CERT_REQUEST_TYPE;
- public static final String VAL_KEYGEN_REQUEST =
- EnrollProfile.CTX_CERT_REQUEST;
+ public static final String VAL_KEYGEN_REQUEST_TYPE =
+ EnrollProfile.CTX_CERT_REQUEST_TYPE;
+ public static final String VAL_KEYGEN_REQUEST =
+ EnrollProfile.CTX_CERT_REQUEST;
public EnrollProfile mEnrollProfile = null;
@@ -69,7 +66,7 @@ public class KeyGenInput extends EnrollInput implements IProfileInput {
* Initializes this default policy.
*/
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
mEnrollProfile = (EnrollProfile) profile;
}
@@ -92,20 +89,20 @@ public class KeyGenInput extends EnrollInput implements IProfileInput {
* Populates the request with this policy default.
*/
public void populate(IProfileContext ctx, IRequest request)
- throws EProfileException {
+ throws EProfileException {
String keygen_request_type = ctx.get(VAL_KEYGEN_REQUEST_TYPE);
String keygen_request = ctx.get(VAL_KEYGEN_REQUEST);
X509CertInfo info =
- request.getExtDataInCertInfo(EnrollProfile.REQUEST_CERTINFO);
+ request.getExtDataInCertInfo(EnrollProfile.REQUEST_CERTINFO);
if (keygen_request_type == null) {
CMS.debug("KeyGenInput: populate - invalid cert request type " +
- "");
+ "");
throw new EProfileException(
CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_UNKNOWN_CERT_REQ_TYPE",
- ""));
+ "CMS_PROFILE_UNKNOWN_CERT_REQ_TYPE",
+ ""));
}
if (keygen_request_type.startsWith(EnrollProfile.REQ_TYPE_PKCS10)) {
PKCS10 pkcs10 = mEnrollProfile.parsePKCS10(getLocale(request), keygen_request);
@@ -115,7 +112,7 @@ public class KeyGenInput extends EnrollInput implements IProfileInput {
getLocale(request), "CMS_PROFILE_NO_CERT_REQ"));
}
- mEnrollProfile.fillPKCS10(getLocale(request), pkcs10, info, request);
+ mEnrollProfile.fillPKCS10(getLocale(request), pkcs10, info, request);
} else if (keygen_request_type.startsWith(EnrollProfile.REQ_TYPE_KEYGEN)) {
DerInputStream keygen = mEnrollProfile.parseKeyGen(getLocale(request), keygen_request);
@@ -124,7 +121,7 @@ public class KeyGenInput extends EnrollInput implements IProfileInput {
getLocale(request), "CMS_PROFILE_NO_CERT_REQ"));
}
- mEnrollProfile.fillKeyGen(getLocale(request), keygen, info, request);
+ mEnrollProfile.fillKeyGen(getLocale(request), keygen, info, request);
} else if (keygen_request_type.startsWith(EnrollProfile.REQ_TYPE_CRMF)) {
CertReqMsg msgs[] = mEnrollProfile.parseCRMF(getLocale(request), keygen_request);
@@ -149,17 +146,17 @@ public class KeyGenInput extends EnrollInput implements IProfileInput {
// This profile only handle the first request in CRMF
Integer seqNum = request.getExtDataInInteger(EnrollProfile.REQUEST_SEQ_NUM);
- if (seqNum == null) {
- throw new EProfileException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_UNKNOWN_SEQ_NUM"));
+ if (seqNum == null) {
+ throw new EProfileException(
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_UNKNOWN_SEQ_NUM"));
}
mEnrollProfile.fillTaggedRequest(getLocale(request), msgs[seqNum.intValue()], info, request);
} else {
// error
CMS.debug("DualKeyGenInput: populate - " +
- "invalid cert request type " + keygen_request_type);
+ "invalid cert request type " + keygen_request_type);
throw new EProfileException(CMS.getUserMessage(
getLocale(request),
"CMS_PROFILE_UNKNOWN_CERT_REQ_TYPE",
@@ -169,8 +166,7 @@ public class KeyGenInput extends EnrollInput implements IProfileInput {
}
/**
- * Retrieves the descriptor of the given value
- * parameter by name.
+ * Retrieves the descriptor of the given value parameter by name.
*/
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_KEYGEN_REQUEST_TYPE)) {
diff --git a/pki/base/common/src/com/netscape/cms/profile/input/SerialNumRenewInput.java b/pki/base/common/src/com/netscape/cms/profile/input/SerialNumRenewInput.java
index dce75c15..870f75d2 100644
--- a/pki/base/common/src/com/netscape/cms/profile/input/SerialNumRenewInput.java
+++ b/pki/base/common/src/com/netscape/cms/profile/input/SerialNumRenewInput.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.input;
-
import java.util.Locale;
import com.netscape.certsrv.apps.CMS;
@@ -30,15 +29,13 @@ import com.netscape.certsrv.property.Descriptor;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements the serial number input
- * for renewal
+ * This class implements the serial number input for renewal
* <p>
- *
- * @author Christina Fu
+ *
+ * @author Christina Fu
*/
-public class SerialNumRenewInput extends EnrollInput implements IProfileInput {
+public class SerialNumRenewInput extends EnrollInput implements IProfileInput {
public static final String SERIAL_NUM = "serial_num";
@@ -50,7 +47,7 @@ public class SerialNumRenewInput extends EnrollInput implements IProfileInput {
* Initializes this default policy.
*/
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
@@ -72,13 +69,12 @@ public class SerialNumRenewInput extends EnrollInput implements IProfileInput {
* Populates the request with this policy default.
*/
public void populate(IProfileContext ctx, IRequest request)
- throws EProfileException {
+ throws EProfileException {
//
}
/**
- * Retrieves the descriptor of the given value
- * parameter by name.
+ * Retrieves the descriptor of the given value parameter by name.
*/
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(SERIAL_NUM)) {
diff --git a/pki/base/common/src/com/netscape/cms/profile/input/SubjectDNInput.java b/pki/base/common/src/com/netscape/cms/profile/input/SubjectDNInput.java
index 4a8f6050..18f18fad 100644
--- a/pki/base/common/src/com/netscape/cms/profile/input/SubjectDNInput.java
+++ b/pki/base/common/src/com/netscape/cms/profile/input/SubjectDNInput.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.input;
-
import java.util.Enumeration;
import java.util.Locale;
import java.util.Vector;
@@ -37,11 +36,10 @@ import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
import com.netscape.cms.profile.common.EnrollProfile;
-
/**
* This plugin accepts subject DN from end user.
*/
-public class SubjectDNInput extends EnrollInput implements IProfileInput {
+public class SubjectDNInput extends EnrollInput implements IProfileInput {
public static final String VAL_SUBJECT = "subject";
@@ -52,7 +50,7 @@ public class SubjectDNInput extends EnrollInput implements IProfileInput {
* Initializes this default policy.
*/
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
@@ -70,37 +68,36 @@ public class SubjectDNInput extends EnrollInput implements IProfileInput {
return CMS.getUserMessage(locale, "CMS_PROFILE_INPUT_SUBJECT_NAME_TEXT");
}
-
public String getConfig(String name) {
- String config = super.getConfig(name);
- if (config == null || config.equals(""))
- return "true";
- return config;
+ String config = super.getConfig(name);
+ if (config == null || config.equals(""))
+ return "true";
+ return config;
}
/**
* Returns selected value names based on the configuration.
*/
public Enumeration<String> getValueNames() {
- Vector<String> v = new Vector<String>();
- v.addElement(VAL_SUBJECT);
- return v.elements();
+ Vector<String> v = new Vector<String>();
+ v.addElement(VAL_SUBJECT);
+ return v.elements();
}
/**
* Populates the request with this policy default.
*/
public void populate(IProfileContext ctx, IRequest request)
- throws EProfileException {
+ throws EProfileException {
X509CertInfo info =
- request.getExtDataInCertInfo(EnrollProfile.REQUEST_CERTINFO);
+ request.getExtDataInCertInfo(EnrollProfile.REQUEST_CERTINFO);
String subjectName = "";
subjectName = ctx.get(VAL_SUBJECT);
if (subjectName.equals("")) {
throw new EProfileException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_SUBJECT_NAME_NOT_FOUND"));
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_SUBJECT_NAME_NOT_FOUND"));
}
X500Name name = null;
@@ -108,10 +105,10 @@ public class SubjectDNInput extends EnrollInput implements IProfileInput {
name = new X500Name(subjectName);
} catch (Exception e) {
throw new EProfileException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_INVALID_SUBJECT_NAME", subjectName));
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_INVALID_SUBJECT_NAME", subjectName));
}
- parseSubjectName(name, info, request);
+ parseSubjectName(name, info, request);
request.setExtData(EnrollProfile.REQUEST_CERTINFO, info);
}
@@ -120,8 +117,7 @@ public class SubjectDNInput extends EnrollInput implements IProfileInput {
}
/**
- * Retrieves the descriptor of the given value
- * parameter by name.
+ * Retrieves the descriptor of the given value parameter by name.
*/
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_SUBJECT)) {
@@ -133,13 +129,13 @@ public class SubjectDNInput extends EnrollInput implements IProfileInput {
}
protected void parseSubjectName(X500Name subj, X509CertInfo info, IRequest req)
- throws EProfileException {
+ throws EProfileException {
try {
req.setExtData(EnrollProfile.REQUEST_SUBJECT_NAME,
new CertificateSubjectName(subj));
} catch (Exception e) {
- CMS.debug("SubjectNameInput: parseSubject Name " +
- e.toString());
+ CMS.debug("SubjectNameInput: parseSubject Name " +
+ e.toString());
}
}
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/input/SubjectNameInput.java b/pki/base/common/src/com/netscape/cms/profile/input/SubjectNameInput.java
index 15f906f9..5ada65c9 100644
--- a/pki/base/common/src/com/netscape/cms/profile/input/SubjectNameInput.java
+++ b/pki/base/common/src/com/netscape/cms/profile/input/SubjectNameInput.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.input;
-
import java.util.Enumeration;
import java.util.Locale;
import java.util.Vector;
@@ -37,20 +36,18 @@ import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
import com.netscape.cms.profile.common.EnrollProfile;
-
/**
- * This class implements the subject name input
- * that populates text fields to the enrollment
- * page so that distinguished name parameters
- * can be collected from the user.
+ * This class implements the subject name input that populates text fields to
+ * the enrollment page so that distinguished name parameters can be collected
+ * from the user.
* <p>
- * The collected parameters could be used for
- * fomulating the subject name in the certificate.
+ * The collected parameters could be used for fomulating the subject name in the
+ * certificate.
* <p>
- *
+ *
* @version $Revision$, $Date$
*/
-public class SubjectNameInput extends EnrollInput implements IProfileInput {
+public class SubjectNameInput extends EnrollInput implements IProfileInput {
public static final String CONFIG_UID = "sn_uid";
public static final String CONFIG_EMAIL = "sn_e";
@@ -88,7 +85,7 @@ public class SubjectNameInput extends EnrollInput implements IProfileInput {
* Initializes this default policy.
*/
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
@@ -106,101 +103,100 @@ public class SubjectNameInput extends EnrollInput implements IProfileInput {
return CMS.getUserMessage(locale, "CMS_PROFILE_INPUT_SUBJECT_NAME_TEXT");
}
-
public String getConfig(String name) {
- String config = super.getConfig(name);
- if (config == null || config.equals(""))
- return "true";
- return config;
+ String config = super.getConfig(name);
+ if (config == null || config.equals(""))
+ return "true";
+ return config;
}
/**
* Returns selected value names based on the configuration.
*/
public Enumeration getValueNames() {
- Vector v = new Vector();
- String c_uid = getConfig(CONFIG_UID);
- if (c_uid == null || c_uid.equals("")) {
- v.addElement(VAL_UID); // default case
- } else {
- if (c_uid.equals("true")) {
- v.addElement(VAL_UID);
- }
- }
- String c_email = getConfig(CONFIG_EMAIL);
- if (c_email == null || c_email.equals("")) {
- v.addElement(VAL_EMAIL);
- } else {
- if (c_email.equals("true")) {
- v.addElement(VAL_EMAIL);
- }
- }
- String c_cn = getConfig(CONFIG_CN);
- if (c_cn == null || c_cn.equals("")) {
- v.addElement(VAL_CN);
- } else {
- if (c_cn.equals("true")) {
- v.addElement(VAL_CN);
- }
- }
- String c_ou3 = getConfig(CONFIG_OU3);
- if (c_ou3 == null || c_ou3.equals("")) {
- v.addElement(VAL_OU3);
- } else {
- if (c_ou3.equals("true")) {
- v.addElement(VAL_OU3);
- }
- }
- String c_ou2 = getConfig(CONFIG_OU2);
- if (c_ou2 == null || c_ou2.equals("")) {
- v.addElement(VAL_OU2);
- } else {
- if (c_ou2.equals("true")) {
- v.addElement(VAL_OU2);
- }
- }
- String c_ou1 = getConfig(CONFIG_OU1);
- if (c_ou1 == null || c_ou1.equals("")) {
- v.addElement(VAL_OU1);
- } else {
- if (c_ou1.equals("true")) {
- v.addElement(VAL_OU1);
- }
- }
- String c_ou = getConfig(CONFIG_OU);
- if (c_ou == null || c_ou.equals("")) {
- v.addElement(VAL_OU);
- } else {
- if (c_ou.equals("true")) {
- v.addElement(VAL_OU);
- }
- }
- String c_o = getConfig(CONFIG_O);
- if (c_o == null || c_o.equals("")) {
- v.addElement(VAL_O);
- } else {
- if (c_o.equals("true")) {
- v.addElement(VAL_O);
- }
- }
- String c_c = getConfig(CONFIG_C);
- if (c_c == null || c_c.equals("")) {
- v.addElement(VAL_C);
- } else {
- if (c_c.equals("true")) {
- v.addElement(VAL_C);
- }
- }
- return v.elements();
+ Vector v = new Vector();
+ String c_uid = getConfig(CONFIG_UID);
+ if (c_uid == null || c_uid.equals("")) {
+ v.addElement(VAL_UID); // default case
+ } else {
+ if (c_uid.equals("true")) {
+ v.addElement(VAL_UID);
+ }
+ }
+ String c_email = getConfig(CONFIG_EMAIL);
+ if (c_email == null || c_email.equals("")) {
+ v.addElement(VAL_EMAIL);
+ } else {
+ if (c_email.equals("true")) {
+ v.addElement(VAL_EMAIL);
+ }
+ }
+ String c_cn = getConfig(CONFIG_CN);
+ if (c_cn == null || c_cn.equals("")) {
+ v.addElement(VAL_CN);
+ } else {
+ if (c_cn.equals("true")) {
+ v.addElement(VAL_CN);
+ }
+ }
+ String c_ou3 = getConfig(CONFIG_OU3);
+ if (c_ou3 == null || c_ou3.equals("")) {
+ v.addElement(VAL_OU3);
+ } else {
+ if (c_ou3.equals("true")) {
+ v.addElement(VAL_OU3);
+ }
+ }
+ String c_ou2 = getConfig(CONFIG_OU2);
+ if (c_ou2 == null || c_ou2.equals("")) {
+ v.addElement(VAL_OU2);
+ } else {
+ if (c_ou2.equals("true")) {
+ v.addElement(VAL_OU2);
+ }
+ }
+ String c_ou1 = getConfig(CONFIG_OU1);
+ if (c_ou1 == null || c_ou1.equals("")) {
+ v.addElement(VAL_OU1);
+ } else {
+ if (c_ou1.equals("true")) {
+ v.addElement(VAL_OU1);
+ }
+ }
+ String c_ou = getConfig(CONFIG_OU);
+ if (c_ou == null || c_ou.equals("")) {
+ v.addElement(VAL_OU);
+ } else {
+ if (c_ou.equals("true")) {
+ v.addElement(VAL_OU);
+ }
+ }
+ String c_o = getConfig(CONFIG_O);
+ if (c_o == null || c_o.equals("")) {
+ v.addElement(VAL_O);
+ } else {
+ if (c_o.equals("true")) {
+ v.addElement(VAL_O);
+ }
+ }
+ String c_c = getConfig(CONFIG_C);
+ if (c_c == null || c_c.equals("")) {
+ v.addElement(VAL_C);
+ } else {
+ if (c_c.equals("true")) {
+ v.addElement(VAL_C);
+ }
+ }
+ return v.elements();
}
/**
* Populates the request with this policy default.
*/
public void populate(IProfileContext ctx, IRequest request)
- throws EProfileException {
+ throws EProfileException {
X509CertInfo info =
- request.getExtDataInCertInfo(EnrollProfile.REQUEST_CERTINFO);
+ request.getExtDataInCertInfo(EnrollProfile.REQUEST_CERTINFO);
String subjectName = "";
String uid = ctx.get(VAL_UID);
@@ -270,8 +266,8 @@ public class SubjectNameInput extends EnrollInput implements IProfileInput {
}
if (subjectName.equals("")) {
throw new EProfileException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_SUBJECT_NAME_NOT_FOUND"));
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_SUBJECT_NAME_NOT_FOUND"));
}
X500Name name = null;
@@ -279,10 +275,10 @@ public class SubjectNameInput extends EnrollInput implements IProfileInput {
name = new X500Name(subjectName);
} catch (Exception e) {
throw new EProfileException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_INVALID_SUBJECT_NAME", subjectName));
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_INVALID_SUBJECT_NAME", subjectName));
}
- parseSubjectName(name, info, request);
+ parseSubjectName(name, info, request);
request.setExtData(EnrollProfile.REQUEST_CERTINFO, info);
}
@@ -329,8 +325,7 @@ public class SubjectNameInput extends EnrollInput implements IProfileInput {
}
/**
- * Retrieves the descriptor of the given value
- * parameter by name.
+ * Retrieves the descriptor of the given value parameter by name.
*/
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_UID)) {
@@ -374,13 +369,13 @@ public class SubjectNameInput extends EnrollInput implements IProfileInput {
}
protected void parseSubjectName(X500Name subj, X509CertInfo info, IRequest req)
- throws EProfileException {
+ throws EProfileException {
try {
req.setExtData(EnrollProfile.REQUEST_SUBJECT_NAME,
new CertificateSubjectName(subj));
} catch (Exception e) {
- CMS.debug("SubjectNameInput: parseSubject Name " +
- e.toString());
+ CMS.debug("SubjectNameInput: parseSubject Name " +
+ e.toString());
}
}
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/input/SubmitterInfoInput.java b/pki/base/common/src/com/netscape/cms/profile/input/SubmitterInfoInput.java
index 52df2d41..5d7be747 100644
--- a/pki/base/common/src/com/netscape/cms/profile/input/SubmitterInfoInput.java
+++ b/pki/base/common/src/com/netscape/cms/profile/input/SubmitterInfoInput.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.input;
-
import java.util.Locale;
import com.netscape.certsrv.apps.CMS;
@@ -30,16 +29,14 @@ import com.netscape.certsrv.property.Descriptor;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class implements the submitter information
- * input that collects certificate requestor's
- * information such as name, email and phone.
+ * This class implements the submitter information input that collects
+ * certificate requestor's information such as name, email and phone.
* <p>
- *
+ *
* @version $Revision$, $Date$
*/
-public class SubmitterInfoInput extends EnrollInput implements IProfileInput {
+public class SubmitterInfoInput extends EnrollInput implements IProfileInput {
public static final String NAME = "requestor_name";
public static final String EMAIL = "requestor_email";
@@ -55,7 +52,7 @@ public class SubmitterInfoInput extends EnrollInput implements IProfileInput {
* Initializes this default policy.
*/
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
@@ -77,13 +74,12 @@ public class SubmitterInfoInput extends EnrollInput implements IProfileInput {
* Populates the request with this policy default.
*/
public void populate(IProfileContext ctx, IRequest request)
- throws EProfileException {
+ throws EProfileException {
//
}
/**
- * Retrieves the descriptor of the given value
- * parameter by name.
+ * Retrieves the descriptor of the given value parameter by name.
*/
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(NAME)) {
diff --git a/pki/base/common/src/com/netscape/cms/profile/input/nsHKeyCertReqInput.java b/pki/base/common/src/com/netscape/cms/profile/input/nsHKeyCertReqInput.java
index 64988fed..4e51feec 100644
--- a/pki/base/common/src/com/netscape/cms/profile/input/nsHKeyCertReqInput.java
+++ b/pki/base/common/src/com/netscape/cms/profile/input/nsHKeyCertReqInput.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.input;
-
import java.util.Locale;
import netscape.security.x509.X509CertInfo;
@@ -33,19 +32,17 @@ import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
import com.netscape.cms.profile.common.EnrollProfile;
-
/**
- * This class implements the certificate request input from TPS.
- * This input populates 2 main fields to the enrollment "page":
- * 1/ token cuid, 2/ publickey
+ * This class implements the certificate request input from TPS. This input
+ * populates 2 main fields to the enrollment "page": 1/ token cuid, 2/ publickey
* <p>
*
- * This input usually is used by an enrollment profile for
- * certificate requests coming from TPS.
- *
+ * This input usually is used by an enrollment profile for certificate requests
+ * coming from TPS.
+ *
* @version $Revision$, $Date$
*/
-public class nsHKeyCertReqInput extends EnrollInput implements IProfileInput {
+public class nsHKeyCertReqInput extends EnrollInput implements IProfileInput {
public static final String VAL_TOKEN_CUID = "tokencuid";
public static final String VAL_PUBLIC_KEY = "publickey";
@@ -60,7 +57,7 @@ public class nsHKeyCertReqInput extends EnrollInput implements IProfileInput {
* Initializes this default policy.
*/
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
mEnrollProfile = (EnrollProfile) profile;
@@ -80,84 +77,82 @@ public class nsHKeyCertReqInput extends EnrollInput implements IProfileInput {
return CMS.getUserMessage(locale, "CMS_PROFILE_INPUT_TOKENKEY_CERT_REQ_TEXT");
}
- /*
- * Pretty print token cuid
- */
- public String toPrettyPrint(String cuid)
- {
- if (cuid == null)
- return null;
-
- if (cuid.length() != 20)
- return null;
-
- StringBuffer sb = new StringBuffer();
- for (int i=0; i < cuid.length(); i++) {
- if (i == 4 || i == 8 || i == 12 || i == 16) {
- sb.append("-");
- }
- sb.append(cuid.charAt(i));
- }
- return sb.toString();
- }
+ /*
+ * Pretty print token cuid
+ */
+ public String toPrettyPrint(String cuid) {
+ if (cuid == null)
+ return null;
+
+ if (cuid.length() != 20)
+ return null;
+
+ StringBuffer sb = new StringBuffer();
+ for (int i = 0; i < cuid.length(); i++) {
+ if (i == 4 || i == 8 || i == 12 || i == 16) {
+ sb.append("-");
+ }
+ sb.append(cuid.charAt(i));
+ }
+ return sb.toString();
+ }
/**
* Populates the request with this policy default.
*/
public void populate(IProfileContext ctx, IRequest request)
- throws EProfileException {
+ throws EProfileException {
String tcuid = ctx.get(VAL_TOKEN_CUID);
- // pretty print tcuid
- String prettyPrintCuid = toPrettyPrint(tcuid);
- if (prettyPrintCuid == null) {
+ // pretty print tcuid
+ String prettyPrintCuid = toPrettyPrint(tcuid);
+ if (prettyPrintCuid == null) {
throw new EProfileException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_TOKENKEY_NO_TOKENCUID",
- ""));
- }
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_TOKENKEY_NO_TOKENCUID",
+ ""));
+ }
- request.setExtData("pretty_print_tokencuid", prettyPrintCuid);
+ request.setExtData("pretty_print_tokencuid", prettyPrintCuid);
String pk = ctx.get(VAL_PUBLIC_KEY);
X509CertInfo info =
- request.getExtDataInCertInfo(EnrollProfile.REQUEST_CERTINFO);
+ request.getExtDataInCertInfo(EnrollProfile.REQUEST_CERTINFO);
if (tcuid == null) {
- CMS.debug("nsHKeyCertReqInput: populate - tokencuid not found " +
- "");
+ CMS.debug("nsHKeyCertReqInput: populate - tokencuid not found " +
+ "");
throw new EProfileException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_TOKENKEY_NO_TOKENCUID",
- ""));
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_TOKENKEY_NO_TOKENCUID",
+ ""));
}
if (pk == null) {
- CMS.debug("nsHKeyCertReqInput: populate - public key not found " +
- "");
+ CMS.debug("nsHKeyCertReqInput: populate - public key not found " +
+ "");
throw new EProfileException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_TOKENKEY_NO_PUBLIC_KEY",
- ""));
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_TOKENKEY_NO_PUBLIC_KEY",
+ ""));
}
- mEnrollProfile.fillNSHKEY(getLocale(request), tcuid, pk, info, request);
+ mEnrollProfile.fillNSHKEY(getLocale(request), tcuid, pk, info, request);
request.setExtData(EnrollProfile.REQUEST_CERTINFO, info);
}
/**
- * Retrieves the descriptor of the given value
- * parameter by name.
+ * Retrieves the descriptor of the given value parameter by name.
*/
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_TOKEN_CUID)) {
return new Descriptor(IDescriptor.STRING, null,
null,
CMS.getUserMessage(locale,
- "CMS_PROFILE_INPUT_TOKENKEY_CERT_REQ_TOKEN_CUID"));
+ "CMS_PROFILE_INPUT_TOKENKEY_CERT_REQ_TOKEN_CUID"));
} else if (name.equals(VAL_PUBLIC_KEY)) {
return new Descriptor(IDescriptor.STRING, null,
null,
CMS.getUserMessage(locale,
- "CMS_PROFILE_INPUT_TOKENKEY_CERT_REQ_PK"));
+ "CMS_PROFILE_INPUT_TOKENKEY_CERT_REQ_PK"));
}
return null;
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/input/nsNKeyCertReqInput.java b/pki/base/common/src/com/netscape/cms/profile/input/nsNKeyCertReqInput.java
index 58984c6c..b2476a66 100644
--- a/pki/base/common/src/com/netscape/cms/profile/input/nsNKeyCertReqInput.java
+++ b/pki/base/common/src/com/netscape/cms/profile/input/nsNKeyCertReqInput.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.input;
-
import java.util.Locale;
import netscape.security.x509.X509CertInfo;
@@ -33,19 +32,17 @@ import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
import com.netscape.cms.profile.common.EnrollProfile;
-
/**
- * This class implements the certificate request input from TPS.
- * This input populates 2 main fields to the enrollment "page":
- * 1/ id, 2/ publickey
+ * This class implements the certificate request input from TPS. This input
+ * populates 2 main fields to the enrollment "page": 1/ id, 2/ publickey
* <p>
*
- * This input usually is used by an enrollment profile for
- * certificate requests coming from TPS.
- *
+ * This input usually is used by an enrollment profile for certificate requests
+ * coming from TPS.
+ *
* @version $Revision$, $Date$
*/
-public class nsNKeyCertReqInput extends EnrollInput implements IProfileInput {
+public class nsNKeyCertReqInput extends EnrollInput implements IProfileInput {
public static final String VAL_SN = "screenname";
public static final String VAL_PUBLIC_KEY = "publickey";
@@ -60,7 +57,7 @@ public class nsNKeyCertReqInput extends EnrollInput implements IProfileInput {
* Initializes this default policy.
*/
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
mEnrollProfile = (EnrollProfile) profile;
@@ -84,48 +81,47 @@ public class nsNKeyCertReqInput extends EnrollInput implements IProfileInput {
* Populates the request with this policy default.
*/
public void populate(IProfileContext ctx, IRequest request)
- throws EProfileException {
+ throws EProfileException {
String sn = ctx.get(VAL_SN);
String pk = ctx.get(VAL_PUBLIC_KEY);
X509CertInfo info =
- request.getExtDataInCertInfo(EnrollProfile.REQUEST_CERTINFO);
+ request.getExtDataInCertInfo(EnrollProfile.REQUEST_CERTINFO);
if (sn == null) {
- CMS.debug("nsNKeyCertReqInput: populate - id not found " +
- "");
+ CMS.debug("nsNKeyCertReqInput: populate - id not found " +
+ "");
throw new EProfileException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_TOKENKEY_NO_ID",
- ""));
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_TOKENKEY_NO_ID",
+ ""));
}
if (pk == null) {
- CMS.debug("nsNKeyCertReqInput: populate - public key not found " +
- "");
+ CMS.debug("nsNKeyCertReqInput: populate - public key not found " +
+ "");
throw new EProfileException(
- CMS.getUserMessage(getLocale(request),
- "CMS_PROFILE_TOKENKEY_NO_PUBLIC_KEY",
- ""));
+ CMS.getUserMessage(getLocale(request),
+ "CMS_PROFILE_TOKENKEY_NO_PUBLIC_KEY",
+ ""));
}
- mEnrollProfile.fillNSNKEY(getLocale(request), sn, pk, info, request);
+ mEnrollProfile.fillNSNKEY(getLocale(request), sn, pk, info, request);
request.setExtData(EnrollProfile.REQUEST_CERTINFO, info);
}
/**
- * Retrieves the descriptor of the given value
- * parameter by name.
+ * Retrieves the descriptor of the given value parameter by name.
*/
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_SN)) {
return new Descriptor(IDescriptor.STRING, null,
null,
CMS.getUserMessage(locale,
- "CMS_PROFILE_INPUT_TOKENKEY_CERT_REQ_UID"));
+ "CMS_PROFILE_INPUT_TOKENKEY_CERT_REQ_UID"));
} else if (name.equals(VAL_PUBLIC_KEY)) {
return new Descriptor(IDescriptor.STRING, null,
null,
CMS.getUserMessage(locale,
- "CMS_PROFILE_INPUT_TOKENKEY_CERT_REQ_PK"));
+ "CMS_PROFILE_INPUT_TOKENKEY_CERT_REQ_PK"));
}
return null;
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/output/CMMFOutput.java b/pki/base/common/src/com/netscape/cms/profile/output/CMMFOutput.java
index 999bdc67..421d5852 100644
--- a/pki/base/common/src/com/netscape/cms/profile/output/CMMFOutput.java
+++ b/pki/base/common/src/com/netscape/cms/profile/output/CMMFOutput.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.output;
-
import java.io.ByteArrayOutputStream;
import java.security.cert.X509Certificate;
import java.util.Locale;
@@ -45,14 +44,13 @@ import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
import com.netscape.cms.profile.common.EnrollProfile;
-
/**
- * This class implements the output plugin that outputs
- * CMMF response for the issued certificate.
- *
+ * This class implements the output plugin that outputs CMMF response for the
+ * issued certificate.
+ *
* @version $Revision$, $Date$
*/
-public class CMMFOutput extends EnrollOutput implements IProfileOutput {
+public class CMMFOutput extends EnrollOutput implements IProfileOutput {
public static final String VAL_PRETTY_CERT = "pretty_cert";
public static final String VAL_CMMF_RESPONSE = "cmmf_response";
@@ -66,7 +64,7 @@ public class CMMFOutput extends EnrollOutput implements IProfileOutput {
* Initializes this default policy.
*/
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
@@ -88,72 +86,71 @@ public class CMMFOutput extends EnrollOutput implements IProfileOutput {
* Populates the request with this policy default.
*/
public void populate(IProfileContext ctx, IRequest request)
- throws EProfileException {
+ throws EProfileException {
}
/**
- * Retrieves the descriptor of the given value
- * parameter by name.
+ * Retrieves the descriptor of the given value parameter by name.
*/
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_PRETTY_CERT)) {
return new Descriptor(IDescriptor.PRETTY_PRINT, null,
null,
- CMS.getUserMessage(locale,
- "CMS_PROFILE_OUTPUT_CERT_PP"));
+ CMS.getUserMessage(locale,
+ "CMS_PROFILE_OUTPUT_CERT_PP"));
} else if (name.equals(VAL_CMMF_RESPONSE)) {
return new Descriptor(IDescriptor.PRETTY_PRINT, null,
null,
- CMS.getUserMessage(locale,
- "CMS_PROFILE_OUTPUT_CMMF_B64"));
+ CMS.getUserMessage(locale,
+ "CMS_PROFILE_OUTPUT_CMMF_B64"));
}
return null;
}
public String getValue(String name, Locale locale, IRequest request)
- throws EProfileException {
+ throws EProfileException {
if (name.equals(VAL_PRETTY_CERT)) {
X509CertImpl cert = request.getExtDataInCert(
EnrollProfile.REQUEST_ISSUED_CERT);
- ICertPrettyPrint prettyCert = CMS.getCertPrettyPrint(cert);
+ ICertPrettyPrint prettyCert = CMS.getCertPrettyPrint(cert);
return prettyCert.toString(locale);
} else if (name.equals(VAL_CMMF_RESPONSE)) {
try {
- X509CertImpl cert = request.getExtDataInCert(
- EnrollProfile.REQUEST_ISSUED_CERT);
- if (cert == null)
- return null;
-
- ICertificateAuthority ca = (ICertificateAuthority)
- CMS.getSubsystem("ca");
- CertificateChain cachain = ca.getCACertChain();
- X509Certificate[] cacerts = cachain.getChain();
-
- byte[][] caPubs = new byte[cacerts.length][];
-
- for (int j = 0; j < cacerts.length; j++) {
- caPubs[j] = ((X509CertImpl) cacerts[j]).getEncoded();
- }
-
- CertRepContent certRepContent = null;
- certRepContent = new CertRepContent(caPubs);
-
- PKIStatusInfo status = new PKIStatusInfo(PKIStatusInfo.granted);
- CertifiedKeyPair certifiedKP =
- new CertifiedKeyPair(new CertOrEncCert(cert.getEncoded()));
- CertResponse resp =
- new CertResponse(new INTEGER(request.getRequestId().toString()),
- status, certifiedKP);
- certRepContent.addCertResponse(resp);
-
- ByteArrayOutputStream certRepOut = new ByteArrayOutputStream();
- certRepContent.encode(certRepOut);
- byte[] certRepBytes = certRepOut.toByteArray();
-
- return CMS.BtoA(certRepBytes);
+ X509CertImpl cert = request.getExtDataInCert(
+ EnrollProfile.REQUEST_ISSUED_CERT);
+ if (cert == null)
+ return null;
+
+ ICertificateAuthority ca = (ICertificateAuthority)
+ CMS.getSubsystem("ca");
+ CertificateChain cachain = ca.getCACertChain();
+ X509Certificate[] cacerts = cachain.getChain();
+
+ byte[][] caPubs = new byte[cacerts.length][];
+
+ for (int j = 0; j < cacerts.length; j++) {
+ caPubs[j] = ((X509CertImpl) cacerts[j]).getEncoded();
+ }
+
+ CertRepContent certRepContent = null;
+ certRepContent = new CertRepContent(caPubs);
+
+ PKIStatusInfo status = new PKIStatusInfo(PKIStatusInfo.granted);
+ CertifiedKeyPair certifiedKP =
+ new CertifiedKeyPair(new CertOrEncCert(cert.getEncoded()));
+ CertResponse resp =
+ new CertResponse(new INTEGER(request.getRequestId().toString()),
+ status, certifiedKP);
+ certRepContent.addCertResponse(resp);
+
+ ByteArrayOutputStream certRepOut = new ByteArrayOutputStream();
+ certRepContent.encode(certRepOut);
+ byte[] certRepBytes = certRepOut.toByteArray();
+
+ return CMS.BtoA(certRepBytes);
} catch (Exception e) {
- return null;
+ return null;
}
} else {
return null;
diff --git a/pki/base/common/src/com/netscape/cms/profile/output/CertOutput.java b/pki/base/common/src/com/netscape/cms/profile/output/CertOutput.java
index 7a2631da..676b280f 100644
--- a/pki/base/common/src/com/netscape/cms/profile/output/CertOutput.java
+++ b/pki/base/common/src/com/netscape/cms/profile/output/CertOutput.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.output;
-
import java.util.Locale;
import netscape.security.x509.X509CertImpl;
@@ -34,14 +33,13 @@ import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
import com.netscape.cms.profile.common.EnrollProfile;
-
/**
- * This class implements the pretty print certificate output
- * that displays the issued certificate in a pretty print format.
- *
+ * This class implements the pretty print certificate output that displays the
+ * issued certificate in a pretty print format.
+ *
* @version $Revision$, $Date$
*/
-public class CertOutput extends EnrollOutput implements IProfileOutput {
+public class CertOutput extends EnrollOutput implements IProfileOutput {
public static final String VAL_PRETTY_CERT = "pretty_cert";
public static final String VAL_B64_CERT = "b64_cert";
@@ -54,7 +52,7 @@ public class CertOutput extends EnrollOutput implements IProfileOutput {
* Initializes this default policy.
*/
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
@@ -76,36 +74,35 @@ public class CertOutput extends EnrollOutput implements IProfileOutput {
* Populates the request with this policy default.
*/
public void populate(IProfileContext ctx, IRequest request)
- throws EProfileException {
+ throws EProfileException {
}
/**
- * Retrieves the descriptor of the given value
- * parameter by name.
+ * Retrieves the descriptor of the given value parameter by name.
*/
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_PRETTY_CERT)) {
return new Descriptor(IDescriptor.PRETTY_PRINT, null,
null,
- CMS.getUserMessage(locale,
- "CMS_PROFILE_OUTPUT_CERT_PP"));
+ CMS.getUserMessage(locale,
+ "CMS_PROFILE_OUTPUT_CERT_PP"));
} else if (name.equals(VAL_B64_CERT)) {
return new Descriptor(IDescriptor.PRETTY_PRINT, null,
null,
- CMS.getUserMessage(locale,
- "CMS_PROFILE_OUTPUT_CERT_B64"));
+ CMS.getUserMessage(locale,
+ "CMS_PROFILE_OUTPUT_CERT_B64"));
}
return null;
}
public String getValue(String name, Locale locale, IRequest request)
- throws EProfileException {
+ throws EProfileException {
if (name.equals(VAL_PRETTY_CERT)) {
X509CertImpl cert = request.getExtDataInCert(
EnrollProfile.REQUEST_ISSUED_CERT);
if (cert == null)
return null;
- ICertPrettyPrint prettyCert = CMS.getCertPrettyPrint(cert);
+ ICertPrettyPrint prettyCert = CMS.getCertPrettyPrint(cert);
return prettyCert.toString(locale);
} else if (name.equals(VAL_B64_CERT)) {
@@ -113,7 +110,7 @@ public class CertOutput extends EnrollOutput implements IProfileOutput {
EnrollProfile.REQUEST_ISSUED_CERT);
if (cert == null)
return null;
- return CMS.getEncodedCert(cert);
+ return CMS.getEncodedCert(cert);
} else {
return null;
}
diff --git a/pki/base/common/src/com/netscape/cms/profile/output/EnrollOutput.java b/pki/base/common/src/com/netscape/cms/profile/output/EnrollOutput.java
index 5e3f077b..e0cd89da 100644
--- a/pki/base/common/src/com/netscape/cms/profile/output/EnrollOutput.java
+++ b/pki/base/common/src/com/netscape/cms/profile/output/EnrollOutput.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.output;
-
import java.util.Enumeration;
import java.util.Locale;
import java.util.Vector;
@@ -31,22 +30,21 @@ import com.netscape.certsrv.property.EPropertyException;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
-
/**
* This class implements the basic enrollment output.
- *
+ *
* @version $Revision$, $Date$
*/
-public abstract class EnrollOutput implements IProfileOutput {
+public abstract class EnrollOutput implements IProfileOutput {
private IConfigStore mConfig = null;
private Vector<String> mValueNames = new Vector<String>();
protected Vector<String> mConfigNames = new Vector<String>();
-
+
/**
* Initializes this default policy.
*/
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
mConfig = config;
}
@@ -60,28 +58,26 @@ public abstract class EnrollOutput implements IProfileOutput {
/**
* Populates the request with this policy default.
- *
+ *
* @param ctx profile context
* @param request request
* @exception EProfileException failed to populate
*/
public abstract void populate(IProfileContext ctx, IRequest request)
- throws EProfileException;
+ throws EProfileException;
/**
- * Retrieves the descriptor of the given value
- * parameter by name.
- *
+ * Retrieves the descriptor of the given value parameter by name.
+ *
* @param locale user locale
* @param name property name
* @return property descriptor
*/
public abstract IDescriptor getValueDescriptor(Locale locale, String name);
-
/**
* Retrieves the localizable name of this policy.
- *
+ *
* @param locale user locale
* @return output policy name
*/
@@ -89,7 +85,7 @@ public abstract class EnrollOutput implements IProfileOutput {
/**
* Retrieves the localizable description of this policy.
- *
+ *
* @param locale user locale
* @return output policy description
*/
@@ -103,7 +99,7 @@ public abstract class EnrollOutput implements IProfileOutput {
}
public String getValue(String name, Locale locale, IRequest request)
- throws EProfileException {
+ throws EProfileException {
return request.getExtDataInString(name);
}
@@ -111,7 +107,7 @@ public abstract class EnrollOutput implements IProfileOutput {
* Sets the value of the given value parameter by name.
*/
public void setValue(String name, Locale locale, IRequest request,
- String value) throws EPropertyException {
+ String value) throws EPropertyException {
request.setExtData(name, value);
}
@@ -124,7 +120,7 @@ public abstract class EnrollOutput implements IProfileOutput {
}
public void setConfig(String name, String value)
- throws EPropertyException {
+ throws EPropertyException {
}
public String getConfig(String name) {
diff --git a/pki/base/common/src/com/netscape/cms/profile/output/PKCS7Output.java b/pki/base/common/src/com/netscape/cms/profile/output/PKCS7Output.java
index 65718481..e2d9a08c 100644
--- a/pki/base/common/src/com/netscape/cms/profile/output/PKCS7Output.java
+++ b/pki/base/common/src/com/netscape/cms/profile/output/PKCS7Output.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.output;
-
import java.io.ByteArrayOutputStream;
import java.security.cert.X509Certificate;
import java.util.Locale;
@@ -42,14 +41,13 @@ import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
import com.netscape.cms.profile.common.EnrollProfile;
-
/**
- * This class implements the output plugin that outputs
- * PKCS7 for the issued certificate.
- *
+ * This class implements the output plugin that outputs PKCS7 for the issued
+ * certificate.
+ *
* @version $Revision$, $Date$
*/
-public class PKCS7Output extends EnrollOutput implements IProfileOutput {
+public class PKCS7Output extends EnrollOutput implements IProfileOutput {
public static final String VAL_PRETTY_CERT = "pretty_cert";
public static final String VAL_PKCS7 = "pkcs7";
@@ -63,7 +61,7 @@ public class PKCS7Output extends EnrollOutput implements IProfileOutput {
* Initializes this default policy.
*/
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
@@ -85,72 +83,71 @@ public class PKCS7Output extends EnrollOutput implements IProfileOutput {
* Populates the request with this policy default.
*/
public void populate(IProfileContext ctx, IRequest request)
- throws EProfileException {
+ throws EProfileException {
}
/**
- * Retrieves the descriptor of the given value
- * parameter by name.
+ * Retrieves the descriptor of the given value parameter by name.
*/
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_PRETTY_CERT)) {
return new Descriptor(IDescriptor.PRETTY_PRINT, null,
null,
- CMS.getUserMessage(locale,
- "CMS_PROFILE_OUTPUT_CERT_PP"));
+ CMS.getUserMessage(locale,
+ "CMS_PROFILE_OUTPUT_CERT_PP"));
} else if (name.equals(VAL_PKCS7)) {
return new Descriptor(IDescriptor.PRETTY_PRINT, null,
null,
- CMS.getUserMessage(locale,
- "CMS_PROFILE_OUTPUT_PKCS7_B64"));
+ CMS.getUserMessage(locale,
+ "CMS_PROFILE_OUTPUT_PKCS7_B64"));
}
return null;
}
public String getValue(String name, Locale locale, IRequest request)
- throws EProfileException {
+ throws EProfileException {
if (name.equals(VAL_PRETTY_CERT)) {
X509CertImpl cert = request.getExtDataInCert(
EnrollProfile.REQUEST_ISSUED_CERT);
if (cert == null)
- return null;
- ICertPrettyPrint prettyCert = CMS.getCertPrettyPrint(cert);
+ return null;
+ ICertPrettyPrint prettyCert = CMS.getCertPrettyPrint(cert);
return prettyCert.toString(locale);
} else if (name.equals(VAL_PKCS7)) {
try {
- X509CertImpl cert = request.getExtDataInCert(
- EnrollProfile.REQUEST_ISSUED_CERT);
- if (cert == null)
- return null;
-
- ICertificateAuthority ca = (ICertificateAuthority)
- CMS.getSubsystem("ca");
- CertificateChain cachain = ca.getCACertChain();
- X509Certificate[] cacerts = cachain.getChain();
-
- X509CertImpl[] userChain = new X509CertImpl[cacerts.length + 1];
- int m = 1, n = 0;
-
- for (; n < cacerts.length; m++, n++) {
- userChain[m] = (X509CertImpl) cacerts[n];
- }
-
- userChain[0] = cert;
- PKCS7 p7 = new PKCS7(new AlgorithmId[0],
- new ContentInfo(new byte[0]),
- userChain,
- new SignerInfo[0]);
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
-
- p7.encodeSignedData(bos);
- byte[] p7Bytes = bos.toByteArray();
- String p7Str = CMS.BtoA(p7Bytes);
-
- return p7Str;
+ X509CertImpl cert = request.getExtDataInCert(
+ EnrollProfile.REQUEST_ISSUED_CERT);
+ if (cert == null)
+ return null;
+
+ ICertificateAuthority ca = (ICertificateAuthority)
+ CMS.getSubsystem("ca");
+ CertificateChain cachain = ca.getCACertChain();
+ X509Certificate[] cacerts = cachain.getChain();
+
+ X509CertImpl[] userChain = new X509CertImpl[cacerts.length + 1];
+ int m = 1, n = 0;
+
+ for (; n < cacerts.length; m++, n++) {
+ userChain[m] = (X509CertImpl) cacerts[n];
+ }
+
+ userChain[0] = cert;
+ PKCS7 p7 = new PKCS7(new AlgorithmId[0],
+ new ContentInfo(new byte[0]),
+ userChain,
+ new SignerInfo[0]);
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+
+ p7.encodeSignedData(bos);
+ byte[] p7Bytes = bos.toByteArray();
+ String p7Str = CMS.BtoA(p7Bytes);
+
+ return p7Str;
} catch (Exception e) {
- return "";
+ return "";
}
} else {
return null;
diff --git a/pki/base/common/src/com/netscape/cms/profile/output/nsNKeyOutput.java b/pki/base/common/src/com/netscape/cms/profile/output/nsNKeyOutput.java
index 90aa40a1..2ba07e6e 100644
--- a/pki/base/common/src/com/netscape/cms/profile/output/nsNKeyOutput.java
+++ b/pki/base/common/src/com/netscape/cms/profile/output/nsNKeyOutput.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.profile.output;
-
import java.util.Locale;
import netscape.security.x509.X509CertImpl;
@@ -33,14 +32,13 @@ import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.request.IRequest;
import com.netscape.cms.profile.common.EnrollProfile;
-
/**
- * This class implements the output plugin that outputs
- * DER for the issued certificate for token keys
- *
+ * This class implements the output plugin that outputs DER for the issued
+ * certificate for token keys
+ *
* @version $Revision$, $Date$
*/
-public class nsNKeyOutput extends EnrollOutput implements IProfileOutput {
+public class nsNKeyOutput extends EnrollOutput implements IProfileOutput {
public static final String VAL_DER = "der";
@@ -52,7 +50,7 @@ public class nsNKeyOutput extends EnrollOutput implements IProfileOutput {
* Initializes this default policy.
*/
public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ throws EProfileException {
super.init(profile, config);
}
@@ -74,35 +72,34 @@ public class nsNKeyOutput extends EnrollOutput implements IProfileOutput {
* Populates the request with this policy default.
*/
public void populate(IProfileContext ctx, IRequest request)
- throws EProfileException {
+ throws EProfileException {
}
/**
- * Retrieves the descriptor of the given value
- * parameter by name.
+ * Retrieves the descriptor of the given value parameter by name.
*/
public IDescriptor getValueDescriptor(Locale locale, String name) {
if (name.equals(VAL_DER)) {
return new Descriptor("der_b64", null,
null,
- CMS.getUserMessage(locale,
- "CMS_PROFILE_OUTPUT_DER_B64"));
+ CMS.getUserMessage(locale,
+ "CMS_PROFILE_OUTPUT_DER_B64"));
}
return null;
}
public String getValue(String name, Locale locale, IRequest request)
- throws EProfileException {
+ throws EProfileException {
if (name.equals(VAL_DER)) {
try {
- X509CertImpl cert = request.getExtDataInCert(
- EnrollProfile.REQUEST_ISSUED_CERT);
- if (cert == null)
- return null;
- return CMS.BtoA(cert.getEncoded());
+ X509CertImpl cert = request.getExtDataInCert(
+ EnrollProfile.REQUEST_ISSUED_CERT);
+ if (cert == null)
+ return null;
+ return CMS.BtoA(cert.getEncoded());
} catch (Exception e) {
- return "";
+ return "";
}
} else {
return null;
diff --git a/pki/base/common/src/com/netscape/cms/profile/updater/SubsystemGroupUpdater.java b/pki/base/common/src/com/netscape/cms/profile/updater/SubsystemGroupUpdater.java
index 69803421..589763b5 100644
--- a/pki/base/common/src/com/netscape/cms/profile/updater/SubsystemGroupUpdater.java
+++ b/pki/base/common/src/com/netscape/cms/profile/updater/SubsystemGroupUpdater.java
@@ -43,8 +43,8 @@ import com.netscape.certsrv.usrgrp.IUser;
import com.netscape.cms.profile.common.EnrollProfile;
/**
- * This updater class will create the new user to the subsystem group and
- * then add the subsystem certificate to the user.
+ * This updater class will create the new user to the subsystem group and then
+ * add the subsystem certificate to the user.
*
* @version $Revision$, $Date$
*/
@@ -58,7 +58,7 @@ public class SubsystemGroupUpdater implements IProfileUpdater {
private Vector mValueNames = new Vector();
private final static String LOGGING_SIGNED_AUDIT_CONFIG_ROLE =
- "LOGGING_SIGNED_AUDIT_CONFIG_ROLE_3";
+ "LOGGING_SIGNED_AUDIT_CONFIG_ROLE_3";
private final static String SIGNED_AUDIT_PASSWORD_VALUE = "********";
private final static String SIGNED_AUDIT_EMPTY_NAME_VALUE_PAIR = "Unknown";
private final static String SIGNED_AUDIT_NAME_VALUE_DELIMITER = ";;";
@@ -67,8 +67,8 @@ public class SubsystemGroupUpdater implements IProfileUpdater {
public SubsystemGroupUpdater() {
}
- public void init(IProfile profile, IConfigStore config)
- throws EProfileException {
+ public void init(IProfile profile, IConfigStore config)
+ throws EProfileException {
mConfig = config;
mProfile = profile;
mEnrollProfile = (EnrollProfile) profile;
@@ -82,8 +82,8 @@ public class SubsystemGroupUpdater implements IProfileUpdater {
return null;
}
- public void setConfig(String name, String value)
- throws EPropertyException {
+ public void setConfig(String name, String value)
+ throws EPropertyException {
if (mConfig.getSubStore("params") == null) {
//
} else {
@@ -108,8 +108,8 @@ public class SubsystemGroupUpdater implements IProfileUpdater {
return mConfig;
}
- public void update(IRequest req, RequestStatus status)
- throws EProfileException {
+ public void update(IRequest req, RequestStatus status)
+ throws EProfileException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -124,33 +124,34 @@ public class SubsystemGroupUpdater implements IProfileUpdater {
return;
IConfigStore mainConfig = CMS.getConfigStore();
-
- int num=0;
+
+ int num = 0;
try {
num = mainConfig.getInteger("subsystem.count", 0);
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
IUGSubsystem system = (IUGSubsystem) (CMS.getSubsystem(IUGSubsystem.ID));
String requestor_name = "subsystem";
try {
- requestor_name = req.getExtDataInString("requestor_name");
+ requestor_name = req.getExtDataInString("requestor_name");
} catch (Exception e1) {
- // ignore
+ // ignore
}
// i.e. tps-1.2.3.4-4
String id = requestor_name;
-
+
num++;
mainConfig.putInteger("subsystem.count", num);
-
+
try {
mainConfig.commit(false);
} catch (Exception e) {
}
String auditParams = "Scope;;users+Operation;;OP_ADD+source;;SubsystemGroupUpdater" +
- "+Resource;;"+ id +
+ "+Resource;;" + id +
"+fullname;;" + id +
"+state;;1" +
"+userType;;agentType+email;;<null>+password;;<null>+phone;;<null>";
@@ -196,8 +197,8 @@ public class SubsystemGroupUpdater implements IProfileUpdater {
}
auditParams = "Scope;;certs+Operation;;OP_ADD+source;;SubsystemGroupUpdater" +
- "+Resource;;"+ id +
- "+cert;;"+ b64;
+ "+Resource;;" + id +
+ "+cert;;" + b64;
system.addUserCert(user);
CMS.debug("SubsystemGroupUpdater update: successfully add the user certificate");
@@ -216,7 +217,7 @@ public class SubsystemGroupUpdater implements IProfileUpdater {
ILogger.FAILURE,
auditParams);
audit(auditMessage);
- throw new EProfileException(e.toString());
+ throw new EProfileException(e.toString());
}
} catch (Exception e) {
CMS.debug("UpdateSubsystemGroup: update addUser " + e.toString());
@@ -232,17 +233,17 @@ public class SubsystemGroupUpdater implements IProfileUpdater {
IGroup group = null;
String groupName = "Subsystem Group";
auditParams = "Scope;;groups+Operation;;OP_MODIFY+source;;SubsystemGroupUpdater" +
- "+Resource;;"+ groupName;
+ "+Resource;;" + groupName;
try {
group = system.getGroupFromName(groupName);
-
+
auditParams += "+user;;";
Enumeration members = group.getMemberNames();
while (members.hasMoreElements()) {
auditParams += (String) members.nextElement();
if (members.hasMoreElements()) {
- auditParams +=",";
+ auditParams += ",";
}
}
@@ -287,10 +288,10 @@ public class SubsystemGroupUpdater implements IProfileUpdater {
}
mSignedAuditLogger.log(ILogger.EV_SIGNED_AUDIT,
- null,
- ILogger.S_SIGNED_AUDIT,
- ILogger.LL_SECURITY,
- msg);
+ null,
+ ILogger.S_SIGNED_AUDIT,
+ ILogger.LL_SECURITY,
+ msg);
}
private String auditSubjectID() {
diff --git a/pki/base/common/src/com/netscape/cms/publish/mappers/AVAPattern.java b/pki/base/common/src/com/netscape/cms/publish/mappers/AVAPattern.java
index aea489e3..ca05129c 100644
--- a/pki/base/common/src/com/netscape/cms/publish/mappers/AVAPattern.java
+++ b/pki/base/common/src/com/netscape/cms/publish/mappers/AVAPattern.java
@@ -20,7 +20,6 @@
package com.netscape.cms.publish.mappers;
-
///////////////////////
// import statements //
///////////////////////
@@ -49,24 +48,24 @@ import com.netscape.certsrv.ldap.ELdapException;
import com.netscape.certsrv.publish.ECompSyntaxErr;
import com.netscape.certsrv.request.IRequest;
-
//////////////////////
// class definition //
//////////////////////
/**
- * avaPattern is a string representing an ldap
- * attribute formulated from the certificate
- * subject name, extension or request attributes.
+ * avaPattern is a string representing an ldap attribute formulated from the
+ * certificate subject name, extension or request attributes.
* <p>
*
- * The syntax is
+ * The syntax is
+ *
* <pre>
* avaPattern := constant-value |
* "$subj" "." attrName [ "." attrNumber ] |
* "$req" "." [ prefix .] attrName [ "." attrNumber ] |
- * "$ext" "." extName [ "." nameType ] [ "." attrNumber ]
+ * "$ext" "." extName [ "." nameType ] [ "." attrNumber ]
* </pre>
+ *
* <pre>
* Example: <i>$ext.SubjectAlternativeName.RFC822Name.1</i>
* cert subjectAltName is rfc822Name: jjames@mcom.com
@@ -77,15 +76,16 @@ import com.netscape.certsrv.request.IRequest;
* The first rfc822name value in the subjAltName extension. <br>
* <p>
* </pre>
- * If a request attribute or subject DN component does not exist,
- * the attribute is skipped.
- *
+ *
+ * If a request attribute or subject DN component does not exist, the attribute
+ * is skipped.
+ *
* @version $Revision$, $Date$
*/
class AVAPattern {
- ////////////////
+ // //////////////
// parameters //
- ////////////////
+ // //////////////
/* the value type of the dn component */
public static final String TYPE_REQ = "$req";
@@ -101,29 +101,30 @@ class AVAPattern {
"EDIName",
"URIName",
"IPAddress",
- "OIDName"};
+ "OIDName" };
private static final char[] endChars = new char[] { '+', ',' };
- private static final LdapV3DNStrConverter mLdapDNStrConverter =
- new LdapV3DNStrConverter();
+ private static final LdapV3DNStrConverter mLdapDNStrConverter =
+ new LdapV3DNStrConverter();
- /* the list of request attributes needed by this AVA */
+ /* the list of request attributes needed by this AVA */
protected String[] mReqAttrs = null;
- /* the list of cert attributes needed by this AVA*/
+ /* the list of cert attributes needed by this AVA */
protected String[] mCertAttrs = null;
/* value type */
protected String mType = null;
- /* value - could be name of a request attribute or
- * cert subject attribute or extension name.
+ /*
+ * value - could be name of a request attribute or cert subject attribute or
+ * extension name.
*/
protected String mValue = null;
- /* value type - general name type of an
- * extension attribute if any.
+ /*
+ * value type - general name type of an extension attribute if any.
*/
protected String mGNType = null;
@@ -135,12 +136,12 @@ class AVAPattern {
protected String mTestDN = null;
- /////////////
+ // ///////////
// methods //
- /////////////
+ // ///////////
public AVAPattern(String component)
- throws ELdapException {
+ throws ELdapException {
if (component == null || component.length() == 0) {
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX", component));
}
@@ -148,33 +149,33 @@ class AVAPattern {
parse(new PushbackReader(new StringReader(component)));
}
- public AVAPattern(PushbackReader in)
- throws ELdapException {
+ public AVAPattern(PushbackReader in)
+ throws ELdapException {
parse(in);
}
private void parse(PushbackReader in)
- throws ELdapException {
+ throws ELdapException {
int c;
// skip spaces
- //System.out.println("============ AVAPattern Begin ===========");
- //System.out.println("skip spaces");
+ // System.out.println("============ AVAPattern Begin ===========");
+ // System.out.println("skip spaces");
try {
- while ((c = in.read()) == ' ' || c == '\t') {//System.out.println("spaces read "+(char)c);
+ while ((c = in.read()) == ' ' || c == '\t') {// System.out.println("spaces read "+(char)c);
;
}
} catch (IOException e) {
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX", "All blank"));
}
- if (c == -1) {
+ if (c == -1) {
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX", "All blank"));
}
if (c == '$') {
- // check for $subj $ext or $req
+ // check for $subj $ext or $req
try {
c = in.read();
} catch (IOException e) {
@@ -189,9 +190,9 @@ class AVAPattern {
if (c == 'r') {
try {
- if (in.read() != 'e' ||
- in.read() != 'q' ||
- in.read() != '.') {
+ if (in.read() != 'e' ||
+ in.read() != 'q' ||
+ in.read() != '.') {
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX",
"expecting $req in ava pattern"));
}
@@ -201,13 +202,13 @@ class AVAPattern {
}
mType = TYPE_REQ;
- //System.out.println("---- mtype $req");
+ // System.out.println("---- mtype $req");
} else if (c == 's') {
try {
- if (in.read() != 'u' ||
- in.read() != 'b' ||
- in.read() != 'j' ||
- in.read() != '.') {
+ if (in.read() != 'u' ||
+ in.read() != 'b' ||
+ in.read() != 'j' ||
+ in.read() != '.') {
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX",
"expecting $subj in ava pattern"));
}
@@ -217,12 +218,12 @@ class AVAPattern {
}
mType = TYPE_SUBJ;
- //System.out.println("----- mtype $subj");
+ // System.out.println("----- mtype $subj");
} else if (c == 'e') {
try {
- if (in.read() != 'x' ||
- in.read() != 't' ||
- in.read() != '.') {
+ if (in.read() != 'x' ||
+ in.read() != 't' ||
+ in.read() != '.') {
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX",
"expecting $ext in ava pattern"));
}
@@ -232,10 +233,10 @@ class AVAPattern {
}
mType = TYPE_EXT;
- //System.out.println("----- mtype $ext");
+ // System.out.println("----- mtype $ext");
} else {
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX",
- "unknown keyword. expecting $subj $ext or $req."));
+ "unknown keyword. expecting $subj $ext or $req."));
}
// get request attribute or
@@ -245,14 +246,14 @@ class AVAPattern {
StringBuffer valueBuf = new StringBuffer();
try {
- while ((c = in.read()) != ',' &&
- c != -1 && c != '.' && c != '+') {
- //System.out.println("mValue read "+(char)c);
+ while ((c = in.read()) != ',' &&
+ c != -1 && c != '.' && c != '+') {
+ // System.out.println("mValue read "+(char)c);
valueBuf.append((char) c);
}
if (c == '+' || c == ',') { // either ',' or '+'
- in.unread(c); // pushback last , or +
+ in.unread(c); // pushback last , or +
}
} catch (IOException e) {
throw new ELdapException(
@@ -260,11 +261,11 @@ class AVAPattern {
}
mValue = valueBuf.toString().trim();
- if (mValue.length() == 0) {
+ if (mValue.length() == 0) {
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX",
"$subj $ext or $req attribute name expected"));
}
- //System.out.println("----- mValue "+mValue);
+ // System.out.println("----- mValue "+mValue);
// get nth dn xxx not nth request attribute .
if (c == '.') {
@@ -272,13 +273,13 @@ class AVAPattern {
try {
while ((c = in.read()) != ',' && c != -1 && c != '.'
- && c != '+') {
- //System.out.println("mElement read "+(char)c);
+ && c != '+') {
+ // System.out.println("mElement read "+(char)c);
attrNumberBuf.append((char) c);
}
- if (c == ',' || c == '+') { // either ',' or '+'
- in.unread(c); // pushback last , or +
+ if (c == ',' || c == '+') { // either ',' or '+'
+ in.unread(c); // pushback last , or +
}
} catch (IOException e) {
throw new ELdapException(
@@ -304,7 +305,7 @@ class AVAPattern {
} else {
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX",
"Invalid format in nth element " +
- "$req $ext or $subj"));
+ "$req $ext or $subj"));
}
// get nth request attribute .
@@ -313,14 +314,14 @@ class AVAPattern {
try {
while ((c = in.read()) != ',' &&
- c != -1 && c != '+') {
- //System.out.println("mElement read "+
- // (char)c);
+ c != -1 && c != '+') {
+ // System.out.println("mElement read "+
+ // (char)c);
attrNumberBuf1.append((char) c);
}
- if (c != -1) { // either ',' or '+'
- in.unread(c); // pushback last , or +
+ if (c != -1) { // either ',' or '+'
+ in.unread(c); // pushback last , or +
}
} catch (IOException ex) {
throw new ELdapException(
@@ -328,28 +329,28 @@ class AVAPattern {
}
String attrNumber1 =
- attrNumberBuf1.toString().trim();
+ attrNumberBuf1.toString().trim();
if (attrNumber1.length() == 0) {
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX", "nth element $req or $ext expected"));
}
- try {
- mElement = Integer.parseInt(attrNumber1) - 1;
+ try {
+ mElement = Integer.parseInt(attrNumber1) - 1;
} catch (NumberFormatException ex) {
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX",
"Invalid format in nth element " +
- "$req or $ext."));
+ "$req or $ext."));
}
}
}
}
- //System.out.println("----- mElement "+mElement);
+ // System.out.println("----- mElement "+mElement);
} else {
// value is constant. treat as regular ava.
mType = TYPE_CONSTANT;
- // parse ava value.
+ // parse ava value.
StringBuffer valueBuf = new StringBuffer();
valueBuf.append((char) c);
@@ -361,7 +362,7 @@ class AVAPattern {
}
if (c == '+' || c == ',') { // either ',' or '+'
- in.unread(c); // pushback last , or +
+ in.unread(c); // pushback last , or +
}
} catch (IOException e) {
throw new ELdapException(
@@ -370,22 +371,19 @@ class AVAPattern {
mValue = valueBuf.toString().trim();
- /* try {
- * AVA ava = mLdapDNStrConverter.parseAVA(
- * valueBuf.toString());
- * mValue = ava.toLdapDNString();
- * //System.out.println("----- mValue "+mValue);
- * } catch (IOException e) {
- * throw new ECompSyntaxErr(e.toString());
- * }
+ /*
+ * try { AVA ava = mLdapDNStrConverter.parseAVA(
+ * valueBuf.toString()); mValue = ava.toLdapDNString();
+ * //System.out.println("----- mValue "+mValue); } catch
+ * (IOException e) { throw new ECompSyntaxErr(e.toString()); }
*/
}
}
public String formAVA(IRequest req,
- X500Name subject,
- CertificateExtensions extensions)
- throws ELdapException {
+ X500Name subject,
+ CertificateExtensions extensions)
+ throws ELdapException {
if (TYPE_CONSTANT.equals(mType)) {
return mValue;
}
@@ -393,11 +391,11 @@ class AVAPattern {
if (TYPE_SUBJ.equals(mType)) {
String dn = subject.toString();
- if (mTestDN != null) {
+ if (mTestDN != null) {
dn = mTestDN;
}
- //System.out.println("AVAPattern Using dn "+mTestDN);
+ // System.out.println("AVAPattern Using dn "+mTestDN);
String[] rdns = LDAPDN.explodeDN(dn, false);
String value = null;
@@ -410,8 +408,8 @@ class AVAPattern {
for (int j = 0; j < avas.length; j++) {
String[] exploded = explodeAVA(avas[j]);
- if (exploded[0].equalsIgnoreCase(mValue) &&
- ++nFound == mElement) {
+ if (exploded[0].equalsIgnoreCase(mValue) &&
+ ++nFound == mElement) {
value = exploded[1];
break;
}
@@ -431,10 +429,10 @@ class AVAPattern {
for (int i = 0; i < extensions.size(); i++) {
Extension ext = (Extension)
- extensions.elementAt(i);
+ extensions.elementAt(i);
String extName =
- OIDMap.getName(ext.getExtensionId());
+ OIDMap.getName(ext.getExtensionId());
int index = extName.lastIndexOf(".");
@@ -450,9 +448,9 @@ class AVAPattern {
SubjectAlternativeNameExtension.class.getSimpleName())) {
try {
GeneralNames subjectNames = (GeneralNames)
- ((SubjectAlternativeNameExtension)
+ ((SubjectAlternativeNameExtension)
ext).get(
- SubjectAlternativeNameExtension.SUBJECT_NAME);
+ SubjectAlternativeNameExtension.SUBJECT_NAME);
if (subjectNames.size() == 0) {
break;
@@ -461,11 +459,10 @@ class AVAPattern {
int j = 0;
for (Enumeration<GeneralNameInterface> n =
- subjectNames.elements();
- n.hasMoreElements();) {
+ subjectNames.elements(); n.hasMoreElements();) {
GeneralName gn = (GeneralName)
- n.nextElement();
+ n.nextElement();
String gname = gn.toString();
@@ -476,7 +473,7 @@ class AVAPattern {
}
String gType =
- gname.substring(0, index);
+ gname.substring(0, index);
if (mGNType != null) {
if (mGNType.equalsIgnoreCase(gType)) {
@@ -497,12 +494,12 @@ class AVAPattern {
j++;
}
}
- } catch (IOException e) {
+ } catch (IOException e) {
CMS.debug(
- "AVAPattern: Publishing attr not formed " +
- "from extension " +
- "-- no attr : " +
- mValue);
+ "AVAPattern: Publishing attr not formed " +
+ "from extension " +
+ "-- no attr : " +
+ mValue);
}
}
}
@@ -510,10 +507,10 @@ class AVAPattern {
}
CMS.debug(
- "AVAPattern: Publishing:attr not formed " +
- "from extension " +
- "-- no attr : " +
- mValue);
+ "AVAPattern: Publishing:attr not formed " +
+ "from extension " +
+ "-- no attr : " +
+ mValue);
return null;
}
@@ -522,8 +519,7 @@ class AVAPattern {
// mPrefix and mValue are looked up case-insensitive
String reqAttr = req.getExtDataInString(mPrefix, mValue);
if (reqAttr == null) {
- throw new
- ELdapException(
+ throw new ELdapException(
CMS.getUserMessage("CMS_LDAP_NO_REQUEST", mValue, ""));
}
@@ -550,10 +546,9 @@ class AVAPattern {
}
/**
- * Explode RDN into AVAs.
- * Does not handle escaped '+'
- * Java ldap library does not yet support multiple avas per rdn.
- * If RDN is malformed returns empty array.
+ * Explode RDN into AVAs. Does not handle escaped '+' Java ldap library does
+ * not yet support multiple avas per rdn. If RDN is malformed returns empty
+ * array.
*/
public static String[] explodeRDN(String rdn) {
int plus = rdn.indexOf('+');
@@ -578,9 +573,8 @@ class AVAPattern {
}
/**
- * Explode AVA into name and value.
- * Does not handle escaped '='
- * If AVA is malformed empty array is returned.
+ * Explode AVA into name and value. Does not handle escaped '=' If AVA is
+ * malformed empty array is returned.
*/
public static String[] explodeAVA(String ava) {
int equals = ava.indexOf('=');
@@ -593,4 +587,3 @@ class AVAPattern {
ava.substring(equals + 1).trim() };
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/publish/mappers/LdapCaSimpleMap.java b/pki/base/common/src/com/netscape/cms/publish/mappers/LdapCaSimpleMap.java
index 3cf1bca8..ee903016 100644
--- a/pki/base/common/src/com/netscape/cms/publish/mappers/LdapCaSimpleMap.java
+++ b/pki/base/common/src/com/netscape/cms/publish/mappers/LdapCaSimpleMap.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.publish.mappers;
-
import java.io.IOException;
import java.security.cert.X509Certificate;
import java.util.Locale;
@@ -48,20 +47,18 @@ import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.publish.ILdapMapper;
import com.netscape.certsrv.request.IRequest;
-
-/**
- * Maps a request to an entry in the LDAP server.
- * Takes a dnPattern to form the baseDN from the request attributes
- * and certificate subject name.Do a base search for the entry
- * in the directory to publish the cert or crl.
- * The restriction of this mapper is that the ldap dn components must
- * be part of certificate subject name or request attributes or constant.
- *
+/**
+ * Maps a request to an entry in the LDAP server. Takes a dnPattern to form the
+ * baseDN from the request attributes and certificate subject name.Do a base
+ * search for the entry in the directory to publish the cert or crl. The
+ * restriction of this mapper is that the ldap dn components must be part of
+ * certificate subject name or request attributes or constant.
+ *
* @version $Revision$, $Date$
*/
public class LdapCaSimpleMap implements ILdapMapper, IExtendedPluginInfo {
- protected static final String PROP_DNPATTERN = "dnPattern";
- protected static final String PROP_CREATECA = "createCAEntry";
+ protected static final String PROP_DNPATTERN = "dnPattern";
+ protected static final String PROP_CREATECA = "createCAEntry";
protected String mDnPattern = null;
protected boolean mCreateCAEntry = true;
@@ -72,20 +69,20 @@ public class LdapCaSimpleMap implements ILdapMapper, IExtendedPluginInfo {
/* the subject DN pattern */
protected MapDNPattern mPattern = null;
- /* the list of request attriubutes to retrieve*/
+ /* the list of request attriubutes to retrieve */
protected String[] mReqAttrs = null;
- /* the list of cert attriubutes to retrieve*/
+ /* the list of cert attriubutes to retrieve */
protected String[] mCertAttrs = null;
/* default dn pattern if left blank or not set in the config */
- public static final String DEFAULT_DNPATTERN =
- "UID=$req.HTTP_PARAMS.UID, OU=people, O=$subj.o, C=$subj.c";
+ public static final String DEFAULT_DNPATTERN =
+ "UID=$req.HTTP_PARAMS.UID, OU=people, O=$subj.o, C=$subj.c";
- /**
+ /**
* Constructor.
- *
- * @param dnPattern The base DN.
+ *
+ * @param dnPattern The base DN.
*/
public LdapCaSimpleMap(String dnPattern) {
try {
@@ -93,7 +90,7 @@ public class LdapCaSimpleMap implements ILdapMapper, IExtendedPluginInfo {
} catch (EBaseException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("OPERATION_ERROR", e.toString()));
}
-
+
}
/**
@@ -105,11 +102,11 @@ public class LdapCaSimpleMap implements ILdapMapper, IExtendedPluginInfo {
public String[] getExtendedPluginInfo(Locale locale) {
String params[] = {
"dnPattern;string;Describes how to form the Ldap Subject name in" +
- " the directory. Example 1: 'uid=CertMgr, o=Fedora'. Example 2:" +
- " 'uid=$req.HTTP_PARAMS.uid, E=$ext.SubjectAlternativeName.RFC822Name, ou=$subj.ou'. " +
- "$req means: take the attribute from the request. " +
- "$subj means: take the attribute from the certificate subject name. " +
- "$ext means: take the attribute from the certificate extension",
+ " the directory. Example 1: 'uid=CertMgr, o=Fedora'. Example 2:" +
+ " 'uid=$req.HTTP_PARAMS.uid, E=$ext.SubjectAlternativeName.RFC822Name, ou=$subj.ou'. " +
+ "$req means: take the attribute from the request. " +
+ "$subj means: take the attribute from the certificate subject name. " +
+ "$ext means: take the attribute from the certificate extension",
"createCAEntry;boolean;If checked, CA entry will be created automatically",
IExtendedPluginInfo.HELP_TOKEN + ";configuration-ldappublish-mapper-casimplemapper",
IExtendedPluginInfo.HELP_TEXT + ";Describes how to form the LDAP DN of the entry to publish to"
@@ -122,11 +119,11 @@ public class LdapCaSimpleMap implements ILdapMapper, IExtendedPluginInfo {
return mConfig;
}
- /**
+ /**
* for initializing from config store.
*/
- public void init(IConfigStore config)
- throws EBaseException {
+ public void init(IConfigStore config)
+ throws EBaseException {
mConfig = config;
String dnPattern = mConfig.getString(PROP_DNPATTERN);
@@ -138,12 +135,12 @@ public class LdapCaSimpleMap implements ILdapMapper, IExtendedPluginInfo {
* common initialization routine.
*/
protected void init(String dnPattern)
- throws EBaseException {
- if (mInited)
+ throws EBaseException {
+ if (mInited)
return;
mDnPattern = dnPattern;
- if (mDnPattern == null || mDnPattern.length() == 0)
+ if (mDnPattern == null || mDnPattern.length() == 0)
mDnPattern = DEFAULT_DNPATTERN;
try {
mPattern = new MapDNPattern(mDnPattern);
@@ -151,7 +148,7 @@ public class LdapCaSimpleMap implements ILdapMapper, IExtendedPluginInfo {
String[] mCertAttrs = mPattern.getCertAttrs();
} catch (ELdapException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_DN_PATTERN_INIT", dnPattern, e.toString()));
- throw new EBaseException("falied to init with pattern " +
+ throw new EBaseException("falied to init with pattern " +
dnPattern + " " + e);
}
@@ -159,29 +156,29 @@ public class LdapCaSimpleMap implements ILdapMapper, IExtendedPluginInfo {
}
/**
- * Maps a X500 subject name to LDAP entry.
- * Uses DN pattern to form a DN for a LDAP base search.
+ * Maps a X500 subject name to LDAP entry. Uses DN pattern to form a DN for
+ * a LDAP base search.
*
- * @param conn the LDAP connection.
- * @param obj the object to map.
+ * @param conn the LDAP connection.
+ * @param obj the object to map.
* @exception ELdapException if any LDAP exceptions occured.
- */
+ */
public String map(LDAPConnection conn, Object obj)
- throws ELdapException {
+ throws ELdapException {
return map(conn, null, obj);
}
/**
- * Maps a X500 subject name to LDAP entry.
- * Uses DN pattern to form a DN for a LDAP base search.
+ * Maps a X500 subject name to LDAP entry. Uses DN pattern to form a DN for
+ * a LDAP base search.
*
- * @param conn the LDAP connection.
- * @param req the request to map.
- * @param obj the object to map.
+ * @param conn the LDAP connection.
+ * @param req the request to map.
+ * @param obj the object to map.
* @exception ELdapException if any LDAP exceptions occured.
- */
+ */
public String map(LDAPConnection conn, IRequest req, Object obj)
- throws ELdapException {
+ throws ELdapException {
if (conn == null)
return null;
String dn = null;
@@ -204,26 +201,26 @@ public class LdapCaSimpleMap implements ILdapMapper, IExtendedPluginInfo {
String[] attrs = new String[] { LDAPv3.NO_ATTRS };
log(ILogger.LL_INFO, "searching for dn: " + dn + " filter:"
- + filter + " scope: base");
+ + filter + " scope: base");
- LDAPSearchResults results =
- conn.search(dn, scope, filter, attrs, false);
+ LDAPSearchResults results =
+ conn.search(dn, scope, filter, attrs, false);
LDAPEntry entry = results.next();
if (results.hasMoreElements()) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_MORE_THAN_ONE_ENTRY", dn,
- ((req == null) ? "" : req.getRequestId().toString())));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("PUBLISH_MORE_THAN_ONE_ENTRY", dn,
+ ((req == null) ? "" : req.getRequestId().toString())));
throw new ELdapException(
- CMS.getUserMessage("CMS_LDAP_MORE_THAN_ONE_ENTRY",
- ((req == null) ? "" : req.getRequestId().toString())));
+ CMS.getUserMessage("CMS_LDAP_MORE_THAN_ONE_ENTRY",
+ ((req == null) ? "" : req.getRequestId().toString())));
}
if (entry != null)
return entry.getDN();
else {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_ENTRY_NOT_FOUND", dn,
- ((req == null) ? "" : req.getRequestId().toString())));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("PUBLISH_ENTRY_NOT_FOUND", dn,
+ ((req == null) ? "" : req.getRequestId().toString())));
throw new ELdapException(CMS.getUserMessage("CMS_LDAP_NO_MATCH_FOUND",
"null entry"));
}
@@ -232,7 +229,7 @@ public class LdapCaSimpleMap implements ILdapMapper, IExtendedPluginInfo {
// need to intercept this because message from LDAP is
// "DSA is unavailable" which confuses with DSA PKI.
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
+ CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
throw new ELdapServerDownException(CMS.getUserMessage("CMS_LDAP_SERVER_UNAVAILABLE", conn.getHost(), "" + conn.getPort()));
} else if (e.getLDAPResultCode() == LDAPException.NO_SUCH_OBJECT && mCreateCAEntry) {
try {
@@ -246,8 +243,7 @@ public class LdapCaSimpleMap implements ILdapMapper, IExtendedPluginInfo {
} else {
log(ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_CA_ENTRY_NOT_CREATED1"));
}
- throw new
- ELdapException(CMS.getUserMessage("CMS_LDAP_CREATE_CA_FAILED", dn));
+ throw new ELdapException(CMS.getUserMessage("CMS_LDAP_CREATE_CA_FAILED", dn));
}
} else {
log(ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_DN_MAP_EXCEPTION", dn, e.toString()));
@@ -260,19 +256,19 @@ public class LdapCaSimpleMap implements ILdapMapper, IExtendedPluginInfo {
}
private void createCAEntry(LDAPConnection conn, String dn)
- throws LDAPException {
+ throws LDAPException {
LDAPAttributeSet attrs = new LDAPAttributeSet();
// OID 2.5.6.16
- String caOc[] = new String[] {"top",
- "person",
- "organizationalPerson",
- "inetOrgPerson"};
-
- String oOc[] = {"top",
- "organization"};
- String oiOc[] = {"top",
- "organizationalunit"};
-
+ String caOc[] = new String[] { "top",
+ "person",
+ "organizationalPerson",
+ "inetOrgPerson" };
+
+ String oOc[] = { "top",
+ "organization" };
+ String oiOc[] = { "top",
+ "organizationalunit" };
+
DN dnobj = new DN(dn);
String attrval[] = dnobj.explodeDN(true);
@@ -286,6 +282,7 @@ public class LdapCaSimpleMap implements ILdapMapper, IExtendedPluginInfo {
/**
* form a dn from component in the request and cert subject name
+ *
* @param req The request
* @param obj The certificate or crl
*/
@@ -296,13 +293,13 @@ public class LdapCaSimpleMap implements ILdapMapper, IExtendedPluginInfo {
try {
X509Certificate cert = (X509Certificate) obj;
- subjectDN =
+ subjectDN =
(X500Name) ((X509Certificate) cert).getSubjectDN();
CMS.debug("LdapCaSimpleMap: cert subject dn:" + subjectDN.toString());
X509CertInfo info = (X509CertInfo)
- ((X509CertImpl) cert).get(
- X509CertImpl.NAME + "." + X509CertImpl.INFO);
+ ((X509CertImpl) cert).get(
+ X509CertImpl.NAME + "." + X509CertImpl.INFO);
certExt = (CertificateExtensions) info.get(
CertificateExtensions.NAME);
@@ -316,12 +313,12 @@ public class LdapCaSimpleMap implements ILdapMapper, IExtendedPluginInfo {
try {
X509CRLImpl crl = (X509CRLImpl) obj;
- subjectDN =
+ subjectDN =
(X500Name) ((X509CRLImpl) crl).getIssuerDN();
CMS.debug("LdapCaSimpleMap: crl issuer dn: " +
- subjectDN.toString());
- }catch (ClassCastException ex) {
+ subjectDN.toString());
+ } catch (ClassCastException ex) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_PUBLISH_OBJ_NOT_SUPPORTED",
((req == null) ? "" : req.getRequestId().toString())));
return null;
@@ -332,9 +329,9 @@ public class LdapCaSimpleMap implements ILdapMapper, IExtendedPluginInfo {
return dn;
} catch (ELdapException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_CANT_FORM_DN",
- ((req == null) ? "" : req.getRequestId().toString()), e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("PUBLISH_CANT_FORM_DN",
+ ((req == null) ? "" : req.getRequestId().toString()), e.toString()));
throw new EBaseException("falied to form dn for request: " +
((req == null) ? "" : req.getRequestId().toString()) + " " + e);
}
@@ -362,9 +359,9 @@ public class LdapCaSimpleMap implements ILdapMapper, IExtendedPluginInfo {
try {
if (mDnPattern == null) {
v.addElement(PROP_DNPATTERN + "=");
- }else {
+ } else {
v.addElement(PROP_DNPATTERN + "=" +
- mConfig.getString(PROP_DNPATTERN));
+ mConfig.getString(PROP_DNPATTERN));
}
v.addElement(PROP_CREATECA + "=" + mConfig.getBoolean(PROP_CREATECA, true));
} catch (Exception e) {
@@ -374,8 +371,7 @@ public class LdapCaSimpleMap implements ILdapMapper, IExtendedPluginInfo {
private void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_LDAP, level,
- "LdapCaSimpleMapper: " + msg);
+ "LdapCaSimpleMapper: " + msg);
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/publish/mappers/LdapCertCompsMap.java b/pki/base/common/src/com/netscape/cms/publish/mappers/LdapCertCompsMap.java
index 17c562ce..0b510472 100644
--- a/pki/base/common/src/com/netscape/cms/publish/mappers/LdapCertCompsMap.java
+++ b/pki/base/common/src/com/netscape/cms/publish/mappers/LdapCertCompsMap.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.publish.mappers;
-
import java.security.cert.CRLException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
@@ -34,22 +33,20 @@ import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.publish.ILdapMapper;
import com.netscape.certsrv.request.IRequest;
-
-/**
- * Maps a X509 certificate to a LDAP entry using AVAs in the certificate's
- * subject name to form the ldap search dn and filter.
- * Takes a optional root search dn.
- * The DN comps are used to form a LDAP entry to begin a subtree search.
- * The filter comps are used to form a search filter for the subtree.
- * If none of the DN comps matched, baseDN is used for the subtree.
- * If the baseDN is null and none of the DN comps matched, it is an error.
- * If none of the DN comps and filter comps matched, it is an error.
- * If just the filter comps is null, a base search is performed.
- *
+/**
+ * Maps a X509 certificate to a LDAP entry using AVAs in the certificate's
+ * subject name to form the ldap search dn and filter. Takes a optional root
+ * search dn. The DN comps are used to form a LDAP entry to begin a subtree
+ * search. The filter comps are used to form a search filter for the subtree. If
+ * none of the DN comps matched, baseDN is used for the subtree. If the baseDN
+ * is null and none of the DN comps matched, it is an error. If none of the DN
+ * comps and filter comps matched, it is an error. If just the filter comps is
+ * null, a base search is performed.
+ *
* @version $Revision$, $Date$
*/
-public class LdapCertCompsMap
- extends LdapDNCompsMap implements ILdapMapper {
+public class LdapCertCompsMap
+ extends LdapDNCompsMap implements ILdapMapper {
ILogger mLogger = CMS.getLogger();
public LdapCertCompsMap() {
@@ -57,22 +54,22 @@ public class LdapCertCompsMap
// via configuration
}
- /**
+ /**
* Constructor.
- *
- * The DN comps are used to form a LDAP entry to begin a subtree search.
- * The filter comps are used to form a search filter for the subtree.
- * If none of the DN comps matched, baseDN is used for the subtree.
- * If the baseDN is null and none of the DN comps matched, it is an error.
- * If none of the DN comps and filter comps matched, it is an error.
- * If just the filter comps is null, a base search is performed.
*
- * @param baseDN The base DN.
+ * The DN comps are used to form a LDAP entry to begin a subtree search. The
+ * filter comps are used to form a search filter for the subtree. If none of
+ * the DN comps matched, baseDN is used for the subtree. If the baseDN is
+ * null and none of the DN comps matched, it is an error. If none of the DN
+ * comps and filter comps matched, it is an error. If just the filter comps
+ * is null, a base search is performed.
+ *
+ * @param baseDN The base DN.
* @param dnComps Components to form the LDAP base dn for search.
* @param filterComps Components to form the LDAP search filter.
*/
public LdapCertCompsMap(String baseDN, ObjectIdentifier[] dnComps,
- ObjectIdentifier[] filterComps) {
+ ObjectIdentifier[] filterComps) {
init(baseDN, dnComps, filterComps);
}
@@ -99,40 +96,38 @@ public class LdapCertCompsMap
/**
* constructor using non-standard certificate attribute.
*/
- public LdapCertCompsMap(String certAttr, String baseDN,
- ObjectIdentifier[] dnComps,
- ObjectIdentifier[] filterComps) {
+ public LdapCertCompsMap(String certAttr, String baseDN,
+ ObjectIdentifier[] dnComps,
+ ObjectIdentifier[] filterComps) {
super(certAttr, baseDN, dnComps, filterComps);
}
protected void init(String baseDN, ObjectIdentifier[] dnComps,
- ObjectIdentifier[] filterComps) {
+ ObjectIdentifier[] filterComps) {
super.init(baseDN, dnComps, filterComps);
}
/**
- * Maps a certificate to LDAP entry.
- * Uses DN components and filter components to form a DN and
- * filter for a LDAP search.
- * If the formed DN is null the baseDN will be used.
- * If the formed DN is null and baseDN is null an error is thrown.
- * If the filter is null a base search is performed.
- * If both are null an error is thrown.
+ * Maps a certificate to LDAP entry. Uses DN components and filter
+ * components to form a DN and filter for a LDAP search. If the formed DN is
+ * null the baseDN will be used. If the formed DN is null and baseDN is null
+ * an error is thrown. If the filter is null a base search is performed. If
+ * both are null an error is thrown.
*
* @param conn - the LDAP connection.
* @param obj - the X509Certificate.
*/
public String
- map(LDAPConnection conn, Object obj)
- throws ELdapException {
+ map(LDAPConnection conn, Object obj)
+ throws ELdapException {
if (conn == null)
return null;
try {
X509Certificate cert = (X509Certificate) obj;
String result = null;
// form dn and filter for search.
- X500Name subjectDN =
- (X500Name) ((X509Certificate) cert).getSubjectDN();
+ X500Name subjectDN =
+ (X500Name) ((X509Certificate) cert).getSubjectDN();
CMS.debug("LdapCertCompsMap: " + subjectDN.toString());
@@ -148,8 +143,8 @@ public class LdapCertCompsMap
try {
X509CRLImpl crl = (X509CRLImpl) obj;
String result = null;
- X500Name issuerDN =
- (X500Name) ((X509CRLImpl) crl).getIssuerDN();
+ X500Name issuerDN =
+ (X500Name) ((X509CRLImpl) crl).getIssuerDN();
CMS.debug("LdapCertCompsMap: " + issuerDN.toString());
@@ -168,14 +163,13 @@ public class LdapCertCompsMap
}
public String map(LDAPConnection conn, IRequest req, Object obj)
- throws ELdapException {
+ throws ELdapException {
return map(conn, obj);
}
private void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_LDAP, level,
- "LdapCertCompsMap: " + msg);
+ "LdapCertCompsMap: " + msg);
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/publish/mappers/LdapCertExactMap.java b/pki/base/common/src/com/netscape/cms/publish/mappers/LdapCertExactMap.java
index 7eded9cd..d8e95d60 100644
--- a/pki/base/common/src/com/netscape/cms/publish/mappers/LdapCertExactMap.java
+++ b/pki/base/common/src/com/netscape/cms/publish/mappers/LdapCertExactMap.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.publish.mappers;
-
import java.security.cert.X509Certificate;
import java.util.Locale;
import java.util.Vector;
@@ -41,11 +40,10 @@ import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.publish.ILdapMapper;
import com.netscape.certsrv.request.IRequest;
-
-/**
- * Maps a X509 certificate to a LDAP entry by using the subject name
- * of the certificate as the LDAP entry DN.
- *
+/**
+ * Maps a X509 certificate to a LDAP entry by using the subject name of the
+ * certificate as the LDAP entry DN.
+ *
* @version $Revision$, $Date$
*/
public class LdapCertExactMap implements ILdapMapper, IExtendedPluginInfo {
@@ -64,7 +62,7 @@ public class LdapCertExactMap implements ILdapMapper, IExtendedPluginInfo {
}
public void init(IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
if (mInited == true)
return;
mConfig = config;
@@ -74,9 +72,9 @@ public class LdapCertExactMap implements ILdapMapper, IExtendedPluginInfo {
public String[] getExtendedPluginInfo(Locale locale) {
String[] params = {
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-ldappublish-mapper-certexactmapper",
+ ";configuration-ldappublish-mapper-certexactmapper",
IExtendedPluginInfo.HELP_TEXT +
- ";Literally uses the subject name of the certificate as the DN to publish to"
+ ";Literally uses the subject name of the certificate as the DN to publish to"
};
return params;
@@ -95,7 +93,7 @@ public class LdapCertExactMap implements ILdapMapper, IExtendedPluginInfo {
return v;
}
-
+
public Vector<String> getInstanceParams() {
Vector<String> v = new Vector<String>();
@@ -103,15 +101,15 @@ public class LdapCertExactMap implements ILdapMapper, IExtendedPluginInfo {
}
/**
- * Finds the entry for the certificate by looking for the cert
- * subject name in the subject name attribute.
+ * Finds the entry for the certificate by looking for the cert subject name
+ * in the subject name attribute.
*
* @param conn - the LDAP connection.
* @param obj - the X509Certificate.
- */
+ */
public String
- map(LDAPConnection conn, Object obj)
- throws ELdapException {
+ map(LDAPConnection conn, Object obj)
+ throws ELdapException {
if (conn == null)
return null;
@@ -120,7 +118,7 @@ public class LdapCertExactMap implements ILdapMapper, IExtendedPluginInfo {
try {
X509Certificate cert = (X509Certificate) obj;
- subjectDN =
+ subjectDN =
(X500Name) ((X509Certificate) cert).getSubjectDN();
CMS.debug("LdapCertExactMap: cert subject dn:" + subjectDN.toString());
@@ -128,12 +126,12 @@ public class LdapCertExactMap implements ILdapMapper, IExtendedPluginInfo {
try {
X509CRLImpl crl = (X509CRLImpl) obj;
- subjectDN =
+ subjectDN =
(X500Name) ((X509CRLImpl) crl).getIssuerDN();
CMS.debug("LdapCertExactMap: crl issuer dn: " +
- subjectDN.toString());
- }catch (ClassCastException ex) {
+ subjectDN.toString());
+ } catch (ClassCastException ex) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_NOT_SUPPORTED_OBJECT"));
return null;
}
@@ -141,19 +139,19 @@ public class LdapCertExactMap implements ILdapMapper, IExtendedPluginInfo {
try {
boolean hasCert = false;
boolean hasSubjectName = false;
- String[] attrs = new String[] { LDAPv3.NO_ATTRS };
+ String[] attrs = new String[] { LDAPv3.NO_ATTRS };
log(ILogger.LL_INFO, "Searching for " + subjectDN.toString());
- LDAPSearchResults results =
- conn.search(subjectDN.toString(), LDAPv2.SCOPE_BASE,
- "(objectclass=*)", attrs, false);
-
+ LDAPSearchResults results =
+ conn.search(subjectDN.toString(), LDAPv2.SCOPE_BASE,
+ "(objectclass=*)", attrs, false);
+
LDAPEntry entry = results.next();
if (results.hasMoreElements()) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_MORE_THAN_ONE_ENTRY", "", subjectDN.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("PUBLISH_MORE_THAN_ONE_ENTRY", "", subjectDN.toString()));
}
if (entry != null) {
log(ILogger.LL_INFO, "entry found");
@@ -165,7 +163,7 @@ public class LdapCertExactMap implements ILdapMapper, IExtendedPluginInfo {
// need to intercept this because message from LDAP is
// "DSA is unavailable" which confuses with DSA PKI.
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
+ CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
throw new ELdapServerDownException(CMS.getUserMessage("CMS_LDAP_SERVER_UNAVAILABLE", conn.getHost(), "" + conn.getPort()));
} else {
log(ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_DN_MAP_EXCEPTION", e.toString()));
@@ -174,30 +172,23 @@ public class LdapCertExactMap implements ILdapMapper, IExtendedPluginInfo {
}
/*
- catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_CANT_GET_SUBJECT", e.toString()));
- throw new ELdapException(
- LdapResources.GET_CERT_SUBJECT_DN_FAILED, e);
- }
- catch (CertificateEncodingException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_CANT_DECODE_CERT", e.toString()));
- throw new ELdapException(
- LdapResources.GET_DER_ENCODED_CERT_FAILED, e);
- }
+ * catch (IOException e) { log(ILogger.LL_FAILURE,
+ * CMS.getLogMessage("PUBLISH_CANT_GET_SUBJECT", e.toString())); throw
+ * new ELdapException( LdapResources.GET_CERT_SUBJECT_DN_FAILED, e); }
+ * catch (CertificateEncodingException e) { log(ILogger.LL_FAILURE,
+ * CMS.getLogMessage("PUBLISH_CANT_DECODE_CERT", e.toString())); throw
+ * new ELdapException( LdapResources.GET_DER_ENCODED_CERT_FAILED, e); }
*/
}
public String map(LDAPConnection conn, IRequest req, Object obj)
- throws ELdapException {
+ throws ELdapException {
return map(conn, obj);
}
private void log(int level, String msg) {
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_LDAP, level,
- "LdapCertExactMap: " + msg);
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_LDAP, level,
+ "LdapCertExactMap: " + msg);
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/publish/mappers/LdapCertSubjMap.java b/pki/base/common/src/com/netscape/cms/publish/mappers/LdapCertSubjMap.java
index 42db2b27..a999cd0f 100644
--- a/pki/base/common/src/com/netscape/cms/publish/mappers/LdapCertSubjMap.java
+++ b/pki/base/common/src/com/netscape/cms/publish/mappers/LdapCertSubjMap.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.publish.mappers;
-
import java.security.cert.X509Certificate;
import java.util.Locale;
import java.util.Vector;
@@ -41,11 +40,10 @@ import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.publish.ILdapMapper;
import com.netscape.certsrv.request.IRequest;
-
-/**
- * Maps a X509 certificate to a LDAP entry by finding an LDAP entry
- * which has an attribute whose contents are equal to the cert subject name.
- *
+/**
+ * Maps a X509 certificate to a LDAP entry by finding an LDAP entry which has an
+ * attribute whose contents are equal to the cert subject name.
+ *
* @version $Revision$, $Date$
*/
public class LdapCertSubjMap implements ILdapMapper, IExtendedPluginInfo {
@@ -64,8 +62,9 @@ public class LdapCertSubjMap implements ILdapMapper, IExtendedPluginInfo {
/**
* constructs a certificate subject name mapper with search base.
- * @param searchBase the dn to start searching for the certificate
- * subject name.
+ *
+ * @param searchBase the dn to start searching for the certificate subject
+ * name.
*/
public LdapCertSubjMap(String searchBase) {
if (searchBase == null)
@@ -82,10 +81,10 @@ public class LdapCertSubjMap implements ILdapMapper, IExtendedPluginInfo {
* @param certSubjNameAttr attribute for certificate subject names.
* @param certAttr attribute to find certificate.
*/
- public LdapCertSubjMap(String searchBase,
- String certSubjNameAttr, String certAttr) {
- if (searchBase == null ||
- certSubjNameAttr == null || certAttr == null)
+ public LdapCertSubjMap(String searchBase,
+ String certSubjNameAttr, String certAttr) {
+ if (searchBase == null ||
+ certSubjNameAttr == null || certAttr == null)
throw new IllegalArgumentException(
"a null argument to constructor " + this.getClass().getName());
mCertSubjNameAttr = certSubjNameAttr;
@@ -93,10 +92,10 @@ public class LdapCertSubjMap implements ILdapMapper, IExtendedPluginInfo {
mInited = true;
}
- public LdapCertSubjMap(String searchBase,
- String certSubjNameAttr, String certAttr, boolean useAllEntries) {
- if (searchBase == null ||
- certSubjNameAttr == null || certAttr == null)
+ public LdapCertSubjMap(String searchBase,
+ String certSubjNameAttr, String certAttr, boolean useAllEntries) {
+ if (searchBase == null ||
+ certSubjNameAttr == null || certAttr == null)
throw new IllegalArgumentException(
"a null argument to constructor " + this.getClass().getName());
mCertSubjNameAttr = certSubjNameAttr;
@@ -128,15 +127,15 @@ public class LdapCertSubjMap implements ILdapMapper, IExtendedPluginInfo {
"searchBase;string;Base DN to search from",
"useAllEntries;boolean;Use all entries for publishing",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-ldappublish-mapper-certsubjmapper",
+ ";configuration-ldappublish-mapper-certsubjmapper",
IExtendedPluginInfo.HELP_TEXT +
- ";This plugin assumes you want to publish to an LDAP entry which has " +
- "an attribute whose contents are equal to the cert subject name"
+ ";This plugin assumes you want to publish to an LDAP entry which has " +
+ "an attribute whose contents are equal to the cert subject name"
};
return params;
}
-
+
public Vector<String> getInstanceParams() {
Vector<String> v = new Vector<String>();
@@ -159,7 +158,7 @@ public class LdapCertSubjMap implements ILdapMapper, IExtendedPluginInfo {
}
public void init(IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
if (mInited == true)
return;
mConfig = config;
@@ -171,15 +170,15 @@ public class LdapCertSubjMap implements ILdapMapper, IExtendedPluginInfo {
}
/**
- * Finds the entry for the certificate by looking for the cert
- * subject name in the subject name attribute.
+ * Finds the entry for the certificate by looking for the cert subject name
+ * in the subject name attribute.
*
* @param conn - the LDAP connection.
* @param obj - the X509Certificate.
- */
+ */
public String
- map(LDAPConnection conn, Object obj)
- throws ELdapException {
+ map(LDAPConnection conn, Object obj)
+ throws ELdapException {
if (conn == null)
return null;
X500Name subjectDN = null;
@@ -187,7 +186,7 @@ public class LdapCertSubjMap implements ILdapMapper, IExtendedPluginInfo {
try {
X509Certificate cert = (X509Certificate) obj;
- subjectDN =
+ subjectDN =
(X500Name) ((X509Certificate) cert).getSubjectDN();
CMS.debug("LdapCertSubjMap: cert subject dn:" + subjectDN.toString());
@@ -195,12 +194,12 @@ public class LdapCertSubjMap implements ILdapMapper, IExtendedPluginInfo {
try {
X509CRLImpl crl = (X509CRLImpl) obj;
- subjectDN =
+ subjectDN =
(X500Name) ((X509CRLImpl) crl).getIssuerDN();
CMS.debug("LdapCertSubjMap: crl issuer dn: " +
- subjectDN.toString());
- }catch (ClassCastException ex) {
+ subjectDN.toString());
+ } catch (ClassCastException ex) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_NOT_SUPPORTED_OBJECT"));
return null;
}
@@ -208,20 +207,20 @@ public class LdapCertSubjMap implements ILdapMapper, IExtendedPluginInfo {
try {
boolean hasCert = false;
boolean hasSubjectName = false;
- String[] attrs = new String[] { LDAPv3.NO_ATTRS };
+ String[] attrs = new String[] { LDAPv3.NO_ATTRS };
log(ILogger.LL_INFO, "search " + mSearchBase +
- " (" + mCertSubjNameAttr + "=" + subjectDN + ") " + mCertSubjNameAttr);
+ " (" + mCertSubjNameAttr + "=" + subjectDN + ") " + mCertSubjNameAttr);
+
+ LDAPSearchResults results =
+ conn.search(mSearchBase, LDAPv2.SCOPE_SUB,
+ "(" + mCertSubjNameAttr + "=" + subjectDN + ")", attrs, false);
- LDAPSearchResults results =
- conn.search(mSearchBase, LDAPv2.SCOPE_SUB,
- "(" + mCertSubjNameAttr + "=" + subjectDN + ")", attrs, false);
-
LDAPEntry entry = results.next();
if (results.hasMoreElements()) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_MORE_THAN_ONE_ENTRY", "", subjectDN.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("PUBLISH_MORE_THAN_ONE_ENTRY", "", subjectDN.toString()));
}
if (entry != null) {
log(ILogger.LL_INFO, "entry found");
@@ -233,38 +232,32 @@ public class LdapCertSubjMap implements ILdapMapper, IExtendedPluginInfo {
// need to intercept this because message from LDAP is
// "DSA is unavailable" which confuses with DSA PKI.
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
+ CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
throw new ELdapServerDownException(CMS.getUserMessage("CMS_LDAP_SERVER_UNAVAILABLE", conn.getHost(), "" + conn.getPort()));
} else {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_DN_MAP_EXCEPTION", "LDAPException", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("PUBLISH_DN_MAP_EXCEPTION", "LDAPException", e.toString()));
throw new ELdapException(CMS.getUserMessage("CMS_LDAP_NO_MATCH_FOUND", e.toString()));
}
}
/*
- catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_CANT_GET_SUBJECT", e.toString()));
- throw new ELdapException(
- LdapResources.GET_CERT_SUBJECT_DN_FAILED, e);
- }
- catch (CertificateEncodingException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_CANT_DECODE_CERT", e.toString()));
- throw new ELdapException(
- LdapResources.GET_DER_ENCODED_CERT_FAILED, e);
- }
+ * catch (IOException e) { log(ILogger.LL_FAILURE,
+ * CMS.getLogMessage("PUBLISH_CANT_GET_SUBJECT", e.toString())); throw
+ * new ELdapException( LdapResources.GET_CERT_SUBJECT_DN_FAILED, e); }
+ * catch (CertificateEncodingException e) { log(ILogger.LL_FAILURE,
+ * CMS.getLogMessage("PUBLISH_CANT_DECODE_CERT", e.toString())); throw
+ * new ELdapException( LdapResources.GET_DER_ENCODED_CERT_FAILED, e); }
*/
}
public String map(LDAPConnection conn, IRequest req, Object obj)
- throws ELdapException {
+ throws ELdapException {
return map(conn, obj);
}
public Vector<String> mapAll(LDAPConnection conn, Object obj)
- throws ELdapException {
+ throws ELdapException {
Vector<String> v = new Vector<String>();
if (conn == null)
@@ -282,20 +275,20 @@ public class LdapCertSubjMap implements ILdapMapper, IExtendedPluginInfo {
try {
boolean hasCert = false;
boolean hasSubjectName = false;
- String[] attrs = new String[] { LDAPv3.NO_ATTRS };
+ String[] attrs = new String[] { LDAPv3.NO_ATTRS };
log(ILogger.LL_INFO, "search " + mSearchBase +
- " (" + mCertSubjNameAttr + "=" + subjectDN + ") " + mCertSubjNameAttr);
+ " (" + mCertSubjNameAttr + "=" + subjectDN + ") " + mCertSubjNameAttr);
+
+ LDAPSearchResults results =
+ conn.search(mSearchBase, LDAPv2.SCOPE_SUB,
+ "(" + mCertSubjNameAttr + "=" + subjectDN + ")", attrs, false);
- LDAPSearchResults results =
- conn.search(mSearchBase, LDAPv2.SCOPE_SUB,
- "(" + mCertSubjNameAttr + "=" + subjectDN + ")", attrs, false);
-
while (results.hasMoreElements()) {
LDAPEntry entry = results.next();
String dn = entry.getDN();
v.addElement(dn);
- CMS.debug("LdapCertSubjMap: dn="+dn);
+ CMS.debug("LdapCertSubjMap: dn=" + dn);
}
CMS.debug("LdapCertSubjMap: Number of entries: " + v.size());
} catch (LDAPException e) {
@@ -303,11 +296,11 @@ public class LdapCertSubjMap implements ILdapMapper, IExtendedPluginInfo {
// need to intercept this because message from LDAP is
// "DSA is unavailable" which confuses with DSA PKI.
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
+ CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
throw new ELdapServerDownException(CMS.getUserMessage("CMS_LDAP_SERVER_UNAVAILABLE", conn.getHost(), "" + conn.getPort()));
} else {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_DN_MAP_EXCEPTION", "LDAPException", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("PUBLISH_DN_MAP_EXCEPTION", "LDAPException", e.toString()));
throw new ELdapException(CMS.getUserMessage("CMS_LDAP_NO_MATCH_FOUND", e.toString()));
}
}
@@ -316,13 +309,13 @@ public class LdapCertSubjMap implements ILdapMapper, IExtendedPluginInfo {
}
public Vector<String> mapAll(LDAPConnection conn, IRequest req, Object obj)
- throws ELdapException {
+ throws ELdapException {
return mapAll(conn, obj);
}
private void log(int level, String msg) {
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_LDAP, level,
- "LdapCertSubjMap: " + msg);
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_LDAP, level,
+ "LdapCertSubjMap: " + msg);
}
/**
@@ -344,4 +337,3 @@ public class LdapCertSubjMap implements ILdapMapper, IExtendedPluginInfo {
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/publish/mappers/LdapCrlIssuerCompsMap.java b/pki/base/common/src/com/netscape/cms/publish/mappers/LdapCrlIssuerCompsMap.java
index 40283e98..4155cad4 100644
--- a/pki/base/common/src/com/netscape/cms/publish/mappers/LdapCrlIssuerCompsMap.java
+++ b/pki/base/common/src/com/netscape/cms/publish/mappers/LdapCrlIssuerCompsMap.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.publish.mappers;
-
import java.security.cert.CRLException;
import java.util.Vector;
@@ -32,16 +31,14 @@ import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.publish.ILdapMapper;
import com.netscape.certsrv.request.IRequest;
-
-/**
- * Default crl mapper.
- * maps the crl to a ldap entry by using components in the issuer name
- * to find the CA's entry.
- *
+/**
+ * Default crl mapper. maps the crl to a ldap entry by using components in the
+ * issuer name to find the CA's entry.
+ *
* @version $Revision$, $Date$
*/
-public class LdapCrlIssuerCompsMap
- extends LdapDNCompsMap implements ILdapMapper {
+public class LdapCrlIssuerCompsMap
+ extends LdapDNCompsMap implements ILdapMapper {
ILogger mLogger = CMS.getLogger();
public LdapCrlIssuerCompsMap() {
@@ -49,31 +46,31 @@ public class LdapCrlIssuerCompsMap
// via configuration
}
- /**
+ /**
* Constructor.
- *
- * The DN comps are used to form a LDAP entry to begin a subtree search.
- * The filter comps are used to form a search filter for the subtree.
- * If none of the DN comps matched, baseDN is used for the subtree.
- * If the baseDN is null and none of the DN comps matched, it is an error.
- * If none of the DN comps and filter comps matched, it is an error.
- * If just the filter comps is null, a base search is performed.
*
- * @param baseDN The base DN.
+ * The DN comps are used to form a LDAP entry to begin a subtree search. The
+ * filter comps are used to form a search filter for the subtree. If none of
+ * the DN comps matched, baseDN is used for the subtree. If the baseDN is
+ * null and none of the DN comps matched, it is an error. If none of the DN
+ * comps and filter comps matched, it is an error. If just the filter comps
+ * is null, a base search is performed.
+ *
+ * @param baseDN The base DN.
* @param dnComps Components to form the LDAP base dn for search.
* @param filterComps Components to form the LDAP search filter.
*/
public LdapCrlIssuerCompsMap(String baseDN, ObjectIdentifier[] dnComps,
- ObjectIdentifier[] filterComps) {
+ ObjectIdentifier[] filterComps) {
init(baseDN, dnComps, filterComps);
}
/**
* constructor using non-standard certificate attribute.
*/
- public LdapCrlIssuerCompsMap(String crlAttr, String baseDN,
- ObjectIdentifier[] dnComps,
- ObjectIdentifier[] filterComps) {
+ public LdapCrlIssuerCompsMap(String crlAttr, String baseDN,
+ ObjectIdentifier[] dnComps,
+ ObjectIdentifier[] filterComps) {
super(crlAttr, baseDN, dnComps, filterComps);
}
@@ -88,7 +85,7 @@ public class LdapCrlIssuerCompsMap
public Vector getDefaultParams() {
Vector v = super.getDefaultParams();
- //v.addElement("crlAttr=" + LdapCrlPublisher.LDAP_CRL_ATTR);
+ // v.addElement("crlAttr=" + LdapCrlPublisher.LDAP_CRL_ATTR);
return v;
}
@@ -99,35 +96,33 @@ public class LdapCrlIssuerCompsMap
}
protected void init(String baseDN, ObjectIdentifier[] dnComps,
- ObjectIdentifier[] filterComps) {
- //mLdapAttr = LdapCrlPublisher.LDAP_CRL_ATTR;
+ ObjectIdentifier[] filterComps) {
+ // mLdapAttr = LdapCrlPublisher.LDAP_CRL_ATTR;
super.init(baseDN, dnComps, filterComps);
}
/**
- * Maps a crl to LDAP entry.
- * Uses issuer DN components and filter components to form a DN and
- * filter for a LDAP search.
- * If the formed DN is null the baseDN will be used.
- * If the formed DN is null and baseDN is null an error is thrown.
- * If the filter is null a base search is performed.
- * If both are null an error is thrown.
+ * Maps a crl to LDAP entry. Uses issuer DN components and filter components
+ * to form a DN and filter for a LDAP search. If the formed DN is null the
+ * baseDN will be used. If the formed DN is null and baseDN is null an error
+ * is thrown. If the filter is null a base search is performed. If both are
+ * null an error is thrown.
*
* @param conn - the LDAP connection.
* @param obj - the X509Certificate.
* @return the result. LdapCertMapResult is also used for CRL.
- */
+ */
public String
- map(LDAPConnection conn, Object obj)
- throws ELdapException {
+ map(LDAPConnection conn, Object obj)
+ throws ELdapException {
if (conn == null)
return null;
X509CRLImpl crl = (X509CRLImpl) obj;
try {
String result = null;
- X500Name issuerDN =
- (X500Name) ((X509CRLImpl) crl).getIssuerDN();
+ X500Name issuerDN =
+ (X500Name) ((X509CRLImpl) crl).getIssuerDN();
CMS.debug("LdapCrlIssuerCompsMap: " + issuerDN.toString());
@@ -136,14 +131,14 @@ public class LdapCrlIssuerCompsMap
result = super.map(conn, issuerDN, crlbytes);
return result;
} catch (CRLException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_CANT_DECODE_CRL", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("PUBLISH_CANT_DECODE_CRL", e.toString()));
throw new ELdapException(CMS.getUserMessage("CMS_LDAP_GET_DER_ENCODED_CRL_FAILED", e.toString()));
}
}
public String map(LDAPConnection conn, IRequest req, Object obj)
- throws ELdapException {
+ throws ELdapException {
return map(conn, obj);
}
@@ -152,8 +147,7 @@ public class LdapCrlIssuerCompsMap
*/
private void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_LDAP, level,
- "LdapCrlCompsMap: " + msg);
+ "LdapCrlCompsMap: " + msg);
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/publish/mappers/LdapDNCompsMap.java b/pki/base/common/src/com/netscape/cms/publish/mappers/LdapDNCompsMap.java
index a9df7dae..1d01b239 100644
--- a/pki/base/common/src/com/netscape/cms/publish/mappers/LdapDNCompsMap.java
+++ b/pki/base/common/src/com/netscape/cms/publish/mappers/LdapDNCompsMap.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.publish.mappers;
-
import java.io.IOException;
import java.util.Enumeration;
import java.util.Locale;
@@ -46,23 +45,21 @@ import com.netscape.certsrv.ldap.ELdapServerDownException;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.publish.ILdapPlugin;
-
-/**
- * Maps a Subject name to an entry in the LDAP server.
- * subject name to form the ldap search dn and filter.
- * Takes a optional root search dn.
- * The DN comps are used to form a LDAP entry to begin a subtree search.
- * The filter comps are used to form a search filter for the subtree.
- * If none of the DN comps matched, baseDN is used for the subtree.
- * If the baseDN is null and none of the DN comps matched, it is an error.
- * If none of the DN comps and filter comps matched, it is an error.
- * If just the filter comps is null, a base search is performed.
- *
+/**
+ * Maps a Subject name to an entry in the LDAP server. subject name to form the
+ * ldap search dn and filter. Takes a optional root search dn. The DN comps are
+ * used to form a LDAP entry to begin a subtree search. The filter comps are
+ * used to form a search filter for the subtree. If none of the DN comps
+ * matched, baseDN is used for the subtree. If the baseDN is null and none of
+ * the DN comps matched, it is an error. If none of the DN comps and filter
+ * comps matched, it is an error. If just the filter comps is null, a base
+ * search is performed.
+ *
* @version $Revision$, $Date$
*/
-public class LdapDNCompsMap
- implements ILdapPlugin, IExtendedPluginInfo {
- //protected String mLdapAttr = null;
+public class LdapDNCompsMap
+ implements ILdapPlugin, IExtendedPluginInfo {
+ // protected String mLdapAttr = null;
protected String mBaseDN = null;
protected ObjectIdentifier[] mDnComps = null;
protected ObjectIdentifier[] mFilterComps = null;
@@ -71,24 +68,24 @@ public class LdapDNCompsMap
private boolean mInited = false;
protected IConfigStore mConfig = null;
- /**
+ /**
* Constructor.
- *
- * The DN comps are used to form a LDAP entry to begin a subtree search.
- * The filter comps are used to form a search filter for the subtree.
- * If none of the DN comps matched, baseDN is used for the subtree.
- * If the baseDN is null and none of the DN comps matched, it is an error.
- * If none of the DN comps and filter comps matched, it is an error.
- * If just the filter comps is null, a base search is performed.
*
- * @param baseDN The base DN.
+ * The DN comps are used to form a LDAP entry to begin a subtree search. The
+ * filter comps are used to form a search filter for the subtree. If none of
+ * the DN comps matched, baseDN is used for the subtree. If the baseDN is
+ * null and none of the DN comps matched, it is an error. If none of the DN
+ * comps and filter comps matched, it is an error. If just the filter comps
+ * is null, a base search is performed.
+ *
+ * @param baseDN The base DN.
* @param dnComps Components to form the LDAP base dn for search.
* @param filterComps Components to form the LDAP search filter.
*/
- public LdapDNCompsMap(String ldapAttr, String baseDN,
- ObjectIdentifier[] dnComps,
- ObjectIdentifier[] filterComps) {
- //mLdapAttr = ldapAttr;
+ public LdapDNCompsMap(String ldapAttr, String baseDN,
+ ObjectIdentifier[] dnComps,
+ ObjectIdentifier[] filterComps) {
+ // mLdapAttr = ldapAttr;
init(baseDN, dnComps, filterComps);
}
@@ -102,17 +99,17 @@ public class LdapDNCompsMap
return mConfig;
}
- /**
+ /**
* for initializing from config store.
*/
- public void init(IConfigStore config)
- throws EBaseException {
+ public void init(IConfigStore config)
+ throws EBaseException {
mConfig = config;
String baseDN = mConfig.getString("baseDN");
- ObjectIdentifier[] dnComps =
- getCompsFromString(mConfig.getString("dnComps"));
- ObjectIdentifier[] filterComps =
- getCompsFromString(mConfig.getString("filterComps"));
+ ObjectIdentifier[] dnComps =
+ getCompsFromString(mConfig.getString("dnComps"));
+ ObjectIdentifier[] filterComps =
+ getCompsFromString(mConfig.getString("filterComps"));
init(baseDN, dnComps, filterComps);
}
@@ -131,12 +128,12 @@ public class LdapDNCompsMap
"dnComps;string;Comma-separated list of attributes to put in the DN",
"filterComps;string;Comma-separated list of attributes to form the filter",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-ldappublish-mapper-dncompsmapper",
+ ";configuration-ldappublish-mapper-dncompsmapper",
IExtendedPluginInfo.HELP_TEXT +
- ";More complex mapper. Used when there is not enough information " +
- "in the cert request to form the complete LDAP DN. Using this " +
- "plugin, you can specify additional LDAP filters to narrow down the " +
- "search"
+ ";More complex mapper. Used when there is not enough information " +
+ "in the cert request to form the complete LDAP DN. Using this " +
+ "plugin, you can specify additional LDAP filters to narrow down the " +
+ "search"
};
return s;
@@ -163,14 +160,14 @@ public class LdapDNCompsMap
if (mDnComps == null) {
v.addElement("dnComps=");
} else {
- v.addElement("dnComps=" +
- mConfig.getString("dnComps"));
+ v.addElement("dnComps=" +
+ mConfig.getString("dnComps"));
}
if (mFilterComps == null) {
v.addElement("filterComps=");
} else {
- v.addElement("filterComps=" +
- mConfig.getString("filterComps"));
+ v.addElement("filterComps=" +
+ mConfig.getString("filterComps"));
}
} catch (Exception e) {
}
@@ -181,8 +178,8 @@ public class LdapDNCompsMap
* common initialization routine.
*/
protected void init(String baseDN, ObjectIdentifier[] dnComps,
- ObjectIdentifier[] filterComps) {
- if (mInited)
+ ObjectIdentifier[] filterComps) {
+ if (mInited)
return;
mBaseDN = baseDN;
@@ -191,36 +188,34 @@ public class LdapDNCompsMap
if (filterComps != null)
mFilterComps = (ObjectIdentifier[]) filterComps.clone();
- // log debug info.
+ // log debug info.
for (int i = 0; i < mDnComps.length; i++) {
CMS.debug(
- "LdapDNCompsMap: dnComp " + X500NameAttrMap.getDefault().getName(mDnComps[i]));
+ "LdapDNCompsMap: dnComp " + X500NameAttrMap.getDefault().getName(mDnComps[i]));
}
for (int i = 0; i < mFilterComps.length; i++) {
CMS.debug("LdapDNCompsMap: filterComp " +
- X500NameAttrMap.getDefault().getName(mFilterComps[i]));
+ X500NameAttrMap.getDefault().getName(mFilterComps[i]));
}
mInited = true;
}
/**
- * Maps a X500 subject name to LDAP entry.
- * Uses DN components and filter components to form a DN and
- * filter for a LDAP search.
- * If the formed DN is null the baseDN will be used.
- * If the formed DN is null and baseDN is null an error is thrown.
- * If the filter is null a base search is performed.
- * If both are null an error is thrown.
+ * Maps a X500 subject name to LDAP entry. Uses DN components and filter
+ * components to form a DN and filter for a LDAP search. If the formed DN is
+ * null the baseDN will be used. If the formed DN is null and baseDN is null
+ * an error is thrown. If the filter is null a base search is performed. If
+ * both are null an error is thrown.
*
- * @param conn the LDAP connection.
- * @param x500name the dn to map.
- * @param obj the object
+ * @param conn the LDAP connection.
+ * @param x500name the dn to map.
+ * @param obj the object
* @exception ELdapException if any LDAP exceptions occured.
* @return the DN of the entry.
- */
- public String map(LDAPConnection conn, X500Name x500name,
- byte[] obj)
- throws ELdapException {
+ */
+ public String map(LDAPConnection conn, X500Name x500name,
+ byte[] obj)
+ throws ELdapException {
try {
if (conn == null)
return null;
@@ -234,17 +229,17 @@ public class LdapDNCompsMap
if (dn == null) {
// #362332
// if (filter == null) {
- // log(ILogger.LL_FAILURE, "No dn and filter formed");
- // throw new ELdapException(
- // LdapResources.NO_DN_AND_FILTER_COMPS,
- // x500name.toString());
+ // log(ILogger.LL_FAILURE, "No dn and filter formed");
+ // throw new ELdapException(
+ // LdapResources.NO_DN_AND_FILTER_COMPS,
+ // x500name.toString());
// }
if (mBaseDN == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_NO_BASE"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("PUBLISH_NO_BASE"));
throw new ELdapException(
- CMS.getUserMessage("CMS_LDAP_NO_DN_COMPS_AND_BASEDN",
- x500name.toString()));
+ CMS.getUserMessage("CMS_LDAP_NO_DN_COMPS_AND_BASEDN",
+ x500name.toString()));
}
dn = mBaseDN;
}
@@ -261,23 +256,23 @@ public class LdapDNCompsMap
attrs = new String[] { LDAPv3.NO_ATTRS };
log(ILogger.LL_INFO, "searching for " + dn + " " + filter + " " +
- ((scope == LDAPv2.SCOPE_SUB) ? "sub" : "base"));
+ ((scope == LDAPv2.SCOPE_SUB) ? "sub" : "base"));
- LDAPSearchResults results =
- conn.search(dn, scope, filter, attrs, false);
+ LDAPSearchResults results =
+ conn.search(dn, scope, filter, attrs, false);
LDAPEntry entry = results.next();
if (results.hasMoreElements()) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_MORE_THAN_ONE_ENTRY", "", x500name.toString()));
- throw new ELdapException(CMS.getUserMessage("CMS_LDAP_MORE_THAN_ONE_ENTRY",
- x500name.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("PUBLISH_MORE_THAN_ONE_ENTRY", "", x500name.toString()));
+ throw new ELdapException(CMS.getUserMessage("CMS_LDAP_MORE_THAN_ONE_ENTRY",
+ x500name.toString()));
}
if (entry != null) {
return entry.getDN();
} else {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_ENTRY_NOT_FOUND", "", x500name.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("PUBLISH_ENTRY_NOT_FOUND", "", x500name.toString()));
throw new ELdapException(CMS.getUserMessage("CMS_LDAP_NO_MATCH_FOUND",
"null entry"));
}
@@ -286,11 +281,11 @@ public class LdapDNCompsMap
// need to intercept this because message from LDAP is
// "DSA is unavailable" which confuses with DSA PKI.
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
+ CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
throw new ELdapServerDownException(CMS.getUserMessage("CMS_LDAP_SERVER_UNAVAILABLE", conn.getHost(), "" + conn.getPort()));
} else {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_DN_MAP_EXCEPTION", "LDAPException", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("PUBLISH_DN_MAP_EXCEPTION", "LDAPException", e.toString()));
throw new ELdapException(CMS.getUserMessage("CMS_LDAP_NO_MATCH_FOUND", e.toString()));
}
}
@@ -298,15 +293,16 @@ public class LdapDNCompsMap
private void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_LDAP, level,
- "LdapDNCompsMap: " + msg);
+ "LdapDNCompsMap: " + msg);
}
/**
* form a dn and filter from component in the cert subject name
+ *
* @param subjName subject name
*/
public String[] formDNandFilter(X500Name subjName)
- throws ELdapException {
+ throws ELdapException {
Vector<RDN> dnRdns = new Vector<RDN>();
SearchFilter filter = new SearchFilter();
X500NameAttrMap attrMap = X500NameAttrMap.getDefault();
@@ -328,16 +324,16 @@ public class LdapDNCompsMap
DerValue val = ava.getValue();
AVA newAVA = new AVA(mailOid, val);
RDN newRDN = new RDN(new AVA[] { newAVA }
- );
+ );
- CMS.debug(
- "LdapDNCompsMap: Converted " + rdn.toLdapDNString() + " to " +
- newRDN.toLdapDNString() + " in DN");
+ CMS.debug(
+ "LdapDNCompsMap: Converted " + rdn.toLdapDNString() + " to " +
+ newRDN.toLdapDNString() + " in DN");
rdn = newRDN;
}
dnRdns.addElement(rdn);
CMS.debug(
- "LdapDNCompsMap: adding dn comp " + rdn.toLdapDNString());
+ "LdapDNCompsMap: adding dn comp " + rdn.toLdapDNString());
break;
}
}
@@ -348,29 +344,29 @@ public class LdapDNCompsMap
AVA newAVA = new AVA(mailOid, val);
CMS.debug(
- "LdapDNCompsMap: Converted " + ava.toLdapDNString() + " to " +
- newAVA.toLdapDNString() + " in filter");
+ "LdapDNCompsMap: Converted " + ava.toLdapDNString() + " to " +
+ newAVA.toLdapDNString() + " in filter");
ava = newAVA;
}
filter.addElement(ava.toLdapDNString());
CMS.debug(
- "LdapDNCompsMap: adding filter comp " + ava.toLdapDNString());
+ "LdapDNCompsMap: adding filter comp " + ava.toLdapDNString());
break;
}
}
- // XXX should be an error when string is null?
+ // XXX should be an error when string is null?
// return to caller to decide.
if (dnRdns.size() != 0) {
dnStr = new X500Name(dnRdns).toLdapDNString();
- }
+ }
if (filter.size() != 0) {
filterStr = filter.toFilterString();
}
}
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_FROM_SUBJ_TO_DN", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("PUBLISH_FROM_SUBJ_TO_DN", e.toString()));
throw new ELdapException(CMS.getUserMessage("CMS_LDAP_FORM_DN_COMPS_FAILED", e.toString()));
}
@@ -386,12 +382,13 @@ public class LdapDNCompsMap
}
/**
- * class for forming search filters for ldap searching from
- * name=value components. components are anded.
+ * class for forming search filters for ldap searching from name=value
+ * components. components are anded.
*/
public static class SearchFilter extends Vector<Object> {
private static final long serialVersionUID = 4210302171279891828L;
+
public String toFilterString() {
StringBuffer buf = new StringBuffer();
@@ -412,21 +409,22 @@ public class LdapDNCompsMap
}
/**
- * useful routine for parsing components given as string to
- * arrays of objectidentifiers.
- * The string is expected to be comma separated AVA attribute names.
- * For example, "uid,cn,o,ou". Attribute names are case insensitive.
+ * useful routine for parsing components given as string to arrays of
+ * objectidentifiers. The string is expected to be comma separated AVA
+ * attribute names. For example, "uid,cn,o,ou". Attribute names are case
+ * insensitive.
+ *
* @param val the string specifying the comps
* @exception ELdapException if any error occurs.
*/
public static ObjectIdentifier[] getCompsFromString(String val)
- throws ELdapException {
+ throws ELdapException {
StringTokenizer tokens;
ObjectIdentifier[] comps;
String attr;
ObjectIdentifier oid;
- if (val == null || val.length() == 0)
+ if (val == null || val.length() == 0)
return new ObjectIdentifier[0];
tokens = new StringTokenizer(val, ", \t\n\r");
@@ -439,7 +437,7 @@ public class LdapDNCompsMap
while (tokens.hasMoreTokens()) {
attr = tokens.nextToken().trim();
// mail -> E hack to look for E in subject names.
- if (attr.equalsIgnoreCase("mail"))
+ if (attr.equalsIgnoreCase("mail"))
attr = "E";
oid = X500NameAttrMap.getDefault().getOid(attr);
if (oid != null) {
@@ -453,4 +451,3 @@ public class LdapDNCompsMap
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/publish/mappers/LdapEnhancedMap.java b/pki/base/common/src/com/netscape/cms/publish/mappers/LdapEnhancedMap.java
index e3c2fa1b..c47a3647 100644
--- a/pki/base/common/src/com/netscape/cms/publish/mappers/LdapEnhancedMap.java
+++ b/pki/base/common/src/com/netscape/cms/publish/mappers/LdapEnhancedMap.java
@@ -20,7 +20,6 @@
package com.netscape.cms.publish.mappers;
-
///////////////////////
// import statements //
///////////////////////
@@ -56,38 +55,30 @@ import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.publish.ILdapMapper;
import com.netscape.certsrv.request.IRequest;
-
//////////////////////
// class definition //
//////////////////////
-/**
- * Maps a request to an entry in the LDAP server.
- * Takes a dnPattern to form the baseDN from the
- * request attributes and certificate subject name.
- * Does a base search for the entry in the directory
- * to publish the cert or crl. The restriction of
- * this mapper is that the ldap dn components must
- * be part of certificate subject name or request
- * attributes or constant. The difference of this
- * mapper and LdapSimpleMap is that if the ldap
- * entry is not found, it has the option to create
- * the ldap entry given the dn and attributes
- * formulated.
- *
+/**
+ * Maps a request to an entry in the LDAP server. Takes a dnPattern to form the
+ * baseDN from the request attributes and certificate subject name. Does a base
+ * search for the entry in the directory to publish the cert or crl. The
+ * restriction of this mapper is that the ldap dn components must be part of
+ * certificate subject name or request attributes or constant. The difference of
+ * this mapper and LdapSimpleMap is that if the ldap entry is not found, it has
+ * the option to create the ldap entry given the dn and attributes formulated.
+ *
* @version $Revision$, $Date$
*/
public class LdapEnhancedMap
- implements ILdapMapper, IExtendedPluginInfo {
- ////////////////////////
+ implements ILdapMapper, IExtendedPluginInfo {
+ // //////////////////////
// default parameters //
- ////////////////////////
-
+ // //////////////////////
-
- //////////////////////////////////////
+ // ////////////////////////////////////
// local LdapEnhancedMap parameters //
- //////////////////////////////////////
+ // ////////////////////////////////////
private boolean mInited = false;
@@ -102,14 +93,14 @@ public class LdapEnhancedMap
protected String[] mLdapValues = null;
- ////////////////////////////
+ // //////////////////////////
// ILdapMapper parameters //
- ////////////////////////////
+ // //////////////////////////
/* mapper plug-in fields */
- protected static final String PROP_DNPATTERN = "dnPattern";
+ protected static final String PROP_DNPATTERN = "dnPattern";
protected static final String PROP_CREATE = "createEntry";
- // the object class of the entry to be created. xxxx not done yet
+ // the object class of the entry to be created. xxxx not done yet
protected static final String PROP_OBJCLASS = "objectClass";
// req/cert/ext attribute --> directory attribute table
protected static final String PROP_ATTRNUM = "attrNum";
@@ -119,10 +110,10 @@ public class LdapEnhancedMap
/* mapper plug-in fields initialization values */
private static final int DEFAULT_NUM_ATTRS = 1;
- /* Holds mapper plug-in fields accepted by this implementation.
- * This list is passed to the configuration console so configuration
- * for instances of this implementation can be configured through the
- * console.
+ /*
+ * Holds mapper plug-in fields accepted by this implementation. This list is
+ * passed to the configuration console so configuration for instances of
+ * this implementation can be configured through the console.
*/
private static Vector<String> defaultParams = new Vector<String>();
@@ -145,9 +136,9 @@ public class LdapEnhancedMap
/* miscellaneous constants local to this mapper plug-in */
// default dn pattern if left blank or not set in the config
- public static final String DEFAULT_DNPATTERN =
- "UID=$req.HTTP_PARAMS.UID, " +
- "OU=people, O=$subj.o, C=$subj.c";
+ public static final String DEFAULT_DNPATTERN =
+ "UID=$req.HTTP_PARAMS.UID, " +
+ "OU=people, O=$subj.o, C=$subj.c";
private static final int MAX_ATTRS = 10;
protected static final int DEFAULT_ATTRNUM = 1;
@@ -155,21 +146,19 @@ public class LdapEnhancedMap
protected IConfigStore mConfig = null;
protected AVAPattern[] mPatterns = null;
- ////////////////////////////////////
+ // //////////////////////////////////
// IExtendedPluginInfo parameters //
- ////////////////////////////////////
-
-
+ // //////////////////////////////////
- ///////////////////////
+ // /////////////////////
// Logger parameters //
- ///////////////////////
+ // /////////////////////
private ILogger mLogger = CMS.getLogger();
- /////////////////////
+ // ///////////////////
// default methods //
- /////////////////////
+ // ///////////////////
/**
* Default constructor, initialization must follow.
@@ -177,22 +166,22 @@ public class LdapEnhancedMap
public LdapEnhancedMap() {
}
- ///////////////////////////////////
+ // /////////////////////////////////
// local LdapEnhancedMap methods //
- ///////////////////////////////////
+ // /////////////////////////////////
/**
* common initialization routine.
*/
protected void init(String dnPattern)
- throws EBaseException {
+ throws EBaseException {
if (mInited) {
return;
}
mDnPattern = dnPattern;
if (mDnPattern == null ||
- mDnPattern.length() == 0) {
+ mDnPattern.length() == 0) {
mDnPattern = DEFAULT_DNPATTERN;
}
@@ -202,11 +191,11 @@ public class LdapEnhancedMap
String[] mCertAttrs = mPattern.getCertAttrs();
} catch (ELdapException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_DN_PATTERN_INIT",
- dnPattern, e.toString()));
+ CMS.getLogMessage("PUBLISH_DN_PATTERN_INIT",
+ dnPattern, e.toString()));
throw new EBaseException(
- "falied to init with pattern " +
- dnPattern + " " + e);
+ "falied to init with pattern " +
+ dnPattern + " " + e);
}
mInited = true;
@@ -214,43 +203,44 @@ public class LdapEnhancedMap
/**
* form a dn from component in the request and cert subject name
+ *
* @param req The request
* @param obj The certificate or crl
*/
private String formDN(IRequest req, Object obj)
- throws EBaseException {
+ throws EBaseException {
CertificateExtensions certExt = null;
X500Name subjectDN = null;
try {
X509Certificate cert = (X509Certificate) obj;
- subjectDN =
+ subjectDN =
(X500Name) ((X509Certificate) cert).getSubjectDN();
CMS.debug(
- "LdapEnhancedMap: cert subject dn:" +
- subjectDN.toString());
+ "LdapEnhancedMap: cert subject dn:" +
+ subjectDN.toString());
- //certExt = (CertificateExtensions)
- // ((X509CertImpl)cert).get(
- // X509CertInfo.EXTENSIONS);
+ // certExt = (CertificateExtensions)
+ // ((X509CertImpl)cert).get(
+ // X509CertInfo.EXTENSIONS);
X509CertInfo info = (X509CertInfo)
- ((X509CertImpl) cert).get(
- X509CertImpl.NAME +
- "." +
- X509CertImpl.INFO);
+ ((X509CertImpl) cert).get(
+ X509CertImpl.NAME +
+ "." +
+ X509CertImpl.INFO);
certExt = (CertificateExtensions)
info.get(CertificateExtensions.NAME);
} catch (java.security.cert.CertificateParsingException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_CANT_GET_EXT", e.toString()));
+ CMS.getLogMessage("PUBLISH_CANT_GET_EXT", e.toString()));
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_CANT_GET_EXT", e.toString()));
+ CMS.getLogMessage("PUBLISH_CANT_GET_EXT", e.toString()));
} catch (java.security.cert.CertificateException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_CANT_GET_EXT", e.toString()));
+ CMS.getLogMessage("PUBLISH_CANT_GET_EXT", e.toString()));
} catch (ClassCastException e) {
try {
@@ -260,14 +250,14 @@ public class LdapEnhancedMap
((X509CRLImpl) crl).getIssuerDN();
CMS.debug(
- "LdapEnhancedMap: crl issuer dn: " +
+ "LdapEnhancedMap: crl issuer dn: " +
- subjectDN.toString());
+ subjectDN.toString());
} catch (ClassCastException ex) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_PUBLISH_OBJ_NOT_SUPPORTED",
- ((req == null) ? ""
- : req.getRequestId().toString())));
+ CMS.getLogMessage("PUBLISH_PUBLISH_OBJ_NOT_SUPPORTED",
+ ((req == null) ? ""
+ : req.getRequestId().toString())));
return null;
}
}
@@ -289,26 +279,26 @@ public class LdapEnhancedMap
return dn;
} catch (ELdapException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_CANT_FORM_DN",
- ((req == null) ? ""
- : req.getRequestId().toString()), e.toString()));
+ CMS.getLogMessage("PUBLISH_CANT_FORM_DN",
+ ((req == null) ? ""
+ : req.getRequestId().toString()), e.toString()));
throw new EBaseException(
"failed to form dn for request: " +
- ((req == null) ? ""
- : req.getRequestId().toString()) +
- " " + e);
+ ((req == null) ? ""
+ : req.getRequestId().toString()) +
+ " " + e);
}
}
private void createEntry(LDAPConnection conn, String dn)
- throws LDAPException {
+ throws LDAPException {
LDAPAttributeSet attrs = new LDAPAttributeSet();
// OID 2.5.6.16
- String caOc[] = { "top",
- "person",
- "organizationalPerson",
+ String caOc[] = { "top",
+ "person",
+ "organizationalPerson",
"inetOrgPerson" };
DN dnobj = new DN(dn);
@@ -319,10 +309,10 @@ public class LdapEnhancedMap
attrs.add(new LDAPAttribute("objectclass", caOc));
for (int i = 0; i < mNumAttrs; i++) {
- if (mLdapNames[i] != null &&
- !mLdapNames[i].trim().equals("") &&
- mLdapValues[i] != null &&
- !mLdapValues[i].trim().equals("")) {
+ if (mLdapNames[i] != null &&
+ !mLdapNames[i].trim().equals("") &&
+ mLdapValues[i] != null &&
+ !mLdapValues[i].trim().equals("")) {
attrs.add(new LDAPAttribute(mLdapNames[i],
mLdapValues[i]));
}
@@ -333,18 +323,17 @@ public class LdapEnhancedMap
conn.add(entry);
}
- /////////////////////////
+ // ///////////////////////
// ILdapMapper methods //
- /////////////////////////
+ // ///////////////////////
- /**
+ /**
* for initializing from config store.
- *
- * implementation for extended
- * ILdapPlugin interface method
+ *
+ * implementation for extended ILdapPlugin interface method
*/
- public void init(IConfigStore config)
- throws EBaseException {
+ public void init(IConfigStore config)
+ throws EBaseException {
mConfig = config;
mDnPattern = mConfig.getString(PROP_DNPATTERN,
@@ -364,16 +353,16 @@ public class LdapEnhancedMap
for (int i = 0; i < mNumAttrs; i++) {
mLdapNames[i] =
mConfig.getString(PROP_ATTR_NAME +
- Integer.toString(i),
- "");
+ Integer.toString(i),
+ "");
mLdapPatterns[i] =
mConfig.getString(PROP_ATTR_PATTERN +
- Integer.toString(i),
- "");
+ Integer.toString(i),
+ "");
if (mLdapPatterns[i] != null &&
- !mLdapPatterns[i].trim().equals("")) {
+ !mLdapPatterns[i].trim().equals("")) {
mPatterns[i] = new AVAPattern(mLdapPatterns[i]);
}
}
@@ -381,9 +370,8 @@ public class LdapEnhancedMap
init(mDnPattern);
}
- /**
- * implementation for extended
- * ILdapPlugin interface method
+ /**
+ * implementation for extended ILdapPlugin interface method
*/
public IConfigStore getConfigStore() {
return mConfig;
@@ -407,34 +395,34 @@ public class LdapEnhancedMap
try {
if (mDnPattern == null) {
v.addElement(PROP_DNPATTERN + "=");
- }else {
+ } else {
v.addElement(PROP_DNPATTERN + "=" +
- mConfig.getString(PROP_DNPATTERN));
+ mConfig.getString(PROP_DNPATTERN));
}
v.addElement(PROP_CREATE + "=" +
- mConfig.getBoolean(PROP_CREATE,
- true));
+ mConfig.getBoolean(PROP_CREATE,
+ true));
v.addElement(PROP_ATTRNUM + "=" +
- mConfig.getInteger(PROP_ATTRNUM,
- DEFAULT_NUM_ATTRS));
+ mConfig.getInteger(PROP_ATTRNUM,
+ DEFAULT_NUM_ATTRS));
for (int i = 0; i < mNumAttrs; i++) {
if (mLdapNames[i] != null) {
v.addElement(PROP_ATTR_NAME + i +
- "=" + mLdapNames[i]);
+ "=" + mLdapNames[i]);
} else {
v.addElement(PROP_ATTR_NAME + i +
- "=");
+ "=");
}
if (mLdapPatterns[i] != null) {
v.addElement(PROP_ATTR_PATTERN + i +
- "=" + mLdapPatterns[i]);
+ "=" + mLdapPatterns[i]);
} else {
v.addElement(PROP_ATTR_PATTERN + i +
- "=");
+ "=");
}
}
} catch (Exception e) {
@@ -444,29 +432,29 @@ public class LdapEnhancedMap
}
/**
- * Maps an X500 subject name to an LDAP entry.
- * Uses DN pattern to form a DN for an LDAP base search.
+ * Maps an X500 subject name to an LDAP entry. Uses DN pattern to form a DN
+ * for an LDAP base search.
*
- * @param conn the LDAP connection.
- * @param obj the object to map.
- * @exception ELdapException if any LDAP exceptions occurred.
- */
+ * @param conn the LDAP connection.
+ * @param obj the object to map.
+ * @exception ELdapException if any LDAP exceptions occurred.
+ */
public String map(LDAPConnection conn, Object obj)
- throws ELdapException {
+ throws ELdapException {
return map(conn, null, obj);
}
/**
- * Maps an X500 subject name to an LDAP entry.
- * Uses DN pattern to form a DN for an LDAP base search.
+ * Maps an X500 subject name to an LDAP entry. Uses DN pattern to form a DN
+ * for an LDAP base search.
*
- * @param conn the LDAP connection.
- * @param req the request to map.
- * @param obj the object to map.
- * @exception ELdapException if any LDAP exceptions occurred.
- */
+ * @param conn the LDAP connection.
+ * @param req the request to map.
+ * @param obj the object to map.
+ * @exception ELdapException if any LDAP exceptions occurred.
+ */
public String map(LDAPConnection conn, IRequest req, Object obj)
- throws ELdapException {
+ throws ELdapException {
if (conn == null) {
return null;
}
@@ -477,7 +465,7 @@ public class LdapEnhancedMap
dn = formDN(req, obj);
if (dn == null) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_DN_NOT_FORMED"));
+ CMS.getLogMessage("PUBLISH_DN_NOT_FORMED"));
String s1 = "";
@@ -494,9 +482,9 @@ public class LdapEnhancedMap
String[] attrs = new String[] { LDAPv3.NO_ATTRS };
log(ILogger.LL_INFO,
- "searching for dn: " +
- dn + " filter:" +
- filter + " scope: base");
+ "searching for dn: " +
+ dn + " filter:" +
+ filter + " scope: base");
LDAPSearchResults results = conn.search(dn,
scope,
@@ -508,27 +496,27 @@ public class LdapEnhancedMap
if (results.hasMoreElements()) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_MORE_THAN_ONE_ENTRY",
- dn +
- ((req == null) ? ""
- : req.getRequestId().toString())));
+ CMS.getLogMessage("PUBLISH_MORE_THAN_ONE_ENTRY",
+ dn +
+ ((req == null) ? ""
+ : req.getRequestId().toString())));
throw new ELdapException(
- CMS.getUserMessage("CMS_LDAP_MORE_THAN_ONE_ENTRY",
- ((req == null) ? ""
- : req.getRequestId().toString())));
+ CMS.getUserMessage("CMS_LDAP_MORE_THAN_ONE_ENTRY",
+ ((req == null) ? ""
+ : req.getRequestId().toString())));
}
if (entry != null) {
return entry.getDN();
} else {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_ENTRY_NOT_FOUND",
- dn +
- ((req == null) ? ""
- : req.getRequestId().toString())));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("PUBLISH_ENTRY_NOT_FOUND",
+ dn +
+ ((req == null) ? ""
+ : req.getRequestId().toString())));
- throw new ELdapException(CMS.getUserMessage("CMS_LDAP_NO_MATCH_FOUND",
+ throw new ELdapException(CMS.getUserMessage("CMS_LDAP_NO_MATCH_FOUND",
"null entry"));
}
} catch (LDAPException e) {
@@ -536,112 +524,111 @@ public class LdapEnhancedMap
// need to intercept this because message from LDAP is
// "DSA is unavailable" which confuses with DSA PKI.
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
+ CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
throw new ELdapServerDownException(CMS.getUserMessage("CMS_LDAP_SERVER_UNAVAILABLE", conn.getHost(), "" + conn.getPort()));
} else if (e.getLDAPResultCode() ==
- LDAPException.NO_SUCH_OBJECT && mCreateEntry) {
+ LDAPException.NO_SUCH_OBJECT && mCreateEntry) {
try {
createEntry(conn, dn);
log(ILogger.LL_INFO,
- "Entry " +
- dn +
- " Created");
+ "Entry " +
+ dn +
+ " Created");
return dn;
} catch (LDAPException e1) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_DN_MAP_EXCEPTION",
- dn,
- e.toString()));
+ CMS.getLogMessage("PUBLISH_DN_MAP_EXCEPTION",
+ dn,
+ e.toString()));
log(ILogger.LL_FAILURE,
- "Entry is not created. " +
- "This may because there are " +
- "entries in the directory " +
- "hierachy not exit.");
+ "Entry is not created. " +
+ "This may because there are " +
+ "entries in the directory " +
+ "hierachy not exit.");
throw new ELdapException(
CMS.getUserMessage("CMS_LDAP_CREATE_ENTRY", dn));
}
} else {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_DN_MAP_EXCEPTION",
- dn,
- e.toString()));
+ CMS.getLogMessage("PUBLISH_DN_MAP_EXCEPTION",
+ dn,
+ e.toString()));
throw new ELdapException(CMS.getUserMessage("CMS_LDAP_NO_MATCH_FOUND", e.toString()));
}
} catch (EBaseException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_EXCEPTION_CAUGHT",
- e.toString()));
+ CMS.getLogMessage("PUBLISH_EXCEPTION_CAUGHT",
+ e.toString()));
throw new ELdapException(CMS.getUserMessage("CMS_LDAP_NO_MATCH_FOUND", e.toString()));
}
}
- /////////////////////////////////
+ // ///////////////////////////////
// IExtendedPluginInfo methods //
- /////////////////////////////////
+ // ///////////////////////////////
public String[] getExtendedPluginInfo(Locale locale) {
Vector<String> v = new Vector<String>();
v.addElement(PROP_DNPATTERN +
- ";string;Describes how to form the Ldap " +
- "Subject name in the directory. " +
- "Example 1: 'uid=CertMgr, o=Fedora'. " +
- "Example 2: 'uid=$req.HTTP_PARAMS.uid, " +
- "E=$ext.SubjectAlternativeName.RFC822Name, " +
- "ou=$subj.ou'. " +
- "$req means: take the attribute from the " +
- "request. " +
- "$subj means: take the attribute from the " +
- "certificate subject name. " +
- "$ext means: take the attribute from the " +
- "certificate extension");
+ ";string;Describes how to form the Ldap " +
+ "Subject name in the directory. " +
+ "Example 1: 'uid=CertMgr, o=Fedora'. " +
+ "Example 2: 'uid=$req.HTTP_PARAMS.uid, " +
+ "E=$ext.SubjectAlternativeName.RFC822Name, " +
+ "ou=$subj.ou'. " +
+ "$req means: take the attribute from the " +
+ "request. " +
+ "$subj means: take the attribute from the " +
+ "certificate subject name. " +
+ "$ext means: take the attribute from the " +
+ "certificate extension");
v.addElement(PROP_CREATE +
- ";boolean;If checked, An entry will be " +
- "created automatically");
+ ";boolean;If checked, An entry will be " +
+ "created automatically");
v.addElement(PROP_ATTRNUM +
- ";string;How many attributes to add.");
+ ";string;How many attributes to add.");
v.addElement(IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-ldappublish-mapper-enhancedmapper");
+ ";configuration-ldappublish-mapper-enhancedmapper");
v.addElement(IExtendedPluginInfo.HELP_TEXT +
- ";Describes how to form the LDAP DN of the " +
- "entry to publish to");
+ ";Describes how to form the LDAP DN of the " +
+ "entry to publish to");
for (int i = 0; i < MAX_ATTRS; i++) {
v.addElement(PROP_ATTR_NAME +
- Integer.toString(i) +
- ";string;" +
- "The name of LDAP attribute " +
- "to be added. e.g. mail");
+ Integer.toString(i) +
+ ";string;" +
+ "The name of LDAP attribute " +
+ "to be added. e.g. mail");
v.addElement(PROP_ATTR_PATTERN +
- Integer.toString(i) +
- ";string;" +
- "How to create the LDAP attribute value. " +
- "e.g. $req.HTTP_PARAMS.csrRequestorEmail, " +
- "$subj.E or " +
- "$ext.SubjectAlternativeName.RFC822Name");
+ Integer.toString(i) +
+ ";string;" +
+ "How to create the LDAP attribute value. " +
+ "e.g. $req.HTTP_PARAMS.csrRequestorEmail, " +
+ "$subj.E or " +
+ "$ext.SubjectAlternativeName.RFC822Name");
}
String params[] =
- com.netscape.cmsutil.util.Utils.getStringArrayFromVector(v);
+ com.netscape.cmsutil.util.Utils.getStringArrayFromVector(v);
return params;
}
- ////////////////////
+ // //////////////////
// Logger methods //
- ////////////////////
+ // //////////////////
private void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_LDAP, level,
- "LdapEnhancedMapper: " + msg);
+ "LdapEnhancedMapper: " + msg);
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/publish/mappers/LdapSimpleMap.java b/pki/base/common/src/com/netscape/cms/publish/mappers/LdapSimpleMap.java
index 192b1d30..0ac56781 100644
--- a/pki/base/common/src/com/netscape/cms/publish/mappers/LdapSimpleMap.java
+++ b/pki/base/common/src/com/netscape/cms/publish/mappers/LdapSimpleMap.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.publish.mappers;
-
import java.io.IOException;
import java.security.cert.X509Certificate;
import java.util.Locale;
@@ -45,19 +44,17 @@ import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.publish.ILdapMapper;
import com.netscape.certsrv.request.IRequest;
-
-/**
- * Maps a request to an entry in the LDAP server.
- * Takes a dnPattern to form the baseDN from the request attributes
- * and certificate subject name.Do a base search for the entry
- * in the directory to publish the cert or crl.
- * The restriction of this mapper is that the ldap dn components must
- * be part of certificate subject name or request attributes or constant.
- *
+/**
+ * Maps a request to an entry in the LDAP server. Takes a dnPattern to form the
+ * baseDN from the request attributes and certificate subject name.Do a base
+ * search for the entry in the directory to publish the cert or crl. The
+ * restriction of this mapper is that the ldap dn components must be part of
+ * certificate subject name or request attributes or constant.
+ *
* @version $Revision$, $Date$
*/
public class LdapSimpleMap implements ILdapMapper, IExtendedPluginInfo {
- protected static final String PROP_DNPATTERN = "dnPattern";
+ protected static final String PROP_DNPATTERN = "dnPattern";
protected String mDnPattern = null;
private ILogger mLogger = CMS.getLogger();
@@ -67,20 +64,20 @@ public class LdapSimpleMap implements ILdapMapper, IExtendedPluginInfo {
/* the subject DN pattern */
protected MapDNPattern mPattern = null;
- /* the list of request attriubutes to retrieve*/
+ /* the list of request attriubutes to retrieve */
protected String[] mReqAttrs = null;
- /* the list of cert attriubutes to retrieve*/
+ /* the list of cert attriubutes to retrieve */
protected String[] mCertAttrs = null;
/* default dn pattern if left blank or not set in the config */
- public static final String DEFAULT_DNPATTERN =
- "UID=$req.HTTP_PARAMS.UID, OU=people, O=$subj.o, C=$subj.c";
+ public static final String DEFAULT_DNPATTERN =
+ "UID=$req.HTTP_PARAMS.UID, OU=people, O=$subj.o, C=$subj.c";
- /**
+ /**
* Constructor.
- *
- * @param dnPattern The base DN.
+ *
+ * @param dnPattern The base DN.
*/
public LdapSimpleMap(String dnPattern) {
try {
@@ -88,7 +85,7 @@ public class LdapSimpleMap implements ILdapMapper, IExtendedPluginInfo {
} catch (EBaseException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("OPERATION_ERROR", e.toString()));
}
-
+
}
/**
@@ -100,11 +97,11 @@ public class LdapSimpleMap implements ILdapMapper, IExtendedPluginInfo {
public String[] getExtendedPluginInfo(Locale locale) {
String params[] = {
"dnPattern;string;Describes how to form the Ldap Subject name in" +
- " the directory. Example 1: 'uid=CertMgr, o=Fedora'. Example 2:" +
- " 'uid=$req.HTTP_PARAMS.uid, E=$ext.SubjectAlternativeName.RFC822Name, ou=$subj.ou'. " +
- "$req means: take the attribute from the request. " +
- "$subj means: take the attribute from the certificate subject name. " +
- "$ext means: take the attribute from the certificate extension",
+ " the directory. Example 1: 'uid=CertMgr, o=Fedora'. Example 2:" +
+ " 'uid=$req.HTTP_PARAMS.uid, E=$ext.SubjectAlternativeName.RFC822Name, ou=$subj.ou'. " +
+ "$req means: take the attribute from the request. " +
+ "$subj means: take the attribute from the certificate subject name. " +
+ "$ext means: take the attribute from the certificate extension",
IExtendedPluginInfo.HELP_TOKEN + ";configuration-ldappublish-mapper-simplemapper",
IExtendedPluginInfo.HELP_TEXT + ";Describes how to form the LDAP DN of the entry to publish to"
};
@@ -116,11 +113,11 @@ public class LdapSimpleMap implements ILdapMapper, IExtendedPluginInfo {
return mConfig;
}
- /**
+ /**
* for initializing from config store.
*/
- public void init(IConfigStore config)
- throws EBaseException {
+ public void init(IConfigStore config)
+ throws EBaseException {
mConfig = config;
String dnPattern = mConfig.getString(PROP_DNPATTERN);
@@ -131,12 +128,12 @@ public class LdapSimpleMap implements ILdapMapper, IExtendedPluginInfo {
* common initialization routine.
*/
protected void init(String dnPattern)
- throws EBaseException {
- if (mInited)
+ throws EBaseException {
+ if (mInited)
return;
mDnPattern = dnPattern;
- if (mDnPattern == null || mDnPattern.length() == 0)
+ if (mDnPattern == null || mDnPattern.length() == 0)
mDnPattern = DEFAULT_DNPATTERN;
try {
mPattern = new MapDNPattern(mDnPattern);
@@ -145,7 +142,7 @@ public class LdapSimpleMap implements ILdapMapper, IExtendedPluginInfo {
} catch (ELdapException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_DN_PATTERN_INIT",
dnPattern, e.toString()));
- throw new EBaseException("falied to init with pattern " +
+ throw new EBaseException("falied to init with pattern " +
dnPattern + " " + e);
}
@@ -153,29 +150,29 @@ public class LdapSimpleMap implements ILdapMapper, IExtendedPluginInfo {
}
/**
- * Maps a X500 subject name to LDAP entry.
- * Uses DN pattern to form a DN for a LDAP base search.
+ * Maps a X500 subject name to LDAP entry. Uses DN pattern to form a DN for
+ * a LDAP base search.
*
- * @param conn the LDAP connection.
- * @param obj the object to map.
+ * @param conn the LDAP connection.
+ * @param obj the object to map.
* @exception ELdapException if any LDAP exceptions occured.
- */
+ */
public String map(LDAPConnection conn, Object obj)
- throws ELdapException {
+ throws ELdapException {
return map(conn, null, obj);
}
/**
- * Maps a X500 subject name to LDAP entry.
- * Uses DN pattern to form a DN for a LDAP base search.
+ * Maps a X500 subject name to LDAP entry. Uses DN pattern to form a DN for
+ * a LDAP base search.
*
- * @param conn the LDAP connection.
- * @param req the request to map.
- * @param obj the object to map.
+ * @param conn the LDAP connection.
+ * @param req the request to map.
+ * @param obj the object to map.
* @exception ELdapException if any LDAP exceptions occured.
- */
+ */
public String map(LDAPConnection conn, IRequest req, Object obj)
- throws ELdapException {
+ throws ELdapException {
if (conn == null)
return null;
String dn = null;
@@ -198,22 +195,22 @@ public class LdapSimpleMap implements ILdapMapper, IExtendedPluginInfo {
String[] attrs = new String[] { LDAPv3.NO_ATTRS };
log(ILogger.LL_INFO, "searching for dn: " + dn + " filter:"
- + filter + " scope: base");
+ + filter + " scope: base");
- LDAPSearchResults results =
- conn.search(dn, scope, filter, attrs, false);
+ LDAPSearchResults results =
+ conn.search(dn, scope, filter, attrs, false);
LDAPEntry entry = results.next();
if (results.hasMoreElements()) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_MORE_THAN_ONE_ENTRY", dn, ((req == null) ? "" : req.getRequestId().toString())));
- throw new ELdapException(CMS.getUserMessage("CMS_LDAP_MORE_THAN_ONE_ENTRY",
- ((req == null) ? "" : req.getRequestId().toString())));
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_MORE_THAN_ONE_ENTRY", dn, ((req == null) ? "" : req.getRequestId().toString())));
+ throw new ELdapException(CMS.getUserMessage("CMS_LDAP_MORE_THAN_ONE_ENTRY",
+ ((req == null) ? "" : req.getRequestId().toString())));
}
if (entry != null)
return entry.getDN();
else {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_ENTRY_NOT_FOUND", dn, ((req == null) ? "" : req.getRequestId().toString())));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("PUBLISH_ENTRY_NOT_FOUND", dn, ((req == null) ? "" : req.getRequestId().toString())));
throw new ELdapException(CMS.getUserMessage("CMS_LDAP_NO_MATCH_FOUND",
"null entry"));
}
@@ -224,7 +221,7 @@ public class LdapSimpleMap implements ILdapMapper, IExtendedPluginInfo {
// need to intercept this because message from LDAP is
// "DSA is unavailable" which confuses with DSA PKI.
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
+ CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
throw new ELdapServerDownException(CMS.getUserMessage("CMS_LDAP_SERVER_UNAVAILABLE", conn.getHost(), "" + conn.getPort()));
} else {
log(ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_DN_MAP_EXCEPTION", "", e.toString()));
@@ -238,6 +235,7 @@ public class LdapSimpleMap implements ILdapMapper, IExtendedPluginInfo {
/**
* form a dn from component in the request and cert subject name
+ *
* @param req The request
* @param obj The certificate or crl
*/
@@ -249,15 +247,15 @@ public class LdapSimpleMap implements ILdapMapper, IExtendedPluginInfo {
try {
X509Certificate cert = (X509Certificate) obj;
- subjectDN =
+ subjectDN =
(X500Name) ((X509Certificate) cert).getSubjectDN();
CMS.debug("LdapSimpleMap: cert subject dn:" + subjectDN.toString());
- //certExt = (CertificateExtensions)
- // ((X509CertImpl)cert).get(X509CertInfo.EXTENSIONS);
+ // certExt = (CertificateExtensions)
+ // ((X509CertImpl)cert).get(X509CertInfo.EXTENSIONS);
X509CertInfo info = (X509CertInfo)
- ((X509CertImpl) cert).get(
- X509CertImpl.NAME + "." + X509CertImpl.INFO);
+ ((X509CertImpl) cert).get(
+ X509CertImpl.NAME + "." + X509CertImpl.INFO);
certExt = (CertificateExtensions) info.get(
CertificateExtensions.NAME);
@@ -271,15 +269,15 @@ public class LdapSimpleMap implements ILdapMapper, IExtendedPluginInfo {
try {
X509CRLImpl crl = (X509CRLImpl) obj;
- subjectDN =
+ subjectDN =
(X500Name) ((X509CRLImpl) crl).getIssuerDN();
CMS.debug("LdapSimpleMap: crl issuer dn: " +
- subjectDN.toString());
- }catch (ClassCastException ex) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_PUBLISH_OBJ_NOT_SUPPORTED",
- ((req == null) ? "" : req.getRequestId().toString())));
+ subjectDN.toString());
+ } catch (ClassCastException ex) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("PUBLISH_PUBLISH_OBJ_NOT_SUPPORTED",
+ ((req == null) ? "" : req.getRequestId().toString())));
return null;
}
}
@@ -315,9 +313,9 @@ public class LdapSimpleMap implements ILdapMapper, IExtendedPluginInfo {
try {
if (mDnPattern == null) {
v.addElement(PROP_DNPATTERN + "=");
- }else {
+ } else {
v.addElement(PROP_DNPATTERN + "=" +
- mConfig.getString(PROP_DNPATTERN));
+ mConfig.getString(PROP_DNPATTERN));
}
} catch (Exception e) {
}
@@ -326,8 +324,7 @@ public class LdapSimpleMap implements ILdapMapper, IExtendedPluginInfo {
private void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_LDAP, level,
- "LdapSimpleMapper: " + msg);
+ "LdapSimpleMapper: " + msg);
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/publish/mappers/MapAVAPattern.java b/pki/base/common/src/com/netscape/cms/publish/mappers/MapAVAPattern.java
index 667a7c5a..7be61610 100644
--- a/pki/base/common/src/com/netscape/cms/publish/mappers/MapAVAPattern.java
+++ b/pki/base/common/src/com/netscape/cms/publish/mappers/MapAVAPattern.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.publish.mappers;
-
import java.io.IOException;
import java.io.PushbackReader;
import java.io.StringReader;
@@ -42,26 +41,28 @@ import com.netscape.certsrv.ldap.ELdapException;
import com.netscape.certsrv.publish.ECompSyntaxErr;
import com.netscape.certsrv.request.IRequest;
-
/**
- * class for parsing a DN pattern used to construct a ldap dn from
- * request attributes and cert subject name.<p>
+ * class for parsing a DN pattern used to construct a ldap dn from request
+ * attributes and cert subject name.
+ * <p>
+ *
+ * dnpattern is a string representing a ldap dn pattern to formulate from the
+ * certificate subject name attributes and request attributes . If empty or not
+ * set, the certificate subject name will be used as the ldap dn.
+ * <p>
*
- * dnpattern is a string representing a ldap dn pattern to formulate from
- * the certificate subject name attributes and request attributes .
- * If empty or not set, the certificate subject name
- * will be used as the ldap dn. <p>
+ * The syntax is
*
- * The syntax is
* <pre>
- * dnPattern := rdnPattern *[ "," rdnPattern ]
- * rdnPattern := avaPattern *[ "+" avaPattern ]
+ * dnPattern := rdnPattern *[ "," rdnPattern ]
+ * rdnPattern := avaPattern *[ "+" avaPattern ]
* avaPattern := name "=" value |
- * name "=" "$subj" "." attrName [ "." attrNumber ] |
- * name "=" "$ext" "." extName [ "." nameType ] [ "." attrNumber ]
- * name "=" "$req" "." attrName [ "." attrNumber ] |
- * "$rdn" "." number
+ * name "=" "$subj" "." attrName [ "." attrNumber ] |
+ * name "=" "$ext" "." extName [ "." nameType ] [ "." attrNumber ]
+ * name "=" "$req" "." attrName [ "." attrNumber ] |
+ * "$rdn" "." number
* </pre>
+ *
* <pre>
* Example1: <i>cn=Certificate Manager,ou=people,o=mcom.com</i>
* cert subject name: dn: CN=Certificate Manager, OU=people, O=mcom.com
@@ -72,7 +73,7 @@ import com.netscape.certsrv.request.IRequest;
* <p>
* note: Subordinate ca enrollment will use ca mapper. Use predicate
* to distinguish the ca itself and the subordinates.
- *
+ *
* Example2: <i>UID=$req.HTTP_PARAMS.uid, OU=$subj.ou, OU=people, , O=mcom.com</i>
* cert subject name: dn: UID=jjames, OU=IS, OU=people, , O=mcom.com
* request attributes: uid: cmanager
@@ -97,10 +98,10 @@ import com.netscape.certsrv.request.IRequest;
* O = the string mcom.com. <br>
* <p>
* </pre>
- * If an request attribute or subject DN component does not exist,
- * the attribute is skipped. There is potential risk that a wrong dn
- * will be mapped into.
- *
+ *
+ * If an request attribute or subject DN component does not exist, the attribute
+ * is skipped. There is potential risk that a wrong dn will be mapped into.
+ *
* @version $Revision$, $Date$
*/
class MapAVAPattern {
@@ -120,26 +121,28 @@ class MapAVAPattern {
"EDIName",
"URIName",
"IPAddress",
- "OIDName"};
+ "OIDName" };
private static final char[] endChars = new char[] { '+', ',' };
- private static final LdapV3DNStrConverter mLdapDNStrConverter =
- new LdapV3DNStrConverter();
+ private static final LdapV3DNStrConverter mLdapDNStrConverter =
+ new LdapV3DNStrConverter();
- /* the list of request attributes needed by this AVA */
+ /* the list of request attributes needed by this AVA */
protected String[] mReqAttrs = null;
- /* the list of cert attributes needed by this AVA*/
+ /* the list of cert attributes needed by this AVA */
protected String[] mCertAttrs = null;
/* value type */
protected String mType = null;
/* the attribute in the AVA pair */
- protected String mAttr = null;
+ protected String mAttr = null;
- /* value - could be name of a request attribute or
- * cert subject dn attribute. */
+ /*
+ * value - could be name of a request attribute or cert subject dn
+ * attribute.
+ */
protected String mValue = null;
/* value type - general name type of an extension attribute if any. */
@@ -154,47 +157,47 @@ class MapAVAPattern {
protected String mTestDN = null;
public MapAVAPattern(String component)
- throws ELdapException {
- if (component == null || component.length() == 0)
+ throws ELdapException {
+ if (component == null || component.length() == 0)
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX", component));
parse(new PushbackReader(new StringReader(component)));
}
- public MapAVAPattern(PushbackReader in)
- throws ELdapException {
+ public MapAVAPattern(PushbackReader in)
+ throws ELdapException {
parse(in);
}
private void parse(PushbackReader in)
- throws ELdapException {
+ throws ELdapException {
int c;
// mark ava beginning.
// skip spaces
- //System.out.println("============ AVAPattern Begin ===========");
- //System.out.println("skip spaces");
+ // System.out.println("============ AVAPattern Begin ===========");
+ // System.out.println("skip spaces");
try {
- while ((c = in.read()) == ' ' || c == '\t') {//System.out.println("spaces read "+(char)c);
+ while ((c = in.read()) == ' ' || c == '\t') {// System.out.println("spaces read "+(char)c);
;
}
} catch (IOException e) {
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX", "All blank"));
}
- if (c == -1)
+ if (c == -1)
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX", "All blank"));
- // $rdn "." number syntax.
+ // $rdn "." number syntax.
if (c == '$') {
- //System.out.println("$rdn syntax");
+ // System.out.println("$rdn syntax");
mType = TYPE_RDN;
try {
- if (in.read() != 'r' ||
- in.read() != 'd' ||
- in.read() != 'n' ||
- in.read() != '.')
+ if (in.read() != 'r' ||
+ in.read() != 'd' ||
+ in.read() != 'n' ||
+ in.read() != '.')
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX", "Invalid $ syntax, expecting $rdn"));
} catch (IOException e) {
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX", "Invalid $ syntax, expecting $rdn"));
@@ -204,7 +207,7 @@ class MapAVAPattern {
try {
while ((c = in.read()) != ',' && c != -1 && c != '+') {
- //System.out.println("rdnNumber read "+(char)c);
+ // System.out.println("rdnNumber read "+(char)c);
rdnNumberBuf.append((char) c);
}
if (c != -1) // either ',' or '+'
@@ -216,7 +219,7 @@ class MapAVAPattern {
String rdnNumber = rdnNumberBuf.toString().trim();
- if (rdnNumber.length() == 0)
+ if (rdnNumber.length() == 0)
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX", "$rdn number not set in ava pattern"));
try {
mElement = Integer.parseInt(rdnNumber) - 1;
@@ -226,20 +229,20 @@ class MapAVAPattern {
return;
}
- // name "=" ... syntax.
+ // name "=" ... syntax.
- // read name
- //System.out.println("reading name");
+ // read name
+ // System.out.println("reading name");
- StringBuffer attrBuf = new StringBuffer();
+ StringBuffer attrBuf = new StringBuffer();
try {
while (c != '=' && c != -1 && c != ',' && c != '+') {
attrBuf.append((char) c);
c = in.read();
- //System.out.println("name read "+(char)c);
- }
- if (c == ',' || c == '+')
+ // System.out.println("name read "+(char)c);
+ }
+ if (c == ',' || c == '+')
in.unread(c);
} catch (IOException e) {
throw new ELdapException(
@@ -248,39 +251,39 @@ class MapAVAPattern {
if (c != '=')
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX", "Missing \"=\" in ava pattern"));
- // read value
- //System.out.println("reading value");
+ // read value
+ // System.out.println("reading value");
- // skip spaces
- //System.out.println("skip spaces for value");
+ // skip spaces
+ // System.out.println("skip spaces for value");
try {
- while ((c = in.read()) == ' ' || c == '\t') {//System.out.println("spaces2 read "+(char)c);
+ while ((c = in.read()) == ' ' || c == '\t') {// System.out.println("spaces2 read "+(char)c);
;
}
} catch (IOException e) {
throw new ELdapException(
CMS.getUserMessage("CMS_LDAP_INTERNAL_ERROR", e.toString()));
}
- if (c == -1)
+ if (c == -1)
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX", "no value after = in ava pattern"));
if (c == '$') {
- // check for $subj $ext or $req
+ // check for $subj $ext or $req
try {
c = in.read();
- //System.out.println("check $dn or $attr read "+(char)c);
+ // System.out.println("check $dn or $attr read "+(char)c);
} catch (IOException e) {
throw new ELdapException(
CMS.getUserMessage("CMS_LDAP_INTERNAL_ERROR", e.toString()));
}
- if (c == -1)
+ if (c == -1)
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX",
"expecting $subj or $req in ava pattern"));
if (c == 'r') {
try {
- if (in.read() != 'e' ||
- in.read() != 'q' ||
- in.read() != '.')
+ if (in.read() != 'e' ||
+ in.read() != 'q' ||
+ in.read() != '.')
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX",
"expecting $req in ava pattern"));
} catch (IOException e) {
@@ -288,13 +291,13 @@ class MapAVAPattern {
CMS.getUserMessage("CMS_LDAP_INTERNAL_ERROR", e.toString()));
}
mType = TYPE_REQ;
- //System.out.println("---- mtype $req");
+ // System.out.println("---- mtype $req");
} else if (c == 's') {
try {
- if (in.read() != 'u' ||
- in.read() != 'b' ||
- in.read() != 'j' ||
- in.read() != '.')
+ if (in.read() != 'u' ||
+ in.read() != 'b' ||
+ in.read() != 'j' ||
+ in.read() != '.')
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX",
"expecting $subj in ava pattern"));
} catch (IOException e) {
@@ -302,43 +305,40 @@ class MapAVAPattern {
CMS.getUserMessage("CMS_LDAP_INTERNAL_ERROR", e.toString()));
}
mType = TYPE_SUBJ;
- //System.out.println("----- mtype $subj");
+ // System.out.println("----- mtype $subj");
} else if (c == 'e') {
try {
- if (in.read() != 'x' ||
- in.read() != 't' ||
- in.read() != '.')
- throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX",
+ if (in.read() != 'x' ||
+ in.read() != 't' ||
+ in.read() != '.')
+ throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX",
"expecting $ext in ava pattern"));
} catch (IOException e) {
throw new ELdapException(
CMS.getUserMessage("CMS_LDAP_INTERNAL_ERROR", e.toString()));
}
mType = TYPE_EXT;
- //System.out.println("----- mtype $ext");
+ // System.out.println("----- mtype $ext");
} else {
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX",
- "unknown keyword. expecting $subj $ext or $req."));
+ "unknown keyword. expecting $subj $ext or $req."));
}
- // get request attr name of subject dn pattern from above.
+ // get request attr name of subject dn pattern from above.
String attrName = attrBuf.toString().trim();
- //System.out.println("----- attrName "+attrName);
- if (attrName.length() == 0)
+ // System.out.println("----- attrName "+attrName);
+ if (attrName.length() == 0)
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX", "attribute name expected"));
- mAttr = attrName;
+ mAttr = attrName;
/*
- try {
- ObjectIdentifier attrOid =
- mLdapDNStrConverter.parseAVAKeyword(attrName);
- mAttr = mLdapDNStrConverter.encodeOID(attrOid);
- //System.out.println("----- mAttr "+mAttr);
- }
- catch (IOException e) {
- throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX", e.toString()));
- }
+ * try { ObjectIdentifier attrOid =
+ * mLdapDNStrConverter.parseAVAKeyword(attrName); mAttr =
+ * mLdapDNStrConverter.encodeOID(attrOid);
+ * //System.out.println("----- mAttr "+mAttr); } catch (IOException
+ * e) { throw new ECompSyntaxErr(CMS.getUserMessage(
+ * "CMS_AUTHENTICATION_COMPONENT_SYNTAX", e.toString())); }
*/
// get request attribute or cert subject dn attribute
@@ -346,44 +346,44 @@ class MapAVAPattern {
StringBuffer valueBuf = new StringBuffer();
try {
- while ((c = in.read()) != ',' &&
- c != -1 && c != '.' && c != '+') {
- //System.out.println("mValue read "+(char)c);
+ while ((c = in.read()) != ',' &&
+ c != -1 && c != '.' && c != '+') {
+ // System.out.println("mValue read "+(char)c);
valueBuf.append((char) c);
}
if (c == '+' || c == ',') // either ',' or '+'
- in.unread(c); // pushback last , or +
+ in.unread(c); // pushback last , or +
} catch (IOException e) {
throw new ELdapException(
CMS.getUserMessage("CMS_LDAP_INTERNAL_ERROR", e.toString()));
}
mValue = valueBuf.toString().trim();
- if (mValue.length() == 0)
+ if (mValue.length() == 0)
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX",
"$subj or $req attribute name expected"));
- //System.out.println("----- mValue "+mValue);
+ // System.out.println("----- mValue "+mValue);
- // get nth dn xxx not nth request attribute .
+ // get nth dn xxx not nth request attribute .
if (c == '.') {
StringBuffer attrNumberBuf = new StringBuffer();
try {
while ((c = in.read()) != ',' && c != -1 && c != '.'
- && c != '+') {
- //System.out.println("mElement read "+(char)c);
+ && c != '+') {
+ // System.out.println("mElement read "+(char)c);
attrNumberBuf.append((char) c);
}
- if (c == ',' || c == '+') // either ',' or '+'
- in.unread(c); // pushback last , or +
+ if (c == ',' || c == '+') // either ',' or '+'
+ in.unread(c); // pushback last , or +
} catch (IOException e) {
throw new ELdapException(
CMS.getUserMessage("CMS_LDAP_INTERNAL_ERROR", e.toString()));
}
String attrNumber = attrNumberBuf.toString().trim();
- if (attrNumber.length() == 0)
- throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX",
+ if (attrNumber.length() == 0)
+ throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX",
"nth element $req $ext or $subj expected"));
try {
mElement = Integer.parseInt(attrNumber) - 1;
@@ -393,67 +393,67 @@ class MapAVAPattern {
mValue = attrNumber;
} else if (TYPE_EXT.equals(mType)) {
mGNType = attrNumber;
- } else
- throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX",
+ } else
+ throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX",
"Invalid format in nth element $req $ext or $subj"));
- // get nth request attribute .
+ // get nth request attribute .
if (c == '.') {
StringBuffer attrNumberBuf1 = new StringBuffer();
try {
while ((c = in.read()) != ',' && c != -1 && c != '+') {
- //System.out.println("mElement read "+(char)c);
+ // System.out.println("mElement read "+(char)c);
attrNumberBuf1.append((char) c);
}
if (c != -1) // either ',' or '+'
- in.unread(c); // pushback last , or +
+ in.unread(c); // pushback last , or +
} catch (IOException ex) {
throw new ELdapException(
CMS.getUserMessage("CMS_LDAP_INTERNAL_ERROR", ex.toString()));
}
String attrNumber1 = attrNumberBuf1.toString().trim();
- if (attrNumber1.length() == 0)
- throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX",
+ if (attrNumber1.length() == 0)
+ throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX",
"nth element $req expected"));
- try {
- mElement = Integer.parseInt(attrNumber1) - 1;
+ try {
+ mElement = Integer.parseInt(attrNumber1) - 1;
} catch (NumberFormatException ex) {
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX",
"Invalid format in nth element $req."));
-
+
}
}
}
}
- //System.out.println("----- mElement "+mElement);
+ // System.out.println("----- mElement "+mElement);
} else {
// value is constant. treat as regular ava.
mType = TYPE_CONSTANT;
- //System.out.println("----- mType constant");
- // parse ava value.
+ // System.out.println("----- mType constant");
+ // parse ava value.
StringBuffer valueBuf = new StringBuffer();
valueBuf.append((char) c);
// read forward to get attribute value
try {
- while ((c = in.read()) != ',' &&
- c != -1) {
+ while ((c = in.read()) != ',' &&
+ c != -1) {
valueBuf.append((char) c);
}
if (c == '+' || c == ',') { // either ',' or '+'
- in.unread(c); // pushback last , or +
+ in.unread(c); // pushback last , or +
}
} catch (IOException e) {
throw new ELdapException(
CMS.getUserMessage("CMS_LDAP_INTERNAL_ERROR", e.toString()));
}
- try {
- AVA ava = mLdapDNStrConverter.parseAVA(attrBuf + "=" + valueBuf);
+ try {
+ AVA ava = mLdapDNStrConverter.parseAVA(attrBuf + "=" + valueBuf);
mValue = ava.toLdapDNString();
- //System.out.println("----- mValue "+mValue);
+ // System.out.println("----- mValue "+mValue);
} catch (IOException e) {
throw new ECompSyntaxErr(CMS.getUserMessage("CMS_AUTHENTICATION_COMPONENT_SYNTAX", e.toString()));
}
@@ -461,19 +461,19 @@ class MapAVAPattern {
}
public String formAVA(IRequest req, X500Name subject, CertificateExtensions extensions)
- throws ELdapException {
+ throws ELdapException {
if (TYPE_CONSTANT.equals(mType))
return mValue;
if (TYPE_RDN.equals(mType)) {
String dn = subject.toString();
- if (mTestDN != null)
+ if (mTestDN != null)
dn = mTestDN;
- //System.out.println("AVAPattern Using dn "+mTestDN);
+ // System.out.println("AVAPattern Using dn "+mTestDN);
String[] rdns = LDAPDN.explodeDN(dn, false);
- if (mElement >= rdns.length)
+ if (mElement >= rdns.length)
return null;
return rdns[mElement];
}
@@ -481,9 +481,9 @@ class MapAVAPattern {
if (TYPE_SUBJ.equals(mType)) {
String dn = subject.toString();
- if (mTestDN != null)
+ if (mTestDN != null)
dn = mTestDN;
- //System.out.println("AVAPattern Using dn "+mTestDN);
+ // System.out.println("AVAPattern Using dn "+mTestDN);
String[] rdns = LDAPDN.explodeDN(dn, false);
String value = null;
int nFound = -1;
@@ -494,8 +494,8 @@ class MapAVAPattern {
for (int j = 0; j < avas.length; j++) {
String[] exploded = explodeAVA(avas[j]);
- if (exploded[0].equalsIgnoreCase(mValue) &&
- ++nFound == mElement) {
+ if (exploded[0].equalsIgnoreCase(mValue) &&
+ ++nFound == mElement) {
value = exploded[1];
break;
}
@@ -503,10 +503,10 @@ class MapAVAPattern {
}
if (value == null) {
CMS.debug(
- "MapAVAPattern: attr " + mAttr +
- " not formed from: cert subject " +
- dn +
- "-- no subject component : " + mValue);
+ "MapAVAPattern: attr " + mAttr +
+ " not formed from: cert subject " +
+ dn +
+ "-- no subject component : " + mValue);
return null;
}
return mAttr + "=" + value;
@@ -516,21 +516,19 @@ class MapAVAPattern {
if (extensions != null) {
for (int i = 0; i < extensions.size(); i++) {
Extension ext = (Extension)
- extensions.elementAt(i);
+ extensions.elementAt(i);
String extName = OIDMap.getName(ext.getExtensionId());
int index = extName.lastIndexOf(".");
if (index != -1)
extName = extName.substring(index + 1);
- if (
- extName.equals(mValue)) {
+ if (extName.equals(mValue)) {
// Check the extensions one by one.
// For now, just give subjectAltName as an example.
- if
- (mValue.equalsIgnoreCase(SubjectAlternativeNameExtension.class.getSimpleName())) {
+ if (mValue.equalsIgnoreCase(SubjectAlternativeNameExtension.class.getSimpleName())) {
try {
GeneralNames subjectNames = (GeneralNames)
- ((SubjectAlternativeNameExtension) ext).get(SubjectAlternativeNameExtension.SUBJECT_NAME);
+ ((SubjectAlternativeNameExtension) ext).get(SubjectAlternativeNameExtension.SUBJECT_NAME);
if (subjectNames.size() == 0)
break;
@@ -541,7 +539,8 @@ class MapAVAPattern {
String gname = gn.toString();
index = gname.indexOf(":");
- if (index == -1) break;
+ if (index == -1)
+ break;
String gType = gname.substring(0, index);
if (mGNType != null) {
@@ -563,18 +562,18 @@ class MapAVAPattern {
j++;
}
}
- } catch (IOException e) {
+ } catch (IOException e) {
CMS.debug(
- "MapAVAPattern: Publishing attr not formed from extension." +
- "-- no attr : " + mValue);
+ "MapAVAPattern: Publishing attr not formed from extension." +
+ "-- no attr : " + mValue);
}
}
}
}
}
CMS.debug(
- "MapAVAPattern: Publishing:attr not formed from extension " +
- "-- no attr : " + mValue);
+ "MapAVAPattern: Publishing:attr not formed from extension " +
+ "-- no attr : " + mValue);
return null;
}
@@ -583,8 +582,7 @@ class MapAVAPattern {
// mPrefix and mValue are looked up case-insensitive
String reqAttr = req.getExtDataInString(mPrefix, mValue);
if (reqAttr == null) {
- throw new
- ELdapException(CMS.getUserMessage("CMS_LDAP_NO_REQUEST",
+ throw new ELdapException(CMS.getUserMessage("CMS_LDAP_NO_REQUEST",
mValue, mAttr));
}
return mAttr + "=" + reqAttr;
@@ -608,20 +606,19 @@ class MapAVAPattern {
}
/**
- * Explode RDN into AVAs.
- * Does not handle escaped '+'
- * Java ldap library does not yet support multiple avas per rdn.
- * If RDN is malformed returns empty array.
+ * Explode RDN into AVAs. Does not handle escaped '+' Java ldap library does
+ * not yet support multiple avas per rdn. If RDN is malformed returns empty
+ * array.
*/
public static String[] explodeRDN(String rdn) {
int plus = rdn.indexOf('+');
- if (plus == -1)
+ if (plus == -1)
return new String[] { rdn };
Vector<String> avas = new Vector<String>();
StringTokenizer token = new StringTokenizer(rdn, "+");
- while (token.hasMoreTokens())
+ while (token.hasMoreTokens())
avas.addElement(token.nextToken());
String[] theAvas = new String[avas.size()];
@@ -630,17 +627,15 @@ class MapAVAPattern {
}
/**
- * Explode AVA into name and value.
- * Does not handle escaped '='
- * If AVA is malformed empty array is returned.
+ * Explode AVA into name and value. Does not handle escaped '=' If AVA is
+ * malformed empty array is returned.
*/
public static String[] explodeAVA(String ava) {
int equals = ava.indexOf('=');
- if (equals == -1)
+ if (equals == -1)
return null;
return new String[] {
- ava.substring(0, equals).trim(), ava.substring(equals + 1).trim()};
+ ava.substring(0, equals).trim(), ava.substring(equals + 1).trim() };
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/publish/mappers/MapDNPattern.java b/pki/base/common/src/com/netscape/cms/publish/mappers/MapDNPattern.java
index 5de5e3dd..07405443 100644
--- a/pki/base/common/src/com/netscape/cms/publish/mappers/MapDNPattern.java
+++ b/pki/base/common/src/com/netscape/cms/publish/mappers/MapDNPattern.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.publish.mappers;
-
import java.io.IOException;
import java.io.PushbackReader;
import java.io.StringReader;
@@ -31,25 +30,27 @@ import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.ldap.ELdapException;
import com.netscape.certsrv.request.IRequest;
-
/**
- * class for parsing a DN pattern used to construct a ldap dn from
- * request attributes and cert subject name.<p>
+ * class for parsing a DN pattern used to construct a ldap dn from request
+ * attributes and cert subject name.
+ * <p>
*
- * dnpattern is a string representing a ldap dn pattern to formulate from
- * the certificate subject name attributes and request attributes .
- * If empty or not set, the certificate subject name
- * will be used as the ldap dn. <p>
+ * dnpattern is a string representing a ldap dn pattern to formulate from the
+ * certificate subject name attributes and request attributes . If empty or not
+ * set, the certificate subject name will be used as the ldap dn.
+ * <p>
+ *
+ * The syntax is
*
- * The syntax is
* <pre>
- * dnPattern := rdnPattern *[ "," rdnPattern ]
- * rdnPattern := avaPattern *[ "+" avaPattern ]
+ * dnPattern := rdnPattern *[ "," rdnPattern ]
+ * rdnPattern := avaPattern *[ "+" avaPattern ]
* avaPattern := name "=" value |
- * name "=" "$subj" "." attrName [ "." attrNumber ] |
- * name "=" "$req" "." attrName [ "." attrNumber ] |
- * "$rdn" "." number
+ * name "=" "$subj" "." attrName [ "." attrNumber ] |
+ * name "=" "$req" "." attrName [ "." attrNumber ] |
+ * "$rdn" "." number
* </pre>
+ *
* <pre>
* Example1: <i>cn=Certificate Manager,ou=people,o=mcom.com</i>
* cert subject name: dn: CN=Certificate Manager, OU=people, O=mcom.com
@@ -60,7 +61,7 @@ import com.netscape.certsrv.request.IRequest;
* <p>
* note: Subordinate ca enrollment will use ca mapper. Use predicate
* to distinguish the ca itself and the subordinates.
- *
+ *
* Example2: <i>UID=$req.HTTP_PARAMS.uid, OU=$subj.ou, O=people, , O=mcom.com</i>
* cert subject name: dn: UID=jjames, OU=IS, O=people, , O=mcom.com
* request attributes: uid: cmanager
@@ -73,18 +74,18 @@ import com.netscape.certsrv.request.IRequest;
* O = the string people, mcom.com. <br>
* <p>
* </pre>
- * If an request attribute or subject DN component does not exist,
- * the attribute is skipped. There is potential risk that a wrong dn
- * will be mapped into.
- *
+ *
+ * If an request attribute or subject DN component does not exist, the attribute
+ * is skipped. There is potential risk that a wrong dn will be mapped into.
+ *
* @version $Revision$, $Date$
*/
public class MapDNPattern {
- /* the list of request attriubutes to retrieve*/
+ /* the list of request attriubutes to retrieve */
protected String[] mReqAttrs = null;
- /* the list of cert attriubutes to retrieve*/
+ /* the list of cert attriubutes to retrieve */
protected String[] mCertAttrs = null;
/* rdn patterns */
@@ -95,16 +96,17 @@ public class MapDNPattern {
protected String mTestDN = null;
- /**
+ /**
* Construct a DN pattern by parsing a pattern string.
+ *
* @param pattern the DN pattern
- * @exception EBaseException If parsing error occurs.
+ * @exception EBaseException If parsing error occurs.
*/
public MapDNPattern(String pattern)
- throws ELdapException {
+ throws ELdapException {
if (pattern == null || pattern.equals("")) {
CMS.debug(
- "MapDNPattern: null pattern");
+ "MapDNPattern: null pattern");
} else {
mPatternString = pattern;
PushbackReader in = new PushbackReader(new StringReader(pattern));
@@ -113,13 +115,13 @@ public class MapDNPattern {
}
}
- public MapDNPattern(PushbackReader in)
- throws ELdapException {
+ public MapDNPattern(PushbackReader in)
+ throws ELdapException {
parse(in);
}
private void parse(PushbackReader in)
- throws ELdapException {
+ throws ELdapException {
Vector<MapRDNPattern> rdnPatterns = new Vector<MapRDNPattern>();
MapRDNPattern rdnPattern = null;
int lastChar = -1;
@@ -133,8 +135,7 @@ public class MapDNPattern {
throw new ELdapException(
CMS.getUserMessage("CMS_LDAP_INTERNAL_ERROR", e.toString()));
}
- }
- while (lastChar == ',');
+ } while (lastChar == ',');
mRDNPatterns = new MapRDNPattern[rdnPatterns.size()];
rdnPatterns.copyInto(mRDNPatterns);
@@ -144,8 +145,8 @@ public class MapDNPattern {
for (int i = 0; i < mRDNPatterns.length; i++) {
String[] rdnAttrs = mRDNPatterns[i].getReqAttrs();
- if (rdnAttrs != null && rdnAttrs.length > 0)
- for (int j = 0; j < rdnAttrs.length; j++)
+ if (rdnAttrs != null && rdnAttrs.length > 0)
+ for (int j = 0; j < rdnAttrs.length; j++)
reqAttrs.addElement(rdnAttrs[j]);
}
mReqAttrs = new String[reqAttrs.size()];
@@ -156,8 +157,8 @@ public class MapDNPattern {
for (int i = 0; i < mRDNPatterns.length; i++) {
String[] rdnAttrs = mRDNPatterns[i].getCertAttrs();
- if (rdnAttrs != null && rdnAttrs.length > 0)
- for (int j = 0; j < rdnAttrs.length; j++)
+ if (rdnAttrs != null && rdnAttrs.length > 0)
+ for (int j = 0; j < rdnAttrs.length; j++)
certAttrs.addElement(rdnAttrs[j]);
}
mCertAttrs = new String[certAttrs.size()];
@@ -166,12 +167,13 @@ public class MapDNPattern {
/**
* Form a Ldap v3 DN string from a request and a cert subject name.
+ *
* @param req the request for (un)publish
* @param subject the subjectDN of the certificate
- * @return Ldap v3 DN string to use for base ldap search.
+ * @return Ldap v3 DN string to use for base ldap search.
*/
public String formDN(IRequest req, X500Name subject, CertificateExtensions ext)
- throws ELdapException {
+ throws ELdapException {
StringBuffer formedDN = new StringBuffer();
for (int i = 0; i < mRDNPatterns.length; i++) {
@@ -180,11 +182,11 @@ public class MapDNPattern {
String rdn = mRDNPatterns[i].formRDN(req, subject, ext);
if (rdn != null && rdn.length() != 0) {
- if (formedDN.length() != 0)
- formedDN.append(",");
- formedDN.append(rdn);
+ if (formedDN.length() != 0)
+ formedDN.append(",");
+ formedDN.append(rdn);
} else {
- throw new ELdapException("pattern not matched");
+ throw new ELdapException("pattern not matched");
}
}
return formedDN.toString();
@@ -198,4 +200,3 @@ public class MapDNPattern {
return (String[]) mCertAttrs.clone();
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/publish/mappers/MapRDNPattern.java b/pki/base/common/src/com/netscape/cms/publish/mappers/MapRDNPattern.java
index 65091000..55e25ab2 100644
--- a/pki/base/common/src/com/netscape/cms/publish/mappers/MapRDNPattern.java
+++ b/pki/base/common/src/com/netscape/cms/publish/mappers/MapRDNPattern.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.publish.mappers;
-
import java.io.IOException;
import java.io.PushbackReader;
import java.io.StringReader;
@@ -30,25 +29,27 @@ import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.ldap.ELdapException;
import com.netscape.certsrv.request.IRequest;
-
/**
- * class for parsing a DN pattern used to construct a ldap dn from
- * request attributes and cert subject name.<p>
+ * class for parsing a DN pattern used to construct a ldap dn from request
+ * attributes and cert subject name.
+ * <p>
*
- * dnpattern is a string representing a ldap dn pattern to formulate from
- * the certificate subject name attributes and request attributes .
- * If empty or not set, the certificate subject name
- * will be used as the ldap dn. <p>
+ * dnpattern is a string representing a ldap dn pattern to formulate from the
+ * certificate subject name attributes and request attributes . If empty or not
+ * set, the certificate subject name will be used as the ldap dn.
+ * <p>
+ *
+ * The syntax is
*
- * The syntax is
* <pre>
- * dnPattern := rdnPattern *[ "," rdnPattern ]
- * rdnPattern := avaPattern *[ "+" avaPattern ]
+ * dnPattern := rdnPattern *[ "," rdnPattern ]
+ * rdnPattern := avaPattern *[ "+" avaPattern ]
* avaPattern := name "=" value |
- * name "=" "$subj" "." attrName [ "." attrNumber ] |
- * name "=" "$req" "." attrName [ "." attrNumber ] |
- * "$rdn" "." number
+ * name "=" "$subj" "." attrName [ "." attrNumber ] |
+ * name "=" "$req" "." attrName [ "." attrNumber ] |
+ * "$rdn" "." number
* </pre>
+ *
* <pre>
* Example1: <i>cn=Certificate Manager,ou=people,o=mcom.com</i>
* cert subject name: dn: CN=Certificate Manager, OU=people, O=mcom.com
@@ -59,7 +60,7 @@ import com.netscape.certsrv.request.IRequest;
* <p>
* note: Subordinate ca enrollment will use ca mapper. Use predicate
* to distinguish the ca itself and the subordinates.
- *
+ *
* Example2: <i>UID=$req.HTTP_PARAMS.uid, OU=$subj.ou, O=people, , O=mcom.com</i>
* cert subject name: dn: UID=jjames, OU=IS, O=people, , O=mcom.com
* request attributes: uid: cmanager
@@ -72,18 +73,18 @@ import com.netscape.certsrv.request.IRequest;
* O = the string people, mcom.com. <br>
* <p>
* </pre>
- * If an request attribute or subject DN component does not exist,
- * the attribute is skipped.There is potential risk that a wrong dn
- * will be mapped into.
- *
+ *
+ * If an request attribute or subject DN component does not exist, the attribute
+ * is skipped.There is potential risk that a wrong dn will be mapped into.
+ *
* @version $Revision$, $Date$
*/
class MapRDNPattern {
- /* the list of request attributes needed by this RDN */
+ /* the list of request attributes needed by this RDN */
protected String[] mReqAttrs = null;
- /* the list of cert attributes needed by this RDN */
+ /* the list of cert attributes needed by this RDN */
protected String[] mCertAttrs = null;
/* AVA patterns */
@@ -94,16 +95,17 @@ class MapRDNPattern {
protected String mTestDN = null;
- /**
+ /**
* Construct a DN pattern by parsing a pattern string.
+ *
* @param pattenr the DN pattern
- * @exception ELdapException If parsing error occurs.
+ * @exception ELdapException If parsing error occurs.
*/
public MapRDNPattern(String pattern)
- throws ELdapException {
+ throws ELdapException {
if (pattern == null || pattern.equals("")) {
CMS.debug(
- "MapDNPattern: null pattern");
+ "MapDNPattern: null pattern");
} else {
mPatternString = pattern;
PushbackReader in = new PushbackReader(new StringReader(pattern));
@@ -113,16 +115,16 @@ class MapRDNPattern {
}
/**
- * Construct a DN pattern from a input stream of pattern
+ * Construct a DN pattern from a input stream of pattern
*/
- public MapRDNPattern(PushbackReader in)
- throws ELdapException {
+ public MapRDNPattern(PushbackReader in)
+ throws ELdapException {
parse(in);
}
private void parse(PushbackReader in)
- throws ELdapException {
- //System.out.println("_________ begin rdn _________");
+ throws ELdapException {
+ // System.out.println("_________ begin rdn _________");
Vector<MapAVAPattern> avaPatterns = new Vector<MapAVAPattern>();
MapAVAPattern avaPattern = null;
int lastChar;
@@ -130,23 +132,22 @@ class MapRDNPattern {
do {
avaPattern = new MapAVAPattern(in);
avaPatterns.addElement(avaPattern);
- //System.out.println("added AVAPattern"+
- //" mType "+avaPattern.mType+
- //" mAttr "+avaPattern.mAttr+
- //" mValue "+avaPattern.mValue+
- //" mElement "+avaPattern.mElement);
- try {
- lastChar = in.read();
+ // System.out.println("added AVAPattern"+
+ // " mType "+avaPattern.mType+
+ // " mAttr "+avaPattern.mAttr+
+ // " mValue "+avaPattern.mValue+
+ // " mElement "+avaPattern.mElement);
+ try {
+ lastChar = in.read();
} catch (IOException e) {
throw new ELdapException(
CMS.getUserMessage("CMS_LDAP_INTERNAL_ERROR", e.toString()));
}
- }
- while (lastChar == '+');
+ } while (lastChar == '+');
if (lastChar != -1) {
try {
- in.unread(lastChar); // pushback last ,
+ in.unread(lastChar); // pushback last ,
} catch (IOException e) {
throw new ELdapException(
CMS.getUserMessage("CMS_LDAP_INTERNAL_ERROR", e.toString()));
@@ -161,7 +162,7 @@ class MapRDNPattern {
for (int i = 0; i < mAVAPatterns.length; i++) {
String avaAttr = mAVAPatterns[i].getReqAttr();
- if (avaAttr == null || avaAttr.length() == 0)
+ if (avaAttr == null || avaAttr.length() == 0)
continue;
reqAttrs.addElement(avaAttr);
}
@@ -173,7 +174,7 @@ class MapRDNPattern {
for (int i = 0; i < mAVAPatterns.length; i++) {
String avaAttr = mAVAPatterns[i].getCertAttr();
- if (avaAttr == null || avaAttr.length() == 0)
+ if (avaAttr == null || avaAttr.length() == 0)
continue;
certAttrs.addElement(avaAttr);
}
@@ -183,16 +184,17 @@ class MapRDNPattern {
/**
* Form a Ldap v3 DN string from a request and a cert subject name.
+ *
* @param req the request for (un)publish
* @param subject the subjectDN of the certificate
- * @return Ldap v3 DN string to use for base ldap search.
+ * @return Ldap v3 DN string to use for base ldap search.
*/
public String formRDN(IRequest req, X500Name subject, CertificateExtensions ext)
- throws ELdapException {
+ throws ELdapException {
StringBuffer formedRDN = new StringBuffer();
for (int i = 0; i < mAVAPatterns.length; i++) {
- if (mTestDN != null)
+ if (mTestDN != null)
mAVAPatterns[i].mTestDN = mTestDN;
String ava = mAVAPatterns[i].formAVA(req, subject, ext);
@@ -202,7 +204,7 @@ class MapRDNPattern {
formedRDN.append(ava);
}
}
- //System.out.println("formed RDN "+formedRDN.toString());
+ // System.out.println("formed RDN "+formedRDN.toString());
return formedRDN.toString();
}
diff --git a/pki/base/common/src/com/netscape/cms/publish/mappers/NoMap.java b/pki/base/common/src/com/netscape/cms/publish/mappers/NoMap.java
index b1d10902..db1747d4 100644
--- a/pki/base/common/src/com/netscape/cms/publish/mappers/NoMap.java
+++ b/pki/base/common/src/com/netscape/cms/publish/mappers/NoMap.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.publish.mappers;
-
import java.util.Locale;
import java.util.Vector;
@@ -30,10 +29,9 @@ import com.netscape.certsrv.ldap.ELdapException;
import com.netscape.certsrv.publish.ILdapMapper;
import com.netscape.certsrv.request.IRequest;
-
-/**
+/**
* No Map
- *
+ *
* @version $Revision$, $Date$
*/
public class NoMap implements ILdapMapper, IExtendedPluginInfo {
@@ -56,32 +54,32 @@ public class NoMap implements ILdapMapper, IExtendedPluginInfo {
}
public IConfigStore getConfigStore() {
- return mConfig;
+ return mConfig;
}
- /**
+ /**
* for initializing from config store.
*/
- public void init(IConfigStore config)
- throws EBaseException {
+ public void init(IConfigStore config)
+ throws EBaseException {
mConfig = config;
}
/**
- * Maps a X500 subject name to LDAP entry.
- * Uses DN pattern to form a DN for a LDAP base search.
+ * Maps a X500 subject name to LDAP entry. Uses DN pattern to form a DN for
+ * a LDAP base search.
*
- * @param conn the LDAP connection.
- * @param obj the object to map.
+ * @param conn the LDAP connection.
+ * @param obj the object to map.
* @exception ELdapException if any LDAP exceptions occured.
- */
+ */
public String map(LDAPConnection conn, Object obj)
- throws ELdapException {
+ throws ELdapException {
return null;
}
public String map(LDAPConnection conn, IRequest req, Object obj)
- throws ELdapException {
+ throws ELdapException {
return null;
}
diff --git a/pki/base/common/src/com/netscape/cms/publish/publishers/FileBasedPublisher.java b/pki/base/common/src/com/netscape/cms/publish/publishers/FileBasedPublisher.java
index f0154e44..ab5f2785 100644
--- a/pki/base/common/src/com/netscape/cms/publish/publishers/FileBasedPublisher.java
+++ b/pki/base/common/src/com/netscape/cms/publish/publishers/FileBasedPublisher.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.publish.publishers;
-
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
@@ -47,10 +46,9 @@ import com.netscape.certsrv.ldap.ELdapException;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.publish.ILdapPublisher;
-/**
- * This publisher writes certificate and CRL into
- * a directory.
- *
+/**
+ * This publisher writes certificate and CRL into a directory.
+ *
* @version $Revision$, $Date$
*/
public class FileBasedPublisher implements ILdapPublisher, IExtendedPluginInfo {
@@ -74,10 +72,10 @@ public class FileBasedPublisher implements ILdapPublisher, IExtendedPluginInfo {
protected String mLinkExt = null;
protected int mZipLevel = 9;
- public void setIssuingPointId(String crlIssuingPointId)
- {
+ public void setIssuingPointId(String crlIssuingPointId) {
mCrlIssuingPointId = crlIssuingPointId;
}
+
/**
* Returns the implementation name.
*/
@@ -99,14 +97,14 @@ public class FileBasedPublisher implements ILdapPublisher, IExtendedPluginInfo {
PROP_DER + ";boolean;Store certificates or CRLs into *.der files.",
PROP_B64 + ";boolean;Store certificates or CRLs into *.b64 files.",
PROP_GMT + ";choice(LocalTime,GMT);Use local time or GMT to time stamp CRL file name with CRL's 'thisUpdate' field.",
- PROP_LNK + ";boolean;Generate link to the latest binary CRL. It requires '"+PROP_DER+"' to be enabled.",
+ PROP_LNK + ";boolean;Generate link to the latest binary CRL. It requires '" + PROP_DER + "' to be enabled.",
PROP_EXT + ";string;Name extension used by link to the latest CRL. Default name extension is 'der'.",
PROP_ZIP + ";boolean;Generate compressed CRLs.",
PROP_LEV + ";choice(0,1,2,3,4,5,6,7,8,9);Set compression level from 0 to 9.",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-ldappublish-publisher-filepublisher",
+ ";configuration-ldappublish-publisher-filepublisher",
IExtendedPluginInfo.HELP_TEXT +
- ";Stores the certificates or CRLs into files. Certificate is named as cert-<serialno>.der or *.b64, and CRL is named as <IssuingPoint>-<thisUpdate-time>.der or *.b64."
+ ";Stores the certificates or CRLs into files. Certificate is named as cert-<serialno>.der or *.b64, and CRL is named as <IssuingPoint>-<thisUpdate-time>.der or *.b64."
};
return params;
@@ -139,14 +137,14 @@ public class FileBasedPublisher implements ILdapPublisher, IExtendedPluginInfo {
try {
if (mTimeStamp == null || (!mTimeStamp.equals("GMT")))
mTimeStamp = "LocalTime";
- v.addElement(PROP_DIR+"=" + dir);
- v.addElement(PROP_DER+"=" + mConfig.getBoolean(PROP_DER,true));
- v.addElement(PROP_B64+"=" + mConfig.getBoolean(PROP_B64,false));
- v.addElement(PROP_GMT+"=" + mTimeStamp);
- v.addElement(PROP_LNK+"=" + mConfig.getBoolean(PROP_LNK,false));
- v.addElement(PROP_EXT+"=" + ext);
- v.addElement(PROP_ZIP+"=" + mConfig.getBoolean(PROP_ZIP,false));
- v.addElement(PROP_LEV+"=" + mZipLevel);
+ v.addElement(PROP_DIR + "=" + dir);
+ v.addElement(PROP_DER + "=" + mConfig.getBoolean(PROP_DER, true));
+ v.addElement(PROP_B64 + "=" + mConfig.getBoolean(PROP_B64, false));
+ v.addElement(PROP_GMT + "=" + mTimeStamp);
+ v.addElement(PROP_LNK + "=" + mConfig.getBoolean(PROP_LNK, false));
+ v.addElement(PROP_EXT + "=" + ext);
+ v.addElement(PROP_ZIP + "=" + mConfig.getBoolean(PROP_ZIP, false));
+ v.addElement(PROP_LEV + "=" + mZipLevel);
} catch (Exception e) {
}
return v;
@@ -158,14 +156,14 @@ public class FileBasedPublisher implements ILdapPublisher, IExtendedPluginInfo {
public Vector<String> getDefaultParams() {
Vector<String> v = new Vector<String>();
- v.addElement(PROP_DIR+"=");
- v.addElement(PROP_DER+"=true");
- v.addElement(PROP_B64+"=false");
- v.addElement(PROP_GMT+"=LocalTime");
- v.addElement(PROP_LNK+"=false");
- v.addElement(PROP_EXT+"=");
- v.addElement(PROP_ZIP+"=false");
- v.addElement(PROP_LEV+"=9");
+ v.addElement(PROP_DIR + "=");
+ v.addElement(PROP_DER + "=true");
+ v.addElement(PROP_B64 + "=false");
+ v.addElement(PROP_GMT + "=LocalTime");
+ v.addElement(PROP_LNK + "=false");
+ v.addElement(PROP_EXT + "=");
+ v.addElement(PROP_ZIP + "=false");
+ v.addElement(PROP_LEV + "=9");
return v;
}
@@ -193,7 +191,7 @@ public class FileBasedPublisher implements ILdapPublisher, IExtendedPluginInfo {
}
// convert to forward slash
- dir = dir.replace('\\', '/');
+ dir = dir.replace('\\', '/');
config.putString(PROP_DIR, dir);
File dirCheck = new File(dir);
@@ -209,7 +207,7 @@ public class FileBasedPublisher implements ILdapPublisher, IExtendedPluginInfo {
} catch (Exception e) {
throw new RuntimeException("Invalid Instance Dir " + e);
}
- dirCheck = new File(mInstanceRoot +
+ dirCheck = new File(mInstanceRoot +
File.separator + dir);
if (dirCheck.isDirectory()) {
mDir = mInstanceRoot + File.separator + dir;
@@ -224,7 +222,7 @@ public class FileBasedPublisher implements ILdapPublisher, IExtendedPluginInfo {
}
private String[] getCrlNamePrefix(X509CRL crl, boolean useGMT) {
- String[] namePrefix = {"crl", "crl"};
+ String[] namePrefix = { "crl", "crl" };
if (mCrlIssuingPointId != null && mCrlIssuingPointId.length() != 0) {
namePrefix[0] = mCrlIssuingPointId;
@@ -232,10 +230,11 @@ public class FileBasedPublisher implements ILdapPublisher, IExtendedPluginInfo {
}
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyyMMdd-HHmmss");
TimeZone tz = TimeZone.getTimeZone("GMT");
- if (useGMT) format.setTimeZone(tz);
+ if (useGMT)
+ format.setTimeZone(tz);
String timeStamp = format.format(crl.getThisUpdate()).toString();
namePrefix[0] += "-" + timeStamp;
- if (((netscape.security.x509.X509CRLImpl)crl).isDeltaCRL()) {
+ if (((netscape.security.x509.X509CRLImpl) crl).isDeltaCRL()) {
namePrefix[0] += "-delta";
namePrefix[1] += "-delta";
}
@@ -243,23 +242,23 @@ public class FileBasedPublisher implements ILdapPublisher, IExtendedPluginInfo {
return namePrefix;
}
- private void createLink(String linkName, String fileName) {
+ private void createLink(String linkName, String fileName) {
String cmd = "ln -s " + fileName + " " + linkName + ".new";
if (com.netscape.cmsutil.util.Utils.exec(cmd)) {
File oldLink = new File(linkName + ".old");
- if (oldLink.exists()) { // remove old link if exists
+ if (oldLink.exists()) { // remove old link if exists
oldLink.delete();
}
File link = new File(linkName);
- if (link.exists()) { // current link becomes an old link
+ if (link.exists()) { // current link becomes an old link
link.renameTo(new File(linkName + ".old"));
}
File newLink = new File(linkName + ".new");
- if (newLink.exists()) { // new link becomes current link
+ if (newLink.exists()) { // new link becomes current link
newLink.renameTo(new File(linkName));
}
oldLink = new File(linkName + ".old");
- if (oldLink.exists()) { // remove a new old link
+ if (oldLink.exists()) { // remove a new old link
oldLink.delete();
}
} else {
@@ -270,38 +269,34 @@ public class FileBasedPublisher implements ILdapPublisher, IExtendedPluginInfo {
/**
* Publishs a object to the ldap directory.
*
- * @param conn a Ldap connection
- * (null if LDAP publishing is not enabled)
- * @param dn dn of the ldap entry to publish cert
- * (null if LDAP publishing is not enabled)
- * @param object object to publish
- * (java.security.cert.X509Certificate or,
- * java.security.cert.X509CRL)
+ * @param conn a Ldap connection (null if LDAP publishing is not enabled)
+ * @param dn dn of the ldap entry to publish cert (null if LDAP publishing
+ * is not enabled)
+ * @param object object to publish (java.security.cert.X509Certificate or,
+ * java.security.cert.X509CRL)
*/
public void publish(LDAPConnection conn, String dn, Object object)
- throws ELdapException {
+ throws ELdapException {
CMS.debug("FileBasedPublisher: publish");
try {
if (object instanceof X509Certificate) {
X509Certificate cert = (X509Certificate) object;
BigInteger sno = cert.getSerialNumber();
String name = mDir +
- File.separator + "cert-" +
- sno.toString();
- if (mDerAttr)
- {
+ File.separator + "cert-" +
+ sno.toString();
+ if (mDerAttr) {
String fileName = name + ".der";
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(cert.getEncoded());
fos.close();
}
- if (mB64Attr)
- {
+ if (mB64Attr) {
String fileName = name + ".b64";
FileOutputStream fos = new FileOutputStream(fileName);
ByteArrayOutputStream output = new ByteArrayOutputStream();
Base64OutputStream b64 =
- new Base64OutputStream(new PrintStream(new FilterOutputStream(output)));
+ new Base64OutputStream(new PrintStream(new FilterOutputStream(output)));
b64.write(cert.getEncoded());
b64.flush();
(new PrintStream(fos)).print(output.toString("8859_1"));
@@ -314,7 +309,7 @@ public class FileBasedPublisher implements ILdapPublisher, IExtendedPluginInfo {
String tempFile = baseName + ".temp";
FileOutputStream fos;
ZipOutputStream zos;
- byte [] encodedArray = null;
+ byte[] encodedArray = null;
File destFile = null;
String destName = null;
File renameFile = null;
@@ -325,16 +320,16 @@ public class FileBasedPublisher implements ILdapPublisher, IExtendedPluginInfo {
fos.write(encodedArray);
fos.close();
if (mZipCRL) {
- zos = new ZipOutputStream(new FileOutputStream(baseName+".zip"));
+ zos = new ZipOutputStream(new FileOutputStream(baseName + ".zip"));
zos.setLevel(mZipLevel);
- zos.putNextEntry(new ZipEntry(baseName+".der"));
+ zos.putNextEntry(new ZipEntry(baseName + ".der"));
zos.write(encodedArray, 0, encodedArray.length);
zos.closeEntry();
zos.close();
}
destName = baseName + ".der";
destFile = new File(destName);
-
+
if (destFile.exists())
destFile.delete();
renameFile = new File(tempFile);
@@ -348,58 +343,55 @@ public class FileBasedPublisher implements ILdapPublisher, IExtendedPluginInfo {
linkExt += "der";
}
String linkName = mDir + File.separator + namePrefix[1] + linkExt;
- createLink(linkName, destName);
+ createLink(linkName, destName);
if (mZipCRL) {
linkName = mDir + File.separator + namePrefix[1] + ".zip";
- createLink(linkName, baseName+".zip");
+ createLink(linkName, baseName + ".zip");
}
}
}
-
+
// output base64 file
- if(mB64Attr==true)
- {
- if (encodedArray ==null)
- encodedArray = crl.getEncoded();
-
- ByteArrayOutputStream os = new ByteArrayOutputStream();
-
- fos = new FileOutputStream(tempFile);
- fos.write(com.netscape.osutil.OSUtil.BtoA(encodedArray).getBytes());
- fos.close();
- destName = baseName + ".b64";
- destFile = new File(destName);
-
- if(destFile.exists())
- destFile.delete();
- renameFile = new File(tempFile);
- renameFile.renameTo(destFile);
- }
+ if (mB64Attr == true) {
+ if (encodedArray == null)
+ encodedArray = crl.getEncoded();
+
+ ByteArrayOutputStream os = new ByteArrayOutputStream();
+
+ fos = new FileOutputStream(tempFile);
+ fos.write(com.netscape.osutil.OSUtil.BtoA(encodedArray).getBytes());
+ fos.close();
+ destName = baseName + ".b64";
+ destFile = new File(destName);
+
+ if (destFile.exists())
+ destFile.delete();
+ renameFile = new File(tempFile);
+ renameFile.renameTo(destFile);
+ }
}
} catch (IOException e) {
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_FILE_PUBLISHER_ERROR", e.toString()));
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
+ ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_FILE_PUBLISHER_ERROR", e.toString()));
} catch (CertificateEncodingException e) {
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_FILE_PUBLISHER_ERROR", e.toString()));
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
+ ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_FILE_PUBLISHER_ERROR", e.toString()));
} catch (CRLException e) {
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_FILE_PUBLISHER_ERROR", e.toString()));
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
+ ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_FILE_PUBLISHER_ERROR", e.toString()));
}
}
/**
* Unpublishs a object to the ldap directory.
- *
- * @param conn the Ldap connection
- * (null if LDAP publishing is not enabled)
- * @param dn dn of the ldap entry to unpublish cert
- * (null if LDAP publishing is not enabled)
- * @param object object to unpublish
- * (java.security.cert.X509Certificate)
+ *
+ * @param conn the Ldap connection (null if LDAP publishing is not enabled)
+ * @param dn dn of the ldap entry to unpublish cert (null if LDAP publishing
+ * is not enabled)
+ * @param object object to unpublish (java.security.cert.X509Certificate)
*/
public void unpublish(LDAPConnection conn, String dn, Object object)
- throws ELdapException {
+ throws ELdapException {
CMS.debug("FileBasedPublisher: unpublish");
String name = mDir + File.separator;
String fileName;
@@ -425,13 +417,15 @@ public class FileBasedPublisher implements ILdapPublisher, IExtendedPluginInfo {
f = new File(fileName);
f.delete();
}
- /**
+
+ /**
* returns the Der attribute where it'll be published.
*/
public boolean getDerAttr() {
return mDerAttr;
}
- /**
+
+ /**
* returns the B64 attribute where it'll be published.
*/
public boolean getB64Attr() {
diff --git a/pki/base/common/src/com/netscape/cms/publish/publishers/LdapCaCertPublisher.java b/pki/base/common/src/com/netscape/cms/publish/publishers/LdapCaCertPublisher.java
index 4727a690..746d9118 100644
--- a/pki/base/common/src/com/netscape/cms/publish/publishers/LdapCaCertPublisher.java
+++ b/pki/base/common/src/com/netscape/cms/publish/publishers/LdapCaCertPublisher.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.publish.publishers;
-
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.Locale;
@@ -42,14 +41,13 @@ import com.netscape.certsrv.ldap.ELdapServerDownException;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.publish.ILdapPublisher;
-
-/**
- * Interface for publishing a CA certificate to
- *
+/**
+ * Interface for publishing a CA certificate to
+ *
* @version $Revision$, $Date$
*/
-public class LdapCaCertPublisher
- implements ILdapPublisher, IExtendedPluginInfo {
+public class LdapCaCertPublisher
+ implements ILdapPublisher, IExtendedPluginInfo {
public static final String LDAP_CACERT_ATTR = "caCertificate;binary";
public static final String LDAP_CA_OBJECTCLASS = "pkiCA";
public static final String LDAP_ARL_ATTR = "authorityRevocationList;binary";
@@ -64,7 +62,6 @@ public class LdapCaCertPublisher
private boolean mInited = false;
protected IConfigStore mConfig = null;
private String mcrlIssuingPointId;
-
/**
* constructor constructs default values.
@@ -76,13 +73,13 @@ public class LdapCaCertPublisher
String s[] = {
"caCertAttr;string;Name of Ldap attribute in which to store certificate",
"caObjectClass;string;The name of the objectclasses which should be " +
- "added to this entry, if they do not already exist. This can be " +
- "'certificationAuthority' (if using RFC 2256) or 'pkiCA' (if using RFC 4523)",
+ "added to this entry, if they do not already exist. This can be " +
+ "'certificationAuthority' (if using RFC 2256) or 'pkiCA' (if using RFC 4523)",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-ldappublish-publisher-cacertpublisher",
+ ";configuration-ldappublish-publisher-cacertpublisher",
IExtendedPluginInfo.HELP_TEXT +
- ";This plugin knows how to publish the CA cert to " +
- "'certificateAuthority' and 'pkiCA' -type entries"
+ ";This plugin knows how to publish the CA cert to " +
+ "'certificateAuthority' and 'pkiCA' -type entries"
};
return s;
@@ -117,12 +114,12 @@ public class LdapCaCertPublisher
}
public void init(IConfigStore config)
- throws EBaseException {
- if (mInited)
+ throws EBaseException {
+ if (mInited)
return;
mConfig = config;
mCaCertAttr = mConfig.getString("caCertAttr", LDAP_CACERT_ATTR);
- mCaObjectclass = mConfig.getString("caObjectClass",
+ mCaObjectclass = mConfig.getString("caObjectClass",
LDAP_CA_OBJECTCLASS);
mObjAdded = mConfig.getString("caObjectClassAdded", "");
mObjDeleted = mConfig.getString("caObjectClassDeleted", "");
@@ -151,16 +148,16 @@ public class LdapCaCertPublisher
}
/**
- * publish a CA certificate
- * Adds the cert to the multi-valued certificate attribute as a
- * DER encoded binary blob. Does not check if cert already exists.
- * Converts the class to certificateAuthority.
+ * publish a CA certificate Adds the cert to the multi-valued certificate
+ * attribute as a DER encoded binary blob. Does not check if cert already
+ * exists. Converts the class to certificateAuthority.
+ *
* @param conn the LDAP connection
* @param dn dn of the entry to publish the certificate
- * @param certObj the certificate object.
+ * @param certObj the certificate object.
*/
public void publish(LDAPConnection conn, String dn, Object certObj)
- throws ELdapException {
+ throws ELdapException {
if (conn == null) {
log(ILogger.LL_INFO, "LdapCaCertPublisher: no LDAP connection");
return;
@@ -176,31 +173,30 @@ public class LdapCaCertPublisher
// see if we should create local connection
LDAPConnection altConn = null;
try {
- String host = mConfig.getString("host", null);
- String port = mConfig.getString("port", null);
- if (host != null && port != null) {
- int portVal = Integer.parseInt(port);
- int version = Integer.parseInt(mConfig.getString("version", "2"));
- String cert_nick = mConfig.getString("clientCertNickname", null);
- LDAPSSLSocketFactoryExt sslSocket = null;
- if (cert_nick != null) {
- sslSocket = CMS.getLdapJssSSLSocketFactory(cert_nick);
+ String host = mConfig.getString("host", null);
+ String port = mConfig.getString("port", null);
+ if (host != null && port != null) {
+ int portVal = Integer.parseInt(port);
+ int version = Integer.parseInt(mConfig.getString("version", "2"));
+ String cert_nick = mConfig.getString("clientCertNickname", null);
+ LDAPSSLSocketFactoryExt sslSocket = null;
+ if (cert_nick != null) {
+ sslSocket = CMS.getLdapJssSSLSocketFactory(cert_nick);
+ }
+ String mgr_dn = mConfig.getString("bindDN", null);
+ String mgr_pwd = mConfig.getString("bindPWD", null);
+
+ altConn = CMS.getBoundConnection(host, portVal,
+ version,
+ sslSocket, mgr_dn, mgr_pwd);
+ conn = altConn;
}
- String mgr_dn = mConfig.getString("bindDN", null);
- String mgr_pwd = mConfig.getString("bindPWD", null);
-
- altConn = CMS.getBoundConnection(host, portVal,
- version,
- sslSocket, mgr_dn, mgr_pwd);
- conn = altConn;
- }
} catch (LDAPException e) {
- CMS.debug("Failed to create alt connection " + e);
+ CMS.debug("Failed to create alt connection " + e);
} catch (EBaseException e) {
- CMS.debug("Failed to create alt connection " + e);
+ CMS.debug("Failed to create alt connection " + e);
}
-
if (!(certObj instanceof X509Certificate))
throw new IllegalArgumentException("Illegal arg to publish");
@@ -210,40 +206,40 @@ public class LdapCaCertPublisher
byte[] certEnc = cert.getEncoded();
/* search for attribute names to determine existence of attributes */
- LDAPSearchResults res =
- conn.search(dn, LDAPv2.SCOPE_BASE, "(objectclass=*)",
- new String[] { LDAP_CRL_ATTR, LDAP_ARL_ATTR }, true);
+ LDAPSearchResults res =
+ conn.search(dn, LDAPv2.SCOPE_BASE, "(objectclass=*)",
+ new String[] { LDAP_CRL_ATTR, LDAP_ARL_ATTR }, true);
LDAPEntry entry = res.next();
LDAPAttribute arls = entry.getAttribute(LDAP_ARL_ATTR);
LDAPAttribute crls = entry.getAttribute(LDAP_CRL_ATTR);
/* search for objectclass and caCert values */
- LDAPSearchResults res1 =
- conn.search(dn, LDAPv2.SCOPE_BASE, "(objectclass=*)",
- new String[] { "objectclass", mCaCertAttr }, false);
+ LDAPSearchResults res1 =
+ conn.search(dn, LDAPv2.SCOPE_BASE, "(objectclass=*)",
+ new String[] { "objectclass", mCaCertAttr }, false);
LDAPEntry entry1 = res1.next();
LDAPAttribute ocs = entry1.getAttribute("objectclass");
LDAPAttribute certs = entry1.getAttribute(mCaCertAttr);
- boolean hasCert =
- LdapUserCertPublisher.ByteValueExists(certs, certEnc);
+ boolean hasCert =
+ LdapUserCertPublisher.ByteValueExists(certs, certEnc);
LDAPModificationSet modSet = new LDAPModificationSet();
if (hasCert) {
log(ILogger.LL_INFO, "publish: CA " + dn + " already has Cert");
- } else {
+ } else {
/*
- fix for 360458 - if no cert, use add, if has cert but
- not equal, use replace
+ * fix for 360458 - if no cert, use add, if has cert but not
+ * equal, use replace
*/
if (certs == null) {
- modSet.add(LDAPModification.ADD,
- new LDAPAttribute(mCaCertAttr, certEnc));
+ modSet.add(LDAPModification.ADD,
+ new LDAPAttribute(mCaCertAttr, certEnc));
log(ILogger.LL_INFO, "CA cert added");
} else {
- modSet.add(LDAPModification.REPLACE,
- new LDAPAttribute(mCaCertAttr, certEnc));
+ modSet.add(LDAPModification.REPLACE,
+ new LDAPAttribute(mCaCertAttr, certEnc));
log(ILogger.LL_INFO, "CA cert replaced");
}
}
@@ -251,22 +247,22 @@ public class LdapCaCertPublisher
String[] oclist = mCaObjectclass.split(",");
boolean attrsAdded = false;
- for (int i=0; i < oclist.length; i++) {
+ for (int i = 0; i < oclist.length; i++) {
String oc = oclist[i].trim();
boolean hasoc = LdapUserCertPublisher.StringValueExists(ocs, oc);
if (!hasoc) {
log(ILogger.LL_INFO, "adding CA objectclass " + oc + " to " + dn);
modSet.add(LDAPModification.ADD,
- new LDAPAttribute("objectclass", oc));
+ new LDAPAttribute("objectclass", oc));
if ((!attrsAdded) && oc.equalsIgnoreCase("certificationAuthority")) {
// add MUST attributes
- if (arls == null)
+ if (arls == null)
modSet.add(LDAPModification.ADD,
- new LDAPAttribute(LDAP_ARL_ATTR, ""));
+ new LDAPAttribute(LDAP_ARL_ATTR, ""));
if (crls == null)
modSet.add(LDAPModification.ADD,
- new LDAPAttribute(LDAP_CRL_ATTR, ""));
+ new LDAPAttribute(LDAP_CRL_ATTR, ""));
attrsAdded = true;
}
}
@@ -275,15 +271,15 @@ public class LdapCaCertPublisher
// delete objectclasses that have been deleted from config
String[] delList = mObjDeleted.split(",");
if (delList.length > 0) {
- for (int i=0; i< delList.length; i++) {
+ for (int i = 0; i < delList.length; i++) {
String deloc = delList[i].trim();
boolean hasoc = LdapUserCertPublisher.StringValueExists(ocs, deloc);
boolean match = false;
- for (int j=0; j< oclist.length; j++) {
+ for (int j = 0; j < oclist.length; j++) {
if ((oclist[j].trim()).equals(deloc)) {
match = true;
break;
- }
+ }
}
if (!match && hasoc) {
log(ILogger.LL_INFO, "deleting CA objectclass " + deloc + " from " + dn);
@@ -294,7 +290,7 @@ public class LdapCaCertPublisher
}
// reset mObjAdded and mObjDeleted, if needed
- if ((!mObjAdded.equals("")) || (!mObjDeleted.equals(""))) {
+ if ((!mObjAdded.equals("")) || (!mObjDeleted.equals(""))) {
mObjAdded = "";
mObjDeleted = "";
mConfig.putString("caObjectClassAdded", "");
@@ -305,8 +301,9 @@ public class LdapCaCertPublisher
log(ILogger.LL_INFO, "Failure in updating mObjAdded and mObjDeleted");
}
}
-
- if (modSet.size() > 0) conn.modify(dn, modSet);
+
+ if (modSet.size() > 0)
+ conn.modify(dn, modSet);
} catch (CertificateEncodingException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_CANT_DECODE_CERT", dn));
throw new ELdapException(CMS.getUserMessage("CMS_LDAP_GET_DER_ENCODED_CERT_FAILED", e.toString()));
@@ -315,32 +312,31 @@ public class LdapCaCertPublisher
// need to intercept this because message from LDAP is
// "DSA is unavailable" which confuses with DSA PKI.
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
+ CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
throw new ELdapServerDownException(CMS.getUserMessage("CMS_LDAP_SERVER_UNAVAILABLE", conn.getHost(), "" + conn.getPort()));
} else {
log(ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_PUBLISHER_EXCEPTION", "", e.toString()));
throw new ELdapException(CMS.getUserMessage("CMS_LDAP_PUBLISH_CACERT_ERROR", e.toString()));
}
} finally {
- if (altConn != null) {
- try {
- altConn.disconnect();
- } catch (LDAPException e) {
- // safely ignored
- }
- }
+ if (altConn != null) {
+ try {
+ altConn.disconnect();
+ } catch (LDAPException e) {
+ // safely ignored
+ }
+ }
}
return;
}
/**
- * deletes the certificate from CA's certificate attribute.
- * if it's the last cert will also remove the certificateAuthority
- * objectclass.
+ * deletes the certificate from CA's certificate attribute. if it's the last
+ * cert will also remove the certificateAuthority objectclass.
*/
public void unpublish(LDAPConnection conn, String dn, Object certObj)
- throws ELdapException {
+ throws ELdapException {
if (!(certObj instanceof X509Certificate))
throw new IllegalArgumentException("Illegal arg to publish");
@@ -355,43 +351,43 @@ public class LdapCaCertPublisher
try {
byte[] certEnc = cert.getEncoded();
- LDAPSearchResults res =
- conn.search(dn, LDAPv2.SCOPE_BASE, "(objectclass=*)",
- new String[] { mCaCertAttr, "objectclass" }, false);
+ LDAPSearchResults res =
+ conn.search(dn, LDAPv2.SCOPE_BASE, "(objectclass=*)",
+ new String[] { mCaCertAttr, "objectclass" }, false);
LDAPEntry entry = res.next();
LDAPAttribute certs = entry.getAttribute(mCaCertAttr);
LDAPAttribute ocs = entry.getAttribute("objectclass");
- boolean hasCert =
- LdapUserCertPublisher.ByteValueExists(certs, certEnc);
+ boolean hasCert =
+ LdapUserCertPublisher.ByteValueExists(certs, certEnc);
if (!hasCert) {
log(ILogger.LL_INFO, "unpublish: " + dn + " has not cert already");
- //throw new ELdapException(
- // LdapResources.ALREADY_UNPUBLISHED_1, dn);
+ // throw new ELdapException(
+ // LdapResources.ALREADY_UNPUBLISHED_1, dn);
return;
}
LDAPModificationSet modSet = new LDAPModificationSet();
modSet.add(LDAPModification.DELETE,
- new LDAPAttribute(mCaCertAttr, certEnc));
+ new LDAPAttribute(mCaCertAttr, certEnc));
if (certs.size() == 1) {
// if last ca cert, remove oc also.
- String[] oclist = mCaObjectclass.split(",");
- for (int i =0 ; i < oclist.length; i++) {
+ String[] oclist = mCaObjectclass.split(",");
+ for (int i = 0; i < oclist.length; i++) {
String oc = oclist[i].trim();
- boolean hasOC = LdapUserCertPublisher.StringValueExists(ocs, oc);
+ boolean hasOC = LdapUserCertPublisher.StringValueExists(ocs, oc);
if (hasOC) {
log(ILogger.LL_INFO, "unpublish: deleting CA oc" + oc + " from " + dn);
modSet.add(LDAPModification.DELETE,
- new LDAPAttribute("objectclass", oc));
+ new LDAPAttribute("objectclass", oc));
}
- }
+ }
}
- conn.modify(dn, modSet);
+ conn.modify(dn, modSet);
} catch (CertificateEncodingException e) {
CMS.debug("LdapCaCertPublisher: unpublish: Cannot decode cert for " + dn);
throw new ELdapException(CMS.getUserMessage("CMS_LDAP_GET_DER_ENCODED_CERT_FAILED", e.toString()));
@@ -400,7 +396,7 @@ public class LdapCaCertPublisher
// need to intercept this because message from LDAP is
// "DSA is unavailable" which confuses with DSA PKI.
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
+ CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
throw new ELdapServerDownException(CMS.getUserMessage("CMS_LDAP_SERVER_UNAVAILABLE", conn.getHost(), "" + conn.getPort()));
} else {
log(ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_UNPUBLISH_ERROR", e.toString()));
@@ -415,7 +411,7 @@ public class LdapCaCertPublisher
*/
private void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_LDAP, level,
- "LdapCaPublisher: " + msg);
+ "LdapCaPublisher: " + msg);
}
}
diff --git a/pki/base/common/src/com/netscape/cms/publish/publishers/LdapCertSubjPublisher.java b/pki/base/common/src/com/netscape/cms/publish/publishers/LdapCertSubjPublisher.java
index 50cfd7c5..2abb9e0a 100644
--- a/pki/base/common/src/com/netscape/cms/publish/publishers/LdapCertSubjPublisher.java
+++ b/pki/base/common/src/com/netscape/cms/publish/publishers/LdapCertSubjPublisher.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.publish.publishers;
-
import java.io.IOException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
@@ -44,12 +43,11 @@ import com.netscape.certsrv.ldap.ELdapServerDownException;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.publish.ILdapPublisher;
-
-/**
- * Interface for mapping a X509 certificate to a LDAP entry
- * Publishes a certificate as binary and its subject name.
- * there is one subject name value for each certificate.
- *
+/**
+ * Interface for mapping a X509 certificate to a LDAP entry Publishes a
+ * certificate as binary and its subject name. there is one subject name value
+ * for each certificate.
+ *
* @version $Revision$, $Date$
*/
public class LdapCertSubjPublisher implements ILdapPublisher {
@@ -97,20 +95,20 @@ public class LdapCertSubjPublisher implements ILdapPublisher {
}
public void init(IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
if (mInited)
return;
mConfig = config;
- mCertAttr = mConfig.getString("certAttr",
+ mCertAttr = mConfig.getString("certAttr",
LdapUserCertPublisher.LDAP_USERCERT_ATTR);
- mSubjNameAttr = mConfig.getString("certSubjectName",
+ mSubjNameAttr = mConfig.getString("certSubjectName",
LDAP_CERTSUBJNAME_ATTR);
mInited = true;
}
/**
- * constrcutor using specified certificate attribute and
- * certificate subject name attribute.
+ * constrcutor using specified certificate attribute and certificate subject
+ * name attribute.
*/
public LdapCertSubjPublisher(String certAttr, String subjNameAttr) {
mCertAttr = certAttr;
@@ -134,19 +132,21 @@ public class LdapCertSubjPublisher implements ILdapPublisher {
}
/**
- * publish a user certificate
- * Adds the cert to the multi-valued certificate attribute as a
- * DER encoded binary blob. Does not check if cert already exists.
- * Then adds the subject name of the cert to the subject name attribute.
+ * publish a user certificate Adds the cert to the multi-valued certificate
+ * attribute as a DER encoded binary blob. Does not check if cert already
+ * exists. Then adds the subject name of the cert to the subject name
+ * attribute.
+ *
* @param conn the LDAP connection
* @param dn dn of the entry to publish the certificate
- * @param certObj the certificate object.
- * @exception ELdapException if cert or subject name already exists,
- * if cert encoding fails, if getting cert subject name fails.
- * Use ELdapException.getException() to find underlying exception.
+ * @param certObj the certificate object.
+ * @exception ELdapException if cert or subject name already exists, if cert
+ * encoding fails, if getting cert subject name fails. Use
+ * ELdapException.getException() to find underlying
+ * exception.
*/
public void publish(LDAPConnection conn, String dn, Object certObj)
- throws ELdapException {
+ throws ELdapException {
if (conn == null) {
log(ILogger.LL_INFO, "LdapCertSubjPublisher: no LDAP connection");
return;
@@ -162,9 +162,9 @@ public class LdapCertSubjPublisher implements ILdapPublisher {
byte[] certEnc = cert.getEncoded();
String subjName = ((X500Name) cert.getSubjectDN()).toLdapDNString();
- LDAPSearchResults res =
- conn.search(dn, LDAPv2.SCOPE_BASE, "(objectclass=*)",
- new String[] { mCertAttr, mSubjNameAttr }, false);
+ LDAPSearchResults res =
+ conn.search(dn, LDAPv2.SCOPE_BASE, "(objectclass=*)",
+ new String[] { mCertAttr, mSubjNameAttr }, false);
LDAPEntry entry = res.next();
LDAPAttribute certs = entry.getAttribute(mCertAttr);
@@ -177,14 +177,14 @@ public class LdapCertSubjPublisher implements ILdapPublisher {
// check if has subject name already.
if (subjnames != null) {
- hasSubjname =
+ hasSubjname =
LdapUserCertPublisher.StringValueExists(subjnames, subjName);
}
// if has both, done.
if (hasCert && hasSubjname) {
- log(ILogger.LL_INFO,
- "publish: " + subjName + " already has cert & subject name");
+ log(ILogger.LL_INFO,
+ "publish: " + subjName + " already has cert & subject name");
return;
}
@@ -193,14 +193,14 @@ public class LdapCertSubjPublisher implements ILdapPublisher {
if (!hasCert) {
log(ILogger.LL_INFO, "publish: adding cert to " + subjName);
- modSet.add(LDAPModification.ADD,
- new LDAPAttribute(mCertAttr, certEnc));
+ modSet.add(LDAPModification.ADD,
+ new LDAPAttribute(mCertAttr, certEnc));
}
// add subject name if not already there.
if (!hasSubjname) {
log(ILogger.LL_INFO, "publish: adding " + subjName + " to " + dn);
- modSet.add(LDAPModification.ADD,
- new LDAPAttribute(mSubjNameAttr, subjName));
+ modSet.add(LDAPModification.ADD,
+ new LDAPAttribute(mSubjNameAttr, subjName));
}
conn.modify(dn, modSet);
} catch (CertificateEncodingException e) {
@@ -211,7 +211,7 @@ public class LdapCertSubjPublisher implements ILdapPublisher {
// need to intercept this because message from LDAP is
// "DSA is unavailable" which confuses with DSA PKI.
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
+ CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
throw new ELdapServerDownException(CMS.getUserMessage("CMS_LDAP_SERVER_UNAVAILABLE", conn.getHost(), "" + conn.getPort()));
} else {
log(ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_PUBLISHER_EXCEPTION", "", e.toString()));
@@ -224,13 +224,12 @@ public class LdapCertSubjPublisher implements ILdapPublisher {
}
/**
- * deletes the certificate from the list of certificates.
- * does not check if certificate is already there.
- * also takes out the subject name if no other certificate remain
- * with the same subject name.
+ * deletes the certificate from the list of certificates. does not check if
+ * certificate is already there. also takes out the subject name if no other
+ * certificate remain with the same subject name.
*/
public void unpublish(LDAPConnection conn, String dn, Object certObj)
- throws ELdapException {
+ throws ELdapException {
if (!(certObj instanceof X509Certificate))
throw new IllegalArgumentException("Illegal arg to publish");
@@ -242,9 +241,9 @@ public class LdapCertSubjPublisher implements ILdapPublisher {
byte[] certEnc = cert.getEncoded();
- LDAPSearchResults res =
- conn.search(dn, LDAPv2.SCOPE_BASE, "(objectclass=*)",
- new String[] { mCertAttr, mSubjNameAttr }, false);
+ LDAPSearchResults res =
+ conn.search(dn, LDAPv2.SCOPE_BASE, "(objectclass=*)",
+ new String[] { mCertAttr, mSubjNameAttr }, false);
LDAPEntry entry = res.next();
LDAPAttribute certs = entry.getAttribute(mCertAttr);
@@ -266,8 +265,8 @@ public class LdapCertSubjPublisher implements ILdapPublisher {
try {
X509CertImpl certval = new X509CertImpl(val);
// XXX use some sort of X500name equals function here.
- String subjnam =
- ((X500Name) certval.getSubjectDN()).toLdapDNString();
+ String subjnam =
+ ((X500Name) certval.getSubjectDN()).toLdapDNString();
if (subjnam.equalsIgnoreCase(subjName)) {
hasAnotherCert = true;
@@ -275,45 +274,45 @@ public class LdapCertSubjPublisher implements ILdapPublisher {
} catch (CertificateEncodingException e) {
// ignore this certificate.
CMS.debug(
- "LdapCertSubjPublisher: unpublish: an invalid cert in dn entry encountered");
+ "LdapCertSubjPublisher: unpublish: an invalid cert in dn entry encountered");
} catch (CertificateException e) {
// ignore this certificate.
CMS.debug(
- "LdapCertSubjPublisher: unpublish: an invalid cert in dn entry encountered");
+ "LdapCertSubjPublisher: unpublish: an invalid cert in dn entry encountered");
}
}
}
// check if doesn't have subject name already.
if (subjnames != null) {
- hasSubjname =
+ hasSubjname =
LdapUserCertPublisher.StringValueExists(subjnames, subjName);
}
// if doesn't have both, done.
if (!hasCert && !hasSubjname) {
- log(ILogger.LL_INFO,
- "unpublish: " + subjName + " already has not cert & subjname");
+ log(ILogger.LL_INFO,
+ "unpublish: " + subjName + " already has not cert & subjname");
return;
}
- // delete cert if there.
+ // delete cert if there.
LDAPModificationSet modSet = new LDAPModificationSet();
if (hasCert) {
- log(ILogger.LL_INFO,
- "unpublish: deleting cert " + subjName + " from " + dn);
+ log(ILogger.LL_INFO,
+ "unpublish: deleting cert " + subjName + " from " + dn);
modSet.add(LDAPModification.DELETE,
- new LDAPAttribute(mCertAttr, certEnc));
+ new LDAPAttribute(mCertAttr, certEnc));
}
// delete subject name if no other cert has the same name.
if (hasSubjname && !hasAnotherCert) {
- log(ILogger.LL_INFO,
- "unpublish: deleting subject name " + subjName + " from " + dn);
+ log(ILogger.LL_INFO,
+ "unpublish: deleting subject name " + subjName + " from " + dn);
modSet.add(LDAPModification.DELETE,
- new LDAPAttribute(mSubjNameAttr, subjName));
+ new LDAPAttribute(mSubjNameAttr, subjName));
}
- conn.modify(dn, modSet);
+ conn.modify(dn, modSet);
} catch (CertificateEncodingException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_UNPUBLISH_ERROR", e.toString()));
throw new ELdapException(CMS.getUserMessage("CMS_LDAP_GET_DER_ENCODED_CERT_FAILED", e.toString()));
@@ -325,7 +324,7 @@ public class LdapCertSubjPublisher implements ILdapPublisher {
// need to intercept this because message from LDAP is
// "DSA is unavailable" which confuses with DSA PKI.
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
+ CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
throw new ELdapServerDownException(CMS.getUserMessage("CMS_LDAP_SERVER_UNAVAILABLE", conn.getHost(), "" + conn.getPort()));
} else {
log(ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_UNPUBLISH_ERROR", e.toString()));
@@ -337,7 +336,7 @@ public class LdapCertSubjPublisher implements ILdapPublisher {
private void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_LDAP, level,
- "LdapCertSubjPublisher: " + msg);
+ "LdapCertSubjPublisher: " + msg);
}
}
diff --git a/pki/base/common/src/com/netscape/cms/publish/publishers/LdapCertificatePairPublisher.java b/pki/base/common/src/com/netscape/cms/publish/publishers/LdapCertificatePairPublisher.java
index e4a7e0b7..60c07570 100644
--- a/pki/base/common/src/com/netscape/cms/publish/publishers/LdapCertificatePairPublisher.java
+++ b/pki/base/common/src/com/netscape/cms/publish/publishers/LdapCertificatePairPublisher.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.publish.publishers;
-
import java.util.Locale;
import java.util.Vector;
@@ -39,15 +38,14 @@ import com.netscape.certsrv.ldap.ELdapServerDownException;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.publish.ILdapPublisher;
-
-/**
- * module for publishing a cross certificate pair to ldap
- * crossCertificatePair attribute
- *
+/**
+ * module for publishing a cross certificate pair to ldap crossCertificatePair
+ * attribute
+ *
* @version $Revision$, $Date$
*/
-public class LdapCertificatePairPublisher
- implements ILdapPublisher, IExtendedPluginInfo {
+public class LdapCertificatePairPublisher
+ implements ILdapPublisher, IExtendedPluginInfo {
public static final String LDAP_CROSS_CERT_PAIR_ATTR = "crossCertificatePair;binary";
public static final String LDAP_CA_OBJECTCLASS = "pkiCA";
public static final String LDAP_ARL_ATTR = "authorityRevocationList;binary";
@@ -73,13 +71,13 @@ public class LdapCertificatePairPublisher
String s[] = {
"crossCertPairAttr;string;Name of Ldap attribute in which to store cross certificates",
"caObjectClass;string;The name of the objectclasses which should be " +
- "added to this entry, if they do not already exist. This can be " +
- "'certificationAuthority' (if using RFC 2256) or 'pkiCA' (if using RFC 4523)",
+ "added to this entry, if they do not already exist. This can be " +
+ "'certificationAuthority' (if using RFC 2256) or 'pkiCA' (if using RFC 4523)",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-ldappublish-publisher-crosscertpairpublisher",
+ ";configuration-ldappublish-publisher-crosscertpairpublisher",
IExtendedPluginInfo.HELP_TEXT +
- ";This plugin knows how to publish the CA cert to " +
- "'certificateAuthority' and 'pkiCA' -type entries"
+ ";This plugin knows how to publish the CA cert to " +
+ "'certificateAuthority' and 'pkiCA' -type entries"
};
return s;
@@ -118,12 +116,12 @@ public class LdapCertificatePairPublisher
}
public void init(IConfigStore config)
- throws EBaseException {
- if (mInited)
+ throws EBaseException {
+ if (mInited)
return;
mConfig = config;
mCrossCertPairAttr = mConfig.getString("crossCertPairAttr", LDAP_CROSS_CERT_PAIR_ATTR);
- mCaObjectclass = mConfig.getString("caObjectClass",
+ mCaObjectclass = mConfig.getString("caObjectClass",
LDAP_CA_OBJECTCLASS);
mObjAdded = mConfig.getString("caObjectClassAdded", "");
mObjDeleted = mConfig.getString("caObjectClassDeleted", "");
@@ -153,27 +151,27 @@ public class LdapCertificatePairPublisher
}
/**
- * publish a certificatePair
- * -should not be called from listeners.
+ * publish a certificatePair -should not be called from listeners.
+ *
* @param conn the LDAP connection
* @param dn dn of the entry to publish the XcertificatePair
- * @param pair the Xcertificate bytes object.
+ * @param pair the Xcertificate bytes object.
*/
public synchronized void publish(LDAPConnection conn, String dn, Object pair)
- throws ELdapException {
+ throws ELdapException {
publish(conn, dn, (byte[]) pair);
}
/**
- * publish a certificatePair
- * -should not be called from listeners.
+ * publish a certificatePair -should not be called from listeners.
+ *
* @param conn the LDAP connection
* @param dn dn of the entry to publish the XcertificatePair
* @param pair the cross cert bytes
*/
public synchronized void publish(LDAPConnection conn, String dn,
- byte[] pair)
- throws ELdapException {
+ byte[] pair)
+ throws ELdapException {
if (conn == null) {
log(ILogger.LL_INFO, "LdapCertificatePairPublisher: no LDAP connection");
@@ -189,17 +187,17 @@ public class LdapCertificatePairPublisher
try {
// search for attributes to determine if they exist
LDAPSearchResults res =
- conn.search(dn, LDAPv2.SCOPE_BASE, "(objectclass=*)",
- new String[] { LDAP_CACERT_ATTR, LDAP_CRL_ATTR, LDAP_ARL_ATTR }, true);
+ conn.search(dn, LDAPv2.SCOPE_BASE, "(objectclass=*)",
+ new String[] { LDAP_CACERT_ATTR, LDAP_CRL_ATTR, LDAP_ARL_ATTR }, true);
LDAPEntry entry = res.next();
LDAPAttribute certs = entry.getAttribute(LDAP_CACERT_ATTR);
LDAPAttribute arls = entry.getAttribute(LDAP_ARL_ATTR);
LDAPAttribute crls = entry.getAttribute(LDAP_CRL_ATTR);
// search for objectclass and crosscertpair attributes and values
- LDAPSearchResults res1 =
- conn.search(dn, LDAPv2.SCOPE_BASE, "(objectclass=*)",
- new String[] { "objectclass", mCrossCertPairAttr }, false);
+ LDAPSearchResults res1 =
+ conn.search(dn, LDAPv2.SCOPE_BASE, "(objectclass=*)",
+ new String[] { "objectclass", mCrossCertPairAttr }, false);
LDAPEntry entry1 = res1.next();
LDAPAttribute ocs = entry1.getAttribute("objectclass");
LDAPAttribute certPairs = entry1.getAttribute("crosscertificatepair;binary");
@@ -207,53 +205,53 @@ public class LdapCertificatePairPublisher
LDAPModificationSet modSet = new LDAPModificationSet();
boolean hasCert = LdapUserCertPublisher.ByteValueExists(certPairs, pair);
- if (LdapUserCertPublisher.ByteValueExists(certPairs, pair)) {
+ if (LdapUserCertPublisher.ByteValueExists(certPairs, pair)) {
CMS.debug("LdapCertificatePairPublisher: cross cert pair bytes exist in publishing directory, do not publish again.");
return;
}
if (hasCert) {
log(ILogger.LL_INFO, "publish: CA " + dn + " already has cross cert pair bytes");
} else {
- modSet.add(LDAPModification.ADD,
- new LDAPAttribute(mCrossCertPairAttr, pair));
+ modSet.add(LDAPModification.ADD,
+ new LDAPAttribute(mCrossCertPairAttr, pair));
log(ILogger.LL_INFO, "cross cert pair published with dn=" + dn);
}
String[] oclist = mCaObjectclass.split(",");
boolean attrsAdded = false;
- for (int i=0; i < oclist.length; i++) {
+ for (int i = 0; i < oclist.length; i++) {
String oc = oclist[i].trim();
boolean hasoc = LdapUserCertPublisher.StringValueExists(ocs, oc);
if (!hasoc) {
log(ILogger.LL_INFO, "adding CA objectclass " + oc + " to " + dn);
modSet.add(LDAPModification.ADD,
- new LDAPAttribute("objectclass", oc));
+ new LDAPAttribute("objectclass", oc));
if ((!attrsAdded) && oc.equalsIgnoreCase("certificationAuthority")) {
// add MUST attributes
- if (arls == null)
+ if (arls == null)
modSet.add(LDAPModification.ADD,
- new LDAPAttribute(LDAP_ARL_ATTR, ""));
+ new LDAPAttribute(LDAP_ARL_ATTR, ""));
if (crls == null)
modSet.add(LDAPModification.ADD,
- new LDAPAttribute(LDAP_CRL_ATTR, ""));
+ new LDAPAttribute(LDAP_CRL_ATTR, ""));
if (certs == null)
- modSet.add(LDAPModification.ADD,
- new LDAPAttribute(LDAP_CACERT_ATTR, ""));
+ modSet.add(LDAPModification.ADD,
+ new LDAPAttribute(LDAP_CACERT_ATTR, ""));
attrsAdded = true;
}
}
- }
+ }
// delete objectclasses that have been deleted from config
String[] delList = mObjDeleted.split(",");
if (delList.length > 0) {
- for (int i=0; i< delList.length; i++) {
+ for (int i = 0; i < delList.length; i++) {
String deloc = delList[i].trim();
boolean hasoc = LdapUserCertPublisher.StringValueExists(ocs, deloc);
boolean match = false;
- for (int j=0; j< oclist.length; j++) {
+ for (int j = 0; j < oclist.length; j++) {
if ((oclist[j].trim()).equals(deloc)) {
match = true;
break;
@@ -280,14 +278,15 @@ public class LdapCertificatePairPublisher
}
}
- if (modSet.size() > 0) conn.modify(dn, modSet);
+ if (modSet.size() > 0)
+ conn.modify(dn, modSet);
CMS.debug("LdapCertificatePairPublisher: in publish() just published");
} catch (LDAPException e) {
if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE) {
// need to intercept this because message from LDAP is
// "DSA is unavailable" which confuses with DSA PKI.
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
+ CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
throw new ELdapServerDownException(CMS.getUserMessage("CMS_LDAP_SERVER_UNAVAILABLE", conn.getHost(), "" + conn.getPort()));
} else {
log(ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_PUBLISHER_EXCEPTION", "", e.toString()));
@@ -301,7 +300,7 @@ public class LdapCertificatePairPublisher
* unsupported
*/
public void unpublish(LDAPConnection conn, String dn, Object certObj)
- throws ELdapException {
+ throws ELdapException {
CMS.debug("LdapCertificatePairPublisher: unpublish() is unsupported in this revision");
}
@@ -310,7 +309,7 @@ public class LdapCertificatePairPublisher
*/
private void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_LDAP, level,
- "LdapCertificatePairPublisher: " + msg);
+ "LdapCertificatePairPublisher: " + msg);
}
}
diff --git a/pki/base/common/src/com/netscape/cms/publish/publishers/LdapCrlPublisher.java b/pki/base/common/src/com/netscape/cms/publish/publishers/LdapCrlPublisher.java
index 22dc1294..a87791d3 100644
--- a/pki/base/common/src/com/netscape/cms/publish/publishers/LdapCrlPublisher.java
+++ b/pki/base/common/src/com/netscape/cms/publish/publishers/LdapCrlPublisher.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.publish.publishers;
-
import java.security.cert.CRLException;
import java.security.cert.X509CRL;
import java.util.Locale;
@@ -42,10 +41,9 @@ import com.netscape.certsrv.ldap.ELdapServerDownException;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.publish.ILdapPublisher;
-
/**
- * For publishing master or global CRL.
- * Publishes (replaces) the CRL in the CA's LDAP entry.
+ * For publishing master or global CRL. Publishes (replaces) the CRL in the CA's
+ * LDAP entry.
*
* @version $Revision$, $Date$
*/
@@ -82,14 +80,14 @@ public class LdapCrlPublisher implements ILdapPublisher, IExtendedPluginInfo {
String[] params = {
"crlAttr;string;Name of Ldap attribute in which to store the CRL",
"crlObjectClass;string;The name of the objectclasses which should be " +
- "added to this entry, if they do not already exist. This can be a comma-" +
- "separated list such as 'certificationAuthority,certificationAuthority-V2' " +
- "(if using RFC 2256) or 'pkiCA, deltaCRL' (if using RFC 4523)",
+ "added to this entry, if they do not already exist. This can be a comma-" +
+ "separated list such as 'certificationAuthority,certificationAuthority-V2' " +
+ "(if using RFC 2256) or 'pkiCA, deltaCRL' (if using RFC 4523)",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-ldappublish-publisher-crlpublisher",
+ ";configuration-ldappublish-publisher-crlpublisher",
IExtendedPluginInfo.HELP_TEXT +
- ";This plugin knows how to publish CRL's to " +
- "'certificateAuthority' and 'pkiCA' -type entries"
+ ";This plugin knows how to publish CRL's to " +
+ "'certificateAuthority' and 'pkiCA' -type entries"
};
return params;
@@ -115,14 +113,14 @@ public class LdapCrlPublisher implements ILdapPublisher, IExtendedPluginInfo {
return mConfig;
}
- public void init(IConfigStore config)
- throws EBaseException {
+ public void init(IConfigStore config)
+ throws EBaseException {
if (mInited)
return;
mConfig = config;
mCrlAttr = mConfig.getString("crlAttr", LDAP_CRL_ATTR);
mCrlObjectClass = mConfig.getString("crlObjectClass",
- LDAP_CRL_OBJECTCLASS);
+ LDAP_CRL_OBJECTCLASS);
mObjAdded = mConfig.getString("crlObjectClassAdded", "");
mObjDeleted = mConfig.getString("crlObjectClassDeleted", "");
@@ -142,11 +140,11 @@ public class LdapCrlPublisher implements ILdapPublisher, IExtendedPluginInfo {
}
/**
- * Replaces the CRL in the certificateRevocationList attribute.
- * CRL's are published as a DER encoded blob.
+ * Replaces the CRL in the certificateRevocationList attribute. CRL's are
+ * published as a DER encoded blob.
*/
public void publish(LDAPConnection conn, String dn, Object crlObj)
- throws ELdapException {
+ throws ELdapException {
if (conn == null) {
log(ILogger.LL_INFO, "publish CRL: no LDAP connection");
return;
@@ -162,28 +160,28 @@ public class LdapCrlPublisher implements ILdapPublisher, IExtendedPluginInfo {
// see if we should create local connection
LDAPConnection altConn = null;
try {
- String host = mConfig.getString("host", null);
- String port = mConfig.getString("port", null);
- if (host != null && port != null) {
- int portVal = Integer.parseInt(port);
- int version = Integer.parseInt(mConfig.getString("version", "2"));
- String cert_nick = mConfig.getString("clientCertNickname", null);
- LDAPSSLSocketFactoryExt sslSocket = null;
- if (cert_nick != null) {
- sslSocket = CMS.getLdapJssSSLSocketFactory(cert_nick);
+ String host = mConfig.getString("host", null);
+ String port = mConfig.getString("port", null);
+ if (host != null && port != null) {
+ int portVal = Integer.parseInt(port);
+ int version = Integer.parseInt(mConfig.getString("version", "2"));
+ String cert_nick = mConfig.getString("clientCertNickname", null);
+ LDAPSSLSocketFactoryExt sslSocket = null;
+ if (cert_nick != null) {
+ sslSocket = CMS.getLdapJssSSLSocketFactory(cert_nick);
+ }
+ String mgr_dn = mConfig.getString("bindDN", null);
+ String mgr_pwd = mConfig.getString("bindPWD", null);
+
+ altConn = CMS.getBoundConnection(host, portVal,
+ version,
+ sslSocket, mgr_dn, mgr_pwd);
+ conn = altConn;
}
- String mgr_dn = mConfig.getString("bindDN", null);
- String mgr_pwd = mConfig.getString("bindPWD", null);
-
- altConn = CMS.getBoundConnection(host, portVal,
- version,
- sslSocket, mgr_dn, mgr_pwd);
- conn = altConn;
- }
} catch (LDAPException e) {
- CMS.debug("Failed to create alt connection " + e);
+ CMS.debug("Failed to create alt connection " + e);
} catch (EBaseException e) {
- CMS.debug("Failed to create alt connection " + e);
+ CMS.debug("Failed to create alt connection " + e);
}
try {
@@ -194,10 +192,10 @@ public class LdapCrlPublisher implements ILdapPublisher, IExtendedPluginInfo {
LDAPSearchResults res = null;
if (mCrlAttr.equals(LDAP_CRL_ATTR)) {
res = conn.search(dn, LDAPv2.SCOPE_BASE, "(objectclass=*)",
- new String[] { LDAP_CACERT_ATTR, LDAP_ARL_ATTR }, true);
+ new String[] { LDAP_CACERT_ATTR, LDAP_ARL_ATTR }, true);
} else {
res = conn.search(dn, LDAPv2.SCOPE_BASE, "(objectclass=*)",
- new String[] { LDAP_CRL_ATTR, LDAP_CACERT_ATTR, LDAP_ARL_ATTR }, true);
+ new String[] { LDAP_CRL_ATTR, LDAP_CACERT_ATTR, LDAP_ARL_ATTR }, true);
}
LDAPEntry entry = res.next();
@@ -216,26 +214,26 @@ public class LdapCrlPublisher implements ILdapPublisher, IExtendedPluginInfo {
String[] oclist = mCrlObjectClass.split(",");
boolean attrsAdded = false;
- for (int i=0; i < oclist.length; i++) {
+ for (int i = 0; i < oclist.length; i++) {
String oc = oclist[i].trim();
boolean hasoc = LdapUserCertPublisher.StringValueExists(ocs, oc);
if (!hasoc) {
log(ILogger.LL_INFO, "adding CRL objectclass " + oc + " to " + dn);
modSet.add(LDAPModification.ADD,
- new LDAPAttribute("objectclass", oc));
+ new LDAPAttribute("objectclass", oc));
if ((!attrsAdded) && oc.equalsIgnoreCase("certificationAuthority")) {
// add MUST attributes
if (arls == null)
modSet.add(LDAPModification.ADD,
- new LDAPAttribute(LDAP_ARL_ATTR, ""));
+ new LDAPAttribute(LDAP_ARL_ATTR, ""));
if (certs == null)
modSet.add(LDAPModification.ADD,
- new LDAPAttribute(LDAP_CACERT_ATTR, ""));
+ new LDAPAttribute(LDAP_CACERT_ATTR, ""));
- if ((crls == null) && (!mCrlAttr.equals(LDAP_CRL_ATTR)))
+ if ((crls == null) && (!mCrlAttr.equals(LDAP_CRL_ATTR)))
modSet.add(LDAPModification.ADD,
- new LDAPAttribute(LDAP_CRL_ATTR, ""));
+ new LDAPAttribute(LDAP_CRL_ATTR, ""));
attrsAdded = true;
}
}
@@ -246,11 +244,11 @@ public class LdapCrlPublisher implements ILdapPublisher, IExtendedPluginInfo {
// delete objectclasses that have been deleted from config
String[] delList = mObjDeleted.split(",");
if (delList.length > 0) {
- for (int i=0; i< delList.length; i++) {
+ for (int i = 0; i < delList.length; i++) {
String deloc = delList[i].trim();
boolean hasoc = LdapUserCertPublisher.StringValueExists(ocs, deloc);
boolean match = false;
- for (int j=0; j< oclist.length; j++) {
+ for (int j = 0; j < oclist.length; j++) {
if ((oclist[j].trim()).equals(deloc)) {
match = true;
break;
@@ -275,7 +273,7 @@ public class LdapCrlPublisher implements ILdapPublisher, IExtendedPluginInfo {
} catch (Exception e) {
log(ILogger.LL_INFO, "Failure in updating mObjAdded and mObjDeleted");
}
- }
+ }
conn.modify(dn, modSet);
} catch (CRLException e) {
@@ -286,31 +284,31 @@ public class LdapCrlPublisher implements ILdapPublisher, IExtendedPluginInfo {
// need to intercept this because message from LDAP is
// "DSA is unavailable" which confuses with DSA PKI.
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
+ CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
throw new ELdapServerDownException(CMS.getUserMessage("CMS_LDAP_SERVER_UNAVAILABLE", conn.getHost(), "" + conn.getPort()));
} else {
log(ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_PUBLISH_ERROR", e.toString()));
throw new ELdapException(CMS.getUserMessage("CMS_LDAP_PUBLISH_CRL_ERROR", e.toString()));
}
} finally {
- if (altConn != null) {
- try {
- altConn.disconnect();
- } catch (LDAPException e) {
- // safely ignored
- }
- }
+ if (altConn != null) {
+ try {
+ altConn.disconnect();
+ } catch (LDAPException e) {
+ // safely ignored
+ }
+ }
}
}
/**
- * There shouldn't be a need to call this.
- * CRLs are always replaced but this is implemented anyway in case
- * there is ever a reason to remove a global CRL.
+ * There shouldn't be a need to call this. CRLs are always replaced but this
+ * is implemented anyway in case there is ever a reason to remove a global
+ * CRL.
*/
public void unpublish(LDAPConnection conn, String dn, Object crlObj)
- throws ELdapException {
+ throws ELdapException {
try {
byte[] crlEnc = ((X509CRL) crlObj).getEncoded();
@@ -320,7 +318,6 @@ public class LdapCrlPublisher implements ILdapPublisher, IExtendedPluginInfo {
} catch (EBaseException e) {
}
-
LDAPSearchResults res = conn.search(dn, LDAPv2.SCOPE_BASE,
"(objectclass=*)", new String[] { mCrlAttr, "objectclass" }, false);
LDAPEntry e = res.next();
@@ -330,21 +327,21 @@ public class LdapCrlPublisher implements ILdapPublisher, IExtendedPluginInfo {
LDAPModificationSet modSet = new LDAPModificationSet();
boolean hasOC = false;
- boolean hasCRL =
- LdapUserCertPublisher.ByteValueExists(crls, crlEnc);
+ boolean hasCRL =
+ LdapUserCertPublisher.ByteValueExists(crls, crlEnc);
if (hasCRL) {
- modSet.add(LDAPModification.DELETE,
- new LDAPAttribute(mCrlAttr, crlEnc));
+ modSet.add(LDAPModification.DELETE,
+ new LDAPAttribute(mCrlAttr, crlEnc));
}
-
+
String[] oclist = mCrlObjectClass.split(",");
- for (int i=0; i < oclist.length; i++) {
+ for (int i = 0; i < oclist.length; i++) {
String oc = oclist[i].trim();
if (LdapUserCertPublisher.StringValueExists(ocs, oc)) {
log(ILogger.LL_INFO, "unpublish: deleting CRL object class " + oc + " from " + dn);
- modSet.add(LDAPModification.DELETE,
- new LDAPAttribute("objectClass", oc));
+ modSet.add(LDAPModification.DELETE,
+ new LDAPAttribute("objectClass", oc));
hasOC = true;
}
}
@@ -353,7 +350,7 @@ public class LdapCrlPublisher implements ILdapPublisher, IExtendedPluginInfo {
conn.modify(dn, modSet);
} else {
log(ILogger.LL_INFO,
- "unpublish: " + dn + " already has not CRL");
+ "unpublish: " + dn + " already has not CRL");
}
} catch (CRLException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_UNPUBLISH_ERROR", e.toString()));
@@ -363,7 +360,7 @@ public class LdapCrlPublisher implements ILdapPublisher, IExtendedPluginInfo {
// need to intercept this because message from LDAP is
// "DSA is unavailable" which confuses with DSA PKI.
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
+ CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
throw new ELdapServerDownException(CMS.getUserMessage("CMS_LDAP_SERVER_UNAVAILABLE", conn.getHost(), "" + conn.getPort()));
} else {
log(ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_UNPUBLISH_ERROR", e.toString()));
@@ -375,6 +372,6 @@ public class LdapCrlPublisher implements ILdapPublisher, IExtendedPluginInfo {
private void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_LDAP, level,
- "LdapCrlPublisher: " + msg);
+ "LdapCrlPublisher: " + msg);
}
}
diff --git a/pki/base/common/src/com/netscape/cms/publish/publishers/LdapEncryptCertPublisher.java b/pki/base/common/src/com/netscape/cms/publish/publishers/LdapEncryptCertPublisher.java
index f4dcbb3c..d9e60df4 100644
--- a/pki/base/common/src/com/netscape/cms/publish/publishers/LdapEncryptCertPublisher.java
+++ b/pki/base/common/src/com/netscape/cms/publish/publishers/LdapEncryptCertPublisher.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.publish.publishers;
-
import java.io.IOException;
import java.math.BigInteger;
import java.security.cert.CertificateEncodingException;
@@ -51,10 +50,9 @@ import com.netscape.certsrv.ldap.ELdapServerDownException;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.publish.ILdapPublisher;
-
-/**
- * Interface for mapping a X509 certificate to a LDAP entry
- *
+/**
+ * Interface for mapping a X509 certificate to a LDAP entry
+ *
* @version $Revision$, $Date$
*/
public class LdapEncryptCertPublisher implements ILdapPublisher, IExtendedPluginInfo {
@@ -82,9 +80,9 @@ public class LdapEncryptCertPublisher implements ILdapPublisher, IExtendedPlugin
String[] params = {
"certAttr;string;LDAP attribute in which to store the certificate",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-ldappublish-publisher-usercertpublisher",
+ ";configuration-ldappublish-publisher-usercertpublisher",
IExtendedPluginInfo.HELP_TEXT +
- ";This plugin knows how to publish user certificates"
+ ";This plugin knows how to publish user certificates"
};
return params;
@@ -110,7 +108,7 @@ public class LdapEncryptCertPublisher implements ILdapPublisher, IExtendedPlugin
}
public void init(IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
if (mInited)
return;
mConfig = config;
@@ -124,16 +122,16 @@ public class LdapEncryptCertPublisher implements ILdapPublisher, IExtendedPlugin
}
/**
- * publish a user certificate
- * Adds the cert to the multi-valued certificate attribute as a
- * DER encoded binary blob. Does not check if cert already exists.
+ * publish a user certificate Adds the cert to the multi-valued certificate
+ * attribute as a DER encoded binary blob. Does not check if cert already
+ * exists.
*
* @param conn the LDAP connection
* @param dn dn of the entry to publish the certificate
- * @param certObj the certificate object.
+ * @param certObj the certificate object.
*/
public void publish(LDAPConnection conn, String dn, Object certObj)
- throws ELdapException {
+ throws ELdapException {
if (conn == null)
return;
@@ -147,7 +145,7 @@ public class LdapEncryptCertPublisher implements ILdapPublisher, IExtendedPlugin
byte[] certEnc = cert.getEncoded();
// check if cert already exists.
- LDAPSearchResults res = conn.search(dn, LDAPv2.SCOPE_BASE,
+ LDAPSearchResults res = conn.search(dn, LDAPv2.SCOPE_BASE,
"(objectclass=*)", new String[] { mCertAttr }, false);
LDAPEntry entry = res.next();
LDAPAttribute attr = getModificationAttribute(entry.getAttribute(mCertAttr), certEnc);
@@ -157,10 +155,10 @@ public class LdapEncryptCertPublisher implements ILdapPublisher, IExtendedPlugin
return;
}
- // publish
+ // publish
LDAPModification mod = new LDAPModification(LDAPModification.REPLACE, attr);
- conn.modify(dn, mod);
+ conn.modify(dn, mod);
} catch (CertificateEncodingException e) {
CMS.debug("LdapEncryptCertPublisher: error in publish: " + e.toString());
throw new ELdapException(CMS.getUserMessage("CMS_LDAP_GET_DER_ENCODED_CERT_FAILED", e.toString()));
@@ -169,7 +167,7 @@ public class LdapEncryptCertPublisher implements ILdapPublisher, IExtendedPlugin
// need to intercept this because message from LDAP is
// "DSA is unavailable" which confuses with DSA PKI.
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
+ CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
throw new ELdapServerDownException(CMS.getUserMessage("CMS_LDAP_SERVER_UNAVAILABLE", conn.getHost(), "" + conn.getPort()));
} else {
log(ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_PUBLISH_ERROR", e.toString()));
@@ -180,12 +178,11 @@ public class LdapEncryptCertPublisher implements ILdapPublisher, IExtendedPlugin
}
/**
- * unpublish a user certificate
- * deletes the certificate from the list of certificates.
- * does not check if certificate is already there.
+ * unpublish a user certificate deletes the certificate from the list of
+ * certificates. does not check if certificate is already there.
*/
public void unpublish(LDAPConnection conn, String dn, Object certObj)
- throws ELdapException {
+ throws ELdapException {
if (!(certObj instanceof X509Certificate))
throw new IllegalArgumentException("Illegal arg to publish");
@@ -195,7 +192,7 @@ public class LdapEncryptCertPublisher implements ILdapPublisher, IExtendedPlugin
byte[] certEnc = cert.getEncoded();
// check if cert already deleted.
- LDAPSearchResults res = conn.search(dn, LDAPv2.SCOPE_BASE,
+ LDAPSearchResults res = conn.search(dn, LDAPv2.SCOPE_BASE,
"(objectclass=*)", new String[] { mCertAttr }, false);
LDAPEntry entry = res.next();
@@ -207,7 +204,7 @@ public class LdapEncryptCertPublisher implements ILdapPublisher, IExtendedPlugin
LDAPModification mod = new LDAPModification(LDAPModification.DELETE,
new LDAPAttribute(mCertAttr, certEnc));
- conn.modify(dn, mod);
+ conn.modify(dn, mod);
} catch (CertificateEncodingException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_UNPUBLISH_ERROR", e.toString()));
throw new ELdapException(CMS.getUserMessage("CMS_LDAP_GET_DER_ENCODED_CERT_FAILED", e.toString()));
@@ -216,7 +213,7 @@ public class LdapEncryptCertPublisher implements ILdapPublisher, IExtendedPlugin
// need to intercept this because message from LDAP is
// "DSA is unavailable" which confuses with DSA PKI.
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
+ CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
throw new ELdapServerDownException(CMS.getUserMessage("CMS_LDAP_SERVER_UNAVAILABLE", conn.getHost(), "" + conn.getPort()));
} else {
log(ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_UNPUBLISH_ERROR", e.toString()));
@@ -228,11 +225,11 @@ public class LdapEncryptCertPublisher implements ILdapPublisher, IExtendedPlugin
private void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_LDAP, level,
- "LdapUserCertPublisher: " + msg);
+ "LdapUserCertPublisher: " + msg);
}
public LDAPAttribute getModificationAttribute(
- LDAPAttribute attr, byte[] bval) {
+ LDAPAttribute attr, byte[] bval) {
LDAPAttribute at = new LDAPAttribute(attr.getName(), bval);
// determine if the given cert is a signing or an encryption
@@ -248,7 +245,7 @@ public class LdapEncryptCertPublisher implements ILdapPublisher, IExtendedPlugin
}
@SuppressWarnings("unchecked")
- Enumeration<byte[]> vals = attr.getByteValues();
+ Enumeration<byte[]> vals = attr.getByteValues();
byte[] val = null;
while (vals.hasMoreElements()) {
@@ -258,12 +255,12 @@ public class LdapEncryptCertPublisher implements ILdapPublisher, IExtendedPlugin
log(ILogger.LL_INFO, "Checking " + cert);
if (CMS.isEncryptionCert(thisCert) &&
- CMS.isEncryptionCert(cert)) {
+ CMS.isEncryptionCert(cert)) {
// skip
log(ILogger.LL_INFO, "SKIP ENCRYPTION " + cert);
revokeCert(cert);
} else if (CMS.isSigningCert(thisCert) &&
- CMS.isSigningCert(cert)) {
+ CMS.isSigningCert(cert)) {
// skip
log(ILogger.LL_INFO, "SKIP SIGNING " + cert);
revokeCert(cert);
@@ -278,8 +275,8 @@ public class LdapEncryptCertPublisher implements ILdapPublisher, IExtendedPlugin
}
private RevokedCertImpl formCRLEntry(
- BigInteger serialNo, RevocationReason reason)
- throws EBaseException {
+ BigInteger serialNo, RevocationReason reason)
+ throws EBaseException {
CRLReasonExtension reasonExt = new CRLReasonExtension(reason);
CRLExtensions crlentryexts = new CRLExtensions();
@@ -291,13 +288,13 @@ public class LdapEncryptCertPublisher implements ILdapPublisher, IExtendedPlugin
throw new ELdapException(CMS.getUserMessage("CMS_LDAP_INTERNAL_ERROR", e.toString()));
}
RevokedCertImpl crlentry =
- new RevokedCertImpl(serialNo, new Date(), crlentryexts);
+ new RevokedCertImpl(serialNo, new Date(), crlentryexts);
return crlentry;
}
private void revokeCert(X509CertImpl cert)
- throws EBaseException {
+ throws EBaseException {
try {
if (mConfig.getBoolean(PROP_REVOKE_CERT, true) == false) {
return;
@@ -308,7 +305,7 @@ public class LdapEncryptCertPublisher implements ILdapPublisher, IExtendedPlugin
BigInteger serialNum = cert.getSerialNumber();
// need to revoke certificate also
ICertificateAuthority ca = (ICertificateAuthority)
- CMS.getSubsystem("ca");
+ CMS.getSubsystem("ca");
ICAService service = (ICAService) ca.getCAService();
RevokedCertImpl crlEntry = formCRLEntry(
serialNum, RevocationReason.KEY_COMPROMISE);
@@ -324,7 +321,7 @@ public class LdapEncryptCertPublisher implements ILdapPublisher, IExtendedPlugin
return false;
}
@SuppressWarnings("unchecked")
- Enumeration<byte[]> vals = attr.getByteValues();
+ Enumeration<byte[]> vals = attr.getByteValues();
byte[] val = null;
while (vals.hasMoreElements()) {
@@ -344,7 +341,7 @@ public class LdapEncryptCertPublisher implements ILdapPublisher, IExtendedPlugin
return false;
}
@SuppressWarnings("unchecked")
- Enumeration<String> vals = attr.getStringValues();
+ Enumeration<String> vals = attr.getStringValues();
String val = null;
while (vals.hasMoreElements()) {
@@ -357,4 +354,3 @@ public class LdapEncryptCertPublisher implements ILdapPublisher, IExtendedPlugin
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/publish/publishers/LdapUserCertPublisher.java b/pki/base/common/src/com/netscape/cms/publish/publishers/LdapUserCertPublisher.java
index f612d005..f904c102 100644
--- a/pki/base/common/src/com/netscape/cms/publish/publishers/LdapUserCertPublisher.java
+++ b/pki/base/common/src/com/netscape/cms/publish/publishers/LdapUserCertPublisher.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.publish.publishers;
-
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
@@ -43,10 +42,9 @@ import com.netscape.certsrv.logging.AuditFormat;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.publish.ILdapPublisher;
-
-/**
- * Interface for mapping a X509 certificate to a LDAP entry
- *
+/**
+ * Interface for mapping a X509 certificate to a LDAP entry
+ *
* @version $Revision$, $Date$
*/
public class LdapUserCertPublisher implements ILdapPublisher, IExtendedPluginInfo {
@@ -72,9 +70,9 @@ public class LdapUserCertPublisher implements ILdapPublisher, IExtendedPluginInf
String[] params = {
"certAttr;string;LDAP attribute in which to store the certificate",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-ldappublish-publisher-usercertpublisher",
+ ";configuration-ldappublish-publisher-usercertpublisher",
IExtendedPluginInfo.HELP_TEXT +
- ";This plugin knows how to publish user certificates"
+ ";This plugin knows how to publish user certificates"
};
return params;
@@ -100,7 +98,7 @@ public class LdapUserCertPublisher implements ILdapPublisher, IExtendedPluginInf
}
public void init(IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
if (mInited)
return;
mConfig = config;
@@ -113,16 +111,16 @@ public class LdapUserCertPublisher implements ILdapPublisher, IExtendedPluginInf
}
/**
- * publish a user certificate
- * Adds the cert to the multi-valued certificate attribute as a
- * DER encoded binary blob. Does not check if cert already exists.
+ * publish a user certificate Adds the cert to the multi-valued certificate
+ * attribute as a DER encoded binary blob. Does not check if cert already
+ * exists.
*
* @param conn the LDAP connection
* @param dn dn of the entry to publish the certificate
- * @param certObj the certificate object.
+ * @param certObj the certificate object.
*/
public void publish(LDAPConnection conn, String dn, Object certObj)
- throws ELdapException {
+ throws ELdapException {
if (conn == null)
return;
@@ -130,28 +128,28 @@ public class LdapUserCertPublisher implements ILdapPublisher, IExtendedPluginInf
// see if we should create local connection
LDAPConnection altConn = null;
try {
- String host = mConfig.getString("host", null);
- String port = mConfig.getString("port", null);
- if (host != null && port != null) {
- int portVal = Integer.parseInt(port);
- int version = Integer.parseInt(mConfig.getString("version", "2"));
- String cert_nick = mConfig.getString("clientCertNickname", null);
- LDAPSSLSocketFactoryExt sslSocket = null;
- if (cert_nick != null) {
- sslSocket = CMS.getLdapJssSSLSocketFactory(cert_nick);
+ String host = mConfig.getString("host", null);
+ String port = mConfig.getString("port", null);
+ if (host != null && port != null) {
+ int portVal = Integer.parseInt(port);
+ int version = Integer.parseInt(mConfig.getString("version", "2"));
+ String cert_nick = mConfig.getString("clientCertNickname", null);
+ LDAPSSLSocketFactoryExt sslSocket = null;
+ if (cert_nick != null) {
+ sslSocket = CMS.getLdapJssSSLSocketFactory(cert_nick);
+ }
+ String mgr_dn = mConfig.getString("bindDN", null);
+ String mgr_pwd = mConfig.getString("bindPWD", null);
+
+ altConn = CMS.getBoundConnection(host, portVal,
+ version,
+ sslSocket, mgr_dn, mgr_pwd);
+ conn = altConn;
}
- String mgr_dn = mConfig.getString("bindDN", null);
- String mgr_pwd = mConfig.getString("bindPWD", null);
-
- altConn = CMS.getBoundConnection(host, portVal,
- version,
- sslSocket, mgr_dn, mgr_pwd);
- conn = altConn;
- }
} catch (LDAPException e) {
- CMS.debug("Failed to create alt connection " + e);
+ CMS.debug("Failed to create alt connection " + e);
} catch (EBaseException e) {
- CMS.debug("Failed to create alt connection " + e);
+ CMS.debug("Failed to create alt connection " + e);
}
if (!(certObj instanceof X509Certificate))
@@ -169,7 +167,7 @@ public class LdapUserCertPublisher implements ILdapPublisher, IExtendedPluginInf
byte[] certEnc = cert.getEncoded();
// check if cert already exists.
- LDAPSearchResults res = conn.search(dn, LDAPv2.SCOPE_BASE,
+ LDAPSearchResults res = conn.search(dn, LDAPv2.SCOPE_BASE,
"(objectclass=*)", new String[] { mCertAttr }, false);
LDAPEntry entry = res.next();
@@ -178,26 +176,26 @@ public class LdapUserCertPublisher implements ILdapPublisher, IExtendedPluginInf
return;
}
- // publish
+ // publish
LDAPModification mod = null;
if (deleteCert) {
- mod = new LDAPModification(LDAPModification.REPLACE,
- new LDAPAttribute(mCertAttr, certEnc));
+ mod = new LDAPModification(LDAPModification.REPLACE,
+ new LDAPAttribute(mCertAttr, certEnc));
} else {
- mod = new LDAPModification(LDAPModification.ADD,
- new LDAPAttribute(mCertAttr, certEnc));
+ mod = new LDAPModification(LDAPModification.ADD,
+ new LDAPAttribute(mCertAttr, certEnc));
}
- conn.modify(dn, mod);
+ conn.modify(dn, mod);
// log a successful message to the "transactions" log
- mLogger.log( ILogger.EV_AUDIT,
+ mLogger.log(ILogger.EV_AUDIT,
ILogger.S_LDAP,
ILogger.LL_INFO,
AuditFormat.LDAP_PUBLISHED_FORMAT,
new Object[] { "LdapUserCertPublisher",
cert.getSerialNumber().toString(16),
- cert.getSubjectDN() } );
+ cert.getSubjectDN() });
} catch (CertificateEncodingException e) {
CMS.debug("LdapUserCertPublisher: error in publish: " + e.toString());
throw new ELdapException(CMS.getUserMessage("CMS_LDAP_GET_DER_ENCODED_CERT_FAILED", e.toString()));
@@ -206,31 +204,30 @@ public class LdapUserCertPublisher implements ILdapPublisher, IExtendedPluginInf
// need to intercept this because message from LDAP is
// "DSA is unavailable" which confuses with DSA PKI.
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
+ CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
throw new ELdapServerDownException(CMS.getUserMessage("CMS_LDAP_SERVER_UNAVAILABLE", conn.getHost(), "" + conn.getPort()));
} else {
log(ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_PUBLISH_ERROR", e.toString()));
throw new ELdapException(CMS.getUserMessage("CMS_LDAP_PUBLISH_USERCERT_ERROR", e.toString()));
}
} finally {
- if (altConn != null) {
- try {
- altConn.disconnect();
- } catch (LDAPException e) {
- // safely ignored
- }
- }
+ if (altConn != null) {
+ try {
+ altConn.disconnect();
+ } catch (LDAPException e) {
+ // safely ignored
+ }
+ }
}
return;
}
/**
- * unpublish a user certificate
- * deletes the certificate from the list of certificates.
- * does not check if certificate is already there.
+ * unpublish a user certificate deletes the certificate from the list of
+ * certificates. does not check if certificate is already there.
*/
public void unpublish(LDAPConnection conn, String dn, Object certObj)
- throws ELdapException {
+ throws ELdapException {
boolean disableUnpublish = false;
try {
@@ -239,8 +236,8 @@ public class LdapUserCertPublisher implements ILdapPublisher, IExtendedPluginInf
}
if (disableUnpublish) {
- CMS.debug("UserCertPublisher: disable unpublish");
- return;
+ CMS.debug("UserCertPublisher: disable unpublish");
+ return;
}
if (!(certObj instanceof X509Certificate))
@@ -252,7 +249,7 @@ public class LdapUserCertPublisher implements ILdapPublisher, IExtendedPluginInf
byte[] certEnc = cert.getEncoded();
// check if cert already deleted.
- LDAPSearchResults res = conn.search(dn, LDAPv2.SCOPE_BASE,
+ LDAPSearchResults res = conn.search(dn, LDAPv2.SCOPE_BASE,
"(objectclass=*)", new String[] { mCertAttr }, false);
LDAPEntry entry = res.next();
@@ -264,7 +261,7 @@ public class LdapUserCertPublisher implements ILdapPublisher, IExtendedPluginInf
LDAPModification mod = new LDAPModification(LDAPModification.DELETE,
new LDAPAttribute(mCertAttr, certEnc));
- conn.modify(dn, mod);
+ conn.modify(dn, mod);
} catch (CertificateEncodingException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_UNPUBLISH_ERROR", e.toString()));
throw new ELdapException(CMS.getUserMessage("CMS_LDAP_GET_DER_ENCODED_CERT_FAILED", e.toString()));
@@ -273,7 +270,7 @@ public class LdapUserCertPublisher implements ILdapPublisher, IExtendedPluginInf
// need to intercept this because message from LDAP is
// "DSA is unavailable" which confuses with DSA PKI.
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
+ CMS.getLogMessage("PUBLISH_NO_LDAP_SERVER"));
throw new ELdapServerDownException(CMS.getUserMessage("CMS_LDAP_SERVER_UNAVAILABLE", conn.getHost(), "" + conn.getPort()));
} else {
log(ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_UNPUBLISH_ERROR"));
@@ -285,7 +282,7 @@ public class LdapUserCertPublisher implements ILdapPublisher, IExtendedPluginInf
private void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_LDAP, level,
- "LdapUserCertPublisher: " + msg);
+ "LdapUserCertPublisher: " + msg);
}
/**
diff --git a/pki/base/common/src/com/netscape/cms/publish/publishers/OCSPPublisher.java b/pki/base/common/src/com/netscape/cms/publish/publishers/OCSPPublisher.java
index ad37a666..feca23ff 100644
--- a/pki/base/common/src/com/netscape/cms/publish/publishers/OCSPPublisher.java
+++ b/pki/base/common/src/com/netscape/cms/publish/publishers/OCSPPublisher.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.publish.publishers;
-
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
@@ -42,11 +41,9 @@ import com.netscape.certsrv.publish.ILdapPublisher;
import com.netscape.cmsutil.http.HttpRequest;
import com.netscape.cmsutil.http.JssSSLSocketFactory;
-
-/**
- * This publisher writes certificate and CRL into
- * a directory.
- *
+/**
+ * This publisher writes certificate and CRL into a directory.
+ *
* @version $Revision$, $Date$
*/
public class OCSPPublisher implements ILdapPublisher, IExtendedPluginInfo {
@@ -86,9 +83,9 @@ public class OCSPPublisher implements ILdapPublisher, IExtendedPluginInfo {
PROP_NICK + ";string;Nickname of cert used for client authentication",
PROP_CLIENT_AUTH_ENABLE + ";boolean;Client Authentication enabled",
IExtendedPluginInfo.HELP_TOKEN +
- ";configuration-ldappublish-publisher-ocsppublisher",
+ ";configuration-ldappublish-publisher-ocsppublisher",
IExtendedPluginInfo.HELP_TEXT +
- ";Publishes CRLs to a Online Certificate Status Manager, an OCSP responder provided by CMS."
+ ";Publishes CRLs to a Online Certificate Status Manager, an OCSP responder provided by CMS."
};
return params;
@@ -146,11 +143,10 @@ public class OCSPPublisher implements ILdapPublisher, IExtendedPluginInfo {
nickname = config.getString("ca.subsystem.nickname", "");
String tokenname = config.getString("ca.subsystem.tokenname", "");
if (!tokenname.equals("internal") && !tokenname.equals("Internal Key Storage Token"))
- nickname = tokenname+":"+nickname;
+ nickname = tokenname + ":" + nickname;
} catch (Exception e) {
}
-
v.addElement(PROP_HOST + "=");
v.addElement(PROP_PORT + "=");
v.addElement(PROP_PATH + "=/ocsp/agent/ocsp/addCRL");
@@ -178,45 +174,42 @@ public class OCSPPublisher implements ILdapPublisher, IExtendedPluginInfo {
return mConfig;
}
- protected Socket Connect(String host, boolean secure, JssSSLSocketFactory factory)
- {
- Socket socket = null;
- StringTokenizer st = new StringTokenizer(host, " ");
- while (st.hasMoreTokens()) {
- String hp = st.nextToken(); // host:port
- StringTokenizer st1 = new StringTokenizer(hp, ":");
- String h = st1.nextToken();
- int p = Integer.parseInt(st1.nextToken());
- try {
- if (secure) {
- socket = factory.makeSocket(h, p);
- } else {
- socket = new Socket(h, p);
- }
- return socket;
- } catch (Exception e) {
- }
- try {
- Thread.sleep(5000); // 5 seconds delay
- } catch (Exception e) {
- }
- }
- return null;
+ protected Socket Connect(String host, boolean secure, JssSSLSocketFactory factory) {
+ Socket socket = null;
+ StringTokenizer st = new StringTokenizer(host, " ");
+ while (st.hasMoreTokens()) {
+ String hp = st.nextToken(); // host:port
+ StringTokenizer st1 = new StringTokenizer(hp, ":");
+ String h = st1.nextToken();
+ int p = Integer.parseInt(st1.nextToken());
+ try {
+ if (secure) {
+ socket = factory.makeSocket(h, p);
+ } else {
+ socket = new Socket(h, p);
+ }
+ return socket;
+ } catch (Exception e) {
+ }
+ try {
+ Thread.sleep(5000); // 5 seconds delay
+ } catch (Exception e) {
+ }
+ }
+ return null;
}
/**
* Publishs a object to the ldap directory.
*
- * @param conn a Ldap connection
- * (null if LDAP publishing is not enabled)
- * @param dn dn of the ldap entry to publish cert
- * (null if LDAP publishing is not enabled)
- * @param object object to publish
- * (java.security.cert.X509Certificate or,
- * java.security.cert.X509CRL)
+ * @param conn a Ldap connection (null if LDAP publishing is not enabled)
+ * @param dn dn of the ldap entry to publish cert (null if LDAP publishing
+ * is not enabled)
+ * @param object object to publish (java.security.cert.X509Certificate or,
+ * java.security.cert.X509CRL)
*/
public synchronized void publish(LDAPConnection conn, String dn, Object object)
- throws ELdapException {
+ throws ELdapException {
try {
if (!(object instanceof X509CRL))
return;
@@ -226,18 +219,18 @@ public class OCSPPublisher implements ILdapPublisher, IExtendedPluginInfo {
// open the connection and prepare it to POST
boolean secure = true;
-
+
String host = mHost;
int port = Integer.parseInt(mPort);
String path = mPath;
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- ILogger.LL_INFO, "OCSPPublisher: " +
- "Host='" + host + "' Port='" + port +
- "' URL='" + path + "'");
- CMS.debug("OCSPPublisher: " +
- "Host='" + host + "' Port='" + port +
- "' URL='" + path + "'");
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
+ ILogger.LL_INFO, "OCSPPublisher: " +
+ "Host='" + host + "' Port='" + port +
+ "' URL='" + path + "'");
+ CMS.debug("OCSPPublisher: " +
+ "Host='" + host + "' Port='" + port +
+ "' URL='" + path + "'");
StringBuffer query = new StringBuffer();
query.append("crl=");
@@ -256,23 +249,23 @@ public class OCSPPublisher implements ILdapPublisher, IExtendedPluginInfo {
}
if (mHost != null && mHost.indexOf(' ') != -1) {
- // support failover hosts configuration
- // host parameter can be
- // "directory.knowledge.com:1050 people.catalog.com 199.254.1.2"
- do {
- socket = Connect(mHost, secure, factory);
- } while (socket == null);
+ // support failover hosts configuration
+ // host parameter can be
+ // "directory.knowledge.com:1050 people.catalog.com 199.254.1.2"
+ do {
+ socket = Connect(mHost, secure, factory);
+ } while (socket == null);
} else {
- if (secure) {
- socket = factory.makeSocket(host, port);
- } else {
- socket = new Socket(host, port);
- }
+ if (secure) {
+ socket = factory.makeSocket(host, port);
+ } else {
+ socket = new Socket(host, port);
+ }
}
- if( socket == null ) {
- CMS.debug( "OCSPPublisher::publish() - socket is null!" );
- throw new ELdapException( "socket is null" );
+ if (socket == null) {
+ CMS.debug("OCSPPublisher::publish() - socket is null!");
+ throw new ELdapException("socket is null");
}
// use HttpRequest and POST
@@ -283,17 +276,17 @@ public class OCSPPublisher implements ILdapPublisher, IExtendedPluginInfo {
httpReq.setHeader("Connection", "Keep-Alive");
httpReq.setHeader("Content-Type",
- "application/x-www-form-urlencoded");
+ "application/x-www-form-urlencoded");
httpReq.setHeader("Content-Transfer-Encoding", "7bit");
- httpReq.setHeader("Content-Length",
- Integer.toString(query.length()));
+ httpReq.setHeader("Content-Length",
+ Integer.toString(query.length()));
httpReq.setContent(query.toString());
OutputStream os = socket.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(os, "UTF8");
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- ILogger.LL_INFO, "OCSPPublisher: start sending CRL");
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
+ ILogger.LL_INFO, "OCSPPublisher: start sending CRL");
long startTime = CMS.getCurrentDate().getTime();
CMS.debug("OCSPPublisher: start CRL sending startTime=" + startTime);
httpReq.write(outputStreamWriter);
@@ -301,8 +294,8 @@ public class OCSPPublisher implements ILdapPublisher, IExtendedPluginInfo {
CMS.debug("OCSPPublisher: done CRL sending endTime=" + endTime + " diff=" + (endTime - startTime));
// Read the response
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- ILogger.LL_INFO, "OCSPPublisher: start getting response");
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
+ ILogger.LL_INFO, "OCSPPublisher: start getting response");
DataInputStream dis = new DataInputStream(socket.getInputStream());
String nextline;
String line = "";
@@ -321,40 +314,38 @@ public class OCSPPublisher implements ILdapPublisher, IExtendedPluginInfo {
}
dis.close();
if (status) {
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- ILogger.LL_INFO, "OCSPPublisher: successful");
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
+ ILogger.LL_INFO, "OCSPPublisher: successful");
} else {
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- ILogger.LL_INFO, "OCSPPublisher: failed - " + error);
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
+ ILogger.LL_INFO, "OCSPPublisher: failed - " + error);
}
-
+
} catch (IOException e) {
CMS.debug("OCSPPublisher: publish failed " + e.toString());
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_OCSP_PUBLISHER_ERROR", e.toString()));
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
+ ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_OCSP_PUBLISHER_ERROR", e.toString()));
} catch (CRLException e) {
CMS.debug("OCSPPublisher: publish failed " + e.toString());
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_OCSP_PUBLISHER_ERROR", e.toString()));
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
+ ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_OCSP_PUBLISHER_ERROR", e.toString()));
} catch (Exception e) {
CMS.debug("OCSPPublisher: publish failed " + e.toString());
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_OCSP_PUBLISHER_ERROR", e.toString()));
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
+ ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_OCSP_PUBLISHER_ERROR", e.toString()));
}
}
/**
* Unpublishs a object to the ldap directory.
- *
- * @param conn the Ldap connection
- * (null if LDAP publishing is not enabled)
- * @param dn dn of the ldap entry to unpublish cert
- * (null if LDAP publishing is not enabled)
- * @param object object to unpublish
- * (java.security.cert.X509Certificate)
+ *
+ * @param conn the Ldap connection (null if LDAP publishing is not enabled)
+ * @param dn dn of the ldap entry to unpublish cert (null if LDAP publishing
+ * is not enabled)
+ * @param object object to unpublish (java.security.cert.X509Certificate)
*/
public void unpublish(LDAPConnection conn, String dn, Object object)
- throws ELdapException {
+ throws ELdapException {
// NOT USED
}
}
diff --git a/pki/base/common/src/com/netscape/cms/publish/publishers/Utils.java b/pki/base/common/src/com/netscape/cms/publish/publishers/Utils.java
index d5717aad..6232fa23 100644
--- a/pki/base/common/src/com/netscape/cms/publish/publishers/Utils.java
+++ b/pki/base/common/src/com/netscape/cms/publish/publishers/Utils.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.publish.publishers;
-
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
@@ -29,10 +28,9 @@ import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;
-
/**
* Publisher utility class.
- *
+ *
* @version $Revision$, $Date$
*/
public class Utils {
@@ -58,8 +56,8 @@ public class Utils {
}
}
- /// Sorts an array of Strings.
- // Java currently has no general sort function. Sorting Strings is
+ // / Sorts an array of Strings.
+ // Java currently has no general sort function. Sorting Strings is
// common enough that it's worth making a special case.
public static void sortStrings(String[] strings) {
// Just does a bubblesort.
@@ -75,8 +73,8 @@ public class Utils {
}
}
- /// Returns a date string formatted in Unix ls style - if it's within
- // six months of now, Mmm dd hh:ss, else Mmm dd yyyy.
+ // / Returns a date string formatted in Unix ls style - if it's within
+ // six months of now, Mmm dd hh:ss, else Mmm dd yyyy.
public static String lsDateStr(Date date) {
long dateTime = date.getTime();
@@ -104,9 +102,10 @@ public class Utils {
}
return true;
}
-
+
/**
* strips out double quotes around String parameter
+ *
* @param s the string potentially bracketed with double quotes
* @return string stripped of surrounding double quotes
*/
@@ -123,9 +122,8 @@ public class Utils {
}
/**
- * returns an array of strings from a vector of Strings
- * there'll be trouble if the Vector contains something other
- * than just Strings
+ * returns an array of strings from a vector of Strings there'll be trouble
+ * if the Vector contains something other than just Strings
*/
public static String[] getStringArrayFromVector(Vector v) {
String s[] = new String[v.size()];
diff --git a/pki/base/common/src/com/netscape/cms/request/RequestScheduler.java b/pki/base/common/src/com/netscape/cms/request/RequestScheduler.java
index b48af995..ad4672a6 100644
--- a/pki/base/common/src/com/netscape/cms/request/RequestScheduler.java
+++ b/pki/base/common/src/com/netscape/cms/request/RequestScheduler.java
@@ -17,18 +17,15 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.request;
-
import java.util.Vector;
import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.IRequestScheduler;
-
/**
- * This class represents a request scheduler that prioritizes
- * the threads based on the request processing order.
- * The request that enters the request queue first should
- * be processed first.
+ * This class represents a request scheduler that prioritizes the threads based
+ * on the request processing order. The request that enters the request queue
+ * first should be processed first.
*
* @version $Revision$, $Date$
*/
@@ -37,7 +34,7 @@ public class RequestScheduler implements IRequestScheduler {
/**
* Request entered the request queue processing.
- *
+ *
* @param r request
*/
public synchronized void requestIn(IRequest r) {
@@ -51,10 +48,10 @@ public class RequestScheduler implements IRequestScheduler {
/**
* Request exited the request queue processing.
- *
+ *
* @param r request
*/
- public synchronized void requestOut(IRequest r) {
+ public synchronized void requestOut(IRequest r) {
Thread current = Thread.currentThread();
Thread first = (Thread) mRequestThreads.elementAt(0);
diff --git a/pki/base/common/src/com/netscape/cms/selftests/ASelfTest.java b/pki/base/common/src/com/netscape/cms/selftests/ASelfTest.java
index df7f02bc..bda3fd51 100644
--- a/pki/base/common/src/com/netscape/cms/selftests/ASelfTest.java
+++ b/pki/base/common/src/com/netscape/cms/selftests/ASelfTest.java
@@ -20,7 +20,6 @@
package com.netscape.cms.selftests;
-
///////////////////////
// import statements //
///////////////////////
@@ -37,7 +36,6 @@ import com.netscape.certsrv.selftests.ESelfTestException;
import com.netscape.certsrv.selftests.ISelfTest;
import com.netscape.certsrv.selftests.ISelfTestSubsystem;
-
//////////////////////
// class definition //
//////////////////////
@@ -51,16 +49,14 @@ import com.netscape.certsrv.selftests.ISelfTestSubsystem;
* @version $Revision$, $Date$
*/
public abstract class ASelfTest
- implements ISelfTest {
- ////////////////////////
+ implements ISelfTest {
+ // //////////////////////
// default parameters //
- ////////////////////////
-
-
+ // //////////////////////
- //////////////////////////
+ // ////////////////////////
// ISelfTest parameters //
- //////////////////////////
+ // ////////////////////////
// parameter information
private static final String SELF_TEST_NAME = "ASelfTest";
@@ -71,32 +67,30 @@ public abstract class ASelfTest
protected IConfigStore mConfig = null;
protected String mPrefix = null;
- /////////////////////
+ // ///////////////////
// default methods //
- /////////////////////
+ // ///////////////////
-
-
- ///////////////////////
+ // /////////////////////
// ISelfTest methods //
- ///////////////////////
+ // /////////////////////
/**
- * Initializes this subsystem with the configuration store
- * associated with this instance name.
+ * Initializes this subsystem with the configuration store associated with
+ * this instance name.
* <P>
- *
+ *
* @param subsystem the associated subsystem
- * @param instanceName the name of this self test instance
+ * @param instanceName the name of this self test instance
* @param parameters configuration store (self test parameters)
* @exception EDuplicateSelfTestException subsystem has duplicate name/value
* @exception EInvalidSelfTestException subsystem has invalid name/value
* @exception EMissingSelfTestException subsystem has missing name/value
*/
public void initSelfTest(ISelfTestSubsystem subsystem,
- String instanceName,
- IConfigStore parameters)
- throws EDuplicateSelfTestException,
+ String instanceName,
+ IConfigStore parameters)
+ throws EDuplicateSelfTestException,
EInvalidSelfTestException,
EMissingSelfTestException {
// store individual self test class values for this instance
@@ -108,9 +102,9 @@ public abstract class ASelfTest
instanceName = instanceName.trim();
} else {
mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
- CMS.getLogMessage(
- "SELFTESTS_PARAMETER_WAS_NULL",
- SELF_TEST_NAME));
+ CMS.getLogMessage(
+ "SELFTESTS_PARAMETER_WAS_NULL",
+ SELF_TEST_NAME));
throw new EMissingSelfTestException();
}
@@ -124,14 +118,14 @@ public abstract class ASelfTest
mConfig = parameters.getSubStore(pluginPath);
if ((mConfig != null) &&
- (mConfig.getName() != null) &&
- (mConfig.getName() != "")) {
+ (mConfig.getName() != null) &&
+ (mConfig.getName() != "")) {
mPrefix = mConfig.getName().trim();
} else {
mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
- CMS.getLogMessage(
- "SELFTESTS_PARAMETER_WAS_NULL",
- SELF_TEST_NAME));
+ CMS.getLogMessage(
+ "SELFTESTS_PARAMETER_WAS_NULL",
+ SELF_TEST_NAME));
throw new EMissingSelfTestException();
}
@@ -142,24 +136,24 @@ public abstract class ASelfTest
/**
* Notifies this subsystem if it is in execution mode.
* <P>
- *
+ *
* @exception ESelfTestException failed to start
*/
public abstract void startupSelfTest()
- throws ESelfTestException;
+ throws ESelfTestException;
/**
- * Stops this subsystem. The subsystem may call shutdownSelfTest
- * anytime after initialization.
+ * Stops this subsystem. The subsystem may call shutdownSelfTest anytime
+ * after initialization.
* <P>
*/
public abstract void shutdownSelfTest();
/**
- * Returns the name associated with this self test. This method may
- * return null if the self test has not been intialized.
+ * Returns the name associated with this self test. This method may return
+ * null if the self test has not been intialized.
* <P>
- *
+ *
* @return instanceName of this self test
*/
public String getSelfTestName() {
@@ -167,10 +161,10 @@ public abstract class ASelfTest
}
/**
- * Returns the root configuration storage (self test parameters)
- * associated with this subsystem.
+ * Returns the root configuration storage (self test parameters) associated
+ * with this subsystem.
* <P>
- *
+ *
* @return configuration store (self test parameters) of this subsystem
*/
public IConfigStore getSelfTestConfigStore() {
@@ -178,10 +172,10 @@ public abstract class ASelfTest
}
/**
- * Retrieves description associated with an individual self test.
- * This method may return null.
+ * Retrieves description associated with an individual self test. This
+ * method may return null.
* <P>
- *
+ *
* @param locale locale of the client that requests the description
* @return description of self test
*/
@@ -190,11 +184,10 @@ public abstract class ASelfTest
/**
* Execute an individual self test.
* <P>
- *
+ *
* @param logger specifies logging subsystem
* @exception ESelfTestException self test exception
*/
public abstract void runSelfTest(ILogEventListener logger)
- throws ESelfTestException;
+ throws ESelfTestException;
}
-
diff --git a/pki/base/common/src/com/netscape/cms/selftests/ca/CAPresence.java b/pki/base/common/src/com/netscape/cms/selftests/ca/CAPresence.java
index cf3338ef..6d7a8de7 100644
--- a/pki/base/common/src/com/netscape/cms/selftests/ca/CAPresence.java
+++ b/pki/base/common/src/com/netscape/cms/selftests/ca/CAPresence.java
@@ -20,8 +20,6 @@
package com.netscape.cms.selftests.ca;
-
-
///////////////////////
// import statements //
///////////////////////
@@ -44,8 +42,6 @@ import com.netscape.certsrv.selftests.ESelfTestException;
import com.netscape.certsrv.selftests.ISelfTestSubsystem;
import com.netscape.cms.selftests.ASelfTest;
-
-
//////////////////////
// class definition //
//////////////////////
@@ -59,83 +55,75 @@ import com.netscape.cms.selftests.ASelfTest;
* @version $Revision$, $Date$
*/
public class CAPresence
-extends ASelfTest
-{
- ////////////////////////
+ extends ASelfTest {
+ // //////////////////////
// default parameters //
- ////////////////////////
-
+ // //////////////////////
-
- ///////////////////////////
+ // /////////////////////////
// CAPresence parameters //
- ///////////////////////////
+ // /////////////////////////
// parameter information
public static final String PROP_CA_SUB_ID = "CaSubId";
- private String mCaSubId = null;
-
+ private String mCaSubId = null;
-
- /////////////////////
+ // ///////////////////
// default methods //
- /////////////////////
-
+ // ///////////////////
-
- ////////////////////////
+ // //////////////////////
// CAPresence methods //
- ////////////////////////
+ // //////////////////////
/**
- * Initializes this subsystem with the configuration store
- * associated with this instance name.
+ * Initializes this subsystem with the configuration store associated with
+ * this instance name.
* <P>
- *
+ *
* @param subsystem the associated subsystem
- * @param instanceName the name of this self test instance
+ * @param instanceName the name of this self test instance
* @param parameters configuration store (self test parameters)
* @exception EDuplicateSelfTestException subsystem has duplicate name/value
* @exception EInvalidSelfTestException subsystem has invalid name/value
* @exception EMissingSelfTestException subsystem has missing name/value
*/
- public void initSelfTest( ISelfTestSubsystem subsystem,
+ public void initSelfTest(ISelfTestSubsystem subsystem,
String instanceName,
- IConfigStore parameters )
- throws EDuplicateSelfTestException,
- EInvalidSelfTestException,
- EMissingSelfTestException
- {
- super.initSelfTest( subsystem, instanceName, parameters );
+ IConfigStore parameters)
+ throws EDuplicateSelfTestException,
+ EInvalidSelfTestException,
+ EMissingSelfTestException {
+ super.initSelfTest(subsystem, instanceName, parameters);
// retrieve mandatory parameter(s)
try {
- mCaSubId = mConfig.getString( PROP_CA_SUB_ID );
- if( mCaSubId != null ) {
+ mCaSubId = mConfig.getString(PROP_CA_SUB_ID);
+ if (mCaSubId != null) {
mCaSubId = mCaSubId.trim();
} else {
- mSelfTestSubsystem.log( mSelfTestSubsystem.getSelfTestLogger(),
+ mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
CMS.getLogMessage(
- "SELFTESTS_MISSING_VALUES",
- getSelfTestName(),
- mPrefix
- + "."
- + PROP_CA_SUB_ID ) );
+ "SELFTESTS_MISSING_VALUES",
+ getSelfTestName(),
+ mPrefix
+ + "."
+ + PROP_CA_SUB_ID));
- throw new EMissingSelfTestException( PROP_CA_SUB_ID );
+ throw new EMissingSelfTestException(PROP_CA_SUB_ID);
}
- } catch( EBaseException e ) {
- mSelfTestSubsystem.log( mSelfTestSubsystem.getSelfTestLogger(),
+ } catch (EBaseException e) {
+ mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
CMS.getLogMessage(
- "SELFTESTS_MISSING_NAME",
- getSelfTestName(),
- mPrefix
- + "."
- + PROP_CA_SUB_ID ) );
+ "SELFTESTS_MISSING_NAME",
+ getSelfTestName(),
+ mPrefix
+ + "."
+ + PROP_CA_SUB_ID));
- throw new EMissingSelfTestException( mPrefix,
+ throw new EMissingSelfTestException(mPrefix,
PROP_CA_SUB_ID,
- null );
+ null);
}
// retrieve optional parameter(s)
@@ -143,145 +131,132 @@ extends ASelfTest
return;
}
-
/**
* Notifies this subsystem if it is in execution mode.
* <P>
- *
+ *
* @exception ESelfTestException failed to start
*/
public void startupSelfTest()
- throws ESelfTestException
- {
+ throws ESelfTestException {
return;
}
-
/**
- * Stops this subsystem. The subsystem may call shutdownSelfTest
- * anytime after initialization.
+ * Stops this subsystem. The subsystem may call shutdownSelfTest anytime
+ * after initialization.
* <P>
*/
- public void shutdownSelfTest()
- {
+ public void shutdownSelfTest() {
return;
}
-
/**
- * Returns the name associated with this self test. This method may
- * return null if the self test has not been intialized.
+ * Returns the name associated with this self test. This method may return
+ * null if the self test has not been intialized.
* <P>
- *
+ *
* @return instanceName of this self test
*/
- public String getSelfTestName()
- {
+ public String getSelfTestName() {
return super.getSelfTestName();
}
-
/**
- * Returns the root configuration storage (self test parameters)
- * associated with this subsystem.
+ * Returns the root configuration storage (self test parameters) associated
+ * with this subsystem.
* <P>
- *
+ *
* @return configuration store (self test parameters) of this subsystem
*/
- public IConfigStore getSelfTestConfigStore()
- {
+ public IConfigStore getSelfTestConfigStore() {
return super.getSelfTestConfigStore();
}
-
/**
- * Retrieves description associated with an individual self test.
- * This method may return null.
+ * Retrieves description associated with an individual self test. This
+ * method may return null.
* <P>
- *
+ *
* @param locale locale of the client that requests the description
* @return description of self test
*/
- public String getSelfTestDescription( Locale locale )
- {
- return CMS.getUserMessage( locale,
- "CMS_SELFTESTS_CA_PRESENCE_DESCRIPTION" );
+ public String getSelfTestDescription(Locale locale) {
+ return CMS.getUserMessage(locale,
+ "CMS_SELFTESTS_CA_PRESENCE_DESCRIPTION");
}
-
/**
* Execute an individual self test.
* <P>
- *
+ *
* @param logger specifies logging subsystem
* @exception ESelfTestException self test exception
*/
- public void runSelfTest( ILogEventListener logger )
- throws ESelfTestException
- {
+ public void runSelfTest(ILogEventListener logger)
+ throws ESelfTestException {
String logMessage = null;
ICertificateAuthority ca = null;
X509CertImpl caCert = null;
X509Key caPubKey = null;
- ca = ( ICertificateAuthority ) CMS.getSubsystem( mCaSubId );
+ ca = (ICertificateAuthority) CMS.getSubsystem(mCaSubId);
- if( ca == null ) {
+ if (ca == null) {
// log that the CA is not installed
- logMessage = CMS.getLogMessage( "SELFTESTS_CA_IS_NOT_PRESENT",
- getSelfTestName() );
+ logMessage = CMS.getLogMessage("SELFTESTS_CA_IS_NOT_PRESENT",
+ getSelfTestName());
- mSelfTestSubsystem.log( logger,
- logMessage );
+ mSelfTestSubsystem.log(logger,
+ logMessage);
- throw new ESelfTestException( logMessage );
+ throw new ESelfTestException(logMessage);
} else {
// Retrieve the CA certificate
caCert = ca.getCACert();
- if( caCert == null ) {
+ if (caCert == null) {
// log that the CA is not yet initialized
- logMessage = CMS.getLogMessage(
+ logMessage = CMS.getLogMessage(
"SELFTESTS_CA_IS_NOT_INITIALIZED",
- getSelfTestName() );
+ getSelfTestName());
- mSelfTestSubsystem.log( logger,
- logMessage );
+ mSelfTestSubsystem.log(logger,
+ logMessage);
- throw new ESelfTestException( logMessage );
+ throw new ESelfTestException(logMessage);
}
// Retrieve the CA certificate public key
try {
- caPubKey = ( X509Key ) caCert.get( X509CertImpl.PUBLIC_KEY );
+ caPubKey = (X509Key) caCert.get(X509CertImpl.PUBLIC_KEY);
- if( caPubKey == null ) {
+ if (caPubKey == null) {
// log that something is seriously wrong with the CA
- logMessage = CMS.getLogMessage( "SELFTESTS_CA_IS_CORRUPT",
- getSelfTestName() );
+ logMessage = CMS.getLogMessage("SELFTESTS_CA_IS_CORRUPT",
+ getSelfTestName());
- mSelfTestSubsystem.log( logger,
- logMessage );
+ mSelfTestSubsystem.log(logger,
+ logMessage);
- throw new ESelfTestException( logMessage );
+ throw new ESelfTestException(logMessage);
}
- } catch( CertificateParsingException e ) {
+ } catch (CertificateParsingException e) {
// log that something is seriously wrong with the CA
- mSelfTestSubsystem.log( logger,
- e.toString() );
+ mSelfTestSubsystem.log(logger,
+ e.toString());
- throw new ESelfTestException( e.toString() );
+ throw new ESelfTestException(e.toString());
}
// log that the CA is present
- logMessage = CMS.getLogMessage( "SELFTESTS_CA_IS_PRESENT",
- getSelfTestName() );
+ logMessage = CMS.getLogMessage("SELFTESTS_CA_IS_PRESENT",
+ getSelfTestName());
- mSelfTestSubsystem.log( logger,
- logMessage );
+ mSelfTestSubsystem.log(logger,
+ logMessage);
}
return;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/selftests/ca/CAValidity.java b/pki/base/common/src/com/netscape/cms/selftests/ca/CAValidity.java
index cff35ce5..cdda0a0d 100644
--- a/pki/base/common/src/com/netscape/cms/selftests/ca/CAValidity.java
+++ b/pki/base/common/src/com/netscape/cms/selftests/ca/CAValidity.java
@@ -20,8 +20,6 @@
package com.netscape.cms.selftests.ca;
-
-
///////////////////////
// import statements //
///////////////////////
@@ -44,14 +42,12 @@ import com.netscape.certsrv.selftests.ESelfTestException;
import com.netscape.certsrv.selftests.ISelfTestSubsystem;
import com.netscape.cms.selftests.ASelfTest;
-
-
//////////////////////
// class definition //
//////////////////////
/**
- * This class implements a self test to check the validity of the CA.
+ * This class implements a self test to check the validity of the CA.
* <P>
*
* @author mharmsen
@@ -59,83 +55,75 @@ import com.netscape.cms.selftests.ASelfTest;
* @version $Revision$, $Date$
*/
public class CAValidity
-extends ASelfTest
-{
- ////////////////////////
+ extends ASelfTest {
+ // //////////////////////
// default parameters //
- ////////////////////////
-
+ // //////////////////////
-
- ///////////////////////////
+ // /////////////////////////
// CAValidity parameters //
- ///////////////////////////
+ // /////////////////////////
// parameter information
public static final String PROP_CA_SUB_ID = "CaSubId";
- private String mCaSubId = null;
-
+ private String mCaSubId = null;
-
- /////////////////////
+ // ///////////////////
// default methods //
- /////////////////////
-
+ // ///////////////////
-
- ////////////////////////
+ // //////////////////////
// CAValidity methods //
- ////////////////////////
+ // //////////////////////
/**
- * Initializes this subsystem with the configuration store
- * associated with this instance name.
+ * Initializes this subsystem with the configuration store associated with
+ * this instance name.
* <P>
- *
+ *
* @param subsystem the associated subsystem
- * @param instanceName the name of this self test instance
+ * @param instanceName the name of this self test instance
* @param parameters configuration store (self test parameters)
* @exception EDuplicateSelfTestException subsystem has duplicate name/value
* @exception EInvalidSelfTestException subsystem has invalid name/value
* @exception EMissingSelfTestException subsystem has missing name/value
*/
- public void initSelfTest( ISelfTestSubsystem subsystem,
+ public void initSelfTest(ISelfTestSubsystem subsystem,
String instanceName,
- IConfigStore parameters )
- throws EDuplicateSelfTestException,
- EInvalidSelfTestException,
- EMissingSelfTestException
- {
- super.initSelfTest( subsystem, instanceName, parameters );
+ IConfigStore parameters)
+ throws EDuplicateSelfTestException,
+ EInvalidSelfTestException,
+ EMissingSelfTestException {
+ super.initSelfTest(subsystem, instanceName, parameters);
// retrieve mandatory parameter(s)
try {
- mCaSubId = mConfig.getString( PROP_CA_SUB_ID );
- if( mCaSubId != null ) {
+ mCaSubId = mConfig.getString(PROP_CA_SUB_ID);
+ if (mCaSubId != null) {
mCaSubId = mCaSubId.trim();
} else {
- mSelfTestSubsystem.log( mSelfTestSubsystem.getSelfTestLogger(),
+ mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
CMS.getLogMessage(
- "SELFTESTS_MISSING_VALUES",
- getSelfTestName(),
- mPrefix
- + "."
- + PROP_CA_SUB_ID ) );
+ "SELFTESTS_MISSING_VALUES",
+ getSelfTestName(),
+ mPrefix
+ + "."
+ + PROP_CA_SUB_ID));
- throw new EMissingSelfTestException( PROP_CA_SUB_ID );
+ throw new EMissingSelfTestException(PROP_CA_SUB_ID);
}
- } catch( EBaseException e ) {
- mSelfTestSubsystem.log( mSelfTestSubsystem.getSelfTestLogger(),
+ } catch (EBaseException e) {
+ mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
CMS.getLogMessage(
- "SELFTESTS_MISSING_NAME",
- getSelfTestName(),
- mPrefix
- + "."
- + PROP_CA_SUB_ID ) );
+ "SELFTESTS_MISSING_NAME",
+ getSelfTestName(),
+ mPrefix
+ + "."
+ + PROP_CA_SUB_ID));
- throw new EMissingSelfTestException( mPrefix,
+ throw new EMissingSelfTestException(mPrefix,
PROP_CA_SUB_ID,
- null );
+ null);
}
// retrieve optional parameter(s)
@@ -143,145 +131,132 @@ extends ASelfTest
return;
}
-
/**
* Notifies this subsystem if it is in execution mode.
* <P>
- *
+ *
* @exception ESelfTestException failed to start
*/
public void startupSelfTest()
- throws ESelfTestException
- {
+ throws ESelfTestException {
return;
}
-
/**
- * Stops this subsystem. The subsystem may call shutdownSelfTest
- * anytime after initialization.
+ * Stops this subsystem. The subsystem may call shutdownSelfTest anytime
+ * after initialization.
* <P>
*/
- public void shutdownSelfTest()
- {
+ public void shutdownSelfTest() {
return;
}
-
/**
- * Returns the name associated with this self test. This method may
- * return null if the self test has not been intialized.
+ * Returns the name associated with this self test. This method may return
+ * null if the self test has not been intialized.
* <P>
- *
+ *
* @return instanceName of this self test
*/
- public String getSelfTestName()
- {
+ public String getSelfTestName() {
return super.getSelfTestName();
}
-
/**
- * Returns the root configuration storage (self test parameters)
- * associated with this subsystem.
+ * Returns the root configuration storage (self test parameters) associated
+ * with this subsystem.
* <P>
- *
+ *
* @return configuration store (self test parameters) of this subsystem
*/
- public IConfigStore getSelfTestConfigStore()
- {
+ public IConfigStore getSelfTestConfigStore() {
return super.getSelfTestConfigStore();
}
-
/**
- * Retrieves description associated with an individual self test.
- * This method may return null.
+ * Retrieves description associated with an individual self test. This
+ * method may return null.
* <P>
- *
+ *
* @param locale locale of the client that requests the description
* @return description of self test
*/
- public String getSelfTestDescription( Locale locale )
- {
- return CMS.getUserMessage( locale,
- "CMS_SELFTESTS_CA_VALIDITY_DESCRIPTION" );
+ public String getSelfTestDescription(Locale locale) {
+ return CMS.getUserMessage(locale,
+ "CMS_SELFTESTS_CA_VALIDITY_DESCRIPTION");
}
-
/**
* Execute an individual self test.
* <P>
- *
+ *
* @param logger specifies logging subsystem
* @exception ESelfTestException self test exception
*/
- public void runSelfTest( ILogEventListener logger )
- throws ESelfTestException
- {
+ public void runSelfTest(ILogEventListener logger)
+ throws ESelfTestException {
String logMessage = null;
ICertificateAuthority ca = null;
X509CertImpl caCert = null;
- ca = ( ICertificateAuthority ) CMS.getSubsystem( mCaSubId );
+ ca = (ICertificateAuthority) CMS.getSubsystem(mCaSubId);
- if( ca == null ) {
+ if (ca == null) {
// log that the CA is not installed
- logMessage = CMS.getLogMessage( "SELFTESTS_CA_IS_NOT_PRESENT",
- getSelfTestName() );
+ logMessage = CMS.getLogMessage("SELFTESTS_CA_IS_NOT_PRESENT",
+ getSelfTestName());
- mSelfTestSubsystem.log( logger,
- logMessage );
+ mSelfTestSubsystem.log(logger,
+ logMessage);
- throw new ESelfTestException( logMessage );
+ throw new ESelfTestException(logMessage);
} else {
// Retrieve the CA certificate
caCert = ca.getCACert();
- if( caCert == null ) {
+ if (caCert == null) {
// log that the CA is not yet initialized
- logMessage = CMS.getLogMessage(
+ logMessage = CMS.getLogMessage(
"SELFTESTS_CA_IS_NOT_INITIALIZED",
- getSelfTestName() );
+ getSelfTestName());
- mSelfTestSubsystem.log( logger,
- logMessage );
+ mSelfTestSubsystem.log(logger,
+ logMessage);
- throw new ESelfTestException( logMessage );
+ throw new ESelfTestException(logMessage);
}
// Retrieve the CA validity period
try {
caCert.checkValidity();
- } catch( CertificateNotYetValidException e ) {
+ } catch (CertificateNotYetValidException e) {
// log that the CA is not yet valid
- logMessage = CMS.getLogMessage( "SELFTESTS_CA_IS_NOT_YET_VALID",
- getSelfTestName() );
+ logMessage = CMS.getLogMessage("SELFTESTS_CA_IS_NOT_YET_VALID",
+ getSelfTestName());
- mSelfTestSubsystem.log( logger,
- logMessage );
+ mSelfTestSubsystem.log(logger,
+ logMessage);
- throw new ESelfTestException( logMessage );
- } catch( CertificateExpiredException e ) {
+ throw new ESelfTestException(logMessage);
+ } catch (CertificateExpiredException e) {
// log that the CA is expired
- logMessage = CMS.getLogMessage( "SELFTESTS_CA_IS_EXPIRED",
- getSelfTestName() );
+ logMessage = CMS.getLogMessage("SELFTESTS_CA_IS_EXPIRED",
+ getSelfTestName());
- mSelfTestSubsystem.log( logger,
- logMessage );
+ mSelfTestSubsystem.log(logger,
+ logMessage);
- throw new ESelfTestException( logMessage );
+ throw new ESelfTestException(logMessage);
}
// log that the CA is valid
- logMessage = CMS.getLogMessage( "SELFTESTS_CA_IS_VALID",
- getSelfTestName() );
+ logMessage = CMS.getLogMessage("SELFTESTS_CA_IS_VALID",
+ getSelfTestName());
- mSelfTestSubsystem.log( logger,
- logMessage );
+ mSelfTestSubsystem.log(logger,
+ logMessage);
}
return;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/selftests/common/SystemCertsVerification.java b/pki/base/common/src/com/netscape/cms/selftests/common/SystemCertsVerification.java
index b3388d9e..a85d5ba4 100644
--- a/pki/base/common/src/com/netscape/cms/selftests/common/SystemCertsVerification.java
+++ b/pki/base/common/src/com/netscape/cms/selftests/common/SystemCertsVerification.java
@@ -20,8 +20,6 @@
package com.netscape.cms.selftests.common;
-
-
///////////////////////
// import statements //
///////////////////////
@@ -39,97 +37,86 @@ import com.netscape.certsrv.selftests.ESelfTestException;
import com.netscape.certsrv.selftests.ISelfTestSubsystem;
import com.netscape.cms.selftests.ASelfTest;
-
-
//////////////////////
// class definition //
//////////////////////
/**
- * This class implements a self test to check the system certs
- * of the subsystem
+ * This class implements a self test to check the system certs of the subsystem
* <P>
*
- * @version $Revision: $, $Date: $
+ * @version $Revision: $, $Date: $
*/
public class SystemCertsVerification
-extends ASelfTest
-{
- ////////////////////////
+ extends ASelfTest {
+ // //////////////////////
// default parameters //
- ////////////////////////
-
+ // //////////////////////
-
- ///////////////////////////
+ // /////////////////////////
// SystemCertsVerification parameters //
- ///////////////////////////
+ // /////////////////////////
// parameter information
public static final String PROP_SUB_ID = "SubId";
- private String mSubId = null;
-
+ private String mSubId = null;
-
- /////////////////////
+ // ///////////////////
// default methods //
- /////////////////////
-
+ // ///////////////////
-
- ////////////////////////
+ // //////////////////////
// SystemCertsVerification methods //
- ////////////////////////
+ // //////////////////////
/**
- * Initializes this subsystem with the configuration store
- * associated with this instance name.
+ * Initializes this subsystem with the configuration store associated with
+ * this instance name.
* <P>
- *
+ *
* @param subsystem the associated subsystem
- * @param instanceName the name of this self test instance
+ * @param instanceName the name of this self test instance
* @param parameters configuration store (self test parameters)
* @exception EDuplicateSelfTestException subsystem has duplicate name/value
* @exception EInvalidSelfTestException subsystem has invalid name/value
* @exception EMissingSelfTestException subsystem has missing name/value
*/
- public void initSelfTest( ISelfTestSubsystem subsystem,
+ public void initSelfTest(ISelfTestSubsystem subsystem,
String instanceName,
- IConfigStore parameters )
- throws EDuplicateSelfTestException,
- EInvalidSelfTestException,
- EMissingSelfTestException
- {
- super.initSelfTest( subsystem, instanceName, parameters );
+ IConfigStore parameters)
+ throws EDuplicateSelfTestException,
+ EInvalidSelfTestException,
+ EMissingSelfTestException {
+ super.initSelfTest(subsystem, instanceName, parameters);
// retrieve mandatory parameter(s)
try {
- mSubId = mConfig.getString( PROP_SUB_ID );
- if( mSubId != null ) {
+ mSubId = mConfig.getString(PROP_SUB_ID);
+ if (mSubId != null) {
mSubId = mSubId.trim();
} else {
- mSelfTestSubsystem.log( mSelfTestSubsystem.getSelfTestLogger(),
+ mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
CMS.getLogMessage(
- "SELFTESTS_MISSING_VALUES",
- getSelfTestName(),
- mPrefix
- + "."
- + PROP_SUB_ID ) );
+ "SELFTESTS_MISSING_VALUES",
+ getSelfTestName(),
+ mPrefix
+ + "."
+ + PROP_SUB_ID));
- throw new EMissingSelfTestException( PROP_SUB_ID );
+ throw new EMissingSelfTestException(PROP_SUB_ID);
}
- } catch( EBaseException e ) {
- mSelfTestSubsystem.log( mSelfTestSubsystem.getSelfTestLogger(),
+ } catch (EBaseException e) {
+ mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
CMS.getLogMessage(
- "SELFTESTS_MISSING_NAME",
- getSelfTestName(),
- mPrefix
- + "."
- + PROP_SUB_ID ) );
+ "SELFTESTS_MISSING_NAME",
+ getSelfTestName(),
+ mPrefix
+ + "."
+ + PROP_SUB_ID));
- throw new EMissingSelfTestException( mPrefix,
+ throw new EMissingSelfTestException(mPrefix,
PROP_SUB_ID,
- null );
+ null);
}
// retrieve optional parameter(s)
@@ -137,102 +124,89 @@ extends ASelfTest
return;
}
-
/**
* Notifies this subsystem if it is in execution mode.
* <P>
- *
+ *
* @exception ESelfTestException failed to start
*/
public void startupSelfTest()
- throws ESelfTestException
- {
+ throws ESelfTestException {
return;
}
-
/**
- * Stops this subsystem. The subsystem may call shutdownSelfTest
- * anytime after initialization.
+ * Stops this subsystem. The subsystem may call shutdownSelfTest anytime
+ * after initialization.
* <P>
*/
- public void shutdownSelfTest()
- {
+ public void shutdownSelfTest() {
return;
}
-
/**
- * Returns the name associated with this self test. This method may
- * return null if the self test has not been intialized.
+ * Returns the name associated with this self test. This method may return
+ * null if the self test has not been intialized.
* <P>
- *
+ *
* @return instanceName of this self test
*/
- public String getSelfTestName()
- {
+ public String getSelfTestName() {
return super.getSelfTestName();
}
-
/**
- * Returns the root configuration storage (self test parameters)
- * associated with this subsystem.
+ * Returns the root configuration storage (self test parameters) associated
+ * with this subsystem.
* <P>
- *
+ *
* @return configuration store (self test parameters) of this subsystem
*/
- public IConfigStore getSelfTestConfigStore()
- {
+ public IConfigStore getSelfTestConfigStore() {
return super.getSelfTestConfigStore();
}
-
/**
- * Retrieves description associated with an individual self test.
- * This method may return null.
+ * Retrieves description associated with an individual self test. This
+ * method may return null.
* <P>
- *
+ *
* @param locale locale of the client that requests the description
* @return description of self test
*/
- public String getSelfTestDescription( Locale locale )
- {
- return CMS.getUserMessage( locale,
- "CMS_SELFTESTS_SYSTEM_CERTS_VERIFICATION_DESCRIPTION" );
+ public String getSelfTestDescription(Locale locale) {
+ return CMS.getUserMessage(locale,
+ "CMS_SELFTESTS_SYSTEM_CERTS_VERIFICATION_DESCRIPTION");
}
-
/**
* Execute an individual self test.
* <P>
- *
+ *
* @param logger specifies logging subsystem
* @exception ESelfTestException self test exception
*/
- public void runSelfTest( ILogEventListener logger )
- throws ESelfTestException
- {
+ public void runSelfTest(ILogEventListener logger)
+ throws ESelfTestException {
String logMessage = null;
boolean rc = false;
rc = CMS.verifySystemCerts();
if (rc == true) {
- logMessage = CMS.getLogMessage( "SELFTESTS_COMMON_SYSTEM_CERTS_VERIFICATION_SUCCESS",
- getSelfTestName() );
+ logMessage = CMS.getLogMessage("SELFTESTS_COMMON_SYSTEM_CERTS_VERIFICATION_SUCCESS",
+ getSelfTestName());
- mSelfTestSubsystem.log( logger,
- logMessage );
+ mSelfTestSubsystem.log(logger,
+ logMessage);
} else {
- logMessage = CMS.getLogMessage( "SELFTESTS_COMMON_SYSTEM_CERTS_VERIFICATION_FAILURE",
- getSelfTestName() );
+ logMessage = CMS.getLogMessage("SELFTESTS_COMMON_SYSTEM_CERTS_VERIFICATION_FAILURE",
+ getSelfTestName());
- mSelfTestSubsystem.log( logger,
- logMessage );
- throw new ESelfTestException( logMessage );
+ mSelfTestSubsystem.log(logger,
+ logMessage);
+ throw new ESelfTestException(logMessage);
}
return;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/selftests/kra/KRAPresence.java b/pki/base/common/src/com/netscape/cms/selftests/kra/KRAPresence.java
index 52255e24..1c86bb5c 100644
--- a/pki/base/common/src/com/netscape/cms/selftests/kra/KRAPresence.java
+++ b/pki/base/common/src/com/netscape/cms/selftests/kra/KRAPresence.java
@@ -20,8 +20,6 @@
package com.netscape.cms.selftests.kra;
-
-
///////////////////////
// import statements //
///////////////////////
@@ -41,8 +39,6 @@ import com.netscape.certsrv.selftests.ESelfTestException;
import com.netscape.certsrv.selftests.ISelfTestSubsystem;
import com.netscape.cms.selftests.ASelfTest;
-
-
//////////////////////
// class definition //
//////////////////////
@@ -56,83 +52,75 @@ import com.netscape.cms.selftests.ASelfTest;
* @version $Revision$, $Date$
*/
public class KRAPresence
-extends ASelfTest
-{
- ////////////////////////
+ extends ASelfTest {
+ // //////////////////////
// default parameters //
- ////////////////////////
-
+ // //////////////////////
-
- ///////////////////////////
+ // /////////////////////////
// KRAPresence parameters //
- ///////////////////////////
+ // /////////////////////////
// parameter information
public static final String PROP_KRA_SUB_ID = "SubId";
- private String mSubId = null;
-
+ private String mSubId = null;
-
- /////////////////////
+ // ///////////////////
// default methods //
- /////////////////////
-
+ // ///////////////////
-
- ////////////////////////
+ // //////////////////////
// KRAPresence methods //
- ////////////////////////
+ // //////////////////////
/**
- * Initializes this subsystem with the configuration store
- * associated with this instance name.
+ * Initializes this subsystem with the configuration store associated with
+ * this instance name.
* <P>
- *
+ *
* @param subsystem the associated subsystem
- * @param instanceName the name of this self test instance
+ * @param instanceName the name of this self test instance
* @param parameters configuration store (self test parameters)
* @exception EDuplicateSelfTestException subsystem has duplicate name/value
* @exception EInvalidSelfTestException subsystem has invalid name/value
* @exception EMissingSelfTestException subsystem has missing name/value
*/
- public void initSelfTest( ISelfTestSubsystem subsystem,
+ public void initSelfTest(ISelfTestSubsystem subsystem,
String instanceName,
- IConfigStore parameters )
- throws EDuplicateSelfTestException,
- EInvalidSelfTestException,
- EMissingSelfTestException
- {
- super.initSelfTest( subsystem, instanceName, parameters );
+ IConfigStore parameters)
+ throws EDuplicateSelfTestException,
+ EInvalidSelfTestException,
+ EMissingSelfTestException {
+ super.initSelfTest(subsystem, instanceName, parameters);
// retrieve mandatory parameter(s)
try {
- mSubId = mConfig.getString( PROP_KRA_SUB_ID );
- if( mSubId != null ) {
+ mSubId = mConfig.getString(PROP_KRA_SUB_ID);
+ if (mSubId != null) {
mSubId = mSubId.trim();
} else {
- mSelfTestSubsystem.log( mSelfTestSubsystem.getSelfTestLogger(),
+ mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
CMS.getLogMessage(
- "SELFTESTS_MISSING_VALUES",
- getSelfTestName(),
- mPrefix
- + "."
- + PROP_KRA_SUB_ID ) );
+ "SELFTESTS_MISSING_VALUES",
+ getSelfTestName(),
+ mPrefix
+ + "."
+ + PROP_KRA_SUB_ID));
- throw new EMissingSelfTestException( PROP_KRA_SUB_ID );
+ throw new EMissingSelfTestException(PROP_KRA_SUB_ID);
}
- } catch( EBaseException e ) {
- mSelfTestSubsystem.log( mSelfTestSubsystem.getSelfTestLogger(),
+ } catch (EBaseException e) {
+ mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
CMS.getLogMessage(
- "SELFTESTS_MISSING_NAME",
- getSelfTestName(),
- mPrefix
- + "."
- + PROP_KRA_SUB_ID ) );
+ "SELFTESTS_MISSING_NAME",
+ getSelfTestName(),
+ mPrefix
+ + "."
+ + PROP_KRA_SUB_ID));
- throw new EMissingSelfTestException( mPrefix,
+ throw new EMissingSelfTestException(mPrefix,
PROP_KRA_SUB_ID,
- null );
+ null);
}
// retrieve optional parameter(s)
@@ -140,137 +128,124 @@ extends ASelfTest
return;
}
-
/**
* Notifies this subsystem if it is in execution mode.
* <P>
- *
+ *
* @exception ESelfTestException failed to start
*/
public void startupSelfTest()
- throws ESelfTestException
- {
+ throws ESelfTestException {
return;
}
-
/**
- * Stops this subsystem. The subsystem may call shutdownSelfTest
- * anytime after initialization.
+ * Stops this subsystem. The subsystem may call shutdownSelfTest anytime
+ * after initialization.
* <P>
*/
- public void shutdownSelfTest()
- {
+ public void shutdownSelfTest() {
return;
}
-
/**
- * Returns the name associated with this self test. This method may
- * return null if the self test has not been intialized.
+ * Returns the name associated with this self test. This method may return
+ * null if the self test has not been intialized.
* <P>
- *
+ *
* @return instanceName of this self test
*/
- public String getSelfTestName()
- {
+ public String getSelfTestName() {
return super.getSelfTestName();
}
-
/**
- * Returns the root configuration storage (self test parameters)
- * associated with this subsystem.
+ * Returns the root configuration storage (self test parameters) associated
+ * with this subsystem.
* <P>
- *
+ *
* @return configuration store (self test parameters) of this subsystem
*/
- public IConfigStore getSelfTestConfigStore()
- {
+ public IConfigStore getSelfTestConfigStore() {
return super.getSelfTestConfigStore();
}
-
/**
- * Retrieves description associated with an individual self test.
- * This method may return null.
+ * Retrieves description associated with an individual self test. This
+ * method may return null.
* <P>
- *
+ *
* @param locale locale of the client that requests the description
* @return description of self test
*/
- public String getSelfTestDescription( Locale locale )
- {
- return CMS.getUserMessage( locale,
- "CMS_SELFTESTS_KRA_PRESENCE_DESCRIPTION" );
+ public String getSelfTestDescription(Locale locale) {
+ return CMS.getUserMessage(locale,
+ "CMS_SELFTESTS_KRA_PRESENCE_DESCRIPTION");
}
-
/**
* Execute an individual self test.
* <P>
- *
+ *
* @param logger specifies logging subsystem
* @exception ESelfTestException self test exception
*/
- public void runSelfTest( ILogEventListener logger )
- throws ESelfTestException
- {
+ public void runSelfTest(ILogEventListener logger)
+ throws ESelfTestException {
String logMessage = null;
IKeyRecoveryAuthority kra = null;
org.mozilla.jss.crypto.X509Certificate kraCert = null;
PublicKey kraPubKey = null;
- kra = ( IKeyRecoveryAuthority ) CMS.getSubsystem( mSubId );
+ kra = (IKeyRecoveryAuthority) CMS.getSubsystem(mSubId);
- if( kra == null ) {
+ if (kra == null) {
// log that the KRA is not installed
- logMessage = CMS.getLogMessage( "SELFTESTS_KRA_IS_NOT_PRESENT",
- getSelfTestName() );
+ logMessage = CMS.getLogMessage("SELFTESTS_KRA_IS_NOT_PRESENT",
+ getSelfTestName());
- mSelfTestSubsystem.log( logger,
- logMessage );
+ mSelfTestSubsystem.log(logger,
+ logMessage);
- throw new ESelfTestException( logMessage );
+ throw new ESelfTestException(logMessage);
} else {
// Retrieve the KRA certificate
kraCert = kra.getTransportCert();
- if( kraCert == null ) {
+ if (kraCert == null) {
// log that the RA is not yet initialized
- logMessage = CMS.getLogMessage(
+ logMessage = CMS.getLogMessage(
"SELFTESTS_KRA_IS_NOT_INITIALIZED",
- getSelfTestName() );
+ getSelfTestName());
- mSelfTestSubsystem.log( logger,
- logMessage );
+ mSelfTestSubsystem.log(logger,
+ logMessage);
- throw new ESelfTestException( logMessage );
+ throw new ESelfTestException(logMessage);
}
// Retrieve the KRA certificate public key
- kraPubKey = ( PublicKey ) kraCert.getPublicKey();
+ kraPubKey = (PublicKey) kraCert.getPublicKey();
- if( kraPubKey == null ) {
+ if (kraPubKey == null) {
// log that something is seriously wrong with the KRA
- logMessage = CMS.getLogMessage( "SELFTESTS_KRA_IS_CORRUPT",
- getSelfTestName() );
+ logMessage = CMS.getLogMessage("SELFTESTS_KRA_IS_CORRUPT",
+ getSelfTestName());
- mSelfTestSubsystem.log( logger,
- logMessage );
+ mSelfTestSubsystem.log(logger,
+ logMessage);
- throw new ESelfTestException( logMessage );
+ throw new ESelfTestException(logMessage);
}
// log that the KRA is present
- logMessage = CMS.getLogMessage( "SELFTESTS_KRA_IS_PRESENT",
- getSelfTestName() );
+ logMessage = CMS.getLogMessage("SELFTESTS_KRA_IS_PRESENT",
+ getSelfTestName());
- mSelfTestSubsystem.log( logger,
- logMessage );
+ mSelfTestSubsystem.log(logger,
+ logMessage);
}
return;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/selftests/ocsp/OCSPPresence.java b/pki/base/common/src/com/netscape/cms/selftests/ocsp/OCSPPresence.java
index 507148bd..cfdb20af 100644
--- a/pki/base/common/src/com/netscape/cms/selftests/ocsp/OCSPPresence.java
+++ b/pki/base/common/src/com/netscape/cms/selftests/ocsp/OCSPPresence.java
@@ -20,8 +20,6 @@
package com.netscape.cms.selftests.ocsp;
-
-
///////////////////////
// import statements //
///////////////////////
@@ -45,8 +43,6 @@ import com.netscape.certsrv.selftests.ESelfTestException;
import com.netscape.certsrv.selftests.ISelfTestSubsystem;
import com.netscape.cms.selftests.ASelfTest;
-
-
//////////////////////
// class definition //
//////////////////////
@@ -60,83 +56,75 @@ import com.netscape.cms.selftests.ASelfTest;
* @version $Revision$, $Date$
*/
public class OCSPPresence
-extends ASelfTest
-{
- ////////////////////////
+ extends ASelfTest {
+ // //////////////////////
// default parameters //
- ////////////////////////
-
-
+ // //////////////////////
- /////////////////////////////
+ // ///////////////////////////
// OCSPPresence parameters //
- /////////////////////////////
+ // ///////////////////////////
// parameter information
public static final String PROP_OCSP_SUB_ID = "OcspSubId";
- private String mOcspSubId = null;
+ private String mOcspSubId = null;
-
-
- /////////////////////
+ // ///////////////////
// default methods //
- /////////////////////
-
+ // ///////////////////
-
- //////////////////////////
+ // ////////////////////////
// OCSPPresence methods //
- //////////////////////////
+ // ////////////////////////
/**
- * Initializes this subsystem with the configuration store
- * associated with this instance name.
+ * Initializes this subsystem with the configuration store associated with
+ * this instance name.
* <P>
- *
+ *
* @param subsystem the associated subsystem
- * @param instanceName the name of this self test instance
+ * @param instanceName the name of this self test instance
* @param parameters configuration store (self test parameters)
* @exception EDuplicateSelfTestException subsystem has duplicate name/value
* @exception EInvalidSelfTestException subsystem has invalid name/value
* @exception EMissingSelfTestException subsystem has missing name/value
*/
- public void initSelfTest( ISelfTestSubsystem subsystem,
+ public void initSelfTest(ISelfTestSubsystem subsystem,
String instanceName,
- IConfigStore parameters )
- throws EDuplicateSelfTestException,
- EInvalidSelfTestException,
- EMissingSelfTestException
- {
- super.initSelfTest( subsystem, instanceName, parameters );
+ IConfigStore parameters)
+ throws EDuplicateSelfTestException,
+ EInvalidSelfTestException,
+ EMissingSelfTestException {
+ super.initSelfTest(subsystem, instanceName, parameters);
// retrieve mandatory parameter(s)
try {
- mOcspSubId = mConfig.getString( PROP_OCSP_SUB_ID );
- if( mOcspSubId != null ) {
+ mOcspSubId = mConfig.getString(PROP_OCSP_SUB_ID);
+ if (mOcspSubId != null) {
mOcspSubId = mOcspSubId.trim();
} else {
- mSelfTestSubsystem.log( mSelfTestSubsystem.getSelfTestLogger(),
+ mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
CMS.getLogMessage(
- "SELFTESTS_MISSING_VALUES",
- getSelfTestName(),
- mPrefix
- + "."
- + PROP_OCSP_SUB_ID ) );
+ "SELFTESTS_MISSING_VALUES",
+ getSelfTestName(),
+ mPrefix
+ + "."
+ + PROP_OCSP_SUB_ID));
- throw new EMissingSelfTestException( PROP_OCSP_SUB_ID );
+ throw new EMissingSelfTestException(PROP_OCSP_SUB_ID);
}
- } catch( EBaseException e ) {
- mSelfTestSubsystem.log( mSelfTestSubsystem.getSelfTestLogger(),
+ } catch (EBaseException e) {
+ mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
CMS.getLogMessage(
- "SELFTESTS_MISSING_NAME",
- getSelfTestName(),
- mPrefix
- + "."
- + PROP_OCSP_SUB_ID ) );
+ "SELFTESTS_MISSING_NAME",
+ getSelfTestName(),
+ mPrefix
+ + "."
+ + PROP_OCSP_SUB_ID));
- throw new EMissingSelfTestException( mPrefix,
+ throw new EMissingSelfTestException(mPrefix,
PROP_OCSP_SUB_ID,
- null );
+ null);
}
// retrieve optional parameter(s)
@@ -144,162 +132,149 @@ extends ASelfTest
return;
}
-
/**
* Notifies this subsystem if it is in execution mode.
* <P>
- *
+ *
* @exception ESelfTestException failed to start
*/
public void startupSelfTest()
- throws ESelfTestException
- {
+ throws ESelfTestException {
return;
}
-
/**
- * Stops this subsystem. The subsystem may call shutdownSelfTest
- * anytime after initialization.
+ * Stops this subsystem. The subsystem may call shutdownSelfTest anytime
+ * after initialization.
* <P>
*/
- public void shutdownSelfTest()
- {
+ public void shutdownSelfTest() {
return;
}
-
/**
- * Returns the name associated with this self test. This method may
- * return null if the self test has not been intialized.
+ * Returns the name associated with this self test. This method may return
+ * null if the self test has not been intialized.
* <P>
- *
+ *
* @return instanceName of this self test
*/
- public String getSelfTestName()
- {
+ public String getSelfTestName() {
return super.getSelfTestName();
}
-
/**
- * Returns the root configuration storage (self test parameters)
- * associated with this subsystem.
+ * Returns the root configuration storage (self test parameters) associated
+ * with this subsystem.
* <P>
- *
+ *
* @return configuration store (self test parameters) of this subsystem
*/
- public IConfigStore getSelfTestConfigStore()
- {
+ public IConfigStore getSelfTestConfigStore() {
return super.getSelfTestConfigStore();
}
-
/**
- * Retrieves description associated with an individual self test.
- * This method may return null.
+ * Retrieves description associated with an individual self test. This
+ * method may return null.
* <P>
- *
+ *
* @param locale locale of the client that requests the description
* @return description of self test
*/
- public String getSelfTestDescription( Locale locale )
- {
- return CMS.getUserMessage( locale,
- "CMS_SELFTESTS_OCSP_PRESENCE_DESCRIPTION" );
+ public String getSelfTestDescription(Locale locale) {
+ return CMS.getUserMessage(locale,
+ "CMS_SELFTESTS_OCSP_PRESENCE_DESCRIPTION");
}
-
/**
* Execute an individual self test.
* <P>
- *
+ *
* @param logger specifies logging subsystem
* @exception ESelfTestException self test exception
*/
- public void runSelfTest( ILogEventListener logger )
- throws ESelfTestException
- {
+ public void runSelfTest(ILogEventListener logger)
+ throws ESelfTestException {
String logMessage = null;
IOCSPAuthority ocsp = null;
ISigningUnit ocspSigningUnit = null;
X509CertImpl ocspCert = null;
X509Key ocspPubKey = null;
- ocsp = ( IOCSPAuthority ) CMS.getSubsystem( mOcspSubId );
+ ocsp = (IOCSPAuthority) CMS.getSubsystem(mOcspSubId);
- if( ocsp == null ) {
+ if (ocsp == null) {
// log that the OCSP is not installed
- logMessage = CMS.getLogMessage( "SELFTESTS_OCSP_IS_NOT_PRESENT",
- getSelfTestName() );
+ logMessage = CMS.getLogMessage("SELFTESTS_OCSP_IS_NOT_PRESENT",
+ getSelfTestName());
- mSelfTestSubsystem.log( logger,
- logMessage );
+ mSelfTestSubsystem.log(logger,
+ logMessage);
- throw new ESelfTestException( logMessage );
+ throw new ESelfTestException(logMessage);
} else {
// Retrieve the OCSP signing unit
ocspSigningUnit = ocsp.getSigningUnit();
- if( ocspSigningUnit == null ) {
+ if (ocspSigningUnit == null) {
// log that the OCSP is not yet initialized
- logMessage = CMS.getLogMessage(
+ logMessage = CMS.getLogMessage(
"SELFTESTS_OCSP_IS_NOT_INITIALIZED",
- getSelfTestName() );
-
- mSelfTestSubsystem.log( logger,
- logMessage );
-
- throw new ESelfTestException( logMessage );
+ getSelfTestName());
+
+ mSelfTestSubsystem.log(logger,
+ logMessage);
+
+ throw new ESelfTestException(logMessage);
}
// Retrieve the OCSP certificate
ocspCert = ocspSigningUnit.getCertImpl();
- if( ocspCert == null ) {
+ if (ocspCert == null) {
// log that the OCSP is not yet initialized
- logMessage = CMS.getLogMessage(
+ logMessage = CMS.getLogMessage(
"SELFTESTS_OCSP_IS_NOT_INITIALIZED",
- getSelfTestName() );
-
- mSelfTestSubsystem.log( logger,
- logMessage );
-
- throw new ESelfTestException( logMessage );
+ getSelfTestName());
+
+ mSelfTestSubsystem.log(logger,
+ logMessage);
+
+ throw new ESelfTestException(logMessage);
}
// Retrieve the OCSP certificate public key
try {
- ocspPubKey = ( X509Key )
- ocspCert.get( X509CertImpl.PUBLIC_KEY );
+ ocspPubKey = (X509Key)
+ ocspCert.get(X509CertImpl.PUBLIC_KEY);
- if( ocspPubKey == null ) {
+ if (ocspPubKey == null) {
// log that something is seriously wrong with the OCSP
- logMessage = CMS.getLogMessage( "SELFTESTS_OCSP_IS_CORRUPT",
- getSelfTestName() );
+ logMessage = CMS.getLogMessage("SELFTESTS_OCSP_IS_CORRUPT",
+ getSelfTestName());
- mSelfTestSubsystem.log( logger,
- logMessage );
+ mSelfTestSubsystem.log(logger,
+ logMessage);
- throw new ESelfTestException( logMessage );
+ throw new ESelfTestException(logMessage);
}
- } catch( CertificateParsingException e ) {
+ } catch (CertificateParsingException e) {
// log that something is seriously wrong with the OCSP
- mSelfTestSubsystem.log( logger,
- e.toString() );
+ mSelfTestSubsystem.log(logger,
+ e.toString());
- throw new ESelfTestException( e.toString() );
+ throw new ESelfTestException(e.toString());
}
// log that the OCSP is present
- logMessage = CMS.getLogMessage( "SELFTESTS_OCSP_IS_PRESENT",
- getSelfTestName() );
+ logMessage = CMS.getLogMessage("SELFTESTS_OCSP_IS_PRESENT",
+ getSelfTestName());
- mSelfTestSubsystem.log( logger,
- logMessage );
+ mSelfTestSubsystem.log(logger,
+ logMessage);
}
return;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/selftests/ocsp/OCSPValidity.java b/pki/base/common/src/com/netscape/cms/selftests/ocsp/OCSPValidity.java
index e6516b2a..e1ff529b 100644
--- a/pki/base/common/src/com/netscape/cms/selftests/ocsp/OCSPValidity.java
+++ b/pki/base/common/src/com/netscape/cms/selftests/ocsp/OCSPValidity.java
@@ -20,8 +20,6 @@
package com.netscape.cms.selftests.ocsp;
-
-
///////////////////////
// import statements //
///////////////////////
@@ -45,14 +43,12 @@ import com.netscape.certsrv.selftests.ESelfTestException;
import com.netscape.certsrv.selftests.ISelfTestSubsystem;
import com.netscape.cms.selftests.ASelfTest;
-
-
//////////////////////
// class definition //
//////////////////////
/**
- * This class implements a self test to check the validity of the OCSP.
+ * This class implements a self test to check the validity of the OCSP.
* <P>
*
* @author mharmsen
@@ -60,83 +56,75 @@ import com.netscape.cms.selftests.ASelfTest;
* @version $Revision$, $Date$
*/
public class OCSPValidity
-extends ASelfTest
-{
- ////////////////////////
+ extends ASelfTest {
+ // //////////////////////
// default parameters //
- ////////////////////////
-
-
+ // //////////////////////
- /////////////////////////////
+ // ///////////////////////////
// OCSPValidity parameters //
- /////////////////////////////
+ // ///////////////////////////
// parameter information
public static final String PROP_OCSP_SUB_ID = "OcspSubId";
- private String mOcspSubId = null;
+ private String mOcspSubId = null;
-
-
- /////////////////////
+ // ///////////////////
// default methods //
- /////////////////////
-
+ // ///////////////////
-
- //////////////////////////
+ // ////////////////////////
// OCSPValidity methods //
- //////////////////////////
+ // ////////////////////////
/**
- * Initializes this subsystem with the configuration store
- * associated with this instance name.
+ * Initializes this subsystem with the configuration store associated with
+ * this instance name.
* <P>
- *
+ *
* @param subsystem the associated subsystem
- * @param instanceName the name of this self test instance
+ * @param instanceName the name of this self test instance
* @param parameters configuration store (self test parameters)
* @exception EDuplicateSelfTestException subsystem has duplicate name/value
* @exception EInvalidSelfTestException subsystem has invalid name/value
* @exception EMissingSelfTestException subsystem has missing name/value
*/
- public void initSelfTest( ISelfTestSubsystem subsystem,
+ public void initSelfTest(ISelfTestSubsystem subsystem,
String instanceName,
- IConfigStore parameters )
- throws EDuplicateSelfTestException,
- EInvalidSelfTestException,
- EMissingSelfTestException
- {
- super.initSelfTest( subsystem, instanceName, parameters );
+ IConfigStore parameters)
+ throws EDuplicateSelfTestException,
+ EInvalidSelfTestException,
+ EMissingSelfTestException {
+ super.initSelfTest(subsystem, instanceName, parameters);
// retrieve mandatory parameter(s)
try {
- mOcspSubId = mConfig.getString( PROP_OCSP_SUB_ID );
- if( mOcspSubId != null ) {
+ mOcspSubId = mConfig.getString(PROP_OCSP_SUB_ID);
+ if (mOcspSubId != null) {
mOcspSubId = mOcspSubId.trim();
} else {
- mSelfTestSubsystem.log( mSelfTestSubsystem.getSelfTestLogger(),
+ mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
CMS.getLogMessage(
- "SELFTESTS_MISSING_VALUES",
- getSelfTestName(),
- mPrefix
- + "."
- + PROP_OCSP_SUB_ID ) );
+ "SELFTESTS_MISSING_VALUES",
+ getSelfTestName(),
+ mPrefix
+ + "."
+ + PROP_OCSP_SUB_ID));
- throw new EMissingSelfTestException( PROP_OCSP_SUB_ID );
+ throw new EMissingSelfTestException(PROP_OCSP_SUB_ID);
}
- } catch( EBaseException e ) {
- mSelfTestSubsystem.log( mSelfTestSubsystem.getSelfTestLogger(),
+ } catch (EBaseException e) {
+ mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
CMS.getLogMessage(
- "SELFTESTS_MISSING_NAME",
- getSelfTestName(),
- mPrefix
- + "."
- + PROP_OCSP_SUB_ID ) );
+ "SELFTESTS_MISSING_NAME",
+ getSelfTestName(),
+ mPrefix
+ + "."
+ + PROP_OCSP_SUB_ID));
- throw new EMissingSelfTestException( mPrefix,
+ throw new EMissingSelfTestException(mPrefix,
PROP_OCSP_SUB_ID,
- null );
+ null);
}
// retrieve optional parameter(s)
@@ -144,162 +132,149 @@ extends ASelfTest
return;
}
-
/**
* Notifies this subsystem if it is in execution mode.
* <P>
- *
+ *
* @exception ESelfTestException failed to start
*/
public void startupSelfTest()
- throws ESelfTestException
- {
+ throws ESelfTestException {
return;
}
-
/**
- * Stops this subsystem. The subsystem may call shutdownSelfTest
- * anytime after initialization.
+ * Stops this subsystem. The subsystem may call shutdownSelfTest anytime
+ * after initialization.
* <P>
*/
- public void shutdownSelfTest()
- {
+ public void shutdownSelfTest() {
return;
}
-
/**
- * Returns the name associated with this self test. This method may
- * return null if the self test has not been intialized.
+ * Returns the name associated with this self test. This method may return
+ * null if the self test has not been intialized.
* <P>
- *
+ *
* @return instanceName of this self test
*/
- public String getSelfTestName()
- {
+ public String getSelfTestName() {
return super.getSelfTestName();
}
-
/**
- * Returns the root configuration storage (self test parameters)
- * associated with this subsystem.
+ * Returns the root configuration storage (self test parameters) associated
+ * with this subsystem.
* <P>
- *
+ *
* @return configuration store (self test parameters) of this subsystem
*/
- public IConfigStore getSelfTestConfigStore()
- {
+ public IConfigStore getSelfTestConfigStore() {
return super.getSelfTestConfigStore();
}
-
/**
- * Retrieves description associated with an individual self test.
- * This method may return null.
+ * Retrieves description associated with an individual self test. This
+ * method may return null.
* <P>
- *
+ *
* @param locale locale of the client that requests the description
* @return description of self test
*/
- public String getSelfTestDescription( Locale locale )
- {
- return CMS.getUserMessage( locale,
- "CMS_SELFTESTS_OCSP_VALIDITY_DESCRIPTION" );
+ public String getSelfTestDescription(Locale locale) {
+ return CMS.getUserMessage(locale,
+ "CMS_SELFTESTS_OCSP_VALIDITY_DESCRIPTION");
}
-
/**
* Execute an individual self test.
* <P>
- *
+ *
* @param logger specifies logging subsystem
* @exception ESelfTestException self test exception
*/
- public void runSelfTest( ILogEventListener logger )
- throws ESelfTestException
- {
+ public void runSelfTest(ILogEventListener logger)
+ throws ESelfTestException {
String logMessage = null;
IOCSPAuthority ocsp = null;
ISigningUnit ocspSigningUnit = null;
X509CertImpl ocspCert = null;
- ocsp = ( IOCSPAuthority ) CMS.getSubsystem( mOcspSubId );
+ ocsp = (IOCSPAuthority) CMS.getSubsystem(mOcspSubId);
- if( ocsp == null ) {
+ if (ocsp == null) {
// log that the OCSP is not installed
- logMessage = CMS.getLogMessage( "SELFTESTS_OCSP_IS_NOT_PRESENT",
- getSelfTestName() );
+ logMessage = CMS.getLogMessage("SELFTESTS_OCSP_IS_NOT_PRESENT",
+ getSelfTestName());
- mSelfTestSubsystem.log( logger,
- logMessage );
+ mSelfTestSubsystem.log(logger,
+ logMessage);
- throw new ESelfTestException( logMessage );
+ throw new ESelfTestException(logMessage);
} else {
// Retrieve the OCSP signing unit
ocspSigningUnit = ocsp.getSigningUnit();
- if( ocspSigningUnit == null ) {
+ if (ocspSigningUnit == null) {
// log that the OCSP is not yet initialized
- logMessage = CMS.getLogMessage(
+ logMessage = CMS.getLogMessage(
"SELFTESTS_OCSP_IS_NOT_INITIALIZED",
- getSelfTestName() );
-
- mSelfTestSubsystem.log( logger,
- logMessage );
-
- throw new ESelfTestException( logMessage );
+ getSelfTestName());
+
+ mSelfTestSubsystem.log(logger,
+ logMessage);
+
+ throw new ESelfTestException(logMessage);
}
// Retrieve the OCSP certificate
ocspCert = ocspSigningUnit.getCertImpl();
- if( ocspCert == null ) {
+ if (ocspCert == null) {
// log that the OCSP is not yet initialized
- logMessage = CMS.getLogMessage(
+ logMessage = CMS.getLogMessage(
"SELFTESTS_OCSP_IS_NOT_INITIALIZED",
- getSelfTestName() );
+ getSelfTestName());
- mSelfTestSubsystem.log( logger,
- logMessage );
+ mSelfTestSubsystem.log(logger,
+ logMessage);
- throw new ESelfTestException( logMessage );
+ throw new ESelfTestException(logMessage);
}
// Retrieve the OCSP validity period
try {
ocspCert.checkValidity();
- } catch( CertificateNotYetValidException e ) {
+ } catch (CertificateNotYetValidException e) {
// log that the OCSP is not yet valid
logMessage = CMS.getLogMessage(
"SELFTESTS_OCSP_IS_NOT_YET_VALID",
- getSelfTestName() );
+ getSelfTestName());
- mSelfTestSubsystem.log( logger,
- logMessage );
+ mSelfTestSubsystem.log(logger,
+ logMessage);
- throw new ESelfTestException( logMessage );
- } catch( CertificateExpiredException e ) {
+ throw new ESelfTestException(logMessage);
+ } catch (CertificateExpiredException e) {
// log that the OCSP is expired
- logMessage = CMS.getLogMessage( "SELFTESTS_OCSP_IS_EXPIRED",
- getSelfTestName() );
+ logMessage = CMS.getLogMessage("SELFTESTS_OCSP_IS_EXPIRED",
+ getSelfTestName());
- mSelfTestSubsystem.log( logger,
- logMessage );
+ mSelfTestSubsystem.log(logger,
+ logMessage);
- throw new ESelfTestException( logMessage );
+ throw new ESelfTestException(logMessage);
}
// log that the OCSP is valid
- logMessage = CMS.getLogMessage( "SELFTESTS_OCSP_IS_VALID",
- getSelfTestName() );
+ logMessage = CMS.getLogMessage("SELFTESTS_OCSP_IS_VALID",
+ getSelfTestName());
- mSelfTestSubsystem.log( logger,
- logMessage );
+ mSelfTestSubsystem.log(logger,
+ logMessage);
}
return;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/selftests/ra/RAPresence.java b/pki/base/common/src/com/netscape/cms/selftests/ra/RAPresence.java
index 1a8b4c3e..0163cdf3 100644
--- a/pki/base/common/src/com/netscape/cms/selftests/ra/RAPresence.java
+++ b/pki/base/common/src/com/netscape/cms/selftests/ra/RAPresence.java
@@ -20,8 +20,6 @@
package com.netscape.cms.selftests.ra;
-
-
///////////////////////
// import statements //
///////////////////////
@@ -41,8 +39,6 @@ import com.netscape.certsrv.selftests.ESelfTestException;
import com.netscape.certsrv.selftests.ISelfTestSubsystem;
import com.netscape.cms.selftests.ASelfTest;
-
-
//////////////////////
// class definition //
//////////////////////
@@ -50,6 +46,7 @@ import com.netscape.cms.selftests.ASelfTest;
/**
* This class implements a self test to check for RA presence.
* <P>
+ *
* <PRE>
* NOTE: This self-test is for Registration Authorities prior to
* Netscape Certificate Management System 7.0. It does NOT
@@ -65,83 +62,75 @@ import com.netscape.cms.selftests.ASelfTest;
* @version $Revision$, $Date$
*/
public class RAPresence
-extends ASelfTest
-{
- ////////////////////////
+ extends ASelfTest {
+ // //////////////////////
// default parameters //
- ////////////////////////
+ // //////////////////////
-
-
- ///////////////////////////
+ // /////////////////////////
// RAPresence parameters //
- ///////////////////////////
+ // /////////////////////////
// parameter information
public static final String PROP_RA_SUB_ID = "RaSubId";
- private String mRaSubId = null;
-
-
+ private String mRaSubId = null;
- /////////////////////
+ // ///////////////////
// default methods //
- /////////////////////
+ // ///////////////////
-
-
- ////////////////////////
+ // //////////////////////
// RAPresence methods //
- ////////////////////////
+ // //////////////////////
/**
- * Initializes this subsystem with the configuration store
- * associated with this instance name.
+ * Initializes this subsystem with the configuration store associated with
+ * this instance name.
* <P>
- *
+ *
* @param subsystem the associated subsystem
- * @param instanceName the name of this self test instance
+ * @param instanceName the name of this self test instance
* @param parameters configuration store (self test parameters)
* @exception EDuplicateSelfTestException subsystem has duplicate name/value
* @exception EInvalidSelfTestException subsystem has invalid name/value
* @exception EMissingSelfTestException subsystem has missing name/value
*/
- public void initSelfTest( ISelfTestSubsystem subsystem,
+ public void initSelfTest(ISelfTestSubsystem subsystem,
String instanceName,
- IConfigStore parameters )
- throws EDuplicateSelfTestException,
- EInvalidSelfTestException,
- EMissingSelfTestException
- {
- super.initSelfTest( subsystem, instanceName, parameters );
+ IConfigStore parameters)
+ throws EDuplicateSelfTestException,
+ EInvalidSelfTestException,
+ EMissingSelfTestException {
+ super.initSelfTest(subsystem, instanceName, parameters);
// retrieve mandatory parameter(s)
try {
- mRaSubId = mConfig.getString( PROP_RA_SUB_ID );
- if( mRaSubId != null ) {
+ mRaSubId = mConfig.getString(PROP_RA_SUB_ID);
+ if (mRaSubId != null) {
mRaSubId = mRaSubId.trim();
} else {
- mSelfTestSubsystem.log( mSelfTestSubsystem.getSelfTestLogger(),
+ mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
CMS.getLogMessage(
- "SELFTESTS_MISSING_VALUES",
- getSelfTestName(),
- mPrefix
- + "."
- + PROP_RA_SUB_ID ) );
+ "SELFTESTS_MISSING_VALUES",
+ getSelfTestName(),
+ mPrefix
+ + "."
+ + PROP_RA_SUB_ID));
- throw new EMissingSelfTestException( PROP_RA_SUB_ID );
+ throw new EMissingSelfTestException(PROP_RA_SUB_ID);
}
- } catch( EBaseException e ) {
- mSelfTestSubsystem.log( mSelfTestSubsystem.getSelfTestLogger(),
+ } catch (EBaseException e) {
+ mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
CMS.getLogMessage(
- "SELFTESTS_MISSING_NAME",
- getSelfTestName(),
- mPrefix
- + "."
- + PROP_RA_SUB_ID ) );
+ "SELFTESTS_MISSING_NAME",
+ getSelfTestName(),
+ mPrefix
+ + "."
+ + PROP_RA_SUB_ID));
- throw new EMissingSelfTestException( mPrefix,
+ throw new EMissingSelfTestException(mPrefix,
PROP_RA_SUB_ID,
- null );
+ null);
}
// retrieve optional parameter(s)
@@ -149,137 +138,124 @@ extends ASelfTest
return;
}
-
/**
* Notifies this subsystem if it is in execution mode.
* <P>
- *
+ *
* @exception ESelfTestException failed to start
*/
public void startupSelfTest()
- throws ESelfTestException
- {
+ throws ESelfTestException {
return;
}
-
/**
- * Stops this subsystem. The subsystem may call shutdownSelfTest
- * anytime after initialization.
+ * Stops this subsystem. The subsystem may call shutdownSelfTest anytime
+ * after initialization.
* <P>
*/
- public void shutdownSelfTest()
- {
+ public void shutdownSelfTest() {
return;
}
-
/**
- * Returns the name associated with this self test. This method may
- * return null if the self test has not been intialized.
+ * Returns the name associated with this self test. This method may return
+ * null if the self test has not been intialized.
* <P>
- *
+ *
* @return instanceName of this self test
*/
- public String getSelfTestName()
- {
+ public String getSelfTestName() {
return super.getSelfTestName();
}
-
/**
- * Returns the root configuration storage (self test parameters)
- * associated with this subsystem.
+ * Returns the root configuration storage (self test parameters) associated
+ * with this subsystem.
* <P>
- *
+ *
* @return configuration store (self test parameters) of this subsystem
*/
- public IConfigStore getSelfTestConfigStore()
- {
+ public IConfigStore getSelfTestConfigStore() {
return super.getSelfTestConfigStore();
}
-
/**
- * Retrieves description associated with an individual self test.
- * This method may return null.
+ * Retrieves description associated with an individual self test. This
+ * method may return null.
* <P>
- *
+ *
* @param locale locale of the client that requests the description
* @return description of self test
*/
- public String getSelfTestDescription( Locale locale )
- {
- return CMS.getUserMessage( locale,
- "CMS_SELFTESTS_RA_PRESENCE_DESCRIPTION" );
+ public String getSelfTestDescription(Locale locale) {
+ return CMS.getUserMessage(locale,
+ "CMS_SELFTESTS_RA_PRESENCE_DESCRIPTION");
}
-
/**
* Execute an individual self test.
* <P>
- *
+ *
* @param logger specifies logging subsystem
* @exception ESelfTestException self test exception
*/
- public void runSelfTest( ILogEventListener logger )
- throws ESelfTestException
- {
+ public void runSelfTest(ILogEventListener logger)
+ throws ESelfTestException {
String logMessage = null;
IRegistrationAuthority ra = null;
org.mozilla.jss.crypto.X509Certificate raCert = null;
PublicKey raPubKey = null;
- ra = ( IRegistrationAuthority ) CMS.getSubsystem( mRaSubId );
+ ra = (IRegistrationAuthority) CMS.getSubsystem(mRaSubId);
- if( ra == null ) {
+ if (ra == null) {
// log that the RA is not installed
- logMessage = CMS.getLogMessage( "SELFTESTS_RA_IS_NOT_PRESENT",
- getSelfTestName() );
+ logMessage = CMS.getLogMessage("SELFTESTS_RA_IS_NOT_PRESENT",
+ getSelfTestName());
- mSelfTestSubsystem.log( logger,
- logMessage );
+ mSelfTestSubsystem.log(logger,
+ logMessage);
- throw new ESelfTestException( logMessage );
+ throw new ESelfTestException(logMessage);
} else {
// Retrieve the RA certificate
raCert = ra.getRACert();
- if( raCert == null ) {
+ if (raCert == null) {
// log that the RA is not yet initialized
- logMessage = CMS.getLogMessage(
+ logMessage = CMS.getLogMessage(
"SELFTESTS_RA_IS_NOT_INITIALIZED",
- getSelfTestName() );
+ getSelfTestName());
- mSelfTestSubsystem.log( logger,
- logMessage );
+ mSelfTestSubsystem.log(logger,
+ logMessage);
- throw new ESelfTestException( logMessage );
+ throw new ESelfTestException(logMessage);
}
// Retrieve the RA certificate public key
- raPubKey = ( PublicKey ) raCert.getPublicKey();
+ raPubKey = (PublicKey) raCert.getPublicKey();
- if( raPubKey == null ) {
+ if (raPubKey == null) {
// log that something is seriously wrong with the RA
- logMessage = CMS.getLogMessage( "SELFTESTS_RA_IS_CORRUPT",
- getSelfTestName() );
+ logMessage = CMS.getLogMessage("SELFTESTS_RA_IS_CORRUPT",
+ getSelfTestName());
- mSelfTestSubsystem.log( logger,
- logMessage );
+ mSelfTestSubsystem.log(logger,
+ logMessage);
- throw new ESelfTestException( logMessage );
+ throw new ESelfTestException(logMessage);
}
// log that the RA is present
- logMessage = CMS.getLogMessage( "SELFTESTS_RA_IS_PRESENT",
- getSelfTestName() );
+ logMessage = CMS.getLogMessage("SELFTESTS_RA_IS_PRESENT",
+ getSelfTestName());
- mSelfTestSubsystem.log( logger,
- logMessage );
+ mSelfTestSubsystem.log(logger,
+ logMessage);
}
return;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/selftests/tks/TKSKnownSessionKey.java b/pki/base/common/src/com/netscape/cms/selftests/tks/TKSKnownSessionKey.java
index ba0ae3cb..e01d68b8 100644
--- a/pki/base/common/src/com/netscape/cms/selftests/tks/TKSKnownSessionKey.java
+++ b/pki/base/common/src/com/netscape/cms/selftests/tks/TKSKnownSessionKey.java
@@ -20,8 +20,6 @@
package com.netscape.cms.selftests.tks;
-
-
///////////////////////
// import statements //
///////////////////////
@@ -42,8 +40,6 @@ import com.netscape.certsrv.selftests.ISelfTestSubsystem;
import com.netscape.cms.selftests.ASelfTest;
import com.netscape.symkey.SessionKey;
-
-
//////////////////////
// class definition //
//////////////////////
@@ -58,46 +54,43 @@ import com.netscape.symkey.SessionKey;
* @version $Revision$, $Date$
*/
public class TKSKnownSessionKey
-extends ASelfTest
-{
+ extends ASelfTest {
// parameter information
public static final String PROP_TKS_SUB_ID = "TksSubId";
- private String mTksSubId = null;
- private String mToken = null;
- private String mUseSoftToken = null;
- private String mKeyName = null;
- private byte[] mKeyInfo = null;
+ private String mTksSubId = null;
+ private String mToken = null;
+ private String mUseSoftToken = null;
+ private String mKeyName = null;
+ private byte[] mKeyInfo = null;
private byte[] mCardChallenge = null;
private byte[] mHostChallenge = null;
- private byte[] mCUID = null;
- private byte[] mMacKey = null;
- private byte[] mSessionKey = null;
-
+ private byte[] mCUID = null;
+ private byte[] mMacKey = null;
+ private byte[] mSessionKey = null;
/**
- * Initializes this subsystem with the configuration store
- * associated with this instance name.
+ * Initializes this subsystem with the configuration store associated with
+ * this instance name.
* <P>
- *
+ *
* @param subsystem the associated subsystem
- * @param instanceName the name of this self test instance
+ * @param instanceName the name of this self test instance
* @param parameters configuration store (self test parameters)
* @exception EDuplicateSelfTestException subsystem has duplicate name/value
* @exception EInvalidSelfTestException subsystem has invalid name/value
* @exception EMissingSelfTestException subsystem has missing name/value
*/
- public void initSelfTest (ISelfTestSubsystem subsystem,
+ public void initSelfTest(ISelfTestSubsystem subsystem,
String instanceName,
IConfigStore parameters)
- throws EDuplicateSelfTestException,
- EInvalidSelfTestException,
- EMissingSelfTestException
- {
+ throws EDuplicateSelfTestException,
+ EInvalidSelfTestException,
+ EMissingSelfTestException {
ISubsystem tks = null;
IConfigStore tksConfig = null;
String logMessage = null;
- super.initSelfTest( subsystem, instanceName, parameters );
+ super.initSelfTest(subsystem, instanceName, parameters);
mTksSubId = getConfigString(PROP_TKS_SUB_ID);
mToken = getConfigString("token");
@@ -128,34 +121,34 @@ extends ASelfTest
if (defKeySetMacKey == null) {
CMS.debug("TKSKnownSessionKey: invalid mac key");
CMS.debug("TKSKnownSessionKey self test FAILED");
- mSelfTestSubsystem.log (mSelfTestSubsystem.getSelfTestLogger(),
+ mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
CMS.getLogMessage("SELFTESTS_INVALID_VALUES",
- getSelfTestName(), mPrefix + "." + "macKey"));
- throw new EInvalidSelfTestException (mPrefix, "macKey", null);
+ getSelfTestName(), mPrefix + "." + "macKey"));
+ throw new EInvalidSelfTestException(mPrefix, "macKey", null);
}
-
+
try {
mSessionKey = getConfigByteArray("sessionKey", 16);
} catch (EMissingSelfTestException e) {
if (mSessionKey == null) {
- mSessionKey = SessionKey.ComputeSessionKey (mToken, mKeyName,
+ mSessionKey = SessionKey.ComputeSessionKey(mToken, mKeyName,
mCardChallenge, mHostChallenge,
mKeyInfo, mCUID, mMacKey, mUseSoftToken, null, null);
if (mSessionKey == null || mSessionKey.length != 16) {
- mSelfTestSubsystem.log (mSelfTestSubsystem.getSelfTestLogger(),
+ mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
CMS.getLogMessage("SELFTESTS_MISSING_VALUES",
- getSelfTestName(), mPrefix + ".sessionKey"));
- throw new EMissingSelfTestException ("sessionKey");
+ getSelfTestName(), mPrefix + ".sessionKey"));
+ throw new EMissingSelfTestException("sessionKey");
}
String sessionKey = SpecialEncode(mSessionKey);
mConfig.putString("sessionKey", sessionKey);
try {
CMS.getConfigStore().commit(true);
} catch (EBaseException be) {
- mSelfTestSubsystem.log (mSelfTestSubsystem.getSelfTestLogger(),
+ mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
CMS.getLogMessage("SELFTESTS_MISSING_VALUES",
- getSelfTestName(), mPrefix + ".sessionKey"));
- throw new EMissingSelfTestException ("sessionKey");
+ getSelfTestName(), mPrefix + ".sessionKey"));
+ throw new EMissingSelfTestException("sessionKey");
}
}
}
@@ -163,9 +156,7 @@ extends ASelfTest
return;
}
-
- private String SpecialEncode (byte data[])
- {
+ private String SpecialEncode(byte data[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < data.length; i++) {
@@ -179,9 +170,7 @@ extends ASelfTest
return sb.toString();
}
-
- private String getConfigString (String name) throws EMissingSelfTestException
- {
+ private String getConfigString(String name) throws EMissingSelfTestException {
String value = null;
try {
@@ -189,137 +178,124 @@ extends ASelfTest
if (value != null) {
value = value.trim();
} else {
- mSelfTestSubsystem.log (mSelfTestSubsystem.getSelfTestLogger(),
+ mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
CMS.getLogMessage("SELFTESTS_MISSING_VALUES",
- getSelfTestName(), mPrefix + "." + name));
- throw new EMissingSelfTestException (name);
+ getSelfTestName(), mPrefix + "." + name));
+ throw new EMissingSelfTestException(name);
}
} catch (EBaseException e) {
- mSelfTestSubsystem.log (mSelfTestSubsystem.getSelfTestLogger(),
+ mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
CMS.getLogMessage("SELFTESTS_MISSING_NAME",
- getSelfTestName(), mPrefix + "." + name));
- throw new EMissingSelfTestException (mPrefix, name, null);
+ getSelfTestName(), mPrefix + "." + name));
+ throw new EMissingSelfTestException(mPrefix, name, null);
}
return value;
}
-
- private byte[] getConfigByteArray (String name, int size) throws EMissingSelfTestException,
- EInvalidSelfTestException
- {
+ private byte[] getConfigByteArray(String name, int size) throws EMissingSelfTestException,
+ EInvalidSelfTestException {
String stringValue = getConfigString(name);
byte byteValue[] = com.netscape.cmsutil.util.Utils.SpecialDecode(stringValue);
if (byteValue == null) {
- mSelfTestSubsystem.log (mSelfTestSubsystem.getSelfTestLogger(),
+ mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
CMS.getLogMessage("SELFTESTS_MISSING_NAME",
- getSelfTestName(), mPrefix + "." + name));
- throw new EMissingSelfTestException (name);
+ getSelfTestName(), mPrefix + "." + name));
+ throw new EMissingSelfTestException(name);
}
if (byteValue.length != size) {
- mSelfTestSubsystem.log (mSelfTestSubsystem.getSelfTestLogger(),
+ mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
CMS.getLogMessage("SELFTESTS_INVALID_VALUES",
- getSelfTestName(), mPrefix + "." + name));
- throw new EInvalidSelfTestException (mPrefix, name, stringValue);
+ getSelfTestName(), mPrefix + "." + name));
+ throw new EInvalidSelfTestException(mPrefix, name, stringValue);
}
return byteValue;
}
-
/**
* Notifies this subsystem if it is in execution mode.
* <P>
- *
+ *
* @exception ESelfTestException failed to start
*/
public void startupSelfTest()
- throws ESelfTestException
- {
+ throws ESelfTestException {
return;
}
-
/**
- * Stops this subsystem. The subsystem may call shutdownSelfTest
- * anytime after initialization.
+ * Stops this subsystem. The subsystem may call shutdownSelfTest anytime
+ * after initialization.
* <P>
*/
- public void shutdownSelfTest()
- {
+ public void shutdownSelfTest() {
return;
}
-
/**
- * Returns the name associated with this self test. This method may
- * return null if the self test has not been intialized.
+ * Returns the name associated with this self test. This method may return
+ * null if the self test has not been intialized.
* <P>
- *
+ *
* @return instanceName of this self test
*/
- public String getSelfTestName()
- {
+ public String getSelfTestName() {
return super.getSelfTestName();
}
-
/**
- * Returns the root configuration storage (self test parameters)
- * associated with this subsystem.
+ * Returns the root configuration storage (self test parameters) associated
+ * with this subsystem.
* <P>
- *
+ *
* @return configuration store (self test parameters) of this subsystem
*/
- public IConfigStore getSelfTestConfigStore()
- {
+ public IConfigStore getSelfTestConfigStore() {
return super.getSelfTestConfigStore();
}
-
/**
- * Retrieves description associated with an individual self test.
- * This method may return null.
+ * Retrieves description associated with an individual self test. This
+ * method may return null.
* <P>
- *
+ *
* @param locale locale of the client that requests the description
* @return description of self test
*/
- public String getSelfTestDescription( Locale locale )
- {
- return CMS.getUserMessage (locale, "CMS_SELFTESTS_TKS_PRESENCE_DESCRIPTION");
+ public String getSelfTestDescription(Locale locale) {
+ return CMS.getUserMessage(locale, "CMS_SELFTESTS_TKS_PRESENCE_DESCRIPTION");
}
-
/**
* Execute an individual self test.
* <P>
- *
+ *
* @param logger specifies logging subsystem
* @exception ESelfTestException self test exception
*/
- public void runSelfTest (ILogEventListener logger)
- throws ESelfTestException
- {
+ public void runSelfTest(ILogEventListener logger)
+ throws ESelfTestException {
String logMessage = null;
String keySet = "defKeySet";
- byte[] sessionKey = SessionKey.ComputeSessionKey (mToken, mKeyName,
+ byte[] sessionKey = SessionKey.ComputeSessionKey(mToken, mKeyName,
mCardChallenge, mHostChallenge,
mKeyInfo, mCUID, mMacKey, mUseSoftToken, keySet, null);
// Now we just see if we can successfully generate a session key.
- // For FIPS compliance, the routine now returns a wrapped key, which can't be extracted and compared.
+ // For FIPS compliance, the routine now returns a wrapped key, which
+ // can't be extracted and compared.
if (sessionKey == null) {
CMS.debug("TKSKnownSessionKey: generated no session key");
CMS.debug("TKSKnownSessionKey self test FAILED");
- logMessage = CMS.getLogMessage ("SELFTESTS_TKS_FAILED", getSelfTestName(), getSelfTestName());
- mSelfTestSubsystem.log (logger, logMessage);
- throw new ESelfTestException( logMessage );
- } else {
- logMessage = CMS.getLogMessage ("SELFTESTS_TKS_SUCCEEDED", getSelfTestName(), getSelfTestName());
- mSelfTestSubsystem.log (logger, logMessage);
+ logMessage = CMS.getLogMessage("SELFTESTS_TKS_FAILED", getSelfTestName(), getSelfTestName());
+ mSelfTestSubsystem.log(logger, logMessage);
+ throw new ESelfTestException(logMessage);
+ } else {
+ logMessage = CMS.getLogMessage("SELFTESTS_TKS_SUCCEEDED", getSelfTestName(), getSelfTestName());
+ mSelfTestSubsystem.log(logger, logMessage);
CMS.debug("TKSKnownSessionKey self test SUCCEEDED");
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/admin/ACLAdminServlet.java b/pki/base/common/src/com/netscape/cms/servlet/admin/ACLAdminServlet.java
index 4737e2f7..b805cc96 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/admin/ACLAdminServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/admin/ACLAdminServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.admin;
-
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
@@ -45,10 +44,9 @@ import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.usrgrp.IUGSubsystem;
import com.netscape.certsrv.usrgrp.IUser;
-
/**
* Manage Access Control List configuration
- *
+ *
* @version $Revision$, $Date$
*/
public class ACLAdminServlet extends AdminServlet {
@@ -64,7 +62,7 @@ public class ACLAdminServlet extends AdminServlet {
private IAuthzManager mAuthzMgr = null;
private final static String LOGGING_SIGNED_AUDIT_CONFIG_ACL =
- "LOGGING_SIGNED_AUDIT_CONFIG_ACL_3";
+ "LOGGING_SIGNED_AUDIT_CONFIG_ACL_3";
/**
* Constructs servlet.
@@ -74,17 +72,18 @@ public class ACLAdminServlet extends AdminServlet {
mUG = (IUGSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_UG);
}
- /**
- * initialize the servlet.
+ /**
+ * initialize the servlet.
* <ul>
* <li>http.param OP_TYPE = OP_SEARCH,
* <li>http.param OP_SCOPE - the scope of the request operation:
- * <ul><LI>"impl" ACL implementations
- * <LI>"acls" ACL rules
- * <LI>"evaluatorTypes" ACL evaluators.
- * </ul>
+ * <ul>
+ * <LI>"impl" ACL implementations
+ * <LI>"acls" ACL rules
+ * <LI>"evaluatorTypes" ACL evaluators.
* </ul>
- *
+ * </ul>
+ *
* @param config servlet configuration, read from the web.xml file
*/
public void init(ServletConfig config) throws ServletException {
@@ -99,24 +98,24 @@ public class ACLAdminServlet extends AdminServlet {
return INFO;
}
- /**
+ /**
* Process the HTTP request.
- *
+ *
* @param req the object holding the request information
* @param resp the object holding the response information
*/
public void service(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
+ throws ServletException, IOException {
String scope = super.getParameter(req, Constants.OP_SCOPE);
String op = super.getParameter(req, Constants.OP_TYPE);
if (op == null) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_INVALID_PROTOCOL"));
- sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_PROTOCOL"),
- null, resp);
+ sendResponse(ERROR,
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_PROTOCOL"),
+ null, resp);
return;
}
@@ -126,8 +125,8 @@ public class ACLAdminServlet extends AdminServlet {
super.authenticate(req);
} catch (IOException e) {
log(ILogger.LL_SECURITY, CMS.getLogMessage("ADMIN_SRVLT_FAIL_AUTHS"));
- sendResponse(ERROR, CMS.getUserMessage(getLocale(req),"CMS_ADMIN_SRVLT_AUTHS_FAILED"),
- null, resp);
+ sendResponse(ERROR, CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHS_FAILED"),
+ null, resp);
return;
}
@@ -141,8 +140,8 @@ public class ACLAdminServlet extends AdminServlet {
} catch (Exception e) {
log(ILogger.LL_FAILURE, e.toString());
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_PERFORM_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_PERFORM_FAILED"),
+ null, resp);
return;
}
@@ -152,9 +151,9 @@ public class ACLAdminServlet extends AdminServlet {
if (op.equals(OpDef.OP_SEARCH)) {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
- sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ sendResponse(ERROR,
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_ACL)) {
@@ -171,8 +170,8 @@ public class ACLAdminServlet extends AdminServlet {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_ACL)) {
@@ -183,8 +182,8 @@ public class ACLAdminServlet extends AdminServlet {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_ACL)) {
@@ -195,8 +194,8 @@ public class ACLAdminServlet extends AdminServlet {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_ACL_IMPLS)) {
@@ -207,8 +206,8 @@ public class ACLAdminServlet extends AdminServlet {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_ACL_IMPLS)) {
@@ -218,38 +217,38 @@ public class ACLAdminServlet extends AdminServlet {
} else {
log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_INVALID_OP_SCOPE"));
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
+ null, resp);
return;
}
} catch (EBaseException e) {
log(ILogger.LL_FAILURE, e.toString());
sendResponse(ERROR, e.toString(getLocale(req)),
- null, resp);
+ null, resp);
return;
} catch (Exception e) {
log(ILogger.LL_FAILURE, e.toString());
log(ILogger.LL_DEBUG, "SRVLT_FAIL_PERFORM 2");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_PERFORM_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_PERFORM_FAILED"),
+ null, resp);
return;
}
log(ILogger.LL_DEBUG, "SRVLT_FAIL_PERFORM 3");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_PERFORM_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_PERFORM_FAILED"),
+ null, resp);
return;
}
/**
* list acls resources by name
*/
- private void listResources(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException, IOException,
+ private void listResources(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException, IOException,
EBaseException {
NameValuePairs params = new NameValuePairs();
@@ -260,7 +259,7 @@ public class ACLAdminServlet extends AdminServlet {
ACL acl = (ACL) res.nextElement();
String desc = acl.getDescription();
- if (desc == null)
+ if (desc == null)
params.add(acl.getName(), "");
else
params.add(acl.getName(), desc);
@@ -272,19 +271,19 @@ public class ACLAdminServlet extends AdminServlet {
/**
* get acls information for a resource
*/
- private void getResourceACL(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException, IOException,
+ private void getResourceACL(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException, IOException,
EBaseException {
NameValuePairs params = new NameValuePairs();
- //get resource id first
+ // get resource id first
String resourceId = super.getParameter(req, Constants.RS_ID);
if (resourceId == null) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID"));
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
@@ -295,7 +294,7 @@ public class ACLAdminServlet extends AdminServlet {
StringBuffer rights = new StringBuffer();
- if (rightsEnum.hasMoreElements()) {
+ if (rightsEnum.hasMoreElements()) {
while (rightsEnum.hasMoreElements()) {
if (rights.length() != 0) {
rights.append(",");
@@ -332,8 +331,8 @@ public class ACLAdminServlet extends AdminServlet {
} else {
log(ILogger.LL_FAILURE, CMS.getLogMessage("ACLS_SRVLT_RESOURCE_NOT_FOUND"));
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_ACL_RESOURCE_NOT_FOUND"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ACL_RESOURCE_NOT_FOUND"),
+ null, resp);
return;
}
}
@@ -341,19 +340,20 @@ public class ACLAdminServlet extends AdminServlet {
/**
* modify acls information for a resource
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ACL used when configuring
* Access Control List (ACL) information
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
* @exception EBaseException an error has occurred
*/
- private void updateResources(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException, IOException,
+ private void updateResources(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException, IOException,
EBaseException {
String auditMessage = null;
@@ -378,15 +378,15 @@ public class ACLAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
// get resource acls
String resourceACLs = super.getParameter(req, Constants.PR_ACI);
String rights = super.getParameter(req, Constants.PR_ACL_RIGHTS);
- String desc = super.getParameter(req, Constants.PR_ACL_DESC);
+ String desc = super.getParameter(req, Constants.PR_ACL_DESC);
try {
mAuthzMgr.updateACLs(resourceId, rights, resourceACLs, desc);
@@ -417,22 +417,22 @@ public class ACLAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_ACL_UPDATE_FAIL"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ACL_UPDATE_FAIL"),
+ null, resp);
return;
}
// } catch( EBaseException eAudit1 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_ACL,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_ACL,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit1;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit1;
} catch (IOException eAudit2) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -446,31 +446,31 @@ public class ACLAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit2;
// } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_ACL,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_ACL,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
}
}
-
+
/**
* list access evaluators by types and class paths
*/
- private void listACLsEvaluators(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException, IOException,
+ private void listACLsEvaluators(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException, IOException,
EBaseException {
NameValuePairs params = new NameValuePairs();
Enumeration<IAccessEvaluator> res = mAuthzMgr.aclEvaluatorElements();
while (res.hasMoreElements()) {
- IAccessEvaluator evaluator = res.nextElement();
+ IAccessEvaluator evaluator = res.nextElement();
// params.add(evaluator.getType(), evaluator.getDescription());
params.add(evaluator.getType(), evaluator.getClass().getName());
@@ -480,18 +480,18 @@ public class ACLAdminServlet extends AdminServlet {
}
private void listACLsEvaluatorTypes(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException, IOException,
+ HttpServletResponse resp) throws ServletException, IOException,
EBaseException {
NameValuePairs params = new NameValuePairs();
Enumeration<IAccessEvaluator> res = mAuthzMgr.aclEvaluatorElements();
while (res.hasMoreElements()) {
- IAccessEvaluator evaluator = res.nextElement();
+ IAccessEvaluator evaluator = res.nextElement();
String[] operators = evaluator.getSupportedOperators();
StringBuffer str = new StringBuffer();
for (int i = 0; i < operators.length; i++) {
- if (str.length() > 0)
+ if (str.length() > 0)
str.append(",");
str.append(operators[i]);
}
@@ -505,22 +505,23 @@ public class ACLAdminServlet extends AdminServlet {
/**
* add access evaluators
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ACL used when configuring
* Access Control List (ACL) information
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @param scope string used to obtain the contents of this ACL evaluator's
- * substore
+ * substore
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
* @exception EBaseException an error has occurred
*/
- private synchronized void addACLsEvaluator(HttpServletRequest req,
- HttpServletResponse resp, String scope)
- throws ServletException, IOException, EBaseException {
+ private synchronized void addACLsEvaluator(HttpServletRequest req,
+ HttpServletResponse resp, String scope)
+ throws ServletException, IOException, EBaseException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -543,26 +544,25 @@ public class ACLAdminServlet extends AdminServlet {
log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID"));
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
// is the evaluator type unique?
/*
- if (!mACLs.isTypeUnique(type)) {
- String infoMsg = "replacing existing type: "+ type;
- log(ILogger.LL_WARN, infoMsg);
- }
+ * if (!mACLs.isTypeUnique(type)) { String infoMsg =
+ * "replacing existing type: "+ type; log(ILogger.LL_WARN, infoMsg);
+ * }
*/
// get class
String classPath = super.getParameter(req, Constants.PR_ACL_CLASS);
IConfigStore destStore =
- mConfig.getSubStore(PROP_EVAL);
+ mConfig.getSubStore(PROP_EVAL);
IConfigStore mStore =
- destStore.getSubStore(ScopeDef.SC_ACL_IMPLS);
+ destStore.getSubStore(ScopeDef.SC_ACL_IMPLS);
// Does the class exist?
Class<?> newImpl = null;
@@ -584,17 +584,16 @@ public class ACLAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_ACL_CLASS_LOAD_FAIL"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ACL_CLASS_LOAD_FAIL"),
+ null, resp);
return;
}
// is the class an IAccessEvaluator?
try {
- if
- (Class.forName("com.netscape.certsrv.evaluators.IAccessEvaluator").isAssignableFrom(newImpl) == false) {
+ if (Class.forName("com.netscape.certsrv.evaluators.IAccessEvaluator").isAssignableFrom(newImpl) == false) {
String errMsg = "class not com.netscape.certsrv.evaluators.IAccessEvaluator" +
- classPath;
+ classPath;
log(ILogger.LL_FAILURE, errMsg);
@@ -608,13 +607,13 @@ public class ACLAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_ACL_ILL_CLASS"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ACL_ILL_CLASS"),
+ null, resp);
return;
}
} catch (Exception e) {
String errMsg = "class not com.netscape.certsrv.evaluators.IAccessEvaluator" +
- classPath;
+ classPath;
log(ILogger.LL_FAILURE, errMsg);
@@ -628,8 +627,8 @@ public class ACLAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_ACL_ILL_CLASS"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ACL_ILL_CLASS"),
+ null, resp);
return;
}
@@ -653,8 +652,8 @@ public class ACLAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_ACL_COMMIT_FAIL"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ACL_COMMIT_FAIL"),
+ null, resp);
return;
}
@@ -676,8 +675,8 @@ public class ACLAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_ACL_INST_CLASS_FAIL"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ACL_INST_CLASS_FAIL"),
+ null, resp);
return;
}
@@ -688,7 +687,7 @@ public class ACLAdminServlet extends AdminServlet {
mAuthzMgr.registerEvaluator(type, evaluator);
}
- //...
+ // ...
NameValuePairs params = new NameValuePairs();
// store a message in the signed audit log file
@@ -702,17 +701,17 @@ public class ACLAdminServlet extends AdminServlet {
sendResponse(SUCCESS, null, params, resp);
// } catch( EBaseException eAudit1 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_ACL,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_ACL,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit1;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit1;
} catch (IOException eAudit2) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -726,38 +725,39 @@ public class ACLAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit2;
// } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_ACL,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_ACL,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
}
}
/**
* remove access evaluators
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ACL used when configuring
* Access Control List (ACL) information
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @param scope string used to obtain the contents of this ACL evaluator's
- * substore
+ * substore
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
* @exception EBaseException an error has occurred
*/
- private synchronized void deleteACLsEvaluator(HttpServletRequest req,
- HttpServletResponse resp, String scope) throws ServletException,
+ private synchronized void deleteACLsEvaluator(HttpServletRequest req,
+ HttpServletResponse resp, String scope) throws ServletException,
IOException, EBaseException {
String auditMessage = null;
@@ -782,8 +782,8 @@ public class ACLAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
@@ -803,8 +803,8 @@ public class ACLAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_ACL_EVAL_NOT_FOUND"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ACL_EVAL_NOT_FOUND"),
+ null, resp);
return;
}
@@ -814,13 +814,13 @@ public class ACLAdminServlet extends AdminServlet {
try {
IConfigStore destStore =
- mConfig.getSubStore(PROP_EVAL);
+ mConfig.getSubStore(PROP_EVAL);
IConfigStore mStore =
- destStore.getSubStore(ScopeDef.SC_ACL_IMPLS);
+ destStore.getSubStore(ScopeDef.SC_ACL_IMPLS);
mStore.removeSubStore(id);
} catch (Exception eeee) {
- //CMS.debugStackTrace(eeee);
+ // CMS.debugStackTrace(eeee);
}
// commiting
try {
@@ -838,8 +838,8 @@ public class ACLAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_ACL_COMMIT_FAIL"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ACL_COMMIT_FAIL"),
+ null, resp);
return;
}
@@ -855,17 +855,17 @@ public class ACLAdminServlet extends AdminServlet {
sendResponse(SUCCESS, null, params, resp);
return;
// } catch( EBaseException eAudit1 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_ACL,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_ACL,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit1;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit1;
} catch (IOException eAudit2) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -879,50 +879,43 @@ public class ACLAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit2;
// } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_ACL,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_ACL,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
}
}
-
+
/**
* Searchs for certificate requests.
*/
-
+
/*
- private void getACLs(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException, IOException,
- EBaseException {
- NameValuePairs params = new NameValuePairs();
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- ObjectOutputStream oos = new ObjectOutputStream(bos);
- String names = getParameter(req, Constants.PT_NAMES);
- StringTokenizer st = new StringTokenizer(names, ",");
- while (st.hasMoreTokens()) {
- String target = st.nextToken();
- ACL acl = AccessManager.getInstance().getACL(target);
- oos.writeObject(acl);
- }
- // BASE64Encoder encoder = new BASE64Encoder();
- // params.add(Constants.PT_ACLS, encoder.encodeBuffer(bos.toByteArray()));
- params.add(Constants.PT_ACLS, CMS.BtoA(bos.toByteArray()));
- sendResponse(SUCCESS, null, params, resp);
- }
+ * private void getACLs(HttpServletRequest req, HttpServletResponse resp)
+ * throws ServletException, IOException, EBaseException { NameValuePairs
+ * params = new NameValuePairs(); ByteArrayOutputStream bos = new
+ * ByteArrayOutputStream(); ObjectOutputStream oos = new
+ * ObjectOutputStream(bos); String names = getParameter(req,
+ * Constants.PT_NAMES); StringTokenizer st = new StringTokenizer(names,
+ * ","); while (st.hasMoreTokens()) { String target = st.nextToken(); ACL
+ * acl = AccessManager.getInstance().getACL(target); oos.writeObject(acl); }
+ * // BASE64Encoder encoder = new BASE64Encoder(); //
+ * params.add(Constants.PT_ACLS, encoder.encodeBuffer(bos.toByteArray()));
+ * params.add(Constants.PT_ACLS, CMS.BtoA(bos.toByteArray()));
+ * sendResponse(SUCCESS, null, params, resp); }
*/
private void log(int level, String msg) {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_ACLS,
- level, "ACLAdminServlet: " + msg);
+ level, "ACLAdminServlet: " + msg);
}
-}
-
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/admin/AdminResources.java b/pki/base/common/src/com/netscape/cms/servlet/admin/AdminResources.java
index 2024e496..038355f0 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/admin/AdminResources.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/admin/AdminResources.java
@@ -17,13 +17,11 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.admin;
-
import java.util.ListResourceBundle;
-
/**
* A class represents a resource bundle for the remote admin.
- *
+ *
* @version $Revision$, $Date$
* @see java.util.ListResourceBundle
*/
@@ -37,8 +35,7 @@ public class AdminResources extends ListResourceBundle {
}
/**
- * Constants. The suffix represents the number of
- * possible parameters.
+ * Constants. The suffix represents the number of possible parameters.
*/
static final Object[][] contents = {};
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/admin/AdminServlet.java b/pki/base/common/src/com/netscape/cms/servlet/admin/AdminServlet.java
index 0f2a6ec7..c7bc1554 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/admin/AdminServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/admin/AdminServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.admin;
-
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
@@ -56,32 +55,27 @@ import com.netscape.certsrv.usrgrp.IUGSubsystem;
import com.netscape.certsrv.usrgrp.IUser;
import com.netscape.cms.servlet.base.UserInfo;
-
/**
- * A class represents an administration servlet that
- * is responsible to serve administrative
- * operation such as configuration parameter updates.
- *
- * Since each administration servlet needs to perform
- * authentication information parsing and response
- * formulation, it makes sense to encapsulate the
+ * A class represents an administration servlet that is responsible to serve
+ * administrative operation such as configuration parameter updates.
+ *
+ * Since each administration servlet needs to perform authentication information
+ * parsing and response formulation, it makes sense to encapsulate the
* commonalities into this class.
- *
- * By extending this serlvet, the subclass does not
- * need to re-implement the request parsing code
- * (i.e. authentication information parsing).
- *
- * If a subsystem needs to expose configuration
- * parameters management, it should create an
- * administration servlet (i.e. CAAdminServlet)
- * and register it to RemoteAdmin subsystem.
- *
+ *
+ * By extending this serlvet, the subclass does not need to re-implement the
+ * request parsing code (i.e. authentication information parsing).
+ *
+ * If a subsystem needs to expose configuration parameters management, it should
+ * create an administration servlet (i.e. CAAdminServlet) and register it to
+ * RemoteAdmin subsystem.
+ *
* <code>
* public class CAAdminServlet extends AdminServlet {
* ...
* }
* </code>
- *
+ *
* @version $Revision$, $Date$
*/
public class AdminServlet extends HttpServlet {
@@ -117,8 +111,8 @@ public class AdminServlet extends HttpServlet {
public final static String AUTHZ_SRC_TYPE = "sourceType";
public final static String AUTHZ_SRC_LDAP = "ldap";
public final static String AUTHZ_SRC_XML = "web.xml";
- public static final String CERT_ATTR =
- "javax.servlet.request.X509Certificate";
+ public static final String CERT_ATTR =
+ "javax.servlet.request.X509Certificate";
public final static String SIGNED_AUDIT_SCOPE = "Scope";
public final static String SIGNED_AUDIT_OPERATION = "Operation";
@@ -130,19 +124,19 @@ public class AdminServlet extends HttpServlet {
public final static String SIGNED_AUDIT_NAME_VALUE_PAIRS_DELIMITER = "+";
private final static String LOGGING_SIGNED_AUDIT_AUTH_FAIL =
- "LOGGING_SIGNED_AUDIT_AUTH_FAIL_4";
+ "LOGGING_SIGNED_AUDIT_AUTH_FAIL_4";
private final static String LOGGING_SIGNED_AUDIT_AUTH_SUCCESS =
- "LOGGING_SIGNED_AUDIT_AUTH_SUCCESS_3";
+ "LOGGING_SIGNED_AUDIT_AUTH_SUCCESS_3";
private final static String LOGGING_SIGNED_AUDIT_AUTHZ_FAIL =
- "LOGGING_SIGNED_AUDIT_AUTHZ_FAIL_4";
+ "LOGGING_SIGNED_AUDIT_AUTHZ_FAIL_4";
private final static String LOGGING_SIGNED_AUDIT_AUTHZ_SUCCESS =
- "LOGGING_SIGNED_AUDIT_AUTHZ_SUCCESS_4";
+ "LOGGING_SIGNED_AUDIT_AUTHZ_SUCCESS_4";
private final static String LOGGING_SIGNED_AUDIT_ROLE_ASSUME =
- "LOGGING_SIGNED_AUDIT_ROLE_ASSUME_3";
+ "LOGGING_SIGNED_AUDIT_ROLE_ASSUME_3";
private final static String CERTUSERDB =
- IAuthSubsystem.CERTUSERDB_AUTHMGR_ID;
+ IAuthSubsystem.CERTUSERDB_AUTHMGR_ID;
private final static String PASSWDUSERDB =
- IAuthSubsystem.PASSWDUSERDB_AUTHMGR_ID;
+ IAuthSubsystem.PASSWDUSERDB_AUTHMGR_ID;
/**
* Constructs generic administration servlet.
@@ -175,8 +169,8 @@ public class AdminServlet extends HttpServlet {
if (srcType.equalsIgnoreCase(AUTHZ_SRC_XML)) {
CMS.debug("AdminServlet: " + CMS.getLogMessage("ADMIN_SRVLT_AUTHZ_INITED", ""));
- // get authz mgr from xml file; if not specified, use
- // ldap by default
+ // get authz mgr from xml file; if not specified, use
+ // ldap by default
mAclMethod = getSCparam(sc, PROP_AUTHZ_MGR, AUTHZ_MGR_LDAP);
if (mAclMethod.equalsIgnoreCase(AUTHZ_MGR_BASIC)) {
@@ -185,7 +179,7 @@ public class AdminServlet extends HttpServlet {
if (aclInfo != null) {
try {
addACLInfo(aclInfo);
- //mAuthz.authzMgrAccessInit(mAclMethod, aclInfo);
+ // mAuthz.authzMgrAccessInit(mAclMethod, aclInfo);
} catch (EBaseException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_AUTHZ_MGR_INIT_FAIL"));
throw new ServletException("failed to init authz info from xml config file");
@@ -204,45 +198,44 @@ public class AdminServlet extends HttpServlet {
}
}
- public void outputHttpParameters(HttpServletRequest httpReq)
- {
+ public void outputHttpParameters(HttpServletRequest httpReq) {
CMS.debug("AdminServlet:service() uri = " + httpReq.getRequestURI());
Enumeration paramNames = httpReq.getParameterNames();
while (paramNames.hasMoreElements()) {
- String pn = (String)paramNames.nextElement();
+ String pn = (String) paramNames.nextElement();
// added this facility so that password can be hidden,
- // all sensitive parameters should be prefixed with
+ // all sensitive parameters should be prefixed with
// __ (double underscores); however, in the event that
// a security parameter slips through, we perform multiple
// additional checks to insure that it is NOT displayed
- if( pn.startsWith("__") ||
- pn.endsWith("password") ||
- pn.endsWith("passwd") ||
- pn.endsWith("pwd") ||
- pn.equalsIgnoreCase("admin_password_again") ||
- pn.equalsIgnoreCase("directoryManagerPwd") ||
- pn.equalsIgnoreCase("bindpassword") ||
- pn.equalsIgnoreCase("bindpwd") ||
- pn.equalsIgnoreCase("passwd") ||
- pn.equalsIgnoreCase("password") ||
- pn.equalsIgnoreCase("pin") ||
- pn.equalsIgnoreCase("pwd") ||
- pn.equalsIgnoreCase("pwdagain") ||
- pn.equalsIgnoreCase("uPasswd") ) {
- CMS.debug("AdminServlet::service() param name='" + pn +
- "' value='(sensitive)'" );
+ if (pn.startsWith("__") ||
+ pn.endsWith("password") ||
+ pn.endsWith("passwd") ||
+ pn.endsWith("pwd") ||
+ pn.equalsIgnoreCase("admin_password_again") ||
+ pn.equalsIgnoreCase("directoryManagerPwd") ||
+ pn.equalsIgnoreCase("bindpassword") ||
+ pn.equalsIgnoreCase("bindpwd") ||
+ pn.equalsIgnoreCase("passwd") ||
+ pn.equalsIgnoreCase("password") ||
+ pn.equalsIgnoreCase("pin") ||
+ pn.equalsIgnoreCase("pwd") ||
+ pn.equalsIgnoreCase("pwdagain") ||
+ pn.equalsIgnoreCase("uPasswd")) {
+ CMS.debug("AdminServlet::service() param name='" + pn +
+ "' value='(sensitive)'");
} else {
- CMS.debug("AdminServlet::service() param name='" + pn +
- "' value='" + httpReq.getParameter(pn) + "'" );
+ CMS.debug("AdminServlet::service() param name='" + pn +
+ "' value='" + httpReq.getParameter(pn) + "'");
}
}
}
-
+
/**
* Serves HTTP admin request.
*/
public void service(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
+ throws ServletException, IOException {
boolean running_state = CMS.isInRunningState();
if (!running_state)
@@ -250,7 +243,7 @@ public class AdminServlet extends HttpServlet {
"CMS server is not ready to serve.");
if (CMS.debugOn()) {
- outputHttpParameters(req);
+ outputHttpParameters(req);
}
}
@@ -274,18 +267,18 @@ public class AdminServlet extends HttpServlet {
}
/**
- * Authenticates to the identity scope with the given
- * userid and password via identity manager.
+ * Authenticates to the identity scope with the given userid and password
+ * via identity manager.
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_AUTH_FAIL used when authentication
- * fails (in case of SSL-client auth, only webserver env can pick up the
- * SSL violation; CMS authMgr can pick up cert mis-match, so this event
- * is used)
- * <li>signed.audit LOGGING_SIGNED_AUDIT_AUTH_SUCCESS used when authentication
- * succeeded
+ * fails (in case of SSL-client auth, only webserver env can pick up the SSL
+ * violation; CMS authMgr can pick up cert mis-match, so this event is used)
+ * <li>signed.audit LOGGING_SIGNED_AUDIT_AUTH_SUCCESS used when
+ * authentication succeeded
* </ul>
+ *
* @exception IOException an input/output error has occurred
*/
protected void authenticate(HttpServletRequest req) throws
@@ -307,12 +300,12 @@ public class AdminServlet extends HttpServlet {
// do nothing for now.
}
IAuthSubsystem auth = (IAuthSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_AUTH);
+ CMS.getSubsystem(CMS.SUBSYSTEM_AUTH);
X509Certificate cert = null;
if (authType.equals("sslclientauth")) {
X509Certificate[] allCerts =
- (X509Certificate[]) req.getAttribute(CERT_ATTR);
+ (X509Certificate[]) req.getAttribute(CERT_ATTR);
if (allCerts == null || allCerts.length == 0) {
// store a message in the signed audit log file
@@ -362,10 +355,9 @@ public class AdminServlet extends HttpServlet {
mServletID));
try {
if (authType.equals("sslclientauth")) {
- IAuthManager
- authMgr = auth.get(IAuthSubsystem.CERTUSERDB_AUTHMGR_ID);
+ IAuthManager authMgr = auth.get(IAuthSubsystem.CERTUSERDB_AUTHMGR_ID);
IAuthCredentials authCreds =
- getAuthCreds(authMgr, cert);
+ getAuthCreds(authMgr, cert);
token = (AuthToken) authMgr.authenticate(authCreds);
} else {
@@ -400,15 +392,14 @@ public class AdminServlet extends HttpServlet {
mServletID));
}
} catch (EBaseException e) {
- //will fix it later for authorization
+ // will fix it later for authorization
/*
- String errMsg = "authenticate(): " +
- AdminResources.SRVLT_FAIL_AUTHS +": "+userid +":"+
- e.getMessage();
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAIL",
- CMS.getLogMessage("ADMIN_SRVLT_FAIL_AUTHS"),
- userid,e.getMessage()));
+ * String errMsg = "authenticate(): " +
+ * AdminResources.SRVLT_FAIL_AUTHS +": "+userid +":"+
+ * e.getMessage(); log(ILogger.LL_FAILURE,
+ * CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAIL",
+ * CMS.getLogMessage("ADMIN_SRVLT_FAIL_AUTHS"),
+ * userid,e.getMessage()));
*/
if (authType.equals("sslclientauth")) {
@@ -441,9 +432,9 @@ public class AdminServlet extends HttpServlet {
if (tuserid == null) {
mLogger.log(
- ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_NO_AUTH_TOKEN",
- tuserid));
+ ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_NO_AUTH_TOKEN",
+ tuserid));
if (authType.equals("sslclientauth")) {
// store a message in the signed audit log file
@@ -477,9 +468,9 @@ public class AdminServlet extends HttpServlet {
if (user == null) {
mLogger.log(
- ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_USER_NOT_FOUND",
- tuserid));
+ ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_USER_NOT_FOUND",
+ tuserid));
if (authType.equals("sslclientauth")) {
// store a message in the signed audit log file
@@ -515,7 +506,7 @@ public class AdminServlet extends HttpServlet {
sessionContext.put(SessionContext.USER, user);
} catch (EUsrGrpException e) {
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_USR_GRP_ERR", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_USR_GRP_ERR", e.toString()));
if (authType.equals("sslclientauth")) {
// store a message in the signed audit log file
@@ -595,8 +586,8 @@ public class AdminServlet extends HttpServlet {
}
public static AuthCredentials getAuthCreds(
- IAuthManager authMgr, X509Certificate clientCert)
- throws EBaseException {
+ IAuthManager authMgr, X509Certificate clientCert)
+ throws EBaseException {
// get credentials from http parameters.
String[] reqCreds = authMgr.getRequiredCreds();
AuthCredentials creds = new AuthCredentials();
@@ -606,8 +597,8 @@ public class AdminServlet extends HttpServlet {
if (reqCred.equals(IAuthManager.CRED_SSL_CLIENT_CERT)) {
// cert could be null;
- creds.set(reqCred, new X509Certificate[] { clientCert}
- );
+ creds.set(reqCred, new X509Certificate[] { clientCert }
+ );
}
}
return creds;
@@ -616,15 +607,16 @@ public class AdminServlet extends HttpServlet {
/**
* Authorize must occur after Authenticate
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_AUTHZ_FAIL used when authorization
* has failed
- * <li>signed.audit LOGGING_SIGNED_AUDIT_AUTHZ_SUCCESS used when authorization
- * is successful
- * <li>signed.audit LOGGING_SIGNED_AUDIT_ROLE_ASSUME used when user assumes a
- * role (in current CMS that's when one accesses a role port)
+ * <li>signed.audit LOGGING_SIGNED_AUDIT_AUTHZ_SUCCESS used when
+ * authorization is successful
+ * <li>signed.audit LOGGING_SIGNED_AUDIT_ROLE_ASSUME used when user assumes
+ * a role (in current CMS that's when one accesses a role port)
* </ul>
+ *
* @param req HTTP servlet request
* @return the authorization token
*/
@@ -646,7 +638,7 @@ public class AdminServlet extends HttpServlet {
// hardcoded for now .. just testing
try {
// we check both "read" and "write" for now. later within
- // each servlet, they can break it down
+ // each servlet, they can break it down
authzTok = mAuthz.authorize(mAclMethod, authToken, AUTHZ_RES_NAME, mOp);
// initialize the ACL resource, overwriting "auditACLResource"
// if it is not null
@@ -779,15 +771,15 @@ public class AdminServlet extends HttpServlet {
/**
* Sends response.
- *
+ *
* @param returnCode return code
* @param errorMsg localized error message
* @param params result parameters
* @param resp HTTP servlet response
*/
protected void sendResponse(int returnCode, String errorMsg,
- NameValuePairs params, HttpServletResponse resp)
- throws IOException {
+ NameValuePairs params, HttpServletResponse resp)
+ throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
@@ -806,8 +798,8 @@ public class AdminServlet extends HttpServlet {
String value = java.net.URLEncoder.encode((String)
params.getValue(name));
- buf.append(java.net.URLEncoder.encode(name) +
- "=" + value);
+ buf.append(java.net.URLEncoder.encode(name) +
+ "=" + value);
if (e.hasMoreElements())
buf.append("&");
}
@@ -850,7 +842,7 @@ public class AdminServlet extends HttpServlet {
protected String getParameter(HttpServletRequest req, String name) {
// Servlet framework already apply URLdecode
- // return URLdecode(req.getParameter(name));
+ // return URLdecode(req.getParameter(name));
return req.getParameter(name);
}
@@ -858,8 +850,8 @@ public class AdminServlet extends HttpServlet {
* Generic configuration store get operation.
*/
protected synchronized void getConfig(
- IConfigStore config, HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ IConfigStore config, HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
Enumeration e = req.getParameterNames();
@@ -867,8 +859,8 @@ public class AdminServlet extends HttpServlet {
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
- //if (name.equals(Constants.PT_OP))
- // continue;
+ // if (name.equals(Constants.PT_OP))
+ // continue;
if (name.equals(Constants.OP_TYPE))
continue;
if (name.equals(Constants.RS_ID))
@@ -876,21 +868,20 @@ public class AdminServlet extends HttpServlet {
if (name.equals(Constants.OP_SCOPE))
continue;
- //System.out.println(name);
- //System.out.println(name+","+config.getString(name));
+ // System.out.println(name);
+ // System.out.println(name+","+config.getString(name));
params.add(name, config.getString(name));
}
sendResponse(SUCCESS, null, params, resp);
}
/**
- * Generic configuration store set operation.
- * The caller is responsible to do validiation before
- * calling this, and commit changes after this call.
+ * Generic configuration store set operation. The caller is responsible to
+ * do validiation before calling this, and commit changes after this call.
*/
protected synchronized void setConfig(
- IConfigStore config, HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ IConfigStore config, HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
Enumeration e = req.getParameterNames();
@@ -898,16 +889,16 @@ public class AdminServlet extends HttpServlet {
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
- //if (name.equals(Constants.PT_OP))
- // continue;
+ // if (name.equals(Constants.PT_OP))
+ // continue;
if (name.equals(Constants.OP_TYPE))
continue;
if (name.equals(Constants.RS_ID))
continue;
if (name.equals(Constants.OP_SCOPE))
continue;
- // XXX Need validation...
- // XXX what if update failed
+ // XXX Need validation...
+ // XXX what if update failed
config.putString(name, req.getParameter(name));
}
commit(true);
@@ -918,8 +909,8 @@ public class AdminServlet extends HttpServlet {
* Lists configuration store.
*/
protected synchronized void listConfig(
- IConfigStore config, HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ IConfigStore config, HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
Enumeration e = config.getPropertyNames();
NameValuePairs params = new NameValuePairs();
@@ -938,14 +929,14 @@ public class AdminServlet extends HttpServlet {
public boolean authorize(IAuthToken token) throws EBaseException {
String mGroupNames[] = { "Administrators" };
boolean mAnd = true;
-
+
try {
String userid = token.getInString("userid");
if (userid == null) {
mLogger.log(
- ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_GRP_AUTHZ_FAIL", userid));
+ ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_GRP_AUTHZ_FAIL", userid));
return false;
}
@@ -955,8 +946,8 @@ public class AdminServlet extends HttpServlet {
if (user == null) {
mLogger.log(
- ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_USER_NOT_IN_DB", userid));
+ ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_USER_NOT_IN_DB", userid));
return false;
}
@@ -973,9 +964,9 @@ public class AdminServlet extends HttpServlet {
for (int i = 0; i < mGroupNames.length; i++) {
if (!mUG.isMemberOf(user, mGroupNames[i])) {
mLogger.log(
- ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_USER_NOT_IN_GRP", userid,
- mGroupNames[i]));
+ ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_USER_NOT_IN_GRP", userid,
+ mGroupNames[i]));
return false;
}
}
@@ -984,9 +975,9 @@ public class AdminServlet extends HttpServlet {
for (int i = 0; i < mGroupNames.length; i++) {
if (mUG.isMemberOf(user, mGroupNames[i])) {
mLogger.log(ILogger.EV_SYSTEM,
- ILogger.S_OTHER, ILogger.LL_INFO,
- CMS.getLogMessage("ADMIN_SRVLT_GRP_AUTH_SUCC_USER", userid,
- mGroupNames[i]));
+ ILogger.S_OTHER, ILogger.LL_INFO,
+ CMS.getLogMessage("ADMIN_SRVLT_GRP_AUTH_SUCC_USER", userid,
+ mGroupNames[i]));
return true;
}
}
@@ -998,24 +989,24 @@ public class AdminServlet extends HttpServlet {
groups.append(mGroupNames[j]);
}
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_USER_NOT_ANY_GRP", userid, groups.toString()));
+ ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_USER_NOT_ANY_GRP", userid, groups.toString()));
return false;
}
} catch (EUsrGrpException e) {
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_USR_GRP_ERR", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_USR_GRP_ERR", e.toString()));
return false;
}
}
/**
* FileConfigStore functionality
- *
- * The original config file is moved to <filename>.<date>.
- * Commits the current properties to the configuration file.
+ *
+ * The original config file is moved to <filename>.<date>. Commits the
+ * current properties to the configuration file.
* <P>
- *
+ *
* @param createBackup true if a backup file should be created
*/
protected void commit(boolean createBackup) throws EBaseException {
@@ -1026,16 +1017,16 @@ public class AdminServlet extends HttpServlet {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_ADMIN,
- level, "AdminServlet: " + msg);
+ level, "AdminServlet: " + msg);
}
/**
* Signed Audit Log
- *
- * This method is inherited by all extended admin servlets
- * and is called to store messages to the signed audit log.
+ *
+ * This method is inherited by all extended admin servlets and is called to
+ * store messages to the signed audit log.
* <P>
- *
+ *
* @param msg signed audit log message
*/
protected void audit(String msg) {
@@ -1047,20 +1038,19 @@ public class AdminServlet extends HttpServlet {
}
mSignedAuditLogger.log(ILogger.EV_SIGNED_AUDIT,
- null,
- ILogger.S_SIGNED_AUDIT,
- ILogger.LL_SECURITY,
- msg);
+ null,
+ ILogger.S_SIGNED_AUDIT,
+ ILogger.LL_SECURITY,
+ msg);
}
/**
* Signed Audit Log Subject ID
- *
- * This method is inherited by all extended "CMSServlet"s,
- * and is called to obtain the "SubjectID" for
- * a signed audit log message.
+ *
+ * This method is inherited by all extended "CMSServlet"s, and is called to
+ * obtain the "SubjectID" for a signed audit log message.
* <P>
- *
+ *
* @return id string containing the signed audit log message SubjectID
*/
protected String auditSubjectID() {
@@ -1092,13 +1082,13 @@ public class AdminServlet extends HttpServlet {
/**
* Signed Audit Parameters
- *
- * This method is inherited by all extended admin servlets and
- * is called to extract parameters from the HttpServletRequest
- * and return a string of name;;value pairs separated by a '+'
- * if more than one name;;value pair exists.
+ *
+ * This method is inherited by all extended admin servlets and is called to
+ * extract parameters from the HttpServletRequest and return a string of
+ * name;;value pairs separated by a '+' if more than one name;;value pair
+ * exists.
* <P>
- *
+ *
* @param req HTTP servlet request
* @return a delimited string of one or more delimited name/value pairs
*/
@@ -1172,26 +1162,27 @@ public class AdminServlet extends HttpServlet {
//
// To fix Blackflag Bug # 613800:
//
- // Check "com.netscape.certsrv.common.Constants" for
- // case-insensitive "password", "pwd", and "passwd"
- // name fields, and hide any password values:
+ // Check "com.netscape.certsrv.common.Constants" for
+ // case-insensitive "password", "pwd", and "passwd"
+ // name fields, and hide any password values:
//
- /* "password" */ if( name.equals( Constants.PASSWORDTYPE ) ||
- name.equals( Constants.TYPE_PASSWORD ) ||
- name.equals( Constants.PR_USER_PASSWORD ) ||
- name.equals( Constants.PT_OLD_PASSWORD ) ||
- name.equals( Constants.PT_NEW_PASSWORD ) ||
- name.equals( Constants.PT_DIST_STORE ) ||
- name.equals( Constants.PT_DIST_EMAIL ) ||
- /* "pwd" */ name.equals( Constants.PR_AUTH_ADMIN_PWD ) ||
- // ignore this one name.equals( Constants.PR_BINDPWD_PROMPT ) ||
- name.equals( Constants.PR_DIRECTORY_MANAGER_PWD ) ||
- name.equals( Constants.PR_OLD_AGENT_PWD ) ||
- name.equals( Constants.PR_AGENT_PWD ) ||
- name.equals( Constants.PT_PUBLISH_PWD ) ||
- /* "passwd" */ name.equals( Constants.PR_BIND_PASSWD ) ||
- name.equals( Constants.PR_BIND_PASSWD_AGAIN ) ||
- name.equals( Constants.PR_TOKEN_PASSWD ) ) {
+ /* "password" */if (name.equals(Constants.PASSWORDTYPE) ||
+ name.equals(Constants.TYPE_PASSWORD) ||
+ name.equals(Constants.PR_USER_PASSWORD) ||
+ name.equals(Constants.PT_OLD_PASSWORD) ||
+ name.equals(Constants.PT_NEW_PASSWORD) ||
+ name.equals(Constants.PT_DIST_STORE) ||
+ name.equals(Constants.PT_DIST_EMAIL) ||
+ /* "pwd" */name.equals(Constants.PR_AUTH_ADMIN_PWD) ||
+ // ignore this one name.equals(
+ // Constants.PR_BINDPWD_PROMPT ) ||
+ name.equals(Constants.PR_DIRECTORY_MANAGER_PWD) ||
+ name.equals(Constants.PR_OLD_AGENT_PWD) ||
+ name.equals(Constants.PR_AGENT_PWD) ||
+ name.equals(Constants.PT_PUBLISH_PWD) ||
+ /* "passwd" */name.equals(Constants.PR_BIND_PASSWD) ||
+ name.equals(Constants.PR_BIND_PASSWD_AGAIN) ||
+ name.equals(Constants.PR_TOKEN_PASSWD)) {
// hide password value
parameters += name
@@ -1216,14 +1207,14 @@ public class AdminServlet extends HttpServlet {
/**
* Signed Audit Groups
- *
- * This method is called to extract all "groups" associated
- * with the "auditSubjectID()".
+ *
+ * This method is called to extract all "groups" associated with the
+ * "auditSubjectID()".
* <P>
- *
+ *
* @param SubjectID string containing the signed audit log message SubjectID
- * @return a delimited string of groups associated
- * with the "auditSubjectID()"
+ * @return a delimited string of groups associated with the
+ * "auditSubjectID()"
*/
private String auditGroups(String SubjectID) {
// if no signed audit object exists, bail
@@ -1232,7 +1223,7 @@ public class AdminServlet extends HttpServlet {
}
if ((SubjectID == null) ||
- (SubjectID.equals(ILogger.UNIDENTIFIED))) {
+ (SubjectID.equals(ILogger.UNIDENTIFIED))) {
return ILogger.SIGNED_AUDIT_EMPTY_VALUE;
}
@@ -1250,7 +1241,7 @@ public class AdminServlet extends HttpServlet {
IGroup group = (IGroup) groups.nextElement();
if (group.isMember(SubjectID) == true) {
- if (membersString.length()!=0) {
+ if (membersString.length() != 0) {
membersString.append(", ");
}
@@ -1258,7 +1249,7 @@ public class AdminServlet extends HttpServlet {
}
}
- if (membersString.length()!= 0) {
+ if (membersString.length() != 0) {
return membersString.toString();
} else {
return ILogger.SIGNED_AUDIT_EMPTY_VALUE;
@@ -1266,7 +1257,8 @@ public class AdminServlet extends HttpServlet {
}
protected NameValuePairs convertStringArrayToNVPairs(String[] s) {
- if (s == null) return null;
+ if (s == null)
+ return null;
NameValuePairs nvps = new NameValuePairs();
int i;
diff --git a/pki/base/common/src/com/netscape/cms/servlet/admin/AuthAdminServlet.java b/pki/base/common/src/com/netscape/cms/servlet/admin/AuthAdminServlet.java
index 4a7329c9..28a25216 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/admin/AuthAdminServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/admin/AuthAdminServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.admin;
-
import java.io.IOException;
import java.util.Enumeration;
import java.util.Locale;
@@ -46,13 +45,12 @@ import com.netscape.certsrv.common.ScopeDef;
import com.netscape.certsrv.ldap.ILdapAuthInfo;
import com.netscape.certsrv.logging.ILogger;
-
/**
- * A class representing an administration servlet for the
- * Authentication Management subsystem. This servlet is responsible
- * to serve configuration requests for the Auths Management subsystem.
+ * A class representing an administration servlet for the Authentication
+ * Management subsystem. This servlet is responsible to serve configuration
+ * requests for the Auths Management subsystem.
+ *
*
- *
* @version $Revision$, $Date$
*/
public class AuthAdminServlet extends AdminServlet {
@@ -64,13 +62,13 @@ public class AuthAdminServlet extends AdminServlet {
private final static String INFO = "AuthAdminServlet";
private IAuthSubsystem mAuths = null;
- private final static String PW_PASSWORD_CACHE_ADD =
- "PASSWORD_CACHE_ADD";
+ private final static String PW_PASSWORD_CACHE_ADD =
+ "PASSWORD_CACHE_ADD";
private final static String VIEW = ";" + Constants.VIEW;
private final static String EDIT = ";" + Constants.EDIT;
private final static String LOGGING_SIGNED_AUDIT_CONFIG_AUTH =
- "LOGGING_SIGNED_AUDIT_CONFIG_AUTH_3";
+ "LOGGING_SIGNED_AUDIT_CONFIG_AUTH_3";
public AuthAdminServlet() {
super();
@@ -88,18 +86,18 @@ public class AuthAdminServlet extends AdminServlet {
/**
* Returns serlvet information.
*/
- public String getServletInfo() {
- return INFO;
+ public String getServletInfo() {
+ return INFO;
}
/**
- * retrieve extended plugin info such as brief description, type info
- * from policy, authentication,
- * need to add: listener, mapper and publishing plugins
- * --- same as policy, should we move this into extendedpluginhelper?
+ * retrieve extended plugin info such as brief description, type info from
+ * policy, authentication, need to add: listener, mapper and publishing
+ * plugins --- same as policy, should we move this into
+ * extendedpluginhelper?
*/
private void getExtendedPluginInfo(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String id = req.getParameter(Constants.RS_ID);
@@ -110,7 +108,7 @@ public class AuthAdminServlet extends AdminServlet {
String implName = id.substring(colon + 1);
NameValuePairs params =
- getExtendedPluginInfo(getLocale(req), implType, implName);
+ getExtendedPluginInfo(getLocale(req), implType, implName);
sendResponse(SUCCESS, null, params, resp);
}
@@ -142,42 +140,43 @@ public class AuthAdminServlet extends AdminServlet {
* Serves HTTP admin request.
*/
public void service(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
+ throws ServletException, IOException {
super.service(req, resp);
String scope = req.getParameter(Constants.OP_SCOPE);
String op = req.getParameter(Constants.OP_TYPE);
if (op == null) {
- //System.out.println("SRVLT_INVALID_PROTOCOL");
- sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_PROTOCOL"),
- null, resp);
+ // System.out.println("SRVLT_INVALID_PROTOCOL");
+ sendResponse(ERROR,
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_PROTOCOL"),
+ null, resp);
return;
}
// if it is not authentication, that means it is for CSC admin ping.
// the best way to do is to define another protocol for ping and move
// it to the generic servlet which is admin servlet.
- if (!op.equals(OpDef.OP_AUTH)) {
+ if (!op.equals(OpDef.OP_AUTH)) {
if (scope.equals(ScopeDef.SC_AUTH)) {
String id = req.getParameter(Constants.RS_ID);
// for CSC admin ping only
if (op.equals(OpDef.OP_READ) &&
- id.equals(Constants.RS_ID_CONFIG)) {
+ id.equals(Constants.RS_ID_CONFIG)) {
- // no need to authenticate this. if we're alive, return true.
+ // no need to authenticate this. if we're alive, return
+ // true.
NameValuePairs params = new NameValuePairs();
params.add(Constants.PR_PING, Constants.TRUE);
sendResponse(SUCCESS, null, params, resp);
return;
} else {
- //System.out.println("SRVLT_INVALID_OP_TYPE");
+ // System.out.println("SRVLT_INVALID_OP_TYPE");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_TYPE", op),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_TYPE", op),
+ null, resp);
return;
}
}
@@ -186,7 +185,7 @@ public class AuthAdminServlet extends AdminServlet {
try {
if (op.equals(OpDef.OP_AUTH)) {
if (scope.equals(ScopeDef.SC_AUTHTYPE)) {
- IConfigStore configStore = CMS.getConfigStore();
+ IConfigStore configStore = CMS.getConfigStore();
String val = configStore.getString("authType", "pwd");
NameValuePairs params = new NameValuePairs();
@@ -196,11 +195,11 @@ public class AuthAdminServlet extends AdminServlet {
}
}
} catch (Exception e) {
- sendResponse(ERROR,CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHS_FAILED"),
- null, resp);
+ sendResponse(ERROR, CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHS_FAILED"),
+ null, resp);
return;
}
- // for the rest
+ // for the rest
try {
super.authenticate(req);
if (op.equals(OpDef.OP_AUTH)) { // for admin authentication only
@@ -208,9 +207,9 @@ public class AuthAdminServlet extends AdminServlet {
return;
}
} catch (IOException e) {
- //System.out.println("SRVLT_FAIL_AUTHS");
- sendResponse(ERROR,CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHS_FAILED"),
- null, resp);
+ // System.out.println("SRVLT_FAIL_AUTHS");
+ sendResponse(ERROR, CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHS_FAILED"),
+ null, resp);
return;
}
@@ -223,8 +222,8 @@ public class AuthAdminServlet extends AdminServlet {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
getExtendedPluginInfo(req, resp);
@@ -238,8 +237,8 @@ public class AuthAdminServlet extends AdminServlet {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_AUTH_IMPLS)) {
@@ -249,17 +248,17 @@ public class AuthAdminServlet extends AdminServlet {
listAuthMgrInsts(req, resp);
return;
} else {
- sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
- null, resp);
+ sendResponse(ERROR,
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
+ null, resp);
return;
}
} else if (op.equals(OpDef.OP_READ)) {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_AUTH_IMPLS)) {
@@ -269,17 +268,17 @@ public class AuthAdminServlet extends AdminServlet {
getInstConfig(req, resp);
return;
} else {
- sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
- null, resp);
+ sendResponse(ERROR,
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
+ null, resp);
return;
}
} else if (op.equals(OpDef.OP_ADD)) {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_AUTH_IMPLS)) {
@@ -289,17 +288,17 @@ public class AuthAdminServlet extends AdminServlet {
addAuthMgrInst(req, resp, scope);
return;
} else {
- sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
- null, resp);
+ sendResponse(ERROR,
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
+ null, resp);
return;
}
} else if (op.equals(OpDef.OP_DELETE)) {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_AUTH_IMPLS)) {
@@ -309,17 +308,17 @@ public class AuthAdminServlet extends AdminServlet {
delAuthMgrInst(req, resp, scope);
return;
} else {
- sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
- null, resp);
+ sendResponse(ERROR,
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
+ null, resp);
return;
}
} else if (op.equals(OpDef.OP_MODIFY)) {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_AUTH_MGR_INSTANCE)) {
@@ -328,18 +327,18 @@ public class AuthAdminServlet extends AdminServlet {
}
} else {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
+ null, resp);
return;
}
- }
+ }
} catch (EBaseException e) {
sendResponse(ERROR, e.toString(getLocale(req)), null, resp);
return;
- }
+ }
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_PERFORM_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_PERFORM_FAILED"),
+ null, resp);
return;
}
@@ -356,23 +355,24 @@ public class AuthAdminServlet extends AdminServlet {
/**
* Add authentication manager plug-in
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_AUTH used when configuring
* authentication
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @param scope string used to obtain the contents of this authentication
- * manager's substore
+ * manager's substore
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
* @exception EBaseException an error has occurred
*/
-
- private synchronized void addAuthMgrPlugin(HttpServletRequest req,
- HttpServletResponse resp, String scope)
- throws ServletException, IOException, EBaseException {
+
+ private synchronized void addAuthMgrPlugin(HttpServletRequest req,
+ HttpServletResponse resp, String scope)
+ throws ServletException, IOException, EBaseException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -392,10 +392,10 @@ public class AuthAdminServlet extends AdminServlet {
audit(auditMessage);
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
// is the manager id unique?
@@ -410,8 +410,8 @@ public class AuthAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- new EAuthException(CMS.getUserMessage(getLocale(req),"CMS_AUTHENTICATION_DUP_MGR_PLUGIN_ID", id)).toString(),
- null, resp);
+ new EAuthException(CMS.getUserMessage(getLocale(req), "CMS_AUTHENTICATION_DUP_MGR_PLUGIN_ID", id)).toString(),
+ null, resp);
return;
}
@@ -428,13 +428,13 @@ public class AuthAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_AUTHENTICATION_NULL_AUTHMGR_CLASSNAME"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_AUTHENTICATION_NULL_AUTHMGR_CLASSNAME"),
+ null, resp);
return;
}
if (classPath.equals("com.netscape.cmscore.authentication.PasswdUserDBAuthentication") ||
- classPath.equals("com.netscape.cmscore.authentication.CertUserDBAuthentication")) {
+ classPath.equals("com.netscape.cmscore.authentication.CertUserDBAuthentication")) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CONFIG_AUTH,
@@ -445,17 +445,17 @@ public class AuthAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_BASE_PERMISSION_DENIED"), null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_BASE_PERMISSION_DENIED"), null, resp);
return;
}
IConfigStore destStore =
- mConfig.getSubStore(DestDef.DEST_AUTH_ADMIN);
+ mConfig.getSubStore(DestDef.DEST_AUTH_ADMIN);
IConfigStore instancesConfig =
- destStore.getSubStore(scope);
+ destStore.getSubStore(scope);
// Does the class exist?
-
+
Class<IAuthManager> newImpl = null;
try {
@@ -473,8 +473,8 @@ public class AuthAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_AUTHENTICATION_AUTHMGR_PLUGIN_NOT_FOUND"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_AUTHENTICATION_AUTHMGR_PLUGIN_NOT_FOUND"),
+ null, resp);
return;
} catch (IllegalArgumentException e) {
// store a message in the signed audit log file
@@ -487,8 +487,8 @@ public class AuthAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_AUTHENTICATION_AUTHMGR_PLUGIN_NOT_FOUND"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_AUTHENTICATION_AUTHMGR_PLUGIN_NOT_FOUND"),
+ null, resp);
return;
}
@@ -505,11 +505,12 @@ public class AuthAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_AUTHENTICATION_ILL_CLASS"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_AUTHENTICATION_ILL_CLASS"),
+ null, resp);
return;
}
- } catch (NullPointerException e) { // unlikely, only if newImpl null.
+ } catch (NullPointerException e) { // unlikely, only if newImpl
+ // null.
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CONFIG_AUTH,
@@ -520,8 +521,8 @@ public class AuthAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_AUTHENTICATION_ILL_CLASS"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_AUTHENTICATION_ILL_CLASS"),
+ null, resp);
return;
}
@@ -542,10 +543,10 @@ public class AuthAdminServlet extends AdminServlet {
audit(auditMessage);
- //System.out.println("SRVLT_FAIL_COMMIT");
+ // System.out.println("SRVLT_FAIL_COMMIT");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
+ null, resp);
return;
}
@@ -553,8 +554,8 @@ public class AuthAdminServlet extends AdminServlet {
AuthMgrPlugin plugin = new AuthMgrPlugin(id, classPath);
mAuths.getPlugins().put(id, plugin);
- mAuths.log(ILogger.LL_INFO,
- CMS.getLogMessage("ADMIN_SRVLT_PLUGIN_ADD", id));
+ mAuths.log(ILogger.LL_INFO,
+ CMS.getLogMessage("ADMIN_SRVLT_PLUGIN_ADD", id));
NameValuePairs params = new NameValuePairs();
@@ -570,17 +571,17 @@ public class AuthAdminServlet extends AdminServlet {
sendResponse(SUCCESS, null, params, resp);
return;
// } catch( EBaseException eAudit1 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_AUTH,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_AUTH,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit1;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit1;
} catch (IOException eAudit2) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -594,39 +595,40 @@ public class AuthAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit2;
// } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_AUTH,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_AUTH,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
}
}
/**
* Add authentication manager instance
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_AUTH used when configuring
* authentication
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @param scope string used to obtain the contents of this authentication
- * manager's substore
+ * manager's substore
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
* @exception EBaseException an error has occurred
*/
- private synchronized void addAuthMgrInst(HttpServletRequest req,
- HttpServletResponse resp, String scope)
- throws ServletException, IOException, EBaseException {
+ private synchronized void addAuthMgrInst(HttpServletRequest req,
+ HttpServletResponse resp, String scope)
+ throws ServletException, IOException, EBaseException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -647,8 +649,8 @@ public class AuthAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
@@ -664,8 +666,8 @@ public class AuthAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_AUTHENTICATION_ILL_MGR_INST_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_AUTHENTICATION_ILL_MGR_INST_ID"),
+ null, resp);
return;
}
@@ -685,21 +687,21 @@ public class AuthAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_AUTHENTICATION_MISSING_PARAMS"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_AUTHENTICATION_MISSING_PARAMS"),
+ null, resp);
return;
}
// prevent agent & admin creation.
if (implname.equals(IAuthSubsystem.PASSWDUSERDB_PLUGIN_ID) ||
- implname.equals(IAuthSubsystem.CERTUSERDB_PLUGIN_ID)) {
+ implname.equals(IAuthSubsystem.CERTUSERDB_PLUGIN_ID)) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_BASE_PERMISSION_DENIED"), null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_BASE_PERMISSION_DENIED"), null, resp);
}
// check if implementation exists.
AuthMgrPlugin plugin =
- (AuthMgrPlugin) mAuths.getPlugins().get(implname);
+ (AuthMgrPlugin) mAuths.getPlugins().get(implname);
if (plugin == null) {
// store a message in the signed audit log file
@@ -712,8 +714,8 @@ public class AuthAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- new EAuthMgrPluginNotFound(CMS.getUserMessage(getLocale(req),"CMS_AUTHENTICATION_AUTHMGR_NOT_FOUND", implname)).toString(),
- null, resp);
+ new EAuthMgrPluginNotFound(CMS.getUserMessage(getLocale(req), "CMS_AUTHENTICATION_AUTHMGR_NOT_FOUND", implname)).toString(),
+ null, resp);
return;
}
@@ -723,9 +725,9 @@ public class AuthAdminServlet extends AdminServlet {
String[] configParams = mAuths.getConfigParams(implname);
IConfigStore destStore =
- mConfig.getSubStore(DestDef.DEST_AUTH_ADMIN);
+ mConfig.getSubStore(DestDef.DEST_AUTH_ADMIN);
IConfigStore instancesConfig =
- destStore.getSubStore(scope);
+ destStore.getSubStore(scope);
IConfigStore substore = instancesConfig.makeSubStore(id);
if (configParams != null) {
@@ -765,8 +767,8 @@ public class AuthAdminServlet extends AdminServlet {
// cleanup
instancesConfig.removeSubStore(id);
sendResponse(ERROR,
- new EAuthException(CMS.getUserMessage(getLocale(req),"CMS_AUTHENTICATION_LOAD_CLASS_FAIL", className)).toString(),
- null, resp);
+ new EAuthException(CMS.getUserMessage(getLocale(req), "CMS_AUTHENTICATION_LOAD_CLASS_FAIL", className)).toString(),
+ null, resp);
return;
} catch (InstantiationException e) {
// store a message in the signed audit log file
@@ -780,8 +782,8 @@ public class AuthAdminServlet extends AdminServlet {
instancesConfig.removeSubStore(id);
sendResponse(ERROR,
- new EAuthException(CMS.getUserMessage(getLocale(req),"CMS_AUTHENTICATION_LOAD_CLASS_FAIL", className)).toString(),
- null, resp);
+ new EAuthException(CMS.getUserMessage(getLocale(req), "CMS_AUTHENTICATION_LOAD_CLASS_FAIL", className)).toString(),
+ null, resp);
return;
} catch (IllegalAccessException e) {
// store a message in the signed audit log file
@@ -795,8 +797,8 @@ public class AuthAdminServlet extends AdminServlet {
instancesConfig.removeSubStore(id);
sendResponse(ERROR,
- new EAuthException(CMS.getUserMessage(getLocale(req),"CMS_AUTHENTICATION_LOAD_CLASS_FAIL", className)).toString(),
- null, resp);
+ new EAuthException(CMS.getUserMessage(getLocale(req), "CMS_AUTHENTICATION_LOAD_CLASS_FAIL", className)).toString(),
+ null, resp);
return;
}
@@ -835,16 +837,16 @@ public class AuthAdminServlet extends AdminServlet {
// clean up.
instancesConfig.removeSubStore(id);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
+ null, resp);
return;
}
// inited and commited ok. now add manager instance to list.
mAuths.add(id, authMgrInst);
- mAuths.log(ILogger.LL_INFO,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_MGR_ADD", id));
+ mAuths.log(ILogger.LL_INFO,
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_MGR_ADD", id));
NameValuePairs params = new NameValuePairs();
@@ -886,22 +888,22 @@ public class AuthAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit2;
// } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_AUTH,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_AUTH,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
}
}
- private synchronized void listAuthMgrPlugins(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ private synchronized void listAuthMgrPlugins(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
@@ -909,8 +911,8 @@ public class AuthAdminServlet extends AdminServlet {
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
- AuthMgrPlugin value = (AuthMgrPlugin)
- mAuths.getPlugins().get(name);
+ AuthMgrPlugin value = (AuthMgrPlugin)
+ mAuths.getPlugins().get(name);
if (value.isVisible()) {
params.add(name, value.getClassPath() + EDIT);
@@ -920,14 +922,13 @@ public class AuthAdminServlet extends AdminServlet {
return;
}
- private synchronized void listAuthMgrInsts(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ private synchronized void listAuthMgrInsts(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
- for (Enumeration<?> e = mAuths.getInstances().keys();
- e.hasMoreElements();) {
+ for (Enumeration<?> e = mAuths.getInstances().keys(); e.hasMoreElements();) {
String name = (String) e.nextElement();
AuthManagerProxy proxy = (AuthManagerProxy) mAuths.getInstances().get(name);
IAuthManager value = proxy.getAuthManager();
@@ -938,7 +939,7 @@ public class AuthAdminServlet extends AdminServlet {
}
AuthMgrPlugin amgrplugin = (AuthMgrPlugin)
- mAuths.getPlugins().get(value.getImplName());
+ mAuths.getPlugins().get(value.getImplName());
if (!amgrplugin.isVisible()) {
params.add(name, value.getImplName() + ";invisible;" + enableStr);
@@ -953,21 +954,22 @@ public class AuthAdminServlet extends AdminServlet {
/**
* Delete authentication manager plug-in
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_AUTH used when configuring
* authentication
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @param scope string used to obtain the contents of this authentication
- * manager's substore
+ * manager's substore
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
* @exception EBaseException an error has occurred
*/
- private synchronized void delAuthMgrPlugin(HttpServletRequest req,
- HttpServletResponse resp, String scope) throws ServletException,
+ private synchronized void delAuthMgrPlugin(HttpServletRequest req,
+ HttpServletResponse resp, String scope) throws ServletException,
IOException, EBaseException {
String auditMessage = null;
@@ -989,18 +991,18 @@ public class AuthAdminServlet extends AdminServlet {
audit(auditMessage);
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
// prevent deletion of admin and agent.
if (id.equals(IAuthSubsystem.PASSWDUSERDB_PLUGIN_ID) ||
- id.equals(IAuthSubsystem.CERTUSERDB_PLUGIN_ID)) {
+ id.equals(IAuthSubsystem.CERTUSERDB_PLUGIN_ID)) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_BASE_PERMISSION_DENIED"), null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_BASE_PERMISSION_DENIED"), null, resp);
}
// does auth manager exist?
@@ -1015,15 +1017,14 @@ public class AuthAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- new EAuthMgrPluginNotFound(CMS.getUserMessage(getLocale(req), "CMS_AUTHENTICATION_DUP_MGR_PLUGIN_ID", id)).toString(),
- null, resp);
+ new EAuthMgrPluginNotFound(CMS.getUserMessage(getLocale(req), "CMS_AUTHENTICATION_DUP_MGR_PLUGIN_ID", id)).toString(),
+ null, resp);
return;
}
// first check if any instances from this auth manager
// DON'T remove auth manager if any instance
- for (Enumeration<?> e = mAuths.getInstances().keys();
- e.hasMoreElements();) {
+ for (Enumeration<?> e = mAuths.getInstances().keys(); e.hasMoreElements();) {
IAuthManager authMgr = (IAuthManager) mAuths.get((String) e.nextElement());
if (authMgr.getImplName() == id) {
@@ -1037,19 +1038,19 @@ public class AuthAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_AUTHENTICATION_MGR_IN_USE"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_AUTHENTICATION_MGR_IN_USE"),
+ null, resp);
return;
}
}
-
+
// then delete this auth manager
mAuths.getPlugins().remove((Object) id);
IConfigStore destStore =
- mConfig.getSubStore(DestDef.DEST_AUTH_ADMIN);
+ mConfig.getSubStore(DestDef.DEST_AUTH_ADMIN);
IConfigStore instancesConfig =
- destStore.getSubStore(scope);
+ destStore.getSubStore(scope);
instancesConfig.removeSubStore(id);
// commiting
@@ -1066,8 +1067,8 @@ public class AuthAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
+ null, resp);
return;
}
@@ -1083,17 +1084,17 @@ public class AuthAdminServlet extends AdminServlet {
sendResponse(SUCCESS, null, params, resp);
return;
// } catch( EBaseException eAudit1 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_AUTH,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_AUTH,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit1;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit1;
} catch (IOException eAudit2) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -1107,38 +1108,39 @@ public class AuthAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit2;
// } catch( ServletException eAudit1 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_AUTH,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_AUTH,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit1;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit1;
}
}
/**
* Delete authentication manager instance
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_AUTH used when configuring
* authentication
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @param scope string used to obtain the contents of this authentication
- * manager's substore
+ * manager's substore
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
* @exception EBaseException an error has occurred
*/
- private synchronized void delAuthMgrInst(HttpServletRequest req,
- HttpServletResponse resp, String scope) throws ServletException,
+ private synchronized void delAuthMgrInst(HttpServletRequest req,
+ HttpServletResponse resp, String scope) throws ServletException,
IOException, EBaseException {
String auditMessage = null;
@@ -1160,18 +1162,18 @@ public class AuthAdminServlet extends AdminServlet {
audit(auditMessage);
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
// prevent deletion of admin and agent.
if (id.equals(IAuthSubsystem.PASSWDUSERDB_AUTHMGR_ID) ||
- id.equals(IAuthSubsystem.CERTUSERDB_AUTHMGR_ID)) {
+ id.equals(IAuthSubsystem.CERTUSERDB_AUTHMGR_ID)) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_BASE_PERMISSION_DENIED"), null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_BASE_PERMISSION_DENIED"), null, resp);
}
// does auth manager instance exist?
@@ -1186,23 +1188,23 @@ public class AuthAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- new EAuthMgrNotFound(CMS.getUserMessage(getLocale(req),"CMS_AUTHENTICATION_AUTHMGR_NOT_FOUND", id)).toString(),
- null, resp);
+ new EAuthMgrNotFound(CMS.getUserMessage(getLocale(req), "CMS_AUTHENTICATION_AUTHMGR_NOT_FOUND", id)).toString(),
+ null, resp);
return;
}
// only remove from memory
// cannot shutdown because we don't keep track of whether it's
- // being used.
+ // being used.
IAuthManager mgrInst = (IAuthManager) mAuths.get(id);
mAuths.getInstances().remove((Object) id);
// remove the configuration.
IConfigStore destStore =
- mConfig.getSubStore(DestDef.DEST_AUTH_ADMIN);
+ mConfig.getSubStore(DestDef.DEST_AUTH_ADMIN);
IConfigStore instancesConfig =
- destStore.getSubStore(scope);
+ destStore.getSubStore(scope);
instancesConfig.removeSubStore(id);
// commiting
@@ -1218,15 +1220,15 @@ public class AuthAdminServlet extends AdminServlet {
audit(auditMessage);
- //System.out.println("SRVLT_FAIL_COMMIT");
+ // System.out.println("SRVLT_FAIL_COMMIT");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
+ null, resp);
return;
}
- //This only works in the fact that we only support one instance per
- //auth plugin.
+ // This only works in the fact that we only support one instance per
+ // auth plugin.
ILdapAuthInfo authInfo = CMS.getLdapAuthInfo();
authInfo.removePassword("Rule " + id);
@@ -1243,17 +1245,17 @@ public class AuthAdminServlet extends AdminServlet {
sendResponse(SUCCESS, null, params, resp);
return;
// } catch( EBaseException eAudit1 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_AUTH,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_AUTH,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit1;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit1;
} catch (IOException eAudit2) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -1267,40 +1269,39 @@ public class AuthAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit2;
// } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_AUTH,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_AUTH,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
}
}
/**
- * used for getting the required configuration parameters (with
- * possible default values) for a particular auth manager plugin
- * implementation name specified in the RS_ID. Actually, there is
- * no logic in here to set any default value here...there's no
- * default value for any parameter in this authentication subsystem
- * at this point. Later, if we do have one (or some), it can be
- * added. The interface remains the same.
+ * used for getting the required configuration parameters (with possible
+ * default values) for a particular auth manager plugin implementation name
+ * specified in the RS_ID. Actually, there is no logic in here to set any
+ * default value here...there's no default value for any parameter in this
+ * authentication subsystem at this point. Later, if we do have one (or
+ * some), it can be added. The interface remains the same.
*/
- private synchronized void getConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException, EBaseException {
+ private synchronized void getConfig(HttpServletRequest req,
+ HttpServletResponse resp)
+ throws ServletException, IOException, EBaseException {
String implname = req.getParameter(Constants.RS_ID);
if (implname == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
@@ -1318,25 +1319,25 @@ public class AuthAdminServlet extends AdminServlet {
return;
}
- private synchronized void getInstConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ private synchronized void getInstConfig(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String id = req.getParameter(Constants.RS_ID);
if (id == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
// does auth manager instance exist?
if (mAuths.getInstances().containsKey(id) == false) {
sendResponse(ERROR,
- new EAuthMgrNotFound(CMS.getUserMessage(getLocale(req),"CMS_AUTHENTICATION_AUTHMGR_NOT_FOUND", id)).toString(),
- null, resp);
+ new EAuthMgrNotFound(CMS.getUserMessage(getLocale(req), "CMS_AUTHENTICATION_AUTHMGR_NOT_FOUND", id)).toString(),
+ null, resp);
return;
}
@@ -1365,29 +1366,29 @@ public class AuthAdminServlet extends AdminServlet {
}
/**
- * Modify authentication manager instance
- * This will actually create a new instance with new configuration
- * parameters and replace the old instance if the new instance is
- * created and initialized successfully.
- * The old instance is left running, so this is very expensive.
- * Restart of server recommended.
+ * Modify authentication manager instance This will actually create a new
+ * instance with new configuration parameters and replace the old instance
+ * if the new instance is created and initialized successfully. The old
+ * instance is left running, so this is very expensive. Restart of server
+ * recommended.
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_AUTH used when configuring
* authentication
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @param scope string used to obtain the contents of this authentication
- * manager's substore
+ * manager's substore
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
* @exception EBaseException an error has occurred
*/
- private synchronized void modAuthMgrInst(HttpServletRequest req,
- HttpServletResponse resp, String scope)
- throws ServletException, IOException, EBaseException {
+ private synchronized void modAuthMgrInst(HttpServletRequest req,
+ HttpServletResponse resp, String scope)
+ throws ServletException, IOException, EBaseException {
// expensive operation.
@@ -1409,18 +1410,18 @@ public class AuthAdminServlet extends AdminServlet {
audit(auditMessage);
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
// prevent modification of admin and agent.
if (id.equals(IAuthSubsystem.PASSWDUSERDB_AUTHMGR_ID) ||
- id.equals(IAuthSubsystem.CERTUSERDB_AUTHMGR_ID)) {
+ id.equals(IAuthSubsystem.CERTUSERDB_AUTHMGR_ID)) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_BASE_PERMISSION_DENIED"), null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_BASE_PERMISSION_DENIED"), null, resp);
}
// Does the manager instance exist?
@@ -1435,8 +1436,8 @@ public class AuthAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage("CMS_AUTHENTICATION_MGR_IMPL_NOT_FOUND"),
- null, resp);
+ CMS.getUserMessage("CMS_AUTHENTICATION_MGR_IMPL_NOT_FOUND"),
+ null, resp);
return;
}
@@ -1454,14 +1455,14 @@ public class AuthAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage("CMS_AUTHENTICATION_MISSING_PARAMS"),
- null, resp);
+ CMS.getUserMessage("CMS_AUTHENTICATION_MISSING_PARAMS"),
+ null, resp);
return;
}
- // get plugin for implementation
+ // get plugin for implementation
AuthMgrPlugin plugin =
- (AuthMgrPlugin) mAuths.getPlugins().get(implname);
+ (AuthMgrPlugin) mAuths.getPlugins().get(implname);
if (plugin == null) {
// store a message in the signed audit log file
@@ -1474,15 +1475,15 @@ public class AuthAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- new EAuthMgrPluginNotFound(CMS.getUserMessage(getLocale(req),"CMS_AUTHENTICATION_AUTHMGR_NOT_FOUND", implname)).toString(),
- null, resp);
+ new EAuthMgrPluginNotFound(CMS.getUserMessage(getLocale(req), "CMS_AUTHENTICATION_AUTHMGR_NOT_FOUND", implname)).toString(),
+ null, resp);
return;
}
- // save old instance substore params in case new one fails.
+ // save old instance substore params in case new one fails.
- IAuthManager oldinst =
- (IAuthManager) mAuths.get(id);
+ IAuthManager oldinst =
+ (IAuthManager) mAuths.get(id);
IConfigStore oldConfig = oldinst.getConfigStore();
String[] oldConfigParms = oldinst.getConfigParams();
@@ -1490,7 +1491,7 @@ public class AuthAdminServlet extends AdminServlet {
// implName is always required so always include it it.
saveParams.add(IAuthSubsystem.PROP_PLUGIN,
- (String) oldConfig.get(IAuthSubsystem.PROP_PLUGIN));
+ (String) oldConfig.get(IAuthSubsystem.PROP_PLUGIN));
if (oldConfigParms != null) {
for (int i = 0; i < oldConfigParms.length; i++) {
String key = oldConfigParms[i];
@@ -1507,9 +1508,9 @@ public class AuthAdminServlet extends AdminServlet {
// remove old substore.
IConfigStore destStore =
- mConfig.getSubStore(DestDef.DEST_AUTH_ADMIN);
+ mConfig.getSubStore(DestDef.DEST_AUTH_ADMIN);
IConfigStore instancesConfig =
- destStore.getSubStore(scope);
+ destStore.getSubStore(scope);
instancesConfig.removeSubStore(id);
@@ -1551,8 +1552,8 @@ public class AuthAdminServlet extends AdminServlet {
// cleanup
restore(instancesConfig, id, saveParams);
sendResponse(ERROR,
- new EAuthException(CMS.getUserMessage(getLocale(req),"CMS_AUTHENTICATION_LOAD_CLASS_FAIL", className)).toString(),
- null, resp);
+ new EAuthException(CMS.getUserMessage(getLocale(req), "CMS_AUTHENTICATION_LOAD_CLASS_FAIL", className)).toString(),
+ null, resp);
return;
} catch (InstantiationException e) {
// store a message in the signed audit log file
@@ -1566,8 +1567,8 @@ public class AuthAdminServlet extends AdminServlet {
restore(instancesConfig, id, saveParams);
sendResponse(ERROR,
- new EAuthException(CMS.getUserMessage(getLocale(req),"CMS_AUTHENTICATION_LOAD_CLASS_FAIL", className)).toString(),
- null, resp);
+ new EAuthException(CMS.getUserMessage(getLocale(req), "CMS_AUTHENTICATION_LOAD_CLASS_FAIL", className)).toString(),
+ null, resp);
return;
} catch (IllegalAccessException e) {
// store a message in the signed audit log file
@@ -1581,8 +1582,8 @@ public class AuthAdminServlet extends AdminServlet {
restore(instancesConfig, id, saveParams);
sendResponse(ERROR,
- new EAuthException(CMS.getUserMessage(getLocale(req),"CMS_AUTHENTICATION_LOAD_CLASS_FAIL", className)).toString(),
- null, resp);
+ new EAuthException(CMS.getUserMessage(getLocale(req), "CMS_AUTHENTICATION_LOAD_CLASS_FAIL", className)).toString(),
+ null, resp);
return;
}
@@ -1606,7 +1607,7 @@ public class AuthAdminServlet extends AdminServlet {
return;
}
- // initialized ok. commiting
+ // initialized ok. commiting
try {
mConfig.commit(true);
} catch (EBaseException e) {
@@ -1621,10 +1622,10 @@ public class AuthAdminServlet extends AdminServlet {
// clean up.
restore(instancesConfig, id, saveParams);
- //System.out.println("SRVLT_FAIL_COMMIT");
+ // System.out.println("SRVLT_FAIL_COMMIT");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
+ null, resp);
return;
}
@@ -1632,8 +1633,8 @@ public class AuthAdminServlet extends AdminServlet {
mAuths.add(id, newMgrInst);
- mAuths.log(ILogger.LL_INFO,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_MGR_REPL", id));
+ mAuths.log(ILogger.LL_INFO,
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_MGR_REPL", id));
NameValuePairs params = new NameValuePairs();
@@ -1673,23 +1674,23 @@ public class AuthAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit2;
// } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_AUTH,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_AUTH,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
}
}
// convenience routine.
- private static void restore(IConfigStore store,
- String id, NameValuePairs saveParams) {
+ private static void restore(IConfigStore store,
+ String id, NameValuePairs saveParams) {
store.removeSubStore(id);
IConfigStore rstore = store.makeSubStore(id);
@@ -1699,7 +1700,7 @@ public class AuthAdminServlet extends AdminServlet {
String key = (String) keys.nextElement();
String value = saveParams.getValue(key);
- if (value != null)
+ if (value != null)
rstore.put(key, value);
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/admin/AuthCredentials.java b/pki/base/common/src/com/netscape/cms/servlet/admin/AuthCredentials.java
index bfa9cccd..cca86dce 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/admin/AuthCredentials.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/admin/AuthCredentials.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.admin;
-
import java.util.Enumeration;
import java.util.Hashtable;
@@ -25,11 +24,10 @@ import com.netscape.certsrv.authentication.IAuthCredentials;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IArgBlock;
-
/**
* Authentication Credentials as input to the authMgr
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class AuthCredentials implements IAuthCredentials {
@@ -38,21 +36,23 @@ public class AuthCredentials implements IAuthCredentials {
*/
private static final long serialVersionUID = -6938644716486895814L;
private Hashtable authCreds = null;
- // Inserted by bskim
+ // Inserted by bskim
private IArgBlock argblk = null;
+
// Insert end
-
+
public AuthCredentials() {
authCreds = new Hashtable();
}
/**
* sets a credential with credential name and the credential
+ *
* @param name credential name
* @param cred credential
* @exception com.netscape.certsrv.base.EBaseException NullPointerException
*/
- public void set(String name, Object cred)throws EBaseException {
+ public void set(String name, Object cred) throws EBaseException {
if (cred == null) {
throw new EBaseException("AuthCredentials.set()");
}
@@ -62,7 +62,8 @@ public class AuthCredentials implements IAuthCredentials {
/**
* returns the credential to which the specified name is mapped in this
- * credential set
+ * credential set
+ *
* @param name credential name
* @return the named authentication credential
*/
@@ -71,9 +72,10 @@ public class AuthCredentials implements IAuthCredentials {
}
/**
- * removes the name and its corresponding credential from this
- * credential set. This method does nothing if the named
- * credential is not in the credential set.
+ * removes the name and its corresponding credential from this credential
+ * set. This method does nothing if the named credential is not in the
+ * credential set.
+ *
* @param name credential name
*/
public void delete(String name) {
@@ -81,27 +83,27 @@ public class AuthCredentials implements IAuthCredentials {
}
/**
- * returns an enumeration of the credentials in this credential
- * set. Use the Enumeration methods on the returned object to
- * fetch the elements sequentially.
+ * returns an enumeration of the credentials in this credential set. Use the
+ * Enumeration methods on the returned object to fetch the elements
+ * sequentially.
+ *
* @return an enumeration of the values in this credential set
* @see java.util.Enumeration
*/
public Enumeration getElements() {
return (authCreds.elements());
}
-
+
// Inserted by bskim
public void setArgBlock(IArgBlock blk) {
argblk = blk;
return;
- }
+ }
// Insert end
-
+
public IArgBlock getArgBlock() {
return argblk;
- }
+ }
// Insert end
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/admin/CAAdminServlet.java b/pki/base/common/src/com/netscape/cms/servlet/admin/CAAdminServlet.java
index 0ae51ce4..a70d5130 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/admin/CAAdminServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/admin/CAAdminServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.admin;
-
import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;
@@ -45,13 +44,11 @@ import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.request.IRequestListener;
import com.netscape.cmsutil.util.Utils;
-
/**
- * A class representings an administration servlet for Certificate
- * Authority. This servlet is responsible to serve CA
- * administrative operations such as configuration parameter
- * updates.
- *
+ * A class representings an administration servlet for Certificate Authority.
+ * This servlet is responsible to serve CA administrative operations such as
+ * configuration parameter updates.
+ *
* @version $Revision$, $Date$
*/
public class CAAdminServlet extends AdminServlet {
@@ -66,7 +63,7 @@ public class CAAdminServlet extends AdminServlet {
private final static String INFO = "CAAdminServlet";
private final static String LOGGING_SIGNED_AUDIT_CONFIG_CRL_PROFILE =
- "LOGGING_SIGNED_AUDIT_CONFIG_CRL_PROFILE_3";
+ "LOGGING_SIGNED_AUDIT_CONFIG_CRL_PROFILE_3";
private ICertificateAuthority mCA = null;
protected static final String PROP_ENABLED = "enabled";
@@ -94,22 +91,22 @@ public class CAAdminServlet extends AdminServlet {
}
/**
- * Serves HTTP request. Each request is authenticated to
- * the authenticate manager.
+ * Serves HTTP request. Each request is authenticated to the authenticate
+ * manager.
*/
public void service(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
+ throws ServletException, IOException {
super.service(req, resp);
-
- //get all operational flags
+
+ // get all operational flags
String op = req.getParameter(Constants.OP_TYPE);
String scope = req.getParameter(Constants.OP_SCOPE);
- //check operational flags
+ // check operational flags
if ((op == null) || (scope == null)) {
sendResponse(1, "Invalid Protocol", null, resp);
return;
- }
+ }
super.authenticate(req);
@@ -120,8 +117,8 @@ public class CAAdminServlet extends AdminServlet {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
getExtendedPluginInfo(req, resp);
@@ -135,8 +132,8 @@ public class CAAdminServlet extends AdminServlet {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_GENERAL))
@@ -159,8 +156,8 @@ public class CAAdminServlet extends AdminServlet {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_GENERAL))
@@ -171,9 +168,9 @@ public class CAAdminServlet extends AdminServlet {
setCRLIPsConfig(req, resp);
else if (scope.equals(ScopeDef.SC_CRL))
setCRLConfig(req, resp);
- else if (scope.equals(ScopeDef.SC_NOTIFICATION_REQ_COMP))
+ else if (scope.equals(ScopeDef.SC_NOTIFICATION_REQ_COMP))
setNotificationReqCompConfig(req, resp);
- else if (scope.equals(ScopeDef.SC_NOTIFICATION_REV_COMP))
+ else if (scope.equals(ScopeDef.SC_NOTIFICATION_REV_COMP))
setNotificationRevCompConfig(req, resp);
else if (scope.equals(ScopeDef.SC_NOTIFICATION_RIQ))
setNotificationRIQConfig(req, resp);
@@ -183,8 +180,8 @@ public class CAAdminServlet extends AdminServlet {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_CRLEXTS_RULES))
@@ -195,8 +192,8 @@ public class CAAdminServlet extends AdminServlet {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_CRLIPS))
@@ -205,8 +202,8 @@ public class CAAdminServlet extends AdminServlet {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_CRLIPS))
@@ -220,23 +217,24 @@ public class CAAdminServlet extends AdminServlet {
}
}
- /*==========================================================
- * private methods
- *==========================================================*/
-
+ /*
+ * ========================================================== private
+ * methods==========================================================
+ */
+
/*
* handle request completion (cert issued) notification config requests
*/
private void getNotificationCompConfig(HttpServletRequest req,
- HttpServletResponse resp, IConfigStore rc) throws ServletException,
+ HttpServletResponse resp, IConfigStore rc) throws ServletException,
IOException, EBaseException {
-
+
NameValuePairs params = new NameValuePairs();
Enumeration e = req.getParameterNames();
-
+
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
-
+
if (name.equals(Constants.OP_TYPE))
continue;
if (name.equals(Constants.RS_ID))
@@ -247,33 +245,33 @@ public class CAAdminServlet extends AdminServlet {
continue;
params.add(name, rc.getString(name, ""));
}
-
+
params.add(Constants.PR_ENABLE,
- rc.getString(PROP_ENABLED, Constants.FALSE));
+ rc.getString(PROP_ENABLED, Constants.FALSE));
sendResponse(SUCCESS, null, params, resp);
}
-
+
private void getNotificationRevCompConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
-
+
IConfigStore config = mCA.getConfigStore();
IConfigStore nc =
- config.getSubStore(ICertificateAuthority.PROP_NOTIFY_SUBSTORE);
+ config.getSubStore(ICertificateAuthority.PROP_NOTIFY_SUBSTORE);
IConfigStore rc = nc.getSubStore(ICertificateAuthority.PROP_CERT_REVOKED_SUBSTORE);
-
+
getNotificationCompConfig(req, resp, rc);
}
-
+
private void getNotificationReqCompConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
-
+
IConfigStore config = mCA.getConfigStore();
IConfigStore nc =
- config.getSubStore(ICertificateAuthority.PROP_NOTIFY_SUBSTORE);
+ config.getSubStore(ICertificateAuthority.PROP_NOTIFY_SUBSTORE);
IConfigStore rc = nc.getSubStore(ICertificateAuthority.PROP_CERT_ISSUED_SUBSTORE);
-
+
getNotificationCompConfig(req, resp, rc);
}
@@ -281,14 +279,14 @@ public class CAAdminServlet extends AdminServlet {
* handle getting request in queue notification config info
*/
private void getNotificationRIQConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
IConfigStore config = mCA.getConfigStore();
IConfigStore nc =
- config.getSubStore(ICertificateAuthority.PROP_NOTIFY_SUBSTORE);
+ config.getSubStore(ICertificateAuthority.PROP_NOTIFY_SUBSTORE);
IConfigStore riq = nc.getSubStore(ICertificateAuthority.PROP_REQ_IN_Q_SUBSTORE);
@@ -308,8 +306,8 @@ public class CAAdminServlet extends AdminServlet {
params.add(name, riq.getString(name, ""));
}
- params.add(Constants.PR_ENABLE,
- riq.getString(PROP_ENABLED, Constants.FALSE));
+ params.add(Constants.PR_ENABLE,
+ riq.getString(PROP_ENABLED, Constants.FALSE));
sendResponse(SUCCESS, null, params, resp);
}
@@ -317,15 +315,15 @@ public class CAAdminServlet extends AdminServlet {
* handle setting request in queue notification config info
*/
private void setNotificationRIQConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
IConfigStore config = mCA.getConfigStore();
IConfigStore nc =
- config.getSubStore(ICertificateAuthority.PROP_NOTIFY_SUBSTORE);
+ config.getSubStore(ICertificateAuthority.PROP_NOTIFY_SUBSTORE);
IConfigStore riq = nc.getSubStore(ICertificateAuthority.PROP_REQ_IN_Q_SUBSTORE);
- //set rest of the parameters
+ // set rest of the parameters
Enumeration e = req.getParameterNames();
while (e.hasMoreElements()) {
@@ -346,15 +344,15 @@ public class CAAdminServlet extends AdminServlet {
File template = new File(val);
if ((!template.exists()) || (!template.canRead())
- || (template.isDirectory())) {
+ || (template.isDirectory())) {
String error =
- "Template: " + val + " does not exist or invalid";
+ "Template: " + val + " does not exist or invalid";
log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_INVALID_PATH"));
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_PATH"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_PATH"),
+ null, resp);
return;
}
}
@@ -377,10 +375,10 @@ public class CAAdminServlet extends AdminServlet {
* handle setting request complete notification config info
*/
private void setNotificationCompConfig(HttpServletRequest req,
- HttpServletResponse resp, IConfigStore rc, IRequestListener thisListener) throws ServletException,
+ HttpServletResponse resp, IConfigStore rc, IRequestListener thisListener) throws ServletException,
IOException, EBaseException {
-
- //set rest of the parameters
+
+ // set rest of the parameters
Enumeration e = req.getParameterNames();
while (e.hasMoreElements()) {
@@ -401,15 +399,15 @@ public class CAAdminServlet extends AdminServlet {
File template = new File(val);
if ((!template.exists()) || (!template.canRead())
- || (template.isDirectory())) {
+ || (template.isDirectory())) {
String error =
- "Template: " + val + " does not exist or invalid";
+ "Template: " + val + " does not exist or invalid";
log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_INVALID_PATH"));
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_PATH"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_PATH"),
+ null, resp);
return;
}
}
@@ -429,23 +427,23 @@ public class CAAdminServlet extends AdminServlet {
}
private void setNotificationRevCompConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
IConfigStore config = mCA.getConfigStore();
IConfigStore nc =
- config.getSubStore(ICertificateAuthority.PROP_NOTIFY_SUBSTORE);
+ config.getSubStore(ICertificateAuthority.PROP_NOTIFY_SUBSTORE);
- IConfigStore rc = nc.getSubStore(ICertificateAuthority.PROP_CERT_REVOKED_SUBSTORE);
+ IConfigStore rc = nc.getSubStore(ICertificateAuthority.PROP_CERT_REVOKED_SUBSTORE);
setNotificationCompConfig(req, resp, rc, mCA.getCertRevokedListener());
- }
+ }
private void setNotificationReqCompConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
IConfigStore config = mCA.getConfigStore();
IConfigStore nc =
- config.getSubStore(ICertificateAuthority.PROP_NOTIFY_SUBSTORE);
+ config.getSubStore(ICertificateAuthority.PROP_NOTIFY_SUBSTORE);
IConfigStore rc = nc.getSubStore(ICertificateAuthority.PROP_CERT_ISSUED_SUBSTORE);
@@ -454,8 +452,8 @@ public class CAAdminServlet extends AdminServlet {
}
private void listCRLIPsConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException, EBaseException {
+ HttpServletResponse resp)
+ throws ServletException, IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
Enumeration ips = mCA.getCRLIssuingPoints();
@@ -469,16 +467,16 @@ public class CAAdminServlet extends AdminServlet {
if (ipId != null && ipId.length() > 0)
params.add(ipId, ip.getDescription());
params.add(ipId + "." + Constants.PR_ENABLED,
- (Boolean.valueOf(ip.isCRLIssuingPointEnabled())).toString());
+ (Boolean.valueOf(ip.isCRLIssuingPointEnabled())).toString());
}
}
-
+
sendResponse(SUCCESS, null, params, resp);
}
private void getCRLIPsConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException, EBaseException {
+ HttpServletResponse resp)
+ throws ServletException, IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
String id = req.getParameter(Constants.RS_ID);
@@ -518,11 +516,12 @@ public class CAAdminServlet extends AdminServlet {
/**
* Add CRL issuing points configuration
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_CRL_PROFILE used when
* configuring CRL profile (extensions, frequency, CRL format)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
@@ -530,8 +529,8 @@ public class CAAdminServlet extends AdminServlet {
* @exception EBaseException an error has occurred
*/
private void addCRLIPsConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException, EBaseException {
+ HttpServletResponse resp)
+ throws ServletException, IOException, EBaseException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -578,7 +577,7 @@ public class CAAdminServlet extends AdminServlet {
boolean enable = true;
if (sEnable != null && sEnable.length() > 0 &&
- sEnable.equalsIgnoreCase(Constants.FALSE)) {
+ sEnable.equalsIgnoreCase(Constants.FALSE)) {
enable = false;
params.add(Constants.PR_ENABLED, Constants.FALSE);
} else {
@@ -586,7 +585,7 @@ public class CAAdminServlet extends AdminServlet {
}
IConfigStore crlSubStore =
- mCA.getConfigStore().getSubStore(ICertificateAuthority.PROP_CRL_SUBSTORE);
+ mCA.getConfigStore().getSubStore(ICertificateAuthority.PROP_CRL_SUBSTORE);
Enumeration crlNames = crlSubStore.getSubStoreNames();
while (crlNames.hasMoreElements()) {
@@ -656,28 +655,29 @@ public class CAAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit2;
// } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_CRL_PROFILE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_CRL_PROFILE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
}
}
/**
* Set CRL issuing points configuration
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_CRL_PROFILE used when
* configuring CRL profile (extensions, frequency, CRL format)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
@@ -685,8 +685,8 @@ public class CAAdminServlet extends AdminServlet {
* @exception EBaseException an error has occurred
*/
private void setCRLIPsConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException, EBaseException {
+ HttpServletResponse resp)
+ throws ServletException, IOException, EBaseException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -733,7 +733,7 @@ public class CAAdminServlet extends AdminServlet {
boolean enable = true;
if (sEnable != null && sEnable.length() > 0 &&
- sEnable.equalsIgnoreCase(Constants.FALSE)) {
+ sEnable.equalsIgnoreCase(Constants.FALSE)) {
enable = false;
params.add(Constants.PR_ENABLED, Constants.FALSE);
} else {
@@ -741,7 +741,7 @@ public class CAAdminServlet extends AdminServlet {
}
IConfigStore crlSubStore =
- mCA.getConfigStore().getSubStore(ICertificateAuthority.PROP_CRL_SUBSTORE);
+ mCA.getConfigStore().getSubStore(ICertificateAuthority.PROP_CRL_SUBSTORE);
boolean done = false;
Enumeration crlNames = crlSubStore.getSubStoreNames();
@@ -759,8 +759,8 @@ public class CAAdminServlet extends AdminServlet {
if (c != null) {
c.putString(Constants.PR_DESCRIPTION, desc);
- c.putString(Constants.PR_ENABLED,
- (enable) ? Constants.TRUE : Constants.FALSE);
+ c.putString(Constants.PR_ENABLED,
+ (enable) ? Constants.TRUE : Constants.FALSE);
}
done = true;
break;
@@ -816,28 +816,29 @@ public class CAAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit2;
// } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_CRL_PROFILE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_CRL_PROFILE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
}
}
/**
* Delete CRL issuing points configuration
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_CRL_PROFILE used when
* configuring CRL profile (extensions, frequency, CRL format)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
@@ -845,8 +846,8 @@ public class CAAdminServlet extends AdminServlet {
* @exception EBaseException an error has occurred
*/
private void deleteCRLIPsConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException, EBaseException {
+ HttpServletResponse resp)
+ throws ServletException, IOException, EBaseException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -859,7 +860,7 @@ public class CAAdminServlet extends AdminServlet {
if (id != null && id.length() > 0) {
IConfigStore crlSubStore =
- mCA.getConfigStore().getSubStore(ICertificateAuthority.PROP_CRL_SUBSTORE);
+ mCA.getConfigStore().getSubStore(ICertificateAuthority.PROP_CRL_SUBSTORE);
boolean done = false;
Enumeration crlNames = crlSubStore.getSubStoreNames();
@@ -923,23 +924,23 @@ public class CAAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit2;
// } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_CRL_PROFILE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_CRL_PROFILE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
}
}
private void getCRLExtsConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException, EBaseException {
+ HttpServletResponse resp)
+ throws ServletException, IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
String ipId = null;
@@ -974,11 +975,12 @@ public class CAAdminServlet extends AdminServlet {
/**
* Delete CRL extensions configuration
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_CRL_PROFILE used when
* configuring CRL profile (extensions, frequency, CRL format)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
@@ -986,8 +988,8 @@ public class CAAdminServlet extends AdminServlet {
* @exception EBaseException an error has occurred
*/
private void setCRLExtsConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException, EBaseException {
+ HttpServletResponse resp)
+ throws ServletException, IOException, EBaseException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -1007,10 +1009,10 @@ public class CAAdminServlet extends AdminServlet {
IConfigStore config = mCA.getConfigStore();
IConfigStore crlsSubStore =
- config.getSubStore(ICertificateAuthority.PROP_CRL_SUBSTORE);
+ config.getSubStore(ICertificateAuthority.PROP_CRL_SUBSTORE);
IConfigStore crlSubStore = crlsSubStore.getSubStore(ipId);
IConfigStore crlExtsSubStore =
- crlSubStore.getSubStore(ICertificateAuthority.PROP_CRLEXT_SUBSTORE);
+ crlSubStore.getSubStore(ICertificateAuthority.PROP_CRLEXT_SUBSTORE);
String id = req.getParameter(Constants.RS_ID);
@@ -1077,23 +1079,23 @@ public class CAAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit2;
// } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_CRL_PROFILE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_CRL_PROFILE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
}
}
private void listCRLExtsConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException, EBaseException {
+ HttpServletResponse resp)
+ throws ServletException, IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
String id = req.getParameter(Constants.PR_ID);
@@ -1130,12 +1132,12 @@ public class CAAdminServlet extends AdminServlet {
sendResponse(SUCCESS, null, params, resp);
}
- /**
- * retrieve extended plugin info such as brief description,
- * type info from CRL extensions
+ /**
+ * retrieve extended plugin info such as brief description, type info from
+ * CRL extensions
*/
private void getExtendedPluginInfo(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String id = req.getParameter(Constants.RS_ID);
int colon = id.indexOf(':');
@@ -1143,8 +1145,8 @@ public class CAAdminServlet extends AdminServlet {
String implType = id.substring(0, colon);
String implName = id.substring(colon + 1);
- NameValuePairs params =
- getExtendedPluginInfo(getLocale(req), implType, implName);
+ NameValuePairs params =
+ getExtendedPluginInfo(getLocale(req), implType, implName);
sendResponse(SUCCESS, null, params, resp);
}
@@ -1191,11 +1193,12 @@ public class CAAdminServlet extends AdminServlet {
/**
* Set CRL configuration
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_CRL_PROFILE used when
* configuring CRL profile (extensions, frequency, CRL format)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
@@ -1203,7 +1206,7 @@ public class CAAdminServlet extends AdminServlet {
* @exception EBaseException an error has occurred
*/
private void setCRLConfig(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException, EBaseException {
+ throws ServletException, IOException, EBaseException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -1215,17 +1218,17 @@ public class CAAdminServlet extends AdminServlet {
String id = req.getParameter(Constants.RS_ID);
if (id == null || id.length() <= 0 ||
- id.equals(Constants.RS_ID_CONFIG)) {
+ id.equals(Constants.RS_ID_CONFIG)) {
id = ICertificateAuthority.PROP_MASTER_CRL;
}
ICRLIssuingPoint ip = mCA.getCRLIssuingPoint(id);
- //Save New Settings to the config file
+ // Save New Settings to the config file
IConfigStore config = mCA.getConfigStore();
IConfigStore crlsSubStore = config.getSubStore(ICertificateAuthority.PROP_CRL_SUBSTORE);
IConfigStore crlSubStore = crlsSubStore.getSubStore(id);
- //set reset of the parameters
+ // set reset of the parameters
Enumeration e = req.getParameterNames();
while (e.hasMoreElements()) {
@@ -1286,22 +1289,22 @@ public class CAAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit2;
// } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_CRL_PROFILE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_CRL_PROFILE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
}
}
private void getCRLConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
@@ -1309,11 +1312,11 @@ public class CAAdminServlet extends AdminServlet {
String id = req.getParameter(Constants.RS_ID);
if (id == null || id.length() <= 0 ||
- id.equals(Constants.RS_ID_CONFIG)) {
+ id.equals(Constants.RS_ID_CONFIG)) {
id = ICertificateAuthority.PROP_MASTER_CRL;
}
IConfigStore crlsSubStore =
- mCA.getConfigStore().getSubStore(ICertificateAuthority.PROP_CRL_SUBSTORE);
+ mCA.getConfigStore().getSubStore(ICertificateAuthority.PROP_CRL_SUBSTORE);
IConfigStore crlSubStore = crlsSubStore.getSubStore(id);
Enumeration e = req.getParameterNames();
@@ -1335,9 +1338,9 @@ public class CAAdminServlet extends AdminServlet {
getSigningAlgConfig(params);
sendResponse(SUCCESS, null, params, resp);
}
-
+
private void getConnectorConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
IConfigStore caConfig = mCA.getConfigStore();
IConfigStore connectorConfig = caConfig.getSubStore("connector");
@@ -1370,14 +1373,14 @@ public class CAAdminServlet extends AdminServlet {
}
private void setConnectorConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
IConfigStore caConfig = mCA.getConfigStore();
IConfigStore connectorConfig = caConfig.getSubStore("connector");
IConfigStore caConnectorConfig = null;
-// String nickname = CMS.getServerCertNickname();
+ // String nickname = CMS.getServerCertNickname();
if (isKRAConnector(req)) {
caConnectorConfig = connectorConfig.getSubStore("KRA");
@@ -1397,12 +1400,10 @@ public class CAAdminServlet extends AdminServlet {
continue;
if (name.equals(Constants.OP_SCOPE))
continue;
-/*
- if (name.equals("nickName")) {
- caConnectorConfig.putString(name, nickname);
- continue;
- }
-*/
+ /*
+ * if (name.equals("nickName")) {
+ * caConnectorConfig.putString(name, nickname); continue; }
+ */
if (name.equals("host")) {
try {
Utils.checkHost(req.getParameter("host"));
@@ -1456,27 +1457,23 @@ public class CAAdminServlet extends AdminServlet {
}
private void getGeneralConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
String value = "false";
/*
- ISubsystem eeGateway =
- SubsystemRegistry.getInstance().get("eeGateway");
- if (eeGateway != null) {
- IConfigStore eeConfig = eeGateway.getConfigStore();
- if (eeConfig != null)
- value = eeConfig.getString("enabled", "true");
- String ocspValue = "true";
- ocspValue = eeConfig.getString("enableOCSP", "true");
- params.add(Constants.PR_OCSP_ENABLED, ocspValue);
- }
- params.add(Constants.PR_EE_ENABLED, value);
+ * ISubsystem eeGateway =
+ * SubsystemRegistry.getInstance().get("eeGateway"); if (eeGateway !=
+ * null) { IConfigStore eeConfig = eeGateway.getConfigStore(); if
+ * (eeConfig != null) value = eeConfig.getString("enabled", "true");
+ * String ocspValue = "true"; ocspValue =
+ * eeConfig.getString("enableOCSP", "true");
+ * params.add(Constants.PR_OCSP_ENABLED, ocspValue); }
+ * params.add(Constants.PR_EE_ENABLED, value);
*/
-
IConfigStore caConfig = mCA.getConfigStore();
value = caConfig.getString(ICertificateAuthority.PROP_ENABLE_PAST_CATIME, "false");
@@ -1485,18 +1482,18 @@ public class CAAdminServlet extends AdminServlet {
getSigningAlgConfig(params);
getSerialConfig(params);
getMaxSerialConfig(params);
-
+
sendResponse(SUCCESS, null, params, resp);
}
private void getSigningAlgConfig(NameValuePairs params) {
params.add(Constants.PR_DEFAULT_ALGORITHM,
- mCA.getDefaultAlgorithm());
+ mCA.getDefaultAlgorithm());
String[] algorithms = mCA.getCASigningAlgorithms();
StringBuffer algorStr = new StringBuffer();
for (int i = 0; i < algorithms.length; i++) {
- if (i == 0)
+ if (i == 0)
algorStr.append(algorithms[i]);
else {
algorStr.append(":");
@@ -1508,23 +1505,23 @@ public class CAAdminServlet extends AdminServlet {
private void getSerialConfig(NameValuePairs params) {
params.add(Constants.PR_SERIAL,
- mCA.getStartSerial());
+ mCA.getStartSerial());
}
private void getMaxSerialConfig(NameValuePairs params) {
params.add(Constants.PR_MAXSERIAL,
- mCA.getMaxSerial());
+ mCA.getMaxSerial());
}
private void setGeneralConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
ISubsystem eeGateway = null;
/*
- ISubsystem eeGateway =
- SubsystemRegistry.getInstance().get("eeGateway");
+ * ISubsystem eeGateway =
+ * SubsystemRegistry.getInstance().get("eeGateway");
*/
IConfigStore eeConfig = null;
@@ -1533,7 +1530,7 @@ public class CAAdminServlet extends AdminServlet {
Enumeration enum1 = req.getParameterNames();
boolean restart = false;
- //mCA.setMaxSerial("");
+ // mCA.setMaxSerial("");
while (enum1.hasMoreElements()) {
String key = (String) enum1.nextElement();
String value = req.getParameter(key);
@@ -1541,15 +1538,11 @@ public class CAAdminServlet extends AdminServlet {
if (key.equals(Constants.PR_EE_ENABLED)) {
/*
- if (eeConfig != null) {
- if (((EEGateway)eeGateway).isEnabled() &&
- value.equals("false") ||
- !((EEGateway)eeGateway).isEnabled() &&
- value.equals("true")) {
- restart=true;;
- }
- eeConfig.putString("enabled", value);
- }
+ * if (eeConfig != null) { if
+ * (((EEGateway)eeGateway).isEnabled() && value.equals("false")
+ * || !((EEGateway)eeGateway).isEnabled() &&
+ * value.equals("true")) { restart=true;; }
+ * eeConfig.putString("enabled", value); }
*/
} else if (key.equals(Constants.PR_VALIDITY)) {
mCA.setValidity(value);
@@ -1573,6 +1566,6 @@ public class CAAdminServlet extends AdminServlet {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_OTHER,
- level, "CAAdminServlet: " + msg);
+ level, "CAAdminServlet: " + msg);
}
-}
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/admin/CMSAdminServlet.java b/pki/base/common/src/com/netscape/cms/servlet/admin/CMSAdminServlet.java
index 3251e46b..f55ba57b 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/admin/CMSAdminServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/admin/CMSAdminServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.admin;
-
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
@@ -82,11 +81,10 @@ import com.netscape.cmsutil.util.Cert;
import com.netscape.symkey.SessionKey;
/**
- * A class representings an administration servlet. This
- * servlet is responsible to serve Certificate Server
- * level administrative operations such as configuration
- * parameter updates.
- *
+ * A class representings an administration servlet. This servlet is responsible
+ * to serve Certificate Server level administrative operations such as
+ * configuration parameter updates.
+ *
* @version $Revision$, $Date$
*/
public final class CMSAdminServlet extends AdminServlet {
@@ -108,13 +106,13 @@ public final class CMSAdminServlet extends AdminServlet {
private ILogger mSignedAuditLogger = CMS.getSignedAuditLogger();
private final static byte EOL[] = { Character.LINE_SEPARATOR };
private final static String LOGGING_SIGNED_AUDIT_CONFIG_ENCRYPTION =
- "LOGGING_SIGNED_AUDIT_CONFIG_ENCRYPTION_3";
+ "LOGGING_SIGNED_AUDIT_CONFIG_ENCRYPTION_3";
private final static String LOGGING_SIGNED_AUDIT_CONFIG_TRUSTED_PUBLIC_KEY =
- "LOGGING_SIGNED_AUDIT_CONFIG_TRUSTED_PUBLIC_KEY_3";
+ "LOGGING_SIGNED_AUDIT_CONFIG_TRUSTED_PUBLIC_KEY_3";
private final static String LOGGING_SIGNED_AUDIT_KEY_GEN_ASYMMETRIC =
- "LOGGING_SIGNED_AUDIT_KEY_GEN_ASYMMETRIC_3";
+ "LOGGING_SIGNED_AUDIT_KEY_GEN_ASYMMETRIC_3";
private final static String LOGGING_SIGNED_AUDIT_SELFTESTS_EXECUTION =
- "LOGGING_SIGNED_AUDIT_SELFTESTS_EXECUTION_2";
+ "LOGGING_SIGNED_AUDIT_SELFTESTS_EXECUTION_2";
private final static String LOGGING_SIGNED_AUDIT_CIMC_CERT_VERIFICATION =
"LOGGING_SIGNED_AUDIT_CIMC_CERT_VERIFICATION_3";
@@ -145,13 +143,13 @@ public final class CMSAdminServlet extends AdminServlet {
* Serves HTTP request.
*/
public void service(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
+ throws ServletException, IOException {
super.service(req, resp);
try {
super.authenticate(req);
} catch (IOException e) {
sendResponse(ERROR, CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHS_FAILED"),
- null, resp);
+ null, resp);
return;
}
@@ -164,8 +162,8 @@ public final class CMSAdminServlet extends AdminServlet {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
getEnv(req, resp);
@@ -175,8 +173,8 @@ public final class CMSAdminServlet extends AdminServlet {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_LDAP))
@@ -199,13 +197,13 @@ public final class CMSAdminServlet extends AdminServlet {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_LDAP))
setDBConfig(req, resp);
- else if (scope.equals(ScopeDef.SC_SMTP))
+ else if (scope.equals(ScopeDef.SC_SMTP))
modifySMTPConfig(req, resp);
else if (scope.equals(ScopeDef.SC_TASKS))
performTasks(req, resp);
@@ -213,9 +211,9 @@ public final class CMSAdminServlet extends AdminServlet {
modifyEncryption(req, resp);
else if (scope.equals(ScopeDef.SC_ISSUE_IMPORT_CERT))
issueImportCert(req, resp);
- else if (scope.equals(ScopeDef.SC_INSTALL_CERT))
+ else if (scope.equals(ScopeDef.SC_INSTALL_CERT))
installCert(req, resp);
- else if (scope.equals(ScopeDef.SC_IMPORT_CROSS_CERT))
+ else if (scope.equals(ScopeDef.SC_IMPORT_CROSS_CERT))
importXCert(req, resp);
else if (scope.equals(ScopeDef.SC_DELETE_CERTS))
deleteCerts(req, resp);
@@ -229,8 +227,8 @@ public final class CMSAdminServlet extends AdminServlet {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_SUBSYSTEM))
@@ -239,11 +237,11 @@ public final class CMSAdminServlet extends AdminServlet {
getCACerts(req, resp);
else if (scope.equals(ScopeDef.SC_ALL_CERTLIST))
getAllCertsManage(req, resp);
- else if (scope.equals(ScopeDef.SC_USERCERTSLIST))
+ else if (scope.equals(ScopeDef.SC_USERCERTSLIST))
getUserCerts(req, resp);
- else if (scope.equals(ScopeDef.SC_TKSKEYSLIST))
+ else if (scope.equals(ScopeDef.SC_TKSKEYSLIST))
getTKSKeys(req, resp);
- else if (scope.equals(ScopeDef.SC_TOKEN))
+ else if (scope.equals(ScopeDef.SC_TOKEN))
getAllTokenNames(req, resp);
else if (scope.equals(ScopeDef.SC_ROOTCERTSLIST))
getRootCerts(req, resp);
@@ -251,21 +249,21 @@ public final class CMSAdminServlet extends AdminServlet {
mOp = "delete";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_ROOTCERTSLIST)) {
deleteRootCert(req, resp);
} else if (scope.equals(ScopeDef.SC_USERCERTSLIST)) {
- deleteUserCert(req,resp);
+ deleteUserCert(req, resp);
}
} else if (op.equals(OpDef.OP_PROCESS)) {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_CERT_REQUEST))
@@ -282,14 +280,14 @@ public final class CMSAdminServlet extends AdminServlet {
checkTokenStatus(req, resp);
else if (scope.equals(ScopeDef.SC_SELFTESTS))
runSelfTestsOnDemand(req, resp);
- else if (scope.equals(ScopeDef.SC_TKSKEYSLIST))
+ else if (scope.equals(ScopeDef.SC_TKSKEYSLIST))
createMasterKey(req, resp);
} else if (op.equals(OpDef.OP_VALIDATE)) {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_SUBJECT_NAME))
@@ -303,7 +301,7 @@ public final class CMSAdminServlet extends AdminServlet {
}
} catch (EBaseException e) {
sendResponse(ERROR, e.toString(getLocale(req)),
- null, resp);
+ null, resp);
return;
} catch (Exception e) {
StringWriter sw = new StringWriter();
@@ -316,7 +314,7 @@ public final class CMSAdminServlet extends AdminServlet {
}
private void getEnv(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
@@ -324,16 +322,16 @@ public final class CMSAdminServlet extends AdminServlet {
params.add(Constants.PR_NT, Constants.TRUE);
else
params.add(Constants.PR_NT, Constants.FALSE);
-
+
sendResponse(SUCCESS, null, params, resp);
}
private void getAllTokenNames(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
ICryptoSubsystem jssSubSystem = (ICryptoSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
NameValuePairs params = new NameValuePairs();
params.add(Constants.PR_TOKEN_LIST, jssSubSystem.getTokenList());
@@ -342,15 +340,15 @@ public final class CMSAdminServlet extends AdminServlet {
}
private void getAllNicknames(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
ICryptoSubsystem jssSubSystem = (ICryptoSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
params.add(Constants.PR_ALL_NICKNAMES, jssSubSystem.getAllCerts());
-
+
sendResponse(SUCCESS, null, params, resp);
}
@@ -361,18 +359,18 @@ public final class CMSAdminServlet extends AdminServlet {
String type = "";
ISubsystem sys = (ISubsystem) e.nextElement();
- //get subsystem type
+ // get subsystem type
if ((sys instanceof IKeyRecoveryAuthority) &&
- subsystem.equals("kra"))
+ subsystem.equals("kra"))
return true;
else if ((sys instanceof IRegistrationAuthority) &&
- subsystem.equals("ra"))
+ subsystem.equals("ra"))
return true;
else if ((sys instanceof ICertificateAuthority) &&
- subsystem.equals("ca"))
+ subsystem.equals("ca"))
return true;
else if ((sys instanceof IOCSPAuthority) &&
- subsystem.equals("ocsp"))
+ subsystem.equals("ocsp"))
return true;
}
@@ -380,7 +378,7 @@ public final class CMSAdminServlet extends AdminServlet {
}
private void readEncryption(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
Enumeration<ISubsystem> e = CMS.getSubsystems();
@@ -394,7 +392,7 @@ public final class CMSAdminServlet extends AdminServlet {
String type = "";
ISubsystem sys = (ISubsystem) e.nextElement();
- //get subsystem type
+ // get subsystem type
if (sys instanceof IKeyRecoveryAuthority)
isKRAInstalled = true;
else if (sys instanceof IRegistrationAuthority)
@@ -405,17 +403,17 @@ public final class CMSAdminServlet extends AdminServlet {
isOCSPInstalled = true;
else if (sys instanceof ITKSAuthority)
isTKSInstalled = true;
-
- }
+
+ }
ICryptoSubsystem jssSubSystem = (ICryptoSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
String caTokenName = "";
NameValuePairs params = new NameValuePairs();
params.add(Constants.PR_CIPHER_VERSION,
- jssSubSystem.getCipherVersion());
+ jssSubSystem.getCipherVersion());
params.add(Constants.PR_CIPHER_FORTEZZA, jssSubSystem.isCipherFortezza());
params.add(Constants.PR_CIPHER_PREF, jssSubSystem.getCipherPreferences());
@@ -427,7 +425,7 @@ public final class CMSAdminServlet extends AdminServlet {
while (tokenizer.hasMoreElements()) {
String tokenName = (String) tokenizer.nextElement();
String certs = jssSubSystem.getCertListWithoutTokenName(tokenName);
-
+
if (certs.equals(""))
continue;
if (tokenNewList.equals(""))
@@ -451,13 +449,13 @@ public final class CMSAdminServlet extends AdminServlet {
String caNickName = signingUnit.getNickname();
- //params.add(Constants.PR_CERT_CA, caTokenName+","+caNickName);
+ // params.add(Constants.PR_CERT_CA, caTokenName+","+caNickName);
params.add(Constants.PR_CERT_CA, getCertNickname(caNickName));
}
if (isRAInstalled) {
IRegistrationAuthority ra = (IRegistrationAuthority)
- CMS.getSubsystem(CMS.SUBSYSTEM_RA);
+ CMS.getSubsystem(CMS.SUBSYSTEM_RA);
String raNickname = ra.getNickname();
params.add(Constants.PR_CERT_RA, getCertNickname(raNickname));
@@ -465,17 +463,17 @@ public final class CMSAdminServlet extends AdminServlet {
if (isKRAInstalled) {
IKeyRecoveryAuthority kra = (IKeyRecoveryAuthority)
- CMS.getSubsystem(CMS.SUBSYSTEM_KRA);
+ CMS.getSubsystem(CMS.SUBSYSTEM_KRA);
String kraNickname = kra.getNickname();
params.add(Constants.PR_CERT_TRANS, getCertNickname(kraNickname));
}
if (isTKSInstalled) {
ITKSAuthority tks = (ITKSAuthority)
- CMS.getSubsystem(CMS.SUBSYSTEM_TKS);
+ CMS.getSubsystem(CMS.SUBSYSTEM_TKS);
}
String nickName = CMS.getServerCertNickname();
-
+
params.add(Constants.PR_CERT_SERVER, getCertNickname(nickName));
sendResponse(SUCCESS, null, params, resp);
@@ -517,17 +515,18 @@ public final class CMSAdminServlet extends AdminServlet {
/**
* Modify encryption configuration
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ENCRYPTION used when
* configuring encryption (cert settings and SSL cipher preferences)
* </ul>
+ *
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
* @exception EBaseException failed to modify encryption configuration
*/
private void modifyEncryption(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String auditMessage = null;
@@ -537,10 +536,10 @@ public final class CMSAdminServlet extends AdminServlet {
// to the signed audit log and stored as failures
try {
@SuppressWarnings("unchecked")
- Enumeration<String> enum1 = req.getParameterNames();
+ Enumeration<String> enum1 = req.getParameterNames();
NameValuePairs params = new NameValuePairs();
ICryptoSubsystem jssSubSystem = (ICryptoSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
jssSubSystem.getInternalTokenName();
Enumeration<ISubsystem> e = CMS.getSubsystems();
@@ -554,7 +553,7 @@ public final class CMSAdminServlet extends AdminServlet {
String type = "";
ISubsystem sys = (ISubsystem) e.nextElement();
- //get subsystem type
+ // get subsystem type
if (sys instanceof IKeyRecoveryAuthority)
isKRAInstalled = true;
else if (sys instanceof IRegistrationAuthority)
@@ -563,14 +562,14 @@ public final class CMSAdminServlet extends AdminServlet {
isCAInstalled = true;
else if (sys instanceof IOCSPAuthority)
isOCSPInstalled = true;
- else if (sys instanceof ITKSAuthority)
+ else if (sys instanceof ITKSAuthority)
isTKSInstalled = true;
}
- ICertificateAuthority ca = null;
+ ICertificateAuthority ca = null;
IRegistrationAuthority ra = null;
IKeyRecoveryAuthority kra = null;
- ITKSAuthority tks = null;
+ ITKSAuthority tks = null;
if (isCAInstalled)
ca = (ICertificateAuthority) CMS.getSubsystem(CMS.SUBSYSTEM_CA);
@@ -693,19 +692,19 @@ public final class CMSAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit2;
- // } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_ENCRYPTION,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
- //
- // audit( auditMessage );
- //
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
- }
+ // } catch( ServletException eAudit3 ) {
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_ENCRYPTION,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
+ //
+ // audit( auditMessage );
+ //
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
+ }
}
private String getCertConfigNickname(String val) throws EBaseException {
@@ -727,9 +726,9 @@ public final class CMSAdminServlet extends AdminServlet {
CMS.setServerCertNickname(nickName);
/*
- RemoteAdmin raAdmin = (RemoteAdmin)RemoteAdmin.getInstance();
- HTTPService httpsService = raAdmin.getHttpsService();
- httpsService.setNickName(nickName);
+ * RemoteAdmin raAdmin = (RemoteAdmin)RemoteAdmin.getInstance();
+ * HTTPService httpsService = raAdmin.getHttpsService();
+ * httpsService.setNickName(nickName);
*/
}
@@ -737,9 +736,9 @@ public final class CMSAdminServlet extends AdminServlet {
CMS.setServerCertNickname(nickName);
/*
- AgentGateway gateway = (AgentGateway)mReg.get(AgentGateway.ID);
- HTTPService httpsService = gateway.getHttpsService();
- httpsService.setNickName(nickName);
+ * AgentGateway gateway = (AgentGateway)mReg.get(AgentGateway.ID);
+ * HTTPService httpsService = gateway.getHttpsService();
+ * httpsService.setNickName(nickName);
*/
}
@@ -747,9 +746,9 @@ public final class CMSAdminServlet extends AdminServlet {
CMS.setServerCertNickname(nickName);
/*
- HTTPSubsystem eeGateway = ra.getHTTPSubsystem();
- HTTPService httpsService = eeGateway.getHttpsService();
- httpsService.setNickName(nickName);
+ * HTTPSubsystem eeGateway = ra.getHTTPSubsystem(); HTTPService
+ * httpsService = eeGateway.getHttpsService();
+ * httpsService.setNickName(nickName);
*/
}
@@ -757,9 +756,9 @@ public final class CMSAdminServlet extends AdminServlet {
CMS.setServerCertNickname(nickName);
/*
- HTTPSubsystem caGateway = ca.getHTTPSubsystem();
- HTTPService httpsService = caGateway.getHttpsService();
- httpsService.setNickName(nickName);
+ * HTTPSubsystem caGateway = ca.getHTTPSubsystem(); HTTPService
+ * httpsService = caGateway.getHttpsService();
+ * httpsService.setNickName(nickName);
*/
}
@@ -767,21 +766,21 @@ public final class CMSAdminServlet extends AdminServlet {
* Performs Server Tasks: RESTART/STOP operation
*/
private void performTasks(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String restart = req.getParameter(Constants.PR_SERVER_RESTART);
String stop = req.getParameter(Constants.PR_SERVER_STOP);
NameValuePairs params = new NameValuePairs();
if (restart != null) {
- //XXX Uncommented afetr watchdog is implemented
+ // XXX Uncommented afetr watchdog is implemented
sendResponse(SUCCESS, null, params, resp);
- //mServer.restart();
+ // mServer.restart();
return;
}
if (stop != null) {
- //XXX Send response first then shutdown
+ // XXX Send response first then shutdown
sendResponse(SUCCESS, null, params, resp);
CMS.shutdown();
return;
@@ -795,7 +794,7 @@ public final class CMSAdminServlet extends AdminServlet {
* Reads subsystems that server has loaded with.
*/
private void readSubsystem(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
Enumeration<ISubsystem> e = CMS.getSubsystems();
@@ -805,7 +804,7 @@ public final class CMSAdminServlet extends AdminServlet {
String type = "";
ISubsystem sys = (ISubsystem) e.nextElement();
- //get subsystem type
+ // get subsystem type
if (sys instanceof IKeyRecoveryAuthority)
type = Constants.PR_KRA_INSTANCE;
if (sys instanceof IRegistrationAuthority)
@@ -814,7 +813,7 @@ public final class CMSAdminServlet extends AdminServlet {
type = Constants.PR_CA_INSTANCE;
if (sys instanceof IOCSPAuthority)
type = Constants.PR_OCSP_INSTANCE;
- if (sys instanceof ITKSAuthority)
+ if (sys instanceof ITKSAuthority)
type = Constants.PR_TKS_INSTANCE;
if (!type.trim().equals(""))
params.add(sys.getId(), type);
@@ -827,7 +826,7 @@ public final class CMSAdminServlet extends AdminServlet {
* Reads server statistics.
*/
private void readStat(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
IConfigStore cs = CMS.getConfigStore();
@@ -850,9 +849,9 @@ public final class CMSAdminServlet extends AdminServlet {
}
params.add(Constants.PR_STAT_STARTUP,
- (new Date(CMS.getStartupTime())).toString());
+ (new Date(CMS.getStartupTime())).toString());
params.add(Constants.PR_STAT_TIME,
- (new Date(System.currentTimeMillis())).toString());
+ (new Date(System.currentTimeMillis())).toString());
sendResponse(SUCCESS, null, params, resp);
}
@@ -860,12 +859,12 @@ public final class CMSAdminServlet extends AdminServlet {
* Modifies database information.
*/
private void setDBConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
IConfigStore dbConfig = mConfig.getSubStore(PROP_INTERNAL_DB);
@SuppressWarnings("unchecked")
- Enumeration<String> enum1 = req.getParameterNames();
+ Enumeration<String> enum1 = req.getParameterNames();
while (enum1.hasMoreElements()) {
String key = (String) enum1.nextElement();
@@ -876,117 +875,112 @@ public final class CMSAdminServlet extends AdminServlet {
continue;
if (key.equals(Constants.OP_SCOPE))
continue;
-
- dbConfig.putString(key, req.getParameter(key));
+
+ dbConfig.putString(key, req.getParameter(key));
}
sendResponse(RESTART, null, null, resp);
mConfig.commit(true);
}
- /**
+
+ /**
* Create Master Key
*/
-private void createMasterKey(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ private void createMasterKey(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
@SuppressWarnings("unchecked")
- Enumeration<String> e = req.getParameterNames();
- String newKeyName = null, selectedToken = null;
+ Enumeration<String> e = req.getParameterNames();
+ String newKeyName = null, selectedToken = null;
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
- if (name.equals(Constants.PR_KEY_LIST))
- {
- newKeyName = req.getParameter(name);
- }
- if (name.equals(Constants.PR_TOKEN_LIST))
- {
- selectedToken = req.getParameter(name);
- }
-
+ if (name.equals(Constants.PR_KEY_LIST)) {
+ newKeyName = req.getParameter(name);
+ }
+ if (name.equals(Constants.PR_TOKEN_LIST)) {
+ selectedToken = req.getParameter(name);
+ }
}
- if(selectedToken!=null && newKeyName!=null)
- {
- String symKeys = SessionKey.GenMasterKey(selectedToken,newKeyName);
- CMS.getConfigStore().putString("tks.defaultSlot", selectedToken);
- String masterKeyPrefix = CMS.getConfigStore().getString("tks.master_key_prefix", null);
-
- SessionKey.SetDefaultPrefix(masterKeyPrefix);
- params.add(Constants.PR_KEY_LIST, newKeyName);
- params.add(Constants.PR_TOKEN_LIST, selectedToken);
- }
- sendResponse(SUCCESS, null, params, resp);
-}
+ if (selectedToken != null && newKeyName != null) {
+ String symKeys = SessionKey.GenMasterKey(selectedToken, newKeyName);
+ CMS.getConfigStore().putString("tks.defaultSlot", selectedToken);
+ String masterKeyPrefix = CMS.getConfigStore().getString("tks.master_key_prefix", null);
+
+ SessionKey.SetDefaultPrefix(masterKeyPrefix);
+ params.add(Constants.PR_KEY_LIST, newKeyName);
+ params.add(Constants.PR_TOKEN_LIST, selectedToken);
+ }
+ sendResponse(SUCCESS, null, params, resp);
+ }
- /**
+ /**
* Reads secmod.db
*/
private void getTKSKeys(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
@SuppressWarnings("unchecked")
- Enumeration<String> e = req.getParameterNames();
+ Enumeration<String> e = req.getParameterNames();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
- if (name.equals(Constants.PR_TOKEN_LIST))
- {
- String selectedToken = req.getParameter(name);
-
- int count = 0;
- int keys_found = 0;
-
- ICryptoSubsystem jssSubSystem = (ICryptoSubsystem)CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
-
- CryptoToken token = null;
- CryptoManager mCryptoManager = null;
- try {
- mCryptoManager = CryptoManager.getInstance();
- } catch (Exception e2) {
- }
-
- if(!jssSubSystem.isTokenLoggedIn(selectedToken))
- {
- PasswordCallback cpcb = new ConsolePasswordCallback();
- while (true) {
+ if (name.equals(Constants.PR_TOKEN_LIST)) {
+ String selectedToken = req.getParameter(name);
+
+ int count = 0;
+ int keys_found = 0;
+
+ ICryptoSubsystem jssSubSystem = (ICryptoSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
+
+ CryptoToken token = null;
+ CryptoManager mCryptoManager = null;
+ try {
+ mCryptoManager = CryptoManager.getInstance();
+ } catch (Exception e2) {
+ }
+
+ if (!jssSubSystem.isTokenLoggedIn(selectedToken)) {
+ PasswordCallback cpcb = new ConsolePasswordCallback();
+ while (true) {
try {
- token = mCryptoManager.getTokenByName(selectedToken);
- token.login(cpcb);
+ token = mCryptoManager.getTokenByName(selectedToken);
+ token.login(cpcb);
break;
} catch (Exception e3) {
- //log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_INCORRECT_PWD"));
+ // log(ILogger.LL_FAILURE,
+ // CMS.getLogMessage("CMSCORE_SECURITY_INCORRECT_PWD"));
continue;
}
- }
- }
- // String symKeys = new String("key1,key2");
- String symKeys = SessionKey.ListSymmetricKeys(selectedToken);
- params.add(Constants.PR_TOKEN_LIST, symKeys);
+ }
+ }
+ // String symKeys = new String("key1,key2");
+ String symKeys = SessionKey.ListSymmetricKeys(selectedToken);
+ params.add(Constants.PR_TOKEN_LIST, symKeys);
- }
+ }
}
sendResponse(SUCCESS, null, params, resp);
}
-
-
+
/**
* Reads database information.
*/
private void getDBConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
IConfigStore dbConfig = mConfig.getSubStore(PROP_DB);
IConfigStore ldapConfig = dbConfig.getSubStore("ldap");
NameValuePairs params = new NameValuePairs();
@SuppressWarnings("unchecked")
- Enumeration<String> e = req.getParameterNames();
-
+ Enumeration<String> e = req.getParameterNames();
+
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
@@ -998,7 +992,7 @@ private void createMasterKey(HttpServletRequest req,
continue;
if (name.equals(Constants.PR_SECURE_PORT_ENABLED))
params.add(name, ldapConfig.getString(name, "Constants.FALSE"));
- else
+ else
params.add(name, ldapConfig.getString(name, ""));
}
sendResponse(SUCCESS, null, params, resp);
@@ -1008,7 +1002,7 @@ private void createMasterKey(HttpServletRequest req,
* Modifies SMTP configuration.
*/
private void modifySMTPConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
// XXX
IConfigStore sConfig = mConfig.getSubStore(PROP_SMTP);
@@ -1022,7 +1016,7 @@ private void createMasterKey(HttpServletRequest req,
if (port != null)
sConfig.putString("port", port);
-
+
commit(true);
sendResponse(SUCCESS, null, null, resp);
@@ -1032,23 +1026,23 @@ private void createMasterKey(HttpServletRequest req,
* Reads SMTP configuration.
*/
private void readSMTPConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
IConfigStore dbConfig = mConfig.getSubStore(PROP_SMTP);
NameValuePairs params = new NameValuePairs();
params.add(Constants.PR_SERVER_NAME,
- dbConfig.getString("host"));
+ dbConfig.getString("host"));
params.add(Constants.PR_PORT,
- dbConfig.getString("port"));
+ dbConfig.getString("port"));
sendResponse(SUCCESS, null, params, resp);
}
private void loggedInToken(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
@SuppressWarnings("unchecked")
- Enumeration<String> enum1 = req.getParameterNames();
+ Enumeration<String> enum1 = req.getParameterNames();
String tokenName = "";
String pwd = "";
@@ -1064,7 +1058,7 @@ private void createMasterKey(HttpServletRequest req,
}
ICryptoSubsystem jssSubSystem = (ICryptoSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
jssSubSystem.loggedInToken(tokenName, pwd);
@@ -1074,10 +1068,10 @@ private void createMasterKey(HttpServletRequest req,
}
private void checkTokenStatus(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
@SuppressWarnings("unchecked")
- Enumeration<String> enum1 = req.getParameterNames();
+ Enumeration<String> enum1 = req.getParameterNames();
String key = "";
String value = "";
@@ -1090,7 +1084,7 @@ private void createMasterKey(HttpServletRequest req,
}
ICryptoSubsystem jssSubSystem = (ICryptoSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
boolean status = jssSubSystem.isTokenLoggedIn(value);
NameValuePairs params = new NameValuePairs();
@@ -1103,17 +1097,18 @@ private void createMasterKey(HttpServletRequest req,
/**
* Retrieve a certificate request
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_KEY_GEN_ASYMMETRIC used when
* asymmetric keys are generated
* </ul>
+ *
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
* @exception EBaseException failed to retrieve certificate request
*/
private void getCertRequest(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -1124,7 +1119,7 @@ private void createMasterKey(HttpServletRequest req,
try {
NameValuePairs params = new NameValuePairs();
@SuppressWarnings("unchecked")
- Enumeration<String> enum1 = req.getParameterNames();
+ Enumeration<String> enum1 = req.getParameterNames();
String tokenName = Constants.PR_INTERNAL_TOKEN_NAME;
String keyType = "";
int keyLength = 512;
@@ -1164,10 +1159,10 @@ private void createMasterKey(HttpServletRequest req,
}
pathname = mConfig.getString("instanceRoot", "")
- + File.separator + "conf" + File.separator;
+ + File.separator + "conf" + File.separator;
dir = pathname;
ICryptoSubsystem jssSubSystem = (ICryptoSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
KeyPair keypair = null;
PQGParams pqgParams = null;
@@ -1208,9 +1203,9 @@ private void createMasterKey(HttpServletRequest req,
if (keyType.equals("ECC")) {
// get ECC keypair
keypair = jssSubSystem.getECCKeyPair(tokenName, keyCurveName, certType);
- } else { //DSA or RSA
+ } else { // DSA or RSA
if (keyType.equals("DSA"))
- pqgParams = jssSubSystem.getPQG(keyLength);
+ pqgParams = jssSubSystem.getPQG(keyLength);
keypair = jssSubSystem.getKeyPair(tokenName, keyType, keyLength, pqgParams);
}
}
@@ -1289,25 +1284,25 @@ private void createMasterKey(HttpServletRequest req,
// rethrow the specific exception to be handled later
throw eAudit2;
- // } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_KEY_GEN_ASYMMETRIC,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditPublicKey );
- //
- // audit( auditMessage );
- //
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
- }
- }
-
- private void setCANewnickname(String tokenName, String nickname)
- throws EBaseException {
+ // } catch( ServletException eAudit3 ) {
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_KEY_GEN_ASYMMETRIC,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditPublicKey );
+ //
+ // audit( auditMessage );
+ //
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
+ }
+ }
+
+ private void setCANewnickname(String tokenName, String nickname)
+ throws EBaseException {
ICertificateAuthority ca = (ICertificateAuthority)
- CMS.getSubsystem(CMS.SUBSYSTEM_CA);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CA);
ISigningUnit signingUnit = ca.getSigningUnit();
if (tokenName.equals(Constants.PR_INTERNAL_TOKEN_NAME))
@@ -1322,16 +1317,16 @@ private void createMasterKey(HttpServletRequest req,
private String getCANewnickname() throws EBaseException {
ICertificateAuthority ca = (ICertificateAuthority)
- CMS.getSubsystem(CMS.SUBSYSTEM_CA);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CA);
ISigningUnit signingUnit = ca.getSigningUnit();
- return signingUnit.getNewNickName();
+ return signingUnit.getNewNickName();
}
private void setRANewnickname(String tokenName, String nickname)
- throws EBaseException {
+ throws EBaseException {
IRegistrationAuthority ra = (IRegistrationAuthority)
- CMS.getSubsystem(CMS.SUBSYSTEM_RA);
+ CMS.getSubsystem(CMS.SUBSYSTEM_RA);
if (tokenName.equals(Constants.PR_INTERNAL_TOKEN_NAME))
ra.setNewNickName(nickname);
@@ -1345,13 +1340,13 @@ private void createMasterKey(HttpServletRequest req,
private String getRANewnickname() throws EBaseException {
IRegistrationAuthority ra = (IRegistrationAuthority)
- CMS.getSubsystem(CMS.SUBSYSTEM_RA);
+ CMS.getSubsystem(CMS.SUBSYSTEM_RA);
return ra.getNewNickName();
}
private void setOCSPNewnickname(String tokenName, String nickname)
- throws EBaseException {
+ throws EBaseException {
IOCSPAuthority ocsp = (IOCSPAuthority) CMS.getSubsystem(CMS.SUBSYSTEM_OCSP);
if (ocsp != null) {
@@ -1367,7 +1362,7 @@ private void createMasterKey(HttpServletRequest req,
}
} else {
ICertificateAuthority ca = (ICertificateAuthority)
- CMS.getSubsystem(CMS.SUBSYSTEM_CA);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CA);
ISigningUnit signingUnit = ca.getOCSPSigningUnit();
if (tokenName.equals(Constants.PR_INTERNAL_TOKEN_NAME))
@@ -1387,20 +1382,20 @@ private void createMasterKey(HttpServletRequest req,
if (ocsp != null) {
ISigningUnit signingUnit = ocsp.getSigningUnit();
- return signingUnit.getNewNickName();
+ return signingUnit.getNewNickName();
} else {
ICertificateAuthority ca = (ICertificateAuthority)
- CMS.getSubsystem(CMS.SUBSYSTEM_CA);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CA);
ISigningUnit signingUnit = ca.getOCSPSigningUnit();
- return signingUnit.getNewNickName();
+ return signingUnit.getNewNickName();
}
}
- private void setKRANewnickname(String tokenName, String nickname)
- throws EBaseException {
+ private void setKRANewnickname(String tokenName, String nickname)
+ throws EBaseException {
IKeyRecoveryAuthority kra = (IKeyRecoveryAuthority)
- CMS.getSubsystem(CMS.SUBSYSTEM_KRA);
+ CMS.getSubsystem(CMS.SUBSYSTEM_KRA);
if (tokenName.equals(Constants.PR_INTERNAL_TOKEN_NAME))
kra.setNewNickName(nickname);
@@ -1418,81 +1413,76 @@ private void createMasterKey(HttpServletRequest req,
return kra.getNewNickName();
}
- private void setRADMNewnickname(String tokenName, String nickName)
- throws EBaseException {
+ private void setRADMNewnickname(String tokenName, String nickName)
+ throws EBaseException {
CMS.setServerCertNickname(tokenName, nickName);
/*
- RemoteAdmin raAdmin = (RemoteAdmin)RemoteAdmin.getInstance();
- HTTPService httpsService = raAdmin.getHttpsService();
- if (tokenName.equals(Constants.PR_INTERNAL_TOKEN_NAME))
- httpsService.setNewNickName(nickName);
- else {
- if (tokenName.equals("") && nickName.equals(""))
- httpsService.setNewNickName("");
- else
- httpsService.setNewNickName(tokenName+":"+nickName);
- }
+ * RemoteAdmin raAdmin = (RemoteAdmin)RemoteAdmin.getInstance();
+ * HTTPService httpsService = raAdmin.getHttpsService(); if
+ * (tokenName.equals(Constants.PR_INTERNAL_TOKEN_NAME))
+ * httpsService.setNewNickName(nickName); else { if
+ * (tokenName.equals("") && nickName.equals(""))
+ * httpsService.setNewNickName(""); else
+ * httpsService.setNewNickName(tokenName+":"+nickName); }
*/
}
- private String getRADMNewnickname()
- throws EBaseException {
+ private String getRADMNewnickname()
+ throws EBaseException {
// assuming the nickname does not change.
return CMS.getServerCertNickname();
/*
- RemoteAdmin raAdmin = (RemoteAdmin)RemoteAdmin.getInstance();
- HTTPService httpsService = raAdmin.getHttpsService();
- return httpsService.getNewNickName();
+ * RemoteAdmin raAdmin = (RemoteAdmin)RemoteAdmin.getInstance();
+ * HTTPService httpsService = raAdmin.getHttpsService(); return
+ * httpsService.getNewNickName();
*/
}
private void setAgentNewnickname(String tokenName, String nickName)
- throws EBaseException {
+ throws EBaseException {
CMS.setServerCertNickname(tokenName, nickName);
/*
- AgentGateway gateway = (AgentGateway)mReg.get(AgentGateway.ID);
- HTTPService httpsService = gateway.getHttpsService();
- if (tokenName.equals(Constants.PR_INTERNAL_TOKEN_NAME))
- httpsService.setNewNickName(nickName);
- else {
- if (tokenName.equals("") && nickName.equals(""))
- httpsService.setNewNickName("");
- else
- httpsService.setNewNickName(tokenName+":"+nickName);
- }
+ * AgentGateway gateway = (AgentGateway)mReg.get(AgentGateway.ID);
+ * HTTPService httpsService = gateway.getHttpsService(); if
+ * (tokenName.equals(Constants.PR_INTERNAL_TOKEN_NAME))
+ * httpsService.setNewNickName(nickName); else { if
+ * (tokenName.equals("") && nickName.equals(""))
+ * httpsService.setNewNickName(""); else
+ * httpsService.setNewNickName(tokenName+":"+nickName); }
*/
}
- private String getAgentNewnickname()
- throws EBaseException {
+ private String getAgentNewnickname()
+ throws EBaseException {
// assuming the nickname does not change.
return CMS.getServerCertNickname();
/*
- AgentGateway gateway = (AgentGateway)mReg.get(AgentGateway.ID);
- HTTPService httpsService = gateway.getHttpsService();
- return httpsService.getNewNickName();
+ * AgentGateway gateway = (AgentGateway)mReg.get(AgentGateway.ID);
+ * HTTPService httpsService = gateway.getHttpsService(); return
+ * httpsService.getNewNickName();
*/
}
/**
* Issue import certificate
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_TRUSTED_PUBLIC_KEY used when
- * "Certificate Setup Wizard" is used to import CA certs into the
+ * "Certificate Setup Wizard" is used to import CA certs into the
* certificate database
* </ul>
+ *
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
* @exception EBaseException failed to issue an import certificate
*/
private void issueImportCert(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -1501,7 +1491,7 @@ private void createMasterKey(HttpServletRequest req,
// to the signed audit log and stored as failures
try {
@SuppressWarnings("unchecked")
- Enumeration<String> enum1 = req.getParameterNames();
+ Enumeration<String> enum1 = req.getParameterNames();
String pkcs = "";
String type = "";
String tokenName = Constants.PR_INTERNAL_TOKEN_NAME;
@@ -1518,7 +1508,7 @@ private void createMasterKey(HttpServletRequest req,
String key = (String) enum1.nextElement();
String value = req.getParameter(key);
- if (key.equals("pathname")) {
+ if (key.equals("pathname")) {
configPath = mConfig.getString("instanceRoot", "")
+ File.separator + "conf" + File.separator;
pathname = configPath + value;
@@ -1532,16 +1522,16 @@ private void createMasterKey(HttpServletRequest req,
String certType = (String) properties.get(Constants.RS_ID);
ICryptoSubsystem jssSubSystem = (ICryptoSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
IDBSubsystem dbs = (IDBSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_DBS);
+ CMS.getSubsystem(CMS.SUBSYSTEM_DBS);
ICertificateAuthority ca = (ICertificateAuthority)
- CMS.getSubsystem(CMS.SUBSYSTEM_CA);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CA);
ICertificateRepository repository =
- (ICertificateRepository) ca.getCertificateRepository();
+ (ICertificateRepository) ca.getCertificateRepository();
ISigningUnit signingUnit = ca.getSigningUnit();
String oldtokenname = null;
- //this is the old nick name
+ // this is the old nick name
String nickname = getNickname(certType);
String nicknameWithoutTokenName = "";
String oldcatokenname = signingUnit.getTokenName();
@@ -1566,8 +1556,7 @@ private void createMasterKey(HttpServletRequest req,
audit(auditMessage);
- throw new
- EBaseException(CMS.getLogMessage("BASE_CERT_NOT_FOUND"));
+ throw new EBaseException(CMS.getLogMessage("BASE_CERT_NOT_FOUND"));
}
if (newtokenname == null)
@@ -1587,13 +1576,12 @@ private void createMasterKey(HttpServletRequest req,
audit(auditMessage);
- throw new
- EBaseException(CMS.getLogMessage("BASE_CERT_NOT_FOUND"));
+ throw new EBaseException(CMS.getLogMessage("BASE_CERT_NOT_FOUND"));
}
- //xxx renew ca ,use old issuer?
+ // xxx renew ca ,use old issuer?
properties.setIssuerName(
- jssSubSystem.getCertSubjectName(oldcatokenname,
+ jssSubSystem.getCertSubjectName(oldcatokenname,
canicknameWithoutTokenName));
KeyPair pair = null;
@@ -1608,11 +1596,10 @@ private void createMasterKey(HttpServletRequest req,
audit(auditMessage);
- throw new
- EBaseException(CMS.getLogMessage("BASE_CERT_NOT_FOUND"));
+ throw new EBaseException(CMS.getLogMessage("BASE_CERT_NOT_FOUND"));
}
- //xxx set to old nickname?
+ // xxx set to old nickname?
properties.setCertNickname(nickname);
if (!certType.equals(Constants.PR_CA_SIGNING_CERT)) {
CertificateExtensions exts = jssSubSystem.getExtensions(
@@ -1633,14 +1620,14 @@ private void createMasterKey(HttpServletRequest req,
defaultOCSPSigningAlg = properties.getHashType();
}
}
-
+
// create a new CA certificate or ssl server cert
- if (properties.getKeyCurveName() != null) { //new ECC
+ if (properties.getKeyCurveName() != null) { // new ECC
CMS.debug("CMSAdminServlet: issueImportCert: generating ECC keys");
pair = jssSubSystem.getECCKeyPair(properties);
- if (certType.equals(Constants.PR_CA_SIGNING_CERT))
+ if (certType.equals(Constants.PR_CA_SIGNING_CERT))
caKeyPair = pair;
- } else if (properties.getKeyLength() != null) { //new RSA or DSA
+ } else if (properties.getKeyLength() != null) { // new RSA or DSA
keyType = properties.getKeyType();
String keyLen = properties.getKeyLength();
PQGParams pqgParams = null;
@@ -1648,10 +1635,10 @@ private void createMasterKey(HttpServletRequest req,
if (keyType.equals("DSA")) {
pqgParams = jssSubSystem.getCAPQG(Integer.parseInt(keyLen),
mConfig);
- //properties.put(Constants.PR_PQGPARAMS, pqgParams);
+ // properties.put(Constants.PR_PQGPARAMS, pqgParams);
}
pair = jssSubSystem.getKeyPair(properties);
- if (certType.equals(Constants.PR_CA_SIGNING_CERT))
+ if (certType.equals(Constants.PR_CA_SIGNING_CERT))
caKeyPair = pair;
// renew the CA certificate or ssl server cert
} else {
@@ -1664,11 +1651,12 @@ private void createMasterKey(HttpServletRequest req,
}
/*
- String alg = jssSubSystem.getSignatureAlgorithm(nickname);
- SignatureAlgorithm sigAlg = SigningUnit.mapAlgorithmToJss(alg);
- properties.setSignatureAlgorithm(sigAlg);
- properties.setAlgorithmId(
- jssSubSystem.getAlgorithmId(alg, mConfig));
+ * String alg = jssSubSystem.getSignatureAlgorithm(nickname);
+ * SignatureAlgorithm sigAlg =
+ * SigningUnit.mapAlgorithmToJss(alg);
+ * properties.setSignatureAlgorithm(sigAlg);
+ * properties.setAlgorithmId( jssSubSystem.getAlgorithmId(alg,
+ * mConfig));
*/
}
@@ -1684,7 +1672,7 @@ private void createMasterKey(HttpServletRequest req,
properties.setAlgorithmId(jssSubSystem.getAlgorithmId(alg, mConfig));
}
- if (pair == null)
+ if (pair == null)
CMS.debug("CMSAdminServlet: issueImportCert: key pair is null");
BigInteger nextSerialNo = repository.getNextSerialNumber();
@@ -1692,36 +1680,34 @@ private void createMasterKey(HttpServletRequest req,
properties.setSerialNumber(nextSerialNo);
properties.setKeyPair(pair);
properties.setConfigFile(mConfig);
- // properties.put(Constants.PR_CA_KEYPAIR, pair);
+ // properties.put(Constants.PR_CA_KEYPAIR, pair);
properties.put(Constants.PR_CA_KEYPAIR, caKeyPair);
- X509CertImpl signedCert =
- jssSubSystem.getSignedCert(properties, certType,
+ X509CertImpl signedCert =
+ jssSubSystem.getSignedCert(properties, certType,
caKeyPair.getPrivate());
- if (signedCert == null)
- CMS.debug("CMSAdminServlet: issueImportCert: signedCert is null");
+ if (signedCert == null)
+ CMS.debug("CMSAdminServlet: issueImportCert: signedCert is null");
- /* bug 600124
- try {
- jssSubSystem.deleteTokenCertificate(nickname, pathname);
- } catch (Throwable e) {
- //skip it
- }
+ /*
+ * bug 600124 try { jssSubSystem.deleteTokenCertificate(nickname,
+ * pathname); } catch (Throwable e) { //skip it }
*/
boolean nicknameChanged = false;
- //xxx import cert with nickname without token name?
- //jss adds the token prefix!!!
- //log(ILogger.LL_DEBUG,"import as alias"+ nicknameWithoutTokenName);
+ // xxx import cert with nickname without token name?
+ // jss adds the token prefix!!!
+ // log(ILogger.LL_DEBUG,"import as alias"+
+ // nicknameWithoutTokenName);
try {
CMS.debug("CMSAdminServlet: issueImportCert: Importing cert: " + nicknameWithoutTokenName);
jssSubSystem.importCert(signedCert, nicknameWithoutTokenName,
certType);
} catch (EBaseException e) {
// if it fails, let use a different nickname to try
- Date now = new Date();
+ Date now = new Date();
String newNickname = nicknameWithoutTokenName
+ "-" + now.getTime();
@@ -1746,20 +1732,20 @@ private void createMasterKey(HttpServletRequest req,
if (certType.equals(Constants.PR_CA_SIGNING_CERT)) {
try {
X509CertInfo certInfo = (X509CertInfo) signedCert.get(
- X509CertImpl.NAME + "." + X509CertImpl.INFO);
+ X509CertImpl.NAME + "." + X509CertImpl.INFO);
CertificateExtensions extensions = (CertificateExtensions)
- certInfo.get(X509CertInfo.EXTENSIONS);
+ certInfo.get(X509CertInfo.EXTENSIONS);
if (extensions != null) {
BasicConstraintsExtension basic =
- (BasicConstraintsExtension)
- extensions.get(BasicConstraintsExtension.class.getSimpleName());
+ (BasicConstraintsExtension)
+ extensions.get(BasicConstraintsExtension.class.getSimpleName());
if (basic == null)
log(CMS.getLogMessage("ADMIN_SRVLT_BASIC_CONSTRAIN_NULL"));
else {
Integer pathlen = (Integer)
- basic.get(BasicConstraintsExtension.PATH_LEN);
+ basic.get(BasicConstraintsExtension.PATH_LEN);
int num = pathlen.intValue();
if (num == 0)
@@ -1776,7 +1762,7 @@ private void createMasterKey(HttpServletRequest req,
}
}
- CMS.debug("CMSAdminServlet: oldtoken:" + oldtokenname
+ CMS.debug("CMSAdminServlet: oldtoken:" + oldtokenname
+ " newtoken:" + newtokenname + " nickname:" + nickname);
if ((newtokenname != null &&
!newtokenname.equals(oldtokenname)) || nicknameChanged) {
@@ -1786,10 +1772,10 @@ private void createMasterKey(HttpServletRequest req,
newtokenname);
} else {
signingUnit.updateConfig(newtokenname + ":" +
- nicknameWithoutTokenName,
+ nicknameWithoutTokenName,
newtokenname);
}
- } else if (certType.equals(Constants.PR_SERVER_CERT)) {
+ } else if (certType.equals(Constants.PR_SERVER_CERT)) {
if (newtokenname.equals(Constants.PR_INTERNAL_TOKEN_NAME)) {
nickname = nicknameWithoutTokenName;
} else {
@@ -1797,13 +1783,13 @@ private void createMasterKey(HttpServletRequest req,
+ nicknameWithoutTokenName;
}
- //setRADMNewnickname("","");
- //modifyRADMCert(nickname);
+ // setRADMNewnickname("","");
+ // modifyRADMCert(nickname);
modifyAgentGatewayCert(nickname);
if (isSubsystemInstalled("ra")) {
IRegistrationAuthority ra =
- (IRegistrationAuthority)
- CMS.getSubsystem(CMS.SUBSYSTEM_RA);
+ (IRegistrationAuthority)
+ CMS.getSubsystem(CMS.SUBSYSTEM_RA);
modifyEEGatewayCert(ra, nickname);
}
@@ -1820,23 +1806,23 @@ private void createMasterKey(HttpServletRequest req,
modifyRADMCert(nickname);
} else if (certType.equals(Constants.PR_OCSP_SIGNING_CERT)) {
- if (ca != null) {
+ if (ca != null) {
ISigningUnit ocspSigningUnit = ca.getOCSPSigningUnit();
if (newtokenname.equals(Constants.PR_INTERNAL_TOKEN_NAME)) {
ocspSigningUnit.updateConfig(
- nicknameWithoutTokenName, newtokenname);
+ nicknameWithoutTokenName, newtokenname);
} else {
ocspSigningUnit.updateConfig(newtokenname + ":" +
- nicknameWithoutTokenName,
- newtokenname);
+ nicknameWithoutTokenName,
+ newtokenname);
}
}
}
}
-
+
// set signing algorithms if needed
- if (certType.equals(Constants.PR_CA_SIGNING_CERT))
+ if (certType.equals(Constants.PR_CA_SIGNING_CERT))
signingUnit.setDefaultAlgorithm(defaultSigningAlg);
if (defaultOCSPSigningAlg != null) {
@@ -1884,46 +1870,47 @@ private void createMasterKey(HttpServletRequest req,
// rethrow the specific exception to be handled later
throw eAudit2;
- // } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_TRUSTED_PUBLIC_KEY,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
- //
- // audit( auditMessage );
- //
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
- }
- }
-
- private void updateCASignature(String nickname, KeyCertData properties,
- ICryptoSubsystem jssSubSystem) throws EBaseException {
+ // } catch( ServletException eAudit3 ) {
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_TRUSTED_PUBLIC_KEY,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
+ //
+ // audit( auditMessage );
+ //
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
+ }
+ }
+
+ private void updateCASignature(String nickname, KeyCertData properties,
+ ICryptoSubsystem jssSubSystem) throws EBaseException {
String alg = jssSubSystem.getSignatureAlgorithm(nickname);
SignatureAlgorithm sigAlg = Cert.mapAlgorithmToJss(alg);
properties.setSignatureAlgorithm(sigAlg);
properties.setAlgorithmId(
- jssSubSystem.getAlgorithmId(alg, mConfig));
+ jssSubSystem.getAlgorithmId(alg, mConfig));
}
/**
* Install certificates
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_TRUSTED_PUBLIC_KEY used when
- * "Certificate Setup Wizard" is used to import CA certs into the
+ * "Certificate Setup Wizard" is used to import CA certs into the
* certificate database
* </ul>
+ *
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
* @exception EBaseException failed to install a certificate
*/
private void installCert(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -1940,37 +1927,37 @@ private void createMasterKey(HttpServletRequest req,
String serverID = "";
String certpath = "";
@SuppressWarnings("unchecked")
- Enumeration<String> enum1 = req.getParameterNames();
+ Enumeration<String> enum1 = req.getParameterNames();
while (enum1.hasMoreElements()) {
String key = (String) enum1.nextElement();
String value = req.getParameter(key);
- if (key.equals(Constants.PR_PKCS10))
+ if (key.equals(Constants.PR_PKCS10))
pkcs = value;
else if (key.equals(Constants.RS_ID))
certType = value;
else if (key.equals(Constants.PR_NICKNAME))
nickname = value;
- else if (key.equals("pathname"))
+ else if (key.equals("pathname"))
pathname = value;
else if (key.equals(Constants.PR_SERVER_ROOT))
serverRoot = value;
- else if (key.equals(Constants.PR_SERVER_ID))
+ else if (key.equals(Constants.PR_SERVER_ID))
serverID = value;
- else if (key.equals(Constants.PR_CERT_FILEPATH))
+ else if (key.equals(Constants.PR_CERT_FILEPATH))
certpath = value;
}
-
+
try {
if (pkcs == null || pkcs.equals("")) {
if (certpath == null || certpath.equals("")) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CONFIG_TRUSTED_PUBLIC_KEY,
- auditSubjectID,
- ILogger.FAILURE,
- auditParams(req));
+ LOGGING_SIGNED_AUDIT_CONFIG_TRUSTED_PUBLIC_KEY,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditParams(req));
audit(auditMessage);
@@ -1981,7 +1968,7 @@ private void createMasterKey(HttpServletRequest req,
} else {
FileInputStream in = new FileInputStream(certpath);
BufferedReader d =
- new BufferedReader(new InputStreamReader(in));
+ new BufferedReader(new InputStreamReader(in));
String content = "";
pkcs = "";
@@ -2009,7 +1996,7 @@ private void createMasterKey(HttpServletRequest req,
audit(auditMessage);
throw new EBaseException(
- CMS.getLogMessage("BASE_OPEN_FILE_FAILED"));
+ CMS.getLogMessage("BASE_OPEN_FILE_FAILED"));
}
pkcs = pkcs.trim();
@@ -2017,8 +2004,8 @@ private void createMasterKey(HttpServletRequest req,
+ File.separator + "config" + File.separator + pathname;
ICryptoSubsystem jssSubSystem = (ICryptoSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
- //String nickname = getNickname(certType);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
+ // String nickname = getNickname(certType);
String nicknameWithoutTokenName = "";
int index = nickname.indexOf(":");
@@ -2039,72 +2026,62 @@ private void createMasterKey(HttpServletRequest req,
audit(auditMessage);
throw new EBaseException(
- CMS.getLogMessage("BASE_CERT_NOT_FOUND"));
+ CMS.getLogMessage("BASE_CERT_NOT_FOUND"));
}
/*
- if (certType.equals(Constants.PR_CA_SIGNING_CERT) ||
- certType.equals(Constants.PR_RA_SIGNING_CERT) ||
- certType.equals(Constants.PR_OCSP_SIGNING_CERT) ||
- certType.equals(Constants.PR_KRA_TRANSPORT_CERT) ||
- certType.equals(Constants.PR_SERVER_CERT) ||
- certType.equals(Constants.PR_SERVER_CERT_RADM)) {
- String oldnickname = getNickname(certType);
- try {
- jssSubsystem.deleteTokenCertificate(oldnickname,
- pathname);
- //jssSubsystem.deleteTokenCertificate(nickname,
- pathname);
- } catch (EBaseException e) {
- // skip it
- }
- } else {
- try {
- jssSubsystem.deleteTokenCertificate(nickname, pathname);
- } catch (EBaseException e) {
- // skip it
- }
- }
- */
+ * if (certType.equals(Constants.PR_CA_SIGNING_CERT) ||
+ * certType.equals(Constants.PR_RA_SIGNING_CERT) ||
+ * certType.equals(Constants.PR_OCSP_SIGNING_CERT) ||
+ * certType.equals(Constants.PR_KRA_TRANSPORT_CERT) ||
+ * certType.equals(Constants.PR_SERVER_CERT) ||
+ * certType.equals(Constants.PR_SERVER_CERT_RADM)) { String
+ * oldnickname = getNickname(certType); try {
+ * jssSubsystem.deleteTokenCertificate(oldnickname, pathname);
+ * //jssSubsystem.deleteTokenCertificate(nickname, pathname); }
+ * catch (EBaseException e) { // skip it } } else { try {
+ * jssSubsystem.deleteTokenCertificate(nickname, pathname); } catch
+ * (EBaseException e) { // skip it } }
+ */
// 600124 - renewal of SSL crash the server
// we now do not delete previously installed certificates.
- // Same Subject | Same Nickname | Same Key | Legal
- // -----------------------------------------------------------
- // 1. Yes Yes No Yes
- // 2. Yes Yes Yes Yes
- // 3. No No Yes Yes
- // 4. No No No Yes
- // 5. No Yes Yes No
- // 6. No Yes No No
- // 7. Yes No Yes No
- // 8. Yes No No No
+ // Same Subject | Same Nickname | Same Key | Legal
+ // -----------------------------------------------------------
+ // 1. Yes Yes No Yes
+ // 2. Yes Yes Yes Yes
+ // 3. No No Yes Yes
+ // 4. No No No Yes
+ // 5. No Yes Yes No
+ // 6. No Yes No No
+ // 7. Yes No Yes No
+ // 8. Yes No No No
// Based on above table, the following cases are permitted:
// Existing Key:
- // (a) Same Subject & Same Nickname --- (2)
- // (b) Different Subject & Different Nickname --- (3)
- // (In order to support Case b., we need to use a different
- // nickname).
+ // (a) Same Subject & Same Nickname --- (2)
+ // (b) Different Subject & Different Nickname --- (3)
+ // (In order to support Case b., we need to use a different
+ // nickname).
// New Key:
- // (c) Same Subject & Same Nickname --- (1)
- // (d) Different Subject & Different Nickname --- (4)
- // (In order to support Case b., we need to use a different
- // nickname).
+ // (c) Same Subject & Same Nickname --- (1)
+ // (d) Different Subject & Different Nickname --- (4)
+ // (In order to support Case b., we need to use a different
+ // nickname).
//
- CMS.debug("CMSAdminServlet.installCert(): About to try jssSubSystem.importCert: "+ nicknameWithoutTokenName);
+ CMS.debug("CMSAdminServlet.installCert(): About to try jssSubSystem.importCert: " + nicknameWithoutTokenName);
try {
- jssSubSystem.importCert(pkcs, nicknameWithoutTokenName,
- certType);
+ jssSubSystem.importCert(pkcs, nicknameWithoutTokenName,
+ certType);
} catch (EBaseException e) {
boolean certFound = false;
String eString = e.toString();
- if(eString.contains("Failed to find certificate that was just imported")) {
- CMS.debug("CMSAdminServlet.installCert(): nickname="+nicknameWithoutTokenName + " TokenException: " + eString);
+ if (eString.contains("Failed to find certificate that was just imported")) {
+ CMS.debug("CMSAdminServlet.installCert(): nickname=" + nicknameWithoutTokenName + " TokenException: " + eString);
X509Certificate cert = null;
try {
@@ -2116,11 +2093,11 @@ private void createMasterKey(HttpServletRequest req,
} catch (Exception ex) {
CMS.debug("CMSAdminServlet.installCert() Can't find cert just imported: " + ex.toString());
}
- }
+ }
if (!certFound) {
// if it fails, let use a different nickname to try
- Date now = new Date();
+ Date now = new Date();
String newNickname = nicknameWithoutTokenName + "-" +
now.getTime();
@@ -2131,16 +2108,16 @@ private void createMasterKey(HttpServletRequest req,
} else {
nickname = tokenName + ":" + newNickname;
}
- CMS.debug("CMSAdminServlet: installCert(): After second install attempt following initial error: nickname="+nickname);
- }
+ CMS.debug("CMSAdminServlet: installCert(): After second install attempt following initial error: nickname=" + nickname);
+ }
}
if (certType.equals(Constants.PR_CA_SIGNING_CERT)) {
ICertificateAuthority ca =
- (ICertificateAuthority) CMS.getSubsystem(CMS.SUBSYSTEM_CA);
+ (ICertificateAuthority) CMS.getSubsystem(CMS.SUBSYSTEM_CA);
ISigningUnit signingUnit = ca.getSigningUnit();
String signatureAlg =
- jssSubSystem.getSignatureAlgorithm(nickname);
+ jssSubSystem.getSignatureAlgorithm(nickname);
signingUnit.setDefaultAlgorithm(signatureAlg);
setCANewnickname("", "");
@@ -2149,26 +2126,26 @@ private void createMasterKey(HttpServletRequest req,
if (nickname.equals(nicknameWithoutTokenName)) {
signingUnit.updateConfig(nickname,
- Constants.PR_INTERNAL_TOKEN_NAME);
+ Constants.PR_INTERNAL_TOKEN_NAME);
extensions = jssSubSystem.getExtensions(
- Constants.PR_INTERNAL_TOKEN_NAME, nickname);
+ Constants.PR_INTERNAL_TOKEN_NAME, nickname);
} else {
String tokenname1 = nickname.substring(0, index);
signingUnit.updateConfig(nickname, tokenname1);
extensions = jssSubSystem.getExtensions(tokenname1,
- nicknameWithoutTokenName);
+ nicknameWithoutTokenName);
}
if (extensions != null) {
BasicConstraintsExtension basic =
- (BasicConstraintsExtension)
- extensions.get(BasicConstraintsExtension.class.getSimpleName());
+ (BasicConstraintsExtension)
+ extensions.get(BasicConstraintsExtension.class.getSimpleName());
if (basic == null)
log(CMS.getLogMessage("ADMIN_SRVLT_BASIC_CONSTRAIN_NULL"));
else {
Integer pathlen = (Integer)
- basic.get(BasicConstraintsExtension.PATH_LEN);
+ basic.get(BasicConstraintsExtension.PATH_LEN);
int num = pathlen.intValue();
if (num == 0)
@@ -2187,34 +2164,34 @@ private void createMasterKey(HttpServletRequest req,
} else if (certType.equals(Constants.PR_RA_SIGNING_CERT)) {
setRANewnickname("", "");
IRegistrationAuthority ra =
- (IRegistrationAuthority) CMS.getSubsystem(CMS.SUBSYSTEM_RA);
+ (IRegistrationAuthority) CMS.getSubsystem(CMS.SUBSYSTEM_RA);
ra.setNickname(nickname);
} else if (certType.equals(Constants.PR_OCSP_SIGNING_CERT)) {
setOCSPNewnickname("", "");
IOCSPAuthority ocsp =
- (IOCSPAuthority) CMS.getSubsystem(CMS.SUBSYSTEM_OCSP);
+ (IOCSPAuthority) CMS.getSubsystem(CMS.SUBSYSTEM_OCSP);
if (ocsp != null) {
ISigningUnit signingUnit = ocsp.getSigningUnit();
if (nickname.equals(nicknameWithoutTokenName)) {
signingUnit.updateConfig(nickname,
- Constants.PR_INTERNAL_TOKEN_NAME);
+ Constants.PR_INTERNAL_TOKEN_NAME);
} else {
String tokenname1 = nickname.substring(0, index);
signingUnit.updateConfig(nickname, tokenname1);
}
- } else {
+ } else {
ICertificateAuthority ca =
- (ICertificateAuthority)
- CMS.getSubsystem(CMS.SUBSYSTEM_CA);
+ (ICertificateAuthority)
+ CMS.getSubsystem(CMS.SUBSYSTEM_CA);
ISigningUnit signingUnit = ca.getOCSPSigningUnit();
if (nickname.equals(nicknameWithoutTokenName)) {
signingUnit.updateConfig(nickname,
- Constants.PR_INTERNAL_TOKEN_NAME);
+ Constants.PR_INTERNAL_TOKEN_NAME);
} else {
String tokenname1 = nickname.substring(0, index);
@@ -2224,24 +2201,24 @@ private void createMasterKey(HttpServletRequest req,
} else if (certType.equals(Constants.PR_KRA_TRANSPORT_CERT)) {
setKRANewnickname("", "");
IKeyRecoveryAuthority kra =
- (IKeyRecoveryAuthority) CMS.getSubsystem(CMS.SUBSYSTEM_KRA);
+ (IKeyRecoveryAuthority) CMS.getSubsystem(CMS.SUBSYSTEM_KRA);
kra.setNickname(nickname);
} else if (certType.equals(Constants.PR_SERVER_CERT)) {
setAgentNewnickname("", "");
- //modifyRADMCert(nickname);
+ // modifyRADMCert(nickname);
modifyAgentGatewayCert(nickname);
if (isSubsystemInstalled("ra")) {
IRegistrationAuthority ra =
- (IRegistrationAuthority)
- CMS.getSubsystem(CMS.SUBSYSTEM_RA);
+ (IRegistrationAuthority)
+ CMS.getSubsystem(CMS.SUBSYSTEM_RA);
modifyEEGatewayCert(ra, nickname);
}
if (isSubsystemInstalled("ca")) {
ICertificateAuthority ca =
- (ICertificateAuthority)
- CMS.getSubsystem(CMS.SUBSYSTEM_CA);
+ (ICertificateAuthority)
+ CMS.getSubsystem(CMS.SUBSYSTEM_CA);
modifyCAGatewayCert(ca, nickname);
}
@@ -2252,7 +2229,7 @@ private void createMasterKey(HttpServletRequest req,
boolean verified = CMS.verifySystemCertByNickname(nickname, null);
if (verified == true) {
- CMS.debug("CMSAdminServlet: installCert(): verifySystemCertByNickname() succeeded:"+ nickname);
+ CMS.debug("CMSAdminServlet: installCert(): verifySystemCertByNickname() succeeded:" + nickname);
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CIMC_CERT_VERIFICATION,
auditSubjectID,
@@ -2261,7 +2238,7 @@ private void createMasterKey(HttpServletRequest req,
audit(auditMessage);
} else {
- CMS.debug("CMSAdminServlet: installCert(): verifySystemCertByNickname() failed:"+ nickname);
+ CMS.debug("CMSAdminServlet: installCert(): verifySystemCertByNickname() failed:" + nickname);
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CIMC_CERT_VERIFICATION,
auditSubjectID,
@@ -2280,11 +2257,11 @@ private void createMasterKey(HttpServletRequest req,
audit(auditMessage);
mConfig.commit(true);
- if(verified == true) {
+ if (verified == true) {
sendResponse(SUCCESS, null, null, resp);
} else {
sendResponse(ERROR, CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_CERT_VALIDATE_FAILED"),
- null, resp);
+ null, resp);
}
} catch (EBaseException eAudit1) {
// store a message in the signed audit log file
@@ -2310,37 +2287,38 @@ private void createMasterKey(HttpServletRequest req,
// rethrow the specific exception to be handled later
throw eAudit2;
- // } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_TRUSTED_PUBLIC_KEY,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
- //
- // audit( auditMessage );
- //
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
- }
+ // } catch( ServletException eAudit3 ) {
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_TRUSTED_PUBLIC_KEY,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
+ //
+ // audit( auditMessage );
+ //
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
+ }
}
/**
- * For "importing" cross-signed cert into internal db for further
- * cross pair matching and publishing
+ * For "importing" cross-signed cert into internal db for further cross pair
+ * matching and publishing
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_TRUSTED_PUBLIC_KEY used when
* "Certificate Setup Wizard" is used to import a CA cross-signed
* certificate into the database
* </ul>
+ *
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
* @exception EBaseException failed to import a cross-certificate pair
*/
private void importXCert(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -2355,7 +2333,7 @@ private void createMasterKey(HttpServletRequest req,
String serverID = "";
String certpath = "";
@SuppressWarnings("unchecked")
- Enumeration<String> enum1 = req.getParameterNames();
+ Enumeration<String> enum1 = req.getParameterNames();
NameValuePairs results = new NameValuePairs();
while (enum1.hasMoreElements()) {
@@ -2363,29 +2341,29 @@ private void createMasterKey(HttpServletRequest req,
String value = req.getParameter(key);
// really should be PR_CERT_CONTENT
- if (key.equals(Constants.PR_PKCS10))
+ if (key.equals(Constants.PR_PKCS10))
b64Cert = value;
else if (key.equals(Constants.RS_ID))
certType = value;
- else if (key.equals("pathname"))
+ else if (key.equals("pathname"))
pathname = value;
else if (key.equals(Constants.PR_SERVER_ROOT))
serverRoot = value;
- else if (key.equals(Constants.PR_SERVER_ID))
+ else if (key.equals(Constants.PR_SERVER_ID))
serverID = value;
- else if (key.equals(Constants.PR_CERT_FILEPATH))
+ else if (key.equals(Constants.PR_CERT_FILEPATH))
certpath = value;
}
-
+
try {
if (b64Cert == null || b64Cert.equals("")) {
if (certpath == null || certpath.equals("")) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CONFIG_TRUSTED_PUBLIC_KEY,
- auditSubjectID,
- ILogger.FAILURE,
- auditParams(req));
+ LOGGING_SIGNED_AUDIT_CONFIG_TRUSTED_PUBLIC_KEY,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditParams(req));
audit(auditMessage);
@@ -2396,7 +2374,7 @@ private void createMasterKey(HttpServletRequest req,
} else {
FileInputStream in = new FileInputStream(certpath);
BufferedReader d =
- new BufferedReader(new InputStreamReader(in));
+ new BufferedReader(new InputStreamReader(in));
String content = "";
b64Cert = "";
@@ -2423,7 +2401,7 @@ private void createMasterKey(HttpServletRequest req,
audit(auditMessage);
throw new EBaseException(
- CMS.getLogMessage("BASE_OPEN_FILE_FAILED"));
+ CMS.getLogMessage("BASE_OPEN_FILE_FAILED"));
}
CMS.debug("CMSAdminServlet: got b64Cert");
b64Cert = Cert.stripBrackets(b64Cert.trim());
@@ -2441,10 +2419,10 @@ private void createMasterKey(HttpServletRequest req,
+ File.separator + "config" + File.separator + pathname;
ICrossCertPairSubsystem ccps =
- (ICrossCertPairSubsystem) CMS.getSubsystem("CrossCertPair");
+ (ICrossCertPairSubsystem) CMS.getSubsystem("CrossCertPair");
try {
- //this will import into internal ldap crossCerts entry
+ // this will import into internal ldap crossCerts entry
ccps.importCert(bCert);
} catch (Exception e) {
// store a message in the signed audit log file
@@ -2480,8 +2458,8 @@ private void createMasterKey(HttpServletRequest req,
}
ICryptoSubsystem jssSubSystem = (ICryptoSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
- String content = jssSubSystem.getCertPrettyPrint(b64Cert,
+ CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
+ String content = jssSubSystem.getCertPrettyPrint(b64Cert,
super.getLocale(req));
results.add(Constants.PR_NICKNAME, "FBCA cross-signed cert");
@@ -2521,19 +2499,19 @@ private void createMasterKey(HttpServletRequest req,
// rethrow the specific exception to be handled later
throw eAudit2;
- // } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_TRUSTED_PUBLIC_KEY,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
- //
- // audit( auditMessage );
- //
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
- }
+ // } catch( ServletException eAudit3 ) {
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_TRUSTED_PUBLIC_KEY,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
+ //
+ // audit( auditMessage );
+ //
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
+ }
}
private String getNickname(String certType) throws EBaseException {
@@ -2541,13 +2519,13 @@ private void createMasterKey(HttpServletRequest req,
if (certType.equals(Constants.PR_CA_SIGNING_CERT)) {
ICertificateAuthority ca =
- (ICertificateAuthority) CMS.getSubsystem(CMS.SUBSYSTEM_CA);
+ (ICertificateAuthority) CMS.getSubsystem(CMS.SUBSYSTEM_CA);
ISigningUnit signingUnit = ca.getSigningUnit();
nickname = signingUnit.getNickname();
} else if (certType.equals(Constants.PR_OCSP_SIGNING_CERT)) {
IOCSPAuthority ocsp =
- (IOCSPAuthority) CMS.getSubsystem(CMS.SUBSYSTEM_OCSP);
+ (IOCSPAuthority) CMS.getSubsystem(CMS.SUBSYSTEM_OCSP);
if (ocsp == null) {
// this is a local CA service
@@ -2562,28 +2540,28 @@ private void createMasterKey(HttpServletRequest req,
}
} else if (certType.equals(Constants.PR_RA_SIGNING_CERT)) {
IRegistrationAuthority ra =
- (IRegistrationAuthority) CMS.getSubsystem(CMS.SUBSYSTEM_RA);
+ (IRegistrationAuthority) CMS.getSubsystem(CMS.SUBSYSTEM_RA);
nickname = ra.getNickname();
} else if (certType.equals(Constants.PR_KRA_TRANSPORT_CERT)) {
IKeyRecoveryAuthority kra =
- (IKeyRecoveryAuthority) CMS.getSubsystem(CMS.SUBSYSTEM_KRA);
+ (IKeyRecoveryAuthority) CMS.getSubsystem(CMS.SUBSYSTEM_KRA);
nickname = kra.getNickname();
} else if (certType.equals(Constants.PR_SERVER_CERT)) {
nickname = CMS.getServerCertNickname();
} else if (certType.equals(Constants.PR_SERVER_CERT_RADM)) {
nickname = CMS.getServerCertNickname();
- }
+ }
return nickname;
}
private void getCertInfo(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
@SuppressWarnings("unchecked")
- Enumeration<String> enum1 = req.getParameterNames();
+ Enumeration<String> enum1 = req.getParameterNames();
NameValuePairs results = new NameValuePairs();
String pkcs = "";
String path = "";
@@ -2616,7 +2594,7 @@ private void createMasterKey(HttpServletRequest req,
} else {
FileInputStream in = new FileInputStream(path);
BufferedReader d =
- new BufferedReader(new InputStreamReader(in));
+ new BufferedReader(new InputStreamReader(in));
String content = "";
pkcs = "";
@@ -2640,7 +2618,7 @@ private void createMasterKey(HttpServletRequest req,
int totalLen = pkcs.length();
if (pkcs.indexOf(BEGIN_HEADER) != 0 ||
- pkcs.indexOf(END_HEADER) != (totalLen - 25)) {
+ pkcs.indexOf(END_HEADER) != (totalLen - 25)) {
throw (new EBaseException(CMS.getLogMessage("BASE_INVALID_CERT_FORMAT")));
}
@@ -2665,25 +2643,25 @@ private void createMasterKey(HttpServletRequest req,
nickname = getNickname(certType);
ICryptoSubsystem jssSubSystem = (ICryptoSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
String content = jssSubSystem.getCertPrettyPrint(pkcs,
super.getLocale(req));
if (nickname != null && !nickname.equals(""))
results.add(Constants.PR_NICKNAME, nickname);
results.add(Constants.PR_CERT_CONTENT, content);
- //results = jssSubSystem.getCertInfo(value);
+ // results = jssSubSystem.getCertInfo(value);
sendResponse(SUCCESS, null, results, resp);
}
private void getCertPrettyPrint(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
- @SuppressWarnings("unchecked")
+ @SuppressWarnings("unchecked")
Enumeration<String> enum1 = req.getParameterNames();
ICryptoSubsystem jssSubSystem = (ICryptoSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
String nickname = "";
String serialno = "";
String issuername = "";
@@ -2703,7 +2681,7 @@ private void createMasterKey(HttpServletRequest req,
if (key.equals(Constants.PR_NICK_NAME)) {
nickname = value;
continue;
- }
+ }
if (key.equals(Constants.PR_SERIAL_NUMBER)) {
serialno = value;
continue;
@@ -2714,20 +2692,20 @@ private void createMasterKey(HttpServletRequest req,
}
}
- String print = jssSubSystem.getCertPrettyPrintAndFingerPrint(nickname,
- serialno, issuername, locale);
+ String print = jssSubSystem.getCertPrettyPrintAndFingerPrint(nickname,
+ serialno, issuername, locale);
pairs.add(nickname, print);
sendResponse(SUCCESS, null, pairs, resp);
}
private void getRootCertTrustBit(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
- @SuppressWarnings("unchecked")
+ @SuppressWarnings("unchecked")
Enumeration<String> enum1 = req.getParameterNames();
ICryptoSubsystem jssSubSystem = (ICryptoSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
String nickname = "";
String serialno = "";
String issuername = "";
@@ -2759,92 +2737,92 @@ private void createMasterKey(HttpServletRequest req,
}
String trustbit = jssSubSystem.getRootCertTrustBit(nickname,
- serialno, issuername);
+ serialno, issuername);
pairs.add(nickname, trustbit);
sendResponse(SUCCESS, null, pairs, resp);
}
private void getCACerts(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
ICryptoSubsystem jssSubSystem = (ICryptoSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
NameValuePairs pairs = jssSubSystem.getCACerts();
sendResponse(SUCCESS, null, pairs, resp);
}
private void deleteRootCert(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String id = req.getParameter(Constants.RS_ID);
ICryptoSubsystem jssSubSystem = (ICryptoSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
int mindex = id.indexOf(":SERIAL#<");
String nickname = id.substring(0, mindex);
String sstr1 = id.substring(mindex);
int lindex = sstr1.indexOf(">");
String serialno = sstr1.substring(9, lindex);
- String issuername = sstr1.substring(lindex+1);
+ String issuername = sstr1.substring(lindex + 1);
jssSubSystem.deleteRootCert(nickname, serialno, issuername);
sendResponse(SUCCESS, null, null, resp);
}
private void deleteUserCert(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String id = req.getParameter(Constants.RS_ID);
ICryptoSubsystem jssSubSystem = (ICryptoSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
int mindex = id.indexOf(":SERIAL#<");
String nickname = id.substring(0, mindex);
String sstr1 = id.substring(mindex);
int lindex = sstr1.indexOf(">");
String serialno = sstr1.substring(9, lindex);
- String issuername = sstr1.substring(lindex+1);
+ String issuername = sstr1.substring(lindex + 1);
jssSubSystem.deleteUserCert(nickname, serialno, issuername);
sendResponse(SUCCESS, null, null, resp);
}
private void getRootCerts(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
ICryptoSubsystem jssSubSystem = (ICryptoSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
NameValuePairs pairs = jssSubSystem.getRootCerts();
sendResponse(SUCCESS, null, pairs, resp);
}
private void getAllCertsManage(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
ICryptoSubsystem jssSubSystem = (ICryptoSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
NameValuePairs pairs = jssSubSystem.getAllCertsManage();
sendResponse(SUCCESS, null, pairs, resp);
}
private void getUserCerts(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
ICryptoSubsystem jssSubSystem = (ICryptoSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
NameValuePairs pairs = jssSubSystem.getUserCerts();
sendResponse(SUCCESS, null, pairs, resp);
}
private void deleteCerts(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
- @SuppressWarnings("unchecked")
+ @SuppressWarnings("unchecked")
Enumeration<String> enum1 = req.getParameterNames();
ICryptoSubsystem jssSubSystem = (ICryptoSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
String nickname = "";
String date = "";
@@ -2862,19 +2840,19 @@ private void createMasterKey(HttpServletRequest req,
nickname = value.substring(0, index);
date = value.substring(index + 1);
- // cant use this one now since jss doesnt have the interface to
+ // cant use this one now since jss doesnt have the interface to
// do it.
jssSubSystem.deleteCert(nickname, date);
- // jssSubsystem.deleteCACert(nickname, date);
+ // jssSubsystem.deleteCACert(nickname, date);
}
sendResponse(SUCCESS, null, null, resp);
}
private void validateSubjectName(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
- @SuppressWarnings("unchecked")
+ @SuppressWarnings("unchecked")
Enumeration<String> enum1 = req.getParameterNames();
while (enum1.hasMoreElements()) {
@@ -2883,19 +2861,19 @@ private void createMasterKey(HttpServletRequest req,
if (key.equals(Constants.PR_SUBJECT_NAME)) {
ICryptoSubsystem jssSubSystem = (ICryptoSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
jssSubSystem.isX500DN(value);
}
}
sendResponse(SUCCESS, null, null, resp);
- }
+ }
private void validateKeyLength(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
- @SuppressWarnings("unchecked")
+ @SuppressWarnings("unchecked")
Enumeration<String> enum1 = req.getParameterNames();
String keyType = "RSA";
String keyLen = "512";
@@ -2917,16 +2895,16 @@ private void createMasterKey(HttpServletRequest req,
int minKey = mConfig.getInteger(
ConfigConstants.PR_RSA_MIN_KEYLENGTH, 512);
ICryptoSubsystem jssSubSystem = (ICryptoSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
// jssSubSystem.checkKeyLength(keyType, keyLength, certType, minKey);
sendResponse(SUCCESS, null, null, resp);
}
private void validateCurveName(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
- @SuppressWarnings("unchecked")
+ @SuppressWarnings("unchecked")
Enumeration<String> enum1 = req.getParameterNames();
String curveName = null;
@@ -2942,7 +2920,7 @@ private void createMasterKey(HttpServletRequest req,
String curveList = mConfig.getString("keys.ecc.curve.list", "nistp521");
String[] curves = curveList.split(",");
boolean match = false;
- for (int i=0; i<curves.length; i++) {
+ for (int i = 0; i < curves.length; i++) {
if (curves[i].equals(curveName)) {
match = true;
}
@@ -2955,9 +2933,9 @@ private void createMasterKey(HttpServletRequest req,
}
private void validateCertExtension(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
- @SuppressWarnings("unchecked")
+ @SuppressWarnings("unchecked")
Enumeration<String> enum1 = req.getParameterNames();
String certExt = "";
@@ -2972,19 +2950,19 @@ private void createMasterKey(HttpServletRequest req,
}
ICryptoSubsystem jssSubSystem = (ICryptoSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
jssSubSystem.checkCertificateExt(certExt);
sendResponse(SUCCESS, null, null, resp);
}
private void getSubjectName(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
@SuppressWarnings("unchecked")
Enumeration<String> enum1 = req.getParameterNames();
-
+
String nickname = "";
String keyType = "RSA";
String keyLen = "512";
@@ -3003,7 +2981,7 @@ private void createMasterKey(HttpServletRequest req,
}
ICryptoSubsystem jssSubSystem = (ICryptoSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
String subjectName = jssSubSystem.getSubjectDN(nickname);
params.add(Constants.PR_SUBJECT_NAME, subjectName);
@@ -3011,7 +2989,7 @@ private void createMasterKey(HttpServletRequest req,
}
private void processSubjectName(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
@SuppressWarnings("unchecked")
@@ -3033,7 +3011,7 @@ private void createMasterKey(HttpServletRequest req,
}
ICryptoSubsystem jssSubSystem = (ICryptoSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
String subjectName = jssSubSystem.getSubjectDN(nickname);
params.add(Constants.PR_SUBJECT_NAME, subjectName);
@@ -3041,7 +3019,7 @@ private void createMasterKey(HttpServletRequest req,
}
public void setRootCertTrust(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -3053,10 +3031,10 @@ private void createMasterKey(HttpServletRequest req,
CMS.debug("CMSAdminServlet: setRootCertTrust()");
ICryptoSubsystem jssSubSystem = (ICryptoSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
try {
jssSubSystem.setRootCertTrust(nickname, serialno, issuername, trust);
- } catch (EBaseException e) {
+ } catch (EBaseException e) {
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CONFIG_TRUSTED_PUBLIC_KEY,
auditSubjectID,
@@ -3083,18 +3061,19 @@ private void createMasterKey(HttpServletRequest req,
/**
* Establish trust of a CA certificate
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_TRUSTED_PUBLIC_KEY used when
- * "Manage Certificate" is used to edit the trustness of certs and
- * deletion of certs
+ * "Manage Certificate" is used to edit the trustness of certs and deletion
+ * of certs
* </ul>
+ *
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
* @exception EBaseException failed to establish CA certificate trust
*/
private void trustCACert(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -3104,10 +3083,10 @@ private void createMasterKey(HttpServletRequest req,
// ensure that any low-level exceptions are reported
// to the signed audit log and stored as failures
try {
- @SuppressWarnings("unchecked")
+ @SuppressWarnings("unchecked")
Enumeration<String> enum1 = req.getParameterNames();
ICryptoSubsystem jssSubSystem = (ICryptoSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
+ CMS.getSubsystem(CMS.SUBSYSTEM_CRYPTO);
String trust = "";
while (enum1.hasMoreElements()) {
@@ -3134,7 +3113,7 @@ private void createMasterKey(HttpServletRequest req,
audit(auditMessage);
- //sendResponse(SUCCESS, null, null, resp);
+ // sendResponse(SUCCESS, null, null, resp);
sendResponse(RESTART, null, null, resp);
} catch (EBaseException eAudit1) {
// store a message in the signed audit log file
@@ -3160,41 +3139,42 @@ private void createMasterKey(HttpServletRequest req,
// rethrow the specific exception to be handled later
throw eAudit2;
- // } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_TRUSTED_PUBLIC_KEY,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
- //
- // audit( auditMessage );
- //
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
- }
+ // } catch( ServletException eAudit3 ) {
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_TRUSTED_PUBLIC_KEY,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
+ //
+ // audit( auditMessage );
+ //
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
+ }
}
/**
* Execute all self tests specified to be run on demand.
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_SELFTESTS_EXECUTION used when self
* tests are run on demand
* </ul>
- * @exception EMissingSelfTestException a self test plugin instance
- * property name was missing
+ *
+ * @exception EMissingSelfTestException a self test plugin instance property
+ * name was missing
* @exception ESelfTestException a self test is missing a required
- * configuration parameter
+ * configuration parameter
* @exception IOException an input/output error has occurred
*/
private synchronized void
- runSelfTestsOnDemand(HttpServletRequest req,
- HttpServletResponse resp)
- throws EMissingSelfTestException,
- ESelfTestException,
- IOException {
+ runSelfTestsOnDemand(HttpServletRequest req,
+ HttpServletResponse resp)
+ throws EMissingSelfTestException,
+ ESelfTestException,
+ IOException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -3203,7 +3183,7 @@ private void createMasterKey(HttpServletRequest req,
try {
if (CMS.debugOn()) {
CMS.debug("CMSAdminServlet::runSelfTestsOnDemand():"
- + " ENTERING . . .");
+ + " ENTERING . . .");
}
@SuppressWarnings("unchecked")
Enumeration<String> enum1 = req.getParameterNames();
@@ -3224,10 +3204,10 @@ private void createMasterKey(HttpServletRequest req,
}
ISelfTestSubsystem mSelfTestSubsystem = (ISelfTestSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_SELFTESTS);
+ CMS.getSubsystem(CMS.SUBSYSTEM_SELFTESTS);
if ((request == null) ||
- (request.equals(""))) {
+ (request.equals(""))) {
// self test plugin run on demand request parameter was missing
// log the error
logMessage = CMS.getLogMessage("SELFTESTS_RUN_ON_DEMAND_REQUEST",
@@ -3236,7 +3216,7 @@ private void createMasterKey(HttpServletRequest req,
);
mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
- logMessage);
+ logMessage);
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -3264,7 +3244,7 @@ private void createMasterKey(HttpServletRequest req,
getServletInfo());
mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
- logMessage);
+ logMessage);
// store this information for console notification
content += logMessage
@@ -3288,8 +3268,8 @@ private void createMasterKey(HttpServletRequest req,
getServletInfo());
mSelfTestSubsystem.log(
- mSelfTestSubsystem.getSelfTestLogger(),
- logMessage);
+ mSelfTestSubsystem.getSelfTestLogger(),
+ logMessage);
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -3309,18 +3289,19 @@ private void createMasterKey(HttpServletRequest req,
}
ISelfTest test = (ISelfTest)
- mSelfTestSubsystem.getSelfTest(instanceName);
+ mSelfTestSubsystem.getSelfTest(instanceName);
if (test == null) {
- // self test plugin instance property name is not present
+ // self test plugin instance property name is not
+ // present
// log the error
logMessage = CMS.getLogMessage("SELFTESTS_MISSING_NAME",
getServletInfo(),
instanceFullName);
mSelfTestSubsystem.log(
- mSelfTestSubsystem.getSelfTestLogger(),
- logMessage);
+ mSelfTestSubsystem.getSelfTestLogger(),
+ logMessage);
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -3342,9 +3323,9 @@ private void createMasterKey(HttpServletRequest req,
try {
if (CMS.debugOn()) {
CMS.debug("CMSAdminServlet::runSelfTestsOnDemand():"
- + " running \""
- + test.getSelfTestName()
- + "\"");
+ + " running \""
+ + test.getSelfTestName()
+ + "\"");
}
// store this information for console notification
@@ -3368,8 +3349,8 @@ private void createMasterKey(HttpServletRequest req,
instanceFullName);
mSelfTestSubsystem.log(
- mSelfTestSubsystem.getSelfTestLogger(),
- logMessage);
+ mSelfTestSubsystem.getSelfTestLogger(),
+ logMessage);
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -3401,7 +3382,7 @@ private void createMasterKey(HttpServletRequest req,
logMessage = CMS.getLogMessage("SELFTESTS_RUN_ON_DEMAND_SUCCEEDED",
getServletInfo());
mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
- logMessage);
+ logMessage);
// store this information for console notification
content += logMessage
@@ -3412,7 +3393,7 @@ private void createMasterKey(HttpServletRequest req,
getServletInfo());
mSelfTestSubsystem.log(mSelfTestSubsystem.getSelfTestLogger(),
- logMessage);
+ logMessage);
// store this information for console notification
content += logMessage
@@ -3429,14 +3410,14 @@ private void createMasterKey(HttpServletRequest req,
// notify console of SUCCESS
results.add(Constants.PR_RUN_SELFTESTS_ON_DEMAND_CLASS,
- CMSAdminServlet.class.getName());
+ CMSAdminServlet.class.getName());
results.add(Constants.PR_RUN_SELFTESTS_ON_DEMAND_CONTENT,
- content);
+ content);
sendResponse(SUCCESS, null, results, resp);
if (CMS.debugOn()) {
CMS.debug("CMSAdminServlet::runSelfTestsOnDemand():"
- + " EXITING.");
+ + " EXITING.");
}
} catch (EMissingSelfTestException eAudit1) {
// store a message in the signed audit log file
@@ -3475,16 +3456,16 @@ private void createMasterKey(HttpServletRequest req,
}
public void log(int level, String msg) {
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, level, "CMSAdminServlet: " + msg);
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, level, "CMSAdminServlet: " + msg);
}
/**
* Signed Audit Log Public Key
- *
+ *
* This method is called to obtain the public key from the passed in
* "KeyPair" object for a signed audit log message.
* <P>
- *
+ *
* @param object a Key Pair Object
* @return key string containing the public key
*/
@@ -3533,4 +3514,3 @@ private void createMasterKey(HttpServletRequest req,
}
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/admin/JobsAdminServlet.java b/pki/base/common/src/com/netscape/cms/servlet/admin/JobsAdminServlet.java
index 7f18d94e..dffa4034 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/admin/JobsAdminServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/admin/JobsAdminServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.admin;
-
import java.io.IOException;
import java.util.Enumeration;
import java.util.Locale;
@@ -42,10 +41,9 @@ import com.netscape.certsrv.jobs.IJobsScheduler;
import com.netscape.certsrv.jobs.JobPlugin;
import com.netscape.certsrv.logging.ILogger;
-
/**
- * A class representing an administration servlet for the
- * Jobs Scheduler and it's scheduled jobs.
+ * A class representing an administration servlet for the Jobs Scheduler and
+ * it's scheduled jobs.
*
* @version $Revision$, $Date$
*/
@@ -82,16 +80,16 @@ public class JobsAdminServlet extends AdminServlet {
/**
* Returns serlvet information.
*/
- public String getServletInfo() {
- return INFO;
+ public String getServletInfo() {
+ return INFO;
}
- /**
- * retrieve extended plugin info such as brief description, type info
- * from jobs
+ /**
+ * retrieve extended plugin info such as brief description, type info from
+ * jobs
*/
private void getExtendedPluginInfo(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String id = req.getParameter(Constants.RS_ID);
@@ -100,8 +98,8 @@ public class JobsAdminServlet extends AdminServlet {
String implType = id.substring(0, colon);
String implName = id.substring(colon + 1);
- NameValuePairs params =
- getExtendedPluginInfo(getLocale(req), implType, implName);
+ NameValuePairs params =
+ getExtendedPluginInfo(getLocale(req), implType, implName);
sendResponse(SUCCESS, null, params, resp);
}
@@ -111,7 +109,7 @@ public class JobsAdminServlet extends AdminServlet {
Object impl = null;
JobPlugin jp =
- (JobPlugin) mJobsSched.getPlugins().get(implName);
+ (JobPlugin) mJobsSched.getPlugins().get(implName);
if (jp != null)
impl = getClassByNameAsExtendedPluginInfo(jp.getClassPath());
@@ -137,25 +135,25 @@ public class JobsAdminServlet extends AdminServlet {
* Serves HTTP admin request.
*/
public void service(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
+ throws ServletException, IOException {
super.service(req, resp);
String scope = req.getParameter(Constants.OP_SCOPE);
String op = req.getParameter(Constants.OP_TYPE);
if (op == null) {
- //System.out.println("SRVLT_INVALID_PROTOCOL");
- sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_PROTOCOL"),
- null, resp);
+ // System.out.println("SRVLT_INVALID_PROTOCOL");
+ sendResponse(ERROR,
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_PROTOCOL"),
+ null, resp);
return;
}
try {
super.authenticate(req);
} catch (IOException e) {
- sendResponse(ERROR,CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHS_FAILED"),
- null, resp);
+ sendResponse(ERROR, CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHS_FAILED"),
+ null, resp);
return;
}
@@ -165,8 +163,8 @@ public class JobsAdminServlet extends AdminServlet {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_JOBS))
@@ -174,27 +172,27 @@ public class JobsAdminServlet extends AdminServlet {
else if (scope.equals(ScopeDef.SC_JOBS_IMPLS))
getConfig(req, resp);
else if (scope.equals(ScopeDef.SC_JOBS_INSTANCE))
- getInstConfig(req, resp);
+ getInstConfig(req, resp);
else if (scope.equals(ScopeDef.SC_EXTENDED_PLUGIN_INFO)) {
- try {
- getExtendedPluginInfo(req, resp);
- } catch (EBaseException e) {
- sendResponse(ERROR, e.toString(getLocale(req)), null, resp);
- return;
+ try {
+ getExtendedPluginInfo(req, resp);
+ } catch (EBaseException e) {
+ sendResponse(ERROR, e.toString(getLocale(req)), null, resp);
+ return;
}
} else {
- //System.out.println("SRVLT_INVALID_OP_SCOPE");
- sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
- null, resp);
+ // System.out.println("SRVLT_INVALID_OP_SCOPE");
+ sendResponse(ERROR,
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
+ null, resp);
return;
}
} else if (op.equals(OpDef.OP_MODIFY)) {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_JOBS)) {
@@ -202,17 +200,17 @@ public class JobsAdminServlet extends AdminServlet {
} else if (scope.equals(ScopeDef.SC_JOBS_INSTANCE)) {
modJobsInst(req, resp, scope);
} else {
- sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
- null, resp);
+ sendResponse(ERROR,
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
+ null, resp);
return;
}
} else if (op.equals(OpDef.OP_SEARCH)) {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_JOBS_IMPLS))
@@ -220,18 +218,18 @@ public class JobsAdminServlet extends AdminServlet {
else if (scope.equals(ScopeDef.SC_JOBS_INSTANCE))
listJobsInsts(req, resp);
else {
- //System.out.println("SRVLT_INVALID_OP_SCOPE");
- sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
- null, resp);
+ // System.out.println("SRVLT_INVALID_OP_SCOPE");
+ sendResponse(ERROR,
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
+ null, resp);
return;
}
} else if (op.equals(OpDef.OP_ADD)) {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_JOBS_IMPLS))
@@ -239,18 +237,18 @@ public class JobsAdminServlet extends AdminServlet {
else if (scope.equals(ScopeDef.SC_JOBS_INSTANCE))
addJobsInst(req, resp, scope);
else {
- //System.out.println("SRVLT_INVALID_OP_SCOPE");
- sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
- null, resp);
+ // System.out.println("SRVLT_INVALID_OP_SCOPE");
+ sendResponse(ERROR,
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
+ null, resp);
return;
}
} else if (op.equals(OpDef.OP_DELETE)) {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_JOBS_IMPLS))
@@ -258,42 +256,42 @@ public class JobsAdminServlet extends AdminServlet {
else if (scope.equals(ScopeDef.SC_JOBS_INSTANCE))
delJobsInst(req, resp, scope);
else {
- //System.out.println("SRVLT_INVALID_OP_SCOPE");
- sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
- null, resp);
+ // System.out.println("SRVLT_INVALID_OP_SCOPE");
+ sendResponse(ERROR,
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
+ null, resp);
return;
}
} else {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_TYPE", op),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_TYPE", op),
+ null, resp);
return;
}
} catch (EBaseException e) {
sendResponse(ERROR, e.toString(getLocale(req)), null, resp);
return;
- }
+ }
}
- private synchronized void addJobPlugin(HttpServletRequest req,
- HttpServletResponse resp, String scope)
- throws ServletException, IOException, EBaseException {
+ private synchronized void addJobPlugin(HttpServletRequest req,
+ HttpServletResponse resp, String scope)
+ throws ServletException, IOException, EBaseException {
String id = req.getParameter(Constants.RS_ID);
if (id == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
// is the job plugin id unique?
if (mJobsSched.getPlugins().containsKey((Object) id)) {
sendResponse(ERROR,
- new EJobsException(CMS.getUserMessage(getLocale(req),"CMS_JOB_SRVLT_ILL_JOB_PLUGIN_ID", id)).toString(),
- null, resp);
+ new EJobsException(CMS.getUserMessage(getLocale(req), "CMS_JOB_SRVLT_ILL_JOB_PLUGIN_ID", id)).toString(),
+ null, resp);
return;
}
@@ -301,15 +299,15 @@ public class JobsAdminServlet extends AdminServlet {
if (classPath == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_JOB_SRVLT_NULL_CLASS"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_JOB_SRVLT_NULL_CLASS"),
+ null, resp);
return;
}
IConfigStore destStore =
- mConfig.getSubStore(DestDef.DEST_JOBS_ADMIN);
+ mConfig.getSubStore(DestDef.DEST_JOBS_ADMIN);
IConfigStore instancesConfig =
- destStore.getSubStore(scope);
+ destStore.getSubStore(scope);
// Does the class exist?
Class newImpl = null;
@@ -318,13 +316,13 @@ public class JobsAdminServlet extends AdminServlet {
newImpl = Class.forName(classPath);
} catch (ClassNotFoundException e) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_JOB_SRVLT_NO_CLASS"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_JOB_SRVLT_NO_CLASS"),
+ null, resp);
return;
} catch (IllegalArgumentException e) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_JOB_SRVLT_NO_CLASS"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_JOB_SRVLT_NO_CLASS"),
+ null, resp);
return;
}
@@ -332,14 +330,14 @@ public class JobsAdminServlet extends AdminServlet {
try {
if (IJob.class.isAssignableFrom(newImpl) == false) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_JOB_SRVLT_ILL_CLASS"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_JOB_SRVLT_ILL_CLASS"),
+ null, resp);
return;
}
} catch (NullPointerException e) { // unlikely, only if newImpl null.
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_JOB_SRVLT_ILL_CLASS"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_JOB_SRVLT_ILL_CLASS"),
+ null, resp);
return;
}
@@ -351,10 +349,10 @@ public class JobsAdminServlet extends AdminServlet {
try {
mConfig.commit(true);
} catch (EBaseException e) {
- //System.out.println("SRVLT_FAIL_COMMIT");
+ // System.out.println("SRVLT_FAIL_COMMIT");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
+ null, resp);
return;
}
@@ -362,8 +360,8 @@ public class JobsAdminServlet extends AdminServlet {
JobPlugin plugin = new JobPlugin(id, classPath);
mJobsSched.getPlugins().put(id, plugin);
- mJobsSched.log(ILogger.LL_INFO,
- CMS.getLogMessage("ADMIN_SRVLT_JS_PLUGIN_ADD", id));
+ mJobsSched.log(ILogger.LL_INFO,
+ CMS.getLogMessage("ADMIN_SRVLT_JS_PLUGIN_ADD", id));
NameValuePairs params = new NameValuePairs();
@@ -371,24 +369,24 @@ public class JobsAdminServlet extends AdminServlet {
return;
}
- private synchronized void addJobsInst(HttpServletRequest req,
- HttpServletResponse resp, String scope)
- throws ServletException, IOException, EBaseException {
+ private synchronized void addJobsInst(HttpServletRequest req,
+ HttpServletResponse resp, String scope)
+ throws ServletException, IOException, EBaseException {
String id = req.getParameter(Constants.RS_ID);
if (id == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
// is the job instance id unique?
if (mJobsSched.getInstances().containsKey((Object) id)) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_JOB_SRVLT_ILL_JOB_INST_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_JOB_SRVLT_ILL_JOB_INST_ID"),
+ null, resp);
return;
}
@@ -399,21 +397,21 @@ public class JobsAdminServlet extends AdminServlet {
if (implname == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_JOB_SRVLT_ADD_MISSING_PARAMS"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_JOB_SRVLT_ADD_MISSING_PARAMS"),
+ null, resp);
return;
}
// check if implementation exists.
JobPlugin plugin =
- (JobPlugin) mJobsSched.getPlugins().get(implname);
+ (JobPlugin) mJobsSched.getPlugins().get(implname);
if (plugin == null) {
sendResponse(ERROR,
- new
- EJobsException(CMS.getUserMessage(getLocale(req),"CMS_JOB_SRVLT_JOB_PLUGIN_NOT_FOUND",
- id)).toString(),
- null, resp);
+ new
+ EJobsException(CMS.getUserMessage(getLocale(req), "CMS_JOB_SRVLT_JOB_PLUGIN_NOT_FOUND",
+ id)).toString(),
+ null, resp);
return;
}
@@ -423,9 +421,9 @@ public class JobsAdminServlet extends AdminServlet {
String[] configParams = mJobsSched.getConfigParams(implname);
IConfigStore destStore =
- mConfig.getSubStore(DestDef.DEST_JOBS_ADMIN);
+ mConfig.getSubStore(DestDef.DEST_JOBS_ADMIN);
IConfigStore instancesConfig =
- destStore.getSubStore(scope);
+ destStore.getSubStore(scope);
IConfigStore substore = instancesConfig.makeSubStore(id);
if (configParams != null) {
@@ -437,10 +435,10 @@ public class JobsAdminServlet extends AdminServlet {
substore.put(key, val);
} else if (!key.equals("profileId")) {
sendResponse(ERROR,
- new
- EJobsException(CMS.getUserMessage(getLocale(req),"CMS_JOB_SRVLT_MISSING_INST_PARAM_VAL",
- key)).toString(),
- null, resp);
+ new
+ EJobsException(CMS.getUserMessage(getLocale(req), "CMS_JOB_SRVLT_MISSING_INST_PARAM_VAL",
+ key)).toString(),
+ null, resp);
return;
}
}
@@ -458,28 +456,28 @@ public class JobsAdminServlet extends AdminServlet {
// cleanup
instancesConfig.removeSubStore(id);
sendResponse(ERROR,
- new EJobsException(
- CMS.getUserMessage(getLocale(req),"CMS_JOB_LOAD_CLASS_FAILED", className)).toString(),
- null, resp);
+ new EJobsException(
+ CMS.getUserMessage(getLocale(req), "CMS_JOB_LOAD_CLASS_FAILED", className)).toString(),
+ null, resp);
return;
} catch (InstantiationException e) {
instancesConfig.removeSubStore(id);
sendResponse(ERROR,
- new EJobsException(
- CMS.getUserMessage(getLocale(req),"CMS_JOB_LOAD_CLASS_FAILED", className)).toString(),
- null, resp);
+ new EJobsException(
+ CMS.getUserMessage(getLocale(req), "CMS_JOB_LOAD_CLASS_FAILED", className)).toString(),
+ null, resp);
return;
} catch (IllegalAccessException e) {
instancesConfig.removeSubStore(id);
sendResponse(ERROR,
- new EJobsException(
- CMS.getUserMessage(getLocale(req),"CMS_JOB_LOAD_CLASS_FAILED", className)).toString(),
- null, resp);
+ new EJobsException(
+ CMS.getUserMessage(getLocale(req), "CMS_JOB_LOAD_CLASS_FAILED", className)).toString(),
+ null, resp);
return;
}
-
+
IJobsScheduler scheduler = (IJobsScheduler)
- CMS.getSubsystem(CMS.SUBSYSTEM_JOBS);
+ CMS.getSubsystem(CMS.SUBSYSTEM_JOBS);
// initialize the job plugin
try {
@@ -498,16 +496,16 @@ public class JobsAdminServlet extends AdminServlet {
// clean up.
instancesConfig.removeSubStore(id);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
+ null, resp);
return;
}
// inited and commited ok. now add manager instance to list.
mJobsSched.getInstances().put(id, jobsInst);
- mJobsSched.log(ILogger.LL_INFO,
- CMS.getLogMessage("ADMIN_SRVLT_JOB_INST_ADD", id));
+ mJobsSched.log(ILogger.LL_INFO,
+ CMS.getLogMessage("ADMIN_SRVLT_JOB_INST_ADD", id));
NameValuePairs params = new NameValuePairs();
@@ -516,8 +514,8 @@ public class JobsAdminServlet extends AdminServlet {
return;
}
- private synchronized void listJobPlugins(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ private synchronized void listJobPlugins(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
@@ -525,83 +523,81 @@ public class JobsAdminServlet extends AdminServlet {
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
- JobPlugin value = (JobPlugin)
- mJobsSched.getPlugins().get(name);
+ JobPlugin value = (JobPlugin)
+ mJobsSched.getPlugins().get(name);
params.add(name, value.getClassPath());
- // params.add(name, value.getClassPath()+EDIT);
+ // params.add(name, value.getClassPath()+EDIT);
}
sendResponse(SUCCESS, null, params, resp);
return;
}
- private synchronized void listJobsInsts(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ private synchronized void listJobsInsts(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
- for (Enumeration e = mJobsSched.getInstances().keys();
- e.hasMoreElements();) {
+ for (Enumeration e = mJobsSched.getInstances().keys(); e.hasMoreElements();) {
String name = (String) e.nextElement();
- IJob value = (IJob)
- mJobsSched.getInstances().get((Object) name);
+ IJob value = (IJob)
+ mJobsSched.getInstances().get((Object) name);
- // params.add(name, value.getImplName());
+ // params.add(name, value.getImplName());
params.add(name, value.getImplName() + VISIBLE +
- (value.isEnabled() ? ENABLED : DISABLED)
- );
+ (value.isEnabled() ? ENABLED : DISABLED)
+ );
}
sendResponse(SUCCESS, null, params, resp);
return;
}
- private synchronized void delJobPlugin(HttpServletRequest req,
- HttpServletResponse resp, String scope) throws ServletException,
+ private synchronized void delJobPlugin(HttpServletRequest req,
+ HttpServletResponse resp, String scope) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
String id = req.getParameter(Constants.RS_ID);
if (id == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
// does this job plugin exist?
if (mJobsSched.getPlugins().containsKey(id) == false) {
sendResponse(ERROR,
- new
- EJobsException(CMS.getUserMessage(getLocale(req),"CMS_JOB_SRVLT_JOB_PLUGIN_NOT_FOUND",
- id)).toString(),
- null, resp);
+ new
+ EJobsException(CMS.getUserMessage(getLocale(req), "CMS_JOB_SRVLT_JOB_PLUGIN_NOT_FOUND",
+ id)).toString(),
+ null, resp);
return;
}
// first check if any instances from this job plugin
// DON'T remove job plugin if any instance
- for (Enumeration e = mJobsSched.getInstances().elements();
- e.hasMoreElements();) {
+ for (Enumeration e = mJobsSched.getInstances().elements(); e.hasMoreElements();) {
IJob jobs = (IJob) e.nextElement();
if ((jobs.getImplName()).equals(id)) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_JOB_SRVLT_JOB_IN_USE"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_JOB_SRVLT_JOB_IN_USE"),
+ null, resp);
return;
}
}
-
+
// then delete this job plugin
mJobsSched.getPlugins().remove((Object) id);
IConfigStore destStore =
- mConfig.getSubStore(DestDef.DEST_JOBS_ADMIN);
+ mConfig.getSubStore(DestDef.DEST_JOBS_ADMIN);
IConfigStore instancesConfig =
- destStore.getSubStore(scope);
+ destStore.getSubStore(scope);
instancesConfig.removeSubStore(id);
// commiting
@@ -609,8 +605,8 @@ public class JobsAdminServlet extends AdminServlet {
mConfig.commit(true);
} catch (EBaseException e) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
+ null, resp);
return;
}
@@ -618,52 +614,52 @@ public class JobsAdminServlet extends AdminServlet {
return;
}
- private synchronized void delJobsInst(HttpServletRequest req,
- HttpServletResponse resp, String scope) throws ServletException,
+ private synchronized void delJobsInst(HttpServletRequest req,
+ HttpServletResponse resp, String scope) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
String id = req.getParameter(Constants.RS_ID);
if (id == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
// does job plugin instance exist?
if (mJobsSched.getInstances().containsKey(id) == false) {
sendResponse(ERROR,
- new EJobsException(CMS.getUserMessage(getLocale(req),"CMS_JOB_SRVLT_JOB_NOT_FOUND",
- id)).toString(),
- null, resp);
+ new EJobsException(CMS.getUserMessage(getLocale(req), "CMS_JOB_SRVLT_JOB_NOT_FOUND",
+ id)).toString(),
+ null, resp);
return;
}
// only remove from memory
// cannot shutdown because we don't keep track of whether it's
- // being used.
+ // being used.
IJob jobInst = (IJob) mJobsSched.getInstances().get(id);
mJobsSched.getInstances().remove((Object) id);
// remove the configuration.
IConfigStore destStore =
- mConfig.getSubStore(DestDef.DEST_JOBS_ADMIN);
+ mConfig.getSubStore(DestDef.DEST_JOBS_ADMIN);
IConfigStore instancesConfig =
- destStore.getSubStore(scope);
+ destStore.getSubStore(scope);
instancesConfig.removeSubStore(id);
// commiting
try {
mConfig.commit(true);
} catch (EBaseException e) {
- //System.out.println("SRVLT_FAIL_COMMIT");
+ // System.out.println("SRVLT_FAIL_COMMIT");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
+ null, resp);
return;
}
@@ -672,25 +668,24 @@ public class JobsAdminServlet extends AdminServlet {
}
/**
- * used for getting the required configuration parameters (with
- * possible default values) for a particular job plugin
- * implementation name specified in the RS_ID. Actually, there is
- * no logic in here to set any default value here...there's no
- * default value for any parameter in this job scheduler subsystem
- * at this point. Later, if we do have one (or some), it can be
- * added. The interface remains the same.
+ * used for getting the required configuration parameters (with possible
+ * default values) for a particular job plugin implementation name specified
+ * in the RS_ID. Actually, there is no logic in here to set any default
+ * value here...there's no default value for any parameter in this job
+ * scheduler subsystem at this point. Later, if we do have one (or some), it
+ * can be added. The interface remains the same.
*/
- private synchronized void getConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException, EBaseException {
+ private synchronized void getConfig(HttpServletRequest req,
+ HttpServletResponse resp)
+ throws ServletException, IOException, EBaseException {
String implname = req.getParameter(Constants.RS_ID);
if (implname == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
@@ -708,25 +703,25 @@ public class JobsAdminServlet extends AdminServlet {
return;
}
- private synchronized void getInstConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ private synchronized void getInstConfig(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String id = req.getParameter(Constants.RS_ID);
if (id == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
// does job plugin instance exist?
if (mJobsSched.getInstances().containsKey(id) == false) {
sendResponse(ERROR,
- new EJobsException(CMS.getUserMessage(getLocale(req),"CMS_JOB_SRVLT_JOB_NOT_FOUND",
- id)).toString(),
- null, resp);
+ new EJobsException(CMS.getUserMessage(getLocale(req), "CMS_JOB_SRVLT_JOB_NOT_FOUND",
+ id)).toString(),
+ null, resp);
return;
}
@@ -757,34 +752,32 @@ public class JobsAdminServlet extends AdminServlet {
}
/**
- * Modify job plugin instance.
- * This will actually create a new instance with new configuration
- * parameters and replace the old instance, if the new instance
- * created and initialized successfully.
- * The old instance is left running. so this is very expensive.
- * Restart of server recommended.
+ * Modify job plugin instance. This will actually create a new instance with
+ * new configuration parameters and replace the old instance, if the new
+ * instance created and initialized successfully. The old instance is left
+ * running. so this is very expensive. Restart of server recommended.
*/
- private synchronized void modJobsInst(HttpServletRequest req,
- HttpServletResponse resp, String scope)
- throws ServletException, IOException, EBaseException {
+ private synchronized void modJobsInst(HttpServletRequest req,
+ HttpServletResponse resp, String scope)
+ throws ServletException, IOException, EBaseException {
// expensive operation.
String id = req.getParameter(Constants.RS_ID);
if (id == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
// Does the job instance exist?
if (!mJobsSched.getInstances().containsKey((Object) id)) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_JOB_SRVLT_ILL_JOB_INST_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_JOB_SRVLT_ILL_JOB_INST_ID"),
+ null, resp);
return;
}
@@ -793,27 +786,27 @@ public class JobsAdminServlet extends AdminServlet {
if (implname == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_JOB_SRVLT_ADD_MISSING_PARAMS"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_JOB_SRVLT_ADD_MISSING_PARAMS"),
+ null, resp);
return;
}
- // get plugin for implementation
+ // get plugin for implementation
JobPlugin plugin =
- (JobPlugin) mJobsSched.getPlugins().get(implname);
+ (JobPlugin) mJobsSched.getPlugins().get(implname);
if (plugin == null) {
sendResponse(ERROR,
- new EJobsException(CMS.getUserMessage(getLocale(req),"CMS_JOB_SRVLT_JOB_PLUGIN_NOT_FOUND",
- id)).toString(),
- null, resp);
+ new EJobsException(CMS.getUserMessage(getLocale(req), "CMS_JOB_SRVLT_JOB_PLUGIN_NOT_FOUND",
+ id)).toString(),
+ null, resp);
return;
}
- // save old instance substore params in case new one fails.
+ // save old instance substore params in case new one fails.
- IJob oldinst =
- (IJob) mJobsSched.getInstances().get((Object) id);
+ IJob oldinst =
+ (IJob) mJobsSched.getInstances().get((Object) id);
IConfigStore oldConfig = oldinst.getConfigStore();
String[] oldConfigParms = oldinst.getConfigParams();
@@ -821,7 +814,7 @@ public class JobsAdminServlet extends AdminServlet {
// implName is always required so always include it it.
saveParams.add(IJobsScheduler.PROP_PLUGIN,
- (String) oldConfig.get(IJobsScheduler.PROP_PLUGIN));
+ (String) oldConfig.get(IJobsScheduler.PROP_PLUGIN));
if (oldConfigParms != null) {
for (int i = 0; i < oldConfigParms.length; i++) {
String key = oldConfigParms[i];
@@ -838,9 +831,9 @@ public class JobsAdminServlet extends AdminServlet {
// remove old substore.
IConfigStore destStore =
- mConfig.getSubStore(DestDef.DEST_JOBS_ADMIN);
+ mConfig.getSubStore(DestDef.DEST_JOBS_ADMIN);
IConfigStore instancesConfig =
- destStore.getSubStore(scope);
+ destStore.getSubStore(scope);
instancesConfig.removeSubStore(id);
@@ -861,10 +854,10 @@ public class JobsAdminServlet extends AdminServlet {
} else if (!key.equals("profileId")) {
restore(instancesConfig, id, saveParams);
sendResponse(ERROR,
- new
- EJobsException(CMS.getUserMessage(getLocale(req),"CMS_JOB_SRVLT_MISSING_INST_PARAM_VAL",
- key)).toString(),
- null, resp);
+ new
+ EJobsException(CMS.getUserMessage(getLocale(req), "CMS_JOB_SRVLT_MISSING_INST_PARAM_VAL",
+ key)).toString(),
+ null, resp);
return;
}
}
@@ -880,30 +873,30 @@ public class JobsAdminServlet extends AdminServlet {
// cleanup
restore(instancesConfig, id, saveParams);
sendResponse(ERROR,
- new EJobsException(
- CMS.getUserMessage(getLocale(req),"CMS_JOB_LOAD_CLASS_FAILED", className)).toString(),
- null, resp);
+ new EJobsException(
+ CMS.getUserMessage(getLocale(req), "CMS_JOB_LOAD_CLASS_FAILED", className)).toString(),
+ null, resp);
return;
} catch (InstantiationException e) {
restore(instancesConfig, id, saveParams);
sendResponse(ERROR,
- new EJobsException(
- CMS.getUserMessage(getLocale(req),"CMS_JOB_LOAD_CLASS_FAILED", className)).toString(),
- null, resp);
+ new EJobsException(
+ CMS.getUserMessage(getLocale(req), "CMS_JOB_LOAD_CLASS_FAILED", className)).toString(),
+ null, resp);
return;
} catch (IllegalAccessException e) {
restore(instancesConfig, id, saveParams);
sendResponse(ERROR,
- new EJobsException(
- CMS.getUserMessage(getLocale(req),"CMS_JOB_LOAD_CLASS_FAILED", className)).toString(),
- null, resp);
+ new EJobsException(
+ CMS.getUserMessage(getLocale(req), "CMS_JOB_LOAD_CLASS_FAILED", className)).toString(),
+ null, resp);
return;
}
// initialize the job plugin
IJobsScheduler scheduler = (IJobsScheduler)
- CMS.getSubsystem(CMS.SUBSYSTEM_JOBS);
+ CMS.getSubsystem(CMS.SUBSYSTEM_JOBS);
try {
newJobInst.init(scheduler, id, implname, substore);
@@ -919,17 +912,17 @@ public class JobsAdminServlet extends AdminServlet {
return;
}
- // initialized ok. commiting
+ // initialized ok. commiting
try {
mConfig.commit(true);
} catch (EBaseException e) {
// clean up.
restore(instancesConfig, id, saveParams);
- //System.out.println("SRVLT_FAIL_COMMIT");
+ // System.out.println("SRVLT_FAIL_COMMIT");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
+ null, resp);
return;
}
@@ -937,8 +930,8 @@ public class JobsAdminServlet extends AdminServlet {
mJobsSched.getInstances().put(id, newJobInst);
- mJobsSched.log(ILogger.LL_INFO,
- CMS.getLogMessage("ADMIN_SRVLT_JOB_INST_REP", id));
+ mJobsSched.log(ILogger.LL_INFO,
+ CMS.getLogMessage("ADMIN_SRVLT_JOB_INST_REP", id));
NameValuePairs params = new NameValuePairs();
@@ -947,25 +940,25 @@ public class JobsAdminServlet extends AdminServlet {
}
private void getSettings(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
IConfigStore config = mConfig.getSubStore(DestDef.DEST_JOBS_ADMIN);
- params.add(Constants.PR_ENABLE,
- config.getString(IJobsScheduler.PROP_ENABLED,
- Constants.FALSE));
+ params.add(Constants.PR_ENABLE,
+ config.getString(IJobsScheduler.PROP_ENABLED,
+ Constants.FALSE));
// default 1 minute
- params.add(Constants.PR_JOBS_FREQUENCY,
- config.getString(IJobsScheduler.PROP_INTERVAL, "1"));
+ params.add(Constants.PR_JOBS_FREQUENCY,
+ config.getString(IJobsScheduler.PROP_INTERVAL, "1"));
- //System.out.println("Send: "+params.toString());
+ // System.out.println("Send: "+params.toString());
sendResponse(SUCCESS, null, params, resp);
}
private void setSettings(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException, EBaseException {
- //Save New Settings to the config file
+ throws ServletException, IOException, EBaseException {
+ // Save New Settings to the config file
IConfigStore config = mConfig.getSubStore(DestDef.DEST_JOBS_ADMIN);
String enabled = config.getString(IJobsScheduler.PROP_ENABLED);
@@ -978,14 +971,14 @@ public class JobsAdminServlet extends AdminServlet {
config.putString(IJobsScheduler.PROP_ENABLED, enabledSetTo);
}
- //set frequency
+ // set frequency
String interval =
- req.getParameter(Constants.PR_JOBS_FREQUENCY);
+ req.getParameter(Constants.PR_JOBS_FREQUENCY);
if (interval != null) {
config.putString(IJobsScheduler.PROP_INTERVAL, interval);
mJobsSched.setInterval(
- config.getInteger(IJobsScheduler.PROP_INTERVAL));
+ config.getInteger(IJobsScheduler.PROP_INTERVAL));
}
if (enabledChanged == true) {
@@ -999,8 +992,8 @@ public class JobsAdminServlet extends AdminServlet {
}
// convenience routine.
- private static void restore(IConfigStore store,
- String id, NameValuePairs saveParams) {
+ private static void restore(IConfigStore store,
+ String id, NameValuePairs saveParams) {
store.removeSubStore(id);
IConfigStore rstore = store.makeSubStore(id);
@@ -1010,7 +1003,7 @@ public class JobsAdminServlet extends AdminServlet {
String key = (String) keys.nextElement();
String value = saveParams.getValue(key);
- if (!value.equals(""))
+ if (!value.equals(""))
rstore.put(key, value);
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/admin/KRAAdminServlet.java b/pki/base/common/src/com/netscape/cms/servlet/admin/KRAAdminServlet.java
index e4138d74..feb4ea9b 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/admin/KRAAdminServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/admin/KRAAdminServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.admin;
-
import java.io.IOException;
import java.util.Enumeration;
@@ -35,13 +34,11 @@ import com.netscape.certsrv.common.ScopeDef;
import com.netscape.certsrv.kra.IKeyRecoveryAuthority;
import com.netscape.certsrv.logging.ILogger;
-
/**
- * A class representings an administration servlet for Key
- * Recovery Authority. This servlet is responsible to serve
- * KRA administrative operation such as configuration
- * parameter updates.
- *
+ * A class representings an administration servlet for Key Recovery Authority.
+ * This servlet is responsible to serve KRA administrative operation such as
+ * configuration parameter updates.
+ *
* @version $Revision$, $Date$
*/
public class KRAAdminServlet extends AdminServlet {
@@ -57,7 +54,7 @@ public class KRAAdminServlet extends AdminServlet {
private IKeyRecoveryAuthority mKRA = null;
private final static String LOGGING_SIGNED_AUDIT_CONFIG_DRM =
- "LOGGING_SIGNED_AUDIT_CONFIG_DRM_3";
+ "LOGGING_SIGNED_AUDIT_CONFIG_DRM_3";
/**
* Constructs KRA servlet.
@@ -73,63 +70,60 @@ public class KRAAdminServlet extends AdminServlet {
/**
* Returns serlvet information.
- *
+ *
* @return name of this servlet
*/
- public String getServletInfo() {
- return INFO;
+ public String getServletInfo() {
+ return INFO;
}
/**
* Serves HTTP admin request.
- *
+ *
* @param req HTTP request
* @param resp HTTP response
*/
public void service(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
+ throws ServletException, IOException {
super.service(req, resp);
super.authenticate(req);
String scope = req.getParameter(Constants.OP_SCOPE);
if (scope == null) {
- sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
- null, resp);
+ sendResponse(ERROR,
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
+ null, resp);
return;
}
String op = req.getParameter(Constants.OP_TYPE);
if (op == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_TYPE", op),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_TYPE", op),
+ null, resp);
return;
}
-
+
try {
AUTHZ_RES_NAME = "certServer.kra.configuration";
if (op.equals(OpDef.OP_READ)) {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
- /* Functions not implemented in console
- if (scope.equals(ScopeDef.SC_AUTO_RECOVERY)) {
- readAutoRecoveryConfig(req, resp);
- return;
- } else if (scope.equals(ScopeDef.SC_RECOVERY)) {
- readRecoveryConfig(req, resp);
- return;
- } else if (scope.equals(ScopeDef.SC_NOTIFICATION_RIQ)) {
- getNotificationRIQConfig(req, resp);
- return;
- } else
- */
+ /*
+ * Functions not implemented in console if
+ * (scope.equals(ScopeDef.SC_AUTO_RECOVERY)) {
+ * readAutoRecoveryConfig(req, resp); return; } else if
+ * (scope.equals(ScopeDef.SC_RECOVERY)) {
+ * readRecoveryConfig(req, resp); return; } else if
+ * (scope.equals(ScopeDef.SC_NOTIFICATION_RIQ)) {
+ * getNotificationRIQConfig(req, resp); return; } else
+ */
if (scope.equals(ScopeDef.SC_GENERAL)) {
getGeneralConfig(req, resp);
return;
@@ -138,44 +132,39 @@ public class KRAAdminServlet extends AdminServlet {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
- /* Functions not implemented in console
- if (scope.equals(ScopeDef.SC_AUTO_RECOVERY)) {
- modifyAutoRecoveryConfig(req, resp);
- return;
- } else if (scope.equals(ScopeDef.SC_AGENT_PWD)) {
- changeAgentPwd(req, resp);
- return;
- } else if (scope.equals(ScopeDef.SC_MNSCHEME)) {
- changeMNScheme(req, resp);
- return;
- } else if (scope.equals(ScopeDef.SC_NOTIFICATION_RIQ)) {
- setNotificationRIQConfig(req, resp);
- return;
- } else
- */
+ /*
+ * Functions not implemented in console if
+ * (scope.equals(ScopeDef.SC_AUTO_RECOVERY)) {
+ * modifyAutoRecoveryConfig(req, resp); return; } else if
+ * (scope.equals(ScopeDef.SC_AGENT_PWD)) { changeAgentPwd(req,
+ * resp); return; } else if (scope.equals(ScopeDef.SC_MNSCHEME))
+ * { changeMNScheme(req, resp); return; } else if
+ * (scope.equals(ScopeDef.SC_NOTIFICATION_RIQ)) {
+ * setNotificationRIQConfig(req, resp); return; } else
+ */
if (scope.equals(ScopeDef.SC_GENERAL)) {
- setGeneralConfig(req,resp);
+ setGeneralConfig(req, resp);
}
- }
+ }
} catch (EBaseException e) {
// convert exception into locale-specific message
- sendResponse(ERROR, e.toString(getLocale(req)),
- null, resp);
+ sendResponse(ERROR, e.toString(getLocale(req)),
+ null, resp);
return;
} catch (Exception e) {
e.printStackTrace();
}
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_PROTOCOL"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_PROTOCOL"),
+ null, resp);
}
private void getGeneralConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
@@ -188,7 +177,7 @@ public class KRAAdminServlet extends AdminServlet {
}
private void setGeneralConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
Enumeration enum1 = req.getParameterNames();
boolean restart = false;
@@ -202,14 +191,14 @@ public class KRAAdminServlet extends AdminServlet {
if (key.equals(Constants.PR_NO_OF_REQUIRED_RECOVERY_AGENTS)) {
try {
- int number = Integer.parseInt(value);
+ int number = Integer.parseInt(value);
mKRA.setNoOfRequiredAgents(number);
} catch (NumberFormatException e) {
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CONFIG_DRM,
- auditSubjectID,
- ILogger.FAILURE,
- auditParams(req));
+ LOGGING_SIGNED_AUDIT_CONFIG_DRM,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditParams(req));
audit(auditMessage);
throw new EBaseException("Number of agents must be an integer");
@@ -220,10 +209,10 @@ public class KRAAdminServlet extends AdminServlet {
commit(true);
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CONFIG_DRM,
- auditSubjectID,
- ILogger.SUCCESS,
- auditParams(req));
+ LOGGING_SIGNED_AUDIT_CONFIG_DRM,
+ auditSubjectID,
+ ILogger.SUCCESS,
+ auditParams(req));
audit(auditMessage);
diff --git a/pki/base/common/src/com/netscape/cms/servlet/admin/LogAdminServlet.java b/pki/base/common/src/com/netscape/cms/servlet/admin/LogAdminServlet.java
index 08d6fcf5..4dc862a5 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/admin/LogAdminServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/admin/LogAdminServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.admin;
-
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
@@ -45,13 +44,11 @@ import com.netscape.certsrv.logging.ILogSubsystem;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.logging.LogPlugin;
-
/**
- * A class representings an administration servlet for logging
- * subsystem. This servlet is responsible to serve
- * logging administrative operation such as configuration
- * parameter updates and log retriever.
- *
+ * A class representings an administration servlet for logging subsystem. This
+ * servlet is responsible to serve logging administrative operation such as
+ * configuration parameter updates and log retriever.
+ *
* @version $Revision$, $Date$
*/
public class LogAdminServlet extends AdminServlet {
@@ -70,11 +67,11 @@ public class LogAdminServlet extends AdminServlet {
private final static String SIGNED_AUDIT_LOG_TYPE = "SignedAudit";
private final static String LOGGING_SIGNED_AUDIT_CONFIG_SIGNED_AUDIT =
- "LOGGING_SIGNED_AUDIT_CONFIG_SIGNED_AUDIT_3";
+ "LOGGING_SIGNED_AUDIT_CONFIG_SIGNED_AUDIT_3";
private final static String LOGGING_SIGNED_AUDIT_LOG_PATH_CHANGE =
- "LOGGING_SIGNED_AUDIT_LOG_PATH_CHANGE_4";
+ "LOGGING_SIGNED_AUDIT_LOG_PATH_CHANGE_4";
private final static String LOGGING_SIGNED_AUDIT_LOG_EXPIRATION_CHANGE =
- "LOGGING_SIGNED_AUDIT_LOG_EXPIRATION_CHANGE_4";
+ "LOGGING_SIGNED_AUDIT_LOG_EXPIRATION_CHANGE_4";
/**
* Constructs Log servlet.
@@ -114,15 +111,15 @@ public class LogAdminServlet extends AdminServlet {
* Serves HTTP admin request.
*/
public void service(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
+ throws ServletException, IOException {
super.service(req, resp);
String op = req.getParameter(Constants.OP_TYPE);
if (op == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_PROTOCOL"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_PROTOCOL"),
+ null, resp);
return;
}
@@ -138,8 +135,8 @@ public class LogAdminServlet extends AdminServlet {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
try {
@@ -155,8 +152,8 @@ public class LogAdminServlet extends AdminServlet {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
@@ -169,17 +166,17 @@ public class LogAdminServlet extends AdminServlet {
} else if (scope.equals(ScopeDef.SC_GENERAL)) {
getGeneralConfig(req, resp);
} else {
- sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
- null, resp);
+ sendResponse(ERROR,
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
+ null, resp);
return;
}
} else if (op.equals(OpDef.OP_DELETE)) {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
@@ -190,17 +187,17 @@ public class LogAdminServlet extends AdminServlet {
delLogInst(req, resp, scope);
return;
} else {
- sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
- null, resp);
+ sendResponse(ERROR,
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
+ null, resp);
return;
}
} else if (op.equals(OpDef.OP_ADD)) {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
@@ -211,9 +208,9 @@ public class LogAdminServlet extends AdminServlet {
addLogInst(req, resp, scope);
return;
} else {
- sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
- null, resp);
+ sendResponse(ERROR,
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
+ null, resp);
return;
}
} else if (op.equals(OpDef.OP_MODIFY)) {
@@ -221,8 +218,8 @@ public class LogAdminServlet extends AdminServlet {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
@@ -232,17 +229,17 @@ public class LogAdminServlet extends AdminServlet {
} else if (scope.equals(ScopeDef.SC_GENERAL)) {
setGeneralConfig(req, resp);
} else {
- sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
- null, resp);
+ sendResponse(ERROR,
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
+ null, resp);
return;
}
} else if (op.equals(OpDef.OP_SEARCH)) {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_LOG_IMPLS)) {
@@ -268,13 +265,13 @@ public class LogAdminServlet extends AdminServlet {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
ILogEventListener loginst =
- mSys.getLogInstance(instName);
+ mSys.getLogInstance(instName);
if (loginst != null) {
NameValuePairs nvps = loginst.retrieveLogContent(toHashtable(req));
@@ -296,12 +293,12 @@ public class LogAdminServlet extends AdminServlet {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
ILogEventListener loginst =
- mSys.getLogInstance(instName);
+ mSys.getLogInstance(instName);
if (loginst != null) {
NameValuePairs nvps = loginst.retrieveLogList(toHashtable(req));
@@ -310,15 +307,15 @@ public class LogAdminServlet extends AdminServlet {
}
return;
} else {
- sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
- null, resp);
+ sendResponse(ERROR,
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
+ null, resp);
return;
}
} else {
- sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_TYPE", op),
- null, resp);
+ sendResponse(ERROR,
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_TYPE", op),
+ null, resp);
return;
}
}
@@ -329,15 +326,15 @@ public class LogAdminServlet extends AdminServlet {
System.out.println("XXX >>>" + e.toString() + "<<<");
e.printStackTrace();
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_PROTOCOL"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_PROTOCOL"),
+ null, resp);
}
return;
}
- private synchronized void listLogInsts(HttpServletRequest req,
- HttpServletResponse resp, boolean all) throws ServletException,
+ private synchronized void listLogInsts(HttpServletRequest req,
+ HttpServletResponse resp, boolean all) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
@@ -351,9 +348,9 @@ public class LogAdminServlet extends AdminServlet {
if (value == null)
continue;
String pName = mSys.getLogPluginName(value);
- LogPlugin pClass = (LogPlugin)
- mSys.getLogPlugins().get(pName);
- String c = pClass.getClassPath();
+ LogPlugin pClass = (LogPlugin)
+ mSys.getLogPlugins().get(pName);
+ String c = pClass.getClassPath();
// not show ntEventlog here
if (all || (!all && !c.endsWith("NTEventLog")))
@@ -363,12 +360,12 @@ public class LogAdminServlet extends AdminServlet {
return;
}
- /**
- * retrieve extended plugin info such as brief description, type info
- * from logging
+ /**
+ * retrieve extended plugin info such as brief description, type info from
+ * logging
*/
private void getExtendedPluginInfo(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String id = req.getParameter(Constants.RS_ID);
@@ -381,10 +378,10 @@ public class LogAdminServlet extends AdminServlet {
sendResponse(SUCCESS, null, params, resp);
}
- private NameValuePairs getExtendedPluginInfo(Locale locale, String implType, String implName) {
- IExtendedPluginInfo ext_info = null;
+ private NameValuePairs getExtendedPluginInfo(Locale locale, String implType, String implName) {
+ IExtendedPluginInfo ext_info = null;
Object impl = null;
- LogPlugin lp = (LogPlugin) mSys.getLogPlugins().get(implName);
+ LogPlugin lp = (LogPlugin) mSys.getLogPlugins().get(implName);
if (lp != null) {
impl = getClassByNameAsExtendedPluginInfo(lp.getClassPath());
@@ -410,11 +407,12 @@ public class LogAdminServlet extends AdminServlet {
/**
* Add log plug-in
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_SIGNED_AUDIT used when
* configuring signedAudit
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @param scope string used to obtain the contents of the log's substore
@@ -423,9 +421,9 @@ public class LogAdminServlet extends AdminServlet {
* @exception EBaseException an error has occurred
*/
@SuppressWarnings("unchecked")
- private synchronized void addLogPlugin(HttpServletRequest req,
- HttpServletResponse resp, String scope)
- throws ServletException, IOException, EBaseException {
+ private synchronized void addLogPlugin(HttpServletRequest req,
+ HttpServletResponse resp, String scope)
+ throws ServletException, IOException, EBaseException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -443,7 +441,7 @@ public class LogAdminServlet extends AdminServlet {
}
if (id == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
// store a message in the signed audit log file
if (logType.equals(SIGNED_AUDIT_LOG_TYPE)) {
@@ -457,8 +455,8 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
@@ -476,8 +474,8 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- new ELogException(CMS.getUserMessage(getLocale(req),"CMS_LOG_SRVLT_ILL_PLUGIN_ID", id)).toString(),
- null, resp);
+ new ELogException(CMS.getUserMessage(getLocale(req), "CMS_LOG_SRVLT_ILL_PLUGIN_ID", id)).toString(),
+ null, resp);
return;
}
@@ -496,8 +494,8 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_LOG_SRVLT_NULL_CLASS"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_LOG_SRVLT_NULL_CLASS"),
+ null, resp);
return;
}
@@ -505,7 +503,7 @@ public class LogAdminServlet extends AdminServlet {
destStore = mConfig.getSubStore("log");
IConfigStore instancesConfig =
- destStore.getSubStore("impl");
+ destStore.getSubStore("impl");
// Does the class exist?
Class<ILogEventListener> newImpl = null;
@@ -525,8 +523,8 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_LOG_SRVLT_NO_CLASS"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_LOG_SRVLT_NO_CLASS"),
+ null, resp);
return;
} catch (IllegalArgumentException e) {
// store a message in the signed audit log file
@@ -541,8 +539,8 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_LOG_SRVLT_NO_CLASS"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_LOG_SRVLT_NO_CLASS"),
+ null, resp);
return;
}
@@ -561,11 +559,12 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_LOG_SRVLT_ILL_CLASS"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_LOG_SRVLT_ILL_CLASS"),
+ null, resp);
return;
}
- } catch (NullPointerException e) { // unlikely, only if newImpl null.
+ } catch (NullPointerException e) { // unlikely, only if newImpl
+ // null.
// store a message in the signed audit log file
if (logType.equals(SIGNED_AUDIT_LOG_TYPE)) {
auditMessage = CMS.getLogMessage(
@@ -578,8 +577,8 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_LOG_SRVLT_ILL_CLASS"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_LOG_SRVLT_ILL_CLASS"),
+ null, resp);
return;
}
@@ -591,7 +590,7 @@ public class LogAdminServlet extends AdminServlet {
try {
mConfig.commit(true);
} catch (EBaseException e) {
- //System.out.println("SRVLT_FAIL_COMMIT");
+ // System.out.println("SRVLT_FAIL_COMMIT");
// store a message in the signed audit log file
if (logType.equals(SIGNED_AUDIT_LOG_TYPE)) {
@@ -605,8 +604,8 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
+ null, resp);
return;
}
@@ -631,17 +630,17 @@ public class LogAdminServlet extends AdminServlet {
sendResponse(SUCCESS, null, params, resp);
return;
// } catch( EBaseException eAudit1 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_SIGNED_AUDIT,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_SIGNED_AUDIT,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit1;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit1;
} catch (IOException eAudit2) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -655,17 +654,17 @@ public class LogAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit2;
// } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_SIGNED_AUDIT,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_SIGNED_AUDIT,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
}
}
@@ -682,11 +681,12 @@ public class LogAdminServlet extends AdminServlet {
/**
* Add log instance
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_SIGNED_AUDIT used when
* configuring signedAudit
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @param scope string used to obtain the contents of the log's substore
@@ -694,9 +694,9 @@ public class LogAdminServlet extends AdminServlet {
* @exception IOException an input/output error has occurred
* @exception EBaseException an error has occurred
*/
- private synchronized void addLogInst(HttpServletRequest req,
- HttpServletResponse resp, String scope)
- throws ServletException, IOException, EBaseException {
+ private synchronized void addLogInst(HttpServletRequest req,
+ HttpServletResponse resp, String scope)
+ throws ServletException, IOException, EBaseException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -726,8 +726,8 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
@@ -743,8 +743,8 @@ public class LogAdminServlet extends AdminServlet {
audit(auditMessage);
}
- sendResponse(ERROR, "Invalid ID '" + id + "'",
- null, resp);
+ sendResponse(ERROR, "Invalid ID '" + id + "'",
+ null, resp);
return;
}
@@ -761,8 +761,8 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_LOG_SRVLT_ILL_INST_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_LOG_SRVLT_ILL_INST_ID"),
+ null, resp);
return;
}
@@ -783,15 +783,15 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_LOG_SRVLT_ADD_MISSING_PARAMS"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_LOG_SRVLT_ADD_MISSING_PARAMS"),
+ null, resp);
return;
}
// check if implementation exists.
LogPlugin plugin =
- (LogPlugin) mSys.getLogPlugins().get(
- implname);
+ (LogPlugin) mSys.getLogPlugins().get(
+ implname);
if (plugin == null) {
// store a message in the signed audit log file
@@ -806,17 +806,17 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- new ELogPluginNotFound(CMS.getUserMessage(getLocale(req), "CMS_LOG_PLUGIN_NOT_FOUND",implname)).toString(),
- null, resp);
+ new ELogPluginNotFound(CMS.getUserMessage(getLocale(req), "CMS_LOG_PLUGIN_NOT_FOUND", implname)).toString(),
+ null, resp);
return;
}
Vector<String> configParams = mSys.getLogDefaultParams(implname);
IConfigStore destStore =
- mConfig.getSubStore("log");
+ mConfig.getSubStore("log");
IConfigStore instancesConfig =
- destStore.getSubStore("instance");
+ destStore.getSubStore("instance");
IConfigStore substore = instancesConfig.makeSubStore(id);
if (configParams != null) {
@@ -826,17 +826,17 @@ public class LogAdminServlet extends AdminServlet {
String val = req.getParameter(kv.substring(0, index));
if (val == null) {
- substore.put(kv.substring(0, index),
- kv.substring(index + 1));
+ substore.put(kv.substring(0, index),
+ kv.substring(index + 1));
} else {
- substore.put(kv.substring(0, index),
- val);
+ substore.put(kv.substring(0, index),
+ val);
}
}
}
substore.put("pluginName", implname);
- // Fix Blackflag Bug #615603: Currently, although expiring log
+ // Fix Blackflag Bug #615603: Currently, although expiring log
// files is no longer supported, it is still a required parameter
// that must be present during the creation and modification of
// custom log plugins.
@@ -864,8 +864,8 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- new ELogException(CMS.getUserMessage(getLocale(req),"CMS_LOG_LOAD_CLASS_FAIL", className)).toString(),
- null, resp);
+ new ELogException(CMS.getUserMessage(getLocale(req), "CMS_LOG_LOAD_CLASS_FAIL", className)).toString(),
+ null, resp);
return;
} catch (InstantiationException e) {
instancesConfig.removeSubStore(id);
@@ -882,8 +882,8 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- new ELogException(CMS.getUserMessage(getLocale(req),"CMS_LOG_LOAD_CLASS_FAIL", className)).toString(),
- null, resp);
+ new ELogException(CMS.getUserMessage(getLocale(req), "CMS_LOG_LOAD_CLASS_FAIL", className)).toString(),
+ null, resp);
return;
} catch (IllegalAccessException e) {
instancesConfig.removeSubStore(id);
@@ -900,8 +900,8 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- new ELogException(CMS.getUserMessage(getLocale(req),"CMS_LOG_LOAD_CLASS_FAIL", className)).toString(),
- null, resp);
+ new ELogException(CMS.getUserMessage(getLocale(req), "CMS_LOG_LOAD_CLASS_FAIL", className)).toString(),
+ null, resp);
return;
}
@@ -962,8 +962,8 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
+ null, resp);
return;
}
@@ -988,17 +988,17 @@ public class LogAdminServlet extends AdminServlet {
sendResponse(SUCCESS, null, params, resp);
return;
// } catch( EBaseException eAudit1 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_SIGNED_AUDIT,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_SIGNED_AUDIT,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit1;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit1;
} catch (IOException eAudit2) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -1012,42 +1012,42 @@ public class LogAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit2;
// } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_SIGNED_AUDIT,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_SIGNED_AUDIT,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
}
}
- private synchronized void listLogPlugins(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ private synchronized void listLogPlugins(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
Enumeration<String> e = mSys.getLogPlugins().keys();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
- LogPlugin value = (LogPlugin)
- mSys.getLogPlugins().get(name);
+ LogPlugin value = (LogPlugin)
+ mSys.getLogPlugins().get(name);
// get Description
- String c = value.getClassPath();
+ String c = value.getClassPath();
String desc = "unknown";
try {
ILogEventListener lp = (ILogEventListener)
- Class.forName(c).newInstance();
+ Class.forName(c).newInstance();
desc = lp.getDescription();
} catch (Exception exp) {
- sendResponse(ERROR, exp.toString(), null,
- resp);
+ sendResponse(ERROR, exp.toString(), null,
+ resp);
return;
}
params.add(name, value.getClassPath() + "," + desc);
@@ -1069,11 +1069,12 @@ public class LogAdminServlet extends AdminServlet {
/**
* Delete log instance
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_SIGNED_AUDIT used when
* configuring signedAudit
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @param scope string used to obtain the contents of the log's substore
@@ -1081,9 +1082,9 @@ public class LogAdminServlet extends AdminServlet {
* @exception IOException an input/output error has occurred
* @exception EBaseException an error has occurred
*/
- private synchronized void delLogInst(HttpServletRequest req,
- HttpServletResponse resp, String scope)
- throws ServletException, IOException, EBaseException {
+ private synchronized void delLogInst(HttpServletRequest req,
+ HttpServletResponse resp, String scope)
+ throws ServletException, IOException, EBaseException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -1102,7 +1103,7 @@ public class LogAdminServlet extends AdminServlet {
}
if (id == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
// store a message in the signed audit log file
if (logType.equals(SIGNED_AUDIT_LOG_TYPE)) {
@@ -1116,8 +1117,8 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
@@ -1135,31 +1136,31 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- new ELogNotFound(CMS.getUserMessage(getLocale(req), "CMS_LOG_INSTANCE_NOT_FOUND",id)).toString(),
- null, resp);
+ new ELogNotFound(CMS.getUserMessage(getLocale(req), "CMS_LOG_INSTANCE_NOT_FOUND", id)).toString(),
+ null, resp);
return;
}
// only remove from memory
// cannot shutdown because we don't keep track of whether it's
- // being used.
+ // being used.
ILogEventListener logInst = (ILogEventListener)
- mSys.getLogInstance(id);
+ mSys.getLogInstance(id);
mSys.getLogInsts().remove((Object) id);
// remove the configuration.
IConfigStore destStore =
- mConfig.getSubStore("log");
+ mConfig.getSubStore("log");
IConfigStore instancesConfig =
- destStore.getSubStore("instance");
+ destStore.getSubStore("instance");
instancesConfig.removeSubStore(id);
// commiting
try {
mConfig.commit(true);
} catch (EBaseException e) {
- //System.out.println("SRVLT_FAIL_COMMIT");
+ // System.out.println("SRVLT_FAIL_COMMIT");
// store a message in the signed audit log file
if (logType.equals(SIGNED_AUDIT_LOG_TYPE)) {
@@ -1173,8 +1174,8 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
+ null, resp);
return;
}
@@ -1192,17 +1193,17 @@ public class LogAdminServlet extends AdminServlet {
sendResponse(SUCCESS, null, params, resp);
return;
// } catch( EBaseException eAudit1 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_SIGNED_AUDIT,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_SIGNED_AUDIT,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit1;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit1;
} catch (IOException eAudit2) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -1216,28 +1217,29 @@ public class LogAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit2;
// } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_SIGNED_AUDIT,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_SIGNED_AUDIT,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
}
}
/**
* Delete log plug-in
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_SIGNED_AUDIT used when
* configuring signedAudit
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @param scope string used to obtain the contents of the log's substore
@@ -1245,9 +1247,9 @@ public class LogAdminServlet extends AdminServlet {
* @exception IOException an input/output error has occurred
* @exception EBaseException an error has occurred
*/
- private synchronized void delLogPlugin(HttpServletRequest req,
- HttpServletResponse resp, String scope)
- throws ServletException, IOException, EBaseException {
+ private synchronized void delLogPlugin(HttpServletRequest req,
+ HttpServletResponse resp, String scope)
+ throws ServletException, IOException, EBaseException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -1266,7 +1268,7 @@ public class LogAdminServlet extends AdminServlet {
}
if (id == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
// store a message in the signed audit log file
if (logType.equals(SIGNED_AUDIT_LOG_TYPE)) {
@@ -1280,8 +1282,8 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
@@ -1298,15 +1300,14 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- new ELogPluginNotFound(CMS.getUserMessage(getLocale(req),"CMS_LOG_PLUGIN_NOT_FOUND",id)).toString(),
- null, resp);
+ new ELogPluginNotFound(CMS.getUserMessage(getLocale(req), "CMS_LOG_PLUGIN_NOT_FOUND", id)).toString(),
+ null, resp);
return;
}
// first check if any instances from this log
// DON'T remove log if any instance
- for (Enumeration<String> e = mSys.getLogInsts().keys();
- e.hasMoreElements();) {
+ for (Enumeration<String> e = mSys.getLogInsts().keys(); e.hasMoreElements();) {
String name = (String) e.nextElement();
ILogEventListener log = mSys.getLogInstance(name);
@@ -1323,19 +1324,19 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_LOG_SRVLT_IN_USE"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_LOG_SRVLT_IN_USE"),
+ null, resp);
return;
}
}
-
+
// then delete this log
mSys.getLogPlugins().remove((Object) id);
IConfigStore destStore =
- mConfig.getSubStore("log");
+ mConfig.getSubStore("log");
IConfigStore instancesConfig =
- destStore.getSubStore("impl");
+ destStore.getSubStore("impl");
instancesConfig.removeSubStore(id);
// commiting
@@ -1354,8 +1355,8 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
+ null, resp);
return;
}
@@ -1373,17 +1374,17 @@ public class LogAdminServlet extends AdminServlet {
sendResponse(SUCCESS, null, params, resp);
return;
// } catch( EBaseException eAudit1 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_SIGNED_AUDIT,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_SIGNED_AUDIT,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit1;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit1;
} catch (IOException eAudit2) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -1397,35 +1398,36 @@ public class LogAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit2;
// } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_SIGNED_AUDIT,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_SIGNED_AUDIT,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
}
}
/**
* Modify log instance
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_SIGNED_AUDIT used when
* configuring signedAudit
* <li>signed.audit LOGGING_SIGNED_AUDIT_LOG_PATH_CHANGE used when log file
- * name (including any path changes) for any of audit, system, transaction,
+ * name (including any path changes) for any of audit, system, transaction,
* or other customized log file change is attempted (authorization should
* not allow, but make sure it's written after the attempt)
* <li>signed.audit LOGGING_SIGNED_AUDIT_LOG_EXPIRATION_CHANGE used when log
* expiration time change is attempted (authorization should not allow, but
* make sure it's written after the attempt)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @param scope string used to obtain the contents of the log's substore
@@ -1433,9 +1435,9 @@ public class LogAdminServlet extends AdminServlet {
* @exception IOException an input/output error has occurred
* @exception EBaseException an error has occurred
*/
- private synchronized void modLogInst(HttpServletRequest req,
- HttpServletResponse resp, String scope)
- throws ServletException, IOException, EBaseException {
+ private synchronized void modLogInst(HttpServletRequest req,
+ HttpServletResponse resp, String scope)
+ throws ServletException, IOException, EBaseException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -1476,7 +1478,7 @@ public class LogAdminServlet extends AdminServlet {
}
if (id == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
// store a message in the signed audit log file
if (logType.equals(SIGNED_AUDIT_LOG_TYPE)) {
@@ -1490,8 +1492,8 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
@@ -1509,8 +1511,8 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_LOG_SRVLT_ILL_INST_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_LOG_SRVLT_ILL_INST_ID"),
+ null, resp);
return;
}
@@ -1530,14 +1532,14 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),"CMS_LOG_SRVLT_ADD_MISSING_PARAMS"),
+ CMS.getUserMessage(getLocale(req), "CMS_LOG_SRVLT_ADD_MISSING_PARAMS"),
- null, resp);
+ null, resp);
return;
}
// get plugin for implementation
LogPlugin plugin =
- (LogPlugin) mSys.getLogPlugins().get(implname);
+ (LogPlugin) mSys.getLogPlugins().get(implname);
if (plugin == null) {
// store a message in the signed audit log file
@@ -1552,14 +1554,14 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- new ELogPluginNotFound(CMS.getUserMessage(getLocale(req),"CMS_LOG_PLUGIN_NOT_FOUND",implname)).toString(), null, resp);
+ new ELogPluginNotFound(CMS.getUserMessage(getLocale(req), "CMS_LOG_PLUGIN_NOT_FOUND", implname)).toString(), null, resp);
return;
}
// save old instance substore params in case new one fails.
ILogEventListener oldinst =
- (ILogEventListener) mSys.getLogInstance(id);
+ (ILogEventListener) mSys.getLogInstance(id);
Vector<String> oldConfigParms = oldinst.getInstanceParams();
NameValuePairs saveParams = new NameValuePairs();
@@ -1571,7 +1573,7 @@ public class LogAdminServlet extends AdminServlet {
int index = kv.indexOf('=');
saveParams.add(kv.substring(0, index),
- kv.substring(index + 1));
+ kv.substring(index + 1));
}
}
@@ -1580,27 +1582,27 @@ public class LogAdminServlet extends AdminServlet {
// remove old substore.
IConfigStore destStore =
- mConfig.getSubStore("log");
+ mConfig.getSubStore("log");
IConfigStore instancesConfig =
- destStore.getSubStore("instance");
+ destStore.getSubStore("instance");
// create new substore.
Vector<String> configParams = mSys.getLogInstanceParams(id);
- //instancesConfig.removeSubStore(id);
+ // instancesConfig.removeSubStore(id);
IConfigStore substore = instancesConfig.makeSubStore(id);
substore.put("pluginName", implname);
- // Fix Blackflag Bug #615603: Currently, although expiring log
+ // Fix Blackflag Bug #615603: Currently, although expiring log
// files is no longer supported, it is still a required parameter
// that must be present during the creation and modification of
// custom log plugins.
substore.put("expirationTime", "0");
- // IMPORTANT: save a copy of the original log file path
+ // IMPORTANT: save a copy of the original log file path
origLogPath = substore.getString(Constants.PR_LOG_FILENAME);
newLogPath = origLogPath;
@@ -1612,7 +1614,7 @@ public class LogAdminServlet extends AdminServlet {
newLogPath = "";
}
- // IMPORTANT: save a copy of the original log expiration time
+ // IMPORTANT: save a copy of the original log expiration time
origExpirationTime = substore.getString(
Constants.PR_LOG_EXPIRED_TIME);
newExpirationTime = origExpirationTime;
@@ -1627,16 +1629,15 @@ public class LogAdminServlet extends AdminServlet {
if (configParams != null) {
for (int i = 0; i < configParams.size(); i++) {
- AUTHZ_RES_NAME =
+ AUTHZ_RES_NAME =
"certServer.log.configuration";
String kv = (String) configParams.elementAt(i);
int index = kv.indexOf('=');
String key = kv.substring(0, index);
String val = req.getParameter(key);
- if
- (key.equals("level")) {
- if (val.equals(ILogger.LL_DEBUG_STRING))
+ if (key.equals("level")) {
+ if (val.equals(ILogger.LL_DEBUG_STRING))
val = "0";
else if (val.equals(ILogger.LL_INFO_STRING))
val = "1";
@@ -1653,9 +1654,8 @@ public class LogAdminServlet extends AdminServlet {
}
- if
- (key.equals("rolloverInterval")) {
- if (val.equals("Hourly"))
+ if (key.equals("rolloverInterval")) {
+ if (val.equals("Hourly"))
val = Integer.toString(60 * 60);
else if (val.equals("Daily"))
val = Integer.toString(60 * 60 * 24);
@@ -1667,8 +1667,7 @@ public class LogAdminServlet extends AdminServlet {
val = Integer.toString(60 * 60 * 24 * 365);
}
- if
- (key.equals(Constants.PR_LOG_TYPE)) {
+ if (key.equals(Constants.PR_LOG_TYPE)) {
type = val;
}
@@ -1679,7 +1678,7 @@ public class LogAdminServlet extends AdminServlet {
val = val.trim();
newLogPath = val;
if (!val.equals(origVal.trim())) {
- AUTHZ_RES_NAME =
+ AUTHZ_RES_NAME =
"certServer.log.configuration.fileName";
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
@@ -1709,58 +1708,45 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
- return;
- }
- }
- }
-/*
- if (key.equals("expirationTime")) {
- String origVal = substore.getString(key);
-
- val = val.trim();
- newExpirationTime = val;
- if (!val.equals(origVal.trim())) {
- if (id.equals(SIGNED_AUDIT_LOG_TYPE)) {
- AUTHZ_RES_NAME =
- "certServer.log.configuration.signedAudit.expirationTime";
- }
- mOp = "modify";
- if ((mToken = super.authorize(req)) == null) {
- // store a message in the signed audit log
- // file (regardless of logType)
- if (!(newExpirationTime.equals(origExpirationTime))) {
- auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_LOG_EXPIRATION_CHANGE,
- auditSubjectID,
- ILogger.FAILURE,
- logType,
- newExpirationTime);
-
- audit(auditMessage);
- }
-
- // store a message in the signed audit log
- // file
- if (logType.equals(SIGNED_AUDIT_LOG_TYPE)) {
- auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CONFIG_SIGNED_AUDIT,
- auditSubjectID,
- ILogger.FAILURE,
- auditParams(req));
-
- audit(auditMessage);
- }
-
- sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
}
}
-*/
+ /*
+ * if (key.equals("expirationTime")) { String origVal =
+ * substore.getString(key);
+ *
+ * val = val.trim(); newExpirationTime = val; if
+ * (!val.equals(origVal.trim())) { if
+ * (id.equals(SIGNED_AUDIT_LOG_TYPE)) { AUTHZ_RES_NAME =
+ * "certServer.log.configuration.signedAudit.expirationTime"
+ * ; } mOp = "modify"; if ((mToken =
+ * super.authorize(req)) == null) { // store a message
+ * in the signed audit log // file (regardless of
+ * logType) if
+ * (!(newExpirationTime.equals(origExpirationTime))) {
+ * auditMessage = CMS.getLogMessage(
+ * LOGGING_SIGNED_AUDIT_LOG_EXPIRATION_CHANGE,
+ * auditSubjectID, ILogger.FAILURE, logType,
+ * newExpirationTime);
+ *
+ * audit(auditMessage); }
+ *
+ * // store a message in the signed audit log // file if
+ * (logType.equals(SIGNED_AUDIT_LOG_TYPE)) {
+ * auditMessage = CMS.getLogMessage(
+ * LOGGING_SIGNED_AUDIT_CONFIG_SIGNED_AUDIT,
+ * auditSubjectID, ILogger.FAILURE, auditParams(req));
+ *
+ * audit(auditMessage); }
+ *
+ * sendResponse(ERROR,
+ * CMS.getUserMessage(getLocale(req),
+ * "CMS_ADMIN_SRVLT_AUTHZ_FAILED"), null, resp); return;
+ * } } }
+ */
substore.put(key, val);
}
}
@@ -1772,7 +1758,7 @@ public class LogAdminServlet extends AdminServlet {
ILogEventListener newMgrInst = null;
try {
- newMgrInst = (ILogEventListener)
+ newMgrInst = (ILogEventListener)
Class.forName(className).newInstance();
} catch (ClassNotFoundException e) {
// check to see if the log file path parameter was changed
@@ -1800,16 +1786,13 @@ public class LogAdminServlet extends AdminServlet {
// store a message in the signed audit log file
// (regardless of logType)
/*
- if (!(newExpirationTime.equals(origExpirationTime))) {
- auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_LOG_EXPIRATION_CHANGE,
- auditSubjectID,
- ILogger.FAILURE,
- logType,
- newExpirationTime);
-
- audit(auditMessage);
- }*/
+ * if (!(newExpirationTime.equals(origExpirationTime))) {
+ * auditMessage = CMS.getLogMessage(
+ * LOGGING_SIGNED_AUDIT_LOG_EXPIRATION_CHANGE, auditSubjectID,
+ * ILogger.FAILURE, logType, newExpirationTime);
+ *
+ * audit(auditMessage); }
+ */
// store a message in the signed audit log file
if (logType.equals(SIGNED_AUDIT_LOG_TYPE)) {
@@ -1823,15 +1806,15 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- new ELogException(CMS.getUserMessage(getLocale(req),"CMS_LOG_LOAD_CLASS_FAIL", className)).toString(),
- null, resp);
+ new ELogException(CMS.getUserMessage(getLocale(req), "CMS_LOG_LOAD_CLASS_FAIL", className)).toString(),
+ null, resp);
return;
} catch (InstantiationException e) {
// check to see if the log file path parameter was changed
newLogPath = auditCheckLogPath(req);
// check to see if the log expiration time parameter was changed
- //newExpirationTime = auditCheckLogExpirationTime(req);
+ // newExpirationTime = auditCheckLogExpirationTime(req);
restore(instancesConfig, id, saveParams);
@@ -1850,16 +1833,14 @@ public class LogAdminServlet extends AdminServlet {
// store a message in the signed audit log file
// (regardless of logType)
- /*if (!(newExpirationTime.equals(origExpirationTime))) {
- auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_LOG_EXPIRATION_CHANGE,
- auditSubjectID,
- ILogger.FAILURE,
- logType,
- newExpirationTime);
-
- audit(auditMessage);
- }*/
+ /*
+ * if (!(newExpirationTime.equals(origExpirationTime))) {
+ * auditMessage = CMS.getLogMessage(
+ * LOGGING_SIGNED_AUDIT_LOG_EXPIRATION_CHANGE, auditSubjectID,
+ * ILogger.FAILURE, logType, newExpirationTime);
+ *
+ * audit(auditMessage); }
+ */
// store a message in the signed audit log file
if (logType.equals(SIGNED_AUDIT_LOG_TYPE)) {
@@ -1873,15 +1854,15 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- new ELogException(CMS.getUserMessage(getLocale(req),"CMS_LOG_LOAD_CLASS_FAIL", className)).toString(),
- null, resp);
+ new ELogException(CMS.getUserMessage(getLocale(req), "CMS_LOG_LOAD_CLASS_FAIL", className)).toString(),
+ null, resp);
return;
} catch (IllegalAccessException e) {
// check to see if the log file path parameter was changed
newLogPath = auditCheckLogPath(req);
// check to see if the log expiration time parameter was changed
- //newExpirationTime = auditCheckLogExpirationTime(req);
+ // newExpirationTime = auditCheckLogExpirationTime(req);
restore(instancesConfig, id, saveParams);
@@ -1900,16 +1881,14 @@ public class LogAdminServlet extends AdminServlet {
// store a message in the signed audit log file
// (regardless of logType)
- /* if (!(newExpirationTime.equals(origExpirationTime))) {
- auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_LOG_EXPIRATION_CHANGE,
- auditSubjectID,
- ILogger.FAILURE,
- logType,
- newExpirationTime);
-
- audit(auditMessage);
- } */
+ /*
+ * if (!(newExpirationTime.equals(origExpirationTime))) {
+ * auditMessage = CMS.getLogMessage(
+ * LOGGING_SIGNED_AUDIT_LOG_EXPIRATION_CHANGE, auditSubjectID,
+ * ILogger.FAILURE, logType, newExpirationTime);
+ *
+ * audit(auditMessage); }
+ */
// store a message in the signed audit log file
if (logType.equals(SIGNED_AUDIT_LOG_TYPE)) {
@@ -1923,13 +1902,13 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- new ELogException(CMS.getUserMessage(getLocale(req),"CMS_LOG_LOAD_CLASS_FAIL", className)).toString(),
- null, resp);
+ new ELogException(CMS.getUserMessage(getLocale(req), "CMS_LOG_LOAD_CLASS_FAIL", className)).toString(),
+ null, resp);
return;
}
// initialize the log
- // initialized ok. commiting
+ // initialized ok. commiting
try {
mConfig.commit(true);
} catch (EBaseException e) {
@@ -1941,7 +1920,7 @@ public class LogAdminServlet extends AdminServlet {
// clean up.
restore(instancesConfig, id, saveParams);
- //System.out.println("SRVLT_FAIL_COMMIT");
+ // System.out.println("SRVLT_FAIL_COMMIT");
// store a message in the signed audit log file
// (regardless of logType)
@@ -1958,16 +1937,14 @@ public class LogAdminServlet extends AdminServlet {
// store a message in the signed audit log file
// (regardless of logType)
- /* if (!(newExpirationTime.equals(origExpirationTime))) {
- auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_LOG_EXPIRATION_CHANGE,
- auditSubjectID,
- ILogger.FAILURE,
- logType,
- newExpirationTime);
-
- audit(auditMessage);
- }*/
+ /*
+ * if (!(newExpirationTime.equals(origExpirationTime))) {
+ * auditMessage = CMS.getLogMessage(
+ * LOGGING_SIGNED_AUDIT_LOG_EXPIRATION_CHANGE, auditSubjectID,
+ * ILogger.FAILURE, logType, newExpirationTime);
+ *
+ * audit(auditMessage); }
+ */
// store a message in the signed audit log file
if (logType.equals(SIGNED_AUDIT_LOG_TYPE)) {
@@ -1981,18 +1958,19 @@ public class LogAdminServlet extends AdminServlet {
}
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
+ null, resp);
return;
}
// commited ok. replace instance.
- // REMOVED - we didn't do anything to shut off the old instance
- // so, it will still be running at this point. You'd have two
- // log isntances writing to the same file - this would be a big PROBLEM!!!
+ // REMOVED - we didn't do anything to shut off the old instance
+ // so, it will still be running at this point. You'd have two
+ // log isntances writing to the same file - this would be a big
+ // PROBLEM!!!
- //mSys.getLogInsts().put(id, newMgrInst);
+ // mSys.getLogInsts().put(id, newMgrInst);
NameValuePairs params = new NameValuePairs();
@@ -2000,7 +1978,7 @@ public class LogAdminServlet extends AdminServlet {
newLogPath = auditCheckLogPath(req);
// check to see if the log expiration time parameter was changed
- //newExpirationTime = auditCheckLogExpirationTime(req);
+ // newExpirationTime = auditCheckLogExpirationTime(req);
// store a message in the signed audit log file
// (regardless of logType)
@@ -2017,16 +1995,14 @@ public class LogAdminServlet extends AdminServlet {
// store a message in the signed audit log file
// (regardless of logType)
- /*if (!(newExpirationTime.equals(origExpirationTime))) {
- auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_LOG_EXPIRATION_CHANGE,
- auditSubjectID,
- ILogger.SUCCESS,
- logType,
- newExpirationTime);
-
- audit(auditMessage);
- }*/
+ /*
+ * if (!(newExpirationTime.equals(origExpirationTime))) {
+ * auditMessage = CMS.getLogMessage(
+ * LOGGING_SIGNED_AUDIT_LOG_EXPIRATION_CHANGE, auditSubjectID,
+ * ILogger.SUCCESS, logType, newExpirationTime);
+ *
+ * audit(auditMessage); }
+ */
// store a message in the signed audit log file
if (logType.equals(SIGNED_AUDIT_LOG_TYPE)) {
@@ -2063,16 +2039,14 @@ public class LogAdminServlet extends AdminServlet {
// store a message in the signed audit log file
// (regardless of logType)
- /* if (!(newExpirationTime.equals(origExpirationTime))) {
- auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_LOG_EXPIRATION_CHANGE,
- auditSubjectID,
- ILogger.FAILURE,
- logType,
- newExpirationTime);
-
- audit(auditMessage);
- } */
+ /*
+ * if (!(newExpirationTime.equals(origExpirationTime))) {
+ * auditMessage = CMS.getLogMessage(
+ * LOGGING_SIGNED_AUDIT_LOG_EXPIRATION_CHANGE, auditSubjectID,
+ * ILogger.FAILURE, logType, newExpirationTime);
+ *
+ * audit(auditMessage); }
+ */
// store a message in the signed audit log file
if (logType.equals(SIGNED_AUDIT_LOG_TYPE)) {
@@ -2109,16 +2083,14 @@ public class LogAdminServlet extends AdminServlet {
// store a message in the signed audit log file
// (regardless of logType)
- /*if (!(newExpirationTime.equals(origExpirationTime))) {
- auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_LOG_EXPIRATION_CHANGE,
- auditSubjectID,
- ILogger.FAILURE,
- logType,
- newExpirationTime);
-
- audit(auditMessage);
- }*/
+ /*
+ * if (!(newExpirationTime.equals(origExpirationTime))) {
+ * auditMessage = CMS.getLogMessage(
+ * LOGGING_SIGNED_AUDIT_LOG_EXPIRATION_CHANGE, auditSubjectID,
+ * ILogger.FAILURE, logType, newExpirationTime);
+ *
+ * audit(auditMessage); }
+ */
// store a message in the signed audit log file
if (logType.equals(SIGNED_AUDIT_LOG_TYPE)) {
@@ -2134,74 +2106,73 @@ public class LogAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit2;
// } catch( ServletException eAudit3 ) {
- // // check to see if the log file path parameter was changed
- // newLogPath = auditCheckLogPath( req );
+ // // check to see if the log file path parameter was changed
+ // newLogPath = auditCheckLogPath( req );
//
- // // check to see if the log expiration time parameter was changed
- // newExpirationTime = auditCheckLogExpirationTime( req );
+ // // check to see if the log expiration time parameter was changed
+ // newExpirationTime = auditCheckLogExpirationTime( req );
//
- // // store a message in the signed audit log file
- // // (regardless of logType)
- // if( !( newLogPath.equals( origLogPath ) ) ) {
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_LOG_PATH_CHANGE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // logType,
- // newLogPath );
+ // // store a message in the signed audit log file
+ // // (regardless of logType)
+ // if( !( newLogPath.equals( origLogPath ) ) ) {
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_LOG_PATH_CHANGE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // logType,
+ // newLogPath );
//
- // audit( auditMessage );
- // }
+ // audit( auditMessage );
+ // }
//
- // // store a message in the signed audit log file
- // // (regardless of logType)
- // if( !( newExpirationTime.equals( origExpirationTime ) ) ) {
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_LOG_EXPIRATION_CHANGE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // logType,
- // newExpirationTime );
+ // // store a message in the signed audit log file
+ // // (regardless of logType)
+ // if( !( newExpirationTime.equals( origExpirationTime ) ) ) {
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_LOG_EXPIRATION_CHANGE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // logType,
+ // newExpirationTime );
//
- // audit( auditMessage );
- // }
+ // audit( auditMessage );
+ // }
//
- // // store a message in the signed audit log file
- // if( logType.equals( SIGNED_AUDIT_LOG_TYPE ) ) {
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_SIGNED_AUDIT,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // if( logType.equals( SIGNED_AUDIT_LOG_TYPE ) ) {
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_SIGNED_AUDIT,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
- // }
+ // audit( auditMessage );
+ // }
//
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
}
}
/**
- * used for getting the required configuration parameters (with
- * possible default values) for a particular plugin
- * implementation name specified in the RS_ID. Actually, there is
- * no logic in here to set any default value here...there's no
- * default value for any parameter in this log subsystem
- * at this point. Later, if we do have one (or some), it can be
- * added. The interface remains the same.
+ * used for getting the required configuration parameters (with possible
+ * default values) for a particular plugin implementation name specified in
+ * the RS_ID. Actually, there is no logic in here to set any default value
+ * here...there's no default value for any parameter in this log subsystem
+ * at this point. Later, if we do have one (or some), it can be added. The
+ * interface remains the same.
*/
- private synchronized void getConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException, EBaseException {
+ private synchronized void getConfig(HttpServletRequest req,
+ HttpServletResponse resp)
+ throws ServletException, IOException, EBaseException {
String implname = req.getParameter(Constants.RS_ID);
if (implname == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
@@ -2218,8 +2189,8 @@ public class LogAdminServlet extends AdminServlet {
if (index == -1) {
params.add(kv, "");
} else {
- params.add(kv.substring(0, index),
- kv.substring(index + 1));
+ params.add(kv.substring(0, index),
+ kv.substring(index + 1));
}
}
}
@@ -2227,43 +2198,43 @@ public class LogAdminServlet extends AdminServlet {
return;
}
- private synchronized void getInstConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ private synchronized void getInstConfig(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String id = req.getParameter(Constants.RS_ID);
if (id == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
// does log instance exist?
if (mSys.getLogInsts().containsKey(id) == false) {
sendResponse(ERROR,
- new ELogNotFound(CMS.getUserMessage(getLocale(req),"CMS_LOG_INSTANCE_NOT_FOUND",id)).toString(),
- null, resp);
+ new ELogNotFound(CMS.getUserMessage(getLocale(req), "CMS_LOG_INSTANCE_NOT_FOUND", id)).toString(),
+ null, resp);
return;
}
ILogEventListener logInst = (ILogEventListener)
- mSys.getLogInstance(id);
+ mSys.getLogInstance(id);
Vector<String> configParams = logInst.getInstanceParams();
NameValuePairs params = new NameValuePairs();
- params.add(Constants.PR_LOG_IMPL_NAME,
- getLogPluginName(logInst));
+ params.add(Constants.PR_LOG_IMPL_NAME,
+ getLogPluginName(logInst));
// implName is always required so always send it.
if (configParams != null) {
for (int i = 0; i < configParams.size(); i++) {
String kv = (String) configParams.elementAt(i);
int index = kv.indexOf('=');
- params.add(kv.substring(0, index),
- kv.substring(index + 1));
+ params.add(kv.substring(0, index),
+ kv.substring(index + 1));
}
}
@@ -2272,8 +2243,8 @@ public class LogAdminServlet extends AdminServlet {
}
// convenience routine.
- private static void restore(IConfigStore store,
- String id, NameValuePairs saveParams) {
+ private static void restore(IConfigStore store,
+ String id, NameValuePairs saveParams) {
store.removeSubStore(id);
IConfigStore rstore = store.makeSubStore(id);
@@ -2283,17 +2254,17 @@ public class LogAdminServlet extends AdminServlet {
String key = (String) keys.nextElement();
String value = saveParams.getValue(key);
- if (value != null)
+ if (value != null)
rstore.put(key, value);
}
}
/**
* Signed Audit Check Log Path
- *
+ *
* This method is called to extract the log file path.
* <P>
- *
+ *
* @param req http servlet request
* @return a string containing the log file path
*/
@@ -2311,7 +2282,7 @@ public class LogAdminServlet extends AdminServlet {
}
private void getGeneralConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
@@ -2327,11 +2298,11 @@ public class LogAdminServlet extends AdminServlet {
}
private void setGeneralConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
@SuppressWarnings("unchecked")
- Enumeration<String> enum1 = req.getParameterNames();
+ Enumeration<String> enum1 = req.getParameterNames();
boolean restart = false;
while (enum1.hasMoreElements()) {
@@ -2353,7 +2324,7 @@ public class LogAdminServlet extends AdminServlet {
CMS.debug("setGeneralConfig: Invalid value for " + Constants.PR_DEBUG_LOG_LEVEL + ": " + value);
throw new EBaseException("Invalid value for " + Constants.PR_DEBUG_LOG_LEVEL);
}
- }
+ }
}
mConfig.commit(true);
@@ -2365,4 +2336,3 @@ public class LogAdminServlet extends AdminServlet {
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/admin/OCSPAdminServlet.java b/pki/base/common/src/com/netscape/cms/servlet/admin/OCSPAdminServlet.java
index 152b364f..263878f0 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/admin/OCSPAdminServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/admin/OCSPAdminServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.admin;
-
import java.io.IOException;
import java.util.Enumeration;
import java.util.Locale;
@@ -39,13 +38,11 @@ import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.ocsp.IOCSPAuthority;
import com.netscape.certsrv.ocsp.IOCSPStore;
-
/**
- * A class representings an administration servlet for Certificate
- * Authority. This servlet is responsible to serve OCSP
- * administrative operations such as configuration parameter
- * updates.
- *
+ * A class representings an administration servlet for Certificate Authority.
+ * This servlet is responsible to serve OCSP administrative operations such as
+ * configuration parameter updates.
+ *
* @version $Revision$, $Date$
*/
public class OCSPAdminServlet extends AdminServlet {
@@ -60,7 +57,7 @@ public class OCSPAdminServlet extends AdminServlet {
private final static String INFO = "OCSPAdminServlet";
private final static String LOGGING_SIGNED_AUDIT_CONFIG_OCSP_PROFILE =
- "LOGGING_SIGNED_AUDIT_CONFIG_OCSP_PROFILE_3";
+ "LOGGING_SIGNED_AUDIT_CONFIG_OCSP_PROFILE_3";
private IOCSPAuthority mOCSP = null;
@@ -84,33 +81,33 @@ public class OCSPAdminServlet extends AdminServlet {
}
/**
- * Serves HTTP request. Each request is authenticated to
- * the authenticate manager.
+ * Serves HTTP request. Each request is authenticated to the authenticate
+ * manager.
*/
public void service(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
+ throws ServletException, IOException {
super.service(req, resp);
-
- //get all operational flags
+
+ // get all operational flags
String op = req.getParameter(Constants.OP_TYPE);
String scope = req.getParameter(Constants.OP_SCOPE);
- //check operational flags
+ // check operational flags
if ((op == null) || (scope == null)) {
sendResponse(1, "Invalid Protocol", null, resp);
return;
- }
+ }
super.authenticate(req);
-
+
try {
AUTHZ_RES_NAME = "certServer.ocsp.configuration";
if (scope.equals(ScopeDef.SC_EXTENDED_PLUGIN_INFO)) {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
try {
@@ -126,8 +123,8 @@ public class OCSPAdminServlet extends AdminServlet {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
setDefaultStore(req, resp);
@@ -139,8 +136,8 @@ public class OCSPAdminServlet extends AdminServlet {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_GENERAL)) {
@@ -154,8 +151,8 @@ public class OCSPAdminServlet extends AdminServlet {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_GENERAL)) {
@@ -169,8 +166,8 @@ public class OCSPAdminServlet extends AdminServlet {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_OCSPSTORES_RULES)) {
@@ -185,11 +182,11 @@ public class OCSPAdminServlet extends AdminServlet {
}
/**
- * retrieve extended plugin info such as brief description,
- * type info from CRL extensions
+ * retrieve extended plugin info such as brief description, type info from
+ * CRL extensions
*/
private void getExtendedPluginInfo(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String id = req.getParameter(Constants.RS_ID);
int colon = id.indexOf(':');
@@ -198,7 +195,7 @@ public class OCSPAdminServlet extends AdminServlet {
String implName = id.substring(colon + 1);
NameValuePairs params =
- getExtendedPluginInfo(getLocale(req), implType, implName);
+ getExtendedPluginInfo(getLocale(req), implType, implName);
sendResponse(SUCCESS, null, params, resp);
}
@@ -229,12 +226,13 @@ public class OCSPAdminServlet extends AdminServlet {
/**
* Set default OCSP store
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_OCSP_PROFILE used when
* configuring OCSP profile (everything under Online Certificate Status
* Manager)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
@@ -242,8 +240,8 @@ public class OCSPAdminServlet extends AdminServlet {
* @exception EBaseException an error has occurred
*/
private void setDefaultStore(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException, EBaseException {
+ HttpServletResponse resp)
+ throws ServletException, IOException, EBaseException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -253,7 +251,7 @@ public class OCSPAdminServlet extends AdminServlet {
String id = req.getParameter(Constants.RS_ID);
mOCSP.getConfigStore().putString(IOCSPAuthority.PROP_DEF_STORE_ID,
- id);
+ id);
commit(true);
// store a message in the signed audit log file
@@ -291,23 +289,23 @@ public class OCSPAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit2;
// } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_OCSP_PROFILE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_OCSP_PROFILE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
}
}
private void getOCSPStoresConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException, EBaseException {
+ HttpServletResponse resp)
+ throws ServletException, IOException, EBaseException {
String id = req.getParameter(Constants.RS_ID);
IOCSPStore store = mOCSP.getOCSPStore(id);
@@ -319,12 +317,13 @@ public class OCSPAdminServlet extends AdminServlet {
/**
* Set OCSP store configuration
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_OCSP_PROFILE used when
* configuring OCSP profile (everything under Online Certificate Status
* Manager)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
@@ -332,8 +331,8 @@ public class OCSPAdminServlet extends AdminServlet {
* @exception EBaseException an error has occurred
*/
private void setOCSPStoresConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException, EBaseException {
+ HttpServletResponse resp)
+ throws ServletException, IOException, EBaseException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -403,23 +402,23 @@ public class OCSPAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit2;
// } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_OCSP_PROFILE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_OCSP_PROFILE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
}
}
private void listOCSPStoresConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException, EBaseException {
+ HttpServletResponse resp)
+ throws ServletException, IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
IConfigStore config = mOCSP.getConfigStore();
String defStore = config.getString(IOCSPAuthority.PROP_DEF_STORE_ID);
@@ -439,7 +438,7 @@ public class OCSPAdminServlet extends AdminServlet {
}
private void getGeneralConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
@@ -451,7 +450,7 @@ public class OCSPAdminServlet extends AdminServlet {
private void getSigningAlgConfig(NameValuePairs params) {
params.add(Constants.PR_DEFAULT_ALGORITHM,
- mOCSP.getDefaultAlgorithm());
+ mOCSP.getDefaultAlgorithm());
String[] algorithms = mOCSP.getOCSPSigningAlgorithms();
StringBuffer algorStr = new StringBuffer();
@@ -460,7 +459,7 @@ public class OCSPAdminServlet extends AdminServlet {
algorStr.append(algorithms[i]);
else
algorStr.append(":");
- algorStr.append(algorithms[i]);
+ algorStr.append(algorithms[i]);
}
params.add(Constants.PR_ALL_ALGORITHMS, algorStr.toString());
}
@@ -468,12 +467,13 @@ public class OCSPAdminServlet extends AdminServlet {
/**
* Set general OCSP configuration
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_OCSP_PROFILE used when
* configuring OCSP profile (everything under Online Certificate Status
* Manager)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
@@ -481,7 +481,7 @@ public class OCSPAdminServlet extends AdminServlet {
* @exception EBaseException an error has occurred
*/
private void setGeneralConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String auditMessage = null;
@@ -538,7 +538,7 @@ public class OCSPAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit2;
-
+
}
}
-}
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/admin/PolicyAdminServlet.java b/pki/base/common/src/com/netscape/cms/servlet/admin/PolicyAdminServlet.java
index 10a768a2..2216c2c3 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/admin/PolicyAdminServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/admin/PolicyAdminServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.admin;
-
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
@@ -44,14 +43,12 @@ import com.netscape.certsrv.policy.IPolicyProcessor;
import com.netscape.certsrv.policy.IPolicyRule;
import com.netscape.certsrv.ra.IRegistrationAuthority;
-
/**
* This class is an administration servlet for policy management.
- *
- * Each service (CA, KRA, RA) should be responsible
- * for registering an instance of this with the remote
- * administration subsystem.
- *
+ *
+ * Each service (CA, KRA, RA) should be responsible for registering an instance
+ * of this with the remote administration subsystem.
+ *
* @version $Revision$, $Date$
*/
public class PolicyAdminServlet extends AdminServlet {
@@ -63,8 +60,8 @@ public class PolicyAdminServlet extends AdminServlet {
public final static String PROP_AUTHORITY = "authority";
private final static String INFO = "PolicyAdminServlet";
- private final static String PW_PASSWORD_CACHE_ADD =
- "PASSWORD_CACHE_ADD";
+ private final static String PW_PASSWORD_CACHE_ADD =
+ "PASSWORD_CACHE_ADD";
public final static String PROP_PREDICATE = "predicate";
private IPolicyProcessor mProcessor = null;
@@ -85,7 +82,7 @@ public class PolicyAdminServlet extends AdminServlet {
public static String MISSING_POLICY_ORDERING = "Missing policy ordering";
private final static String LOGGING_SIGNED_AUDIT_CONFIG_CERT_POLICY =
- "LOGGING_SIGNED_AUDIT_CONFIG_CERT_POLICY_3";
+ "LOGGING_SIGNED_AUDIT_CONFIG_CERT_POLICY_3";
/**
* Constructs administration servlet.
@@ -102,7 +99,7 @@ public class PolicyAdminServlet extends AdminServlet {
String authority = config.getInitParameter(PROP_AUTHORITY);
String policyStatus = null;
- CMS.debug( "PolicyAdminServlet: In Policy Admin Servlet init!" );
+ CMS.debug("PolicyAdminServlet: In Policy Admin Servlet init!");
// CMS 6.1 began utilizing the "Certificate Profiles" framework
// instead of the legacy "Certificate Policies" framework.
@@ -112,22 +109,22 @@ public class PolicyAdminServlet extends AdminServlet {
// that this legacy "Certificate Policies" framework would be
// deprecated and disabled by default (see Bugzilla Bug #472597).
//
- // NOTE: The "Certificate Policies" framework ONLY applied to
- // to CA, KRA, and legacy RA (pre-CMS 7.0) subsystems.
+ // NOTE: The "Certificate Policies" framework ONLY applied to
+ // to CA, KRA, and legacy RA (pre-CMS 7.0) subsystems.
//
- // Further, the "PolicyAdminServlet.java" servlet is ONLY used
- // by the CA Console for the following:
+ // Further, the "PolicyAdminServlet.java" servlet is ONLY used
+ // by the CA Console for the following:
//
- // SERVLET-NAME URL-PATTERN
- // ====================================================
- // capolicy ca/capolicy
+ // SERVLET-NAME URL-PATTERN
+ // ====================================================
+ // capolicy ca/capolicy
//
- // Finally, the "PolicyAdminServlet.java" servlet is ONLY used
- // by the KRA Console for the following:
+ // Finally, the "PolicyAdminServlet.java" servlet is ONLY used
+ // by the KRA Console for the following:
//
- // SERVLET-NAME URL-PATTERN
- // ====================================================
- // krapolicy kra/krapolicy
+ // SERVLET-NAME URL-PATTERN
+ // ====================================================
+ // krapolicy kra/krapolicy
//
if (authority != null)
mAuthority = (IAuthority) CMS.getSubsystem(authority);
@@ -138,28 +135,28 @@ public class PolicyAdminServlet extends AdminServlet {
policyStatus = ICertificateAuthority.ID
+ "." + "Policy"
+ "." + IPolicyProcessor.PROP_ENABLE;
- if( mConfig.getBoolean( policyStatus, true ) == true ) {
- // NOTE: If "ca.Policy.enable=<boolean>" is missing,
- // then the referenced instance existed prior
- // to this name=value pair existing in its
- // 'CS.cfg' file, and thus we err on the
- // side that the user may still need to
- // use the policy framework.
- CMS.debug( "PolicyAdminServlet::init "
+ if (mConfig.getBoolean(policyStatus, true) == true) {
+ // NOTE: If "ca.Policy.enable=<boolean>" is missing,
+ // then the referenced instance existed prior
+ // to this name=value pair existing in its
+ // 'CS.cfg' file, and thus we err on the
+ // side that the user may still need to
+ // use the policy framework.
+ CMS.debug("PolicyAdminServlet::init "
+ "Certificate Policy Framework (deprecated) "
- + "is ENABLED" );
+ + "is ENABLED");
} else {
- // CS 8.1 Default: ca.Policy.enable=false
- CMS.debug( "PolicyAdminServlet::init "
+ // CS 8.1 Default: ca.Policy.enable=false
+ CMS.debug("PolicyAdminServlet::init "
+ "Certificate Policy Framework (deprecated) "
- + "is DISABLED" );
- return;
+ + "is DISABLED");
+ return;
}
- } catch( EBaseException e ) {
- throw new ServletException( authority
+ } catch (EBaseException e) {
+ throw new ServletException(authority
+ " does not have a "
+ "master policy switch called '"
- + policyStatus + "'" );
+ + policyStatus + "'");
}
} else if (mAuthority instanceof IRegistrationAuthority) {
// this refers to the legacy RA (pre-CMS 7.0)
@@ -167,34 +164,34 @@ public class PolicyAdminServlet extends AdminServlet {
} else if (mAuthority instanceof IKeyRecoveryAuthority) {
mProcessor = ((IKeyRecoveryAuthority) mAuthority).getPolicyProcessor();
try {
- policyStatus = IKeyRecoveryAuthority.ID
+ policyStatus = IKeyRecoveryAuthority.ID
+ "." + "Policy"
+ "." + IPolicyProcessor.PROP_ENABLE;
- if( mConfig.getBoolean( policyStatus, true ) == true ) {
- // NOTE: If "kra.Policy.enable=<boolean>" is missing,
- // then the referenced instance existed prior
- // to this name=value pair existing in its
- // 'CS.cfg' file, and thus we err on the
- // side that the user may still need to
- // use the policy framework.
- CMS.debug( "PolicyAdminServlet::init "
+ if (mConfig.getBoolean(policyStatus, true) == true) {
+ // NOTE: If "kra.Policy.enable=<boolean>" is missing,
+ // then the referenced instance existed prior
+ // to this name=value pair existing in its
+ // 'CS.cfg' file, and thus we err on the
+ // side that the user may still need to
+ // use the policy framework.
+ CMS.debug("PolicyAdminServlet::init "
+ "Certificate Policy Framework (deprecated) "
- + "is ENABLED" );
+ + "is ENABLED");
} else {
- // CS 8.1 Default: kra.Policy.enable=false
- CMS.debug( "PolicyAdminServlet::init "
+ // CS 8.1 Default: kra.Policy.enable=false
+ CMS.debug("PolicyAdminServlet::init "
+ "Certificate Policy Framework (deprecated) "
- + "is DISABLED" );
- return;
+ + "is DISABLED");
+ return;
}
- } catch( EBaseException e ) {
- throw new ServletException( authority
+ } catch (EBaseException e) {
+ throw new ServletException(authority
+ " does not have a "
+ "master policy switch called '"
- + policyStatus + "'" );
+ + policyStatus + "'");
}
- } else
- throw new ServletException(authority + " does not have policy processor!");
+ } else
+ throw new ServletException(authority + " does not have policy processor!");
}
/**
@@ -204,15 +201,15 @@ public class PolicyAdminServlet extends AdminServlet {
return INFO;
}
- /**
- * retrieve extended plugin info such as brief description, type info
- * from policy, authentication,
- * need to add: listener, mapper and publishing plugins
+ /**
+ * retrieve extended plugin info such as brief description, type info from
+ * policy, authentication, need to add: listener, mapper and publishing
+ * plugins
*/
private void getExtendedPluginInfo(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
-
+
if (!readAuthorize(req, resp))
return;
String id = req.getParameter(Constants.RS_ID);
@@ -248,27 +245,27 @@ public class PolicyAdminServlet extends AdminServlet {
ext_info = (IExtendedPluginInfo) impl;
}
}
-
+
NameValuePairs nvps = null;
-
+
if (ext_info == null) {
nvps = new NameValuePairs();
} else {
nvps = convertStringArrayToNVPairs(ext_info.getExtendedPluginInfo(locale));
}
-
+
return nvps;
}
public NameValuePairs getExtendedPluginInfo(Locale locale, String pluginType,
- String implName,
- String instName) {
+ String implName,
+ String instName) {
IExtendedPluginInfo ext_info = null;
Object impl = null;
IPolicyRule policy = mProcessor.getPolicyInstance(instName);
-
+
impl = policy;
if (impl == null) {
impl = mProcessor.getPolicyImpl(implName);
@@ -313,8 +310,8 @@ public class PolicyAdminServlet extends AdminServlet {
* Serves HTTP admin request.
*/
public void service(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
super.service(req, resp);
super.authenticate(req);
@@ -332,30 +329,30 @@ public class PolicyAdminServlet extends AdminServlet {
} catch (EBaseException e) {
sendResponse(ERROR, e.toString(getLocale(req)), null, resp);
return;
- }
+ }
} else
sendResponse(ERROR, INVALID_POLICY_SCOPE, null, resp);
}
- private boolean readAuthorize(HttpServletRequest req,
- HttpServletResponse resp) throws IOException {
+ private boolean readAuthorize(HttpServletRequest req,
+ HttpServletResponse resp) throws IOException {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return false;
}
return true;
}
- private boolean modifyAuthorize(HttpServletRequest req,
- HttpServletResponse resp) throws IOException {
+ private boolean modifyAuthorize(HttpServletRequest req,
+ HttpServletResponse resp) throws IOException {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return false;
}
return true;
@@ -365,8 +362,8 @@ public class PolicyAdminServlet extends AdminServlet {
* Process Policy Implementation Management.
*/
public void processPolicyImplMgmt(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
// Get operation type
String op = req.getParameter(Constants.OP_TYPE);
@@ -388,12 +385,12 @@ public class PolicyAdminServlet extends AdminServlet {
addPolicyImpl(req, resp);
} else
sendResponse(ERROR, INVALID_POLICY_IMPL_OP,
- null, resp);
+ null, resp);
}
public void processPolicyRuleMgmt(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
// Get operation type
String op = req.getParameter(Constants.OP_TYPE);
@@ -424,17 +421,17 @@ public class PolicyAdminServlet extends AdminServlet {
modifyPolicyInstance(req, resp);
} else
sendResponse(ERROR, INVALID_POLICY_IMPL_OP,
- null, resp);
+ null, resp);
}
public void listPolicyImpls(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
Enumeration policyImplNames = mProcessor.getPolicyImplsInfo();
Enumeration policyImpls = mProcessor.getPolicyImpls();
if (policyImplNames == null ||
- policyImpls == null) {
+ policyImpls == null) {
sendResponse(ERROR, INVALID_POLICY_IMPL_CONFIG, null, resp);
return;
}
@@ -443,12 +440,12 @@ public class PolicyAdminServlet extends AdminServlet {
NameValuePairs nvp = new NameValuePairs();
while (policyImplNames.hasMoreElements() &&
- policyImpls.hasMoreElements()) {
+ policyImpls.hasMoreElements()) {
String id = (String) policyImplNames.nextElement();
IPolicyRule impl = (IPolicyRule)
- policyImpls.nextElement();
+ policyImpls.nextElement();
String className =
- impl.getClass().getName();
+ impl.getClass().getName();
String desc = impl.getDescription();
nvp.add(id, className + "," + desc);
@@ -457,8 +454,8 @@ public class PolicyAdminServlet extends AdminServlet {
}
public void listPolicyInstances(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
Enumeration instancesInfo = mProcessor.getPolicyInstancesInfo();
if (instancesInfo == null) {
@@ -475,7 +472,7 @@ public class PolicyAdminServlet extends AdminServlet {
int i = info.indexOf(";");
nvp.add(info.substring(0, i), info.substring(i + 1));
-
+
}
sendResponse(SUCCESS, null, nvp, resp);
}
@@ -483,19 +480,20 @@ public class PolicyAdminServlet extends AdminServlet {
/**
* Delete policy implementation
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_CERT_POLICY used when
* configuring cert policy constraints and extensions
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
*/
public void deletePolicyImpl(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -533,7 +531,7 @@ public class PolicyAdminServlet extends AdminServlet {
sendResponse(SUCCESS, null, null, resp);
} catch (Exception e) {
- //e.printStackTrace();
+ // e.printStackTrace();
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -559,23 +557,23 @@ public class PolicyAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit1;
// } catch( ServletException eAudit2 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_CERT_POLICY,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_CERT_POLICY,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit2;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit2;
}
}
public void getPolicyImplConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
// Get the policy impl id.
String id = req.getParameter(Constants.RS_ID);
@@ -604,19 +602,20 @@ public class PolicyAdminServlet extends AdminServlet {
/**
* Add policy implementation
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_CERT_POLICY used when
* configuring cert policy constraints and extensions
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
*/
public void addPolicyImpl(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -693,36 +692,37 @@ public class PolicyAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit1;
// } catch( ServletException eAudit2 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_CERT_POLICY,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_CERT_POLICY,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit2;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit2;
}
}
/**
* Delete policy instance
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_CERT_POLICY used when
* configuring cert policy constraints and extensions
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
*/
public void deletePolicyInstance(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -760,7 +760,7 @@ public class PolicyAdminServlet extends AdminServlet {
sendResponse(SUCCESS, null, null, resp);
} catch (Exception e) {
- //e.printStackTrace();
+ // e.printStackTrace();
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -786,23 +786,23 @@ public class PolicyAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit1;
// } catch( ServletException eAudit2 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_CERT_POLICY,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_CERT_POLICY,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit2;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit2;
}
}
public void getPolicyInstanceConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
// Get the policy rule id.
String id = req.getParameter(Constants.RS_ID).trim();
@@ -836,7 +836,7 @@ public class PolicyAdminServlet extends AdminServlet {
}
public void
- putUserPWPair(String combo) {
+ putUserPWPair(String combo) {
int semicolon;
semicolon = combo.indexOf(";");
@@ -849,19 +849,20 @@ public class PolicyAdminServlet extends AdminServlet {
/**
* Add policy instance
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_CERT_POLICY used when
* configuring cert policy constraints and extensions
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
*/
public void addPolicyInstance(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -988,36 +989,37 @@ public class PolicyAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit1;
// } catch( ServletException eAudit2 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_CERT_POLICY,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_CERT_POLICY,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit2;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit2;
}
}
/**
* Change ordering of policy instances
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_CERT_POLICY used when
* configuring cert policy constraints and extensions
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
*/
public void changePolicyInstanceOrdering(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -1025,7 +1027,7 @@ public class PolicyAdminServlet extends AdminServlet {
// to the signed audit log and stored as failures
try {
String policyOrder =
- req.getParameter(Constants.PR_POLICY_ORDER);
+ req.getParameter(Constants.PR_POLICY_ORDER);
if (policyOrder == null) {
// store a message in the signed audit log file
@@ -1078,36 +1080,37 @@ public class PolicyAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit1;
// } catch( ServletException eAudit2 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_CERT_POLICY,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_CERT_POLICY,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit2;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit2;
}
}
/**
* Modify policy instance
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_CERT_POLICY used when
* configuring cert policy constraints and extensions
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
*/
public void modifyPolicyInstance(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -1179,7 +1182,7 @@ public class PolicyAdminServlet extends AdminServlet {
sendResponse(ERROR, INVALID_POLICY_IMPL_ID, null, resp);
return;
}
- // XXX
+ // XXX
for (Enumeration n = req.getParameterNames(); n.hasMoreElements();) {
String p = (String) n.nextElement();
String l = (String) req.getParameter(p);
@@ -1189,15 +1192,10 @@ public class PolicyAdminServlet extends AdminServlet {
}
/*
- for(Enumeration e = v.elements(); e.hasMoreElements(); )
- {
- String nv = (String)e.nextElement();
- int index = nv.indexOf("=");
- String key = nv.substring(0, index);
- val = req.getParameter(key);
- if (val != null)
- ht.put(key, val);
- }
+ * for(Enumeration e = v.elements(); e.hasMoreElements(); ) { String
+ * nv = (String)e.nextElement(); int index = nv.indexOf("="); String
+ * key = nv.substring(0, index); val = req.getParameter(key); if
+ * (val != null) ht.put(key, val); }
*/
try {
@@ -1238,18 +1236,17 @@ public class PolicyAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit1;
// } catch( ServletException eAudit2 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_CERT_POLICY,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_CERT_POLICY,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit2;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit2;
}
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/admin/ProfileAdminServlet.java b/pki/base/common/src/com/netscape/cms/servlet/admin/ProfileAdminServlet.java
index 9c83a30c..02eafb28 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/admin/ProfileAdminServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/admin/ProfileAdminServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.admin;
-
import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
@@ -53,14 +52,12 @@ import com.netscape.certsrv.registry.IPluginInfo;
import com.netscape.certsrv.registry.IPluginRegistry;
import com.netscape.cms.profile.common.ProfilePolicy;
-
/**
* This class is an administration servlet for policy management.
- *
- * Each service (CA, KRA, RA) should be responsible
- * for registering an instance of this with the remote
- * administration subsystem.
- *
+ *
+ * Each service (CA, KRA, RA) should be responsible for registering an instance
+ * of this with the remote administration subsystem.
+ *
* @version $Revision$, $Date$
*/
public class ProfileAdminServlet extends AdminServlet {
@@ -72,8 +69,8 @@ public class ProfileAdminServlet extends AdminServlet {
public final static String PROP_AUTHORITY = "authority";
private final static String INFO = "ProfileAdminServlet";
- private final static String PW_PASSWORD_CACHE_ADD =
- "PASSWORD_CACHE_ADD";
+ private final static String PW_PASSWORD_CACHE_ADD =
+ "PASSWORD_CACHE_ADD";
public final static String PROP_PREDICATE = "predicate";
private IAuthority mAuthority = null;
@@ -97,7 +94,7 @@ public class ProfileAdminServlet extends AdminServlet {
public static String BAD_CONFIGURATION_VAL = "Invalid configuration value.";
private final static String LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE =
- "LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE_3";
+ "LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE_3";
/**
* Constructs administration servlet.
@@ -130,8 +127,8 @@ public class ProfileAdminServlet extends AdminServlet {
* Serves HTTP admin request.
*/
public void service(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
super.service(req, resp);
super.authenticate(req);
@@ -139,7 +136,7 @@ public class ProfileAdminServlet extends AdminServlet {
AUTHZ_RES_NAME = "certServer.profile.configuration";
String scope = req.getParameter(Constants.OP_SCOPE);
- CMS.debug("ProfileAdminServlet: service scope: " + scope);
+ CMS.debug("ProfileAdminServlet: service scope: " + scope);
if (scope.equals(ScopeDef.SC_PROFILE_RULES)) {
processProfileRuleMgmt(req, resp);
} else if (scope.equals(ScopeDef.SC_PROFILE_POLICIES)) {
@@ -162,33 +159,33 @@ public class ProfileAdminServlet extends AdminServlet {
sendResponse(ERROR, INVALID_POLICY_SCOPE, null, resp);
}
- private boolean readAuthorize(HttpServletRequest req,
- HttpServletResponse resp) throws IOException {
+ private boolean readAuthorize(HttpServletRequest req,
+ HttpServletResponse resp) throws IOException {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return false;
}
return true;
}
- private boolean modifyAuthorize(HttpServletRequest req,
- HttpServletResponse resp) throws IOException {
+ private boolean modifyAuthorize(HttpServletRequest req,
+ HttpServletResponse resp) throws IOException {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return false;
}
return true;
}
public void processProfilePolicy(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
// Get operation type
String op = req.getParameter(Constants.OP_TYPE);
@@ -208,8 +205,8 @@ public class ProfileAdminServlet extends AdminServlet {
}
public void processProfileInput(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
// Get operation type
String op = req.getParameter(Constants.OP_TYPE);
String scope = super.getParameter(req, Constants.OP_SCOPE);
@@ -230,8 +227,8 @@ public class ProfileAdminServlet extends AdminServlet {
}
public void processProfileOutput(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
// Get operation type
String op = req.getParameter(Constants.OP_TYPE);
String scope = super.getParameter(req, Constants.OP_SCOPE);
@@ -252,8 +249,8 @@ public class ProfileAdminServlet extends AdminServlet {
}
public void processProfileInputConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
// Get operation type
String op = req.getParameter(Constants.OP_TYPE);
@@ -269,8 +266,8 @@ public class ProfileAdminServlet extends AdminServlet {
}
public void processProfileOutputConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
// Get operation type
String op = req.getParameter(Constants.OP_TYPE);
@@ -286,8 +283,8 @@ public class ProfileAdminServlet extends AdminServlet {
}
public void processPolicyDefaultConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
// Get operation type
String op = req.getParameter(Constants.OP_TYPE);
@@ -307,8 +304,8 @@ public class ProfileAdminServlet extends AdminServlet {
}
public void processPolicyConstraintConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
// Get operation type
String op = req.getParameter(Constants.OP_TYPE);
@@ -332,8 +329,8 @@ public class ProfileAdminServlet extends AdminServlet {
* Process Policy Implementation Management.
*/
public void processPolicyImplMgmt(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
// Get operation type
String op = req.getParameter(Constants.OP_TYPE);
@@ -343,12 +340,12 @@ public class ProfileAdminServlet extends AdminServlet {
listProfileImpls(req, resp);
} else
sendResponse(ERROR, INVALID_POLICY_IMPL_OP,
- null, resp);
+ null, resp);
}
public void processProfileRuleMgmt(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
// Get operation type
String op = req.getParameter(Constants.OP_TYPE);
@@ -374,15 +371,15 @@ public class ProfileAdminServlet extends AdminServlet {
modifyProfileInstance(req, resp);
} else
sendResponse(ERROR, INVALID_POLICY_IMPL_OP,
- null, resp);
+ null, resp);
}
/**
* Lists all registered profile impementations
*/
public void listProfileImpls(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
Enumeration<String> impls = mRegistry.getIds("profile");
NameValuePairs nvp = new NameValuePairs();
@@ -391,29 +388,30 @@ public class ProfileAdminServlet extends AdminServlet {
String id = (String) impls.nextElement();
IPluginInfo info = mRegistry.getPluginInfo("profile", id);
- nvp.add(id, info.getClassName() + "," +
- info.getDescription(getLocale(req)));
- }
+ nvp.add(id, info.getClassName() + "," +
+ info.getDescription(getLocale(req)));
+ }
sendResponse(SUCCESS, null, nvp, resp);
}
/**
* Add policy profile
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE used when
* configuring cert profile (general settings and cert profile; obsoletes
* extensions and constraints policies)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
*/
public void addProfilePolicy(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -451,10 +449,10 @@ public class ProfileAdminServlet extends AdminServlet {
if (mProfileSub.isProfileEnable(profileId)) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),
- "CMS_PROFILE_CREATE_POLICY_FAILED",
- "Profile is currently enabled"),
- null, resp);
+ CMS.getUserMessage(getLocale(req),
+ "CMS_PROFILE_CREATE_POLICY_FAILED",
+ "Profile is currently enabled"),
+ null, resp);
return;
}
@@ -466,27 +464,27 @@ public class ProfileAdminServlet extends AdminServlet {
try {
if (!isValidId(setId)) {
- sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),
- "CMS_PROFILE_CREATE_POLICY_FAILED",
- "Invalid set id " + setId),
- null, resp);
- return;
+ sendResponse(ERROR,
+ CMS.getUserMessage(getLocale(req),
+ "CMS_PROFILE_CREATE_POLICY_FAILED",
+ "Invalid set id " + setId),
+ null, resp);
+ return;
}
if (!isValidId(pId)) {
- sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req),
- "CMS_PROFILE_CREATE_POLICY_FAILED",
- "Invalid policy id " + pId),
- null, resp);
- return;
+ sendResponse(ERROR,
+ CMS.getUserMessage(getLocale(req),
+ "CMS_PROFILE_CREATE_POLICY_FAILED",
+ "Invalid policy id " + pId),
+ null, resp);
+ return;
}
policy = profile.createProfilePolicy(setId, pId,
defImpl, conImpl);
} catch (EBaseException e1) {
// error
CMS.debug("ProfileAdminServlet: addProfilePolicy " +
- e1.toString());
+ e1.toString());
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -498,9 +496,9 @@ public class ProfileAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_PROFILE_CREATE_POLICY_FAILED",
- e1.toString()),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_PROFILE_CREATE_POLICY_FAILED",
+ e1.toString()),
+ null, resp);
return;
}
NameValuePairs nvp = new NameValuePairs();
@@ -528,37 +526,38 @@ public class ProfileAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit1;
// } catch( ServletException eAudit2 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit2;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit2;
}
}
/**
* Add profile input
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE used when
* configuring cert profile (general settings and cert profile; obsoletes
* extensions and constraints policies)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
*/
public void addProfileInput(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -594,11 +593,11 @@ public class ProfileAdminServlet extends AdminServlet {
IProfileInput input = null;
@SuppressWarnings("unchecked")
- Enumeration<String> names = req.getParameterNames();
+ Enumeration<String> names = req.getParameterNames();
NameValuePairs nvps = new NameValuePairs();
while (names.hasMoreElements()) {
- String name = names.nextElement();
+ String name = names.nextElement();
if (name.equals("OP_SCOPE"))
continue;
@@ -623,9 +622,9 @@ public class ProfileAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_PROFILE_CREATE_INPUT_FAILED",
- e1.toString()),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_PROFILE_CREATE_INPUT_FAILED",
+ e1.toString()),
+ null, resp);
return;
}
@@ -655,37 +654,38 @@ public class ProfileAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit1;
// } catch( ServletException eAudit2 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit2;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit2;
}
}
/**
* Add profile output
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE used when
* configuring cert profile (general settings and cert profile; obsoletes
* extensions and constraints policies)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
*/
public void addProfileOutput(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -721,11 +721,11 @@ public class ProfileAdminServlet extends AdminServlet {
IProfileOutput output = null;
@SuppressWarnings("unchecked")
- Enumeration<String> names = req.getParameterNames();
+ Enumeration<String> names = req.getParameterNames();
NameValuePairs nvps = new NameValuePairs();
while (names.hasMoreElements()) {
- String name = names.nextElement();
+ String name = names.nextElement();
if (name.equals("OP_SCOPE"))
continue;
@@ -751,9 +751,9 @@ public class ProfileAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_PROFILE_CREATE_OUTPUT_FAILED",
- e1.toString()),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_PROFILE_CREATE_OUTPUT_FAILED",
+ e1.toString()),
+ null, resp);
return;
}
@@ -783,37 +783,38 @@ public class ProfileAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit1;
// } catch( ServletException eAudit2 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit2;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit2;
}
}
/**
* Delete policy profile
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE used when
* configuring cert profile (general settings and cert profile; obsoletes
* extensions and constraints policies)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
*/
public void deleteProfilePolicy(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -823,10 +824,10 @@ public class ProfileAdminServlet extends AdminServlet {
String profileId = "";
String policyId = "";
@SuppressWarnings("unchecked")
- Enumeration<String> names = req.getParameterNames();
+ Enumeration<String> names = req.getParameterNames();
while (names.hasMoreElements()) {
- String name = names.nextElement();
+ String name = names.nextElement();
if (name.equals("OP_SCOPE"))
continue;
@@ -904,37 +905,38 @@ public class ProfileAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit1;
// } catch( ServletException eAudit2 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit2;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit2;
}
}
/**
* Delete profile input
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE used when
* configuring cert profile (general settings and cert profile; obsoletes
* extensions and constraints policies)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
*/
public void deleteProfileInput(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -944,7 +946,7 @@ public class ProfileAdminServlet extends AdminServlet {
String profileId = "";
String inputId = "";
@SuppressWarnings("unchecked")
- Enumeration<String> names = req.getParameterNames();
+ Enumeration<String> names = req.getParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
@@ -1022,37 +1024,38 @@ public class ProfileAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit1;
// } catch( ServletException eAudit2 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit2;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit2;
}
}
/**
* Delete profile output
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE used when
* configuring cert profile (general settings and cert profile; obsoletes
* extensions and constraints policies)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
*/
public void deleteProfileOutput(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -1062,7 +1065,7 @@ public class ProfileAdminServlet extends AdminServlet {
String profileId = "";
String outputId = "";
@SuppressWarnings("unchecked")
- Enumeration<String> names = req.getParameterNames();
+ Enumeration<String> names = req.getParameterNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
@@ -1140,37 +1143,38 @@ public class ProfileAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit1;
// } catch( ServletException eAudit2 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit2;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit2;
}
}
/**
* Add default policy profile configuration
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE used when
* configuring cert profile (general settings and cert profile; obsoletes
* extensions and constraints policies)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
*/
public void addPolicyDefaultConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -1201,7 +1205,7 @@ public class ProfileAdminServlet extends AdminServlet {
sendResponse(ERROR, null, null, resp);
return;
- }
+ }
StringTokenizer ss = new StringTokenizer(policyId, ":");
String setId = ss.nextToken();
@@ -1210,9 +1214,9 @@ public class ProfileAdminServlet extends AdminServlet {
IProfilePolicy policy = profile.getProfilePolicy(setId, pId);
IPolicyDefault def = policy.getDefault();
IConfigStore defConfig = def.getConfigStore();
-
+
@SuppressWarnings("unchecked")
- Enumeration<String> names = req.getParameterNames();
+ Enumeration<String> names = req.getParameterNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
@@ -1224,18 +1228,20 @@ public class ProfileAdminServlet extends AdminServlet {
if (name.equals("RS_ID"))
continue;
try {
- def.setConfig(name,req.getParameter(name));
+ def.setConfig(name, req.getParameter(name));
} catch (EPropertyException e) {
- CMS.debug("ProfileAdminServlet: modifyPolicyDefConfig setConfig exception.");
- try {
- profile.deleteProfilePolicy(setId, pId);
- } catch (Exception e11) {}
- sendResponse(ERROR,BAD_CONFIGURATION_VAL,null,resp);
- return;
+ CMS.debug("ProfileAdminServlet: modifyPolicyDefConfig setConfig exception.");
+ try {
+ profile.deleteProfilePolicy(setId, pId);
+ } catch (Exception e11) {
+ }
+ sendResponse(ERROR, BAD_CONFIGURATION_VAL, null, resp);
+ return;
}
- // defConfig.putString("params." + name, req.getParameter(name));
+ // defConfig.putString("params." + name,
+ // req.getParameter(name));
}
try {
profile.getConfigStore().commit(false);
@@ -1277,37 +1283,38 @@ public class ProfileAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit1;
// } catch( ServletException eAudit2 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit2;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit2;
}
}
/**
* Add policy constraints profile configuration
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE used when
* configuring cert profile (general settings and cert profile; obsoletes
* extensions and constraints policies)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
*/
public void addPolicyConstraintConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -1338,7 +1345,7 @@ public class ProfileAdminServlet extends AdminServlet {
sendResponse(ERROR, null, null, resp);
return;
- }
+ }
StringTokenizer ss = new StringTokenizer(policyId, ":");
String setId = ss.nextToken();
@@ -1349,10 +1356,10 @@ public class ProfileAdminServlet extends AdminServlet {
IConfigStore conConfig = con.getConfigStore();
@SuppressWarnings("unchecked")
- Enumeration<String> names = req.getParameterNames();
+ Enumeration<String> names = req.getParameterNames();
while (names.hasMoreElements()) {
- String name = names.nextElement();
+ String name = names.nextElement();
if (name.equals("OP_SCOPE"))
continue;
@@ -1362,18 +1369,20 @@ public class ProfileAdminServlet extends AdminServlet {
continue;
try {
- con.setConfig(name,req.getParameter(name));
+ con.setConfig(name, req.getParameter(name));
} catch (EPropertyException e) {
- CMS.debug("ProfileAdminServlet: addPolicyConstraintsConfig setConfig exception.");
- try {
- profile.deleteProfilePolicy(setId, pId);
- } catch (Exception e11) {}
- sendResponse(ERROR,BAD_CONFIGURATION_VAL,null,resp);
- return;
+ CMS.debug("ProfileAdminServlet: addPolicyConstraintsConfig setConfig exception.");
+ try {
+ profile.deleteProfilePolicy(setId, pId);
+ } catch (Exception e11) {
+ }
+ sendResponse(ERROR, BAD_CONFIGURATION_VAL, null, resp);
+ return;
}
- // conConfig.putString("params." + name, req.getParameter(name));
+ // conConfig.putString("params." + name,
+ // req.getParameter(name));
}
try {
profile.getConfigStore().commit(false);
@@ -1416,37 +1425,38 @@ public class ProfileAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit1;
// } catch( ServletException eAudit2 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit2;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit2;
}
}
/**
* Modify default policy profile configuration
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE used when
* configuring cert profile (general settings and cert profile; obsoletes
* extensions and constraints policies)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
*/
public void modifyPolicyDefaultConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -1477,7 +1487,7 @@ public class ProfileAdminServlet extends AdminServlet {
sendResponse(ERROR, null, null, resp);
return;
- }
+ }
StringTokenizer ss = new StringTokenizer(policyId, ":");
String setId = ss.nextToken();
@@ -1485,9 +1495,9 @@ public class ProfileAdminServlet extends AdminServlet {
IProfilePolicy policy = profile.getProfilePolicy(setId, pId);
IPolicyDefault def = policy.getDefault();
IConfigStore defConfig = def.getConfigStore();
-
+
@SuppressWarnings("unchecked")
- Enumeration<String> names = req.getParameterNames();
+ Enumeration<String> names = req.getParameterNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
@@ -1499,15 +1509,16 @@ public class ProfileAdminServlet extends AdminServlet {
if (name.equals("RS_ID"))
continue;
try {
- def.setConfig(name,req.getParameter(name));
+ def.setConfig(name, req.getParameter(name));
} catch (EPropertyException e) {
- CMS.debug("ProfileAdminServlet: modifyPolicyDefConfig setConfig exception.");
- sendResponse(ERROR,BAD_CONFIGURATION_VAL,null,resp);
- return;
+ CMS.debug("ProfileAdminServlet: modifyPolicyDefConfig setConfig exception.");
+ sendResponse(ERROR, BAD_CONFIGURATION_VAL, null, resp);
+ return;
}
- // defConfig.putString("params." + name, req.getParameter(name));
+ // defConfig.putString("params." + name,
+ // req.getParameter(name));
}
try {
profile.getConfigStore().commit(false);
@@ -1549,37 +1560,38 @@ public class ProfileAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit1;
// } catch( ServletException eAudit2 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit2;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit2;
}
}
/**
* Modify profile input configuration
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE used when
* configuring cert profile (general settings and cert profile; obsoletes
* extensions and constraints policies)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
*/
public void modifyInputConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -1616,7 +1628,7 @@ public class ProfileAdminServlet extends AdminServlet {
IConfigStore inputConfig = input.getConfigStore();
@SuppressWarnings("unchecked")
- Enumeration<String> names = req.getParameterNames();
+ Enumeration<String> names = req.getParameterNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
@@ -1669,37 +1681,38 @@ public class ProfileAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit1;
// } catch( ServletException eAudit2 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit2;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit2;
}
}
/**
* Modify profile output configuration
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE used when
* configuring cert profile (general settings and cert profile; obsoletes
* extensions and constraints policies)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
*/
public void modifyOutputConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -1736,7 +1749,7 @@ public class ProfileAdminServlet extends AdminServlet {
IConfigStore outputConfig = output.getConfigStore();
@SuppressWarnings("unchecked")
- Enumeration<String> names = req.getParameterNames();
+ Enumeration<String> names = req.getParameterNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
@@ -1748,7 +1761,7 @@ public class ProfileAdminServlet extends AdminServlet {
if (name.equals("RS_ID"))
continue;
outputConfig.putString("params." + name,
- req.getParameter(name));
+ req.getParameter(name));
}
try {
profile.getConfigStore().commit(false);
@@ -1790,37 +1803,38 @@ public class ProfileAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit1;
// } catch( ServletException eAudit2 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit2;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit2;
}
}
/**
* Modify policy constraints profile configuration
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE used when
* configuring cert profile (general settings and cert profile; obsoletes
* extensions and constraints policies)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
*/
public void modifyPolicyConstraintConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -1851,7 +1865,7 @@ public class ProfileAdminServlet extends AdminServlet {
sendResponse(ERROR, null, null, resp);
return;
- }
+ }
StringTokenizer ss = new StringTokenizer(policyId, ":");
String setId = ss.nextToken();
@@ -1861,9 +1875,9 @@ public class ProfileAdminServlet extends AdminServlet {
IConfigStore conConfig = con.getConfigStore();
@SuppressWarnings("unchecked")
- Enumeration<String> names = req.getParameterNames();
+ Enumeration<String> names = req.getParameterNames();
- CMS.debug("ProfileAdminServlet: modifyPolicyConstraintConfig policy " + policy + " con " + con);
+ CMS.debug("ProfileAdminServlet: modifyPolicyConstraintConfig policy " + policy + " con " + con);
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
@@ -1874,17 +1888,19 @@ public class ProfileAdminServlet extends AdminServlet {
if (name.equals("RS_ID"))
continue;
- // CMS.debug("ProfileAdminServlet: modifyPolicyConstraintConfig name" + name + " val " + req.getParameter(name));
+ // CMS.debug("ProfileAdminServlet: modifyPolicyConstraintConfig name"
+ // + name + " val " + req.getParameter(name));
try {
- con.setConfig(name,req.getParameter(name));
+ con.setConfig(name, req.getParameter(name));
} catch (EPropertyException e) {
- CMS.debug("ProfileAdminServlet: modifyPolicyConstraintsConfig setConfig exception.");
- sendResponse(ERROR,BAD_CONFIGURATION_VAL,null,resp);
- return;
+ CMS.debug("ProfileAdminServlet: modifyPolicyConstraintsConfig setConfig exception.");
+ sendResponse(ERROR, BAD_CONFIGURATION_VAL, null, resp);
+ return;
}
- //conConfig.putString("params." + name, req.getParameter(name));
+ // conConfig.putString("params." + name,
+ // req.getParameter(name));
}
try {
profile.getConfigStore().commit(false);
@@ -1927,23 +1943,23 @@ public class ProfileAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit1;
// } catch( ServletException eAudit2 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit2;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit2;
}
}
public void getPolicyDefaultConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
String id = req.getParameter(Constants.RS_ID);
StringTokenizer st = new StringTokenizer(id, ";");
@@ -1955,9 +1971,9 @@ public class ProfileAdminServlet extends AdminServlet {
try {
profile = mProfileSub.getProfile(profileId);
} catch (EBaseException e1) {
- CMS.debug( "ProfileAdminServlet::getPolicyDefaultConfig() - " +
- "profile is null!" );
- throw new ServletException( e1.toString() );
+ CMS.debug("ProfileAdminServlet::getPolicyDefaultConfig() - " +
+ "profile is null!");
+ throw new ServletException(e1.toString());
}
IProfilePolicy policy = null;
@@ -1987,15 +2003,15 @@ public class ProfileAdminServlet extends AdminServlet {
}
public void getPolicyConstraintConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
String id = req.getParameter(Constants.RS_ID);
String constraintsList = req.getParameter(Constants.PR_CONSTRAINTS_LIST);
// this one gets called when one of the elements in the default list get
// selected, then it returns the list of supported constraintsPolicy
if (constraintsList != null) {
-
+
}
StringTokenizer st = new StringTokenizer(id, ";");
@@ -2007,9 +2023,9 @@ public class ProfileAdminServlet extends AdminServlet {
try {
profile = mProfileSub.getProfile(profileId);
} catch (EBaseException e1) {
- CMS.debug( "ProfileAdminServlet::getPolicyConstraintConfig() - " +
- "profile is null!" );
- throw new ServletException( e1.toString() );
+ CMS.debug("ProfileAdminServlet::getPolicyConstraintConfig() - " +
+ "profile is null!");
+ throw new ServletException(e1.toString());
}
StringTokenizer ss = new StringTokenizer(policyId, ":");
@@ -2035,8 +2051,8 @@ public class ProfileAdminServlet extends AdminServlet {
}
public void getProfilePolicy(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
String id = req.getParameter(Constants.RS_ID);
// only allow profile retrival if it is disabled
@@ -2046,9 +2062,9 @@ public class ProfileAdminServlet extends AdminServlet {
try {
profile = mProfileSub.getProfile(id);
} catch (EBaseException e1) {
- CMS.debug( "ProfileAdminServlet::getProfilePolicy() - " +
- "profile is null!" );
- throw new ServletException( e1.toString() );
+ CMS.debug("ProfileAdminServlet::getProfilePolicy() - " +
+ "profile is null!");
+ throw new ServletException(e1.toString());
}
NameValuePairs nvp = new NameValuePairs();
@@ -2070,9 +2086,9 @@ public class ProfileAdminServlet extends AdminServlet {
IPolicyConstraint con = policy.getConstraint();
IConfigStore conConfig = con.getConfigStore();
- nvp.add(setId + ":" + policy.getId(),
- def.getName(getLocale(req)) + ";" +
- con.getName(getLocale(req)));
+ nvp.add(setId + ":" + policy.getId(),
+ def.getName(getLocale(req)) + ";" +
+ con.getName(getLocale(req)));
}
}
@@ -2080,17 +2096,17 @@ public class ProfileAdminServlet extends AdminServlet {
}
public void getProfileOutput(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
String id = req.getParameter(Constants.RS_ID);
IProfile profile = null;
try {
profile = mProfileSub.getProfile(id);
} catch (EBaseException e1) {
- CMS.debug( "ProfileAdminServlet::getProfileOutput() - " +
- "profile is null!" );
- throw new ServletException( e1.toString() );
+ CMS.debug("ProfileAdminServlet::getProfileOutput() - " +
+ "profile is null!");
+ throw new ServletException(e1.toString());
}
NameValuePairs nvp = new NameValuePairs();
@@ -2107,17 +2123,17 @@ public class ProfileAdminServlet extends AdminServlet {
}
public void getProfileInput(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
String id = req.getParameter(Constants.RS_ID);
IProfile profile = null;
try {
profile = mProfileSub.getProfile(id);
} catch (EBaseException e1) {
- CMS.debug( "ProfileAdminServlet::getProfileInput() - " +
- "profile is null!" );
- throw new ServletException( e1.toString() );
+ CMS.debug("ProfileAdminServlet::getProfileInput() - " +
+ "profile is null!");
+ throw new ServletException(e1.toString());
}
NameValuePairs nvp = new NameValuePairs();
@@ -2134,9 +2150,9 @@ public class ProfileAdminServlet extends AdminServlet {
}
public void getInputConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
-
+ HttpServletResponse resp)
+ throws ServletException, IOException {
+
String id = req.getParameter(Constants.RS_ID);
StringTokenizer st = new StringTokenizer(id, ";");
String profileId = st.nextToken();
@@ -2146,9 +2162,9 @@ public class ProfileAdminServlet extends AdminServlet {
try {
profile = mProfileSub.getProfile(profileId);
} catch (EBaseException e1) {
- CMS.debug( "ProfileAdminServlet::getInputConfig() - " +
- "profile is null!" );
- throw new ServletException( e1.toString() );
+ CMS.debug("ProfileAdminServlet::getInputConfig() - " +
+ "profile is null!");
+ throw new ServletException(e1.toString());
}
IProfileInput profileInput = null;
@@ -2160,14 +2176,14 @@ public class ProfileAdminServlet extends AdminServlet {
while (names.hasMoreElements()) {
String name = names.nextElement();
IDescriptor desc = profileInput.getConfigDescriptor(
- getLocale(req), name);
+ getLocale(req), name);
if (desc == null) {
nvp.add(name, ";" + ";" + profileInput.getConfig(name));
} else {
- nvp.add(name, desc.getSyntax() + ";" +
+ nvp.add(name, desc.getSyntax() + ";" +
getNonNull(desc.getConstraint()) + ";" +
desc.getDescription(getLocale(req)) + ";" +
- profileInput.getConfig(name));
+ profileInput.getConfig(name));
}
}
@@ -2175,8 +2191,8 @@ public class ProfileAdminServlet extends AdminServlet {
}
public void getOutputConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
String id = req.getParameter(Constants.RS_ID);
StringTokenizer st = new StringTokenizer(id, ";");
@@ -2187,9 +2203,9 @@ public class ProfileAdminServlet extends AdminServlet {
try {
profile = mProfileSub.getProfile(profileId);
} catch (EBaseException e1) {
- CMS.debug( "ProfileAdminServlet::getOutputConfig() - " +
- "profile is null!" );
- throw new ServletException( e1.toString() );
+ CMS.debug("ProfileAdminServlet::getOutputConfig() - " +
+ "profile is null!");
+ throw new ServletException(e1.toString());
}
IProfileOutput profileOutput = null;
@@ -2201,14 +2217,14 @@ public class ProfileAdminServlet extends AdminServlet {
while (names.hasMoreElements()) {
String name = names.nextElement();
IDescriptor desc = profileOutput.getConfigDescriptor(
- getLocale(req), name);
+ getLocale(req), name);
if (desc == null) {
nvp.add(name, ";" + ";" + profileOutput.getConfig(name));
} else {
- nvp.add(name, desc.getSyntax() + ";" +
+ nvp.add(name, desc.getSyntax() + ";" +
getNonNull(desc.getConstraint()) + ";" +
desc.getDescription(getLocale(req)) + ";" +
- profileOutput.getConfig(name));
+ profileOutput.getConfig(name));
}
}
@@ -2216,14 +2232,14 @@ public class ProfileAdminServlet extends AdminServlet {
}
public void listProfileInstances(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
NameValuePairs nvp = new NameValuePairs();
Enumeration<String> e = mProfileSub.getProfileIds();
while (e.hasMoreElements()) {
- String profileId = e.nextElement();
+ String profileId = e.nextElement();
IProfile profile = null;
try {
@@ -2231,7 +2247,7 @@ public class ProfileAdminServlet extends AdminServlet {
} catch (EBaseException e1) {
// error
}
-
+
String status = null;
if (mProfileSub.isProfileEnable(profileId)) {
@@ -2247,8 +2263,8 @@ public class ProfileAdminServlet extends AdminServlet {
}
public void getProfileInstanceConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
String id = req.getParameter(Constants.RS_ID);
IProfile profile = null;
@@ -2256,9 +2272,9 @@ public class ProfileAdminServlet extends AdminServlet {
try {
profile = mProfileSub.getProfile(id);
} catch (EBaseException e1) {
- CMS.debug( "ProfileAdminServlet::getProfileInstanceConfig() - " +
- "profile is null!" );
- throw new ServletException( e1.toString() );
+ CMS.debug("ProfileAdminServlet::getProfileInstanceConfig() - " +
+ "profile is null!");
+ throw new ServletException(e1.toString());
}
NameValuePairs nvp = new NameValuePairs();
@@ -2285,20 +2301,21 @@ public class ProfileAdminServlet extends AdminServlet {
/**
* Delete profile instance
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE used when
* configuring cert profile (general settings and cert profile; obsoletes
* extensions and constraints policies)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
*/
public void deleteProfileInstance(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -2324,14 +2341,14 @@ public class ProfileAdminServlet extends AdminServlet {
String config = null;
- ISubsystem subsystem = CMS.getSubsystem("ca");
+ ISubsystem subsystem = CMS.getSubsystem("ca");
String subname = "ca";
- if (subsystem == null)
- subname = "ra";
+ if (subsystem == null)
+ subname = "ra";
try {
- config = CMS.getConfigStore().getString("instanceRoot") +
+ config = CMS.getConfigStore().getString("instanceRoot") +
"/profiles/" + subname + "/" + id + ".cfg";
} catch (EBaseException e) {
// store a message in the signed audit log file
@@ -2346,7 +2363,7 @@ public class ProfileAdminServlet extends AdminServlet {
sendResponse(ERROR, null, null, resp);
return;
}
-
+
try {
mProfileSub.deleteProfile(id, config);
} catch (EProfileException e) {
@@ -2386,22 +2403,22 @@ public class ProfileAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit1;
// } catch( ServletException eAudit2 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit2;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit2;
}
}
public void
- putUserPWPair(String combo) {
+ putUserPWPair(String combo) {
int semicolon;
semicolon = combo.indexOf(";");
@@ -2411,12 +2428,11 @@ public class ProfileAdminServlet extends AdminServlet {
CMS.putPasswordCache(user, pw);
}
- public boolean isValidId(String id)
- {
+ public boolean isValidId(String id) {
for (int i = 0; i < id.length(); i++) {
- char c = id.charAt(i);
- if (!Character.isLetterOrDigit(c))
- return false;
+ char c = id.charAt(i);
+ if (!Character.isLetterOrDigit(c))
+ return false;
}
return true;
}
@@ -2424,20 +2440,21 @@ public class ProfileAdminServlet extends AdminServlet {
/**
* Add profile instance
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE used when
* configuring cert profile (general settings and cert profile; obsoletes
* extensions and constraints policies)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
*/
public void addProfileInstance(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -2465,14 +2482,14 @@ public class ProfileAdminServlet extends AdminServlet {
IProfile p = null;
try {
- p = mProfileSub.getProfile(id);
+ p = mProfileSub.getProfile(id);
} catch (EProfileException e1) {
}
if (p != null) {
sendResponse(ERROR, POLICY_INST_ID_ALREADY_USED, null, resp);
return;
}
-
+
String impl = req.getParameter("impl");
String name = req.getParameter("name");
String desc = req.getParameter("desc");
@@ -2516,8 +2533,8 @@ public class ProfileAdminServlet extends AdminServlet {
profile = mProfileSub.createProfile(id, impl,
info.getClassName(),
config);
- profile.setName(getLocale(req), name);
- profile.setDescription(getLocale(req), name);
+ profile.setName(getLocale(req), name);
+ profile.setDescription(getLocale(req), name);
if (visible != null && visible.equals("true")) {
profile.setVisible(true);
} else {
@@ -2528,10 +2545,10 @@ public class ProfileAdminServlet extends AdminServlet {
mProfileSub.createProfileConfig(id, impl, config);
if (profile instanceof IProfileEx) {
- // populates profile specific plugins such as
- // policies, inputs and outputs
- ((IProfileEx)profile).populate();
- }
+ // populates profile specific plugins such as
+ // policies, inputs and outputs
+ ((IProfileEx) profile).populate();
+ }
} catch (Exception e) {
CMS.debug("ProfileAdminServlet: " + e.toString());
@@ -2571,37 +2588,38 @@ public class ProfileAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit1;
// } catch( ServletException eAudit2 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit2;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit2;
}
}
/**
* Modify profile instance
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE used when
* configuring cert profile (general settings and cert profile; obsoletes
* extensions and constraints policies)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
*/
public void modifyProfileInstance(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -2656,7 +2674,7 @@ public class ProfileAdminServlet extends AdminServlet {
audit(auditMessage);
try {
- profile.getConfigStore().commit(false);
+ profile.getConfigStore().commit(false);
} catch (Exception e) {
}
@@ -2674,25 +2692,24 @@ public class ProfileAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit1;
// } catch( ServletException eAudit2 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit2;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit2;
}
}
- protected String getNonNull(String s) {
- if (s == null)
- return "";
- return s;
- }
+ protected String getNonNull(String s) {
+ if (s == null)
+ return "";
+ return s;
+ }
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/admin/PublisherAdminServlet.java b/pki/base/common/src/com/netscape/cms/servlet/admin/PublisherAdminServlet.java
index 2842542e..b71bf4f1 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/admin/PublisherAdminServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/admin/PublisherAdminServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.admin;
-
import java.io.IOException;
import java.util.Enumeration;
import java.util.Locale;
@@ -68,12 +67,11 @@ import com.netscape.certsrv.publish.RulePlugin;
import com.netscape.certsrv.security.ICryptoSubsystem;
import com.netscape.cmsutil.password.IPasswordStore;
-
/**
- * A class representing an publishing servlet for the
- * Publishing subsystem. This servlet is responsible
- * to serve configuration requests for the Publishing subsystem.
- *
+ * A class representing an publishing servlet for the Publishing subsystem. This
+ * servlet is responsible to serve configuration requests for the Publishing
+ * subsystem.
+ *
* @version $Revision$, $Date$
*/
public class PublisherAdminServlet extends AdminServlet {
@@ -85,8 +83,8 @@ public class PublisherAdminServlet extends AdminServlet {
public final static String PROP_AUTHORITY = "authority";
private final static String INFO = "PublisherAdminServlet";
- private final static String PW_TAG_CA_LDAP_PUBLISHING =
- "CA LDAP Publishing";
+ private final static String PW_TAG_CA_LDAP_PUBLISHING =
+ "CA LDAP Publishing";
public final static String NOMAPPER = "<NONE>";
private IPublisherProcessor mProcessor = null;
private IAuthority mAuth = null;
@@ -110,22 +108,22 @@ public class PublisherAdminServlet extends AdminServlet {
if (mAuth != null)
if (mAuth instanceof ICertificateAuthority) {
mProcessor = ((ICertificateAuthority) mAuth).getPublisherProcessor();
- } else
- throw new ServletException(authority + " does not have publishing processor!");
+ } else
+ throw new ServletException(authority + " does not have publishing processor!");
}
/**
* Returns serlvet information.
*/
- public String getServletInfo() {
- return INFO;
+ public String getServletInfo() {
+ return INFO;
}
/**
* Serves HTTP admin request.
*/
public void service(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
+ throws ServletException, IOException {
super.service(req, resp);
CMS.debug("PublisherAdminServlet: in service");
@@ -133,14 +131,14 @@ public class PublisherAdminServlet extends AdminServlet {
String op = req.getParameter(Constants.OP_TYPE);
if (op == null) {
- //System.out.println("SRVLT_INVALID_PROTOCOL");
- sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_PROTOCOL"),
- null, resp);
+ // System.out.println("SRVLT_INVALID_PROTOCOL");
+ sendResponse(ERROR,
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_PROTOCOL"),
+ null, resp);
return;
}
- // for the rest
+ // for the rest
try {
super.authenticate(req);
@@ -149,8 +147,8 @@ public class PublisherAdminServlet extends AdminServlet {
return;
}
} catch (IOException e) {
- sendResponse(ERROR, CMS.getUserMessage(getLocale(req),"CMS_ADMIN_SRVLT_AUTHS_FAILED"),
- null, resp);
+ sendResponse(ERROR, CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHS_FAILED"),
+ null, resp);
return;
}
try {
@@ -160,8 +158,8 @@ public class PublisherAdminServlet extends AdminServlet {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_LDAP)) {
@@ -188,13 +186,13 @@ public class PublisherAdminServlet extends AdminServlet {
} else if (scope.equals(ScopeDef.SC_RULE_RULES)) {
getRuleInstConfig(req, resp);
return;
- }
+ }
} else if (op.equals(OpDef.OP_MODIFY)) {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_LDAP)) {
@@ -214,20 +212,20 @@ public class PublisherAdminServlet extends AdminServlet {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_LDAP)) {
testSetLDAPDest(req, resp);
return;
- }
+ }
} else if (op.equals(OpDef.OP_SEARCH)) {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_PUBLISHER_IMPLS)) {
@@ -242,7 +240,7 @@ public class PublisherAdminServlet extends AdminServlet {
} else if (scope.equals(ScopeDef.SC_MAPPER_RULES)) {
listMapperInsts(req, resp);
return;
- } else if (scope.equals(ScopeDef.SC_RULE_IMPLS)) {
+ } else if (scope.equals(ScopeDef.SC_RULE_IMPLS)) {
listRulePlugins(req, resp);
return;
} else if (scope.equals(ScopeDef.SC_RULE_RULES)) {
@@ -253,8 +251,8 @@ public class PublisherAdminServlet extends AdminServlet {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_PUBLISHER_IMPLS)) {
@@ -275,13 +273,13 @@ public class PublisherAdminServlet extends AdminServlet {
} else if (scope.equals(ScopeDef.SC_RULE_RULES)) {
addRuleInst(req, resp, scope);
return;
- }
+ }
} else if (op.equals(OpDef.OP_DELETE)) {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_PUBLISHER_IMPLS)) {
@@ -304,31 +302,31 @@ public class PublisherAdminServlet extends AdminServlet {
return;
}
} else {
- sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_TYPE", op),
- null, resp);
+ sendResponse(ERROR,
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_TYPE", op),
+ null, resp);
return;
}
} else {
- //System.out.println("SRVLT_INVALID_OP_SCOPE");
- sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
- null, resp);
+ // System.out.println("SRVLT_INVALID_OP_SCOPE");
+ sendResponse(ERROR,
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
+ null, resp);
return;
}
} catch (EBaseException e) {
sendResponse(ERROR, e.toString(getLocale(req)), null, resp);
return;
- }
- //System.out.println("SRVLT_FAIL_PERFORM 2");
+ }
+ // System.out.println("SRVLT_FAIL_PERFORM 2");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_PERFORM_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_PERFORM_FAILED"),
+ null, resp);
return;
}
private IExtendedPluginInfo getExtendedPluginInfo(IPublisherProcessor
- p) {
+ p) {
Enumeration mappers = p.getMapperInsts().keys();
Enumeration publishers = p.getPublisherInsts().keys();
@@ -337,11 +335,11 @@ public class PublisherAdminServlet extends AdminServlet {
for (; mappers.hasMoreElements();) {
String name = (String) mappers.nextElement();
- if (map.length()== 0) {
- map.append(name);
+ if (map.length() == 0) {
+ map.append(name);
} else {
- map.append(",");
- map.append(name);
+ map.append(",");
+ map.append(name);
}
}
StringBuffer publish = new StringBuffer();
@@ -374,17 +372,17 @@ public class PublisherAdminServlet extends AdminServlet {
// Should get the registered rules from processor
// instead of plugin
- // OLD: impl = getClassByNameAsExtendedPluginInfo(plugin.getClassPath());
+ // OLD: impl =
+ // getClassByNameAsExtendedPluginInfo(plugin.getClassPath());
impl = getExtendedPluginInfo(p_processor);
} else if (implType.equals(Constants.PR_EXT_PLUGIN_IMPLTYPE_MAPPER)) {
IPublisherProcessor p_processor = mProcessor;
Plugin plugin = (Plugin) p_processor.getMapperPlugins().get(implName
- );
+ );
impl = getClassByNameAsExtendedPluginInfo(plugin.getClassPath());
- } else if (implType.equals(Constants.PR_EXT_PLUGIN_IMPLTYPE_PUBLISHER)
- ) {
+ } else if (implType.equals(Constants.PR_EXT_PLUGIN_IMPLTYPE_PUBLISHER)) {
IPublisherProcessor p_processor = mProcessor;
Plugin plugin = (Plugin) p_processor.getPublisherPlugins().get(implName);
@@ -408,13 +406,13 @@ public class PublisherAdminServlet extends AdminServlet {
}
- /**
- * retrieve extended plugin info such as brief description, type info
- * from policy, authentication,
- * need to add: listener, mapper and publishing plugins
+ /**
+ * retrieve extended plugin info such as brief description, type info from
+ * policy, authentication, need to add: listener, mapper and publishing
+ * plugins
*/
private void getExtendedPluginInfo(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String id = req.getParameter(Constants.RS_ID);
@@ -423,14 +421,14 @@ public class PublisherAdminServlet extends AdminServlet {
String implType = id.substring(0, colon);
String implName = id.substring(colon + 1);
- NameValuePairs params =
- getExtendedPluginInfo(getLocale(req), implType, implName);
+ NameValuePairs params =
+ getExtendedPluginInfo(getLocale(req), implType, implName);
sendResponse(SUCCESS, null, params, resp);
}
-
+
private void getLDAPDest(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
IConfigStore config = mAuth.getConfigStore();
@@ -482,34 +480,34 @@ public class PublisherAdminServlet extends AdminServlet {
params.add(name, value);
}
}
- params.add(Constants.PR_PUBLISHING_ENABLE,
- publishcfg.getString(IPublisherProcessor.PROP_ENABLE, Constants.FALSE));
+ params.add(Constants.PR_PUBLISHING_ENABLE,
+ publishcfg.getString(IPublisherProcessor.PROP_ENABLE, Constants.FALSE));
params.add(Constants.PR_PUBLISHING_QUEUE_ENABLE,
- publishcfg.getString(Constants.PR_PUBLISHING_QUEUE_ENABLE, Constants.TRUE));
+ publishcfg.getString(Constants.PR_PUBLISHING_QUEUE_ENABLE, Constants.TRUE));
params.add(Constants.PR_PUBLISHING_QUEUE_THREADS,
- publishcfg.getString(Constants.PR_PUBLISHING_QUEUE_THREADS, "3"));
+ publishcfg.getString(Constants.PR_PUBLISHING_QUEUE_THREADS, "3"));
params.add(Constants.PR_PUBLISHING_QUEUE_PAGE_SIZE,
- publishcfg.getString(Constants.PR_PUBLISHING_QUEUE_PAGE_SIZE, "40"));
+ publishcfg.getString(Constants.PR_PUBLISHING_QUEUE_PAGE_SIZE, "40"));
params.add(Constants.PR_PUBLISHING_QUEUE_PRIORITY,
- publishcfg.getString(Constants.PR_PUBLISHING_QUEUE_PRIORITY, "0"));
+ publishcfg.getString(Constants.PR_PUBLISHING_QUEUE_PRIORITY, "0"));
params.add(Constants.PR_PUBLISHING_QUEUE_STATUS,
- publishcfg.getString(Constants.PR_PUBLISHING_QUEUE_STATUS, "200"));
- params.add(Constants.PR_ENABLE,
- ldapcfg.getString(IPublisherProcessor.PROP_ENABLE, Constants.FALSE));
+ publishcfg.getString(Constants.PR_PUBLISHING_QUEUE_STATUS, "200"));
+ params.add(Constants.PR_ENABLE,
+ ldapcfg.getString(IPublisherProcessor.PROP_ENABLE, Constants.FALSE));
sendResponse(SUCCESS, null, params, resp);
}
private void setLDAPDest(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException, EBaseException {
+ throws ServletException, IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
- //Save New Settings to the config file
+ // Save New Settings to the config file
IConfigStore config = mAuth.getConfigStore();
IConfigStore publishcfg = config.getSubStore(IPublisherProcessor.PROP_PUBLISH_SUBSTORE);
IConfigStore ldapcfg = publishcfg.getSubStore(IPublisherProcessor.PROP_LDAP_PUBLISH_SUBSTORE);
IConfigStore ldap = ldapcfg.getSubStore(IPublisherProcessor.PROP_LDAP);
- //set enable flag
+ // set enable flag
publishcfg.putString(IPublisherProcessor.PROP_ENABLE, req.getParameter(Constants.PR_PUBLISHING_ENABLE));
String enable = req.getParameter(Constants.PR_ENABLE);
@@ -518,8 +516,8 @@ public class PublisherAdminServlet extends AdminServlet {
// need to disable the ldap module here
mProcessor.setLdapConnModule(null);
}
-
- //set reset of the parameters
+
+ // set reset of the parameters
Enumeration e = req.getParameterNames();
String pwd = null;
@@ -536,9 +534,9 @@ public class PublisherAdminServlet extends AdminServlet {
continue;
if (name.equals(Constants.PR_PUBLISHING_ENABLE))
continue;
- // don't store password in the config file.
- if (name.equals(Constants.PR_BIND_PASSWD))
- continue; // old style password read from config.
+ // don't store password in the config file.
+ if (name.equals(Constants.PR_BIND_PASSWD))
+ continue; // old style password read from config.
if (name.equals(Constants.PR_DIRECTORY_MANAGER_PWD)) {
pwd = req.getParameter(name);
continue;
@@ -567,40 +565,36 @@ public class PublisherAdminServlet extends AdminServlet {
/* Don't enter the publishing pw into the config store */
ldap.putString(name, req.getParameter(name));
}
-
+
commit(true);
- /* Do a "PUT" of the new pw to the watchdog"
- ** do not remove - cfu
- if (pwd != null)
- CMS.putPasswordCache(PW_TAG_CA_LDAP_PUBLISHING, pwd);
+ /*
+ * Do a "PUT" of the new pw to the watchdog"* do not remove - cfu if
+ * (pwd != null) CMS.putPasswordCache(PW_TAG_CA_LDAP_PUBLISHING, pwd);
*/
// support publishing dirsrv with different pwd than internaldb
// update passwordFile
String prompt = ldap.getString(Constants.PR_BINDPWD_PROMPT);
IPasswordStore pwdStore = CMS.getPasswordStore();
- CMS.debug("PublisherAdminServlet: setLDAPDest(): saving password for "+ prompt + " to password file");
+ CMS.debug("PublisherAdminServlet: setLDAPDest(): saving password for " + prompt + " to password file");
pwdStore.putPassword(prompt, pwd);
pwdStore.commit();
CMS.debug("PublisherAdminServlet: setLDAPDest(): password saved");
-/* we'll shut down and restart the PublisherProcessor instead
- // what a hack to do this without require restart server
-// ILdapAuthInfo authInfo = CMS.getLdapAuthInfo();
- ILdapConnModule connModule = mProcessor.getLdapConnModule();
- ILdapAuthInfo authInfo = null;
- if (connModule != null) {
- authInfo = connModule.getLdapAuthInfo();
- }
-
-// authInfo.addPassword(PW_TAG_CA_LDAP_PUBLISHING, pwd);
- if (authInfo != null) {
- CMS.debug("PublisherAdminServlet: setLDAPDest(): adding password to memory cache");
- authInfo.addPassword(prompt, pwd);
- } else
- CMS.debug("PublisherAdminServlet: setLDAPDest(): authInfo null");
-*/
+ /*
+ * we'll shut down and restart the PublisherProcessor instead // what a
+ * hack to do this without require restart server // ILdapAuthInfo
+ * authInfo = CMS.getLdapAuthInfo(); ILdapConnModule connModule =
+ * mProcessor.getLdapConnModule(); ILdapAuthInfo authInfo = null; if
+ * (connModule != null) { authInfo = connModule.getLdapAuthInfo(); }
+ *
+ * // authInfo.addPassword(PW_TAG_CA_LDAP_PUBLISHING, pwd); if (authInfo
+ * != null) { CMS.debug(
+ * "PublisherAdminServlet: setLDAPDest(): adding password to memory cache"
+ * ); authInfo.addPassword(prompt, pwd); } else
+ * CMS.debug("PublisherAdminServlet: setLDAPDest(): authInfo null");
+ */
try {
CMS.debug("PublisherAdminServlet: setLDAPDest(): restarting publishing processor");
@@ -613,24 +607,24 @@ public class PublisherAdminServlet extends AdminServlet {
log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_FAIL_RES_LDAP", ex.toString()));
}
- //XXX See if we can dynamically in B2
+ // XXX See if we can dynamically in B2
sendResponse(SUCCESS, null, null, resp);
}
private void testSetLDAPDest(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException, EBaseException {
+ throws ServletException, IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
CMS.debug("PublisherAdmineServlet: in testSetLDAPDest");
- //Save New Settings to the config file
+ // Save New Settings to the config file
IConfigStore config = mAuth.getConfigStore();
IConfigStore publishcfg = config.getSubStore(IPublisherProcessor.PROP_PUBLISH_SUBSTORE);
IConfigStore ldapcfg = publishcfg.getSubStore(IPublisherProcessor.PROP_LDAP_PUBLISH_SUBSTORE);
IConfigStore ldap = ldapcfg.getSubStore(IPublisherProcessor.PROP_LDAP);
- //set enable flag
- publishcfg.putString(IPublisherProcessor.PROP_ENABLE,
- req.getParameter(Constants.PR_PUBLISHING_ENABLE));
+ // set enable flag
+ publishcfg.putString(IPublisherProcessor.PROP_ENABLE,
+ req.getParameter(Constants.PR_PUBLISHING_ENABLE));
String ldapPublish = req.getParameter(Constants.PR_ENABLE);
ldapcfg.putString(IPublisherProcessor.PROP_ENABLE, ldapPublish);
@@ -639,7 +633,7 @@ public class PublisherAdminServlet extends AdminServlet {
mProcessor.setLdapConnModule(null);
}
- //set reset of the parameters
+ // set reset of the parameters
Enumeration e = req.getParameterNames();
String pwd = null;
@@ -656,9 +650,9 @@ public class PublisherAdminServlet extends AdminServlet {
continue;
if (name.equals(Constants.PR_PUBLISHING_ENABLE))
continue;
- // don't store password in the config file.
- if (name.equals(Constants.PR_BIND_PASSWD))
- continue; // old style password read from config.
+ // don't store password in the config file.
+ if (name.equals(Constants.PR_BIND_PASSWD))
+ continue; // old style password read from config.
if (name.equals(Constants.PR_DIRECTORY_MANAGER_PWD)) {
pwd = req.getParameter(name);
continue;
@@ -687,25 +681,25 @@ public class PublisherAdminServlet extends AdminServlet {
/* Don't enter the publishing pw into the config store */
ldap.putString(name, req.getParameter(name));
}
-
+
// test before commit
if (publishcfg.getBoolean(IPublisherProcessor.PROP_ENABLE) &&
- ldapcfg.getBoolean(IPublisherProcessor.PROP_ENABLE)) {
- params.add("title",
- "You've attempted to configure CMS to connect" +
- " to a LDAP directory. The connection status is" +
- " as follows:\n \n");
+ ldapcfg.getBoolean(IPublisherProcessor.PROP_ENABLE)) {
+ params.add("title",
+ "You've attempted to configure CMS to connect" +
+ " to a LDAP directory. The connection status is" +
+ " as follows:\n \n");
LDAPConnection conn = null;
ILdapConnInfo connInfo =
- CMS.getLdapConnInfo(ldap.getSubStore(
- ILdapBoundConnFactory.PROP_LDAPCONNINFO));
- //LdapAuthInfo authInfo =
- //new LdapAuthInfo(ldap.getSubStore(
- // ILdapBoundConnFactory.PROP_LDAPAUTHINFO));
- String host = connInfo.getHost();
+ CMS.getLdapConnInfo(ldap.getSubStore(
+ ILdapBoundConnFactory.PROP_LDAPCONNINFO));
+ // LdapAuthInfo authInfo =
+ // new LdapAuthInfo(ldap.getSubStore(
+ // ILdapBoundConnFactory.PROP_LDAPAUTHINFO));
+ String host = connInfo.getHost();
int port = connInfo.getPort();
boolean secure = connInfo.getSecure();
- //int authType = authInfo.getAuthType();
+ // int authType = authInfo.getAuthType();
String authType = ldap.getSubStore(
ILdapBoundConnFactory.PROP_LDAPAUTHINFO).getString(ILdapAuthInfo.PROP_LDAPAUTHTYPE);
int version = connInfo.getVersion();
@@ -714,57 +708,57 @@ public class PublisherAdminServlet extends AdminServlet {
if (authType.equals(ILdapAuthInfo.LDAP_SSLCLIENTAUTH_STR)) {
try {
- //certNickName = authInfo.getParms()[0];
+ // certNickName = authInfo.getParms()[0];
certNickName = ldap.getSubStore(
ILdapBoundConnFactory.PROP_LDAPAUTHINFO).getString(ILdapAuthInfo.PROP_CLIENTCERTNICKNAME);
conn = new LDAPConnection(CMS.getLdapJssSSLSocketFactory(
certNickName));
CMS.debug("Publishing Test certNickName=" + certNickName);
- params.add(Constants.PR_CONN_INITED,
- "Create ssl LDAPConnection with certificate: " +
- certNickName + dashes(70 - 44 - certNickName.length()) + " Success");
+ params.add(Constants.PR_CONN_INITED,
+ "Create ssl LDAPConnection with certificate: " +
+ certNickName + dashes(70 - 44 - certNickName.length()) + " Success");
} catch (Exception ex) {
- params.add(Constants.PR_CONN_INIT_FAIL,
- "Create ssl LDAPConnection with certificate: " +
- certNickName + dashes(70 - 44 - certNickName.length()) + " failure\n" + " exception: " + ex);
- params.add(Constants.PR_SAVE_NOT,
- "\n \nIf the problem is not fixed then LDAP publishing will fail.\n" +
- "Do you want to save the configuration anyway?");
+ params.add(Constants.PR_CONN_INIT_FAIL,
+ "Create ssl LDAPConnection with certificate: " +
+ certNickName + dashes(70 - 44 - certNickName.length()) + " failure\n" + " exception: " + ex);
+ params.add(Constants.PR_SAVE_NOT,
+ "\n \nIf the problem is not fixed then LDAP publishing will fail.\n" +
+ "Do you want to save the configuration anyway?");
sendResponse(SUCCESS, null, params, resp);
return;
}
try {
conn.connect(host, port);
- params.add(Constants.PR_CONN_OK,
- "Connect to directory server " +
- host + " at port " + port +
- dashes(70 - 37 - host.length() - (Integer.valueOf(port)).toString().length()) + " Success");
- params.add(Constants.PR_AUTH_OK,
- "Authentication: SSL client authentication" +
- dashes(70 - 41) + " Success" +
- "\nBind to the directory as: " + certNickName +
- dashes(70 - 26 - certNickName.length()) + " Success");
+ params.add(Constants.PR_CONN_OK,
+ "Connect to directory server " +
+ host + " at port " + port +
+ dashes(70 - 37 - host.length() - (Integer.valueOf(port)).toString().length()) + " Success");
+ params.add(Constants.PR_AUTH_OK,
+ "Authentication: SSL client authentication" +
+ dashes(70 - 41) + " Success" +
+ "\nBind to the directory as: " + certNickName +
+ dashes(70 - 26 - certNickName.length()) + " Success");
} catch (LDAPException ex) {
if (ex.getLDAPResultCode() == LDAPException.UNAVAILABLE) {
// need to intercept this because message from LDAP is
// "DSA is unavailable" which confuses with DSA PKI.
- params.add(Constants.PR_CONN_FAIL,
- "Connect to directory server " +
- host + " at port " + port +
- dashes(70 - 37 - host.length() - (Integer.valueOf(port)).toString().length()) +
- " Failure\n" +
- " error: server unavailable");
+ params.add(Constants.PR_CONN_FAIL,
+ "Connect to directory server " +
+ host + " at port " + port +
+ dashes(70 - 37 - host.length() - (Integer.valueOf(port)).toString().length()) +
+ " Failure\n" +
+ " error: server unavailable");
} else {
- params.add(Constants.PR_CONN_FAIL,
- "Connect to directory server " +
- host + " at port " + port +
- dashes(70 - 37 - host.length() - (Integer.valueOf(port)).toString().length()) +
- " Failure");
+ params.add(Constants.PR_CONN_FAIL,
+ "Connect to directory server " +
+ host + " at port " + port +
+ dashes(70 - 37 - host.length() - (Integer.valueOf(port)).toString().length()) +
+ " Failure");
}
- params.add(Constants.PR_SAVE_NOT,
- "\n \nIf the problem is not fixed then " +
- "LDAP publishing will fail.\n" +
- "Do you want to save the configuration anyway?");
+ params.add(Constants.PR_SAVE_NOT,
+ "\n \nIf the problem is not fixed then " +
+ "LDAP publishing will fail.\n" +
+ "Do you want to save the configuration anyway?");
sendResponse(SUCCESS, null, params, resp);
return;
}
@@ -773,99 +767,97 @@ public class PublisherAdminServlet extends AdminServlet {
if (secure) {
conn = new LDAPConnection(
CMS.getLdapJssSSLSocketFactory());
- params.add(Constants.PR_CONN_INITED,
- "Create ssl LDAPConnection" +
- dashes(70 - 25) + " Success");
+ params.add(Constants.PR_CONN_INITED,
+ "Create ssl LDAPConnection" +
+ dashes(70 - 25) + " Success");
} else {
conn = new LDAPConnection();
- params.add(Constants.PR_CONN_INITED,
- "Create LDAPConnection" +
- dashes(70 - 21) + " Success");
+ params.add(Constants.PR_CONN_INITED,
+ "Create LDAPConnection" +
+ dashes(70 - 21) + " Success");
}
} catch (Exception ex) {
- params.add(Constants.PR_CONN_INIT_FAIL,
- "Create LDAPConnection" +
- dashes(70 - 21) + " Failure\n" +
- "exception: " + ex);
- params.add(Constants.PR_SAVE_NOT,
- "\n \nIf the problem is not fixed then " +
- "LDAP publishing will fail.\n" +
- "Do you want to save the configuration anyway?");
+ params.add(Constants.PR_CONN_INIT_FAIL,
+ "Create LDAPConnection" +
+ dashes(70 - 21) + " Failure\n" +
+ "exception: " + ex);
+ params.add(Constants.PR_SAVE_NOT,
+ "\n \nIf the problem is not fixed then " +
+ "LDAP publishing will fail.\n" +
+ "Do you want to save the configuration anyway?");
sendResponse(SUCCESS, null, params, resp);
return;
}
try {
conn.connect(host, port);
- params.add(Constants.PR_CONN_OK,
- "Connect to directory server " +
- host + " at port " + port +
- dashes(70 - 37 - host.length() - (Integer.valueOf(port)).toString().length()) + " Success");
+ params.add(Constants.PR_CONN_OK,
+ "Connect to directory server " +
+ host + " at port " + port +
+ dashes(70 - 37 - host.length() - (Integer.valueOf(port)).toString().length()) + " Success");
} catch (LDAPException ex) {
if (ex.getLDAPResultCode() == LDAPException.UNAVAILABLE) {
// need to intercept this because message from LDAP is
// "DSA is unavailable" which confuses with DSA PKI.
- params.add(Constants.PR_CONN_FAIL,
- "Connect to directory server " +
- host + " at port " + port +
- dashes(70 - 37 - host.length() - (Integer.valueOf(port)).toString().length()) + " Failure" +
- "\nerror: server unavailable");
+ params.add(Constants.PR_CONN_FAIL,
+ "Connect to directory server " +
+ host + " at port " + port +
+ dashes(70 - 37 - host.length() - (Integer.valueOf(port)).toString().length()) + " Failure" +
+ "\nerror: server unavailable");
} else {
- params.add(Constants.PR_CONN_FAIL,
- "Connect to directory server " +
- host + " at port " + port +
- dashes(70 - 37 - host.length() - (Integer.valueOf(port)).toString().length()) + " Failure" +
- "\nexception: " + ex);
+ params.add(Constants.PR_CONN_FAIL,
+ "Connect to directory server " +
+ host + " at port " + port +
+ dashes(70 - 37 - host.length() - (Integer.valueOf(port)).toString().length()) + " Failure" +
+ "\nexception: " + ex);
}
- params.add(Constants.PR_SAVE_NOT,
- "\n \nIf the problem is not fixed then " +
- "LDAP publishing will fail.\n" +
- "Do you want to save the configuration anyway?");
+ params.add(Constants.PR_SAVE_NOT,
+ "\n \nIf the problem is not fixed then " +
+ "LDAP publishing will fail.\n" +
+ "Do you want to save the configuration anyway?");
sendResponse(SUCCESS, null, params, resp);
return;
}
try {
- //bindAs = authInfo.getParms()[0];
+ // bindAs = authInfo.getParms()[0];
bindAs = ldap.getSubStore(
ILdapBoundConnFactory.PROP_LDAPAUTHINFO).getString(ILdapAuthInfo.PROP_BINDDN);
conn.authenticate(version, bindAs, pwd);
- params.add(Constants.PR_AUTH_OK,
- "Authentication: Basic authentication" +
- dashes(70 - 36) + " Success" +
- "\nBind to the directory as: " + bindAs +
- dashes(70 - 26 - bindAs.length()) + " Success");
+ params.add(Constants.PR_AUTH_OK,
+ "Authentication: Basic authentication" +
+ dashes(70 - 36) + " Success" +
+ "\nBind to the directory as: " + bindAs +
+ dashes(70 - 26 - bindAs.length()) + " Success");
} catch (LDAPException ex) {
- if (ex.getLDAPResultCode() ==
- LDAPException.NO_SUCH_OBJECT) {
- params.add(Constants.PR_AUTH_FAIL,
- "Authentication: Basic authentication" +
- dashes(70 - 36) + "Failure" +
- "\nBind to the directory as: " + bindAs +
- dashes(70 - 26 - bindAs.length()) +
- "Failure" + "\nThe object doesn't exist. " +
- "Please correct the value assigned in the" +
- " \"Directory manager DN\" field.");
- } else if (ex.getLDAPResultCode() ==
- LDAPException.INVALID_CREDENTIALS) {
- params.add(Constants.PR_AUTH_FAIL,
- "Authentication: Basic authentication" +
- dashes(70 - 36) + " Failure" +
- "\nBind to the directory as: " + bindAs +
- dashes(70 - 26 - bindAs.length()) +
- " Failure" + "\nInvalid password. " +
- "Please correct the value assigned in the" +
- " \"Password\" field.");
+ if (ex.getLDAPResultCode() == LDAPException.NO_SUCH_OBJECT) {
+ params.add(Constants.PR_AUTH_FAIL,
+ "Authentication: Basic authentication" +
+ dashes(70 - 36) + "Failure" +
+ "\nBind to the directory as: " + bindAs +
+ dashes(70 - 26 - bindAs.length()) +
+ "Failure" + "\nThe object doesn't exist. " +
+ "Please correct the value assigned in the" +
+ " \"Directory manager DN\" field.");
+ } else if (ex.getLDAPResultCode() == LDAPException.INVALID_CREDENTIALS) {
+ params.add(Constants.PR_AUTH_FAIL,
+ "Authentication: Basic authentication" +
+ dashes(70 - 36) + " Failure" +
+ "\nBind to the directory as: " + bindAs +
+ dashes(70 - 26 - bindAs.length()) +
+ " Failure" + "\nInvalid password. " +
+ "Please correct the value assigned in the" +
+ " \"Password\" field.");
} else {
- params.add(Constants.PR_AUTH_FAIL,
- "Authentication: Basic authentication" +
- dashes(70 - 36) + " Failure" +
- "\nBind to the directory as: " + bindAs +
- dashes(70 - 26 - bindAs.length()) +
- " Failure");
+ params.add(Constants.PR_AUTH_FAIL,
+ "Authentication: Basic authentication" +
+ dashes(70 - 36) + " Failure" +
+ "\nBind to the directory as: " + bindAs +
+ dashes(70 - 26 - bindAs.length()) +
+ " Failure");
}
- params.add(Constants.PR_SAVE_NOT,
- "\n \nIf the problem is not fixed then " +
- "LDAP publishing will fail.\n" +
- "Do you want to save the configuration anyway?");
+ params.add(Constants.PR_SAVE_NOT,
+ "\n \nIf the problem is not fixed then " +
+ "LDAP publishing will fail.\n" +
+ "Do you want to save the configuration anyway?");
sendResponse(SUCCESS, null, params, resp);
return;
}
@@ -873,55 +865,55 @@ public class PublisherAdminServlet extends AdminServlet {
}
- //commit(true);
+ // commit(true);
if (ldapcfg.getBoolean(IPublisherProcessor.PROP_ENABLE) &&
- pwd != null) {
+ pwd != null) {
- /* Do a "PUT" of the new pw to the watchdog"
- ** do not remove - cfu
- CMS.putPasswordCache(PW_TAG_CA_LDAP_PUBLISHING, pwd);
+ /*
+ * Do a "PUT" of the new pw to the watchdog"* do not remove - cfu
+ * CMS.putPasswordCache(PW_TAG_CA_LDAP_PUBLISHING, pwd);
*/
// support publishing dirsrv with different pwd than internaldb
// update passwordFile
String prompt = ldap.getString(Constants.PR_BINDPWD_PROMPT);
IPasswordStore pwdStore = CMS.getPasswordStore();
- CMS.debug("PublisherAdminServlet: testSetLDAPDest(): saving password for "+
- prompt + " to password file");
+ CMS.debug("PublisherAdminServlet: testSetLDAPDest(): saving password for " +
+ prompt + " to password file");
pwdStore.putPassword(prompt, pwd);
pwdStore.commit();
CMS.debug("PublisherAdminServlet: testSetLDAPDest(): password saved");
-/* we'll shut down and restart the PublisherProcessor instead
- // what a hack to do this without require restart server
-// ILdapAuthInfo authInfo = CMS.getLdapAuthInfo();
- ILdapConnModule connModule = mProcessor.getLdapConnModule();
- ILdapAuthInfo authInfo = null;
- if (connModule != null) {
- authInfo = connModule.getLdapAuthInfo();
- } else
- CMS.debug("PublisherAdminServlet: testSetLDAPDest(): connModule null");
-
-// authInfo.addPassword(PW_TAG_CA_LDAP_PUBLISHING, pwd);
- if (authInfo != null) {
- CMS.debug("PublisherAdminServlet: testSetLDAPDest(): adding password to memory cache");
- authInfo.addPassword(prompt, pwd);
- } else
- CMS.debug("PublisherAdminServlet: testSetLDAPDest(): authInfo null");
-*/
+ /*
+ * we'll shut down and restart the PublisherProcessor instead //
+ * what a hack to do this without require restart server //
+ * ILdapAuthInfo authInfo = CMS.getLdapAuthInfo(); ILdapConnModule
+ * connModule = mProcessor.getLdapConnModule(); ILdapAuthInfo
+ * authInfo = null; if (connModule != null) { authInfo =
+ * connModule.getLdapAuthInfo(); } else
+ * CMS.debug("PublisherAdminServlet: testSetLDAPDest(): connModule null"
+ * );
+ *
+ * // authInfo.addPassword(PW_TAG_CA_LDAP_PUBLISHING, pwd); if
+ * (authInfo != null) { CMS.debug(
+ * "PublisherAdminServlet: testSetLDAPDest(): adding password to memory cache"
+ * ); authInfo.addPassword(prompt, pwd); } else
+ * CMS.debug("PublisherAdminServlet: testSetLDAPDest(): authInfo null"
+ * );
+ */
}
- //params.add(Constants.PR_SAVE_OK,
- // "\n \nConfiguration changes are now committed.");
+ // params.add(Constants.PR_SAVE_OK,
+ // "\n \nConfiguration changes are now committed.");
mProcessor.shutdown();
if (publishcfg.getBoolean(IPublisherProcessor.PROP_ENABLE)) {
mProcessor.startup();
- //params.add("restarted", "Publishing is restarted.");
+ // params.add("restarted", "Publishing is restarted.");
if (ldapcfg.getBoolean(IPublisherProcessor.PROP_ENABLE)) {
ICertAuthority authority = (ICertAuthority) mProcessor.getAuthority();
- if (!(authority instanceof ICertificateAuthority))
+ if (!(authority instanceof ICertificateAuthority))
return;
ICertificateAuthority ca = (ICertificateAuthority) authority;
@@ -929,26 +921,26 @@ public class PublisherAdminServlet extends AdminServlet {
try {
mProcessor.publishCACert(ca.getCACert());
CMS.debug("PublisherAdminServlet: " + CMS.getLogMessage("ADMIN_SRVLT_PUB_CA_CERT"));
- params.add("publishCA",
- "CA certificate is published.");
+ params.add("publishCA",
+ "CA certificate is published.");
} catch (Exception ex) {
// exception not thrown - not seen as a fatal error.
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_NO_PUB_CA_CERT", ex.toString()));
- params.add("publishCA",
- "Failed to publish CA certificate.");
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_NO_PUB_CA_CERT", ex.toString()));
+ params.add("publishCA",
+ "Failed to publish CA certificate.");
int index = ex.toString().indexOf("Failed to create CA");
if (index > -1) {
params.add("createError",
- ex.toString().substring(index));
+ ex.toString().substring(index));
}
mProcessor.shutdown();
// Do you want to enable LDAP publishing anyway
- params.add(Constants.PR_SAVE_NOT,
- "\n \nIf the problem is not fixed then " +
- "the CA certificate won't be published.\n" +
- "Do you want to enable LDAP publishing anyway?");
+ params.add(Constants.PR_SAVE_NOT,
+ "\n \nIf the problem is not fixed then " +
+ "the CA certificate won't be published.\n" +
+ "Do you want to enable LDAP publishing anyway?");
sendResponse(SUCCESS, null, params, resp);
return;
@@ -958,65 +950,65 @@ public class PublisherAdminServlet extends AdminServlet {
CMS.debug("PublisherAdminServlet: about to update CRL");
ca.publishCRLNow();
CMS.debug(CMS.getLogMessage("ADMIN_SRVLT_PUB_CRL"));
- params.add("publishCRL",
- "CRL is published.");
+ params.add("publishCRL",
+ "CRL is published.");
} catch (Exception ex) {
// exception not thrown - not seen as a fatal error.
- log(ILogger.LL_FAILURE,
- "Could not publish crl " + ex.toString());
- params.add("publishCRL",
- "Failed to publish CRL.");
+ log(ILogger.LL_FAILURE,
+ "Could not publish crl " + ex.toString());
+ params.add("publishCRL",
+ "Failed to publish CRL.");
mProcessor.shutdown();
// Do you want to enable LDAP publishing anyway
- params.add(Constants.PR_SAVE_NOT,
- "\n \nIf the problem is not fixed then " +
- "the CRL won't be published.\n" +
- "Do you want to enable LDAP publishing anyway?");
+ params.add(Constants.PR_SAVE_NOT,
+ "\n \nIf the problem is not fixed then " +
+ "the CRL won't be published.\n" +
+ "Do you want to enable LDAP publishing anyway?");
sendResponse(SUCCESS, null, params, resp);
return;
}
}
commit(true);
- params.add(Constants.PR_SAVE_OK,
- "\n \nConfiguration changes are now committed.");
+ params.add(Constants.PR_SAVE_OK,
+ "\n \nConfiguration changes are now committed.");
params.add("restarted", "Publishing is restarted.");
} else {
commit(true);
- params.add(Constants.PR_SAVE_OK,
- "\n \nConfiguration changes are now committed.");
- params.add("stopped",
- "Publishing is stopped.");
+ params.add(Constants.PR_SAVE_OK,
+ "\n \nConfiguration changes are now committed.");
+ params.add("stopped",
+ "Publishing is stopped.");
}
- //XXX See if we can dynamically in B2
+ // XXX See if we can dynamically in B2
sendResponse(SUCCESS, null, params, resp);
}
- private synchronized void addMapperPlugin(HttpServletRequest req,
- HttpServletResponse resp, String scope)
- throws ServletException, IOException, EBaseException {
+ private synchronized void addMapperPlugin(HttpServletRequest req,
+ HttpServletResponse resp, String scope)
+ throws ServletException, IOException, EBaseException {
String id = req.getParameter(Constants.RS_ID);
if (id == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
// is the manager id unique?
if (mProcessor.getMapperPlugins().containsKey((Object) id)) {
sendResponse(ERROR,
- new ELdapException(CMS.getUserMessage(getLocale(req),"CMS_LDAP_SRVLT_ILL_PLUGIN_ID", id)).toString(),
- null, resp);
+ new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_SRVLT_ILL_PLUGIN_ID", id)).toString(),
+ null, resp);
return;
}
String classPath = req.getParameter(Constants.PR_MAPPER_CLASS);
if (classPath == null) {
- sendResponse(ERROR, CMS.getUserMessage(getLocale(req),"CMS_LDAP_SRVLT_NULL_CLASS"), null, resp);
+ sendResponse(ERROR, CMS.getUserMessage(getLocale(req), "CMS_LDAP_SRVLT_NULL_CLASS"), null, resp);
return;
}
@@ -1057,10 +1049,10 @@ public class PublisherAdminServlet extends AdminServlet {
try {
mConfig.commit(true);
} catch (EBaseException e) {
- //System.out.println("SRVLT_FAIL_COMMIT");
+ // System.out.println("SRVLT_FAIL_COMMIT");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
+ null, resp);
return;
}
@@ -1068,8 +1060,8 @@ public class PublisherAdminServlet extends AdminServlet {
MapperPlugin plugin = new MapperPlugin(id, classPath);
mProcessor.getMapperPlugins().put(id, plugin);
- mProcessor.log(ILogger.LL_INFO,
- CMS.getLogMessage("ADMIN_SRVLT_MAPPER_ADDED", ""));
+ mProcessor.log(ILogger.LL_INFO,
+ CMS.getLogMessage("ADMIN_SRVLT_MAPPER_ADDED", ""));
NameValuePairs params = new NameValuePairs();
@@ -1087,27 +1079,27 @@ public class PublisherAdminServlet extends AdminServlet {
return true;
}
- private synchronized void addMapperInst(HttpServletRequest req,
- HttpServletResponse resp, String scope)
- throws ServletException, IOException, EBaseException {
+ private synchronized void addMapperInst(HttpServletRequest req,
+ HttpServletResponse resp, String scope)
+ throws ServletException, IOException, EBaseException {
String id = req.getParameter(Constants.RS_ID);
if (id == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
if (!isValidID(id)) {
- sendResponse(ERROR, "Invalid ID '" + id + "'",
- null, resp);
+ sendResponse(ERROR, "Invalid ID '" + id + "'",
+ null, resp);
return;
}
if (mProcessor.getMapperInsts().containsKey((Object) id)) {
sendResponse(ERROR, CMS.getUserMessage(getLocale(req), "CMS_LDAP_SRVLT_ILL_INST_ID", id),
- null, resp);
+ null, resp);
return;
}
@@ -1122,13 +1114,13 @@ public class PublisherAdminServlet extends AdminServlet {
// check if implementation exists.
MapperPlugin plugin =
- (MapperPlugin) mProcessor.getMapperPlugins().get(
- implname);
+ (MapperPlugin) mProcessor.getMapperPlugins().get(
+ implname);
if (plugin == null) {
sendResponse(ERROR,
- new EMapperPluginNotFound(CMS.getUserMessage(getLocale(req), "CMS_LDAP_MAPPER_PLUGIN_NOT_FOUND", implname)).toString(),
- null, resp);
+ new EMapperPluginNotFound(CMS.getUserMessage(getLocale(req), "CMS_LDAP_MAPPER_PLUGIN_NOT_FOUND", implname)).toString(),
+ null, resp);
return;
}
@@ -1145,11 +1137,11 @@ public class PublisherAdminServlet extends AdminServlet {
String val = req.getParameter(kv.substring(0, index));
if (val == null) {
- substore.put(kv.substring(0, index),
- kv.substring(index + 1));
+ substore.put(kv.substring(0, index),
+ kv.substring(index + 1));
} else {
- substore.put(kv.substring(0, index),
- val);
+ substore.put(kv.substring(0, index),
+ val);
}
}
}
@@ -1165,20 +1157,20 @@ public class PublisherAdminServlet extends AdminServlet {
// cleanup
instancesConfig.removeSubStore(id);
sendResponse(ERROR,
- new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
- null, resp);
+ new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
+ null, resp);
return;
} catch (InstantiationException e) {
instancesConfig.removeSubStore(id);
sendResponse(ERROR,
- new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
- null, resp);
+ new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
+ null, resp);
return;
} catch (IllegalAccessException e) {
instancesConfig.removeSubStore(id);
sendResponse(ERROR,
- new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
- null, resp);
+ new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
+ null, resp);
return;
}
@@ -1203,46 +1195,46 @@ public class PublisherAdminServlet extends AdminServlet {
// clean up.
instancesConfig.removeSubStore(id);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
+ null, resp);
return;
}
// inited and commited ok. now add mapper instance to list.
mProcessor.getMapperInsts().put(id, new MapperProxy(true, mapperInst));
- mProcessor.log(ILogger.LL_INFO,
- CMS.getLogMessage("ADMIN_SRVLT_MAPPER_INST_ADDED", id));
+ mProcessor.log(ILogger.LL_INFO,
+ CMS.getLogMessage("ADMIN_SRVLT_MAPPER_INST_ADDED", id));
NameValuePairs params = new NameValuePairs();
params.add(Constants.PR_MAPPER_IMPL_NAME, implname);
sendResponse(SUCCESS, null, params, resp);
return;
- }
+ }
- private synchronized void listMapperPlugins(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ private synchronized void listMapperPlugins(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
Enumeration e = mProcessor.getMapperPlugins().keys();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
- MapperPlugin value = (MapperPlugin)
- mProcessor.getMapperPlugins().get(name);
+ MapperPlugin value = (MapperPlugin)
+ mProcessor.getMapperPlugins().get(name);
// get Description
- String c = value.getClassPath();
+ String c = value.getClassPath();
String desc = "unknown";
try {
ILdapMapper lp = (ILdapMapper)
- Class.forName(c).newInstance();
+ Class.forName(c).newInstance();
desc = lp.getDescription();
} catch (Exception exp) {
- sendResponse(ERROR, exp.toString(), null,
- resp);
+ sendResponse(ERROR, exp.toString(), null,
+ resp);
return;
}
params.add(name, value.getClassPath() + "," + desc);
@@ -1261,8 +1253,8 @@ public class PublisherAdminServlet extends AdminServlet {
}
}
- private synchronized void listMapperInsts(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ private synchronized void listMapperInsts(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
@@ -1278,40 +1270,40 @@ public class PublisherAdminServlet extends AdminServlet {
return;
}
- private synchronized void delMapperInst(HttpServletRequest req,
- HttpServletResponse resp, String scope)
- throws ServletException, IOException, EBaseException {
+ private synchronized void delMapperInst(HttpServletRequest req,
+ HttpServletResponse resp, String scope)
+ throws ServletException, IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
String id = req.getParameter(Constants.RS_ID);
if (id == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
// does a`mapper instance exist?
if (mProcessor.getMapperInsts().containsKey(id) == false) {
sendResponse(ERROR,
- new EMapperNotFound(CMS.getUserMessage(getLocale(req), "CMS_LDAP_MAPPER_NOT_FOUND", id)).toString(),
- null, resp);
+ new EMapperNotFound(CMS.getUserMessage(getLocale(req), "CMS_LDAP_MAPPER_NOT_FOUND", id)).toString(),
+ null, resp);
return;
}
// only remove from memory
// cannot shutdown because we don't keep track of whether it's
- // being used.
+ // being used.
ILdapMapper mapperInst = (ILdapMapper)
- mProcessor.getMapperInstance(id);
+ mProcessor.getMapperInstance(id);
mProcessor.getMapperInsts().remove((Object) id);
// remove the configuration.
IConfigStore destStore =
- mConfig.getSubStore(
- mAuth.getId() + ".publish.mapper");
+ mConfig.getSubStore(
+ mAuth.getId() + ".publish.mapper");
IConfigStore instancesConfig = destStore.getSubStore("instance");
instancesConfig.removeSubStore(id);
@@ -1319,41 +1311,40 @@ public class PublisherAdminServlet extends AdminServlet {
try {
mConfig.commit(true);
} catch (EBaseException e) {
- //System.out.println("SRVLT_FAIL_COMMIT");
+ // System.out.println("SRVLT_FAIL_COMMIT");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
+ null, resp);
return;
}
sendResponse(SUCCESS, null, params, resp);
return;
- }
+ }
- private synchronized void delMapperPlugin(HttpServletRequest req,
- HttpServletResponse resp, String scope)
- throws ServletException, IOException, EBaseException {
+ private synchronized void delMapperPlugin(HttpServletRequest req,
+ HttpServletResponse resp, String scope)
+ throws ServletException, IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
String id = req.getParameter(Constants.RS_ID);
if (id == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
if (mProcessor.getMapperPlugins().containsKey(id) == false) {
sendResponse(ERROR,
- new EMapperPluginNotFound(CMS.getUserMessage(getLocale(req), "CMS_LDAP_MAPPER_PLUGIN_NOT_FOUND", id)).toString(),
- null, resp);
+ new EMapperPluginNotFound(CMS.getUserMessage(getLocale(req), "CMS_LDAP_MAPPER_PLUGIN_NOT_FOUND", id)).toString(),
+ null, resp);
return;
}
// first check if any instances from this mapper
// DON'T remove mapper if any instance
- for (Enumeration e = mProcessor.getMapperInsts().keys();
- e.hasMoreElements();) {
+ for (Enumeration e = mProcessor.getMapperInsts().keys(); e.hasMoreElements();) {
String name = (String) e.nextElement();
ILdapMapper mapper = mProcessor.getMapperInstance(name);
@@ -1362,15 +1353,15 @@ public class PublisherAdminServlet extends AdminServlet {
return;
}
}
-
+
// then delete this mapper
mProcessor.getMapperPlugins().remove((Object) id);
IConfigStore destStore =
- mConfig.getSubStore(
- mAuth.getId() + ".publish.mapper");
+ mConfig.getSubStore(
+ mAuth.getId() + ".publish.mapper");
IConfigStore instancesConfig =
- destStore.getSubStore("impl");
+ destStore.getSubStore("impl");
instancesConfig.removeSubStore(id);
// commiting
@@ -1378,26 +1369,26 @@ public class PublisherAdminServlet extends AdminServlet {
mConfig.commit(true);
} catch (EBaseException e) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
+ null, resp);
return;
}
sendResponse(SUCCESS, null, params, resp);
return;
- }
+ }
- private synchronized void getMapperConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException, EBaseException {
+ private synchronized void getMapperConfig(HttpServletRequest req,
+ HttpServletResponse resp)
+ throws ServletException, IOException, EBaseException {
String implname = req.getParameter(Constants.RS_ID);
if (implname == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
@@ -1411,50 +1402,50 @@ public class PublisherAdminServlet extends AdminServlet {
String kv = (String) configParams.elementAt(i);
int index = kv.indexOf('=');
- params.add(kv.substring(0, index),
- kv.substring(index + 1));
+ params.add(kv.substring(0, index),
+ kv.substring(index + 1));
}
}
sendResponse(0, null, params, resp);
return;
}
- private synchronized void getMapperInstConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ private synchronized void getMapperInstConfig(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String id = req.getParameter(Constants.RS_ID);
if (id == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
// does mapper instance exist?
if (mProcessor.getMapperInsts().containsKey(id) == false) {
sendResponse(ERROR,
- new EMapperNotFound(CMS.getUserMessage(getLocale(req), "CMS_LDAP_MAPPER_NOT_FOUND", id)).toString(),
- null, resp);
+ new EMapperNotFound(CMS.getUserMessage(getLocale(req), "CMS_LDAP_MAPPER_NOT_FOUND", id)).toString(),
+ null, resp);
return;
}
ILdapMapper mapperInst = (ILdapMapper)
- mProcessor.getMapperInstance(id);
+ mProcessor.getMapperInstance(id);
Vector configParams = mapperInst.getInstanceParams();
NameValuePairs params = new NameValuePairs();
- params.add(Constants.PR_MAPPER_IMPL_NAME,
- getMapperPluginName(mapperInst));
+ params.add(Constants.PR_MAPPER_IMPL_NAME,
+ getMapperPluginName(mapperInst));
// implName is always required so always send it.
if (configParams != null) {
for (int i = 0; i < configParams.size(); i++) {
String kv = (String) configParams.elementAt(i);
int index = kv.indexOf('=');
- params.add(kv.substring(0, index),
- kv.substring(index + 1));
+ params.add(kv.substring(0, index),
+ kv.substring(index + 1));
}
}
@@ -1462,24 +1453,24 @@ public class PublisherAdminServlet extends AdminServlet {
return;
}
- private synchronized void modMapperInst(HttpServletRequest req,
- HttpServletResponse resp, String scope)
- throws ServletException, IOException, EBaseException {
+ private synchronized void modMapperInst(HttpServletRequest req,
+ HttpServletResponse resp, String scope)
+ throws ServletException, IOException, EBaseException {
String id = req.getParameter(Constants.RS_ID);
if (id == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
// Does the manager instance exist?
if (!mProcessor.getMapperInsts().containsKey((Object) id)) {
sendResponse(ERROR, CMS.getUserMessage(getLocale(req), "CMS_LDAP_SRVLT_ILL_INST_ID", id),
- null, resp);
+ null, resp);
return;
}
@@ -1492,19 +1483,19 @@ public class PublisherAdminServlet extends AdminServlet {
}
// get plugin for implementation
MapperPlugin plugin =
- (MapperPlugin) mProcessor.getMapperPlugins().get(implname);
+ (MapperPlugin) mProcessor.getMapperPlugins().get(implname);
if (plugin == null) {
sendResponse(ERROR,
- new EMapperPluginNotFound(CMS.getUserMessage(getLocale(req), "CMS_LDAP_MAPPER_PLUGIN_NOT_FOUND", implname)).toString(),
- null, resp);
+ new EMapperPluginNotFound(CMS.getUserMessage(getLocale(req), "CMS_LDAP_MAPPER_PLUGIN_NOT_FOUND", implname)).toString(),
+ null, resp);
return;
}
// save old instance substore params in case new one fails.
ILdapMapper oldinst =
- (ILdapMapper) mProcessor.getMapperInstance(id);
+ (ILdapMapper) mProcessor.getMapperInstance(id);
Vector oldConfigParms = oldinst.getInstanceParams();
NameValuePairs saveParams = new NameValuePairs();
@@ -1516,7 +1507,7 @@ public class PublisherAdminServlet extends AdminServlet {
int index = kv.indexOf('=');
saveParams.add(kv.substring(0, index),
- kv.substring(index + 1));
+ kv.substring(index + 1));
}
}
@@ -1525,8 +1516,8 @@ public class PublisherAdminServlet extends AdminServlet {
// remove old substore.
IConfigStore destStore =
- mConfig.getSubStore(mAuth.getId() +
- ".publish.mapper");
+ mConfig.getSubStore(mAuth.getId() +
+ ".publish.mapper");
IConfigStore instancesConfig = destStore.getSubStore("instance");
// create new substore.
@@ -1557,26 +1548,26 @@ public class PublisherAdminServlet extends AdminServlet {
ILdapMapper newMgrInst = null;
try {
- newMgrInst = (ILdapMapper)
+ newMgrInst = (ILdapMapper)
Class.forName(className).newInstance();
} catch (ClassNotFoundException e) {
// cleanup
restore(instancesConfig, id, saveParams);
sendResponse(ERROR,
- new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
- null, resp);
+ new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
+ null, resp);
return;
} catch (InstantiationException e) {
restore(instancesConfig, id, saveParams);
sendResponse(ERROR,
- new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
- null, resp);
+ new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
+ null, resp);
return;
} catch (IllegalAccessException e) {
restore(instancesConfig, id, saveParams);
sendResponse(ERROR,
- new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
- null, resp);
+ new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
+ null, resp);
return;
}
// initialize the mapper
@@ -1586,26 +1577,26 @@ public class PublisherAdminServlet extends AdminServlet {
} catch (EBaseException e) {
// don't commit in this case and cleanup the new substore.
restore(instancesConfig, id, saveParams);
- sendResponse(ERROR, e.toString(getLocale(req)), null,
- resp);
+ sendResponse(ERROR, e.toString(getLocale(req)), null,
+ resp);
return;
} catch (Throwable e) {
restore(instancesConfig, id, saveParams);
- sendResponse(ERROR, e.toString(), null,
- resp);
+ sendResponse(ERROR, e.toString(), null,
+ resp);
return;
}
- // initialized ok. commiting
+ // initialized ok. commiting
try {
mConfig.commit(true);
} catch (EBaseException e) {
// clean up.
restore(instancesConfig, id, saveParams);
- //System.out.println("SRVLT_FAIL_COMMIT");
+ // System.out.println("SRVLT_FAIL_COMMIT");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
+ null, resp);
return;
}
@@ -1614,31 +1605,31 @@ public class PublisherAdminServlet extends AdminServlet {
mProcessor.getMapperInsts().put(id, new MapperProxy(true, newMgrInst));
mProcessor.log(ILogger.LL_INFO,
- CMS.getLogMessage("ADMIN_SRVLT_MAPPER_REPLACED", id));
+ CMS.getLogMessage("ADMIN_SRVLT_MAPPER_REPLACED", id));
NameValuePairs params = new NameValuePairs();
sendResponse(SUCCESS, null, params, resp);
return;
}
- private synchronized void addRulePlugin(HttpServletRequest req,
- HttpServletResponse resp, String scope)
- throws ServletException, IOException, EBaseException {
+ private synchronized void addRulePlugin(HttpServletRequest req,
+ HttpServletResponse resp, String scope)
+ throws ServletException, IOException, EBaseException {
String id = req.getParameter(Constants.RS_ID);
if (id == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
// is the rule id unique?
if (mProcessor.getRulePlugins().containsKey((Object) id)) {
sendResponse(ERROR,
- new ELdapException(CMS.getUserMessage("CMS_LDAP_SRVLT_ILL_PLUGIN_ID", id)).toString(getLocale(req)),
- null, resp);
+ new ELdapException(CMS.getUserMessage("CMS_LDAP_SRVLT_ILL_PLUGIN_ID", id)).toString(getLocale(req)),
+ null, resp);
return;
}
@@ -1687,10 +1678,10 @@ public class PublisherAdminServlet extends AdminServlet {
try {
mConfig.commit(true);
} catch (EBaseException e) {
- //System.out.println("SRVLT_FAIL_COMMIT");
+ // System.out.println("SRVLT_FAIL_COMMIT");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
+ null, resp);
return;
}
@@ -1698,8 +1689,8 @@ public class PublisherAdminServlet extends AdminServlet {
RulePlugin plugin = new RulePlugin(id, classPath);
mProcessor.getRulePlugins().put(id, plugin);
- mProcessor.log(ILogger.LL_INFO,
- CMS.getLogMessage("ADMIN_SRVLT_RULE_PLUG_ADDED", id));
+ mProcessor.log(ILogger.LL_INFO,
+ CMS.getLogMessage("ADMIN_SRVLT_RULE_PLUG_ADDED", id));
NameValuePairs params = new NameValuePairs();
@@ -1707,26 +1698,26 @@ public class PublisherAdminServlet extends AdminServlet {
return;
}
- private synchronized void addRuleInst(HttpServletRequest req,
- HttpServletResponse resp, String scope)
- throws ServletException, IOException, EBaseException {
+ private synchronized void addRuleInst(HttpServletRequest req,
+ HttpServletResponse resp, String scope)
+ throws ServletException, IOException, EBaseException {
String id = req.getParameter(Constants.RS_ID);
if (id == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
if (!isValidID(id)) {
- sendResponse(ERROR, "Invalid ID '" + id + "'",
- null, resp);
+ sendResponse(ERROR, "Invalid ID '" + id + "'",
+ null, resp);
return;
}
if (mProcessor.getRuleInsts().containsKey((Object) id)) {
sendResponse(ERROR, CMS.getUserMessage(getLocale(req), "CMS_LDAP_SRVLT_ILL_INST_ID", id),
- null, resp);
+ null, resp);
return;
}
@@ -1741,23 +1732,23 @@ public class PublisherAdminServlet extends AdminServlet {
// check if implementation exists.
RulePlugin plugin =
- (RulePlugin) mProcessor.getRulePlugins().get(
- implname);
+ (RulePlugin) mProcessor.getRulePlugins().get(
+ implname);
if (plugin == null) {
sendResponse(ERROR,
- new EPublisherPluginNotFound(CMS.getUserMessage(getLocale(req), "CMS_LDAP_PUBLISHER_PLUGIN_NOT_FOUND", implname)).toString(),
- null, resp);
+ new EPublisherPluginNotFound(CMS.getUserMessage(getLocale(req), "CMS_LDAP_PUBLISHER_PLUGIN_NOT_FOUND", implname)).toString(),
+ null, resp);
return;
}
Vector configParams = mProcessor.getRuleDefaultParams(implname);
IConfigStore destStore =
- mConfig.getSubStore(mAuth.getId()
- + ".publish.rule");
+ mConfig.getSubStore(mAuth.getId()
+ + ".publish.rule");
IConfigStore instancesConfig =
- destStore.getSubStore("instance");
+ destStore.getSubStore("instance");
IConfigStore substore = instancesConfig.makeSubStore(id);
if (configParams != null) {
@@ -1767,13 +1758,13 @@ public class PublisherAdminServlet extends AdminServlet {
String val = req.getParameter(kv.substring(0, index));
if (val == null) {
- substore.put(kv.substring(0, index),
- kv.substring(index + 1));
+ substore.put(kv.substring(0, index),
+ kv.substring(index + 1));
} else {
if (val.equals(NOMAPPER))
val = "";
- substore.put(kv.substring(0, index),
- val);
+ substore.put(kv.substring(0, index),
+ val);
}
}
}
@@ -1789,20 +1780,20 @@ public class PublisherAdminServlet extends AdminServlet {
// cleanup
instancesConfig.removeSubStore(id);
sendResponse(ERROR,
- new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
- null, resp);
+ new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
+ null, resp);
return;
} catch (InstantiationException e) {
instancesConfig.removeSubStore(id);
sendResponse(ERROR,
- new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
- null, resp);
+ new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
+ null, resp);
return;
} catch (IllegalAccessException e) {
instancesConfig.removeSubStore(id);
sendResponse(ERROR,
- new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
- null, resp);
+ new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
+ null, resp);
return;
}
@@ -1828,40 +1819,40 @@ public class PublisherAdminServlet extends AdminServlet {
// clean up.
instancesConfig.removeSubStore(id);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
+ null, resp);
return;
}
// inited and commited ok. now add manager instance to list.
mProcessor.getRuleInsts().put(id, ruleInst);
- mProcessor.log(ILogger.LL_INFO,
- CMS.getLogMessage("ADMIN_SRVLT_RULE_INST_ADDED", id));
+ mProcessor.log(ILogger.LL_INFO,
+ CMS.getLogMessage("ADMIN_SRVLT_RULE_INST_ADDED", id));
NameValuePairs params = new NameValuePairs();
params.add(Constants.PR_RULE_IMPL_NAME, implname);
sendResponse(SUCCESS, null, params, resp);
return;
- }
+ }
- private synchronized void listRulePlugins(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ private synchronized void listRulePlugins(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
Enumeration e = mProcessor.getRulePlugins().keys();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
- RulePlugin value = (RulePlugin)
- mProcessor.getRulePlugins().get(name);
+ RulePlugin value = (RulePlugin)
+ mProcessor.getRulePlugins().get(name);
// get Description
- String c = value.getClassPath();
+ String c = value.getClassPath();
String desc = "unknown";
try {
ILdapRule lp = (ILdapRule)
- Class.forName(c).newInstance();
+ Class.forName(c).newInstance();
desc = lp.getDescription();
} catch (Exception exp) {
@@ -1872,8 +1863,8 @@ public class PublisherAdminServlet extends AdminServlet {
return;
}
- private synchronized void listRuleInsts(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ private synchronized void listRuleInsts(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
String insts = null;
@@ -1881,8 +1872,8 @@ public class PublisherAdminServlet extends AdminServlet {
for (; e.hasMoreElements();) {
String name = (String) e.nextElement();
- ILdapRule value = (ILdapRule)
- mProcessor.getRuleInsts().get((Object) name);
+ ILdapRule value = (ILdapRule)
+ mProcessor.getRuleInsts().get((Object) name);
String enabled = value.enabled() ? "enabled" : "disabled";
params.add(name, value.getInstanceName() + ";visible;" + enabled);
@@ -1901,47 +1892,46 @@ public class PublisherAdminServlet extends AdminServlet {
}
}
- private synchronized void delRulePlugin(HttpServletRequest req,
- HttpServletResponse resp, String scope)
- throws ServletException, IOException, EBaseException {
+ private synchronized void delRulePlugin(HttpServletRequest req,
+ HttpServletResponse resp, String scope)
+ throws ServletException, IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
String id = req.getParameter(Constants.RS_ID);
if (id == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
// does rule exist?
if (mProcessor.getRulePlugins().containsKey(id) == false) {
sendResponse(ERROR,
- new ERulePluginNotFound(CMS.getUserMessage(getLocale(req), "CMS_LDAP_RULE_PLUGIN_NOT_FOUND", id)).toString(),
- null, resp);
+ new ERulePluginNotFound(CMS.getUserMessage(getLocale(req), "CMS_LDAP_RULE_PLUGIN_NOT_FOUND", id)).toString(),
+ null, resp);
return;
}
// first check if any instances from this rule
// DON'T remove rule if any instance
- for (Enumeration e = mProcessor.getRuleInsts().elements();
- e.hasMoreElements();) {
- ILdapRule rule = (ILdapRule)
- e.nextElement();
+ for (Enumeration e = mProcessor.getRuleInsts().elements(); e.hasMoreElements();) {
+ ILdapRule rule = (ILdapRule)
+ e.nextElement();
if (id.equals(getRulePluginName(rule))) {
sendResponse(ERROR, CMS.getUserMessage(getLocale(req), "CMS_LDAP_SRVLT_IN_USE"), null, resp);
return;
}
}
-
+
// then delete this rule
mProcessor.getRulePlugins().remove((Object) id);
IConfigStore destStore =
- mConfig.getSubStore(
- mAuth.getId() + ".rule");
+ mConfig.getSubStore(
+ mAuth.getId() + ".rule");
IConfigStore instancesConfig = destStore.getSubStore("impl");
instancesConfig.removeSubStore(id);
@@ -1950,26 +1940,26 @@ public class PublisherAdminServlet extends AdminServlet {
mConfig.commit(true);
} catch (EBaseException e) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
+ null, resp);
return;
}
sendResponse(SUCCESS, null, params, resp);
return;
- }
+ }
- private synchronized void delRuleInst(HttpServletRequest req,
- HttpServletResponse resp, String scope)
- throws ServletException, IOException, EBaseException {
+ private synchronized void delRuleInst(HttpServletRequest req,
+ HttpServletResponse resp, String scope)
+ throws ServletException, IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
String id = req.getParameter(Constants.RS_ID);
if (id == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
@@ -1978,23 +1968,23 @@ public class PublisherAdminServlet extends AdminServlet {
// does rule instance exist?
if (mProcessor.getRuleInsts().containsKey(id) == false) {
sendResponse(ERROR,
- new ERuleNotFound(CMS.getUserMessage(getLocale(req), "CMS_LDAP_RULE_NOT_FOUND", id)).toString(),
- null, resp);
+ new ERuleNotFound(CMS.getUserMessage(getLocale(req), "CMS_LDAP_RULE_NOT_FOUND", id)).toString(),
+ null, resp);
return;
}
// only remove from memory
// cannot shutdown because we don't keep track of whether it's
- // being used.
+ // being used.
ILdapRule ruleInst = (ILdapRule)
- mProcessor.getRuleInsts().get(id);
+ mProcessor.getRuleInsts().get(id);
mProcessor.getRuleInsts().remove((Object) id);
// remove the configuration.
IConfigStore destStore =
- mConfig.getSubStore(
- mAuth.getId() + ".publish.rule");
+ mConfig.getSubStore(
+ mAuth.getId() + ".publish.rule");
IConfigStore instancesConfig = destStore.getSubStore("instance");
instancesConfig.removeSubStore(id);
@@ -2002,26 +1992,26 @@ public class PublisherAdminServlet extends AdminServlet {
try {
mConfig.commit(true);
} catch (EBaseException e) {
- //System.out.println("SRVLT_FAIL_COMMIT");
+ // System.out.println("SRVLT_FAIL_COMMIT");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
+ null, resp);
return;
}
sendResponse(SUCCESS, null, params, resp);
return;
- }
+ }
- private synchronized void getRuleConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException, EBaseException {
+ private synchronized void getRuleConfig(HttpServletRequest req,
+ HttpServletResponse resp)
+ throws ServletException, IOException, EBaseException {
String implname = req.getParameter(Constants.RS_ID);
if (implname == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
@@ -2035,50 +2025,50 @@ public class PublisherAdminServlet extends AdminServlet {
String kv = (String) configParams.elementAt(i);
int index = kv.indexOf('=');
- params.add(kv.substring(0, index),
- kv.substring(index + 1));
+ params.add(kv.substring(0, index),
+ kv.substring(index + 1));
}
}
sendResponse(0, null, params, resp);
return;
}
- private synchronized void getRuleInstConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ private synchronized void getRuleInstConfig(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String id = req.getParameter(Constants.RS_ID);
if (id == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
// does rule instance exist?
if (mProcessor.getRuleInsts().containsKey(id) == false) {
sendResponse(ERROR,
- new ERuleNotFound(CMS.getUserMessage(getLocale(req), "CMS_LDAP_RULE_NOT_FOUND", id)).toString(),
- null, resp);
+ new ERuleNotFound(CMS.getUserMessage(getLocale(req), "CMS_LDAP_RULE_NOT_FOUND", id)).toString(),
+ null, resp);
return;
}
ILdapRule ruleInst = (ILdapRule)
- mProcessor.getRuleInsts().get(id);
+ mProcessor.getRuleInsts().get(id);
Vector configParams = ruleInst.getInstanceParams();
NameValuePairs params = new NameValuePairs();
- params.add(Constants.PR_RULE_IMPL_NAME,
- getRulePluginName(ruleInst));
+ params.add(Constants.PR_RULE_IMPL_NAME,
+ getRulePluginName(ruleInst));
// implName is always required so always send it.
if (configParams != null) {
for (int i = 0; i < configParams.size(); i++) {
String kv = (String) configParams.elementAt(i);
int index = kv.indexOf('=');
- params.add(kv.substring(0, index),
- kv.substring(index + 1));
+ params.add(kv.substring(0, index),
+ kv.substring(index + 1));
}
}
@@ -2086,23 +2076,23 @@ public class PublisherAdminServlet extends AdminServlet {
return;
}
- private synchronized void modRuleInst(HttpServletRequest req,
- HttpServletResponse resp, String scope)
- throws ServletException, IOException, EBaseException {
+ private synchronized void modRuleInst(HttpServletRequest req,
+ HttpServletResponse resp, String scope)
+ throws ServletException, IOException, EBaseException {
String id = req.getParameter(Constants.RS_ID);
if (id == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
// Does the manager instance exist?
if (!mProcessor.getRuleInsts().containsKey((Object) id)) {
sendResponse(ERROR, CMS.getUserMessage(getLocale(req), "CMS_LDAP_SRVLT_ILL_INST_ID", id),
- null, resp);
+ null, resp);
return;
}
@@ -2114,22 +2104,23 @@ public class PublisherAdminServlet extends AdminServlet {
return;
}
- // get plugin for implementation
+ // get plugin for implementation
RulePlugin plugin =
- (RulePlugin) mProcessor.getRulePlugins().get(implname);
+ (RulePlugin) mProcessor.getRulePlugins().get(implname);
if (plugin == null) {
sendResponse(ERROR,
- //new ERulePluginNotFound(implname).toString(getLocale(req)),
- "",
- null, resp);
+ // new
+ // ERulePluginNotFound(implname).toString(getLocale(req)),
+ "",
+ null, resp);
return;
}
- // save old instance substore params in case new one fails.
+ // save old instance substore params in case new one fails.
- ILdapRule oldinst =
- (ILdapRule) mProcessor.getRuleInsts().get((Object) id);
+ ILdapRule oldinst =
+ (ILdapRule) mProcessor.getRuleInsts().get((Object) id);
Vector oldConfigParms = oldinst.getInstanceParams();
NameValuePairs saveParams = new NameValuePairs();
@@ -2141,7 +2132,7 @@ public class PublisherAdminServlet extends AdminServlet {
int index = kv.indexOf('=');
saveParams.add(kv.substring(0, index),
- kv.substring(index + 1));
+ kv.substring(index + 1));
}
}
@@ -2150,8 +2141,8 @@ public class PublisherAdminServlet extends AdminServlet {
// remove old substore.
IConfigStore destStore =
- mConfig.getSubStore(
- mAuth.getId() + ".publish.rule");
+ mConfig.getSubStore(
+ mAuth.getId() + ".publish.rule");
IConfigStore instancesConfig = destStore.getSubStore("instance");
// create new substore.
@@ -2171,8 +2162,8 @@ public class PublisherAdminServlet extends AdminServlet {
String val = req.getParameter(key);
if (val == null) {
- substore.put(key,
- kv.substring(index + 1));
+ substore.put(key,
+ kv.substring(index + 1));
} else {
if (val.equals(NOMAPPER))
val = "";
@@ -2192,20 +2183,20 @@ public class PublisherAdminServlet extends AdminServlet {
// cleanup
restore(instancesConfig, id, saveParams);
sendResponse(ERROR,
- new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
- null, resp);
+ new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
+ null, resp);
return;
} catch (InstantiationException e) {
restore(instancesConfig, id, saveParams);
sendResponse(ERROR,
- new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
- null, resp);
+ new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
+ null, resp);
return;
} catch (IllegalAccessException e) {
restore(instancesConfig, id, saveParams);
sendResponse(ERROR,
- new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
- null, resp);
+ new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
+ null, resp);
return;
}
@@ -2224,16 +2215,16 @@ public class PublisherAdminServlet extends AdminServlet {
return;
}
- // initialized ok. commiting
+ // initialized ok. commiting
try {
mConfig.commit(true);
} catch (EBaseException e) {
// clean up.
restore(instancesConfig, id, saveParams);
- //System.out.println("SRVLT_FAIL_COMMIT");
+ // System.out.println("SRVLT_FAIL_COMMIT");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
+ null, resp);
return;
}
@@ -2241,40 +2232,40 @@ public class PublisherAdminServlet extends AdminServlet {
mProcessor.getRuleInsts().put(id, newRuleInst);
- mProcessor.log(ILogger.LL_INFO,
- CMS.getLogMessage("ADMIN_SRVLT_RULE_INST_REP", id));
+ mProcessor.log(ILogger.LL_INFO,
+ CMS.getLogMessage("ADMIN_SRVLT_RULE_INST_REP", id));
NameValuePairs params = new NameValuePairs();
sendResponse(SUCCESS, null, params, resp);
return;
}
- private synchronized void addPublisherPlugin(HttpServletRequest req,
- HttpServletResponse resp, String scope)
- throws ServletException, IOException, EBaseException {
+ private synchronized void addPublisherPlugin(HttpServletRequest req,
+ HttpServletResponse resp, String scope)
+ throws ServletException, IOException, EBaseException {
String id = req.getParameter(Constants.RS_ID);
if (id == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
// is the manager id unique?
if (mProcessor.getPublisherPlugins().containsKey((Object) id)) {
sendResponse(ERROR,
- new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_SRVLT_ILL_PLUGIN_ID", id)).toString(),
- null, resp);
+ new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_SRVLT_ILL_PLUGIN_ID", id)).toString(),
+ null, resp);
return;
}
String classPath = req.getParameter(Constants.PR_PUBLISHER_CLASS);
if (classPath == null) {
- sendResponse(ERROR, CMS.getUserMessage(getLocale(req),"CMS_LDAP_SRVLT_NULL_CLASS"), null, resp);
+ sendResponse(ERROR, CMS.getUserMessage(getLocale(req), "CMS_LDAP_SRVLT_NULL_CLASS"), null, resp);
return;
}
@@ -2316,10 +2307,10 @@ public class PublisherAdminServlet extends AdminServlet {
try {
mConfig.commit(true);
} catch (EBaseException e) {
- //System.out.println("SRVLT_FAIL_COMMIT");
+ // System.out.println("SRVLT_FAIL_COMMIT");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
+ null, resp);
return;
}
@@ -2327,8 +2318,8 @@ public class PublisherAdminServlet extends AdminServlet {
PublisherPlugin plugin = new PublisherPlugin(id, classPath);
mProcessor.getPublisherPlugins().put(id, plugin);
- mProcessor.log(ILogger.LL_INFO,
- CMS.getLogMessage("ADMIN_SRVLT_PUB_PLUG_ADDED", id));
+ mProcessor.log(ILogger.LL_INFO,
+ CMS.getLogMessage("ADMIN_SRVLT_PUB_PLUG_ADDED", id));
NameValuePairs params = new NameValuePairs();
@@ -2336,28 +2327,28 @@ public class PublisherAdminServlet extends AdminServlet {
return;
}
- private synchronized void addPublisherInst(HttpServletRequest req,
- HttpServletResponse resp, String scope)
- throws ServletException, IOException, EBaseException {
+ private synchronized void addPublisherInst(HttpServletRequest req,
+ HttpServletResponse resp, String scope)
+ throws ServletException, IOException, EBaseException {
String id = req.getParameter(Constants.RS_ID);
if (id == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
if (!isValidID(id)) {
- sendResponse(ERROR, "Invalid ID '" + id + "'",
- null, resp);
+ sendResponse(ERROR, "Invalid ID '" + id + "'",
+ null, resp);
return;
}
if (mProcessor.getPublisherInsts().containsKey((Object) id)) {
sendResponse(ERROR, CMS.getUserMessage(getLocale(req), "CMS_LDAP_SRVLT_ILL_INST_ID", id),
- null, resp);
+ null, resp);
return;
}
@@ -2372,20 +2363,20 @@ public class PublisherAdminServlet extends AdminServlet {
// check if implementation exists.
PublisherPlugin plugin =
- (PublisherPlugin) mProcessor.getPublisherPlugins().get(
- implname);
+ (PublisherPlugin) mProcessor.getPublisherPlugins().get(
+ implname);
if (plugin == null) {
sendResponse(ERROR,
- new EPublisherPluginNotFound(CMS.getUserMessage(getLocale(req), "CMS_LDAP_PUBLISHER_PLUGIN_NOT_FOUND", implname)).toString(),
- null, resp);
+ new EPublisherPluginNotFound(CMS.getUserMessage(getLocale(req), "CMS_LDAP_PUBLISHER_PLUGIN_NOT_FOUND", implname)).toString(),
+ null, resp);
return;
}
Vector configParams = mProcessor.getPublisherDefaultParams(implname);
IConfigStore destStore =
- mConfig.getSubStore(mAuth.getId() + ".publish.publisher");
+ mConfig.getSubStore(mAuth.getId() + ".publish.publisher");
IConfigStore instancesConfig = destStore.getSubStore("instance");
IConfigStore substore = instancesConfig.makeSubStore(id);
@@ -2404,15 +2395,15 @@ public class PublisherAdminServlet extends AdminServlet {
if (index == -1) {
substore.put(kv, "");
} else {
- substore.put(kv.substring(0, index),
- kv.substring(index + 1));
+ substore.put(kv.substring(0, index),
+ kv.substring(index + 1));
}
} else {
if (index == -1) {
substore.put(kv, val);
} else {
- substore.put(kv.substring(0, index),
- val);
+ substore.put(kv.substring(0, index),
+ val);
}
}
}
@@ -2429,20 +2420,20 @@ public class PublisherAdminServlet extends AdminServlet {
// cleanup
instancesConfig.removeSubStore(id);
sendResponse(ERROR,
- new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
- null, resp);
+ new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
+ null, resp);
return;
} catch (InstantiationException e) {
instancesConfig.removeSubStore(id);
sendResponse(ERROR,
- new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
- null, resp);
+ new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
+ null, resp);
return;
} catch (IllegalAccessException e) {
instancesConfig.removeSubStore(id);
sendResponse(ERROR,
- new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
- null, resp);
+ new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
+ null, resp);
return;
}
@@ -2467,16 +2458,16 @@ public class PublisherAdminServlet extends AdminServlet {
// clean up.
instancesConfig.removeSubStore(id);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
+ null, resp);
return;
}
// inited and commited ok. now add manager instance to list.
mProcessor.getPublisherInsts().put(id, new PublisherProxy(true, publisherInst));
- mProcessor.log(ILogger.LL_INFO,
- CMS.getLogMessage("ADMIN_SRVLT_PUB_INST_ADDED", id));
+ mProcessor.log(ILogger.LL_INFO,
+ CMS.getLogMessage("ADMIN_SRVLT_PUB_INST_ADDED", id));
NameValuePairs params = new NameValuePairs();
@@ -2485,8 +2476,8 @@ public class PublisherAdminServlet extends AdminServlet {
return;
}
- private synchronized void listPublisherPlugins(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ private synchronized void listPublisherPlugins(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
@@ -2494,15 +2485,15 @@ public class PublisherAdminServlet extends AdminServlet {
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
- PublisherPlugin value = (PublisherPlugin)
- mProcessor.getPublisherPlugins().get(name);
+ PublisherPlugin value = (PublisherPlugin)
+ mProcessor.getPublisherPlugins().get(name);
// get Description
- String c = value.getClassPath();
+ String c = value.getClassPath();
String desc = "unknown";
try {
ILdapPublisher lp = (ILdapPublisher)
- Class.forName(c).newInstance();
+ Class.forName(c).newInstance();
desc = lp.getDescription();
} catch (Exception exp) {
@@ -2523,8 +2514,8 @@ public class PublisherAdminServlet extends AdminServlet {
}
}
- private synchronized void listPublisherInsts(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ private synchronized void listPublisherInsts(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
@@ -2543,48 +2534,47 @@ public class PublisherAdminServlet extends AdminServlet {
return;
}
- private synchronized void delPublisherPlugin(HttpServletRequest req,
- HttpServletResponse resp, String scope) throws ServletException,
+ private synchronized void delPublisherPlugin(HttpServletRequest req,
+ HttpServletResponse resp, String scope) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
String id = req.getParameter(Constants.RS_ID);
if (id == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
// does publisher exist?
if (mProcessor.getPublisherPlugins().containsKey(id) == false) {
sendResponse(ERROR,
- new EPublisherPluginNotFound(CMS.getUserMessage(getLocale(req), "CMS_LDAP_PUBLISHER_PLUGIN_NOT_FOUND", id)).toString(),
- null, resp);
+ new EPublisherPluginNotFound(CMS.getUserMessage(getLocale(req), "CMS_LDAP_PUBLISHER_PLUGIN_NOT_FOUND", id)).toString(),
+ null, resp);
return;
}
// first check if any instances from this publisher
// DON'T remove publisher if any instance
- for (Enumeration e = mProcessor.getPublisherInsts().keys();
- e.hasMoreElements();) {
+ for (Enumeration e = mProcessor.getPublisherInsts().keys(); e.hasMoreElements();) {
String name = (String) e.nextElement();
- ILdapPublisher publisher =
- mProcessor.getPublisherInstance(name);
+ ILdapPublisher publisher =
+ mProcessor.getPublisherInstance(name);
if (id.equals(getPublisherPluginName(publisher))) {
sendResponse(ERROR, CMS.getUserMessage(getLocale(req), "CMS_LDAP_SRVLT_IN_USE"), null, resp);
return;
}
}
-
+
// then delete this publisher
mProcessor.getPublisherPlugins().remove((Object) id);
IConfigStore destStore =
- mConfig.getSubStore(mAuth.getId() + ".publish.publisher");
+ mConfig.getSubStore(mAuth.getId() + ".publish.publisher");
IConfigStore instancesConfig = destStore.getSubStore("impl");
instancesConfig.removeSubStore(id);
@@ -2593,8 +2583,8 @@ public class PublisherAdminServlet extends AdminServlet {
mConfig.commit(true);
} catch (EBaseException e) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
+ null, resp);
return;
}
@@ -2602,18 +2592,18 @@ public class PublisherAdminServlet extends AdminServlet {
return;
}
- private synchronized void delPublisherInst(HttpServletRequest req,
- HttpServletResponse resp, String scope) throws ServletException,
+ private synchronized void delPublisherInst(HttpServletRequest req,
+ HttpServletResponse resp, String scope) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
String id = req.getParameter(Constants.RS_ID);
if (id == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
@@ -2622,21 +2612,21 @@ public class PublisherAdminServlet extends AdminServlet {
// does publisher instance exist?
if (mProcessor.getPublisherInsts().containsKey(id) == false) {
sendResponse(ERROR,
- new EPublisherNotFound(CMS.getUserMessage(getLocale(req), "CMS_LDAP_PUBLISHER_NOT_FOUND", id)).toString(),
- null, resp);
+ new EPublisherNotFound(CMS.getUserMessage(getLocale(req), "CMS_LDAP_PUBLISHER_NOT_FOUND", id)).toString(),
+ null, resp);
return;
}
// only remove from memory
// cannot shutdown because we don't keep track of whether it's
- // being used.
+ // being used.
ILdapPublisher publisherInst = mProcessor.getPublisherInstance(id);
mProcessor.getPublisherInsts().remove((Object) id);
// remove the configuration.
IConfigStore destStore =
- mConfig.getSubStore(mAuth.getId() + ".publish.publisher");
+ mConfig.getSubStore(mAuth.getId() + ".publish.publisher");
IConfigStore instancesConfig = destStore.getSubStore("instance");
instancesConfig.removeSubStore(id);
@@ -2644,10 +2634,10 @@ public class PublisherAdminServlet extends AdminServlet {
try {
mConfig.commit(true);
} catch (EBaseException e) {
- //System.out.println("SRVLT_FAIL_COMMIT");
+ // System.out.println("SRVLT_FAIL_COMMIT");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
+ null, resp);
return;
}
sendResponse(SUCCESS, null, params, resp);
@@ -2655,25 +2645,24 @@ public class PublisherAdminServlet extends AdminServlet {
}
/**
- * used for getting the required configuration parameters (with
- * possible default values) for a particular plugin
- * implementation name specified in the RS_ID. Actually, there is
- * no logic in here to set any default value here...there's no
- * default value for any parameter in this publishing subsystem
- * at this point. Later, if we do have one (or some), it can be
- * added. The interface remains the same.
+ * used for getting the required configuration parameters (with possible
+ * default values) for a particular plugin implementation name specified in
+ * the RS_ID. Actually, there is no logic in here to set any default value
+ * here...there's no default value for any parameter in this publishing
+ * subsystem at this point. Later, if we do have one (or some), it can be
+ * added. The interface remains the same.
*/
- private synchronized void getConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException, EBaseException {
+ private synchronized void getConfig(HttpServletRequest req,
+ HttpServletResponse resp)
+ throws ServletException, IOException, EBaseException {
String implname = req.getParameter(Constants.RS_ID);
if (implname == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
@@ -2690,8 +2679,8 @@ public class PublisherAdminServlet extends AdminServlet {
if (index == -1) {
params.add(kv, "");
} else {
- params.add(kv.substring(0, index),
- kv.substring(index + 1));
+ params.add(kv.substring(0, index),
+ kv.substring(index + 1));
}
}
}
@@ -2699,43 +2688,43 @@ public class PublisherAdminServlet extends AdminServlet {
return;
}
- private synchronized void getInstConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ private synchronized void getInstConfig(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String id = req.getParameter(Constants.RS_ID);
if (id == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
// does publisher instance exist?
if (mProcessor.getPublisherInsts().containsKey(id) == false) {
sendResponse(ERROR,
- new EPublisherNotFound(CMS.getUserMessage(getLocale(req), "CMS_LDAP_PUBLISHER_NOT_FOUND", id)).toString(),
- null, resp);
+ new EPublisherNotFound(CMS.getUserMessage(getLocale(req), "CMS_LDAP_PUBLISHER_NOT_FOUND", id)).toString(),
+ null, resp);
return;
}
ILdapPublisher publisherInst = (ILdapPublisher)
- mProcessor.getPublisherInstance(id);
+ mProcessor.getPublisherInstance(id);
Vector configParams = publisherInst.getInstanceParams();
NameValuePairs params = new NameValuePairs();
- params.add(Constants.PR_PUBLISHER_IMPL_NAME,
- getPublisherPluginName(publisherInst));
+ params.add(Constants.PR_PUBLISHER_IMPL_NAME,
+ getPublisherPluginName(publisherInst));
// implName is always required so always send it.
if (configParams != null) {
for (int i = 0; i < configParams.size(); i++) {
String kv = (String) configParams.elementAt(i);
int index = kv.indexOf('=');
- params.add(kv.substring(0, index),
- kv.substring(index + 1));
+ params.add(kv.substring(0, index),
+ kv.substring(index + 1));
}
}
@@ -2744,33 +2733,31 @@ public class PublisherAdminServlet extends AdminServlet {
}
/**
- * Modify publisher instance.
- * This will actually create a new instance with new configuration
- * parameters and replace the old instance, if the new instance
- * created and initialized successfully.
- * The old instance is left running. so this is very expensive.
- * Restart of server recommended.
+ * Modify publisher instance. This will actually create a new instance with
+ * new configuration parameters and replace the old instance, if the new
+ * instance created and initialized successfully. The old instance is left
+ * running. so this is very expensive. Restart of server recommended.
*/
- private synchronized void modPublisherInst(HttpServletRequest req,
- HttpServletResponse resp, String scope)
- throws ServletException, IOException, EBaseException {
+ private synchronized void modPublisherInst(HttpServletRequest req,
+ HttpServletResponse resp, String scope)
+ throws ServletException, IOException, EBaseException {
// expensive operation.
String id = req.getParameter(Constants.RS_ID);
if (id == null) {
- //System.out.println("SRVLT_NULL_RS_ID");
+ // System.out.println("SRVLT_NULL_RS_ID");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
// Does the manager instance exist?
if (!mProcessor.getPublisherInsts().containsKey((Object) id)) {
sendResponse(ERROR, CMS.getUserMessage(getLocale(req), "CMS_LDAP_SRVLT_ILL_INST_ID", id),
- null, resp);
+ null, resp);
return;
}
@@ -2782,18 +2769,18 @@ public class PublisherAdminServlet extends AdminServlet {
return;
}
- // get plugin for implementation
+ // get plugin for implementation
PublisherPlugin plugin =
- (PublisherPlugin) mProcessor.getPublisherPlugins().get(implname);
+ (PublisherPlugin) mProcessor.getPublisherPlugins().get(implname);
if (plugin == null) {
sendResponse(ERROR,
- new EPublisherPluginNotFound(CMS.getUserMessage(getLocale(req), "CMS_LDAP_PUBLISHER_PLUGIN_NOT_FOUND", implname)).toString(),
- null, resp);
+ new EPublisherPluginNotFound(CMS.getUserMessage(getLocale(req), "CMS_LDAP_PUBLISHER_PLUGIN_NOT_FOUND", implname)).toString(),
+ null, resp);
return;
}
- // save old instance substore params in case new one fails.
+ // save old instance substore params in case new one fails.
ILdapPublisher oldinst = mProcessor.getPublisherInstance(id);
Vector oldConfigParms = oldinst.getInstanceParams();
@@ -2813,8 +2800,8 @@ public class PublisherAdminServlet extends AdminServlet {
pubType = "crl";
}
- saveParams.add(kv.substring(0, index),
- kv.substring(index + 1));
+ saveParams.add(kv.substring(0, index),
+ kv.substring(index + 1));
}
}
}
@@ -2824,7 +2811,7 @@ public class PublisherAdminServlet extends AdminServlet {
// remove old substore.
IConfigStore destStore =
- mConfig.getSubStore(mAuth.getId() + ".publish.publisher");
+ mConfig.getSubStore(mAuth.getId() + ".publish.publisher");
IConfigStore instancesConfig = destStore.getSubStore("instance");
// get objects added and deleted
@@ -2859,9 +2846,9 @@ public class PublisherAdminServlet extends AdminServlet {
}
// process any changes to the ldap object class definitions
- if (pubType.equals("cacert")) {
+ if (pubType.equals("cacert")) {
processChangedOC(saveParams, substore, "caObjectClass");
- substore.put("pubtype", "cacert");
+ substore.put("pubtype", "cacert");
}
if (pubType.equals("crl")) {
@@ -2880,20 +2867,20 @@ public class PublisherAdminServlet extends AdminServlet {
// cleanup
restore(instancesConfig, id, saveParams);
sendResponse(ERROR,
- new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
- null, resp);
+ new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
+ null, resp);
return;
} catch (InstantiationException e) {
restore(instancesConfig, id, saveParams);
sendResponse(ERROR,
- new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
- null, resp);
+ new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
+ null, resp);
return;
} catch (IllegalAccessException e) {
restore(instancesConfig, id, saveParams);
sendResponse(ERROR,
- new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
- null, resp);
+ new ELdapException(CMS.getUserMessage(getLocale(req), "CMS_LDAP_FAIL_LOAD_CLASS", className)).toString(),
+ null, resp);
return;
}
@@ -2912,16 +2899,16 @@ public class PublisherAdminServlet extends AdminServlet {
return;
}
- // initialized ok. commiting
+ // initialized ok. commiting
try {
mConfig.commit(true);
} catch (EBaseException e) {
// clean up.
restore(instancesConfig, id, saveParams);
- //System.out.println("SRVLT_FAIL_COMMIT");
+ // System.out.println("SRVLT_FAIL_COMMIT");
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_COMMIT_FAILED"),
+ null, resp);
return;
}
@@ -2929,8 +2916,8 @@ public class PublisherAdminServlet extends AdminServlet {
mProcessor.getPublisherInsts().put(id, new PublisherProxy(true, newMgrInst));
- mProcessor.log(ILogger.LL_INFO,
- CMS.getLogMessage("ADMIN_SRVLT_PUB_INST_REP", id));
+ mProcessor.log(ILogger.LL_INFO,
+ CMS.getLogMessage("ADMIN_SRVLT_PUB_INST_REP", id));
NameValuePairs params = new NameValuePairs();
@@ -2938,54 +2925,57 @@ public class PublisherAdminServlet extends AdminServlet {
return;
}
- // convenience function - takes list1, list2. Returns what is in list1
+ // convenience function - takes list1, list2. Returns what is in list1
// but not in list2
private String[] getExtras(String[] list1, String[] list2) {
- Vector <String> extras = new Vector<String>();
- for (int i=0; i< list1.length; i++) {
- boolean match=false;
- for (int j=0; j < list2.length; j++) {
- if ((list1[i].trim()).equalsIgnoreCase(list2[j].trim())) {
- match = true;
- break;
- }
- }
- if (!match) extras.add(list1[i].trim());
- }
-
- return (String[])extras.toArray(new String[extras.size()]);
+ Vector<String> extras = new Vector<String>();
+ for (int i = 0; i < list1.length; i++) {
+ boolean match = false;
+ for (int j = 0; j < list2.length; j++) {
+ if ((list1[i].trim()).equalsIgnoreCase(list2[j].trim())) {
+ match = true;
+ break;
+ }
+ }
+ if (!match)
+ extras.add(list1[i].trim());
+ }
+
+ return (String[]) extras.toArray(new String[extras.size()]);
}
- // convenience function - takes list1, list2. Concatenates the two
+ // convenience function - takes list1, list2. Concatenates the two
// lists removing duplicates
private String[] joinLists(String[] list1, String[] list2) {
- Vector <String> sum = new Vector<String>();
- for (int i=0; i< list1.length; i++) {
- sum.add(list1[i]);
- }
-
- for (int i=0; i < list2.length; i++) {
- boolean match=false;
- for (int j=0; j < list1.length; j++) {
- if ((list2[i].trim()).equalsIgnoreCase(list1[j].trim())) {
- match = true;
- break;
- }
- }
- if (!match) sum.add(list2[i].trim());
- }
-
- return (String[])sum.toArray(new String[sum.size()]);
+ Vector<String> sum = new Vector<String>();
+ for (int i = 0; i < list1.length; i++) {
+ sum.add(list1[i]);
+ }
+
+ for (int i = 0; i < list2.length; i++) {
+ boolean match = false;
+ for (int j = 0; j < list1.length; j++) {
+ if ((list2[i].trim()).equalsIgnoreCase(list1[j].trim())) {
+ match = true;
+ break;
+ }
+ }
+ if (!match)
+ sum.add(list2[i].trim());
+ }
+
+ return (String[]) sum.toArray(new String[sum.size()]);
}
// convenience funtion. Takes a string array and delimiter
// and returns a String with the concatenation
private static String join(String[] s, String delimiter) {
- if (s.length == 0) return "";
+ if (s.length == 0)
+ return "";
StringBuffer buffer = new StringBuffer(s[0]);
if (s.length > 1) {
- for (int i=1; i< s.length; i++) {
+ for (int i = 1; i < s.length; i++) {
buffer.append(delimiter).append(s[i].trim());
}
}
@@ -3005,36 +2995,38 @@ public class PublisherAdminServlet extends AdminServlet {
oldAdded = saveParams.getValue(objName + "Added");
oldDeleted = saveParams.getValue(objName + "Deleted");
- if ((oldOC == null) || (newOC == null)) return;
- if (oldOC.equalsIgnoreCase(newOC)) return;
+ if ((oldOC == null) || (newOC == null))
+ return;
+ if (oldOC.equalsIgnoreCase(newOC))
+ return;
- String [] oldList = oldOC.split(",");
- String [] newList = newOC.split(",");
- String [] deletedList = getExtras(oldList, newList);
- String [] addedList = getExtras(newList, oldList);
+ String[] oldList = oldOC.split(",");
+ String[] newList = newOC.split(",");
+ String[] deletedList = getExtras(oldList, newList);
+ String[] addedList = getExtras(newList, oldList);
// CMS.debug("addedList = " + join(addedList, ","));
// CMS.debug("deletedList = " + join(deletedList, ","));
- if ((addedList.length ==0) && (deletedList.length == 0))
- return; // no changes
+ if ((addedList.length == 0) && (deletedList.length == 0))
+ return; // no changes
if (oldAdded != null) {
// CMS.debug("oldAdded is " + oldAdded);
- String [] oldAddedList = oldAdded.split(",");
+ String[] oldAddedList = oldAdded.split(",");
addedList = joinLists(addedList, oldAddedList);
}
if (oldDeleted != null) {
// CMS.debug("oldDeleted is " + oldDeleted);
- String [] oldDeletedList = oldDeleted.split(",");
+ String[] oldDeletedList = oldDeleted.split(",");
deletedList = joinLists(deletedList, oldDeletedList);
}
String[] addedList1 = getExtras(addedList, deletedList);
String[] deletedList1 = getExtras(deletedList, addedList);
- //create the final strings and write to config
+ // create the final strings and write to config
String addedListStr = join(addedList1, ",");
String deletedListStr = join(deletedList1, ",");
@@ -3046,8 +3038,8 @@ public class PublisherAdminServlet extends AdminServlet {
}
// convenience routine.
- private static void restore(IConfigStore store,
- String id, NameValuePairs saveParams) {
+ private static void restore(IConfigStore store,
+ String id, NameValuePairs saveParams) {
store.removeSubStore(id);
IConfigStore rstore = store.makeSubStore(id);
@@ -3057,7 +3049,7 @@ public class PublisherAdminServlet extends AdminServlet {
String key = (String) keys.nextElement();
String value = saveParams.getValue(key);
- if (value != null)
+ if (value != null)
rstore.put(key, value);
}
}
@@ -3078,7 +3070,7 @@ public class PublisherAdminServlet extends AdminServlet {
public void log(int level, String msg) {
if (mLogger == null)
return;
- mLogger.log(ILogger.EV_SYSTEM,
- ILogger.S_LDAP, level, "PublishingAdminServlet: " + msg);
+ mLogger.log(ILogger.EV_SYSTEM,
+ ILogger.S_LDAP, level, "PublishingAdminServlet: " + msg);
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/admin/RAAdminServlet.java b/pki/base/common/src/com/netscape/cms/servlet/admin/RAAdminServlet.java
index 35bbb91a..ddea62d6 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/admin/RAAdminServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/admin/RAAdminServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.admin;
-
import java.io.IOException;
import java.util.Enumeration;
@@ -36,13 +35,11 @@ import com.netscape.certsrv.common.ScopeDef;
import com.netscape.certsrv.ra.IRegistrationAuthority;
import com.netscape.certsrv.request.IRequestListener;
-
/**
- * A class representings an administration servlet for Registration
- * Authority. This servlet is responsible to serve RA
- * administrative operations such as configuration parameter
- * updates.
- *
+ * A class representings an administration servlet for Registration Authority.
+ * This servlet is responsible to serve RA administrative operations such as
+ * configuration parameter updates.
+ *
* @version $Revision$, $Date$
*/
public class RAAdminServlet extends AdminServlet {
@@ -53,15 +50,17 @@ public class RAAdminServlet extends AdminServlet {
protected static final String PROP_ENABLED = "enabled";
- /*==========================================================
- * variables
- *==========================================================*/
+ /*
+ * ========================================================== variables
+ * ==========================================================
+ */
private final static String INFO = "RAAdminServlet";
private IRegistrationAuthority mRA = null;
- /*==========================================================
- * constructors
- *==========================================================*/
+ /*
+ * ========================================================== constructors
+ * ==========================================================
+ */
/**
* Constructs RA servlet.
@@ -70,9 +69,10 @@ public class RAAdminServlet extends AdminServlet {
super();
}
- /*==========================================================
- * public methods
- *==========================================================*/
+ /*
+ * ========================================================== public methods
+ * ==========================================================
+ */
/**
* Initializes this servlet.
@@ -90,35 +90,35 @@ public class RAAdminServlet extends AdminServlet {
}
/**
- * Serves HTTP request. Each request is authenticated to
- * the authenticate manager.
+ * Serves HTTP request. Each request is authenticated to the authenticate
+ * manager.
*/
public void service(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
+ throws ServletException, IOException {
super.service(req, resp);
- //get all operational flags
+ // get all operational flags
String op = req.getParameter(Constants.OP_TYPE);
String scope = req.getParameter(Constants.OP_SCOPE);
- //check operational flags
+ // check operational flags
if ((op == null) || (scope == null)) {
sendResponse(1, "Invalid Protocol", null, resp);
return;
}
- //authenticate the user
+ // authenticate the user
super.authenticate(req);
- //perform services
+ // perform services
try {
AUTHZ_RES_NAME = "certServer.ra.configuration";
if (op.equals(OpDef.OP_READ)) {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_GENERAL)) {
@@ -144,8 +144,8 @@ public class RAAdminServlet extends AdminServlet {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_GENERAL)) {
@@ -157,7 +157,7 @@ public class RAAdminServlet extends AdminServlet {
} else if (scope.equals(ScopeDef.SC_NOTIFICATION_REQ_COMP)) {
setNotificationReqCompConfig(req, resp);
return;
- }else if (scope.equals(ScopeDef.SC_NOTIFICATION_REV_COMP)) {
+ } else if (scope.equals(ScopeDef.SC_NOTIFICATION_REV_COMP)) {
setNotificationRevCompConfig(req, resp);
return;
} else if (scope.equals(ScopeDef.SC_NOTIFICATION_RIQ)) {
@@ -169,22 +169,23 @@ public class RAAdminServlet extends AdminServlet {
}
}
} catch (Exception e) {
- //System.out.println("XXX >>>" + e.toString() + "<<<");
+ // System.out.println("XXX >>>" + e.toString() + "<<<");
sendResponse(1, "Unknown operation", null, resp);
}
return;
}
- /*==========================================================
- * private methods
- *==========================================================*/
-
+ /*
+ * ========================================================== private
+ * methods==========================================================
+ */
+
/*
* handle getting completion (cert issued) notification config info
*/
private void getNotificationCompConfig(HttpServletRequest req,
- HttpServletResponse resp, IConfigStore rc) throws ServletException,
+ HttpServletResponse resp, IConfigStore rc) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
Enumeration e = req.getParameterNames();
@@ -203,19 +204,19 @@ public class RAAdminServlet extends AdminServlet {
params.add(name, rc.getString(name, ""));
}
- params.add(Constants.PR_ENABLE,
- rc.getString(PROP_ENABLED, Constants.FALSE));
- //System.out.println("Send: "+params.toString());
+ params.add(Constants.PR_ENABLE,
+ rc.getString(PROP_ENABLED, Constants.FALSE));
+ // System.out.println("Send: "+params.toString());
sendResponse(SUCCESS, null, params, resp);
}
private void getNotificationReqCompConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
IConfigStore config = mRA.getConfigStore();
IConfigStore nc =
- config.getSubStore(IRegistrationAuthority.PROP_NOTIFY_SUBSTORE);
+ config.getSubStore(IRegistrationAuthority.PROP_NOTIFY_SUBSTORE);
IConfigStore rc = nc.getSubStore(IRegistrationAuthority.PROP_CERT_ISSUED_SUBSTORE);
@@ -224,12 +225,12 @@ public class RAAdminServlet extends AdminServlet {
}
private void getNotificationRevCompConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
IConfigStore config = mRA.getConfigStore();
IConfigStore nc =
- config.getSubStore(IRegistrationAuthority.PROP_NOTIFY_SUBSTORE);
+ config.getSubStore(IRegistrationAuthority.PROP_NOTIFY_SUBSTORE);
IConfigStore rc = nc.getSubStore(IRegistrationAuthority.PROP_CERT_REVOKED_SUBSTORE);
@@ -241,14 +242,14 @@ public class RAAdminServlet extends AdminServlet {
* handle getting request in queue notification config info
*/
private void getNotificationRIQConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
IConfigStore config = mRA.getConfigStore();
IConfigStore nc =
- config.getSubStore(IRegistrationAuthority.PROP_NOTIFY_SUBSTORE);
+ config.getSubStore(IRegistrationAuthority.PROP_NOTIFY_SUBSTORE);
IConfigStore riq = nc.getSubStore(IRegistrationAuthority.PROP_REQ_IN_Q_SUBSTORE);
@@ -268,9 +269,9 @@ public class RAAdminServlet extends AdminServlet {
params.add(name, riq.getString(name, ""));
}
- params.add(Constants.PR_ENABLE,
- riq.getString(PROP_ENABLED, Constants.FALSE));
- //System.out.println("Send: "+params.toString());
+ params.add(Constants.PR_ENABLE,
+ riq.getString(PROP_ENABLED, Constants.FALSE));
+ // System.out.println("Send: "+params.toString());
sendResponse(SUCCESS, null, params, resp);
}
@@ -278,15 +279,15 @@ public class RAAdminServlet extends AdminServlet {
* handle setting request in queue notification config info
*/
private void setNotificationRIQConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
IConfigStore config = mRA.getConfigStore();
IConfigStore nc =
- config.getSubStore(IRegistrationAuthority.PROP_NOTIFY_SUBSTORE);
+ config.getSubStore(IRegistrationAuthority.PROP_NOTIFY_SUBSTORE);
IConfigStore riq = nc.getSubStore(IRegistrationAuthority.PROP_REQ_IN_Q_SUBSTORE);
- //set rest of the parameters
+ // set rest of the parameters
Enumeration e = req.getParameterNames();
while (e.hasMoreElements()) {
@@ -321,9 +322,9 @@ public class RAAdminServlet extends AdminServlet {
* handle setting request complete notification config info
*/
private void setNotificationCompConfig(HttpServletRequest req,
- HttpServletResponse resp, IConfigStore rc, IRequestListener thisListener) throws ServletException,
+ HttpServletResponse resp, IConfigStore rc, IRequestListener thisListener) throws ServletException,
IOException, EBaseException {
- //set rest of the parameters
+ // set rest of the parameters
Enumeration e = req.getParameterNames();
while (e.hasMoreElements()) {
@@ -355,24 +356,24 @@ public class RAAdminServlet extends AdminServlet {
}
private void setNotificationReqCompConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
IConfigStore config = mRA.getConfigStore();
IConfigStore nc =
- config.getSubStore(IRegistrationAuthority.PROP_NOTIFY_SUBSTORE);
+ config.getSubStore(IRegistrationAuthority.PROP_NOTIFY_SUBSTORE);
IConfigStore rc = nc.getSubStore(IRegistrationAuthority.PROP_CERT_ISSUED_SUBSTORE);
setNotificationCompConfig(req, resp, rc, mRA.getCertIssuedListener());
-
+
}
private void setNotificationRevCompConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
IConfigStore config = mRA.getConfigStore();
IConfigStore nc =
- config.getSubStore(IRegistrationAuthority.PROP_NOTIFY_SUBSTORE);
+ config.getSubStore(IRegistrationAuthority.PROP_NOTIFY_SUBSTORE);
IConfigStore rc = nc.getSubStore(IRegistrationAuthority.PROP_CERT_REVOKED_SUBSTORE);
@@ -380,7 +381,7 @@ public class RAAdminServlet extends AdminServlet {
}
private void getConnectorConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
IConfigStore raConfig = mRA.getConfigStore();
IConfigStore connectorConfig = raConfig.getSubStore("connector");
@@ -395,15 +396,10 @@ public class RAAdminServlet extends AdminServlet {
}
/*
- Enumeration enum = req.getParameterNames();
- NameValuePairs params = new NameValuePairs();
- while (enum.hasMoreElements()) {
- String key = (String)enum.nextElement();
- if (key.equals("RS_ID")) {
- String val = req.getParameter(key);
- if (val.equals("CA Connector"))
- }
- }
+ * Enumeration enum = req.getParameterNames(); NameValuePairs params =
+ * new NameValuePairs(); while (enum.hasMoreElements()) { String key =
+ * (String)enum.nextElement(); if (key.equals("RS_ID")) { String val =
+ * req.getParameter(key); if (val.equals("CA Connector")) } }
*/
Enumeration enum1 = req.getParameterNames();
@@ -427,13 +423,13 @@ public class RAAdminServlet extends AdminServlet {
}
private void setConnectorConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
IConfigStore raConfig = mRA.getConfigStore();
IConfigStore connectorConfig = raConfig.getSubStore("connector");
IConfigStore caConnectorConfig = null;
- // String nickname = raConfig.getString("certNickname", "");
+ // String nickname = raConfig.getString("certNickname", "");
if (isCAConnector(req)) {
caConnectorConfig = connectorConfig.getSubStore("CA");
@@ -455,12 +451,10 @@ public class RAAdminServlet extends AdminServlet {
continue;
if (name.equals(Constants.OP_SCOPE))
continue;
-/*
- if (name.equals("nickName")) {
- caConnectorConfig.putString(name, nickname);
- continue;
- }
-*/
+ /*
+ * if (name.equals("nickName")) {
+ * caConnectorConfig.putString(name, nickname); continue; }
+ */
caConnectorConfig.putString(name, req.getParameter(name));
}
}
@@ -526,50 +520,41 @@ public class RAAdminServlet extends AdminServlet {
return false;
}
- //reading the RA general information
+ // reading the RA general information
private void readGeneralConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
/*
- ISubsystem eeGateway =
- SubsystemRegistry.getInstance().get("eeGateway");
- String value = "false";
- if (eeGateway != null) {
- IConfigStore eeConfig = eeGateway.getConfigStore();
- if (eeConfig != null)
- value = eeConfig.getString("enabled", "true");
- }
- params.add(Constants.PR_EE_ENABLED, value);
+ * ISubsystem eeGateway =
+ * SubsystemRegistry.getInstance().get("eeGateway"); String value =
+ * "false"; if (eeGateway != null) { IConfigStore eeConfig =
+ * eeGateway.getConfigStore(); if (eeConfig != null) value =
+ * eeConfig.getString("enabled", "true"); }
+ * params.add(Constants.PR_EE_ENABLED, value);
*/
-
+
sendResponse(SUCCESS, null, params, resp);
}
- //mdify RA General Information
+ // mdify RA General Information
private void modifyGeneralConfig(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
/*
- ISubsystem eeGateway =
- SubsystemRegistry.getInstance().get("eeGateway");
- IConfigStore eeConfig = null;
- if (eeGateway != null)
- eeConfig = eeGateway.getConfigStore();
-
- Enumeration enum = req.getParameterNames();
- while (enum.hasMoreElements()) {
- String key = (String)enum.nextElement();
- if (key.equals(Constants.PR_EE_ENABLED)) {
- if (eeConfig != null)
- eeConfig.putString("enabled",
- req.getParameter(Constants.PR_EE_ENABLED));
- }
- }
-
+ * ISubsystem eeGateway =
+ * SubsystemRegistry.getInstance().get("eeGateway"); IConfigStore
+ * eeConfig = null; if (eeGateway != null) eeConfig =
+ * eeGateway.getConfigStore();
+ *
+ * Enumeration enum = req.getParameterNames(); while
+ * (enum.hasMoreElements()) { String key = (String)enum.nextElement();
+ * if (key.equals(Constants.PR_EE_ENABLED)) { if (eeConfig != null)
+ * eeConfig.putString("enabled",
+ * req.getParameter(Constants.PR_EE_ENABLED)); } }
*/
sendResponse(RESTART, null, null, resp);
commit(true);
diff --git a/pki/base/common/src/com/netscape/cms/servlet/admin/RegistryAdminServlet.java b/pki/base/common/src/com/netscape/cms/servlet/admin/RegistryAdminServlet.java
index 7605eb2e..36cc7100 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/admin/RegistryAdminServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/admin/RegistryAdminServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.admin;
-
import java.io.IOException;
import java.util.Enumeration;
@@ -41,7 +40,7 @@ import com.netscape.certsrv.registry.IPluginRegistry;
/**
* This implements the administration servlet for registry subsystem.
- *
+ *
* @version $Revision$, $Date$
*/
public class RegistryAdminServlet extends AdminServlet {
@@ -53,8 +52,8 @@ public class RegistryAdminServlet extends AdminServlet {
public final static String PROP_AUTHORITY = "authority";
private final static String INFO = "RegistryAdminServlet";
- private final static String PW_PASSWORD_CACHE_ADD =
- "PASSWORD_CACHE_ADD";
+ private final static String PW_PASSWORD_CACHE_ADD =
+ "PASSWORD_CACHE_ADD";
public final static String PROP_PREDICATE = "predicate";
private IAuthority mAuthority = null;
@@ -104,8 +103,8 @@ public class RegistryAdminServlet extends AdminServlet {
* Serves HTTP admin request.
*/
public void service(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
super.service(req, resp);
super.authenticate(req);
@@ -113,7 +112,7 @@ public class RegistryAdminServlet extends AdminServlet {
AUTHZ_RES_NAME = "certServer.registry.configuration";
String scope = req.getParameter(Constants.OP_SCOPE);
String op = req.getParameter(Constants.OP_TYPE);
-
+
if (scope.equals(ScopeDef.SC_SUPPORTED_CONSTRAINTPOLICIES)) {
if (op.equals(OpDef.OP_READ))
if (!readAuthorize(req, resp))
@@ -124,25 +123,25 @@ public class RegistryAdminServlet extends AdminServlet {
}
}
- private boolean readAuthorize(HttpServletRequest req,
- HttpServletResponse resp) throws IOException {
+ private boolean readAuthorize(HttpServletRequest req,
+ HttpServletResponse resp) throws IOException {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return false;
}
return true;
}
- private boolean modifyAuthorize(HttpServletRequest req,
- HttpServletResponse resp) throws IOException {
+ private boolean modifyAuthorize(HttpServletRequest req,
+ HttpServletResponse resp) throws IOException {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return false;
}
return true;
@@ -152,8 +151,8 @@ public class RegistryAdminServlet extends AdminServlet {
* Process Policy Implementation Management.
*/
public void processImplMgmt(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
// Get operation type
String op = req.getParameter(Constants.OP_TYPE);
String scope = req.getParameter(Constants.OP_SCOPE);
@@ -176,16 +175,16 @@ public class RegistryAdminServlet extends AdminServlet {
addImpl(req, resp);
} else
sendResponse(ERROR, INVALID_POLICY_IMPL_OP,
- null, resp);
+ null, resp);
}
public void addImpl(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
// Get the policy impl id.
String id = req.getParameter(Constants.RS_ID);
- String scope = req.getParameter(Constants.OP_SCOPE);
+ String scope = req.getParameter(Constants.OP_SCOPE);
String classPath = req.getParameter(Constants.PR_POLICY_CLASS);
String desc = req.getParameter(Constants.PR_POLICY_DESC);
@@ -198,17 +197,17 @@ public class RegistryAdminServlet extends AdminServlet {
IPluginInfo info = mRegistry.createPluginInfo(id, desc, classPath);
try {
- mRegistry.addPluginInfo(scope, id, info);
+ mRegistry.addPluginInfo(scope, id, info);
} catch (Exception e) {
- CMS.debug(e.toString());
+ CMS.debug(e.toString());
}
sendResponse(SUCCESS, null, nvp, resp);
}
public void deleteImpl(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
// Get the policy impl id.
String id = req.getParameter(Constants.RS_ID);
@@ -225,13 +224,13 @@ public class RegistryAdminServlet extends AdminServlet {
sendResponse(ERROR, MISSING_POLICY_IMPL_ID, null, resp);
return;
}
-
+
NameValuePairs nvp = new NameValuePairs();
try {
- mRegistry.removePluginInfo(scope, id);
+ mRegistry.removePluginInfo(scope, id);
} catch (Exception e) {
- CMS.debug(e.toString());
+ CMS.debug(e.toString());
}
sendResponse(SUCCESS, null, nvp, resp);
@@ -241,26 +240,26 @@ public class RegistryAdminServlet extends AdminServlet {
* Lists all registered profile impementations
*/
public void listImpls(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
String scope = req.getParameter(Constants.OP_SCOPE);
Enumeration<String> impls = mRegistry.getIds(scope);
NameValuePairs nvp = new NameValuePairs();
while (impls.hasMoreElements()) {
- String id = impls.nextElement();
+ String id = impls.nextElement();
IPluginInfo info = mRegistry.getPluginInfo(scope, id);
- nvp.add(id, info.getClassName() + "," +
- info.getDescription(getLocale(req)) + "," + info.getName(getLocale(req)));
- }
+ nvp.add(id, info.getClassName() + "," +
+ info.getDescription(getLocale(req)) + "," + info.getName(getLocale(req)));
+ }
sendResponse(SUCCESS, null, nvp, resp);
}
- public void getSupportedConstraintPolicies(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException, IOException {
+ public void getSupportedConstraintPolicies(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException, IOException {
String id = req.getParameter(Constants.RS_ID);
if (id == null) {
@@ -273,7 +272,7 @@ public class RegistryAdminServlet extends AdminServlet {
IPluginInfo info = mRegistry.getPluginInfo("defaultPolicy", id);
String className = info.getClassName();
IPolicyDefault policyDefaultClass = (IPolicyDefault)
- Class.forName(className).newInstance();
+ Class.forName(className).newInstance();
if (policyDefaultClass != null) {
Enumeration<String> impls = mRegistry.getIds("constraintPolicy");
@@ -283,14 +282,14 @@ public class RegistryAdminServlet extends AdminServlet {
IPluginInfo constraintInfo = mRegistry.getPluginInfo(
"constraintPolicy", constraintID);
IPolicyConstraint policyConstraintClass = (IPolicyConstraint)
- Class.forName(constraintInfo.getClassName()).newInstance();
+ Class.forName(constraintInfo.getClassName()).newInstance();
CMS.debug("RegistryAdminServlet: getSUpportedConstraint " + constraintInfo.getClassName());
if (policyConstraintClass.isApplicable(policyDefaultClass)) {
CMS.debug("RegistryAdminServlet: getSUpportedConstraint isApplicable " + constraintInfo.getClassName());
nvp.add(constraintID, constraintInfo.getClassName() + "," +
- constraintInfo.getDescription(getLocale(req)) + "," + constraintInfo.getName(getLocale(req)));
+ constraintInfo.getDescription(getLocale(req)) + "," + constraintInfo.getName(getLocale(req)));
}
}
}
@@ -302,8 +301,8 @@ public class RegistryAdminServlet extends AdminServlet {
}
public void getProfileImplConfig(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
+ HttpServletResponse resp)
+ throws ServletException, IOException {
// Get the policy impl id.
String id = req.getParameter(Constants.RS_ID);
@@ -320,7 +319,7 @@ public class RegistryAdminServlet extends AdminServlet {
sendResponse(ERROR, MISSING_POLICY_IMPL_ID, null, resp);
return;
}
-
+
NameValuePairs nvp = new NameValuePairs();
String className = info.getClassName();
@@ -337,19 +336,19 @@ public class RegistryAdminServlet extends AdminServlet {
if (names != null) {
while (names.hasMoreElements()) {
String name = names.nextElement();
- CMS.debug("RegistryAdminServlet: getProfileImpl descriptor " + name);
+ CMS.debug("RegistryAdminServlet: getProfileImpl descriptor " + name);
IDescriptor desc = template.getConfigDescriptor(getLocale(req), name);
if (desc != null) {
- try {
- String value = getNonNull(desc.getSyntax()) + ";" + getNonNull(desc.getConstraint()) + ";" + desc.getDescription(getLocale(req)) + ";" + getNonNull(desc.getDefaultValue());
-
- CMS.debug("RegistryAdminServlet: getProfileImpl " + value);
- nvp.add(name, value);
- } catch (Exception e) {
-
- CMS.debug("RegistryAdminServlet: getProfileImpl skipped descriptor for " + name);
- }
+ try {
+ String value = getNonNull(desc.getSyntax()) + ";" + getNonNull(desc.getConstraint()) + ";" + desc.getDescription(getLocale(req)) + ";" + getNonNull(desc.getDefaultValue());
+
+ CMS.debug("RegistryAdminServlet: getProfileImpl " + value);
+ nvp.add(name, value);
+ } catch (Exception e) {
+
+ CMS.debug("RegistryAdminServlet: getProfileImpl skipped descriptor for " + name);
+ }
} else {
CMS.debug("RegistryAdminServlet: getProfileImpl cannot find descriptor for " + name);
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/admin/UsrGrpAdminServlet.java b/pki/base/common/src/com/netscape/cms/servlet/admin/UsrGrpAdminServlet.java
index fe8d1826..4074ba9f 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/admin/UsrGrpAdminServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/admin/UsrGrpAdminServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.admin;
-
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateExpiredException;
@@ -58,16 +57,14 @@ import com.netscape.certsrv.usrgrp.IUGSubsystem;
import com.netscape.certsrv.usrgrp.IUser;
import com.netscape.cmsutil.util.Cert;
-
/**
- * A class representing an administration servlet for
- * User/Group Manager. It communicates with client
- * SDK to allow remote administration of User/Group
+ * A class representing an administration servlet for User/Group Manager. It
+ * communicates with client SDK to allow remote administration of User/Group
* manager.
- *
- * This servlet will be registered to remote
- * administration subsystem by usrgrp manager.
- *
+ *
+ * This servlet will be registered to remote administration subsystem by usrgrp
+ * manager.
+ *
* @version $Revision$, $Date$
*/
public class UsrGrpAdminServlet extends AdminServlet {
@@ -83,22 +80,21 @@ public class UsrGrpAdminServlet extends AdminServlet {
private final static String RES_OCSP_GROUP = "certServer.ocsp.group";
private final static String RES_TKS_GROUP = "certServer.tks.group";
private final static String SYSTEM_USER = "$System$";
- // private final static String RES_GROUP = "root.common.goldfish";
+ // private final static String RES_GROUP = "root.common.goldfish";
private final static String BACK_SLASH = "\\";
private final static String LOGGING_SIGNED_AUDIT_CONFIG_ROLE =
- "LOGGING_SIGNED_AUDIT_CONFIG_ROLE_3";
+ "LOGGING_SIGNED_AUDIT_CONFIG_ROLE_3";
private IUGSubsystem mMgr = null;
private IAuthzSubsystem mAuthz = null;
- private static String [] mMultiRoleGroupEnforceList = null;
- private final static String MULTI_ROLE_ENABLE= "multiroles.enable";
+ private static String[] mMultiRoleGroupEnforceList = null;
+ private final static String MULTI_ROLE_ENABLE = "multiroles.enable";
private final static String MULTI_ROLE_ENFORCE_GROUP_LIST = "multiroles.false.groupEnforceList";
-
/**
* Constructs User/Group manager servlet.
*/
@@ -126,7 +122,7 @@ public class UsrGrpAdminServlet extends AdminServlet {
* Serves incoming User/Group management request.
*/
public void service(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
+ throws ServletException, IOException {
super.service(req, resp);
String scope = super.getParameter(req, Constants.OP_SCOPE);
@@ -134,9 +130,9 @@ public class UsrGrpAdminServlet extends AdminServlet {
if (op == null) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_INVALID_PROTOCOL"));
- sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_PROTOCOL"),
- null, resp);
+ sendResponse(ERROR,
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_PROTOCOL"),
+ null, resp);
return;
}
@@ -148,63 +144,57 @@ public class UsrGrpAdminServlet extends AdminServlet {
log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_FAIL_AUTHS"));
sendResponse(ERROR, CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHS_FAILED"),
- null, resp);
+ null, resp);
return;
}
// authorization
// temporary test before servlets are exposed with authtoken
/*
- SessionContext sc = SessionContext.getContext();
- AuthToken authToken = (AuthToken) sc.get(SessionContext.AUTH_TOKEN);
-
- AuthzToken authzTok = null;
- CMS.debug("UserGrpAdminServlet: " + CMS.getLogMessage("ADMIN_SRVLT_CHECK_AUTHZ_SUB"));
- // hardcoded for now .. just testing
- try {
- authzTok = mAuthz.authorize("DirAclAuthz", authToken, RES_GROUP, "read");
- } catch (EBaseException e) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_AUTH_CALL_FAIL",e.toString()));
- }
- if (AuthzToken.AUTHZ_STATUS_FAIL.equals(authzTok.get(AuthzToken.TOKEN_AUTHZ_STATUS))) {
- // audit would have been needed here if this weren't just a test...
-
- log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_FAIL_AUTHS"));
-
- sendResponse(ERROR,
- MessageFormatter.getLocalizedString(
- getLocale(req),
- AdminResources.class.getName(),
- AdminResources.SRVLT_FAIL_AUTHS),
- null, resp);
- return;
- }
+ * SessionContext sc = SessionContext.getContext(); AuthToken authToken
+ * = (AuthToken) sc.get(SessionContext.AUTH_TOKEN);
+ *
+ * AuthzToken authzTok = null; CMS.debug("UserGrpAdminServlet: " +
+ * CMS.getLogMessage("ADMIN_SRVLT_CHECK_AUTHZ_SUB")); // hardcoded for
+ * now .. just testing try { authzTok = mAuthz.authorize("DirAclAuthz",
+ * authToken, RES_GROUP, "read"); } catch (EBaseException e) {
+ * log(ILogger.LL_FAILURE,
+ * CMS.getLogMessage("ADMIN_SRVLT_AUTH_CALL_FAIL",e.toString())); } if
+ * (AuthzToken
+ * .AUTHZ_STATUS_FAIL.equals(authzTok.get(AuthzToken.TOKEN_AUTHZ_STATUS
+ * ))) { // audit would have been needed here if this weren't just a
+ * test...
+ *
+ * log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_FAIL_AUTHS"));
+ *
+ * sendResponse(ERROR, MessageFormatter.getLocalizedString(
+ * getLocale(req), AdminResources.class.getName(),
+ * AdminResources.SRVLT_FAIL_AUTHS), null, resp); return; }
*/
-
try {
ISubsystem subsystem = CMS.getSubsystem("ca");
- if (subsystem != null)
+ if (subsystem != null)
AUTHZ_RES_NAME = RES_CA_GROUP;
subsystem = CMS.getSubsystem("ra");
- if (subsystem != null)
+ if (subsystem != null)
AUTHZ_RES_NAME = RES_RA_GROUP;
subsystem = CMS.getSubsystem("kra");
- if (subsystem != null)
+ if (subsystem != null)
AUTHZ_RES_NAME = RES_KRA_GROUP;
subsystem = CMS.getSubsystem("ocsp");
- if (subsystem != null)
+ if (subsystem != null)
AUTHZ_RES_NAME = RES_OCSP_GROUP;
subsystem = CMS.getSubsystem("tks");
- if (subsystem != null)
+ if (subsystem != null)
AUTHZ_RES_NAME = RES_TKS_GROUP;
if (scope != null) {
if (scope.equals(ScopeDef.SC_USER_TYPE)) {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
@@ -216,8 +206,8 @@ public class UsrGrpAdminServlet extends AdminServlet {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_GROUPS)) {
@@ -234,8 +224,8 @@ public class UsrGrpAdminServlet extends AdminServlet {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_GROUPS)) {
@@ -252,8 +242,8 @@ public class UsrGrpAdminServlet extends AdminServlet {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_GROUPS)) {
@@ -270,8 +260,8 @@ public class UsrGrpAdminServlet extends AdminServlet {
mOp = "modify";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_GROUPS)) {
@@ -285,8 +275,8 @@ public class UsrGrpAdminServlet extends AdminServlet {
mOp = "read";
if ((mToken = super.authorize(req)) == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_AUTHZ_FAILED"),
+ null, resp);
return;
}
if (scope.equals(ScopeDef.SC_GROUPS)) {
@@ -296,11 +286,11 @@ public class UsrGrpAdminServlet extends AdminServlet {
findUsers(req, resp);
return;
} else {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_INVALID_OP_SCOPE"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_INVALID_OP_SCOPE"));
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_INVALID_OP_SCOPE"),
+ null, resp);
return;
}
}
@@ -308,21 +298,21 @@ public class UsrGrpAdminServlet extends AdminServlet {
} catch (EBaseException e) {
log(ILogger.LL_FAILURE, e.toString());
sendResponse(ERROR, e.toString(getLocale(req)),
- null, resp);
+ null, resp);
return;
} catch (Exception e) {
log(ILogger.LL_FAILURE, e.toString());
log(ILogger.LL_FAILURE, CMS.getLogMessage(" ADMIN_SRVLT_FAIL_PERFORM"));
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_PERFORM_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_PERFORM_FAILED"),
+ null, resp);
return;
}
}
private void getUserType(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
- IOException, EBaseException {
+ HttpServletResponse resp) throws ServletException,
+ IOException, EBaseException {
String id = super.getParameter(req, Constants.RS_ID);
IUser user = mMgr.getUser(id);
@@ -337,14 +327,14 @@ public class UsrGrpAdminServlet extends AdminServlet {
}
/**
- * Searches for users in LDAP directory. List uids only
- *
+ * Searches for users in LDAP directory. List uids only
+ *
* Request/Response Syntax:
- * http://warp.mcom.com/server/certificate/columbo/design/
- * ui/admin-protocol-definition.html#user-admin
+ * http://warp.mcom.com/server/certificate/columbo/design/
+ * ui/admin-protocol-definition.html#user-admin
*/
- private synchronized void findUsers(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ private synchronized void findUsers(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
@@ -355,7 +345,7 @@ public class UsrGrpAdminServlet extends AdminServlet {
e = mMgr.listUsers("*");
} catch (Exception ex) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_INTERNAL_ERROR"), null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_INTERNAL_ERROR"), null, resp);
return;
}
@@ -383,27 +373,26 @@ public class UsrGrpAdminServlet extends AdminServlet {
}
/**
- * List user information. Certificates covered in a separate
- * protocol for findUserCerts(). List of group memberships are
- * also provided.
- *
+ * List user information. Certificates covered in a separate protocol for
+ * findUserCerts(). List of group memberships are also provided.
+ *
* Request/Response Syntax:
- * http://warp.mcom.com/server/certificate/columbo/design/
- * ui/admin-protocol-definition.html#user-admin
+ * http://warp.mcom.com/server/certificate/columbo/design/
+ * ui/admin-protocol-definition.html#user-admin
*/
- private synchronized void findUser(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ private synchronized void findUser(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
- //get id first
+ // get id first
String id = super.getParameter(req, Constants.RS_ID);
if (id == null) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID"));
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
@@ -416,7 +405,7 @@ public class UsrGrpAdminServlet extends AdminServlet {
} catch (Exception e) {
e.printStackTrace();
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_INTERNAL_ERROR"), null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_INTERNAL_ERROR"), null, resp);
return;
}
@@ -427,7 +416,7 @@ public class UsrGrpAdminServlet extends AdminServlet {
params.add(Constants.PR_USER_STATE, user.getState());
// get list of groups, and get a list of those that this
- // uid belongs to
+ // uid belongs to
Enumeration e = null;
try {
@@ -435,7 +424,7 @@ public class UsrGrpAdminServlet extends AdminServlet {
} catch (Exception ex) {
ex.printStackTrace();
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_INTERNAL_ERROR"), null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_INTERNAL_ERROR"), null, resp);
return;
}
@@ -445,7 +434,7 @@ public class UsrGrpAdminServlet extends AdminServlet {
IGroup group = (IGroup) e.nextElement();
if (group.isMember(id) == true) {
- if (grpString.length()!=0) {
+ if (grpString.length() != 0) {
grpString.append(",");
}
grpString.append(group.getGroupID());
@@ -461,31 +450,31 @@ public class UsrGrpAdminServlet extends AdminServlet {
log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_USER_NOT_EXIST"));
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_USRGRP_SRVLT_USER_NOT_EXIST"), null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_USRGRP_SRVLT_USER_NOT_EXIST"), null, resp);
return;
}
/**
* List user certificate(s)
- *
+ *
* Request/Response Syntax:
- * http://warp.mcom.com/server/certificate/columbo/design/
- * ui/admin-protocol-definition.html#user-admin
+ * http://warp.mcom.com/server/certificate/columbo/design/
+ * ui/admin-protocol-definition.html#user-admin
*/
- private synchronized void findUserCerts(HttpServletRequest req,
- HttpServletResponse resp, Locale clientLocale)
- throws ServletException,
+ private synchronized void findUserCerts(HttpServletRequest req,
+ HttpServletResponse resp, Locale clientLocale)
+ throws ServletException,
IOException, EBaseException {
- //get id first
+ // get id first
String id = super.getParameter(req, Constants.RS_ID);
if (id == null) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID"));
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
@@ -498,7 +487,7 @@ public class UsrGrpAdminServlet extends AdminServlet {
} catch (Exception e) {
e.printStackTrace();
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_USRGRP_SRVLT_USER_NOT_EXIST"), null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_USRGRP_SRVLT_USER_NOT_EXIST"), null, resp);
return;
}
@@ -506,23 +495,23 @@ public class UsrGrpAdminServlet extends AdminServlet {
log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_USER_NOT_EXIST"));
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_USRGRP_SRVLT_USER_NOT_EXIST"), null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_USRGRP_SRVLT_USER_NOT_EXIST"), null, resp);
return;
}
X509Certificate[] certs =
- (X509Certificate[]) user.getX509Certificates();
+ (X509Certificate[]) user.getX509Certificates();
if (certs != null) {
for (int i = 0; i < certs.length; i++) {
ICertPrettyPrint print = CMS.getCertPrettyPrint(certs[i]);
- // add base64 encoding
- String base64 = CMS.getEncodedCert(certs[i]);
-
+ // add base64 encoding
+ String base64 = CMS.getEncodedCert(certs[i]);
+
// pretty print certs
params.add(getCertificateString(certs[i]),
- print.toString(clientLocale) + "\n" + base64);
+ print.toString(clientLocale) + "\n" + base64);
}
sendResponse(SUCCESS, null, params, resp);
return;
@@ -542,18 +531,18 @@ public class UsrGrpAdminServlet extends AdminServlet {
// note that it did not represent a certificate fully
return cert.getVersion() + ";" + cert.getSerialNumber().toString() +
- ";" + cert.getIssuerDN() + ";" + cert.getSubjectDN();
+ ";" + cert.getIssuerDN() + ";" + cert.getSubjectDN();
}
/**
* Searchess for groups in LDAP server
- *
+ *
* Request/Response Syntax:
- * http://warp.mcom.com/server/certificate/columbo/design/
- * ui/admin-protocol-definition.html#group
+ * http://warp.mcom.com/server/certificate/columbo/design/
+ * ui/admin-protocol-definition.html#group
*/
- private synchronized void findGroups(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ private synchronized void findGroups(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
@@ -582,25 +571,24 @@ public class UsrGrpAdminServlet extends AdminServlet {
}
/**
- * finds a group
- * Request/Response Syntax:
- * http://warp.mcom.com/server/certificate/columbo/design/
- * ui/admin-protocol-definition.html#user-admin
+ * finds a group Request/Response Syntax:
+ * http://warp.mcom.com/server/certificate/columbo/design/
+ * ui/admin-protocol-definition.html#user-admin
*/
- private synchronized void findGroup(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ private synchronized void findGroup(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
NameValuePairs params = new NameValuePairs();
- //get id first
+ // get id first
String id = super.getParameter(req, Constants.RS_ID);
if (id == null) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID"));
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
@@ -619,14 +607,14 @@ public class UsrGrpAdminServlet extends AdminServlet {
params.add(Constants.PR_GROUP_GROUP, group.getGroupID());
params.add(Constants.PR_GROUP_DESC,
- group.getDescription());
+ group.getDescription());
Enumeration members = group.getMemberNames();
StringBuffer membersString = new StringBuffer();
if (members != null) {
while (members.hasMoreElements()) {
- if (membersString.length()!=0) {
+ if (membersString.length() != 0) {
membersString.append(", ");
}
@@ -644,7 +632,7 @@ public class UsrGrpAdminServlet extends AdminServlet {
log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_GROUP_NOT_EXIST"));
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_USRGRP_SRVLT_GROUP_NOT_EXIST"), null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_USRGRP_SRVLT_GROUP_NOT_EXIST"), null, resp);
return;
}
@@ -653,24 +641,25 @@ public class UsrGrpAdminServlet extends AdminServlet {
/**
* Adds a new user to LDAP server
* <P>
- *
+ *
* Request/Response Syntax:
- * http://warp.mcom.com/server/certificate/columbo/design/
- * ui/admin-protocol-definition.html#user-admin
+ * http://warp.mcom.com/server/certificate/columbo/design/
+ * ui/admin-protocol-definition.html#user-admin
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring
* role information (anything under users/groups)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
* @exception EBaseException an error has occurred
*/
- private synchronized void addUser(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ private synchronized void addUser(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String auditMessage = null;
@@ -694,8 +683,8 @@ public class UsrGrpAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
@@ -713,8 +702,8 @@ public class UsrGrpAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_RS_ID_BS"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_RS_ID_BS"),
+ null, resp);
return;
}
@@ -732,8 +721,8 @@ public class UsrGrpAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_SPECIAL_ID", id),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_SPECIAL_ID", id),
+ null, resp);
return;
}
@@ -756,7 +745,7 @@ public class UsrGrpAdminServlet extends AdminServlet {
sendResponse(ERROR, msg, null, resp);
return;
- } else
+ } else
user.setFullName(fname);
String email = super.getParameter(req, Constants.PR_USER_EMAIL);
@@ -783,7 +772,7 @@ public class UsrGrpAdminServlet extends AdminServlet {
throw new EUsrGrpException(passwdCheck.getReason(pword));
- //UsrGrpResources.BAD_PASSWD);
+ // UsrGrpResources.BAD_PASSWD);
}
user.setPassword(pword);
@@ -835,10 +824,10 @@ public class UsrGrpAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_USRGRP_USER_ADD_FAILED"), null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_USRGRP_USER_ADD_FAILED"), null, resp);
return;
}
-
+
if (e.hasMoreElements()) {
IGroup group = (IGroup) e.nextElement();
@@ -858,18 +847,18 @@ public class UsrGrpAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_USRGRP_USER_ADD_FAILED"), null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_USRGRP_USER_ADD_FAILED"), null, resp);
return;
}
}
// for audit log
SessionContext sContext = SessionContext.getContext();
String adminId = (String) sContext.get(SessionContext.USER_ID);
-
+
mLogger.log(ILogger.EV_AUDIT, ILogger.S_USRGRP,
- AuditFormat.LEVEL, AuditFormat.ADDUSERGROUPFORMAT,
- new Object[] {adminId, id, groupName}
- );
+ AuditFormat.LEVEL, AuditFormat.ADDUSERGROUPFORMAT,
+ new Object[] { adminId, id, groupName }
+ );
}
NameValuePairs params = new NameValuePairs();
@@ -899,10 +888,10 @@ public class UsrGrpAdminServlet extends AdminServlet {
if (user.getUserID() == null) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_USRGRP_USER_ADD_FAILED_1", "uid"), null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_USRGRP_USER_ADD_FAILED_1", "uid"), null, resp);
} else {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_USRGRP_USER_ADD_FAILED"), null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_USRGRP_USER_ADD_FAILED"), null, resp);
}
return;
} catch (LDAPException e) {
@@ -920,7 +909,7 @@ public class UsrGrpAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_USRGRP_USER_ADD_FAILED"), null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_USRGRP_USER_ADD_FAILED"), null, resp);
return;
} catch (Exception e) {
log(ILogger.LL_FAILURE, e.toString());
@@ -935,7 +924,7 @@ public class UsrGrpAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_USRGRP_USER_ADD_FAILED"), null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_USRGRP_USER_ADD_FAILED"), null, resp);
return;
}
} catch (EBaseException eAudit1) {
@@ -963,41 +952,42 @@ public class UsrGrpAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit2;
// } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
}
}
/**
* Adds a certificate to a user
* <P>
- *
+ *
* Request/Response Syntax:
- * http://warp.mcom.com/server/certificate/columbo/design/
- * ui/admin-protocol-definition.html#user-admin
+ * http://warp.mcom.com/server/certificate/columbo/design/
+ * ui/admin-protocol-definition.html#user-admin
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring
* role information (anything under users/groups)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
* @exception EBaseException an error has occurred
*/
- private synchronized void addUserCert(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ private synchronized void addUserCert(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String auditMessage = null;
@@ -1021,8 +1011,8 @@ public class UsrGrpAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
@@ -1068,7 +1058,7 @@ public class UsrGrpAdminServlet extends AdminServlet {
try {
CryptoManager manager = CryptoManager.getInstance();
-
+
PKCS7 pkcs7 = new PKCS7(p7Cert);
X509Certificate p7certs[] = pkcs7.getCertificates();
@@ -1084,7 +1074,7 @@ public class UsrGrpAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_USRGRP_SRVLT_CERT_ERROR"), null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_USRGRP_SRVLT_CERT_ERROR"), null, resp);
return;
}
// fix for 370099 - cert ordering can not be assumed
@@ -1095,7 +1085,7 @@ public class UsrGrpAdminServlet extends AdminServlet {
// the ordering
if (p7certs[0].getSubjectDN().toString().equals(
p7certs[0].getIssuerDN().toString()) &&
- (p7certs.length == 1)) {
+ (p7certs.length == 1)) {
certs[0] = p7certs[0];
CMS.debug("UsrGrpAdminServlet: " + CMS.getLogMessage("ADMIN_SRVLT_SINGLE_CERT_IMPORT"));
} else if (p7certs[0].getIssuerDN().toString().equals(p7certs[1].getSubjectDN().toString())) {
@@ -1119,7 +1109,7 @@ public class UsrGrpAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_USRGRP_SRVLT_CERT_ERROR"), null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_USRGRP_SRVLT_CERT_ERROR"), null, resp);
return;
}
@@ -1140,8 +1130,8 @@ public class UsrGrpAdminServlet extends AdminServlet {
for (j = jBegin; j < jEnd; j++) {
CMS.debug("UsrGrpAdminServlet: " + CMS.getLogMessage("ADMIN_SRVLT_CERT_IN_CHAIN", String.valueOf(j), String.valueOf(p7certs[j].getSubjectDN())));
org.mozilla.jss.crypto.X509Certificate leafCert =
- null;
-
+ null;
+
leafCert =
manager.importCACertPackage(p7certs[j].getEncoded());
@@ -1152,10 +1142,10 @@ public class UsrGrpAdminServlet extends AdminServlet {
}
if (leafCert instanceof InternalCertificate) {
- ((InternalCertificate) leafCert).setSSLTrust(
- InternalCertificate.VALID_CA |
- InternalCertificate.TRUSTED_CA |
- InternalCertificate.TRUSTED_CLIENT_CA);
+ ((InternalCertificate) leafCert).setSSLTrust(
+ InternalCertificate.VALID_CA |
+ InternalCertificate.TRUSTED_CA |
+ InternalCertificate.TRUSTED_CLIENT_CA);
} else {
log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NOT_INTERNAL_CERT",
String.valueOf(p7certs[j].getSubjectDN())));
@@ -1163,13 +1153,15 @@ public class UsrGrpAdminServlet extends AdminServlet {
}
/*
- } catch (CryptoManager.UserCertConflictException ex) {
- // got a "user cert" in the chain, most likely the CA
- // cert of this instance, which has a private key. Ignore
- log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_PKS7_IGNORED", ex.toString()));
- */
+ * } catch (CryptoManager.UserCertConflictException ex) { //
+ * got a "user cert" in the chain, most likely the CA //
+ * cert of this instance, which has a private key. Ignore
+ * log(ILogger.LL_FAILURE,
+ * CMS.getLogMessage("ADMIN_SRVLT_PKS7_IGNORED",
+ * ex.toString()));
+ */
} catch (Exception ex) {
- //-----
+ // -----
log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_CERT_ERROR", ex.toString()));
// store a message in the signed audit log file
@@ -1182,7 +1174,7 @@ public class UsrGrpAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_USRGRP_SRVLT_CERT_ERROR"), null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_USRGRP_SRVLT_CERT_ERROR"), null, resp);
return;
}
} catch (Exception e) {
@@ -1198,7 +1190,7 @@ public class UsrGrpAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_USRGRP_SRVLT_CERT_O_ERROR"), null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_USRGRP_SRVLT_CERT_O_ERROR"), null, resp);
return;
}
@@ -1236,10 +1228,10 @@ public class UsrGrpAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_USRGRP_SRVLT_CERT_EXPIRED"), null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_USRGRP_SRVLT_CERT_EXPIRED"), null, resp);
return;
} catch (CertificateNotYetValidException e) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_CERT_NOT_YET_VALID",
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_CERT_NOT_YET_VALID",
String.valueOf(certs[0].getSubjectDN())));
// store a message in the signed audit log file
@@ -1252,7 +1244,7 @@ public class UsrGrpAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_USRGRP_SRVLT_CERT_NOT_YET_VALID"), null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_USRGRP_SRVLT_CERT_NOT_YET_VALID"), null, resp);
return;
} catch (LDAPException e) {
@@ -1265,13 +1257,12 @@ public class UsrGrpAdminServlet extends AdminServlet {
audit(auditMessage);
- if (e.getLDAPResultCode() ==
- LDAPException.ATTRIBUTE_OR_VALUE_EXISTS) {
+ if (e.getLDAPResultCode() == LDAPException.ATTRIBUTE_OR_VALUE_EXISTS) {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_USRGRP_SRVLT_USER_CERT_EXISTS"), null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_USRGRP_SRVLT_USER_CERT_EXISTS"), null, resp);
} else {
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_USRGRP_USER_MOD_FAILED"), null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_USRGRP_USER_MOD_FAILED"), null, resp);
}
return;
} catch (Exception e) {
@@ -1287,21 +1278,21 @@ public class UsrGrpAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_USRGRP_USER_MOD_FAILED"), null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_USRGRP_USER_MOD_FAILED"), null, resp);
return;
}
// } catch( EBaseException eAudit1 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit1;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit1;
} catch (IOException eAudit2) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -1315,45 +1306,46 @@ public class UsrGrpAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit2;
// } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
}
}
/**
* Removes a certificate for a user
* <P>
- *
+ *
* Request/Response Syntax:
- * http://warp.mcom.com/server/certificate/columbo/design/
- * ui/admin-protocol-definition.html#user-admin
+ * http://warp.mcom.com/server/certificate/columbo/design/
+ * ui/admin-protocol-definition.html#user-admin
* <P>
- *
+ *
* In this method, "certDN" is actually a combination of version,
- * serialNumber, issuerDN, and SubjectDN.
+ * serialNumber, issuerDN, and SubjectDN.
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring
* role information (anything under users/groups)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
* @exception EBaseException an error has occurred
*/
- private synchronized void modifyUserCert(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ private synchronized void modifyUserCert(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String auditMessage = null;
@@ -1377,8 +1369,8 @@ public class UsrGrpAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
@@ -1431,21 +1423,21 @@ public class UsrGrpAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_USRGRP_USER_MOD_FAILED"), null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_USRGRP_USER_MOD_FAILED"), null, resp);
return;
}
// } catch( EBaseException eAudit1 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit1;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit1;
} catch (IOException eAudit2) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -1459,44 +1451,44 @@ public class UsrGrpAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit2;
// } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
}
}
/**
- * removes a user. user not removed if belongs to any group
- * (Administrators should remove the user from "uniquemember" of
- * any group he/she belongs to before trying to remove the user
- * itself.
+ * removes a user. user not removed if belongs to any group (Administrators
+ * should remove the user from "uniquemember" of any group he/she belongs to
+ * before trying to remove the user itself.
* <P>
- *
+ *
* Request/Response Syntax:
- * http://warp.mcom.com/server/certificate/columbo/design/
- * ui/admin-protocol-definition.html#user-admin
+ * http://warp.mcom.com/server/certificate/columbo/design/
+ * ui/admin-protocol-definition.html#user-admin
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring
* role information (anything under users/groups)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
* @exception EBaseException an error has occurred
*/
- private synchronized void removeUser(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ private synchronized void removeUser(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String auditMessage = null;
@@ -1505,7 +1497,7 @@ public class UsrGrpAdminServlet extends AdminServlet {
// ensure that any low-level exceptions are reported
// to the signed audit log and stored as failures
try {
- //get id first
+ // get id first
String id = super.getParameter(req, Constants.RS_ID);
boolean mustDelete = false;
int index = 0;
@@ -1528,8 +1520,8 @@ public class UsrGrpAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
// get list of groups, and see if uid belongs to any
@@ -1570,8 +1562,8 @@ public class UsrGrpAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_USRGRP_SRVLT_FAIL_USER_RMV_G"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_USRGRP_SRVLT_FAIL_USER_RMV_G"),
+ null, resp);
return;
}
}
@@ -1604,7 +1596,7 @@ public class UsrGrpAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_USRGRP_SRVLT_FAIL_USER_RMV"), null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_USRGRP_SRVLT_FAIL_USER_RMV"), null, resp);
return;
}
} catch (EBaseException eAudit1) {
@@ -1632,41 +1624,42 @@ public class UsrGrpAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit2;
// } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
}
}
/**
* Adds a new group in local scope.
* <P>
- *
+ *
* Request/Response Syntax:
- * http://warp.mcom.com/server/certificate/columbo/design/
- * ui/admin-protocol-definition.html#group
+ * http://warp.mcom.com/server/certificate/columbo/design/
+ * ui/admin-protocol-definition.html#group
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring
* role information (anything under users/groups)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
* @exception EBaseException an error has occurred
*/
- private synchronized void addGroup(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ private synchronized void addGroup(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String auditMessage = null;
@@ -1675,7 +1668,7 @@ public class UsrGrpAdminServlet extends AdminServlet {
// ensure that any low-level exceptions are reported
// to the signed audit log and stored as failures
try {
- //get id first
+ // get id first
String id = super.getParameter(req, Constants.RS_ID);
if (id == null) {
@@ -1691,8 +1684,8 @@ public class UsrGrpAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
@@ -1743,8 +1736,8 @@ public class UsrGrpAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_USRGRP_GROUP_ADD_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_USRGRP_GROUP_ADD_FAILED"),
+ null, resp);
return;
}
} catch (EBaseException eAudit1) {
@@ -1772,41 +1765,42 @@ public class UsrGrpAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit2;
// } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
}
}
/**
* removes a group
* <P>
- *
+ *
* Request/Response Syntax:
- * http://warp.mcom.com/server/certificate/columbo/design/
- * ui/admin-protocol-definition.html#group
+ * http://warp.mcom.com/server/certificate/columbo/design/
+ * ui/admin-protocol-definition.html#group
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring
* role information (anything under users/groups)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
* @exception EBaseException an error has occurred
*/
- private synchronized void removeGroup(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ private synchronized void removeGroup(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String auditMessage = null;
@@ -1815,7 +1809,7 @@ public class UsrGrpAdminServlet extends AdminServlet {
// ensure that any low-level exceptions are reported
// to the signed audit log and stored as failures
try {
- //get id first
+ // get id first
String id = super.getParameter(req, Constants.RS_ID);
if (id == null) {
@@ -1831,8 +1825,8 @@ public class UsrGrpAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
@@ -1875,44 +1869,45 @@ public class UsrGrpAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit2;
// } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
}
}
/**
* modifies a group
* <P>
- *
- * last person of the super power group "Certificate
- * Server Administrators" can never be removed.
+ *
+ * last person of the super power group "Certificate Server Administrators"
+ * can never be removed.
* <P>
- *
- * http://warp.mcom.com/server/certificate/columbo/design/
- * ui/admin-protocol-definition.html#group
+ *
+ * http://warp.mcom.com/server/certificate/columbo/design/
+ * ui/admin-protocol-definition.html#group
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring
* role information (anything under users/groups)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
* @exception EBaseException an error has occurred
*/
- private synchronized void modifyGroup(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ private synchronized void modifyGroup(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String auditMessage = null;
@@ -1921,7 +1916,7 @@ public class UsrGrpAdminServlet extends AdminServlet {
// ensure that any low-level exceptions are reported
// to the signed audit log and stored as failures
try {
- //get id first
+ // get id first
String id = super.getParameter(req, Constants.RS_ID);
if (id == null) {
@@ -1937,8 +1932,8 @@ public class UsrGrpAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
@@ -1968,7 +1963,7 @@ public class UsrGrpAdminServlet extends AdminServlet {
if (multiRole) {
group.addMemberName(memberName);
} else {
- if( isGroupInMultiRoleEnforceList(groupName)) {
+ if (isGroupInMultiRoleEnforceList(groupName)) {
if (!isDuplicate(groupName, memberName)) {
group.addMemberName(memberName);
} else {
@@ -2019,8 +2014,8 @@ public class UsrGrpAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_USRGRP_GROUP_MODIFY_FAILED"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_USRGRP_GROUP_MODIFY_FAILED"),
+ null, resp);
return;
}
} catch (EBaseException eAudit1) {
@@ -2048,50 +2043,49 @@ public class UsrGrpAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit2;
// } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
}
}
- private boolean isGroupInMultiRoleEnforceList(String groupName)
- {
+ private boolean isGroupInMultiRoleEnforceList(String groupName) {
String groupList = null;
if (groupName == null || groupName.equals("")) {
return true;
}
if (mMultiRoleGroupEnforceList == null) {
- try {
- groupList = mConfig.getString(MULTI_ROLE_ENFORCE_GROUP_LIST);
- } catch (Exception e) {
- }
-
- if (groupList != null && !groupList.equals("")) {
- mMultiRoleGroupEnforceList = groupList.split(",");
- for (int j = 0 ; j < mMultiRoleGroupEnforceList.length; j++) {
- mMultiRoleGroupEnforceList[j] = mMultiRoleGroupEnforceList[j].trim();
- }
- }
- }
-
- if (mMultiRoleGroupEnforceList == null)
- return true;
-
- for (int i = 0; i < mMultiRoleGroupEnforceList.length; i++) {
- if (groupName.equals(mMultiRoleGroupEnforceList[i])) {
- return true;
- }
- }
- return false;
+ try {
+ groupList = mConfig.getString(MULTI_ROLE_ENFORCE_GROUP_LIST);
+ } catch (Exception e) {
+ }
+
+ if (groupList != null && !groupList.equals("")) {
+ mMultiRoleGroupEnforceList = groupList.split(",");
+ for (int j = 0; j < mMultiRoleGroupEnforceList.length; j++) {
+ mMultiRoleGroupEnforceList[j] = mMultiRoleGroupEnforceList[j].trim();
+ }
+ }
+ }
+
+ if (mMultiRoleGroupEnforceList == null)
+ return true;
+
+ for (int i = 0; i < mMultiRoleGroupEnforceList.length; i++) {
+ if (groupName.equals(mMultiRoleGroupEnforceList[i])) {
+ return true;
+ }
+ }
+ return false;
}
private boolean isDuplicate(String groupName, String memberName) {
@@ -2100,7 +2094,7 @@ public class UsrGrpAdminServlet extends AdminServlet {
// Let's not mess with users that are already a member of this group
boolean isMember = false;
try {
- isMember = mMgr.isMemberOf(memberName,groupName);
+ isMember = mMgr.isMemberOf(memberName, groupName);
} catch (Exception e) {
}
@@ -2134,24 +2128,25 @@ public class UsrGrpAdminServlet extends AdminServlet {
/**
* Modifies an existing user in local scope.
* <P>
- *
+ *
* Request/Response Syntax:
- * http://warp.mcom.com/server/certificate/columbo/design/
- * ui/admin-protocol-definition.html#user-admin
+ * http://warp.mcom.com/server/certificate/columbo/design/
+ * ui/admin-protocol-definition.html#user-admin
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring
* role information (anything under users/groups)
* </ul>
+ *
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @exception ServletException a servlet error has occurred
* @exception IOException an input/output error has occurred
* @exception EBaseException an error has occurred
*/
- private synchronized void modifyUser(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException,
+ private synchronized void modifyUser(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException,
IOException, EBaseException {
String auditMessage = null;
@@ -2160,7 +2155,7 @@ public class UsrGrpAdminServlet extends AdminServlet {
// ensure that any low-level exceptions are reported
// to the signed audit log and stored as failures
try {
- //get id first
+ // get id first
String id = super.getParameter(req, Constants.RS_ID);
if (id == null) {
@@ -2176,8 +2171,8 @@ public class UsrGrpAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
- null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_ADMIN_SRVLT_NULL_RS_ID"),
+ null, resp);
return;
}
@@ -2186,7 +2181,7 @@ public class UsrGrpAdminServlet extends AdminServlet {
if ((fname == null) || (fname.length() == 0)) {
String msg =
- CMS.getUserMessage(getLocale(req), "CMS_USRGRP_USER_MOD_FAILED", "full name");
+ CMS.getUserMessage(getLocale(req), "CMS_USRGRP_USER_MOD_FAILED", "full name");
log(ILogger.LL_FAILURE, msg);
@@ -2226,7 +2221,7 @@ public class UsrGrpAdminServlet extends AdminServlet {
throw new EUsrGrpException(passwdCheck.getReason(pword));
- //UsrGrpResources.BAD_PASSWD);
+ // UsrGrpResources.BAD_PASSWD);
}
user.setPassword(pword);
@@ -2270,7 +2265,7 @@ public class UsrGrpAdminServlet extends AdminServlet {
audit(auditMessage);
sendResponse(ERROR,
- CMS.getUserMessage(getLocale(req), "CMS_USRGRP_USER_MOD_FAILED"), null, resp);
+ CMS.getUserMessage(getLocale(req), "CMS_USRGRP_USER_MOD_FAILED"), null, resp);
return;
}
} catch (EBaseException eAudit1) {
@@ -2298,17 +2293,17 @@ public class UsrGrpAdminServlet extends AdminServlet {
// rethrow the specific exception to be handled later
throw eAudit2;
// } catch( ServletException eAudit3 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditParams( req ) );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditParams( req ) );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit3;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit3;
}
}
@@ -2316,6 +2311,6 @@ public class UsrGrpAdminServlet extends AdminServlet {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_USRGRP,
- level, "UsrGrpAdminServlet: " + msg);
+ level, "UsrGrpAdminServlet: " + msg);
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/base/CMSServlet.java b/pki/base/common/src/com/netscape/cms/servlet/base/CMSServlet.java
index 696b091e..7df37706 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/base/CMSServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/base/CMSServlet.java
@@ -99,10 +99,9 @@ import com.netscape.cms.servlet.common.ICMSTemplateFiller;
import com.netscape.cms.servlet.common.Utils;
import com.netscape.cmsutil.xml.XMLObject;
-
/**
* This is the base class of all CS servlet.
- *
+ *
* @version $Revision$, $Date$
*/
public abstract class CMSServlet extends HttpServlet {
@@ -127,76 +126,55 @@ public abstract class CMSServlet extends HttpServlet {
public final static String AUTHZ_CONFIG_STORE = "authz";
public final static String AUTHZ_SRC_XML = "web.xml";
public final static String PROP_AUTHZ_MGR = "AuthzMgr";
- public final static String PROP_ACL = "ACLinfo";
+ public final static String PROP_ACL = "ACLinfo";
public final static String AUTHZ_MGR_BASIC = "BasicAclAuthz";
public final static String AUTHZ_MGR_LDAP = "DirAclAuthz";
private final static String FAILED = "1";
private final static String HDR_LANG = "accept-language";
-
- // final error message - if error and exception templates don't work
+
+ // final error message - if error and exception templates don't work
// send out this text string directly to output.
public final static String PROP_FINAL_ERROR_MSG = "finalErrorMsg";
public final static String ERROR_MSG_TOKEN = "$ERROR_MSG";
- public final static String FINAL_ERROR_MSG =
- "<HTML>\n" +
- "<BODY BGCOLOR=white>\n" +
- "<P>\n" +
- "The Certificate System has encountered " +
- "an unrecoverable error.\n" +
- "<P>\n" +
- "Error Message:<BR>\n" +
- "<I>$ERROR_MSG</I>\n" +
- "<P>\n" +
- "Please contact your local administrator for assistance.\n" +
- "</BODY>\n" +
- "</HTML>\n";
+ public final static String FINAL_ERROR_MSG =
+ "<HTML>\n" +
+ "<BODY BGCOLOR=white>\n" +
+ "<P>\n" +
+ "The Certificate System has encountered " +
+ "an unrecoverable error.\n" +
+ "<P>\n" +
+ "Error Message:<BR>\n" +
+ "<I>$ERROR_MSG</I>\n" +
+ "<P>\n" +
+ "Please contact your local administrator for assistance.\n" +
+ "</BODY>\n" +
+ "</HTML>\n";
// properties from configuration.
- protected final static String
- PROP_UNAUTHORIZED_TEMPLATE = "unauthorizedTemplate";
- protected final static String
- UNAUTHORIZED_TEMPLATE = "/GenUnauthorized.template";
- protected final static String
- PROP_SUCCESS_TEMPLATE = "successTemplate";
- protected final static String
- SUCCESS_TEMPLATE = "/GenSuccess.template";
- protected final static String
- PROP_PENDING_TEMPLATE = "pendingTemplate";
- protected final static String
- PENDING_TEMPLATE = "/GenPending.template";
- protected final static String
- PROP_SVC_PENDING_TEMPLATE = "svcpendingTemplate";
- protected final static String
- SVC_PENDING_TEMPLATE = "/GenSvcPending.template";
- protected final static String
- PROP_REJECTED_TEMPLATE = "rejectedTemplate";
- protected final static String
- REJECTED_TEMPLATE = "/GenRejected.template";
- protected final static String
- PROP_ERROR_TEMPLATE = "errorTemplate";
- protected final static String
- ERROR_TEMPLATE = "/GenError.template";
- protected final static String
- PROP_EXCEPTION_TEMPLATE = "unexpectedErrorTemplate";
- protected final static String
- EXCEPTION_TEMPLATE = "/GenUnexpectedError.template";
-
- private final static String
- PROP_UNAUTHOR_TEMPLATE_FILLER = "unauthorizedTemplateFiller";
- protected final static String
- PROP_SUCCESS_TEMPLATE_FILLER = "successTemplateFiller";
- private final static String
- PROP_ERROR_TEMPLATE_FILLER = "errorTemplateFiller";
- private final static String
- PROP_PENDING_TEMPLATE_FILLER = "pendingTemplateFiller";
- private final static String
- PROP_SVC_PENDING_TEMPLATE_FILLER = "svcpendingTemplateFiller";
- private final static String
- PROP_REJECTED_TEMPLATE_FILLER = "rejectedTemplateFiller";
- private final static String
- PROP_EXCEPTION_TEMPLATE_FILLER = "exceptionTemplateFiller";
+ protected final static String PROP_UNAUTHORIZED_TEMPLATE = "unauthorizedTemplate";
+ protected final static String UNAUTHORIZED_TEMPLATE = "/GenUnauthorized.template";
+ protected final static String PROP_SUCCESS_TEMPLATE = "successTemplate";
+ protected final static String SUCCESS_TEMPLATE = "/GenSuccess.template";
+ protected final static String PROP_PENDING_TEMPLATE = "pendingTemplate";
+ protected final static String PENDING_TEMPLATE = "/GenPending.template";
+ protected final static String PROP_SVC_PENDING_TEMPLATE = "svcpendingTemplate";
+ protected final static String SVC_PENDING_TEMPLATE = "/GenSvcPending.template";
+ protected final static String PROP_REJECTED_TEMPLATE = "rejectedTemplate";
+ protected final static String REJECTED_TEMPLATE = "/GenRejected.template";
+ protected final static String PROP_ERROR_TEMPLATE = "errorTemplate";
+ protected final static String ERROR_TEMPLATE = "/GenError.template";
+ protected final static String PROP_EXCEPTION_TEMPLATE = "unexpectedErrorTemplate";
+ protected final static String EXCEPTION_TEMPLATE = "/GenUnexpectedError.template";
+
+ private final static String PROP_UNAUTHOR_TEMPLATE_FILLER = "unauthorizedTemplateFiller";
+ protected final static String PROP_SUCCESS_TEMPLATE_FILLER = "successTemplateFiller";
+ private final static String PROP_ERROR_TEMPLATE_FILLER = "errorTemplateFiller";
+ private final static String PROP_PENDING_TEMPLATE_FILLER = "pendingTemplateFiller";
+ private final static String PROP_SVC_PENDING_TEMPLATE_FILLER = "svcpendingTemplateFiller";
+ private final static String PROP_REJECTED_TEMPLATE_FILLER = "rejectedTemplateFiller";
+ private final static String PROP_EXCEPTION_TEMPLATE_FILLER = "exceptionTemplateFiller";
protected final static String RA_AGENT_GROUP = "Registration Manager Agents";
protected final static String CA_AGENT_GROUP = "Certificate Manager Agents";
@@ -206,25 +184,18 @@ public abstract class CMSServlet extends HttpServlet {
protected final static String ADMIN_GROUP = "Administrators";
// default http params NOT to save in request.(config values added to list )
- private static final String
- PROP_DONT_SAVE_HTTP_PARAMS = "dontSaveHttpParams";
- private static final String[]
- DONT_SAVE_HTTP_PARAMS = { "pwd", "password", "passwd",
+ private static final String PROP_DONT_SAVE_HTTP_PARAMS = "dontSaveHttpParams";
+ private static final String[] DONT_SAVE_HTTP_PARAMS = { "pwd", "password", "passwd",
"challengePassword", "confirmChallengePassword" };
// default http headers to save in request. (config values added to list)
- private static final String
- PROP_SAVE_HTTP_HEADERS = "saveHttpHeaders";
- private static final String[]
- SAVE_HTTP_HEADERS = { "accept-language", "user-agent", };
+ private static final String PROP_SAVE_HTTP_HEADERS = "saveHttpHeaders";
+ private static final String[] SAVE_HTTP_HEADERS = { "accept-language", "user-agent", };
// request prefixes to distinguish from other request attributes.
- public static final String
- PFX_HTTP_HEADER = "HTTP_HEADER";
- public static final String
- PFX_HTTP_PARAM = "HTTP_PARAM";
- public static final String
- PFX_AUTH_TOKEN = "AUTH_TOKEN";
+ public static final String PFX_HTTP_HEADER = "HTTP_HEADER";
+ public static final String PFX_HTTP_PARAM = "HTTP_PARAM";
+ public static final String PFX_AUTH_TOKEN = "AUTH_TOKEN";
/* input http params */
protected final static String AUTHMGR_PARAM = "authenticator";
@@ -232,10 +203,10 @@ public abstract class CMSServlet extends HttpServlet {
/* fixed credential passed to auth managers */
protected final static String CERT_AUTH_CRED = "sslClientCert";
- public static final String CERT_ATTR =
- "javax.servlet.request.X509Certificate";
+ public static final String CERT_ATTR =
+ "javax.servlet.request.X509Certificate";
- // members.
+ // members.
protected boolean mRenderResult = true;
protected String mFinalErrorMsg = FINAL_ERROR_MSG;
@@ -243,7 +214,7 @@ public abstract class CMSServlet extends HttpServlet {
protected ServletConfig mServletConfig = null;
protected ServletContext mServletContext = null;
- private CMSFileLoader mFileLoader = null;
+ private CMSFileLoader mFileLoader = null;
protected Vector<String> mDontSaveHttpParams = new Vector<String>();
protected Vector<String> mSaveHttpHeaders = new Vector<String>();
@@ -251,14 +222,14 @@ public abstract class CMSServlet extends HttpServlet {
protected String mId = null;
protected IConfigStore mConfig = null;
- // the authority, RA, CA, KRA this servlet is serving.
+ // the authority, RA, CA, KRA this servlet is serving.
protected IAuthority mAuthority = null;
protected IRequestQueue mRequestQueue = null;
// system logger.
protected ILogger mLogger = CMS.getLogger();
protected int mLogCategory = ILogger.S_OTHER;
- private MessageDigest mSHADigest = null;
+ private MessageDigest mSHADigest = null;
protected String mGetClientCert = "false";
protected String mAuthMgr = null;
@@ -270,18 +241,18 @@ public abstract class CMSServlet extends HttpServlet {
protected ILogger mSignedAuditLogger = CMS.getSignedAuditLogger();
protected String mOutputTemplatePath = null;
private IUGSubsystem mUG = (IUGSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_UG);
+ CMS.getSubsystem(CMS.SUBSYSTEM_UG);
private final static String LOGGING_SIGNED_AUDIT_AUTH_FAIL =
- "LOGGING_SIGNED_AUDIT_AUTH_FAIL_4";
+ "LOGGING_SIGNED_AUDIT_AUTH_FAIL_4";
private final static String LOGGING_SIGNED_AUDIT_AUTH_SUCCESS =
- "LOGGING_SIGNED_AUDIT_AUTH_SUCCESS_3";
+ "LOGGING_SIGNED_AUDIT_AUTH_SUCCESS_3";
private final static String LOGGING_SIGNED_AUDIT_AUTHZ_FAIL =
- "LOGGING_SIGNED_AUDIT_AUTHZ_FAIL_4";
+ "LOGGING_SIGNED_AUDIT_AUTHZ_FAIL_4";
private final static String LOGGING_SIGNED_AUDIT_AUTHZ_SUCCESS =
- "LOGGING_SIGNED_AUDIT_AUTHZ_SUCCESS_4";
+ "LOGGING_SIGNED_AUDIT_AUTHZ_SUCCESS_4";
private final static String LOGGING_SIGNED_AUDIT_ROLE_ASSUME =
- "LOGGING_SIGNED_AUDIT_ROLE_ASSUME_3";
+ "LOGGING_SIGNED_AUDIT_ROLE_ASSUME_3";
public CMSServlet() {
}
@@ -328,33 +299,33 @@ public abstract class CMSServlet extends HttpServlet {
if (mAuthority != null)
mRequestQueue = mAuthority.getRequestQueue();
- // set default templates.
+ // set default templates.
setDefaultTemplates(sc);
// for logging to the right authority category.
if (mAuthority == null) {
mLogCategory = ILogger.S_OTHER;
} else {
- if (mAuthority instanceof ICertificateAuthority)
+ if (mAuthority instanceof ICertificateAuthority)
mLogCategory = ILogger.S_CA;
- else if (mAuthority instanceof IRegistrationAuthority)
+ else if (mAuthority instanceof IRegistrationAuthority)
mLogCategory = ILogger.S_RA;
- else if (mAuthority instanceof IKeyRecoveryAuthority)
+ else if (mAuthority instanceof IKeyRecoveryAuthority)
mLogCategory = ILogger.S_KRA;
- else
+ else
mLogCategory = ILogger.S_OTHER;
}
try {
- // get final error message.
+ // get final error message.
// used when templates can't even be loaded.
- String eMsg =
- sc.getInitParameter(PROP_FINAL_ERROR_MSG);
+ String eMsg =
+ sc.getInitParameter(PROP_FINAL_ERROR_MSG);
if (eMsg != null)
mFinalErrorMsg = eMsg;
- // get any configured templates.
+ // get any configured templates.
Enumeration<CMSLoadTemplate> templs = mTemplates.elements();
while (templs.hasMoreElements()) {
@@ -363,13 +334,13 @@ public abstract class CMSServlet extends HttpServlet {
if (templ == null || templ.mPropName == null) {
continue;
}
- String tName =
- sc.getInitParameter(templ.mPropName);
+ String tName =
+ sc.getInitParameter(templ.mPropName);
if (tName != null)
templ.mTemplateName = tName;
- String fillerName =
- sc.getInitParameter(templ.mFillerPropName);
+ String fillerName =
+ sc.getInitParameter(templ.mFillerPropName);
if (fillerName != null) {
ICMSTemplateFiller filler = newFillerObject(fillerName);
@@ -379,32 +350,32 @@ public abstract class CMSServlet extends HttpServlet {
}
}
- // get http params NOT to store in a IRequest and
- // get http headers TO store in a IRequest.
+ // get http params NOT to store in a IRequest and
+ // get http headers TO store in a IRequest.
getDontSaveHttpParams(sc);
getSaveHttpHeaders(sc);
} catch (Exception e) {
- // should never occur since we provide defaults above.
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_CONF_TEMP_PARAMS",
- e.toString()));
+ // should never occur since we provide defaults above.
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_CONF_TEMP_PARAMS",
+ e.toString()));
throw new ServletException(e.toString());
}
try {
mSHADigest = MessageDigest.getInstance("SHA1");
} catch (NoSuchAlgorithmException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_CONF_TEMP_PARAMS",
- e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_CONF_TEMP_PARAMS",
+ e.toString()));
throw new ServletException(e.toString());
}
}
-
+
public String getId() {
return mId;
}
-
+
public String getAuthMgr() {
return mAuthMgr;
}
@@ -416,44 +387,43 @@ public abstract class CMSServlet extends HttpServlet {
return false;
}
- public void outputHttpParameters(HttpServletRequest httpReq)
- {
- CMS.debug("CMSServlet:service() uri = " + httpReq.getRequestURI());
+ public void outputHttpParameters(HttpServletRequest httpReq) {
+ CMS.debug("CMSServlet:service() uri = " + httpReq.getRequestURI());
Enumeration<?> paramNames = httpReq.getParameterNames();
while (paramNames.hasMoreElements()) {
- String pn = (String)paramNames.nextElement();
+ String pn = (String) paramNames.nextElement();
// added this facility so that password can be hidden,
- // all sensitive parameters should be prefixed with
+ // all sensitive parameters should be prefixed with
// __ (double underscores); however, in the event that
// a security parameter slips through, we perform multiple
// additional checks to insure that it is NOT displayed
- if( pn.startsWith("__") ||
- pn.endsWith("password") ||
- pn.endsWith("passwd") ||
- pn.endsWith("pwd") ||
- pn.equalsIgnoreCase("admin_password_again") ||
- pn.equalsIgnoreCase("directoryManagerPwd") ||
- pn.equalsIgnoreCase("bindpassword") ||
- pn.equalsIgnoreCase("bindpwd") ||
- pn.equalsIgnoreCase("passwd") ||
- pn.equalsIgnoreCase("password") ||
- pn.equalsIgnoreCase("pin") ||
- pn.equalsIgnoreCase("pwd") ||
- pn.equalsIgnoreCase("pwdagain") ||
- pn.startsWith("p12Password") ||
- pn.equalsIgnoreCase("uPasswd") ) {
- CMS.debug("CMSServlet::service() param name='" + pn +
- "' value='(sensitive)'" );
+ if (pn.startsWith("__") ||
+ pn.endsWith("password") ||
+ pn.endsWith("passwd") ||
+ pn.endsWith("pwd") ||
+ pn.equalsIgnoreCase("admin_password_again") ||
+ pn.equalsIgnoreCase("directoryManagerPwd") ||
+ pn.equalsIgnoreCase("bindpassword") ||
+ pn.equalsIgnoreCase("bindpwd") ||
+ pn.equalsIgnoreCase("passwd") ||
+ pn.equalsIgnoreCase("password") ||
+ pn.equalsIgnoreCase("pin") ||
+ pn.equalsIgnoreCase("pwd") ||
+ pn.equalsIgnoreCase("pwdagain") ||
+ pn.startsWith("p12Password") ||
+ pn.equalsIgnoreCase("uPasswd")) {
+ CMS.debug("CMSServlet::service() param name='" + pn +
+ "' value='(sensitive)'");
} else {
- CMS.debug("CMSServlet::service() param name='" + pn +
- "' value='" + httpReq.getParameter(pn) + "'" );
+ CMS.debug("CMSServlet::service() param name='" + pn +
+ "' value='" + httpReq.getParameter(pn) + "'");
}
}
}
- public void service(HttpServletRequest httpReq,
- HttpServletResponse httpResp)
- throws ServletException, IOException {
+ public void service(HttpServletRequest httpReq,
+ HttpServletResponse httpResp)
+ throws ServletException, IOException {
boolean running_state = CMS.isInRunningState();
@@ -473,16 +443,16 @@ public abstract class CMSServlet extends HttpServlet {
httpReq.setCharacterEncoding("UTF-8");
if (CMS.debugOn()) {
- outputHttpParameters(httpReq);
+ outputHttpParameters(httpReq);
}
CMS.debug("CMSServlet: " + mId + " start to service.");
String className = this.getClass().getName();
- // get a cms request
+ // get a cms request
CMSRequest cmsRequest = newCMSRequest();
- // set argblock
- cmsRequest.setHttpParams(CMS.createArgBlock("http-request-params",toHashtable(httpReq)));
+ // set argblock
+ cmsRequest.setHttpParams(CMS.createArgBlock("http-request-params", toHashtable(httpReq)));
// set http request
cmsRequest.setHttpReq(httpReq);
@@ -516,21 +486,22 @@ public abstract class CMSServlet extends HttpServlet {
renderResult(cmsRequest);
SessionContext.releaseContext();
return;
- }
+ }
long startTime = CMS.getCurrentDate().getTime();
process(cmsRequest);
renderResult(cmsRequest);
Date endDate = CMS.getCurrentDate();
long endTime = endDate.getTime();
if (CMS.debugOn()) {
- CMS.debug(CMS.DEBUG_INFORM, "CMSServlet: curDate=" + endDate + " id=" + mId + " time=" + (endTime - startTime));
+ CMS.debug(CMS.DEBUG_INFORM, "CMSServlet: curDate=" + endDate + " id=" + mId + " time=" + (endTime - startTime));
}
iCommandQueue.unRegisterProccess((Object) cmsRequest, (Object) this);
} catch (EBaseException e) {
iCommandQueue.unRegisterProccess((Object) cmsRequest, (Object) this);
- // ByteArrayOutputStream os = new ByteArrayOutputStream(); for debugging only
+ // ByteArrayOutputStream os = new ByteArrayOutputStream(); for
+ // debugging only
// PrintStream ps = new PrintStream(os);
- //e.printStackTrace(ps);
+ // e.printStackTrace(ps);
log(e.toString());
renderException(cmsRequest, e);
} catch (Exception ex) {
@@ -551,39 +522,38 @@ public abstract class CMSServlet extends HttpServlet {
/**
* Create a new CMSRequest object. This should be overriden by servlets
- * implementing different types of request
- * @return a new CMSRequest object
+ * implementing different types of request
+ *
+ * @return a new CMSRequest object
*/
protected CMSRequest newCMSRequest() {
return new CMSRequest();
}
/**
- * process an HTTP request. Servlets must override this with their
- * own implementation
- * @throws EBaseException if the servlet was unable to satisfactorily
- * process the request
+ * process an HTTP request. Servlets must override this with their own
+ * implementation
+ *
+ * @throws EBaseException if the servlet was unable to satisfactorily
+ * process the request
*/
- protected void process(CMSRequest cmsRequest)
- throws EBaseException
- {
+ protected void process(CMSRequest cmsRequest)
+ throws EBaseException {
}
-
/**
- * Output a template.
- * If an error occurs while outputing the template the exception template
- * is used to display the error.
+ * Output a template. If an error occurs while outputing the template the
+ * exception template is used to display the error.
*
* @param cmsReq the CS request
*/
protected void renderResult(CMSRequest cmsReq)
- throws IOException {
+ throws IOException {
if (!mRenderResult)
return;
Integer status = cmsReq.getStatus();
-
+
CMSLoadTemplate ltempl = (CMSLoadTemplate) mTemplates.get(status);
if (ltempl == null || ltempl.mTemplateName == null) {
@@ -594,13 +564,12 @@ public abstract class CMSServlet extends HttpServlet {
renderTemplate(cmsReq, ltempl.mTemplateName, filler);
}
-
+
private static final String PRESERVED = "preserved";
public static final String TEMPLATE_NAME = "templateName";
-
+
protected void outputArgBlockAsXML(XMLObject xmlObj, Node parent,
- String argBlockName, IArgBlock argBlock)
- {
+ String argBlockName, IArgBlock argBlock) {
Node argBlockContainer = xmlObj.createContainer(parent, argBlockName);
if (argBlock != null) {
@@ -614,15 +583,14 @@ public abstract class CMSServlet extends HttpServlet {
}
}
- protected void outputXML(HttpServletResponse httpResp, CMSTemplateParams params)
- {
+ protected void outputXML(HttpServletResponse httpResp, CMSTemplateParams params) {
XMLObject xmlObj = null;
try {
xmlObj = new XMLObject();
Node root = xmlObj.createRoot("xml");
outputArgBlockAsXML(xmlObj, root, "header", params.getHeader());
- outputArgBlockAsXML(xmlObj, root, "fixed", params.getFixed());
+ outputArgBlockAsXML(xmlObj, root, "fixed", params.getFixed());
Enumeration<IArgBlock> records = params.queryRecords();
Node recordsNode = xmlObj.createContainer(root, "records");
@@ -645,14 +613,14 @@ public abstract class CMSServlet extends HttpServlet {
}
protected void renderTemplate(
- CMSRequest cmsReq, String templateName, ICMSTemplateFiller filler)
- throws IOException {
+ CMSRequest cmsReq, String templateName, ICMSTemplateFiller filler)
+ throws IOException {
try {
IArgBlock httpParams = cmsReq.getHttpParams();
Locale[] locale = new Locale[1];
CMSTemplate template =
- getTemplate(templateName, cmsReq.getHttpReq(), locale);
+ getTemplate(templateName, cmsReq.getHttpReq(), locale);
CMSTemplateParams templateParams = null;
if (filler != null) {
@@ -670,20 +638,20 @@ public abstract class CMSServlet extends HttpServlet {
}
if (httpParams != null) {
- String httpTemplateName =
- httpParams.getValueAsString(
- TEMPLATE_NAME, null);
+ String httpTemplateName =
+ httpParams.getValueAsString(
+ TEMPLATE_NAME, null);
if (httpTemplateName != null) {
templateName = httpTemplateName;
}
}
- if (templateParams == null)
+ if (templateParams == null)
templateParams = new CMSTemplateParams(null, null);
- // #359630
- // inject preserved http parameter into the template
+ // #359630
+ // inject preserved http parameter into the template
if (httpParams != null) {
String preserved = httpParams.getValueAsString(
PRESERVED, null);
@@ -704,40 +672,40 @@ public abstract class CMSServlet extends HttpServlet {
cmsReq.getHttpResp().setContentLength(bos.size());
bos.writeTo(cmsReq.getHttpResp().getOutputStream());
} catch (Exception e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_OUT_TEMPLATE", templateName, e.toString()));
- renderException(cmsReq,
- new ECMSGWException(CMS.getLogMessage("CMSGW_ERROR_DISPLAY_TEMPLATE")));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_OUT_TEMPLATE", templateName, e.toString()));
+ renderException(cmsReq,
+ new ECMSGWException(CMS.getLogMessage("CMSGW_ERROR_DISPLAY_TEMPLATE")));
return;
}
}
/**
- * Output exception (unexpected error) template
- * This is different from other templates in that if an exception occurs
- * while rendering the exception a message is printed out directly.
- * If the message gets an error an IOException is thrown.
- * In others if an exception occurs while rendering the template the
- * exception template (this) is called.
+ * Output exception (unexpected error) template This is different from other
+ * templates in that if an exception occurs while rendering the exception a
+ * message is printed out directly. If the message gets an error an
+ * IOException is thrown. In others if an exception occurs while rendering
+ * the template the exception template (this) is called.
* <p>
+ *
* @param cmsReq the CS request to pass to template filler if any.
* @param e the unexpected exception
*/
- protected void renderException(CMSRequest cmsReq, EBaseException e)
- throws IOException {
+ protected void renderException(CMSRequest cmsReq, EBaseException e)
+ throws IOException {
try {
Locale[] locale = new Locale[1];
- CMSLoadTemplate loadTempl =
- (CMSLoadTemplate) mTemplates.get(CMSRequest.EXCEPTION);
- CMSTemplate template = getTemplate(loadTempl.mTemplateName,
+ CMSLoadTemplate loadTempl =
+ (CMSLoadTemplate) mTemplates.get(CMSRequest.EXCEPTION);
+ CMSTemplate template = getTemplate(loadTempl.mTemplateName,
cmsReq.getHttpReq(), locale);
ICMSTemplateFiller filler = loadTempl.mFiller;
CMSTemplateParams templateParams = null;
// When an exception occurs the exit is non-local which probably
// will leave the requestStatus value set to something other
- // than CMSRequest.EXCEPTION, so force the requestStatus to
- // EXCEPTION since it must be that if we're here.
+ // than CMSRequest.EXCEPTION, so force the requestStatus to
+ // EXCEPTION since it must be that if we're here.
cmsReq.setStatus(CMSRequest.EXCEPTION);
if (filler != null) {
@@ -749,7 +717,7 @@ public abstract class CMSServlet extends HttpServlet {
}
if (e != null) {
templateParams.getFixed().set(
- ICMSTemplateFiller.EXCEPTION, e.toString(locale[0]));
+ ICMSTemplateFiller.EXCEPTION, e.toString(locale[0]));
}
// just output arg blocks as XML
@@ -772,25 +740,25 @@ public abstract class CMSServlet extends HttpServlet {
}
}
- public void renderFinalError(CMSRequest cmsReq, Exception ex)
- throws IOException {
- // this template is the last resort for all other unexpected
- // errors in other templates so we can only output text.
+ public void renderFinalError(CMSRequest cmsReq, Exception ex)
+ throws IOException {
+ // this template is the last resort for all other unexpected
+ // errors in other templates so we can only output text.
HttpServletResponse httpResp = cmsReq.getHttpResp();
httpResp.setContentType("text/html");
ServletOutputStream out = httpResp.getOutputStream();
-
- // replace $ERRORMSG with exception message if included.
+
+ // replace $ERRORMSG with exception message if included.
String finalErrMsg = mFinalErrorMsg;
int tokenIdx = mFinalErrorMsg.indexOf(ERROR_MSG_TOKEN);
if (tokenIdx != -1) {
- finalErrMsg =
+ finalErrMsg =
mFinalErrorMsg.substring(0, tokenIdx) +
- ex.toString() +
- mFinalErrorMsg.substring(
- tokenIdx + ERROR_MSG_TOKEN.length());
+ ex.toString() +
+ mFinalErrorMsg.substring(
+ tokenIdx + ERROR_MSG_TOKEN.length());
}
out.println(finalErrMsg);
return;
@@ -803,31 +771,23 @@ public abstract class CMSServlet extends HttpServlet {
SSLSocket s = null;
/*
- try {
- s = (SSLSocket) ((HTTPRequest) httpReq).getConnection().getSocket();
- } catch (ClassCastException e) {
- CMS.getLogger().log(
- ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_WARN,
- CMS.getLogMessage("CMSGW_SSL_NO_INVALIDATE"));
- // ignore.
- return;
- }
- try {
- s.invalidateSession();
- s.resetHandshake();
- }catch (SocketException se) {
- }
+ * try { s = (SSLSocket) ((HTTPRequest)
+ * httpReq).getConnection().getSocket(); } catch (ClassCastException e)
+ * { CMS.getLogger().log( ILogger.EV_SYSTEM, ILogger.S_OTHER,
+ * ILogger.LL_WARN, CMS.getLogMessage("CMSGW_SSL_NO_INVALIDATE")); //
+ * ignore. return; } try { s.invalidateSession(); s.resetHandshake();
+ * }catch (SocketException se) { }
*/
return;
}
/**
- * construct a authentication credentials to pass into authentication
+ * construct a authentication credentials to pass into authentication
* manager.
*/
public static AuthCredentials getAuthCreds(
- IAuthManager authMgr, IArgBlock argBlock, X509Certificate clientCert)
- throws EBaseException {
+ IAuthManager authMgr, IArgBlock argBlock, X509Certificate clientCert)
+ throws EBaseException {
// get credentials from http parameters.
String[] reqCreds = authMgr.getRequiredCreds();
AuthCredentials creds = new AuthCredentials();
@@ -837,8 +797,8 @@ public abstract class CMSServlet extends HttpServlet {
if (reqCred.equals(IAuthManager.CRED_SSL_CLIENT_CERT)) {
// cert could be null;
- creds.set(reqCred, new X509Certificate[] { clientCert}
- );
+ creds.set(reqCred, new X509Certificate[] { clientCert }
+ );
} else {
String value = argBlock.getValueAsString(reqCred);
@@ -854,19 +814,19 @@ public abstract class CMSServlet extends HttpServlet {
/**
* get ssl client authenticated certificate
*/
- protected X509Certificate
- getSSLClientCertificate(HttpServletRequest httpReq)
- throws EBaseException {
+ protected X509Certificate
+ getSSLClientCertificate(HttpServletRequest httpReq)
+ throws EBaseException {
X509Certificate cert = null;
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_INFO,
- CMS.getLogMessage("CMSGW_GETTING_SSL_CLIENT_CERT"));
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_INFO,
+ CMS.getLogMessage("CMSGW_GETTING_SSL_CLIENT_CERT"));
- // iws60 support Java Servlet Spec V2.2, attribute
+ // iws60 support Java Servlet Spec V2.2, attribute
// javax.servlet.request.X509Certificate now contains array
// of X509Certificates instead of one X509Certificate object
- X509Certificate[] allCerts = (X509Certificate[]) httpReq.getAttribute(CERT_ATTR);
+ X509Certificate[] allCerts = (X509Certificate[]) httpReq.getAttribute(CERT_ATTR);
if (allCerts == null || allCerts.length == 0) {
throw new EBaseException("You did not provide a valid certificate for this operation");
@@ -876,10 +836,10 @@ public abstract class CMSServlet extends HttpServlet {
if (cert == null) {
// just don't have a cert.
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_SSL_CL_CERT_FAIL"));
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_SSL_CL_CERT_FAIL"));
return null;
- }
+ }
// convert to sun's x509 cert interface.
try {
@@ -888,53 +848,53 @@ public abstract class CMSServlet extends HttpServlet {
cert = new X509CertImpl(certEncoded);
} catch (CertificateEncodingException e) {
mLogger.log(
- ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_SSL_CL_CERT_FAIL_ENCODE", e.getMessage()));
+ ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_SSL_CL_CERT_FAIL_ENCODE", e.getMessage()));
return null;
} catch (CertificateException e) {
mLogger.log(
- ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_SSL_CL_CERT_FAIL_DECODE", e.getMessage()));
+ ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_SSL_CL_CERT_FAIL_DECODE", e.getMessage()));
return null;
}
- return cert;
+ return cert;
}
/**
* get a template based on result status.
*/
protected CMSTemplate getTemplate(
- String templateName, HttpServletRequest httpReq, Locale[] locale)
- throws EBaseException, IOException {
+ String templateName, HttpServletRequest httpReq, Locale[] locale)
+ throws EBaseException, IOException {
// this converts to system dependent file seperator char.
if (mServletConfig == null) {
- CMS.debug( "CMSServlet:getTemplate() - mServletConfig is null!" );
+ CMS.debug("CMSServlet:getTemplate() - mServletConfig is null!");
return null;
}
if (mServletConfig.getServletContext() == null) {
}
if (templateName == null) {
}
- String realpath =
- mServletConfig.getServletContext().getRealPath("/" + templateName);
+ String realpath =
+ mServletConfig.getServletContext().getRealPath("/" + templateName);
if (realpath == null) {
mLogger.log(
- ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_NO_FIND_TEMPLATE", templateName));
+ ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_NO_FIND_TEMPLATE", templateName));
throw new ECMSGWException(CMS.getLogMessage("CMSGW_ERROR_DISPLAY_TEMPLATE"));
}
File realpathFile = new File(realpath);
- File templateFile =
- getLangFile(httpReq, realpathFile, locale);
+ File templateFile =
+ getLangFile(httpReq, realpathFile, locale);
String charSet = httpReq.getCharacterEncoding();
if (charSet == null) {
charSet = "UTF8";
}
- CMSTemplate template =
- (CMSTemplate) mFileLoader.getCMSFile(templateFile, charSet);
+ CMSTemplate template =
+ (CMSTemplate) mFileLoader.getCMSFile(templateFile, charSet);
return template;
}
@@ -943,13 +903,13 @@ public abstract class CMSServlet extends HttpServlet {
* log according to authority category.
*/
protected void log(int event, int level, String msg) {
- mLogger.log(event, mLogCategory, level,
- "Servlet " + mId + ": " + msg);
+ mLogger.log(event, mLogCategory, level,
+ "Servlet " + mId + ": " + msg);
}
protected void log(int level, String msg) {
- mLogger.log(ILogger.EV_SYSTEM, mLogCategory, level,
- "Servlet " + mId + ": " + msg);
+ mLogger.log(ILogger.EV_SYSTEM, mLogCategory, level,
+ "Servlet " + mId + ": " + msg);
}
/**
@@ -965,8 +925,8 @@ public abstract class CMSServlet extends HttpServlet {
dontSaveParams = sc.getInitParameter(
PROP_DONT_SAVE_HTTP_PARAMS);
if (dontSaveParams != null) {
- StringTokenizer params =
- new StringTokenizer(dontSaveParams, ",");
+ StringTokenizer params =
+ new StringTokenizer(dontSaveParams, ",");
while (params.hasMoreTokens()) {
String param = params.nextToken();
@@ -976,8 +936,8 @@ public abstract class CMSServlet extends HttpServlet {
}
} catch (Exception e) {
// should never happen
- log(ILogger.LL_WARN,
- CMS.getLogMessage("CMSGW_NO_CONFIG_VALUE", PROP_DONT_SAVE_HTTP_PARAMS, e.toString()));
+ log(ILogger.LL_WARN,
+ CMS.getLogMessage("CMSGW_NO_CONFIG_VALUE", PROP_DONT_SAVE_HTTP_PARAMS, e.toString()));
// default just in case.
for (int i = 0; i < DONT_SAVE_HTTP_PARAMS.length; i++) {
mDontSaveHttpParams.addElement(DONT_SAVE_HTTP_PARAMS[i]);
@@ -997,12 +957,12 @@ public abstract class CMSServlet extends HttpServlet {
}
// now get from config file if there's more.
- String saveHeaders =
- sc.getInitParameter(PROP_SAVE_HTTP_HEADERS);
+ String saveHeaders =
+ sc.getInitParameter(PROP_SAVE_HTTP_HEADERS);
- if (saveHeaders != null) {
- StringTokenizer headers =
- new StringTokenizer(saveHeaders, ",");
+ if (saveHeaders != null) {
+ StringTokenizer headers =
+ new StringTokenizer(saveHeaders, ",");
while (headers.hasMoreTokens()) {
String hdr = headers.nextToken();
@@ -1021,8 +981,8 @@ public abstract class CMSServlet extends HttpServlet {
* save http headers in a IRequest.
*/
protected void saveHttpHeaders(
- HttpServletRequest httpReq, IRequest req)
- throws EBaseException {
+ HttpServletRequest httpReq, IRequest req)
+ throws EBaseException {
Hashtable<String, String> headers = new Hashtable<String, String>();
Enumeration<String> hdrs = mSaveHttpHeaders.elements();
@@ -1041,7 +1001,7 @@ public abstract class CMSServlet extends HttpServlet {
* save http headers in a IRequest.
*/
protected void saveHttpParams(
- IArgBlock httpParams, IRequest req) {
+ IArgBlock httpParams, IRequest req) {
Hashtable<String, String> saveParams = new Hashtable<String, String>();
Enumeration<String> names = httpParams.elements();
@@ -1075,14 +1035,14 @@ public abstract class CMSServlet extends HttpServlet {
* handy routine for getting a cert record given a serial number.
*/
protected ICertRecord getCertRecord(BigInteger serialNo) {
- if (mAuthority == null ||
- !(mAuthority instanceof ICertificateAuthority)) {
- log(ILogger.LL_WARN,
- CMS.getLogMessage("CMSGW_NON_CERT_AUTH"));
+ if (mAuthority == null ||
+ !(mAuthority instanceof ICertificateAuthority)) {
+ log(ILogger.LL_WARN,
+ CMS.getLogMessage("CMSGW_NON_CERT_AUTH"));
return null;
}
- ICertificateRepository certdb =
- (ICertificateRepository) ((ICertificateAuthority) mAuthority).getCertificateRepository();
+ ICertificateRepository certdb =
+ (ICertificateRepository) ((ICertificateAuthority) mAuthority).getCertificateRepository();
if (certdb == null) {
log(ILogger.LL_WARN, CMS.getLogMessage("CMSGW_CERT_DB_NULL", mAuthority.toString()));
@@ -1093,16 +1053,16 @@ public abstract class CMSServlet extends HttpServlet {
try {
certRecord = certdb.readCertificateRecord(serialNo);
} catch (EBaseException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_NO_CERT_REC", serialNo.toString(16), e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_NO_CERT_REC", serialNo.toString(16), e.toString()));
return null;
}
return certRecord;
}
/**
- * handy routine for validating if a cert is from this CA.
- * mAuthority must be a CA.
+ * handy routine for validating if a cert is from this CA. mAuthority must
+ * be a CA.
*/
protected boolean isCertFromCA(X509Certificate cert) {
BigInteger serialno = cert.getSerialNumber();
@@ -1114,8 +1074,8 @@ public abstract class CMSServlet extends HttpServlet {
}
/**
- * handy routine for checking if a list of certs is from this CA.
- * mAuthortiy must be a CA.
+ * handy routine for checking if a list of certs is from this CA. mAuthortiy
+ * must be a CA.
*/
protected boolean areCertsFromCA(X509Certificate[] certs) {
for (int i = certs.length - 1; i >= 0; i--) {
@@ -1126,18 +1086,18 @@ public abstract class CMSServlet extends HttpServlet {
}
/**
- * handy routine for getting a certificate from the certificate
- * repository. mAuthority must be a CA.
+ * handy routine for getting a certificate from the certificate repository.
+ * mAuthority must be a CA.
*/
protected X509Certificate getX509Certificate(BigInteger serialNo) {
- if (mAuthority == null ||
- !(mAuthority instanceof ICertificateAuthority)) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_NOT_CERT_AUTH"));
+ if (mAuthority == null ||
+ !(mAuthority instanceof ICertificateAuthority)) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_NOT_CERT_AUTH"));
return null;
}
- ICertificateRepository certdb =
- (ICertificateRepository) ((ICertificateAuthority) mAuthority).getCertificateRepository();
+ ICertificateRepository certdb =
+ (ICertificateRepository) ((ICertificateAuthority) mAuthority).getCertificateRepository();
if (certdb == null) {
log(ILogger.LL_WARN, CMS.getLogMessage("CMSGW_CERT_DB_NULL", mAuthority.toString()));
@@ -1148,15 +1108,16 @@ public abstract class CMSServlet extends HttpServlet {
try {
cert = certdb.getX509Certificate(serialNo);
} catch (EBaseException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_NO_CERT_REC", serialNo.toString(16), e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_NO_CERT_REC", serialNo.toString(16), e.toString()));
return null;
}
return cert;
}
/**
- * instantiate a new filler from a class name,
+ * instantiate a new filler from a class name,
+ *
* @return null if can't be instantiated, new instance otherwise.
*/
protected ICMSTemplateFiller newFillerObject(String fillerClass) {
@@ -1169,8 +1130,8 @@ public abstract class CMSServlet extends HttpServlet {
if ((e instanceof RuntimeException)) {
throw (RuntimeException) e;
} else {
- log(ILogger.LL_WARN,
- CMS.getLogMessage("CMSGW_CANT_LOAD_FILLER", fillerClass, e.toString()));
+ log(ILogger.LL_WARN,
+ CMS.getLogMessage("CMSGW_CANT_LOAD_FILLER", fillerClass, e.toString()));
return null;
}
}
@@ -1178,18 +1139,17 @@ public abstract class CMSServlet extends HttpServlet {
}
/**
- * set default templates.
- * subclasses can override, and should override at least the success
- * template
+ * set default templates. subclasses can override, and should override at
+ * least the success template
*/
protected void setDefaultTemplates(ServletConfig sc) {
// Subclasses should override these for diff templates and params in
- // their constructors.
- // Set a template name to null to not use these standard ones.
- // When template name is set to null nothing will be displayed.
+ // their constructors.
+ // Set a template name to null to not use these standard ones.
+ // When template name is set to null nothing will be displayed.
// Servlet is assumed to have rendered its own output.
- // The only exception is the unexpected error template where the
- // default one will always be used if template name is null.
+ // The only exception is the unexpected error template where the
+ // default one will always be used if template name is null.
String successTemplate = null;
String errorTemplate = null;
String unauthorizedTemplate = null;
@@ -1210,17 +1170,17 @@ public abstract class CMSServlet extends HttpServlet {
if (successTemplate == null) {
successTemplate = SUCCESS_TEMPLATE;
if (gateway != null)
- //successTemplate = "/"+gateway+successTemplate;
- successTemplate = "/"+gateway+successTemplate;
+ // successTemplate = "/"+gateway+successTemplate;
+ successTemplate = "/" + gateway + successTemplate;
}
errorTemplate = sc.getInitParameter(
PROP_ERROR_TEMPLATE);
if (errorTemplate == null) {
errorTemplate = ERROR_TEMPLATE;
- if (gateway != null)
- //errorTemplate = "/"+gateway+errorTemplate;
- errorTemplate = "/"+gateway+errorTemplate;
+ if (gateway != null)
+ // errorTemplate = "/"+gateway+errorTemplate;
+ errorTemplate = "/" + gateway + errorTemplate;
}
unauthorizedTemplate = sc.getInitParameter(
@@ -1228,8 +1188,8 @@ public abstract class CMSServlet extends HttpServlet {
if (unauthorizedTemplate == null) {
unauthorizedTemplate = UNAUTHORIZED_TEMPLATE;
if (gateway != null)
- //unauthorizedTemplate = "/"+gateway+unauthorizedTemplate;
- unauthorizedTemplate = "/"+gateway+unauthorizedTemplate;
+ // unauthorizedTemplate = "/"+gateway+unauthorizedTemplate;
+ unauthorizedTemplate = "/" + gateway + unauthorizedTemplate;
}
pendingTemplate = sc.getInitParameter(
@@ -1237,8 +1197,8 @@ public abstract class CMSServlet extends HttpServlet {
if (pendingTemplate == null) {
pendingTemplate = PENDING_TEMPLATE;
if (gateway != null)
- //pendingTemplate = "/"+gateway+pendingTemplate;
- pendingTemplate = "/"+gateway+pendingTemplate;
+ // pendingTemplate = "/"+gateway+pendingTemplate;
+ pendingTemplate = "/" + gateway + pendingTemplate;
}
svcpendingTemplate = sc.getInitParameter(
@@ -1246,8 +1206,8 @@ public abstract class CMSServlet extends HttpServlet {
if (svcpendingTemplate == null) {
svcpendingTemplate = SVC_PENDING_TEMPLATE;
if (gateway != null)
- //svcpendingTemplate = "/"+gateway+svcpendingTemplate;
- svcpendingTemplate = "/"+gateway+svcpendingTemplate;
+ // svcpendingTemplate = "/"+gateway+svcpendingTemplate;
+ svcpendingTemplate = "/" + gateway + svcpendingTemplate;
}
rejectedTemplate = sc.getInitParameter(
@@ -1255,8 +1215,8 @@ public abstract class CMSServlet extends HttpServlet {
if (rejectedTemplate == null) {
rejectedTemplate = REJECTED_TEMPLATE;
if (gateway != null)
- //rejectedTemplate = "/"+gateway+rejectedTemplate;
- rejectedTemplate = "/"+gateway+rejectedTemplate;
+ // rejectedTemplate = "/"+gateway+rejectedTemplate;
+ rejectedTemplate = "/" + gateway + rejectedTemplate;
}
unexpectedErrorTemplate = sc.getInitParameter(
@@ -1264,51 +1224,52 @@ public abstract class CMSServlet extends HttpServlet {
if (unexpectedErrorTemplate == null) {
unexpectedErrorTemplate = EXCEPTION_TEMPLATE;
if (gateway != null)
- //unexpectedErrorTemplate = "/"+gateway+unexpectedErrorTemplate;
- unexpectedErrorTemplate = "/"+gateway+unexpectedErrorTemplate;
+ // unexpectedErrorTemplate =
+ // "/"+gateway+unexpectedErrorTemplate;
+ unexpectedErrorTemplate = "/" + gateway + unexpectedErrorTemplate;
}
} catch (Exception e) {
- // this should never happen.
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_IMP_INIT_SERV_ERR", e.toString(),
- mId));
+ // this should never happen.
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_IMP_INIT_SERV_ERR", e.toString(),
+ mId));
}
mTemplates.put(
- CMSRequest.UNAUTHORIZED,
- new CMSLoadTemplate(
- PROP_UNAUTHORIZED_TEMPLATE, PROP_UNAUTHOR_TEMPLATE_FILLER,
- unauthorizedTemplate, null));
+ CMSRequest.UNAUTHORIZED,
+ new CMSLoadTemplate(
+ PROP_UNAUTHORIZED_TEMPLATE, PROP_UNAUTHOR_TEMPLATE_FILLER,
+ unauthorizedTemplate, null));
mTemplates.put(
- CMSRequest.SUCCESS,
- new CMSLoadTemplate(
- PROP_SUCCESS_TEMPLATE, PROP_SUCCESS_TEMPLATE_FILLER,
- successTemplate, new GenSuccessTemplateFiller()));
+ CMSRequest.SUCCESS,
+ new CMSLoadTemplate(
+ PROP_SUCCESS_TEMPLATE, PROP_SUCCESS_TEMPLATE_FILLER,
+ successTemplate, new GenSuccessTemplateFiller()));
mTemplates.put(
- CMSRequest.PENDING,
- new CMSLoadTemplate(
- PROP_PENDING_TEMPLATE, PROP_PENDING_TEMPLATE_FILLER,
- pendingTemplate, new GenPendingTemplateFiller()));
+ CMSRequest.PENDING,
+ new CMSLoadTemplate(
+ PROP_PENDING_TEMPLATE, PROP_PENDING_TEMPLATE_FILLER,
+ pendingTemplate, new GenPendingTemplateFiller()));
mTemplates.put(
- CMSRequest.SVC_PENDING,
- new CMSLoadTemplate(
- PROP_SVC_PENDING_TEMPLATE, PROP_SVC_PENDING_TEMPLATE_FILLER,
- svcpendingTemplate, new GenSvcPendingTemplateFiller()));
+ CMSRequest.SVC_PENDING,
+ new CMSLoadTemplate(
+ PROP_SVC_PENDING_TEMPLATE, PROP_SVC_PENDING_TEMPLATE_FILLER,
+ svcpendingTemplate, new GenSvcPendingTemplateFiller()));
mTemplates.put(
- CMSRequest.REJECTED,
- new CMSLoadTemplate(
- PROP_REJECTED_TEMPLATE, PROP_REJECTED_TEMPLATE_FILLER,
- rejectedTemplate, new GenRejectedTemplateFiller()));
+ CMSRequest.REJECTED,
+ new CMSLoadTemplate(
+ PROP_REJECTED_TEMPLATE, PROP_REJECTED_TEMPLATE_FILLER,
+ rejectedTemplate, new GenRejectedTemplateFiller()));
mTemplates.put(
- CMSRequest.ERROR,
- new CMSLoadTemplate(
- PROP_ERROR_TEMPLATE, PROP_ERROR_TEMPLATE_FILLER,
- errorTemplate, new GenErrorTemplateFiller()));
+ CMSRequest.ERROR,
+ new CMSLoadTemplate(
+ PROP_ERROR_TEMPLATE, PROP_ERROR_TEMPLATE_FILLER,
+ errorTemplate, new GenErrorTemplateFiller()));
mTemplates.put(
- CMSRequest.EXCEPTION,
- new CMSLoadTemplate(
- PROP_EXCEPTION_TEMPLATE, PROP_EXCEPTION_TEMPLATE_FILLER,
- unexpectedErrorTemplate, new GenUnexpectedErrorTemplateFiller()));
+ CMSRequest.EXCEPTION,
+ new CMSLoadTemplate(
+ PROP_EXCEPTION_TEMPLATE, PROP_EXCEPTION_TEMPLATE_FILLER,
+ unexpectedErrorTemplate, new GenUnexpectedErrorTemplateFiller()));
}
/**
@@ -1317,8 +1278,8 @@ public abstract class CMSServlet extends HttpServlet {
public static boolean clientIsNav(HttpServletRequest httpReq) {
String useragent = httpReq.getHeader("user-agent");
- if (useragent.startsWith("Mozilla") &&
- useragent.indexOf("MSIE") == -1)
+ if (useragent.startsWith("Mozilla") &&
+ useragent.indexOf("MSIE") == -1)
return true;
return false;
}
@@ -1339,40 +1300,36 @@ public abstract class CMSServlet extends HttpServlet {
* set using cartman JS. (no other way to tell)
*/
private static String CMMF_RESPONSE = "cmmfResponse";
+
public static boolean doCMMFResponse(IArgBlock httpParams) {
if (httpParams.getValueAsBoolean(CMMF_RESPONSE, false))
return true;
- else
+ else
return false;
}
private static final String IMPORT_CERT = "importCert";
private static final String IMPORT_CHAIN = "importCAChain";
private static final String IMPORT_CERT_MIME_TYPE = "importCertMimeType";
- // default mime type
- private static final String
- NS_X509_USER_CERT = "application/x-x509-user-cert";
- private static final String
- NS_X509_EMAIL_CERT = "application/x-x509-email-cert";
+ // default mime type
+ private static final String NS_X509_USER_CERT = "application/x-x509-user-cert";
+ private static final String NS_X509_EMAIL_CERT = "application/x-x509-email-cert";
// CMC mime types
- public static final String
- SIMPLE_ENROLLMENT_REQUEST = "application/pkcs10";
- public static final String
- SIMPLE_ENROLLMENT_RESPONSE = "application/pkcs7-mime";
- public static final String
- FULL_ENROLLMENT_REQUEST = "application/pkcs7-mime";
- public static final String
- FULL_ENROLLMENT_RESPONSE = "application/pkcs7-mime";
+ public static final String SIMPLE_ENROLLMENT_REQUEST = "application/pkcs10";
+ public static final String SIMPLE_ENROLLMENT_RESPONSE = "application/pkcs7-mime";
+ public static final String FULL_ENROLLMENT_REQUEST = "application/pkcs7-mime";
+ public static final String FULL_ENROLLMENT_RESPONSE = "application/pkcs7-mime";
/**
* handy routine to check if client want full enrollment response
*/
public static String FULL_RESPONSE = "fullResponse";
+
public static boolean doFullResponse(IArgBlock httpParams) {
if (httpParams.getValueAsBoolean(FULL_RESPONSE, false))
return true;
- else
+ else
return false;
}
@@ -1381,23 +1338,23 @@ public abstract class CMSServlet extends HttpServlet {
* @return true if import cert directly is true and import cert.
*/
protected boolean checkImportCertToNav(
- HttpServletResponse httpResp, IArgBlock httpParams, X509CertImpl cert)
- throws EBaseException {
+ HttpServletResponse httpResp, IArgBlock httpParams, X509CertImpl cert)
+ throws EBaseException {
if (!httpParams.getValueAsBoolean(IMPORT_CERT, false)) {
return false;
}
boolean importCAChain =
- httpParams.getValueAsBoolean(IMPORT_CHAIN, true);
+ httpParams.getValueAsBoolean(IMPORT_CHAIN, true);
// XXX Temporary workaround because of problem with passing Mime type
boolean emailCert =
- httpParams.getValueAsBoolean("emailCert", false);
+ httpParams.getValueAsBoolean("emailCert", false);
String importMimeType = (emailCert) ?
- httpParams.getValueAsString(IMPORT_CERT_MIME_TYPE, NS_X509_EMAIL_CERT) :
- httpParams.getValueAsString(IMPORT_CERT_MIME_TYPE, NS_X509_USER_CERT);
+ httpParams.getValueAsString(IMPORT_CERT_MIME_TYPE, NS_X509_EMAIL_CERT) :
+ httpParams.getValueAsString(IMPORT_CERT_MIME_TYPE, NS_X509_USER_CERT);
- // String importMimeType =
- // httpParams.getValueAsString(
- // IMPORT_CERT_MIME_TYPE, NS_X509_USER_CERT);
+ // String importMimeType =
+ // httpParams.getValueAsString(
+ // IMPORT_CERT_MIME_TYPE, NS_X509_USER_CERT);
importCertToNav(httpResp, cert, importMimeType, importCAChain);
return true;
}
@@ -1406,17 +1363,17 @@ public abstract class CMSServlet extends HttpServlet {
* handy routine to import cert to old navigator in nav mime type.
*/
public void importCertToNav(
- HttpServletResponse httpResp, X509CertImpl cert,
- String contentType, boolean importCAChain)
- throws EBaseException {
+ HttpServletResponse httpResp, X509CertImpl cert,
+ String contentType, boolean importCAChain)
+ throws EBaseException {
ServletOutputStream out = null;
byte[] encoding = null;
- CMS.debug("CMSServlet: importCertToNav " +
- "contentType=" + contentType + " " +
+ CMS.debug("CMSServlet: importCertToNav " +
+ "contentType=" + contentType + " " +
"importCAChain=" + importCAChain);
- try {
- out = httpResp.getOutputStream();
+ try {
+ out = httpResp.getOutputStream();
// CA chain.
if (importCAChain) {
CertificateChain caChain = null;
@@ -1426,9 +1383,9 @@ public abstract class CMSServlet extends HttpServlet {
caChain = ((ICertAuthority) mAuthority).getCACertChain();
caCerts = caChain.getChain();
- // set user + CA cert chain in pkcs7
- X509CertImpl[] userChain =
- new X509CertImpl[caCerts.length + 1];
+ // set user + CA cert chain in pkcs7
+ X509CertImpl[] userChain =
+ new X509CertImpl[caCerts.length + 1];
userChain[0] = cert;
int m = 1, n = 0;
@@ -1437,8 +1394,8 @@ public abstract class CMSServlet extends HttpServlet {
userChain[m] = (X509CertImpl) caCerts[n];
/*
- System.out.println(
- m+"th Cert "+userChain[m].toString());
+ * System.out.println(
+ * m+"th Cert "+userChain[m].toString());
*/
}
p7 = new PKCS7(new AlgorithmId[0],
@@ -1456,16 +1413,16 @@ public abstract class CMSServlet extends HttpServlet {
}
httpResp.setContentType(contentType);
out.write(encoding);
- } catch (IOException e) {
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_RET_CERT_IMPORT_ERR", e.toString()));
+ } catch (IOException e) {
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
+ ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_RET_CERT_IMPORT_ERR", e.toString()));
throw new ECMSGWException(
CMS.getLogMessage("CMSGW_ERROR_RETURNING_CERT"));
} catch (CertificateEncodingException e) {
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_NO_ENCODED_IMP_CERT", e.toString()));
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
+ ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_NO_ENCODED_IMP_CERT", e.toString()));
throw new ECMSGWException(
CMS.getLogMessage("CMSGW_ERROR_ENCODING_ISSUED_CERT"));
}
@@ -1511,75 +1468,76 @@ public abstract class CMSServlet extends HttpServlet {
* handy routine for getting agent's relative path
*/
protected String getRelPath(IAuthority authority) {
- if (authority instanceof ICertificateAuthority)
+ if (authority instanceof ICertificateAuthority)
return "ca/";
- else if (authority instanceof IRegistrationAuthority)
+ else if (authority instanceof IRegistrationAuthority)
return "ra/";
- else if (authority instanceof IKeyRecoveryAuthority)
+ else if (authority instanceof IKeyRecoveryAuthority)
return "kra/";
- else
+ else
return "/";
}
/**
- * A system certificate such as the CA signing certificate
- * should not be allowed to delete.
- * The main purpose is to avoid revoking the self signed
+ * A system certificate such as the CA signing certificate should not be
+ * allowed to delete. The main purpose is to avoid revoking the self signed
* CA certificate accidentially.
*/
protected boolean isSystemCertificate(BigInteger serialNo) {
if (!(mAuthority instanceof ICertificateAuthority)) {
return false;
}
- X509Certificate caCert =
- ((ICertificateAuthority)mAuthority).getCACert();
+ X509Certificate caCert =
+ ((ICertificateAuthority) mAuthority).getCACert();
if (caCert != null) {
- /* only check this if we are self-signed */
- if (caCert.getSubjectDN().equals(caCert.getIssuerDN())) {
- if (caCert.getSerialNumber().equals(serialNo)) {
- return true;
+ /* only check this if we are self-signed */
+ if (caCert.getSubjectDN().equals(caCert.getIssuerDN())) {
+ if (caCert.getSerialNumber().equals(serialNo)) {
+ return true;
+ }
}
- }
}
return false;
}
/**
* make a CRL entry from a serial number and revocation reason.
+ *
* @return a RevokedCertImpl that can be entered in a CRL.
*/
protected RevokedCertImpl formCRLEntry(
- BigInteger serialNo, RevocationReason reason)
- throws EBaseException {
+ BigInteger serialNo, RevocationReason reason)
+ throws EBaseException {
CRLReasonExtension reasonExt = new CRLReasonExtension(reason);
CRLExtensions crlentryexts = new CRLExtensions();
try {
crlentryexts.set(CRLReasonExtension.class.getSimpleName(), reasonExt);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_CRL_REASON", reason.toString(), e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_CRL_REASON", reason.toString(), e.toString()));
throw new ECMSGWException(
CMS.getLogMessage("CMSGW_ERROR_SETTING_CRLREASON"));
}
- RevokedCertImpl crlentry =
- new RevokedCertImpl(serialNo, CMS.getCurrentDate(), crlentryexts);
+ RevokedCertImpl crlentry =
+ new RevokedCertImpl(serialNo, CMS.getCurrentDate(), crlentryexts);
return crlentry;
}
/**
* check if a certificate (serial number) is revoked on a CA.
+ *
* @return true if cert is marked revoked in the CA's database.
- * @return false if cert is not marked revoked.
+ * @return false if cert is not marked revoked.
*/
- protected boolean certIsRevoked(BigInteger serialNum)
- throws EBaseException {
+ protected boolean certIsRevoked(BigInteger serialNum)
+ throws EBaseException {
ICertRecord certRecord = getCertRecord(serialNum);
if (certRecord == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_BAD_CERT_SER_NUM", String.valueOf(serialNum)));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_BAD_CERT_SER_NUM", String.valueOf(serialNum)));
throw new ECMSGWException(
CMS.getLogMessage("CMSGW_INVALID_CERT"));
}
@@ -1590,7 +1548,7 @@ public abstract class CMSServlet extends HttpServlet {
public static String generateSalt() {
Random rnd = new Random();
- String salt = new Integer( rnd.nextInt() ).toString();
+ String salt = new Integer(rnd.nextInt()).toString();
return salt;
}
@@ -1608,8 +1566,8 @@ public abstract class CMSServlet extends HttpServlet {
* @param locale array of at least one to be filled with locale found.
*/
public static File getLangFile(
- HttpServletRequest req, File realpathFile, Locale[] locale)
- throws IOException {
+ HttpServletRequest req, File realpathFile, Locale[] locale)
+ throws IOException {
File file = null;
String acceptLang = req.getHeader("accept-language");
@@ -1626,7 +1584,7 @@ public abstract class CMSServlet extends HttpServlet {
}
String name = realpathFile.getName();
- if (name == null) { // filename should never be null.
+ if (name == null) { // filename should never be null.
throw new IOException("file has no name");
}
int i;
@@ -1655,8 +1613,8 @@ public abstract class CMSServlet extends HttpServlet {
}
String langfilepath =
- parent + File.separatorChar +
- lang + File.separatorChar + name;
+ parent + File.separatorChar +
+ lang + File.separatorChar + name;
file = new File(langfilepath);
if (file.exists()) {
@@ -1688,18 +1646,18 @@ public abstract class CMSServlet extends HttpServlet {
}
public IAuthToken authenticate(CMSRequest req)
- throws EBaseException {
+ throws EBaseException {
return authenticate(req, mAuthMgr);
}
public IAuthToken authenticate(HttpServletRequest httpReq)
- throws EBaseException {
+ throws EBaseException {
return authenticate(httpReq, mAuthMgr);
}
- public IAuthToken authenticate(CMSRequest req, String authMgrName)
- throws EBaseException {
- IAuthToken authToken = authenticate(req.getHttpReq(),
+ public IAuthToken authenticate(CMSRequest req, String authMgrName)
+ throws EBaseException {
+ IAuthToken authToken = authenticate(req.getHttpReq(),
authMgrName);
saveAuthToken(authToken, req.getIRequest());
@@ -1709,19 +1667,19 @@ public abstract class CMSServlet extends HttpServlet {
/**
* Authentication
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_AUTH_FAIL used when authentication
- * fails (in case of SSL-client auth, only webserver env can pick up the
- * SSL violation; CS authMgr can pick up cert mis-match, so this event
- * is used)
- * <li>signed.audit LOGGING_SIGNED_AUDIT_AUTH_SUCCESS used when authentication
- * succeeded
+ * fails (in case of SSL-client auth, only webserver env can pick up the SSL
+ * violation; CS authMgr can pick up cert mis-match, so this event is used)
+ * <li>signed.audit LOGGING_SIGNED_AUDIT_AUTH_SUCCESS used when
+ * authentication succeeded
* </ul>
+ *
* @exception EBaseException an error has occurred
*/
public IAuthToken authenticate(HttpServletRequest httpReq, String authMgrName)
- throws EBaseException {
+ throws EBaseException {
String auditMessage = null;
String auditSubjectID = ILogger.UNIDENTIFIED;
String auditAuthMgrID = ILogger.UNIDENTIFIED;
@@ -1750,19 +1708,19 @@ public abstract class CMSServlet extends HttpServlet {
//
// check ssl client authentication if specified.
//
- X509Certificate clientCert = null;
+ X509Certificate clientCert = null;
- if (getClientCert != null && getClientCert.equals("true")) {
+ if (getClientCert != null && getClientCert.equals("true")) {
CMS.debug("CMSServlet: retrieving SSL certificate");
clientCert = getSSLClientCertificate(httpReq);
}
//
// check authentication by auth manager if any.
- //
+ //
if (authMgrName == null) {
- // Fixed Blackflag Bug #613900: Since this code block does
+ // Fixed Blackflag Bug #613900: Since this code block does
// NOT actually constitute an authentication failure, but
// rather the case in which a given servlet has been correctly
// configured to NOT require an authentication manager, the
@@ -1795,10 +1753,10 @@ public abstract class CMSServlet extends HttpServlet {
}
AuthToken authToken = CMSGateway.checkAuthManager(httpReq,
httpArgs,
- clientCert,
+ clientCert,
authMgrName);
if (authToken == null) {
- return null;
+ return null;
}
String userid = authToken.getInString(IAuthToken.USER_ID);
@@ -1807,7 +1765,7 @@ public abstract class CMSServlet extends HttpServlet {
if (userid != null) {
ctx.put(SessionContext.USER_ID, userid);
}
-
+
// reset the "auditSubjectID"
auditSubjectID = auditSubjectID();
@@ -1828,7 +1786,7 @@ public abstract class CMSServlet extends HttpServlet {
auditSubjectID,
ILogger.FAILURE,
auditAuthMgrID,
- auditUID);
+ auditUID);
audit(auditMessage);
// rethrow the specific exception to be handled later
@@ -1837,7 +1795,7 @@ public abstract class CMSServlet extends HttpServlet {
}
public AuthzToken authorize(String authzMgrName, String resource, IAuthToken authToken,
- String exp) throws EBaseException {
+ String exp) throws EBaseException {
AuthzToken authzToken = null;
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -1911,29 +1869,30 @@ public abstract class CMSServlet extends HttpServlet {
/**
* Authorize must occur after Authenticate
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_AUTHZ_FAIL used when authorization
* has failed
- * <li>signed.audit LOGGING_SIGNED_AUDIT_AUTHZ_SUCCESS used when authorization
- * is successful
- * <li>signed.audit LOGGING_SIGNED_AUDIT_ROLE_ASSUME used when user assumes a
- * role (in current CS that's when one accesses a role port)
+ * <li>signed.audit LOGGING_SIGNED_AUDIT_AUTHZ_SUCCESS used when
+ * authorization is successful
+ * <li>signed.audit LOGGING_SIGNED_AUDIT_ROLE_ASSUME used when user assumes
+ * a role (in current CS that's when one accesses a role port)
* </ul>
+ *
* @param authzMgrName string representing the name of the authorization
- * manager
+ * manager
* @param authToken the authentication token
* @param resource a string representing the ACL resource id as defined in
- * the ACL resource list
+ * the ACL resource list
* @param operation a string representing one of the operations as defined
- * within the ACL statement (e. g. - "read" for an ACL statement containing
- * "(read,write)")
+ * within the ACL statement (e. g. - "read" for an ACL statement
+ * containing "(read,write)")
* @exception EBaseException an error has occurred
* @return the authorization token
*/
public AuthzToken authorize(String authzMgrName, IAuthToken authToken,
- String resource, String operation)
- throws EBaseException {
+ String resource, String operation)
+ throws EBaseException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
String auditGroupID = auditGroupID();
@@ -1941,19 +1900,18 @@ public abstract class CMSServlet extends HttpServlet {
String auditACLResource = resource;
String auditOperation = operation;
-
SessionContext auditContext = SessionContext.getExistingContext();
String authManagerId = null;
- if(auditContext != null) {
+ if (auditContext != null) {
authManagerId = (String) auditContext.get(SessionContext.AUTH_MANAGER_ID);
-
- if(authManagerId != null && authManagerId.equals("TokenAuth")) {
- if (auditSubjectID.equals(ILogger.NONROLEUSER) ||
- auditSubjectID.equals(ILogger.UNIDENTIFIED)) {
- CMS.debug("CMSServlet: in authorize... TokenAuth auditSubjectID unavailable, changing to auditGroupID");
- auditID = auditGroupID;
- }
+
+ if (authManagerId != null && authManagerId.equals("TokenAuth")) {
+ if (auditSubjectID.equals(ILogger.NONROLEUSER) ||
+ auditSubjectID.equals(ILogger.UNIDENTIFIED)) {
+ CMS.debug("CMSServlet: in authorize... TokenAuth auditSubjectID unavailable, changing to auditGroupID");
+ auditID = auditGroupID;
+ }
}
}
@@ -1968,7 +1926,7 @@ public abstract class CMSServlet extends HttpServlet {
}
if (authzMgrName == null) {
- // Fixed Blackflag Bug #613900: Since this code block does
+ // Fixed Blackflag Bug #613900: Since this code block does
// NOT actually constitute an authorization failure, but
// rather the case in which a given servlet has been correctly
// configured to NOT require an authorization manager, the
@@ -2073,11 +2031,11 @@ public abstract class CMSServlet extends HttpServlet {
/**
* Signed Audit Log
- *
- * This method is inherited by all extended "CMSServlet"s,
- * and is called to store messages to the signed audit log.
+ *
+ * This method is inherited by all extended "CMSServlet"s, and is called to
+ * store messages to the signed audit log.
* <P>
- *
+ *
* @param msg signed audit log message
*/
protected void audit(String msg) {
@@ -2089,20 +2047,19 @@ public abstract class CMSServlet extends HttpServlet {
}
mSignedAuditLogger.log(ILogger.EV_SIGNED_AUDIT,
- null,
- ILogger.S_SIGNED_AUDIT,
- ILogger.LL_SECURITY,
- msg);
+ null,
+ ILogger.S_SIGNED_AUDIT,
+ ILogger.LL_SECURITY,
+ msg);
}
/**
* Signed Audit Log Subject ID
- *
- * This method is inherited by all extended "CMSServlet"s,
- * and is called to obtain the "SubjectID" for
- * a signed audit log message.
+ *
+ * This method is inherited by all extended "CMSServlet"s, and is called to
+ * obtain the "SubjectID" for a signed audit log message.
* <P>
- *
+ *
* @return id string containing the signed audit log message SubjectID
*/
protected String auditSubjectID() {
@@ -2137,12 +2094,11 @@ public abstract class CMSServlet extends HttpServlet {
/**
* Signed Audit Log Group ID
- *
- * This method is inherited by all extended "CMSServlet"s,
- * and is called to obtain the "gid" for
- * a signed audit log message.
+ *
+ * This method is inherited by all extended "CMSServlet"s, and is called to
+ * obtain the "gid" for a signed audit log message.
* <P>
- *
+ *
* @return id string containing the signed audit log message SubjectID
*/
protected String auditGroupID() {
@@ -2177,14 +2133,14 @@ public abstract class CMSServlet extends HttpServlet {
/**
* Signed Audit Groups
- *
- * This method is called to extract all "groups" associated
- * with the "auditSubjectID()".
+ *
+ * This method is called to extract all "groups" associated with the
+ * "auditSubjectID()".
* <P>
- *
+ *
* @param id string containing the signed audit log message SubjectID
- * @return a delimited string of groups associated
- * with the "auditSubjectID()"
+ * @return a delimited string of groups associated with the
+ * "auditSubjectID()"
*/
private String auditGroups(String SubjectID) {
// if no signed audit object exists, bail
@@ -2193,7 +2149,7 @@ public abstract class CMSServlet extends HttpServlet {
}
if ((SubjectID == null) ||
- (SubjectID.equals(ILogger.UNIDENTIFIED))) {
+ (SubjectID.equals(ILogger.UNIDENTIFIED))) {
return ILogger.SIGNED_AUDIT_EMPTY_VALUE;
}
@@ -2211,7 +2167,7 @@ public abstract class CMSServlet extends HttpServlet {
IGroup group = (IGroup) groups.nextElement();
if (group.isMember(SubjectID) == true) {
- if (membersString.length()!= 0) {
+ if (membersString.length() != 0) {
membersString.append(", ");
}
@@ -2219,7 +2175,7 @@ public abstract class CMSServlet extends HttpServlet {
}
}
- if (membersString.length()!=0) {
+ if (membersString.length() != 0) {
return membersString.toString();
} else {
return ILogger.SIGNED_AUDIT_EMPTY_VALUE;
@@ -2243,18 +2199,18 @@ public abstract class CMSServlet extends HttpServlet {
return locale;
}
- protected void outputResult(HttpServletResponse httpResp,
- String contentType, byte[] content) {
+ protected void outputResult(HttpServletResponse httpResp,
+ String contentType, byte[] content) {
try {
OutputStream os = httpResp.getOutputStream();
-
+
httpResp.setContentType(contentType);
httpResp.setContentLength(content.length);
os.write(content);
os.flush();
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_BAD_SERV_OUT_STREAM", "", e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_BAD_SERV_OUT_STREAM", "", e.toString()));
return;
}
}
@@ -2288,34 +2244,36 @@ public abstract class CMSServlet extends HttpServlet {
} catch (Exception ee) {
CMS.debug("Failed to send XML output to the server.");
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_BAD_SERV_OUT_STREAM", "", ee.toString()));
+ CMS.getLogMessage("CMSGW_ERR_BAD_SERV_OUT_STREAM", "", ee.toString()));
}
}
- protected StringBuffer escapeValueRfc1779(String v, boolean doubleEscape)
- {
+ protected StringBuffer escapeValueRfc1779(String v, boolean doubleEscape) {
StringBuffer result = new StringBuffer();
// Do we need to escape any characters
for (int i = 0; i < v.length(); i++) {
int c = v.charAt(i);
if (c == ',' || c == '=' || c == '+' || c == '<' ||
- c == '>' || c == '#' || c == ';' || c == '\r' ||
- c == '\n' || c == '\\' || c == '"') {
- if ((c == 0x5c) && ((i+1) < v.length())) {
- int nextC = v.charAt(i+1);
+ c == '>' || c == '#' || c == ';' || c == '\r' ||
+ c == '\n' || c == '\\' || c == '"') {
+ if ((c == 0x5c) && ((i + 1) < v.length())) {
+ int nextC = v.charAt(i + 1);
if ((c == 0x5c) && (nextC == ',' || nextC == '=' || nextC == '+' ||
nextC == '<' || nextC == '>' || nextC == '#' ||
nextC == ';' || nextC == '\r' || nextC == '\n' ||
nextC == '\\' || nextC == '"')) {
- if (doubleEscape) result.append('\\');
+ if (doubleEscape)
+ result.append('\\');
} else {
result.append('\\');
- if (doubleEscape) result.append('\\');
+ if (doubleEscape)
+ result.append('\\');
}
} else {
result.append('\\');
- if (doubleEscape) result.append('\\');
+ if (doubleEscape)
+ result.append('\\');
}
}
if (c == '\r') {
@@ -2323,11 +2281,10 @@ public abstract class CMSServlet extends HttpServlet {
} else if (c == '\n') {
result.append("0A");
} else {
- result.append((char)c);
+ result.append((char) c);
}
}
return result;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/base/CMSStartServlet.java b/pki/base/common/src/com/netscape/cms/servlet/base/CMSStartServlet.java
index 64c59c5a..99e12555 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/base/CMSStartServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/base/CMSStartServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.base;
-
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
@@ -32,11 +31,10 @@ import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.cmsutil.util.Utils;
-
/**
- * This servlet is started by the web server at startup, and
- * it starts the CMS framework.
- *
+ * This servlet is started by the web server at startup, and it starts the CMS
+ * framework.
+ *
* @version $Revision$, $Date$
*/
public class CMSStartServlet extends HttpServlet {
@@ -55,34 +53,34 @@ public class CMSStartServlet extends HttpServlet {
if (!f.exists()) {
int index = path.lastIndexOf("CS.cfg");
if (index != -1) {
- old_path = path.substring(0, index)+"CMS.cfg";
+ old_path = path.substring(0, index) + "CMS.cfg";
}
File f1 = new File(old_path);
if (f1.exists()) {
// The following block of code moves "CMS.cfg" to "CS.cfg".
try {
- if( Utils.isNT() ) {
+ if (Utils.isNT()) {
// NT is very picky on the path
- Utils.exec( "copy " +
- f1.getAbsolutePath().replace( '/', '\\' ) +
+ Utils.exec("copy " +
+ f1.getAbsolutePath().replace('/', '\\') +
" " +
- f.getAbsolutePath().replace( '/', '\\' ) );
+ f.getAbsolutePath().replace('/', '\\'));
} else {
// Create a copy of the original file which
// preserves the original file permissions.
- Utils.exec( "cp -p " + f1.getAbsolutePath() + " " +
- f.getAbsolutePath() );
+ Utils.exec("cp -p " + f1.getAbsolutePath() + " " +
+ f.getAbsolutePath());
}
// Remove the original file if and only if
// the backup copy was successful.
- if( f.exists() ) {
+ if (f.exists()) {
f1.delete();
// Make certain that the new file has
// the correct permissions.
- if( !Utils.isNT() ) {
- Utils.exec( "chmod 00660 " + f.getAbsolutePath() );
+ if (!Utils.isNT()) {
+ Utils.exec("chmod 00660 " + f.getAbsolutePath());
}
}
} catch (Exception e) {
@@ -96,7 +94,7 @@ public class CMSStartServlet extends HttpServlet {
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
- throws ServletException, IOException {
+ throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
diff --git a/pki/base/common/src/com/netscape/cms/servlet/base/DisplayHtmlServlet.java b/pki/base/common/src/com/netscape/cms/servlet/base/DisplayHtmlServlet.java
index 8d853f0b..7499c781 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/base/DisplayHtmlServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/base/DisplayHtmlServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.base;
-
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
@@ -33,10 +32,10 @@ import com.netscape.certsrv.logging.ILogger;
import com.netscape.cms.servlet.common.CMSRequest;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
- * This is the servlet that displays the html page for the corresponding input id.
- *
+ * This is the servlet that displays the html page for the corresponding input
+ * id.
+ *
* @version $Revision$, $Date$
*/
public class DisplayHtmlServlet extends CMSServlet {
@@ -55,7 +54,7 @@ public class DisplayHtmlServlet extends CMSServlet {
public void init(ServletConfig sc) throws ServletException {
super.init(sc);
- mHTMLPath = sc.getInitParameter(PROP_HTML_PATH);
+ mHTMLPath = sc.getInitParameter(PROP_HTML_PATH);
mTemplates.remove(CMSRequest.SUCCESS);
}
@@ -68,18 +67,18 @@ public class DisplayHtmlServlet extends CMSServlet {
IAuthToken authToken = authenticate(cmsReq);
try {
- String realpath =
- mServletConfig.getServletContext().getRealPath("/" + mHTMLPath);
+ String realpath =
+ mServletConfig.getServletContext().getRealPath("/" + mHTMLPath);
if (realpath == null) {
mLogger.log(
- ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_NO_FIND_TEMPLATE", mHTMLPath));
- throw new ECMSGWException(CMS.getLogMessage("CMSGW_ERROR_DISPLAY_TEMPLATE")) ;
+ ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_NO_FIND_TEMPLATE", mHTMLPath));
+ throw new ECMSGWException(CMS.getLogMessage("CMSGW_ERROR_DISPLAY_TEMPLATE"));
}
File file = new File(realpath);
long flen = file.length();
- byte[] bin = new byte[(int)flen];
+ byte[] bin = new byte[(int) flen];
FileInputStream ins = new FileInputStream(file);
int len = 0;
@@ -92,9 +91,9 @@ public class DisplayHtmlServlet extends CMSServlet {
ins.close();
bos.close();
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_OUT_TEMPLATE", mHTMLPath, e.toString()));
- throw new ECMSGWException(CMS.getLogMessage("CMSGW_ERROR_DISPLAY_TEMPLATE"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_OUT_TEMPLATE", mHTMLPath, e.toString()));
+ throw new ECMSGWException(CMS.getLogMessage("CMSGW_ERROR_DISPLAY_TEMPLATE"));
}
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/base/DynamicVariablesServlet.java b/pki/base/common/src/com/netscape/cms/servlet/base/DynamicVariablesServlet.java
index 9607fbe2..84fcf347 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/base/DynamicVariablesServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/base/DynamicVariablesServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.base;
-
import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
@@ -39,14 +38,13 @@ import com.netscape.certsrv.authentication.IAuthToken;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
-
/**
- * Return some javascript to the request which contains the list of
- * dynamic data in the CMS system.
+ * Return some javascript to the request which contains the list of dynamic data
+ * in the CMS system.
* <p>
- * This allows the requestor (browser) to make decisions about what
- * to present in the UI, depending on how CMS is configured
- *
+ * This allows the requestor (browser) to make decisions about what to present
+ * in the UI, depending on how CMS is configured
+ *
* @version $Revision$, $Date$
*/
public class DynamicVariablesServlet extends CMSServlet {
@@ -83,10 +81,10 @@ public class DynamicVariablesServlet extends CMSServlet {
private static final String VAR_CLA_CRL_URL_STRING = "clacrlurl()";
private static final Integer VAR_CLA_CRL_URL = Integer.valueOf(6);
private String VAR_CLA_CRL_URL_VALUE = null;
-
+
private String mAuthMgrCacheString = "";
- private long mAuthMgrCacheTime = 0;
- private final int AUTHMGRCACHE = 10; //number of seconds to cache list of
+ private long mAuthMgrCacheTime = 0;
+ private final int AUTHMGRCACHE = 10; // number of seconds to cache list of
// authmanagers for
private Hashtable dynvars = null;
private String mGetClientCert = "false";
@@ -99,7 +97,7 @@ public class DynamicVariablesServlet extends CMSServlet {
IConfigStore config = CMS.getConfigStore().getSubStore(PROP_CLONING);
try {
- mCrlurl =
+ mCrlurl =
config.getString(PROP_CRLURL, "");
} catch (EBaseException e) {
}
@@ -119,33 +117,38 @@ public class DynamicVariablesServlet extends CMSServlet {
/**
* Reads the following variables from the servlet config:
* <ul>
- * <li><strong>AuthMgr</strong> - the authentication manager to use to authenticate the request
- * <li><strong>GetClientCert</strong> - whether to request client auth for this request
- * <li><strong>authority</strong> - the authority (ca, ra, drm) to return to the client
- * <li><strong>dynamicVariables</strong> - a string of the form:
- * serverdate=serverdate(),subsystemname=subsystemname(),
- * http=http(),authmgrs=authmgrs(),clacrlurl=clacrlurl()
+ * <li><strong>AuthMgr</strong> - the authentication manager to use to
+ * authenticate the request
+ * <li><strong>GetClientCert</strong> - whether to request client auth for
+ * this request
+ * <li><strong>authority</strong> - the authority (ca, ra, drm) to return to
+ * the client
+ * <li><strong>dynamicVariables</strong> - a string of the form:
+ * serverdate=serverdate(),subsystemname=subsystemname(),
+ * http=http(),authmgrs=authmgrs(),clacrlurl=clacrlurl()
* </ul>
- * The dynamicVariables string is parsed by splitting on commas.
- * When services, the HTTP request provides a piece of javascript
- * code as follows.
+ * The dynamicVariables string is parsed by splitting on commas. When
+ * services, the HTTP request provides a piece of javascript code as
+ * follows.
* <p>
* Each sub expression "lhs=rhs()" forms a javascript statement of the form
- * <i>lhs=xxx;</i> Where lhs is xxx is the result of 'evaluating' the
- * rhs. The possible values for the rhs() function are:
+ * <i>lhs=xxx;</i> Where lhs is xxx is the result of 'evaluating' the rhs.
+ * The possible values for the rhs() function are:
* <ul>
- * <li><strong>serverdate()</strong> - the timestamp of the server (used to ensure that the client
- * clock is set correctly)
+ * <li><strong>serverdate()</strong> - the timestamp of the server (used to
+ * ensure that the client clock is set correctly)
* <li><strong>subsystemname()</strong>
- * <li><strong>http()</strong> - "true" or "false" - is this an http connection (as opposed to https)
+ * <li><strong>http()</strong> - "true" or "false" - is this an http
+ * connection (as opposed to https)
* <li>authmgrs() - a comma separated list of authentication managers
- * <li>clacrlurl() - the URL to get the CRL from, in the case of a Clone CA. This is
- * defined in the CMS configuration parameter 'cloning.cloneMasterCrlUrl'
+ * <li>clacrlurl() - the URL to get the CRL from, in the case of a Clone CA.
+ * This is defined in the CMS configuration parameter
+ * 'cloning.cloneMasterCrlUrl'
* </ul>
+ *
* @see javax.servlet.Servlet#init(ServletConfig)
*/
-
public void init(ServletConfig sc) throws ServletException {
super.init(sc);
mAuthMgr = sc.getInitParameter(PROP_AUTHMGR);
@@ -194,8 +197,8 @@ public class DynamicVariablesServlet extends CMSServlet {
}
public void service(HttpServletRequest httpReq,
- HttpServletResponse httpResp)
- throws ServletException, IOException {
+ HttpServletResponse httpResp)
+ throws ServletException, IOException {
boolean running_state = CMS.isInRunningState();
if (!running_state)
@@ -214,7 +217,7 @@ public class DynamicVariablesServlet extends CMSServlet {
httpResp.setContentType("application/x-javascript");
httpResp.setHeader("Pragma", "no-cache");
-
+
try {
ServletOutputStream os = httpResp.getOutputStream();
diff --git a/pki/base/common/src/com/netscape/cms/servlet/base/GetStats.java b/pki/base/common/src/com/netscape/cms/servlet/base/GetStats.java
index 3b8f8bd4..b4f1aed1 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/base/GetStats.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/base/GetStats.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.base;
-
import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
@@ -43,10 +42,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* Retrieve information.
- *
+ *
* @version $Revision$, $Date$
*/
public class GetStats extends CMSServlet {
@@ -62,9 +60,9 @@ public class GetStats extends CMSServlet {
}
/**
- * initialize the servlet. This servlet uses the template
- * file "getOCSPInfo.template" to render the result page.
- *
+ * initialize the servlet. This servlet uses the template file
+ * "getOCSPInfo.template" to render the result page.
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -79,14 +77,13 @@ public class GetStats extends CMSServlet {
mTemplates.remove(CMSRequest.SUCCESS);
}
-
/**
- * Process the HTTP request.
- *
+ * Process the HTTP request.
+ *
* @param cmsReq the object holding the request and response information
*/
protected void process(CMSRequest cmsReq)
- throws EBaseException {
+ throws EBaseException {
HttpServletRequest httpReq = cmsReq.getHttpReq();
HttpServletResponse httpResp = cmsReq.getHttpResp();
@@ -98,10 +95,10 @@ public class GetStats extends CMSServlet {
mAuthzResourceName, "read");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -118,10 +115,10 @@ public class GetStats extends CMSServlet {
try {
form = getTemplate(mFormPath, httpReq, locale);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
cmsReq.setStatus(CMSRequest.ERROR);
return;
}
@@ -130,12 +127,12 @@ public class GetStats extends CMSServlet {
IArgBlock fixed = CMS.createArgBlock();
CMSTemplateParams argSet = new CMSTemplateParams(header, fixed);
- IStatsSubsystem statsSub = (IStatsSubsystem)CMS.getSubsystem("stats");
+ IStatsSubsystem statsSub = (IStatsSubsystem) CMS.getSubsystem("stats");
StatsEvent st = statsSub.getMainStatsEvent();
String op = httpReq.getParameter("op");
if (op != null && op.equals("clear")) {
- statsSub.resetCounters();
+ statsSub.resetCounters();
}
header.addStringValue("startTime", statsSub.getStartTime().toString());
@@ -149,43 +146,42 @@ public class GetStats extends CMSServlet {
form.renderOutput(out, argSet);
cmsReq.setStatus(CMSRequest.SUCCESS);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
cmsReq.setStatus(CMSRequest.ERROR);
}
cmsReq.setStatus(CMSRequest.SUCCESS);
return;
}
- public String getSep(int level)
- {
- StringBuffer s = new StringBuffer();
- for (int i = 0; i < level; i++) {
- s.append("-");
- }
- return s.toString();
+ public String getSep(int level) {
+ StringBuffer s = new StringBuffer();
+ for (int i = 0; i < level; i++) {
+ s.append("-");
+ }
+ return s.toString();
}
public void parse(CMSTemplateParams argSet, StatsEvent st, int level) {
Enumeration names = st.getSubEventNames();
while (names.hasMoreElements()) {
- String name = (String)names.nextElement();
- StatsEvent subSt = st.getSubEvent(name);
-
- IArgBlock rarg = CMS.createArgBlock();
- rarg.addStringValue("name", getSep(level) + " " + subSt.getName());
- rarg.addLongValue("noOfOp", subSt.getNoOfOperations());
- rarg.addLongValue("timeTaken", subSt.getTimeTaken());
- rarg.addLongValue("max", subSt.getMax());
- rarg.addLongValue("min", subSt.getMin());
- rarg.addLongValue("percentage", subSt.getPercentage());
- rarg.addLongValue("avg", subSt.getAvg());
- rarg.addLongValue("stddev", subSt.getStdDev());
- argSet.addRepeatRecord(rarg);
-
- parse(argSet, subSt, level+1);
+ String name = (String) names.nextElement();
+ StatsEvent subSt = st.getSubEvent(name);
+
+ IArgBlock rarg = CMS.createArgBlock();
+ rarg.addStringValue("name", getSep(level) + " " + subSt.getName());
+ rarg.addLongValue("noOfOp", subSt.getNoOfOperations());
+ rarg.addLongValue("timeTaken", subSt.getTimeTaken());
+ rarg.addLongValue("max", subSt.getMax());
+ rarg.addLongValue("min", subSt.getMin());
+ rarg.addLongValue("percentage", subSt.getPercentage());
+ rarg.addLongValue("avg", subSt.getAvg());
+ rarg.addLongValue("stddev", subSt.getStdDev());
+ argSet.addRepeatRecord(rarg);
+
+ parse(argSet, subSt, level + 1);
}
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/base/IndexServlet.java b/pki/base/common/src/com/netscape/cms/servlet/base/IndexServlet.java
index 89179b57..a4b72121 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/base/IndexServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/base/IndexServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.base;
-
import java.io.IOException;
import javax.servlet.ServletConfig;
@@ -32,11 +31,9 @@ import com.netscape.cms.servlet.common.CMSRequest;
import com.netscape.cms.servlet.common.ECMSGWException;
import com.netscape.cms.servlet.common.IndexTemplateFiller;
-
/**
- * This is the servlet that builds the index page in
- * various ports.
- *
+ * This is the servlet that builds the index page in various ports.
+ *
* @version $Revision$, $Date$
*/
public class IndexServlet extends CMSServlet {
@@ -68,10 +65,9 @@ public class IndexServlet extends CMSServlet {
mTemplateName = sc.getInitParameter(PROP_TEMPLATE);
/*
- mTemplates.put(CMSRequest.SUCCESS,
- new CMSLoadTemplate(
- PROP_SUCCESS_TEMPLATE, PROP_SUCCESS_TEMPLATE_FILLER,
- mTemplateName, new IndexTemplateFiller()));
+ * mTemplates.put(CMSRequest.SUCCESS, new CMSLoadTemplate(
+ * PROP_SUCCESS_TEMPLATE, PROP_SUCCESS_TEMPLATE_FILLER, mTemplateName,
+ * new IndexTemplateFiller()));
*/
mTemplates.remove(CMSRequest.SUCCESS);
}
@@ -91,26 +87,26 @@ public class IndexServlet extends CMSServlet {
* Serves HTTP request.
*/
public void process(CMSRequest cmsReq) throws EBaseException {
- if (CMSGateway.getEnableAdminEnroll() &&
- mAuthority != null &&
- mAuthority instanceof ICertificateAuthority) {
+ if (CMSGateway.getEnableAdminEnroll() &&
+ mAuthority != null &&
+ mAuthority instanceof ICertificateAuthority) {
try {
cmsReq.getHttpResp().sendRedirect("/ca/adminEnroll.html");
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_FAIL_REDIRECT_ADMIN_ENROLL", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_FAIL_REDIRECT_ADMIN_ENROLL", e.toString()));
throw new ECMSGWException(
CMS.getLogMessage("CMSGW_ERROR_REDIRECTING_ADMINENROLL1",
- e.toString()));
+ e.toString()));
}
return;
} else {
try {
renderTemplate(
- cmsReq, mTemplateName, new IndexTemplateFiller());
+ cmsReq, mTemplateName, new IndexTemplateFiller());
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_FAIL_RENDER_TEMPLATE", mTemplateName, e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_FAIL_RENDER_TEMPLATE", mTemplateName, e.toString()));
throw new ECMSGWException(
CMS.getLogMessage("CMSG_ERROR_DISPLAY_TEMPLATE"));
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/base/PortsServlet.java b/pki/base/common/src/com/netscape/cms/servlet/base/PortsServlet.java
index 4c3dec80..6c84b88d 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/base/PortsServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/base/PortsServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.base;
-
import java.io.IOException;
import javax.servlet.ServletConfig;
@@ -34,7 +33,7 @@ import com.netscape.cmsutil.xml.XMLObject;
/**
* This servlet returns port information.
- *
+ *
* @version $Revision$, $Date$
*/
public class PortsServlet extends CMSServlet {
@@ -50,7 +49,7 @@ public class PortsServlet extends CMSServlet {
public void init(ServletConfig sc) throws ServletException {
super.init(sc);
- // override these to output directly ourselves.
+ // override these to output directly ourselves.
mTemplates.remove(CMSRequest.SUCCESS);
mTemplates.remove(CMSRequest.ERROR);
}
@@ -67,10 +66,10 @@ public class PortsServlet extends CMSServlet {
String port = null;
if (secure.equals("true"))
- port = CMS.getEESSLPort();
+ port = CMS.getEESSLPort();
else
port = CMS.getEENonSSLPort();
-
+
try {
XMLObject xmlObj = null;
xmlObj = new XMLObject();
diff --git a/pki/base/common/src/com/netscape/cms/servlet/base/ProxyServlet.java b/pki/base/common/src/com/netscape/cms/servlet/base/ProxyServlet.java
index 15bfb306..382d8821 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/base/ProxyServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/base/ProxyServlet.java
@@ -2,7 +2,6 @@
package com.netscape.cms.servlet.base;
-
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
@@ -21,34 +20,29 @@ import javax.servlet.http.HttpServletResponse;
import com.netscape.certsrv.apps.CMS;
-
/**
* This is a servlet that proxies request to another servlet.
- *
- * SERVLET REDIRECTION
- * Specify the URL of a servlet to forward the request to
- * destServlet: /ee/ca/newservlet
- *
- * PARAMETER MAPPING
- * In the servlet configuration (as an init-param in web.xml) you
- * can optionally specify a value for the parameter 'parameterMap'
- * which contains a list of HTTP parameters which should be
- * translated to new names.
*
- * parameterMap: name1->newname1,name2->newname2
- *
+ * SERVLET REDIRECTION Specify the URL of a servlet to forward the request to
+ * destServlet: /ee/ca/newservlet
+ *
+ * PARAMETER MAPPING In the servlet configuration (as an init-param in web.xml)
+ * you can optionally specify a value for the parameter 'parameterMap' which
+ * contains a list of HTTP parameters which should be translated to new names.
+ *
+ * parameterMap: name1->newname1,name2->newname2
+ *
* Optionally, names can be set to static values:
- *
- * parameterMap: name1->name2=value
- *
- * Examples:
- * Consider the following HTTP input parameters:
- * vehicle:car make:ford model:explorer
*
- * The following config strings will have this effect:
- * parameterMap: make->manufacturer,model->name=expedition,->suv=true
- * output: vehicle:car manufactuer:ford model:expedition suv:true
- *
+ * parameterMap: name1->name2=value
+ *
+ * Examples: Consider the following HTTP input parameters: vehicle:car make:ford
+ * model:explorer
+ *
+ * The following config strings will have this effect: parameterMap:
+ * make->manufacturer,model->name=expedition,->suv=true output: vehicle:car
+ * manufactuer:ford model:expedition suv:true
+ *
* @version $Revision$, $Date$
*/
public class ProxyServlet extends HttpServlet {
@@ -64,40 +58,41 @@ public class ProxyServlet extends HttpServlet {
private Vector mMatchStrings = new Vector();
private String mDestServletOnNoMatch = null;
private String mAppendPathInfoOnNoMatch = null;
- private Map mParamMap = new HashMap();
- private Map mParamValue = new HashMap();
+ private Map mParamMap = new HashMap();
+ private Map mParamValue = new HashMap();
public ProxyServlet() {
}
- private void parseParamTable(String s) {
- if (s == null) return;
-
- String[] params = s.split(",");
- for (int i=0;i<params.length;i++) {
- String p = params[i];
- if (p != null) {
- String[] paramNames = p.split("->");
- if (paramNames.length != 2) {
- }
- String from = paramNames[0];
- String to = paramNames[1];
- if (from != null && to != null) {
- String[] splitTo = to.split("=");
- String toName = splitTo[0];
- if (from.length() >0) {
- mParamMap.put(from,toName);
- }
- if (splitTo.length == 2) {
- String toValue = splitTo[1];
- String toValues[] = new String[1];
- toValues[0] = toValue;
- mParamValue.put(toName,toValues);
- }
- }
- }
- }
- }
+ private void parseParamTable(String s) {
+ if (s == null)
+ return;
+
+ String[] params = s.split(",");
+ for (int i = 0; i < params.length; i++) {
+ String p = params[i];
+ if (p != null) {
+ String[] paramNames = p.split("->");
+ if (paramNames.length != 2) {
+ }
+ String from = paramNames[0];
+ String to = paramNames[1];
+ if (from != null && to != null) {
+ String[] splitTo = to.split("=");
+ String toName = splitTo[0];
+ if (from.length() > 0) {
+ mParamMap.put(from, toName);
+ }
+ if (splitTo.length == 2) {
+ String toValue = splitTo[1];
+ String toValues[] = new String[1];
+ toValues[0] = toValue;
+ mParamValue.put(toName, toValues);
+ }
+ }
+ }
+ }
+ }
public void init(ServletConfig sc) throws ServletException {
super.init(sc);
@@ -115,14 +110,13 @@ public class ProxyServlet extends HttpServlet {
mAppendPathInfo = sc.getInitParameter("appendPathInfo");
mAppendPathInfoOnNoMatch = sc.getInitParameter("appendPathInfoOnNoMatch");
String map = sc.getInitParameter("parameterMap");
- if (map != null) {
- parseParamTable(map);
- }
+ if (map != null) {
+ parseParamTable(map);
+ }
}
public void service(HttpServletRequest req, HttpServletResponse res) throws
- IOException, ServletException
- {
+ IOException, ServletException {
RequestDispatcher dispatcher = null;
String dest = mDest;
String uri = req.getRequestURI();
@@ -132,120 +126,118 @@ public class ProxyServlet extends HttpServlet {
if (mMatchStrings.size() != 0) {
boolean matched = false;
for (int i = 0; i < mMatchStrings.size(); i++) {
- String t = (String)mMatchStrings.elementAt(i);
- if (uri.indexOf(t) != -1) {
+ String t = (String) mMatchStrings.elementAt(i);
+ if (uri.indexOf(t) != -1) {
matched = true;
}
}
if (!matched) {
dest = mDestServletOnNoMatch;
// append Path info for OCSP request in Get method
- if (mAppendPathInfoOnNoMatch != null &&
- !mAppendPathInfoOnNoMatch.equals("")) {
+ if (mAppendPathInfoOnNoMatch != null &&
+ !mAppendPathInfoOnNoMatch.equals("")) {
dest = dest + uri.replace(mAppendPathInfoOnNoMatch, "");
}
}
}
if (dest == null || dest.equals("")) {
- // mapping everything
- dest = uri;
- dest = dest.replaceFirst(mSrcContext, "");
+ // mapping everything
+ dest = uri;
+ dest = dest.replaceFirst(mSrcContext, "");
}
if (mAppendPathInfo != null && !mAppendPathInfo.equals("")) {
- dest = dest + uri.replace(mAppendPathInfo, "");
+ dest = dest + uri.replace(mAppendPathInfo, "");
}
if (mDestContext != null && !mDestContext.equals("")) {
- dispatcher = getServletContext().getContext(mDestContext).getRequestDispatcher(dest);
+ dispatcher = getServletContext().getContext(mDestContext).getRequestDispatcher(dest);
} else {
- dispatcher = req.getRequestDispatcher(dest);
+ dispatcher = req.getRequestDispatcher(dest);
}
- // If a parameter map was specified
- if (mParamMap != null && !mParamMap.isEmpty()) {
- // Make a new wrapper with the new parameters
- ProxyWrapper r = new ProxyWrapper(req);
- r.setParameterMapAndValue(mParamMap,mParamValue);
- req = r;
- }
-
- dispatcher.forward(req, res);
+ // If a parameter map was specified
+ if (mParamMap != null && !mParamMap.isEmpty()) {
+ // Make a new wrapper with the new parameters
+ ProxyWrapper r = new ProxyWrapper(req);
+ r.setParameterMapAndValue(mParamMap, mParamValue);
+ req = r;
+ }
+
+ dispatcher.forward(req, res);
}
}
-class ProxyWrapper extends HttpServletRequestWrapper
-{
- private Map mMap = null;
- private Map mValueMap = null;
-
- public ProxyWrapper(HttpServletRequest req)
- {
- super(req);
- }
-
- public void setParameterMapAndValue(Map m,Map v)
- {
- if (m != null) mMap = m;
- if (v != null) mValueMap = v;
- }
-
- public Map getParameterMap()
- {
- try {
- // If we haven't specified any parameter mapping, just
- // use the regular implementation
- if (mMap == null) return super.getParameterMap();
- else {
- // Make a new Map for us to put stuff in
- Map n = new HashMap();
- // get the HTTP parameters the user supplied.
- Map m = super.getParameterMap();
- Set s = m.entrySet();
- Iterator i = s.iterator();
- while (i.hasNext()) {
- Map.Entry me = (Map.Entry) i.next();
- String name = (String) me.getKey();
- String[] values = (String[])(me.getValue());
- String newname = null;
- if (name != null) {
- newname = (String) mMap.get(name);
- }
-
- // No mapping specified, just use existing name/value
- if (newname == null || mValueMap == null) {
- n.put(name,values);
- } else { // new name specified
- Object o = mValueMap.get(newname);
- // check if new (static) value specified
- if (o==null) {
- n.put(newname,values);
- } else {
- String newvalues[] = (String[])mValueMap.get(newname);
- n.put(newname,newvalues);
- }
- }
- }
- // Now, deal with static values set in the config
- // which weren't set in the HTTP request
- Set s2 = mValueMap.entrySet();
- Iterator i2 = s2.iterator();
- // Cycle through all the static values
- while (i2.hasNext()) {
- Map.Entry me2 = (Map.Entry) i2.next();
- String name2 = (String) me2.getKey();
- if (n.get(name2) == null) {
- String[] values2 = (String[])me2.getValue();
- // If the parameter is not set in the map
- // Set it now
- n.put(name2,values2);
- }
- }
-
- return n;
- }
- } catch (NullPointerException npe) {
- CMS.debug(npe);
- return null;
- }
- }
-}
+class ProxyWrapper extends HttpServletRequestWrapper {
+ private Map mMap = null;
+ private Map mValueMap = null;
+
+ public ProxyWrapper(HttpServletRequest req) {
+ super(req);
+ }
+
+ public void setParameterMapAndValue(Map m, Map v) {
+ if (m != null)
+ mMap = m;
+ if (v != null)
+ mValueMap = v;
+ }
+ public Map getParameterMap() {
+ try {
+ // If we haven't specified any parameter mapping, just
+ // use the regular implementation
+ if (mMap == null)
+ return super.getParameterMap();
+ else {
+ // Make a new Map for us to put stuff in
+ Map n = new HashMap();
+ // get the HTTP parameters the user supplied.
+ Map m = super.getParameterMap();
+ Set s = m.entrySet();
+ Iterator i = s.iterator();
+ while (i.hasNext()) {
+ Map.Entry me = (Map.Entry) i.next();
+ String name = (String) me.getKey();
+ String[] values = (String[]) (me.getValue());
+ String newname = null;
+ if (name != null) {
+ newname = (String) mMap.get(name);
+ }
+
+ // No mapping specified, just use existing name/value
+ if (newname == null || mValueMap == null) {
+ n.put(name, values);
+ } else { // new name specified
+ Object o = mValueMap.get(newname);
+ // check if new (static) value specified
+ if (o == null) {
+ n.put(newname, values);
+ } else {
+ String newvalues[] = (String[]) mValueMap.get(newname);
+ n.put(newname, newvalues);
+ }
+ }
+ }
+ // Now, deal with static values set in the config
+ // which weren't set in the HTTP request
+ Set s2 = mValueMap.entrySet();
+ Iterator i2 = s2.iterator();
+ // Cycle through all the static values
+ while (i2.hasNext()) {
+ Map.Entry me2 = (Map.Entry) i2.next();
+ String name2 = (String) me2.getKey();
+ if (n.get(name2) == null) {
+ String[] values2 = (String[]) me2.getValue();
+ // If the parameter is not set in the map
+ // Set it now
+ n.put(name2, values2);
+ }
+ }
+
+ return n;
+ }
+ } catch (NullPointerException npe) {
+ CMS.debug(npe);
+ return null;
+ }
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/base/SystemInfoServlet.java b/pki/base/common/src/com/netscape/cms/servlet/base/SystemInfoServlet.java
index 5daac065..a708483f 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/base/SystemInfoServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/base/SystemInfoServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.base;
-
import java.io.IOException;
import java.util.Date;
@@ -30,15 +29,14 @@ import javax.servlet.http.HttpServletResponse;
import com.netscape.certsrv.apps.CMS;
/**
- * Displays detailed information about java VM internals, including
- * current JVM memory usage, and detailed information about each
- * thread.
+ * Displays detailed information about java VM internals, including current JVM
+ * memory usage, and detailed information about each thread.
* <p>
* Also allows user to trigger a new garbage collection
- *
+ *
* @version $Revision$, $Date$
*/
-public class SystemInfoServlet extends HttpServlet {
+public class SystemInfoServlet extends HttpServlet {
/**
*
@@ -53,21 +51,24 @@ public class SystemInfoServlet extends HttpServlet {
}
/**
- * service the request, returning HTML to the client.
- * This method has different behaviour depending on the
- * value of the 'op' HTTP parameter.
+ * service the request, returning HTML to the client. This method has
+ * different behaviour depending on the value of the 'op' HTTP parameter.
* <UL>
- * <LI>op = <i>undefined</i> - display a menu with links to the other functionality of this servlet
- * <li>op = gc - tell the JVM that we want to do a garbage collection and to run finalizers
- * (@see java.lang.Runtime.getRuntime#gc() )
- * <li>op = general - display information about memory, and other JVM informatino
- * <li>op = thread - display details about each thread.
+ * <LI>op = <i>undefined</i> - display a menu with links to the other
+ * functionality of this servlet
+ * <li>op = gc - tell the JVM that we want to do a garbage collection and to
+ * run finalizers (@see java.lang.Runtime.getRuntime#gc() )
+ * <li>op = general - display information about memory, and other JVM
+ * informatino
+ * <li>op = thread - display details about each thread.
* </UL>
- * @see javax.servlet.http.HttpServlet#service(HttpServletRequest, HttpServletResponse)
+ *
+ * @see javax.servlet.http.HttpServlet#service(HttpServletRequest,
+ * HttpServletResponse)
*/
- public void service(HttpServletRequest request,
- HttpServletResponse response)
- throws ServletException, IOException {
+ public void service(HttpServletRequest request,
+ HttpServletResponse response)
+ throws ServletException, IOException {
boolean collect = false;
String op = request.getParameter("op");
@@ -83,9 +84,9 @@ public class SystemInfoServlet extends HttpServlet {
}
}
- private void mainMenu(HttpServletRequest request,
- HttpServletResponse response)
- throws ServletException, IOException {
+ private void mainMenu(HttpServletRequest request,
+ HttpServletResponse response)
+ throws ServletException, IOException {
response.getWriter().println("<HTML>");
response.getWriter().println("<H1>");
response.getWriter().println("<a href=" + request.getServletPath() + ">");
@@ -122,9 +123,9 @@ public class SystemInfoServlet extends HttpServlet {
response.getWriter().println("</HTML>");
}
- private void gc(HttpServletRequest request,
- HttpServletResponse response)
- throws ServletException, IOException {
+ private void gc(HttpServletRequest request,
+ HttpServletResponse response)
+ throws ServletException, IOException {
java.lang.Runtime.getRuntime().gc();
java.lang.Runtime.getRuntime().runFinalization();
response.getWriter().println("<HTML>");
@@ -140,9 +141,9 @@ public class SystemInfoServlet extends HttpServlet {
response.getWriter().println("</HTML>");
}
- private void general(HttpServletRequest request,
- HttpServletResponse response)
- throws ServletException, IOException {
+ private void general(HttpServletRequest request,
+ HttpServletResponse response)
+ throws ServletException, IOException {
response.getWriter().println("<HTML>");
response.getWriter().println("<H1>");
response.getWriter().println("<a href=" + request.getServletPath() + ">");
@@ -221,9 +222,9 @@ public class SystemInfoServlet extends HttpServlet {
response.getWriter().println("</HTML>");
}
- private void thread(HttpServletRequest request,
- HttpServletResponse response)
- throws ServletException, IOException {
+ private void thread(HttpServletRequest request,
+ HttpServletResponse response)
+ throws ServletException, IOException {
response.getWriter().println("</table>");
response.getWriter().println("<HTML>");
response.getWriter().println("<H1>");
diff --git a/pki/base/common/src/com/netscape/cms/servlet/base/UserInfo.java b/pki/base/common/src/com/netscape/cms/servlet/base/UserInfo.java
index 02ab5b52..ca829561 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/base/UserInfo.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/base/UserInfo.java
@@ -17,11 +17,10 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.base;
-
/**
- * This class represents information about the client e.g. version,
- * langauge, vendor.
- *
+ * This class represents information about the client e.g. version, langauge,
+ * vendor.
+ *
* @version $Revision$, $Date$
*/
public class UserInfo {
@@ -36,7 +35,7 @@ public class UserInfo {
/**
* Returns the user language.
- *
+ *
* @param s user language info from the browser
* @return user language
*/
@@ -53,7 +52,7 @@ public class UserInfo {
/**
* Returns the user country.
- *
+ *
* @param s user language info from the browser
* @return user country
*/
@@ -67,10 +66,10 @@ public class UserInfo {
}
return "";
}
-
+
/**
* Returns the users agent.
- *
+ *
* @param s user language info from the browser
* @return user agent
*/
@@ -79,7 +78,7 @@ public class UserInfo {
if (s.indexOf(MSIE) != -1) {
return MSIE;
}
-
+
// Check for Netscape i.e. Mozilla
if (s.indexOf(MOZILLA) != -1) {
return MOZILLA;
@@ -87,5 +86,5 @@ public class UserInfo {
// Don't know agent. Return empty string.
return "";
- }
+ }
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/CMCRevReqServlet.java b/pki/base/common/src/com/netscape/cms/servlet/cert/CMCRevReqServlet.java
index 15d069e3..8b912032 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/CMCRevReqServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/CMCRevReqServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.io.IOException;
import java.math.BigInteger;
import java.security.cert.CertificateException;
@@ -67,10 +66,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* Revoke a certificate with a CMC-formatted revocation request
- *
+ *
* @version $Revision$, $Date$
*/
public class CMCRevReqServlet extends CMSServlet {
@@ -83,7 +81,7 @@ public class CMCRevReqServlet extends CMSServlet {
// revocation templates.
private final static String TPL_FILE = "revocationResult.template";
public static final String CRED_CMC = "cmcRequest";
-
+
private ICertificateRepository mCertDB = null;
private String mFormPath = null;
private IRequestQueue mQueue = null;
@@ -92,29 +90,28 @@ public class CMCRevReqServlet extends CMSServlet {
private final static String REVOKE = "revoke";
private final static String ON_HOLD = "on-hold";
private final static int ON_HOLD_REASON = 6;
- private final static String
- LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST =
- "LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_5";
- private final static String
- LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED =
- "LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED_7";
-
- // http params
+ private final static String LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST =
+ "LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_5";
+ private final static String LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED =
+ "LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED_7";
+
+ // http params
public static final String SERIAL_NO = TOKEN_CERT_SERIAL;
public static final String REASON_CODE = "reasonCode";
public static final String CHALLENGE_PHRASE = "challengePhrase";
// request attributes
public static final String SERIALNO_ARRAY = "serialNoArray";
-
+
public CMCRevReqServlet() {
super();
}
- /**
+ /**
* initialize the servlet.
- * @param sc servlet configuration, read from the web.xml file
- */
+ *
+ * @param sc servlet configuration, read from the web.xml file
+ */
public void init(ServletConfig sc) throws ServletException {
super.init(sc);
@@ -136,26 +133,26 @@ public class CMCRevReqServlet extends CMSServlet {
mFormPath = mOutputTemplatePath;
}
-
- /**
- * Process the HTTP request.
- *
- * <ul>
- * <li>http.param cmcRequest the base-64 encoded CMC request
- * </ul>
- * @param cmsReq the object holding the request and response information
+ /**
+ * Process the HTTP request.
+ *
+ * <ul>
+ * <li>http.param cmcRequest the base-64 encoded CMC request
+ * </ul>
+ *
+ * @param cmsReq the object holding the request and response information
*/
protected void process(CMSRequest cmsReq) throws EBaseException {
String cmcAgentSerialNumber = null;
IArgBlock httpParams = cmsReq.getHttpParams();
HttpServletRequest req = cmsReq.getHttpReq();
- HttpServletResponse resp = cmsReq.getHttpResp();
-
+ HttpServletResponse resp = cmsReq.getHttpResp();
+
CMSTemplate form = null;
Locale[] locale = new Locale[1];
-CMS.debug("**** mFormPath = "+mFormPath);
+ CMS.debug("**** mFormPath = " + mFormPath);
try {
form = getTemplate(mFormPath, req, locale);
} catch (IOException e) {
@@ -167,12 +164,11 @@ CMS.debug("**** mFormPath = "+mFormPath);
IArgBlock header = CMS.createArgBlock();
IArgBlock ctx = CMS.createArgBlock();
CMSTemplateParams argSet = new CMSTemplateParams(header, ctx);
-
String cmc = (String) httpParams.get(CRED_CMC);
if (cmc == null) {
throw new EMissingCredential(
- CMS.getUserMessage("CMS_AUTHENTICATION_NULL_CREDENTIAL", CRED_CMC));
+ CMS.getUserMessage("CMS_AUTHENTICATION_NULL_CREDENTIAL", CRED_CMC));
}
IAuthToken authToken = authenticate(cmsReq);
@@ -189,10 +185,10 @@ CMS.debug("**** mFormPath = "+mFormPath);
return;
}
- //IAuthToken authToken = getAuthToken(cmsReq);
- //Object subject = authToken.get(CMCAuth.TOKEN_CERT_SERIAL);
- //Object uid = authToken.get("uid");
- //===========================
+ // IAuthToken authToken = getAuthToken(cmsReq);
+ // Object subject = authToken.get(CMCAuth.TOKEN_CERT_SERIAL);
+ // Object uid = authToken.get("uid");
+ // ===========================
String authMgr = AuditFormat.NOAUTH;
BigInteger[] serialNoArray = null;
@@ -200,8 +196,8 @@ CMS.debug("**** mFormPath = "+mFormPath);
serialNoArray = authToken.getInBigIntegerArray(TOKEN_CERT_SERIAL);
}
- Integer reasonCode = Integer.valueOf(0);
- if (authToken != null) {
+ Integer reasonCode = Integer.valueOf(0);
+ if (authToken != null) {
reasonCode = authToken.getInInteger(REASON_CODE);
}
RevocationReason reason = RevocationReason.fromInt(reasonCode.intValue());
@@ -211,15 +207,15 @@ CMS.debug("**** mFormPath = "+mFormPath);
String revokeAll = null;
int verifiedRecordCount = 0;
int totalRecordCount = 0;
-
+
if (serialNoArray != null) {
totalRecordCount = serialNoArray.length;
verifiedRecordCount = serialNoArray.length;
}
-
+
X509CertImpl[] certs = null;
- //for audit log.
+ // for audit log.
String initiative = null;
if (mAuthMgr != null && mAuthMgr.equals("CMCAuth")) {
@@ -247,7 +243,7 @@ CMS.debug("**** mFormPath = "+mFormPath);
IRequest getCertsChallengeReq = null;
getCertsChallengeReq = mQueue.newRequest(
- GETCERTS_FOR_CHALLENGE_REQUEST);
+ GETCERTS_FOR_CHALLENGE_REQUEST);
getCertsChallengeReq.setExtData(SERIALNO_ARRAY, serialNoArray);
mQueue.processRequest(getCertsChallengeReq);
RequestStatus status = getCertsChallengeReq.getRequestStatus();
@@ -257,7 +253,7 @@ CMS.debug("**** mFormPath = "+mFormPath);
header.addStringValue("request", getCertsChallengeReq.getRequestId().toString());
mRequestID = getCertsChallengeReq.getRequestId().toString();
} else {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_FAIL_GET_CERT_CHALL_PWRD"));
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_FAIL_GET_CERT_CHALL_PWRD"));
}
}
@@ -268,22 +264,22 @@ CMS.debug("**** mFormPath = "+mFormPath);
IArgBlock rarg = CMS.createArgBlock();
rarg.addBigIntegerValue("serialNumber",
- serialNoArray[i], 16);
+ serialNoArray[i], 16);
rarg.addStringValue("subject",
- certs[i].getSubjectDN().toString());
+ certs[i].getSubjectDN().toString());
rarg.addLongValue("validNotBefore",
- certs[i].getNotBefore().getTime() / 1000);
+ certs[i].getNotBefore().getTime() / 1000);
rarg.addLongValue("validNotAfter",
- certs[i].getNotAfter().getTime() / 1000);
- //argSet.addRepeatRecord(rarg);
+ certs[i].getNotAfter().getTime() / 1000);
+ // argSet.addRepeatRecord(rarg);
}
revokeAll = "(|(certRecordId=" + serialNoArray[0].toString() + "))";
- cmcAgentSerialNumber= authToken.getInString(IAuthManager.CRED_SSL_CLIENT_CERT);
+ cmcAgentSerialNumber = authToken.getInString(IAuthManager.CRED_SSL_CLIENT_CERT);
process(argSet, header, reasonCode.intValue(), invalidityDate, initiative, req, resp,
- verifiedRecordCount, revokeAll, totalRecordCount,
- comments, locale[0],cmcAgentSerialNumber);
-
+ verifiedRecordCount, revokeAll, totalRecordCount,
+ comments, locale[0], cmcAgentSerialNumber);
+
} else {
header.addIntegerValue("totalRecordCount", 0);
header.addIntegerValue("verifiedRecordCount", 0);
@@ -292,7 +288,7 @@ CMS.debug("**** mFormPath = "+mFormPath);
try {
ServletOutputStream out = resp.getOutputStream();
- if ((serialNoArray== null) || (serialNoArray.length == 0)) {
+ if ((serialNoArray == null) || (serialNoArray.length == 0)) {
cmsReq.setStatus(CMSRequest.ERROR);
EBaseException ee = new EBaseException("No matched certificate is found");
@@ -300,16 +296,16 @@ CMS.debug("**** mFormPath = "+mFormPath);
} else {
String xmlOutput = req.getParameter("xml");
if (xmlOutput != null && xmlOutput.equals("true")) {
- outputXML(resp, argSet);
+ outputXML(resp, argSet);
} else {
- resp.setContentType("text/html");
- form.renderOutput(out, argSet);
- cmsReq.setStatus(CMSRequest.SUCCESS);
+ resp.setContentType("text/html");
+ form.renderOutput(out, argSet);
+ cmsReq.setStatus(CMSRequest.SUCCESS);
}
}
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_ERR_STREAM_TEMPLATE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_ERR_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(CMS.getLogMessage("CMSGW_ERROR_DISPLAY_TEMPLATE"));
}
}
@@ -318,56 +314,57 @@ CMS.debug("**** mFormPath = "+mFormPath);
* Process cert status change request using the Certificate Management
* protocol using CMS (CMC)
* <P>
- *
+ *
* (Certificate Request - an "EE" cert status change request)
* <P>
- *
+ *
* (Certificate Request Processed - an "EE" cert status change request)
* <P>
- *
+ *
* <ul>
- * <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST used when
- * a cert status change request (e. g. - "revocation") is made (before
+ * <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST used
+ * when a cert status change request (e. g. - "revocation") is made (before
* approval process)
- * <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED
- * used when a certificate status is changed (revoked, expired, on-hold,
- * off-hold)
+ * <li>signed.audit
+ * LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED used when a
+ * certificate status is changed (revoked, expired, on-hold, off-hold)
* </ul>
+ *
* @param argSet CMS template parameters
* @param header argument block
- * @param reason revocation reason (0 - Unspecified, 1 - Key compromised,
- * 2 - CA key compromised; should not be used, 3 - Affiliation changed,
- * 4 - Certificate superceded, 5 - Cessation of operation, or
- * 6 - Certificate is on hold)
+ * @param reason revocation reason (0 - Unspecified, 1 - Key compromised, 2
+ * - CA key compromised; should not be used, 3 - Affiliation
+ * changed, 4 - Certificate superceded, 5 - Cessation of
+ * operation, or 6 - Certificate is on hold)
* @param invalidityDate certificate validity date
* @param initiative string containing the audit format
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @param verifiedRecordCount number of verified records
- * @param revokeAll string containing information on all of the
- * certificates to be revoked
+ * @param revokeAll string containing information on all of the certificates
+ * to be revoked
* @param totalRecordCount total number of records (verified and unverified)
* @param comments string containing certificate comments
* @param locale the system locale
* @exception EBaseException an error has occurred
*/
private void process(CMSTemplateParams argSet, IArgBlock header,
- int reason, Date invalidityDate,
- String initiative,
- HttpServletRequest req,
- HttpServletResponse resp,
- int verifiedRecordCount,
- String revokeAll,
- int totalRecordCount,
- String comments,
- Locale locale,String cmcAgentSerialNumber)
- throws EBaseException {
+ int reason, Date invalidityDate,
+ String initiative,
+ HttpServletRequest req,
+ HttpServletResponse resp,
+ int verifiedRecordCount,
+ String revokeAll,
+ int totalRecordCount,
+ String comments,
+ Locale locale, String cmcAgentSerialNumber)
+ throws EBaseException {
String eeSerialNumber = null;
- if(cmcAgentSerialNumber!=null) {
+ if (cmcAgentSerialNumber != null) {
eeSerialNumber = cmcAgentSerialNumber;
- }else{
- X509CertImpl sslCert = ( X509CertImpl ) getSSLClientCertificate( req );
- if( sslCert != null ) {
+ } else {
+ X509CertImpl sslCert = (X509CertImpl) getSSLClientCertificate(req);
+ if (sslCert != null) {
eeSerialNumber = sslCert.getSerialNumber().toString();
}
}
@@ -375,11 +372,11 @@ CMS.debug("**** mFormPath = "+mFormPath);
boolean auditRequest = true;
String auditMessage = null;
String auditSubjectID = auditSubjectID();
- String auditRequesterID = auditRequesterID( req );
- String auditSerialNumber = auditSerialNumber( eeSerialNumber );
- String auditRequestType = auditRequestType( reason );
+ String auditRequesterID = auditRequesterID(req);
+ String auditSerialNumber = auditSerialNumber(eeSerialNumber);
+ String auditRequestType = auditRequestType(reason);
String auditApprovalStatus = ILogger.SIGNED_AUDIT_EMPTY_VALUE;
- String auditReasonNum = String.valueOf( reason );
+ String auditReasonNum = String.valueOf(reason);
try {
int count = 0;
@@ -418,18 +415,18 @@ CMS.debug("**** mFormPath = "+mFormPath);
IArgBlock rarg = CMS.createArgBlock();
rarg.addBigIntegerValue("serialNumber",
- cert.getSerialNumber(), 16);
+ cert.getSerialNumber(), 16);
if (rec.getStatus().equals(ICertRecord.STATUS_REVOKED)) {
rarg.addStringValue("error", "Certificate " +
- cert.getSerialNumber().toString() +
- " is already revoked.");
+ cert.getSerialNumber().toString() +
+ " is already revoked.");
} else {
oldCertsV.addElement(cert);
RevokedCertImpl revCertImpl =
- new RevokedCertImpl(cert.getSerialNumber(),
- CMS.getCurrentDate(), entryExtn);
+ new RevokedCertImpl(cert.getSerialNumber(),
+ CMS.getCurrentDate(), entryExtn);
revCertImplsV.addElement(revCertImpl);
count++;
@@ -441,14 +438,12 @@ CMS.debug("**** mFormPath = "+mFormPath);
} else if (mAuthority instanceof IRegistrationAuthority) {
String reqIdStr = null;
- if (mRequestID != null && mRequestID.length() > 0)
+ if (mRequestID != null && mRequestID.length() > 0)
reqIdStr = mRequestID;
Vector<String> serialNumbers = new Vector<String>();
if (revokeAll != null && revokeAll.length() > 0) {
- for (int i = revokeAll.indexOf('=');
- i < revokeAll.length() && i > -1;
- i = revokeAll.indexOf('=', i)) {
+ for (int i = revokeAll.indexOf('='); i < revokeAll.length() && i > -1; i = revokeAll.indexOf('=', i)) {
if (i > -1) {
i++;
while (i < revokeAll.length() && revokeAll.charAt(i) == ' ') {
@@ -457,8 +452,8 @@ CMS.debug("**** mFormPath = "+mFormPath);
String legalDigits = "0123456789";
int j = i;
- while (j < revokeAll.length() &&
- legalDigits.indexOf(revokeAll.charAt(j)) != -1) {
+ while (j < revokeAll.length() &&
+ legalDigits.indexOf(revokeAll.charAt(j)) != -1) {
j++;
}
if (j > i) {
@@ -485,12 +480,12 @@ CMS.debug("**** mFormPath = "+mFormPath);
IArgBlock rarg = CMS.createArgBlock();
rarg.addBigIntegerValue("serialNumber",
- certs[i].getSerialNumber(), 16);
+ certs[i].getSerialNumber(), 16);
oldCertsV.addElement(certs[i]);
RevokedCertImpl revCertImpl =
- new RevokedCertImpl(certs[i].getSerialNumber(),
- CMS.getCurrentDate(), entryExtn);
+ new RevokedCertImpl(certs[i].getSerialNumber(),
+ CMS.getCurrentDate(), entryExtn);
revCertImplsV.addElement(revCertImpl);
count++;
@@ -507,12 +502,12 @@ CMS.debug("**** mFormPath = "+mFormPath);
IArgBlock rarg = CMS.createArgBlock();
rarg.addBigIntegerValue("serialNumber",
- cert.getSerialNumber(), 16);
+ cert.getSerialNumber(), 16);
oldCertsV.addElement(cert);
RevokedCertImpl revCertImpl =
- new RevokedCertImpl(cert.getSerialNumber(),
- CMS.getCurrentDate(), entryExtn);
+ new RevokedCertImpl(cert.getSerialNumber(),
+ CMS.getCurrentDate(), entryExtn);
revCertImplsV.addElement(revCertImpl);
count++;
@@ -533,7 +528,7 @@ CMS.debug("**** mFormPath = "+mFormPath);
}
IRequest revReq =
- mQueue.newRequest(IRequest.REVOCATION_REQUEST);
+ mQueue.newRequest(IRequest.REVOCATION_REQUEST);
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -573,29 +568,29 @@ CMS.debug("**** mFormPath = "+mFormPath);
if (result.equals(IRequest.RES_ERROR)) {
String[] svcErrors =
- revReq.getExtDataInStringArray(IRequest.SVCERRORS);
+ revReq.getExtDataInStringArray(IRequest.SVCERRORS);
if (svcErrors != null && svcErrors.length > 0) {
for (int i = 0; i < svcErrors.length; i++) {
String err = svcErrors[i];
if (err != null) {
- //cmsReq.setErrorDescription(err);
+ // cmsReq.setErrorDescription(err);
for (int j = 0; j < count; j++) {
if (oldCerts[j] != null) {
mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.DOREVOKEFORMAT,
- new Object[] {
- revReq.getRequestId(),
- initiative,
- "completed with error: " +
- err,
- oldCerts[j].getSubjectDN(),
- oldCerts[j].getSerialNumber().toString(16),
- RevocationReason.fromInt(reason).toString()}
- );
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.DOREVOKEFORMAT,
+ new Object[] {
+ revReq.getRequestId(),
+ initiative,
+ "completed with error: " +
+ err,
+ oldCerts[j].getSubjectDN(),
+ oldCerts[j].getSerialNumber().toString(16),
+ RevocationReason.fromInt(reason).toString() }
+ );
}
}
}
@@ -608,23 +603,23 @@ CMS.debug("**** mFormPath = "+mFormPath);
for (int j = 0; j < count; j++) {
if (oldCerts[j] != null) {
mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.DOREVOKEFORMAT,
- new Object[] {
- revReq.getRequestId(),
- initiative,
- "completed",
- oldCerts[j].getSubjectDN(),
- oldCerts[j].getSerialNumber().toString(16),
- RevocationReason.fromInt(reason).toString()}
- );
+ AuditFormat.LEVEL,
+ AuditFormat.DOREVOKEFORMAT,
+ new Object[] {
+ revReq.getRequestId(),
+ initiative,
+ "completed",
+ oldCerts[j].getSubjectDN(),
+ oldCerts[j].getSerialNumber().toString(16),
+ RevocationReason.fromInt(reason).toString() }
+ );
}
}
header.addStringValue("revoked", "yes");
Integer updateCRLResult =
- revReq.getExtDataInInteger(IRequest.CRL_UPDATE_STATUS);
+ revReq.getExtDataInInteger(IRequest.CRL_UPDATE_STATUS);
if (updateCRLResult != null) {
header.addStringValue("updateCRL", "yes");
@@ -633,15 +628,15 @@ CMS.debug("**** mFormPath = "+mFormPath);
} else {
header.addStringValue("updateCRLSuccess", "no");
String crlError =
- revReq.getExtDataInString(IRequest.CRL_UPDATE_ERROR);
+ revReq.getExtDataInString(IRequest.CRL_UPDATE_ERROR);
if (crlError != null)
header.addStringValue("updateCRLError",
- crlError);
+ crlError);
}
// let known crl publishing status too.
Integer publishCRLResult =
- revReq.getExtDataInInteger(IRequest.CRL_PUBLISH_STATUS);
+ revReq.getExtDataInInteger(IRequest.CRL_PUBLISH_STATUS);
if (publishCRLResult != null) {
if (publishCRLResult.equals(IRequest.RES_SUCCESS)) {
@@ -649,22 +644,22 @@ CMS.debug("**** mFormPath = "+mFormPath);
} else {
header.addStringValue("publishCRLSuccess", "no");
String publError =
- revReq.getExtDataInString(IRequest.CRL_PUBLISH_ERROR);
+ revReq.getExtDataInString(IRequest.CRL_PUBLISH_ERROR);
if (publError != null)
header.addStringValue("publishCRLError",
- publError);
+ publError);
}
}
}
if (mAuthority instanceof ICertificateAuthority) {
// let known update and publish status of all crls.
Enumeration<ICRLIssuingPoint> otherCRLs =
- ((ICertificateAuthority) mAuthority).getCRLIssuingPoints();
+ ((ICertificateAuthority) mAuthority).getCRLIssuingPoints();
while (otherCRLs.hasMoreElements()) {
ICRLIssuingPoint crl = (ICRLIssuingPoint)
- otherCRLs.nextElement();
+ otherCRLs.nextElement();
String crlId = crl.getId();
if (crlId.equals(ICertificateAuthority.PROP_MASTER_CRL))
@@ -674,25 +669,25 @@ CMS.debug("**** mFormPath = "+mFormPath);
if (updateResult != null) {
if (updateResult.equals(IRequest.RES_SUCCESS)) {
- CMS.debug("CMCRevReqServlet: " + CMS.getLogMessage("ADMIN_SRVLT_ADDING_HEADER",
+ CMS.debug("CMCRevReqServlet: " + CMS.getLogMessage("ADMIN_SRVLT_ADDING_HEADER",
updateStatusStr));
header.addStringValue(updateStatusStr, "yes");
} else {
String updateErrorStr = crl.getCrlUpdateErrorStr();
- CMS.debug("CMCRevReqServlet: " + CMS.getLogMessage("ADMIN_SRVLT_ADDING_HEADER_NO",
+ CMS.debug("CMCRevReqServlet: " + CMS.getLogMessage("ADMIN_SRVLT_ADDING_HEADER_NO",
updateStatusStr));
header.addStringValue(updateStatusStr, "no");
String error =
- revReq.getExtDataInString(updateErrorStr);
+ revReq.getExtDataInString(updateErrorStr);
if (error != null)
header.addStringValue(updateErrorStr,
- error);
+ error);
}
String publishStatusStr = crl.getCrlPublishStatusStr();
Integer publishResult =
- revReq.getExtDataInInteger(publishStatusStr);
+ revReq.getExtDataInInteger(publishStatusStr);
if (publishResult == null)
continue;
@@ -700,15 +695,15 @@ CMS.debug("**** mFormPath = "+mFormPath);
header.addStringValue(publishStatusStr, "yes");
} else {
String publishErrorStr =
- crl.getCrlPublishErrorStr();
+ crl.getCrlPublishErrorStr();
header.addStringValue(publishStatusStr, "no");
String error =
- revReq.getExtDataInString(publishErrorStr);
+ revReq.getExtDataInString(publishErrorStr);
if (error != null)
header.addStringValue(
- publishErrorStr, error);
+ publishErrorStr, error);
}
}
}
@@ -717,7 +712,7 @@ CMS.debug("**** mFormPath = "+mFormPath);
if (mPublisherProcessor != null && mPublisherProcessor.ldapEnabled()) {
header.addStringValue("dirEnabled", "yes");
Integer[] ldapPublishStatus =
- revReq.getExtDataInIntegerArray("ldapPublishStatus");
+ revReq.getExtDataInIntegerArray("ldapPublishStatus");
int certsToUpdate = 0;
int certsUpdated = 0;
@@ -734,11 +729,11 @@ CMS.debug("**** mFormPath = "+mFormPath);
// add crl publishing status.
String publError =
- revReq.getExtDataInString(IRequest.CRL_PUBLISH_ERROR);
+ revReq.getExtDataInString(IRequest.CRL_PUBLISH_ERROR);
if (publError != null) {
header.addStringValue("crlPublishError",
- publError);
+ publError);
}
} else {
header.addStringValue("dirEnabled", "no");
@@ -752,16 +747,16 @@ CMS.debug("**** mFormPath = "+mFormPath);
for (int j = 0; j < count; j++) {
if (oldCerts[j] != null) {
mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.DOREVOKEFORMAT,
- new Object[] {
- revReq.getRequestId(),
- initiative,
- "pending",
- oldCerts[j].getSubjectDN(),
- oldCerts[j].getSerialNumber().toString(16),
- RevocationReason.fromInt(reason).toString()}
- );
+ AuditFormat.LEVEL,
+ AuditFormat.DOREVOKEFORMAT,
+ new Object[] {
+ revReq.getRequestId(),
+ initiative,
+ "pending",
+ oldCerts[j].getSubjectDN(),
+ oldCerts[j].getSerialNumber().toString(16),
+ RevocationReason.fromInt(reason).toString() }
+ );
}
}
@@ -771,7 +766,8 @@ CMS.debug("**** mFormPath = "+mFormPath);
if (errors != null && errors.size() > 0) {
for (int ii = 0; ii < errors.size(); ii++) {
- errorStr.append(errors.elementAt(ii));;
+ errorStr.append(errors.elementAt(ii));
+ ;
}
}
header.addStringValue("error", errorStr.toString());
@@ -780,16 +776,16 @@ CMS.debug("**** mFormPath = "+mFormPath);
for (int j = 0; j < count; j++) {
if (oldCerts[j] != null) {
mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.DOREVOKEFORMAT,
- new Object[] {
- revReq.getRequestId(),
- initiative,
- stat.toString(),
- oldCerts[j].getSubjectDN(),
- oldCerts[j].getSerialNumber().toString(16),
- RevocationReason.fromInt(reason).toString()}
- );
+ AuditFormat.LEVEL,
+ AuditFormat.DOREVOKEFORMAT,
+ new Object[] {
+ revReq.getRequestId(),
+ initiative,
+ stat.toString(),
+ oldCerts[j].getSubjectDN(),
+ oldCerts[j].getSerialNumber().toString(16),
+ RevocationReason.fromInt(reason).toString() }
+ );
}
}
}
@@ -798,17 +794,17 @@ CMS.debug("**** mFormPath = "+mFormPath);
// if and only if "auditApprovalStatus" is
// "complete", "revoked", or "canceled"
if ((auditApprovalStatus.equals(RequestStatus.COMPLETE_STRING))
- || (auditApprovalStatus.equals(RequestStatus.REJECTED_STRING))
- || (auditApprovalStatus.equals(RequestStatus.CANCELED_STRING))) {
+ || (auditApprovalStatus.equals(RequestStatus.REJECTED_STRING))
+ || (auditApprovalStatus.equals(RequestStatus.CANCELED_STRING))) {
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED,
- auditSubjectID,
- ILogger.SUCCESS,
- auditRequesterID,
- auditSerialNumber,
- auditRequestType,
- auditReasonNum,
- auditApprovalStatus);
+ LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED,
+ auditSubjectID,
+ ILogger.SUCCESS,
+ auditRequesterID,
+ auditSerialNumber,
+ auditRequestType,
+ auditReasonNum,
+ auditApprovalStatus);
audit(auditMessage);
}
@@ -818,12 +814,12 @@ CMS.debug("**** mFormPath = "+mFormPath);
// store a "CERT_STATUS_CHANGE_REQUEST" failure
// message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST,
- auditSubjectID,
- ILogger.FAILURE,
- auditRequesterID,
- auditSerialNumber,
- auditRequestType);
+ LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditRequesterID,
+ auditSerialNumber,
+ auditRequestType);
audit(auditMessage);
} else {
@@ -832,11 +828,10 @@ CMS.debug("**** mFormPath = "+mFormPath);
// if and only if "auditApprovalStatus" is
// "complete", "revoked", or "canceled"
if ((auditApprovalStatus.equals(RequestStatus.COMPLETE_STRING))
- || (auditApprovalStatus.equals(RequestStatus.REJECTED_STRING))
- || (auditApprovalStatus.equals(RequestStatus.CANCELED_STRING)))
- {
+ || (auditApprovalStatus.equals(RequestStatus.REJECTED_STRING))
+ || (auditApprovalStatus.equals(RequestStatus.CANCELED_STRING))) {
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED,
+ LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED,
auditSubjectID,
ILogger.FAILURE,
auditRequesterID,
@@ -857,12 +852,12 @@ CMS.debug("**** mFormPath = "+mFormPath);
// store a "CERT_STATUS_CHANGE_REQUEST" failure
// message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST,
- auditSubjectID,
- ILogger.FAILURE,
- auditRequesterID,
- auditSerialNumber,
- auditRequestType);
+ LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditRequesterID,
+ auditSerialNumber,
+ auditRequestType);
audit(auditMessage);
} else {
@@ -871,18 +866,17 @@ CMS.debug("**** mFormPath = "+mFormPath);
// if and only if "auditApprovalStatus" is
// "complete", "revoked", or "canceled"
if ((auditApprovalStatus.equals(RequestStatus.COMPLETE_STRING))
- || (auditApprovalStatus.equals(RequestStatus.REJECTED_STRING))
- || (auditApprovalStatus.equals(RequestStatus.CANCELED_STRING)))
- {
+ || (auditApprovalStatus.equals(RequestStatus.REJECTED_STRING))
+ || (auditApprovalStatus.equals(RequestStatus.CANCELED_STRING))) {
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED,
- auditSubjectID,
- ILogger.FAILURE,
- auditRequesterID,
- auditSerialNumber,
- auditRequestType,
- auditReasonNum,
- auditApprovalStatus);
+ LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditRequesterID,
+ auditSerialNumber,
+ auditRequestType,
+ auditReasonNum,
+ auditApprovalStatus);
audit(auditMessage);
}
@@ -891,18 +885,18 @@ CMS.debug("**** mFormPath = "+mFormPath);
throw e;
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_MARKING_CERT_REVOKED", e.toString()));
+ CMS.getLogMessage("CMSGW_ERROR_MARKING_CERT_REVOKED", e.toString()));
if (auditRequest) {
// store a "CERT_STATUS_CHANGE_REQUEST" failure
// message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST,
- auditSubjectID,
- ILogger.FAILURE,
- auditRequesterID,
- auditSerialNumber,
- auditRequestType);
+ LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditRequesterID,
+ auditSerialNumber,
+ auditRequestType);
audit(auditMessage);
} else {
@@ -911,18 +905,17 @@ CMS.debug("**** mFormPath = "+mFormPath);
// if and only if "auditApprovalStatus" is
// "complete", "revoked", or "canceled"
if ((auditApprovalStatus.equals(RequestStatus.COMPLETE_STRING))
- || (auditApprovalStatus.equals(RequestStatus.REJECTED_STRING))
- || (auditApprovalStatus.equals(RequestStatus.CANCELED_STRING)))
- {
+ || (auditApprovalStatus.equals(RequestStatus.REJECTED_STRING))
+ || (auditApprovalStatus.equals(RequestStatus.CANCELED_STRING))) {
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED,
- auditSubjectID,
- ILogger.FAILURE,
- auditRequesterID,
- auditSerialNumber,
- auditRequestType,
- auditReasonNum,
- auditApprovalStatus);
+ LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditRequesterID,
+ auditSerialNumber,
+ auditRequestType,
+ auditReasonNum,
+ auditApprovalStatus);
audit(auditMessage);
}
@@ -934,12 +927,12 @@ CMS.debug("**** mFormPath = "+mFormPath);
// store a "CERT_STATUS_CHANGE_REQUEST" failure
// message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST,
- auditSubjectID,
- ILogger.FAILURE,
- auditRequesterID,
- auditSerialNumber,
- auditRequestType);
+ LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditRequesterID,
+ auditSerialNumber,
+ auditRequestType);
audit(auditMessage);
} else {
@@ -948,18 +941,17 @@ CMS.debug("**** mFormPath = "+mFormPath);
// if and only if "auditApprovalStatus" is
// "complete", "revoked", or "canceled"
if ((auditApprovalStatus.equals(RequestStatus.COMPLETE_STRING))
- || (auditApprovalStatus.equals(RequestStatus.REJECTED_STRING))
- || (auditApprovalStatus.equals(RequestStatus.CANCELED_STRING)))
- {
+ || (auditApprovalStatus.equals(RequestStatus.REJECTED_STRING))
+ || (auditApprovalStatus.equals(RequestStatus.CANCELED_STRING))) {
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED,
- auditSubjectID,
- ILogger.FAILURE,
- auditRequesterID,
- auditSerialNumber,
- auditRequestType,
- auditReasonNum,
- auditApprovalStatus);
+ LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditRequesterID,
+ auditSerialNumber,
+ auditRequestType,
+ auditReasonNum,
+ auditApprovalStatus);
audit(auditMessage);
}
@@ -973,11 +965,11 @@ CMS.debug("**** mFormPath = "+mFormPath);
/**
* Signed Audit Log Requester ID
- *
- * This method is called to obtain the "RequesterID" for
- * a signed audit log message.
+ *
+ * This method is called to obtain the "RequesterID" for a signed audit log
+ * message.
* <P>
- *
+ *
* @param req HTTP request
* @return id string containing the signed audit log message RequesterID
*/
@@ -1003,11 +995,11 @@ CMS.debug("**** mFormPath = "+mFormPath);
/**
* Signed Audit Log Serial Number
- *
+ *
* This method is called to obtain the serial number of the certificate
* whose status is to be changed for a signed audit log message.
* <P>
- *
+ *
* @param eeSerialNumber a string containing the un-normalized serialNumber
* @return id string containing the signed audit log message RequesterID
*/
@@ -1026,7 +1018,7 @@ CMS.debug("**** mFormPath = "+mFormPath);
// convert it to hexadecimal
serialNumber = "0x"
+ Integer.toHexString(
- Integer.valueOf(serialNumber).intValue());
+ Integer.valueOf(serialNumber).intValue());
} else {
serialNumber = ILogger.SIGNED_AUDIT_EMPTY_VALUE;
}
@@ -1036,11 +1028,11 @@ CMS.debug("**** mFormPath = "+mFormPath);
/**
* Signed Audit Log Request Type
- *
- * This method is called to obtain the "Request Type" for
- * a signed audit log message.
+ *
+ * This method is called to obtain the "Request Type" for a signed audit log
+ * message.
* <P>
- *
+ *
* @param reason an integer denoting the revocation reason
* @return string containing REVOKE or ON_HOLD
*/
@@ -1062,4 +1054,3 @@ CMS.debug("**** mFormPath = "+mFormPath);
return requestType;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/ChallengeRevocationServlet1.java b/pki/base/common/src/com/netscape/cms/servlet/cert/ChallengeRevocationServlet1.java
index 181e6e9c..f467652c 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/ChallengeRevocationServlet1.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/ChallengeRevocationServlet1.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.io.IOException;
import java.math.BigInteger;
import java.security.cert.CertificateException;
@@ -66,11 +65,11 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
- * Takes the certificate info (serial number) and optional challenge phrase, creates a
- * revocation request and submits it to the authority subsystem for processing
- *
+ * Takes the certificate info (serial number) and optional challenge phrase,
+ * creates a revocation request and submits it to the authority subsystem for
+ * processing
+ *
* @version $Revision$, $Date$
*/
public class ChallengeRevocationServlet1 extends CMSServlet {
@@ -89,7 +88,7 @@ public class ChallengeRevocationServlet1 extends CMSServlet {
private IPublisherProcessor mPublisherProcessor = null;
private String mRequestID = null;
- // http params
+ // http params
public static final String SERIAL_NO = TOKEN_CERT_SERIAL;
public static final String REASON_CODE = "reasonCode";
public static final String CHALLENGE_PHRASE = "challengePhrase";
@@ -102,10 +101,10 @@ public class ChallengeRevocationServlet1 extends CMSServlet {
}
/**
- * Initialize the servlet. This servlet uses the file
- * revocationResult.template for the response
- *
- * @param sc servlet configuration, read from the web.xml file
+ * Initialize the servlet. This servlet uses the file
+ * revocationResult.template for the response
+ *
+ * @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
super.init(sc);
@@ -125,17 +124,17 @@ public class ChallengeRevocationServlet1 extends CMSServlet {
mQueue = mAuthority.getRequestQueue();
}
- /**
- * Process the HTTP request.
+ /**
+ * Process the HTTP request.
* <ul>
* <li>http.param REASON_CODE the revocation reason
- * <li>http.param b64eCertificate the base-64 encoded certificate to revoke
+ * <li>http.param b64eCertificate the base-64 encoded certificate to revoke
* </ul>
- *
+ *
* @param cmsReq the object holding the request and response information
*/
- protected void process(CMSRequest cmsReq)
- throws EBaseException {
+ protected void process(CMSRequest cmsReq)
+ throws EBaseException {
IArgBlock httpParams = cmsReq.getHttpParams();
HttpServletRequest req = cmsReq.getHttpReq();
HttpServletResponse resp = cmsReq.getHttpResp();
@@ -159,27 +158,27 @@ public class ChallengeRevocationServlet1 extends CMSServlet {
// for audit log
IAuthToken authToken = authenticate(cmsReq);
String authMgr = AuditFormat.NOAUTH;
-
+
BigInteger[] serialNoArray = null;
if (authToken != null) {
serialNoArray = authToken.getInBigIntegerArray(SERIAL_NO);
}
// set revocation reason, default to unspecified if not set.
- int reasonCode =
- httpParams.getValueAsInt(REASON_CODE, 0);
- // header.addIntegerValue("reason", reasonCode);
+ int reasonCode =
+ httpParams.getValueAsInt(REASON_CODE, 0);
+ // header.addIntegerValue("reason", reasonCode);
RevocationReason reason = RevocationReason.fromInt(reasonCode);
String comments = req.getParameter(IRequest.REQUESTOR_COMMENTS);
Date invalidityDate = null;
String revokeAll = null;
- int totalRecordCount = (serialNoArray != null)? serialNoArray.length:0;
- int verifiedRecordCount = (serialNoArray != null)? serialNoArray.length:0;
+ int totalRecordCount = (serialNoArray != null) ? serialNoArray.length : 0;
+ int verifiedRecordCount = (serialNoArray != null) ? serialNoArray.length : 0;
X509CertImpl[] certs = null;
- //for audit log.
+ // for audit log.
String initiative = null;
if (mAuthMgr != null && mAuthMgr.equals(IAuthSubsystem.CERTUSERDB_AUTHMGR_ID)) {
@@ -198,11 +197,11 @@ public class ChallengeRevocationServlet1 extends CMSServlet {
AuthzToken authzToken = null;
try {
- authzToken = authorize(mAclMethod, authToken,
+ authzToken = authorize(mAclMethod, authToken,
mAuthzResourceName, "revoke");
} catch (Exception e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -222,7 +221,7 @@ public class ChallengeRevocationServlet1 extends CMSServlet {
IRequest getCertsChallengeReq = null;
getCertsChallengeReq = mQueue.newRequest(
- GETCERTS_FOR_CHALLENGE_REQUEST);
+ GETCERTS_FOR_CHALLENGE_REQUEST);
getCertsChallengeReq.setExtData(SERIALNO_ARRAY, serialNoArray);
mQueue.processRequest(getCertsChallengeReq);
RequestStatus status = getCertsChallengeReq.getRequestStatus();
@@ -232,7 +231,7 @@ public class ChallengeRevocationServlet1 extends CMSServlet {
header.addStringValue("request", getCertsChallengeReq.getRequestId().toString());
mRequestID = getCertsChallengeReq.getRequestId().toString();
} else {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_FAIL_GET_CERT_CHALL_PWRD"));
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_FAIL_GET_CERT_CHALL_PWRD"));
}
}
@@ -243,20 +242,20 @@ public class ChallengeRevocationServlet1 extends CMSServlet {
IArgBlock rarg = CMS.createArgBlock();
rarg.addBigIntegerValue("serialNumber",
- serialNoArray[i], 16);
+ serialNoArray[i], 16);
rarg.addStringValue("subject",
- certs[i].getSubjectDN().toString());
+ certs[i].getSubjectDN().toString());
rarg.addLongValue("validNotBefore",
- certs[i].getNotBefore().getTime() / 1000);
+ certs[i].getNotBefore().getTime() / 1000);
rarg.addLongValue("validNotAfter",
- certs[i].getNotAfter().getTime() / 1000);
- //argSet.addRepeatRecord(rarg);
+ certs[i].getNotAfter().getTime() / 1000);
+ // argSet.addRepeatRecord(rarg);
}
revokeAll = "(|(certRecordId=" + serialNoArray[0].toString() + "))";
process(argSet, header, reasonCode, invalidityDate, initiative, req, resp,
- verifiedRecordCount, revokeAll, totalRecordCount,
- comments, locale[0]);
+ verifiedRecordCount, revokeAll, totalRecordCount,
+ comments, locale[0]);
} else {
header.addIntegerValue("totalRecordCount", 0);
header.addIntegerValue("verifiedRecordCount", 0);
@@ -265,10 +264,10 @@ public class ChallengeRevocationServlet1 extends CMSServlet {
try {
ServletOutputStream out = resp.getOutputStream();
- if( serialNoArray == null ) {
- CMS.debug( "ChallengeRevcationServlet1::process() - " +
- " serialNoArray is null!" );
- EBaseException ee = new EBaseException( "No matched certificate is found" );
+ if (serialNoArray == null) {
+ CMS.debug("ChallengeRevcationServlet1::process() - " +
+ " serialNoArray is null!");
+ EBaseException ee = new EBaseException("No matched certificate is found");
cmsReq.setError(ee);
return;
@@ -282,31 +281,31 @@ public class ChallengeRevocationServlet1 extends CMSServlet {
} else {
String xmlOutput = req.getParameter("xml");
if (xmlOutput != null && xmlOutput.equals("true")) {
- outputXML(resp, argSet);
+ outputXML(resp, argSet);
} else {
- resp.setContentType("text/html");
- form.renderOutput(out, argSet);
- cmsReq.setStatus(CMSRequest.SUCCESS);
+ resp.setContentType("text/html");
+ form.renderOutput(out, argSet);
+ cmsReq.setStatus(CMSRequest.SUCCESS);
}
}
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_ERR_STREAM_TEMPLATE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_ERR_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(CMS.getLogMessage("CMSGW_ERROR_DISPLAY_TEMPLATE"));
}
}
private void process(CMSTemplateParams argSet, IArgBlock header,
- int reason, Date invalidityDate,
- String initiative,
- HttpServletRequest req,
- HttpServletResponse resp,
- int verifiedRecordCount,
- String revokeAll,
- int totalRecordCount,
- String comments,
- Locale locale)
- throws EBaseException {
+ int reason, Date invalidityDate,
+ String initiative,
+ HttpServletRequest req,
+ HttpServletResponse resp,
+ int verifiedRecordCount,
+ String revokeAll,
+ int totalRecordCount,
+ String comments,
+ Locale locale)
+ throws EBaseException {
try {
int count = 0;
Vector<X509CertImpl> oldCertsV = new Vector<X509CertImpl>();
@@ -344,18 +343,18 @@ public class ChallengeRevocationServlet1 extends CMSServlet {
IArgBlock rarg = CMS.createArgBlock();
rarg.addBigIntegerValue("serialNumber",
- cert.getSerialNumber(), 16);
+ cert.getSerialNumber(), 16);
if (rec.getStatus().equals(ICertRecord.STATUS_REVOKED)) {
rarg.addStringValue("error", "Certificate " +
- cert.getSerialNumber().toString() +
- " is already revoked.");
+ cert.getSerialNumber().toString() +
+ " is already revoked.");
} else {
oldCertsV.addElement(cert);
RevokedCertImpl revCertImpl =
- new RevokedCertImpl(cert.getSerialNumber(),
- CMS.getCurrentDate(), entryExtn);
+ new RevokedCertImpl(cert.getSerialNumber(),
+ CMS.getCurrentDate(), entryExtn);
revCertImplsV.addElement(revCertImpl);
count++;
@@ -367,14 +366,12 @@ public class ChallengeRevocationServlet1 extends CMSServlet {
} else if (mAuthority instanceof IRegistrationAuthority) {
String reqIdStr = null;
- if (mRequestID != null && mRequestID.length() > 0)
+ if (mRequestID != null && mRequestID.length() > 0)
reqIdStr = mRequestID;
Vector<String> serialNumbers = new Vector<String>();
if (revokeAll != null && revokeAll.length() > 0) {
- for (int i = revokeAll.indexOf('=');
- i < revokeAll.length() && i > -1;
- i = revokeAll.indexOf('=', i)) {
+ for (int i = revokeAll.indexOf('='); i < revokeAll.length() && i > -1; i = revokeAll.indexOf('=', i)) {
if (i > -1) {
i++;
while (i < revokeAll.length() && revokeAll.charAt(i) == ' ') {
@@ -383,8 +380,8 @@ public class ChallengeRevocationServlet1 extends CMSServlet {
String legalDigits = "0123456789";
int j = i;
- while (j < revokeAll.length() &&
- legalDigits.indexOf(revokeAll.charAt(j)) != -1) {
+ while (j < revokeAll.length() &&
+ legalDigits.indexOf(revokeAll.charAt(j)) != -1) {
j++;
}
if (j > i) {
@@ -411,12 +408,12 @@ public class ChallengeRevocationServlet1 extends CMSServlet {
IArgBlock rarg = CMS.createArgBlock();
rarg.addBigIntegerValue("serialNumber",
- certs[i].getSerialNumber(), 16);
+ certs[i].getSerialNumber(), 16);
oldCertsV.addElement(certs[i]);
RevokedCertImpl revCertImpl =
- new RevokedCertImpl(certs[i].getSerialNumber(),
- CMS.getCurrentDate(), entryExtn);
+ new RevokedCertImpl(certs[i].getSerialNumber(),
+ CMS.getCurrentDate(), entryExtn);
revCertImplsV.addElement(revCertImpl);
count++;
@@ -433,12 +430,12 @@ public class ChallengeRevocationServlet1 extends CMSServlet {
IArgBlock rarg = CMS.createArgBlock();
rarg.addBigIntegerValue("serialNumber",
- cert.getSerialNumber(), 16);
+ cert.getSerialNumber(), 16);
oldCertsV.addElement(cert);
RevokedCertImpl revCertImpl =
- new RevokedCertImpl(cert.getSerialNumber(),
- CMS.getCurrentDate(), entryExtn);
+ new RevokedCertImpl(cert.getSerialNumber(),
+ CMS.getCurrentDate(), entryExtn);
revCertImplsV.addElement(revCertImpl);
count++;
@@ -459,7 +456,7 @@ public class ChallengeRevocationServlet1 extends CMSServlet {
}
IRequest revReq =
- mQueue.newRequest(IRequest.REVOCATION_REQUEST);
+ mQueue.newRequest(IRequest.REVOCATION_REQUEST);
revReq.setExtData(IRequest.CERT_INFO, revCertImpls);
revReq.setExtData(IRequest.REQ_TYPE, IRequest.REVOCATION_REQUEST);
@@ -479,29 +476,29 @@ public class ChallengeRevocationServlet1 extends CMSServlet {
if (result.equals(IRequest.RES_ERROR)) {
String[] svcErrors =
- revReq.getExtDataInStringArray(IRequest.SVCERRORS);
+ revReq.getExtDataInStringArray(IRequest.SVCERRORS);
if (svcErrors != null && svcErrors.length > 0) {
for (int i = 0; i < svcErrors.length; i++) {
String err = svcErrors[i];
if (err != null) {
- //cmsReq.setErrorDescription(err);
+ // cmsReq.setErrorDescription(err);
for (int j = 0; j < count; j++) {
if (oldCerts[j] != null) {
mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.DOREVOKEFORMAT,
- new Object[] {
- revReq.getRequestId(),
- initiative,
- "completed with error: " +
- err,
- oldCerts[j].getSubjectDN(),
- oldCerts[j].getSerialNumber().toString(16),
- RevocationReason.fromInt(reason).toString()}
- );
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.DOREVOKEFORMAT,
+ new Object[] {
+ revReq.getRequestId(),
+ initiative,
+ "completed with error: " +
+ err,
+ oldCerts[j].getSubjectDN(),
+ oldCerts[j].getSerialNumber().toString(16),
+ RevocationReason.fromInt(reason).toString() }
+ );
}
}
}
@@ -514,23 +511,23 @@ public class ChallengeRevocationServlet1 extends CMSServlet {
for (int j = 0; j < count; j++) {
if (oldCerts[j] != null) {
mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.DOREVOKEFORMAT,
- new Object[] {
- revReq.getRequestId(),
- initiative,
- "completed",
- oldCerts[j].getSubjectDN(),
- oldCerts[j].getSerialNumber().toString(16),
- RevocationReason.fromInt(reason).toString()}
- );
+ AuditFormat.LEVEL,
+ AuditFormat.DOREVOKEFORMAT,
+ new Object[] {
+ revReq.getRequestId(),
+ initiative,
+ "completed",
+ oldCerts[j].getSubjectDN(),
+ oldCerts[j].getSerialNumber().toString(16),
+ RevocationReason.fromInt(reason).toString() }
+ );
}
}
header.addStringValue("revoked", "yes");
Integer updateCRLResult =
- revReq.getExtDataInInteger(IRequest.CRL_UPDATE_STATUS);
+ revReq.getExtDataInInteger(IRequest.CRL_UPDATE_STATUS);
if (updateCRLResult != null) {
header.addStringValue("updateCRL", "yes");
@@ -539,15 +536,15 @@ public class ChallengeRevocationServlet1 extends CMSServlet {
} else {
header.addStringValue("updateCRLSuccess", "no");
String crlError =
- revReq.getExtDataInString(IRequest.CRL_UPDATE_ERROR);
+ revReq.getExtDataInString(IRequest.CRL_UPDATE_ERROR);
if (crlError != null)
header.addStringValue("updateCRLError",
- crlError);
+ crlError);
}
// let known crl publishing status too.
Integer publishCRLResult =
- revReq.getExtDataInInteger(IRequest.CRL_PUBLISH_STATUS);
+ revReq.getExtDataInInteger(IRequest.CRL_PUBLISH_STATUS);
if (publishCRLResult != null) {
if (publishCRLResult.equals(IRequest.RES_SUCCESS)) {
@@ -555,22 +552,22 @@ public class ChallengeRevocationServlet1 extends CMSServlet {
} else {
header.addStringValue("publishCRLSuccess", "no");
String publError =
- revReq.getExtDataInString(IRequest.CRL_PUBLISH_ERROR);
+ revReq.getExtDataInString(IRequest.CRL_PUBLISH_ERROR);
if (publError != null)
header.addStringValue("publishCRLError",
- publError);
+ publError);
}
}
}
if (mAuthority instanceof ICertificateAuthority) {
// let known update and publish status of all crls.
Enumeration<ICRLIssuingPoint> otherCRLs =
- ((ICertificateAuthority) mAuthority).getCRLIssuingPoints();
+ ((ICertificateAuthority) mAuthority).getCRLIssuingPoints();
while (otherCRLs.hasMoreElements()) {
ICRLIssuingPoint crl = (ICRLIssuingPoint)
- otherCRLs.nextElement();
+ otherCRLs.nextElement();
String crlId = crl.getId();
if (crlId.equals(ICertificateAuthority.PROP_MASTER_CRL))
@@ -580,25 +577,25 @@ public class ChallengeRevocationServlet1 extends CMSServlet {
if (updateResult != null) {
if (updateResult.equals(IRequest.RES_SUCCESS)) {
- CMS.debug("ChallengeRevcationServlet1: " + CMS.getLogMessage("ADMIN_SRVLT_ADDING_HEADER",
+ CMS.debug("ChallengeRevcationServlet1: " + CMS.getLogMessage("ADMIN_SRVLT_ADDING_HEADER",
updateStatusStr));
header.addStringValue(updateStatusStr, "yes");
} else {
String updateErrorStr = crl.getCrlUpdateErrorStr();
- CMS.debug("ChallengeRevcationServlet1: " + CMS.getLogMessage("ADMIN_SRVLT_ADDING_HEADER_NO",
+ CMS.debug("ChallengeRevcationServlet1: " + CMS.getLogMessage("ADMIN_SRVLT_ADDING_HEADER_NO",
updateStatusStr));
header.addStringValue(updateStatusStr, "no");
String error =
- revReq.getExtDataInString(updateErrorStr);
+ revReq.getExtDataInString(updateErrorStr);
if (error != null)
header.addStringValue(updateErrorStr,
- error);
+ error);
}
String publishStatusStr = crl.getCrlPublishStatusStr();
Integer publishResult =
- revReq.getExtDataInInteger(publishStatusStr);
+ revReq.getExtDataInInteger(publishStatusStr);
if (publishResult == null)
continue;
@@ -606,15 +603,15 @@ public class ChallengeRevocationServlet1 extends CMSServlet {
header.addStringValue(publishStatusStr, "yes");
} else {
String publishErrorStr =
- crl.getCrlPublishErrorStr();
+ crl.getCrlPublishErrorStr();
header.addStringValue(publishStatusStr, "no");
String error =
- revReq.getExtDataInString(publishErrorStr);
+ revReq.getExtDataInString(publishErrorStr);
if (error != null)
header.addStringValue(
- publishErrorStr, error);
+ publishErrorStr, error);
}
}
}
@@ -623,7 +620,7 @@ public class ChallengeRevocationServlet1 extends CMSServlet {
if (mPublisherProcessor != null && mPublisherProcessor.ldapEnabled()) {
header.addStringValue("dirEnabled", "yes");
Integer[] ldapPublishStatus =
- revReq.getExtDataInIntegerArray("ldapPublishStatus");
+ revReq.getExtDataInIntegerArray("ldapPublishStatus");
int certsToUpdate = 0;
int certsUpdated = 0;
@@ -640,11 +637,11 @@ public class ChallengeRevocationServlet1 extends CMSServlet {
// add crl publishing status.
String publError =
- revReq.getExtDataInString(IRequest.CRL_PUBLISH_ERROR);
+ revReq.getExtDataInString(IRequest.CRL_PUBLISH_ERROR);
if (publError != null) {
header.addStringValue("crlPublishError",
- publError);
+ publError);
}
} else {
header.addStringValue("dirEnabled", "no");
@@ -658,16 +655,16 @@ public class ChallengeRevocationServlet1 extends CMSServlet {
for (int j = 0; j < count; j++) {
if (oldCerts[j] != null) {
mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.DOREVOKEFORMAT,
- new Object[] {
- revReq.getRequestId(),
- initiative,
- "pending",
- oldCerts[j].getSubjectDN(),
- oldCerts[j].getSerialNumber().toString(16),
- RevocationReason.fromInt(reason).toString()}
- );
+ AuditFormat.LEVEL,
+ AuditFormat.DOREVOKEFORMAT,
+ new Object[] {
+ revReq.getRequestId(),
+ initiative,
+ "pending",
+ oldCerts[j].getSubjectDN(),
+ oldCerts[j].getSerialNumber().toString(16),
+ RevocationReason.fromInt(reason).toString() }
+ );
}
}
@@ -686,16 +683,16 @@ public class ChallengeRevocationServlet1 extends CMSServlet {
for (int j = 0; j < count; j++) {
if (oldCerts[j] != null) {
mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.DOREVOKEFORMAT,
- new Object[] {
- revReq.getRequestId(),
- initiative,
- stat.toString(),
- oldCerts[j].getSubjectDN(),
- oldCerts[j].getSerialNumber().toString(16),
- RevocationReason.fromInt(reason).toString()}
- );
+ AuditFormat.LEVEL,
+ AuditFormat.DOREVOKEFORMAT,
+ new Object[] {
+ revReq.getRequestId(),
+ initiative,
+ stat.toString(),
+ oldCerts[j].getSubjectDN(),
+ oldCerts[j].getSerialNumber().toString(16),
+ RevocationReason.fromInt(reason).toString() }
+ );
}
}
}
@@ -706,7 +703,7 @@ public class ChallengeRevocationServlet1 extends CMSServlet {
throw e;
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_MARKING_CERT_REVOKED", e.toString()));
+ CMS.getLogMessage("CMSGW_ERROR_MARKING_CERT_REVOKED", e.toString()));
throw new ECMSGWException(CMS.getLogMessage("CMSGW_ERROR_MARKING_CERT_REVOKED"));
} catch (Exception e) {
e.printStackTrace();
@@ -715,4 +712,3 @@ public class ChallengeRevocationServlet1 extends CMSServlet {
return;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/CloneRedirect.java b/pki/base/common/src/com/netscape/cms/servlet/cert/CloneRedirect.java
index b3693a53..fb531759 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/CloneRedirect.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/CloneRedirect.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.io.IOException;
import java.util.Locale;
@@ -39,12 +38,11 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
- * Redirect a request to the Master. This servlet is used in
- * a clone when a requested service (such as CRL) is not available.
- * It redirects the user to the master.
- *
+ * Redirect a request to the Master. This servlet is used in a clone when a
+ * requested service (such as CRL) is not available. It redirects the user to
+ * the master.
+ *
* @version $Revision$, $Date$
*/
public class CloneRedirect extends CMSServlet {
@@ -71,7 +69,8 @@ public class CloneRedirect extends CMSServlet {
/**
* Initialize the servlet.
- * @param sc servlet configuration, read from the web.xml file
+ *
+ * @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
super.init(sc);
@@ -93,8 +92,8 @@ public class CloneRedirect extends CMSServlet {
if (mAuthority instanceof ICertificateAuthority)
mCA = (ICertificateAuthority) mAuthority;
-
- // override success to do output with our own template.
+
+ // override success to do output with our own template.
mTemplates.remove(CMSRequest.SUCCESS);
}
@@ -117,28 +116,28 @@ public class CloneRedirect extends CMSServlet {
try {
form = getTemplate(mFormPath, req, locale);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_DISPLAY_TEMPLATE"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERROR_DISPLAY_TEMPLATE"));
throw new ECMSGWException(
CMS.getLogMessage("CMSGW_ERROR_DISPLAY_TEMPLATE"));
}
- CMS.debug("CloneRedirect: " + CMS.getLogMessage("ADMIN_SRVLT_ADD_MASTER_URL", mNewUrl));
+ CMS.debug("CloneRedirect: " + CMS.getLogMessage("ADMIN_SRVLT_ADD_MASTER_URL", mNewUrl));
header.addStringValue("masterURL", mNewUrl);
try {
ServletOutputStream out = resp.getOutputStream();
String xmlOutput = req.getParameter("xml");
- if (xmlOutput != null && xmlOutput.equals("true")) {
- outputXML(resp, argSet);
- } else {
- resp.setContentType("text/html");
- form.renderOutput(out, argSet);
- cmsReq.setStatus(CMSRequest.SUCCESS);
- }
+ if (xmlOutput != null && xmlOutput.equals("true")) {
+ outputXML(resp, argSet);
+ } else {
+ resp.setContentType("text/html");
+ form.renderOutput(out, argSet);
+ cmsReq.setStatus(CMSRequest.SUCCESS);
+ }
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_ERR_STREAM_TEMPLATE", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_ERR_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(CMS.getLogMessage("CMSGW_ERROR_DISPLAY_TEMPLATE"));
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/DirAuthServlet.java b/pki/base/common/src/com/netscape/cms/servlet/cert/DirAuthServlet.java
index 0ccf7f18..03c909cc 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/DirAuthServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/DirAuthServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.io.IOException;
import java.util.Date;
import java.util.Locale;
@@ -45,10 +44,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* 'Face-to-face' certificate enrollment.
- *
+ *
* @version $Revision$, $Date$
*/
public class DirAuthServlet extends CMSServlet {
@@ -64,8 +62,9 @@ public class DirAuthServlet extends CMSServlet {
super();
}
- /**
+ /**
* initialize the servlet.
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -81,15 +80,14 @@ public class DirAuthServlet extends CMSServlet {
mTemplates.remove(CMSRequest.SUCCESS);
}
-
- /**
+ /**
* Process the HTTP request. This servlet reads configuration information
- * from the hashDirEnrollment configuration substore
- *
+ * from the hashDirEnrollment configuration substore
+ *
* @param cmsReq the object holding the request and response information
*/
protected void process(CMSRequest cmsReq)
- throws EBaseException {
+ throws EBaseException {
HttpServletRequest httpReq = cmsReq.getHttpReq();
HttpServletResponse httpResp = cmsReq.getHttpResp();
@@ -112,8 +110,8 @@ public class DirAuthServlet extends CMSServlet {
try {
form = getTemplate(mFormPath, httpReq, locale);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_DISPLAY_TEMPLATE"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERROR_DISPLAY_TEMPLATE"));
cmsReq.setError(new ECMSGWException(
CMS.getLogMessage("CMSGW_ERROR_DISPLAY_TEMPLATE")));
cmsReq.setStatus(CMSRequest.ERROR);
@@ -166,7 +164,7 @@ public class DirAuthServlet extends CMSServlet {
printError(cmsReq, "2");
cmsReq.setStatus(CMSRequest.SUCCESS);
return;
- }
+ }
mgr.setLastLogin(reqHost, currTime);
@@ -176,11 +174,11 @@ public class DirAuthServlet extends CMSServlet {
mgr.addAuthToken(pageID, authToken);
- header.addStringValue("pageID", pageID);
+ header.addStringValue("pageID", pageID);
header.addStringValue("uid", uid);
header.addStringValue("fingerprint", mgr.hashFingerprint(reqHost, pageID, uid));
header.addStringValue("hostname", reqHost);
-
+
try {
ServletOutputStream out = httpResp.getOutputStream();
@@ -188,8 +186,8 @@ public class DirAuthServlet extends CMSServlet {
form.renderOutput(out, argSet);
cmsReq.setStatus(CMSRequest.SUCCESS);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_ERR_STREAM_TEMPLATE", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_ERR_STREAM_TEMPLATE", e.toString()));
cmsReq.setError(new ECMSGWException(
CMS.getLogMessage("CMSGW_ERROR_DISPLAY_TEMPLATE")));
cmsReq.setStatus(CMSRequest.ERROR);
@@ -199,7 +197,7 @@ public class DirAuthServlet extends CMSServlet {
}
private void printError(CMSRequest cmsReq, String errorCode)
- throws EBaseException {
+ throws EBaseException {
IArgBlock httpParams = cmsReq.getHttpParams();
HttpServletRequest httpReq = cmsReq.getHttpReq();
HttpServletResponse httpResp = cmsReq.getHttpResp();
@@ -219,7 +217,7 @@ public class DirAuthServlet extends CMSServlet {
form = getTemplate(formPath, httpReq, locale);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_ERR_GET_TEMPLATE", formPath, e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_ERR_GET_TEMPLATE", formPath, e.toString()));
cmsReq.setError(new ECMSGWException(
CMS.getLogMessage("CMSGW_ERROR_DISPLAY_TEMPLATE")));
cmsReq.setStatus(CMSRequest.ERROR);
@@ -234,7 +232,7 @@ public class DirAuthServlet extends CMSServlet {
cmsReq.setStatus(CMSRequest.SUCCESS);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_ERR_STREAM_TEMPLATE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_ERR_STREAM_TEMPLATE", e.toString()));
cmsReq.setError(new ECMSGWException(
CMS.getLogMessage("CMSGW_ERROR_DISPLAY_TEMPLATE")));
cmsReq.setStatus(CMSRequest.ERROR);
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/DisableEnrollResult.java b/pki/base/common/src/com/netscape/cms/servlet/cert/DisableEnrollResult.java
index 9f353312..a5cdc98e 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/DisableEnrollResult.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/DisableEnrollResult.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.io.IOException;
import java.security.cert.X509Certificate;
import java.util.Locale;
@@ -45,10 +44,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* For Face-to-face enrollment, disable EE enrollment feature
- *
+ *
* @version $Revision$, $Date$
* @see com.netscape.cms.servlet.cert.EnableEnrollResult
*/
@@ -83,7 +81,7 @@ public class DisableEnrollResult extends CMSServlet {
* Services the request
*/
protected void process(CMSRequest cmsReq)
- throws EBaseException {
+ throws EBaseException {
HttpServletRequest httpReq = cmsReq.getHttpReq();
HttpServletResponse httpResp = cmsReq.getHttpResp();
@@ -125,10 +123,10 @@ public class DisableEnrollResult extends CMSServlet {
try {
form = getTemplate(mFormPath, httpReq, locale);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_ERR_GET_TEMPLATE", mFormPath, e.toString()));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
cmsReq.setStatus(CMSRequest.ERROR);
return;
}
@@ -162,10 +160,10 @@ public class DisableEnrollResult extends CMSServlet {
form.renderOutput(out, argSet);
cmsReq.setStatus(CMSRequest.SUCCESS);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_ERR_STREAM_TEMPLATE", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_ERR_STREAM_TEMPLATE", e.toString()));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
cmsReq.setStatus(CMSRequest.ERROR);
}
cmsReq.setStatus(CMSRequest.SUCCESS);
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/DisplayBySerial.java b/pki/base/common/src/com/netscape/cms/servlet/cert/DisplayBySerial.java
index ea62b9cb..2a32b594 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/DisplayBySerial.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/DisplayBySerial.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
@@ -67,13 +66,12 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* Display detailed information about a certificate
- *
- * The template 'displayBySerial.template' is used to
- * render the response for this servlet.
- *
+ *
+ * The template 'displayBySerial.template' is used to render the response for
+ * this servlet.
+ *
* @version $Revision$, $Date$
*/
public class DisplayBySerial extends CMSServlet {
@@ -99,6 +97,7 @@ public class DisplayBySerial extends CMSServlet {
/**
* initialize the servlet.
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -109,16 +108,16 @@ public class DisplayBySerial extends CMSServlet {
try {
mCACerts = ((ICertAuthority) mAuthority).getCACertChain().getChain();
} catch (Exception e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_CA_CHAIN_NOT_AVAILABLE"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_CA_CHAIN_NOT_AVAILABLE"));
}
// coming from ee
mForm1Path = "/" + mAuthority.getId() + "/" + TPL_FILE1;
-
- if (mOutputTemplatePath != null)
+
+ if (mOutputTemplatePath != null)
mForm1Path = mOutputTemplatePath;
- // override success and error templates to null -
+ // override success and error templates to null -
// handle templates locally.
mTemplates.remove(CMSRequest.SUCCESS);
}
@@ -126,8 +125,8 @@ public class DisplayBySerial extends CMSServlet {
/**
* Serves HTTP request. The format of this request is as follows:
* <ul>
- * <li>http.param serialNumber Decimal serial number of certificate to display
- * (or hex if serialNumber preceded by 0x)
+ * <li>http.param serialNumber Decimal serial number of certificate to
+ * display (or hex if serialNumber preceded by 0x)
* </ul>
*/
public void process(CMSRequest cmsReq) throws EBaseException {
@@ -151,7 +150,7 @@ public class DisplayBySerial extends CMSServlet {
mAuthzResourceName, "read");
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -170,8 +169,8 @@ public class DisplayBySerial extends CMSServlet {
error = new ECMSGWException(CMS.getLogMessage("BASE_INVALID_NUMBER_FORMAT"));
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mForm1Path, e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mForm1Path, e.toString()));
throw new ECMSGWException(
CMS.getLogMessage("CMSGW_ERROR_DISPLAY_TEMPLATE"));
} catch (EDBRecordNotFoundException e) {
@@ -185,15 +184,15 @@ public class DisplayBySerial extends CMSServlet {
try {
if (serialNumber.compareTo(MINUS_ONE) > 0) {
- process(argSet, header, serialNumber,
- req, resp, locale[0]);
+ process(argSet, header, serialNumber,
+ req, resp, locale[0]);
} else {
error = new ECMSGWException(
CMS.getLogMessage("CMSGW_INVALID_SERIAL_NUMBER"));
}
} catch (EBaseException e) {
error = e;
- }
+ }
try {
ServletOutputStream out = resp.getOutputStream();
@@ -201,19 +200,19 @@ public class DisplayBySerial extends CMSServlet {
if (error == null) {
String xmlOutput = req.getParameter("xml");
if (xmlOutput != null && xmlOutput.equals("true")) {
- outputXML(resp, argSet);
+ outputXML(resp, argSet);
} else {
- resp.setContentType("text/html");
- form.renderOutput(out, argSet);
- cmsReq.setStatus(CMSRequest.SUCCESS);
+ resp.setContentType("text/html");
+ form.renderOutput(out, argSet);
+ cmsReq.setStatus(CMSRequest.SUCCESS);
}
} else {
cmsReq.setStatus(CMSRequest.ERROR);
cmsReq.setError(error);
}
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_BAD_SERV_OUT_STREAM", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_BAD_SERV_OUT_STREAM", e.toString()));
throw new ECMSGWException(CMS.getLogMessage("CMSGW_ERROR_DISPLAY_TEMPLATE"));
}
@@ -223,53 +222,53 @@ public class DisplayBySerial extends CMSServlet {
* Display information about a particular certificate
*/
private void process(CMSTemplateParams argSet, IArgBlock header,
- BigInteger seq, HttpServletRequest req,
- HttpServletResponse resp,
- Locale locale)
- throws EBaseException {
+ BigInteger seq, HttpServletRequest req,
+ HttpServletResponse resp,
+ Locale locale)
+ throws EBaseException {
String certType[] = new String[1];
try {
ICertRecord rec = getCertRecord(seq, certType);
-
+
if (certType[0].equalsIgnoreCase("x509")) {
processX509(argSet, header, seq, req, resp, locale);
return;
}
} catch (EBaseException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_DISP_BY_SERIAL", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_DISP_BY_SERIAL", e.toString()));
throw e;
}
-
+
return;
}
-
+
private void processX509(CMSTemplateParams argSet, IArgBlock header,
- BigInteger seq, HttpServletRequest req,
- HttpServletResponse resp,
- Locale locale)
- throws EBaseException {
+ BigInteger seq, HttpServletRequest req,
+ HttpServletResponse resp,
+ Locale locale)
+ throws EBaseException {
try {
ICertRecord rec = (ICertRecord) mCertDB.readCertificateRecord(seq);
- if (rec == null) {
- CMS.debug("DisplayBySerial: failed to read record");
- throw new ECMSGWException(
- CMS.getLogMessage("CMSGW_ERROR_ENCODING_ISSUED_CERT"));
+ if (rec == null) {
+ CMS.debug("DisplayBySerial: failed to read record");
+ throw new ECMSGWException(
+ CMS.getLogMessage("CMSGW_ERROR_ENCODING_ISSUED_CERT"));
}
X509CertImpl cert = rec.getCertificate();
- if (cert == null) {
- CMS.debug("DisplayBySerial: no certificate in record");
- throw new ECMSGWException(
- CMS.getLogMessage("CMSGW_ERROR_ENCODING_ISSUED_CERT"));
+ if (cert == null) {
+ CMS.debug("DisplayBySerial: no certificate in record");
+ throw new ECMSGWException(
+ CMS.getLogMessage("CMSGW_ERROR_ENCODING_ISSUED_CERT"));
}
try {
X509CertInfo info = (X509CertInfo) cert.get(X509CertImpl.NAME + "." + X509CertImpl.INFO);
- if (info == null) {
- CMS.debug("DisplayBySerial: no info found");
- throw new ECMSGWException(
- CMS.getLogMessage("CMSGW_ERROR_ENCODING_ISSUED_CERT"));
+ if (info == null) {
+ CMS.debug("DisplayBySerial: no info found");
+ throw new ECMSGWException(
+ CMS.getLogMessage("CMSGW_ERROR_ENCODING_ISSUED_CERT"));
}
CertificateExtensions extensions = (CertificateExtensions) info.get(X509CertInfo.EXTENSIONS);
@@ -287,11 +286,11 @@ public class DisplayBySerial extends CMSServlet {
}
if (ext instanceof KeyUsageExtension) {
KeyUsageExtension usage =
- (KeyUsageExtension) ext;
+ (KeyUsageExtension) ext;
try {
if (((Boolean) usage.get(KeyUsageExtension.DIGITAL_SIGNATURE)).booleanValue() ||
- ((Boolean) usage.get(KeyUsageExtension.DATA_ENCIPHERMENT)).booleanValue())
+ ((Boolean) usage.get(KeyUsageExtension.DATA_ENCIPHERMENT)).booleanValue())
emailCert = true;
} catch (ArrayIndexOutOfBoundsException e) {
// bug356108:
@@ -321,8 +320,8 @@ public class DisplayBySerial extends CMSServlet {
header.addBooleanValue("noCertImport", noCertImport);
} catch (Exception e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_PARSING_EXTENS", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERROR_PARSING_EXTENS", e.toString()));
}
IRevocationInfo revocationInfo = rec.getRevocationInfo();
@@ -347,20 +346,16 @@ public class DisplayBySerial extends CMSServlet {
ICertPrettyPrint certDetails = CMS.getCertPrettyPrint(cert);
- header.addStringValue("certPrettyPrint",
- certDetails.toString(locale));
+ header.addStringValue("certPrettyPrint",
+ certDetails.toString(locale));
/*
- String scheme = req.getScheme();
- if (scheme.equals("http") && connectionIsSSL(req))
- scheme = "https";
- String requestURI = req.getRequestURI();
- int i = requestURI.indexOf('?');
- String newRequestURI =
- (i > -1)? requestURI.substring(0, i): requestURI;
- header.addStringValue("serviceURL", scheme +"://"+
- req.getServerName() + ":"+
- req.getServerPort() + newRequestURI);
+ * String scheme = req.getScheme(); if (scheme.equals("http") &&
+ * connectionIsSSL(req)) scheme = "https"; String requestURI =
+ * req.getRequestURI(); int i = requestURI.indexOf('?'); String
+ * newRequestURI = (i > -1)? requestURI.substring(0, i): requestURI;
+ * header.addStringValue("serviceURL", scheme +"://"+
+ * req.getServerName() + ":"+ req.getServerPort() + newRequestURI);
*/
header.addStringValue("authorityid", mAuthority.getId());
@@ -369,8 +364,8 @@ public class DisplayBySerial extends CMSServlet {
try {
certFingerprints = CMS.getFingerPrints(cert);
} catch (Exception e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_DIGESTING_CERT", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_DIGESTING_CERT", e.toString()));
}
if (certFingerprints.length() > 0)
header.addStringValue("certFingerprint", certFingerprints);
@@ -382,12 +377,12 @@ public class DisplayBySerial extends CMSServlet {
header.addStringValue("serialNumber", seq.toString(16));
/*
- String userAgent = req.getHeader("user-agent");
- String agent =
- (userAgent != null)? UserInfo.getUserAgent(userAgent): "";
+ * String userAgent = req.getHeader("user-agent"); String agent =
+ * (userAgent != null)? UserInfo.getUserAgent(userAgent): "";
*/
// Now formulate a PKCS#7 blob
- X509CertImpl[] certsInChain = new X509CertImpl[1];;
+ X509CertImpl[] certsInChain = new X509CertImpl[1];
+ ;
if (mCACerts != null) {
for (int i = 0; i < mCACerts.length; i++) {
if (cert.equals(mCACerts[i])) {
@@ -398,10 +393,10 @@ public class DisplayBySerial extends CMSServlet {
certsInChain = new X509CertImpl[mCACerts.length + 1];
}
}
-
+
// Set the EE cert
certsInChain[0] = cert;
-
+
// Set the Ca certificate chain
if (mCACerts != null) {
for (int i = 0; i < mCACerts.length; i++) {
@@ -414,43 +409,43 @@ public class DisplayBySerial extends CMSServlet {
String p7Str;
try {
- PKCS7 p7 = new PKCS7(new AlgorithmId[0],
+ PKCS7 p7 = new PKCS7(new AlgorithmId[0],
new ContentInfo(new byte[0]),
certsInChain,
new SignerInfo[0]);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
- p7.encodeSignedData(bos,false);
+ p7.encodeSignedData(bos, false);
byte[] p7Bytes = bos.toByteArray();
- p7Str = com.netscape.osutil.OSUtil.BtoA(p7Bytes);
+ p7Str = com.netscape.osutil.OSUtil.BtoA(p7Bytes);
header.addStringValue("pkcs7ChainBase64", p7Str);
} catch (Exception e) {
- //p7Str = "PKCS#7 B64 Encoding error - " + e.toString()
- //+ "; Please contact your administrator";
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_FORMING_PKCS7_1", e.toString()));
+ // p7Str = "PKCS#7 B64 Encoding error - " + e.toString()
+ // + "; Please contact your administrator";
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERROR_FORMING_PKCS7_1", e.toString()));
throw new ECMSGWException(
CMS.getLogMessage("CMSGW_ERROR_FORMING_PKCS7"));
}
} catch (EBaseException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("MSGW_ERR_DISP_BY_SERIAL", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("MSGW_ERR_DISP_BY_SERIAL", e.toString()));
throw e;
} catch (CertificateEncodingException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_ENCODE_CERT", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_ENCODE_CERT", e.toString()));
throw new ECMSGWException(
CMS.getLogMessage("CMSGW_ERROR_ENCODING_ISSUED_CERT"));
}
return;
}
-
+
private ICertRecord getCertRecord(BigInteger seq, String certtype[])
- throws EBaseException {
+ throws EBaseException {
ICertRecord rec = null;
-
+
try {
rec = (ICertRecord) mCertDB.readCertificateRecord(seq);
X509CertImpl x509cert = rec.getCertificate();
@@ -460,16 +455,16 @@ public class DisplayBySerial extends CMSServlet {
return rec;
}
} catch (EBaseException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_DISP_BY_SERIAL", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_DISP_BY_SERIAL", e.toString()));
throw e;
}
-
+
return rec;
}
private BigInteger getSerialNumber(HttpServletRequest req)
- throws NumberFormatException {
+ throws NumberFormatException {
String serialNumString = req.getParameter("serialNumber");
if (serialNumString != null) {
@@ -477,11 +472,10 @@ public class DisplayBySerial extends CMSServlet {
if (serialNumString.startsWith("0x") || serialNumString.startsWith("0X")) {
return new BigInteger(serialNumString.substring(2), 16);
} else {
- return new BigInteger(serialNumString);
+ return new BigInteger(serialNumString);
}
- } else {
+ } else {
throw new NumberFormatException();
- }
+ }
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/DisplayCRL.java b/pki/base/common/src/com/netscape/cms/servlet/cert/DisplayCRL.java
index 3a5f3f06..cb0e1cf9 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/DisplayCRL.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/DisplayCRL.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.io.IOException;
import java.math.BigInteger;
import java.security.cert.CRLException;
@@ -50,10 +49,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* Decode the CRL and display it to the requester.
- *
+ *
* @version $Revision$, $Date$
*/
public class DisplayCRL extends CMSServlet {
@@ -64,8 +62,8 @@ public class DisplayCRL extends CMSServlet {
private static final long serialVersionUID = 1152016798229054027L;
private final static String INFO = "DisplayCRL";
private final static String TPL_FILE = "displayCRL.template";
- //private final static String E_TPL_FILE = "error.template";
- //private final static String OUT_ERROR = "errorDetails";
+ // private final static String E_TPL_FILE = "error.template";
+ // private final static String OUT_ERROR = "errorDetails";
private String mFormPath = null;
private ICertificateAuthority mCA = null;
@@ -78,9 +76,10 @@ public class DisplayCRL extends CMSServlet {
}
/**
- * Initialize the servlet. This servlet uses the 'displayCRL.template' file to
- * to render the response to the client.
- * @param sc servlet configuration, read from the web.xml file
+ * Initialize the servlet. This servlet uses the 'displayCRL.template' file
+ * to to render the response to the client.
+ *
+ * @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
super.init(sc);
@@ -96,15 +95,16 @@ public class DisplayCRL extends CMSServlet {
}
/**
- * Process the HTTP request
+ * Process the HTTP request
* <ul>
- * <li>http.param crlIssuingPoint number
- * <li>http.param crlDisplayType entireCRL or crlHeader or base64Encoded or deltaCRL
- * <li>http.param pageStart which page to start displaying from
- * <li>http.param pageSize number of entries to show per page
+ * <li>http.param crlIssuingPoint number
+ * <li>http.param crlDisplayType entireCRL or crlHeader or base64Encoded or
+ * deltaCRL
+ * <li>http.param pageStart which page to start displaying from
+ * <li>http.param pageSize number of entries to show per page
* </ul>
+ *
* @param cmsReq the Request to service.
-
*/
public void process(CMSRequest cmsReq) throws EBaseException {
HttpServletRequest req = cmsReq.getHttpReq();
@@ -132,8 +132,8 @@ public class DisplayCRL extends CMSServlet {
try {
form = getTemplate(mFormPath, req, locale);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE_1", mFormPath, e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE_1", mFormPath, e.toString()));
throw new ECMSGWException(
CMS.getLogMessage("CMSGW_ERROR_DISPLAY_TEMPLATE"));
}
@@ -148,22 +148,22 @@ public class DisplayCRL extends CMSServlet {
String crlIssuingPointId = req.getParameter("crlIssuingPoint");
process(argSet, header, req, resp, crlIssuingPointId,
- locale[0]);
+ locale[0]);
try {
ServletOutputStream out = resp.getOutputStream();
String xmlOutput = req.getParameter("xml");
- if (xmlOutput != null && xmlOutput.equals("true")) {
- outputXML(resp, argSet);
- } else {
- resp.setContentType("text/html");
- form.renderOutput(out, argSet);
- cmsReq.setStatus(CMSRequest.SUCCESS);
- }
+ if (xmlOutput != null && xmlOutput.equals("true")) {
+ outputXML(resp, argSet);
+ } else {
+ resp.setContentType("text/html");
+ form.renderOutput(out, argSet);
+ cmsReq.setStatus(CMSRequest.SUCCESS);
+ }
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_BAD_SERV_OUT_STREAM", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_BAD_SERV_OUT_STREAM", e.toString()));
throw new ECMSGWException(CMS.getLogMessage("CMSGW_ERROR_DISPLAY_TEMPLATE"));
}
}
@@ -192,24 +192,25 @@ public class DisplayCRL extends CMSServlet {
masterHost = CMS.getConfigStore().getString("master.ca.agent.host", "");
masterPort = CMS.getConfigStore().getString("master.ca.agent.port", "");
if (masterHost != null && masterHost.length() > 0 &&
- masterPort != null && masterPort.length() > 0) {
+ masterPort != null && masterPort.length() > 0) {
clonedCA = true;
ipNames = crlRepository.getIssuingPointsNames();
}
} catch (EBaseException e) {
}
-
+
if (clonedCA) {
if (crlIssuingPointId != null) {
if (ipNames != null && ipNames.size() > 0) {
int i;
for (i = 0; i < ipNames.size(); i++) {
- String ipName = (String)ipNames.elementAt(i);
+ String ipName = (String) ipNames.elementAt(i);
if (crlIssuingPointId.equals(ipName)) {
break;
}
}
- if (i >= ipNames.size()) crlIssuingPointId = null;
+ if (i >= ipNames.size())
+ crlIssuingPointId = null;
} else {
crlIssuingPointId = null;
}
@@ -226,13 +227,14 @@ public class DisplayCRL extends CMSServlet {
isCRLCacheEnabled = ip.isCRLCacheEnabled();
break;
}
- if (!ips.hasMoreElements()) crlIssuingPointId = null;
+ if (!ips.hasMoreElements())
+ crlIssuingPointId = null;
}
}
}
if (crlIssuingPointId == null) {
header.addStringValue("error",
- "Request to unspecified or non-existing CRL issuing point: "+ipId);
+ "Request to unspecified or non-existing CRL issuing point: " + ipId);
return;
}
@@ -240,22 +242,23 @@ public class DisplayCRL extends CMSServlet {
String crlDisplayType = req.getParameter("crlDisplayType");
- if (crlDisplayType == null) crlDisplayType = "cachedCRL";
+ if (crlDisplayType == null)
+ crlDisplayType = "cachedCRL";
header.addStringValue("crlDisplayType", crlDisplayType);
try {
- crlRecord =
+ crlRecord =
(ICRLIssuingPointRecord) mCA.getCRLRepository().readCRLIssuingPointRecord(crlIssuingPointId);
} catch (EBaseException e) {
header.addStringValue("error", e.toString(locale));
return;
}
if (crlRecord == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_CRL_NOT_YET_UPDATED_1", crlIssuingPointId));
- header.addStringValue("error",
- new ECMSGWException(CMS.getUserMessage(locale, "CMS_GW_CRL_NOT_YET_UPDATED")).toString());
- return;
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_CRL_NOT_YET_UPDATED_1", crlIssuingPointId));
+ header.addStringValue("error",
+ new ECMSGWException(CMS.getUserMessage(locale, "CMS_GW_CRL_NOT_YET_UPDATED")).toString());
+ return;
}
header.addStringValue("crlIssuingPoint", crlIssuingPointId);
@@ -283,10 +286,10 @@ public class DisplayCRL extends CMSServlet {
byte[] crlbytes = crlRecord.getCRL();
if (crlbytes == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_CRL_NOT_YET_UPDATED_1", crlIssuingPointId));
- header.addStringValue("error",
- new ECMSGWException(CMS.getUserMessage(locale, "CMS_GW_CRL_NOT_YET_UPDATED")).toString());
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_CRL_NOT_YET_UPDATED_1", crlIssuingPointId));
+ header.addStringValue("error",
+ new ECMSGWException(CMS.getUserMessage(locale, "CMS_GW_CRL_NOT_YET_UPDATED")).toString());
return;
}
@@ -299,8 +302,8 @@ public class DisplayCRL extends CMSServlet {
} catch (Exception e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERR_DECODE_CRL", e.toString()));
- header.addStringValue("error",
- new ECMSGWException(CMS.getUserMessage(locale, "CMS_GW_DECODE_CRL_FAILED")).toString());
+ header.addStringValue("error",
+ new ECMSGWException(CMS.getUserMessage(locale, "CMS_GW_DECODE_CRL_FAILED")).toString());
}
}
@@ -320,24 +323,25 @@ public class DisplayCRL extends CMSServlet {
long lPageStart = new Long(pageStart).longValue();
long lPageSize = new Long(pageSize).longValue();
- if (lPageStart < 1) lPageStart = 1;
+ if (lPageStart < 1)
+ lPageStart = 1;
// if (lPageStart + lPageSize - lCRLSize > 1)
- // lPageStart = lCRLSize - lPageSize + 1;
+ // lPageStart = lCRLSize - lPageSize + 1;
header.addStringValue(
- "crlPrettyPrint", crlDetails.toString(locale,
- lCRLSize, lPageStart, lPageSize));
+ "crlPrettyPrint", crlDetails.toString(locale,
+ lCRLSize, lPageStart, lPageSize));
header.addLongValue("pageStart", lPageStart);
header.addLongValue("pageSize", lPageSize);
} else {
header.addStringValue(
- "crlPrettyPrint", crlDetails.toString(locale));
+ "crlPrettyPrint", crlDetails.toString(locale));
}
} else if (crlDisplayType.equals("crlHeader")) {
ICRLPrettyPrint crlDetails = CMS.getCRLPrettyPrint(crl);
header.addStringValue(
- "crlPrettyPrint", crlDetails.toString(locale, lCRLSize, 0, 0));
+ "crlPrettyPrint", crlDetails.toString(locale, lCRLSize, 0, 0));
} else if (crlDisplayType.equals("base64Encoded")) {
try {
byte[] ba = crl.getEncoded();
@@ -377,14 +381,14 @@ public class DisplayCRL extends CMSServlet {
} catch (CRLException e) {
}
} else if (crlDisplayType.equals("deltaCRL")) {
- if ((clonedCA && crlRecord.getDeltaCRLSize() != null &&
- crlRecord.getDeltaCRLSize().longValue() > -1) ||
- (crlIP != null && crlIP.isDeltaCRLEnabled())) {
+ if ((clonedCA && crlRecord.getDeltaCRLSize() != null &&
+ crlRecord.getDeltaCRLSize().longValue() > -1) ||
+ (crlIP != null && crlIP.isDeltaCRLEnabled())) {
byte[] deltaCRLBytes = crlRecord.getDeltaCRL();
if (deltaCRLBytes == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_NO_DELTA_CRL", crlIssuingPointId));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_NO_DELTA_CRL", crlIssuingPointId));
header.addStringValue("error", "Delta CRL is not available");
} else {
X509CRLImpl deltaCRL = null;
@@ -393,23 +397,23 @@ public class DisplayCRL extends CMSServlet {
deltaCRL = new X509CRLImpl(deltaCRLBytes);
} catch (Exception e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERR_DECODE_DELTA_CRL", e.toString()));
- header.addStringValue("error",
- new ECMSGWException(CMS.getUserMessage(locale, "CMS_GW_DECODE_CRL_FAILED")).toString());
+ header.addStringValue("error",
+ new ECMSGWException(CMS.getUserMessage(locale, "CMS_GW_DECODE_CRL_FAILED")).toString());
}
if (deltaCRL != null) {
BigInteger crlNumber = crlRecord.getCRLNumber();
BigInteger deltaNumber = crlRecord.getDeltaCRLNumber();
if ((clonedCA && crlNumber != null && deltaNumber != null &&
- deltaNumber.compareTo(crlNumber) >= 0) ||
- (crlIP != null && crlIP.isThisCurrentDeltaCRL(deltaCRL))) {
+ deltaNumber.compareTo(crlNumber) >= 0) ||
+ (crlIP != null && crlIP.isThisCurrentDeltaCRL(deltaCRL))) {
header.addIntegerValue("deltaCRLSize",
- deltaCRL.getNumberOfRevokedCertificates());
+ deltaCRL.getNumberOfRevokedCertificates());
ICRLPrettyPrint crlDetails = CMS.getCRLPrettyPrint(deltaCRL);
header.addStringValue(
- "crlPrettyPrint", crlDetails.toString(locale, 0, 0, 0));
+ "crlPrettyPrint", crlDetails.toString(locale, 0, 0, 0));
try {
byte[] ba = deltaCRL.getEncoded();
@@ -455,8 +459,8 @@ public class DisplayCRL extends CMSServlet {
}
} else {
header.addStringValue("error", "Delta CRL is not enabled for " +
- crlIssuingPointId +
- " issuing point");
+ crlIssuingPointId +
+ " issuing point");
}
}
@@ -464,10 +468,10 @@ public class DisplayCRL extends CMSServlet {
header.addStringValue("error", CMS.getUserMessage(locale, "CMS_GW_CRL_CACHE_IS_NOT_ENABLED", crlIssuingPointId));
header.addStringValue("crlPrettyPrint", CMS.getUserMessage(locale, "CMS_GW_CRL_CACHE_IS_NOT_ENABLED", crlIssuingPointId));
} else {
- header.addStringValue("error",
- new ECMSGWException(CMS.getUserMessage(locale, "CMS_GW_DECODE_CRL_FAILED")).toString());
- header.addStringValue("crlPrettyPrint",
- new ECMSGWException(CMS.getUserMessage(locale, "CMS_GW_DECODE_CRL_FAILED")).toString());
+ header.addStringValue("error",
+ new ECMSGWException(CMS.getUserMessage(locale, "CMS_GW_DECODE_CRL_FAILED")).toString());
+ header.addStringValue("crlPrettyPrint",
+ new ECMSGWException(CMS.getUserMessage(locale, "CMS_GW_DECODE_CRL_FAILED")).toString());
}
return;
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/DisplayHashUserEnroll.java b/pki/base/common/src/com/netscape/cms/servlet/cert/DisplayHashUserEnroll.java
index 6efda2bb..8d2be7a4 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/DisplayHashUserEnroll.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/DisplayHashUserEnroll.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.io.IOException;
import java.util.Date;
import java.util.Locale;
@@ -45,11 +44,10 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
- * Servlet to report the status, ie, the agent-initiated user
- * enrollment is enabled or disabled.
- *
+ * Servlet to report the status, ie, the agent-initiated user enrollment is
+ * enabled or disabled.
+ *
* @version $Revision$, $Date$
*/
public class DisplayHashUserEnroll extends CMSServlet {
@@ -90,7 +88,7 @@ public class DisplayHashUserEnroll extends CMSServlet {
* Services the request
*/
protected void process(CMSRequest cmsReq)
- throws EBaseException {
+ throws EBaseException {
HttpServletRequest httpReq = cmsReq.getHttpReq();
HttpServletResponse httpResp = cmsReq.getHttpResp();
@@ -117,7 +115,7 @@ public class DisplayHashUserEnroll extends CMSServlet {
if (!(mAuthority instanceof IRegistrationAuthority)) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_ERR_GET_TEMPLATE"));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_NOT_YET_IMPLEMENTED")));
+ CMS.getUserMessage("CMS_GW_NOT_YET_IMPLEMENTED")));
cmsReq.setStatus(CMSRequest.ERROR);
return;
}
@@ -152,7 +150,7 @@ public class DisplayHashUserEnroll extends CMSServlet {
printError(cmsReq, "2");
cmsReq.setStatus(CMSRequest.SUCCESS);
return;
- }
+ }
mgr.setLastLogin(reqHost, currTime);
@@ -162,10 +160,10 @@ public class DisplayHashUserEnroll extends CMSServlet {
try {
form = getTemplate(mFormPath, httpReq, locale);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_ERR_GET_TEMPLATE", mFormPath, e.toString()));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
cmsReq.setStatus(CMSRequest.ERROR);
return;
}
@@ -177,10 +175,10 @@ public class DisplayHashUserEnroll extends CMSServlet {
form.renderOutput(out, argSet);
cmsReq.setStatus(CMSRequest.SUCCESS);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_OUT_STREAM_TEMPLATE", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_OUT_STREAM_TEMPLATE", e.toString()));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
cmsReq.setStatus(CMSRequest.ERROR);
}
cmsReq.setStatus(CMSRequest.SUCCESS);
@@ -188,7 +186,7 @@ public class DisplayHashUserEnroll extends CMSServlet {
}
private void printError(CMSRequest cmsReq, String errorCode)
- throws EBaseException {
+ throws EBaseException {
IArgBlock httpParams = cmsReq.getHttpParams();
HttpServletRequest httpReq = cmsReq.getHttpReq();
HttpServletResponse httpResp = cmsReq.getHttpResp();
@@ -208,9 +206,9 @@ public class DisplayHashUserEnroll extends CMSServlet {
form = getTemplate(formPath, httpReq, locale);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_ERR_GET_TEMPLATE", formPath, e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_ERR_GET_TEMPLATE", formPath, e.toString()));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
cmsReq.setStatus(CMSRequest.ERROR);
return;
}
@@ -223,10 +221,10 @@ public class DisplayHashUserEnroll extends CMSServlet {
cmsReq.setStatus(CMSRequest.SUCCESS);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_BAD_SERV_OUT_STREAM", "", e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_BAD_SERV_OUT_STREAM", "", e.toString()));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
cmsReq.setStatus(CMSRequest.ERROR);
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/DoRevoke.java b/pki/base/common/src/com/netscape/cms/servlet/cert/DoRevoke.java
index 3c562d65..e95d6dbe 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/DoRevoke.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/DoRevoke.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
@@ -71,10 +70,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* Revoke a Certificate
- *
+ *
* @version $Revision$, $Date$
*/
public class DoRevoke extends CMSServlet {
@@ -98,20 +96,19 @@ public class DoRevoke extends CMSServlet {
private final static String REVOKE = "revoke";
private final static String ON_HOLD = "on-hold";
private final static int ON_HOLD_REASON = 6;
- private final static String
- LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST =
- "LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_5";
- private final static String
- LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED =
- "LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED_7";
+ private final static String LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST =
+ "LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_5";
+ private final static String LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED =
+ "LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED_7";
public DoRevoke() {
super();
}
/**
- * initialize the servlet. This servlet uses the template
- * file "revocationResult.template" to render the result
+ * initialize the servlet. This servlet uses the template file
+ * "revocationResult.template" to render the result
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -145,16 +142,20 @@ public class DoRevoke extends CMSServlet {
}
/**
- * Serves HTTP request. The http parameters used by this request are as follows:
+ * Serves HTTP request. The http parameters used by this request are as
+ * follows:
+ *
* <pre>
* serialNumber Serial number of certificate to revoke (in HEX)
* revocationReason Revocation reason (Described below)
* totalRecordCount [number]
* verifiedRecordCount [number]
* invalidityDate [number of seconds in Jan 1,1970]
- *
+ *
* </pre>
+ *
* revocationReason can be one of these values:
+ *
* <pre>
* 0 = Unspecified (default)
* 1 = Key compromised
@@ -204,7 +205,7 @@ public class DoRevoke extends CMSServlet {
if (req.getParameter("verifiedRecordCount") != null) {
verifiedRecordCount = Integer.parseInt(
req.getParameter(
- "verifiedRecordCount"));
+ "verifiedRecordCount"));
}
if (req.getParameter("invalidityDate") != null) {
long l = Long.parseLong(req.getParameter(
@@ -228,8 +229,8 @@ public class DoRevoke extends CMSServlet {
try {
user = (IUser) mUL.locateUser(new Certificates(certChain));
} catch (Exception e) {
- CMS.debug("DoRevoke: Failed to map certificate '"+
- cert2.getSubjectDN().getName()+"' to user.");
+ CMS.debug("DoRevoke: Failed to map certificate '" +
+ cert2.getSubjectDN().getName() + "' to user.");
}
if (mUG.isMemberOf(user, "Subsystem Group")) {
skipNonceVerification = true;
@@ -249,8 +250,8 @@ public class DoRevoke extends CMSServlet {
} else {
CMS.debug("DoRevoke: Missing nonce");
}
- CMS.debug("DoRevoke: nonceVerified="+nonceVerified);
- CMS.debug("DoRevoke: skipNonceVerification="+skipNonceVerification);
+ CMS.debug("DoRevoke: nonceVerified=" + nonceVerified);
+ CMS.debug("DoRevoke: skipNonceVerification=" + skipNonceVerification);
if ((!nonceVerified) && (!skipNonceVerification)) {
cmsReq.setStatus(CMSRequest.UNAUTHORIZED);
return;
@@ -261,7 +262,7 @@ public class DoRevoke extends CMSServlet {
String eeSubjectDN = null;
String eeSerialNumber = null;
- //for audit log.
+ // for audit log.
String initiative = null;
String authMgr = AuditFormat.NOAUTH;
@@ -275,25 +276,24 @@ public class DoRevoke extends CMSServlet {
mAuthzResourceName, "revoke");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
cmsReq.setStatus(CMSRequest.UNAUTHORIZED);
return;
}
-
-
+
if (mAuthMgr != null && mAuthMgr.equals(IAuthSubsystem.CERTUSERDB_AUTHMGR_ID)) {
if (authToken != null) {
String serialNumber = req.getParameter("serialNumber");
X509CertImpl sslCert = (X509CertImpl) getSSLClientCertificate(req);
- if (serialNumber != null) {
+ if (serialNumber != null) {
eeSerialNumber = serialNumber;
}
@@ -306,12 +306,12 @@ public class DoRevoke extends CMSServlet {
} else {
// request is fromUser.
initiative = AuditFormat.FROMUSER;
-
+
String serialNumber = req.getParameter("serialNumber");
X509CertImpl sslCert = (X509CertImpl) getSSLClientCertificate(req);
if (serialNumber == null || sslCert == null ||
- !(serialNumber.equals(sslCert.getSerialNumber().toString(16)))) {
+ !(serialNumber.equals(sslCert.getSerialNumber().toString(16)))) {
authorized = false;
} else {
eeSubjectDN = sslCert.getSubjectDN().toString();
@@ -322,29 +322,24 @@ public class DoRevoke extends CMSServlet {
if (authorized) {
process(argSet, header, reason, invalidityDate, initiative,
- req, resp, verifiedRecordCount, revokeAll,
- totalRecordCount, eeSerialNumber, eeSubjectDN,
- comments, locale[0]);
+ req, resp, verifiedRecordCount, revokeAll,
+ totalRecordCount, eeSerialNumber, eeSubjectDN,
+ comments, locale[0]);
}
} catch (NumberFormatException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("BASE_INVALID_NUMBER_FORMAT"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("BASE_INVALID_NUMBER_FORMAT"));
error = new EBaseException(CMS.getLogMessage("BASE_INVALID_NUMBER_FORMAT"));
} catch (EBaseException e) {
error = e;
}
/*
- catch (Exception e) {
- noError = false;
- header.addStringValue(OUT_ERROR,
- MessageFormatter.getLocalizedString(
- errorlocale[0],
- BaseResources.class.getName(),
- BaseResources.INTERNAL_ERROR_1,
- e.toString()));
- }
+ * catch (Exception e) { noError = false;
+ * header.addStringValue(OUT_ERROR, MessageFormatter.getLocalizedString(
+ * errorlocale[0], BaseResources.class.getName(),
+ * BaseResources.INTERNAL_ERROR_1, e.toString())); }
*/
try {
@@ -353,11 +348,11 @@ public class DoRevoke extends CMSServlet {
if (error == null && authorized) {
String xmlOutput = req.getParameter("xml");
if (xmlOutput != null && xmlOutput.equals("true")) {
- outputXML(resp, argSet);
+ outputXML(resp, argSet);
} else {
- resp.setContentType("text/html");
- form.renderOutput(out, argSet);
- cmsReq.setStatus(CMSRequest.SUCCESS);
+ resp.setContentType("text/html");
+ form.renderOutput(out, argSet);
+ cmsReq.setStatus(CMSRequest.SUCCESS);
}
} else if (!authorized) {
cmsReq.setStatus(CMSRequest.UNAUTHORIZED);
@@ -366,8 +361,8 @@ public class DoRevoke extends CMSServlet {
cmsReq.setError(error);
}
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_OUT_STREAM_TEMPLATE", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_OUT_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(CMS.getLogMessage("CMSGW_ERROR_DISPLAY_TEMPLATE"));
}
}
@@ -375,58 +370,59 @@ public class DoRevoke extends CMSServlet {
/**
* Process cert status change request
* <P>
- *
- * (Certificate Request - either an "agent" cert status change request,
- * or an "EE" cert status change request)
+ *
+ * (Certificate Request - either an "agent" cert status change request, or
+ * an "EE" cert status change request)
* <P>
- *
- * (Certificate Request Processed - either an "agent" cert status change
- * request, or an "EE" cert status change request)
+ *
+ * (Certificate Request Processed - either an "agent" cert status change
+ * request, or an "EE" cert status change request)
* <P>
- *
+ *
* <ul>
- * <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST used when
- * a cert status change request (e. g. - "revocation") is made (before
+ * <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST used
+ * when a cert status change request (e. g. - "revocation") is made (before
* approval process)
- * <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED
- * used when a certificate status is changed (revoked, expired, on-hold,
- * off-hold)
+ * <li>signed.audit
+ * LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED used when a
+ * certificate status is changed (revoked, expired, on-hold, off-hold)
* </ul>
+ *
* @param argSet CMS template parameters
* @param header argument block
- * @param reason revocation reason (0 - Unspecified, 1 - Key compromised,
- * 2 - CA key compromised; should not be used, 3 - Affiliation changed,
- * 4 - Certificate superceded, 5 - Cessation of operation, or
- * 6 - Certificate is on hold)
+ * @param reason revocation reason (0 - Unspecified, 1 - Key compromised, 2
+ * - CA key compromised; should not be used, 3 - Affiliation
+ * changed, 4 - Certificate superceded, 5 - Cessation of
+ * operation, or 6 - Certificate is on hold)
* @param invalidityDate certificate validity date
* @param initiative string containing the audit format
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @param verifiedRecordCount number of verified records
- * @param revokeAll string containing information on all of the
- * certificates to be revoked
+ * @param revokeAll string containing information on all of the certificates
+ * to be revoked
* @param totalRecordCount total number of records (verified and unverified)
- * @param eeSerialNumber string containing the end-entity certificate
- * serial number
+ * @param eeSerialNumber string containing the end-entity certificate serial
+ * number
* @param eeSubjectDN string containing the end-entity certificate subject
- * distinguished name (DN)
+ * distinguished name (DN)
* @param comments string containing certificate comments
* @param locale the system locale
* @exception EBaseException an error has occurred
*/
private void process(CMSTemplateParams argSet, IArgBlock header,
- int reason, Date invalidityDate,
- String initiative,
- HttpServletRequest req,
- HttpServletResponse resp,
- int verifiedRecordCount,
- String revokeAll,
- int totalRecordCount,
- String eeSerialNumber,
- String eeSubjectDN,
- String comments,
- Locale locale)
- throws EBaseException {
+ int reason, Date invalidityDate,
+ String initiative,
+ HttpServletRequest req,
+ HttpServletResponse resp,
+ int verifiedRecordCount,
+ String revokeAll,
+ int totalRecordCount,
+ String eeSerialNumber,
+ String eeSubjectDN,
+ String comments,
+ Locale locale)
+ throws EBaseException {
boolean auditRequest = true;
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -436,7 +432,7 @@ public class DoRevoke extends CMSServlet {
String auditApprovalStatus = ILogger.SIGNED_AUDIT_EMPTY_VALUE;
String auditReasonNum = String.valueOf(reason);
- CMS.debug("DoRevoke: eeSerialNumber: " + eeSerialNumber + " auditSerialNumber: " + auditSerialNumber);
+ CMS.debug("DoRevoke: eeSerialNumber: " + eeSerialNumber + " auditSerialNumber: " + auditSerialNumber);
long startTime = CMS.getCurrentDate().getTime();
try {
@@ -483,16 +479,16 @@ public class DoRevoke extends CMSServlet {
CMS.debug("DoRevoke: skipped revocation request for system certificate " + xcert.getSerialNumber());
continue;
}
-
+
if (xcert != null) {
rarg.addStringValue("serialNumber",
- xcert.getSerialNumber().toString(16));
+ xcert.getSerialNumber().toString(16));
if (eeSerialNumber != null &&
- (eeSerialNumber.equals(xcert.getSerialNumber().toString())) &&
- rec.getStatus().equals(ICertRecord.STATUS_REVOKED)) {
+ (eeSerialNumber.equals(xcert.getSerialNumber().toString())) &&
+ rec.getStatus().equals(ICertRecord.STATUS_REVOKED)) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CA_CERTIFICATE_ALREADY_REVOKED_1", xcert.getSerialNumber().toString(16)));
+ CMS.getLogMessage("CA_CERTIFICATE_ALREADY_REVOKED_1", xcert.getSerialNumber().toString(16)));
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -508,19 +504,19 @@ public class DoRevoke extends CMSServlet {
throw new ECMSGWException(CMS.getLogMessage("CMSGW_UNAUTHORIZED"));
} else if (rec.getStatus().equals(ICertRecord.STATUS_REVOKED)) {
rarg.addStringValue("error", "Certificate 0x" +
- xcert.getSerialNumber().toString(16) +
- " is already revoked.");
+ xcert.getSerialNumber().toString(16) +
+ " is already revoked.");
} else if (eeSubjectDN != null &&
- (!eeSubjectDN.equals(xcert.getSubjectDN().toString()))) {
+ (!eeSubjectDN.equals(xcert.getSubjectDN().toString()))) {
rarg.addStringValue("error", "Certificate 0x" +
- xcert.getSerialNumber().toString(16) +
- " belongs to different subject.");
+ xcert.getSerialNumber().toString(16) +
+ " belongs to different subject.");
} else {
oldCertsV.addElement(xcert);
RevokedCertImpl revCertImpl =
- new RevokedCertImpl(xcert.getSerialNumber(),
- CMS.getCurrentDate(), entryExtn);
+ new RevokedCertImpl(xcert.getSerialNumber(),
+ CMS.getCurrentDate(), entryExtn);
revCertImplsV.addElement(revCertImpl);
count++;
@@ -535,9 +531,7 @@ public class DoRevoke extends CMSServlet {
Vector<String> serialNumbers = new Vector<String>();
if (revokeAll != null && revokeAll.length() > 0) {
- for (int i = revokeAll.indexOf('=');
- i < revokeAll.length() && i > -1;
- i = revokeAll.indexOf('=', i)) {
+ for (int i = revokeAll.indexOf('='); i < revokeAll.length() && i > -1; i = revokeAll.indexOf('=', i)) {
if (i > -1) {
i++;
while (i < revokeAll.length() && revokeAll.charAt(i) == ' ') {
@@ -564,29 +558,28 @@ public class DoRevoke extends CMSServlet {
for (int i = 0; i < certs.length; i++) {
boolean addToList = false;
- for (int j = 0; j < serialNumbers.size();
- j++) {
- //xxxxx serial number in decimal?
+ for (int j = 0; j < serialNumbers.size(); j++) {
+ // xxxxx serial number in decimal?
if (certs[i].getSerialNumber().toString().equals((String) serialNumbers.elementAt(j)) &&
- eeSubjectDN != null && eeSubjectDN.equals(certs[i].getSubjectDN().toString())) {
+ eeSubjectDN != null && eeSubjectDN.equals(certs[i].getSubjectDN().toString())) {
addToList = true;
break;
}
}
if (eeSerialNumber != null &&
- eeSerialNumber.equals(certs[i].getSerialNumber().toString())) {
+ eeSerialNumber.equals(certs[i].getSerialNumber().toString())) {
authorized = true;
}
if (addToList) {
IArgBlock rarg = CMS.createArgBlock();
rarg.addStringValue("serialNumber",
- certs[i].getSerialNumber().toString(16));
+ certs[i].getSerialNumber().toString(16));
oldCertsV.addElement(certs[i]);
RevokedCertImpl revCertImpl =
- new RevokedCertImpl(certs[i].getSerialNumber(),
- CMS.getCurrentDate(), entryExtn);
+ new RevokedCertImpl(certs[i].getSerialNumber(),
+ CMS.getCurrentDate(), entryExtn);
revCertImplsV.addElement(revCertImpl);
count++;
@@ -596,7 +589,7 @@ public class DoRevoke extends CMSServlet {
}
if (!authorized) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_REQ_AUTH_REVOKED_CERT"));
+ CMS.getLogMessage("CMSGW_REQ_AUTH_REVOKED_CERT"));
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -615,19 +608,19 @@ public class DoRevoke extends CMSServlet {
String b64eCert = req.getParameter("b64eCertificate");
if (b64eCert != null) {
- // BASE64Decoder decoder = new BASE64Decoder();
- // byte[] certBytes = decoder.decodeBuffer(b64eCert);
+ // BASE64Decoder decoder = new BASE64Decoder();
+ // byte[] certBytes = decoder.decodeBuffer(b64eCert);
byte[] certBytes = CMS.AtoB(b64eCert);
X509CertImpl cert = new X509CertImpl(certBytes);
IArgBlock rarg = CMS.createArgBlock();
rarg.addStringValue("serialNumber",
- cert.getSerialNumber().toString(16));
+ cert.getSerialNumber().toString(16));
oldCertsV.addElement(cert);
RevokedCertImpl revCertImpl =
- new RevokedCertImpl(cert.getSerialNumber(),
- CMS.getCurrentDate(), entryExtn);
+ new RevokedCertImpl(cert.getSerialNumber(),
+ CMS.getCurrentDate(), entryExtn);
revCertImplsV.addElement(revCertImpl);
count++;
@@ -636,8 +629,8 @@ public class DoRevoke extends CMSServlet {
}
}
}
- if (count == 0) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_REV_CERTS_ZERO"));
+ if (count == 0) {
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_REV_CERTS_ZERO"));
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -656,7 +649,7 @@ public class DoRevoke extends CMSServlet {
header.addIntegerValue("totalRecordCount", count);
X509CertImpl[] oldCerts = new X509CertImpl[count];
- //Certificate[] oldCerts = new Certificate[count];
+ // Certificate[] oldCerts = new Certificate[count];
RevokedCertImpl[] revCertImpls = new RevokedCertImpl[count];
for (int i = 0; i < count; i++) {
@@ -665,7 +658,7 @@ public class DoRevoke extends CMSServlet {
}
IRequest revReq =
- mQueue.newRequest(IRequest.REVOCATION_REQUEST);
+ mQueue.newRequest(IRequest.REVOCATION_REQUEST);
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -680,7 +673,7 @@ public class DoRevoke extends CMSServlet {
revReq.setExtData(IRequest.CERT_INFO, revCertImpls);
revReq.setExtData(IRequest.REQ_TYPE, IRequest.REVOCATION_REQUEST);
- if(initiative.equals(AuditFormat.FROMUSER))
+ if (initiative.equals(AuditFormat.FROMUSER))
revReq.setExtData(IRequest.REQUESTOR_TYPE, IRequest.REQUESTOR_EE);
else
revReq.setExtData(IRequest.REQUESTOR_TYPE, IRequest.REQUESTOR_AGENT);
@@ -708,37 +701,37 @@ public class DoRevoke extends CMSServlet {
// that is meant for the Master CA. From Clone's point of view
// the request is complete
if ((stat == RequestStatus.COMPLETE) || ((type.equals(IRequest.CLA_CERT4CRL_REQUEST)) && (stat == RequestStatus.SVC_PENDING))) {
- // audit log the error
+ // audit log the error
Integer result = revReq.getExtDataInInteger(IRequest.RESULT);
if (result.equals(IRequest.RES_ERROR)) {
String[] svcErrors =
- revReq.getExtDataInStringArray(IRequest.SVCERRORS);
+ revReq.getExtDataInStringArray(IRequest.SVCERRORS);
if (svcErrors != null && svcErrors.length > 0) {
for (int i = 0; i < svcErrors.length; i++) {
String err = svcErrors[i];
if (err != null) {
- //cmsReq.setErrorDescription(err);
+ // cmsReq.setErrorDescription(err);
for (int j = 0; j < count; j++) {
if (oldCerts[j] instanceof X509CertImpl) {
X509CertImpl cert = (X509CertImpl) oldCerts[j];
if (oldCerts[j] != null) {
mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.DOREVOKEFORMAT,
- new Object[] {
- revReq.getRequestId(),
- initiative,
- "completed with error: " +
- err,
- cert.getSubjectDN(),
- cert.getSerialNumber().toString(16),
- RevocationReason.fromInt(reason).toString()}
- );
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.DOREVOKEFORMAT,
+ new Object[] {
+ revReq.getRequestId(),
+ initiative,
+ "completed with error: " +
+ err,
+ cert.getSubjectDN(),
+ cert.getSerialNumber().toString(16),
+ RevocationReason.fromInt(reason).toString() }
+ );
}
}
}
@@ -751,10 +744,10 @@ public class DoRevoke extends CMSServlet {
// "complete", "revoked", or "canceled"
if ((auditApprovalStatus.equals(
RequestStatus.COMPLETE_STRING)) ||
- (auditApprovalStatus.equals(
- RequestStatus.REJECTED_STRING)) ||
- (auditApprovalStatus.equals(
- RequestStatus.CANCELED_STRING))) {
+ (auditApprovalStatus.equals(
+ RequestStatus.REJECTED_STRING)) ||
+ (auditApprovalStatus.equals(
+ RequestStatus.CANCELED_STRING))) {
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED,
auditSubjectID,
@@ -768,7 +761,7 @@ public class DoRevoke extends CMSServlet {
audit(auditMessage);
}
- return;
+ return;
}
long endTime = CMS.getCurrentDate().getTime();
@@ -780,24 +773,24 @@ public class DoRevoke extends CMSServlet {
X509CertImpl cert = (X509CertImpl) oldCerts[j];
mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.DOREVOKEFORMAT,
- new Object[] {
- revReq.getRequestId(),
- initiative,
- "completed",
- cert.getSubjectDN(),
- cert.getSerialNumber().toString(16),
- RevocationReason.fromInt(reason).toString() + " time: " + (endTime - startTime)}
- );
+ AuditFormat.LEVEL,
+ AuditFormat.DOREVOKEFORMAT,
+ new Object[] {
+ revReq.getRequestId(),
+ initiative,
+ "completed",
+ cert.getSubjectDN(),
+ cert.getSerialNumber().toString(16),
+ RevocationReason.fromInt(reason).toString() + " time: " + (endTime - startTime) }
+ );
}
}
}
header.addStringValue("revoked", "yes");
- Integer updateCRLResult =
- revReq.getExtDataInInteger(IRequest.CRL_UPDATE_STATUS);
+ Integer updateCRLResult =
+ revReq.getExtDataInInteger(IRequest.CRL_UPDATE_STATUS);
if (updateCRLResult != null) {
header.addStringValue("updateCRL", "yes");
@@ -806,15 +799,15 @@ public class DoRevoke extends CMSServlet {
} else {
header.addStringValue("updateCRLSuccess", "no");
String crlError =
- revReq.getExtDataInString(IRequest.CRL_UPDATE_ERROR);
+ revReq.getExtDataInString(IRequest.CRL_UPDATE_ERROR);
- if (crlError != null)
- header.addStringValue("updateCRLError",
- crlError);
+ if (crlError != null)
+ header.addStringValue("updateCRLError",
+ crlError);
}
// let known crl publishing status too.
Integer publishCRLResult =
- revReq.getExtDataInInteger(IRequest.CRL_PUBLISH_STATUS);
+ revReq.getExtDataInInteger(IRequest.CRL_PUBLISH_STATUS);
if (publishCRLResult != null) {
if (publishCRLResult.equals(IRequest.RES_SUCCESS)) {
@@ -822,23 +815,23 @@ public class DoRevoke extends CMSServlet {
} else {
header.addStringValue("publishCRLSuccess", "no");
String publError =
- revReq.getExtDataInString(IRequest.CRL_PUBLISH_ERROR);
+ revReq.getExtDataInString(IRequest.CRL_PUBLISH_ERROR);
- if (publError != null)
- header.addStringValue("publishCRLError",
- publError);
+ if (publError != null)
+ header.addStringValue("publishCRLError",
+ publError);
}
}
}
if (mAuthority instanceof ICertificateAuthority) {
- // let known update and publish status of all crls.
- Enumeration<ICRLIssuingPoint> otherCRLs =
- ((ICertificateAuthority) mAuthority).getCRLIssuingPoints();
+ // let known update and publish status of all crls.
+ Enumeration<ICRLIssuingPoint> otherCRLs =
+ ((ICertificateAuthority) mAuthority).getCRLIssuingPoints();
while (otherCRLs.hasMoreElements()) {
ICRLIssuingPoint crl = (ICRLIssuingPoint)
- otherCRLs.nextElement();
+ otherCRLs.nextElement();
String crlId = crl.getId();
if (crlId.equals(ICertificateAuthority.PROP_MASTER_CRL))
@@ -857,31 +850,31 @@ public class DoRevoke extends CMSServlet {
updateStatusStr));
header.addStringValue(updateStatusStr, "no");
String error =
- revReq.getExtDataInString(updateErrorStr);
+ revReq.getExtDataInString(updateErrorStr);
- if (error != null)
+ if (error != null)
header.addStringValue(updateErrorStr,
- error);
+ error);
}
String publishStatusStr = crl.getCrlPublishStatusStr();
Integer publishResult =
- revReq.getExtDataInInteger(publishStatusStr);
+ revReq.getExtDataInInteger(publishStatusStr);
- if (publishResult == null)
+ if (publishResult == null)
continue;
if (publishResult.equals(IRequest.RES_SUCCESS)) {
header.addStringValue(publishStatusStr, "yes");
} else {
- String publishErrorStr =
- crl.getCrlPublishErrorStr();
+ String publishErrorStr =
+ crl.getCrlPublishErrorStr();
header.addStringValue(publishStatusStr, "no");
String error =
- revReq.getExtDataInString(publishErrorStr);
+ revReq.getExtDataInString(publishErrorStr);
- if (error != null)
+ if (error != null)
header.addStringValue(
- publishErrorStr, error);
+ publishErrorStr, error);
}
}
}
@@ -889,8 +882,8 @@ public class DoRevoke extends CMSServlet {
if (mPublisherProcessor != null && mPublisherProcessor.ldapEnabled()) {
header.addStringValue("dirEnabled", "yes");
- Integer[] ldapPublishStatus =
- revReq.getExtDataInIntegerArray("ldapPublishStatus");
+ Integer[] ldapPublishStatus =
+ revReq.getExtDataInIntegerArray("ldapPublishStatus");
int certsToUpdate = 0;
int certsUpdated = 0;
@@ -905,13 +898,13 @@ public class DoRevoke extends CMSServlet {
header.addIntegerValue("certsUpdated", certsUpdated);
header.addIntegerValue("certsToUpdate", certsToUpdate);
- // add crl publishing status.
+ // add crl publishing status.
String publError =
- revReq.getExtDataInString(IRequest.CRL_PUBLISH_ERROR);
+ revReq.getExtDataInString(IRequest.CRL_PUBLISH_ERROR);
if (publError != null) {
header.addStringValue("crlPublishError",
- publError);
+ publError);
}
} else {
header.addStringValue("dirEnabled", "no");
@@ -946,16 +939,16 @@ public class DoRevoke extends CMSServlet {
X509CertImpl cert = (X509CertImpl) oldCerts[j];
mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.DOREVOKEFORMAT,
- new Object[] {
- revReq.getRequestId(),
- initiative,
- stat.toString(),
- cert.getSubjectDN(),
- cert.getSerialNumber().toString(16),
- RevocationReason.fromInt(reason).toString()}
- );
+ AuditFormat.LEVEL,
+ AuditFormat.DOREVOKEFORMAT,
+ new Object[] {
+ revReq.getRequestId(),
+ initiative,
+ stat.toString(),
+ cert.getSubjectDN(),
+ cert.getSerialNumber().toString(16),
+ RevocationReason.fromInt(reason).toString() }
+ );
}
}
}
@@ -965,9 +958,8 @@ public class DoRevoke extends CMSServlet {
// if and only if "auditApprovalStatus" is
// "complete", "revoked", or "canceled"
if ((auditApprovalStatus.equals(RequestStatus.COMPLETE_STRING))
- || (auditApprovalStatus.equals(RequestStatus.REJECTED_STRING))
- || (auditApprovalStatus.equals(RequestStatus.CANCELED_STRING))
- ) {
+ || (auditApprovalStatus.equals(RequestStatus.REJECTED_STRING))
+ || (auditApprovalStatus.equals(RequestStatus.CANCELED_STRING))) {
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED,
auditSubjectID,
@@ -1001,10 +993,10 @@ public class DoRevoke extends CMSServlet {
// "complete", "revoked", or "canceled"
if ((auditApprovalStatus.equals(
RequestStatus.COMPLETE_STRING)) ||
- (auditApprovalStatus.equals(
- RequestStatus.REJECTED_STRING)) ||
- (auditApprovalStatus.equals(
- RequestStatus.CANCELED_STRING))) {
+ (auditApprovalStatus.equals(
+ RequestStatus.REJECTED_STRING)) ||
+ (auditApprovalStatus.equals(
+ RequestStatus.CANCELED_STRING))) {
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED,
auditSubjectID,
@@ -1042,10 +1034,10 @@ public class DoRevoke extends CMSServlet {
// "complete", "revoked", or "canceled"
if ((auditApprovalStatus.equals(
RequestStatus.COMPLETE_STRING)) ||
- (auditApprovalStatus.equals(
- RequestStatus.REJECTED_STRING)) ||
- (auditApprovalStatus.equals(
- RequestStatus.CANCELED_STRING))) {
+ (auditApprovalStatus.equals(
+ RequestStatus.REJECTED_STRING)) ||
+ (auditApprovalStatus.equals(
+ RequestStatus.CANCELED_STRING))) {
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED,
auditSubjectID,
@@ -1062,8 +1054,8 @@ public class DoRevoke extends CMSServlet {
throw e;
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_MARKING_CERT_REVOKED_1", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERROR_MARKING_CERT_REVOKED_1", e.toString()));
if (auditRequest) {
// store a "CERT_STATUS_CHANGE_REQUEST" failure
@@ -1084,10 +1076,10 @@ public class DoRevoke extends CMSServlet {
// "complete", "revoked", or "canceled"
if ((auditApprovalStatus.equals(
RequestStatus.COMPLETE_STRING)) ||
- (auditApprovalStatus.equals(
- RequestStatus.REJECTED_STRING)) ||
- (auditApprovalStatus.equals(
- RequestStatus.CANCELED_STRING))) {
+ (auditApprovalStatus.equals(
+ RequestStatus.REJECTED_STRING)) ||
+ (auditApprovalStatus.equals(
+ RequestStatus.CANCELED_STRING))) {
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED,
auditSubjectID,
@@ -1110,11 +1102,11 @@ public class DoRevoke extends CMSServlet {
/**
* Signed Audit Log Requester ID
- *
- * This method is called to obtain the "RequesterID" for
- * a signed audit log message.
+ *
+ * This method is called to obtain the "RequesterID" for a signed audit log
+ * message.
* <P>
- *
+ *
* @param req HTTP request
* @return id string containing the signed audit log message RequesterID
*/
@@ -1140,11 +1132,11 @@ public class DoRevoke extends CMSServlet {
/**
* Signed Audit Log Serial Number
- *
+ *
* This method is called to obtain the serial number of the certificate
* whose status is to be changed for a signed audit log message.
* <P>
- *
+ *
* @param eeSerialNumber a string containing the un-normalized serialNumber
* @return id string containing the signed audit log message RequesterID
*/
@@ -1163,30 +1155,30 @@ public class DoRevoke extends CMSServlet {
// find out if the value is hex or decimal
int value = -1;
-
- //try int
- try {
- value = Integer.parseInt(serialNumber,10);
+
+ // try int
+ try {
+ value = Integer.parseInt(serialNumber, 10);
} catch (NumberFormatException e) {
}
-
- //try hex
- if( value == -1) {
+
+ // try hex
+ if (value == -1) {
try {
- value = Integer.parseInt(serialNumber,16);
+ value = Integer.parseInt(serialNumber, 16);
} catch (NumberFormatException e) {
}
}
// give up if it isn't hex or dec
- if ( value == -1) {
+ if (value == -1) {
throw new NumberFormatException();
}
// convert it to hexadecimal
serialNumber = "0x"
+ Integer.toHexString(
- value);
+ value);
} else {
serialNumber = ILogger.SIGNED_AUDIT_EMPTY_VALUE;
}
@@ -1196,11 +1188,11 @@ public class DoRevoke extends CMSServlet {
/**
* Signed Audit Log Request Type
- *
- * This method is called to obtain the "Request Type" for
- * a signed audit log message.
+ *
+ * This method is called to obtain the "Request Type" for a signed audit log
+ * message.
* <P>
- *
+ *
* @param reason an integer denoting the revocation reason
* @return string containing REVOKE or ON_HOLD
*/
@@ -1222,4 +1214,3 @@ public class DoRevoke extends CMSServlet {
return requestType;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/DoRevokeTPS.java b/pki/base/common/src/com/netscape/cms/servlet/cert/DoRevokeTPS.java
index 12093661..e7b83b0c 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/DoRevokeTPS.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/DoRevokeTPS.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
@@ -63,10 +62,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* Revoke a Certificate
- *
+ *
* @version $Revision$, $Date$
*/
public class DoRevokeTPS extends CMSServlet {
@@ -89,20 +87,19 @@ public class DoRevokeTPS extends CMSServlet {
private final static String REVOKE = "revoke";
private final static String ON_HOLD = "on-hold";
private final static int ON_HOLD_REASON = 6;
- private final static String
- LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST =
- "LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_5";
- private final static String
- LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED =
- "LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED_7";
+ private final static String LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST =
+ "LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_5";
+ private final static String LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED =
+ "LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED_7";
public DoRevokeTPS() {
super();
}
/**
- * initialize the servlet. This servlet uses the template
- * file "revocationResult.template" to render the result
+ * initialize the servlet. This servlet uses the template file
+ * "revocationResult.template" to render the result
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -131,16 +128,20 @@ public class DoRevokeTPS extends CMSServlet {
}
/**
- * Serves HTTP request. The http parameters used by this request are as follows:
+ * Serves HTTP request. The http parameters used by this request are as
+ * follows:
+ *
* <pre>
* serialNumber Serial number of certificate to revoke (in HEX)
* revocationReason Revocation reason (Described below)
* totalRecordCount [number]
* verifiedRecordCount [number]
* invalidityDate [number of seconds in Jan 1,1970]
- *
+ *
* </pre>
+ *
* revocationReason can be one of these values:
+ *
* <pre>
* 0 = Unspecified (default)
* 1 = Key compromised
@@ -174,7 +175,7 @@ public class DoRevokeTPS extends CMSServlet {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
throw new ECMSGWException(CMS.getLogMessage("CMSGW_ERROR_DISPLAY_TEMPLATE"));
} catch (Exception e) {
- CMS.debug("DoRevokeTPS getTemplate failed");
+ CMS.debug("DoRevokeTPS getTemplate failed");
throw new EBaseException(CMS.getLogMessage("CMSGW_ERROR_DISPLAY_TEMPLATE"));
}
@@ -203,7 +204,7 @@ public class DoRevokeTPS extends CMSServlet {
revokeAll = req.getParameter("revokeAll");
String comments = req.getParameter(IRequest.REQUESTOR_COMMENTS);
- //for audit log.
+ // for audit log.
String initiative = null;
String authMgr = AuditFormat.NOAUTH;
@@ -215,17 +216,17 @@ public class DoRevokeTPS extends CMSServlet {
mAuthzResourceName, "revoke");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
cmsReq.setStatus(CMSRequest.UNAUTHORIZED);
return;
}
-
+
if (mAuthMgr != null && mAuthMgr.equals(IAuthSubsystem.CERTUSERDB_AUTHMGR_ID)) {
if (authToken != null) {
authMgr = authToken.getInString(AuthToken.TOKEN_AUTHMGR_INST_NAME);
@@ -242,11 +243,11 @@ public class DoRevokeTPS extends CMSServlet {
if (authorized) {
process(argSet, header, reason, invalidityDate, initiative, req,
- resp, revokeAll, totalRecordCount, comments, locale[0]);
+ resp, revokeAll, totalRecordCount, comments, locale[0]);
}
} catch (NumberFormatException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("BASE_INVALID_NUMBER_FORMAT"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("BASE_INVALID_NUMBER_FORMAT"));
error = new EBaseException(CMS.getLogMessage("BASE_INVALID_NUMBER_FORMAT"));
} catch (EBaseException e) {
error = e;
@@ -260,10 +261,10 @@ public class DoRevokeTPS extends CMSServlet {
errorString = "error=unauthorized";
} else if (error != null) {
o_status = "status=3";
- errorString = "error="+error.toString();
+ errorString = "error=" + error.toString();
}
- String pp = o_status+"\n"+errorString;
+ String pp = o_status + "\n" + errorString;
byte[] b = pp.getBytes();
resp.setContentType("text/html");
resp.setContentLength(b.length);
@@ -271,8 +272,8 @@ public class DoRevokeTPS extends CMSServlet {
os.write(b);
os.flush();
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_OUT_STREAM_TEMPLATE", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_OUT_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(CMS.getLogMessage("CMSGW_ERROR_DISPLAY_TEMPLATE"));
}
}
@@ -280,50 +281,51 @@ public class DoRevokeTPS extends CMSServlet {
/**
* Process cert status change request
* <P>
- *
- * (Certificate Request - either an "agent" cert status change request,
- * or an "EE" cert status change request)
+ *
+ * (Certificate Request - either an "agent" cert status change request, or
+ * an "EE" cert status change request)
* <P>
- *
- * (Certificate Request Processed - either an "agent" cert status change
- * request, or an "EE" cert status change request)
+ *
+ * (Certificate Request Processed - either an "agent" cert status change
+ * request, or an "EE" cert status change request)
* <P>
- *
+ *
* <ul>
- * <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST used when
- * a cert status change request (e. g. - "revocation") is made (before
+ * <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST used
+ * when a cert status change request (e. g. - "revocation") is made (before
* approval process)
- * <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED
- * used when a certificate status is changed (revoked, expired, on-hold,
- * off-hold)
+ * <li>signed.audit
+ * LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED used when a
+ * certificate status is changed (revoked, expired, on-hold, off-hold)
* </ul>
+ *
* @param argSet CMS template parameters
* @param header argument block
- * @param reason revocation reason (0 - Unspecified, 1 - Key compromised,
- * 2 - CA key compromised; should not be used, 3 - Affiliation changed,
- * 4 - Certificate superceded, 5 - Cessation of operation, or
- * 6 - Certificate is on hold)
+ * @param reason revocation reason (0 - Unspecified, 1 - Key compromised, 2
+ * - CA key compromised; should not be used, 3 - Affiliation
+ * changed, 4 - Certificate superceded, 5 - Cessation of
+ * operation, or 6 - Certificate is on hold)
* @param invalidityDate certificate validity date
* @param initiative string containing the audit format
* @param req HTTP servlet request
* @param resp HTTP servlet response
- * @param revokeAll string containing information on all of the
- * certificates to be revoked
+ * @param revokeAll string containing information on all of the certificates
+ * to be revoked
* @param totalRecordCount total number of records (verified and unverified)
* @param comments string containing certificate comments
* @param locale the system locale
* @exception EBaseException an error has occurred
*/
private void process(CMSTemplateParams argSet, IArgBlock header,
- int reason, Date invalidityDate,
- String initiative,
- HttpServletRequest req,
- HttpServletResponse resp,
- String revokeAll,
- int totalRecordCount,
- String comments,
- Locale locale)
- throws EBaseException {
+ int reason, Date invalidityDate,
+ String initiative,
+ HttpServletRequest req,
+ HttpServletResponse resp,
+ String revokeAll,
+ int totalRecordCount,
+ String comments,
+ Locale locale)
+ throws EBaseException {
boolean auditRequest = true;
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -333,21 +335,20 @@ public class DoRevokeTPS extends CMSServlet {
String auditApprovalStatus = ILogger.SIGNED_AUDIT_EMPTY_VALUE;
String auditReasonNum = String.valueOf(reason);
-
if (revokeAll != null) {
- CMS.debug("DoRevokeTPS.process revokeAll" + revokeAll);
+ CMS.debug("DoRevokeTPS.process revokeAll" + revokeAll);
- String serial = "";
+ String serial = "";
String[] tokens;
tokens = revokeAll.split("=");
if (tokens.length == 2) {
serial = tokens[1];
- //remove the trailing paren
+ // remove the trailing paren
if (serial.endsWith(")")) {
- serial = serial.substring(0,serial.length() -1);
+ serial = serial.substring(0, serial.length() - 1);
}
- auditSerialNumber = serial;
+ auditSerialNumber = serial;
}
}
@@ -393,7 +394,7 @@ public class DoRevokeTPS extends CMSServlet {
}
X509CertImpl xcert = rec.getCertificate();
IArgBlock rarg = CMS.createArgBlock();
-
+
// we do not want to revoke the CA certificate accidentially
if (xcert != null && isSystemCertificate(xcert.getSerialNumber())) {
CMS.debug("DoRevokeTPS: skipped revocation request for system certificate " + xcert.getSerialNumber());
@@ -403,20 +404,20 @@ public class DoRevokeTPS extends CMSServlet {
if (xcert != null) {
rarg.addStringValue("serialNumber",
- xcert.getSerialNumber().toString(16));
+ xcert.getSerialNumber().toString(16));
if (rec.getStatus().equals(ICertRecord.STATUS_REVOKED)) {
alreadyRevokedCertFound = true;
- CMS.debug("Certificate 0x"+xcert.getSerialNumber().toString(16) + " has been revoked.");
+ CMS.debug("Certificate 0x" + xcert.getSerialNumber().toString(16) + " has been revoked.");
} else {
oldCertsV.addElement(xcert);
RevokedCertImpl revCertImpl =
- new RevokedCertImpl(xcert.getSerialNumber(),
- CMS.getCurrentDate(), entryExtn);
+ new RevokedCertImpl(xcert.getSerialNumber(),
+ CMS.getCurrentDate(), entryExtn);
revCertImplsV.addElement(revCertImpl);
- CMS.debug("Certificate 0x"+xcert.getSerialNumber().toString(16)+" is going to be revoked.");
+ CMS.debug("Certificate 0x" + xcert.getSerialNumber().toString(16) + " is going to be revoked.");
count++;
}
} else {
@@ -424,27 +425,27 @@ public class DoRevokeTPS extends CMSServlet {
}
}
- if (count == 0) {
+ if (count == 0) {
// Situation where no certs were reoked here, but some certs
// requested happened to be already revoked. Don't return error.
if (alreadyRevokedCertFound == true && badCertsRequested == false) {
- CMS.debug("Only have previously revoked certs in the list.");
- // store a message in the signed audit log file
- auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST,
- auditSubjectID,
- ILogger.SUCCESS,
- auditRequesterID,
- auditSerialNumber,
- auditRequestType);
+ CMS.debug("Only have previously revoked certs in the list.");
+ // store a message in the signed audit log file
+ auditMessage = CMS.getLogMessage(
+ LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST,
+ auditSubjectID,
+ ILogger.SUCCESS,
+ auditRequesterID,
+ auditSerialNumber,
+ auditRequestType);
- audit(auditMessage);
- return;
+ audit(auditMessage);
+ return;
}
-
+
errorString = "error=No certificates are revoked.";
o_status = "status=2";
- log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_REV_CERTS_ZERO"));
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_REV_CERTS_ZERO"));
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -469,7 +470,7 @@ public class DoRevokeTPS extends CMSServlet {
}
IRequest revReq =
- mQueue.newRequest(IRequest.REVOCATION_REQUEST);
+ mQueue.newRequest(IRequest.REVOCATION_REQUEST);
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -484,7 +485,7 @@ public class DoRevokeTPS extends CMSServlet {
revReq.setExtData(IRequest.CERT_INFO, revCertImpls);
revReq.setExtData(IRequest.REQ_TYPE, IRequest.REVOCATION_REQUEST);
- if(initiative.equals(AuditFormat.FROMUSER)) {
+ if (initiative.equals(AuditFormat.FROMUSER)) {
revReq.setExtData(IRequest.REQUESTOR_TYPE, IRequest.REQUESTOR_EE);
} else {
revReq.setExtData(IRequest.REQUESTOR_TYPE, IRequest.REQUESTOR_AGENT);
@@ -513,37 +514,37 @@ public class DoRevokeTPS extends CMSServlet {
// that is meant for the Master CA. From Clone's point of view
// the request is complete
if ((stat == RequestStatus.COMPLETE) || ((type.equals(IRequest.CLA_CERT4CRL_REQUEST)) && (stat == RequestStatus.SVC_PENDING))) {
- // audit log the error
+ // audit log the error
Integer result = revReq.getExtDataInInteger(IRequest.RESULT);
if (result.equals(IRequest.RES_ERROR)) {
String[] svcErrors =
- revReq.getExtDataInStringArray(IRequest.SVCERRORS);
+ revReq.getExtDataInStringArray(IRequest.SVCERRORS);
if (svcErrors != null && svcErrors.length > 0) {
for (int i = 0; i < svcErrors.length; i++) {
String err = svcErrors[i];
if (err != null) {
- //cmsReq.setErrorDescription(err);
+ // cmsReq.setErrorDescription(err);
for (int j = 0; j < count; j++) {
if (oldCerts[j] instanceof X509CertImpl) {
X509CertImpl cert = (X509CertImpl) oldCerts[j];
if (oldCerts[j] != null) {
mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.DOREVOKEFORMAT,
- new Object[] {
- revReq.getRequestId(),
- initiative,
- "completed with error: " +
- err,
- cert.getSubjectDN(),
- cert.getSerialNumber().toString(16),
- RevocationReason.fromInt(reason).toString()}
- );
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.DOREVOKEFORMAT,
+ new Object[] {
+ revReq.getRequestId(),
+ initiative,
+ "completed with error: " +
+ err,
+ cert.getSubjectDN(),
+ cert.getSerialNumber().toString(16),
+ RevocationReason.fromInt(reason).toString() }
+ );
}
}
}
@@ -556,10 +557,10 @@ public class DoRevokeTPS extends CMSServlet {
// "complete", "revoked", or "canceled"
if ((auditApprovalStatus.equals(
RequestStatus.COMPLETE_STRING)) ||
- (auditApprovalStatus.equals(
- RequestStatus.REJECTED_STRING)) ||
- (auditApprovalStatus.equals(
- RequestStatus.CANCELED_STRING))) {
+ (auditApprovalStatus.equals(
+ RequestStatus.REJECTED_STRING)) ||
+ (auditApprovalStatus.equals(
+ RequestStatus.CANCELED_STRING))) {
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED,
auditSubjectID,
@@ -573,7 +574,7 @@ public class DoRevokeTPS extends CMSServlet {
audit(auditMessage);
}
- return;
+ return;
}
long endTime = CMS.getCurrentDate().getTime();
@@ -585,24 +586,24 @@ public class DoRevokeTPS extends CMSServlet {
X509CertImpl cert = (X509CertImpl) oldCerts[j];
mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.DOREVOKEFORMAT,
- new Object[] {
- revReq.getRequestId(),
- initiative,
- "completed",
- cert.getSubjectDN(),
- cert.getSerialNumber().toString(16),
- RevocationReason.fromInt(reason).toString() + " time: " + (endTime - startTime)}
- );
+ AuditFormat.LEVEL,
+ AuditFormat.DOREVOKEFORMAT,
+ new Object[] {
+ revReq.getRequestId(),
+ initiative,
+ "completed",
+ cert.getSubjectDN(),
+ cert.getSerialNumber().toString(16),
+ RevocationReason.fromInt(reason).toString() + " time: " + (endTime - startTime) }
+ );
}
}
}
header.addStringValue("revoked", "yes");
- Integer updateCRLResult =
- revReq.getExtDataInInteger(IRequest.CRL_UPDATE_STATUS);
+ Integer updateCRLResult =
+ revReq.getExtDataInInteger(IRequest.CRL_UPDATE_STATUS);
if (updateCRLResult != null) {
if (!updateCRLResult.equals(IRequest.RES_SUCCESS)) {
@@ -615,29 +616,29 @@ public class DoRevokeTPS extends CMSServlet {
}
// let known crl publishing status too.
Integer publishCRLResult =
- revReq.getExtDataInInteger(IRequest.CRL_PUBLISH_STATUS);
+ revReq.getExtDataInInteger(IRequest.CRL_PUBLISH_STATUS);
if (publishCRLResult != null) {
if (!publishCRLResult.equals(IRequest.RES_SUCCESS)) {
String publError =
- revReq.getExtDataInString(IRequest.CRL_PUBLISH_ERROR);
+ revReq.getExtDataInString(IRequest.CRL_PUBLISH_ERROR);
o_status = "status=3";
if (publError != null) {
- errorString = "error="+publError;
+ errorString = "error=" + publError;
}
}
}
}
if (mAuthority instanceof ICertificateAuthority) {
- // let known update and publish status of all crls.
- Enumeration<ICRLIssuingPoint> otherCRLs =
- ((ICertificateAuthority) mAuthority).getCRLIssuingPoints();
+ // let known update and publish status of all crls.
+ Enumeration<ICRLIssuingPoint> otherCRLs =
+ ((ICertificateAuthority) mAuthority).getCRLIssuingPoints();
while (otherCRLs.hasMoreElements()) {
ICRLIssuingPoint crl = (ICRLIssuingPoint)
- otherCRLs.nextElement();
+ otherCRLs.nextElement();
String crlId = crl.getId();
if (crlId.equals(ICertificateAuthority.PROP_MASTER_CRL))
@@ -652,25 +653,25 @@ public class DoRevokeTPS extends CMSServlet {
CMS.debug("DoRevoke: " + CMS.getLogMessage("ADMIN_SRVLT_ADDING_HEADER_NO",
updateStatusStr));
String error =
- revReq.getExtDataInString(updateErrorStr);
+ revReq.getExtDataInString(updateErrorStr);
o_status = "status=3";
- if (error != null) {
- errorString = "error="+error;
+ if (error != null) {
+ errorString = "error=" + error;
}
}
String publishStatusStr = crl.getCrlPublishStatusStr();
Integer publishResult =
- revReq.getExtDataInInteger(publishStatusStr);
+ revReq.getExtDataInInteger(publishStatusStr);
- if (publishResult == null)
+ if (publishResult == null)
continue;
if (!publishResult.equals(IRequest.RES_SUCCESS)) {
- String publishErrorStr =
- crl.getCrlPublishErrorStr();
+ String publishErrorStr =
+ crl.getCrlPublishErrorStr();
String error =
- revReq.getExtDataInString(publishErrorStr);
+ revReq.getExtDataInString(publishErrorStr);
o_status = "status=3";
if (error != null) {
@@ -683,8 +684,8 @@ public class DoRevokeTPS extends CMSServlet {
if (mPublisherProcessor != null && mPublisherProcessor.ldapEnabled()) {
header.addStringValue("dirEnabled", "yes");
- Integer[] ldapPublishStatus =
- revReq.getExtDataInIntegerArray("ldapPublishStatus");
+ Integer[] ldapPublishStatus =
+ revReq.getExtDataInIntegerArray("ldapPublishStatus");
int certsToUpdate = 0;
int certsUpdated = 0;
@@ -697,12 +698,12 @@ public class DoRevokeTPS extends CMSServlet {
}
}
- // add crl publishing status.
+ // add crl publishing status.
String publError =
- revReq.getExtDataInString(IRequest.CRL_PUBLISH_ERROR);
+ revReq.getExtDataInString(IRequest.CRL_PUBLISH_ERROR);
if (publError != null) {
- errorString = "error="+publError;
+ errorString = "error=" + publError;
o_status = "status=3";
}
} else if (mPublisherProcessor == null && mPublisherProcessor.ldapEnabled()) {
@@ -712,7 +713,7 @@ public class DoRevokeTPS extends CMSServlet {
} else {
if (stat == RequestStatus.PENDING || stat == RequestStatus.REJECTED) {
o_status = "status=2";
- errorString = "error="+stat.toString();
+ errorString = "error=" + stat.toString();
} else {
o_status = "status=2";
errorString = "error=Undefined request status";
@@ -743,16 +744,16 @@ public class DoRevokeTPS extends CMSServlet {
X509CertImpl cert = (X509CertImpl) oldCerts[j];
mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.DOREVOKEFORMAT,
- new Object[] {
- revReq.getRequestId(),
- initiative,
- stat.toString(),
- cert.getSubjectDN(),
- cert.getSerialNumber().toString(16),
- RevocationReason.fromInt(reason).toString()}
- );
+ AuditFormat.LEVEL,
+ AuditFormat.DOREVOKEFORMAT,
+ new Object[] {
+ revReq.getRequestId(),
+ initiative,
+ stat.toString(),
+ cert.getSubjectDN(),
+ cert.getSerialNumber().toString(16),
+ RevocationReason.fromInt(reason).toString() }
+ );
}
}
}
@@ -762,9 +763,8 @@ public class DoRevokeTPS extends CMSServlet {
// if and only if "auditApprovalStatus" is
// "complete", "revoked", or "canceled"
if ((auditApprovalStatus.equals(RequestStatus.COMPLETE_STRING))
- || (auditApprovalStatus.equals(RequestStatus.REJECTED_STRING))
- || (auditApprovalStatus.equals(RequestStatus.CANCELED_STRING))
- ) {
+ || (auditApprovalStatus.equals(RequestStatus.REJECTED_STRING))
+ || (auditApprovalStatus.equals(RequestStatus.CANCELED_STRING))) {
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED,
auditSubjectID,
@@ -799,10 +799,10 @@ public class DoRevokeTPS extends CMSServlet {
// "complete", "revoked", or "canceled"
if ((auditApprovalStatus.equals(
RequestStatus.COMPLETE_STRING)) ||
- (auditApprovalStatus.equals(
- RequestStatus.REJECTED_STRING)) ||
- (auditApprovalStatus.equals(
- RequestStatus.CANCELED_STRING))) {
+ (auditApprovalStatus.equals(
+ RequestStatus.REJECTED_STRING)) ||
+ (auditApprovalStatus.equals(
+ RequestStatus.CANCELED_STRING))) {
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED,
auditSubjectID,
@@ -819,8 +819,8 @@ public class DoRevokeTPS extends CMSServlet {
throw e;
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_MARKING_CERT_REVOKED_1", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERROR_MARKING_CERT_REVOKED_1", e.toString()));
if (auditRequest) {
// store a "CERT_STATUS_CHANGE_REQUEST" failure
@@ -841,10 +841,10 @@ public class DoRevokeTPS extends CMSServlet {
// "complete", "revoked", or "canceled"
if ((auditApprovalStatus.equals(
RequestStatus.COMPLETE_STRING)) ||
- (auditApprovalStatus.equals(
- RequestStatus.REJECTED_STRING)) ||
- (auditApprovalStatus.equals(
- RequestStatus.CANCELED_STRING))) {
+ (auditApprovalStatus.equals(
+ RequestStatus.REJECTED_STRING)) ||
+ (auditApprovalStatus.equals(
+ RequestStatus.CANCELED_STRING))) {
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED,
auditSubjectID,
@@ -867,11 +867,11 @@ public class DoRevokeTPS extends CMSServlet {
/**
* Signed Audit Log Requester ID
- *
- * This method is called to obtain the "RequesterID" for
- * a signed audit log message.
+ *
+ * This method is called to obtain the "RequesterID" for a signed audit log
+ * message.
* <P>
- *
+ *
* @param req HTTP request
* @return id string containing the signed audit log message RequesterID
*/
@@ -897,11 +897,11 @@ public class DoRevokeTPS extends CMSServlet {
/**
* Signed Audit Log Serial Number
- *
+ *
* This method is called to obtain the serial number of the certificate
* whose status is to be changed for a signed audit log message.
* <P>
- *
+ *
* @param eeSerialNumber a string containing the un-normalized serialNumber
* @return id string containing the signed audit log message RequesterID
*/
@@ -920,7 +920,7 @@ public class DoRevokeTPS extends CMSServlet {
// convert it to hexadecimal
serialNumber = "0x"
+ Integer.toHexString(
- Integer.valueOf(serialNumber).intValue());
+ Integer.valueOf(serialNumber).intValue());
} else {
serialNumber = ILogger.SIGNED_AUDIT_EMPTY_VALUE;
}
@@ -930,11 +930,11 @@ public class DoRevokeTPS extends CMSServlet {
/**
* Signed Audit Log Request Type
- *
- * This method is called to obtain the "Request Type" for
- * a signed audit log message.
+ *
+ * This method is called to obtain the "Request Type" for a signed audit log
+ * message.
* <P>
- *
+ *
* @param reason an integer denoting the revocation reason
* @return string containing REVOKE or ON_HOLD
*/
@@ -956,4 +956,3 @@ public class DoRevokeTPS extends CMSServlet {
return requestType;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/DoUnrevoke.java b/pki/base/common/src/com/netscape/cms/servlet/cert/DoUnrevoke.java
index e1791045..0b7c6f85 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/DoUnrevoke.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/DoUnrevoke.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.io.IOException;
import java.math.BigInteger;
import java.util.Enumeration;
@@ -56,11 +55,10 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
- * 'Unrevoke' a certificate. (For certificates that are on-hold only,
- * take them off-hold)
- *
+ * 'Unrevoke' a certificate. (For certificates that are on-hold only, take them
+ * off-hold)
+ *
* @version $Revision$, $Date$
*/
public class DoUnrevoke extends CMSServlet {
@@ -80,19 +78,18 @@ public class DoUnrevoke extends CMSServlet {
private final static String OFF_HOLD = "off-hold";
private final static int OFF_HOLD_REASON = 6;
- private final static String
- LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST =
- "LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_5";
- private final static String
- LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED =
- "LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED_7";
-
+ private final static String LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST =
+ "LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_5";
+ private final static String LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED =
+ "LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED_7";
+
public DoUnrevoke() {
super();
}
/**
* initialize the servlet.
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -112,14 +109,14 @@ public class DoUnrevoke extends CMSServlet {
}
/**
- * Process the HTTP request.
+ * Process the HTTP request.
* <ul>
- * <li>http.param serialNumber Decimal serial number of certificate to unrevoke. The
- * certificate must be revoked with a revovcation reason 'on hold' for this
- * operation to succeed. The serial number may be expressed as a hex number by
- * prefixing '0x' to the serialNumber string
+ * <li>http.param serialNumber Decimal serial number of certificate to
+ * unrevoke. The certificate must be revoked with a revovcation reason 'on
+ * hold' for this operation to succeed. The serial number may be expressed
+ * as a hex number by prefixing '0x' to the serialNumber string
* </ul>
- *
+ *
* @param cmsReq the object holding the request and response information
*/
public void process(CMSRequest cmsReq) throws EBaseException {
@@ -136,10 +133,10 @@ public class DoUnrevoke extends CMSServlet {
try {
form = getTemplate(mFormPath, req, locale);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
IArgBlock header = CMS.createArgBlock();
@@ -149,20 +146,20 @@ public class DoUnrevoke extends CMSServlet {
try {
serialNumber = getSerialNumbers(req);
- //for audit log.
+ // for audit log.
IAuthToken authToken = authenticate(cmsReq);
String authMgr = AuditFormat.NOAUTH;
-
+
if (authToken != null) {
authMgr =
authToken.getInString(AuthToken.TOKEN_AUTHMGR_INST_NAME);
- } else {
- CMS.debug( "DoUnrevoke::process() - authToken is null!" );
+ } else {
+ CMS.debug("DoUnrevoke::process() - authToken is null!");
return;
}
String agentID = authToken.getInString("userid");
String initiative = AuditFormat.FROMAGENT + " agentID: " + agentID
- + " authenticated by " + authMgr;
+ + " authenticated by " + authMgr;
AuthzToken authzToken = null;
@@ -171,10 +168,10 @@ public class DoUnrevoke extends CMSServlet {
mAuthzResourceName, "unrevoke");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -186,7 +183,7 @@ public class DoUnrevoke extends CMSServlet {
} catch (NumberFormatException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_INVALID_SERIAL_NUM_FORMAT"));
- error = new EBaseException(CMS.getUserMessage(getLocale(req),"CMS_BASE_INVALID_NUMBER_FORMAT"));
+ error = new EBaseException(CMS.getUserMessage(getLocale(req), "CMS_BASE_INVALID_NUMBER_FORMAT"));
} catch (EBaseException e) {
error = e;
}
@@ -197,44 +194,45 @@ public class DoUnrevoke extends CMSServlet {
if (error == null) {
String xmlOutput = req.getParameter("xml");
if (xmlOutput != null && xmlOutput.equals("true")) {
- outputXML(resp, argSet);
+ outputXML(resp, argSet);
} else {
- resp.setContentType("text/html");
- form.renderOutput(out, argSet);
- cmsReq.setStatus(CMSRequest.SUCCESS);
+ resp.setContentType("text/html");
+ form.renderOutput(out, argSet);
+ cmsReq.setStatus(CMSRequest.SUCCESS);
}
} else {
cmsReq.setStatus(CMSRequest.ERROR);
cmsReq.setError(error);
}
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_ERR_STREAM_TEMPLATE", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_ERR_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
}
-
/**
* Process X509 cert status change request
* <P>
- *
- * (Certificate Request - an "agent" cert status change request to take
- * a certificate off-hold)
+ *
+ * (Certificate Request - an "agent" cert status change request to take a
+ * certificate off-hold)
* <P>
- *
- * (Certificate Request Processed - an "agent" cert status change request
- * to take a certificate off-hold)
+ *
+ * (Certificate Request Processed - an "agent" cert status change request to
+ * take a certificate off-hold)
* <P>
- *
+ *
* <ul>
- * <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST used when
- * a cert status change request (e. g. - "revocation") is made (before
+ * <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST used
+ * when a cert status change request (e. g. - "revocation") is made (before
* approval process)
- * <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED
- * used when a certificate status is changed (taken off-hold)
+ * <li>signed.audit
+ * LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED used when a
+ * certificate status is changed (taken off-hold)
* </ul>
+ *
* @param argSet CMS template parameters
* @param header argument block
* @param serialNumbers the serial number of the certificate
@@ -245,11 +243,11 @@ public class DoUnrevoke extends CMSServlet {
* @exception EBaseException an error has occurred
*/
private void process(CMSTemplateParams argSet, IArgBlock header,
- BigInteger[] serialNumbers,
- HttpServletRequest req,
- HttpServletResponse resp,
- Locale locale, String initiative)
- throws EBaseException {
+ BigInteger[] serialNumbers,
+ HttpServletRequest req,
+ HttpServletResponse resp,
+ Locale locale, String initiative)
+ throws EBaseException {
boolean auditRequest = true;
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -262,11 +260,13 @@ public class DoUnrevoke extends CMSServlet {
try {
StringBuffer snList = new StringBuffer();
- // certs are for old cloning and they should be removed as soon as possible
+ // certs are for old cloning and they should be removed as soon as
+ // possible
X509CertImpl[] certs = new X509CertImpl[serialNumbers.length];
for (int i = 0; i < serialNumbers.length; i++) {
- certs[i] = (X509CertImpl)getX509Certificate(serialNumbers[i]);
- if (snList.length() > 0) snList.append(", ");
+ certs[i] = (X509CertImpl) getX509Certificate(serialNumbers[i]);
+ if (snList.length() > 0)
+ snList.append(", ");
snList.append("0x");
snList.append(serialNumbers[i].toString(16));
}
@@ -310,15 +310,15 @@ public class DoUnrevoke extends CMSServlet {
header.addStringValue("unrevoked", "yes");
if (certs[0] != null) {
mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.DOUNREVOKEFORMAT,
- new Object[] {
- unrevReq.getRequestId(),
- initiative,
- "completed",
- certs[0].getSubjectDN(),
- "0x" + serialNumbers[0].toString(16)}
- );
+ AuditFormat.LEVEL,
+ AuditFormat.DOUNREVOKEFORMAT,
+ new Object[] {
+ unrevReq.getRequestId(),
+ initiative,
+ "completed",
+ certs[0].getSubjectDN(),
+ "0x" + serialNumbers[0].toString(16) }
+ );
}
} else {
header.addStringValue("unrevoked", "no");
@@ -328,59 +328,59 @@ public class DoUnrevoke extends CMSServlet {
header.addStringValue("error", error);
if (certs[0] != null) {
mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.DOUNREVOKEFORMAT,
- new Object[] {
- unrevReq.getRequestId(),
- initiative,
- "completed with error: " +
- error,
- certs[0].getSubjectDN(),
- "0x" + serialNumbers[0].toString(16)}
- );
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.DOUNREVOKEFORMAT,
+ new Object[] {
+ unrevReq.getRequestId(),
+ initiative,
+ "completed with error: " +
+ error,
+ certs[0].getSubjectDN(),
+ "0x" + serialNumbers[0].toString(16) }
+ );
}
/****************************************************/
-
- /* IMPORTANT: In the event that the following */
-
- /* "throw error;" statement is */
-
- /* uncommented, uncomment the following */
-
- /* signed audit log message, also!!! */
-
+
+ /* IMPORTANT: In the event that the following */
+
+ /* "throw error;" statement is */
+
+ /* uncommented, uncomment the following */
+
+ /* signed audit log message, also!!! */
+
/****************************************************/
- // // store a message in the signed audit log file
- // // if and only if "auditApprovalStatus" is
- // // "complete", "revoked", or "canceled"
- // if( ( auditApprovalStatus.equals(
- // RequestStatus.COMPLETE_STRING ) ) ||
- // ( auditApprovalStatus.equals(
- // RequestStatus.REJECTED_STRING ) ) ||
- // ( auditApprovalStatus.equals(
- // RequestStatus.CANCELED_STRING ) ) ) {
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditRequesterID,
- // auditSerialNumber,
- // auditRequestType,
- // auditReasonNum,
- // auditApprovalStatus );
+ // // store a message in the signed audit log file
+ // // if and only if "auditApprovalStatus" is
+ // // "complete", "revoked", or "canceled"
+ // if( ( auditApprovalStatus.equals(
+ // RequestStatus.COMPLETE_STRING ) ) ||
+ // ( auditApprovalStatus.equals(
+ // RequestStatus.REJECTED_STRING ) ) ||
+ // ( auditApprovalStatus.equals(
+ // RequestStatus.CANCELED_STRING ) ) ) {
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditRequesterID,
+ // auditSerialNumber,
+ // auditRequestType,
+ // auditReasonNum,
+ // auditApprovalStatus );
//
- // audit( auditMessage );
- // }
+ // audit( auditMessage );
+ // }
- // throw error;
+ // throw error;
}
}
- Integer updateCRLResult =
- unrevReq.getExtDataInInteger(IRequest.CRL_UPDATE_STATUS);
+ Integer updateCRLResult =
+ unrevReq.getExtDataInInteger(IRequest.CRL_UPDATE_STATUS);
if (updateCRLResult != null) {
header.addStringValue("updateCRL", "yes");
@@ -389,15 +389,15 @@ public class DoUnrevoke extends CMSServlet {
} else {
header.addStringValue("updateCRLSuccess", "no");
String crlError =
- unrevReq.getExtDataInString(IRequest.CRL_UPDATE_ERROR);
+ unrevReq.getExtDataInString(IRequest.CRL_UPDATE_ERROR);
- if (crlError != null)
- header.addStringValue("updateCRLError",
- crlError);
+ if (crlError != null)
+ header.addStringValue("updateCRLError",
+ crlError);
}
// let known crl publishing status too.
- Integer publishCRLResult =
- unrevReq.getExtDataInInteger(IRequest.CRL_PUBLISH_STATUS);
+ Integer publishCRLResult =
+ unrevReq.getExtDataInInteger(IRequest.CRL_PUBLISH_STATUS);
if (publishCRLResult != null) {
if (publishCRLResult.equals(IRequest.RES_SUCCESS)) {
@@ -405,22 +405,22 @@ public class DoUnrevoke extends CMSServlet {
} else {
header.addStringValue("publishCRLSuccess", "no");
String publError =
- unrevReq.getExtDataInString(IRequest.CRL_PUBLISH_ERROR);
+ unrevReq.getExtDataInString(IRequest.CRL_PUBLISH_ERROR);
- if (publError != null)
- header.addStringValue("publishCRLError",
- publError);
+ if (publError != null)
+ header.addStringValue("publishCRLError",
+ publError);
}
}
}
- // let known update and publish status of all crls.
- Enumeration otherCRLs =
- ((ICertificateAuthority) mAuthority).getCRLIssuingPoints();
+ // let known update and publish status of all crls.
+ Enumeration otherCRLs =
+ ((ICertificateAuthority) mAuthority).getCRLIssuingPoints();
while (otherCRLs.hasMoreElements()) {
ICRLIssuingPoint crl = (ICRLIssuingPoint)
- otherCRLs.nextElement();
+ otherCRLs.nextElement();
String crlId = crl.getId();
if (crlId.equals(ICertificateAuthority.PROP_MASTER_CRL))
@@ -431,48 +431,48 @@ public class DoUnrevoke extends CMSServlet {
if (updateResult != null) {
if (updateResult.equals(IRequest.RES_SUCCESS)) {
CMS.debug("DoUnrevoke: adding header " +
- updateStatusStr + " yes ");
+ updateStatusStr + " yes ");
header.addStringValue(updateStatusStr, "yes");
} else {
String updateErrorStr = crl.getCrlUpdateErrorStr();
CMS.debug("DoUnrevoke: adding header " +
- updateStatusStr + " no ");
+ updateStatusStr + " no ");
header.addStringValue(updateStatusStr, "no");
String error =
- unrevReq.getExtDataInString(updateErrorStr);
+ unrevReq.getExtDataInString(updateErrorStr);
- if (error != null)
+ if (error != null)
header.addStringValue(
- updateErrorStr, error);
+ updateErrorStr, error);
}
String publishStatusStr = crl.getCrlPublishStatusStr();
Integer publishResult =
- unrevReq.getExtDataInInteger(publishStatusStr);
+ unrevReq.getExtDataInInteger(publishStatusStr);
- if (publishResult == null)
+ if (publishResult == null)
continue;
if (publishResult.equals(IRequest.RES_SUCCESS)) {
header.addStringValue(publishStatusStr, "yes");
} else {
- String publishErrorStr =
- crl.getCrlPublishErrorStr();
+ String publishErrorStr =
+ crl.getCrlPublishErrorStr();
header.addStringValue(publishStatusStr, "no");
String error =
- unrevReq.getExtDataInString(publishErrorStr);
+ unrevReq.getExtDataInString(publishErrorStr);
- if (error != null)
+ if (error != null)
header.addStringValue(
- publishErrorStr, error);
+ publishErrorStr, error);
}
}
}
if (mPublisherProcessor != null && mPublisherProcessor.ldapEnabled()) {
header.addStringValue("dirEnabled", "yes");
- Integer[] ldapPublishStatus =
- unrevReq.getExtDataInIntegerArray("ldapPublishStatus");
+ Integer[] ldapPublishStatus =
+ unrevReq.getExtDataInIntegerArray("ldapPublishStatus");
if (ldapPublishStatus != null) {
if (ldapPublishStatus[0] == IRequest.RES_SUCCESS) {
@@ -490,30 +490,30 @@ public class DoUnrevoke extends CMSServlet {
header.addStringValue("unrevoked", "pending");
if (certs[0] != null) {
mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.DOUNREVOKEFORMAT,
- new Object[] {
- unrevReq.getRequestId(),
- initiative,
- "pending",
- certs[0].getSubjectDN(),
- "0x" + serialNumbers[0].toString(16)}
- );
+ AuditFormat.LEVEL,
+ AuditFormat.DOUNREVOKEFORMAT,
+ new Object[] {
+ unrevReq.getRequestId(),
+ initiative,
+ "pending",
+ certs[0].getSubjectDN(),
+ "0x" + serialNumbers[0].toString(16) }
+ );
}
} else {
header.addStringValue("error", "Request Status.Error");
header.addStringValue("unrevoked", "no");
if (certs[0] != null) {
mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.DOUNREVOKEFORMAT,
- new Object[] {
- unrevReq.getRequestId(),
- initiative,
- status.toString(),
- certs[0].getSubjectDN(),
- "0x" + serialNumbers[0].toString(16)}
- );
+ AuditFormat.LEVEL,
+ AuditFormat.DOUNREVOKEFORMAT,
+ new Object[] {
+ unrevReq.getRequestId(),
+ initiative,
+ status.toString(),
+ certs[0].getSubjectDN(),
+ "0x" + serialNumbers[0].toString(16) }
+ );
}
}
@@ -521,9 +521,8 @@ public class DoUnrevoke extends CMSServlet {
// if and only if "auditApprovalStatus" is
// "complete", "revoked", or "canceled"
if ((auditApprovalStatus.equals(RequestStatus.COMPLETE_STRING))
- || (auditApprovalStatus.equals(RequestStatus.REJECTED_STRING))
- || (auditApprovalStatus.equals(RequestStatus.CANCELED_STRING))
- ) {
+ || (auditApprovalStatus.equals(RequestStatus.REJECTED_STRING))
+ || (auditApprovalStatus.equals(RequestStatus.CANCELED_STRING))) {
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED,
auditSubjectID,
@@ -557,10 +556,10 @@ public class DoUnrevoke extends CMSServlet {
// "complete", "revoked", or "canceled"
if ((auditApprovalStatus.equals(
RequestStatus.COMPLETE_STRING)) ||
- (auditApprovalStatus.equals(
- RequestStatus.REJECTED_STRING)) ||
- (auditApprovalStatus.equals(
- RequestStatus.CANCELED_STRING))) {
+ (auditApprovalStatus.equals(
+ RequestStatus.REJECTED_STRING)) ||
+ (auditApprovalStatus.equals(
+ RequestStatus.CANCELED_STRING))) {
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED,
auditSubjectID,
@@ -580,7 +579,7 @@ public class DoUnrevoke extends CMSServlet {
}
private BigInteger[] getSerialNumbers(HttpServletRequest req)
- throws NumberFormatException {
+ throws NumberFormatException {
String serialNumString = req.getParameter("serialNumber");
StringTokenizer snList = new StringTokenizer(serialNumString, " ");
@@ -601,7 +600,7 @@ public class DoUnrevoke extends CMSServlet {
biList.addElement(bi);
} else {
throw new NumberFormatException();
- }
+ }
}
if (biList.size() < 1) {
throw new NumberFormatException();
@@ -617,11 +616,11 @@ public class DoUnrevoke extends CMSServlet {
/**
* Signed Audit Log Requester ID
- *
- * This method is called to obtain the "RequesterID" for
- * a signed audit log message.
+ *
+ * This method is called to obtain the "RequesterID" for a signed audit log
+ * message.
* <P>
- *
+ *
* @param req HTTP request
* @return id string containing the signed audit log message RequesterID
*/
@@ -647,11 +646,11 @@ public class DoUnrevoke extends CMSServlet {
/**
* Signed Audit Log Serial Number
- *
+ *
* This method is called to obtain the serial number of the certificate
* whose status is to be changed for a signed audit log message.
* <P>
- *
+ *
* @param eeSerialNumber a string containing the un-normalized serialNumber
* @return id string containing the signed audit log message RequesterID
*/
@@ -670,7 +669,7 @@ public class DoUnrevoke extends CMSServlet {
// convert it to hexadecimal
serialNumber = "0x"
+ Integer.toHexString(
- Integer.valueOf(serialNumber).intValue());
+ Integer.valueOf(serialNumber).intValue());
} else {
serialNumber = ILogger.SIGNED_AUDIT_EMPTY_VALUE;
}
@@ -678,4 +677,3 @@ public class DoUnrevoke extends CMSServlet {
return serialNumber;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/DoUnrevokeTPS.java b/pki/base/common/src/com/netscape/cms/servlet/cert/DoUnrevokeTPS.java
index 8f46ee9c..4472d0e5 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/DoUnrevokeTPS.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/DoUnrevokeTPS.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
@@ -55,11 +54,10 @@ import com.netscape.cms.servlet.common.CMSRequest;
import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
- * 'Unrevoke' a certificate. (For certificates that are on-hold only,
- * take them off-hold)
- *
+ * 'Unrevoke' a certificate. (For certificates that are on-hold only, take them
+ * off-hold)
+ *
* @version $Revision$, $Date$
*/
public class DoUnrevokeTPS extends CMSServlet {
@@ -81,19 +79,18 @@ public class DoUnrevokeTPS extends CMSServlet {
private final static String OFF_HOLD = "off-hold";
private final static int OFF_HOLD_REASON = 6;
- private final static String
- LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST =
- "LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_5";
- private final static String
- LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED =
- "LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED_7";
-
+ private final static String LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST =
+ "LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_5";
+ private final static String LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED =
+ "LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED_7";
+
public DoUnrevokeTPS() {
super();
}
/**
* initialize the servlet.
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -112,14 +109,14 @@ public class DoUnrevokeTPS extends CMSServlet {
}
/**
- * Process the HTTP request.
+ * Process the HTTP request.
* <ul>
- * <li>http.param serialNumber Decimal serial number of certificate to unrevoke. The
- * certificate must be revoked with a revovcation reason 'on hold' for this
- * operation to succeed. The serial number may be expressed as a hex number by
- * prefixing '0x' to the serialNumber string
+ * <li>http.param serialNumber Decimal serial number of certificate to
+ * unrevoke. The certificate must be revoked with a revovcation reason 'on
+ * hold' for this operation to succeed. The serial number may be expressed
+ * as a hex number by prefixing '0x' to the serialNumber string
* </ul>
- *
+ *
* @param cmsReq the object holding the request and response information
*/
public void process(CMSRequest cmsReq) throws EBaseException {
@@ -133,34 +130,31 @@ public class DoUnrevokeTPS extends CMSServlet {
Locale[] locale = new Locale[1];
-/*
- try {
- form = getTemplate(mFormPath, req, locale);
- } catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", e.toString()));
- throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
- }
-*/
+ /*
+ * try { form = getTemplate(mFormPath, req, locale); } catch
+ * (IOException e) { log(ILogger.LL_FAILURE,
+ * CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", e.toString())); throw new
+ * ECMSGWException(
+ * CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")); }
+ */
try {
serialNumbers = getSerialNumbers(req);
- //for audit log.
+ // for audit log.
IAuthToken authToken = authenticate(cmsReq);
String authMgr = AuditFormat.NOAUTH;
-
+
if (authToken != null) {
authMgr =
authToken.getInString(AuthToken.TOKEN_AUTHMGR_INST_NAME);
- } else {
- CMS.debug( "DoUnrevokeTPS::process() - authToken is null!" );
+ } else {
+ CMS.debug("DoUnrevokeTPS::process() - authToken is null!");
return;
- }
+ }
String agentID = authToken.getInString("userid");
String initiative = AuditFormat.FROMAGENT + " agentID: " + agentID
- + " authenticated by " + authMgr;
+ + " authenticated by " + authMgr;
AuthzToken authzToken = null;
@@ -169,17 +163,17 @@ public class DoUnrevokeTPS extends CMSServlet {
mAuthzResourceName, "unrevoke");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
cmsReq.setStatus(CMSRequest.UNAUTHORIZED);
o_status = "status=3";
errorString = "error=unauthorized";
- String pp = o_status+"\n"+errorString;
+ String pp = o_status + "\n" + errorString;
byte[] b = pp.getBytes();
resp.setContentType("text/html");
resp.setContentLength(b.length);
@@ -192,7 +186,7 @@ public class DoUnrevokeTPS extends CMSServlet {
process(serialNumbers, req, resp, locale[0], initiative);
} catch (NumberFormatException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_INVALID_SERIAL_NUM_FORMAT"));
- error = new EBaseException(CMS.getUserMessage(getLocale(req),"CMS_BASE_INVALID_NUMBER_FORMAT"));
+ error = new EBaseException(CMS.getUserMessage(getLocale(req), "CMS_BASE_INVALID_NUMBER_FORMAT"));
} catch (EBaseException e) {
error = e;
} catch (IOException e) {
@@ -206,10 +200,10 @@ public class DoUnrevokeTPS extends CMSServlet {
errorString = "error=";
} else {
o_status = "status=3";
- errorString = "error="+error.toString();
+ errorString = "error=" + error.toString();
}
- String pp = o_status+"\n"+errorString;
+ String pp = o_status + "\n" + errorString;
byte[] b = pp.getBytes();
resp.setContentType("text/html");
resp.setContentLength(b.length);
@@ -217,33 +211,34 @@ public class DoUnrevokeTPS extends CMSServlet {
os.write(b);
os.flush();
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_ERR_STREAM_TEMPLATE", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_ERR_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
}
-
/**
* Process X509 cert status change request
* <P>
- *
- * (Certificate Request - an "agent" cert status change request to take
- * a certificate off-hold)
+ *
+ * (Certificate Request - an "agent" cert status change request to take a
+ * certificate off-hold)
* <P>
- *
- * (Certificate Request Processed - an "agent" cert status change request
- * to take a certificate off-hold)
+ *
+ * (Certificate Request Processed - an "agent" cert status change request to
+ * take a certificate off-hold)
* <P>
- *
+ *
* <ul>
- * <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST used when
- * a cert status change request (e. g. - "revocation") is made (before
+ * <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST used
+ * when a cert status change request (e. g. - "revocation") is made (before
* approval process)
- * <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED
- * used when a certificate status is changed (taken off-hold)
+ * <li>signed.audit
+ * LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED used when a
+ * certificate status is changed (taken off-hold)
* </ul>
+ *
* @param serialNumbers the serial number of the certificate
* @param req HTTP servlet request
* @param resp HTTP servlet response
@@ -252,10 +247,10 @@ public class DoUnrevokeTPS extends CMSServlet {
* @exception EBaseException an error has occurred
*/
private void process(BigInteger[] serialNumbers,
- HttpServletRequest req,
- HttpServletResponse resp,
- Locale locale, String initiative)
- throws EBaseException {
+ HttpServletRequest req,
+ HttpServletResponse resp,
+ Locale locale, String initiative)
+ throws EBaseException {
boolean auditRequest = true;
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -268,11 +263,13 @@ public class DoUnrevokeTPS extends CMSServlet {
try {
String snList = "";
- // certs are for old cloning and they should be removed as soon as possible
+ // certs are for old cloning and they should be removed as soon as
+ // possible
X509CertImpl[] certs = new X509CertImpl[serialNumbers.length];
for (int i = 0; i < serialNumbers.length; i++) {
- certs[i] = (X509CertImpl)getX509Certificate(serialNumbers[i]);
- if (snList.length() > 0) snList += ", ";
+ certs[i] = (X509CertImpl) getX509Certificate(serialNumbers[i]);
+ if (snList.length() > 0)
+ snList += ", ";
snList += "0x" + serialNumbers[i].toString(16);
}
@@ -313,76 +310,76 @@ public class DoUnrevokeTPS extends CMSServlet {
if (result != null && result.equals(IRequest.RES_SUCCESS)) {
if (certs[0] != null) {
mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.DOUNREVOKEFORMAT,
- new Object[] {
- unrevReq.getRequestId(),
- initiative,
- "completed",
- certs[0].getSubjectDN(),
- "0x" + serialNumbers[0].toString(16)}
- );
+ AuditFormat.LEVEL,
+ AuditFormat.DOUNREVOKEFORMAT,
+ new Object[] {
+ unrevReq.getRequestId(),
+ initiative,
+ "completed",
+ certs[0].getSubjectDN(),
+ "0x" + serialNumbers[0].toString(16) }
+ );
}
} else {
String error = unrevReq.getExtDataInString(IRequest.ERROR);
if (error != null) {
o_status = "status=3";
- errorString = "error="+error;
+ errorString = "error=" + error;
if (certs[0] != null) {
mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.DOUNREVOKEFORMAT,
- new Object[] {
- unrevReq.getRequestId(),
- initiative,
- "completed with error: " +
- error,
- certs[0].getSubjectDN(),
- "0x" + serialNumbers[0].toString(16)}
- );
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.DOUNREVOKEFORMAT,
+ new Object[] {
+ unrevReq.getRequestId(),
+ initiative,
+ "completed with error: " +
+ error,
+ certs[0].getSubjectDN(),
+ "0x" + serialNumbers[0].toString(16) }
+ );
}
}
}
- Integer updateCRLResult =
- unrevReq.getExtDataInInteger(IRequest.CRL_UPDATE_STATUS);
+ Integer updateCRLResult =
+ unrevReq.getExtDataInInteger(IRequest.CRL_UPDATE_STATUS);
if (updateCRLResult != null) {
if (!updateCRLResult.equals(IRequest.RES_SUCCESS)) {
String crlError =
- unrevReq.getExtDataInString(IRequest.CRL_UPDATE_ERROR);
+ unrevReq.getExtDataInString(IRequest.CRL_UPDATE_ERROR);
if (crlError != null) {
o_status = "status=3";
- errorString = "error="+crlError;
+ errorString = "error=" + crlError;
}
}
// let known crl publishing status too.
- Integer publishCRLResult =
- unrevReq.getExtDataInInteger(IRequest.CRL_PUBLISH_STATUS);
+ Integer publishCRLResult =
+ unrevReq.getExtDataInInteger(IRequest.CRL_PUBLISH_STATUS);
if (publishCRLResult != null) {
if (!publishCRLResult.equals(IRequest.RES_SUCCESS)) {
String publError =
- unrevReq.getExtDataInString(IRequest.CRL_PUBLISH_ERROR);
+ unrevReq.getExtDataInString(IRequest.CRL_PUBLISH_ERROR);
if (publError != null) {
o_status = "status=3";
- errorString = "error="+publError;
+ errorString = "error=" + publError;
}
}
}
}
- // let known update and publish status of all crls.
- Enumeration otherCRLs =
- ((ICertificateAuthority) mAuthority).getCRLIssuingPoints();
+ // let known update and publish status of all crls.
+ Enumeration otherCRLs =
+ ((ICertificateAuthority) mAuthority).getCRLIssuingPoints();
while (otherCRLs.hasMoreElements()) {
ICRLIssuingPoint crl = (ICRLIssuingPoint)
- otherCRLs.nextElement();
+ otherCRLs.nextElement();
String crlId = crl.getId();
if (crlId.equals(ICertificateAuthority.PROP_MASTER_CRL))
@@ -394,37 +391,37 @@ public class DoUnrevokeTPS extends CMSServlet {
if (!updateResult.equals(IRequest.RES_SUCCESS)) {
String updateErrorStr = crl.getCrlUpdateErrorStr();
String error =
- unrevReq.getExtDataInString(updateErrorStr);
+ unrevReq.getExtDataInString(updateErrorStr);
if (error != null) {
o_status = "status=3";
- errorString = "error="+error;
+ errorString = "error=" + error;
}
}
String publishStatusStr = crl.getCrlPublishStatusStr();
Integer publishResult =
- unrevReq.getExtDataInInteger(publishStatusStr);
+ unrevReq.getExtDataInInteger(publishStatusStr);
- if (publishResult == null)
+ if (publishResult == null)
continue;
if (!publishResult.equals(IRequest.RES_SUCCESS)) {
- String publishErrorStr =
- crl.getCrlPublishErrorStr();
+ String publishErrorStr =
+ crl.getCrlPublishErrorStr();
String error =
- unrevReq.getExtDataInString(publishErrorStr);
+ unrevReq.getExtDataInString(publishErrorStr);
if (error != null) {
o_status = "status=3";
- errorString = "error="+error;
+ errorString = "error=" + error;
}
}
}
}
if (mPublisherProcessor != null && mPublisherProcessor.ldapEnabled()) {
- Integer[] ldapPublishStatus =
- unrevReq.getExtDataInIntegerArray("ldapPublishStatus");
+ Integer[] ldapPublishStatus =
+ unrevReq.getExtDataInIntegerArray("ldapPublishStatus");
if (ldapPublishStatus != null) {
if (ldapPublishStatus[0] != IRequest.RES_SUCCESS) {
@@ -432,25 +429,25 @@ public class DoUnrevokeTPS extends CMSServlet {
errorString = "error=Problem in publishing to LDAP";
}
}
- } else if (mPublisherProcessor == null || (! mPublisherProcessor.ldapEnabled())) {
+ } else if (mPublisherProcessor == null || (!mPublisherProcessor.ldapEnabled())) {
o_status = "status=3";
errorString = "error=LDAP Publisher not enabled";
}
} else if (status == RequestStatus.PENDING) {
o_status = "status=2";
- errorString = "error="+status.toString();
+ errorString = "error=" + status.toString();
if (certs[0] != null) {
mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.DOUNREVOKEFORMAT,
- new Object[] {
- unrevReq.getRequestId(),
- initiative,
- "pending",
- certs[0].getSubjectDN(),
- "0x" + serialNumbers[0].toString(16)}
- );
+ AuditFormat.LEVEL,
+ AuditFormat.DOUNREVOKEFORMAT,
+ new Object[] {
+ unrevReq.getRequestId(),
+ initiative,
+ "pending",
+ certs[0].getSubjectDN(),
+ "0x" + serialNumbers[0].toString(16) }
+ );
}
} else {
o_status = "status=2";
@@ -458,15 +455,15 @@ public class DoUnrevokeTPS extends CMSServlet {
if (certs[0] != null) {
mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.DOUNREVOKEFORMAT,
- new Object[] {
- unrevReq.getRequestId(),
- initiative,
- status.toString(),
- certs[0].getSubjectDN(),
- "0x" + serialNumbers[0].toString(16)}
- );
+ AuditFormat.LEVEL,
+ AuditFormat.DOUNREVOKEFORMAT,
+ new Object[] {
+ unrevReq.getRequestId(),
+ initiative,
+ status.toString(),
+ certs[0].getSubjectDN(),
+ "0x" + serialNumbers[0].toString(16) }
+ );
}
}
@@ -474,9 +471,8 @@ public class DoUnrevokeTPS extends CMSServlet {
// if and only if "auditApprovalStatus" is
// "complete", "revoked", or "canceled"
if ((auditApprovalStatus.equals(RequestStatus.COMPLETE_STRING))
- || (auditApprovalStatus.equals(RequestStatus.REJECTED_STRING))
- || (auditApprovalStatus.equals(RequestStatus.CANCELED_STRING))
- ) {
+ || (auditApprovalStatus.equals(RequestStatus.REJECTED_STRING))
+ || (auditApprovalStatus.equals(RequestStatus.CANCELED_STRING))) {
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED,
auditSubjectID,
@@ -510,10 +506,10 @@ public class DoUnrevokeTPS extends CMSServlet {
// "complete", "revoked", or "canceled"
if ((auditApprovalStatus.equals(
RequestStatus.COMPLETE_STRING)) ||
- (auditApprovalStatus.equals(
- RequestStatus.REJECTED_STRING)) ||
- (auditApprovalStatus.equals(
- RequestStatus.CANCELED_STRING))) {
+ (auditApprovalStatus.equals(
+ RequestStatus.REJECTED_STRING)) ||
+ (auditApprovalStatus.equals(
+ RequestStatus.CANCELED_STRING))) {
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED,
auditSubjectID,
@@ -533,7 +529,7 @@ public class DoUnrevokeTPS extends CMSServlet {
}
private BigInteger[] getSerialNumbers(HttpServletRequest req)
- throws NumberFormatException {
+ throws NumberFormatException {
String serialNumString = req.getParameter("serialNumber");
StringTokenizer snList = new StringTokenizer(serialNumString, " ");
@@ -554,7 +550,7 @@ public class DoUnrevokeTPS extends CMSServlet {
biList.addElement(bi);
} else {
throw new NumberFormatException();
- }
+ }
}
if (biList.size() < 1) {
throw new NumberFormatException();
@@ -570,11 +566,11 @@ public class DoUnrevokeTPS extends CMSServlet {
/**
* Signed Audit Log Requester ID
- *
- * This method is called to obtain the "RequesterID" for
- * a signed audit log message.
+ *
+ * This method is called to obtain the "RequesterID" for a signed audit log
+ * message.
* <P>
- *
+ *
* @param req HTTP request
* @return id string containing the signed audit log message RequesterID
*/
@@ -600,11 +596,11 @@ public class DoUnrevokeTPS extends CMSServlet {
/**
* Signed Audit Log Serial Number
- *
+ *
* This method is called to obtain the serial number of the certificate
* whose status is to be changed for a signed audit log message.
* <P>
- *
+ *
* @param eeSerialNumber a string containing the un-normalized serialNumber
* @return id string containing the signed audit log message RequesterID
*/
@@ -623,7 +619,7 @@ public class DoUnrevokeTPS extends CMSServlet {
// convert it to hexadecimal
serialNumber = "0x"
+ Integer.toHexString(
- Integer.valueOf(serialNumber).intValue());
+ Integer.valueOf(serialNumber).intValue());
} else {
serialNumber = ILogger.SIGNED_AUDIT_EMPTY_VALUE;
}
@@ -631,4 +627,3 @@ public class DoUnrevokeTPS extends CMSServlet {
return serialNumber;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/EnableEnrollResult.java b/pki/base/common/src/com/netscape/cms/servlet/cert/EnableEnrollResult.java
index b1d89426..2a143b66 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/EnableEnrollResult.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/EnableEnrollResult.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.io.IOException;
import java.security.cert.X509Certificate;
import java.util.Locale;
@@ -46,10 +45,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* For Face-to-face enrollment, enable EE enrollment feature
- *
+ *
* @version $Revision$, $Date$
* @see com.netscape.cms.servlet.cert.DisableEnrollResult
*/
@@ -88,7 +86,7 @@ public class EnableEnrollResult extends CMSServlet {
* Services the request
*/
protected void process(CMSRequest cmsReq)
- throws EBaseException {
+ throws EBaseException {
HttpServletRequest httpReq = cmsReq.getHttpReq();
HttpServletResponse httpResp = cmsReq.getHttpResp();
@@ -119,7 +117,7 @@ public class EnableEnrollResult extends CMSServlet {
if (!(mAuthority instanceof IRegistrationAuthority)) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_CA_FROM_RA_NOT_IMP"));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_NOT_YET_IMPLEMENTED")));
+ CMS.getUserMessage("CMS_GW_NOT_YET_IMPLEMENTED")));
cmsReq.setStatus(CMSRequest.ERROR);
return;
}
@@ -130,10 +128,10 @@ public class EnableEnrollResult extends CMSServlet {
try {
form = getTemplate(mFormPath, httpReq, locale);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
cmsReq.setStatus(CMSRequest.ERROR);
return;
}
@@ -162,7 +160,7 @@ public class EnableEnrollResult extends CMSServlet {
String timeout = args.getValueAsString("timeout", "600");
mgr.createEntry(host, dn, Long.parseLong(timeout) * 1000,
- random.nextLong() + "", 0);
+ random.nextLong() + "", 0);
header.addStringValue("code", "0");
}
@@ -173,10 +171,10 @@ public class EnableEnrollResult extends CMSServlet {
form.renderOutput(out, argSet);
cmsReq.setStatus(CMSRequest.SUCCESS);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
cmsReq.setStatus(CMSRequest.ERROR);
}
cmsReq.setStatus(CMSRequest.SUCCESS);
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/EnrollServlet.java b/pki/base/common/src/com/netscape/cms/servlet/cert/EnrollServlet.java
index 44d0c509..ecad6d8a 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/EnrollServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/EnrollServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.io.IOException;
import java.math.BigInteger;
import java.security.cert.CertificateEncodingException;
@@ -75,10 +74,9 @@ import com.netscape.cms.servlet.processors.KeyGenProcessor;
import com.netscape.cms.servlet.processors.PKCS10Processor;
import com.netscape.cms.servlet.processors.PKIProcessor;
-
/**
* Submit a Certificate Enrollment request
- *
+ *
* @version $Revision$, $Date$
*/
public class EnrollServlet extends CMSServlet {
@@ -90,10 +88,9 @@ public class EnrollServlet extends CMSServlet {
public final static String ADMIN_ENROLL_SERVLET_ID = "caadminEnroll";
// enrollment templates.
- public static final String
- ENROLL_SUCCESS_TEMPLATE = "EnrollSuccess.template";
+ public static final String ENROLL_SUCCESS_TEMPLATE = "EnrollSuccess.template";
- // http params
+ // http params
public static final String OLD_CERT_TYPE = "csrCertType";
public static final String CERT_TYPE = "certType";
// same as in ConfigConstant.java
@@ -116,8 +113,7 @@ public class EnrollServlet extends CMSServlet {
private boolean mAuthTokenOverride = true;
private String mEnrollSuccessTemplate = null;
- private ICMSTemplateFiller
- mEnrollSuccessFiller = new ImportCertsTemplateFiller();
+ private ICMSTemplateFiller mEnrollSuccessFiller = new ImportCertsTemplateFiller();
ICertificateAuthority mCa = null;
ICertificateRepository mRepository = null;
@@ -126,55 +122,55 @@ public class EnrollServlet extends CMSServlet {
private String auditServiceID = ILogger.UNIDENTIFIED;
private final static String ADMIN_CA_ENROLLMENT_SERVLET =
- "caadminEnroll";
+ "caadminEnroll";
private final static String AGENT_CA_BULK_ENROLLMENT_SERVLET =
- "cabulkissuance";
+ "cabulkissuance";
private final static String AGENT_RA_BULK_ENROLLMENT_SERVLET =
- "rabulkissuance";
+ "rabulkissuance";
private final static String EE_CA_CERT_BASED_ENROLLMENT_SERVLET =
- "cacertbasedenrollment";
+ "cacertbasedenrollment";
private final static String EE_CA_ENROLLMENT_SERVLET =
- "caenrollment";
+ "caenrollment";
private final static String EE_RA_CERT_BASED_ENROLLMENT_SERVLET =
- "racertbasedenrollment";
+ "racertbasedenrollment";
private final static String EE_RA_ENROLLMENT_SERVLET =
- "raenrollment";
+ "raenrollment";
private final static byte EOL[] = { Character.LINE_SEPARATOR };
- private final static String[]
- SIGNED_AUDIT_AUTOMATED_REJECTION_REASON = new String[] {
-
- /* 0 */ "automated non-profile cert request rejection: "
+ private final static String[] SIGNED_AUDIT_AUTOMATED_REJECTION_REASON = new String[] {
+
+ /* 0 */"automated non-profile cert request rejection: "
+ "unable to render OLD_CERT_TYPE response",
-
- /* 1 */ "automated non-profile cert request rejection: "
+
+ /* 1 */"automated non-profile cert request rejection: "
+ "unable to complete handleEnrollAuditLog() method",
-
- /* 2 */ "automated non-profile cert request rejection: "
+
+ /* 2 */"automated non-profile cert request rejection: "
+ "unable to render success template",
-
- /* 3 */ "automated non-profile cert request rejection: "
+
+ /* 3 */"automated non-profile cert request rejection: "
+ "indeterminate reason for inability to process "
+ "cert request due to an EBaseException"
};
- private final static String
- LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST =
- "LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST_5";
- private final static String
- LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED =
- "LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED_5";
-
+ private final static String LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST =
+ "LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST_5";
+ private final static String LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED =
+ "LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED_5";
+
private static final String HEADER = "-----BEGIN NEW CERTIFICATE REQUEST-----";
private static final String TRAILER = "-----END NEW CERTIFICATE REQUEST-----";
-
+
public EnrollServlet() {
super();
}
/**
- * initialize the servlet.<p>
- * the following parameters are read from the servlet config:
- * <ul><li>CMSServlet.PROP_ID - ID for signed audit log messages
- * <li>CMSServlet.PROP_SUCCESS_TEMPLATE - success template file
+ * initialize the servlet.
+ * <p>
+ * the following parameters are read from the servlet config:
+ * <ul>
+ * <li>CMSServlet.PROP_ID - ID for signed audit log messages
+ * <li>CMSServlet.PROP_SUCCESS_TEMPLATE - success template file
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -185,8 +181,8 @@ public class EnrollServlet extends CMSServlet {
try {
IConfigStore configStore = CMS.getConfigStore();
- String PKI_Subsystem = configStore.getString( "subsystem.0.id",
- null );
+ String PKI_Subsystem = configStore.getString("subsystem.0.id",
+ null);
// CMS 6.1 began utilizing the "Certificate Profiles" framework
// instead of the legacy "Certificate Policies" framework.
@@ -197,51 +193,51 @@ public class EnrollServlet extends CMSServlet {
// framework would be deprecated and disabled by default
// (see Bugzilla Bug #472597).
//
- // NOTE: The "Certificate Policies" framework ONLY applied to
- // to CA, KRA, and legacy RA (pre-CMS 7.0) subsystems.
+ // NOTE: The "Certificate Policies" framework ONLY applied to
+ // to CA, KRA, and legacy RA (pre-CMS 7.0) subsystems.
//
- // Further, the "EnrollServlet.java" servlet is ONLY
- // used by the CA for the following:
+ // Further, the "EnrollServlet.java" servlet is ONLY
+ // used by the CA for the following:
//
- // SERVLET-NAME URL-PATTERN
- // ====================================================
- // caadminEnroll ca/admin/ca/adminEnroll.html
- // cabulkissuance ca/agent/ca/bulkissuance.html
- // cacertbasedenrollment ca/certbasedenrollment.html
- // caenrollment ca/enrollment.html
+ // SERVLET-NAME URL-PATTERN
+ // ====================================================
+ // caadminEnroll ca/admin/ca/adminEnroll.html
+ // cabulkissuance ca/agent/ca/bulkissuance.html
+ // cacertbasedenrollment ca/certbasedenrollment.html
+ // caenrollment ca/enrollment.html
//
- // The "EnrollServlet.java" servlet is NOT used by
- // the KRA.
+ // The "EnrollServlet.java" servlet is NOT used by
+ // the KRA.
//
- if( PKI_Subsystem.trim().equalsIgnoreCase( "ca" ) ) {
+ if (PKI_Subsystem.trim().equalsIgnoreCase("ca")) {
String policyStatus = PKI_Subsystem.trim().toLowerCase()
+ "." + "Policy"
+ "." + IPolicyProcessor.PROP_ENABLE;
- if( configStore.getBoolean( policyStatus, true ) == true ) {
- // NOTE: If "<subsystem>.Policy.enable=<boolean>"
- // is missing, then the referenced instance
- // existed prior to this name=value pair
- // existing in its 'CS.cfg' file, and thus
- // we err on the side that the user may
- // still need to use the policy framework.
- CMS.debug( "EnrollServlet::init Certificate "
+ if (configStore.getBoolean(policyStatus, true) == true) {
+ // NOTE: If "<subsystem>.Policy.enable=<boolean>"
+ // is missing, then the referenced instance
+ // existed prior to this name=value pair
+ // existing in its 'CS.cfg' file, and thus
+ // we err on the side that the user may
+ // still need to use the policy framework.
+ CMS.debug("EnrollServlet::init Certificate "
+ "Policy Framework (deprecated) "
- + "is ENABLED" );
+ + "is ENABLED");
} else {
- // CS 8.1 Default: <subsystem>.Policy.enable=false
- CMS.debug( "EnrollServlet::init Certificate "
+ // CS 8.1 Default: <subsystem>.Policy.enable=false
+ CMS.debug("EnrollServlet::init Certificate "
+ "Policy Framework (deprecated) "
- + "is DISABLED" );
+ + "is DISABLED");
return;
}
}
- } catch( EBaseException e ) {
- throw new ServletException( "EnrollServlet::init - "
+ } catch (EBaseException e) {
+ throw new ServletException("EnrollServlet::init - "
+ "EBaseException: "
+ "Unable to initialize "
+ "Certificate Policy Framework "
- + "(deprecated)" );
+ + "(deprecated)");
}
// override success template to allow direct import of keygen certs.
@@ -254,18 +250,18 @@ public class EnrollServlet extends CMSServlet {
if (id != null) {
if (!(auditServiceID.equals(
ADMIN_CA_ENROLLMENT_SERVLET))
- && !(auditServiceID.equals(
- AGENT_CA_BULK_ENROLLMENT_SERVLET))
- && !(auditServiceID.equals(
- AGENT_RA_BULK_ENROLLMENT_SERVLET))
- && !(auditServiceID.equals(
- EE_CA_CERT_BASED_ENROLLMENT_SERVLET))
- && !(auditServiceID.equals(
- EE_CA_ENROLLMENT_SERVLET))
- && !(auditServiceID.equals(
- EE_RA_CERT_BASED_ENROLLMENT_SERVLET))
- && !(auditServiceID.equals(
- EE_RA_ENROLLMENT_SERVLET))) {
+ && !(auditServiceID.equals(
+ AGENT_CA_BULK_ENROLLMENT_SERVLET))
+ && !(auditServiceID.equals(
+ AGENT_RA_BULK_ENROLLMENT_SERVLET))
+ && !(auditServiceID.equals(
+ EE_CA_CERT_BASED_ENROLLMENT_SERVLET))
+ && !(auditServiceID.equals(
+ EE_CA_ENROLLMENT_SERVLET))
+ && !(auditServiceID.equals(
+ EE_RA_CERT_BASED_ENROLLMENT_SERVLET))
+ && !(auditServiceID.equals(
+ EE_RA_ENROLLMENT_SERVLET))) {
auditServiceID = ILogger.UNIDENTIFIED;
} else {
auditServiceID = id.trim();
@@ -282,7 +278,7 @@ public class EnrollServlet extends CMSServlet {
if (fillername != null) {
ICMSTemplateFiller filler = newFillerObject(fillername);
- if (filler != null)
+ if (filler != null)
mEnrollSuccessFiller = filler;
}
@@ -291,10 +287,10 @@ public class EnrollServlet extends CMSServlet {
init_testbed_hack(mConfig);
} catch (Exception e) {
- // this should never happen.
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_IMP_INIT_SERV_ERR",
- e.toString(), mId));
+ // this should never happen.
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_IMP_INIT_SERV_ERR",
+ e.toString(), mId));
}
} catch (ServletException eAudit1) {
// rethrow caught exception
@@ -302,64 +298,61 @@ public class EnrollServlet extends CMSServlet {
}
}
-
- /**
- * XXX (SHOULD CHANGE TO READ FROM Servletconfig)
- * Getter method to see if Proof of Posession checking is enabled.
- * this value is set in the CMS.cfg filem with the parameter
- * "enrollment.enforcePop". It defaults to false
- * @return true if user is required to Prove that they possess the
- * private key corresponding to the public key in the certificate
- * request they are submitting
- */
+ /**
+ * XXX (SHOULD CHANGE TO READ FROM Servletconfig) Getter method to see if
+ * Proof of Posession checking is enabled. this value is set in the CMS.cfg
+ * filem with the parameter "enrollment.enforcePop". It defaults to false
+ *
+ * @return true if user is required to Prove that they possess the private
+ * key corresponding to the public key in the certificate request
+ * they are submitting
+ */
public boolean getEnforcePop() {
return enforcePop;
}
/**
- * Process the HTTP request.
- * <UL><LI>If the request is coming through the admin port, it is only
- * allowed to continue if 'admin enrollment' is enabled in the CMS.cfg file
- * <LI>If the CMS.cfg parameter useThreadNaming is true, the current thread is
- * renamed with more information about the current request ID
- * <LI>The request is preprocessed, then processed further in one
- * of the cert request processor classes: KeyGenProcessor, PKCS10Processor,
- * CMCProcessor, CRMFProcessor
- * </UL>
- *
+ * Process the HTTP request.
+ * <UL>
+ * <LI>If the request is coming through the admin port, it is only allowed
+ * to continue if 'admin enrollment' is enabled in the CMS.cfg file
+ * <LI>If the CMS.cfg parameter useThreadNaming is true, the current thread
+ * is renamed with more information about the current request ID
+ * <LI>The request is preprocessed, then processed further in one of the
+ * cert request processor classes: KeyGenProcessor, PKCS10Processor,
+ * CMCProcessor, CRMFProcessor
+ * </UL>
+ *
* @param cmsReq the object holding the request and response information
*/
- protected void process(CMSRequest cmsReq)
- throws EBaseException {
+ protected void process(CMSRequest cmsReq)
+ throws EBaseException {
// SPECIAL CASE:
// if it is adminEnroll servlet,check if it's enabled
if (mId.equals(ADMIN_ENROLL_SERVLET_ID) &&
- !CMSGateway.getEnableAdminEnroll()) {
- log(ILogger.LL_SECURITY,
- CMS.getLogMessage("ADMIN_SRVLT_ENROLL_ACCESS_AFTER_SETUP"));
+ !CMSGateway.getEnableAdminEnroll()) {
+ log(ILogger.LL_SECURITY,
+ CMS.getLogMessage("ADMIN_SRVLT_ENROLL_ACCESS_AFTER_SETUP"));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_REDIRECTING_ADMINENROLL_ERROR", "Attempt to access adminEnroll after already setup."));
+ CMS.getUserMessage("CMS_GW_REDIRECTING_ADMINENROLL_ERROR", "Attempt to access adminEnroll after already setup."));
}
- processX509(cmsReq);
+ processX509(cmsReq);
}
private boolean getCertAuthEnrollStatus(IArgBlock httpParams) {
/*
- * === certAuth based enroll ===
- * "certAuthEnroll" is on.
- * "certauthEnrollType can be one of the three:
- * single - it's for single cert enrollment
- * dual - it's for dual certs enrollment
- * encryption - getting the encryption cert only via
- * authentication of the signing cert
- * (crmf or keyGenInfo)
+ * === certAuth based enroll === "certAuthEnroll" is on.
+ * "certauthEnrollType can be one of the three: single - it's for single
+ * cert enrollment dual - it's for dual certs enrollment encryption -
+ * getting the encryption cert only via authentication of the signing
+ * cert (crmf or keyGenInfo)
*/
boolean certAuthEnroll = false;
String certAuthEnrollOn =
- httpParams.getValueAsString("certauthEnroll", null);
+ httpParams.getValueAsString("certauthEnroll", null);
if ((certAuthEnrollOn != null) && (certAuthEnrollOn.equals("on"))) {
certAuthEnroll = true;
@@ -371,7 +364,7 @@ public class EnrollServlet extends CMSServlet {
}
private String getCertAuthEnrollType(IArgBlock httpParams, boolean certAuthEnroll)
- throws EBaseException {
+ throws EBaseException {
String certauthEnrollType = null;
@@ -387,53 +380,53 @@ public class EnrollServlet extends CMSServlet {
CMS.debug("EnrollServlet: certauthEnrollType is single");
} else {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_INVALID_CERTAUTH_ENROLL_TYPE_1", certauthEnrollType));
+ CMS.getLogMessage("CMSGW_INVALID_CERTAUTH_ENROLL_TYPE_1", certauthEnrollType));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_INVALID_CERTAUTH_ENROLL_TYPE"));
+ CMS.getUserMessage("CMS_GW_INVALID_CERTAUTH_ENROLL_TYPE"));
}
} else {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("MSGW_MISSING_CERTAUTH_ENROLL_TYPE"));
+ CMS.getLogMessage("MSGW_MISSING_CERTAUTH_ENROLL_TYPE"));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_MISSING_CERTAUTH_ENROLL_TYPE"));
+ CMS.getUserMessage("CMS_GW_MISSING_CERTAUTH_ENROLL_TYPE"));
}
}
-
+
return certauthEnrollType;
-
+
}
private boolean checkClientCertSigningOnly(X509Certificate sslClientCert)
- throws EBaseException {
+ throws EBaseException {
if ((CMS.isSigningCert((X509CertImpl) sslClientCert) ==
false) ||
- ((CMS.isSigningCert((X509CertImpl) sslClientCert) ==
+ ((CMS.isSigningCert((X509CertImpl) sslClientCert) ==
true) &&
(CMS.isEncryptionCert((X509CertImpl) sslClientCert) ==
true))) {
// either it's not a signing cert, or it's a dual cert
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_INVALID_CERT_TYPE"));
+ CMS.getLogMessage("CMSGW_INVALID_CERT_TYPE"));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_INVALID_CERT_TYPE"));
+ CMS.getUserMessage("CMS_GW_INVALID_CERT_TYPE"));
}
return true;
}
-
+
private X509CertInfo[] handleCertAuthDual(X509CertInfo certInfo, IAuthToken authToken, X509Certificate sslClientCert,
- ICertificateAuthority mCa, String certBasedOldSubjectDN,
- BigInteger certBasedOldSerialNum)
- throws EBaseException {
-
+ ICertificateAuthority mCa, String certBasedOldSubjectDN,
+ BigInteger certBasedOldSerialNum)
+ throws EBaseException {
+
CMS.debug("EnrollServlet: In handleCertAuthDual!");
-
+
if (mCa == null) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_NOT_A_CA"));
+ CMS.getLogMessage("CMSGW_NOT_A_CA"));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_NOT_A_CA"));
+ CMS.getUserMessage("CMS_GW_NOT_A_CA"));
}
// first, make sure the client cert is indeed a
@@ -456,20 +449,20 @@ public class EnrollServlet extends CMSServlet {
certInfo.set(X509CertInfo.KEY, new CertificateX509Key(key));
} catch (CertificateException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_FAILED_SET_KEY_FROM_CERT_AUTH_ENROLL_1", e.toString()));
+ CMS.getLogMessage("CMSGW_FAILED_SET_KEY_FROM_CERT_AUTH_ENROLL_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SET_KEY_FROM_CERT_AUTH_ENROLL_FAILED", e.toString()));
+ CMS.getUserMessage("CMS_GW_SET_KEY_FROM_CERT_AUTH_ENROLL_FAILED", e.toString()));
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_FAILED_SET_KEY_FROM_CERT_AUTH_ENROLL_IO", e.toString()));
+ CMS.getLogMessage("CMSGW_FAILED_SET_KEY_FROM_CERT_AUTH_ENROLL_IO", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SET_KEY_FROM_CERT_AUTH_ENROLL_FAILED", e.toString()));
+ CMS.getUserMessage("CMS_GW_SET_KEY_FROM_CERT_AUTH_ENROLL_FAILED", e.toString()));
}
String filter =
- "(&(x509cert.subject=" + certBasedOldSubjectDN + ")(!(x509cert.serialNumber=" + certBasedOldSerialNum + "))(certStatus=VALID))";
+ "(&(x509cert.subject=" + certBasedOldSubjectDN + ")(!(x509cert.serialNumber=" + certBasedOldSerialNum + "))(certStatus=VALID))";
ICertRecordList list =
- (ICertRecordList) mCa.getCertificateRepository().findCertRecordsInList(filter, null, 10);
+ (ICertRecordList) mCa.getCertificateRepository().findCertRecordsInList(filter, null, 10);
int size = list.getSize();
Enumeration<ICertRecord> en = list.getCertRecords(0, size - 1);
boolean gotEncCert = false;
@@ -482,8 +475,8 @@ public class EnrollServlet extends CMSServlet {
// pairing encryption cert not found
} else {
X509CertInfo encCertInfo = CMS.getDefaultX509CertInfo();
- X509CertInfo[] cInfoArray = new X509CertInfo[] {certInfo,
- encCertInfo};
+ X509CertInfo[] cInfoArray = new X509CertInfo[] { certInfo,
+ encCertInfo };
int i = 1;
boolean encCertFound = false;
@@ -494,7 +487,7 @@ public class EnrollServlet extends CMSServlet {
// if not encryption cert only, try next one
if ((CMS.isEncryptionCert(cert) == false) ||
- ((CMS.isEncryptionCert(cert) == true) &&
+ ((CMS.isEncryptionCert(cert) == true) &&
(CMS.isSigningCert(cert) == true))) {
CMS.debug("EnrollServlet: Not encryption only cert, will try next one.");
@@ -508,27 +501,27 @@ public class EnrollServlet extends CMSServlet {
try {
encCertInfo = (X509CertInfo)
cert.get(
- X509CertImpl.NAME + "." + X509CertImpl.INFO);
+ X509CertImpl.NAME + "." + X509CertImpl.INFO);
} catch (CertificateParsingException ex) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_MISSING_CERTINFO_ENCRYPT_CERT"));
+ CMS.getLogMessage("CMSGW_MISSING_CERTINFO_ENCRYPT_CERT"));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_MISSING_CERTINFO"));
+ CMS.getUserMessage("CMS_GW_MISSING_CERTINFO"));
}
try {
encCertInfo.set(X509CertInfo.KEY, new CertificateX509Key(key));
} catch (CertificateException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_FAILED_SET_KEY_FROM_CERT_AUTH_ENROLL_1", e.toString()));
+ CMS.getLogMessage("CMSGW_FAILED_SET_KEY_FROM_CERT_AUTH_ENROLL_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SET_KEY_FROM_CERT_AUTH_ENROLL_FAILED", e.toString()));
+ CMS.getUserMessage("CMS_GW_SET_KEY_FROM_CERT_AUTH_ENROLL_FAILED", e.toString()));
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_FAILED_SET_KEY_FROM_CERT_AUTH_ENROLL_1", e.toString()));
+ CMS.getLogMessage("CMSGW_FAILED_SET_KEY_FROM_CERT_AUTH_ENROLL_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SET_KEY_FROM_CERT_AUTH_ENROLL_FAILED", e.toString()));
+ CMS.getUserMessage("CMS_GW_SET_KEY_FROM_CERT_AUTH_ENROLL_FAILED", e.toString()));
}
CMS.debug("EnrollServlet: About to fillCertInfoFromAuthToken!");
@@ -545,14 +538,14 @@ public class EnrollServlet extends CMSServlet {
CMS.debug("EnrollServlet: returning cInfoArray of length " + cInfoArray.length);
return cInfoArray;
- }
+ }
}
private boolean handleEnrollAuditLog(IRequest req, CMSRequest cmsReq, String authMgr, IAuthToken authToken,
- X509CertInfo certInfo, long startTime)
- throws EBaseException {
- //for audit log
+ X509CertInfo certInfo, long startTime)
+ throws EBaseException {
+ // for audit log
String initiative = null;
String agentID = null;
@@ -563,7 +556,7 @@ public class EnrollServlet extends CMSServlet {
} else {
agentID = authToken.getInString("userid");
initiative = AuditFormat.FROMAGENT + " agentID: " + agentID;
- }
+ }
// if service not complete return standard templates.
RequestStatus status = req.getRequestStatus();
@@ -584,54 +577,54 @@ public class EnrollServlet extends CMSServlet {
wholeMsg.append(msgs.nextElement());
}
mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.ENROLLMENTFORMAT,
- new Object[] {
- req.getRequestId(),
- initiative,
- authMgr,
- status.toString(),
- certInfo.get(X509CertInfo.SUBJECT),
- " violation: " +
- wholeMsg.toString()}
- );
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.ENROLLMENTFORMAT,
+ new Object[] {
+ req.getRequestId(),
+ initiative,
+ authMgr,
+ status.toString(),
+ certInfo.get(X509CertInfo.SUBJECT),
+ " violation: " +
+ wholeMsg.toString() }
+ );
} else { // no policy violation, from agent
mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.ENROLLMENTFORMAT,
- new Object[] {
- req.getRequestId(),
- initiative,
- authMgr,
- status.toString(),
- certInfo.get(X509CertInfo.SUBJECT), ""}
- );
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.ENROLLMENTFORMAT,
+ new Object[] {
+ req.getRequestId(),
+ initiative,
+ authMgr,
+ status.toString(),
+ certInfo.get(X509CertInfo.SUBJECT), "" }
+ );
}
} else { // other imcomplete status
long endTime = CMS.getCurrentDate().getTime();
mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.ENROLLMENTFORMAT,
- new Object[] {
- req.getRequestId(),
- initiative,
- authMgr,
- status.toString(),
- certInfo.get(X509CertInfo.SUBJECT) + " time: " + (endTime - startTime), ""}
- );
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.ENROLLMENTFORMAT,
+ new Object[] {
+ req.getRequestId(),
+ initiative,
+ authMgr,
+ status.toString(),
+ certInfo.get(X509CertInfo.SUBJECT) + " time: " + (endTime - startTime), "" }
+ );
}
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_CANT_GET_CERT_SUBJ_AUDITING",
- e.toString()));
+ CMS.getLogMessage("CMSGW_CANT_GET_CERT_SUBJ_AUDITING",
+ e.toString()));
} catch (CertificateException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_CANT_GET_CERT_SUBJ_AUDITING",
- e.toString()));
+ CMS.getLogMessage("CMSGW_CANT_GET_CERT_SUBJ_AUDITING",
+ e.toString()));
}
return false;
}
@@ -643,40 +636,40 @@ public class EnrollServlet extends CMSServlet {
cmsReq.setStatus(CMSRequest.ERROR);
cmsReq.setError(req.getExtDataInString(IRequest.ERROR));
String[] svcErrors =
- req.getExtDataInStringArray(IRequest.SVCERRORS);
+ req.getExtDataInStringArray(IRequest.SVCERRORS);
if (svcErrors != null && svcErrors.length > 0) {
for (int i = 0; i < svcErrors.length; i++) {
String err = svcErrors[i];
if (err != null) {
- //System.out.println(
- //"revocation servlet: setting error description "+
- //err.toString());
+ // System.out.println(
+ // "revocation servlet: setting error description "+
+ // err.toString());
cmsReq.setErrorDescription(err);
// audit log the error
try {
mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.ENROLLMENTFORMAT,
- new Object[] {
- req.getRequestId(),
- initiative,
- authMgr,
- "completed with error: " +
- err,
- certInfo.get(X509CertInfo.SUBJECT), ""
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.ENROLLMENTFORMAT,
+ new Object[] {
+ req.getRequestId(),
+ initiative,
+ authMgr,
+ "completed with error: " +
+ err,
+ certInfo.get(X509CertInfo.SUBJECT), ""
}
- );
+ );
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_CANT_GET_CERT_SUBJ_AUDITING",
- e.toString()));
+ CMS.getLogMessage("CMSGW_CANT_GET_CERT_SUBJ_AUDITING",
+ e.toString()));
} catch (CertificateException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_CANT_GET_CERT_SUBJ_AUDITING",
- e.toString()));
+ CMS.getLogMessage("CMSGW_CANT_GET_CERT_SUBJ_AUDITING",
+ e.toString()));
}
}
@@ -693,29 +686,30 @@ public class EnrollServlet extends CMSServlet {
/**
* Process X509 certificate enrollment request
* <P>
- *
+ *
* (Certificate Request - either an "admin" cert request for an admin
- * certificate, an "agent" cert request for "bulk enrollment", or
- * an "EE" standard cert request)
+ * certificate, an "agent" cert request for "bulk enrollment", or an "EE"
+ * standard cert request)
* <P>
- *
+ *
* (Certificate Request Processed - either an automated "admin" non-profile
- * based CA admin cert acceptance, an automated "admin" non-profile based
- * CA admin cert rejection, an automated "EE" non-profile based cert
- * acceptance, or an automated "EE" non-profile based cert rejection)
+ * based CA admin cert acceptance, an automated "admin" non-profile based CA
+ * admin cert rejection, an automated "EE" non-profile based cert
+ * acceptance, or an automated "EE" non-profile based cert rejection)
* <P>
- *
+ *
* <ul>
- * <li>signed.audit LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST used when a
- * non-profile cert request is made (before approval process)
+ * <li>signed.audit LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST used when
+ * a non-profile cert request is made (before approval process)
* <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED used when a
* certificate request has just been through the approval process
* </ul>
+ *
* @param cmsReq a certificate enrollment request
* @exception EBaseException an error has occurred
*/
- protected void processX509(CMSRequest cmsReq)
- throws EBaseException {
+ protected void processX509(CMSRequest cmsReq)
+ throws EBaseException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
String auditRequesterID = ILogger.UNIDENTIFIED;
@@ -733,7 +727,7 @@ public class EnrollServlet extends CMSServlet {
IConfigStore configStore = CMS.getConfigStore();
- /* XXX shouldn't we read this from ServletConfig at init time? */
+ /* XXX shouldn't we read this from ServletConfig at init time? */
enforcePop = configStore.getBoolean("enrollment.enforcePop", false);
CMS.debug("EnrollServlet: enforcePop " + enforcePop);
@@ -743,7 +737,7 @@ public class EnrollServlet extends CMSServlet {
startTime = CMS.getCurrentDate().getTime();
httpParams = cmsReq.getHttpParams();
httpReq = cmsReq.getHttpReq();
- if (mAuthMgr != null) {
+ if (mAuthMgr != null) {
authToken = authenticate(cmsReq);
}
@@ -752,10 +746,10 @@ public class EnrollServlet extends CMSServlet {
mAuthzResourceName, "submit");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -763,8 +757,8 @@ public class EnrollServlet extends CMSServlet {
// store a message in the signed audit log file
// (either an "admin" cert request for an admin certificate,
- // an "agent" cert request for "bulk enrollment", or
- // an "EE" standard cert request)
+ // an "agent" cert request for "bulk enrollment", or
+ // an "EE" standard cert request)
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST,
auditSubjectID,
@@ -791,27 +785,24 @@ public class EnrollServlet extends CMSServlet {
}
try {
- if (CMS.getConfigStore().getBoolean("useThreadNaming", false)) {
- String currentName = Thread.currentThread().getName();
+ if (CMS.getConfigStore().getBoolean("useThreadNaming", false)) {
+ String currentName = Thread.currentThread().getName();
Thread.currentThread().setName(currentName
- + "-request-"
- + req.getRequestId().toString()
- + "-"
- + (new Date()).getTime());
+ + "-request-"
+ + req.getRequestId().toString()
+ + "-"
+ + (new Date()).getTime());
}
} catch (Exception e) {
}
/*
- * === certAuth based enroll ===
- * "certAuthEnroll" is on.
- * "certauthEnrollType can be one of the three:
- * single - it's for single cert enrollment
- * dual - it's for dual certs enrollment
- * encryption - getting the encryption cert only via
- * authentication of the signing cert
- * (crmf or keyGenInfo)
+ * === certAuth based enroll === "certAuthEnroll" is on.
+ * "certauthEnrollType can be one of the three: single - it's for
+ * single cert enrollment dual - it's for dual certs enrollment
+ * encryption - getting the encryption cert only via authentication
+ * of the signing cert (crmf or keyGenInfo)
*/
boolean certAuthEnroll = false;
String certauthEnrollType = null;
@@ -826,8 +817,8 @@ public class EnrollServlet extends CMSServlet {
} catch (ECMSGWException e) {
// store a message in the signed audit log file
// (either an "admin" cert request for an admin certificate,
- // an "agent" cert request for "bulk enrollment", or
- // an "EE" standard cert request)
+ // an "agent" cert request for "bulk enrollment", or
+ // an "EE" standard cert request)
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST,
auditSubjectID,
@@ -844,7 +835,7 @@ public class EnrollServlet extends CMSServlet {
CMS.debug("EnrollServlet: In EnrollServlet.processX509!");
CMS.debug("EnrollServlet: certAuthEnroll " + certAuthEnroll);
CMS.debug("EnrollServlet: certauthEnrollType " + certauthEnrollType);
-
+
String challengePassword = httpParams.getValueAsString(
"challengePassword", "");
@@ -859,18 +850,18 @@ public class EnrollServlet extends CMSServlet {
BigInteger certBasedOldSerialNum = null;
// check if request was authenticated, if so set authtoken &
- // certInfo. also if authenticated, take certInfo from authToken.
+ // certInfo. also if authenticated, take certInfo from authToken.
certInfo = null;
if (certAuthEnroll == true) {
sslClientCert = getSSLClientCertificate(httpReq);
if (sslClientCert == null) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_MISSING_SSL_CLIENT_CERT"));
+ CMS.getLogMessage("CMSGW_MISSING_SSL_CLIENT_CERT"));
// store a message in the signed audit log file
// (either an "admin" cert request for an admin certificate,
- // an "agent" cert request for "bulk enrollment", or
- // an "EE" standard cert request)
+ // an "agent" cert request for "bulk enrollment", or
+ // an "EE" standard cert request)
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST,
auditSubjectID,
@@ -882,7 +873,7 @@ public class EnrollServlet extends CMSServlet {
audit(auditMessage);
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_MISSING_SSL_CLIENT_CERT"));
+ CMS.getUserMessage("CMS_GW_MISSING_SSL_CLIENT_CERT"));
}
certBasedOldSubjectDN = (String)
@@ -896,23 +887,23 @@ public class EnrollServlet extends CMSServlet {
// if the cert subject name is NOT MISSING, retrieve the
// actual "auditCertificateSubjectName" and "normalize" it
if (certBasedOldSubjectDN != null) {
- // NOTE: This is ok even if the cert subject name
- // is "" (empty)!
+ // NOTE: This is ok even if the cert subject name
+ // is "" (empty)!
auditCertificateSubjectName = certBasedOldSubjectDN.trim();
}
try {
certInfo = (X509CertInfo)
((X509CertImpl) sslClientCert).get(
- X509CertImpl.NAME + "." + X509CertImpl.INFO);
+ X509CertImpl.NAME + "." + X509CertImpl.INFO);
} catch (CertificateParsingException ex) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_MISSING_CERTINFO"));
+ CMS.getLogMessage("CMSGW_MISSING_CERTINFO"));
// store a message in the signed audit log file
// (either an "admin" cert request for an admin certificate,
- // an "agent" cert request for "bulk enrollment", or
- // an "EE" standard cert request)
+ // an "agent" cert request for "bulk enrollment", or
+ // an "EE" standard cert request)
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST,
auditSubjectID,
@@ -924,14 +915,14 @@ public class EnrollServlet extends CMSServlet {
audit(auditMessage);
throw new ECMSGWException(
- CMS.getUserMessage(getLocale(httpReq), "CMS_GW_MISSING_CERTINFO"));
+ CMS.getUserMessage(getLocale(httpReq), "CMS_GW_MISSING_CERTINFO"));
}
} else {
CMS.debug("EnrollServlet: No CertAuthEnroll.");
certInfo = CMS.getDefaultX509CertInfo();
}
- X509CertInfo[] certInfoArray = new X509CertInfo[] {certInfo};
+ X509CertInfo[] certInfoArray = new X509CertInfo[] { certInfo };
X509CertInfo authCertInfo = null;
String authMgr = AuditFormat.NOAUTH;
@@ -940,15 +931,15 @@ public class EnrollServlet extends CMSServlet {
if (authToken != null) {
authMgr =
authToken.getInString(AuthToken.TOKEN_AUTHMGR_INST_NAME);
- // don't store agent token in request.
- // agent currently used for bulk issuance.
+ // don't store agent token in request.
+ // agent currently used for bulk issuance.
// if (!authMgr.equals(AuthSubsystem.CERTUSERDB_AUTHMGR_ID)) {
- log(ILogger.LL_INFO,
- "Enrollment request was authenticated by " +
- authToken.getInString(AuthToken.TOKEN_AUTHMGR_INST_NAME));
+ log(ILogger.LL_INFO,
+ "Enrollment request was authenticated by " +
+ authToken.getInString(AuthToken.TOKEN_AUTHMGR_INST_NAME));
PKIProcessor.fillCertInfoFromAuthToken(certInfo,
- authToken);
+ authToken);
// save authtoken attrs to request directly
// (for policy use)
saveAuthToken(authToken, req);
@@ -960,17 +951,17 @@ public class EnrollServlet extends CMSServlet {
if (certAuthEnroll == true) {
// log(ILogger.LL_DEBUG,
- // "just gotten subjectDN and serialNumber " +
- // "from ssl client cert");
+ // "just gotten subjectDN and serialNumber " +
+ // "from ssl client cert");
if (authToken == null) {
// authToken is null, can't match to anyone; bail!
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_PROCESS_ENROLL_NO_AUTH"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_PROCESS_ENROLL_NO_AUTH"));
// store a message in the signed audit log file
// (either an "admin" cert request for an admin certificate,
- // an "agent" cert request for "bulk enrollment", or
- // an "EE" standard cert request)
+ // an "agent" cert request for "bulk enrollment", or
+ // an "EE" standard cert request)
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST,
auditSubjectID,
@@ -1028,7 +1019,7 @@ public class EnrollServlet extends CMSServlet {
}
}
- //pkcs10 = httpParams.getValuePKCS10(PKCS10_REQUEST, null);
+ // pkcs10 = httpParams.getValuePKCS10(PKCS10_REQUEST, null);
} else {
try {
@@ -1039,24 +1030,23 @@ public class EnrollServlet extends CMSServlet {
ex.printStackTrace();
}
}
-
+
String cmc = null;
String asciiBASE64Blob = httpParams.getValueAsString(CMC_REQUEST, null);
-
- if(asciiBASE64Blob!=null)
- {
- int startIndex = asciiBASE64Blob.indexOf(HEADER);
- int endIndex = asciiBASE64Blob.indexOf(TRAILER);
- if (startIndex!= -1 && endIndex!=-1) {
- startIndex = startIndex + HEADER.length();
- cmc=asciiBASE64Blob.substring(startIndex, endIndex);
- }else
- cmc = asciiBASE64Blob;
- CMS.debug("EnrollServlet: cmc " + cmc);
+
+ if (asciiBASE64Blob != null) {
+ int startIndex = asciiBASE64Blob.indexOf(HEADER);
+ int endIndex = asciiBASE64Blob.indexOf(TRAILER);
+ if (startIndex != -1 && endIndex != -1) {
+ startIndex = startIndex + HEADER.length();
+ cmc = asciiBASE64Blob.substring(startIndex, endIndex);
+ } else
+ cmc = asciiBASE64Blob;
+ CMS.debug("EnrollServlet: cmc " + cmc);
}
-
+
String crmf = httpParams.getValueAsString(CRMF_REQUEST, null);
-
+
CMS.debug("EnrollServlet: crmf " + crmf);
if (certAuthEnroll == true) {
@@ -1066,7 +1056,7 @@ public class EnrollServlet extends CMSServlet {
// for dual certs
if (certauthEnrollType.equals(CERT_AUTH_DUAL)) {
- CMS.debug("EnrollServlet: Attempting CERT_AUTH_DUAL");
+ CMS.debug("EnrollServlet: Attempting CERT_AUTH_DUAL");
boolean gotEncCert = false;
X509CertInfo[] cInfoArray = null;
@@ -1078,8 +1068,8 @@ public class EnrollServlet extends CMSServlet {
} catch (ECMSGWException e) {
// store a message in the signed audit log file
// (either an "admin" cert request for an admin
- // certificate, an "agent" cert request for
- // "bulk enrollment", or an "EE" standard cert request)
+ // certificate, an "agent" cert request for
+ // "bulk enrollment", or an "EE" standard cert request)
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST,
auditSubjectID,
@@ -1103,13 +1093,13 @@ public class EnrollServlet extends CMSServlet {
if (gotEncCert == false) {
// encryption cert not found, bail
log(ILogger.LL_FAILURE,
- CMS.getLogMessage(
- "CMSGW_ENCRYPTION_CERT_NOT_FOUND"));
+ CMS.getLogMessage(
+ "CMSGW_ENCRYPTION_CERT_NOT_FOUND"));
// store a message in the signed audit log file
// (either an "admin" cert request for an admin
- // certificate, an "agent" cert request for
- // "bulk enrollment", or an "EE" standard cert request)
+ // certificate, an "agent" cert request for
+ // "bulk enrollment", or an "EE" standard cert request)
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST,
auditSubjectID,
@@ -1121,7 +1111,7 @@ public class EnrollServlet extends CMSServlet {
audit(auditMessage);
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_ENCRYPTION_CERT_NOT_FOUND"));
+ CMS.getUserMessage("CMS_GW_ENCRYPTION_CERT_NOT_FOUND"));
}
} else if (certauthEnrollType.equals(CERT_AUTH_ENCRYPTION)) {
@@ -1135,8 +1125,8 @@ public class EnrollServlet extends CMSServlet {
} catch (ECMSGWException e) {
// store a message in the signed audit log file
// (either an "admin" cert request for an admin
- // certificate, an "agent" cert request for
- // "bulk enrollment", or an "EE" standard cert request)
+ // certificate, an "agent" cert request for
+ // "bulk enrollment", or an "EE" standard cert request)
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST,
auditSubjectID,
@@ -1158,12 +1148,12 @@ public class EnrollServlet extends CMSServlet {
this);
keyGenProc.fillCertInfo(null, certInfo,
- authToken, httpParams);
+ authToken, httpParams);
req.setExtData(CLIENT_ISSUER,
- sslClientCert.getIssuerDN().toString());
+ sslClientCert.getIssuerDN().toString());
CMS.debug("EnrollServlet: sslClientCert issuerDN = " +
- sslClientCert.getIssuerDN().toString());
+ sslClientCert.getIssuerDN().toString());
} else if (crmf != null && crmf != "") {
CRMFProcessor crmfProc = new CRMFProcessor(cmsReq, this, enforcePop);
@@ -1173,18 +1163,18 @@ public class EnrollServlet extends CMSServlet {
req);
req.setExtData(CLIENT_ISSUER,
- sslClientCert.getIssuerDN().toString());
+ sslClientCert.getIssuerDN().toString());
CMS.debug("EnrollServlet: sslClientCert issuerDN = " +
- sslClientCert.getIssuerDN().toString());
+ sslClientCert.getIssuerDN().toString());
} else {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_CANT_PROCESS_ENROLL_REQ") +
- CMS.getLogMessage("CMSGW_MISSING_KEYGEN_INFO"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_CANT_PROCESS_ENROLL_REQ") +
+ CMS.getLogMessage("CMSGW_MISSING_KEYGEN_INFO"));
// store a message in the signed audit log file
// (either an "admin" cert request for an admin
- // certificate, an "agent" cert request for
- // "bulk enrollment", or an "EE" standard cert request)
+ // certificate, an "agent" cert request for
+ // "bulk enrollment", or an "EE" standard cert request)
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST,
auditSubjectID,
@@ -1196,7 +1186,7 @@ public class EnrollServlet extends CMSServlet {
audit(auditMessage);
throw new ECMSGWException(
- CMS.getUserMessage(getLocale(httpReq), "CMS_GW_MISSING_KEYGEN_INFO"));
+ CMS.getUserMessage(getLocale(httpReq), "CMS_GW_MISSING_KEYGEN_INFO"));
}
} else if (certauthEnrollType.equals(CERT_AUTH_SINGLE)) {
@@ -1208,13 +1198,13 @@ public class EnrollServlet extends CMSServlet {
this);
keyGenProc.fillCertInfo(null, certInfo,
- authToken, httpParams);
+ authToken, httpParams);
} else if (pkcs10 != null) {
PKCS10Processor pkcs10Proc = new PKCS10Processor(cmsReq,
this);
pkcs10Proc.fillCertInfo(pkcs10, certInfo,
- authToken, httpParams);
+ authToken, httpParams);
} else if (cmc != null && cmc != "") {
CMCProcessor cmcProc = new CMCProcessor(cmsReq, this, enforcePop);
@@ -1230,14 +1220,14 @@ public class EnrollServlet extends CMSServlet {
httpParams,
req);
} else {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_CANT_PROCESS_ENROLL_REQ") +
- CMS.getLogMessage("CMSGW_MISSING_KEYGEN_INFO"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_CANT_PROCESS_ENROLL_REQ") +
+ CMS.getLogMessage("CMSGW_MISSING_KEYGEN_INFO"));
// store a message in the signed audit log file
// (either an "admin" cert request for an admin
- // certificate, an "agent" cert request for
- // "bulk enrollment", or an "EE" standard cert request)
+ // certificate, an "agent" cert request for
+ // "bulk enrollment", or an "EE" standard cert request)
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST,
auditSubjectID,
@@ -1249,10 +1239,10 @@ public class EnrollServlet extends CMSServlet {
audit(auditMessage);
throw new ECMSGWException(
- CMS.getUserMessage(getLocale(httpReq), "CMS_GW_MISSING_KEYGEN_INFO"));
+ CMS.getUserMessage(getLocale(httpReq), "CMS_GW_MISSING_KEYGEN_INFO"));
}
req.setExtData(CLIENT_ISSUER,
- sslClientCert.getIssuerDN().toString());
+ sslClientCert.getIssuerDN().toString());
}
} else if (keyGenInfo != null) {
@@ -1279,14 +1269,14 @@ public class EnrollServlet extends CMSServlet {
certInfoArray = crmfProc.fillCertInfoArray(crmf, authToken,
httpParams, req);
} else {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_CANT_PROCESS_ENROLL_REQ") +
- CMS.getLogMessage("CMSGW_MISSING_KEYGEN_INFO"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_CANT_PROCESS_ENROLL_REQ") +
+ CMS.getLogMessage("CMSGW_MISSING_KEYGEN_INFO"));
// store a message in the signed audit log file
// (either an "admin" cert request for an admin certificate,
- // an "agent" cert request for "bulk enrollment", or
- // an "EE" standard cert request)
+ // an "agent" cert request for "bulk enrollment", or
+ // an "EE" standard cert request)
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST,
auditSubjectID,
@@ -1300,28 +1290,26 @@ public class EnrollServlet extends CMSServlet {
throw new ECMSGWException(CMS.getUserMessage(getLocale(httpReq), "CMS_GW_MISSING_KEYGEN_INFO"));
}
-
// if ca, fill in default signing alg here
-
+
try {
- ICertificateAuthority caSub =
- (ICertificateAuthority) CMS.getSubsystem("ca");
- if (certInfoArray != null && caSub != null) {
- for (int ix = 0; ix < certInfoArray.length; ix++) {
- X509CertInfo ci = (X509CertInfo)certInfoArray[ix];
- String defaultSig = caSub.getDefaultAlgorithm();
- AlgorithmId algid = AlgorithmId.get(defaultSig);
- ci.set(X509CertInfo.ALGORITHM_ID,
- new CertificateAlgorithmId(algid));
+ ICertificateAuthority caSub =
+ (ICertificateAuthority) CMS.getSubsystem("ca");
+ if (certInfoArray != null && caSub != null) {
+ for (int ix = 0; ix < certInfoArray.length; ix++) {
+ X509CertInfo ci = (X509CertInfo) certInfoArray[ix];
+ String defaultSig = caSub.getDefaultAlgorithm();
+ AlgorithmId algid = AlgorithmId.get(defaultSig);
+ ci.set(X509CertInfo.ALGORITHM_ID,
+ new CertificateAlgorithmId(algid));
+ }
}
- }
} catch (Exception e) {
- CMS.debug("Failed to set signing alg to certinfo " + e.toString());
+ CMS.debug("Failed to set signing alg to certinfo " + e.toString());
}
req.setExtData(IRequest.CERT_INFO, certInfoArray);
-
if (challengePassword != null && !challengePassword.equals("")) {
String pwd = hashPassword(challengePassword);
@@ -1330,8 +1318,8 @@ public class EnrollServlet extends CMSServlet {
// store a message in the signed audit log file
// (either an "admin" cert request for an admin certificate,
- // an "agent" cert request for "bulk enrollment", or
- // an "EE" standard cert request)
+ // an "agent" cert request for "bulk enrollment", or
+ // an "EE" standard cert request)
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST,
auditSubjectID,
@@ -1345,8 +1333,8 @@ public class EnrollServlet extends CMSServlet {
} catch (EBaseException eAudit1) {
// store a message in the signed audit log file
// (either an "admin" cert request for an admin certificate,
- // an "agent" cert request for "bulk enrollment", or
- // an "EE" standard cert request)
+ // an "agent" cert request for "bulk enrollment", or
+ // an "EE" standard cert request)
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST,
auditSubjectID,
@@ -1365,9 +1353,9 @@ public class EnrollServlet extends CMSServlet {
// ensure that any low-level exceptions are reported
// to the signed audit log and stored as failures
try {
- // send request to request queue.
+ // send request to request queue.
mRequestQueue.processRequest(req);
- // process result.
+ // process result.
// render OLD_CERT_TYPE's response differently, we
// do not want any javascript in HTML, and need to
@@ -1379,11 +1367,11 @@ public class EnrollServlet extends CMSServlet {
issuedCerts =
cmsReq.getIRequest().getExtDataInCertArray(
- IRequest.ISSUED_CERTS);
+ IRequest.ISSUED_CERTS);
for (int i = 0; i < issuedCerts.length; i++) {
// (automated "agent" cert request processed
- // - "accepted")
+ // - "accepted")
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED,
auditSubjectID,
@@ -1449,27 +1437,27 @@ public class EnrollServlet extends CMSServlet {
// audit log the success.
long endTime = CMS.getCurrentDate().getTime();
- mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.ENROLLMENTFORMAT,
- new Object[]
- { req.getRequestId(),
- initiative,
- mAuthMgr,
- "completed",
- issuedCerts[0].getSubjectDN(),
- "cert issued serial number: 0x" +
- issuedCerts[0].getSerialNumber().toString(16) +
- " time: " +
- (endTime - startTime) }
- );
+ mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.ENROLLMENTFORMAT,
+ new Object[]
+ { req.getRequestId(),
+ initiative,
+ mAuthMgr,
+ "completed",
+ issuedCerts[0].getSubjectDN(),
+ "cert issued serial number: 0x" +
+ issuedCerts[0].getSerialNumber().toString(16) +
+ " time: " +
+ (endTime - startTime) }
+ );
// handle initial admin enrollment if in adminEnroll mode.
checkAdminEnroll(cmsReq, issuedCerts);
// return cert as mime type binary if requested.
if (checkImportCertToNav(cmsReq.getHttpResp(),
- httpParams, issuedCerts[0])) {
+ httpParams, issuedCerts[0])) {
cmsReq.setStatus(CMSRequest.SUCCESS);
for (int i = 0; i < issuedCerts.length; i++) {
@@ -1490,10 +1478,10 @@ public class EnrollServlet extends CMSServlet {
// use success template.
try {
- cmsReq.setResult(issuedCerts);
- renderTemplate(cmsReq, mEnrollSuccessTemplate,
- mEnrollSuccessFiller);
- cmsReq.setStatus(CMSRequest.SUCCESS);
+ cmsReq.setResult(issuedCerts);
+ renderTemplate(cmsReq, mEnrollSuccessTemplate,
+ mEnrollSuccessFiller);
+ cmsReq.setStatus(CMSRequest.SUCCESS);
for (int i = 0; i < issuedCerts.length; i++) {
// (automated "agent" cert request processed - "accepted")
@@ -1508,10 +1496,10 @@ public class EnrollServlet extends CMSServlet {
audit(auditMessage);
}
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_TEMP_REND_ERR",
- mEnrollSuccessFiller.toString(),
- e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_TEMP_REND_ERR",
+ mEnrollSuccessFiller.toString(),
+ e.toString()));
// (automated "agent" cert request processed - "rejected")
auditMessage = CMS.getLogMessage(
@@ -1525,7 +1513,7 @@ public class EnrollServlet extends CMSServlet {
audit(auditMessage);
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_RETURNING_RESULT_ERROR"));
+ CMS.getUserMessage("CMS_GW_RETURNING_RESULT_ERROR"));
}
} catch (EBaseException eAudit1) {
// store a message in the signed audit log file
@@ -1547,11 +1535,11 @@ public class EnrollServlet extends CMSServlet {
}
/**
- * check if this is first enroll from admin enroll.
- * If so disable admin enroll from here on.
+ * check if this is first enroll from admin enroll. If so disable admin
+ * enroll from here on.
*/
protected void checkAdminEnroll(CMSRequest cmsReq, X509CertImpl[] issuedCerts)
- throws EBaseException {
+ throws EBaseException {
// this is special case, get the admin certificate
if (mAuthMgr != null && mAuthMgr.equals(IAuthSubsystem.PASSWDUSERDB_AUTHMGR_ID)) {
addAdminAgent(cmsReq, issuedCerts);
@@ -1559,8 +1547,8 @@ public class EnrollServlet extends CMSServlet {
}
}
- protected void addAdminAgent(CMSRequest cmsReq, X509CertImpl[] issuedCerts)
- throws EBaseException {
+ protected void addAdminAgent(CMSRequest cmsReq, X509CertImpl[] issuedCerts)
+ throws EBaseException {
String userid = cmsReq.getHttpParams().getValueAsString("uid");
IUGSubsystem ug = (IUGSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_UG);
@@ -1571,13 +1559,13 @@ public class EnrollServlet extends CMSServlet {
ug.addUserCert(adminuser);
} catch (netscape.ldap.LDAPException e) {
CMS.debug(
- "EnrollServlet: Cannot add admin's certificate to its entry in the " +
- "user group database. Error " + e);
+ "EnrollServlet: Cannot add admin's certificate to its entry in the " +
+ "user group database. Error " + e);
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_ADDING_ADMIN_CERT_ERROR", e.toString()));
+ CMS.getUserMessage("CMS_GW_ADDING_ADMIN_CERT_ERROR", e.toString()));
}
- IGroup agentGroup =
- ug.getGroupFromName(CA_AGENT_GROUP);
+ IGroup agentGroup =
+ ug.getGroupFromName(CA_AGENT_GROUP);
if (agentGroup != null) {
// add user to the group if necessary
@@ -1585,15 +1573,15 @@ public class EnrollServlet extends CMSServlet {
agentGroup.addMemberName(userid);
ug.modifyGroup(agentGroup);
mLogger.log(ILogger.EV_AUDIT, ILogger.S_USRGRP,
- AuditFormat.LEVEL, AuditFormat.ADDUSERGROUPFORMAT,
- new Object[] {userid, userid, CA_AGENT_GROUP}
- );
+ AuditFormat.LEVEL, AuditFormat.ADDUSERGROUPFORMAT,
+ new Object[] { userid, userid, CA_AGENT_GROUP }
+ );
}
} else {
String msg = "Cannot add admin to the " +
- CA_AGENT_GROUP +
- " group: Group does not exist.";
+ CA_AGENT_GROUP +
+ " group: Group does not exist.";
CMS.debug("EnrollServlet: " + msg);
throw new ECMSGWException(CMS.getUserMessage("CMS_GW_ADDING_ADMIN_ERROR"));
@@ -1620,7 +1608,11 @@ public class EnrollServlet extends CMSServlet {
out.println("<H1>");
out.println("SUCCESS");
out.println("</H1>");
- out.println("Your request is submitted and approved. Please cut and paste the certificate into your server."); // XXX - localize the message
+ out.println("Your request is submitted and approved. Please cut and paste the certificate into your server."); // XXX
+ // -
+ // localize
+ // the
+ // message
out.println("<P>");
out.println("Request Creation Time: ");
out.println(cmsReq.getIRequest().getCreationTime().toString());
@@ -1635,24 +1627,28 @@ public class EnrollServlet extends CMSServlet {
out.println("<P>");
out.println("<PRE>");
X509CertImpl certs[] =
- cmsReq.getIRequest().getExtDataInCertArray(IRequest.ISSUED_CERTS);
+ cmsReq.getIRequest().getExtDataInCertArray(IRequest.ISSUED_CERTS);
out.println(CMS.getEncodedCert(certs[0]));
out.println("</PRE>");
out.println("<P>");
out.println("<!HTTP_OUTPUT REQUEST_CREATION_TIME=" +
- cmsReq.getIRequest().getCreationTime().toString() + ">");
- out.println("<!HTTP_OUTPUT REQUEST_STATUS=" +
- cmsReq.getStatus().toString() + ">");
- out.println("<!HTTP_OUTPUT REQUEST_ID=" +
- cmsReq.getIRequest().getRequestId().toString() + ">");
+ cmsReq.getIRequest().getCreationTime().toString() + ">");
+ out.println("<!HTTP_OUTPUT REQUEST_STATUS=" +
+ cmsReq.getStatus().toString() + ">");
+ out.println("<!HTTP_OUTPUT REQUEST_ID=" +
+ cmsReq.getIRequest().getRequestId().toString() + ">");
out.println("<!HTTP_OUTPUT X509_CERTIFICATE=" +
- CMS.getEncodedCert(certs[0]) + ">");
+ CMS.getEncodedCert(certs[0]) + ">");
} else if (cmsReq.getIRequest().getRequestStatus().equals(RequestStatus.PENDING)) {
out.println("<H1>");
out.println("PENDING");
out.println("</H1>");
- out.println("Your request is submitted. You can check on the status of your request with an authorized agent or local administrator by referring to the request ID."); // XXX - localize the message
+ out.println("Your request is submitted. You can check on the status of your request with an authorized agent or local administrator by referring to the request ID."); // XXX
+ // -
+ // localize
+ // the
+ // message
out.println("<P>");
out.println("Request Creation Time: ");
out.println(cmsReq.getIRequest().getCreationTime().toString());
@@ -1664,17 +1660,21 @@ public class EnrollServlet extends CMSServlet {
out.println(cmsReq.getIRequest().getRequestId().toString());
out.println("<P>");
out.println("<!HTTP_OUTPUT REQUEST_CREATION_TIME=" +
- cmsReq.getIRequest().getCreationTime().toString() + ">");
- out.println("<!HTTP_OUTPUT REQUEST_STATUS=" +
- cmsReq.getStatus().toString() + ">");
- out.println("<!HTTP_OUTPUT REQUEST_ID=" +
- cmsReq.getIRequest().getRequestId().toString() + ">");
+ cmsReq.getIRequest().getCreationTime().toString() + ">");
+ out.println("<!HTTP_OUTPUT REQUEST_STATUS=" +
+ cmsReq.getStatus().toString() + ">");
+ out.println("<!HTTP_OUTPUT REQUEST_ID=" +
+ cmsReq.getIRequest().getRequestId().toString() + ">");
} else {
out.println("<H1>");
out.println("ERROR");
out.println("</H1>");
out.println("<!INFO>");
- out.println("Please consult your local administrator for assistance."); // XXX - localize the message
+ out.println("Please consult your local administrator for assistance."); // XXX
+ // -
+ // localize
+ // the
+ // message
out.println("<!/INFO>");
out.println("<P>");
out.println("Request Status: ");
@@ -1683,47 +1683,43 @@ public class EnrollServlet extends CMSServlet {
out.println("Error: ");
out.println(cmsReq.getError()); // XXX - need to parse in Locale
out.println("<P>");
- out.println("<!HTTP_OUTPUT REQUEST_STATUS=" +
- cmsReq.getStatus().toString() + ">");
- out.println("<!HTTP_OUTPUT ERROR=" +
- cmsReq.getError() + ">");
+ out.println("<!HTTP_OUTPUT REQUEST_STATUS=" +
+ cmsReq.getStatus().toString() + ">");
+ out.println("<!HTTP_OUTPUT ERROR=" +
+ cmsReq.getError() + ">");
}
/**
- // include all the input data
- ArgBlock args = cmsReq.getHttpParams();
- Enumeration ele = args.getElements();
- while (ele.hasMoreElements()) {
- String eleT = (String)ele.nextElement();
- out.println("<!HTTP_INPUT " + eleT + "=" +
- args.get(eleT) + ">");
- }
+ * // include all the input data ArgBlock args = cmsReq.getHttpParams();
+ * Enumeration ele = args.getElements(); while (ele.hasMoreElements()) {
+ * String eleT = (String)ele.nextElement(); out.println("<!HTTP_INPUT "
+ * + eleT + "=" + args.get(eleT) + ">"); }
**/
out.println("</HTML>");
}
- // XXX ALERT !!
- // Remove the following and calls to them when we bundle a cartman
- // later than alpha1.
- // These are here to cover up problem in cartman where the
- // key usage extension always ends up being digital signature only
+ // XXX ALERT !!
+ // Remove the following and calls to them when we bundle a cartman
+ // later than alpha1.
+ // These are here to cover up problem in cartman where the
+ // key usage extension always ends up being digital signature only
// and for rsa-ex ends up having no bits set.
private boolean mIsTestBed = false;
- private void init_testbed_hack(IConfigStore config)
- throws EBaseException {
+ private void init_testbed_hack(IConfigStore config)
+ throws EBaseException {
mIsTestBed = config.getBoolean("isTestBed", true);
}
/**
* Signed Audit Log Info Certificate Value
- *
+ *
* This method is called to obtain the certificate from the passed in
* "X509CertImpl" for a signed audit log message.
* <P>
- *
+ *
* @param x509cert an X509CertImpl
* @return cert string containing the certificate
*/
@@ -1776,4 +1772,3 @@ public class EnrollServlet extends CMSServlet {
}
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/GetBySerial.java b/pki/base/common/src/com/netscape/cms/servlet/cert/GetBySerial.java
index a723cb52..0d11600c 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/GetBySerial.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/GetBySerial.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
@@ -58,7 +57,6 @@ import com.netscape.cms.servlet.common.ECMSGWException;
import com.netscape.cms.servlet.common.ICMSTemplateFiller;
import com.netscape.cmsutil.crypto.CryptoUtil;
-
/**
* Retrieve certificate by serial number.
*
@@ -83,10 +81,11 @@ public class GetBySerial extends CMSServlet {
super();
}
- /**
+ /**
* Initialize the servlet. This servlet uses the template file
- * "ImportCert.template" to import the cert to the users browser,
- * if that is what the user requested
+ * "ImportCert.template" to import the cert to the users browser, if that is
+ * what the user requested
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -102,7 +101,7 @@ public class GetBySerial extends CMSServlet {
}
mImportTemplateFiller = new ImportCertsTemplateFiller();
- // override success and error templates to null -
+ // override success and error templates to null -
// handle templates locally.
mTemplates.remove(CMSRequest.SUCCESS);
@@ -115,11 +114,11 @@ public class GetBySerial extends CMSServlet {
}
/**
- * Process the HTTP request.
+ * Process the HTTP request.
* <ul>
- * <li>http.param serialNumber serial number of certificate in HEX
+ * <li>http.param serialNumber serial number of certificate in HEX
* </ul>
- *
+ *
* @param cmsReq the object holding the request and response information
*/
public void process(CMSRequest cmsReq) throws EBaseException {
@@ -139,10 +138,10 @@ public class GetBySerial extends CMSServlet {
mAuthzResourceName, "import");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -160,18 +159,18 @@ public class GetBySerial extends CMSServlet {
serialNo = null;
}
if (serial == null || serialNo == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_INVALID_SERIAL_NUMBER"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_INVALID_SERIAL_NUMBER"));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_INVALID_SERIAL_NUMBER")));
+ CMS.getUserMessage("CMS_GW_INVALID_SERIAL_NUMBER")));
cmsReq.setStatus(CMSRequest.ERROR);
return;
}
ICertRecord certRecord = (ICertRecord) getCertRecord(serialNo);
if (certRecord == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_CERT_SERIAL_NOT_FOUND_1", serialNo.toString(16)));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_CERT_SERIAL_NOT_FOUND_1", serialNo.toString(16)));
cmsReq.setError(new ECMSGWException(
CMS.getUserMessage("CMS_GW_CERT_SERIAL_NOT_FOUND", "0x" + serialNo.toString(16))));
cmsReq.setStatus(CMSRequest.ERROR);
@@ -181,37 +180,37 @@ public class GetBySerial extends CMSServlet {
// if RA, needs requestOwner to match
// first, find the user's group
if (authToken != null) {
- String group = authToken.getInString("group");
-
- if ((group != null) && (group != "")) {
- CMS.debug("GetBySerial process: auth group="+group);
- if (group.equals("Registration Manager Agents")) {
- boolean groupMatched = false;
- // find the cert record's orig. requestor's group
- MetaInfo metai = certRecord.getMetaInfo();
- if (metai != null) {
- String reqId = (String) metai.get(ICertRecord.META_REQUEST_ID);
- RequestId rid = new RequestId(reqId);
- IRequest creq = mReqQ.findRequest(rid);
- if (creq != null) {
- String reqOwner = creq.getRequestOwner();
- if (reqOwner != null) {
- CMS.debug("GetBySerial process: req owner="+reqOwner);
- if (reqOwner.equals(group))
- groupMatched = true;
- }
+ String group = authToken.getInString("group");
+
+ if ((group != null) && (group != "")) {
+ CMS.debug("GetBySerial process: auth group=" + group);
+ if (group.equals("Registration Manager Agents")) {
+ boolean groupMatched = false;
+ // find the cert record's orig. requestor's group
+ MetaInfo metai = certRecord.getMetaInfo();
+ if (metai != null) {
+ String reqId = (String) metai.get(ICertRecord.META_REQUEST_ID);
+ RequestId rid = new RequestId(reqId);
+ IRequest creq = mReqQ.findRequest(rid);
+ if (creq != null) {
+ String reqOwner = creq.getRequestOwner();
+ if (reqOwner != null) {
+ CMS.debug("GetBySerial process: req owner=" + reqOwner);
+ if (reqOwner.equals(group))
+ groupMatched = true;
+ }
+ }
+ }
+ if (groupMatched == false) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_CERT_SERIAL_NOT_FOUND_1", serialNo.toString(16)));
+ cmsReq.setError(new ECMSGWException(
+ CMS.getUserMessage("CMS_GW_CERT_SERIAL_NOT_FOUND", "0x" + serialNo.toString(16))));
+ cmsReq.setStatus(CMSRequest.ERROR);
+ return;
+ }
}
- }
- if (groupMatched == false) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_CERT_SERIAL_NOT_FOUND_1", serialNo.toString(16)));
- cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_CERT_SERIAL_NOT_FOUND", "0x" + serialNo.toString(16))));
- cmsReq.setStatus(CMSRequest.ERROR);
- return;
- }
}
- }
}
X509CertImpl cert = certRecord.getCertificate();
@@ -224,7 +223,7 @@ public class GetBySerial extends CMSServlet {
IArgBlock ctx = CMS.createArgBlock();
Locale[] locale = new Locale[1];
CMSTemplateParams argSet = new CMSTemplateParams(header, ctx);
- ICertificateAuthority ca = (ICertificateAuthority)CMS.getSubsystem("ca");
+ ICertificateAuthority ca = (ICertificateAuthority) CMS.getSubsystem("ca");
CertificateChain cachain = ca.getCACertChain();
X509Certificate[] cacerts = cachain.getChain();
X509CertImpl[] userChain = new X509CertImpl[cacerts.length + 1];
@@ -236,7 +235,7 @@ public class GetBySerial extends CMSServlet {
userChain[0] = cert;
PKCS7 p7 = new PKCS7(new AlgorithmId[0],
- new ContentInfo(new byte[0]), userChain, new SignerInfo[0]);
+ new ContentInfo(new byte[0]), userChain, new SignerInfo[0]);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
@@ -246,7 +245,7 @@ public class GetBySerial extends CMSServlet {
byte[] p7Bytes = bos.toByteArray();
String p7Str = CMS.BtoA(p7Bytes);
-
+
header.addStringValue("pkcs7", CryptoUtil.normalizeCertStr(p7Str));
try {
CMSTemplate form = getTemplate(mIETemplate, req, locale);
@@ -256,16 +255,16 @@ public class GetBySerial extends CMSServlet {
form.renderOutput(out, argSet);
return;
} catch (Exception ee) {
- CMS.debug("GetBySerial process: Exception="+ee.toString());
+ CMS.debug("GetBySerial process: Exception=" + ee.toString());
}
- } //browser is IE
-
+ } // browser is IE
+
MetaInfo metai = certRecord.getMetaInfo();
String crmfReqId = null;
if (metai != null) {
crmfReqId = (String) metai.get(ICertRecord.META_CRMF_REQID);
- if (crmfReqId != null)
+ if (crmfReqId != null)
cmsReq.setResult(IRequest.CRMF_REQID, crmfReqId);
}
@@ -283,7 +282,7 @@ public class GetBySerial extends CMSServlet {
cmsReq.setStatus(CMSRequest.SUCCESS);
// XXX follow request in cert record to set certtype, which will
- // import cert only if it's client. For now assume "client" if
+ // import cert only if it's client. For now assume "client" if
// someone clicked to import this cert.
cmsReq.getHttpParams().set("certType", "client");
@@ -294,8 +293,7 @@ public class GetBySerial extends CMSServlet {
throw new ECMSGWException(CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
}
-
+
return;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/GetCAChain.java b/pki/base/common/src/com/netscape/cms/servlet/cert/GetCAChain.java
index b765a2cb..c0029d9c 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/GetCAChain.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/GetCAChain.java
@@ -15,10 +15,9 @@
// (C) 2007 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
- package com.netscape.cms.servlet.cert;
+package com.netscape.cms.servlet.cert;
-
- import java.io.ByteArrayOutputStream;
+import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
@@ -49,236 +48,237 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
- /**
- * Retrieve the Certificates comprising the CA Chain for this CA.
- *
- * @version $Revision$, $Date$
- */
- public class GetCAChain extends CMSServlet {
- /**
+/**
+ * Retrieve the Certificates comprising the CA Chain for this CA.
+ *
+ * @version $Revision$, $Date$
+ */
+public class GetCAChain extends CMSServlet {
+ /**
*
*/
- private static final long serialVersionUID = -8189048155415074581L;
- private final static String TPL_FILE = "displayCaCert.template";
- private String mFormPath = null;
-
- public GetCAChain() {
- super();
- }
-
- /**
- * initialize the servlet.
- * @param sc servlet configuration, read from the web.xml file
- */
- public void init(ServletConfig sc) throws ServletException {
- super.init(sc);
-
- // override success to display own output.
- mTemplates.remove(CMSRequest.SUCCESS);
- // coming from ee
- mFormPath = "/" + mAuthority.getId() + "/" + TPL_FILE;
- }
-
- /**
- * Process the HTTP request.
- * <ul>
- * <li>http.param op 'downloadBIN' - return the binary certificate chain
- * <li>http.param op 'displayIND' - display pretty-print of certificate chain components
- * </ul>
- * @param cmsReq the object holding the request and response information
- */
- protected void process(CMSRequest cmsReq)
- throws EBaseException {
- HttpServletRequest httpReq = cmsReq.getHttpReq();
- HttpServletResponse httpResp = cmsReq.getHttpResp();
-
- IAuthToken authToken = authenticate(cmsReq);
-
- // Construct an ArgBlock
- IArgBlock args = cmsReq.getHttpParams();
-
- // Get the operation code
- String op = null;
-
- op = args.getValueAsString("op", null);
- if (op == null) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_NO_OPTIONS_SELECTED"));
- throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_NO_OPTIONS_SELECTED"));
- }
-
- cmsReq.setStatus(CMSRequest.SUCCESS);
-
- AuthzToken authzToken = null;
-
- if (op.startsWith("download")) {
- try {
- authzToken = authorize(mAclMethod, authToken,
- mAuthzResourceName, "download");
- } catch (EAuthzAccessDenied e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
- } catch (Exception e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
- }
-
- if (authzToken == null) {
- cmsReq.setStatus(CMSRequest.UNAUTHORIZED);
- return;
- }
-
- downloadChain(op, args, httpReq, httpResp, cmsReq);
- } else if (op.startsWith("display")) {
- try {
- authzToken = mAuthz.authorize(mAclMethod, authToken,
- mAuthzResourceName, "read");
- } catch (EAuthzAccessDenied e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
- } catch (Exception e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
- }
-
- if (authzToken == null) {
- cmsReq.setStatus(CMSRequest.UNAUTHORIZED);
- return;
- }
-
- displayChain(op, args, httpReq, httpResp, cmsReq);
- } else {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_INVALID_OPTIONS_CA_CHAIN"));
- throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_INVALID_OPTIONS_SELECTED"));
- }
- // cmsReq.setResult(null);
- return;
- }
-
- private void downloadChain(String op,
- IArgBlock args,
- HttpServletRequest httpReq,
- HttpServletResponse httpResp,
- CMSRequest cmsReq)
- throws EBaseException {
-
- /* check browser info ? */
-
- /* check if pkcs7 will work for both nav and ie */
-
- byte[] bytes = null;
-
- /*
- * Some IE actions - IE doesn't want PKCS7 for "download" CA Cert.
- * This means that we can only hand out the root CA, and not
- * the whole chain.
- */
-
- if (clientIsMSIE(httpReq) && (op.equals("download") || op.equals("downloadBIN"))) {
- X509Certificate[] caCerts =
- ((ICertAuthority) mAuthority).getCACertChain().getChain();
-
- try {
- bytes = caCerts[0].getEncoded();
- } catch (CertificateEncodingException e) {
- cmsReq.setStatus(CMSRequest.ERROR);
- log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERROR_GETTING_CACERT_ENCODED", e.toString()));
- throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_GETTING_CA_CERT_ERROR"));
- }
- } else {
- CertificateChain certChain =
- ((ICertAuthority) mAuthority).getCACertChain();
-
- if (certChain == null) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_CA_CHAIN_EMPTY"));
- throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_CA_CHAIN_EMPTY"));
- }
-
- try {
- ByteArrayOutputStream encoded = new ByteArrayOutputStream();
-
- certChain.encode(encoded, false);
- bytes = encoded.toByteArray();
- } catch (IOException e) {
- cmsReq.setStatus(CMSRequest.ERROR);
- log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERROR_ENCODING_CA_CHAIN_1", e.toString()));
- throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_ENCODING_CA_CHAIN_ERROR"));
- }
- }
-
- String mimeType = null;
-
- if (op.equals("downloadBIN")) {
- mimeType = "application/octet-stream";
- } else {
- try {
- mimeType = args.getValueAsString("mimeType");
- } catch (EBaseException e) {
- mimeType = "application/octet-stream";
- }
- }
-
- try {
- if (op.equals("downloadBIN")) {
- // file suffixes changed to comply with RFC 5280
- // requirements for AIA extensions
- if (clientIsMSIE(httpReq)) {
- httpResp.setHeader("Content-disposition",
- "attachment; filename=ca.cer");
- } else {
- httpResp.setHeader("Content-disposition",
- "attachment; filename=ca.p7c");
- }
- }
- httpResp.setContentType(mimeType);
- httpResp.getOutputStream().write(bytes);
- httpResp.setContentLength(bytes.length);
- httpResp.getOutputStream().flush();
- } catch (IOException e) {
- cmsReq.setStatus(CMSRequest.ERROR);
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_DISPLAYING_CACHAIN_1", e.toString()));
- throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAYING_CACHAIN_ERROR"));
- }
- }
-
- private void displayChain(String op,
- IArgBlock args,
- HttpServletRequest httpReq,
- HttpServletResponse httpResp,
- CMSRequest cmsReq)
- throws EBaseException {
- String outputString = null;
-
- CertificateChain certChain =
- ((ICertAuthority) mAuthority).getCACertChain();
-
- if (certChain == null) {
- cmsReq.setStatus(CMSRequest.ERROR);
- log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_CA_CHAIN_NOT_AVAILABLE"));
- throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_CA_CHAIN_NOT_AVAILABLE"));
- }
-
- CMSTemplate form = null;
- Locale[] locale = new Locale[1];
-
- if (mOutputTemplatePath != null)
- mFormPath = mOutputTemplatePath;
+ private static final long serialVersionUID = -8189048155415074581L;
+ private final static String TPL_FILE = "displayCaCert.template";
+ private String mFormPath = null;
+
+ public GetCAChain() {
+ super();
+ }
+
+ /**
+ * initialize the servlet.
+ *
+ * @param sc servlet configuration, read from the web.xml file
+ */
+ public void init(ServletConfig sc) throws ServletException {
+ super.init(sc);
+
+ // override success to display own output.
+ mTemplates.remove(CMSRequest.SUCCESS);
+ // coming from ee
+ mFormPath = "/" + mAuthority.getId() + "/" + TPL_FILE;
+ }
+
+ /**
+ * Process the HTTP request.
+ * <ul>
+ * <li>http.param op 'downloadBIN' - return the binary certificate chain
+ * <li>http.param op 'displayIND' - display pretty-print of certificate
+ * chain components
+ * </ul>
+ *
+ * @param cmsReq the object holding the request and response information
+ */
+ protected void process(CMSRequest cmsReq)
+ throws EBaseException {
+ HttpServletRequest httpReq = cmsReq.getHttpReq();
+ HttpServletResponse httpResp = cmsReq.getHttpResp();
+
+ IAuthToken authToken = authenticate(cmsReq);
+
+ // Construct an ArgBlock
+ IArgBlock args = cmsReq.getHttpParams();
+
+ // Get the operation code
+ String op = null;
+
+ op = args.getValueAsString("op", null);
+ if (op == null) {
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_NO_OPTIONS_SELECTED"));
+ throw new ECMSGWException(
+ CMS.getUserMessage("CMS_GW_NO_OPTIONS_SELECTED"));
+ }
+
+ cmsReq.setStatus(CMSRequest.SUCCESS);
+
+ AuthzToken authzToken = null;
+
+ if (op.startsWith("download")) {
+ try {
+ authzToken = authorize(mAclMethod, authToken,
+ mAuthzResourceName, "download");
+ } catch (EAuthzAccessDenied e) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ } catch (Exception e) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ }
+
+ if (authzToken == null) {
+ cmsReq.setStatus(CMSRequest.UNAUTHORIZED);
+ return;
+ }
+
+ downloadChain(op, args, httpReq, httpResp, cmsReq);
+ } else if (op.startsWith("display")) {
+ try {
+ authzToken = mAuthz.authorize(mAclMethod, authToken,
+ mAuthzResourceName, "read");
+ } catch (EAuthzAccessDenied e) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ } catch (Exception e) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ }
+
+ if (authzToken == null) {
+ cmsReq.setStatus(CMSRequest.UNAUTHORIZED);
+ return;
+ }
+
+ displayChain(op, args, httpReq, httpResp, cmsReq);
+ } else {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_INVALID_OPTIONS_CA_CHAIN"));
+ throw new ECMSGWException(
+ CMS.getUserMessage("CMS_GW_INVALID_OPTIONS_SELECTED"));
+ }
+ // cmsReq.setResult(null);
+ return;
+ }
+
+ private void downloadChain(String op,
+ IArgBlock args,
+ HttpServletRequest httpReq,
+ HttpServletResponse httpResp,
+ CMSRequest cmsReq)
+ throws EBaseException {
+
+ /* check browser info ? */
+
+ /* check if pkcs7 will work for both nav and ie */
+
+ byte[] bytes = null;
+
+ /*
+ * Some IE actions - IE doesn't want PKCS7 for "download" CA Cert. This
+ * means that we can only hand out the root CA, and not the whole chain.
+ */
+
+ if (clientIsMSIE(httpReq) && (op.equals("download") || op.equals("downloadBIN"))) {
+ X509Certificate[] caCerts =
+ ((ICertAuthority) mAuthority).getCACertChain().getChain();
+
+ try {
+ bytes = caCerts[0].getEncoded();
+ } catch (CertificateEncodingException e) {
+ cmsReq.setStatus(CMSRequest.ERROR);
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERROR_GETTING_CACERT_ENCODED", e.toString()));
+ throw new ECMSGWException(
+ CMS.getUserMessage("CMS_GW_GETTING_CA_CERT_ERROR"));
+ }
+ } else {
+ CertificateChain certChain =
+ ((ICertAuthority) mAuthority).getCACertChain();
+
+ if (certChain == null) {
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_CA_CHAIN_EMPTY"));
+ throw new ECMSGWException(
+ CMS.getUserMessage("CMS_GW_CA_CHAIN_EMPTY"));
+ }
+
+ try {
+ ByteArrayOutputStream encoded = new ByteArrayOutputStream();
+
+ certChain.encode(encoded, false);
+ bytes = encoded.toByteArray();
+ } catch (IOException e) {
+ cmsReq.setStatus(CMSRequest.ERROR);
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERROR_ENCODING_CA_CHAIN_1", e.toString()));
+ throw new ECMSGWException(
+ CMS.getUserMessage("CMS_GW_ENCODING_CA_CHAIN_ERROR"));
+ }
+ }
+
+ String mimeType = null;
+
+ if (op.equals("downloadBIN")) {
+ mimeType = "application/octet-stream";
+ } else {
+ try {
+ mimeType = args.getValueAsString("mimeType");
+ } catch (EBaseException e) {
+ mimeType = "application/octet-stream";
+ }
+ }
+
+ try {
+ if (op.equals("downloadBIN")) {
+ // file suffixes changed to comply with RFC 5280
+ // requirements for AIA extensions
+ if (clientIsMSIE(httpReq)) {
+ httpResp.setHeader("Content-disposition",
+ "attachment; filename=ca.cer");
+ } else {
+ httpResp.setHeader("Content-disposition",
+ "attachment; filename=ca.p7c");
+ }
+ }
+ httpResp.setContentType(mimeType);
+ httpResp.getOutputStream().write(bytes);
+ httpResp.setContentLength(bytes.length);
+ httpResp.getOutputStream().flush();
+ } catch (IOException e) {
+ cmsReq.setStatus(CMSRequest.ERROR);
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERROR_DISPLAYING_CACHAIN_1", e.toString()));
+ throw new ECMSGWException(
+ CMS.getUserMessage("CMS_GW_DISPLAYING_CACHAIN_ERROR"));
+ }
+ }
+
+ private void displayChain(String op,
+ IArgBlock args,
+ HttpServletRequest httpReq,
+ HttpServletResponse httpResp,
+ CMSRequest cmsReq)
+ throws EBaseException {
+ String outputString = null;
+
+ CertificateChain certChain =
+ ((ICertAuthority) mAuthority).getCACertChain();
+
+ if (certChain == null) {
+ cmsReq.setStatus(CMSRequest.ERROR);
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_CA_CHAIN_NOT_AVAILABLE"));
+ throw new ECMSGWException(
+ CMS.getUserMessage("CMS_GW_CA_CHAIN_NOT_AVAILABLE"));
+ }
+
+ CMSTemplate form = null;
+ Locale[] locale = new Locale[1];
+
+ if (mOutputTemplatePath != null)
+ mFormPath = mOutputTemplatePath;
try {
form = getTemplate(mFormPath, httpReq, locale);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", e.toString()));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
cmsReq.setStatus(CMSRequest.ERROR);
return;
}
@@ -306,7 +306,7 @@ import com.netscape.cms.servlet.common.ECMSGWException;
byte[] bytes = null;
try {
- subjectdn =
+ subjectdn =
certChain.getFirstCertificate().getSubjectDN().toString();
ByteArrayOutputStream encoded = new ByteArrayOutputStream();
@@ -315,14 +315,14 @@ import com.netscape.cms.servlet.common.ECMSGWException;
} catch (IOException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERROR_ENCODING_CA_CHAIN_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_ENCODING_CA_CHAIN_ERROR"));
+ CMS.getUserMessage("CMS_GW_ENCODING_CA_CHAIN_ERROR"));
}
String chainBase64 = getBase64(bytes);
header.addStringValue("subjectdn", subjectdn);
header.addStringValue("chainBase64", chainBase64);
- } else {
+ } else {
try {
X509Certificate[] certs = certChain.getChain();
@@ -339,13 +339,13 @@ import com.netscape.cms.servlet.common.ECMSGWException;
String subjectdn = certs[i].getSubjectDN().toString();
String finger = null;
try {
- finger = CMS.getFingerPrints(certs[i]);
+ finger = CMS.getFingerPrints(certs[i]);
} catch (Exception e) {
throw new IOException("Internal Error");
}
- ICertPrettyPrint certDetails =
- CMS.getCertPrettyPrint((X509CertImpl) certs[i]);
+ ICertPrettyPrint certDetails =
+ CMS.getCertPrettyPrint((X509CertImpl) certs[i]);
IArgBlock rarg = CMS.createArgBlock();
@@ -353,14 +353,14 @@ import com.netscape.cms.servlet.common.ECMSGWException;
rarg.addStringValue("subjectdn", subjectdn);
rarg.addStringValue("base64", getBase64(bytes));
rarg.addStringValue("certDetails",
- certDetails.toString(locale[0]));
+ certDetails.toString(locale[0]));
argSet.addRepeatRecord(rarg);
}
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_DISPLAYING_CACHAIN_1", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERROR_DISPLAYING_CACHAIN_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAYING_CACHAIN_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAYING_CACHAIN_ERROR"));
}
}
@@ -371,10 +371,10 @@ import com.netscape.cms.servlet.common.ECMSGWException;
form.renderOutput(out, argSet);
cmsReq.setStatus(CMSRequest.SUCCESS);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_BAD_SERV_OUT_STREAM", "", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_BAD_SERV_OUT_STREAM", "", e.toString()));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
cmsReq.setStatus(CMSRequest.ERROR);
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/GetCRL.java b/pki/base/common/src/com/netscape/cms/servlet/cert/GetCRL.java
index 2bbec482..68d38aab 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/GetCRL.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/GetCRL.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.io.IOException;
import java.math.BigInteger;
import java.security.cert.CRLException;
@@ -48,10 +47,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* Retrieve CRL for a Certificate Authority
- *
+ *
* @version $Revision$, $Date$
*/
public class GetCRL extends CMSServlet {
@@ -68,6 +66,7 @@ public class GetCRL extends CMSServlet {
/**
* initialize the servlet.
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -79,15 +78,14 @@ public class GetCRL extends CMSServlet {
mFormPath = mOutputTemplatePath;
}
-
/**
- * Process the HTTP request.
- *
+ * Process the HTTP request.
+ *
* @param cmsReq the object holding the request and response information
- * @see DisplayCRL#process
+ * @see DisplayCRL#process
*/
protected void process(CMSRequest cmsReq)
- throws EBaseException {
+ throws EBaseException {
HttpServletRequest httpReq = cmsReq.getHttpReq();
HttpServletResponse httpResp = cmsReq.getHttpResp();
@@ -100,10 +98,10 @@ public class GetCRL extends CMSServlet {
mAuthzResourceName, "read");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -117,7 +115,7 @@ public class GetCRL extends CMSServlet {
if (!(mAuthority instanceof ICertificateAuthority)) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_CA_FROM_RA_NOT_IMP"));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_NOT_YET_IMPLEMENTED")));
+ CMS.getUserMessage("CMS_GW_NOT_YET_IMPLEMENTED")));
cmsReq.setStatus(CMSRequest.ERROR);
return;
}
@@ -125,14 +123,14 @@ public class GetCRL extends CMSServlet {
CMSTemplate form = null;
Locale[] locale = new Locale[1];
-CMS.debug("**** mFormPath before getTemplate = "+mFormPath);
+ CMS.debug("**** mFormPath before getTemplate = " + mFormPath);
try {
form = getTemplate(mFormPath, httpReq, locale);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
cmsReq.setStatus(CMSRequest.ERROR);
return;
}
@@ -150,14 +148,14 @@ CMS.debug("**** mFormPath before getTemplate = "+mFormPath);
if (op == null) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_NO_OPTIONS_SELECTED"));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_NO_OPTIONS_SELECTED")));
+ CMS.getUserMessage("CMS_GW_NO_OPTIONS_SELECTED")));
cmsReq.setStatus(CMSRequest.ERROR);
return;
}
if (crlId == null) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_NO_CRL_ISSUING_POINT"));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_NO_CRL_SELECTED")));
+ CMS.getUserMessage("CMS_GW_NO_CRL_SELECTED")));
cmsReq.setStatus(CMSRequest.ERROR);
return;
}
@@ -165,23 +163,24 @@ CMS.debug("**** mFormPath before getTemplate = "+mFormPath);
ICRLIssuingPointRecord crlRecord = null;
ICertificateAuthority ca = (ICertificateAuthority) mAuthority;
ICRLIssuingPoint crlIP = null;
- if (ca != null) crlIP = ca.getCRLIssuingPoint(crlId);
+ if (ca != null)
+ crlIP = ca.getCRLIssuingPoint(crlId);
try {
crlRecord = (ICRLIssuingPointRecord) ca.getCRLRepository().readCRLIssuingPointRecord(crlId);
} catch (EBaseException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_NO_CRL_ISSUING_POINT_FOUND", crlId));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_NO_CRL_ISSUING_POINT_FOUND", crlId));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_CRL_NOT_FOUND")));
+ CMS.getUserMessage("CMS_GW_CRL_NOT_FOUND")));
cmsReq.setStatus(CMSRequest.ERROR);
return;
}
if (crlRecord == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_CRL_NOT_YET_UPDATED_1", crlId));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_CRL_NOT_YET_UPDATED_1", crlId));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_CRL_NOT_UPDATED")));
+ CMS.getUserMessage("CMS_GW_CRL_NOT_UPDATED")));
cmsReq.setStatus(CMSRequest.ERROR);
return;
}
@@ -201,12 +200,12 @@ CMS.debug("**** mFormPath before getTemplate = "+mFormPath);
}
if ((op.equals("checkCRLcache") ||
- (op.equals("displayCRL") && crlDisplayType != null && crlDisplayType.equals("cachedCRL"))) &&
- (crlIP == null || (!crlIP.isCRLCacheEnabled()) || crlIP.isCRLCacheEmpty())) {
+ (op.equals("displayCRL") && crlDisplayType != null && crlDisplayType.equals("cachedCRL"))) &&
+ (crlIP == null || (!crlIP.isCRLCacheEnabled()) || crlIP.isCRLCacheEmpty())) {
cmsReq.setError(
- CMS.getUserMessage(
- ((crlIP != null && crlIP.isCRLCacheEnabled() && crlIP.isCRLCacheEmpty())?
- "CMS_GW_CRL_CACHE_IS_EMPTY":"CMS_GW_CRL_CACHE_IS_NOT_ENABLED"), crlId));
+ CMS.getUserMessage(
+ ((crlIP != null && crlIP.isCRLCacheEnabled() && crlIP.isCRLCacheEmpty()) ?
+ "CMS_GW_CRL_CACHE_IS_EMPTY" : "CMS_GW_CRL_CACHE_IS_NOT_ENABLED"), crlId));
cmsReq.setStatus(CMSRequest.ERROR);
return;
}
@@ -214,26 +213,26 @@ CMS.debug("**** mFormPath before getTemplate = "+mFormPath);
byte[] crlbytes = null;
if (op.equals("importDeltaCRL") || op.equals("getDeltaCRL") ||
- (op.equals("displayCRL") && crlDisplayType != null &&
- crlDisplayType.equals("deltaCRL"))) {
+ (op.equals("displayCRL") && crlDisplayType != null &&
+ crlDisplayType.equals("deltaCRL"))) {
crlbytes = crlRecord.getDeltaCRL();
} else if (op.equals("importCRL") || op.equals("getCRL") ||
op.equals("checkCRL") ||
(op.equals("displayCRL") &&
- crlDisplayType != null &&
+ crlDisplayType != null &&
(crlDisplayType.equals("entireCRL") ||
- crlDisplayType.equals("crlHeader") ||
+ crlDisplayType.equals("crlHeader") ||
crlDisplayType.equals("base64Encoded")))) {
crlbytes = crlRecord.getCRL();
- }
+ }
if (crlbytes == null && (!op.equals("checkCRLcache")) &&
- (!(op.equals("displayCRL") && crlDisplayType != null &&
- crlDisplayType.equals("cachedCRL")))) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_CRL_NOT_YET_UPDATED_1", crlId));
+ (!(op.equals("displayCRL") && crlDisplayType != null &&
+ crlDisplayType.equals("cachedCRL")))) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_CRL_NOT_YET_UPDATED_1", crlId));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_CRL_NOT_UPDATED")));
+ CMS.getUserMessage("CMS_GW_CRL_NOT_UPDATED")));
cmsReq.setStatus(CMSRequest.ERROR);
return;
}
@@ -242,15 +241,15 @@ CMS.debug("**** mFormPath before getTemplate = "+mFormPath);
X509CRLImpl crl = null;
if (op.equals("checkCRL") || op.equals("importCRL") ||
- op.equals("importDeltaCRL") ||
- (op.equals("displayCRL") && crlDisplayType != null &&
- (crlDisplayType.equals("entireCRL") ||
- crlDisplayType.equals("crlHeader") ||
- crlDisplayType.equals("base64Encoded") ||
- crlDisplayType.equals("deltaCRL")))) {
+ op.equals("importDeltaCRL") ||
+ (op.equals("displayCRL") && crlDisplayType != null &&
+ (crlDisplayType.equals("entireCRL") ||
+ crlDisplayType.equals("crlHeader") ||
+ crlDisplayType.equals("base64Encoded") ||
+ crlDisplayType.equals("deltaCRL")))) {
try {
if (op.equals("displayCRL") && crlDisplayType != null &&
- crlDisplayType.equals("crlHeader")) {
+ crlDisplayType.equals("crlHeader")) {
crl = new X509CRLImpl(crlbytes, false);
} else {
crl = new X509CRLImpl(crlbytes);
@@ -258,25 +257,25 @@ CMS.debug("**** mFormPath before getTemplate = "+mFormPath);
} catch (Exception e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_FAILED_DECODE_CRL_1", e.toString()));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DECODE_CRL_FAILED")));
+ CMS.getUserMessage("CMS_GW_DECODE_CRL_FAILED")));
cmsReq.setStatus(CMSRequest.ERROR);
return;
}
if ((op.equals("importDeltaCRL") || (op.equals("displayCRL") &&
- crlDisplayType != null && crlDisplayType.equals("deltaCRL"))) &&
- ((!(crlIP != null && crlIP.isThisCurrentDeltaCRL(crl))) &&
- (crlRecord.getCRLNumber() == null ||
- crlRecord.getDeltaCRLNumber() == null ||
- crlRecord.getDeltaCRLNumber().compareTo(crlRecord.getCRLNumber()) < 0 ||
- crlRecord.getDeltaCRLSize() == null ||
+ crlDisplayType != null && crlDisplayType.equals("deltaCRL"))) &&
+ ((!(crlIP != null && crlIP.isThisCurrentDeltaCRL(crl))) &&
+ (crlRecord.getCRLNumber() == null ||
+ crlRecord.getDeltaCRLNumber() == null ||
+ crlRecord.getDeltaCRLNumber().compareTo(crlRecord.getCRLNumber()) < 0 ||
+ crlRecord.getDeltaCRLSize() == null ||
crlRecord.getDeltaCRLSize().longValue() == -1))) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERR_NO_DELTA_CRL_1"));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_CRL_NOT_UPDATED")));
+ CMS.getUserMessage("CMS_GW_CRL_NOT_UPDATED")));
cmsReq.setStatus(CMSRequest.ERROR);
return;
}
- }
+ }
String mimeType = "application/x-pkcs7-crl";
@@ -300,13 +299,13 @@ CMS.debug("**** mFormPath before getTemplate = "+mFormPath);
if (op.equals("checkCRL")) {
header.addBooleanValue("isOnCRL",
- crl.isRevoked(new BigInteger(certSerialNumber)));
+ crl.isRevoked(new BigInteger(certSerialNumber)));
}
if (op.equals("displayCRL")) {
if (crlDisplayType.equals("entireCRL") || crlDisplayType.equals("cachedCRL")) {
- ICRLPrettyPrint crlDetails = (crlDisplayType.equals("entireCRL"))?
- CMS.getCRLPrettyPrint(crl):
+ ICRLPrettyPrint crlDetails = (crlDisplayType.equals("entireCRL")) ?
+ CMS.getCRLPrettyPrint(crl) :
CMS.getCRLCachePrettyPrint(crlIP);
String pageStart = args.getValueAsString("pageStart", null);
String pageSize = args.getValueAsString("pageSize", null);
@@ -315,22 +314,23 @@ CMS.debug("**** mFormPath before getTemplate = "+mFormPath);
long lPageStart = new Long(pageStart).longValue();
long lPageSize = new Long(pageSize).longValue();
- if (lPageStart < 1) lPageStart = 1;
+ if (lPageStart < 1)
+ lPageStart = 1;
header.addStringValue("crlPrettyPrint",
crlDetails.toString(locale[0],
- lCRLSize, lPageStart, lPageSize));
+ lCRLSize, lPageStart, lPageSize));
header.addLongValue("pageStart", lPageStart);
header.addLongValue("pageSize", lPageSize);
} else {
header.addStringValue(
- "crlPrettyPrint", crlDetails.toString(locale[0]));
+ "crlPrettyPrint", crlDetails.toString(locale[0]));
}
} else if (crlDisplayType.equals("crlHeader")) {
ICRLPrettyPrint crlDetails = CMS.getCRLPrettyPrint(crl);
header.addStringValue(
- "crlPrettyPrint", crlDetails.toString(locale[0], lCRLSize, 0, 0));
+ "crlPrettyPrint", crlDetails.toString(locale[0], lCRLSize, 0, 0));
} else if (crlDisplayType.equals("base64Encoded")) {
try {
byte[] ba = crl.getEncoded();
@@ -365,12 +365,12 @@ CMS.debug("**** mFormPath before getTemplate = "+mFormPath);
}
} else if (crlDisplayType.equals("deltaCRL")) {
header.addIntegerValue("deltaCRLSize",
- crl.getNumberOfRevokedCertificates());
+ crl.getNumberOfRevokedCertificates());
ICRLPrettyPrint crlDetails = CMS.getCRLPrettyPrint(crl);
header.addStringValue(
- "crlPrettyPrint", crlDetails.toString(locale[0], 0, 0, 0));
+ "crlPrettyPrint", crlDetails.toString(locale[0], 0, 0, 0));
try {
byte[] ba = crl.getEncoded();
@@ -413,10 +413,10 @@ CMS.debug("**** mFormPath before getTemplate = "+mFormPath);
form.renderOutput(out, argSet);
cmsReq.setStatus(CMSRequest.SUCCESS);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_OUT_STREAM_TEMPLATE", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_OUT_STREAM_TEMPLATE", e.toString()));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
cmsReq.setStatus(CMSRequest.ERROR);
}
return;
@@ -428,21 +428,21 @@ CMS.debug("**** mFormPath before getTemplate = "+mFormPath);
} else if (op.equals("getCRL")) {
mimeType = "application/octet-stream";
httpResp.setHeader("Content-disposition",
- "attachment; filename=" + crlId + ".crl");
+ "attachment; filename=" + crlId + ".crl");
} else if (op.equals("getDeltaCRL")) {
mimeType = "application/octet-stream";
httpResp.setHeader("Content-disposition",
- "attachment; filename=delta-" + crlId + ".crl");
+ "attachment; filename=delta-" + crlId + ".crl");
} else {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_INVALID_OPTIONS_SELECTED"));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_INVALID_OPTIONS_SELECTED"));
+ CMS.getUserMessage("CMS_GW_INVALID_OPTIONS_SELECTED"));
}
try {
- // if (clientIsMSIE(httpReq) && op.equals("getCRL"))
- // httpResp.setHeader("Content-disposition",
- // "attachment; filename=getCRL.crl");
+ // if (clientIsMSIE(httpReq) && op.equals("getCRL"))
+ // httpResp.setHeader("Content-disposition",
+ // "attachment; filename=getCRL.crl");
httpResp.setContentType(mimeType);
httpResp.setContentLength(bytes.length);
httpResp.getOutputStream().write(bytes);
@@ -450,9 +450,9 @@ CMS.debug("**** mFormPath before getTemplate = "+mFormPath);
} catch (IOException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERROR_DISPLAYING_CRLINFO"));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAYING_CRLINFO_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAYING_CRLINFO_ERROR"));
}
- // cmsReq.setResult(null);
+ // cmsReq.setResult(null);
cmsReq.setStatus(CMSRequest.SUCCESS);
return;
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/GetCertFromRequest.java b/pki/base/common/src/com/netscape/cms/servlet/cert/GetCertFromRequest.java
index 5909bc4b..3ea9d02b 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/GetCertFromRequest.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/GetCertFromRequest.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.io.IOException;
import java.util.Locale;
@@ -52,10 +51,9 @@ import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
import com.netscape.cms.servlet.common.ICMSTemplateFiller;
-
/**
- * Gets a issued certificate from a request id.
- *
+ * Gets a issued certificate from a request id.
+ *
* @version $Revision$, $Date$
*/
public class GetCertFromRequest extends CMSServlet {
@@ -64,27 +62,26 @@ public class GetCertFromRequest extends CMSServlet {
*/
private static final long serialVersionUID = 5310646832256611066L;
private final static String PROP_IMPORT = "importCert";
- protected static final String
- GET_CERT_FROM_REQUEST_TEMPLATE = "ImportCert.template";
- protected static final String
- DISPLAY_CERT_FROM_REQUEST_TEMPLATE = "displayCertFromRequest.template";
+ protected static final String GET_CERT_FROM_REQUEST_TEMPLATE = "ImportCert.template";
+ protected static final String DISPLAY_CERT_FROM_REQUEST_TEMPLATE = "displayCertFromRequest.template";
protected static final String REQUEST_ID = "requestId";
protected static final String CERT_TYPE = "certtype";
- protected String mCertFrReqSuccessTemplate = null;
+ protected String mCertFrReqSuccessTemplate = null;
protected ICMSTemplateFiller mCertFrReqFiller = null;
protected IRequestQueue mQueue = null;
protected boolean mImportCert = true;
- public GetCertFromRequest() {
+ public GetCertFromRequest() {
super();
}
/**
* initialize the servlet. This servlet uses the template files
- * "displayCertFromRequest.template" and "ImportCert.template"
+ * "displayCertFromRequest.template" and "ImportCert.template"
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -102,23 +99,23 @@ public class GetCertFromRequest extends CMSServlet {
if (mImportCert)
defTemplate = GET_CERT_FROM_REQUEST_TEMPLATE;
- else
+ else
defTemplate = DISPLAY_CERT_FROM_REQUEST_TEMPLATE;
if (mAuthority instanceof IRegistrationAuthority)
defTemplate = "/ra/" + defTemplate;
- else
+ else
defTemplate = "/ca/" + defTemplate;
mCertFrReqSuccessTemplate = sc.getInitParameter(
PROP_SUCCESS_TEMPLATE);
if (mCertFrReqSuccessTemplate == null)
mCertFrReqSuccessTemplate = defTemplate;
String fillername =
- sc.getInitParameter(PROP_SUCCESS_TEMPLATE_FILLER);
+ sc.getInitParameter(PROP_SUCCESS_TEMPLATE_FILLER);
if (fillername != null) {
ICMSTemplateFiller filler = newFillerObject(fillername);
- if (filler != null)
+ if (filler != null)
mCertFrReqFiller = filler;
} else {
mCertFrReqFiller = new CertFrRequestFiller();
@@ -126,22 +123,21 @@ public class GetCertFromRequest extends CMSServlet {
} catch (Exception e) {
// should never happen.
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_IMP_INIT_SERV_ERR", e.toString(),
- mId));
+ CMS.getLogMessage("CMSGW_IMP_INIT_SERV_ERR", e.toString(),
+ mId));
}
}
-
/**
- * Process the HTTP request.
+ * Process the HTTP request.
* <ul>
- * <li>http.param requestId The request ID to search on
+ * <li>http.param requestId The request ID to search on
* </ul>
- *
+ *
* @param cmsReq the object holding the request and response information
*/
- protected void process(CMSRequest cmsReq)
- throws EBaseException {
+ protected void process(CMSRequest cmsReq)
+ throws EBaseException {
IArgBlock httpParams = cmsReq.getHttpParams();
HttpServletRequest httpReq = cmsReq.getHttpReq();
@@ -154,10 +150,10 @@ public class GetCertFromRequest extends CMSServlet {
mAuthzResourceName, "read");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -165,7 +161,7 @@ public class GetCertFromRequest extends CMSServlet {
return;
}
- String requestId = httpParams.getValueAsString(REQUEST_ID, null);
+ String requestId = httpParams.getValueAsString(REQUEST_ID, null);
if (requestId == null) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_NO_REQUEST_ID_PROVIDED"));
@@ -185,51 +181,51 @@ public class GetCertFromRequest extends CMSServlet {
if (r == null) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_REQUEST_ID_NOT_FOUND", requestId));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_REQUEST_ID_NOT_FOUND", requestId));
+ CMS.getUserMessage("CMS_GW_REQUEST_ID_NOT_FOUND", requestId));
}
if (authToken != null) {
- //if RA, group and requestOwner must match
- String group = authToken.getInString("group");
- if ((group != null) && (group != "") &&
- group.equals("Registration Manager Agents")) {
- boolean groupMatched = false;
- String reqOwner = r.getRequestOwner();
- if (reqOwner != null) {
- CMS.debug("GetCertFromRequest process: req owner="+reqOwner);
- if (reqOwner.equals(group))
- groupMatched = true;
- }
- if (groupMatched == false) {
- CMS.debug("RA group unmatched");
- log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_REQUEST_ID_NOT_FOUND", requestId));
- throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_REQUEST_ID_NOT_FOUND", requestId));
+ // if RA, group and requestOwner must match
+ String group = authToken.getInString("group");
+ if ((group != null) && (group != "") &&
+ group.equals("Registration Manager Agents")) {
+ boolean groupMatched = false;
+ String reqOwner = r.getRequestOwner();
+ if (reqOwner != null) {
+ CMS.debug("GetCertFromRequest process: req owner=" + reqOwner);
+ if (reqOwner.equals(group))
+ groupMatched = true;
+ }
+ if (groupMatched == false) {
+ CMS.debug("RA group unmatched");
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_REQUEST_ID_NOT_FOUND", requestId));
+ throw new ECMSGWException(
+ CMS.getUserMessage("CMS_GW_REQUEST_ID_NOT_FOUND", requestId));
+ }
}
- }
}
if (!((r.getRequestType().equals(IRequest.ENROLLMENT_REQUEST)) || (r.getRequestType().equals(IRequest.RENEWAL_REQUEST)))) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_REQUEST_NOT_ENROLLMENT_1", requestId));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_REQUEST_NOT_ENROLLMENT_1", requestId));
throw new ECMSGWException(
CMS.getUserMessage("CMS_GW_REQUEST_NOT_ENROLLMENT", requestId));
}
RequestStatus status = r.getRequestStatus();
if (!status.equals(RequestStatus.COMPLETE)) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_REQUEST_NOT_COMPLETED_1", requestId));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_REQUEST_NOT_COMPLETED_1", requestId));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_REQUEST_NOT_COMPLETED", requestId));
+ CMS.getUserMessage("CMS_GW_REQUEST_NOT_COMPLETED", requestId));
}
Integer result = r.getExtDataInInteger(IRequest.RESULT);
if (result != null && !result.equals(IRequest.RES_SUCCESS)) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_REQUEST_HAD_ERROR_1", requestId));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_REQUEST_HAD_ERROR_1", requestId));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_REQUEST_HAD_ERROR", requestId));
+ CMS.getUserMessage("CMS_GW_REQUEST_HAD_ERROR", requestId));
}
Object o = r.getExtDataInCertArray(IRequest.ISSUED_CERTS);
@@ -242,19 +238,19 @@ public class GetCertFromRequest extends CMSServlet {
o = certs;
}
if (o == null || !(o instanceof X509CertImpl[])) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_REQUEST_HAD_NO_CERTS_1", requestId));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_REQUEST_HAD_NO_CERTS_1", requestId));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_REQUEST_HAD_NO_CERTS", requestId));
+ CMS.getUserMessage("CMS_GW_REQUEST_HAD_NO_CERTS", requestId));
}
if (o instanceof X509CertImpl[]) {
X509CertImpl[] certs = (X509CertImpl[]) o;
if (certs == null || certs.length == 0 || certs[0] == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_REQUEST_HAD_NO_CERTS_1", requestId));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_REQUEST_HAD_NO_CERTS_1", requestId));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_REQUEST_HAD_NO_CERTS", requestId));
+ CMS.getUserMessage("CMS_GW_REQUEST_HAD_NO_CERTS", requestId));
}
// for importsCert to get the crmf_reqid.
@@ -263,7 +259,7 @@ public class GetCertFromRequest extends CMSServlet {
cmsReq.setStatus(CMSRequest.SUCCESS);
if (mImportCert &&
- checkImportCertToNav(cmsReq.getHttpResp(), httpParams, certs[0])) {
+ checkImportCertToNav(cmsReq.getHttpResp(), httpParams, certs[0])) {
return;
}
try {
@@ -271,26 +267,25 @@ public class GetCertFromRequest extends CMSServlet {
renderTemplate(cmsReq, mCertFrReqSuccessTemplate, mCertFrReqFiller);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGE_ERROR_DISPLAY_TEMPLATE_1",
- mCertFrReqSuccessTemplate, e.toString()));
+ CMS.getLogMessage("CMSGE_ERROR_DISPLAY_TEMPLATE_1",
+ mCertFrReqSuccessTemplate, e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
}
return;
}
}
-
class CertFrRequestFiller extends ImportCertsTemplateFiller {
public CertFrRequestFiller() {
}
public CMSTemplateParams getTemplateParams(
- CMSRequest cmsReq, IAuthority authority, Locale locale, Exception e)
- throws Exception {
- CMSTemplateParams tparams =
- super.getTemplateParams(cmsReq, authority, locale, e);
+ CMSRequest cmsReq, IAuthority authority, Locale locale, Exception e)
+ throws Exception {
+ CMSTemplateParams tparams =
+ super.getTemplateParams(cmsReq, authority, locale, e);
String reqId = cmsReq.getHttpParams().getValueAsString(
GetCertFromRequest.REQUEST_ID);
@@ -329,11 +324,11 @@ class CertFrRequestFiller extends ImportCertsTemplateFiller {
}
if (ext instanceof KeyUsageExtension) {
KeyUsageExtension usage =
- (KeyUsageExtension) ext;
+ (KeyUsageExtension) ext;
try {
if (((Boolean) usage.get(KeyUsageExtension.DIGITAL_SIGNATURE)).booleanValue() ||
- ((Boolean) usage.get(KeyUsageExtension.DATA_ENCIPHERMENT)).booleanValue())
+ ((Boolean) usage.get(KeyUsageExtension.DATA_ENCIPHERMENT)).booleanValue())
emailCert = true;
} catch (ArrayIndexOutOfBoundsException e0) {
// bug356108:
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/GetEnableStatus.java b/pki/base/common/src/com/netscape/cms/servlet/cert/GetEnableStatus.java
index 8b5536ea..e589cc06 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/GetEnableStatus.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/GetEnableStatus.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.io.IOException;
import java.util.Enumeration;
import java.util.Locale;
@@ -45,10 +44,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* Servlet to get the enrollment status, enable or disable.
- *
+ *
* @version $Revision$, $Date$
*/
public class GetEnableStatus extends CMSServlet {
@@ -64,7 +62,8 @@ public class GetEnableStatus extends CMSServlet {
}
/**
- * initialize the servlet.
+ * initialize the servlet.
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -80,15 +79,15 @@ public class GetEnableStatus extends CMSServlet {
}
/**
- * Process the HTTP request.
+ * Process the HTTP request.
* <ul>
* <li>http.param
* </ul>
- *
+ *
* @param cmsReq the object holding the request and response information
*/
protected void process(CMSRequest cmsReq)
- throws EBaseException {
+ throws EBaseException {
HttpServletRequest httpReq = cmsReq.getHttpReq();
HttpServletResponse httpResp = cmsReq.getHttpResp();
@@ -115,7 +114,7 @@ public class GetEnableStatus extends CMSServlet {
if (!(mAuthority instanceof IRegistrationAuthority)) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_CA_FROM_RA_NOT_IMP"));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_NOT_YET_IMPLEMENTED")));
+ CMS.getUserMessage("CMS_GW_NOT_YET_IMPLEMENTED")));
cmsReq.setStatus(CMSRequest.ERROR);
return;
}
@@ -126,11 +125,11 @@ public class GetEnableStatus extends CMSServlet {
try {
form = getTemplate(mFormPath, httpReq, locale);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE",
- mFormPath, e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE",
+ mFormPath, e.toString()));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
cmsReq.setStatus(CMSRequest.ERROR);
return;
}
@@ -164,10 +163,10 @@ public class GetEnableStatus extends CMSServlet {
form.renderOutput(out, argSet);
cmsReq.setStatus(CMSRequest.SUCCESS);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
cmsReq.setStatus(CMSRequest.ERROR);
}
cmsReq.setStatus(CMSRequest.SUCCESS);
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/GetInfo.java b/pki/base/common/src/com/netscape/cms/servlet/cert/GetInfo.java
index 9d83d430..3548caa0 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/GetInfo.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/GetInfo.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.io.IOException;
import java.math.BigInteger;
import java.util.Enumeration;
@@ -49,10 +48,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* Get detailed information about CA CRL processing
- *
+ *
* @version $Revision$, $Date$
*/
public class GetInfo extends CMSServlet {
@@ -76,6 +74,7 @@ public class GetInfo extends CMSServlet {
/**
* initialize the servlet.
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -90,11 +89,11 @@ public class GetInfo extends CMSServlet {
}
/**
- * XXX Process the HTTP request.
+ * XXX Process the HTTP request.
* <ul>
* <li>http.param template filename of template to use to render the result
* </ul>
- *
+ *
* @param cmsReq the object holding the request and response information
*/
public void process(CMSRequest cmsReq) throws EBaseException {
@@ -109,10 +108,10 @@ public class GetInfo extends CMSServlet {
mAuthzResourceName, "read");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -129,35 +128,30 @@ public class GetInfo extends CMSServlet {
String template = req.getParameter("template");
String formFile = "";
-/*
- for (int i = 0; ((template != null) && (i < template.length())); i++) {
- char c = template.charAt(i);
- if (!Character.isLetterOrDigit(c) && c != '_' && c != '-') {
- template = null;
- break;
- }
- }
-*/
-
+ /*
+ * for (int i = 0; ((template != null) && (i < template.length())); i++)
+ * { char c = template.charAt(i); if (!Character.isLetterOrDigit(c) && c
+ * != '_' && c != '-') { template = null; break; } }
+ */
if (template != null) {
formFile = template + ".template";
} else {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE_1"));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
CMSTemplate form = null;
Locale[] locale = new Locale[1];
-CMS.debug("*** formFile = "+formFile);
+ CMS.debug("*** formFile = " + formFile);
try {
form = getTemplate(formFile, req, locale);
} catch (IOException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", formFile, e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
try {
@@ -172,29 +166,29 @@ CMS.debug("*** formFile = "+formFile);
if (error == null) {
String xmlOutput = req.getParameter("xml");
if (xmlOutput != null && xmlOutput.equals("true")) {
- outputXML(resp, argSet);
+ outputXML(resp, argSet);
} else {
- resp.setContentType("text/html");
- form.renderOutput(out, argSet);
- cmsReq.setStatus(CMSRequest.SUCCESS);
+ resp.setContentType("text/html");
+ form.renderOutput(out, argSet);
+ cmsReq.setStatus(CMSRequest.SUCCESS);
}
} else {
cmsReq.setStatus(CMSRequest.ERROR);
cmsReq.setError(error);
}
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
}
private void process(CMSTemplateParams argSet, IArgBlock header,
- HttpServletRequest req,
- HttpServletResponse resp,
- Locale locale)
- throws EBaseException {
+ HttpServletRequest req,
+ HttpServletResponse resp,
+ Locale locale)
+ throws EBaseException {
if (mCA != null) {
String crlIssuingPoints = "";
String crlNumbers = "";
@@ -209,15 +203,15 @@ CMS.debug("*** formFile = "+formFile);
String masterHost = CMS.getConfigStore().getString("master.ca.agent.host", "");
String masterPort = CMS.getConfigStore().getString("master.ca.agent.port", "");
-
+
if (masterHost != null && masterHost.length() > 0 &&
- masterPort != null && masterPort.length() > 0) {
+ masterPort != null && masterPort.length() > 0) {
ICRLRepository crlRepository = mCA.getCRLRepository();
Vector ipNames = crlRepository.getIssuingPointsNames();
for (int i = 0; i < ipNames.size(); i++) {
- String ipName = (String)ipNames.elementAt(i);
+ String ipName = (String) ipNames.elementAt(i);
ICRLIssuingPointRecord crlRecord = null;
try {
crlRecord = crlRepository.readCRLIssuingPointRecord(ipName);
@@ -236,8 +230,8 @@ CMS.debug("*** formFile = "+formFile);
if (crlSizes.length() > 0)
crlSizes += "+";
- crlSizes += ((crlRecord.getCRLSize() != null)?
- crlRecord.getCRLSize().toString(): "-1");
+ crlSizes += ((crlRecord.getCRLSize() != null) ?
+ crlRecord.getCRLSize().toString() : "-1");
if (deltaSizes.length() > 0)
deltaSizes += "+";
@@ -307,7 +301,7 @@ CMS.debug("*** formFile = "+formFile);
recentChanges += "Publishing CRL #" + ip.getCRLNumber();
} else if (ip.isCRLUpdateInProgress() == ICRLIssuingPoint.CRL_UPDATE_STARTED) {
recentChanges += "Creating CRL #" + ip.getNextCRLNumber();
- } else { // ip.CRL_UPDATE_DONE
+ } else { // ip.CRL_UPDATE_DONE
recentChanges += ip.getNumberOfRecentlyRevokedCerts() + ", " +
ip.getNumberOfRecentlyUnrevokedCerts() + ", " +
ip.getNumberOfRecentlyExpiredCerts();
@@ -326,7 +320,7 @@ CMS.debug("*** formFile = "+formFile);
if (crlTesting.length() > 0)
crlTesting += "+";
- crlTesting += ((ip.isCRLCacheTestingEnabled())?"1":"0");
+ crlTesting += ((ip.isCRLCacheTestingEnabled()) ? "1" : "0");
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/HashEnrollServlet.java b/pki/base/common/src/com/netscape/cms/servlet/cert/HashEnrollServlet.java
index 5507cadf..58acbcfd 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/HashEnrollServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/HashEnrollServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -85,10 +84,9 @@ import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
import com.netscape.cms.servlet.common.ICMSTemplateFiller;
-
/**
* performs face-to-face enrollment.
- *
+ *
* @version $Revision$, $Date$
*/
public class HashEnrollServlet extends CMSServlet {
@@ -100,10 +98,9 @@ public class HashEnrollServlet extends CMSServlet {
public final static String ADMIN_ENROLL_SERVLET_ID = "adminEnroll";
// enrollment templates.
- public static final String
- ENROLL_SUCCESS_TEMPLATE = "/ra/HashEnrollSuccess.template";
+ public static final String ENROLL_SUCCESS_TEMPLATE = "/ra/HashEnrollSuccess.template";
- // http params
+ // http params
public static final String OLD_CERT_TYPE = "csrCertType";
public static final String CERT_TYPE = "certType";
// same as in ConfigConstant.java
@@ -123,8 +120,7 @@ public class HashEnrollServlet extends CMSServlet {
private boolean mAuthTokenOverride = true;
private String mEnrollSuccessTemplate = null;
- private ICMSTemplateFiller
- mEnrollSuccessFiller = new ImportCertsTemplateFiller();
+ private ICMSTemplateFiller mEnrollSuccessFiller = new ImportCertsTemplateFiller();
ICertificateAuthority mCa = null;
ICertificateRepository mRepository = null;
@@ -135,6 +131,7 @@ public class HashEnrollServlet extends CMSServlet {
/**
* initialize the servlet.
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -146,13 +143,13 @@ public class HashEnrollServlet extends CMSServlet {
CMSServlet.PROP_SUCCESS_TEMPLATE);
if (mEnrollSuccessTemplate == null)
mEnrollSuccessTemplate = ENROLL_SUCCESS_TEMPLATE;
- String fillername =
- sc.getInitParameter(PROP_SUCCESS_TEMPLATE_FILLER);
+ String fillername =
+ sc.getInitParameter(PROP_SUCCESS_TEMPLATE_FILLER);
if (fillername != null) {
ICMSTemplateFiller filler = newFillerObject(fillername);
- if (filler != null)
+ if (filler != null)
mEnrollSuccessFiller = filler;
}
@@ -161,20 +158,19 @@ public class HashEnrollServlet extends CMSServlet {
init_testbed_hack(mConfig);
} catch (Exception e) {
- // this should never happen.
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_IMP_INIT_SERV_ERR", e.toString(), mId));
+ // this should never happen.
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_IMP_INIT_SERV_ERR", e.toString(), mId));
}
}
-
/**
- * Process the HTTP request.
- *
+ * Process the HTTP request.
+ *
* @param cmsReq the object holding the request and response information
*/
- protected void process(CMSRequest cmsReq)
- throws EBaseException {
+ protected void process(CMSRequest cmsReq)
+ throws EBaseException {
IArgBlock httpParams = cmsReq.getHttpParams();
HttpServletRequest httpReq = cmsReq.getHttpReq();
HttpServletResponse httpResp = cmsReq.getHttpResp();
@@ -193,7 +189,7 @@ public class HashEnrollServlet extends CMSServlet {
IConfigStore configStore = CMS.getConfigStore();
String val = configStore.getString("hashDirEnrollment.name");
IAuthSubsystem authSS = (IAuthSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_AUTH);
+ CMS.getSubsystem(CMS.SUBSYSTEM_AUTH);
IAuthManager authMgr = authSS.get(val);
HashAuthentication mgr = (HashAuthentication) authMgr;
@@ -226,14 +222,15 @@ public class HashEnrollServlet extends CMSServlet {
certType = httpParams.getValueAsString(OLD_CERT_TYPE, null);
if (certType == null) {
certType = httpParams.getValueAsString(CERT_TYPE, "client");
- } else {;
- }
+ } else {
+ ;
+ }
- processX509(cmsReq);
+ processX509(cmsReq);
}
-
+
private void printError(CMSRequest cmsReq, String errorCode)
- throws EBaseException {
+ throws EBaseException {
IArgBlock httpParams = cmsReq.getHttpParams();
HttpServletRequest httpReq = cmsReq.getHttpReq();
HttpServletResponse httpResp = cmsReq.getHttpResp();
@@ -253,9 +250,9 @@ public class HashEnrollServlet extends CMSServlet {
form = getTemplate(formPath, httpReq, locale);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", formPath, e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", formPath, e.toString()));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
cmsReq.setStatus(CMSRequest.ERROR);
return;
}
@@ -267,16 +264,16 @@ public class HashEnrollServlet extends CMSServlet {
cmsReq.setStatus(CMSRequest.SUCCESS);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_BAD_SERV_OUT_STREAM",
- e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_BAD_SERV_OUT_STREAM",
+ e.toString()));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
cmsReq.setStatus(CMSRequest.ERROR);
}
}
- protected void processX509(CMSRequest cmsReq)
- throws EBaseException {
+ protected void processX509(CMSRequest cmsReq)
+ throws EBaseException {
IArgBlock httpParams = cmsReq.getHttpParams();
HttpServletRequest httpReq = cmsReq.getHttpReq();
@@ -284,19 +281,16 @@ public class HashEnrollServlet extends CMSServlet {
IRequest req = mRequestQueue.newRequest(IRequest.ENROLLMENT_REQUEST);
/*
- * === certAuth based enroll ===
- * "certAuthEnroll" is on.
- * "certauthEnrollType can be one of the three:
- * single - it's for single cert enrollment
- * dual - it's for dual certs enrollment
- * encryption - getting the encryption cert only via
- * authentication of the signing cert
- * (crmf or keyGenInfo)
+ * === certAuth based enroll === "certAuthEnroll" is on.
+ * "certauthEnrollType can be one of the three: single - it's for single
+ * cert enrollment dual - it's for dual certs enrollment encryption -
+ * getting the encryption cert only via authentication of the signing
+ * cert (crmf or keyGenInfo)
*/
boolean certAuthEnroll = false;
String certAuthEnrollOn =
- httpParams.getValueAsString("certauthEnroll", null);
+ httpParams.getValueAsString("certauthEnroll", null);
X509CertInfo new_certInfo = null;
if ((certAuthEnrollOn != null) && (certAuthEnrollOn.equals("on"))) {
@@ -307,7 +301,7 @@ public class HashEnrollServlet extends CMSServlet {
String certauthEnrollType = null;
if (certAuthEnroll == true) {
- certauthEnrollType =
+ certauthEnrollType =
httpParams.getValueAsString("certauthEnrollType", null);
if (certauthEnrollType != null) {
if (certauthEnrollType.equals("dual")) {
@@ -318,15 +312,15 @@ public class HashEnrollServlet extends CMSServlet {
CMS.debug("HashEnrollServlet: certauthEnrollType is single");
} else {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_INVALID_CERTAUTH_ENROLL_TYPE_1", certauthEnrollType));
+ CMS.getLogMessage("CMSGW_INVALID_CERTAUTH_ENROLL_TYPE_1", certauthEnrollType));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_INVALID_CERTAUTH_ENROLL_TYPE"));
+ CMS.getUserMessage("CMS_GW_INVALID_CERTAUTH_ENROLL_TYPE"));
}
} else {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_MISSING_CERTAUTH_ENROLL_TYPE"));
+ CMS.getLogMessage("CMSGW_MISSING_CERTAUTH_ENROLL_TYPE"));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_MISSING_CERTAUTH_ENROLL_TYPE"));
+ CMS.getUserMessage("CMS_GW_MISSING_CERTAUTH_ENROLL_TYPE"));
}
}
@@ -356,8 +350,8 @@ public class HashEnrollServlet extends CMSServlet {
String certBasedOldSubjectDN = null;
BigInteger certBasedOldSerialNum = null;
- // check if request was authenticated, if so set authtoken & certInfo.
- // also if authenticated, take certInfo from authToken.
+ // check if request was authenticated, if so set authtoken & certInfo.
+ // also if authenticated, take certInfo from authToken.
X509CertInfo certInfo = null;
if (certAuthEnroll == true) {
@@ -365,7 +359,7 @@ public class HashEnrollServlet extends CMSServlet {
if (sslClientCert == null) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_MISSING_SSL_CLIENT_CERT"));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_MISSING_SSL_CLIENT_CERT"));
+ CMS.getUserMessage("CMS_GW_MISSING_SSL_CLIENT_CERT"));
}
certBasedOldSubjectDN = (String) sslClientCert.getSubjectDN().toString();
@@ -373,24 +367,24 @@ public class HashEnrollServlet extends CMSServlet {
try {
certInfo = (X509CertInfo)
((X509CertImpl) sslClientCert).get(
- X509CertImpl.NAME + "." + X509CertImpl.INFO);
+ X509CertImpl.NAME + "." + X509CertImpl.INFO);
} catch (CertificateParsingException ex) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_MISSING_CERTINFO_ENCRYPT_CERT"));
+ CMS.getLogMessage("CMSGW_MISSING_CERTINFO_ENCRYPT_CERT"));
throw new ECMSGWException(
- CMS.getUserMessage(getLocale(httpReq), "CMS_GW_MISSING_CERTINFO"));
+ CMS.getUserMessage(getLocale(httpReq), "CMS_GW_MISSING_CERTINFO"));
}
} else {
certInfo = CMS.getDefaultX509CertInfo();
}
- X509CertInfo[] certInfoArray = new X509CertInfo[] {certInfo};
+ X509CertInfo[] certInfoArray = new X509CertInfo[] { certInfo };
- //AuthToken authToken = access.getAuthToken();
+ // AuthToken authToken = access.getAuthToken();
IConfigStore configStore = CMS.getConfigStore();
String val = configStore.getString("hashDirEnrollment.name");
IAuthSubsystem authSS = (IAuthSubsystem)
- CMS.getSubsystem(CMS.SUBSYSTEM_AUTH);
+ CMS.getSubsystem(CMS.SUBSYSTEM_AUTH);
IAuthManager authMgr1 = authSS.get(val);
HashAuthentication mgr = (HashAuthentication) authMgr1;
String pageID = httpParams.getValueAsString("pageID", null);
@@ -405,24 +399,24 @@ public class HashEnrollServlet extends CMSServlet {
cmsReq.setStatus(CMSRequest.SUCCESS);
return;
} else {
- authMgr =
+ authMgr =
authToken.getInString(AuthToken.TOKEN_AUTHMGR_INST_NAME);
- // don't store agent token in request.
- // agent currently used for bulk issuance.
+ // don't store agent token in request.
+ // agent currently used for bulk issuance.
// if (!authMgr.equals(IAuthSubsystem.CERTUSERDB_AUTHMGR_ID)) {
- log(ILogger.LL_INFO,
- "Enrollment request was authenticated by " +
- authToken.getInString(AuthToken.TOKEN_AUTHMGR_INST_NAME));
+ log(ILogger.LL_INFO,
+ "Enrollment request was authenticated by " +
+ authToken.getInString(AuthToken.TOKEN_AUTHMGR_INST_NAME));
fillCertInfoFromAuthToken(certInfo, authToken);
- // save authtoken attrs to request directly (for policy use)
+ // save authtoken attrs to request directly (for policy use)
saveAuthToken(authToken, req);
// req.set(IRequest.AUTH_TOKEN, authToken);
// }
}
// fill certInfo from input types: keygen, cmc, pkcs10 or crmf
- KeyGenInfo keyGenInfo =
- httpParams.getValueAsKeyGenInfo(SUBJECT_KEYGEN_INFO, null);
+ KeyGenInfo keyGenInfo =
+ httpParams.getValueAsKeyGenInfo(SUBJECT_KEYGEN_INFO, null);
String certType = null;
@@ -441,8 +435,8 @@ public class HashEnrollServlet extends CMSServlet {
req.setExtData(IRequest.HTTP_PARAMS, CERT_TYPE, certType);
}
- String crmf =
- httpParams.getValueAsString(CRMF_REQUEST, null);
+ String crmf =
+ httpParams.getValueAsString(CRMF_REQUEST, null);
if (certAuthEnroll == true) {
@@ -452,24 +446,24 @@ public class HashEnrollServlet extends CMSServlet {
if (certauthEnrollType.equals(CERT_AUTH_DUAL)) {
if (mCa == null) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_NOT_A_CA"));
+ CMS.getLogMessage("CMSGW_NOT_A_CA"));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_NOT_A_CA"));
+ CMS.getUserMessage("CMS_GW_NOT_A_CA"));
}
// first, make sure the client cert is indeed a
- // signing only cert
+ // signing only cert
if ((CMS.isSigningCert((X509CertImpl) sslClientCert) ==
false) ||
- ((CMS.isSigningCert((X509CertImpl) sslClientCert) ==
+ ((CMS.isSigningCert((X509CertImpl) sslClientCert) ==
true) &&
(CMS.isEncryptionCert((X509CertImpl) sslClientCert) ==
true))) {
// either it's not a signing cert, or it's a dual cert
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_INVALID_CERT_TYPE"));
+ CMS.getLogMessage("CMSGW_INVALID_CERT_TYPE"));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_INVALID_CERT_TYPE"));
+ CMS.getUserMessage("CMS_GW_INVALID_CERT_TYPE"));
}
X509Key key = null;
@@ -478,22 +472,22 @@ public class HashEnrollServlet extends CMSServlet {
try {
certInfo.set(X509CertInfo.KEY, new CertificateX509Key(key));
} catch (CertificateException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_FAILED_SET_KEY_FROM_CERT_AUTH_ENROLL_1", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_FAILED_SET_KEY_FROM_CERT_AUTH_ENROLL_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SET_KEY_FROM_CERT_AUTH_ENROLL_FAILED", e.toString()));
+ CMS.getUserMessage("CMS_GW_SET_KEY_FROM_CERT_AUTH_ENROLL_FAILED", e.toString()));
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_FAILED_SET_KEY_FROM_CERT_AUTH_ENROLL_1", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_FAILED_SET_KEY_FROM_CERT_AUTH_ENROLL_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SET_KEY_FROM_CERT_AUTH_ENROLL_FAILED", e.toString()));
+ CMS.getUserMessage("CMS_GW_SET_KEY_FROM_CERT_AUTH_ENROLL_FAILED", e.toString()));
}
String filter =
- "(&(x509cert.subject=" + certBasedOldSubjectDN + ")(!(x509cert.serialNumber=" + certBasedOldSerialNum + "))(certStatus=VALID))";
- ICertRecordList list =
- (ICertRecordList) mCa.getCertificateRepository().findCertRecordsInList(filter,
- null, 10);
+ "(&(x509cert.subject=" + certBasedOldSubjectDN + ")(!(x509cert.serialNumber=" + certBasedOldSerialNum + "))(certStatus=VALID))";
+ ICertRecordList list =
+ (ICertRecordList) mCa.getCertificateRepository().findCertRecordsInList(filter,
+ null, 10);
int size = list.getSize();
Enumeration<ICertRecord> en = list.getCertRecords(0, size - 1);
boolean gotEncCert = false;
@@ -502,8 +496,8 @@ public class HashEnrollServlet extends CMSServlet {
// pairing encryption cert not found
} else {
X509CertInfo encCertInfo = CMS.getDefaultX509CertInfo();
- X509CertInfo[] cInfoArray = new X509CertInfo[] {certInfo,
- encCertInfo};
+ X509CertInfo[] cInfoArray = new X509CertInfo[] { certInfo,
+ encCertInfo };
int i = 1;
while (en.hasMoreElements()) {
@@ -512,7 +506,7 @@ public class HashEnrollServlet extends CMSServlet {
// if not encryption cert only, try next one
if ((CMS.isEncryptionCert(cert) == false) ||
- ((CMS.isEncryptionCert(cert) == true) &&
+ ((CMS.isEncryptionCert(cert) == true) &&
(CMS.isSigningCert(cert) == true))) {
continue;
}
@@ -521,27 +515,27 @@ public class HashEnrollServlet extends CMSServlet {
try {
encCertInfo = (X509CertInfo)
cert.get(
- X509CertImpl.NAME + "." + X509CertImpl.INFO);
+ X509CertImpl.NAME + "." + X509CertImpl.INFO);
} catch (CertificateParsingException ex) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_MISSING_CERTINFO_ENCRYPT_CERT"));
+ CMS.getLogMessage("CMSGW_MISSING_CERTINFO_ENCRYPT_CERT"));
throw new ECMSGWException(
- CMS.getUserMessage(getLocale(httpReq), "CMS_GW_MISSING_CERTINFO"));
+ CMS.getUserMessage(getLocale(httpReq), "CMS_GW_MISSING_CERTINFO"));
}
try {
encCertInfo.set(X509CertInfo.KEY, new CertificateX509Key(key));
} catch (CertificateException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_FAILED_SET_KEY_FROM_CERT_AUTH_ENROLL_1", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_FAILED_SET_KEY_FROM_CERT_AUTH_ENROLL_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SET_KEY_FROM_CERT_AUTH_ENROLL_FAILED", e.toString()));
+ CMS.getUserMessage("CMS_GW_SET_KEY_FROM_CERT_AUTH_ENROLL_FAILED", e.toString()));
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_FAILED_SET_KEY_FROM_CERT_AUTH_ENROLL_1", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_FAILED_SET_KEY_FROM_CERT_AUTH_ENROLL_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SET_KEY_FROM_CERT_AUTH_ENROLL_FAILED", e.toString()));
+ CMS.getUserMessage("CMS_GW_SET_KEY_FROM_CERT_AUTH_ENROLL_FAILED", e.toString()));
}
fillCertInfoFromAuthToken(encCertInfo, authToken);
@@ -555,24 +549,24 @@ public class HashEnrollServlet extends CMSServlet {
if (gotEncCert == false) {
// encryption cert not found, bail
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ENCRYPTION_CERT_NOT_FOUND"));
+ CMS.getLogMessage("CMSGW_ENCRYPTION_CERT_NOT_FOUND"));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_ENCRYPTION_CERT_NOT_FOUND"));
+ CMS.getUserMessage("CMS_GW_ENCRYPTION_CERT_NOT_FOUND"));
}
} else if (certauthEnrollType.equals(CERT_AUTH_ENCRYPTION)) {
// first, make sure the client cert is indeed a
- // signing only cert
+ // signing only cert
if ((CMS.isSigningCert((X509CertImpl) sslClientCert) ==
false) ||
- ((CMS.isSigningCert((X509CertImpl) sslClientCert) ==
+ ((CMS.isSigningCert((X509CertImpl) sslClientCert) ==
true) &&
(CMS.isEncryptionCert((X509CertImpl) sslClientCert) ==
true))) {
// either it's not a signing cert, or it's a dual cert
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_INVALID_CERT_TYPE"));
+ CMS.getLogMessage("CMSGW_INVALID_CERT_TYPE"));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_INVALID_CERT_TYPE"));
+ CMS.getUserMessage("CMS_GW_INVALID_CERT_TYPE"));
}
/*
@@ -581,14 +575,14 @@ public class HashEnrollServlet extends CMSServlet {
if (crmf != null && crmf != "") {
certInfoArray = fillCRMF(crmf, authToken, httpParams, req);
req.setExtData(CLIENT_ISSUER,
- sslClientCert.getIssuerDN().toString());
+ sslClientCert.getIssuerDN().toString());
CMS.debug(
- "HashEnrollServlet: sslClientCert issuerDN = " + sslClientCert.getIssuerDN().toString());
+ "HashEnrollServlet: sslClientCert issuerDN = " + sslClientCert.getIssuerDN().toString());
} else {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_MISSING_KEYGEN_INFO"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_MISSING_KEYGEN_INFO"));
throw new ECMSGWException(CMS.getUserMessage(getLocale(httpReq),
- "CMS_GW_MISSING_KEYGEN_INFO"));
+ "CMS_GW_MISSING_KEYGEN_INFO"));
}
} else if (certauthEnrollType.equals(CERT_AUTH_SINGLE)) {
// have to be buried here to handle the issuer
@@ -596,21 +590,21 @@ public class HashEnrollServlet extends CMSServlet {
if (crmf != null && crmf != "") {
certInfoArray = fillCRMF(crmf, authToken, httpParams, req);
} else {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_MISSING_KEYGEN_INFO"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_MISSING_KEYGEN_INFO"));
throw new ECMSGWException(CMS.getUserMessage(getLocale(httpReq),
- "CMS_GW_MISSING_KEYGEN_INFO"));
+ "CMS_GW_MISSING_KEYGEN_INFO"));
}
req.setExtData(CLIENT_ISSUER,
- sslClientCert.getIssuerDN().toString());
+ sslClientCert.getIssuerDN().toString());
}
} else if (crmf != null && crmf != "") {
certInfoArray = fillCRMF(crmf, authToken, httpParams, req);
} else {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_MISSING_KEYGEN_INFO"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_MISSING_KEYGEN_INFO"));
throw new ECMSGWException(CMS.getUserMessage(getLocale(httpReq),
- "CMS_GW_MISSING_KEYGEN_INFO"));
+ "CMS_GW_MISSING_KEYGEN_INFO"));
}
req.setExtData(IRequest.CERT_INFO, certInfoArray);
@@ -621,9 +615,9 @@ public class HashEnrollServlet extends CMSServlet {
req.setExtData(CHALLENGE_PASSWORD, pwd);
}
- // send request to request queue.
+ // send request to request queue.
mRequestQueue.processRequest(req);
- // process result.
+ // process result.
// render OLD_CERT_TYPE's response differently, we
// dont want any javascript in HTML, and need to
@@ -638,24 +632,24 @@ public class HashEnrollServlet extends CMSServlet {
return;
}
- //for audit log
+ // for audit log
String initiative = null;
String agentID = null;
if (!authMgr.equals(IAuthSubsystem.CERTUSERDB_AUTHMGR_ID)) {
- // request is from eegateway, so fromUser.
+ // request is from eegateway, so fromUser.
initiative = AuditFormat.FROMUSER;
} else {
agentID = authToken.getInString("userid");
initiative = AuditFormat.FROMAGENT + " agentID: " + agentID;
- }
+ }
// if service not complete return standard templates.
RequestStatus status = req.getRequestStatus();
if (status != RequestStatus.COMPLETE) {
cmsReq.setIRequestStatus(); // set status acc. to IRequest status.
- // audit log the status
+ // audit log the status
try {
if (status == RequestStatus.REJECTED) {
Vector<String> messages = req.getExtDataInStringVector(IRequest.ERRORS);
@@ -668,52 +662,52 @@ public class HashEnrollServlet extends CMSServlet {
wholeMsg.append("\n");
wholeMsg.append(msgs.nextElement());
}
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.ENROLLMENTFORMAT,
- new Object[] {
- req.getRequestId(),
- initiative,
- authMgr,
- status.toString(),
- certInfo.get(X509CertInfo.SUBJECT),
- " violation: " +
- wholeMsg.toString()},
- ILogger.L_MULTILINE
- );
+ mLogger.log(ILogger.EV_AUDIT,
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.ENROLLMENTFORMAT,
+ new Object[] {
+ req.getRequestId(),
+ initiative,
+ authMgr,
+ status.toString(),
+ certInfo.get(X509CertInfo.SUBJECT),
+ " violation: " +
+ wholeMsg.toString() },
+ ILogger.L_MULTILINE
+ );
} else { // no policy violation, from agent
mLogger.log(ILogger.EV_AUDIT,
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.ENROLLMENTFORMAT,
+ new Object[] {
+ req.getRequestId(),
+ initiative,
+ authMgr,
+ status.toString(),
+ certInfo.get(X509CertInfo.SUBJECT), "" }
+ );
+ }
+ } else { // other imcomplete status
+ mLogger.log(ILogger.EV_AUDIT,
ILogger.S_OTHER,
AuditFormat.LEVEL,
AuditFormat.ENROLLMENTFORMAT,
new Object[] {
- req.getRequestId(),
- initiative,
- authMgr,
- status.toString(),
- certInfo.get(X509CertInfo.SUBJECT), ""}
- );
- }
- } else { // other imcomplete status
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.ENROLLMENTFORMAT,
- new Object[] {
- req.getRequestId(),
- initiative,
- authMgr,
- status.toString(),
- certInfo.get(X509CertInfo.SUBJECT), ""}
- );
+ req.getRequestId(),
+ initiative,
+ authMgr,
+ status.toString(),
+ certInfo.get(X509CertInfo.SUBJECT), "" }
+ );
}
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_CANT_GET_CERT_SUBJ_AUDITING", e.toString()));
+ CMS.getLogMessage("CMSGW_CANT_GET_CERT_SUBJ_AUDITING", e.toString()));
} catch (CertificateException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_CANT_GET_CERT_SUBJ_AUDITING", e.toString()));
+ CMS.getLogMessage("CMSGW_CANT_GET_CERT_SUBJ_AUDITING", e.toString()));
}
return;
}
@@ -725,39 +719,39 @@ public class HashEnrollServlet extends CMSServlet {
cmsReq.setStatus(CMSRequest.ERROR);
cmsReq.setError(req.getExtDataInString(IRequest.ERROR));
String[] svcErrors =
- req.getExtDataInStringArray(IRequest.SVCERRORS);
+ req.getExtDataInStringArray(IRequest.SVCERRORS);
if (svcErrors != null && svcErrors.length > 0) {
for (int i = 0; i < svcErrors.length; i++) {
String err = svcErrors[i];
if (err != null) {
- //System.out.println(
- //"revocation servlet: setting error description "+
- //err.toString());
+ // System.out.println(
+ // "revocation servlet: setting error description "+
+ // err.toString());
cmsReq.setErrorDescription(err);
// audit log the error
try {
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.ENROLLMENTFORMAT,
- new Object[] {
- req.getRequestId(),
- initiative,
- authMgr,
- "completed with error: " +
- err,
- certInfo.get(X509CertInfo.SUBJECT), ""}
- );
+ mLogger.log(ILogger.EV_AUDIT,
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.ENROLLMENTFORMAT,
+ new Object[] {
+ req.getRequestId(),
+ initiative,
+ authMgr,
+ "completed with error: " +
+ err,
+ certInfo.get(X509CertInfo.SUBJECT), "" }
+ );
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_CANT_GET_CERT_SUBJ_AUDITING",
- e.toString()));
+ CMS.getLogMessage("CMSGW_CANT_GET_CERT_SUBJ_AUDITING",
+ e.toString()));
} catch (CertificateException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_CANT_GET_CERT_SUBJ_AUDITING",
- e.toString()));
+ CMS.getLogMessage("CMSGW_CANT_GET_CERT_SUBJ_AUDITING",
+ e.toString()));
}
}
}
@@ -768,143 +762,143 @@ public class HashEnrollServlet extends CMSServlet {
// service success
cmsReq.setStatus(CMSRequest.SUCCESS);
X509CertImpl[] issuedCerts =
- req.getExtDataInCertArray(IRequest.ISSUED_CERTS);
+ req.getExtDataInCertArray(IRequest.ISSUED_CERTS);
// audit log the success.
- mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.ENROLLMENTFORMAT,
- new Object[] {
- req.getRequestId(),
- initiative,
- authMgr,
- "completed",
- issuedCerts[0].getSubjectDN(),
- "cert issued serial number: 0x" +
- issuedCerts[0].getSerialNumber().toString(16)}
- );
+ mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.ENROLLMENTFORMAT,
+ new Object[] {
+ req.getRequestId(),
+ initiative,
+ authMgr,
+ "completed",
+ issuedCerts[0].getSubjectDN(),
+ "cert issued serial number: 0x" +
+ issuedCerts[0].getSerialNumber().toString(16) }
+ );
// return cert as mime type binary if requested.
if (checkImportCertToNav(
- cmsReq.getHttpResp(), httpParams, issuedCerts[0])) {
+ cmsReq.getHttpResp(), httpParams, issuedCerts[0])) {
cmsReq.setStatus(CMSRequest.SUCCESS);
return;
}
-
+
// use success template.
try {
- cmsReq.setResult(issuedCerts);
- renderTemplate(cmsReq, mEnrollSuccessTemplate,
- mEnrollSuccessFiller);
- cmsReq.setStatus(CMSRequest.SUCCESS);
+ cmsReq.setResult(issuedCerts);
+ renderTemplate(cmsReq, mEnrollSuccessTemplate,
+ mEnrollSuccessFiller);
+ cmsReq.setStatus(CMSRequest.SUCCESS);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_TEMP_REND_ERR", mEnrollSuccessFiller.toString(), e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_TEMP_REND_ERR", mEnrollSuccessFiller.toString(), e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_RETURNING_RESULT_ERROR"));
+ CMS.getUserMessage("CMS_GW_RETURNING_RESULT_ERROR"));
}
return;
}
/**
- * fill subject name, validity, extensions from authoken if any,
- * overriding what was in pkcs10.
- * fill subject name, extensions from http input if not authenticated.
- * requests not authenticated will need to be approved by an agent.
+ * fill subject name, validity, extensions from authoken if any, overriding
+ * what was in pkcs10. fill subject name, extensions from http input if not
+ * authenticated. requests not authenticated will need to be approved by an
+ * agent.
*/
protected void fillCertInfoFromAuthToken(
- X509CertInfo certInfo, IAuthToken authToken)
- throws EBaseException {
+ X509CertInfo certInfo, IAuthToken authToken)
+ throws EBaseException {
// override subject, validity and extensions from auth token
// CA determines algorithm, version and issuer.
- // take key from keygen, cmc, pkcs10 or crmf.
+ // take key from keygen, cmc, pkcs10 or crmf.
// subject name.
try {
String subjectname =
- authToken.getInString(AuthToken.TOKEN_CERT_SUBJECT);
+ authToken.getInString(AuthToken.TOKEN_CERT_SUBJECT);
if (subjectname != null) {
CertificateSubjectName certSubject = (CertificateSubjectName)
- new CertificateSubjectName(new X500Name(subjectname));
+ new CertificateSubjectName(new X500Name(subjectname));
certInfo.set(X509CertInfo.SUBJECT, certSubject);
- log(ILogger.LL_INFO,
- "cert subject set to " + certSubject + " from authtoken");
+ log(ILogger.LL_INFO,
+ "cert subject set to " + certSubject + " from authtoken");
}
} catch (CertificateException e) {
- log(ILogger.LL_WARN,
- CMS.getLogMessage("CMSGW_ERROR_SET_SUBJECT_NAME_1", e.toString()));
+ log(ILogger.LL_WARN,
+ CMS.getLogMessage("CMSGW_ERROR_SET_SUBJECT_NAME_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SET_SUBJECT_NAME_ERROR"));
+ CMS.getUserMessage("CMS_GW_SET_SUBJECT_NAME_ERROR"));
} catch (IOException e) {
- log(ILogger.LL_WARN,
- CMS.getLogMessage("CMSGW_ERROR_SET_SUBJECT_NAME_1",
- e.toString()));
+ log(ILogger.LL_WARN,
+ CMS.getLogMessage("CMSGW_ERROR_SET_SUBJECT_NAME_1",
+ e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SET_SUBJECT_NAME_ERROR"));
+ CMS.getUserMessage("CMS_GW_SET_SUBJECT_NAME_ERROR"));
}
// validity
try {
CertificateValidity validity = null;
- Date notBefore =
- authToken.getInDate(AuthToken.TOKEN_CERT_NOTBEFORE);
- Date notAfter =
- authToken.getInDate(AuthToken.TOKEN_CERT_NOTAFTER);
+ Date notBefore =
+ authToken.getInDate(AuthToken.TOKEN_CERT_NOTBEFORE);
+ Date notAfter =
+ authToken.getInDate(AuthToken.TOKEN_CERT_NOTAFTER);
if (notBefore != null && notAfter != null) {
validity = new CertificateValidity(notBefore, notAfter);
certInfo.set(X509CertInfo.VALIDITY, validity);
- log(ILogger.LL_INFO,
- "cert validity set to " + validity + " from authtoken");
+ log(ILogger.LL_INFO,
+ "cert validity set to " + validity + " from authtoken");
}
} catch (CertificateException e) {
- log(ILogger.LL_WARN,
- CMS.getLogMessage("CMSGW_ERROR_SET_VALIDITY_1",
- e.toString()));
+ log(ILogger.LL_WARN,
+ CMS.getLogMessage("CMSGW_ERROR_SET_VALIDITY_1",
+ e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SET_VALIDITY_ERROR"));
+ CMS.getUserMessage("CMS_GW_SET_VALIDITY_ERROR"));
} catch (IOException e) {
- log(ILogger.LL_WARN,
- CMS.getLogMessage("CMSGW_ERROR_SET_VALIDITY_1", e.toString()));
+ log(ILogger.LL_WARN,
+ CMS.getLogMessage("CMSGW_ERROR_SET_VALIDITY_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SET_VALIDITY_ERROR"));
+ CMS.getUserMessage("CMS_GW_SET_VALIDITY_ERROR"));
}
-
+
// extensions
try {
CertificateExtensions extensions =
- authToken.getInCertExts(X509CertInfo.EXTENSIONS);
+ authToken.getInCertExts(X509CertInfo.EXTENSIONS);
if (extensions != null) {
certInfo.set(X509CertInfo.EXTENSIONS, extensions);
log(ILogger.LL_INFO, "cert extensions set from authtoken");
}
} catch (CertificateException e) {
- log(ILogger.LL_WARN,
- CMS.getLogMessage("CMSGW_ERROR_SET_EXTENSIONS_1", e.toString()));
+ log(ILogger.LL_WARN,
+ CMS.getLogMessage("CMSGW_ERROR_SET_EXTENSIONS_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SET_EXTENSIONS_ERROR"));
+ CMS.getUserMessage("CMS_GW_SET_EXTENSIONS_ERROR"));
} catch (IOException e) {
- log(ILogger.LL_WARN,
- CMS.getLogMessage("CMSGW_ERROR_SET_EXTENSIONS_1",
- e.toString()));
+ log(ILogger.LL_WARN,
+ CMS.getLogMessage("CMSGW_ERROR_SET_EXTENSIONS_1",
+ e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SET_EXTENSIONS_ERROR"));
+ CMS.getUserMessage("CMS_GW_SET_EXTENSIONS_ERROR"));
}
}
protected X509CertInfo[] fillCRMF(
- String crmf, IAuthToken authToken, IArgBlock httpParams, IRequest req)
- throws EBaseException {
+ String crmf, IAuthToken authToken, IArgBlock httpParams, IRequest req)
+ throws EBaseException {
try {
byte[] crmfBlob = CMS.AtoB(crmf);
ByteArrayInputStream crmfBlobIn =
- new ByteArrayInputStream(crmfBlob);
-
+ new ByteArrayInputStream(crmfBlob);
+
SEQUENCE crmfMsgs = (SEQUENCE)
- new SEQUENCE.OF_Template(new CertReqMsg.Template()).decode(crmfBlobIn);
+ new SEQUENCE.OF_Template(new CertReqMsg.Template()).decode(crmfBlobIn);
int nummsgs = crmfMsgs.size();
X509CertInfo[] certInfoArray = new X509CertInfo[nummsgs];
@@ -914,17 +908,11 @@ public class HashEnrollServlet extends CMSServlet {
CertReqMsg certReqMsg = (CertReqMsg) crmfMsgs.elementAt(i);
/*
- if (certReqMsg.hasPop()) {
- try {
- certReqMsg.verify();
- } catch (ChallengeResponseException ex) {
- // create and save the challenge
- // construct the cmmf message together
- // in a sequence to challenge the requestor
- } catch (Exception e) {
- // failed, should only affect one request
- }
- }
+ * if (certReqMsg.hasPop()) { try { certReqMsg.verify(); } catch
+ * (ChallengeResponseException ex) { // create and save the
+ * challenge // construct the cmmf message together // in a
+ * sequence to challenge the requestor } catch (Exception e) {
+ * // failed, should only affect one request } }
*/
CertRequest certReq = certReqMsg.getCertReq();
INTEGER certReqId = certReq.getCertReqId();
@@ -951,92 +939,92 @@ public class HashEnrollServlet extends CMSServlet {
if (certTemplate.getNotBefore() != null || certTemplate.getNotAfter() != null) {
CertificateValidity certValidity = new CertificateValidity(certTemplate.getNotBefore(), certTemplate.getNotAfter());
- certInfo.set(X509CertInfo.VALIDITY, certValidity);
+ certInfo.set(X509CertInfo.VALIDITY, certValidity);
}
if (certTemplate.hasSubject()) {
Name subjectdn = certTemplate.getSubject();
- ByteArrayOutputStream subjectEncStream =
- new ByteArrayOutputStream();
+ ByteArrayOutputStream subjectEncStream =
+ new ByteArrayOutputStream();
subjectdn.encode(subjectEncStream);
byte[] subjectEnc = subjectEncStream.toByteArray();
X500Name subject = new X500Name(subjectEnc);
- certInfo.set(X509CertInfo.SUBJECT,
- new CertificateSubjectName(subject));
- } else if (authToken == null ||
- authToken.getInString(AuthToken.TOKEN_CERT_SUBJECT) == null) {
- // No subject name - error!
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_MISSING_SUBJECT_NAME_FROM_AUTHTOKEN"));
+ certInfo.set(X509CertInfo.SUBJECT,
+ new CertificateSubjectName(subject));
+ } else if (authToken == null ||
+ authToken.getInString(AuthToken.TOKEN_CERT_SUBJECT) == null) {
+ // No subject name - error!
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_MISSING_SUBJECT_NAME_FROM_AUTHTOKEN"));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_MISSING_SUBJECT_NAME_FROM_AUTHTOKEN"));
+ CMS.getUserMessage("CMS_GW_MISSING_SUBJECT_NAME_FROM_AUTHTOKEN"));
}
- // get extensions
+ // get extensions
CertificateExtensions extensions = null;
try {
extensions = (CertificateExtensions)
- certInfo.get(X509CertInfo.EXTENSIONS);
+ certInfo.get(X509CertInfo.EXTENSIONS);
} catch (CertificateException e) {
extensions = null;
} catch (IOException e) {
extensions = null;
}
if (certTemplate.hasExtensions()) {
- // put each extension from CRMF into CertInfo.
- // index by extension name, consistent with
+ // put each extension from CRMF into CertInfo.
+ // index by extension name, consistent with
// CertificateExtensions.parseExtension() method.
- if (extensions == null)
+ if (extensions == null)
extensions = new CertificateExtensions();
int numexts = certTemplate.numExtensions();
for (int j = 0; j < numexts; j++) {
- org.mozilla.jss.pkix.cert.Extension jssext =
- certTemplate.extensionAt(j);
+ org.mozilla.jss.pkix.cert.Extension jssext =
+ certTemplate.extensionAt(j);
boolean isCritical = jssext.getCritical();
- org.mozilla.jss.asn1.OBJECT_IDENTIFIER jssoid =
- jssext.getExtnId();
+ org.mozilla.jss.asn1.OBJECT_IDENTIFIER jssoid =
+ jssext.getExtnId();
long[] numbers = jssoid.getNumbers();
int[] oidNumbers = new int[numbers.length];
for (int k = numbers.length - 1; k >= 0; k--) {
oidNumbers[k] = (int) numbers[k];
}
- ObjectIdentifier oid =
- new ObjectIdentifier(oidNumbers);
- org.mozilla.jss.asn1.OCTET_STRING jssvalue =
- jssext.getExtnValue();
- ByteArrayOutputStream jssvalueout =
- new ByteArrayOutputStream();
+ ObjectIdentifier oid =
+ new ObjectIdentifier(oidNumbers);
+ org.mozilla.jss.asn1.OCTET_STRING jssvalue =
+ jssext.getExtnValue();
+ ByteArrayOutputStream jssvalueout =
+ new ByteArrayOutputStream();
jssvalue.encode(jssvalueout);
byte[] extValue = jssvalueout.toByteArray();
- Extension ext =
- new Extension(oid, isCritical, extValue);
+ Extension ext =
+ new Extension(oid, isCritical, extValue);
extensions.parseExtension(ext);
}
- certInfo.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ certInfo.set(X509CertInfo.VERSION,
+ new CertificateVersion(CertificateVersion.V3));
certInfo.set(X509CertInfo.EXTENSIONS, extensions);
}
- // Added a new configuration parameter
+ // Added a new configuration parameter
// eeGateway.Enrollment.authTokenOverride=[true|false]
// By default, it is set to true. In most
// of the case, administrator would want
// to have the control of the subject name
// formulation.
// -- CRMFfillCert
- if (authToken != null &&
- authToken.getInString(AuthToken.TOKEN_CERT_SUBJECT) != null) {
- // if authenticated override subect name, validity and
+ if (authToken != null &&
+ authToken.getInString(AuthToken.TOKEN_CERT_SUBJECT) != null) {
+ // if authenticated override subect name, validity and
// extensions if any from authtoken.
fillCertInfoFromAuthToken(certInfo, authToken);
}
@@ -1048,27 +1036,27 @@ public class HashEnrollServlet extends CMSServlet {
return certInfoArray;
} catch (CertificateException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_CRMF_TO_CERTINFO_1", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERROR_CRMF_TO_CERTINFO_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_CRMF_TO_CERTINFO_ERROR"));
+ CMS.getUserMessage("CMS_GW_CRMF_TO_CERTINFO_ERROR"));
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_CRMF_TO_CERTINFO_1",
- e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERROR_CRMF_TO_CERTINFO_1",
+ e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_CRMF_TO_CERTINFO_ERROR"));
+ CMS.getUserMessage("CMS_GW_CRMF_TO_CERTINFO_ERROR"));
} catch (InvalidBERException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_CRMF_TO_CERTINFO_1", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERROR_CRMF_TO_CERTINFO_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_CRMF_TO_CERTINFO_ERROR"));
+ CMS.getUserMessage("CMS_GW_CRMF_TO_CERTINFO_ERROR"));
} catch (InvalidKeyException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_CRMF_TO_CERTINFO_1",
- e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERROR_CRMF_TO_CERTINFO_1",
+ e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_CRMF_TO_CERTINFO_ERROR"));
+ CMS.getUserMessage("CMS_GW_CRMF_TO_CERTINFO_ERROR"));
}
}
@@ -1092,7 +1080,11 @@ public class HashEnrollServlet extends CMSServlet {
out.println("<H1>");
out.println("SUCCESS");
out.println("</H1>");
- out.println("Your request is submitted and approved. Please cut and paste the certificate into your server."); // XXX - localize the message
+ out.println("Your request is submitted and approved. Please cut and paste the certificate into your server."); // XXX
+ // -
+ // localize
+ // the
+ // message
out.println("<P>");
out.println("Request Creation Time: ");
out.println(cmsReq.getIRequest().getCreationTime().toString());
@@ -1107,24 +1099,28 @@ public class HashEnrollServlet extends CMSServlet {
out.println("<P>");
out.println("<PRE>");
X509CertImpl certs[] =
- cmsReq.getIRequest().getExtDataInCertArray(IRequest.ISSUED_CERTS);
+ cmsReq.getIRequest().getExtDataInCertArray(IRequest.ISSUED_CERTS);
out.println(CMS.getEncodedCert(certs[0]));
out.println("</PRE>");
out.println("<P>");
out.println("<!HTTP_OUTPUT REQUEST_CREATION_TIME=" +
- cmsReq.getIRequest().getCreationTime().toString() + ">");
- out.println("<!HTTP_OUTPUT REQUEST_STATUS=" +
- cmsReq.getStatus().toString() + ">");
- out.println("<!HTTP_OUTPUT REQUEST_ID=" +
- cmsReq.getIRequest().getRequestId().toString() + ">");
+ cmsReq.getIRequest().getCreationTime().toString() + ">");
+ out.println("<!HTTP_OUTPUT REQUEST_STATUS=" +
+ cmsReq.getStatus().toString() + ">");
+ out.println("<!HTTP_OUTPUT REQUEST_ID=" +
+ cmsReq.getIRequest().getRequestId().toString() + ">");
out.println("<!HTTP_OUTPUT X509_CERTIFICATE=" +
- CMS.getEncodedCert(certs[0]) + ">");
+ CMS.getEncodedCert(certs[0]) + ">");
} else if (cmsReq.getIRequest().getRequestStatus().equals(RequestStatus.PENDING)) {
out.println("<H1>");
out.println("PENDING");
out.println("</H1>");
- out.println("Your request is submitted. You can check on the status of your request with an authorized agent or local administrator by referring to the request ID."); // XXX - localize the message
+ out.println("Your request is submitted. You can check on the status of your request with an authorized agent or local administrator by referring to the request ID."); // XXX
+ // -
+ // localize
+ // the
+ // message
out.println("<P>");
out.println("Request Creation Time: ");
out.println(cmsReq.getIRequest().getCreationTime().toString());
@@ -1136,17 +1132,21 @@ public class HashEnrollServlet extends CMSServlet {
out.println(cmsReq.getIRequest().getRequestId().toString());
out.println("<P>");
out.println("<!HTTP_OUTPUT REQUEST_CREATION_TIME=" +
- cmsReq.getIRequest().getCreationTime().toString() + ">");
- out.println("<!HTTP_OUTPUT REQUEST_STATUS=" +
- cmsReq.getStatus().toString() + ">");
- out.println("<!HTTP_OUTPUT REQUEST_ID=" +
- cmsReq.getIRequest().getRequestId().toString() + ">");
+ cmsReq.getIRequest().getCreationTime().toString() + ">");
+ out.println("<!HTTP_OUTPUT REQUEST_STATUS=" +
+ cmsReq.getStatus().toString() + ">");
+ out.println("<!HTTP_OUTPUT REQUEST_ID=" +
+ cmsReq.getIRequest().getRequestId().toString() + ">");
} else {
out.println("<H1>");
out.println("ERROR");
out.println("</H1>");
out.println("<!INFO>");
- out.println("Please consult your local administrator for assistance."); // XXX - localize the message
+ out.println("Please consult your local administrator for assistance."); // XXX
+ // -
+ // localize
+ // the
+ // message
out.println("<!/INFO>");
out.println("<P>");
out.println("Request Status: ");
@@ -1155,62 +1155,58 @@ public class HashEnrollServlet extends CMSServlet {
out.println("Error: ");
out.println(cmsReq.getError()); // XXX - need to parse in Locale
out.println("<P>");
- out.println("<!HTTP_OUTPUT REQUEST_STATUS=" +
- cmsReq.getStatus().toString() + ">");
- out.println("<!HTTP_OUTPUT ERROR=" +
- cmsReq.getError() + ">");
+ out.println("<!HTTP_OUTPUT REQUEST_STATUS=" +
+ cmsReq.getStatus().toString() + ">");
+ out.println("<!HTTP_OUTPUT ERROR=" +
+ cmsReq.getError() + ">");
}
/**
- // include all the input data
- IArgBlock args = cmsReq.getHttpParams();
- Enumeration ele = args.getElements();
- while (ele.hasMoreElements()) {
- String eleT = (String)ele.nextElement();
- out.println("<!HTTP_INPUT " + eleT + "=" +
- args.get(eleT) + ">");
- }
+ * // include all the input data IArgBlock args =
+ * cmsReq.getHttpParams(); Enumeration ele = args.getElements(); while
+ * (ele.hasMoreElements()) { String eleT = (String)ele.nextElement();
+ * out.println("<!HTTP_INPUT " + eleT + "=" + args.get(eleT) + ">"); }
**/
out.println("</HTML>");
}
- // XXX ALERT !!
- // Remove the following and calls to them when we bundle a cartman
- // later than alpha1.
- // These are here to cover up problem in cartman where the
- // key usage extension always ends up being digital signature only
+ // XXX ALERT !!
+ // Remove the following and calls to them when we bundle a cartman
+ // later than alpha1.
+ // These are here to cover up problem in cartman where the
+ // key usage extension always ends up being digital signature only
// and for rsa-ex ends up having no bits set.
private boolean mIsTestBed = false;
- private void init_testbed_hack(IConfigStore config)
- throws EBaseException {
+ private void init_testbed_hack(IConfigStore config)
+ throws EBaseException {
mIsTestBed = config.getBoolean("isTestBed", true);
}
private void do_testbed_hack(
- int nummsgs, X509CertInfo[] certinfo, IArgBlock httpParams)
- throws EBaseException {
- if (!mIsTestBed)
+ int nummsgs, X509CertInfo[] certinfo, IArgBlock httpParams)
+ throws EBaseException {
+ if (!mIsTestBed)
return;
- // get around bug in cartman - bits are off by one byte.
+ // get around bug in cartman - bits are off by one byte.
for (int i = 0; i < certinfo.length; i++) {
try {
X509CertInfo cert = certinfo[i];
CertificateExtensions exts = (CertificateExtensions)
- cert.get(CertificateExtensions.NAME);
+ cert.get(CertificateExtensions.NAME);
if (exts == null) {
// should not happen.
continue;
}
KeyUsageExtension ext = (KeyUsageExtension)
- exts.get(KeyUsageExtension.class.getSimpleName());
+ exts.get(KeyUsageExtension.class.getSimpleName());
- if (ext == null)
- // should not happen
+ if (ext == null)
+ // should not happen
continue;
byte[] value = ext.getExtensionValue();
@@ -1221,13 +1217,12 @@ public class HashEnrollServlet extends CMSServlet {
newvalue[1] = 0x03;
newvalue[2] = 0x07;
newvalue[3] = value[3];
- // force encryption certs to have digitial signature
+ // force encryption certs to have digitial signature
// set too so smime can find the cert for encryption.
if (value[3] == 0x20) {
/*
- newvalue[3] = 0x3f;
- newvalue[4] = (byte)0x80;
+ * newvalue[3] = 0x3f; newvalue[4] = (byte)0x80;
*/
if (httpParams.getValueAsBoolean(
"dual-use-hack", true)) {
@@ -1235,22 +1230,21 @@ public class HashEnrollServlet extends CMSServlet {
}
}
newvalue[4] = 0;
- KeyUsageExtension newext =
- new KeyUsageExtension(Boolean.valueOf(true),
- (Object) newvalue);
+ KeyUsageExtension newext =
+ new KeyUsageExtension(Boolean.valueOf(true),
+ (Object) newvalue);
exts.delete(KeyUsageExtension.class.getSimpleName());
exts.set(KeyUsageExtension.class.getSimpleName(), newext);
}
} catch (IOException e) {
- // should never happen
+ // should never happen
continue;
} catch (CertificateException e) {
- // should never happen
+ // should never happen
continue;
}
}
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/ImportCertsTemplateFiller.java b/pki/base/common/src/com/netscape/cms/servlet/cert/ImportCertsTemplateFiller.java
index 75726730..58822812 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/ImportCertsTemplateFiller.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/ImportCertsTemplateFiller.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.StringReader;
@@ -58,25 +57,25 @@ import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
import com.netscape.cms.servlet.common.ICMSTemplateFiller;
-
/**
* Set up HTTP response to import certificate into browsers
*
- * The result must have been populate with the set of certificates
- * to return.
+ * The result must have been populate with the set of certificates to return.
+ *
* <pre>
* inputs: certtype.
* outputs:
- * - cert type from http input (if any)
+ * - cert type from http input (if any)
* - CA chain
- * - authority name (RM, CM, DRM)
+ * - authority name (RM, CM, DRM)
* - scheme:host:port of server.
- * array of one or more
+ * array of one or more
* - cert serial number
* - cert pretty print
- * - cert in base 64 encoding.
- * - cmmf blob to import
+ * - cert in base 64 encoding.
+ * - cmmf blob to import
* </pre>
+ *
* @version $Revision$, $Date$
*/
public class ImportCertsTemplateFiller implements ICMSTemplateFiller {
@@ -88,7 +87,7 @@ public class ImportCertsTemplateFiller implements ICMSTemplateFiller {
public static final String CERT_FINGERPRINT = "certFingerprint"; // cisco
public static final String CERT_NICKNAME = "certNickname";
public static final String CMMF_RESP = "cmmfResponse";
- public static final String PKCS7_RESP = "pkcs7ChainBase64"; // for MSIE
+ public static final String PKCS7_RESP = "pkcs7ChainBase64"; // for MSIE
public ImportCertsTemplateFiller() {
}
@@ -100,32 +99,32 @@ public class ImportCertsTemplateFiller implements ICMSTemplateFiller {
* @param e unexpected exception e. ignored.
*/
public CMSTemplateParams getTemplateParams(
- CMSRequest cmsReq, IAuthority authority, Locale locale, Exception e)
- throws Exception {
+ CMSRequest cmsReq, IAuthority authority, Locale locale, Exception e)
+ throws Exception {
Certificate[] certs = (Certificate[]) cmsReq.getResult();
if (certs instanceof X509CertImpl[])
- return getX509TemplateParams(cmsReq, authority, locale, e);
+ return getX509TemplateParams(cmsReq, authority, locale, e);
else
return null;
}
-
+
public CMSTemplateParams getX509TemplateParams(
- CMSRequest cmsReq, IAuthority authority, Locale locale, Exception e)
- throws Exception {
+ CMSRequest cmsReq, IAuthority authority, Locale locale, Exception e)
+ throws Exception {
IArgBlock header = CMS.createArgBlock();
IArgBlock fixed = CMS.createArgBlock();
CMSTemplateParams params = new CMSTemplateParams(header, fixed);
- // set host name and port.
+ // set host name and port.
HttpServletRequest httpReq = cmsReq.getHttpReq();
String host = httpReq.getServerName();
int port = httpReq.getServerPort();
String scheme = httpReq.getScheme();
String format = httpReq.getParameter("format");
- if(format!=null && format.equals("cmc"))
+ if (format != null && format.equals("cmc"))
fixed.set("importCMC", "false");
- String agentPort = ""+port;
+ String agentPort = "" + port;
fixed.set("agentHost", host);
fixed.set("agentPort", agentPort);
fixed.set(ICMSTemplateFiller.HOST, host);
@@ -148,33 +147,34 @@ public class ImportCertsTemplateFiller implements ICMSTemplateFiller {
// set cert type.
IArgBlock httpParams = cmsReq.getHttpParams();
- String certType =
- httpParams.getValueAsString(CERT_TYPE, null);
+ String certType =
+ httpParams.getValueAsString(CERT_TYPE, null);
- if (certType != null)
+ if (certType != null)
fixed.set(CERT_TYPE, certType);
- // this authority
- fixed.set(ICMSTemplateFiller.AUTHORITY,
- (String) authority.getOfficialName());
+ // this authority
+ fixed.set(ICMSTemplateFiller.AUTHORITY,
+ (String) authority.getOfficialName());
// CA chain.
- CertificateChain cachain =
- ((ICertAuthority) authority).getCACertChain();
+ CertificateChain cachain =
+ ((ICertAuthority) authority).getCACertChain();
X509Certificate[] cacerts = cachain.getChain();
String replyTo = httpParams.getValueAsString("replyTo", null);
- if (replyTo != null) fixed.set("replyTo", replyTo);
+ if (replyTo != null)
+ fixed.set("replyTo", replyTo);
- // set user + CA cert chain and pkcs7 for MSIE.
+ // set user + CA cert chain and pkcs7 for MSIE.
X509CertImpl[] userChain = new X509CertImpl[cacerts.length + 1];
int m = 1, n = 0;
- for (; n < cacerts.length; m++, n++)
+ for (; n < cacerts.length; m++, n++)
userChain[m] = (X509CertImpl) cacerts[n];
- // certs.
+ // certs.
X509CertImpl[] certs = (X509CertImpl[]) cmsReq.getResult();
// expose CRMF request id
@@ -188,7 +188,7 @@ public class ImportCertsTemplateFiller implements ICMSTemplateFiller {
fixed.set(CRMF_REQID, crmfReqId);
}
- // set CA certs in cmmf, initialize CertRepContent
+ // set CA certs in cmmf, initialize CertRepContent
// note cartman can't trust ca certs yet but it'll import them.
// also set cert nickname for cartman.
CertRepContent certRepContent = null;
@@ -196,23 +196,23 @@ public class ImportCertsTemplateFiller implements ICMSTemplateFiller {
if (CMSServlet.doCMMFResponse(httpParams)) {
byte[][] caPubs = new byte[cacerts.length][];
- for (int j = 0; j < cacerts.length; j++)
+ for (int j = 0; j < cacerts.length; j++)
caPubs[j] = ((X509CertImpl) cacerts[j]).getEncoded();
certRepContent = new CertRepContent(caPubs);
- String certnickname =
- cmsReq.getHttpParams().getValueAsString(CERT_NICKNAME, null);
+ String certnickname =
+ cmsReq.getHttpParams().getValueAsString(CERT_NICKNAME, null);
// if nickname is not requested set to subject name by default.
- if (certnickname == null)
+ if (certnickname == null)
fixed.set(CERT_NICKNAME, certs[0].getSubjectDN().toString());
else
fixed.set(CERT_NICKNAME, certnickname);
}
- // make pkcs7 for MSIE
- if (CMSServlet.clientIsMSIE(cmsReq.getHttpReq()) &&
- (certType == null || certType.equals("client"))) {
+ // make pkcs7 for MSIE
+ if (CMSServlet.clientIsMSIE(cmsReq.getHttpReq()) &&
+ (certType == null || certType.equals("client"))) {
userChain[0] = certs[0];
PKCS7 p7 = new PKCS7(new AlgorithmId[0],
new ContentInfo(new byte[0]),
@@ -222,7 +222,7 @@ public class ImportCertsTemplateFiller implements ICMSTemplateFiller {
p7.encodeSignedData(bos);
byte[] p7Bytes = bos.toByteArray();
- // String p7Str = encoder.encodeBuffer(p7Bytes);
+ // String p7Str = encoder.encodeBuffer(p7Bytes);
String p7Str = CMS.BtoA(p7Bytes);
header.set(PKCS7_RESP, p7Str);
@@ -234,24 +234,24 @@ public class ImportCertsTemplateFiller implements ICMSTemplateFiller {
X509CertImpl cert = certs[i];
// set serial number.
- BigInteger serialNo =
- ((X509Certificate) cert).getSerialNumber();
+ BigInteger serialNo =
+ ((X509Certificate) cert).getSerialNumber();
repeat.addBigIntegerValue(ISSUED_CERT_SERIAL, serialNo, 16);
// set base64 encoded blob.
byte[] certEncoded = cert.getEncoded();
- // String b64 = encoder.encodeBuffer(certEncoded);
+ // String b64 = encoder.encodeBuffer(certEncoded);
String b64 = CMS.BtoA(certEncoded);
String b64cert = "-----BEGIN CERTIFICATE-----\n" +
- b64 + "\n-----END CERTIFICATE-----";
+ b64 + "\n-----END CERTIFICATE-----";
repeat.set(BASE64_CERT, b64cert);
-
+
// set cert pretty print.
-
+
String prettyPrintRequested =
- cmsReq.getHttpParams().getValueAsString(CERT_PRETTYPRINT, null);
+ cmsReq.getHttpParams().getValueAsString(CERT_PRETTYPRINT, null);
if (prettyPrintRequested == null) {
prettyPrintRequested = "true";
@@ -266,7 +266,8 @@ public class ImportCertsTemplateFiller implements ICMSTemplateFiller {
repeat.set(CERT_PRETTYPRINT, ppStr);
// Now formulate a PKCS#7 blob
- X509CertImpl[] certsInChain = new X509CertImpl[1];;
+ X509CertImpl[] certsInChain = new X509CertImpl[1];
+ ;
if (cacerts != null) {
for (int j = 0; j < cacerts.length; j++) {
if (cert.equals(cacerts[j])) {
@@ -277,10 +278,10 @@ public class ImportCertsTemplateFiller implements ICMSTemplateFiller {
certsInChain = new X509CertImpl[cacerts.length + 1];
}
}
-
+
// Set the EE cert
certsInChain[0] = cert;
-
+
// Set the Ca certificate chain
if (cacerts != null) {
for (int j = 0; j < cacerts.length; j++) {
@@ -292,7 +293,7 @@ public class ImportCertsTemplateFiller implements ICMSTemplateFiller {
String p7Str;
try {
- PKCS7 p7 = new PKCS7(new AlgorithmId[0],
+ PKCS7 p7 = new PKCS7(new AlgorithmId[0],
new ContentInfo(new byte[0]),
certsInChain,
new SignerInfo[0]);
@@ -301,14 +302,14 @@ public class ImportCertsTemplateFiller implements ICMSTemplateFiller {
p7.encodeSignedData(bos);
byte[] p7Bytes = bos.toByteArray();
- //p7Str = encoder.encodeBuffer(p7Bytes);
+ // p7Str = encoder.encodeBuffer(p7Bytes);
p7Str = CMS.BtoA(p7Bytes);
repeat.addStringValue("pkcs7ChainBase64", p7Str);
} catch (Exception ex) {
- //p7Str = "PKCS#7 B64 Encoding error - " + ex.toString()
- //+ "; Please contact your administrator";
+ // p7Str = "PKCS#7 B64 Encoding error - " + ex.toString()
+ // + "; Please contact your administrator";
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_FORMING_PKCS7_ERROR"));
+ CMS.getUserMessage("CMS_GW_FORMING_PKCS7_ERROR"));
}
// set cert fingerprint (for Cisco routers)
@@ -325,18 +326,18 @@ public class ImportCertsTemplateFiller implements ICMSTemplateFiller {
throw new EBaseException(
CMS.getUserMessage(locale, "CMS_BASE_INTERNAL_ERROR", ex.toString()));
}
- if (fingerprint != null && fingerprint.length() > 0)
+ if (fingerprint != null && fingerprint.length() > 0)
repeat.set(CERT_FINGERPRINT, fingerprint);
- // cmmf response for this cert.
+ // cmmf response for this cert.
if (CMSServlet.doCMMFResponse(httpParams) && crmfReqId != null &&
- (certType == null || certType.equals("client"))) {
+ (certType == null || certType.equals("client"))) {
PKIStatusInfo status = new PKIStatusInfo(PKIStatusInfo.granted);
- CertifiedKeyPair certifiedKP =
- new CertifiedKeyPair(new CertOrEncCert(certEncoded));
- CertResponse resp =
- new CertResponse(new INTEGER(crmfReqId), status,
- certifiedKP);
+ CertifiedKeyPair certifiedKP =
+ new CertifiedKeyPair(new CertOrEncCert(certEncoded));
+ CertResponse resp =
+ new CertResponse(new INTEGER(crmfReqId), status,
+ certifiedKP);
certRepContent.addCertResponse(resp);
}
@@ -352,19 +353,19 @@ public class ImportCertsTemplateFiller implements ICMSTemplateFiller {
byte[] certRepBytes = certRepOut.toByteArray();
String certRepB64 = com.netscape.osutil.OSUtil.BtoA(certRepBytes);
// add CR to each return as required by cartman
- BufferedReader certRepB64lines =
- new BufferedReader(new StringReader(certRepB64));
+ BufferedReader certRepB64lines =
+ new BufferedReader(new StringReader(certRepB64));
StringWriter certRepStringOut = new StringWriter();
String oneLine = null;
boolean first = true;
while ((oneLine = certRepB64lines.readLine()) != null) {
if (first) {
- //certRepStringOut.write("\""+oneLine+"\"");
+ // certRepStringOut.write("\""+oneLine+"\"");
certRepStringOut.write(oneLine);
first = false;
} else {
- //certRepStringOut.write("+\"\\n"+oneLine+"\"");
+ // certRepStringOut.write("+\"\\n"+oneLine+"\"");
certRepStringOut.write("\n" + oneLine);
}
}
@@ -376,4 +377,3 @@ public class ImportCertsTemplateFiller implements ICMSTemplateFiller {
return params;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/ListCerts.java b/pki/base/common/src/com/netscape/cms/servlet/cert/ListCerts.java
index a65be25a..9e89bb1a 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/ListCerts.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/ListCerts.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.io.IOException;
import java.math.BigInteger;
import java.security.PublicKey;
@@ -57,10 +56,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* Retrieve a paged list of certs matching the specified query
- *
+ *
* @version $Revision$, $Date$
*/
public class ListCerts extends CMSServlet {
@@ -78,8 +76,8 @@ public class ListCerts extends CMSServlet {
private ICertificateRepository mCertDB = null;
private X500Name mAuthName = null;
private String mFormPath = null;
- private boolean mReverse = false;
- private boolean mHardJumpTo = false; //jump to the end
+ private boolean mReverse = false;
+ private boolean mHardJumpTo = false; // jump to the end
private String mDirection = null;
private boolean mUseClientFilter = false;
private Vector<String> mAllowedClientFilters = new Vector<String>();
@@ -95,7 +93,7 @@ public class ListCerts extends CMSServlet {
/**
* initialize the servlet. This servlet uses the template file
* "queryCert.template" to render the response
- *
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -120,28 +118,29 @@ public class ListCerts extends CMSServlet {
/* do nothing, just use the default if integer parsing failed */
}
- /* useClientFilter should be off by default. We keep
- this parameter around so that we do not break
- the client applications that submits raw LDAP
- filter into this servlet. */
+ /*
+ * useClientFilter should be off by default. We keep this parameter
+ * around so that we do not break the client applications that submits
+ * raw LDAP filter into this servlet.
+ */
if (sc.getInitParameter(USE_CLIENT_FILTER) != null &&
- sc.getInitParameter(USE_CLIENT_FILTER).equalsIgnoreCase("true")) { mUseClientFilter = true;
+ sc.getInitParameter(USE_CLIENT_FILTER).equalsIgnoreCase("true")) {
+ mUseClientFilter = true;
}
if (sc.getInitParameter(ALLOWED_CLIENT_FILTERS) == null || sc.getInitParameter(ALLOWED_CLIENT_FILTERS).equals("")) {
- mAllowedClientFilters.addElement("(certStatus=*)");
- mAllowedClientFilters.addElement("(certStatus=VALID)");
- mAllowedClientFilters.addElement("(|(certStatus=VALID)(certStatus=INVALID)(certStatus=EXPIRED))");
- mAllowedClientFilters.addElement("(|(certStatus=VALID)(certStatus=REVOKED))");
+ mAllowedClientFilters.addElement("(certStatus=*)");
+ mAllowedClientFilters.addElement("(certStatus=VALID)");
+ mAllowedClientFilters.addElement("(|(certStatus=VALID)(certStatus=INVALID)(certStatus=EXPIRED))");
+ mAllowedClientFilters.addElement("(|(certStatus=VALID)(certStatus=REVOKED))");
} else {
StringTokenizer st = new StringTokenizer(sc.getInitParameter(ALLOWED_CLIENT_FILTERS), ",");
while (st.hasMoreTokens()) {
- mAllowedClientFilters.addElement(st.nextToken());
+ mAllowedClientFilters.addElement(st.nextToken());
}
}
}
- public String buildFilter(HttpServletRequest req)
- {
+ public String buildFilter(HttpServletRequest req) {
String queryCertFilter = req.getParameter("queryCertFilter");
com.netscape.certsrv.apps.CMS.debug("client queryCertFilter=" + queryCertFilter);
@@ -151,7 +150,7 @@ public class ListCerts extends CMSServlet {
Enumeration<String> filters = mAllowedClientFilters.elements();
// check to see if the filter is allowed
while (filters.hasMoreElements()) {
- String filter = (String)filters.nextElement();
+ String filter = (String) filters.nextElement();
com.netscape.certsrv.apps.CMS.debug("Comparing filter=" + filter + " queryCertFilter=" + queryCertFilter);
if (filter.equals(queryCertFilter)) {
return queryCertFilter;
@@ -166,34 +165,37 @@ public class ListCerts extends CMSServlet {
boolean skipRevoked = false;
boolean skipNonValid = false;
if (req.getParameter("skipRevoked") != null &&
- req.getParameter("skipRevoked").equals("on")) {
+ req.getParameter("skipRevoked").equals("on")) {
skipRevoked = true;
}
if (req.getParameter("skipNonValid") != null &&
- req.getParameter("skipNonValid").equals("on")) {
+ req.getParameter("skipNonValid").equals("on")) {
skipNonValid = true;
}
if (!skipRevoked && !skipNonValid) {
- queryCertFilter = "(certStatus=*)";
- } else if (skipRevoked && skipNonValid) {
- queryCertFilter = "(certStatus=VALID)";
- } else if (skipRevoked) {
- queryCertFilter = "(|(certStatus=VALID)(certStatus=INVALID)(certStatus=EXPIRED))";
- } else if (skipNonValid) {
- queryCertFilter = "(|(certStatus=VALID)(certStatus=REVOKED))";
+ queryCertFilter = "(certStatus=*)";
+ } else if (skipRevoked && skipNonValid) {
+ queryCertFilter = "(certStatus=VALID)";
+ } else if (skipRevoked) {
+ queryCertFilter = "(|(certStatus=VALID)(certStatus=INVALID)(certStatus=EXPIRED))";
+ } else if (skipNonValid) {
+ queryCertFilter = "(|(certStatus=VALID)(certStatus=REVOKED))";
}
return queryCertFilter;
}
/**
- * Process the HTTP request.
- * <ul>
- * <li>http.param maxCount Number of certificates to show
+ * Process the HTTP request.
+ * <ul>
+ * <li>http.param maxCount Number of certificates to show
* <li>http.param queryFilter and ldap style filter specifying the
- * certificates to show
- * <li>http.param querySentinelDown the serial number of the first certificate to show (default decimal, or hex if prefixed with 0x) when paging down
- * <li>http.param querySentinelUp the serial number of the first certificate to show (default decimal, or hex if prefixed with 0x) when paging up
+ * certificates to show
+ * <li>http.param querySentinelDown the serial number of the first
+ * certificate to show (default decimal, or hex if prefixed with 0x) when
+ * paging down
+ * <li>http.param querySentinelUp the serial number of the first certificate
+ * to show (default decimal, or hex if prefixed with 0x) when paging up
* <li>http.param direction "up", "down", "begin", or "end"
* </ul>
*/
@@ -232,24 +234,24 @@ public class ListCerts extends CMSServlet {
try {
form = getTemplate(mFormPath, req, locale);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- com.netscape.certsrv.apps.CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ log(ILogger.LL_FAILURE,
+ com.netscape.certsrv.apps.CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
throw new ECMSGWException(
- com.netscape.certsrv.apps.CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ com.netscape.certsrv.apps.CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
- mHardJumpTo = false;
+ mHardJumpTo = false;
try {
- if (req.getParameter("direction") != null) {
- mDirection = req.getParameter("direction").trim();
- mReverse = mDirection.equals("up");
- if (mReverse)
- com.netscape.certsrv.apps.CMS.debug("reverse is true");
- else
- com.netscape.certsrv.apps.CMS.debug("reverse is false");
+ if (req.getParameter("direction") != null) {
+ mDirection = req.getParameter("direction").trim();
+ mReverse = mDirection.equals("up");
+ if (mReverse)
+ com.netscape.certsrv.apps.CMS.debug("reverse is true");
+ else
+ com.netscape.certsrv.apps.CMS.debug("reverse is false");
- }
+ }
if (req.getParameter("maxCount") != null) {
maxCount = Integer.parseInt(req.getParameter("maxCount"));
@@ -259,19 +261,19 @@ public class ListCerts extends CMSServlet {
maxCount = mMaxReturns;
}
- String sentinelStr = "";
- if (mReverse) {
- sentinelStr = req.getParameter("querySentinelUp");
- } else if (mDirection.equals("end")) {
- // this servlet will figure out the end
- sentinelStr = "0";
- mReverse = true;
- mHardJumpTo = true;
- } else if (mDirection.equals("down")) {
- sentinelStr = req.getParameter("querySentinelDown");
- } else
- sentinelStr = "0";
- //begin and non-specified have sentinel default "0"
+ String sentinelStr = "";
+ if (mReverse) {
+ sentinelStr = req.getParameter("querySentinelUp");
+ } else if (mDirection.equals("end")) {
+ // this servlet will figure out the end
+ sentinelStr = "0";
+ mReverse = true;
+ mHardJumpTo = true;
+ } else if (mDirection.equals("down")) {
+ sentinelStr = req.getParameter("querySentinelDown");
+ } else
+ sentinelStr = "0";
+ // begin and non-specified have sentinel default "0"
if (sentinelStr != null) {
if (sentinelStr.trim().startsWith("0x")) {
@@ -286,9 +288,9 @@ public class ListCerts extends CMSServlet {
if (mAuthority instanceof ICertificateAuthority) {
X509CertImpl caCert = ((ICertificateAuthority) mAuthority).getSigningUnit().getCertImpl();
- //if (isCertFromCA(caCert))
+ // if (isCertFromCA(caCert))
header.addStringValue("caSerialNumber",
- caCert.getSerialNumber().toString(16));
+ caCert.getSerialNumber().toString(16));
}
// constructs the ldap filter on the server side
@@ -298,7 +300,7 @@ public class ListCerts extends CMSServlet {
cmsReq.setStatus(CMSRequest.UNAUTHORIZED);
return;
}
-
+
com.netscape.certsrv.apps.CMS.debug("queryCertFilter=" + queryCertFilter);
int totalRecordCount = -1;
@@ -307,16 +309,16 @@ public class ListCerts extends CMSServlet {
totalRecordCount = Integer.parseInt(req.getParameter("totalRecordCount"));
} catch (Exception e) {
}
- processCertFilter(argSet, header, maxCount,
- sentinel,
- totalRecordCount,
- req.getParameter("serialTo"),
- queryCertFilter,
- req, resp, revokeAll, locale[0]);
+ processCertFilter(argSet, header, maxCount,
+ sentinel,
+ totalRecordCount,
+ req.getParameter("serialTo"),
+ queryCertFilter,
+ req, resp, revokeAll, locale[0]);
} catch (NumberFormatException e) {
log(ILogger.LL_FAILURE, com.netscape.certsrv.apps.CMS.getLogMessage("BASE_INVALID_NUMBER_FORMAT"));
-
- error = new EBaseException(com.netscape.certsrv.apps.CMS.getUserMessage(getLocale(req),"CMS_BASE_INVALID_NUMBER_FORMAT"));
+
+ error = new EBaseException(com.netscape.certsrv.apps.CMS.getUserMessage(getLocale(req), "CMS_BASE_INVALID_NUMBER_FORMAT"));
} catch (EBaseException e) {
error = e;
}
@@ -329,36 +331,36 @@ public class ListCerts extends CMSServlet {
if (error == null) {
String xmlOutput = req.getParameter("xml");
if (xmlOutput != null && xmlOutput.equals("true")) {
- outputXML(resp, argSet);
+ outputXML(resp, argSet);
} else {
- cmsReq.setStatus(CMSRequest.SUCCESS);
- resp.setContentType("text/html");
- form.renderOutput(out, argSet);
+ cmsReq.setStatus(CMSRequest.SUCCESS);
+ resp.setContentType("text/html");
+ form.renderOutput(out, argSet);
}
} else {
cmsReq.setStatus(CMSRequest.ERROR);
cmsReq.setError(error);
}
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- com.netscape.certsrv.apps.CMS.getLogMessage("CMSGW_ERR_OUT_STREAM_TEMPLATE", e.toString()));
+ log(ILogger.LL_FAILURE,
+ com.netscape.certsrv.apps.CMS.getLogMessage("CMSGW_ERR_OUT_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- com.netscape.certsrv.apps.CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ com.netscape.certsrv.apps.CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
}
- private void processCertFilter(CMSTemplateParams argSet,
- IArgBlock header,
- int maxCount,
- BigInteger sentinel,
- int totalRecordCount,
- String serialTo,
- String filter,
- HttpServletRequest req,
- HttpServletResponse resp,
- String revokeAll,
- Locale locale
- ) throws EBaseException {
+ private void processCertFilter(CMSTemplateParams argSet,
+ IArgBlock header,
+ int maxCount,
+ BigInteger sentinel,
+ int totalRecordCount,
+ String serialTo,
+ String filter,
+ HttpServletRequest req,
+ HttpServletResponse resp,
+ String revokeAll,
+ Locale locale
+ ) throws EBaseException {
BigInteger serialToVal = MINUS_ONE;
try {
@@ -376,31 +378,31 @@ public class ListCerts extends CMSServlet {
}
String jumpTo = sentinel.toString();
- int pSize = 0;
- if (mReverse) {
- if (!mHardJumpTo) //reverse gets one more
- pSize = -1*maxCount-1;
- else
- pSize = -1*maxCount;
- } else
- pSize = maxCount;
+ int pSize = 0;
+ if (mReverse) {
+ if (!mHardJumpTo) // reverse gets one more
+ pSize = -1 * maxCount - 1;
+ else
+ pSize = -1 * maxCount;
+ } else
+ pSize = maxCount;
ICertRecordList list = (ICertRecordList) mCertDB.findCertRecordsInList(
- filter, (String[]) null, jumpTo, mHardJumpTo, "serialno",
- pSize);
+ filter, (String[]) null, jumpTo, mHardJumpTo, "serialno",
+ pSize);
// retrive maxCount + 1 entries
- Enumeration<ICertRecord> e = list.getCertRecords(0, maxCount);
+ Enumeration<ICertRecord> e = list.getCertRecords(0, maxCount);
ICertRecordList tolist = null;
int toCurIndex = 0;
if (!serialToVal.equals(MINUS_ONE)) {
- // if user specify a range, we need to
+ // if user specify a range, we need to
// calculate the totalRecordCount
tolist = (ICertRecordList) mCertDB.findCertRecordsInList(
- filter,
- (String[]) null, serialTo,
+ filter,
+ (String[]) null, serialTo,
"serialno", maxCount);
Enumeration<ICertRecord> en = tolist.getCertRecords(0, 0);
@@ -420,82 +422,85 @@ public class ListCerts extends CMSServlet {
}
}
}
-
+
int curIndex = list.getCurrentIndex();
int count = 0;
- BigInteger firstSerial = new BigInteger("0");
- BigInteger curSerial = new BigInteger("0");
- ICertRecord[] recs = new ICertRecord[maxCount];
- int rcount = 0;
+ BigInteger firstSerial = new BigInteger("0");
+ BigInteger curSerial = new BigInteger("0");
+ ICertRecord[] recs = new ICertRecord[maxCount];
+ int rcount = 0;
if (e != null) {
- /* in reverse (page up), because the sentinel is the one after the
- * last item to be displayed, we need to skip it
- */
- while ((count < ((mReverse &&!mHardJumpTo)? (maxCount+1):maxCount)) && e.hasMoreElements()) {
+ /*
+ * in reverse (page up), because the sentinel is the one after the
+ * last item to be displayed, we need to skip it
+ */
+ while ((count < ((mReverse && !mHardJumpTo) ? (maxCount + 1) : maxCount)) && e.hasMoreElements()) {
ICertRecord rec = (ICertRecord) e.nextElement();
if (rec == null) {
- com.netscape.certsrv.apps.CMS.debug("record "+count+" is null");
+ com.netscape.certsrv.apps.CMS.debug("record " + count + " is null");
break;
- }
+ }
curSerial = rec.getSerialNumber();
- com.netscape.certsrv.apps.CMS.debug("record "+count+" is serial#"+curSerial);
-
- if (count == 0) {
- firstSerial = curSerial;
- if (mReverse && !mHardJumpTo) {//reverse got one more, skip
- count++;
- continue;
- }
- }
-
- // DS has a problem where last record will be returned
- // even though the filter is not matched.
- /*cfu - is this necessary? it breaks when paging up
- if (curSerial.compareTo(sentinel) == -1) {
- com.netscape.certsrv.apps.CMS.debug("curSerial compare sentinel -1 break...");
-
- break;
- }
- */
+ com.netscape.certsrv.apps.CMS.debug("record " + count + " is serial#" + curSerial);
+
+ if (count == 0) {
+ firstSerial = curSerial;
+ if (mReverse && !mHardJumpTo) {// reverse got one more, skip
+ count++;
+ continue;
+ }
+ }
+
+ // DS has a problem where last record will be returned
+ // even though the filter is not matched.
+ /*
+ * cfu - is this necessary? it breaks when paging up if
+ * (curSerial.compareTo(sentinel) == -1) {
+ * com.netscape.certsrv.apps
+ * .CMS.debug("curSerial compare sentinel -1 break...");
+ *
+ * break; }
+ */
if (!serialToVal.equals(MINUS_ONE)) {
// check if we go over the limit
if (curSerial.compareTo(serialToVal) == 1) {
- com.netscape.certsrv.apps.CMS.debug("curSerial compare serialToVal 1 breaking...");
+ com.netscape.certsrv.apps.CMS.debug("curSerial compare serialToVal 1 breaking...");
break;
- }
+ }
}
- if (mReverse) {
- recs[rcount++] = rec;
- } else {
+ if (mReverse) {
+ recs[rcount++] = rec;
+ } else {
- IArgBlock rarg = com.netscape.certsrv.apps.CMS.createArgBlock();
+ IArgBlock rarg = com.netscape.certsrv.apps.CMS.createArgBlock();
- fillRecordIntoArg(rec, rarg);
- argSet.addRepeatRecord(rarg);
- }
+ fillRecordIntoArg(rec, rarg);
+ argSet.addRepeatRecord(rarg);
+ }
count++;
}
} else {
com.netscape.certsrv.apps.CMS.debug(
- "ListCerts::processCertFilter() - no Cert Records found!" );
+ "ListCerts::processCertFilter() - no Cert Records found!");
return;
}
- if (mReverse) {
- // fill records into arg block and argSet
- for (int ii = rcount-1; ii>= 0; ii--) {
- if (recs[ii] != null) {
- IArgBlock rarg = com.netscape.certsrv.apps.CMS.createArgBlock();
- //com.netscape.certsrv.apps.CMS.debug("item "+ii+" is serial # "+ recs[ii].getSerialNumber());
- fillRecordIntoArg(recs[ii], rarg);
- argSet.addRepeatRecord(rarg);
- }
- }
- }
+ if (mReverse) {
+ // fill records into arg block and argSet
+ for (int ii = rcount - 1; ii >= 0; ii--) {
+ if (recs[ii] != null) {
+ IArgBlock rarg = com.netscape.certsrv.apps.CMS.createArgBlock();
+ // com.netscape.certsrv.apps.CMS.debug("item "+ii+" is serial # "+
+ // recs[ii].getSerialNumber());
+ fillRecordIntoArg(recs[ii], rarg);
+ argSet.addRepeatRecord(rarg);
+ }
+ }
+ }
// peek ahead
ICertRecord nextRec = null;
@@ -519,58 +524,58 @@ public class ListCerts extends CMSServlet {
if (totalRecordCount == -1) {
if (!serialToVal.equals(MINUS_ONE)) {
totalRecordCount = toCurIndex - curIndex + 1;
- com.netscape.certsrv.apps.CMS.debug("totalRecordCount="+totalRecordCount);
+ com.netscape.certsrv.apps.CMS.debug("totalRecordCount=" + totalRecordCount);
} else {
- totalRecordCount = list.getSize() -
+ totalRecordCount = list.getSize() -
list.getCurrentIndex();
- com.netscape.certsrv.apps.CMS.debug("totalRecordCount="+totalRecordCount);
+ com.netscape.certsrv.apps.CMS.debug("totalRecordCount=" + totalRecordCount);
}
}
header.addIntegerValue("totalRecordCount", totalRecordCount);
- header.addIntegerValue("currentRecordCount", list.getSize() -
- list.getCurrentIndex());
-
- String qs = "";
- if (mReverse)
- qs = "querySentinelUp";
- else
- qs = "querySentinelDown";
-
- if (mHardJumpTo) {
- com.netscape.certsrv.apps.CMS.debug("curSerial added to querySentinelUp:"+ curSerial.toString());
-
- header.addStringValue("querySentinelUp", curSerial.toString());
- } else {
- if (nextRec == null) {
- header.addStringValue(qs, null);
- com.netscape.certsrv.apps.CMS.debug("nextRec is null");
- if (mReverse) {
- com.netscape.certsrv.apps.CMS.debug("curSerial added to querySentinelUp:"+ curSerial.toString());
-
- header.addStringValue("querySentinelUp", curSerial.toString());
- }
+ header.addIntegerValue("currentRecordCount", list.getSize() -
+ list.getCurrentIndex());
+
+ String qs = "";
+ if (mReverse)
+ qs = "querySentinelUp";
+ else
+ qs = "querySentinelDown";
+
+ if (mHardJumpTo) {
+ com.netscape.certsrv.apps.CMS.debug("curSerial added to querySentinelUp:" + curSerial.toString());
+
+ header.addStringValue("querySentinelUp", curSerial.toString());
} else {
- BigInteger nextRecNo = nextRec.getSerialNumber();
+ if (nextRec == null) {
+ header.addStringValue(qs, null);
+ com.netscape.certsrv.apps.CMS.debug("nextRec is null");
+ if (mReverse) {
+ com.netscape.certsrv.apps.CMS.debug("curSerial added to querySentinelUp:" + curSerial.toString());
- if (serialToVal.equals(MINUS_ONE)) {
- header.addStringValue(
- qs, nextRecNo.toString());
+ header.addStringValue("querySentinelUp", curSerial.toString());
+ }
} else {
- if (nextRecNo.compareTo(serialToVal) <= 0) {
+ BigInteger nextRecNo = nextRec.getSerialNumber();
+
+ if (serialToVal.equals(MINUS_ONE)) {
header.addStringValue(
- qs, nextRecNo.toString());
+ qs, nextRecNo.toString());
} else {
- header.addStringValue(qs,
- null);
+ if (nextRecNo.compareTo(serialToVal) <= 0) {
+ header.addStringValue(
+ qs, nextRecNo.toString());
+ } else {
+ header.addStringValue(qs,
+ null);
+ }
}
+ com.netscape.certsrv.apps.CMS.debug("querySentinel " + qs + " = " + nextRecNo.toString());
}
- com.netscape.certsrv.apps.CMS.debug("querySentinel "+qs+" = "+nextRecNo.toString());
- }
- } // !mHardJumpto
+ } // !mHardJumpto
- header.addStringValue(!mReverse? "querySentinelUp":"querySentinelDown",
- firstSerial.toString());
+ header.addStringValue(!mReverse ? "querySentinelUp" : "querySentinelDown",
+ firstSerial.toString());
}
@@ -578,7 +583,7 @@ public class ListCerts extends CMSServlet {
* Fills cert record into argument block.
*/
private void fillRecordIntoArg(ICertRecord rec, IArgBlock rarg)
- throws EBaseException {
+ throws EBaseException {
X509CertImpl xcert = rec.getCertificate();
@@ -586,9 +591,9 @@ public class ListCerts extends CMSServlet {
fillX509RecordIntoArg(rec, rarg);
}
}
-
+
private void fillX509RecordIntoArg(ICertRecord rec, IArgBlock rarg)
- throws EBaseException {
+ throws EBaseException {
X509CertImpl cert = rec.getCertificate();
@@ -631,12 +636,13 @@ public class ListCerts extends CMSServlet {
rarg.addStringValue("signatureAlgorithm", cert.getSigAlgOID());
String issuedBy = rec.getIssuedBy();
- if (issuedBy == null) issuedBy = "";
+ if (issuedBy == null)
+ issuedBy = "";
rarg.addStringValue("issuedBy", issuedBy); // cert.getIssuerDN().toString()
rarg.addLongValue("issuedOn", rec.getCreateTime().getTime() / 1000);
rarg.addStringValue("revokedBy",
- ((rec.getRevokedBy() == null) ? "" : rec.getRevokedBy()));
+ ((rec.getRevokedBy() == null) ? "" : rec.getRevokedBy()));
if (rec.getRevokedOn() == null) {
rarg.addStringValue("revokedOn", null);
} else {
@@ -665,4 +671,3 @@ public class ListCerts extends CMSServlet {
}
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/Monitor.java b/pki/base/common/src/com/netscape/cms/servlet/cert/Monitor.java
index db77d039..b248d2bd 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/Monitor.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/Monitor.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
@@ -51,10 +50,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* Provide statistical queries of request and certificate records.
- *
+ *
* @version $Revision$, $Date$
*/
public class Monitor extends CMSServlet {
@@ -83,8 +81,8 @@ public class Monitor extends CMSServlet {
/**
* initialize the servlet. This servlet uses the template file
- * 'monitor.template' to render the response.
- *
+ * 'monitor.template' to render the response.
+ *
* @param sc servlet configuration, read from the web.xml file
*/
@@ -111,8 +109,8 @@ public class Monitor extends CMSServlet {
* Process the HTTP request.
* <ul>
* <li>http.param startTime start of time period to query
- * <li>http.param endTime end of time period to query
- * <li>http.param interval time between queries
+ * <li>http.param endTime end of time period to query
+ * <li>http.param interval time between queries
* <li>http.param numberOfIntervals number of queries to run
* <li>http.param maxResults =number
* <li>http.param timeLimit =time
@@ -130,10 +128,10 @@ public class Monitor extends CMSServlet {
mAuthzResourceName, "read");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -158,8 +156,8 @@ public class Monitor extends CMSServlet {
try {
form = getTemplate(mFormPath, req, locale);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
throw new ECMSGWException(CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
@@ -172,7 +170,7 @@ public class Monitor extends CMSServlet {
process(argSet, header, startTime, endTime, interval, numberOfIntervals, locale[0]);
} catch (EBaseException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_PROCESSING_REQ", e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_PROCESSING_REQ", e.toString()));
error = e;
}
@@ -182,29 +180,29 @@ public class Monitor extends CMSServlet {
if (error == null) {
String xmlOutput = req.getParameter("xml");
if (xmlOutput != null && xmlOutput.equals("true")) {
- outputXML(resp, argSet);
+ outputXML(resp, argSet);
} else {
- resp.setContentType("text/html");
- form.renderOutput(out, argSet);
- cmsReq.setStatus(CMSRequest.SUCCESS);
+ resp.setContentType("text/html");
+ form.renderOutput(out, argSet);
+ cmsReq.setStatus(CMSRequest.SUCCESS);
}
} else {
cmsReq.setStatus(CMSRequest.ERROR);
cmsReq.setError(error);
}
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE",
- e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE",
+ e.toString()));
throw new ECMSGWException(CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
}
- private void process(CMSTemplateParams argSet, IArgBlock header,
- String startTime, String endTime,
- String interval, String numberOfIntervals,
- Locale locale)
- throws EBaseException {
+ private void process(CMSTemplateParams argSet, IArgBlock header,
+ String startTime, String endTime,
+ String interval, String numberOfIntervals,
+ Locale locale)
+ throws EBaseException {
if (interval == null || interval.length() == 0) {
header.addStringValue("error", "Invalid interval: " + interval);
return;
@@ -270,7 +268,7 @@ public class Monitor extends CMSServlet {
return;
}
-
+
Date nextDate(Date d, int seconds) {
Date date = new Date((d.getTime()) + ((long) (seconds * 1000)));
@@ -326,12 +324,12 @@ public class Monitor extends CMSServlet {
mTotalReqs += count;
}
} catch (Exception ex) {
- return "Exception: " + ex;
+ return "Exception: " + ex;
}
return null;
} else {
- return "Missing start or end date";
+ return "Missing start or end date";
}
}
@@ -348,12 +346,12 @@ public class Monitor extends CMSServlet {
int hour = Integer.parseInt(z.substring(8, 10));
int minute = Integer.parseInt(z.substring(10, 12));
int second = Integer.parseInt(z.substring(12, 14));
- Calendar calendar= Calendar.getInstance();
+ Calendar calendar = Calendar.getInstance();
calendar.set(year, month, date, hour, minute, second);
d = calendar.getTime();
} catch (NumberFormatException nfe) {
}
- } else if (z != null && z.length() > 1 && z.charAt(0) == '-') { // -5
+ } else if (z != null && z.length() > 1 && z.charAt(0) == '-') { // -5
try {
int i = Integer.parseInt(z);
@@ -370,23 +368,27 @@ public class Monitor extends CMSServlet {
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
-
String time = "" + (calendar.get(Calendar.YEAR));
int i = calendar.get(Calendar.MONTH) + 1;
- if (i < 10) time += "0";
+ if (i < 10)
+ time += "0";
time += i;
- i = calendar.get(Calendar.DAY_OF_MONTH);
- if (i < 10) time += "0";
+ i = calendar.get(Calendar.DAY_OF_MONTH);
+ if (i < 10)
+ time += "0";
time += i;
i = calendar.get(Calendar.HOUR_OF_DAY);
- if (i < 10) time += "0";
+ if (i < 10)
+ time += "0";
time += i;
i = calendar.get(Calendar.MINUTE);
- if (i < 10) time += "0";
+ if (i < 10)
+ time += "0";
time += i;
i = calendar.get(Calendar.SECOND);
- if (i < 10) time += "0";
+ if (i < 10)
+ time += "0";
time += i + "Z";
return time;
}
@@ -403,4 +405,3 @@ public class Monitor extends CMSServlet {
return filter;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/ReasonToRevoke.java b/pki/base/common/src/com/netscape/cms/servlet/cert/ReasonToRevoke.java
index 50296cf1..db09fae9 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/ReasonToRevoke.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/ReasonToRevoke.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.io.IOException;
import java.util.Enumeration;
import java.util.Locale;
@@ -48,10 +47,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* Specify the RevocationReason when revoking a certificate
- *
+ *
* @version $Revision$, $Date$
*/
public class ReasonToRevoke extends CMSServlet {
@@ -75,9 +73,9 @@ public class ReasonToRevoke extends CMSServlet {
}
/**
- * initialize the servlet. This servlet uses the template file
- * 'reasonToRevoke.template' to render the response
- *
+ * initialize the servlet. This servlet uses the template file
+ * 'reasonToRevoke.template' to render the response
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -108,13 +106,13 @@ public class ReasonToRevoke extends CMSServlet {
/**
* Returns serlvet information.
*/
- public String getServletInfo() {
- return INFO;
+ public String getServletInfo() {
+ return INFO;
}
/**
- * Process the HTTP request.
- *
+ * Process the HTTP request.
+ *
* @param cmsReq the object holding the request and response information
*/
public void process(CMSRequest cmsReq) throws EBaseException {
@@ -130,10 +128,10 @@ public class ReasonToRevoke extends CMSServlet {
mAuthzResourceName, "revoke");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -151,10 +149,10 @@ public class ReasonToRevoke extends CMSServlet {
try {
form = getTemplate(mFormPath, req, locale);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
IArgBlock header = CMS.createArgBlock();
@@ -163,31 +161,26 @@ public class ReasonToRevoke extends CMSServlet {
try {
if (req.getParameter("totalRecordCount") != null) {
- totalRecordCount =
+ totalRecordCount =
Integer.parseInt(req.getParameter("totalRecordCount"));
}
revokeAll = req.getParameter("revokeAll");
- process(argSet, header, req, resp,
- revokeAll, totalRecordCount, locale[0]);
+ process(argSet, header, req, resp,
+ revokeAll, totalRecordCount, locale[0]);
} catch (EBaseException e) {
error = e;
} catch (NumberFormatException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_INVALID_RECORD_COUNT_FORMAT"));
error = new EBaseException(CMS.getUserMessage(getLocale(req), "CMS_BASE_INVALID_NUMBER_FORMAT"));
- }
+ }
/*
- catch (Exception e) {
- noError = false;
- header.addStringValue(OUT_ERROR,
- MessageFormatter.getLocalizedString(
- errorlocale[0],
- BaseResources.class.getName(),
- BaseResources.INTERNAL_ERROR_1,
- e.toString()));
- }
+ * catch (Exception e) { noError = false;
+ * header.addStringValue(OUT_ERROR, MessageFormatter.getLocalizedString(
+ * errorlocale[0], BaseResources.class.getName(),
+ * BaseResources.INTERNAL_ERROR_1, e.toString())); }
*/
try {
@@ -196,30 +189,30 @@ public class ReasonToRevoke extends CMSServlet {
if (error == null) {
String xmlOutput = req.getParameter("xml");
if (xmlOutput != null && xmlOutput.equals("true")) {
- outputXML(resp, argSet);
+ outputXML(resp, argSet);
} else {
- resp.setContentType("text/html");
- form.renderOutput(out, argSet);
- cmsReq.setStatus(CMSRequest.SUCCESS);
+ resp.setContentType("text/html");
+ form.renderOutput(out, argSet);
+ cmsReq.setStatus(CMSRequest.SUCCESS);
}
} else {
cmsReq.setStatus(CMSRequest.ERROR);
cmsReq.setError(error);
}
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_OUT_STREAM_TEMPLATE", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_OUT_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
}
private void process(CMSTemplateParams argSet, IArgBlock header,
- HttpServletRequest req,
- HttpServletResponse resp,
- String revokeAll, int totalRecordCount,
- Locale locale)
- throws EBaseException {
+ HttpServletRequest req,
+ HttpServletResponse resp,
+ String revokeAll, int totalRecordCount,
+ Locale locale)
+ throws EBaseException {
header.addStringValue("revokeAll", revokeAll);
header.addIntegerValue("totalRecordCount", totalRecordCount);
@@ -238,14 +231,14 @@ public class ReasonToRevoke extends CMSServlet {
if (isCertFromCA(caCert)) {
header.addStringValue("caSerialNumber",
- caCert.getSerialNumber().toString(16));
+ caCert.getSerialNumber().toString(16));
}
}
/**
- ICertRecordList list = mCertDB.findCertRecordsInList(
- revokeAll, null, totalRecordCount);
- Enumeration e = list.getCertRecords(0, totalRecordCount - 1);
+ * ICertRecordList list = mCertDB.findCertRecordsInList( revokeAll,
+ * null, totalRecordCount); Enumeration e = list.getCertRecords(0,
+ * totalRecordCount - 1);
**/
Enumeration e = mCertDB.searchCertificates(revokeAll,
totalRecordCount, mTimeLimits);
@@ -265,16 +258,16 @@ public class ReasonToRevoke extends CMSServlet {
count++;
IArgBlock rarg = CMS.createArgBlock();
- rarg.addStringValue("serialNumber",
- xcert.getSerialNumber().toString(16));
- rarg.addStringValue("serialNumberDecimal",
- xcert.getSerialNumber().toString());
- rarg.addStringValue("subject",
- xcert.getSubjectDN().toString());
- rarg.addLongValue("validNotBefore",
- xcert.getNotBefore().getTime() / 1000);
- rarg.addLongValue("validNotAfter",
- xcert.getNotAfter().getTime() / 1000);
+ rarg.addStringValue("serialNumber",
+ xcert.getSerialNumber().toString(16));
+ rarg.addStringValue("serialNumberDecimal",
+ xcert.getSerialNumber().toString());
+ rarg.addStringValue("subject",
+ xcert.getSubjectDN().toString());
+ rarg.addLongValue("validNotBefore",
+ xcert.getNotBefore().getTime() / 1000);
+ rarg.addLongValue("validNotAfter",
+ xcert.getNotAfter().getTime() / 1000);
argSet.addRepeatRecord(rarg);
}
}
@@ -288,4 +281,3 @@ public class ReasonToRevoke extends CMSServlet {
return;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/RemoteAuthConfig.java b/pki/base/common/src/com/netscape/cms/servlet/cert/RemoteAuthConfig.java
index 9c414b9c..c1d95acf 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/RemoteAuthConfig.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/RemoteAuthConfig.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
@@ -54,7 +53,6 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* Allow agent to turn on/off authentication managers
*
@@ -89,11 +87,11 @@ public class RemoteAuthConfig extends CMSServlet {
/**
* Initializes the servlet.
- *
- * Presence of "auths.enableRemoteConfiguration=true" in CMS.cfg
- * enables remote configuration for authentication plugins.
- * List of remotely set instances can be found in CMS.cfg
- * at "auths.remotelySetInstances=<name1>,<name2>,...,<nameN>"
+ *
+ * Presence of "auths.enableRemoteConfiguration=true" in CMS.cfg enables
+ * remote configuration for authentication plugins. List of remotely set
+ * instances can be found in CMS.cfg at
+ * "auths.remotelySetInstances=<name1>,<name2>,...,<nameN>"
*/
public void init(ServletConfig sc) throws ServletException {
super.init(sc);
@@ -104,7 +102,8 @@ public class RemoteAuthConfig extends CMSServlet {
try {
mEnableRemoteConfiguration = mAuthConfig.getBoolean(ENABLE_REMOTE_CONFIG, false);
} catch (EBaseException eb) {
- // Thanks to design of getBoolean we have to catch but we will never get anything.
+ // Thanks to design of getBoolean we have to catch but we will never
+ // get anything.
}
String remoteList = null;
@@ -112,7 +111,8 @@ public class RemoteAuthConfig extends CMSServlet {
try {
remoteList = mAuthConfig.getString(REMOTELY_SET_INSTANCES, null);
} catch (EBaseException eb) {
- // Thanks to design of getString we have to catch but we will never get anything.
+ // Thanks to design of getString we have to catch but we will never
+ // get anything.
}
if (remoteList != null) {
StringTokenizer s = new StringTokenizer(remoteList, ",");
@@ -133,16 +133,10 @@ public class RemoteAuthConfig extends CMSServlet {
/**
* Serves HTTPS request. The format of this request is as follows:
- * https://host:ee-port/remoteAuthConfig?
- * op="add"|"delete"&
- * instance=<instanceName>&
- * of=<authPluginName>&
- * host=<hostName>&
- * port=<portNumber>&
- * password=<password>&
- * [adminDN=<adminDN>]&
- * [uid=<uid>]&
- * [baseDN=<baseDN>]
+ * https://host:ee-port/remoteAuthConfig? op="add"|"delete"&
+ * instance=<instanceName>& of=<authPluginName>& host=<hostName>&
+ * port=<portNumber>& password=<password>& [adminDN=<adminDN>]& [uid=<uid>]&
+ * [baseDN=<baseDN>]
*/
public void process(CMSRequest cmsReq) throws EBaseException {
HttpServletRequest req = cmsReq.getHttpReq();
@@ -201,7 +195,7 @@ public class RemoteAuthConfig extends CMSServlet {
}
} else {
header.addStringValue("error", "Unknown instance " +
- instance + ".");
+ instance + ".");
}
} else {
header.addStringValue("error", "Unknown plugin name: " + plugin);
@@ -217,7 +211,7 @@ public class RemoteAuthConfig extends CMSServlet {
}
if (isInstanceListed(instance)) {
header.addStringValue("error", "Instance name " +
- instance + " is already in use.");
+ instance + " is already in use.");
} else {
errMsg = addInstance(instance, plugin,
host, port, baseDN,
@@ -253,7 +247,7 @@ public class RemoteAuthConfig extends CMSServlet {
} catch (IOException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
try {
@@ -263,15 +257,15 @@ public class RemoteAuthConfig extends CMSServlet {
form.renderOutput(out, argSet);
cmsReq.setStatus(CMSRequest.SUCCESS);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
}
private String authenticateRemoteAdmin(String host, String port,
- String adminDN, String password) {
+ String adminDN, String password) {
if (host == null || host.length() == 0) {
return "Missing host name.";
}
@@ -339,13 +333,11 @@ public class RemoteAuthConfig extends CMSServlet {
} catch (LDAPException e) {
/*
- switch (e.getLDAPResultCode()) {
- case LDAPException.NO_SUCH_OBJECT:
- case LDAPException.INVALID_CREDENTIALS:
- case LDAPException.INSUFFICIENT_ACCESS_RIGHTS:
- case LDAPException.LDAP_PARTIAL_RESULTS:
- default:
- }
+ * switch (e.getLDAPResultCode()) { case
+ * LDAPException.NO_SUCH_OBJECT: case
+ * LDAPException.INVALID_CREDENTIALS: case
+ * LDAPException.INSUFFICIENT_ACCESS_RIGHTS: case
+ * LDAPException.LDAP_PARTIAL_RESULTS: default: }
*/
c.disconnect();
return "LDAP error: " + e.toString();
@@ -362,8 +354,8 @@ public class RemoteAuthConfig extends CMSServlet {
}
private String authenticateRemoteAdmin(String host, String port,
- String uid, String baseDN,
- String password) {
+ String uid, String baseDN,
+ String password) {
if (host == null || host.length() == 0) {
return "Missing host name.";
}
@@ -473,8 +465,8 @@ public class RemoteAuthConfig extends CMSServlet {
}
private String addInstance(String instance, String plugin,
- String host, String port,
- String baseDN, String dnPattern) {
+ String host, String port,
+ String baseDN, String dnPattern) {
if (host == null || host.length() == 0) {
return "Missing host name.";
}
@@ -516,7 +508,8 @@ public class RemoteAuthConfig extends CMSServlet {
StringBuffer list = new StringBuffer();
for (int i = 0; i < mRemotelySetInstances.size(); i++) {
- if (i > 0) list.append(",");
+ if (i > 0)
+ list.append(",");
list.append((String) mRemotelySetInstances.elementAt(i));
}
@@ -542,7 +535,8 @@ public class RemoteAuthConfig extends CMSServlet {
StringBuffer list = new StringBuffer();
for (int i = 0; i < mRemotelySetInstances.size(); i++) {
- if (i > 0) list.append(",");
+ if (i > 0)
+ list.append(",");
list.append((String) mRemotelySetInstances.elementAt(i));
}
@@ -602,17 +596,21 @@ public class RemoteAuthConfig extends CMSServlet {
int y = now.get(Calendar.YEAR);
String name = "R" + y;
- if (now.get(Calendar.MONTH) < 10) name += "0";
+ if (now.get(Calendar.MONTH) < 10)
+ name += "0";
name += now.get(Calendar.MONTH);
- if (now.get(Calendar.DAY_OF_MONTH) < 10) name += "0";
+ if (now.get(Calendar.DAY_OF_MONTH) < 10)
+ name += "0";
name += now.get(Calendar.DAY_OF_MONTH);
- if (now.get(Calendar.HOUR_OF_DAY) < 10) name += "0";
+ if (now.get(Calendar.HOUR_OF_DAY) < 10)
+ name += "0";
name += now.get(Calendar.HOUR_OF_DAY);
- if (now.get(Calendar.MINUTE) < 10) name += "0";
+ if (now.get(Calendar.MINUTE) < 10)
+ name += "0";
name += now.get(Calendar.MINUTE);
- if (now.get(Calendar.SECOND) < 10) name += "0";
+ if (now.get(Calendar.SECOND) < 10)
+ name += "0";
name += now.get(Calendar.SECOND);
return name;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/RenewalServlet.java b/pki/base/common/src/com/netscape/cms/servlet/cert/RenewalServlet.java
index 050dd36d..e603103a 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/RenewalServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/RenewalServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.io.IOException;
import java.math.BigInteger;
import java.security.cert.CertificateException;
@@ -59,7 +58,7 @@ import com.netscape.cms.servlet.common.ICMSTemplateFiller;
/**
* Certificate Renewal
- *
+ *
* @version $Revision$, $Date$
*/
public class RenewalServlet extends CMSServlet {
@@ -69,29 +68,27 @@ public class RenewalServlet extends CMSServlet {
private static final long serialVersionUID = -3094124661102395244L;
// renewal templates.
- public static final String
- RENEWAL_SUCCESS_TEMPLATE = "RenewalSuccess.template";
+ public static final String RENEWAL_SUCCESS_TEMPLATE = "RenewalSuccess.template";
- // http params
+ // http params
public static final String CERT_TYPE = "certType";
public static final String SERIAL_NO = "serialNo";
- // XXX can't do pkcs10 cause it's got no serial no.
+ // XXX can't do pkcs10 cause it's got no serial no.
// (unless put serial no in pki attributes)
- // public static final String PKCS10 = "pkcs10";
+ // public static final String PKCS10 = "pkcs10";
public static final String IMPORT_CERT = "importCert";
private String mRenewalSuccessTemplate = RENEWAL_SUCCESS_TEMPLATE;
- private ICMSTemplateFiller
- mRenewalSuccessFiller = new ImportCertsTemplateFiller();
+ private ICMSTemplateFiller mRenewalSuccessFiller = new ImportCertsTemplateFiller();
public RenewalServlet() {
super();
}
/**
- * initialize the servlet. This servlet makes use of the
- * template file "RenewalSuccess.template" to render the
- * response
+ * initialize the servlet. This servlet makes use of the template file
+ * "RenewalSuccess.template" to render the response
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -103,43 +100,42 @@ public class RenewalServlet extends CMSServlet {
PROP_SUCCESS_TEMPLATE);
if (mRenewalSuccessTemplate == null)
mRenewalSuccessTemplate = RENEWAL_SUCCESS_TEMPLATE;
- String fillername =
- sc.getInitParameter(PROP_SUCCESS_TEMPLATE_FILLER);
+ String fillername =
+ sc.getInitParameter(PROP_SUCCESS_TEMPLATE_FILLER);
if (fillername != null) {
ICMSTemplateFiller filler = newFillerObject(fillername);
- if (filler != null)
+ if (filler != null)
mRenewalSuccessFiller = filler;
}
} catch (Exception e) {
- // this should never happen.
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_IMP_INIT_SERV_ERR", e.toString(),
- mId));
+ // this should never happen.
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_IMP_INIT_SERV_ERR", e.toString(),
+ mId));
}
}
-
/**
- * Process the HTTP request.
- *
+ * Process the HTTP request.
+ *
* @param cmsReq the object holding the request and response information
*/
- protected void process(CMSRequest cmsReq)
- throws EBaseException {
+ protected void process(CMSRequest cmsReq)
+ throws EBaseException {
long startTime = CMS.getCurrentDate().getTime();
IArgBlock httpParams = cmsReq.getHttpParams();
HttpServletRequest httpReq = cmsReq.getHttpReq();
- // renewal requires either:
- // - coming from ee:
- // - old cert from ssl client auth
- // - old certs from auth manager
- // - coming from agent or trusted RA:
- // - serial no of cert to be renewed.
-
+ // renewal requires either:
+ // - coming from ee:
+ // - old cert from ssl client auth
+ // - old certs from auth manager
+ // - coming from agent or trusted RA:
+ // - serial no of cert to be renewed.
+
BigInteger old_serial_no = null;
X509CertImpl old_cert = null;
X509CertImpl renewed_cert = null;
@@ -156,10 +152,10 @@ public class RenewalServlet extends CMSServlet {
mAuthzResourceName, "renew");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -174,7 +170,7 @@ public class RenewalServlet extends CMSServlet {
authToken.getInString(AuthToken.TOKEN_AUTHMGR_INST_NAME);
}
- // coming from agent
+ // coming from agent
if (mAuthMgr != null && mAuthMgr.equals(IAuthSubsystem.CERTUSERDB_AUTHMGR_ID)) {
X509Certificate[] cert = new X509Certificate[1];
@@ -190,7 +186,7 @@ public class RenewalServlet extends CMSServlet {
int endDate = httpParams.getValueAsInt("endDate", -1);
if (beginYear != -1 && beginMonth != -1 && beginDate != -1 &&
- endYear != -1 && endMonth != -1 && endDate != -1) {
+ endYear != -1 && endMonth != -1 && endDate != -1) {
Calendar calendar = Calendar.getInstance();
calendar.set(beginYear, beginMonth, beginDate);
notBefore = calendar.getTime();
@@ -199,7 +195,7 @@ public class RenewalServlet extends CMSServlet {
}
} // coming from client
else {
- // from auth manager
+ // from auth manager
X509CertImpl[] cert = new X509CertImpl[1];
old_serial_no = getCertFromAuthMgr(authToken, cert);
@@ -213,44 +209,44 @@ public class RenewalServlet extends CMSServlet {
X509CertInfo new_certInfo = null;
req = mRequestQueue.newRequest(IRequest.RENEWAL_REQUEST);
- req.setExtData(IRequest.OLD_SERIALS, new BigInteger[] {old_serial_no});
+ req.setExtData(IRequest.OLD_SERIALS, new BigInteger[] { old_serial_no });
if (old_cert != null) {
req.setExtData(IRequest.OLD_CERTS,
- new X509CertImpl[] { old_cert }
- );
- // create new certinfo from old_cert contents.
+ new X509CertImpl[] { old_cert }
+ );
+ // create new certinfo from old_cert contents.
X509CertInfo old_certInfo = (X509CertInfo)
- ((X509CertImpl) old_cert).get(
- X509CertImpl.NAME + "." + X509CertImpl.INFO);
+ ((X509CertImpl) old_cert).get(
+ X509CertImpl.NAME + "." + X509CertImpl.INFO);
new_certInfo = new X509CertInfo(old_certInfo.getEncodedInfo());
} else {
- // if no old cert (came from RA agent) create new cert info
- // (serializable) to pass through policies. And set the old
+ // if no old cert (came from RA agent) create new cert info
+ // (serializable) to pass through policies. And set the old
// serial number to pick up.
new_certInfo = new CertInfo();
- new_certInfo.set(X509CertInfo.SERIAL_NUMBER,
- new CertificateSerialNumber(old_serial_no));
+ new_certInfo.set(X509CertInfo.SERIAL_NUMBER,
+ new CertificateSerialNumber(old_serial_no));
}
-
+
if (notBefore == null || notAfter == null) {
notBefore = new Date(0);
notAfter = new Date(0);
}
- new_certInfo.set(X509CertInfo.VALIDITY,
- new CertificateValidity(notBefore, notAfter));
+ new_certInfo.set(X509CertInfo.VALIDITY,
+ new CertificateValidity(notBefore, notAfter));
req.setExtData(IRequest.CERT_INFO, new X509CertInfo[] { new_certInfo }
- );
+ );
} catch (CertificateException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_SETTING_RENEWAL_VALIDITY_1", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERROR_SETTING_RENEWAL_VALIDITY_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SETTING_RENEWAL_VALIDITY_ERROR"));
+ CMS.getUserMessage("CMS_GW_SETTING_RENEWAL_VALIDITY_ERROR"));
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_SETTING_RENEWAL_VALIDITY_1", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERROR_SETTING_RENEWAL_VALIDITY_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SETTING_RENEWAL_VALIDITY_ERROR"));
+ CMS.getUserMessage("CMS_GW_SETTING_RENEWAL_VALIDITY_ERROR"));
}
saveHttpHeaders(httpReq, req);
@@ -259,7 +255,7 @@ public class RenewalServlet extends CMSServlet {
saveAuthToken(authToken, req);
cmsReq.setIRequest(req);
- // send request to request queue.
+ // send request to request queue.
mRequestQueue.processRequest(req);
// for audit log
@@ -269,12 +265,12 @@ public class RenewalServlet extends CMSServlet {
if (mAuthMgr != null && mAuthMgr.equals(IAuthSubsystem.CERTUSERDB_AUTHMGR_ID)) {
agentID = authToken.getInString("userid");
initiative = AuditFormat.FROMAGENT + " agentID: " + agentID;
- }else {
+ } else {
// request is from eegateway, so fromUser.
initiative = AuditFormat.FROMUSER;
}
- // check resulting status
+ // check resulting status
RequestStatus status = req.getRequestStatus();
if (status != RequestStatus.COMPLETE) {
@@ -292,92 +288,92 @@ public class RenewalServlet extends CMSServlet {
wholeMsg.append(msgs.nextElement());
}
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.RENEWALFORMAT,
- new Object[] {
- req.getRequestId(),
- initiative,
- authMgr,
- status.toString(),
- old_cert.getSubjectDN(),
- old_cert.getSerialNumber().toString(16),
- "violation: " +
- wholeMsg.toString()}
- // wholeMsg},
- // ILogger.L_MULTILINE
- );
+ mLogger.log(ILogger.EV_AUDIT,
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.RENEWALFORMAT,
+ new Object[] {
+ req.getRequestId(),
+ initiative,
+ authMgr,
+ status.toString(),
+ old_cert.getSubjectDN(),
+ old_cert.getSerialNumber().toString(16),
+ "violation: " +
+ wholeMsg.toString() }
+ // wholeMsg},
+ // ILogger.L_MULTILINE
+ );
} else { // no policy violation, from agent
mLogger.log(ILogger.EV_AUDIT,
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.RENEWALFORMAT,
+ new Object[] {
+ req.getRequestId(),
+ initiative,
+ authMgr,
+ status.toString(),
+ old_cert.getSubjectDN(),
+ old_cert.getSerialNumber().toString(16),
+ "" }
+ );
+ }
+ } else { // other imcomplete status
+ mLogger.log(ILogger.EV_AUDIT,
ILogger.S_OTHER,
AuditFormat.LEVEL,
AuditFormat.RENEWALFORMAT,
new Object[] {
- req.getRequestId(),
- initiative,
- authMgr,
- status.toString(),
- old_cert.getSubjectDN(),
- old_cert.getSerialNumber().toString(16),
- "" }
- );
- }
- } else { // other imcomplete status
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.RENEWALFORMAT,
- new Object[] {
- req.getRequestId(),
- initiative,
- authMgr,
- status.toString(),
- old_cert.getSubjectDN(),
- old_cert.getSerialNumber().toString(16),
- "" }
- );
+ req.getRequestId(),
+ initiative,
+ authMgr,
+ status.toString(),
+ old_cert.getSubjectDN(),
+ old_cert.getSerialNumber().toString(16),
+ "" }
+ );
}
return;
}
- // service error
+ // service error
Integer result = req.getExtDataInInteger(IRequest.RESULT);
CMS.debug(
- "RenewalServlet: Result for request " + req.getRequestId() + " is " + result);
+ "RenewalServlet: Result for request " + req.getRequestId() + " is " + result);
if (result.equals(IRequest.RES_ERROR)) {
CMS.debug(
- "RenewalServlet: Result for request " + req.getRequestId() + " is error.");
+ "RenewalServlet: Result for request " + req.getRequestId() + " is error.");
cmsReq.setStatus(CMSRequest.ERROR);
cmsReq.setError(req.getExtDataInString(IRequest.ERROR));
String[] svcErrors =
- req.getExtDataInStringArray(IRequest.SVCERRORS);
+ req.getExtDataInStringArray(IRequest.SVCERRORS);
if (svcErrors != null && svcErrors.length > 0) {
for (int i = 0; i < svcErrors.length; i++) {
String err = svcErrors[i];
if (err != null) {
- //System.out.println(
- //"revocation servlet: setting error description "+
- //err.toString());
+ // System.out.println(
+ // "revocation servlet: setting error description "+
+ // err.toString());
cmsReq.setErrorDescription(err);
mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.RENEWALFORMAT,
- new Object[] {
- req.getRequestId(),
- initiative,
- authMgr,
- "completed with error: " +
- err,
- old_cert.getSubjectDN(),
- old_cert.getSerialNumber().toString(16),
- "" }
- );
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.RENEWALFORMAT,
+ new Object[] {
+ req.getRequestId(),
+ initiative,
+ authMgr,
+ "completed with error: " +
+ err,
+ old_cert.getSubjectDN(),
+ old_cert.getSerialNumber().toString(16),
+ "" }
+ );
}
}
@@ -393,31 +389,31 @@ public class RenewalServlet extends CMSServlet {
long endTime = CMS.getCurrentDate().getTime();
mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.RENEWALFORMAT,
- new Object[] {
- req.getRequestId(),
- initiative,
- authMgr,
- "completed",
- old_cert.getSubjectDN(),
- old_cert.getSerialNumber().toString(16),
- "new serial number: 0x" +
- renewed_cert.getSerialNumber().toString(16) + " time: " + (endTime - startTime)}
- );
+ AuditFormat.LEVEL,
+ AuditFormat.RENEWALFORMAT,
+ new Object[] {
+ req.getRequestId(),
+ initiative,
+ authMgr,
+ "completed",
+ old_cert.getSubjectDN(),
+ old_cert.getSerialNumber().toString(16),
+ "new serial number: 0x" +
+ renewed_cert.getSerialNumber().toString(16) + " time: " + (endTime - startTime) }
+ );
return;
}
private void respondSuccess(
- CMSRequest cmsReq, X509CertImpl renewed_cert)
- throws EBaseException {
- cmsReq.setResult(new X509CertImpl[] {renewed_cert}
- );
+ CMSRequest cmsReq, X509CertImpl renewed_cert)
+ throws EBaseException {
+ cmsReq.setResult(new X509CertImpl[] { renewed_cert }
+ );
cmsReq.setStatus(CMSRequest.SUCCESS);
- // check if cert should be imported.
- // browser must have input type set to nav or cartman since
+ // check if cert should be imported.
+ // browser must have input type set to nav or cartman since
// there's no other way to tell
IArgBlock httpParams = cmsReq.getHttpParams();
@@ -425,45 +421,45 @@ public class RenewalServlet extends CMSServlet {
String certType = httpParams.getValueAsString(CERT_TYPE, "client");
String agent = httpReq.getHeader("user-agent");
- if (checkImportCertToNav(cmsReq.getHttpResp(),
+ if (checkImportCertToNav(cmsReq.getHttpResp(),
httpParams, renewed_cert)) {
return;
} else {
try {
- renderTemplate(cmsReq,
- mRenewalSuccessTemplate, mRenewalSuccessFiller);
+ renderTemplate(cmsReq,
+ mRenewalSuccessTemplate, mRenewalSuccessFiller);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGE_ERROR_DISPLAY_TEMPLATE_1",
- mRenewalSuccessTemplate, e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGE_ERROR_DISPLAY_TEMPLATE_1",
+ mRenewalSuccessTemplate, e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
}
return;
}
- protected BigInteger getRenewedCert(ICertRecord certRec)
- throws EBaseException {
+ protected BigInteger getRenewedCert(ICertRecord certRec)
+ throws EBaseException {
BigInteger renewedCert = null;
String serial = null;
- MetaInfo meta = certRec.getMetaInfo();
+ MetaInfo meta = certRec.getMetaInfo();
if (meta == null) {
- log(ILogger.LL_INFO,
- "no meta info in cert serial 0x" + certRec.getSerialNumber().toString(16));
+ log(ILogger.LL_INFO,
+ "no meta info in cert serial 0x" + certRec.getSerialNumber().toString(16));
return null;
}
serial = (String) meta.get(ICertRecord.META_RENEWED_CERT);
if (serial == null) {
- log(ILogger.LL_INFO,
- "no renewed cert in cert 0x" + certRec.getSerialNumber().toString(16));
+ log(ILogger.LL_INFO,
+ "no renewed cert in cert 0x" + certRec.getSerialNumber().toString(16));
return null;
}
renewedCert = new BigInteger(serial);
- log(ILogger.LL_INFO,
- "renewed cert serial 0x" + renewedCert.toString(16) + "found for 0x" +
- certRec.getSerialNumber().toString(16));
+ log(ILogger.LL_INFO,
+ "renewed cert serial 0x" + renewedCert.toString(16) + "found for 0x" +
+ certRec.getSerialNumber().toString(16));
return renewedCert;
}
@@ -471,27 +467,27 @@ public class RenewalServlet extends CMSServlet {
* get certs to renew from agent.
*/
private BigInteger getCertFromAgent(
- IArgBlock httpParams, X509Certificate[] certContainer)
- throws EBaseException {
+ IArgBlock httpParams, X509Certificate[] certContainer)
+ throws EBaseException {
BigInteger serialno = null;
X509Certificate cert = null;
// get serial no
serialno = httpParams.getValueAsBigInteger(SERIAL_NO, null);
if (serialno == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_MISSING_SERIALNO_FOR_RENEW"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_MISSING_SERIALNO_FOR_RENEW"));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_MISSING_SERIALNO_FOR_RENEW"));
+ CMS.getUserMessage("CMS_GW_MISSING_SERIALNO_FOR_RENEW"));
}
// get cert from db if we're cert authority.
if (mAuthority instanceof ICertificateAuthority) {
cert = getX509Certificate(serialno);
if (cert == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_MISSING_SERIALNO_FOR_RENEW_1", serialno.toString(16)));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_MISSING_SERIALNO_FOR_RENEW_1", serialno.toString(16)));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_INVALID_CERT_FOR_RENEWAL"));
+ CMS.getUserMessage("CMS_GW_INVALID_CERT_FOR_RENEWAL"));
}
}
certContainer[0] = cert;
@@ -502,23 +498,23 @@ public class RenewalServlet extends CMSServlet {
* get cert to renew from auth manager
*/
private BigInteger getCertFromAuthMgr(
- IAuthToken authToken, X509Certificate[] certContainer)
- throws EBaseException {
+ IAuthToken authToken, X509Certificate[] certContainer)
+ throws EBaseException {
X509CertImpl cert =
- authToken.getInCert(AuthToken.TOKEN_CERT);
+ authToken.getInCert(AuthToken.TOKEN_CERT);
if (cert == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_MISSING_CERTS_RENEW_FROM_AUTHMGR"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_MISSING_CERTS_RENEW_FROM_AUTHMGR"));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_MISSING_CERTS_RENEW_FROM_AUTHMGR"));
+ CMS.getUserMessage("CMS_GW_MISSING_CERTS_RENEW_FROM_AUTHMGR"));
}
- if (mAuthority instanceof ICertificateAuthority &&
- !isCertFromCA(cert)) {
+ if (mAuthority instanceof ICertificateAuthority &&
+ !isCertFromCA(cert)) {
log(ILogger.LL_FAILURE, "certficate from auth manager for " +
- " renewal is not from this ca.");
+ " renewal is not from this ca.");
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_INVALID_CERT_FOR_RENEWAL"));
+ CMS.getUserMessage("CMS_GW_INVALID_CERT_FOR_RENEWAL"));
}
certContainer[0] = cert;
BigInteger serialno = ((X509Certificate) cert).getSerialNumber();
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/RevocationServlet.java b/pki/base/common/src/com/netscape/cms/servlet/cert/RevocationServlet.java
index 9b39acc7..78d2b8b9 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/RevocationServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/RevocationServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.io.IOException;
import java.math.BigInteger;
import java.security.cert.CertificateEncodingException;
@@ -57,10 +56,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* Perform the first step in revoking a certificate
- *
+ *
* @version $Revision$, $Date$
*/
public class RevocationServlet extends CMSServlet {
@@ -72,11 +70,11 @@ public class RevocationServlet extends CMSServlet {
// revocation templates.
private final static String TPL_FILE = "reasonToRevoke.template";
- // http params
+ // http params
public static final String SERIAL_NO = "serialNo";
- // XXX can't do pkcs10 cause it's got no serial no.
+ // XXX can't do pkcs10 cause it's got no serial no.
// (unless put serial no in pki attributes)
- // public static final String PKCS10 = "pkcs10";
+ // public static final String PKCS10 = "pkcs10";
public static final String REASON_CODE = "reasonCode";
private String mFormPath = null;
@@ -85,15 +83,14 @@ public class RevocationServlet extends CMSServlet {
private Random mRandom = null;
private Nonces mNonces = null;
-
public RevocationServlet() {
super();
}
/**
- * initialize the servlet. This servlet uses
- * the template file "reasonToRevoke.template" to render the
- * result.
+ * initialize the servlet. This servlet uses the template file
+ * "reasonToRevoke.template" to render the result.
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -115,7 +112,7 @@ public class RevocationServlet extends CMSServlet {
}
}
- // set to false by revokeByDN=false in web.xml
+ // set to false by revokeByDN=false in web.xml
mRevokeByDN = false;
String tmp = sc.getInitParameter(PROP_REVOKEBYDN);
@@ -127,28 +124,27 @@ public class RevocationServlet extends CMSServlet {
}
}
-
/**
- * Process the HTTP request. Note that this servlet does not
- * actually perform the certificate revocation. This is the first
- * step in the multi-step revocation process. (the next step is
- * in the ReasonToRevoke servlet.
- *
+ * Process the HTTP request. Note that this servlet does not actually
+ * perform the certificate revocation. This is the first step in the
+ * multi-step revocation process. (the next step is in the ReasonToRevoke
+ * servlet.
+ *
* @param cmsReq the object holding the request and response information
*/
- protected void process(CMSRequest cmsReq)
- throws EBaseException {
+ protected void process(CMSRequest cmsReq)
+ throws EBaseException {
IArgBlock httpParams = cmsReq.getHttpParams();
HttpServletRequest httpReq = cmsReq.getHttpReq();
HttpServletResponse httpResp = cmsReq.getHttpResp();
- // revocation requires either:
- // - coming from ee:
- // - old cert from ssl client auth
- // - old certs from auth manager
- // - coming from agent or trusted RA:
- // - serial no of cert to be revoked.
-
+ // revocation requires either:
+ // - coming from ee:
+ // - old cert from ssl client auth
+ // - old certs from auth manager
+ // - coming from agent or trusted RA:
+ // - serial no of cert to be revoked.
+
BigInteger old_serial_no = null;
X509CertImpl old_cert = null;
String revokeAll = null;
@@ -159,10 +155,10 @@ public class RevocationServlet extends CMSServlet {
try {
form = getTemplate(mFormPath, httpReq, locale);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
IArgBlock header = CMS.createArgBlock();
@@ -178,18 +174,18 @@ public class RevocationServlet extends CMSServlet {
mAuthzResourceName, "submit");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
cmsReq.setStatus(CMSRequest.UNAUTHORIZED);
return;
}
-
- // coming from agent
+
+ // coming from agent
if (mAuthMgr != null && mAuthMgr.equals(IAuthSubsystem.CERTUSERDB_AUTHMGR_ID)) {
X509Certificate[] cert = new X509Certificate[1];
@@ -197,22 +193,24 @@ public class RevocationServlet extends CMSServlet {
old_cert = (X509CertImpl) cert[0];
} // coming from client
else {
- // from auth manager
+ // from auth manager
X509CertImpl[] cert = new X509CertImpl[1];
-
+
old_serial_no = getCertFromAuthMgr(authToken, cert);
old_cert = cert[0];
}
header.addStringValue("serialNumber", old_cert.getSerialNumber().toString(16));
header.addStringValue("serialNumberDecimal", old_cert.getSerialNumber().toString());
- // header.addStringValue("subject", old_cert.getSubjectDN().toString());
- // header.addLongValue("validNotBefore", old_cert.getNotBefore().getTime()/1000);
- // header.addLongValue("validNotAfter", old_cert.getNotAfter().getTime()/1000);
+ // header.addStringValue("subject", old_cert.getSubjectDN().toString());
+ // header.addLongValue("validNotBefore",
+ // old_cert.getNotBefore().getTime()/1000);
+ // header.addLongValue("validNotAfter",
+ // old_cert.getNotAfter().getTime()/1000);
if (mNonces != null) {
long n = mRandom.nextLong();
- long m = mNonces.addNonce(n, (X509Certificate)old_cert);
+ long m = mNonces.addNonce(n, (X509Certificate) old_cert);
if ((n + m) != 0) {
header.addStringValue("nonce", Long.toString(m));
}
@@ -229,12 +227,12 @@ public class RevocationServlet extends CMSServlet {
} else if (mAuthority instanceof IRegistrationAuthority) {
IRequest req = mRequestQueue.newRequest(IRequest.GETCERTS_REQUEST);
String filter = "(&(" + ICertRecord.ATTR_X509CERT + "." +
- X509CertInfo.SUBJECT + "=" +
- old_cert.getSubjectDN().toString() + ")(|(" +
- ICertRecord.ATTR_CERT_STATUS + "=" +
- ICertRecord.STATUS_VALID + ")(" +
- ICertRecord.ATTR_CERT_STATUS + "=" +
- ICertRecord.STATUS_EXPIRED + ")))";
+ X509CertInfo.SUBJECT + "=" +
+ old_cert.getSubjectDN().toString() + ")(|(" +
+ ICertRecord.ATTR_CERT_STATUS + "=" +
+ ICertRecord.STATUS_VALID + ")(" +
+ ICertRecord.ATTR_CERT_STATUS + "=" +
+ ICertRecord.STATUS_EXPIRED + ")))";
req.setExtData(IRequest.CERT_FILTER, filter);
mRequestQueue.processRequest(req);
@@ -271,8 +269,8 @@ public class RevocationServlet extends CMSServlet {
if (!noInfo && (certsToRevoke == null || certsToRevoke.length == 0 ||
(!authorized))) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CA_CERT_ALREADY_REVOKED_1", old_serial_no.toString(16)));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CA_CERT_ALREADY_REVOKED_1", old_serial_no.toString(16)));
throw new ECMSGWException(CMS.getUserMessage("CMS_GW_CERT_ALREADY_REVOKED"));
}
@@ -296,15 +294,15 @@ public class RevocationServlet extends CMSServlet {
IArgBlock rarg = CMS.createArgBlock();
rarg.addStringValue("serialNumber",
- certsToRevoke[i].getSerialNumber().toString(16));
+ certsToRevoke[i].getSerialNumber().toString(16));
rarg.addStringValue("serialNumberDecimal",
- certsToRevoke[i].getSerialNumber().toString());
+ certsToRevoke[i].getSerialNumber().toString());
rarg.addStringValue("subject",
- certsToRevoke[i].getSubjectDN().toString());
+ certsToRevoke[i].getSubjectDN().toString());
rarg.addLongValue("validNotBefore",
- certsToRevoke[i].getNotBefore().getTime() / 1000);
+ certsToRevoke[i].getNotBefore().getTime() / 1000);
rarg.addLongValue("validNotAfter",
- certsToRevoke[i].getNotAfter().getTime() / 1000);
+ certsToRevoke[i].getNotAfter().getTime() / 1000);
argSet.addRepeatRecord(rarg);
}
} else {
@@ -313,7 +311,7 @@ public class RevocationServlet extends CMSServlet {
}
// set revocation reason, default to unspecified if not set.
- int reasonCode = httpParams.getValueAsInt(REASON_CODE, 0);
+ int reasonCode = httpParams.getValueAsInt(REASON_CODE, 0);
header.addIntegerValue("reason", reasonCode);
@@ -324,10 +322,10 @@ public class RevocationServlet extends CMSServlet {
form.renderOutput(out, argSet);
cmsReq.setStatus(CMSRequest.SUCCESS);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_OUT_STREAM_TEMPLATE", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_OUT_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
return;
@@ -337,28 +335,28 @@ public class RevocationServlet extends CMSServlet {
* get cert to revoke from agent.
*/
private BigInteger getCertFromAgent(
- IArgBlock httpParams, X509Certificate[] certContainer)
- throws EBaseException {
+ IArgBlock httpParams, X509Certificate[] certContainer)
+ throws EBaseException {
BigInteger serialno = null;
X509Certificate cert = null;
// get serial no
serialno = httpParams.getValueAsBigInteger(SERIAL_NO, null);
if (serialno == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_MISSING_SERIALNO_FOR_REVOKE"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_MISSING_SERIALNO_FOR_REVOKE"));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_MISSING_SERIALNO_FOR_REVOKE"));
+ CMS.getUserMessage("CMS_GW_MISSING_SERIALNO_FOR_REVOKE"));
}
// get cert from db if we're cert authority.
if (mAuthority instanceof ICertificateAuthority) {
cert = getX509Certificate(serialno);
if (cert == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_INVALID_CERT_FOR_REVOCATION"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_INVALID_CERT_FOR_REVOCATION"));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_INVALID_CERT_FOR_REVOCATION"));
+ CMS.getUserMessage("CMS_GW_INVALID_CERT_FOR_REVOCATION"));
}
}
certContainer[0] = cert;
@@ -369,22 +367,22 @@ public class RevocationServlet extends CMSServlet {
* get cert to revoke from auth manager
*/
private BigInteger getCertFromAuthMgr(
- IAuthToken authToken, X509Certificate[] certContainer)
- throws EBaseException {
+ IAuthToken authToken, X509Certificate[] certContainer)
+ throws EBaseException {
X509CertImpl cert =
- authToken.getInCert(AuthToken.TOKEN_CERT);
+ authToken.getInCert(AuthToken.TOKEN_CERT);
if (cert == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_MISSING_CERTS_REVOKE_FROM_AUTHMGR"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_MISSING_CERTS_REVOKE_FROM_AUTHMGR"));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_MISSING_CERTS_REVOKE_FROM_AUTHMGR"));
+ CMS.getUserMessage("CMS_GW_MISSING_CERTS_REVOKE_FROM_AUTHMGR"));
}
- if (mAuthority instanceof ICertificateAuthority &&
- !isCertFromCA(cert)) {
+ if (mAuthority instanceof ICertificateAuthority &&
+ !isCertFromCA(cert)) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_INVALID_CERT_FOR_REVOCATION"));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_INVALID_CERT_FOR_REVOCATION"));
+ CMS.getUserMessage("CMS_GW_INVALID_CERT_FOR_REVOCATION"));
}
certContainer[0] = cert;
BigInteger serialno = ((X509Certificate) cert).getSerialNumber();
@@ -393,4 +391,3 @@ public class RevocationServlet extends CMSServlet {
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/RevocationSuccessTemplateFiller.java b/pki/base/common/src/com/netscape/cms/servlet/cert/RevocationSuccessTemplateFiller.java
index 3a571d44..bd983a6c 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/RevocationSuccessTemplateFiller.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/RevocationSuccessTemplateFiller.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
@@ -31,21 +30,13 @@ import com.netscape.cms.servlet.common.CMSRequest;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ICMSTemplateFiller;
-
/**
- * Certificates Template filler.
- * must have list of certificates in result.
- * looks at inputs: certtype.
- * outputs:
- * - cert type from http input (if any)
- * - CA chain
- * - authority name (RM, CM, DRM)
- * - scheme:host:port of server.
- * array of one or more
- * - cert serial number
- * - cert pretty print
- * - cert in base 64 encoding.
- * - cmmf blob to import
+ * Certificates Template filler. must have list of certificates in result. looks
+ * at inputs: certtype. outputs: - cert type from http input (if any) - CA chain
+ * - authority name (RM, CM, DRM) - scheme:host:port of server. array of one or
+ * more - cert serial number - cert pretty print - cert in base 64 encoding. -
+ * cmmf blob to import
+ *
* @version $Revision$, $Date$
*/
class RevocationSuccessTemplateFiller implements ICMSTemplateFiller {
@@ -61,12 +52,12 @@ class RevocationSuccessTemplateFiller implements ICMSTemplateFiller {
* @param e unexpected exception e. ignored.
*/
public CMSTemplateParams getTemplateParams(
- CMSRequest cmsReq, IAuthority authority, Locale locale, Exception e)
- throws Exception {
+ CMSRequest cmsReq, IAuthority authority, Locale locale, Exception e)
+ throws Exception {
IArgBlock fixed = CMS.createArgBlock();
CMSTemplateParams params = new CMSTemplateParams(null, fixed);
- // set host name and port.
+ // set host name and port.
HttpServletRequest httpReq = cmsReq.getHttpReq();
String host = httpReq.getServerName();
int port = httpReq.getServerPort();
@@ -77,15 +68,15 @@ class RevocationSuccessTemplateFiller implements ICMSTemplateFiller {
fixed.set(ICMSTemplateFiller.SCHEME, scheme);
// this authority
- fixed.set(ICMSTemplateFiller.AUTHORITY,
- (String) authority.getOfficialName());
+ fixed.set(ICMSTemplateFiller.AUTHORITY,
+ (String) authority.getOfficialName());
// XXX CA chain.
- RevokedCertImpl[] revoked =
- (RevokedCertImpl[]) cmsReq.getResult();
+ RevokedCertImpl[] revoked =
+ (RevokedCertImpl[]) cmsReq.getResult();
- // revoked certs.
+ // revoked certs.
for (int i = 0; i < revoked.length; i++) {
IArgBlock repeat = CMS.createArgBlock();
@@ -96,4 +87,3 @@ class RevocationSuccessTemplateFiller implements ICMSTemplateFiller {
return params;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/SrchCerts.java b/pki/base/common/src/com/netscape/cms/servlet/cert/SrchCerts.java
index 17bad7a1..dfd735f0 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/SrchCerts.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/SrchCerts.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.io.IOException;
import java.math.BigInteger;
import java.security.PublicKey;
@@ -61,10 +60,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* Search for certificates matching complex query filter
- *
+ *
* @version $Revision$, $Date$
*/
public class SrchCerts extends CMSServlet {
@@ -96,8 +94,9 @@ public class SrchCerts extends CMSServlet {
}
/**
- * initialize the servlet. This servlet uses srchCert.template
- * to render the response
+ * initialize the servlet. This servlet uses srchCert.template to render the
+ * response
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -140,20 +139,20 @@ public class SrchCerts extends CMSServlet {
/* do nothing, just use the default if integer parsing failed */
}
- /* useClientFilter should be off by default. We keep
- this parameter around so that we do not break
- the client applications that submits raw LDAP
- filter into this servlet. */
+ /*
+ * useClientFilter should be off by default. We keep this parameter
+ * around so that we do not break the client applications that submits
+ * raw LDAP filter into this servlet.
+ */
if (sc.getInitParameter("useClientFilter") != null &&
- sc.getInitParameter("useClientFilter").equalsIgnoreCase("true")) {
+ sc.getInitParameter("useClientFilter").equalsIgnoreCase("true")) {
mUseClientFilter = true;
}
}
- private boolean isOn(HttpServletRequest req, String name)
- {
+ private boolean isOn(HttpServletRequest req, String name) {
String inUse = req.getParameter(name);
- if (inUse == null) {
+ if (inUse == null) {
return false;
}
if (inUse.equals("on")) {
@@ -162,10 +161,9 @@ public class SrchCerts extends CMSServlet {
return false;
}
- private boolean isOff(HttpServletRequest req, String name)
- {
+ private boolean isOff(HttpServletRequest req, String name) {
String inUse = req.getParameter(name);
- if (inUse == null) {
+ if (inUse == null) {
return false;
}
if (inUse.equals("off")) {
@@ -174,8 +172,7 @@ public class SrchCerts extends CMSServlet {
return false;
}
- private void buildCertStatusFilter(HttpServletRequest req, StringBuffer filter)
- {
+ private void buildCertStatusFilter(HttpServletRequest req, StringBuffer filter) {
if (!isOn(req, "statusInUse")) {
return;
}
@@ -185,8 +182,7 @@ public class SrchCerts extends CMSServlet {
filter.append(")");
}
- private void buildProfileFilter(HttpServletRequest req, StringBuffer filter)
- {
+ private void buildProfileFilter(HttpServletRequest req, StringBuffer filter) {
if (!isOn(req, "profileInUse")) {
return;
}
@@ -196,16 +192,14 @@ public class SrchCerts extends CMSServlet {
filter.append(")");
}
- private void buildBasicConstraintsFilter(HttpServletRequest req, StringBuffer filter)
- {
+ private void buildBasicConstraintsFilter(HttpServletRequest req, StringBuffer filter) {
if (!isOn(req, "basicConstraintsInUse")) {
return;
}
filter.append("(x509cert.BasicConstraints.isCA=on)");
}
- private void buildSerialNumberRangeFilter(HttpServletRequest req, StringBuffer filter)
- {
+ private void buildSerialNumberRangeFilter(HttpServletRequest req, StringBuffer filter) {
if (!isOn(req, "serialNumberRangeInUse")) {
return;
}
@@ -225,9 +219,8 @@ public class SrchCerts extends CMSServlet {
}
}
- private void buildAVAFilter(HttpServletRequest req, String paramName,
- String avaName, StringBuffer lf, String match)
- {
+ private void buildAVAFilter(HttpServletRequest req, String paramName,
+ String avaName, StringBuffer lf, String match) {
String val = req.getParameter(paramName);
if (val != null && !val.equals("")) {
if (match != null && match.equals("exact")) {
@@ -254,8 +247,7 @@ public class SrchCerts extends CMSServlet {
}
}
- private void buildSubjectFilter(HttpServletRequest req, StringBuffer filter)
- {
+ private void buildSubjectFilter(HttpServletRequest req, StringBuffer filter) {
if (!isOn(req, "subjectInUse")) {
return;
}
@@ -286,9 +278,8 @@ public class SrchCerts extends CMSServlet {
}
}
- private void buildRevokedByFilter(HttpServletRequest req,
- StringBuffer filter)
- {
+ private void buildRevokedByFilter(HttpServletRequest req,
+ StringBuffer filter) {
if (!isOn(req, "revokedByInUse")) {
return;
}
@@ -302,10 +293,9 @@ public class SrchCerts extends CMSServlet {
}
}
- private void buildDateFilter(HttpServletRequest req, String prefix,
+ private void buildDateFilter(HttpServletRequest req, String prefix,
String outStr, long adjustment,
- StringBuffer filter)
- {
+ StringBuffer filter) {
String queryCertFilter = null;
long epoch = 0;
try {
@@ -324,19 +314,17 @@ public class SrchCerts extends CMSServlet {
}
private void buildRevokedOnFilter(HttpServletRequest req,
- StringBuffer filter)
- {
+ StringBuffer filter) {
if (!isOn(req, "revokedOnInUse")) {
return;
}
buildDateFilter(req, "revokedOnFrom", "certRevokedOn>=", 0, filter);
- buildDateFilter(req, "revokedOnTo", "certRevokedOn<=", 86399999,
+ buildDateFilter(req, "revokedOnTo", "certRevokedOn<=", 86399999,
filter);
}
private void buildRevocationReasonFilter(HttpServletRequest req,
- StringBuffer filter)
- {
+ StringBuffer filter) {
if (!isOn(req, "revocationReasonInUse")) {
return;
}
@@ -347,23 +335,22 @@ public class SrchCerts extends CMSServlet {
String queryCertFilter = null;
StringTokenizer st = new StringTokenizer(reasons, ",");
if (st.hasMoreTokens()) {
- filter.append("(|");
- while (st.hasMoreTokens()) {
- String token = st.nextToken();
- if (queryCertFilter == null) {
- queryCertFilter = "";
- }
- filter.append("(x509cert.certRevoInfo=");
- filter.append(token);
- filter.append(")");
- }
- filter.append(")");
+ filter.append("(|");
+ while (st.hasMoreTokens()) {
+ String token = st.nextToken();
+ if (queryCertFilter == null) {
+ queryCertFilter = "";
+ }
+ filter.append("(x509cert.certRevoInfo=");
+ filter.append(token);
+ filter.append(")");
+ }
+ filter.append(")");
}
}
- private void buildIssuedByFilter(HttpServletRequest req,
- StringBuffer filter)
- {
+ private void buildIssuedByFilter(HttpServletRequest req,
+ StringBuffer filter) {
if (!isOn(req, "issuedByInUse")) {
return;
}
@@ -378,43 +365,39 @@ public class SrchCerts extends CMSServlet {
}
private void buildIssuedOnFilter(HttpServletRequest req,
- StringBuffer filter)
- {
+ StringBuffer filter) {
if (!isOn(req, "issuedOnInUse")) {
return;
}
buildDateFilter(req, "issuedOnFrom", "certCreateTime>=", 0, filter);
- buildDateFilter(req, "issuedOnTo", "certCreateTime<=", 86399999,
+ buildDateFilter(req, "issuedOnTo", "certCreateTime<=", 86399999,
filter);
}
private void buildValidNotBeforeFilter(HttpServletRequest req,
- StringBuffer filter)
- {
+ StringBuffer filter) {
if (!isOn(req, "validNotBeforeInUse")) {
return;
}
- buildDateFilter(req, "validNotBeforeFrom", "x509cert.notBefore>=",
+ buildDateFilter(req, "validNotBeforeFrom", "x509cert.notBefore>=",
0, filter);
- buildDateFilter(req, "validNotBeforeTo", "x509cert.notBefore<=",
+ buildDateFilter(req, "validNotBeforeTo", "x509cert.notBefore<=",
86399999, filter);
}
private void buildValidNotAfterFilter(HttpServletRequest req,
- StringBuffer filter)
- {
+ StringBuffer filter) {
if (!isOn(req, "validNotAfterInUse")) {
return;
}
- buildDateFilter(req, "validNotAfterFrom", "x509cert.notAfter>=",
+ buildDateFilter(req, "validNotAfterFrom", "x509cert.notAfter>=",
0, filter);
- buildDateFilter(req, "validNotAfterTo", "x509cert.notAfter<=",
+ buildDateFilter(req, "validNotAfterTo", "x509cert.notAfter<=",
86399999, filter);
}
private void buildValidityLengthFilter(HttpServletRequest req,
- StringBuffer filter)
- {
+ StringBuffer filter) {
if (!isOn(req, "validityLengthInUse")) {
return;
}
@@ -439,8 +422,7 @@ public class SrchCerts extends CMSServlet {
}
private void buildCertTypeFilter(HttpServletRequest req,
- StringBuffer filter)
- {
+ StringBuffer filter) {
if (!isOn(req, "certTypeInUse")) {
return;
}
@@ -471,8 +453,7 @@ public class SrchCerts extends CMSServlet {
}
}
- public String buildFilter(HttpServletRequest req)
- {
+ public String buildFilter(HttpServletRequest req) {
String queryCertFilter = req.getParameter("queryCertFilter");
StringBuffer filter = new StringBuffer();
@@ -504,10 +485,8 @@ public class SrchCerts extends CMSServlet {
/**
* Serves HTTP request. This format of this request is as follows:
- * queryCert?
- * [maxCount=<number>]
- * [queryFilter=<filter>]
- * [revokeAll=<filter>]
+ * queryCert? [maxCount=<number>] [queryFilter=<filter>]
+ * [revokeAll=<filter>]
*/
public void process(CMSRequest cmsReq) throws EBaseException {
HttpServletRequest req = cmsReq.getHttpReq();
@@ -522,10 +501,10 @@ public class SrchCerts extends CMSServlet {
mAuthzResourceName, "list");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -551,10 +530,10 @@ public class SrchCerts extends CMSServlet {
try {
form = getTemplate(mFormPath, req, locale);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
try {
@@ -571,10 +550,10 @@ public class SrchCerts extends CMSServlet {
String queryCertFilter = buildFilter(req);
process(argSet, header, queryCertFilter,
- revokeAll, maxResults, timeLimit, req, resp, locale[0]);
+ revokeAll, maxResults, timeLimit, req, resp, locale[0]);
} catch (NumberFormatException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("BASE_INVALID_NUMBER_FORMAT"));
- error = new EBaseException(CMS.getUserMessage(getLocale(req),"CMS_BASE_INVALID_NUMBER_FORMAT"));
+ error = new EBaseException(CMS.getUserMessage(getLocale(req), "CMS_BASE_INVALID_NUMBER_FORMAT"));
} catch (EBaseException e) {
error = e;
}
@@ -585,33 +564,33 @@ public class SrchCerts extends CMSServlet {
if (error == null) {
String xmlOutput = req.getParameter("xml");
if (xmlOutput != null && xmlOutput.equals("true")) {
- outputXML(resp, argSet);
+ outputXML(resp, argSet);
} else {
- cmsReq.setStatus(CMSRequest.SUCCESS);
- resp.setContentType("text/html");
- form.renderOutput(out, argSet);
+ cmsReq.setStatus(CMSRequest.SUCCESS);
+ resp.setContentType("text/html");
+ form.renderOutput(out, argSet);
}
} else {
cmsReq.setStatus(CMSRequest.ERROR);
cmsReq.setError(error);
}
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_OUT_STREAM_TEMPLATE", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_OUT_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
}
/**
* Process the key search.
*/
- private void process(CMSTemplateParams argSet, IArgBlock header,
- String filter, String revokeAll,
- int maxResults, int timeLimit,
- HttpServletRequest req, HttpServletResponse resp,
- Locale locale)
- throws EBaseException {
+ private void process(CMSTemplateParams argSet, IArgBlock header,
+ String filter, String revokeAll,
+ int maxResults, int timeLimit,
+ HttpServletRequest req, HttpServletResponse resp,
+ Locale locale)
+ throws EBaseException {
try {
long startTime = CMS.getCurrentDate().getTime();
@@ -629,7 +608,7 @@ public class SrchCerts extends CMSServlet {
timeLimit = mTimeLimits;
}
CMS.debug("Start searching ... " + "filter=" + filter + " maxreturns=" + maxResults + " timelimit=" + timeLimit);
- Enumeration<ICertRecord > e = mCertDB.searchCertificates(filter, maxResults, timeLimit);
+ Enumeration<ICertRecord> e = mCertDB.searchCertificates(filter, maxResults, timeLimit);
int count = 0;
@@ -671,7 +650,8 @@ public class SrchCerts extends CMSServlet {
int i = filter.indexOf(CURRENT_TIME, k);
while (i > -1) {
- if (now == null) now = new Date();
+ if (now == null)
+ now = new Date();
newFilter.append(filter.substring(k, i));
newFilter.append(now.getTime());
k = i + CURRENT_TIME.length();
@@ -687,7 +667,7 @@ public class SrchCerts extends CMSServlet {
* Fills cert record into argument block.
*/
private void fillRecordIntoArg(ICertRecord rec, IArgBlock rarg)
- throws EBaseException {
+ throws EBaseException {
X509CertImpl xcert = rec.getCertificate();
@@ -695,9 +675,9 @@ public class SrchCerts extends CMSServlet {
fillX509RecordIntoArg(rec, rarg);
}
}
-
+
private void fillX509RecordIntoArg(ICertRecord rec, IArgBlock rarg)
- throws EBaseException {
+ throws EBaseException {
X509CertImpl cert = rec.getCertificate();
@@ -708,7 +688,7 @@ public class SrchCerts extends CMSServlet {
String subject = (String) cert.getSubjectDN().toString();
if (subject.equals("")) {
- rarg.addStringValue("subject", " ");
+ rarg.addStringValue("subject", " ");
} else {
rarg.addStringValue("subject", subject);
@@ -744,12 +724,13 @@ public class SrchCerts extends CMSServlet {
rarg.addStringValue("signatureAlgorithm", cert.getSigAlgOID());
String issuedBy = rec.getIssuedBy();
- if (issuedBy == null) issuedBy = "";
+ if (issuedBy == null)
+ issuedBy = "";
rarg.addStringValue("issuedBy", issuedBy); // cert.getIssuerDN().toString()
rarg.addLongValue("issuedOn", rec.getCreateTime().getTime() / 1000);
rarg.addStringValue("revokedBy",
- ((rec.getRevokedBy() == null) ? "" : rec.getRevokedBy()));
+ ((rec.getRevokedBy() == null) ? "" : rec.getRevokedBy()));
if (rec.getRevokedOn() == null) {
rarg.addStringValue("revokedOn", null);
} else {
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/UpdateCRL.java b/pki/base/common/src/com/netscape/cms/servlet/cert/UpdateCRL.java
index b10086e1..45544583 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/UpdateCRL.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/UpdateCRL.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.io.IOException;
import java.math.BigInteger;
import java.util.Date;
@@ -60,10 +59,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* Force the CRL to be updated now.
- *
+ *
* @version $Revision$, $Date$
*/
public class UpdateCRL extends CMSServlet {
@@ -88,40 +86,41 @@ public class UpdateCRL extends CMSServlet {
}
/**
- * Initializes the servlet. This servlet uses updateCRL.template
- * to render the result
+ * Initializes the servlet. This servlet uses updateCRL.template to render
+ * the result
*/
public void init(ServletConfig sc) throws ServletException {
super.init(sc);
mFormPath = "/" + mAuthority.getId() + "/" + TPL_FILE;
if (mAuthority instanceof ICertificateAuthority)
mCA = (ICertificateAuthority) mAuthority;
-
- // override success to do output orw own template.
+
+ // override success to do output orw own template.
mTemplates.remove(CMSRequest.SUCCESS);
if (mOutputTemplatePath != null)
mFormPath = mOutputTemplatePath;
}
/**
- * Process the HTTP request.
+ * Process the HTTP request.
* <ul>
* <li>http.param signatureAlgorithm the algorithm to use to sign the CRL
- * <li>http.param waitForUpdate true/false - should the servlet wait until
- * the CRL update is complete?
+ * <li>http.param waitForUpdate true/false - should the servlet wait until
+ * the CRL update is complete?
* <li>http.param clearCRLCache true/false - should the CRL cache cleared
- * before the CRL is generated?
+ * before the CRL is generated?
* <li>http.param crlIssuingPoint the CRL Issuing Point to Update
* </ul>
+ *
* @param cmsReq the object holding the request and response information
*/
public void process(CMSRequest cmsReq) throws EBaseException {
HttpServletRequest req = cmsReq.getHttpReq();
HttpServletResponse resp = cmsReq.getHttpResp();
- IStatsSubsystem statsSub = (IStatsSubsystem)CMS.getSubsystem("stats");
+ IStatsSubsystem statsSub = (IStatsSubsystem) CMS.getSubsystem("stats");
if (statsSub != null) {
- statsSub.startTiming("crl", true /* main action */);
+ statsSub.startTiming("crl", true /* main action */);
}
long startTime = CMS.getCurrentDate().getTime();
@@ -133,16 +132,16 @@ public class UpdateCRL extends CMSServlet {
mAuthzResourceName, "update");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
cmsReq.setStatus(CMSRequest.UNAUTHORIZED);
if (statsSub != null) {
- statsSub.endTiming("crl");
+ statsSub.endTiming("crl");
}
return;
}
@@ -159,21 +158,21 @@ public class UpdateCRL extends CMSServlet {
try {
form = getTemplate(mFormPath, req, locale);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
if (statsSub != null) {
- statsSub.endTiming("crl");
+ statsSub.endTiming("crl");
}
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
try {
- String signatureAlgorithm =
- req.getParameter("signatureAlgorithm");
+ String signatureAlgorithm =
+ req.getParameter("signatureAlgorithm");
- process(argSet, header, req, resp,
- signatureAlgorithm, locale[0]);
+ process(argSet, header, req, resp,
+ signatureAlgorithm, locale[0]);
} catch (EBaseException e) {
error = e;
}
@@ -184,42 +183,43 @@ public class UpdateCRL extends CMSServlet {
if (error == null) {
String xmlOutput = req.getParameter("xml");
if (xmlOutput != null && xmlOutput.equals("true")) {
- outputXML(resp, argSet);
+ outputXML(resp, argSet);
} else {
- resp.setContentType("text/html");
- form.renderOutput(out, argSet);
- cmsReq.setStatus(CMSRequest.SUCCESS);
+ resp.setContentType("text/html");
+ form.renderOutput(out, argSet);
+ cmsReq.setStatus(CMSRequest.SUCCESS);
}
} else {
cmsReq.setStatus(CMSRequest.ERROR);
cmsReq.setError(error);
}
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE",
- e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE",
+ e.toString()));
if (statsSub != null) {
- statsSub.endTiming("crl");
+ statsSub.endTiming("crl");
}
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
if (statsSub != null) {
- statsSub.endTiming("crl");
+ statsSub.endTiming("crl");
}
}
- private CRLExtensions crlEntryExtensions (String reason, String invalidity) {
+ private CRLExtensions crlEntryExtensions(String reason, String invalidity) {
CRLExtensions entryExts = new CRLExtensions();
CRLReasonExtension crlReasonExtn = null;
if (reason != null && reason.length() > 0) {
try {
RevocationReason revReason = RevocationReason.fromInt(Integer.parseInt(reason));
- if (revReason == null) revReason = RevocationReason.UNSPECIFIED;
+ if (revReason == null)
+ revReason = RevocationReason.UNSPECIFIED;
crlReasonExtn = new CRLReasonExtension(revReason);
} catch (Exception e) {
- CMS.debug("Invalid revocation reason: "+reason);
+ CMS.debug("Invalid revocation reason: " + reason);
}
}
@@ -229,15 +229,15 @@ public class UpdateCRL extends CMSServlet {
Date invalidityDate = null;
try {
long backInTime = Long.parseLong(invalidity);
- invalidityDate = new Date(now-(backInTime*60000));
+ invalidityDate = new Date(now - (backInTime * 60000));
} catch (Exception e) {
- CMS.debug("Invalid invalidity time offset: "+invalidity);
+ CMS.debug("Invalid invalidity time offset: " + invalidity);
}
if (invalidityDate != null) {
try {
invalidityDateExtn = new InvalidityDateExtension(invalidityDate);
} catch (Exception e) {
- CMS.debug("Error creating invalidity extension: "+e);
+ CMS.debug("Error creating invalidity extension: " + e);
}
}
}
@@ -246,7 +246,7 @@ public class UpdateCRL extends CMSServlet {
try {
entryExts.set(crlReasonExtn.getName(), crlReasonExtn);
} catch (Exception e) {
- CMS.debug("Error adding revocation reason extension to entry extensions: "+e);
+ CMS.debug("Error adding revocation reason extension to entry extensions: " + e);
}
}
@@ -254,7 +254,7 @@ public class UpdateCRL extends CMSServlet {
try {
entryExts.set(invalidityDateExtn.getName(), invalidityDateExtn);
} catch (Exception e) {
- CMS.debug("Error adding invalidity date extension to entry extensions: "+e);
+ CMS.debug("Error adding invalidity date extension to entry extensions: " + e);
}
}
@@ -293,18 +293,18 @@ public class UpdateCRL extends CMSServlet {
}
private void process(CMSTemplateParams argSet, IArgBlock header,
- HttpServletRequest req,
- HttpServletResponse resp,
- String signatureAlgorithm,
- Locale locale)
- throws EBaseException {
+ HttpServletRequest req,
+ HttpServletResponse resp,
+ String signatureAlgorithm,
+ Locale locale)
+ throws EBaseException {
long startTime = CMS.getCurrentDate().getTime();
- String waitForUpdate =
- req.getParameter("waitForUpdate");
- String clearCache =
- req.getParameter("clearCRLCache");
- String crlIssuingPointId =
- req.getParameter("crlIssuingPoint");
+ String waitForUpdate =
+ req.getParameter("waitForUpdate");
+ String clearCache =
+ req.getParameter("clearCRLCache");
+ String crlIssuingPointId =
+ req.getParameter("crlIssuingPoint");
String test = req.getParameter("test");
String add = req.getParameter("add");
String from = req.getParameter("from");
@@ -317,45 +317,46 @@ public class UpdateCRL extends CMSServlet {
Enumeration<ICRLIssuingPoint> ips = mCA.getCRLIssuingPoints();
while (ips.hasMoreElements()) {
- ICRLIssuingPoint ip = ips.nextElement();
+ ICRLIssuingPoint ip = ips.nextElement();
if (crlIssuingPointId.equals(ip.getId())) {
break;
}
- if (!ips.hasMoreElements()) crlIssuingPointId = null;
+ if (!ips.hasMoreElements())
+ crlIssuingPointId = null;
}
}
if (crlIssuingPointId == null) {
crlIssuingPointId = ICertificateAuthority.PROP_MASTER_CRL;
}
- ICRLIssuingPoint crlIssuingPoint =
- mCA.getCRLIssuingPoint(crlIssuingPointId);
+ ICRLIssuingPoint crlIssuingPoint =
+ mCA.getCRLIssuingPoint(crlIssuingPointId);
header.addStringValue("crlIssuingPoint", crlIssuingPointId);
IPublisherProcessor lpm = mCA.getPublisherProcessor();
if (crlIssuingPoint != null) {
if (clearCache != null && clearCache.equals("true") &&
- crlIssuingPoint.isCRLGenerationEnabled() &&
- crlIssuingPoint.isCRLUpdateInProgress() == ICRLIssuingPoint.CRL_UPDATE_DONE &&
- crlIssuingPoint.isCRLIssuingPointInitialized()
+ crlIssuingPoint.isCRLGenerationEnabled() &&
+ crlIssuingPoint.isCRLUpdateInProgress() == ICRLIssuingPoint.CRL_UPDATE_DONE &&
+ crlIssuingPoint.isCRLIssuingPointInitialized()
== ICRLIssuingPoint.CRL_IP_INITIALIZED) {
crlIssuingPoint.clearCRLCache();
}
if (waitForUpdate != null && waitForUpdate.equals("true") &&
- crlIssuingPoint.isCRLGenerationEnabled() &&
- crlIssuingPoint.isCRLUpdateInProgress() == ICRLIssuingPoint.CRL_UPDATE_DONE &&
- crlIssuingPoint.isCRLIssuingPointInitialized()
+ crlIssuingPoint.isCRLGenerationEnabled() &&
+ crlIssuingPoint.isCRLUpdateInProgress() == ICRLIssuingPoint.CRL_UPDATE_DONE &&
+ crlIssuingPoint.isCRLIssuingPointInitialized()
== ICRLIssuingPoint.CRL_IP_INITIALIZED) {
if (test != null && test.equals("true") &&
- crlIssuingPoint.isCRLCacheTestingEnabled() &&
- (!mTesting.contains(crlIssuingPointId))) {
+ crlIssuingPoint.isCRLCacheTestingEnabled() &&
+ (!mTesting.contains(crlIssuingPointId))) {
CMS.debug("CRL test started.");
mTesting.add(crlIssuingPointId);
BigInteger addLen = null;
BigInteger startFrom = null;
if (add != null && add.length() > 0 &&
- from != null && from.length() > 0) {
+ from != null && from.length() > 0) {
try {
addLen = new BigInteger(add);
startFrom = new BigInteger(from);
@@ -366,7 +367,7 @@ public class UpdateCRL extends CMSServlet {
Date revocationDate = CMS.getCurrentDate();
String err = null;
- CRLExtensions entryExts = crlEntryExtensions (reason, invalidity);
+ CRLExtensions entryExts = crlEntryExtensions(reason, invalidity);
BigInteger serialNumber = startFrom;
BigInteger counter = addLen;
@@ -380,16 +381,16 @@ public class UpdateCRL extends CMSServlet {
long t1 = System.currentTimeMillis();
long t2 = 0;
-
+
while (counter.compareTo(BigInteger.ZERO) > 0) {
RevokedCertImpl revokedCert =
- new RevokedCertImpl(serialNumber, revocationDate, entryExts);
+ new RevokedCertImpl(serialNumber, revocationDate, entryExts);
crlIssuingPoint.addRevokedCert(serialNumber, revokedCert);
serialNumber = serialNumber.add(BigInteger.ONE);
counter = counter.subtract(BigInteger.ONE);
if ((counter.compareTo(BigInteger.ZERO) == 0) ||
- (stepBy != null && ((counter.mod(stepBy)).compareTo(BigInteger.ZERO) == 0))) {
+ (stepBy != null && ((counter.mod(stepBy)).compareTo(BigInteger.ZERO) == 0))) {
t2 = System.currentTimeMillis();
long t0 = t2 - t1;
t1 = t2;
@@ -465,40 +466,40 @@ public class UpdateCRL extends CMSServlet {
String agentId = (String) sContext.get(SessionContext.USER_ID);
IAuthToken authToken = (IAuthToken) sContext.get(SessionContext.AUTH_TOKEN);
String authMgr = AuditFormat.NOAUTH;
-
+
if (authToken != null) {
authMgr = authToken.getInString(AuthToken.TOKEN_AUTHMGR_INST_NAME);
}
long endTime = CMS.getCurrentDate().getTime();
if (crlIssuingPoint.getNextUpdate() != null) {
- mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.CRLUPDATEFORMAT,
- new Object[] {
- AuditFormat.FROMAGENT + " agentID: " + agentId,
- authMgr,
- "completed",
- crlIssuingPoint.getId(),
- crlIssuingPoint.getCRLNumber(),
- crlIssuingPoint.getLastUpdate(),
- crlIssuingPoint.getNextUpdate(),
- Long.toString(crlIssuingPoint.getCRLSize()) + " time: " + (endTime - startTime)}
- );
- }else {
- mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.CRLUPDATEFORMAT,
- new Object[] {
- AuditFormat.FROMAGENT + " agentID: " + agentId,
- authMgr,
- "completed",
- crlIssuingPoint.getId(),
- crlIssuingPoint.getCRLNumber(),
- crlIssuingPoint.getLastUpdate(),
- "not set",
- Long.toString(crlIssuingPoint.getCRLSize()) + " time: " + (endTime - startTime)}
- );
+ mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.CRLUPDATEFORMAT,
+ new Object[] {
+ AuditFormat.FROMAGENT + " agentID: " + agentId,
+ authMgr,
+ "completed",
+ crlIssuingPoint.getId(),
+ crlIssuingPoint.getCRLNumber(),
+ crlIssuingPoint.getLastUpdate(),
+ crlIssuingPoint.getNextUpdate(),
+ Long.toString(crlIssuingPoint.getCRLSize()) + " time: " + (endTime - startTime) }
+ );
+ } else {
+ mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.CRLUPDATEFORMAT,
+ new Object[] {
+ AuditFormat.FROMAGENT + " agentID: " + agentId,
+ authMgr,
+ "completed",
+ crlIssuingPoint.getId(),
+ crlIssuingPoint.getCRLNumber(),
+ crlIssuingPoint.getLastUpdate(),
+ "not set",
+ Long.toString(crlIssuingPoint.getCRLSize()) + " time: " + (endTime - startTime) }
+ );
}
} catch (EBaseException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERR_UPDATE_CRL", e.toString()));
@@ -511,8 +512,7 @@ public class UpdateCRL extends CMSServlet {
}
}
} else {
- if (crlIssuingPoint.isCRLIssuingPointInitialized()
- != ICRLIssuingPoint.CRL_IP_INITIALIZED) {
+ if (crlIssuingPoint.isCRLIssuingPointInitialized() != ICRLIssuingPoint.CRL_IP_INITIALIZED) {
header.addStringValue("crlUpdate", "notInitialized");
} else if (crlIssuingPoint.isCRLUpdateInProgress()
!= ICRLIssuingPoint.CRL_UPDATE_DONE ||
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/UpdateDir.java b/pki/base/common/src/com/netscape/cms/servlet/cert/UpdateDir.java
index ccba3362..5b7688c5 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/UpdateDir.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/UpdateDir.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;
-
import java.io.IOException;
import java.math.BigInteger;
import java.util.Enumeration;
@@ -58,10 +57,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* Update the configured LDAP server with specified objects
- *
+ *
* @version $Revision$, $Date$
*/
public class UpdateDir extends CMSServlet {
@@ -85,12 +83,12 @@ public class UpdateDir extends CMSServlet {
private final static int REVOKED_FROM = 10;
private final static int REVOKED_TO = 11;
private final static int CHECK_FLAG = 12;
- private final static String[] updateName =
- {"updateAll", "updateCRL", "updateCA",
- "updateValid", "validFrom", "validTo",
- "updateExpired", "expiredFrom", "expiredTo",
- "updateRevoked", "revokedFrom", "revokedTo",
- "checkFlag"};
+ private final static String[] updateName =
+ { "updateAll", "updateCRL", "updateCA",
+ "updateValid", "validFrom", "validTo",
+ "updateExpired", "expiredFrom", "expiredTo",
+ "updateRevoked", "revokedFrom", "revokedTo",
+ "checkFlag" };
private String mFormPath = null;
private ICertificateAuthority mCA = null;
@@ -112,7 +110,7 @@ public class UpdateDir extends CMSServlet {
public void init(ServletConfig sc) throws ServletException {
super.init(sc);
- if( mAuthority != null ) {
+ if (mAuthority != null) {
mFormPath = "/" + mAuthority.getId() + "/" + TPL_FILE;
if (mAuthority instanceof ICertificateAuthority) {
mCA = (ICertificateAuthority) mAuthority;
@@ -129,8 +127,8 @@ public class UpdateDir extends CMSServlet {
}
/**
- * Process the HTTP request.
- *
+ * Process the HTTP request.
+ *
* @param cmsReq the object holding the request and response information
*/
public void process(CMSRequest cmsReq) throws EBaseException {
@@ -146,10 +144,10 @@ public class UpdateDir extends CMSServlet {
mAuthzResourceName, "update");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -169,17 +167,17 @@ public class UpdateDir extends CMSServlet {
try {
form = getTemplate(mFormPath, req, locale);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
try {
String crlIssuingPointId = req.getParameter("crlIssuingPoint");
if (mPublisherProcessor == null ||
- !mPublisherProcessor.enabled())
+ !mPublisherProcessor.enabled())
throw new ECMSGWException(CMS.getUserMessage("CMS_GW_NO_PUB_MODULE"));
String[] updateValue = new String[updateName.length];
@@ -191,7 +189,7 @@ public class UpdateDir extends CMSServlet {
String masterHost = CMS.getConfigStore().getString("master.ca.agent.host", "");
String masterPort = CMS.getConfigStore().getString("master.ca.agent.port", "");
if (masterHost != null && masterHost.length() > 0 &&
- masterPort != null && masterPort.length() > 0) {
+ masterPort != null && masterPort.length() > 0) {
mClonedCA = true;
}
@@ -206,29 +204,29 @@ public class UpdateDir extends CMSServlet {
if (error == null) {
String xmlOutput = req.getParameter("xml");
if (xmlOutput != null && xmlOutput.equals("true")) {
- outputXML(resp, argSet);
+ outputXML(resp, argSet);
} else {
- resp.setContentType("text/html");
- form.renderOutput(out, argSet);
- cmsReq.setStatus(CMSRequest.SUCCESS);
+ resp.setContentType("text/html");
+ form.renderOutput(out, argSet);
+ cmsReq.setStatus(CMSRequest.SUCCESS);
}
} else {
cmsReq.setStatus(CMSRequest.ERROR);
cmsReq.setError(error);
}
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_OUT_STREAM_TEMPLATE", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_OUT_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
}
private void updateCRLIssuingPoint(
- IArgBlock header,
- String crlIssuingPointId,
- ICRLIssuingPoint crlIssuingPoint,
- Locale locale) {
+ IArgBlock header,
+ String crlIssuingPointId,
+ ICRLIssuingPoint crlIssuingPoint,
+ Locale locale) {
SessionContext sc = SessionContext.getContext();
sc.put(ICRLIssuingPoint.SC_ISSUING_POINT_ID, crlIssuingPointId);
@@ -237,28 +235,28 @@ public class UpdateDir extends CMSServlet {
try {
if (mCRLRepository != null) {
- crlRecord = (ICRLIssuingPointRecord)mCRLRepository.readCRLIssuingPointRecord(crlIssuingPointId);
+ crlRecord = (ICRLIssuingPointRecord) mCRLRepository.readCRLIssuingPointRecord(crlIssuingPointId);
}
} catch (EBaseException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERR_GET_CRL_RECORD", e.toString()));
}
if (crlRecord == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_CRL_NOT_YET_UPDATED_1", crlIssuingPointId));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_CRL_NOT_YET_UPDATED_1", crlIssuingPointId));
header.addStringValue("crlPublished", "Failure");
header.addStringValue("crlError",
- new ECMSGWException(CMS.getUserMessage(locale, "CMS_GW_CRL_NOT_YET_UPDATED")).toString());
+ new ECMSGWException(CMS.getUserMessage(locale, "CMS_GW_CRL_NOT_YET_UPDATED")).toString());
} else {
- String publishDN = (crlIssuingPoint != null)? crlIssuingPoint.getPublishDN(): null;
+ String publishDN = (crlIssuingPoint != null) ? crlIssuingPoint.getPublishDN() : null;
byte[] crlbytes = crlRecord.getCRL();
if (crlbytes == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_CRL_NOT_YET_UPDATED_1", ""));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_CRL_NOT_YET_UPDATED_1", ""));
header.addStringValue("crlPublished", "Failure");
header.addStringValue("crlError",
- new ECMSGWException(CMS.getUserMessage(locale, "CMS_GW_CRL_NOT_YET_UPDATED")).toString());
+ new ECMSGWException(CMS.getUserMessage(locale, "CMS_GW_CRL_NOT_YET_UPDATED")).toString());
} else {
X509CRLImpl crl = null;
@@ -271,13 +269,13 @@ public class UpdateDir extends CMSServlet {
if (crl == null) {
header.addStringValue("crlPublished", "Failure");
header.addStringValue("crlError",
- new ECMSGWException(CMS.getUserMessage(locale,"CMS_GW_DECODE_CRL_FAILED")).toString());
+ new ECMSGWException(CMS.getUserMessage(locale, "CMS_GW_DECODE_CRL_FAILED")).toString());
} else {
try {
if (publishDN != null) {
mPublisherProcessor.publishCRL(publishDN, crl);
} else {
- mPublisherProcessor.publishCRL(crl,crlIssuingPointId);
+ mPublisherProcessor.publishCRL(crl, crlIssuingPointId);
}
header.addStringValue("crlPublished", "Success");
} catch (ELdapException e) {
@@ -307,20 +305,20 @@ public class UpdateDir extends CMSServlet {
BigInteger deltaNumber = crlRecord.getDeltaCRLNumber();
Long deltaCRLSize = crlRecord.getDeltaCRLSize();
if (deltaCRLSize != null && deltaCRLSize.longValue() > -1 &&
- crlNumber != null && deltaNumber != null &&
- deltaNumber.compareTo(crlNumber) >= 0) {
+ crlNumber != null && deltaNumber != null &&
+ deltaNumber.compareTo(crlNumber) >= 0) {
goodDelta = true;
}
}
if (deltaCrl != null && ((mClonedCA && goodDelta) ||
- (crlIssuingPoint != null &&
- crlIssuingPoint.isThisCurrentDeltaCRL(deltaCrl)))) {
+ (crlIssuingPoint != null &&
+ crlIssuingPoint.isThisCurrentDeltaCRL(deltaCrl)))) {
try {
if (publishDN != null) {
mPublisherProcessor.publishCRL(publishDN, deltaCrl);
} else {
- mPublisherProcessor.publishCRL(deltaCrl,crlIssuingPointId);
+ mPublisherProcessor.publishCRL(deltaCrl, crlIssuingPointId);
}
} catch (ELdapException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERR_PUBLISH_DELTA_CRL", e.toString()));
@@ -331,16 +329,16 @@ public class UpdateDir extends CMSServlet {
}
private void process(CMSTemplateParams argSet, IArgBlock header,
- HttpServletRequest req,
- HttpServletResponse resp,
- String crlIssuingPointId,
- String[] updateValue,
- Locale locale)
- throws EBaseException {
+ HttpServletRequest req,
+ HttpServletResponse resp,
+ String crlIssuingPointId,
+ String[] updateValue,
+ Locale locale)
+ throws EBaseException {
// all or crl
if ((updateValue[UPDATE_ALL] != null &&
updateValue[UPDATE_ALL].equalsIgnoreCase("yes")) ||
- (updateValue[UPDATE_CRL] != null &&
+ (updateValue[UPDATE_CRL] != null &&
updateValue[UPDATE_CRL].equalsIgnoreCase("yes"))) {
// check if received issuing point ID is known to the server
if (crlIssuingPointId != null) {
@@ -352,7 +350,8 @@ public class UpdateDir extends CMSServlet {
if (crlIssuingPointId.equals(ip.getId())) {
break;
}
- if (!ips.hasMoreElements()) crlIssuingPointId = null;
+ if (!ips.hasMoreElements())
+ crlIssuingPointId = null;
}
}
if (crlIssuingPointId == null) {
@@ -361,7 +360,7 @@ public class UpdateDir extends CMSServlet {
Vector ipNames = mCRLRepository.getIssuingPointsNames();
if (ipNames != null && ipNames.size() > 0) {
for (int i = 0; i < ipNames.size(); i++) {
- String ipName = (String)ipNames.elementAt(i);
+ String ipName = (String) ipNames.elementAt(i);
updateCRLIssuingPoint(header, ipName, null, locale);
}
@@ -377,11 +376,11 @@ public class UpdateDir extends CMSServlet {
}
} else {
ICRLIssuingPoint crlIssuingPoint =
- mCA.getCRLIssuingPoint(crlIssuingPointId);
+ mCA.getCRLIssuingPoint(crlIssuingPointId);
ICRLIssuingPointRecord crlRecord = null;
- updateCRLIssuingPoint(header, crlIssuingPointId,
- crlIssuingPoint, locale);
+ updateCRLIssuingPoint(header, crlIssuingPointId,
+ crlIssuingPoint, locale);
}
}
@@ -390,7 +389,7 @@ public class UpdateDir extends CMSServlet {
// all or ca
if ((updateValue[UPDATE_ALL] != null &&
updateValue[UPDATE_ALL].equalsIgnoreCase("yes")) ||
- (updateValue[UPDATE_CA] != null &&
+ (updateValue[UPDATE_CA] != null &&
updateValue[UPDATE_CA].equalsIgnoreCase("yes"))) {
X509CertImpl caCert = mCA.getSigningUnit().getCertImpl();
@@ -408,7 +407,7 @@ public class UpdateDir extends CMSServlet {
// all or valid
if ((updateValue[UPDATE_ALL] != null &&
updateValue[UPDATE_ALL].equalsIgnoreCase("yes")) ||
- (updateValue[UPDATE_VALID] != null &&
+ (updateValue[UPDATE_VALID] != null &&
updateValue[UPDATE_VALID].equalsIgnoreCase("yes"))) {
if (certificateRepository != null) {
if (updateValue[VALID_FROM].startsWith("0x")) {
@@ -420,16 +419,16 @@ public class UpdateDir extends CMSServlet {
Enumeration validCerts = null;
if (updateValue[CHECK_FLAG] != null &&
- updateValue[CHECK_FLAG].equalsIgnoreCase("yes")) {
- validCerts =
+ updateValue[CHECK_FLAG].equalsIgnoreCase("yes")) {
+ validCerts =
certificateRepository.getValidNotPublishedCertificates(
- updateValue[VALID_FROM],
- updateValue[VALID_TO]);
+ updateValue[VALID_FROM],
+ updateValue[VALID_TO]);
} else {
- validCerts =
+ validCerts =
certificateRepository.getValidCertificates(
- updateValue[VALID_FROM],
- updateValue[VALID_TO]);
+ updateValue[VALID_FROM],
+ updateValue[VALID_TO]);
}
int i = 0;
int l = 0;
@@ -438,8 +437,8 @@ public class UpdateDir extends CMSServlet {
if (validCerts != null) {
while (validCerts.hasMoreElements()) {
ICertRecord certRecord =
- (ICertRecord) validCerts.nextElement();
- //X509CertImpl cert = certRecord.getCertificate();
+ (ICertRecord) validCerts.nextElement();
+ // X509CertImpl cert = certRecord.getCertificate();
X509CertImpl cert = null;
Object o = certRecord.getCertificate();
@@ -454,9 +453,9 @@ public class UpdateDir extends CMSServlet {
// ca's self signed signing cert and
// server cert has no related request and
// have no metaInfo
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_FAIL_GET_ICERT_RECORD",
- cert.getSerialNumber().toString(16)));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_FAIL_GET_ICERT_RECORD",
+ cert.getSerialNumber().toString(16)));
} else {
ridString = (String) metaInfo.get(ICertRecord.META_REQUEST_ID);
}
@@ -465,55 +464,55 @@ public class UpdateDir extends CMSServlet {
if (ridString != null) {
RequestId rid = new RequestId(ridString);
-
+
r = mCA.getRequestQueue().findRequest(rid);
- }
+ }
try {
l++;
- SessionContext sc = SessionContext.getContext();
+ SessionContext sc = SessionContext.getContext();
if (r == null) {
if (CMS.isEncryptionCert(cert))
sc.put((Object) "isEncryptionCert", (Object) "true");
- else
+ else
sc.put((Object) "isEncryptionCert", (Object) "false");
mPublisherProcessor.publishCert(cert, null);
} else {
if (CMS.isEncryptionCert(cert))
r.setExtData("isEncryptionCert", "true");
- else
+ else
r.setExtData("isEncryptionCert", "false");
mPublisherProcessor.publishCert(cert, r);
}
i++;
} catch (Exception e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_FAIL_PUBLISH_CERT", certRecord.getSerialNumber().toString(16),
- e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_FAIL_PUBLISH_CERT", certRecord.getSerialNumber().toString(16),
+ e.toString()));
validCertsError +=
"Failed to publish certificate: 0x" +
- certRecord.getSerialNumber().toString(16) +
- ".\n <BR> &nbsp;&nbsp;&nbsp;&nbsp;";
+ certRecord.getSerialNumber().toString(16) +
+ ".\n <BR> &nbsp;&nbsp;&nbsp;&nbsp;";
}
}
}
if (i > 0 && i == l) {
header.addStringValue("validCertsPublished",
- "Success");
+ "Success");
if (i == 1)
- header.addStringValue("validCertsError", i +
- " valid certificate is published in the directory.");
+ header.addStringValue("validCertsError", i +
+ " valid certificate is published in the directory.");
else
- header.addStringValue("validCertsError", i +
- " valid certificates are published in the directory.");
+ header.addStringValue("validCertsError", i +
+ " valid certificates are published in the directory.");
} else {
if (l == 0) {
header.addStringValue("validCertsPublished", "No");
} else {
header.addStringValue("validCertsPublished", "Failure");
- header.addStringValue("validCertsError",
- validCertsError);
+ header.addStringValue("validCertsError",
+ validCertsError);
}
}
} else {
@@ -525,7 +524,7 @@ public class UpdateDir extends CMSServlet {
// all or expired
if ((updateValue[UPDATE_ALL] != null &&
updateValue[UPDATE_ALL].equalsIgnoreCase("yes")) ||
- (updateValue[UPDATE_EXPIRED] != null &&
+ (updateValue[UPDATE_EXPIRED] != null &&
updateValue[UPDATE_EXPIRED].equalsIgnoreCase("yes"))) {
if (certificateRepository != null) {
if (updateValue[EXPIRED_FROM].startsWith("0x")) {
@@ -537,26 +536,26 @@ public class UpdateDir extends CMSServlet {
Enumeration expiredCerts = null;
if (updateValue[CHECK_FLAG] != null &&
- updateValue[CHECK_FLAG].equalsIgnoreCase("yes")) {
+ updateValue[CHECK_FLAG].equalsIgnoreCase("yes")) {
expiredCerts =
certificateRepository.getExpiredPublishedCertificates(
- updateValue[EXPIRED_FROM],
- updateValue[EXPIRED_TO]);
+ updateValue[EXPIRED_FROM],
+ updateValue[EXPIRED_TO]);
} else {
expiredCerts =
certificateRepository.getExpiredCertificates(
- updateValue[EXPIRED_FROM],
- updateValue[EXPIRED_TO]);
+ updateValue[EXPIRED_FROM],
+ updateValue[EXPIRED_TO]);
}
int i = 0;
int l = 0;
StringBuffer expiredCertsError = new StringBuffer();
- if (expiredCerts != null) {
+ if (expiredCerts != null) {
while (expiredCerts.hasMoreElements()) {
ICertRecord certRecord =
- (ICertRecord) expiredCerts.nextElement();
- //X509CertImpl cert = certRecord.getCertificate();
+ (ICertRecord) expiredCerts.nextElement();
+ // X509CertImpl cert = certRecord.getCertificate();
X509CertImpl cert = null;
Object o = certRecord.getCertificate();
@@ -571,9 +570,9 @@ public class UpdateDir extends CMSServlet {
// ca's self signed signing cert and
// server cert has no related request and
// have no metaInfo
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_FAIL_GET_ICERT_RECORD",
- cert.getSerialNumber().toString(16)));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_FAIL_GET_ICERT_RECORD",
+ cert.getSerialNumber().toString(16)));
} else {
ridString = (String) metaInfo.get(ICertRecord.META_REQUEST_ID);
}
@@ -582,9 +581,9 @@ public class UpdateDir extends CMSServlet {
if (ridString != null) {
RequestId rid = new RequestId(ridString);
-
+
r = mCA.getRequestQueue().findRequest(rid);
- }
+ }
try {
l++;
@@ -595,10 +594,10 @@ public class UpdateDir extends CMSServlet {
}
i++;
} catch (Exception e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("LDAP_ERROR_UNPUBLISH_CERT",
- certRecord.getSerialNumber().toString(16),
- e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("LDAP_ERROR_UNPUBLISH_CERT",
+ certRecord.getSerialNumber().toString(16),
+ e.toString()));
expiredCertsError.append(
"Failed to unpublish certificate: 0x");
expiredCertsError.append(
@@ -611,18 +610,18 @@ public class UpdateDir extends CMSServlet {
if (i > 0 && i == l) {
header.addStringValue("expiredCertsUnpublished", "Success");
if (i == 1)
- header.addStringValue("expiredCertsError", i +
- " expired certificate is unpublished in the directory.");
+ header.addStringValue("expiredCertsError", i +
+ " expired certificate is unpublished in the directory.");
else
- header.addStringValue("expiredCertsError", i +
- " expired certificates are unpublished in the directory.");
+ header.addStringValue("expiredCertsError", i +
+ " expired certificates are unpublished in the directory.");
} else {
if (l == 0) {
header.addStringValue("expiredCertsUnpublished", "No");
} else {
header.addStringValue("expiredCertsUnpublished", "Failure");
- header.addStringValue("expiredCertsError",
- expiredCertsError.toString());
+ header.addStringValue("expiredCertsError",
+ expiredCertsError.toString());
}
}
} else {
@@ -634,7 +633,7 @@ public class UpdateDir extends CMSServlet {
// all or revoked
if ((updateValue[UPDATE_ALL] != null &&
updateValue[UPDATE_ALL].equalsIgnoreCase("yes")) ||
- (updateValue[UPDATE_REVOKED] != null &&
+ (updateValue[UPDATE_REVOKED] != null &&
updateValue[UPDATE_REVOKED].equalsIgnoreCase("yes"))) {
if (certificateRepository != null) {
if (updateValue[REVOKED_FROM].startsWith("0x")) {
@@ -646,26 +645,26 @@ public class UpdateDir extends CMSServlet {
Enumeration revokedCerts = null;
if (updateValue[CHECK_FLAG] != null &&
- updateValue[CHECK_FLAG].equalsIgnoreCase("yes")) {
+ updateValue[CHECK_FLAG].equalsIgnoreCase("yes")) {
revokedCerts =
certificateRepository.getRevokedPublishedCertificates(
- updateValue[REVOKED_FROM],
- updateValue[REVOKED_TO]);
+ updateValue[REVOKED_FROM],
+ updateValue[REVOKED_TO]);
} else {
revokedCerts =
certificateRepository.getRevokedCertificates(
- updateValue[REVOKED_FROM],
- updateValue[REVOKED_TO]);
+ updateValue[REVOKED_FROM],
+ updateValue[REVOKED_TO]);
}
int i = 0;
int l = 0;
String revokedCertsError = "";
- if (revokedCerts != null) {
+ if (revokedCerts != null) {
while (revokedCerts.hasMoreElements()) {
ICertRecord certRecord =
- (ICertRecord) revokedCerts.nextElement();
- //X509CertImpl cert = certRecord.getCertificate();
+ (ICertRecord) revokedCerts.nextElement();
+ // X509CertImpl cert = certRecord.getCertificate();
X509CertImpl cert = null;
Object o = certRecord.getCertificate();
@@ -680,9 +679,9 @@ public class UpdateDir extends CMSServlet {
// ca's self signed signing cert and
// server cert has no related request and
// have no metaInfo
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_FAIL_GET_ICERT_RECORD",
- cert.getSerialNumber().toString(16)));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_FAIL_GET_ICERT_RECORD",
+ cert.getSerialNumber().toString(16)));
} else {
ridString = (String) metaInfo.get(ICertRecord.META_REQUEST_ID);
}
@@ -691,9 +690,9 @@ public class UpdateDir extends CMSServlet {
if (ridString != null) {
RequestId rid = new RequestId(ridString);
-
+
r = mCA.getRequestQueue().findRequest(rid);
- }
+ }
try {
l++;
@@ -704,32 +703,32 @@ public class UpdateDir extends CMSServlet {
}
i++;
} catch (Exception e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("LDAP_ERROR_UNPUBLISH_CERT",
- certRecord.getSerialNumber().toString(16),
- e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("LDAP_ERROR_UNPUBLISH_CERT",
+ certRecord.getSerialNumber().toString(16),
+ e.toString()));
revokedCertsError +=
"Failed to unpublish certificate: 0x" +
- certRecord.getSerialNumber().toString(16) +
- ".\n <BR> &nbsp;&nbsp;&nbsp;&nbsp;";
+ certRecord.getSerialNumber().toString(16) +
+ ".\n <BR> &nbsp;&nbsp;&nbsp;&nbsp;";
}
}
}
if (i > 0 && i == l) {
header.addStringValue("revokedCertsUnpublished", "Success");
if (i == 1)
- header.addStringValue("revokedCertsError", i +
- " revoked certificate is unpublished in the directory.");
+ header.addStringValue("revokedCertsError", i +
+ " revoked certificate is unpublished in the directory.");
else
- header.addStringValue("revokedCertsError", i +
- " revoked certificates are unpublished in the directory.");
+ header.addStringValue("revokedCertsError", i +
+ " revoked certificates are unpublished in the directory.");
} else {
if (l == 0) {
header.addStringValue("revokedCertsUnpublished", "No");
} else {
header.addStringValue("revokedCertsUnpublished", "Failure");
- header.addStringValue("revokedCertsError",
- revokedCertsError);
+ header.addStringValue("revokedCertsError",
+ revokedCertsError);
}
}
} else {
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/scep/CRSEnrollment.java b/pki/base/common/src/com/netscape/cms/servlet/cert/scep/CRSEnrollment.java
index f181e156..ad28c921 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/scep/CRSEnrollment.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/scep/CRSEnrollment.java
@@ -122,242 +122,234 @@ import com.netscape.certsrv.request.RequestStatus;
import com.netscape.cms.servlet.profile.SSLClientCertProvider;
import com.netscape.cmsutil.scep.CRSPKIMessage;
-
/**
- * This servlet deals with PKCS#10-based certificate requests from
- * CRS, now called SCEP, and defined at:
- * http://search.ietf.org/internet-drafts/draft-nourse-scep-02.txt
+ * This servlet deals with PKCS#10-based certificate requests from CRS, now
+ * called SCEP, and defined at:
+ * http://search.ietf.org/internet-drafts/draft-nourse-scep-02.txt
*
* The router is hardcoded to look for the http://host:80/cgi-bin/pkiclient.exe
- *
- * The HTTP parameters are 'operation' and 'message'
- * operation can be either 'GetCACert' or 'PKIOperation'
- *
+ *
+ * The HTTP parameters are 'operation' and 'message' operation can be either
+ * 'GetCACert' or 'PKIOperation'
+ *
* @version $Revision$, $Date$
*/
-public class CRSEnrollment extends HttpServlet
-{
- /**
+public class CRSEnrollment extends HttpServlet {
+ /**
*
*/
private static final long serialVersionUID = 8483002540957382369L;
-protected IProfileSubsystem mProfileSubsystem = null;
- protected String mProfileId = null;
- protected ICertAuthority mAuthority;
- protected IConfigStore mConfig = null;
- protected IAuthSubsystem mAuthSubsystem;
- protected String mAppendDN=null;
- protected String mEntryObjectclass=null;
- protected boolean mCreateEntry=false;
- protected boolean mFlattenDN=false;
-
- private String mAuthManagerName;
- private String mSubstoreName;
- private boolean mEnabled = false;
- private boolean mUseCA = true;
- private String mNickname = null;
- private String mTokenName = "";
- private String mHashAlgorithm = "SHA1";
- private String mHashAlgorithmList = null;
- private String[] mAllowedHashAlgorithm;
- private String mConfiguredEncryptionAlgorithm = "DES3";
- private String mEncryptionAlgorithm = "DES3";
- private String mEncryptionAlgorithmList = null;
- private String[] mAllowedEncryptionAlgorithm;
- private Random mRandom = null;
- private int mNonceSizeLimit = 0;
- protected ILogger mLogger = CMS.getLogger();
- private ICertificateAuthority ca;
- /* for hashing challenge password */
- protected MessageDigest mSHADigest = null;
-
- private static final String PROP_SUBSTORENAME = "substorename";
- private static final String PROP_AUTHORITY = "authority";
- private static final String PROP_CRS = "crs";
- private static final String PROP_CRSCA = "casubsystem";
- private static final String PROP_CRSAUTHMGR = "authName";
- private static final String PROP_APPENDDN = "appendDN";
- private static final String PROP_CREATEENTRY= "createEntry";
- private static final String PROP_FLATTENDN = "flattenDN";
- private static final String PROP_ENTRYOC = "entryObjectclass";
-
- // URL parameters
- private static final String URL_OPERATION = "operation";
- private static final String URL_MESSAGE = "message";
-
- // possible values for 'operation'
- private static final String OP_GETCACERT = "GetCACert";
- private static final String OP_PKIOPERATION = "PKIOperation";
-
- public static final String AUTH_PASSWORD = "pwd";
-
- public static final String AUTH_CREDS = "AuthCreds";
- public static final String AUTH_TOKEN = "AuthToken";
- public static final String AUTH_FAILED = "AuthFailed";
-
- public static final String SANE_DNSNAME = "DNSName";
- public static final String SANE_IPADDRESS = "IPAddress";
-
- public static final String CERTINFO = "CertInfo";
- public static final String SUBJECTNAME = "SubjectName";
-
-
- public static ObjectIdentifier OID_UNSTRUCTUREDNAME = null;
- public static ObjectIdentifier OID_UNSTRUCTUREDADDRESS = null;
- public static ObjectIdentifier OID_SERIALNUMBER = null;
-
- public CRSEnrollment(){}
-
- public static Hashtable<String, String> toHashtable(HttpServletRequest req) {
- Hashtable<String, String> httpReqHash = new Hashtable<String, String>();
- @SuppressWarnings("unchecked")
- Enumeration<String> names = req.getParameterNames();
- while (names.hasMoreElements()) {
- String name = (String)names.nextElement();
- httpReqHash.put(name, req.getParameter(name));
- }
- return httpReqHash;
- }
-
- public void init(ServletConfig sc) {
- // Find the CertificateAuthority we should use for CRS.
- String crsCA = sc.getInitParameter(PROP_AUTHORITY);
- if (crsCA == null)
- crsCA = "ca";
- mAuthority = (ICertAuthority) CMS.getSubsystem(crsCA);
- ca = (ICertificateAuthority)mAuthority;
-
- if (mAuthority == null) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_CANT_FIND_AUTHORITY",crsCA));
- }
-
- try {
- if (mAuthority instanceof ISubsystem) {
- IConfigStore authorityConfig = ((ISubsystem)mAuthority).getConfigStore();
- IConfigStore scepConfig = authorityConfig.getSubStore("scep");
- mEnabled = scepConfig.getBoolean("enable", false);
- mHashAlgorithm = scepConfig.getString("hashAlgorithm", "SHA1");
- mConfiguredEncryptionAlgorithm = scepConfig.getString("encryptionAlgorithm", "DES3");
- mNonceSizeLimit = scepConfig.getInteger("nonceSizeLimit", 0);
- mHashAlgorithmList = scepConfig.getString("allowedHashAlgorithms", "SHA1,SHA256,SHA512");
- mAllowedHashAlgorithm = mHashAlgorithmList.split(",");
- mEncryptionAlgorithmList = scepConfig.getString("allowedEncryptionAlgorithms", "DES3");
- mAllowedEncryptionAlgorithm = mEncryptionAlgorithmList.split(",");
- mNickname = scepConfig.getString("nickname", ca.getNickname());
- if (mNickname.equals(ca.getNickname())) {
- mTokenName = ca.getSigningUnit().getTokenName();
- } else {
- mTokenName = scepConfig.getString("tokenname", "");
- mUseCA = false;
- }
- if (!(mTokenName.equalsIgnoreCase(Constants.PR_INTERNAL_TOKEN) ||
- mTokenName.equalsIgnoreCase("Internal Key Storage Token") ||
- mTokenName.length() == 0)) {
- int i = mNickname.indexOf(':');
- if (!((i > -1) && (mTokenName.length() == i) && (mNickname.startsWith(mTokenName)))) {
- mNickname = mTokenName + ":" + mNickname;
- }
- }
- }
- } catch (EBaseException e) {
- CMS.debug("CRSEnrollment: init: EBaseException: "+e);
- }
- mEncryptionAlgorithm = mConfiguredEncryptionAlgorithm;
- CMS.debug("CRSEnrollment: init: SCEP support is "+((mEnabled)?"enabled":"disabled")+".");
- CMS.debug("CRSEnrollment: init: SCEP nickname: "+mNickname);
- CMS.debug("CRSEnrollment: init: CA nickname: "+ca.getNickname());
- CMS.debug("CRSEnrollment: init: Token name: "+mTokenName);
- CMS.debug("CRSEnrollment: init: Is SCEP using CA keys: "+mUseCA);
- CMS.debug("CRSEnrollment: init: mNonceSizeLimit: "+mNonceSizeLimit);
- CMS.debug("CRSEnrollment: init: mHashAlgorithm: "+mHashAlgorithm);
- CMS.debug("CRSEnrollment: init: mHashAlgorithmList: "+mHashAlgorithmList);
- for (int i = 0; i < mAllowedHashAlgorithm.length; i++) {
- mAllowedHashAlgorithm[i] = mAllowedHashAlgorithm[i].trim();
- CMS.debug("CRSEnrollment: init: mAllowedHashAlgorithm["+i+"]="+mAllowedHashAlgorithm[i]);
- }
- CMS.debug("CRSEnrollment: init: mEncryptionAlgorithm: "+mEncryptionAlgorithm);
- CMS.debug("CRSEnrollment: init: mEncryptionAlgorithmList: "+mEncryptionAlgorithmList);
- for (int i = 0; i < mAllowedEncryptionAlgorithm.length; i++) {
- mAllowedEncryptionAlgorithm[i] = mAllowedEncryptionAlgorithm[i].trim();
- CMS.debug("CRSEnrollment: init: mAllowedEncryptionAlgorithm["+i+"]="+mAllowedEncryptionAlgorithm[i]);
- }
-
- try {
- mProfileSubsystem = (IProfileSubsystem)CMS.getSubsystem("profile");
- mProfileId = sc.getInitParameter("profileId");
- CMS.debug("CRSEnrollment: init: mProfileId="+mProfileId);
-
- mAuthSubsystem = (IAuthSubsystem)CMS.getSubsystem(CMS.SUBSYSTEM_AUTH);
- mAuthManagerName = sc.getInitParameter(PROP_CRSAUTHMGR);
- mAppendDN = sc.getInitParameter(PROP_APPENDDN);
- String tmp = sc.getInitParameter(PROP_CREATEENTRY);
- if (tmp != null && tmp.trim().equalsIgnoreCase("true"))
- mCreateEntry = true;
- else
- mCreateEntry = false;
- tmp = sc.getInitParameter(PROP_FLATTENDN);
- if (tmp != null && tmp.trim().equalsIgnoreCase("true"))
- mFlattenDN = true;
- else
- mFlattenDN = false;
- mEntryObjectclass = sc.getInitParameter(PROP_ENTRYOC);
- if (mEntryObjectclass == null)
- mEntryObjectclass = "cep";
- mSubstoreName = sc.getInitParameter(PROP_SUBSTORENAME);
- if (mSubstoreName == null)
- mSubstoreName = "default";
- } catch (Exception e) {
- }
-
- OID_UNSTRUCTUREDNAME = X500NameAttrMap.getDefault().getOid("UNSTRUCTUREDNAME");
- OID_UNSTRUCTUREDADDRESS = X500NameAttrMap.getDefault().getOid("UNSTRUCTUREDADDRESS");
- OID_SERIALNUMBER = X500NameAttrMap.getDefault().getOid("SERIALNUMBER");
-
-
- try {
- mSHADigest = MessageDigest.getInstance("SHA1");
+ protected IProfileSubsystem mProfileSubsystem = null;
+ protected String mProfileId = null;
+ protected ICertAuthority mAuthority;
+ protected IConfigStore mConfig = null;
+ protected IAuthSubsystem mAuthSubsystem;
+ protected String mAppendDN = null;
+ protected String mEntryObjectclass = null;
+ protected boolean mCreateEntry = false;
+ protected boolean mFlattenDN = false;
+
+ private String mAuthManagerName;
+ private String mSubstoreName;
+ private boolean mEnabled = false;
+ private boolean mUseCA = true;
+ private String mNickname = null;
+ private String mTokenName = "";
+ private String mHashAlgorithm = "SHA1";
+ private String mHashAlgorithmList = null;
+ private String[] mAllowedHashAlgorithm;
+ private String mConfiguredEncryptionAlgorithm = "DES3";
+ private String mEncryptionAlgorithm = "DES3";
+ private String mEncryptionAlgorithmList = null;
+ private String[] mAllowedEncryptionAlgorithm;
+ private Random mRandom = null;
+ private int mNonceSizeLimit = 0;
+ protected ILogger mLogger = CMS.getLogger();
+ private ICertificateAuthority ca;
+ /* for hashing challenge password */
+ protected MessageDigest mSHADigest = null;
+
+ private static final String PROP_SUBSTORENAME = "substorename";
+ private static final String PROP_AUTHORITY = "authority";
+ private static final String PROP_CRS = "crs";
+ private static final String PROP_CRSCA = "casubsystem";
+ private static final String PROP_CRSAUTHMGR = "authName";
+ private static final String PROP_APPENDDN = "appendDN";
+ private static final String PROP_CREATEENTRY = "createEntry";
+ private static final String PROP_FLATTENDN = "flattenDN";
+ private static final String PROP_ENTRYOC = "entryObjectclass";
+
+ // URL parameters
+ private static final String URL_OPERATION = "operation";
+ private static final String URL_MESSAGE = "message";
+
+ // possible values for 'operation'
+ private static final String OP_GETCACERT = "GetCACert";
+ private static final String OP_PKIOPERATION = "PKIOperation";
+
+ public static final String AUTH_PASSWORD = "pwd";
+
+ public static final String AUTH_CREDS = "AuthCreds";
+ public static final String AUTH_TOKEN = "AuthToken";
+ public static final String AUTH_FAILED = "AuthFailed";
+
+ public static final String SANE_DNSNAME = "DNSName";
+ public static final String SANE_IPADDRESS = "IPAddress";
+
+ public static final String CERTINFO = "CertInfo";
+ public static final String SUBJECTNAME = "SubjectName";
+
+ public static ObjectIdentifier OID_UNSTRUCTUREDNAME = null;
+ public static ObjectIdentifier OID_UNSTRUCTUREDADDRESS = null;
+ public static ObjectIdentifier OID_SERIALNUMBER = null;
+
+ public CRSEnrollment() {
+ }
+
+ public static Hashtable<String, String> toHashtable(HttpServletRequest req) {
+ Hashtable<String, String> httpReqHash = new Hashtable<String, String>();
+ @SuppressWarnings("unchecked")
+ Enumeration<String> names = req.getParameterNames();
+ while (names.hasMoreElements()) {
+ String name = (String) names.nextElement();
+ httpReqHash.put(name, req.getParameter(name));
+ }
+ return httpReqHash;
+ }
+
+ public void init(ServletConfig sc) {
+ // Find the CertificateAuthority we should use for CRS.
+ String crsCA = sc.getInitParameter(PROP_AUTHORITY);
+ if (crsCA == null)
+ crsCA = "ca";
+ mAuthority = (ICertAuthority) CMS.getSubsystem(crsCA);
+ ca = (ICertificateAuthority) mAuthority;
+
+ if (mAuthority == null) {
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_CANT_FIND_AUTHORITY", crsCA));
+ }
+
+ try {
+ if (mAuthority instanceof ISubsystem) {
+ IConfigStore authorityConfig = ((ISubsystem) mAuthority).getConfigStore();
+ IConfigStore scepConfig = authorityConfig.getSubStore("scep");
+ mEnabled = scepConfig.getBoolean("enable", false);
+ mHashAlgorithm = scepConfig.getString("hashAlgorithm", "SHA1");
+ mConfiguredEncryptionAlgorithm = scepConfig.getString("encryptionAlgorithm", "DES3");
+ mNonceSizeLimit = scepConfig.getInteger("nonceSizeLimit", 0);
+ mHashAlgorithmList = scepConfig.getString("allowedHashAlgorithms", "SHA1,SHA256,SHA512");
+ mAllowedHashAlgorithm = mHashAlgorithmList.split(",");
+ mEncryptionAlgorithmList = scepConfig.getString("allowedEncryptionAlgorithms", "DES3");
+ mAllowedEncryptionAlgorithm = mEncryptionAlgorithmList.split(",");
+ mNickname = scepConfig.getString("nickname", ca.getNickname());
+ if (mNickname.equals(ca.getNickname())) {
+ mTokenName = ca.getSigningUnit().getTokenName();
+ } else {
+ mTokenName = scepConfig.getString("tokenname", "");
+ mUseCA = false;
+ }
+ if (!(mTokenName.equalsIgnoreCase(Constants.PR_INTERNAL_TOKEN) ||
+ mTokenName.equalsIgnoreCase("Internal Key Storage Token") || mTokenName.length() == 0)) {
+ int i = mNickname.indexOf(':');
+ if (!((i > -1) && (mTokenName.length() == i) && (mNickname.startsWith(mTokenName)))) {
+ mNickname = mTokenName + ":" + mNickname;
+ }
+ }
+ }
+ } catch (EBaseException e) {
+ CMS.debug("CRSEnrollment: init: EBaseException: " + e);
+ }
+ mEncryptionAlgorithm = mConfiguredEncryptionAlgorithm;
+ CMS.debug("CRSEnrollment: init: SCEP support is " + ((mEnabled) ? "enabled" : "disabled") + ".");
+ CMS.debug("CRSEnrollment: init: SCEP nickname: " + mNickname);
+ CMS.debug("CRSEnrollment: init: CA nickname: " + ca.getNickname());
+ CMS.debug("CRSEnrollment: init: Token name: " + mTokenName);
+ CMS.debug("CRSEnrollment: init: Is SCEP using CA keys: " + mUseCA);
+ CMS.debug("CRSEnrollment: init: mNonceSizeLimit: " + mNonceSizeLimit);
+ CMS.debug("CRSEnrollment: init: mHashAlgorithm: " + mHashAlgorithm);
+ CMS.debug("CRSEnrollment: init: mHashAlgorithmList: " + mHashAlgorithmList);
+ for (int i = 0; i < mAllowedHashAlgorithm.length; i++) {
+ mAllowedHashAlgorithm[i] = mAllowedHashAlgorithm[i].trim();
+ CMS.debug("CRSEnrollment: init: mAllowedHashAlgorithm[" + i + "]=" + mAllowedHashAlgorithm[i]);
+ }
+ CMS.debug("CRSEnrollment: init: mEncryptionAlgorithm: " + mEncryptionAlgorithm);
+ CMS.debug("CRSEnrollment: init: mEncryptionAlgorithmList: " + mEncryptionAlgorithmList);
+ for (int i = 0; i < mAllowedEncryptionAlgorithm.length; i++) {
+ mAllowedEncryptionAlgorithm[i] = mAllowedEncryptionAlgorithm[i].trim();
+ CMS.debug("CRSEnrollment: init: mAllowedEncryptionAlgorithm[" + i + "]=" + mAllowedEncryptionAlgorithm[i]);
+ }
+
+ try {
+ mProfileSubsystem = (IProfileSubsystem) CMS.getSubsystem("profile");
+ mProfileId = sc.getInitParameter("profileId");
+ CMS.debug("CRSEnrollment: init: mProfileId=" + mProfileId);
+
+ mAuthSubsystem = (IAuthSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_AUTH);
+ mAuthManagerName = sc.getInitParameter(PROP_CRSAUTHMGR);
+ mAppendDN = sc.getInitParameter(PROP_APPENDDN);
+ String tmp = sc.getInitParameter(PROP_CREATEENTRY);
+ if (tmp != null && tmp.trim().equalsIgnoreCase("true"))
+ mCreateEntry = true;
+ else
+ mCreateEntry = false;
+ tmp = sc.getInitParameter(PROP_FLATTENDN);
+ if (tmp != null && tmp.trim().equalsIgnoreCase("true"))
+ mFlattenDN = true;
+ else
+ mFlattenDN = false;
+ mEntryObjectclass = sc.getInitParameter(PROP_ENTRYOC);
+ if (mEntryObjectclass == null)
+ mEntryObjectclass = "cep";
+ mSubstoreName = sc.getInitParameter(PROP_SUBSTORENAME);
+ if (mSubstoreName == null)
+ mSubstoreName = "default";
+ } catch (Exception e) {
+ }
+
+ OID_UNSTRUCTUREDNAME = X500NameAttrMap.getDefault().getOid("UNSTRUCTUREDNAME");
+ OID_UNSTRUCTUREDADDRESS = X500NameAttrMap.getDefault().getOid("UNSTRUCTUREDADDRESS");
+ OID_SERIALNUMBER = X500NameAttrMap.getDefault().getOid("SERIALNUMBER");
+
+ try {
+ mSHADigest = MessageDigest.getInstance("SHA1");
+ } catch (NoSuchAlgorithmException e) {
+ }
+
+ mRandom = new Random();
}
- catch (NoSuchAlgorithmException e) {
- }
-
- mRandom = new Random();
- }
-
-
- /**
- *
- * Service a CRS Request. It all starts here. This is where the message from the
- * router is processed
- *
- * @param httpReq The HttpServletRequest.
- * @param httpResp The HttpServletResponse.
- *
- */
- public void service(HttpServletRequest httpReq,
+
+ /**
+ *
+ * Service a CRS Request. It all starts here. This is where the message from
+ * the router is processed
+ *
+ * @param httpReq The HttpServletRequest.
+ * @param httpResp The HttpServletResponse.
+ *
+ */
+ public void service(HttpServletRequest httpReq,
HttpServletResponse httpResp)
- throws ServletException
- {
- boolean running_state = CMS.isInRunningState();
- if (!running_state)
- throw new ServletException(
- "CMS server is not ready to serve.");
+ throws ServletException {
+ boolean running_state = CMS.isInRunningState();
+ if (!running_state)
+ throw new ServletException(
+ "CMS server is not ready to serve.");
String operation = null;
- String message = null;
+ String message = null;
mEncryptionAlgorithm = mConfiguredEncryptionAlgorithm;
-
-
+
// Parse the URL from the HTTP Request. Split it up into
// a structure which enables us to read the form elements
IArgBlock input = CMS.createArgBlock(toHashtable(httpReq));
-
- try {
+
+ try {
// Read in two form parameters - the router sets these
- operation = (String)input.get(URL_OPERATION);
+ operation = (String) input.get(URL_OPERATION);
CMS.debug("operation=" + operation);
- message = (String)input.get(URL_MESSAGE);
+ message = (String) input.get(URL_MESSAGE);
CMS.debug("message=" + message);
-
+
if (!mEnabled) {
CMS.debug("CRSEnrollment: SCEP support is disabled.");
throw new ServletException("SCEP support is disabled.");
@@ -366,55 +358,48 @@ protected IProfileSubsystem mProfileSubsystem = null;
// 'operation' is mandatory.
throw new ServletException("Bad request: operation missing from URL");
}
-
- /**
- * the router can make two kinds of requests
- * 1) simple request for CA cert
- * 2) encoded, signed, enveloped request for anything else (PKIOperation)
+
+ /**
+ * the router can make two kinds of requests 1) simple request for
+ * CA cert 2) encoded, signed, enveloped request for anything else
+ * (PKIOperation)
*/
-
+
if (operation.equals(OP_GETCACERT)) {
- handleGetCACert(httpReq, httpResp);
- }
- else if (operation.equals(OP_PKIOPERATION)) {
- String decodeMode = (String)input.get("decode");
+ handleGetCACert(httpReq, httpResp);
+ } else if (operation.equals(OP_PKIOPERATION)) {
+ String decodeMode = (String) input.get("decode");
if (decodeMode == null || decodeMode.equals("false")) {
- handlePKIOperation(httpReq, httpResp, message);
+ handlePKIOperation(httpReq, httpResp, message);
} else {
- decodePKIMessage(httpReq, httpResp, message);
+ decodePKIMessage(httpReq, httpResp, message);
}
- }
- else {
+ } else {
CMS.debug("Invalid operation " + operation);
- throw new ServletException("unknown operation requested: "+operation);
+ throw new ServletException("unknown operation requested: " + operation);
}
-
- }
- catch (ServletException e)
- {
+
+ } catch (ServletException e) {
CMS.debug("ServletException " + e);
throw new ServletException(e.getMessage().toString());
+ } catch (Exception e) {
+ CMS.debug("Service exception " + e);
+ log(ILogger.LL_FAILURE, e.getMessage());
}
- catch (Exception e)
- {
- CMS.debug("Service exception " + e);
- log(ILogger.LL_FAILURE,e.getMessage());
- }
-
+
}
/**
- * Log a message to the system log
+ * Log a message to the system log
*/
-
private void log(int level, String msg) {
-
+
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- level, "CEP Enrollment: "+msg);
+ level, "CEP Enrollment: " + msg);
}
- private boolean isAlgorithmAllowed (String[] allowedAlgorithm, String algorithm) {
+ private boolean isAlgorithmAllowed(String[] allowedAlgorithm, String algorithm) {
boolean allowed = false;
if (algorithm != null && algorithm.length() > 0) {
@@ -429,7 +414,7 @@ protected IProfileSubsystem mProfileSubsystem = null;
}
public IAuthToken authenticate(AuthCredentials credentials, IProfileAuthenticator authenticator,
- HttpServletRequest request) throws EBaseException {
+ HttpServletRequest request) throws EBaseException {
// build credential
Enumeration<String> authNames = authenticator.getValueNames();
@@ -445,314 +430,301 @@ protected IProfileSubsystem mProfileSubsystem = null;
credentials.set("clientHost", request.getRemoteHost());
IAuthToken authToken = authenticator.authenticate(credentials);
if (authToken == null) {
- return null;
+ return null;
}
SessionContext sc = SessionContext.getContext();
if (sc != null) {
- sc.put(SessionContext.AUTH_MANAGER_ID, authenticator.getName());
- String userid = authToken.getInString(IAuthToken.USER_ID);
- if (userid != null) {
- sc.put(SessionContext.USER_ID, userid);
- }
+ sc.put(SessionContext.AUTH_MANAGER_ID, authenticator.getName());
+ String userid = authToken.getInString(IAuthToken.USER_ID);
+ if (userid != null) {
+ sc.put(SessionContext.USER_ID, userid);
+ }
}
return authToken;
}
- /**
- * Return the CA certificate back to the requestor.
- * This needs to be changed so that if the CA has a certificate chain,
- * the whole thing should get packaged as a PKIMessage (degnerate PKCS7 - no
- * signerInfo)
- */
-
- public void handleGetCACert(HttpServletRequest httpReq,
- HttpServletResponse httpResp)
- throws ServletException {
- java.security.cert.X509Certificate[] chain = null;
-
- CertificateChain certChain = mAuthority.getCACertChain();
-
- try {
- if (certChain == null) {
- throw new ServletException("Internal Error: cannot get CA Cert");
- }
-
- chain = certChain.getChain();
-
- byte[] bytes = null;
-
- int i = 0;
- String message = (String)httpReq.getParameter(URL_MESSAGE);
- CMS.debug("handleGetCACert message=" + message);
- if (message != null) {
- try {
- int j = Integer.parseInt(message);
- if (j < chain.length) {
- i = j;
- }
- } catch (NumberFormatException e1) {
+ /**
+ * Return the CA certificate back to the requestor. This needs to be changed
+ * so that if the CA has a certificate chain, the whole thing should get
+ * packaged as a PKIMessage (degnerate PKCS7 - no signerInfo)
+ */
+
+ public void handleGetCACert(HttpServletRequest httpReq,
+ HttpServletResponse httpResp)
+ throws ServletException {
+ java.security.cert.X509Certificate[] chain = null;
+
+ CertificateChain certChain = mAuthority.getCACertChain();
+
+ try {
+ if (certChain == null) {
+ throw new ServletException("Internal Error: cannot get CA Cert");
+ }
+
+ chain = certChain.getChain();
+
+ byte[] bytes = null;
+
+ int i = 0;
+ String message = (String) httpReq.getParameter(URL_MESSAGE);
+ CMS.debug("handleGetCACert message=" + message);
+ if (message != null) {
+ try {
+ int j = Integer.parseInt(message);
+ if (j < chain.length) {
+ i = j;
+ }
+ } catch (NumberFormatException e1) {
+ }
+ }
+ CMS.debug("handleGetCACert selected chain=" + i);
+
+ if (mUseCA) {
+ bytes = chain[i].getEncoded();
+ } else {
+ CryptoContext cx = new CryptoContext();
+ bytes = cx.getSigningCert().getEncoded();
}
- }
- CMS.debug("handleGetCACert selected chain=" + i);
-
- if (mUseCA) {
- bytes = chain[i].getEncoded();
- } else {
- CryptoContext cx = new CryptoContext();
- bytes = cx.getSigningCert().getEncoded();
- }
-
- httpResp.setContentType("application/x-x509-ca-cert");
-
-
-// The following code may be used one day to encode
-// the RA/CA cert chain for RA mode, but it will need some
-// work.
-
- /******
- SET certs = new SET();
- for (int i=0; i<chain.length; i++) {
- ANY cert = new ANY(chain[i].getEncoded());
- certs.addElement(cert);
- }
-
- SignedData crsd = new SignedData(
- new SET(), // empty set of digestAlgorithmID's
- new ContentInfo(
- new OBJECT_IDENTIFIER(new long[] {1,2,840,113549,1,7,1}),
- null), //empty content
- certs,
- null, // no CRL's
- new SET() // empty SignerInfos
- );
-
- ContentInfo wrap = new ContentInfo(ContentInfo.SIGNED_DATA, crsd);
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- wrap.encode(baos);
-
- bytes = baos.toByteArray();
-
- httpResp.setContentType("application/x-x509-ca-ra-cert");
- *****/
-
- httpResp.setContentLength(bytes.length);
- httpResp.getOutputStream().write(bytes);
- httpResp.getOutputStream().flush();
-
- CMS.debug("Output certificate chain:");
- CMS.debug(bytes);
- }
- catch (Exception e) {
- CMS.debug("handleGetCACert exception " + e);
- log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERROR_SENDING_DER_ENCODE_CERT",e.getMessage()));
- throw new ServletException("Failed sending DER encoded version of CA cert to client");
- }
-
- }
-
- public String getPasswordFromP10(PKCS10 p10)
- {
- PKCS10Attributes p10atts = p10.getAttributes();
- Enumeration<PKCS10Attribute> e = p10atts.getElements();
-
- try {
- while (e.hasMoreElements()) {
- PKCS10Attribute p10a = (PKCS10Attribute)e.nextElement();
- CertAttrSet attr = p10a.getAttributeValue();
-
- if (attr.getName().equals(ChallengePassword.NAME)) {
- if (attr.get(ChallengePassword.PASSWORD) != null) {
- return (String)attr.get(ChallengePassword.PASSWORD);
- }
- }
- }
- } catch(Exception e1) {
- // do nothing
- }
- return null;
- }
-
- /**
- * If the 'operation' is 'PKIOperation', the 'message' part of the URL is a
- * PKIMessage structure. We decode it to see what type message it is.
- */
-
- /**
- * Decodes the PKI message and return information to RA.
- */
- public void decodePKIMessage(HttpServletRequest httpReq,
+
+ httpResp.setContentType("application/x-x509-ca-cert");
+
+ // The following code may be used one day to encode
+ // the RA/CA cert chain for RA mode, but it will need some
+ // work.
+
+ /******
+ * SET certs = new SET(); for (int i=0; i<chain.length; i++) { ANY
+ * cert = new ANY(chain[i].getEncoded()); certs.addElement(cert); }
+ *
+ * SignedData crsd = new SignedData( new SET(), // empty set of
+ * digestAlgorithmID's new ContentInfo( new OBJECT_IDENTIFIER(new
+ * long[] {1,2,840,113549,1,7,1}), null), //empty content certs,
+ * null, // no CRL's new SET() // empty SignerInfos );
+ *
+ * ContentInfo wrap = new ContentInfo(ContentInfo.SIGNED_DATA,
+ * crsd);
+ *
+ * ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ * wrap.encode(baos);
+ *
+ * bytes = baos.toByteArray();
+ *
+ * httpResp.setContentType("application/x-x509-ca-ra-cert");
+ *****/
+
+ httpResp.setContentLength(bytes.length);
+ httpResp.getOutputStream().write(bytes);
+ httpResp.getOutputStream().flush();
+
+ CMS.debug("Output certificate chain:");
+ CMS.debug(bytes);
+ } catch (Exception e) {
+ CMS.debug("handleGetCACert exception " + e);
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERROR_SENDING_DER_ENCODE_CERT", e.getMessage()));
+ throw new ServletException("Failed sending DER encoded version of CA cert to client");
+ }
+
+ }
+
+ public String getPasswordFromP10(PKCS10 p10) {
+ PKCS10Attributes p10atts = p10.getAttributes();
+ Enumeration<PKCS10Attribute> e = p10atts.getElements();
+
+ try {
+ while (e.hasMoreElements()) {
+ PKCS10Attribute p10a = (PKCS10Attribute) e.nextElement();
+ CertAttrSet attr = p10a.getAttributeValue();
+
+ if (attr.getName().equals(ChallengePassword.NAME)) {
+ if (attr.get(ChallengePassword.PASSWORD) != null) {
+ return (String) attr.get(ChallengePassword.PASSWORD);
+ }
+ }
+ }
+ } catch (Exception e1) {
+ // do nothing
+ }
+ return null;
+ }
+
+ /**
+ * If the 'operation' is 'PKIOperation', the 'message' part of the URL is a
+ * PKIMessage structure. We decode it to see what type message it is.
+ */
+
+ /**
+ * Decodes the PKI message and return information to RA.
+ */
+ public void decodePKIMessage(HttpServletRequest httpReq,
HttpServletResponse httpResp,
String msg)
- throws ServletException {
-
- CryptoContext cx=null;
-
- CRSPKIMessage req=null;
-
- byte[] decodedPKIMessage;
- byte[] response=null;
- String responseData = "";
-
- decodedPKIMessage = com.netscape.osutil.OSUtil.AtoB(msg);
-
- try {
- ByteArrayInputStream is = new ByteArrayInputStream(decodedPKIMessage);
-
- // We make two CRSPKIMessages. One of them, is the request, so we initialize
- // it from the DER given to us from the router.
- // The second is the response, and we'll fill this in as we go.
-
- if (decodedPKIMessage.length < 50) {
- throw new ServletException("CRS request is too small to be a real request ("+
- decodedPKIMessage.length+" bytes)");
- }
- try {
- req = new CRSPKIMessage(is);
- String ea = req.getEncryptionAlgorithm();
- if (!isAlgorithmAllowed (mAllowedEncryptionAlgorithm, ea)) {
- CMS.debug("CRSEnrollment: decodePKIMessage: Encryption algorithm '"+ea+
- "' is not allowed ("+mEncryptionAlgorithmList+").");
- throw new ServletException("Encryption algorithm '"+ea+
- "' is not allowed ("+mEncryptionAlgorithmList+").");
+ throws ServletException {
+
+ CryptoContext cx = null;
+
+ CRSPKIMessage req = null;
+
+ byte[] decodedPKIMessage;
+ byte[] response = null;
+ String responseData = "";
+
+ decodedPKIMessage = com.netscape.osutil.OSUtil.AtoB(msg);
+
+ try {
+ ByteArrayInputStream is = new ByteArrayInputStream(decodedPKIMessage);
+
+ // We make two CRSPKIMessages. One of them, is the request, so we
+ // initialize
+ // it from the DER given to us from the router.
+ // The second is the response, and we'll fill this in as we go.
+
+ if (decodedPKIMessage.length < 50) {
+ throw new ServletException("CRS request is too small to be a real request (" +
+ decodedPKIMessage.length + " bytes)");
+ }
+ try {
+ req = new CRSPKIMessage(is);
+ String ea = req.getEncryptionAlgorithm();
+ if (!isAlgorithmAllowed(mAllowedEncryptionAlgorithm, ea)) {
+ CMS.debug("CRSEnrollment: decodePKIMessage: Encryption algorithm '" + ea +
+ "' is not allowed (" + mEncryptionAlgorithmList + ").");
+ throw new ServletException("Encryption algorithm '" + ea +
+ "' is not allowed (" + mEncryptionAlgorithmList + ").");
+ }
+ String da = req.getDigestAlgorithmName();
+ if (!isAlgorithmAllowed(mAllowedHashAlgorithm, da)) {
+ CMS.debug("CRSEnrollment: decodePKIMessage: Hashing algorithm '" + da +
+ "' is not allowed (" + mHashAlgorithmList + ").");
+ throw new ServletException("Hashing algorithm '" + da +
+ "' is not allowed (" + mHashAlgorithmList + ").");
+ }
+ if (ea != null) {
+ mEncryptionAlgorithm = ea;
+ }
+ } catch (Exception e) {
+ CMS.debug(e);
+ throw new ServletException("Could not decode the request.");
}
- String da = req.getDigestAlgorithmName();
- if (!isAlgorithmAllowed (mAllowedHashAlgorithm, da)) {
- CMS.debug("CRSEnrollment: decodePKIMessage: Hashing algorithm '"+da+
- "' is not allowed ("+mHashAlgorithmList+").");
- throw new ServletException("Hashing algorithm '"+da+
- "' is not allowed ("+mHashAlgorithmList+").");
+
+ // Create a new crypto context for doing all the crypto operations
+ cx = new CryptoContext();
+
+ // Verify Signature on message (throws exception if sig bad)
+ verifyRequest(req, cx);
+ unwrapPKCS10(req, cx);
+
+ IProfile profile = mProfileSubsystem.getProfile(mProfileId);
+ if (profile == null) {
+ CMS.debug("Profile '" + mProfileId + "' not found.");
+ throw new ServletException("Profile '" + mProfileId + "' not found.");
+ } else {
+ CMS.debug("Found profile '" + mProfileId + "'.");
}
- if (ea != null) {
- mEncryptionAlgorithm = ea;
- }
- }
- catch (Exception e) {
- CMS.debug(e);
- throw new ServletException("Could not decode the request.");
- }
-
- // Create a new crypto context for doing all the crypto operations
- cx = new CryptoContext();
-
- // Verify Signature on message (throws exception if sig bad)
- verifyRequest(req,cx);
- unwrapPKCS10(req,cx);
-
- IProfile profile = mProfileSubsystem.getProfile(mProfileId);
- if (profile == null) {
- CMS.debug("Profile '" + mProfileId + "' not found.");
- throw new ServletException("Profile '" + mProfileId + "' not found.");
- } else {
- CMS.debug("Found profile '" + mProfileId + "'.");
- }
-
- IProfileAuthenticator authenticator = null;
- try {
- CMS.debug("Retrieving authenticator");
- authenticator = profile.getAuthenticator();
- if (authenticator == null) {
- CMS.debug("Authenticator not found.");
- throw new ServletException("Authenticator not found.");
- } else {
- CMS.debug("Got authenticator=" + authenticator.getClass().getName());
- }
- } catch (EProfileException e) {
- throw new ServletException("Authenticator not found.");
- }
- AuthCredentials credentials = new AuthCredentials();
- IAuthToken authToken = null;
- // for ssl authentication; pass in servlet for retrieving
- // ssl client certificates
- SessionContext context = SessionContext.getContext();
-
- // insert profile context so that input parameter can be retrieved
- context.put("sslClientCertProvider", new SSLClientCertProvider(httpReq));
-
- try {
- authToken = authenticate(credentials, authenticator, httpReq);
- } catch (Exception e) {
- CMS.debug("Authentication failure: "+ e.getMessage());
- throw new ServletException("Authentication failure: "+ e.getMessage());
- }
- if (authToken == null) {
- CMS.debug("Authentication failure.");
- throw new ServletException("Authentication failure.");
- }
-
- // Deal with Transaction ID
- String transactionID = req.getTransactionID();
- responseData = responseData +
- "<TransactionID>" + transactionID + "</TransactionID>";
-
- // End-User or RA's IP address
- responseData = responseData +
- "<RemoteAddr>" + httpReq.getRemoteAddr() + "</RemoteAddr>";
-
- responseData = responseData +
- "<RemoteHost>" + httpReq.getRemoteHost() + "</RemoteHost>";
-
- // Deal with Nonces
- byte[] sn = req.getSenderNonce();
-
- // Deal with message type
- String mt = req.getMessageType();
- responseData = responseData +
- "<MessageType>" + mt + "</MessageType>";
-
- PKCS10 p10 = (PKCS10)req.getP10();
- X500Name p10subject = p10.getSubjectName();
- responseData = responseData +
- "<SubjectName>" + p10subject.toString() + "</SubjectName>";
-
- String pkcs10Attr = "";
- PKCS10Attributes p10atts = p10.getAttributes();
- Enumeration<PKCS10Attribute> e = p10atts.getElements();
-
- while (e.hasMoreElements()) {
- PKCS10Attribute p10a = (PKCS10Attribute)e.nextElement();
- CertAttrSet attr = p10a.getAttributeValue();
-
-
- if (attr.getName().equals(ChallengePassword.NAME)) {
- if (attr.get(ChallengePassword.PASSWORD) != null) {
- pkcs10Attr = pkcs10Attr +
- "<ChallengePassword><Password>" + (String)attr.get(ChallengePassword.PASSWORD) + "</Password></ChallengePassword>";
- }
-
- }
- String extensionsStr = "";
- if (attr.getName().equals(ExtensionsRequested.NAME)) {
-
- Enumeration<Extension> exts = ((ExtensionsRequested)attr).getExtensions().elements();
- while (exts.hasMoreElements()) {
- Extension ext = exts.nextElement();
-
- if (ext.getExtensionId().equals(
- OIDMap.getOID(SubjectAlternativeNameExtension.IDENT)) ) {
- DerOutputStream dos = new DerOutputStream();
- SubjectAlternativeNameExtension sane = new SubjectAlternativeNameExtension(
- Boolean.valueOf(false), // noncritical
- ext.getExtensionValue());
-
-
- @SuppressWarnings("unchecked")
- Vector<GeneralNameInterface> v =
- (Vector<GeneralNameInterface>) sane.get(SubjectAlternativeNameExtension. SUBJECT_NAME);
-
- Enumeration<GeneralNameInterface> gne = v.elements();
+
+ IProfileAuthenticator authenticator = null;
+ try {
+ CMS.debug("Retrieving authenticator");
+ authenticator = profile.getAuthenticator();
+ if (authenticator == null) {
+ CMS.debug("Authenticator not found.");
+ throw new ServletException("Authenticator not found.");
+ } else {
+ CMS.debug("Got authenticator=" + authenticator.getClass().getName());
+ }
+ } catch (EProfileException e) {
+ throw new ServletException("Authenticator not found.");
+ }
+ AuthCredentials credentials = new AuthCredentials();
+ IAuthToken authToken = null;
+ // for ssl authentication; pass in servlet for retrieving
+ // ssl client certificates
+ SessionContext context = SessionContext.getContext();
+
+ // insert profile context so that input parameter can be retrieved
+ context.put("sslClientCertProvider", new SSLClientCertProvider(httpReq));
+
+ try {
+ authToken = authenticate(credentials, authenticator, httpReq);
+ } catch (Exception e) {
+ CMS.debug("Authentication failure: " + e.getMessage());
+ throw new ServletException("Authentication failure: " + e.getMessage());
+ }
+ if (authToken == null) {
+ CMS.debug("Authentication failure.");
+ throw new ServletException("Authentication failure.");
+ }
+
+ // Deal with Transaction ID
+ String transactionID = req.getTransactionID();
+ responseData = responseData +
+ "<TransactionID>" + transactionID + "</TransactionID>";
+
+ // End-User or RA's IP address
+ responseData = responseData +
+ "<RemoteAddr>" + httpReq.getRemoteAddr() + "</RemoteAddr>";
+
+ responseData = responseData +
+ "<RemoteHost>" + httpReq.getRemoteHost() + "</RemoteHost>";
+
+ // Deal with Nonces
+ byte[] sn = req.getSenderNonce();
+
+ // Deal with message type
+ String mt = req.getMessageType();
+ responseData = responseData +
+ "<MessageType>" + mt + "</MessageType>";
+
+ PKCS10 p10 = (PKCS10) req.getP10();
+ X500Name p10subject = p10.getSubjectName();
+ responseData = responseData +
+ "<SubjectName>" + p10subject.toString() + "</SubjectName>";
+
+ String pkcs10Attr = "";
+ PKCS10Attributes p10atts = p10.getAttributes();
+ Enumeration<PKCS10Attribute> e = p10atts.getElements();
+
+ while (e.hasMoreElements()) {
+ PKCS10Attribute p10a = (PKCS10Attribute) e.nextElement();
+ CertAttrSet attr = p10a.getAttributeValue();
+
+ if (attr.getName().equals(ChallengePassword.NAME)) {
+ if (attr.get(ChallengePassword.PASSWORD) != null) {
+ pkcs10Attr = pkcs10Attr +
+ "<ChallengePassword><Password>" + (String) attr.get(ChallengePassword.PASSWORD) + "</Password></ChallengePassword>";
+ }
+
+ }
+ String extensionsStr = "";
+ if (attr.getName().equals(ExtensionsRequested.NAME)) {
+
+ Enumeration<Extension> exts = ((ExtensionsRequested) attr).getExtensions().elements();
+ while (exts.hasMoreElements()) {
+ Extension ext = exts.nextElement();
+
+ if (ext.getExtensionId().equals(
+ OIDMap.getOID(SubjectAlternativeNameExtension.IDENT))) {
+ DerOutputStream dos = new DerOutputStream();
+ SubjectAlternativeNameExtension sane = new SubjectAlternativeNameExtension(
+ Boolean.valueOf(false), // noncritical
+ ext.getExtensionValue());
+
+ @SuppressWarnings("unchecked")
+ Vector<GeneralNameInterface> v =
+ (Vector<GeneralNameInterface>) sane.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
+
+ Enumeration<GeneralNameInterface> gne = v.elements();
StringBuffer subjAltNameStr = new StringBuffer();
- while (gne.hasMoreElements()) {
- GeneralNameInterface gni = gne.nextElement();
- if (gni instanceof GeneralName) {
- GeneralName genName = (GeneralName) gni;
+ while (gne.hasMoreElements()) {
+ GeneralNameInterface gni = gne.nextElement();
+ if (gni instanceof GeneralName) {
+ GeneralName genName = (GeneralName) gni;
- String gn = genName.toString();
- int colon = gn.indexOf(':');
- String gnType = gn.substring(0,colon).trim();
- String gnValue = gn.substring(colon+1).trim();
+ String gn = genName.toString();
+ int colon = gn.indexOf(':');
+ String gnType = gn.substring(0, colon).trim();
+ String gnValue = gn.substring(colon + 1).trim();
subjAltNameStr.append("<");
subjAltNameStr.append(gnType);
@@ -761,1453 +733,1398 @@ protected IProfileSubsystem mProfileSubsystem = null;
subjAltNameStr.append("</");
subjAltNameStr.append(gnType);
subjAltNameStr.append(">");
- }
- } // while
+ }
+ } // while
extensionsStr = "<SubjAltName>" +
- subjAltNameStr.toString() + "</SubjAltName>";
- } // if
- } // while
- pkcs10Attr = pkcs10Attr +
+ subjAltNameStr.toString() + "</SubjAltName>";
+ } // if
+ } // while
+ pkcs10Attr = pkcs10Attr +
"<Extensions>" + extensionsStr + "</Extensions>";
- } // if extensions
- } // while
- responseData = responseData +
- "<PKCS10>" + pkcs10Attr + "</PKCS10>";
-
- } catch (ServletException e) {
- throw new ServletException(e.getMessage().toString());
- } catch (CRSInvalidSignatureException e) {
- CMS.debug("handlePKIMessage exception " + e);
- CMS.debug(e);
- } catch (Exception e) {
- CMS.debug("handlePKIMessage exception " + e);
- CMS.debug(e);
- throw new ServletException("Failed to process message in CEP servlet: "+ e.getMessage());
- }
-
- // We have now processed the request, and need to make the response message
-
- try {
-
- responseData = "<XMLResponse>" + responseData + "</XMLResponse>";
- // Get the response coding
- response = responseData.getBytes();
-
- // Encode the httpResp into B64
- httpResp.setContentType("application/xml");
- httpResp.setContentLength(response.length);
- httpResp.getOutputStream().write(response);
- httpResp.getOutputStream().flush();
-
- int i1 = responseData.indexOf("<Password>");
- if (i1 > -1) {
- i1 += 10; // 10 is a length of "<Password>"
- int i2 = responseData.indexOf("</Password>", i1);
- if (i2 > -1) {
- responseData = responseData.substring(0, i1) + "********" +
+ } // if extensions
+ } // while
+ responseData = responseData +
+ "<PKCS10>" + pkcs10Attr + "</PKCS10>";
+
+ } catch (ServletException e) {
+ throw new ServletException(e.getMessage().toString());
+ } catch (CRSInvalidSignatureException e) {
+ CMS.debug("handlePKIMessage exception " + e);
+ CMS.debug(e);
+ } catch (Exception e) {
+ CMS.debug("handlePKIMessage exception " + e);
+ CMS.debug(e);
+ throw new ServletException("Failed to process message in CEP servlet: " + e.getMessage());
+ }
+
+ // We have now processed the request, and need to make the response
+ // message
+
+ try {
+
+ responseData = "<XMLResponse>" + responseData + "</XMLResponse>";
+ // Get the response coding
+ response = responseData.getBytes();
+
+ // Encode the httpResp into B64
+ httpResp.setContentType("application/xml");
+ httpResp.setContentLength(response.length);
+ httpResp.getOutputStream().write(response);
+ httpResp.getOutputStream().flush();
+
+ int i1 = responseData.indexOf("<Password>");
+ if (i1 > -1) {
+ i1 += 10; // 10 is a length of "<Password>"
+ int i2 = responseData.indexOf("</Password>", i1);
+ if (i2 > -1) {
+ responseData = responseData.substring(0, i1) + "********" +
responseData.substring(i2, responseData.length());
- }
- }
-
- CMS.debug("Output (decoding) PKIOperation response:");
- CMS.debug(responseData);
- }
- catch (Exception e) {
- throw new ServletException("Failed to create response for CEP message"+e.getMessage());
- }
-
- }
-
-
- /**
- * finds a request with this transaction ID.
- * If could not find any request - return null
- * If could only find 'rejected' or 'cancelled' requests, return null
- * If found 'pending' or 'completed' request - return that request
- */
-
-
- public void handlePKIOperation(HttpServletRequest httpReq,
+ }
+ }
+
+ CMS.debug("Output (decoding) PKIOperation response:");
+ CMS.debug(responseData);
+ } catch (Exception e) {
+ throw new ServletException("Failed to create response for CEP message" + e.getMessage());
+ }
+
+ }
+
+ /**
+ * finds a request with this transaction ID. If could not find any request -
+ * return null If could only find 'rejected' or 'cancelled' requests, return
+ * null If found 'pending' or 'completed' request - return that request
+ */
+
+ public void handlePKIOperation(HttpServletRequest httpReq,
HttpServletResponse httpResp,
String msg)
- throws ServletException {
-
-
- CryptoContext cx=null;
-
- CRSPKIMessage req=null;
- CRSPKIMessage crsResp=null;
-
- byte[] decodedPKIMessage;
- byte[] response=null;
- X509CertImpl cert = null;
-
- decodedPKIMessage = com.netscape.osutil.OSUtil.AtoB(msg);
-
- try {
- ByteArrayInputStream is = new ByteArrayInputStream(decodedPKIMessage);
-
- // We make two CRSPKIMessages. One of them, is the request, so we initialize
- // it from the DER given to us from the router.
- // The second is the response, and we'll fill this in as we go.
-
- if (decodedPKIMessage.length < 50) {
- throw new ServletException("CRS request is too small to be a real request ("+
- decodedPKIMessage.length+" bytes)");
- }
- try {
- req = new CRSPKIMessage(is);
- String ea = req.getEncryptionAlgorithm();
- if (!isAlgorithmAllowed (mAllowedEncryptionAlgorithm, ea)) {
- CMS.debug("CRSEnrollment: handlePKIOperation: Encryption algorithm '"+ea+
- "' is not allowed ("+mEncryptionAlgorithmList+").");
- throw new ServletException("Encryption algorithm '"+ea+
- "' is not allowed ("+mEncryptionAlgorithmList+").");
+ throws ServletException {
+
+ CryptoContext cx = null;
+
+ CRSPKIMessage req = null;
+ CRSPKIMessage crsResp = null;
+
+ byte[] decodedPKIMessage;
+ byte[] response = null;
+ X509CertImpl cert = null;
+
+ decodedPKIMessage = com.netscape.osutil.OSUtil.AtoB(msg);
+
+ try {
+ ByteArrayInputStream is = new ByteArrayInputStream(decodedPKIMessage);
+
+ // We make two CRSPKIMessages. One of them, is the request, so we
+ // initialize
+ // it from the DER given to us from the router.
+ // The second is the response, and we'll fill this in as we go.
+
+ if (decodedPKIMessage.length < 50) {
+ throw new ServletException("CRS request is too small to be a real request (" +
+ decodedPKIMessage.length + " bytes)");
+ }
+ try {
+ req = new CRSPKIMessage(is);
+ String ea = req.getEncryptionAlgorithm();
+ if (!isAlgorithmAllowed(mAllowedEncryptionAlgorithm, ea)) {
+ CMS.debug("CRSEnrollment: handlePKIOperation: Encryption algorithm '" + ea +
+ "' is not allowed (" + mEncryptionAlgorithmList + ").");
+ throw new ServletException("Encryption algorithm '" + ea +
+ "' is not allowed (" + mEncryptionAlgorithmList + ").");
+ }
+ String da = req.getDigestAlgorithmName();
+ if (!isAlgorithmAllowed(mAllowedHashAlgorithm, da)) {
+ CMS.debug("CRSEnrollment: handlePKIOperation: Hashing algorithm '" + da +
+ "' is not allowed (" + mHashAlgorithmList + ").");
+ throw new ServletException("Hashing algorithm '" + da +
+ "' is not allowed (" + mHashAlgorithmList + ").");
+ }
+ if (ea != null) {
+ mEncryptionAlgorithm = ea;
+ }
+ crsResp = new CRSPKIMessage();
+ } catch (ServletException e) {
+ throw new ServletException(e.getMessage().toString());
+ } catch (Exception e) {
+ CMS.debug(e);
+ throw new ServletException("Could not decode the request.");
+ }
+ crsResp.setMessageType(CRSPKIMessage.mType_CertRep);
+
+ // Create a new crypto context for doing all the crypto operations
+ cx = new CryptoContext();
+
+ // Verify Signature on message (throws exception if sig bad)
+ verifyRequest(req, cx);
+
+ // Deal with Transaction ID
+ String transactionID = req.getTransactionID();
+ if (transactionID == null) {
+ throw new ServletException("Error: malformed PKIMessage - missing transactionID");
+ } else {
+ crsResp.setTransactionID(transactionID);
+ }
+
+ // Deal with Nonces
+ byte[] sn = req.getSenderNonce();
+ if (sn == null) {
+ throw new ServletException("Error: malformed PKIMessage - missing sendernonce");
+ } else {
+ if (mNonceSizeLimit > 0 && sn.length > mNonceSizeLimit) {
+ byte[] snLimited = (mNonceSizeLimit > 0) ? new byte[mNonceSizeLimit] : null;
+ System.arraycopy(sn, 0, snLimited, 0, mNonceSizeLimit);
+ crsResp.setRecipientNonce(snLimited);
+ } else {
+ crsResp.setRecipientNonce(sn);
+ }
+ byte[] serverNonce = new byte[16];
+ mRandom.nextBytes(serverNonce);
+ crsResp.setSenderNonce(serverNonce);
+ // crsResp.setSenderNonce(new byte[] {0});
}
- String da = req.getDigestAlgorithmName();
- if (!isAlgorithmAllowed (mAllowedHashAlgorithm, da)) {
- CMS.debug("CRSEnrollment: handlePKIOperation: Hashing algorithm '"+da+
- "' is not allowed ("+mHashAlgorithmList+").");
- throw new ServletException("Hashing algorithm '"+da+
- "' is not allowed ("+mHashAlgorithmList+").");
+
+ // Deal with message type
+ String mt = req.getMessageType();
+ if (mt == null) {
+ throw new ServletException("Error: malformed PKIMessage - missing messageType");
}
- if (ea != null) {
- mEncryptionAlgorithm = ea;
- }
- crsResp = new CRSPKIMessage();
- }
- catch (ServletException e) {
- throw new ServletException(e.getMessage().toString());
- }
- catch (Exception e) {
+
+ // now run appropriate code, depending on message type
+ if (mt.equals(CRSPKIMessage.mType_PKCSReq)) {
+ CMS.debug("Processing PKCSReq");
+ try {
+ // Check if there is an existing request. If this returns
+ // non-null,
+ // then the request is 'active' (either pending or
+ // completed) in
+ // which case, we compare the hash of the new request to the
+ // hash of the
+ // one in the queue - if they are the same, I return the
+ // state of the
+ // original request - as if it was 'getCertInitial' message.
+ // If the hashes are different, then the user attempted to
+ // enroll
+ // for a new request with the same txid, which is not
+ // allowed -
+ // so we return 'failure'.
+
+ IRequest cmsRequest = findRequestByTransactionID(req.getTransactionID(), true);
+
+ // If there was no request (with a cert) with this
+ // transaction ID,
+ // process it as a new request
+
+ cert = handlePKCSReq(httpReq, cmsRequest, req, crsResp, cx);
+
+ } catch (CRSFailureException e) {
+ throw new ServletException("Couldn't handle CEP request (PKCSReq) - " + e.getMessage());
+ }
+ } else if (mt.equals(CRSPKIMessage.mType_GetCertInitial)) {
+ CMS.debug("Processing GetCertInitial");
+ cert = handleGetCertInitial(req, crsResp);
+ } else {
+ CMS.debug("Invalid request type " + mt);
+ }
+ } catch (ServletException e) {
+ throw new ServletException(e.getMessage().toString());
+ } catch (CRSInvalidSignatureException e) {
+ CMS.debug("handlePKIMessage exception " + e);
+ CMS.debug(e);
+ crsResp.setFailInfo(CRSPKIMessage.mFailInfo_badMessageCheck);
+ } catch (Exception e) {
+ CMS.debug("handlePKIMessage exception " + e);
CMS.debug(e);
- throw new ServletException("Could not decode the request.");
- }
- crsResp.setMessageType(CRSPKIMessage.mType_CertRep);
-
- // Create a new crypto context for doing all the crypto operations
- cx = new CryptoContext();
-
- // Verify Signature on message (throws exception if sig bad)
- verifyRequest(req,cx);
-
- // Deal with Transaction ID
- String transactionID = req.getTransactionID();
- if (transactionID == null) {
- throw new ServletException("Error: malformed PKIMessage - missing transactionID");
- }
- else {
- crsResp.setTransactionID(transactionID);
- }
-
- // Deal with Nonces
- byte[] sn = req.getSenderNonce();
- if (sn == null) {
- throw new ServletException("Error: malformed PKIMessage - missing sendernonce");
- }
- else {
- if (mNonceSizeLimit > 0 && sn.length > mNonceSizeLimit) {
- byte[] snLimited = (mNonceSizeLimit > 0)? new byte[mNonceSizeLimit]: null;
- System.arraycopy(sn, 0, snLimited, 0, mNonceSizeLimit);
- crsResp.setRecipientNonce(snLimited);
- } else {
- crsResp.setRecipientNonce(sn);
- }
- byte[] serverNonce = new byte[16];
- mRandom.nextBytes(serverNonce);
- crsResp.setSenderNonce(serverNonce);
- // crsResp.setSenderNonce(new byte[] {0});
- }
-
- // Deal with message type
- String mt = req.getMessageType();
- if (mt == null) {
- throw new ServletException("Error: malformed PKIMessage - missing messageType");
- }
-
- // now run appropriate code, depending on message type
- if (mt.equals(CRSPKIMessage.mType_PKCSReq)) {
- CMS.debug("Processing PKCSReq");
- try {
- // Check if there is an existing request. If this returns non-null,
- // then the request is 'active' (either pending or completed) in
- // which case, we compare the hash of the new request to the hash of the
- // one in the queue - if they are the same, I return the state of the
- // original request - as if it was 'getCertInitial' message.
- // If the hashes are different, then the user attempted to enroll
- // for a new request with the same txid, which is not allowed -
- // so we return 'failure'.
-
- IRequest cmsRequest= findRequestByTransactionID(req.getTransactionID(),true);
-
- // If there was no request (with a cert) with this transaction ID,
- // process it as a new request
-
- cert = handlePKCSReq(httpReq, cmsRequest,req,crsResp,cx);
-
- }
- catch (CRSFailureException e) {
- throw new ServletException("Couldn't handle CEP request (PKCSReq) - "+e.getMessage());
- }
- }
- else if (mt.equals(CRSPKIMessage.mType_GetCertInitial)) {
- CMS.debug("Processing GetCertInitial");
- cert = handleGetCertInitial(req,crsResp);
- } else {
- CMS.debug("Invalid request type " + mt);
- }
- }
- catch (ServletException e) {
- throw new ServletException(e.getMessage().toString());
- }
- catch (CRSInvalidSignatureException e) {
- CMS.debug("handlePKIMessage exception " + e);
- CMS.debug(e);
- crsResp.setFailInfo(CRSPKIMessage.mFailInfo_badMessageCheck);
- }
- catch (Exception e) {
- CMS.debug("handlePKIMessage exception " + e);
- CMS.debug(e);
- throw new ServletException("Failed to process message in CEP servlet: "+ e.getMessage());
- }
-
- // We have now processed the request, and need to make the response message
-
- try {
- // make the response
- processCertRep(cx, cert,crsResp, req);
-
- // Get the response coding
- response = crsResp.getResponse();
-
- // Encode the crsResp into B64
- httpResp.setContentType("application/x-pki-message");
- httpResp.setContentLength(response.length);
- httpResp.getOutputStream().write(response);
- httpResp.getOutputStream().flush();
-
- CMS.debug("Output PKIOperation response:");
- CMS.debug(CMS.BtoA(response));
- }
- catch (Exception e) {
- throw new ServletException("Failed to create response for CEP message"+e.getMessage());
- }
-
- }
-
-
- /**
- * finds a request with this transaction ID.
- * If could not find any request - return null
- * If could only find 'rejected' or 'cancelled' requests, return null
- * If found 'pending' or 'completed' request - return that request
- */
-
- public IRequest findRequestByTransactionID(String txid, boolean ignoreRejected)
- throws EBaseException {
-
- /* Check if certificate request has been completed */
-
- IRequestQueue rq = ca.getRequestQueue();
- IRequest foundRequest = null;
-
- Enumeration<RequestId> rids = rq.findRequestsBySourceId(txid);
- if (rids == null) { return null; }
-
- int count=0;
- while (rids.hasMoreElements()) {
- RequestId rid = rids.nextElement();
- if (rid == null) {
- continue;
- }
-
- IRequest request = rq.findRequest(rid);
- if (request == null) {
- continue;
- }
- if ( !ignoreRejected ||
- request.getRequestStatus().equals(RequestStatus.PENDING) ||
- request.getRequestStatus().equals(RequestStatus.COMPLETE)) {
- if (foundRequest != null) {
- }
- foundRequest = request;
- }
- }
- return foundRequest;
- }
-
- /**
- * Called if the router is requesting us to send it its certificate
- * Examine request queue for a request matching the transaction ID.
- * Ignore any rejected or cancelled requests.
- *
- * If a request is found in the pending state, the response should be
- * 'pending'
- *
- * If a request is found in the completed state, the response should be
- * to return the certificate
- *
- * If no request is found, the response should be to return null
- *
- */
-
- public X509CertImpl handleGetCertInitial(CRSPKIMessage req,CRSPKIMessage resp)
- {
- IRequest foundRequest=null;
-
- // already done by handlePKIOperation
- // resp.setRecipientNonce(req.getSenderNonce());
- // resp.setSenderNonce(null);
-
- try {
- foundRequest = findRequestByTransactionID(req.getTransactionID(),false);
- } catch (EBaseException e) {
- }
-
- if (foundRequest == null) {
- resp.setFailInfo(CRSPKIMessage.mFailInfo_badCertId);
- resp.setPKIStatus(CRSPKIMessage.mStatus_FAILURE);
- return null;
- }
-
- return makeResponseFromRequest(req,resp,foundRequest);
- }
-
-
- public void verifyRequest(CRSPKIMessage req, CryptoContext cx)
- throws CRSInvalidSignatureException {
-
- // Get Signed Data
-
- byte[] reqAAbytes = req.getAA();
- byte[] reqAAsig = req.getAADigest();
-
- }
-
-
- /**
- * Create an entry for this user in the publishing directory
- *
- */
-
- private boolean createEntry(String dn)
- {
- boolean result = false;
-
- IPublisherProcessor ldapPub = mAuthority.getPublisherProcessor();
- if (ldapPub == null || !ldapPub.enabled()) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERROR_CREATE_ENTRY_FROM_CEP"));
-
- return result;
- }
-
- ILdapConnFactory connFactory = ((IPublisherProcessor)ldapPub).getLdapConnModule().getLdapConnFactory();
- if (connFactory == null) {
- return result;
- }
-
- LDAPConnection connection=null;
- try {
- connection = connFactory.getConn();
- String[] objectclasses = { "top", mEntryObjectclass };
- LDAPAttribute ocAttrs = new LDAPAttribute("objectclass",objectclasses);
-
- LDAPAttributeSet attrSet = new LDAPAttributeSet();
- attrSet.add(ocAttrs);
-
- LDAPEntry newEntry = new LDAPEntry(dn, attrSet);
- connection.add(newEntry);
- result=true;
- }
- catch (Exception e) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_FAIL_CREAT_ENTRY_EXISTS",dn));
- }
- finally {
- try {
- connFactory.returnConn(connection);
- }
- catch (Exception f) {}
- }
- return result;
+ throw new ServletException("Failed to process message in CEP servlet: " + e.getMessage());
+ }
+
+ // We have now processed the request, and need to make the response
+ // message
+
+ try {
+ // make the response
+ processCertRep(cx, cert, crsResp, req);
+
+ // Get the response coding
+ response = crsResp.getResponse();
+
+ // Encode the crsResp into B64
+ httpResp.setContentType("application/x-pki-message");
+ httpResp.setContentLength(response.length);
+ httpResp.getOutputStream().write(response);
+ httpResp.getOutputStream().flush();
+
+ CMS.debug("Output PKIOperation response:");
+ CMS.debug(CMS.BtoA(response));
+ } catch (Exception e) {
+ throw new ServletException("Failed to create response for CEP message" + e.getMessage());
+ }
+
+ }
+
+ /**
+ * finds a request with this transaction ID. If could not find any request -
+ * return null If could only find 'rejected' or 'cancelled' requests, return
+ * null If found 'pending' or 'completed' request - return that request
+ */
+
+ public IRequest findRequestByTransactionID(String txid, boolean ignoreRejected)
+ throws EBaseException {
+
+ /* Check if certificate request has been completed */
+
+ IRequestQueue rq = ca.getRequestQueue();
+ IRequest foundRequest = null;
+
+ Enumeration<RequestId> rids = rq.findRequestsBySourceId(txid);
+ if (rids == null) {
+ return null;
+ }
+
+ int count = 0;
+ while (rids.hasMoreElements()) {
+ RequestId rid = rids.nextElement();
+ if (rid == null) {
+ continue;
+ }
+
+ IRequest request = rq.findRequest(rid);
+ if (request == null) {
+ continue;
+ }
+ if (!ignoreRejected ||
+ request.getRequestStatus().equals(RequestStatus.PENDING) ||
+ request.getRequestStatus().equals(RequestStatus.COMPLETE)) {
+ if (foundRequest != null) {
+ }
+ foundRequest = request;
+ }
+ }
+ return foundRequest;
+ }
+
+ /**
+ * Called if the router is requesting us to send it its certificate Examine
+ * request queue for a request matching the transaction ID. Ignore any
+ * rejected or cancelled requests.
+ *
+ * If a request is found in the pending state, the response should be
+ * 'pending'
+ *
+ * If a request is found in the completed state, the response should be to
+ * return the certificate
+ *
+ * If no request is found, the response should be to return null
+ *
+ */
+
+ public X509CertImpl handleGetCertInitial(CRSPKIMessage req, CRSPKIMessage resp) {
+ IRequest foundRequest = null;
+
+ // already done by handlePKIOperation
+ // resp.setRecipientNonce(req.getSenderNonce());
+ // resp.setSenderNonce(null);
+
+ try {
+ foundRequest = findRequestByTransactionID(req.getTransactionID(), false);
+ } catch (EBaseException e) {
+ }
+
+ if (foundRequest == null) {
+ resp.setFailInfo(CRSPKIMessage.mFailInfo_badCertId);
+ resp.setPKIStatus(CRSPKIMessage.mStatus_FAILURE);
+ return null;
+ }
+
+ return makeResponseFromRequest(req, resp, foundRequest);
+ }
+
+ public void verifyRequest(CRSPKIMessage req, CryptoContext cx)
+ throws CRSInvalidSignatureException {
+
+ // Get Signed Data
+
+ byte[] reqAAbytes = req.getAA();
+ byte[] reqAAsig = req.getAADigest();
+
}
+ /**
+ * Create an entry for this user in the publishing directory
+ *
+ */
+ private boolean createEntry(String dn) {
+ boolean result = false;
- /**
- * Here we decrypt the PKCS10 message from the client
- *
- */
-
- public void unwrapPKCS10(CRSPKIMessage req, CryptoContext cx)
- throws ServletException,
+ IPublisherProcessor ldapPub = mAuthority.getPublisherProcessor();
+ if (ldapPub == null || !ldapPub.enabled()) {
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERROR_CREATE_ENTRY_FROM_CEP"));
+
+ return result;
+ }
+
+ ILdapConnFactory connFactory = ((IPublisherProcessor) ldapPub).getLdapConnModule().getLdapConnFactory();
+ if (connFactory == null) {
+ return result;
+ }
+
+ LDAPConnection connection = null;
+ try {
+ connection = connFactory.getConn();
+ String[] objectclasses = { "top", mEntryObjectclass };
+ LDAPAttribute ocAttrs = new LDAPAttribute("objectclass", objectclasses);
+
+ LDAPAttributeSet attrSet = new LDAPAttributeSet();
+ attrSet.add(ocAttrs);
+
+ LDAPEntry newEntry = new LDAPEntry(dn, attrSet);
+ connection.add(newEntry);
+ result = true;
+ } catch (Exception e) {
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_FAIL_CREAT_ENTRY_EXISTS", dn));
+ } finally {
+ try {
+ connFactory.returnConn(connection);
+ } catch (Exception f) {
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Here we decrypt the PKCS10 message from the client
+ *
+ */
+
+ public void unwrapPKCS10(CRSPKIMessage req, CryptoContext cx)
+ throws ServletException,
CryptoManager.NotInitializedException,
- CryptoContext.CryptoContextException,
+ CryptoContext.CryptoContextException,
CRSFailureException {
-
- byte[] decryptedP10bytes = null;
- SymmetricKey sk;
- SymmetricKey skinternal;
- SymmetricKey.Type skt;
- KeyWrapper kw;
- Cipher cip;
- EncryptionAlgorithm ea;
- boolean errorInRequest = false;
-
- // Unwrap the session key with the Cert server key
- try {
- kw = cx.getKeyWrapper();
-
- kw.initUnwrap(cx.getPrivateKey(),null);
-
- skt = SymmetricKey.Type.DES;
- ea = EncryptionAlgorithm.DES_CBC;
- if (mEncryptionAlgorithm != null && mEncryptionAlgorithm.equals("DES3")) {
- skt = SymmetricKey.Type.DES3;
- ea = EncryptionAlgorithm.DES3_CBC;
- }
-
- sk = kw.unwrapSymmetric(req.getWrappedKey(),
+
+ byte[] decryptedP10bytes = null;
+ SymmetricKey sk;
+ SymmetricKey skinternal;
+ SymmetricKey.Type skt;
+ KeyWrapper kw;
+ Cipher cip;
+ EncryptionAlgorithm ea;
+ boolean errorInRequest = false;
+
+ // Unwrap the session key with the Cert server key
+ try {
+ kw = cx.getKeyWrapper();
+
+ kw.initUnwrap(cx.getPrivateKey(), null);
+
+ skt = SymmetricKey.Type.DES;
+ ea = EncryptionAlgorithm.DES_CBC;
+ if (mEncryptionAlgorithm != null && mEncryptionAlgorithm.equals("DES3")) {
+ skt = SymmetricKey.Type.DES3;
+ ea = EncryptionAlgorithm.DES3_CBC;
+ }
+
+ sk = kw.unwrapSymmetric(req.getWrappedKey(),
skt,
SymmetricKey.Usage.DECRYPT,
- 0); // keylength is ignored
-
- skinternal = cx.getDESKeyGenerator().clone(sk);
-
- cip = skinternal.getOwningToken().getCipherContext(ea);
-
- cip.initDecrypt(skinternal,(new IVParameterSpec(req.getIV())));
-
- decryptedP10bytes = cip.doFinal(req.getEncryptedPkcs10());
- CMS.debug("decryptedP10bytes:");
- CMS.debug(decryptedP10bytes);
-
- req.setP10(new PKCS10(decryptedP10bytes));
- } catch (Exception e) {
- CMS.debug("failed to unwrap PKCS10 " + e);
- throw new CRSFailureException("Could not unwrap PKCS10 blob: "+e.getMessage());
- }
-
- }
-
-
-
-private void getDetailFromRequest(CRSPKIMessage req, CRSPKIMessage crsResp)
- throws CRSFailureException {
-
- IRequest issueReq = null;
- X509CertImpl issuedCert=null;
- SubjectAlternativeNameExtension sane = null;
- CertAttrSet requested_ext = null;
-
- try {
- PKCS10 p10 = req.getP10();
-
- if (p10 == null) {
- crsResp.setFailInfo(CRSPKIMessage.mFailInfo_badMessageCheck);
- crsResp.setPKIStatus(CRSPKIMessage.mStatus_FAILURE);
- throw new CRSFailureException("Failed to decode pkcs10 from CEP request");
- }
-
- AuthCredentials authCreds = new AuthCredentials();
-
- String challengePassword = null;
- // Here, we make a new CertInfo - it's a new start for a certificate
-
- X509CertInfo certInfo = CMS.getDefaultX509CertInfo();
-
- // get some stuff out of the request
- X509Key key = p10.getSubjectPublicKeyInfo();
- X500Name p10subject = p10.getSubjectName();
-
- X500Name subject=null;
-
- // The following code will copy all the attributes
- // into the AuthCredentials so they can be used for
- // authentication
- //
- // Optionally, you can re-map the subject name from:
- // one RDN, with many AVA's to
- // many RDN's with one AVA in each.
-
- Enumeration<RDN> rdne = p10subject.getRDNs();
- Vector<RDN> rdnv = new Vector<RDN>();
-
- Hashtable<String, String> sanehash = new Hashtable<String, String>();
-
- X500NameAttrMap xnap = X500NameAttrMap.getDefault();
- while (rdne.hasMoreElements()) {
- RDN rdn = (RDN) rdne.nextElement();
- int i=0;
- AVA[] oldavas = rdn.getAssertion();
- for (i=0; i<rdn.getAssertionLength(); i++) {
- AVA[] newavas = new AVA[1];
- newavas[0] = oldavas[i];
-
- authCreds.set(xnap.getName(oldavas[i].getOid()),
- oldavas[i].getValue().getAsString());
-
- if (oldavas[i].getOid().equals(OID_UNSTRUCTUREDNAME)) {
-
- sanehash.put(SANE_DNSNAME,oldavas[i].getValue().getAsString());
- }
- if (oldavas[i].getOid().equals(OID_UNSTRUCTUREDADDRESS)) {
- sanehash.put(SANE_IPADDRESS,oldavas[i].getValue().getAsString());
- }
-
- RDN newrdn = new RDN(newavas);
- if (mFlattenDN) {
- rdnv.addElement(newrdn);
- }
- }
- }
-
- if (mFlattenDN) subject = new X500Name(rdnv);
- else subject = p10subject;
-
-
- // create default key usage extension
- KeyUsageExtension kue = new KeyUsageExtension();
- kue.set(KeyUsageExtension.DIGITAL_SIGNATURE, Boolean.valueOf(true));
- kue.set(KeyUsageExtension.KEY_ENCIPHERMENT, Boolean.valueOf(true));
-
-
- PKCS10Attributes p10atts = p10.getAttributes();
- Enumeration<PKCS10Attribute> e = p10atts.getElements();
-
- while (e.hasMoreElements()) {
- PKCS10Attribute p10a = (PKCS10Attribute)e.nextElement();
- CertAttrSet attr = p10a.getAttributeValue();
-
-
- if (attr.getName().equals(ChallengePassword.NAME)) {
- if (attr.get(ChallengePassword.PASSWORD) != null) {
- req.put(AUTH_PASSWORD,
- (String)attr.get(ChallengePassword.PASSWORD));
- req.put(ChallengePassword.NAME,
- hashPassword(
- (String)attr.get(ChallengePassword.PASSWORD)));
- }
- }
-
- if (attr.getName().equals(ExtensionsRequested.NAME)) {
-
- Enumeration<Extension> exts = ((ExtensionsRequested)attr).getExtensions().elements();
- while (exts.hasMoreElements()) {
- Extension ext = exts.nextElement();
-
- if (ext.getExtensionId().equals(
- OIDMap.getOID(KeyUsageExtension.IDENT)) ) {
-
- kue = new KeyUsageExtension(
- new Boolean(false), // noncritical
- ext.getExtensionValue());
- }
-
- if (ext.getExtensionId().equals(
- OIDMap.getOID(SubjectAlternativeNameExtension.IDENT)) ) {
- DerOutputStream dos = new DerOutputStream();
- sane = new SubjectAlternativeNameExtension(
- new Boolean(false), // noncritical
- ext.getExtensionValue());
-
-
- @SuppressWarnings("unchecked")
- Vector<GeneralNameInterface> v =
- (Vector<GeneralNameInterface>) sane.get(SubjectAlternativeNameExtension. SUBJECT_NAME);
-
- Enumeration<GeneralNameInterface> gne = v.elements();
-
- while (gne.hasMoreElements()) {
- GeneralNameInterface gni = (GeneralNameInterface) gne.nextElement();
- if (gni instanceof GeneralName) {
- GeneralName genName = (GeneralName) gni;
-
- String gn = genName.toString();
- int colon = gn.indexOf(':');
- String gnType = gn.substring(0,colon).trim();
- String gnValue = gn.substring(colon+1).trim();
-
- authCreds.set(gnType,gnValue);
- }
- }
- }
- }
- }
- }
-
- if (authCreds != null) req.put(AUTH_CREDS,authCreds);
-
- try {
- if (sane == null) sane = makeDefaultSubjectAltName(sanehash);
- } catch (Exception sane_e) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ENROLL_FAIL_NO_SUBJ_ALT_NAME",
- sane_e.getMessage()));
- }
-
-
-
- try {
- if (mAppendDN != null && ! mAppendDN.equals("")) {
-
- X500Name newSubject = new X500Name(subject.toString());
- subject = new X500Name( subject.toString().concat(","+mAppendDN));
- }
-
- } catch (Exception sne) {
- log(ILogger.LL_INFO, "Unable to use appendDN parameter: "+mAppendDN+". Error is "+sne.getMessage()+" Using unmodified subjectname");
- }
-
- if (subject != null) req.put(SUBJECTNAME, subject);
-
- if (key == null || subject == null) {
- // log
- //throw new ERegistrationException(RegistrationResources.ERROR_MALFORMED_P10);
- }
-
-
-
- certInfo.set(X509CertInfo.VERSION,
+ 0); // keylength is ignored
+
+ skinternal = cx.getDESKeyGenerator().clone(sk);
+
+ cip = skinternal.getOwningToken().getCipherContext(ea);
+
+ cip.initDecrypt(skinternal, (new IVParameterSpec(req.getIV())));
+
+ decryptedP10bytes = cip.doFinal(req.getEncryptedPkcs10());
+ CMS.debug("decryptedP10bytes:");
+ CMS.debug(decryptedP10bytes);
+
+ req.setP10(new PKCS10(decryptedP10bytes));
+ } catch (Exception e) {
+ CMS.debug("failed to unwrap PKCS10 " + e);
+ throw new CRSFailureException("Could not unwrap PKCS10 blob: " + e.getMessage());
+ }
+
+ }
+
+ private void getDetailFromRequest(CRSPKIMessage req, CRSPKIMessage crsResp)
+ throws CRSFailureException {
+
+ IRequest issueReq = null;
+ X509CertImpl issuedCert = null;
+ SubjectAlternativeNameExtension sane = null;
+ CertAttrSet requested_ext = null;
+
+ try {
+ PKCS10 p10 = req.getP10();
+
+ if (p10 == null) {
+ crsResp.setFailInfo(CRSPKIMessage.mFailInfo_badMessageCheck);
+ crsResp.setPKIStatus(CRSPKIMessage.mStatus_FAILURE);
+ throw new CRSFailureException("Failed to decode pkcs10 from CEP request");
+ }
+
+ AuthCredentials authCreds = new AuthCredentials();
+
+ String challengePassword = null;
+ // Here, we make a new CertInfo - it's a new start for a certificate
+
+ X509CertInfo certInfo = CMS.getDefaultX509CertInfo();
+
+ // get some stuff out of the request
+ X509Key key = p10.getSubjectPublicKeyInfo();
+ X500Name p10subject = p10.getSubjectName();
+
+ X500Name subject = null;
+
+ // The following code will copy all the attributes
+ // into the AuthCredentials so they can be used for
+ // authentication
+ //
+ // Optionally, you can re-map the subject name from:
+ // one RDN, with many AVA's to
+ // many RDN's with one AVA in each.
+
+ Enumeration<RDN> rdne = p10subject.getRDNs();
+ Vector<RDN> rdnv = new Vector<RDN>();
+
+ Hashtable<String, String> sanehash = new Hashtable<String, String>();
+
+ X500NameAttrMap xnap = X500NameAttrMap.getDefault();
+ while (rdne.hasMoreElements()) {
+ RDN rdn = (RDN) rdne.nextElement();
+ int i = 0;
+ AVA[] oldavas = rdn.getAssertion();
+ for (i = 0; i < rdn.getAssertionLength(); i++) {
+ AVA[] newavas = new AVA[1];
+ newavas[0] = oldavas[i];
+
+ authCreds.set(xnap.getName(oldavas[i].getOid()),
+ oldavas[i].getValue().getAsString());
+
+ if (oldavas[i].getOid().equals(OID_UNSTRUCTUREDNAME)) {
+
+ sanehash.put(SANE_DNSNAME, oldavas[i].getValue().getAsString());
+ }
+ if (oldavas[i].getOid().equals(OID_UNSTRUCTUREDADDRESS)) {
+ sanehash.put(SANE_IPADDRESS, oldavas[i].getValue().getAsString());
+ }
+
+ RDN newrdn = new RDN(newavas);
+ if (mFlattenDN) {
+ rdnv.addElement(newrdn);
+ }
+ }
+ }
+
+ if (mFlattenDN)
+ subject = new X500Name(rdnv);
+ else
+ subject = p10subject;
+
+ // create default key usage extension
+ KeyUsageExtension kue = new KeyUsageExtension();
+ kue.set(KeyUsageExtension.DIGITAL_SIGNATURE, Boolean.valueOf(true));
+ kue.set(KeyUsageExtension.KEY_ENCIPHERMENT, Boolean.valueOf(true));
+
+ PKCS10Attributes p10atts = p10.getAttributes();
+ Enumeration<PKCS10Attribute> e = p10atts.getElements();
+
+ while (e.hasMoreElements()) {
+ PKCS10Attribute p10a = (PKCS10Attribute) e.nextElement();
+ CertAttrSet attr = p10a.getAttributeValue();
+
+ if (attr.getName().equals(ChallengePassword.NAME)) {
+ if (attr.get(ChallengePassword.PASSWORD) != null) {
+ req.put(AUTH_PASSWORD,
+ (String) attr.get(ChallengePassword.PASSWORD));
+ req.put(ChallengePassword.NAME,
+ hashPassword(
+ (String) attr.get(ChallengePassword.PASSWORD)));
+ }
+ }
+
+ if (attr.getName().equals(ExtensionsRequested.NAME)) {
+
+ Enumeration<Extension> exts = ((ExtensionsRequested) attr).getExtensions().elements();
+ while (exts.hasMoreElements()) {
+ Extension ext = exts.nextElement();
+
+ if (ext.getExtensionId().equals(
+ OIDMap.getOID(KeyUsageExtension.IDENT))) {
+
+ kue = new KeyUsageExtension(
+ new Boolean(false), // noncritical
+ ext.getExtensionValue());
+ }
+
+ if (ext.getExtensionId().equals(
+ OIDMap.getOID(SubjectAlternativeNameExtension.IDENT))) {
+ DerOutputStream dos = new DerOutputStream();
+ sane = new SubjectAlternativeNameExtension(
+ new Boolean(false), // noncritical
+ ext.getExtensionValue());
+
+ @SuppressWarnings("unchecked")
+ Vector<GeneralNameInterface> v =
+ (Vector<GeneralNameInterface>) sane.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
+
+ Enumeration<GeneralNameInterface> gne = v.elements();
+
+ while (gne.hasMoreElements()) {
+ GeneralNameInterface gni = (GeneralNameInterface) gne.nextElement();
+ if (gni instanceof GeneralName) {
+ GeneralName genName = (GeneralName) gni;
+
+ String gn = genName.toString();
+ int colon = gn.indexOf(':');
+ String gnType = gn.substring(0, colon).trim();
+ String gnValue = gn.substring(colon + 1).trim();
+
+ authCreds.set(gnType, gnValue);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if (authCreds != null)
+ req.put(AUTH_CREDS, authCreds);
+
+ try {
+ if (sane == null)
+ sane = makeDefaultSubjectAltName(sanehash);
+ } catch (Exception sane_e) {
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ENROLL_FAIL_NO_SUBJ_ALT_NAME",
+ sane_e.getMessage()));
+ }
+
+ try {
+ if (mAppendDN != null && !mAppendDN.equals("")) {
+
+ X500Name newSubject = new X500Name(subject.toString());
+ subject = new X500Name(subject.toString().concat("," + mAppendDN));
+ }
+
+ } catch (Exception sne) {
+ log(ILogger.LL_INFO, "Unable to use appendDN parameter: " + mAppendDN + ". Error is " + sne.getMessage() + " Using unmodified subjectname");
+ }
+
+ if (subject != null)
+ req.put(SUBJECTNAME, subject);
+
+ if (key == null || subject == null) {
+ // log
+ // throw new
+ // ERegistrationException(RegistrationResources.ERROR_MALFORMED_P10);
+ }
+
+ certInfo.set(X509CertInfo.VERSION,
new CertificateVersion(CertificateVersion.V3));
-
- certInfo.set(X509CertInfo.SUBJECT,
+
+ certInfo.set(X509CertInfo.SUBJECT,
new CertificateSubjectName(subject));
-
- certInfo.set(X509CertInfo.KEY,
+
+ certInfo.set(X509CertInfo.KEY,
new CertificateX509Key(key));
-
- CertificateExtensions ext = new CertificateExtensions();
-
- if (kue != null) {
- ext.set(KeyUsageExtension.class.getSimpleName(), kue);
- }
-
- // add subjectAltName extension, if present
- if (sane != null) {
- ext.set(SubjectAlternativeNameExtension.class.getSimpleName(), sane);
- }
-
- certInfo.set(X509CertInfo.EXTENSIONS,ext);
-
- req.put(CERTINFO, certInfo);
- } catch (Exception e) {
- crsResp.setFailInfo(CRSPKIMessage.mFailInfo_badMessageCheck);
- crsResp.setPKIStatus(CRSPKIMessage.mStatus_FAILURE);
- return ;
- } // NEED TO FIX
- }
-
-
- private SubjectAlternativeNameExtension makeDefaultSubjectAltName(Hashtable<String, String> ht) {
-
- // if no subjectaltname extension was requested, we try to make it up
- // from some of the elements of the subject name
-
- int itemCount = ht.size();
- GeneralNameInterface[] gn = new GeneralNameInterface[ht.size()];
-
- itemCount = 0;
- Enumeration<String> en = ht.keys();
- while (en.hasMoreElements()) {
- String key = (String) en.nextElement();
- if (key.equals(SANE_DNSNAME)) {
- gn[itemCount++] = new DNSName((String)ht.get(key));
- }
- if (key.equals(SANE_IPADDRESS)) {
- gn[itemCount++] = new IPAddressName((String)ht.get(key));
+
+ CertificateExtensions ext = new CertificateExtensions();
+
+ if (kue != null) {
+ ext.set(KeyUsageExtension.class.getSimpleName(), kue);
+ }
+
+ // add subjectAltName extension, if present
+ if (sane != null) {
+ ext.set(SubjectAlternativeNameExtension.class.getSimpleName(), sane);
+ }
+
+ certInfo.set(X509CertInfo.EXTENSIONS, ext);
+
+ req.put(CERTINFO, certInfo);
+ } catch (Exception e) {
+ crsResp.setFailInfo(CRSPKIMessage.mFailInfo_badMessageCheck);
+ crsResp.setPKIStatus(CRSPKIMessage.mStatus_FAILURE);
+ return;
+ } // NEED TO FIX
+ }
+
+ private SubjectAlternativeNameExtension makeDefaultSubjectAltName(Hashtable<String, String> ht) {
+
+ // if no subjectaltname extension was requested, we try to make it up
+ // from some of the elements of the subject name
+
+ int itemCount = ht.size();
+ GeneralNameInterface[] gn = new GeneralNameInterface[ht.size()];
+
+ itemCount = 0;
+ Enumeration<String> en = ht.keys();
+ while (en.hasMoreElements()) {
+ String key = (String) en.nextElement();
+ if (key.equals(SANE_DNSNAME)) {
+ gn[itemCount++] = new DNSName((String) ht.get(key));
+ }
+ if (key.equals(SANE_IPADDRESS)) {
+ gn[itemCount++] = new IPAddressName((String) ht.get(key));
+ }
+ }
+
+ try {
+ return new SubjectAlternativeNameExtension(new GeneralNames(gn));
+ } catch (Exception e) {
+ log(ILogger.LL_INFO, CMS.getLogMessage("CMSGW_ENROLL_FAIL_NO_SUBJ_ALT_NAME",
+ e.getMessage()));
+ return null;
}
}
- try {
- return new SubjectAlternativeNameExtension( new GeneralNames(gn) );
- } catch (Exception e) {
- log(ILogger.LL_INFO, CMS.getLogMessage("CMSGW_ENROLL_FAIL_NO_SUBJ_ALT_NAME",
- e.getMessage()));
- return null;
- }
- }
-
-
-
- // Perform authentication
-
- /*
- * if the authentication is set up for CEP, and the user provides
- * some credential, an attempt is made to authenticate the user
- * If this fails, this method will return true
- * If it is sucessful, this method will return true and
- * an authtoken will be in the request
- *
- * If authentication is not configured, this method will
- * return false. The request will be processed in the usual
- * way, but no authtoken will be in the request.
- *
- * In other word, this method returns true if the request
- * should be aborted, false otherwise.
- */
-
- private boolean authenticateUser(CRSPKIMessage req) {
- boolean authenticationFailed = true;
-
- if (mAuthManagerName == null) {
- return false;
- }
-
- String password = (String)req.get(AUTH_PASSWORD);
-
- AuthCredentials authCreds = (AuthCredentials)req.get(AUTH_CREDS);
-
- if (authCreds == null) {
- authCreds = new AuthCredentials();
- }
-
- // authtoken starts as null
- AuthToken token = null;
-
- if (password != null && !password.equals("")) {
- try {
- authCreds.set(AUTH_PASSWORD,password);
- } catch (Exception e) {}
- }
-
+ // Perform authentication
+
+ /*
+ * if the authentication is set up for CEP, and the user provides some
+ * credential, an attempt is made to authenticate the user If this fails,
+ * this method will return true If it is sucessful, this method will return
+ * true and an authtoken will be in the request
+ *
+ * If authentication is not configured, this method will return false. The
+ * request will be processed in the usual way, but no authtoken will be in
+ * the request.
+ *
+ * In other word, this method returns true if the request should be aborted,
+ * false otherwise.
+ */
- try {
- token = (AuthToken)mAuthSubsystem.authenticate(authCreds,mAuthManagerName);
- authCreds.delete(AUTH_PASSWORD);
- // if we got here, the authenticate call must not have thrown
- // an exception
- authenticationFailed = false;
- }
- catch (EInvalidCredentials ex) {
- // Invalid credentials - we must reject the request
- authenticationFailed = true;
- }
- catch (EMissingCredential mc) {
- // Misssing credential - we'll log, and process manually
- authenticationFailed = false;
- }
- catch (EBaseException ex) {
- // If there's some other error, we'll reject
- // So, we just continue on, - AUTH_TOKEN will not be set.
- }
-
- if (token != null) {
- req.put(AUTH_TOKEN,token);
- }
-
- return authenticationFailed;
- }
-
- private boolean areFingerprintsEqual(IRequest req, Hashtable<String, byte[]> fingerprints)
- {
-
- Hashtable<String, Object> old_fprints = req.getExtDataInHashtable(IRequest.FINGERPRINTS);
- if (old_fprints == null) { return false; }
-
- byte[] old_md5 = CMS.AtoB((String) old_fprints.get("MD5"));
- byte[] new_md5 = (byte[]) fingerprints.get("MD5");
-
- if (old_md5.length != new_md5.length) return false;
-
- for (int i=0;i<old_md5.length; i++) {
- if (old_md5[i] != new_md5[i]) return false;
- }
- return true;
- }
-
- public X509CertImpl handlePKCSReq(HttpServletRequest httpReq,
- IRequest cmsRequest, CRSPKIMessage req,
- CRSPKIMessage crsResp, CryptoContext cx)
- throws ServletException,
+ private boolean authenticateUser(CRSPKIMessage req) {
+ boolean authenticationFailed = true;
+
+ if (mAuthManagerName == null) {
+ return false;
+ }
+
+ String password = (String) req.get(AUTH_PASSWORD);
+
+ AuthCredentials authCreds = (AuthCredentials) req.get(AUTH_CREDS);
+
+ if (authCreds == null) {
+ authCreds = new AuthCredentials();
+ }
+
+ // authtoken starts as null
+ AuthToken token = null;
+
+ if (password != null && !password.equals("")) {
+ try {
+ authCreds.set(AUTH_PASSWORD, password);
+ } catch (Exception e) {
+ }
+ }
+
+ try {
+ token = (AuthToken) mAuthSubsystem.authenticate(authCreds, mAuthManagerName);
+ authCreds.delete(AUTH_PASSWORD);
+ // if we got here, the authenticate call must not have thrown
+ // an exception
+ authenticationFailed = false;
+ } catch (EInvalidCredentials ex) {
+ // Invalid credentials - we must reject the request
+ authenticationFailed = true;
+ } catch (EMissingCredential mc) {
+ // Misssing credential - we'll log, and process manually
+ authenticationFailed = false;
+ } catch (EBaseException ex) {
+ // If there's some other error, we'll reject
+ // So, we just continue on, - AUTH_TOKEN will not be set.
+ }
+
+ if (token != null) {
+ req.put(AUTH_TOKEN, token);
+ }
+
+ return authenticationFailed;
+ }
+
+ private boolean areFingerprintsEqual(IRequest req, Hashtable<String, byte[]> fingerprints) {
+
+ Hashtable<String, Object> old_fprints = req.getExtDataInHashtable(IRequest.FINGERPRINTS);
+ if (old_fprints == null) {
+ return false;
+ }
+
+ byte[] old_md5 = CMS.AtoB((String) old_fprints.get("MD5"));
+ byte[] new_md5 = (byte[]) fingerprints.get("MD5");
+
+ if (old_md5.length != new_md5.length)
+ return false;
+
+ for (int i = 0; i < old_md5.length; i++) {
+ if (old_md5[i] != new_md5[i])
+ return false;
+ }
+ return true;
+ }
+
+ public X509CertImpl handlePKCSReq(HttpServletRequest httpReq,
+ IRequest cmsRequest, CRSPKIMessage req,
+ CRSPKIMessage crsResp, CryptoContext cx)
+ throws ServletException,
CryptoManager.NotInitializedException,
CRSFailureException {
- try {
- unwrapPKCS10(req,cx);
- Hashtable<String, byte[]> fingerprints = makeFingerPrints(req);
-
- if (cmsRequest != null) {
- if (areFingerprintsEqual(cmsRequest, fingerprints)) {
- CMS.debug("created response from request");
- return makeResponseFromRequest(req,crsResp,cmsRequest);
- }
- else {
- CMS.debug("duplicated transaction id");
- log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ENROLL_FAIL_DUP_TRANS_ID"));
- crsResp.setFailInfo(CRSPKIMessage.mFailInfo_badRequest);
- crsResp.setPKIStatus(CRSPKIMessage.mStatus_FAILURE);
- return null;
- }
- }
-
- getDetailFromRequest(req,crsResp);
- boolean authFailed = authenticateUser(req);
-
- if (authFailed) {
- CMS.debug("authentication failed");
- log(ILogger.LL_SECURITY, CMS.getLogMessage("CMSGW_ENROLL_FAIL_NO_AUTH"));
- crsResp.setFailInfo(CRSPKIMessage.mFailInfo_badIdentity);
- crsResp.setPKIStatus(CRSPKIMessage.mStatus_FAILURE);
-
-
- // perform audit log
- String auditMessage = CMS.getLogMessage(
+ try {
+ unwrapPKCS10(req, cx);
+ Hashtable<String, byte[]> fingerprints = makeFingerPrints(req);
+
+ if (cmsRequest != null) {
+ if (areFingerprintsEqual(cmsRequest, fingerprints)) {
+ CMS.debug("created response from request");
+ return makeResponseFromRequest(req, crsResp, cmsRequest);
+ } else {
+ CMS.debug("duplicated transaction id");
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ENROLL_FAIL_DUP_TRANS_ID"));
+ crsResp.setFailInfo(CRSPKIMessage.mFailInfo_badRequest);
+ crsResp.setPKIStatus(CRSPKIMessage.mStatus_FAILURE);
+ return null;
+ }
+ }
+
+ getDetailFromRequest(req, crsResp);
+ boolean authFailed = authenticateUser(req);
+
+ if (authFailed) {
+ CMS.debug("authentication failed");
+ log(ILogger.LL_SECURITY, CMS.getLogMessage("CMSGW_ENROLL_FAIL_NO_AUTH"));
+ crsResp.setFailInfo(CRSPKIMessage.mFailInfo_badIdentity);
+ crsResp.setPKIStatus(CRSPKIMessage.mStatus_FAILURE);
+
+ // perform audit log
+ String auditMessage = CMS.getLogMessage(
"LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST_5",
httpReq.getRemoteAddr(),
ILogger.FAILURE,
req.getTransactionID(),
"CRSEnrollment",
ILogger.SIGNED_AUDIT_EMPTY_VALUE);
- ILogger signedAuditLogger = CMS.getSignedAuditLogger();
- if (signedAuditLogger != null) {
- signedAuditLogger.log(ILogger.EV_SIGNED_AUDIT,
- null, ILogger.S_SIGNED_AUDIT,
- ILogger.LL_SECURITY, auditMessage);
- }
-
- return null;
- }
- else {
- IRequest ireq = postRequest(httpReq, req,crsResp);
-
-
- CMS.debug("created response");
- return makeResponseFromRequest(req,crsResp, ireq);
- }
- } catch (CryptoContext.CryptoContextException e) {
- CMS.debug("failed to decrypt the request " + e);
- log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ENROLL_FAIL_NO_DECRYPT_PKCS10",
- e.getMessage()));
- crsResp.setFailInfo(CRSPKIMessage.mFailInfo_badMessageCheck);
- crsResp.setPKIStatus(CRSPKIMessage.mStatus_FAILURE);
- } catch (EBaseException e) {
- CMS.debug("operation failure - " + e);
- log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERNOLL_FAIL_NO_NEW_REQUEST_POSTED",
- e.getMessage()));
- crsResp.setFailInfo(CRSPKIMessage.mFailInfo_internalCAError);
- crsResp.setPKIStatus(CRSPKIMessage.mStatus_FAILURE);
- }
- return null;
- }
-
-
-////// post the request
-
-/*
- needed:
-
- token (authtoken)
- certInfo
- fingerprints x
- req.transactionID
- crsResp
-*/
-
-private IRequest postRequest(HttpServletRequest httpReq, CRSPKIMessage req, CRSPKIMessage crsResp)
-throws EBaseException {
- X500Name subject = (X500Name)req.get(SUBJECTNAME);
-
- if (mCreateEntry) {
- if (subject == null) {
- CMS.debug( "CRSEnrollment::postRequest() - subject is null!" );
- return null;
- }
- createEntry(subject.toString());
- }
-
- // use profile framework to handle SCEP
- if (mProfileId != null) {
- PKCS10 pkcs10data = req.getP10();
- String pkcs10blob = CMS.BtoA(pkcs10data.toByteArray());
-
- // XXX authentication handling
- CMS.debug("Found profile=" + mProfileId);
- IProfile profile = mProfileSubsystem.getProfile(mProfileId);
- if (profile == null) {
- CMS.debug("profile " + mProfileId + " not found");
- return null;
- }
- IProfileContext ctx = profile.createContext();
-
- IProfileAuthenticator authenticator = null;
- try {
- CMS.debug("Retrieving authenticator");
- authenticator = profile.getAuthenticator();
+ ILogger signedAuditLogger = CMS.getSignedAuditLogger();
+ if (signedAuditLogger != null) {
+ signedAuditLogger.log(ILogger.EV_SIGNED_AUDIT,
+ null, ILogger.S_SIGNED_AUDIT,
+ ILogger.LL_SECURITY, auditMessage);
+ }
+
+ return null;
+ } else {
+ IRequest ireq = postRequest(httpReq, req, crsResp);
+
+ CMS.debug("created response");
+ return makeResponseFromRequest(req, crsResp, ireq);
+ }
+ } catch (CryptoContext.CryptoContextException e) {
+ CMS.debug("failed to decrypt the request " + e);
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ENROLL_FAIL_NO_DECRYPT_PKCS10",
+ e.getMessage()));
+ crsResp.setFailInfo(CRSPKIMessage.mFailInfo_badMessageCheck);
+ crsResp.setPKIStatus(CRSPKIMessage.mStatus_FAILURE);
+ } catch (EBaseException e) {
+ CMS.debug("operation failure - " + e);
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERNOLL_FAIL_NO_NEW_REQUEST_POSTED",
+ e.getMessage()));
+ crsResp.setFailInfo(CRSPKIMessage.mFailInfo_internalCAError);
+ crsResp.setPKIStatus(CRSPKIMessage.mStatus_FAILURE);
+ }
+ return null;
+ }
+
+ // //// post the request
+
+ /*
+ * needed:
+ *
+ * token (authtoken) certInfo fingerprints x req.transactionID crsResp
+ */
+
+ private IRequest postRequest(HttpServletRequest httpReq, CRSPKIMessage req, CRSPKIMessage crsResp)
+ throws EBaseException {
+ X500Name subject = (X500Name) req.get(SUBJECTNAME);
+
+ if (mCreateEntry) {
+ if (subject == null) {
+ CMS.debug("CRSEnrollment::postRequest() - subject is null!");
+ return null;
+ }
+ createEntry(subject.toString());
+ }
+
+ // use profile framework to handle SCEP
+ if (mProfileId != null) {
+ PKCS10 pkcs10data = req.getP10();
+ String pkcs10blob = CMS.BtoA(pkcs10data.toByteArray());
+
+ // XXX authentication handling
+ CMS.debug("Found profile=" + mProfileId);
+ IProfile profile = mProfileSubsystem.getProfile(mProfileId);
+ if (profile == null) {
+ CMS.debug("profile " + mProfileId + " not found");
+ return null;
+ }
+ IProfileContext ctx = profile.createContext();
+
+ IProfileAuthenticator authenticator = null;
+ try {
+ CMS.debug("Retrieving authenticator");
+ authenticator = profile.getAuthenticator();
+ if (authenticator == null) {
+ CMS.debug("No authenticator Found");
+ } else {
+ CMS.debug("Got authenticator=" + authenticator.getClass().getName());
+ }
+ } catch (EProfileException e) {
+ // authenticator not installed correctly
+ }
+
+ IAuthToken authToken = null;
+
+ // for ssl authentication; pass in servlet for retrieving
+ // ssl client certificates
+ SessionContext context = SessionContext.getContext();
+
+ // insert profile context so that input parameter can be retrieved
+ context.put("profileContext", ctx);
+ context.put("sslClientCertProvider",
+ new SSLClientCertProvider(httpReq));
+
+ String p10Password = getPasswordFromP10(pkcs10data);
+ AuthCredentials credentials = new AuthCredentials();
+ credentials.set("UID", httpReq.getRemoteAddr());
+ credentials.set("PWD", p10Password);
+
if (authenticator == null) {
- CMS.debug("No authenticator Found");
+ // XXX - to help caRouterCert to work, we need to
+ // add authentication to caRouterCert
+ authToken = new AuthToken(null);
} else {
- CMS.debug("Got authenticator=" + authenticator.getClass().getName());
+ authToken = authenticate(credentials, authenticator, httpReq);
}
- } catch (EProfileException e) {
- // authenticator not installed correctly
- }
-
- IAuthToken authToken = null;
-
- // for ssl authentication; pass in servlet for retrieving
- // ssl client certificates
- SessionContext context = SessionContext.getContext();
-
-
- // insert profile context so that input parameter can be retrieved
- context.put("profileContext", ctx);
- context.put("sslClientCertProvider",
- new SSLClientCertProvider(httpReq));
-
- String p10Password = getPasswordFromP10(pkcs10data);
- AuthCredentials credentials = new AuthCredentials();
- credentials.set("UID", httpReq.getRemoteAddr());
- credentials.set("PWD", p10Password);
-
- if (authenticator == null) {
- // XXX - to help caRouterCert to work, we need to
- // add authentication to caRouterCert
- authToken = new AuthToken(null);
- } else {
- authToken = authenticate(credentials, authenticator, httpReq);
- }
-
- IRequest reqs[] = null;
- CMS.debug("CRSEnrollment: Creating profile requests");
- ctx.set(IEnrollProfile.CTX_CERT_REQUEST_TYPE, "pkcs10");
- ctx.set(IEnrollProfile.CTX_CERT_REQUEST, pkcs10blob);
- Locale locale = Locale.getDefault();
- reqs = profile.createRequests(ctx, locale);
- if (reqs == null) {
- CMS.debug("CRSEnrollment: No request has been created");
- return null;
- } else {
- CMS.debug("CRSEnrollment: Request (" + reqs.length + ") have been created");
- }
- // set transaction id
- reqs[0].setSourceId(req.getTransactionID());
- reqs[0].setExtData("profile", "true");
- reqs[0].setExtData("profileId", mProfileId);
- reqs[0].setExtData(IEnrollProfile.CTX_CERT_REQUEST_TYPE, IEnrollProfile.REQ_TYPE_PKCS10);
- reqs[0].setExtData(IEnrollProfile.CTX_CERT_REQUEST, pkcs10blob);
- reqs[0].setExtData("requestor_name", "");
- reqs[0].setExtData("requestor_email", "");
- reqs[0].setExtData("requestor_phone", "");
- reqs[0].setExtData("profileRemoteHost", httpReq.getRemoteHost());
- reqs[0].setExtData("profileRemoteAddr", httpReq.getRemoteAddr());
- reqs[0].setExtData("profileApprovedBy", profile.getApprovedBy());
-
- CMS.debug("CRSEnrollment: Populating inputs");
- profile.populateInput(ctx, reqs[0]);
- CMS.debug("CRSEnrollment: Populating requests");
- profile.populate(reqs[0]);
-
- CMS.debug("CRSEnrollment: Submitting request");
- profile.submit(authToken, reqs[0]);
- CMS.debug("CRSEnrollment: Done submitting request");
- profile.getRequestQueue().markAsServiced(reqs[0]);
- CMS.debug("CRSEnrollment: Request marked as serviced");
-
- return reqs[0];
-
- }
-
- IRequestQueue rq = ca.getRequestQueue();
- IRequest pkiReq = rq.newRequest(IRequest.ENROLLMENT_REQUEST);
-
- AuthToken token = (AuthToken) req.get(AUTH_TOKEN);
- if (token != null) {
- pkiReq.setExtData(IRequest.AUTH_TOKEN,token);
- }
-
- pkiReq.setExtData(IRequest.HTTP_PARAMS, IRequest.CERT_TYPE, IRequest.CEP_CERT);
- X509CertInfo certInfo = (X509CertInfo) req.get(CERTINFO);
- pkiReq.setExtData(IRequest.CERT_INFO, new X509CertInfo[] { certInfo } );
- pkiReq.setExtData("cepsubstore", mSubstoreName);
-
- try {
- String chpwd = (String)req.get(ChallengePassword.NAME);
- if (chpwd != null) {
- pkiReq.setExtData("challengePhrase",
- chpwd );
- }
- } catch (Exception pwex) {
- }
-
- Hashtable<?, ?> fingerprints = (Hashtable<?, ?>)req.get(IRequest.FINGERPRINTS);
- if (fingerprints.size() > 0) {
- Hashtable<String, String> encodedPrints = new Hashtable<String, String>(fingerprints.size());
- Enumeration<?> e = fingerprints.keys();
- while (e.hasMoreElements()) {
- String key = (String)e.nextElement();
- byte[] value = (byte[])fingerprints.get(key);
- encodedPrints.put(key, CMS.BtoA(value));
- }
- pkiReq.setExtData(IRequest.FINGERPRINTS, encodedPrints);
- }
-
- pkiReq.setSourceId(req.getTransactionID());
-
- rq.processRequest(pkiReq);
-
- crsResp.setPKIStatus(CRSPKIMessage.mStatus_SUCCESS);
-
- mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
+
+ IRequest reqs[] = null;
+ CMS.debug("CRSEnrollment: Creating profile requests");
+ ctx.set(IEnrollProfile.CTX_CERT_REQUEST_TYPE, "pkcs10");
+ ctx.set(IEnrollProfile.CTX_CERT_REQUEST, pkcs10blob);
+ Locale locale = Locale.getDefault();
+ reqs = profile.createRequests(ctx, locale);
+ if (reqs == null) {
+ CMS.debug("CRSEnrollment: No request has been created");
+ return null;
+ } else {
+ CMS.debug("CRSEnrollment: Request (" + reqs.length + ") have been created");
+ }
+ // set transaction id
+ reqs[0].setSourceId(req.getTransactionID());
+ reqs[0].setExtData("profile", "true");
+ reqs[0].setExtData("profileId", mProfileId);
+ reqs[0].setExtData(IEnrollProfile.CTX_CERT_REQUEST_TYPE, IEnrollProfile.REQ_TYPE_PKCS10);
+ reqs[0].setExtData(IEnrollProfile.CTX_CERT_REQUEST, pkcs10blob);
+ reqs[0].setExtData("requestor_name", "");
+ reqs[0].setExtData("requestor_email", "");
+ reqs[0].setExtData("requestor_phone", "");
+ reqs[0].setExtData("profileRemoteHost", httpReq.getRemoteHost());
+ reqs[0].setExtData("profileRemoteAddr", httpReq.getRemoteAddr());
+ reqs[0].setExtData("profileApprovedBy", profile.getApprovedBy());
+
+ CMS.debug("CRSEnrollment: Populating inputs");
+ profile.populateInput(ctx, reqs[0]);
+ CMS.debug("CRSEnrollment: Populating requests");
+ profile.populate(reqs[0]);
+
+ CMS.debug("CRSEnrollment: Submitting request");
+ profile.submit(authToken, reqs[0]);
+ CMS.debug("CRSEnrollment: Done submitting request");
+ profile.getRequestQueue().markAsServiced(reqs[0]);
+ CMS.debug("CRSEnrollment: Request marked as serviced");
+
+ return reqs[0];
+
+ }
+
+ IRequestQueue rq = ca.getRequestQueue();
+ IRequest pkiReq = rq.newRequest(IRequest.ENROLLMENT_REQUEST);
+
+ AuthToken token = (AuthToken) req.get(AUTH_TOKEN);
+ if (token != null) {
+ pkiReq.setExtData(IRequest.AUTH_TOKEN, token);
+ }
+
+ pkiReq.setExtData(IRequest.HTTP_PARAMS, IRequest.CERT_TYPE, IRequest.CEP_CERT);
+ X509CertInfo certInfo = (X509CertInfo) req.get(CERTINFO);
+ pkiReq.setExtData(IRequest.CERT_INFO, new X509CertInfo[] { certInfo });
+ pkiReq.setExtData("cepsubstore", mSubstoreName);
+
+ try {
+ String chpwd = (String) req.get(ChallengePassword.NAME);
+ if (chpwd != null) {
+ pkiReq.setExtData("challengePhrase",
+ chpwd);
+ }
+ } catch (Exception pwex) {
+ }
+
+ Hashtable<?, ?> fingerprints = (Hashtable<?, ?>) req.get(IRequest.FINGERPRINTS);
+ if (fingerprints.size() > 0) {
+ Hashtable<String, String> encodedPrints = new Hashtable<String, String>(fingerprints.size());
+ Enumeration<?> e = fingerprints.keys();
+ while (e.hasMoreElements()) {
+ String key = (String) e.nextElement();
+ byte[] value = (byte[]) fingerprints.get(key);
+ encodedPrints.put(key, CMS.BtoA(value));
+ }
+ pkiReq.setExtData(IRequest.FINGERPRINTS, encodedPrints);
+ }
+
+ pkiReq.setSourceId(req.getTransactionID());
+
+ rq.processRequest(pkiReq);
+
+ crsResp.setPKIStatus(CRSPKIMessage.mStatus_SUCCESS);
+
+ mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
AuditFormat.LEVEL,
AuditFormat.ENROLLMENTFORMAT,
new Object[] {
- pkiReq.getRequestId(),
- AuditFormat.FROMROUTER,
- mAuthManagerName == null ? AuditFormat.NOAUTH : mAuthManagerName,
- "pending",
- subject ,
- ""}
+ pkiReq.getRequestId(),
+ AuditFormat.FROMROUTER,
+ mAuthManagerName == null ? AuditFormat.NOAUTH : mAuthManagerName,
+ "pending",
+ subject,
+ "" }
);
-
- return pkiReq;
- }
-
+ return pkiReq;
+ }
- public Hashtable<String, byte[]> makeFingerPrints(CRSPKIMessage req) {
+ public Hashtable<String, byte[]> makeFingerPrints(CRSPKIMessage req) {
Hashtable<String, byte[]> fingerprints = new Hashtable<String, byte[]>();
MessageDigest md;
- String[] hashes = new String[] {"MD2", "MD5", "SHA1", "SHA256", "SHA512"};
- PKCS10 p10 = (PKCS10)req.getP10();
+ String[] hashes = new String[] { "MD2", "MD5", "SHA1", "SHA256", "SHA512" };
+ PKCS10 p10 = (PKCS10) req.getP10();
- for (int i=0;i<hashes.length;i++) {
- try {
- md = MessageDigest.getInstance(hashes[i]);
- md.update(p10.getCertRequestInfo());
- fingerprints.put(hashes[i],md.digest());
- }
- catch (NoSuchAlgorithmException nsa) {}
+ for (int i = 0; i < hashes.length; i++) {
+ try {
+ md = MessageDigest.getInstance(hashes[i]);
+ md.update(p10.getCertRequestInfo());
+ fingerprints.put(hashes[i], md.digest());
+ } catch (NoSuchAlgorithmException nsa) {
+ }
}
- if (fingerprints != null) {
- req.put(IRequest.FINGERPRINTS,fingerprints);
- }
- return fingerprints;
- }
-
-
- // Take a look to see if the request was successful, and fill
- // in the response message
+ if (fingerprints != null) {
+ req.put(IRequest.FINGERPRINTS, fingerprints);
+ }
+ return fingerprints;
+ }
+ // Take a look to see if the request was successful, and fill
+ // in the response message
- private X509CertImpl makeResponseFromRequest(CRSPKIMessage crsReq, CRSPKIMessage crsResp,
- IRequest pkiReq)
- {
+ private X509CertImpl makeResponseFromRequest(CRSPKIMessage crsReq, CRSPKIMessage crsResp,
+ IRequest pkiReq) {
- X509CertImpl issuedCert=null;
+ X509CertImpl issuedCert = null;
RequestStatus status = pkiReq.getRequestStatus();
String profileId = pkiReq.getExtDataInString("profileId");
if (profileId != null) {
- CMS.debug("CRSEnrollment: Found profile request");
- X509CertImpl cert =
- pkiReq.getExtDataInCert(IEnrollProfile.REQUEST_ISSUED_CERT);
- if (cert == null) {
- CMS.debug("CRSEnrollment: No certificate has been found");
- } else {
- CMS.debug("CRSEnrollment: Found certificate");
- }
- crsResp.setPKIStatus(CRSPKIMessage.mStatus_SUCCESS);
- return cert;
+ CMS.debug("CRSEnrollment: Found profile request");
+ X509CertImpl cert =
+ pkiReq.getExtDataInCert(IEnrollProfile.REQUEST_ISSUED_CERT);
+ if (cert == null) {
+ CMS.debug("CRSEnrollment: No certificate has been found");
+ } else {
+ CMS.debug("CRSEnrollment: Found certificate");
+ }
+ crsResp.setPKIStatus(CRSPKIMessage.mStatus_SUCCESS);
+ return cert;
}
-
- if ( status.equals(RequestStatus.COMPLETE)) {
+ if (status.equals(RequestStatus.COMPLETE)) {
Integer success = pkiReq.getExtDataInInteger(IRequest.RESULT);
-
if (success.equals(IRequest.RES_SUCCESS)) {
// The cert was issued, lets send it back to the router
X509CertImpl[] issuedCertBuf =
- pkiReq.getExtDataInCertArray(IRequest.ISSUED_CERTS);
+ pkiReq.getExtDataInCertArray(IRequest.ISSUED_CERTS);
if (issuedCertBuf == null || issuedCertBuf.length == 0) {
- // writeError("Internal Error: Bad operation",httpReq,httpResp);
- CMS.debug( "CRSEnrollment::makeResponseFromRequest() - " +
- "Bad operation" );
+ // writeError("Internal Error: Bad operation",httpReq,httpResp);
+ CMS.debug("CRSEnrollment::makeResponseFromRequest() - " +
+ "Bad operation");
return null;
}
issuedCert = issuedCertBuf[0];
crsResp.setPKIStatus(CRSPKIMessage.mStatus_SUCCESS);
-
- }
- else { // status is not 'success' - there must've been a problem
-
+
+ } else { // status is not 'success' - there must've been a problem
+
crsResp.setPKIStatus(CRSPKIMessage.mStatus_FAILURE);
crsResp.setFailInfo(CRSPKIMessage.mFailInfo_badAlg);
}
- }
- else if (status.equals(RequestStatus.REJECTED_STRING) ||
+ } else if (status.equals(RequestStatus.REJECTED_STRING) ||
status.equals(RequestStatus.CANCELED_STRING)) {
- crsResp.setPKIStatus(CRSPKIMessage.mStatus_FAILURE);
- crsResp.setFailInfo(CRSPKIMessage.mFailInfo_badRequest);
- }
- else { // not complete
+ crsResp.setPKIStatus(CRSPKIMessage.mStatus_FAILURE);
+ crsResp.setFailInfo(CRSPKIMessage.mFailInfo_badRequest);
+ } else { // not complete
crsResp.setPKIStatus(CRSPKIMessage.mStatus_PENDING);
}
return issuedCert;
}
+ protected String hashPassword(String pwd) {
+ String salt = "lala123";
+ byte[] pwdDigest = mSHADigest.digest((salt + pwd).getBytes());
+ String b64E = com.netscape.osutil.OSUtil.BtoA(pwdDigest);
+ return "{SHA}" + b64E;
+ }
+ /**
+ * Make the CRSPKIMESSAGE response
+ */
+ private void processCertRep(CryptoContext cx,
+ X509CertImpl issuedCert,
+ CRSPKIMessage crsResp,
+ CRSPKIMessage crsReq)
+ throws CRSFailureException {
+ byte[] msgdigest = null;
+ byte[] encryptedDesKey = null;
+ try {
+ if (issuedCert != null) {
+ SymmetricKey sk;
+ SymmetricKey skinternal;
- protected String hashPassword(String pwd) {
- String salt = "lala123";
- byte[] pwdDigest = mSHADigest.digest((salt+pwd).getBytes());
- String b64E = com.netscape.osutil.OSUtil.BtoA(pwdDigest);
- return "{SHA}"+b64E;
- }
+ KeyGenAlgorithm kga = KeyGenAlgorithm.DES;
+ EncryptionAlgorithm ea = EncryptionAlgorithm.DES_CBC;
+ if (mEncryptionAlgorithm != null && mEncryptionAlgorithm.equals("DES3")) {
+ kga = KeyGenAlgorithm.DES3;
+ ea = EncryptionAlgorithm.DES3_CBC;
+ }
+ // 1. Make the Degenerated PKCS7 with the recipient's
+ // certificate in it
+ byte toBeEncrypted[] =
+ crsResp.makeSignedRep(1, // version
+ issuedCert.getEncoded()
+ );
+ // 2. Encrypt the above byte array with a new random DES key
- /**
- * Make the CRSPKIMESSAGE response
- */
+ sk = cx.getDESKeyGenerator().generate();
+ skinternal = cx.getInternalToken().getKeyGenerator(kga).clone(sk);
- private void processCertRep(CryptoContext cx,
- X509CertImpl issuedCert,
- CRSPKIMessage crsResp,
- CRSPKIMessage crsReq)
- throws CRSFailureException {
- byte[] msgdigest = null;
- byte[] encryptedDesKey = null;
-
- try {
- if (issuedCert != null) {
-
- SymmetricKey sk;
- SymmetricKey skinternal;
-
- KeyGenAlgorithm kga = KeyGenAlgorithm.DES;
- EncryptionAlgorithm ea = EncryptionAlgorithm.DES_CBC;
- if (mEncryptionAlgorithm != null && mEncryptionAlgorithm.equals("DES3")) {
- kga = KeyGenAlgorithm.DES3;
- ea = EncryptionAlgorithm.DES3_CBC;
- }
-
- // 1. Make the Degenerated PKCS7 with the recipient's certificate in it
-
- byte toBeEncrypted[] =
- crsResp.makeSignedRep(1, // version
- issuedCert.getEncoded()
- );
-
- // 2. Encrypt the above byte array with a new random DES key
-
- sk = cx.getDESKeyGenerator().generate();
-
- skinternal = cx.getInternalToken().getKeyGenerator(kga).clone(sk);
-
- byte[] padded = Cipher.pad(toBeEncrypted, ea.getBlockSize());
-
-
- // This should be changed to generate proper DES IV.
-
- Cipher cipher = cx.getInternalToken().getCipherContext(ea);
- IVParameterSpec desIV =
- new IVParameterSpec(new byte[]{
- (byte)0xff, (byte)0x00,
- (byte)0xff, (byte)0x00,
- (byte)0xff, (byte)0x00,
- (byte)0xff, (byte)0x00 } );
-
- cipher.initEncrypt(sk,desIV);
- byte[] encryptedData = cipher.doFinal(padded);
-
- crsResp.makeEncryptedContentInfo(desIV.getIV(),encryptedData, mEncryptionAlgorithm);
-
- // 3. Extract the recipient's public key
-
- PublicKey rcpPK = crsReq.getSignerPublicKey();
-
-
- // 4. Encrypt the DES key with the public key
-
- // we have to move the key onto the interal token.
- //skinternal = cx.getInternalKeyStorageToken().cloneKey(sk);
- skinternal = cx.getInternalToken().cloneKey(sk);
-
- KeyWrapper kw = cx.getInternalKeyWrapper();
- kw.initWrap(rcpPK, null);
- encryptedDesKey = kw.wrap(skinternal);
-
- crsResp.setRcpIssuerAndSerialNumber(crsReq.getSgnIssuerAndSerialNumber());
- crsResp.makeRecipientInfo(0, encryptedDesKey );
-
- }
-
-
- byte[] ed = crsResp.makeEnvelopedData(0);
-
- // 7. Make Digest of SignedData Content
- MessageDigest md = MessageDigest.getInstance(mHashAlgorithm);
- msgdigest = md.digest(ed);
-
- crsResp.setMsgDigest(msgdigest);
-
- }
-
- catch (Exception e) {
- throw new CRSFailureException("Failed to create inner response to CEP message: "+e.getMessage());
- }
-
-
- // 5. Make a RecipientInfo
-
- // The issuer name & serial number here, should be that of
- // the EE's self-signed Certificate
- // [I can get it from the req blob, but later, I should
- // store the recipient's self-signed certificate with the request
- // so I can get at it later. I need to do this to support
- // 'PENDING']
-
-
- try {
-
- // 8. Make Authenticated Attributes
- // we can just pull the transaction ID out of the request.
- // Later, we will have to put it out of the Request queue,
- // so we can support PENDING
- crsResp.setTransactionID(crsReq.getTransactionID());
- // recipientNonce and SenderNonce have already been set
-
- crsResp.makeAuthenticatedAttributes();
- // crsResp.makeAuthenticatedAttributes_old();
-
-
-
- // now package up the rest of the SignerInfo
- {
- byte[] signingcertbytes = cx.getSigningCert().getEncoded();
-
-
- Certificate.Template sgncert_t = new Certificate.Template();
- Certificate sgncert =
- (Certificate) sgncert_t.decode(new ByteArrayInputStream(signingcertbytes));
-
- IssuerAndSerialNumber sgniasn =
- new IssuerAndSerialNumber(sgncert.getInfo().getIssuer(),
+ byte[] padded = Cipher.pad(toBeEncrypted, ea.getBlockSize());
+
+ // This should be changed to generate proper DES IV.
+
+ Cipher cipher = cx.getInternalToken().getCipherContext(ea);
+ IVParameterSpec desIV =
+ new IVParameterSpec(new byte[] {
+ (byte) 0xff, (byte) 0x00,
+ (byte) 0xff, (byte) 0x00,
+ (byte) 0xff, (byte) 0x00,
+ (byte) 0xff, (byte) 0x00 });
+
+ cipher.initEncrypt(sk, desIV);
+ byte[] encryptedData = cipher.doFinal(padded);
+
+ crsResp.makeEncryptedContentInfo(desIV.getIV(), encryptedData, mEncryptionAlgorithm);
+
+ // 3. Extract the recipient's public key
+
+ PublicKey rcpPK = crsReq.getSignerPublicKey();
+
+ // 4. Encrypt the DES key with the public key
+
+ // we have to move the key onto the interal token.
+ // skinternal = cx.getInternalKeyStorageToken().cloneKey(sk);
+ skinternal = cx.getInternalToken().cloneKey(sk);
+
+ KeyWrapper kw = cx.getInternalKeyWrapper();
+ kw.initWrap(rcpPK, null);
+ encryptedDesKey = kw.wrap(skinternal);
+
+ crsResp.setRcpIssuerAndSerialNumber(crsReq.getSgnIssuerAndSerialNumber());
+ crsResp.makeRecipientInfo(0, encryptedDesKey);
+
+ }
+
+ byte[] ed = crsResp.makeEnvelopedData(0);
+
+ // 7. Make Digest of SignedData Content
+ MessageDigest md = MessageDigest.getInstance(mHashAlgorithm);
+ msgdigest = md.digest(ed);
+
+ crsResp.setMsgDigest(msgdigest);
+
+ }
+
+ catch (Exception e) {
+ throw new CRSFailureException("Failed to create inner response to CEP message: " + e.getMessage());
+ }
+
+ // 5. Make a RecipientInfo
+
+ // The issuer name & serial number here, should be that of
+ // the EE's self-signed Certificate
+ // [I can get it from the req blob, but later, I should
+ // store the recipient's self-signed certificate with the request
+ // so I can get at it later. I need to do this to support
+ // 'PENDING']
+
+ try {
+
+ // 8. Make Authenticated Attributes
+ // we can just pull the transaction ID out of the request.
+ // Later, we will have to put it out of the Request queue,
+ // so we can support PENDING
+ crsResp.setTransactionID(crsReq.getTransactionID());
+ // recipientNonce and SenderNonce have already been set
+
+ crsResp.makeAuthenticatedAttributes();
+ // crsResp.makeAuthenticatedAttributes_old();
+
+ // now package up the rest of the SignerInfo
+ {
+ byte[] signingcertbytes = cx.getSigningCert().getEncoded();
+
+ Certificate.Template sgncert_t = new Certificate.Template();
+ Certificate sgncert =
+ (Certificate) sgncert_t.decode(new ByteArrayInputStream(signingcertbytes));
+
+ IssuerAndSerialNumber sgniasn =
+ new IssuerAndSerialNumber(sgncert.getInfo().getIssuer(),
sgncert.getInfo().getSerialNumber());
-
- crsResp.setSgnIssuerAndSerialNumber(sgniasn);
-
- // 10. Make SignerInfo
- crsResp.makeSignerInfo(1, cx.getPrivateKey(), mHashAlgorithm);
-
- // 11. Make SignedData
- crsResp.makeSignedData(1, signingcertbytes, mHashAlgorithm);
-
- crsResp.debug();
- }
- }
- catch (Exception e) {
- throw new CRSFailureException("Failed to create outer response to CEP request: "+e.getMessage());
- }
-
-
- // if debugging, dump out the response into a file
-
- }
-
-
-
- class CryptoContext {
- private CryptoManager cm;
- private CryptoToken internalToken;
- private CryptoToken keyStorageToken;
- private CryptoToken internalKeyStorageToken;
- private KeyGenerator DESkg;
- private Enumeration<?> externalTokens = null;
- private org.mozilla.jss.crypto.X509Certificate signingCert;
- private org.mozilla.jss.crypto.PrivateKey signingCertPrivKey;
- private int signingCertKeySize = 0;
-
-
- class CryptoContextException extends Exception {
- /**
+
+ crsResp.setSgnIssuerAndSerialNumber(sgniasn);
+
+ // 10. Make SignerInfo
+ crsResp.makeSignerInfo(1, cx.getPrivateKey(), mHashAlgorithm);
+
+ // 11. Make SignedData
+ crsResp.makeSignedData(1, signingcertbytes, mHashAlgorithm);
+
+ crsResp.debug();
+ }
+ } catch (Exception e) {
+ throw new CRSFailureException("Failed to create outer response to CEP request: " + e.getMessage());
+ }
+
+ // if debugging, dump out the response into a file
+
+ }
+
+ class CryptoContext {
+ private CryptoManager cm;
+ private CryptoToken internalToken;
+ private CryptoToken keyStorageToken;
+ private CryptoToken internalKeyStorageToken;
+ private KeyGenerator DESkg;
+ private Enumeration<?> externalTokens = null;
+ private org.mozilla.jss.crypto.X509Certificate signingCert;
+ private org.mozilla.jss.crypto.PrivateKey signingCertPrivKey;
+ private int signingCertKeySize = 0;
+
+ class CryptoContextException extends Exception {
+ /**
*
*/
- private static final long serialVersionUID = -1124116326126256475L;
- public CryptoContextException() { super(); }
- public CryptoContextException(String s) { super(s); }
- }
+ private static final long serialVersionUID = -1124116326126256475L;
- public CryptoContext()
- throws CryptoContextException
- {
- try {
- KeyGenAlgorithm kga = KeyGenAlgorithm.DES;
- if (mEncryptionAlgorithm != null && mEncryptionAlgorithm.equals("DES3")) {
- kga = KeyGenAlgorithm.DES3;
- }
- cm = CryptoManager.getInstance();
- internalToken = cm.getInternalCryptoToken();
- DESkg = internalToken.getKeyGenerator(kga);
- if (mTokenName.equalsIgnoreCase(Constants.PR_INTERNAL_TOKEN) ||
- mTokenName.equalsIgnoreCase("Internal Key Storage Token") ||
- mTokenName.length() == 0) {
- keyStorageToken = cm.getInternalKeyStorageToken();
- internalKeyStorageToken = keyStorageToken;
- CMS.debug("CRSEnrollment: CryptoContext: internal token name: '"+mTokenName+"'");
- } else {
- keyStorageToken = cm.getTokenByName(mTokenName);
- internalKeyStorageToken = null;
- }
- if (!mUseCA && internalKeyStorageToken == null) {
- PasswordCallback cb = CMS.getPasswordCallback();
- keyStorageToken.login(cb); // ONE_TIME by default.
- }
- signingCert = cm.findCertByNickname(mNickname);
- signingCertPrivKey = cm.findPrivKeyByCert(signingCert);
- byte[] encPubKeyInfo = signingCert.getPublicKey().getEncoded();
- SEQUENCE.Template outer = SEQUENCE.getTemplate();
- outer.addElement( ANY.getTemplate() ); // algid
- outer.addElement( BIT_STRING.getTemplate() );
- SEQUENCE outerSeq = (SEQUENCE) ASN1Util.decode(outer, encPubKeyInfo);
- BIT_STRING bs = (BIT_STRING) outerSeq.elementAt(1);
- byte[] encPubKey = bs.getBits();
- if( bs.getPadCount() != 0) {
- throw new CryptoContextException("Internal error: Invalid Public key. Not an integral number of bytes.");
- }
- SEQUENCE.Template inner = new SEQUENCE.Template();
- inner.addElement( INTEGER.getTemplate());
- inner.addElement( INTEGER.getTemplate());
- SEQUENCE pubKeySeq = (SEQUENCE) ASN1Util.decode(inner, encPubKey);
- INTEGER modulus = (INTEGER) pubKeySeq.elementAt(0);
- signingCertKeySize = modulus.bitLength();
-
- try {
- FileOutputStream fos = new FileOutputStream("pubkey.der");
- fos.write(signingCert.getPublicKey().getEncoded());
- fos.close();
- } catch (Exception e) {}
-
- }
- catch (InvalidBERException e) {
- throw new CryptoContextException("Internal Error: Bad internal Certificate Representation. Not a valid RSA-signed certificate");
- }
- catch (CryptoManager.NotInitializedException e) {
- throw new CryptoContextException("Crypto Manager not initialized");
- }
- catch (NoSuchAlgorithmException e) {
- throw new CryptoContextException("Cannot create DES key generator");
- }
- catch (ObjectNotFoundException e) {
- throw new CryptoContextException("Certificate not found: "+ca.getNickname());
- }
- catch (TokenException e) {
- throw new CryptoContextException("Problem with Crypto Token: "+e.getMessage());
- }
- catch (NoSuchTokenException e) {
- throw new CryptoContextException("Crypto Token not found: "+e.getMessage());
- }
- catch (IncorrectPasswordException e) {
- throw new CryptoContextException("Incorrect Password.");
- }
- }
-
-
- public KeyGenerator getDESKeyGenerator() {
- return DESkg;
- }
+ public CryptoContextException() {
+ super();
+ }
- public CryptoToken getInternalToken() {
- return internalToken;
- }
+ public CryptoContextException(String s) {
+ super(s);
+ }
+ }
- public void setExternalTokens( Enumeration<?> tokens ) {
- externalTokens = tokens;
- }
+ public CryptoContext()
+ throws CryptoContextException {
+ try {
+ KeyGenAlgorithm kga = KeyGenAlgorithm.DES;
+ if (mEncryptionAlgorithm != null && mEncryptionAlgorithm.equals("DES3")) {
+ kga = KeyGenAlgorithm.DES3;
+ }
+ cm = CryptoManager.getInstance();
+ internalToken = cm.getInternalCryptoToken();
+ DESkg = internalToken.getKeyGenerator(kga);
+ if (mTokenName.equalsIgnoreCase(Constants.PR_INTERNAL_TOKEN) ||
+ mTokenName.equalsIgnoreCase("Internal Key Storage Token") ||
+ mTokenName.length() == 0) {
+ keyStorageToken = cm.getInternalKeyStorageToken();
+ internalKeyStorageToken = keyStorageToken;
+ CMS.debug("CRSEnrollment: CryptoContext: internal token name: '" + mTokenName + "'");
+ } else {
+ keyStorageToken = cm.getTokenByName(mTokenName);
+ internalKeyStorageToken = null;
+ }
+ if (!mUseCA && internalKeyStorageToken == null) {
+ PasswordCallback cb = CMS.getPasswordCallback();
+ keyStorageToken.login(cb); // ONE_TIME by default.
+ }
+ signingCert = cm.findCertByNickname(mNickname);
+ signingCertPrivKey = cm.findPrivKeyByCert(signingCert);
+ byte[] encPubKeyInfo = signingCert.getPublicKey().getEncoded();
+ SEQUENCE.Template outer = SEQUENCE.getTemplate();
+ outer.addElement(ANY.getTemplate()); // algid
+ outer.addElement(BIT_STRING.getTemplate());
+ SEQUENCE outerSeq = (SEQUENCE) ASN1Util.decode(outer, encPubKeyInfo);
+ BIT_STRING bs = (BIT_STRING) outerSeq.elementAt(1);
+ byte[] encPubKey = bs.getBits();
+ if (bs.getPadCount() != 0) {
+ throw new CryptoContextException("Internal error: Invalid Public key. Not an integral number of bytes.");
+ }
+ SEQUENCE.Template inner = new SEQUENCE.Template();
+ inner.addElement(INTEGER.getTemplate());
+ inner.addElement(INTEGER.getTemplate());
+ SEQUENCE pubKeySeq = (SEQUENCE) ASN1Util.decode(inner, encPubKey);
+ INTEGER modulus = (INTEGER) pubKeySeq.elementAt(0);
+ signingCertKeySize = modulus.bitLength();
- public Enumeration<?> getExternalTokens() {
- return externalTokens;
- }
+ try {
+ FileOutputStream fos = new FileOutputStream("pubkey.der");
+ fos.write(signingCert.getPublicKey().getEncoded());
+ fos.close();
+ } catch (Exception e) {
+ }
- public CryptoToken getInternalKeyStorageToken() {
- return internalKeyStorageToken;
- }
+ } catch (InvalidBERException e) {
+ throw new CryptoContextException("Internal Error: Bad internal Certificate Representation. Not a valid RSA-signed certificate");
+ } catch (CryptoManager.NotInitializedException e) {
+ throw new CryptoContextException("Crypto Manager not initialized");
+ } catch (NoSuchAlgorithmException e) {
+ throw new CryptoContextException("Cannot create DES key generator");
+ } catch (ObjectNotFoundException e) {
+ throw new CryptoContextException("Certificate not found: " + ca.getNickname());
+ } catch (TokenException e) {
+ throw new CryptoContextException("Problem with Crypto Token: " + e.getMessage());
+ } catch (NoSuchTokenException e) {
+ throw new CryptoContextException("Crypto Token not found: " + e.getMessage());
+ } catch (IncorrectPasswordException e) {
+ throw new CryptoContextException("Incorrect Password.");
+ }
+ }
- public CryptoToken getKeyStorageToken() {
- return keyStorageToken;
- }
+ public KeyGenerator getDESKeyGenerator() {
+ return DESkg;
+ }
- public CryptoManager getCryptoManager() {
- return cm;
- }
+ public CryptoToken getInternalToken() {
+ return internalToken;
+ }
- public KeyWrapper getKeyWrapper()
- throws CryptoContextException {
- try {
- return signingCertPrivKey.getOwningToken().getKeyWrapper(KeyWrapAlgorithm.RSA);
+ public void setExternalTokens(Enumeration<?> tokens) {
+ externalTokens = tokens;
}
- catch (TokenException e) {
- throw new CryptoContextException("Problem with Crypto Token: "+e.getMessage());
+
+ public Enumeration<?> getExternalTokens() {
+ return externalTokens;
}
- catch (NoSuchAlgorithmException e) {
- throw new CryptoContextException(e.getMessage());
+
+ public CryptoToken getInternalKeyStorageToken() {
+ return internalKeyStorageToken;
}
- }
- public KeyWrapper getInternalKeyWrapper()
- throws CryptoContextException {
- try {
- return getInternalToken().getKeyWrapper(KeyWrapAlgorithm.RSA);
+ public CryptoToken getKeyStorageToken() {
+ return keyStorageToken;
}
- catch (TokenException e) {
- throw new CryptoContextException("Problem with Crypto Token: "+e.getMessage());
+
+ public CryptoManager getCryptoManager() {
+ return cm;
}
- catch (NoSuchAlgorithmException e) {
- throw new CryptoContextException(e.getMessage());
+
+ public KeyWrapper getKeyWrapper()
+ throws CryptoContextException {
+ try {
+ return signingCertPrivKey.getOwningToken().getKeyWrapper(KeyWrapAlgorithm.RSA);
+ } catch (TokenException e) {
+ throw new CryptoContextException("Problem with Crypto Token: " + e.getMessage());
+ } catch (NoSuchAlgorithmException e) {
+ throw new CryptoContextException(e.getMessage());
+ }
}
- }
- public org.mozilla.jss.crypto.PrivateKey getPrivateKey() {
- return signingCertPrivKey;
- }
+ public KeyWrapper getInternalKeyWrapper()
+ throws CryptoContextException {
+ try {
+ return getInternalToken().getKeyWrapper(KeyWrapAlgorithm.RSA);
+ } catch (TokenException e) {
+ throw new CryptoContextException("Problem with Crypto Token: " + e.getMessage());
+ } catch (NoSuchAlgorithmException e) {
+ throw new CryptoContextException(e.getMessage());
+ }
+ }
- public org.mozilla.jss.crypto.X509Certificate getSigningCert() {
- return signingCert;
- }
-
- }
+ public org.mozilla.jss.crypto.PrivateKey getPrivateKey() {
+ return signingCertPrivKey;
+ }
+ public org.mozilla.jss.crypto.X509Certificate getSigningCert() {
+ return signingCert;
+ }
- /* General failure. The request/response cannot be processed. */
+ }
+ /* General failure. The request/response cannot be processed. */
- class CRSFailureException extends Exception {
- /**
+ class CRSFailureException extends Exception {
+ /**
*
*/
- private static final long serialVersionUID = 1962741611501549051L;
- public CRSFailureException() { super(); }
- public CRSFailureException(String s) { super(s); }
- }
+ private static final long serialVersionUID = 1962741611501549051L;
- class CRSInvalidSignatureException extends Exception {
- /**
+ public CRSFailureException() {
+ super();
+ }
+
+ public CRSFailureException(String s) {
+ super(s);
+ }
+ }
+
+ class CRSInvalidSignatureException extends Exception {
+ /**
*
*/
- private static final long serialVersionUID = 9096408193567657944L;
- public CRSInvalidSignatureException() { super(); }
- public CRSInvalidSignatureException(String s) { super(s); }
- }
+ private static final long serialVersionUID = 9096408193567657944L;
+
+ public CRSInvalidSignatureException() {
+ super();
+ }
-
+ public CRSInvalidSignatureException(String s) {
+ super(s);
+ }
+ }
- class CRSPolicyException extends Exception {
- /**
+ class CRSPolicyException extends Exception {
+ /**
*
*/
- private static final long serialVersionUID = 5846593800658787396L;
- public CRSPolicyException() { super(); }
- public CRSPolicyException(String s) { super(s); }
- }
+ private static final long serialVersionUID = 5846593800658787396L;
-}
+ public CRSPolicyException() {
+ super();
+ }
+ public CRSPolicyException(String s) {
+ super(s);
+ }
+ }
+
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/scep/ChallengePassword.java b/pki/base/common/src/com/netscape/cms/servlet/cert/scep/ChallengePassword.java
index 49a591f0..79110442 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/scep/ChallengePassword.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/scep/ChallengePassword.java
@@ -29,115 +29,113 @@ import netscape.security.util.DerValue;
import netscape.security.x509.CertAttrSet;
/**
- * Class for handling the decoding of a SCEP Challenge Password
- * object. Currently this class cannot be used for encoding
- * thus some fo the methods are unimplemented
+ * Class for handling the decoding of a SCEP Challenge Password object.
+ * Currently this class cannot be used for encoding thus some fo the methods are
+ * unimplemented
*/
public class ChallengePassword implements CertAttrSet {
- public static final String NAME = "ChallengePassword";
- public static final String PASSWORD = "password";
-
- private String cpw;
-
-
- /**
- * Get the password marshalled in this object
- * @return the challenge password
- */
- public String toString() {
- return cpw;
- }
-
- /**
- * Create a ChallengePassword object
- * @param stuff (must be of type byte[]) a DER-encoded by array following
- * The ASN.1 template for ChallenegePassword specified in the SCEP
- * documentation
- * @throws IOException if the DER encoded byt array was malformed, or if it
- * did not match the template
- */
-
- public ChallengePassword(Object stuff)
- throws IOException {
-
- ByteArrayInputStream is = new ByteArrayInputStream((byte[])stuff);
- try {
- decode(is);
- } catch (Exception e) {
- throw new IOException(e.getMessage());
- }
-
- }
-
- /**
- * Currently Unimplemented
- */
- public void encode(OutputStream out)
- throws CertificateException, IOException
- { }
-
- public void decode(InputStream in)
- throws CertificateException, IOException
- {
+ public static final String NAME = "ChallengePassword";
+ public static final String PASSWORD = "password";
+
+ private String cpw;
+
+ /**
+ * Get the password marshalled in this object
+ *
+ * @return the challenge password
+ */
+ public String toString() {
+ return cpw;
+ }
+
+ /**
+ * Create a ChallengePassword object
+ *
+ * @param stuff (must be of type byte[]) a DER-encoded by array following
+ * The ASN.1 template for ChallenegePassword specified in the
+ * SCEP documentation
+ * @throws IOException if the DER encoded byt array was malformed, or if it
+ * did not match the template
+ */
+
+ public ChallengePassword(Object stuff)
+ throws IOException {
+
+ ByteArrayInputStream is = new ByteArrayInputStream((byte[]) stuff);
+ try {
+ decode(is);
+ } catch (Exception e) {
+ throw new IOException(e.getMessage());
+ }
+
+ }
+
+ /**
+ * Currently Unimplemented
+ */
+ public void encode(OutputStream out)
+ throws CertificateException, IOException {
+ }
+
+ public void decode(InputStream in)
+ throws CertificateException, IOException {
DerValue derVal = new DerValue(in);
construct(derVal);
-
+
+ }
+
+ private void construct(DerValue derVal) throws IOException {
+ try {
+ cpw = derVal.getPrintableString();
+ } catch (NullPointerException e) {
+ cpw = "";
+ }
+ }
+
+ /**
+ * Currently Unimplemented
+ */
+ public void set(String name, Object obj)
+ throws CertificateException, IOException {
}
- private void construct(DerValue derVal) throws IOException {
- try {
- cpw = derVal.getPrintableString();
- }
- catch (NullPointerException e) {
- cpw = "";
- }
- }
-
-
- /**
- * Currently Unimplemented
- */
- public void set(String name, Object obj)
- throws CertificateException, IOException
- { }
-
- /**
- * Get an attribute of this object.
- * @param name the name of the attribute of this object to get. The only
- * supported attribute is "password"
- */
- public Object get(String name)
- throws CertificateException, IOException
- {
+ /**
+ * Get an attribute of this object.
+ *
+ * @param name the name of the attribute of this object to get. The only
+ * supported attribute is "password"
+ */
+ public Object get(String name)
+ throws CertificateException, IOException {
if (name.equalsIgnoreCase(PASSWORD)) {
return cpw;
- }
- else {
- throw new IOException("Attribute name not recognized by "+
+ } else {
+ throw new IOException("Attribute name not recognized by " +
"CertAttrSet: ChallengePassword");
}
}
-
- /**
- * Currently Unimplemented
- */
- public void delete(String name)
- throws CertificateException, IOException
- { }
-
- /**
- * @return an empty set of elements
- */
- public Enumeration<String> getAttributeNames()
- { return (new Vector<String>()).elements();}
-
- /**
- * @return the String "ChallengePassword"
- */
- public String getName()
- { return NAME;}
-
-
+
+ /**
+ * Currently Unimplemented
+ */
+ public void delete(String name)
+ throws CertificateException, IOException {
+ }
+
+ /**
+ * @return an empty set of elements
+ */
+ public Enumeration<String> getAttributeNames() {
+ return (new Vector<String>()).elements();
+ }
+
+ /**
+ * @return the String "ChallengePassword"
+ */
+ public String getName() {
+ return NAME;
+ }
+
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/cert/scep/ExtensionsRequested.java b/pki/base/common/src/com/netscape/cms/servlet/cert/scep/ExtensionsRequested.java
index 6f689b34..eb1433aa 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/cert/scep/ExtensionsRequested.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/cert/scep/ExtensionsRequested.java
@@ -30,51 +30,46 @@ import netscape.security.util.DerValue;
import netscape.security.x509.CertAttrSet;
import netscape.security.x509.Extension;
-
public class ExtensionsRequested implements CertAttrSet {
+ public static final String NAME = "EXTENSIONS_REQUESTED";
- public static final String NAME = "EXTENSIONS_REQUESTED";
-
public static final String KUE_DIGITAL_SIGNATURE = "kue_digital_signature";
- public static final String KUE_KEY_ENCIPHERMENT = "kue_key_encipherment";
+ public static final String KUE_KEY_ENCIPHERMENT = "kue_key_encipherment";
private String kue_digital_signature = "false";
- private String kue_key_encipherment = "false";
-
+ private String kue_key_encipherment = "false";
+
private Vector<Extension> exts = new Vector<Extension>();
public ExtensionsRequested(Object stuff) throws IOException {
ByteArrayInputStream is = new ByteArrayInputStream((byte[]) stuff);
-
+
try {
decode(is);
- }
- catch (Exception e) {
+ } catch (Exception e) {
e.printStackTrace();
throw new IOException(e.getMessage());
}
}
-
- public void encode(OutputStream out)
- throws CertificateException, IOException
- { }
-
- public void decode(InputStream in)
- throws CertificateException, IOException
- {
+
+ public void encode(OutputStream out)
+ throws CertificateException, IOException {
+ }
+
+ public void decode(InputStream in)
+ throws CertificateException, IOException {
DerValue derVal = new DerValue(in);
-
+
construct(derVal);
}
-
+
public void set(String name, Object obj)
- throws CertificateException, IOException
- { }
-
- public Object get(String name)
- throws CertificateException, IOException
- {
+ throws CertificateException, IOException {
+ }
+
+ public Object get(String name)
+ throws CertificateException, IOException {
if (name.equalsIgnoreCase(KUE_DIGITAL_SIGNATURE)) {
return kue_digital_signature;
}
@@ -84,107 +79,83 @@ public class ExtensionsRequested implements CertAttrSet {
throw new IOException("Unsupported attribute queried");
}
-
- public void delete(String name)
- throws CertificateException, IOException
- {
+
+ public void delete(String name)
+ throws CertificateException, IOException {
+ }
+
+ public Enumeration<String> getAttributeNames() {
+ return (new Vector<String>()).elements();
+ }
+
+ public String getName() {
+ return NAME;
}
- public Enumeration<String> getAttributeNames()
- { return (new Vector<String>()).elements();}
-
- public String getName()
- { return NAME;}
-
-
-
-/**
- construct - expects this in the inputstream (from the router):
-
- 211 30 31: SEQUENCE {
- 213 06 10: OBJECT IDENTIFIER '2 16 840 1 113733 1 9 8'
- 225 31 17: SET {
- 227 04 15: OCTET STRING, encapsulates {
- 229 30 13: SEQUENCE {
- 231 30 11: SEQUENCE {
- 233 06 3: OBJECT IDENTIFIER keyUsage (2 5 29 15)
- 238 04 4: OCTET STRING
- : 03 02 05 A0
- : }
- : }
- : }
-
- or this (from IRE client):
-
- 262 30 51: SEQUENCE {
- 264 06 9: OBJECT IDENTIFIER extensionReq (1 2 840 113549 1 9 14)
- 275 31 38: SET {
- 277 30 36: SEQUENCE {
- 279 30 34: SEQUENCE {
- 281 06 3: OBJECT IDENTIFIER subjectAltName (2 5 29 17)
- 286 04 27: OCTET STRING
- : 30 19 87 04 D0 0C 3E 6F 81 03 61 61 61 82 0C 61
- : 61 61 2E 6D 63 6F 6D 2E 63 6F 6D
- : }
- : }
- : }
- : }
-
-
- */
+ /**
+ * construct - expects this in the inputstream (from the router):
+ *
+ * 211 30 31: SEQUENCE { 213 06 10: OBJECT IDENTIFIER '2 16 840 1 113733 1 9
+ * 8' 225 31 17: SET { 227 04 15: OCTET STRING, encapsulates { 229 30 13:
+ * SEQUENCE { 231 30 11: SEQUENCE { 233 06 3: OBJECT IDENTIFIER keyUsage (2
+ * 5 29 15) 238 04 4: OCTET STRING : 03 02 05 A0 : } : } : }
+ *
+ * or this (from IRE client):
+ *
+ * 262 30 51: SEQUENCE { 264 06 9: OBJECT IDENTIFIER extensionReq (1 2 840
+ * 113549 1 9 14) 275 31 38: SET { 277 30 36: SEQUENCE { 279 30 34: SEQUENCE
+ * { 281 06 3: OBJECT IDENTIFIER subjectAltName (2 5 29 17) 286 04 27: OCTET
+ * STRING : 30 19 87 04 D0 0C 3E 6F 81 03 61 61 61 82 0C 61 : 61 61 2E 6D 63
+ * 6F 6D 2E 63 6F 6D : } : } : } : }
+ */
private void construct(DerValue dv) throws IOException {
- DerInputStream stream = null;
- DerValue[] dvs;
+ DerInputStream stream = null;
+ DerValue[] dvs;
- try { // try decoding as sequence first
+ try { // try decoding as sequence first
- stream = dv.toDerInputStream();
+ stream = dv.toDerInputStream();
- DerValue stream_dv = stream.getDerValue();
- stream.reset();
-
+ DerValue stream_dv = stream.getDerValue();
+ stream.reset();
- dvs = stream.getSequence(2);
- }
- catch (IOException ioe) {
- // if it failed, the outer sequence may be
- // encapsulated in an octet string, as in the first
- // example above
+ dvs = stream.getSequence(2);
+ } catch (IOException ioe) {
+ // if it failed, the outer sequence may be
+ // encapsulated in an octet string, as in the first
+ // example above
- byte[] octet_string = dv.getOctetString();
+ byte[] octet_string = dv.getOctetString();
- // Make a new input stream from the byte array,
- // and re-parse it as a sequence.
+ // Make a new input stream from the byte array,
+ // and re-parse it as a sequence.
- dv = new DerValue(octet_string);
+ dv = new DerValue(octet_string);
- stream = dv.toDerInputStream();
- dvs = stream.getSequence(2);
- }
+ stream = dv.toDerInputStream();
+ dvs = stream.getSequence(2);
+ }
- // now, the stream will be in the correct format
- stream.reset();
+ // now, the stream will be in the correct format
+ stream.reset();
- while (true) {
- DerValue ext_dv=null;
- try {
- ext_dv = stream.getDerValue();
- }
- catch (IOException ex) {
- break;
- }
+ while (true) {
+ DerValue ext_dv = null;
+ try {
+ ext_dv = stream.getDerValue();
+ } catch (IOException ex) {
+ break;
+ }
- Extension ext = new Extension(ext_dv);
- exts.addElement(ext);
- }
+ Extension ext = new Extension(ext_dv);
+ exts.addElement(ext);
+ }
}
- public Vector<Extension> getExtensions() {
- return exts;
- }
+ public Vector<Extension> getExtensions() {
+ return exts;
+ }
}
-
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/common/AuthCredentials.java b/pki/base/common/src/com/netscape/cms/servlet/common/AuthCredentials.java
index 759238d9..3d0f788e 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/common/AuthCredentials.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/common/AuthCredentials.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.common;
-
import java.util.Enumeration;
import java.util.Hashtable;
@@ -25,11 +24,10 @@ import com.netscape.certsrv.authentication.IAuthCredentials;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IArgBlock;
-
/**
* Authentication Credentials as input to the authMgr
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class AuthCredentials implements IAuthCredentials {
@@ -38,21 +36,23 @@ public class AuthCredentials implements IAuthCredentials {
*/
private static final long serialVersionUID = -5995164231849154265L;
private Hashtable authCreds = null;
- // Inserted by bskim
+ // Inserted by bskim
private IArgBlock argblk = null;
+
// Insert end
-
+
public AuthCredentials() {
authCreds = new Hashtable();
}
/**
* sets a credential with credential name and the credential
+ *
* @param name credential name
* @param cred credential
* @exception com.netscape.certsrv.base.EBaseException NullPointerException
*/
- public void set(String name, Object cred)throws EBaseException {
+ public void set(String name, Object cred) throws EBaseException {
if (cred == null) {
throw new EBaseException("AuthCredentials.set()");
}
@@ -62,7 +62,8 @@ public class AuthCredentials implements IAuthCredentials {
/**
* returns the credential to which the specified name is mapped in this
- * credential set
+ * credential set
+ *
* @param name credential name
* @return the named authentication credential
*/
@@ -71,9 +72,10 @@ public class AuthCredentials implements IAuthCredentials {
}
/**
- * removes the name and its corresponding credential from this
- * credential set. This method does nothing if the named
- * credential is not in the credential set.
+ * removes the name and its corresponding credential from this credential
+ * set. This method does nothing if the named credential is not in the
+ * credential set.
+ *
* @param name credential name
*/
public void delete(String name) {
@@ -81,27 +83,27 @@ public class AuthCredentials implements IAuthCredentials {
}
/**
- * returns an enumeration of the credentials in this credential
- * set. Use the Enumeration methods on the returned object to
- * fetch the elements sequentially.
+ * returns an enumeration of the credentials in this credential set. Use the
+ * Enumeration methods on the returned object to fetch the elements
+ * sequentially.
+ *
* @return an enumeration of the values in this credential set
* @see java.util.Enumeration
*/
public Enumeration getElements() {
return (authCreds.elements());
}
-
+
// Inserted by bskim
public void setArgBlock(IArgBlock blk) {
argblk = blk;
return;
- }
+ }
// Insert end
-
+
public IArgBlock getArgBlock() {
return argblk;
- }
+ }
// Insert end
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/common/CMCOutputTemplate.java b/pki/base/common/src/com/netscape/cms/servlet/common/CMCOutputTemplate.java
index 3fac4a63..9fbb04e0 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/common/CMCOutputTemplate.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/common/CMCOutputTemplate.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.common;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -94,33 +93,33 @@ import com.netscape.certsrv.request.RequestStatus;
/**
* Utility CMCOutputTemplate
- *
+ *
* @version $ $, $Date$
*/
public class CMCOutputTemplate {
public CMCOutputTemplate() {
}
- public void createFullResponseWithFailedStatus(HttpServletResponse resp,
- SEQUENCE bpids, int code, UTF8String s) {
+ public void createFullResponseWithFailedStatus(HttpServletResponse resp,
+ SEQUENCE bpids, int code, UTF8String s) {
SEQUENCE controlSeq = new SEQUENCE();
SEQUENCE cmsSeq = new SEQUENCE();
SEQUENCE otherMsgSeq = new SEQUENCE();
int bpid = 1;
- OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL,
- new INTEGER(code), null);
+ OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL,
+ new INTEGER(code), null);
CMCStatusInfo cmcStatusInfo = new CMCStatusInfo(
- new INTEGER(CMCStatusInfo.FAILED),
- bpids, s, otherInfo);
+ new INTEGER(CMCStatusInfo.FAILED),
+ bpids, s, otherInfo);
TaggedAttribute tagattr = new TaggedAttribute(
- new INTEGER(bpid++),
- OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
+ new INTEGER(bpid++),
+ OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
controlSeq.addElement(tagattr);
try {
ResponseBody respBody = new ResponseBody(controlSeq,
- cmsSeq, otherMsgSeq);
+ cmsSeq, otherMsgSeq);
SET certs = new SET();
ContentInfo contentInfo = getContentInfo(respBody, certs);
@@ -137,13 +136,13 @@ public class CMCOutputTemplate {
os.write(contentBytes);
os.flush();
} catch (Exception e) {
- CMS.debug("CMCOutputTemplate createFullResponseWithFailedStatus Exception: "+e.toString());
+ CMS.debug("CMCOutputTemplate createFullResponseWithFailedStatus Exception: " + e.toString());
return;
}
}
- public void createFullResponse(HttpServletResponse resp, IRequest []reqs,
- String cert_request_type, int[] error_codes) {
+ public void createFullResponse(HttpServletResponse resp, IRequest[] reqs,
+ String cert_request_type, int[] error_codes) {
SEQUENCE controlSeq = new SEQUENCE();
SEQUENCE cmsSeq = new SEQUENCE();
@@ -157,32 +156,32 @@ public class CMCOutputTemplate {
SEQUENCE success_bpids = null;
SEQUENCE failed_bpids = null;
if (cert_request_type.equals("crmf") ||
- cert_request_type.equals("pkcs10")) {
+ cert_request_type.equals("pkcs10")) {
String reqId = reqs[0].getRequestId().toString();
OtherInfo otherInfo = null;
if (error_codes[0] == 2) {
PendInfo pendInfo = new PendInfo(reqId, new Date());
otherInfo = new OtherInfo(OtherInfo.PEND, null,
- pendInfo);
+ pendInfo);
} else {
- otherInfo = new OtherInfo(OtherInfo.FAIL,
- new INTEGER(OtherInfo.BAD_REQUEST), null);
+ otherInfo = new OtherInfo(OtherInfo.FAIL,
+ new INTEGER(OtherInfo.BAD_REQUEST), null);
}
-
+
SEQUENCE bpids = new SEQUENCE();
bpids.addElement(new INTEGER(1));
CMCStatusInfo cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.PENDING,
- bpids, (String)null, otherInfo);
+ bpids, (String) null, otherInfo);
TaggedAttribute tagattr = new TaggedAttribute(
- new INTEGER(bpid++),
- OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
+ new INTEGER(bpid++),
+ OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
controlSeq.addElement(tagattr);
} else if (cert_request_type.equals("cmc")) {
pending_bpids = new SEQUENCE();
success_bpids = new SEQUENCE();
failed_bpids = new SEQUENCE();
if (reqs != null) {
- for (int i=0; i<reqs.length; i++) {
+ for (int i = 0; i < reqs.length; i++) {
if (error_codes[i] == 0) {
success_bpids.addElement(new INTEGER(
reqs[i].getExtDataInBigInteger("bodyPartId")));
@@ -192,77 +191,77 @@ public class CMCOutputTemplate {
} else {
failed_bpids.addElement(new INTEGER(
reqs[i].getExtDataInBigInteger("bodyPartId")));
- }
+ }
}
}
TaggedAttribute tagattr = null;
CMCStatusInfo cmcStatusInfo = null;
- SEQUENCE identityBpids = (SEQUENCE)context.get("identityProof");
+ SEQUENCE identityBpids = (SEQUENCE) context.get("identityProof");
if (identityBpids != null && identityBpids.size() > 0) {
- OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL,
- new INTEGER(OtherInfo.BAD_IDENTITY), null);
+ OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL,
+ new INTEGER(OtherInfo.BAD_IDENTITY), null);
cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED,
- identityBpids, (String)null, otherInfo);
+ identityBpids, (String) null, otherInfo);
tagattr = new TaggedAttribute(
- new INTEGER(bpid++),
- OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
+ new INTEGER(bpid++),
+ OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
controlSeq.addElement(tagattr);
}
- SEQUENCE POPLinkWitnessBpids = (SEQUENCE)context.get("POPLinkWitness");
+ SEQUENCE POPLinkWitnessBpids = (SEQUENCE) context.get("POPLinkWitness");
if (POPLinkWitnessBpids != null && POPLinkWitnessBpids.size() > 0) {
OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL,
- new INTEGER(OtherInfo.BAD_REQUEST), null);
+ new INTEGER(OtherInfo.BAD_REQUEST), null);
cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED,
- POPLinkWitnessBpids, (String)null, otherInfo);
+ POPLinkWitnessBpids, (String) null, otherInfo);
tagattr = new TaggedAttribute(
- new INTEGER(bpid++),
- OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
+ new INTEGER(bpid++),
+ OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
controlSeq.addElement(tagattr);
}
if (pending_bpids.size() > 0) {
- cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.PENDING,
- pending_bpids, (String)null, null);
+ cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.PENDING,
+ pending_bpids, (String) null, null);
tagattr = new TaggedAttribute(
- new INTEGER(bpid++),
- OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
- controlSeq.addElement(tagattr);
- }
+ new INTEGER(bpid++),
+ OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
+ controlSeq.addElement(tagattr);
+ }
if (success_bpids.size() > 0) {
boolean confirmRequired = false;
try {
- confirmRequired =
- CMS.getConfigStore().getBoolean("cmc.cert.confirmRequired",
- false);
- } catch (Exception e) {
+ confirmRequired =
+ CMS.getConfigStore().getBoolean("cmc.cert.confirmRequired",
+ false);
+ } catch (Exception e) {
}
if (confirmRequired) {
CMS.debug("CMCOutputTemplate: confirmRequired in the request");
- cmcStatusInfo =
- new CMCStatusInfo(CMCStatusInfo.CONFIRM_REQUIRED,
- success_bpids, (String)null, null);
+ cmcStatusInfo =
+ new CMCStatusInfo(CMCStatusInfo.CONFIRM_REQUIRED,
+ success_bpids, (String) null, null);
} else {
- cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.SUCCESS,
- success_bpids, (String)null, null);
+ cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.SUCCESS,
+ success_bpids, (String) null, null);
}
tagattr = new TaggedAttribute(
- new INTEGER(bpid++),
- OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
- controlSeq.addElement(tagattr);
+ new INTEGER(bpid++),
+ OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
+ controlSeq.addElement(tagattr);
}
if (failed_bpids.size() > 0) {
- OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL,
- new INTEGER(OtherInfo.BAD_REQUEST), null);
- cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED,
- failed_bpids, (String)null, otherInfo);
+ OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL,
+ new INTEGER(OtherInfo.BAD_REQUEST), null);
+ cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED,
+ failed_bpids, (String) null, otherInfo);
tagattr = new TaggedAttribute(
- new INTEGER(bpid++),
- OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
- controlSeq.addElement(tagattr);
+ new INTEGER(bpid++),
+ OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
+ controlSeq.addElement(tagattr);
}
}
@@ -270,80 +269,80 @@ public class CMCOutputTemplate {
try {
// deal with controls
- Integer nums = (Integer)(context.get("numOfControls"));
+ Integer nums = (Integer) (context.get("numOfControls"));
if (nums != null && nums.intValue() > 0) {
TaggedAttribute attr =
- (TaggedAttribute)(context.get(OBJECT_IDENTIFIER.id_cmc_getCert));
+ (TaggedAttribute) (context.get(OBJECT_IDENTIFIER.id_cmc_getCert));
if (attr != null) {
try {
processGetCertControl(attr, certs);
} catch (EBaseException ee) {
- CMS.debug("CMCOutputTemplate: "+ee.toString());
+ CMS.debug("CMCOutputTemplate: " + ee.toString());
OtherInfo otherInfo1 = new OtherInfo(OtherInfo.FAIL,
- new INTEGER(OtherInfo.BAD_CERT_ID), null);
+ new INTEGER(OtherInfo.BAD_CERT_ID), null);
SEQUENCE bpids1 = new SEQUENCE();
bpids1.addElement(attr.getBodyPartID());
CMCStatusInfo cmcStatusInfo1 = new CMCStatusInfo(
- new INTEGER(CMCStatusInfo.FAILED),
- bpids1, null, otherInfo1);
+ new INTEGER(CMCStatusInfo.FAILED),
+ bpids1, null, otherInfo1);
TaggedAttribute tagattr1 = new TaggedAttribute(
- new INTEGER(bpid++),
- OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo1);
+ new INTEGER(bpid++),
+ OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo1);
controlSeq.addElement(tagattr1);
}
}
- attr =
- (TaggedAttribute)(context.get(OBJECT_IDENTIFIER.id_cmc_dataReturn));
+ attr =
+ (TaggedAttribute) (context.get(OBJECT_IDENTIFIER.id_cmc_dataReturn));
if (attr != null)
bpid = processDataReturnControl(attr, controlSeq, bpid);
attr =
- (TaggedAttribute)context.get(OBJECT_IDENTIFIER.id_cmc_transactionId);
+ (TaggedAttribute) context.get(OBJECT_IDENTIFIER.id_cmc_transactionId);
if (attr != null)
bpid = processTransactionControl(attr, controlSeq, bpid);
attr =
- (TaggedAttribute)context.get(OBJECT_IDENTIFIER.id_cmc_senderNonce);
+ (TaggedAttribute) context.get(OBJECT_IDENTIFIER.id_cmc_senderNonce);
if (attr != null)
bpid = processSenderNonceControl(attr, controlSeq, bpid);
attr =
- (TaggedAttribute)context.get(OBJECT_IDENTIFIER.id_cmc_QueryPending);
+ (TaggedAttribute) context.get(OBJECT_IDENTIFIER.id_cmc_QueryPending);
if (attr != null)
- bpid = processQueryPendingControl(attr, controlSeq, bpid);
+ bpid = processQueryPendingControl(attr, controlSeq, bpid);
- attr =
- (TaggedAttribute)context.get(OBJECT_IDENTIFIER.id_cmc_idConfirmCertAcceptance);
+ attr =
+ (TaggedAttribute) context.get(OBJECT_IDENTIFIER.id_cmc_idConfirmCertAcceptance);
- if (attr != null)
+ if (attr != null)
bpid = processConfirmCertAcceptanceControl(attr, controlSeq,
- bpid);
+ bpid);
- attr =
- (TaggedAttribute)context.get(OBJECT_IDENTIFIER.id_cmc_revokeRequest);
+ attr =
+ (TaggedAttribute) context.get(OBJECT_IDENTIFIER.id_cmc_revokeRequest);
- if (attr != null)
+ if (attr != null)
bpid = processRevokeRequestControl(attr, controlSeq,
- bpid);
+ bpid);
}
if (success_bpids != null && success_bpids.size() > 0) {
- for (int i=0; i<reqs.length; i++) {
+ for (int i = 0; i < reqs.length; i++) {
if (error_codes[i] == 0) {
- X509CertImpl impl =
- (reqs[i].getExtDataInCert(IEnrollProfile.REQUEST_ISSUED_CERT));
+ X509CertImpl impl =
+ (reqs[i].getExtDataInCert(IEnrollProfile.REQUEST_ISSUED_CERT));
byte[] bin = impl.getEncoded();
Certificate.Template certTemplate = new Certificate.Template();
- Certificate cert = (Certificate)certTemplate.decode(
- new ByteArrayInputStream(bin));
+ Certificate cert = (Certificate) certTemplate.decode(
+ new ByteArrayInputStream(bin));
certs.addElement(cert);
}
}
}
ResponseBody respBody = new ResponseBody(controlSeq,
- cmsSeq, otherMsgSeq);
+ cmsSeq, otherMsgSeq);
ContentInfo contentInfo = getContentInfo(respBody, certs);
ByteArrayOutputStream fos = new ByteArrayOutputStream();
@@ -354,16 +353,16 @@ public class CMCOutputTemplate {
resp.setContentType("application/pkcs7-mime");
resp.setContentLength(contentBytes.length);
OutputStream os = resp.getOutputStream();
- os.write(contentBytes);
+ os.write(contentBytes);
os.flush();
} catch (java.security.cert.CertificateEncodingException e) {
- CMS.debug("CMCOutputTemplate exception: "+e.toString());
+ CMS.debug("CMCOutputTemplate exception: " + e.toString());
} catch (InvalidBERException e) {
- CMS.debug("CMCOutputTemplate exception: "+e.toString());
+ CMS.debug("CMCOutputTemplate exception: " + e.toString());
} catch (IOException e) {
- CMS.debug("CMCOutputTemplate exception: "+e.toString());
+ CMS.debug("CMCOutputTemplate exception: " + e.toString());
} catch (Exception e) {
- CMS.debug("Exception: "+e.toString());
+ CMS.debug("Exception: " + e.toString());
}
}
@@ -371,48 +370,46 @@ public class CMCOutputTemplate {
try {
ICertificateAuthority ca = null;
// add CA cert chain
- ca = (ICertificateAuthority)CMS.getSubsystem("ca");
+ ca = (ICertificateAuthority) CMS.getSubsystem("ca");
CertificateChain certchains = ca.getCACertChain();
java.security.cert.X509Certificate[] chains = certchains.getChain();
- for (int i=0; i<chains.length; i++) {
+ for (int i = 0; i < chains.length; i++) {
Certificate.Template certTemplate = new Certificate.Template();
- Certificate cert = (Certificate)certTemplate.decode(
- new ByteArrayInputStream(chains[i].getEncoded()));
+ Certificate cert = (Certificate) certTemplate.decode(
+ new ByteArrayInputStream(chains[i].getEncoded()));
certs.addElement(cert);
}
-
+
EncapsulatedContentInfo enContentInfo = new EncapsulatedContentInfo(
- OBJECT_IDENTIFIER.id_cct_PKIResponse, respBody);
+ OBJECT_IDENTIFIER.id_cct_PKIResponse, respBody);
org.mozilla.jss.crypto.X509Certificate x509CAcert = null;
x509CAcert = ca.getCaX509Cert();
X509CertImpl caimpl = new X509CertImpl(x509CAcert.getEncoded());
- X500Name issuerName = (X500Name)caimpl.getIssuerDN();
+ X500Name issuerName = (X500Name) caimpl.getIssuerDN();
byte[] issuerByte = issuerName.getEncoded();
- ByteArrayInputStream istream = new ByteArrayInputStream(issuerByte);
+ ByteArrayInputStream istream = new ByteArrayInputStream(issuerByte);
Name issuer = (Name) Name.getTemplate().decode(istream);
IssuerAndSerialNumber ias = new IssuerAndSerialNumber(
- issuer, new INTEGER(x509CAcert.getSerialNumber().toString()));
+ issuer, new INTEGER(x509CAcert.getSerialNumber().toString()));
SignerIdentifier si = new SignerIdentifier(
- SignerIdentifier.ISSUER_AND_SERIALNUMBER, ias, null);
+ SignerIdentifier.ISSUER_AND_SERIALNUMBER, ias, null);
// use CA instance's default signature and digest algorithm
SignatureAlgorithm signAlg = ca.getDefaultSignatureAlgorithm();
org.mozilla.jss.crypto.PrivateKey privKey =
- CryptoManager.getInstance().findPrivKeyByCert(x509CAcert);
-/*
- org.mozilla.jss.crypto.PrivateKey.Type keyType = privKey.getType();
- if( keyType.equals( org.mozilla.jss.crypto.PrivateKey.RSA ) ) {
- signAlg = SignatureAlgorithm.RSASignatureWithSHA1Digest;
- } else if( keyType.equals( org.mozilla.jss.crypto.PrivateKey.DSA ) ) {
- signAlg = SignatureAlgorithm.DSASignatureWithSHA1Digest;
- } else if( keyType.equals( org.mozilla.jss.crypto.PrivateKey.EC ) ) {
- signAlg = SignatureAlgorithm.ECSignatureWithSHA1Digest;
- } else {
- CMS.debug( "CMCOutputTemplate::getContentInfo() - "
- + "signAlg is unsupported!" );
- return null;
- }
-*/
+ CryptoManager.getInstance().findPrivKeyByCert(x509CAcert);
+ /*
+ * org.mozilla.jss.crypto.PrivateKey.Type keyType =
+ * privKey.getType(); if( keyType.equals(
+ * org.mozilla.jss.crypto.PrivateKey.RSA ) ) { signAlg =
+ * SignatureAlgorithm.RSASignatureWithSHA1Digest; } else if(
+ * keyType.equals( org.mozilla.jss.crypto.PrivateKey.DSA ) ) {
+ * signAlg = SignatureAlgorithm.DSASignatureWithSHA1Digest; } else
+ * if( keyType.equals( org.mozilla.jss.crypto.PrivateKey.EC ) ) {
+ * signAlg = SignatureAlgorithm.ECSignatureWithSHA1Digest; } else {
+ * CMS.debug( "CMCOutputTemplate::getContentInfo() - " +
+ * "signAlg is unsupported!" ); return null; }
+ */
DigestAlgorithm digestAlg = signAlg.getDigestAlg();
MessageDigest msgDigest = null;
byte[] digest = null;
@@ -425,9 +422,9 @@ public class CMCOutputTemplate {
digest = msgDigest.digest(ostream.toByteArray());
SignerInfo signInfo = new
- SignerInfo(si, null, null,
- OBJECT_IDENTIFIER.id_cct_PKIResponse,
- digest, signAlg, privKey);
+ SignerInfo(si, null, null,
+ OBJECT_IDENTIFIER.id_cct_PKIResponse,
+ digest, signAlg, privKey);
SET signInfos = new SET();
signInfos.addElement(signInfo);
@@ -436,30 +433,30 @@ public class CMCOutputTemplate {
if (digestAlg != null) {
AlgorithmIdentifier ai = new
- AlgorithmIdentifier(digestAlg.toOID(), null);
-
+ AlgorithmIdentifier(digestAlg.toOID(), null);
+
digestAlgs.addElement(ai);
}
SignedData signedData = new SignedData(digestAlgs,
- enContentInfo, certs, null, signInfos);
+ enContentInfo, certs, null, signInfos);
ContentInfo contentInfo = new ContentInfo(signedData);
CMS.debug("CMCOutputTemplate::getContentInfo() - done");
return contentInfo;
} catch (Exception e) {
- CMS.debug("CMCOutputTemplate: Failed to create CMCContentInfo. Exception: "+e.toString());
+ CMS.debug("CMCOutputTemplate: Failed to create CMCContentInfo. Exception: " + e.toString());
}
- return null;
+ return null;
}
- public void createSimpleResponse(HttpServletResponse resp, IRequest []reqs) {
+ public void createSimpleResponse(HttpServletResponse resp, IRequest[] reqs) {
SET certs = new SET();
SessionContext context = SessionContext.getContext();
try {
- TaggedAttribute attr =
- (TaggedAttribute)(context.get(OBJECT_IDENTIFIER.id_cmc_getCert));
+ TaggedAttribute attr =
+ (TaggedAttribute) (context.get(OBJECT_IDENTIFIER.id_cmc_getCert));
processGetCertControl(attr, certs);
- } catch (Exception e) {
+ } catch (Exception e) {
CMS.debug("CMCOutputTemplate: No certificate is found.");
}
@@ -472,34 +469,34 @@ public class CMCOutputTemplate {
try {
if (reqs != null) {
- for (int i=0; i<reqs.length; i++) {
- X509CertImpl impl =
- (reqs[i].getExtDataInCert(IEnrollProfile.REQUEST_ISSUED_CERT));
+ for (int i = 0; i < reqs.length; i++) {
+ X509CertImpl impl =
+ (reqs[i].getExtDataInCert(IEnrollProfile.REQUEST_ISSUED_CERT));
byte[] bin = impl.getEncoded();
Certificate.Template certTemplate = new Certificate.Template();
- Certificate cert =
- (Certificate)certTemplate.decode(new ByteArrayInputStream(bin));
+ Certificate cert =
+ (Certificate) certTemplate.decode(new ByteArrayInputStream(bin));
certs.addElement(cert);
}
// Get CA certs
- ICertificateAuthority ca = (ICertificateAuthority)CMS.getSubsystem("ca");
+ ICertificateAuthority ca = (ICertificateAuthority) CMS.getSubsystem("ca");
CertificateChain certchains = ca.getCACertChain();
java.security.cert.X509Certificate[] chains = certchains.getChain();
- for (int i=0; i<chains.length; i++) {
+ for (int i = 0; i < chains.length; i++) {
Certificate.Template certTemplate = new Certificate.Template();
- Certificate cert = (Certificate)certTemplate.decode(
- new ByteArrayInputStream(chains[i].getEncoded()));
+ Certificate cert = (Certificate) certTemplate.decode(
+ new ByteArrayInputStream(chains[i].getEncoded()));
certs.addElement(cert);
}
}
-
+
if (certs.size() == 0)
return;
SignedData signedData = new SignedData(digestAlgorithms,
- enContentInfo, certs, null, signedInfos);
+ enContentInfo, certs, null, signedInfos);
ContentInfo contentInfo = new ContentInfo(signedData);
ByteArrayOutputStream fos = new ByteArrayOutputStream();
@@ -510,48 +507,48 @@ public class CMCOutputTemplate {
resp.setContentType("application/pkcs7-mime");
resp.setContentLength(contentBytes.length);
OutputStream os = resp.getOutputStream();
- os.write(contentBytes);
+ os.write(contentBytes);
os.flush();
} catch (java.security.cert.CertificateEncodingException e) {
- CMS.debug("CMCOutputTemplate exception: "+e.toString());
+ CMS.debug("CMCOutputTemplate exception: " + e.toString());
} catch (InvalidBERException e) {
- CMS.debug("CMCOutputTemplate exception: "+e.toString());
+ CMS.debug("CMCOutputTemplate exception: " + e.toString());
} catch (IOException e) {
- CMS.debug("CMCOutputTemplate exception: "+e.toString());
+ CMS.debug("CMCOutputTemplate exception: " + e.toString());
}
}
private int processConfirmCertAcceptanceControl(
- TaggedAttribute attr, SEQUENCE controlSeq, int bpid) {
+ TaggedAttribute attr, SEQUENCE controlSeq, int bpid) {
if (attr != null) {
INTEGER bodyId = attr.getBodyPartID();
SEQUENCE seq = new SEQUENCE();
- seq.addElement(bodyId);
+ seq.addElement(bodyId);
SET values = attr.getValues();
if (values != null && values.size() > 0) {
try {
- CMCCertId cmcCertId =
- (CMCCertId)(ASN1Util.decode(CMCCertId.getTemplate(),
- ASN1Util.encode(values.elementAt(0))));
- BigInteger serialno = (BigInteger)(cmcCertId.getSerial());
- SEQUENCE issuers = cmcCertId.getIssuer();
- //ANY issuer = (ANY)issuers.elementAt(0);
- ANY issuer =
- (ANY)(ASN1Util.decode(ANY.getTemplate(),
- ASN1Util.encode(issuers.elementAt(0))));
+ CMCCertId cmcCertId =
+ (CMCCertId) (ASN1Util.decode(CMCCertId.getTemplate(),
+ ASN1Util.encode(values.elementAt(0))));
+ BigInteger serialno = (BigInteger) (cmcCertId.getSerial());
+ SEQUENCE issuers = cmcCertId.getIssuer();
+ // ANY issuer = (ANY)issuers.elementAt(0);
+ ANY issuer =
+ (ANY) (ASN1Util.decode(ANY.getTemplate(),
+ ASN1Util.encode(issuers.elementAt(0))));
byte[] b = issuer.getEncoded();
X500Name n = new X500Name(b);
ICertificateAuthority ca = null;
- ca = (ICertificateAuthority)CMS.getSubsystem("ca");
+ ca = (ICertificateAuthority) CMS.getSubsystem("ca");
X500Name caName = ca.getX500Name();
boolean confirmAccepted = false;
if (n.toString().equalsIgnoreCase(caName.toString())) {
CMS.debug("CMCOutputTemplate: Issuer names are equal");
ICertificateRepository repository =
- (ICertificateRepository)ca.getCertificateRepository();
+ (ICertificateRepository) ca.getCertificateRepository();
X509CertImpl impl = null;
try {
- repository.getX509Certificate(serialno);
+ repository.getX509Certificate(serialno);
} catch (EBaseException ee) {
CMS.debug("CMCOutputTemplate: Certificate in the confirm acceptance control was not found");
}
@@ -559,77 +556,77 @@ public class CMCOutputTemplate {
CMCStatusInfo cmcStatusInfo = null;
if (confirmAccepted) {
CMS.debug("CMCOutputTemplate: Confirm Acceptance received. The certificate exists in the certificate repository.");
- cmcStatusInfo =
- new CMCStatusInfo(CMCStatusInfo.SUCCESS, seq,
- (String)null, null);
+ cmcStatusInfo =
+ new CMCStatusInfo(CMCStatusInfo.SUCCESS, seq,
+ (String) null, null);
} else {
CMS.debug("CMCOutputTemplate: Confirm Acceptance received. The certificate does not exist in the certificate repository.");
- OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL,
- new INTEGER(OtherInfo.BAD_CERT_ID), null);
- cmcStatusInfo =
- new CMCStatusInfo(CMCStatusInfo.FAILED, seq,
- (String)null, otherInfo);
+ OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL,
+ new INTEGER(OtherInfo.BAD_CERT_ID), null);
+ cmcStatusInfo =
+ new CMCStatusInfo(CMCStatusInfo.FAILED, seq,
+ (String) null, otherInfo);
}
TaggedAttribute statustagattr = new TaggedAttribute(
- new INTEGER(bpid++),
- OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
- controlSeq.addElement(statustagattr);
+ new INTEGER(bpid++),
+ OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
+ controlSeq.addElement(statustagattr);
} catch (Exception e) {
- CMS.debug("CMCOutputTemplate exception: "+e.toString());
+ CMS.debug("CMCOutputTemplate exception: " + e.toString());
}
- }
+ }
}
return bpid;
}
private void processGetCertControl(TaggedAttribute attr, SET certs)
- throws InvalidBERException, java.security.cert.CertificateEncodingException,
- IOException, EBaseException {
+ throws InvalidBERException, java.security.cert.CertificateEncodingException,
+ IOException, EBaseException {
if (attr != null) {
SET vals = attr.getValues();
if (vals.size() == 1) {
GetCert getCert =
- (GetCert)(ASN1Util.decode(GetCert.getTemplate(),
- ASN1Util.encode(vals.elementAt(0))));
- BigInteger serialno = (BigInteger)(getCert.getSerialNumber());
- ANY issuer = (ANY)getCert.getIssuer();
+ (GetCert) (ASN1Util.decode(GetCert.getTemplate(),
+ ASN1Util.encode(vals.elementAt(0))));
+ BigInteger serialno = (BigInteger) (getCert.getSerialNumber());
+ ANY issuer = (ANY) getCert.getIssuer();
byte b[] = issuer.getEncoded();
X500Name n = new X500Name(b);
- ICertificateAuthority ca = (ICertificateAuthority)CMS.getSubsystem("ca");
+ ICertificateAuthority ca = (ICertificateAuthority) CMS.getSubsystem("ca");
X500Name caName = ca.getX500Name();
if (!n.toString().equalsIgnoreCase(caName.toString())) {
CMS.debug("CMCOutputTemplate: Issuer names are equal in the GetCert Control");
throw new EBaseException("Certificate is not found");
}
ICertificateRepository repository =
- (ICertificateRepository)ca.getCertificateRepository();
+ (ICertificateRepository) ca.getCertificateRepository();
X509CertImpl impl = repository.getX509Certificate(serialno);
byte[] bin = impl.getEncoded();
Certificate.Template certTemplate = new Certificate.Template();
Certificate cert =
- (Certificate)certTemplate.decode(new ByteArrayInputStream(bin));
+ (Certificate) certTemplate.decode(new ByteArrayInputStream(bin));
certs.addElement(cert);
}
}
}
-
+
private int processQueryPendingControl(TaggedAttribute attr,
- SEQUENCE controlSeq, int bpid) {
+ SEQUENCE controlSeq, int bpid) {
if (attr != null) {
SET values = attr.getValues();
- if (values != null && values.size() > 0) {
+ if (values != null && values.size() > 0) {
SEQUENCE pending_bpids = new SEQUENCE();
SEQUENCE success_bpids = new SEQUENCE();
SEQUENCE failed_bpids = new SEQUENCE();
- for (int i=0; i<values.size(); i++) {
+ for (int i = 0; i < values.size(); i++) {
try {
INTEGER reqId = (INTEGER)
- ASN1Util.decode(INTEGER.getTemplate(),
- ASN1Util.encode(values.elementAt(i)));
+ ASN1Util.decode(INTEGER.getTemplate(),
+ ASN1Util.encode(values.elementAt(i)));
String requestId = new String(reqId.toByteArray());
- ICertificateAuthority ca = (ICertificateAuthority)CMS.getSubsystem("ca");
+ ICertificateAuthority ca = (ICertificateAuthority) CMS.getSubsystem("ca");
IRequestQueue queue = ca.getRequestQueue();
IRequest r = queue.findRequest(new RequestId(requestId));
if (r != null) {
@@ -649,43 +646,43 @@ public class CMCOutputTemplate {
if (pending_bpids.size() > 0) {
CMCStatusInfo cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.PENDING,
- pending_bpids, (String)null, null);
+ pending_bpids, (String) null, null);
TaggedAttribute tagattr = new TaggedAttribute(
- new INTEGER(bpid++),
- OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
+ new INTEGER(bpid++),
+ OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
controlSeq.addElement(tagattr);
}
if (success_bpids.size() > 0) {
CMCStatusInfo cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.SUCCESS,
- pending_bpids, (String)null, null);
+ pending_bpids, (String) null, null);
TaggedAttribute tagattr = new TaggedAttribute(
- new INTEGER(bpid++),
- OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
+ new INTEGER(bpid++),
+ OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
controlSeq.addElement(tagattr);
}
if (failed_bpids.size() > 0) {
CMCStatusInfo cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED,
- pending_bpids, (String)null, null);
+ pending_bpids, (String) null, null);
TaggedAttribute tagattr = new TaggedAttribute(
- new INTEGER(bpid++),
- OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
+ new INTEGER(bpid++),
+ OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
controlSeq.addElement(tagattr);
}
- }
+ }
}
return bpid;
}
- private int processTransactionControl(TaggedAttribute attr,
- SEQUENCE controlSeq, int bpid) {
+ private int processTransactionControl(TaggedAttribute attr,
+ SEQUENCE controlSeq, int bpid) {
if (attr != null) {
SET transIds = attr.getValues();
if (transIds != null) {
TaggedAttribute tagattr = new TaggedAttribute(
- new INTEGER(bpid++), OBJECT_IDENTIFIER.id_cmc_transactionId,
- transIds);
+ new INTEGER(bpid++), OBJECT_IDENTIFIER.id_cmc_transactionId,
+ transIds);
controlSeq.addElement(tagattr);
}
}
@@ -694,16 +691,16 @@ public class CMCOutputTemplate {
}
private int processSenderNonceControl(TaggedAttribute attr,
- SEQUENCE controlSeq, int bpid) {
+ SEQUENCE controlSeq, int bpid) {
if (attr != null) {
SET sNonce = attr.getValues();
if (sNonce != null) {
TaggedAttribute tagattr = new TaggedAttribute(
- new INTEGER(bpid++), OBJECT_IDENTIFIER.id_cmc_recipientNonce,
- sNonce);
+ new INTEGER(bpid++), OBJECT_IDENTIFIER.id_cmc_recipientNonce,
+ sNonce);
controlSeq.addElement(tagattr);
Date date = new Date();
- String salt = "lala123"+date.toString();
+ String salt = "lala123" + date.toString();
byte[] dig;
try {
MessageDigest SHA1Digest = MessageDigest.getInstance("SHA1");
@@ -714,8 +711,8 @@ public class CMCOutputTemplate {
String b64E = CMS.BtoA(dig);
tagattr = new TaggedAttribute(
- new INTEGER(bpid++), OBJECT_IDENTIFIER.id_cmc_senderNonce,
- new OCTET_STRING(b64E.getBytes()));
+ new INTEGER(bpid++), OBJECT_IDENTIFIER.id_cmc_senderNonce,
+ new OCTET_STRING(b64E.getBytes()));
controlSeq.addElement(tagattr);
}
}
@@ -723,29 +720,29 @@ public class CMCOutputTemplate {
return bpid;
}
- private int processDataReturnControl(TaggedAttribute attr,
- SEQUENCE controlSeq, int bpid) throws InvalidBERException {
+ private int processDataReturnControl(TaggedAttribute attr,
+ SEQUENCE controlSeq, int bpid) throws InvalidBERException {
if (attr != null) {
SET vals = attr.getValues();
-
+
if (vals.size() > 0) {
- OCTET_STRING str =
- (OCTET_STRING)(ASN1Util.decode(OCTET_STRING.getTemplate(),
- ASN1Util.encode(vals.elementAt(0))));
+ OCTET_STRING str =
+ (OCTET_STRING) (ASN1Util.decode(OCTET_STRING.getTemplate(),
+ ASN1Util.encode(vals.elementAt(0))));
TaggedAttribute tagattr = new TaggedAttribute(
- new INTEGER(bpid++),
- OBJECT_IDENTIFIER.id_cmc_dataReturn, str);
- controlSeq.addElement(tagattr);
+ new INTEGER(bpid++),
+ OBJECT_IDENTIFIER.id_cmc_dataReturn, str);
+ controlSeq.addElement(tagattr);
}
- }
+ }
return bpid;
}
- private int processRevokeRequestControl(TaggedAttribute attr,
- SEQUENCE controlSeq, int bpid) throws InvalidBERException, EBaseException,
- IOException {
+ private int processRevokeRequestControl(TaggedAttribute attr,
+ SEQUENCE controlSeq, int bpid) throws InvalidBERException, EBaseException,
+ IOException {
boolean revoke = false;
SessionContext context = SessionContext.getContext();
if (attr != null) {
@@ -754,10 +751,10 @@ public class CMCOutputTemplate {
SET vals = attr.getValues();
if (vals.size() > 0) {
RevRequest revRequest =
- (RevRequest)(ASN1Util.decode(new RevRequest.Template(),
- ASN1Util.encode(vals.elementAt(0))));
+ (RevRequest) (ASN1Util.decode(new RevRequest.Template(),
+ ASN1Util.encode(vals.elementAt(0))));
OCTET_STRING str = revRequest.getSharedSecret();
- INTEGER pid = attr.getBodyPartID();
+ INTEGER pid = attr.getBodyPartID();
TaggedAttribute tagattr = null;
INTEGER revokeCertSerial = revRequest.getSerialNumber();
BigInteger revokeSerial = new BigInteger(revokeCertSerial.toByteArray());
@@ -767,25 +764,25 @@ public class CMCOutputTemplate {
needVerify = CMS.getConfigStore().getBoolean("cmc.revokeCert.verify", true);
} catch (Exception e) {
}
-
+
if (needVerify) {
- Integer num1 = (Integer)context.get("numOfOtherMsgs");
+ Integer num1 = (Integer) context.get("numOfOtherMsgs");
int num = num1.intValue();
- for (int i=0; i<num; i++) {
- OtherMsg data = (OtherMsg)context.get("otherMsg"+i);
- INTEGER dpid = data.getBodyPartID();
+ for (int i = 0; i < num; i++) {
+ OtherMsg data = (OtherMsg) context.get("otherMsg" + i);
+ INTEGER dpid = data.getBodyPartID();
if (pid.longValue() == dpid.longValue()) {
- ANY msgValue = data.getOtherMsgValue();
- SignedData msgData =
- (SignedData)msgValue.decodeWith(SignedData.getTemplate());
+ ANY msgValue = data.getOtherMsgValue();
+ SignedData msgData =
+ (SignedData) msgValue.decodeWith(SignedData.getTemplate());
if (!verifyRevRequestSignature(msgData)) {
OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL, new INTEGER(OtherInfo.BAD_MESSAGE_CHECK), null);
SEQUENCE failed_bpids = new SEQUENCE();
failed_bpids.addElement(attrbpid);
- cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED, failed_bpids, (String)null, otherInfo);
+ cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED, failed_bpids, (String) null, otherInfo);
tagattr = new TaggedAttribute(
- new INTEGER(bpid++),
- OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
+ new INTEGER(bpid++),
+ OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
controlSeq.addElement(tagattr);
return bpid;
}
@@ -794,7 +791,7 @@ public class CMCOutputTemplate {
}
revoke = true;
- // check shared secret
+ // check shared secret
} else {
ISharedToken tokenClass = null;
boolean sharedSecretFound = true;
@@ -810,15 +807,15 @@ public class CMCOutputTemplate {
}
try {
- tokenClass = (ISharedToken)Class.forName(name).newInstance();
+ tokenClass = (ISharedToken) Class.forName(name).newInstance();
} catch (ClassNotFoundException e) {
- CMS.debug("EnrollProfile: Failed to find class name: "+name);
+ CMS.debug("EnrollProfile: Failed to find class name: " + name);
sharedSecretFound = false;
} catch (InstantiationException e) {
- CMS.debug("EnrollProfile: Failed to instantiate class: "+name);
+ CMS.debug("EnrollProfile: Failed to instantiate class: " + name);
sharedSecretFound = false;
} catch (IllegalAccessException e) {
- CMS.debug("EnrollProfile: Illegal access: "+name);
+ CMS.debug("EnrollProfile: Illegal access: " + name);
sharedSecretFound = false;
}
@@ -827,10 +824,10 @@ public class CMCOutputTemplate {
OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL, new INTEGER(OtherInfo.INTERNAL_CA_ERROR), null);
SEQUENCE failed_bpids = new SEQUENCE();
failed_bpids.addElement(attrbpid);
- cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED, failed_bpids, (String)null, otherInfo);
+ cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED, failed_bpids, (String) null, otherInfo);
tagattr = new TaggedAttribute(
- new INTEGER(bpid++),
- OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
+ new INTEGER(bpid++),
+ OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
controlSeq.addElement(tagattr);
return bpid;
}
@@ -846,10 +843,10 @@ public class CMCOutputTemplate {
OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL, new INTEGER(OtherInfo.INTERNAL_CA_ERROR), null);
SEQUENCE failed_bpids = new SEQUENCE();
failed_bpids.addElement(attrbpid);
- cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED, failed_bpids, (String)null, otherInfo);
+ cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED, failed_bpids, (String) null, otherInfo);
tagattr = new TaggedAttribute(
- new INTEGER(bpid++),
- OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
+ new INTEGER(bpid++),
+ OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
controlSeq.addElement(tagattr);
return bpid;
}
@@ -864,23 +861,23 @@ public class CMCOutputTemplate {
OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL, new INTEGER(OtherInfo.BAD_MESSAGE_CHECK), null);
SEQUENCE failed_bpids = new SEQUENCE();
failed_bpids.addElement(attrbpid);
- cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED, failed_bpids, (String)null, otherInfo);
+ cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED, failed_bpids, (String) null, otherInfo);
tagattr = new TaggedAttribute(
- new INTEGER(bpid++),
- OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
+ new INTEGER(bpid++),
+ OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
controlSeq.addElement(tagattr);
return bpid;
}
- }
+ }
if (revoke) {
- ICertificateAuthority ca = (ICertificateAuthority)CMS.getSubsystem("ca");
- ICertificateRepository repository = (ICertificateRepository)ca.getCertificateRepository();
+ ICertificateAuthority ca = (ICertificateAuthority) CMS.getSubsystem("ca");
+ ICertificateRepository repository = (ICertificateRepository) ca.getCertificateRepository();
ICertRecord record = null;
try {
record = repository.readCertificateRecord(revokeSerial);
} catch (EBaseException ee) {
- CMS.debug("CMCOutputTemplate: Exception: "+ee.toString());
+ CMS.debug("CMCOutputTemplate: Exception: " + ee.toString());
}
if (record == null) {
@@ -888,10 +885,10 @@ public class CMCOutputTemplate {
OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL, new INTEGER(OtherInfo.BAD_CERT_ID), null);
SEQUENCE failed_bpids = new SEQUENCE();
failed_bpids.addElement(attrbpid);
- cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED, failed_bpids, (String)null, otherInfo);
+ cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED, failed_bpids, (String) null, otherInfo);
tagattr = new TaggedAttribute(
- new INTEGER(bpid++),
- OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
+ new INTEGER(bpid++),
+ OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
controlSeq.addElement(tagattr);
return bpid;
}
@@ -901,10 +898,10 @@ public class CMCOutputTemplate {
SEQUENCE success_bpids = new SEQUENCE();
success_bpids.addElement(attrbpid);
cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.SUCCESS,
- success_bpids, (String)null, null);
+ success_bpids, (String) null, null);
tagattr = new TaggedAttribute(
- new INTEGER(bpid++),
- OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
+ new INTEGER(bpid++),
+ OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
controlSeq.addElement(tagattr);
return bpid;
}
@@ -928,7 +925,7 @@ public class CMCOutputTemplate {
RevokedCertImpl revCertImpl = new RevokedCertImpl(impl.getSerialNumber(), CMS.getCurrentDate(), entryExtn);
RevokedCertImpl[] revCertImpls = new RevokedCertImpl[1];
revCertImpls[0] = revCertImpl;
- IRequestQueue queue = ca.getRequestQueue();
+ IRequestQueue queue = ca.getRequestQueue();
IRequest revReq = queue.newRequest(IRequest.REVOCATION_REQUEST);
revReq.setExtData(IRequest.CERT_INFO, revCertImpls);
revReq.setExtData(IRequest.REVOKED_REASON,
@@ -941,17 +938,17 @@ public class CMCOutputTemplate {
RequestStatus stat = revReq.getRequestStatus();
if (stat == RequestStatus.COMPLETE) {
Integer result = revReq.getExtDataInInteger(IRequest.RESULT);
- CMS.debug("CMCOutputTemplate: revReq result = "+result);
+ CMS.debug("CMCOutputTemplate: revReq result = " + result);
if (result.equals(IRequest.RES_ERROR)) {
CMS.debug("CMCOutputTemplate: revReq exception: " +
revReq.getExtDataInString(IRequest.ERROR));
OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL, new INTEGER(OtherInfo.BAD_REQUEST), null);
SEQUENCE failed_bpids = new SEQUENCE();
failed_bpids.addElement(attrbpid);
- cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED, failed_bpids, (String)null, otherInfo);
+ cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED, failed_bpids, (String) null, otherInfo);
tagattr = new TaggedAttribute(
- new INTEGER(bpid++),
- OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
+ new INTEGER(bpid++),
+ OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
controlSeq.addElement(tagattr);
return bpid;
}
@@ -960,36 +957,36 @@ public class CMCOutputTemplate {
ILogger logger = CMS.getLogger();
String initiative = AuditFormat.FROMUSER;
logger.log(ILogger.EV_AUDIT, ILogger.S_OTHER, AuditFormat.LEVEL,
- AuditFormat.DOREVOKEFORMAT, new Object[] {
- revReq.getRequestId(), initiative, "completed",
- impl.getSubjectDN(),
- impl.getSerialNumber().toString(16),
- reason.toString()});
+ AuditFormat.DOREVOKEFORMAT, new Object[] {
+ revReq.getRequestId(), initiative, "completed",
+ impl.getSubjectDN(),
+ impl.getSerialNumber().toString(16),
+ reason.toString() });
CMS.debug("CMCOutputTemplate: Certificate get revoked.");
SEQUENCE success_bpids = new SEQUENCE();
success_bpids.addElement(attrbpid);
cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.SUCCESS,
- success_bpids, (String)null, null);
+ success_bpids, (String) null, null);
tagattr = new TaggedAttribute(
- new INTEGER(bpid++),
- OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
+ new INTEGER(bpid++),
+ OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
controlSeq.addElement(tagattr);
return bpid;
} else {
OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL, new INTEGER(OtherInfo.BAD_MESSAGE_CHECK), null);
SEQUENCE failed_bpids = new SEQUENCE();
failed_bpids.addElement(attrbpid);
- cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED, failed_bpids, (String)null, otherInfo);
+ cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED, failed_bpids, (String) null, otherInfo);
tagattr = new TaggedAttribute(
- new INTEGER(bpid++),
- OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
+ new INTEGER(bpid++),
+ OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
controlSeq.addElement(tagattr);
return bpid;
}
}
}
- return bpid;
+ return bpid;
}
private RevocationReason toRevocationReason(ENUMERATED n) {
@@ -998,7 +995,7 @@ public class CMCOutputTemplate {
return RevocationReason.UNSPECIFIED;
else if (code == RevRequest.affiliationChanged.getValue())
return RevocationReason.AFFILIATION_CHANGED;
- else if (code == RevRequest.cACompromise.getValue())
+ else if (code == RevRequest.cACompromise.getValue())
return RevocationReason.CA_COMPROMISE;
else if (code == RevRequest.certificateHold.getValue())
return RevocationReason.CERTIFICATE_HOLD;
@@ -1022,33 +1019,33 @@ public class CMCOutputTemplate {
EncapsulatedContentInfo ci = msgData.getContentInfo();
OCTET_STRING content = ci.getContent();
ByteArrayInputStream s = new ByteArrayInputStream(content.toByteArray());
- TaggedAttribute tattr = (TaggedAttribute)(new TaggedAttribute.Template()).decode(s);
+ TaggedAttribute tattr = (TaggedAttribute) (new TaggedAttribute.Template()).decode(s);
SET values = tattr.getValues();
RevRequest revRequest = null;
if (values != null && values.size() > 0)
revRequest =
- (RevRequest)(ASN1Util.decode(new RevRequest.Template(),
- ASN1Util.encode(values.elementAt(0))));
+ (RevRequest) (ASN1Util.decode(new RevRequest.Template(),
+ ASN1Util.encode(values.elementAt(0))));
SET dias = msgData.getDigestAlgorithmIdentifiers();
int numDig = dias.size();
Hashtable<String, byte[]> digs = new Hashtable<String, byte[]>();
- for (int i=0; i<numDig; i++) {
+ for (int i = 0; i < numDig; i++) {
AlgorithmIdentifier dai =
- (AlgorithmIdentifier) dias.elementAt(i);
+ (AlgorithmIdentifier) dias.elementAt(i);
String name =
- DigestAlgorithm.fromOID(dai.getOID()).toString();
+ DigestAlgorithm.fromOID(dai.getOID()).toString();
MessageDigest md =
- MessageDigest.getInstance(name);
+ MessageDigest.getInstance(name);
byte[] digest = md.digest(content.toByteArray());
digs.put(name, digest);
}
SET sis = msgData.getSignerInfos();
- int numSis = sis.size();
- for (int i=0; i<numSis; i++) {
+ int numSis = sis.size();
+ for (int i = 0; i < numSis; i++) {
org.mozilla.jss.pkix.cms.SignerInfo si =
- (org.mozilla.jss.pkix.cms.SignerInfo)sis.elementAt(i);
+ (org.mozilla.jss.pkix.cms.SignerInfo) sis.elementAt(i);
String name = si.getDigestAlgorithm().toString();
byte[] digest = digs.get(name);
if (digest == null) {
@@ -1060,21 +1057,21 @@ public class CMCOutputTemplate {
SignerIdentifier sid = si.getSignerIdentifier();
if (sid.getType().equals(SignerIdentifier.ISSUER_AND_SERIALNUMBER)) {
org.mozilla.jss.pkix.cms.IssuerAndSerialNumber issuerAndSerialNumber =
- sid.getIssuerAndSerialNumber();
+ sid.getIssuerAndSerialNumber();
java.security.cert.X509Certificate cert = null;
if (msgData.hasCertificates()) {
SET certs = msgData.getCertificates();
int numCerts = certs.size();
- for (int j=0; j<numCerts; j++) {
+ for (int j = 0; j < numCerts; j++) {
org.mozilla.jss.pkix.cert.Certificate certJss =
- (Certificate) certs.elementAt(j);
- org.mozilla.jss.pkix.cert.CertificateInfo certI =
- certJss.getInfo();
+ (Certificate) certs.elementAt(j);
+ org.mozilla.jss.pkix.cert.CertificateInfo certI =
+ certJss.getInfo();
Name issuer = certI.getIssuer();
byte[] issuerB = ASN1Util.encode(issuer);
INTEGER sn = certI.getSerialNumber();
if (new String(issuerB).equalsIgnoreCase(new String(ASN1Util.encode(issuerAndSerialNumber.getIssuer()))) &&
- sn.toString().equals(issuerAndSerialNumber.getSerialNumber().toString())) {
+ sn.toString().equals(issuerAndSerialNumber.getSerialNumber().toString())) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
certJss.encode(os);
cert = new X509CertImpl(os.toByteArray());
@@ -1082,23 +1079,23 @@ public class CMCOutputTemplate {
}
}
}
-
+
if (cert != null) {
PublicKey pbKey = cert.getPublicKey();
- String type = ((X509Key)pbKey).getAlgorithm();
+ String type = ((X509Key) pbKey).getAlgorithm();
PrivateKey.Type kType = PrivateKey.RSA;
if (type.equals("DSA"))
kType = PrivateKey.DSA;
- PK11PubKey pubK = PK11PubKey.fromRaw(kType, ((X509Key)pbKey).getKey());
+ PK11PubKey pubK = PK11PubKey.fromRaw(kType, ((X509Key) pbKey).getKey());
si.verify(digest, ci.getContentType(), pubK);
return true;
}
- }
- }
-
+ }
+ }
+
return false;
} catch (Exception e) {
- CMS.debug("CMCOutputTemplate: verifyRevRequestSignature. Exception: "+e.toString());
+ CMS.debug("CMCOutputTemplate: verifyRevRequestSignature. Exception: " + e.toString());
return false;
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/common/CMSFile.java b/pki/base/common/src/com/netscape/cms/servlet/common/CMSFile.java
index 7f89297c..4d7c4cdd 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/common/CMSFile.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/common/CMSFile.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.common;
-
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
@@ -27,10 +26,9 @@ import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.logging.ILogger;
-
/**
* CMSFile represents a file from the filesystem cached in memory
- *
+ *
* @version $Revision$, $Date$
*/
public class CMSFile {
diff --git a/pki/base/common/src/com/netscape/cms/servlet/common/CMSFileLoader.java b/pki/base/common/src/com/netscape/cms/servlet/common/CMSFileLoader.java
index bf4c3cf6..1d1d3479 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/common/CMSFileLoader.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/common/CMSFileLoader.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.common;
-
import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
@@ -26,10 +25,9 @@ import java.util.Hashtable;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
-
/**
* CMSFileLoader - file cache.
- *
+ *
* @version $Revision$, $Date$
*/
@@ -45,14 +43,14 @@ public class CMSFileLoader {
// property to cache templates only
public final String PROP_CACHE_TEMPLATES_ONLY = "cacheTemplatesOnly";
- // hash of files to their content.
+ // hash of files to their content.
private Hashtable mLoadedFiles = new Hashtable();
- // max number of files
+ // max number of files
private int mMaxSize = MAX_SIZE;
// number of files to clear when max is reached.
- private int mClearSize = CLEAR_SIZE;
+ private int mClearSize = CLEAR_SIZE;
// whether to cache templates and forms only.
private boolean mCacheTemplatesOnly = true;
@@ -63,15 +61,15 @@ public class CMSFileLoader {
public void init(IConfigStore config) throws EBaseException {
mMaxSize = config.getInteger(PROP_MAX_SIZE, MAX_SIZE);
mClearSize = config.getInteger(PROP_CLEAR_SIZE, CLEAR_SIZE);
- mCacheTemplatesOnly =
+ mCacheTemplatesOnly =
config.getBoolean(PROP_CACHE_TEMPLATES_ONLY, true);
}
// Changed by bskim
- //public byte[] get(String absPath) throws EBaseException, IOException {
- // File file = new File(absPath);
- // return get(file);
- //}
+ // public byte[] get(String absPath) throws EBaseException, IOException {
+ // File file = new File(absPath);
+ // return get(file);
+ // }
public byte[] get(String absPath, String enc) throws EBaseException, IOException {
File file = new File(absPath);
@@ -81,19 +79,19 @@ public class CMSFileLoader {
// Change end
// Changed by bskim
- //public byte[] get(File file) throws EBaseException, IOException {
- // CMSFile cmsFile = getCMSFile(file);
+ // public byte[] get(File file) throws EBaseException, IOException {
+ // CMSFile cmsFile = getCMSFile(file);
public byte[] get(File file, String enc) throws EBaseException, IOException {
CMSFile cmsFile = getCMSFile(file, enc);
- // Change end
+ // Change end
return cmsFile.getContent();
}
// Changed by bskim
- //public CMSFile getCMSFile(File file) throws EBaseException, IOException {
+ // public CMSFile getCMSFile(File file) throws EBaseException, IOException {
public CMSFile getCMSFile(File file, String enc) throws EBaseException, IOException {
- // Change end
+ // Change end
String absPath = file.getAbsolutePath();
long modified = file.lastModified();
CMSFile cmsFile = (CMSFile) mLoadedFiles.get(absPath);
@@ -102,8 +100,8 @@ public class CMSFileLoader {
// new file.
if (cmsFile == null || modified != lastModified) {
// Changed by bskim
- //cmsFile = updateFile(absPath, file);
- cmsFile = updateFile(absPath, file, enc);
+ // cmsFile = updateFile(absPath, file);
+ cmsFile = updateFile(absPath, file, enc);
// Change end
}
cmsFile.setLastAccess(System.currentTimeMillis());
@@ -111,10 +109,10 @@ public class CMSFileLoader {
}
// Changed by bskim
- //private CMSFile updateFile(String absPath, File file)
- private CMSFile updateFile(String absPath, File file, String enc)
- // Change end
- throws EBaseException, IOException {
+ // private CMSFile updateFile(String absPath, File file)
+ private CMSFile updateFile(String absPath, File file, String enc)
+ // Change end
+ throws EBaseException, IOException {
// clear if cache size exceeded.
if (mLoadedFiles.size() >= mMaxSize) {
clearSomeFiles();
@@ -125,24 +123,24 @@ public class CMSFileLoader {
// check if file is a js template or plain template by its first String
if (absPath.endsWith(CMSTemplate.SUFFIX)) {
// Changed by bskim
- //cmsFile = new CMSTemplate(file);
+ // cmsFile = new CMSTemplate(file);
cmsFile = new CMSTemplate(file, enc);
// End of Change
} else {
cmsFile = new CMSFile(file);
}
- mLoadedFiles.put(absPath, cmsFile); // replace old one if any.
+ mLoadedFiles.put(absPath, cmsFile); // replace old one if any.
return cmsFile;
}
private synchronized void clearSomeFiles() {
// recheck this in case some other thread has cleared it.
- if (mLoadedFiles.size() < mMaxSize)
+ if (mLoadedFiles.size() < mMaxSize)
return;
- // remove the LRU files.
- // XXX could be optimized more.
+ // remove the LRU files.
+ // XXX could be optimized more.
Enumeration elements = mLoadedFiles.elements();
for (int i = mClearSize; i > 0; i--) {
@@ -160,4 +158,3 @@ public class CMSFileLoader {
}
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/common/CMSGWResources.java b/pki/base/common/src/com/netscape/cms/servlet/common/CMSGWResources.java
index a76b1c75..c3854935 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/common/CMSGWResources.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/common/CMSGWResources.java
@@ -17,14 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.common;
-
import java.util.ListResourceBundle;
-
/**
* A class represents a resource bundle for cms gateway.
* <P>
- *
+ *
* @version $Revision$, $Date$
* @see java.util.ListResourceBundle
*/
@@ -38,8 +36,7 @@ public class CMSGWResources extends ListResourceBundle {
}
/*
- * Constants. The suffix represents the number of
- * possible parameters.
+ * Constants. The suffix represents the number of possible parameters.
*/
static final Object[][] contents = {};
diff --git a/pki/base/common/src/com/netscape/cms/servlet/common/CMSGateway.java b/pki/base/common/src/com/netscape/cms/servlet/common/CMSGateway.java
index b5c6e3c7..8fa9471e 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/common/CMSGateway.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/common/CMSGateway.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.common;
-
import java.io.File;
import java.io.IOException;
import java.security.cert.X509Certificate;
@@ -41,10 +40,9 @@ import com.netscape.certsrv.base.IArgBlock;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.logging.ILogger;
-
/**
* This class is to hold some general method for servlets.
- *
+ *
* @version $Revision$, $Date$
*/
public class CMSGateway {
@@ -52,8 +50,8 @@ public class CMSGateway {
private final static String PROP_ENABLE_ADMIN_ENROLL = "enableAdminEnroll";
private final static String PROP_SERVER_XML = "server.xml";
- public static final String CERT_ATTR =
- "javax.servlet.request.X509Certificate";
+ public static final String CERT_ATTR =
+ "javax.servlet.request.X509Certificate";
protected static CMSFileLoader mFileLoader = new CMSFileLoader();
@@ -68,11 +66,11 @@ public class CMSGateway {
mEnableFileServing = true;
mConfig = CMS.getConfigStore().getSubStore(PROP_CMSGATEWAY);
try {
- mEnableAdminEnroll =
+ mEnableAdminEnroll =
mConfig.getBoolean(PROP_ENABLE_ADMIN_ENROLL, false);
} catch (EBaseException e) {
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_BAD_CONFIG_PARAM"));
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_BAD_CONFIG_PARAM"));
}
}
@@ -88,7 +86,7 @@ public class CMSGateway {
httpReqHash.put(name, req.getParameter(name));
}
-
+
String ip = req.getRemoteAddr();
if (ip != null)
httpReqHash.put("clientHost", ip);
@@ -99,11 +97,11 @@ public class CMSGateway {
return mEnableAdminEnroll;
}
- public static void setEnableAdminEnroll(boolean enableAdminEnroll)
- throws EBaseException {
+ public static void setEnableAdminEnroll(boolean enableAdminEnroll)
+ throws EBaseException {
IConfigStore mainConfig = CMS.getConfigStore();
- //!!! Is it thread safe? xxxx
+ // !!! Is it thread safe? xxxx
mEnableAdminEnroll = enableAdminEnroll;
mConfig.putBoolean(PROP_ENABLE_ADMIN_ENROLL, enableAdminEnroll);
mainConfig.commit(true);
@@ -112,9 +110,9 @@ public class CMSGateway {
public static void disableAdminEnroll() throws EBaseException {
setEnableAdminEnroll(false);
- /* need to do this in web.xml and restart ws
- removeServlet("/ca/adminEnroll", "AdminEnroll");
- initGateway();
+ /*
+ * need to do this in web.xml and restart ws
+ * removeServlet("/ca/adminEnroll", "AdminEnroll"); initGateway();
*/
}
@@ -123,14 +121,14 @@ public class CMSGateway {
* manager.
*/
public static AuthCredentials getAuthCreds(
- IAuthManager authMgr, IArgBlock argBlock, X509Certificate clientCert)
- throws EBaseException {
+ IAuthManager authMgr, IArgBlock argBlock, X509Certificate clientCert)
+ throws EBaseException {
// get credentials from http parameters.
if (authMgr == null)
- return null;
+ return null;
String[] reqCreds = authMgr.getRequiredCreds();
AuthCredentials creds = new AuthCredentials();
-
+
if (clientCert instanceof java.security.cert.X509Certificate) {
try {
clientCert = new netscape.security.x509.X509CertImpl(clientCert.getEncoded());
@@ -144,8 +142,8 @@ public class CMSGateway {
if (reqCred.equals(IAuthManager.CRED_SSL_CLIENT_CERT)) {
// cert could be null;
- creds.set(reqCred, new X509Certificate[] { clientCert}
- );
+ creds.set(reqCred, new X509Certificate[] { clientCert }
+ );
} else {
String value = argBlock.getValueAsString(reqCred);
@@ -163,9 +161,9 @@ public class CMSGateway {
protected final static String AUTHMGR_PARAM = "authenticator";
public static AuthToken checkAuthManager(
- HttpServletRequest httpReq, IArgBlock httpParams,
- X509Certificate cert, String authMgrName)
- throws EBaseException {
+ HttpServletRequest httpReq, IArgBlock httpParams,
+ X509Certificate cert, String authMgrName)
+ throws EBaseException {
IArgBlock httpArgs = httpParams;
if (httpArgs == null)
@@ -181,43 +179,43 @@ public class CMSGateway {
}
if (authMgrName == null || authMgrName.length() == 0) {
- throw new EBaseException(CMS.getLogMessage("BASE_INTERNAL_ERROR_1",
+ throw new EBaseException(CMS.getLogMessage("BASE_INTERNAL_ERROR_1",
CMS.getLogMessage("CMSGW_AUTH_MAN_EXPECTED")));
}
-
- IAuthManager authMgr =
- authSub.getAuthManager(IAuthSubsystem.CERTUSERDB_AUTHMGR_ID);
+
+ IAuthManager authMgr =
+ authSub.getAuthManager(IAuthSubsystem.CERTUSERDB_AUTHMGR_ID);
authMgr = authSub.getAuthManager(authMgrName);
if (authMgr == null)
return null;
- IAuthCredentials creds =
- getAuthCreds(authMgr, CMS.createArgBlock(toHashtable(httpReq)), cert);
+ IAuthCredentials creds =
+ getAuthCreds(authMgr, CMS.createArgBlock(toHashtable(httpReq)), cert);
AuthToken authToken = null;
try {
- authToken = (AuthToken) authMgr.authenticate(creds);
+ authToken = (AuthToken) authMgr.authenticate(creds);
} catch (EBaseException e) {
throw e;
} catch (Exception e) {
CMS.debug("CMSGateway: " + e);
// catch all errors from authentication manager.
- throw new ECMSGWException(CMS.getLogMessage("CMSGW_AUTH_ERROR_2",
+ throw new ECMSGWException(CMS.getLogMessage("CMSGW_AUTH_ERROR_2",
e.toString(), e.getMessage()));
}
return authToken;
}
public static void renderTemplate(
- String templateName,
- HttpServletRequest req,
- HttpServletResponse resp,
- ServletConfig servletConfig,
- CMSFileLoader fileLoader)
- throws EBaseException, IOException {
- CMSTemplate template =
- getTemplate(templateName, req,
- servletConfig, fileLoader, new Locale[1]);
+ String templateName,
+ HttpServletRequest req,
+ HttpServletResponse resp,
+ ServletConfig servletConfig,
+ CMSFileLoader fileLoader)
+ throws EBaseException, IOException {
+ CMSTemplate template =
+ getTemplate(templateName, req,
+ servletConfig, fileLoader, new Locale[1]);
ServletOutputStream out = resp.getOutputStream();
template.renderOutput(out, new CMSTemplateParams(null, null));
@@ -240,8 +238,8 @@ public class CMSGateway {
* @param locale array of at least one to be filled with locale found.
*/
public static File getLangFile(
- HttpServletRequest req, File realpathFile, Locale[] locale)
- throws IOException {
+ HttpServletRequest req, File realpathFile, Locale[] locale)
+ throws IOException {
File file = null;
String acceptLang = req.getHeader("accept-language");
@@ -258,7 +256,7 @@ public class CMSGateway {
}
String name = realpathFile.getName();
- if (name == null) { // filename should never be null.
+ if (name == null) { // filename should never be null.
throw new IOException("file has no name");
}
int i;
@@ -287,8 +285,8 @@ public class CMSGateway {
}
String langfilepath =
- parent + File.separatorChar +
- lang + File.separatorChar + name;
+ parent + File.separatorChar +
+ lang + File.separatorChar + name;
file = new File(langfilepath);
if (file.exists()) {
@@ -311,54 +309,54 @@ public class CMSGateway {
}
/**
- * get a template
+ * get a template
*/
protected static CMSTemplate getTemplate(
- String templateName,
- HttpServletRequest httpReq,
- ServletConfig servletConfig,
- CMSFileLoader fileLoader,
- Locale[] locale)
- throws EBaseException, IOException {
+ String templateName,
+ HttpServletRequest httpReq,
+ ServletConfig servletConfig,
+ CMSFileLoader fileLoader,
+ Locale[] locale)
+ throws EBaseException, IOException {
// this converts to system dependent file seperator char.
if (servletConfig == null) {
- CMS.debug( "CMSGateway:getTemplate() - servletConfig is null!" );
+ CMS.debug("CMSGateway:getTemplate() - servletConfig is null!");
return null;
}
if (servletConfig.getServletContext() == null) {
}
if (templateName == null) {
}
- String realpath =
- servletConfig.getServletContext().getRealPath("/" + templateName);
+ String realpath =
+ servletConfig.getServletContext().getRealPath("/" + templateName);
File realpathFile = new File(realpath);
- File templateFile =
- getLangFile(httpReq, realpathFile, locale);
- CMSTemplate template =
- //(CMSTemplate)fileLoader.getCMSFile(templateFile);
- (CMSTemplate) fileLoader.getCMSFile(templateFile, httpReq.getCharacterEncoding());
+ File templateFile =
+ getLangFile(httpReq, realpathFile, locale);
+ CMSTemplate template =
+ // (CMSTemplate)fileLoader.getCMSFile(templateFile);
+ (CMSTemplate) fileLoader.getCMSFile(templateFile, httpReq.getCharacterEncoding());
return template;
}
/**
- * Get the If-Modified-Since header and compare it to the millisecond
- * epoch value passed in. If there is no header, or there is a problem
- * parsing the value, or if the file has been modified this will return
- * true, indicating the file has changed.
- *
+ * Get the If-Modified-Since header and compare it to the millisecond epoch
+ * value passed in. If there is no header, or there is a problem parsing the
+ * value, or if the file has been modified this will return true, indicating
+ * the file has changed.
+ *
* @param lastModified The time value in milliseconds past the epoch to
- * compare the If-Modified-Since header to.
+ * compare the If-Modified-Since header to.
*/
public static boolean modifiedSince(HttpServletRequest req, long lastModified) {
long ifModSinceStr;
try {
ifModSinceStr = req.getDateHeader("If-Modified-Since");
- }catch (IllegalArgumentException e) {
+ } catch (IllegalArgumentException e) {
return true;
}
-
+
if (ifModSinceStr < 0) {
return true;
}
@@ -371,4 +369,3 @@ public class CMSGateway {
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/common/CMSLoadTemplate.java b/pki/base/common/src/com/netscape/cms/servlet/common/CMSLoadTemplate.java
index ca5abf03..62276df1 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/common/CMSLoadTemplate.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/common/CMSLoadTemplate.java
@@ -17,12 +17,9 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.common;
-
-
-
/**
- * handy class containing cms templates to load & fill.
- *
+ * handy class containing cms templates to load & fill.
+ *
* @version $Revision$, $Date$
*/
public class CMSLoadTemplate {
@@ -35,9 +32,9 @@ public class CMSLoadTemplate {
}
public CMSLoadTemplate(
- String propName, String fillerPropName,
- String templateName, ICMSTemplateFiller filler) {
-
+ String propName, String fillerPropName,
+ String templateName, ICMSTemplateFiller filler) {
+
mPropName = propName;
mFillerPropName = fillerPropName;
mTemplateName = templateName;
diff --git a/pki/base/common/src/com/netscape/cms/servlet/common/CMSRequest.java b/pki/base/common/src/com/netscape/cms/servlet/common/CMSRequest.java
index 27f1d3a5..53f9ac22 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/common/CMSRequest.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/common/CMSRequest.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.common;
-
import java.util.Hashtable;
import java.util.Vector;
@@ -35,7 +34,7 @@ import com.netscape.certsrv.request.RequestStatus;
/**
* This represents a user request.
- *
+ *
* @version $Revision$, $Date$
*/
public class CMSRequest {
@@ -46,7 +45,8 @@ public class CMSRequest {
public static final Integer SVC_PENDING = Integer.valueOf(4);
public static final Integer REJECTED = Integer.valueOf(5);
public static final Integer ERROR = Integer.valueOf(6);
- public static final Integer EXCEPTION = Integer.valueOf(7); // unexpected error.
+ public static final Integer EXCEPTION = Integer.valueOf(7); // unexpected
+ // error.
private static final String RESULT = "cmsRequestResult";
@@ -59,7 +59,7 @@ public class CMSRequest {
// http headers & other info.
private HttpServletRequest mHttpReq = null;
- // http response.
+ // http response.
private HttpServletResponse mHttpResp = null;
// http servlet config.
@@ -68,11 +68,11 @@ public class CMSRequest {
// http servlet context.
private ServletContext mServletContext = null;
- // permanent request in request queue.
+ // permanent request in request queue.
private IRequest mRequest = null;
// whether request processed successfully
- private Integer mStatus = SUCCESS;
+ private Integer mStatus = SUCCESS;
// exception message containing error that occured.
// note exception could also be thrown seperately.
@@ -85,13 +85,13 @@ public class CMSRequest {
Object mResult = null;
Hashtable mResults = new Hashtable();
- /**
+ /**
* Constructor
*/
public CMSRequest() {
}
- // set methods use by servlets.
+ // set methods use by servlets.
/**
* set the HTTP parameters
@@ -115,46 +115,46 @@ public class CMSRequest {
}
/**
- * set the HTTP Response object which is used to create the
- * HTTP response which is sent back to the user
+ * set the HTTP Response object which is used to create the HTTP response
+ * which is sent back to the user
*/
public void setHttpResp(HttpServletResponse httpResp) {
mHttpResp = httpResp;
}
/**
- * set the servlet configuration. The servlet configuration is
- * read from the WEB-APPS/web.xml file under the &lt;servlet&gt;
- * XML definition. The parameters are delimited by init-param
- * param-name/param-value options as described in the servlet
- * documentation.
+ * set the servlet configuration. The servlet configuration is read from the
+ * WEB-APPS/web.xml file under the &lt;servlet&gt; XML definition. The
+ * parameters are delimited by init-param param-name/param-value options as
+ * described in the servlet documentation.
*/
public void setServletConfig(ServletConfig servletConfig) {
mServletConfig = servletConfig;
}
- /*
- * set the servlet context. the servletcontext has detail
- * about the currently running request
+ /*
+ * set the servlet context. the servletcontext has detail about the
+ * currently running request
*/
public void setServletContext(ServletContext servletContext) {
mServletContext = servletContext;
}
- /**
- * Set request status.
- * @param status request status. Allowed values are
- * UNAUTHORIZED, SUCCESS, REJECTED, PENDING, ERROR, SVC_PENDING
+ /**
+ * Set request status.
+ *
+ * @param status request status. Allowed values are UNAUTHORIZED, SUCCESS,
+ * REJECTED, PENDING, ERROR, SVC_PENDING
* @throws IllegalArgumentException if status is not one of the above values
*/
public void setStatus(Integer status) {
- if ( !status.equals( UNAUTHORIZED ) &&
- !status.equals( SUCCESS ) &&
- !status.equals( REJECTED ) &&
- !status.equals( PENDING ) &&
- !status.equals( ERROR ) &&
- !status.equals( SVC_PENDING ) &&
- !status.equals( EXCEPTION ) ) {
+ if (!status.equals(UNAUTHORIZED) &&
+ !status.equals(SUCCESS) &&
+ !status.equals(REJECTED) &&
+ !status.equals(PENDING) &&
+ !status.equals(ERROR) &&
+ !status.equals(SVC_PENDING) &&
+ !status.equals(EXCEPTION)) {
throw new IllegalArgumentException(CMS.getLogMessage("CMSGW_BAD_REQ_STATUS"));
}
mStatus = status;
@@ -169,9 +169,9 @@ public class CMSRequest {
}
public void setErrorDescription(String descr) {
- if (mErrorDescr == null)
+ if (mErrorDescr == null)
mErrorDescr = new Vector();
- mErrorDescr.addElement(descr);
+ mErrorDescr.addElement(descr);
}
public void setResult(Object result) {
@@ -235,7 +235,7 @@ public class CMSRequest {
return reason;
}
- // handy routines for IRequest.
+ // handy routines for IRequest.
public void setExtData(String type, String value) {
if (mRequest != null) {
@@ -251,7 +251,7 @@ public class CMSRequest {
}
}
- // policy errors; set on rejection or possibly deferral.
+ // policy errors; set on rejection or possibly deferral.
public Vector getPolicyMessages() {
if (mRequest != null) {
return mRequest.getExtDataInStringVector(IRequest.ERRORS);
@@ -259,13 +259,13 @@ public class CMSRequest {
return null;
}
- /**
- * set default CMS status according to IRequest status.
+ /**
+ * set default CMS status according to IRequest status.
*/
public void setIRequestStatus() throws EBaseException {
if (mRequest == null) {
- EBaseException e =
- new ECMSGWException(CMS.getLogMessage("CMSGW_MISSING_REQUEST"));
+ EBaseException e =
+ new ECMSGWException(CMS.getLogMessage("CMSGW_MISSING_REQUEST"));
throw e;
}
@@ -277,11 +277,11 @@ public class CMSRequest {
mStatus = CMSRequest.SUCCESS;
return;
}
- // unexpected resulting request status.
+ // unexpected resulting request status.
if (status == RequestStatus.REJECTED) {
mStatus = CMSRequest.REJECTED;
return;
- } // pending or service pending.
+ } // pending or service pending.
else if (status == RequestStatus.PENDING) {
mStatus = CMSRequest.PENDING;
return;
@@ -292,8 +292,8 @@ public class CMSRequest {
RequestId reqId = mRequest.getRequestId();
throw new ECMSGWException(
- CMS.getLogMessage("CMSGW_UNEXPECTED_REQUEST_STATUS_2",
- status.toString(), reqId.toString()));
+ CMS.getLogMessage("CMSGW_UNEXPECTED_REQUEST_STATUS_2",
+ status.toString(), reqId.toString()));
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/common/CMSTemplate.java b/pki/base/common/src/com/netscape/cms/servlet/common/CMSTemplate.java
index b90278fa..748b769e 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/common/CMSTemplate.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/common/CMSTemplate.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.common;
-
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
@@ -39,23 +38,21 @@ import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IArgBlock;
import com.netscape.certsrv.logging.ILogger;
-
/**
- * File templates. This implementation will take
- * an HTML file with a special customer tag
- * &lt;CMS_TEMPLATE&gt; and replace the tag with
- * a series of javascript variable definitions
- * (depending on the servlet)
- *
+ * File templates. This implementation will take an HTML file with a special
+ * customer tag &lt;CMS_TEMPLATE&gt; and replace the tag with a series of
+ * javascript variable definitions (depending on the servlet)
+ *
* @version $Revision$, $Date$
*/
public class CMSTemplate extends CMSFile {
public static final String SUFFIX = ".template";
- /*==========================================================
- * variables
- *==========================================================*/
+ /*
+ * ========================================================== variables
+ * ==========================================================
+ */
/* private variables */
private String mTemplateFileName = "";
@@ -68,19 +65,21 @@ public class CMSTemplate extends CMSFile {
public static final String TEMPLATE_TAG = "<CMS_TEMPLATE>";
/* Character set for i18n */
-
+
/* Will be set by CMSServlet.getTemplate() */
private String mCharset = null;
- /*==========================================================
- * constructors
- *==========================================================*/
+ /*
+ * ========================================================== constructors
+ * ==========================================================
+ */
/**
* Constructor
+ *
* @param file template file to load
* @param charset character set
- * @throws IOException if the there was an error opening the file
+ * @throws IOException if the there was an error opening the file
*/
public CMSTemplate(File file, String charset) throws IOException, EBaseException {
mCharset = charset;
@@ -89,8 +88,8 @@ public class CMSTemplate extends CMSFile {
try {
init(file);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_CANT_LOAD_TEMPLATE", mAbsPath, e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_CANT_LOAD_TEMPLATE", mAbsPath, e.toString()));
throw new ECMSGWException(
CMS.getLogMessage("CMSGW_ERROR_LOADING_TEMPLATE"));
}
@@ -99,16 +98,17 @@ public class CMSTemplate extends CMSFile {
mContent = content.getBytes(mCharset);
}
- /*==========================================================
- * public methods
- *==========================================================*/
+ /*
+ * ========================================================== public methods
+ * ==========================================================
+ */
/* *
- * Load the form from the file and setup the
- * pre/post output buffer if it is a template
- * file. Otherwise, only post output buffer is
- * filled.
+ * Load the form from the file and setup the pre/post output buffer if it is
+ * a template file. Otherwise, only post output buffer is filled.
+ *
* @param template the template file to load
+ *
* @return true if successful
*/
public boolean init(File template) throws EBaseException, IOException {
@@ -128,8 +128,9 @@ public class CMSTemplate extends CMSFile {
mTimeStamp = now.getTime();
- /* if template file, find template tag substring and set
- * pre/post output string
+ /*
+ * if template file, find template tag substring and set pre/post output
+ * string
*/
int location = content.indexOf(TEMPLATE_TAG);
@@ -137,8 +138,8 @@ public class CMSTemplate extends CMSFile {
log(ILogger.LL_FAILURE, CMS.getLogMessage(
"CMSGW_TEMPLATE_MISSING", mAbsPath, TEMPLATE_TAG));
throw new ECMSGWException(
- CMS.getLogMessage("CMSGW_MISSING_TEMPLATE_TAG_2",
- TEMPLATE_TAG, mAbsPath));
+ CMS.getLogMessage("CMSGW_MISSING_TEMPLATE_TAG_2",
+ TEMPLATE_TAG, mAbsPath));
}
mPreOutput = content.substring(0, location);
mPostOutput = content.substring(TEMPLATE_TAG.length() + location);
@@ -146,16 +147,17 @@ public class CMSTemplate extends CMSFile {
return true;
}
- /**
- * Write a javascript representation of 'input'
- * surrounded by SCRIPT tags to the outputstream
+ /**
+ * Write a javascript representation of 'input' surrounded by SCRIPT tags to
+ * the outputstream
+ *
* @param rout the outputstream to write to
* @param input the parameters to write
*/
public void renderOutput(OutputStream rout, CMSTemplateParams input)
- throws IOException {
+ throws IOException {
Enumeration<String> e = null;
- Enumeration<IArgBlock> q = null;
+ Enumeration<IArgBlock> q = null;
IArgBlock r = null;
boolean headerBlock = false, fixedBlock = false, queryBlock = false;
CMSTemplateParams data = (CMSTemplateParams) input;
@@ -165,7 +167,7 @@ public class CMSTemplate extends CMSFile {
http_out = new HTTPOutputStreamWriter(rout);
else
http_out = new HTTPOutputStreamWriter(rout, mCharset);
-
+
try {
templateLine out = new templateLine();
@@ -179,7 +181,7 @@ public class CMSTemplate extends CMSFile {
out.println("var recordSet = new Array;");
out.println("var result = new Object();");
- // hack
+ // hack
out.println("var httpParamsCount = 0;");
out.println("var httpHeadersCount = 0;");
out.println("var authTokenCount = 0;");
@@ -194,7 +196,7 @@ public class CMSTemplate extends CMSFile {
e = r.elements();
while (e.hasMoreElements()) {
headerBlock = true;
- String n = e.nextElement();
+ String n = e.nextElement();
Object v = r.getValue(n);
out.println("header." + n + " = " + renderValue(v) + ";");
@@ -228,7 +230,7 @@ public class CMSTemplate extends CMSFile {
out.println("record.SERVER_ATTRS = new Array;");
// Get a query record
- r = q.nextElement();
+ r = q.nextElement();
e = r.elements();
while (e.hasMoreElements()) {
String n = e.nextElement();
@@ -241,11 +243,11 @@ public class CMSTemplate extends CMSFile {
out.println("record.recordSet = recordSet;");
}
- //if (headerBlock)
+ // if (headerBlock)
out.println("result.header = header;");
- //if (fixedBlock)
+ // if (fixedBlock)
out.println("result.fixed = fixed;");
- //if (queryBlock)
+ // if (queryBlock)
out.println("result.recordSet = recordSet;");
out.println("</SCRIPT>");
out.println(mPostOutput);
@@ -257,15 +259,14 @@ public class CMSTemplate extends CMSFile {
}
/**
- * Ouput the pre-amble HTML Header including
- * the pre-output buffer.
- *
+ * Ouput the pre-amble HTML Header including the pre-output buffer.
+ *
* @param out output stream specified
* @return success or error
*/
public boolean outputProlog(PrintWriter out) {
- //Debug.trace("FormCache:outputProlog");
+ // Debug.trace("FormCache:outputProlog");
/* output pre-output buffer */
out.print(mPreOutput);
@@ -279,9 +280,8 @@ public class CMSTemplate extends CMSFile {
}
/**
- * Output the post HTML tags and post-output
- * buffer.
- *
+ * Output the post HTML tags and post-output buffer.
+ *
* @param out output stream specified
* @return success or error
*/
@@ -300,11 +300,12 @@ public class CMSTemplate extends CMSFile {
return mAbsPath;
}
- // inherit getabspath, getContent, get last access and set last access
+ // inherit getabspath, getContent, get last access and set last access
- /*==========================================================
- * private methods
- *==========================================================*/
+ /*
+ * ========================================================== private
+ * methods==========================================================
+ */
/* load file into string */
private String loadFile(File template) throws IOException {
@@ -313,7 +314,8 @@ public class CMSTemplate extends CMSFile {
/* create input stream, can throw IOException */
FileInputStream inStream = new FileInputStream(template);
- InputStreamReader inReader = new InputStreamReader(inStream, mCharset);;
+ InputStreamReader inReader = new InputStreamReader(inStream, mCharset);
+ ;
BufferedReader in = new BufferedReader(inReader);
StringBuffer buf = new StringBuffer();
String line;
@@ -326,8 +328,8 @@ public class CMSTemplate extends CMSFile {
in.close();
inStream.close();
} catch (IOException e) {
- log(ILogger.LL_WARN,
- CMS.getLogMessage("CMSGW_ERR_CLOSE_TEMPL_FILE", mAbsPath, e.getMessage()));
+ log(ILogger.LL_WARN,
+ CMS.getLogMessage("CMSGW_ERR_CLOSE_TEMPL_FILE", mAbsPath, e.getMessage()));
}
return buf.toString();
}
@@ -354,8 +356,8 @@ public class CMSTemplate extends CMSFile {
}
} else if (v instanceof BigInteger) {
s = ((BigInteger) v).toString(10);
- } else if (v instanceof Character &&
- ((Character) v).equals(Character.valueOf((char) 0))) {
+ } else if (v instanceof Character &&
+ ((Character) v).equals(Character.valueOf((char) 0))) {
s = "null";
} else {
s = "\"" + v.toString() + "\"";
@@ -365,10 +367,10 @@ public class CMSTemplate extends CMSFile {
}
/**
- * Escape the contents of src string in preparation to be enclosed in
- * double quotes as a JavaScript String Literal within an <script>
- * portion of an HTML document.
- * stevep - performance improvements - about 4 times faster than before.
+ * Escape the contents of src string in preparation to be enclosed in double
+ * quotes as a JavaScript String Literal within an <script> portion of an
+ * HTML document. stevep - performance improvements - about 4 times faster
+ * than before.
*/
public static String escapeJavaScriptString(String v) {
int l = v.length();
@@ -381,25 +383,25 @@ public class CMSTemplate extends CMSFile {
for (int i = 0; i < l; i++) {
char c = in[i];
- if ((c > 0x23) && (c!= 0x5c) && (c!= 0x3c) && (c!= 0x3e)) {
+ if ((c > 0x23) && (c != 0x5c) && (c != 0x3c) && (c != 0x3e)) {
out[j++] = c;
continue;
}
- if ((c == 0x5c) && ((i+1)<l) && (in[i+1] == 'n' ||
- in[i+1] == 'r' || in[i+1] == 'f' || in[i+1] == 't' ||
- in[i+1] == '<' || in[i+1] == '>' ||
- in[i+1] == '\"' || in[i+1] == '\'' || in[i+1] == '\\')) {
- if (in[i+1] == 'x' && ((i+3)<l) && in[i+2] == '3' &&
- (in[i+3] == 'c' || in[i+3] == 'e')) {
+ if ((c == 0x5c) && ((i + 1) < l) && (in[i + 1] == 'n' ||
+ in[i + 1] == 'r' || in[i + 1] == 'f' || in[i + 1] == 't' ||
+ in[i + 1] == '<' || in[i + 1] == '>' ||
+ in[i + 1] == '\"' || in[i + 1] == '\'' || in[i + 1] == '\\')) {
+ if (in[i + 1] == 'x' && ((i + 3) < l) && in[i + 2] == '3' &&
+ (in[i + 3] == 'c' || in[i + 3] == 'e')) {
out[j++] = '\\';
- out[j++] = in[i+1];
- out[j++] = in[i+2];
- out[j++] = in[i+3];
+ out[j++] = in[i + 1];
+ out[j++] = in[i + 2];
+ out[j++] = in[i + 3];
i += 3;
- } else {
+ } else {
out[j++] = '\\';
- out[j++] = in[i+1];
+ out[j++] = in[i + 1];
i++;
}
continue;
@@ -457,9 +459,9 @@ public class CMSTemplate extends CMSFile {
return new String(out, 0, j);
}
- /**
- * Like escapeJavaScriptString(String s) but also escape '[' for
- * HTML processing.
+ /**
+ * Like escapeJavaScriptString(String s) but also escape '[' for HTML
+ * processing.
*/
public static String escapeJavaScriptStringHTML(String v) {
int l = v.length();
@@ -477,20 +479,20 @@ public class CMSTemplate extends CMSFile {
continue;
}
- if ((c == 0x5c) && ((i+1)<l) && (in[i+1] == 'n' ||
- in[i+1] == 'r' || in[i+1] == 'f' || in[i+1] == 't' ||
- in[i+1] == '<' || in[i+1] == '>' ||
- in[i+1] == '\"' || in[i+1] == '\'' || in[i+1] == '\\')) {
- if (in[i+1] == 'x' && ((i+3)<l) && in[i+2] == '3' &&
- (in[i+3] == 'c' || in[i+3] == 'e')) {
+ if ((c == 0x5c) && ((i + 1) < l) && (in[i + 1] == 'n' ||
+ in[i + 1] == 'r' || in[i + 1] == 'f' || in[i + 1] == 't' ||
+ in[i + 1] == '<' || in[i + 1] == '>' ||
+ in[i + 1] == '\"' || in[i + 1] == '\'' || in[i + 1] == '\\')) {
+ if (in[i + 1] == 'x' && ((i + 3) < l) && in[i + 2] == '3' &&
+ (in[i + 3] == 'c' || in[i + 3] == 'e')) {
out[j++] = '\\';
- out[j++] = in[i+1];
- out[j++] = in[i+2];
- out[j++] = in[i+3];
+ out[j++] = in[i + 1];
+ out[j++] = in[i + 2];
+ out[j++] = in[i + 3];
i += 3;
- } else {
+ } else {
out[j++] = '\\';
- out[j++] = in[i+1];
+ out[j++] = in[i + 1];
i++;
}
continue;
@@ -551,25 +553,24 @@ public class CMSTemplate extends CMSFile {
* for debugging, return contents that would've been outputed.
*/
public String getOutput(CMSTemplateParams input)
- throws IOException {
+ throws IOException {
debugOutputStream out = new debugOutputStream();
renderOutput(out, input);
return out.toString();
}
- private
- class HTTPOutputStreamWriter extends OutputStreamWriter {
+ private class HTTPOutputStreamWriter extends OutputStreamWriter {
public HTTPOutputStreamWriter(OutputStream out)
- throws UnsupportedEncodingException {
+ throws UnsupportedEncodingException {
super(out);
}
-
+
public HTTPOutputStreamWriter(OutputStream out, String enc)
- throws UnsupportedEncodingException {
+ throws UnsupportedEncodingException {
super(out, enc);
}
-
+
public void print(String s) throws IOException {
write(s, 0, s.length());
flush();
@@ -577,9 +578,9 @@ public class CMSTemplate extends CMSFile {
}
}
-
private class templateLine {
private StringBuffer s = new StringBuffer();
+
void println(String p) {
s.append('\n');
s.append(p);
@@ -595,7 +596,6 @@ public class CMSTemplate extends CMSFile {
}
-
private static class debugOutputStream extends ServletOutputStream {
private StringWriter mStringWriter = new StringWriter();
@@ -604,7 +604,7 @@ public class CMSTemplate extends CMSFile {
}
public void write(int b) throws IOException {
- mStringWriter.write(b);
+ mStringWriter.write(b);
}
public String toString() {
diff --git a/pki/base/common/src/com/netscape/cms/servlet/common/CMSTemplateParams.java b/pki/base/common/src/com/netscape/cms/servlet/common/CMSTemplateParams.java
index 4f8cfc2a..ce2c26c3 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/common/CMSTemplateParams.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/common/CMSTemplateParams.java
@@ -17,16 +17,14 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.common;
-
import java.util.Enumeration;
import java.util.Vector;
import com.netscape.certsrv.base.IArgBlock;
-
/**
* Holds template parameters
- *
+ *
* @version $Revision$, $Date$
*/
public class CMSTemplateParams {
diff --git a/pki/base/common/src/com/netscape/cms/servlet/common/ECMSGWException.java b/pki/base/common/src/com/netscape/cms/servlet/common/ECMSGWException.java
index 0cd1102d..e8b848f7 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/common/ECMSGWException.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/common/ECMSGWException.java
@@ -17,14 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.common;
-
import com.netscape.certsrv.base.EBaseException;
-
/**
* A class represents a CMS gateway exception.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class ECMSGWException extends EBaseException {
@@ -36,7 +34,7 @@ public class ECMSGWException extends EBaseException {
/**
* CA resource class name.
*/
- private static final String CMSGW_RESOURCES = CMSGWResources.class.getName();
+ private static final String CMSGW_RESOURCES = CMSGWResources.class.getName();
/**
* Constructs a CMS Gateway exception.
diff --git a/pki/base/common/src/com/netscape/cms/servlet/common/GenErrorTemplateFiller.java b/pki/base/common/src/com/netscape/cms/servlet/common/GenErrorTemplateFiller.java
index 6debd2c7..b0032479 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/common/GenErrorTemplateFiller.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/common/GenErrorTemplateFiller.java
@@ -16,7 +16,6 @@
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.common;
-
import java.util.Enumeration;
import java.util.Locale;
@@ -27,10 +26,9 @@ import com.netscape.certsrv.authority.IAuthority;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IArgBlock;
-
/**
- * Default error template filler
- *
+ * Default error template filler
+ *
* @version $Revision$, $Date$
*/
public class GenErrorTemplateFiller implements ICMSTemplateFiller {
@@ -38,14 +36,15 @@ public class GenErrorTemplateFiller implements ICMSTemplateFiller {
}
/**
- * fill error details and description if any.
+ * fill error details and description if any.
+ *
* @param cmsReq the CMS Request.
* @param authority the authority
* @param locale the locale of template.
* @param e unexpected error. ignored.
*/
public CMSTemplateParams getTemplateParams(
- CMSRequest cmsReq, IAuthority authority, Locale locale, Exception e) {
+ CMSRequest cmsReq, IAuthority authority, Locale locale, Exception e) {
IArgBlock fixed = CMS.createArgBlock();
CMSTemplateParams params = new CMSTemplateParams(null, fixed);
@@ -53,21 +52,22 @@ public class GenErrorTemplateFiller implements ICMSTemplateFiller {
if (cmsReq != null) {
Integer sts = cmsReq.getStatus();
- if (sts != null)
+ if (sts != null)
fixed.set(ICMSTemplateFiller.REQUEST_STATUS, sts.toString());
} else {
- CMS.debug( "GenErrorTemplateFiller::getTemplateParams() - " +
- "cmsReq is null!" );
+ CMS.debug("GenErrorTemplateFiller::getTemplateParams() - " +
+ "cmsReq is null!");
return null;
}
-
- // error
+
+ // error
String ex = cmsReq.getError();
// Changed by beomsuk
- /*if (ex == null)
- ex = new EBaseException(CMS.getLogMessage("BASE_UNKNOWN_ERROR"));
- fixed.set(ICMSTemplateFiller.ERROR, ex.toString(locale));
+ /*
+ * if (ex == null) ex = new
+ * EBaseException(CMS.getLogMessage("BASE_UNKNOWN_ERROR"));
+ * fixed.set(ICMSTemplateFiller.ERROR, ex.toString(locale));
*/
if ((ex == null) && (cmsReq.getReason() == null))
ex = new EBaseException(CMS.getLogMessage("BASE_UNKNOWN_ERROR")).toString();
@@ -75,9 +75,9 @@ public class GenErrorTemplateFiller implements ICMSTemplateFiller {
fixed.set(ICMSTemplateFiller.ERROR, ex);
else if (cmsReq.getReason() != null)
fixed.set(ICMSTemplateFiller.ERROR, cmsReq.getReason());
- // Change end
-
- // error description if any.
+ // Change end
+
+ // error description if any.
Vector descr = cmsReq.getErrorDescr();
if (descr != null) {
@@ -85,20 +85,19 @@ public class GenErrorTemplateFiller implements ICMSTemplateFiller {
while (num.hasMoreElements()) {
String elem = (String) num.nextElement();
- //System.out.println("Setting description "+elem.toString());
+ // System.out.println("Setting description "+elem.toString());
IArgBlock argBlock = CMS.createArgBlock();
- argBlock.set(ICMSTemplateFiller.ERROR_DESCR,
- elem);
+ argBlock.set(ICMSTemplateFiller.ERROR_DESCR,
+ elem);
params.addRepeatRecord(argBlock);
}
}
// this authority
- if (authority != null)
- fixed.set(ICMSTemplateFiller.AUTHORITY,
- authority.getOfficialName());
+ if (authority != null)
+ fixed.set(ICMSTemplateFiller.AUTHORITY,
+ authority.getOfficialName());
return params;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/common/GenPendingTemplateFiller.java b/pki/base/common/src/com/netscape/cms/servlet/common/GenPendingTemplateFiller.java
index 15456865..c5a0d9a5 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/common/GenPendingTemplateFiller.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/common/GenPendingTemplateFiller.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.common;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
@@ -59,10 +58,9 @@ import com.netscape.certsrv.ra.IRegistrationAuthority;
import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.RequestId;
-
/**
- * default Pending template filler
- *
+ * default Pending template filler
+ *
* @version $Revision$, $Date$
*/
public class GenPendingTemplateFiller implements ICMSTemplateFiller {
@@ -72,28 +70,29 @@ public class GenPendingTemplateFiller implements ICMSTemplateFiller {
}
/**
- * fill error details and description if any.
+ * fill error details and description if any.
+ *
* @param cmsReq CMS Request
* @param authority this authority
* @param locale locale of template.
* @param e unexpected exception e. ignored.
*/
public CMSTemplateParams getTemplateParams(
- CMSRequest cmsReq, IAuthority authority, Locale locale, Exception e) {
+ CMSRequest cmsReq, IAuthority authority, Locale locale, Exception e) {
IArgBlock fixed = CMS.createArgBlock();
CMSTemplateParams params = new CMSTemplateParams(null, fixed);
- if( cmsReq == null ) {
+ if (cmsReq == null) {
return null;
}
// request status if any.
Integer sts = cmsReq.getStatus();
- if (sts != null)
+ if (sts != null)
fixed.set(ICMSTemplateFiller.REQUEST_STATUS, sts.toString());
- // request id
+ // request id
IRequest req = cmsReq.getIRequest();
if (req != null) {
@@ -109,17 +108,17 @@ public class GenPendingTemplateFiller implements ICMSTemplateFiller {
PendInfo pendInfo = new PendInfo(reqId.toString(), new
Date());
OtherInfo otherInfo = new
- OtherInfo(OtherInfo.PEND, null, pendInfo);
+ OtherInfo(OtherInfo.PEND, null, pendInfo);
SEQUENCE bpids = new SEQUENCE();
String[] reqIdArray =
- req.getExtDataInStringArray(IRequest.CMC_REQIDS);
+ req.getExtDataInStringArray(IRequest.CMC_REQIDS);
for (int i = 0; i < reqIdArray.length; i++) {
bpids.addElement(new INTEGER(reqIdArray[i]));
}
CMCStatusInfo cmcStatusInfo = new
- CMCStatusInfo(CMCStatusInfo.PENDING, bpids,
- (String) null, otherInfo);
+ CMCStatusInfo(CMCStatusInfo.PENDING, bpids,
+ (String) null, otherInfo);
TaggedAttribute ta = new TaggedAttribute(new
INTEGER(bpid++),
OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo,
@@ -130,7 +129,7 @@ public class GenPendingTemplateFiller implements ICMSTemplateFiller {
// create recipientNonce
// create responseInfo if regInfo exist
String[] transIds =
- req.getExtDataInStringArray(IRequest.CMC_TRANSID);
+ req.getExtDataInStringArray(IRequest.CMC_TRANSID);
SET ids = new SET();
for (int i = 0; i < transIds.length; i++) {
@@ -167,7 +166,7 @@ public class GenPendingTemplateFiller implements ICMSTemplateFiller {
dig = salt.getBytes();
}
String b64E = CMS.BtoA(dig);
- String[] newNonce = {b64E};
+ String[] newNonce = { b64E };
ta = new TaggedAttribute(new
INTEGER(bpid++),
@@ -180,13 +179,13 @@ public class GenPendingTemplateFiller implements ICMSTemplateFiller {
SEQUENCE(), new
SEQUENCE());
EncapsulatedContentInfo ci = new
- EncapsulatedContentInfo(OBJECT_IDENTIFIER.id_cct_PKIResponse,
- rb);
+ EncapsulatedContentInfo(OBJECT_IDENTIFIER.id_cct_PKIResponse,
+ rb);
org.mozilla.jss.crypto.X509Certificate x509cert = null;
if (authority instanceof ICertificateAuthority) {
x509cert = ((ICertificateAuthority) authority).getCaX509Cert();
- }else if (authority instanceof IRegistrationAuthority) {
+ } else if (authority instanceof IRegistrationAuthority) {
x509cert = ((IRegistrationAuthority) authority).getRACert();
}
if (x509cert == null)
@@ -194,12 +193,12 @@ public class GenPendingTemplateFiller implements ICMSTemplateFiller {
try {
X509CertImpl cert = new X509CertImpl(x509cert.getEncoded());
ByteArrayInputStream issuer1 = new
- ByteArrayInputStream(((X500Name) cert.getIssuerDN()).getEncoded());
+ ByteArrayInputStream(((X500Name) cert.getIssuerDN()).getEncoded());
Name issuer = (Name) Name.getTemplate().decode(issuer1);
IssuerAndSerialNumber ias = new
- IssuerAndSerialNumber(issuer, new INTEGER(cert.getSerialNumber().toString()));
+ IssuerAndSerialNumber(issuer, new INTEGER(cert.getSerialNumber().toString()));
SignerIdentifier si = new
- SignerIdentifier(SignerIdentifier.ISSUER_AND_SERIALNUMBER, ias, null);
+ SignerIdentifier(SignerIdentifier.ISSUER_AND_SERIALNUMBER, ias, null);
// SHA1 is the default digest Alg for now.
DigestAlgorithm digestAlg = null;
@@ -207,14 +206,14 @@ public class GenPendingTemplateFiller implements ICMSTemplateFiller {
org.mozilla.jss.crypto.PrivateKey privKey = CryptoManager.getInstance().findPrivKeyByCert(x509cert);
org.mozilla.jss.crypto.PrivateKey.Type keyType = privKey.getType();
- if( keyType.equals(org.mozilla.jss.crypto.PrivateKey.RSA ) ) {
+ if (keyType.equals(org.mozilla.jss.crypto.PrivateKey.RSA)) {
signAlg = SignatureAlgorithm.RSASignatureWithSHA1Digest;
- } else if( keyType.equals(org.mozilla.jss.crypto.PrivateKey.DSA ) ) {
+ } else if (keyType.equals(org.mozilla.jss.crypto.PrivateKey.DSA)) {
signAlg = SignatureAlgorithm.DSASignatureWithSHA1Digest;
} else {
- CMS.debug( "GenPendingTemplateFiller::getTemplateParams() - "
+ CMS.debug("GenPendingTemplateFiller::getTemplateParams() - "
+ "keyType " + keyType.toString()
- + " is unsupported!" );
+ + " is unsupported!");
return null;
}
@@ -224,41 +223,41 @@ public class GenPendingTemplateFiller implements ICMSTemplateFiller {
try {
SHADigest = MessageDigest.getInstance("SHA1");
digestAlg = DigestAlgorithm.SHA1;
-
+
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
rb.encode((OutputStream) ostream);
digest = SHADigest.digest(ostream.toByteArray());
} catch (NoSuchAlgorithmException ex) {
- //log("digest fail");
+ // log("digest fail");
}
SignerInfo signInfo = new
- SignerInfo(si, null, null,
- OBJECT_IDENTIFIER.id_cct_PKIResponse,
- digest, signAlg,
- privKey);
+ SignerInfo(si, null, null,
+ OBJECT_IDENTIFIER.id_cct_PKIResponse,
+ digest, signAlg,
+ privKey);
SET signInfos = new SET();
signInfos.addElement(signInfo);
-
+
SET digestAlgs = new SET();
if (digestAlg != null) {
AlgorithmIdentifier ai = new
- AlgorithmIdentifier(digestAlg.toOID(),
- null);
+ AlgorithmIdentifier(digestAlg.toOID(),
+ null);
digestAlgs.addElement(ai);
}
-
+
SignedData fResponse = new
- SignedData(digestAlgs, ci,
- null, null, signInfos);
+ SignedData(digestAlgs, ci,
+ null, null, signInfos);
ContentInfo fullResponse = new
- ContentInfo(ContentInfo.SIGNED_DATA, fResponse);
+ ContentInfo(ContentInfo.SIGNED_DATA, fResponse);
ByteArrayOutputStream ostream = new
- ByteArrayOutputStream();
+ ByteArrayOutputStream();
fullResponse.encode((OutputStream) ostream);
byte[] fr = ostream.toByteArray();
@@ -270,9 +269,9 @@ public class GenPendingTemplateFiller implements ICMSTemplateFiller {
}
}
// this authority
- if (authority != null)
- fixed.set(ICMSTemplateFiller.AUTHORITY,
- authority.getOfficialName());
+ if (authority != null)
+ fixed.set(ICMSTemplateFiller.AUTHORITY,
+ authority.getOfficialName());
return params;
}
@@ -286,4 +285,3 @@ public class GenPendingTemplateFiller implements ICMSTemplateFiller {
return false;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/common/GenRejectedTemplateFiller.java b/pki/base/common/src/com/netscape/cms/servlet/common/GenRejectedTemplateFiller.java
index 798b7f0d..d1396b79 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/common/GenRejectedTemplateFiller.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/common/GenRejectedTemplateFiller.java
@@ -16,7 +16,6 @@
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.common;
-
import java.util.Enumeration;
import java.util.Locale;
@@ -27,10 +26,9 @@ import com.netscape.certsrv.authority.IAuthority;
import com.netscape.certsrv.base.IArgBlock;
import com.netscape.certsrv.request.IRequest;
-
/**
- * default Service Pending template filler
- *
+ * default Service Pending template filler
+ *
* @version $Revision$, $Date$
*/
public class GenRejectedTemplateFiller implements ICMSTemplateFiller {
@@ -46,7 +44,7 @@ public class GenRejectedTemplateFiller implements ICMSTemplateFiller {
* @param e unexpected exception e. ignored.
*/
public CMSTemplateParams getTemplateParams(
- CMSRequest cmsReq, IAuthority authority, Locale locale, Exception e) {
+ CMSRequest cmsReq, IAuthority authority, Locale locale, Exception e) {
IArgBlock fixed = CMS.createArgBlock();
CMSTemplateParams params = new CMSTemplateParams(null, fixed);
@@ -54,15 +52,15 @@ public class GenRejectedTemplateFiller implements ICMSTemplateFiller {
if (cmsReq != null) {
Integer sts = cmsReq.getStatus();
- if (sts != null)
+ if (sts != null)
fixed.set(ICMSTemplateFiller.REQUEST_STATUS, sts.toString());
} else {
- CMS.debug( "GenRejectedTemplateFiller::getTemplateParams() - " +
- "cmsReq is null!" );
+ CMS.debug("GenRejectedTemplateFiller::getTemplateParams() - " +
+ "cmsReq is null!");
return null;
}
- // request id
+ // request id
IRequest req = cmsReq.getIRequest();
if (req != null) {
@@ -76,7 +74,7 @@ public class GenRejectedTemplateFiller implements ICMSTemplateFiller {
while (msgs.hasMoreElements()) {
String ex = (String) msgs.nextElement();
- IArgBlock messageArgBlock = CMS.createArgBlock();
+ IArgBlock messageArgBlock = CMS.createArgBlock();
messageArgBlock.set(POLICY_MESSAGE, ex);
params.addRepeatRecord(messageArgBlock);
@@ -86,10 +84,9 @@ public class GenRejectedTemplateFiller implements ICMSTemplateFiller {
// this authority
- if (authority != null)
- fixed.set(ICMSTemplateFiller.AUTHORITY,
- authority.getOfficialName());
+ if (authority != null)
+ fixed.set(ICMSTemplateFiller.AUTHORITY,
+ authority.getOfficialName());
return params;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/common/GenSuccessTemplateFiller.java b/pki/base/common/src/com/netscape/cms/servlet/common/GenSuccessTemplateFiller.java
index ff3d4f8c..67cad94f 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/common/GenSuccessTemplateFiller.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/common/GenSuccessTemplateFiller.java
@@ -16,7 +16,6 @@
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.common;
-
import java.util.Locale;
@@ -24,10 +23,9 @@ import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.authority.IAuthority;
import com.netscape.certsrv.base.IArgBlock;
-
/**
- * default Success template filler
- *
+ * default Success template filler
+ *
* @version $Revision$, $Date$
*/
public class GenSuccessTemplateFiller implements ICMSTemplateFiller {
@@ -36,14 +34,15 @@ public class GenSuccessTemplateFiller implements ICMSTemplateFiller {
}
/**
- * fill error details and description if any.
+ * fill error details and description if any.
+ *
* @param cmsReq CMS Request
* @param authority this authority
* @param locale locale of template.
* @param e unexpected exception e. ignored.
*/
public CMSTemplateParams getTemplateParams(
- CMSRequest cmsReq, IAuthority authority, Locale locale, Exception e) {
+ CMSRequest cmsReq, IAuthority authority, Locale locale, Exception e) {
IArgBlock fixed = CMS.createArgBlock();
CMSTemplateParams params = new CMSTemplateParams(null, fixed);
@@ -51,15 +50,14 @@ public class GenSuccessTemplateFiller implements ICMSTemplateFiller {
if (cmsReq != null) {
Integer sts = cmsReq.getStatus();
- if (sts != null)
+ if (sts != null)
fixed.set(ICMSTemplateFiller.REQUEST_STATUS, sts.toString());
}
- // this authority
- if (authority != null)
- fixed.set(ICMSTemplateFiller.AUTHORITY,
- authority.getOfficialName());
+ // this authority
+ if (authority != null)
+ fixed.set(ICMSTemplateFiller.AUTHORITY,
+ authority.getOfficialName());
return params;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/common/GenSvcPendingTemplateFiller.java b/pki/base/common/src/com/netscape/cms/servlet/common/GenSvcPendingTemplateFiller.java
index d08b83a8..ec1b9777 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/common/GenSvcPendingTemplateFiller.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/common/GenSvcPendingTemplateFiller.java
@@ -16,7 +16,6 @@
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.common;
-
import java.util.Locale;
@@ -25,10 +24,9 @@ import com.netscape.certsrv.authority.IAuthority;
import com.netscape.certsrv.base.IArgBlock;
import com.netscape.certsrv.request.IRequest;
-
/**
- * default Service Pending template filler
- *
+ * default Service Pending template filler
+ *
* @version $Revision$, $Date$
*/
public class GenSvcPendingTemplateFiller implements ICMSTemplateFiller {
@@ -38,14 +36,15 @@ public class GenSvcPendingTemplateFiller implements ICMSTemplateFiller {
}
/**
- * fill error details and description if any.
+ * fill error details and description if any.
+ *
* @param cmsReq CMS Request
* @param authority this authority
* @param locale locale of template.
* @param e unexpected exception e. ignored.
*/
public CMSTemplateParams getTemplateParams(
- CMSRequest cmsReq, IAuthority authority, Locale locale, Exception e) {
+ CMSRequest cmsReq, IAuthority authority, Locale locale, Exception e) {
IArgBlock fixed = CMS.createArgBlock();
CMSTemplateParams params = new CMSTemplateParams(null, fixed);
@@ -72,10 +71,9 @@ public class GenSvcPendingTemplateFiller implements ICMSTemplateFiller {
}
// this authority
- if (authority != null)
- fixed.set(ICMSTemplateFiller.AUTHORITY,
- authority.getOfficialName());
+ if (authority != null)
+ fixed.set(ICMSTemplateFiller.AUTHORITY,
+ authority.getOfficialName());
return params;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/common/GenUnauthorizedTemplateFiller.java b/pki/base/common/src/com/netscape/cms/servlet/common/GenUnauthorizedTemplateFiller.java
index befacf83..567b01d0 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/common/GenUnauthorizedTemplateFiller.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/common/GenUnauthorizedTemplateFiller.java
@@ -16,7 +16,6 @@
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.common;
-
import java.util.Locale;
@@ -24,10 +23,9 @@ import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.authority.IAuthority;
import com.netscape.certsrv.base.IArgBlock;
-
/**
- * default Unauthorized template filler
- *
+ * default Unauthorized template filler
+ *
* @version $Revision$, $Date$
*/
public class GenUnauthorizedTemplateFiller implements ICMSTemplateFiller {
@@ -36,14 +34,15 @@ public class GenUnauthorizedTemplateFiller implements ICMSTemplateFiller {
}
/**
- * fill error details and description if any.
+ * fill error details and description if any.
+ *
* @param cmsReq CMS Request
* @param authority this authority
* @param locale locale of template.
* @param e unexpected exception e. ignored.
*/
public CMSTemplateParams getTemplateParams(
- CMSRequest cmsReq, IAuthority authority, Locale locale, Exception e) {
+ CMSRequest cmsReq, IAuthority authority, Locale locale, Exception e) {
IArgBlock fixed = CMS.createArgBlock();
CMSTemplateParams params = new CMSTemplateParams(null, fixed);
@@ -51,19 +50,18 @@ public class GenUnauthorizedTemplateFiller implements ICMSTemplateFiller {
if (cmsReq != null) {
Integer sts = cmsReq.getStatus();
- if (sts != null)
+ if (sts != null)
fixed.set(ICMSTemplateFiller.REQUEST_STATUS, sts.toString());
}
// set unauthorized error
- fixed.set(ICMSTemplateFiller.ERROR,
- new ECMSGWException(CMS.getLogMessage("CMSGW_UNAUTHORIZED")));
+ fixed.set(ICMSTemplateFiller.ERROR,
+ new ECMSGWException(CMS.getLogMessage("CMSGW_UNAUTHORIZED")));
- // this authority
- if (authority != null)
- fixed.set(ICMSTemplateFiller.AUTHORITY,
- authority.getOfficialName());
+ // this authority
+ if (authority != null)
+ fixed.set(ICMSTemplateFiller.AUTHORITY,
+ authority.getOfficialName());
return params;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/common/GenUnexpectedErrorTemplateFiller.java b/pki/base/common/src/com/netscape/cms/servlet/common/GenUnexpectedErrorTemplateFiller.java
index 1ae6ee45..757440b1 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/common/GenUnexpectedErrorTemplateFiller.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/common/GenUnexpectedErrorTemplateFiller.java
@@ -16,7 +16,6 @@
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.common;
-
import java.util.Locale;
@@ -25,10 +24,9 @@ import com.netscape.certsrv.authority.IAuthority;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IArgBlock;
-
/**
- * default unexpected error template filler
- *
+ * default unexpected error template filler
+ *
* @version $Revision$, $Date$
*/
public class GenUnexpectedErrorTemplateFiller implements ICMSTemplateFiller {
@@ -37,41 +35,42 @@ public class GenUnexpectedErrorTemplateFiller implements ICMSTemplateFiller {
}
/**
- * fill error details and description if any.
+ * fill error details and description if any.
+ *
* @param cmsReq CMS Request
* @param authority this authority
* @param locale locale of template.
* @param e unexpected exception e. ignored.
*/
public CMSTemplateParams getTemplateParams(
- CMSRequest cmsReq, IAuthority authority, Locale locale, Exception e) {
+ CMSRequest cmsReq, IAuthority authority, Locale locale, Exception e) {
IArgBlock fixed = CMS.createArgBlock();
CMSTemplateParams params = new CMSTemplateParams(null, fixed);
-
+
// When an exception occurs the exit is non-local which probably
// will leave the requestStatus value set to something other
- // than CMSRequest.EXCEPTION, so force the requestStatus to
- // EXCEPTION since it must be that if we're here.
+ // than CMSRequest.EXCEPTION, so force the requestStatus to
+ // EXCEPTION since it must be that if we're here.
Integer sts = CMSRequest.EXCEPTION;
- if (cmsReq != null) cmsReq.setStatus(sts);
+ if (cmsReq != null)
+ cmsReq.setStatus(sts);
fixed.set(ICMSTemplateFiller.REQUEST_STATUS, sts.toString());
// the unexpected error (exception)
- if (e == null)
+ if (e == null)
e = new EBaseException(CMS.getLogMessage("BASE_UNKNOWN_ERROR"));
String errMsg = null;
- if (e instanceof EBaseException)
+ if (e instanceof EBaseException)
errMsg = ((EBaseException) e).toString(locale);
- else
+ else
errMsg = e.toString();
fixed.set(ICMSTemplateFiller.EXCEPTION, errMsg);
// this authority
- if (authority != null)
- fixed.set(ICMSTemplateFiller.AUTHORITY,
- authority.getOfficialName());
+ if (authority != null)
+ fixed.set(ICMSTemplateFiller.AUTHORITY,
+ authority.getOfficialName());
return params;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/common/ICMSTemplateFiller.java b/pki/base/common/src/com/netscape/cms/servlet/common/ICMSTemplateFiller.java
index ddd6f0a1..b8c84e7d 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/common/ICMSTemplateFiller.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/common/ICMSTemplateFiller.java
@@ -17,35 +17,33 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.common;
-
import java.util.Locale;
import com.netscape.certsrv.authority.IAuthority;
-
/**
* This interface represents a template filler.
- *
+ *
* @version $Revision$, $Date$
*/
public interface ICMSTemplateFiller {
- // common template variables.
+ // common template variables.
public final static String ERROR = "errorDetails";
public final static String ERROR_DESCR = "errorDescription";
public final static String EXCEPTION = "unexpectedError";
- public static final String HOST = "host";
- public static final String PORT = "port";
- public static final String SCHEME = "scheme";
+ public static final String HOST = "host";
+ public static final String PORT = "port";
+ public static final String SCHEME = "scheme";
- public static final String AUTHORITY = "authorityName";
+ public static final String AUTHORITY = "authorityName";
- public static final String REQUEST_STATUS = "requestStatus";
+ public static final String REQUEST_STATUS = "requestStatus";
- public static final String KEYREC_ID = "keyrecId";
- public static final String REQUEST_ID = "requestId";
+ public static final String KEYREC_ID = "keyrecId";
+ public static final String REQUEST_ID = "requestId";
public CMSTemplateParams getTemplateParams(
- CMSRequest cmsReq, IAuthority mAuthority, Locale locale, Exception e)
- throws Exception;
+ CMSRequest cmsReq, IAuthority mAuthority, Locale locale, Exception e)
+ throws Exception;
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/common/IRawJS.java b/pki/base/common/src/com/netscape/cms/servlet/common/IRawJS.java
index 27ea5ec1..827f24f1 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/common/IRawJS.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/common/IRawJS.java
@@ -17,10 +17,9 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.common;
-
/**
* This represents raw JS parameters.
- *
+ *
* @version $Revision$, $Date$
*/
public interface IRawJS {
diff --git a/pki/base/common/src/com/netscape/cms/servlet/common/IndexTemplateFiller.java b/pki/base/common/src/com/netscape/cms/servlet/common/IndexTemplateFiller.java
index ce1a5082..23f962e5 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/common/IndexTemplateFiller.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/common/IndexTemplateFiller.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.common;
-
import java.util.Locale;
import com.netscape.certsrv.apps.CMS;
@@ -26,15 +25,13 @@ import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IArgBlock;
import com.netscape.certsrv.base.ISubsystem;
-
/**
- * A class represents a certificate server kernel. This
- * kernel contains a list of resident subsystems such
- * as logging, security, remote administration. Additional
- * subsystems can be loaded into this kernel by specifying
- * parameters in the configuration store.
+ * A class represents a certificate server kernel. This kernel contains a list
+ * of resident subsystems such as logging, security, remote administration.
+ * Additional subsystems can be loaded into this kernel by specifying parameters
+ * in the configuration store.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class IndexTemplateFiller implements ICMSTemplateFiller {
@@ -53,7 +50,7 @@ public class IndexTemplateFiller implements ICMSTemplateFiller {
}
public CMSTemplateParams getTemplateParams(
- CMSRequest cmsReq, IAuthority mAuthority, Locale locale, Exception e) {
+ CMSRequest cmsReq, IAuthority mAuthority, Locale locale, Exception e) {
IArgBlock header = CMS.createArgBlock();
IArgBlock ctx = CMS.createArgBlock();
CMSTemplateParams params = new CMSTemplateParams(header, ctx);
@@ -103,11 +100,11 @@ public class IndexTemplateFiller implements ICMSTemplateFiller {
count++;
}
// information about what is selected is provided
- // from the caller. This parameter (selected) is used
+ // from the caller. This parameter (selected) is used
// by header servlet
try {
- header.addStringValue("selected",
- cmsReq.getHttpParams().getValueAsString("selected"));
+ header.addStringValue("selected",
+ cmsReq.getHttpParams().getValueAsString("selected"));
} catch (EBaseException ex) {
}
header.addIntegerValue(OUT_TOTAL_COUNT, count);
diff --git a/pki/base/common/src/com/netscape/cms/servlet/common/RawJS.java b/pki/base/common/src/com/netscape/cms/servlet/common/RawJS.java
index fb31fec1..f936e075 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/common/RawJS.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/common/RawJS.java
@@ -17,10 +17,9 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.common;
-
/**
* This represents raw JS parameters.
- *
+ *
* @version $Revision$, $Date$
*/
public class RawJS implements IRawJS {
diff --git a/pki/base/common/src/com/netscape/cms/servlet/common/Utils.java b/pki/base/common/src/com/netscape/cms/servlet/common/Utils.java
index 580909cb..9c728c03 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/common/Utils.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/common/Utils.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.common;
-
import java.util.StringTokenizer;
import javax.servlet.ServletConfig;
@@ -28,10 +27,9 @@ import com.netscape.certsrv.authorization.IAuthzSubsystem;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
-
/**
* Utility class
- *
+ *
* @version $Revision$, $Date$
*/
public class Utils {
@@ -45,13 +43,13 @@ public class Utils {
public final static String AUTHZ_MGR_BASIC = "BasicAclAuthz";
public final static String AUTHZ_MGR_LDAP = "DirAclAuthz";
- public static String initializeAuthz(ServletConfig sc,
- IAuthzSubsystem authz, String id) throws ServletException {
+ public static String initializeAuthz(ServletConfig sc,
+ IAuthzSubsystem authz, String id) throws ServletException {
String srcType = AUTHZ_SRC_LDAP;
try {
IConfigStore authzConfig =
- CMS.getConfigStore().getSubStore(AUTHZ_CONFIG_STORE);
+ CMS.getConfigStore().getSubStore(AUTHZ_CONFIG_STORE);
srcType = authzConfig.getString(AUTHZ_SRC_TYPE, AUTHZ_SRC_LDAP);
} catch (EBaseException e) {
@@ -64,7 +62,7 @@ public class Utils {
CMS.debug(CMS.getLogMessage("ADMIN_SRVLT_AUTHZ_INITED", ""));
aclMethod = sc.getInitParameter(PROP_AUTHZ_MGR);
if (aclMethod != null &&
- aclMethod.equalsIgnoreCase(AUTHZ_MGR_BASIC)) {
+ aclMethod.equalsIgnoreCase(AUTHZ_MGR_BASIC)) {
String aclInfo = sc.getInitParameter(PROP_ACL);
if (aclInfo != null) {
@@ -95,7 +93,7 @@ public class Utils {
}
public static void addACLInfo(IAuthzSubsystem authz, String aclMethod,
- String aclInfo) throws EBaseException {
+ String aclInfo) throws EBaseException {
StringTokenizer tokenizer = new StringTokenizer(aclInfo, "#");
diff --git a/pki/base/common/src/com/netscape/cms/servlet/connector/CloneServlet.java b/pki/base/common/src/com/netscape/cms/servlet/connector/CloneServlet.java
index b3809579..439b201a 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/connector/CloneServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/connector/CloneServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.connector;
-
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
@@ -58,12 +57,10 @@ import com.netscape.certsrv.request.RequestStatus;
import com.netscape.cms.servlet.base.CMSServlet;
import com.netscape.cms.servlet.common.CMSRequest;
-
/**
- * Clone servlet - part of the Clone Authority (CLA)
- * processes Revoked certs from its dependant clone CAs
- * service request and return status.
- *
+ * Clone servlet - part of the Clone Authority (CLA) processes Revoked certs
+ * from its dependant clone CAs service request and return status.
+ *
* @version $Revision$, $Date$
*/
public class CloneServlet extends CMSServlet {
@@ -94,8 +91,8 @@ public class CloneServlet extends CMSServlet {
mAuthSubsystem = (IAuthSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_AUTH);
}
- public void service(HttpServletRequest req,
- HttpServletResponse resp) throws ServletException, IOException {
+ public void service(HttpServletRequest req,
+ HttpServletResponse resp) throws ServletException, IOException {
boolean running_state = CMS.isInRunningState();
if (!running_state)
@@ -130,14 +127,14 @@ public class CloneServlet extends CMSServlet {
IRequest r = null;
IRequest reply = null;
- // NOTE must read all bufer before redoing handshake for
+ // NOTE must read all bufer before redoing handshake for
// ssl client auth for client auth to work.
// get request method
- method = req.getMethod();
+ method = req.getMethod();
// get content length
- len = req.getContentLength();
+ len = req.getContentLength();
// get content, a base 64 encoded serialized request.
if (len > 0) {
@@ -159,16 +156,16 @@ public class CloneServlet extends CMSServlet {
// force client auth handshake, validate clone CA (CCA)
// and get CCA's Id.
- // NOTE must do this after all contents are read for ssl
- // redohandshake to work
+ // NOTE must do this after all contents are read for ssl
+ // redohandshake to work
X509Certificate peerCert;
try {
peerCert = getPeerCert(req);
- }catch (EBaseException e) {
- mAuthority.log(ILogger.LL_SECURITY,
- CMS.getLogMessage("CMSGW_HAS_NO_CLIENT_CERT"));
+ } catch (EBaseException e) {
+ mAuthority.log(ILogger.LL_SECURITY,
+ CMS.getLogMessage("CMSGW_HAS_NO_CLIENT_CERT"));
resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
@@ -190,7 +187,7 @@ public class CloneServlet extends CMSServlet {
CMS.debug("CloneServlet: about to authenticate");
token = authenticate(peerCert);
// cfu maybe don't need CCA_Id, because the above check
- // was good enough
+ // was good enough
CCAUserId = token.getInString("userid");
CCA_Id = (String) peerCert.getSubjectDN().toString();
} catch (EInvalidCredentials e) {
@@ -203,8 +200,8 @@ public class CloneServlet extends CMSServlet {
return;
}
- mAuthority.log(ILogger.LL_INFO,
- "Clone Certificate Authority authenticated: " + peerCert.getSubjectDN());
+ mAuthority.log(ILogger.LL_INFO,
+ "Clone Certificate Authority authenticated: " + peerCert.getSubjectDN());
// authorize, any authenticated user are authorized
AuthzToken authzToken = null;
@@ -232,29 +229,29 @@ public class CloneServlet extends CMSServlet {
}
// now process CCA request - should just be posting revoked
- // certs for now
+ // certs for now
try {
// decode request.
CMS.debug("Cloneservlet: before decoding request, encodedreq= " + encodedreq);
msg = (IPKIMessage) mReqEncoder.decode(encodedreq);
- // process request
+ // process request
CMS.debug("Cloneservlet: decoded request");
replymsg = processRequest(CCA_Id, CCAUserId, msg, token);
} catch (IOException e) {
e.printStackTrace();
- mAuthority.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_IO_ERROR_REMOTE_REQUEST", e.toString()));
+ mAuthority.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_IO_ERROR_REMOTE_REQUEST", e.toString()));
resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
} catch (EBaseException e) {
- mAuthority.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_IO_ERROR_REMOTE_REQUEST", e.toString()));
+ mAuthority.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_IO_ERROR_REMOTE_REQUEST", e.toString()));
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
- // encode reply
+ // encode reply
String encodedrep = mReqEncoder.encode(replymsg);
resp.setStatus(HttpServletResponse.SC_OK);
@@ -271,46 +268,46 @@ public class CloneServlet extends CMSServlet {
out.flush();
}
- //cfu ++change this to just check the subject and signer
+ // cfu ++change this to just check the subject and signer
protected IAuthToken authenticate(
- X509Certificate peerCert)
- throws EBaseException {
+ X509Certificate peerCert)
+ throws EBaseException {
try {
- // XXX using agent authentication now since we're only
- // verifying that the cert belongs to a user in the db.
- // XXX change this to ACL in the future.
+ // XXX using agent authentication now since we're only
+ // verifying that the cert belongs to a user in the db.
+ // XXX change this to ACL in the future.
// build JAVA X509Certificate from peerCert.
X509CertImpl cert = new X509CertImpl(peerCert.getEncoded());
AuthCredentials creds = new AuthCredentials();
- creds.set(IAuthManager.CRED_SSL_CLIENT_CERT,
- new X509Certificate[] {cert}
- );
+ creds.set(IAuthManager.CRED_SSL_CLIENT_CERT,
+ new X509Certificate[] { cert }
+ );
- IAuthToken token = mAuthSubsystem.authenticate(creds,
+ IAuthToken token = mAuthSubsystem.authenticate(creds,
IAuthSubsystem.CERTUSERDB_AUTHMGR_ID);
return token;
} catch (CertificateException e) {
- mAuthority.log(ILogger.LL_SECURITY,
- CMS.getLogMessage("CMSGW_REMOTE_AUTHORITY_AUTH_FAILURE", peerCert.getSubjectDN().toString()));
+ mAuthority.log(ILogger.LL_SECURITY,
+ CMS.getLogMessage("CMSGW_REMOTE_AUTHORITY_AUTH_FAILURE", peerCert.getSubjectDN().toString()));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR", e.toString()));
} catch (EInvalidCredentials e) {
- mAuthority.log(ILogger.LL_SECURITY,
- CMS.getLogMessage("CMSGW_REMOTE_AUTHORITY_AUTH_FAILURE", peerCert.getSubjectDN().toString()));
+ mAuthority.log(ILogger.LL_SECURITY,
+ CMS.getLogMessage("CMSGW_REMOTE_AUTHORITY_AUTH_FAILURE", peerCert.getSubjectDN().toString()));
throw e;
} catch (EBaseException e) {
- mAuthority.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_REMOTE_AUTHORITY_AUTH_FAILURE", peerCert.getSubjectDN().toString()));
+ mAuthority.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_REMOTE_AUTHORITY_AUTH_FAILURE", peerCert.getSubjectDN().toString()));
throw e;
}
}
protected IPKIMessage processRequest(
- String source, String sourceUserId, IPKIMessage msg, IAuthToken token)
- throws EBaseException {
+ String source, String sourceUserId, IPKIMessage msg, IAuthToken token)
+ throws EBaseException {
IPKIMessage replymsg = null;
IRequest r = null;
IRequestQueue queue = mAuthority.getRequestQueue();
@@ -331,8 +328,8 @@ public class CloneServlet extends CMSServlet {
mAuthority.log(ILogger.LL_FAILURE, errormsg);
throw new EBaseException(errormsg);
} else {
- mAuthority.log(ILogger.LL_INFO,
- "Found request " + thisreqid + " for " + srcid);
+ mAuthority.log(ILogger.LL_INFO,
+ "Found request " + thisreqid + " for " + srcid);
replymsg = CMS.getHttpPKIMessage();
replymsg.fromRequest(thisreq);
return replymsg;
@@ -348,7 +345,7 @@ public class CloneServlet extends CMSServlet {
// setting requestor type must come after copy contents. because
// requestor is a regular attribute.
thisreq.setExtData(IRequest.REQUESTOR_TYPE,
- IRequest.REQUESTOR_RA);
+ IRequest.REQUESTOR_RA);
mAuthority.log(ILogger.LL_INFO, "Processing remote request " + srcid);
// Set this so that request's updateBy is recorded
@@ -362,17 +359,17 @@ public class CloneServlet extends CMSServlet {
replymsg = CMS.getHttpPKIMessage();
replymsg.fromRequest(thisreq);
- //for audit log
+ // for audit log
String agentID = sourceUserId;
String initiative = AuditFormat.FROMRA + " trustedManagerID: " +
- agentID + " remote reqID " + msg.getReqId();
+ agentID + " remote reqID " + msg.getReqId();
String authMgr = AuditFormat.NOAUTH;
if (token != null) {
- authMgr =
+ authMgr =
token.getInString(AuthToken.TOKEN_AUTHMGR_INST_NAME);
}
-
+
// Get the certificate info from the request
X509CertInfo certInfo[] = thisreq.getExtDataInCertInfoArray(IRequest.CERT_INFO);
@@ -380,36 +377,35 @@ public class CloneServlet extends CMSServlet {
if (!thisreq.getRequestStatus().equals(RequestStatus.COMPLETE)) {
if (certInfo != null) {
for (int i = 0; i < certInfo.length; i++) {
- mLogger.log(ILogger.EV_AUDIT,
+ mLogger.log(ILogger.EV_AUDIT,
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.FORMAT,
+ new Object[] {
+ thisreq.getRequestType(),
+ thisreq.getRequestId(),
+ initiative,
+ authMgr,
+ thisreq.getRequestStatus(),
+ certInfo[i].get(X509CertInfo.SUBJECT),
+ "" }
+ );
+ }
+ } else {
+ mLogger.log(ILogger.EV_AUDIT,
ILogger.S_OTHER,
AuditFormat.LEVEL,
- AuditFormat.FORMAT,
+ AuditFormat.NODNFORMAT,
new Object[] {
- thisreq.getRequestType(),
- thisreq.getRequestId(),
- initiative,
- authMgr,
- thisreq.getRequestStatus(),
- certInfo[i].get(X509CertInfo.SUBJECT),
- ""}
- );
- }
- } else {
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.NODNFORMAT,
- new Object[] {
- thisreq.getRequestType(),
- thisreq.getRequestId(),
- initiative,
- authMgr,
- thisreq.getRequestStatus()}
- );
+ thisreq.getRequestType(),
+ thisreq.getRequestId(),
+ initiative,
+ authMgr,
+ thisreq.getRequestStatus() }
+ );
}
} else {
- if
- (thisreq.getRequestType().equals(IRequest.CLA_CERT4CRL_REQUEST)) {
+ if (thisreq.getRequestType().equals(IRequest.CLA_CERT4CRL_REQUEST)) {
Integer result = thisreq.getExtDataInInteger(IRequest.RESULT);
if (result.equals(IRequest.RES_ERROR)) {
@@ -420,155 +416,83 @@ public class CloneServlet extends CMSServlet {
}
}
- /* cfu ---
- if (thisreq.getRequestType().equals(IRequest.ENROLLMENT_REQUEST)) {
- // XXX make the repeat record.
- // Get the certificate(s) from the request
- X509CertImpl issuedCerts[] =
- (X509CertImpl[])thisreq.get(IRequest.ISSUED_CERTS);
- // return potentially more than one certificates.
- if (issuedCerts != null) {
- for (int i = 0; i < issuedCerts.length; i++) {
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.FORMAT,
- new Object[] {
- thisreq.getRequestType(),
- thisreq.getRequestId() ,
- initiative ,
- authMgr ,
- "completed",
- issuedCerts[i].getSubjectDN() ,
- "cert issued serial number: 0x" +
- issuedCerts[i].getSerialNumber().toString(16)}
- );
- }
- } else {
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.NODNFORMAT,
- new Object[] {
- thisreq.getRequestType(),
- thisreq.getRequestId() ,
- initiative ,
- authMgr ,
- "completed"}
- );
- }
- } else if (thisreq.getRequestType().equals(IRequest.RENEWAL_REQUEST)) {
- X509CertImpl[] certs = (X509CertImpl[])thisreq.get(IRequest.OLD_CERTS);
- X509CertImpl old_cert = certs[0];
- certs = (X509CertImpl[])thisreq.get(IRequest.ISSUED_CERTS);
- X509CertImpl renewed_cert = certs[0];
- if (old_cert != null && renewed_cert != null) {
- mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.RENEWALFORMAT,
- new Object[] {
- thisreq.getRequestId(),
- initiative ,
- authMgr ,
- "completed",
- old_cert.getSubjectDN() ,
- old_cert.getSerialNumber().toString(16) ,
- "new serial number: 0x" +
- renewed_cert.getSerialNumber().toString(16)}
- );
- } else {
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.NODNFORMAT,
- new Object[] {
- thisreq.getRequestType(),
- thisreq.getRequestId() ,
- initiative ,
- authMgr ,
- "completed with error"}
- );
- }
- } else if (thisreq.getRequestType().equals(IRequest.REVOCATION_REQUEST)) {
- X509CertImpl[] oldCerts = (X509CertImpl[])thisreq.get(IRequest.OLD_CERTS);
- RevokedCertImpl crlentries[] =
- (RevokedCertImpl[])thisreq.get(IRequest.REVOKED_CERTS);
- CRLExtensions crlExts = crlentries[0].getExtensions();
- int reason = 0;
- if (crlExts != null) {
- Enumeration enum = crlExts.getElements();
- while(enum.hasMoreElements()){
- Extension ext = (Extension) enum.nextElement();
- if (ext instanceof CRLReasonExtension) {
- reason = ((CRLReasonExtension)ext).getReason().toInt
- ();
- break;
- }
- }
- }
-
- int count = oldCerts.length;
- Integer result = (Integer)thisreq.get(IRequest.RESULT);
- if (result.equals(IRequest.RES_ERROR)) {
- EBaseException ex = (EBaseException)thisreq.get(IRequest.ERROR);
- EBaseException[] svcErrors =
- (EBaseException[])thisreq.get(IRequest.SVCERRORS);
- if (svcErrors != null && svcErrors.length > 0) {
- for (int i = 0; i < svcErrors.length; i++) {
- EBaseException err = svcErrors[i];
- if (err != null) {
- for (int j = 0; j < count; j++) {
- if (oldCerts[j] != null) {
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.DOREVOKEFORMAT,
- new Object[] {
- thisreq.getRequestId(),
- initiative ,
- "completed with error: " +
- err.toString() ,
- oldCerts[j].getSubjectDN() ,
- oldCerts[j].getSerialNumber().toString(16),
- RevocationReason.fromInt(reason).toString()}
- );
- }
- }
- }
- }
- }
- } else {
- // the success.
- for (int j = 0; j < count; j++) {
- if (oldCerts[j] != null) {
- mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.DOREVOKEFORMAT,
- new Object[] {
- thisreq.getRequestId(),
- initiative ,
- "completed" ,
- oldCerts[j].getSubjectDN() ,
- oldCerts[j].getSerialNumber().toString(16),
- RevocationReason.fromInt(reason).toString()}
- );
- }
- }
- }
- } else {
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.NODNFORMAT,
- new Object[] {
- thisreq.getRequestType(),
- thisreq.getRequestId() ,
- initiative ,
- authMgr ,
- "completed"}
- );
- }
- cfu */
+ /*
+ * cfu --- if
+ * (thisreq.getRequestType().equals(IRequest.ENROLLMENT_REQUEST
+ * )) { // XXX make the repeat record. // Get the certificate(s)
+ * from the request X509CertImpl issuedCerts[] =
+ * (X509CertImpl[])thisreq.get(IRequest.ISSUED_CERTS); // return
+ * potentially more than one certificates. if (issuedCerts !=
+ * null) { for (int i = 0; i < issuedCerts.length; i++) {
+ * mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
+ * AuditFormat.LEVEL, AuditFormat.FORMAT, new Object[] {
+ * thisreq.getRequestType(), thisreq.getRequestId() , initiative
+ * , authMgr , "completed", issuedCerts[i].getSubjectDN() ,
+ * "cert issued serial number: 0x" +
+ * issuedCerts[i].getSerialNumber().toString(16)} ); } } else {
+ * mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
+ * AuditFormat.LEVEL, AuditFormat.NODNFORMAT, new Object[] {
+ * thisreq.getRequestType(), thisreq.getRequestId() , initiative
+ * , authMgr , "completed"} ); } } else if
+ * (thisreq.getRequestType().equals(IRequest.RENEWAL_REQUEST)) {
+ * X509CertImpl[] certs =
+ * (X509CertImpl[])thisreq.get(IRequest.OLD_CERTS); X509CertImpl
+ * old_cert = certs[0]; certs =
+ * (X509CertImpl[])thisreq.get(IRequest.ISSUED_CERTS);
+ * X509CertImpl renewed_cert = certs[0]; if (old_cert != null &&
+ * renewed_cert != null) { mLogger.log(ILogger.EV_AUDIT,
+ * ILogger.S_OTHER, AuditFormat.LEVEL,
+ * AuditFormat.RENEWALFORMAT, new Object[] {
+ * thisreq.getRequestId(), initiative , authMgr , "completed",
+ * old_cert.getSubjectDN() ,
+ * old_cert.getSerialNumber().toString(16) ,
+ * "new serial number: 0x" +
+ * renewed_cert.getSerialNumber().toString(16)} ); } else {
+ * mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
+ * AuditFormat.LEVEL, AuditFormat.NODNFORMAT, new Object[] {
+ * thisreq.getRequestType(), thisreq.getRequestId() , initiative
+ * , authMgr , "completed with error"} ); } } else if
+ * (thisreq.getRequestType
+ * ().equals(IRequest.REVOCATION_REQUEST)) { X509CertImpl[]
+ * oldCerts = (X509CertImpl[])thisreq.get(IRequest.OLD_CERTS);
+ * RevokedCertImpl crlentries[] =
+ * (RevokedCertImpl[])thisreq.get(IRequest.REVOKED_CERTS);
+ * CRLExtensions crlExts = crlentries[0].getExtensions(); int
+ * reason = 0; if (crlExts != null) { Enumeration enum =
+ * crlExts.getElements(); while(enum.hasMoreElements()){
+ * Extension ext = (Extension) enum.nextElement(); if (ext
+ * instanceof CRLReasonExtension) { reason =
+ * ((CRLReasonExtension)ext).getReason().toInt (); break; } } }
+ *
+ * int count = oldCerts.length; Integer result =
+ * (Integer)thisreq.get(IRequest.RESULT); if
+ * (result.equals(IRequest.RES_ERROR)) { EBaseException ex =
+ * (EBaseException)thisreq.get(IRequest.ERROR); EBaseException[]
+ * svcErrors =
+ * (EBaseException[])thisreq.get(IRequest.SVCERRORS); if
+ * (svcErrors != null && svcErrors.length > 0) { for (int i = 0;
+ * i < svcErrors.length; i++) { EBaseException err =
+ * svcErrors[i]; if (err != null) { for (int j = 0; j < count;
+ * j++) { if (oldCerts[j] != null) {
+ * mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
+ * AuditFormat.LEVEL, AuditFormat.DOREVOKEFORMAT, new Object[] {
+ * thisreq.getRequestId(), initiative , "completed with error: "
+ * + err.toString() , oldCerts[j].getSubjectDN() ,
+ * oldCerts[j].getSerialNumber().toString(16),
+ * RevocationReason.fromInt(reason).toString()} ); } } } } } }
+ * else { // the success. for (int j = 0; j < count; j++) { if
+ * (oldCerts[j] != null) { mLogger.log(ILogger.EV_AUDIT,
+ * ILogger.S_OTHER, AuditFormat.LEVEL,
+ * AuditFormat.DOREVOKEFORMAT, new Object[] {
+ * thisreq.getRequestId(), initiative , "completed" ,
+ * oldCerts[j].getSubjectDN() ,
+ * oldCerts[j].getSerialNumber().toString(16),
+ * RevocationReason.fromInt(reason).toString()} ); } } } } else
+ * { mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
+ * AuditFormat.LEVEL, AuditFormat.NODNFORMAT, new Object[] {
+ * thisreq.getRequestType(), thisreq.getRequestId() , initiative
+ * , authMgr , "completed"} ); } cfu
+ */
}
} catch (IOException e) {
} catch (CertificateException e) {
@@ -578,7 +502,7 @@ public class CloneServlet extends CMSServlet {
}
protected X509Certificate
- getPeerCert(HttpServletRequest req) throws EBaseException {
+ getPeerCert(HttpServletRequest req) throws EBaseException {
return getSSLClientCertificate(req);
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/connector/ConnectorServlet.java b/pki/base/common/src/com/netscape/cms/servlet/connector/ConnectorServlet.java
index 67956bd8..cc496bd6 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/connector/ConnectorServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/connector/ConnectorServlet.java
@@ -72,12 +72,10 @@ import com.netscape.certsrv.request.RequestStatus;
import com.netscape.cms.servlet.base.CMSServlet;
import com.netscape.cms.servlet.common.CMSRequest;
-
/**
- * Connector servlet
- * process requests from remote authority -
- * service request or return status.
- *
+ * Connector servlet process requests from remote authority - service request or
+ * return status.
+ *
* @version $Revision$, $Date$
*/
public class ConnectorServlet extends CMSServlet {
@@ -96,13 +94,13 @@ public class ConnectorServlet extends CMSServlet {
protected ILogger mSignedAuditLogger = CMS.getSignedAuditLogger();
private final static String SIGNED_AUDIT_PROTECTION_METHOD_SSL = "ssl";
private final static String SIGNED_AUDIT_PROTECTION_METHOD_UNKNOWN =
- "unknown";
+ "unknown";
private final static String LOGGING_SIGNED_AUDIT_INTER_BOUNDARY_SUCCESS =
- "LOGGING_SIGNED_AUDIT_INTER_BOUNDARY_SUCCESS_5";
+ "LOGGING_SIGNED_AUDIT_INTER_BOUNDARY_SUCCESS_5";
private final static String LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST =
- "LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST_5";
+ "LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST_5";
private final static String LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED =
- "LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED_5";
+ "LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED_5";
private final static byte EOL[] = { Character.LINE_SEPARATOR };
@@ -118,13 +116,13 @@ public class ConnectorServlet extends CMSServlet {
mAuthority = (IAuthority)
CMS.getSubsystem(authority);
mReqEncoder = CMS.getHttpRequestEncoder();
-
+
mAuthSubsystem = (IAuthSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_AUTH);
}
- public void service(HttpServletRequest request,
- HttpServletResponse response)
- throws ServletException, IOException {
+ public void service(HttpServletRequest request,
+ HttpServletResponse response)
+ throws ServletException, IOException {
boolean running_state = CMS.isInRunningState();
@@ -163,14 +161,14 @@ public class ConnectorServlet extends CMSServlet {
IRequest r = null;
IRequest reply = null;
- // NOTE must read all bufer before redoing handshake for
+ // NOTE must read all bufer before redoing handshake for
// ssl client auth for client auth to work.
// get request method
- method = req.getMethod();
+ method = req.getMethod();
// get content length
- len = request.getContentLength();
+ len = request.getContentLength();
// get content, a base 64 encoded serialized request.
if (len > 0) {
@@ -191,16 +189,16 @@ public class ConnectorServlet extends CMSServlet {
}
// force client auth handshake, validate RA and get RA's Id.
- // NOTE must do this after all contents are read for ssl
- // redohandshake to work
+ // NOTE must do this after all contents are read for ssl
+ // redohandshake to work
X509Certificate peerCert;
try {
peerCert = getPeerCert(req);
- }catch (EBaseException e) {
- mAuthority.log(ILogger.LL_SECURITY,
- CMS.getLogMessage("CMSGW_HAS_NO_CLIENT_CERT"));
+ } catch (EBaseException e) {
+ mAuthority.log(ILogger.LL_SECURITY,
+ CMS.getLogMessage("CMSGW_HAS_NO_CLIENT_CERT"));
resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
@@ -211,7 +209,7 @@ public class ConnectorServlet extends CMSServlet {
return;
}
- // authenticate RA
+ // authenticate RA
String RA_Id = null;
String raUserId = null;
@@ -231,8 +229,8 @@ public class ConnectorServlet extends CMSServlet {
return;
}
- mAuthority.log(ILogger.LL_INFO,
- "Remote Authority authenticated: " + peerCert.getSubjectDN());
+ mAuthority.log(ILogger.LL_INFO,
+ "Remote Authority authenticated: " + peerCert.getSubjectDN());
// authorize
AuthzToken authzToken = null;
@@ -265,20 +263,20 @@ public class ConnectorServlet extends CMSServlet {
try {
// decode request.
msg = (IPKIMessage) mReqEncoder.decode(encodedreq);
- // process request
+ // process request
replymsg = processRequest(RA_Id, raUserId, msg, token);
} catch (IOException e) {
CMS.debug("ConnectorServlet: service " + e.toString());
CMS.debug(e);
- mAuthority.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_IO_ERROR_REMOTE_REQUEST", e.toString()));
+ mAuthority.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_IO_ERROR_REMOTE_REQUEST", e.toString()));
resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
} catch (EBaseException e) {
CMS.debug("ConnectorServlet: service " + e.toString());
CMS.debug(e);
- mAuthority.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_IO_ERROR_REMOTE_REQUEST", e.toString()));
+ mAuthority.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_IO_ERROR_REMOTE_REQUEST", e.toString()));
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
} catch (Exception e) {
@@ -288,7 +286,7 @@ public class ConnectorServlet extends CMSServlet {
CMS.debug("ConnectorServlet: done processRequest");
- // encode reply
+ // encode reply
try {
String encodedrep = mReqEncoder.encode(replymsg);
@@ -328,8 +326,8 @@ public class ConnectorServlet extends CMSServlet {
try {
info = request.getExtDataInCertInfo(IEnrollProfile.REQUEST_CERTINFO);
- // request.set(IEnrollProfile.REQUEST_SEQ_NUM, new Integer("0"));
- CertificateX509Key certKey = (CertificateX509Key)info.get(X509CertInfo.KEY);
+ // request.set(IEnrollProfile.REQUEST_SEQ_NUM, new Integer("0"));
+ CertificateX509Key certKey = (CertificateX509Key) info.get(X509CertInfo.KEY);
if (certKey != null) {
byteStream = new ByteArrayOutputStream();
certKey.encode(byteStream);
@@ -369,16 +367,16 @@ public class ConnectorServlet extends CMSServlet {
certAlgOut.toByteArray());
}
} catch (Exception e) {
- CMS.debug("ConnectorServlet: profile normalization " +
- e.toString());
+ CMS.debug("ConnectorServlet: profile normalization " +
+ e.toString());
}
String profileId = request.getExtDataInString("profileId");
IProfileSubsystem ps = (IProfileSubsystem)
- CMS.getSubsystem("profile");
+ CMS.getSubsystem("profile");
IEnrollProfile profile = null;
- // profile subsystem may not be available. In case of KRA for
+ // profile subsystem may not be available. In case of KRA for
// example
if (ps == null) {
CMS.debug("ConnectorServlet: Profile Subsystem not found ");
@@ -399,15 +397,15 @@ public class ConnectorServlet extends CMSServlet {
/**
* Process request
* <P>
- *
+ *
* (Certificate Request - all "agent" profile cert requests made through a
- * connector)
+ * connector)
* <P>
- *
- * (Certificate Request Processed - all automated "agent" profile based
- * cert acceptance made through a connector)
+ *
+ * (Certificate Request Processed - all automated "agent" profile based cert
+ * acceptance made through a connector)
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST used when a
* profile cert request is made (before approval process)
@@ -417,6 +415,7 @@ public class ConnectorServlet extends CMSServlet {
* inter-CIMC_Boundary data transfer is successful (this is used when data
* does not need to be captured)
* </ul>
+ *
* @param source string containing source
* @param sourceUserId string containing source user ID
* @param msg PKI message
@@ -425,8 +424,8 @@ public class ConnectorServlet extends CMSServlet {
* @return PKI message
*/
protected IPKIMessage processRequest(
- String source, String sourceUserId, IPKIMessage msg, IAuthToken token)
- throws EBaseException {
+ String source, String sourceUserId, IPKIMessage msg, IAuthToken token)
+ throws EBaseException {
String auditMessage = null;
String auditSubjectID = sourceUserId;
String auditProtectionMethod = SIGNED_AUDIT_PROTECTION_METHOD_SSL;
@@ -477,12 +476,12 @@ public class ConnectorServlet extends CMSServlet {
if (thisreq == null) {
// strange case.
String errormsg = "Cannot find request in request queue " +
- thisreqid;
+ thisreqid;
mAuthority.log(ILogger.LL_FAILURE,
- CMS.getLogMessage(
- "CMSGW_REQUEST_ID_NOT_FOUND_1",
- thisreqid.toString()));
+ CMS.getLogMessage(
+ "CMSGW_REQUEST_ID_NOT_FOUND_1",
+ thisreqid.toString()));
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -495,14 +494,14 @@ public class ConnectorServlet extends CMSServlet {
audit(auditMessage);
- // NOTE: The signed audit event
- // LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST
- // does not yet matter at this point!
+ // NOTE: The signed audit event
+ // LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST
+ // does not yet matter at this point!
throw new EBaseException(errormsg);
} else {
- mAuthority.log(ILogger.LL_INFO,
- "Found request " + thisreqid + " for " + srcid);
+ mAuthority.log(ILogger.LL_INFO,
+ "Found request " + thisreqid + " for " + srcid);
replymsg = CMS.getHttpPKIMessage();
replymsg.fromRequest(thisreq);
@@ -517,9 +516,9 @@ public class ConnectorServlet extends CMSServlet {
audit(auditMessage);
- // NOTE: The signed audit event
- // LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST
- // does not yet matter at this point!
+ // NOTE: The signed audit event
+ // LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST
+ // does not yet matter at this point!
return replymsg;
}
@@ -527,77 +526,77 @@ public class ConnectorServlet extends CMSServlet {
// if not found process request.
thisreq = queue.newRequest(msg.getReqType());
- CMS.debug("ConnectorServlet: created requestId=" +
- thisreq.getRequestId().toString());
+ CMS.debug("ConnectorServlet: created requestId=" +
+ thisreq.getRequestId().toString());
thisreq.setSourceId(srcid);
- // NOTE: For the following signed audit message, since we only
- // care about the "msg.toRequest( thisreq );" command, and
- // since this command does not throw an EBaseException
- // (which is the only exception designated by this method),
- // then this code does NOT need to be contained within its
- // own special try/catch block.
- msg.toRequest( thisreq );
+ // NOTE: For the following signed audit message, since we only
+ // care about the "msg.toRequest( thisreq );" command, and
+ // since this command does not throw an EBaseException
+ // (which is the only exception designated by this method),
+ // then this code does NOT need to be contained within its
+ // own special try/catch block.
+ msg.toRequest(thisreq);
- if( isProfileRequest( thisreq ) ) {
+ if (isProfileRequest(thisreq)) {
X509CertInfo info =
thisreq.getExtDataInCertInfo(
- IEnrollProfile.REQUEST_CERTINFO );
+ IEnrollProfile.REQUEST_CERTINFO);
try {
- CertificateSubjectName sn = ( CertificateSubjectName )
- info.get( X509CertInfo.SUBJECT );
+ CertificateSubjectName sn = (CertificateSubjectName)
+ info.get(X509CertInfo.SUBJECT);
// if the cert subject name is NOT MISSING, retrieve the
// actual "auditCertificateSubjectName" and "normalize"
// it
- if( sn != null ) {
+ if (sn != null) {
subject = sn.toString();
- if( subject != null ) {
- // NOTE: This is ok even if the cert subject
- // name is "" (empty)!
+ if (subject != null) {
+ // NOTE: This is ok even if the cert subject
+ // name is "" (empty)!
auditCertificateSubjectName = subject.trim();
}
}
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST,
- auditSubjectID,
- ILogger.SUCCESS,
- auditRequesterID,
- auditProfileID(),
- auditCertificateSubjectName );
+ LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST,
+ auditSubjectID,
+ ILogger.SUCCESS,
+ auditRequesterID,
+ auditProfileID(),
+ auditCertificateSubjectName);
- audit( auditMessage );
- } catch( CertificateException e ) {
- CMS.debug( "ConnectorServlet: processRequest "
- + e.toString() );
+ audit(auditMessage);
+ } catch (CertificateException e) {
+ CMS.debug("ConnectorServlet: processRequest "
+ + e.toString());
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST,
- auditSubjectID,
- ILogger.FAILURE,
- auditRequesterID,
- auditProfileID(),
- auditCertificateSubjectName );
+ LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditRequesterID,
+ auditProfileID(),
+ auditCertificateSubjectName);
- audit( auditMessage );
- } catch( IOException e ) {
- CMS.debug( "ConnectorServlet: processRequest "
- + e.toString() );
+ audit(auditMessage);
+ } catch (IOException e) {
+ CMS.debug("ConnectorServlet: processRequest "
+ + e.toString());
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST,
- auditSubjectID,
- ILogger.FAILURE,
- auditRequesterID,
- auditProfileID(),
- auditCertificateSubjectName );
+ LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditRequesterID,
+ auditProfileID(),
+ auditCertificateSubjectName);
- audit( auditMessage );
+ audit(auditMessage);
}
}
@@ -606,9 +605,9 @@ public class ConnectorServlet extends CMSServlet {
// setting requestor type must come after copy contents. because
// requestor is a regular attribute.
thisreq.setExtData(IRequest.REQUESTOR_TYPE,
- IRequest.REQUESTOR_RA);
+ IRequest.REQUESTOR_RA);
mAuthority.log(ILogger.LL_INFO, "Processing remote request " +
- srcid);
+ srcid);
// Set this so that request's updateBy is recorded
SessionContext s = SessionContext.getContext();
@@ -622,52 +621,52 @@ public class ConnectorServlet extends CMSServlet {
}
CMS.debug("ConnectorServlet: calling processRequest instance=" +
- thisreq);
+ thisreq);
if (isProfileRequest(thisreq)) {
normalizeProfileRequest(thisreq);
}
try {
- queue.processRequest( thisreq );
+ queue.processRequest(thisreq);
- if( isProfileRequest( thisreq ) ) {
+ if (isProfileRequest(thisreq)) {
// reset the "auditInfoCertValue"
- auditInfoCertValue = auditInfoCertValue( thisreq );
+ auditInfoCertValue = auditInfoCertValue(thisreq);
- if( auditInfoCertValue != null ) {
- if( !( auditInfoCertValue.equals(
- ILogger.SIGNED_AUDIT_EMPTY_VALUE ) ) ) {
+ if (auditInfoCertValue != null) {
+ if (!(auditInfoCertValue.equals(
+ ILogger.SIGNED_AUDIT_EMPTY_VALUE))) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED,
- auditSubjectID,
- ILogger.SUCCESS,
- auditRequesterID,
- ILogger.SIGNED_AUDIT_ACCEPTANCE,
- auditInfoCertValue );
-
- audit( auditMessage );
+ LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED,
+ auditSubjectID,
+ ILogger.SUCCESS,
+ auditRequesterID,
+ ILogger.SIGNED_AUDIT_ACCEPTANCE,
+ auditInfoCertValue);
+
+ audit(auditMessage);
}
}
}
- } catch( EBaseException eAudit1 ) {
- if( isProfileRequest( thisreq ) ) {
+ } catch (EBaseException eAudit1) {
+ if (isProfileRequest(thisreq)) {
// reset the "auditInfoCertValue"
- auditInfoCertValue = auditInfoCertValue( thisreq );
+ auditInfoCertValue = auditInfoCertValue(thisreq);
- if( auditInfoCertValue != null ) {
- if( !( auditInfoCertValue.equals(
- ILogger.SIGNED_AUDIT_EMPTY_VALUE ) ) ) {
+ if (auditInfoCertValue != null) {
+ if (!(auditInfoCertValue.equals(
+ ILogger.SIGNED_AUDIT_EMPTY_VALUE))) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED,
- auditSubjectID,
- ILogger.FAILURE,
- auditRequesterID,
- ILogger.SIGNED_AUDIT_ACCEPTANCE,
- auditInfoCertValue );
-
- audit( auditMessage );
+ LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditRequesterID,
+ ILogger.SIGNED_AUDIT_ACCEPTANCE,
+ auditInfoCertValue);
+
+ audit(auditMessage);
}
}
}
@@ -681,23 +680,23 @@ public class ConnectorServlet extends CMSServlet {
replymsg.fromRequest(thisreq);
CMS.debug("ConnectorServlet: replymsg.reqStatus=" +
- replymsg.getReqStatus());
+ replymsg.getReqStatus());
- //for audit log
+ // for audit log
String agentID = sourceUserId;
String initiative = AuditFormat.FROMRA + " trustedManagerID: " +
- agentID + " remote reqID " + msg.getReqId();
+ agentID + " remote reqID " + msg.getReqId();
String authMgr = AuditFormat.NOAUTH;
if (token != null) {
- authMgr =
+ authMgr =
token.getInString(AuthToken.TOKEN_AUTHMGR_INST_NAME);
}
if (isProfileRequest(thisreq)) {
// XXX audit log
- CMS.debug("ConnectorServlet: done requestId=" +
- thisreq.getRequestId().toString());
+ CMS.debug("ConnectorServlet: done requestId=" +
+ thisreq.getRequestId().toString());
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -710,9 +709,9 @@ public class ConnectorServlet extends CMSServlet {
audit(auditMessage);
- // NOTE: The signed audit event
- // LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST
- // has already been logged at this point!
+ // NOTE: The signed audit event
+ // LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST
+ // has already been logged at this point!
return replymsg;
}
@@ -724,32 +723,32 @@ public class ConnectorServlet extends CMSServlet {
if (!thisreq.getRequestStatus().equals(RequestStatus.COMPLETE)) {
if (x509Info != null) {
for (int i = 0; i < x509Info.length; i++) {
- mLogger.log(ILogger.EV_AUDIT,
+ mLogger.log(ILogger.EV_AUDIT,
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.FORMAT,
+ new Object[] {
+ thisreq.getRequestType(),
+ thisreq.getRequestId(),
+ initiative,
+ authMgr,
+ thisreq.getRequestStatus(),
+ x509Info[i].get(X509CertInfo.SUBJECT),
+ "" }
+ );
+ }
+ } else {
+ mLogger.log(ILogger.EV_AUDIT,
ILogger.S_OTHER,
AuditFormat.LEVEL,
- AuditFormat.FORMAT,
+ AuditFormat.NODNFORMAT,
new Object[] {
- thisreq.getRequestType(),
- thisreq.getRequestId(),
- initiative,
- authMgr,
- thisreq.getRequestStatus(),
- x509Info[i].get(X509CertInfo.SUBJECT),
- ""}
- );
- }
- } else {
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.NODNFORMAT,
- new Object[] {
- thisreq.getRequestType(),
- thisreq.getRequestId(),
- initiative,
- authMgr,
- thisreq.getRequestStatus()}
- );
+ thisreq.getRequestType(),
+ thisreq.getRequestId(),
+ initiative,
+ authMgr,
+ thisreq.getRequestStatus() }
+ );
}
} else {
if (thisreq.getRequestType().equals(IRequest.ENROLLMENT_REQUEST)) {
@@ -761,40 +760,40 @@ public class ConnectorServlet extends CMSServlet {
x509Certs =
thisreq.getExtDataInCertArray(IRequest.ISSUED_CERTS);
- // return potentially more than one certificates.
+ // return potentially more than one certificates.
if (x509Certs != null) {
for (int i = 0; i < x509Certs.length; i++) {
- mLogger.log(ILogger.EV_AUDIT,
+ mLogger.log(ILogger.EV_AUDIT,
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.FORMAT,
+ new Object[] {
+ thisreq.getRequestType(),
+ thisreq.getRequestId(),
+ initiative,
+ authMgr,
+ "completed",
+ x509Certs[i].getSubjectDN(),
+ "cert issued serial number: 0x" +
+ x509Certs[i].getSerialNumber().toString(16) }
+ );
+ }
+ } else {
+ mLogger.log(ILogger.EV_AUDIT,
ILogger.S_OTHER,
AuditFormat.LEVEL,
- AuditFormat.FORMAT,
+ AuditFormat.NODNFORMAT,
new Object[] {
- thisreq.getRequestType(),
- thisreq.getRequestId(),
- initiative,
- authMgr,
- "completed",
- x509Certs[i].getSubjectDN(),
- "cert issued serial number: 0x" +
- x509Certs[i].getSerialNumber().toString(16)}
- );
- }
- } else {
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.NODNFORMAT,
- new Object[] {
- thisreq.getRequestType(),
- thisreq.getRequestId(),
- initiative,
- authMgr,
- "completed"}
- );
+ thisreq.getRequestType(),
+ thisreq.getRequestId(),
+ initiative,
+ authMgr,
+ "completed" }
+ );
}
} else if (thisreq.getRequestType().equals(IRequest.RENEWAL_REQUEST)) {
X509CertImpl[] certs =
- thisreq.getExtDataInCertArray(IRequest.OLD_CERTS);
+ thisreq.getExtDataInCertArray(IRequest.OLD_CERTS);
X509CertImpl old_cert = certs[0];
certs = thisreq.getExtDataInCertArray(IRequest.ISSUED_CERTS);
@@ -802,36 +801,36 @@ public class ConnectorServlet extends CMSServlet {
if (old_cert != null && renewed_cert != null) {
mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.RENEWALFORMAT,
- new Object[] {
- thisreq.getRequestId(),
- initiative,
- authMgr,
- "completed",
- old_cert.getSubjectDN(),
- old_cert.getSerialNumber().toString(16),
- "new serial number: 0x" +
- renewed_cert.getSerialNumber().toString(16)}
- );
+ AuditFormat.LEVEL,
+ AuditFormat.RENEWALFORMAT,
+ new Object[] {
+ thisreq.getRequestId(),
+ initiative,
+ authMgr,
+ "completed",
+ old_cert.getSubjectDN(),
+ old_cert.getSerialNumber().toString(16),
+ "new serial number: 0x" +
+ renewed_cert.getSerialNumber().toString(16) }
+ );
} else {
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.NODNFORMAT,
- new Object[] {
- thisreq.getRequestType(),
- thisreq.getRequestId(),
- initiative,
- authMgr,
- "completed with error"}
- );
+ mLogger.log(ILogger.EV_AUDIT,
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.NODNFORMAT,
+ new Object[] {
+ thisreq.getRequestType(),
+ thisreq.getRequestId(),
+ initiative,
+ authMgr,
+ "completed with error" }
+ );
}
} else if (thisreq.getRequestType().equals(IRequest.REVOCATION_REQUEST)) {
Certificate[] oldCerts =
- thisreq.getExtDataInCertArray(IRequest.OLD_CERTS);
+ thisreq.getExtDataInCertArray(IRequest.OLD_CERTS);
RevokedCertImpl crlentries[] =
- thisreq.getExtDataInRevokedCertArray(IRequest.REVOKED_CERTS);
+ thisreq.getExtDataInRevokedCertArray(IRequest.REVOKED_CERTS);
CRLExtensions crlExts = crlentries[0].getExtensions();
int reason = 0;
@@ -839,7 +838,7 @@ public class ConnectorServlet extends CMSServlet {
Enumeration<Extension> enum1 = crlExts.getElements();
while (enum1.hasMoreElements()) {
- Extension ext = enum1.nextElement();
+ Extension ext = enum1.nextElement();
if (ext instanceof CRLReasonExtension) {
reason = ((CRLReasonExtension) ext).getReason().toInt();
@@ -853,7 +852,7 @@ public class ConnectorServlet extends CMSServlet {
if (result.equals(IRequest.RES_ERROR)) {
String[] svcErrors =
- thisreq.getExtDataInStringArray(IRequest.SVCERRORS);
+ thisreq.getExtDataInStringArray(IRequest.SVCERRORS);
if (svcErrors != null && svcErrors.length > 0) {
for (int i = 0; i < svcErrors.length; i++) {
@@ -866,18 +865,18 @@ public class ConnectorServlet extends CMSServlet {
X509CertImpl cert = (X509CertImpl) oldCerts[j];
mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.DOREVOKEFORMAT,
- new Object[] {
- thisreq.getRequestId(),
- initiative,
- "completed with error: " +
- err,
- cert.getSubjectDN(),
- cert.getSerialNumber().toString(16),
- RevocationReason.fromInt(reason).toString()}
- );
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.DOREVOKEFORMAT,
+ new Object[] {
+ thisreq.getRequestId(),
+ initiative,
+ "completed with error: " +
+ err,
+ cert.getSubjectDN(),
+ cert.getSerialNumber().toString(16),
+ RevocationReason.fromInt(reason).toString() }
+ );
}
}
}
@@ -892,32 +891,32 @@ public class ConnectorServlet extends CMSServlet {
X509CertImpl cert = (X509CertImpl) oldCerts[j];
mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.DOREVOKEFORMAT,
- new Object[] {
- thisreq.getRequestId(),
- initiative,
- "completed",
- cert.getSubjectDN(),
- cert.getSerialNumber().toString(16),
- RevocationReason.fromInt(reason).toString()}
- );
+ AuditFormat.LEVEL,
+ AuditFormat.DOREVOKEFORMAT,
+ new Object[] {
+ thisreq.getRequestId(),
+ initiative,
+ "completed",
+ cert.getSubjectDN(),
+ cert.getSerialNumber().toString(16),
+ RevocationReason.fromInt(reason).toString() }
+ );
}
}
}
}
} else {
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.NODNFORMAT,
- new Object[] {
- thisreq.getRequestType(),
- thisreq.getRequestId(),
- initiative,
- authMgr,
- "completed"}
- );
+ mLogger.log(ILogger.EV_AUDIT,
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.NODNFORMAT,
+ new Object[] {
+ thisreq.getRequestType(),
+ thisreq.getRequestId(),
+ initiative,
+ authMgr,
+ "completed" }
+ );
}
}
@@ -974,9 +973,9 @@ public class ConnectorServlet extends CMSServlet {
SessionContext.releaseContext();
}
- // NOTE: The signed audit event
- // LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST
- // has already been logged at this point!
+ // NOTE: The signed audit event
+ // LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST
+ // has already been logged at this point!
return replymsg;
} catch (EBaseException e) {
@@ -991,17 +990,17 @@ public class ConnectorServlet extends CMSServlet {
audit(auditMessage);
- // NOTE: The signed audit event
- // LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST
- // has either already been logged, or
- // does not yet matter at this point!
+ // NOTE: The signed audit event
+ // LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST
+ // has either already been logged, or
+ // does not yet matter at this point!
return replymsg;
}
}
protected X509Certificate
- getPeerCert(HttpServletRequest req) throws EBaseException {
+ getPeerCert(HttpServletRequest req) throws EBaseException {
return getSSLClientCertificate(req);
}
@@ -1011,11 +1010,11 @@ public class ConnectorServlet extends CMSServlet {
/**
* Signed Audit Log
- *
- * This method is inherited by all extended "CMSServlet"s,
- * and is called to store messages to the signed audit log.
+ *
+ * This method is inherited by all extended "CMSServlet"s, and is called to
+ * store messages to the signed audit log.
* <P>
- *
+ *
* @param msg signed audit log message
*/
protected void audit(String msg) {
@@ -1027,20 +1026,19 @@ public class ConnectorServlet extends CMSServlet {
}
mSignedAuditLogger.log(ILogger.EV_SIGNED_AUDIT,
- null,
- ILogger.S_SIGNED_AUDIT,
- ILogger.LL_SECURITY,
- msg);
+ null,
+ ILogger.S_SIGNED_AUDIT,
+ ILogger.LL_SECURITY,
+ msg);
}
/**
* Signed Audit Log Profile ID
- *
- * This method is inherited by all extended "EnrollProfile"s,
- * and is called to obtain the "ProfileID" for
- * a signed audit log message.
+ *
+ * This method is inherited by all extended "EnrollProfile"s, and is called
+ * to obtain the "ProfileID" for a signed audit log message.
* <P>
- *
+ *
* @return id string containing the signed audit log message ProfileID
*/
protected String auditProfileID() {
@@ -1062,11 +1060,11 @@ public class ConnectorServlet extends CMSServlet {
/**
* Signed Audit Log Info Certificate Value
- *
+ *
* This method is called to obtain the certificate from the passed in
* "X509CertImpl" for a signed audit log message.
* <P>
- *
+ *
* @param request a Request containing an X509CertImpl
* @return cert string containing the certificate
*/
@@ -1122,4 +1120,3 @@ public class ConnectorServlet extends CMSServlet {
}
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/connector/GenerateKeyPairServlet.java b/pki/base/common/src/com/netscape/cms/servlet/connector/GenerateKeyPairServlet.java
index 2a024c3a..7c5f1fea 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/connector/GenerateKeyPairServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/connector/GenerateKeyPairServlet.java
@@ -40,17 +40,14 @@ import com.netscape.certsrv.request.IRequestQueue;
import com.netscape.cms.servlet.base.CMSServlet;
import com.netscape.cms.servlet.common.CMSRequest;
-
-
/**
- * GenerateKeyPairServlet
- * handles "server-side key pair generation" requests from the
- * netkey RA.
- *
+ * GenerateKeyPairServlet handles "server-side key pair generation" requests
+ * from the netkey RA.
+ *
* @author Christina Fu (cfu)
* @version $Revision$, $Date$
*/
-//XXX add auditing later
+// XXX add auditing later
public class GenerateKeyPairServlet extends CMSServlet {
/**
@@ -68,7 +65,7 @@ public class GenerateKeyPairServlet extends CMSServlet {
/**
* Constructs GenerateKeyPair servlet.
- *
+ *
*/
public GenerateKeyPairServlet() {
super();
@@ -82,35 +79,29 @@ public class GenerateKeyPairServlet extends CMSServlet {
if (authority != null)
mAuthority = (IAuthority)
CMS.getSubsystem(authority);
-
+
mAuthSubsystem = (IAuthSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_AUTH);
}
/**
* Returns serlvet information.
- *
+ *
* @return name of this servlet
*/
- public String getServletInfo() {
- return INFO;
+ public String getServletInfo() {
+ return INFO;
}
/*
- * processServerSideKeyGen -
- * handles netkey DRM serverside keygen.
- * netkey operations:
- * 1. generate keypair (archive user priv key)
- * 2. unwrap des key with transport key, then url decode it
- * 3. wrap user priv key with des key
- * 4. send the following to RA:
- * * des key wrapped(user priv key)
- * * user public key
- * (note: RA should have kek-wrapped des key from TKS)
- * * recovery blob (used for recovery)
+ * processServerSideKeyGen - handles netkey DRM serverside keygen. netkey
+ * operations: 1. generate keypair (archive user priv key) 2. unwrap des key
+ * with transport key, then url decode it 3. wrap user priv key with des key
+ * 4. send the following to RA: * des key wrapped(user priv key) * user
+ * public key (note: RA should have kek-wrapped des key from TKS) * recovery
+ * blob (used for recovery)
*/
private void processServerSideKeyGen(HttpServletRequest req,
- HttpServletResponse resp) throws EBaseException
- {
+ HttpServletResponse resp) throws EBaseException {
IRequestQueue queue = mAuthority.getRequestQueue();
IRequest thisreq = null;
@@ -123,8 +114,8 @@ public class GenerateKeyPairServlet extends CMSServlet {
String rCUID = req.getParameter("CUID");
String rUserid = req.getParameter("userid");
String rdesKeyString = req.getParameter("drm_trans_desKey");
- String rArchive = req.getParameter("archive");
- String rKeysize = req.getParameter("keysize");
+ String rArchive = req.getParameter("archive");
+ String rKeysize = req.getParameter("keysize");
if ((rCUID == null) || (rCUID.equals(""))) {
CMS.debug("GenerateKeyPairServlet: processServerSideKeygen(): missing request parameter: CUID");
@@ -136,19 +127,19 @@ public class GenerateKeyPairServlet extends CMSServlet {
missingParam = true;
}
- if ((rKeysize == null) || (rKeysize.equals(""))) {
- rKeysize = "1024"; // default to 1024
- }
+ if ((rKeysize == null) || (rKeysize.equals(""))) {
+ rKeysize = "1024"; // default to 1024
+ }
if ((rdesKeyString == null) ||
- (rdesKeyString.equals(""))) {
+ (rdesKeyString.equals(""))) {
CMS.debug("GenerateKeyPairServlet: processServerSideKeygen(): missing request parameter: DRM-transportKey-wrapped DES key");
missingParam = true;
}
if ((rArchive == null) || (rArchive.equals(""))) {
CMS.debug("GenerateKeyPairServlet: processServerSideKeygen(): missing key archival flag 'archive' ,default to true");
- rArchive = "true";
+ rArchive = "true";
}
String selectedToken = null;
@@ -160,17 +151,17 @@ public class GenerateKeyPairServlet extends CMSServlet {
thisreq.setExtData(IRequest.NETKEY_ATTR_CUID, rCUID);
thisreq.setExtData(IRequest.NETKEY_ATTR_USERID, rUserid);
thisreq.setExtData(IRequest.NETKEY_ATTR_DRMTRANS_DES_KEY, rdesKeyString);
- thisreq.setExtData(IRequest.NETKEY_ATTR_ARCHIVE_FLAG, rArchive);
- thisreq.setExtData(IRequest.NETKEY_ATTR_KEY_SIZE, rKeysize);
+ thisreq.setExtData(IRequest.NETKEY_ATTR_ARCHIVE_FLAG, rArchive);
+ thisreq.setExtData(IRequest.NETKEY_ATTR_KEY_SIZE, rKeysize);
- queue.processRequest( thisreq );
+ queue.processRequest(thisreq);
Integer result = thisreq.getExtDataInInteger(IRequest.RESULT);
if (result != null) {
- // sighs! tps thinks 0 is good, and DRM thinks 1 is good
- if (result.intValue() == 1)
- status = "0";
- else
- status = result.toString();
+ // sighs! tps thinks 0 is good, and DRM thinks 1 is good
+ if (result.intValue() == 1)
+ status = "0";
+ else
+ status = result.toString();
} else
status = "7";
@@ -184,40 +175,39 @@ public class GenerateKeyPairServlet extends CMSServlet {
String wrappedPrivKeyString = "";
String publicKeyString = "";
- if( thisreq == null ) {
- CMS.debug( "GenerateKeyPairServlet::processServerSideKeyGen() - "
- + "thisreq is null!" );
- throw new EBaseException( "thisreq is null" );
+ if (thisreq == null) {
+ CMS.debug("GenerateKeyPairServlet::processServerSideKeyGen() - "
+ + "thisreq is null!");
+ throw new EBaseException("thisreq is null");
}
publicKeyString = thisreq.getExtDataInString("public_key");
wrappedPrivKeyString = thisreq.getExtDataInString("wrappedUserPrivate");
- String ivString = thisreq.getExtDataInString("iv_s");
+ String ivString = thisreq.getExtDataInString("iv_s");
/*
- if (selectedToken == null)
- status = "4";
- */
- if (!status.equals("0"))
- value = "status="+status;
+ * if (selectedToken == null) status = "4";
+ */
+ if (!status.equals("0"))
+ value = "status=" + status;
else {
StringBuffer sb = new StringBuffer();
sb.append("status=0&");
- sb.append("wrapped_priv_key=");
- sb.append(wrappedPrivKeyString);
- sb.append("&iv_param=");
- sb.append(ivString);
+ sb.append("wrapped_priv_key=");
+ sb.append(wrappedPrivKeyString);
+ sb.append("&iv_param=");
+ sb.append(ivString);
sb.append("&public_key=");
- sb.append(publicKeyString);
+ sb.append(publicKeyString);
value = sb.toString();
}
- CMS.debug("processServerSideKeyGen:outputString.encode " +value);
+ CMS.debug("processServerSideKeyGen:outputString.encode " + value);
- try{
+ try {
resp.setContentLength(value.length());
- CMS.debug("GenerateKeyPairServlet:outputString.length " +value.length());
+ CMS.debug("GenerateKeyPairServlet:outputString.length " + value.length());
OutputStream ooss = resp.getOutputStream();
ooss.write(value.getBytes());
ooss.flush();
@@ -227,20 +217,14 @@ public class GenerateKeyPairServlet extends CMSServlet {
}
}
-
- /*
-
- * For GenerateKeyPair:
- *
- * input:
- * CUID=value0
- * trans-wrapped-desKey=value1
- *
- * output:
- * status=value0
- * publicKey=value1
- * desKey-wrapped-userPrivateKey=value2
- * proofOfArchival=value3
+ /*
+ *
+ * For GenerateKeyPair:
+ *
+ * input: CUID=value0 trans-wrapped-desKey=value1
+ *
+ * output: status=value0 publicKey=value1
+ * desKey-wrapped-userPrivateKey=value2 proofOfArchival=value3
*/
public void process(CMSRequest cmsReq) throws EBaseException {
@@ -258,7 +242,7 @@ public class GenerateKeyPairServlet extends CMSServlet {
if (authzToken == null) {
- try{
+ try {
resp.setContentType("text/html");
String value = "unauthorized=";
CMS.debug("GenerateKeyPairServlet: Unauthorized");
@@ -268,7 +252,7 @@ public class GenerateKeyPairServlet extends CMSServlet {
ooss.write(value.getBytes());
ooss.flush();
mRenderResult = false;
- }catch (Exception e) {
+ } catch (Exception e) {
CMS.debug("GenerateKeyPairServlet: " + e.toString());
}
@@ -277,28 +261,28 @@ public class GenerateKeyPairServlet extends CMSServlet {
}
// begin Netkey serverSideKeyGen and archival
- CMS.debug("GenerateKeyPairServlet: processServerSideKeyGen would be called");
- processServerSideKeyGen(req, resp);
- return;
+ CMS.debug("GenerateKeyPairServlet: processServerSideKeyGen would be called");
+ processServerSideKeyGen(req, resp);
+ return;
// end Netkey functions
}
- /** XXX remember tocheck peer SSL cert and get RA id later
- *
+ /**
+ * XXX remember tocheck peer SSL cert and get RA id later
+ *
* Serves HTTP admin request.
- *
+ *
* @param req HTTP request
* @param resp HTTP response
*/
public void service(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
+ throws ServletException, IOException {
String scope = req.getParameter(Constants.OP_SCOPE);
String op = req.getParameter(Constants.OP_TYPE);
- super.service(req, resp);
+ super.service(req, resp);
-
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/connector/TokenKeyRecoveryServlet.java b/pki/base/common/src/com/netscape/cms/servlet/connector/TokenKeyRecoveryServlet.java
index fa454bd6..758fb423 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/connector/TokenKeyRecoveryServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/connector/TokenKeyRecoveryServlet.java
@@ -39,16 +39,14 @@ import com.netscape.certsrv.request.IRequestQueue;
import com.netscape.cms.servlet.base.CMSServlet;
import com.netscape.cms.servlet.common.CMSRequest;
-
/**
- * TokenKeyRecoveryServlet
- * handles "key recovery service" requests from the
+ * TokenKeyRecoveryServlet handles "key recovery service" requests from the
* netkey TPS
- *
+ *
* @author Christina Fu (cfu)
* @version $Revision$, $Date$
*/
-//XXX add auditing later
+// XXX add auditing later
public class TokenKeyRecoveryServlet extends CMSServlet {
/**
@@ -65,7 +63,7 @@ public class TokenKeyRecoveryServlet extends CMSServlet {
/**
* Constructs TokenKeyRecovery servlet.
- *
+ *
*/
public TokenKeyRecoveryServlet() {
super();
@@ -79,25 +77,25 @@ public class TokenKeyRecoveryServlet extends CMSServlet {
if (authority != null)
mAuthority = (IAuthority)
CMS.getSubsystem(authority);
-
+
mAuthSubsystem = (IAuthSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_AUTH);
}
/**
* Returns serlvet information.
- *
+ *
* @return name of this servlet
*/
- public String getServletInfo() {
- return INFO;
+ public String getServletInfo() {
+ return INFO;
}
- /**
+ /**
* Process the HTTP request.
- *
+ *
* @param s The URL to decode
*/
- protected String URLdecode(String s) {
+ protected String URLdecode(String s) {
if (s == null)
return null;
ByteArrayOutputStream out = new ByteArrayOutputStream(s.length());
@@ -117,39 +115,30 @@ public class TokenKeyRecoveryServlet extends CMSServlet {
}
} // end for
return out.toString();
- }
+ }
/*
- * processTokenKeyRecovery
- * handles netkey key recovery requests
- * input params are:
- * CUID - the CUID of the old token where the keys/certs were initially for
- * userid - the userid that belongs to both the old token and the new token
- * drm_trans_desKey - the des key generated for the NEW token
- * wrapped with DRM transport key
- * cert - the user cert corresponding to the key to be recovered
- *
- * operations:
- * 1. unwrap des key with transport key, then url decode it
- * 2. retrieve user private key
- * 3. wrap user priv key with des key
- * 4. send the following to RA:
- * * des key wrapped(user priv key)
- * (note: RA should have kek-wrapped des key from TKS)
- * * recovery blob (used for recovery)
- *
- * output params are:
- * status=value0
- * publicKey=value1
- * desKey-wrapped-userPrivateKey=value2
+ * processTokenKeyRecovery handles netkey key recovery requests input params
+ * are: CUID - the CUID of the old token where the keys/certs were initially
+ * for userid - the userid that belongs to both the old token and the new
+ * token drm_trans_desKey - the des key generated for the NEW token wrapped
+ * with DRM transport key cert - the user cert corresponding to the key to
+ * be recovered
+ *
+ * operations: 1. unwrap des key with transport key, then url decode it 2.
+ * retrieve user private key 3. wrap user priv key with des key 4. send the
+ * following to RA: * des key wrapped(user priv key) (note: RA should have
+ * kek-wrapped des key from TKS) * recovery blob (used for recovery)
+ *
+ * output params are: status=value0 publicKey=value1
+ * desKey-wrapped-userPrivateKey=value2
*/
private void processTokenKeyRecovery(HttpServletRequest req,
- HttpServletResponse resp) throws EBaseException
- {
+ HttpServletResponse resp) throws EBaseException {
IRequestQueue queue = mAuthority.getRequestQueue();
IRequest thisreq = null;
-
- // IConfigStore sconfig = CMS.getConfigStore();
+
+ // IConfigStore sconfig = CMS.getConfigStore();
boolean missingParam = false;
String status = "0";
@@ -158,7 +147,7 @@ public class TokenKeyRecoveryServlet extends CMSServlet {
String rCUID = req.getParameter("CUID");
String rUserid = req.getParameter("userid");
String rdesKeyString = req.getParameter("drm_trans_desKey");
- String rCert = req.getParameter("cert");
+ String rCert = req.getParameter("cert");
if ((rCUID == null) || (rCUID.equals(""))) {
CMS.debug("TokenKeyRecoveryServlet: processTokenKeyRecovery(): missing request parameter: CUID");
@@ -171,7 +160,7 @@ public class TokenKeyRecoveryServlet extends CMSServlet {
}
if ((rdesKeyString == null) ||
- (rdesKeyString.equals(""))) {
+ (rdesKeyString.equals(""))) {
CMS.debug("TokenKeyRecoveryServlet: processTokenKeyRecovery(): missing request parameter: DRM-transportKey-wrapped des key");
missingParam = true;
}
@@ -192,18 +181,18 @@ public class TokenKeyRecoveryServlet extends CMSServlet {
thisreq.setExtData(IRequest.NETKEY_ATTR_DRMTRANS_DES_KEY, rdesKeyString);
thisreq.setExtData(IRequest.NETKEY_ATTR_USER_CERT, rCert);
- //XXX auto process for netkey
- queue.processRequest( thisreq );
- // IService svc = (IService) new TokenKeyRecoveryService(kra);
- // svc.serviceRequest(thisreq);
+ // XXX auto process for netkey
+ queue.processRequest(thisreq);
+ // IService svc = (IService) new TokenKeyRecoveryService(kra);
+ // svc.serviceRequest(thisreq);
Integer result = thisreq.getExtDataInInteger(IRequest.RESULT);
if (result != null) {
- // sighs! tps thinks 0 is good, and drm thinks 1 is good
- if (result.intValue() == 1)
- status ="0";
- else
- status = result.toString();
+ // sighs! tps thinks 0 is good, and drm thinks 1 is good
+ if (result.intValue() == 1)
+ status = "0";
+ else
+ status = result.toString();
} else
status = "7";
@@ -218,25 +207,25 @@ public class TokenKeyRecoveryServlet extends CMSServlet {
String wrappedPrivKeyString = "";
String publicKeyString = "";
String ivString = "";
- /* if is RECOVERY_PROTOTYPE
- String recoveryBlobString = "";
-
- IKeyRecord kr = (IKeyRecord) thisreq.get("keyRecord");
- byte publicKey_b[] = kr.getPublicKeyData();
-
- BigInteger serialNo = kr.getSerialNumber();
-
- String serialNumberString =
- com.netscape.cmsutil.util.Utils.SpecialEncode(serialNo.toByteArray());
-
- recoveryBlobString = (String)
- thisreq.get("recoveryBlob");
- */
-
- if( thisreq == null ) {
- CMS.debug( "TokenKeyRecoveryServlet::processTokenKeyRecovery() - "
- + "thisreq is null!" );
- throw new EBaseException( "thisreq is null" );
+ /*
+ * if is RECOVERY_PROTOTYPE String recoveryBlobString = "";
+ *
+ * IKeyRecord kr = (IKeyRecord) thisreq.get("keyRecord"); byte
+ * publicKey_b[] = kr.getPublicKeyData();
+ *
+ * BigInteger serialNo = kr.getSerialNumber();
+ *
+ * String serialNumberString =
+ * com.netscape.cmsutil.util.Utils.SpecialEncode
+ * (serialNo.toByteArray());
+ *
+ * recoveryBlobString = (String) thisreq.get("recoveryBlob");
+ */
+
+ if (thisreq == null) {
+ CMS.debug("TokenKeyRecoveryServlet::processTokenKeyRecovery() - "
+ + "thisreq is null!");
+ throw new EBaseException("thisreq is null");
}
publicKeyString = thisreq.getExtDataInString("public_key");
@@ -244,11 +233,10 @@ public class TokenKeyRecoveryServlet extends CMSServlet {
ivString = thisreq.getExtDataInString("iv_s");
/*
- if (selectedToken == null)
- status = "4";
- */
- if (!status.equals("0"))
- value = "status="+status;
+ * if (selectedToken == null) status = "4";
+ */
+ if (!status.equals("0"))
+ value = "status=" + status;
else {
StringBuffer sb = new StringBuffer();
sb.append("status=0&");
@@ -259,13 +247,13 @@ public class TokenKeyRecoveryServlet extends CMSServlet {
sb.append("&iv_param=");
sb.append(ivString);
value = sb.toString();
-
+
}
- CMS.debug("ProcessTokenKeyRecovery:outputString.encode " +value);
+ CMS.debug("ProcessTokenKeyRecovery:outputString.encode " + value);
- try{
+ try {
resp.setContentLength(value.length());
- CMS.debug("TokenKeyRecoveryServlet:outputString.length " +value.length());
+ CMS.debug("TokenKeyRecoveryServlet:outputString.length " + value.length());
OutputStream ooss = resp.getOutputStream();
ooss.write(value.getBytes());
ooss.flush();
@@ -275,19 +263,13 @@ public class TokenKeyRecoveryServlet extends CMSServlet {
}
}
-
- /*
- * For TokenKeyRecovery
- *
- * input:
- * CUID=value0
- * trans-wrapped-desKey=value1
- *
- * output:
- * status=value0
- * publicKey=value1
- * desKey-wrapped-userPrivateKey=value2
- * proofOfArchival=value3
+ /*
+ * For TokenKeyRecovery
+ *
+ * input: CUID=value0 trans-wrapped-desKey=value1
+ *
+ * output: status=value0 publicKey=value1
+ * desKey-wrapped-userPrivateKey=value2 proofOfArchival=value3
*/
public void process(CMSRequest cmsReq) throws EBaseException {
@@ -305,7 +287,7 @@ public class TokenKeyRecoveryServlet extends CMSServlet {
if (authzToken == null) {
- try{
+ try {
resp.setContentType("text/html");
String value = "unauthorized=";
CMS.debug("TokenKeyRecoveryServlet: Unauthorized");
@@ -315,7 +297,7 @@ public class TokenKeyRecoveryServlet extends CMSServlet {
ooss.write(value.getBytes());
ooss.flush();
mRenderResult = false;
- }catch (Exception e) {
+ } catch (Exception e) {
CMS.debug("TokenKeyRecoveryServlet: " + e.toString());
}
@@ -324,28 +306,28 @@ public class TokenKeyRecoveryServlet extends CMSServlet {
}
// begin Netkey serverSideKeyGen and archival
- CMS.debug("TokenKeyRecoveryServlet: processTokenKeyRecovery would be called");
- processTokenKeyRecovery(req, resp);
- return;
+ CMS.debug("TokenKeyRecoveryServlet: processTokenKeyRecovery would be called");
+ processTokenKeyRecovery(req, resp);
+ return;
// end Netkey functions
}
- /** XXX remember to check peer SSL cert and get RA id later
- *
+ /**
+ * XXX remember to check peer SSL cert and get RA id later
+ *
* Serves HTTP admin request.
- *
+ *
* @param req HTTP request
* @param resp HTTP response
*/
public void service(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
+ throws ServletException, IOException {
String scope = req.getParameter(Constants.OP_SCOPE);
String op = req.getParameter(Constants.OP_TYPE);
- super.service(req, resp);
+ super.service(req, resp);
-
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/AdminAuthenticatePanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/AdminAuthenticatePanel.java
index a2509287..8482e71b 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/AdminAuthenticatePanel.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/AdminAuthenticatePanel.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.IOException;
import java.util.StringTokenizer;
@@ -41,19 +40,20 @@ import com.netscape.cms.servlet.wizard.WizardServlet;
public class AdminAuthenticatePanel extends WizardPanelBase {
- public AdminAuthenticatePanel() {}
+ public AdminAuthenticatePanel() {
+ }
/**
* Initializes this panel.
*/
- public void init(ServletConfig config, int panelno)
- throws ServletException {
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
setPanelNo(panelno);
setName("Admin Authentication");
}
public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
- throws ServletException {
+ throws ServletException {
setPanelNo(panelno);
setName("Admin Authentication");
setId(id);
@@ -62,24 +62,24 @@ public class AdminAuthenticatePanel extends WizardPanelBase {
public boolean isSubPanel() {
return true;
}
-
+
/**
* Should we skip this panel for the configuration.
*/
public boolean shouldSkip() {
CMS.debug("AdminAuthenticatePanel: should skip");
-
+
IConfigStore cs = CMS.getConfigStore();
// if we are root, no need to get the certificate chain.
-
+
try {
- String select = cs.getString("preop.subsystem.select","");
+ String select = cs.getString("preop.subsystem.select", "");
if (select.equals("new")) {
return true;
}
} catch (EBaseException e) {
}
-
+
return false;
}
@@ -103,15 +103,16 @@ public class AdminAuthenticatePanel extends WizardPanelBase {
} else {
return true;
}
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
return false;
}
public PropertySet getUsage() {
PropertySet set = new PropertySet();
-
+
/* XXX */
-
+
return set;
}
@@ -125,12 +126,12 @@ public class AdminAuthenticatePanel extends WizardPanelBase {
IConfigStore config = CMS.getConfigStore();
if (isPanelDone()) {
-
+
try {
String s = config.getString("preop.master.admin.uid", "");
String type = config.getString("preop.subsystem.select", "");
if (type.equals("clone"))
- context.put("uid", s);
+ context.put("uid", s);
else
context.put("uid", "");
} catch (Exception e) {
@@ -170,7 +171,7 @@ public class AdminAuthenticatePanel extends WizardPanelBase {
cstype = toLowerCaseSubsystemType(cstype);
if (subsystemtype.equals("clone")) {
- CMS.debug("AdminAuthenticatePanel: this is the clone subsystem");
+ CMS.debug("AdminAuthenticatePanel: this is the clone subsystem");
String uid = HttpInput.getUID(request, "uid");
if (uid == null) {
context.put("errorString", "Uid is empty");
@@ -185,7 +186,7 @@ public class AdminAuthenticatePanel extends WizardPanelBase {
try {
host = config.getString("preop.master.hostname");
} catch (Exception e) {
- CMS.debug("AdminAuthenticatePanel update: "+e.toString());
+ CMS.debug("AdminAuthenticatePanel update: " + e.toString());
context.put("errorString", "Missing hostname for master");
throw new IOException("Missing hostname");
}
@@ -193,7 +194,7 @@ public class AdminAuthenticatePanel extends WizardPanelBase {
try {
httpsport = config.getInteger("preop.master.httpsadminport");
} catch (Exception e) {
- CMS.debug("AdminAuthenticatePanel update: "+e.toString());
+ CMS.debug("AdminAuthenticatePanel update: " + e.toString());
context.put("errorString", "Missing port for master");
throw new IOException("Missing port");
}
@@ -235,10 +236,10 @@ public class AdminAuthenticatePanel extends WizardPanelBase {
c1.append("cloning.");
c1.append(t1);
c1.append(".pubkey.encoded");
-
- if (s1.length()!=0)
+
+ if (s1.length() != 0)
s1.append(",");
-
+
s1.append(cstype);
s1.append(".");
s1.append(t1);
@@ -248,11 +249,11 @@ public class AdminAuthenticatePanel extends WizardPanelBase {
c1.append(",preop.ca.hostname,preop.ca.httpport,preop.ca.httpsport,preop.ca.list,preop.ca.pkcs7,preop.ca.type");
}
- String content = "uid="+uid+"&pwd="+pwd+"&op=get&names=cloning.module.token,instanceId,internaldb.basedn,internaldb.ldapauth.password,internaldb.replication.password,internaldb.ldapconn.host,internaldb.ldapconn.port,internaldb.ldapauth.bindDN"+c1.toString()+"&substores="+s1.toString();
+ String content = "uid=" + uid + "&pwd=" + pwd + "&op=get&names=cloning.module.token,instanceId,internaldb.basedn,internaldb.ldapauth.password,internaldb.replication.password,internaldb.ldapconn.host,internaldb.ldapconn.port,internaldb.ldapauth.bindDN" + c1.toString() + "&substores=" + s1.toString();
boolean success = updateConfigEntries(host, httpsport, true,
- "/"+cstype+"/admin/"+cstype+"/getConfigEntries", content, config,
- response);
+ "/" + cstype + "/admin/" + cstype + "/getConfigEntries", content, config,
+ response);
try {
config.commit(false);
@@ -285,16 +286,15 @@ public class AdminAuthenticatePanel extends WizardPanelBase {
* If validiate() returns false, this method will be called.
*/
public void displayError(HttpServletRequest request,
- HttpServletResponse response,
- Context context)
- {
+ HttpServletResponse response,
+ Context context) {
context.put("title", "Admin Authentication");
context.put("password", "");
context.put("panel", "admin/console/config/adminauthenticatepanel.vm");
}
private boolean isCertdbCloned(HttpServletRequest request,
- Context context) {
+ Context context) {
IConfigStore config = CMS.getConfigStore();
String certList = "";
try {
@@ -306,13 +306,13 @@ public class AdminAuthenticatePanel extends WizardPanelBase {
String tokenname = config.getString("preop.module.token", "");
CryptoToken tok = cm.getTokenByName(tokenname);
CryptoStore store = tok.getCryptoStore();
- String name1 = "preop.master."+token+".nickname";
+ String name1 = "preop.master." + token + ".nickname";
String nickname = config.getString(name1, "");
if (!tokenname.equals("Internal Key Storage Token") &&
- !tokenname.equals("internal"))
- nickname = tokenname+":"+nickname;
+ !tokenname.equals("internal"))
+ nickname = tokenname + ":" + nickname;
- CMS.debug("AdminAuthenticatePanel isCertdbCloned: "+nickname);
+ CMS.debug("AdminAuthenticatePanel isCertdbCloned: " + nickname);
X509Certificate cert = cm.findCertByNickname(nickname);
if (cert == null)
return false;
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/AdminPanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/AdminPanel.java
index 78bb9485..c865741c 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/AdminPanel.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/AdminPanel.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
@@ -70,13 +69,14 @@ public class AdminPanel extends WizardPanelBase {
private static final String ADMIN_UID = "admin";
private final static String CERT_TAG = "admin";
- public AdminPanel() {}
+ public AdminPanel() {
+ }
/**
* Initializes this panel.
*/
- public void init(ServletConfig config, int panelno)
- throws ServletException {
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
setPanelNo(panelno);
setName("Administrator");
}
@@ -101,27 +101,37 @@ public class AdminPanel extends WizardPanelBase {
} else {
return true;
}
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
return false;
}
public PropertySet getUsage() {
PropertySet set = new PropertySet();
-
- Descriptor emailDesc = new Descriptor(IDescriptor.STRING, null, /* no constraint */
+
+ Descriptor emailDesc = new Descriptor(IDescriptor.STRING, null, /*
+ * no
+ * constraint
+ */
null, /* no default parameter */
"Email address for an administrator");
set.add("admin_email", emailDesc);
- Descriptor pwdDesc = new Descriptor(IDescriptor.STRING, null, /* no constraint */
+ Descriptor pwdDesc = new Descriptor(IDescriptor.STRING, null, /*
+ * no
+ * constraint
+ */
null, /* no default parameter */
"Administrator's password");
set.add("pwd", pwdDesc);
- Descriptor pwdAgainDesc = new Descriptor(IDescriptor.STRING, null, /* no constraint */
+ Descriptor pwdAgainDesc = new Descriptor(IDescriptor.STRING, null, /*
+ * no
+ * constraint
+ */
null, /* no default parameter */
"Administrator's password again");
@@ -152,7 +162,8 @@ public class AdminPanel extends WizardPanelBase {
try {
type = cs.getString("preop.ca.type", "");
subsystemtype = cs.getString("cs.type", "");
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
if (isPanelDone()) {
try {
@@ -161,11 +172,12 @@ public class AdminPanel extends WizardPanelBase {
context.put("admin_pwd", "");
context.put("admin_pwd_again", "");
context.put("admin_uid", cs.getString("preop.admin.uid"));
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
} else {
String def_admin_name = "";
try {
- def_admin_name = cs.getString("cs.type") + " Administrator of Instance " + cs.getString("instanceId");
+ def_admin_name = cs.getString("cs.type") + " Administrator of Instance " + cs.getString("instanceId");
} catch (EBaseException e) {
}
context.put("admin_name", def_admin_name);
@@ -176,7 +188,7 @@ public class AdminPanel extends WizardPanelBase {
}
ISubsystem ca = (ISubsystem) CMS.getSubsystem("ca");
- if (ca == null) {
+ if (ca == null) {
context.put("ca", "false");
} else {
context.put("ca", "true");
@@ -186,13 +198,14 @@ public class AdminPanel extends WizardPanelBase {
String domainname = "";
try {
domainname = cs.getString("securitydomain.name", "");
- } catch (EBaseException e1) {}
+ } catch (EBaseException e1) {
+ }
context.put("securityDomain", domainname);
context.put("title", "Administrator");
context.put("panel", "admin/console/config/adminpanel.vm");
context.put("errorString", "");
context.put("info", info);
-
+
}
/**
@@ -200,8 +213,7 @@ public class AdminPanel extends WizardPanelBase {
*/
public void validate(HttpServletRequest request,
HttpServletResponse response,
- Context context) throws IOException
- {
+ Context context) throws IOException {
String pwd = HttpInput.getPassword(request, "__pwd");
String pwd_again = HttpInput.getPassword(request, "__admin_password_again");
String email = HttpInput.getEmail(request, "email");
@@ -256,13 +268,14 @@ public class AdminPanel extends WizardPanelBase {
try {
type = config.getString(PRE_CA_TYPE, "");
subsystemtype = config.getString("cs.type", "");
- security_domain_type = config.getString("securitydomain.select","");
+ security_domain_type = config.getString("securitydomain.select", "");
selected_hierarchy = config.getString("preop.hierarchy.select", "");
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
ISubsystem ca = (ISubsystem) CMS.getSubsystem("ca");
- if (ca == null) {
+ if (ca == null) {
context.put("ca", "false");
} else {
context.put("ca", "true");
@@ -286,13 +299,13 @@ public class AdminPanel extends WizardPanelBase {
throw e;
}
- // REMINDER: This panel is NOT used by "clones"
- if( ca != null ) {
- if( selected_hierarchy.equals( "root" ) ) {
- CMS.debug( "AdminPanel update: "
+ // REMINDER: This panel is NOT used by "clones"
+ if (ca != null) {
+ if (selected_hierarchy.equals("root")) {
+ CMS.debug("AdminPanel update: "
+ "Root CA subsystem");
} else {
- CMS.debug( "AdminPanel update: "
+ CMS.debug("AdminPanel update: "
+ "Subordinate CA subsystem");
}
@@ -309,10 +322,10 @@ public class AdminPanel extends WizardPanelBase {
String ca_hostname = null;
int ca_port = -1;
- // REMINDER: This panel is NOT used by "clones"
- CMS.debug( "AdminPanel update: "
+ // REMINDER: This panel is NOT used by "clones"
+ CMS.debug("AdminPanel update: "
+ subsystemtype
- + " subsystem" );
+ + " subsystem");
if (type.equals("sdca")) {
try {
@@ -339,10 +352,11 @@ public class AdminPanel extends WizardPanelBase {
try {
config.commit(false);
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
context.put("updateStatus", "success");
-
+
}
private void createAdmin(HttpServletRequest request) throws IOException {
@@ -459,13 +473,15 @@ public class AdminPanel extends WizardPanelBase {
try {
sd_hostname = config.getString("securitydomain.host", "");
sd_port = config.getInteger("securitydomain.httpseeport");
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
String profileId = HttpInput.getID(request, "profileId");
if (profileId == null) {
try {
profileId = config.getString("preop.admincert.profile", "caAdminCert");
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
}
String cert_request_type = HttpInput.getID(request, "cert_request_type");
@@ -474,7 +490,7 @@ public class AdminPanel extends WizardPanelBase {
String session_id = CMS.getConfigSDSessionId();
String subjectDN = HttpInput.getString(request, "subject");
- String content = "profileId="+profileId+"&cert_request_type="+cert_request_type+"&cert_request="+cert_request+"&xmlOutput=true&sessionID="+session_id+"&subject="+subjectDN;
+ String content = "profileId=" + profileId + "&cert_request_type=" + cert_request_type + "&cert_request=" + cert_request + "&xmlOutput=true&sessionID=" + session_id + "&subject=" + subjectDN;
HttpClient httpclient = new HttpClient();
String c = null;
@@ -497,7 +513,7 @@ public class AdminPanel extends WizardPanelBase {
c = httpresponse.getContent();
CMS.debug("AdminPanel submitRequest: content=" + c);
-
+
// retrieve the request Id ad admin certificate
if (c != null) {
try {
@@ -508,15 +524,15 @@ public class AdminPanel extends WizardPanelBase {
try {
parser = new XMLObject(bis);
} catch (Exception e) {
- CMS.debug( "AdminPanel::submitRequest() - "
- + "Exception="+e.toString() );
- throw new IOException( e.toString() );
+ CMS.debug("AdminPanel::submitRequest() - "
+ + "Exception=" + e.toString());
+ throw new IOException(e.toString());
}
String status = parser.getValue("Status");
CMS.debug("AdminPanel update: status=" + status);
if (status.equals("2")) {
- //relogin to the security domain
+ // relogin to the security domain
reloginSecurityDomain(response);
return;
} else if (!status.equals("0")) {
@@ -525,7 +541,7 @@ public class AdminPanel extends WizardPanelBase {
context.put("errorString", error);
throw new IOException(error);
}
-
+
IConfigStore cs = CMS.getConfigStore();
String id = parser.getValue("Id");
@@ -539,7 +555,7 @@ public class AdminPanel extends WizardPanelBase {
+ File.separator + "admin.b64";
cs.putString("preop.admincert.b64", dir);
- PrintStream ps = new PrintStream(new FileOutputStream(dir));
+ PrintStream ps = new PrintStream(new FileOutputStream(dir));
ps.println(b64);
ps.flush();
@@ -564,9 +580,9 @@ public class AdminPanel extends WizardPanelBase {
String cert_request_type = HttpInput.getID(request, "cert_request_type");
IConfigStore cs = CMS.getConfigStore();
- if( cs == null ) {
- CMS.debug( "AdminPanel::createAdminCertificate() - cs is null!" );
- throw new IOException( "cs is null" );
+ if (cs == null) {
+ CMS.debug("AdminPanel::createAdminCertificate() - cs is null!");
+ throw new IOException("cs is null");
}
String subject = "";
@@ -582,10 +598,10 @@ public class AdminPanel extends WizardPanelBase {
"AdminPanel createAdminCertificate: Exception="
+ e.toString());
}
- // this request is from IE. The VBScript has problem of generating
- // certificate request if the subject name has E and UID components.
- // For now, we always hardcoded the subject DN to be cn=NAME in
- // the IE browser.
+ // this request is from IE. The VBScript has problem of generating
+ // certificate request if the subject name has E and UID components.
+ // For now, we always hardcoded the subject DN to be cn=NAME in
+ // the IE browser.
} else if (cert_request_type.equals("pkcs10")) {
try {
byte[] b = CMS.AtoB(cert_request);
@@ -594,33 +610,33 @@ public class AdminPanel extends WizardPanelBase {
x509key = pkcs10.getSubjectPublicKeyInfo();
} catch (Exception e) {
CMS.debug("AdminPanel createAdminCertificate: Exception="
- + e.toString());
+ + e.toString());
}
}
- if( x509key == null ) {
- CMS.debug( "AdminPanel::createAdminCertificate() - x509key is null!" );
- throw new IOException( "x509key is null" );
+ if (x509key == null) {
+ CMS.debug("AdminPanel::createAdminCertificate() - x509key is null!");
+ throw new IOException("x509key is null");
}
try {
cs.putString(PCERT_PREFIX + CERT_TAG + ".dn", subject);
String caType = cs.getString(PCERT_PREFIX + CERT_TAG + ".type", "local");
X509CertImpl impl = CertUtil.createLocalCert(cs, x509key,
- PCERT_PREFIX, CERT_TAG, caType, context);
+ PCERT_PREFIX, CERT_TAG, caType, context);
// update the locally created request for renewal
- CertUtil.updateLocalRequest(cs, CERT_TAG, cert_request,cert_request_type, subject);
+ CertUtil.updateLocalRequest(cs, CERT_TAG, cert_request, cert_request_type, subject);
ISubsystem ca = (ISubsystem) CMS.getSubsystem("ca");
if (ca != null) {
createPKCS7(impl);
}
cs.putString("preop.admincert.serialno.0",
- impl.getSerialNumber().toString(16));
+ impl.getSerialNumber().toString(16));
} catch (Exception e) {
CMS.debug("AdminPanel createAdminCertificate: Exception="
- + e.toString());
+ + e.toString());
}
}
@@ -640,8 +656,9 @@ public class AdminPanel extends WizardPanelBase {
try {
type = cs.getString("preop.ca.type", "");
- } catch (Exception e) {}
- if (ca == null && type.equals("otherca")) {
+ } catch (Exception e) {
+ }
+ if (ca == null && type.equals("otherca")) {
info = "Since you do not join the Redhat CA network, the administrator's certificate will not be generated automatically.";
}
context.put("info", info);
@@ -655,7 +672,7 @@ public class AdminPanel extends WizardPanelBase {
public boolean shouldSkip() {
try {
IConfigStore c = CMS.getConfigStore();
- String s = c.getString("preop.subsystem.select",null);
+ String s = c.getString("preop.subsystem.select", null);
if (s != null && s.equals("clone")) {
return true;
}
@@ -665,11 +682,10 @@ public class AdminPanel extends WizardPanelBase {
return false;
}
-
private void createPKCS7(X509CertImpl cert) {
try {
IConfigStore cs = CMS.getConfigStore();
- ICertificateAuthority ca = (ICertificateAuthority)CMS.getSubsystem("ca");
+ ICertificateAuthority ca = (ICertificateAuthority) CMS.getSubsystem("ca");
CertificateChain cachain = ca.getCACertChain();
X509Certificate[] cacerts = cachain.getChain();
X509CertImpl[] userChain = new X509CertImpl[cacerts.length + 1];
@@ -681,7 +697,7 @@ public class AdminPanel extends WizardPanelBase {
userChain[0] = cert;
PKCS7 p7 = new PKCS7(new AlgorithmId[0],
- new ContentInfo(new byte[0]), userChain, new SignerInfo[0]);
+ new ContentInfo(new byte[0]), userChain, new SignerInfo[0]);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
p7.encodeSignedData(bos);
@@ -689,7 +705,7 @@ public class AdminPanel extends WizardPanelBase {
String p7Str = CMS.BtoA(p7Bytes);
cs.putString("preop.admincert.pkcs7", CryptoUtil.normalizeCertStr(p7Str));
} catch (Exception e) {
- CMS.debug("AdminPanel createPKCS7: Failed to create pkcs7 file. Exception: "+e.toString());
+ CMS.debug("AdminPanel createPKCS7: Failed to create pkcs7 file. Exception: " + e.toString());
}
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/AgentAuthenticatePanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/AgentAuthenticatePanel.java
index a62b22b7..4e2ab363 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/AgentAuthenticatePanel.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/AgentAuthenticatePanel.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.IOException;
import javax.servlet.ServletConfig;
@@ -36,19 +35,20 @@ import com.netscape.cms.servlet.wizard.WizardServlet;
public class AgentAuthenticatePanel extends WizardPanelBase {
- public AgentAuthenticatePanel() {}
+ public AgentAuthenticatePanel() {
+ }
/**
* Initializes this panel.
*/
- public void init(ServletConfig config, int panelno)
- throws ServletException {
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
setPanelNo(panelno);
setName("Agent Authentication");
}
public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
- throws ServletException {
+ throws ServletException {
setPanelNo(panelno);
setName("Agent Authentication");
setId(id);
@@ -57,18 +57,18 @@ public class AgentAuthenticatePanel extends WizardPanelBase {
public boolean isSubPanel() {
return true;
}
-
+
/**
* Should we skip this panel for the configuration.
*/
public boolean shouldSkip() {
CMS.debug("DisplayCertChainPanel: should skip");
-
+
IConfigStore cs = CMS.getConfigStore();
// if we are root, no need to get the certificate chain.
-
+
try {
- String select = cs.getString("securitydomain.select","");
+ String select = cs.getString("securitydomain.select", "");
if (select.equals("new")) {
return true;
}
@@ -78,7 +78,7 @@ public class AgentAuthenticatePanel extends WizardPanelBase {
return true;
} catch (EBaseException e) {
}
-
+
return false;
}
@@ -96,15 +96,16 @@ public class AgentAuthenticatePanel extends WizardPanelBase {
} else {
return true;
}
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
return false;
}
public PropertySet getUsage() {
PropertySet set = new PropertySet();
-
+
/* XXX */
-
+
return set;
}
@@ -118,14 +119,14 @@ public class AgentAuthenticatePanel extends WizardPanelBase {
IConfigStore config = CMS.getConfigStore();
if (isPanelDone()) {
-
+
try {
String s = config.getString("preop.ca.agent.uid", "");
String type = config.getString("preop.hierarchy.select", "");
if (type.equals("root"))
context.put("uid", "");
else
- context.put("uid", s);
+ context.put("uid", s);
} catch (Exception e) {
CMS.debug(e.toString());
}
@@ -143,8 +144,7 @@ public class AgentAuthenticatePanel extends WizardPanelBase {
*/
public void validate(HttpServletRequest request,
HttpServletResponse response,
- Context context) throws IOException
- {
+ Context context) throws IOException {
}
/**
@@ -182,34 +182,34 @@ public class AgentAuthenticatePanel extends WizardPanelBase {
try {
host = config.getString("preop.ca.hostname");
} catch (Exception e) {
- CMS.debug("AgentAuthenticatePanel update: "+e.toString());
+ CMS.debug("AgentAuthenticatePanel update: " + e.toString());
context.put("errorString", "Missing hostname");
throw new IOException("Missing hostname");
}
-
+
try {
httpsport = config.getInteger("preop.ca.httpsport");
} catch (Exception e) {
- CMS.debug("AgentAuthenticatePanel update: "+e.toString());
+ CMS.debug("AgentAuthenticatePanel update: " + e.toString());
context.put("errorString", "Missing port");
throw new IOException("Missing port");
}
-/*
- // Bugzilla Bug #583825 - CC: Obsolete servlets to be removed from
- // web.xml as part of CC interface review
- boolean authenticated = authenticate(host, httpsport, true,
- "/ca/ee/ca/checkIdentity", "uid="+uid+"&pwd="+pwd);
-
- if (!authenticated) {
- context.put("errorString", "Wrong user id or password");
- throw new IOException("Wrong user id or password");
- }
-*/
+ /*
+ * // Bugzilla Bug #583825 - CC: Obsolete servlets to be removed
+ * from // web.xml as part of CC interface review boolean
+ * authenticated = authenticate(host, httpsport, true,
+ * "/ca/ee/ca/checkIdentity", "uid="+uid+"&pwd="+pwd);
+ *
+ * if (!authenticated) { context.put("errorString",
+ * "Wrong user id or password"); throw new
+ * IOException("Wrong user id or password"); }
+ */
try {
config.commit(false);
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
}
}
@@ -217,9 +217,8 @@ public class AgentAuthenticatePanel extends WizardPanelBase {
* If validiate() returns false, this method will be called.
*/
public void displayError(HttpServletRequest request,
- HttpServletResponse response,
- Context context)
- {
+ HttpServletResponse response,
+ Context context) {
context.put("password", "");
context.put("title", "Agent Authentication");
context.put("panel", "admin/console/config/agentauthenticatepanel.vm");
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/AuthenticatePanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/AuthenticatePanel.java
index ceab1d8d..6700b931 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/AuthenticatePanel.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/AuthenticatePanel.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.IOException;
import javax.servlet.ServletConfig;
@@ -36,19 +35,20 @@ import com.netscape.cms.servlet.wizard.WizardServlet;
public class AuthenticatePanel extends WizardPanelBase {
- public AuthenticatePanel() {}
+ public AuthenticatePanel() {
+ }
/**
* Initializes this panel.
*/
- public void init(ServletConfig config, int panelno)
- throws ServletException {
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
setPanelNo(panelno);
setName("Authentication");
}
public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
- throws ServletException {
+ throws ServletException {
setPanelNo(panelno);
setName("Authentication");
setId(id);
@@ -62,21 +62,22 @@ public class AuthenticatePanel extends WizardPanelBase {
public boolean isPanelDone() {
IConfigStore cs = CMS.getConfigStore();
try {
- String s = cs.getString("preop.ca.agent.uid","");
+ String s = cs.getString("preop.ca.agent.uid", "");
if (s == null || s.equals("")) {
return false;
} else {
return true;
}
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
return false;
}
public PropertySet getUsage() {
PropertySet set = new PropertySet();
-
+
/* XXX */
-
+
return set;
}
@@ -90,14 +91,14 @@ public class AuthenticatePanel extends WizardPanelBase {
IConfigStore config = CMS.getConfigStore();
if (isPanelDone()) {
-
+
try {
String s = config.getString("preop.ca.agent.uid", "");
String type = config.getString("preop.hierarchy.select", "");
if (type.equals("root"))
context.put("uid", "");
else
- context.put("uid", s);
+ context.put("uid", s);
} catch (Exception e) {
CMS.debug(e.toString());
}
@@ -151,30 +152,31 @@ public class AuthenticatePanel extends WizardPanelBase {
try {
host = config.getString("preop.ca.hostname");
} catch (Exception e) {
- CMS.debug("AuthenticatePanel update: "+e.toString());
+ CMS.debug("AuthenticatePanel update: " + e.toString());
context.put("errorString", "Missing hostname");
throw new IOException("Missing hostname");
}
-
+
try {
httpsport = config.getInteger("preop.ca.httpsport");
} catch (Exception e) {
- CMS.debug("AuthenticatePanel update: "+e.toString());
+ CMS.debug("AuthenticatePanel update: " + e.toString());
context.put("errorString", "Missing port");
throw new IOException("Missing port");
}
- boolean authenticated = authenticate(host, httpsport, true,
- "/ca/ee/ca/configSubsystem", "uid="+uid+"&pwd="+pwd);
+ boolean authenticated = authenticate(host, httpsport, true,
+ "/ca/ee/ca/configSubsystem", "uid=" + uid + "&pwd=" + pwd);
- if (!authenticated) {
- context.put("errorString", "Wrong user id or password");
- throw new IOException("Wrong user id or password");
- }
+ if (!authenticated) {
+ context.put("errorString", "Wrong user id or password");
+ throw new IOException("Wrong user id or password");
+ }
try {
config.commit(false);
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
}
}
@@ -182,9 +184,8 @@ public class AuthenticatePanel extends WizardPanelBase {
* If validiate() returns false, this method will be called.
*/
public void displayError(HttpServletRequest request,
- HttpServletResponse response,
- Context context)
- {
+ HttpServletResponse response,
+ Context context) {
context.put("password", "");
context.put("panel", "admin/console/config/authenticatepanel.vm");
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/BackupKeyCertPanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/BackupKeyCertPanel.java
index 77977808..d7f35540 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/BackupKeyCertPanel.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/BackupKeyCertPanel.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.ByteArrayOutputStream;
import java.io.CharConversionException;
import java.io.IOException;
@@ -71,19 +70,20 @@ import com.netscape.cmsutil.crypto.CryptoUtil;
public class BackupKeyCertPanel extends WizardPanelBase {
- public BackupKeyCertPanel() {}
+ public BackupKeyCertPanel() {
+ }
/**
* Initializes this panel.
*/
- public void init(ServletConfig config, int panelno)
- throws ServletException {
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
setPanelNo(panelno);
setName("Export Keys and Certificates");
}
public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
- throws ServletException {
+ throws ServletException {
setPanelNo(panelno);
setName("Export Keys and Certificates");
setId(id);
@@ -105,11 +105,11 @@ public class BackupKeyCertPanel extends WizardPanelBase {
try {
String s = cs.getString("preop.module.token", "");
- if (s.equals("Internal Key Storage Token"))
+ if (s.equals("Internal Key Storage Token"))
return false;
} catch (Exception e) {
}
-
+
return true;
}
@@ -122,15 +122,16 @@ public class BackupKeyCertPanel extends WizardPanelBase {
} else {
return true;
}
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
return false;
}
public PropertySet getUsage() {
PropertySet set = new PropertySet();
-
+
/* XXX */
-
+
return set;
}
@@ -170,7 +171,7 @@ public class BackupKeyCertPanel extends WizardPanelBase {
* Checks if the given parameters are valid.
*/
public void validate(HttpServletRequest request,
- HttpServletResponse response, Context context) throws IOException {
+ HttpServletResponse response, Context context) throws IOException {
String select = HttpInput.getID(request, "choice");
if (select.equals("backupkey")) {
String pwd = request.getParameter("__pwd");
@@ -219,9 +220,8 @@ public class BackupKeyCertPanel extends WizardPanelBase {
* If validiate() returns false, this method will be called.
*/
public void displayError(HttpServletRequest request,
- HttpServletResponse response,
- Context context)
- {
+ HttpServletResponse response,
+ Context context) {
String select = "";
try {
select = HttpInput.getID(request, "choice");
@@ -242,8 +242,8 @@ public class BackupKeyCertPanel extends WizardPanelBase {
context.put("panel", "admin/console/config/backupkeycertpanel.vm");
}
- public void backupKeysCerts(HttpServletRequest request)
- throws IOException {
+ public void backupKeysCerts(HttpServletRequest request)
+ throws IOException {
CMS.debug("BackupKeyCertPanel backupKeysCerts: start");
IConfigStore cs = CMS.getConfigStore();
String certlist = "";
@@ -257,9 +257,9 @@ public class BackupKeyCertPanel extends WizardPanelBase {
try {
cm = CryptoManager.getInstance();
} catch (Exception e) {
- CMS.debug( "BackupKeyCertPanel::backupKeysCerts() - "
- + "Exception="+e.toString() );
- throw new IOException( e.toString() );
+ CMS.debug("BackupKeyCertPanel::backupKeysCerts() - "
+ + "Exception=" + e.toString());
+ throw new IOException(e.toString());
}
String pwd = request.getParameter("__pwd");
@@ -273,12 +273,12 @@ public class BackupKeyCertPanel extends WizardPanelBase {
String nickname = "";
String modname = "";
try {
- nickname = cs.getString("preop.cert."+t+".nickname");
+ nickname = cs.getString("preop.cert." + t + ".nickname");
modname = cs.getString("preop.module.token");
} catch (Exception e) {
}
if (!modname.equals("Internal Key Storage Token"))
- nickname = modname+":"+nickname;
+ nickname = modname + ":" + nickname;
X509Certificate x509cert = null;
byte localKeyId[] = null;
@@ -288,7 +288,7 @@ public class BackupKeyCertPanel extends WizardPanelBase {
} catch (IOException e) {
throw e;
} catch (Exception e) {
- CMS.debug("BackupKeyCertPanel: Exception="+e.toString());
+ CMS.debug("BackupKeyCertPanel: Exception=" + e.toString());
throw new IOException("Failed to create pkcs12 file.");
}
@@ -296,22 +296,22 @@ public class BackupKeyCertPanel extends WizardPanelBase {
PrivateKey pkey = cm.findPrivKeyByCert(x509cert);
addKeyBag(pkey, x509cert, pass, localKeyId, encSafeContents);
} catch (Exception e) {
- CMS.debug("BackupKeyCertPanel: Exception="+e.toString());
+ CMS.debug("BackupKeyCertPanel: Exception=" + e.toString());
throw new IOException("Failed to create pkcs12 file.");
}
- } //while loop
-
+ } // while loop
+
X509Certificate[] cacerts = cm.getCACerts();
- for (int i=0; i<cacerts.length; i++) {
- //String nickname = cacerts[i].getSubjectDN().toString();
+ for (int i = 0; i < cacerts.length; i++) {
+ // String nickname = cacerts[i].getSubjectDN().toString();
String nickname = null;
try {
byte[] localKeyId = addCertBag(cacerts[i], nickname, safeContents);
} catch (IOException e) {
throw e;
} catch (Exception e) {
- CMS.debug("BackupKeyCertPanel backKeysCerts: Exception="+e.toString());
+ CMS.debug("BackupKeyCertPanel backKeysCerts: Exception=" + e.toString());
throw new IOException("Failed to create pkcs12 file.");
}
}
@@ -319,9 +319,9 @@ public class BackupKeyCertPanel extends WizardPanelBase {
try {
AuthenticatedSafes authSafes = new AuthenticatedSafes();
authSafes.addSafeContents(safeContents);
- authSafes.addSafeContents(encSafeContents);
+ authSafes.addSafeContents(encSafeContents);
PFX pfx = new PFX(authSafes);
- pfx.computeMacData(pass, null, 5);
+ pfx.computeMacData(pass, null, 5);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
pfx.encode(bos);
byte[] output = bos.toByteArray();
@@ -329,13 +329,13 @@ public class BackupKeyCertPanel extends WizardPanelBase {
pass.clear();
cs.commit(false);
} catch (Exception e) {
- CMS.debug("BackupKeyCertPanel backupKeysCerts: Exception="+e.toString());
+ CMS.debug("BackupKeyCertPanel backupKeysCerts: Exception=" + e.toString());
}
}
private void addKeyBag(PrivateKey pkey, X509Certificate x509cert,
- Password pass, byte[] localKeyId, SEQUENCE safeContents)
- throws IOException {
+ Password pass, byte[] localKeyId, SEQUENCE safeContents)
+ throws IOException {
try {
PasswordConverter passConverter = new PasswordConverter();
@@ -344,23 +344,23 @@ public class BackupKeyCertPanel extends WizardPanelBase {
byte[] priData = getEncodedKey(pkey);
PrivateKeyInfo pki = (PrivateKeyInfo)
- ASN1Util.decode(PrivateKeyInfo.getTemplate(), priData);
+ ASN1Util.decode(PrivateKeyInfo.getTemplate(), priData);
ASN1Value key = EncryptedPrivateKeyInfo.createPBE(
- PBEAlgorithm.PBE_SHA1_DES3_CBC,
- pass, salt, 1, passConverter, pki);
+ PBEAlgorithm.PBE_SHA1_DES3_CBC,
+ pass, salt, 1, passConverter, pki);
SET keyAttrs = createBagAttrs(
- x509cert.getSubjectDN().toString(), localKeyId);
- SafeBag keyBag = new SafeBag(SafeBag.PKCS8_SHROUDED_KEY_BAG,
- key, keyAttrs);
+ x509cert.getSubjectDN().toString(), localKeyId);
+ SafeBag keyBag = new SafeBag(SafeBag.PKCS8_SHROUDED_KEY_BAG,
+ key, keyAttrs);
safeContents.addElement(keyBag);
} catch (Exception e) {
- CMS.debug("BackupKeyCertPanel getKeyBag: Exception="+e.toString());
+ CMS.debug("BackupKeyCertPanel getKeyBag: Exception=" + e.toString());
throw new IOException("Failed to create pk12 file.");
}
}
- private byte[] addCertBag(X509Certificate x509cert, String nickname,
- SEQUENCE safeContents) throws IOException {
+ private byte[] addCertBag(X509Certificate x509cert, String nickname,
+ SEQUENCE safeContents) throws IOException {
byte[] localKeyId = null;
try {
ASN1Value cert = new OCTET_STRING(x509cert.getEncoded());
@@ -369,10 +369,10 @@ public class BackupKeyCertPanel extends WizardPanelBase {
if (nickname != null)
certAttrs = createBagAttrs(nickname, localKeyId);
SafeBag certBag = new SafeBag(SafeBag.CERT_BAG,
- new CertBag(CertBag.X509_CERT_TYPE, cert), certAttrs);
+ new CertBag(CertBag.X509_CERT_TYPE, cert), certAttrs);
safeContents.addElement(certBag);
} catch (Exception e) {
- CMS.debug("BackupKeyCertPanel addCertBag: "+e.toString());
+ CMS.debug("BackupKeyCertPanel addCertBag: " + e.toString());
throw new IOException("Failed to create pk12 file.");
}
@@ -386,7 +386,7 @@ public class BackupKeyCertPanel extends WizardPanelBase {
KeyGenerator kg = token.getKeyGenerator(KeyGenAlgorithm.DES3);
SymmetricKey sk = kg.generate();
KeyWrapper wrapper = token.getKeyWrapper(KeyWrapAlgorithm.DES3_CBC_PAD);
- byte iv[] = {0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1};
+ byte iv[] = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 };
IVParameterSpec param = new IVParameterSpec(iv);
wrapper.initWrap(sk, param);
byte[] enckey = wrapper.wrap(pkey);
@@ -395,14 +395,14 @@ public class BackupKeyCertPanel extends WizardPanelBase {
byte[] recovered = c.doFinal(enckey);
return recovered;
} catch (Exception e) {
- CMS.debug("BackupKeyCertPanel getEncodedKey: Exception="+e.toString());
+ CMS.debug("BackupKeyCertPanel getEncodedKey: Exception=" + e.toString());
}
return null;
}
- private byte[] createLocalKeyId(X509Certificate cert)
- throws IOException {
+ private byte[] createLocalKeyId(X509Certificate cert)
+ throws IOException {
try {
// SHA1 hash of the X509Cert der encoding
byte certDer[] = cert.getEncoded();
@@ -412,16 +412,16 @@ public class BackupKeyCertPanel extends WizardPanelBase {
md.update(certDer);
return md.digest();
} catch (CertificateEncodingException e) {
- CMS.debug("BackupKeyCertPanel createLocalKeyId: Exception: "+e.toString());
+ CMS.debug("BackupKeyCertPanel createLocalKeyId: Exception: " + e.toString());
throw new IOException("Failed to encode certificate.");
} catch (NoSuchAlgorithmException e) {
- CMS.debug("BackupKeyCertPanel createLocalKeyId: Exception: "+e.toString());
+ CMS.debug("BackupKeyCertPanel createLocalKeyId: Exception: " + e.toString());
throw new IOException("No such algorithm supported.");
}
}
private SET createBagAttrs(String nickName, byte localKeyId[])
- throws IOException {
+ throws IOException {
try {
SET attrs = new SET();
SEQUENCE nickNameAttr = new SEQUENCE();
@@ -442,7 +442,7 @@ public class BackupKeyCertPanel extends WizardPanelBase {
attrs.addElement(localKeyAttr);
return attrs;
} catch (CharConversionException e) {
- CMS.debug("BackupKeyCertPanel createBagAttrs: Exception="+e.toString());
+ CMS.debug("BackupKeyCertPanel createBagAttrs: Exception=" + e.toString());
throw new IOException("Failed to create PKCS12 file.");
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/BaseServlet.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/BaseServlet.java
index 01d06631..46371017 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/BaseServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/BaseServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.IOException;
import java.util.Enumeration;
@@ -30,7 +29,6 @@ import org.apache.velocity.servlet.VelocityServlet;
import com.netscape.certsrv.apps.CMS;
-
public class BaseServlet extends VelocityServlet {
/**
@@ -53,7 +51,8 @@ public class BaseServlet extends VelocityServlet {
if (pin == null) {
try {
response.sendRedirect("login");
- } catch (IOException e) {}
+ } catch (IOException e) {
+ }
return false;
}
return true;
@@ -66,29 +65,29 @@ public class BaseServlet extends VelocityServlet {
while (paramNames.hasMoreElements()) {
String pn = (String) paramNames.nextElement();
// added this facility so that password can be hidden,
- // all sensitive parameters should be prefixed with
+ // all sensitive parameters should be prefixed with
// __ (double underscores); however, in the event that
// a security parameter slips through, we perform multiple
// additional checks to insure that it is NOT displayed
- if( pn.startsWith("__") ||
- pn.endsWith("password") ||
- pn.endsWith("passwd") ||
- pn.endsWith("pwd") ||
- pn.equalsIgnoreCase("admin_password_again") ||
- pn.equalsIgnoreCase("directoryManagerPwd") ||
- pn.equalsIgnoreCase("bindpassword") ||
- pn.equalsIgnoreCase("bindpwd") ||
- pn.equalsIgnoreCase("passwd") ||
- pn.equalsIgnoreCase("password") ||
- pn.equalsIgnoreCase("pin") ||
- pn.equalsIgnoreCase("pwd") ||
- pn.equalsIgnoreCase("pwdagain") ||
- pn.equalsIgnoreCase("uPasswd") ) {
- CMS.debug("BaseServlet::service() param name='" + pn +
- "' value='(sensitive)'" );
+ if (pn.startsWith("__") ||
+ pn.endsWith("password") ||
+ pn.endsWith("passwd") ||
+ pn.endsWith("pwd") ||
+ pn.equalsIgnoreCase("admin_password_again") ||
+ pn.equalsIgnoreCase("directoryManagerPwd") ||
+ pn.equalsIgnoreCase("bindpassword") ||
+ pn.equalsIgnoreCase("bindpwd") ||
+ pn.equalsIgnoreCase("passwd") ||
+ pn.equalsIgnoreCase("password") ||
+ pn.equalsIgnoreCase("pin") ||
+ pn.equalsIgnoreCase("pwd") ||
+ pn.equalsIgnoreCase("pwdagain") ||
+ pn.equalsIgnoreCase("uPasswd")) {
+ CMS.debug("BaseServlet::service() param name='" + pn +
+ "' value='(sensitive)'");
} else {
- CMS.debug("BaseServlet::service() param name='" + pn +
- "' value='" + httpReq.getParameter(pn) + "'" );
+ CMS.debug("BaseServlet::service() param name='" + pn +
+ "' value='" + httpReq.getParameter(pn) + "'");
}
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/CAInfoPanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/CAInfoPanel.java
index 33a0ff69..f48f4d2f 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/CAInfoPanel.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/CAInfoPanel.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.IOException;
import java.net.URL;
import java.util.StringTokenizer;
@@ -39,19 +38,20 @@ import com.netscape.cms.servlet.wizard.WizardServlet;
public class CAInfoPanel extends WizardPanelBase {
- public CAInfoPanel() {}
+ public CAInfoPanel() {
+ }
/**
* Initializes this panel.
*/
- public void init(ServletConfig config, int panelno)
- throws ServletException {
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
setPanelNo(panelno);
setName("CA Information");
}
- public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
- throws ServletException {
+ public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
+ throws ServletException {
setPanelNo(panelno);
setName("CA Information");
setId(id);
@@ -82,14 +82,15 @@ public class CAInfoPanel extends WizardPanelBase {
} else {
return true;
}
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
return false;
}
public PropertySet getUsage() {
PropertySet set = new PropertySet();
-
+
return set;
}
@@ -118,15 +119,18 @@ public class CAInfoPanel extends WizardPanelBase {
try {
hostname = cs.getString("preop.ca.hostname");
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
try {
httpport = cs.getString("preop.ca.httpport");
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
try {
httpsport = cs.getString("preop.ca.httpsport");
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
if (type.equals("sdca")) {
context.put("check_sdca", "checked");
@@ -143,12 +147,11 @@ public class CAInfoPanel extends WizardPanelBase {
String cstype = "CA";
String portType = "SecurePort";
-/*
- try {
- cstype = cs.getString("cs.type", "");
- } catch (EBaseException e) {}
-*/
-
+ /*
+ * try { cstype = cs.getString("cs.type", ""); } catch (EBaseException
+ * e) {}
+ */
+
CMS.debug("CAInfoPanel: Ready to get url");
Vector v = getUrlListFromSecurityDomain(cs, cstype, portType);
v.addElement("External CA");
@@ -163,12 +166,13 @@ public class CAInfoPanel extends WizardPanelBase {
list.append(",");
}
}
-
+
try {
cs.putString("preop.ca.list", list.toString());
cs.commit(false);
- } catch (Exception e) {}
-
+ } catch (Exception e) {
+ }
+
context.put("urls", v);
context.put("sdcaHostname", hostname);
@@ -196,11 +200,9 @@ public class CAInfoPanel extends WizardPanelBase {
Context context) throws IOException {
/*
- String select = request.getParameter("choice");
- if (select == null) {
- CMS.debug("CAInfoPanel: choice not found");
- throw new IOException("choice not found");
- }
+ * String select = request.getParameter("choice"); if (select == null) {
+ * CMS.debug("CAInfoPanel: choice not found"); throw new
+ * IOException("choice not found"); }
*/
IConfigStore config = CMS.getConfigStore();
@@ -213,25 +215,26 @@ public class CAInfoPanel extends WizardPanelBase {
String select = null;
String index = request.getParameter("urls");
- String url = "";
+ String url = "";
if (index.startsWith("http")) {
- // user may submit url directlry
- url = index;
+ // user may submit url directlry
+ url = index;
} else {
- try {
- int x = Integer.parseInt(index);
- String list = config.getString("preop.ca.list", "");
- StringTokenizer tokenizer = new StringTokenizer(list, ",");
- int counter = 0;
-
- while (tokenizer.hasMoreTokens()) {
- url = tokenizer.nextToken();
- if (counter == x) {
- break;
+ try {
+ int x = Integer.parseInt(index);
+ String list = config.getString("preop.ca.list", "");
+ StringTokenizer tokenizer = new StringTokenizer(list, ",");
+ int counter = 0;
+
+ while (tokenizer.hasMoreTokens()) {
+ url = tokenizer.nextToken();
+ if (counter == x) {
+ break;
+ }
+ counter++;
}
- counter++;
+ } catch (Exception e) {
}
- } catch (Exception e) {}
}
URL urlx = null;
@@ -240,7 +243,7 @@ public class CAInfoPanel extends WizardPanelBase {
select = "otherca";
config.putString("preop.ca.pkcs7", "");
config.putInteger("preop.ca.certchain.size", 0);
- } else {
+ } else {
select = "sdca";
// parse URL (CA1 - https://...)
@@ -272,7 +275,8 @@ public class CAInfoPanel extends WizardPanelBase {
try {
config.commit(false);
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
}
private void sdca(HttpServletRequest request, Context context, String hostname, String httpsPortStr) throws IOException {
@@ -301,9 +305,9 @@ public class CAInfoPanel extends WizardPanelBase {
config.putString("preop.ca.hostname", hostname);
config.putString("preop.ca.httpsport", httpsPortStr);
ConfigCertApprovalCallback certApprovalCallback = new ConfigCertApprovalCallback();
- updateCertChainUsingSecureEEPort( config, "ca", hostname,
+ updateCertChainUsingSecureEEPort(config, "ca", hostname,
httpsport, true, context,
- certApprovalCallback );
+ certApprovalCallback);
}
/**
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/Cert.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/Cert.java
index fb8c2d9c..0aedded8 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/Cert.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/Cert.java
@@ -17,9 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
-
-
public class Cert {
private String mNickname = "";
private String mTokenname = "";
@@ -116,8 +113,8 @@ public class Cert {
}
public String escapeForHTML(String s) {
- s = s.replaceAll("\"", "&quot;");
- return s;
+ s = s.replaceAll("\"", "&quot;");
+ return s;
}
public String getEscapedDN() {
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/CertPrettyPrintPanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/CertPrettyPrintPanel.java
index 30bcc78d..119dead0 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/CertPrettyPrintPanel.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/CertPrettyPrintPanel.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.IOException;
import java.util.Locale;
import java.util.StringTokenizer;
@@ -42,19 +41,20 @@ import com.netscape.cmsutil.crypto.CryptoUtil;
public class CertPrettyPrintPanel extends WizardPanelBase {
private Vector mCerts = null;
- public CertPrettyPrintPanel() {}
+ public CertPrettyPrintPanel() {
+ }
/**
* Initializes this panel.
*/
- public void init(ServletConfig config, int panelno)
- throws ServletException {
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
setPanelNo(panelno);
setName("Certificates");
}
public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
- throws ServletException {
+ throws ServletException {
setPanelNo(panelno);
setName("Certificates");
setId(id);
@@ -63,7 +63,7 @@ public class CertPrettyPrintPanel extends WizardPanelBase {
public PropertySet getUsage() {
// expects no input from client
PropertySet set = new PropertySet();
-
+
return set;
}
@@ -83,7 +83,8 @@ public class CertPrettyPrintPanel extends WizardPanelBase {
} else {
return true;
}
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
return false;
}
@@ -153,7 +154,7 @@ public class CertPrettyPrintPanel extends WizardPanelBase {
} catch (Exception e) {
CMS.debug(
"CertPrettyPrintPanel: display() certTag " + certTag
- + " Exception caught: " + e.toString());
+ + " Exception caught: " + e.toString());
}
}
} catch (Exception e) {
@@ -192,7 +193,7 @@ public class CertPrettyPrintPanel extends WizardPanelBase {
config.commit(false);
} catch (EBaseException e) {
CMS.debug(
- "CertPrettyPrintPanel: update() Exception caught at config commit: "
+ "CertPrettyPrintPanel: update() Exception caught at config commit: "
+ e.toString());
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/CertRequestPanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/CertRequestPanel.java
index 5e783b1a..d8710c08 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/CertRequestPanel.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/CertRequestPanel.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.IOException;
import java.math.BigInteger;
import java.security.Principal;
@@ -58,35 +57,39 @@ public class CertRequestPanel extends WizardPanelBase {
private Vector mCerts = null;
private WizardServlet mServlet = null;
- public CertRequestPanel() {}
+ public CertRequestPanel() {
+ }
/**
* Initializes this panel.
*/
- public void init(ServletConfig config, int panelno)
- throws ServletException {
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
setPanelNo(panelno);
setName("Requests & Certificates");
}
public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
- throws ServletException {
+ throws ServletException {
setPanelNo(panelno);
setName("Requests and Certificates");
mServlet = servlet;
setId(id);
}
- // XXX how do you do this? There could be multiple certs.
+ // XXX how do you do this? There could be multiple certs.
public PropertySet getUsage() {
PropertySet set = new PropertySet();
-
- Descriptor certDesc = new Descriptor(IDescriptor.STRING, null, /* no constraint */
+
+ Descriptor certDesc = new Descriptor(IDescriptor.STRING, null, /*
+ * no
+ * constraint
+ */
null, /* no default parameters */
null);
set.add("cert", certDesc);
-
+
return set;
}
@@ -95,13 +98,13 @@ public class CertRequestPanel extends WizardPanelBase {
*/
public boolean showApplyButton() {
if (isPanelDone())
- return false;
+ return false;
else
- return true;
+ return true;
}
- private boolean findCertificate(String tokenname, String nickname)
- throws IOException {
+ private boolean findCertificate(String tokenname, String nickname)
+ throws IOException {
IConfigStore cs = CMS.getConfigStore();
CryptoManager cm = null;
try {
@@ -114,7 +117,7 @@ public class CertRequestPanel extends WizardPanelBase {
boolean hardware = false;
if (!tokenname.equals("internal") && !tokenname.equals("Internal Key Storage Token")) {
hardware = true;
- fullnickname = tokenname+":"+nickname;
+ fullnickname = tokenname + ":" + nickname;
}
try {
@@ -126,16 +129,16 @@ public class CertRequestPanel extends WizardPanelBase {
return true;
} catch (Exception ee) {
if (hardware) {
- CMS.debug("CertRequestPanel findCertificate: The certificate with the same nickname: "+ fullnickname +" has been found on HSM. Please remove it before proceeding.");
- throw new IOException("The certificate with the same nickname: "+ fullnickname +" has been found on HSM. Please remove it before proceeding.");
+ CMS.debug("CertRequestPanel findCertificate: The certificate with the same nickname: " + fullnickname + " has been found on HSM. Please remove it before proceeding.");
+ throw new IOException("The certificate with the same nickname: " + fullnickname + " has been found on HSM. Please remove it before proceeding.");
}
return true;
}
} catch (IOException e) {
- CMS.debug("CertRequestPanel findCertificate: throw exception:"+e.toString());
+ CMS.debug("CertRequestPanel findCertificate: throw exception:" + e.toString());
throw e;
} catch (Exception e) {
- CMS.debug("CertRequestPanel findCertificate: Exception="+e.toString());
+ CMS.debug("CertRequestPanel findCertificate: Exception=" + e.toString());
return false;
}
}
@@ -148,13 +151,13 @@ public class CertRequestPanel extends WizardPanelBase {
try {
select = cs.getString("preop.subsystem.select", "");
list = cs.getString("preop.cert.list", "");
- tokenname = cs.getString("preop.module.token", "");
+ tokenname = cs.getString("preop.module.token", "");
} catch (Exception e) {
}
ICertificateAuthority ca = (ICertificateAuthority) CMS.getSubsystem(
- ICertificateAuthority.ID);
-
+ ICertificateAuthority.ID);
+
if (ca != null) {
CMS.debug("CertRequestPanel cleanup: get certificate repository");
BigInteger beginS = null;
@@ -176,27 +179,26 @@ public class CertRequestPanel extends WizardPanelBase {
try {
cr.removeCertRecords(beginS, endS);
} catch (Exception e) {
- CMS.debug("CertRequestPanel cleanUp exception in removing all objects: "+e.toString());
+ CMS.debug("CertRequestPanel cleanUp exception in removing all objects: " + e.toString());
}
-
+
try {
- cr.resetSerialNumber(new BigInteger(beginNum,16));
+ cr.resetSerialNumber(new BigInteger(beginNum, 16));
} catch (Exception e) {
- CMS.debug("CertRequestPanel cleanUp exception in resetting serial number: "+e.toString());
+ CMS.debug("CertRequestPanel cleanUp exception in resetting serial number: " + e.toString());
}
}
}
-
StringTokenizer st = new StringTokenizer(list, ",");
String nickname = "";
boolean enable = false;
while (st.hasMoreTokens()) {
String t = st.nextToken();
-
+
try {
- enable = cs.getBoolean(PCERT_PREFIX+t+".enable", true);
- nickname = cs.getString(PCERT_PREFIX +t+".nickname", "");
+ enable = cs.getBoolean(PCERT_PREFIX + t + ".enable", true);
+ nickname = cs.getString(PCERT_PREFIX + t + ".nickname", "");
} catch (Exception e) {
}
@@ -208,10 +210,10 @@ public class CertRequestPanel extends WizardPanelBase {
if (findCertificate(tokenname, nickname)) {
try {
- CMS.debug("CertRequestPanel cleanup: deleting certificate ("+nickname+").");
- deleteCert(tokenname, nickname);
+ CMS.debug("CertRequestPanel cleanup: deleting certificate (" + nickname + ").");
+ deleteCert(tokenname, nickname);
} catch (Exception e) {
- CMS.debug("CertRequestPanel cleanup: failed to delete certificate (" +nickname+"). Exception: " +e.toString());
+ CMS.debug("CertRequestPanel cleanup: failed to delete certificate (" + nickname + "). Exception: " + e.toString());
}
}
}
@@ -235,7 +237,8 @@ public class CertRequestPanel extends WizardPanelBase {
} else {
return true;
}
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
return false;
}
@@ -254,19 +257,19 @@ public class CertRequestPanel extends WizardPanelBase {
CMS.debug(
"CertRequestPanel getCert: certTag=" + certTag
- + " cert=" + certs);
- //get and set formated cert
- if (!certs.startsWith("...")) {
+ + " cert=" + certs);
+ // get and set formated cert
+ if (!certs.startsWith("...")) {
certf = CryptoUtil.certFormat(certs);
}
cert.setCert(certf);
- //get and set cert pretty print
+ // get and set cert pretty print
byte[] certb = CryptoUtil.base64Decode(certs);
CertPrettyPrint pp = new CertPrettyPrint(certb);
cert.setCertpp(pp.toString(Locale.getDefault()));
} else {
- CMS.debug( "CertRequestPanel::getCert() - cert is null!" );
+ CMS.debug("CertRequestPanel::getCert() - cert is null!");
return;
}
String userfriendlyname = config.getString(
@@ -285,18 +288,16 @@ public class CertRequestPanel extends WizardPanelBase {
}
public X509Key getECCX509Key(IConfigStore config, String certTag)
- throws Exception
- {
+ throws Exception {
X509Key pubk = null;
String pubKeyEncoded = config.getString(
PCERT_PREFIX + certTag + ".pubkey.encoded");
- pubk = CryptoUtil.getPublicX509ECCKey(CryptoUtil.string2byte(pubKeyEncoded));
+ pubk = CryptoUtil.getPublicX509ECCKey(CryptoUtil.string2byte(pubKeyEncoded));
return pubk;
}
public X509Key getRSAX509Key(IConfigStore config, String certTag)
- throws Exception
- {
+ throws Exception {
X509Key pubk = null;
String pubKeyModulus = config.getString(
@@ -305,7 +306,7 @@ public class CertRequestPanel extends WizardPanelBase {
PCERT_PREFIX + certTag + ".pubkey.exponent");
pubk = CryptoUtil.getPublicX509Key(
CryptoUtil.string2byte(pubKeyModulus),
- CryptoUtil.string2byte(pubKeyPublicExponent));
+ CryptoUtil.string2byte(pubKeyPublicExponent));
return pubk;
}
@@ -323,8 +324,8 @@ public class CertRequestPanel extends WizardPanelBase {
} else if (pubKeyType.equals("ecc")) {
pubk = getECCX509Key(config, certTag);
} else {
- CMS.debug( "CertRequestPanel::handleCertRequest() - "
- + "pubKeyType " + pubKeyType + " is unsupported!" );
+ CMS.debug("CertRequestPanel::handleCertRequest() - "
+ + "pubKeyType " + pubKeyType + " is unsupported!");
return;
}
@@ -341,7 +342,7 @@ public class CertRequestPanel extends WizardPanelBase {
PCERT_PREFIX + certTag + ".privkey.id");
CMS.debug("CertRequestPanel: privKeyID=" + privKeyID);
byte[] keyIDb = CryptoUtil.string2byte(privKeyID);
-
+
PrivateKey privk = CryptoUtil.findPrivateKeyFromID(keyIDb);
if (privk != null) {
@@ -349,7 +350,7 @@ public class CertRequestPanel extends WizardPanelBase {
} else {
CMS.debug("CertRequestPanel: error getting private key null");
}
-
+
// construct cert request
String caDN = config.getString(PCERT_PREFIX + certTag + ".dn");
@@ -361,7 +362,7 @@ public class CertRequestPanel extends WizardPanelBase {
byte[] certReqb = certReq.toByteArray();
String certReqs = CryptoUtil.base64Encode(certReqb);
String certReqf = CryptoUtil.reqFormat(certReqs);
-
+
String subsystem = config.getString(
PCERT_PREFIX + certTag + ".subsystem");
config.putString(subsystem + "." + certTag + ".certreq", certReqs);
@@ -410,7 +411,7 @@ public class CertRequestPanel extends WizardPanelBase {
PCERT_PREFIX + certTag + ".type");
c.setType(type);
- boolean enable = config.getBoolean(PCERT_PREFIX+certTag+".enable", true);
+ boolean enable = config.getBoolean(PCERT_PREFIX + certTag + ".enable", true);
c.setEnable(enable);
getCert(config, context, certTag, c);
@@ -458,7 +459,7 @@ public class CertRequestPanel extends WizardPanelBase {
if (issuerDN.equals(subjectDN))
return true;
} catch (Exception e) {
- CMS.debug("CertRequestPanel findBootstrapServerCert Exception="+e.toString());
+ CMS.debug("CertRequestPanel findBootstrapServerCert Exception=" + e.toString());
}
return false;
@@ -472,7 +473,7 @@ public class CertRequestPanel extends WizardPanelBase {
deleteCert("Internal Key Storage Token", nickname);
} catch (Exception e) {
- CMS.debug("CertRequestPanel deleteBootstrapServerCert Exception="+e.toString());
+ CMS.debug("CertRequestPanel deleteBootstrapServerCert Exception=" + e.toString());
}
}
@@ -502,7 +503,7 @@ public class CertRequestPanel extends WizardPanelBase {
String tokenname = "";
try {
- tokenname = config.getString("preop.module.token", "");
+ tokenname = config.getString("preop.module.token", "");
} catch (Exception e) {
}
@@ -510,11 +511,11 @@ public class CertRequestPanel extends WizardPanelBase {
Cert cert = (Cert) c.nextElement();
String certTag = cert.getCertTag();
String subsystem = cert.getSubsystem();
- boolean enable = config.getBoolean(PCERT_PREFIX+certTag+".enable", true);
+ boolean enable = config.getBoolean(PCERT_PREFIX + certTag + ".enable", true);
if (!enable)
continue;
- if (hasErr)
+ if (hasErr)
continue;
String nickname = cert.getNickname();
@@ -522,7 +523,8 @@ public class CertRequestPanel extends WizardPanelBase {
CMS.debug(
"CertRequestPanel: update() for cert tag "
+ cert.getCertTag());
- // String b64 = config.getString(CERT_PREFIX+ certTag +".cert", "");
+ // String b64 = config.getString(CERT_PREFIX+ certTag +".cert",
+ // "");
String b64 = HttpInput.getCert(request, certTag);
if (cert.getType().equals("local")
@@ -533,20 +535,20 @@ public class CertRequestPanel extends WizardPanelBase {
PCERT_PREFIX + certTag + ".keytype");
X509Key x509key = null;
if (pubKeyType.equals("rsa")) {
- x509key = getRSAX509Key(config, certTag);
+ x509key = getRSAX509Key(config, certTag);
} else if (pubKeyType.equals("ecc")) {
- x509key = getECCX509Key(config, certTag);
+ x509key = getECCX509Key(config, certTag);
}
-
+
if (findCertificate(tokenname, nickname)) {
if (!certTag.equals("sslserver"))
- continue;
+ continue;
}
- X509CertImpl impl = CertUtil.createLocalCert(config, x509key,
+ X509CertImpl impl = CertUtil.createLocalCert(config, x509key,
PCERT_PREFIX, certTag, cert.getType(), context);
if (impl != null) {
- byte[] certb = impl.getEncoded();
+ byte[] certb = impl.getEncoded();
String certs = CryptoUtil.base64Encode(certb);
cert.setCert(certs);
@@ -574,13 +576,13 @@ public class CertRequestPanel extends WizardPanelBase {
+ certTag + " Exception: "
+ ee.toString());
CMS.debug("ok");
-// hasErr = true;
+ // hasErr = true;
}
}
} else if (cert.getType().equals("remote")) {
if (b64 != null && b64.length() > 0
&& !b64.startsWith("...")) {
- String b64chain = HttpInput.getCertChain(request, certTag+"_cc");
+ String b64chain = HttpInput.getCertChain(request, certTag + "_cc");
CMS.debug(
"CertRequestPanel: in update() process remote...import cert");
@@ -590,11 +592,11 @@ public class CertRequestPanel extends WizardPanelBase {
try {
if (certTag.equals("sslserver") && findBootstrapServerCert())
deleteBootstrapServerCert();
- if (findCertificate(tokenname, nickname)) {
- deleteCert(tokenname, nickname);
+ if (findCertificate(tokenname, nickname)) {
+ deleteCert(tokenname, nickname);
}
} catch (Exception e) {
- CMS.debug("CertRequestPanel update (remote): deleteCert Exception="+e.toString());
+ CMS.debug("CertRequestPanel update (remote): deleteCert Exception=" + e.toString());
}
input = CryptoUtil.stripCertBrackets(input.trim());
String certs = CryptoUtil.normalizeCertStr(input);
@@ -619,21 +621,21 @@ public class CertRequestPanel extends WizardPanelBase {
leaf = certchains[certchains.length - 1];
}
- if( leaf == null ) {
- CMS.debug( "CertRequestPanel::update() - "
- + "leaf is null!" );
- throw new IOException( "leaf is null" );
+ if (leaf == null) {
+ CMS.debug("CertRequestPanel::update() - "
+ + "leaf is null!");
+ throw new IOException("leaf is null");
}
- if (/*(certchains.length <= 1) &&*/
- (b64chain != null && b64chain.length() != 0)) {
- CMS.debug("CertRequestPanel: cert might not have contained chain...calling importCertificateChain: " + b64chain);
- try {
- CryptoUtil.importCertificateChain(
- CryptoUtil.normalizeCertAndReq(b64chain));
- } catch (Exception e) {
- CMS.debug("CertRequestPanel: importCertChain: Exception: "+e.toString());
- }
+ if (/* (certchains.length <= 1) && */
+ (b64chain != null && b64chain.length() != 0)) {
+ CMS.debug("CertRequestPanel: cert might not have contained chain...calling importCertificateChain: " + b64chain);
+ try {
+ CryptoUtil.importCertificateChain(
+ CryptoUtil.normalizeCertAndReq(b64chain));
+ } catch (Exception e) {
+ CMS.debug("CertRequestPanel: importCertChain: Exception: " + e.toString());
+ }
}
InternalCertificate icert = (InternalCertificate) leaf;
@@ -651,17 +653,17 @@ public class CertRequestPanel extends WizardPanelBase {
+ certTag + " Exception: "
+ ee.toString());
CMS.debug("ok");
-// hasErr=true;
+ // hasErr=true;
}
} else {
CMS.debug("CertRequestPanel: in update() input null");
hasErr = true;
}
} else {
- CMS.debug("CertRequestPanel: in update() b64 not set");
- hasErr=true;
+ CMS.debug("CertRequestPanel: in update() b64 not set");
+ hasErr = true;
}
-
+
} else {
b64 = CryptoUtil.stripCertBrackets(b64.trim());
String certs = CryptoUtil.normalizeCertStr(b64);
@@ -671,10 +673,10 @@ public class CertRequestPanel extends WizardPanelBase {
if (certTag.equals("sslserver") && findBootstrapServerCert())
deleteBootstrapServerCert();
if (findCertificate(tokenname, nickname)) {
- deleteCert(tokenname, nickname);
+ deleteCert(tokenname, nickname);
}
} catch (Exception ee) {
- CMS.debug("CertRequestPanel update: deleteCert Exception="+ee.toString());
+ CMS.debug("CertRequestPanel update: deleteCert Exception=" + ee.toString());
}
try {
@@ -683,12 +685,13 @@ public class CertRequestPanel extends WizardPanelBase {
else
CryptoUtil.importUserCertificate(impl, nickname, false);
} catch (Exception ee) {
- CMS.debug("CertRequestPanel: Failed to import user certificate."+ee.toString());
- hasErr=true;
+ CMS.debug("CertRequestPanel: Failed to import user certificate." + ee.toString());
+ hasErr = true;
}
}
- //update requests in request queue for local certs to allow renewal
+ // update requests in request queue for local certs to allow
+ // renewal
if ((cert.getType().equals("local")) || (cert.getType().equals("selfsign"))) {
CertUtil.updateLocalRequest(config, certTag, cert.getRequest(), "pkcs10", null);
}
@@ -696,16 +699,16 @@ public class CertRequestPanel extends WizardPanelBase {
if (certTag.equals("signing") && subsystem.equals("ca")) {
String NickName = nickname;
if (!tokenname.equals("internal") && !tokenname.equals("Internal Key Storage Token"))
- NickName = tokenname+ ":"+ nickname;
+ NickName = tokenname + ":" + nickname;
- CMS.debug("CertRequestPanel update: set trust on CA signing cert "+NickName);
+ CMS.debug("CertRequestPanel update: set trust on CA signing cert " + NickName);
CryptoUtil.trustCertByNickname(NickName);
CMS.reinit(ICertificateAuthority.ID);
- }
- } //while loop
+ }
+ } // while loop
if (hasErr == false) {
- config.putBoolean("preop.CertRequestPanel.done", true);
+ config.putBoolean("preop.CertRequestPanel.done", true);
}
config.commit(false);
} catch (Exception e) {
@@ -713,7 +716,7 @@ public class CertRequestPanel extends WizardPanelBase {
System.err.println("Exception caught: " + e.toString());
}
- //reset the attribute of the user certificate to u,u,u
+ // reset the attribute of the user certificate to u,u,u
String certlist = "";
try {
certlist = config.getString("preop.cert.list", "");
@@ -723,13 +726,13 @@ public class CertRequestPanel extends WizardPanelBase {
String tag = tokenizer.nextToken();
if (tag.equals("signing"))
continue;
- String nickname = config.getString("preop.cert."+tag+".nickname", "");
+ String nickname = config.getString("preop.cert." + tag + ".nickname", "");
String tokenname = config.getString("preop.module.token", "");
if (!tokenname.equals("Internal Key Storage Token"))
- nickname = tokenname+":"+nickname;
+ nickname = tokenname + ":" + nickname;
X509Certificate c = cm.findCertByNickname(nickname);
if (c instanceof InternalCertificate) {
- InternalCertificate ic = (InternalCertificate)c;
+ InternalCertificate ic = (InternalCertificate) c;
ic.setSSLTrust(InternalCertificate.USER);
ic.setEmailTrust(InternalCertificate.USER);
if (tag.equals("audit_signing")) {
@@ -738,10 +741,10 @@ public class CertRequestPanel extends WizardPanelBase {
ic.setObjectSigningTrust(InternalCertificate.USER);
}
}
- }
+ }
} catch (Exception e) {
}
- if (!hasErr) {
+ if (!hasErr) {
context.put("updateStatus", "success");
} else {
context.put("updateStatus", "failure");
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/CertUtil.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/CertUtil.java
index 3725149d..dc81d3e4 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/CertUtil.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/CertUtil.java
@@ -64,13 +64,12 @@ import com.netscape.cmsutil.http.HttpResponse;
import com.netscape.cmsutil.http.JssSSLSocketFactory;
import com.netscape.cmsutil.xml.XMLObject;
-
public class CertUtil {
static final int LINE_COUNT = 76;
- public static X509CertImpl createRemoteCert(String hostname,
- int port, String content, HttpServletResponse response, WizardPanelBase panel)
- throws IOException {
+ public static X509CertImpl createRemoteCert(String hostname,
+ int port, String content, HttpServletResponse response, WizardPanelBase panel)
+ throws IOException {
HttpClient httpclient = new HttpClient();
String c = null;
CMS.debug("CertUtil createRemoteCert: content " + content);
@@ -104,15 +103,15 @@ public class CertUtil {
try {
parser = new XMLObject(bis);
} catch (Exception e) {
- CMS.debug( "CertUtil::createRemoteCert() - "
- + "Exception="+e.toString() );
- throw new IOException( e.toString() );
+ CMS.debug("CertUtil::createRemoteCert() - "
+ + "Exception=" + e.toString());
+ throw new IOException(e.toString());
}
String status = parser.getValue("Status");
CMS.debug("CertUtil createRemoteCert: status=" + status);
if (status.equals("2")) {
- //relogin to the security domain
+ // relogin to the security domain
panel.reloginSecurityDomain(response);
return null;
} else if (!status.equals("0")) {
@@ -136,7 +135,7 @@ public class CertUtil {
return null;
}
- public static String getPKCS10(IConfigStore config, String prefix,
+ public static String getPKCS10(IConfigStore config, String prefix,
Cert certObj, Context context) throws IOException {
String certTag = certObj.getCertTag();
@@ -147,29 +146,29 @@ public class CertUtil {
String algorithm = config.getString(
prefix + certTag + ".keyalgorithm");
if (pubKeyType.equals("rsa")) {
- String pubKeyModulus = config.getString(
- prefix + certTag + ".pubkey.modulus");
- String pubKeyPublicExponent = config.getString(
- prefix + certTag + ".pubkey.exponent");
- pubk = CryptoUtil.getPublicX509Key(
- CryptoUtil.string2byte(pubKeyModulus),
- CryptoUtil.string2byte(pubKeyPublicExponent));
+ String pubKeyModulus = config.getString(
+ prefix + certTag + ".pubkey.modulus");
+ String pubKeyPublicExponent = config.getString(
+ prefix + certTag + ".pubkey.exponent");
+ pubk = CryptoUtil.getPublicX509Key(
+ CryptoUtil.string2byte(pubKeyModulus),
+ CryptoUtil.string2byte(pubKeyPublicExponent));
} else if (pubKeyType.equals("ecc")) {
- String pubKeyEncoded = config.getString(
+ String pubKeyEncoded = config.getString(
prefix + certTag + ".pubkey.encoded");
- pubk = CryptoUtil.getPublicX509ECCKey(
- CryptoUtil.string2byte(pubKeyEncoded));
+ pubk = CryptoUtil.getPublicX509ECCKey(
+ CryptoUtil.string2byte(pubKeyEncoded));
} else {
- CMS.debug( "CertRequestPanel::getPKCS10() - "
- + "public key type is unsupported!" );
- throw new IOException( "public key type is unsupported" );
+ CMS.debug("CertRequestPanel::getPKCS10() - "
+ + "public key type is unsupported!");
+ throw new IOException("public key type is unsupported");
}
if (pubk != null) {
CMS.debug("CertRequestPanel: got public key");
} else {
CMS.debug("CertRequestPanel: error getting public key null");
- throw new IOException( "public key is null" );
+ throw new IOException("public key is null");
}
// get private key
String privKeyID = config.getString(prefix + certTag + ".privkey.id");
@@ -201,15 +200,14 @@ public class CertUtil {
}
}
-
-/*
- * create requests so renewal can work on these initial certs
- */
+ /*
+ * create requests so renewal can work on these initial certs
+ */
public static IRequest createLocalRequest(IRequestQueue queue, String serialNum, X509CertInfo info) throws EBaseException {
-// RequestId rid = new RequestId(serialNum);
+ // RequestId rid = new RequestId(serialNum);
// just need a request, no need to get into a queue
-// IRequest r = new EnrollmentRequest(rid);
- CMS.debug("CertUtil: createLocalRequest for serial: "+ serialNum);
+ // IRequest r = new EnrollmentRequest(rid);
+ CMS.debug("CertUtil: createLocalRequest for serial: " + serialNum);
IRequest req = queue.newRequest("enrollment");
CMS.debug("certUtil: newRequest called");
req.setExtData("profile", "true");
@@ -224,7 +222,7 @@ public class CertUtil {
req.setExtData("requestor_phone", "");
req.setExtData("profileRemoteHost", "");
req.setExtData("profileRemoteAddr", "");
- req.setExtData("requestnotes","");
+ req.setExtData("requestnotes", "");
req.setExtData("isencryptioncert", "false");
req.setExtData("profileapprovedby", "system");
@@ -235,13 +233,12 @@ public class CertUtil {
return req;
}
-/**
- * update local cert request with the actual request
- * called from CertRequestPanel.java
- */
- public static void updateLocalRequest(IConfigStore config, String certTag, String certReq, String reqType, String subjectName)
- {
- try {
+ /**
+ * update local cert request with the actual request called from
+ * CertRequestPanel.java
+ */
+ public static void updateLocalRequest(IConfigStore config, String certTag, String certReq, String reqType, String subjectName) {
+ try {
CMS.debug("Updating local request... certTag=" + certTag);
RequestId rid = new RequestId(config.getString("preop.cert." + certTag + ".reqId"));
@@ -262,54 +259,56 @@ public class CertUtil {
}
queue.updateRequest(req);
} else {
- CMS.debug("CertUtil:updateLocalRequest - request queue = null");
+ CMS.debug("CertUtil:updateLocalRequest - request queue = null");
}
} catch (Exception e) {
CMS.debug("CertUtil:updateLocalRequest - Exception:" + e.toString());
}
}
-/**
- * reads from the admin cert profile caAdminCert.profile and takes the first
- * entry in the list of allowed algorithms. Users that wish a different algorithm
- * can specify it in the profile using default.params.signingAlg
- */
+ /**
+ * reads from the admin cert profile caAdminCert.profile and takes the first
+ * entry in the list of allowed algorithms. Users that wish a different
+ * algorithm can specify it in the profile using default.params.signingAlg
+ */
public static String getAdminProfileAlgorithm(IConfigStore config) {
String algorithm = "SHA256withRSA";
try {
- String caSigningKeyType = config.getString("preop.cert.signing.keytype","rsa");
+ String caSigningKeyType = config.getString("preop.cert.signing.keytype", "rsa");
String pfile = config.getString("profile.caAdminCert.config");
FileInputStream fis = new FileInputStream(pfile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
- String strLine;
- while ((strLine = br.readLine()) != null) {
- String marker2 = "default.params.signingAlg=";
- int indx = strLine.indexOf(marker2);
- if (indx != -1) {
- String alg = strLine.substring(indx + marker2.length());
- if ((alg.length() > 0) && (!alg.equals("-"))) {
- algorithm = alg;
- break;
- };
- };
-
- String marker = "signingAlgsAllowed=";
- indx = strLine.indexOf(marker);
- if (indx != -1) {
- String[] algs = strLine.substring(indx + marker.length()).split(",");
- for (int i=0; i<algs.length; i++) {
- if ((caSigningKeyType.equals("rsa") && (algs[i].indexOf("RSA") != -1)) ||
- (caSigningKeyType.equals("ecc") && (algs[i].indexOf("EC" ) != -1)) ) {
- algorithm = algs[i];
- break;
- }
- }
- }
- }
- in.close();
+ String strLine;
+ while ((strLine = br.readLine()) != null) {
+ String marker2 = "default.params.signingAlg=";
+ int indx = strLine.indexOf(marker2);
+ if (indx != -1) {
+ String alg = strLine.substring(indx + marker2.length());
+ if ((alg.length() > 0) && (!alg.equals("-"))) {
+ algorithm = alg;
+ break;
+ }
+ ;
+ }
+ ;
+
+ String marker = "signingAlgsAllowed=";
+ indx = strLine.indexOf(marker);
+ if (indx != -1) {
+ String[] algs = strLine.substring(indx + marker.length()).split(",");
+ for (int i = 0; i < algs.length; i++) {
+ if ((caSigningKeyType.equals("rsa") && (algs[i].indexOf("RSA") != -1)) ||
+ (caSigningKeyType.equals("ecc") && (algs[i].indexOf("EC") != -1))) {
+ algorithm = algs[i];
+ break;
+ }
+ }
+ }
+ }
+ in.close();
} catch (Exception e) {
CMS.debug("getAdminProfleAlgorithm: exception: " + e);
}
@@ -324,14 +323,15 @@ public class CertUtil {
try {
profile = config.getString(prefix + certTag + ".profile");
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
X509CertImpl cert = null;
ICertificateAuthority ca = null;
ICertificateRepository cr = null;
RequestId reqId = null;
String profileId = null;
- IRequestQueue queue = null;
+ IRequestQueue queue = null;
IRequest req = null;
try {
@@ -355,7 +355,7 @@ public class CertUtil {
CMS.debug("Creating local certificate... dn=" + dn);
info = CryptoUtil.createX509CertInfo(x509key, serialNo.intValue(), dn, dn, date,
date, keyAlgorithm);
- } else {
+ } else {
String issuerdn = config.getString("preop.cert.signing.dn", "");
CMS.debug("Creating local certificate... issuerdn=" + issuerdn);
CMS.debug("Creating local certificate... dn=" + dn);
@@ -375,7 +375,7 @@ public class CertUtil {
queue = ca.getRequestQueue();
if (queue != null) {
req = createLocalRequest(queue, serialNo.toString(), info);
- CMS.debug("CertUtil profile name= "+profile);
+ CMS.debug("CertUtil profile name= " + profile);
req.setExtData("req_key", x509key.toString());
// store original profile id in cert request
@@ -387,7 +387,7 @@ public class CertUtil {
String name = profile.substring(0, idx);
req.setExtData("origprofileid", name);
}
-
+
// store mapped profile ID for use in renewal
profileId = processor.getProfileIDMapping();
req.setExtData("profileid", profileId);
@@ -399,7 +399,7 @@ public class CertUtil {
CMS.debug("certUtil: requestQueue null");
}
} catch (Exception e) {
- CMS.debug("Creating local request exception:"+e.toString());
+ CMS.debug("Creating local request exception:" + e.toString());
}
processor.populate(info);
@@ -410,36 +410,36 @@ public class CertUtil {
PrivateKey caPrik = CryptoUtil.findPrivateKeyFromID(
keyIDb);
- if( caPrik == null ) {
- CMS.debug( "CertUtil::createSelfSignedCert() - "
- + "CA private key is null!" );
- throw new IOException( "CA private key is null" );
+ if (caPrik == null) {
+ CMS.debug("CertUtil::createSelfSignedCert() - "
+ + "CA private key is null!");
+ throw new IOException("CA private key is null");
} else {
CMS.debug("CertUtil createSelfSignedCert: got CA private key");
}
String keyAlgo = x509key.getAlgorithm();
CMS.debug("key algorithm is " + keyAlgo);
- String caSigningKeyType =
- config.getString("preop.cert.signing.keytype","rsa");
- String caSigningKeyAlgo = "";
- if (type.equals("selfsign")) {
- caSigningKeyAlgo = config.getString("preop.cert.signing.keyalgorithm","SHA256withRSA");
+ String caSigningKeyType =
+ config.getString("preop.cert.signing.keytype", "rsa");
+ String caSigningKeyAlgo = "";
+ if (type.equals("selfsign")) {
+ caSigningKeyAlgo = config.getString("preop.cert.signing.keyalgorithm", "SHA256withRSA");
} else {
- caSigningKeyAlgo = config.getString("preop.cert.signing.signingalgorithm","SHA256withRSA");
+ caSigningKeyAlgo = config.getString("preop.cert.signing.signingalgorithm", "SHA256withRSA");
}
CMS.debug("CA Signing Key type " + caSigningKeyType);
CMS.debug("CA Signing Key algorithm " + caSigningKeyAlgo);
if (caSigningKeyType.equals("ecc")) {
- CMS.debug("CA signing cert is ECC");
- cert = CryptoUtil.signECCCert(caPrik, info,
- caSigningKeyAlgo);
+ CMS.debug("CA signing cert is ECC");
+ cert = CryptoUtil.signECCCert(caPrik, info,
+ caSigningKeyAlgo);
} else {
- CMS.debug("CA signing cert is not ecc");
- cert = CryptoUtil.signCert(caPrik, info,
- caSigningKeyAlgo);
+ CMS.debug("CA signing cert is not ecc");
+ cert = CryptoUtil.signCert(caPrik, info,
+ caSigningKeyAlgo);
}
if (cert != null) {
@@ -462,13 +462,13 @@ public class CertUtil {
if (reqId != null) {
meta.set(ICertRecord.META_REQUEST_ID, reqId.toString());
}
-
+
meta.set(ICertRecord.META_PROFILE_ID, profileId);
record = (ICertRecord) cr.createCertRecord(
- cert.getSerialNumber(), cert, meta);
+ cert.getSerialNumber(), cert, meta);
} catch (Exception e) {
CMS.debug(
- "NamePanel configCert: failed to add metainfo. Exception: " + e.toString());
+ "NamePanel configCert: failed to add metainfo. Exception: " + e.toString());
}
try {
@@ -488,10 +488,10 @@ public class CertUtil {
}
if (req != null) {
- // update request with cert
+ // update request with cert
req.setExtData(IEnrollProfile.REQUEST_ISSUED_CERT, cert);
- // store request in db
+ // store request in db
try {
CMS.debug("certUtil: before updateRequest");
if (queue != null) {
@@ -507,21 +507,21 @@ public class CertUtil {
public static void addUserCertificate(X509CertImpl cert) {
IConfigStore cs = CMS.getConfigStore();
- int num=0;
+ int num = 0;
try {
num = cs.getInteger("preop.subsystem.count", 0);
} catch (Exception e) {
}
IUGSubsystem system = (IUGSubsystem) (CMS.getSubsystem(IUGSubsystem.ID));
- String id = "user"+num;
+ String id = "user" + num;
- try {
- String sysType = cs.getString("cs.type", "");
- String machineName = cs.getString("machineName", "");
- String securePort = cs.getString("service.securePort", "");
- id = sysType + "-" + machineName + "-" + securePort;
+ try {
+ String sysType = cs.getString("cs.type", "");
+ String machineName = cs.getString("machineName", "");
+ String securePort = cs.getString("service.securePort", "");
+ id = sysType + "-" + machineName + "-" + securePort;
} catch (Exception e1) {
- // ignore
+ // ignore
}
num++;
@@ -566,7 +566,7 @@ public class CertUtil {
system.addUserCert(user);
CMS.debug("CertUtil addUserCertificate: successfully add the user certificate");
} catch (Exception e) {
- CMS.debug("CertUtil addUserCertificate exception="+e.toString());
+ CMS.debug("CertUtil addUserCertificate exception=" + e.toString());
}
IGroup group = null;
@@ -603,17 +603,17 @@ public class CertUtil {
}
if (content.length() > 0)
result.append(content);
- result.append("\n");
+ result.append("\n");
return result.toString();
}
public static boolean privateKeyExistsOnToken(String certTag,
- String tokenname, String nickname) {
+ String tokenname, String nickname) {
IConfigStore cs = CMS.getConfigStore();
String givenid = "";
try {
- givenid = cs.getString("preop.cert."+certTag+".privkey.id");
+ givenid = cs.getString("preop.cert." + certTag + ".privkey.id");
} catch (Exception e) {
CMS.debug("CertUtil privateKeyExistsOnToken: we did not generate private key yet.");
return false;
@@ -624,7 +624,7 @@ public class CertUtil {
boolean hardware = false;
if (!tokenname.equals("internal") && !tokenname.equals("Internal Key Storage Token")) {
hardware = true;
- fullnickname = tokenname+":"+nickname;
+ fullnickname = tokenname + ":" + nickname;
}
X509Certificate cert = null;
@@ -633,7 +633,7 @@ public class CertUtil {
cm = CryptoManager.getInstance();
cert = cm.findCertByNickname(fullnickname);
} catch (Exception e) {
- CMS.debug("CertUtil privateKeyExistsOnToken: nickname="+fullnickname+" Exception:"+e.toString());
+ CMS.debug("CertUtil privateKeyExistsOnToken: nickname=" + fullnickname + " Exception:" + e.toString());
return false;
}
@@ -641,19 +641,19 @@ public class CertUtil {
try {
privKey = cm.findPrivKeyByCert(cert);
} catch (Exception e) {
- CMS.debug("CertUtil privateKeyExistsOnToken: cant find private key ("+fullnickname+") exception: "+e.toString());
+ CMS.debug("CertUtil privateKeyExistsOnToken: cant find private key (" + fullnickname + ") exception: " + e.toString());
return false;
}
if (privKey == null) {
- CMS.debug("CertUtil privateKeyExistsOnToken: cant find private key ("+fullnickname+")");
+ CMS.debug("CertUtil privateKeyExistsOnToken: cant find private key (" + fullnickname + ")");
return false;
} else {
String str = "";
try {
str = CryptoUtil.byte2string(privKey.getUniqueID());
} catch (Exception e) {
- CMS.debug("CertUtil privateKeyExistsOnToken: encode string Exception: "+e.toString());
+ CMS.debug("CertUtil privateKeyExistsOnToken: encode string Exception: " + e.toString());
}
if (str.equals(givenid)) {
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/CheckIdentity.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/CheckIdentity.java
index b3c10b6e..a28ae76b 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/CheckIdentity.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/CheckIdentity.java
@@ -36,7 +36,6 @@ import com.netscape.cms.servlet.base.UserInfo;
import com.netscape.cms.servlet.common.CMSRequest;
import com.netscape.cmsutil.xml.XMLObject;
-
public class CheckIdentity extends CMSServlet {
/**
@@ -52,6 +51,7 @@ public class CheckIdentity extends CMSServlet {
/**
* initialize the servlet.
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -61,7 +61,8 @@ public class CheckIdentity extends CMSServlet {
}
/**
- * Process the HTTP request.
+ * Process the HTTP request.
+ *
* @param cmsReq the object holding the request and response information
*/
protected void process(CMSRequest cmsReq) throws EBaseException {
@@ -74,12 +75,12 @@ public class CheckIdentity extends CMSServlet {
authToken = authenticate(cmsReq);
} catch (Exception e) {
CMS.debug("CheckIdentity authentication failed");
- log(ILogger.LL_FAILURE,
+ log(ILogger.LL_FAILURE,
CMS.getLogMessage("CMSGW_ERR_BAD_SERV_OUT_STREAM", "",
- e.toString()));
+ e.toString()));
outputError(httpResp, "Error: Not authenticated");
return;
- }
+ }
try {
XMLObject xmlObj = null;
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigBaseServlet.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigBaseServlet.java
index f2587300..b538dbb5 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigBaseServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigBaseServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
@@ -28,7 +27,6 @@ import org.apache.velocity.context.Context;
import com.netscape.certsrv.apps.CMS;
-
public abstract class ConfigBaseServlet extends BaseServlet {
/**
*
@@ -50,7 +48,7 @@ public abstract class ConfigBaseServlet extends BaseServlet {
public abstract void display(HttpServletRequest request,
HttpServletResponse response, Context context);
- public abstract void update(HttpServletRequest request,
+ public abstract void update(HttpServletRequest request,
HttpServletResponse response, Context context);
public abstract Template getTemplate(HttpServletRequest request,
@@ -64,29 +62,29 @@ public abstract class ConfigBaseServlet extends BaseServlet {
while (paramNames.hasMoreElements()) {
String pn = (String) paramNames.nextElement();
// added this facility so that password can be hidden,
- // all sensitive parameters should be prefixed with
+ // all sensitive parameters should be prefixed with
// __ (double underscores); however, in the event that
// a security parameter slips through, we perform multiple
// additional checks to insure that it is NOT displayed
- if( pn.startsWith("__") ||
- pn.endsWith("password") ||
- pn.endsWith("passwd") ||
- pn.endsWith("pwd") ||
- pn.equalsIgnoreCase("admin_password_again") ||
- pn.equalsIgnoreCase("directoryManagerPwd") ||
- pn.equalsIgnoreCase("bindpassword") ||
- pn.equalsIgnoreCase("bindpwd") ||
- pn.equalsIgnoreCase("passwd") ||
- pn.equalsIgnoreCase("password") ||
- pn.equalsIgnoreCase("pin") ||
- pn.equalsIgnoreCase("pwd") ||
- pn.equalsIgnoreCase("pwdagain") ||
- pn.equalsIgnoreCase("uPasswd") ) {
- CMS.debug("ConfigBaseServlet::service() param name='" + pn +
- "' value='(sensitive)'" );
+ if (pn.startsWith("__") ||
+ pn.endsWith("password") ||
+ pn.endsWith("passwd") ||
+ pn.endsWith("pwd") ||
+ pn.equalsIgnoreCase("admin_password_again") ||
+ pn.equalsIgnoreCase("directoryManagerPwd") ||
+ pn.equalsIgnoreCase("bindpassword") ||
+ pn.equalsIgnoreCase("bindpwd") ||
+ pn.equalsIgnoreCase("passwd") ||
+ pn.equalsIgnoreCase("password") ||
+ pn.equalsIgnoreCase("pin") ||
+ pn.equalsIgnoreCase("pwd") ||
+ pn.equalsIgnoreCase("pwdagain") ||
+ pn.equalsIgnoreCase("uPasswd")) {
+ CMS.debug("ConfigBaseServlet::service() param name='" + pn +
+ "' value='(sensitive)'");
} else {
- CMS.debug("ConfigBaseServlet::service() param name='" + pn +
- "' value='" + httpReq.getParameter(pn) + "'" );
+ CMS.debug("ConfigBaseServlet::service() param name='" + pn +
+ "' value='" + httpReq.getParameter(pn) + "'");
}
}
}
@@ -97,7 +95,7 @@ public abstract class ConfigBaseServlet extends BaseServlet {
public Template process(HttpServletRequest request,
HttpServletResponse response,
Context context) {
-
+
if (CMS.debugOn()) {
outputHttpParameters(request);
}
@@ -107,16 +105,16 @@ public abstract class ConfigBaseServlet extends BaseServlet {
} else {
update(request, response, context);
}
-
+
Template template = null;
-
+
try {
context.put("name", "Velocity Test");
template = getTemplate(request, response, context);
} catch (Exception e) {
System.err.println("Exception caught: " + e.getMessage());
}
-
+
return template;
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigCertApprovalCallback.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigCertApprovalCallback.java
index d95c85d1..956c285b 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigCertApprovalCallback.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigCertApprovalCallback.java
@@ -20,16 +20,14 @@ package com.netscape.cms.servlet.csadmin;
import org.mozilla.jss.crypto.X509Certificate;
import org.mozilla.jss.ssl.SSLCertificateApprovalCallback;
-
-public class ConfigCertApprovalCallback
- implements SSLCertificateApprovalCallback {
+public class ConfigCertApprovalCallback
+ implements SSLCertificateApprovalCallback {
public ConfigCertApprovalCallback() {
}
public boolean approve(X509Certificate cert,
- SSLCertificateApprovalCallback.ValidityStatus status) {
- return true;
+ SSLCertificateApprovalCallback.ValidityStatus status) {
+ return true;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigCertReqServlet.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigCertReqServlet.java
index 37493b6b..b04de414 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigCertReqServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigCertReqServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -25,7 +24,6 @@ import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;
-
public class ConfigCertReqServlet extends BaseServlet {
/**
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigCloneServlet.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigCloneServlet.java
index e7d88a35..ed1d9cc0 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigCloneServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigCloneServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -25,7 +24,6 @@ import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;
-
public class ConfigCloneServlet extends BaseServlet {
/**
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigDatabaseServlet.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigDatabaseServlet.java
index 08ebf08e..2b4a82a0 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigDatabaseServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigDatabaseServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -28,7 +27,6 @@ import org.apache.velocity.context.Context;
import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.base.IConfigStore;
-
public class ConfigDatabaseServlet extends ConfigBaseServlet {
/**
@@ -47,7 +45,8 @@ public class ConfigDatabaseServlet extends ConfigBaseServlet {
try {
modified = cs.getString("preop.configDatabase.modified", "");
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
if (modified.equals("true")) {
return true;
@@ -75,7 +74,8 @@ public class ConfigDatabaseServlet extends ConfigBaseServlet {
basedn = cs.getString("internaldb.basedn", "");
binddn = cs.getString("internaldb.ldapauth.bindDN", "");
database = cs.getString("internaldb.database", "");
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
} else {
hostname = HOST;
portStr = PORT;
@@ -113,7 +113,7 @@ public class ConfigDatabaseServlet extends ConfigBaseServlet {
int port = -1;
try {
- port = Integer.parseInt(portStr);
+ port = Integer.parseInt(portStr);
cs.putInteger("internaldb.ldapconn.port", port);
} catch (Exception e) {
errorString = "Port is invalid";
@@ -159,7 +159,7 @@ public class ConfigDatabaseServlet extends ConfigBaseServlet {
CMS.debug("ConfigDatabaseServlet update: " + e.toString());
return;
}
- psStore.putString("internaldb", bindpwd);
+ psStore.putString("internaldb", bindpwd);
} else {
errorString = "Bind password is empty string";
}
@@ -189,7 +189,8 @@ public class ConfigDatabaseServlet extends ConfigBaseServlet {
Context context) {
try {
return Velocity.getTemplate("admin/console/config/config_db.vm");
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
return null;
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigHSMLoginPanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigHSMLoginPanel.java
index d04fbf2f..fa9dbb05 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigHSMLoginPanel.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigHSMLoginPanel.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.FileNotFoundException;
import java.io.IOException;
@@ -46,7 +45,8 @@ public class ConfigHSMLoginPanel extends WizardPanelBase {
private CryptoManager mCryptoManager = null;
private String mPwdFilePath = "";
- public ConfigHSMLoginPanel() {}
+ public ConfigHSMLoginPanel() {
+ }
public void init(ServletConfig config, int panelno) throws ServletException {
try {
@@ -132,7 +132,7 @@ public class ConfigHSMLoginPanel extends WizardPanelBase {
CMS.debug("ConfigHSMLoginPanel: passwrd file path: " + e.toString());
}
CMS.debug("ConfigHSMLoginPanel: checking if passwd in cache");
- String tokPwd = pr.getPassword("hardware-"+tokName);
+ String tokPwd = pr.getPassword("hardware-" + tokName);
boolean loggedIn = false;
@@ -157,48 +157,52 @@ public class ConfigHSMLoginPanel extends WizardPanelBase {
password = new Password(tokPwd.toCharArray());
try {
- if (token.passwordIsInitialized()) {
- CMS.debug(
- "ConfigHSMLoginPanel: loginToken():token password is initialized");
- if (!token.isLoggedIn()) {
- CMS.debug(
- "ConfigHSMLoginPanel: loginToken():Token is not logged in, try it");
- token.login(password);
- context.put("status", "justLoggedIn");
- } else {
- CMS.debug(
- "ConfigHSMLoginPanel:Token has already logged on");
- context.put("status", "alreadyLoggedIn");
- }
- } else {
- CMS.debug(
- "ConfigHSMLoginPanel: loginToken():Token password not initialized");
- context.put("status", "tokenPasswordNotInitialized");
- rv = false;
- }
-
- } catch (IncorrectPasswordException e) {
- context.put("status", "incorrectPassword");
- context.put("errorString", e.toString());
- CMS.debug("ConfigHSMLoginPanel: loginToken():" + e.toString());
- rv = false;
- } catch (Exception e) {
- CMS.debug("ConfigHSMLoginPanel: loginToken():" + e.toString());
- context.put("errorString", e.toString());
- rv = false;
- }
+ if (token.passwordIsInitialized()) {
+ CMS.debug(
+ "ConfigHSMLoginPanel: loginToken():token password is initialized");
+ if (!token.isLoggedIn()) {
+ CMS.debug(
+ "ConfigHSMLoginPanel: loginToken():Token is not logged in, try it");
+ token.login(password);
+ context.put("status", "justLoggedIn");
+ } else {
+ CMS.debug(
+ "ConfigHSMLoginPanel:Token has already logged on");
+ context.put("status", "alreadyLoggedIn");
+ }
+ } else {
+ CMS.debug(
+ "ConfigHSMLoginPanel: loginToken():Token password not initialized");
+ context.put("status", "tokenPasswordNotInitialized");
+ rv = false;
+ }
+
+ } catch (IncorrectPasswordException e) {
+ context.put("status", "incorrectPassword");
+ context.put("errorString", e.toString());
+ CMS.debug("ConfigHSMLoginPanel: loginToken():" + e.toString());
+ rv = false;
+ } catch (Exception e) {
+ CMS.debug("ConfigHSMLoginPanel: loginToken():" + e.toString());
+ context.put("errorString", e.toString());
+ rv = false;
+ }
return rv;
}
// XXX how do you do this?
public PropertySet getUsage() {
PropertySet set = new PropertySet();
-
- Descriptor choiceDesc = new Descriptor(IDescriptor.CHOICE, "", "", null); /* no default parameters */
+
+ Descriptor choiceDesc = new Descriptor(IDescriptor.CHOICE, "", "", null); /*
+ * no
+ * default
+ * parameters
+ */
set.add(
"choice", choiceDesc);
-
+
return set;
}
@@ -220,10 +224,10 @@ public class ConfigHSMLoginPanel extends WizardPanelBase {
select = cs.getString("preop.subsystem.select", "");
} catch (Exception e) {
}
-
-// if (select.equals("clone"))
- // return;
-
+
+ // if (select.equals("clone"))
+ // return;
+
CMS.debug("ConfigHSMLoginPanel: in update()");
String uTokName = null;
@@ -233,7 +237,7 @@ public class ConfigHSMLoginPanel extends WizardPanelBase {
uPasswd = HttpInput.getPassword(request, "__uPasswd");
} catch (Exception e) {
}
-
+
if (uPasswd == null) {
CMS.debug("ConfigHSMLoginPanel: password not found");
context.put("error", "no password");
@@ -270,13 +274,13 @@ public class ConfigHSMLoginPanel extends WizardPanelBase {
PlainPasswordWriter pw = new PlainPasswordWriter();
pw.init(mPwdFilePath);
- pw.putPassword("hardware-"+uTokName, uPasswd);
+ pw.putPassword("hardware-" + uTokName, uPasswd);
pw.commit();
} catch (FileNotFoundException e) {
CMS.debug(
"ConfigHSMLoginPanel: update(): Exception caught: "
- + e.toString() + " writing to "+ mPwdFilePath);
+ + e.toString() + " writing to " + mPwdFilePath);
CMS.debug(
"ConfigHSMLoginPanel: update(): password not written to cache");
System.err.println("Exception caught: " + e.toString());
@@ -288,7 +292,7 @@ public class ConfigHSMLoginPanel extends WizardPanelBase {
System.err.println("Exception caught: " + e.toString());
context.put("error", "Exception:" + e.toString());
}
-
+
} // found password
context.put("panel", "admin/console/config/config_hsmloginpanel.vm");
@@ -308,4 +312,3 @@ public class ConfigHSMLoginPanel extends WizardPanelBase {
context.put("panel", "admin/console/config/config_hsmloginpanel.vm");
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigHSMServlet.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigHSMServlet.java
index bfc6e278..9428ecce 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigHSMServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigHSMServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
@@ -39,7 +38,6 @@ import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.cmsutil.crypto.Module;
-
public class ConfigHSMServlet extends ConfigBaseServlet {
/**
*
@@ -131,9 +129,9 @@ public class ConfigHSMServlet extends ConfigBaseServlet {
} else {
CMS.debug(
"ConfigHSMServlet: token " + token.getName()
- + " not to be added");
+ + " not to be added");
}
-
+
} catch (TokenException ex) {
CMS.debug("ConfigHSMServlet:" + ex.toString());
}
@@ -165,11 +163,11 @@ public class ConfigHSMServlet extends ConfigBaseServlet {
if ((cn == null) || (cn.equals(""))) {
break;
}
-
+
CMS.debug("ConfigHSMServlet: got from config module: " + cn);
// create a Module object
Module module = new Module(cn, pn, img);
-
+
if (mCurrModTable.containsKey(cn)) {
CMS.debug("ConfigHSMServlet: module found: " + cn);
module.setFound(true);
@@ -178,7 +176,7 @@ public class ConfigHSMServlet extends ConfigBaseServlet {
loadModTokens(module, m);
}
-
+
CMS.debug("ConfigHSMServlet: adding module " + cn);
// add module to set
if (!mSupportedModules.contains(module)) {
@@ -290,8 +288,8 @@ public class ConfigHSMServlet extends ConfigBaseServlet {
Context context) {
try {
return Velocity.getTemplate("admin/console/config/config_hsm.vm");
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
return null;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigImportCertServlet.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigImportCertServlet.java
index 3b3b8a64..c65e559d 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigImportCertServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigImportCertServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -25,7 +24,6 @@ import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;
-
public class ConfigImportCertServlet extends BaseServlet {
/**
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigJoinServlet.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigJoinServlet.java
index 01917303..5d50193c 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigJoinServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigJoinServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -30,7 +29,6 @@ import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.cmsutil.crypto.CryptoUtil;
-
public class ConfigJoinServlet extends ConfigBaseServlet {
/**
@@ -52,12 +50,13 @@ public class ConfigJoinServlet extends ConfigBaseServlet {
public boolean isPanelModified() {
IConfigStore config = CMS.getConfigStore();
-
+
String cert = null;
try {
cert = config.getString("preop.join.cert", null);
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
if (cert == null || cert.equals("")) {
return false;
} else {
@@ -69,7 +68,7 @@ public class ConfigJoinServlet extends ConfigBaseServlet {
* Displays panel.
*/
public void display(HttpServletRequest request,
- HttpServletResponse response,
+ HttpServletResponse response,
Context context) {
IConfigStore config = CMS.getConfigStore();
@@ -85,7 +84,8 @@ public class ConfigJoinServlet extends ConfigBaseServlet {
CryptoUtil.string2byte(pubKeyPublicExponent),
CryptoUtil.string2byte(priKeyID));
context.put("certreq", pkcs10);
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
String select = "auto";
boolean select_manual = true;
@@ -94,8 +94,8 @@ public class ConfigJoinServlet extends ConfigBaseServlet {
try {
select = config.getString("preop.join.select", null);
} catch (EBaseException e) {
- CMS.debug( "ConfigJoinServlet::display() - "
- + "Exception="+e.toString() );
+ CMS.debug("ConfigJoinServlet::display() - "
+ + "Exception=" + e.toString());
return;
}
if (select.equals("auto")) {
@@ -109,12 +109,13 @@ public class ConfigJoinServlet extends ConfigBaseServlet {
String cert = config.getString("preop.join.cert", "");
context.put("cert", cert);
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
}
} else {
context.put("cert", "");
}
- if (select_manual) {
+ if (select_manual) {
context.put("check_manual", "checked");
context.put("check_auto", "");
} else {
@@ -128,7 +129,7 @@ public class ConfigJoinServlet extends ConfigBaseServlet {
* Updates panel.
*/
public void update(HttpServletRequest request,
- HttpServletResponse response,
+ HttpServletResponse response,
Context context) {
CMS.debug("JoinServlet: update");
IConfigStore config = CMS.getConfigStore();
@@ -160,9 +161,10 @@ public class ConfigJoinServlet extends ConfigBaseServlet {
}
config.putString("preop.join.select", select);
config.commit(false);
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
}
-
+
public Template getTemplate(HttpServletRequest request,
HttpServletResponse response,
Context context) {
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigRootCAServlet.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigRootCAServlet.java
index 895c75ac..44046fdc 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigRootCAServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigRootCAServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
@@ -32,7 +31,6 @@ import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.profile.CertInfoProfile;
-
public class ConfigRootCAServlet extends ConfigBaseServlet {
/**
@@ -54,12 +52,13 @@ public class ConfigRootCAServlet extends ConfigBaseServlet {
public boolean isPanelModified() {
IConfigStore config = CMS.getConfigStore();
-
+
String profile = null;
try {
profile = config.getString("preop.hierarchy.profile", null);
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
if (profile == null || profile.equals("")) {
return false;
} else {
@@ -73,7 +72,8 @@ public class ConfigRootCAServlet extends ConfigBaseServlet {
try {
instancePath = config.getString("instanceRoot");
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
String p[] = { "caCert.profile" };
Vector profiles = new Vector();
@@ -81,13 +81,14 @@ public class ConfigRootCAServlet extends ConfigBaseServlet {
try {
profiles.addElement(
new CertInfoProfile(instancePath + "/conf/" + p[i]));
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
}
return profiles;
}
public void display(HttpServletRequest request,
- HttpServletResponse response,
+ HttpServletResponse response,
Context context) {
IConfigStore config = CMS.getConfigStore();
String profile = null;
@@ -95,7 +96,8 @@ public class ConfigRootCAServlet extends ConfigBaseServlet {
if (isPanelModified()) {
try {
profile = config.getString("preop.hierarchy.profile", null);
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
}
if (profile == null) {
profile = "caCert.profile";
@@ -108,15 +110,16 @@ public class ConfigRootCAServlet extends ConfigBaseServlet {
}
public void update(HttpServletRequest request,
- HttpServletResponse response,
+ HttpServletResponse response,
Context context) {
String profile = request.getParameter("profile");
IConfigStore config = CMS.getConfigStore();
config.putString("preop.hierarchy.profile", profile);
try {
- config.commit(false);
- } catch (Exception e) {}
+ config.commit(false);
+ } catch (Exception e) {
+ }
context.put("status", "update");
context.put("error", "");
Vector profiles = getProfiles();
@@ -124,7 +127,7 @@ public class ConfigRootCAServlet extends ConfigBaseServlet {
context.put("profiles", profiles);
context.put("selected_profile_id", profile);
}
-
+
public Template getTemplate(HttpServletRequest request,
HttpServletResponse response,
Context context) {
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/CreateSubsystemPanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/CreateSubsystemPanel.java
index daf14c9e..377043d5 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/CreateSubsystemPanel.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/CreateSubsystemPanel.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.IOException;
import java.net.URL;
import java.util.StringTokenizer;
@@ -39,19 +38,20 @@ import com.netscape.cms.servlet.wizard.WizardServlet;
public class CreateSubsystemPanel extends WizardPanelBase {
- public CreateSubsystemPanel() {}
+ public CreateSubsystemPanel() {
+ }
/**
* Initializes this panel.
*/
- public void init(ServletConfig config, int panelno)
- throws ServletException {
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
setPanelNo(panelno);
setName("Subsystem Selection");
}
public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
- throws ServletException {
+ throws ServletException {
setPanelNo(panelno);
setName("Subsystem Type");
setId(id);
@@ -72,15 +72,16 @@ public class CreateSubsystemPanel extends WizardPanelBase {
} else {
return true;
}
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
return false;
}
public PropertySet getUsage() {
PropertySet set = new PropertySet();
-
+
/* XXX */
-
+
return set;
}
@@ -112,8 +113,8 @@ public class CreateSubsystemPanel extends WizardPanelBase {
context.put("check_newsubsystem", "");
context.put("check_clonesubsystem", "checked");
}
- context.put("subsystemName",
- config.getString("preop.subsystem.name"));
+ context.put("subsystemName",
+ config.getString("preop.subsystem.name"));
} catch (Exception e) {
CMS.debug(e.toString());
}
@@ -121,8 +122,8 @@ public class CreateSubsystemPanel extends WizardPanelBase {
context.put("check_newsubsystem", "checked");
context.put("check_clonesubsystem", "");
try {
- context.put("subsystemName",
- config.getString("preop.system.fullname"));
+ context.put("subsystemName",
+ config.getString("preop.system.fullname"));
} catch (Exception e) {
CMS.debug(e.toString());
}
@@ -144,7 +145,7 @@ public class CreateSubsystemPanel extends WizardPanelBase {
} catch (EBaseException e) {
}
- Vector v = getUrlListFromSecurityDomain(config, cstype, "SecurePort" );
+ Vector v = getUrlListFromSecurityDomain(config, cstype, "SecurePort");
StringBuffer list = new StringBuffer();
int size = v.size();
@@ -164,7 +165,7 @@ public class CreateSubsystemPanel extends WizardPanelBase {
errorString = "Internal error, cs.type is missing from CS.cfg";
}
- if (list.length()==0)
+ if (list.length() == 0)
context.put("disableClone", "true");
context.put("panel", "admin/console/config/createsubsystempanel.vm");
@@ -196,8 +197,8 @@ public class CreateSubsystemPanel extends WizardPanelBase {
throw new IOException("choice not found");
}
- config.putString("preop.subsystem.name",
- HttpInput.getName(request, "subsystemName"));
+ config.putString("preop.subsystem.name",
+ HttpInput.getName(request, "subsystemName"));
if (select.equals("newsubsystem")) {
config.putString("preop.subsystem.select", "new");
config.putString("subsystem.select", "New");
@@ -209,7 +210,7 @@ public class CreateSubsystemPanel extends WizardPanelBase {
}
cstype = toLowerCaseSubsystemType(cstype);
-
+
config.putString("preop.subsystem.select", "clone");
config.putString("subsystem.select", "Clone");
@@ -223,9 +224,9 @@ public class CreateSubsystemPanel extends WizardPanelBase {
while (t.hasMoreTokens()) {
String tag = t.nextToken();
if (tag.equals("sslserver"))
- config.putBoolean(PCERT_PREFIX+tag+".enable", true);
- else
- config.putBoolean(PCERT_PREFIX+tag+".enable", false);
+ config.putBoolean(PCERT_PREFIX + tag + ".enable", true);
+ else
+ config.putBoolean(PCERT_PREFIX + tag + ".enable", false);
}
// get the master CA
@@ -254,10 +255,10 @@ public class CreateSubsystemPanel extends WizardPanelBase {
String host = u.getHost();
int https_ee_port = u.getPort();
- String https_admin_port = getSecurityDomainAdminPort( config,
+ String https_admin_port = getSecurityDomainAdminPort(config,
host,
String.valueOf(https_ee_port),
- cstype );
+ cstype);
config.putString("preop.master.hostname", host);
config.putInteger("preop.master.httpsport", https_ee_port);
@@ -265,12 +266,12 @@ public class CreateSubsystemPanel extends WizardPanelBase {
ConfigCertApprovalCallback certApprovalCallback = new ConfigCertApprovalCallback();
if (cstype.equals("ca")) {
- updateCertChainUsingSecureEEPort( config, "clone", host, https_ee_port,
- true, context, certApprovalCallback );
+ updateCertChainUsingSecureEEPort(config, "clone", host, https_ee_port,
+ true, context, certApprovalCallback);
}
- getTokenInfo(config, cstype, host, https_ee_port, true, context,
- certApprovalCallback);
+ getTokenInfo(config, cstype, host, https_ee_port, true, context,
+ certApprovalCallback);
} else {
CMS.debug("CreateSubsystemPanel: invalid choice " + select);
errorString = "Invalid choice";
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/DatabasePanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/DatabasePanel.java
index e18d86cf..a69f462a 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/DatabasePanel.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/DatabasePanel.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
@@ -64,7 +63,7 @@ import com.netscape.cmsutil.ldap.LDAPUtil;
public class DatabasePanel extends WizardPanelBase {
private static final String HOST = "localhost";
- private static final String CLONE_HOST="Enter FQDN here";
+ private static final String CLONE_HOST = "Enter FQDN here";
private static final String PORT = "389";
private static final String BASEDN = "o=netscapeCertificateServer";
private static final String BINDDN = "cn=Directory Manager";
@@ -74,19 +73,20 @@ public class DatabasePanel extends WizardPanelBase {
private WizardServlet mServlet = null;
- public DatabasePanel() {}
+ public DatabasePanel() {
+ }
/**
* Initializes this panel.
*/
- public void init(ServletConfig config, int panelno)
- throws ServletException {
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
setPanelNo(panelno);
setName("Internal Database");
}
public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
- throws ServletException {
+ throws ServletException {
setPanelNo(panelno);
setName("Internal Database");
setId(id);
@@ -109,7 +109,8 @@ public class DatabasePanel extends WizardPanelBase {
} else {
return true;
}
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
return false;
}
@@ -120,7 +121,7 @@ public class DatabasePanel extends WizardPanelBase {
"Host name");
set.add("hostname", hostDesc);
-
+
Descriptor portDesc = new Descriptor(IDescriptor.INTEGER, null, null,
"Port");
@@ -130,14 +131,14 @@ public class DatabasePanel extends WizardPanelBase {
"Base DN");
set.add("basedn", basednDesc);
-
+
Descriptor binddnDesc = new Descriptor(IDescriptor.STRING, null, null,
"Bind DN");
set.add("binddn", binddnDesc);
Descriptor bindpwdDesc = new Descriptor(IDescriptor.PASSWORD, null, null,
- "Bind Password");
+ "Bind Password");
set.add("bindpwd", bindpwdDesc);
@@ -187,8 +188,8 @@ public class DatabasePanel extends WizardPanelBase {
basedn = cs.getString("internaldb.basedn", "");
binddn = cs.getString("internaldb.ldapauth.bindDN", "");
database = cs.getString("internaldb.database", "");
- secure = cs.getString("internaldb.ldapconn.secureConn", "");
- cloneStartTLS = cs.getString("internaldb.ldapconn.cloneStartTLS", "");
+ secure = cs.getString("internaldb.ldapconn.secureConn", "");
+ cloneStartTLS = cs.getString("internaldb.ldapconn.cloneStartTLS", "");
errorString = cs.getString("preop.database.errorString", "");
} catch (Exception e) {
CMS.debug("DatabasePanel display: " + e.toString());
@@ -199,12 +200,12 @@ public class DatabasePanel extends WizardPanelBase {
try {
basedn = cs.getString("internaldb.basedn", "");
} catch (Exception e) {
- CMS.debug( "DatabasePanel::display() - "
- + "Exception="+e.toString() );
+ CMS.debug("DatabasePanel::display() - "
+ + "Exception=" + e.toString());
return;
}
binddn = BINDDN;
- database = basedn.substring(basedn.lastIndexOf('=')+1);
+ database = basedn.substring(basedn.lastIndexOf('=') + 1);
CMS.debug("Clone: database=" + database);
} else {
hostname = HOST;
@@ -223,11 +224,10 @@ public class DatabasePanel extends WizardPanelBase {
boolean multipleEnable = false;
try {
multipleEnable = cs.getBoolean(
- "internaldb.multipleSuffix.enable", false);
+ "internaldb.multipleSuffix.enable", false);
} catch (Exception e) {
}
-
-
+
if (multipleEnable)
basedn = "ou=" + instanceId + "," + suffix;
else
@@ -243,15 +243,14 @@ public class DatabasePanel extends WizardPanelBase {
context.put("binddn", binddn);
context.put("bindpwd", bindpwd);
context.put("database", database);
- context.put("secureConn", (secure.equals("true")? "on":"off"));
- context.put("cloneStartTLS", (cloneStartTLS.equals("true")? "on":"off"));
+ context.put("secureConn", (secure.equals("true") ? "on" : "off"));
+ context.put("cloneStartTLS", (cloneStartTLS.equals("true") ? "on" : "off"));
context.put("panel", "admin/console/config/databasepanel.vm");
context.put("errorString", errorString);
}
public void initParams(HttpServletRequest request, Context context)
- throws IOException
- {
+ throws IOException {
IConfigStore config = CMS.getConfigStore();
String select = "";
try {
@@ -323,7 +322,7 @@ public class DatabasePanel extends WizardPanelBase {
} catch (Exception e) {
}
- //get the real host name
+ // get the real host name
String realhostname = "";
if (hostname.equals("localhost")) {
try {
@@ -395,8 +394,7 @@ public class DatabasePanel extends WizardPanelBase {
}
private LDAPConnection getLocalLDAPConn(Context context, String secure)
- throws IOException
- {
+ throws IOException {
IConfigStore cs = CMS.getConfigStore();
String host = "";
@@ -409,7 +407,7 @@ public class DatabasePanel extends WizardPanelBase {
host = cs.getString("internaldb.ldapconn.host");
port = cs.getString("internaldb.ldapconn.port");
binddn = cs.getString("internaldb.ldapauth.bindDN");
- pwd = (String) context.get("bindpwd");
+ pwd = (String) context.get("bindpwd");
security = cs.getString("internaldb.ldapconn.secureConn");
} catch (Exception e) {
CMS.debug("DatabasePanel populateDB: " + e.toString());
@@ -428,12 +426,12 @@ public class DatabasePanel extends WizardPanelBase {
LDAPConnection conn = null;
if (security.equals("true")) {
- CMS.debug("DatabasePanel populateDB: creating secure (SSL) connection for internal ldap");
- conn = new LDAPConnection(CMS.getLdapJssSSLSocketFactory());
- } else {
- CMS.debug("DatabasePanel populateDB: creating non-secure (non-SSL) connection for internal ldap");
- conn = new LDAPConnection();
- }
+ CMS.debug("DatabasePanel populateDB: creating secure (SSL) connection for internal ldap");
+ conn = new LDAPConnection(CMS.getLdapJssSSLSocketFactory());
+ } else {
+ CMS.debug("DatabasePanel populateDB: creating non-secure (non-SSL) connection for internal ldap");
+ conn = new LDAPConnection();
+ }
CMS.debug("DatabasePanel connecting to " + host + ":" + p);
try {
@@ -443,81 +441,78 @@ public class DatabasePanel extends WizardPanelBase {
throw new IOException("Failed to connect to the internal database.");
}
- return conn;
+ return conn;
}
- private boolean deleteDir(File dir)
- {
+ private boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
- for (int i=0; i<children.length; i++) {
+ for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
-
+
// The directory is now empty so delete it
return dir.delete();
- }
+ }
- private void cleanupDB(LDAPConnection conn, String baseDN, String database)
- {
+ private void cleanupDB(LDAPConnection conn, String baseDN, String database) {
String[] entries = {};
String filter = "objectclass=*";
LDAPSearchConstraints cons = null;
String[] attrs = null;
- String dn="";
+ String dn = "";
try {
CMS.debug("Deleting baseDN: " + baseDN);
LDAPSearchResults res = conn.search(baseDN, LDAPConnection.SCOPE_BASE, filter,
- attrs, true, cons);
- if (res != null)
- deleteEntries(res, conn, baseDN, entries);
+ attrs, true, cons);
+ if (res != null)
+ deleteEntries(res, conn, baseDN, entries);
+ } catch (LDAPException e) {
}
- catch (LDAPException e) {}
-
+
try {
- dn="cn=mapping tree, cn=config";
- filter = "nsslapd-backend=" + database;
- LDAPSearchResults res = conn.search(dn, LDAPConnection.SCOPE_ONE, filter,
- attrs, true, cons);
- if (res != null) {
- while (res.hasMoreElements()) {
- dn = res.next().getDN();
- filter = "objectclass=*";
- LDAPSearchResults res2 = conn.search(dn, LDAPConnection.SCOPE_BASE, filter,
- attrs, true, cons);
- if (res2 != null)
- deleteEntries(res2, conn, dn, entries);
- }
- }
- }
- catch (LDAPException e) {}
+ dn = "cn=mapping tree, cn=config";
+ filter = "nsslapd-backend=" + database;
+ LDAPSearchResults res = conn.search(dn, LDAPConnection.SCOPE_ONE, filter,
+ attrs, true, cons);
+ if (res != null) {
+ while (res.hasMoreElements()) {
+ dn = res.next().getDN();
+ filter = "objectclass=*";
+ LDAPSearchResults res2 = conn.search(dn, LDAPConnection.SCOPE_BASE, filter,
+ attrs, true, cons);
+ if (res2 != null)
+ deleteEntries(res2, conn, dn, entries);
+ }
+ }
+ } catch (LDAPException e) {
+ }
try {
dn = "cn=" + database + ",cn=ldbm database, cn=plugins, cn=config";
LDAPSearchResults res = conn.search(dn, LDAPConnection.SCOPE_BASE, filter,
- attrs, true, cons);
+ attrs, true, cons);
if (res != null) {
deleteEntries(res, conn, dn, entries);
- String dbdir = getInstanceDir(conn) + "/db/" + database;
- if (dbdir != null) {
- CMS.debug(" Deleting dbdir " + dbdir);
+ String dbdir = getInstanceDir(conn) + "/db/" + database;
+ if (dbdir != null) {
+ CMS.debug(" Deleting dbdir " + dbdir);
boolean success = deleteDir(new File(dbdir));
if (!success) {
CMS.debug("Unable to delete database directory " + dbdir);
}
}
}
+ } catch (LDAPException e) {
}
- catch (LDAPException e) {}
}
-
- private void populateDB(HttpServletRequest request, Context context, String secure)
- throws IOException {
+ private void populateDB(HttpServletRequest request, Context context, String secure)
+ throws IOException {
IConfigStore cs = CMS.getConfigStore();
String baseDN = "";
@@ -542,41 +537,44 @@ public class DatabasePanel extends WizardPanelBase {
boolean foundDatabase = false;
try {
LDAPEntry entry = conn.read(baseDN);
- if (entry != null) foundBaseDN = true;
+ if (entry != null)
+ foundBaseDN = true;
} catch (LDAPException e) {
- switch( e.getLDAPResultCode() ) {
- case LDAPException.NO_SUCH_OBJECT:
- break;
- default:
- CMS.debug("DatabasePanel update: LDAPException " + e.toString());
- throw new IOException("Failed to create the database");
+ switch (e.getLDAPResultCode()) {
+ case LDAPException.NO_SUCH_OBJECT:
+ break;
+ default:
+ CMS.debug("DatabasePanel update: LDAPException " + e.toString());
+ throw new IOException("Failed to create the database");
}
}
try {
dn = "cn=" + database + ",cn=ldbm database, cn=plugins, cn=config";
LDAPEntry entry = conn.read(dn);
- if (entry != null) foundDatabase = true;
+ if (entry != null)
+ foundDatabase = true;
} catch (LDAPException e) {
- switch( e.getLDAPResultCode() ) {
- case LDAPException.NO_SUCH_OBJECT:
- break;
- default:
- CMS.debug("DatabasePanel update: LDAPException " + e.toString());
- throw new IOException("Failed to create the database");
+ switch (e.getLDAPResultCode()) {
+ case LDAPException.NO_SUCH_OBJECT:
+ break;
+ default:
+ CMS.debug("DatabasePanel update: LDAPException " + e.toString());
+ throw new IOException("Failed to create the database");
}
}
try {
dn = "cn=\"" + baseDN + "\",cn=mapping tree, cn=config";
LDAPEntry entry = conn.read(dn);
- if (entry != null) foundDatabase = true;
+ if (entry != null)
+ foundDatabase = true;
} catch (LDAPException e) {
- switch( e.getLDAPResultCode() ) {
- case LDAPException.NO_SUCH_OBJECT:
- break;
- default:
- CMS.debug("DatabasePanel update: LDAPException " + e.toString());
- throw new IOException("Failed to create the database");
+ switch (e.getLDAPResultCode()) {
+ case LDAPException.NO_SUCH_OBJECT:
+ break;
+ default:
+ CMS.debug("DatabasePanel update: LDAPException " + e.toString());
+ throw new IOException("Failed to create the database");
}
}
@@ -584,8 +582,7 @@ public class DatabasePanel extends WizardPanelBase {
CMS.debug("DatabasePanel update: This database has already been used.");
if (remove == null) {
throw new IOException("This database has already been used. Select the checkbox below to remove all data and reuse this database");
- }
- else {
+ } else {
CMS.debug("DatabasePanel update: Deleting existing DB and reusing base DN");
cleanupDB(conn, baseDN, database);
foundBaseDN = false;
@@ -596,9 +593,8 @@ public class DatabasePanel extends WizardPanelBase {
if (foundBaseDN) {
CMS.debug("DatabasePanel update: This base DN has already been used.");
if (remove == null) {
- throw new IOException("This base DN ("+baseDN+") has already been used. Select the checkbox below to remove all data and reuse this base DN");
- }
- else {
+ throw new IOException("This base DN (" + baseDN + ") has already been used. Select the checkbox below to remove all data and reuse this base DN");
+ } else {
CMS.debug("DatabasePanel update: Deleting existing DB and reusing base DN");
cleanupDB(conn, baseDN, database);
foundBaseDN = false;
@@ -609,7 +605,7 @@ public class DatabasePanel extends WizardPanelBase {
// create database
try {
LDAPAttributeSet attrs = new LDAPAttributeSet();
- String oc[] = { "top", "extensibleObject", "nsBackendInstance"};
+ String oc[] = { "top", "extensibleObject", "nsBackendInstance" };
attrs.add(new LDAPAttribute("objectClass", oc));
attrs.add(new LDAPAttribute("cn", database));
attrs.add(new LDAPAttribute("nsslapd-suffix", baseDN));
@@ -623,7 +619,7 @@ public class DatabasePanel extends WizardPanelBase {
try {
LDAPAttributeSet attrs = new LDAPAttributeSet();
- String oc2[] = { "top", "extensibleObject", "nsMappingTree"};
+ String oc2[] = { "top", "extensibleObject", "nsMappingTree" };
attrs.add(new LDAPAttribute("objectClass", oc2));
attrs.add(new LDAPAttribute("cn", baseDN));
attrs.add(new LDAPAttribute("nsslapd-backend", database));
@@ -644,19 +640,19 @@ public class DatabasePanel extends WizardPanelBase {
String n = st.nextToken();
String v = st.nextToken();
LDAPAttributeSet attrs = new LDAPAttributeSet();
- String oc3[] = { "top", "domain"};
+ String oc3[] = { "top", "domain" };
if (n.equals("o")) {
- oc3[1] = "organization";
+ oc3[1] = "organization";
} else if (n.equals("ou")) {
- oc3[1] = "organizationalUnit";
- }
+ oc3[1] = "organizationalUnit";
+ }
attrs.add(new LDAPAttribute("objectClass", oc3));
attrs.add(new LDAPAttribute(n, v));
LDAPEntry entry = new LDAPEntry(baseDN, attrs);
conn.add(entry);
} catch (Exception e) {
CMS.debug("Warning: suffix creation error - " + e.toString());
- throw new IOException("Failed to create the base DN: "+baseDN);
+ throw new IOException("Failed to create the base DN: " + baseDN);
}
// check to see if the base dn exists
@@ -666,15 +662,17 @@ public class DatabasePanel extends WizardPanelBase {
LDAPEntry entry = conn.read(baseDN);
if (entry != null) {
- foundBaseDN = true;
+ foundBaseDN = true;
}
- } catch (LDAPException e) {}
+ } catch (LDAPException e) {
+ }
boolean createBaseDN = true;
boolean testing = false;
try {
testing = cs.getBoolean("internaldb.multipleSuffix.enable", false);
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
if (!foundBaseDN) {
if (!testing) {
@@ -697,7 +695,7 @@ public class DatabasePanel extends WizardPanelBase {
// support only one level creation - create new entry
// right under the suffix
LDAPAttributeSet attrs = new LDAPAttributeSet();
- String oc[] = { "top", "organizationalUnit"};
+ String oc[] = { "top", "organizationalUnit" };
attrs.add(new LDAPAttribute("objectClass", oc));
attrs.add(new LDAPAttribute("ou", dns2[0]));
@@ -705,7 +703,7 @@ public class DatabasePanel extends WizardPanelBase {
try {
conn.add(entry);
- foundBaseDN = true;
+ foundBaseDN = true;
CMS.debug("DatabasePanel added " + baseDN);
} catch (LDAPException e) {
throw new IOException("Failed to create " + baseDN);
@@ -723,25 +721,26 @@ public class DatabasePanel extends WizardPanelBase {
}
if (select.equals("clone")) {
- // if this is clone, add index before replication
- // don't put in the schema or bad things will happen
-
- importLDIFS("preop.internaldb.ldif", conn);
- importLDIFS("preop.internaldb.index_ldif", conn);
+ // if this is clone, add index before replication
+ // don't put in the schema or bad things will happen
+
+ importLDIFS("preop.internaldb.ldif", conn);
+ importLDIFS("preop.internaldb.index_ldif", conn);
} else {
- // data will be replicated from the master to the clone
- // so clone does not need the data
- //
+ // data will be replicated from the master to the clone
+ // so clone does not need the data
+ //
- importLDIFS("preop.internaldb.schema.ldif", conn);
- importLDIFS("preop.internaldb.ldif", conn);
- importLDIFS("preop.internaldb.data_ldif", conn);
- importLDIFS("preop.internaldb.index_ldif", conn);
+ importLDIFS("preop.internaldb.schema.ldif", conn);
+ importLDIFS("preop.internaldb.ldif", conn);
+ importLDIFS("preop.internaldb.data_ldif", conn);
+ importLDIFS("preop.internaldb.index_ldif", conn);
}
try {
conn.disconnect();
- } catch (LDAPException e) {}
+ } catch (LDAPException e) {
+ }
}
private void importLDIFS(String param, LDAPConnection conn) throws IOException {
@@ -751,11 +750,11 @@ public class DatabasePanel extends WizardPanelBase {
CMS.debug("DatabasePanel populateDB param=" + param);
try {
v = cs.getString(param);
- } catch (EBaseException e) {
+ } catch (EBaseException e) {
CMS.debug("DatabasePanel populateDB: " + e.toString());
throw new IOException("Cant find ldif files.");
}
-
+
StringTokenizer tokenizer = new StringTokenizer(v, ",");
String baseDN = null;
String database = null;
@@ -787,13 +786,12 @@ public class DatabasePanel extends WizardPanelBase {
String instanceId = null;
try {
- instanceId = cs.getString("instanceId");
+ instanceId = cs.getString("instanceId");
} catch (EBaseException e) {
throw new IOException("instanceId is missing");
}
-
- String configDir = instancePath + File.separator + "conf";
+ String configDir = instancePath + File.separator + "conf";
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken().trim();
@@ -846,11 +844,11 @@ public class DatabasePanel extends WizardPanelBase {
if (!endOfline) {
ps.println(s);
}
- }
+ }
}
in.close();
ps.close();
- } catch (Exception e) {
+ } catch (Exception e) {
CMS.debug("DBSubsystem popuateDB: " + e.toString());
throw new IOException(
"Problem of copying ldif file: " + filename);
@@ -867,7 +865,7 @@ public class DatabasePanel extends WizardPanelBase {
HttpServletResponse response,
Context context) throws IOException {
IConfigStore cs = CMS.getConfigStore();
- boolean hasErr = false;
+ boolean hasErr = false;
boolean firsttime = false;
context.put("firsttime", "false");
@@ -903,17 +901,19 @@ public class DatabasePanel extends WizardPanelBase {
cs.putString("internaldb.ldapauth.bindDN", binddn);
cs.putString("internaldb.database", database2);
String secure = HttpInput.getCheckbox(request, "secureConn");
- cs.putString("internaldb.ldapconn.secureConn", (secure.equals("on")?"true":"false"));
+ cs.putString("internaldb.ldapconn.secureConn", (secure.equals("on") ? "true" : "false"));
String cloneStartTLS = HttpInput.getCheckbox(request, "cloneStartTLS");
- cs.putString("internaldb.ldapconn.cloneStartTLS", (cloneStartTLS.equals("on")?"true":"false"));
+ cs.putString("internaldb.ldapconn.cloneStartTLS", (cloneStartTLS.equals("on") ? "true" : "false"));
String remove = HttpInput.getID(request, "removeData");
if (isPanelDone() && (remove == null || remove.equals(""))) {
- /* if user submits the same data, they just want to skip
- to the next panel, no database population is required. */
- if (hostname1.equals(hostname2) &&
- portStr1.equals(portStr2) &&
- database1.equals(database2)) {
+ /*
+ * if user submits the same data, they just want to skip to the next
+ * panel, no database population is required.
+ */
+ if (hostname1.equals(hostname2) &&
+ portStr1.equals(portStr2) &&
+ database1.equals(database2)) {
context.put("updateStatus", "success");
return;
}
@@ -921,15 +921,14 @@ public class DatabasePanel extends WizardPanelBase {
mServlet.cleanUpFromPanel(mServlet.getPanelNo(request));
-
try {
- populateDB(request, context, (secure.equals("on")?"true":"false"));
+ populateDB(request, context, (secure.equals("on") ? "true" : "false"));
} catch (IOException e) {
- CMS.debug("DatabasePanel update: populateDB Exception: "+e.toString());
+ CMS.debug("DatabasePanel update: populateDB Exception: " + e.toString());
context.put("updateStatus", "failure");
throw e;
} catch (Exception e) {
- CMS.debug("DatabasePanel update: populateDB Exception: "+e.toString());
+ CMS.debug("DatabasePanel update: populateDB Exception: " + e.toString());
context.put("errorString", e.toString());
cs.putString("preop.database.errorString", e.toString());
context.put("updateStatus", "failure");
@@ -950,11 +949,11 @@ public class DatabasePanel extends WizardPanelBase {
} catch (Exception e) {
CMS.debug("ConfigDatabaseServlet update: " + e.toString());
context.put("updateStatus", "failure");
- throw new IOException( e.toString() );
+ throw new IOException(e.toString());
}
psStore.putString("internaldb", bindpwd);
psStore.putString("replicationdb", replicationpwd);
- cs.putString("preop.internaldb.replicationpwd" , replicationpwd);
+ cs.putString("preop.internaldb.replicationpwd", replicationpwd);
cs.putString("preop.database.removeData", "false");
try {
@@ -983,57 +982,58 @@ public class DatabasePanel extends WizardPanelBase {
// always populate the index the last
try {
- CMS.debug("Populating local indexes");
- LDAPConnection conn = getLocalLDAPConn(context,
- (secure.equals("on")?"true":"false"));
- importLDIFS("preop.internaldb.post_ldif", conn);
-
- /* For vlvtask, we need to check if the task has
- been completed or not. Presence of nsTaskExitCode means task is complete
- */
- String wait_dn = cs.getString("preop.internaldb.wait_dn", "");
- if (!wait_dn.equals("")) {
- int i = 0;
- LDAPEntry task = null;
- boolean taskComplete = false;
- CMS.debug("Checking wait_dn " + wait_dn);
- do {
- Thread.sleep(1000);
- try {
- task = conn.read(wait_dn, (String[])null);
- if (task != null) {
- LDAPAttribute attr = task.getAttribute("nsTaskExitCode");
- if (attr != null) {
- taskComplete = true;
- String val = (String) attr.getStringValues().nextElement();
- if (val.compareTo("0") != 0) {
- CMS.debug("Error in populating local indexes: nsTaskExitCode=" + val);
- }
- }
+ CMS.debug("Populating local indexes");
+ LDAPConnection conn = getLocalLDAPConn(context,
+ (secure.equals("on") ? "true" : "false"));
+ importLDIFS("preop.internaldb.post_ldif", conn);
+
+ /*
+ * For vlvtask, we need to check if the task has been completed or
+ * not. Presence of nsTaskExitCode means task is complete
+ */
+ String wait_dn = cs.getString("preop.internaldb.wait_dn", "");
+ if (!wait_dn.equals("")) {
+ int i = 0;
+ LDAPEntry task = null;
+ boolean taskComplete = false;
+ CMS.debug("Checking wait_dn " + wait_dn);
+ do {
+ Thread.sleep(1000);
+ try {
+ task = conn.read(wait_dn, (String[]) null);
+ if (task != null) {
+ LDAPAttribute attr = task.getAttribute("nsTaskExitCode");
+ if (attr != null) {
+ taskComplete = true;
+ String val = (String) attr.getStringValues().nextElement();
+ if (val.compareTo("0") != 0) {
+ CMS.debug("Error in populating local indexes: nsTaskExitCode=" + val);
+ }
+ }
+ }
+ } catch (LDAPException le) {
+ CMS.debug("Still checking wait_dn '" + wait_dn + "' (" + le.toString() + ")");
+ } catch (Exception e) {
+ CMS.debug("Still checking wait_dn '" + wait_dn + "' (" + e.toString() + ").");
+ }
+ } while ((!taskComplete) && (i < 20));
+ if (i < 20) {
+ CMS.debug("Done checking wait_dn " + wait_dn);
+ } else {
+ CMS.debug("Done checking wait_dn " + wait_dn + " due to timeout.");
}
- } catch (LDAPException le) {
- CMS.debug("Still checking wait_dn '" + wait_dn + "' (" + le.toString() + ")");
- } catch (Exception e) {
- CMS.debug("Still checking wait_dn '" + wait_dn + "' (" + e.toString() + ").");
- }
- } while ((!taskComplete) && (i < 20));
- if (i < 20) {
- CMS.debug("Done checking wait_dn " + wait_dn);
- } else {
- CMS.debug("Done checking wait_dn " + wait_dn + " due to timeout.");
}
- }
- conn.disconnect();
- CMS.debug("Done populating local indexes");
+ conn.disconnect();
+ CMS.debug("Done populating local indexes");
} catch (Exception e) {
- CMS.debug("Populating index failure - " + e);
+ CMS.debug("Populating index failure - " + e);
}
// setup replication after indexes have been created
if (select.equals("clone")) {
CMS.debug("Start setting up replication.");
- setupReplication(request, context, (secure.equals("on")?"true":"false"), (cloneStartTLS.equals("on")?"true":"false"));
+ setupReplication(request, context, (secure.equals("on") ? "true" : "false"), (cloneStartTLS.equals("on") ? "true" : "false"));
CMS.debug("Finish setting up replication.");
try {
@@ -1048,25 +1048,24 @@ public class DatabasePanel extends WizardPanelBase {
}
}
-
if (hasErr == false) {
- cs.putBoolean("preop.Database.done", true);
- try {
- cs.commit(false);
- } catch (EBaseException e) {
- CMS.debug(
- "DatabasePanel: update() Exception caught at config commit: "
- + e.toString());
- }
- }
+ cs.putBoolean("preop.Database.done", true);
+ try {
+ cs.commit(false);
+ } catch (EBaseException e) {
+ CMS.debug(
+ "DatabasePanel: update() Exception caught at config commit: "
+ + e.toString());
+ }
+ }
context.put("updateStatus", "success");
}
private void setupReplication(HttpServletRequest request,
- Context context, String secure, String cloneStartTLS) throws IOException {
+ Context context, String secure, String cloneStartTLS) throws IOException {
String bindpwd = HttpInput.getPassword(request, "__bindpwd");
IConfigStore cs = CMS.getConfigStore();
-
+
String cstype = "";
String machinename = "";
String instanceId = "";
@@ -1078,13 +1077,12 @@ public class DatabasePanel extends WizardPanelBase {
} catch (Exception e) {
}
-
- //setup replication agreement
- String masterAgreementName = "masterAgreement1-"+machinename+"-"+instanceId;
+ // setup replication agreement
+ String masterAgreementName = "masterAgreement1-" + machinename + "-" + instanceId;
cs.putString("internaldb.replication.master", masterAgreementName);
- String cloneAgreementName = "cloneAgreement1-"+machinename+"-"+instanceId;
+ String cloneAgreementName = "cloneAgreement1-" + machinename + "-" + instanceId;
cs.putString("internaldb.replication.consumer", cloneAgreementName);
-
+
try {
cs.commit(false);
} catch (Exception e) {
@@ -1119,18 +1117,18 @@ public class DatabasePanel extends WizardPanelBase {
master2_replicationpwd = cs.getString("preop.internaldb.replicationpwd", "");
} catch (Exception e) {
}
-
+
LDAPConnection conn1 = null;
LDAPConnection conn2 = null;
if (secure.equals("true")) {
- CMS.debug("DatabasePanel setupReplication: creating secure (SSL) connections for internal ldap");
- conn1 = new LDAPConnection(CMS.getLdapJssSSLSocketFactory());
- conn2 = new LDAPConnection(CMS.getLdapJssSSLSocketFactory());
- } else {
- CMS.debug("DatabasePanel setupreplication: creating non-secure (non-SSL) connections for internal ldap");
- conn1 = new LDAPConnection();
- conn2 = new LDAPConnection();
- }
+ CMS.debug("DatabasePanel setupReplication: creating secure (SSL) connections for internal ldap");
+ conn1 = new LDAPConnection(CMS.getLdapJssSSLSocketFactory());
+ conn2 = new LDAPConnection(CMS.getLdapJssSSLSocketFactory());
+ } else {
+ CMS.debug("DatabasePanel setupreplication: creating non-secure (non-SSL) connections for internal ldap");
+ conn1 = new LDAPConnection();
+ conn2 = new LDAPConnection();
+ }
String basedn = "";
try {
@@ -1140,13 +1138,13 @@ public class DatabasePanel extends WizardPanelBase {
try {
conn1.connect(master1_hostname, master1_port, master1_binddn,
- master1_bindpwd);
+ master1_bindpwd);
conn2.connect(master2_hostname, master2_port, master2_binddn,
- master2_bindpwd);
+ master2_bindpwd);
String suffix = cs.getString("internaldb.basedn", "");
- String replicadn = "cn=replica,cn=\""+suffix+"\",cn=mapping tree,cn=config";
- CMS.debug("DatabasePanel setupReplication: replicadn="+replicadn);
+ String replicadn = "cn=replica,cn=\"" + suffix + "\",cn=mapping tree,cn=config";
+ CMS.debug("DatabasePanel setupReplication: replicadn=" + replicadn);
String masterBindUser = "Replication Manager " + masterAgreementName;
String cloneBindUser = "Replication Manager " + cloneAgreementName;
@@ -1168,16 +1166,16 @@ public class DatabasePanel extends WizardPanelBase {
CMS.debug("DatabasePanel setupReplication: Finished enabling replication");
- createReplicationAgreement(replicadn, conn1, masterAgreementName,
- master2_hostname, master2_port, master2_replicationpwd, basedn, cloneBindUser, secure, cloneStartTLS);
+ createReplicationAgreement(replicadn, conn1, masterAgreementName,
+ master2_hostname, master2_port, master2_replicationpwd, basedn, cloneBindUser, secure, cloneStartTLS);
- createReplicationAgreement(replicadn, conn2, cloneAgreementName,
- master1_hostname, master1_port, master1_replicationpwd, basedn, masterBindUser, secure, cloneStartTLS);
+ createReplicationAgreement(replicadn, conn2, cloneAgreementName,
+ master1_hostname, master1_port, master1_replicationpwd, basedn, masterBindUser, secure, cloneStartTLS);
// initialize consumer
initializeConsumer(replicadn, conn1, masterAgreementName);
- while (! replicationDone(replicadn, conn1, masterAgreementName)) {
+ while (!replicationDone(replicadn, conn1, masterAgreementName)) {
CMS.debug("DatabasePanel setupReplication: Waiting for replication to complete");
Thread.sleep(1000);
}
@@ -1185,12 +1183,12 @@ public class DatabasePanel extends WizardPanelBase {
String status = replicationStatus(replicadn, conn1, masterAgreementName);
if (!status.startsWith("0 ")) {
CMS.debug("DatabasePanel setupReplication: consumer initialization failed. " +
- status);
+ status);
throw new IOException("consumer initialization failed. " + status);
- }
+ }
} catch (Exception e) {
- CMS.debug("DatabasePanel setupReplication: "+e.toString());
+ CMS.debug("DatabasePanel setupReplication: " + e.toString());
throw new IOException("Failed to setup the replication for cloning.");
}
}
@@ -1203,15 +1201,15 @@ public class DatabasePanel extends WizardPanelBase {
Context context) {
try {
- initParams(request, context);
- } catch (IOException e) {
+ initParams(request, context);
+ } catch (IOException e) {
}
context.put("title", "Database");
context.put("panel", "admin/console/config/databasepanel.vm");
}
private void createReplicationManager(LDAPConnection conn, String bindUser, String pwd)
- throws LDAPException {
+ throws LDAPException {
LDAPAttributeSet attrs = null;
LDAPEntry entry = null;
String dn = "cn=" + bindUser + ",cn=config";
@@ -1231,11 +1229,11 @@ public class DatabasePanel extends WizardPanelBase {
conn.delete(dn);
conn.add(entry);
} catch (LDAPException ee) {
- CMS.debug("DatabasePanel createReplicationManager: "+ee.toString());
+ CMS.debug("DatabasePanel createReplicationManager: " + ee.toString());
}
return;
} else {
- CMS.debug("DatabasePanel createReplicationManager: Failed to create replication manager. Exception: "+e.toString());
+ CMS.debug("DatabasePanel createReplicationManager: Failed to create replication manager. Exception: " + e.toString());
throw e;
}
}
@@ -1244,7 +1242,7 @@ public class DatabasePanel extends WizardPanelBase {
}
private void createChangeLog(LDAPConnection conn, String dir)
- throws LDAPException {
+ throws LDAPException {
LDAPAttributeSet attrs = null;
LDAPEntry entry = null;
String dn = "cn=changelog5,cn=config";
@@ -1259,17 +1257,15 @@ public class DatabasePanel extends WizardPanelBase {
} catch (LDAPException e) {
if (e.getLDAPResultCode() == LDAPException.ENTRY_ALREADY_EXISTS) {
CMS.debug("DatabasePanel createChangeLog: Changelog entry has already used");
-/* leave it, dont delete it because it will have operation error
- try {
- conn.delete(dn);
- conn.add(entry);
- } catch (LDAPException ee) {
- CMS.debug("DatabasePanel createChangeLog: "+ee.toString());
- }
-*/
+ /*
+ * leave it, dont delete it because it will have operation error
+ * try { conn.delete(dn); conn.add(entry); } catch
+ * (LDAPException ee) {
+ * CMS.debug("DatabasePanel createChangeLog: "+ee.toString()); }
+ */
return;
} else {
- CMS.debug("DatabasePanel createChangeLog: Failed to create changelog entry. Exception: "+e.toString());
+ CMS.debug("DatabasePanel createChangeLog: Failed to create changelog entry. Exception: " + e.toString());
throw e;
}
}
@@ -1278,8 +1274,8 @@ public class DatabasePanel extends WizardPanelBase {
}
private int enableReplication(String replicadn, LDAPConnection conn, String bindUser, String basedn, int id)
- throws LDAPException {
- CMS.debug("DatabasePanel enableReplication: replicadn: "+replicadn);
+ throws LDAPException {
+ CMS.debug("DatabasePanel enableReplication: replicadn: " + replicadn);
LDAPAttributeSet attrs = null;
LDAPEntry entry = null;
try {
@@ -1290,7 +1286,7 @@ public class DatabasePanel extends WizardPanelBase {
attrs.add(new LDAPAttribute("nsDS5ReplicaRoot", basedn));
attrs.add(new LDAPAttribute("nsDS5ReplicaType", "3"));
attrs.add(new LDAPAttribute("nsDS5ReplicaBindDN",
- "cn=" + bindUser + ",cn=config"));
+ "cn=" + bindUser + ",cn=config"));
attrs.add(new LDAPAttribute("cn", "replica"));
attrs.add(new LDAPAttribute("nsDS5ReplicaId", Integer.toString(id)));
attrs.add(new LDAPAttribute("nsds5flags", "1"));
@@ -1298,49 +1294,51 @@ public class DatabasePanel extends WizardPanelBase {
conn.add(entry);
} catch (LDAPException e) {
if (e.getLDAPResultCode() == LDAPException.ENTRY_ALREADY_EXISTS) {
- /* BZ 470918 -we cant just add the new dn. We need to do a replace instead
- * until the DS code is fixed */
- CMS.debug("DatabasePanel enableReplication: "+replicadn+" has already been used");
-
+ /*
+ * BZ 470918 -we cant just add the new dn. We need to do a
+ * replace instead until the DS code is fixed
+ */
+ CMS.debug("DatabasePanel enableReplication: " + replicadn + " has already been used");
+
try {
entry = conn.read(replicadn);
LDAPAttribute attr = entry.getAttribute("nsDS5ReplicaBindDN");
- attr.addValue( "cn=" + bindUser + ",cn=config");
+ attr.addValue("cn=" + bindUser + ",cn=config");
LDAPModification mod = new LDAPModification(LDAPModification.REPLACE, attr);
conn.modify(replicadn, mod);
} catch (LDAPException ee) {
- CMS.debug("DatabasePanel enableReplication: Failed to modify "
- +replicadn+" entry. Exception: "+e.toString());
+ CMS.debug("DatabasePanel enableReplication: Failed to modify "
+ + replicadn + " entry. Exception: " + e.toString());
}
return id;
} else {
- CMS.debug("DatabasePanel enableReplication: Failed to create "+replicadn+" entry. Exception: "+e.toString());
+ CMS.debug("DatabasePanel enableReplication: Failed to create " + replicadn + " entry. Exception: " + e.toString());
return id;
}
}
- CMS.debug("DatabasePanel enableReplication: Successfully create "+replicadn+" entry.");
+ CMS.debug("DatabasePanel enableReplication: Successfully create " + replicadn + " entry.");
return id + 1;
}
- private void createReplicationAgreement(String replicadn,
- LDAPConnection conn, String name, String replicahost, int replicaport,
- String replicapwd, String basedn, String bindUser, String secure, String cloneStartTLS) throws LDAPException {
- String dn = "cn="+name+","+replicadn;
- CMS.debug("DatabasePanel createReplicationAgreement: dn: "+dn);
+ private void createReplicationAgreement(String replicadn,
+ LDAPConnection conn, String name, String replicahost, int replicaport,
+ String replicapwd, String basedn, String bindUser, String secure, String cloneStartTLS) throws LDAPException {
+ String dn = "cn=" + name + "," + replicadn;
+ CMS.debug("DatabasePanel createReplicationAgreement: dn: " + dn);
LDAPEntry entry = null;
LDAPAttributeSet attrs = null;
try {
attrs = new LDAPAttributeSet();
attrs.add(new LDAPAttribute("objectclass", "top"));
attrs.add(new LDAPAttribute("objectclass",
- "nsds5replicationagreement"));
+ "nsds5replicationagreement"));
attrs.add(new LDAPAttribute("cn", name));
attrs.add(new LDAPAttribute("nsDS5ReplicaRoot", basedn));
attrs.add(new LDAPAttribute("nsDS5ReplicaHost", replicahost));
- attrs.add(new LDAPAttribute("nsDS5ReplicaPort", ""+replicaport));
+ attrs.add(new LDAPAttribute("nsDS5ReplicaPort", "" + replicaport));
attrs.add(new LDAPAttribute("nsDS5ReplicaBindDN",
- "cn=" + bindUser + ",cn=config"));
+ "cn=" + bindUser + ",cn=config"));
attrs.add(new LDAPAttribute("nsDS5ReplicaBindMethod", "Simple"));
attrs.add(new LDAPAttribute("nsds5replicacredentials", replicapwd));
@@ -1351,50 +1349,50 @@ public class DatabasePanel extends WizardPanelBase {
}
CMS.debug("About to set description attr to " + name);
- attrs.add(new LDAPAttribute("description",name));
+ attrs.add(new LDAPAttribute("description", name));
entry = new LDAPEntry(dn, attrs);
conn.add(entry);
} catch (LDAPException e) {
if (e.getLDAPResultCode() == LDAPException.ENTRY_ALREADY_EXISTS) {
- CMS.debug("DatabasePanel createReplicationAgreement: "+dn+" has already used");
+ CMS.debug("DatabasePanel createReplicationAgreement: " + dn + " has already used");
try {
conn.delete(dn);
} catch (LDAPException ee) {
- CMS.debug("DatabasePanel createReplicationAgreement: "+ee.toString());
+ CMS.debug("DatabasePanel createReplicationAgreement: " + ee.toString());
throw ee;
}
try {
conn.add(entry);
} catch (LDAPException ee) {
- CMS.debug("DatabasePanel createReplicationAgreement: "+ee.toString());
+ CMS.debug("DatabasePanel createReplicationAgreement: " + ee.toString());
throw ee;
}
} else {
- CMS.debug("DatabasePanel createReplicationAgreement: Failed to create "+dn+" entry. Exception: "+e.toString());
+ CMS.debug("DatabasePanel createReplicationAgreement: Failed to create " + dn + " entry. Exception: " + e.toString());
throw e;
}
}
- CMS.debug("DatabasePanel createReplicationAgreement: Successfully create replication agreement "+name);
+ CMS.debug("DatabasePanel createReplicationAgreement: Successfully create replication agreement " + name);
}
- private void initializeConsumer(String replicadn, LDAPConnection conn,
- String name) {
- String dn = "cn="+name+","+replicadn;
- CMS.debug("DatabasePanel initializeConsumer: initializeConsumer dn: "+dn);
- CMS.debug("DatabasePanel initializeConsumer: initializeConsumer host: "+conn.getHost() + " port: " + conn.getPort());
+ private void initializeConsumer(String replicadn, LDAPConnection conn,
+ String name) {
+ String dn = "cn=" + name + "," + replicadn;
+ CMS.debug("DatabasePanel initializeConsumer: initializeConsumer dn: " + dn);
+ CMS.debug("DatabasePanel initializeConsumer: initializeConsumer host: " + conn.getHost() + " port: " + conn.getPort());
try {
LDAPAttribute attr = new LDAPAttribute("nsds5beginreplicarefresh",
- "start");
+ "start");
LDAPModification mod = new LDAPModification(
- LDAPModification.REPLACE, attr);
+ LDAPModification.REPLACE, attr);
CMS.debug("DatabasePanel initializeConsumer: start modifying");
conn.modify(dn, mod);
CMS.debug("DatabasePanel initializeConsumer: Finish modification.");
} catch (LDAPException e) {
- CMS.debug("DatabasePanel initializeConsumer: Failed to modify "+dn+" entry. Exception: "+e.toString());
+ CMS.debug("DatabasePanel initializeConsumer: Failed to modify " + dn + " entry. Exception: " + e.toString());
return;
} catch (Exception e) {
CMS.debug("DatabasePanel initializeConsumer: exception " + e);
@@ -1405,33 +1403,33 @@ public class DatabasePanel extends WizardPanelBase {
Thread.sleep(5000);
CMS.debug("DatabasePanel initializeConsumer: finish sleeping.");
} catch (InterruptedException ee) {
- CMS.debug("DatabasePanel initializeConsumer: exception: "+ee.toString());
+ CMS.debug("DatabasePanel initializeConsumer: exception: " + ee.toString());
}
CMS.debug("DatabasePanel initializeConsumer: Successfully initialize consumer");
}
- private boolean replicationDone(String replicadn, LDAPConnection conn, String name)
- throws IOException {
- String dn = "cn="+name+","+replicadn;
+ private boolean replicationDone(String replicadn, LDAPConnection conn, String name)
+ throws IOException {
+ String dn = "cn=" + name + "," + replicadn;
String filter = "(objectclass=*)";
- String[] attrs = {"nsds5beginreplicarefresh"};
+ String[] attrs = { "nsds5beginreplicarefresh" };
- CMS.debug("DatabasePanel replicationDone: dn: "+dn);
+ CMS.debug("DatabasePanel replicationDone: dn: " + dn);
try {
LDAPSearchResults results = conn.search(dn, LDAPConnection.SCOPE_BASE, filter,
- attrs, true);
+ attrs, true);
int count = results.getCount();
if (count < 1) {
throw new IOException("Replication entry not found");
- }
-
+ }
+
LDAPEntry entry = results.next();
LDAPAttribute refresh = entry.getAttribute("nsds5beginreplicarefresh");
if (refresh == null) {
return true;
- }
+ }
return false;
} catch (Exception e) {
CMS.debug("DatabasePanel replicationDone: exception " + e);
@@ -1439,29 +1437,29 @@ public class DatabasePanel extends WizardPanelBase {
}
}
- private String replicationStatus(String replicadn, LDAPConnection conn, String name)
- throws IOException {
- String dn = "cn="+name+","+replicadn;
+ private String replicationStatus(String replicadn, LDAPConnection conn, String name)
+ throws IOException {
+ String dn = "cn=" + name + "," + replicadn;
String filter = "(objectclass=*)";
- String[] attrs = {"nsds5replicalastinitstatus"};
+ String[] attrs = { "nsds5replicalastinitstatus" };
String status = null;
- CMS.debug("DatabasePanel replicationStatus: dn: "+dn);
+ CMS.debug("DatabasePanel replicationStatus: dn: " + dn);
try {
LDAPSearchResults results = conn.search(dn, LDAPConnection.SCOPE_BASE, filter,
- attrs, false);
+ attrs, false);
int count = results.getCount();
if (count < 1) {
throw new IOException("Replication entry not found");
- }
+ }
LDAPEntry entry = results.next();
LDAPAttribute attr = entry.getAttribute("nsds5replicalastinitstatus");
if (attr != null) {
Enumeration valsInAttr = attr.getStringValues();
if (valsInAttr.hasMoreElements()) {
- return (String)valsInAttr.nextElement();
+ return (String) valsInAttr.nextElement();
} else {
throw new IOException("No value returned for nsds5replicalastinitstatus");
}
@@ -1475,35 +1473,35 @@ public class DatabasePanel extends WizardPanelBase {
}
private String getInstanceDir(LDAPConnection conn) {
- String instancedir="";
+ String instancedir = "";
try {
String filter = "(objectclass=*)";
- String[] attrs = {"nsslapd-directory"};
+ String[] attrs = { "nsslapd-directory" };
LDAPSearchResults results = conn.search("cn=config,cn=ldbm database,cn=plugins,cn=config", LDAPv3.SCOPE_SUB,
- filter, attrs, false);
+ filter, attrs, false);
while (results.hasMoreElements()) {
LDAPEntry entry = results.next();
String dn = entry.getDN();
- CMS.debug("DatabasePanel getInstanceDir: DN for storing nsslapd-directory: "+dn);
+ CMS.debug("DatabasePanel getInstanceDir: DN for storing nsslapd-directory: " + dn);
LDAPAttributeSet entryAttrs = entry.getAttributeSet();
Enumeration attrsInSet = entryAttrs.getAttributes();
while (attrsInSet.hasMoreElements()) {
- LDAPAttribute nextAttr = (LDAPAttribute)attrsInSet.nextElement();
+ LDAPAttribute nextAttr = (LDAPAttribute) attrsInSet.nextElement();
String attrName = nextAttr.getName();
- CMS.debug("DatabasePanel getInstanceDir: attribute name: "+attrName);
+ CMS.debug("DatabasePanel getInstanceDir: attribute name: " + attrName);
Enumeration valsInAttr = nextAttr.getStringValues();
- while ( valsInAttr.hasMoreElements() ) {
- String nextValue = (String)valsInAttr.nextElement();
+ while (valsInAttr.hasMoreElements()) {
+ String nextValue = (String) valsInAttr.nextElement();
if (attrName.equalsIgnoreCase("nsslapd-directory")) {
- CMS.debug("DatabasePanel getInstanceDir: instanceDir="+nextValue);
- return nextValue.substring(0,nextValue.lastIndexOf("/db"));
+ CMS.debug("DatabasePanel getInstanceDir: instanceDir=" + nextValue);
+ return nextValue.substring(0, nextValue.lastIndexOf("/db"));
}
}
}
}
} catch (LDAPException e) {
- CMS.debug("DatabasePanel getInstanceDir: Error in retrieving the instance directory. Exception: "+e.toString());
+ CMS.debug("DatabasePanel getInstanceDir: Error in retrieving the instance directory. Exception: " + e.toString());
}
return instancedir;
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/DatabaseServlet.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/DatabaseServlet.java
index d8fd7526..c44f6113 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/DatabaseServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/DatabaseServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -25,7 +24,6 @@ import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;
-
public class DatabaseServlet extends BaseServlet {
/**
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/DisplayCertChainPanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/DisplayCertChainPanel.java
index 1e1b6dec..f0a995fe 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/DisplayCertChainPanel.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/DisplayCertChainPanel.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Locale;
@@ -42,25 +41,26 @@ import com.netscape.cmsutil.crypto.CryptoUtil;
public class DisplayCertChainPanel extends WizardPanelBase {
- public DisplayCertChainPanel() {}
+ public DisplayCertChainPanel() {
+ }
/**
* Initializes this panel.
*/
- public void init(ServletConfig config, int panelno)
- throws ServletException {
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
setPanelNo(panelno);
setName("Display Certificate Chain");
}
public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
- throws ServletException {
+ throws ServletException {
setPanelNo(panelno);
setName("Display Certificate Chain");
setId(id);
}
-
- public boolean isSubPanel() {
+
+ public boolean isSubPanel() {
return true;
}
@@ -70,7 +70,7 @@ public class DisplayCertChainPanel extends WizardPanelBase {
public PropertySet getUsage() {
PropertySet set = new PropertySet();
-
+
return set;
}
@@ -86,8 +86,8 @@ public class DisplayCertChainPanel extends WizardPanelBase {
IConfigStore cs = CMS.getConfigStore();
// if we are root, no need to get the certificate chain.
- try {
- String select = cs.getString("securitydomain.select","");
+ try {
+ String select = cs.getString("securitydomain.select", "");
String type = cs.getString("preop.subsystem.select", "");
String hierarchy = cs.getString("preop.hierarchy.select", "");
@@ -117,7 +117,7 @@ public class DisplayCertChainPanel extends WizardPanelBase {
Context context) {
CMS.debug("DisplayCertChainPanel: display");
- // update session id
+ // update session id
String session_id = request.getParameter("session_id");
if (session_id != null) {
CMS.debug("DisplayCertChainPanel setting session id.");
@@ -132,7 +132,8 @@ public class DisplayCertChainPanel extends WizardPanelBase {
try {
certchain_size = cs.getString(certChainConfigName, "");
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
int size = 0;
Vector v = new Vector();
@@ -140,20 +141,22 @@ public class DisplayCertChainPanel extends WizardPanelBase {
if (!certchain_size.equals("")) {
try {
size = Integer.parseInt(certchain_size);
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
for (int i = 0; i < size; i++) {
certChainConfigName = "preop." + type + ".certchain." + i;
try {
String c = cs.getString(certChainConfigName, "");
byte[] b_c = CryptoUtil.base64Decode(c);
CertPrettyPrint pp = new CertPrettyPrint(
- new X509CertImpl(b_c));
+ new X509CertImpl(b_c));
v.addElement(pp.toString(Locale.getDefault()));
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
}
}
-
+
if (getId().equals("securitydomain")) {
context.put("panelid", "securitydomain");
context.put("panelname", "Security Domain Trust Verification");
@@ -184,7 +187,7 @@ public class DisplayCertChainPanel extends WizardPanelBase {
importCertChain(getId());
if (getId().equals("securitydomain")) {
- int panel = getPanelNo()+1;
+ int panel = getPanelNo() + 1;
IConfigStore cs = CMS.getConfigStore();
try {
String sd_hostname = cs.getString("securitydomain.host", "");
@@ -192,23 +195,23 @@ public class DisplayCertChainPanel extends WizardPanelBase {
String cs_hostname = cs.getString("machineName", "");
int cs_port = cs.getInteger("pkicreate.admin_secure_port", -1);
String subsystem = cs.getString("cs.type", "");
- String urlVal = "https://"+cs_hostname+":"+cs_port+"/"+toLowerCaseSubsystemType(subsystem)+"/admin/console/config/wizard?p="+panel+"&subsystem="+subsystem;
+ String urlVal = "https://" + cs_hostname + ":" + cs_port + "/" + toLowerCaseSubsystemType(subsystem) + "/admin/console/config/wizard?p=" + panel + "&subsystem=" + subsystem;
String encodedValue = URLEncoder.encode(urlVal, "UTF-8");
- String sdurl = "https://"+sd_hostname+":"+sd_port+"/ca/admin/ca/securityDomainLogin?url="+encodedValue;
+ String sdurl = "https://" + sd_hostname + ":" + sd_port + "/ca/admin/ca/securityDomainLogin?url=" + encodedValue;
response.sendRedirect(sdurl);
// The user previously specified the CA Security Domain's
// SSL Admin port in the "Security Domain Panel";
// now retrieve this specified CA Security Domain's
// non-SSL EE, SSL Agent, and SSL EE ports:
- cs.putString( "securitydomain.httpport",
- getSecurityDomainPort( cs, "UnSecurePort" ) );
- cs.putString("securitydomain.httpsagentport",
- getSecurityDomainPort( cs, "SecureAgentPort" ) );
- cs.putString("securitydomain.httpseeport",
- getSecurityDomainPort( cs, "SecurePort" ) );
+ cs.putString("securitydomain.httpport",
+ getSecurityDomainPort(cs, "UnSecurePort"));
+ cs.putString("securitydomain.httpsagentport",
+ getSecurityDomainPort(cs, "SecureAgentPort"));
+ cs.putString("securitydomain.httpseeport",
+ getSecurityDomainPort(cs, "SecurePort"));
} catch (Exception ee) {
- CMS.debug("DisplayCertChainPanel Exception="+ee.toString());
+ CMS.debug("DisplayCertChainPanel Exception=" + ee.toString());
}
}
context.put("updateStatus", "success");
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/DisplayServlet.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/DisplayServlet.java
index 00871921..3bb8c73c 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/DisplayServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/DisplayServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -25,7 +24,6 @@ import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;
-
public class DisplayServlet extends BaseServlet {
/**
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/DonePanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/DonePanel.java
index 9669ddb1..ed12465f 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/DonePanel.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/DonePanel.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.IOException;
import java.math.BigInteger;
import java.net.URLEncoder;
@@ -58,22 +57,23 @@ public class DonePanel extends WizardPanelBase {
public static final BigInteger BIG_ZERO = new BigInteger("0");
public static final Long MINUS_ONE = Long.valueOf(-1);
public static final String RESTART_SERVER_AFTER_CONFIGURATION =
- "restart_server_after_configuration";
+ "restart_server_after_configuration";
public static final String PKI_SECURITY_DOMAIN = "pki_security_domain";
- public DonePanel() {}
+ public DonePanel() {
+ }
/**
* Initializes this panel.
*/
- public void init(ServletConfig config, int panelno)
- throws ServletException {
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
setPanelNo(panelno);
setName("Done");
}
public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
- throws ServletException {
+ throws ServletException {
setPanelNo(panelno);
setName("Done");
setId(id);
@@ -88,15 +88,14 @@ public class DonePanel extends WizardPanelBase {
public PropertySet getUsage() {
PropertySet set = new PropertySet();
-
+
/* XXX */
-
+
return set;
}
private LDAPConnection getLDAPConn(Context context)
- throws IOException
- {
+ throws IOException {
IConfigStore cs = CMS.getConfigStore();
String host = "";
@@ -112,8 +111,8 @@ public class DonePanel extends WizardPanelBase {
pwd = pwdStore.getPassword("internaldb");
}
- if ( pwd == null) {
- throw new IOException("DonePanel: Failed to obtain password from password store");
+ if (pwd == null) {
+ throw new IOException("DonePanel: Failed to obtain password from password store");
}
try {
@@ -138,11 +137,11 @@ public class DonePanel extends WizardPanelBase {
LDAPConnection conn = null;
if (security.equals("true")) {
- CMS.debug("DonePanel getLDAPConn: creating secure (SSL) connection for internal ldap");
- conn = new LDAPConnection(CMS.getLdapJssSSLSocketFactory());
+ CMS.debug("DonePanel getLDAPConn: creating secure (SSL) connection for internal ldap");
+ conn = new LDAPConnection(CMS.getLdapJssSSLSocketFactory());
} else {
- CMS.debug("DonePanel getLDAPConn: creating non-secure (non-SSL) connection for internal ldap");
- conn = new LDAPConnection();
+ CMS.debug("DonePanel getLDAPConn: creating non-secure (non-SSL) connection for internal ldap");
+ conn = new LDAPConnection();
}
CMS.debug("DonePanel connecting to " + host + ":" + p);
@@ -153,10 +152,9 @@ public class DonePanel extends WizardPanelBase {
throw new IOException("Failed to connect to the internal database.");
}
- return conn;
+ return conn;
}
-
/**
* Display the panel.
*/
@@ -165,7 +163,7 @@ public class DonePanel extends WizardPanelBase {
Context context) {
CMS.debug("DonePanel: display()");
- // update session id
+ // update session id
String session_id = request.getParameter("session_id");
if (session_id != null) {
CMS.debug("NamePanel setting session id.");
@@ -193,31 +191,32 @@ public class DonePanel extends WizardPanelBase {
instanceRoot = cs.getString("instanceRoot");
select = cs.getString("preop.subsystem.select", "");
systemdService = cs.getString("pkicreate.systemd.servicename", "");
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
String initDaemon = "";
if (type.equals("CA")) {
- initDaemon = "pki-cad";
+ initDaemon = "pki-cad";
} else if (type.equals("KRA")) {
- initDaemon = "pki-krad";
+ initDaemon = "pki-krad";
} else if (type.equals("OCSP")) {
- initDaemon = "pki-ocspd";
+ initDaemon = "pki-ocspd";
} else if (type.equals("TKS")) {
- initDaemon = "pki-tksd";
+ initDaemon = "pki-tksd";
}
- String os = System.getProperty( "os.name" );
- if( os.equalsIgnoreCase( "Linux" ) ) {
- if (! systemdService.equals("")) {
- context.put( "initCommand", "/bin/systemctl");
- context.put( "instanceId", systemdService );
+ String os = System.getProperty("os.name");
+ if (os.equalsIgnoreCase("Linux")) {
+ if (!systemdService.equals("")) {
+ context.put("initCommand", "/bin/systemctl");
+ context.put("instanceId", systemdService);
} else {
- context.put( "initCommand", "/sbin/service " + initDaemon );
- context.put( "instanceId", instanceId );
+ context.put("initCommand", "/sbin/service " + initDaemon);
+ context.put("instanceId", instanceId);
}
} else {
- /* default case: e. g. - ( os.equalsIgnoreCase( "SunOS" ) */
- context.put( "initCommand", "/etc/init.d/" + initDaemon );
- context.put( "instanceId", instanceId );
+ /* default case: e. g. - ( os.equalsIgnoreCase( "SunOS" ) */
+ context.put("initCommand", "/etc/init.d/" + initDaemon);
+ context.put("instanceId", instanceId);
}
context.put("title", "Done");
context.put("panel", "admin/console/config/donepanel.vm");
@@ -233,7 +232,7 @@ public class DonePanel extends WizardPanelBase {
return;
} else
context.put("csstate", "0");
-
+
} catch (Exception e) {
}
@@ -280,11 +279,11 @@ public class DonePanel extends WizardPanelBase {
String basedn = cs.getString("internaldb.basedn");
String secdomain = cs.getString("securitydomain.name");
- try {
+ try {
// Create security domain ldap entry
String dn = "ou=Security Domain," + basedn;
CMS.debug("DonePanel: creating ldap entry : " + dn);
-
+
LDAPEntry entry = null;
LDAPAttributeSet attrs = null;
attrs = new LDAPAttributeSet();
@@ -305,10 +304,10 @@ public class DonePanel extends WizardPanelBase {
throw e;
}
- try {
+ try {
// create list containers
- String clist[] = {"CAList", "OCSPList", "KRAList", "RAList", "TKSList", "TPSList"};
- for (int i=0; i< clist.length; i++) {
+ String clist[] = { "CAList", "OCSPList", "KRAList", "RAList", "TKSList", "TPSList" };
+ for (int i = 0; i < clist.length; i++) {
LDAPEntry entry = null;
LDAPAttributeSet attrs = null;
String dn = "cn=" + clist[i] + ",ou=Security Domain," + basedn;
@@ -320,12 +319,12 @@ public class DonePanel extends WizardPanelBase {
conn.add(entry);
}
} catch (Exception e) {
- CMS.debug("Unable to create security domain list groups" );
+ CMS.debug("Unable to create security domain list groups");
throw e;
- }
+ }
try {
- // Add this host (only CA can create new domain)
+ // Add this host (only CA can create new domain)
String cn = ownhost + ":" + ownadminsport;
String dn = "cn=" + cn + ",cn=CAList,ou=Security Domain," + basedn;
LDAPEntry entry = null;
@@ -340,8 +339,8 @@ public class DonePanel extends WizardPanelBase {
attrs.add(new LDAPAttribute("SecureAdminPort",
ownadminsport));
if (owneeclientauthsport != null) {
- attrs.add(new LDAPAttribute("SecureEEClientAuthPort",
- owneeclientauthsport));
+ attrs.add(new LDAPAttribute("SecureEEClientAuthPort",
+ owneeclientauthsport));
}
attrs.add(new LDAPAttribute("UnSecurePort", ownport));
attrs.add(new LDAPAttribute("Clone", "FALSE"));
@@ -357,31 +356,32 @@ public class DonePanel extends WizardPanelBase {
CMS.debug("DonePanel display: finish updating domain info");
conn.disconnect();
} catch (Exception e) {
- CMS.debug("DonePanel display: "+e.toString());
+ CMS.debug("DonePanel display: " + e.toString());
}
int sd_admin_port_int = -1;
try {
- sd_admin_port_int = Integer.parseInt( sd_admin_port );
+ sd_admin_port_int = Integer.parseInt(sd_admin_port);
} catch (Exception e) {
}
try {
// Fetch the "new" security domain and display it
- CMS.debug( "Dump contents of new Security Domain . . ." );
- String c = getDomainXML( sd_host, sd_admin_port_int, true );
- } catch( Exception e ) {}
+ CMS.debug("Dump contents of new Security Domain . . .");
+ String c = getDomainXML(sd_host, sd_admin_port_int, true);
+ } catch (Exception e) {
+ }
// Since this instance is a new Security Domain,
// create an empty file to designate this fact.
String security_domain = instanceRoot + "/conf/"
+ PKI_SECURITY_DOMAIN;
- if( !Utils.isNT() ) {
- Utils.exec( "touch " + security_domain );
- Utils.exec( "chmod 00660 " + security_domain );
+ if (!Utils.isNT()) {
+ Utils.exec("touch " + security_domain);
+ Utils.exec("chmod 00660 " + security_domain);
}
- } else { //existing domain
+ } else { // existing domain
int sd_agent_port_int = -1;
int sd_admin_port_int = -1;
try {
@@ -398,34 +398,34 @@ public class DonePanel extends WizardPanelBase {
cloneStr = "&clone=false";
String domainMasterStr = "";
- if (cloneMaster)
+ if (cloneMaster)
domainMasterStr = "&dm=true";
- else
- domainMasterStr = "&dm=false";
+ else
+ domainMasterStr = "&dm=false";
String eecaStr = "";
- if (owneeclientauthsport != null)
- eecaStr="&eeclientauthsport=" + owneeclientauthsport;
+ if (owneeclientauthsport != null)
+ eecaStr = "&eeclientauthsport=" + owneeclientauthsport;
- updateDomainXML( sd_host, sd_agent_port_int, true,
- "/ca/agent/ca/updateDomainXML",
+ updateDomainXML(sd_host, sd_agent_port_int, true,
+ "/ca/agent/ca/updateDomainXML",
"list=" + s
- + "&type=" + type
- + "&host=" + ownhost
- + "&name=" + subsystemName
- + "&sport=" + ownsport
- + domainMasterStr
- + cloneStr
- + "&agentsport=" + ownagentsport
- + "&adminsport=" + ownadminsport
- + eecaStr
- + "&httpport=" + ownport );
+ + "&type=" + type
+ + "&host=" + ownhost
+ + "&name=" + subsystemName
+ + "&sport=" + ownsport
+ + domainMasterStr
+ + cloneStr
+ + "&agentsport=" + ownagentsport
+ + "&adminsport=" + ownadminsport
+ + eecaStr
+ + "&httpport=" + ownport);
// Fetch the "updated" security domain and display it
- CMS.debug( "Dump contents of updated Security Domain . . ." );
- String c = getDomainXML( sd_host, sd_admin_port_int, true );
+ CMS.debug("Dump contents of updated Security Domain . . .");
+ String c = getDomainXML(sd_host, sd_admin_port_int, true);
} catch (Exception e) {
context.put("errorString", "Failed to update the security domain on the domain master.");
- //return;
+ // return;
}
}
@@ -439,7 +439,6 @@ public class DonePanel extends WizardPanelBase {
CMS.debug("DonePanel: exception in adding service.securityDomainPort to CS.cfg" + e);
}
-
// need to push connector information to the CA
if (type.equals("KRA") && !ca_host.equals("")) {
try {
@@ -469,7 +468,7 @@ public class DonePanel extends WizardPanelBase {
setupClientAuthUser();
}
-
+
if (!select.equals("clone")) {
if (type.equals("CA") || type.equals("KRA")) {
String beginRequestNumStr = "";
@@ -478,7 +477,7 @@ public class DonePanel extends WizardPanelBase {
String endSerialNumStr = "";
String requestIncStr = "";
String serialIncStr = "";
-
+
try {
endRequestNumStr = cs.getString("dbs.endRequestNumber", "");
endSerialNumStr = cs.getString("dbs.endSerialNumber", "");
@@ -495,25 +494,26 @@ public class DonePanel extends WizardPanelBase {
serialdn = "ou=certificateRepository,ou=" + type.toLowerCase() + "," + basedn;
} else {
serialdn = "ou=keyRepository,ou=" + type.toLowerCase() + "," + basedn;
- }
- LDAPAttribute attrSerialNextRange = new LDAPAttribute( "nextRange", endSerialNum.add(oneNum).toString());
- LDAPModification serialmod = new LDAPModification( LDAPModification.REPLACE, attrSerialNextRange );
- conn.modify( serialdn, serialmod );
+ }
+ LDAPAttribute attrSerialNextRange = new LDAPAttribute("nextRange", endSerialNum.add(oneNum).toString());
+ LDAPModification serialmod = new LDAPModification(LDAPModification.REPLACE, attrSerialNextRange);
+ conn.modify(serialdn, serialmod);
String requestdn = "ou=" + type.toLowerCase() + ",ou=requests," + basedn;
- LDAPAttribute attrRequestNextRange = new LDAPAttribute( "nextRange", endRequestNum.add(oneNum).toString());
- LDAPModification requestmod = new LDAPModification( LDAPModification.REPLACE, attrRequestNextRange );
- conn.modify( requestdn, requestmod );
+ LDAPAttribute attrRequestNextRange = new LDAPAttribute("nextRange", endRequestNum.add(oneNum).toString());
+ LDAPModification requestmod = new LDAPModification(LDAPModification.REPLACE, attrRequestNextRange);
+ conn.modify(requestdn, requestmod);
- conn.disconnect();
+ conn.disconnect();
} catch (Exception e) {
CMS.debug("Unable to update global next range numbers: " + e);
- }
+ }
}
- }
+ }
if (cloneMaster) {
- // cloning a domain master CA, the clone is also master of its domain
+ // cloning a domain master CA, the clone is also master of its
+ // domain
try {
cs.putString("securitydomain.host", ownhost);
cs.putString("securitydomain.httpport", ownport);
@@ -550,24 +550,30 @@ public class DonePanel extends WizardPanelBase {
// more cloning variables needed for non-ca clones
- if (! type.equals("CA")) {
+ if (!type.equals("CA")) {
String val = cs.getString("preop.ca.hostname", "");
- if (val.compareTo("") != 0) cs.putString("cloning.ca.hostname", val);
+ if (val.compareTo("") != 0)
+ cs.putString("cloning.ca.hostname", val);
val = cs.getString("preop.ca.httpport", "");
- if (val.compareTo("") != 0) cs.putString("cloning.ca.httpport", val);
+ if (val.compareTo("") != 0)
+ cs.putString("cloning.ca.httpport", val);
- val = cs.getString("preop.ca.httpsport", "");
- if (val.compareTo("") != 0) cs.putString("cloning.ca.httpsport", val);
+ val = cs.getString("preop.ca.httpsport", "");
+ if (val.compareTo("") != 0)
+ cs.putString("cloning.ca.httpsport", val);
val = cs.getString("preop.ca.list", "");
- if (val.compareTo("") != 0) cs.putString("cloning.ca.list", val);
+ if (val.compareTo("") != 0)
+ cs.putString("cloning.ca.list", val);
val = cs.getString("preop.ca.pkcs7", "");
- if (val.compareTo("") != 0) cs.putString("cloning.ca.pkcs7", val);
+ if (val.compareTo("") != 0)
+ cs.putString("cloning.ca.pkcs7", val);
val = cs.getString("preop.ca.type", "");
- if (val.compareTo("") != 0) cs.putString("cloning.ca.type", val);
+ if (val.compareTo("") != 0)
+ cs.putString("cloning.ca.type", val);
}
// save EC type for sslserver cert (if present)
@@ -581,9 +587,9 @@ public class DonePanel extends WizardPanelBase {
// been restarted!
String restart_server = instanceRoot + "/conf/"
+ RESTART_SERVER_AFTER_CONFIGURATION;
- if( !Utils.isNT() ) {
- Utils.exec( "touch " + restart_server );
- Utils.exec( "chmod 00660 " + restart_server );
+ if (!Utils.isNT()) {
+ Utils.exec("touch " + restart_server);
+ Utils.exec("chmod 00660 " + restart_server);
}
} catch (Exception e) {
@@ -593,13 +599,12 @@ public class DonePanel extends WizardPanelBase {
context.put("csstate", "1");
}
- private void setupClientAuthUser()
- {
+ private void setupClientAuthUser() {
IConfigStore cs = CMS.getConfigStore();
// retrieve CA subsystem certificate from the CA
IUGSubsystem system =
- (IUGSubsystem) (CMS.getSubsystem(IUGSubsystem.ID));
+ (IUGSubsystem) (CMS.getSubsystem(IUGSubsystem.ID));
String id = "";
try {
String b64 = getCASubsystemCert();
@@ -640,9 +645,8 @@ public class DonePanel extends WizardPanelBase {
}
}
-
- private void updateOCSPConfig(HttpServletResponse response)
- throws IOException {
+ private void updateOCSPConfig(HttpServletResponse response)
+ throws IOException {
IConfigStore config = CMS.getConfigStore();
String cahost = "";
int caport = -1;
@@ -661,7 +665,7 @@ public class DonePanel extends WizardPanelBase {
int ocspport = Integer.parseInt(CMS.getAgentPort());
int ocspagentport = Integer.parseInt(CMS.getAgentPort());
String session_id = CMS.getConfigSDSessionId();
- String content = "xmlOutput=true&sessionID="+session_id+"&ocsp_host="+ocsphost+"&ocsp_port="+ocspport;
+ String content = "xmlOutput=true&sessionID=" + session_id + "&ocsp_host=" + ocsphost + "&ocsp_port=" + ocspport;
updateOCSPConfig(cahost, caport, true, content, response);
}
@@ -675,7 +679,7 @@ public class DonePanel extends WizardPanelBase {
if (b64.equals(""))
throw new IOException("Failed to get certificate chain.");
-
+
try {
// this could be a chain
X509Certificate[] certs = Cert.mapCertFromPKCS7(b64);
@@ -686,9 +690,9 @@ public class DonePanel extends WizardPanelBase {
} else {
leafCert = certs[0];
}
-
- IOCSPAuthority ocsp =
- (IOCSPAuthority)CMS.getSubsystem(IOCSPAuthority.ID);
+
+ IOCSPAuthority ocsp =
+ (IOCSPAuthority) CMS.getSubsystem(IOCSPAuthority.ID);
IDefStore defStore = ocsp.getDefaultStore();
// (1) need to normalize (sort) the chain
@@ -696,9 +700,9 @@ public class DonePanel extends WizardPanelBase {
// (2) store certificate (and certificate chain) into
// database
ICRLIssuingPointRecord rec = defStore.createCRLIssuingPointRecord(
- leafCert.getSubjectDN().getName(),
- BIG_ZERO,
- MINUS_ONE, null, null);
+ leafCert.getSubjectDN().getName(),
+ BIG_ZERO,
+ MINUS_ONE, null, null);
try {
rec.set(ICRLIssuingPointRecord.ATTR_CA_CERT, leafCert.getEncoded());
@@ -706,7 +710,9 @@ public class DonePanel extends WizardPanelBase {
// error
}
defStore.addCRLIssuingPoint(leafCert.getSubjectDN().getName(), rec);
- //log(ILogger.EV_AUDIT, AuditFormat.LEVEL, "Added CA certificate " + leafCert.getSubjectDN().getName());
+ // log(ILogger.EV_AUDIT, AuditFormat.LEVEL,
+ // "Added CA certificate " +
+ // leafCert.getSubjectDN().getName());
CMS.debug("DonePanel importCACertToOCSP: Added CA certificate.");
}
@@ -748,7 +754,7 @@ public class DonePanel extends WizardPanelBase {
}
private void updateConnectorInfo(String ownagenthost, String ownagentsport)
- throws IOException {
+ throws IOException {
IConfigStore cs = CMS.getConfigStore();
int port = -1;
String url = "";
@@ -757,21 +763,21 @@ public class DonePanel extends WizardPanelBase {
try {
url = cs.getString("preop.ca.url", "");
if (!url.equals("")) {
- host = cs.getString("preop.ca.hostname", "");
- port = cs.getInteger("preop.ca.httpsadminport", -1);
- transportCert = cs.getString("kra.transport.cert", "");
+ host = cs.getString("preop.ca.hostname", "");
+ port = cs.getInteger("preop.ca.httpsadminport", -1);
+ transportCert = cs.getString("kra.transport.cert", "");
}
} catch (Exception e) {
}
if (host == null) {
- CMS.debug("DonePanel: preop.ca.url is not defined. External CA selected. No transport certificate setup is required");
+ CMS.debug("DonePanel: preop.ca.url is not defined. External CA selected. No transport certificate setup is required");
} else {
- CMS.debug("DonePanel: Transport certificate is being setup in " + url);
- String session_id = CMS.getConfigSDSessionId();
- String content = "ca.connector.KRA.enable=true&ca.connector.KRA.local=false&ca.connector.KRA.timeout=30&ca.connector.KRA.uri=/kra/agent/kra/connector&ca.connector.KRA.host="+ownagenthost+"&ca.connector.KRA.port="+ownagentsport+"&ca.connector.KRA.transportCert="+URLEncoder.encode(transportCert)+"&sessionID="+session_id;
+ CMS.debug("DonePanel: Transport certificate is being setup in " + url);
+ String session_id = CMS.getConfigSDSessionId();
+ String content = "ca.connector.KRA.enable=true&ca.connector.KRA.local=false&ca.connector.KRA.timeout=30&ca.connector.KRA.uri=/kra/agent/kra/connector&ca.connector.KRA.host=" + ownagenthost + "&ca.connector.KRA.port=" + ownagentsport + "&ca.connector.KRA.transportCert=" + URLEncoder.encode(transportCert) + "&sessionID=" + session_id;
- updateConnectorInfo(host, port, true, content);
+ updateConnectorInfo(host, port, true, content);
}
}
@@ -802,12 +808,14 @@ public class DonePanel extends WizardPanelBase {
*/
public void update(HttpServletRequest request,
HttpServletResponse response,
- Context context) throws IOException {}
+ Context context) throws IOException {
+ }
/**
* If validiate() returns false, this method will be called.
*/
public void displayError(HttpServletRequest request,
HttpServletResponse response,
- Context context) {/* This should never be called */}
+ Context context) {/* This should never be called */
+ }
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/DownloadPKCS12.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/DownloadPKCS12.java
index 9d7fc22a..25332d86 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/DownloadPKCS12.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/DownloadPKCS12.java
@@ -50,6 +50,7 @@ public class DownloadPKCS12 extends CMSServlet {
/**
* initialize the servlet.
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -59,7 +60,7 @@ public class DownloadPKCS12 extends CMSServlet {
}
/**
- * Process the HTTP request.
+ * Process the HTTP request.
*/
protected void process(CMSRequest cmsReq) throws EBaseException {
CMS.debug("DownloadPKCS12: processing...");
@@ -70,7 +71,7 @@ public class DownloadPKCS12 extends CMSServlet {
mRenderResult = false;
// check the pin from the session
- String pin = (String)httpReq.getSession().getAttribute("pin");
+ String pin = (String) httpReq.getSession().getAttribute("pin");
if (pin == null) {
CMS.debug("DownloadPKCS12 process: Failed to get the pin from the cookie.");
outputError(httpResp, AUTH_FAILURE, "Error: Not authenticated");
@@ -101,18 +102,27 @@ public class DownloadPKCS12 extends CMSServlet {
httpResp.getOutputStream().write(pkcs12);
return;
} catch (Exception e) {
- CMS.debug("DownloadPKCS12 process: Exception="+e.toString());
+ CMS.debug("DownloadPKCS12 process: Exception=" + e.toString());
}
}
- protected void setDefaultTemplates(ServletConfig sc) {}
+ protected void setDefaultTemplates(ServletConfig sc) {
+ }
protected void renderTemplate(
CMSRequest cmsReq, String templateName, ICMSTemplateFiller filler)
- throws IOException {// do nothing
- }
+ throws IOException {// do nothing
+ }
- protected void renderResult(CMSRequest cmsReq) throws IOException {// do nothing, ie, it will not return the default javascript.
+ protected void renderResult(CMSRequest cmsReq) throws IOException {// do
+ // nothing,
+ // ie, it
+ // will
+ // not
+ // return
+ // the
+ // default
+ // javascript.
}
/**
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetCertChain.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetCertChain.java
index 87cb7a7c..452ead98 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetCertChain.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetCertChain.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Locale;
@@ -40,7 +39,6 @@ import com.netscape.cms.servlet.base.UserInfo;
import com.netscape.cms.servlet.common.CMSRequest;
import com.netscape.cmsutil.xml.XMLObject;
-
public class GetCertChain extends CMSServlet {
/**
@@ -56,6 +54,7 @@ public class GetCertChain extends CMSServlet {
/**
* initialize the servlet.
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -63,11 +62,13 @@ public class GetCertChain extends CMSServlet {
}
/**
- * Process the HTTP request.
+ * Process the HTTP request.
* <ul>
* <li>http.param op 'downloadBIN' - return the binary certificate chain
- * <li>http.param op 'displayIND' - display pretty-print of certificate chain components
+ * <li>http.param op 'displayIND' - display pretty-print of certificate
+ * chain components
* </ul>
+ *
* @param cmsReq the object holding the request and response information
*/
protected void process(CMSRequest cmsReq) throws EBaseException {
@@ -95,7 +96,7 @@ public class GetCertChain extends CMSServlet {
} catch (IOException e) {
log(ILogger.LL_FAILURE,
CMS.getLogMessage("CMSGW_ERROR_ENCODING_CA_CHAIN_1",
- e.toString()));
+ e.toString()));
outputError(httpResp,
"Error: Failed to encode the certificate chain");
}
@@ -121,7 +122,15 @@ public class GetCertChain extends CMSServlet {
}
}
- protected void renderResult(CMSRequest cmsReq) throws IOException {// do nothing, ie, it will not return the default javascript.
+ protected void renderResult(CMSRequest cmsReq) throws IOException {// do
+ // nothing,
+ // ie, it
+ // will
+ // not
+ // return
+ // the
+ // default
+ // javascript.
}
/**
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetConfigEntries.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetConfigEntries.java
index c1010b46..456bf6c1 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetConfigEntries.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetConfigEntries.java
@@ -59,6 +59,7 @@ public class GetConfigEntries extends CMSServlet {
/**
* initialize the servlet.
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -67,11 +68,13 @@ public class GetConfigEntries extends CMSServlet {
}
/**
- * Process the HTTP request.
+ * Process the HTTP request.
* <ul>
* <li>http.param op 'downloadBIN' - return the binary certificate chain
- * <li>http.param op 'displayIND' - display pretty-print of certificate chain components
+ * <li>http.param op 'displayIND' - display pretty-print of certificate
+ * chain components
* </ul>
+ *
* @param cmsReq the object holding the request and response information
*/
protected void process(CMSRequest cmsReq) throws EBaseException {
@@ -84,12 +87,12 @@ public class GetConfigEntries extends CMSServlet {
authToken = authenticate(cmsReq);
} catch (Exception e) {
CMS.debug("GetConfigEntries authentication failed");
- log(ILogger.LL_FAILURE,
+ log(ILogger.LL_FAILURE,
CMS.getLogMessage("CMSGW_ERR_BAD_SERV_OUT_STREAM", "",
- e.toString()));
+ e.toString()));
outputError(httpResp, AUTH_FAILURE, "Error: Not authenticated");
return;
- }
+ }
// Construct an ArgBlock
IArgBlock args = cmsReq.getHttpParams();
@@ -104,32 +107,32 @@ public class GetConfigEntries extends CMSServlet {
try {
xmlObj = new XMLObject();
} catch (Exception e) {
- CMS.debug("GetConfigEntries process: Exception: "+e.toString());
- throw new EBaseException( e.toString() );
+ CMS.debug("GetConfigEntries process: Exception: " + e.toString());
+ throw new EBaseException(e.toString());
}
Node root = xmlObj.createRoot("XMLResponse");
AuthzToken authzToken = null;
try {
- authzToken = authorize(mAclMethod, authToken, mAuthzResourceName,
+ authzToken = authorize(mAclMethod, authToken, mAuthzResourceName,
"read");
} catch (EAuthzAccessDenied e) {
- log(ILogger.LL_FAILURE,
+ log(ILogger.LL_FAILURE,
CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
- outputError(httpResp, "Error: Not authorized");
- return;
+ outputError(httpResp, "Error: Not authorized");
+ return;
} catch (Exception e) {
- log(ILogger.LL_FAILURE,
+ log(ILogger.LL_FAILURE,
CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
- outputError(httpResp,
+ outputError(httpResp,
"Error: Encountered problem during authorization.");
- return;
+ return;
}
if (authzToken == null) {
- outputError(httpResp, "Error: Not authorized");
- return;
+ outputError(httpResp, "Error: Not authorized");
+ return;
}
if (op != null) {
@@ -140,9 +143,9 @@ public class GetConfigEntries extends CMSServlet {
String name1 = t.nextToken();
IConfigStore cs = config.getSubStore(name1);
Enumeration enum1 = cs.getPropertyNames();
-
+
while (enum1.hasMoreElements()) {
- String name = name1+"."+enum1.nextElement();
+ String name = name1 + "." + enum1.nextElement();
try {
String value = config.getString(name);
Node container = xmlObj.createContainer(root, "Config");
@@ -171,10 +174,10 @@ public class GetConfigEntries extends CMSServlet {
value = getLDAPPassword();
} else if (name.equals("internaldb.replication.password")) {
value = getReplicationPassword();
- } else
+ } else
continue;
}
-
+
Node container = xmlObj.createContainer(root, "Config");
xmlObj.addItemToContainer(container, "name", name);
xmlObj.addItemToContainer(container, "value", value);
@@ -208,7 +211,15 @@ public class GetConfigEntries extends CMSServlet {
return locale;
}
- protected void renderResult(CMSRequest cmsReq) throws IOException {// do nothing, ie, it will not return the default javascript.
+ protected void renderResult(CMSRequest cmsReq) throws IOException {// do
+ // nothing,
+ // ie, it
+ // will
+ // not
+ // return
+ // the
+ // default
+ // javascript.
}
private String getLDAPPassword() {
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetCookie.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetCookie.java
index 74edda79..daa60911 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetCookie.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetCookie.java
@@ -45,7 +45,6 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
public class GetCookie extends CMSServlet {
/**
@@ -58,9 +57,9 @@ public class GetCookie extends CMSServlet {
private String mFormPath = null;
private final static String LOGGING_SIGNED_AUDIT_SECURITY_DOMAIN_UPDATE =
- "LOGGING_SIGNED_AUDIT_SECURITY_DOMAIN_UPDATE_1";
+ "LOGGING_SIGNED_AUDIT_SECURITY_DOMAIN_UPDATE_1";
private final static String LOGGING_SIGNED_AUDIT_ROLE_ASSUME =
- "LOGGING_SIGNED_AUDIT_ROLE_ASSUME_3";
+ "LOGGING_SIGNED_AUDIT_ROLE_ASSUME_3";
public GetCookie() {
super();
@@ -68,6 +67,7 @@ public class GetCookie extends CMSServlet {
/**
* initialize the servlet.
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -78,12 +78,13 @@ public class GetCookie extends CMSServlet {
mRandom = new Random();
mErrorFormPath = sc.getInitParameter("errorTemplatePath");
if (mOutputTemplatePath != null) {
- mFormPath = mOutputTemplatePath;
+ mFormPath = mOutputTemplatePath;
}
}
/**
- * Process the HTTP request.
+ * Process the HTTP request.
+ *
* @param cmsReq the object holding the request and response information
*/
protected void process(CMSRequest cmsReq) throws EBaseException {
@@ -100,14 +101,14 @@ public class GetCookie extends CMSServlet {
}
IArgBlock header = CMS.createArgBlock();
- IArgBlock ctx = CMS.createArgBlock();
+ IArgBlock ctx = CMS.createArgBlock();
CMSTemplateParams argSet = new CMSTemplateParams(header, ctx);
CMSTemplate form = null;
Locale[] locale = new Locale[1];
String url = httpReq.getParameter("url");
- CMS.debug("GetCookie before auth, url ="+url);
+ CMS.debug("GetCookie before auth, url =" + url);
String url_e = "";
URL u = null;
try {
@@ -115,13 +116,13 @@ public class GetCookie extends CMSServlet {
u = new URL(url_e);
} catch (Exception eee) {
throw new ECMSGWException(
- "GetCookie missing parameter: url");
+ "GetCookie missing parameter: url");
}
int index2 = url_e.indexOf("subsystem=");
String subsystem = "";
if (index2 > 0) {
- subsystem = url.substring(index2+10);
+ subsystem = url.substring(index2 + 10);
int index1 = subsystem.indexOf("&");
if (index1 > 0)
subsystem = subsystem.substring(0, index1);
@@ -131,9 +132,9 @@ public class GetCookie extends CMSServlet {
authToken = authenticate(cmsReq);
} catch (Exception e) {
CMS.debug("GetCookie authentication failed");
- log(ILogger.LL_FAILURE,
+ log(ILogger.LL_FAILURE,
CMS.getLogMessage("CMSGW_ERR_BAD_SERV_OUT_STREAM", "",
- e.toString()));
+ e.toString()));
header.addStringValue("sd_uid", "");
header.addStringValue("sd_pwd", "");
header.addStringValue("host", u.getHost());
@@ -149,17 +150,17 @@ public class GetCookie extends CMSServlet {
form = getTemplate(mErrorFormPath, httpReq, locale);
} catch (IOException eee) {
CMS.debug("GetCookie process: cant locate the form");
-/*
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", e.toString()));
- throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
-*/
- }
+ /*
+ * log(ILogger.LL_FAILURE,
+ * CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", e.toString()));
+ * throw new ECMSGWException(
+ * CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ */
+ }
- if( form == null ) {
+ if (form == null) {
CMS.debug("GetCookie::process() - form is null!");
- throw new EBaseException( "form is null" );
+ throw new EBaseException("form is null");
}
try {
@@ -170,16 +171,16 @@ public class GetCookie extends CMSServlet {
form.renderOutput(out, argSet);
} catch (IOException ee) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_OUT_STREAM_TEMPLATE", ee.toString()));
- throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getLogMessage("CMSGW_ERR_OUT_STREAM_TEMPLATE", ee.toString()));
+ throw new ECMSGWException(
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
return;
- }
+ }
String cookie = "";
String auditMessage = "";
-
+
if (authToken != null) {
String uid = authToken.getInString("uid");
String groupname = getGroupName(uid, subsystem);
@@ -195,7 +196,7 @@ public class GetCookie extends CMSServlet {
// assign cookie
long num = mRandom.nextLong();
- cookie = num+"";
+ cookie = num + "";
ISecurityDomainSessionTable ctable = CMS.getSecurityDomainSessionTable();
String addr = "";
try {
@@ -207,11 +208,11 @@ public class GetCookie extends CMSServlet {
ip = InetAddress.getByName(addr).toString();
int index = ip.indexOf("/");
if (index > 0)
- ip = ip.substring(index+1);
+ ip = ip.substring(index + 1);
} catch (Exception e) {
}
- String auditParams = "operation;;issue_token+token;;"+ cookie + "+ip;;" + ip +
+ String auditParams = "operation;;issue_token+token;;" + cookie + "+ip;;" + ip +
"+uid;;" + uid + "+groupname;;" + groupname;
int status = ctable.addEntry(cookie, ip, uid, groupname);
@@ -232,18 +233,19 @@ public class GetCookie extends CMSServlet {
}
try {
- String sd_url = "https://"+CMS.getEESSLHost()+":"+CMS.getEESSLPort();
+ String sd_url = "https://" + CMS.getEESSLHost() + ":" + CMS.getEESSLPort();
if (!url.startsWith("$")) {
try {
form = getTemplate(mFormPath, httpReq, locale);
} catch (IOException e) {
CMS.debug("GetCookie process: cant locate the form");
-/*
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", e.toString()));
- throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
-*/
+ /*
+ * log(ILogger.LL_FAILURE,
+ * CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE",
+ * e.toString())); throw new ECMSGWException(
+ * CMS.getUserMessage
+ * ("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ */
}
header.addStringValue("url", url);
@@ -254,13 +256,13 @@ public class GetCookie extends CMSServlet {
ServletOutputStream out = httpResp.getOutputStream();
cmsReq.setStatus(CMSRequest.SUCCESS);
- httpResp.setContentType("text/html");
- form.renderOutput(out, argSet);
+ httpResp.setContentType("text/html");
+ form.renderOutput(out, argSet);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_OUT_STREAM_TEMPLATE", e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_OUT_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
}
} catch (Exception e) {
@@ -278,25 +280,25 @@ public class GetCookie extends CMSServlet {
private String getGroupName(String uid, String subsystemname) {
String groupname = "";
- IUGSubsystem subsystem =
- (IUGSubsystem)(CMS.getSubsystem(IUGSubsystem.ID));
- if (subsystem.isMemberOf(uid, "Enterprise CA Administrators") &&
- subsystemname.equals("CA")) {
+ IUGSubsystem subsystem =
+ (IUGSubsystem) (CMS.getSubsystem(IUGSubsystem.ID));
+ if (subsystem.isMemberOf(uid, "Enterprise CA Administrators") &&
+ subsystemname.equals("CA")) {
return "Enterprise CA Administrators";
} else if (subsystem.isMemberOf(uid, "Enterprise KRA Administrators") &&
- subsystemname.equals("KRA")) {
+ subsystemname.equals("KRA")) {
return "Enterprise KRA Administrators";
} else if (subsystem.isMemberOf(uid, "Enterprise OCSP Administrators") &&
- subsystemname.equals("OCSP")) {
+ subsystemname.equals("OCSP")) {
return "Enterprise OCSP Administrators";
} else if (subsystem.isMemberOf(uid, "Enterprise TKS Administrators") &&
- subsystemname.equals("TKS")) {
+ subsystemname.equals("TKS")) {
return "Enterprise TKS Administrators";
} else if (subsystem.isMemberOf(uid, "Enterprise RA Administrators") &&
- subsystemname.equals("RA")) {
+ subsystemname.equals("RA")) {
return "Enterprise RA Administrators";
} else if (subsystem.isMemberOf(uid, "Enterprise TPS Administrators") &&
- subsystemname.equals("TPS")) {
+ subsystemname.equals("TPS")) {
return "Enterprise TPS Administrators";
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetDomainXML.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetDomainXML.java
index f9e6c70e..d983e4a1 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetDomainXML.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetDomainXML.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Enumeration;
@@ -48,7 +47,6 @@ import com.netscape.cms.servlet.common.CMSRequest;
import com.netscape.cms.servlet.common.ICMSTemplateFiller;
import com.netscape.cmsutil.xml.XMLObject;
-
public class GetDomainXML extends CMSServlet {
/**
@@ -64,6 +62,7 @@ public class GetDomainXML extends CMSServlet {
/**
* initialize the servlet.
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -73,11 +72,13 @@ public class GetDomainXML extends CMSServlet {
}
/**
- * Process the HTTP request.
+ * Process the HTTP request.
* <ul>
* <li>http.param op 'downloadBIN' - return the binary certificate chain
- * <li>http.param op 'displayIND' - display pretty-print of certificate chain components
+ * <li>http.param op 'displayIND' - display pretty-print of certificate
+ * chain components
* </ul>
+ *
* @param cmsReq the object holding the request and response information
*/
protected void process(CMSRequest cmsReq) throws EBaseException {
@@ -95,8 +96,7 @@ public class GetDomainXML extends CMSServlet {
try {
secstore = cs.getString("securitydomain.store");
basedn = cs.getString("internaldb.basedn");
- }
- catch (Exception e) {
+ } catch (Exception e) {
CMS.debug("Unable to determine the security domain name or internal basedn. Please run the domaininfo migration script");
}
@@ -120,16 +120,16 @@ public class GetDomainXML extends CMSServlet {
connFactory.init(ldapConfig);
conn = connFactory.getConn();
- // get the security domain name
+ // get the security domain name
String secdomain = (String) conn.read(dn).getAttribute("name").getStringValues().nextElement();
XMLObject xmlObj = new XMLObject();
Node domainInfo = xmlObj.createRoot("DomainInfo");
xmlObj.addItemToContainer(domainInfo, "Name", secdomain);
- // this should return CAList, KRAList etc.
+ // this should return CAList, KRAList etc.
LDAPSearchResults res = conn.search(dn, LDAPConnection.SCOPE_ONE, filter,
- attrs, true, cons);
+ attrs, true, cons);
while (res.hasMoreElements()) {
int count = 0;
@@ -137,10 +137,10 @@ public class GetDomainXML extends CMSServlet {
String listName = dn.substring(3, dn.indexOf(","));
String subType = listName.substring(0, listName.indexOf("List"));
Node listNode = xmlObj.createContainer(domainInfo, listName);
-
+
filter = "objectclass=pkiSubsystem";
- LDAPSearchResults res2 = conn.search(dn, LDAPConnection.SCOPE_ONE, filter,
- attrs, false, cons);
+ LDAPSearchResults res2 = conn.search(dn, LDAPConnection.SCOPE_ONE, filter,
+ attrs, false, cons);
while (res2.hasMoreElements()) {
Node node = xmlObj.createContainer(listNode, subType);
LDAPEntry entry = res2.next();
@@ -149,32 +149,29 @@ public class GetDomainXML extends CMSServlet {
while (attrsInSet.hasMoreElements()) {
LDAPAttribute nextAttr = (LDAPAttribute) attrsInSet.nextElement();
String attrName = nextAttr.getName();
- if ((! attrName.equals("cn")) && (! attrName.equals("objectClass"))) {
+ if ((!attrName.equals("cn")) && (!attrName.equals("objectClass"))) {
String attrValue = (String) nextAttr.getStringValues().nextElement();
xmlObj.addItemToContainer(node, securityDomainLDAPtoXML(attrName), attrValue);
}
}
- count ++;
- }
+ count++;
+ }
xmlObj.addItemToContainer(listNode, "SubsystemCount", Integer.toString(count));
}
// Add new xml object as string to response.
response.addItemToContainer(root, "DomainInfo", xmlObj.toXMLString());
- }
- catch (Exception e) {
+ } catch (Exception e) {
CMS.debug("GetDomainXML: Failed to read domain.xml from ldap " + e.toString());
status = FAILED;
- }
- finally {
- if ((conn != null) && (connFactory!= null)) {
+ } finally {
+ if ((conn != null) && (connFactory != null)) {
CMS.debug("Releasing ldap connection");
connFactory.returnConn(conn);
}
}
- }
- else {
- // get data from file store
+ } else {
+ // get data from file store
String path = CMS.getConfigStore().getString("instanceRoot", "")
+ "/conf/domain.xml";
@@ -194,10 +191,9 @@ public class GetDomainXML extends CMSServlet {
CMS.debug("GetDomainXML: Done Reading domain.xml...");
response.addItemToContainer(root, "DomainInfo", new String(buf));
- }
- catch (Exception e) {
- CMS.debug("Failed to read domain.xml from file" + e.toString());
- status = FAILED;
+ } catch (Exception e) {
+ CMS.debug("Failed to read domain.xml from file" + e.toString());
+ status = FAILED;
}
}
@@ -211,18 +207,29 @@ public class GetDomainXML extends CMSServlet {
}
protected String securityDomainLDAPtoXML(String attribute) {
- if (attribute.equals("host")) return "Host";
- else return attribute;
+ if (attribute.equals("host"))
+ return "Host";
+ else
+ return attribute;
}
- protected void setDefaultTemplates(ServletConfig sc) {}
+ protected void setDefaultTemplates(ServletConfig sc) {
+ }
protected void renderTemplate(
CMSRequest cmsReq, String templateName, ICMSTemplateFiller filler)
- throws IOException {// do nothing
- }
+ throws IOException {// do nothing
+ }
- protected void renderResult(CMSRequest cmsReq) throws IOException {// do nothing, ie, it will not return the default javascript.
+ protected void renderResult(CMSRequest cmsReq) throws IOException {// do
+ // nothing,
+ // ie, it
+ // will
+ // not
+ // return
+ // the
+ // default
+ // javascript.
}
/**
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetStatus.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetStatus.java
index 02fe36c1..623acf9a 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetStatus.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetStatus.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.IOException;
import java.util.Locale;
@@ -36,7 +35,6 @@ import com.netscape.cms.servlet.base.UserInfo;
import com.netscape.cms.servlet.common.CMSRequest;
import com.netscape.cmsutil.xml.XMLObject;
-
public class GetStatus extends CMSServlet {
/**
@@ -52,6 +50,7 @@ public class GetStatus extends CMSServlet {
/**
* initialize the servlet.
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -59,18 +58,19 @@ public class GetStatus extends CMSServlet {
}
/**
- * Process the HTTP request.
+ * Process the HTTP request.
+ *
* @param cmsReq the object holding the request and response information
*/
protected void process(CMSRequest cmsReq) throws EBaseException {
HttpServletRequest httpReq = cmsReq.getHttpReq();
HttpServletResponse httpResp = cmsReq.getHttpResp();
- IConfigStore config = CMS.getConfigStore();
+ IConfigStore config = CMS.getConfigStore();
String outputString = null;
- String state = config.getString("cs.state", "");
- String type = config.getString("cs.type", "");
+ String state = config.getString("cs.state", "");
+ String type = config.getString("cs.type", "");
try {
XMLObject xmlObj = null;
@@ -89,7 +89,15 @@ public class GetStatus extends CMSServlet {
}
}
- protected void renderResult(CMSRequest cmsReq) throws IOException {// do nothing, ie, it will not return the default javascript.
+ protected void renderResult(CMSRequest cmsReq) throws IOException {// do
+ // nothing,
+ // ie, it
+ // will
+ // not
+ // return
+ // the
+ // default
+ // javascript.
}
/**
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetSubsystemCert.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetSubsystemCert.java
index c1bf138e..59e135a1 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetSubsystemCert.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetSubsystemCert.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.IOException;
import java.util.Locale;
@@ -39,7 +38,6 @@ import com.netscape.cms.servlet.common.CMSRequest;
import com.netscape.cmsutil.crypto.CryptoUtil;
import com.netscape.cmsutil.xml.XMLObject;
-
public class GetSubsystemCert extends CMSServlet {
/**
@@ -55,6 +53,7 @@ public class GetSubsystemCert extends CMSServlet {
/**
* initialize the servlet.
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -62,7 +61,7 @@ public class GetSubsystemCert extends CMSServlet {
}
/**
- * Process the HTTP request.
+ * Process the HTTP request.
*/
protected void process(CMSRequest cmsReq) throws EBaseException {
HttpServletRequest httpReq = cmsReq.getHttpReq();
@@ -76,16 +75,16 @@ public class GetSubsystemCert extends CMSServlet {
nickname = cs.getString("ca.subsystem.nickname", "");
String tokenname = cs.getString("ca.subsystem.tokenname", "");
if (!tokenname.equals("internal") && !tokenname.equals("Internal Key Storage Token"))
- nickname = tokenname+":"+nickname;
+ nickname = tokenname + ":" + nickname;
} catch (Exception e) {
}
- CMS.debug("GetSubsystemCert process: nickname="+nickname);
+ CMS.debug("GetSubsystemCert process: nickname=" + nickname);
String s = "";
try {
CryptoManager cm = CryptoManager.getInstance();
X509Certificate cert = cm.findCertByNickname(nickname);
-
+
if (cert == null) {
CMS.debug("GetSubsystemCert process: subsystem cert is null");
outputError(httpResp, "Error: Failed to get subsystem certificate.");
@@ -95,7 +94,7 @@ public class GetSubsystemCert extends CMSServlet {
byte[] bytes = cert.getEncoded();
s = CryptoUtil.normalizeCertStr(CryptoUtil.base64Encode(bytes));
} catch (Exception e) {
- CMS.debug("GetSubsystemCert process: exception: "+e.toString());
+ CMS.debug("GetSubsystemCert process: exception: " + e.toString());
}
try {
@@ -111,7 +110,15 @@ public class GetSubsystemCert extends CMSServlet {
}
}
- protected void renderResult(CMSRequest cmsReq) throws IOException {// do nothing, ie, it will not return the default javascript.
+ protected void renderResult(CMSRequest cmsReq) throws IOException {// do
+ // nothing,
+ // ie, it
+ // will
+ // not
+ // return
+ // the
+ // default
+ // javascript.
}
/**
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetTokenInfo.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetTokenInfo.java
index d7af0740..f4d68392 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetTokenInfo.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetTokenInfo.java
@@ -52,6 +52,7 @@ public class GetTokenInfo extends CMSServlet {
/**
* initialize the servlet.
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -60,11 +61,13 @@ public class GetTokenInfo extends CMSServlet {
}
/**
- * Process the HTTP request.
+ * Process the HTTP request.
* <ul>
* <li>http.param op 'downloadBIN' - return the binary certificate chain
- * <li>http.param op 'displayIND' - display pretty-print of certificate chain components
+ * <li>http.param op 'displayIND' - display pretty-print of certificate
+ * chain components
* </ul>
+ *
* @param cmsReq the object holding the request and response information
*/
protected void process(CMSRequest cmsReq) throws EBaseException {
@@ -78,8 +81,8 @@ public class GetTokenInfo extends CMSServlet {
try {
xmlObj = new XMLObject();
} catch (Exception e) {
- CMS.debug("GetTokenInfo process: Exception: "+e.toString());
- throw new EBaseException( e.toString() );
+ CMS.debug("GetTokenInfo process: Exception: " + e.toString());
+ throw new EBaseException(e.toString());
}
Node root = xmlObj.createRoot("XMLResponse");
@@ -97,7 +100,7 @@ public class GetTokenInfo extends CMSServlet {
String name = t1.nextToken();
if (name.equals("sslserver"))
continue;
- name = "cloning."+name+".nickname";
+ name = "cloning." + name + ".nickname";
String value = "";
try {
@@ -105,7 +108,7 @@ public class GetTokenInfo extends CMSServlet {
} catch (Exception ee) {
continue;
}
-
+
Node container = xmlObj.createContainer(root, "Config");
xmlObj.addItemToContainer(container, "name", name);
xmlObj.addItemToContainer(container, "value", value);
@@ -149,6 +152,14 @@ public class GetTokenInfo extends CMSServlet {
return locale;
}
- protected void renderResult(CMSRequest cmsReq) throws IOException {// do nothing, ie, it will not return the default javascript.
+ protected void renderResult(CMSRequest cmsReq) throws IOException {// do
+ // nothing,
+ // ie, it
+ // will
+ // not
+ // return
+ // the
+ // default
+ // javascript.
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetTransportCert.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetTransportCert.java
index bc29b34a..2722b0f7 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetTransportCert.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetTransportCert.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.IOException;
import java.security.cert.CertificateEncodingException;
import java.util.Locale;
@@ -63,6 +62,7 @@ public class GetTransportCert extends CMSServlet {
/**
* initialize the servlet.
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -72,7 +72,7 @@ public class GetTransportCert extends CMSServlet {
}
/**
- * Process the HTTP request.
+ * Process the HTTP request.
*/
protected void process(CMSRequest cmsReq) throws EBaseException {
CMS.debug("UpdateUpdater: processing...");
@@ -86,9 +86,9 @@ public class GetTransportCert extends CMSServlet {
CMS.debug("GetTransportCert authentication successful.");
} catch (Exception e) {
CMS.debug("GetTransportCert: authentication failed.");
- log(ILogger.LL_FAILURE,
+ log(ILogger.LL_FAILURE,
CMS.getLogMessage("CMSGW_ERR_BAD_SERV_OUT_STREAM", "",
- e.toString()));
+ e.toString()));
outputError(httpResp, AUTH_FAILURE, "Error: Not authenticated");
return;
}
@@ -101,19 +101,19 @@ public class GetTransportCert extends CMSServlet {
AuthzToken authzToken = null;
try {
- authzToken = authorize(mAclMethod, authToken, mAuthzResourceName,
- "read");
+ authzToken = authorize(mAclMethod, authToken, mAuthzResourceName,
+ "read");
CMS.debug("GetTransportCert authorization successful.");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
outputError(httpResp, "Error: Not authorized");
return;
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
outputError(httpResp,
- "Error: Encountered problem during authorization.");
+ "Error: Encountered problem during authorization.");
return;
}
@@ -126,17 +126,17 @@ public class GetTransportCert extends CMSServlet {
IKeyRecoveryAuthority kra =
(IKeyRecoveryAuthority) mAuthority;
- ITransportKeyUnit tu = kra.getTransportKeyUnit();
- org.mozilla.jss.crypto.X509Certificate transportCert =
+ ITransportKeyUnit tu = kra.getTransportKeyUnit();
+ org.mozilla.jss.crypto.X509Certificate transportCert =
tu.getCertificate();
- String mime64 = "";
+ String mime64 = "";
try {
mime64 = CMS.BtoA(transportCert.getEncoded());
mime64 = com.netscape.cmsutil.util.Cert.normalizeCertStrAndReq(mime64);
- } catch (CertificateEncodingException eee) {
+ } catch (CertificateEncodingException eee) {
CMS.debug("GetTransportCert: Failed to encode certificate");
- }
+ }
// send success status back to the requestor
try {
@@ -154,14 +154,23 @@ public class GetTransportCert extends CMSServlet {
}
}
- protected void setDefaultTemplates(ServletConfig sc) {}
+ protected void setDefaultTemplates(ServletConfig sc) {
+ }
protected void renderTemplate(
CMSRequest cmsReq, String templateName, ICMSTemplateFiller filler)
- throws IOException {// do nothing
- }
+ throws IOException {// do nothing
+ }
- protected void renderResult(CMSRequest cmsReq) throws IOException {// do nothing, ie, it will not return the default javascript.
+ protected void renderResult(CMSRequest cmsReq) throws IOException {// do
+ // nothing,
+ // ie, it
+ // will
+ // not
+ // return
+ // the
+ // default
+ // javascript.
}
/**
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/HierarchyPanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/HierarchyPanel.java
index a00b0fb7..b42bdb7d 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/HierarchyPanel.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/HierarchyPanel.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.IOException;
import javax.servlet.ServletConfig;
@@ -36,19 +35,20 @@ import com.netscape.cms.servlet.wizard.WizardServlet;
public class HierarchyPanel extends WizardPanelBase {
- public HierarchyPanel() {}
+ public HierarchyPanel() {
+ }
/**
* Initializes this panel.
*/
- public void init(ServletConfig config, int panelno)
- throws ServletException {
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
setPanelNo(panelno);
setName("PKI Hierarchy");
}
public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
- throws ServletException {
+ throws ServletException {
setPanelNo(panelno);
setName("PKI Hierarchy");
setId(id);
@@ -56,7 +56,7 @@ public class HierarchyPanel extends WizardPanelBase {
public boolean shouldSkip() {
- // we dont need to ask the hierachy if we are
+ // we dont need to ask the hierachy if we are
// setting up a clone
try {
IConfigStore c = CMS.getConfigStore();
@@ -64,8 +64,8 @@ public class HierarchyPanel extends WizardPanelBase {
null);
if (s != null && s.equals("clone")) {
// mark this panel as done
- c.putString("preop.hierarchy.select","root");
- c.putString("hierarchy.select","Clone");
+ c.putString("preop.hierarchy.select", "root");
+ c.putString("hierarchy.select", "Clone");
return true;
}
} catch (EBaseException e) {
@@ -89,15 +89,16 @@ public class HierarchyPanel extends WizardPanelBase {
} else {
return true;
}
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
return false;
}
public PropertySet getUsage() {
PropertySet set = new PropertySet();
-
+
/* XXX */
-
+
return set;
}
@@ -117,7 +118,7 @@ public class HierarchyPanel extends WizardPanelBase {
if (s.equals("root")) {
context.put("check_root", "checked");
} else if (s.equals("join")) {
- context.put("check_join", "checked");
+ context.put("check_join", "checked");
}
} catch (Exception e) {
CMS.debug(e.toString());
@@ -163,16 +164,17 @@ public class HierarchyPanel extends WizardPanelBase {
}
if (select.equals("root")) {
- config.putString("preop.hierarchy.select", "root");
- config.putString("hierarchy.select", "Root");
+ config.putString("preop.hierarchy.select", "root");
+ config.putString("hierarchy.select", "Root");
config.putString("preop.ca.type", "sdca");
try {
config.commit(false);
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
} else if (select.equals("join")) {
config.putString(PCERT_PREFIX + "signing.type", "remote");
config.putString("preop.hierarchy.select", "join");
- config.putString("hierarchy.select", "Subordinate");
+ config.putString("hierarchy.select", "Subordinate");
} else {
config.putString(PCERT_PREFIX + "signing.type", "remote");
CMS.debug("HierarchyPanel: invalid choice " + select);
@@ -187,5 +189,6 @@ public class HierarchyPanel extends WizardPanelBase {
*/
public void displayError(HttpServletRequest request,
HttpServletResponse response,
- Context context) {}
+ Context context) {
+ }
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ImportAdminCertPanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ImportAdminCertPanel.java
index d4f93a9b..991bb49b 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ImportAdminCertPanel.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ImportAdminCertPanel.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
@@ -47,19 +46,20 @@ import com.netscape.cmsutil.crypto.CryptoUtil;
public class ImportAdminCertPanel extends WizardPanelBase {
- public ImportAdminCertPanel() {}
+ public ImportAdminCertPanel() {
+ }
/**
* Initializes this panel.
*/
- public void init(ServletConfig config, int panelno)
- throws ServletException {
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
setPanelNo(panelno);
setName("Import Administrator's Certificate");
}
public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
- throws ServletException {
+ throws ServletException {
setPanelNo(panelno);
setName("Import Administrator's Certificate");
setId(id);
@@ -102,11 +102,12 @@ public class ImportAdminCertPanel extends WizardPanelBase {
try {
type = cs.getString("preop.ca.type", "");
subsystemtype = cs.getString("cs.type", "");
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
try {
String serialno = cs.getString("preop.admincert.serialno.0");
-
+
context.put("serialNumber", serialno);
} catch (Exception e) {
context.put("errorString", "Failed to get serial number.");
@@ -129,21 +130,26 @@ public class ImportAdminCertPanel extends WizardPanelBase {
if (ca == null) {
if (type.equals("otherca")) {
try {
- // this is a non-CA system that has elected to have its certificates
+ // this is a non-CA system that has elected to have its
+ // certificates
// signed by a CA outside of the security domain.
- // in this case, we submitted the cert request for the admin cert to
+ // in this case, we submitted the cert request for the admin
+ // cert to
// to security domain host.
caHost = cs.getString("securitydomain.host", "");
caPort = cs.getString("securitydomain.httpsadminport", "");
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
} else if (type.equals("sdca")) {
try {
// this is a non-CA system that submitted its certs to a CA
- // within the security domain. In this case, we submitted the cert
+ // within the security domain. In this case, we submitted
+ // the cert
// request for the admin cert to this CA
caHost = cs.getString("preop.ca.hostname", "");
caPort = cs.getString("preop.ca.httpsadminport", "");
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
}
} else {
// for CAs, we always generate our own admin certs
@@ -151,7 +157,8 @@ public class ImportAdminCertPanel extends WizardPanelBase {
try {
caHost = cs.getString("service.machineName", "");
caPort = cs.getString("pkicreate.admin_secure_port", "");
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
}
String pkcs7 = "";
@@ -192,12 +199,13 @@ public class ImportAdminCertPanel extends WizardPanelBase {
subsystemtype = cs.getString("cs.type", "");
security_domain_type = cs.getString("securitydomain.select", "");
selected_hierarchy = cs.getString("preop.hierarchy.select", "");
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
ICertificateAuthority ca = (ICertificateAuthority) CMS.getSubsystem(
ICertificateAuthority.ID);
- if (ca == null) {
+ if (ca == null) {
context.put("ca", "false");
} else {
context.put("ca", "true");
@@ -206,18 +214,18 @@ public class ImportAdminCertPanel extends WizardPanelBase {
X509CertImpl certs[] = new X509CertImpl[1];
- // REMINDER: This panel is NOT used by "clones"
- if( ca != null ) {
+ // REMINDER: This panel is NOT used by "clones"
+ if (ca != null) {
String serialno = null;
- if( selected_hierarchy.equals( "root" ) ) {
- CMS.debug( "ImportAdminCertPanel update: "
+ if (selected_hierarchy.equals("root")) {
+ CMS.debug("ImportAdminCertPanel update: "
+ "Root CA subsystem - "
- + "(new Security Domain)" );
+ + "(new Security Domain)");
} else {
- CMS.debug( "ImportAdminCertPanel update: "
+ CMS.debug("ImportAdminCertPanel update: "
+ "Subordinate CA subsystem - "
- + "(new Security Domain)" );
+ + "(new Security Domain)");
}
try {
@@ -234,35 +242,37 @@ public class ImportAdminCertPanel extends WizardPanelBase {
try {
certs[0] = repost.getX509Certificate(
new BigInteger(serialno, 16));
- } catch (Exception ee) {}
+ } catch (Exception ee) {
+ }
} else {
String dir = null;
- // REMINDER: This panel is NOT used by "clones"
- if( subsystemtype.equals( "CA" ) ) {
- if( selected_hierarchy.equals( "root" ) ) {
- CMS.debug( "ImportAdminCertPanel update: "
+ // REMINDER: This panel is NOT used by "clones"
+ if (subsystemtype.equals("CA")) {
+ if (selected_hierarchy.equals("root")) {
+ CMS.debug("ImportAdminCertPanel update: "
+ "Root CA subsystem - "
- + "(existing Security Domain)" );
+ + "(existing Security Domain)");
} else {
- CMS.debug( "ImportAdminCertPanel update: "
+ CMS.debug("ImportAdminCertPanel update: "
+ "Subordinate CA subsystem - "
- + "(existing Security Domain)" );
+ + "(existing Security Domain)");
}
} else {
- CMS.debug( "ImportAdminCertPanel update: "
+ CMS.debug("ImportAdminCertPanel update: "
+ subsystemtype
- + " subsystem" );
+ + " subsystem");
}
try {
- dir = cs.getString("preop.admincert.b64", "");
+ dir = cs.getString("preop.admincert.b64", "");
CMS.debug("ImportAdminCertPanel update: dir=" + dir);
- } catch (Exception ee) {}
+ } catch (Exception ee) {
+ }
try {
BufferedReader reader = new BufferedReader(
- new FileReader(dir));
+ new FileReader(dir));
String b64 = "";
StringBuffer sb = new StringBuffer();
@@ -289,7 +299,7 @@ public class ImportAdminCertPanel extends WizardPanelBase {
user.setX509Certificates(certs);
ug.addUserCert(user);
} catch (LDAPException e) {
- CMS.debug("ImportAdminCertPanel update: failed to add certificate to the internal database. Exception: "+e.toString());
+ CMS.debug("ImportAdminCertPanel update: failed to add certificate to the internal database. Exception: " + e.toString());
if (e.getLDAPResultCode() != LDAPException.ATTRIBUTE_OR_VALUE_EXISTS) {
context.put("updateStatus", "failure");
throw new IOException(e.toString());
@@ -312,7 +322,7 @@ public class ImportAdminCertPanel extends WizardPanelBase {
public boolean shouldSkip() {
try {
IConfigStore c = CMS.getConfigStore();
- String s = c.getString("preop.subsystem.select",null);
+ String s = c.getString("preop.subsystem.select", null);
if (s != null && s.equals("clone")) {
return true;
}
@@ -322,7 +332,6 @@ public class ImportAdminCertPanel extends WizardPanelBase {
return false;
}
-
/**
* If validiate() returns false, this method will be called.
*/
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ImportCAChainPanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ImportCAChainPanel.java
index 0c2e7fa0..a26b2dc2 100755
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ImportCAChainPanel.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ImportCAChainPanel.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.IOException;
import javax.servlet.ServletConfig;
@@ -36,19 +35,20 @@ import com.netscape.cms.servlet.wizard.WizardServlet;
public class ImportCAChainPanel extends WizardPanelBase {
- public ImportCAChainPanel() {}
+ public ImportCAChainPanel() {
+ }
/**
* Initializes this panel.
*/
- public void init(ServletConfig config, int panelno)
- throws ServletException {
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
setPanelNo(panelno);
setName("Import CA's Certificate Chain");
}
public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
- throws ServletException {
+ throws ServletException {
setPanelNo(panelno);
setName("Import CA's Certificate Chain");
setId(id);
@@ -89,7 +89,7 @@ public class ImportCAChainPanel extends WizardPanelBase {
context.put("https_port", cs.getString("pkicreate.ee_secure_port"));
context.put("http_port", cs.getString("pkicreate.unsecure_port"));
} catch (EBaseException e) {
- CMS.debug("ImportCACertChain:display: Exception: " + e.toString());
+ CMS.debug("ImportCACertChain:display: Exception: " + e.toString());
context.put("errorString", "Error loading values for Import CA Certificate Panel");
}
@@ -119,7 +119,6 @@ public class ImportCAChainPanel extends WizardPanelBase {
Context context) throws IOException {
IConfigStore cs = CMS.getConfigStore();
-
context.put("errorString", "");
context.put("title", "Import CA's Certificate Chain");
context.put("panel", "admin/console/config/importcachainpanel.vm");
@@ -141,6 +140,7 @@ public class ImportCAChainPanel extends WizardPanelBase {
context.put("http_port", cs.getString("pkicreate.unsecure_port"));
context.put("title", "Import CA's Certificate Chain");
context.put("panel", "admin/console/config/importcachainpanel.vm");
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ImportTransportCert.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ImportTransportCert.java
index 3f54ec1c..2cfc6cad 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ImportTransportCert.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ImportTransportCert.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.IOException;
import java.util.Locale;
@@ -61,6 +60,7 @@ public class ImportTransportCert extends CMSServlet {
/**
* initialize the servlet.
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -70,7 +70,7 @@ public class ImportTransportCert extends CMSServlet {
}
/**
- * Process the HTTP request.
+ * Process the HTTP request.
*/
protected void process(CMSRequest cmsReq) throws EBaseException {
CMS.debug("UpdateUpdater: processing...");
@@ -84,9 +84,9 @@ public class ImportTransportCert extends CMSServlet {
CMS.debug("ImportTransportCert authentication successful.");
} catch (Exception e) {
CMS.debug("ImportTransportCert: authentication failed.");
- log(ILogger.LL_FAILURE,
+ log(ILogger.LL_FAILURE,
CMS.getLogMessage("CMSGW_ERR_BAD_SERV_OUT_STREAM", "",
- e.toString()));
+ e.toString()));
outputError(httpResp, AUTH_FAILURE, "Error: Not authenticated");
return;
}
@@ -99,19 +99,19 @@ public class ImportTransportCert extends CMSServlet {
AuthzToken authzToken = null;
try {
- authzToken = authorize(mAclMethod, authToken, mAuthzResourceName,
- "modify");
+ authzToken = authorize(mAclMethod, authToken, mAuthzResourceName,
+ "modify");
CMS.debug("ImportTransportCert authorization successful.");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
outputError(httpResp, "Error: Not authorized");
return;
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
outputError(httpResp,
- "Error: Encountered problem during authorization.");
+ "Error: Encountered problem during authorization.");
return;
}
@@ -126,17 +126,17 @@ public class ImportTransportCert extends CMSServlet {
String certsString = httpReq.getParameter("certificate");
try {
- CryptoManager cm = CryptoManager.getInstance();
- CMS.debug("ImportTransportCert: Importing certificate");
- org.mozilla.jss.crypto.X509Certificate cert =
- cm.importCACertPackage(CMS.AtoB(certsString));
- String nickName = cert.getNickname();
- CMS.debug("ImportTransportCert: nickname " + nickName);
- cs.putString("tks.drm_transport_cert_nickname", nickName);
- CMS.debug("ImportTransportCert: Commiting configuration");
- cs.commit(false);
-
- // send success status back to the requestor
+ CryptoManager cm = CryptoManager.getInstance();
+ CMS.debug("ImportTransportCert: Importing certificate");
+ org.mozilla.jss.crypto.X509Certificate cert =
+ cm.importCACertPackage(CMS.AtoB(certsString));
+ String nickName = cert.getNickname();
+ CMS.debug("ImportTransportCert: nickname " + nickName);
+ cs.putString("tks.drm_transport_cert_nickname", nickName);
+ CMS.debug("ImportTransportCert: Commiting configuration");
+ cs.commit(false);
+
+ // send success status back to the requestor
CMS.debug("ImportTransportCert: Sending response");
XMLObject xmlObj = new XMLObject();
Node root = xmlObj.createRoot("XMLResponse");
@@ -150,14 +150,23 @@ public class ImportTransportCert extends CMSServlet {
}
}
- protected void setDefaultTemplates(ServletConfig sc) {}
+ protected void setDefaultTemplates(ServletConfig sc) {
+ }
protected void renderTemplate(
CMSRequest cmsReq, String templateName, ICMSTemplateFiller filler)
- throws IOException {// do nothing
- }
+ throws IOException {// do nothing
+ }
- protected void renderResult(CMSRequest cmsReq) throws IOException {// do nothing, ie, it will not return the default javascript.
+ protected void renderResult(CMSRequest cmsReq) throws IOException {// do
+ // nothing,
+ // ie, it
+ // will
+ // not
+ // return
+ // the
+ // default
+ // javascript.
}
/**
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/LDAPSecurityDomainSessionTable.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/LDAPSecurityDomainSessionTable.java
index a421302b..d661a318 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/LDAPSecurityDomainSessionTable.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/LDAPSecurityDomainSessionTable.java
@@ -36,11 +36,11 @@ import com.netscape.certsrv.base.ISecurityDomainSessionTable;
import com.netscape.cmsutil.password.IPasswordStore;
/**
- * This object stores the values for IP, uid and group based on the cookie id in LDAP.
- * Entries are stored under ou=Security Domain, ou=sessions, $basedn
+ * This object stores the values for IP, uid and group based on the cookie id in
+ * LDAP. Entries are stored under ou=Security Domain, ou=sessions, $basedn
*/
-public class LDAPSecurityDomainSessionTable
- implements ISecurityDomainSessionTable {
+public class LDAPSecurityDomainSessionTable
+ implements ISecurityDomainSessionTable {
private long m_timeToLive;
@@ -48,8 +48,8 @@ public class LDAPSecurityDomainSessionTable
m_timeToLive = timeToLive;
}
- public int addEntry(String sessionId, String ip,
- String uid, String group) {
+ public int addEntry(String sessionId, String ip,
+ String uid, String group) {
IConfigStore cs = CMS.getConfigStore();
LDAPConnection conn = null;
boolean sessions_exists = true;
@@ -77,14 +77,14 @@ public class LDAPSecurityDomainSessionTable
attrs.add(new LDAPAttribute("ou", "sessions"));
entry = new LDAPEntry(sessionsdn, attrs);
conn.add(entry);
- } catch (Exception e) {
+ } catch (Exception e) {
if ((e instanceof LDAPException) && (((LDAPException) e).getLDAPResultCode() == LDAPException.ENTRY_ALREADY_EXISTS)) {
// continue
} else {
CMS.debug("SecurityDomainSessionTable: unable to create ou=sessions:" + e);
sessions_exists = false;
}
- }
+ }
// add new entry
try {
@@ -106,9 +106,9 @@ public class LDAPSecurityDomainSessionTable
CMS.debug("SecurityDomainSessionTable: added session entry" + sessionId);
status = SUCCESS;
}
- } catch(Exception e) {
+ } catch (Exception e) {
CMS.debug("SecurityDomainSessionTable: unable to create session entry" + sessionId + ": " + e);
- }
+ }
try {
conn.disconnect();
@@ -155,8 +155,9 @@ public class LDAPSecurityDomainSessionTable
conn = getLDAPConn();
LDAPSearchResults res = conn.search(sessionsdn, LDAPv2.SCOPE_SUB, filter, attrs, false);
- if (res.getCount() > 0) ret = true;
- } catch(Exception e) {
+ if (res.getCount() > 0)
+ ret = true;
+ } catch (Exception e) {
CMS.debug("SecurityDomainSessionTable: unable to query session " + sessionId + ": " + e);
}
@@ -168,7 +169,6 @@ public class LDAPSecurityDomainSessionTable
return ret;
}
-
public Enumeration<String> getSessionIds() {
IConfigStore cs = CMS.getConfigStore();
LDAPConnection conn = null;
@@ -188,13 +188,13 @@ public class LDAPSecurityDomainSessionTable
}
} catch (LDAPException e) {
switch (e.getLDAPResultCode()) {
- case LDAPException.NO_SUCH_OBJECT:
- CMS.debug("SecurityDomainSessionTable: getSessionIds(): no sessions have been created");
- break;
- default:
- CMS.debug("SecurityDomainSessionTable: unable to query sessionIds due to ldap exception: " + e);
+ case LDAPException.NO_SUCH_OBJECT:
+ CMS.debug("SecurityDomainSessionTable: getSessionIds(): no sessions have been created");
+ break;
+ default:
+ CMS.debug("SecurityDomainSessionTable: unable to query sessionIds due to ldap exception: " + e);
}
- } catch(Exception e) {
+ } catch (Exception e) {
CMS.debug("SecurityDomainSessionTable: unable to query sessionIds: " + e);
}
@@ -211,18 +211,18 @@ public class LDAPSecurityDomainSessionTable
IConfigStore cs = CMS.getConfigStore();
LDAPConnection conn = null;
String ret = null;
- try {
+ try {
String basedn = cs.getString("internaldb.basedn");
String sessionsdn = "ou=sessions,ou=Security Domain," + basedn;
String filter = "(cn=" + sessionId + ")";
String[] attrs = { attr };
conn = getLDAPConn();
LDAPSearchResults res = conn.search(sessionsdn, LDAPv2.SCOPE_SUB, filter, attrs, false);
- if (res.getCount() > 0) {
+ if (res.getCount() > 0) {
LDAPEntry entry = res.next();
ret = entry.getAttribute(attr).getStringValueArray()[0];
}
- } catch(Exception e) {
+ } catch (Exception e) {
CMS.debug("SecurityDomainSessionTable: unable to query session " + sessionId + ": " + e);
}
@@ -261,7 +261,7 @@ public class LDAPSecurityDomainSessionTable
public int getSize() {
IConfigStore cs = CMS.getConfigStore();
LDAPConnection conn = null;
- int ret =0;
+ int ret = 0;
try {
String basedn = cs.getString("internaldb.basedn");
@@ -272,7 +272,7 @@ public class LDAPSecurityDomainSessionTable
conn = getLDAPConn();
LDAPSearchResults res = conn.search(sessionsdn, LDAPv2.SCOPE_SUB, filter, attrs, false);
ret = res.getCount();
- } catch(Exception e) {
+ } catch (Exception e) {
CMS.debug("SecurityDomainSessionTable: unable to query sessionIds: " + e);
}
@@ -286,8 +286,7 @@ public class LDAPSecurityDomainSessionTable
}
private LDAPConnection getLDAPConn()
- throws IOException
- {
+ throws IOException {
IConfigStore cs = CMS.getConfigStore();
String host = "";
@@ -299,12 +298,12 @@ public class LDAPSecurityDomainSessionTable
IPasswordStore pwdStore = CMS.getPasswordStore();
if (pwdStore != null) {
- //CMS.debug("SecurityDomainSessionTable: getLDAPConn: password store available");
+ // CMS.debug("SecurityDomainSessionTable: getLDAPConn: password store available");
pwd = pwdStore.getPassword("internaldb");
}
- if ( pwd == null) {
- throw new IOException("SecurityDomainSessionTable: Failed to obtain password from password store");
+ if (pwd == null) {
+ throw new IOException("SecurityDomainSessionTable: Failed to obtain password from password store");
}
try {
@@ -329,14 +328,15 @@ public class LDAPSecurityDomainSessionTable
LDAPConnection conn = null;
if (security.equals("true")) {
- //CMS.debug("SecurityDomainSessionTable getLDAPConn: creating secure (SSL) connection for internal ldap");
- conn = new LDAPConnection(CMS.getLdapJssSSLSocketFactory());
+ // CMS.debug("SecurityDomainSessionTable getLDAPConn: creating secure (SSL) connection for internal ldap");
+ conn = new LDAPConnection(CMS.getLdapJssSSLSocketFactory());
} else {
- //CMS.debug("SecurityDomainSessionTable getLDAPConn: creating non-secure (non-SSL) connection for internal ldap");
- conn = new LDAPConnection();
+ // CMS.debug("SecurityDomainSessionTable getLDAPConn: creating non-secure (non-SSL) connection for internal ldap");
+ conn = new LDAPConnection();
}
- //CMS.debug("SecurityDomainSessionTable connecting to " + host + ":" + p);
+ // CMS.debug("SecurityDomainSessionTable connecting to " + host + ":" +
+ // p);
try {
conn.connect(host, p, binddn, pwd);
} catch (LDAPException e) {
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/LoginServlet.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/LoginServlet.java
index e7fdbe3f..713cb170 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/LoginServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/LoginServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -27,7 +26,6 @@ import org.apache.velocity.context.Context;
import com.netscape.certsrv.apps.CMS;
-
public class LoginServlet extends BaseServlet {
/**
@@ -52,7 +50,7 @@ public class LoginServlet extends BaseServlet {
if (pin == null) {
context.put("error", "");
} else {
- String cspin = CMS.getConfigStore().getString("preop.pin");
+ String cspin = CMS.getConfigStore().getString("preop.pin");
if (cspin != null && cspin.equals(pin)) {
// create session
@@ -62,7 +60,7 @@ public class LoginServlet extends BaseServlet {
return null;
} else {
context.put("error", "Login Failed");
- }
+ }
}
template = Velocity.getTemplate("admin/console/config/login.vm");
} catch (Exception e) {
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/MainPageServlet.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/MainPageServlet.java
index a91ca979..2c68ee02 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/MainPageServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/MainPageServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.IOException;
import java.util.Locale;
@@ -43,7 +42,7 @@ public class MainPageServlet extends CMSServlet {
*
*/
private static final long serialVersionUID = 2425301522251239666L;
- private static final String PROP_AUTHORITY_ID="authorityId";
+ private static final String PROP_AUTHORITY_ID = "authorityId";
private String mAuthorityId = null;
private String mFormPath = null;
@@ -75,12 +74,12 @@ public class MainPageServlet extends CMSServlet {
form = getTemplate(mFormPath, request, locale);
} catch (IOException e) {
CMS.debug("MainPageServlet process: cant locate the form");
-/*
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", e.toString()));
- throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
-*/
+ /*
+ * log(ILogger.LL_FAILURE,
+ * CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", e.toString())); throw
+ * new ECMSGWException(
+ * CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ */
}
process(argSet, header, ctx, request, response);
@@ -90,21 +89,21 @@ public class MainPageServlet extends CMSServlet {
ServletOutputStream out = response.getOutputStream();
cmsReq.setStatus(CMSRequest.SUCCESS);
- response.setContentType("text/html");
- form.renderOutput(out, argSet);
+ response.setContentType("text/html");
+ form.renderOutput(out, argSet);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_OUT_STREAM_TEMPLATE", e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_OUT_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
}
private void process(CMSTemplateParams argSet, IArgBlock header,
- IArgBlock ctx, HttpServletRequest req, HttpServletResponse resp)
- throws EBaseException {
+ IArgBlock ctx, HttpServletRequest req, HttpServletResponse resp)
+ throws EBaseException {
- int num = 0;
+ int num = 0;
IArgBlock rarg = null;
IConfigStore cs = CMS.getConfigStore();
int state = 0;
@@ -125,8 +124,8 @@ public class MainPageServlet extends CMSServlet {
rarg = CMS.createArgBlock();
rarg.addStringValue("type", "admin");
rarg.addStringValue("prefix", "http");
- rarg.addIntegerValue("port",
- Integer.valueOf(CMS.getEENonSSLPort()).intValue());
+ rarg.addIntegerValue("port",
+ Integer.valueOf(CMS.getEENonSSLPort()).intValue());
rarg.addStringValue("host", host);
rarg.addStringValue("uri", adminInterface);
argSet.addRepeatRecord(rarg);
@@ -136,8 +135,8 @@ public class MainPageServlet extends CMSServlet {
rarg = CMS.createArgBlock();
rarg.addStringValue("type", "ee");
rarg.addStringValue("prefix", "https");
- rarg.addIntegerValue("port",
- Integer.valueOf(CMS.getEESSLPort()).intValue());
+ rarg.addIntegerValue("port",
+ Integer.valueOf(CMS.getEESSLPort()).intValue());
rarg.addStringValue("host", host);
rarg.addStringValue("uri", eeInterface);
argSet.addRepeatRecord(rarg);
@@ -147,8 +146,8 @@ public class MainPageServlet extends CMSServlet {
rarg = CMS.createArgBlock();
rarg.addStringValue("type", "agent");
rarg.addStringValue("prefix", "https");
- rarg.addIntegerValue("port",
- Integer.valueOf(CMS.getAgentPort()).intValue());
+ rarg.addIntegerValue("port",
+ Integer.valueOf(CMS.getAgentPort()).intValue());
rarg.addStringValue("host", host);
rarg.addStringValue("uri", agentInterface);
argSet.addRepeatRecord(rarg);
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ModulePanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ModulePanel.java
index 38185a33..e98df72a 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ModulePanel.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ModulePanel.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
@@ -50,19 +49,21 @@ public class ModulePanel extends WizardPanelBase {
private Vector mOtherModules = null;
private Hashtable mCurrModTable = new Hashtable();
private WizardServlet mServlet = null;
- public ModulePanel() {}
+
+ public ModulePanel() {
+ }
/**
* Initializes this panel.
*/
- public void init(ServletConfig config, int panelno)
- throws ServletException {
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
setPanelNo(panelno);
setName("Key Store");
}
public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
- throws ServletException {
+ throws ServletException {
setPanelNo(panelno);
setName("Key Store");
setId(id);
@@ -71,7 +72,7 @@ public class ModulePanel extends WizardPanelBase {
public void cleanUp() throws IOException {
IConfigStore cs = CMS.getConfigStore();
- cs.putBoolean("preop.ModulePanel.done",false);
+ cs.putBoolean("preop.ModulePanel.done", false);
}
public void loadCurrModTable() {
@@ -142,14 +143,14 @@ public class ModulePanel extends WizardPanelBase {
CMS.debug("ModulePanel: token logged in?" + token.isLoggedIn());
CMS.debug("ModulePanel: token is present?" + token.isPresent());
if (!token.getName().equals("Internal Crypto Services Token") &&
- !token.getName().equals("NSS Generic Crypto Services")) {
+ !token.getName().equals("NSS Generic Crypto Services")) {
module.addToken(token);
} else {
CMS.debug(
"ModulePanel: token " + token.getName()
- + " not to be added");
+ + " not to be added");
}
-
+
} catch (TokenException ex) {
CMS.debug("ModulePanel:" + ex.toString());
}
@@ -181,11 +182,11 @@ public class ModulePanel extends WizardPanelBase {
if ((cn == null) || (cn.equals(""))) {
break;
}
-
+
CMS.debug("ModulePanel: got from config module: " + cn);
// create a Module object
Module module = new Module(cn, pn, img);
-
+
if (mCurrModTable.containsKey(cn)) {
CMS.debug("ModulePanel: module found: " + cn);
module.setFound(true);
@@ -194,7 +195,7 @@ public class ModulePanel extends WizardPanelBase {
loadModTokens(module, m);
}
-
+
CMS.debug("ModulePanel: adding module " + cn);
// add module to set
if (!mSupportedModules.contains(module)) {
@@ -211,16 +212,19 @@ public class ModulePanel extends WizardPanelBase {
}
public PropertySet getUsage() {
- // it a token choice. Available tokens are discovered dynamically so
+ // it a token choice. Available tokens are discovered dynamically so
// can't be a real CHOICE
PropertySet set = new PropertySet();
-
- Descriptor tokenDesc = new Descriptor(IDescriptor.STRING, null, /* no constraint */
+
+ Descriptor tokenDesc = new Descriptor(IDescriptor.STRING, null, /*
+ * no
+ * constraint
+ */
null, /* default parameter */
"module token selection");
set.add("choice", tokenDesc);
-
+
return set;
}
@@ -235,7 +239,8 @@ public class ModulePanel extends WizardPanelBase {
} else {
return true;
}
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
return false;
}
@@ -272,8 +277,8 @@ public class ModulePanel extends WizardPanelBase {
context.put("oms", mOtherModules);
context.put("sms", mSupportedModules);
// context.put("status_token", "None");
- String subpanelno = String.valueOf(getPanelNo()+1);
- CMS.debug("ModulePanel subpanelno =" +subpanelno);
+ String subpanelno = String.valueOf(getPanelNo() + 1);
+ CMS.debug("ModulePanel subpanelno =" + subpanelno);
context.put("subpanelno", subpanelno);
context.put("panel", "admin/console/config/modulepanel.vm");
}
@@ -292,7 +297,7 @@ public class ModulePanel extends WizardPanelBase {
public void update(HttpServletRequest request,
HttpServletResponse response,
Context context) throws IOException {
- boolean hasErr = false;
+ boolean hasErr = false;
try {
// get the value of the choice
@@ -306,13 +311,13 @@ public class ModulePanel extends WizardPanelBase {
IConfigStore config = CMS.getConfigStore();
String oldtokenname = config.getString("preop.module.token", "");
- if (!oldtokenname.equals(select))
+ if (!oldtokenname.equals(select))
mServlet.cleanUpFromPanel(mServlet.getPanelNo(request));
- if (hasErr == false) {
- config.putString("preop.module.token", select);
- config.putBoolean("preop.ModulePanel.done", true);
- }
+ if (hasErr == false) {
+ config.putString("preop.module.token", select);
+ config.putBoolean("preop.ModulePanel.done", true);
+ }
config.commit(false);
context.put("updateStatus", "success");
} catch (Exception e) {
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ModuleServlet.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ModuleServlet.java
index a0a627ee..53a297e5 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ModuleServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ModuleServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -27,7 +26,6 @@ import org.apache.velocity.context.Context;
import com.netscape.certsrv.apps.CMS;
-
public class ModuleServlet extends BaseServlet {
/**
@@ -36,14 +34,12 @@ public class ModuleServlet extends BaseServlet {
private static final long serialVersionUID = 6518965840466227888L;
/**
- * Collect information on where keys are to be generated.
- * Once collected, write to CS.cfg:
- * "preop.module=soft"
- * or
- * "preop.module=hard"
- *
+ * Collect information on where keys are to be generated. Once collected,
+ * write to CS.cfg: "preop.module=soft" or "preop.module=hard"
+ *
* <ul>
- * <li>http.param selection "soft" or "hard" for software token or hardware token
+ * <li>http.param selection "soft" or "hard" for software token or hardware
+ * token
* </ul>
*/
public Template process(HttpServletRequest request,
@@ -76,7 +72,7 @@ public class ModuleServlet extends BaseServlet {
CMS.debug("ModuleServlet: illegal selection: " + selection);
context.put("error", "failed selection");
}
-
+
} else {
CMS.debug("ModuleServlet: no selection");
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/NamePanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/NamePanel.java
index ec3686e9..45239586 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/NamePanel.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/NamePanel.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@@ -54,19 +53,20 @@ public class NamePanel extends WizardPanelBase {
private Vector mCerts = null;
private WizardServlet mServlet = null;
- public NamePanel() {}
+ public NamePanel() {
+ }
/**
* Initializes this panel.
*/
- public void init(ServletConfig config, int panelno)
- throws ServletException {
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
setPanelNo(panelno);
setName("Subject Names");
}
public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
- throws ServletException {
+ throws ServletException {
setPanelNo(panelno);
setName("Subject Names");
setId(id);
@@ -79,26 +79,38 @@ public class NamePanel extends WizardPanelBase {
public PropertySet getUsage() {
PropertySet set = new PropertySet();
- Descriptor caDN = new Descriptor(IDescriptor.STRING, null, /* no constraint */
- null, /* no default parameter */
+ Descriptor caDN = new Descriptor(IDescriptor.STRING, null, /*
+ * no
+ * constraint
+ */
+ null, /* no default parameter */
"CA Signing Certificate's DN");
set.add("caDN", caDN);
- Descriptor sslDN = new Descriptor(IDescriptor.STRING, null, /* no constraint */
- null, /* no default parameter */
+ Descriptor sslDN = new Descriptor(IDescriptor.STRING, null, /*
+ * no
+ * constraint
+ */
+ null, /* no default parameter */
"SSL Server Certificate's DN");
set.add("sslDN", sslDN);
- Descriptor subsystemDN = new Descriptor(IDescriptor.STRING, null, /* no constraint */
- null, /* no default parameter */
+ Descriptor subsystemDN = new Descriptor(IDescriptor.STRING, null, /*
+ * no
+ * constraint
+ */
+ null, /* no default parameter */
"CA Subsystem Certificate's DN");
set.add("subsystemDN", subsystemDN);
- Descriptor ocspDN = new Descriptor(IDescriptor.STRING, null, /* no constraint */
- null, /* no default parameter */
+ Descriptor ocspDN = new Descriptor(IDescriptor.STRING, null, /*
+ * no
+ * constraint
+ */
+ null, /* no default parameter */
"OCSP Signing Certificate's DN");
set.add("ocspDN", ocspDN);
@@ -124,7 +136,7 @@ public class NamePanel extends WizardPanelBase {
StringTokenizer st = new StringTokenizer(list, ",");
while (st.hasMoreTokens()) {
String t = st.nextToken();
- cs.remove("preop.cert."+t+".done");
+ cs.remove("preop.cert." + t + ".done");
}
try {
@@ -142,7 +154,8 @@ public class NamePanel extends WizardPanelBase {
} else {
return true;
}
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
return false;
}
@@ -164,7 +177,7 @@ public class NamePanel extends WizardPanelBase {
CMS.debug("NamePanel: display()");
context.put("title", "Subject Names");
- // update session id
+ // update session id
String session_id = request.getParameter("session_id");
if (session_id != null) {
CMS.debug("NamePanel setting session id.");
@@ -179,16 +192,16 @@ public class NamePanel extends WizardPanelBase {
String hselect = "";
String cstype = "";
try {
- //if CA, at the hierarchy panel, was it root or subord?
+ // if CA, at the hierarchy panel, was it root or subord?
hselect = config.getString("preop.hierarchy.select", "");
select = config.getString("preop.subsystem.select", "");
cstype = config.getString("cs.type", "");
context.put("select", select);
if (cstype.equals("CA") && hselect.equals("root")) {
- CMS.debug("NamePanel ca is root");
+ CMS.debug("NamePanel ca is root");
context.put("isRoot", "true");
} else {
- CMS.debug("NamePanel not ca or not root");
+ CMS.debug("NamePanel not ca or not root");
context.put("isRoot", "false");
}
} catch (Exception e) {
@@ -227,27 +240,27 @@ public class NamePanel extends WizardPanelBase {
String type = config.getString(PCERT_PREFIX + certTag + ".type");
c.setType(type);
- boolean enable = config.getBoolean(PCERT_PREFIX+certTag+".enable", true);
+ boolean enable = config.getBoolean(PCERT_PREFIX + certTag + ".enable", true);
c.setEnable(enable);
- String cert = config.getString(subsystem +"."+certTag +".cert", "");
- String certreq =
- config.getString(subsystem + "." +certTag +".certreq", "");
+ String cert = config.getString(subsystem + "." + certTag + ".cert", "");
+ String certreq =
+ config.getString(subsystem + "." + certTag + ".certreq", "");
String dn = config.getString(PCERT_PREFIX + certTag + ".dn");
- boolean override = config.getBoolean(PCERT_PREFIX + certTag +
- ".cncomponent.override", true);
- //o_sd is to add o=secritydomainname
+ boolean override = config.getBoolean(PCERT_PREFIX + certTag +
+ ".cncomponent.override", true);
+ // o_sd is to add o=secritydomainname
boolean o_sd = config.getBoolean(PCERT_PREFIX + certTag +
- "o_securitydomain", true);
- domainname = config.getString("securitydomain.name", "");
- CMS.debug("NamePanel: display() override is "+override);
- CMS.debug("NamePanel: display() o_securitydomain is "+o_sd);
- CMS.debug("NamePanel: display() domainname is "+domainname);
+ "o_securitydomain", true);
+ domainname = config.getString("securitydomain.name", "");
+ CMS.debug("NamePanel: display() override is " + override);
+ CMS.debug("NamePanel: display() o_securitydomain is " + o_sd);
+ CMS.debug("NamePanel: display() domainname is " + domainname);
boolean dnUpdated = false;
try {
- dnUpdated = config.getBoolean(PCERT_PREFIX+certTag+".updatedDN");
+ dnUpdated = config.getBoolean(PCERT_PREFIX + certTag + ".updatedDN");
} catch (Exception e) {
}
@@ -259,16 +272,16 @@ public class NamePanel extends WizardPanelBase {
if (select.equals("clone") || dnUpdated) {
c.setDN(dn);
} else if (count != 0 && override && (cert.equals("") || certreq.equals(""))) {
- CMS.debug("NamePanel subsystemCount = "+count);
- c.setDN(dn + " "+count+
- ((!instanceId.equals(""))? (",OU=" + instanceId):"") +
- ((o_sd)? (",O=" + domainname):""));
- config.putBoolean(PCERT_PREFIX+certTag+".updatedDN", true);
+ CMS.debug("NamePanel subsystemCount = " + count);
+ c.setDN(dn + " " + count +
+ ((!instanceId.equals("")) ? (",OU=" + instanceId) : "") +
+ ((o_sd) ? (",O=" + domainname) : ""));
+ config.putBoolean(PCERT_PREFIX + certTag + ".updatedDN", true);
} else {
- c.setDN(dn +
- ((!instanceId.equals(""))? (",OU=" + instanceId):"") +
- ((o_sd)? (",O=" + domainname):""));
- config.putBoolean(PCERT_PREFIX+certTag+".updatedDN", true);
+ c.setDN(dn +
+ ((!instanceId.equals("")) ? (",OU=" + instanceId) : "") +
+ ((o_sd) ? (",O=" + domainname) : ""));
+ config.putBoolean(PCERT_PREFIX + certTag + ".updatedDN", true);
}
}
@@ -302,7 +315,8 @@ public class NamePanel extends WizardPanelBase {
try {
config.putString("preop.ca.list", list.toString());
config.commit(false);
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
context.put("urls", v);
@@ -334,24 +348,24 @@ public class NamePanel extends WizardPanelBase {
} // while
}
- /*
+ /*
* update some parameters for clones
*/
public void updateCloneConfig(IConfigStore config)
- throws EBaseException, IOException {
+ throws EBaseException, IOException {
String cstype = config.getString("cs.type", null);
cstype = toLowerCaseSubsystemType(cstype);
if (cstype.equals("kra")) {
String token = config.getString(PRE_CONF_CA_TOKEN);
if (!token.equals("Internal Key Storage Token")) {
- CMS.debug("NamePanel: updating configuration for KRA clone with hardware token");
+ CMS.debug("NamePanel: updating configuration for KRA clone with hardware token");
String subsystem = config.getString(PCERT_PREFIX + "storage.subsystem");
String storageNickname = getNickname(config, "storage");
String transportNickname = getNickname(config, "transport");
config.putString(subsystem + ".storageUnit.hardware", token);
- config.putString(subsystem + ".storageUnit.nickName", token+":"+storageNickname);
- config.putString(subsystem + ".transportUnit.nickName", token+":"+transportNickname);
+ config.putString(subsystem + ".storageUnit.nickName", token + ":" + storageNickname);
+ config.putString(subsystem + ".transportUnit.nickName", token + ":" + transportNickname);
config.commit(false);
} else { // software token
// parameters already set
@@ -361,12 +375,12 @@ public class NamePanel extends WizardPanelBase {
// audit signing cert
String audit_nn = config.getString(cstype + ".audit_signing" + ".nickname", "");
String audit_tk = config.getString(cstype + ".audit_signing" + ".tokenname", "");
- if (!audit_tk.equals("Internal Key Storage Token") && !audit_tk.equals("")) {
+ if (!audit_tk.equals("Internal Key Storage Token") && !audit_tk.equals("")) {
config.putString("log.instance.SignedAudit.signedAuditCertNickname",
- audit_tk + ":" + audit_nn);
+ audit_tk + ":" + audit_nn);
} else {
config.putString("log.instance.SignedAudit.signedAuditCertNickname",
- audit_nn);
+ audit_nn);
}
}
@@ -374,7 +388,7 @@ public class NamePanel extends WizardPanelBase {
* get some of the "preop" parameters to persisting parameters
*/
public void updateConfig(IConfigStore config, String certTag)
- throws EBaseException, IOException {
+ throws EBaseException, IOException {
String token = config.getString(PRE_CONF_CA_TOKEN);
String subsystem = config.getString(PCERT_PREFIX + certTag + ".subsystem");
CMS.debug("NamePanel: subsystem " + subsystem);
@@ -389,34 +403,35 @@ public class NamePanel extends WizardPanelBase {
config.putString(subsystem + "." + certTag + ".certnickname", nickname);
}
- // if KRA, hardware token needs param "kra.storageUnit.hardware" in CS.cfg
+ // if KRA, hardware token needs param "kra.storageUnit.hardware" in
+ // CS.cfg
String cstype = config.getString("cs.type", null);
cstype = toLowerCaseSubsystemType(cstype);
if (cstype.equals("kra")) {
- if (!token.equals("Internal Key Storage Token")) {
- if (certTag.equals("storage")) {
- config.putString(subsystem + ".storageUnit.hardware", token);
- config.putString(subsystem + ".storageUnit.nickName", token+":"+nickname);
- } else if (certTag.equals("transport")) {
- config.putString(subsystem + ".transportUnit.nickName", token+":"+nickname);
- }
- } else { // software token
- if (certTag.equals("storage")) {
- config.putString(subsystem + ".storageUnit.nickName", nickname);
- } else if (certTag.equals("transport")) {
- config.putString(subsystem + ".transportUnit.nickName", nickname);
- }
- }
+ if (!token.equals("Internal Key Storage Token")) {
+ if (certTag.equals("storage")) {
+ config.putString(subsystem + ".storageUnit.hardware", token);
+ config.putString(subsystem + ".storageUnit.nickName", token + ":" + nickname);
+ } else if (certTag.equals("transport")) {
+ config.putString(subsystem + ".transportUnit.nickName", token + ":" + nickname);
+ }
+ } else { // software token
+ if (certTag.equals("storage")) {
+ config.putString(subsystem + ".storageUnit.nickName", nickname);
+ } else if (certTag.equals("transport")) {
+ config.putString(subsystem + ".transportUnit.nickName", nickname);
+ }
+ }
}
String serverCertNickname = nickname;
String path = CMS.getConfigStore().getString("instanceRoot", "");
if (certTag.equals("sslserver")) {
- if (!token.equals("Internal Key Storage Token")) {
- serverCertNickname = token+":"+nickname;
+ if (!token.equals("Internal Key Storage Token")) {
+ serverCertNickname = token + ":" + nickname;
}
- File file = new File(path+"/conf/serverCertNick.conf");
- PrintStream ps = new PrintStream(new FileOutputStream(path+"/conf/serverCertNick.conf"));
+ File file = new File(path + "/conf/serverCertNick.conf");
+ PrintStream ps = new PrintStream(new FileOutputStream(path + "/conf/serverCertNick.conf"));
ps.println(serverCertNickname);
ps.close();
}
@@ -424,23 +439,23 @@ public class NamePanel extends WizardPanelBase {
config.putString(subsystem + "." + certTag + ".nickname", nickname);
config.putString(subsystem + "." + certTag + ".tokenname", token);
if (certTag.equals("audit_signing")) {
- if (!token.equals("Internal Key Storage Token") && !token.equals("")) {
- config.putString("log.instance.SignedAudit.signedAuditCertNickname",
- token + ":" + nickname);
- } else {
- config.putString("log.instance.SignedAudit.signedAuditCertNickname",
- nickname);
- }
+ if (!token.equals("Internal Key Storage Token") && !token.equals("")) {
+ config.putString("log.instance.SignedAudit.signedAuditCertNickname",
+ token + ":" + nickname);
+ } else {
+ config.putString("log.instance.SignedAudit.signedAuditCertNickname",
+ nickname);
+ }
}
/*
- config.putString(CERT_PREFIX + certTag + ".defaultSigningAlgorithm",
- "SHA1withRSA");
+ * config.putString(CERT_PREFIX + certTag + ".defaultSigningAlgorithm",
+ * "SHA1withRSA");
*/
// for system certs verification
- if (!token.equals("Internal Key Storage Token") && !token.equals("")) {
+ if (!token.equals("Internal Key Storage Token") && !token.equals("")) {
config.putString(subsystem + ".cert." + certTag + ".nickname",
- token + ":" + nickname);
+ token + ":" + nickname);
} else {
config.putString(subsystem + ".cert." + certTag + ".nickname", nickname);
}
@@ -459,7 +474,7 @@ public class NamePanel extends WizardPanelBase {
IConfigStore config = CMS.getConfigStore();
String caType = certObj.getType();
- CMS.debug("NamePanel: in configCert caType is "+ caType);
+ CMS.debug("NamePanel: in configCert caType is " + caType);
X509CertImpl cert = null;
String certTag = certObj.getCertTag();
@@ -469,13 +484,13 @@ public class NamePanel extends WizardPanelBase {
String v = config.getString("preop.ca.type", "");
CMS.debug("NamePanel configCert: remote CA");
- String pkcs10 = CertUtil.getPKCS10(config, PCERT_PREFIX,
- certObj, context);
+ String pkcs10 = CertUtil.getPKCS10(config, PCERT_PREFIX,
+ certObj, context);
certObj.setRequest(pkcs10);
String subsystem = config.getString(
PCERT_PREFIX + certTag + ".subsystem");
config.putString(subsystem + "." + certTag + ".certreq", pkcs10);
- String profileId = config.getString(PCERT_PREFIX+certTag+".profile");
+ String profileId = config.getString(PCERT_PREFIX + certTag + ".profile");
String session_id = CMS.getConfigSDSessionId();
String sd_hostname = "";
int sd_ee_port = -1;
@@ -483,15 +498,15 @@ public class NamePanel extends WizardPanelBase {
sd_hostname = config.getString("securitydomain.host", "");
sd_ee_port = config.getInteger("securitydomain.httpseeport", -1);
} catch (Exception ee) {
- CMS.debug("NamePanel: configCert() exception caught:"+ee.toString());
+ CMS.debug("NamePanel: configCert() exception caught:" + ee.toString());
}
String sysType = config.getString("cs.type", "");
String machineName = config.getString("machineName", "");
String securePort = config.getString("service.securePort", "");
if (certTag.equals("subsystem")) {
- String content = "requestor_name=" + sysType + "-" + machineName + "-" + securePort + "&profileId="+profileId+"&cert_request_type=pkcs10&cert_request="+URLEncoder.encode(pkcs10, "UTF-8")+"&xmlOutput=true&sessionID="+session_id;
- cert = CertUtil.createRemoteCert(sd_hostname, sd_ee_port,
- content, response, this);
+ String content = "requestor_name=" + sysType + "-" + machineName + "-" + securePort + "&profileId=" + profileId + "&cert_request_type=pkcs10&cert_request=" + URLEncoder.encode(pkcs10, "UTF-8") + "&xmlOutput=true&sessionID=" + session_id;
+ cert = CertUtil.createRemoteCert(sd_hostname, sd_ee_port,
+ content, response, this);
if (cert == null) {
throw new IOException("Error: remote certificate is null");
}
@@ -504,18 +519,18 @@ public class NamePanel extends WizardPanelBase {
} catch (Exception ee) {
}
- String content = "requestor_name=" + sysType + "-" + machineName + "-" + securePort + "&profileId="+profileId+"&cert_request_type=pkcs10&cert_request="+URLEncoder.encode(pkcs10, "UTF-8")+"&xmlOutput=true&sessionID="+session_id;
- cert = CertUtil.createRemoteCert(ca_hostname, ca_port,
- content, response, this);
+ String content = "requestor_name=" + sysType + "-" + machineName + "-" + securePort + "&profileId=" + profileId + "&cert_request_type=pkcs10&cert_request=" + URLEncoder.encode(pkcs10, "UTF-8") + "&xmlOutput=true&sessionID=" + session_id;
+ cert = CertUtil.createRemoteCert(ca_hostname, ca_port,
+ content, response, this);
if (cert == null) {
throw new IOException("Error: remote certificate is null");
}
} else if (v.equals("otherca")) {
config.putString(subsystem + "." + certTag + ".cert",
"...paste certificate here...");
- } else {
+ } else {
CMS.debug("NamePanel: no preop.ca.type is provided");
- }
+ }
} else { // not remote CA, ie, self-signed or local
ISubsystem ca = CMS.getSubsystem(ICertificateAuthority.ID);
@@ -524,76 +539,76 @@ public class NamePanel extends WizardPanelBase {
CMS.debug(
"The value for " + s
- + " should be remote, nothing else.");
+ + " should be remote, nothing else.");
throw new IOException(
"The value for " + s + " should be remote");
- }
-
+ }
+
String pubKeyType = config.getString(
PCERT_PREFIX + certTag + ".keytype");
if (pubKeyType.equals("rsa")) {
- String pubKeyModulus = config.getString(
- PCERT_PREFIX + certTag + ".pubkey.modulus");
- String pubKeyPublicExponent = config.getString(
- PCERT_PREFIX + certTag + ".pubkey.exponent");
- String subsystem = config.getString(
- PCERT_PREFIX + certTag + ".subsystem");
+ String pubKeyModulus = config.getString(
+ PCERT_PREFIX + certTag + ".pubkey.modulus");
+ String pubKeyPublicExponent = config.getString(
+ PCERT_PREFIX + certTag + ".pubkey.exponent");
+ String subsystem = config.getString(
+ PCERT_PREFIX + certTag + ".subsystem");
- if (certTag.equals("signing")) {
- X509Key x509key = CryptoUtil.getPublicX509Key(
- CryptoUtil.string2byte(pubKeyModulus),
- CryptoUtil.string2byte(pubKeyPublicExponent));
-
- cert = CertUtil.createLocalCert(config, x509key,
- PCERT_PREFIX, certTag, caType, context);
- } else {
- String cacert = config.getString("ca.signing.cert", "");
-
- if (cacert.equals("") || cacert.startsWith("...")) {
- certObj.setCert(
- "...certificate be generated internally...");
- config.putString(subsystem + "." + certTag + ".cert",
- "...certificate be generated internally...");
- } else {
+ if (certTag.equals("signing")) {
X509Key x509key = CryptoUtil.getPublicX509Key(
CryptoUtil.string2byte(pubKeyModulus),
CryptoUtil.string2byte(pubKeyPublicExponent));
cert = CertUtil.createLocalCert(config, x509key,
PCERT_PREFIX, certTag, caType, context);
+ } else {
+ String cacert = config.getString("ca.signing.cert", "");
+
+ if (cacert.equals("") || cacert.startsWith("...")) {
+ certObj.setCert(
+ "...certificate be generated internally...");
+ config.putString(subsystem + "." + certTag + ".cert",
+ "...certificate be generated internally...");
+ } else {
+ X509Key x509key = CryptoUtil.getPublicX509Key(
+ CryptoUtil.string2byte(pubKeyModulus),
+ CryptoUtil.string2byte(pubKeyPublicExponent));
+
+ cert = CertUtil.createLocalCert(config, x509key,
+ PCERT_PREFIX, certTag, caType, context);
+ }
}
- }
} else if (pubKeyType.equals("ecc")) {
- String pubKeyEncoded = config.getString(
- PCERT_PREFIX + certTag + ".pubkey.encoded");
- String subsystem = config.getString(
- PCERT_PREFIX + certTag + ".subsystem");
-
- if (certTag.equals("signing")) {
+ String pubKeyEncoded = config.getString(
+ PCERT_PREFIX + certTag + ".pubkey.encoded");
+ String subsystem = config.getString(
+ PCERT_PREFIX + certTag + ".subsystem");
- X509Key x509key = CryptoUtil.getPublicX509ECCKey(CryptoUtil.string2byte(pubKeyEncoded));
- cert = CertUtil.createLocalCert(config, x509key,
- PCERT_PREFIX, certTag, caType, context);
- } else {
- String cacert = config.getString("ca.signing.cert", "");
-
- if (cacert.equals("") || cacert.startsWith("...")) {
- certObj.setCert(
- "...certificate be generated internally...");
- config.putString(subsystem + "." + certTag + ".cert",
- "...certificate be generated internally...");
- } else {
- X509Key x509key = CryptoUtil.getPublicX509ECCKey(
- CryptoUtil.string2byte(pubKeyEncoded));
+ if (certTag.equals("signing")) {
+ X509Key x509key = CryptoUtil.getPublicX509ECCKey(CryptoUtil.string2byte(pubKeyEncoded));
cert = CertUtil.createLocalCert(config, x509key,
PCERT_PREFIX, certTag, caType, context);
+ } else {
+ String cacert = config.getString("ca.signing.cert", "");
+
+ if (cacert.equals("") || cacert.startsWith("...")) {
+ certObj.setCert(
+ "...certificate be generated internally...");
+ config.putString(subsystem + "." + certTag + ".cert",
+ "...certificate be generated internally...");
+ } else {
+ X509Key x509key = CryptoUtil.getPublicX509ECCKey(
+ CryptoUtil.string2byte(pubKeyEncoded));
+
+ cert = CertUtil.createLocalCert(config, x509key,
+ PCERT_PREFIX, certTag, caType, context);
+ }
}
- }
} else {
- // invalid key type
- CMS.debug("Invalid key type " + pubKeyType);
+ // invalid key type
+ CMS.debug("Invalid key type " + pubKeyType);
}
if (cert != null) {
if (certTag.equals("subsystem"))
@@ -605,7 +620,7 @@ public class NamePanel extends WizardPanelBase {
byte[] certb = cert.getEncoded();
String certs = CryptoUtil.base64Encode(certb);
- // certObj.setCert(certs);
+ // certObj.setCert(certs);
String subsystem = config.getString(
PCERT_PREFIX + certTag + ".subsystem");
config.putString(subsystem + "." + certTag + ".cert", certs);
@@ -617,58 +632,57 @@ public class NamePanel extends WizardPanelBase {
CMS.debug("NamePanel configCert() exception caught:" + e.toString());
}
}
-
+
public void configCertWithTag(HttpServletRequest request,
HttpServletResponse response,
- Context context, String tag) throws IOException
- {
- CMS.debug("NamePanel: configCertWithTag start");
- Enumeration c = mCerts.elements();
- IConfigStore config = CMS.getConfigStore();
-
- while (c.hasMoreElements()) {
- Cert cert = (Cert) c.nextElement();
- String ct = cert.getCertTag();
- CMS.debug("NamePanel: configCertWithTag ct=" + ct +
- " tag=" +tag);
- if (ct.equals(tag)) {
- try {
- String nickname = HttpInput.getNickname(request, ct + "_nick");
- if (nickname != null) {
- CMS.debug("configCertWithTag: Setting nickname for " + ct + " to " + nickname);
- config.putString(PCERT_PREFIX + ct + ".nickname", nickname);
- cert.setNickname(nickname);
- config.commit(false);
- }
- String dn = HttpInput.getDN(request, ct);
- if (dn != null) {
- config.putString(PCERT_PREFIX + ct + ".dn", dn);
- config.commit(false);
- }
- } catch (Exception e) {
- CMS.debug("NamePanel: configCertWithTag: Exception in setting nickname for " + ct + ": " + e.toString());
- }
+ Context context, String tag) throws IOException {
+ CMS.debug("NamePanel: configCertWithTag start");
+ Enumeration c = mCerts.elements();
+ IConfigStore config = CMS.getConfigStore();
- configCert(request, response, context, cert);
- CMS.debug("NamePanel: configCertWithTag done with tag=" + tag);
- return;
+ while (c.hasMoreElements()) {
+ Cert cert = (Cert) c.nextElement();
+ String ct = cert.getCertTag();
+ CMS.debug("NamePanel: configCertWithTag ct=" + ct +
+ " tag=" + tag);
+ if (ct.equals(tag)) {
+ try {
+ String nickname = HttpInput.getNickname(request, ct + "_nick");
+ if (nickname != null) {
+ CMS.debug("configCertWithTag: Setting nickname for " + ct + " to " + nickname);
+ config.putString(PCERT_PREFIX + ct + ".nickname", nickname);
+ cert.setNickname(nickname);
+ config.commit(false);
+ }
+ String dn = HttpInput.getDN(request, ct);
+ if (dn != null) {
+ config.putString(PCERT_PREFIX + ct + ".dn", dn);
+ config.commit(false);
+ }
+ } catch (Exception e) {
+ CMS.debug("NamePanel: configCertWithTag: Exception in setting nickname for " + ct + ": " + e.toString());
}
- }
- CMS.debug("NamePanel: configCertWithTag done");
+
+ configCert(request, response, context, cert);
+ CMS.debug("NamePanel: configCertWithTag done with tag=" + tag);
+ return;
+ }
+ }
+ CMS.debug("NamePanel: configCertWithTag done");
}
private boolean inputChanged(HttpServletRequest request)
- throws IOException {
- IConfigStore config = CMS.getConfigStore();
-
+ throws IOException {
+ IConfigStore config = CMS.getConfigStore();
+
boolean hasChanged = false;
try {
Enumeration c = mCerts.elements();
while (c.hasMoreElements()) {
Cert cert = (Cert) c.nextElement();
- String ct = cert.getCertTag();
- boolean enable = config.getBoolean(PCERT_PREFIX+ct+".enable", true);
+ String ct = cert.getCertTag();
+ boolean enable = config.getBoolean(PCERT_PREFIX + ct + ".enable", true);
if (!enable)
continue;
@@ -679,10 +693,10 @@ public class NamePanel extends WizardPanelBase {
if (!olddn.equals(dn))
hasChanged = true;
- String oldnick = config.getString(PCERT_PREFIX + ct + ".nickname");
- String nick = HttpInput.getNickname(request, ct + "_nick");
- if (!oldnick.equals(nick))
- hasChanged = true;
+ String oldnick = config.getString(PCERT_PREFIX + ct + ".nickname");
+ String nick = HttpInput.getNickname(request, ct + "_nick");
+ if (!oldnick.equals(nick))
+ hasChanged = true;
}
} catch (Exception e) {
@@ -690,34 +704,34 @@ public class NamePanel extends WizardPanelBase {
return hasChanged;
}
-
- public String getURL(HttpServletRequest request, IConfigStore config)
- {
+
+ public String getURL(HttpServletRequest request, IConfigStore config) {
String index = request.getParameter("urls");
- if (index == null){
- return null;
+ if (index == null) {
+ return null;
}
String url = "";
if (index.startsWith("http")) {
- // user may submit url directlry
- url = index;
+ // user may submit url directlry
+ url = index;
} else {
- try {
- int x = Integer.parseInt(index);
- String list = config.getString("preop.ca.list", "");
- StringTokenizer tokenizer = new StringTokenizer(list, ",");
- int counter = 0;
-
- while (tokenizer.hasMoreTokens()) {
- url = tokenizer.nextToken();
- if (counter == x) {
- break;
+ try {
+ int x = Integer.parseInt(index);
+ String list = config.getString("preop.ca.list", "");
+ StringTokenizer tokenizer = new StringTokenizer(list, ",");
+ int counter = 0;
+
+ while (tokenizer.hasMoreTokens()) {
+ url = tokenizer.nextToken();
+ if (counter == x) {
+ break;
+ }
+ counter++;
}
- counter++;
+ } catch (Exception e) {
}
- } catch (Exception e) {}
}
- return url;
+ return url;
}
/**
@@ -727,7 +741,7 @@ public class NamePanel extends WizardPanelBase {
HttpServletResponse response,
Context context) throws IOException {
CMS.debug("NamePanel: in update()");
- boolean hasErr = false;
+ boolean hasErr = false;
if (inputChanged(request)) {
mServlet.cleanUpFromPanel(mServlet.getPanelNo(request));
@@ -736,12 +750,12 @@ public class NamePanel extends WizardPanelBase {
return;
}
- IConfigStore config = CMS.getConfigStore();
+ IConfigStore config = CMS.getConfigStore();
String hselect = "";
ISubsystem subsystem = CMS.getSubsystem(ICertificateAuthority.ID);
try {
- //if CA, at the hierarchy panel, was it root or subord?
+ // if CA, at the hierarchy panel, was it root or subord?
hselect = config.getString("preop.hierarchy.select", "");
String cstype = config.getString("preop.subsystem.select", "");
if (cstype.equals("clone")) {
@@ -750,13 +764,14 @@ public class NamePanel extends WizardPanelBase {
configCertWithTag(request, response, context, "sslserver");
String url = getURL(request, config);
if (url != null && !url.equals("External CA")) {
- // preop.ca.url and admin port are required for setting KRA connector
- url = url.substring(url.indexOf("https"));
- config.putString("preop.ca.url", url);
+ // preop.ca.url and admin port are required for setting KRA
+ // connector
+ url = url.substring(url.indexOf("https"));
+ config.putString("preop.ca.url", url);
- URL urlx = new URL(url);
- updateCloneSDCAInfo(request, context, urlx.getHost(),
- Integer.toString(urlx.getPort()));
+ URL urlx = new URL(url);
+ updateCloneSDCAInfo(request, context, urlx.getHost(),
+ Integer.toString(urlx.getPort()));
}
updateCloneConfig(config);
@@ -770,50 +785,51 @@ public class NamePanel extends WizardPanelBase {
return;
}
- //if no hselect, then not CA
- if (hselect.equals("") || hselect.equals("join")) {
- String select = null;
- String url = getURL(request, config);
+ // if no hselect, then not CA
+ if (hselect.equals("") || hselect.equals("join")) {
+ String select = null;
+ String url = getURL(request, config);
- URL urlx = null;
+ URL urlx = null;
- if (url.equals("External CA")) {
- CMS.debug("NamePanel: external CA selected");
- select = "otherca";
- config.putString("preop.ca.type", "otherca");
- if (subsystem != null) {
- config.putString(PCERT_PREFIX+"signing.type", "remote");
- }
+ if (url.equals("External CA")) {
+ CMS.debug("NamePanel: external CA selected");
+ select = "otherca";
+ config.putString("preop.ca.type", "otherca");
+ if (subsystem != null) {
+ config.putString(PCERT_PREFIX + "signing.type", "remote");
+ }
- config.putString("preop.ca.pkcs7", "");
- config.putInteger("preop.ca.certchain.size", 0);
- context.put("check_otherca", "checked");
- CMS.debug("NamePanel: update: this is the external CA.");
- } else {
- CMS.debug("NamePanel: local CA selected");
- select = "sdca";
- // parse URL (CA1 - https://...)
- url = url.substring(url.indexOf("https"));
- config.putString("preop.ca.url", url);
-
- urlx = new URL(url);
- config.putString("preop.ca.type", "sdca");
- CMS.debug("NamePanel: update: this is a CA in the security domain.");
- context.put("check_sdca", "checked");
- sdca(request, context, urlx.getHost(),
- Integer.toString(urlx.getPort()));
- if (subsystem != null) {
- config.putString(PCERT_PREFIX + "signing.type", "remote");
- config.putString(PCERT_PREFIX + "signing.profile",
- "caInstallCACert");
+ config.putString("preop.ca.pkcs7", "");
+ config.putInteger("preop.ca.certchain.size", 0);
+ context.put("check_otherca", "checked");
+ CMS.debug("NamePanel: update: this is the external CA.");
+ } else {
+ CMS.debug("NamePanel: local CA selected");
+ select = "sdca";
+ // parse URL (CA1 - https://...)
+ url = url.substring(url.indexOf("https"));
+ config.putString("preop.ca.url", url);
+
+ urlx = new URL(url);
+ config.putString("preop.ca.type", "sdca");
+ CMS.debug("NamePanel: update: this is a CA in the security domain.");
+ context.put("check_sdca", "checked");
+ sdca(request, context, urlx.getHost(),
+ Integer.toString(urlx.getPort()));
+ if (subsystem != null) {
+ config.putString(PCERT_PREFIX + "signing.type", "remote");
+ config.putString(PCERT_PREFIX + "signing.profile",
+ "caInstallCACert");
+ }
}
- }
- try {
- config.commit(false);
- } catch (Exception e) {}
+ try {
+ config.commit(false);
+ } catch (Exception e) {
+ }
- }
+ }
try {
@@ -821,13 +837,13 @@ public class NamePanel extends WizardPanelBase {
while (c.hasMoreElements()) {
Cert cert = (Cert) c.nextElement();
- String ct = cert.getCertTag();
+ String ct = cert.getCertTag();
String tokenname = cert.getTokenname();
- boolean enable = config.getBoolean(PCERT_PREFIX+ct+".enable", true);
+ boolean enable = config.getBoolean(PCERT_PREFIX + ct + ".enable", true);
if (!enable)
continue;
- boolean certDone = config.getBoolean(PCERT_PREFIX+ct+".done", false);
+ boolean certDone = config.getBoolean(PCERT_PREFIX + ct + ".done", false);
if (certDone)
continue;
@@ -850,32 +866,32 @@ public class NamePanel extends WizardPanelBase {
try {
configCert(request, response, context, cert);
- config.putBoolean("preop.cert."+cert.getCertTag()+".done",
- true);
+ config.putBoolean("preop.cert." + cert.getCertTag() + ".done",
+ true);
config.commit(false);
} catch (Exception e) {
CMS.debug(
"NamePanel: update() exception caught:"
+ e.toString());
- hasErr = true;
+ hasErr = true;
System.err.println("Exception caught: " + e.toString());
}
- } // while
- if (hasErr == false) {
- config.putBoolean("preop.NamePanel.done", true);
- config.commit(false);
- }
+ } // while
+ if (hasErr == false) {
+ config.putBoolean("preop.NamePanel.done", true);
+ config.commit(false);
+ }
} catch (Exception e) {
CMS.debug("NamePanel: Exception caught: " + e.toString());
System.err.println("Exception caught: " + e.toString());
}// try
-
try {
config.commit(false);
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
if (!hasErr) {
context.put("updateStatus", "success");
@@ -897,15 +913,15 @@ public class NamePanel extends WizardPanelBase {
// Retrieve the associated HTTPS Admin port so that it
// may be stored for use with ImportAdminCertPanel
- https_admin_port = getSecurityDomainAdminPort( config,
+ https_admin_port = getSecurityDomainAdminPort(config,
hostname,
httpsPortStr,
- "CA" );
+ "CA");
int httpsport = -1;
try {
- httpsport = Integer.parseInt(httpsPortStr);
+ httpsport = Integer.parseInt(httpsPortStr);
} catch (Exception e) {
CMS.debug(
"NamePanel update: Https port is not valid. Exception: "
@@ -934,15 +950,15 @@ public class NamePanel extends WizardPanelBase {
// Retrieve the associated HTTPS Admin port so that it
// may be stored for use with ImportAdminCertPanel
- https_admin_port = getSecurityDomainAdminPort( config,
+ https_admin_port = getSecurityDomainAdminPort(config,
hostname,
httpsPortStr,
- "CA" );
+ "CA");
int httpsport = -1;
try {
- httpsport = Integer.parseInt(httpsPortStr);
+ httpsport = Integer.parseInt(httpsPortStr);
} catch (Exception e) {
CMS.debug(
"NamePanel update: Https port is not valid. Exception: "
@@ -954,21 +970,19 @@ public class NamePanel extends WizardPanelBase {
config.putString("preop.ca.httpsport", httpsPortStr);
config.putString("preop.ca.httpsadminport", https_admin_port);
ConfigCertApprovalCallback certApprovalCallback = new ConfigCertApprovalCallback();
- updateCertChainUsingSecureEEPort( config, "ca", hostname,
+ updateCertChainUsingSecureEEPort(config, "ca", hostname,
httpsport, true, context,
- certApprovalCallback );
+ certApprovalCallback);
try {
- CMS.debug("Importing CA chain");
- importCertChain("ca");
+ CMS.debug("Importing CA chain");
+ importCertChain("ca");
} catch (Exception e1) {
- CMS.debug("Failed in importing CA chain");
+ CMS.debug("Failed in importing CA chain");
}
}
-
public void initParams(HttpServletRequest request, Context context)
- throws IOException
- {
+ throws IOException {
context.put("certs", mCerts);
}
@@ -977,10 +991,9 @@ public class NamePanel extends WizardPanelBase {
*/
public void displayError(HttpServletRequest request,
HttpServletResponse response,
- Context context)
- {
+ Context context) {
try {
- initParams(request, context);
+ initParams(request, context);
} catch (IOException e) {
}
context.put("title", "Subject Names");
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/RegisterUser.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/RegisterUser.java
index cf37fdff..28fdfd84 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/RegisterUser.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/RegisterUser.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.IOException;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
@@ -50,11 +49,9 @@ import com.netscape.cms.servlet.common.ICMSTemplateFiller;
import com.netscape.cmsutil.xml.XMLObject;
/**
- * This servlet creates a TPS user in the CA,
- * and it associates TPS's server certificate to
- * the user. Finally, it addes the user to the
- * administrator group. This procedure will
- * allows TPS to connect to the CA for certificate
+ * This servlet creates a TPS user in the CA, and it associates TPS's server
+ * certificate to the user. Finally, it addes the user to the administrator
+ * group. This procedure will allows TPS to connect to the CA for certificate
* issuance.
*/
public class RegisterUser extends CMSServlet {
@@ -68,8 +65,7 @@ public class RegisterUser extends CMSServlet {
private final static String AUTH_FAILURE = "2";
private String mGroupName = null;
private final static String LOGGING_SIGNED_AUDIT_CONFIG_ROLE =
- "LOGGING_SIGNED_AUDIT_CONFIG_ROLE_3";
-
+ "LOGGING_SIGNED_AUDIT_CONFIG_ROLE_3";
public RegisterUser() {
super();
@@ -77,6 +73,7 @@ public class RegisterUser extends CMSServlet {
/**
* initialize the servlet.
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -88,7 +85,7 @@ public class RegisterUser extends CMSServlet {
}
/**
- * Process the HTTP request.
+ * Process the HTTP request.
*/
protected void process(CMSRequest cmsReq) throws EBaseException {
CMS.debug("UpdateUpdater: processing...");
@@ -102,9 +99,9 @@ public class RegisterUser extends CMSServlet {
CMS.debug("RegisterUser authentication successful.");
} catch (Exception e) {
CMS.debug("RegisterUser: authentication failed.");
- log(ILogger.LL_FAILURE,
+ log(ILogger.LL_FAILURE,
CMS.getLogMessage("CMSGW_ERR_BAD_SERV_OUT_STREAM", "",
- e.toString()));
+ e.toString()));
outputError(httpResp, AUTH_FAILURE, "Error: Not authenticated");
return;
}
@@ -117,19 +114,19 @@ public class RegisterUser extends CMSServlet {
AuthzToken authzToken = null;
try {
- authzToken = authorize(mAclMethod, authToken, mAuthzResourceName,
- "modify");
+ authzToken = authorize(mAclMethod, authToken, mAuthzResourceName,
+ "modify");
CMS.debug("RegisterUser authorization successful.");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
outputError(httpResp, "Error: Not authorized");
return;
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
outputError(httpResp,
- "Error: Encountered problem during authorization.");
+ "Error: Encountered problem during authorization.");
return;
}
@@ -150,93 +147,93 @@ public class RegisterUser extends CMSServlet {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
- String auditParams = "Scope;;users+Operation;;OP_ADD+source;;RegisterUser" +
- "+Resource;;"+ uid +
- "+fullname;;"+ name +
+ String auditParams = "Scope;;users+Operation;;OP_ADD+source;;RegisterUser" +
+ "+Resource;;" + uid +
+ "+fullname;;" + name +
"+state;;1" +
"+userType;;<null>+email;;<null>+password;;<null>+phone;;<null>";
- IUGSubsystem ugsys = (IUGSubsystem)CMS.getSubsystem(CMS.SUBSYSTEM_UG);
+ IUGSubsystem ugsys = (IUGSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_UG);
IUser user = null;
boolean foundByCert = false;
X509Certificate certs[] = new X509Certificate[1];
try {
- byte bCert[] = null;
- X509CertImpl cert = null;
- bCert = (byte[]) (com.netscape.osutil.OSUtil.AtoB(certsString));
- cert = new X509CertImpl(bCert);
- certs[0] = (X509Certificate)cert;
-
- // test to see if the cert already belongs to a user
- ICertUserLocator cul = ugsys.getCertUserLocator();
- com.netscape.certsrv.usrgrp.Certificates c =
- new com.netscape.certsrv.usrgrp.Certificates(certs);
- user = (IUser) cul.locateUser(c);
+ byte bCert[] = null;
+ X509CertImpl cert = null;
+ bCert = (byte[]) (com.netscape.osutil.OSUtil.AtoB(certsString));
+ cert = new X509CertImpl(bCert);
+ certs[0] = (X509Certificate) cert;
+
+ // test to see if the cert already belongs to a user
+ ICertUserLocator cul = ugsys.getCertUserLocator();
+ com.netscape.certsrv.usrgrp.Certificates c =
+ new com.netscape.certsrv.usrgrp.Certificates(certs);
+ user = (IUser) cul.locateUser(c);
} catch (Exception ec) {
- CMS.debug("RegisterUser: exception thrown: "+ec.toString());
+ CMS.debug("RegisterUser: exception thrown: " + ec.toString());
}
if (user == null) {
- CMS.debug("RegisterUser NOT found user by cert");
- try {
- user = ugsys.getUser(uid);
- CMS.debug("RegisterUser found user by uid "+uid);
- } catch (Exception eee) {
- }
+ CMS.debug("RegisterUser NOT found user by cert");
+ try {
+ user = ugsys.getUser(uid);
+ CMS.debug("RegisterUser found user by uid " + uid);
+ } catch (Exception eee) {
+ }
} else {
- foundByCert = true;
- CMS.debug("RegisterUser found user by cert");
+ foundByCert = true;
+ CMS.debug("RegisterUser found user by cert");
}
-
- try {
-
- if (user == null) {
- // create user only if such user does not exist
- user = ugsys.createUser(uid);
- user.setFullName(name);
- user.setState("1");
- user.setUserType("");
- user.setEmail("");
- user.setPhone("");
- user.setPassword("");
-
- ugsys.addUser(user);
- CMS.debug("RegisterUser created user " + uid);
- auditMessage = CMS.getLogMessage(
+
+ try {
+
+ if (user == null) {
+ // create user only if such user does not exist
+ user = ugsys.createUser(uid);
+ user.setFullName(name);
+ user.setState("1");
+ user.setUserType("");
+ user.setEmail("");
+ user.setPhone("");
+ user.setPassword("");
+
+ ugsys.addUser(user);
+ CMS.debug("RegisterUser created user " + uid);
+ auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
auditSubjectID,
ILogger.SUCCESS,
auditParams);
- audit(auditMessage);
- }
-
- // extract all line separators
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < certsString.length(); i++) {
- if (!Character.isWhitespace(certsString.charAt(i))) {
- sb.append(certsString.charAt(i));
- }
- }
- certsString = sb.toString();
-
- auditParams = "Scope;;certs+Operation;;OP_ADD+source;;RegisterUser" +
- "+Resource;;"+ uid +
- "+cert;;"+certsString;
-
- user.setX509Certificates(certs);
- if (!foundByCert) {
- ugsys.addUserCert(user);
- CMS.debug("RegisterUser added user certificate");
- auditMessage = CMS.getLogMessage(
+ audit(auditMessage);
+ }
+
+ // extract all line separators
+ StringBuffer sb = new StringBuffer();
+ for (int i = 0; i < certsString.length(); i++) {
+ if (!Character.isWhitespace(certsString.charAt(i))) {
+ sb.append(certsString.charAt(i));
+ }
+ }
+ certsString = sb.toString();
+
+ auditParams = "Scope;;certs+Operation;;OP_ADD+source;;RegisterUser" +
+ "+Resource;;" + uid +
+ "+cert;;" + certsString;
+
+ user.setX509Certificates(certs);
+ if (!foundByCert) {
+ ugsys.addUserCert(user);
+ CMS.debug("RegisterUser added user certificate");
+ auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
auditSubjectID,
ILogger.SUCCESS,
auditParams);
- audit(auditMessage);
- } else
- CMS.debug("RegisterUser no need to add user certificate");
- } catch (Exception eee) {
+ audit(auditMessage);
+ } else
+ CMS.debug("RegisterUser no need to add user certificate");
+ } catch (Exception eee) {
CMS.debug("RegisterUser error " + eee.toString());
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
@@ -249,20 +246,19 @@ public class RegisterUser extends CMSServlet {
return;
}
-
// add user to the group
auditParams = "Scope;;groups+Operation;;OP_MODIFY+source;;RegisterUser" +
- "+Resource;;"+ mGroupName;
+ "+Resource;;" + mGroupName;
try {
Enumeration groups = ugsys.findGroups(mGroupName);
- IGroup group = (IGroup)groups.nextElement();
+ IGroup group = (IGroup) groups.nextElement();
auditParams += "+user;;";
Enumeration members = group.getMemberNames();
while (members.hasMoreElements()) {
auditParams += (String) members.nextElement();
if (members.hasMoreElements()) {
- auditParams +=",";
+ auditParams += ",";
}
}
@@ -280,15 +276,15 @@ public class RegisterUser extends CMSServlet {
audit(auditMessage);
}
- } catch (Exception e) {
- auditMessage = CMS.getLogMessage(
+ } catch (Exception e) {
+ auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
auditSubjectID,
ILogger.FAILURE,
auditParams);
- audit(auditMessage);
- }
+ audit(auditMessage);
+ }
// send success status back to the requestor
try {
@@ -305,14 +301,23 @@ public class RegisterUser extends CMSServlet {
}
}
- protected void setDefaultTemplates(ServletConfig sc) {}
+ protected void setDefaultTemplates(ServletConfig sc) {
+ }
protected void renderTemplate(
CMSRequest cmsReq, String templateName, ICMSTemplateFiller filler)
- throws IOException {// do nothing
- }
+ throws IOException {// do nothing
+ }
- protected void renderResult(CMSRequest cmsReq) throws IOException {// do nothing, ie, it will not return the default javascript.
+ protected void renderResult(CMSRequest cmsReq) throws IOException {// do
+ // nothing,
+ // ie, it
+ // will
+ // not
+ // return
+ // the
+ // default
+ // javascript.
}
/**
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/RestoreKeyCertPanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/RestoreKeyCertPanel.java
index 76f5a749..4763f814 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/RestoreKeyCertPanel.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/RestoreKeyCertPanel.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
@@ -76,19 +75,20 @@ import com.netscape.cms.servlet.wizard.WizardServlet;
public class RestoreKeyCertPanel extends WizardPanelBase {
- public RestoreKeyCertPanel() {}
+ public RestoreKeyCertPanel() {
+ }
/**
* Initializes this panel.
*/
- public void init(ServletConfig config, int panelno)
- throws ServletException {
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
setPanelNo(panelno);
setName("Import Keys and Certificates");
}
public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
- throws ServletException {
+ throws ServletException {
setPanelNo(panelno);
setName("Import Keys and Certificates");
setId(id);
@@ -99,18 +99,18 @@ public class RestoreKeyCertPanel extends WizardPanelBase {
*/
public boolean shouldSkip() {
CMS.debug("RestoreKeyCertPanel: should skip");
-
+
IConfigStore cs = CMS.getConfigStore();
// if we are root, no need to get the certificate chain.
-
+
try {
- String select = cs.getString("preop.subsystem.select","");
+ String select = cs.getString("preop.subsystem.select", "");
if (select.equals("clone")) {
return false;
}
} catch (EBaseException e) {
}
-
+
return true;
}
@@ -138,15 +138,16 @@ public class RestoreKeyCertPanel extends WizardPanelBase {
} else {
return true;
}
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
return false;
}
public PropertySet getUsage() {
PropertySet set = new PropertySet();
-
+
/* XXX */
-
+
return set;
}
@@ -160,7 +161,7 @@ public class RestoreKeyCertPanel extends WizardPanelBase {
IConfigStore config = CMS.getConfigStore();
if (isPanelDone()) {
-
+
try {
String s = config.getString("preop.pk12.path", "");
String type = config.getString("preop.subsystem.select", "");
@@ -193,15 +194,14 @@ public class RestoreKeyCertPanel extends WizardPanelBase {
if (!tokenname.equals("Internal Key Storage Token"))
return;
- // Path can be empty. If this case, we just want to
+ // Path can be empty. If this case, we just want to
// get to the next panel. Customer has HSM.
String s = HttpInput.getString(request, "path");
// if (s == null || s.equals("")) {
- // CMS.debug("RestoreKeyCertPanel validate: path is empty");
- // throw new IOException("Path is empty");
+ // CMS.debug("RestoreKeyCertPanel validate: path is empty");
+ // throw new IOException("Path is empty");
// }
-
if (s != null && !s.equals("")) {
s = HttpInput.getPassword(request, "__password");
if (s == null || s.equals("")) {
@@ -217,15 +217,14 @@ public class RestoreKeyCertPanel extends WizardPanelBase {
*/
public void update(HttpServletRequest request,
HttpServletResponse response,
- Context context) throws IOException
- {
+ Context context) throws IOException {
IConfigStore config = CMS.getConfigStore();
String path = HttpInput.getString(request, "path");
if (path == null || path.equals("")) {
- // skip to next panel
+ // skip to next panel
config.putBoolean("preop.restorekeycert.done", true);
try {
- config.commit(false);
+ config.commit(false);
} catch (EBaseException e) {
}
getConfigEntriesFromMaster(request, response, context);
@@ -233,7 +232,7 @@ public class RestoreKeyCertPanel extends WizardPanelBase {
return;
}
String pwd = HttpInput.getPassword(request, "__password");
-
+
String tokenn = "";
String instanceRoot = "";
@@ -246,7 +245,7 @@ public class RestoreKeyCertPanel extends WizardPanelBase {
if (tokenn.equals("Internal Key Storage Token")) {
byte b[] = new byte[1000000];
FileInputStream fis = new FileInputStream(instanceRoot + "/alias/" + path);
- while (fis.available() > 0)
+ while (fis.available() > 0)
fis.read(b);
fis.close();
@@ -256,10 +255,10 @@ public class RestoreKeyCertPanel extends WizardPanelBase {
PFX pfx = null;
boolean verifypfx = false;
try {
- pfx = (PFX)(new PFX.Template()).decode(bis);
- verifypfx = pfx.verifyAuthSafes(password, reason);
+ pfx = (PFX) (new PFX.Template()).decode(bis);
+ verifypfx = pfx.verifyAuthSafes(password, reason);
} catch (Exception e) {
- CMS.debug("RestoreKeyCertPanel update: Exception="+e.toString());
+ CMS.debug("RestoreKeyCertPanel update: Exception=" + e.toString());
}
if (verifypfx) {
@@ -267,50 +266,50 @@ public class RestoreKeyCertPanel extends WizardPanelBase {
AuthenticatedSafes safes = pfx.getAuthSafes();
Vector pkeyinfo_collection = new Vector();
Vector cert_collection = new Vector();
- for (int i=0; i<safes.getSize(); i++) {
+ for (int i = 0; i < safes.getSize(); i++) {
try {
- SEQUENCE scontent = safes.getSafeContentsAt(null, i);
- for (int j=0; j<scontent.size(); j++) {
- SafeBag bag = (SafeBag)scontent.elementAt(j);
+ SEQUENCE scontent = safes.getSafeContentsAt(null, i);
+ for (int j = 0; j < scontent.size(); j++) {
+ SafeBag bag = (SafeBag) scontent.elementAt(j);
OBJECT_IDENTIFIER oid = bag.getBagType();
if (oid.equals(SafeBag.PKCS8_SHROUDED_KEY_BAG)) {
- EncryptedPrivateKeyInfo privkeyinfo =
- (EncryptedPrivateKeyInfo)bag.getInterpretedBagContent();
+ EncryptedPrivateKeyInfo privkeyinfo =
+ (EncryptedPrivateKeyInfo) bag.getInterpretedBagContent();
PasswordConverter passConverter = new PasswordConverter();
PrivateKeyInfo pkeyinfo = privkeyinfo.decrypt(password, new PasswordConverter());
Vector pkeyinfo_v = new Vector();
pkeyinfo_v.addElement(pkeyinfo);
SET bagAttrs = bag.getBagAttributes();
- for (int k=0; k<bagAttrs.size(); k++) {
- Attribute attrs = (Attribute)bagAttrs.elementAt(k);
+ for (int k = 0; k < bagAttrs.size(); k++) {
+ Attribute attrs = (Attribute) bagAttrs.elementAt(k);
OBJECT_IDENTIFIER aoid = attrs.getType();
if (aoid.equals(SafeBag.FRIENDLY_NAME)) {
SET val = attrs.getValues();
- ANY ss = (ANY)val.elementAt(0);
+ ANY ss = (ANY) val.elementAt(0);
ByteArrayInputStream bbis = new ByteArrayInputStream(ss.getEncoded());
- BMPString sss = (BMPString)(new BMPString.Template()).decode(bbis);
+ BMPString sss = (BMPString) (new BMPString.Template()).decode(bbis);
String s = sss.toString();
pkeyinfo_v.addElement(s);
}
}
pkeyinfo_collection.addElement(pkeyinfo_v);
} else if (oid.equals(SafeBag.CERT_BAG)) {
- CertBag cbag = (CertBag)bag.getInterpretedBagContent();
- OCTET_STRING str = (OCTET_STRING)cbag.getInterpretedCert();
+ CertBag cbag = (CertBag) bag.getInterpretedBagContent();
+ OCTET_STRING str = (OCTET_STRING) cbag.getInterpretedCert();
byte[] x509cert = str.toByteArray();
Vector cert_v = new Vector();
cert_v.addElement(x509cert);
SET bagAttrs = bag.getBagAttributes();
-
+
if (bagAttrs != null) {
- for (int k=0; k<bagAttrs.size(); k++) {
- Attribute attrs = (Attribute)bagAttrs.elementAt(k);
+ for (int k = 0; k < bagAttrs.size(); k++) {
+ Attribute attrs = (Attribute) bagAttrs.elementAt(k);
OBJECT_IDENTIFIER aoid = attrs.getType();
if (aoid.equals(SafeBag.FRIENDLY_NAME)) {
SET val = attrs.getValues();
- ANY ss = (ANY)val.elementAt(0);
+ ANY ss = (ANY) val.elementAt(0);
ByteArrayInputStream bbis = new ByteArrayInputStream(ss.getEncoded());
- BMPString sss = (BMPString)(new BMPString.Template()).decode(bbis);
+ BMPString sss = (BMPString) (new BMPString.Template()).decode(bbis);
String s = sss.toString();
cert_v.addElement(s);
}
@@ -321,10 +320,10 @@ public class RestoreKeyCertPanel extends WizardPanelBase {
}
}
} catch (Exception e) {
- CMS.debug("RestoreKeyCertPanel update: Exception="+e.toString());
+ CMS.debug("RestoreKeyCertPanel update: Exception=" + e.toString());
}
}
-
+
importkeycert(pkeyinfo_collection, cert_collection);
} else {
context.put("updateStatus", "failure");
@@ -342,7 +341,7 @@ public class RestoreKeyCertPanel extends WizardPanelBase {
cstype = toLowerCaseSubsystemType(cstype);
if (subsystemtype.equals("clone")) {
- CMS.debug("RestoreKeyCertPanel: this is the clone subsystem");
+ CMS.debug("RestoreKeyCertPanel: this is the clone subsystem");
boolean cloneReady = isCertdbCloned(request, context);
if (!cloneReady) {
CMS.debug("RestoreKeyCertPanel update: clone does not have all the certificates.");
@@ -363,7 +362,7 @@ public class RestoreKeyCertPanel extends WizardPanelBase {
}
private void getConfigEntriesFromMaster(HttpServletRequest request,
- HttpServletResponse response, Context context) throws IOException {
+ HttpServletResponse response, Context context) throws IOException {
try {
IConfigStore config = CMS.getConfigStore();
String cstype = "";
@@ -388,14 +387,14 @@ public class RestoreKeyCertPanel extends WizardPanelBase {
String content = "";
if (cstype.equals("ca") || cstype.equals("kra")) {
- content = "type=request&xmlOutput=true&sessionID="+session_id;
+ content = "type=request&xmlOutput=true&sessionID=" + session_id;
CMS.debug("http content=" + content);
updateNumberRange(master_hostname, master_ee_port, true, content, "request", response);
- content = "type=serialNo&xmlOutput=true&sessionID="+session_id;
+ content = "type=serialNo&xmlOutput=true&sessionID=" + session_id;
updateNumberRange(master_hostname, master_ee_port, true, content, "serialNo", response);
- content = "type=replicaId&xmlOutput=true&sessionID="+session_id;
+ content = "type=replicaId&xmlOutput=true&sessionID=" + session_id;
updateNumberRange(master_hostname, master_ee_port, true, content, "replicaId", response);
}
@@ -406,7 +405,7 @@ public class RestoreKeyCertPanel extends WizardPanelBase {
}
StringBuffer c1 = new StringBuffer();
- StringBuffer s1 = new StringBuffer();
+ StringBuffer s1 = new StringBuffer();
StringTokenizer tok = new StringTokenizer(list, ",");
while (tok.hasMoreTokens()) {
String t1 = tok.nextToken();
@@ -438,8 +437,7 @@ public class RestoreKeyCertPanel extends WizardPanelBase {
c1.append(t1);
c1.append(".pubkey.encoded");
-
- if (s1.length()!=0)
+ if (s1.length() != 0)
s1.append(",");
s1.append(cstype);
@@ -449,18 +447,18 @@ public class RestoreKeyCertPanel extends WizardPanelBase {
if (!cstype.equals("ca")) {
c1.append(",cloning.ca.hostname,cloning.ca.httpport,cloning.ca.httpsport,cloning.ca.list,cloning.ca.pkcs7,cloning.ca.type");
- }
+ }
if (cstype.equals("ca")) {
/* get ca connector details */
- if (s1.length()!=0)
+ if (s1.length() != 0)
s1.append(",");
s1.append("ca.connector.KRA");
}
- content = "op=get&names=cloning.token,instanceId,internaldb.basedn,internaldb.ldapauth.password,internaldb.replication.password,internaldb.ldapconn.host,internaldb.ldapconn.port,internaldb.ldapauth.bindDN"+c1.toString()+"&substores="+s1.toString()+"&xmlOutput=true&sessionID="+session_id;
+ content = "op=get&names=cloning.token,instanceId,internaldb.basedn,internaldb.ldapauth.password,internaldb.replication.password,internaldb.ldapconn.host,internaldb.ldapconn.port,internaldb.ldapauth.bindDN" + c1.toString() + "&substores=" + s1.toString() + "&xmlOutput=true&sessionID=" + session_id;
boolean success = updateConfigEntries(master_hostname, master_port, true,
- "/"+cstype+"/admin/"+cstype+"/getConfigEntries", content, config, response);
+ "/" + cstype + "/admin/" + cstype + "/getConfigEntries", content, config, response);
if (!success) {
context.put("errorString", "Failed to get configuration entries from the master");
throw new IOException("Failed to get configuration entries from the master");
@@ -473,7 +471,7 @@ public class RestoreKeyCertPanel extends WizardPanelBase {
} catch (IOException eee) {
throw eee;
} catch (Exception eee) {
- CMS.debug("RestoreKeyCertPanel: update exception caught:"+eee.toString());
+ CMS.debug("RestoreKeyCertPanel: update exception caught:" + eee.toString());
}
} catch (IOException ee) {
@@ -491,38 +489,38 @@ public class RestoreKeyCertPanel extends WizardPanelBase {
String s = st.nextToken();
if (s.equals("sslserver"))
continue;
- String name = "preop.master."+s+".nickname";
+ String name = "preop.master." + s + ".nickname";
String nickname = cs.getString(name, "");
CryptoManager cm = CryptoManager.getInstance();
X509Certificate xcert = null;
try {
xcert = cm.findCertByNickname(nickname);
} catch (Exception ee) {
- CMS.debug("RestoreKeyCertPanel deleteExistingCerts: Exception="+ee.toString());
+ CMS.debug("RestoreKeyCertPanel deleteExistingCerts: Exception=" + ee.toString());
}
CryptoToken ct = cm.getInternalKeyStorageToken();
CryptoStore store = ct.getCryptoStore();
try {
store.deleteCert(xcert);
} catch (Exception ee) {
- CMS.debug("RestoreKeyCertPanel deleteExistingCerts: Exception="+ee.toString());
+ CMS.debug("RestoreKeyCertPanel deleteExistingCerts: Exception=" + ee.toString());
}
}
} catch (Exception e) {
- CMS.debug("RestoreKeyCertPanel deleteExistingCerts: Exception="+e.toString());
- }
+ CMS.debug("RestoreKeyCertPanel deleteExistingCerts: Exception=" + e.toString());
+ }
}
private org.mozilla.jss.crypto.PrivateKey.Type getPrivateKeyType(PublicKey pubkey) {
- CMS.debug("Key Algorithm '"+pubkey.getAlgorithm()+"'");
- if (pubkey.getAlgorithm().equals("EC")) {
- return org.mozilla.jss.crypto.PrivateKey.Type.EC;
- }
- return org.mozilla.jss.crypto.PrivateKey.Type.RSA;
+ CMS.debug("Key Algorithm '" + pubkey.getAlgorithm() + "'");
+ if (pubkey.getAlgorithm().equals("EC")) {
+ return org.mozilla.jss.crypto.PrivateKey.Type.EC;
+ }
+ return org.mozilla.jss.crypto.PrivateKey.Type.RSA;
}
- private void importkeycert(Vector pkeyinfo_collection,
- Vector cert_collection) throws IOException {
+ private void importkeycert(Vector pkeyinfo_collection,
+ Vector cert_collection) throws IOException {
CryptoManager cm = null;
try {
cm = CryptoManager.getInstance();
@@ -532,12 +530,12 @@ public class RestoreKeyCertPanel extends WizardPanelBase {
// delete all existing certificates first
deleteExistingCerts();
- for (int i=0; i<pkeyinfo_collection.size(); i++) {
+ for (int i = 0; i < pkeyinfo_collection.size(); i++) {
try {
- Vector pkeyinfo_v = (Vector)pkeyinfo_collection.elementAt(i);
- PrivateKeyInfo pkeyinfo = (PrivateKeyInfo)pkeyinfo_v.elementAt(0);
- String nickname = (String)pkeyinfo_v.elementAt(1);
- byte[] x509cert = getX509Cert(nickname, cert_collection);
+ Vector pkeyinfo_v = (Vector) pkeyinfo_collection.elementAt(i);
+ PrivateKeyInfo pkeyinfo = (PrivateKeyInfo) pkeyinfo_v.elementAt(0);
+ String nickname = (String) pkeyinfo_v.elementAt(1);
+ byte[] x509cert = getX509Cert(nickname, cert_collection);
X509Certificate cert = cm.importCACertPackage(x509cert);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
pkeyinfo.encode(bos);
@@ -550,32 +548,32 @@ public class RestoreKeyCertPanel extends WizardPanelBase {
try {
store.deleteCert(cert);
} catch (Exception ee) {
- CMS.debug("RestoreKeyCertPanel importKeyCert: Exception="+ee.toString());
+ CMS.debug("RestoreKeyCertPanel importKeyCert: Exception=" + ee.toString());
}
KeyGenerator kg = token.getKeyGenerator(KeyGenAlgorithm.DES3);
SymmetricKey sk = kg.generate();
- byte iv[] = {0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1};
+ byte iv[] = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 };
IVParameterSpec param = new IVParameterSpec(iv);
Cipher c = token.getCipherContext(EncryptionAlgorithm.DES3_CBC_PAD);
c.initEncrypt(sk, param);
byte[] encpkey = c.doFinal(pkey);
-
+
KeyWrapper wrapper = token.getKeyWrapper(KeyWrapAlgorithm.DES3_CBC_PAD);
wrapper.initUnwrap(sk, param);
org.mozilla.jss.crypto.PrivateKey pp = wrapper.unwrapPrivate(encpkey, getPrivateKeyType(publickey), publickey);
} catch (Exception e) {
- CMS.debug("RestoreKeyCertPanel importkeycert: Exception="+e.toString());
+ CMS.debug("RestoreKeyCertPanel importkeycert: Exception=" + e.toString());
}
}
- for (int i=0; i<cert_collection.size(); i++) {
+ for (int i = 0; i < cert_collection.size(); i++) {
try {
- Vector cert_v = (Vector)cert_collection.elementAt(i);
- byte[] cert = (byte[])cert_v.elementAt(0);
+ Vector cert_v = (Vector) cert_collection.elementAt(i);
+ byte[] cert = (byte[]) cert_v.elementAt(0);
if (cert_v.size() > 1) {
- String name = (String)cert_v.elementAt(1);
+ String name = (String) cert_v.elementAt(1);
// we need to delete the trusted CA certificate if it is
// the same as the ca signing certificate
if (isCASigningCert(name)) {
@@ -586,10 +584,10 @@ public class RestoreKeyCertPanel extends WizardPanelBase {
CMS.debug("RestoreKeyCertPanel deleteCert: this is pk11store");
if (store instanceof PK11Store) {
try {
- PK11Store pk11store = (PK11Store)store;
+ PK11Store pk11store = (PK11Store) store;
pk11store.deleteCertOnly(certchain);
} catch (Exception ee) {
- CMS.debug("RestoreKeyCertPanel importKeyCert: Exception="+ee.toString());
+ CMS.debug("RestoreKeyCertPanel importKeyCert: Exception=" + ee.toString());
}
}
}
@@ -598,18 +596,18 @@ public class RestoreKeyCertPanel extends WizardPanelBase {
X509Certificate xcert = cm.importUserCACertPackage(cert, name);
if (name.startsWith("caSigningCert")) {
// we need to change the trust attribute to CT
- InternalCertificate icert = (InternalCertificate)xcert;
- icert.setSSLTrust(InternalCertificate.TRUSTED_CA
- | InternalCertificate.TRUSTED_CLIENT_CA
- | InternalCertificate.VALID_CA);
+ InternalCertificate icert = (InternalCertificate) xcert;
+ icert.setSSLTrust(InternalCertificate.TRUSTED_CA
+ | InternalCertificate.TRUSTED_CLIENT_CA
+ | InternalCertificate.VALID_CA);
} else if (name.startsWith("auditSigningCert")) {
- InternalCertificate icert = (InternalCertificate)xcert;
+ InternalCertificate icert = (InternalCertificate) xcert;
icert.setObjectSigningTrust(InternalCertificate.USER | InternalCertificate.VALID_PEER | InternalCertificate.TRUSTED_PEER);
}
} else
cm.importCACertPackage(cert);
} catch (Exception e) {
- CMS.debug("RestoreKeyCertPanel importkeycert: Exception="+e.toString());
+ CMS.debug("RestoreKeyCertPanel importkeycert: Exception=" + e.toString());
}
}
}
@@ -628,15 +626,15 @@ public class RestoreKeyCertPanel extends WizardPanelBase {
return false;
}
- private X509Certificate getX509CertFromToken(byte[] cert)
- throws IOException {
+ private X509Certificate getX509CertFromToken(byte[] cert)
+ throws IOException {
try {
X509CertImpl impl = new X509CertImpl(cert);
String issuer_impl = impl.getIssuerDN().toString();
BigInteger serial_impl = impl.getSerialNumber();
CryptoManager cm = CryptoManager.getInstance();
X509Certificate[] permcerts = cm.getPermCerts();
- for (int i=0; i<permcerts.length; i++) {
+ for (int i = 0; i < permcerts.length; i++) {
String issuer_p = permcerts[i].getSubjectDN().toString();
BigInteger serial_p = permcerts[i].getSerialNumber();
if (issuer_p.equals(issuer_impl) && serial_p.compareTo(serial_impl) == 0) {
@@ -644,25 +642,25 @@ public class RestoreKeyCertPanel extends WizardPanelBase {
}
}
} catch (Exception e) {
- CMS.debug("RestoreKeyCertPanel getX509CertFromToken: Exception="+e.toString());
+ CMS.debug("RestoreKeyCertPanel getX509CertFromToken: Exception=" + e.toString());
}
return null;
}
- private byte[] getX509Cert(String nickname, Vector cert_collection)
- throws IOException {
- for (int i=0; i<cert_collection.size(); i++) {
- Vector v = (Vector)cert_collection.elementAt(i);
- byte[] b = (byte[])v.elementAt(0);
+ private byte[] getX509Cert(String nickname, Vector cert_collection)
+ throws IOException {
+ for (int i = 0; i < cert_collection.size(); i++) {
+ Vector v = (Vector) cert_collection.elementAt(i);
+ byte[] b = (byte[]) v.elementAt(0);
X509CertImpl impl = null;
try {
impl = new X509CertImpl(b);
} catch (Exception e) {
- CMS.debug("RestoreKeyCertPanel getX509Cert: Exception="+e.toString());
- throw new IOException( e.toString() );
+ CMS.debug("RestoreKeyCertPanel getX509Cert: Exception=" + e.toString());
+ throw new IOException(e.toString());
}
- Principal subjectdn = impl.getSubjectDN();
+ Principal subjectdn = impl.getSubjectDN();
if (LDAPDN.equals(subjectdn.toString(), nickname))
return b;
}
@@ -674,9 +672,8 @@ public class RestoreKeyCertPanel extends WizardPanelBase {
* If validiate() returns false, this method will be called.
*/
public void displayError(HttpServletRequest request,
- HttpServletResponse response,
- Context context)
- {
+ HttpServletResponse response,
+ Context context) {
context.put("title", "Import Keys and Certificates");
context.put("password", "");
context.put("path", "");
@@ -684,7 +681,7 @@ public class RestoreKeyCertPanel extends WizardPanelBase {
}
private boolean isCertdbCloned(HttpServletRequest request,
- Context context) {
+ Context context) {
IConfigStore config = CMS.getConfigStore();
String certList = "";
try {
@@ -698,13 +695,13 @@ public class RestoreKeyCertPanel extends WizardPanelBase {
String tokenname = config.getString("preop.module.token", "");
CryptoToken tok = cm.getTokenByName(tokenname);
CryptoStore store = tok.getCryptoStore();
- String name1 = "preop.master."+token+".nickname";
+ String name1 = "preop.master." + token + ".nickname";
String nickname = config.getString(name1, "");
if (!tokenname.equals("Internal Key Storage Token") &&
- !tokenname.equals("internal"))
- nickname = tokenname+":"+nickname;
+ !tokenname.equals("internal"))
+ nickname = tokenname + ":" + nickname;
- CMS.debug("RestoreKeyCertPanel isCertdbCloned: "+nickname);
+ CMS.debug("RestoreKeyCertPanel isCertdbCloned: " + nickname);
X509Certificate cert = cm.findCertByNickname(nickname);
if (cert == null)
return false;
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/SavePKCS12Panel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/SavePKCS12Panel.java
index 854e8f10..0c066268 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/SavePKCS12Panel.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/SavePKCS12Panel.java
@@ -34,19 +34,20 @@ import com.netscape.cms.servlet.wizard.WizardServlet;
public class SavePKCS12Panel extends WizardPanelBase {
- public SavePKCS12Panel() {}
+ public SavePKCS12Panel() {
+ }
/**
* Initializes this panel.
*/
- public void init(ServletConfig config, int panelno)
- throws ServletException {
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
setPanelNo(panelno);
setName("Save Keys and Certificates");
}
public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
- throws ServletException {
+ throws ServletException {
setPanelNo(panelno);
setName("Save Keys and Certificates");
setId(id);
@@ -60,11 +61,11 @@ public class SavePKCS12Panel extends WizardPanelBase {
try {
boolean enable = cs.getBoolean("preop.backupkeys.enable", false);
- if (!enable)
+ if (!enable)
return true;
} catch (Exception e) {
}
-
+
return false;
}
@@ -77,13 +78,14 @@ public class SavePKCS12Panel extends WizardPanelBase {
} else {
return true;
}
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
return false;
}
public PropertySet getUsage() {
PropertySet set = new PropertySet();
-
+
return set;
}
@@ -116,7 +118,7 @@ public class SavePKCS12Panel extends WizardPanelBase {
* Checks if the given parameters are valid.
*/
public void validate(HttpServletRequest request,
- HttpServletResponse response, Context context) throws IOException {
+ HttpServletResponse response, Context context) throws IOException {
}
/**
@@ -134,9 +136,8 @@ public class SavePKCS12Panel extends WizardPanelBase {
* If validiate() returns false, this method will be called.
*/
public void displayError(HttpServletRequest request,
- HttpServletResponse response,
- Context context)
- {
+ HttpServletResponse response,
+ Context context) {
context.put("title", "Save Keys and Certificates");
context.put("panel", "admin/console/config/savepkcs12panel.vm");
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/SecurityDomainLogin.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/SecurityDomainLogin.java
index 3a5d82d1..42165b08 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/SecurityDomainLogin.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/SecurityDomainLogin.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.net.URL;
import java.net.URLDecoder;
@@ -59,9 +58,9 @@ public class SecurityDomainLogin extends BaseServlet {
int index = url.indexOf("subsystem=");
String subsystem = "";
if (index > 0) {
- subsystem = url.substring(index+10);
+ subsystem = url.substring(index + 10);
int index1 = subsystem.indexOf("&");
- if (index1 > 0)
+ if (index1 > 0)
subsystem = subsystem.substring(0, index1);
}
context.put("sd_uid", "");
@@ -70,14 +69,14 @@ public class SecurityDomainLogin extends BaseServlet {
context.put("host", u.getHost());
context.put("sdhost", CMS.getEESSLHost());
if (subsystem.equals("KRA")) {
- subsystem = "DRM";
+ subsystem = "DRM";
}
context.put("subsystem", subsystem);
// The "securitydomain.name" property ONLY resides in the "CS.cfg"
// associated with the CS subsystem hosting the security domain.
IConfigStore cs = CMS.getConfigStore();
String sdname = cs.getString("securitydomain.name", "");
- context.put("name", sdname);
+ context.put("name", sdname);
template = Velocity.getTemplate("admin/console/config/securitydomainloginpanel.vm");
} catch (Exception e) {
System.err.println("Exception caught: " + e.getMessage());
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/SecurityDomainPanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/SecurityDomainPanel.java
index 90a6aeb0..8e52aa37 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/SecurityDomainPanel.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/SecurityDomainPanel.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
@@ -39,19 +38,20 @@ import com.netscape.cms.servlet.wizard.WizardServlet;
public class SecurityDomainPanel extends WizardPanelBase {
- public SecurityDomainPanel() {}
+ public SecurityDomainPanel() {
+ }
/**
* Initializes this panel.
*/
- public void init(ServletConfig config, int panelno)
- throws ServletException {
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
setPanelNo(panelno);
setName("Security Domain");
}
public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
- throws ServletException {
+ throws ServletException {
setPanelNo(panelno);
setName("Security Domain");
setId(id);
@@ -72,15 +72,16 @@ public class SecurityDomainPanel extends WizardPanelBase {
} else {
return true;
}
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
return false;
}
public PropertySet getUsage() {
PropertySet set = new PropertySet();
-
+
/* XXX */
-
+
return set;
}
@@ -136,7 +137,8 @@ public class SecurityDomainPanel extends WizardPanelBase {
context.put("https_ee_port", CMS.getEESSLPort());
context.put("https_admin_port", CMS.getAdminPort());
context.put("sdomainAdminURL", default_admin_url);
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
context.put("panel", "admin/console/config/securitydomainpanel.vm");
context.put("errorString", errorString);
@@ -157,18 +159,18 @@ public class SecurityDomainPanel extends WizardPanelBase {
while (st.hasMoreTokens()) {
count++;
String n = st.nextToken();
- if (first) { //skip the hostname
+ if (first) { // skip the hostname
first = false;
continue;
}
if (count == numTokens) // skip the last element (e.g. com)
continue;
- sb.append((defaultDomain.length()==0)? "":" ");
+ sb.append((defaultDomain.length() == 0) ? "" : " ");
sb.append(capitalize(n));
}
- defaultDomain = sb.toString() + " "+ "Domain";
+ defaultDomain = sb.toString() + " " + "Domain";
name = defaultDomain;
- CMS.debug("SecurityDomainPanel: defaultDomain generated:"+ name);
+ CMS.debug("SecurityDomainPanel: defaultDomain generated:" + name);
} catch (MalformedURLException e) {
errorString = "Malformed URL";
// not being able to come up with default domain name is ok
@@ -176,54 +178,53 @@ public class SecurityDomainPanel extends WizardPanelBase {
}
context.put("sdomainName", name);
- if( default_admin_url != null ) {
+ if (default_admin_url != null) {
String r = null;
try {
// check to see if "default" security domain exists
// on local machine
- URL u = new URL( default_admin_url );
+ URL u = new URL(default_admin_url);
String hostname = u.getHost();
int port = u.getPort();
- ConfigCertApprovalCallback
- certApprovalCallback = new ConfigCertApprovalCallback();
- r = pingCS( hostname, port, true, certApprovalCallback );
+ ConfigCertApprovalCallback certApprovalCallback = new ConfigCertApprovalCallback();
+ r = pingCS(hostname, port, true, certApprovalCallback);
} catch (Exception e) {
- CMS.debug( "SecurityDomainPanel: exception caught: "
- + e.toString() );
+ CMS.debug("SecurityDomainPanel: exception caught: "
+ + e.toString());
}
-
- if( r != null ) {
+
+ if (r != null) {
// "default" security domain exists on local machine;
// fill "sdomainURL" in with "default" security domain
// as an initial "guess"
- CMS.debug( "SecurityDomainPanel: pingCS returns: "+r );
- context.put( "sdomainURL", default_admin_url );
+ CMS.debug("SecurityDomainPanel: pingCS returns: " + r);
+ context.put("sdomainURL", default_admin_url);
} else {
// "default" security domain does NOT exist on local machine;
// leave "sdomainURL" blank
- CMS.debug( "SecurityDomainPanel: pingCS no successful response" );
- context.put( "sdomainURL", "" );
+ CMS.debug("SecurityDomainPanel: pingCS no successful response");
+ context.put("sdomainURL", "");
}
}
// Information for "existing" Security Domain CAs
String initDaemon = "pki-cad";
String instanceId = "&lt;security_domain_instance_name&gt;";
- String os = System.getProperty( "os.name" );
- if( os.equalsIgnoreCase( "Linux" ) ) {
- if (! systemdService.equals("")) {
- context.put( "initCommand", "/usr/bin/pkicontrol" );
- context.put( "instanceId", "ca " + systemdService );
+ String os = System.getProperty("os.name");
+ if (os.equalsIgnoreCase("Linux")) {
+ if (!systemdService.equals("")) {
+ context.put("initCommand", "/usr/bin/pkicontrol");
+ context.put("instanceId", "ca " + systemdService);
} else {
- context.put( "initCommand", "/sbin/service " + initDaemon );
- context.put( "instanceId", instanceId );
+ context.put("initCommand", "/sbin/service " + initDaemon);
+ context.put("instanceId", instanceId);
}
} else {
- /* default case: e. g. - ( os.equalsIgnoreCase( "SunOS" ) */
- context.put( "initCommand", "/etc/init.d/" + initDaemon );
- context.put( "instanceId", instanceId );
+ /* default case: e. g. - ( os.equalsIgnoreCase( "SunOS" ) */
+ context.put("initCommand", "/etc/init.d/" + initDaemon);
+ context.put("instanceId", instanceId);
}
}
@@ -231,7 +232,7 @@ public class SecurityDomainPanel extends WizardPanelBase {
if (s.length() == 0) {
return s;
} else {
- return s.substring(0,1).toUpperCase() + s.substring(1);
+ return s.substring(0, 1).toUpperCase() + s.substring(1);
}
}
@@ -241,7 +242,7 @@ public class SecurityDomainPanel extends WizardPanelBase {
public void validate(HttpServletRequest request,
HttpServletResponse response,
Context context) throws IOException {
-
+
String select = HttpInput.getID(request, "choice");
if (select.equals("newdomain")) {
String name = HttpInput.getSecurityDomainName(request, "sdomainName");
@@ -251,50 +252,48 @@ public class SecurityDomainPanel extends WizardPanelBase {
throw new IOException("Missing name value for the security domain");
}
} else if (select.equals("existingdomain")) {
- CMS.debug( "SecurityDomainPanel: validating "
- + "SSL Admin HTTPS . . ." );
- String admin_url = HttpInput.getURL( request, "sdomainURL" );
- if( admin_url == null || admin_url.equals("") ) {
- initParams( request, context );
+ CMS.debug("SecurityDomainPanel: validating "
+ + "SSL Admin HTTPS . . .");
+ String admin_url = HttpInput.getURL(request, "sdomainURL");
+ if (admin_url == null || admin_url.equals("")) {
+ initParams(request, context);
context.put("updateStatus", "validate-failure");
- throw new IOException( "Missing SSL Admin HTTPS url value "
- + "for the security domain" );
+ throw new IOException("Missing SSL Admin HTTPS url value "
+ + "for the security domain");
} else {
String r = null;
try {
- URL u = new URL( admin_url );
+ URL u = new URL(admin_url);
String hostname = u.getHost();
int admin_port = u.getPort();
- ConfigCertApprovalCallback
- certApprovalCallback = new ConfigCertApprovalCallback();
- r = pingCS( hostname, admin_port, true,
- certApprovalCallback );
- } catch( Exception e ) {
- CMS.debug( "SecurityDomainPanel: exception caught: "
- + e.toString() );
+ ConfigCertApprovalCallback certApprovalCallback = new ConfigCertApprovalCallback();
+ r = pingCS(hostname, admin_port, true,
+ certApprovalCallback);
+ } catch (Exception e) {
+ CMS.debug("SecurityDomainPanel: exception caught: "
+ + e.toString());
context.put("updateStatus", "validate-failure");
- throw new IOException( "Illegal SSL Admin HTTPS url value "
- + "for the security domain" );
+ throw new IOException("Illegal SSL Admin HTTPS url value "
+ + "for the security domain");
}
if (r != null) {
CMS.debug("SecurityDomainPanel: pingAdminCS returns: "
- + r );
- context.put( "sdomainURL", admin_url );
+ + r);
+ context.put("sdomainURL", admin_url);
} else {
- CMS.debug( "SecurityDomainPanel: pingAdminCS "
- + "no successful response for SSL Admin HTTPS" );
- context.put( "sdomainURL", "" );
+ CMS.debug("SecurityDomainPanel: pingAdminCS "
+ + "no successful response for SSL Admin HTTPS");
+ context.put("sdomainURL", "");
}
}
}
}
- public void initParams(HttpServletRequest request, Context context)
- throws IOException
- {
+ public void initParams(HttpServletRequest request, Context context)
+ throws IOException {
IConfigStore config = CMS.getConfigStore();
try {
context.put("cstype", config.getString("cs.type"));
@@ -306,7 +305,7 @@ public class SecurityDomainPanel extends WizardPanelBase {
context.put("check_newdomain", "checked");
context.put("check_existingdomain", "");
} else if (select.equals("existingdomain")) {
- context.put("check_newdomain", "");
+ context.put("check_newdomain", "");
context.put("check_existingdomain", "checked");
}
@@ -340,29 +339,30 @@ public class SecurityDomainPanel extends WizardPanelBase {
if (select.equals("newdomain")) {
config.putString("preop.securitydomain.select", "new");
config.putString("securitydomain.select", "new");
- config.putString("preop.securitydomain.name",
- HttpInput.getDomainName(request, "sdomainName"));
- config.putString("securitydomain.name",
- HttpInput.getDomainName(request, "sdomainName"));
- config.putString("securitydomain.host",
- CMS.getEENonSSLHost());
- config.putString("securitydomain.httpport",
- CMS.getEENonSSLPort());
- config.putString("securitydomain.httpsagentport",
- CMS.getAgentPort());
- config.putString("securitydomain.httpseeport",
- CMS.getEESSLPort());
- config.putString("securitydomain.httpsadminport",
- CMS.getAdminPort());
-
- // make sure the subsystem certificate is issued by the security
+ config.putString("preop.securitydomain.name",
+ HttpInput.getDomainName(request, "sdomainName"));
+ config.putString("securitydomain.name",
+ HttpInput.getDomainName(request, "sdomainName"));
+ config.putString("securitydomain.host",
+ CMS.getEENonSSLHost());
+ config.putString("securitydomain.httpport",
+ CMS.getEENonSSLPort());
+ config.putString("securitydomain.httpsagentport",
+ CMS.getAgentPort());
+ config.putString("securitydomain.httpseeport",
+ CMS.getEESSLPort());
+ config.putString("securitydomain.httpsadminport",
+ CMS.getAdminPort());
+
+ // make sure the subsystem certificate is issued by the security
// domain
config.putString("preop.cert.subsystem.type", "local");
config.putString("preop.cert.subsystem.profile", "subsystemCert.profile");
-
+
try {
config.commit(false);
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
String instanceRoot = "";
try {
@@ -383,31 +383,32 @@ public class SecurityDomainPanel extends WizardPanelBase {
String hostname = "";
int admin_port = -1;
- if( admin_url != null ) {
+ if (admin_url != null) {
try {
- URL admin_u = new URL( admin_url );
+ URL admin_u = new URL(admin_url);
hostname = admin_u.getHost();
admin_port = admin_u.getPort();
- } catch( MalformedURLException e ) {
+ } catch (MalformedURLException e) {
errorString = "Malformed SSL Admin HTTPS URL";
context.put("updateStatus", "failure");
- throw new IOException( errorString );
+ throw new IOException(errorString);
}
- context.put( "sdomainURL", admin_url );
- config.putString( "securitydomain.host", hostname );
- config.putInteger( "securitydomain.httpsadminport",
- admin_port );
+ context.put("sdomainURL", admin_url);
+ config.putString("securitydomain.host", hostname);
+ config.putInteger("securitydomain.httpsadminport",
+ admin_port);
}
try {
config.commit(false);
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
ConfigCertApprovalCallback certApprovalCallback = new ConfigCertApprovalCallback();
- updateCertChain( config, "securitydomain", hostname, admin_port,
- true, context, certApprovalCallback );
+ updateCertChain(config, "securitydomain", hostname, admin_port,
+ true, context, certApprovalCallback);
} else {
CMS.debug("SecurityDomainPanel: invalid choice " + select);
errorString = "Invalid choice";
@@ -425,7 +426,8 @@ public class SecurityDomainPanel extends WizardPanelBase {
context.put("wizardname", config.getString("preop.wizard.name"));
context.put("panelname", "Security Domain Configuration");
context.put("systemname", config.getString("preop.system.name"));
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
context.put("errorString", errorString);
context.put("updateStatus", "success");
@@ -446,32 +448,33 @@ public class SecurityDomainPanel extends WizardPanelBase {
try {
default_admin_url = config.getString("preop.securitydomain.admin_url", "");
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
- if( default_admin_url != null ) {
+ if (default_admin_url != null) {
String r = null;
try {
// check to see if "default" security domain exists
// on local machine
- URL u = new URL( default_admin_url );
+ URL u = new URL(default_admin_url);
String hostname = u.getHost();
int port = u.getPort();
- ConfigCertApprovalCallback
- certApprovalCallback = new ConfigCertApprovalCallback();
- r = pingCS( hostname, port, true, certApprovalCallback );
- } catch (Exception e) {}
-
- if( r != null ) {
+ ConfigCertApprovalCallback certApprovalCallback = new ConfigCertApprovalCallback();
+ r = pingCS(hostname, port, true, certApprovalCallback);
+ } catch (Exception e) {
+ }
+
+ if (r != null) {
// "default" security domain exists on local machine;
// refill "sdomainURL" in with "default" security domain
// as an initial "guess"
- context.put( "sdomainURL", default_admin_url );
+ context.put("sdomainURL", default_admin_url);
} else {
// "default" security domain does NOT exist on local machine;
// leave "sdomainURL" blank
- context.put( "sdomainURL", "" );
+ context.put("sdomainURL", "");
}
}
@@ -483,19 +486,20 @@ public class SecurityDomainPanel extends WizardPanelBase {
context.put("https_admin_port", CMS.getAdminPort());
context.put("sdomainAdminURL",
config.getString("preop.securitydomain.admin_url"));
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
// Information for "existing" Security Domain CAs
String initDaemon = "pki-cad";
String instanceId = "&lt;security_domain_instance_name&gt;";
- String os = System.getProperty( "os.name" );
- if( os.equalsIgnoreCase( "Linux" ) ) {
- context.put( "initCommand", "/sbin/service " + initDaemon );
- context.put( "instanceId", instanceId );
+ String os = System.getProperty("os.name");
+ if (os.equalsIgnoreCase("Linux")) {
+ context.put("initCommand", "/sbin/service " + initDaemon);
+ context.put("instanceId", instanceId);
} else {
- /* default case: e. g. - ( os.equalsIgnoreCase( "SunOS" ) */
- context.put( "initCommand", "/etc/init.d/" + initDaemon );
- context.put( "instanceId", instanceId );
+ /* default case: e. g. - ( os.equalsIgnoreCase( "SunOS" ) */
+ context.put("initCommand", "/etc/init.d/" + initDaemon);
+ context.put("instanceId", instanceId);
}
context.put("title", "Security Domain");
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/SecurityDomainSessionTable.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/SecurityDomainSessionTable.java
index 75cc0fb6..d15ca5ad 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/SecurityDomainSessionTable.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/SecurityDomainSessionTable.java
@@ -27,8 +27,8 @@ import com.netscape.certsrv.base.ISecurityDomainSessionTable;
/**
* This object stores the values for IP, uid and group based on the cookie id.
*/
-public class SecurityDomainSessionTable
- implements ISecurityDomainSessionTable {
+public class SecurityDomainSessionTable
+ implements ISecurityDomainSessionTable {
private Hashtable<String, Vector<Comparable<?>>> m_sessions;
private long m_timeToLive;
@@ -38,8 +38,8 @@ public class SecurityDomainSessionTable
m_timeToLive = timeToLive;
}
- public int addEntry(String sessionId, String ip,
- String uid, String group) {
+ public int addEntry(String sessionId, String ip,
+ String uid, String group) {
Vector<Comparable<?>> v = new Vector<Comparable<?>>();
v.addElement(ip);
v.addElement(uid);
@@ -67,28 +67,28 @@ public class SecurityDomainSessionTable
public String getIP(String sessionId) {
Vector<Comparable<?>> v = m_sessions.get(sessionId);
if (v != null)
- return (String)v.elementAt(0);
+ return (String) v.elementAt(0);
return null;
}
public String getUID(String sessionId) {
Vector<Comparable<?>> v = m_sessions.get(sessionId);
if (v != null)
- return (String)v.elementAt(1);
+ return (String) v.elementAt(1);
return null;
}
public String getGroup(String sessionId) {
Vector<Comparable<?>> v = m_sessions.get(sessionId);
if (v != null)
- return (String)v.elementAt(2);
+ return (String) v.elementAt(2);
return null;
}
public long getBeginTime(String sessionId) {
Vector<Comparable<?>> v = m_sessions.get(sessionId);
- if (v != null) {
- Long n = (Long)v.elementAt(3);
+ if (v != null) {
+ Long n = (Long) v.elementAt(3);
if (n != null)
return n.longValue();
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/SessionTimer.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/SessionTimer.java
index c3a1e325..49cadb9c 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/SessionTimer.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/SessionTimer.java
@@ -29,7 +29,7 @@ public class SessionTimer extends TimerTask {
private ISecurityDomainSessionTable m_sessiontable = null;
private ILogger mSignedAuditLogger = CMS.getSignedAuditLogger();
private final static String LOGGING_SIGNED_AUDIT_SECURITY_DOMAIN_UPDATE =
- "LOGGING_SIGNED_AUDIT_SECURITY_DOMAIN_UPDATE_1";
+ "LOGGING_SIGNED_AUDIT_SECURITY_DOMAIN_UPDATE_1";
public SessionTimer(ISecurityDomainSessionTable table) {
super();
@@ -39,15 +39,15 @@ public class SessionTimer extends TimerTask {
public void run() {
Enumeration keys = m_sessiontable.getSessionIds();
while (keys.hasMoreElements()) {
- String sessionId = (String)keys.nextElement();
+ String sessionId = (String) keys.nextElement();
long beginTime = m_sessiontable.getBeginTime(sessionId);
Date nowDate = new Date();
long nowTime = nowDate.getTime();
long timeToLive = m_sessiontable.getTimeToLive();
- if ((nowTime-beginTime) > timeToLive) {
+ if ((nowTime - beginTime) > timeToLive) {
m_sessiontable.removeEntry(sessionId);
CMS.debug("SessionTimer run: successfully remove the session id entry from the table.");
-
+
// audit message
String auditParams = "operation;;expire_token+token;;" + sessionId;
String auditMessage = CMS.getLogMessage(
@@ -62,9 +62,7 @@ public class SessionTimer extends TimerTask {
ILogger.LL_SECURITY,
auditMessage);
-
}
}
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/SizePanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/SizePanel.java
index 0e6a507a..8f5d6808 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/SizePanel.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/SizePanel.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.IOException;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
@@ -54,13 +53,14 @@ public class SizePanel extends WizardPanelBase {
private String default_rsa_key_size;
private boolean mShowSigning = false;
- public SizePanel() {}
+ public SizePanel() {
+ }
/**
* Initializes this panel.
*/
- public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
- throws ServletException {
+ public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
+ throws ServletException {
setPanelNo(panelno);
setName("Key Pairs");
setId(id);
@@ -69,25 +69,28 @@ public class SizePanel extends WizardPanelBase {
public PropertySet getUsage() {
PropertySet set = new PropertySet();
-
+
Descriptor choiceDesc = new Descriptor(IDescriptor.CHOICE,
"default,custom", null, /* no default parameter */
"If 'default', the key size will be configured automatically. If 'custom', the key size will be set to the value of the parameter 'custom_size'.");
set.add("choice", choiceDesc);
-
- Descriptor customSizeDesc = new Descriptor(IDescriptor.STRING, null, /* no constraint */
+
+ Descriptor customSizeDesc = new Descriptor(IDescriptor.STRING, null, /*
+ * no
+ * constraint
+ */
null, /* no default parameter */
"Custom Key Size");
set.add("custom_size", customSizeDesc);
-
+
return set;
}
public void cleanUp() throws IOException {
IConfigStore cs = CMS.getConfigStore();
- /* clean up if necessary*/
+ /* clean up if necessary */
try {
boolean done = cs.getBoolean("preop.SizePanel.done");
cs.putBoolean("preop.SizePanel.done", false);
@@ -105,7 +108,8 @@ public class SizePanel extends WizardPanelBase {
} else {
return true;
}
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
return false;
}
@@ -118,7 +122,7 @@ public class SizePanel extends WizardPanelBase {
Context context) {
CMS.debug("SizePanel: display()");
try {
- initParams(request, context);
+ initParams(request, context);
} catch (IOException e) {
}
@@ -134,12 +138,12 @@ public class SizePanel extends WizardPanelBase {
}
try {
- default_ecc_curve_name = config.getString("keys.ecc.curve.default", "nistp256");
+ default_ecc_curve_name = config.getString("keys.ecc.curve.default", "nistp256");
} catch (Exception e) {
}
try {
- default_rsa_key_size = config.getString("keys.rsa.keysize.default", "2048");
+ default_rsa_key_size = config.getString("keys.rsa.keysize.default", "2048");
} catch (Exception e) {
}
@@ -180,12 +184,13 @@ public class SizePanel extends WizardPanelBase {
PCERT_PREFIX + certTag + ".signing.required",
false);
c.setSigningRequired(signingRequired);
- if (signingRequired) mShowSigning = true;
+ if (signingRequired)
+ mShowSigning = true;
String userfriendlyname = config.getString(
PCERT_PREFIX + certTag + ".userfriendlyname");
c.setUserFriendlyName(userfriendlyname);
- boolean enable = config.getBoolean(PCERT_PREFIX+certTag+".enable", true);
+ boolean enable = config.getBoolean(PCERT_PREFIX + certTag + ".enable", true);
c.setEnable(enable);
mCerts.addElement(c);
}// while
@@ -236,13 +241,13 @@ public class SizePanel extends WizardPanelBase {
if (select1.equals("clone")) {
// preset the sslserver dn for cloning case
try {
- String val = config.getString("preop.cert.sslserver.dn", "");
- config.putString("preop.cert.sslserver.dn", val+",o=clone");
+ String val = config.getString("preop.cert.sslserver.dn", "");
+ config.putString("preop.cert.sslserver.dn", val + ",o=clone");
} catch (Exception ee) {
}
}
}
-
+
String token = "";
try {
token = config.getString(PRE_CONF_CA_TOKEN, "");
@@ -251,11 +256,13 @@ public class SizePanel extends WizardPanelBase {
while (c.hasMoreElements()) {
Cert cert = (Cert) c.nextElement();
String ct = cert.getCertTag();
- boolean enable = config.getBoolean(PCERT_PREFIX+ct+".enable", true);
+ boolean enable = config.getBoolean(PCERT_PREFIX + ct + ".enable", true);
if (!enable)
continue;
- String keytype = HttpInput.getKeyType(request, ct + "_keytype"); // rsa or ecc
+ String keytype = HttpInput.getKeyType(request, ct + "_keytype"); // rsa
+ // or
+ // ecc
String keyalgorithm = HttpInput.getString(request, ct + "_keyalgorithm");
if (keyalgorithm == null) {
@@ -280,28 +287,28 @@ public class SizePanel extends WizardPanelBase {
}
CMS.debug(
"SizePanel: update() keysize choice selected:" + select);
- String oldkeysize =
- config.getString(PCERT_PREFIX+ct+".keysize.size", "");
- String oldkeytype =
- config.getString(PCERT_PREFIX + ct + ".keytype", "");
- String oldkeyalgorithm =
- config.getString(PCERT_PREFIX + ct + ".keyalgorithm", "");
- String oldsigningalgorithm =
- config.getString(PCERT_PREFIX + ct + ".signingalgorithm", "");
+ String oldkeysize =
+ config.getString(PCERT_PREFIX + ct + ".keysize.size", "");
+ String oldkeytype =
+ config.getString(PCERT_PREFIX + ct + ".keytype", "");
+ String oldkeyalgorithm =
+ config.getString(PCERT_PREFIX + ct + ".keyalgorithm", "");
+ String oldsigningalgorithm =
+ config.getString(PCERT_PREFIX + ct + ".signingalgorithm", "");
String oldcurvename =
- config.getString(PCERT_PREFIX + ct + ".curvename.name", "");
+ config.getString(PCERT_PREFIX + ct + ".curvename.name", "");
if (select.equals("default")) {
// XXXrenaming these...keep for now just in case
config.putString("preop.keysize.select", "default");
if (keytype != null && keytype.equals("ecc")) {
- config.putString("preop.curvename.custom_name",
- default_ecc_curve_name);
- config.putString("preop.curvename.name", default_ecc_curve_name);
+ config.putString("preop.curvename.custom_name",
+ default_ecc_curve_name);
+ config.putString("preop.curvename.name", default_ecc_curve_name);
} else {
- config.putString("preop.keysize.custom_size",
- default_rsa_key_size);
- config.putString("preop.keysize.size", default_rsa_key_size);
+ config.putString("preop.keysize.custom_size",
+ default_rsa_key_size);
+ config.putString("preop.keysize.size", default_rsa_key_size);
}
config.putString(PCERT_PREFIX + ct + ".keytype", keytype);
@@ -311,31 +318,31 @@ public class SizePanel extends WizardPanelBase {
"default");
if (keytype != null && keytype.equals("ecc")) {
- config.putString(PCERT_PREFIX + ct +
- ".curvename.custom_name",
- default_ecc_curve_name);
- config.putString(PCERT_PREFIX + ct + ".curvename.name",
- default_ecc_curve_name);
+ config.putString(PCERT_PREFIX + ct +
+ ".curvename.custom_name",
+ default_ecc_curve_name);
+ config.putString(PCERT_PREFIX + ct + ".curvename.name",
+ default_ecc_curve_name);
} else {
- config.putString(PCERT_PREFIX + ct +
- ".keysize.custom_size",
- default_rsa_key_size);
- config.putString(PCERT_PREFIX + ct + ".keysize.size",
- default_rsa_key_size);
+ config.putString(PCERT_PREFIX + ct +
+ ".keysize.custom_size",
+ default_rsa_key_size);
+ config.putString(PCERT_PREFIX + ct + ".keysize.size",
+ default_rsa_key_size);
}
} else if (select.equals("custom")) {
// XXXrenaming these...keep for now just in case
config.putString("preop.keysize.select", "custom");
if (keytype != null && keytype.equals("ecc")) {
- config.putString("preop.curvename.name",
- HttpInput.getString(request, ct + "_custom_curvename"));
+ config.putString("preop.curvename.name",
+ HttpInput.getString(request, ct + "_custom_curvename"));
config.putString("preop.curvename.custom_name",
- HttpInput.getString(request, ct + "_custom_curvename"));
+ HttpInput.getString(request, ct + "_custom_curvename"));
} else {
- config.putString("preop.keysize.size",
- HttpInput.getKeySize(request, ct + "_custom_size", keytype));
+ config.putString("preop.keysize.size",
+ HttpInput.getKeySize(request, ct + "_custom_size", keytype));
config.putString("preop.keysize.custom_size",
- HttpInput.getKeySize(request, ct + "_custom_size", keytype));
+ HttpInput.getKeySize(request, ct + "_custom_size", keytype));
}
config.putString(PCERT_PREFIX + ct + ".keytype", keytype);
@@ -346,42 +353,42 @@ public class SizePanel extends WizardPanelBase {
if (keytype != null && keytype.equals("ecc")) {
config.putString(PCERT_PREFIX + ct + ".curvename.custom_name",
- HttpInput.getString(request, ct + "_custom_curvename"));
+ HttpInput.getString(request, ct + "_custom_curvename"));
config.putString(PCERT_PREFIX + ct + ".curvename.name",
- HttpInput.getString(request, ct + "_custom_curvename"));
+ HttpInput.getString(request, ct + "_custom_curvename"));
} else {
config.putString(PCERT_PREFIX + ct + ".keysize.custom_size",
- HttpInput.getKeySize(request, ct + "_custom_size"));
+ HttpInput.getKeySize(request, ct + "_custom_size"));
config.putString(PCERT_PREFIX + ct + ".keysize.size",
- HttpInput.getKeySize(request, ct + "_custom_size"));
+ HttpInput.getKeySize(request, ct + "_custom_size"));
}
} else {
CMS.debug("SizePanel: invalid choice " + select);
throw new IOException("invalid choice " + select);
}
- String newkeysize =
- config.getString(PCERT_PREFIX+ct+".keysize.size", "");
- String newkeytype =
- config.getString(PCERT_PREFIX + ct + ".keytype", "");
- String newkeyalgorithm =
- config.getString(PCERT_PREFIX + ct + ".keyalgorithm", "");
- String newsigningalgorithm =
- config.getString(PCERT_PREFIX + ct + ".signingalgorithm", "");
- String newcurvename =
- config.getString(PCERT_PREFIX+ct+".curvename.name", "");
-
- if (!oldkeysize.equals(newkeysize) ||
- !oldkeytype.equals(newkeytype) ||
- !oldkeyalgorithm.equals(newkeyalgorithm) ||
- !oldsigningalgorithm.equals(newsigningalgorithm) ||
- !oldcurvename.equals(newcurvename))
+ String newkeysize =
+ config.getString(PCERT_PREFIX + ct + ".keysize.size", "");
+ String newkeytype =
+ config.getString(PCERT_PREFIX + ct + ".keytype", "");
+ String newkeyalgorithm =
+ config.getString(PCERT_PREFIX + ct + ".keyalgorithm", "");
+ String newsigningalgorithm =
+ config.getString(PCERT_PREFIX + ct + ".signingalgorithm", "");
+ String newcurvename =
+ config.getString(PCERT_PREFIX + ct + ".curvename.name", "");
+
+ if (!oldkeysize.equals(newkeysize) ||
+ !oldkeytype.equals(newkeytype) ||
+ !oldkeyalgorithm.equals(newkeyalgorithm) ||
+ !oldsigningalgorithm.equals(newsigningalgorithm) ||
+ !oldcurvename.equals(newcurvename))
hasChanged = true;
}// while
try {
config.commit(false);
- } catch (EBaseException e) {
+ } catch (EBaseException e) {
CMS.debug("SizePanel: update() Exception caught at config commit: " + e.toString());
}
@@ -393,7 +400,7 @@ public class SizePanel extends WizardPanelBase {
context.put("updateStatus", "success");
return;
}
- } catch (IOException e) {
+ } catch (IOException e) {
CMS.debug("SizePanel: update() IOException caught: " + e.toString());
context.put("updateStatus", "failure");
throw e;
@@ -401,11 +408,11 @@ public class SizePanel extends WizardPanelBase {
CMS.debug("SizePanel: update() NumberFormatException caught: " + e.toString());
context.put("updateStatus", "failure");
throw e;
- } catch (Exception e) {
+ } catch (Exception e) {
CMS.debug("SizePanel: update() Exception caught: " + e.toString());
}
- // generate key pair
+ // generate key pair
Enumeration c = mCerts.elements();
while (c.hasMoreElements()) {
@@ -414,7 +421,7 @@ public class SizePanel extends WizardPanelBase {
String friendlyName = ct;
boolean enable = true;
try {
- enable = config.getBoolean(PCERT_PREFIX+ct+".enable", true);
+ enable = config.getBoolean(PCERT_PREFIX + ct + ".enable", true);
friendlyName = config.getString(PCERT_PREFIX + ct + ".userfriendlyname", ct);
} catch (Exception e) {
}
@@ -425,15 +432,15 @@ public class SizePanel extends WizardPanelBase {
try {
String keytype = config.getString(PCERT_PREFIX + ct + ".keytype");
String keyalgorithm = config.getString(PCERT_PREFIX + ct + ".keyalgorithm");
-
+
if (keytype.equals("rsa")) {
int keysize = config.getInteger(
- PCERT_PREFIX + ct + ".keysize.size");
+ PCERT_PREFIX + ct + ".keysize.size");
createRSAKeyPair(token, keysize, config, ct);
} else {
String curveName = config.getString(
- PCERT_PREFIX + ct + ".curvename.name", default_ecc_curve_name);
+ PCERT_PREFIX + ct + ".curvename.name", default_ecc_curve_name);
createECCKeyPair(token, curveName, config, ct);
}
config.commit(false);
@@ -441,40 +448,39 @@ public class SizePanel extends WizardPanelBase {
CMS.debug(e);
CMS.debug("SizePanel: key generation failure: " + e.toString());
context.put("updateStatus", "failure");
- throw new IOException("key generation failure for the certificate: " + friendlyName +
+ throw new IOException("key generation failure for the certificate: " + friendlyName +
". See the logs for details.");
}
} // while
if (hasErr == false) {
- config.putBoolean("preop.SizePanel.done", true);
- try {
- config.commit(false);
- } catch (EBaseException e) {
- CMS.debug(
- "SizePanel: update() Exception caught at config commit: "
- + e.toString());
- }
- }
+ config.putBoolean("preop.SizePanel.done", true);
+ try {
+ config.commit(false);
+ } catch (EBaseException e) {
+ CMS.debug(
+ "SizePanel: update() Exception caught at config commit: "
+ + e.toString());
+ }
+ }
CMS.debug("SizePanel: update() done");
context.put("updateStatus", "success");
}
- public void createECCKeyPair(String token, String curveName, IConfigStore config, String ct)
- throws NoSuchAlgorithmException, NoSuchTokenException, TokenException, CryptoManager.NotInitializedException
- {
- CMS.debug("Generating ECC key pair with curvename="+ curveName +
- ", token="+token);
+ public void createECCKeyPair(String token, String curveName, IConfigStore config, String ct)
+ throws NoSuchAlgorithmException, NoSuchTokenException, TokenException, CryptoManager.NotInitializedException {
+ CMS.debug("Generating ECC key pair with curvename=" + curveName +
+ ", token=" + token);
KeyPair pair = null;
/*
- * default ssl server cert to ECDHE unless stated otherwise
- * note: IE only supports "ECDHE", but "ECDH" is more efficient
- *
+ * default ssl server cert to ECDHE unless stated otherwise note: IE
+ * only supports "ECDHE", but "ECDH" is more efficient
+ *
* for "ECDHE", server.xml should have the following for ciphers:
* +TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
* -TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
- *
+ *
* for "ECDH", server.xml should have the following for ciphers:
* -TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
* +TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
@@ -488,48 +494,48 @@ public class SizePanel extends WizardPanelBase {
// ECDHE needs "SIGN" but no "DERIVE"
org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage usages_mask[] = {
- org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage.DERIVE
+ org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage.DERIVE
};
// ECDH needs "DERIVE" but no any kind of "SIGN"
org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage ECDH_usages_mask[] = {
- org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage.SIGN,
- org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage.SIGN_RECOVER,
+ org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage.SIGN,
+ org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage.SIGN_RECOVER,
};
do {
- if (ct.equals("sslserver") && sslType.equalsIgnoreCase("ECDH")) {
- CMS.debug("SizePanel: createECCKeypair: sslserver cert for ECDH. Make sure server.xml is set properly with -TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,+TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA");
- pair = CryptoUtil.generateECCKeyPair(token, curveName,
- null,
- ECDH_usages_mask);
- } else {
- if (ct.equals("sslserver")) {
- CMS.debug("SizePanel: createECCKeypair: sslserver cert for ECDHE. Make sure server.xml is set properly with +TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,-TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA");
- }
- pair = CryptoUtil.generateECCKeyPair(token, curveName,
- null,
- usages_mask);
- }
-
- // XXX - store curve , w
- byte id[] = ((org.mozilla.jss.crypto.PrivateKey) pair.getPrivate()).getUniqueID();
- String kid = CryptoUtil.byte2string(id);
- config.putString(PCERT_PREFIX + ct + ".privkey.id", kid);
-
- // try to locate the private key
- org.mozilla.jss.crypto.PrivateKey privk =
- CryptoUtil.findPrivateKeyFromID(CryptoUtil.string2byte(kid));
- if (privk == null) {
- CMS.debug("Found bad ECC key id " + kid);
- pair = null;
+ if (ct.equals("sslserver") && sslType.equalsIgnoreCase("ECDH")) {
+ CMS.debug("SizePanel: createECCKeypair: sslserver cert for ECDH. Make sure server.xml is set properly with -TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,+TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA");
+ pair = CryptoUtil.generateECCKeyPair(token, curveName,
+ null,
+ ECDH_usages_mask);
+ } else {
+ if (ct.equals("sslserver")) {
+ CMS.debug("SizePanel: createECCKeypair: sslserver cert for ECDHE. Make sure server.xml is set properly with +TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,-TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA");
+ }
+ pair = CryptoUtil.generateECCKeyPair(token, curveName,
+ null,
+ usages_mask);
+ }
+
+ // XXX - store curve , w
+ byte id[] = ((org.mozilla.jss.crypto.PrivateKey) pair.getPrivate()).getUniqueID();
+ String kid = CryptoUtil.byte2string(id);
+ config.putString(PCERT_PREFIX + ct + ".privkey.id", kid);
+
+ // try to locate the private key
+ org.mozilla.jss.crypto.PrivateKey privk =
+ CryptoUtil.findPrivateKeyFromID(CryptoUtil.string2byte(kid));
+ if (privk == null) {
+ CMS.debug("Found bad ECC key id " + kid);
+ pair = null;
}
} while (pair == null);
- CMS.debug("Public key class " + pair.getPublic().getClass().getName());
+ CMS.debug("Public key class " + pair.getPublic().getClass().getName());
byte encoded[] = pair.getPublic().getEncoded();
config.putString(PCERT_PREFIX + ct + ".pubkey.encoded",
- CryptoUtil.byte2string(encoded));
+ CryptoUtil.byte2string(encoded));
String keyAlgo = "";
try {
@@ -537,25 +543,24 @@ public class SizePanel extends WizardPanelBase {
} catch (Exception e1) {
}
- setSigningAlgorithm(ct, keyAlgo, config);
+ setSigningAlgorithm(ct, keyAlgo, config);
}
- public void createRSAKeyPair(String token, int keysize, IConfigStore config, String ct)
- throws NoSuchAlgorithmException, NoSuchTokenException, TokenException, CryptoManager.NotInitializedException
- {
+ public void createRSAKeyPair(String token, int keysize, IConfigStore config, String ct)
+ throws NoSuchAlgorithmException, NoSuchTokenException, TokenException, CryptoManager.NotInitializedException {
/* generate key pair */
KeyPair pair = null;
do {
- pair = CryptoUtil.generateRSAKeyPair(token, keysize);
- byte id[] = ((org.mozilla.jss.crypto.PrivateKey) pair.getPrivate()).getUniqueID();
- String kid = CryptoUtil.byte2string(id);
- config.putString(PCERT_PREFIX + ct + ".privkey.id", kid);
- // try to locate the private key
- org.mozilla.jss.crypto.PrivateKey privk =
- CryptoUtil.findPrivateKeyFromID(CryptoUtil.string2byte(kid));
- if (privk == null) {
- CMS.debug("Found bad RSA key id " + kid);
- pair = null;
+ pair = CryptoUtil.generateRSAKeyPair(token, keysize);
+ byte id[] = ((org.mozilla.jss.crypto.PrivateKey) pair.getPrivate()).getUniqueID();
+ String kid = CryptoUtil.byte2string(id);
+ config.putString(PCERT_PREFIX + ct + ".privkey.id", kid);
+ // try to locate the private key
+ org.mozilla.jss.crypto.PrivateKey privk =
+ CryptoUtil.findPrivateKeyFromID(CryptoUtil.string2byte(kid));
+ if (privk == null) {
+ CMS.debug("Found bad RSA key id " + kid);
+ pair = null;
}
} while (pair == null);
@@ -563,9 +568,9 @@ public class SizePanel extends WizardPanelBase {
byte exponent[] = ((RSAPublicKey) pair.getPublic()).getPublicExponent().toByteArray();
config.putString(PCERT_PREFIX + ct + ".pubkey.modulus",
- CryptoUtil.byte2string(modulus));
+ CryptoUtil.byte2string(modulus));
config.putString(PCERT_PREFIX + ct + ".pubkey.exponent",
- CryptoUtil.byte2string(exponent));
+ CryptoUtil.byte2string(exponent));
String keyAlgo = "";
try {
@@ -573,41 +578,40 @@ public class SizePanel extends WizardPanelBase {
} catch (Exception e1) {
}
- setSigningAlgorithm(ct, keyAlgo, config);
+ setSigningAlgorithm(ct, keyAlgo, config);
}
public void setSigningAlgorithm(String ct, String keyAlgo, IConfigStore config) {
String systemType = "";
try {
- systemType = config.getString("preop.system.name");
+ systemType = config.getString("preop.system.name");
} catch (Exception e1) {
}
if (systemType.equalsIgnoreCase("CA")) {
- if (ct.equals("signing")) {
- config.putString("ca.signing.defaultSigningAlgorithm",
+ if (ct.equals("signing")) {
+ config.putString("ca.signing.defaultSigningAlgorithm",
keyAlgo);
- config.putString("ca.crl.MasterCRL.signingAlgorithm",
+ config.putString("ca.crl.MasterCRL.signingAlgorithm",
keyAlgo);
- } else if (ct.equals("ocsp_signing")) {
- config.putString("ca.ocsp_signing.defaultSigningAlgorithm",
+ } else if (ct.equals("ocsp_signing")) {
+ config.putString("ca.ocsp_signing.defaultSigningAlgorithm",
keyAlgo);
- }
+ }
} else if (systemType.equalsIgnoreCase("OCSP")) {
- if (ct.equals("signing")) {
- config.putString("ocsp.signing.defaultSigningAlgorithm",
+ if (ct.equals("signing")) {
+ config.putString("ocsp.signing.defaultSigningAlgorithm",
keyAlgo);
- }
+ }
} else if (systemType.equalsIgnoreCase("KRA") ||
- systemType.equalsIgnoreCase("DRM")) {
- if (ct.equals("transport")) {
+ systemType.equalsIgnoreCase("DRM")) {
+ if (ct.equals("transport")) {
config.putString("kra.transportUnit.signingAlgorithm", keyAlgo);
- }
+ }
}
}
public void initParams(HttpServletRequest request, Context context)
- throws IOException
- {
+ throws IOException {
IConfigStore config = CMS.getConfigStore();
String s = "";
try {
@@ -646,7 +650,7 @@ public class SizePanel extends WizardPanelBase {
HttpServletResponse response,
Context context) {
try {
- initParams(request, context);
+ initParams(request, context);
} catch (IOException e) {
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/TokenAuthenticate.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/TokenAuthenticate.java
index cf59e07c..027ec305 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/TokenAuthenticate.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/TokenAuthenticate.java
@@ -51,6 +51,7 @@ public class TokenAuthenticate extends CMSServlet {
/**
* initialize the servlet.
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -58,13 +59,14 @@ public class TokenAuthenticate extends CMSServlet {
}
/**
- * Process the HTTP request.
+ * Process the HTTP request.
+ *
* @param cmsReq the object holding the request and response information
*/
protected void process(CMSRequest cmsReq) throws EBaseException {
HttpServletRequest httpReq = cmsReq.getHttpReq();
HttpServletResponse httpResp = cmsReq.getHttpResp();
- IConfigStore config = CMS.getConfigStore();
+ IConfigStore config = CMS.getConfigStore();
String sessionId = httpReq.getParameter("sessionID");
CMS.debug("TokenAuthentication: sessionId=" + sessionId);
@@ -85,9 +87,9 @@ public class TokenAuthenticate extends CMSServlet {
CMS.debug("TokenAuthentication: found session");
if (checkIP) {
String hostname = table.getIP(sessionId);
- if (! hostname.equals(givenHost)) {
- CMS.debug("TokenAuthentication: hostname=" + hostname + " and givenHost="
- + givenHost + " are different");
+ if (!hostname.equals(givenHost)) {
+ CMS.debug("TokenAuthentication: hostname=" + hostname + " and givenHost="
+ + givenHost + " are different");
CMS.debug("TokenAuthenticate authenticate failed, wrong hostname.");
outputError(httpResp, "Error: Failed Authentication");
return;
@@ -122,7 +124,15 @@ public class TokenAuthenticate extends CMSServlet {
}
}
- protected void renderResult(CMSRequest cmsReq) throws IOException {// do nothing, ie, it will not return the default javascript.
+ protected void renderResult(CMSRequest cmsReq) throws IOException {// do
+ // nothing,
+ // ie, it
+ // will
+ // not
+ // return
+ // the
+ // default
+ // javascript.
}
/**
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateConnector.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateConnector.java
index cf699c61..f6bd23d1 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateConnector.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateConnector.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.IOException;
import java.util.Enumeration;
import java.util.Locale;
@@ -45,7 +44,6 @@ import com.netscape.cms.servlet.common.CMSRequest;
import com.netscape.cms.servlet.common.ICMSTemplateFiller;
import com.netscape.cmsutil.xml.XMLObject;
-
public class UpdateConnector extends CMSServlet {
/**
@@ -62,6 +60,7 @@ public class UpdateConnector extends CMSServlet {
/**
* initialize the servlet.
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -71,7 +70,7 @@ public class UpdateConnector extends CMSServlet {
}
/**
- * Process the HTTP request.
+ * Process the HTTP request.
*/
protected void process(CMSRequest cmsReq) throws EBaseException {
CMS.debug("UpdateConnector: processing...");
@@ -85,9 +84,9 @@ public class UpdateConnector extends CMSServlet {
CMS.debug("UpdateConnector authentication successful.");
} catch (Exception e) {
CMS.debug("UpdateConnector: authentication failed.");
- log(ILogger.LL_FAILURE,
+ log(ILogger.LL_FAILURE,
CMS.getLogMessage("CMSGW_ERR_BAD_SERV_OUT_STREAM", "",
- e.toString()));
+ e.toString()));
outputError(httpResp, AUTH_FAILURE, "Error: Not authenticated");
return;
}
@@ -100,19 +99,19 @@ public class UpdateConnector extends CMSServlet {
AuthzToken authzToken = null;
try {
- authzToken = authorize(mAclMethod, authToken, mAuthzResourceName,
- "modify");
+ authzToken = authorize(mAclMethod, authToken, mAuthzResourceName,
+ "modify");
CMS.debug("UpdateConnector authorization successful.");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
outputError(httpResp, "Error: Not authorized");
return;
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
outputError(httpResp,
- "Error: Encountered problem during authorization.");
+ "Error: Encountered problem during authorization.");
return;
}
@@ -125,7 +124,7 @@ public class UpdateConnector extends CMSServlet {
Enumeration list = httpReq.getParameterNames();
while (list.hasMoreElements()) {
- String name = (String)list.nextElement();
+ String name = (String) list.nextElement();
String val = httpReq.getParameter(name);
if (name != null && name.startsWith("ca.connector")) {
CMS.debug("Adding connector update name=" + name + " val=" + val);
@@ -134,24 +133,24 @@ public class UpdateConnector extends CMSServlet {
CMS.debug("Skipping connector update name=" + name + " val=" + val);
}
}
-
- try {
+
+ try {
String nickname = cs.getString("ca.subsystem.nickname", "");
String tokenname = cs.getString("ca.subsystem.tokenname", "");
if (!tokenname.equals("Internal Key Storage Token"))
- nickname = tokenname+":"+nickname;
+ nickname = tokenname + ":" + nickname;
cs.putString("ca.connector.KRA.nickName", nickname);
cs.commit(false);
} catch (Exception e) {
}
// start the connector
- try {
+ try {
ICertificateAuthority ca = (ICertificateAuthority)
- CMS.getSubsystem("ca");
- ICAService caService = (ICAService)ca.getCAService();
+ CMS.getSubsystem("ca");
+ ICAService caService = (ICAService) ca.getCAService();
IConnector kraConnector = caService.getConnector(
- cs.getSubStore("ca.connector.KRA"));
+ cs.getSubStore("ca.connector.KRA"));
caService.setKRAConnector(kraConnector);
kraConnector.start();
} catch (Exception e) {
@@ -173,14 +172,23 @@ public class UpdateConnector extends CMSServlet {
}
}
- protected void setDefaultTemplates(ServletConfig sc) {}
+ protected void setDefaultTemplates(ServletConfig sc) {
+ }
protected void renderTemplate(
CMSRequest cmsReq, String templateName, ICMSTemplateFiller filler)
- throws IOException {// do nothing
- }
+ throws IOException {// do nothing
+ }
- protected void renderResult(CMSRequest cmsReq) throws IOException {// do nothing, ie, it will not return the default javascript.
+ protected void renderResult(CMSRequest cmsReq) throws IOException {// do
+ // nothing,
+ // ie, it
+ // will
+ // not
+ // return
+ // the
+ // default
+ // javascript.
}
/**
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateDomainXML.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateDomainXML.java
index c9fe27ef..4ca53eb5 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateDomainXML.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateDomainXML.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
@@ -55,7 +54,6 @@ import com.netscape.cms.servlet.common.CMSRequest;
import com.netscape.cms.servlet.common.ICMSTemplateFiller;
import com.netscape.cmsutil.xml.XMLObject;
-
public class UpdateDomainXML extends CMSServlet {
/**
@@ -65,9 +63,9 @@ public class UpdateDomainXML extends CMSServlet {
private final static String SUCCESS = "0";
private final static String FAILED = "1";
private final static String LOGGING_SIGNED_AUDIT_SECURITY_DOMAIN_UPDATE =
- "LOGGING_SIGNED_AUDIT_SECURITY_DOMAIN_UPDATE_1";
+ "LOGGING_SIGNED_AUDIT_SECURITY_DOMAIN_UPDATE_1";
private final static String LOGGING_SIGNED_AUDIT_CONFIG_ROLE =
- "LOGGING_SIGNED_AUDIT_CONFIG_ROLE_3";
+ "LOGGING_SIGNED_AUDIT_CONFIG_ROLE_3";
public UpdateDomainXML() {
super();
@@ -75,6 +73,7 @@ public class UpdateDomainXML extends CMSServlet {
/**
* initialize the servlet.
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -101,20 +100,19 @@ public class UpdateDomainXML extends CMSServlet {
status = FAILED;
CMS.debug("Failed to delete entry" + e.toString());
}
- } catch (Exception e) {
- CMS.debug("Failed to delete entry" + e.toString());
- } finally {
+ } catch (Exception e) {
+ CMS.debug("Failed to delete entry" + e.toString());
+ } finally {
try {
- if ((conn != null) && (connFactory!= null)) {
+ if ((conn != null) && (connFactory != null)) {
CMS.debug("Releasing ldap connection");
connFactory.returnConn(conn);
}
- }
- catch (Exception e) {
+ } catch (Exception e) {
CMS.debug("Error releasing the ldap connection" + e.toString());
}
- }
- return status;
+ }
+ return status;
}
private String modify_ldap(String dn, LDAPModification mod) {
@@ -135,23 +133,21 @@ public class UpdateDomainXML extends CMSServlet {
status = FAILED;
CMS.debug("Failed to modify entry" + e.toString());
}
- } catch (Exception e) {
+ } catch (Exception e) {
CMS.debug("Failed to modify entry" + e.toString());
- } finally {
+ } finally {
try {
- if ((conn != null) && (connFactory!= null)) {
+ if ((conn != null) && (connFactory != null)) {
CMS.debug("Releasing ldap connection");
connFactory.returnConn(conn);
}
- }
- catch (Exception e) {
+ } catch (Exception e) {
CMS.debug("Error releasing the ldap connection" + e.toString());
}
- }
- return status;
+ }
+ return status;
}
-
private String add_to_ldap(LDAPEntry entry, String dn) {
CMS.debug("UpdateDomainXML: add_to_ldap: starting");
String status = SUCCESS;
@@ -172,37 +168,36 @@ public class UpdateDomainXML extends CMSServlet {
conn.delete(dn);
conn.add(entry);
} catch (LDAPException ee) {
- CMS.debug("UpdateDomainXML: Error when replacing existing entry "+ee.toString());
+ CMS.debug("UpdateDomainXML: Error when replacing existing entry " + ee.toString());
status = FAILED;
}
} else {
- CMS.debug("UpdateDomainXML: Failed to update ldap domain info. Exception: "+e.toString());
+ CMS.debug("UpdateDomainXML: Failed to update ldap domain info. Exception: " + e.toString());
status = FAILED;
}
} catch (Exception e) {
CMS.debug("Failed to add entry" + e.toString());
} finally {
try {
- if ((conn != null) && (connFactory!= null)) {
+ if ((conn != null) && (connFactory != null)) {
CMS.debug("Releasing ldap connection");
connFactory.returnConn(conn);
}
- }
- catch (Exception e) {
+ } catch (Exception e) {
CMS.debug("Error releasing the ldap connection" + e.toString());
}
- }
- return status;
+ }
+ return status;
}
-
-
/**
- * Process the HTTP request.
+ * Process the HTTP request.
* <ul>
* <li>http.param op 'downloadBIN' - return the binary certificate chain
- * <li>http.param op 'displayIND' - display pretty-print of certificate chain components
+ * <li>http.param op 'displayIND' - display pretty-print of certificate
+ * chain components
* </ul>
+ *
* @param cmsReq the object holding the request and response information
*/
protected void process(CMSRequest cmsReq) throws EBaseException {
@@ -219,7 +214,7 @@ public class UpdateDomainXML extends CMSServlet {
authToken = authenticate(cmsReq);
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
outputError(httpResp, AUTH_FAILURE, "Error: Not authenticated");
return;
}
@@ -233,19 +228,19 @@ public class UpdateDomainXML extends CMSServlet {
AuthzToken authzToken = null;
try {
- authzToken = authorize(mAclMethod, authToken, mAuthzResourceName,
- "modify");
+ authzToken = authorize(mAclMethod, authToken, mAuthzResourceName,
+ "modify");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
outputError(httpResp, AUTH_FAILURE, "Error: Not authorized");
return;
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
outputError(httpResp,
- AUTH_FAILURE,
- "Error: Encountered problem during authorization.");
+ AUTH_FAILURE,
+ "Error: Encountered problem during authorization.");
return;
}
if (authzToken == null) {
@@ -272,7 +267,7 @@ public class UpdateDomainXML extends CMSServlet {
String missing = "";
if ((host == null) || host.equals("")) {
missing += " host ";
- }
+ }
if ((name == null) || name.equals("")) {
missing += " name ";
}
@@ -286,20 +281,20 @@ public class UpdateDomainXML extends CMSServlet {
clone = "false";
}
- if (! missing.equals("")) {
- CMS.debug("UpdateDomainXML process: required parameters:" + missing +
+ if (!missing.equals("")) {
+ CMS.debug("UpdateDomainXML process: required parameters:" + missing +
"not provided in request");
- outputError(httpResp, "Error: required parameters: " + missing +
+ outputError(httpResp, "Error: required parameters: " + missing +
"not provided in request");
return;
}
String auditMessage = null;
String auditSubjectID = auditSubjectID();
- String auditParams = "host;;"+host+"+name;;"+name+"+sport;;"+sport+
- "+clone;;"+clone+"+type;;"+type;
+ String auditParams = "host;;" + host + "+name;;" + name + "+sport;;" + sport +
+ "+clone;;" + clone + "+type;;" + type;
if (operation != null) {
- auditParams += "+operation;;"+operation;
+ auditParams += "+operation;;" + operation;
} else {
auditParams += "+operation;;add";
}
@@ -312,8 +307,7 @@ public class UpdateDomainXML extends CMSServlet {
try {
basedn = cs.getString("internaldb.basedn");
secstore = cs.getString("securitydomain.store");
- }
- catch (Exception e) {
+ } catch (Exception e) {
CMS.debug("Unable to determine security domain name or basedn. Please run the domaininfo migration script");
}
@@ -326,7 +320,7 @@ public class UpdateDomainXML extends CMSServlet {
String listName = type + "List";
String cn = host + ":";
- if ((adminsport!= null) && (adminsport != "")) {
+ if ((adminsport != null) && (adminsport != "")) {
cn += adminsport;
} else {
cn += sport;
@@ -361,64 +355,63 @@ public class UpdateDomainXML extends CMSServlet {
attrs.add(new LDAPAttribute("clone", clone.toUpperCase()));
attrs.add(new LDAPAttribute("SubsystemName", name));
entry = new LDAPEntry(dn, attrs);
-
- if ((operation != null) && (operation.equals("remove"))) {
- status = remove_from_ldap(dn);
- String adminUserDN;
- if ((agentsport != null) && (!agentsport.equals(""))) {
- adminUserDN = "uid=" + type + "-" + host + "-" + agentsport + ",ou=People," + basedn;
- } else {
- adminUserDN = "uid=" + type + "-" + host + "-" + sport + ",ou=People," + basedn;
- }
- String userAuditParams = "Scope;;users+Operation;;OP_DELETE+source;;UpdateDomainXML" +
- "+resource;;"+adminUserDN;
- if (status.equals(SUCCESS)) {
- // remove the user for this subsystem's admin
- status2 = remove_from_ldap(adminUserDN);
- if (status2.equals(SUCCESS)) {
- auditMessage = CMS.getLogMessage(
+
+ if ((operation != null) && (operation.equals("remove"))) {
+ status = remove_from_ldap(dn);
+ String adminUserDN;
+ if ((agentsport != null) && (!agentsport.equals(""))) {
+ adminUserDN = "uid=" + type + "-" + host + "-" + agentsport + ",ou=People," + basedn;
+ } else {
+ adminUserDN = "uid=" + type + "-" + host + "-" + sport + ",ou=People," + basedn;
+ }
+ String userAuditParams = "Scope;;users+Operation;;OP_DELETE+source;;UpdateDomainXML" +
+ "+resource;;" + adminUserDN;
+ if (status.equals(SUCCESS)) {
+ // remove the user for this subsystem's admin
+ status2 = remove_from_ldap(adminUserDN);
+ if (status2.equals(SUCCESS)) {
+ auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
auditSubjectID,
ILogger.SUCCESS,
userAuditParams);
- audit(auditMessage);
+ audit(auditMessage);
- // remove this user from the subsystem group
- userAuditParams = "Scope;;groups+Operation;;OP_DELETE_USER" +
+ // remove this user from the subsystem group
+ userAuditParams = "Scope;;groups+Operation;;OP_DELETE_USER" +
"+source;;UpdateDomainXML" +
- "+resource;;Subsystem Group+user;;"+adminUserDN;
- dn = "cn=Subsystem Group, ou=groups," + basedn;
- LDAPModification mod = new LDAPModification(LDAPModification.DELETE,
+ "+resource;;Subsystem Group+user;;" + adminUserDN;
+ dn = "cn=Subsystem Group, ou=groups," + basedn;
+ LDAPModification mod = new LDAPModification(LDAPModification.DELETE,
new LDAPAttribute("uniqueMember", adminUserDN));
- status2 = modify_ldap(dn, mod);
- if (status2.equals(SUCCESS)) {
- auditMessage = CMS.getLogMessage(
+ status2 = modify_ldap(dn, mod);
+ if (status2.equals(SUCCESS)) {
+ auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
auditSubjectID,
ILogger.SUCCESS,
userAuditParams);
- } else {
- auditMessage = CMS.getLogMessage(
+ } else {
+ auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
auditSubjectID,
ILogger.FAILURE,
userAuditParams);
- }
- audit(auditMessage);
- } else { // error deleting user
- auditMessage = CMS.getLogMessage(
+ }
+ audit(auditMessage);
+ } else { // error deleting user
+ auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
auditSubjectID,
ILogger.FAILURE,
userAuditParams);
- audit(auditMessage);
- }
+ audit(auditMessage);
}
+ }
} else {
- status = add_to_ldap(entry, dn);
+ status = add_to_ldap(entry, dn);
}
- }
- else {
+ } else {
// update the domain.xml file
String path = CMS.getConfigStore().getString("instanceRoot", "")
+ "/conf/domain.xml";
@@ -430,7 +423,7 @@ public class UpdateDomainXML extends CMSServlet {
CMS.debug("UpdateDomainXML: Inserting new domain info");
XMLObject parser = new XMLObject(new FileInputStream(path));
Node n = parser.getContainer(list);
- int count =0;
+ int count = 0;
if ((operation != null) && (operation.equals("remove"))) {
// delete node
@@ -444,11 +437,11 @@ public class UpdateDomainXML extends CMSServlet {
Vector v_host = parser.getValuesFromContainer(nn, "Host");
Vector v_adminport = parser.getValuesFromContainer(nn, "SecureAdminPort");
if ((v_name.elementAt(0).equals(name)) && (v_host.elementAt(0).equals(host))
- && (v_adminport.elementAt(0).equals(adminsport))) {
- Node parent = nn.getParentNode();
- Node remNode = parent.removeChild(nn);
- count --;
- break;
+ && (v_adminport.elementAt(0).equals(adminsport))) {
+ Node parent = nn.getParentNode();
+ Node remNode = parent.removeChild(nn);
+ count--;
+ break;
}
}
} else {
@@ -463,33 +456,33 @@ public class UpdateDomainXML extends CMSServlet {
parser.addItemToContainer(parent, "UnSecurePort", httpport);
parser.addItemToContainer(parent, "DomainManager", domainmgr.toUpperCase());
parser.addItemToContainer(parent, "Clone", clone.toUpperCase());
- count ++;
+ count++;
}
- //update count
+ // update count
String countS = "";
NodeList nlist = n.getChildNodes();
Node countnode = null;
- for (int i=0; i<nlist.getLength(); i++) {
- Element nn = (Element)nlist.item(i);
+ for (int i = 0; i < nlist.getLength(); i++) {
+ Element nn = (Element) nlist.item(i);
String tagname = nn.getTagName();
if (tagname.equals("SubsystemCount")) {
countnode = nn;
NodeList nlist1 = nn.getChildNodes();
Node nn1 = nlist1.item(0);
- countS = nn1.getNodeValue();
+ countS = nn1.getNodeValue();
break;
}
}
- CMS.debug("UpdateDomainXML process: SubsystemCount="+countS);
+ CMS.debug("UpdateDomainXML process: SubsystemCount=" + countS);
try {
- count += Integer.parseInt(countS);
+ count += Integer.parseInt(countS);
} catch (Exception ee) {
}
Node nn2 = n.removeChild(countnode);
- parser.addItemToContainer(n, "SubsystemCount", ""+count);
+ parser.addItemToContainer(n, "SubsystemCount", "" + count);
// recreate domain.xml
CMS.debug("UpdateDomainXML: Recreating domain.xml");
@@ -503,7 +496,7 @@ public class UpdateDomainXML extends CMSServlet {
}
}
-
+
if (status.equals(SUCCESS)) {
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_SECURITY_DOMAIN_UPDATE,
@@ -520,11 +513,11 @@ public class UpdateDomainXML extends CMSServlet {
}
audit(auditMessage);
- if (status.equals(SUCCESS) && status2.equals(SUCCESS)) {
- status = SUCCESS;
- } else {
- status = FAILED;
- }
+ if (status.equals(SUCCESS) && status2.equals(SUCCESS)) {
+ status = SUCCESS;
+ } else {
+ status = FAILED;
+ }
try {
// send success status back to the requestor
@@ -537,24 +530,34 @@ public class UpdateDomainXML extends CMSServlet {
outputResult(httpResp, "application/xml", cb);
} catch (Exception e) {
- CMS.debug("UpdateDomainXML: Failed to send the XML output" + e.toString());
+ CMS.debug("UpdateDomainXML: Failed to send the XML output" + e.toString());
}
}
protected String securityDomainXMLtoLDAP(String xmltag) {
- if (xmltag.equals("Host")) return "host";
- else return xmltag;
+ if (xmltag.equals("Host"))
+ return "host";
+ else
+ return xmltag;
}
-
- protected void setDefaultTemplates(ServletConfig sc) {}
+ protected void setDefaultTemplates(ServletConfig sc) {
+ }
protected void renderTemplate(
CMSRequest cmsReq, String templateName, ICMSTemplateFiller filler)
- throws IOException {// do nothing
- }
+ throws IOException {// do nothing
+ }
- protected void renderResult(CMSRequest cmsReq) throws IOException {// do nothing, ie, it will not return the default javascript.
+ protected void renderResult(CMSRequest cmsReq) throws IOException {// do
+ // nothing,
+ // ie, it
+ // will
+ // not
+ // return
+ // the
+ // default
+ // javascript.
}
/**
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateNumberRange.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateNumberRange.java
index 0a1787aa..c0d0db10 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateNumberRange.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateNumberRange.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.IOException;
import java.math.BigInteger;
import java.util.Locale;
@@ -45,7 +44,6 @@ import com.netscape.cms.servlet.common.CMSRequest;
import com.netscape.cms.servlet.common.ICMSTemplateFiller;
import com.netscape.cmsutil.xml.XMLObject;
-
public class UpdateNumberRange extends CMSServlet {
/**
@@ -56,7 +54,7 @@ public class UpdateNumberRange extends CMSServlet {
private final static String FAILED = "1";
private final static String AUTH_FAILURE = "2";
private final static String LOGGING_SIGNED_AUDIT_CONFIG_SERIAL_NUMBER =
- "LOGGING_SIGNED_AUDIT_CONFIG_SERIAL_NUMBER_1";
+ "LOGGING_SIGNED_AUDIT_CONFIG_SERIAL_NUMBER_1";
public UpdateNumberRange() {
super();
@@ -64,6 +62,7 @@ public class UpdateNumberRange extends CMSServlet {
/**
* initialize the servlet.
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -73,11 +72,13 @@ public class UpdateNumberRange extends CMSServlet {
}
/**
- * Process the HTTP request.
+ * Process the HTTP request.
* <ul>
* <li>http.param op 'downloadBIN' - return the binary certificate chain
- * <li>http.param op 'displayIND' - display pretty-print of certificate chain components
+ * <li>http.param op 'displayIND' - display pretty-print of certificate
+ * chain components
* </ul>
+ *
* @param cmsReq the object holding the request and response information
*/
protected void process(CMSRequest cmsReq) throws EBaseException {
@@ -96,18 +97,18 @@ public class UpdateNumberRange extends CMSServlet {
AuthzToken authzToken = null;
try {
- authzToken = authorize(mAclMethod, authToken, mAuthzResourceName,
- "modify");
+ authzToken = authorize(mAclMethod, authToken, mAuthzResourceName,
+ "modify");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
outputError(httpResp, "Error: Not authorized");
return;
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
outputError(httpResp,
- "Error: Encountered problem during authorization.");
+ "Error: Encountered problem during authorization.");
return;
}
if (authzToken == null) {
@@ -131,13 +132,13 @@ public class UpdateNumberRange extends CMSServlet {
BigInteger oneNum = new BigInteger("1");
String endNumConfig = null;
String cloneNumConfig = null;
- String nextEndConfig = null;
+ String nextEndConfig = null;
int radix = 10;
IRepository repo = null;
if (cstype.equals("KRA")) {
IKeyRecoveryAuthority kra = (IKeyRecoveryAuthority) CMS.getSubsystem(
- IKeyRecoveryAuthority.ID);
+ IKeyRecoveryAuthority.ID);
if (type.equals("request")) {
repo = kra.getRequestQueue().getRequestRepository();
} else if (type.equals("serialNo")) {
@@ -147,7 +148,7 @@ public class UpdateNumberRange extends CMSServlet {
}
} else { // CA
ICertificateAuthority ca = (ICertificateAuthority) CMS.getSubsystem(
- ICertificateAuthority.ID);
+ ICertificateAuthority.ID);
if (type.equals("request")) {
repo = ca.getRequestQueue().getRequestRepository();
} else if (type.equals("serialNo")) {
@@ -157,26 +158,28 @@ public class UpdateNumberRange extends CMSServlet {
}
}
- // checkRanges for replicaID - we do this each time a replica is created.
- // This needs to be done beforehand to ensure that we always have enough
+ // checkRanges for replicaID - we do this each time a replica is
+ // created.
+ // This needs to be done beforehand to ensure that we always have
+ // enough
// replica numbers
if (type.equals("replicaId")) {
- CMS.debug("Checking replica number ranges");
- repo.checkRanges();
+ CMS.debug("Checking replica number ranges");
+ repo.checkRanges();
}
-
+
if (type.equals("request")) {
radix = 10;
endNumConfig = "dbs.endRequestNumber";
cloneNumConfig = "dbs.requestCloneTransferNumber";
nextEndConfig = "dbs.nextEndRequestNumber";
} else if (type.equals("serialNo")) {
- radix=16;
+ radix = 16;
endNumConfig = "dbs.endSerialNumber";
cloneNumConfig = "dbs.serialCloneTransferNumber";
nextEndConfig = "dbs.nextEndSerialNumber";
} else if (type.equals("replicaId")) {
- radix=10;
+ radix = 10;
endNumConfig = "dbs.endReplicaNumber";
cloneNumConfig = "dbs.replicaCloneTransferNumber";
nextEndConfig = "dbs.nextEndReplicaNumber";
@@ -192,11 +195,11 @@ public class UpdateNumberRange extends CMSServlet {
String nextEndNumStr = cs.getString(nextEndConfig, "");
BigInteger endNum2 = new BigInteger(nextEndNumStr, radix);
CMS.debug("Transferring from the end of on-deck range");
- String newValStr = endNum2.subtract(decrement).toString(radix);
- repo.setNextMaxSerial(newValStr);
- cs.putString(nextEndConfig, newValStr);
- beginNum = endNum2.subtract(decrement).add(oneNum);
- endNum = endNum2;
+ String newValStr = endNum2.subtract(decrement).toString(radix);
+ repo.setNextMaxSerial(newValStr);
+ cs.putString(nextEndConfig, newValStr);
+ beginNum = endNum2.subtract(decrement).add(oneNum);
+ endNum = endNum2;
} else {
CMS.debug("Transferring from the end of the current range");
String newValStr = beginNum.subtract(oneNum).toString(radix);
@@ -204,10 +207,9 @@ public class UpdateNumberRange extends CMSServlet {
cs.putString(endNumConfig, newValStr);
}
-
- if( beginNum == null ) {
- CMS.debug( "UpdateNumberRange::process() - " +
- "beginNum is null!" );
+ if (beginNum == null) {
+ CMS.debug("UpdateNumberRange::process() - " +
+ "beginNum is null!");
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CONFIG_SERIAL_NUMBER,
auditSubjectID,
@@ -219,7 +221,7 @@ public class UpdateNumberRange extends CMSServlet {
// Enable serial number management in master for certs and requests
if (type.equals("replicaId")) {
- repo.setEnableSerialMgmt(true);
+ repo.setEnableSerialMgmt(true);
}
// insert info
@@ -248,7 +250,7 @@ public class UpdateNumberRange extends CMSServlet {
audit(auditMessage);
} catch (Exception e) {
- CMS.debug("UpdateNumberRange: Failed to update number range. Exception: "+e.toString());
+ CMS.debug("UpdateNumberRange: Failed to update number range. Exception: " + e.toString());
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CONFIG_SERIAL_NUMBER,
@@ -261,14 +263,23 @@ public class UpdateNumberRange extends CMSServlet {
}
}
- protected void setDefaultTemplates(ServletConfig sc) {}
+ protected void setDefaultTemplates(ServletConfig sc) {
+ }
protected void renderTemplate(
CMSRequest cmsReq, String templateName, ICMSTemplateFiller filler)
- throws IOException {// do nothing
- }
+ throws IOException {// do nothing
+ }
- protected void renderResult(CMSRequest cmsReq) throws IOException {// do nothing, ie, it will not return the default javascript.
+ protected void renderResult(CMSRequest cmsReq) throws IOException {// do
+ // nothing,
+ // ie, it
+ // will
+ // not
+ // return
+ // the
+ // default
+ // javascript.
}
/**
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateOCSPConfig.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateOCSPConfig.java
index 2339c4c7..10161f1b 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateOCSPConfig.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateOCSPConfig.java
@@ -40,7 +40,6 @@ import com.netscape.cms.servlet.common.CMSRequest;
import com.netscape.cms.servlet.common.ICMSTemplateFiller;
import com.netscape.cmsutil.xml.XMLObject;
-
public class UpdateOCSPConfig extends CMSServlet {
/**
@@ -57,6 +56,7 @@ public class UpdateOCSPConfig extends CMSServlet {
/**
* initialize the servlet.
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -81,18 +81,18 @@ public class UpdateOCSPConfig extends CMSServlet {
AuthzToken authzToken = null;
try {
- authzToken = authorize(mAclMethod, authToken, mAuthzResourceName,
- "modify");
+ authzToken = authorize(mAclMethod, authToken, mAuthzResourceName,
+ "modify");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
outputError(httpResp, "Error: Not authorized");
return;
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
outputError(httpResp,
- "Error: Encountered problem during authorization.");
+ "Error: Encountered problem during authorization.");
return;
}
if (authzToken == null) {
@@ -108,31 +108,31 @@ public class UpdateOCSPConfig extends CMSServlet {
nickname = cs.getString("ca.subsystem.nickname", "");
String tokenname = cs.getString("ca.subsystem.tokenname", "");
if (!tokenname.equals("internal") && !tokenname.equals("Internal Key Storage Token"))
- nickname = tokenname+":"+nickname;
+ nickname = tokenname + ":" + nickname;
} catch (Exception e) {
}
- CMS.debug("UpdateOCSPConfig process: nickname="+nickname);
+ CMS.debug("UpdateOCSPConfig process: nickname=" + nickname);
String ocsphost = httpReq.getParameter("ocsp_host");
String ocspport = httpReq.getParameter("ocsp_port");
try {
cs.putString("ca.publish.enable", "true");
- cs.putString("ca.publish.publisher.instance.OCSPPublisher.host",
- ocsphost);
- cs.putString("ca.publish.publisher.instance.OCSPPublisher.port",
- ocspport);
- cs.putString("ca.publish.publisher.instance.OCSPPublisher.nickName",
- nickname);
+ cs.putString("ca.publish.publisher.instance.OCSPPublisher.host",
+ ocsphost);
+ cs.putString("ca.publish.publisher.instance.OCSPPublisher.port",
+ ocspport);
+ cs.putString("ca.publish.publisher.instance.OCSPPublisher.nickName",
+ nickname);
cs.putString("ca.publish.publisher.instance.OCSPPublisher.path",
- "/ocsp/agent/ocsp/addCRL");
+ "/ocsp/agent/ocsp/addCRL");
cs.putString("ca.publish.publisher.instance.OCSPPublisher.pluginName", "OCSPPublisher");
cs.putString("ca.publish.publisher.instance.OCSPPublisher.enableClientAuth", "true");
cs.putString("ca.publish.rule.instance.ocsprule.enable", "true");
cs.putString("ca.publish.rule.instance.ocsprule.mapper", "NoMap");
cs.putString("ca.publish.rule.instance.ocsprule.pluginName", "Rule");
- cs.putString("ca.publish.rule.instance.ocsprule.publisher",
- "OCSPPublisher");
+ cs.putString("ca.publish.rule.instance.ocsprule.publisher",
+ "OCSPPublisher");
cs.putString("ca.publish.rule.instance.ocsprule.type", "crl");
cs.commit(false);
// insert info
@@ -147,19 +147,28 @@ public class UpdateOCSPConfig extends CMSServlet {
outputResult(httpResp, "application/xml", cb);
} catch (Exception e) {
- CMS.debug("UpdateOCSPConfig: Failed to update OCSP configuration. Exception: "+e.toString());
+ CMS.debug("UpdateOCSPConfig: Failed to update OCSP configuration. Exception: " + e.toString());
outputError(httpResp, "Error: Failed to update OCSP configuration.");
}
}
- protected void setDefaultTemplates(ServletConfig sc) {}
+ protected void setDefaultTemplates(ServletConfig sc) {
+ }
protected void renderTemplate(
CMSRequest cmsReq, String templateName, ICMSTemplateFiller filler)
- throws IOException {// do nothing
- }
+ throws IOException {// do nothing
+ }
- protected void renderResult(CMSRequest cmsReq) throws IOException {// do nothing, ie, it will not return the default javascript.
+ protected void renderResult(CMSRequest cmsReq) throws IOException {// do
+ // nothing,
+ // ie, it
+ // will
+ // not
+ // return
+ // the
+ // default
+ // javascript.
}
/**
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/WelcomePanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/WelcomePanel.java
index 7b1c9959..4224c4eb 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/WelcomePanel.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/WelcomePanel.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.IOException;
import javax.servlet.ServletConfig;
@@ -35,13 +34,14 @@ import com.netscape.cms.servlet.wizard.WizardServlet;
public class WelcomePanel extends WizardPanelBase {
- public WelcomePanel() {}
+ public WelcomePanel() {
+ }
/**
* Initializes this panel.
*/
- public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
- throws ServletException {
+ public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
+ throws ServletException {
setPanelNo(panelno);
setName("Welcome");
setId(id);
@@ -52,19 +52,20 @@ public class WelcomePanel extends WizardPanelBase {
cs.putBoolean("preop.welcome.done", false);
}
- public boolean isPanelDone() {
+ public boolean isPanelDone() {
IConfigStore cs = CMS.getConfigStore();
try {
return cs.getBoolean("preop.welcome.done");
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
return false;
}
public PropertySet getUsage() {
PropertySet set = new PropertySet();
-
+
/* XXX */
-
+
return set;
}
@@ -80,7 +81,7 @@ public class WelcomePanel extends WizardPanelBase {
try {
context.put("cstype", cs.getString("cs.type"));
context.put("wizardname", cs.getString("preop.wizard.name"));
- context.put("panelname",
+ context.put("panelname",
cs.getString("preop.system.fullname") + " Configuration Wizard");
context.put("systemname",
cs.getString("preop.system.name"));
@@ -90,7 +91,8 @@ public class WelcomePanel extends WizardPanelBase {
cs.getString("preop.product.name"));
context.put("productversion",
cs.getString("preop.product.version"));
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
context.put("panel", "admin/console/config/welcomepanel.vm");
}
@@ -112,7 +114,8 @@ public class WelcomePanel extends WizardPanelBase {
try {
cs.putBoolean("preop.welcome.done", true);
cs.commit(false);
- } catch (EBaseException e) {}
+ } catch (EBaseException e) {
+ }
}
/**
@@ -120,5 +123,6 @@ public class WelcomePanel extends WizardPanelBase {
*/
public void displayError(HttpServletRequest request,
HttpServletResponse response,
- Context context) {/* This should never be called */}
+ Context context) {/* This should never be called */
+ }
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/WelcomeServlet.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/WelcomeServlet.java
index 06eb63ff..f5a96bc8 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/WelcomeServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/WelcomeServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -25,7 +24,6 @@ import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;
-
public class WelcomeServlet extends BaseServlet {
/**
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/WizardPanelBase.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/WizardPanelBase.java
index a2a7d5df..70b427e5 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/csadmin/WizardPanelBase.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/WizardPanelBase.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;
-
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.ConnectException;
@@ -79,8 +78,8 @@ public class WizardPanelBase implements IWizardPanel {
public static final String PRE_CONF_AGENT_GROUP = "preop.admin.group";
/**
- * Definition for "preop" static variables in CS.cfg
- * -- "preop" config parameters should not assumed to exist after configuation
+ * Definition for "preop" static variables in CS.cfg -- "preop" config
+ * parameters should not assumed to exist after configuation
*/
public static final String PRE_CONF_CA_TOKEN = "preop.module.token";
@@ -95,15 +94,13 @@ public class WizardPanelBase implements IWizardPanel {
/**
* Initializes this panel.
*/
- public void init(ServletConfig config, int panelno)
- throws ServletException
- {
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
mPanelNo = panelno;
}
- public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
- throws ServletException
- {
+ public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
+ throws ServletException {
mPanelNo = panelno;
}
@@ -142,7 +139,7 @@ public class WizardPanelBase implements IWizardPanel {
return set;
}
-
+
/**
* Should we skip this panel?
*/
@@ -187,7 +184,8 @@ public class WizardPanelBase implements IWizardPanel {
*/
public void display(HttpServletRequest request,
HttpServletResponse response,
- Context context) {}
+ Context context) {
+ }
/**
* Checks if the given parameters are valid.
@@ -202,14 +200,16 @@ public class WizardPanelBase implements IWizardPanel {
*/
public void update(HttpServletRequest request,
HttpServletResponse response,
- Context context) throws IOException {}
+ Context context) throws IOException {
+ }
/**
* If validiate() returns false, this method will be called.
*/
public void displayError(HttpServletRequest request,
HttpServletResponse response,
- Context context) {}
+ Context context) {
+ }
/**
* Retrieves locale based on the request.
@@ -233,7 +233,8 @@ public class WizardPanelBase implements IWizardPanel {
try {
instanceID = config.getString("instanceId", "");
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
String nickname = certTag + "Cert cert-" + instanceID;
String preferredNickname = null;
@@ -241,7 +242,8 @@ public class WizardPanelBase implements IWizardPanel {
try {
preferredNickname = config.getString(
PCERT_PREFIX + certTag + ".nickname", null);
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
if (preferredNickname != null) {
nickname = preferredNickname;
@@ -250,7 +252,7 @@ public class WizardPanelBase implements IWizardPanel {
}
public void updateDomainXML(String hostname, int port, boolean https,
- String servlet, String uri) throws IOException {
+ String servlet, String uri) throws IOException {
CMS.debug("WizardPanelBase updateDomainXML start hostname=" + hostname + " port=" + port);
IConfigStore cs = CMS.getConfigStore();
String nickname = "";
@@ -258,17 +260,18 @@ public class WizardPanelBase implements IWizardPanel {
try {
nickname = cs.getString("preop.cert.subsystem.nickname", "");
tokenname = cs.getString("preop.module.token", "");
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
if (!tokenname.equals("") &&
- !tokenname.equals("Internal Key Storage Token") &&
- !tokenname.equals("internal")) {
- nickname = tokenname+":"+nickname;
+ !tokenname.equals("Internal Key Storage Token") &&
+ !tokenname.equals("internal")) {
+ nickname = tokenname + ":" + nickname;
}
CMS.debug("WizardPanelBase updateDomainXML nickname=" + nickname);
CMS.debug("WizardPanelBase: start sending updateDomainXML request");
- String c = getHttpResponse(hostname, port, https, servlet, uri, nickname);
+ String c = getHttpResponse(hostname, port, https, servlet, uri, nickname);
CMS.debug("WizardPanelBase: done sending updateDomainXML request");
if (c != null) {
@@ -278,9 +281,9 @@ public class WizardPanelBase implements IWizardPanel {
try {
obj = new XMLObject(bis);
} catch (Exception e) {
- CMS.debug( "WizardPanelBase::updateDomainXML() - "
- + "Exception="+e.toString() );
- throw new IOException( e.toString() );
+ CMS.debug("WizardPanelBase::updateDomainXML() - "
+ + "Exception=" + e.toString());
+ throw new IOException(e.toString());
}
String status = obj.getValue("Status");
@@ -291,7 +294,7 @@ public class WizardPanelBase implements IWizardPanel {
} else {
String error = obj.getValue("Error");
throw new IOException(error);
- }
+ }
} catch (IOException e) {
CMS.debug("WizardPanelBase: updateDomainXML: " + e.toString());
throw e;
@@ -302,8 +305,8 @@ public class WizardPanelBase implements IWizardPanel {
}
}
- public int getSubsystemCount( String hostname, int https_admin_port,
- boolean https, String type )
+ public int getSubsystemCount(String hostname, int https_admin_port,
+ boolean https, String type)
throws IOException {
CMS.debug("WizardPanelBase getSubsystemCount start");
String c = getDomainXML(hostname, https_admin_port, true);
@@ -311,12 +314,12 @@ public class WizardPanelBase implements IWizardPanel {
try {
ByteArrayInputStream bis = new ByteArrayInputStream(c.getBytes());
XMLObject obj = new XMLObject(bis);
- String containerName = type+"List";
+ String containerName = type + "List";
Node n = obj.getContainer(containerName);
NodeList nlist = n.getChildNodes();
String countS = "";
- for (int i=0; i<nlist.getLength(); i++) {
- Element nn = (Element)nlist.item(i);
+ for (int i = 0; i < nlist.getLength(); i++) {
+ Element nn = (Element) nlist.item(i);
String tagname = nn.getTagName();
if (tagname.equals("SubsystemCount")) {
NodeList nlist1 = nn.getChildNodes();
@@ -325,7 +328,7 @@ public class WizardPanelBase implements IWizardPanel {
break;
}
}
- CMS.debug("WizardPanelBase getSubsystemCount: SubsystemCount="+countS);
+ CMS.debug("WizardPanelBase getSubsystemCount: SubsystemCount=" + countS);
int num = 0;
if (countS != null && !countS.equals("")) {
@@ -337,7 +340,7 @@ public class WizardPanelBase implements IWizardPanel {
return num;
} catch (Exception e) {
- CMS.debug("WizardPanelBase: getSubsystemCount: "+e.toString());
+ CMS.debug("WizardPanelBase: getSubsystemCount: " + e.toString());
throw new IOException(e.toString());
}
}
@@ -345,12 +348,12 @@ public class WizardPanelBase implements IWizardPanel {
return -1;
}
- public String getDomainXML( String hostname, int https_admin_port,
- boolean https )
+ public String getDomainXML(String hostname, int https_admin_port,
+ boolean https)
throws IOException {
CMS.debug("WizardPanelBase getDomainXML start");
- String c = getHttpResponse( hostname, https_admin_port, https,
- "/ca/admin/ca/getDomainXML", null, null );
+ String c = getHttpResponse(hostname, https_admin_port, https,
+ "/ca/admin/ca/getDomainXML", null, null);
if (c != null) {
try {
ByteArrayInputStream bis = new ByteArrayInputStream(c.getBytes());
@@ -359,9 +362,9 @@ public class WizardPanelBase implements IWizardPanel {
try {
parser = new XMLObject(bis);
} catch (Exception e) {
- CMS.debug( "WizardPanelBase::getDomainXML() - "
- + "Exception="+e.toString() );
- throw new IOException( e.toString() );
+ CMS.debug("WizardPanelBase::getDomainXML() - "
+ + "Exception=" + e.toString());
+ throw new IOException(e.toString());
}
String status = parser.getValue("Status");
@@ -374,12 +377,12 @@ public class WizardPanelBase implements IWizardPanel {
CMS.debug(
"WizardPanelBase getDomainXML: domainInfo="
+ domainInfo);
- return domainInfo;
+ return domainInfo;
} else {
String error = parser.getValue("Error");
throw new IOException(error);
- }
+ }
} catch (IOException e) {
CMS.debug("WizardPanelBase: getDomainXML: " + e.toString());
throw e;
@@ -392,29 +395,29 @@ public class WizardPanelBase implements IWizardPanel {
return null;
}
- public String getSubsystemCert(String host, int port, boolean https)
- throws IOException {
+ public String getSubsystemCert(String host, int port, boolean https)
+ throws IOException {
CMS.debug("WizardPanelBase getSubsystemCert start");
- String c = getHttpResponse(host, port, https,
- "/ca/admin/ca/getSubsystemCert", null, null);
+ String c = getHttpResponse(host, port, https,
+ "/ca/admin/ca/getSubsystemCert", null, null);
if (c != null) {
try {
- ByteArrayInputStream bis =
- new ByteArrayInputStream(c.getBytes());
+ ByteArrayInputStream bis =
+ new ByteArrayInputStream(c.getBytes());
XMLObject parser = null;
try {
parser = new XMLObject(bis);
} catch (Exception e) {
- CMS.debug( "WizardPanelBase::getSubsystemCert() - "
- + "Exception="+e.toString() );
- throw new IOException( e.toString() );
+ CMS.debug("WizardPanelBase::getSubsystemCert() - "
+ + "Exception=" + e.toString());
+ throw new IOException(e.toString());
}
String status = parser.getValue("Status");
if (status.equals(SUCCESS)) {
String s = parser.getValue("Cert");
return s;
} else
- return null;
+ return null;
} catch (Exception e) {
}
}
@@ -423,10 +426,10 @@ public class WizardPanelBase implements IWizardPanel {
}
public void updateConnectorInfo(String host, int port, boolean https,
- String content) throws IOException {
+ String content) throws IOException {
CMS.debug("WizardPanelBase updateConnectorInfo start");
- String c = getHttpResponse(host, port, https,
- "/ca/admin/ca/updateConnector", content, null);
+ String c = getHttpResponse(host, port, https,
+ "/ca/admin/ca/updateConnector", content, null);
if (c != null) {
try {
ByteArrayInputStream bis = new ByteArrayInputStream(c.getBytes());
@@ -435,9 +438,9 @@ public class WizardPanelBase implements IWizardPanel {
try {
parser = new XMLObject(bis);
} catch (Exception e) {
- CMS.debug( "WizardPanelBase::updateConnectorInfo() - "
- + "Exception="+e.toString() );
- throw new IOException( e.toString() );
+ CMS.debug("WizardPanelBase::updateConnectorInfo() - "
+ + "Exception=" + e.toString());
+ throw new IOException(e.toString());
}
String status = parser.getValue("Status");
@@ -447,7 +450,7 @@ public class WizardPanelBase implements IWizardPanel {
if (!status.equals(SUCCESS)) {
String error = parser.getValue("Error");
throw new IOException(error);
- }
+ }
} catch (IOException e) {
CMS.debug("WizardPanelBase: updateConnectorInfo: " + e.toString());
throw e;
@@ -458,16 +461,16 @@ public class WizardPanelBase implements IWizardPanel {
}
}
- public String getCertChainUsingSecureAdminPort( String hostname,
+ public String getCertChainUsingSecureAdminPort(String hostname,
int https_admin_port,
boolean https,
ConfigCertApprovalCallback
- certApprovalCallback )
+ certApprovalCallback)
throws IOException {
CMS.debug("WizardPanelBase getCertChainUsingSecureAdminPort start");
- String c = getHttpResponse( hostname, https_admin_port, https,
+ String c = getHttpResponse(hostname, https_admin_port, https,
"/ca/admin/ca/getCertChain", null, null,
- certApprovalCallback );
+ certApprovalCallback);
if (c != null) {
try {
@@ -477,9 +480,9 @@ public class WizardPanelBase implements IWizardPanel {
try {
parser = new XMLObject(bis);
} catch (Exception e) {
- CMS.debug( "WizardPanelBase::getCertChainUsingSecureAdminPort() - "
- + "Exception="+e.toString() );
- throw new IOException( e.toString() );
+ CMS.debug("WizardPanelBase::getCertChainUsingSecureAdminPort() - "
+ + "Exception=" + e.toString());
+ throw new IOException(e.toString());
}
String status = parser.getValue("Status");
@@ -493,12 +496,12 @@ public class WizardPanelBase implements IWizardPanel {
CMS.debug(
"WizardPanelBase getCertChainUsingSecureAdminPort: certchain="
+ certchain);
- return certchain;
+ return certchain;
} else {
String error = parser.getValue("Error");
throw new IOException(error);
- }
+ }
} catch (IOException e) {
CMS.debug("WizardPanelBase: getCertChainUsingSecureAdminPort: " + e.toString());
throw e;
@@ -511,16 +514,16 @@ public class WizardPanelBase implements IWizardPanel {
return null;
}
- public String getCertChainUsingSecureEEPort( String hostname,
+ public String getCertChainUsingSecureEEPort(String hostname,
int https_ee_port,
boolean https,
ConfigCertApprovalCallback
- certApprovalCallback )
+ certApprovalCallback)
throws IOException {
CMS.debug("WizardPanelBase getCertChainUsingSecureEEPort start");
- String c = getHttpResponse( hostname, https_ee_port, https,
+ String c = getHttpResponse(hostname, https_ee_port, https,
"/ca/ee/ca/getCertChain", null, null,
- certApprovalCallback );
+ certApprovalCallback);
if (c != null) {
try {
@@ -530,9 +533,9 @@ public class WizardPanelBase implements IWizardPanel {
try {
parser = new XMLObject(bis);
} catch (Exception e) {
- CMS.debug( "WizardPanelBase::getCertChainUsingSecureEEPort() - "
- + "Exception="+e.toString() );
- throw new IOException( e.toString() );
+ CMS.debug("WizardPanelBase::getCertChainUsingSecureEEPort() - "
+ + "Exception=" + e.toString());
+ throw new IOException(e.toString());
}
String status = parser.getValue("Status");
@@ -546,12 +549,12 @@ public class WizardPanelBase implements IWizardPanel {
CMS.debug(
"WizardPanelBase getCertChainUsingSecureEEPort: certchain="
+ certchain);
- return certchain;
+ return certchain;
} else {
String error = parser.getValue("Error");
throw new IOException(error);
- }
+ }
} catch (IOException e) {
CMS.debug("WizardPanelBase: getCertChainUsingSecureEEPort: " + e.toString());
throw e;
@@ -565,8 +568,8 @@ public class WizardPanelBase implements IWizardPanel {
}
public boolean updateConfigEntries(String hostname, int port, boolean https,
- String servlet, String uri, IConfigStore config,
- HttpServletResponse response) throws IOException {
+ String servlet, String uri, IConfigStore config,
+ HttpServletResponse response) throws IOException {
CMS.debug("WizardPanelBase updateConfigEntries start");
String c = getHttpResponse(hostname, port, https, servlet, uri, null);
@@ -578,9 +581,9 @@ public class WizardPanelBase implements IWizardPanel {
try {
parser = new XMLObject(bis);
} catch (Exception e) {
- CMS.debug( "WizardPanelBase::updateConfigEntries() - "
- + "Exception="+e.toString() );
- throw new IOException( e.toString() );
+ CMS.debug("WizardPanelBase::updateConfigEntries() - "
+ + "Exception=" + e.toString());
+ throw new IOException(e.toString());
}
String status = parser.getValue("Status");
@@ -594,11 +597,11 @@ public class WizardPanelBase implements IWizardPanel {
} catch (Exception e) {
CMS.debug("WizardPanelBase::updateConfigEntries() - unable to get cs.type: " + e.toString());
}
-
- Document doc = parser.getDocument();
+
+ Document doc = parser.getDocument();
NodeList list = doc.getElementsByTagName("name");
int len = list.getLength();
- for (int i=0; i<len; i++) {
+ for (int i = 0; i < len; i++) {
Node n = list.item(i);
NodeList nn = n.getChildNodes();
String name = nn.item(0).getNodeValue();
@@ -606,14 +609,14 @@ public class WizardPanelBase implements IWizardPanel {
nn = parent.getChildNodes();
int len1 = nn.getLength();
String v = "";
- for (int j=0; j<len1; j++) {
+ for (int j = 0; j < len1; j++) {
Node nv = nn.item(j);
String val = nv.getNodeName();
if (val.equals("value")) {
NodeList n2 = nv.getChildNodes();
if (n2.getLength() > 0)
- v = n2.item(0).getNodeValue();
- break;
+ v = n2.item(0).getNodeValue();
+ break;
}
}
@@ -625,7 +628,7 @@ public class WizardPanelBase implements IWizardPanel {
config.putString("preop.internaldb.master.binddn", v);
} else if (name.equals("internaldb.basedn")) {
config.putString(name, v);
- config.putString("preop.internaldb.master.basedn", v);
+ config.putString("preop.internaldb.master.basedn", v);
} else if (name.equals("internaldb.ldapauth.password")) {
config.putString("preop.internaldb.master.bindpwd", v);
} else if (name.equals("internaldb.replication.password")) {
@@ -649,7 +652,7 @@ public class WizardPanelBase implements IWizardPanel {
config.putString("preop.master.storage.nickname", v);
config.putString("kra.storageUnit.nickName", v);
config.putString("preop.cert.storage.nickname", v);
- } else if (name.equals("cloning.audit_signing.nickname")) {
+ } else if (name.equals("cloning.audit_signing.nickname")) {
config.putString("preop.master.audit_signing.nickname", v);
config.putString("preop.cert.audit_signing.nickname", v);
config.putString(name, v);
@@ -686,7 +689,7 @@ public class WizardPanelBase implements IWizardPanel {
String error = parser.getValue("Error");
throw new IOException(error);
- }
+ }
} catch (IOException e) {
CMS.debug("WizardPanelBase: updateConfigEntries: " + e.toString());
throw e;
@@ -713,9 +716,9 @@ public class WizardPanelBase implements IWizardPanel {
try {
parser = new XMLObject(bis);
} catch (Exception e) {
- CMS.debug( "WizardPanelBase::authenticate() - "
- + "Exception="+e.toString() );
- throw new IOException( e.toString() );
+ CMS.debug("WizardPanelBase::authenticate() - "
+ + "Exception=" + e.toString());
+ throw new IOException(e.toString());
}
String status = parser.getValue("Status");
@@ -729,7 +732,7 @@ public class WizardPanelBase implements IWizardPanel {
} else {
String error = parser.getValue("Error");
return false;
- }
+ }
} catch (Exception e) {
CMS.debug("WizardPanelBase: authenticate: " + e.toString());
throw new IOException(e.toString());
@@ -739,12 +742,12 @@ public class WizardPanelBase implements IWizardPanel {
return false;
}
- public void updateOCSPConfig(String hostname, int port, boolean https,
- String content, HttpServletResponse response)
- throws IOException {
+ public void updateOCSPConfig(String hostname, int port, boolean https,
+ String content, HttpServletResponse response)
+ throws IOException {
CMS.debug("WizardPanelBase updateOCSPConfig start");
- String c = getHttpResponse(hostname, port, https,
- "/ca/ee/ca/updateOCSPConfig", content, null);
+ String c = getHttpResponse(hostname, port, https,
+ "/ca/ee/ca/updateOCSPConfig", content, null);
if (c == null || c.equals("")) {
CMS.debug("WizardPanelBase updateOCSPConfig: content is null.");
throw new IOException("The server you want to contact is not available");
@@ -756,9 +759,9 @@ public class WizardPanelBase implements IWizardPanel {
try {
parser = new XMLObject(bis);
} catch (Exception e) {
- CMS.debug( "WizardPanelBase::updateOCSPConfig() - "
- + "Exception="+e.toString() );
- throw new IOException( e.toString() );
+ CMS.debug("WizardPanelBase::updateOCSPConfig() - "
+ + "Exception=" + e.toString());
+ throw new IOException(e.toString());
}
String status = parser.getValue("Status");
@@ -774,7 +777,7 @@ public class WizardPanelBase implements IWizardPanel {
String error = parser.getValue("Error");
throw new IOException(error);
- }
+ }
} catch (IOException e) {
CMS.debug("WizardPanelBase updateOCSPConfig: " + e.toString());
throw e;
@@ -785,10 +788,10 @@ public class WizardPanelBase implements IWizardPanel {
}
}
- public void updateNumberRange(String hostname, int port, boolean https,
- String content, String type, HttpServletResponse response)
- throws IOException {
- CMS.debug("WizardPanelBase updateNumberRange start host=" + hostname +
+ public void updateNumberRange(String hostname, int port, boolean https,
+ String content, String type, HttpServletResponse response)
+ throws IOException {
+ CMS.debug("WizardPanelBase updateNumberRange start host=" + hostname +
" port=" + port);
IConfigStore cs = CMS.getConfigStore();
String cstype = "";
@@ -798,13 +801,13 @@ public class WizardPanelBase implements IWizardPanel {
}
cstype = toLowerCaseSubsystemType(cstype);
- String c = getHttpResponse(hostname, port, https,
- "/"+cstype+"/ee/"+cstype+"/updateNumberRange", content, null);
+ String c = getHttpResponse(hostname, port, https,
+ "/" + cstype + "/ee/" + cstype + "/updateNumberRange", content, null);
if (c == null || c.equals("")) {
CMS.debug("WizardPanelBase updateNumberRange: content is null.");
throw new IOException("The server you want to contact is not available");
} else {
- CMS.debug("content="+c);
+ CMS.debug("content=" + c);
try {
ByteArrayInputStream bis = new ByteArrayInputStream(c.getBytes());
XMLObject parser = null;
@@ -812,9 +815,9 @@ public class WizardPanelBase implements IWizardPanel {
try {
parser = new XMLObject(bis);
} catch (Exception e) {
- CMS.debug( "WizardPanelBase::updateNumberRange() - "
- + "Exception="+e.toString() );
- throw new IOException( e.toString() );
+ CMS.debug("WizardPanelBase::updateNumberRange() - "
+ + "Exception=" + e.toString());
+ throw new IOException(e.toString());
}
String status = parser.getValue("Status");
@@ -843,7 +846,7 @@ public class WizardPanelBase implements IWizardPanel {
String error = parser.getValue("Error");
throw new IOException(error);
- }
+ }
} catch (IOException e) {
CMS.debug("WizardPanelBase: updateNumberRange: " + e.toString());
CMS.debug(e);
@@ -856,9 +859,9 @@ public class WizardPanelBase implements IWizardPanel {
}
}
- public int getPort(String hostname, int port, boolean https,
- String portServlet, boolean sport)
- throws IOException {
+ public int getPort(String hostname, int port, boolean https,
+ String portServlet, boolean sport)
+ throws IOException {
CMS.debug("WizardPanelBase getPort start");
String c = getHttpResponse(hostname, port, https, portServlet,
"secure=" + sport, null);
@@ -871,9 +874,9 @@ public class WizardPanelBase implements IWizardPanel {
try {
parser = new XMLObject(bis);
} catch (Exception e) {
- CMS.debug( "WizardPanelBase::getPort() - "
- + "Exception="+e.toString() );
- throw new IOException( e.toString() );
+ CMS.debug("WizardPanelBase::getPort() - "
+ + "Exception=" + e.toString());
+ throw new IOException(e.toString());
}
String status = parser.getValue("Status");
@@ -889,7 +892,7 @@ public class WizardPanelBase implements IWizardPanel {
String error = parser.getValue("Error");
throw new IOException(error);
- }
+ }
} catch (IOException e) {
CMS.debug("WizardPanelBase: getPort: " + e.toString());
throw e;
@@ -903,14 +906,14 @@ public class WizardPanelBase implements IWizardPanel {
}
public String getHttpResponse(String hostname, int port, boolean secure,
- String uri, String content, String clientnickname) throws IOException {
+ String uri, String content, String clientnickname) throws IOException {
return getHttpResponse(hostname, port, secure, uri, content, clientnickname, null);
}
- public String getHttpResponse(String hostname, int port, boolean secure,
- String uri, String content, String clientnickname,
- SSLCertificateApprovalCallback certApprovalCallback)
- throws IOException {
+ public String getHttpResponse(String hostname, int port, boolean secure,
+ String uri, String content, String clientnickname,
+ SSLCertificateApprovalCallback certApprovalCallback)
+ throws IOException {
HttpClient httpclient = null;
String c = null;
@@ -960,8 +963,8 @@ public class WizardPanelBase implements IWizardPanel {
return c;
}
- public boolean isSDHostDomainMaster (IConfigStore config) {
- String dm="false";
+ public boolean isSDHostDomainMaster(IConfigStore config) {
+ String dm = "false";
try {
String hostname = config.getString("securitydomain.host");
int httpsadminport = config.getInteger("securitydomain.httpsadminport");
@@ -971,40 +974,40 @@ public class WizardPanelBase implements IWizardPanel {
CMS.debug("Getting DomainMaster from security domain");
- ByteArrayInputStream bis = new ByteArrayInputStream( c.getBytes() );
- XMLObject parser = new XMLObject( bis );
+ ByteArrayInputStream bis = new ByteArrayInputStream(c.getBytes());
+ XMLObject parser = new XMLObject(bis);
Document doc = parser.getDocument();
- NodeList nodeList = doc.getElementsByTagName( "CA" );
+ NodeList nodeList = doc.getElementsByTagName("CA");
int len = nodeList.getLength();
- for( int i = 0; i < len; i++ ) {
+ for (int i = 0; i < len; i++) {
Vector v_hostname =
- parser.getValuesFromContainer( nodeList.item(i),
- "Host" );
+ parser.getValuesFromContainer(nodeList.item(i),
+ "Host");
Vector v_https_admin_port =
- parser.getValuesFromContainer( nodeList.item(i),
- "SecureAdminPort" );
+ parser.getValuesFromContainer(nodeList.item(i),
+ "SecureAdminPort");
Vector v_domain_mgr =
- parser.getValuesFromContainer( nodeList.item(i),
- "DomainManager" );
+ parser.getValuesFromContainer(nodeList.item(i),
+ "DomainManager");
- if( v_hostname.elementAt( 0 ).equals( hostname ) &&
- v_https_admin_port.elementAt( 0 ).equals( Integer.toString(httpsadminport) ) ) {
- dm = v_domain_mgr.elementAt( 0 ).toString();
+ if (v_hostname.elementAt(0).equals(hostname) &&
+ v_https_admin_port.elementAt(0).equals(Integer.toString(httpsadminport))) {
+ dm = v_domain_mgr.elementAt(0).toString();
break;
}
}
} catch (Exception e) {
- CMS.debug( e.toString() );
+ CMS.debug(e.toString());
}
return dm.equalsIgnoreCase("true");
}
-
- public Vector getMasterUrlListFromSecurityDomain( IConfigStore config,
+
+ public Vector getMasterUrlListFromSecurityDomain(IConfigStore config,
String type,
- String portType ) {
+ String portType) {
Vector v = new Vector();
try {
@@ -1026,13 +1029,13 @@ public class WizardPanelBase implements IWizardPanel {
list = "TKSList";
}
- CMS.debug( "Getting " + portType + " from Security Domain ..." );
- if( !portType.equals( "UnSecurePort" ) &&
- !portType.equals( "SecureAgentPort" ) &&
- !portType.equals( "SecurePort" ) &&
- !portType.equals( "SecureAdminPort" ) ) {
- CMS.debug( "getPortFromSecurityDomain: " +
- "unknown port type " + portType );
+ CMS.debug("Getting " + portType + " from Security Domain ...");
+ if (!portType.equals("UnSecurePort") &&
+ !portType.equals("SecureAgentPort") &&
+ !portType.equals("SecurePort") &&
+ !portType.equals("SecureAdminPort")) {
+ CMS.debug("getPortFromSecurityDomain: " +
+ "unknown port type " + portType);
return v;
}
@@ -1050,8 +1053,8 @@ public class WizardPanelBase implements IWizardPanel {
CMS.debug("Len " + len);
for (int i = 0; i < len; i++) {
Vector v_clone = parser.getValuesFromContainer(nodeList.item(i),
- "Clone");
- String clone = (String)v_clone.elementAt(0);
+ "Clone");
+ String clone = (String) v_clone.elementAt(0);
if (clone.equalsIgnoreCase("true"))
continue;
Vector v_name = parser.getValuesFromContainer(nodeList.item(i),
@@ -1061,11 +1064,11 @@ public class WizardPanelBase implements IWizardPanel {
Vector v_port = parser.getValuesFromContainer(nodeList.item(i),
portType);
- v.addElement( v_name.elementAt(0)
+ v.addElement(v_name.elementAt(0)
+ " - https://"
+ v_host.elementAt(0)
+ ":"
- + v_port.elementAt(0) );
+ + v_port.elementAt(0));
}
} catch (Exception e) {
CMS.debug(e.toString());
@@ -1074,9 +1077,9 @@ public class WizardPanelBase implements IWizardPanel {
return v;
}
- public Vector getUrlListFromSecurityDomain( IConfigStore config,
+ public Vector getUrlListFromSecurityDomain(IConfigStore config,
String type,
- String portType ) {
+ String portType) {
Vector v = new Vector();
try {
@@ -1098,13 +1101,13 @@ public class WizardPanelBase implements IWizardPanel {
list = "TKSList";
}
- CMS.debug( "Getting " + portType + " from Security Domain ..." );
- if( !portType.equals( "UnSecurePort" ) &&
- !portType.equals( "SecureAgentPort" ) &&
- !portType.equals( "SecurePort" ) &&
- !portType.equals( "SecureAdminPort" ) ) {
- CMS.debug( "getPortFromSecurityDomain: " +
- "unknown port type " + portType );
+ CMS.debug("Getting " + portType + " from Security Domain ...");
+ if (!portType.equals("UnSecurePort") &&
+ !portType.equals("SecureAgentPort") &&
+ !portType.equals("SecurePort") &&
+ !portType.equals("SecureAdminPort")) {
+ CMS.debug("getPortFromSecurityDomain: " +
+ "unknown port type " + portType);
return v;
}
@@ -1132,17 +1135,17 @@ public class WizardPanelBase implements IWizardPanel {
if (v_host.elementAt(0).equals(hostname) && v_admin_port.elementAt(0).equals(new Integer(httpsadminport).toString())) {
// add security domain CA to the beginning of list
- v.add( 0, v_name.elementAt(0)
+ v.add(0, v_name.elementAt(0)
+ " - https://"
+ v_host.elementAt(0)
+ ":"
- + v_port.elementAt(0) );
+ + v_port.elementAt(0));
} else {
- v.addElement( v_name.elementAt(0)
+ v.addElement(v_name.elementAt(0)
+ " - https://"
+ v_host.elementAt(0)
+ ":"
- + v_port.elementAt(0) );
+ + v_port.elementAt(0));
}
}
} catch (Exception e) {
@@ -1154,155 +1157,155 @@ public class WizardPanelBase implements IWizardPanel {
// Given an HTTPS Hostname and EE port,
// retrieve the associated HTTPS Admin port
- public String getSecurityDomainAdminPort( IConfigStore config,
+ public String getSecurityDomainAdminPort(IConfigStore config,
String hostname,
String https_ee_port,
- String cstype ) {
+ String cstype) {
String https_admin_port = new String();
try {
- String sd_hostname = config.getString( "securitydomain.host" );
+ String sd_hostname = config.getString("securitydomain.host");
int sd_httpsadminport =
- config.getInteger( "securitydomain.httpsadminport" );
+ config.getInteger("securitydomain.httpsadminport");
- CMS.debug( "Getting domain.xml from CA ..." );
- String c = getDomainXML( sd_hostname, sd_httpsadminport, true );
+ CMS.debug("Getting domain.xml from CA ...");
+ String c = getDomainXML(sd_hostname, sd_httpsadminport, true);
- CMS.debug( "Getting associated HTTPS Admin port from " +
+ CMS.debug("Getting associated HTTPS Admin port from " +
"HTTPS Hostname '" + hostname +
- "' and EE port '" + https_ee_port + "'" );
- ByteArrayInputStream bis = new ByteArrayInputStream( c.getBytes() );
- XMLObject parser = new XMLObject( bis );
+ "' and EE port '" + https_ee_port + "'");
+ ByteArrayInputStream bis = new ByteArrayInputStream(c.getBytes());
+ XMLObject parser = new XMLObject(bis);
Document doc = parser.getDocument();
- NodeList nodeList = doc.getElementsByTagName( cstype.toUpperCase() );
+ NodeList nodeList = doc.getElementsByTagName(cstype.toUpperCase());
int len = nodeList.getLength();
- for( int i = 0; i < len; i++ ) {
+ for (int i = 0; i < len; i++) {
Vector v_hostname =
- parser.getValuesFromContainer( nodeList.item(i),
- "Host" );
+ parser.getValuesFromContainer(nodeList.item(i),
+ "Host");
Vector v_https_ee_port =
- parser.getValuesFromContainer( nodeList.item(i),
- "SecurePort" );
+ parser.getValuesFromContainer(nodeList.item(i),
+ "SecurePort");
Vector v_https_admin_port =
- parser.getValuesFromContainer( nodeList.item(i),
- "SecureAdminPort" );
+ parser.getValuesFromContainer(nodeList.item(i),
+ "SecureAdminPort");
- if( v_hostname.elementAt( 0 ).equals( hostname ) &&
- v_https_ee_port.elementAt( 0 ).equals( https_ee_port ) ) {
+ if (v_hostname.elementAt(0).equals(hostname) &&
+ v_https_ee_port.elementAt(0).equals(https_ee_port)) {
https_admin_port =
- v_https_admin_port.elementAt( 0 ).toString();
+ v_https_admin_port.elementAt(0).toString();
break;
}
}
} catch (Exception e) {
- CMS.debug( e.toString() );
+ CMS.debug(e.toString());
}
- return( https_admin_port );
+ return (https_admin_port);
}
- public String getSecurityDomainPort( IConfigStore config,
- String portType ) {
+ public String getSecurityDomainPort(IConfigStore config,
+ String portType) {
String port = new String();
try {
- String hostname = config.getString( "securitydomain.host" );
+ String hostname = config.getString("securitydomain.host");
int httpsadminport =
- config.getInteger( "securitydomain.httpsadminport" );
-
- CMS.debug( "Getting domain.xml from CA ..." );
- String c = getDomainXML( hostname, httpsadminport, true );
-
- CMS.debug( "Getting " + portType + " from Security Domain ..." );
- if( !portType.equals( "UnSecurePort" ) &&
- !portType.equals( "SecureAgentPort" ) &&
- !portType.equals( "SecurePort" ) &&
- !portType.equals( "SecureAdminPort" ) ) {
- CMS.debug( "getPortFromSecurityDomain: " +
- "unknown port type " + portType );
+ config.getInteger("securitydomain.httpsadminport");
+
+ CMS.debug("Getting domain.xml from CA ...");
+ String c = getDomainXML(hostname, httpsadminport, true);
+
+ CMS.debug("Getting " + portType + " from Security Domain ...");
+ if (!portType.equals("UnSecurePort") &&
+ !portType.equals("SecureAgentPort") &&
+ !portType.equals("SecurePort") &&
+ !portType.equals("SecureAdminPort")) {
+ CMS.debug("getPortFromSecurityDomain: " +
+ "unknown port type " + portType);
return "";
}
- ByteArrayInputStream bis = new ByteArrayInputStream( c.getBytes() );
- XMLObject parser = new XMLObject( bis );
+ ByteArrayInputStream bis = new ByteArrayInputStream(c.getBytes());
+ XMLObject parser = new XMLObject(bis);
Document doc = parser.getDocument();
- NodeList nodeList = doc.getElementsByTagName( "CA" );
+ NodeList nodeList = doc.getElementsByTagName("CA");
int len = nodeList.getLength();
- for( int i = 0; i < len; i++ ) {
+ for (int i = 0; i < len; i++) {
Vector v_admin_port =
- parser.getValuesFromContainer( nodeList.item(i),
- "SecureAdminPort" );
+ parser.getValuesFromContainer(nodeList.item(i),
+ "SecureAdminPort");
Vector v_port = null;
- if( portType.equals( "UnSecurePort" ) ) {
- v_port = parser.getValuesFromContainer( nodeList.item(i),
- "UnSecurePort" );
- } else if( portType.equals( "SecureAgentPort" ) ) {
- v_port = parser.getValuesFromContainer( nodeList.item(i),
- "SecureAgentPort" );
- } else if( portType.equals( "SecurePort" ) ) {
- v_port = parser.getValuesFromContainer( nodeList.item(i),
- "SecurePort" );
- } else if( portType.equals( "SecureAdminPort" ) ) {
- v_port = parser.getValuesFromContainer( nodeList.item(i),
- "SecureAdminPort" );
+ if (portType.equals("UnSecurePort")) {
+ v_port = parser.getValuesFromContainer(nodeList.item(i),
+ "UnSecurePort");
+ } else if (portType.equals("SecureAgentPort")) {
+ v_port = parser.getValuesFromContainer(nodeList.item(i),
+ "SecureAgentPort");
+ } else if (portType.equals("SecurePort")) {
+ v_port = parser.getValuesFromContainer(nodeList.item(i),
+ "SecurePort");
+ } else if (portType.equals("SecureAdminPort")) {
+ v_port = parser.getValuesFromContainer(nodeList.item(i),
+ "SecureAdminPort");
}
- if( ( v_port != null ) &&
- ( v_admin_port.elementAt( 0 ).equals(
- Integer.toString( httpsadminport ) ) ) ) {
- port = v_port.elementAt( 0 ).toString();
+ if ((v_port != null) &&
+ (v_admin_port.elementAt(0).equals(
+ Integer.toString(httpsadminport)))) {
+ port = v_port.elementAt(0).toString();
break;
}
}
} catch (Exception e) {
- CMS.debug( e.toString() );
+ CMS.debug(e.toString());
}
- return( port );
+ return (port);
}
- public String pingCS( String hostname, int port, boolean https,
- SSLCertificateApprovalCallback certApprovalCallback )
- throws IOException {
- CMS.debug( "WizardPanelBase pingCS: started" );
+ public String pingCS(String hostname, int port, boolean https,
+ SSLCertificateApprovalCallback certApprovalCallback)
+ throws IOException {
+ CMS.debug("WizardPanelBase pingCS: started");
- String c = getHttpResponse( hostname, port, https,
- "/ca/admin/ca/getStatus",
- null, null, certApprovalCallback );
+ String c = getHttpResponse(hostname, port, https,
+ "/ca/admin/ca/getStatus",
+ null, null, certApprovalCallback);
- if( c != null ) {
+ if (c != null) {
try {
ByteArrayInputStream bis = new
- ByteArrayInputStream( c.getBytes() );
+ ByteArrayInputStream(c.getBytes());
XMLObject parser = null;
String state = null;
try {
- parser = new XMLObject( bis );
- CMS.debug( "WizardPanelBase pingCS: got XML parsed" );
- state = parser.getValue( "State" );
+ parser = new XMLObject(bis);
+ CMS.debug("WizardPanelBase pingCS: got XML parsed");
+ state = parser.getValue("State");
- if( state != null ) {
- CMS.debug( "WizardPanelBase pingCS: state=" + state );
+ if (state != null) {
+ CMS.debug("WizardPanelBase pingCS: state=" + state);
}
} catch (Exception e) {
- CMS.debug( "WizardPanelBase: pingCS: parser failed"
- + e.toString() );
+ CMS.debug("WizardPanelBase: pingCS: parser failed"
+ + e.toString());
}
return state;
- } catch( Exception e ) {
- CMS.debug( "WizardPanelBase: pingCS: " + e.toString() );
- throw new IOException( e.toString() );
+ } catch (Exception e) {
+ CMS.debug("WizardPanelBase: pingCS: " + e.toString());
+ throw new IOException(e.toString());
}
}
- CMS.debug( "WizardPanelBase pingCS: stopped" );
+ CMS.debug("WizardPanelBase pingCS: stopped");
return null;
}
@@ -1311,7 +1314,7 @@ public class WizardPanelBase implements IWizardPanel {
if (s.equals("CA")) {
x = "ca";
} else if (s.equals("KRA")) {
- x = "kra";
+ x = "kra";
} else if (s.equals("OCSP")) {
x = "ocsp";
} else if (s.equals("TKS")) {
@@ -1321,14 +1324,14 @@ public class WizardPanelBase implements IWizardPanel {
return x;
}
- public void getTokenInfo(IConfigStore config, String type, String host,
- int https_ee_port, boolean https, Context context,
- ConfigCertApprovalCallback certApprovalCallback) throws IOException {
+ public void getTokenInfo(IConfigStore config, String type, String host,
+ int https_ee_port, boolean https, Context context,
+ ConfigCertApprovalCallback certApprovalCallback) throws IOException {
CMS.debug("WizardPanelBase getTokenInfo start");
- String uri = "/"+type+"/ee/"+type+"/getTokenInfo";
- CMS.debug("WizardPanelBase getTokenInfo: uri="+uri);
+ String uri = "/" + type + "/ee/" + type + "/getTokenInfo";
+ CMS.debug("WizardPanelBase getTokenInfo: uri=" + uri);
String c = getHttpResponse(host, https_ee_port, https, uri, null, null,
- certApprovalCallback);
+ certApprovalCallback);
if (c != null) {
try {
ByteArrayInputStream bis = new ByteArrayInputStream(c.getBytes());
@@ -1337,9 +1340,9 @@ public class WizardPanelBase implements IWizardPanel {
try {
parser = new XMLObject(bis);
} catch (Exception e) {
- CMS.debug( "WizardPanelBase::getTokenInfo() - "
- + "Exception="+e.toString() );
- throw new IOException( e.toString() );
+ CMS.debug("WizardPanelBase::getTokenInfo() - "
+ + "Exception=" + e.toString());
+ throw new IOException(e.toString());
}
String status = parser.getValue("Status");
@@ -1350,7 +1353,7 @@ public class WizardPanelBase implements IWizardPanel {
Document doc = parser.getDocument();
NodeList list = doc.getElementsByTagName("name");
int len = list.getLength();
- for (int i=0; i<len; i++) {
+ for (int i = 0; i < len; i++) {
Node n = list.item(i);
NodeList nn = n.getChildNodes();
String name = nn.item(0).getNodeValue();
@@ -1358,17 +1361,17 @@ public class WizardPanelBase implements IWizardPanel {
nn = parent.getChildNodes();
int len1 = nn.getLength();
String v = "";
- for (int j=0; j<len1; j++) {
+ for (int j = 0; j < len1; j++) {
Node nv = nn.item(j);
String val = nv.getNodeName();
if (val.equals("value")) {
NodeList n2 = nv.getChildNodes();
if (n2.getLength() > 0)
v = n2.item(0).getNodeValue();
- break;
+ break;
}
}
- if (name.equals("cloning.signing.nickname")) {
+ if (name.equals("cloning.signing.nickname")) {
config.putString("preop.master.signing.nickname", v);
config.putString(type + ".cert.signing.nickname", v);
config.putString(name, v);
@@ -1406,19 +1409,20 @@ public class WizardPanelBase implements IWizardPanel {
}
// reset nicknames for system cert verification
- String token = config.getString("preop.module.token",
+ String token = config.getString("preop.module.token",
"Internal Key Storage Token");
- if (! token.equals("Internal Key Storage Token")) {
+ if (!token.equals("Internal Key Storage Token")) {
String certlist = config.getString("preop.cert.list");
StringTokenizer t1 = new StringTokenizer(certlist, ",");
while (t1.hasMoreTokens()) {
String tag = t1.nextToken();
- if (tag.equals("sslserver")) continue;
- config.putString(type + ".cert." + tag + ".nickname",
- token + ":" +
- config.getString(type + ".cert." + tag + ".nickname", ""));
- }
+ if (tag.equals("sslserver"))
+ continue;
+ config.putString(type + ".cert." + tag + ".nickname",
+ token + ":" +
+ config.getString(type + ".cert." + tag + ".nickname", ""));
+ }
}
} else {
String error = parser.getValue("Error");
@@ -1431,7 +1435,7 @@ public class WizardPanelBase implements IWizardPanel {
CMS.debug("WizardPanelBase: getTokenInfo: " + e.toString());
throw new IOException(e.toString());
}
- }
+ }
}
public void importCertChain(String id) throws IOException {
@@ -1442,31 +1446,32 @@ public class WizardPanelBase implements IWizardPanel {
try {
pkcs7 = config.getString(configName, "");
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
if (pkcs7.length() > 0) {
try {
CryptoUtil.importCertificateChain(pkcs7);
} catch (Exception e) {
- CMS.debug("DisplayCertChainPanel importCertChain: Exception: "+e.toString());
+ CMS.debug("DisplayCertChainPanel importCertChain: Exception: " + e.toString());
}
}
}
public void updateCertChain(IConfigStore config, String name, String host,
- int https_admin_port, boolean https, Context context) throws IOException {
- updateCertChain( config, name, host, https_admin_port,
- https, context, null );
+ int https_admin_port, boolean https, Context context) throws IOException {
+ updateCertChain(config, name, host, https_admin_port,
+ https, context, null);
}
public void updateCertChain(IConfigStore config, String name, String host,
- int https_admin_port, boolean https, Context context,
- ConfigCertApprovalCallback certApprovalCallback) throws IOException {
- String certchain = getCertChainUsingSecureAdminPort( host,
+ int https_admin_port, boolean https, Context context,
+ ConfigCertApprovalCallback certApprovalCallback) throws IOException {
+ String certchain = getCertChainUsingSecureAdminPort(host,
https_admin_port,
https,
- certApprovalCallback );
- config.putString("preop."+name+".pkcs7", certchain);
+ certApprovalCallback);
+ config.putString("preop." + name + ".pkcs7", certchain);
byte[] decoded = CryptoUtil.base64Decode(certchain);
java.security.cert.X509Certificate[] b_certchain = null;
@@ -1475,7 +1480,7 @@ public class WizardPanelBase implements IWizardPanel {
b_certchain = CryptoUtil.getX509CertificateFromPKCS7(decoded);
} catch (Exception e) {
context.put("errorString",
- "Failed to get the certificate chain.");
+ "Failed to get the certificate chain.");
return;
}
@@ -1483,7 +1488,7 @@ public class WizardPanelBase implements IWizardPanel {
if (b_certchain != null) {
size = b_certchain.length;
}
- config.putInteger("preop."+name+".certchain.size", size);
+ config.putInteger("preop." + name + ".certchain.size", size);
for (int i = 0; i < size; i++) {
byte[] bb = null;
@@ -1491,11 +1496,11 @@ public class WizardPanelBase implements IWizardPanel {
bb = b_certchain[i].getEncoded();
} catch (Exception e) {
context.put("errorString",
- "Failed to get the der-encoded certificate chain.");
+ "Failed to get the der-encoded certificate chain.");
return;
}
- config.putString("preop."+name+".certchain." + i,
- CryptoUtil.normalizeCertStr(CryptoUtil.base64Encode(bb)));
+ config.putString("preop." + name + ".certchain." + i,
+ CryptoUtil.normalizeCertStr(CryptoUtil.base64Encode(bb)));
}
try {
@@ -1504,16 +1509,16 @@ public class WizardPanelBase implements IWizardPanel {
}
}
- public void updateCertChainUsingSecureEEPort( IConfigStore config,
+ public void updateCertChainUsingSecureEEPort(IConfigStore config,
String name, String host,
int https_ee_port,
boolean https,
- Context context,
- ConfigCertApprovalCallback certApprovalCallback ) throws IOException {
- String certchain = getCertChainUsingSecureEEPort( host, https_ee_port,
+ Context context,
+ ConfigCertApprovalCallback certApprovalCallback) throws IOException {
+ String certchain = getCertChainUsingSecureEEPort(host, https_ee_port,
https,
certApprovalCallback);
- config.putString("preop."+name+".pkcs7", certchain);
+ config.putString("preop." + name + ".pkcs7", certchain);
byte[] decoded = CryptoUtil.base64Decode(certchain);
java.security.cert.X509Certificate[] b_certchain = null;
@@ -1522,7 +1527,7 @@ public class WizardPanelBase implements IWizardPanel {
b_certchain = CryptoUtil.getX509CertificateFromPKCS7(decoded);
} catch (Exception e) {
context.put("errorString",
- "Failed to get the certificate chain.");
+ "Failed to get the certificate chain.");
return;
}
@@ -1530,7 +1535,7 @@ public class WizardPanelBase implements IWizardPanel {
if (b_certchain != null) {
size = b_certchain.length;
}
- config.putInteger("preop."+name+".certchain.size", size);
+ config.putInteger("preop." + name + ".certchain.size", size);
for (int i = 0; i < size; i++) {
byte[] bb = null;
@@ -1538,11 +1543,11 @@ public class WizardPanelBase implements IWizardPanel {
bb = b_certchain[i].getEncoded();
} catch (Exception e) {
context.put("errorString",
- "Failed to get the der-encoded certificate chain.");
+ "Failed to get the der-encoded certificate chain.");
return;
}
- config.putString("preop."+name+".certchain." + i,
- CryptoUtil.normalizeCertStr(CryptoUtil.base64Encode(bb)));
+ config.putString("preop." + name + ".certchain." + i,
+ CryptoUtil.normalizeCertStr(CryptoUtil.base64Encode(bb)));
}
try {
@@ -1558,26 +1563,26 @@ public class WizardPanelBase implements IWizardPanel {
CryptoStore store = tok.getCryptoStore();
String fullnickname = nickname;
if (!tokenname.equals("") &&
- !tokenname.equals("Internal Key Storage Token") &&
- !tokenname.equals("internal"))
- fullnickname = tokenname+":"+nickname;
+ !tokenname.equals("Internal Key Storage Token") &&
+ !tokenname.equals("internal"))
+ fullnickname = tokenname + ":" + nickname;
- CMS.debug("WizardPanelBase deleteCert: nickname="+fullnickname);
+ CMS.debug("WizardPanelBase deleteCert: nickname=" + fullnickname);
org.mozilla.jss.crypto.X509Certificate cert = cm.findCertByNickname(fullnickname);
if (store instanceof PK11Store) {
CMS.debug("WizardPanelBase deleteCert: this is pk11store");
- PK11Store pk11store = (PK11Store)store;
+ PK11Store pk11store = (PK11Store) store;
pk11store.deleteCertOnly(cert);
CMS.debug("WizardPanelBase deleteCert: cert deleted successfully");
}
} catch (Exception e) {
- CMS.debug("WizardPanelBase deleteCert: Exception="+e.toString());
+ CMS.debug("WizardPanelBase deleteCert: Exception=" + e.toString());
}
}
public void deleteEntries(LDAPSearchResults res, LDAPConnection conn,
- String dn, String[] entries) {
+ String dn, String[] entries) {
String[] attrs = null;
LDAPSearchConstraints cons = null;
String filter = "objectclass=*";
@@ -1595,23 +1600,23 @@ public class WizardPanelBase implements IWizardPanel {
}
}
} catch (Exception ee) {
- CMS.debug("WizardPanelBase deleteEntries: Exception="+ee.toString());
+ CMS.debug("WizardPanelBase deleteEntries: Exception=" + ee.toString());
}
}
public void deleteEntry(LDAPConnection conn, String dn, String[] entries) {
try {
- for (int i=0; i<entries.length; i++) {
+ for (int i = 0; i < entries.length; i++) {
if (LDAPDN.equals(dn, entries[i])) {
- CMS.debug("WizardPanelBase deleteEntry: entry with this dn "+dn+" is not deleted.");
+ CMS.debug("WizardPanelBase deleteEntry: entry with this dn " + dn + " is not deleted.");
return;
}
}
- CMS.debug("WizardPanelBase deleteEntry: deleting dn="+dn);
+ CMS.debug("WizardPanelBase deleteEntry: deleting dn=" + dn);
conn.delete(dn);
} catch (Exception e) {
- CMS.debug("WizardPanelBase deleteEntry: Exception="+e.toString());
+ CMS.debug("WizardPanelBase deleteEntry: Exception=" + e.toString());
}
}
@@ -1624,12 +1629,12 @@ public class WizardPanelBase implements IWizardPanel {
int cs_port = cs.getInteger("pkicreate.admin_secure_port", -1);
int panel = getPanelNo();
String subsystem = cs.getString("cs.type", "");
- String urlVal = "https://"+cs_hostname+":"+cs_port+"/"+toLowerCaseSubsystemType(subsystem)+"/admin/console/config/wizard?p="+panel+"&subsystem="+subsystem;
+ String urlVal = "https://" + cs_hostname + ":" + cs_port + "/" + toLowerCaseSubsystemType(subsystem) + "/admin/console/config/wizard?p=" + panel + "&subsystem=" + subsystem;
String encodedValue = URLEncoder.encode(urlVal, "UTF-8");
- String sdurl = "https://"+hostname+":"+port+"/ca/admin/ca/securityDomainLogin?url="+encodedValue;
+ String sdurl = "https://" + hostname + ":" + port + "/ca/admin/ca/securityDomainLogin?url=" + encodedValue;
response.sendRedirect(sdurl);
} catch (Exception e) {
- CMS.debug("WizardPanelBase reloginSecurityDomain: Exception="+e.toString());
+ CMS.debug("WizardPanelBase reloginSecurityDomain: Exception=" + e.toString());
}
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/filter/AdminRequestFilter.java b/pki/base/common/src/com/netscape/cms/servlet/filter/AdminRequestFilter.java
index bbfa4b39..ca184988 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/filter/AdminRequestFilter.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/filter/AdminRequestFilter.java
@@ -28,30 +28,28 @@ import javax.servlet.http.HttpServletResponse;
import com.netscape.certsrv.apps.CMS;
-public class AdminRequestFilter implements Filter
-{
+public class AdminRequestFilter implements Filter {
private static final String HTTPS_SCHEME = "https";
private static final String HTTPS_PORT = "https_port";
private static final String HTTPS_ROLE = "Admin";
private static final String PROXY_PORT = "proxy_port";
private FilterConfig config;
-
+
/* Create a new AdminRequestFilter */
- public AdminRequestFilter() {}
-
- public void init( FilterConfig filterConfig )
- throws ServletException
- {
+ public AdminRequestFilter() {
+ }
+
+ public void init(FilterConfig filterConfig)
+ throws ServletException {
this.config = filterConfig;
}
-
- public void doFilter( ServletRequest request,
+
+ public void doFilter(ServletRequest request,
ServletResponse response,
- FilterChain chain )
+ FilterChain chain)
throws java.io.IOException,
- ServletException
- {
+ ServletException {
String filterName = getClass().getName();
String scheme = null;
@@ -64,32 +62,32 @@ public class AdminRequestFilter implements Filter
String param_active = null;
// CMS.debug("Entering the admin filter");
- param_active = config.getInitParameter( "active");
+ param_active = config.getInitParameter("active");
- if( request instanceof HttpServletRequest ) {
- HttpServletResponse resp = ( HttpServletResponse ) response;
+ if (request instanceof HttpServletRequest) {
+ HttpServletResponse resp = (HttpServletResponse) response;
- // RFC 1738: verify that scheme is "https"
+ // RFC 1738: verify that scheme is "https"
scheme = request.getScheme();
- if( ! scheme.equals( HTTPS_SCHEME ) ) {
+ if (!scheme.equals(HTTPS_SCHEME)) {
msg = "The scheme MUST be '" + HTTPS_SCHEME
- + "', NOT '" + scheme + "'!";
- CMS.debug( filterName + ": " + msg );
- resp.sendError( HttpServletResponse.SC_UNAUTHORIZED, msg );
+ + "', NOT '" + scheme + "'!";
+ CMS.debug(filterName + ": " + msg);
+ resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, msg);
return;
}
// Always obtain an "https" port from request
port = request.getLocalPort();
- request_port = Integer.toString( port );
+ request_port = Integer.toString(port);
// Always obtain the "https" port passed in as a parameter
- param_https_port = config.getInitParameter( HTTPS_PORT );
- if( param_https_port == null ) {
+ param_https_port = config.getInitParameter(HTTPS_PORT);
+ if (param_https_port == null) {
msg = "The <param-name> '" + HTTPS_PORT
- + "' </param-name> " + "MUST be specified in 'web.xml'!";
- CMS.debug( filterName + ": " + msg );
- resp.sendError( HttpServletResponse.SC_NOT_IMPLEMENTED, msg );
+ + "' </param-name> " + "MUST be specified in 'web.xml'!";
+ CMS.debug(filterName + ": " + msg);
+ resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, msg);
return;
}
@@ -97,29 +95,29 @@ public class AdminRequestFilter implements Filter
boolean bad_port = false;
// Compare the request and param "https" ports
- if( ! param_https_port.equals( request_port ) ) {
+ if (!param_https_port.equals(request_port)) {
String uri = ((HttpServletRequest) request).getRequestURI();
- if (param_proxy_port != null) {
+ if (param_proxy_port != null) {
if (!param_proxy_port.equals(request_port)) {
msg = "Use HTTPS port '" + param_https_port
- + "' or proxy port '" + param_proxy_port
- + "' instead of '" + request_port
- + "' when performing " + HTTPS_ROLE + " tasks!";
+ + "' or proxy port '" + param_proxy_port
+ + "' instead of '" + request_port
+ + "' when performing " + HTTPS_ROLE + " tasks!";
bad_port = true;
}
} else {
msg = "Use HTTPS port '" + param_https_port
- + "' instead of '" + request_port
- + "' when performing " + HTTPS_ROLE + " tasks!";
+ + "' instead of '" + request_port
+ + "' when performing " + HTTPS_ROLE + " tasks!";
bad_port = true;
}
if (bad_port) {
- CMS.debug( filterName + ": " + msg );
- CMS.debug( filterName + ": uri is " + uri);
- if ((param_active != null) &&(param_active.equals("false"))) {
+ CMS.debug(filterName + ": " + msg);
+ CMS.debug(filterName + ": uri is " + uri);
+ if ((param_active != null) && (param_active.equals("false"))) {
CMS.debug("Filter is disabled .. continuing");
} else {
- resp.sendError( HttpServletResponse.SC_NOT_FOUND, msg );
+ resp.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
return;
}
}
@@ -128,11 +126,9 @@ public class AdminRequestFilter implements Filter
// CMS.debug("Exiting the admin filter");
- chain.doFilter( request, response );
+ chain.doFilter(request, response);
}
-
- public void destroy()
- {
+
+ public void destroy() {
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/filter/AgentRequestFilter.java b/pki/base/common/src/com/netscape/cms/servlet/filter/AgentRequestFilter.java
index 1ae44a64..163e3a18 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/filter/AgentRequestFilter.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/filter/AgentRequestFilter.java
@@ -28,30 +28,28 @@ import javax.servlet.http.HttpServletResponse;
import com.netscape.certsrv.apps.CMS;
-public class AgentRequestFilter implements Filter
-{
+public class AgentRequestFilter implements Filter {
private static final String HTTPS_SCHEME = "https";
private static final String HTTPS_PORT = "https_port";
private static final String HTTPS_ROLE = "Agent";
private static final String PROXY_PORT = "proxy_port";
private FilterConfig config;
-
+
/* Create a new AgentRequestFilter */
- public AgentRequestFilter() {}
-
- public void init( FilterConfig filterConfig )
- throws ServletException
- {
+ public AgentRequestFilter() {
+ }
+
+ public void init(FilterConfig filterConfig)
+ throws ServletException {
this.config = filterConfig;
}
-
- public void doFilter( ServletRequest request,
+
+ public void doFilter(ServletRequest request,
ServletResponse response,
- FilterChain chain )
+ FilterChain chain)
throws java.io.IOException,
- ServletException
- {
+ ServletException {
String filterName = getClass().getName();
String scheme = null;
@@ -65,32 +63,32 @@ public class AgentRequestFilter implements Filter
String param_active = null;
// CMS.debug("Entering the agent filter");
- param_active = config.getInitParameter( "active");
+ param_active = config.getInitParameter("active");
- if( request instanceof HttpServletRequest ) {
- HttpServletResponse resp = ( HttpServletResponse ) response;
+ if (request instanceof HttpServletRequest) {
+ HttpServletResponse resp = (HttpServletResponse) response;
- // RFC 1738: verify that scheme is "https"
+ // RFC 1738: verify that scheme is "https"
scheme = request.getScheme();
- if( ! scheme.equals( HTTPS_SCHEME ) ) {
+ if (!scheme.equals(HTTPS_SCHEME)) {
msg = "The scheme MUST be '" + HTTPS_SCHEME
- + "', NOT '" + scheme + "'!";
- CMS.debug( filterName + ": " + msg );
- resp.sendError( HttpServletResponse.SC_UNAUTHORIZED, msg );
+ + "', NOT '" + scheme + "'!";
+ CMS.debug(filterName + ": " + msg);
+ resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, msg);
return;
}
// Always obtain an "https" port from request
port = request.getLocalPort();
- request_port = Integer.toString( port );
+ request_port = Integer.toString(port);
// Always obtain the "https" port passed in as a parameter
- param_https_port = config.getInitParameter( HTTPS_PORT );
- if( param_https_port == null ) {
+ param_https_port = config.getInitParameter(HTTPS_PORT);
+ if (param_https_port == null) {
msg = "The <param-name> '" + HTTPS_PORT
- + "' </param-name> " + "MUST be specified in 'web.xml'!";
- CMS.debug( filterName + ": " + msg );
- resp.sendError( HttpServletResponse.SC_NOT_IMPLEMENTED, msg );
+ + "' </param-name> " + "MUST be specified in 'web.xml'!";
+ CMS.debug(filterName + ": " + msg);
+ resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, msg);
return;
}
@@ -98,29 +96,29 @@ public class AgentRequestFilter implements Filter
boolean bad_port = false;
// Compare the request and param "https" ports
- if( ! param_https_port.equals( request_port ) ) {
+ if (!param_https_port.equals(request_port)) {
String uri = ((HttpServletRequest) request).getRequestURI();
if (param_proxy_port != null) {
if (!param_proxy_port.equals(request_port)) {
msg = "Use HTTPS port '" + param_https_port
- + "' or proxy port '" + param_proxy_port
- + "' instead of '" + request_port
- + "' when performing " + HTTPS_ROLE + " tasks!";
+ + "' or proxy port '" + param_proxy_port
+ + "' instead of '" + request_port
+ + "' when performing " + HTTPS_ROLE + " tasks!";
bad_port = true;
}
} else {
msg = "Use HTTPS port '" + param_https_port
- + "' instead of '" + request_port
- + "' when performing " + HTTPS_ROLE + " tasks!";
+ + "' instead of '" + request_port
+ + "' when performing " + HTTPS_ROLE + " tasks!";
bad_port = true;
}
if (bad_port) {
- CMS.debug( filterName + ": " + msg );
- CMS.debug( filterName + ": uri is " + uri);
- if ((param_active != null) &&(param_active.equals("false"))) {
+ CMS.debug(filterName + ": " + msg);
+ CMS.debug(filterName + ": uri is " + uri);
+ if ((param_active != null) && (param_active.equals("false"))) {
CMS.debug("Filter is disabled .. continuing");
} else {
- resp.sendError( HttpServletResponse.SC_NOT_FOUND, msg );
+ resp.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
return;
}
}
@@ -128,11 +126,9 @@ public class AgentRequestFilter implements Filter
}
// CMS.debug("Exiting the Agent filter");
- chain.doFilter( request, response );
+ chain.doFilter(request, response);
}
-
- public void destroy()
- {
+
+ public void destroy() {
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/filter/EEClientAuthRequestFilter.java b/pki/base/common/src/com/netscape/cms/servlet/filter/EEClientAuthRequestFilter.java
index 8b53c6c6..e734458e 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/filter/EEClientAuthRequestFilter.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/filter/EEClientAuthRequestFilter.java
@@ -28,30 +28,28 @@ import javax.servlet.http.HttpServletResponse;
import com.netscape.certsrv.apps.CMS;
-public class EEClientAuthRequestFilter implements Filter
-{
+public class EEClientAuthRequestFilter implements Filter {
private static final String HTTPS_SCHEME = "https";
private static final String HTTPS_PORT = "https_port";
private static final String HTTPS_ROLE = "EE Client Auth";
private static final String PROXY_PORT = "proxy_port";
private FilterConfig config;
-
+
/* Create a new EEClientAuthRequestFilter */
- public EEClientAuthRequestFilter() {}
-
- public void init( FilterConfig filterConfig )
- throws ServletException
- {
+ public EEClientAuthRequestFilter() {
+ }
+
+ public void init(FilterConfig filterConfig)
+ throws ServletException {
this.config = filterConfig;
}
-
- public void doFilter( ServletRequest request,
+
+ public void doFilter(ServletRequest request,
ServletResponse response,
- FilterChain chain )
+ FilterChain chain)
throws java.io.IOException,
- ServletException
- {
+ ServletException {
String filterName = getClass().getName();
String scheme = null;
@@ -64,32 +62,32 @@ public class EEClientAuthRequestFilter implements Filter
String param_proxy_port = null;
// CMS.debug("Entering the EECA filter");
- param_active = config.getInitParameter( "active");
+ param_active = config.getInitParameter("active");
- if( request instanceof HttpServletRequest ) {
- HttpServletResponse resp = ( HttpServletResponse ) response;
+ if (request instanceof HttpServletRequest) {
+ HttpServletResponse resp = (HttpServletResponse) response;
- // RFC 1738: verify that scheme is "https"
+ // RFC 1738: verify that scheme is "https"
scheme = request.getScheme();
- if( ! scheme.equals( HTTPS_SCHEME ) ) {
+ if (!scheme.equals(HTTPS_SCHEME)) {
msg = "The scheme MUST be '" + HTTPS_SCHEME
- + "', NOT '" + scheme + "'!";
- CMS.debug( filterName + ": " + msg );
- resp.sendError( HttpServletResponse.SC_UNAUTHORIZED, msg );
+ + "', NOT '" + scheme + "'!";
+ CMS.debug(filterName + ": " + msg);
+ resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, msg);
return;
}
// Always obtain an "https" port from request
port = request.getLocalPort();
- request_port = Integer.toString( port );
+ request_port = Integer.toString(port);
// Always obtain the "https" port passed in as a parameter
- param_https_port = config.getInitParameter( HTTPS_PORT );
- if( param_https_port == null ) {
+ param_https_port = config.getInitParameter(HTTPS_PORT);
+ if (param_https_port == null) {
msg = "The <param-name> '" + HTTPS_PORT
- + "' </param-name> " + "MUST be specified in 'web.xml'!";
- CMS.debug( filterName + ": " + msg );
- resp.sendError( HttpServletResponse.SC_NOT_IMPLEMENTED, msg );
+ + "' </param-name> " + "MUST be specified in 'web.xml'!";
+ CMS.debug(filterName + ": " + msg);
+ resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, msg);
return;
}
@@ -97,41 +95,39 @@ public class EEClientAuthRequestFilter implements Filter
boolean bad_port = false;
// Compare the request and param "https" ports
- if( ! param_https_port.equals( request_port ) ) {
+ if (!param_https_port.equals(request_port)) {
String uri = ((HttpServletRequest) request).getRequestURI();
if (param_proxy_port != null) {
if (!param_proxy_port.equals(request_port)) {
msg = "Use HTTPS port '" + param_https_port
- + "' or proxy port '" + param_proxy_port
- + "' instead of '" + request_port
- + "' when performing " + HTTPS_ROLE + " tasks!";
+ + "' or proxy port '" + param_proxy_port
+ + "' instead of '" + request_port
+ + "' when performing " + HTTPS_ROLE + " tasks!";
bad_port = true;
}
} else {
msg = "Use HTTPS port '" + param_https_port
- + "' instead of '" + request_port
- + "' when performing " + HTTPS_ROLE + " tasks!";
+ + "' instead of '" + request_port
+ + "' when performing " + HTTPS_ROLE + " tasks!";
bad_port = true;
}
if (bad_port) {
- CMS.debug( filterName + ": " + msg );
- CMS.debug( filterName + ": uri is " + uri);
- if ((param_active != null) &&(param_active.equals("false"))) {
+ CMS.debug(filterName + ": " + msg);
+ CMS.debug(filterName + ": uri is " + uri);
+ if ((param_active != null) && (param_active.equals("false"))) {
CMS.debug("Filter is disabled .. continuing");
} else {
- resp.sendError( HttpServletResponse.SC_NOT_FOUND, msg );
+ resp.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
return;
}
}
}
}
- // CMS.debug("exiting the EECA filter");
+ // CMS.debug("exiting the EECA filter");
- chain.doFilter( request, response );
+ chain.doFilter(request, response);
}
-
- public void destroy()
- {
+
+ public void destroy() {
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/filter/EERequestFilter.java b/pki/base/common/src/com/netscape/cms/servlet/filter/EERequestFilter.java
index f66cf087..4004702b 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/filter/EERequestFilter.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/filter/EERequestFilter.java
@@ -28,8 +28,7 @@ import javax.servlet.http.HttpServletResponse;
import com.netscape.certsrv.apps.CMS;
-public class EERequestFilter implements Filter
-{
+public class EERequestFilter implements Filter {
private static final String HTTP_SCHEME = "http";
private static final String HTTP_PORT = "http_port";
private static final String HTTP_ROLE = "EE";
@@ -40,22 +39,21 @@ public class EERequestFilter implements Filter
private static final String PROXY_HTTP_PORT = "proxy_http_port";
private FilterConfig config;
-
+
/* Create a new EERequestFilter */
- public EERequestFilter() {}
-
- public void init( FilterConfig filterConfig )
- throws ServletException
- {
+ public EERequestFilter() {
+ }
+
+ public void init(FilterConfig filterConfig)
+ throws ServletException {
this.config = filterConfig;
}
-
- public void doFilter( ServletRequest request,
+
+ public void doFilter(ServletRequest request,
ServletResponse response,
- FilterChain chain )
+ FilterChain chain)
throws java.io.IOException,
- ServletException
- {
+ ServletException {
String filterName = getClass().getName();
String scheme = null;
@@ -70,45 +68,45 @@ public class EERequestFilter implements Filter
String param_active = null;
// CMS.debug("Entering the EE filter");
- param_active = config.getInitParameter( "active");
+ param_active = config.getInitParameter("active");
- if( request instanceof HttpServletRequest ) {
- HttpServletResponse resp = ( HttpServletResponse ) response;
+ if (request instanceof HttpServletRequest) {
+ HttpServletResponse resp = (HttpServletResponse) response;
- // RFC 1738: verify that scheme is either "http" or "https"
+ // RFC 1738: verify that scheme is either "http" or "https"
scheme = request.getScheme();
- if( ( ! scheme.equals( HTTP_SCHEME ) ) &&
- ( ! scheme.equals( HTTPS_SCHEME ) ) ) {
+ if ((!scheme.equals(HTTP_SCHEME)) &&
+ (!scheme.equals(HTTPS_SCHEME))) {
msg = "The scheme MUST be either '" + HTTP_SCHEME
- + "' or '" + HTTPS_SCHEME
- + "', NOT '" + scheme + "'!";
- CMS.debug( filterName + ": " + msg );
- resp.sendError( HttpServletResponse.SC_UNAUTHORIZED, msg );
- return;
+ + "' or '" + HTTPS_SCHEME
+ + "', NOT '" + scheme + "'!";
+ CMS.debug(filterName + ": " + msg);
+ resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, msg);
+ return;
}
// Always obtain either an "http" or an "https" port from request
port = request.getLocalPort();
- request_port = Integer.toString( port );
+ request_port = Integer.toString(port);
// Always obtain the "http" port passed in as a parameter
- param_http_port = config.getInitParameter( HTTP_PORT );
- if( param_http_port == null ) {
+ param_http_port = config.getInitParameter(HTTP_PORT);
+ if (param_http_port == null) {
msg = "The <param-name> '" + HTTP_PORT
- + "' </param-name> " + "MUST be specified in 'web.xml'!";
- CMS.debug( filterName + ": " + msg );
- resp.sendError( HttpServletResponse.SC_NOT_IMPLEMENTED, msg );
- return;
+ + "' </param-name> " + "MUST be specified in 'web.xml'!";
+ CMS.debug(filterName + ": " + msg);
+ resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, msg);
+ return;
}
// Always obtain the "https" port passed in as a parameter
- param_https_port = config.getInitParameter( HTTPS_PORT );
- if( param_https_port == null ) {
+ param_https_port = config.getInitParameter(HTTPS_PORT);
+ if (param_https_port == null) {
msg = "The <param-name> '" + HTTPS_PORT
- + "' </param-name> " + "MUST be specified in 'web.xml'!";
- CMS.debug( filterName + ": " + msg );
- resp.sendError( HttpServletResponse.SC_NOT_IMPLEMENTED, msg );
- return;
+ + "' </param-name> " + "MUST be specified in 'web.xml'!";
+ CMS.debug(filterName + ": " + msg);
+ resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, msg);
+ return;
}
param_proxy_http_port = config.getInitParameter(PROXY_HTTP_PORT);
@@ -119,58 +117,58 @@ public class EERequestFilter implements Filter
// the request and param "http" ports;
// otherwise, if the scheme is "https", compare
// the request and param "https" ports
- if( scheme.equals( HTTP_SCHEME ) ) {
- if( ! param_http_port.equals( request_port ) ) {
+ if (scheme.equals(HTTP_SCHEME)) {
+ if (!param_http_port.equals(request_port)) {
String uri = ((HttpServletRequest) request).getRequestURI();
- if (param_proxy_http_port != null) {
+ if (param_proxy_http_port != null) {
if (!param_proxy_http_port.equals(request_port)) {
msg = "Use HTTP port '" + param_http_port
- + "' or proxy port '" + param_proxy_http_port
- + "' instead of '" + request_port
- + "' when performing " + HTTP_ROLE + " tasks!";
+ + "' or proxy port '" + param_proxy_http_port
+ + "' instead of '" + request_port
+ + "' when performing " + HTTP_ROLE + " tasks!";
bad_port = true;
}
} else {
msg = "Use HTTP port '" + param_http_port
- + "' instead of '" + request_port
- + "' when performing " + HTTP_ROLE + " tasks!";
+ + "' instead of '" + request_port
+ + "' when performing " + HTTP_ROLE + " tasks!";
bad_port = true;
}
if (bad_port) {
- CMS.debug( filterName + ": " + msg );
- CMS.debug( filterName + ": uri is " + uri);
- if ((param_active != null) &&(param_active.equals("false"))) {
+ CMS.debug(filterName + ": " + msg);
+ CMS.debug(filterName + ": uri is " + uri);
+ if ((param_active != null) && (param_active.equals("false"))) {
CMS.debug("Filter is disabled .. continuing");
} else {
- resp.sendError( HttpServletResponse.SC_NOT_FOUND, msg );
+ resp.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
return;
}
}
}
- } else if( scheme.equals( HTTPS_SCHEME ) ) {
- if( ! param_https_port.equals( request_port ) ) {
+ } else if (scheme.equals(HTTPS_SCHEME)) {
+ if (!param_https_port.equals(request_port)) {
String uri = ((HttpServletRequest) request).getRequestURI();
- if (param_proxy_port != null) {
+ if (param_proxy_port != null) {
if (!param_proxy_port.equals(request_port)) {
msg = "Use HTTPS port '" + param_https_port
- + "' or proxy port '" + param_proxy_port
- + "' instead of '" + request_port
- + "' when performing " + HTTPS_ROLE + " tasks!";
+ + "' or proxy port '" + param_proxy_port
+ + "' instead of '" + request_port
+ + "' when performing " + HTTPS_ROLE + " tasks!";
bad_port = true;
}
} else {
msg = "Use HTTPS port '" + param_https_port
- + "' instead of '" + request_port
- + "' when performing " + HTTPS_ROLE + " tasks!";
+ + "' instead of '" + request_port
+ + "' when performing " + HTTPS_ROLE + " tasks!";
bad_port = true;
}
if (bad_port) {
- CMS.debug( filterName + ": " + msg );
- CMS.debug( filterName + ": uri is " + uri);
- if ((param_active != null) &&(param_active.equals("false"))) {
+ CMS.debug(filterName + ": " + msg);
+ CMS.debug(filterName + ": uri is " + uri);
+ if ((param_active != null) && (param_active.equals("false"))) {
CMS.debug("Filter is disabled .. continuing");
} else {
- resp.sendError( HttpServletResponse.SC_NOT_FOUND, msg );
+ resp.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
return;
}
}
@@ -180,11 +178,9 @@ public class EERequestFilter implements Filter
}
// CMS.debug("Exiting the EE filter");
- chain.doFilter( request, response );
+ chain.doFilter(request, response);
}
-
- public void destroy()
- {
+
+ public void destroy() {
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/key/ConfirmRecoverBySerial.java b/pki/base/common/src/com/netscape/cms/servlet/key/ConfirmRecoverBySerial.java
index 166036a9..a5c17e28 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/key/ConfirmRecoverBySerial.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/key/ConfirmRecoverBySerial.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.key;
-
import java.io.IOException;
import java.math.BigInteger;
import java.util.Locale;
@@ -43,13 +42,11 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
- * A class representing a recoverKey servlet. This servlet
- * shows key information and presents a list of text boxes
- * so that recovery agents can type in their identifiers
- * and passwords.
- *
+ * A class representing a recoverKey servlet. This servlet shows key information
+ * and presents a list of text boxes so that recovery agents can type in their
+ * identifiers and passwords.
+ *
* @version $Revision$, $Date$
*/
public class ConfirmRecoverBySerial extends CMSServlet {
@@ -59,8 +56,8 @@ public class ConfirmRecoverBySerial extends CMSServlet {
*/
private static final long serialVersionUID = 2221819191344494389L;
private final static String INFO = "recoverBySerial";
- private final static String TPL_FILE =
- "confirmRecoverBySerial.template";
+ private final static String TPL_FILE =
+ "confirmRecoverBySerial.template";
private final static String IN_SERIALNO = "serialNumber";
private final static String OUT_SERIALNO = IN_SERIALNO;
@@ -95,22 +92,20 @@ public class ConfirmRecoverBySerial extends CMSServlet {
/**
* Returns serlvet information.
*/
- public String getServletInfo() {
- return INFO;
+ public String getServletInfo() {
+ return INFO;
}
/**
- * Serves HTTP request. The format of this request is
- * as follows:
- * confirmRecoverBySerial?
- * [serialNumber=<serialno>]
+ * Serves HTTP request. The format of this request is as follows:
+ * confirmRecoverBySerial? [serialNumber=<serialno>]
*/
public void process(CMSRequest cmsReq) throws EBaseException {
// Note that we should try to handle all the exceptions
- // instead of passing it up back to the servlet
+ // instead of passing it up back to the servlet
// framework.
-
+
HttpServletRequest req = cmsReq.getHttpReq();
HttpServletResponse resp = cmsReq.getHttpResp();
@@ -123,9 +118,9 @@ public class ConfirmRecoverBySerial extends CMSServlet {
form = getTemplate(mFormPath, req, locale);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
IArgBlock header = CMS.createArgBlock();
@@ -147,8 +142,8 @@ public class ConfirmRecoverBySerial extends CMSServlet {
process(argSet, header, seqNum, req, resp, locale[0]);
} catch (NumberFormatException e) {
- header.addStringValue(OUT_ERROR,
- CMS.getUserMessage(locale[0], "CMS_BASE_INTERNAL_ERROR", e.toString()));
+ header.addStringValue(OUT_ERROR,
+ CMS.getUserMessage(locale[0], "CMS_BASE_INTERNAL_ERROR", e.toString()));
}
try {
@@ -157,10 +152,10 @@ public class ConfirmRecoverBySerial extends CMSServlet {
resp.setContentType("text/html");
form.renderOutput(out, argSet);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
cmsReq.setStatus(CMSRequest.SUCCESS);
}
@@ -169,17 +164,17 @@ public class ConfirmRecoverBySerial extends CMSServlet {
* Requests for a list of agent passwords.
*/
private void process(CMSTemplateParams argSet,
- IArgBlock header, int seq,
- HttpServletRequest req, HttpServletResponse resp,
- Locale locale) {
+ IArgBlock header, int seq,
+ HttpServletRequest req, HttpServletResponse resp,
+ Locale locale) {
try {
header.addIntegerValue(OUT_SERIALNO, seq);
header.addIntegerValue(OUT_M,
- mRecoveryService.getNoOfRequiredAgents());
+ mRecoveryService.getNoOfRequiredAgents());
header.addStringValue(OUT_OP,
- req.getParameter(OUT_OP));
+ req.getParameter(OUT_OP));
header.addStringValue(OUT_SERVICE_URL,
- req.getRequestURI());
+ req.getRequestURI());
IKeyRecord rec = (IKeyRecord) mKeyDB.readKeyRecord(new BigInteger(
Integer.toString(seq)));
diff --git a/pki/base/common/src/com/netscape/cms/servlet/key/DisplayBySerial.java b/pki/base/common/src/com/netscape/cms/servlet/key/DisplayBySerial.java
index 510f1ac3..41d7b02c 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/key/DisplayBySerial.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/key/DisplayBySerial.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.key;
-
import java.io.IOException;
import java.math.BigInteger;
import java.util.Locale;
@@ -44,11 +43,10 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* Display a specific Key Archival Request
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class DisplayBySerial extends CMSServlet {
@@ -78,7 +76,7 @@ public class DisplayBySerial extends CMSServlet {
/**
* initialize the servlet. This servlet uses the template file
* "displayBySerial.template" to process the response.
- *
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -94,8 +92,8 @@ public class DisplayBySerial extends CMSServlet {
/**
* Returns serlvet information.
*/
- public String getServletInfo() {
- return INFO;
+ public String getServletInfo() {
+ return INFO;
}
/**
@@ -103,7 +101,7 @@ public class DisplayBySerial extends CMSServlet {
* <ul>
* <li>http.param serialNumber serial number of the key archival request
* </ul>
- *
+ *
* @param cmsReq the object holding the request and response information
*/
public void process(CMSRequest cmsReq) throws EBaseException {
@@ -119,10 +117,10 @@ public class DisplayBySerial extends CMSServlet {
mAuthzResourceName, "read");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -137,13 +135,13 @@ public class DisplayBySerial extends CMSServlet {
form = getTemplate(mFormPath, req, locale);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
// Note that we should try to handle all the exceptions
- // instead of passing it up back to the servlet
+ // instead of passing it up back to the servlet
// framework.
IArgBlock header = CMS.createArgBlock();
@@ -159,7 +157,7 @@ public class DisplayBySerial extends CMSServlet {
process(argSet, header, seqNum, req, resp, locale[0]);
} catch (NumberFormatException e) {
header.addStringValue(OUT_ERROR,
- CMS.getUserMessage(locale[0], "CMS_BASE_INTERNAL_ERROR", e.toString()));
+ CMS.getUserMessage(locale[0], "CMS_BASE_INTERNAL_ERROR", e.toString()));
}
try {
@@ -169,9 +167,9 @@ public class DisplayBySerial extends CMSServlet {
form.renderOutput(out, argSet);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
}
@@ -179,15 +177,15 @@ public class DisplayBySerial extends CMSServlet {
* Display information about a particular key.
*/
private void process(CMSTemplateParams argSet,
- IArgBlock header, int seq,
- HttpServletRequest req, HttpServletResponse resp,
- Locale locale) {
+ IArgBlock header, int seq,
+ HttpServletRequest req, HttpServletResponse resp,
+ Locale locale) {
try {
header.addStringValue(OUT_OP,
- req.getParameter(OUT_OP));
+ req.getParameter(OUT_OP));
header.addStringValue(OUT_SERVICE_URL,
- req.getRequestURI());
- IKeyRecord rec = (IKeyRecord) mKeyDB.readKeyRecord(new
+ req.getRequestURI());
+ IKeyRecord rec = (IKeyRecord) mKeyDB.readKeyRecord(new
BigInteger(Integer.toString(seq)));
KeyRecordParser.fillRecordIntoArg(rec, header);
diff --git a/pki/base/common/src/com/netscape/cms/servlet/key/DisplayBySerialForRecovery.java b/pki/base/common/src/com/netscape/cms/servlet/key/DisplayBySerialForRecovery.java
index 2ef78c64..82d75884 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/key/DisplayBySerialForRecovery.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/key/DisplayBySerialForRecovery.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.key;
-
import java.io.IOException;
import java.math.BigInteger;
import java.util.Locale;
@@ -45,11 +44,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
- * Display a Specific Key Archival Request, and initiate
- * key recovery process
- *
+ * Display a Specific Key Archival Request, and initiate key recovery process
+ *
* @version $Revision$, $Date$
*/
public class DisplayBySerialForRecovery extends CMSServlet {
@@ -80,7 +77,7 @@ public class DisplayBySerialForRecovery extends CMSServlet {
/**
* initialize the servlet. This servlet uses the template file
* "displayBySerialForRecovery.template" to process the response.
- *
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -95,17 +92,17 @@ public class DisplayBySerialForRecovery extends CMSServlet {
/**
* Returns serlvet information.
*/
- public String getServletInfo() {
- return INFO;
+ public String getServletInfo() {
+ return INFO;
}
/**
* Process the HTTP request.
* <ul>
- * <li>http.param serialNumber request ID of key archival request
- * <li>http.param publicKeyData
+ * <li>http.param serialNumber request ID of key archival request
+ * <li>http.param publicKeyData
* </ul>
- *
+ *
* @param cmsReq the object holding the request and response information
*/
public void process(CMSRequest cmsReq) throws EBaseException {
@@ -121,10 +118,10 @@ public class DisplayBySerialForRecovery extends CMSServlet {
mAuthzResourceName, "read");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -139,13 +136,13 @@ public class DisplayBySerialForRecovery extends CMSServlet {
form = getTemplate(mFormPath, req, locale);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
// Note that we should try to handle all the exceptions
- // instead of passing it up back to the servlet
+ // instead of passing it up back to the servlet
// framework.
IArgBlock header = CMS.createArgBlock();
@@ -159,12 +156,12 @@ public class DisplayBySerialForRecovery extends CMSServlet {
seqNum = Integer.parseInt(
req.getParameter(IN_SERIALNO));
}
- process(argSet, header,
- req.getParameter("publicKeyData"),
- seqNum, req, resp, locale[0]);
+ process(argSet, header,
+ req.getParameter("publicKeyData"),
+ seqNum, req, resp, locale[0]);
} catch (NumberFormatException e) {
header.addStringValue(OUT_ERROR,
- CMS.getUserMessage(locale[0], "CMS_BASE_INTERNAL_ERROR", e.toString()));
+ CMS.getUserMessage(locale[0], "CMS_BASE_INTERNAL_ERROR", e.toString()));
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.toString());
@@ -176,9 +173,9 @@ public class DisplayBySerialForRecovery extends CMSServlet {
form.renderOutput(out, argSet);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
cmsReq.setStatus(CMSRequest.SUCCESS);
}
@@ -187,23 +184,23 @@ public class DisplayBySerialForRecovery extends CMSServlet {
* Display information about a particular key.
*/
private synchronized void process(CMSTemplateParams argSet,
- IArgBlock header, String publicKeyData, int seq,
- HttpServletRequest req, HttpServletResponse resp,
- Locale locale) {
+ IArgBlock header, String publicKeyData, int seq,
+ HttpServletRequest req, HttpServletResponse resp,
+ Locale locale) {
try {
header.addIntegerValue("noOfRequiredAgents",
- mService.getNoOfRequiredAgents());
+ mService.getNoOfRequiredAgents());
header.addStringValue(OUT_OP,
- req.getParameter(OUT_OP));
+ req.getParameter(OUT_OP));
header.addStringValue("keySplitting",
- CMS.getConfigStore().getString("kra.keySplitting"));
+ CMS.getConfigStore().getString("kra.keySplitting"));
header.addStringValue(OUT_SERVICE_URL,
- req.getRequestURI());
+ req.getRequestURI());
if (publicKeyData != null) {
header.addStringValue("publicKeyData",
- publicKeyData);
+ publicKeyData);
}
- IKeyRecord rec = (IKeyRecord) mKeyDB.readKeyRecord(new
+ IKeyRecord rec = (IKeyRecord) mKeyDB.readKeyRecord(new
BigInteger(Integer.toString(seq)));
KeyRecordParser.fillRecordIntoArg(rec, header);
diff --git a/pki/base/common/src/com/netscape/cms/servlet/key/DisplayTransport.java b/pki/base/common/src/com/netscape/cms/servlet/key/DisplayTransport.java
index d4baf181..2fd882b7 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/key/DisplayTransport.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/key/DisplayTransport.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.key;
-
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
@@ -34,11 +33,9 @@ import com.netscape.cms.servlet.base.CMSServlet;
import com.netscape.cms.servlet.common.CMSRequest;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
- * Retrieve Transport Certificate used to
- * wrap Private key Archival requests
- *
+ * Retrieve Transport Certificate used to wrap Private key Archival requests
+ *
* @version $Revision$, $Date$
*/
public class DisplayTransport extends CMSServlet {
@@ -67,13 +64,13 @@ public class DisplayTransport extends CMSServlet {
/**
* Returns serlvet information.
*/
- public String getServletInfo() {
- return INFO;
+ public String getServletInfo() {
+ return INFO;
}
/**
* Process the HTTP request.
- *
+ *
* @param cmsReq the object holding the request and response information
*/
public void process(CMSRequest cmsReq) throws EBaseException {
@@ -98,21 +95,21 @@ public class DisplayTransport extends CMSServlet {
}
try {
- IKeyRecoveryAuthority kra =
- (IKeyRecoveryAuthority) mAuthority;
+ IKeyRecoveryAuthority kra =
+ (IKeyRecoveryAuthority) mAuthority;
ITransportKeyUnit tu = kra.getTransportKeyUnit();
org.mozilla.jss.crypto.X509Certificate transportCert =
- tu.getCertificate();
+ tu.getCertificate();
resp.setStatus(HttpServletResponse.SC_OK);
resp.setContentType("text/html");
- String content = "";
+ String content = "";
content += "<HTML><PRE>";
- String mime64 =
- "-----BEGIN CERTIFICATE-----\n" +
- CMS.BtoA(transportCert.getEncoded()) +
- "-----END CERTIFICATE-----\n";
+ String mime64 =
+ "-----BEGIN CERTIFICATE-----\n" +
+ CMS.BtoA(transportCert.getEncoded()) +
+ "-----END CERTIFICATE-----\n";
content += mime64;
content += "</PRE></HTML>";
@@ -120,9 +117,9 @@ public class DisplayTransport extends CMSServlet {
resp.getOutputStream().write(content.getBytes());
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
cmsReq.setStatus(CMSRequest.SUCCESS);
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/key/ExamineRecovery.java b/pki/base/common/src/com/netscape/cms/servlet/key/ExamineRecovery.java
index 9fbad7a6..9d569a0d 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/key/ExamineRecovery.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/key/ExamineRecovery.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.key;
-
import java.io.IOException;
import java.math.BigInteger;
import java.util.Hashtable;
@@ -46,10 +45,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
- * View the Key Recovery Request
- *
+ * View the Key Recovery Request
+ *
* @version $Revision$, $Date$
*/
public class ExamineRecovery extends CMSServlet {
@@ -100,8 +98,8 @@ public class ExamineRecovery extends CMSServlet {
/**
* Returns serlvet information.
*/
- public String getServletInfo() {
- return INFO;
+ public String getServletInfo() {
+ return INFO;
}
/**
@@ -109,7 +107,7 @@ public class ExamineRecovery extends CMSServlet {
* <ul>
* <li>http.param recoveryID recovery request ID
* </ul>
- *
+ *
* @param cmsReq the object holding the request and response information
*/
@@ -127,10 +125,10 @@ public class ExamineRecovery extends CMSServlet {
mAuthzResourceName, "read");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -145,9 +143,9 @@ public class ExamineRecovery extends CMSServlet {
form = getTemplate(mFormPath, req, locale);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
IArgBlock header = CMS.createArgBlock();
@@ -158,9 +156,9 @@ public class ExamineRecovery extends CMSServlet {
EBaseException error = null;
try {
- process(argSet, header,
- req.getParameter("recoveryID"),
- req, resp, locale[0]);
+ process(argSet, header,
+ req.getParameter("recoveryID"),
+ req, resp, locale[0]);
} catch (EBaseException e) {
error = e;
} catch (Exception e) {
@@ -168,28 +166,23 @@ public class ExamineRecovery extends CMSServlet {
}
/*
- catch (NumberFormatException e) {
- error = eBaseException(
-
- header.addStringValue(OUT_ERROR,
- MessageFormatter.getLocalizedString(
- locale[0],
- BaseResources.class.getName(),
- BaseResources.INTERNAL_ERROR_1,
- e.toString()));
- }
+ * catch (NumberFormatException e) { error = eBaseException(
+ *
+ * header.addStringValue(OUT_ERROR, MessageFormatter.getLocalizedString(
+ * locale[0], BaseResources.class.getName(),
+ * BaseResources.INTERNAL_ERROR_1, e.toString())); }
*/
try {
if (error == null) {
String xmlOutput = req.getParameter("xml");
if (xmlOutput != null && xmlOutput.equals("true")) {
- outputXML(resp, argSet);
+ outputXML(resp, argSet);
} else {
- ServletOutputStream out = resp.getOutputStream();
- resp.setContentType("text/html");
- form.renderOutput(out, argSet);
- cmsReq.setStatus(CMSRequest.SUCCESS);
+ ServletOutputStream out = resp.getOutputStream();
+ resp.setContentType("text/html");
+ form.renderOutput(out, argSet);
+ cmsReq.setStatus(CMSRequest.SUCCESS);
}
} else {
cmsReq.setStatus(CMSRequest.ERROR);
@@ -197,57 +190,55 @@ public class ExamineRecovery extends CMSServlet {
}
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
}
/**
- * Recovers a key. The p12 will be protected by the password
- * provided by the administrator.
+ * Recovers a key. The p12 will be protected by the password provided by the
+ * administrator.
*/
private void process(CMSTemplateParams argSet,
- IArgBlock header, String recoveryID,
- HttpServletRequest req, HttpServletResponse resp,
- Locale locale)
- throws EBaseException {
+ IArgBlock header, String recoveryID,
+ HttpServletRequest req, HttpServletResponse resp,
+ Locale locale)
+ throws EBaseException {
try {
header.addStringValue(OUT_OP,
- req.getParameter(OUT_OP));
+ req.getParameter(OUT_OP));
header.addStringValue(OUT_SERVICE_URL,
- req.getRequestURI());
+ req.getRequestURI());
header.addStringValue("keySplitting",
- CMS.getConfigStore().getString("kra.keySplitting"));
+ CMS.getConfigStore().getString("kra.keySplitting"));
Hashtable params = mService.getRecoveryParams(
recoveryID);
if (params == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_NO_RECOVERY_TOKEN_FOUND_1", recoveryID));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_NO_RECOVERY_TOKEN_FOUND_1", recoveryID));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_NO_RECOVERY_TOKEN_FOUND", recoveryID));
+ CMS.getUserMessage("CMS_GW_NO_RECOVERY_TOKEN_FOUND", recoveryID));
}
- String keyID = (String)params.get("keyID");
- header.addStringValue("serialNumber", keyID);
+ String keyID = (String) params.get("keyID");
+ header.addStringValue("serialNumber", keyID);
header.addStringValue("recoveryID", recoveryID);
- IKeyRepository mKeyDB =
- ((IKeyRecoveryAuthority) mAuthority).getKeyRepository();
+ IKeyRepository mKeyDB =
+ ((IKeyRecoveryAuthority) mAuthority).getKeyRepository();
IKeyRecord rec = (IKeyRecord) mKeyDB.readKeyRecord(new
BigInteger(keyID));
KeyRecordParser.fillRecordIntoArg(rec, header);
-
} catch (EBaseException e) {
log(ILogger.LL_FAILURE, "Error e " + e);
throw e;
- }
+ }
/*
- catch (Exception e) {
- header.addStringValue(OUT_ERROR, e.toString());
- }
+ * catch (Exception e) { header.addStringValue(OUT_ERROR, e.toString());
+ * }
*/
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/key/GetApprovalStatus.java b/pki/base/common/src/com/netscape/cms/servlet/key/GetApprovalStatus.java
index 4bd4d45b..09a084b5 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/key/GetApprovalStatus.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/key/GetApprovalStatus.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.key;
-
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
@@ -45,10 +44,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* Check to see if a Key Recovery Request has been approved
- *
+ *
* @version $Revision$, $Date$
*/
public class GetApprovalStatus extends CMSServlet {
@@ -79,9 +77,9 @@ public class GetApprovalStatus extends CMSServlet {
/**
* initialize the servlet. This servlet uses the template files
- * "getApprovalStatus.template" and "finishRecovery.template"
- * to process the response.
- *
+ * "getApprovalStatus.template" and "finishRecovery.template" to process the
+ * response.
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -95,8 +93,8 @@ public class GetApprovalStatus extends CMSServlet {
/**
* Returns serlvet information.
*/
- public String getServletInfo() {
- return INFO;
+ public String getServletInfo() {
+ return INFO;
}
/**
@@ -104,7 +102,7 @@ public class GetApprovalStatus extends CMSServlet {
* <ul>
* <li>http.param recoveryID request ID to check
* </ul>
- *
+ *
* @param cmsReq the object holding the request and response information
*/
public void process(CMSRequest cmsReq) throws EBaseException {
@@ -148,12 +146,12 @@ public class GetApprovalStatus extends CMSServlet {
if (params == null) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_NO_RECOVERY_TOKEN_FOUND_1", recoveryID));
+ CMS.getLogMessage("CMSGW_NO_RECOVERY_TOKEN_FOUND_1", recoveryID));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_NO_RECOVERY_TOKEN_FOUND", recoveryID));
+ CMS.getUserMessage("CMS_GW_NO_RECOVERY_TOKEN_FOUND", recoveryID));
}
header.addStringValue("serialNumber",
- (String) params.get("keyID"));
+ (String) params.get("keyID"));
int requiredNumber = mService.getNoOfRequiredAgents();
@@ -174,27 +172,21 @@ public class GetApprovalStatus extends CMSServlet {
if (pkcs12 != null) {
rComplete = 1;
- header.addStringValue(OUT_STATUS, "complete");
+ header.addStringValue(OUT_STATUS, "complete");
/*
- mService.destroyRecoveryParams(recoveryID);
- try {
- resp.setContentType("application/x-pkcs12");
- resp.getOutputStream().write(pkcs12);
- return;
- } catch (IOException e) {
- header.addStringValue(OUT_ERROR,
- MessageFormatter.getLocalizedString(
- locale[0],
- BaseResources.class.getName(),
- BaseResources.INTERNAL_ERROR_1,
- e.toString()));
- }
+ * mService.destroyRecoveryParams(recoveryID); try {
+ * resp.setContentType("application/x-pkcs12");
+ * resp.getOutputStream().write(pkcs12); return; } catch
+ * (IOException e) { header.addStringValue(OUT_ERROR,
+ * MessageFormatter.getLocalizedString( locale[0],
+ * BaseResources.class.getName(),
+ * BaseResources.INTERNAL_ERROR_1, e.toString())); }
*/
} else if (((IKeyRecoveryAuthority) mService).getError(recoveryID) != null) {
- // error in recovery process
- header.addStringValue(OUT_ERROR,
- ((IKeyRecoveryAuthority) mService).getError(recoveryID));
+ // error in recovery process
+ header.addStringValue(OUT_ERROR,
+ ((IKeyRecoveryAuthority) mService).getError(recoveryID));
rComplete = 1;
} else {
// pk12 hasn't been created yet.
@@ -210,16 +202,16 @@ public class GetApprovalStatus extends CMSServlet {
mFormPath = "/" + ((IAuthority) mService).getId() + "/" + TPL_FINISH;
} else {
mFormPath = "/" + ((IAuthority) mService).getId() + "/" + TPL_FILE;
- }
+ }
if (mOutputTemplatePath != null)
mFormPath = mOutputTemplatePath;
try {
form = getTemplate(mFormPath, req, locale);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
ServletOutputStream out = resp.getOutputStream();
@@ -228,9 +220,9 @@ public class GetApprovalStatus extends CMSServlet {
form.renderOutput(out, argSet);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
cmsReq.setStatus(CMSRequest.SUCCESS);
diff --git a/pki/base/common/src/com/netscape/cms/servlet/key/GetAsyncPk12.java b/pki/base/common/src/com/netscape/cms/servlet/key/GetAsyncPk12.java
index cea08af3..0a74cb26 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/key/GetAsyncPk12.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/key/GetAsyncPk12.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.key;
-
import java.io.IOException;
import java.util.Locale;
@@ -42,11 +41,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
- * Get the recovered key in PKCS#12 format
- * - for asynchronous key recovery only
- *
+ * Get the recovered key in PKCS#12 format - for asynchronous key recovery only
+ *
*/
public class GetAsyncPk12 extends CMSServlet {
@@ -67,13 +64,11 @@ public class GetAsyncPk12 extends CMSServlet {
private com.netscape.certsrv.kra.IKeyService mService = null;
private final static String OUT_STATUS = "status";
- private final static String
- LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_SUCCESS =
- "LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_SUCCESS_4";
+ private final static String LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_SUCCESS =
+ "LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_SUCCESS_4";
- private final static String
- LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_FAILURE =
- "LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_FAILURE_4";
+ private final static String LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_FAILURE =
+ "LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_FAILURE_4";
private String mFormPath = null;
@@ -87,7 +82,7 @@ public class GetAsyncPk12 extends CMSServlet {
/**
* initialize the servlet. This servlet uses the template file
* "finishAsyncRecovery.template" to process the response.
- *
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -103,8 +98,8 @@ public class GetAsyncPk12 extends CMSServlet {
/**
* Returns serlvet information.
*/
- public String getServletInfo() {
- return INFO;
+ public String getServletInfo() {
+ return INFO;
}
/**
@@ -112,7 +107,7 @@ public class GetAsyncPk12 extends CMSServlet {
* <ul>
* <li>http.param reqID request id for recovery
* </ul>
- *
+ *
* @param cmsReq the object holding the request and response information
*/
public void process(CMSRequest cmsReq) throws EBaseException {
@@ -132,10 +127,10 @@ public class GetAsyncPk12 extends CMSServlet {
mAuthzResourceName, "download");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -150,9 +145,9 @@ public class GetAsyncPk12 extends CMSServlet {
form = getTemplate(mFormPath, req, locale);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
cmsReq.setStatus(CMSRequest.SUCCESS);
@@ -173,9 +168,9 @@ public class GetAsyncPk12 extends CMSServlet {
agent = (String) sContext.get(SessionContext.USER_ID);
}
- if (agent == null ) {
- CMS.debug( "GetAsyncPk12::process() - agent is null!" );
- throw new EBaseException( "agent is null" );
+ if (agent == null) {
+ CMS.debug("GetAsyncPk12::process() - agent is null!");
+ throw new EBaseException("agent is null");
}
String initAgent = "undefined";
@@ -183,18 +178,18 @@ public class GetAsyncPk12 extends CMSServlet {
if ((initAgent.equals("undefined")) || !agent.equals(initAgent)) {
log(ILogger.LL_SECURITY,
- CMS.getLogMessage("CMSGW_INVALID_AGENT_ASYNC_3",
- reqID, initAgent));
+ CMS.getLogMessage("CMSGW_INVALID_AGENT_ASYNC_3",
+ reqID, initAgent));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_INVALID_AGENT_ASYNC",
- reqID, initAgent));
+ CMS.getUserMessage("CMS_GW_INVALID_AGENT_ASYNC",
+ reqID, initAgent));
}
// The async recovery request must be in "approved" state
- // i.e. all required # of recovery agents approved
+ // i.e. all required # of recovery agents approved
if (mService.isApprovedAsyncKeyRecovery(reqID) != true) {
CMS.debug("GetAsyncPk12::process() - # required recovery agents not met");
- throw new EBaseException( "# required recovery agents not met" );
+ throw new EBaseException("# required recovery agents not met");
}
String password = req.getParameter(IN_PASSWORD);
@@ -202,11 +197,11 @@ public class GetAsyncPk12 extends CMSServlet {
if (password == null || password.equals("")) {
header.addStringValue(OUT_ERROR, "PKCS12 password not found");
- throw new EBaseException( "PKCS12 password not found" );
+ throw new EBaseException("PKCS12 password not found");
}
if (passwordAgain == null || !passwordAgain.equals(password)) {
header.addStringValue(OUT_ERROR, "PKCS12 password not matched");
- throw new EBaseException( "PKCS12 password not matched" );
+ throw new EBaseException("PKCS12 password not matched");
}
// got all approval, return pk12
@@ -219,23 +214,23 @@ public class GetAsyncPk12 extends CMSServlet {
mRenderResult = false;
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_SUCCESS,
- agent,
- ILogger.SUCCESS,
- reqID,
- "");
+ LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_SUCCESS,
+ agent,
+ ILogger.SUCCESS,
+ reqID,
+ "");
- audit(auditMessage);
+ audit(auditMessage);
return;
} catch (IOException e) {
header.addStringValue(OUT_ERROR,
- CMS.getUserMessage(locale[0], "CMS_BASE_INTERNAL_ERROR", e.toString()));
+ CMS.getUserMessage(locale[0], "CMS_BASE_INTERNAL_ERROR", e.toString()));
}
} else if (((IKeyRecoveryAuthority) mService).getError(reqID) != null) {
- // error in recovery process
- header.addStringValue(OUT_ERROR,
- ((IKeyRecoveryAuthority) mService).getError(reqID));
+ // error in recovery process
+ header.addStringValue(OUT_ERROR,
+ ((IKeyRecoveryAuthority) mService).getError(reqID));
} else {
// pk12 hasn't been created yet. Shouldn't get here
}
@@ -245,11 +240,11 @@ public class GetAsyncPk12 extends CMSServlet {
if ((agent != null) && (reqID != null)) {
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_FAILURE,
- agent,
- ILogger.FAILURE,
- reqID,
- "");
+ LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_FAILURE,
+ agent,
+ ILogger.FAILURE,
+ reqID,
+ "");
audit(auditMessage);
}
@@ -261,9 +256,9 @@ public class GetAsyncPk12 extends CMSServlet {
form.renderOutput(out, argSet);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
cmsReq.setStatus(CMSRequest.SUCCESS);
diff --git a/pki/base/common/src/com/netscape/cms/servlet/key/GetPk12.java b/pki/base/common/src/com/netscape/cms/servlet/key/GetPk12.java
index b3651774..f27e966d 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/key/GetPk12.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/key/GetPk12.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.key;
-
import java.io.IOException;
import java.util.Hashtable;
import java.util.Locale;
@@ -43,10 +42,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* Get the recovered key in PKCS#12 format
- *
+ *
* @version $Revision$, $Date$
*/
public class GetPk12 extends CMSServlet {
@@ -66,13 +64,11 @@ public class GetPk12 extends CMSServlet {
private com.netscape.certsrv.kra.IKeyService mService = null;
private final static String OUT_STATUS = "status";
- private final static String
- LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_SUCCESS =
- "LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_SUCCESS_4";
+ private final static String LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_SUCCESS =
+ "LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_SUCCESS_4";
- private final static String
- LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_FAILURE =
- "LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_FAILURE_4";
+ private final static String LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_FAILURE =
+ "LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_FAILURE_4";
private String mFormPath = null;
@@ -86,7 +82,7 @@ public class GetPk12 extends CMSServlet {
/**
* initialize the servlet. This servlet uses the template file
* "finishRecovery.template" to process the response.
- *
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -102,8 +98,8 @@ public class GetPk12 extends CMSServlet {
/**
* Returns serlvet information.
*/
- public String getServletInfo() {
- return INFO;
+ public String getServletInfo() {
+ return INFO;
}
/**
@@ -111,7 +107,7 @@ public class GetPk12 extends CMSServlet {
* <ul>
* <li>http.param recoveryID ID of request to recover
* </ul>
- *
+ *
* @param cmsReq the object holding the request and response information
*/
public void process(CMSRequest cmsReq) throws EBaseException {
@@ -131,10 +127,10 @@ public class GetPk12 extends CMSServlet {
mAuthzResourceName, "download");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -149,9 +145,9 @@ public class GetPk12 extends CMSServlet {
form = getTemplate(mFormPath, req, locale);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
cmsReq.setStatus(CMSRequest.SUCCESS);
@@ -170,9 +166,9 @@ public class GetPk12 extends CMSServlet {
if (params == null) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_NO_RECOVERY_TOKEN_FOUND_1", recoveryID));
+ CMS.getLogMessage("CMSGW_NO_RECOVERY_TOKEN_FOUND_1", recoveryID));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_NO_RECOVERY_TOKEN_FOUND", recoveryID));
+ CMS.getUserMessage("CMS_GW_NO_RECOVERY_TOKEN_FOUND", recoveryID));
}
// only the init DRM agent can get the pkcs12
@@ -181,26 +177,26 @@ public class GetPk12 extends CMSServlet {
agent = (String) sContext.get(SessionContext.USER_ID);
}
- if (agent == null ) {
- CMS.debug( "GetPk12::process() - agent is null!" );
- throw new EBaseException( "agent is null" );
+ if (agent == null) {
+ CMS.debug("GetPk12::process() - agent is null!");
+ throw new EBaseException("agent is null");
}
- String initAgent = (String) params.get("agent");
+ String initAgent = (String) params.get("agent");
if (!agent.equals(initAgent)) {
log(ILogger.LL_SECURITY,
-
- CMS.getLogMessage("CMSGW_INVALID_AGENT_3",
+
+ CMS.getLogMessage("CMSGW_INVALID_AGENT_3",
recoveryID,
initAgent));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_INVALID_AGENT",
- agent, initAgent, recoveryID));
+ CMS.getUserMessage("CMS_GW_INVALID_AGENT",
+ agent, initAgent, recoveryID));
}
header.addStringValue("serialNumber",
- (String) params.get("keyID"));
+ (String) params.get("keyID"));
// got all approval, return pk12
byte pkcs12[] = ((IKeyRecoveryAuthority) mService).getPk12(recoveryID);
@@ -213,23 +209,23 @@ public class GetPk12 extends CMSServlet {
mRenderResult = false;
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_SUCCESS,
- agent,
- ILogger.SUCCESS,
- recoveryID,
- "");
+ LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_SUCCESS,
+ agent,
+ ILogger.SUCCESS,
+ recoveryID,
+ "");
audit(auditMessage);
return;
} catch (IOException e) {
header.addStringValue(OUT_ERROR,
- CMS.getUserMessage(locale[0], "CMS_BASE_INTERNAL_ERROR", e.toString()));
+ CMS.getUserMessage(locale[0], "CMS_BASE_INTERNAL_ERROR", e.toString()));
}
} else if (((IKeyRecoveryAuthority) mService).getError(recoveryID) != null) {
// error in recovery process
- header.addStringValue(OUT_ERROR,
- ((IKeyRecoveryAuthority) mService).getError(recoveryID));
+ header.addStringValue(OUT_ERROR,
+ ((IKeyRecoveryAuthority) mService).getError(recoveryID));
} else {
// pk12 hasn't been created yet. Shouldn't get here
}
@@ -239,11 +235,11 @@ public class GetPk12 extends CMSServlet {
if ((agent != null) && (recoveryID != null)) {
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_FAILURE,
- agent,
- ILogger.FAILURE,
- recoveryID,
- "");
+ LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_FAILURE,
+ agent,
+ ILogger.FAILURE,
+ recoveryID,
+ "");
audit(auditMessage);
}
@@ -255,9 +251,9 @@ public class GetPk12 extends CMSServlet {
form.renderOutput(out, argSet);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
cmsReq.setStatus(CMSRequest.SUCCESS);
diff --git a/pki/base/common/src/com/netscape/cms/servlet/key/GrantAsyncRecovery.java b/pki/base/common/src/com/netscape/cms/servlet/key/GrantAsyncRecovery.java
index a868f47c..a6c26dc5 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/key/GrantAsyncRecovery.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/key/GrantAsyncRecovery.java
@@ -40,10 +40,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* Approve an asynchronous key recovery request
- *
+ *
*/
public class GrantAsyncRecovery extends CMSServlet {
@@ -69,7 +68,7 @@ public class GrantAsyncRecovery extends CMSServlet {
private String mFormPath = null;
private final static String LOGGING_SIGNED_AUDIT_KEY_RECOVERY_AGENT_LOGIN =
- "LOGGING_SIGNED_AUDIT_KEY_RECOVERY_AGENT_LOGIN_4";
+ "LOGGING_SIGNED_AUDIT_KEY_RECOVERY_AGENT_LOGIN_4";
/**
* Constructs EA servlet.
@@ -81,7 +80,7 @@ public class GrantAsyncRecovery extends CMSServlet {
/**
* initialize the servlet. This servlet uses the template file
* 'grantAsyncRecovery.template' to process the response.
- *
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -98,8 +97,8 @@ public class GrantAsyncRecovery extends CMSServlet {
/**
* Returns serlvet information.
*/
- public String getServletInfo() {
- return INFO;
+ public String getServletInfo() {
+ return INFO;
}
/**
@@ -107,9 +106,9 @@ public class GrantAsyncRecovery extends CMSServlet {
* <ul>
* <li>http.param reqID request ID of the request to approve
* <li>http.param agentID User ID of the agent approving the request
-
+ *
* </ul>
- *
+ *
* @param cmsReq the object holding the request and response information
*/
public void process(CMSRequest cmsReq) throws EBaseException {
@@ -128,10 +127,10 @@ public class GrantAsyncRecovery extends CMSServlet {
mAuthzResourceName, "recover");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -146,9 +145,9 @@ public class GrantAsyncRecovery extends CMSServlet {
form = getTemplate(mFormPath, req, locale);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
IArgBlock header = CMS.createArgBlock();
@@ -161,13 +160,13 @@ public class GrantAsyncRecovery extends CMSServlet {
CMS.debug("GrantAsyncRecovery: process() agent uid=" + agentID);
CMS.debug("GrantAsyncRecovery: process() request id=" + req.getParameter("reqID"));
try {
- process(argSet, header,
- req.getParameter("reqID"),
- agentID,
- req, resp, locale[0]);
+ process(argSet, header,
+ req.getParameter("reqID"),
+ agentID,
+ req, resp, locale[0]);
} catch (NumberFormatException e) {
header.addStringValue(OUT_ERROR,
- CMS.getUserMessage(locale[0], "CMS_BASE_INTERNAL_ERROR", e.toString()));
+ CMS.getUserMessage(locale[0], "CMS_BASE_INTERNAL_ERROR", e.toString()));
}
try {
ServletOutputStream out = resp.getOutputStream();
@@ -176,9 +175,9 @@ public class GrantAsyncRecovery extends CMSServlet {
form.renderOutput(out, argSet);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
cmsReq.setStatus(CMSRequest.SUCCESS);
}
@@ -186,12 +185,13 @@ public class GrantAsyncRecovery extends CMSServlet {
/**
* Update agent approval list
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_KEY_RECOVERY_AGENT_LOGIN used
* whenever DRM agents login as recovery agents to approve key recovery
* requests
* </ul>
+ *
* @param argSet CMS template parameters
* @param header argument block
* @param reqID string containing the recovery request ID
@@ -201,10 +201,10 @@ public class GrantAsyncRecovery extends CMSServlet {
* @param locale the system locale
*/
private void process(CMSTemplateParams argSet,
- IArgBlock header, String reqID,
- String agentID,
- HttpServletRequest req, HttpServletResponse resp,
- Locale locale) {
+ IArgBlock header, String reqID,
+ String agentID,
+ HttpServletRequest req, HttpServletResponse resp,
+ Locale locale) {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
String auditRequestID = reqID;
@@ -234,9 +234,9 @@ public class GrantAsyncRecovery extends CMSServlet {
try {
header.addStringValue(OUT_OP,
- req.getParameter(OUT_OP));
+ req.getParameter(OUT_OP));
header.addStringValue(OUT_SERVICE_URL,
- req.getRequestURI());
+ req.getRequestURI());
// update approving agent list
mService.addAgentAsyncKeyRecovery(reqID, agentID);
@@ -281,4 +281,3 @@ public class GrantAsyncRecovery extends CMSServlet {
}
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/key/GrantRecovery.java b/pki/base/common/src/com/netscape/cms/servlet/key/GrantRecovery.java
index 9a7238be..a7356b3c 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/key/GrantRecovery.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/key/GrantRecovery.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.key;
-
import java.io.IOException;
import java.util.Hashtable;
import java.util.Locale;
@@ -42,10 +41,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* Approve a key recovery request
- *
+ *
* @version $Revision$, $Date$
*/
public class GrantRecovery extends CMSServlet {
@@ -74,7 +72,7 @@ public class GrantRecovery extends CMSServlet {
private String mFormPath = null;
private final static String LOGGING_SIGNED_AUDIT_KEY_RECOVERY_AGENT_LOGIN =
- "LOGGING_SIGNED_AUDIT_KEY_RECOVERY_AGENT_LOGIN_4";
+ "LOGGING_SIGNED_AUDIT_KEY_RECOVERY_AGENT_LOGIN_4";
/**
* Constructs EA servlet.
@@ -86,7 +84,7 @@ public class GrantRecovery extends CMSServlet {
/**
* initialize the servlet. This servlet uses the template file
* 'grantRecovery.template' to process the response.
- *
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -103,19 +101,19 @@ public class GrantRecovery extends CMSServlet {
/**
* Returns serlvet information.
*/
- public String getServletInfo() {
- return INFO;
+ public String getServletInfo() {
+ return INFO;
}
/**
* Process the HTTP request.
* <ul>
* <li>http.param recoveryID ID of the request to approve
- * <li>http.param agentID User ID of the agent approving the request
- * <li>http.param agentPWD Password of the agent approving the request
-
+ * <li>http.param agentID User ID of the agent approving the request
+ * <li>http.param agentPWD Password of the agent approving the request
+ *
* </ul>
- *
+ *
* @param cmsReq the object holding the request and response information
*/
public void process(CMSRequest cmsReq) throws EBaseException {
@@ -132,10 +130,10 @@ public class GrantRecovery extends CMSServlet {
mAuthzResourceName, "recover");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -150,9 +148,9 @@ public class GrantRecovery extends CMSServlet {
form = getTemplate(mFormPath, req, locale);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
IArgBlock header = CMS.createArgBlock();
@@ -166,14 +164,14 @@ public class GrantRecovery extends CMSServlet {
agentID = req.getParameter("agentID");
}
try {
- process(argSet, header,
- req.getParameter("recoveryID"),
- agentID,
- req.getParameter("agentPWD"),
- req, resp, locale[0]);
+ process(argSet, header,
+ req.getParameter("recoveryID"),
+ agentID,
+ req.getParameter("agentPWD"),
+ req, resp, locale[0]);
} catch (NumberFormatException e) {
header.addStringValue(OUT_ERROR,
- CMS.getUserMessage(locale[0], "CMS_BASE_INTERNAL_ERROR", e.toString()));
+ CMS.getUserMessage(locale[0], "CMS_BASE_INTERNAL_ERROR", e.toString()));
}
try {
ServletOutputStream out = resp.getOutputStream();
@@ -182,23 +180,24 @@ public class GrantRecovery extends CMSServlet {
form.renderOutput(out, argSet);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
cmsReq.setStatus(CMSRequest.SUCCESS);
}
/**
- * Recovers a key. The p12 will be protected by the password
- * provided by the administrator.
+ * Recovers a key. The p12 will be protected by the password provided by the
+ * administrator.
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_KEY_RECOVERY_AGENT_LOGIN used
* whenever DRM agents login as recovery agents to approve key recovery
* requests
* </ul>
+ *
* @param argSet CMS template parameters
* @param header argument block
* @param recoveryID string containing the recovery ID
@@ -209,10 +208,10 @@ public class GrantRecovery extends CMSServlet {
* @param locale the system locale
*/
private void process(CMSTemplateParams argSet,
- IArgBlock header, String recoveryID,
- String agentID, String agentPWD,
- HttpServletRequest req, HttpServletResponse resp,
- Locale locale) {
+ IArgBlock header, String recoveryID,
+ String agentID, String agentPWD,
+ HttpServletRequest req, HttpServletResponse resp,
+ Locale locale) {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
String auditRecoveryID = recoveryID;
@@ -242,15 +241,15 @@ public class GrantRecovery extends CMSServlet {
try {
header.addStringValue(OUT_OP,
- req.getParameter(OUT_OP));
+ req.getParameter(OUT_OP));
header.addStringValue(OUT_SERVICE_URL,
- req.getRequestURI());
+ req.getRequestURI());
Hashtable h = mService.getRecoveryParams(recoveryID);
if (h == null) {
- header.addStringValue(OUT_ERROR,
- "No such token found");
+ header.addStringValue(OUT_ERROR,
+ "No such token found");
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -265,13 +264,13 @@ public class GrantRecovery extends CMSServlet {
return;
}
header.addStringValue("serialNumber",
- (String) h.get("keyID"));
+ (String) h.get("keyID"));
mService.addDistributedCredential(recoveryID, agentID, agentPWD);
header.addStringValue("agentID",
- agentID);
+ agentID);
header.addStringValue("recoveryID",
- recoveryID);
+ recoveryID);
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -310,4 +309,3 @@ public class GrantRecovery extends CMSServlet {
}
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/key/KeyRecordParser.java b/pki/base/common/src/com/netscape/cms/servlet/key/KeyRecordParser.java
index 9ce8585f..fc6498f5 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/key/KeyRecordParser.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/key/KeyRecordParser.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.key;
-
import java.util.Date;
import com.netscape.certsrv.apps.CMS;
@@ -28,7 +27,7 @@ import com.netscape.certsrv.dbs.keydb.IKeyRecord;
/**
* Output a 'pretty print' of a Key Archival record
- *
+ *
* @version $Revision$, $Date$
*/
public class KeyRecordParser {
@@ -44,28 +43,27 @@ public class KeyRecordParser {
public final static String OUT_RECOVERED_BY = "recoveredBy";
public final static String OUT_RECOVERED_ON = "recoveredOn";
-
/**
* Fills key record into argument block.
*/
- public static void fillRecordIntoArg(IKeyRecord rec, IArgBlock rarg)
- throws EBaseException {
+ public static void fillRecordIntoArg(IKeyRecord rec, IArgBlock rarg)
+ throws EBaseException {
if (rec == null)
return;
rarg.addStringValue(OUT_STATE,
- rec.getState().toString());
+ rec.getState().toString());
rarg.addStringValue(OUT_OWNER_NAME,
- rec.getOwnerName());
+ rec.getOwnerName());
rarg.addIntegerValue(OUT_SERIALNO,
- rec.getSerialNumber().intValue());
+ rec.getSerialNumber().intValue());
rarg.addStringValue(OUT_KEY_ALGORITHM,
- rec.getAlgorithm());
- // Possible Enhancement: sun's BASE64Encode is not
+ rec.getAlgorithm());
+ // Possible Enhancement: sun's BASE64Encode is not
// fast. We may may to have our native implmenetation.
IPrettyPrintFormat pp = CMS.getPrettyPrintFormat(":");
rarg.addStringValue(OUT_PUBLIC_KEY,
- pp.toHexString(rec.getPublicKeyData(), 0, 20));
+ pp.toHexString(rec.getPublicKeyData(), 0, 20));
Integer keySize = rec.getKeySize();
if (keySize == null) {
@@ -74,16 +72,16 @@ public class KeyRecordParser {
rarg.addIntegerValue(OUT_KEY_LEN, keySize.intValue());
}
rarg.addStringValue(OUT_ARCHIVED_BY,
- rec.getArchivedBy());
+ rec.getArchivedBy());
rarg.addLongValue(OUT_ARCHIVED_ON,
- rec.getCreateTime().getTime() / 1000);
+ rec.getCreateTime().getTime() / 1000);
Date dateOfRevocation[] = rec.getDateOfRevocation();
if (dateOfRevocation != null) {
- rarg.addStringValue(OUT_RECOVERED_BY,
- "null");
- rarg.addStringValue(OUT_RECOVERED_ON,
- "null");
+ rarg.addStringValue(OUT_RECOVERED_BY,
+ "null");
+ rarg.addStringValue(OUT_RECOVERED_ON,
+ "null");
}
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/key/RecoverBySerial.java b/pki/base/common/src/com/netscape/cms/servlet/key/RecoverBySerial.java
index edcd2bdf..5a590a8e 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/key/RecoverBySerial.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/key/RecoverBySerial.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.key;
-
import java.io.IOException;
import java.math.BigInteger;
import java.util.Hashtable;
@@ -51,7 +50,7 @@ import com.netscape.cmsutil.util.Cert;
/**
* A class representing a recoverBySerial servlet.
- *
+ *
* @version $Revision$, $Date$
*/
public class RecoverBySerial extends CMSServlet {
@@ -108,22 +107,17 @@ public class RecoverBySerial extends CMSServlet {
/**
* Returns serlvet information.
*/
- public String getServletInfo() {
- return INFO;
+ public String getServletInfo() {
+ return INFO;
}
/**
* Serves HTTP request. The format of this request is as follows:
- * recoverBySerial?
- * [serialNumber=<number>]
- * [uid#=<uid>]
- * [pwd#=<password>]
- * [localAgents=yes|null]
- * [recoveryID=recoveryID]
- * [pkcs12Password=<password of pkcs12>]
- * [pkcs12PasswordAgain=<password of pkcs12>]
- * [pkcs12Delivery=<delivery mechanism for pkcs12>]
- * [cert=<encryption certificate>]
+ * recoverBySerial? [serialNumber=<number>] [uid#=<uid>] [pwd#=<password>]
+ * [localAgents=yes|null] [recoveryID=recoveryID] [pkcs12Password=<password
+ * of pkcs12>] [pkcs12PasswordAgain=<password of pkcs12>]
+ * [pkcs12Delivery=<delivery mechanism for pkcs12>] [cert=<encryption
+ * certificate>]
*/
public void process(CMSRequest cmsReq) throws EBaseException {
@@ -138,10 +132,10 @@ public class RecoverBySerial extends CMSServlet {
mAuthzResourceName, "recover");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -156,9 +150,9 @@ public class RecoverBySerial extends CMSServlet {
form = getTemplate(mFormPath, req, locale);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
cmsReq.setStatus(CMSRequest.SUCCESS);
@@ -189,54 +183,52 @@ public class RecoverBySerial extends CMSServlet {
ctx = SessionContext.getContext();
/*
- When Recovery is first initiated, if it is in asynch mode,
- no pkcs#12 password is needed.
- The initiating agent uid will be recorded in the recovery
- request.
- Later, as approving agents submit their approvals, they will
- also be listed in the request.
+ * When Recovery is first initiated, if it is in asynch mode, no
+ * pkcs#12 password is needed. The initiating agent uid will be
+ * recorded in the recovery request. Later, as approving agents
+ * submit their approvals, they will also be listed in the request.
*/
if ((initAsyncRecovery != null) &&
- initAsyncRecovery.equalsIgnoreCase("ON")) {
- process(form, argSet, header,
- req.getParameter(IN_SERIALNO),
- req.getParameter(IN_CERT),
- req, resp, locale[0]);
-
- int requiredNumber = mService.getNoOfRequiredAgents();
- header.addIntegerValue("noOfRequiredAgents", requiredNumber);
+ initAsyncRecovery.equalsIgnoreCase("ON")) {
+ process(form, argSet, header,
+ req.getParameter(IN_SERIALNO),
+ req.getParameter(IN_CERT),
+ req, resp, locale[0]);
+
+ int requiredNumber = mService.getNoOfRequiredAgents();
+ header.addIntegerValue("noOfRequiredAgents", requiredNumber);
} else {
String recoveryID = req.getParameter("recoveryID");
if (recoveryID != null && !recoveryID.equals("")) {
- ctx.put(SessionContext.RECOVERY_ID,
- req.getParameter("recoveryID"));
+ ctx.put(SessionContext.RECOVERY_ID,
+ req.getParameter("recoveryID"));
+ }
+ byte pkcs12[] = process(form, argSet, header,
+ req.getParameter(IN_SERIALNO),
+ req.getParameter("localAgents"),
+ req.getParameter(IN_PASSWORD),
+ req.getParameter(IN_PASSWORD_AGAIN),
+ req.getParameter(IN_CERT),
+ req.getParameter(IN_DELIVERY),
+ req.getParameter(IN_NICKNAME),
+ req, resp, locale[0]);
+
+ if (pkcs12 != null) {
+ // resp.setStatus(HttpServletResponse.SC_OK);
+ resp.setContentType("application/x-pkcs12");
+ // resp.setContentLength(pkcs12.length);
+ resp.getOutputStream().write(pkcs12);
+ mRenderResult = false;
+ return;
}
- byte pkcs12[] = process(form, argSet, header,
- req.getParameter(IN_SERIALNO),
- req.getParameter("localAgents"),
- req.getParameter(IN_PASSWORD),
- req.getParameter(IN_PASSWORD_AGAIN),
- req.getParameter(IN_CERT),
- req.getParameter(IN_DELIVERY),
- req.getParameter(IN_NICKNAME),
- req, resp, locale[0]);
-
- if (pkcs12 != null) {
- //resp.setStatus(HttpServletResponse.SC_OK);
- resp.setContentType("application/x-pkcs12");
- //resp.setContentLength(pkcs12.length);
- resp.getOutputStream().write(pkcs12);
- mRenderResult = false;
- return;
- }
}
} catch (NumberFormatException e) {
header.addStringValue(OUT_ERROR,
- CMS.getUserMessage(locale[0], "CMS_BASE_INTERNAL_ERROR", e.toString()));
+ CMS.getUserMessage(locale[0], "CMS_BASE_INTERNAL_ERROR", e.toString()));
} catch (IOException e) {
header.addStringValue(OUT_ERROR,
- CMS.getUserMessage(locale[0], "CMS_BASE_INTERNAL_ERROR", e.toString()));
+ CMS.getUserMessage(locale[0], "CMS_BASE_INTERNAL_ERROR", e.toString()));
} finally {
SessionContext.releaseContext();
}
@@ -249,9 +241,9 @@ public class RecoverBySerial extends CMSServlet {
form.renderOutput(out, argSet);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
cmsReq.setStatus(CMSRequest.SUCCESS);
@@ -260,10 +252,10 @@ public class RecoverBySerial extends CMSServlet {
/**
* Async Key Recovery - request initiation
*/
- private void process(CMSTemplate form, CMSTemplateParams argSet,
- IArgBlock header, String seq, String cert,
- HttpServletRequest req, HttpServletResponse resp,
- Locale locale) {
+ private void process(CMSTemplate form, CMSTemplateParams argSet,
+ IArgBlock header, String seq, String cert,
+ HttpServletRequest req, HttpServletResponse resp,
+ Locale locale) {
// seq is the key id
if (seq == null) {
@@ -291,37 +283,37 @@ public class RecoverBySerial extends CMSServlet {
try {
String reqID = mService.initAsyncKeyRecovery(
- new BigInteger(seq), x509cert,
+ new BigInteger(seq), x509cert,
(String) sContext.get(SessionContext.USER_ID));
header.addStringValue(OUT_SERIALNO, req.getParameter(IN_SERIALNO));
header.addStringValue("requestID", reqID);
} catch (EBaseException e) {
String error =
- "Failed to recover key for key id " +
- seq + ".\nException: " + e.toString();
+ "Failed to recover key for key id " +
+ seq + ".\nException: " + e.toString();
CMS.getLogger().log(ILogger.EV_SYSTEM,
- ILogger.S_KRA, ILogger.LL_FAILURE, error);
+ ILogger.S_KRA, ILogger.LL_FAILURE, error);
try {
((IKeyRecoveryAuthority) mService).createError(seq, error);
} catch (EBaseException eb) {
CMS.getLogger().log(ILogger.EV_SYSTEM,
- ILogger.S_KRA, ILogger.LL_FAILURE, eb.toString());
+ ILogger.S_KRA, ILogger.LL_FAILURE, eb.toString());
}
}
return;
}
/**
- * Recovers a key. The p12 will be protected by the password
- * provided by the administrator.
+ * Recovers a key. The p12 will be protected by the password provided by the
+ * administrator.
*/
private byte[] process(CMSTemplate form, CMSTemplateParams argSet,
- IArgBlock header, String seq, String localAgents,
- String password, String passwordAgain,
- String cert, String delivery, String nickname,
- HttpServletRequest req, HttpServletResponse resp,
- Locale locale) {
+ IArgBlock header, String seq, String localAgents,
+ String password, String passwordAgain,
+ String cert, String delivery, String nickname,
+ HttpServletRequest req, HttpServletResponse resp,
+ Locale locale) {
if (seq == null) {
header.addStringValue(OUT_ERROR, "sequence number not found");
return null;
@@ -360,65 +352,65 @@ public class RecoverBySerial extends CMSServlet {
if (sContext != null) {
agent = (String) sContext.get(SessionContext.USER_ID);
}
- if (CMS.getConfigStore().getBoolean("kra.keySplitting")) {
- if (localAgents == null) {
- String recoveryID = req.getParameter("recoveryID");
+ if (CMS.getConfigStore().getBoolean("kra.keySplitting")) {
+ if (localAgents == null) {
+ String recoveryID = req.getParameter("recoveryID");
- if (recoveryID == null || recoveryID.equals("")) {
- header.addStringValue(OUT_ERROR, "No recovery ID specified");
- return null;
- }
- Hashtable params = mService.createRecoveryParams(recoveryID);
+ if (recoveryID == null || recoveryID.equals("")) {
+ header.addStringValue(OUT_ERROR, "No recovery ID specified");
+ return null;
+ }
+ Hashtable params = mService.createRecoveryParams(recoveryID);
- params.put("keyID", req.getParameter(IN_SERIALNO));
+ params.put("keyID", req.getParameter(IN_SERIALNO));
- header.addStringValue("recoveryID", recoveryID);
+ header.addStringValue("recoveryID", recoveryID);
- params.put("agent", agent);
+ params.put("agent", agent);
- // new thread to wait for pk12
- Thread waitThread = new WaitApprovalThread(recoveryID,
- seq, password, x509cert, delivery, nickname,
- SessionContext.getContext());
+ // new thread to wait for pk12
+ Thread waitThread = new WaitApprovalThread(recoveryID,
+ seq, password, x509cert, delivery, nickname,
+ SessionContext.getContext());
- waitThread.start();
- return null;
- } else {
- Vector v = new Vector();
-
- for (int i = 0; i < mService.getNoOfRequiredAgents(); i++) {
- String uid = req.getParameter(IN_UID + i);
- String pwd = req.getParameter(IN_PWD + i);
-
- if (uid != null && pwd != null && !uid.equals("") &&
- !pwd.equals("")) {
- v.addElement(new Credential(uid, pwd));
- } else {
+ waitThread.start();
+ return null;
+ } else {
+ Vector v = new Vector();
+
+ for (int i = 0; i < mService.getNoOfRequiredAgents(); i++) {
+ String uid = req.getParameter(IN_UID + i);
+ String pwd = req.getParameter(IN_PWD + i);
+
+ if (uid != null && pwd != null && !uid.equals("") &&
+ !pwd.equals("")) {
+ v.addElement(new Credential(uid, pwd));
+ } else {
+ header.addStringValue(OUT_ERROR, "Uid(s) or password(s) are not provided");
+ return null;
+ }
+ }
+ if (v.size() != mService.getNoOfRequiredAgents()) {
header.addStringValue(OUT_ERROR, "Uid(s) or password(s) are not provided");
return null;
}
+ creds = new Credential[v.size()];
+ v.copyInto(creds);
}
- if (v.size() != mService.getNoOfRequiredAgents()) {
- header.addStringValue(OUT_ERROR, "Uid(s) or password(s) are not provided");
- return null;
- }
- creds = new Credential[v.size()];
- v.copyInto(creds);
- }
- header.addStringValue(OUT_OP,
- req.getParameter(OUT_OP));
- header.addIntegerValue(OUT_SERIALNO,
- Integer.parseInt(seq));
- header.addStringValue(OUT_SERVICE_URL,
- req.getRequestURI());
- byte pkcs12[] = mService.doKeyRecovery(
- new BigInteger(seq),
- creds, password, x509cert,
- delivery, nickname, agent);
-
- return pkcs12;
- } else {
+ header.addStringValue(OUT_OP,
+ req.getParameter(OUT_OP));
+ header.addIntegerValue(OUT_SERIALNO,
+ Integer.parseInt(seq));
+ header.addStringValue(OUT_SERVICE_URL,
+ req.getRequestURI());
+ byte pkcs12[] = mService.doKeyRecovery(
+ new BigInteger(seq),
+ creds, password, x509cert,
+ delivery, nickname, agent);
+
+ return pkcs12;
+ } else {
String recoveryID = req.getParameter("recoveryID");
if (recoveryID == null || recoveryID.equals("")) {
@@ -440,7 +432,7 @@ public class RecoverBySerial extends CMSServlet {
waitThread.start();
return null;
- }
+ }
} catch (EBaseException e) {
header.addStringValue(OUT_ERROR, e.toString(locale));
} catch (Exception e) {
@@ -450,8 +442,8 @@ public class RecoverBySerial extends CMSServlet {
}
/**
- * Wait approval thread. Wait for recovery agents' approval
- * exit when required number of approval received
+ * Wait approval thread. Wait for recovery agents' approval exit when
+ * required number of approval received
*/
final class WaitApprovalThread extends Thread {
String theRecoveryID = null;
@@ -462,24 +454,24 @@ public class RecoverBySerial extends CMSServlet {
String theNickname = null;
SessionContext theSc = null;
- /**
+ /**
* Wait approval thread constructor including thread name
*/
public WaitApprovalThread(String recoveryID, String seq,
- String password, X509CertImpl cert,
- String delivery, String nickname, SessionContext sc) {
+ String password, X509CertImpl cert,
+ String delivery, String nickname, SessionContext sc) {
super();
- super.setName("waitApproval." + recoveryID + "-" +
- (Thread.activeCount() + 1));
+ super.setName("waitApproval." + recoveryID + "-" +
+ (Thread.activeCount() + 1));
theRecoveryID = recoveryID;
theSeq = seq;
thePassword = password;
theCert = cert;
theDelivery = delivery;
theNickname = nickname;
- theSc = sc;
+ theSc = sc;
}
-
+
public void run() {
SessionContext.setContext(theSc);
Credential creds[] = null;
@@ -487,17 +479,17 @@ public class RecoverBySerial extends CMSServlet {
try {
creds = mService.getDistributedCredentials(theRecoveryID);
} catch (EBaseException e) {
- String error =
- "Failed to get required approvals for recovery id " +
- theRecoveryID + ".\nException: " + e.toString();
+ String error =
+ "Failed to get required approvals for recovery id " +
+ theRecoveryID + ".\nException: " + e.toString();
CMS.getLogger().log(ILogger.EV_SYSTEM,
- ILogger.S_KRA, ILogger.LL_FAILURE, error);
+ ILogger.S_KRA, ILogger.LL_FAILURE, error);
try {
((IKeyRecoveryAuthority) mService).createError(theRecoveryID, error);
} catch (EBaseException eb) {
CMS.getLogger().log(ILogger.EV_SYSTEM,
- ILogger.S_KRA, ILogger.LL_FAILURE, eb.toString());
+ ILogger.S_KRA, ILogger.LL_FAILURE, eb.toString());
}
return;
}
@@ -514,16 +506,16 @@ public class RecoverBySerial extends CMSServlet {
((IKeyRecoveryAuthority) mService).createPk12(theRecoveryID, pkcs12);
} catch (EBaseException e) {
String error =
- "Failed to recover key for recovery id " +
- theRecoveryID + ".\nException: " + e.toString();
+ "Failed to recover key for recovery id " +
+ theRecoveryID + ".\nException: " + e.toString();
CMS.getLogger().log(ILogger.EV_SYSTEM,
- ILogger.S_KRA, ILogger.LL_FAILURE, error);
+ ILogger.S_KRA, ILogger.LL_FAILURE, error);
try {
((IKeyRecoveryAuthority) mService).createError(theRecoveryID, error);
} catch (EBaseException eb) {
CMS.getLogger().log(ILogger.EV_SYSTEM,
- ILogger.S_KRA, ILogger.LL_FAILURE, eb.toString());
+ ILogger.S_KRA, ILogger.LL_FAILURE, eb.toString());
}
}
return;
@@ -531,4 +523,3 @@ public class RecoverBySerial extends CMSServlet {
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/key/SrchKey.java b/pki/base/common/src/com/netscape/cms/servlet/key/SrchKey.java
index c0fdd02e..80eaf9a8 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/key/SrchKey.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/key/SrchKey.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.key;
-
import java.io.IOException;
import java.util.Enumeration;
import java.util.Locale;
@@ -48,7 +47,7 @@ import com.netscape.cms.servlet.common.ECMSGWException;
/**
* Retrieve archived keys matching search criteria
- *
+ *
* @version $Revision$, $Date$
*/
public class SrchKey extends CMSServlet {
@@ -74,7 +73,7 @@ public class SrchKey extends CMSServlet {
private final static String OUT_ERROR = "errorDetails";
private final static String OUT_ARCHIVER = "archiverName";
private final static String OUT_SERVICE_URL = "serviceURL";
- private final static String OUT_TOTAL_COUNT = "totalRecordCount";
+ private final static String OUT_TOTAL_COUNT = "totalRecordCount";
private final static String OUT_TEMPLATE = "templateName";
private IKeyRepository mKeyDB = null;
@@ -93,20 +92,21 @@ public class SrchKey extends CMSServlet {
/**
* initialize the servlet. This servlet uses the template file
* "srchKey.template" to process the response.
- *
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
super.init(sc);
mFormPath = "/" + mAuthority.getId() + "/" + TPL_FILE;
- /* maxReturns doesn't seem to do anything useful in this
- servlet!!! */
+ /*
+ * maxReturns doesn't seem to do anything useful in this servlet!!!
+ */
try {
String tmp =
- sc.getInitParameter(PROP_MAX_SEARCH_RETURNS);
+ sc.getInitParameter(PROP_MAX_SEARCH_RETURNS);
- if (tmp == null)
+ if (tmp == null)
mMaxReturns = 100;
else
mMaxReturns = Integer.parseInt(tmp);
@@ -132,20 +132,20 @@ public class SrchKey extends CMSServlet {
/**
* Returns serlvet information.
*/
- public String getServletInfo() {
- return INFO;
+ public String getServletInfo() {
+ return INFO;
}
/**
* Process the HTTP request.
* <ul>
- * <li>http.param maxCount maximum number of matches to show in result
- * <li>http.param maxResults maximum number of matches to run in ldapsearch
- * <li>http.param queryFilter ldap-style filter to search with
+ * <li>http.param maxCount maximum number of matches to show in result
+ * <li>http.param maxResults maximum number of matches to run in ldapsearch
+ * <li>http.param queryFilter ldap-style filter to search with
* <li>http.param querySentinel ID of first request to show
- * <li>http.param timeLimit number of seconds to limit ldap search to
+ * <li>http.param timeLimit number of seconds to limit ldap search to
* </ul>
- *
+ *
* @param cmsReq the object holding the request and response information
*/
public void process(CMSRequest cmsReq) throws EBaseException {
@@ -162,10 +162,10 @@ public class SrchKey extends CMSServlet {
mAuthzResourceName, "list");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -180,9 +180,9 @@ public class SrchKey extends CMSServlet {
form = getTemplate(mFormPath, req, locale);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
// process query if authentication is successful
@@ -213,11 +213,11 @@ public class SrchKey extends CMSServlet {
if (timeLimitStr != null && timeLimitStr.length() > 0)
timeLimit = Integer.parseInt(timeLimitStr);
process(argSet, header, ctx, maxCount, maxResults,
- timeLimit, sentinel,
- req.getParameter(IN_FILTER), req, resp, locale[0]);
+ timeLimit, sentinel,
+ req.getParameter(IN_FILTER), req, resp, locale[0]);
} catch (NumberFormatException e) {
header.addStringValue(OUT_ERROR,
- CMS.getUserMessage(locale[0], "CMS_BASE_INTERNAL_ERROR", e.toString()));
+ CMS.getUserMessage(locale[0], "CMS_BASE_INTERNAL_ERROR", e.toString()));
}
try {
@@ -227,9 +227,9 @@ public class SrchKey extends CMSServlet {
form.renderOutput(out, argSet);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
cmsReq.setStatus(CMSRequest.SUCCESS);
}
@@ -238,53 +238,53 @@ public class SrchKey extends CMSServlet {
* Process the key search.
*/
private void process(CMSTemplateParams argSet,
- IArgBlock header, IArgBlock ctx,
- int maxCount, int maxResults, int timeLimit, int sentinel, String filter,
- HttpServletRequest req, HttpServletResponse resp, Locale locale) {
+ IArgBlock header, IArgBlock ctx,
+ int maxCount, int maxResults, int timeLimit, int sentinel, String filter,
+ HttpServletRequest req, HttpServletResponse resp, Locale locale) {
try {
// Fill header
- header.addStringValue(OUT_OP,
- req.getParameter(OUT_OP));
+ header.addStringValue(OUT_OP,
+ req.getParameter(OUT_OP));
header.addStringValue(OUT_ARCHIVER,
- mAuthName.toString());
+ mAuthName.toString());
// STRANGE: IE does not like the following:
- // header.addStringValue(OUT_SERVICE_URL,
- // req.getRequestURI());
+ // header.addStringValue(OUT_SERVICE_URL,
+ // req.getRequestURI());
// XXX
header.addStringValue(OUT_SERVICE_URL,
- "/kra?");
+ "/kra?");
header.addStringValue(OUT_TEMPLATE,
- TPL_FILE);
+ TPL_FILE);
header.addStringValue(OUT_FILTER,
- filter);
+ filter);
if (timeLimit == -1 || timeLimit > mTimeLimits) {
CMS.debug("Resetting timelimit from " + timeLimit + " to " + mTimeLimits);
timeLimit = mTimeLimits;
}
CMS.debug("Start searching ... timelimit=" + timeLimit);
- Enumeration e = mKeyDB.searchKeys(filter,
+ Enumeration e = mKeyDB.searchKeys(filter,
maxResults, timeLimit);
int count = 0;
if (e == null) {
- header.addStringValue(OUT_SENTINEL,
- null);
+ header.addStringValue(OUT_SENTINEL,
+ null);
} else {
while (e.hasMoreElements()) {
IKeyRecord rec = (IKeyRecord)
- e.nextElement();
+ e.nextElement();
// rec is null when we specify maxResults
// DS will return an err=4, which triggers
// a LDAPException.SIZE_LIMIT_ExCEEDED
// in DSSearchResults.java
if (rec != null) {
- IArgBlock rarg = CMS.createArgBlock();
+ IArgBlock rarg = CMS.createArgBlock();
- KeyRecordParser.fillRecordIntoArg(rec, rarg);
- argSet.addRepeatRecord(rarg);
- count++;
+ KeyRecordParser.fillRecordIntoArg(rec, rarg);
+ argSet.addRepeatRecord(rarg);
+ count++;
}
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/key/SrchKeyForRecovery.java b/pki/base/common/src/com/netscape/cms/servlet/key/SrchKeyForRecovery.java
index 56a1817e..bd9e64aa 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/key/SrchKeyForRecovery.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/key/SrchKeyForRecovery.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.key;
-
import java.io.IOException;
import java.util.Enumeration;
import java.util.Locale;
@@ -48,8 +47,8 @@ import com.netscape.cms.servlet.common.ECMSGWException;
/**
* Retrieve archived keys matching given public key material
- *
- *
+ *
+ *
* @version $Revision$, $Date$
*/
public class SrchKeyForRecovery extends CMSServlet {
@@ -75,7 +74,7 @@ public class SrchKeyForRecovery extends CMSServlet {
private final static String OUT_ERROR = "errorDetails";
private final static String OUT_ARCHIVER = "archiverName";
private final static String OUT_SERVICE_URL = "serviceURL";
- private final static String OUT_TOTAL_COUNT = "totalRecordCount";
+ private final static String OUT_TOTAL_COUNT = "totalRecordCount";
private final static String OUT_TEMPLATE = "templateName";
private IKeyRepository mKeyDB = null;
@@ -94,7 +93,7 @@ public class SrchKeyForRecovery extends CMSServlet {
/**
* initialize the servlet. This servlet uses the template file
* "srchKeyForRecovery.template" to process the response.
- *
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -103,9 +102,9 @@ public class SrchKeyForRecovery extends CMSServlet {
try {
String tmp =
- sc.getInitParameter(PROP_MAX_SEARCH_RETURNS);
+ sc.getInitParameter(PROP_MAX_SEARCH_RETURNS);
- if (tmp == null)
+ if (tmp == null)
mMaxReturns = 100;
else
mMaxReturns = Integer.parseInt(tmp);
@@ -131,20 +130,20 @@ public class SrchKeyForRecovery extends CMSServlet {
/**
* Returns serlvet information.
*/
- public String getServletInfo() {
- return INFO;
+ public String getServletInfo() {
+ return INFO;
}
/**
* Process the HTTP request.
* <ul>
- * <li>http.param maxCount maximum number of matches to show in result
- * <li>http.param maxResults maximum number of matches to run in ldapsearch
+ * <li>http.param maxCount maximum number of matches to show in result
+ * <li>http.param maxResults maximum number of matches to run in ldapsearch
* <li>http.param publicKeyData public key data to search on
* <li>http.param querySentinel ID of first request to show
- * <li>http.param timeLimit number of seconds to limit ldap search to
+ * <li>http.param timeLimit number of seconds to limit ldap search to
* </ul>
- *
+ *
* @param cmsReq the object holding the request and response information
*/
@@ -161,10 +160,10 @@ public class SrchKeyForRecovery extends CMSServlet {
mAuthzResourceName, "list");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -179,11 +178,11 @@ public class SrchKeyForRecovery extends CMSServlet {
form = getTemplate(mFormPath, req, locale);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
-
+
// process query if authentication is successful
IArgBlock header = CMS.createArgBlock();
IArgBlock ctx = CMS.createArgBlock();
@@ -213,29 +212,28 @@ public class SrchKeyForRecovery extends CMSServlet {
if (timeLimitStr != null && timeLimitStr.length() > 0)
timeLimit = Integer.parseInt(timeLimitStr);
process(argSet, header, ctx, maxCount, maxResults, timeLimit, sentinel,
- req.getParameter("publicKeyData"), req.getParameter(IN_FILTER), req, resp, locale[0]);
+ req.getParameter("publicKeyData"), req.getParameter(IN_FILTER), req, resp, locale[0]);
} catch (NumberFormatException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("BASE_INVALID_NUMBER_FORMAT"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("BASE_INVALID_NUMBER_FORMAT"));
error = new EBaseException(CMS.getUserMessage(getLocale(req), "CMS_BASE_INVALID_NUMBER_FORMAT"));
}
/*
- catch (Exception e) {
- error = new EBaseException(BaseResources.INTERNAL_ERROR_1, e);
- }
+ * catch (Exception e) { error = new
+ * EBaseException(BaseResources.INTERNAL_ERROR_1, e); }
*/
try {
if (error == null) {
String xmlOutput = req.getParameter("xml");
if (xmlOutput != null && xmlOutput.equals("true")) {
- outputXML(resp, argSet);
+ outputXML(resp, argSet);
} else {
- ServletOutputStream out = resp.getOutputStream();
- resp.setContentType("text/html");
- form.renderOutput(out, argSet);
- cmsReq.setStatus(CMSRequest.SUCCESS);
+ ServletOutputStream out = resp.getOutputStream();
+ resp.setContentType("text/html");
+ form.renderOutput(out, argSet);
+ cmsReq.setStatus(CMSRequest.SUCCESS);
}
} else {
cmsReq.setStatus(CMSRequest.ERROR);
@@ -243,9 +241,9 @@ public class SrchKeyForRecovery extends CMSServlet {
}
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
}
@@ -253,31 +251,31 @@ public class SrchKeyForRecovery extends CMSServlet {
* Process the key search.
*/
private void process(CMSTemplateParams argSet,
- IArgBlock header, IArgBlock ctx,
- int maxCount, int maxResults, int timeLimit, int sentinel, String publicKeyData,
- String filter,
- HttpServletRequest req, HttpServletResponse resp, Locale locale)
- throws EBaseException {
+ IArgBlock header, IArgBlock ctx,
+ int maxCount, int maxResults, int timeLimit, int sentinel, String publicKeyData,
+ String filter,
+ HttpServletRequest req, HttpServletResponse resp, Locale locale)
+ throws EBaseException {
try {
// Fill header
- header.addStringValue(OUT_OP,
- req.getParameter(OUT_OP));
+ header.addStringValue(OUT_OP,
+ req.getParameter(OUT_OP));
header.addStringValue(OUT_ARCHIVER,
- mAuthName.toString());
+ mAuthName.toString());
// STRANGE: IE does not like the following:
- // header.addStringValue(OUT_SERVICE_URL,
- // req.getRequestURI());
+ // header.addStringValue(OUT_SERVICE_URL,
+ // req.getRequestURI());
// XXX
header.addStringValue(OUT_SERVICE_URL,
- "/kra?");
+ "/kra?");
header.addStringValue(OUT_TEMPLATE,
- TPL_FILE);
+ TPL_FILE);
header.addStringValue(OUT_FILTER,
- filter);
+ filter);
if (publicKeyData != null) {
header.addStringValue("publicKeyData",
- publicKeyData);
+ publicKeyData);
}
if (timeLimit == -1 || timeLimit > mTimeLimits) {
@@ -290,21 +288,21 @@ public class SrchKeyForRecovery extends CMSServlet {
if (e == null) {
header.addStringValue(OUT_SENTINEL,
- null);
+ null);
} else {
while (e.hasMoreElements()) {
IKeyRecord rec = (IKeyRecord)
- e.nextElement();
+ e.nextElement();
// rec is null when we specify maxResults
// DS will return an err=4, which triggers
- // a LDAPException.SIZE_LIMIT_ExCEEDED
+ // a LDAPException.SIZE_LIMIT_ExCEEDED
// in DSSearchResults.java
if (rec != null) {
- IArgBlock rarg = CMS.createArgBlock();
+ IArgBlock rarg = CMS.createArgBlock();
- KeyRecordParser.fillRecordIntoArg(rec, rarg);
- argSet.addRepeatRecord(rarg);
- count++;
+ KeyRecordParser.fillRecordIntoArg(rec, rarg);
+ argSet.addRepeatRecord(rarg);
+ count++;
}
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/ocsp/AddCAServlet.java b/pki/base/common/src/com/netscape/cms/servlet/ocsp/AddCAServlet.java
index c365d0f8..59303f6e 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/ocsp/AddCAServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/ocsp/AddCAServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.ocsp;
-
import java.io.IOException;
import java.math.BigInteger;
import java.security.cert.X509Certificate;
@@ -46,22 +45,21 @@ import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
import com.netscape.cmsutil.util.Cert;
-
/**
* Configure the CA to respond to OCSP requests for a CA
- *
+ *
* @version $Revision$ $Date$
*/
public class AddCAServlet extends CMSServlet {
-
+
/**
*
*/
private static final long serialVersionUID = 1065151608542115340L;
public static final String BEGIN_HEADER =
- "-----BEGIN CERTIFICATE-----";
+ "-----BEGIN CERTIFICATE-----";
public static final String END_HEADER =
- "-----END CERTIFICATE-----";
+ "-----END CERTIFICATE-----";
public static final BigInteger BIG_ZERO = new BigInteger("0");
public static final Long MINUS_ONE = Long.valueOf(-1);
@@ -71,9 +69,9 @@ public class AddCAServlet extends CMSServlet {
private IOCSPAuthority mOCSPAuthority = null;
private final static String LOGGING_SIGNED_AUDIT_OCSP_ADD_CA_REQUEST =
- "LOGGING_SIGNED_AUDIT_OCSP_ADD_CA_REQUEST_3";
+ "LOGGING_SIGNED_AUDIT_OCSP_ADD_CA_REQUEST_3";
private final static String LOGGING_SIGNED_AUDIT_OCSP_ADD_CA_REQUEST_PROCESSED =
- "LOGGING_SIGNED_AUDIT_OCSP_ADD_CA_REQUEST_PROCESSED_3";
+ "LOGGING_SIGNED_AUDIT_OCSP_ADD_CA_REQUEST_PROCESSED_3";
public AddCAServlet() {
super();
@@ -82,7 +80,7 @@ public class AddCAServlet extends CMSServlet {
/**
* initialize the servlet. This servlet uses the template file
* "addCA.template" to process the response.
- *
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -100,19 +98,19 @@ public class AddCAServlet extends CMSServlet {
/**
* Process the HTTP request.
* <ul>
- * <li>http.param cert ca certificate. The format is base-64, DER
- * encoded, wrapped with -----BEGIN CERTIFICATE-----,
- * -----END CERTIFICATE----- strings
- * <li>signed.audit LOGGING_SIGNED_AUDIT_OCSP_ADD_CA_REQUEST used when
- * a CA is attempted to be added to the OCSP responder
- * <li>signed.audit LOGGING_SIGNED_AUDIT_OCSP_ADD_CA_REQUEST_PROCESSED
- * used when an add CA request to the OCSP Responder is processed
+ * <li>http.param cert ca certificate. The format is base-64, DER encoded,
+ * wrapped with -----BEGIN CERTIFICATE-----, -----END CERTIFICATE-----
+ * strings
+ * <li>signed.audit LOGGING_SIGNED_AUDIT_OCSP_ADD_CA_REQUEST used when a CA
+ * is attempted to be added to the OCSP responder
+ * <li>signed.audit LOGGING_SIGNED_AUDIT_OCSP_ADD_CA_REQUEST_PROCESSED used
+ * when an add CA request to the OCSP Responder is processed
* </ul>
- *
+ *
* @param cmsReq the object holding the request and response information
*/
protected void process(CMSRequest cmsReq)
- throws EBaseException {
+ throws EBaseException {
HttpServletRequest req = cmsReq.getHttpReq();
HttpServletResponse resp = cmsReq.getHttpResp();
String auditMessage = null;
@@ -143,9 +141,9 @@ public class AddCAServlet extends CMSServlet {
form = getTemplate(mFormPath, req, locale);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
IArgBlock header = CMS.createArgBlock();
@@ -153,10 +151,10 @@ public class AddCAServlet extends CMSServlet {
CMSTemplateParams argSet = new CMSTemplateParams(header, fixed);
if (auditSubjectID.equals(ILogger.NONROLEUSER) ||
- auditSubjectID.equals(ILogger.UNIDENTIFIED)) {
+ auditSubjectID.equals(ILogger.UNIDENTIFIED)) {
String uid = authToken.getInString(IAuthToken.USER_ID);
if (uid != null) {
- CMS.debug("AddCAServlet: auditSubjectID set to "+uid);
+ CMS.debug("AddCAServlet: auditSubjectID set to " + uid);
auditSubjectID = uid;
}
}
@@ -164,12 +162,12 @@ public class AddCAServlet extends CMSServlet {
if (b64 == null) {
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_OCSP_ADD_CA_REQUEST,
- auditSubjectID,
- ILogger.FAILURE,
- ILogger.SIGNED_AUDIT_EMPTY_VALUE);
+ LOGGING_SIGNED_AUDIT_OCSP_ADD_CA_REQUEST,
+ auditSubjectID,
+ ILogger.FAILURE,
+ ILogger.SIGNED_AUDIT_EMPTY_VALUE);
- audit( auditMessage );
+ audit(auditMessage);
throw new ECMSGWException(CMS.getUserMessage(getLocale(req), "CMS_GW_MISSING_CA_CERT"));
}
@@ -177,32 +175,32 @@ public class AddCAServlet extends CMSServlet {
auditCA = Cert.normalizeCertStr(Cert.stripCertBrackets(b64.trim()));
// record the fact that a request to add CA is made
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_OCSP_ADD_CA_REQUEST,
- auditSubjectID,
- ILogger.SUCCESS,
- auditCA);
+ LOGGING_SIGNED_AUDIT_OCSP_ADD_CA_REQUEST,
+ auditSubjectID,
+ ILogger.SUCCESS,
+ auditCA);
- audit( auditMessage );
+ audit(auditMessage);
if (b64.indexOf(BEGIN_HEADER) == -1) {
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_OCSP_ADD_CA_REQUEST_PROCESSED,
- auditSubjectID,
- ILogger.FAILURE,
- auditCASubjectDN);
+ LOGGING_SIGNED_AUDIT_OCSP_ADD_CA_REQUEST_PROCESSED,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditCASubjectDN);
- audit( auditMessage );
+ audit(auditMessage);
throw new ECMSGWException(CMS.getUserMessage(getLocale(req), "CMS_GW_MISSING_CERT_HEADER"));
}
if (b64.indexOf(END_HEADER) == -1) {
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_OCSP_ADD_CA_REQUEST_PROCESSED,
- auditSubjectID,
- ILogger.FAILURE,
- auditCASubjectDN);
+ LOGGING_SIGNED_AUDIT_OCSP_ADD_CA_REQUEST_PROCESSED,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditCASubjectDN);
- audit( auditMessage );
+ audit(auditMessage);
throw new ECMSGWException(CMS.getUserMessage(getLocale(req), "CMS_GW_MISSING_CERT_FOOTER"));
}
@@ -215,17 +213,17 @@ public class AddCAServlet extends CMSServlet {
try {
X509Certificate cert = Cert.mapCert(b64);
- if( cert == null ) {
- CMS.debug( "AddCAServlet::process() - cert is null!" );
+ if (cert == null) {
+ CMS.debug("AddCAServlet::process() - cert is null!");
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_OCSP_ADD_CA_REQUEST_PROCESSED,
- auditSubjectID,
- ILogger.FAILURE,
- auditCASubjectDN);
+ LOGGING_SIGNED_AUDIT_OCSP_ADD_CA_REQUEST_PROCESSED,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditCASubjectDN);
- audit( auditMessage );
+ audit(auditMessage);
- throw new EBaseException( "cert is null" );
+ throw new EBaseException("cert is null");
} else {
certs = new X509Certificate[1];
}
@@ -247,15 +245,15 @@ public class AddCAServlet extends CMSServlet {
auditCASubjectDN = leafCert.getSubjectDN().getName();
} catch (Exception e) {
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_OCSP_ADD_CA_REQUEST_PROCESSED,
- auditSubjectID,
- ILogger.FAILURE,
- auditCASubjectDN);
+ LOGGING_SIGNED_AUDIT_OCSP_ADD_CA_REQUEST_PROCESSED,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditCASubjectDN);
- audit( auditMessage );
+ audit(auditMessage);
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_ENCODING_CA_CHAIN_ERROR"));
+ CMS.getUserMessage("CMS_GW_ENCODING_CA_CHAIN_ERROR"));
}
}
if (certs != null && certs.length > 0) {
@@ -264,32 +262,32 @@ public class AddCAServlet extends CMSServlet {
// (2) store certificate (and certificate chain) into
// database
ICRLIssuingPointRecord rec = defStore.createCRLIssuingPointRecord(
- leafCert.getSubjectDN().getName(),
- BIG_ZERO,
+ leafCert.getSubjectDN().getName(),
+ BIG_ZERO,
MINUS_ONE, null, null);
try {
rec.set(ICRLIssuingPointRecord.ATTR_CA_CERT, leafCert.getEncoded());
} catch (Exception e) {
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_OCSP_ADD_CA_REQUEST_PROCESSED,
- auditSubjectID,
- ILogger.FAILURE,
- auditCASubjectDN);
+ LOGGING_SIGNED_AUDIT_OCSP_ADD_CA_REQUEST_PROCESSED,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditCASubjectDN);
- audit( auditMessage );
+ audit(auditMessage);
// error
}
defStore.addCRLIssuingPoint(leafCert.getSubjectDN().getName(), rec);
log(ILogger.EV_AUDIT, AuditFormat.LEVEL, "Added CA certificate " + leafCert.getSubjectDN().getName());
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_OCSP_ADD_CA_REQUEST_PROCESSED,
- auditSubjectID,
- ILogger.SUCCESS,
- auditCASubjectDN);
+ LOGGING_SIGNED_AUDIT_OCSP_ADD_CA_REQUEST_PROCESSED,
+ auditSubjectID,
+ ILogger.SUCCESS,
+ auditCASubjectDN);
- audit( auditMessage );
+ audit(auditMessage);
}
try {
@@ -297,18 +295,18 @@ public class AddCAServlet extends CMSServlet {
String error = null;
String xmlOutput = req.getParameter("xml");
- if (xmlOutput != null && xmlOutput.equals("true")) {
- outputXML(resp, argSet);
- } else {
- resp.setContentType("text/html");
- form.renderOutput(out, argSet);
- cmsReq.setStatus(CMSRequest.SUCCESS);
- }
+ if (xmlOutput != null && xmlOutput.equals("true")) {
+ outputXML(resp, argSet);
+ } else {
+ resp.setContentType("text/html");
+ form.renderOutput(out, argSet);
+ cmsReq.setStatus(CMSRequest.SUCCESS);
+ }
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/ocsp/AddCRLServlet.java b/pki/base/common/src/com/netscape/cms/servlet/ocsp/AddCRLServlet.java
index 029d396b..6273c8e7 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/ocsp/AddCRLServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/ocsp/AddCRLServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.ocsp;
-
import java.io.IOException;
import java.math.BigInteger;
import java.security.cert.CRLException;
@@ -55,10 +54,9 @@ import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
import com.netscape.cmsutil.util.Cert;
-
/**
* Update the OCSP responder with a new CRL
- *
+ *
* @version $Revision$ $Date$
*/
public class AddCRLServlet extends CMSServlet {
@@ -68,18 +66,18 @@ public class AddCRLServlet extends CMSServlet {
*/
private static final long serialVersionUID = 1476080474638590902L;
public static final String BEGIN_HEADER =
- "-----BEGIN CERTIFICATE REVOCATION LIST-----";
+ "-----BEGIN CERTIFICATE REVOCATION LIST-----";
public static final String END_HEADER =
- "-----END CERTIFICATE REVOCATION LIST-----";
+ "-----END CERTIFICATE REVOCATION LIST-----";
private final static String TPL_FILE = "addCRL.template";
private String mFormPath = null;
private IOCSPAuthority mOCSPAuthority = null;
private final static String LOGGING_SIGNED_AUDIT_CRL_RETRIEVAL =
- "LOGGING_SIGNED_AUDIT_CRL_RETRIEVAL_3";
+ "LOGGING_SIGNED_AUDIT_CRL_RETRIEVAL_3";
private final static String LOGGING_SIGNED_AUDIT_CRL_VALIDATION =
- "LOGGING_SIGNED_AUDIT_CRL_VALIDATION_2";
+ "LOGGING_SIGNED_AUDIT_CRL_VALIDATION_2";
public AddCRLServlet() {
super();
@@ -88,7 +86,7 @@ public class AddCRLServlet extends CMSServlet {
/**
* initialize the servlet. This servlet uses the template file
* "addCRL.template" to process the response.
- *
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -105,31 +103,32 @@ public class AddCRLServlet extends CMSServlet {
/**
* Process the HTTP request.
* <P>
- *
+ *
* <ul>
* <li>http.param crl certificate revocation list, base-64, DER encoded
- * wrapped in -----BEGIN CERTIFICATE REVOCATION LIST-----,
- * -----END CERTIFICATE REVOCATION LIST----- strings
+ * wrapped in -----BEGIN CERTIFICATE REVOCATION LIST-----, -----END
+ * CERTIFICATE REVOCATION LIST----- strings
* <li>http.param noui if true, use minimal hardcoded text response
* <li>signed.audit LOGGING_SIGNED_AUDIT_CRL_RETRIEVAL used when CRLs are
* retrieved by the OCSP Responder ("agent" or "EE")
* <li>signed.audit LOGGING_SIGNED_AUDIT_CRL_VALIDATION used when CRL is
* retrieved and validation process occurs ("agent" or "EE")
* </ul>
+ *
* @param cmsReq the object holding the request and response information
* @exception EBaseException an error has occurred
*/
protected synchronized void process(CMSRequest cmsReq)
- throws EBaseException {
+ throws EBaseException {
boolean CRLFetched = false;
boolean CRLValidated = false;
String auditMessage = null;
String auditSubjectID = auditSubjectID();
String auditCRLNum = ILogger.SIGNED_AUDIT_EMPTY_VALUE;
- IStatsSubsystem statsSub = (IStatsSubsystem)CMS.getSubsystem("stats");
+ IStatsSubsystem statsSub = (IStatsSubsystem) CMS.getSubsystem("stats");
if (statsSub != null) {
- statsSub.startTiming("add_crl", true /* main action */);
+ statsSub.startTiming("add_crl", true /* main action */);
}
try {
@@ -152,42 +151,43 @@ public class AddCRLServlet extends CMSServlet {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CRL_RETRIEVAL,
- auditSubjectID,
- ILogger.FAILURE,
- auditCRLNum );
+ LOGGING_SIGNED_AUDIT_CRL_RETRIEVAL,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditCRLNum);
- audit( auditMessage );
+ audit(auditMessage);
return;
}
if (auditSubjectID.equals(ILogger.NONROLEUSER) ||
- auditSubjectID.equals(ILogger.UNIDENTIFIED)) {
+ auditSubjectID.equals(ILogger.UNIDENTIFIED)) {
if (authToken != null) {
String uid = authToken.getInString(IAuthToken.USER_ID);
if (uid != null) {
- CMS.debug("AddCAServlet: auditSubjectID set to "+uid);
+ CMS.debug("AddCAServlet: auditSubjectID set to " + uid);
auditSubjectID = uid;
}
- }
+ }
}
log(ILogger.LL_INFO, "AddCRLServlet");
String b64 = cmsReq.getHttpReq().getParameter("crl");
- if (CMS.debugOn()) CMS.debug("AddCRLServlet: b64=" + b64);
+ if (CMS.debugOn())
+ CMS.debug("AddCRLServlet: b64=" + b64);
if (b64 == null) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CRL_RETRIEVAL,
- auditSubjectID,
- ILogger.FAILURE,
- auditCRLNum );
+ LOGGING_SIGNED_AUDIT_CRL_RETRIEVAL,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditCRLNum);
- audit( auditMessage );
+ audit(auditMessage);
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_MISSING_CRL"));
+ CMS.getUserMessage("CMS_GW_MISSING_CRL"));
}
String nouiParm = cmsReq.getHttpReq().getParameter("noui");
@@ -209,20 +209,20 @@ public class AddCRLServlet extends CMSServlet {
}
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath,
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath,
e.toString()));
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CRL_RETRIEVAL,
- auditSubjectID,
- ILogger.FAILURE,
- auditCRLNum );
+ LOGGING_SIGNED_AUDIT_CRL_RETRIEVAL,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditCRLNum);
- audit( auditMessage );
+ audit(auditMessage);
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
IArgBlock header = CMS.createArgBlock();
@@ -231,32 +231,32 @@ public class AddCRLServlet extends CMSServlet {
if (b64.indexOf(BEGIN_HEADER) == -1) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_MISSING_CRL_HEADER"));
+ CMS.getLogMessage("CMSGW_MISSING_CRL_HEADER"));
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CRL_RETRIEVAL,
- auditSubjectID,
- ILogger.FAILURE,
- auditCRLNum );
+ LOGGING_SIGNED_AUDIT_CRL_RETRIEVAL,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditCRLNum);
- audit( auditMessage );
+ audit(auditMessage);
throw new ECMSGWException(CMS.getUserMessage(getLocale(req),
"CMS_GW_MISSING_CRL_HEADER"));
}
if (b64.indexOf(END_HEADER) == -1) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_MISSING_CRL_FOOTER"));
+ CMS.getLogMessage("CMSGW_MISSING_CRL_FOOTER"));
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CRL_RETRIEVAL,
- auditSubjectID,
- ILogger.FAILURE,
- auditCRLNum );
+ LOGGING_SIGNED_AUDIT_CRL_RETRIEVAL,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditCRLNum);
- audit( auditMessage );
+ audit(auditMessage);
throw new ECMSGWException(CMS.getUserMessage(getLocale(req),
"CMS_GW_MISSING_CRL_FOOTER"));
@@ -270,30 +270,30 @@ public class AddCRLServlet extends CMSServlet {
long startTime = CMS.getCurrentDate().getTime();
CMS.debug("AddCRLServlet: mapCRL start startTime=" + startTime);
if (statsSub != null) {
- statsSub.startTiming("decode_crl");
+ statsSub.startTiming("decode_crl");
}
- crl = mapCRL1( b64 );
+ crl = mapCRL1(b64);
if (statsSub != null) {
- statsSub.endTiming("decode_crl");
+ statsSub.endTiming("decode_crl");
}
long endTime = CMS.getCurrentDate().getTime();
- CMS.debug("AddCRLServlet: mapCRL done endTime=" + endTime +
- " diff=" + (endTime - startTime));
+ CMS.debug("AddCRLServlet: mapCRL done endTime=" + endTime +
+ " diff=" + (endTime - startTime));
// Retrieve the actual CRL number
BigInteger crlNum = crl.getCRLNumber();
- if( crlNum != null ) {
+ if (crlNum != null) {
auditCRLNum = crlNum.toString();
}
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CRL_RETRIEVAL,
- auditSubjectID,
- ILogger.SUCCESS,
- auditCRLNum );
+ LOGGING_SIGNED_AUDIT_CRL_RETRIEVAL,
+ auditSubjectID,
+ ILogger.SUCCESS,
+ auditCRLNum);
- audit( auditMessage );
+ audit(auditMessage);
// acknowledge that the CRL has been retrieved
CRLFetched = true;
@@ -302,18 +302,18 @@ public class AddCRLServlet extends CMSServlet {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CRL_RETRIEVAL,
- auditSubjectID,
- ILogger.FAILURE,
- auditCRLNum );
+ LOGGING_SIGNED_AUDIT_CRL_RETRIEVAL,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditCRLNum);
- audit( auditMessage );
+ audit(auditMessage);
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DECODING_CRL_ERROR"));
+ CMS.getUserMessage("CMS_GW_DECODING_CRL_ERROR"));
}
- log(ILogger.LL_INFO, "AddCRLServlet: CRL Issuer DN " +
- crl.getIssuerDN().getName());
+ log(ILogger.LL_INFO, "AddCRLServlet: CRL Issuer DN " +
+ crl.getIssuerDN().getName());
ICRLIssuingPointRecord pt = null;
@@ -322,101 +322,101 @@ public class AddCRLServlet extends CMSServlet {
crl.getIssuerDN().getName());
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_NO_CRL_ISSUING_POINT_FOUND",
- crl.getIssuerDN().getName()));
+ CMS.getLogMessage("CMSGW_NO_CRL_ISSUING_POINT_FOUND",
+ crl.getIssuerDN().getName()));
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CRL_VALIDATION,
- auditSubjectID,
- ILogger.FAILURE );
+ LOGGING_SIGNED_AUDIT_CRL_VALIDATION,
+ auditSubjectID,
+ ILogger.FAILURE);
- audit( auditMessage );
+ audit(auditMessage);
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DECODING_CRL_ERROR"));
+ CMS.getUserMessage("CMS_GW_DECODING_CRL_ERROR"));
}
log(ILogger.LL_INFO, "AddCRLServlet: IssuingPoint " +
- pt.getThisUpdate());
+ pt.getThisUpdate());
// verify CRL
byte caCertData[] = pt.getCACert();
if (caCertData != null) {
- try {
- X509CertImpl caCert = new X509CertImpl(caCertData);
- CMS.debug("AddCRLServlet: start verify");
-
- CryptoManager cmanager = CryptoManager.getInstance();
- org.mozilla.jss.crypto.X509Certificate jssCert = null;
try {
- jssCert = cmanager.importCACertPackage(
- caCert.getEncoded());
- } catch (Exception e2) {
- CMS.debug("AddCRLServlet: importCACertPackage " +
- e2.toString());
- throw new EBaseException( e2.toString() );
- }
+ X509CertImpl caCert = new X509CertImpl(caCertData);
+ CMS.debug("AddCRLServlet: start verify");
- if (statsSub != null) {
- statsSub.startTiming("verify_crl");
- }
- crl.verify(jssCert.getPublicKey(), "Mozilla-JSS");
- if (statsSub != null) {
- statsSub.endTiming("verify_crl");
- }
- CMS.debug("AddCRLServlet: done verify");
+ CryptoManager cmanager = CryptoManager.getInstance();
+ org.mozilla.jss.crypto.X509Certificate jssCert = null;
+ try {
+ jssCert = cmanager.importCACertPackage(
+ caCert.getEncoded());
+ } catch (Exception e2) {
+ CMS.debug("AddCRLServlet: importCACertPackage " +
+ e2.toString());
+ throw new EBaseException(e2.toString());
+ }
- // store a message in the signed audit log file
- auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CRL_VALIDATION,
- auditSubjectID,
- ILogger.SUCCESS );
+ if (statsSub != null) {
+ statsSub.startTiming("verify_crl");
+ }
+ crl.verify(jssCert.getPublicKey(), "Mozilla-JSS");
+ if (statsSub != null) {
+ statsSub.endTiming("verify_crl");
+ }
+ CMS.debug("AddCRLServlet: done verify");
- audit( auditMessage );
+ // store a message in the signed audit log file
+ auditMessage = CMS.getLogMessage(
+ LOGGING_SIGNED_AUDIT_CRL_VALIDATION,
+ auditSubjectID,
+ ILogger.SUCCESS);
- // acknowledge that the CRL has been validated
- CRLValidated = true;
- } catch (Exception e) {
- CMS.debug("AddCRLServlet: failed to verify CRL " + e.toString());
- CMS.debug(e);
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_NO_CRL_ISSUING_POINT_FOUND",
- crl.getIssuerDN().getName()));
+ audit(auditMessage);
- // store a message in the signed audit log file
- auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CRL_VALIDATION,
- auditSubjectID,
- ILogger.FAILURE );
+ // acknowledge that the CRL has been validated
+ CRLValidated = true;
+ } catch (Exception e) {
+ CMS.debug("AddCRLServlet: failed to verify CRL " + e.toString());
+ CMS.debug(e);
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_NO_CRL_ISSUING_POINT_FOUND",
+ crl.getIssuerDN().getName()));
- audit( auditMessage );
+ // store a message in the signed audit log file
+ auditMessage = CMS.getLogMessage(
+ LOGGING_SIGNED_AUDIT_CRL_VALIDATION,
+ auditSubjectID,
+ ILogger.FAILURE);
- throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DECODING_CRL_ERROR"));
- }
+ audit(auditMessage);
+
+ throw new ECMSGWException(
+ CMS.getUserMessage("CMS_GW_DECODING_CRL_ERROR"));
+ }
}
- if ((pt.getThisUpdate() != null) &&
- (pt.getThisUpdate().getTime() >=
- crl.getThisUpdate().getTime())) {
+ if ((pt.getThisUpdate() != null) &&
+ (pt.getThisUpdate().getTime() >=
+ crl.getThisUpdate().getTime())) {
// error, the uploaded CRL is older than the current
CMS.debug("AddCRLServlet: no update, CRL is older");
log(ILogger.LL_INFO,
- "AddCRLServlet: no update, received CRL is older " +
- "than current CRL");
+ "AddCRLServlet: no update, received CRL is older " +
+ "than current CRL");
if (noUI) {
try {
resp.setContentType("application/text");
- resp.getOutputStream().write("status=1\n".getBytes());
+ resp.getOutputStream().write("status=1\n".getBytes());
resp.getOutputStream().write(
- "error=Sent CRL is older than the current CRL\n".getBytes());
+ "error=Sent CRL is older than the current CRL\n".getBytes());
resp.getOutputStream().flush();
cmsReq.setStatus(CMSRequest.SUCCESS);
- // NOTE: The signed audit events
- // LOGGING_SIGNED_AUDIT_CRL_RETRIEVAL and
- // LOGGING_SIGNED_AUDIT_CRL_VALIDATION have
- // already been logged at this point!
+ // NOTE: The signed audit events
+ // LOGGING_SIGNED_AUDIT_CRL_RETRIEVAL and
+ // LOGGING_SIGNED_AUDIT_CRL_VALIDATION have
+ // already been logged at this point!
return;
} catch (Exception e) {
@@ -424,26 +424,26 @@ public class AddCRLServlet extends CMSServlet {
} else {
CMS.debug("AddCRLServlet: CRL is older");
- // NOTE: The signed audit events
- // LOGGING_SIGNED_AUDIT_CRL_RETRIEVAL and
- // LOGGING_SIGNED_AUDIT_CRL_VALIDATION have
- // already been logged at this point!
+ // NOTE: The signed audit events
+ // LOGGING_SIGNED_AUDIT_CRL_RETRIEVAL and
+ // LOGGING_SIGNED_AUDIT_CRL_VALIDATION have
+ // already been logged at this point!
throw new ECMSGWException(CMS.getUserMessage(
- "CMS_GW_OLD_CRL_ERROR"));
+ "CMS_GW_OLD_CRL_ERROR"));
}
}
if (crl.isDeltaCRL()) {
CMS.debug("AddCRLServlet: no update, Delta CRLs are not supported.");
- log(ILogger.LL_INFO, "AddCRLServlet: no update, "+
- CMS.getUserMessage("CMS_GW_DELTA_CRL_NOT_SUPPORTED"));
+ log(ILogger.LL_INFO, "AddCRLServlet: no update, " +
+ CMS.getUserMessage("CMS_GW_DELTA_CRL_NOT_SUPPORTED"));
if (noUI) {
try {
resp.setContentType("application/text");
- resp.getOutputStream().write("status=1\n".getBytes());
+ resp.getOutputStream().write("status=1\n".getBytes());
resp.getOutputStream().write(
- "error=Delta CRLs are not supported.\n".getBytes());
+ "error=Delta CRLs are not supported.\n".getBytes());
resp.getOutputStream().flush();
cmsReq.setStatus(CMSRequest.SUCCESS);
@@ -465,26 +465,26 @@ public class AddCRLServlet extends CMSServlet {
IRepositoryRecord repRec = defStore.createRepositoryRecord();
- repRec.set(IRepositoryRecord.ATTR_SERIALNO,
- new BigInteger(Long.toString(crl.getThisUpdate().getTime())));
+ repRec.set(IRepositoryRecord.ATTR_SERIALNO,
+ new BigInteger(Long.toString(crl.getThisUpdate().getTime())));
try {
defStore.addRepository(
- crl.getIssuerDN().getName(),
- Long.toString(crl.getThisUpdate().getTime()),
- repRec);
+ crl.getIssuerDN().getName(),
+ Long.toString(crl.getThisUpdate().getTime()),
+ repRec);
log(ILogger.EV_AUDIT, AuditFormat.LEVEL, "Added CRL Updated " +
- Long.toString(crl.getThisUpdate().getTime()));
+ Long.toString(crl.getThisUpdate().getTime()));
} catch (Exception e) {
- CMS.debug("AddCRLServlet: add repository e=" + e.toString());
+ CMS.debug("AddCRLServlet: add repository e=" + e.toString());
}
- log(ILogger.LL_INFO, "AddCRLServlet: Created CRL Repository " +
- Long.toString(crl.getThisUpdate().getTime()));
+ log(ILogger.LL_INFO, "AddCRLServlet: Created CRL Repository " +
+ Long.toString(crl.getThisUpdate().getTime()));
if (defStore.waitOnCRLUpdate()) {
defStore.updateCRL(crl);
} else {
- // when the CRL large, the thread is terminiated by the
- // servlet framework before it can finish its work
+ // when the CRL large, the thread is terminiated by the
+ // servlet framework before it can finish its work
UpdateCRLThread uct = new UpdateCRLThread(defStore, crl);
uct.start();
@@ -496,64 +496,64 @@ public class AddCRLServlet extends CMSServlet {
if (noUI) {
CMS.debug("AddCRLServlet: return result noUI=true");
resp.setContentType("application/text");
- resp.getOutputStream().write("status=0".getBytes());
+ resp.getOutputStream().write("status=0".getBytes());
resp.getOutputStream().flush();
cmsReq.setStatus(CMSRequest.SUCCESS);
} else {
CMS.debug("AddCRLServlet: return result noUI=false");
String xmlOutput = req.getParameter("xml");
if (xmlOutput != null && xmlOutput.equals("true")) {
- outputXML(resp, argSet);
+ outputXML(resp, argSet);
} else {
- resp.setContentType("text/html");
- form.renderOutput(out, argSet);
- cmsReq.setStatus(CMSRequest.SUCCESS);
+ resp.setContentType("text/html");
+ form.renderOutput(out, argSet);
+ cmsReq.setStatus(CMSRequest.SUCCESS);
}
}
} catch (IOException e) {
CMS.debug("AddCRLServlet: return result error=" + e.toString());
mOCSPAuthority.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE",
- e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE",
+ e.toString()));
- // NOTE: The signed audit events
- // LOGGING_SIGNED_AUDIT_CRL_RETRIEVAL and
- // LOGGING_SIGNED_AUDIT_CRL_VALIDATION have
- // already been logged at this point!
+ // NOTE: The signed audit events
+ // LOGGING_SIGNED_AUDIT_CRL_RETRIEVAL and
+ // LOGGING_SIGNED_AUDIT_CRL_VALIDATION have
+ // already been logged at this point!
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
- } catch( EBaseException eAudit1 ) {
- if( !CRLFetched ) {
+ } catch (EBaseException eAudit1) {
+ if (!CRLFetched) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CRL_RETRIEVAL,
- auditSubjectID,
- ILogger.FAILURE,
- auditCRLNum );
+ LOGGING_SIGNED_AUDIT_CRL_RETRIEVAL,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditCRLNum);
- audit( auditMessage );
+ audit(auditMessage);
} else {
- if( !CRLValidated ) {
+ if (!CRLValidated) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CRL_VALIDATION,
- auditSubjectID,
- ILogger.FAILURE );
+ LOGGING_SIGNED_AUDIT_CRL_VALIDATION,
+ auditSubjectID,
+ ILogger.FAILURE);
- audit( auditMessage );
+ audit(auditMessage);
}
}
throw eAudit1;
}
if (statsSub != null) {
- statsSub.endTiming("add_crl");
+ statsSub.endTiming("add_crl");
}
}
public X509CRLImpl mapCRL1(String mime64)
- throws IOException {
+ throws IOException {
mime64 = Cert.stripCRLBrackets(mime64.trim());
byte rawPub[] = CMS.AtoB(mime64);
@@ -568,21 +568,20 @@ public class AddCRLServlet extends CMSServlet {
}
}
-
class UpdateCRLThread extends Thread {
private IDefStore mDefStore = null;
private X509CRL mCRL = null;
public UpdateCRLThread(
- IDefStore defStore, X509CRL crl) {
+ IDefStore defStore, X509CRL crl) {
mDefStore = defStore;
mCRL = crl;
}
public void run() {
try {
- if (!((X509CRLImpl)mCRL).areEntriesIncluded())
- mCRL = new X509CRLImpl(((X509CRLImpl)mCRL).getEncoded());
+ if (!((X509CRLImpl) mCRL).areEntriesIncluded())
+ mCRL = new X509CRLImpl(((X509CRLImpl) mCRL).getEncoded());
mDefStore.updateCRL(mCRL);
} catch (CRLException e) {
} catch (X509ExtensionException e) {
diff --git a/pki/base/common/src/com/netscape/cms/servlet/ocsp/CheckCertServlet.java b/pki/base/common/src/com/netscape/cms/servlet/ocsp/CheckCertServlet.java
index 3e5d1f49..212ce6a1 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/ocsp/CheckCertServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/ocsp/CheckCertServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.ocsp;
-
import java.io.IOException;
import java.security.cert.X509CRLEntry;
import java.security.cert.X509Certificate;
@@ -48,10 +47,9 @@ import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
import com.netscape.cmsutil.util.Cert;
-
/**
- * Check the status of a specific certificate
- *
+ * Check the status of a specific certificate
+ *
* @version $Revision$ $Date$
*/
public class CheckCertServlet extends CMSServlet {
@@ -61,9 +59,9 @@ public class CheckCertServlet extends CMSServlet {
*/
private static final long serialVersionUID = 7782198059640825050L;
public static final String BEGIN_HEADER =
- "-----BEGIN CERTIFICATE-----";
+ "-----BEGIN CERTIFICATE-----";
public static final String END_HEADER =
- "-----END CERTIFICATE-----";
+ "-----END CERTIFICATE-----";
public static final String ATTR_STATUS = "status";
public static final String ATTR_ISSUERDN = "issuerDN";
@@ -85,7 +83,7 @@ public class CheckCertServlet extends CMSServlet {
/**
* initialize the servlet. This servlet uses the template file
* "checkCert.template" to process the response.
- *
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -102,14 +100,14 @@ public class CheckCertServlet extends CMSServlet {
/**
* Process the HTTP request.
* <ul>
- * <li>http.param cert certificate to check. Base64, DER encoded, wrapped
- * in -----BEGIN CERTIFICATE-----, -----END CERTIFICATE----- strings
+ * <li>http.param cert certificate to check. Base64, DER encoded, wrapped in
+ * -----BEGIN CERTIFICATE-----, -----END CERTIFICATE----- strings
* </ul>
- *
+ *
* @param cmsReq the object holding the request and response information
*/
protected void process(CMSRequest cmsReq)
- throws EBaseException {
+ throws EBaseException {
HttpServletRequest req = cmsReq.getHttpReq();
HttpServletResponse resp = cmsReq.getHttpResp();
@@ -136,9 +134,9 @@ public class CheckCertServlet extends CMSServlet {
form = getTemplate(mFormPath, req, locale);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
IArgBlock header = CMS.createArgBlock();
@@ -177,9 +175,9 @@ public class CheckCertServlet extends CMSServlet {
header.addStringValue(ATTR_SUBJECTDN, cert.getSubjectDN().getName());
header.addStringValue(ATTR_SERIALNO, "0x" + cert.getSerialNumber().toString(16));
try {
- X509CRLImpl crl = null;
+ X509CRLImpl crl = null;
- crl = new X509CRLImpl(pt.getCRL());
+ crl = new X509CRLImpl(pt.getCRL());
X509CRLEntry crlentry = crl.getRevokedCertificate(cert.getSerialNumber());
if (crlentry == null) {
@@ -201,18 +199,18 @@ public class CheckCertServlet extends CMSServlet {
String error = null;
String xmlOutput = req.getParameter("xml");
- if (xmlOutput != null && xmlOutput.equals("true")) {
- outputXML(resp, argSet);
- } else {
- resp.setContentType("text/html");
- form.renderOutput(out, argSet);
- cmsReq.setStatus(CMSRequest.SUCCESS);
- }
+ if (xmlOutput != null && xmlOutput.equals("true")) {
+ outputXML(resp, argSet);
+ } else {
+ resp.setContentType("text/html");
+ form.renderOutput(out, argSet);
+ cmsReq.setStatus(CMSRequest.SUCCESS);
+ }
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/ocsp/GetOCSPInfo.java b/pki/base/common/src/com/netscape/cms/servlet/ocsp/GetOCSPInfo.java
index 704c759c..825416e3 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/ocsp/GetOCSPInfo.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/ocsp/GetOCSPInfo.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.ocsp;
-
import java.io.IOException;
import java.util.Locale;
@@ -41,11 +40,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
- * Retrieve information about the number of OCSP requests the OCSP
- * has serviced
- *
+ * Retrieve information about the number of OCSP requests the OCSP has serviced
+ *
* @version $Revision$, $Date$
*/
public class GetOCSPInfo extends CMSServlet {
@@ -61,9 +58,9 @@ public class GetOCSPInfo extends CMSServlet {
}
/**
- * initialize the servlet. This servlet uses the template
- * file "getOCSPInfo.template" to render the result page.
- *
+ * initialize the servlet. This servlet uses the template file
+ * "getOCSPInfo.template" to render the result page.
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -79,14 +76,13 @@ public class GetOCSPInfo extends CMSServlet {
}
-
/**
- * Process the HTTP request.
- *
+ * Process the HTTP request.
+ *
* @param cmsReq the object holding the request and response information
*/
protected void process(CMSRequest cmsReq)
- throws EBaseException {
+ throws EBaseException {
HttpServletRequest httpReq = cmsReq.getHttpReq();
HttpServletResponse httpResp = cmsReq.getHttpResp();
@@ -98,10 +94,10 @@ public class GetOCSPInfo extends CMSServlet {
mAuthzResourceName, "read");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -115,7 +111,7 @@ public class GetOCSPInfo extends CMSServlet {
if (!(mAuthority instanceof IOCSPService)) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_CA_FROM_RA_NOT_IMP"));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_NOT_YET_IMPLEMENTED")));
+ CMS.getUserMessage("CMS_GW_NOT_YET_IMPLEMENTED")));
cmsReq.setStatus(CMSRequest.ERROR);
return;
}
@@ -126,10 +122,10 @@ public class GetOCSPInfo extends CMSServlet {
try {
form = getTemplate(mFormPath, httpReq, locale);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
cmsReq.setStatus(CMSRequest.ERROR);
return;
}
@@ -147,8 +143,8 @@ public class GetOCSPInfo extends CMSServlet {
header.addLongValue("totalData", ca.getOCSPTotalData());
long secs = 0;
if (ca.getOCSPRequestTotalTime() != 0) {
- secs = (ca.getNumOCSPRequest() * 1000) / ca.getOCSPRequestTotalTime();
- }
+ secs = (ca.getNumOCSPRequest() * 1000) / ca.getOCSPRequestTotalTime();
+ }
header.addLongValue("ReqSec", secs);
try {
ServletOutputStream out = httpResp.getOutputStream();
@@ -157,10 +153,10 @@ public class GetOCSPInfo extends CMSServlet {
form.renderOutput(out, argSet);
cmsReq.setStatus(CMSRequest.SUCCESS);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
cmsReq.setError(new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
cmsReq.setStatus(CMSRequest.ERROR);
}
cmsReq.setStatus(CMSRequest.SUCCESS);
diff --git a/pki/base/common/src/com/netscape/cms/servlet/ocsp/ListCAServlet.java b/pki/base/common/src/com/netscape/cms/servlet/ocsp/ListCAServlet.java
index 063d8513..6b9d2094 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/ocsp/ListCAServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/ocsp/ListCAServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.ocsp;
-
import java.io.IOException;
import java.math.BigInteger;
import java.util.Date;
@@ -45,10 +44,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* Show the list of CA's that the OCSP responder can service
- *
+ *
* @version $Revision$ $Date$
*/
public class ListCAServlet extends CMSServlet {
@@ -58,9 +56,9 @@ public class ListCAServlet extends CMSServlet {
*/
private static final long serialVersionUID = 3764395161795483452L;
public static final String BEGIN_HEADER =
- "-----BEGIN CERTIFICATE-----";
+ "-----BEGIN CERTIFICATE-----";
public static final String END_HEADER =
- "-----END CERTIFICATE-----";
+ "-----END CERTIFICATE-----";
private final static String TPL_FILE = "listCAs.template";
private String mFormPath = null;
@@ -73,7 +71,7 @@ public class ListCAServlet extends CMSServlet {
/**
* initialize the servlet. This servlet uses the template file
* "listCAs.template" to process the response.
- *
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -89,11 +87,11 @@ public class ListCAServlet extends CMSServlet {
/**
* Process the HTTP request.
- *
+ *
* @param cmsReq the object holding the request and response information
*/
protected void process(CMSRequest cmsReq)
- throws EBaseException {
+ throws EBaseException {
HttpServletRequest req = cmsReq.getHttpReq();
HttpServletResponse resp = cmsReq.getHttpResp();
@@ -120,9 +118,9 @@ public class ListCAServlet extends CMSServlet {
form = getTemplate(mFormPath, req, locale);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
IArgBlock header = CMS.createArgBlock();
@@ -133,12 +131,12 @@ public class ListCAServlet extends CMSServlet {
Enumeration recs = defStore.searchAllCRLIssuingPointRecord(100);
// show the current CRL number if present
- header.addStringValue("stateCount",
- Integer.toString(defStore.getStateCount()));
+ header.addStringValue("stateCount",
+ Integer.toString(defStore.getStateCount()));
while (recs.hasMoreElements()) {
- ICRLIssuingPointRecord rec =
- (ICRLIssuingPointRecord) recs.nextElement();
+ ICRLIssuingPointRecord rec =
+ (ICRLIssuingPointRecord) recs.nextElement();
IArgBlock rarg = CMS.createArgBlock();
String thisId = rec.getId();
@@ -163,17 +161,17 @@ public class ListCAServlet extends CMSServlet {
rarg.addLongValue("NumRevoked", 0);
} else {
if (rc.longValue() == -1) {
- rarg.addStringValue("NumRevoked", "UNKNOWN");
- } else {
- rarg.addLongValue("NumRevoked", rc.longValue());
+ rarg.addStringValue("NumRevoked", "UNKNOWN");
+ } else {
+ rarg.addLongValue("NumRevoked", rc.longValue());
}
}
BigInteger crlNumber = rec.getCRLNumber();
if (crlNumber == null || crlNumber.equals(new BigInteger("-1"))) {
- rarg.addStringValue("CRLNumber", "UNKNOWN");
+ rarg.addStringValue("CRLNumber", "UNKNOWN");
} else {
- rarg.addStringValue("CRLNumber", crlNumber.toString());
+ rarg.addStringValue("CRLNumber", crlNumber.toString());
}
rarg.addLongValue("ReqCount", defStore.getReqCount(thisId));
@@ -185,18 +183,18 @@ public class ListCAServlet extends CMSServlet {
String error = null;
String xmlOutput = req.getParameter("xml");
- if (xmlOutput != null && xmlOutput.equals("true")) {
- outputXML(resp, argSet);
- } else {
- resp.setContentType("text/html");
- form.renderOutput(out, argSet);
- cmsReq.setStatus(CMSRequest.SUCCESS);
- }
+ if (xmlOutput != null && xmlOutput.equals("true")) {
+ outputXML(resp, argSet);
+ } else {
+ resp.setContentType("text/html");
+ form.renderOutput(out, argSet);
+ cmsReq.setStatus(CMSRequest.SUCCESS);
+ }
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/ocsp/OCSPServlet.java b/pki/base/common/src/com/netscape/cms/servlet/ocsp/OCSPServlet.java
index cfc91975..a11a1739 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/ocsp/OCSPServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/ocsp/OCSPServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.ocsp;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
@@ -47,11 +46,10 @@ import com.netscape.cmsutil.ocsp.ResponseData;
import com.netscape.cmsutil.ocsp.SingleResponse;
import com.netscape.cmsutil.ocsp.TBSRequest;
-
/**
- * Process OCSP messages, According to RFC 2560
- * See http://www.ietf.org/rfc/rfc2560.txt
- *
+ * Process OCSP messages, According to RFC 2560 See
+ * http://www.ietf.org/rfc/rfc2560.txt
+ *
* @version $Revision$ $Date$
*/
public class OCSPServlet extends CMSServlet {
@@ -65,7 +63,7 @@ public class OCSPServlet extends CMSServlet {
public final static String PROP_MAX_REQUEST_SIZE = "MaxRequestSize";
public final static String PROP_ID = "ID";
- private int m_maxRequestSize=5000;
+ private int m_maxRequestSize = 5000;
public OCSPServlet() {
super();
@@ -74,35 +72,35 @@ public class OCSPServlet extends CMSServlet {
/**
* initialize the servlet. This servlet uses the template file
* "ImportCert.template" to process the response.
- *
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
super.init(sc);
String s = sc.getInitParameter(PROP_MAX_REQUEST_SIZE);
if (s != null) {
- try {
- m_maxRequestSize = Integer.parseInt(s);
- } catch (Exception e) {}
- }
+ try {
+ m_maxRequestSize = Integer.parseInt(s);
+ } catch (Exception e) {
+ }
+ }
}
/**
- * Process the HTTP request.
- * This method is invoked when the OCSP service receives a OCSP
- * request. Based on RFC 2560, the request should have the OCSP
- * request in the HTTP body as binary blob.
- *
+ * Process the HTTP request. This method is invoked when the OCSP service
+ * receives a OCSP request. Based on RFC 2560, the request should have the
+ * OCSP request in the HTTP body as binary blob.
+ *
* @param cmsReq the object holding the request and response information
*/
protected void process(CMSRequest cmsReq) throws EBaseException {
HttpServletRequest httpReq = cmsReq.getHttpReq();
HttpServletResponse httpResp = cmsReq.getHttpResp();
- IStatsSubsystem statsSub = (IStatsSubsystem)CMS.getSubsystem("stats");
+ IStatsSubsystem statsSub = (IStatsSubsystem) CMS.getSubsystem("stats");
if (statsSub != null) {
- statsSub.startTiming("ocsp", true /* main action */);
+ statsSub.startTiming("ocsp", true /* main action */);
}
IAuthToken authToken = authenticate(cmsReq);
@@ -119,12 +117,12 @@ public class OCSPServlet extends CMSServlet {
cmsReq.setStatus(CMSRequest.UNAUTHORIZED);
return;
}
-
+
CMS.debug("Servlet Path=" + httpReq.getServletPath());
CMS.debug("RequestURI=" + httpReq.getRequestURI());
- String pathInfo = httpReq.getPathInfo();
+ String pathInfo = httpReq.getPathInfo();
if (pathInfo != null && pathInfo.indexOf('%') != -1) {
- pathInfo = URLDecoder.decode(pathInfo);
+ pathInfo = URLDecoder.decode(pathInfo);
}
CMS.debug("PathInfo=" + pathInfo);
@@ -136,46 +134,46 @@ public class OCSPServlet extends CMSServlet {
String method = httpReq.getMethod();
CMS.debug("Method=" + method);
if (method != null && method.equals("POST")) {
- int reqlen = httpReq.getContentLength();
-
- if (reqlen == -1) {
- throw new Exception("OCSPServlet: Content-Length not supplied");
- }
- if (reqlen == 0) {
- throw new Exception("OCSPServlet: Invalid Content-Length");
- }
- if (reqlen > m_maxRequestSize) {
- throw new Exception("OCSPServlet: Client sending too much OCSP request data ("+reqlen+")");
- }
-
- // for debugging
- reqbuf = new byte[reqlen];
- int bytesread = 0;
- boolean partial = false;
-
- while (bytesread < reqlen) {
- int r = is.read(reqbuf, bytesread, reqlen - bytesread);
- if (r == -1) {
- throw new Exception("OCSPServlet: Client did not supply enough OCSP data");
+ int reqlen = httpReq.getContentLength();
+
+ if (reqlen == -1) {
+ throw new Exception("OCSPServlet: Content-Length not supplied");
+ }
+ if (reqlen == 0) {
+ throw new Exception("OCSPServlet: Invalid Content-Length");
+ }
+ if (reqlen > m_maxRequestSize) {
+ throw new Exception("OCSPServlet: Client sending too much OCSP request data (" + reqlen + ")");
}
- bytesread += r;
- if (partial == false) {
- if (bytesread < reqlen) {
- partial = true;
+
+ // for debugging
+ reqbuf = new byte[reqlen];
+ int bytesread = 0;
+ boolean partial = false;
+
+ while (bytesread < reqlen) {
+ int r = is.read(reqbuf, bytesread, reqlen - bytesread);
+ if (r == -1) {
+ throw new Exception("OCSPServlet: Client did not supply enough OCSP data");
+ }
+ bytesread += r;
+ if (partial == false) {
+ if (bytesread < reqlen) {
+ partial = true;
+ }
}
}
- }
- is = new ByteArrayInputStream(reqbuf);
+ is = new ByteArrayInputStream(reqbuf);
} else {
- // GET method
- if ( (pathInfo == null) ||
- (pathInfo.equals( "" ) ) ||
- (pathInfo.substring(1) == null) ||
- (pathInfo.substring(1).equals( "" ) ) ) {
- throw new Exception("OCSPServlet: OCSP request not provided in GET method");
- }
- is = new ByteArrayInputStream(
- com.netscape.osutil.OSUtil.AtoB(pathInfo.substring(1)));
+ // GET method
+ if ((pathInfo == null) ||
+ (pathInfo.equals("")) ||
+ (pathInfo.substring(1) == null) ||
+ (pathInfo.substring(1).equals(""))) {
+ throw new Exception("OCSPServlet: OCSP request not provided in GET method");
+ }
+ is = new ByteArrayInputStream(
+ com.netscape.osutil.OSUtil.AtoB(pathInfo.substring(1)));
}
// (1) retrieve OCSP request
@@ -183,22 +181,23 @@ public class OCSPServlet extends CMSServlet {
OCSPResponse response = null;
try {
- OCSPRequest.Template reqTemplate =
- new OCSPRequest.Template();
+ OCSPRequest.Template reqTemplate =
+ new OCSPRequest.Template();
- if ( (is == null) ||
- (is.toString().equals( "" ) ) ) {
- throw new Exception( "OCSPServlet: OCSP request is "
+ if ((is == null) ||
+ (is.toString().equals(""))) {
+ throw new Exception("OCSPServlet: OCSP request is "
+ "empty or malformed");
}
ocspReq = (OCSPRequest) reqTemplate.decode(is);
- if ( (ocspReq == null) ||
- (ocspReq.toString().equals( "" ) ) ) {
- throw new Exception( "OCSPServlet: Decoded OCSP request "
+ if ((ocspReq == null) ||
+ (ocspReq.toString().equals(""))) {
+ throw new Exception("OCSPServlet: Decoded OCSP request "
+ "is empty or malformed");
}
response = ((IOCSPService) mAuthority).validate(ocspReq);
- } catch (Exception e) {;
+ } catch (Exception e) {
+ ;
CMS.debug("OCSPServlet: " + e.toString());
}
@@ -219,8 +218,8 @@ public class OCSPServlet extends CMSServlet {
CMS.debug("OCSPServlet: " + CMS.BtoA(ASN1Util.encode(ocspReq)));
TBSRequest tbsReq = ocspReq.getTBSRequest();
for (int i = 0; i < tbsReq.getRequestCount(); i++) {
- com.netscape.cmsutil.ocsp.Request req = tbsReq.getRequestAt(i);
- CMS.debug("Serial Number: " + req.getCertID().getSerialNumber());
+ com.netscape.cmsutil.ocsp.Request req = tbsReq.getRequestAt(i);
+ CMS.debug("Serial Number: " + req.getCertID().getSerialNumber());
}
CMS.debug("OCSPServlet: OCSP Response Size:");
CMS.debug("OCSPServlet: " + Integer.toString(respbytes.length));
@@ -232,17 +231,17 @@ public class OCSPServlet extends CMSServlet {
} else if (rbytes.getObjectIdentifier().equals(
ResponseBytes.OCSP_BASIC)) {
BasicOCSPResponse basicRes = (BasicOCSPResponse)
- BasicOCSPResponse.getTemplate().decode(
- new ByteArrayInputStream(rbytes.getResponse().toByteArray()));
+ BasicOCSPResponse.getTemplate().decode(
+ new ByteArrayInputStream(rbytes.getResponse().toByteArray()));
if (basicRes == null) {
CMS.debug("Basic Res is null");
} else {
ResponseData data = basicRes.getResponseData();
for (int i = 0; i < data.getResponseCount(); i++) {
SingleResponse res = data.getResponseAt(i);
- CMS.debug("Serial Number: " +
- res.getCertID().getSerialNumber() +
- " Status: " +
+ CMS.debug("Serial Number: " +
+ res.getCertID().getSerialNumber() +
+ " Status: " +
res.getCertStatus().getClass().getName());
}
}
@@ -250,14 +249,14 @@ public class OCSPServlet extends CMSServlet {
}
httpResp.setContentType("application/ocsp-response");
-
+
httpResp.setContentLength(respbytes.length);
OutputStream ooss = httpResp.getOutputStream();
ooss.write(respbytes);
ooss.flush();
if (statsSub != null) {
- statsSub.endTiming("ocsp");
+ statsSub.endTiming("ocsp");
}
mRenderResult = false;
diff --git a/pki/base/common/src/com/netscape/cms/servlet/ocsp/RemoveCAServlet.java b/pki/base/common/src/com/netscape/cms/servlet/ocsp/RemoveCAServlet.java
index 3ec72bb8..2ecbdf1e 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/ocsp/RemoveCAServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/ocsp/RemoveCAServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.ocsp;
-
import java.io.IOException;
import java.util.Locale;
@@ -41,11 +40,11 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* Configure the CA to no longer respond to OCSP requests for a CA
- *
- * @version $Revision: 1274 $ $Date: 2010-09-07 22:14:41 -0700 (Tue, 07 Sep 2010) $
+ *
+ * @version $Revision: 1274 $ $Date: 2010-09-07 22:14:41 -0700 (Tue, 07 Sep
+ * 2010) $
*/
public class RemoveCAServlet extends CMSServlet {
@@ -58,12 +57,12 @@ public class RemoveCAServlet extends CMSServlet {
private IOCSPAuthority mOCSPAuthority = null;
private final static String LOGGING_SIGNED_AUDIT_OCSP_REMOVE_CA_REQUEST =
- "LOGGING_SIGNED_AUDIT_OCSP_REMOVE_CA_REQUEST_3";
+ "LOGGING_SIGNED_AUDIT_OCSP_REMOVE_CA_REQUEST_3";
private final static String LOGGING_SIGNED_AUDIT_OCSP_REMOVE_CA_REQUEST_PROCESSED_SUCCESS =
- "LOGGING_SIGNED_AUDIT_OCSP_REMOVE_CA_REQUEST_PROCESSED_SUCCESS_3";
+ "LOGGING_SIGNED_AUDIT_OCSP_REMOVE_CA_REQUEST_PROCESSED_SUCCESS_3";
private final static String LOGGING_SIGNED_AUDIT_OCSP_REMOVE_CA_REQUEST_PROCESSED_FAILURE =
- "LOGGING_SIGNED_AUDIT_OCSP_REMOVE_CA_REQUEST_PROCESSED_FAILURE_3";
+ "LOGGING_SIGNED_AUDIT_OCSP_REMOVE_CA_REQUEST_PROCESSED_FAILURE_3";
public RemoveCAServlet() {
super();
@@ -72,7 +71,7 @@ public class RemoveCAServlet extends CMSServlet {
/**
* initialize the servlet. This servlet uses the template file
* "addCA.template" to process the response.
- *
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -90,18 +89,20 @@ public class RemoveCAServlet extends CMSServlet {
/**
* Process the HTTP request.
* <ul>
- * <li>http.param ca id. The format is string.
- * <li>signed.audit LOGGING_SIGNED_AUDIT_OCSP_REMOVE_CA_REQUEST used when
- * a CA is attempted to be removed from the OCSP responder
- * <li>signed.audit LOGGING_SIGNED_AUDIT_OCSP_REMOVE_CA_REQUEST_PROCESSED_SUCCESS
- * and LOGGING_SIGNED_AUDIT_OCSP_REMOVE_CA_REQUEST_PROCESSED_FAILURE are used when
- * a remove CA request to the OCSP Responder is processed successfully or not.
+ * <li>http.param ca id. The format is string.
+ * <li>signed.audit LOGGING_SIGNED_AUDIT_OCSP_REMOVE_CA_REQUEST used when a
+ * CA is attempted to be removed from the OCSP responder
+ * <li>signed.audit
+ * LOGGING_SIGNED_AUDIT_OCSP_REMOVE_CA_REQUEST_PROCESSED_SUCCESS and
+ * LOGGING_SIGNED_AUDIT_OCSP_REMOVE_CA_REQUEST_PROCESSED_FAILURE are used
+ * when a remove CA request to the OCSP Responder is processed successfully
+ * or not.
* </ul>
- *
+ *
* @param cmsReq the object holding the request and response information
*/
protected void process(CMSRequest cmsReq)
- throws EBaseException {
+ throws EBaseException {
HttpServletRequest req = cmsReq.getHttpReq();
HttpServletResponse resp = cmsReq.getHttpResp();
String auditMessage = null;
@@ -132,9 +133,9 @@ public class RemoveCAServlet extends CMSServlet {
form = getTemplate(mFormPath, req, locale);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
IArgBlock header = CMS.createArgBlock();
@@ -142,79 +143,78 @@ public class RemoveCAServlet extends CMSServlet {
CMSTemplateParams argSet = new CMSTemplateParams(header, fixed);
if (auditSubjectID.equals(ILogger.NONROLEUSER) ||
- auditSubjectID.equals(ILogger.UNIDENTIFIED)) {
+ auditSubjectID.equals(ILogger.UNIDENTIFIED)) {
String uid = authToken.getInString(IAuthToken.USER_ID);
if (uid != null) {
- CMS.debug("RemoveCAServlet: auditSubjectID set to "+uid);
+ CMS.debug("RemoveCAServlet: auditSubjectID set to " + uid);
auditSubjectID = uid;
}
}
- String caID = cmsReq.getHttpReq().getParameter("caID");
-
+ String caID = cmsReq.getHttpReq().getParameter("caID");
- if (caID == null) {
- auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_OCSP_REMOVE_CA_REQUEST_PROCESSED_FAILURE,
- auditSubjectID,
- ILogger.FAILURE,
- ILogger.SIGNED_AUDIT_EMPTY_VALUE);
+ if (caID == null) {
+ auditMessage = CMS.getLogMessage(
+ LOGGING_SIGNED_AUDIT_OCSP_REMOVE_CA_REQUEST_PROCESSED_FAILURE,
+ auditSubjectID,
+ ILogger.FAILURE,
+ ILogger.SIGNED_AUDIT_EMPTY_VALUE);
- throw new ECMSGWException(CMS.getUserMessage(getLocale(req), "CMS_GW_MISSING_CA_ID"));
- }
+ throw new ECMSGWException(CMS.getUserMessage(getLocale(req), "CMS_GW_MISSING_CA_ID"));
+ }
- auditMessage = CMS.getLogMessage(
+ auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_OCSP_REMOVE_CA_REQUEST,
auditSubjectID,
ILogger.SUCCESS,
caID);
- audit( auditMessage );
+ audit(auditMessage);
- IDefStore defStore = mOCSPAuthority.getDefaultStore();
+ IDefStore defStore = mOCSPAuthority.getDefaultStore();
- try {
- defStore.deleteCRLIssuingPointRecord(caID);
+ try {
+ defStore.deleteCRLIssuingPointRecord(caID);
- } catch (EBaseException e) {
+ } catch (EBaseException e) {
- auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_OCSP_REMOVE_CA_REQUEST_PROCESSED_FAILURE,
- auditSubjectID,
- ILogger.FAILURE,
- caID);
- audit( auditMessage );
+ auditMessage = CMS.getLogMessage(
+ LOGGING_SIGNED_AUDIT_OCSP_REMOVE_CA_REQUEST_PROCESSED_FAILURE,
+ auditSubjectID,
+ ILogger.FAILURE,
+ caID);
+ audit(auditMessage);
- CMS.debug("RemoveCAServlet::process: Error deleting CRL IssuingPoint: " + caID);
- throw new EBaseException(e.toString());
+ CMS.debug("RemoveCAServlet::process: Error deleting CRL IssuingPoint: " + caID);
+ throw new EBaseException(e.toString());
}
CMS.debug("RemoveCAServlet::process: CRL IssuingPoint for CA successfully removed: " + caID);
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_OCSP_REMOVE_CA_REQUEST_PROCESSED_SUCCESS,
- auditSubjectID,
- ILogger.SUCCESS,
- caID);
- audit( auditMessage );
+ LOGGING_SIGNED_AUDIT_OCSP_REMOVE_CA_REQUEST_PROCESSED_SUCCESS,
+ auditSubjectID,
+ ILogger.SUCCESS,
+ caID);
+ audit(auditMessage);
try {
ServletOutputStream out = resp.getOutputStream();
String error = null;
String xmlOutput = req.getParameter("xml");
- if (xmlOutput != null && xmlOutput.equals("true")) {
- outputXML(resp, argSet);
- } else {
- resp.setContentType("text/html");
- form.renderOutput(out, argSet);
- cmsReq.setStatus(CMSRequest.SUCCESS);
- }
+ if (xmlOutput != null && xmlOutput.equals("true")) {
+ outputXML(resp, argSet);
+ } else {
+ resp.setContentType("text/html");
+ form.renderOutput(out, argSet);
+ cmsReq.setStatus(CMSRequest.SUCCESS);
+ }
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/processors/CMCProcessor.java b/pki/base/common/src/com/netscape/cms/servlet/processors/CMCProcessor.java
index 1e44dad1..e7d63602 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/processors/CMCProcessor.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/processors/CMCProcessor.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.processors;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -72,11 +71,10 @@ import com.netscape.cms.servlet.base.CMSServlet;
import com.netscape.cms.servlet.common.CMSRequest;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
- * Process CMC messages according to RFC 2797
- * See http://www.ietf.org/rfc/rfc2797.txt
- *
+ * Process CMC messages according to RFC 2797 See
+ * http://www.ietf.org/rfc/rfc2797.txt
+ *
* @version $Revision$, $Date$
*/
public class CMCProcessor extends PKIProcessor {
@@ -95,18 +93,18 @@ public class CMCProcessor extends PKIProcessor {
}
public void process(CMSRequest cmsReq)
- throws EBaseException {
+ throws EBaseException {
}
public void fillCertInfo(
- String protocolString, X509CertInfo certInfo,
- IAuthToken authToken, IArgBlock httpParams)
- throws EBaseException {
+ String protocolString, X509CertInfo certInfo,
+ IAuthToken authToken, IArgBlock httpParams)
+ throws EBaseException {
}
public X509CertInfo[] fillCertInfoArray(
- String protocolString, IAuthToken authToken, IArgBlock httpParams, IRequest req)
- throws EBaseException {
+ String protocolString, IAuthToken authToken, IArgBlock httpParams, IRequest req)
+ throws EBaseException {
CMS.debug("CMCProcessor: In CMCProcessor.fillCertInfoArray!");
String cmc = protocolString;
@@ -114,17 +112,16 @@ public class CMCProcessor extends PKIProcessor {
try {
byte[] cmcBlob = CMS.AtoB(cmc);
ByteArrayInputStream cmcBlobIn =
- new ByteArrayInputStream(cmcBlob);
+ new ByteArrayInputStream(cmcBlob);
org.mozilla.jss.pkix.cms.ContentInfo cmcReq = (org.mozilla.jss.pkix.cms.ContentInfo)
- org.mozilla.jss.pkix.cms.ContentInfo.getTemplate().decode(cmcBlobIn);
+ org.mozilla.jss.pkix.cms.ContentInfo.getTemplate().decode(cmcBlobIn);
- if
- (!cmcReq.getContentType().equals(org.mozilla.jss.pkix.cms.ContentInfo.SIGNED_DATA) || !cmcReq.hasContent())
+ if (!cmcReq.getContentType().equals(org.mozilla.jss.pkix.cms.ContentInfo.SIGNED_DATA) || !cmcReq.hasContent())
throw new ECMSGWException(CMS.getUserMessage("CMS_GW_NO_CMC_CONTENT"));
SignedData cmcFullReq = (SignedData)
- cmcReq.getInterpretedContent();
+ cmcReq.getInterpretedContent();
EncapsulatedContentInfo ci = cmcFullReq.getContentInfo();
@@ -132,7 +129,7 @@ public class CMCProcessor extends PKIProcessor {
if (!id.equals(OBJECT_IDENTIFIER.id_cct_PKIData) || !ci.hasContent()) {
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_NO_PKIDATA"));
+ CMS.getUserMessage("CMS_GW_NO_PKIDATA"));
}
OCTET_STRING content = ci.getContent();
@@ -144,7 +141,7 @@ public class CMCProcessor extends PKIProcessor {
int numReqs = reqSequence.size();
X509CertInfo[] certInfoArray = new X509CertInfo[numReqs];
String[] reqIdArray = new String[numReqs];
-
+
for (int i = 0; i < numReqs; i++) {
// decode message.
TaggedRequest taggedRequest = (TaggedRequest) reqSequence.elementAt(i);
@@ -158,7 +155,7 @@ public class CMCProcessor extends PKIProcessor {
reqIdArray[i] = String.valueOf(p10Id);
CertificationRequest p10 =
- tcr.getCertificationRequest();
+ tcr.getCertificationRequest();
// transfer to sun class
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
@@ -169,13 +166,13 @@ public class CMCProcessor extends PKIProcessor {
try {
PKCS10 pkcs10 = new PKCS10(ostream.toByteArray());
- //xxx do we need to do anything else?
+ // xxx do we need to do anything else?
X509CertInfo certInfo = CMS.getDefaultX509CertInfo();
pkcs10Processor.fillCertInfo(pkcs10, certInfo, authToken, httpParams);
- /* fillPKCS10(pkcs10,certInfo,
- authToken, httpParams);
+ /*
+ * fillPKCS10(pkcs10,certInfo, authToken, httpParams);
*/
certInfoArray[i] = certInfo;
@@ -195,7 +192,7 @@ public class CMCProcessor extends PKIProcessor {
reqIdArray[i] = String.valueOf(srcId);
- certInfoArray[i] = crmfProc.processIndividualRequest(crm, authToken, httpParams);
+ certInfoArray[i] = crmfProc.processIndividualRequest(crm, authToken, httpParams);
} else {
throw new ECMSGWException(CMS.getUserMessage("CMS_GW_NO_CMC_CONTENT"));
@@ -209,12 +206,12 @@ public class CMCProcessor extends PKIProcessor {
for (int i = 0; i < numDig; i++) {
AlgorithmIdentifier dai =
- (AlgorithmIdentifier) dais.elementAt(i);
+ (AlgorithmIdentifier) dais.elementAt(i);
String name =
- DigestAlgorithm.fromOID(dai.getOID()).toString();
+ DigestAlgorithm.fromOID(dai.getOID()).toString();
MessageDigest md =
- MessageDigest.getInstance(name);
+ MessageDigest.getInstance(name);
byte[] digest = md.digest(content.toByteArray());
@@ -226,8 +223,8 @@ public class CMCProcessor extends PKIProcessor {
for (int i = 0; i < numSis; i++) {
org.mozilla.jss.pkix.cms.SignerInfo si =
- (org.mozilla.jss.pkix.cms.SignerInfo)
- sis.elementAt(i);
+ (org.mozilla.jss.pkix.cms.SignerInfo)
+ sis.elementAt(i);
String name = si.getDigestAlgorithm().toString();
byte[] digest = (byte[]) digs.get(name);
@@ -243,8 +240,7 @@ public class CMCProcessor extends PKIProcessor {
SignerIdentifier sid = si.getSignerIdentifier();
- if
- (sid.getType().equals(SignerIdentifier.ISSUER_AND_SERIALNUMBER)) {
+ if (sid.getType().equals(SignerIdentifier.ISSUER_AND_SERIALNUMBER)) {
IssuerAndSerialNumber issuerAndSerialNumber = sid.getIssuerAndSerialNumber();
// find from the certs in the signedData
X509Certificate cert = null;
@@ -255,20 +251,19 @@ public class CMCProcessor extends PKIProcessor {
for (int j = 0; j < numCerts; j++) {
Certificate certJss =
- (Certificate) certs.elementAt(j);
+ (Certificate) certs.elementAt(j);
CertificateInfo certI =
- certJss.getInfo();
+ certJss.getInfo();
Name issuer = certI.getIssuer();
byte[] issuerB = ASN1Util.encode(issuer);
INTEGER sn = certI.getSerialNumber();
- if (
- new String(issuerB).equals(new
+ if (new String(issuerB).equals(new
String(ASN1Util.encode(issuerAndSerialNumber.getIssuer())))
- && sn.toString().equals(issuerAndSerialNumber.getSerialNumber().toString())) {
+ && sn.toString().equals(issuerAndSerialNumber.getSerialNumber().toString())) {
ByteArrayOutputStream os = new
- ByteArrayOutputStream();
+ ByteArrayOutputStream();
certJss.encode(os);
cert = new X509CertImpl(os.toByteArray());
@@ -296,8 +291,8 @@ public class CMCProcessor extends PKIProcessor {
} else {
}
PK11PubKey pubK =
- PK11PubKey.fromRaw(keyType,
- ((X509Key) signKey).getKey());
+ PK11PubKey.fromRaw(keyType,
+ ((X509Key) signKey).getKey());
si.verify(digest, id, pubK);
}
@@ -321,8 +316,7 @@ public class CMCProcessor extends PKIProcessor {
j++;
}
if (signKey == null) {
- throw new
- ECMSGWException(CMS.getUserMessage("CMS_GW_CMC_ERROR",
+ throw new ECMSGWException(CMS.getUserMessage("CMS_GW_CMC_ERROR",
"SubjectKeyIdentifier in SignerInfo does not match any publicKey in the request."));
} else {
PrivateKey.Type keyType = null;
@@ -352,7 +346,7 @@ public class CMCProcessor extends PKIProcessor {
for (int i = 0; i < numControls; i++) {
TaggedAttribute control =
- (TaggedAttribute) controls.elementAt(i);
+ (TaggedAttribute) controls.elementAt(i);
OBJECT_IDENTIFIER type = control.getType();
SET values = control.getValues();
int numVals = values.size();
@@ -364,7 +358,7 @@ public class CMCProcessor extends PKIProcessor {
vals = new String[numVals];
for (int j = 0; j < numVals; j++) {
ANY val = (ANY)
- values.elementAt(j);
+ values.elementAt(j);
INTEGER transId = (INTEGER) ((ANY) val).decodeWith(
INTEGER.getTemplate());
@@ -374,17 +368,16 @@ public class CMCProcessor extends PKIProcessor {
}
if (vals != null)
req.setExtData(IRequest.CMC_TRANSID, vals);
- } else if
- (type.equals(OBJECT_IDENTIFIER.id_cmc_senderNonce)) {
+ } else if (type.equals(OBJECT_IDENTIFIER.id_cmc_senderNonce)) {
String[] vals = null;
if (numVals > 0)
vals = new String[numVals];
for (int j = 0; j < numVals; j++) {
ANY val = (ANY)
- values.elementAt(j);
+ values.elementAt(j);
OCTET_STRING nonce = (OCTET_STRING)
- ((ANY) val).decodeWith(OCTET_STRING.getTemplate());
+ ((ANY) val).decodeWith(OCTET_STRING.getTemplate());
if (nonce != null) {
vals[j] = new String(nonce.toByteArray());
@@ -409,27 +402,27 @@ public class CMCProcessor extends PKIProcessor {
return certInfoArray;
} catch (CertificateException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_CMC_TO_CERTINFO_1", e.toString()));
+ CMS.getLogMessage("CMSGW_ERROR_CMC_TO_CERTINFO_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_CMC_TO_CERTINFO_ERROR"));
+ CMS.getUserMessage("CMS_GW_CMC_TO_CERTINFO_ERROR"));
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_CMC_TO_CERTINFO_1", e.toString()));
+ CMS.getLogMessage("CMSGW_ERROR_CMC_TO_CERTINFO_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_CMC_TO_CERTINFO_ERROR"));
+ CMS.getUserMessage("CMS_GW_CMC_TO_CERTINFO_ERROR"));
} catch (InvalidBERException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_CMC_TO_CERTINFO_1", e.toString()));
+ CMS.getLogMessage("CMSGW_ERROR_CMC_TO_CERTINFO_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_CMC_TO_CERTINFO_ERROR"));
+ CMS.getUserMessage("CMS_GW_CMC_TO_CERTINFO_ERROR"));
} catch (InvalidKeyException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_CMC_TO_CERTINFO_1", e.toString()));
+ CMS.getLogMessage("CMSGW_ERROR_CMC_TO_CERTINFO_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_CMC_TO_CERTINFO_ERROR"));
- }catch (Exception e) {
+ CMS.getUserMessage("CMS_GW_CMC_TO_CERTINFO_ERROR"));
+ } catch (Exception e) {
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_CMC_ERROR", e.toString()));
+ CMS.getUserMessage("CMS_GW_CMC_ERROR", e.toString()));
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/processors/CRMFProcessor.java b/pki/base/common/src/com/netscape/cms/servlet/processors/CRMFProcessor.java
index 27648758..361bf594 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/processors/CRMFProcessor.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/processors/CRMFProcessor.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.processors;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -56,11 +55,10 @@ import com.netscape.cms.servlet.base.CMSServlet;
import com.netscape.cms.servlet.common.CMSRequest;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
- * Process CRMF requests, according to RFC 2511
- * See http://www.ietf.org/rfc/rfc2511.txt
- *
+ * Process CRMF requests, according to RFC 2511 See
+ * http://www.ietf.org/rfc/rfc2511.txt
+ *
* @version $Revision$, $Date$
*/
public class CRMFProcessor extends PKIProcessor {
@@ -70,7 +68,7 @@ public class CRMFProcessor extends PKIProcessor {
private boolean enforcePop = false;
private final static String LOGGING_SIGNED_AUDIT_PROOF_OF_POSSESSION =
- "LOGGING_SIGNED_AUDIT_PROOF_OF_POSSESSION_2";
+ "LOGGING_SIGNED_AUDIT_PROOF_OF_POSSESSION_2";
public CRMFProcessor() {
super();
@@ -84,22 +82,23 @@ public class CRMFProcessor extends PKIProcessor {
}
public void process(CMSRequest cmsReq)
- throws EBaseException {
+ throws EBaseException {
}
/**
* Verify Proof of Possession (POP)
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_PROOF_OF_POSSESSION used when proof
* of possession is checked during certificate enrollment
* </ul>
+ *
* @param certReqMsg the certificate request message
* @exception EBaseException an error has occurred
*/
private void verifyPOP(CertReqMsg certReqMsg)
- throws EBaseException {
+ throws EBaseException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
@@ -118,59 +117,59 @@ public class CRMFProcessor extends PKIProcessor {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_PROOF_OF_POSSESSION,
- auditSubjectID,
- ILogger.SUCCESS );
+ LOGGING_SIGNED_AUDIT_PROOF_OF_POSSESSION,
+ auditSubjectID,
+ ILogger.SUCCESS);
- audit( auditMessage );
+ audit(auditMessage);
} catch (Exception e) {
CMS.debug("CRMFProcessor: Failed POP verify!");
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_POP_VERIFY"));
+ CMS.getLogMessage("CMSGW_ERROR_POP_VERIFY"));
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_PROOF_OF_POSSESSION,
- auditSubjectID,
- ILogger.FAILURE );
+ LOGGING_SIGNED_AUDIT_PROOF_OF_POSSESSION,
+ auditSubjectID,
+ ILogger.FAILURE);
- audit( auditMessage );
+ audit(auditMessage);
throw new ECMSGWException(
- CMS.getLogMessage("CMSGW_ERROR_POP_VERIFY"));
+ CMS.getLogMessage("CMSGW_ERROR_POP_VERIFY"));
}
}
} else {
if (enforcePop == true) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_NO_POP"));
+ CMS.getLogMessage("CMSGW_ERROR_NO_POP"));
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_PROOF_OF_POSSESSION,
- auditSubjectID,
- ILogger.FAILURE );
+ LOGGING_SIGNED_AUDIT_PROOF_OF_POSSESSION,
+ auditSubjectID,
+ ILogger.FAILURE);
- audit( auditMessage );
+ audit(auditMessage);
throw new ECMSGWException(
- CMS.getLogMessage("CMSGW_ERROR_NO_POP"));
+ CMS.getLogMessage("CMSGW_ERROR_NO_POP"));
}
}
- } catch( EBaseException eAudit1 ) {
+ } catch (EBaseException eAudit1) {
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_PROOF_OF_POSSESSION,
- auditSubjectID,
- ILogger.FAILURE );
+ LOGGING_SIGNED_AUDIT_PROOF_OF_POSSESSION,
+ auditSubjectID,
+ ILogger.FAILURE);
- audit( auditMessage );
+ audit(auditMessage);
}
}
- public X509CertInfo processIndividualRequest(CertReqMsg certReqMsg, IAuthToken authToken, IArgBlock httpParams)
- throws EBaseException {
+ public X509CertInfo processIndividualRequest(CertReqMsg certReqMsg, IAuthToken authToken, IArgBlock httpParams)
+ throws EBaseException {
CMS.debug("CRMFProcessor::processIndividualRequest!");
try {
@@ -205,21 +204,21 @@ public class CRMFProcessor extends PKIProcessor {
if (certTemplate.hasSubject()) {
Name subjectdn = certTemplate.getSubject();
ByteArrayOutputStream subjectEncStream =
- new ByteArrayOutputStream();
+ new ByteArrayOutputStream();
subjectdn.encode(subjectEncStream);
byte[] subjectEnc = subjectEncStream.toByteArray();
X500Name subject = new X500Name(subjectEnc);
certInfo.set(X509CertInfo.SUBJECT,
- new CertificateSubjectName(subject));
+ new CertificateSubjectName(subject));
} else if (authToken == null ||
- authToken.getInString(AuthToken.TOKEN_CERT_SUBJECT) == null) {
+ authToken.getInString(AuthToken.TOKEN_CERT_SUBJECT) == null) {
// No subject name - error!
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_MISSING_SUBJECT_NAME_FROM_AUTHTOKEN"));
+ CMS.getLogMessage("CMSGW_MISSING_SUBJECT_NAME_FROM_AUTHTOKEN"));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_MISSING_SUBJECT_NAME_FROM_AUTHTOKEN"));
+ CMS.getUserMessage("CMS_GW_MISSING_SUBJECT_NAME_FROM_AUTHTOKEN"));
}
// get extensions
@@ -243,10 +242,10 @@ public class CRMFProcessor extends PKIProcessor {
for (int j = 0; j < numexts; j++) {
org.mozilla.jss.pkix.cert.Extension jssext =
- certTemplate.extensionAt(j);
+ certTemplate.extensionAt(j);
boolean isCritical = jssext.getCritical();
org.mozilla.jss.asn1.OBJECT_IDENTIFIER jssoid =
- jssext.getExtnId();
+ jssext.getExtnId();
long[] numbers = jssoid.getNumbers();
int[] oidNumbers = new int[numbers.length];
@@ -254,23 +253,23 @@ public class CRMFProcessor extends PKIProcessor {
oidNumbers[k] = (int) numbers[k];
}
ObjectIdentifier oid =
- new ObjectIdentifier(oidNumbers);
+ new ObjectIdentifier(oidNumbers);
org.mozilla.jss.asn1.OCTET_STRING jssvalue =
- jssext.getExtnValue();
+ jssext.getExtnValue();
ByteArrayOutputStream jssvalueout =
- new ByteArrayOutputStream();
+ new ByteArrayOutputStream();
jssvalue.encode(jssvalueout);
byte[] extValue = jssvalueout.toByteArray();
Extension ext =
- new Extension(oid, isCritical, extValue);
+ new Extension(oid, isCritical, extValue);
extensions.parseExtension(ext);
}
certInfo.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ new CertificateVersion(CertificateVersion.V3));
certInfo.set(X509CertInfo.EXTENSIONS, extensions);
}
@@ -283,7 +282,7 @@ public class CRMFProcessor extends PKIProcessor {
// formulation.
// -- CRMFfillCert
if (authToken != null &&
- authToken.getInString(AuthToken.TOKEN_CERT_SUBJECT) != null) {
+ authToken.getInString(AuthToken.TOKEN_CERT_SUBJECT) != null) {
// if authenticated override subect name, validity and
// extensions if any from authtoken.
fillCertInfoFromAuthToken(certInfo, authToken);
@@ -300,31 +299,31 @@ public class CRMFProcessor extends PKIProcessor {
} catch (CertificateException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_CRMF_TO_CERTINFO_1", e.toString()));
+ CMS.getLogMessage("CMSGW_ERROR_CRMF_TO_CERTINFO_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_CRMF_TO_CERTINFO_ERROR"));
+ CMS.getUserMessage("CMS_GW_CRMF_TO_CERTINFO_ERROR"));
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_CRMF_TO_CERTINFO_1", e.toString()));
+ CMS.getLogMessage("CMSGW_ERROR_CRMF_TO_CERTINFO_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_CRMF_TO_CERTINFO_ERROR"));
- } /* catch (InvalidBERException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_CRMF_TO_CERTINFO_1",e.toString()));
- throw new ECMSGWException(
- CMSGWResources.ERROR_CRMF_TO_CERTINFO);
- } */ catch (InvalidKeyException e) {
+ CMS.getUserMessage("CMS_GW_CRMF_TO_CERTINFO_ERROR"));
+ } /*
+ * catch (InvalidBERException e) { log(ILogger.LL_FAILURE,
+ * CMS.getLogMessage("CMSGW_ERROR_CRMF_TO_CERTINFO_1",e.toString()));
+ * throw new ECMSGWException( CMSGWResources.ERROR_CRMF_TO_CERTINFO);
+ * }
+ */catch (InvalidKeyException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_CRMF_TO_CERTINFO_1", e.toString()));
+ CMS.getLogMessage("CMSGW_ERROR_CRMF_TO_CERTINFO_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_CRMF_TO_CERTINFO_ERROR"));
+ CMS.getUserMessage("CMS_GW_CRMF_TO_CERTINFO_ERROR"));
}
}
public X509CertInfo[] fillCertInfoArray(
- String protocolString, IAuthToken authToken, IArgBlock httpParams, IRequest req)
- throws EBaseException {
+ String protocolString, IAuthToken authToken, IArgBlock httpParams, IRequest req)
+ throws EBaseException {
CMS.debug("CRMFProcessor.fillCertInfoArray!");
@@ -333,10 +332,10 @@ public class CRMFProcessor extends PKIProcessor {
try {
byte[] crmfBlob = CMS.AtoB(crmf);
ByteArrayInputStream crmfBlobIn =
- new ByteArrayInputStream(crmfBlob);
+ new ByteArrayInputStream(crmfBlob);
SEQUENCE crmfMsgs = (SEQUENCE)
- new SEQUENCE.OF_Template(new CertReqMsg.Template()).decode(crmfBlobIn);
+ new SEQUENCE.OF_Template(new CertReqMsg.Template()).decode(crmfBlobIn);
int nummsgs = crmfMsgs.size();
X509CertInfo[] certInfoArray = new X509CertInfo[nummsgs];
@@ -344,7 +343,7 @@ public class CRMFProcessor extends PKIProcessor {
for (int i = 0; i < nummsgs; i++) {
// decode message.
CertReqMsg certReqMsg = (CertReqMsg) crmfMsgs.elementAt(i);
-
+
CertRequest certReq = certReqMsg.getCertReq();
INTEGER certReqId = certReq.getCertReqId();
int srcId = certReqId.intValue();
@@ -355,20 +354,19 @@ public class CRMFProcessor extends PKIProcessor {
}
- //do_testbed_hack(nummsgs, certInfoArray, httpParams);
+ // do_testbed_hack(nummsgs, certInfoArray, httpParams);
return certInfoArray;
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_CRMF_TO_CERTINFO_1", e.toString()));
+ CMS.getLogMessage("CMSGW_ERROR_CRMF_TO_CERTINFO_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_CRMF_TO_CERTINFO_ERROR"));
+ CMS.getUserMessage("CMS_GW_CRMF_TO_CERTINFO_ERROR"));
} catch (InvalidBERException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_CRMF_TO_CERTINFO_1", e.toString()));
+ CMS.getLogMessage("CMSGW_ERROR_CRMF_TO_CERTINFO_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_CRMF_TO_CERTINFO_ERROR"));
+ CMS.getUserMessage("CMS_GW_CRMF_TO_CERTINFO_ERROR"));
}
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/processors/IPKIProcessor.java b/pki/base/common/src/com/netscape/cms/servlet/processors/IPKIProcessor.java
index d021f653..9139f888 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/processors/IPKIProcessor.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/processors/IPKIProcessor.java
@@ -17,19 +17,17 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.processors;
-
import com.netscape.certsrv.base.EBaseException;
import com.netscape.cms.servlet.common.CMSRequest;
-
/**
* This represents the request parser.
- *
+ *
* @version $Revision$, $Date$
*/
public interface IPKIProcessor {
public void process(CMSRequest cmsReq)
- throws EBaseException;
+ throws EBaseException;
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/processors/KeyGenProcessor.java b/pki/base/common/src/com/netscape/cms/servlet/processors/KeyGenProcessor.java
index cc035033..810c3ff2 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/processors/KeyGenProcessor.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/processors/KeyGenProcessor.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.processors;
-
import java.io.IOException;
import java.security.cert.CertificateException;
@@ -37,11 +36,10 @@ import com.netscape.cms.servlet.base.CMSServlet;
import com.netscape.cms.servlet.common.CMSRequest;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
- * KeyGenProcess parses Certificate request matching the
- * KEYGEN tag format used by Netscape Communicator 4.x
- *
+ * KeyGenProcess parses Certificate request matching the KEYGEN tag format used
+ * by Netscape Communicator 4.x
+ *
* @version $Revision$, $Date$
*/
public class KeyGenProcessor extends PKIProcessor {
@@ -56,13 +54,13 @@ public class KeyGenProcessor extends PKIProcessor {
}
public void process(CMSRequest cmsReq)
- throws EBaseException {
+ throws EBaseException {
}
public void fillCertInfo(
- String protocolString, X509CertInfo certInfo,
- IAuthToken authToken, IArgBlock httpParams)
- throws EBaseException {
+ String protocolString, X509CertInfo certInfo,
+ IAuthToken authToken, IArgBlock httpParams)
+ throws EBaseException {
CMS.debug("KeyGenProcessor: fillCertInfo");
@@ -72,7 +70,7 @@ public class KeyGenProcessor extends PKIProcessor {
KeyGenInfo keyGenInfo = httpParams.getValueAsKeyGenInfo(
PKIProcessor.SUBJECT_KEYGEN_INFO, null);
-
+
// fill key
X509Key key = null;
@@ -80,20 +78,20 @@ public class KeyGenProcessor extends PKIProcessor {
if (key == null) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_MISSING_KEY_IN_KEYGENINFO"));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_MISSING_KEY_IN_KEYGENINFO"));
+ CMS.getUserMessage("CMS_GW_MISSING_KEY_IN_KEYGENINFO"));
}
try {
certInfo.set(X509CertInfo.KEY, new CertificateX509Key(key));
} catch (CertificateException e) {
log(ILogger.LL_FAILURE,
- "Could not set key into certInfo from keygen. Error " + e);
+ "Could not set key into certInfo from keygen. Error " + e);
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SET_KEY_FROM_KEYGEN_FAILED", e.toString()));
+ CMS.getUserMessage("CMS_GW_SET_KEY_FROM_KEYGEN_FAILED", e.toString()));
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_FAILED_SET_KEY_FROM_KEYGEN_1", e.toString()));
+ CMS.getLogMessage("CMSGW_FAILED_SET_KEY_FROM_KEYGEN_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SET_KEY_FROM_KEYGEN_FAILED", e.toString()));
+ CMS.getUserMessage("CMS_GW_SET_KEY_FROM_KEYGEN_FAILED", e.toString()));
}
String authMgr = mServlet.getAuthMgr();
@@ -106,12 +104,12 @@ public class KeyGenProcessor extends PKIProcessor {
if (authToken.getInString(AuthToken.TOKEN_CERT_SUBJECT) == null) {
// allow special case for agent gateway in admin enroll
// and bulk issuance.
- if (!authMgr.equals(IAuthSubsystem.CERTUSERDB_AUTHMGR_ID) &&
- !authMgr.equals(IAuthSubsystem.PASSWDUSERDB_AUTHMGR_ID)) {
+ if (!authMgr.equals(IAuthSubsystem.CERTUSERDB_AUTHMGR_ID) &&
+ !authMgr.equals(IAuthSubsystem.PASSWDUSERDB_AUTHMGR_ID)) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_MISSING_SUBJECT_NAME_FROM_AUTHTOKEN"));
+ CMS.getLogMessage("CMSGW_MISSING_SUBJECT_NAME_FROM_AUTHTOKEN"));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_MISSING_SUBJECT_NAME_FROM_AUTHTOKEN"));
+ CMS.getUserMessage("CMS_GW_MISSING_SUBJECT_NAME_FROM_AUTHTOKEN"));
}
fillCertInfoFromForm(certInfo, httpParams);
} else {
diff --git a/pki/base/common/src/com/netscape/cms/servlet/processors/PKCS10Processor.java b/pki/base/common/src/com/netscape/cms/servlet/processors/PKCS10Processor.java
index 53d38455..5079969e 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/processors/PKCS10Processor.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/processors/PKCS10Processor.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.processors;
-
import java.io.IOException;
import java.security.cert.CertificateException;
@@ -46,12 +45,10 @@ import com.netscape.cms.servlet.base.CMSServlet;
import com.netscape.cms.servlet.common.CMSRequest;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
- * PKCS10Processor process Certificate Requests in
- * PKCS10 format, as defined here:
- * http://www.rsasecurity.com/rsalabs/pkcs/pkcs-10/index.html
- *
+ * PKCS10Processor process Certificate Requests in PKCS10 format, as defined
+ * here: http://www.rsasecurity.com/rsalabs/pkcs/pkcs-10/index.html
+ *
* @version $Revision$, $Date$
*/
public class PKCS10Processor extends PKIProcessor {
@@ -61,7 +58,7 @@ public class PKCS10Processor extends PKIProcessor {
private final String USE_INTERNAL_PKCS10 = "internal";
public PKCS10Processor() {
-
+
super();
}
@@ -71,24 +68,24 @@ public class PKCS10Processor extends PKIProcessor {
}
public void process(CMSRequest cmsReq)
- throws EBaseException {
+ throws EBaseException {
}
- public void fillCertInfo(
- PKCS10 pkcs10, X509CertInfo certInfo,
- IAuthToken authToken, IArgBlock httpParams)
- throws EBaseException {
+ public void fillCertInfo(
+ PKCS10 pkcs10, X509CertInfo certInfo,
+ IAuthToken authToken, IArgBlock httpParams)
+ throws EBaseException {
mPkcs10 = pkcs10;
-
- fillCertInfo(USE_INTERNAL_PKCS10, certInfo, authToken, httpParams);
+
+ fillCertInfo(USE_INTERNAL_PKCS10, certInfo, authToken, httpParams);
}
public void fillCertInfo(
- String protocolString, X509CertInfo certInfo,
- IAuthToken authToken, IArgBlock httpParams)
- throws EBaseException {
+ String protocolString, X509CertInfo certInfo,
+ IAuthToken authToken, IArgBlock httpParams)
+ throws EBaseException {
PKCS10 p10 = null;
@@ -99,8 +96,8 @@ public class PKCS10Processor extends PKIProcessor {
} else if (protocolString.equals(USE_INTERNAL_PKCS10)) {
p10 = mPkcs10;
} else {
- CMS.debug( "PKCS10Processor::fillCertInfo() - p10 is null!" );
- throw new EBaseException( "p10 is null" );
+ CMS.debug("PKCS10Processor::fillCertInfo() - p10 is null!");
+ throw new EBaseException("p10 is null");
}
if (mServlet == null) {
@@ -123,7 +120,7 @@ public class PKCS10Processor extends PKIProcessor {
certInfo.set(X509CertInfo.KEY, certKey);
} catch (CertificateException e) {
EBaseException ex = new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SET_KEY_FROM_P10_FAILED", e.toString()));
+ CMS.getUserMessage("CMS_GW_SET_KEY_FROM_P10_FAILED", e.toString()));
log(ILogger.LL_FAILURE, ex.toString());
throw ex;
@@ -140,31 +137,31 @@ public class PKCS10Processor extends PKIProcessor {
if (subject != null) {
try {
certInfo.set(X509CertInfo.SUBJECT,
- new CertificateSubjectName(subject));
+ new CertificateSubjectName(subject));
log(ILogger.LL_INFO,
- "Setting subject name " + subject + " from p10.");
+ "Setting subject name " + subject + " from p10.");
} catch (CertificateException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_FAILED_SET_SUBJECT_FROM_P10", e.toString()));
+ CMS.getLogMessage("CMSGW_FAILED_SET_SUBJECT_FROM_P10", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SET_SUBJECT_FROM_P10_FAILED", e.toString()));
+ CMS.getUserMessage("CMS_GW_SET_SUBJECT_FROM_P10_FAILED", e.toString()));
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_FAILED_SET_SUBJECT_FROM_P10", e.toString()));
+ CMS.getLogMessage("CMSGW_FAILED_SET_SUBJECT_FROM_P10", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SET_SUBJECT_FROM_P10_FAILED", e.toString()));
+ CMS.getUserMessage("CMS_GW_SET_SUBJECT_FROM_P10_FAILED", e.toString()));
} catch (Exception e) {
// if anything bad happens in X500 name parsing,
// this will catch it.
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_FAILED_SET_SUBJECT_FROM_P10", e.toString()));
+ CMS.getLogMessage("CMSGW_FAILED_SET_SUBJECT_FROM_P10", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SET_SUBJECT_FROM_P10_FAILED", e.toString()));
+ CMS.getUserMessage("CMS_GW_SET_SUBJECT_FROM_P10_FAILED", e.toString()));
}
} else if (authToken == null ||
- authToken.getInString(AuthToken.TOKEN_CERT_SUBJECT) == null) {
+ authToken.getInString(AuthToken.TOKEN_CERT_SUBJECT) == null) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_MISSING_SUBJECT_IN_P10"));
+ CMS.getLogMessage("CMSGW_MISSING_SUBJECT_IN_P10"));
throw new ECMSGWException(CMS.getUserMessage("CMS_GW_MISSING_SUBJECT_IN_P10"));
}
@@ -177,12 +174,12 @@ public class PKCS10Processor extends PKIProcessor {
if (p10Attrs != null) {
PKCS10Attribute p10Attr = (PKCS10Attribute)
- (p10Attrs.getAttribute(CertificateExtensions.NAME));
+ (p10Attrs.getAttribute(CertificateExtensions.NAME));
if (p10Attr != null && p10Attr.getAttributeId().equals(
PKCS9Attribute.EXTENSION_REQUEST_OID)) {
Extensions exts0 = (Extensions)
- (p10Attr.getAttributeValue());
+ (p10Attr.getAttributeValue());
DerOutputStream extOut = new DerOutputStream();
exts0.encode(extOut);
@@ -196,23 +193,23 @@ public class PKCS10Processor extends PKIProcessor {
}
}
CMS.debug(
- "PKCS10Processor: Seted cert extensions from pkcs10. ");
+ "PKCS10Processor: Seted cert extensions from pkcs10. ");
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_FAILED_SET_EXTENSIONS_FROM_P10", e.toString()));
+ CMS.getLogMessage("CMSGW_FAILED_SET_EXTENSIONS_FROM_P10", e.toString()));
throw new ECMSGWException(
CMS.getUserMessage("CMS_GW_SET_KEY_FROM_P10_FAILED", e.toString()));
} catch (CertificateException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_FAILED_SET_EXTENSIONS_FROM_P10", e.toString()));
+ CMS.getLogMessage("CMSGW_FAILED_SET_EXTENSIONS_FROM_P10", e.toString()));
throw new ECMSGWException(
CMS.getUserMessage("CMS_GW_SET_KEY_FROM_P10_FAILED", e.toString()));
} catch (Exception e) {
// if anything bad happens in extensions parsing,
// this will catch it.
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_FAILED_SET_EXTENSIONS_FROM_P10", e.toString()));
+ CMS.getLogMessage("CMSGW_FAILED_SET_EXTENSIONS_FROM_P10", e.toString()));
throw new ECMSGWException(
CMS.getUserMessage("CMS_GW_SET_KEY_FROM_P10_FAILED", e.toString()));
}
@@ -223,8 +220,8 @@ public class PKCS10Processor extends PKIProcessor {
String authMgr = mServlet.getAuthMgr();
if (authToken != null &&
- authToken.getInString(AuthToken.TOKEN_CERT_SUBJECT) != null &&
- !(authMgr.equals(IAuthSubsystem.PASSWDUSERDB_AUTHMGR_ID))) {
+ authToken.getInString(AuthToken.TOKEN_CERT_SUBJECT) != null &&
+ !(authMgr.equals(IAuthSubsystem.PASSWDUSERDB_AUTHMGR_ID))) {
fillCertInfoFromAuthToken(certInfo, authToken);
}
@@ -233,12 +230,12 @@ public class PKCS10Processor extends PKIProcessor {
// from the http parameters.
if (mServletId.equals(PKIProcessor.ADMIN_ENROLL_SERVLET_ID)) {
fillValidityFromForm(certInfo, httpParams);
- }
-
+ }
+
}
private PKCS10 getPKCS10(IArgBlock httpParams)
- throws EBaseException {
+ throws EBaseException {
PKCS10 pkcs10 = null;
@@ -252,7 +249,7 @@ public class PKCS10Processor extends PKIProcessor {
} else {
// some policies may rely on the fact that
// CERT_TYPE is set. So for 3.5.1 or eariler
- // we need to set CERT_TYPE but not here.
+ // we need to set CERT_TYPE but not here.
}
if (certType.equals("client")) {
// coming from MSIE
@@ -271,13 +268,13 @@ public class PKCS10Processor extends PKIProcessor {
}
}
- //pkcs10 = httpParams.getValuePKCS10(PKCS10_REQUEST, null);
+ // pkcs10 = httpParams.getValuePKCS10(PKCS10_REQUEST, null);
} else {
try {
// coming from server cut & paste blob.
pkcs10 = httpParams.getValueAsPKCS10(PKIProcessor.PKCS10_REQUEST, false, null);
- }catch (Exception ex) {
+ } catch (Exception ex) {
ex.printStackTrace();
}
}
@@ -286,4 +283,4 @@ public class PKCS10Processor extends PKIProcessor {
}
-}
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/processors/PKIProcessor.java b/pki/base/common/src/com/netscape/cms/servlet/processors/PKIProcessor.java
index 625808d7..d0861573 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/processors/PKIProcessor.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/processors/PKIProcessor.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.processors;
-
import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.Date;
@@ -42,10 +41,9 @@ import com.netscape.cms.servlet.base.CMSServlet;
import com.netscape.cms.servlet.common.CMSRequest;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* Process Certificate Requests
- *
+ *
* @version $Revision$, $Date$
*/
public class PKIProcessor implements IPKIProcessor {
@@ -57,7 +55,7 @@ public class PKIProcessor implements IPKIProcessor {
public static final String PKCS10_REQUEST = "pkcs10Request";
public static final String SUBJECT_KEYGEN_INFO = "subjectKeyGenInfo";
- protected CMSRequest mRequest = null;
+ protected CMSRequest mRequest = null;
protected HttpServletRequest httpReq = null;
protected String mServletId = null;
@@ -84,30 +82,30 @@ public class PKIProcessor implements IPKIProcessor {
}
public void process(CMSRequest cmsReq)
- throws EBaseException {
+ throws EBaseException {
}
protected void fillCertInfo(
- String protocolString, X509CertInfo certInfo,
- IAuthToken authToken, IArgBlock httpParams)
- throws EBaseException {
+ String protocolString, X509CertInfo certInfo,
+ IAuthToken authToken, IArgBlock httpParams)
+ throws EBaseException {
}
protected X509CertInfo[] fillCertInfoArray(
- String protocolString, IAuthToken authToken, IArgBlock httpParams, IRequest req)
- throws EBaseException {
+ String protocolString, IAuthToken authToken, IArgBlock httpParams, IRequest req)
+ throws EBaseException {
return null;
}
/**
- * fill subject name, validity, extensions from authoken if any,
- * overriding what was in pkcs10.
- * fill subject name, extensions from http input if not authenticated.
- * requests not authenticated will need to be approved by an agent.
+ * fill subject name, validity, extensions from authoken if any, overriding
+ * what was in pkcs10. fill subject name, extensions from http input if not
+ * authenticated. requests not authenticated will need to be approved by an
+ * agent.
*/
public static void fillCertInfoFromAuthToken(
- X509CertInfo certInfo, IAuthToken authToken)
- throws EBaseException {
+ X509CertInfo certInfo, IAuthToken authToken)
+ throws EBaseException {
// override subject, validity and extensions from auth token
// CA determines algorithm, version and issuer.
// take key from keygen, cmc, pkcs10 or crmf.
@@ -116,60 +114,60 @@ public class PKIProcessor implements IPKIProcessor {
// subject name.
try {
String subjectname =
- authToken.getInString(AuthToken.TOKEN_CERT_SUBJECT);
+ authToken.getInString(AuthToken.TOKEN_CERT_SUBJECT);
if (subjectname != null) {
CertificateSubjectName certSubject = (CertificateSubjectName)
- new CertificateSubjectName(new X500Name(subjectname));
+ new CertificateSubjectName(new X500Name(subjectname));
certInfo.set(X509CertInfo.SUBJECT, certSubject);
log(ILogger.LL_INFO,
- "cert subject set to " + certSubject + " from authtoken");
+ "cert subject set to " + certSubject + " from authtoken");
}
} catch (CertificateException e) {
log(ILogger.LL_WARN,
- CMS.getLogMessage("CMSGW_ERROR_SET_SUBJECT_NAME_1",
- e.toString()));
+ CMS.getLogMessage("CMSGW_ERROR_SET_SUBJECT_NAME_1",
+ e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SET_SUBJECT_NAME_ERROR"));
+ CMS.getUserMessage("CMS_GW_SET_SUBJECT_NAME_ERROR"));
} catch (IOException e) {
log(ILogger.LL_WARN,
- CMS.getLogMessage("CMSGW_ERROR_SET_SUBJECT_NAME",
- e.toString()));
+ CMS.getLogMessage("CMSGW_ERROR_SET_SUBJECT_NAME",
+ e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SET_SUBJECT_NAME_ERROR"));
+ CMS.getUserMessage("CMS_GW_SET_SUBJECT_NAME_ERROR"));
}
// validity
try {
CertificateValidity validity = null;
Date notBefore =
- authToken.getInDate(AuthToken.TOKEN_CERT_NOTBEFORE);
+ authToken.getInDate(AuthToken.TOKEN_CERT_NOTBEFORE);
Date notAfter =
- authToken.getInDate(AuthToken.TOKEN_CERT_NOTAFTER);
+ authToken.getInDate(AuthToken.TOKEN_CERT_NOTAFTER);
if (notBefore != null && notAfter != null) {
validity = new CertificateValidity(notBefore, notAfter);
certInfo.set(X509CertInfo.VALIDITY, validity);
log(ILogger.LL_INFO,
- "cert validity set to " + validity + " from authtoken");
+ "cert validity set to " + validity + " from authtoken");
}
} catch (CertificateException e) {
log(ILogger.LL_WARN,
- CMS.getLogMessage("CMSGW_ERROR_SET_VALIDITY_1", e.toString()));
+ CMS.getLogMessage("CMSGW_ERROR_SET_VALIDITY_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SET_VALIDITY_ERROR"));
+ CMS.getUserMessage("CMS_GW_SET_VALIDITY_ERROR"));
} catch (IOException e) {
log(ILogger.LL_WARN,
- CMS.getLogMessage("CMSGW_ERROR_SET_VALIDITY_1", e.toString()));
+ CMS.getLogMessage("CMSGW_ERROR_SET_VALIDITY_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SET_VALIDITY_ERROR"));
+ CMS.getUserMessage("CMS_GW_SET_VALIDITY_ERROR"));
}
// extensions
try {
CertificateExtensions extensions =
- authToken.getInCertExts(X509CertInfo.EXTENSIONS);
+ authToken.getInCertExts(X509CertInfo.EXTENSIONS);
if (extensions != null) {
certInfo.set(X509CertInfo.EXTENSIONS, extensions);
@@ -177,26 +175,25 @@ public class PKIProcessor implements IPKIProcessor {
}
} catch (CertificateException e) {
log(ILogger.LL_WARN,
- CMS.getLogMessage("CMSGW_ERROR_SET_EXTENSIONS_1", e.toString()));
+ CMS.getLogMessage("CMSGW_ERROR_SET_EXTENSIONS_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SET_EXTENSIONS_ERROR"));
+ CMS.getUserMessage("CMS_GW_SET_EXTENSIONS_ERROR"));
} catch (IOException e) {
log(ILogger.LL_WARN,
- CMS.getLogMessage("CMSGW_ERROR_SET_EXTENSIONS_1", e.toString()));
+ CMS.getLogMessage("CMSGW_ERROR_SET_EXTENSIONS_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SET_EXTENSIONS_ERROR"));
+ CMS.getUserMessage("CMS_GW_SET_EXTENSIONS_ERROR"));
}
}
/**
- * fill subject name, extension from form.
- * this is done for unauthenticated requests.
- * unauthenticated requests must be approved by agents so these will
- * all be seen by and agent.
+ * fill subject name, extension from form. this is done for unauthenticated
+ * requests. unauthenticated requests must be approved by agents so these
+ * will all be seen by and agent.
*/
public static void fillCertInfoFromForm(
- X509CertInfo certInfo, IArgBlock httpParams)
- throws EBaseException {
+ X509CertInfo certInfo, IArgBlock httpParams)
+ throws EBaseException {
CMS.debug("PKIProcessor: fillCertInfoFromForm");
// subject name.
@@ -205,41 +202,41 @@ public class PKIProcessor implements IPKIProcessor {
if (subject == null) {
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_MISSING_SUBJECT_FROM_FORM"));
+ CMS.getUserMessage("CMS_GW_MISSING_SUBJECT_FROM_FORM"));
}
X500Name x500name = new X500Name(subject);
certInfo.set(
- X509CertInfo.SUBJECT, new CertificateSubjectName(x500name));
+ X509CertInfo.SUBJECT, new CertificateSubjectName(x500name));
fillValidityFromForm(certInfo, httpParams);
} catch (CertificateException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_SET_SUBJECT_NAME_1", e.toString()));
+ CMS.getLogMessage("CMSGW_ERROR_SET_SUBJECT_NAME_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SET_SUBJECT_NAME_ERROR"));
+ CMS.getUserMessage("CMS_GW_SET_SUBJECT_NAME_ERROR"));
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_SET_SUBJECT_NAME_1", e.toString()));
+ CMS.getLogMessage("CMSGW_ERROR_SET_SUBJECT_NAME_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SET_SUBJECT_NAME_ERROR"));
+ CMS.getUserMessage("CMS_GW_SET_SUBJECT_NAME_ERROR"));
} catch (IllegalArgumentException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_SET_SUBJECT_NAME_1", e.toString()));
+ CMS.getLogMessage("CMSGW_ERROR_SET_SUBJECT_NAME_1", e.toString()));
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_REQ_ILLEGAL_CHARACTERS"));
+ CMS.getLogMessage("CMSGW_REQ_ILLEGAL_CHARACTERS"));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_CONVERT_DN_TO_X500NAME_ERROR"));
+ CMS.getUserMessage("CMS_GW_CONVERT_DN_TO_X500NAME_ERROR"));
}
// requested extensions.
// let polcies form extensions from http input.
}
- public static void fillValidityFromForm(
- X509CertInfo certInfo, IArgBlock httpParams)
- throws EBaseException {
+ public static void fillValidityFromForm(
+ X509CertInfo certInfo, IArgBlock httpParams)
+ throws EBaseException {
CMS.debug("PKIProcessor: fillValidityFromForm!");
try {
String notValidBeforeStr = httpParams.getValueAsString("notValidBefore", null);
@@ -267,43 +264,43 @@ public class PKIProcessor implements IPKIProcessor {
validity = new CertificateValidity(notBefore, notAfter);
certInfo.set(X509CertInfo.VALIDITY, validity);
log(ILogger.LL_INFO,
- "cert validity set to " + validity + " from authtoken");
+ "cert validity set to " + validity + " from authtoken");
}
}
}
} catch (CertificateException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_SET_SUBJECT_NAME_1", e.toString()));
+ CMS.getLogMessage("CMSGW_ERROR_SET_SUBJECT_NAME_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SET_SUBJECT_NAME_ERROR"));
+ CMS.getUserMessage("CMS_GW_SET_SUBJECT_NAME_ERROR"));
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_SET_SUBJECT_NAME_1", e.toString()));
+ CMS.getLogMessage("CMSGW_ERROR_SET_SUBJECT_NAME_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_SET_SUBJECT_NAME_ERROR"));
+ CMS.getUserMessage("CMS_GW_SET_SUBJECT_NAME_ERROR"));
}
}
/**
* log according to authority category.
*/
- public static void log(int event, int level, String msg) {
+ public static void log(int event, int level, String msg) {
CMS.getLogger().log(event, ILogger.S_OTHER, level,
- "PKIProcessor " + ": " + msg);
+ "PKIProcessor " + ": " + msg);
}
public static void log(int level, String msg) {
CMS.getLogger().log(ILogger.EV_SYSTEM, ILogger.S_OTHER, level,
- "PKIProcessor " + ": " + msg);
+ "PKIProcessor " + ": " + msg);
}
/**
* Signed Audit Log
- *
- * This method is inherited by all extended "CMSServlet"s,
- * and is called to store messages to the signed audit log.
+ *
+ * This method is inherited by all extended "CMSServlet"s, and is called to
+ * store messages to the signed audit log.
* <P>
- *
+ *
* @param msg signed audit log message
*/
protected void audit(String msg) {
@@ -315,20 +312,19 @@ public class PKIProcessor implements IPKIProcessor {
}
mSignedAuditLogger.log(ILogger.EV_SIGNED_AUDIT,
- null,
- ILogger.S_SIGNED_AUDIT,
- ILogger.LL_SECURITY,
- msg);
+ null,
+ ILogger.S_SIGNED_AUDIT,
+ ILogger.LL_SECURITY,
+ msg);
}
/**
* Signed Audit Log Subject ID
- *
- * This method is inherited by all extended "CMSServlet"s,
- * and is called to obtain the "SubjectID" for
- * a signed audit log message.
+ *
+ * This method is inherited by all extended "CMSServlet"s, and is called to
+ * obtain the "SubjectID" for a signed audit log message.
* <P>
- *
+ *
* @return id string containing the signed audit log message SubjectID
*/
protected String auditSubjectID() {
@@ -358,4 +354,3 @@ public class PKIProcessor implements IPKIProcessor {
return subjectID;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileApproveServlet.java b/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileApproveServlet.java
index da24d2c2..b5cec9da 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileApproveServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileApproveServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.profile;
-
import java.util.Enumeration;
import java.util.Locale;
@@ -46,10 +45,9 @@ import com.netscape.certsrv.template.ArgList;
import com.netscape.certsrv.template.ArgSet;
import com.netscape.cms.servlet.common.CMSRequest;
-
/**
* Toggle the approval state of a profile
- *
+ *
* @version $Revision$, $Date$
*/
public class ProfileApproveServlet extends ProfileServlet {
@@ -59,10 +57,10 @@ public class ProfileApproveServlet extends ProfileServlet {
*/
private static final long serialVersionUID = 3956879326742839550L;
private static final String PROP_AUTHORITY_ID = "authorityId";
- private String mAuthorityId = null;
+ private String mAuthorityId = null;
private final static String LOGGING_SIGNED_AUDIT_CERT_PROFILE_APPROVAL =
- "LOGGING_SIGNED_AUDIT_CERT_PROFILE_APPROVAL_4";
+ "LOGGING_SIGNED_AUDIT_CERT_PROFILE_APPROVAL_4";
private final static String OP_APPROVE = "approve";
private final static String OP_DISAPPROVE = "disapprove";
@@ -73,7 +71,7 @@ public class ProfileApproveServlet extends ProfileServlet {
/**
* initialize the servlet. This servlet uses the template file
* "ImportCert.template" to process the response.
- *
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -84,13 +82,14 @@ public class ProfileApproveServlet extends ProfileServlet {
/**
* Process the HTTP request.
* <P>
- *
+ *
* <ul>
* <li>http.param profileId the id of the profile to change
* <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_PROFILE_APPROVAL used when an
* agent approves/disapproves a cert profile set by the administrator for
* automatic approval
* </ul>
+ *
* @param cmsReq the object holding the request and response information
* @exception EBaseException an error has occurred
*/
@@ -126,8 +125,8 @@ public class ProfileApproveServlet extends ProfileServlet {
auditSubjectID = auditSubjectID();
CMS.debug(e.toString());
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE",
- e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE",
+ e.toString()));
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
"CMS_AUTHENTICATION_ERROR"));
@@ -153,12 +152,12 @@ public class ProfileApproveServlet extends ProfileServlet {
mAuthzResourceName, "approve");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE",
- e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE",
+ e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE",
- e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE",
+ e.toString()));
}
if (authzToken == null) {
@@ -214,8 +213,8 @@ public class ProfileApproveServlet extends ProfileServlet {
IAuthority authority = (IAuthority) CMS.getSubsystem(mAuthorityId);
if (authority == null) {
- CMS.debug("ProfileApproveServlet: Authority " + mAuthorityId +
- " not found");
+ CMS.debug("ProfileApproveServlet: Authority " + mAuthorityId +
+ " not found");
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
"CMS_INTERNAL_ERROR"));
@@ -236,8 +235,8 @@ public class ProfileApproveServlet extends ProfileServlet {
IRequestQueue queue = authority.getRequestQueue();
if (queue == null) {
- CMS.debug("ProfileApproveServlet: Request Queue of " +
- mAuthorityId + " not found");
+ CMS.debug("ProfileApproveServlet: Request Queue of " +
+ mAuthorityId + " not found");
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
"CMS_INTERNAL_ERROR"));
@@ -265,31 +264,31 @@ public class ProfileApproveServlet extends ProfileServlet {
try {
if (ps.isProfileEnable(profileId)) {
- if (ps.checkOwner()) {
- if (ps.getProfileEnableBy(profileId).equals(userid)) {
- ps.disableProfile(profileId);
- } else {
- // only enableBy can disable profile
- args.set(ARG_ERROR_CODE, "1");
- args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
- "CMS_PROFILE_NOT_OWNER"));
- outputTemplate(request, response, args);
-
- // store a message in the signed audit log file
- auditMessage = CMS.getLogMessage(
+ if (ps.checkOwner()) {
+ if (ps.getProfileEnableBy(profileId).equals(userid)) {
+ ps.disableProfile(profileId);
+ } else {
+ // only enableBy can disable profile
+ args.set(ARG_ERROR_CODE, "1");
+ args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
+ "CMS_PROFILE_NOT_OWNER"));
+ outputTemplate(request, response, args);
+
+ // store a message in the signed audit log file
+ auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CERT_PROFILE_APPROVAL,
auditSubjectID,
ILogger.FAILURE,
auditProfileID,
auditProfileOp);
- audit(auditMessage);
+ audit(auditMessage);
- return;
+ return;
+ }
+ } else {
+ ps.disableProfile(profileId);
}
- } else {
- ps.disableProfile(profileId);
- }
} else {
ps.enableProfile(profileId, userid);
}
@@ -305,8 +304,8 @@ public class ProfileApproveServlet extends ProfileServlet {
audit(auditMessage);
} catch (EProfileException e) {
// profile not enabled
- CMS.debug("ProfileApproveServlet: profile not error " +
- e.toString());
+ CMS.debug("ProfileApproveServlet: profile not error " +
+ e.toString());
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
"CMS_INTERNAL_ERROR"));
@@ -338,26 +337,26 @@ public class ProfileApproveServlet extends ProfileServlet {
// rethrow the specific exception to be handled later
throw eAudit1;
// } catch( ServletException eAudit2 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CERT_PROFILE_APPROVAL,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditProfileID,
- // auditProfileOp );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CERT_PROFILE_APPROVAL,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditProfileID,
+ // auditProfileOp );
//
- // audit( auditMessage );
+ // audit( auditMessage );
//
- // // rethrow the specific exception to be handled later
- // throw eAudit2;
+ // // rethrow the specific exception to be handled later
+ // throw eAudit2;
}
try {
profile = ps.getProfile(profileId);
} catch (EProfileException e) {
// profile not found
- CMS.debug("ProfileApproveServlet: profile not found " +
- e.toString());
+ CMS.debug("ProfileApproveServlet: profile not found " +
+ e.toString());
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, e.toString());
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
@@ -386,13 +385,13 @@ public class ProfileApproveServlet extends ProfileServlet {
while (policyIds.hasMoreElements()) {
String id = (String) policyIds.nextElement();
IProfilePolicy policy = (IProfilePolicy)
- profile.getProfilePolicy(setId, id);
+ profile.getProfilePolicy(setId, id);
// (3) query all the profile policies
// (4) default plugins convert request parameters
- // into string http parameters
+ // into string http parameters
handlePolicy(list, response, locale,
- id, policy);
+ id, policy);
}
ArgSet setArg = new ArgSet();
@@ -403,8 +402,8 @@ public class ProfileApproveServlet extends ProfileServlet {
args.set(ARG_POLICY_SET_LIST, setlist);
args.set(ARG_PROFILE_ID, profileId);
- args.set(ARG_PROFILE_IS_ENABLED,
- Boolean.toString(ps.isProfileEnable(profileId)));
+ args.set(ARG_PROFILE_IS_ENABLED,
+ Boolean.toString(ps.isProfileEnable(profileId)));
args.set(ARG_PROFILE_ENABLED_BY, ps.getProfileEnableBy(profileId));
args.set(ARG_PROFILE_NAME, profile.getName(locale));
args.set(ARG_PROFILE_DESC, profile.getDescription(locale));
@@ -413,8 +412,8 @@ public class ProfileApproveServlet extends ProfileServlet {
outputTemplate(request, response, args);
}
- private void handlePolicy(ArgList list, ServletResponse response,
- Locale locale, String id, IProfilePolicy policy) {
+ private void handlePolicy(ArgList list, ServletResponse response,
+ Locale locale, String id, IProfilePolicy policy) {
ArgSet set = new ArgSet();
set.set(ARG_POLICY_ID, id);
@@ -434,19 +433,19 @@ public class ProfileApproveServlet extends ProfileServlet {
String defName = (String) defNames.nextElement();
IDescriptor defDesc = def.getValueDescriptor(locale, defName);
if (defDesc == null) {
- CMS.debug("defName=" + defName);
+ CMS.debug("defName=" + defName);
} else {
- String defSyntax = defDesc.getSyntax();
- String defConstraint = defDesc.getConstraint();
- String defValueName = defDesc.getDescription(locale);
- String defValue = null;
-
- defset.set(ARG_DEF_ID, defName);
- defset.set(ARG_DEF_SYNTAX, defSyntax);
- defset.set(ARG_DEF_CONSTRAINT, defConstraint);
- defset.set(ARG_DEF_NAME, defValueName);
- defset.set(ARG_DEF_VAL, defValue);
- deflist.add(defset);
+ String defSyntax = defDesc.getSyntax();
+ String defConstraint = defDesc.getConstraint();
+ String defValueName = defDesc.getDescription(locale);
+ String defValue = null;
+
+ defset.set(ARG_DEF_ID, defName);
+ defset.set(ARG_DEF_SYNTAX, defSyntax);
+ defset.set(ARG_DEF_CONSTRAINT, defConstraint);
+ defset.set(ARG_DEF_NAME, defValueName);
+ defset.set(ARG_DEF_VAL, defValue);
+ deflist.add(defset);
}
}
}
@@ -463,11 +462,11 @@ public class ProfileApproveServlet extends ProfileServlet {
/**
* Signed Audit Log Profile ID
- *
- * This method is called to obtain the "ProfileID" for
- * a signed audit log message.
+ *
+ * This method is called to obtain the "ProfileID" for a signed audit log
+ * message.
* <P>
- *
+ *
* @param req HTTP request
* @return id string containing the signed audit log message ProfileID
*/
@@ -493,14 +492,14 @@ public class ProfileApproveServlet extends ProfileServlet {
/**
* Signed Audit Log Profile Operation
- *
- * This method is called to obtain the "Profile Operation" for
- * a signed audit log message.
+ *
+ * This method is called to obtain the "Profile Operation" for a signed
+ * audit log message.
* <P>
- *
+ *
* @param req HTTP request
- * @return operation string containing either OP_APPROVE, OP_DISAPPROVE,
- * or SIGNED_AUDIT_EMPTY_VALUE
+ * @return operation string containing either OP_APPROVE, OP_DISAPPROVE, or
+ * SIGNED_AUDIT_EMPTY_VALUE
*/
private String auditProfileOp(HttpServletRequest req) {
// if no signed audit object exists, bail
@@ -509,12 +508,12 @@ public class ProfileApproveServlet extends ProfileServlet {
}
if (mProfileSubId == null ||
- mProfileSubId.equals("")) {
+ mProfileSubId.equals("")) {
mProfileSubId = IProfileSubsystem.ID;
}
IProfileSubsystem ps = (IProfileSubsystem)
- CMS.getSubsystem(mProfileSubId);
+ CMS.getSubsystem(mProfileSubId);
if (ps == null) {
return ILogger.SIGNED_AUDIT_EMPTY_VALUE;
@@ -533,4 +532,3 @@ public class ProfileApproveServlet extends ProfileServlet {
}
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileListServlet.java b/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileListServlet.java
index 4da41f7a..8581b3ca 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileListServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileListServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.profile;
-
import java.util.Enumeration;
import java.util.Locale;
@@ -38,10 +37,9 @@ import com.netscape.certsrv.template.ArgList;
import com.netscape.certsrv.template.ArgSet;
import com.netscape.cms.servlet.common.CMSRequest;
-
/**
* List all enabled profiles.
- *
+ *
* @version $Revision$, $Date$
*/
public class ProfileListServlet extends ProfileServlet {
@@ -53,7 +51,7 @@ public class ProfileListServlet extends ProfileServlet {
private static final String PROP_AUTHORITY_ID = "authorityId";
- private String mAuthorityId = null;
+ private String mAuthorityId = null;
public ProfileListServlet() {
super();
@@ -62,7 +60,7 @@ public class ProfileListServlet extends ProfileServlet {
/**
* initialize the servlet. This servlet uses the template file
* "ImportCert.template" to process the response.
- *
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -72,7 +70,7 @@ public class ProfileListServlet extends ProfileServlet {
/**
* Process the HTTP request.
- *
+ *
* @param cmsReq the object holding the request and response information
*/
public void process(CMSRequest cmsReq) throws EBaseException {
@@ -93,10 +91,10 @@ public class ProfileListServlet extends ProfileServlet {
mAuthzResourceName, "list");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -115,17 +113,17 @@ public class ProfileListServlet extends ProfileServlet {
}
CMS.debug("ProfileListServlet: SubId=" + mProfileSubId);
IProfileSubsystem ps = (IProfileSubsystem)
- CMS.getSubsystem(mProfileSubId);
+ CMS.getSubsystem(mProfileSubId);
if (ps == null) {
- CMS.debug("ProfileListServlet: ProfileSubsystem " +
- mProfileSubId + " not found");
+ CMS.debug("ProfileListServlet: ProfileSubsystem " +
+ mProfileSubId + " not found");
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
"CMS_INTERNAL_ERROR"));
outputTemplate(request, response, args);
return;
- }
+ }
ArgList list = new ArgList();
Enumeration e = ps.getProfileIds();
@@ -139,13 +137,13 @@ public class ProfileListServlet extends ProfileServlet {
profile = ps.getProfile(id);
} catch (EBaseException e1) {
// skip bad profile
- CMS.debug("ProfileListServlet: profile " + id +
- " not found (skipped) " + e1.toString());
+ CMS.debug("ProfileListServlet: profile " + id +
+ " not found (skipped) " + e1.toString());
continue;
}
if (profile == null) {
- CMS.debug("ProfileListServlet: profile " + id +
- " not found (skipped)");
+ CMS.debug("ProfileListServlet: profile " + id +
+ " not found (skipped)");
continue;
}
@@ -155,16 +153,16 @@ public class ProfileListServlet extends ProfileServlet {
ArgSet profileArgs = new ArgSet();
profileArgs.set(ARG_PROFILE_IS_ENABLED,
- Boolean.toString(ps.isProfileEnable(id)));
+ Boolean.toString(ps.isProfileEnable(id)));
profileArgs.set(ARG_PROFILE_ENABLED_BY,
- ps.getProfileEnableBy(id));
+ ps.getProfileEnableBy(id));
profileArgs.set(ARG_PROFILE_ID, id);
- profileArgs.set(ARG_PROFILE_IS_VISIBLE,
- Boolean.toString(profile.isVisible()));
+ profileArgs.set(ARG_PROFILE_IS_VISIBLE,
+ Boolean.toString(profile.isVisible()));
profileArgs.set(ARG_PROFILE_NAME, name);
profileArgs.set(ARG_PROFILE_DESC, desc);
list.add(profileArgs);
-
+
}
}
args.set(ARG_RECORD, list);
diff --git a/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileProcessServlet.java b/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileProcessServlet.java
index 33233275..ebfc2e9f 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileProcessServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileProcessServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.profile;
-
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.Date;
@@ -63,10 +62,9 @@ import com.netscape.certsrv.template.ArgSet;
import com.netscape.certsrv.util.IStatsSubsystem;
import com.netscape.cms.servlet.common.CMSRequest;
-
/**
* This servlet approves profile-based request.
- *
+ *
* @version $Revision$, $Date$
*/
public class ProfileProcessServlet extends ProfileServlet {
@@ -79,9 +77,9 @@ public class ProfileProcessServlet extends ProfileServlet {
private Nonces mNonces = null;
private final static String SIGNED_AUDIT_CERT_REQUEST_REASON =
- "requestNotes";
+ "requestNotes";
private final static String LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED =
- "LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED_5";
+ "LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED_5";
public ProfileProcessServlet() {
}
@@ -103,9 +101,9 @@ public class ProfileProcessServlet extends ProfileServlet {
HttpServletRequest request = cmsReq.getHttpReq();
HttpServletResponse response = cmsReq.getHttpResp();
- IStatsSubsystem statsSub = (IStatsSubsystem)CMS.getSubsystem("stats");
+ IStatsSubsystem statsSub = (IStatsSubsystem) CMS.getSubsystem("stats");
if (statsSub != null) {
- statsSub.startTiming("approval", true /* main action */);
+ statsSub.startTiming("approval", true /* main action */);
}
IAuthToken authToken = null;
@@ -119,13 +117,13 @@ public class ProfileProcessServlet extends ProfileServlet {
} catch (EBaseException e) {
CMS.debug("ProfileProcessServlet: " + e.toString());
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
- args.set(ARG_ERROR_CODE, "1");
- args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ args.set(ARG_ERROR_CODE, "1");
+ args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
"CMS_AUTHENTICATION_ERROR"));
outputTemplate(request, response, args);
if (statsSub != null) {
- statsSub.endTiming("approval");
+ statsSub.endTiming("approval");
}
return;
}
@@ -138,10 +136,10 @@ public class ProfileProcessServlet extends ProfileServlet {
mAuthzResourceName, "approve");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -150,7 +148,7 @@ public class ProfileProcessServlet extends ProfileServlet {
"CMS_AUTHORIZATION_ERROR"));
outputTemplate(request, response, args);
if (statsSub != null) {
- statsSub.endTiming("approval");
+ statsSub.endTiming("approval");
}
return;
}
@@ -171,7 +169,7 @@ public class ProfileProcessServlet extends ProfileServlet {
} else {
CMS.debug("ProfileProcessServlet: Missing nonce");
}
- CMS.debug("ProfileProcessServlet: nonceVerified="+nonceVerified);
+ CMS.debug("ProfileProcessServlet: nonceVerified=" + nonceVerified);
if (!nonceVerified) {
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
@@ -194,7 +192,7 @@ public class ProfileProcessServlet extends ProfileServlet {
}
CMS.debug("ProfileProcessServlet: SubId=" + mProfileSubId);
IProfileSubsystem ps = (IProfileSubsystem)
- CMS.getSubsystem(mProfileSubId);
+ CMS.getSubsystem(mProfileSubId);
if (ps == null) {
CMS.debug("ProfileProcessServlet: ProfileSubsystem not found");
@@ -203,7 +201,7 @@ public class ProfileProcessServlet extends ProfileServlet {
"CMS_INTERNAL_ERROR"));
outputTemplate(request, response, args);
if (statsSub != null) {
- statsSub.endTiming("approval");
+ statsSub.endTiming("approval");
}
return;
}
@@ -213,13 +211,13 @@ public class ProfileProcessServlet extends ProfileServlet {
if (authority == null) {
CMS.debug("ProfileProcessServlet: Authority " + mAuthorityId +
- " not found");
+ " not found");
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
"CMS_INTERNAL_ERROR"));
outputTemplate(request, response, args);
if (statsSub != null) {
- statsSub.endTiming("approval");
+ statsSub.endTiming("approval");
}
return;
}
@@ -227,13 +225,13 @@ public class ProfileProcessServlet extends ProfileServlet {
if (queue == null) {
CMS.debug("ProfileProcessServlet: Request Queue of " +
- mAuthorityId + " not found");
+ mAuthorityId + " not found");
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
"CMS_INTERNAL_ERROR"));
outputTemplate(request, response, args);
if (statsSub != null) {
- statsSub.endTiming("approval");
+ statsSub.endTiming("approval");
}
return;
}
@@ -247,7 +245,7 @@ public class ProfileProcessServlet extends ProfileServlet {
"CMS_REQUEST_ID_NOT_FOUND"));
outputTemplate(request, response, args);
if (statsSub != null) {
- statsSub.endTiming("approval");
+ statsSub.endTiming("approval");
}
return;
}
@@ -259,8 +257,8 @@ public class ProfileProcessServlet extends ProfileServlet {
req = queue.findRequest(new RequestId(requestId));
} catch (EBaseException e) {
// request not found
- CMS.debug("ProfileProcessServlet: request not found requestId=" +
- requestId + " " + e.toString());
+ CMS.debug("ProfileProcessServlet: request not found requestId=" +
+ requestId + " " + e.toString());
}
if (req == null) {
args.set(ARG_ERROR_CODE, "1");
@@ -268,12 +266,12 @@ public class ProfileProcessServlet extends ProfileServlet {
"CMS_REQUEST_NOT_FOUND", requestId));
outputTemplate(request, response, args);
if (statsSub != null) {
- statsSub.endTiming("approval");
+ statsSub.endTiming("approval");
}
return;
}
- // check if the request is in one of the terminal states
+ // check if the request is in one of the terminal states
if (!req.getRequestStatus().equals(RequestStatus.PENDING)) {
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
@@ -281,7 +279,7 @@ public class ProfileProcessServlet extends ProfileServlet {
args.set(ARG_REQUEST_ID, requestId);
outputTemplate(request, response, args);
if (statsSub != null) {
- statsSub.endTiming("approval");
+ statsSub.endTiming("approval");
}
return;
}
@@ -296,7 +294,7 @@ public class ProfileProcessServlet extends ProfileServlet {
"CMS_PROFILE_ID_NOT_FOUND"));
outputTemplate(request, response, args);
if (statsSub != null) {
- statsSub.endTiming("approval");
+ statsSub.endTiming("approval");
}
return;
}
@@ -309,20 +307,19 @@ public class ProfileProcessServlet extends ProfileServlet {
"CMS_OP_NOT_FOUND"));
outputTemplate(request, response, args);
if (statsSub != null) {
- statsSub.endTiming("approval");
+ statsSub.endTiming("approval");
}
return;
}
-
IProfile profile = null;
try {
profile = ps.getProfile(profileId);
} catch (EProfileException e) {
// profile not found
- CMS.debug("ProfileProcessServlet: profile not found " +
- " " + " profileId=" + profileId + " " + e.toString());
+ CMS.debug("ProfileProcessServlet: profile not found " +
+ " " + " profileId=" + profileId + " " + e.toString());
}
if (profile == null) {
args.set(ARG_ERROR_CODE, "1");
@@ -330,7 +327,7 @@ public class ProfileProcessServlet extends ProfileServlet {
"CMS_PROFILE_NOT_FOUND", profileId));
outputTemplate(request, response, args);
if (statsSub != null) {
- statsSub.endTiming("approval");
+ statsSub.endTiming("approval");
}
return;
}
@@ -348,12 +345,11 @@ public class ProfileProcessServlet extends ProfileServlet {
"CMS_PROFILE_ID_NOT_ENABLED"));
outputTemplate(request, response, args);
if (statsSub != null) {
- statsSub.endTiming("approval");
+ statsSub.endTiming("approval");
}
return;
}
-
args.set(ARG_ERROR_CODE, "0");
args.set(ARG_ERROR_REASON, "");
@@ -361,7 +357,7 @@ public class ProfileProcessServlet extends ProfileServlet {
if (op.equals("assign")) {
String owner = req.getRequestOwner();
- // assigned owner
+ // assigned owner
if (owner != null && owner.length() > 0) {
if (!grantPermission(req, authToken)) {
CMS.debug("ProfileProcessServlet: Permission not granted to assign request.");
@@ -375,7 +371,7 @@ public class ProfileProcessServlet extends ProfileServlet {
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale, "CMS_PROFILE_DENY_OPERATION"));
outputTemplate(request, response, args);
if (statsSub != null) {
- statsSub.endTiming("approval");
+ statsSub.endTiming("approval");
}
return;
}
@@ -414,14 +410,14 @@ public class ProfileProcessServlet extends ProfileServlet {
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale, "CMS_PROFILE_DENY_OPERATION"));
outputTemplate(request, response, args);
if (statsSub != null) {
- statsSub.endTiming("approval");
+ statsSub.endTiming("approval");
}
return;
}
}
// commit request to the storage
- if (!op.equals("validate")) {
+ if (!op.equals("validate")) {
try {
if (op.equals("approve")) {
queue.markAsServiced(req);
@@ -429,40 +425,40 @@ public class ProfileProcessServlet extends ProfileServlet {
queue.updateRequest(req);
}
} catch (EBaseException e) {
- CMS.debug("ProfileProcessServlet: Request commit error " +
- e.toString());
+ CMS.debug("ProfileProcessServlet: Request commit error " +
+ e.toString());
// save request to disk
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
"CMS_INTERNAL_ERROR"));
outputTemplate(request, response, args);
if (statsSub != null) {
- statsSub.endTiming("approval");
+ statsSub.endTiming("approval");
}
return;
}
}
} catch (ERejectException e) {
- CMS.debug("ProfileProcessServlet: execution rejected " +
- e.toString());
+ CMS.debug("ProfileProcessServlet: execution rejected " +
+ e.toString());
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
"CMS_PROFILE_REJECTED", e.toString()));
} catch (EDeferException e) {
- CMS.debug("ProfileProcessServlet: execution defered " +
- e.toString());
+ CMS.debug("ProfileProcessServlet: execution defered " +
+ e.toString());
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
"CMS_PROFILE_DEFERRED", e.toString()));
} catch (EPropertyException e) {
- CMS.debug("ProfileProcessServlet: execution error " +
- e.toString());
+ CMS.debug("ProfileProcessServlet: execution error " +
+ e.toString());
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
"CMS_PROFILE_PROPERTY_ERROR", e.toString()));
} catch (EProfileException e) {
- CMS.debug("ProfileProcessServlet: execution error " +
- e.toString());
+ CMS.debug("ProfileProcessServlet: execution error " +
+ e.toString());
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
"CMS_INTERNAL_ERROR"));
@@ -475,15 +471,15 @@ public class ProfileProcessServlet extends ProfileServlet {
args.set(ARG_PROFILE_ID, profileId);
outputTemplate(request, response, args);
if (statsSub != null) {
- statsSub.endTiming("approval");
+ statsSub.endTiming("approval");
}
}
-
+
public boolean grantPermission(IRequest req, IAuthToken token) {
try {
boolean enable = CMS.getConfigStore().getBoolean("request.assignee.enable",
- false);
+ false);
if (!enable)
return true;
String owner = req.getRequestOwner();
@@ -496,32 +492,32 @@ public class ProfileProcessServlet extends ProfileServlet {
return true;
} catch (Exception e) {
}
-
+
return false;
}
/**
- * Check if the request creation time is older than the profile
- * lastModified attribute.
+ * Check if the request creation time is older than the profile lastModified
+ * attribute.
*/
- protected void checkProfileVersion(IProfile profile, IRequest req,
- Locale locale) throws EProfileException {
+ protected void checkProfileVersion(IProfile profile, IRequest req,
+ Locale locale) throws EProfileException {
IConfigStore profileConfig = profile.getConfigStore();
if (profileConfig != null) {
String lastModified = null;
try {
- lastModified = profileConfig.getString("lastModified","");
+ lastModified = profileConfig.getString("lastModified", "");
} catch (EBaseException e) {
- CMS.debug(e.toString());
- throw new EProfileException( e.toString() );
+ CMS.debug(e.toString());
+ throw new EProfileException(e.toString());
}
if (!lastModified.equals("")) {
Date profileModifiedAt = new Date(Long.parseLong(lastModified));
- CMS.debug("ProfileProcessServlet: Profile Last Modified=" +
- profileModifiedAt);
+ CMS.debug("ProfileProcessServlet: Profile Last Modified=" +
+ profileModifiedAt);
Date reqCreatedAt = req.getCreationTime();
- CMS.debug("ProfileProcessServlet: Request Created At=" +
- reqCreatedAt);
+ CMS.debug("ProfileProcessServlet: Request Created At=" +
+ reqCreatedAt);
if (profileModifiedAt.after(reqCreatedAt)) {
CMS.debug("Profile Newer Than Request");
throw new ERejectException("Profile Newer Than Request");
@@ -531,18 +527,18 @@ public class ProfileProcessServlet extends ProfileServlet {
}
protected void assignRequest(ServletRequest request, ArgSet args,
- IRequest req,
- IRequestQueue queue, IProfile profile, Locale locale)
- throws EProfileException {
+ IRequest req,
+ IRequestQueue queue, IProfile profile, Locale locale)
+ throws EProfileException {
String id = auditSubjectID();
req.setRequestOwner(id);
}
protected void unassignRequest(ServletRequest request, ArgSet args,
- IRequest req,
- IRequestQueue queue, IProfile profile, Locale locale)
- throws EProfileException {
+ IRequest req,
+ IRequestQueue queue, IProfile profile, Locale locale)
+ throws EProfileException {
req.setRequestOwner("");
}
@@ -552,13 +548,14 @@ public class ProfileProcessServlet extends ProfileServlet {
* <P>
*
* (Certificate Request Processed - a manual "agent" profile based cert
- * cancellation)
+ * cancellation)
* <P>
*
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED used when a
* certificate request has just been through the approval process
* </ul>
+ *
* @param request the servlet request
* @param args argument set
* @param req the certificate request
@@ -566,12 +563,12 @@ public class ProfileProcessServlet extends ProfileServlet {
* @param profile this profile
* @param locale the system locale
* @exception EProfileException an error related to this profile has
- * occurred
+ * occurred
*/
protected void cancelRequest(ServletRequest request, ArgSet args,
- IRequest req,
- IRequestQueue queue, IProfile profile, Locale locale)
- throws EProfileException {
+ IRequest req,
+ IRequestQueue queue, IProfile profile, Locale locale)
+ throws EProfileException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
String auditRequesterID = auditRequesterID(req);
@@ -591,16 +588,16 @@ public class ProfileProcessServlet extends ProfileServlet {
audit(auditMessage);
// } catch( EProfileException eAudit1 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditRequesterID,
- // ILogger.SIGNED_AUDIT_CANCELLATION,
- // auditInfoValue );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditRequesterID,
+ // ILogger.SIGNED_AUDIT_CANCELLATION,
+ // auditInfoValue );
//
- // audit( auditMessage );
+ // audit( auditMessage );
// }
}
@@ -609,13 +606,14 @@ public class ProfileProcessServlet extends ProfileServlet {
* <P>
*
* (Certificate Request Processed - a manual "agent" profile based cert
- * rejection)
+ * rejection)
* <P>
*
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED used when a
* certificate request has just been through the approval process
* </ul>
+ *
* @param request the servlet request
* @param args argument set
* @param req the certificate request
@@ -623,12 +621,12 @@ public class ProfileProcessServlet extends ProfileServlet {
* @param profile this profile
* @param locale the system locale
* @exception EProfileException an error related to this profile has
- * occurred
+ * occurred
*/
protected void rejectRequest(ServletRequest request, ArgSet args,
- IRequest req,
- IRequestQueue queue, IProfile profile, Locale locale)
- throws EProfileException {
+ IRequest req,
+ IRequestQueue queue, IProfile profile, Locale locale)
+ throws EProfileException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
String auditRequesterID = auditRequesterID(req);
@@ -648,16 +646,16 @@ public class ProfileProcessServlet extends ProfileServlet {
audit(auditMessage);
// } catch( EProfileException eAudit1 ) {
- // // store a message in the signed audit log file
- // auditMessage = CMS.getLogMessage(
- // LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED,
- // auditSubjectID,
- // ILogger.FAILURE,
- // auditRequesterID,
- // ILogger.SIGNED_AUDIT_REJECTION,
- // auditInfoValue );
+ // // store a message in the signed audit log file
+ // auditMessage = CMS.getLogMessage(
+ // LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED,
+ // auditSubjectID,
+ // ILogger.FAILURE,
+ // auditRequesterID,
+ // ILogger.SIGNED_AUDIT_REJECTION,
+ // auditInfoValue );
//
- // audit( auditMessage );
+ // audit( auditMessage );
// }
}
@@ -666,13 +664,14 @@ public class ProfileProcessServlet extends ProfileServlet {
* <P>
*
* (Certificate Request Processed - a manual "agent" profile based cert
- * acceptance)
+ * acceptance)
* <P>
*
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED used when a
* certificate request has just been through the approval process
* </ul>
+ *
* @param request the servlet request
* @param args argument set
* @param req the certificate request
@@ -680,12 +679,12 @@ public class ProfileProcessServlet extends ProfileServlet {
* @param profile this profile
* @param locale the system locale
* @exception EProfileException an error related to this profile has
- * occurred
+ * occurred
*/
- protected void approveRequest(ServletRequest request, ArgSet args,
- IRequest req,
- IRequestQueue queue, IProfile profile, Locale locale)
- throws EProfileException {
+ protected void approveRequest(ServletRequest request, ArgSet args,
+ IRequest req,
+ IRequestQueue queue, IProfile profile, Locale locale)
+ throws EProfileException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
String auditRequesterID = auditRequesterID(req);
@@ -709,33 +708,33 @@ public class ProfileProcessServlet extends ProfileServlet {
while (outputNames.hasMoreElements()) {
ArgSet outputset = new ArgSet();
String outputName =
- outputNames.nextElement();
+ outputNames.nextElement();
IDescriptor outputDesc =
- profileOutput.getValueDescriptor(locale,
- outputName);
+ profileOutput.getValueDescriptor(locale,
+ outputName);
if (outputDesc == null)
continue;
String outputSyntax = outputDesc.getSyntax();
String outputConstraint =
- outputDesc.getConstraint();
+ outputDesc.getConstraint();
String outputValueName =
- outputDesc.getDescription(locale);
+ outputDesc.getDescription(locale);
String outputValue = null;
try {
outputValue = profileOutput.getValue(
- outputName,
+ outputName,
locale, req);
} catch (EProfileException e) {
CMS.debug("ProfileSubmitServlet: " +
- e.toString());
+ e.toString());
}
outputset.set(ARG_OUTPUT_ID, outputName);
outputset.set(ARG_OUTPUT_SYNTAX, outputSyntax);
outputset.set(ARG_OUTPUT_CONSTRAINT,
- outputConstraint);
+ outputConstraint);
outputset.set(ARG_OUTPUT_NAME, outputValueName);
outputset.set(ARG_OUTPUT_VAL, outputValue);
outputlist.add(outputset);
@@ -775,13 +774,12 @@ public class ProfileProcessServlet extends ProfileServlet {
CMS.debug("ProfileProcessServlet: about to throw EProfileException because of bad profile execute.");
throw new EProfileException(eAudit1.toString());
-
}
}
- protected void updateValues(ServletRequest request, IRequest req,
- IRequestQueue queue, IProfile profile, Locale locale)
- throws ERejectException, EDeferException, EPropertyException {
+ protected void updateValues(ServletRequest request, IRequest req,
+ IRequestQueue queue, IProfile profile, Locale locale)
+ throws ERejectException, EDeferException, EPropertyException {
String profileSetId = req.getExtDataInString("profileSetId");
Enumeration policies = profile.getProfilePolicies(profileSetId);
@@ -813,17 +811,17 @@ public class ProfileProcessServlet extends ProfileServlet {
}
}
- protected void validate(Locale locale, int count,
- IProfilePolicy policy, IRequest req, ServletRequest request)
- throws ERejectException, EDeferException {
+ protected void validate(Locale locale, int count,
+ IProfilePolicy policy, IRequest req, ServletRequest request)
+ throws ERejectException, EDeferException {
IPolicyConstraint con = policy.getConstraint();
con.validate(req);
}
- protected void setValue(Locale locale, int count,
- IProfilePolicy policy, IRequest req, ServletRequest request)
- throws EPropertyException {
+ protected void setValue(Locale locale, int count,
+ IProfilePolicy policy, IRequest req, ServletRequest request)
+ throws EPropertyException {
// handle default policy
IPolicyDefault def = policy.getDefault();
Enumeration defNames = def.getValueNames();
@@ -838,11 +836,11 @@ public class ProfileProcessServlet extends ProfileServlet {
/**
* Signed Audit Log Requester ID
- *
- * This method is called to obtain the "RequesterID" for
- * a signed audit log message.
+ *
+ * This method is called to obtain the "RequesterID" for a signed audit log
+ * message.
* <P>
- *
+ *
* @param request the actual request
* @return id string containing the signed audit log message RequesterID
*/
@@ -868,11 +866,11 @@ public class ProfileProcessServlet extends ProfileServlet {
/**
* Signed Audit Log Info Value
- *
- * This method is called to obtain the "reason" for
- * a signed audit log message.
+ *
+ * This method is called to obtain the "reason" for a signed audit log
+ * message.
* <P>
- *
+ *
* @param request the actual request
* @return reason string containing the signed audit log message reason
*/
@@ -887,7 +885,7 @@ public class ProfileProcessServlet extends ProfileServlet {
if (request != null) {
// overwrite "reason" if and only if "info" != null
String info =
- request.getExtDataInString(SIGNED_AUDIT_CERT_REQUEST_REASON);
+ request.getExtDataInString(SIGNED_AUDIT_CERT_REQUEST_REASON);
if (info != null) {
reason = info.trim();
@@ -904,11 +902,11 @@ public class ProfileProcessServlet extends ProfileServlet {
/**
* Signed Audit Log Info Certificate Value
- *
+ *
* This method is called to obtain the certificate from the passed in
* "X509CertImpl" for a signed audit log message.
* <P>
- *
+ *
* @param x509cert an X509CertImpl
* @return cert string containing the certificate
*/
@@ -941,7 +939,7 @@ public class ProfileProcessServlet extends ProfileServlet {
// extract all line separators from the "base64Data"
StringBuffer sb = new StringBuffer();
for (int i = 0; i < base64Data.length(); i++) {
- if (!Character.isWhitespace(base64Data.charAt(i))) {
+ if (!Character.isWhitespace(base64Data.charAt(i))) {
sb.append(base64Data.charAt(i));
}
}
@@ -961,4 +959,3 @@ public class ProfileProcessServlet extends ProfileServlet {
}
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileReviewServlet.java b/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileReviewServlet.java
index 00840dd8..7ec8596f 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileReviewServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileReviewServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.profile;
-
import java.util.Enumeration;
import java.util.Locale;
import java.util.Random;
@@ -54,10 +53,9 @@ import com.netscape.certsrv.template.ArgList;
import com.netscape.certsrv.template.ArgSet;
import com.netscape.cms.servlet.common.CMSRequest;
-
/**
* This servlet allows reviewing of profile-based request.
- *
+ *
* @version $Revision$, $Date$
*/
public class ProfileReviewServlet extends ProfileServlet {
@@ -69,7 +67,7 @@ public class ProfileReviewServlet extends ProfileServlet {
private static final String PROP_AUTHORITY_ID = "authorityId";
- private String mAuthorityId = null;
+ private String mAuthorityId = null;
private Random mRandom = null;
private Nonces mNonces = null;
@@ -79,7 +77,7 @@ public class ProfileReviewServlet extends ProfileServlet {
/**
* initialize the servlet. This servlet uses the template file
* "ImportCert.template" to process the response.
- *
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -101,7 +99,7 @@ public class ProfileReviewServlet extends ProfileServlet {
* <ul>
* <li>http.param requestId the ID of the profile to review
* </ul>
- *
+ *
* @param cmsReq the object holding the request and response information
*/
public void process(CMSRequest cmsReq) throws EBaseException {
@@ -120,13 +118,13 @@ public class ProfileReviewServlet extends ProfileServlet {
} catch (EBaseException e) {
CMS.debug("ReviewReqServlet: " + e.toString());
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
- args.set(ARG_ERROR_CODE, "1");
- args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ args.set(ARG_ERROR_CODE, "1");
+ args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
"CMS_AUTHENTICATION_ERROR"));
outputTemplate(request, response, args);
return;
- }
+ }
}
AuthzToken authzToken = null;
@@ -136,15 +134,15 @@ public class ProfileReviewServlet extends ProfileServlet {
mAuthzResourceName, "read");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
- args.set(ARG_ERROR_CODE, "1");
- args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
+ args.set(ARG_ERROR_CODE, "1");
+ args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
"CMS_AUTHORIZATION_ERROR"));
outputTemplate(request, response, args);
return;
@@ -158,7 +156,7 @@ public class ProfileReviewServlet extends ProfileServlet {
}
CMS.debug("ProfileReviewServlet: SubId=" + mProfileSubId);
IProfileSubsystem ps = (IProfileSubsystem)
- CMS.getSubsystem(mProfileSubId);
+ CMS.getSubsystem(mProfileSubId);
if (ps == null) {
CMS.debug("ProfileReviewServlet: ProfileSubsystem not found");
@@ -174,7 +172,7 @@ public class ProfileReviewServlet extends ProfileServlet {
if (authority == null) {
CMS.debug("ProfileReviewServlet: Authority " + mAuthorityId +
- " not found");
+ " not found");
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
"CMS_INTERNAL_ERROR"));
@@ -185,7 +183,7 @@ public class ProfileReviewServlet extends ProfileServlet {
if (queue == null) {
CMS.debug("ProfileReviewServlet: Request Queue of " +
- mAuthorityId + " not found");
+ mAuthorityId + " not found");
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
"CMS_INTERNAL_ERROR"));
@@ -201,8 +199,8 @@ public class ProfileReviewServlet extends ProfileServlet {
req = queue.findRequest(new RequestId(requestId));
} catch (EBaseException e) {
// request not found
- CMS.debug("ProfileReviewServlet: request not found requestId=" +
- requestId + " " + e.toString());
+ CMS.debug("ProfileReviewServlet: request not found requestId=" +
+ requestId + " " + e.toString());
}
if (req == null) {
args.set(ARG_ERROR_CODE, "1");
@@ -214,16 +212,16 @@ public class ProfileReviewServlet extends ProfileServlet {
String profileId = req.getExtDataInString("profileId");
- CMS.debug("ProfileReviewServlet: requestId=" +
- requestId + " profileId=" + profileId);
+ CMS.debug("ProfileReviewServlet: requestId=" +
+ requestId + " profileId=" + profileId);
IProfile profile = null;
try {
profile = ps.getProfile(profileId);
} catch (EProfileException e) {
// profile not found
- CMS.debug("ProfileReviewServlet: profile not found requestId=" +
- requestId + " profileId=" + profileId + " " + e.toString());
+ CMS.debug("ProfileReviewServlet: profile not found requestId=" +
+ requestId + " profileId=" + profileId + " " + e.toString());
}
if (profile == null) {
args.set(ARG_ERROR_CODE, "1");
@@ -232,27 +230,27 @@ public class ProfileReviewServlet extends ProfileServlet {
outputTemplate(request, response, args);
return;
}
-
+
String profileSetId = req.getExtDataInString("profileSetId");
CMS.debug("ProfileReviewServlet: profileSetId=" + profileSetId);
- Enumeration policyIds = (profileSetId != null && profileSetId.length() > 0)?
- profile.getProfilePolicyIds(profileSetId): null;
+ Enumeration policyIds = (profileSetId != null && profileSetId.length() > 0) ?
+ profile.getProfilePolicyIds(profileSetId) : null;
int count = 0;
ArgList list = new ArgList();
if (policyIds != null) {
- while (policyIds.hasMoreElements()) {
+ while (policyIds.hasMoreElements()) {
String id = (String) policyIds.nextElement();
IProfilePolicy policy = (IProfilePolicy)
- profile.getProfilePolicy(req.getExtDataInString("profileSetId"),
- id);
+ profile.getProfilePolicy(req.getExtDataInString("profileSetId"),
+ id);
// (3) query all the profile policies
// (4) default plugins convert request parameters into string
- // http parameters
+ // http parameters
handlePolicy(list, response, locale,
- id, policy, req);
+ id, policy, req);
count++;
}
}
@@ -269,34 +267,34 @@ public class ProfileReviewServlet extends ProfileServlet {
args.set(ARG_REQUEST_TYPE, req.getRequestType());
args.set(ARG_REQUEST_STATUS, req.getRequestStatus().toString());
if (req.getRequestOwner() == null) {
- args.set(ARG_REQUEST_OWNER, "");
+ args.set(ARG_REQUEST_OWNER, "");
} else {
- args.set(ARG_REQUEST_OWNER, req.getRequestOwner());
+ args.set(ARG_REQUEST_OWNER, req.getRequestOwner());
}
args.set(ARG_REQUEST_CREATION_TIME, req.getCreationTime().toString());
- args.set(ARG_REQUEST_MODIFICATION_TIME,
- req.getModificationTime().toString());
+ args.set(ARG_REQUEST_MODIFICATION_TIME,
+ req.getModificationTime().toString());
args.set(ARG_PROFILE_ID, profileId);
- args.set(ARG_PROFILE_APPROVED_BY,
- req.getExtDataInString("profileApprovedBy"));
+ args.set(ARG_PROFILE_APPROVED_BY,
+ req.getExtDataInString("profileApprovedBy"));
args.set(ARG_PROFILE_SET_ID, req.getExtDataInString("profileSetId"));
if (profile.isVisible()) {
- args.set(ARG_PROFILE_IS_VISIBLE, "true");
+ args.set(ARG_PROFILE_IS_VISIBLE, "true");
} else {
- args.set(ARG_PROFILE_IS_VISIBLE, "false");
+ args.set(ARG_PROFILE_IS_VISIBLE, "false");
}
args.set(ARG_PROFILE_NAME, profile.getName(locale));
args.set(ARG_PROFILE_DESC, profile.getDescription(locale));
- args.set(ARG_PROFILE_REMOTE_HOST,
- req.getExtDataInString("profileRemoteHost"));
- args.set(ARG_PROFILE_REMOTE_ADDR,
- req.getExtDataInString("profileRemoteAddr"));
+ args.set(ARG_PROFILE_REMOTE_HOST,
+ req.getExtDataInString("profileRemoteHost"));
+ args.set(ARG_PROFILE_REMOTE_ADDR,
+ req.getExtDataInString("profileRemoteAddr"));
if (req.getExtDataInString("requestNotes") == null) {
args.set(ARG_REQUEST_NOTES, "");
} else {
- args.set(ARG_REQUEST_NOTES,
- req.getExtDataInString("requestNotes"));
+ args.set(ARG_REQUEST_NOTES,
+ req.getExtDataInString("requestNotes"));
}
args.set(ARG_RECORD, list);
@@ -358,7 +356,7 @@ public class ProfileReviewServlet extends ProfileServlet {
while (outputIds.hasMoreElements()) {
String outputId = (String) outputIds.nextElement();
IProfileOutput profileOutput = profile.getProfileOutput(outputId
- );
+ );
Enumeration outputNames = profileOutput.getValueNames();
@@ -366,9 +364,9 @@ public class ProfileReviewServlet extends ProfileServlet {
while (outputNames.hasMoreElements()) {
ArgSet outputset = new ArgSet();
String outputName = (String) outputNames.nextElement
- ();
+ ();
IDescriptor outputDesc =
- profileOutput.getValueDescriptor(locale, outputName);
+ profileOutput.getValueDescriptor(locale, outputName);
if (outputDesc == null)
continue;
@@ -382,7 +380,7 @@ public class ProfileReviewServlet extends ProfileServlet {
locale, req);
} catch (EProfileException e) {
CMS.debug("ProfileSubmitServlet: " + e.toString(
- ));
+ ));
}
outputset.set(ARG_OUTPUT_ID, outputName);
@@ -401,9 +399,9 @@ public class ProfileReviewServlet extends ProfileServlet {
outputTemplate(request, response, args);
}
- private void handlePolicy(ArgList list, ServletResponse response,
- Locale locale, String id, IProfilePolicy policy,
- IRequest req) {
+ private void handlePolicy(ArgList list, ServletResponse response,
+ Locale locale, String id, IProfilePolicy policy,
+ IRequest req) {
ArgSet set = new ArgSet();
set.set(ARG_POLICY_ID, id);
diff --git a/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileSelectServlet.java b/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileSelectServlet.java
index 813af8f6..d18336ae 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileSelectServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileSelectServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.profile;
-
import java.util.Enumeration;
import java.util.Locale;
@@ -48,10 +47,9 @@ import com.netscape.certsrv.template.ArgList;
import com.netscape.certsrv.template.ArgSet;
import com.netscape.cms.servlet.common.CMSRequest;
-
/**
* Retrieve detailed information of a particular profile.
- *
+ *
* @version $Revision$, $Date$
*/
public class ProfileSelectServlet extends ProfileServlet {
@@ -61,7 +59,7 @@ public class ProfileSelectServlet extends ProfileServlet {
*/
private static final long serialVersionUID = -3765390650830903602L;
private static final String PROP_AUTHORITY_ID = "authorityId";
- private String mAuthorityId = null;
+ private String mAuthorityId = null;
public ProfileSelectServlet() {
}
@@ -76,7 +74,7 @@ public class ProfileSelectServlet extends ProfileServlet {
* <ul>
* <li>http.param profileId the id of the profile to select
* </ul>
- *
+ *
* @param cmsReq the object holding the request and response information
*/
public void process(CMSRequest cmsReq) throws EBaseException {
@@ -96,7 +94,7 @@ public class ProfileSelectServlet extends ProfileServlet {
} catch (EBaseException e) {
CMS.debug("ProcessReqServlet: " + e.toString());
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
"CMS_AUTHENTICATION_ERROR"));
@@ -112,10 +110,10 @@ public class ProfileSelectServlet extends ProfileServlet {
mAuthzResourceName, "read");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -134,7 +132,7 @@ public class ProfileSelectServlet extends ProfileServlet {
}
CMS.debug("ProfileSelectServlet: SubId=" + mProfileSubId);
IProfileSubsystem ps = (IProfileSubsystem)
- CMS.getSubsystem(mProfileSubId);
+ CMS.getSubsystem(mProfileSubId);
if (ps == null) {
CMS.debug("ProfileSelectServlet: ProfileSubsystem not found");
@@ -150,7 +148,7 @@ public class ProfileSelectServlet extends ProfileServlet {
if (authority == null) {
CMS.debug("ProfileSelectServlet: Authority " + mAuthorityId +
- " not found");
+ " not found");
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
"CMS_INTERNAL_ERROR"));
@@ -161,7 +159,7 @@ public class ProfileSelectServlet extends ProfileServlet {
if (queue == null) {
CMS.debug("ProfileSelectServlet: Request Queue of " +
- mAuthorityId + " not found");
+ mAuthorityId + " not found");
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
"CMS_INTERNAL_ERROR"));
@@ -179,8 +177,8 @@ public class ProfileSelectServlet extends ProfileServlet {
profile = ps.getProfile(profileId);
} catch (EProfileException e) {
// profile not found
- CMS.debug("ProfileSelectServlet: profile not found profileId=" +
- profileId + " " + e.toString());
+ CMS.debug("ProfileSelectServlet: profile not found profileId=" +
+ profileId + " " + e.toString());
}
if (profile == null) {
args.set(ARG_ERROR_CODE, "1");
@@ -189,7 +187,7 @@ public class ProfileSelectServlet extends ProfileServlet {
outputTemplate(request, response, args);
return;
}
-
+
ArgList setlist = new ArgList();
Enumeration policySetIds = profile.getProfilePolicySetIds();
@@ -204,13 +202,14 @@ public class ProfileSelectServlet extends ProfileServlet {
while (policyIds.hasMoreElements()) {
String id = (String) policyIds.nextElement();
IProfilePolicy policy = (IProfilePolicy)
- profile.getProfilePolicy(setId, id);
+ profile.getProfilePolicy(setId, id);
// (3) query all the profile policies
- // (4) default plugins convert request parameters into string
- // http parameters
+ // (4) default plugins convert request parameters into
+ // string
+ // http parameters
handlePolicy(list, response, locale,
- id, policy);
+ id, policy);
}
}
ArgSet setArg = new ArgSet();
@@ -224,29 +223,29 @@ public class ProfileSelectServlet extends ProfileServlet {
args.set(ARG_PROFILE_ID, profileId);
args.set(ARG_PROFILE_IS_ENABLED,
- Boolean.toString(ps.isProfileEnable(profileId)));
+ Boolean.toString(ps.isProfileEnable(profileId)));
args.set(ARG_PROFILE_ENABLED_BY, ps.getProfileEnableBy(profileId));
args.set(ARG_PROFILE_NAME, profile.getName(locale));
- args.set(ARG_PROFILE_DESC, profile.getDescription(locale));
- args.set(ARG_PROFILE_IS_VISIBLE,
- Boolean.toString(profile.isVisible()));
+ args.set(ARG_PROFILE_DESC, profile.getDescription(locale));
+ args.set(ARG_PROFILE_IS_VISIBLE,
+ Boolean.toString(profile.isVisible()));
args.set(ARG_ERROR_CODE, "0");
args.set(ARG_ERROR_REASON, "");
try {
- boolean keyArchivalEnabled = CMS.getConfigStore().getBoolean("ca.connector.KRA.enable", false);
- if (keyArchivalEnabled == true) {
- CMS.debug("ProfileSelectServlet: keyArchivalEnabled is true");
-
- // output transport certificate if present
- args.set("transportCert",
- CMS.getConfigStore().getString("ca.connector.KRA.transportCert", ""));
- } else {
- CMS.debug("ProfileSelectServlet: keyArchivalEnabled is false");
- args.set("transportCert", "");
- }
+ boolean keyArchivalEnabled = CMS.getConfigStore().getBoolean("ca.connector.KRA.enable", false);
+ if (keyArchivalEnabled == true) {
+ CMS.debug("ProfileSelectServlet: keyArchivalEnabled is true");
+
+ // output transport certificate if present
+ args.set("transportCert",
+ CMS.getConfigStore().getString("ca.connector.KRA.transportCert", ""));
+ } else {
+ CMS.debug("ProfileSelectServlet: keyArchivalEnabled is false");
+ args.set("transportCert", "");
+ }
} catch (EBaseException e) {
- CMS.debug("ProfileSelectServlet: exception caught:"+e.toString());
+ CMS.debug("ProfileSelectServlet: exception caught:" + e.toString());
}
// build authentication
@@ -259,7 +258,7 @@ public class ProfileSelectServlet extends ProfileServlet {
// authenticator not installed correctly
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
- "CMS_AUTHENTICATION_MANAGER_NOT_FOUND",
+ "CMS_AUTHENTICATION_MANAGER_NOT_FOUND",
profile.getAuthenticatorId()));
outputTemplate(request, response, args);
return;
@@ -272,8 +271,8 @@ public class ProfileSelectServlet extends ProfileServlet {
while (authNames.hasMoreElements()) {
ArgSet authset = new ArgSet();
String authName = (String) authNames.nextElement();
- IDescriptor authDesc =
- authenticator.getValueDescriptor(locale, authName);
+ IDescriptor authDesc =
+ authenticator.getValueDescriptor(locale, authName);
if (authDesc == null)
continue;
@@ -291,8 +290,8 @@ public class ProfileSelectServlet extends ProfileServlet {
args.set(ARG_AUTH_LIST, authlist);
args.set(ARG_AUTH_NAME, authenticator.getName(locale));
args.set(ARG_AUTH_DESC, authenticator.getText(locale));
- args.set(ARG_AUTH_IS_SSL,
- Boolean.toString(authenticator.isSSLClientRequired()));
+ args.set(ARG_AUTH_IS_SSL,
+ Boolean.toString(authenticator.isSSLClientRequired()));
}
// build input list
@@ -309,10 +308,10 @@ public class ProfileSelectServlet extends ProfileServlet {
ArgSet inputpluginset = new ArgSet();
inputpluginset.set(ARG_INPUT_PLUGIN_ID, inputId);
- inputpluginset.set(ARG_INPUT_PLUGIN_NAME,
- profileInput.getName(locale));
- inputpluginset.set(ARG_INPUT_PLUGIN_DESC,
- profileInput.getText(locale));
+ inputpluginset.set(ARG_INPUT_PLUGIN_NAME,
+ profileInput.getName(locale));
+ inputpluginset.set(ARG_INPUT_PLUGIN_DESC,
+ profileInput.getText(locale));
inputPluginlist.add(inputpluginset);
Enumeration inputNames = profileInput.getValueNames();
@@ -352,8 +351,8 @@ public class ProfileSelectServlet extends ProfileServlet {
outputTemplate(request, response, args);
}
- private void handlePolicy(ArgList list, ServletResponse response,
- Locale locale, String id, IProfilePolicy policy) {
+ private void handlePolicy(ArgList list, ServletResponse response,
+ Locale locale, String id, IProfilePolicy policy) {
ArgSet set = new ArgSet();
set.set(ARG_POLICY_ID, id);
diff --git a/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileServlet.java b/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileServlet.java
index 46f3797d..37f501b4 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.profile;
-
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileReader;
@@ -46,10 +45,9 @@ import com.netscape.cms.servlet.base.UserInfo;
import com.netscape.cms.servlet.common.CMSRequest;
import com.netscape.cms.servlet.common.Utils;
-
/**
* This servlet is the base class of all profile servlets.
- *
+ *
* @version $Revision$, $Date$
*/
public class ProfileServlet extends CMSServlet {
@@ -67,12 +65,12 @@ public class ProfileServlet extends CMSServlet {
public final static String ARG_REQUEST_ID = "requestId";
public final static String ARG_REQUEST_TYPE = "requestType";
public final static String ARG_REQUEST_STATUS = "requestStatus";
- public final static String ARG_REQUEST_OWNER =
- "requestOwner";
- public final static String ARG_REQUEST_CREATION_TIME =
- "requestCreationTime";
- public final static String ARG_REQUEST_MODIFICATION_TIME =
- "requestModificationTime";
+ public final static String ARG_REQUEST_OWNER =
+ "requestOwner";
+ public final static String ARG_REQUEST_CREATION_TIME =
+ "requestCreationTime";
+ public final static String ARG_REQUEST_MODIFICATION_TIME =
+ "requestModificationTime";
public final static String ARG_REQUEST_NONCE = "nonce";
public final static String ARG_AUTH_ID = "authId";
@@ -166,15 +164,15 @@ public class ProfileServlet extends CMSServlet {
super();
}
- /**
- * initialize the servlet. Servlets implementing this method
- * must specify the template to use as a parameter called
- * "templatePath" in the servletConfig
- *
+ /**
+ * initialize the servlet. Servlets implementing this method must specify
+ * the template to use as a parameter called "templatePath" in the
+ * servletConfig
+ *
* @param sc servlet configuration, read from the web.xml file
*/
- public void init(ServletConfig sc) throws ServletException {
+ public void init(ServletConfig sc) throws ServletException {
super.init(sc);
mTemplate = sc.getServletContext().getRealPath(
sc.getInitParameter(PROP_TEMPLATE));
@@ -193,47 +191,44 @@ public class ProfileServlet extends CMSServlet {
}
}
- protected String escapeXML(String v)
- {
- if (v == null) {
- return "";
- }
- v = v.replaceAll("&", "&amp;");
- return v;
+ protected String escapeXML(String v) {
+ if (v == null) {
+ return "";
+ }
+ v = v.replaceAll("&", "&amp;");
+ return v;
}
- protected void outputArgValueAsXML(PrintStream ps, String name, IArgValue v)
- {
- ps.println("<" + name + ">");
- if (v != null) {
- if (v instanceof ArgList) {
- ArgList list = (ArgList)v;
- ps.println("<list>");
- for (int i = 0; i < list.size(); i++) {
- outputArgValueAsXML(ps, name, list.get(i));
- }
- ps.println("</list>");
- } else if (v instanceof ArgString) {
- ArgString str = (ArgString)v;
- ps.println(escapeXML(str.getValue()));
- } else if (v instanceof ArgSet) {
- ArgSet set = (ArgSet)v;
- ps.println("<set>");
- Enumeration names = set.getNames();
- while (names.hasMoreElements()) {
- String n = (String)names.nextElement();
+ protected void outputArgValueAsXML(PrintStream ps, String name, IArgValue v) {
+ ps.println("<" + name + ">");
+ if (v != null) {
+ if (v instanceof ArgList) {
+ ArgList list = (ArgList) v;
+ ps.println("<list>");
+ for (int i = 0; i < list.size(); i++) {
+ outputArgValueAsXML(ps, name, list.get(i));
+ }
+ ps.println("</list>");
+ } else if (v instanceof ArgString) {
+ ArgString str = (ArgString) v;
+ ps.println(escapeXML(str.getValue()));
+ } else if (v instanceof ArgSet) {
+ ArgSet set = (ArgSet) v;
+ ps.println("<set>");
+ Enumeration names = set.getNames();
+ while (names.hasMoreElements()) {
+ String n = (String) names.nextElement();
outputArgValueAsXML(ps, n, set.get(n));
- }
- ps.println("</set>");
- } else {
- ps.println(v);
- }
+ }
+ ps.println("</set>");
+ } else {
+ ps.println(v);
}
- ps.println("</" + name + ">");
+ }
+ ps.println("</" + name + ">");
}
- protected void outputThisAsXML(ByteArrayOutputStream bos, ArgSet args)
- {
+ protected void outputThisAsXML(ByteArrayOutputStream bos, ArgSet args) {
PrintStream ps = new PrintStream(bos);
ps.println("<xml>");
outputArgValueAsXML(ps, "output", args);
@@ -241,9 +236,9 @@ public class ProfileServlet extends CMSServlet {
ps.flush();
}
- public void outputTemplate(HttpServletRequest request,
+ public void outputTemplate(HttpServletRequest request,
HttpServletResponse response, ArgSet args)
- throws EBaseException {
+ throws EBaseException {
String xmlOutput = request.getParameter("xml");
if (xmlOutput != null && xmlOutput.equals("true")) {
@@ -251,32 +246,31 @@ public class ProfileServlet extends CMSServlet {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
outputThisAsXML(bos, args);
try {
- response.setContentLength(bos.size());
- bos.writeTo(response.getOutputStream());
+ response.setContentLength(bos.size());
+ bos.writeTo(response.getOutputStream());
} catch (Exception e) {
CMS.debug("outputTemplate error " + e);
}
return;
}
- IStatsSubsystem statsSub = (IStatsSubsystem)CMS.getSubsystem("stats");
+ IStatsSubsystem statsSub = (IStatsSubsystem) CMS.getSubsystem("stats");
if (statsSub != null) {
- statsSub.startTiming("output_template");
+ statsSub.startTiming("output_template");
}
BufferedReader reader = null;
try {
reader = new BufferedReader(
- new FileReader(mTemplate));
+ new FileReader(mTemplate));
response.setContentType("text/html; charset=UTF-8");
PrintWriter writer = response.getWriter();
-
// output template
String line = null;
do {
- line = reader.readLine();
+ line = reader.readLine();
if (line != null) {
if (line.indexOf("<CMS_TEMPLATE>") == -1) {
writer.println(line);
@@ -287,21 +281,20 @@ public class ProfileServlet extends CMSServlet {
writer.println("</script>");
}
}
- }
- while (line != null);
+ } while (line != null);
reader.close();
} catch (IOException e) {
- CMS.debug(e);
- throw new EBaseException(e.toString());
+ CMS.debug(e);
+ throw new EBaseException(e.toString());
} finally {
- if (statsSub != null) {
- statsSub.endTiming("output_template");
- }
+ if (statsSub != null) {
+ statsSub.endTiming("output_template");
+ }
}
}
protected void outputArgList(PrintWriter writer, String name, ArgList list)
- throws IOException {
+ throws IOException {
String h_name = null;
@@ -311,7 +304,7 @@ public class ProfileServlet extends CMSServlet {
h_name = name.substring(name.indexOf('.') + 1);
}
writer.println(name + "Set = new Array;");
- // writer.println(h_name + "Count = 0;");
+ // writer.println(h_name + "Count = 0;");
for (int i = 0; i < list.size(); i++) {
writer.println(h_name + " = new Object;");
@@ -342,27 +335,27 @@ public class ProfileServlet extends CMSServlet {
char c = in[i];
/* presumably this gives better performance */
- if ((c > 0x23) && (c!= 0x5c) && (c!= 0x3c) && (c!= 0x3e)) {
+ if ((c > 0x23) && (c != 0x5c) && (c != 0x3c) && (c != 0x3e)) {
out[j++] = c;
continue;
}
/* some inputs are coming in as '\' and 'n' */
/* see BZ 500736 for details */
- if ((c == 0x5c) && ((i+1)<l) && (in[i+1] == 'n' ||
- in[i+1] == 'r' || in[i+1] == 'f' || in[i+1] == 't' ||
- in[i+1] == '<' || in[i+1] == '>' ||
- in[i+1] == '\"' || in[i+1] == '\'' || in[i+1] == '\\')) {
- if (in[i+1] == 'x' && ((i+3)<l) && in[i+2] == '3' &&
- (in[i+3] == 'c' || in[i+3] == 'e')) {
+ if ((c == 0x5c) && ((i + 1) < l) && (in[i + 1] == 'n' ||
+ in[i + 1] == 'r' || in[i + 1] == 'f' || in[i + 1] == 't' ||
+ in[i + 1] == '<' || in[i + 1] == '>' ||
+ in[i + 1] == '\"' || in[i + 1] == '\'' || in[i + 1] == '\\')) {
+ if (in[i + 1] == 'x' && ((i + 3) < l) && in[i + 2] == '3' &&
+ (in[i + 3] == 'c' || in[i + 3] == 'e')) {
out[j++] = '\\';
- out[j++] = in[i+1];
- out[j++] = in[i+2];
- out[j++] = in[i+3];
+ out[j++] = in[i + 1];
+ out[j++] = in[i + 2];
+ out[j++] = in[i + 3];
i += 3;
- } else {
+ } else {
out[j++] = '\\';
- out[j++] = in[i+1];
+ out[j++] = in[i + 1];
i++;
}
continue;
@@ -421,18 +414,18 @@ public class ProfileServlet extends CMSServlet {
}
protected void outputArgString(PrintWriter writer, String name, ArgString str)
- throws IOException {
+ throws IOException {
String s = str.getValue();
// sub \n with "\n"
if (s != null) {
- s = escapeJavaScriptString(s);
+ s = escapeJavaScriptString(s);
}
writer.println(name + "=\"" + s + "\";");
}
protected void outputArgSet(PrintWriter writer, String name, ArgSet set)
- throws IOException {
+ throws IOException {
Enumeration e = set.getNames();
while (e.hasMoreElements()) {
@@ -456,7 +449,7 @@ public class ProfileServlet extends CMSServlet {
}
protected void outputData(PrintWriter writer, ArgSet set)
- throws IOException {
+ throws IOException {
if (set == null)
return;
Enumeration e = set.getNames();
@@ -486,12 +479,12 @@ public class ProfileServlet extends CMSServlet {
*/
protected void log(int event, int level, String msg) {
mLogger.log(event, mLogCategory, level,
- "Servlet " + mId + ": " + msg);
+ "Servlet " + mId + ": " + msg);
}
protected void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM, mLogCategory, level,
- "Servlet " + mId + ": " + msg);
+ "Servlet " + mId + ": " + msg);
}
/**
@@ -512,8 +505,7 @@ public class ProfileServlet extends CMSServlet {
}
protected void renderResult(CMSRequest cmsReq)
- throws IOException {
+ throws IOException {
// do nothing
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileSubmitCMCServlet.java b/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileSubmitCMCServlet.java
index b00b13a9..d7dcb8ad 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileSubmitCMCServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileSubmitCMCServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.profile;
-
import java.io.InputStream;
import java.io.OutputStream;
import java.security.cert.CertificateEncodingException;
@@ -65,10 +64,9 @@ import com.netscape.cms.servlet.common.AuthCredentials;
import com.netscape.cms.servlet.common.CMCOutputTemplate;
import com.netscape.cms.servlet.common.CMSRequest;
-
/**
* This servlet submits end-user request into the profile framework.
- *
+ *
* @version $Revision$, $Date$
*/
public class ProfileSubmitCMCServlet extends ProfileServlet {
@@ -89,27 +87,26 @@ public class ProfileSubmitCMCServlet extends ProfileServlet {
private String requestBinary = null;
private String requestB64 = null;
- private final static String[]
- SIGNED_AUDIT_AUTOMATED_REJECTION_REASON = new String[] {
-
- /* 0 */ "automated profile cert request rejection: "
+ private final static String[] SIGNED_AUDIT_AUTOMATED_REJECTION_REASON = new String[] {
+
+ /* 0 */"automated profile cert request rejection: "
+ "indeterminate reason for inability to process "
+ "cert request due to an EBaseException"
};
private final static String LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED =
- "LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED_5";
+ "LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED_5";
public ProfileSubmitCMCServlet() {
}
/**
- * initialize the servlet. And instance of this servlet can
- * be set up to always issue certificates against a certain profile
- * by setting the 'profileId' configuration in the servletConfig
- * If not, the user must specify the profileID when submitting the request
+ * initialize the servlet. And instance of this servlet can be set up to
+ * always issue certificates against a certain profile by setting the
+ * 'profileId' configuration in the servletConfig If not, the user must
+ * specify the profileID when submitting the request
*
* "ImportCert.template" to process the response.
- *
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -158,7 +155,7 @@ public class ProfileSubmitCMCServlet extends ProfileServlet {
}
public IAuthToken authenticate(IProfileAuthenticator authenticator,
- HttpServletRequest request) throws EBaseException {
+ HttpServletRequest request) throws EBaseException {
AuthCredentials credentials = new AuthCredentials();
// build credential
@@ -177,19 +174,19 @@ public class ProfileSubmitCMCServlet extends ProfileServlet {
IAuthToken authToken = authenticator.authenticate(credentials);
SessionContext sc = SessionContext.getContext();
- if (sc != null) {
- sc.put(SessionContext.AUTH_MANAGER_ID, authenticator.getName());
- String userid = authToken.getInString(IAuthToken.USER_ID);
- if (userid != null) {
- sc.put(SessionContext.USER_ID, userid);
- }
+ if (sc != null) {
+ sc.put(SessionContext.AUTH_MANAGER_ID, authenticator.getName());
+ String userid = authToken.getInString(IAuthToken.USER_ID);
+ if (userid != null) {
+ sc.put(SessionContext.USER_ID, userid);
+ }
}
return authToken;
}
private void setInputsIntoRequest(HttpServletRequest request, IProfile
-profile, IRequest req) {
+ profile, IRequest req) {
Enumeration inputIds = profile.getProfileInputIds();
if (inputIds != null) {
@@ -216,7 +213,7 @@ profile, IRequest req) {
* <P>
*
* (Certificate Request Processed - either an automated "EE" profile based
- * cert acceptance, or an automated "EE" profile based cert rejection)
+ * cert acceptance, or an automated "EE" profile based cert rejection)
* <P>
*
* <ul>
@@ -224,6 +221,7 @@ profile, IRequest req) {
* <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED used when a
* certificate request has just been through the approval process
* </ul>
+ *
* @param cmsReq the object holding the request and response information
* @exception EBaseException an error has occurred
*/
@@ -233,8 +231,8 @@ profile, IRequest req) {
Locale locale = getLocale(request);
ArgSet args = new ArgSet();
- String cert_request_type =
- mServletConfig.getInitParameter("cert_request_type");
+ String cert_request_type =
+ mServletConfig.getInitParameter("cert_request_type");
String outputFormat = mServletConfig.getInitParameter("outputFormat");
int reqlen = request.getContentLength();
@@ -268,29 +266,29 @@ profile, IRequest req) {
while (paramNames.hasMoreElements()) {
String paramName = (String) paramNames.nextElement();
// added this facility so that password can be hidden,
- // all sensitive parameters should be prefixed with
+ // all sensitive parameters should be prefixed with
// __ (double underscores); however, in the event that
// a security parameter slips through, we perform multiple
// additional checks to insure that it is NOT displayed
- if( paramName.startsWith("__") ||
- paramName.endsWith("password") ||
- paramName.endsWith("passwd") ||
- paramName.endsWith("pwd") ||
- paramName.equalsIgnoreCase("admin_password_again") ||
- paramName.equalsIgnoreCase("directoryManagerPwd") ||
- paramName.equalsIgnoreCase("bindpassword") ||
- paramName.equalsIgnoreCase("bindpwd") ||
- paramName.equalsIgnoreCase("passwd") ||
- paramName.equalsIgnoreCase("password") ||
- paramName.equalsIgnoreCase("pin") ||
- paramName.equalsIgnoreCase("pwd") ||
- paramName.equalsIgnoreCase("pwdagain") ||
- paramName.equalsIgnoreCase("uPasswd") ) {
+ if (paramName.startsWith("__") ||
+ paramName.endsWith("password") ||
+ paramName.endsWith("passwd") ||
+ paramName.endsWith("pwd") ||
+ paramName.equalsIgnoreCase("admin_password_again") ||
+ paramName.equalsIgnoreCase("directoryManagerPwd") ||
+ paramName.equalsIgnoreCase("bindpassword") ||
+ paramName.equalsIgnoreCase("bindpwd") ||
+ paramName.equalsIgnoreCase("passwd") ||
+ paramName.equalsIgnoreCase("password") ||
+ paramName.equalsIgnoreCase("pin") ||
+ paramName.equalsIgnoreCase("pwd") ||
+ paramName.equalsIgnoreCase("pwdagain") ||
+ paramName.equalsIgnoreCase("uPasswd")) {
CMS.debug("ProfileSubmitCMCServlet Input Parameter " +
paramName + "='(sensitive)'");
} else {
CMS.debug("ProfileSubmitCMCServlet Input Parameter " +
- paramName + "='" +
+ paramName + "='" +
request.getParameter(paramName) + "'");
}
}
@@ -303,8 +301,8 @@ profile, IRequest req) {
mProfileSubId = IProfileSubsystem.ID;
}
CMS.debug("ProfileSubmitCMCServlet: SubId=" + mProfileSubId);
- IProfileSubsystem ps = (IProfileSubsystem)
- CMS.getSubsystem(mProfileSubId);
+ IProfileSubsystem ps = (IProfileSubsystem)
+ CMS.getSubsystem(mProfileSubId);
if (ps == null) {
CMS.debug("ProfileSubmitCMCServlet: ProfileSubsystem not found");
@@ -317,7 +315,7 @@ profile, IRequest req) {
} catch (Exception ee) {
}
template.createFullResponseWithFailedStatus(response, seq,
- OtherInfo.INTERNAL_CA_ERROR, s);
+ OtherInfo.INTERNAL_CA_ERROR, s);
return;
}
@@ -331,14 +329,14 @@ profile, IRequest req) {
profileId = mProfileId;
}
- IProfile profile = null;
+ IProfile profile = null;
- try {
+ try {
CMS.debug("ProfileSubmitCMCServlet: profileId " + profileId);
- profile = ps.getProfile(profileId);
- } catch (EProfileException e) {
- CMS.debug("ProfileSubmitCMCServlet: profile not found profileId " +
- profileId + " " + e.toString());
+ profile = ps.getProfile(profileId);
+ } catch (EProfileException e) {
+ CMS.debug("ProfileSubmitCMCServlet: profile not found profileId " +
+ profileId + " " + e.toString());
}
if (profile == null) {
CMCOutputTemplate template = new CMCOutputTemplate();
@@ -350,13 +348,13 @@ profile, IRequest req) {
} catch (Exception ee) {
}
template.createFullResponseWithFailedStatus(response, seq,
- OtherInfo.INTERNAL_CA_ERROR, s);
+ OtherInfo.INTERNAL_CA_ERROR, s);
return;
}
if (!ps.isProfileEnable(profileId)) {
- CMS.debug("ProfileSubmitCMCServlet: Profile " + profileId +
- " not enabled");
+ CMS.debug("ProfileSubmitCMCServlet: Profile " + profileId +
+ " not enabled");
CMCOutputTemplate template = new CMCOutputTemplate();
SEQUENCE seq = new SEQUENCE();
seq.addElement(new INTEGER(0));
@@ -366,7 +364,7 @@ profile, IRequest req) {
} catch (Exception ee) {
}
template.createFullResponseWithFailedStatus(response, seq,
- OtherInfo.INTERNAL_CA_ERROR, s);
+ OtherInfo.INTERNAL_CA_ERROR, s);
return;
}
@@ -386,8 +384,8 @@ profile, IRequest req) {
if (authenticator == null) {
CMS.debug("ProfileSubmitCMCServlet: authenticator not found");
} else {
- CMS.debug("ProfileSubmitCMCServlet: authenticator " +
- authenticator.getName() + " found");
+ CMS.debug("ProfileSubmitCMCServlet: authenticator " +
+ authenticator.getName() + " found");
setCredentialsIntoContext(request, authenticator, ctx);
}
@@ -403,39 +401,39 @@ profile, IRequest req) {
SessionContext context = SessionContext.getContext();
// insert profile context so that input parameter can be retrieved
- context.put("profileContext", ctx);
- context.put("sslClientCertProvider",
- new SSLClientCertProvider(request));
+ context.put("profileContext", ctx);
+ context.put("sslClientCertProvider",
+ new SSLClientCertProvider(request));
CMS.debug("ProfileSubmitCMCServlet: set sslClientCertProvider");
- if (authenticator != null) {
+ if (authenticator != null) {
try {
authToken = authenticate(authenticator, request);
// authentication success
} catch (EBaseException e) {
CMCOutputTemplate template = new CMCOutputTemplate();
SEQUENCE seq = new SEQUENCE();
- seq.addElement(new INTEGER(0));
+ seq.addElement(new INTEGER(0));
UTF8String s = null;
try {
- s = new UTF8String(e.toString());
+ s = new UTF8String(e.toString());
} catch (Exception ee) {
}
- template.createFullResponseWithFailedStatus(response, seq,
- OtherInfo.BAD_REQUEST, s);
- CMS.debug("ProfileSubmitCMCServlet: authentication error " +
- e.toString());
+ template.createFullResponseWithFailedStatus(response, seq,
+ OtherInfo.BAD_REQUEST, s);
+ CMS.debug("ProfileSubmitCMCServlet: authentication error " +
+ e.toString());
return;
}
- //authorization only makes sense when request is authenticated
+ // authorization only makes sense when request is authenticated
AuthzToken authzToken = null;
if (authToken != null) {
CMS.debug("ProfileSubmitCMCServlet authToken not null");
try {
authzToken = authorize(mAclMethod, authToken,
- mAuthzResourceName, "submit");
+ mAuthzResourceName, "submit");
} catch (Exception e) {
- CMS.debug("ProfileSubmitCMCServlet authorization failure: "+e.toString());
+ CMS.debug("ProfileSubmitCMCServlet authorization failure: " + e.toString());
}
}
@@ -450,16 +448,16 @@ profile, IRequest req) {
} catch (Exception ee) {
}
template.createFullResponseWithFailedStatus(response, seq,
- OtherInfo.BAD_REQUEST, s);
+ OtherInfo.BAD_REQUEST, s);
return;
}
}
IRequest reqs[] = null;
- ///////////////////////////////////////////////
+ // /////////////////////////////////////////////
// create request
- ///////////////////////////////////////////////
+ // /////////////////////////////////////////////
try {
reqs = profile.createRequests(ctx, locale);
} catch (EProfileException e) {
@@ -473,7 +471,7 @@ profile, IRequest req) {
} catch (Exception ee) {
}
template.createFullResponseWithFailedStatus(response, seq,
- OtherInfo.INTERNAL_CA_ERROR, s);
+ OtherInfo.INTERNAL_CA_ERROR, s);
return;
} catch (Throwable e) {
CMS.debug("ProfileSubmitCMCServlet: createRequests " + e.toString());
@@ -486,17 +484,17 @@ profile, IRequest req) {
} catch (Exception ee) {
}
template.createFullResponseWithFailedStatus(response, seq,
- OtherInfo.INTERNAL_CA_ERROR, s);
+ OtherInfo.INTERNAL_CA_ERROR, s);
return;
}
TaggedAttribute attr =
- (TaggedAttribute)(context.get(OBJECT_IDENTIFIER.id_cmc_lraPOPWitness));
+ (TaggedAttribute) (context.get(OBJECT_IDENTIFIER.id_cmc_lraPOPWitness));
if (attr != null) {
boolean verifyAllow = true;
try {
verifyAllow = CMS.getConfigStore().getBoolean(
- "cmc.lraPopWitness.verify.allow", true);
+ "cmc.lraPopWitness.verify.allow", true);
} catch (EBaseException ee) {
}
@@ -505,18 +503,18 @@ profile, IRequest req) {
SET vals = attr.getValues();
if (vals.size() > 0) {
try {
- lraPop = (LraPopWitness)(ASN1Util.decode(LraPopWitness.getTemplate(),
- ASN1Util.encode(vals.elementAt(0))));
+ lraPop = (LraPopWitness) (ASN1Util.decode(LraPopWitness.getTemplate(),
+ ASN1Util.encode(vals.elementAt(0))));
} catch (InvalidBERException e) {
CMS.debug(
- CMS.getUserMessage(locale, "CMS_PROFILE_ENCODING_ERROR"));
+ CMS.getUserMessage(locale, "CMS_PROFILE_ENCODING_ERROR"));
}
SEQUENCE bodyIds = lraPop.getBodyIds();
CMCOutputTemplate template = new CMCOutputTemplate();
template.createFullResponseWithFailedStatus(response, bodyIds,
- OtherInfo.POP_FAILED, null);
+ OtherInfo.POP_FAILED, null);
return;
}
}
@@ -524,53 +522,53 @@ profile, IRequest req) {
// for CMC, requests may be zero. Then check if controls exist.
if (reqs == null) {
- Integer nums = (Integer)(context.get("numOfControls"));
+ Integer nums = (Integer) (context.get("numOfControls"));
CMCOutputTemplate template = new CMCOutputTemplate();
// if there is only one control GetCert, then simple response
- // must be returned.
+ // must be returned.
if (nums != null && nums.intValue() == 1) {
- TaggedAttribute attr1 = (TaggedAttribute)(context.get(OBJECT_IDENTIFIER.id_cmc_getCert));
+ TaggedAttribute attr1 = (TaggedAttribute) (context.get(OBJECT_IDENTIFIER.id_cmc_getCert));
if (attr1 != null) {
template.createSimpleResponse(response, reqs);
} else
- template.createFullResponse(response, reqs,
- cert_request_type, null);
+ template.createFullResponse(response, reqs,
+ cert_request_type, null);
} else
- template.createFullResponse(response, reqs,
- cert_request_type, null);
+ template.createFullResponse(response, reqs,
+ cert_request_type, null);
return;
}
String errorCode = null;
- String errorReason = null;
+ String errorReason = null;
- ///////////////////////////////////////////////
+ // /////////////////////////////////////////////
// populate request
- ///////////////////////////////////////////////
+ // /////////////////////////////////////////////
for (int k = 0; k < reqs.length; k++) {
// adding parameters to request
setInputsIntoRequest(request, profile, reqs[k]);
// serial auth token into request
if (authToken != null) {
- Enumeration tokenNames = authToken.getElements();
- while (tokenNames.hasMoreElements()) {
- String tokenName = (String)tokenNames.nextElement();
- String[] vals = authToken.getInStringArray(tokenName);
- if (vals != null) {
- for (int i = 0; i < vals.length; i++) {
- reqs[k].setExtData(ARG_AUTH_TOKEN + "." +
- tokenName + "[" + i + "]", vals[i]);
- }
- } else {
- String val = authToken.getInString(tokenName);
- if (val != null) {
- reqs[k].setExtData(ARG_AUTH_TOKEN + "." + tokenName,
- val);
- }
- }
- }
- }
+ Enumeration tokenNames = authToken.getElements();
+ while (tokenNames.hasMoreElements()) {
+ String tokenName = (String) tokenNames.nextElement();
+ String[] vals = authToken.getInStringArray(tokenName);
+ if (vals != null) {
+ for (int i = 0; i < vals.length; i++) {
+ reqs[k].setExtData(ARG_AUTH_TOKEN + "." +
+ tokenName + "[" + i + "]", vals[i]);
+ }
+ } else {
+ String val = authToken.getInString(tokenName);
+ if (val != null) {
+ reqs[k].setExtData(ARG_AUTH_TOKEN + "." + tokenName,
+ val);
+ }
+ }
+ }
+ }
// put profile framework parameters into the request
reqs[k].setExtData(ARG_PROFILE, "true");
@@ -589,7 +587,7 @@ profile, IRequest req) {
} catch (Exception ee) {
}
template.createFullResponseWithFailedStatus(response, seq,
- OtherInfo.INTERNAL_CA_ERROR, s);
+ OtherInfo.INTERNAL_CA_ERROR, s);
return;
}
@@ -598,13 +596,13 @@ profile, IRequest req) {
reqs[k].setExtData(ARG_PROFILE_REMOTE_HOST, request.getRemoteHost());
reqs[k].setExtData(ARG_PROFILE_REMOTE_ADDR, request.getRemoteAddr());
- CMS.debug("ProfileSubmitCMCServlet: request " +
- reqs[k].getRequestId().toString());
+ CMS.debug("ProfileSubmitCMCServlet: request " +
+ reqs[k].getRequestId().toString());
try {
CMS.debug("ProfileSubmitCMCServlet: populating request inputs");
// give authenticator a chance to populate the request
- if (authenticator != null) {
+ if (authenticator != null) {
authenticator.populate(authToken, reqs[k]);
}
profile.populateInput(ctx, reqs[k]);
@@ -620,12 +618,12 @@ profile, IRequest req) {
} catch (Exception ee) {
}
template.createFullResponseWithFailedStatus(response, seq,
- OtherInfo.BAD_REQUEST, s);
+ OtherInfo.BAD_REQUEST, s);
return;
} catch (Throwable e) {
CMS.debug("ProfileSubmitCMCServlet: populate " + e.toString());
- // throw new IOException("Profile " + profileId +
- // " cannot populate");
+ // throw new IOException("Profile " + profileId +
+ // " cannot populate");
CMCOutputTemplate template = new CMCOutputTemplate();
SEQUENCE seq = new SEQUENCE();
seq.addElement(new INTEGER(0));
@@ -635,7 +633,7 @@ profile, IRequest req) {
} catch (Exception ee) {
}
template.createFullResponseWithFailedStatus(response, seq,
- OtherInfo.INTERNAL_CA_ERROR, s);
+ OtherInfo.INTERNAL_CA_ERROR, s);
return;
}
}
@@ -647,28 +645,27 @@ profile, IRequest req) {
int responseType = 0;
try {
- ///////////////////////////////////////////////
+ // /////////////////////////////////////////////
// submit request
- ///////////////////////////////////////////////
+ // /////////////////////////////////////////////
int error_codes[] = null;
if (reqs != null && reqs.length > 0)
- error_codes = new int[reqs.length];
+ error_codes = new int[reqs.length];
for (int k = 0; k < reqs.length; k++) {
try {
// reset the "auditRequesterID"
auditRequesterID = auditRequesterID(reqs[k]);
-
// print request debug
if (reqs[k] != null) {
- Enumeration reqKeys = reqs[k].getExtDataKeys();
- while (reqKeys.hasMoreElements()) {
- String reqKey = (String)reqKeys.nextElement();
- String reqVal = reqs[k].getExtDataInString(reqKey);
- if (reqVal != null) {
- CMS.debug("ProfileSubmitCMCServlet: key=$request." + reqKey + "$ value=" + reqVal);
+ Enumeration reqKeys = reqs[k].getExtDataKeys();
+ while (reqKeys.hasMoreElements()) {
+ String reqKey = (String) reqKeys.nextElement();
+ String reqVal = reqs[k].getExtDataInString(reqKey);
+ if (reqVal != null) {
+ CMS.debug("ProfileSubmitCMCServlet: key=$request." + reqKey + "$ value=" + reqVal);
+ }
}
- }
}
profile.submit(authToken, reqs[k]);
@@ -698,16 +695,16 @@ profile, IRequest req) {
// need to notify
INotify notify = profile.getRequestQueue().getPendingNotify();
if (notify != null) {
- notify.notify(reqs[k]);
+ notify.notify(reqs[k]);
}
-
+
CMS.debug("ProfileSubmitCMCServlet: submit " + e.toString());
errorCode = "2";
errorReason = CMS.getUserMessage(locale,
"CMS_PROFILE_DEFERRED",
e.toString());
} catch (ERejectException e) {
- // return error to the user
+ // return error to the user
reqs[k].setRequestStatus(RequestStatus.REJECTED);
CMS.debug("ProfileSubmitCMCServlet: submit " + e.toString());
errorCode = "3";
@@ -722,7 +719,7 @@ profile, IRequest req) {
"CMS_INTERNAL_ERROR");
}
- try {
+ try {
if (errorCode == null) {
profile.getRequestQueue().markAsServiced(reqs[k]);
} else {
@@ -730,7 +727,7 @@ profile, IRequest req) {
}
} catch (EBaseException e) {
CMS.debug("ProfileSubmitCMCServlet: updateRequest " +
- e.toString());
+ e.toString());
}
if (errorCode != null) {
@@ -774,40 +771,40 @@ profile, IRequest req) {
return;
}
- ///////////////////////////////////////////////
- // output output list
- ///////////////////////////////////////////////
-
- CMS.debug("ProfileSubmitCMCServlet: done serving");
- CMCOutputTemplate template = new CMCOutputTemplate();
- if (cert_request_type.equals("pkcs10") || cert_request_type.equals("crmf")) {
-
- if (outputFormat != null &&outputFormat.equals("pkcs7")) {
- byte[] pkcs7 = CMS.getPKCS7(locale, reqs[0]);
- response.setContentType("application/pkcs7-mime");
- response.setContentLength(pkcs7.length);
- try {
- OutputStream os = response.getOutputStream();
- os.write(pkcs7);
- os.flush();
- } catch (Exception ee) {
- }
- return;
- }
- template.createSimpleResponse(response, reqs);
- } else if (cert_request_type.equals("cmc")) {
- Integer nums = (Integer)(context.get("numOfControls"));
- if (nums != null && nums.intValue() == 1) {
- TaggedAttribute attr1 =
- (TaggedAttribute)(context.get(OBJECT_IDENTIFIER.id_cmc_getCert));
- if (attr1 != null) {
- template.createSimpleResponse(response, reqs);
- return;
- }
- }
- template.createFullResponse(response, reqs, cert_request_type,
- error_codes);
- }
+ // /////////////////////////////////////////////
+ // output output list
+ // /////////////////////////////////////////////
+
+ CMS.debug("ProfileSubmitCMCServlet: done serving");
+ CMCOutputTemplate template = new CMCOutputTemplate();
+ if (cert_request_type.equals("pkcs10") || cert_request_type.equals("crmf")) {
+
+ if (outputFormat != null && outputFormat.equals("pkcs7")) {
+ byte[] pkcs7 = CMS.getPKCS7(locale, reqs[0]);
+ response.setContentType("application/pkcs7-mime");
+ response.setContentLength(pkcs7.length);
+ try {
+ OutputStream os = response.getOutputStream();
+ os.write(pkcs7);
+ os.flush();
+ } catch (Exception ee) {
+ }
+ return;
+ }
+ template.createSimpleResponse(response, reqs);
+ } else if (cert_request_type.equals("cmc")) {
+ Integer nums = (Integer) (context.get("numOfControls"));
+ if (nums != null && nums.intValue() == 1) {
+ TaggedAttribute attr1 =
+ (TaggedAttribute) (context.get(OBJECT_IDENTIFIER.id_cmc_getCert));
+ if (attr1 != null) {
+ template.createSimpleResponse(response, reqs);
+ return;
+ }
+ }
+ template.createFullResponse(response, reqs, cert_request_type,
+ error_codes);
+ }
} finally {
SessionContext.releaseContext();
}
@@ -815,11 +812,11 @@ profile, IRequest req) {
/**
* Signed Audit Log Requester ID
- *
- * This method is called to obtain the "RequesterID" for
- * a signed audit log message.
+ *
+ * This method is called to obtain the "RequesterID" for a signed audit log
+ * message.
* <P>
- *
+ *
* @param request the actual request
* @return id string containing the signed audit log message RequesterID
*/
@@ -845,11 +842,11 @@ profile, IRequest req) {
/**
* Signed Audit Log Info Certificate Value
- *
+ *
* This method is called to obtain the certificate from the passed in
* "X509CertImpl" for a signed audit log message.
* <P>
- *
+ *
* @param request request containing an X509CertImpl
* @return cert string containing the certificate
*/
diff --git a/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileSubmitServlet.java b/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileSubmitServlet.java
index 3f663619..9a830dbf 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileSubmitServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/profile/ProfileSubmitServlet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.profile;
-
import java.math.BigInteger;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
@@ -72,10 +71,9 @@ import com.netscape.cms.servlet.common.CMSRequest;
import com.netscape.cmsutil.util.Cert;
import com.netscape.cmsutil.xml.XMLObject;
-
/**
* This servlet submits end-user request into the profile framework.
- *
+ *
* @author Christina Fu (renewal support)
* @version $Revision$, $Date$
*/
@@ -97,34 +95,31 @@ public class ProfileSubmitServlet extends ProfileServlet {
private String mReqType = null;
private String mAuthorityId = null;
- private final static String[]
- SIGNED_AUDIT_AUTOMATED_REJECTION_REASON = new String[] {
-
- /* 0 */ "automated profile cert request rejection: "
+ private final static String[] SIGNED_AUDIT_AUTOMATED_REJECTION_REASON = new String[] {
+
+ /* 0 */"automated profile cert request rejection: "
+ "indeterminate reason for inability to process "
+ "cert request due to an EBaseException"
};
private final static String LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED =
- "LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED_5";
-
-
- private final static String LOGGING_SIGNED_AUDIT_AUTH_FAIL =
- "LOGGING_SIGNED_AUDIT_AUTH_FAIL_4";
- private final static String LOGGING_SIGNED_AUDIT_AUTH_SUCCESS =
- "LOGGING_SIGNED_AUDIT_AUTH_SUCCESS_3";
+ "LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED_5";
+ private final static String LOGGING_SIGNED_AUDIT_AUTH_FAIL =
+ "LOGGING_SIGNED_AUDIT_AUTH_FAIL_4";
+ private final static String LOGGING_SIGNED_AUDIT_AUTH_SUCCESS =
+ "LOGGING_SIGNED_AUDIT_AUTH_SUCCESS_3";
public ProfileSubmitServlet() {
}
/**
- * initialize the servlet. And instance of this servlet can
- * be set up to always issue certificates against a certain profile
- * by setting the 'profileId' configuration in the servletConfig
- * If not, the user must specify the profileID when submitting the request
+ * initialize the servlet. And instance of this servlet can be set up to
+ * always issue certificates against a certain profile by setting the
+ * 'profileId' configuration in the servletConfig If not, the user must
+ * specify the profileID when submitting the request
*
* "ImportCert.template" to process the response.
- *
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -146,7 +141,8 @@ public class ProfileSubmitServlet extends ProfileServlet {
while (inputNames.hasMoreElements()) {
String inputName = (String) inputNames.nextElement();
if (request.getParameter(inputName) != null) {
- // all subject name parameters start with sn_, no other input parameters do
+ // all subject name parameters start with sn_, no other
+ // input parameters do
if (inputName.matches("^sn_.*")) {
ctx.set(inputName, escapeValueRfc1779(request.getParameter(inputName), false).toString());
} else {
@@ -159,10 +155,9 @@ public class ProfileSubmitServlet extends ProfileServlet {
}
- /*
- * fill input info from "request" to context.
- * This is expected to be used by renewal where the request
- * is retrieved from request record
+ /*
+ * fill input info from "request" to context. This is expected to be used by
+ * renewal where the request is retrieved from request record
*/
private void setInputsIntoContext(IRequest request, IProfile profile, IProfileContext ctx, Locale locale) {
// passing inputs into context
@@ -185,7 +180,7 @@ public class ProfileSubmitServlet extends ProfileServlet {
}
if (inputValue != null) {
- CMS.debug("ProfileSubmitServlet: setInputsIntoContext() setting value in ctx:"+ inputValue);
+ CMS.debug("ProfileSubmitServlet: setInputsIntoContext() setting value in ctx:" + inputValue);
ctx.set(inputName, inputValue);
} else {
CMS.debug("ProfileSubmitServlet: setInputsIntoContext() value null");
@@ -196,8 +191,6 @@ public class ProfileSubmitServlet extends ProfileServlet {
}
-
-
private void setCredentialsIntoContext(HttpServletRequest request, IProfileAuthenticator authenticator, IProfileContext ctx) {
Enumeration<String> authIds = authenticator.getValueNames();
@@ -206,8 +199,8 @@ public class ProfileSubmitServlet extends ProfileServlet {
while (authIds.hasMoreElements()) {
String authName = (String) authIds.nextElement();
- CMS.debug("ProfileSubmitServlet:setCredentialsIntoContext() authName:"+
- authName);
+ CMS.debug("ProfileSubmitServlet:setCredentialsIntoContext() authName:" +
+ authName);
if (request.getParameter(authName) != null) {
CMS.debug("ProfileSubmitServlet:setCredentialsIntoContext() authName found in request");
ctx.set(authName, request.getParameter(authName));
@@ -232,7 +225,7 @@ public class ProfileSubmitServlet extends ProfileServlet {
String n = t.substring(0, i);
if (n.equalsIgnoreCase("uid")) {
String v = t.substring(i + 1);
- CMS.debug("ProfileSubmitServlet:: getUidFromDN(): uid found:"+v);
+ CMS.debug("ProfileSubmitServlet:: getUidFromDN(): uid found:" + v);
return v;
} else {
continue;
@@ -242,70 +235,70 @@ public class ProfileSubmitServlet extends ProfileServlet {
}
/*
- * authenticate for renewal - more to add necessary params/values
- * to the session context
+ * authenticate for renewal - more to add necessary params/values to the
+ * session context
*/
public IAuthToken authenticate(IProfileAuthenticator authenticator,
- HttpServletRequest request, IRequest origReq, SessionContext context)
- throws EBaseException {
- IAuthToken authToken = authenticate(authenticator, request);
- // For renewal, fill in necessary params
- if (authToken!= null) {
- String ouid = origReq.getExtDataInString("auth_token.uid");
- // if the orig cert was manually approved, then there was
- // no auth token uid. Try to get the uid from the cert dn
- // itself, if possible
- if (ouid == null) {
- String sdn = (String) context.get("origSubjectDN");
- if (sdn != null) {
- ouid = getUidFromDN(sdn);
- if (ouid != null)
- CMS.debug("ProfileSubmitServlet: renewal: authToken original uid not found");
- }
- } else {
- CMS.debug("ProfileSubmitServlet: renewal: authToken original uid found in orig request auth_token");
- }
- String auid = authToken.getInString("uid");
- if (auid != null) { // not through ssl client auth
- CMS.debug("ProfileSubmitServlet: renewal: authToken uid found:"+auid);
- // authenticated with uid
- // put "orig_req.auth_token.uid" so that authz with
- // UserOrigReqAccessEvaluator will work
- if (ouid != null) {
- context.put("orig_req.auth_token.uid", ouid);
- CMS.debug("ProfileSubmitServlet: renewal: authToken original uid found:"+ouid);
- } else {
- CMS.debug("ProfileSubmitServlet: renewal: authToken original uid not found");
- }
- } else { // through ssl client auth?
- CMS.debug("ProfileSubmitServlet: renewal: authToken uid not found:");
- // put in orig_req's uid
- if (ouid != null) {
- CMS.debug("ProfileSubmitServlet: renewal: origReq uid not null:" +ouid+". Setting authtoken");
- authToken.set("uid", ouid);
- context.put(SessionContext.USER_ID, ouid);
- } else {
- CMS.debug("ProfileSubmitServlet: renewal: origReq uid not found");
-// throw new EBaseException("origReq uid not found");
- }
- }
-
- String userdn = origReq.getExtDataInString("auth_token.userdn");
- if (userdn != null) {
- CMS.debug("ProfileSubmitServlet: renewal: origReq userdn not null:"+userdn+". Setting authtoken");
- authToken.set("userdn", userdn);
- } else {
- CMS.debug("ProfileSubmitServlet: renewal: origReq userdn not found");
-// throw new EBaseException("origReq userdn not found");
- }
+ HttpServletRequest request, IRequest origReq, SessionContext context)
+ throws EBaseException {
+ IAuthToken authToken = authenticate(authenticator, request);
+ // For renewal, fill in necessary params
+ if (authToken != null) {
+ String ouid = origReq.getExtDataInString("auth_token.uid");
+ // if the orig cert was manually approved, then there was
+ // no auth token uid. Try to get the uid from the cert dn
+ // itself, if possible
+ if (ouid == null) {
+ String sdn = (String) context.get("origSubjectDN");
+ if (sdn != null) {
+ ouid = getUidFromDN(sdn);
+ if (ouid != null)
+ CMS.debug("ProfileSubmitServlet: renewal: authToken original uid not found");
+ }
+ } else {
+ CMS.debug("ProfileSubmitServlet: renewal: authToken original uid found in orig request auth_token");
+ }
+ String auid = authToken.getInString("uid");
+ if (auid != null) { // not through ssl client auth
+ CMS.debug("ProfileSubmitServlet: renewal: authToken uid found:" + auid);
+ // authenticated with uid
+ // put "orig_req.auth_token.uid" so that authz with
+ // UserOrigReqAccessEvaluator will work
+ if (ouid != null) {
+ context.put("orig_req.auth_token.uid", ouid);
+ CMS.debug("ProfileSubmitServlet: renewal: authToken original uid found:" + ouid);
+ } else {
+ CMS.debug("ProfileSubmitServlet: renewal: authToken original uid not found");
+ }
+ } else { // through ssl client auth?
+ CMS.debug("ProfileSubmitServlet: renewal: authToken uid not found:");
+ // put in orig_req's uid
+ if (ouid != null) {
+ CMS.debug("ProfileSubmitServlet: renewal: origReq uid not null:" + ouid + ". Setting authtoken");
+ authToken.set("uid", ouid);
+ context.put(SessionContext.USER_ID, ouid);
} else {
- CMS.debug("ProfileSubmitServlet: renewal: authToken null");
+ CMS.debug("ProfileSubmitServlet: renewal: origReq uid not found");
+ // throw new EBaseException("origReq uid not found");
}
- return authToken;
+ }
+
+ String userdn = origReq.getExtDataInString("auth_token.userdn");
+ if (userdn != null) {
+ CMS.debug("ProfileSubmitServlet: renewal: origReq userdn not null:" + userdn + ". Setting authtoken");
+ authToken.set("userdn", userdn);
+ } else {
+ CMS.debug("ProfileSubmitServlet: renewal: origReq userdn not found");
+ // throw new EBaseException("origReq userdn not found");
+ }
+ } else {
+ CMS.debug("ProfileSubmitServlet: renewal: authToken null");
+ }
+ return authToken;
}
public IAuthToken authenticate(IProfileAuthenticator authenticator,
- HttpServletRequest request) throws EBaseException {
+ HttpServletRequest request) throws EBaseException {
AuthCredentials credentials = new AuthCredentials();
// build credential
@@ -323,12 +316,12 @@ public class ProfileSubmitServlet extends ProfileServlet {
IAuthToken authToken = authenticator.authenticate(credentials);
SessionContext sc = SessionContext.getContext();
- if (sc != null) {
- sc.put(SessionContext.AUTH_MANAGER_ID, authenticator.getName());
- String userid = authToken.getInString(IAuthToken.USER_ID);
- if (userid != null) {
- sc.put(SessionContext.USER_ID, userid);
- }
+ if (sc != null) {
+ sc.put(SessionContext.AUTH_MANAGER_ID, authenticator.getName());
+ String userid = authToken.getInString(IAuthToken.USER_ID);
+ if (userid != null) {
+ sc.put(SessionContext.USER_ID, userid);
+ }
}
return authToken;
@@ -348,7 +341,8 @@ public class ProfileSubmitServlet extends ProfileServlet {
String inputName = (String) inputNames.nextElement();
if (request.getParameter(inputName) != null) {
- // special characters in subject names parameters must be escaped
+ // special characters in subject names parameters
+ // must be escaped
if (inputName.matches("^sn_.*")) {
req.setExtData(inputName, escapeValueRfc1779(request.getParameter(inputName), false).toString());
} else {
@@ -361,10 +355,9 @@ public class ProfileSubmitServlet extends ProfileServlet {
}
}
- /*
- * fill input info from orig request to the renew request.
- * This is expected to be used by renewal where the request
- * is retrieved from request record
+ /*
+ * fill input info from orig request to the renew request. This is expected
+ * to be used by renewal where the request is retrieved from request record
*/
private void setInputsIntoRequest(IRequest request, IProfile profile, IRequest req, Locale locale) {
// passing inputs into request
@@ -387,7 +380,7 @@ public class ProfileSubmitServlet extends ProfileServlet {
}
if (inputValue != null) {
- CMS.debug("ProfileSubmitServlet: setInputsIntoRequest() setting value in ctx:"+ inputValue);
+ CMS.debug("ProfileSubmitServlet: setInputsIntoRequest() setting value in ctx:" + inputValue);
req.setExtData(inputName, inputValue);
} else {
CMS.debug("ProfileSubmitServlet: setInputsIntoRequest() value null");
@@ -412,8 +405,8 @@ public class ProfileSubmitServlet extends ProfileServlet {
while (outputNames.hasMoreElements()) {
ArgSet outputset = new ArgSet();
String outputName = (String) outputNames.nextElement();
- IDescriptor outputDesc =
- profileOutput.getValueDescriptor(locale, outputName);
+ IDescriptor outputDesc =
+ profileOutput.getValueDescriptor(locale, outputName);
if (outputDesc == null)
continue;
@@ -423,7 +416,7 @@ public class ProfileSubmitServlet extends ProfileServlet {
String outputValue = null;
try {
- outputValue = profileOutput.getValue(outputName,
+ outputValue = profileOutput.getValue(outputName,
locale, req);
} catch (EProfileException e) {
CMS.debug("ProfileSubmitServlet: " + e.toString());
@@ -446,7 +439,7 @@ public class ProfileSubmitServlet extends ProfileServlet {
* <P>
*
* (Certificate Request Processed - either an automated "EE" profile based
- * cert acceptance, or an automated "EE" profile based cert rejection)
+ * cert acceptance, or an automated "EE" profile based cert rejection)
* <P>
*
* <ul>
@@ -454,6 +447,7 @@ public class ProfileSubmitServlet extends ProfileServlet {
* <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED used when a
* certificate request has just been through the approval process
* </ul>
+ *
* @param cmsReq the object holding the request and response information
* @exception EBaseException an error has occurred
*/
@@ -476,9 +470,9 @@ public class ProfileSubmitServlet extends ProfileServlet {
CMS.debug("xmlOutput false");
}
- IStatsSubsystem statsSub = (IStatsSubsystem)CMS.getSubsystem("stats");
+ IStatsSubsystem statsSub = (IStatsSubsystem) CMS.getSubsystem("stats");
if (statsSub != null) {
- statsSub.startTiming("enrollment", true /* main action */);
+ statsSub.startTiming("enrollment", true /* main action */);
}
long startTime = CMS.getCurrentDate().getTime();
@@ -488,34 +482,34 @@ public class ProfileSubmitServlet extends ProfileServlet {
if (CMS.debugOn()) {
CMS.debug("Start of ProfileSubmitServlet Input Parameters");
@SuppressWarnings("unchecked")
- Enumeration<String> paramNames = request.getParameterNames();
+ Enumeration<String> paramNames = request.getParameterNames();
while (paramNames.hasMoreElements()) {
String paramName = paramNames.nextElement();
// added this facility so that password can be hidden,
- // all sensitive parameters should be prefixed with
+ // all sensitive parameters should be prefixed with
// __ (double underscores); however, in the event that
// a security parameter slips through, we perform multiple
// additional checks to insure that it is NOT displayed
- if( paramName.startsWith("__") ||
- paramName.endsWith("password") ||
- paramName.endsWith("passwd") ||
- paramName.endsWith("pwd") ||
- paramName.equalsIgnoreCase("admin_password_again") ||
- paramName.equalsIgnoreCase("directoryManagerPwd") ||
- paramName.equalsIgnoreCase("bindpassword") ||
- paramName.equalsIgnoreCase("bindpwd") ||
- paramName.equalsIgnoreCase("passwd") ||
- paramName.equalsIgnoreCase("password") ||
- paramName.equalsIgnoreCase("pin") ||
- paramName.equalsIgnoreCase("pwd") ||
- paramName.equalsIgnoreCase("pwdagain") ||
- paramName.equalsIgnoreCase("uPasswd") ) {
+ if (paramName.startsWith("__") ||
+ paramName.endsWith("password") ||
+ paramName.endsWith("passwd") ||
+ paramName.endsWith("pwd") ||
+ paramName.equalsIgnoreCase("admin_password_again") ||
+ paramName.equalsIgnoreCase("directoryManagerPwd") ||
+ paramName.equalsIgnoreCase("bindpassword") ||
+ paramName.equalsIgnoreCase("bindpwd") ||
+ paramName.equalsIgnoreCase("passwd") ||
+ paramName.equalsIgnoreCase("password") ||
+ paramName.equalsIgnoreCase("pin") ||
+ paramName.equalsIgnoreCase("pwd") ||
+ paramName.equalsIgnoreCase("pwdagain") ||
+ paramName.equalsIgnoreCase("uPasswd")) {
CMS.debug("ProfileSubmitServlet Input Parameter " +
paramName + "='(sensitive)'");
} else {
CMS.debug("ProfileSubmitServlet Input Parameter " +
- paramName + "='" +
+ paramName + "='" +
request.getParameter(paramName) + "'");
}
}
@@ -528,44 +522,42 @@ public class ProfileSubmitServlet extends ProfileServlet {
mProfileSubId = IProfileSubsystem.ID;
}
CMS.debug("ProfileSubmitServlet: SubId=" + mProfileSubId);
- IProfileSubsystem ps = (IProfileSubsystem)
- CMS.getSubsystem(mProfileSubId);
+ IProfileSubsystem ps = (IProfileSubsystem)
+ CMS.getSubsystem(mProfileSubId);
if (ps == null) {
CMS.debug("ProfileSubmitServlet: ProfileSubsystem not found");
if (xmlOutput) {
outputError(response, CMS.getUserMessage(locale,
- "CMS_INTERNAL_ERROR"));
+ "CMS_INTERNAL_ERROR"));
} else {
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
- "CMS_INTERNAL_ERROR"));
+ "CMS_INTERNAL_ERROR"));
outputTemplate(request, response, args);
}
if (statsSub != null) {
- statsSub.endTiming("enrollment");
+ statsSub.endTiming("enrollment");
}
return;
}
/*
* Renewal - Renewal is retrofitted into the Profile Enrollment
- * Framework. The authentication and authorization are taken from
- * the renewal profile, while the input (with requests) and grace
- * period constraint are taken from the original cert's request record.
+ * Framework. The authentication and authorization are taken from the
+ * renewal profile, while the input (with requests) and grace period
+ * constraint are taken from the original cert's request record.
*
- * Things to note:
- * * the renew request will contain the original profile instead
- * of the new
- * * there is no request for system and admin certs generated at
- * time of installation configuration.
+ * Things to note: * the renew request will contain the original profile
+ * instead of the new * there is no request for system and admin certs
+ * generated at time of installation configuration.
*/
String renewal = request.getParameter("renewal");
boolean isRenewal = false;
- if ((renewal!= null) && (renewal.equalsIgnoreCase("true"))) {
+ if ((renewal != null) && (renewal.equalsIgnoreCase("true"))) {
CMS.debug("ProfileSubmitServlet: isRenewal true");
isRenewal = true;
- request.setAttribute("reqType", (Object)"renewal");
+ request.setAttribute("reqType", (Object) "renewal");
} else {
CMS.debug("ProfileSubmitServlet: isRenewal false");
}
@@ -593,11 +585,11 @@ public class ProfileSubmitServlet extends ProfileServlet {
if (isRenewal) {
// dig up the original request to "clone"
renewProfileId = profileId;
- CMS.debug("ProfileSubmitServlet: renewProfileId ="+renewProfileId);
+ CMS.debug("ProfileSubmitServlet: renewProfileId =" + renewProfileId);
IAuthority authority = (IAuthority) CMS.getSubsystem(mAuthorityId);
if (authority == null) {
CMS.debug("ProfileSubmitServlet: renewal: Authority " + mAuthorityId +
- " not found");
+ " not found");
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
"CMS_INTERNAL_ERROR"));
@@ -608,7 +600,7 @@ public class ProfileSubmitServlet extends ProfileServlet {
if (queue == null) {
CMS.debug("ProfileSubmitServlet: renewal: Request Queue of " +
- mAuthorityId + " not found");
+ mAuthorityId + " not found");
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
"CMS_INTERNAL_ERROR"));
@@ -619,7 +611,7 @@ public class ProfileSubmitServlet extends ProfileServlet {
String serial = request.getParameter("serial_num");
BigInteger certSerial = null;
// if serial number is sent with request, then the authentication
- // method is not ssl client auth. In this case, an alternative
+ // method is not ssl client auth. In this case, an alternative
// authentication method is used (default: ldap based)
if (serial != null) {
CMS.debug("ProfileSubmitServlet: renewal: found serial_num");
@@ -638,7 +630,7 @@ public class ProfileSubmitServlet extends ProfileServlet {
CMS.debug("ProfileSubmitServlet: renewal: no ssl client cert chain");
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
- "CMS_INTERNAL_ERROR"));
+ "CMS_INTERNAL_ERROR"));
outputTemplate(request, response, args);
return;
} else { // has ssl client cert
@@ -646,45 +638,45 @@ public class ProfileSubmitServlet extends ProfileServlet {
// shouldn't expect leaf cert to be always at the
// same location
X509Certificate clientCert = null;
- for (int i = 0; i< certs.length; i++) {
+ for (int i = 0; i < certs.length; i++) {
clientCert = certs[i];
- byte [] extBytes = clientCert.getExtensionValue("2.5.29.19");
+ byte[] extBytes = clientCert.getExtensionValue("2.5.29.19");
// try to see if this is a leaf cert
// look for BasicConstraint extension
if (extBytes == null) {
// found leaf cert
- CMS.debug("ProfileSubmitServlet: renewal: found leaf cert");
+ CMS.debug("ProfileSubmitServlet: renewal: found leaf cert");
break;
} else {
- CMS.debug("ProfileSubmitServlet: renewal: found cert having BasicConstraints ext");
- // it's got BasicConstraints extension
- // so it's not likely to be a leaf cert,
- // however, check the isCA field regardless
- try {
- BasicConstraintsExtension bce =
- new BasicConstraintsExtension(true, extBytes);
- if (bce != null) {
- if (!(Boolean)bce.get("is_ca")) {
- CMS.debug("ProfileSubmitServlet: renewal: found CA cert in chain");
- break;
- } // else found a ca cert, continue
- }
- } catch (Exception e) {
- CMS.debug("ProfileSubmitServlet: renewal: exception:"+
+ CMS.debug("ProfileSubmitServlet: renewal: found cert having BasicConstraints ext");
+ // it's got BasicConstraints extension
+ // so it's not likely to be a leaf cert,
+ // however, check the isCA field regardless
+ try {
+ BasicConstraintsExtension bce =
+ new BasicConstraintsExtension(true, extBytes);
+ if (bce != null) {
+ if (!(Boolean) bce.get("is_ca")) {
+ CMS.debug("ProfileSubmitServlet: renewal: found CA cert in chain");
+ break;
+ } // else found a ca cert, continue
+ }
+ } catch (Exception e) {
+ CMS.debug("ProfileSubmitServlet: renewal: exception:" +
e.toString());
- args.set(ARG_ERROR_CODE, "1");
- args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
- "CMS_INTERNAL_ERROR"));
- outputTemplate(request, response, args);
- return;
- }
+ args.set(ARG_ERROR_CODE, "1");
+ args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
+ "CMS_INTERNAL_ERROR"));
+ outputTemplate(request, response, args);
+ return;
+ }
}
}
if (clientCert == null) {
CMS.debug("ProfileSubmitServlet: renewal: no client cert in chain");
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
- "CMS_INTERNAL_ERROR"));
+ "CMS_INTERNAL_ERROR"));
outputTemplate(request, response, args);
return;
}
@@ -694,10 +686,10 @@ public class ProfileSubmitServlet extends ProfileServlet {
clientCert = new X509CertImpl(certEncoded);
} catch (Exception e) {
- CMS.debug("ProfileSubmitServlet: renewal: exception:"+e.toString());
+ CMS.debug("ProfileSubmitServlet: renewal: exception:" + e.toString());
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
- "CMS_INTERNAL_ERROR"));
+ "CMS_INTERNAL_ERROR"));
outputTemplate(request, response, args);
return;
}
@@ -706,7 +698,7 @@ public class ProfileSubmitServlet extends ProfileServlet {
}
}
- CMS.debug("ProfileSubmitServlet: renewal: serial number of cert to renew:"+ certSerial.toString());
+ CMS.debug("ProfileSubmitServlet: renewal: serial number of cert to renew:" + certSerial.toString());
try {
ICertificateRepository certDB = null;
@@ -716,28 +708,28 @@ public class ProfileSubmitServlet extends ProfileServlet {
if (certDB == null) {
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
- "CMS_INTERNAL_ERROR"));
+ "CMS_INTERNAL_ERROR"));
outputTemplate(request, response, args);
return;
}
ICertRecord rec = (ICertRecord) certDB.readCertificateRecord(certSerial);
- if (rec == null) {
- CMS.debug("ProfileSubmitServlet: renewal cert record not found for serial number "+ certSerial.toString());
+ if (rec == null) {
+ CMS.debug("ProfileSubmitServlet: renewal cert record not found for serial number " + certSerial.toString());
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
- "CMS_INTERNAL_ERROR"));
+ "CMS_INTERNAL_ERROR"));
outputTemplate(request, response, args);
return;
} else {
- CMS.debug("ProfileSubmitServlet: renewal cert record found for serial number:"+ certSerial.toString());
+ CMS.debug("ProfileSubmitServlet: renewal cert record found for serial number:" + certSerial.toString());
// check to see if the cert is revoked or revoked_expired
if ((rec.getStatus().equals(ICertRecord.STATUS_REVOKED)) || (rec.getStatus().equals(ICertRecord.STATUS_REVOKED_EXPIRED))) {
- CMS.debug("ProfileSubmitServlet: renewal cert found to be revoked. Serial number = "+ certSerial.toString());
- args.set(ARG_ERROR_CODE, "1");
- args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
- "CMS_CA_CANNOT_RENEW_REVOKED_CERT", certSerial.toString()));
- outputTemplate(request, response, args);
- return;
+ CMS.debug("ProfileSubmitServlet: renewal cert found to be revoked. Serial number = " + certSerial.toString());
+ args.set(ARG_ERROR_CODE, "1");
+ args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
+ "CMS_CA_CANNOT_RENEW_REVOKED_CERT", certSerial.toString()));
+ outputTemplate(request, response, args);
+ return;
}
MetaInfo metaInfo = (MetaInfo) rec.get(ICertRecord.ATTR_META_INFO);
// note: CA's internal certs don't have request ids
@@ -748,54 +740,56 @@ public class ProfileSubmitServlet extends ProfileServlet {
if (rid != null) {
origReq = queue.findRequest(new RequestId(rid));
if (origReq != null) {
- CMS.debug("ProfileSubmitServlet: renewal: found original enrollment request id:"+ rid);
+ CMS.debug("ProfileSubmitServlet: renewal: found original enrollment request id:" + rid);
// debug: print the extData keys
Enumeration<String> en = origReq.getExtDataKeys();
-/*
- CMS.debug("ProfileSubmitServlet: renewal: origRequest extdata key print BEGINS");
- while (en.hasMoreElements()) {
- String next = (String) en.nextElement();
- CMS.debug("ProfileSubmitServlet: renewal: origRequest extdata key:"+ next);
- }
- CMS.debug("ProfileSubmitServlet: renewal: origRequest extdata key print ENDS");
-*/
+ /*
+ * CMS.debug(
+ * "ProfileSubmitServlet: renewal: origRequest extdata key print BEGINS"
+ * ); while (en.hasMoreElements()) { String next
+ * = (String) en.nextElement(); CMS.debug(
+ * "ProfileSubmitServlet: renewal: origRequest extdata key:"
+ * + next); } CMS.debug(
+ * "ProfileSubmitServlet: renewal: origRequest extdata key print ENDS"
+ * );
+ */
String requestorE = origReq.getExtDataInString("requestor_email");
- CMS.debug("ProfileSubmitServlet: renewal original requestor email="+requestorE);
+ CMS.debug("ProfileSubmitServlet: renewal original requestor email=" + requestorE);
profileId = origReq.getExtDataInString("profileId");
if (profileId != null)
- CMS.debug("ProfileSubmitServlet: renewal original profileId="+profileId);
+ CMS.debug("ProfileSubmitServlet: renewal original profileId=" + profileId);
else {
- CMS.debug("ProfileSubmitServlet: renewal original profileId not found");
- args.set(ARG_ERROR_CODE, "1");
- args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
- "CMS_INTERNAL_ERROR"));
- outputTemplate(request, response, args);
- return;
+ CMS.debug("ProfileSubmitServlet: renewal original profileId not found");
+ args.set(ARG_ERROR_CODE, "1");
+ args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
+ "CMS_INTERNAL_ERROR"));
+ outputTemplate(request, response, args);
+ return;
}
origSeqNum = origReq.getExtDataInInteger(IEnrollProfile.REQUEST_SEQ_NUM);
-
- } else { //if origReq
- CMS.debug("ProfileSubmitServlet: renewal original request not found for request id "+ rid);
+
+ } else { // if origReq
+ CMS.debug("ProfileSubmitServlet: renewal original request not found for request id " + rid);
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
- "CMS_INTERNAL_ERROR"));
+ "CMS_INTERNAL_ERROR"));
outputTemplate(request, response, args);
return;
}
} else {
- CMS.debug("ProfileSubmitServlet: renewal: cert record locating request id in MetaInfo failed for serial number "+ certSerial.toString());
- CMS.debug("ProfileSubmitServlet: renewal: cert may be bootstrapped system cert during installation/configuration - no request record exists");
- args.set(ARG_ERROR_CODE, "1");
- args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
- "CMS_INTERNAL_ERROR"+": original request not found"));
- outputTemplate(request, response, args);
- return;
+ CMS.debug("ProfileSubmitServlet: renewal: cert record locating request id in MetaInfo failed for serial number " + certSerial.toString());
+ CMS.debug("ProfileSubmitServlet: renewal: cert may be bootstrapped system cert during installation/configuration - no request record exists");
+ args.set(ARG_ERROR_CODE, "1");
+ args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
+ "CMS_INTERNAL_ERROR" + ": original request not found"));
+ outputTemplate(request, response, args);
+ return;
}
} else {
- CMS.debug("ProfileSubmitServlet: renewal: cert record locating MetaInfo failed for serial number "+ certSerial.toString());
+ CMS.debug("ProfileSubmitServlet: renewal: cert record locating MetaInfo failed for serial number " + certSerial.toString());
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
- "CMS_INTERNAL_ERROR"));
+ "CMS_INTERNAL_ERROR"));
outputTemplate(request, response, args);
return;
}
@@ -803,96 +797,96 @@ public class ProfileSubmitServlet extends ProfileServlet {
CMS.debug("ProfileSubmitServlet: renewal: before getting origNotAfter");
X509CertImpl origCert = rec.getCertificate();
origNotAfter = origCert.getNotAfter();
- CMS.debug("ProfileSubmitServlet: renewal: origNotAfter ="+
- origNotAfter.toString());
+ CMS.debug("ProfileSubmitServlet: renewal: origNotAfter =" +
+ origNotAfter.toString());
origSubjectDN = origCert.getSubjectDN().getName();
- CMS.debug("ProfileSubmitServlet: renewal: orig subj dn ="+
- origSubjectDN);
+ CMS.debug("ProfileSubmitServlet: renewal: orig subj dn =" +
+ origSubjectDN);
}
} catch (Exception e) {
- CMS.debug("ProfileSubmitServlet: renewal: exception:"+e.toString());
+ CMS.debug("ProfileSubmitServlet: renewal: exception:" + e.toString());
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
- "CMS_INTERNAL_ERROR"));
+ "CMS_INTERNAL_ERROR"));
outputTemplate(request, response, args);
return;
}
} // end isRenewal
- IProfile profile = null;
+ IProfile profile = null;
IProfile renewProfile = null;
- try {
- profile = ps.getProfile(profileId);
+ try {
+ profile = ps.getProfile(profileId);
if (isRenewal) {
// in case of renew, "profile" is the orig profile
// while "renewProfile" is the current profile used for renewal
- renewProfile = ps.getProfile(renewProfileId);
+ renewProfile = ps.getProfile(renewProfileId);
}
- } catch (EProfileException e) {
- if(profile == null) {
- CMS.debug("ProfileSubmitServlet: profile not found profileId " +
- profileId + " " + e.toString());
+ } catch (EProfileException e) {
+ if (profile == null) {
+ CMS.debug("ProfileSubmitServlet: profile not found profileId " +
+ profileId + " " + e.toString());
}
if (renewProfile == null) {
CMS.debug("ProfileSubmitServlet: profile not found renewProfileId " +
- renewProfileId + " " + e.toString());
+ renewProfileId + " " + e.toString());
}
}
if (profile == null) {
if (xmlOutput) {
- outputError(response, CMS.getUserMessage(locale,"CMS_PROFILE_NOT_FOUND", profileId));
+ outputError(response, CMS.getUserMessage(locale, "CMS_PROFILE_NOT_FOUND", profileId));
} else {
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
- "CMS_PROFILE_NOT_FOUND", profileId));
+ "CMS_PROFILE_NOT_FOUND", profileId));
outputTemplate(request, response, args);
}
return;
}
if (isRenewal && (renewProfile == null)) {
if (xmlOutput) {
- outputError(response, CMS.getUserMessage(locale,"CMS_PROFILE_NOT_FOUND", renewProfileId));
+ outputError(response, CMS.getUserMessage(locale, "CMS_PROFILE_NOT_FOUND", renewProfileId));
} else {
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
- "CMS_PROFILE_NOT_FOUND", renewProfileId));
+ "CMS_PROFILE_NOT_FOUND", renewProfileId));
outputTemplate(request, response, args);
}
return;
}
if (!ps.isProfileEnable(profileId)) {
- CMS.debug("ProfileSubmitServlet: Profile " + profileId +
- " not enabled");
+ CMS.debug("ProfileSubmitServlet: Profile " + profileId +
+ " not enabled");
if (xmlOutput) {
outputError(response, CMS.getUserMessage(locale, "CMS_PROFILE_NOT_FOUND", profileId));
} else {
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
- "CMS_PROFILE_NOT_FOUND", profileId));
+ "CMS_PROFILE_NOT_FOUND", profileId));
outputTemplate(request, response, args);
}
if (statsSub != null) {
- statsSub.endTiming("enrollment");
+ statsSub.endTiming("enrollment");
}
return;
}
if (isRenewal) {
- if (!ps.isProfileEnable(renewProfileId)) {
- CMS.debug("ProfileSubmitServlet: renewal Profile " + renewProfileId +
- " not enabled");
- if (xmlOutput) {
- outputError(response, CMS.getUserMessage(locale, "CMS_PROFILE_NOT_FOUND", renewProfileId));
- } else {
- args.set(ARG_ERROR_CODE, "1");
- args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
- "CMS_PROFILE_NOT_FOUND", renewProfileId));
- outputTemplate(request, response, args);
+ if (!ps.isProfileEnable(renewProfileId)) {
+ CMS.debug("ProfileSubmitServlet: renewal Profile " + renewProfileId +
+ " not enabled");
+ if (xmlOutput) {
+ outputError(response, CMS.getUserMessage(locale, "CMS_PROFILE_NOT_FOUND", renewProfileId));
+ } else {
+ args.set(ARG_ERROR_CODE, "1");
+ args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
+ "CMS_PROFILE_NOT_FOUND", renewProfileId));
+ outputTemplate(request, response, args);
+ }
+ return;
}
- return;
- }
}
IProfileContext ctx = profile.createContext();
@@ -909,40 +903,41 @@ public class ProfileSubmitServlet extends ProfileServlet {
}
} catch (EProfileException e) {
// authenticator not installed correctly
- CMS.debug("ProfileSubmitServlet: renewal: exception:"+e.toString());
+ CMS.debug("ProfileSubmitServlet: renewal: exception:" + e.toString());
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
- "CMS_INTERNAL_ERROR"));
+ "CMS_INTERNAL_ERROR"));
outputTemplate(request, response, args);
return;
}
if (authenticator == null) {
CMS.debug("ProfileSubmitServlet: authenticator not found");
} else {
- CMS.debug("ProfileSubmitServlet: authenticator " +
- authenticator.getName() + " found");
+ CMS.debug("ProfileSubmitServlet: authenticator " +
+ authenticator.getName() + " found");
setCredentialsIntoContext(request, authenticator, ctx);
}
- // for renewal, this will override or add auth info to the profile context
+ // for renewal, this will override or add auth info to the profile
+ // context
if (isRenewal) {
- if (origAuthenticator!= null) {
- CMS.debug("ProfileSubmitServlet: for renewal, original authenticator " +
- origAuthenticator.getName() + " found");
- setCredentialsIntoContext(request, origAuthenticator, ctx);
- } else {
- CMS.debug("ProfileSubmitServlet: for renewal, original authenticator not found");
- }
+ if (origAuthenticator != null) {
+ CMS.debug("ProfileSubmitServlet: for renewal, original authenticator " +
+ origAuthenticator.getName() + " found");
+ setCredentialsIntoContext(request, origAuthenticator, ctx);
+ } else {
+ CMS.debug("ProfileSubmitServlet: for renewal, original authenticator not found");
+ }
}
CMS.debug("ProfileSubmistServlet: set Inputs into profile Context");
if (isRenewal) {
- // for renewal, input needs to be retrieved from the orig req record
+ // for renewal, input needs to be retrieved from the orig req record
CMS.debug("ProfileSubmitServlet: set original Inputs into profile Context");
setInputsIntoContext(origReq, profile, ctx, locale);
ctx.set(IEnrollProfile.CTX_RENEWAL, "true");
ctx.set("renewProfileId", renewProfileId);
- ctx.set(IEnrollProfile.CTX_RENEWAL_SEQ_NUM, origSeqNum.toString());
+ ctx.set(IEnrollProfile.CTX_RENEWAL_SEQ_NUM, origSeqNum.toString());
} else {
setInputsIntoContext(request, profile, ctx);
}
@@ -956,14 +951,14 @@ public class ProfileSubmitServlet extends ProfileServlet {
SessionContext context = SessionContext.getContext();
// insert profile context so that input parameter can be retrieved
- context.put("profileContext", ctx);
- context.put("sslClientCertProvider",
- new SSLClientCertProvider(request));
+ context.put("profileContext", ctx);
+ context.put("sslClientCertProvider",
+ new SSLClientCertProvider(request));
CMS.debug("ProfileSubmitServlet: set sslClientCertProvider");
if ((isRenewal == true) && (origSubjectDN != null))
- context.put("origSubjectDN", origSubjectDN);
+ context.put("origSubjectDN", origSubjectDN);
if (statsSub != null) {
- statsSub.startTiming("profile_authentication");
+ statsSub.startTiming("profile_authentication");
}
if (authenticator != null) {
@@ -972,23 +967,24 @@ public class ProfileSubmitServlet extends ProfileServlet {
String uid_cred = "Unidentified";
String uid_attempted_cred = "Unidentified";
Enumeration<String> authIds = authenticator.getValueNames();
- //Attempt to possibly fetch attemped uid, may not always be available.
+ // Attempt to possibly fetch attemped uid, may not always be
+ // available.
if (authIds != null) {
while (authIds.hasMoreElements()) {
- String authName = authIds.nextElement();
- String value = request.getParameter(authName);
+ String authName = authIds.nextElement();
+ String value = request.getParameter(authName);
if (value != null) {
- if (authName.equals("uid")) {
- uid_attempted_cred = value;
- }
+ if (authName.equals("uid")) {
+ uid_attempted_cred = value;
+ }
}
}
}
- String authSubjectID = auditSubjectID();
+ String authSubjectID = auditSubjectID();
- String authMgrID = authenticator.getName();
- String auditMessage = null;
+ String authMgrID = authenticator.getName();
+ String auditMessage = null;
try {
if (isRenewal) {
CMS.debug("ProfileSubmitServlet: renewal authenticate begins");
@@ -998,25 +994,25 @@ public class ProfileSubmitServlet extends ProfileServlet {
authToken = authenticate(authenticator, request);
}
} catch (EBaseException e) {
- CMS.debug("ProfileSubmitServlet: authentication error " +
- e.toString());
+ CMS.debug("ProfileSubmitServlet: authentication error " +
+ e.toString());
// authentication error
if (xmlOutput) {
outputError(response, CMS.getUserMessage(locale, "CMS_AUTHENTICATION_ERROR"));
} else {
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
- "CMS_AUTHENTICATION_ERROR"));
+ "CMS_AUTHENTICATION_ERROR"));
outputTemplate(request, response, args);
}
if (statsSub != null) {
- statsSub.endTiming("authentication");
+ statsSub.endTiming("authentication");
}
if (statsSub != null) {
- statsSub.endTiming("enrollment");
+ statsSub.endTiming("enrollment");
}
- //audit log our authentication failure
+ // audit log our authentication failure
authSubjectID += " : " + uid_cred;
auditMessage = CMS.getLogMessage(
@@ -1030,9 +1026,10 @@ public class ProfileSubmitServlet extends ProfileServlet {
return;
}
- //Log successful authentication
+ // Log successful authentication
- //Attempt to get uid from authToken, most tokens respond to the "uid" cred.
+ // Attempt to get uid from authToken, most tokens respond to the
+ // "uid" cred.
uid_cred = authToken.getInString("uid");
if (uid_cred == null || uid_cred.length() == 0) {
@@ -1040,7 +1037,7 @@ public class ProfileSubmitServlet extends ProfileServlet {
}
authSubjectID = authSubjectID + " : " + uid_cred;
-
+
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_AUTH_SUCCESS,
@@ -1052,7 +1049,7 @@ public class ProfileSubmitServlet extends ProfileServlet {
}
if (statsSub != null) {
- statsSub.endTiming("profile_authentication");
+ statsSub.endTiming("profile_authentication");
}
// authentication success
@@ -1061,23 +1058,23 @@ public class ProfileSubmitServlet extends ProfileServlet {
// do profile authorization
String acl = null;
if (isRenewal)
- acl = renewProfile.getAuthzAcl();
+ acl = renewProfile.getAuthzAcl();
else
- acl = profile.getAuthzAcl();
- CMS.debug("ProfileSubmitServlet: authz using acl: "+acl);
+ acl = profile.getAuthzAcl();
+ CMS.debug("ProfileSubmitServlet: authz using acl: " + acl);
if (acl != null && acl.length() > 0) {
try {
String resource = profileId + ".authz.acl";
AuthzToken authzToken = authorize(mAclMethod, resource, authToken, acl);
} catch (Exception e) {
- CMS.debug("ProfileSubmitServlet authorize: "+e.toString());
+ CMS.debug("ProfileSubmitServlet authorize: " + e.toString());
if (xmlOutput) {
- outputError(response, CMS.getUserMessage(locale,
- "CMS_AUTHORIZATION_ERROR"));
+ outputError(response, CMS.getUserMessage(locale,
+ "CMS_AUTHORIZATION_ERROR"));
} else {
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
- "CMS_AUTHORIZATION_ERROR"));
+ "CMS_AUTHORIZATION_ERROR"));
outputTemplate(request, response, args);
}
@@ -1089,11 +1086,11 @@ public class ProfileSubmitServlet extends ProfileServlet {
IRequest reqs[] = null;
if (statsSub != null) {
- statsSub.startTiming("request_population");
+ statsSub.startTiming("request_population");
}
- ///////////////////////////////////////////////
+ // /////////////////////////////////////////////
// create request
- ///////////////////////////////////////////////
+ // /////////////////////////////////////////////
try {
reqs = profile.createRequests(ctx, locale);
} catch (EProfileException e) {
@@ -1107,8 +1104,8 @@ public class ProfileSubmitServlet extends ProfileServlet {
outputTemplate(request, response, args);
}
if (statsSub != null) {
- statsSub.endTiming("request_population");
- statsSub.endTiming("enrollment");
+ statsSub.endTiming("request_population");
+ statsSub.endTiming("enrollment");
}
return;
} catch (Throwable e) {
@@ -1119,44 +1116,44 @@ public class ProfileSubmitServlet extends ProfileServlet {
} else {
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
- "CMS_INTERNAL_ERROR"));
+ "CMS_INTERNAL_ERROR"));
outputTemplate(request, response, args);
}
if (statsSub != null) {
- statsSub.endTiming("request_population");
- statsSub.endTiming("enrollment");
+ statsSub.endTiming("request_population");
+ statsSub.endTiming("enrollment");
}
return;
}
String errorCode = null;
- String errorReason = null;
+ String errorReason = null;
- ///////////////////////////////////////////////
+ // /////////////////////////////////////////////
// populate request
- ///////////////////////////////////////////////
+ // /////////////////////////////////////////////
for (int k = 0; k < reqs.length; k++) {
boolean fromRA = false;
String uid = "";
// adding parameters to request
if (isRenewal) {
- setInputsIntoRequest(origReq, profile, reqs[k], locale);
- // set orig expiration date to be used in Validity constraint
- reqs[k].setExtData("origNotAfter",
- BigInteger.valueOf(origNotAfter.getTime()));
- // set subjectDN to be used in subject name default
- reqs[k].setExtData(IProfileAuthenticator.AUTHENTICATED_NAME, origSubjectDN);
- // set request type
- reqs[k].setRequestType("renewal");
+ setInputsIntoRequest(origReq, profile, reqs[k], locale);
+ // set orig expiration date to be used in Validity constraint
+ reqs[k].setExtData("origNotAfter",
+ BigInteger.valueOf(origNotAfter.getTime()));
+ // set subjectDN to be used in subject name default
+ reqs[k].setExtData(IProfileAuthenticator.AUTHENTICATED_NAME, origSubjectDN);
+ // set request type
+ reqs[k].setRequestType("renewal");
} else
- setInputsIntoRequest(request, profile, reqs[k]);
+ setInputsIntoRequest(request, profile, reqs[k]);
// serial auth token into request
if (authToken != null) {
Enumeration<String> tokenNames = authToken.getElements();
while (tokenNames.hasMoreElements()) {
- String tokenName = tokenNames.nextElement();
+ String tokenName = tokenNames.nextElement();
String[] tokenVals = authToken.getInStringArray(tokenName);
if (tokenVals != null) {
for (int i = 0; i < tokenVals.length; i++) {
@@ -1181,7 +1178,7 @@ public class ProfileSubmitServlet extends ProfileServlet {
}
if (fromRA) {
- CMS.debug("ProfileSubmitServlet: request from RA: "+ uid);
+ CMS.debug("ProfileSubmitServlet: request from RA: " + uid);
reqs[k].setExtData(ARG_REQUEST_OWNER, uid);
}
@@ -1200,13 +1197,13 @@ public class ProfileSubmitServlet extends ProfileServlet {
outputError(response, FAILED, CMS.getUserMessage("CMS_PROFILE_NO_POLICY_SET_FOUND"), reqs[k].getRequestId().toString());
} else {
args.set(ARG_ERROR_CODE, "1");
- args.set(ARG_ERROR_REASON,
- CMS.getUserMessage("CMS_PROFILE_NO_POLICY_SET_FOUND"));
+ args.set(ARG_ERROR_REASON,
+ CMS.getUserMessage("CMS_PROFILE_NO_POLICY_SET_FOUND"));
outputTemplate(request, response, args);
}
if (statsSub != null) {
- statsSub.endTiming("request_population");
- statsSub.endTiming("enrollment");
+ statsSub.endTiming("request_population");
+ statsSub.endTiming("enrollment");
}
return;
}
@@ -1216,13 +1213,13 @@ public class ProfileSubmitServlet extends ProfileServlet {
reqs[k].setExtData(ARG_PROFILE_REMOTE_HOST, request.getRemoteHost());
reqs[k].setExtData(ARG_PROFILE_REMOTE_ADDR, request.getRemoteAddr());
- CMS.debug("ProfileSubmitServlet: request " +
- reqs[k].getRequestId().toString());
+ CMS.debug("ProfileSubmitServlet: request " +
+ reqs[k].getRequestId().toString());
try {
CMS.debug("ProfileSubmitServlet: populating request inputs");
// give authenticator a chance to populate the request
- if (authenticator != null) {
+ if (authenticator != null) {
authenticator.populate(authToken, reqs[k]);
}
profile.populateInput(ctx, reqs[k]);
@@ -1237,31 +1234,31 @@ public class ProfileSubmitServlet extends ProfileServlet {
outputTemplate(request, response, args);
}
if (statsSub != null) {
- statsSub.endTiming("request_population");
- statsSub.endTiming("enrollment");
+ statsSub.endTiming("request_population");
+ statsSub.endTiming("enrollment");
}
return;
} catch (Throwable e) {
CMS.debug("ProfileSubmitServlet: populate " + e.toString());
- // throw new IOException("Profile " + profileId +
- // " cannot populate");
+ // throw new IOException("Profile " + profileId +
+ // " cannot populate");
if (xmlOutput) {
outputError(response, FAILED, CMS.getUserMessage(locale, "CMS_INTERNAL_ERROR"), reqs[k].getRequestId().toString());
} else {
args.set(ARG_ERROR_CODE, "1");
args.set(ARG_ERROR_REASON, CMS.getUserMessage(locale,
- "CMS_INTERNAL_ERROR"));
+ "CMS_INTERNAL_ERROR"));
outputTemplate(request, response, args);
}
if (statsSub != null) {
- statsSub.endTiming("request_population");
- statsSub.endTiming("enrollment");
+ statsSub.endTiming("request_population");
+ statsSub.endTiming("enrollment");
}
return;
}
}
if (statsSub != null) {
- statsSub.endTiming("request_population");
+ statsSub.endTiming("request_population");
}
String auditMessage = null;
@@ -1270,9 +1267,9 @@ public class ProfileSubmitServlet extends ProfileServlet {
String auditInfoCertValue = ILogger.SIGNED_AUDIT_EMPTY_VALUE;
try {
- ///////////////////////////////////////////////
+ // /////////////////////////////////////////////
// submit request
- ///////////////////////////////////////////////
+ // /////////////////////////////////////////////
String requestIds = ""; // deliminated with double space
for (int k = 0; k < reqs.length; k++) {
try {
@@ -1281,15 +1278,15 @@ public class ProfileSubmitServlet extends ProfileServlet {
// print request debug
if (reqs[k] != null) {
- requestIds += " "+reqs[k].getRequestId().toString();
- Enumeration<String> reqKeys = reqs[k].getExtDataKeys();
- while (reqKeys.hasMoreElements()) {
- String reqKey = reqKeys.nextElement();
- String reqVal = reqs[k].getExtDataInString(reqKey);
- if (reqVal != null) {
- CMS.debug("ProfileSubmitServlet: key=$request." + reqKey + "$ value=" + reqVal);
+ requestIds += " " + reqs[k].getRequestId().toString();
+ Enumeration<String> reqKeys = reqs[k].getExtDataKeys();
+ while (reqKeys.hasMoreElements()) {
+ String reqKey = reqKeys.nextElement();
+ String reqVal = reqs[k].getExtDataInString(reqKey);
+ if (reqVal != null) {
+ CMS.debug("ProfileSubmitServlet: key=$request." + reqKey + "$ value=" + reqVal);
+ }
}
- }
}
profile.submit(authToken, reqs[k]);
@@ -1319,16 +1316,16 @@ public class ProfileSubmitServlet extends ProfileServlet {
// need to notify
INotify notify = profile.getRequestQueue().getPendingNotify();
if (notify != null) {
- notify.notify(reqs[k]);
+ notify.notify(reqs[k]);
}
-
+
CMS.debug("ProfileSubmitServlet: submit " + e.toString());
errorCode = "2";
errorReason = CMS.getUserMessage(locale,
"CMS_PROFILE_DEFERRED",
e.toString());
} catch (ERejectException e) {
- // return error to the user
+ // return error to the user
reqs[k].setRequestStatus(RequestStatus.REJECTED);
CMS.debug("ProfileSubmitServlet: submit " + e.toString());
errorCode = "3";
@@ -1343,7 +1340,7 @@ public class ProfileSubmitServlet extends ProfileServlet {
"CMS_INTERNAL_ERROR");
}
- try {
+ try {
if (errorCode == null) {
profile.getRequestQueue().markAsServiced(reqs[k]);
} else {
@@ -1351,7 +1348,7 @@ public class ProfileSubmitServlet extends ProfileServlet {
}
} catch (EBaseException e) {
CMS.debug("ProfileSubmitServlet: updateRequest " +
- e.toString());
+ e.toString());
}
if (errorCode != null) {
@@ -1396,7 +1393,7 @@ public class ProfileSubmitServlet extends ProfileServlet {
ArgSet requestset = new ArgSet();
requestset.set(ARG_REQUEST_ID,
- reqs[k].getRequestId().toString());
+ reqs[k].getRequestId().toString());
requestlist.add(requestset);
}
args.set(ARG_REQUEST_LIST, requestlist);
@@ -1405,14 +1402,14 @@ public class ProfileSubmitServlet extends ProfileServlet {
outputTemplate(request, response, args);
}
if (statsSub != null) {
- statsSub.endTiming("enrollment");
+ statsSub.endTiming("enrollment");
}
return;
}
- ///////////////////////////////////////////////
- // output output list
- ///////////////////////////////////////////////
+ // /////////////////////////////////////////////
+ // output output list
+ // /////////////////////////////////////////////
if (xmlOutput) {
xmlOutput(response, profile, locale, reqs);
} else {
@@ -1431,7 +1428,7 @@ public class ProfileSubmitServlet extends ProfileServlet {
ArgSet requestset = new ArgSet();
requestset.set(ARG_REQUEST_ID,
- reqs[k].getRequestId().toString());
+ reqs[k].getRequestId().toString());
requestlist.add(requestset);
}
args.set(ARG_REQUEST_LIST, requestlist);
@@ -1454,14 +1451,14 @@ public class ProfileSubmitServlet extends ProfileServlet {
audit(auditMessage);
if (statsSub != null) {
- statsSub.endTiming("enrollment");
+ statsSub.endTiming("enrollment");
}
throw eAudit1;
} finally {
SessionContext.releaseContext();
}
if (statsSub != null) {
- statsSub.endTiming("enrollment");
+ statsSub.endTiming("enrollment");
}
}
@@ -1473,19 +1470,19 @@ public class ProfileSubmitServlet extends ProfileServlet {
Node root = xmlObj.createRoot("XMLResponse");
xmlObj.addItemToContainer(root, "Status", SUCCESS);
Node n = xmlObj.createContainer(root, "Requests");
- CMS.debug("ProfileSubmitServlet xmlOutput: req len = " +reqs.length);
+ CMS.debug("ProfileSubmitServlet xmlOutput: req len = " + reqs.length);
- for (int i=0; i<reqs.length; i++) {
+ for (int i = 0; i < reqs.length; i++) {
Node subnode = xmlObj.createContainer(n, "Request");
xmlObj.addItemToContainer(subnode, "Id", reqs[i].getRequestId().toString());
X509CertInfo certInfo =
- reqs[i].getExtDataInCertInfo(IEnrollProfile.REQUEST_CERTINFO);
+ reqs[i].getExtDataInCertInfo(IEnrollProfile.REQUEST_CERTINFO);
if (certInfo != null) {
- String subject = "";
- subject = (String) certInfo.get(X509CertInfo.SUBJECT).toString();
- xmlObj.addItemToContainer(subnode, "SubjectDN", subject);
+ String subject = "";
+ subject = (String) certInfo.get(X509CertInfo.SUBJECT).toString();
+ xmlObj.addItemToContainer(subnode, "SubjectDN", subject);
} else {
- CMS.debug("ProfileSubmitServlet xmlOutput: no certInfo found in request");
+ CMS.debug("ProfileSubmitServlet xmlOutput: no certInfo found in request");
}
Enumeration<String> outputIds = profile.getProfileOutputIds();
if (outputIds != null) {
@@ -1501,23 +1498,23 @@ public class ProfileSubmitServlet extends ProfileServlet {
try {
String outputValue = profileOutput.getValue(outputName, locale, reqs[i]);
if (outputName.equals("b64_cert")) {
- String ss = Cert.normalizeCertStrAndReq(outputValue);
- outputValue = Cert.stripBrackets(ss);
- byte[] bcode = CMS.AtoB(outputValue);
- X509CertImpl impl = new X509CertImpl(bcode);
- xmlObj.addItemToContainer(subnode,
- "serialno", impl.getSerialNumber().toString(16));
- xmlObj.addItemToContainer(subnode, "b64", outputValue);
+ String ss = Cert.normalizeCertStrAndReq(outputValue);
+ outputValue = Cert.stripBrackets(ss);
+ byte[] bcode = CMS.AtoB(outputValue);
+ X509CertImpl impl = new X509CertImpl(bcode);
+ xmlObj.addItemToContainer(subnode,
+ "serialno", impl.getSerialNumber().toString(16));
+ xmlObj.addItemToContainer(subnode, "b64", outputValue);
}// if b64_cert
else if (outputName.equals("pkcs7")) {
- String ss = Cert.normalizeCertStrAndReq(outputValue);
- xmlObj.addItemToContainer(subnode, "pkcs7", ss);
+ String ss = Cert.normalizeCertStrAndReq(outputValue);
+ xmlObj.addItemToContainer(subnode, "pkcs7", ss);
}
-
+
} catch (EProfileException e) {
- CMS.debug("ProfileSubmitServlet xmlOutput: "+e.toString());
+ CMS.debug("ProfileSubmitServlet xmlOutput: " + e.toString());
} catch (Exception e) {
- CMS.debug("ProfileSubmitServlet xmlOutput: "+e.toString());
+ CMS.debug("ProfileSubmitServlet xmlOutput: " + e.toString());
}
}
}
@@ -1534,11 +1531,11 @@ public class ProfileSubmitServlet extends ProfileServlet {
/**
* Signed Audit Log Requester ID
- *
- * This method is called to obtain the "RequesterID" for
- * a signed audit log message.
+ *
+ * This method is called to obtain the "RequesterID" for a signed audit log
+ * message.
* <P>
- *
+ *
* @param request the actual request
* @return id string containing the signed audit log message RequesterID
*/
@@ -1564,11 +1561,11 @@ public class ProfileSubmitServlet extends ProfileServlet {
/**
* Signed Audit Log Info Certificate Value
- *
+ *
* This method is called to obtain the certificate from the passed in
* "X509CertImpl" for a signed audit log message.
* <P>
- *
+ *
* @param request request containing an X509CertImpl
* @return cert string containing the certificate
*/
diff --git a/pki/base/common/src/com/netscape/cms/servlet/profile/SSLClientCertProvider.java b/pki/base/common/src/com/netscape/cms/servlet/profile/SSLClientCertProvider.java
index 989710e3..0114f632 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/profile/SSLClientCertProvider.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/profile/SSLClientCertProvider.java
@@ -32,9 +32,8 @@ public class SSLClientCertProvider implements ISSLClientCertProvider {
public X509Certificate[] getClientCertificateChain() {
X509Certificate[] allCerts = (X509Certificate[])
- mRequest.getAttribute("javax.servlet.request.X509Certificate");
+ mRequest.getAttribute("javax.servlet.request.X509Certificate");
return allCerts;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/request/CertReqParser.java b/pki/base/common/src/com/netscape/cms/servlet/request/CertReqParser.java
index 6a9ccac5..2f14fe71 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/request/CertReqParser.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/request/CertReqParser.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.request;
-
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.lang.reflect.Array;
@@ -61,18 +60,15 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.RawJS;
-
/**
* Output a 'pretty print' of a certificate request
- *
+ *
* @version $Revision$, $Date$
*/
public class CertReqParser extends ReqParser {
-
- public static final CertReqParser
- DETAIL_PARSER = new CertReqParser(true);
- public static final CertReqParser
- NODETAIL_PARSER = new CertReqParser(false);
+
+ public static final CertReqParser DETAIL_PARSER = new CertReqParser(true);
+ public static final CertReqParser NODETAIL_PARSER = new CertReqParser(false);
private boolean mDetails = true;
private IPrettyPrintFormat pp = null;
@@ -86,7 +82,7 @@ public class CertReqParser extends ReqParser {
/**
* Constructs a certificate request parser.
- *
+ *
* @param details return detailed information (this can be time consuming)
*/
public CertReqParser(boolean details) {
@@ -101,34 +97,30 @@ public class CertReqParser extends ReqParser {
private static final String RB = "]";
private static final String EQ = " = ";
- private static final String
- HTTP_PARAMS_COUNTER = IRequest.HTTP_PARAMS + LB + "httpParamsCount++" + RB;
- private static final String
- HTTP_HEADERS_COUNTER = IRequest.HTTP_HEADERS + LB + "httpHeadersCount++" + RB;
- private static final String
- AUTH_TOKEN_COUNTER = IRequest.AUTH_TOKEN + LB + "authTokenCount++" + RB;
- private static final String
- SERVER_ATTRS_COUNTER = IRequest.SERVER_ATTRS + LB + "serverAttrsCount++" + RB;
+ private static final String HTTP_PARAMS_COUNTER = IRequest.HTTP_PARAMS + LB + "httpParamsCount++" + RB;
+ private static final String HTTP_HEADERS_COUNTER = IRequest.HTTP_HEADERS + LB + "httpHeadersCount++" + RB;
+ private static final String AUTH_TOKEN_COUNTER = IRequest.AUTH_TOKEN + LB + "authTokenCount++" + RB;
+ private static final String SERVER_ATTRS_COUNTER = IRequest.SERVER_ATTRS + LB + "serverAttrsCount++" + RB;
/**
* Fills in certificate specific request attributes.
*/
public void fillRequestIntoArg(Locale l, IRequest req, CMSTemplateParams argSet, IArgBlock arg)
- throws EBaseException {
+ throws EBaseException {
if (req.getExtDataInCertInfoArray(IRequest.CERT_INFO) != null) {
- fillX509RequestIntoArg(l, req, argSet, arg);
+ fillX509RequestIntoArg(l, req, argSet, arg);
} else if (req.getExtDataInRevokedCertArray(IRequest.CERT_INFO) != null) {
- fillRevokeRequestIntoArg(l, req, argSet, arg);
+ fillRevokeRequestIntoArg(l, req, argSet, arg);
} else {
- //o = req.get(IRequest.OLD_CERTS);
- //if (o != null)
- fillRevokeRequestIntoArg(l, req, argSet, arg);
+ // o = req.get(IRequest.OLD_CERTS);
+ // if (o != null)
+ fillRevokeRequestIntoArg(l, req, argSet, arg);
}
}
-
+
private void fillX509RequestIntoArg(Locale l, IRequest req, CMSTemplateParams argSet, IArgBlock arg)
- throws EBaseException {
-
+ throws EBaseException {
+
// fill in the standard attributes
super.fillRequestIntoArg(l, req, argSet, arg);
@@ -138,19 +130,19 @@ public class CertReqParser extends ReqParser {
Enumeration<String> enum1 = req.getExtDataKeys();
// gross hack
- String prefix = "record.";
+ String prefix = "record.";
if (argSet.getHeader() == arg)
prefix = "header.";
while (enum1.hasMoreElements()) {
- String name = enum1.nextElement();
+ String name = enum1.nextElement();
if (mDetails) {
// show all http parameters stored in request.
if (name.equalsIgnoreCase(IRequest.HTTP_PARAMS)) {
Hashtable<String, ?> http_params = req.getExtDataInHashtable(name);
- // show certType specially
+ // show certType specially
String certType = (String) http_params.get(IRequest.CERT_TYPE);
if (certType != null) {
@@ -166,16 +158,16 @@ public class CertReqParser extends ReqParser {
Enumeration<String> elms = http_params.keys();
while (elms.hasMoreElements()) {
- String parami =
- IRequest.HTTP_PARAMS + LB + String.valueOf(counter++) + RB;
+ String parami =
+ IRequest.HTTP_PARAMS + LB + String.valueOf(counter++) + RB;
// hack
- String n = elms.nextElement();
+ String n = elms.nextElement();
String rawJS = "new Object;\n\r" +
- prefix + parami + ".name=\"" +
- CMSTemplate.escapeJavaScriptString(n) + "\";\n\r" +
- prefix + parami + ".value=\"" +
- CMSTemplate.escapeJavaScriptStringHTML(
- http_params.get(n).toString()) + "\"";
+ prefix + parami + ".name=\"" +
+ CMSTemplate.escapeJavaScriptString(n) + "\";\n\r" +
+ prefix + parami + ".value=\"" +
+ CMSTemplate.escapeJavaScriptStringHTML(
+ http_params.get(n).toString()) + "\"";
arg.set(parami, new RawJS(rawJS));
}
@@ -186,16 +178,16 @@ public class CertReqParser extends ReqParser {
int counter = 0;
while (elms.hasMoreElements()) {
- String parami =
- IRequest.HTTP_HEADERS + LB + String.valueOf(counter++) + RB;
+ String parami =
+ IRequest.HTTP_HEADERS + LB + String.valueOf(counter++) + RB;
// hack
- String n = elms.nextElement();
+ String n = elms.nextElement();
String rawJS = "new Object;\n\r" +
- prefix + parami + ".name=\"" +
- CMSTemplate.escapeJavaScriptString(n) + "\";\n\r" +
- prefix + parami + ".value=\"" +
- CMSTemplate.escapeJavaScriptStringHTML(
- http_hdrs.get(n).toString()) + "\"";
+ prefix + parami + ".name=\"" +
+ CMSTemplate.escapeJavaScriptString(n) + "\";\n\r" +
+ prefix + parami + ".value=\"" +
+ CMSTemplate.escapeJavaScriptStringHTML(
+ http_hdrs.get(n).toString()) + "\"";
arg.set(parami, new RawJS(rawJS));
}
@@ -206,23 +198,24 @@ public class CertReqParser extends ReqParser {
int counter = 0;
while (elms.hasMoreElements()) {
- String parami =
- IRequest.AUTH_TOKEN + LB + String.valueOf(counter++) + RB;
+ String parami =
+ IRequest.AUTH_TOKEN + LB + String.valueOf(counter++) + RB;
// hack
- String n = elms.nextElement();
+ String n = elms.nextElement();
Object authTokenValue = auth_token.getInStringArray(n);
if (authTokenValue == null) {
authTokenValue = auth_token.getInString(n);
}
String v = expandValue(prefix + parami + ".value",
- authTokenValue);
+ authTokenValue);
String rawJS = "new Object;\n\r" +
- prefix + parami + ".name=\"" +
- CMSTemplate.escapeJavaScriptString(n) + "\";\n" + v;
+ prefix + parami + ".name=\"" +
+ CMSTemplate.escapeJavaScriptString(n) + "\";\n" + v;
arg.set(parami, new RawJS(rawJS));
}
- } // all others are request attrs from policy or internal modules.
+ } // all others are request attrs from policy or internal
+ // modules.
else {
Object val;
if (req.isSimpleExtDataValue(name)) {
@@ -235,41 +228,41 @@ public class CertReqParser extends ReqParser {
}
String valstr = "";
// hack
- String parami =
- IRequest.SERVER_ATTRS + LB + String.valueOf(saCounter++) + RB;
+ String parami =
+ IRequest.SERVER_ATTRS + LB + String.valueOf(saCounter++) + RB;
if (name.equalsIgnoreCase(IRequest.ISSUED_CERTS) && mDetails &&
- (req.getRequestStatus().toString().equals(RequestStatus.COMPLETE_STRING) ||
+ (req.getRequestStatus().toString().equals(RequestStatus.COMPLETE_STRING) ||
req.getRequestType().equals(IRequest.GETREVOCATIONINFO_REQUEST))) {
X509CertImpl issuedCert[] =
- req.getExtDataInCertArray(IRequest.ISSUED_CERTS);
+ req.getExtDataInCertArray(IRequest.ISSUED_CERTS);
if (issuedCert != null && issuedCert[0] != null) {
- val = "<pre>"+CMS.getCertPrettyPrint(issuedCert[0]).toString(l)+"</pre>";
+ val = "<pre>" + CMS.getCertPrettyPrint(issuedCert[0]).toString(l) + "</pre>";
}
} else if (name.equalsIgnoreCase(IRequest.CERT_INFO) && mDetails) {
X509CertInfo[] certInfo =
- req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
+ req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
if (certInfo != null && certInfo[0] != null) {
- val = "<pre>"+certInfo[0].toString()+"</pre>";
+ val = "<pre>" + certInfo[0].toString() + "</pre>";
}
}
valstr = expandValue(prefix + parami + ".value", val);
String rawJS = "new Object;\n\r" +
- prefix + parami + ".name=\"" +
- CMSTemplate.escapeJavaScriptString(name) + "\";\n" +
- valstr; // java string already escaped in expandValue.
+ prefix + parami + ".name=\"" +
+ CMSTemplate.escapeJavaScriptString(name) + "\";\n" +
+ valstr; // java string already escaped in
+ // expandValue.
arg.set(parami, new RawJS(rawJS));
}
}
if (name.equalsIgnoreCase(IRequest.REQUESTOR_PHONE)
- || name.equalsIgnoreCase(IRequest.REQUESTOR_EMAIL)
- || name.equalsIgnoreCase(IRequest.REQUESTOR_COMMENTS)
- || name.equalsIgnoreCase(IRequest.RESULT)
- || name.equalsIgnoreCase(IRequest.REQUEST_TRUSTEDMGR_PRIVILEGE)
- ) {
+ || name.equalsIgnoreCase(IRequest.REQUESTOR_EMAIL)
+ || name.equalsIgnoreCase(IRequest.REQUESTOR_COMMENTS)
+ || name.equalsIgnoreCase(IRequest.RESULT)
+ || name.equalsIgnoreCase(IRequest.REQUEST_TRUSTEDMGR_PRIVILEGE)) {
arg.addStringValue(name, req.getExtDataInString(name));
}
@@ -299,12 +292,12 @@ public class CertReqParser extends ReqParser {
}
if (name.equalsIgnoreCase(IRequest.CERT_INFO)) {
- // Get the certificate info from the request
+ // Get the certificate info from the request
X509CertInfo[] certInfo =
- req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
+ req.getExtDataInCertInfoArray(IRequest.CERT_INFO);
if (certInfo != null && certInfo[0] != null) {
- // Get the subject name if any set.
+ // Get the subject name if any set.
CertificateSubjectName subjectName = null;
String signatureAlgorithm = null;
String signatureAlgorithmName = null;
@@ -332,9 +325,9 @@ public class CertReqParser extends ReqParser {
if (mDetails) {
try {
CertificateAlgorithmId certAlgId = (CertificateAlgorithmId)
- certInfo[0].get(X509CertInfo.ALGORITHM_ID);
+ certInfo[0].get(X509CertInfo.ALGORITHM_ID);
AlgorithmId algId = (AlgorithmId)
- certAlgId.get(CertificateAlgorithmId.ALGORITHM);
+ certAlgId.get(CertificateAlgorithmId.ALGORITHM);
signatureAlgorithm = (algId.getOID()).toString();
signatureAlgorithmName = algId.getName();
@@ -362,36 +355,36 @@ public class CertReqParser extends ReqParser {
// only know about ns cert type
if (ext instanceof NSCertTypeExtension) {
- NSCertTypeExtension nsExtensions =
- (NSCertTypeExtension) ext;
+ NSCertTypeExtension nsExtensions =
+ (NSCertTypeExtension) ext;
try {
arg.addStringValue("ext_" + NSCertTypeExtension.SSL_SERVER,
- nsExtensions.get(NSCertTypeExtension.SSL_SERVER).toString());
+ nsExtensions.get(NSCertTypeExtension.SSL_SERVER).toString());
arg.addStringValue("ext_" + NSCertTypeExtension.SSL_CLIENT,
- nsExtensions.get(NSCertTypeExtension.SSL_CLIENT).toString());
+ nsExtensions.get(NSCertTypeExtension.SSL_CLIENT).toString());
arg.addStringValue("ext_" + NSCertTypeExtension.EMAIL,
- nsExtensions.get(NSCertTypeExtension.EMAIL).toString());
+ nsExtensions.get(NSCertTypeExtension.EMAIL).toString());
arg.addStringValue("ext_" + NSCertTypeExtension.OBJECT_SIGNING,
- nsExtensions.get(NSCertTypeExtension.OBJECT_SIGNING).toString());
+ nsExtensions.get(NSCertTypeExtension.OBJECT_SIGNING).toString());
arg.addStringValue("ext_" + NSCertTypeExtension.SSL_CA,
- nsExtensions.get(NSCertTypeExtension.SSL_CA).toString());
+ nsExtensions.get(NSCertTypeExtension.SSL_CA).toString());
arg.addStringValue("ext_" + NSCertTypeExtension.EMAIL_CA,
- nsExtensions.get(NSCertTypeExtension.EMAIL_CA).toString());
+ nsExtensions.get(NSCertTypeExtension.EMAIL_CA).toString());
arg.addStringValue("ext_" + NSCertTypeExtension.OBJECT_SIGNING_CA,
- nsExtensions.get(NSCertTypeExtension.OBJECT_SIGNING_CA).toString());
+ nsExtensions.get(NSCertTypeExtension.OBJECT_SIGNING_CA).toString());
} catch (Exception e) {
}
} else if (ext instanceof BasicConstraintsExtension) {
- BasicConstraintsExtension bcExt =
- (BasicConstraintsExtension) ext;
+ BasicConstraintsExtension bcExt =
+ (BasicConstraintsExtension) ext;
Integer pathLength = null;
Boolean isCA = null;
@@ -410,8 +403,8 @@ public class CertReqParser extends ReqParser {
IArgBlock rr = CMS.createArgBlock();
rr.addStringValue(
- EXT_PRETTYPRINT,
- CMS.getExtPrettyPrint(ext, 0).toString());
+ EXT_PRETTYPRINT,
+ CMS.getExtPrettyPrint(ext, 0).toString());
argSet.addRepeatRecord(rr);
}
}
@@ -419,7 +412,7 @@ public class CertReqParser extends ReqParser {
}
- // Get the public key
+ // Get the public key
CertificateX509Key certKey = null;
try {
@@ -440,17 +433,17 @@ public class CertReqParser extends ReqParser {
if (key != null) {
arg.addStringValue("subjectPublicKeyInfo",
- key.getAlgorithm() + " - " + key.getAlgorithmId().getOID().toString());
+ key.getAlgorithm() + " - " + key.getAlgorithmId().getOID().toString());
arg.addStringValue("subjectPublicKey",
- pp.toHexString(key.getKey(), 0, 16));
+ pp.toHexString(key.getKey(), 0, 16));
}
- // Get the validity period
+ // Get the validity period
CertificateValidity validity = null;
try {
validity =
- (CertificateValidity)
+ (CertificateValidity)
certInfo[0].get(X509CertInfo.VALIDITY);
if (validity != null) {
long validityLength = (((Date) validity.get(CertificateValidity.NOT_AFTER)).getTime() - ((Date) validity.get(CertificateValidity.NOT_BEFORE)).getTime()) / 1000;
@@ -475,7 +468,7 @@ public class CertReqParser extends ReqParser {
IArgBlock rarg = CMS.createArgBlock();
rarg.addBigIntegerValue("serialNumber",
- oldSerialNo[i], 16);
+ oldSerialNo[i], 16);
argSet.addRepeatRecord(rarg);
}
}
@@ -483,10 +476,10 @@ public class CertReqParser extends ReqParser {
}
if (name.equalsIgnoreCase(IRequest.ISSUED_CERTS) && mDetails &&
- (req.getRequestStatus().toString().equals(RequestStatus.COMPLETE_STRING) ||
+ (req.getRequestStatus().toString().equals(RequestStatus.COMPLETE_STRING) ||
req.getRequestType().equals(IRequest.GETREVOCATIONINFO_REQUEST))) {
X509CertImpl issuedCert[] =
- req.getExtDataInCertArray(IRequest.ISSUED_CERTS);
+ req.getExtDataInCertArray(IRequest.ISSUED_CERTS);
arg.addBigIntegerValue("serialNumber", issuedCert[0].getSerialNumber(), 16);
// Set Serial No for 2nd certificate
@@ -495,7 +488,7 @@ public class CertReqParser extends ReqParser {
}
if (name.equalsIgnoreCase(IRequest.OLD_CERTS) && mDetails) {
X509CertImpl oldCert[] =
- req.getExtDataInCertArray(IRequest.OLD_CERTS);
+ req.getExtDataInCertArray(IRequest.OLD_CERTS);
if (oldCert != null && oldCert.length > 0) {
arg.addBigIntegerValue("serialNumber", oldCert[0].getSerialNumber(), 16);
@@ -505,7 +498,7 @@ public class CertReqParser extends ReqParser {
IArgBlock rarg = CMS.createArgBlock();
rarg.addBigIntegerValue("serialNumber",
- oldCert[i].getSerialNumber(), 16);
+ oldCert[i].getSerialNumber(), 16);
argSet.addRepeatRecord(rarg);
}
}
@@ -526,7 +519,7 @@ public class CertReqParser extends ReqParser {
IArgBlock rarg = CMS.createArgBlock();
rarg.addBigIntegerValue("serialNumber",
- cert[i].getSerialNumber(), 16);
+ cert[i].getSerialNumber(), 16);
argSet.addRepeatRecord(rarg);
}
} catch (IOException e) {
@@ -535,16 +528,16 @@ public class CertReqParser extends ReqParser {
}
}
if (name.equalsIgnoreCase(IRequest.FINGERPRINTS) && mDetails) {
- Hashtable<String, Object> fingerprints =
- req.getExtDataInHashtable(IRequest.FINGERPRINTS);
+ Hashtable<String, Object> fingerprints =
+ req.getExtDataInHashtable(IRequest.FINGERPRINTS);
if (fingerprints != null) {
String namesAndHashes = null;
Enumeration<String> enumFingerprints = fingerprints.keys();
- while (enumFingerprints.hasMoreElements()) {
+ while (enumFingerprints.hasMoreElements()) {
String hashname = enumFingerprints.nextElement();
- String hashvalue = (String) fingerprints.get(hashname);
+ String hashvalue = (String) fingerprints.get(hashname);
byte[] fingerprint = CMS.AtoB(hashvalue);
String ppFingerprint = pp.toHexString(fingerprint, 0);
@@ -578,7 +571,7 @@ public class CertReqParser extends ReqParser {
StringBuffer sb = new StringBuffer();
for (@SuppressWarnings("unchecked")
- Enumeration<String> n = ((Vector<String>)v).elements(); n.hasMoreElements(); j++) {
+ Enumeration<String> n = ((Vector<String>) v).elements(); n.hasMoreElements(); j++) {
sb.append(";\n");
sb.append(valuename);
sb.append(LB);
@@ -588,8 +581,8 @@ public class CertReqParser extends ReqParser {
sb.append("\"");
sb.append(
CMSTemplate.escapeJavaScriptStringHTML(
- n.nextElement().toString()));
- sb.append( "\";\n");
+ n.nextElement().toString()));
+ sb.append("\";\n");
}
sb.append("\n");
valstr = sb.toString();
@@ -599,7 +592,7 @@ public class CertReqParser extends ReqParser {
// if an array.
int len = -1;
- try {
+ try {
len = Array.getLength(v);
} catch (IllegalArgumentException e) {
}
@@ -611,7 +604,7 @@ public class CertReqParser extends ReqParser {
if (Array.get(v, i) != null)
valstr += ";\n" + valuename + LB + i + RB + EQ + "\"" +
CMSTemplate.escapeJavaScriptStringHTML(
- Array.get(v, i).toString()) + "\";\n";
+ Array.get(v, i).toString()) + "\";\n";
}
return valstr;
}
@@ -620,16 +613,16 @@ public class CertReqParser extends ReqParser {
// if string or unrecognized type, just call its toString method.
return valuename + "=\"" +
- CMSTemplate.escapeJavaScriptStringHTML(v.toString()) + "\"";
+ CMSTemplate.escapeJavaScriptStringHTML(v.toString()) + "\"";
}
public String getRequestorDN(IRequest request) {
try {
X509CertInfo info = (X509CertInfo)
- request.getExtDataInCertInfo(IEnrollProfile.REQUEST_CERTINFO);
+ request.getExtDataInCertInfo(IEnrollProfile.REQUEST_CERTINFO);
// retrieve the subject name
CertificateSubjectName sn = (CertificateSubjectName)
- info.get(X509CertInfo.SUBJECT);
+ info.get(X509CertInfo.SUBJECT);
return sn.toString();
} catch (Exception e) {
@@ -644,15 +637,15 @@ public class CertReqParser extends ReqParser {
String cid = request.getExtDataInString(IRequest.NETKEY_ATTR_CUID);
if (cid == null) {
- cid = "";
+ cid = "";
}
String uid = request.getExtDataInString(IRequest.NETKEY_ATTR_USERID);
if (uid == null) {
- uid = "";
+ uid = "";
}
- kid = cid+":"+uid;
+ kid = cid + ":" + uid;
if (kid.equals(":")) {
- kid = "";
+ kid = "";
}
return kid;
@@ -663,14 +656,14 @@ public class CertReqParser extends ReqParser {
}
private void fillRevokeRequestIntoArg(Locale l, IRequest req, CMSTemplateParams argSet, IArgBlock arg)
- throws EBaseException {
+ throws EBaseException {
// fill in the standard attributes
super.fillRequestIntoArg(l, req, argSet, arg);
arg.addStringValue("certExtsEnabled", "yes");
String profile = req.getExtDataInString("profile");
- //CMS.debug("CertReqParser: profile=" + profile);
+ // CMS.debug("CertReqParser: profile=" + profile);
if (profile != null) {
arg.addStringValue("profile", profile);
String requestorDN = getRequestorDN(req);
@@ -691,7 +684,7 @@ public class CertReqParser extends ReqParser {
Enumeration<String> enum1 = req.getExtDataKeys();
// gross hack
- String prefix = "record.";
+ String prefix = "record.";
if (argSet.getHeader() == arg)
prefix = "header.";
@@ -703,7 +696,7 @@ public class CertReqParser extends ReqParser {
// show all http parameters stored in request.
if (name.equalsIgnoreCase(IRequest.HTTP_PARAMS)) {
Hashtable<String, Object> http_params = req.getExtDataInHashtable(name);
- // show certType specially
+ // show certType specially
String certType = (String) http_params.get(IRequest.CERT_TYPE);
if (certType != null) {
@@ -714,16 +707,16 @@ public class CertReqParser extends ReqParser {
Enumeration<String> elms = http_params.keys();
while (elms.hasMoreElements()) {
- String parami =
- IRequest.HTTP_PARAMS + LB + String.valueOf(counter++) + RB;
+ String parami =
+ IRequest.HTTP_PARAMS + LB + String.valueOf(counter++) + RB;
// hack
String n = (String) elms.nextElement();
String rawJS = "new Object;\n\r" +
- prefix + parami + ".name=\"" +
- CMSTemplate.escapeJavaScriptString(n) + "\";\n\r" +
- prefix + parami + ".value=\"" +
- CMSTemplate.escapeJavaScriptStringHTML(
- http_params.get(n).toString()) + "\"";
+ prefix + parami + ".name=\"" +
+ CMSTemplate.escapeJavaScriptString(n) + "\";\n\r" +
+ prefix + parami + ".value=\"" +
+ CMSTemplate.escapeJavaScriptStringHTML(
+ http_params.get(n).toString()) + "\"";
arg.set(parami, new RawJS(rawJS));
}
@@ -734,16 +727,16 @@ public class CertReqParser extends ReqParser {
int counter = 0;
while (elms.hasMoreElements()) {
- String parami =
- IRequest.HTTP_HEADERS + LB + String.valueOf(counter++) + RB;
+ String parami =
+ IRequest.HTTP_HEADERS + LB + String.valueOf(counter++) + RB;
// hack
String n = (String) elms.nextElement();
String rawJS = "new Object;\n\r" +
- prefix + parami + ".name=\"" +
- CMSTemplate.escapeJavaScriptString(n) + "\";\n\r" +
- prefix + parami + ".value=\"" +
- CMSTemplate.escapeJavaScriptStringHTML(
- http_hdrs.get(n).toString()) + "\"";
+ prefix + parami + ".name=\"" +
+ CMSTemplate.escapeJavaScriptString(n) + "\";\n\r" +
+ prefix + parami + ".value=\"" +
+ CMSTemplate.escapeJavaScriptStringHTML(
+ http_hdrs.get(n).toString()) + "\"";
arg.set(parami, new RawJS(rawJS));
}
@@ -754,20 +747,21 @@ public class CertReqParser extends ReqParser {
int counter = 0;
while (elms.hasMoreElements()) {
- String parami =
- IRequest.AUTH_TOKEN + LB + String.valueOf(counter++) + RB;
+ String parami =
+ IRequest.AUTH_TOKEN + LB + String.valueOf(counter++) + RB;
// hack
String n = (String) elms.nextElement();
- String v =
- expandValue(prefix + parami + ".value",
- auth_token.getInString(n));
+ String v =
+ expandValue(prefix + parami + ".value",
+ auth_token.getInString(n));
String rawJS = "new Object;\n\r" +
- prefix + parami + ".name=\"" +
- CMSTemplate.escapeJavaScriptString(n) + "\";\n" + v;
+ prefix + parami + ".name=\"" +
+ CMSTemplate.escapeJavaScriptString(n) + "\";\n" + v;
arg.set(parami, new RawJS(rawJS));
}
- } // all others are request attrs from policy or internal modules.
+ } // all others are request attrs from policy or internal
+ // modules.
else {
Object val;
if (req.isSimpleExtDataValue(name)) {
@@ -780,25 +774,25 @@ public class CertReqParser extends ReqParser {
}
String valstr = "";
// hack
- String parami =
- IRequest.SERVER_ATTRS + LB + String.valueOf(saCounter++) + RB;
+ String parami =
+ IRequest.SERVER_ATTRS + LB + String.valueOf(saCounter++) + RB;
valstr = expandValue(prefix + parami + ".value", val);
String rawJS = "new Object;\n\r" +
- prefix + parami + ".name=\"" +
- CMSTemplate.escapeJavaScriptString(name) + "\";\n" +
- valstr; // java string already escaped in expandValue.
+ prefix + parami + ".name=\"" +
+ CMSTemplate.escapeJavaScriptString(name) + "\";\n" +
+ valstr; // java string already escaped in
+ // expandValue.
arg.set(parami, new RawJS(rawJS));
}
}
if (name.equalsIgnoreCase(IRequest.REQUESTOR_PHONE)
- || name.equalsIgnoreCase(IRequest.REQUESTOR_EMAIL)
- || name.equalsIgnoreCase(IRequest.REQUESTOR_COMMENTS)
- || name.equalsIgnoreCase(IRequest.RESULT)
- || name.equalsIgnoreCase(IRequest.REQUEST_TRUSTEDMGR_PRIVILEGE)
- ) {
+ || name.equalsIgnoreCase(IRequest.REQUESTOR_EMAIL)
+ || name.equalsIgnoreCase(IRequest.REQUESTOR_COMMENTS)
+ || name.equalsIgnoreCase(IRequest.RESULT)
+ || name.equalsIgnoreCase(IRequest.REQUEST_TRUSTEDMGR_PRIVILEGE)) {
arg.addStringValue(name, req.getExtDataInString(name));
}
@@ -828,7 +822,7 @@ public class CertReqParser extends ReqParser {
}
if (name.equalsIgnoreCase(IRequest.CERT_INFO)) {
- // Get the certificate info from the request
+ // Get the certificate info from the request
RevokedCertImpl revokedCert[] = req.getExtDataInRevokedCertArray(IRequest.CERT_INFO);
if (mDetails && revokedCert != null) {
@@ -837,7 +831,7 @@ public class CertReqParser extends ReqParser {
IArgBlock rarg = CMS.createArgBlock();
rarg.addBigIntegerValue("serialNumber",
- revokedCert[i].getSerialNumber(), 16);
+ revokedCert[i].getSerialNumber(), 16);
CRLExtensions crlExtensions = revokedCert[i].getExtensions();
@@ -847,19 +841,19 @@ public class CertReqParser extends ReqParser {
if (ext instanceof CRLReasonExtension) {
rarg.addStringValue("reason",
- ((CRLReasonExtension) ext).getReason().toString());
+ ((CRLReasonExtension) ext).getReason().toString());
}
}
} else {
rarg.addStringValue("reason",
- RevocationReason.UNSPECIFIED.toString());
+ RevocationReason.UNSPECIFIED.toString());
}
argSet.addRepeatRecord(rarg);
}
} else {
arg.addBigIntegerValue("serialNumber",
- revokedCert[0].getSerialNumber(), 16);
+ revokedCert[0].getSerialNumber(), 16);
}
}
}
@@ -873,7 +867,7 @@ public class CertReqParser extends ReqParser {
IArgBlock rarg = CMS.createArgBlock();
rarg.addBigIntegerValue("serialNumber",
- oldSerialNo[i], 16);
+ oldSerialNo[i], 16);
argSet.addRepeatRecord(rarg);
}
}
@@ -881,11 +875,11 @@ public class CertReqParser extends ReqParser {
}
if (name.equalsIgnoreCase(IRequest.OLD_CERTS) && mDetails) {
- //X509CertImpl oldCert[] =
- // (X509CertImpl[])req.get(IRequest.OLD_CERTS);
+ // X509CertImpl oldCert[] =
+ // (X509CertImpl[])req.get(IRequest.OLD_CERTS);
Certificate oldCert[] =
- (Certificate[]) req.getExtDataInCertArray(IRequest.OLD_CERTS);
-
+ (Certificate[]) req.getExtDataInCertArray(IRequest.OLD_CERTS);
+
if (oldCert != null && oldCert.length > 0) {
if (oldCert[0] instanceof X509CertImpl) {
X509CertImpl xcert = (X509CertImpl) oldCert[0];
@@ -898,7 +892,7 @@ public class CertReqParser extends ReqParser {
xcert = (X509CertImpl) oldCert[i];
rarg.addBigIntegerValue("serialNumber",
- xcert.getSerialNumber(), 16);
+ xcert.getSerialNumber(), 16);
argSet.addRepeatRecord(rarg);
}
}
@@ -907,9 +901,9 @@ public class CertReqParser extends ReqParser {
}
if (name.equalsIgnoreCase(IRequest.REVOKED_CERTS) && mDetails &&
- req.getRequestType().equals("getRevocationInfo")) {
- RevokedCertImpl revokedCert[] =
- req.getExtDataInRevokedCertArray(IRequest.REVOKED_CERTS);
+ req.getRequestType().equals("getRevocationInfo")) {
+ RevokedCertImpl revokedCert[] =
+ req.getExtDataInRevokedCertArray(IRequest.REVOKED_CERTS);
if (revokedCert != null && revokedCert[0] != null) {
boolean reasonFound = false;
@@ -920,7 +914,7 @@ public class CertReqParser extends ReqParser {
if (ext instanceof CRLReasonExtension) {
arg.addStringValue("reason",
- ((CRLReasonExtension) ext).getReason().toString());
+ ((CRLReasonExtension) ext).getReason().toString());
reasonFound = true;
}
}
@@ -931,5 +925,5 @@ public class CertReqParser extends ReqParser {
}
}
}
-
+
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/request/CheckRequest.java b/pki/base/common/src/com/netscape/cms/servlet/request/CheckRequest.java
index 127f2ce8..ce05b408 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/request/CheckRequest.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/request/CheckRequest.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.request;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
@@ -81,10 +80,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* Check the status of a certificate request
- *
+ *
* @version $Revision$, $Date$
*/
public class CheckRequest extends CMSServlet {
@@ -116,15 +114,15 @@ public class CheckRequest extends CMSServlet {
/**
* Constructs request query servlet.
*/
- public CheckRequest()
- throws EBaseException {
+ public CheckRequest()
+ throws EBaseException {
super();
}
/**
* initialize the servlet. This servlet uses the template file
* "requestStatus.template" to process the response.
- *
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -140,12 +138,12 @@ public class CheckRequest extends CMSServlet {
* Process the HTTP request.
* <ul>
* <li>http.param requestId ID of the request to check
- * <li>http.param format if 'id', then check the request based on
- * the request ID parameter. If set to CMC, then use the
- * 'queryPending' parameter.
+ * <li>http.param format if 'id', then check the request based on the
+ * request ID parameter. If set to CMC, then use the 'queryPending'
+ * parameter.
* <li>http.param queryPending query formatted as a CMC request
* </ul>
- *
+ *
* @param cmsReq the object holding the request and response information
*/
public void process(CMSRequest cmsReq) throws EBaseException {
@@ -166,10 +164,10 @@ public class CheckRequest extends CMSServlet {
mAuthzResourceName, "read");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -187,9 +185,9 @@ public class CheckRequest extends CMSServlet {
form = getTemplate(mFormPath, req, locale);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
IArgBlock header = CMS.createArgBlock();
@@ -212,13 +210,13 @@ public class CheckRequest extends CMSServlet {
isCMCReq = true;
byte[] cmcBlob = CMS.AtoB(queryPending);
ByteArrayInputStream cmcBlobIn =
- new ByteArrayInputStream(cmcBlob);
+ new ByteArrayInputStream(cmcBlob);
org.mozilla.jss.pkix.cms.ContentInfo cii = (org.mozilla.jss.pkix.cms.ContentInfo)
- org.mozilla.jss.pkix.cms.ContentInfo.getTemplate().decode(cmcBlobIn);
+ org.mozilla.jss.pkix.cms.ContentInfo.getTemplate().decode(cmcBlobIn);
SignedData cmcFullReq = (SignedData)
- cii.getInterpretedContent();
-
+ cii.getInterpretedContent();
+
EncapsulatedContentInfo ci = cmcFullReq.getContentInfo();
OBJECT_IDENTIFIER id = ci.getContentType();
@@ -235,7 +233,7 @@ public class CheckRequest extends CMSServlet {
for (int i = 0; i < numControls; i++) {
// decode message.
- TaggedAttribute taggedAttr = (TaggedAttribute) controlSequence.elementAt(i);
+ TaggedAttribute taggedAttr = (TaggedAttribute) controlSequence.elementAt(i);
OBJECT_IDENTIFIER type = taggedAttr.getType();
if (type.equals(OBJECT_IDENTIFIER.id_cmc_QueryPending)) {
@@ -246,18 +244,16 @@ public class CheckRequest extends CMSServlet {
// We only process one for now.
if (numReq > 0) {
OCTET_STRING reqId = (OCTET_STRING)
- ASN1Util.decode(OCTET_STRING.getTemplate(),
- ASN1Util.encode(requestIds.elementAt(0)));
+ ASN1Util.decode(OCTET_STRING.getTemplate(),
+ ASN1Util.encode(requestIds.elementAt(0)));
requestId = new String(reqId.toByteArray());
}
} else if (type.equals(OBJECT_IDENTIFIER.id_cmc_transactionId)) {
transIds = taggedAttr.getValues();
- }else if
- (type.equals(OBJECT_IDENTIFIER.id_cmc_recipientNonce)) {
+ } else if (type.equals(OBJECT_IDENTIFIER.id_cmc_recipientNonce)) {
rNonces = taggedAttr.getValues();
- } else if
- (type.equals(OBJECT_IDENTIFIER.id_cmc_senderNonce)) {
+ } else if (type.equals(OBJECT_IDENTIFIER.id_cmc_senderNonce)) {
sNonces = taggedAttr.getValues();
}
}
@@ -276,7 +272,7 @@ public class CheckRequest extends CMSServlet {
mCACerts = ((ICertAuthority) mAuthority).getCACertChain().getChain();
} catch (Exception e) {
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_CA_CHAIN_NOT_AVAILABLE"));
+ CMS.getUserMessage("CMS_GW_CA_CHAIN_NOT_AVAILABLE"));
}
if (requestId == null || requestId.trim().equals("")) {
@@ -289,34 +285,34 @@ public class CheckRequest extends CMSServlet {
log(ILogger.LL_FAILURE, CMS.getLogMessage("BASE_INVALID_NUMBER_FORMAT_1", requestId));
throw new EBaseException(
CMS.getUserMessage(getLocale(req), "CMS_BASE_INVALID_NUMBER_FORMAT_1", requestId));
- }
+ }
IRequest r = mQueue.findRequest(new RequestId(requestId));
if (r == null) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_REQUEST_ID_NOT_FOUND_1", requestId));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_REQUEST_ID_NOT_FOUND", requestId));
+ CMS.getUserMessage("CMS_GW_REQUEST_ID_NOT_FOUND", requestId));
}
if (authToken != null) {
- // if RA, requestOwner must match the group
- String group = authToken.getInString("group");
- if ((group != null) && (group != "")) {
- if (group.equals("Registration Manager Agents")) {
- boolean groupMatched = false;
- String requestOwner = r.getExtDataInString("requestOwner");
- if (requestOwner != null) {
- if (requestOwner.equals(group))
- groupMatched = true;
- }
- if (groupMatched == false) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("BASE_INVALID_NUMBER_FORMAT_1", requestId.toString()));
- throw new EBaseException(
- CMS.getUserMessage(getLocale(req), "CMS_BASE_INVALID_NUMBER_FORMAT_1", requestId));
- }
+ // if RA, requestOwner must match the group
+ String group = authToken.getInString("group");
+ if ((group != null) && (group != "")) {
+ if (group.equals("Registration Manager Agents")) {
+ boolean groupMatched = false;
+ String requestOwner = r.getExtDataInString("requestOwner");
+ if (requestOwner != null) {
+ if (requestOwner.equals(group))
+ groupMatched = true;
+ }
+ if (groupMatched == false) {
+ log(ILogger.LL_FAILURE, CMS.getLogMessage("BASE_INVALID_NUMBER_FORMAT_1", requestId.toString()));
+ throw new EBaseException(
+ CMS.getUserMessage(getLocale(req), "CMS_BASE_INVALID_NUMBER_FORMAT_1", requestId));
+ }
+ }
}
- }
}
RequestStatus status = r.getRequestStatus();
@@ -327,35 +323,35 @@ public class CheckRequest extends CMSServlet {
header.addStringValue(STATUS, status.toString());
header.addLongValue(CREATE_ON, r.getCreationTime().getTime() / 1000);
header.addLongValue(UPDATE_ON, r.getModificationTime().getTime() / 1000);
- if (note != null && note.length() > 0)
+ if (note != null && note.length() > 0)
header.addStringValue("requestNotes", note);
String type = r.getRequestType();
Integer result = r.getExtDataInInteger(IRequest.RESULT);
-/* if (type.equals(IRequest.ENROLLMENT_REQUEST) && (r.get("profile") != null) && status.equals(RequestStatus.COMPLETE)) {
- X509CertImpl cert = (X509CertImpl) r.get(IEnrollProfile.REQUEST_ISSUED_CERT);
- IArgBlock rarg = CMS.createArgBlock();
-
- rarg.addBigIntegerValue("serialNumber",
- cert.getSerialNumber(), 16);
- argSet.addRepeatRecord(rarg);
- }
-*/
+ /*
+ * if (type.equals(IRequest.ENROLLMENT_REQUEST) && (r.get("profile") !=
+ * null) && status.equals(RequestStatus.COMPLETE)) { X509CertImpl cert =
+ * (X509CertImpl) r.get(IEnrollProfile.REQUEST_ISSUED_CERT); IArgBlock
+ * rarg = CMS.createArgBlock();
+ *
+ * rarg.addBigIntegerValue("serialNumber", cert.getSerialNumber(), 16);
+ * argSet.addRepeatRecord(rarg); }
+ */
String profileId = r.getExtDataInString("profileId");
if (profileId != null) {
- result = IRequest.RES_SUCCESS;
+ result = IRequest.RES_SUCCESS;
}
if ((type != null) && (type.equals(IRequest.ENROLLMENT_REQUEST) ||
- type.equals(IRequest.RENEWAL_REQUEST)) && (status != null) &&
- status.equals(RequestStatus.COMPLETE) && (result != null) &&
- result.equals(IRequest.RES_SUCCESS)) {
+ type.equals(IRequest.RENEWAL_REQUEST)) && (status != null) &&
+ status.equals(RequestStatus.COMPLETE) && (result != null) &&
+ result.equals(IRequest.RES_SUCCESS)) {
Object o = r.getExtDataInCertArray(IRequest.ISSUED_CERTS);
if (profileId != null) {
- X509CertImpl impl[] = new X509CertImpl[1];
- impl[0] = r.getExtDataInCert(IEnrollProfile.REQUEST_ISSUED_CERT);
- o = impl;
+ X509CertImpl impl[] = new X509CertImpl[1];
+ impl[0] = r.getExtDataInCert(IEnrollProfile.REQUEST_ISSUED_CERT);
+ o = impl;
}
if (o != null && (o instanceof X509CertImpl[])) {
X509CertImpl[] certs = (X509CertImpl[]) o;
@@ -366,11 +362,12 @@ public class CheckRequest extends CMSServlet {
IArgBlock rarg = CMS.createArgBlock();
rarg.addBigIntegerValue("serialNumber",
- certs[i].getSerialNumber(), 16);
+ certs[i].getSerialNumber(), 16);
// add pkcs7 cert for importing
if (importCert || isCMCReq) {
- //byte[] ba = certs[i].getEncoded();
- X509CertImpl[] certsInChain = new X509CertImpl[1];;
+ // byte[] ba = certs[i].getEncoded();
+ X509CertImpl[] certsInChain = new X509CertImpl[1];
+ ;
if (mCACerts != null) {
for (int ii = 0; ii < mCACerts.length; ii++) {
if (certs[i].equals(mCACerts[ii])) {
@@ -381,10 +378,10 @@ public class CheckRequest extends CMSServlet {
certsInChain = new X509CertImpl[mCACerts.length + 1];
}
}
-
+
// Set the EE cert
certsInChain[0] = certs[i];
-
+
// Set the Ca certificate chain
if (mCACerts != null) {
for (int ii = 0; ii < mCACerts.length; ii++) {
@@ -396,7 +393,7 @@ public class CheckRequest extends CMSServlet {
String p7Str;
try {
- PKCS7 p7 = new PKCS7(new AlgorithmId[0],
+ PKCS7 p7 = new PKCS7(new AlgorithmId[0],
new netscape.security.pkcs.ContentInfo(new byte[0]),
certsInChain,
new netscape.security.pkcs.SignerInfo[0]);
@@ -407,7 +404,7 @@ public class CheckRequest extends CMSServlet {
p7Str = CMS.BtoA(p7Bytes);
- StringTokenizer tokenizer = null;
+ StringTokenizer tokenizer = null;
if (File.separator.equals("\\")) {
char[] nl = new char[2];
@@ -438,14 +435,14 @@ public class CheckRequest extends CMSServlet {
if (bodyPartId != null)
bpids.addElement(bodyPartId);
CMCStatusInfo cmcStatusInfo = new
- CMCStatusInfo(CMCStatusInfo.SUCCESS, bpids);
+ CMCStatusInfo(CMCStatusInfo.SUCCESS, bpids);
TaggedAttribute ta = new TaggedAttribute(new
INTEGER(bpid++),
OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo,
cmcStatusInfo);
controlSeq.addElement(ta);
-
+
// copy transactionID, senderNonce,
// create recipientNonce
if (transIds != null) {
@@ -455,7 +452,7 @@ public class CheckRequest extends CMSServlet {
transIds);
controlSeq.addElement(ta);
}
-
+
if (sNonces != null) {
ta = new TaggedAttribute(new
INTEGER(bpid++),
@@ -463,7 +460,7 @@ public class CheckRequest extends CMSServlet {
sNonces);
controlSeq.addElement(ta);
}
-
+
String salt = CMSServlet.generateSalt();
byte[] dig;
@@ -475,42 +472,42 @@ public class CheckRequest extends CMSServlet {
dig = salt.getBytes();
}
String b64E = CMS.BtoA(dig);
- String[] newNonce = {b64E};
+ String[] newNonce = { b64E };
ta = new TaggedAttribute(new
INTEGER(bpid++),
OBJECT_IDENTIFIER.id_cmc_senderNonce,
new OCTET_STRING(newNonce[0].getBytes()));
controlSeq.addElement(ta);
-
+
ResponseBody rb = new ResponseBody(controlSeq, new
SEQUENCE(), new
SEQUENCE());
EncapsulatedContentInfo ci = new
- EncapsulatedContentInfo(OBJECT_IDENTIFIER.id_cct_PKIResponse,
- rb);
-
+ EncapsulatedContentInfo(OBJECT_IDENTIFIER.id_cct_PKIResponse,
+ rb);
+
org.mozilla.jss.crypto.X509Certificate x509cert = null;
if (mAuthority instanceof ICertificateAuthority) {
x509cert = ((ICertificateAuthority) mAuthority).getCaX509Cert();
- }else if (mAuthority instanceof IRegistrationAuthority) {
+ } else if (mAuthority instanceof IRegistrationAuthority) {
x509cert = ((IRegistrationAuthority) mAuthority).getRACert();
}
if (x509cert == null)
- throw new
- ECMSGWException(CMS.getUserMessage("CMS_GW_CMC_ERROR", "No signing cert found."));
+ throw new ECMSGWException(CMS.getUserMessage("CMS_GW_CMC_ERROR", "No signing cert found."));
X509CertImpl cert = new X509CertImpl(x509cert.getEncoded());
ByteArrayInputStream issuer1 = new
- ByteArrayInputStream(((X500Name) cert.getIssuerDN()).getEncoded());
+ ByteArrayInputStream(((X500Name) cert.getIssuerDN()).getEncoded());
Name issuer = (Name) Name.getTemplate().decode(issuer1);
IssuerAndSerialNumber ias = new
- IssuerAndSerialNumber(issuer, new INTEGER(cert.getSerialNumber().toString()));
+ IssuerAndSerialNumber(issuer, new INTEGER(cert.getSerialNumber().toString()));
SignerIdentifier si = new
- SignerIdentifier(SignerIdentifier.ISSUER_AND_SERIALNUMBER, ias, null);
-
- // SHA1 is the default digest Alg for now.
+ SignerIdentifier(SignerIdentifier.ISSUER_AND_SERIALNUMBER, ias, null);
+
+ // SHA1 is the default digest Alg for
+ // now.
DigestAlgorithm digestAlg = null;
SignatureAlgorithm signAlg = null;
org.mozilla.jss.crypto.PrivateKey privKey = CryptoManager.getInstance().findPrivKeyByCert(x509cert);
@@ -518,7 +515,7 @@ public class CheckRequest extends CMSServlet {
if (keyType.equals(org.mozilla.jss.crypto.PrivateKey.RSA))
signAlg = SignatureAlgorithm.RSASignatureWithSHA1Digest;
- else if (keyType.equals(org.mozilla.jss.crypto.PrivateKey.DSA))
+ else if (keyType.equals(org.mozilla.jss.crypto.PrivateKey.DSA))
signAlg = SignatureAlgorithm.DSASignatureWithSHA1Digest;
MessageDigest SHADigest = null;
byte[] digest = null;
@@ -531,46 +528,46 @@ public class CheckRequest extends CMSServlet {
rb.encode((OutputStream) ostream);
digest = SHADigest.digest(ostream.toByteArray());
} catch (NoSuchAlgorithmException ex) {
- //log("digest fail");
+ // log("digest fail");
}
-
+
org.mozilla.jss.pkix.cms.SignerInfo signInfo = new
- org.mozilla.jss.pkix.cms.SignerInfo(si, null, null,
- OBJECT_IDENTIFIER.id_cct_PKIResponse,
- digest, signAlg,
- privKey);
+ org.mozilla.jss.pkix.cms.SignerInfo(si, null, null,
+ OBJECT_IDENTIFIER.id_cct_PKIResponse,
+ digest, signAlg,
+ privKey);
SET signInfos = new SET();
signInfos.addElement(signInfo);
-
+
SET digestAlgs = new SET();
if (digestAlg != null) {
AlgorithmIdentifier ai = new
- AlgorithmIdentifier(digestAlg.toOID(),
- null);
+ AlgorithmIdentifier(digestAlg.toOID(),
+ null);
digestAlgs.addElement(ai);
}
-
+
SET jsscerts = new SET();
for (int j = 0; j < certsInChain.length; j++) {
ByteArrayInputStream is = new
- ByteArrayInputStream(certsInChain[j].getEncoded());
+ ByteArrayInputStream(certsInChain[j].getEncoded());
org.mozilla.jss.pkix.cert.Certificate certJss = (org.mozilla.jss.pkix.cert.Certificate)
- org.mozilla.jss.pkix.cert.Certificate.getTemplate().decode(is);
+ org.mozilla.jss.pkix.cert.Certificate.getTemplate().decode(is);
jsscerts.addElement(certJss);
}
-
+
SignedData fResponse = new
- SignedData(digestAlgs, ci,
- jsscerts, null, signInfos);
+ SignedData(digestAlgs, ci,
+ jsscerts, null, signInfos);
org.mozilla.jss.pkix.cms.ContentInfo fullResponse = new
- org.mozilla.jss.pkix.cms.ContentInfo(org.mozilla.jss.pkix.cms.ContentInfo.SIGNED_DATA, fResponse);
+ org.mozilla.jss.pkix.cms.ContentInfo(org.mozilla.jss.pkix.cms.ContentInfo.SIGNED_DATA, fResponse);
ByteArrayOutputStream ostream = new
- ByteArrayOutputStream();
+ ByteArrayOutputStream();
fullResponse.encode((OutputStream) ostream);
byte[] fr = ostream.toByteArray();
@@ -579,10 +576,10 @@ public class CheckRequest extends CMSServlet {
}
} catch (Exception e) {
e.printStackTrace();
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_FORMING_PKCS7_1", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERROR_FORMING_PKCS7_1", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_FORMING_PKCS7_ERROR"));
+ CMS.getUserMessage("CMS_GW_FORMING_PKCS7_ERROR"));
}
}
argSet.addRepeatRecord(rarg);
@@ -598,11 +595,11 @@ public class CheckRequest extends CMSServlet {
if (error == null) {
String xmlOutput = req.getParameter("xml");
if (xmlOutput != null && xmlOutput.equals("true")) {
- outputXML(resp, argSet);
+ outputXML(resp, argSet);
} else {
- resp.setContentType("text/html");
- form.renderOutput(out, argSet);
- cmsReq.setStatus(CMSRequest.SUCCESS);
+ resp.setContentType("text/html");
+ form.renderOutput(out, argSet);
+ cmsReq.setStatus(CMSRequest.SUCCESS);
}
} else {
cmsReq.setStatus(CMSRequest.ERROR);
@@ -610,10 +607,9 @@ public class CheckRequest extends CMSServlet {
}
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/request/IReqParser.java b/pki/base/common/src/com/netscape/cms/servlet/request/IReqParser.java
index 0e3974a1..99e7d14d 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/request/IReqParser.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/request/IReqParser.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.request;
-
import java.util.Locale;
import com.netscape.certsrv.base.EBaseException;
@@ -25,13 +24,11 @@ import com.netscape.certsrv.base.IArgBlock;
import com.netscape.certsrv.request.IRequest;
import com.netscape.cms.servlet.common.CMSTemplateParams;
-
/**
- * An interface representing a request parser which
- * converts Java request object into name value
- * pairs and vice versa.
+ * An interface representing a request parser which converts Java request object
+ * into name value pairs and vice versa.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public interface IReqParser {
@@ -40,5 +37,5 @@ public interface IReqParser {
* Maps request object into argument block.
*/
public void fillRequestIntoArg(Locale l, IRequest req, CMSTemplateParams argSet, IArgBlock arg)
- throws EBaseException;
+ throws EBaseException;
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/request/KeyReqParser.java b/pki/base/common/src/com/netscape/cms/servlet/request/KeyReqParser.java
index 459aca63..b7ddc16d 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/request/KeyReqParser.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/request/KeyReqParser.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.request;
-
import java.math.BigInteger;
import java.util.Locale;
@@ -29,10 +28,9 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.key.KeyRecordParser;
-
/**
* Output a 'pretty print' of a Key Archival request
- *
+ *
* @version $Revision$, $Date$
*/
public class KeyReqParser extends ReqParser {
@@ -50,7 +48,7 @@ public class KeyReqParser extends ReqParser {
* Fills in certificate specific request attributes.
*/
public void fillRequestIntoArg(Locale l, IRequest req, CMSTemplateParams argSet, IArgBlock arg)
- throws EBaseException {
+ throws EBaseException {
// fill in the standard attributes
super.fillRequestIntoArg(l, req, argSet, arg);
@@ -58,7 +56,7 @@ public class KeyReqParser extends ReqParser {
if (type.equals(IRequest.ENROLLMENT_REQUEST)) {
BigInteger recSerialNo = req.getExtDataInBigInteger("keyRecord");
- IKeyRecoveryAuthority kra = (IKeyRecoveryAuthority)CMS.getSubsystem("kra");
+ IKeyRecoveryAuthority kra = (IKeyRecoveryAuthority) CMS.getSubsystem("kra");
if (kra != null) {
KeyRecordParser.fillRecordIntoArg(
kra.getKeyRepository().readKeyRecord(recSerialNo),
diff --git a/pki/base/common/src/com/netscape/cms/servlet/request/ProcessCertReq.java b/pki/base/common/src/com/netscape/cms/servlet/request/ProcessCertReq.java
index d19c7714..023e52f1 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/request/ProcessCertReq.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/request/ProcessCertReq.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.request;
-
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
@@ -79,12 +78,10 @@ import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
import com.netscape.cms.servlet.common.ICMSTemplateFiller;
-
/**
- * Agent operations on Certificate requests. This servlet is used
- * by an Agent to approve, reject, reassign, or change a certificate
- * request.
- *
+ * Agent operations on Certificate requests. This servlet is used by an Agent to
+ * approve, reject, reassign, or change a certificate request.
+ *
* @version $Revision$, $Date$
*/
public class ProcessCertReq extends CMSServlet {
@@ -105,101 +102,92 @@ public class ProcessCertReq extends CMSServlet {
private boolean mExtraAgentParams = false;
// for RA only since it does not have a database.
- private final static String
- REQ_COMPLETED_TEMPLATE = "ra/RequestCompleted.template";
- private final static String
- PROP_REQ_COMPLETED_TEMPLATE = "requestCompletedTemplate";
- private final static String
- PROP_EXTRA_AGENT_PARAMS = "extraAgentParams";
- private static ICMSTemplateFiller
- REQ_COMPLETED_FILLER = new RAReqCompletedFiller();
+ private final static String REQ_COMPLETED_TEMPLATE = "ra/RequestCompleted.template";
+ private final static String PROP_REQ_COMPLETED_TEMPLATE = "requestCompletedTemplate";
+ private final static String PROP_EXTRA_AGENT_PARAMS = "extraAgentParams";
+ private static ICMSTemplateFiller REQ_COMPLETED_FILLER = new RAReqCompletedFiller();
private String mReqCompletedTemplate = null;
- private final static String
- CERT_TYPE = "certType";
+ private final static String CERT_TYPE = "certType";
private String auditServiceID = ILogger.UNIDENTIFIED;
private final static String AGENT_CA_CLONE_ENROLLMENT_SERVLET =
- "caProcessCertReq";
+ "caProcessCertReq";
private final static String AGENT_RA_CLONE_ENROLLMENT_SERVLET =
- "raProcessCertReq";
+ "raProcessCertReq";
private final static String SIGNED_AUDIT_ACCEPTANCE = "accept";
private final static String SIGNED_AUDIT_CANCELLATION = "cancel";
private final static String SIGNED_AUDIT_CLONING = "clone";
private final static String SIGNED_AUDIT_REJECTION = "reject";
private final static byte EOL[] = { Character.LINE_SEPARATOR };
- private final static String[]
- SIGNED_AUDIT_MANUAL_CANCELLATION_REASON = new String[] {
-
- /* 0 */ "manual non-profile cert request cancellation: "
+ private final static String[] SIGNED_AUDIT_MANUAL_CANCELLATION_REASON = new String[] {
+
+ /* 0 */"manual non-profile cert request cancellation: "
+ "request cannot be processed due to an "
+ "authorization failure",
-
- /* 1 */ "manual non-profile cert request cancellation: "
+
+ /* 1 */"manual non-profile cert request cancellation: "
+ "no reason has been given for cancelling this "
+ "cert request",
-
- /* 2 */ "manual non-profile cert request cancellation: "
+
+ /* 2 */"manual non-profile cert request cancellation: "
+ "indeterminate reason for inability to process "
+ "cert request due to an EBaseException",
-
- /* 3 */ "manual non-profile cert request cancellation: "
+
+ /* 3 */"manual non-profile cert request cancellation: "
+ "indeterminate reason for inability to process "
+ "cert request due to an IOException",
-
- /* 4 */ "manual non-profile cert request cancellation: "
+
+ /* 4 */"manual non-profile cert request cancellation: "
+ "indeterminate reason for inability to process "
+ "cert request due to a CertificateException",
-
- /* 5 */ "manual non-profile cert request cancellation: "
+
+ /* 5 */"manual non-profile cert request cancellation: "
+ "indeterminate reason for inability to process "
+ "cert request due to a NoSuchAlgorithmException"
};
- private final static String[]
- SIGNED_AUDIT_MANUAL_REJECTION_REASON = new String[] {
-
- /* 0 */ "manual non-profile cert request rejection: "
+ private final static String[] SIGNED_AUDIT_MANUAL_REJECTION_REASON = new String[] {
+
+ /* 0 */"manual non-profile cert request rejection: "
+ "request cannot be processed due to an "
+ "authorization failure",
-
- /* 1 */ "manual non-profile cert request rejection: "
+
+ /* 1 */"manual non-profile cert request rejection: "
+ "no reason has been given for rejecting this "
+ "cert request",
-
- /* 2 */ "manual non-profile cert request rejection: "
+
+ /* 2 */"manual non-profile cert request rejection: "
+ "indeterminate reason for inability to process "
+ "cert request due to an EBaseException",
-
- /* 3 */ "manual non-profile cert request rejection: "
+
+ /* 3 */"manual non-profile cert request rejection: "
+ "indeterminate reason for inability to process "
+ "cert request due to an IOException",
-
- /* 4 */ "manual non-profile cert request rejection: "
+
+ /* 4 */"manual non-profile cert request rejection: "
+ "indeterminate reason for inability to process "
+ "cert request due to a CertificateException",
-
- /* 5 */ "manual non-profile cert request rejection: "
+
+ /* 5 */"manual non-profile cert request rejection: "
+ "indeterminate reason for inability to process "
+ "cert request due to a NoSuchAlgorithmException"
};
- private final static String
- LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST =
- "LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST_5";
- private final static String
- LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED =
- "LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED_5";
+ private final static String LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST =
+ "LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST_5";
+ private final static String LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED =
+ "LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED_5";
/**
* Process request.
*/
public ProcessCertReq()
- throws EBaseException {
+ throws EBaseException {
super();
}
/**
* initialize the servlet. This servlet uses the template file
* "processCertReq.template" to process the response.
- *
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -212,8 +200,8 @@ public class ProcessCertReq extends CMSServlet {
if (id != null) {
if (!(auditServiceID.equals(
AGENT_CA_CLONE_ENROLLMENT_SERVLET))
- && !(auditServiceID.equals(
- AGENT_RA_CLONE_ENROLLMENT_SERVLET))) {
+ && !(auditServiceID.equals(
+ AGENT_RA_CLONE_ENROLLMENT_SERVLET))) {
auditServiceID = ILogger.UNIDENTIFIED;
} else {
auditServiceID = id.trim();
@@ -228,7 +216,7 @@ public class ProcessCertReq extends CMSServlet {
mParser = CertReqParser.DETAIL_PARSER;
- // override success and error templates to null -
+ // override success and error templates to null -
// handle templates locally.
mTemplates.remove(CMSRequest.SUCCESS);
@@ -252,25 +240,24 @@ public class ProcessCertReq extends CMSServlet {
}
}
-
/**
* Process the HTTP request.
* <ul>
- * <li>http.param seqNum request id
- * <li>http.param notValidBefore certificate validity
- * - notBefore - in seconds since jan 1, 1970
- * <li>http.param notValidAfter certificate validity
- * - notAfter - in seconds since jan 1, 1970
- * <li>http.param subject certificate subject name
- * <li>http.param toDo requested action
- * (can be one of: clone, reject, accept, cancel)
+ * <li>http.param seqNum request id
+ * <li>http.param notValidBefore certificate validity - notBefore - in
+ * seconds since jan 1, 1970
+ * <li>http.param notValidAfter certificate validity - notAfter - in seconds
+ * since jan 1, 1970
+ * <li>http.param subject certificate subject name
+ * <li>http.param toDo requested action (can be one of: clone, reject,
+ * accept, cancel)
* <li>http.param signatureAlgorithm certificate signing algorithm
- * <li>http.param addExts base-64, DER encoded Extension or
- * SEQUENCE OF Extensions to add to certificate
- * <li>http.param pathLenConstraint integer path length constraint to
- * use in BasicConstraint extension if applicable
+ * <li>http.param addExts base-64, DER encoded Extension or SEQUENCE OF
+ * Extensions to add to certificate
+ * <li>http.param pathLenConstraint integer path length constraint to use in
+ * BasicConstraint extension if applicable
* </ul>
- *
+ *
* @param cmsReq the object holding the request and response information
*/
public void process(CMSRequest cmsReq) throws EBaseException {
@@ -297,15 +284,15 @@ public class ProcessCertReq extends CMSServlet {
form = getTemplate(mFormPath, req, locale);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
try {
if (req.getParameter(SEQNUM) != null) {
CMS.debug(
- "ProcessCertReq: parameter seqNum " + req.getParameter(SEQNUM));
+ "ProcessCertReq: parameter seqNum " + req.getParameter(SEQNUM));
seqNum = Integer.parseInt(req.getParameter(SEQNUM));
}
String notValidBeforeStr = req.getParameter("notValidBefore");
@@ -326,7 +313,6 @@ public class ProcessCertReq extends CMSServlet {
subject = req.getParameter("subject");
signatureAlgorithm = req.getParameter("signatureAlgorithm");
-
IRequest r = null;
if (seqNum > -1) {
@@ -334,23 +320,22 @@ public class ProcessCertReq extends CMSServlet {
Integer.toString(seqNum)));
}
- if(seqNum > -1 && r != null)
- {
+ if (seqNum > -1 && r != null) {
processX509(cmsReq, argSet, header, seqNum, req, resp,
- toDo, signatureAlgorithm, subject,
- notValidBefore, notValidAfter, locale[0], startTime);
+ toDo, signatureAlgorithm, subject,
+ notValidBefore, notValidAfter, locale[0], startTime);
} else {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_INVALID_REQUEST_ID_1", String.valueOf(seqNum)));
error = new ECMSGWException(
- CMS.getUserMessage("CMS_GW_INVALID_REQUEST_ID",
- String.valueOf(seqNum)));
+ CMS.getUserMessage("CMS_GW_INVALID_REQUEST_ID",
+ String.valueOf(seqNum)));
}
} catch (EBaseException e) {
error = e;
} catch (NumberFormatException e) {
log(ILogger.LL_FAILURE, "Error " + e);
- error = new EBaseException(CMS.getUserMessage(getLocale(req),"CMS_BASE_INVALID_NUMBER_FORMAT"));
- }
+ error = new EBaseException(CMS.getUserMessage(getLocale(req), "CMS_BASE_INVALID_NUMBER_FORMAT"));
+ }
try {
ServletOutputStream out = resp.getOutputStream();
@@ -358,46 +343,47 @@ public class ProcessCertReq extends CMSServlet {
if (error == null) {
String xmlOutput = req.getParameter("xml");
if (xmlOutput != null && xmlOutput.equals("true")) {
- outputXML(resp, argSet);
+ outputXML(resp, argSet);
} else {
- String output = form.getOutput(argSet);
- resp.setContentType("text/html");
- form.renderOutput(out, argSet);
- cmsReq.setStatus(CMSRequest.SUCCESS);
+ String output = form.getOutput(argSet);
+ resp.setContentType("text/html");
+ form.renderOutput(out, argSet);
+ cmsReq.setStatus(CMSRequest.SUCCESS);
}
} else {
cmsReq.setStatus(CMSRequest.ERROR);
cmsReq.setError(error);
}
-
+
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
+ CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
return;
}
/**
* Process X509 certificate enrollment request and send request information
- * to the caller.
+ * to the caller.
* <P>
- *
+ *
* (Certificate Request - an "agent" cert request for "cloning")
* <P>
- *
- * (Certificate Request Processed - either a manual "agent" non-profile
- * based cert acceptance, a manual "agent" non-profile based cert
- * cancellation, or a manual "agent" non-profile based cert rejection)
+ *
+ * (Certificate Request Processed - either a manual "agent" non-profile
+ * based cert acceptance, a manual "agent" non-profile based cert
+ * cancellation, or a manual "agent" non-profile based cert rejection)
* <P>
- *
+ *
* <ul>
- * <li>signed.audit LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST used when a
- * non-profile cert request is made (before approval process)
+ * <li>signed.audit LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST used when
+ * a non-profile cert request is made (before approval process)
* <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED used when a
* certificate request has just been through the approval process
* </ul>
+ *
* @param cmsReq a certificate enrollment request
* @param argSet CMS template parameters
* @param header argument block
@@ -405,26 +391,26 @@ public class ProcessCertReq extends CMSServlet {
* @param req HTTP servlet request
* @param resp HTTP servlet response
* @param toDo string representing the requested action (can be one of:
- * clone, reject, accept, cancel)
+ * clone, reject, accept, cancel)
* @param signatureAlgorithm string containing the signature algorithm
* @param subject string containing the subject name of the certificate
- * @param notValidBefore certificate validity - notBefore - in seconds
- * since Jan 1, 1970
+ * @param notValidBefore certificate validity - notBefore - in seconds since
+ * Jan 1, 1970
* @param notValidAfter certificate validity - notAfter - in seconds since
- * Jan 1, 1970
+ * Jan 1, 1970
* @param locale the system locale
* @param startTime the current date
* @exception EBaseException an error has occurred
*/
private void processX509(CMSRequest cmsReq,
- CMSTemplateParams argSet, IArgBlock header,
- int seqNum, HttpServletRequest req,
- HttpServletResponse resp,
- String toDo, String signatureAlgorithm,
- String subject,
- long notValidBefore, long notValidAfter,
- Locale locale, long startTime)
- throws EBaseException {
+ CMSTemplateParams argSet, IArgBlock header,
+ int seqNum, HttpServletRequest req,
+ HttpServletResponse resp,
+ String toDo, String signatureAlgorithm,
+ String subject,
+ long notValidBefore, long notValidAfter,
+ Locale locale, long startTime)
+ throws EBaseException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
String auditRequesterID = ILogger.UNIDENTIFIED;
@@ -434,10 +420,10 @@ public class ProcessCertReq extends CMSServlet {
// "normalize" the "auditCertificateSubjectName"
if (auditCertificateSubjectName != null) {
- // NOTE: This is ok even if the cert subject name is "" (empty)!
+ // NOTE: This is ok even if the cert subject name is "" (empty)!
auditCertificateSubjectName = auditCertificateSubjectName.trim();
} else {
- // NOTE: Here, the cert subject name is MISSING, not "" (empty)!
+ // NOTE: Here, the cert subject name is MISSING, not "" (empty)!
auditCertificateSubjectName = ILogger.SIGNED_AUDIT_EMPTY_VALUE;
}
@@ -453,7 +439,7 @@ public class ProcessCertReq extends CMSServlet {
}
}
- if (mAuthority != null)
+ if (mAuthority != null)
header.addStringValue("authorityid", mAuthority.getId());
if (toDo != null) {
@@ -466,12 +452,12 @@ public class ProcessCertReq extends CMSServlet {
mAuthzResourceName, "execute");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE",
- e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE",
+ e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE",
- e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE",
+ e.toString()));
}
if (authzToken == null) {
@@ -546,71 +532,72 @@ public class ProcessCertReq extends CMSServlet {
int alterationCounter = 0;
for (int i = 0; i < certInfo.length; i++) {
- CertificateAlgorithmId certAlgId =
- (CertificateAlgorithmId)
- certInfo[i].get(X509CertInfo.ALGORITHM_ID);
+ CertificateAlgorithmId certAlgId =
+ (CertificateAlgorithmId)
+ certInfo[i].get(X509CertInfo.ALGORITHM_ID);
AlgorithmId algId = (AlgorithmId)
- certAlgId.get(CertificateAlgorithmId.ALGORITHM);
+ certAlgId.get(CertificateAlgorithmId.ALGORITHM);
if (!(algId.getName().equals(signatureAlgorithm))) {
alterationCounter++;
AlgorithmId newAlgId = AlgorithmId.getAlgorithmId(signatureAlgorithm);
certInfo[i].set(X509CertInfo.ALGORITHM_ID,
- new CertificateAlgorithmId(newAlgId));
+ new CertificateAlgorithmId(newAlgId));
}
- CertificateSubjectName certSubject =
- (CertificateSubjectName)
- certInfo[i].get(X509CertInfo.SUBJECT);
+ CertificateSubjectName certSubject =
+ (CertificateSubjectName)
+ certInfo[i].get(X509CertInfo.SUBJECT);
- if (subject != null &&
- !(certSubject.toString().equals(subject))) {
+ if (subject != null &&
+ !(certSubject.toString().equals(subject))) {
alterationCounter++;
certInfo[i].set(X509CertInfo.SUBJECT,
- new CertificateSubjectName(
- (new X500Name(subject))));
+ new CertificateSubjectName(
+ (new X500Name(subject))));
}
- CertificateValidity certValidity =
- (CertificateValidity)
- certInfo[i].get(X509CertInfo.VALIDITY);
+ CertificateValidity certValidity =
+ (CertificateValidity)
+ certInfo[i].get(X509CertInfo.VALIDITY);
Date currentTime = CMS.getCurrentDate();
boolean validityChanged = false;
- // only override these values if agent specified them
+ // only override these values if agent specified
+ // them
if (notValidBefore > 0) {
Date notBefore = (Date) certValidity.get(
CertificateValidity.NOT_BEFORE);
if (notBefore.getTime() == 0 ||
- notBefore.getTime() != notValidBefore) {
+ notBefore.getTime() != notValidBefore) {
Date validFrom = new Date(notValidBefore);
notBefore = (notValidBefore == 0) ? currentTime : validFrom;
certValidity.set(CertificateValidity.NOT_BEFORE,
- notBefore);
+ notBefore);
validityChanged = true;
}
}
if (notValidAfter > 0) {
Date validTo = new Date(notValidAfter);
Date notAfter = (Date)
- certValidity.get(CertificateValidity.NOT_AFTER);
+ certValidity.get(CertificateValidity.NOT_AFTER);
if (notAfter.getTime() == 0 ||
- notAfter.getTime() != notValidAfter) {
+ notAfter.getTime() != notValidAfter) {
notAfter = currentTime;
notAfter = (notValidAfter == 0) ? currentTime : validTo;
certValidity.set(CertificateValidity.NOT_AFTER,
- notAfter);
+ notAfter);
validityChanged = true;
}
}
if (validityChanged) {
- // this set() trigger this rebuild of internal
+ // this set() trigger this rebuild of internal
// raw der encoding cache of X509CertInfo.
// Otherwise, the above change wont have effect.
certInfo[i].set(X509CertInfo.VALIDITY, certValidity);
@@ -618,8 +605,8 @@ public class ProcessCertReq extends CMSServlet {
if (certInfo[i].get(X509CertInfo.VERSION) == null) {
certInfo[i].set(X509CertInfo.VERSION,
- new CertificateVersion(
- CertificateVersion.V3));
+ new CertificateVersion(
+ CertificateVersion.V3));
}
CertificateExtensions extensions = null;
@@ -639,7 +626,8 @@ public class ProcessCertReq extends CMSServlet {
byte[] b = (byte[]) (com.netscape.osutil.OSUtil.AtoB(addExts));
- // this b can be "Extension" Or "SEQUENCE OF Extension"
+ // this b can be "Extension" Or
+ // "SEQUENCE OF Extension"
try {
DerValue b_der = new DerValue(b);
@@ -669,14 +657,14 @@ public class ProcessCertReq extends CMSServlet {
if (extensions != null) {
try {
- NSCertTypeExtension nsExtensions =
- (NSCertTypeExtension)
- extensions.get(
- NSCertTypeExtension.class.getSimpleName());
+ NSCertTypeExtension nsExtensions =
+ (NSCertTypeExtension)
+ extensions.get(
+ NSCertTypeExtension.class.getSimpleName());
if (nsExtensions != null) {
updateNSExtension(req, nsExtensions);
- }
+ }
} catch (IOException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERROR_PROCESS_NETSCAPE_EXTENSION", e.toString()));
}
@@ -686,20 +674,20 @@ public class ProcessCertReq extends CMSServlet {
if (pathLength != null) {
try {
int pathLen = Integer.parseInt(pathLength);
- BasicConstraintsExtension bcExt =
- (BasicConstraintsExtension)
- extensions.get(
- BasicConstraintsExtension.class.getSimpleName());
+ BasicConstraintsExtension bcExt =
+ (BasicConstraintsExtension)
+ extensions.get(
+ BasicConstraintsExtension.class.getSimpleName());
if (bcExt != null) {
Integer bcPathLen = (Integer) bcExt.get(BasicConstraintsExtension.PATH_LEN);
Boolean isCA = (Boolean) bcExt.get(BasicConstraintsExtension.IS_CA);
if (bcPathLen != null &&
- bcPathLen.intValue() != pathLen &&
- isCA != null) {
+ bcPathLen.intValue() != pathLen &&
+ isCA != null) {
BasicConstraintsExtension bcExt0 =
- new BasicConstraintsExtension(isCA.booleanValue(), pathLen);
+ new BasicConstraintsExtension(isCA.booleanValue(), pathLen);
extensions.delete(BasicConstraintsExtension.class.getSimpleName());
extensions.set(BasicConstraintsExtension.class.getSimpleName(), (Extension) bcExt0);
@@ -775,7 +763,7 @@ public class ProcessCertReq extends CMSServlet {
if (mExtraAgentParams) {
@SuppressWarnings("unchecked")
- Enumeration<String> extraparams = req.getParameterNames();
+ Enumeration<String> extraparams = req.getParameterNames();
int l = IRequest.AGENT_PARAMS.length() + 1;
int ap_counter = 0;
Hashtable<String, String> agentparamsargblock = new Hashtable<String, String>();
@@ -802,7 +790,7 @@ public class ProcessCertReq extends CMSServlet {
}
}
- // this set() trigger this rebuild of internal
+ // this set() trigger this rebuild of internal
// raw der encoding cache of X509CertInfo.
// Otherwise, the above change wont have effect.
certInfo[i].set(X509CertInfo.EXTENSIONS, extensions);
@@ -819,100 +807,100 @@ public class ProcessCertReq extends CMSServlet {
if (r.getRequestStatus().equals(RequestStatus.PENDING)) {
cmsReq.setResult(r);
cmsReq.setStatus(CMSRequest.PENDING);
- if (certInfo != null) {
+ if (certInfo != null) {
for (int i = 0; i < certInfo.length; i++) {
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.FORMAT,
- new Object[] {
- r.getRequestType(),
- r.getRequestId(),
- initiative,
- authMgr,
- "pending",
- certInfo[i].get(X509CertInfo.SUBJECT),
- ""}
- );
+ mLogger.log(ILogger.EV_AUDIT,
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.FORMAT,
+ new Object[] {
+ r.getRequestType(),
+ r.getRequestId(),
+ initiative,
+ authMgr,
+ "pending",
+ certInfo[i].get(X509CertInfo.SUBJECT),
+ "" }
+ );
}
} else {
if (subject != null) {
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.FORMAT,
- new Object[] {
- r.getRequestType(),
- r.getRequestId(),
- initiative,
- authMgr,
- "pending",
- subject,
- ""}
- );
+ mLogger.log(ILogger.EV_AUDIT,
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.FORMAT,
+ new Object[] {
+ r.getRequestType(),
+ r.getRequestId(),
+ initiative,
+ authMgr,
+ "pending",
+ subject,
+ "" }
+ );
} else {
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.NODNFORMAT,
- new Object[] {
- r.getRequestType(),
- r.getRequestId(),
- initiative,
- authMgr,
- "pending"}
- );
+ mLogger.log(ILogger.EV_AUDIT,
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.NODNFORMAT,
+ new Object[] {
+ r.getRequestType(),
+ r.getRequestId(),
+ initiative,
+ authMgr,
+ "pending" }
+ );
}
}
} else if (r.getRequestStatus().equals(
RequestStatus.APPROVED) ||
- r.getRequestStatus().equals(
- RequestStatus.SVC_PENDING)) {
+ r.getRequestStatus().equals(
+ RequestStatus.SVC_PENDING)) {
cmsReq.setResult(r);
cmsReq.setStatus(CMSRequest.SVC_PENDING);
if (certInfo != null) {
for (int i = 0; i < certInfo.length; i++) {
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.FORMAT,
- new Object[] {
- r.getRequestType(),
- r.getRequestId(),
- initiative,
- authMgr,
- r.getRequestStatus(),
- certInfo[i].get(X509CertInfo.SUBJECT),
- ""}
- );
+ mLogger.log(ILogger.EV_AUDIT,
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.FORMAT,
+ new Object[] {
+ r.getRequestType(),
+ r.getRequestId(),
+ initiative,
+ authMgr,
+ r.getRequestStatus(),
+ certInfo[i].get(X509CertInfo.SUBJECT),
+ "" }
+ );
}
} else {
if (subject != null) {
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.FORMAT,
- new Object[] {
- r.getRequestType(),
- r.getRequestId(),
- initiative,
- authMgr,
- r.getRequestStatus(),
- subject,
- ""}
- );
+ mLogger.log(ILogger.EV_AUDIT,
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.FORMAT,
+ new Object[] {
+ r.getRequestType(),
+ r.getRequestId(),
+ initiative,
+ authMgr,
+ r.getRequestStatus(),
+ subject,
+ "" }
+ );
} else {
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.NODNFORMAT,
- new Object[] {
- r.getRequestType(),
- r.getRequestId(),
- initiative,
- authMgr,
- r.getRequestStatus()}
- );
+ mLogger.log(ILogger.EV_AUDIT,
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.NODNFORMAT,
+ new Object[] {
+ r.getRequestType(),
+ r.getRequestId(),
+ initiative,
+ authMgr,
+ r.getRequestStatus() }
+ );
}
}
} else if (r.getRequestStatus().equals(
@@ -922,38 +910,38 @@ public class ProcessCertReq extends CMSServlet {
// XXX make the repeat record.
// Get the certificate(s) from the request
X509CertImpl issuedCerts[] =
- r.getExtDataInCertArray(IRequest.ISSUED_CERTS);
+ r.getExtDataInCertArray(IRequest.ISSUED_CERTS);
- // return potentially more than one certificates.
+ // return potentially more than one certificates.
if (issuedCerts != null) {
long endTime = CMS.getCurrentDate().getTime();
StringBuffer sbuf = new StringBuffer();
- //header.addBigIntegerValue("serialNumber",
- //issuedCerts[0].getSerialNumber(),16);
+ // header.addBigIntegerValue("serialNumber",
+ // issuedCerts[0].getSerialNumber(),16);
for (int i = 0; i < issuedCerts.length; i++) {
- if (i != 0)
+ if (i != 0)
sbuf.append(", ");
sbuf.append("0x" +
- issuedCerts[i].getSerialNumber().toString(16));
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.FORMAT,
- new Object[] {
- r.getRequestType(),
- r.getRequestId(),
- initiative,
- authMgr,
- "completed",
- issuedCerts[i].getSubjectDN(),
- "cert issued serial number: 0x" +
- issuedCerts[i].getSerialNumber().toString(16) + " time: " + (endTime - startTime)}
- );
+ issuedCerts[i].getSerialNumber().toString(16));
+ mLogger.log(ILogger.EV_AUDIT,
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.FORMAT,
+ new Object[] {
+ r.getRequestType(),
+ r.getRequestId(),
+ initiative,
+ authMgr,
+ "completed",
+ issuedCerts[i].getSubjectDN(),
+ "cert issued serial number: 0x" +
+ issuedCerts[i].getSerialNumber().toString(16) + " time: " + (endTime - startTime) }
+ );
// store a message in the signed audit log file
// (one for each manual "agent"
- // cert request processed - "accepted")
+ // cert request processed - "accepted")
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED,
auditSubjectID,
@@ -965,39 +953,39 @@ public class ProcessCertReq extends CMSServlet {
audit(auditMessage);
}
header.addStringValue(
- "serialNumber", sbuf.toString());
+ "serialNumber", sbuf.toString());
} else {
if (subject != null) {
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.FORMAT,
- new Object[] {
- r.getRequestType(),
- r.getRequestId(),
- initiative,
- authMgr,
- "completed",
- subject,
- ""}
- );
+ mLogger.log(ILogger.EV_AUDIT,
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.FORMAT,
+ new Object[] {
+ r.getRequestType(),
+ r.getRequestId(),
+ initiative,
+ authMgr,
+ "completed",
+ subject,
+ "" }
+ );
} else {
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.NODNFORMAT,
- new Object[] {
- r.getRequestType(),
- r.getRequestId(),
- initiative,
- authMgr,
- "completed"}
- );
+ mLogger.log(ILogger.EV_AUDIT,
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.NODNFORMAT,
+ new Object[] {
+ r.getRequestType(),
+ r.getRequestId(),
+ initiative,
+ authMgr,
+ "completed" }
+ );
}
// store a message in the signed audit log file
// (manual "agent" cert request processed
- // - "accepted")
+ // - "accepted")
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED,
auditSubjectID,
@@ -1009,10 +997,10 @@ public class ProcessCertReq extends CMSServlet {
audit(auditMessage);
}
- // grant trusted manager or agent privileges
+ // grant trusted manager or agent privileges
Object grantError = null;
- try {
+ try {
int res = grant_privileges(
cmsReq, r, issuedCerts, header);
@@ -1028,45 +1016,41 @@ public class ProcessCertReq extends CMSServlet {
// if this is a RA, show the certificate right away
// since ther is no cert database.
/*
- if (mAuthority instanceof RegistrationAuthority) {
- Object[] results =
- new Object[] { issuedCerts, grantError };
- cmsReq.setResult(results);
- renderTemplate(cmsReq,
- mReqCompletedTemplate, REQ_COMPLETED_FILLER);
-
- return;
- }
+ * if (mAuthority instanceof RegistrationAuthority) {
+ * Object[] results = new Object[] { issuedCerts,
+ * grantError }; cmsReq.setResult(results);
+ * renderTemplate(cmsReq, mReqCompletedTemplate,
+ * REQ_COMPLETED_FILLER);
+ *
+ * return; }
*/
cmsReq.setResult(r);
String scheme = req.getScheme();
- if (scheme.equals("http") &&
- connectionIsSSL(req)) scheme = "https";
+ if (scheme.equals("http") &&
+ connectionIsSSL(req))
+ scheme = "https";
- /*
- header.addStringValue(
- "authorityid", mAuthority.getId());
- header.addStringValue("serviceURL", scheme +"://"+
- req.getServerName() + ":"+
- req.getServerPort() +
- req.getRequestURI());
- */
+ /*
+ * header.addStringValue( "authorityid",
+ * mAuthority.getId());
+ * header.addStringValue("serviceURL", scheme +"://"+
+ * req.getServerName() + ":"+ req.getServerPort() +
+ * req.getRequestURI());
+ */
if (mPublisherProcessor != null && mPublisherProcessor.ldapEnabled()) {
header.addStringValue("dirEnabled", "yes");
- Integer[] ldapPublishStatus =
- r.getExtDataInIntegerArray("ldapPublishStatus");
+ Integer[] ldapPublishStatus =
+ r.getExtDataInIntegerArray("ldapPublishStatus");
int certsUpdated = 0;
if (ldapPublishStatus != null) {
- for (int i = 0;
- i < ldapPublishStatus.length; i++) {
- if (ldapPublishStatus[i] ==
- IRequest.RES_SUCCESS) {
+ for (int i = 0; i < ldapPublishStatus.length; i++) {
+ if (ldapPublishStatus[i] == IRequest.RES_SUCCESS) {
certsUpdated++;
}
}
@@ -1082,47 +1066,47 @@ public class ProcessCertReq extends CMSServlet {
mQueue.rejectRequest(r);
if (certInfo != null) {
for (int i = 0; i < certInfo.length; i++) {
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.FORMAT,
- new Object[] {
- r.getRequestType(),
- r.getRequestId(),
- initiative,
- authMgr,
- "rejected",
- certInfo[i].get(X509CertInfo.SUBJECT),
- ""}
- );
+ mLogger.log(ILogger.EV_AUDIT,
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.FORMAT,
+ new Object[] {
+ r.getRequestType(),
+ r.getRequestId(),
+ initiative,
+ authMgr,
+ "rejected",
+ certInfo[i].get(X509CertInfo.SUBJECT),
+ "" }
+ );
}
} else {
if (subject != null) {
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.FORMAT,
- new Object[] {
- r.getRequestType(),
- r.getRequestId(),
- initiative,
- authMgr,
- "rejected",
- subject,
- ""}
- );
+ mLogger.log(ILogger.EV_AUDIT,
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.FORMAT,
+ new Object[] {
+ r.getRequestType(),
+ r.getRequestId(),
+ initiative,
+ authMgr,
+ "rejected",
+ subject,
+ "" }
+ );
} else {
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.NODNFORMAT,
- new Object[] {
- r.getRequestType(),
- r.getRequestId(),
- initiative,
- authMgr,
- "rejected"}
- );
+ mLogger.log(ILogger.EV_AUDIT,
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.NODNFORMAT,
+ new Object[] {
+ r.getRequestType(),
+ r.getRequestId(),
+ initiative,
+ authMgr,
+ "rejected" }
+ );
}
}
@@ -1143,47 +1127,47 @@ public class ProcessCertReq extends CMSServlet {
if (certInfo != null) {
for (int i = 0; i < certInfo.length; i++) {
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.FORMAT,
- new Object[] {
- r.getRequestType(),
- r.getRequestId(),
- initiative,
- authMgr,
- "canceled",
- certInfo[i].get(X509CertInfo.SUBJECT),
- ""}
- );
+ mLogger.log(ILogger.EV_AUDIT,
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.FORMAT,
+ new Object[] {
+ r.getRequestType(),
+ r.getRequestId(),
+ initiative,
+ authMgr,
+ "canceled",
+ certInfo[i].get(X509CertInfo.SUBJECT),
+ "" }
+ );
}
} else {
if (subject != null) {
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.FORMAT,
- new Object[] {
- r.getRequestType(),
- r.getRequestId(),
- initiative,
- authMgr,
- "canceled",
- subject,
- ""}
- );
+ mLogger.log(ILogger.EV_AUDIT,
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.FORMAT,
+ new Object[] {
+ r.getRequestType(),
+ r.getRequestId(),
+ initiative,
+ authMgr,
+ "canceled",
+ subject,
+ "" }
+ );
} else {
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.NODNFORMAT,
- new Object[] {
- r.getRequestType(),
- r.getRequestId(),
- initiative,
- authMgr,
- "canceled"}
- );
+ mLogger.log(ILogger.EV_AUDIT,
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.NODNFORMAT,
+ new Object[] {
+ r.getRequestType(),
+ r.getRequestId(),
+ initiative,
+ authMgr,
+ "canceled" }
+ );
}
}
@@ -1204,54 +1188,54 @@ public class ProcessCertReq extends CMSServlet {
IRequest clonedRequest = mQueue.cloneAndMarkPending(r);
header.addStringValue("clonedRequestId",
- clonedRequest.getRequestId().toString());
+ clonedRequest.getRequestId().toString());
if (certInfo != null) {
for (int i = 0; i < certInfo.length; i++) {
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.FORMAT,
- new Object[] {
- r.getRequestType(),
- r.getRequestId(),
- initiative,
- authMgr,
- "cloned to reqID: " +
- clonedRequest.getRequestId().toString(),
- certInfo[i].get(X509CertInfo.SUBJECT),
- ""}
- );
+ mLogger.log(ILogger.EV_AUDIT,
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.FORMAT,
+ new Object[] {
+ r.getRequestType(),
+ r.getRequestId(),
+ initiative,
+ authMgr,
+ "cloned to reqID: " +
+ clonedRequest.getRequestId().toString(),
+ certInfo[i].get(X509CertInfo.SUBJECT),
+ "" }
+ );
}
} else {
if (subject != null) {
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.FORMAT,
- new Object[] {
- r.getRequestType(),
- r.getRequestId(),
- initiative,
- authMgr,
- "cloned to reqID: " +
- clonedRequest.getRequestId().toString(),
- subject,
- ""}
- );
+ mLogger.log(ILogger.EV_AUDIT,
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.FORMAT,
+ new Object[] {
+ r.getRequestType(),
+ r.getRequestId(),
+ initiative,
+ authMgr,
+ "cloned to reqID: " +
+ clonedRequest.getRequestId().toString(),
+ subject,
+ "" }
+ );
} else {
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_OTHER,
- AuditFormat.LEVEL,
- AuditFormat.NODNFORMAT,
- new Object[] {
- r.getRequestType(),
- r.getRequestId(),
- initiative,
- authMgr,
- "cloned to reqID: " +
- clonedRequest.getRequestId().toString()}
- );
+ mLogger.log(ILogger.EV_AUDIT,
+ ILogger.S_OTHER,
+ AuditFormat.LEVEL,
+ AuditFormat.NODNFORMAT,
+ new Object[] {
+ r.getRequestType(),
+ r.getRequestId(),
+ initiative,
+ authMgr,
+ "cloned to reqID: " +
+ clonedRequest.getRequestId().toString() }
+ );
}
}
@@ -1269,12 +1253,12 @@ public class ProcessCertReq extends CMSServlet {
}
}
- // add authority names to know what privileges can be requested.
- if (CMS.getSubsystem("kra") != null)
+ // add authority names to know what privileges can be requested.
+ if (CMS.getSubsystem("kra") != null)
header.addStringValue("localkra", "yes");
- if (CMS.getSubsystem("ca") != null)
+ if (CMS.getSubsystem("ca") != null)
header.addStringValue("localca", "yes");
- if (CMS.getSubsystem("ra") != null)
+ if (CMS.getSubsystem("ra") != null)
header.addStringValue("localra", "yes");
header.addIntegerValue("seqNum", seqNum);
@@ -1389,7 +1373,7 @@ public class ProcessCertReq extends CMSServlet {
}
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_ENCODING_ISSUED_CERT_ERROR"));
+ CMS.getUserMessage("CMS_GW_ENCODING_ISSUED_CERT_ERROR"));
} catch (CertificateException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_IO_ERROR_REMOTE_REQUEST", e.toString()));
@@ -1443,7 +1427,7 @@ public class ProcessCertReq extends CMSServlet {
}
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_ENCODING_ISSUED_CERT_ERROR"));
+ CMS.getUserMessage("CMS_GW_ENCODING_ISSUED_CERT_ERROR"));
} catch (NoSuchAlgorithmException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_IO_ERROR_REMOTE_REQUEST", e.toString()));
@@ -1500,9 +1484,9 @@ public class ProcessCertReq extends CMSServlet {
}
return;
}
-
- private void updateNSExtension(HttpServletRequest req,
- NSCertTypeExtension ext) throws IOException {
+
+ private void updateNSExtension(HttpServletRequest req,
+ NSCertTypeExtension ext) throws IOException {
try {
if (req.getParameter("certTypeSSLServer") == null) {
@@ -1551,106 +1535,101 @@ public class ProcessCertReq extends CMSServlet {
}
/**
- * This method sets extensions parameter into the request so
- * that the NSCertTypeExtension policy creates new
- * NSCertTypExtension with this setting. Note that this
- * setting will not be used if the NSCertType Extension
- * already exist in CertificateExtension. In that case,
- * updateExtensions() will be called to set the extension
- * parameter into the extension directly.
+ * This method sets extensions parameter into the request so that the
+ * NSCertTypeExtension policy creates new NSCertTypExtension with this
+ * setting. Note that this setting will not be used if the NSCertType
+ * Extension already exist in CertificateExtension. In that case,
+ * updateExtensions() will be called to set the extension parameter into the
+ * extension directly.
*/
private int updateExtensionsInRequest(HttpServletRequest req, IRequest r) {
int nChanges = 0;
- if (req.getParameter("certTypeSSLServer") != null) {
- r.setExtData(NSCertTypeExtension.SSL_SERVER, "true");
- nChanges++;
- } else {
- r.deleteExtData(NSCertTypeExtension.SSL_SERVER);
- nChanges++;
- }
+ if (req.getParameter("certTypeSSLServer") != null) {
+ r.setExtData(NSCertTypeExtension.SSL_SERVER, "true");
+ nChanges++;
+ } else {
+ r.deleteExtData(NSCertTypeExtension.SSL_SERVER);
+ nChanges++;
+ }
- if (req.getParameter("certTypeSSLClient") != null) {
- r.setExtData(NSCertTypeExtension.SSL_CLIENT, "true");
- nChanges++;
- } else {
- r.deleteExtData(NSCertTypeExtension.SSL_CLIENT);
- nChanges++;
- }
+ if (req.getParameter("certTypeSSLClient") != null) {
+ r.setExtData(NSCertTypeExtension.SSL_CLIENT, "true");
+ nChanges++;
+ } else {
+ r.deleteExtData(NSCertTypeExtension.SSL_CLIENT);
+ nChanges++;
+ }
- if (req.getParameter("certTypeEmail") != null) {
- r.setExtData(NSCertTypeExtension.EMAIL, "true");
- nChanges++;
- } else {
- r.deleteExtData(NSCertTypeExtension.EMAIL);
- nChanges++;
- }
+ if (req.getParameter("certTypeEmail") != null) {
+ r.setExtData(NSCertTypeExtension.EMAIL, "true");
+ nChanges++;
+ } else {
+ r.deleteExtData(NSCertTypeExtension.EMAIL);
+ nChanges++;
+ }
- if (req.getParameter("certTypeObjSigning") != null) {
- r.setExtData(NSCertTypeExtension.OBJECT_SIGNING, "true");
- nChanges++;
- } else {
- r.deleteExtData(NSCertTypeExtension.OBJECT_SIGNING);
- nChanges++;
- }
+ if (req.getParameter("certTypeObjSigning") != null) {
+ r.setExtData(NSCertTypeExtension.OBJECT_SIGNING, "true");
+ nChanges++;
+ } else {
+ r.deleteExtData(NSCertTypeExtension.OBJECT_SIGNING);
+ nChanges++;
+ }
- if (req.getParameter("certTypeEmailCA") != null) {
- r.setExtData(NSCertTypeExtension.EMAIL_CA, "true");
- nChanges++;
- } else {
- r.deleteExtData(NSCertTypeExtension.EMAIL_CA);
- nChanges++;
- }
+ if (req.getParameter("certTypeEmailCA") != null) {
+ r.setExtData(NSCertTypeExtension.EMAIL_CA, "true");
+ nChanges++;
+ } else {
+ r.deleteExtData(NSCertTypeExtension.EMAIL_CA);
+ nChanges++;
+ }
- if (req.getParameter("certTypeSSLCA") != null) {
- r.setExtData(NSCertTypeExtension.SSL_CA, "true");
- nChanges++;
- } else {
- r.deleteExtData(NSCertTypeExtension.SSL_CA);
- nChanges++;
- }
+ if (req.getParameter("certTypeSSLCA") != null) {
+ r.setExtData(NSCertTypeExtension.SSL_CA, "true");
+ nChanges++;
+ } else {
+ r.deleteExtData(NSCertTypeExtension.SSL_CA);
+ nChanges++;
+ }
- if (req.getParameter("certTypeObjSigningCA") != null) {
- r.setExtData(NSCertTypeExtension.OBJECT_SIGNING_CA, "true");
- nChanges++;
- } else {
- r.deleteExtData(NSCertTypeExtension.OBJECT_SIGNING_CA);
- nChanges++;
- }
+ if (req.getParameter("certTypeObjSigningCA") != null) {
+ r.setExtData(NSCertTypeExtension.OBJECT_SIGNING_CA, "true");
+ nChanges++;
+ } else {
+ r.deleteExtData(NSCertTypeExtension.OBJECT_SIGNING_CA);
+ nChanges++;
+ }
return nChanges;
}
-
+
protected static final String GRANT_ERROR = "grantError";
- public static final String
- GRANT_TRUSTEDMGR_PRIVILEGE = "grantTrustedManagerPrivilege";
- public static final String
- GRANT_CMAGENT_PRIVILEGE = "grantCMAgentPrivilege";
- public static final String
- GRANT_RMAGENT_PRIVILEGE = "grantRMAgentPrivilege";
- public static final String
- GRANT_DRMAGENT_PRIVILEGE = "grantDRMAgentPrivilege";
+ public static final String GRANT_TRUSTEDMGR_PRIVILEGE = "grantTrustedManagerPrivilege";
+ public static final String GRANT_CMAGENT_PRIVILEGE = "grantCMAgentPrivilege";
+ public static final String GRANT_RMAGENT_PRIVILEGE = "grantRMAgentPrivilege";
+ public static final String GRANT_DRMAGENT_PRIVILEGE = "grantDRMAgentPrivilege";
public static final String GRANT_UID = "grantUID";
public static final String GRANT_PRIVILEGE = "grantPrivilege";
protected int grant_privileges(
- CMSRequest cmsReq, IRequest req, Certificate[] certs, IArgBlock header)
- throws EBaseException {
+ CMSRequest cmsReq, IRequest req, Certificate[] certs, IArgBlock header)
+ throws EBaseException {
// get privileges to grant
IArgBlock httpParams = cmsReq.getHttpParams();
- boolean grantTrustedMgr =
- httpParams.getValueAsBoolean(GRANT_TRUSTEDMGR_PRIVILEGE, false);
- boolean grantRMAgent =
- httpParams.getValueAsBoolean(GRANT_RMAGENT_PRIVILEGE, false);
- boolean grantCMAgent =
- httpParams.getValueAsBoolean(GRANT_CMAGENT_PRIVILEGE, false);
- boolean grantDRMAgent =
- httpParams.getValueAsBoolean(GRANT_DRMAGENT_PRIVILEGE, false);
-
- if (!grantTrustedMgr &&
- !grantCMAgent && !grantRMAgent && !grantDRMAgent) {
+ boolean grantTrustedMgr =
+ httpParams.getValueAsBoolean(GRANT_TRUSTEDMGR_PRIVILEGE, false);
+ boolean grantRMAgent =
+ httpParams.getValueAsBoolean(GRANT_RMAGENT_PRIVILEGE, false);
+ boolean grantCMAgent =
+ httpParams.getValueAsBoolean(GRANT_CMAGENT_PRIVILEGE, false);
+ boolean grantDRMAgent =
+ httpParams.getValueAsBoolean(GRANT_DRMAGENT_PRIVILEGE, false);
+
+ if (!grantTrustedMgr &&
+ !grantCMAgent && !grantRMAgent && !grantDRMAgent) {
return 0;
} else {
IAuthToken authToken = getAuthToken(req);
@@ -1669,7 +1648,7 @@ public class ProcessCertReq extends CMSServlet {
if (grantTrustedMgr)
obj[0] = TRUSTED_RA_GROUP;
- else if (grantRMAgent)
+ else if (grantRMAgent)
obj[0] = RA_AGENT_GROUP;
else if (grantCMAgent)
obj[0] = CA_AGENT_GROUP;
@@ -1696,22 +1675,22 @@ public class ProcessCertReq extends CMSServlet {
groupname = TRUSTED_RA_GROUP;
userType = Constants.PR_SUBSYSTEM_TYPE;
} else {
- if (grantCMAgent)
+ if (grantCMAgent)
groupname = CA_AGENT_GROUP;
- else if (grantRMAgent)
+ else if (grantRMAgent)
groupname = RA_AGENT_GROUP;
if (grantDRMAgent) {
- if (groupname != null)
+ if (groupname != null)
groupname1 = KRA_AGENT_GROUP;
- else
+ else
groupname = KRA_AGENT_GROUP;
}
userType = Constants.PR_AGENT_TYPE;
}
- String privilege =
- (groupname1 == null) ? groupname : groupname + " and " + groupname1;
+ String privilege =
+ (groupname1 == null) ? groupname : groupname + " and " + groupname1;
header.addStringValue(GRANT_PRIVILEGE, privilege);
@@ -1727,23 +1706,23 @@ public class ProcessCertReq extends CMSServlet {
IGroup group = ug.findGroup(groupname), group1 = null;
if (group == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_FIND_GROUP_1", groupname));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERROR_FIND_GROUP_1", groupname));
throw new ECMSGWException(CMS.getUserMessage("CMS_GW_FIND_GROUP_ERROR", groupname));
}
if (groupname1 != null) {
group1 = ug.findGroup(groupname1);
if (group1 == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_FIND_GROUP_1", groupname));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERROR_FIND_GROUP_1", groupname));
throw new ECMSGWException(CMS.getUserMessage("CMS_GW_FIND_GROUP_ERROR", groupname1));
}
}
try {
ug.addUser(user);
} catch (Exception e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_ADDING_USER_1", uid));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERROR_ADDING_USER_1", uid));
throw new ECMSGWException(CMS.getUserMessage("CMS_GW_ADDING_USER_ERROR", uid));
}
try {
@@ -1752,11 +1731,11 @@ public class ProcessCertReq extends CMSServlet {
user.setX509Certificates(tmp);
}
-
+
ug.addUserCert(user);
} catch (Exception e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERROR_ADDING_CERT_1", uid));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERROR_ADDING_CERT_1", uid));
throw new ECMSGWException(CMS.getUserMessage("CMS_GW_ADDING_CERT_ERROR", uid));
}
try {
@@ -1765,44 +1744,44 @@ public class ProcessCertReq extends CMSServlet {
// for audit log
SessionContext sContext = SessionContext.getContext();
String adminId = (String) sContext.get(SessionContext.USER_ID);
-
+
mLogger.log(ILogger.EV_AUDIT, ILogger.S_USRGRP,
- AuditFormat.LEVEL, AuditFormat.ADDUSERGROUPFORMAT,
- new Object[] {adminId, uid, groupname}
- );
+ AuditFormat.LEVEL, AuditFormat.ADDUSERGROUPFORMAT,
+ new Object[] { adminId, uid, groupname }
+ );
if (group1 != null) {
group1.addMemberName(uid);
ug.modifyGroup(group1);
-
+
mLogger.log(ILogger.EV_AUDIT, ILogger.S_USRGRP,
- AuditFormat.LEVEL, AuditFormat.ADDUSERGROUPFORMAT,
- new Object[] {adminId, uid, groupname1}
- );
+ AuditFormat.LEVEL, AuditFormat.ADDUSERGROUPFORMAT,
+ new Object[] { adminId, uid, groupname1 }
+ );
}
} catch (Exception e) {
- String msg =
- "Could not add user " + uid + " to group " + groupname;
+ String msg =
+ "Could not add user " + uid + " to group " + groupname;
if (group1 != null)
msg += " or group " + groupname1;
log(ILogger.LL_FAILURE, msg);
- if (group1 == null)
- throw new ECMSGWException(CMS.getUserMessage("CMS_GW_ADDING_MEMBER", uid, groupname));
- else
- throw new ECMSGWException(CMS.getUserMessage("CMS_GW_ADDING_MEMBER_1", uid, groupname, groupname1));
+ if (group1 == null)
+ throw new ECMSGWException(CMS.getUserMessage("CMS_GW_ADDING_MEMBER", uid, groupname));
+ else
+ throw new ECMSGWException(CMS.getUserMessage("CMS_GW_ADDING_MEMBER_1", uid, groupname, groupname1));
}
return 1;
}
/**
* Signed Audit Log Info Name
- *
- * This method is called to obtain the "InfoName" for
- * a signed audit log message.
+ *
+ * This method is called to obtain the "InfoName" for a signed audit log
+ * message.
* <P>
- *
+ *
* @param type signed audit log request processing type
* @return id string containing the signed audit log message InfoName
*/
@@ -1833,11 +1812,11 @@ public class ProcessCertReq extends CMSServlet {
/**
* Signed Audit Log Info Certificate Value
- *
+ *
* This method is called to obtain the certificate from the passed in
* "X509CertImpl" for a signed audit log message.
* <P>
- *
+ *
* @param x509cert an X509CertImpl
* @return cert string containing the certificate
*/
@@ -1891,38 +1870,38 @@ public class ProcessCertReq extends CMSServlet {
}
}
-
class RAReqCompletedFiller extends ImportCertsTemplateFiller {
private static final String RA_AGENT_GROUP = "Registration Manager Agents";
private static final String KRA_AGENT_GROUP = "Data Recovery Manager Agents";
+
public RAReqCompletedFiller() {
super();
}
public CMSTemplateParams getTemplateParams(
- CMSRequest cmsReq, IAuthority authority, Locale locale, Exception e)
- throws Exception {
+ CMSRequest cmsReq, IAuthority authority, Locale locale, Exception e)
+ throws Exception {
Object[] results = (Object[]) cmsReq.getResult();
Object grantError = results[1];
- //X509CertImpl[] issuedCerts = (X509CertImpl[])results[0];
+ // X509CertImpl[] issuedCerts = (X509CertImpl[])results[0];
Certificate[] issuedCerts = (Certificate[]) results[0];
-
+
cmsReq.setResult(issuedCerts);
- CMSTemplateParams params =
- super.getTemplateParams(cmsReq, authority, locale, e);
+ CMSTemplateParams params =
+ super.getTemplateParams(cmsReq, authority, locale, e);
if (grantError != null) {
IArgBlock header = params.getHeader();
if (grantError instanceof String) {
header.addStringValue(
- ProcessCertReq.GRANT_ERROR, (String) grantError);
+ ProcessCertReq.GRANT_ERROR, (String) grantError);
} else {
EBaseException ex = (EBaseException) grantError;
header.addStringValue(
- ProcessCertReq.GRANT_ERROR, ex.toString(locale));
+ ProcessCertReq.GRANT_ERROR, ex.toString(locale));
}
IArgBlock httpParams = cmsReq.getHttpParams();
String uid = httpParams.getValueAsString(
@@ -1941,7 +1920,7 @@ class RAReqCompletedFiller extends ImportCertsTemplateFiller {
if (grantDRMAgent) {
if (privilege != null)
privilege += " and " + KRA_AGENT_GROUP;
- else
+ else
privilege = KRA_AGENT_GROUP;
}
header.addStringValue(ProcessCertReq.GRANT_PRIVILEGE, privilege);
@@ -1949,4 +1928,3 @@ class RAReqCompletedFiller extends ImportCertsTemplateFiller {
return params;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cms/servlet/request/ProcessReq.java b/pki/base/common/src/com/netscape/cms/servlet/request/ProcessReq.java
index 0ac27197..55eebfac 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/request/ProcessReq.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/request/ProcessReq.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.request;
-
import java.io.IOException;
import java.util.Locale;
@@ -50,10 +49,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* Display Generic Request detail to the user.
- *
+ *
* @version $Revision$, $Date$
*/
public class ProcessReq extends CMSServlet {
@@ -74,8 +72,8 @@ public class ProcessReq extends CMSServlet {
private IReqParser mParser = null;
private String[] mSigningAlgorithms = null;
- private static String[] DEF_SIGNING_ALGORITHMS = new String[]
- {"SHA1withRSA", "SHA256withRSA", "SHA512withRSA", "SHA1withDSA", "MD5withRSA", "MD2withRSA"};
+ private static String[] DEF_SIGNING_ALGORITHMS = new String[]
+ { "SHA1withRSA", "SHA256withRSA", "SHA512withRSA", "SHA1withDSA", "MD5withRSA", "MD2withRSA" };
/**
* Process request.
@@ -86,15 +84,15 @@ public class ProcessReq extends CMSServlet {
/**
* initialize the servlet. This servlet uses the template file
- * "processReq.template" to process the response.
- * The initialization parameter 'parser' is read from the
- * servlet configration, and is used to set the type of request.
- * The value of this parameter can be:
- * <UL><LI><B>CertReqParser.NODETAIL_PARSER</B> - Show certificate Summary
- * <LI><B>CertReqParser.DETAIL_PARSER</B> - Show certificate detail
- * <LI><B>KeyReqParser.PARSER</B> - Show key archival detail
- * </UL>
- *
+ * "processReq.template" to process the response. The initialization
+ * parameter 'parser' is read from the servlet configration, and is used to
+ * set the type of request. The value of this parameter can be:
+ * <UL>
+ * <LI><B>CertReqParser.NODETAIL_PARSER</B> - Show certificate Summary
+ * <LI><B>CertReqParser.DETAIL_PARSER</B> - Show certificate detail
+ * <LI><B>KeyReqParser.PARSER</B> - Show key archival detail
+ * </UL>
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -111,13 +109,13 @@ public class ProcessReq extends CMSServlet {
mParser = CertReqParser.DETAIL_PARSER;
else if (tmp.trim().equals("KeyReqParser.PARSER"))
mParser = KeyReqParser.PARSER;
- }
+ }
- // override success and error templates to null -
+ // override success and error templates to null -
// handle templates locally.
mTemplates.remove(CMSRequest.SUCCESS);
mTemplates.remove(CMSRequest.ERROR);
- if (mOutputTemplatePath != null)
+ if (mOutputTemplatePath != null)
mFormPath = mOutputTemplatePath;
}
@@ -126,9 +124,9 @@ public class ProcessReq extends CMSServlet {
* <ul>
* <li>http.param seqNum
* <li>http.param doAssign reassign request. Value can be reassignToMe
- * reassignToNobody
+ * reassignToNobody
* </ul>
- *
+ *
* @param cmsReq the object holding the request and response information
*/
public void process(CMSRequest cmsReq) throws EBaseException {
@@ -152,10 +150,10 @@ public class ProcessReq extends CMSServlet {
try {
form = getTemplate(mFormPath, req, locale);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- "Error getting template " + mFormPath + " Error " + e);
+ log(ILogger.LL_FAILURE,
+ "Error getting template " + mFormPath + " Error " + e);
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
try {
@@ -172,8 +170,8 @@ public class ProcessReq extends CMSServlet {
if (doAssign == null) {
authzToken = authorize(mAclMethod, authToken,
mAuthzResourceName, "read");
- } else if (doAssign.equals("toMe") ||
- doAssign.equals("reassignToMe")) {
+ } else if (doAssign.equals("toMe") ||
+ doAssign.equals("reassignToMe")) {
authzToken = authorize(mAclMethod, authToken,
mAuthzResourceName, "assign");
} else if (doAssign.equals("reassignToNobody")) {
@@ -182,10 +180,10 @@ public class ProcessReq extends CMSServlet {
}
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -193,19 +191,19 @@ public class ProcessReq extends CMSServlet {
return;
}
- process(argSet, header, seqNum, req, resp,
- doAssign, locale[0]);
+ process(argSet, header, seqNum, req, resp,
+ doAssign, locale[0]);
} else {
log(ILogger.LL_FAILURE, "Invalid sequence number " + seqNum);
error = new ECMSGWException(
- CMS.getUserMessage("CMS_GW_INVALID_REQUEST_ID",
- String.valueOf(seqNum)));
+ CMS.getUserMessage("CMS_GW_INVALID_REQUEST_ID",
+ String.valueOf(seqNum)));
}
} catch (EBaseException e) {
error = e;
} catch (NumberFormatException e) {
error = new EBaseException(CMS.getUserMessage(locale[0], "CMS_BASE_INVALID_NUMBER_FORMAT"));
- }
+ }
try {
ServletOutputStream out = resp.getOutputStream();
@@ -213,46 +211,46 @@ public class ProcessReq extends CMSServlet {
if (error == null) {
String xmlOutput = req.getParameter("xml");
if (xmlOutput != null && xmlOutput.equals("true")) {
- outputXML(resp, argSet);
+ outputXML(resp, argSet);
} else {
- String output = form.getOutput(argSet);
- resp.setContentType("text/html");
- form.renderOutput(out, argSet);
- cmsReq.setStatus(CMSRequest.SUCCESS);
+ String output = form.getOutput(argSet);
+ resp.setContentType("text/html");
+ form.renderOutput(out, argSet);
+ cmsReq.setStatus(CMSRequest.SUCCESS);
}
} else {
cmsReq.setError(error);
cmsReq.setStatus(CMSRequest.ERROR);
}
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- "Error getting servlet output stream for rendering template. " +
- "Error " + e);
+ log(ILogger.LL_FAILURE,
+ "Error getting servlet output stream for rendering template. " +
+ "Error " + e);
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
return;
}
/**
- * Sends request information to the calller.
- * returns whether there was an error or not.
+ * Sends request information to the calller. returns whether there was an
+ * error or not.
*/
private void process(CMSTemplateParams argSet, IArgBlock header,
- int seqNum, HttpServletRequest req,
- HttpServletResponse resp,
- String doAssign, Locale locale)
- throws EBaseException {
+ int seqNum, HttpServletRequest req,
+ HttpServletResponse resp,
+ String doAssign, Locale locale)
+ throws EBaseException {
header.addIntegerValue("seqNum", seqNum);
- IRequest r =
- mQueue.findRequest(new RequestId(Integer.toString(seqNum)));
+ IRequest r =
+ mQueue.findRequest(new RequestId(Integer.toString(seqNum)));
if (r != null) {
if (doAssign != null) {
if ((doAssign.equals("toMe"))
- || (doAssign.equals("reassignToMe"))) {
+ || (doAssign.equals("reassignToMe"))) {
SessionContext ctx = SessionContext.getContext();
String id = (String) ctx.get(SessionContext.USER_ID);
@@ -264,32 +262,33 @@ public class ProcessReq extends CMSServlet {
}
}
- // add authority names to know what privileges can be requested.
- if (CMS.getSubsystem("kra") != null)
+ // add authority names to know what privileges can be requested.
+ if (CMS.getSubsystem("kra") != null)
header.addStringValue("localkra", "yes");
- if (CMS.getSubsystem("ca") != null)
+ if (CMS.getSubsystem("ca") != null)
header.addStringValue("localca", "yes");
- if (CMS.getSubsystem("ra") != null)
+ if (CMS.getSubsystem("ra") != null)
header.addStringValue("localra", "yes");
- // DONT NEED TO DO THIS FOR DRM
+ // DONT NEED TO DO THIS FOR DRM
if (mAuthority instanceof ICertAuthority) {
// Check/set signing algorithms dynamically.
- // In RA mSigningAlgorithms could be null at startup if CA is not
- // up and set later when CA comes back up.
+ // In RA mSigningAlgorithms could be null at startup if CA is
+ // not
+ // up and set later when CA comes back up.
// Once it's set assumed that it won't change.
String[] allAlgorithms = mSigningAlgorithms;
if (allAlgorithms == null) {
- allAlgorithms = mSigningAlgorithms =
+ allAlgorithms = mSigningAlgorithms =
((ICertAuthority) mAuthority).getCASigningAlgorithms();
if (allAlgorithms == null) {
CMS.debug(
- "ProcessReq: signing algorithms set to All algorithms");
+ "ProcessReq: signing algorithms set to All algorithms");
allAlgorithms = AlgorithmId.ALL_SIGNING_ALGORITHMS;
- } else
+ } else
CMS.debug(
- "ProcessReq: First signing algorithms is " + allAlgorithms[0]);
+ "ProcessReq: First signing algorithms is " + allAlgorithms[0]);
}
String validAlgorithms = null;
StringBuffer sb = new StringBuffer();
@@ -310,10 +309,10 @@ public class ProcessReq extends CMSServlet {
if (signingAlgorithm != null)
header.addStringValue("caSigningAlgorithm", signingAlgorithm);
header.addLongValue("defaultValidityLength",
- ((ICertificateAuthority) mAuthority).getDefaultValidity() / 1000);
+ ((ICertificateAuthority) mAuthority).getDefaultValidity() / 1000);
} else if (mAuthority instanceof IRegistrationAuthority) {
header.addLongValue("defaultValidityLength",
- ((IRegistrationAuthority) mAuthority).getDefaultValidity() / 1000);
+ ((IRegistrationAuthority) mAuthority).getDefaultValidity() / 1000);
}
X509CertImpl caCert = ((ICertAuthority) mAuthority).getCACert();
@@ -328,8 +327,8 @@ public class ProcessReq extends CMSServlet {
} else {
log(ILogger.LL_FAILURE, "Invalid sequence number " + seqNum);
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_INVALID_REQUEST_ID",
- String.valueOf(seqNum)));
+ CMS.getUserMessage("CMS_GW_INVALID_REQUEST_ID",
+ String.valueOf(seqNum)));
}
return;
diff --git a/pki/base/common/src/com/netscape/cms/servlet/request/QueryReq.java b/pki/base/common/src/com/netscape/cms/servlet/request/QueryReq.java
index 036bd5d0..10c608b6 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/request/QueryReq.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/request/QueryReq.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.request;
-
import java.io.IOException;
import java.util.Enumeration;
import java.util.Locale;
@@ -45,10 +44,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* Show paged list of requests matching search criteria
- *
+ *
* @version $Revision$, $Date$
*/
public class QueryReq extends CMSServlet {
@@ -61,7 +59,7 @@ public class QueryReq extends CMSServlet {
private final static String IN_SHOW_ALL = "showAll";
private final static String IN_SHOW_WAITING = "showWaiting";
private final static String IN_SHOW_IN_SERVICE = "showInService";
- private final static String IN_SHOW_PENDING= "showPending";
+ private final static String IN_SHOW_PENDING = "showPending";
private final static String IN_SHOW_CANCELLED = "showCancelled";
private final static String IN_SHOW_REJECTED = "showRejected";
private final static String IN_SHOW_COMPLETED = "showCompleted";
@@ -85,17 +83,17 @@ public class QueryReq extends CMSServlet {
private final static String OUT_UPDATE_ON = "updatedOn";
private final static String OUT_UPDATE_BY = "updatedBy";
private final static String OUT_REQUESTING_USER = "requestingUser";
- //keeps track of where to begin if page down
+ // keeps track of where to begin if page down
private final static String OUT_FIRST_ENTRY_ON_PAGE = "firstEntryOnPage";
- //keeps track of where to begin if page up
+ // keeps track of where to begin if page up
private final static String OUT_LAST_ENTRY_ON_PAGE = "lastEntryOnPage";
private final static String OUT_SUBJECT = "subject";
private final static String OUT_REQUEST_TYPE = "requestType";
private final static String OUT_COMMENTS = "requestorComments";
private final static String OUT_SERIALNO = "serialNumber";
private final static String OUT_OWNER_NAME = "ownerName";
- private final static String OUT_PUBLIC_KEY_INFO =
- "subjectPublicKeyInfo";
+ private final static String OUT_PUBLIC_KEY_INFO =
+ "subjectPublicKeyInfo";
private final static String OUT_ERROR = "error";
private final static String OUT_AUTHORITY_ID = "authorityid";
@@ -119,7 +117,7 @@ public class QueryReq extends CMSServlet {
/**
* initialize the servlet. This servlet uses the template file
* "queryReq.template" to process the response.
- *
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -142,9 +140,9 @@ public class QueryReq extends CMSServlet {
mParser = CertReqParser.DETAIL_PARSER;
else if (tmp.trim().equals("KeyReqParser.PARSER"))
mParser = KeyReqParser.PARSER;
- }
+ }
- // override success and error templates to null -
+ // override success and error templates to null -
// handle templates locally.
mTemplates.remove(CMSRequest.SUCCESS);
mTemplates.remove(CMSRequest.ERROR);
@@ -152,7 +150,7 @@ public class QueryReq extends CMSServlet {
if (mOutputTemplatePath != null)
mFormPath = mOutputTemplatePath;
}
-
+
private String getRequestType(String p) {
String filter = "(requestType=*)";
@@ -212,348 +210,346 @@ public class QueryReq extends CMSServlet {
/**
* Process the HTTP request.
* <ul>
- * <li>http.param reqState request state
- * (one of showAll, showWaiting, showInService,
- * showCancelled, showRejected, showCompleted)
+ * <li>http.param reqState request state (one of showAll, showWaiting,
+ * showInService, showCancelled, showRejected, showCompleted)
* <li>http.param reqType
* <li>http.param seqNumFromDown request ID to start at (decimal, or hex if
- * when paging down
- * seqNumFromDown starts with 0x)
+ * when paging down seqNumFromDown starts with 0x)
* <li>http.param seqNumFromUp request ID to start at (decimal, or hex if
- * when paging up
- * seqNumFromUp starts with 0x)
+ * when paging up seqNumFromUp starts with 0x)
* <li>http.param maxCount maximum number of records to show
* <li>http.param totalCount total number of records in set of pages
* <li>http.param direction "up", "down", "begin", or "end"
* </ul>
- *
+ *
* @param cmsReq the object holding the request and response information
*/
public void process(CMSRequest cmsReq) throws EBaseException {
- CMS.debug("in QueryReq servlet");
-
- // Authentication / Authorization
-
- HttpServletRequest req = cmsReq.getHttpReq();
- IAuthToken authToken = authenticate(cmsReq);
- AuthzToken authzToken = null;
-
- try {
- authzToken = authorize(mAclMethod, authToken,
- mAuthzResourceName, "list");
- } catch (EAuthzAccessDenied e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
- } catch (Exception e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
- }
- if (authzToken == null) {
- cmsReq.setStatus(CMSRequest.UNAUTHORIZED);
- return;
- }
-
-
-
-
- CMSTemplate form = null;
- Locale[] locale = new Locale[1];
-
- try {
- // if get a EBaseException we just throw it.
- form = getTemplate(mFormPath, req, locale);
- } catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
- throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
- }
-
- /**
- * WARNING:
- *
- * PLEASE DO NOT TOUCH THE FILTER HERE. ALL FILTERS ARE INDEXED.
- *
- **/
- String filter = null;
- String reqState = req.getParameter("reqState");
- String reqType = req.getParameter("reqType");
-
- if (reqState == null || reqType == null) {
- filter = "(requeststate=*)";
- } else if (reqState.equals(IN_SHOW_ALL) &&
- reqType.equals(IN_SHOW_ALL)) {
- filter = "(requeststate=*)";
- } else if (reqState.equals(IN_SHOW_ALL)) {
- filter = getRequestType(reqType);
- } else if (reqType.equals(IN_SHOW_ALL)) {
- filter = getRequestState(reqState);
- } else {
- filter = "(&" + getRequestState(reqState) +
- getRequestType(reqType) + ")";
- }
-
- String direction = "begin";
- if (req.getParameter("direction") != null) {
- direction = req.getParameter("direction").trim();
- }
-
-
- int top=0, bottom=0;
-
- try {
- String top_s = req.getParameter(OUT_FIRST_ENTRY_ON_PAGE);
- if (top_s == null) top_s = "0";
-
- String bottom_s = req.getParameter(OUT_LAST_ENTRY_ON_PAGE);
- if (bottom_s == null) bottom_s = "0";
-
- if (top_s.trim().startsWith("0x")) {
- top = Integer.parseInt(top_s.trim().substring(2), 16);
- } else {
- top = Integer.parseInt(top_s.trim());
- }
- if (bottom_s.trim().startsWith("0x")) {
- bottom = Integer.parseInt(bottom_s.trim().substring(2), 16);
- } else {
- bottom = Integer.parseInt(bottom_s.trim());
- }
-
- } catch (NumberFormatException e) {
-
- }
-
- // avoid NumberFormatException to the user interface
- int maxCount = 10;
- try {
- maxCount = Integer.parseInt(req.getParameter(IN_MAXCOUNT));
- } catch (Exception e) {
- }
+ CMS.debug("in QueryReq servlet");
+
+ // Authentication / Authorization
+
+ HttpServletRequest req = cmsReq.getHttpReq();
+ IAuthToken authToken = authenticate(cmsReq);
+ AuthzToken authzToken = null;
+
+ try {
+ authzToken = authorize(mAclMethod, authToken,
+ mAuthzResourceName, "list");
+ } catch (EAuthzAccessDenied e) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ } catch (Exception e) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ }
+ if (authzToken == null) {
+ cmsReq.setStatus(CMSRequest.UNAUTHORIZED);
+ return;
+ }
+
+ CMSTemplate form = null;
+ Locale[] locale = new Locale[1];
+
+ try {
+ // if get a EBaseException we just throw it.
+ form = getTemplate(mFormPath, req, locale);
+ } catch (IOException e) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
+ throw new ECMSGWException(
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ }
+
+ /**
+ * WARNING:
+ *
+ * PLEASE DO NOT TOUCH THE FILTER HERE. ALL FILTERS ARE INDEXED.
+ *
+ **/
+ String filter = null;
+ String reqState = req.getParameter("reqState");
+ String reqType = req.getParameter("reqType");
+
+ if (reqState == null || reqType == null) {
+ filter = "(requeststate=*)";
+ } else if (reqState.equals(IN_SHOW_ALL) &&
+ reqType.equals(IN_SHOW_ALL)) {
+ filter = "(requeststate=*)";
+ } else if (reqState.equals(IN_SHOW_ALL)) {
+ filter = getRequestType(reqType);
+ } else if (reqType.equals(IN_SHOW_ALL)) {
+ filter = getRequestState(reqState);
+ } else {
+ filter = "(&" + getRequestState(reqState) +
+ getRequestType(reqType) + ")";
+ }
+
+ String direction = "begin";
+ if (req.getParameter("direction") != null) {
+ direction = req.getParameter("direction").trim();
+ }
+
+ int top = 0, bottom = 0;
+
+ try {
+ String top_s = req.getParameter(OUT_FIRST_ENTRY_ON_PAGE);
+ if (top_s == null)
+ top_s = "0";
+
+ String bottom_s = req.getParameter(OUT_LAST_ENTRY_ON_PAGE);
+ if (bottom_s == null)
+ bottom_s = "0";
+
+ if (top_s.trim().startsWith("0x")) {
+ top = Integer.parseInt(top_s.trim().substring(2), 16);
+ } else {
+ top = Integer.parseInt(top_s.trim());
+ }
+ if (bottom_s.trim().startsWith("0x")) {
+ bottom = Integer.parseInt(bottom_s.trim().substring(2), 16);
+ } else {
+ bottom = Integer.parseInt(bottom_s.trim());
+ }
+
+ } catch (NumberFormatException e) {
+
+ }
+
+ // avoid NumberFormatException to the user interface
+ int maxCount = 10;
+ try {
+ maxCount = Integer.parseInt(req.getParameter(IN_MAXCOUNT));
+ } catch (Exception e) {
+ }
if (maxCount > mMaxReturns) {
CMS.debug("Resetting page size from " + maxCount + " to " + mMaxReturns);
maxCount = mMaxReturns;
}
- HttpServletResponse resp = cmsReq.getHttpResp();
- CMSTemplateParams argset = doSearch(locale[0],filter, maxCount, direction, top, bottom );
-
-
- argset.getFixed().addStringValue("reqType",reqType);
+ HttpServletResponse resp = cmsReq.getHttpResp();
+ CMSTemplateParams argset = doSearch(locale[0], filter, maxCount, direction, top, bottom);
+
+ argset.getFixed().addStringValue("reqType", reqType);
argset.getFixed().addStringValue("reqState", reqState);
- argset.getFixed().addIntegerValue("maxCount",maxCount);
-
-
- try {
- form.getOutput(argset);
- resp.setContentType("text/html");
- form.renderOutput(resp.getOutputStream(), argset);
- } catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
- throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
- }
- cmsReq.setStatus(CMSRequest.SUCCESS);
- return;
+ argset.getFixed().addIntegerValue("maxCount", maxCount);
+
+ try {
+ form.getOutput(argset);
+ resp.setContentType("text/html");
+ form.renderOutput(resp.getOutputStream(), argset);
+ } catch (IOException e) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
+ throw new ECMSGWException(
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ }
+ cmsReq.setStatus(CMSRequest.SUCCESS);
+ return;
}
/**
* Perform search based on direction button pressed
- * @param filter ldap filter indicating which VLV to search through. This can be
- * 'all requests', 'pending', etc
+ *
+ * @param filter ldap filter indicating which VLV to search through. This
+ * can be 'all requests', 'pending', etc
* @param count the number of requests to show per page
- * @param direction either 'begin', 'end', 'previous' or 'next' (defaults to end)
- * @param top the number of the request shown on at the top of the current page
- * @param bottom the number of the request shown on at the bottom of the current page
- * @return
+ * @param direction either 'begin', 'end', 'previous' or 'next' (defaults to
+ * end)
+ * @param top the number of the request shown on at the top of the current
+ * page
+ * @param bottom the number of the request shown on at the bottom of the
+ * current page
+ * @return
*/
-
+
private CMSTemplateParams doSearch(Locale l, String filter,
- int count, String direction, int top, int bottom)
- {
- CMSTemplateParams ctp = null;
- if (direction.equals("previous")) {
- ctp = doSearch(l, filter, -count, top-1);
- } else if (direction.equals("next")) {
- ctp = doSearch(l,filter, count, bottom+1);
- } else if (direction.equals("begin")) {
- ctp = doSearch(l,filter, count, 0);
- } else if (direction.equals("first")) {
- ctp = doSearch(l,filter, count, bottom);
- } else { // if 'direction is 'end', default here
- ctp = doSearch(l,filter, -count, -1);
- }
- return ctp;
+ int count, String direction, int top, int bottom) {
+ CMSTemplateParams ctp = null;
+ if (direction.equals("previous")) {
+ ctp = doSearch(l, filter, -count, top - 1);
+ } else if (direction.equals("next")) {
+ ctp = doSearch(l, filter, count, bottom + 1);
+ } else if (direction.equals("begin")) {
+ ctp = doSearch(l, filter, count, 0);
+ } else if (direction.equals("first")) {
+ ctp = doSearch(l, filter, count, bottom);
+ } else { // if 'direction is 'end', default here
+ ctp = doSearch(l, filter, -count, -1);
+ }
+ return ctp;
}
-
-
-
- /**
- *
- * @param locale
- * @param filter the types of requests to return - this must match the VLV index
- * @param count maximum number of records to return
- * @param marker indication of the request ID where the page is anchored
- * @return
- */
+
+ /**
+ *
+ * @param locale
+ * @param filter the types of requests to return - this must match the VLV
+ * index
+ * @param count maximum number of records to return
+ * @param marker indication of the request ID where the page is anchored
+ * @return
+ */
private CMSTemplateParams doSearch(
- Locale locale,
- String filter,
- int count,
- int marker) {
-
- IArgBlock header = CMS.createArgBlock();
- IArgBlock context = CMS.createArgBlock();
- CMSTemplateParams argset = new CMSTemplateParams(header, context);
-
- try {
- long startTime = CMS.getCurrentDate().getTime();
- // preserve the type of request that we are
- // requesting.
-
- header.addStringValue(OUT_AUTHORITY_ID, mAuthority.getId());
- header.addStringValue(OUT_REQUESTING_USER, "admin");
-
-
- boolean jumptoend = false;
- if (marker == -1) {
- marker = 0; // I think this is inconsequential
- jumptoend = true; // override to '99' during search
- }
-
- RequestId id = new RequestId(Integer.toString(marker));
- IRequestVirtualList list = mQueue.getPagedRequestsByFilter(
- id,
- jumptoend,
- filter,
- count+1,
- "requestId");
-
- int totalCount = list.getSize() - list.getCurrentIndex();
- header.addIntegerValue(OUT_TOTALCOUNT, totalCount);
- header.addIntegerValue(OUT_CURRENTCOUNT, list.getSize());
-
- int numEntries = list.getSize() - list.getCurrentIndex();
-
- Vector v = fetchRecords(list,Math.abs(count));
- v = normalizeOrder(v);
- trim(v,id);
-
-
- int currentCount = 0;
- int curNum = 0;
- int firstNum = -1;
- Enumeration requests = v.elements();
-
- while (requests.hasMoreElements()) {
- IRequest request = null;
- try {
- request = (IRequest) requests.nextElement();
- } catch (Exception e) {
- CMS.debug("Error displaying request:"+e.getMessage());
- // handled below
- }
- if (request == null) {
- log(ILogger.LL_WARN, "Error display request on page");
- continue;
- }
-
- curNum = Integer.parseInt(
- request.getRequestId().toString());
-
- if (firstNum == -1) {
- firstNum = curNum;
- }
-
- IArgBlock rec = CMS.createArgBlock();
- mParser.fillRequestIntoArg(locale, request, argset, rec);
- mQueue.releaseRequest(request);
- argset.addRepeatRecord(rec);
-
- currentCount++;
-
- }// while
- long endTime = CMS.getCurrentDate().getTime();
-
- header.addIntegerValue(OUT_CURRENTCOUNT, currentCount);
- header.addStringValue("time", Long.toString(endTime - startTime));
- header.addIntegerValue(OUT_FIRST_ENTRY_ON_PAGE, firstNum);
- header.addIntegerValue(OUT_LAST_ENTRY_ON_PAGE, curNum);
-
- } catch (EBaseException e) {
- header.addStringValue(OUT_ERROR, e.toString(locale));
- } catch (Exception e) {
- }
- return argset;
-
+ Locale locale,
+ String filter,
+ int count,
+ int marker) {
+
+ IArgBlock header = CMS.createArgBlock();
+ IArgBlock context = CMS.createArgBlock();
+ CMSTemplateParams argset = new CMSTemplateParams(header, context);
+
+ try {
+ long startTime = CMS.getCurrentDate().getTime();
+ // preserve the type of request that we are
+ // requesting.
+
+ header.addStringValue(OUT_AUTHORITY_ID, mAuthority.getId());
+ header.addStringValue(OUT_REQUESTING_USER, "admin");
+
+ boolean jumptoend = false;
+ if (marker == -1) {
+ marker = 0; // I think this is inconsequential
+ jumptoend = true; // override to '99' during search
+ }
+
+ RequestId id = new RequestId(Integer.toString(marker));
+ IRequestVirtualList list = mQueue.getPagedRequestsByFilter(
+ id,
+ jumptoend,
+ filter,
+ count + 1,
+ "requestId");
+
+ int totalCount = list.getSize() - list.getCurrentIndex();
+ header.addIntegerValue(OUT_TOTALCOUNT, totalCount);
+ header.addIntegerValue(OUT_CURRENTCOUNT, list.getSize());
+
+ int numEntries = list.getSize() - list.getCurrentIndex();
+
+ Vector v = fetchRecords(list, Math.abs(count));
+ v = normalizeOrder(v);
+ trim(v, id);
+
+ int currentCount = 0;
+ int curNum = 0;
+ int firstNum = -1;
+ Enumeration requests = v.elements();
+
+ while (requests.hasMoreElements()) {
+ IRequest request = null;
+ try {
+ request = (IRequest) requests.nextElement();
+ } catch (Exception e) {
+ CMS.debug("Error displaying request:" + e.getMessage());
+ // handled below
+ }
+ if (request == null) {
+ log(ILogger.LL_WARN, "Error display request on page");
+ continue;
+ }
+
+ curNum = Integer.parseInt(
+ request.getRequestId().toString());
+
+ if (firstNum == -1) {
+ firstNum = curNum;
+ }
+
+ IArgBlock rec = CMS.createArgBlock();
+ mParser.fillRequestIntoArg(locale, request, argset, rec);
+ mQueue.releaseRequest(request);
+ argset.addRepeatRecord(rec);
+
+ currentCount++;
+
+ }// while
+ long endTime = CMS.getCurrentDate().getTime();
+
+ header.addIntegerValue(OUT_CURRENTCOUNT, currentCount);
+ header.addStringValue("time", Long.toString(endTime - startTime));
+ header.addIntegerValue(OUT_FIRST_ENTRY_ON_PAGE, firstNum);
+ header.addIntegerValue(OUT_LAST_ENTRY_ON_PAGE, curNum);
+
+ } catch (EBaseException e) {
+ header.addStringValue(OUT_ERROR, e.toString(locale));
+ } catch (Exception e) {
+ }
+ return argset;
+
}
/**
* If the vector contains the marker element at the end, remove it.
- * @param v The vector to trim
- * @param marker the marker to look for.
+ *
+ * @param v The vector to trim
+ * @param marker the marker to look for.
+ */
+ private void trim(Vector v, RequestId marker) {
+ int i = v.size() - 1;
+ if (((IRequest) v.elementAt(i)).getRequestId().equals(marker)) {
+ v.remove(i);
+ }
+
+ }
+
+ /**
+ * Sometimes the list comes back from LDAP in reverse order. This function
+ * makes sure the results are in 'forward' order.
+ *
+ * @param list
+ * @return
*/
- private void trim(Vector v, RequestId marker) {
- int i = v.size()-1;
- if (((IRequest)v.elementAt(i)).getRequestId().equals(marker)) {
- v.remove(i);
- }
-
- }
-
- /**
- * Sometimes the list comes back from LDAP in reverse order. This function makes
- * sure the results are in 'forward' order.
- * @param list
- * @return
- */
private Vector fetchRecords(IRequestVirtualList list, int maxCount) {
-
- Vector v = new Vector();
- int count = list.getSize();
- int c=0;
- for (int i=0; i<count; i++) {
- IRequest request = list.getElementAt(i);
- if (request != null) {
- v.add(request);
- c++;
- }
- if (c >= maxCount) break;
- }
-
- return v;
+
+ Vector v = new Vector();
+ int count = list.getSize();
+ int c = 0;
+ for (int i = 0; i < count; i++) {
+ IRequest request = list.getElementAt(i);
+ if (request != null) {
+ v.add(request);
+ c++;
+ }
+ if (c >= maxCount)
+ break;
+ }
+
+ return v;
}
/**
* If the requests are in backwards order, reverse the list
+ *
* @param list
* @return
*/
private Vector normalizeOrder(Vector list) {
-
- int firstrequestnum = Integer.parseInt(((IRequest) list.elementAt(0))
- .getRequestId().toString());
- int lastrequestnum = Integer.parseInt(((IRequest) list.elementAt(list
- .size() - 1)).getRequestId().toString());
- boolean reverse = false;
- if (firstrequestnum > lastrequestnum) {
- reverse = true; // if the order is backwards, place items at the beginning
- }
- Vector v = new Vector();
- int count = list.size();
- for (int i = 0; i < count; i++) {
- Object request = list.elementAt(i);
- if (request != null) {
- if (reverse)
- v.add(0, request);
- else
- v.add(request);
- }
- }
-
- return v;
+
+ int firstrequestnum = Integer.parseInt(((IRequest) list.elementAt(0))
+ .getRequestId().toString());
+ int lastrequestnum = Integer.parseInt(((IRequest) list.elementAt(list
+ .size() - 1)).getRequestId().toString());
+ boolean reverse = false;
+ if (firstrequestnum > lastrequestnum) {
+ reverse = true; // if the order is backwards, place items at the
+ // beginning
+ }
+ Vector v = new Vector();
+ int count = list.size();
+ for (int i = 0; i < count; i++) {
+ Object request = list.elementAt(i);
+ if (request != null) {
+ if (reverse)
+ v.add(0, request);
+ else
+ v.add(request);
+ }
+ }
+
+ return v;
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/request/ReqParser.java b/pki/base/common/src/com/netscape/cms/servlet/request/ReqParser.java
index 29414ca5..00f95ec2 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/request/ReqParser.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/request/ReqParser.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.request;
-
import java.util.Locale;
import com.netscape.certsrv.base.EBaseException;
@@ -26,11 +25,10 @@ import com.netscape.certsrv.base.SessionContext;
import com.netscape.certsrv.request.IRequest;
import com.netscape.cms.servlet.common.CMSTemplateParams;
-
/**
* A class representing a request parser.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class ReqParser implements IReqParser {
@@ -51,29 +49,30 @@ public class ReqParser implements IReqParser {
* Maps request object into argument block.
*/
public void fillRequestIntoArg(Locale l, IRequest req, CMSTemplateParams argSet, IArgBlock arg)
- throws EBaseException {
+ throws EBaseException {
arg.addStringValue(TYPE, req.getRequestType());
- arg.addLongValue("seqNum",
- Long.parseLong(req.getRequestId().toString()));
- arg.addStringValue(STATUS,
- req.getRequestStatus().toString());
- arg.addLongValue(CREATE_ON,
- req.getCreationTime().getTime() / 1000);
- arg.addLongValue(UPDATE_ON,
- req.getModificationTime().getTime() / 1000);
+ arg.addLongValue("seqNum",
+ Long.parseLong(req.getRequestId().toString()));
+ arg.addStringValue(STATUS,
+ req.getRequestStatus().toString());
+ arg.addLongValue(CREATE_ON,
+ req.getCreationTime().getTime() / 1000);
+ arg.addLongValue(UPDATE_ON,
+ req.getModificationTime().getTime() / 1000);
String updatedBy = req.getExtDataInString(IRequest.UPDATED_BY);
- if (updatedBy == null) updatedBy = "";
+ if (updatedBy == null)
+ updatedBy = "";
arg.addStringValue(UPDATE_BY, updatedBy);
SessionContext ctx = SessionContext.getContext();
- String id = (String) ctx.get(SessionContext.USER_ID);
+ String id = (String) ctx.get(SessionContext.USER_ID);
arg.addStringValue("callerName", id);
-
+
String owner = req.getRequestOwner();
- if (owner != null)
+ if (owner != null)
arg.addStringValue("assignedTo", owner);
}
}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/request/SearchReqs.java b/pki/base/common/src/com/netscape/cms/servlet/request/SearchReqs.java
index 04b21440..c660be24 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/request/SearchReqs.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/request/SearchReqs.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.request;
-
import java.io.IOException;
import java.math.BigInteger;
import java.util.Date;
@@ -48,10 +47,9 @@ import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
-
/**
* Search for certificates matching complex query filter
- *
+ *
* @version $Revision$, $Date$
*/
public class SearchReqs extends CMSServlet {
@@ -90,8 +88,9 @@ public class SearchReqs extends CMSServlet {
}
/**
- * initialize the servlet. This servlet uses queryReq.template
- * to render the response
+ * initialize the servlet. This servlet uses queryReq.template to render the
+ * response
+ *
* @param sc servlet configuration, read from the web.xml file
*/
public void init(ServletConfig sc) throws ServletException {
@@ -154,10 +153,8 @@ public class SearchReqs extends CMSServlet {
/**
* Serves HTTP request. This format of this request is as follows:
- * queryCert?
- * [maxCount=<number>]
- * [queryFilter=<filter>]
- * [revokeAll=<filter>]
+ * queryCert? [maxCount=<number>] [queryFilter=<filter>]
+ * [revokeAll=<filter>]
*/
public void process(CMSRequest cmsReq) throws EBaseException {
HttpServletRequest req = cmsReq.getHttpReq();
@@ -172,10 +169,10 @@ public class SearchReqs extends CMSServlet {
mAuthzResourceName, "list");
} catch (EAuthzAccessDenied e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
}
if (authzToken == null) {
@@ -198,10 +195,10 @@ public class SearchReqs extends CMSServlet {
try {
form = getTemplate(mFormPath, req, locale);
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
try {
@@ -215,10 +212,10 @@ public class SearchReqs extends CMSServlet {
timeLimit = Integer.parseInt(timeLimitStr);
process(argSet, header, req.getParameter("queryRequestFilter"), authToken,
- maxResults, timeLimit, req, resp, locale[0]);
+ maxResults, timeLimit, req, resp, locale[0]);
} catch (NumberFormatException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("BASE_INVALID_NUMBER_FORMAT"));
- error = new EBaseException(CMS.getUserMessage(getLocale(req),"CMS_BASE_INVALID_NUMBER_FORMAT"));
+ error = new EBaseException(CMS.getUserMessage(getLocale(req), "CMS_BASE_INVALID_NUMBER_FORMAT"));
} catch (EBaseException e) {
error = e;
}
@@ -229,33 +226,33 @@ public class SearchReqs extends CMSServlet {
if (error == null) {
String xmlOutput = req.getParameter("xml");
if (xmlOutput != null && xmlOutput.equals("true")) {
- outputXML(resp, argSet);
+ outputXML(resp, argSet);
} else {
- cmsReq.setStatus(CMSRequest.SUCCESS);
- resp.setContentType("text/html");
- form.renderOutput(out, argSet);
+ cmsReq.setStatus(CMSRequest.SUCCESS);
+ resp.setContentType("text/html");
+ form.renderOutput(out, argSet);
}
} else {
cmsReq.setStatus(CMSRequest.ERROR);
cmsReq.setError(error);
}
} catch (IOException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSGW_ERR_OUT_STREAM_TEMPLATE", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_OUT_STREAM_TEMPLATE", e.toString()));
throw new ECMSGWException(
- CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
}
}
/**
* Process the key search.
*/
- private void process(CMSTemplateParams argSet, IArgBlock header,
- String filter, IAuthToken token,
- int maxResults, int timeLimit,
- HttpServletRequest req, HttpServletResponse resp,
- Locale locale)
- throws EBaseException {
+ private void process(CMSTemplateParams argSet, IArgBlock header,
+ String filter, IAuthToken token,
+ int maxResults, int timeLimit,
+ HttpServletRequest req, HttpServletResponse resp,
+ Locale locale)
+ throws EBaseException {
try {
long startTime = CMS.getCurrentDate().getTime();
@@ -272,12 +269,12 @@ public class SearchReqs extends CMSServlet {
} else {
if (owner.equals("self")) {
String self_uid = token.getInString(IAuthToken.USER_ID);
- requestowner_filter = "(requestowner="+self_uid+")";
+ requestowner_filter = "(requestowner=" + self_uid + ")";
} else {
String uid = req.getParameter("uid");
- requestowner_filter = "(requestowner="+uid+")";
+ requestowner_filter = "(requestowner=" + uid + ")";
}
- newfilter = "(&"+requestowner_filter+filter.substring(2);
+ newfilter = "(&" + requestowner_filter + filter.substring(2);
}
// xxx the filter includes serial number range???
if (maxResults == -1 || maxResults > mMaxReturns) {
@@ -289,8 +286,8 @@ public class SearchReqs extends CMSServlet {
timeLimit = mTimeLimits;
}
IRequestList list = (timeLimit > 0) ?
- mQueue.listRequestsByFilter(newfilter, maxResults, timeLimit) :
- mQueue.listRequestsByFilter(newfilter, maxResults);
+ mQueue.listRequestsByFilter(newfilter, maxResults, timeLimit) :
+ mQueue.listRequestsByFilter(newfilter, maxResults);
int count = 0;
@@ -323,7 +320,8 @@ public class SearchReqs extends CMSServlet {
int i = filter.indexOf(CURRENT_TIME, k);
while (i > -1) {
- if (now == null) now = new Date();
+ if (now == null)
+ now = new Date();
newFilter.append(filter.substring(k, i));
newFilter.append(now.getTime());
k = i + CURRENT_TIME.length();
diff --git a/pki/base/common/src/com/netscape/cms/servlet/tks/TokenServlet.java b/pki/base/common/src/com/netscape/cms/servlet/tks/TokenServlet.java
index ca785565..d9919723 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/tks/TokenServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/tks/TokenServlet.java
@@ -50,14 +50,11 @@ import com.netscape.cms.servlet.base.CMSServlet;
import com.netscape.cms.servlet.common.CMSRequest;
import com.netscape.symkey.SessionKey;
-
-
/**
- * A class representings an administration servlet for Token Key
- * Service Authority. This servlet is responsible to serve
- * tks administrative operation such as configuration
- * parameter updates.
- *
+ * A class representings an administration servlet for Token Key Service
+ * Authority. This servlet is responsible to serve tks administrative operation
+ * such as configuration parameter updates.
+ *
* @version $Revision$, $Date$
*/
public class TokenServlet extends CMSServlet {
@@ -66,66 +63,53 @@ public class TokenServlet extends CMSServlet {
*/
private static final long serialVersionUID = 8687436109695172791L;
protected static final String PROP_ENABLED = "enabled";
- protected static final String TRANSPORT_KEY_NAME ="sharedSecret";
+ protected static final String TRANSPORT_KEY_NAME = "sharedSecret";
private final static String INFO = "TokenServlet";
public static int ERROR = 1;
private ITKSAuthority mTKS = null;
private String mSelectedToken = null;
private String mNewSelectedToken = null;
String mKeyNickName = null;
- String mNewKeyNickName = null;
+ String mNewKeyNickName = null;
private final static String LOGGING_SIGNED_AUDIT_CONFIG_DRM =
- "LOGGING_SIGNED_AUDIT_CONFIG_DRM_3";
+ "LOGGING_SIGNED_AUDIT_CONFIG_DRM_3";
IPrettyPrintFormat pp = CMS.getPrettyPrintFormat(":");
- private final static String
- LOGGING_SIGNED_AUDIT_COMPUTE_SESSION_KEY_REQUEST =
- "LOGGING_SIGNED_AUDIT_COMPUTE_SESSION_KEY_REQUEST_3";
-
- private final static String
- LOGGING_SIGNED_AUDIT_COMPUTE_SESSION_KEY_REQUEST_PROCESSED_SUCCESS =
- "LOGGING_SIGNED_AUDIT_COMPUTE_SESSION_KEY_REQUEST_PROCESSED_SUCCESS_8";
+ private final static String LOGGING_SIGNED_AUDIT_COMPUTE_SESSION_KEY_REQUEST =
+ "LOGGING_SIGNED_AUDIT_COMPUTE_SESSION_KEY_REQUEST_3";
- private final static String
- LOGGING_SIGNED_AUDIT_COMPUTE_SESSION_KEY_REQUEST_PROCESSED_FAILURE =
- "LOGGING_SIGNED_AUDIT_COMPUTE_SESSION_KEY_REQUEST_PROCESSED_FAILURE_9";
+ private final static String LOGGING_SIGNED_AUDIT_COMPUTE_SESSION_KEY_REQUEST_PROCESSED_SUCCESS =
+ "LOGGING_SIGNED_AUDIT_COMPUTE_SESSION_KEY_REQUEST_PROCESSED_SUCCESS_8";
- private final static String
- LOGGING_SIGNED_AUDIT_DIVERSIFY_KEY_REQUEST =
- "LOGGING_SIGNED_AUDIT_DIVERSIFY_KEY_REQUEST_5";
+ private final static String LOGGING_SIGNED_AUDIT_COMPUTE_SESSION_KEY_REQUEST_PROCESSED_FAILURE =
+ "LOGGING_SIGNED_AUDIT_COMPUTE_SESSION_KEY_REQUEST_PROCESSED_FAILURE_9";
- private final static String
- LOGGING_SIGNED_AUDIT_DIVERSIFY_KEY_REQUEST_PROCESSED_SUCCESS =
- "LOGGING_SIGNED_AUDIT_DIVERSIFY_KEY_REQUEST_PROCESSED_SUCCESS_6";
+ private final static String LOGGING_SIGNED_AUDIT_DIVERSIFY_KEY_REQUEST =
+ "LOGGING_SIGNED_AUDIT_DIVERSIFY_KEY_REQUEST_5";
- private final static String
- LOGGING_SIGNED_AUDIT_DIVERSIFY_KEY_REQUEST_PROCESSED_FAILURE =
- "LOGGING_SIGNED_AUDIT_DIVERSIFY_KEY_REQUEST_PROCESSED_FAILURE_7";
+ private final static String LOGGING_SIGNED_AUDIT_DIVERSIFY_KEY_REQUEST_PROCESSED_SUCCESS =
+ "LOGGING_SIGNED_AUDIT_DIVERSIFY_KEY_REQUEST_PROCESSED_SUCCESS_6";
+ private final static String LOGGING_SIGNED_AUDIT_DIVERSIFY_KEY_REQUEST_PROCESSED_FAILURE =
+ "LOGGING_SIGNED_AUDIT_DIVERSIFY_KEY_REQUEST_PROCESSED_FAILURE_7";
- private final static String
- LOGGING_SIGNED_AUDIT_ENCRYPT_DATA_REQUEST =
- "LOGGING_SIGNED_AUDIT_ENCRYPT_DATA_REQUEST_4";
+ private final static String LOGGING_SIGNED_AUDIT_ENCRYPT_DATA_REQUEST =
+ "LOGGING_SIGNED_AUDIT_ENCRYPT_DATA_REQUEST_4";
- private final static String
- LOGGING_SIGNED_AUDIT_ENCRYPT_DATA_REQUEST_PROCESSED_SUCCESS =
- "LOGGING_SIGNED_AUDIT_ENCRYPT_DATA_REQUEST_PROCESSED_SUCCESS_7";
+ private final static String LOGGING_SIGNED_AUDIT_ENCRYPT_DATA_REQUEST_PROCESSED_SUCCESS =
+ "LOGGING_SIGNED_AUDIT_ENCRYPT_DATA_REQUEST_PROCESSED_SUCCESS_7";
- private final static String
- LOGGING_SIGNED_AUDIT_ENCRYPT_DATA_REQUEST_PROCESSED_FAILURE =
- "LOGGING_SIGNED_AUDIT_ENCRYPT_DATA_REQUEST_PROCESSED_FAILURE_8";
+ private final static String LOGGING_SIGNED_AUDIT_ENCRYPT_DATA_REQUEST_PROCESSED_FAILURE =
+ "LOGGING_SIGNED_AUDIT_ENCRYPT_DATA_REQUEST_PROCESSED_FAILURE_8";
- private final static String
- LOGGING_SIGNED_AUDIT_COMPUTE_RANDOM_DATA_REQUEST =
- "LOGGING_SIGNED_AUDIT_COMPUTE_RANDOM_DATA_REQUEST_2";
+ private final static String LOGGING_SIGNED_AUDIT_COMPUTE_RANDOM_DATA_REQUEST =
+ "LOGGING_SIGNED_AUDIT_COMPUTE_RANDOM_DATA_REQUEST_2";
- private final static String
- LOGGING_SIGNED_AUDIT_COMPUTE_RANDOM_DATA_REQUEST_PROCESSED_SUCCESS =
- "LOGGING_SIGNED_AUDIT_COMPUTE_RANDOM_DATA_REQUEST_PROCESSED_SUCCESS_3";
+ private final static String LOGGING_SIGNED_AUDIT_COMPUTE_RANDOM_DATA_REQUEST_PROCESSED_SUCCESS =
+ "LOGGING_SIGNED_AUDIT_COMPUTE_RANDOM_DATA_REQUEST_PROCESSED_SUCCESS_3";
- private final static String
- LOGGING_SIGNED_AUDIT_COMPUTE_RANDOM_DATA_REQUEST_PROCESSED_FAILURE =
- "LOGGING_SIGNED_AUDIT_COMPUTE_RANDOM_DATA_REQUEST_PROCESSED_FAILURE_4";
+ private final static String LOGGING_SIGNED_AUDIT_COMPUTE_RANDOM_DATA_REQUEST_PROCESSED_FAILURE =
+ "LOGGING_SIGNED_AUDIT_COMPUTE_RANDOM_DATA_REQUEST_PROCESSED_FAILURE_4";
/**
* Constructs tks servlet.
@@ -135,14 +119,13 @@ public class TokenServlet extends CMSServlet {
}
- public static String trim(String a)
- {
- StringBuffer newa = new StringBuffer();
+ public static String trim(String a) {
+ StringBuffer newa = new StringBuffer();
StringTokenizer tokens = new StringTokenizer(a, "\n");
- while (tokens.hasMoreTokens()) {
- newa.append(tokens.nextToken());
- }
- return newa.toString();
+ while (tokens.hasMoreTokens()) {
+ newa.append(tokens.nextToken());
+ }
+ return newa.toString();
}
public void init(ServletConfig config) throws ServletException {
@@ -151,18 +134,19 @@ public class TokenServlet extends CMSServlet {
/**
* Returns serlvet information.
- *
+ *
* @return name of this servlet
*/
- public String getServletInfo() {
- return INFO;
+ public String getServletInfo() {
+ return INFO;
}
- /**
- * Process the HTTP request.
- *
+
+ /**
+ * Process the HTTP request.
+ *
* @param s The URL to decode.
*/
- protected String URLdecode(String s) {
+ protected String URLdecode(String s) {
if (s == null)
return null;
ByteArrayOutputStream out = new ByteArrayOutputStream(s.length());
@@ -182,62 +166,59 @@ public class TokenServlet extends CMSServlet {
}
} // end for
return out.toString();
- }
+ }
+
+ private void setDefaultSlotAndKeyName(HttpServletRequest req) {
+ try {
- private void setDefaultSlotAndKeyName(HttpServletRequest req)
- {
- try {
+ String keySet = req.getParameter("keySet");
+ if (keySet == null || keySet.equals("")) {
+ keySet = "defKeySet";
+ }
+ CMS.debug("keySet selected: " + keySet);
- String keySet = req.getParameter("keySet");
- if (keySet == null || keySet.equals("")) {
- keySet = "defKeySet";
- }
- CMS.debug("keySet selected: " + keySet);
+ mNewSelectedToken = null;
- mNewSelectedToken = null;
-
- mSelectedToken = CMS.getConfigStore().getString("tks.defaultSlot");
- String masterKeyPrefix = CMS.getConfigStore().getString("tks.master_key_prefix", null);
- String temp = req.getParameter("KeyInfo"); //#xx#xx
- String keyInfoMap = "tks." + keySet + ".mk_mappings." + temp;
- String mappingValue = CMS.getConfigStore().getString(keyInfoMap, null);
- if(mappingValue!=null)
- {
- StringTokenizer st = new StringTokenizer(mappingValue, ":");
- int tokenNumber=0;
- while (st.hasMoreTokens()) {
-
- String currentToken= st.nextToken();
- if(tokenNumber==0)
- mSelectedToken = currentToken;
- else if(tokenNumber==1)
- mKeyNickName = currentToken;
- tokenNumber++;
-
- }
+ mSelectedToken = CMS.getConfigStore().getString("tks.defaultSlot");
+ String masterKeyPrefix = CMS.getConfigStore().getString("tks.master_key_prefix", null);
+ String temp = req.getParameter("KeyInfo"); // #xx#xx
+ String keyInfoMap = "tks." + keySet + ".mk_mappings." + temp;
+ String mappingValue = CMS.getConfigStore().getString(keyInfoMap, null);
+ if (mappingValue != null) {
+ StringTokenizer st = new StringTokenizer(mappingValue, ":");
+ int tokenNumber = 0;
+ while (st.hasMoreTokens()) {
+
+ String currentToken = st.nextToken();
+ if (tokenNumber == 0)
+ mSelectedToken = currentToken;
+ else if (tokenNumber == 1)
+ mKeyNickName = currentToken;
+ tokenNumber++;
+
+ }
}
- if(req.getParameter("newKeyInfo")!=null) // for diversification
+ if (req.getParameter("newKeyInfo") != null) // for diversification
{
- temp = req.getParameter("newKeyInfo"); //#xx#xx
- String newKeyInfoMap = "tks." + keySet + ".mk_mappings." + temp;
- String newMappingValue = CMS.getConfigStore().getString(newKeyInfoMap, null);
- if(newMappingValue!=null)
- {
- StringTokenizer st = new StringTokenizer(newMappingValue, ":");
- int tokenNumber=0;
- while (st.hasMoreTokens()) {
- String currentToken= st.nextToken();
- if(tokenNumber==0)
- mNewSelectedToken = currentToken;
- else if(tokenNumber==1)
- mNewKeyNickName = currentToken;
- tokenNumber++;
-
- }
+ temp = req.getParameter("newKeyInfo"); // #xx#xx
+ String newKeyInfoMap = "tks." + keySet + ".mk_mappings." + temp;
+ String newMappingValue = CMS.getConfigStore().getString(newKeyInfoMap, null);
+ if (newMappingValue != null) {
+ StringTokenizer st = new StringTokenizer(newMappingValue, ":");
+ int tokenNumber = 0;
+ while (st.hasMoreTokens()) {
+ String currentToken = st.nextToken();
+ if (tokenNumber == 0)
+ mNewSelectedToken = currentToken;
+ else if (tokenNumber == 1)
+ mNewKeyNickName = currentToken;
+ tokenNumber++;
+
+ }
}
- }
+ }
- SessionKey.SetDefaultPrefix(masterKeyPrefix);
+ SessionKey.SetDefaultPrefix(masterKeyPrefix);
} catch (Exception e) {
e.printStackTrace();
@@ -247,9 +228,8 @@ public class TokenServlet extends CMSServlet {
}
private void processComputeSessionKey(HttpServletRequest req,
- HttpServletResponse resp) throws EBaseException
- {
- byte[] card_challenge ,host_challenge,keyInfo, xCUID, CUID, session_key;
+ HttpServletResponse resp) throws EBaseException {
+ byte[] card_challenge, host_challenge, keyInfo, xCUID, CUID, session_key;
byte[] card_crypto, host_cryptogram, input_card_crypto;
byte[] xcard_challenge, xhost_challenge;
byte[] enc_session_key, xkeyInfo;
@@ -257,18 +237,18 @@ public class TokenServlet extends CMSServlet {
String errorMsg = "";
String badParams = "";
String transportKeyName = "";
-
- String rCUID = req.getParameter("CUID");
+
+ String rCUID = req.getParameter("CUID");
String keySet = req.getParameter("keySet");
if (keySet == null || keySet.equals("")) {
- keySet = "defKeySet";
+ keySet = "defKeySet";
}
CMS.debug("keySet selected: " + keySet);
boolean serversideKeygen = false;
byte[] drm_trans_wrapped_desKey = null;
- PK11SymKey desKey = null;
- // PK11SymKey kek_session_key;
+ PK11SymKey desKey = null;
+ // PK11SymKey kek_session_key;
PK11SymKey kek_key;
IConfigStore sconfig = CMS.getConfigStore();
@@ -278,14 +258,14 @@ public class TokenServlet extends CMSServlet {
card_crypto = null;
host_cryptogram = null;
enc_session_key = null;
- // kek_session_key = null;
+ // kek_session_key = null;
SessionContext sContext = SessionContext.getContext();
- String agentId="";
+ String agentId = "";
if (sContext != null) {
agentId =
- (String) sContext.get(SessionContext.USER_ID);
+ (String) sContext.get(SessionContext.USER_ID);
}
auditMessage = CMS.getLogMessage(
@@ -297,19 +277,19 @@ public class TokenServlet extends CMSServlet {
audit(auditMessage);
String kek_wrapped_desKeyString = null;
- String keycheck_s = null;
+ String keycheck_s = null;
CMS.debug("processComputeSessionKey:");
String useSoftToken_s = CMS.getConfigStore().getString("tks.useSoftToken", "true");
- if (!useSoftToken_s.equalsIgnoreCase("true"))
- useSoftToken_s = "false";
+ if (!useSoftToken_s.equalsIgnoreCase("true"))
+ useSoftToken_s = "false";
- String rServersideKeygen = (String) req.getParameter("serversideKeygen");
+ String rServersideKeygen = (String) req.getParameter("serversideKeygen");
if (rServersideKeygen.equals("true")) {
- CMS.debug("TokenServlet: serversideKeygen requested");
- serversideKeygen = true;
+ CMS.debug("TokenServlet: serversideKeygen requested");
+ serversideKeygen = true;
} else {
- CMS.debug("TokenServlet: serversideKeygen not requested");
+ CMS.debug("TokenServlet: serversideKeygen not requested");
}
try {
@@ -318,13 +298,12 @@ public class TokenServlet extends CMSServlet {
}
try {
- transportKeyName = sconfig.getString("tks.tksSharedSymKeyName",TRANSPORT_KEY_NAME);
+ transportKeyName = sconfig.getString("tks.tksSharedSymKeyName", TRANSPORT_KEY_NAME);
} catch (EBaseException e) {
}
CMS.debug("TokenServlet: ComputeSessionKey(): tksSharedSymKeyName: " + transportKeyName);
-
String rcard_challenge = req.getParameter("card_challenge");
String rhost_challenge = req.getParameter("host_challenge");
String rKeyInfo = req.getParameter("KeyInfo");
@@ -353,7 +332,6 @@ public class TokenServlet extends CMSServlet {
missingParam = true;
}
-
String selectedToken = null;
String keyNickName = null;
boolean sameCardCrypto = true;
@@ -362,48 +340,48 @@ public class TokenServlet extends CMSServlet {
xCUID = com.netscape.cmsutil.util.Utils.SpecialDecode(rCUID);
if (xCUID == null || xCUID.length != 10) {
- badParams += " CUID length,";
- CMS.debug("TokenServlet: Invalid CUID length");
- missingParam = true;
+ badParams += " CUID length,";
+ CMS.debug("TokenServlet: Invalid CUID length");
+ missingParam = true;
}
xkeyInfo = com.netscape.cmsutil.util.Utils.SpecialDecode(rKeyInfo);
if (xkeyInfo == null || xkeyInfo.length != 2) {
- badParams += " KeyInfo length,";
- CMS.debug("TokenServlet: Invalid key info length.");
- missingParam = true;
+ badParams += " KeyInfo length,";
+ CMS.debug("TokenServlet: Invalid key info length.");
+ missingParam = true;
}
- xcard_challenge =
- com.netscape.cmsutil.util.Utils.SpecialDecode(rcard_challenge);
+ xcard_challenge =
+ com.netscape.cmsutil.util.Utils.SpecialDecode(rcard_challenge);
if (xcard_challenge == null || xcard_challenge.length != 8) {
- badParams += " card_challenge length,";
- CMS.debug("TokenServlet: Invalid card challenge length.");
- missingParam = true;
+ badParams += " card_challenge length,";
+ CMS.debug("TokenServlet: Invalid card challenge length.");
+ missingParam = true;
}
-
+
xhost_challenge = com.netscape.cmsutil.util.Utils.SpecialDecode(rhost_challenge);
if (xhost_challenge == null || xhost_challenge.length != 8) {
- badParams += " host_challenge length,";
- CMS.debug("TokenServlet: Invalid host challenge length");
- missingParam = true;
+ badParams += " host_challenge length,";
+ CMS.debug("TokenServlet: Invalid host challenge length");
+ missingParam = true;
}
-
+
}
CUID = null;
if (!missingParam) {
- card_challenge =
- com.netscape.cmsutil.util.Utils.SpecialDecode(rcard_challenge);
-
+ card_challenge =
+ com.netscape.cmsutil.util.Utils.SpecialDecode(rcard_challenge);
+
host_challenge = com.netscape.cmsutil.util.Utils.SpecialDecode(rhost_challenge);
keyInfo = com.netscape.cmsutil.util.Utils.SpecialDecode(rKeyInfo);
- CUID =com.netscape.cmsutil.util.Utils.SpecialDecode(rCUID);
+ CUID = com.netscape.cmsutil.util.Utils.SpecialDecode(rCUID);
- String keyInfoMap = "tks." + keySet + ".mk_mappings." + rKeyInfo; //#xx#xx
+ String keyInfoMap = "tks." + keySet + ".mk_mappings." + rKeyInfo; // #xx#xx
String mappingValue = CMS.getConfigStore().getString(keyInfoMap, null);
if (mappingValue == null) {
- selectedToken =
- CMS.getConfigStore().getString("tks.defaultSlot", "internal");
+ selectedToken =
+ CMS.getConfigStore().getString("tks.defaultSlot", "internal");
keyNickName = rKeyInfo;
} else {
StringTokenizer st = new StringTokenizer(mappingValue, ":");
@@ -419,133 +397,130 @@ public class TokenServlet extends CMSServlet {
byte macKeyArray[] = com.netscape.cmsutil.util.Utils.SpecialDecode(sconfig.getString("tks." + keySet + ".mac_key"));
CMS.debug("TokenServlet about to try ComputeSessionKey selectedToken=" + selectedToken + " keyNickName=" + keyNickName);
- session_key = SessionKey.ComputeSessionKey(
- selectedToken,keyNickName,card_challenge,
- host_challenge,keyInfo,CUID, macKeyArray, useSoftToken_s, keySet, transportKeyName );
+ session_key = SessionKey.ComputeSessionKey(
+ selectedToken, keyNickName, card_challenge,
+ host_challenge, keyInfo, CUID, macKeyArray, useSoftToken_s, keySet, transportKeyName);
- if(session_key == null)
- {
+ if (session_key == null) {
CMS.debug("TokenServlet:Tried ComputeSessionKey, got NULL ");
- throw new Exception("Can't compute session key!");
+ throw new Exception("Can't compute session key!");
- }
+ }
byte encKeyArray[] = com.netscape.cmsutil.util.Utils.SpecialDecode(sconfig.getString("tks." + keySet + ".auth_key"));
enc_session_key = SessionKey.ComputeEncSessionKey(
- selectedToken,keyNickName,card_challenge,
- host_challenge,keyInfo,CUID, encKeyArray, useSoftToken_s, keySet);
+ selectedToken, keyNickName, card_challenge,
+ host_challenge, keyInfo, CUID, encKeyArray, useSoftToken_s, keySet);
- if(enc_session_key == null)
- {
+ if (enc_session_key == null) {
CMS.debug("TokenServlet:Tried ComputeEncSessionKey, got NULL ");
- throw new Exception("Can't compute enc session key!");
-
+ throw new Exception("Can't compute enc session key!");
+
}
if (serversideKeygen == true) {
/**
- * 0. generate des key
- * 1. encrypt des key with kek key
- * 2. encrypt des key with DRM transport key
- * These two wrapped items are to be sent back to
- * TPS. 2nd item is to DRM
+ * 0. generate des key 1. encrypt des key with kek key
+ * 2. encrypt des key with DRM transport key These two
+ * wrapped items are to be sent back to TPS. 2nd item is
+ * to DRM
**/
CMS.debug("TokenServlet: calling ComputeKekKey");
- byte kekKeyArray[] = com.netscape.cmsutil.util.Utils.SpecialDecode(sconfig.getString("tks." + keySet + ".kek_key"));
-
+ byte kekKeyArray[] = com.netscape.cmsutil.util.Utils.SpecialDecode(sconfig.getString("tks." + keySet + ".kek_key"));
kek_key = SessionKey.ComputeKekKey(
- selectedToken,keyNickName,card_challenge,
- host_challenge,keyInfo,CUID, kekKeyArray, useSoftToken_s,keySet);
-
+ selectedToken, keyNickName, card_challenge,
+ host_challenge, keyInfo, CUID, kekKeyArray, useSoftToken_s, keySet);
CMS.debug("TokenServlet: called ComputeKekKey");
- if(kek_key == null)
- {
+ if (kek_key == null) {
CMS.debug("TokenServlet:Tried ComputeKekKey, got NULL ");
- throw new Exception("Can't compute kek key!");
-
+ throw new Exception("Can't compute kek key!");
+
}
// now use kek key to wrap kek session key..
- CMS.debug("computeSessionKey:kek key len ="+
- kek_key.getLength());
-
- // (1) generate DES key
- /* applet does not support DES3
- org.mozilla.jss.crypto.KeyGenerator kg =
- internalToken.getKeyGenerator(KeyGenAlgorithm.DES3);
- desKey = kg.generate();*/
-
- /*
- * XXX GenerateSymkey firt generates a 16 byte DES2 key.
- * It then pads it into a 24 byte key with last
- * 8 bytes copied from the 1st 8 bytes. Effectively
- * making it a 24 byte DES2 key. We need this for
- * wrapping private keys on DRM.
- */
- /*generate it on whichever token the master key is at*/
- if (useSoftToken_s.equals("true")) {
- CMS.debug("TokenServlet: key encryption key generated on internal");
-//cfu audit here? sym key gen
- desKey = SessionKey.GenerateSymkey("internal");
-//cfu audit here? sym key gen done
+ CMS.debug("computeSessionKey:kek key len =" +
+ kek_key.getLength());
+
+ // (1) generate DES key
+ /*
+ * applet does not support DES3
+ * org.mozilla.jss.crypto.KeyGenerator kg =
+ * internalToken.getKeyGenerator(KeyGenAlgorithm.DES3);
+ * desKey = kg.generate();
+ */
+
+ /*
+ * XXX GenerateSymkey firt generates a 16 byte DES2 key.
+ * It then pads it into a 24 byte key with last 8 bytes
+ * copied from the 1st 8 bytes. Effectively making it a
+ * 24 byte DES2 key. We need this for wrapping private
+ * keys on DRM.
+ */
+ /* generate it on whichever token the master key is at */
+ if (useSoftToken_s.equals("true")) {
+ CMS.debug("TokenServlet: key encryption key generated on internal");
+ // cfu audit here? sym key gen
+ desKey = SessionKey.GenerateSymkey("internal");
+ // cfu audit here? sym key gen done
} else {
- CMS.debug("TokenServlet: key encryption key generated on " + selectedToken);
- desKey = SessionKey.GenerateSymkey(selectedToken);
+ CMS.debug("TokenServlet: key encryption key generated on " + selectedToken);
+ desKey = SessionKey.GenerateSymkey(selectedToken);
+ }
+ if (desKey != null)
+ CMS.debug("TokenServlet: key encryption key generated for " + rCUID);
+ else {
+ CMS.debug("TokenServlet: key encryption key generation failed for " + rCUID);
+ throw new Exception("can't generate key encryption key");
}
- if (desKey != null)
- CMS.debug("TokenServlet: key encryption key generated for "+rCUID);
- else {
- CMS.debug("TokenServlet: key encryption key generation failed for "+rCUID);
- throw new Exception ("can't generate key encryption key");
- }
-
- /*
- * XXX ECBencrypt actually takes the 24 byte DES2 key
- * and discard the last 8 bytes before it encrypts.
- * This is done so that the applet can digest it
- */
- byte[] encDesKey =
- SessionKey.ECBencrypt( kek_key,
- desKey);
- /*
- CMS.debug("computeSessionKey:encrypted desKey size = "+encDesKey.length);
- CMS.debug(encDesKey);
- */
+
+ /*
+ * XXX ECBencrypt actually takes the 24 byte DES2 key
+ * and discard the last 8 bytes before it encrypts. This
+ * is done so that the applet can digest it
+ */
+ byte[] encDesKey =
+ SessionKey.ECBencrypt(kek_key,
+ desKey);
+ /*
+ * CMS.debug("computeSessionKey:encrypted desKey size = "
+ * +encDesKey.length); CMS.debug(encDesKey);
+ */
kek_wrapped_desKeyString =
- com.netscape.cmsutil.util.Utils.SpecialEncode(encDesKey);
-
- // get keycheck
- byte[] keycheck =
- SessionKey.ComputeKeyCheck(desKey);
- /*
- CMS.debug("computeSessionKey:keycheck size = "+keycheck.length);
- CMS.debug(keycheck);
- */
- keycheck_s =
- com.netscape.cmsutil.util.Utils.SpecialEncode(keycheck);
-
- //XXX use DRM transport cert to wrap desKey
- String drmTransNickname = CMS.getConfigStore().getString("tks.drm_transport_cert_nickname", "");
-
- if ((drmTransNickname == null) || (drmTransNickname == "")) {
- CMS.debug("TokenServlet:did not find DRM transport certificate nickname");
- throw new Exception("can't find DRM transport certificate nickname");
- } else {
- CMS.debug("TokenServlet:drmtransport_cert_nickname="+drmTransNickname);
- }
+ com.netscape.cmsutil.util.Utils.SpecialEncode(encDesKey);
+
+ // get keycheck
+ byte[] keycheck =
+ SessionKey.ComputeKeyCheck(desKey);
+ /*
+ * CMS.debug("computeSessionKey:keycheck size = "+keycheck
+ * .length); CMS.debug(keycheck);
+ */
+ keycheck_s =
+ com.netscape.cmsutil.util.Utils.SpecialEncode(keycheck);
+
+ // XXX use DRM transport cert to wrap desKey
+ String drmTransNickname = CMS.getConfigStore().getString("tks.drm_transport_cert_nickname", "");
+
+ if ((drmTransNickname == null) || (drmTransNickname == "")) {
+ CMS.debug("TokenServlet:did not find DRM transport certificate nickname");
+ throw new Exception("can't find DRM transport certificate nickname");
+ } else {
+ CMS.debug("TokenServlet:drmtransport_cert_nickname=" + drmTransNickname);
+ }
X509Certificate drmTransCert = null;
drmTransCert = CryptoManager.getInstance().findCertByNickname(drmTransNickname);
// wrap kek session key with DRM transport public key
- CryptoToken token = null;
- if (useSoftToken_s.equals("true")) {
- //token = CryptoManager.getInstance().getTokenByName(selectedToken);
- token = CryptoManager.getInstance().getInternalCryptoToken();
+ CryptoToken token = null;
+ if (useSoftToken_s.equals("true")) {
+ // token =
+ // CryptoManager.getInstance().getTokenByName(selectedToken);
+ token = CryptoManager.getInstance().getInternalCryptoToken();
} else {
token = CryptoManager.getInstance().getTokenByName(selectedToken);
}
@@ -553,7 +528,7 @@ public class TokenServlet extends CMSServlet {
String pubKeyAlgo = pubKey.getAlgorithm();
CMS.debug("Transport Cert Key Algorithm: " + pubKeyAlgo);
KeyWrapper keyWrapper = null;
- //For wrapping symmetric keys don't need IV, use ECB
+ // For wrapping symmetric keys don't need IV, use ECB
if (pubKeyAlgo.equals("EC")) {
keyWrapper = token.getKeyWrapper(KeyWrapAlgorithm.AES_ECB);
keyWrapper.initWrap(pubKey, null);
@@ -561,31 +536,29 @@ public class TokenServlet extends CMSServlet {
keyWrapper = token.getKeyWrapper(KeyWrapAlgorithm.RSA);
keyWrapper.initWrap(pubKey, null);
}
- CMS.debug("desKey token " + desKey.getOwningToken().getName() + " token: " + token.getName() );
+ CMS.debug("desKey token " + desKey.getOwningToken().getName() + " token: " + token.getName());
drm_trans_wrapped_desKey = keyWrapper.wrap(desKey);
- CMS.debug("computeSessionKey:desKey wrapped with drm transportation key.");
+ CMS.debug("computeSessionKey:desKey wrapped with drm transportation key.");
} // if (serversideKeygen == true)
byte authKeyArray[] = com.netscape.cmsutil.util.Utils.SpecialDecode(sconfig.getString("tks." + keySet + ".auth_key"));
host_cryptogram = SessionKey.ComputeCryptogram(
- selectedToken,keyNickName,card_challenge,
- host_challenge,keyInfo,CUID,0, authKeyArray, useSoftToken_s, keySet);
+ selectedToken, keyNickName, card_challenge,
+ host_challenge, keyInfo, CUID, 0, authKeyArray, useSoftToken_s, keySet);
- if(host_cryptogram == null)
- {
+ if (host_cryptogram == null) {
CMS.debug("TokenServlet:Tried ComputeCryptogram, got NULL ");
- throw new Exception("Can't compute host cryptogram!");
+ throw new Exception("Can't compute host cryptogram!");
}
card_crypto = SessionKey.ComputeCryptogram(
- selectedToken,keyNickName,card_challenge,
- host_challenge,keyInfo,CUID,1, authKeyArray, useSoftToken_s, keySet);
+ selectedToken, keyNickName, card_challenge,
+ host_challenge, keyInfo, CUID, 1, authKeyArray, useSoftToken_s, keySet);
- if(card_crypto == null)
- {
+ if (card_crypto == null) {
CMS.debug("TokenServlet:Tried ComputeCryptogram, got NULL ");
- throw new Exception("Can't compute card cryptogram!");
+ throw new Exception("Can't compute card cryptogram!");
}
@@ -595,9 +568,9 @@ public class TokenServlet extends CMSServlet {
throw new Exception("Missing card cryptogram");
}
input_card_crypto =
- com.netscape.cmsutil.util.Utils.SpecialDecode(rcard_cryptogram);
+ com.netscape.cmsutil.util.Utils.SpecialDecode(rcard_cryptogram);
if (card_crypto.length == input_card_crypto.length) {
- for (int i=0; i<card_crypto.length; i++) {
+ for (int i = 0; i < card_crypto.length; i++) {
if (card_crypto[i] != input_card_crypto[i]) {
sameCardCrypto = false;
break;
@@ -611,15 +584,15 @@ public class TokenServlet extends CMSServlet {
CMS.getLogger().log(ILogger.EV_AUDIT,
ILogger.S_TKS,
- ILogger.LL_INFO,"processComputeSessionKey for CUID=" +
- trim(pp.toHexString(CUID)));
- } catch (Exception e) {
+ ILogger.LL_INFO, "processComputeSessionKey for CUID=" +
+ trim(pp.toHexString(CUID)));
+ } catch (Exception e) {
CMS.debug(e);
CMS.debug("TokenServlet Computing Session Key: " + e.toString());
if (isCryptoValidate)
sameCardCrypto = false;
}
- }
+ }
} // ! missingParam
String value = "";
@@ -632,34 +605,32 @@ public class TokenServlet extends CMSServlet {
String cryptogram = "";
String status = "0";
if (session_key != null && session_key.length > 0) {
- outputString =
- com.netscape.cmsutil.util.Utils.SpecialEncode(session_key);
- } else {
-
+ outputString =
+ com.netscape.cmsutil.util.Utils.SpecialEncode(session_key);
+ } else {
+
status = "1";
}
if (enc_session_key != null && enc_session_key.length > 0) {
- encSessionKeyString =
- com.netscape.cmsutil.util.Utils.SpecialEncode(enc_session_key);
- } else {
+ encSessionKeyString =
+ com.netscape.cmsutil.util.Utils.SpecialEncode(enc_session_key);
+ } else {
status = "1";
}
-
if (serversideKeygen == true) {
- if ( drm_trans_wrapped_desKey != null && drm_trans_wrapped_desKey.length > 0)
- drm_trans_wrapped_desKeyString =
- com.netscape.cmsutil.util.Utils.SpecialEncode(drm_trans_wrapped_desKey);
- else {
- status = "1";
+ if (drm_trans_wrapped_desKey != null && drm_trans_wrapped_desKey.length > 0)
+ drm_trans_wrapped_desKeyString =
+ com.netscape.cmsutil.util.Utils.SpecialEncode(drm_trans_wrapped_desKey);
+ else {
+ status = "1";
}
- }
+ }
-
if (host_cryptogram != null && host_cryptogram.length > 0) {
- cryptogram =
- com.netscape.cmsutil.util.Utils.SpecialEncode(host_cryptogram);
+ cryptogram =
+ com.netscape.cmsutil.util.Utils.SpecialEncode(host_cryptogram);
} else {
status = "2";
}
@@ -675,32 +646,30 @@ public class TokenServlet extends CMSServlet {
if (missingParam) {
status = "3";
}
-
- if (!status.equals("0")) {
-
-
- if(status.equals("1")) {
- errorMsg = "Problem generating session key info.";
- }
-
- if(status.equals("2")) {
- errorMsg = "Problem creating host_cryptogram.";
- }
-
- if(status.equals("4")) {
- errorMsg = "Problem obtaining token information.";
- }
-
- if(status.equals("3")) {
- if(badParams.endsWith(",")) {
- badParams = badParams.substring(0,badParams.length() -1);
- }
- errorMsg = "Missing input parameters :" + badParams;
- }
-
- value = "status="+status;
- }
- else {
+
+ if (!status.equals("0")) {
+
+ if (status.equals("1")) {
+ errorMsg = "Problem generating session key info.";
+ }
+
+ if (status.equals("2")) {
+ errorMsg = "Problem creating host_cryptogram.";
+ }
+
+ if (status.equals("4")) {
+ errorMsg = "Problem obtaining token information.";
+ }
+
+ if (status.equals("3")) {
+ if (badParams.endsWith(",")) {
+ badParams = badParams.substring(0, badParams.length() - 1);
+ }
+ errorMsg = "Missing input parameters :" + badParams;
+ }
+
+ value = "status=" + status;
+ } else {
if (serversideKeygen == true) {
StringBuffer sb = new StringBuffer();
sb.append("status=0&");
@@ -709,10 +678,10 @@ public class TokenServlet extends CMSServlet {
sb.append("&hostCryptogram=");
sb.append(cryptogram);
sb.append("&encSessionKey=");
- sb.append(encSessionKeyString);
+ sb.append(encSessionKeyString);
sb.append("&kek_wrapped_desKey=");
sb.append(kek_wrapped_desKeyString);
- sb.append("&keycheck=");
+ sb.append("&keycheck=");
sb.append(keycheck_s);
sb.append("&drm_trans_wrapped_desKey=");
sb.append(drm_trans_wrapped_desKeyString);
@@ -722,19 +691,19 @@ public class TokenServlet extends CMSServlet {
sb.append("status=0&");
sb.append("sessionKey=");
sb.append(outputString);
- sb.append("&hostCryptogram=");
- sb.append(cryptogram);
+ sb.append("&hostCryptogram=");
+ sb.append(cryptogram);
sb.append("&encSessionKey=");
sb.append(encSessionKeyString);
value = sb.toString();
}
}
- CMS.debug("TokenServlet:outputString.encode " +value);
+ CMS.debug("TokenServlet:outputString.encode " + value);
- try{
+ try {
resp.setContentLength(value.length());
- CMS.debug("TokenServlet:outputString.length " +value.length());
+ CMS.debug("TokenServlet:outputString.length " + value.length());
OutputStream ooss = resp.getOutputStream();
ooss.write(value.getBytes());
ooss.flush();
@@ -742,65 +711,65 @@ public class TokenServlet extends CMSServlet {
} catch (IOException e) {
CMS.debug("TokenServlet: " + e.toString());
}
-
- if(status.equals("0")) {
- auditMessage = CMS.getLogMessage(
+ if (status.equals("0")) {
+
+ auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_COMPUTE_SESSION_KEY_REQUEST_PROCESSED_SUCCESS,
rCUID,
ILogger.SUCCESS,
status,
agentId,
- isCryptoValidate? "true":"false",
- serversideKeygen? "true":"false",
+ isCryptoValidate ? "true" : "false",
+ serversideKeygen ? "true" : "false",
selectedToken,
keyNickName);
} else {
- auditMessage = CMS.getLogMessage(
+ auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_COMPUTE_SESSION_KEY_REQUEST_PROCESSED_FAILURE,
rCUID,
ILogger.FAILURE,
status,
agentId,
- isCryptoValidate? "true":"false",
- serversideKeygen? "true":"false",
+ isCryptoValidate ? "true" : "false",
+ serversideKeygen ? "true" : "false",
selectedToken,
keyNickName,
errorMsg);
- }
-
+ }
+
audit(auditMessage);
}
private void processDiversifyKey(HttpServletRequest req,
- HttpServletResponse resp) throws EBaseException {
- byte[] KeySetData,KeysValues,CUID,xCUID;
- byte[] xkeyInfo,xnewkeyInfo;
+ HttpServletResponse resp) throws EBaseException {
+ byte[] KeySetData, KeysValues, CUID, xCUID;
+ byte[] xkeyInfo, xnewkeyInfo;
boolean missingParam = false;
String errorMsg = "";
String badParams = "";
IConfigStore sconfig = CMS.getConfigStore();
- String rnewKeyInfo = req.getParameter("newKeyInfo");
+ String rnewKeyInfo = req.getParameter("newKeyInfo");
String newMasterKeyName = req.getParameter("newKeyInfo");
String oldMasterKeyName = req.getParameter("KeyInfo");
- String rCUID =req.getParameter("CUID");
- String auditMessage="";
+ String rCUID = req.getParameter("CUID");
+ String auditMessage = "";
String keySet = req.getParameter("keySet");
if (keySet == null || keySet.equals("")) {
- keySet = "defKeySet";
+ keySet = "defKeySet";
}
CMS.debug("keySet selected: " + keySet);
SessionContext sContext = SessionContext.getContext();
- String agentId="";
+ String agentId = "";
if (sContext != null) {
agentId =
- (String) sContext.get(SessionContext.USER_ID);
+ (String) sContext.get(SessionContext.USER_ID);
}
auditMessage = CMS.getLogMessage(
@@ -813,7 +782,6 @@ public class TokenServlet extends CMSServlet {
audit(auditMessage);
-
if ((rCUID == null) || (rCUID.equals(""))) {
badParams += " CUID,";
CMS.debug("TokenServlet: processDiversifyKey(): missing request parameter: CUID");
@@ -824,130 +792,130 @@ public class TokenServlet extends CMSServlet {
CMS.debug("TokenServlet: processDiversifyKey(): missing request parameter: newKeyInfo");
missingParam = true;
}
- if ((oldMasterKeyName == null) || (oldMasterKeyName.equals(""))){
+ if ((oldMasterKeyName == null) || (oldMasterKeyName.equals(""))) {
badParams += " KeyInfo,";
CMS.debug("TokenServlet: processDiversifyKey(): missing request parameter: KeyInfo");
missingParam = true;
}
if (!missingParam) {
- xkeyInfo = com.netscape.cmsutil.util.Utils.SpecialDecode(oldMasterKeyName);
- if (xkeyInfo == null || xkeyInfo.length != 2) {
- badParams += " KeyInfo length,";
- CMS.debug("TokenServlet: Invalid key info length");
- missingParam = true;
- }
- xnewkeyInfo = com.netscape.cmsutil.util.Utils.SpecialDecode(newMasterKeyName);
- if (xnewkeyInfo == null || xnewkeyInfo.length != 2) {
- badParams += " NewKeyInfo length,";
- CMS.debug("TokenServlet: Invalid new key info length");
- missingParam = true;
- }
- }
+ xkeyInfo = com.netscape.cmsutil.util.Utils.SpecialDecode(oldMasterKeyName);
+ if (xkeyInfo == null || xkeyInfo.length != 2) {
+ badParams += " KeyInfo length,";
+ CMS.debug("TokenServlet: Invalid key info length");
+ missingParam = true;
+ }
+ xnewkeyInfo = com.netscape.cmsutil.util.Utils.SpecialDecode(newMasterKeyName);
+ if (xnewkeyInfo == null || xnewkeyInfo.length != 2) {
+ badParams += " NewKeyInfo length,";
+ CMS.debug("TokenServlet: Invalid new key info length");
+ missingParam = true;
+ }
+ }
String useSoftToken_s = CMS.getConfigStore().getString("tks.useSoftToken", "true");
- if (!useSoftToken_s.equalsIgnoreCase("true"))
- useSoftToken_s = "false";
+ if (!useSoftToken_s.equalsIgnoreCase("true"))
+ useSoftToken_s = "false";
KeySetData = null;
String outputString = null;
if (!missingParam) {
- xCUID = com.netscape.cmsutil.util.Utils.SpecialDecode(rCUID);
- if (xCUID == null || xCUID.length != 10) {
- badParams += " CUID length,";
- CMS.debug("TokenServlet: Invalid CUID length");
- missingParam = true;
- }
- }
+ xCUID = com.netscape.cmsutil.util.Utils.SpecialDecode(rCUID);
+ if (xCUID == null || xCUID.length != 10) {
+ badParams += " CUID length,";
+ CMS.debug("TokenServlet: Invalid CUID length");
+ missingParam = true;
+ }
+ }
if (!missingParam) {
- CUID = com.netscape.cmsutil.util.Utils.SpecialDecode(rCUID);
-
- if (mKeyNickName!=null)
- oldMasterKeyName = mKeyNickName;
- if (mNewKeyNickName!=null)
- newMasterKeyName = mNewKeyNickName;
-
- String oldKeyInfoMap = "tks." + keySet + ".mk_mappings." + req.getParameter("KeyInfo"); //#xx#xx
- String oldMappingValue = CMS.getConfigStore().getString(oldKeyInfoMap, null);
- String oldSelectedToken = null;
- String oldKeyNickName = null;
- if (oldMappingValue == null) {
- oldSelectedToken = CMS.getConfigStore().getString("tks.defaultSlot", "internal");
- oldKeyNickName = req.getParameter("KeyInfo");
- } else {
- StringTokenizer st = new StringTokenizer(oldMappingValue, ":");
- oldSelectedToken = st.nextToken();
- oldKeyNickName = st.nextToken();
- }
-
- String newKeyInfoMap = "tks.mk_mappings." + rnewKeyInfo; //#xx#xx
- String newMappingValue = CMS.getConfigStore().getString(newKeyInfoMap, null);
- String newSelectedToken = null;
- String newKeyNickName = null;
- if (newMappingValue == null) {
- newSelectedToken = CMS.getConfigStore().getString("tks.defaultSlot", "internal");
- newKeyNickName = rnewKeyInfo;
- } else {
- StringTokenizer st = new StringTokenizer(newMappingValue, ":");
- newSelectedToken = st.nextToken();
- newKeyNickName = st.nextToken();
- }
-
- CMS.debug("process DiversifyKey for oldSelectedToke="+
- oldSelectedToken + " newSelectedToken=" + newSelectedToken +
- " oldKeyNickName=" + oldKeyNickName + " newKeyNickName=" +
- newKeyNickName);
-
- byte kekKeyArray[] = com.netscape.cmsutil.util.Utils.SpecialDecode(sconfig.getString("tks." + keySet + ".kek_key"));
- KeySetData = SessionKey.DiversifyKey(oldSelectedToken,
+ CUID = com.netscape.cmsutil.util.Utils.SpecialDecode(rCUID);
+
+ if (mKeyNickName != null)
+ oldMasterKeyName = mKeyNickName;
+ if (mNewKeyNickName != null)
+ newMasterKeyName = mNewKeyNickName;
+
+ String oldKeyInfoMap = "tks." + keySet + ".mk_mappings." + req.getParameter("KeyInfo"); // #xx#xx
+ String oldMappingValue = CMS.getConfigStore().getString(oldKeyInfoMap, null);
+ String oldSelectedToken = null;
+ String oldKeyNickName = null;
+ if (oldMappingValue == null) {
+ oldSelectedToken = CMS.getConfigStore().getString("tks.defaultSlot", "internal");
+ oldKeyNickName = req.getParameter("KeyInfo");
+ } else {
+ StringTokenizer st = new StringTokenizer(oldMappingValue, ":");
+ oldSelectedToken = st.nextToken();
+ oldKeyNickName = st.nextToken();
+ }
+
+ String newKeyInfoMap = "tks.mk_mappings." + rnewKeyInfo; // #xx#xx
+ String newMappingValue = CMS.getConfigStore().getString(newKeyInfoMap, null);
+ String newSelectedToken = null;
+ String newKeyNickName = null;
+ if (newMappingValue == null) {
+ newSelectedToken = CMS.getConfigStore().getString("tks.defaultSlot", "internal");
+ newKeyNickName = rnewKeyInfo;
+ } else {
+ StringTokenizer st = new StringTokenizer(newMappingValue, ":");
+ newSelectedToken = st.nextToken();
+ newKeyNickName = st.nextToken();
+ }
+
+ CMS.debug("process DiversifyKey for oldSelectedToke=" +
+ oldSelectedToken + " newSelectedToken=" + newSelectedToken +
+ " oldKeyNickName=" + oldKeyNickName + " newKeyNickName=" +
+ newKeyNickName);
+
+ byte kekKeyArray[] = com.netscape.cmsutil.util.Utils.SpecialDecode(sconfig.getString("tks." + keySet + ".kek_key"));
+ KeySetData = SessionKey.DiversifyKey(oldSelectedToken,
newSelectedToken, oldKeyNickName,
- newKeyNickName,rnewKeyInfo,CUID, kekKeyArray, useSoftToken_s, keySet);
-
- if (KeySetData == null || KeySetData.length<=1) {
- CMS.getLogger().log(ILogger.EV_AUDIT,
- ILogger.S_TKS,
- ILogger.LL_INFO,"process DiversifyKey: Missing MasterKey in Slot");
- }
-
- CMS.getLogger().log(ILogger.EV_AUDIT,
- ILogger.S_TKS,
- ILogger.LL_INFO,"process DiversifyKey for CUID ="+ trim(pp.toHexString(CUID))
- + ";from oldMasterKeyName="+oldSelectedToken + ":" + oldKeyNickName
- +";to newMasterKeyName="+newSelectedToken + ":" + newKeyNickName);
-
- resp.setContentType("text/html");
-
- if (KeySetData != null) {
- outputString = new String(KeySetData);
- }
+ newKeyNickName, rnewKeyInfo, CUID, kekKeyArray, useSoftToken_s, keySet);
+
+ if (KeySetData == null || KeySetData.length <= 1) {
+ CMS.getLogger().log(ILogger.EV_AUDIT,
+ ILogger.S_TKS,
+ ILogger.LL_INFO, "process DiversifyKey: Missing MasterKey in Slot");
+ }
+
+ CMS.getLogger().log(ILogger.EV_AUDIT,
+ ILogger.S_TKS,
+ ILogger.LL_INFO, "process DiversifyKey for CUID =" + trim(pp.toHexString(CUID))
+ + ";from oldMasterKeyName=" + oldSelectedToken + ":" + oldKeyNickName
+ + ";to newMasterKeyName=" + newSelectedToken + ":" + newKeyNickName);
+
+ resp.setContentType("text/html");
+
+ if (KeySetData != null) {
+ outputString = new String(KeySetData);
+ }
} // ! missingParam
- //CMS.debug("TokenServlet:processDiversifyKey " +outputString);
- //String value="keySetData=%00" if the KeySetData=byte[0]=0;
+ // CMS.debug("TokenServlet:processDiversifyKey " +outputString);
+ // String value="keySetData=%00" if the KeySetData=byte[0]=0;
String value = "";
String status = "0";
if (KeySetData != null && KeySetData.length > 1) {
- value = "status=0&"+"keySetData=" +
+ value = "status=0&" + "keySetData=" +
com.netscape.cmsutil.util.Utils.SpecialEncode(KeySetData);
- CMS.debug("TokenServlet:process DiversifyKey.encode " +value);
+ CMS.debug("TokenServlet:process DiversifyKey.encode " + value);
} else if (missingParam) {
status = "3";
- if(badParams.endsWith(",")) {
- badParams = badParams.substring(0,badParams.length() -1);
+ if (badParams.endsWith(",")) {
+ badParams = badParams.substring(0, badParams.length() - 1);
}
errorMsg = "Missing input parameters: " + badParams;
value = "status=" + status;
- } else {
+ } else {
errorMsg = "Problem diversifying key data.";
status = "1";
value = "status=" + status;
}
resp.setContentLength(value.length());
- CMS.debug("TokenServlet:outputString.length " +value.length());
+ CMS.debug("TokenServlet:outputString.length " + value.length());
- try{
+ try {
OutputStream ooss = resp.getOutputStream();
ooss.write(value.getBytes());
ooss.flush();
@@ -956,9 +924,9 @@ public class TokenServlet extends CMSServlet {
CMS.debug("TokenServlet:process DiversifyKey: " + e.toString());
}
- if(status.equals("0")) {
+ if (status.equals("0")) {
- auditMessage = CMS.getLogMessage(
+ auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_DIVERSIFY_KEY_REQUEST_PROCESSED_SUCCESS,
rCUID,
ILogger.SUCCESS,
@@ -969,7 +937,7 @@ public class TokenServlet extends CMSServlet {
} else {
- auditMessage = CMS.getLogMessage(
+ auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_DIVERSIFY_KEY_REQUEST_PROCESSED_FAILURE,
rCUID,
ILogger.FAILURE,
@@ -978,13 +946,13 @@ public class TokenServlet extends CMSServlet {
oldMasterKeyName,
newMasterKeyName,
errorMsg);
- }
+ }
- audit(auditMessage);
+ audit(auditMessage);
}
private void processEncryptData(HttpServletRequest req,
- HttpServletResponse resp) throws EBaseException {
+ HttpServletResponse resp) throws EBaseException {
byte[] keyInfo, CUID, xCUID, encryptedData, xkeyInfo;
boolean missingParam = false;
byte[] data = null;
@@ -1004,10 +972,10 @@ public class TokenServlet extends CMSServlet {
SessionContext sContext = SessionContext.getContext();
- String agentId="";
+ String agentId = "";
if (sContext != null) {
agentId =
- (String) sContext.get(SessionContext.USER_ID);
+ (String) sContext.get(SessionContext.USER_ID);
}
CMS.debug("keySet selected: " + keySet);
@@ -1032,20 +1000,20 @@ public class TokenServlet extends CMSServlet {
if (isRandom) {
if ((rdata == null) || (rdata.equals(""))) {
- CMS.debug("TokenServlet: processEncryptData(): no data in request. Generating random number as data");
+ CMS.debug("TokenServlet: processEncryptData(): no data in request. Generating random number as data");
} else {
- CMS.debug("TokenServlet: processEncryptData(): contain data in request, however, random generation on TKS is required. Generating...");
+ CMS.debug("TokenServlet: processEncryptData(): contain data in request, however, random generation on TKS is required. Generating...");
}
try {
- SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
- data = new byte[16];
- random.nextBytes(data);
+ SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
+ data = new byte[16];
+ random.nextBytes(data);
} catch (Exception e) {
- CMS.debug("TokenServlet: processEncryptData():"+ e.toString());
- badParams += " Random Number,";
- missingParam = true;
+ CMS.debug("TokenServlet: processEncryptData():" + e.toString());
+ badParams += " Random Number,";
+ missingParam = true;
}
- } else if ((!isRandom) && (((rdata == null) || (rdata.equals(""))))){
+ } else if ((!isRandom) && (((rdata == null) || (rdata.equals(""))))) {
CMS.debug("TokenServlet: processEncryptData(): missing request parameter: data.");
badParams += " data,";
missingParam = true;
@@ -1056,75 +1024,74 @@ public class TokenServlet extends CMSServlet {
CMS.debug("TokenServlet: processEncryptData(): missing request parameter: CUID");
missingParam = true;
}
-
+
if ((rKeyInfo == null) || (rKeyInfo.equals(""))) {
badParams += " KeyInfo,";
CMS.debug("TokenServlet: processEncryptData(): missing request parameter: key info");
missingParam = true;
}
-
if (!missingParam) {
- xCUID = com.netscape.cmsutil.util.Utils.SpecialDecode(rCUID);
- if (xCUID == null || xCUID.length != 10) {
- badParams += " CUID length,";
- CMS.debug("TokenServlet: Invalid CUID length");
- missingParam = true;
- }
- xkeyInfo = com.netscape.cmsutil.util.Utils.SpecialDecode(rKeyInfo);
- if (xkeyInfo == null || xkeyInfo.length != 2) {
- badParams += " KeyInfo length,";
- CMS.debug("TokenServlet: Invalid key info length");
- missingParam = true;
- }
+ xCUID = com.netscape.cmsutil.util.Utils.SpecialDecode(rCUID);
+ if (xCUID == null || xCUID.length != 10) {
+ badParams += " CUID length,";
+ CMS.debug("TokenServlet: Invalid CUID length");
+ missingParam = true;
+ }
+ xkeyInfo = com.netscape.cmsutil.util.Utils.SpecialDecode(rKeyInfo);
+ if (xkeyInfo == null || xkeyInfo.length != 2) {
+ badParams += " KeyInfo length,";
+ CMS.debug("TokenServlet: Invalid key info length");
+ missingParam = true;
+ }
}
- String useSoftToken_s = CMS.getConfigStore().getString("tks.useSoftToken","true");
- if (!useSoftToken_s.equalsIgnoreCase("true"))
- useSoftToken_s = "false";
+ String useSoftToken_s = CMS.getConfigStore().getString("tks.useSoftToken", "true");
+ if (!useSoftToken_s.equalsIgnoreCase("true"))
+ useSoftToken_s = "false";
String selectedToken = null;
String keyNickName = null;
if (!missingParam) {
- if (!isRandom)
- data = com.netscape.cmsutil.util.Utils.SpecialDecode(rdata);
- keyInfo = com.netscape.cmsutil.util.Utils.SpecialDecode(rKeyInfo);
- CUID = com.netscape.cmsutil.util.Utils.SpecialDecode(rCUID);
-
- String keyInfoMap = "tks." + keySet + ".mk_mappings." + rKeyInfo;
- String mappingValue = CMS.getConfigStore().getString(keyInfoMap, null);
- if (mappingValue == null) {
- selectedToken = CMS.getConfigStore().getString("tks.defaultSlot", "internal");
- keyNickName = rKeyInfo;
- } else {
- StringTokenizer st = new StringTokenizer(mappingValue, ":");
- selectedToken = st.nextToken();
- keyNickName = st.nextToken();
- }
-
- byte kekKeyArray[] = com.netscape.cmsutil.util.Utils.SpecialDecode(sconfig.getString("tks." + keySet + ".kek_key"));
- encryptedData = SessionKey.EncryptData(
- selectedToken,keyNickName,data,keyInfo,CUID, kekKeyArray, useSoftToken_s, keySet);
-
- CMS.getLogger().log(ILogger.EV_AUDIT,
+ if (!isRandom)
+ data = com.netscape.cmsutil.util.Utils.SpecialDecode(rdata);
+ keyInfo = com.netscape.cmsutil.util.Utils.SpecialDecode(rKeyInfo);
+ CUID = com.netscape.cmsutil.util.Utils.SpecialDecode(rCUID);
+
+ String keyInfoMap = "tks." + keySet + ".mk_mappings." + rKeyInfo;
+ String mappingValue = CMS.getConfigStore().getString(keyInfoMap, null);
+ if (mappingValue == null) {
+ selectedToken = CMS.getConfigStore().getString("tks.defaultSlot", "internal");
+ keyNickName = rKeyInfo;
+ } else {
+ StringTokenizer st = new StringTokenizer(mappingValue, ":");
+ selectedToken = st.nextToken();
+ keyNickName = st.nextToken();
+ }
+
+ byte kekKeyArray[] = com.netscape.cmsutil.util.Utils.SpecialDecode(sconfig.getString("tks." + keySet + ".kek_key"));
+ encryptedData = SessionKey.EncryptData(
+ selectedToken, keyNickName, data, keyInfo, CUID, kekKeyArray, useSoftToken_s, keySet);
+
+ CMS.getLogger().log(ILogger.EV_AUDIT,
ILogger.S_TKS,
- ILogger.LL_INFO,"process EncryptData for CUID ="+ trim(pp.toHexString(CUID)));
+ ILogger.LL_INFO, "process EncryptData for CUID =" + trim(pp.toHexString(CUID)));
} // !missingParam
resp.setContentType("text/html");
-
+
String value = "";
- String status = "0";
- if (encryptedData != null && encryptedData.length > 0) {
- String outputString = new String(encryptedData);
+ String status = "0";
+ if (encryptedData != null && encryptedData.length > 0) {
+ String outputString = new String(encryptedData);
// sending both the pre-encrypted and encrypted data back
- value = "status=0&"+"data="+
- com.netscape.cmsutil.util.Utils.SpecialEncode(data)+
- "&encryptedData=" +
+ value = "status=0&" + "data=" +
+ com.netscape.cmsutil.util.Utils.SpecialEncode(data) +
+ "&encryptedData=" +
com.netscape.cmsutil.util.Utils.SpecialEncode(encryptedData);
} else if (missingParam) {
- if(badParams.endsWith(",")) {
- badParams = badParams.substring(0,badParams.length() -1);
+ if (badParams.endsWith(",")) {
+ badParams = badParams.substring(0, badParams.length() - 1);
}
errorMsg = "Missing input parameters: " + badParams;
status = "3";
@@ -1135,12 +1102,12 @@ public class TokenServlet extends CMSServlet {
value = "status=" + status;
}
- CMS.debug("TokenServlet:process EncryptData.encode " +value);
+ CMS.debug("TokenServlet:process EncryptData.encode " + value);
try {
resp.setContentLength(value.length());
- CMS.debug("TokenServlet:outputString.lenght " +value.length());
-
+ CMS.debug("TokenServlet:outputString.lenght " + value.length());
+
OutputStream ooss = resp.getOutputStream();
ooss.write(value.getBytes());
ooss.flush();
@@ -1149,9 +1116,9 @@ public class TokenServlet extends CMSServlet {
CMS.debug("TokenServlet: " + e.toString());
}
- if(status.equals("0")) {
+ if (status.equals("0")) {
- auditMessage = CMS.getLogMessage(
+ auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_ENCRYPT_DATA_REQUEST_PROCESSED_SUCCESS,
rCUID,
ILogger.SUCCESS,
@@ -1163,7 +1130,7 @@ public class TokenServlet extends CMSServlet {
} else {
- auditMessage = CMS.getLogMessage(
+ auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_ENCRYPT_DATA_REQUEST_PROCESSED_FAILURE,
rCUID,
ILogger.FAILURE,
@@ -1173,30 +1140,24 @@ public class TokenServlet extends CMSServlet {
selectedToken,
keyNickName,
errorMsg);
- }
+ }
- audit(auditMessage);
+ audit(auditMessage);
}
- /*
- * For EncryptData:
- * data=value1
- * CUID=value2 // missing from RA
- * versionID=value3 // missing from RA
- *
- * For ComputeSession:
- * card_challenge=value1
- * host_challenge=value2
-
- * For DiversifyKey:
- * new_master_key_index
- * master_key_index
+ /*
+ * For EncryptData: data=value1 CUID=value2 // missing from RA
+ * versionID=value3 // missing from RA
+ *
+ * For ComputeSession: card_challenge=value1 host_challenge=value2
+ *
+ * For DiversifyKey: new_master_key_index master_key_index
*/
private void processComputeRandomData(HttpServletRequest req,
- HttpServletResponse resp) throws EBaseException {
-
- byte[] randomData = null;
+ HttpServletResponse resp) throws EBaseException {
+
+ byte[] randomData = null;
String status = "0";
String errorMsg = "";
String badParams = "";
@@ -1207,26 +1168,23 @@ public class TokenServlet extends CMSServlet {
SessionContext sContext = SessionContext.getContext();
- String agentId="";
+ String agentId = "";
if (sContext != null) {
agentId =
- (String) sContext.get(SessionContext.USER_ID);
+ (String) sContext.get(SessionContext.USER_ID);
}
String sDataSize = req.getParameter("dataNumBytes");
- if(sDataSize == null || sDataSize.equals("")) {
+ if (sDataSize == null || sDataSize.equals("")) {
CMS.debug("TokenServlet::processComputeRandomData missing param dataNumBytes");
badParams += " Random Data size, ";
missingParam = true;
status = "1";
} else {
- try
- {
- dataSize = Integer.parseInt(sDataSize.trim());
- }
- catch (NumberFormatException nfe)
- {
+ try {
+ dataSize = Integer.parseInt(sDataSize.trim());
+ } catch (NumberFormatException nfe) {
CMS.debug("TokenServlet::processComputeRandomData invalid data size input!");
badParams += " Random Data size, ";
missingParam = true;
@@ -1244,33 +1202,33 @@ public class TokenServlet extends CMSServlet {
audit(auditMessage);
- if(!missingParam) {
+ if (!missingParam) {
try {
- SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
- randomData = new byte[dataSize];
- random.nextBytes(randomData);
- } catch (Exception e) {
- CMS.debug("TokenServlet::processComputeRandomData:"+ e.toString());
- errorMsg = "Can't generate random data!";
- status = "2";
+ SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
+ randomData = new byte[dataSize];
+ random.nextBytes(randomData);
+ } catch (Exception e) {
+ CMS.debug("TokenServlet::processComputeRandomData:" + e.toString());
+ errorMsg = "Can't generate random data!";
+ status = "2";
}
}
String randomDataOut = "";
- if(status.equals("0")) {
+ if (status.equals("0")) {
if (randomData != null && randomData.length == dataSize) {
randomDataOut =
- com.netscape.cmsutil.util.Utils.SpecialEncode(randomData);
+ com.netscape.cmsutil.util.Utils.SpecialEncode(randomData);
} else {
status = "2";
errorMsg = "Can't convert random data!";
}
}
- if(status.equals("1") && missingParam) {
+ if (status.equals("1") && missingParam) {
- if(badParams.endsWith(",")) {
- badParams = badParams.substring(0,badParams.length() -1);
+ if (badParams.endsWith(",")) {
+ badParams = badParams.substring(0, badParams.length() - 1);
}
errorMsg = "Missing input parameters :" + badParams;
}
@@ -1278,15 +1236,15 @@ public class TokenServlet extends CMSServlet {
resp.setContentType("text/html");
String value = "";
- value = "status="+status;
- if(status.equals("0")) {
- value = value + "&DATA="+randomDataOut;
+ value = "status=" + status;
+ if (status.equals("0")) {
+ value = value + "&DATA=" + randomDataOut;
}
-
+
try {
resp.setContentLength(value.length());
- CMS.debug("TokenServler::processComputeRandomData :outputString.length " +value.length());
-
+ CMS.debug("TokenServler::processComputeRandomData :outputString.length " + value.length());
+
OutputStream ooss = resp.getOutputStream();
ooss.write(value.getBytes());
ooss.flush();
@@ -1295,22 +1253,22 @@ public class TokenServlet extends CMSServlet {
CMS.debug("TokenServlet::processComputeRandomData " + e.toString());
}
- if(status.equals("0")) {
+ if (status.equals("0")) {
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_COMPUTE_RANDOM_DATA_REQUEST_PROCESSED_SUCCESS,
ILogger.SUCCESS,
status,
agentId);
- } else {
- auditMessage = CMS.getLogMessage(
+ } else {
+ auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_COMPUTE_RANDOM_DATA_REQUEST_PROCESSED_FAILURE,
ILogger.FAILURE,
status,
agentId,
errorMsg);
- }
+ }
- audit(auditMessage);
+ audit(auditMessage);
}
public void process(CMSRequest cmsReq) throws EBaseException {
@@ -1328,7 +1286,7 @@ public class TokenServlet extends CMSServlet {
if (authzToken == null) {
- try{
+ try {
resp.setContentType("text/html");
String value = "unauthorized=";
CMS.debug("TokenServlet: Unauthorized");
@@ -1338,37 +1296,36 @@ public class TokenServlet extends CMSServlet {
ooss.write(value.getBytes());
ooss.flush();
mRenderResult = false;
- }catch (Exception e) {
+ } catch (Exception e) {
CMS.debug("TokenServlet: " + e.toString());
}
- // cmsReq.setStatus(CMSRequest.UNAUTHORIZED);
+ // cmsReq.setStatus(CMSRequest.UNAUTHORIZED);
return;
}
String temp = req.getParameter("card_challenge");
mSelectedToken = CMS.getConfigStore().getString("tks.defaultSlot");
setDefaultSlotAndKeyName(req);
- if(temp!=null)
- {
- processComputeSessionKey(req,resp);
- }else if(req.getParameter("data")!=null){
- processEncryptData(req,resp);
- }else if(req.getParameter("newKeyInfo")!=null){
- processDiversifyKey(req,resp);
- }else if(req.getParameter("dataNumBytes") !=null){
- processComputeRandomData(req,resp);
+ if (temp != null) {
+ processComputeSessionKey(req, resp);
+ } else if (req.getParameter("data") != null) {
+ processEncryptData(req, resp);
+ } else if (req.getParameter("newKeyInfo") != null) {
+ processDiversifyKey(req, resp);
+ } else if (req.getParameter("dataNumBytes") != null) {
+ processComputeRandomData(req, resp);
}
}
/**
* Serves HTTP admin request.
- *
+ *
* @param req HTTP request
* @param resp HTTP response
*/
public void service(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
+ throws ServletException, IOException {
String scope = req.getParameter(Constants.OP_SCOPE);
String op = req.getParameter(Constants.OP_TYPE);
diff --git a/pki/base/common/src/com/netscape/cms/servlet/wizard/IWizardPanel.java b/pki/base/common/src/com/netscape/cms/servlet/wizard/IWizardPanel.java
index 9d67065d..d9d3ddec 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/wizard/IWizardPanel.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/wizard/IWizardPanel.java
@@ -33,10 +33,10 @@ public interface IWizardPanel {
/**
* Initializes this panel.
*/
- public void init(ServletConfig config, int panelno)
+ public void init(ServletConfig config, int panelno)
throws ServletException;
- public void init(WizardServlet servlet, ServletConfig config,
+ public void init(WizardServlet servlet, ServletConfig config,
int panelno, String id) throws ServletException;
public String getName();
@@ -44,7 +44,9 @@ public interface IWizardPanel {
public int getPanelNo();
public void setId(String id);
+
public String getId();
+
public PropertySet getUsage();
/**
@@ -84,20 +86,22 @@ public interface IWizardPanel {
*/
public void display(HttpServletRequest request,
HttpServletResponse response,
- Context context );
+ Context context);
+
/**
* Checks if the given parameters are valid.
*/
public void validate(HttpServletRequest request,
HttpServletResponse response,
- Context context ) throws IOException;
+ Context context) throws IOException;
/**
* Commit parameter changes
*/
public void update(HttpServletRequest request,
HttpServletResponse response,
- Context context ) throws IOException;
+ Context context) throws IOException;
+
/**
* If validiate() returns false, this method will be called.
*/
diff --git a/pki/base/common/src/com/netscape/cms/servlet/wizard/WizardServlet.java b/pki/base/common/src/com/netscape/cms/servlet/wizard/WizardServlet.java
index 691d3e98..5c14fcf0 100644
--- a/pki/base/common/src/com/netscape/cms/servlet/wizard/WizardServlet.java
+++ b/pki/base/common/src/com/netscape/cms/servlet/wizard/WizardServlet.java
@@ -37,13 +37,10 @@ import com.netscape.cms.servlet.csadmin.Cert;
import com.netscape.cmsutil.crypto.Module;
/**
- * wizard?p=[panel number]&op=usage <= usage in xml
- * wizard?p=[panel number]&op=display
- * wizard?p=[panel number]&op=next&...[additional parameters]...
- * wizard?p=[panel number]&op=apply
- * wizard?p=[panel number]&op=back
- * wizard?op=menu
- * return menu options
+ * wizard?p=[panel number]&op=usage <= usage in xml wizard?p=[panel
+ * number]&op=display wizard?p=[panel number]&op=next&...[additional
+ * parameters]... wizard?p=[panel number]&op=apply wizard?p=[panel
+ * number]&op=back wizard?op=menu return menu options
*/
public class WizardServlet extends VelocityServlet {
@@ -54,8 +51,7 @@ public class WizardServlet extends VelocityServlet {
private String name = null;
private Vector mPanels = new Vector();
- public void init(ServletConfig config) throws ServletException
- {
+ public void init(ServletConfig config) throws ServletException {
super.init(config);
/* load sequence map */
@@ -64,33 +60,32 @@ public class WizardServlet extends VelocityServlet {
StringTokenizer st = new StringTokenizer(panels, ",");
int pno = 0;
while (st.hasMoreTokens()) {
- String p = st.nextToken();
- StringTokenizer st1 = new StringTokenizer(p, "=");
- String id = st1.nextToken();
- String pvalue = st1.nextToken();
- try {
- IWizardPanel panel = (IWizardPanel)Class.forName(pvalue).newInstance();
- panel.init(this, config, pno, id);
- CMS.debug("WizardServlet: panel name=" + panel.getName());
- mPanels.addElement(panel);
- } catch (Exception e) {
- CMS.debug("WizardServlet: " + e.toString());
- }
- pno++;
+ String p = st.nextToken();
+ StringTokenizer st1 = new StringTokenizer(p, "=");
+ String id = st1.nextToken();
+ String pvalue = st1.nextToken();
+ try {
+ IWizardPanel panel = (IWizardPanel) Class.forName(pvalue).newInstance();
+ panel.init(this, config, pno, id);
+ CMS.debug("WizardServlet: panel name=" + panel.getName());
+ mPanels.addElement(panel);
+ } catch (Exception e) {
+ CMS.debug("WizardServlet: " + e.toString());
+ }
+ pno++;
}
CMS.debug("WizardServlet: done");
-
+
}
public void exposePanels(HttpServletRequest request,
HttpServletResponse response,
- Context context )
- {
+ Context context) {
Enumeration e = mPanels.elements();
Vector panels = new Vector();
while (e.hasMoreElements()) {
- IWizardPanel p = (IWizardPanel)e.nextElement();
- panels.addElement(p);
+ IWizardPanel p = (IWizardPanel) e.nextElement();
+ panels.addElement(p);
}
context.put("panels", panels);
}
@@ -98,84 +93,80 @@ public class WizardServlet extends VelocityServlet {
/**
* Cleans up panels from a particular panel.
*/
- public void cleanUpFromPanel(int pno) throws IOException
- {
- /* panel number starts from zero */
- int s = mPanels.size();
- for (int i = pno; i < s; i++) {
- IWizardPanel panel = (IWizardPanel)mPanels.elementAt(i);
- panel.cleanUp();
- }
+ public void cleanUpFromPanel(int pno) throws IOException {
+ /* panel number starts from zero */
+ int s = mPanels.size();
+ for (int i = pno; i < s; i++) {
+ IWizardPanel panel = (IWizardPanel) mPanels.elementAt(i);
+ panel.cleanUp();
+ }
}
- public IWizardPanel getPanelByNo(int p)
- {
- IWizardPanel panel = (IWizardPanel)mPanels.elementAt(p);
+ public IWizardPanel getPanelByNo(int p) {
+ IWizardPanel panel = (IWizardPanel) mPanels.elementAt(p);
if (panel.shouldSkip()) {
- panel = getPanelByNo(p+1);
+ panel = getPanelByNo(p + 1);
}
return panel;
}
public Template displayPanel(HttpServletRequest request,
HttpServletResponse response,
- Context context )
- {
+ Context context) {
CMS.debug("WizardServlet: in display");
int p = getPanelNo(request);
if (p == 0) {
- CMS.debug("WizardServlet: firstpanel");
- context.put("firstpanel", Boolean.TRUE);
+ CMS.debug("WizardServlet: firstpanel");
+ context.put("firstpanel", Boolean.TRUE);
}
if (p == (mPanels.size() - 1)) {
- CMS.debug("WizardServlet: lastpanel");
- context.put("lastpanel", Boolean.TRUE);
+ CMS.debug("WizardServlet: lastpanel");
+ context.put("lastpanel", Boolean.TRUE);
}
IWizardPanel panel = getPanelByNo(p);
CMS.debug("WizardServlet: panel=" + panel);
if (panel.showApplyButton() == true)
- context.put("showApplyButton", Boolean.TRUE);
+ context.put("showApplyButton", Boolean.TRUE);
else
- context.put("showApplyButton", Boolean.FALSE);
+ context.put("showApplyButton", Boolean.FALSE);
panel.display(request, response, context);
context.put("p", Integer.toString(panel.getPanelNo()));
try {
return Velocity.getTemplate("admin/console/config/wizard.vm");
- } catch (Exception e) {
+ } catch (Exception e) {
}
return null;
}
- public String xml_value_flatten(Object v)
- {
+ public String xml_value_flatten(Object v) {
String ret = "";
if (v instanceof String) {
ret += v;
} else if (v instanceof Integer) {
- ret += ((Integer)v).toString();
+ ret += ((Integer) v).toString();
} else if (v instanceof Vector) {
ret += "<Vector>";
- Vector v1 = (Vector)v;
+ Vector v1 = (Vector) v;
Enumeration e = v1.elements();
StringBuffer sb = new StringBuffer();
while (e.hasMoreElements()) {
- sb.append(xml_value_flatten(e.nextElement()));
+ sb.append(xml_value_flatten(e.nextElement()));
}
ret += sb.toString();
ret += "</Vector>";
} else if (v instanceof Module) { // for hardware token
- Module m = (Module)v;
+ Module m = (Module) v;
ret += "<Module>";
ret += "<CommonName>" + m.getCommonName() + "</CommonName>";
ret += "<UserFriendlyName>" + m.getUserFriendlyName() + "</UserFriendlyName>";
ret += "<ImagePath>" + m.getImagePath() + "</ImagePath>";
ret += "</Module>";
} else if (v instanceof Cert) {
- Cert m = (Cert)v;
+ Cert m = (Cert) v;
ret += "<CertReqPair>";
ret += "<Nickname>" + m.getNickname() + "</Nickname>";
ret += "<Tokenname>" + m.getTokenname() + "</Tokenname>";
@@ -187,7 +178,7 @@ public class WizardServlet extends VelocityServlet {
ret += "<KeyOption>" + m.getKeyOption() + "</KeyOption>";
ret += "</CertReqPair>";
} else if (v instanceof IWizardPanel) {
- IWizardPanel m = (IWizardPanel)v;
+ IWizardPanel m = (IWizardPanel) v;
ret += "<Panel>";
ret += "<Id>" + m.getId() + "</Id>";
ret += "<Name>" + m.getName() + "</Name>";
@@ -198,89 +189,84 @@ public class WizardServlet extends VelocityServlet {
return ret;
}
- public String xml_flatten(Context context)
- {
+ public String xml_flatten(Context context) {
StringBuffer ret = new StringBuffer();
- Object o[] = context.getKeys();
- for (int i = 0; i < o.length; i ++) {
- if (o[i] instanceof String) {
- String key = (String)o[i];
- if (key.startsWith("__")) {
- continue;
- }
- ret.append("<");
- ret.append(key);
- ret.append(">");
- if (key.equals("bindpwd")) {
- ret.append("(sensitive)");
- } else {
- Object v = context.get(key);
- ret.append(xml_value_flatten(v));
+ Object o[] = context.getKeys();
+ for (int i = 0; i < o.length; i++) {
+ if (o[i] instanceof String) {
+ String key = (String) o[i];
+ if (key.startsWith("__")) {
+ continue;
+ }
+ ret.append("<");
+ ret.append(key);
+ ret.append(">");
+ if (key.equals("bindpwd")) {
+ ret.append("(sensitive)");
+ } else {
+ Object v = context.get(key);
+ ret.append(xml_value_flatten(v));
+ }
+ ret.append("</");
+ ret.append(key);
+ ret.append(">");
}
- ret.append("</");
- ret.append(key);
- ret.append(">");
- }
}
return ret.toString();
}
- public int getPanelNo(HttpServletRequest request)
- {
+ public int getPanelNo(HttpServletRequest request) {
int p = 0;
-
- // panel number can be identified by either
- // panel no (p parameter) directly, or
- // panel name (panelname parameter).
+
+ // panel number can be identified by either
+ // panel no (p parameter) directly, or
+ // panel name (panelname parameter).
if (request.getParameter("panelname") != null) {
- String name = request.getParameter("panelname");
- for (int i = 0; i < mPanels.size(); i++) {
- IWizardPanel panel = (IWizardPanel)mPanels.elementAt(i);
- if (panel.getId().equals(name)) {
- return i;
+ String name = request.getParameter("panelname");
+ for (int i = 0; i < mPanels.size(); i++) {
+ IWizardPanel panel = (IWizardPanel) mPanels.elementAt(i);
+ if (panel.getId().equals(name)) {
+ return i;
+ }
}
- }
} else if (request.getParameter("p") != null) {
- p = Integer.parseInt(request.getParameter("p"));
+ p = Integer.parseInt(request.getParameter("p"));
}
return p;
}
- public String getNameFromPanelNo(int p)
- {
- IWizardPanel wp = (IWizardPanel)mPanels.elementAt(p);
- return wp.getId();
+ public String getNameFromPanelNo(int p) {
+ IWizardPanel wp = (IWizardPanel) mPanels.elementAt(p);
+ return wp.getId();
}
- public IWizardPanel getPreviousPanel(int p)
- {
+ public IWizardPanel getPreviousPanel(int p) {
CMS.debug("getPreviousPanel input p=" + p);
- IWizardPanel backpanel = (IWizardPanel)mPanels.elementAt(p-1);
+ IWizardPanel backpanel = (IWizardPanel) mPanels.elementAt(p - 1);
if (backpanel.isSubPanel()) {
- backpanel = (IWizardPanel)mPanels.elementAt(p-1-1);
+ backpanel = (IWizardPanel) mPanels.elementAt(p - 1 - 1);
}
while (backpanel.shouldSkip()) {
- backpanel = (IWizardPanel)
+ backpanel = (IWizardPanel)
mPanels.elementAt(backpanel.getPanelNo() - 1);
}
CMS.debug("getPreviousPanel output p=" + backpanel.getPanelNo());
return backpanel;
}
- public IWizardPanel getNextPanel(int p)
- {
+ public IWizardPanel getNextPanel(int p) {
CMS.debug("getNextPanel input p=" + p);
- IWizardPanel panel = (IWizardPanel)mPanels.elementAt(p);
+ IWizardPanel panel = (IWizardPanel) mPanels.elementAt(p);
if (p == (mPanels.size() - 1)) {
p = p;
- } else if(panel.isSubPanel()) {
- if (panel.isLoopbackPanel()) {
- p = p-1; // Login Panel is a loop back panel
- } else {
- p = p+1;
- }
- } else if (panel.hasSubPanel()) {
- p = p + 2;
+ } else if (panel.isSubPanel()) {
+ if (panel.isLoopbackPanel()) {
+ p = p - 1; // Login Panel is a loop back panel
+ } else {
+ p = p + 1;
+ }
+ } else if (panel.hasSubPanel()) {
+ p = p + 2;
} else {
p = p + 1;
}
@@ -291,190 +277,183 @@ public class WizardServlet extends VelocityServlet {
public Template goApply(HttpServletRequest request,
HttpServletResponse response,
- Context context)
- {
+ Context context) {
return goNextApply(request, response, context, true);
}
public Template goNext(HttpServletRequest request,
HttpServletResponse response,
- Context context )
- {
+ Context context) {
return goNextApply(request, response, context, false);
}
/*
- * The parameter "stay" is used to indicate "apply" without
- * moving to the next panel
+ * The parameter "stay" is used to indicate "apply" without moving to the
+ * next panel
*/
public Template goNextApply(HttpServletRequest request,
HttpServletResponse response,
- Context context, boolean stay )
- {
+ Context context, boolean stay) {
int p = getPanelNo(request);
if (stay == true)
CMS.debug("WizardServlet: in reply " + p);
else
CMS.debug("WizardServlet: in next " + p);
- IWizardPanel panel = (IWizardPanel)mPanels.elementAt(p);
+ IWizardPanel panel = (IWizardPanel) mPanels.elementAt(p);
try {
- panel.validate(request, response, context);
- try {
- panel.update(request, response, context);
- if (stay == true) { // "apply"
-
- if (panel.showApplyButton() == true)
- context.put("showApplyButton", Boolean.TRUE);
- else
- context.put("showApplyButton", Boolean.FALSE);
- panel.display(request, response, context);
- } else { // "next"
- IWizardPanel nextpanel = getNextPanel(p);
-
- if (nextpanel.showApplyButton() == true)
- context.put("showApplyButton", Boolean.TRUE);
- else
- context.put("showApplyButton", Boolean.FALSE);
- nextpanel.display(request, response, context);
- panel = nextpanel;
+ panel.validate(request, response, context);
+ try {
+ panel.update(request, response, context);
+ if (stay == true) { // "apply"
+
+ if (panel.showApplyButton() == true)
+ context.put("showApplyButton", Boolean.TRUE);
+ else
+ context.put("showApplyButton", Boolean.FALSE);
+ panel.display(request, response, context);
+ } else { // "next"
+ IWizardPanel nextpanel = getNextPanel(p);
+
+ if (nextpanel.showApplyButton() == true)
+ context.put("showApplyButton", Boolean.TRUE);
+ else
+ context.put("showApplyButton", Boolean.FALSE);
+ nextpanel.display(request, response, context);
+ panel = nextpanel;
+ }
+ context.put("errorString", "");
+ } catch (Exception e) {
+ context.put("errorString", e.getMessage());
+ panel.displayError(request, response, context);
}
- context.put("errorString", "");
- } catch (Exception e) {
- context.put("errorString", e.getMessage());
- panel.displayError(request, response, context);
- }
} catch (IOException eee) {
- context.put("errorString", eee.getMessage());
- panel.displayError(request, response, context);
+ context.put("errorString", eee.getMessage());
+ panel.displayError(request, response, context);
}
p = panel.getPanelNo();
CMS.debug("panel no=" + p);
CMS.debug("panel name=" + getNameFromPanelNo(p));
- CMS.debug("total number of panels="+mPanels.size());
+ CMS.debug("total number of panels=" + mPanels.size());
context.put("p", Integer.toString(p));
context.put("panelname", getNameFromPanelNo(p));
if (p == 0) {
- CMS.debug("WizardServlet: firstpanel");
- context.put("firstpanel", Boolean.TRUE);
+ CMS.debug("WizardServlet: firstpanel");
+ context.put("firstpanel", Boolean.TRUE);
}
if (p == (mPanels.size() - 1)) {
- CMS.debug("WizardServlet: lastpanel");
- context.put("lastpanel", Boolean.TRUE);
+ CMS.debug("WizardServlet: lastpanel");
+ context.put("lastpanel", Boolean.TRUE);
}
// this is where we handle the xml request
String xml = request.getParameter("xml");
if (xml != null && xml.equals("true")) {
- CMS.debug("WizardServlet: found xml");
-
- response.setContentType("application/xml");
- String xmlstr = xml_flatten(context);
- context.put("xml", xmlstr);
- try {
- return Velocity.getTemplate("admin/console/config/xml.vm");
- } catch (Exception e) {
- CMS.debug("Failing to get template" + e );
- }
+ CMS.debug("WizardServlet: found xml");
+
+ response.setContentType("application/xml");
+ String xmlstr = xml_flatten(context);
+ context.put("xml", xmlstr);
+ try {
+ return Velocity.getTemplate("admin/console/config/xml.vm");
+ } catch (Exception e) {
+ CMS.debug("Failing to get template" + e);
+ }
} else {
- try {
- return Velocity.getTemplate("admin/console/config/wizard.vm");
- } catch (Exception e) {
- CMS.debug("Failing to get template" + e );
- }
+ try {
+ return Velocity.getTemplate("admin/console/config/wizard.vm");
+ } catch (Exception e) {
+ CMS.debug("Failing to get template" + e);
+ }
}
return null;
}
public Template goBack(HttpServletRequest request,
HttpServletResponse response,
- Context context )
- {
+ Context context) {
int p = getPanelNo(request);
CMS.debug("WizardServlet: in back " + p);
IWizardPanel backpanel = getPreviousPanel(p);
if (backpanel.showApplyButton() == true)
- context.put("showApplyButton", Boolean.TRUE);
+ context.put("showApplyButton", Boolean.TRUE);
else
- context.put("showApplyButton", Boolean.FALSE);
+ context.put("showApplyButton", Boolean.FALSE);
backpanel.display(request, response, context);
- context.put("p", Integer.toString(backpanel.getPanelNo()));
+ context.put("p", Integer.toString(backpanel.getPanelNo()));
context.put("panelname", getNameFromPanelNo(backpanel.getPanelNo()));
p = backpanel.getPanelNo();
if (p == 0) {
- CMS.debug("WizardServlet: firstpanel");
- context.put("firstpanel", Boolean.TRUE);
+ CMS.debug("WizardServlet: firstpanel");
+ context.put("firstpanel", Boolean.TRUE);
}
if (p == (mPanels.size() - 1)) {
- CMS.debug("WizardServlet: lastpanel");
- context.put("lastpanel", Boolean.TRUE);
+ CMS.debug("WizardServlet: lastpanel");
+ context.put("lastpanel", Boolean.TRUE);
}
try {
return Velocity.getTemplate("admin/console/config/wizard.vm");
- } catch (Exception e) {
+ } catch (Exception e) {
}
return null;
}
public boolean authenticate(HttpServletRequest request,
HttpServletResponse response,
- Context context ) {
- String pin = (String)request.getSession().getAttribute("pin");
- if (pin == null) {
- try {
- response.sendRedirect("login");
- } catch (IOException e) {
+ Context context) {
+ String pin = (String) request.getSession().getAttribute("pin");
+ if (pin == null) {
+ try {
+ response.sendRedirect("login");
+ } catch (IOException e) {
+ }
+ return false;
}
- return false;
- }
- return true;
+ return true;
}
- public void outputHttpParameters(HttpServletRequest httpReq)
- {
+ public void outputHttpParameters(HttpServletRequest httpReq) {
CMS.debug("WizardServlet:service() uri = " + httpReq.getRequestURI());
Enumeration paramNames = httpReq.getParameterNames();
while (paramNames.hasMoreElements()) {
- String pn = (String)paramNames.nextElement();
+ String pn = (String) paramNames.nextElement();
// added this facility so that password can be hidden,
- // all sensitive parameters should be prefixed with
+ // all sensitive parameters should be prefixed with
// __ (double underscores); however, in the event that
// a security parameter slips through, we perform multiple
// additional checks to insure that it is NOT displayed
- if( pn.startsWith("__") ||
- pn.endsWith("password") ||
- pn.endsWith("passwd") ||
- pn.endsWith("pwd") ||
- pn.equalsIgnoreCase("admin_password_again") ||
- pn.equalsIgnoreCase("directoryManagerPwd") ||
- pn.equalsIgnoreCase("bindpassword") ||
- pn.equalsIgnoreCase("bindpwd") ||
- pn.equalsIgnoreCase("passwd") ||
- pn.equalsIgnoreCase("password") ||
- pn.equalsIgnoreCase("pin") ||
- pn.equalsIgnoreCase("pwd") ||
- pn.equalsIgnoreCase("pwdagain") ||
- pn.equalsIgnoreCase("uPasswd") ) {
- CMS.debug("WizardServlet::service() param name='" + pn +
- "' value='(sensitive)'" );
+ if (pn.startsWith("__") ||
+ pn.endsWith("password") ||
+ pn.endsWith("passwd") ||
+ pn.endsWith("pwd") ||
+ pn.equalsIgnoreCase("admin_password_again") ||
+ pn.equalsIgnoreCase("directoryManagerPwd") ||
+ pn.equalsIgnoreCase("bindpassword") ||
+ pn.equalsIgnoreCase("bindpwd") ||
+ pn.equalsIgnoreCase("passwd") ||
+ pn.equalsIgnoreCase("password") ||
+ pn.equalsIgnoreCase("pin") ||
+ pn.equalsIgnoreCase("pwd") ||
+ pn.equalsIgnoreCase("pwdagain") ||
+ pn.equalsIgnoreCase("uPasswd")) {
+ CMS.debug("WizardServlet::service() param name='" + pn +
+ "' value='(sensitive)'");
} else {
- CMS.debug("WizardServlet::service() param name='" + pn +
- "' value='" + httpReq.getParameter(pn) + "'" );
+ CMS.debug("WizardServlet::service() param name='" + pn +
+ "' value='" + httpReq.getParameter(pn) + "'");
}
}
}
-
public Template handleRequest(HttpServletRequest request,
HttpServletResponse response,
- Context context )
- {
+ Context context) {
CMS.debug("WizardServlet: process");
- if (CMS.debugOn()) {
- outputHttpParameters(request);
+ if (CMS.debugOn()) {
+ outputHttpParameters(request);
}
if (!authenticate(request, response, context)) {
@@ -484,7 +463,7 @@ public class WizardServlet extends VelocityServlet {
String op = request.getParameter("op"); /* operation */
if (op == null) {
- op = "display";
+ op = "display";
}
CMS.debug("WizardServlet: op=" + op);
CMS.debug("WizardServlet: size=" + mPanels.size());
diff --git a/pki/base/common/src/com/netscape/cms/shares/OldJoinShares.java b/pki/base/common/src/com/netscape/cms/shares/OldJoinShares.java
index 0c4dade8..0377c2b3 100644
--- a/pki/base/common/src/com/netscape/cms/shares/OldJoinShares.java
+++ b/pki/base/common/src/com/netscape/cms/shares/OldJoinShares.java
@@ -23,9 +23,9 @@ import java.lang.reflect.Method;
import com.netscape.certsrv.kra.IJoinShares;
/**
- * Use Java's reflection API to leverage CMS's
- * old Share and JoinShares implementations.
- *
+ * Use Java's reflection API to leverage CMS's old Share and JoinShares
+ * implementations.
+ *
* @deprecated
* @version $Revision$ $Date$
*/
@@ -33,59 +33,54 @@ public class OldJoinShares implements IJoinShares {
public Object mOldImpl = null;
- public OldJoinShares()
- {
+ public OldJoinShares() {
}
- public void initialize(int threshold) throws Exception
- {
- Class c = Class.forName("com.netscape.cmscore.shares.JoinShares");
- Class types[] = { int.class };
- Constructor con = c.getConstructor(types);
- Object params[] = {Integer.valueOf(threshold)};
- mOldImpl = con.newInstance(params);
+ public void initialize(int threshold) throws Exception {
+ Class c = Class.forName("com.netscape.cmscore.shares.JoinShares");
+ Class types[] = { int.class };
+ Constructor con = c.getConstructor(types);
+ Object params[] = { Integer.valueOf(threshold) };
+ mOldImpl = con.newInstance(params);
}
- public void addShare(int shareNum, byte[] share)
- {
- try {
- Class types[] = { int.class, share.getClass() };
- Class c = mOldImpl.getClass();
- Method method = c.getMethod("addShare", types);
- Object params[] = {Integer.valueOf(shareNum), share};
- method.invoke(mOldImpl, params);
- } catch (Exception e) {
- }
+ public void addShare(int shareNum, byte[] share) {
+ try {
+ Class types[] = { int.class, share.getClass() };
+ Class c = mOldImpl.getClass();
+ Method method = c.getMethod("addShare", types);
+ Object params[] = { Integer.valueOf(shareNum), share };
+ method.invoke(mOldImpl, params);
+ } catch (Exception e) {
+ }
}
- public int getShareCount()
- {
- if (mOldImpl == null)
- return -1;
- try {
- Class types[] = null;
- Class c = mOldImpl.getClass();
- Method method = c.getMethod("getShareCount", types);
- Object params[] = null;
- Integer result = (Integer)method.invoke(mOldImpl, params);
- return result.intValue();
- } catch (Exception e) {
- return -1;
- }
+ public int getShareCount() {
+ if (mOldImpl == null)
+ return -1;
+ try {
+ Class types[] = null;
+ Class c = mOldImpl.getClass();
+ Method method = c.getMethod("getShareCount", types);
+ Object params[] = null;
+ Integer result = (Integer) method.invoke(mOldImpl, params);
+ return result.intValue();
+ } catch (Exception e) {
+ return -1;
+ }
}
- public byte[] recoverSecret()
- {
- if (mOldImpl == null)
- return null;
- try {
- Class types[] = null;
- Class c = mOldImpl.getClass();
- Method method = c.getMethod("recoverSecret", types);
- Object params[] = null;
- return (byte[])method.invoke(mOldImpl, params);
- } catch (Exception e) {
- return null;
- }
+ public byte[] recoverSecret() {
+ if (mOldImpl == null)
+ return null;
+ try {
+ Class types[] = null;
+ Class c = mOldImpl.getClass();
+ Method method = c.getMethod("recoverSecret", types);
+ Object params[] = null;
+ return (byte[]) method.invoke(mOldImpl, params);
+ } catch (Exception e) {
+ return null;
+ }
}
}
diff --git a/pki/base/common/src/com/netscape/cms/shares/OldShare.java b/pki/base/common/src/com/netscape/cms/shares/OldShare.java
index 4e92f76a..cfd5c709 100644
--- a/pki/base/common/src/com/netscape/cms/shares/OldShare.java
+++ b/pki/base/common/src/com/netscape/cms/shares/OldShare.java
@@ -23,45 +23,41 @@ import java.lang.reflect.Method;
import com.netscape.certsrv.kra.IShare;
/**
- * Use Java's reflection API to leverage CMS's
- * old Share and JoinShares implementations.
- *
+ * Use Java's reflection API to leverage CMS's old Share and JoinShares
+ * implementations.
+ *
* @deprecated
* @version $Revision$ $Date$
*/
-public class OldShare implements IShare
-{
+public class OldShare implements IShare {
public Object mOldImpl = null;
- public OldShare()
- {
+ public OldShare() {
}
- public void initialize(byte[] secret, int threshold) throws Exception
- {
- try {
- Class c = Class.forName("com.netscape.cmscore.shares.Share");
- Class types[] = { secret.getClass(), int.class };
- Constructor cs[] = c.getConstructors();
- Constructor con = c.getConstructor(types);
- Object params[] = {secret, Integer.valueOf(threshold)};
- mOldImpl = con.newInstance(params);
- } catch (Exception e) {
- }
+ public void initialize(byte[] secret, int threshold) throws Exception {
+ try {
+ Class c = Class.forName("com.netscape.cmscore.shares.Share");
+ Class types[] = { secret.getClass(), int.class };
+ Constructor cs[] = c.getConstructors();
+ Constructor con = c.getConstructor(types);
+ Object params[] = { secret, Integer.valueOf(threshold) };
+ mOldImpl = con.newInstance(params);
+ } catch (Exception e) {
+ }
}
- public byte[] createShare(int sharenumber)
- {
- if (mOldImpl == null)
- return null;
- try {
- Class types[] = { int.class };
- Class c = mOldImpl.getClass();
- Method method = c.getMethod("createShare", types);
- Object params[] = {Integer.valueOf(sharenumber)};
- return (byte[])method.invoke(mOldImpl, params);
- } catch (Exception e) {
- return null;
- }
+ public byte[] createShare(int sharenumber) {
+ if (mOldImpl == null)
+ return null;
+ try {
+ Class types[] = { int.class };
+ Class c = mOldImpl.getClass();
+ Method method = c.getMethod("createShare", types);
+ Object params[] = { Integer.valueOf(sharenumber) };
+ return (byte[]) method.invoke(mOldImpl, params);
+ } catch (Exception e) {
+ return null;
+ }
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/apps/CMSEngine.java b/pki/base/common/src/com/netscape/cmscore/apps/CMSEngine.java
index db648125..94a8345c 100644
--- a/pki/base/common/src/com/netscape/cmscore/apps/CMSEngine.java
+++ b/pki/base/common/src/com/netscape/cmscore/apps/CMSEngine.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.apps;
-
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
@@ -184,10 +183,13 @@ public class CMSEngine implements ICMSEngine {
public static final SubsystemRegistry mSSReg = SubsystemRegistry.getInstance();
- public static String instanceDir; /* path to instance <server-root>/cert-<instance-name> */
-
- private IConfigStore mConfig = null;
- private ISubsystem mOwner = null;
+ public static String instanceDir; /*
+ * path to instance
+ * <server-root>/cert-<instance-name>
+ */
+
+ private IConfigStore mConfig = null;
+ private ISubsystem mOwner = null;
private long mStartupTime = 0;
private boolean isStarted = false;
private StringBuffer mWarning = new StringBuffer();
@@ -199,43 +201,43 @@ public class CMSEngine implements ICMSEngine {
private String mConfigSDSessionId = null;
private Timer mSDTimer = null;
- // static subsystems - must be singletons
+ // static subsystems - must be singletons
private static SubsystemInfo[] mStaticSubsystems = {
new SubsystemInfo(
- Debug.ID, Debug.getInstance()),
- new SubsystemInfo(LogSubsystem.ID,
- LogSubsystem.getInstance()),
- new SubsystemInfo(
- OsSubsystem.ID, OsSubsystem.getInstance()),
- new SubsystemInfo(
- JssSubsystem.ID, JssSubsystem.getInstance()),
- new SubsystemInfo(
- DBSubsystem.ID, DBSubsystem.getInstance()),
- new SubsystemInfo(
- UGSubsystem.ID, UGSubsystem.getInstance()),
+ Debug.ID, Debug.getInstance()),
+ new SubsystemInfo(LogSubsystem.ID,
+ LogSubsystem.getInstance()),
+ new SubsystemInfo(
+ OsSubsystem.ID, OsSubsystem.getInstance()),
+ new SubsystemInfo(
+ JssSubsystem.ID, JssSubsystem.getInstance()),
+ new SubsystemInfo(
+ DBSubsystem.ID, DBSubsystem.getInstance()),
new SubsystemInfo(
- PluginRegistry.ID, new PluginRegistry()),
+ UGSubsystem.ID, UGSubsystem.getInstance()),
new SubsystemInfo(
- OidLoaderSubsystem.ID, OidLoaderSubsystem.getInstance()),
+ PluginRegistry.ID, new PluginRegistry()),
new SubsystemInfo(
- X500NameSubsystem.ID, X500NameSubsystem.getInstance()),
- // skip TP subsystem;
+ OidLoaderSubsystem.ID, OidLoaderSubsystem.getInstance()),
+ new SubsystemInfo(
+ X500NameSubsystem.ID, X500NameSubsystem.getInstance()),
+ // skip TP subsystem;
// problem in needing dbsubsystem in constructor. and it's not used.
new SubsystemInfo(
- RequestSubsystem.ID, RequestSubsystem.getInstance()),
+ RequestSubsystem.ID, RequestSubsystem.getInstance()),
};
- // dynamic subsystems are loaded at init time, not neccessarily singletons.
+ // dynamic subsystems are loaded at init time, not neccessarily singletons.
private static SubsystemInfo[] mDynSubsystems = null;
- // final static subsystems - must be singletons.
+ // final static subsystems - must be singletons.
private static SubsystemInfo[] mFinalSubsystems = {
- new SubsystemInfo(
- AuthSubsystem.ID, AuthSubsystem.getInstance()),
- new SubsystemInfo(
- AuthzSubsystem.ID, AuthzSubsystem.getInstance()),
new SubsystemInfo(
- JobsScheduler.ID, JobsScheduler.getInstance()),
+ AuthSubsystem.ID, AuthSubsystem.getInstance()),
+ new SubsystemInfo(
+ AuthzSubsystem.ID, AuthzSubsystem.getInstance()),
+ new SubsystemInfo(
+ JobsScheduler.ID, JobsScheduler.getInstance()),
};
private static final int IP = 0;
@@ -247,12 +249,12 @@ public class CMSEngine implements ICMSEngine {
private static final int EE_NON_SSL = 3;
private static final int EE_CLIENT_AUTH_SSL = 4;
private static String mServerCertNickname = null;
- private static String info[][] = { {null, null, null},//agent
- {null, null, null},//admin
- {null, null, null},//sslEE
- {null, null, null},//non_sslEE
- {null, null, null} //ssl_clientauth_EE
- };
+ private static String info[][] = { { null, null, null },// agent
+ { null, null, null },// admin
+ { null, null, null },// sslEE
+ { null, null, null },// non_sslEE
+ { null, null, null } // ssl_clientauth_EE
+ };
/**
* private constructor.
@@ -261,14 +263,14 @@ public class CMSEngine implements ICMSEngine {
}
/**
- * gets this ID
+ * gets this ID
*/
public String getId() {
return ID;
}
/**
- * should never be called. returns error.
+ * should never be called. returns error.
*/
public void setId(String id) throws EBaseException {
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_OPERATION"));
@@ -283,42 +285,43 @@ public class CMSEngine implements ICMSEngine {
public synchronized IPasswordStore getPasswordStore() {
// initialize the PasswordReader and PasswordWriter
- try {
- String pwdPath = mConfig.getString("passwordFile");
- if (mPasswordStore == null) {
- CMS.debug("CMSEngine: getPasswordStore(): password store not initialized before.");
- String pwdClass = mConfig.getString("passwordClass");
+ try {
+ String pwdPath = mConfig.getString("passwordFile");
+ if (mPasswordStore == null) {
+ CMS.debug("CMSEngine: getPasswordStore(): password store not initialized before.");
+ String pwdClass = mConfig.getString("passwordClass");
- if (pwdClass != null) {
- try {
- mPasswordStore = (IPasswordStore)Class.forName(pwdClass).newInstance();
- } catch (Exception e) {
- CMS.debug("CMSEngine: getPasswordStore(): password store initialization failure:" + e.toString());
+ if (pwdClass != null) {
+ try {
+ mPasswordStore = (IPasswordStore) Class.forName(pwdClass).newInstance();
+ } catch (Exception e) {
+ CMS.debug("CMSEngine: getPasswordStore(): password store initialization failure:" + e.toString());
+ }
+ }
+ } else {
+ CMS.debug("CMSEngine: getPasswordStore(): password store initialized before.");
}
- }
- } else {
- CMS.debug("CMSEngine: getPasswordStore(): password store initialized before.");
- }
- // have to initialize it because other places don't always
- mPasswordStore.init(pwdPath);
- CMS.debug("CMSEngine: getPasswordStore(): password store initialized.");
- } catch (Exception e) {
- CMS.debug("CMSEngine: getPasswordStore(): failure:" + e.toString());
- }
+ // have to initialize it because other places don't always
+ mPasswordStore.init(pwdPath);
+ CMS.debug("CMSEngine: getPasswordStore(): password store initialized.");
+ } catch (Exception e) {
+ CMS.debug("CMSEngine: getPasswordStore(): failure:" + e.toString());
+ }
- return mPasswordStore;
+ return mPasswordStore;
}
/**
* initialize all static, dynamic and final static subsystems.
+ *
* @param owner null
* @param config main config store.
- * @exception EBaseException if any error occur in subsystems during
- * initialization.
+ * @exception EBaseException if any error occur in subsystems during
+ * initialization.
*/
- public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ public void init(ISubsystem owner, IConfigStore config)
+ throws EBaseException {
mOwner = owner;
mConfig = config;
int state = mConfig.getInteger("cs.state");
@@ -337,7 +340,7 @@ public class CMSEngine implements ICMSEngine {
mSDTimer = new Timer();
SessionTimer timertask = new SessionTimer(mSecurityDomainSessionTable);
if ((state != 1) || (sd.equals("existing"))) {
- // for non-security domain hosts or if not yet configured,
+ // for non-security domain hosts or if not yet configured,
// do not check session domain table
} else {
mSDTimer.schedule(timertask, 5, (new Long(secdomain_check_interval)).longValue());
@@ -363,10 +366,10 @@ public class CMSEngine implements ICMSEngine {
loadDynSubsystems();
java.security.Security.addProvider(
- new netscape.security.provider.CMS());
+ new netscape.security.provider.CMS());
mSSReg.put(ID, this);
- initSubsystems(mStaticSubsystems, false);
+ initSubsystems(mStaticSubsystems, false);
// Once the log subsystem is initialized, we
// want to register a listener to catch
@@ -379,7 +382,7 @@ public class CMSEngine implements ICMSEngine {
initSubsystems(mDynSubsystems, true);
initSubsystems(mFinalSubsystems, false);
- CMS.debug("Java version=" + (String)System.getProperty("java.version"));
+ CMS.debug("Java version=" + (String) System.getProperty("java.version"));
java.security.Provider ps[] = java.security.Security.getProviders();
if (ps == null || ps.length <= 0) {
@@ -395,8 +398,10 @@ public class CMSEngine implements ICMSEngine {
/**
* Parse ACL resource attributes
+ *
* @param resACLs same format as the resourceACLs attribute:
- * <PRE>
+ *
+ * <PRE>
* <resource name>:<permission1,permission2,...permissionn>:
* <allow|deny> (<subset of the permission set>) <evaluator expression>
* </PRE>
@@ -420,7 +425,7 @@ public class CMSEngine implements ICMSEngine {
if (resource == null) {
String infoMsg = "resource not specified in resourceACLS attribute:" +
- resACLs;
+ resACLs;
String[] params = new String[2];
@@ -438,7 +443,7 @@ public class CMSEngine implements ICMSEngine {
rightsString = st.substring(0, idx2);
else {
String infoMsg =
- "rights not specified in resourceACLS attribute:" + resACLs;
+ "rights not specified in resourceACLS attribute:" + resACLs;
String[] params = new String[2];
params[0] = resACLs;
@@ -487,7 +492,7 @@ public class CMSEngine implements ICMSEngine {
// fine
String infoMsg = "acls not specified in resourceACLS attribute:" +
- resACLs;
+ resACLs;
String[] params = new String[2];
@@ -511,100 +516,100 @@ public class CMSEngine implements ICMSEngine {
private void parseServerXML() {
try {
String instanceRoot = mConfig.getString("instanceRoot");
- String path = instanceRoot+File.separator+"conf"+File.separator+SERVER_XML;
+ String path = instanceRoot + File.separator + "conf" + File.separator + SERVER_XML;
DOMParser parser = new DOMParser();
parser.parse(path);
NodeList nodes = parser.getDocument().getElementsByTagName("Connector");
- String parentName="";
- String name="";
- String port="";
- for (int i=0; i<nodes.getLength(); i++) {
- Element n = (Element)nodes.item(i);
+ String parentName = "";
+ String name = "";
+ String port = "";
+ for (int i = 0; i < nodes.getLength(); i++) {
+ Element n = (Element) nodes.item(i);
parentName = "";
Element p = (Element) n.getParentNode();
- if(p != null) {
- parentName = p.getAttribute("name");
+ if (p != null) {
+ parentName = p.getAttribute("name");
}
name = n.getAttribute("name");
port = n.getAttribute("port");
-
+
// The "server.xml" file is parsed from top-to-bottom, and
// supports BOTH "Port Separation" (the new default method)
- // as well as "Shared Ports" (the old legacy method). Since
+ // as well as "Shared Ports" (the old legacy method). Since
// both methods must be supported, the file structure MUST
// conform to ONE AND ONLY ONE of the following formats:
//
// Port Separation:
//
- // <Catalina>
- // ...
- // <!-- Port Separation: Unsecure Port -->
- // <Connector name="Unsecure" . . .
- // ...
- // <!-- Port Separation: Agent Secure Port -->
- // <Connector name="Agent" . . .
- // ...
- // <!-- Port Separation: Admin Secure Port -->
- // <Connector name="Admin" . . .
- // ...
- // <!-- Port Separation: EE Secure Port -->
- // <Connector name="EE" . . .
- // ...
- // </Catalina>
+ // <Catalina>
+ // ...
+ // <!-- Port Separation: Unsecure Port -->
+ // <Connector name="Unsecure" . . .
+ // ...
+ // <!-- Port Separation: Agent Secure Port -->
+ // <Connector name="Agent" . . .
+ // ...
+ // <!-- Port Separation: Admin Secure Port -->
+ // <Connector name="Admin" . . .
+ // ...
+ // <!-- Port Separation: EE Secure Port -->
+ // <Connector name="EE" . . .
+ // ...
+ // </Catalina>
//
//
// Shared Ports:
//
- // <Catalina>
- // ...
- // <!-- Shared Ports: Unsecure Port -->
- // <Connector name="Unsecure" . . .
- // ...
- // <!-- Shared Ports: Agent, EE, and Admin Secure Port -->
- // <Connector name="Secure" . . .
- // ...
- // <!--
- // <Connector name="Unused" . . .
- // -->
- // ...
- // <!--
- // <Connector name="Unused" . . .
- // -->
- // ...
- // </Catalina>
+ // <Catalina>
+ // ...
+ // <!-- Shared Ports: Unsecure Port -->
+ // <Connector name="Unsecure" . . .
+ // ...
+ // <!-- Shared Ports: Agent, EE, and Admin Secure Port -->
+ // <Connector name="Secure" . . .
+ // ...
+ // <!--
+ // <Connector name="Unused" . . .
+ // -->
+ // ...
+ // <!--
+ // <Connector name="Unused" . . .
+ // -->
+ // ...
+ // </Catalina>
//
- if ( parentName.equals("Catalina")) {
- if( name.equals( "Unsecure" ) ) {
- // Port Separation: Unsecure Port
- // OR
- // Shared Ports: Unsecure Port
+ if (parentName.equals("Catalina")) {
+ if (name.equals("Unsecure")) {
+ // Port Separation: Unsecure Port
+ // OR
+ // Shared Ports: Unsecure Port
info[EE_NON_SSL][PORT] = port;
- } else if( name.equals( "Agent" ) ) {
- // Port Separation: Agent Secure Port
+ } else if (name.equals("Agent")) {
+ // Port Separation: Agent Secure Port
info[AGENT][PORT] = port;
- } else if( name.equals( "Admin" ) ) {
- // Port Separation: Admin Secure Port
+ } else if (name.equals("Admin")) {
+ // Port Separation: Admin Secure Port
info[ADMIN][PORT] = port;
- } else if( name.equals( "EE" ) ) {
- // Port Separation: EE Secure Port
+ } else if (name.equals("EE")) {
+ // Port Separation: EE Secure Port
info[EE_SSL][PORT] = port;
- } else if( name.equals( "EEClientAuth" ) ) {
+ } else if (name.equals("EEClientAuth")) {
// Port Separation: EE Client Auth Secure Port
- info[EE_CLIENT_AUTH_SSL][PORT] = port;
- } else if( name.equals( "Secure" ) ) {
- // Shared Ports: Agent, EE, and Admin Secure Port
+ info[EE_CLIENT_AUTH_SSL][PORT] = port;
+ } else if (name.equals("Secure")) {
+ // Shared Ports: Agent, EE, and Admin Secure Port
info[AGENT][PORT] = port;
info[ADMIN][PORT] = port;
info[EE_SSL][PORT] = port;
info[EE_CLIENT_AUTH_SSL][PORT] = port;
}
- }
- }
-
- } catch (Exception e) {
- CMS.debug("CMSEngine: parseServerXML exception: " + e.toString());
- }
+ }
+ }
+
+ } catch (Exception e) {
+ CMS.debug("CMSEngine: parseServerXML exception: " + e.toString());
+ }
}
private void fixProxyPorts() throws EBaseException {
@@ -624,24 +629,22 @@ public class CMSEngine implements ICMSEngine {
} catch (EBaseException e) {
CMS.debug("CMSEngine: fixProxyPorts exception: " + e.toString());
throw e;
- }
+ }
}
-
public IConfigStore createFileConfigStore(String path) throws EBaseException {
try {
- /* if the file is not there, create one */
- File f = new File(path);
- if (!f.exists()) {
- f.createNewFile();
- }
+ /* if the file is not there, create one */
+ File f = new File(path);
+ if (!f.exists()) {
+ f.createNewFile();
+ }
} catch (Exception e) {
}
-
return new FileConfigStore(path);
}
-
+
public IArgBlock createArgBlock() {
return new ArgBlock();
}
@@ -684,7 +687,7 @@ public class CMSEngine implements ICMSEngine {
}
public ICRLIssuingPointRecord createCRLIssuingPointRecord(String
- id, BigInteger crlNumber, Long crlSize, Date thisUpdate, Date nextUpdate) {
+ id, BigInteger crlNumber, Long crlSize, Date thisUpdate, Date nextUpdate) {
return new CRLIssuingPointRecord(id, crlNumber, crlSize, thisUpdate, nextUpdate);
}
@@ -778,17 +781,17 @@ public class CMSEngine implements ICMSEngine {
}
public IHttpConnection getHttpConnection(IRemoteAuthority authority,
- ISocketFactory factory) {
+ ISocketFactory factory) {
return new HttpConnection(authority, factory);
}
public IHttpConnection getHttpConnection(IRemoteAuthority authority,
- ISocketFactory factory, int timeout) {
+ ISocketFactory factory, int timeout) {
return new HttpConnection(authority, factory, timeout);
}
public IResender getResender(IAuthority authority, String nickname,
- IRemoteAuthority remote, int interval) {
+ IRemoteAuthority remote, int interval) {
return new Resender(authority, nickname, remote, interval);
}
@@ -796,31 +799,31 @@ public class CMSEngine implements ICMSEngine {
return new HttpPKIMessage();
}
- public ILdapConnInfo getLdapConnInfo(IConfigStore config)
- throws EBaseException, ELdapException {
+ public ILdapConnInfo getLdapConnInfo(IConfigStore config)
+ throws EBaseException, ELdapException {
return new LdapConnInfo(config);
}
- public LDAPSSLSocketFactoryExt getLdapJssSSLSocketFactory(
- String certNickname) {
+ public LDAPSSLSocketFactoryExt getLdapJssSSLSocketFactory(
+ String certNickname) {
return new LdapJssSSLSocketFactory(certNickname);
}
- public LDAPSSLSocketFactoryExt getLdapJssSSLSocketFactory() {
+ public LDAPSSLSocketFactoryExt getLdapJssSSLSocketFactory() {
return new LdapJssSSLSocketFactory();
}
- public ILdapAuthInfo getLdapAuthInfo() {
+ public ILdapAuthInfo getLdapAuthInfo() {
return new LdapAuthInfo();
}
- public ILdapConnFactory getLdapBoundConnFactory()
- throws ELdapException {
+ public ILdapConnFactory getLdapBoundConnFactory()
+ throws ELdapException {
return new LdapBoundConnFactory();
}
- public ILdapConnFactory getLdapAnonConnFactory()
- throws ELdapException {
+ public ILdapConnFactory getLdapAnonConnFactory()
+ throws ELdapException {
return new LdapAnonConnFactory();
}
@@ -844,8 +847,8 @@ public class CMSEngine implements ICMSEngine {
* initialize an array of subsystem info.
*/
private void initSubsystems(SubsystemInfo[] sslist, boolean doSetId)
- throws EBaseException {
- if (sslist == null)
+ throws EBaseException {
+ if (sslist == null)
return;
for (int i = 0; i < sslist.length; i++) {
initSubsystem(sslist[i], doSetId);
@@ -856,34 +859,34 @@ public class CMSEngine implements ICMSEngine {
* load dynamic subsystems
*/
private void loadDynSubsystems()
- throws EBaseException {
+ throws EBaseException {
IConfigStore ssconfig = mConfig.getSubStore(PROP_SUBSYSTEM);
- // count number of dyn loaded subsystems.
+ // count number of dyn loaded subsystems.
Enumeration<String> ssnames = ssconfig.getSubStoreNames();
int nsubsystems = 0;
for (nsubsystems = 0; ssnames.hasMoreElements(); nsubsystems++)
- ssnames.nextElement();
+ ssnames.nextElement();
if (Debug.ON) {
Debug.trace(nsubsystems + " dyn subsystems loading..");
}
- if (nsubsystems == 0)
+ if (nsubsystems == 0)
return;
- // load dyn subsystems.
+ // load dyn subsystems.
mDynSubsystems = new SubsystemInfo[nsubsystems];
ssnames = ssconfig.getSubStoreNames();
for (int i = 0; i < mDynSubsystems.length; i++) {
- IConfigStore config =
- ssconfig.getSubStore(String.valueOf(i));
+ IConfigStore config =
+ ssconfig.getSubStore(String.valueOf(i));
String id = config.getString(PROP_ID);
String classname = config.getString(PROP_CLASS);
ISubsystem ss = null;
try {
ss = (ISubsystem) Class.forName(classname).newInstance();
- } catch (InstantiationException e) {
+ } catch (InstantiationException e) {
throw new EBaseException(
CMS.getUserMessage("CMS_BASE_LOAD_FAILED_1", id, e.toString()));
} catch (IllegalAccessException e) {
@@ -900,23 +903,22 @@ public class CMSEngine implements ICMSEngine {
public LDAPConnection getBoundConnection(String host, int port,
int version, LDAPSSLSocketFactoryExt fac, String bindDN,
- String bindPW) throws LDAPException
- {
- return new LdapBoundConnection(host, port, version, fac,
- bindDN, bindPW);
+ String bindPW) throws LDAPException {
+ return new LdapBoundConnection(host, port, version, fac,
+ bindDN, bindPW);
}
/**
- * initialize a subsystem
+ * initialize a subsystem
*/
- private void initSubsystem(SubsystemInfo ssinfo, boolean doSetId)
- throws EBaseException {
+ private void initSubsystem(SubsystemInfo ssinfo, boolean doSetId)
+ throws EBaseException {
String id = ssinfo.mId;
ISubsystem ss = ssinfo.mInstance;
IConfigStore ssConfig = mConfig.getSubStore(id);
CMS.debug("CMSEngine: initSubsystem id=" + id);
- if (doSetId)
+ if (doSetId)
ss.setId(id);
CMS.debug("CMSEngine: ready to init id=" + id);
ss.init(this, ssConfig);
@@ -925,8 +927,8 @@ public class CMSEngine implements ICMSEngine {
mSSReg.put(id, ss);
CMS.debug("CMSEngine: initialized " + id);
- if(id.equals("ca") || id.equals("ocsp") ||
- id.equals("kra") || id.equals("tks")) {
+ if (id.equals("ca") || id.equals("ocsp") ||
+ id.equals("kra") || id.equals("tks")) {
CMS.debug("CMSEngine::initSubsystem " + id + " Java subsytem about to calculate serverCertNickname. ");
// get SSL server nickname
IConfigStore serverCertStore = mConfig.getSubStore(id + "." + "sslserver");
@@ -934,12 +936,12 @@ public class CMSEngine implements ICMSEngine {
String nickName = serverCertStore.getString("nickname");
String tokenName = serverCertStore.getString("tokenname");
if (tokenName != null && tokenName.length() > 0 &&
- nickName != null && nickName.length() > 0) {
+ nickName != null && nickName.length() > 0) {
CMS.setServerCertNickname(tokenName, nickName);
- CMS.debug("Subsystem " + id + " init sslserver: tokenName:"+tokenName+" nickName:"+nickName);
+ CMS.debug("Subsystem " + id + " init sslserver: tokenName:" + tokenName + " nickName:" + nickName);
} else if (nickName != null && nickName.length() > 0) {
CMS.setServerCertNickname(nickName);
- CMS.debug("Subsystem " + id + " init sslserver: nickName:"+nickName);
+ CMS.debug("Subsystem " + id + " init sslserver: nickName:" + nickName);
} else {
CMS.debug("Subsystem " + id + " init error: SSL server certificate nickname is not available.");
}
@@ -955,16 +957,17 @@ public class CMSEngine implements ICMSEngine {
/**
* Starts up all subsystems. subsystems must be initialized.
+ *
* @exception EBaseException if any subsystem fails to startup.
*/
public void startup() throws EBaseException {
- //OsSubsystem.nativeExit(0);
+ // OsSubsystem.nativeExit(0);
startupSubsystems(mStaticSubsystems);
if (mDynSubsystems != null)
startupSubsystems(mDynSubsystems);
startupSubsystems(mFinalSubsystems);
- // global admin servlet. (anywhere else more fit for this ?)
+ // global admin servlet. (anywhere else more fit for this ?)
mStartupTime = System.currentTimeMillis();
@@ -981,7 +984,7 @@ public class CMSEngine implements ICMSEngine {
CMS.debug("CMSEngine: checking certificate serial number ranges");
ca.getCertificateRepository().checkRanges();
- }
+ }
IKeyRecoveryAuthority kra = (IKeyRecoveryAuthority) getSubsystem("kra");
if ((kra != null) && !isPreOpMode()) {
@@ -992,16 +995,18 @@ public class CMSEngine implements ICMSEngine {
kra.getKeyRepository().checkRanges();
}
- /*LogDoc
- *
+ /*
+ * LogDoc
+ *
* @phase server startup
+ *
* @reason all subsystems are initialized and started.
*/
Logger.getLogger().log(ILogger.EV_SYSTEM, ILogger.S_ADMIN,
- ILogger.LL_INFO, CMS.getLogMessage("SERVER_STARTUP"));
+ ILogger.LL_INFO, CMS.getLogMessage("SERVER_STARTUP"));
System.out.println(Constants.SERVER_STARTUP_MESSAGE);
isStarted = true;
-
+
}
public boolean isInRunningState() {
@@ -1011,31 +1016,31 @@ public class CMSEngine implements ICMSEngine {
public byte[] getPKCS7(Locale locale, IRequest req) {
try {
X509CertImpl cert = req.getExtDataInCert(
- IEnrollProfile.REQUEST_ISSUED_CERT);
+ IEnrollProfile.REQUEST_ISSUED_CERT);
if (cert == null)
return null;
-
+
ICertificateAuthority ca = (ICertificateAuthority)
- CMS.getSubsystem("ca");
+ CMS.getSubsystem("ca");
CertificateChain cachain = ca.getCACertChain();
X509Certificate[] cacerts = cachain.getChain();
X509CertImpl[] userChain = new X509CertImpl[cacerts.length + 1];
int m = 1, n = 0;
-
+
for (; n < cacerts.length; m++, n++) {
userChain[m] = (X509CertImpl) cacerts[n];
}
userChain[0] = cert;
PKCS7 p7 = new PKCS7(new AlgorithmId[0],
- new ContentInfo(new byte[0]),
- userChain,
- new SignerInfo[0]);
+ new ContentInfo(new byte[0]),
+ userChain,
+ new SignerInfo[0]);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
p7.encodeSignedData(bos);
- return bos.toByteArray();
+ return bos.toByteArray();
} catch (Exception e) {
return null;
}
@@ -1046,11 +1051,11 @@ public class CMSEngine implements ICMSEngine {
}
public void setServerCertNickname(String tokenName, String
- nickName) {
+ nickName) {
String newName = null;
if (tokenName.equals(Constants.PR_INTERNAL_TOKEN_NAME) ||
- tokenName.equalsIgnoreCase("Internal Key Storage Token"))
+ tokenName.equalsIgnoreCase("Internal Key Storage Token"))
newName = nickName;
else {
if (tokenName.equals("") && nickName.equals(""))
@@ -1063,83 +1068,63 @@ public class CMSEngine implements ICMSEngine {
public void setServerCertNickname(String newName) {
// modify server.xml
-/*
- String filePrefix = instanceDir + File.separator +
- "config" + File.separator;
- String orig = filePrefix + "server.xml";
- String dest = filePrefix + "server.xml.bak";
- String newF = filePrefix + "server.xml.new";
-
- // save the old copy
- Utils.copy(orig, dest);
-
- BufferedReader in1 = null;
- PrintWriter out1 = null;
-
- try {
- in1 = new BufferedReader(new FileReader(dest));
- out1 = new PrintWriter(
- new BufferedWriter(new FileWriter(newF)));
- String line = "";
-
- while (in1.ready()) {
- line = in1.readLine();
- if (line != null)
- out1.println(lineParsing(line, newName));
- }
-
- out1.close();
- in1.close();
- } catch (Exception eee) {
- Logger.getLogger().log(ILogger.EV_SYSTEM, ILogger.S_ADMIN,
- ILogger.LL_FAILURE, CMS.getLogMessage("OPERATION_ERROR", eee.toString()));
- }
-
- File file = new File(newF);
- File nfile = new File(orig);
-
- try {
- boolean success = file.renameTo(nfile);
-
- if (!success) {
- if (Utils.isNT()) {
- // NT is very picky on the path
- Utils.exec("copy " +
- file.getAbsolutePath().replace('/', '\\') + " " +
- nfile.getAbsolutePath().replace('/', '\\'));
- } else {
- Utils.exec("cp " + file.getAbsolutePath() + " " +
- nfile.getAbsolutePath());
- }
- }
- } catch (Exception exx) {
- Logger.getLogger().log(ILogger.EV_SYSTEM, ILogger.S_ADMIN,
- ILogger.LL_FAILURE, "CMSEngine: Error " + exx.toString());
- }
- // update "cache" for CMS.getServerCertNickname()
-*/
+ /*
+ * String filePrefix = instanceDir + File.separator + "config" +
+ * File.separator; String orig = filePrefix + "server.xml"; String dest
+ * = filePrefix + "server.xml.bak"; String newF = filePrefix +
+ * "server.xml.new";
+ *
+ * // save the old copy Utils.copy(orig, dest);
+ *
+ * BufferedReader in1 = null; PrintWriter out1 = null;
+ *
+ * try { in1 = new BufferedReader(new FileReader(dest)); out1 = new
+ * PrintWriter( new BufferedWriter(new FileWriter(newF))); String line =
+ * "";
+ *
+ * while (in1.ready()) { line = in1.readLine(); if (line != null)
+ * out1.println(lineParsing(line, newName)); }
+ *
+ * out1.close(); in1.close(); } catch (Exception eee) {
+ * Logger.getLogger().log(ILogger.EV_SYSTEM, ILogger.S_ADMIN,
+ * ILogger.LL_FAILURE, CMS.getLogMessage("OPERATION_ERROR",
+ * eee.toString())); }
+ *
+ * File file = new File(newF); File nfile = new File(orig);
+ *
+ * try { boolean success = file.renameTo(nfile);
+ *
+ * if (!success) { if (Utils.isNT()) { // NT is very picky on the path
+ * Utils.exec("copy " + file.getAbsolutePath().replace('/', '\\') + " "
+ * + nfile.getAbsolutePath().replace('/', '\\')); } else {
+ * Utils.exec("cp " + file.getAbsolutePath() + " " +
+ * nfile.getAbsolutePath()); } } } catch (Exception exx) {
+ * Logger.getLogger().log(ILogger.EV_SYSTEM, ILogger.S_ADMIN,
+ * ILogger.LL_FAILURE, "CMSEngine: Error " + exx.toString()); } //
+ * update "cache" for CMS.getServerCertNickname()
+ */
mServerCertNickname = newName;
}
public String getFingerPrint(Certificate cert)
- throws CertificateEncodingException, NoSuchAlgorithmException {
+ throws CertificateEncodingException, NoSuchAlgorithmException {
return CertUtils.getFingerPrint(cert);
}
public String getFingerPrints(Certificate cert)
- throws NoSuchAlgorithmException, CertificateEncodingException {
+ throws NoSuchAlgorithmException, CertificateEncodingException {
return CertUtils.getFingerPrints(cert);
}
public String getFingerPrints(byte[] certDer)
- throws NoSuchAlgorithmException {
+ throws NoSuchAlgorithmException {
return CertUtils.getFingerPrints(certDer);
}
public String getUserMessage(Locale locale, String msgID, String params[]) {
// if locale is null, try to get it out from session context
if (locale == null) {
- SessionContext sc = SessionContext.getExistingContext();
+ SessionContext sc = SessionContext.getExistingContext();
if (sc != null)
locale = (Locale) sc.get(SessionContext.LOCALE);
@@ -1178,8 +1163,8 @@ public class CMSEngine implements ICMSEngine {
return getUserMessage(locale, msgID, params);
}
- public String getUserMessage(Locale locale, String msgID,
- String p1, String p2, String p3) {
+ public String getUserMessage(Locale locale, String msgID,
+ String p1, String p2, String p3) {
String params[] = { p1, p2, p3 };
return getUserMessage(locale, msgID, params);
@@ -1198,7 +1183,7 @@ public class CMSEngine implements ICMSEngine {
}
public void debug(byte data[]) {
- if (!debugOn()) {
+ if (!debugOn()) {
// this helps to not saving stuff to file when debug
// is disable
return;
@@ -1207,7 +1192,7 @@ public class CMSEngine implements ICMSEngine {
}
public void debug(int level, String msg) {
- if (!debugOn()) {
+ if (!debugOn()) {
// this helps to not saving stuff to file when debug
// is disable
return;
@@ -1216,7 +1201,7 @@ public class CMSEngine implements ICMSEngine {
}
public void debug(String msg) {
- if (!debugOn()) {
+ if (!debugOn()) {
// this helps to not saving stuff to file when debug
// is disable
return;
@@ -1225,7 +1210,7 @@ public class CMSEngine implements ICMSEngine {
}
public void debug(Throwable e) {
- if (!debugOn()) {
+ if (!debugOn()) {
// this helps to not saving stuff to file when debug
// is disable
return;
@@ -1244,14 +1229,15 @@ public class CMSEngine implements ICMSEngine {
public void traceHashKey(String type, String key) {
Debug.traceHashKey(type, key);
}
+
public void traceHashKey(String type, String key, String val) {
Debug.traceHashKey(type, key, val);
}
+
public void traceHashKey(String type, String key, String val, String def) {
Debug.traceHashKey(type, key, val, def);
}
-
public String getLogMessage(String msgID) {
return getLogMessage(msgID, (String[]) null);
}
@@ -1310,67 +1296,67 @@ public class CMSEngine implements ICMSEngine {
return getLogMessage(msgID, params);
}
- public void getSubjAltNameConfigDefaultParams(String name,
- Vector<String> params) {
+ public void getSubjAltNameConfigDefaultParams(String name,
+ Vector<String> params) {
GeneralNameUtil.SubjAltNameGN.getDefaultParams(name, params);
}
- public void getSubjAltNameConfigExtendedPluginInfo(String name,
- Vector<String> params) {
+ public void getSubjAltNameConfigExtendedPluginInfo(String name,
+ Vector<String> params) {
GeneralNameUtil.SubjAltNameGN.getExtendedPluginInfo(name, params);
}
- public ISubjAltNameConfig createSubjAltNameConfig(String name, IConfigStore config, boolean isValueConfigured) throws EBaseException {
+ public ISubjAltNameConfig createSubjAltNameConfig(String name, IConfigStore config, boolean isValueConfigured) throws EBaseException {
return new GeneralNameUtil.SubjAltNameGN(name, config, isValueConfigured);
}
- public GeneralName form_GeneralNameAsConstraints(String generalNameChoice, String value) throws EBaseException {
+ public GeneralName form_GeneralNameAsConstraints(String generalNameChoice, String value) throws EBaseException {
return GeneralNameUtil.form_GeneralNameAsConstraints(generalNameChoice, value);
}
- public GeneralName form_GeneralName(String generalNameChoice,
- String value) throws EBaseException {
+ public GeneralName form_GeneralName(String generalNameChoice,
+ String value) throws EBaseException {
return GeneralNameUtil.form_GeneralName(generalNameChoice, value);
}
- public void getGeneralNameConfigDefaultParams(String name,
- boolean isValueConfigured, Vector<String> params) {
+ public void getGeneralNameConfigDefaultParams(String name,
+ boolean isValueConfigured, Vector<String> params) {
GeneralNameUtil.GeneralNameConfig.getDefaultParams(name, isValueConfigured, params);
}
- public void getGeneralNamesConfigDefaultParams(String name,
- boolean isValueConfigured, Vector<String> params) {
+ public void getGeneralNamesConfigDefaultParams(String name,
+ boolean isValueConfigured, Vector<String> params) {
GeneralNameUtil.GeneralNamesConfig.getDefaultParams(name, isValueConfigured, params);
}
- public void getGeneralNameConfigExtendedPluginInfo(String name,
- boolean isValueConfigured, Vector<String> info) {
+ public void getGeneralNameConfigExtendedPluginInfo(String name,
+ boolean isValueConfigured, Vector<String> info) {
GeneralNameUtil.GeneralNameConfig.getExtendedPluginInfo(name, isValueConfigured, info);
}
- public void getGeneralNamesConfigExtendedPluginInfo(String name,
- boolean isValueConfigured, Vector<String> info) {
+ public void getGeneralNamesConfigExtendedPluginInfo(String name,
+ boolean isValueConfigured, Vector<String> info) {
GeneralNameUtil.GeneralNamesConfig.getExtendedPluginInfo(name, isValueConfigured, info);
}
- public IGeneralNamesConfig createGeneralNamesConfig(String name,
- IConfigStore config, boolean isValueConfigured,
- boolean isPolicyEnabled) throws EBaseException {
+ public IGeneralNamesConfig createGeneralNamesConfig(String name,
+ IConfigStore config, boolean isValueConfigured,
+ boolean isPolicyEnabled) throws EBaseException {
return new GeneralNameUtil.GeneralNamesConfig(name, config, isValueConfigured, isPolicyEnabled);
}
- public IGeneralNameAsConstraintsConfig createGeneralNameAsConstraintsConfig(String name, IConfigStore config, boolean isValueConfigured,
- boolean isPolicyEnabled) throws EBaseException {
+ public IGeneralNameAsConstraintsConfig createGeneralNameAsConstraintsConfig(String name, IConfigStore config, boolean isValueConfigured,
+ boolean isPolicyEnabled) throws EBaseException {
return new GeneralNameUtil.GeneralNameAsConstraintsConfig(name, config, isValueConfigured, isPolicyEnabled);
}
- public IGeneralNamesAsConstraintsConfig createGeneralNamesAsConstraintsConfig(String name, IConfigStore config, boolean isValueConfigured,
- boolean isPolicyEnabled) throws EBaseException {
+ public IGeneralNamesAsConstraintsConfig createGeneralNamesAsConstraintsConfig(String name, IConfigStore config, boolean isValueConfigured,
+ boolean isPolicyEnabled) throws EBaseException {
return new GeneralNameUtil.GeneralNamesAsConstraintsConfig(name, config, isValueConfigured, isPolicyEnabled);
}
public ObjectIdentifier checkOID(String attrName, String value)
- throws EBaseException {
+ throws EBaseException {
return CertUtils.checkOID(attrName, value);
}
@@ -1384,10 +1370,9 @@ public class CMSEngine implements ICMSEngine {
public String getEncodedCert(X509Certificate cert) {
try {
- return
- "-----BEGIN CERTIFICATE-----\n" +
- CMS.BtoA(cert.getEncoded()) +
- "\n-----END CERTIFICATE-----\n";
+ return "-----BEGIN CERTIFICATE-----\n" +
+ CMS.BtoA(cert.getEncoded()) +
+ "\n-----END CERTIFICATE-----\n";
} catch (Exception e) {
return null;
}
@@ -1439,10 +1424,10 @@ public class CMSEngine implements ICMSEngine {
public IMailNotification getMailNotification() {
try {
- String className = mConfig.getString("notificationClassName",
+ String className = mConfig.getString("notificationClassName",
"com.netscape.cms.notification.MailNotification");
IMailNotification notification = (IMailNotification)
- Class.forName(className).newInstance();
+ Class.forName(className).newInstance();
return notification;
} catch (Exception e) {
@@ -1475,7 +1460,7 @@ public class CMSEngine implements ICMSEngine {
String className = mConfig.getString("passwordCheckerClass",
"com.netscape.cms.password.PasswordChecker");
IPasswordCheck check = (IPasswordCheck)
- Class.forName(className).newInstance();
+ Class.forName(className).newInstance();
return check;
} catch (Exception e) {
@@ -1494,8 +1479,8 @@ public class CMSEngine implements ICMSEngine {
/**
* starts up subsystems in a subsystem list..
*/
- private void startupSubsystems(SubsystemInfo[] sslist)
- throws EBaseException {
+ private void startupSubsystems(SubsystemInfo[] sslist)
+ throws EBaseException {
ISubsystem ss = null;
for (int i = 0; i < sslist.length; i++) {
@@ -1519,7 +1504,7 @@ public class CMSEngine implements ICMSEngine {
while (e.hasMoreElements()) {
Object thisRequest = e.nextElement();
-
+
HttpServlet thisServlet = (HttpServlet) CommandQueue.mCommandQueue.get(thisRequest);
if (thisServlet != null) {
@@ -1528,6 +1513,7 @@ public class CMSEngine implements ICMSEngine {
}
}
}
+
public static boolean isNT() {
return (File.separator.equals("\\"));
}
@@ -1542,17 +1528,16 @@ public class CMSEngine implements ICMSEngine {
cmds = new String[3];
cmds[0] = "cmd";
cmds[1] = "/c";
- cmds[2] = instanceDir +"\\" + cmd;
+ cmds[2] = instanceDir + "\\" + cmd;
} else {
// UNIX
cmds = new String[3];
cmds[0] = "/bin/sh";
cmds[1] = "-c";
- cmds[2] = instanceDir +"/" +cmd;
+ cmds[2] = instanceDir + "/" + cmd;
}
- Process process = Runtime.getRuntime().exec(cmds);
-
+ Process process = Runtime.getRuntime().exec(cmds);
process.waitFor();
@@ -1562,38 +1547,32 @@ public class CMSEngine implements ICMSEngine {
}
} // end shutdownHttpServer
+
/**
- * Shuts down subsystems in backwards order
- * exceptions are ignored. process exists at end to force exit.
+ * Shuts down subsystems in backwards order exceptions are ignored. process
+ * exists at end to force exit.
*/
public void shutdown() {
Logger.getLogger().log(ILogger.EV_SYSTEM, ILogger.S_ADMIN,
- ILogger.LL_INFO, Constants.SERVER_SHUTDOWN_MESSAGE);
+ ILogger.LL_INFO, Constants.SERVER_SHUTDOWN_MESSAGE);
CMS.debug("CMSEngine.shutdown()");
-
-/*
- CommandQueue commandQueue = new CommandQueue();
- Thread t1 = new Thread(commandQueue);
- t1.setDaemon(true);
- t1.start();
-
- // wait for command queue to emptied before proceeding to shutting down subsystems
- Date time = new Date();
- long startTime = time.getTime();
- long timeOut = time.getTime();
-
- while (t1.isAlive() && ((timeOut - startTime) < (60 * 1000))) //wait for 1 minute
- {
- try {
- Thread.currentThread().sleep(5000); // sleep for 5 sec
- }catch (java.lang.InterruptedException e) {
- }
- timeOut = time.getTime();
- }
- terminateRequests();
-*/
+ /*
+ * CommandQueue commandQueue = new CommandQueue(); Thread t1 = new
+ * Thread(commandQueue);
+ *
+ * t1.setDaemon(true); t1.start();
+ *
+ * // wait for command queue to emptied before proceeding to shutting
+ * down subsystems Date time = new Date(); long startTime =
+ * time.getTime(); long timeOut = time.getTime();
+ *
+ * while (t1.isAlive() && ((timeOut - startTime) < (60 * 1000))) //wait
+ * for 1 minute { try { Thread.currentThread().sleep(5000); // sleep for
+ * 5 sec }catch (java.lang.InterruptedException e) { } timeOut =
+ * time.getTime(); } terminateRequests();
+ */
shutdownSubsystems(mFinalSubsystems);
shutdownSubsystems(mDynSubsystems);
@@ -1603,15 +1582,14 @@ public class CMSEngine implements ICMSEngine {
}
/**
- * Shuts down subsystems in backwards order
- * exceptions are ignored. process exists at end to force exit.
- * Added extra call to shutdown the web server.
+ * Shuts down subsystems in backwards order exceptions are ignored. process
+ * exists at end to force exit. Added extra call to shutdown the web server.
*/
public void forceShutdown() {
Logger.getLogger().log(ILogger.EV_SYSTEM, ILogger.S_ADMIN,
- ILogger.LL_INFO, Constants.SERVER_SHUTDOWN_MESSAGE);
+ ILogger.LL_INFO, Constants.SERVER_SHUTDOWN_MESSAGE);
CMS.debug("CMSEngine.forceShutdown()");
@@ -1621,16 +1599,19 @@ public class CMSEngine implements ICMSEngine {
t1.setDaemon(true);
t1.start();
- // wait for command queue to emptied before proceeding to shutting down subsystems
+ // wait for command queue to emptied before proceeding to shutting down
+ // subsystems
Date time = new Date();
long startTime = time.getTime();
long timeOut = time.getTime();
- while (t1.isAlive() && ((timeOut - startTime) < (60 * 1000))) //wait for 1 minute
+ while (t1.isAlive() && ((timeOut - startTime) < (60 * 1000))) // wait
+ // for 1
+ // minute
{
try {
- Thread.sleep(5000); // sleep for 5 sec
- }catch (java.lang.InterruptedException e) {
+ Thread.sleep(5000); // sleep for 5 sec
+ } catch (java.lang.InterruptedException e) {
}
timeOut = time.getTime();
}
@@ -1647,12 +1628,11 @@ public class CMSEngine implements ICMSEngine {
* shuts down a subsystem list in reverse order.
*/
private void shutdownSubsystems(SubsystemInfo[] sslist) {
- if (sslist == null)
+ if (sslist == null)
return;
for (int i = sslist.length - 1; i >= 0; i--) {
- if (sslist[i] != null && sslist[i].mInstance != null)
- {
+ if (sslist[i] != null && sslist[i].mInstance != null) {
sslist[i].mInstance.shutdown();
}
}
@@ -1679,7 +1659,7 @@ public class CMSEngine implements ICMSEngine {
} catch (EBaseException e) {
// intercept this for now -- don't want to change the callers
Logger.getLogger().log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SDR_ADD_ERROR", e.toString()));
+ ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SDR_ADD_ERROR", e.toString()));
}
}
@@ -1707,22 +1687,21 @@ public class CMSEngine implements ICMSEngine {
}
public static void upgradeConfig(IConfigStore c)
- throws EBaseException {
+ throws EBaseException {
String version = c.getString("cms.version", "pre4.2");
if (version.equals("4.22")) {
Upgrade.perform422to45(c);
- }else if (version.equals("4.2")) {
+ } else if (version.equals("4.2")) {
// SUPPORT UPGRADE FROM 4.2 to 4.2 (SP2)
Upgrade.perform42to422(c);
Upgrade.perform422to45(c);
} else {
// ONLY SUPPORT UPGRADE FROM 4.2 to 4.2 (SP2)
/**
- if (!version.equals("pre4.2"))
- return;
-
- Upgrade.perform(c);
+ * if (!version.equals("pre4.2")) return;
+ *
+ * Upgrade.perform(c);
**/
}
}
@@ -1753,10 +1732,10 @@ public class CMSEngine implements ICMSEngine {
try {
IRegistrationAuthority ra = (IRegistrationAuthority)
- SubsystemRegistry.getInstance().get("ra");
+ SubsystemRegistry.getInstance().get("ra");
if (ra != null) {
- queue = ra.getRequestQueue();
+ queue = ra.getRequestQueue();
}
} catch (Exception e) {
@@ -1788,8 +1767,8 @@ public class CMSEngine implements ICMSEngine {
result = mVCList.check(cert);
}
if (result != VerifiedCert.REVOKED &&
- result != VerifiedCert.NOT_REVOKED &&
- result != VerifiedCert.CHECKED) {
+ result != VerifiedCert.NOT_REVOKED &&
+ result != VerifiedCert.CHECKED) {
CertificateRepository certDB = (CertificateRepository) getCertDB();
@@ -1815,9 +1794,9 @@ public class CMSEngine implements ICMSEngine {
try {
checkRevReq = queue.newRequest(CertRequestConstants.GETREVOCATIONINFO_REQUEST);
checkRevReq.setExtData(IRequest.REQ_TYPE,
- CertRequestConstants.GETREVOCATIONINFO_REQUEST);
+ CertRequestConstants.GETREVOCATIONINFO_REQUEST);
checkRevReq.setExtData(IRequest.REQUESTOR_TYPE,
- IRequest.REQUESTOR_RA);
+ IRequest.REQUESTOR_RA);
X509CertImpl agentCerts[] = new X509CertImpl[certificates.length];
@@ -1865,12 +1844,11 @@ public class CMSEngine implements ICMSEngine {
}
private void log(int level, String msg) {
- Logger.getLogger().log(ILogger.EV_SYSTEM, null,
- ILogger.S_AUTHENTICATION, level, msg);
+ Logger.getLogger().log(ILogger.EV_SYSTEM, null,
+ ILogger.S_AUTHENTICATION, level, msg);
}
}
-
class WarningListener implements ILogEventListener {
private StringBuffer mSB = null;
@@ -1903,19 +1881,19 @@ class WarningListener implements ILogEventListener {
return null;
}
- public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ public void init(ISubsystem owner, IConfigStore config)
+ throws EBaseException {
}
public void startup() {
}
/**
- * Retrieve last "maxLine" number of system log with log lever >"level"
- * and from source "source". If the parameter is omitted. All entries
- * are sent back.
+ * Retrieve last "maxLine" number of system log with log lever >"level" and
+ * from source "source". If the parameter is omitted. All entries are sent
+ * back.
*/
- public synchronized NameValuePairs retrieveLogContent(Hashtable<String, String> req) throws ServletException,
+ public synchronized NameValuePairs retrieveLogContent(Hashtable<String, String> req) throws ServletException,
IOException, EBaseException {
return null;
}
@@ -1923,7 +1901,7 @@ class WarningListener implements ILogEventListener {
/**
* Retrieve log file list.
*/
- public synchronized NameValuePairs retrieveLogList(Hashtable<String, String> req) throws ServletException,
+ public synchronized NameValuePairs retrieveLogList(Hashtable<String, String> req) throws ServletException,
IOException, EBaseException {
return null;
}
@@ -1949,14 +1927,13 @@ class WarningListener implements ILogEventListener {
}
}
-
class SubsystemInfo {
public final String mId;
public final ISubsystem mInstance;
+
public SubsystemInfo(String id, ISubsystem ssInstance) {
mId = id;
mInstance = ssInstance;
}
-
-}
+}
diff --git a/pki/base/common/src/com/netscape/cmscore/apps/CommandQueue.java b/pki/base/common/src/com/netscape/cmscore/apps/CommandQueue.java
index 41b31049..d4b55604 100644
--- a/pki/base/common/src/com/netscape/cmscore/apps/CommandQueue.java
+++ b/pki/base/common/src/com/netscape/cmscore/apps/CommandQueue.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.apps;
-
import java.util.Hashtable;
import javax.servlet.Servlet;
@@ -25,23 +24,22 @@ import javax.servlet.Servlet;
import com.netscape.certsrv.apps.ICommandQueue;
import com.netscape.cms.servlet.common.CMSRequest;
-
/*---------------------------------------------------------------
** CommandQueue - Class
*/
/**
- * register and unregister proccess for clean shutdown
+ * register and unregister proccess for clean shutdown
*/
public class CommandQueue implements Runnable, ICommandQueue {
- public static Hashtable<CMSRequest, Servlet> mCommandQueue = new Hashtable<CMSRequest, Servlet>();
+ public static Hashtable<CMSRequest, Servlet> mCommandQueue = new Hashtable<CMSRequest, Servlet>();
public static boolean mShuttingDown = false;
/*-----------------------------------------------------------
** CommandQueue - Constructor
*/
-
+
/**
* Main constructor.
*/
@@ -52,21 +50,21 @@ public class CommandQueue implements Runnable, ICommandQueue {
/*-----------------------------------------------------------
** run
*/
-
+
/**
* Overrides Thread.run(), calls batchPublish().
*/
public void run() {
- //int priority = Thread.MIN_PRIORITY;
- //Thread.currentThread().setPriority(priority);
+ // int priority = Thread.MIN_PRIORITY;
+ // Thread.currentThread().setPriority(priority);
/*-------------------------------------------------
** Loop until queue is empty
*/
mShuttingDown = true;
while (mCommandQueue.isEmpty() == false) {
try {
- Thread.sleep(5 * 1000);
- //gcProcess();
+ Thread.sleep(5 * 1000);
+ // gcProcess();
} catch (Exception e) {
}
@@ -78,9 +76,9 @@ public class CommandQueue implements Runnable, ICommandQueue {
if ((currentServlet instanceof com.netscape.cms.servlet.base.CMSStartServlet) == false)
mCommandQueue.put(currentRequest, currentServlet);
return true;
- }else
+ } else
return false;
-
+
}
public void unRegisterProccess(Object currentRequest, Object currentServlet) {
@@ -88,13 +86,13 @@ public class CommandQueue implements Runnable, ICommandQueue {
while (e.hasMoreElements()) {
Object thisRequest = e.nextElement();
-
+
if (thisRequest.equals(currentRequest)) {
if (mCommandQueue.get(currentRequest).equals(currentServlet))
mCommandQueue.remove(currentRequest);
}
}
-
+
}
} // CommandQueue
diff --git a/pki/base/common/src/com/netscape/cmscore/apps/PKIServerEvent.java b/pki/base/common/src/com/netscape/cmscore/apps/PKIServerEvent.java
index 27d2e3f7..e815a994 100644
--- a/pki/base/common/src/com/netscape/cmscore/apps/PKIServerEvent.java
+++ b/pki/base/common/src/com/netscape/cmscore/apps/PKIServerEvent.java
@@ -17,11 +17,10 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.apps;
-
/**
* A class represents a PKIServer event.
* <P>
- *
+ *
* @author thomask
* @version $Revision$, $Date$
*/
diff --git a/pki/base/common/src/com/netscape/cmscore/apps/PKIServerListener.java b/pki/base/common/src/com/netscape/cmscore/apps/PKIServerListener.java
index 78fe9069..d461ed21 100644
--- a/pki/base/common/src/com/netscape/cmscore/apps/PKIServerListener.java
+++ b/pki/base/common/src/com/netscape/cmscore/apps/PKIServerListener.java
@@ -17,12 +17,10 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.apps;
-
/**
- * A class represents a listener that listens to
- * PKIServer event.
+ * A class represents a listener that listens to PKIServer event.
* <P>
- *
+ *
* @author thomask
* @version $Revision$, $Date$
*/
diff --git a/pki/base/common/src/com/netscape/cmscore/apps/Setup.java b/pki/base/common/src/com/netscape/cmscore/apps/Setup.java
index 3eb897cc..c46f113f 100644
--- a/pki/base/common/src/com/netscape/cmscore/apps/Setup.java
+++ b/pki/base/common/src/com/netscape/cmscore/apps/Setup.java
@@ -17,14 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.apps;
-
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
-
/**
* Select certificate server serices.
- *
+ *
* @author thomask
* @author nicolson
* @version $Revision$, $Date$
@@ -34,52 +32,53 @@ public class Setup {
// These are a bunch of fixed values that just need to be stored to the
// config file before the server is started.
public static final String[][] authEntries = new String[][] {
- {"auths._000", "##"},
- {"auths._001", "## new authentication"},
- {"auths._002", "##"},
- {"auths.impl._000", "##"},
- {"auths.impl._001", "## authentication manager implementations"},
- {"auths.impl._002", "##"},
- {"auths.impl.UidPwdDirAuth.class", "com.netscape.cms.authentication.UidPwdDirAuthentication"},
- {"auths.impl.UidPwdPinDirAuth.class", "com.netscape.cms.authentication.UidPwdPinDirAuthentication"},
- {"auths.impl.UdnPwdDirAuth.class", "com.netscape.cms.authentication.UdnPwdDirAuthentication"},
- {"auths.impl.NISAuth.class", "com.netscape.cms.authentication.NISAuth"},
- {"auths.impl.CMCAuth.class", "com.netscape.cms.authentication.CMCAuth"},
- {"auths.impl.AgentCertAuth.class", "com.netscape.cms.authentication.AgentCertAuthentication"},
- {"auths.impl.PortalEnroll.class", "com.netscape.cms.authentication.PortalEnroll"
+ { "auths._000", "##" },
+ { "auths._001", "## new authentication" },
+ { "auths._002", "##" },
+ { "auths.impl._000", "##" },
+ { "auths.impl._001", "## authentication manager implementations" },
+ { "auths.impl._002", "##" },
+ { "auths.impl.UidPwdDirAuth.class", "com.netscape.cms.authentication.UidPwdDirAuthentication" },
+ { "auths.impl.UidPwdPinDirAuth.class", "com.netscape.cms.authentication.UidPwdPinDirAuthentication" },
+ { "auths.impl.UdnPwdDirAuth.class", "com.netscape.cms.authentication.UdnPwdDirAuthentication" },
+ { "auths.impl.NISAuth.class", "com.netscape.cms.authentication.NISAuth" },
+ { "auths.impl.CMCAuth.class", "com.netscape.cms.authentication.CMCAuth" },
+ { "auths.impl.AgentCertAuth.class", "com.netscape.cms.authentication.AgentCertAuthentication" },
+ { "auths.impl.PortalEnroll.class", "com.netscape.cms.authentication.PortalEnroll"
},
- {"auths.revocationChecking.bufferSize", "50"},
+ { "auths.revocationChecking.bufferSize", "50" },
};
+
public static void installAuthImpls(IConfigStore c)
- throws EBaseException {
+ throws EBaseException {
for (int i = 0; i < authEntries.length; i++) {
c.putString(authEntries[i][0], authEntries[i][1]);
}
}
public static final String[][] oidmapEntries = new String[][] {
- {"oidmap.pse.class", "netscape.security.extensions.PresenceServerExtension"},
- {"oidmap.pse.oid", "2.16.840.1.113730.1.18"},
- {"oidmap.ocsp_no_check.class", "netscape.security.extensions.OCSPNoCheckExtension"},
- {"oidmap.ocsp_no_check.oid", "1.3.6.1.5.5.7.48.1.5"},
- {"oidmap.netscape_comment.class", "netscape.security.x509.NSCCommentExtension"},
- {"oidmap.netscape_comment.oid", "2.16.840.1.113730.1.13"},
- {"oidmap.extended_key_usage.class", "netscape.security.extensions.ExtendedKeyUsageExtension"},
- {"oidmap.extended_key_usage.oid", "2.5.29.37"},
- {"oidmap.subject_info_access.class", "netscape.security.extensions.SubjectInfoAccessExtension"},
- {"oidmap.subject_info_access.oid", "1.3.6.1.5.5.7.1.11"},
- {"oidmap.auth_info_access.class", "netscape.security.extensions.AuthInfoAccessExtension"},
- {"oidmap.auth_info_access.oid", "1.3.6.1.5.5.7.1.1"},
- {"oidmap.challenge_password.class", "com.netscape.cms.servlet.cert.scep.ChallengePassword"},
- {"oidmap.challenge_password.oid", "1.2.840.113549.1.9.7"},
- {"oidmap.extensions_requested_vsgn.class", "com.netscape.cms.servlet.cert.scep.ExtensionsRequested"},
- {"oidmap.extensions_requested_vsgn.oid", "2.16.840.1.113733.1.9.8"},
- {"oidmap.extensions_requested_pkcs9.class", "com.netscape.cms.servlet.cert.scep.ExtensionsRequested"},
- {"oidmap.extensions_requested_pkcs9.oid", "1.2.840.113549.1.9.14"},
+ { "oidmap.pse.class", "netscape.security.extensions.PresenceServerExtension" },
+ { "oidmap.pse.oid", "2.16.840.1.113730.1.18" },
+ { "oidmap.ocsp_no_check.class", "netscape.security.extensions.OCSPNoCheckExtension" },
+ { "oidmap.ocsp_no_check.oid", "1.3.6.1.5.5.7.48.1.5" },
+ { "oidmap.netscape_comment.class", "netscape.security.x509.NSCCommentExtension" },
+ { "oidmap.netscape_comment.oid", "2.16.840.1.113730.1.13" },
+ { "oidmap.extended_key_usage.class", "netscape.security.extensions.ExtendedKeyUsageExtension" },
+ { "oidmap.extended_key_usage.oid", "2.5.29.37" },
+ { "oidmap.subject_info_access.class", "netscape.security.extensions.SubjectInfoAccessExtension" },
+ { "oidmap.subject_info_access.oid", "1.3.6.1.5.5.7.1.11" },
+ { "oidmap.auth_info_access.class", "netscape.security.extensions.AuthInfoAccessExtension" },
+ { "oidmap.auth_info_access.oid", "1.3.6.1.5.5.7.1.1" },
+ { "oidmap.challenge_password.class", "com.netscape.cms.servlet.cert.scep.ChallengePassword" },
+ { "oidmap.challenge_password.oid", "1.2.840.113549.1.9.7" },
+ { "oidmap.extensions_requested_vsgn.class", "com.netscape.cms.servlet.cert.scep.ExtensionsRequested" },
+ { "oidmap.extensions_requested_vsgn.oid", "2.16.840.1.113733.1.9.8" },
+ { "oidmap.extensions_requested_pkcs9.class", "com.netscape.cms.servlet.cert.scep.ExtensionsRequested" },
+ { "oidmap.extensions_requested_pkcs9.oid", "1.2.840.113549.1.9.14" },
};
public static void installOIDMap(IConfigStore c)
- throws EBaseException {
+ throws EBaseException {
for (int i = 0; i < oidmapEntries.length; i++) {
c.putString(oidmapEntries[i][0], oidmapEntries[i][1]);
}
@@ -89,150 +88,149 @@ public class Setup {
* This function is used for installation and upgrade.
*/
public static void installPolicyImpls(String prefix, IConfigStore c)
- throws EBaseException {
+ throws EBaseException {
boolean isCA = false;
if (prefix.equals("ca"))
isCA = true;
- //
- // Policy implementations (class names)
- //
+ //
+ // Policy implementations (class names)
+ //
c.putString(prefix + ".Policy.impl._000", "##");
c.putString(prefix + ".Policy.impl._001",
- "## Policy Implementations");
+ "## Policy Implementations");
c.putString(prefix + ".Policy.impl._002", "##");
c.putString(
- prefix + ".Policy.impl.KeyAlgorithmConstraints.class",
- "com.netscape.cmscore.policy.KeyAlgorithmConstraints");
+ prefix + ".Policy.impl.KeyAlgorithmConstraints.class",
+ "com.netscape.cmscore.policy.KeyAlgorithmConstraints");
c.putString(
- prefix + ".Policy.impl.DSAKeyConstraints.class",
- "com.netscape.cmscore.policy.DSAKeyConstraints");
+ prefix + ".Policy.impl.DSAKeyConstraints.class",
+ "com.netscape.cmscore.policy.DSAKeyConstraints");
c.putString(
- prefix + ".Policy.impl.RSAKeyConstraints.class",
- "com.netscape.cmscore.policy.RSAKeyConstraints");
+ prefix + ".Policy.impl.RSAKeyConstraints.class",
+ "com.netscape.cmscore.policy.RSAKeyConstraints");
c.putString(
- prefix + ".Policy.impl.SigningAlgorithmConstraints.class",
- "com.netscape.cmscore.policy.SigningAlgorithmConstraints");
+ prefix + ".Policy.impl.SigningAlgorithmConstraints.class",
+ "com.netscape.cmscore.policy.SigningAlgorithmConstraints");
c.putString(
- prefix + ".Policy.impl.ValidityConstraints.class",
- "com.netscape.cmscore.policy.ValidityConstraints");
+ prefix + ".Policy.impl.ValidityConstraints.class",
+ "com.netscape.cmscore.policy.ValidityConstraints");
/**
- c.putString(
- prefix + ".Policy.impl.NameConstraints.class",
- "com.netscape.cmscore.policy.NameConstraints");
+ * c.putString( prefix + ".Policy.impl.NameConstraints.class",
+ * "com.netscape.cmscore.policy.NameConstraints");
**/
c.putString(
- prefix + ".Policy.impl.RenewalConstraints.class",
- "com.netscape.cmscore.policy.RenewalConstraints");
+ prefix + ".Policy.impl.RenewalConstraints.class",
+ "com.netscape.cmscore.policy.RenewalConstraints");
c.putString(
- prefix + ".Policy.impl.RenewalValidityConstraints.class",
- "com.netscape.cmscore.policy.RenewalValidityConstraints");
+ prefix + ".Policy.impl.RenewalValidityConstraints.class",
+ "com.netscape.cmscore.policy.RenewalValidityConstraints");
c.putString(
- prefix + ".Policy.impl.RevocationConstraints.class",
- "com.netscape.cmscore.policy.RevocationConstraints");
- //getTempCMSConfig().putString(
- // prefix + ".Policy.impl.DefaultRevocation.class",
- // "com.netscape.cmscore.policy.DefaultRevocation");
+ prefix + ".Policy.impl.RevocationConstraints.class",
+ "com.netscape.cmscore.policy.RevocationConstraints");
+ // getTempCMSConfig().putString(
+ // prefix + ".Policy.impl.DefaultRevocation.class",
+ // "com.netscape.cmscore.policy.DefaultRevocation");
c.putString(
- prefix + ".Policy.impl.NSCertTypeExt.class",
- "com.netscape.cmscore.policy.NSCertTypeExt");
+ prefix + ".Policy.impl.NSCertTypeExt.class",
+ "com.netscape.cmscore.policy.NSCertTypeExt");
c.putString(
- prefix + ".Policy.impl.KeyUsageExt.class",
- "com.netscape.cmscore.policy.KeyUsageExt");
+ prefix + ".Policy.impl.KeyUsageExt.class",
+ "com.netscape.cmscore.policy.KeyUsageExt");
c.putString(
- prefix + ".Policy.impl.SubjectKeyIdentifierExt.class",
- "com.netscape.cmscore.policy.SubjectKeyIdentifierExt");
+ prefix + ".Policy.impl.SubjectKeyIdentifierExt.class",
+ "com.netscape.cmscore.policy.SubjectKeyIdentifierExt");
c.putString(
- prefix + ".Policy.impl.CertificatePoliciesExt.class",
- "com.netscape.cmscore.policy.CertificatePoliciesExt");
+ prefix + ".Policy.impl.CertificatePoliciesExt.class",
+ "com.netscape.cmscore.policy.CertificatePoliciesExt");
c.putString(
- prefix + ".Policy.impl.NSCCommentExt.class",
- "com.netscape.cmscore.policy.NSCCommentExt");
+ prefix + ".Policy.impl.NSCCommentExt.class",
+ "com.netscape.cmscore.policy.NSCCommentExt");
c.putString(
- prefix + ".Policy.impl.IssuerAltNameExt.class",
- "com.netscape.cmscore.policy.IssuerAltNameExt");
+ prefix + ".Policy.impl.IssuerAltNameExt.class",
+ "com.netscape.cmscore.policy.IssuerAltNameExt");
c.putString(
- prefix + ".Policy.impl.PrivateKeyUsagePeriodExt.class",
- "com.netscape.cmscore.policy.PrivateKeyUsagePeriodExt");
+ prefix + ".Policy.impl.PrivateKeyUsagePeriodExt.class",
+ "com.netscape.cmscore.policy.PrivateKeyUsagePeriodExt");
c.putString(
- prefix + ".Policy.impl.AttributePresentConstraints.class",
- "com.netscape.cmscore.policy.AttributePresentConstraints");
+ prefix + ".Policy.impl.AttributePresentConstraints.class",
+ "com.netscape.cmscore.policy.AttributePresentConstraints");
c.putString(
- prefix + ".Policy.impl.SubjectAltNameExt.class",
- "com.netscape.cmscore.policy.SubjectAltNameExt");
+ prefix + ".Policy.impl.SubjectAltNameExt.class",
+ "com.netscape.cmscore.policy.SubjectAltNameExt");
c.putString(
- prefix + ".Policy.impl.SubjectDirectoryAttributesExt.class",
- "com.netscape.cmscore.policy.SubjectDirectoryAttributesExt");
+ prefix + ".Policy.impl.SubjectDirectoryAttributesExt.class",
+ "com.netscape.cmscore.policy.SubjectDirectoryAttributesExt");
c.putString(
- prefix + ".Policy.impl.CertificateRenewalWindowExt.class",
- "com.netscape.cmscore.policy.CertificateRenewalWindowExt");
+ prefix + ".Policy.impl.CertificateRenewalWindowExt.class",
+ "com.netscape.cmscore.policy.CertificateRenewalWindowExt");
c.putString(
- prefix + ".Policy.impl.CertificateScopeOfUseExt.class",
- "com.netscape.cmscore.policy.CertificateScopeOfUseExt");
+ prefix + ".Policy.impl.CertificateScopeOfUseExt.class",
+ "com.netscape.cmscore.policy.CertificateScopeOfUseExt");
if (isCA) {
c.putString(
- prefix + ".Policy.impl.AuthorityKeyIdentifierExt.class",
- "com.netscape.cmscore.policy.AuthorityKeyIdentifierExt");
+ prefix + ".Policy.impl.AuthorityKeyIdentifierExt.class",
+ "com.netscape.cmscore.policy.AuthorityKeyIdentifierExt");
c.putString(
- prefix + ".Policy.impl.BasicConstraintsExt.class",
- "com.netscape.cmscore.policy.BasicConstraintsExt");
+ prefix + ".Policy.impl.BasicConstraintsExt.class",
+ "com.netscape.cmscore.policy.BasicConstraintsExt");
c.putString(
- prefix + ".Policy.impl.SubCANameConstraints.class",
- "com.netscape.cmscore.policy.SubCANameConstraints");
+ prefix + ".Policy.impl.SubCANameConstraints.class",
+ "com.netscape.cmscore.policy.SubCANameConstraints");
}
c.putString(
- prefix + ".Policy.impl.CRLDistributionPointsExt.class",
- "com.netscape.cmscore.policy.CRLDistributionPointsExt");
+ prefix + ".Policy.impl.CRLDistributionPointsExt.class",
+ "com.netscape.cmscore.policy.CRLDistributionPointsExt");
c.putString(
- prefix + ".Policy.impl.AuthInfoAccessExt.class",
- "com.netscape.cmscore.policy.AuthInfoAccessExt");
+ prefix + ".Policy.impl.AuthInfoAccessExt.class",
+ "com.netscape.cmscore.policy.AuthInfoAccessExt");
c.putString(
- prefix + ".Policy.impl.OCSPNoCheckExt.class",
- "com.netscape.cmscore.policy.OCSPNoCheckExt");
+ prefix + ".Policy.impl.OCSPNoCheckExt.class",
+ "com.netscape.cmscore.policy.OCSPNoCheckExt");
c.putString(
- prefix + ".Policy.impl.ExtendedKeyUsageExt.class",
- "com.netscape.cmscore.policy.ExtendedKeyUsageExt");
+ prefix + ".Policy.impl.ExtendedKeyUsageExt.class",
+ "com.netscape.cmscore.policy.ExtendedKeyUsageExt");
if (isCA) {
c.putString(
- prefix + ".Policy.impl.UniqueSubjectNameConstraints.class",
- "com.netscape.cmscore.policy.UniqueSubjectNameConstraints");
+ prefix + ".Policy.impl.UniqueSubjectNameConstraints.class",
+ "com.netscape.cmscore.policy.UniqueSubjectNameConstraints");
}
c.putString(
- prefix + ".Policy.impl.GenericASN1Ext.class",
- "com.netscape.cmscore.policy.GenericASN1Ext");
+ prefix + ".Policy.impl.GenericASN1Ext.class",
+ "com.netscape.cmscore.policy.GenericASN1Ext");
c.putString(
- prefix + ".Policy.impl.RemoveBasicConstraintsExt.class",
- "com.netscape.cmscore.policy.RemoveBasicConstraintsExt");
+ prefix + ".Policy.impl.RemoveBasicConstraintsExt.class",
+ "com.netscape.cmscore.policy.RemoveBasicConstraintsExt");
}
/**
* This function is used for installation and upgrade.
*/
public static void installCACRLExtensions(IConfigStore c)
- throws EBaseException {
+ throws EBaseException {
// ca crl extensions
// AuthorityKeyIdentifier
c.putString("ca.crl.MasterCRL.extension.AuthorityKeyIdentifier.enable",
- "false");
+ "false");
c.putString("ca.crl.MasterCRL.extension.AuthorityKeyIdentifier.critical",
- "false");
+ "false");
c.putString("ca.crl.MasterCRL.extension.AuthorityKeyIdentifier.type",
- "CRLExtension");
+ "CRLExtension");
c.putString("ca.crl.MasterCRL.extension.AuthorityKeyIdentifier.class",
- "com.netscape.cms.crl.CMSAuthorityKeyIdentifierExtension");
+ "com.netscape.cms.crl.CMSAuthorityKeyIdentifierExtension");
// IssuerAlternativeName
c.putString("ca.crl.MasterCRL.extension.IssuerAlternativeName.enable",
- "false");
+ "false");
c.putString("ca.crl.MasterCRL.extension.IssuerAlternativeName.critical",
- "false");
+ "false");
c.putString("ca.crl.MasterCRL.extension.IssuerAlternativeName.type",
- "CRLExtension");
+ "CRLExtension");
c.putString("ca.crl.MasterCRL.extension.IssuerAlternativeName.class",
- "com.netscape.cms.crl.CMSIssuerAlternativeNameExtension");
+ "com.netscape.cms.crl.CMSIssuerAlternativeNameExtension");
c.putString("ca.crl.MasterCRL.extension.IssuerAlternativeName.numNames", "0");
c.putString("ca.crl.MasterCRL.extension.IssuerAlternativeName.nameType0", "");
c.putString("ca.crl.MasterCRL.extension.IssuerAlternativeName.name0", "");
@@ -242,48 +240,48 @@ public class Setup {
c.putString("ca.crl.MasterCRL.extension.CRLNumber.critical", "false");
c.putString("ca.crl.MasterCRL.extension.CRLNumber.type", "CRLExtension");
c.putString("ca.crl.MasterCRL.extension.CRLNumber.class",
- "com.netscape.cms.crl.CMSCRLNumberExtension");
+ "com.netscape.cms.crl.CMSCRLNumberExtension");
// DeltaCRLIndicator
c.putString("ca.crl.MasterCRL.extension.DeltaCRLIndicator.enable", "false");
c.putString("ca.crl.MasterCRL.extension.DeltaCRLIndicator.critical", "true");
c.putString("ca.crl.MasterCRL.extension.DeltaCRLIndicator.type", "CRLExtension");
c.putString("ca.crl.MasterCRL.extension.DeltaCRLIndicator.class",
- "com.netscape.cms.crl.CMSDeltaCRLIndicatorExtension");
+ "com.netscape.cms.crl.CMSDeltaCRLIndicatorExtension");
// IssuingDistributionPoint
c.putString("ca.crl.MasterCRL.extension.IssuingDistributionPoint.enable",
- "false");
+ "false");
c.putString("ca.crl.MasterCRL.extension.IssuingDistributionPoint.critical",
- "true");
+ "true");
c.putString("ca.crl.MasterCRL.extension.IssuingDistributionPoint.type",
- "CRLExtension");
+ "CRLExtension");
c.putString("ca.crl.MasterCRL.extension.IssuingDistributionPoint.class",
- "com.netscape.cms.crl.CMSIssuingDistributionPointExtension");
+ "com.netscape.cms.crl.CMSIssuingDistributionPointExtension");
c.putString("ca.crl.MasterCRL.extension.IssuingDistributionPoint.pointType", "");
c.putString("ca.crl.MasterCRL.extension.IssuingDistributionPoint.pointName", "");
c.putString("ca.crl.MasterCRL.extension.IssuingDistributionPoint.onlyContainsUserCerts",
- "false");
+ "false");
c.putString("ca.crl.MasterCRL.extension.IssuingDistributionPoint.onlyContainsCACerts",
- "false");
+ "false");
c.putString("ca.crl.MasterCRL.extension.IssuingDistributionPoint.onlySomeReasons", "");
- //"keyCompromise,cACompromise,affiliationChanged,superseded,cessationOfOperation,certificateHold");
+ // "keyCompromise,cACompromise,affiliationChanged,superseded,cessationOfOperation,certificateHold");
c.putString("ca.crl.MasterCRL.extension.IssuingDistributionPoint.indirectCRL",
- "false");
+ "false");
// CRLReason
c.putString("ca.crl.MasterCRL.extension.CRLReason.enable", "true");
c.putString("ca.crl.MasterCRL.extension.CRLReason.critical", "false");
c.putString("ca.crl.MasterCRL.extension.CRLReason.type", "CRLEntryExtension");
c.putString("ca.crl.MasterCRL.extension.CRLReason.class",
- "com.netscape.cms.crl.CMSCRLReasonExtension");
+ "com.netscape.cms.crl.CMSCRLReasonExtension");
// HoldInstruction
c.putString("ca.crl.MasterCRL.extension.HoldInstruction.enable", "false");
c.putString("ca.crl.MasterCRL.extension.HoldInstruction.critical", "false");
c.putString("ca.crl.MasterCRL.extension.HoldInstruction.type", "CRLEntryExtension");
c.putString("ca.crl.MasterCRL.extension.HoldInstruction.class",
- "com.netscape.cms.crl.CMSHoldInstructionExtension");
+ "com.netscape.cms.crl.CMSHoldInstructionExtension");
c.putString("ca.crl.MasterCRL.extension.HoldInstruction.instruction", "none");
// InvalidityDate
@@ -291,18 +289,24 @@ public class Setup {
c.putString("ca.crl.MasterCRL.extension.InvalidityDate.critical", "false");
c.putString("ca.crl.MasterCRL.extension.InvalidityDate.type", "CRLEntryExtension");
c.putString("ca.crl.MasterCRL.extension.InvalidityDate.class",
- "com.netscape.cms.crl.CMSInvalidityDateExtension");
+ "com.netscape.cms.crl.CMSInvalidityDateExtension");
// CertificateIssuer
/*
- c.putString("ca.crl.MasterCRL.extension.CertificateIssuer.enable", "false");
- c.putString("ca.crl.MasterCRL.extension.CertificateIssuer.critical", "true");
- c.putString("ca.crl.MasterCRL.extension.CertificateIssuer.type", "CRLEntryExtension");
- c.putString("ca.crl.MasterCRL.extension.CertificateIssuer.class",
- "com.netscape.cms.crl.CMSCertificateIssuerExtension");
- c.putString("ca.crl.MasterCRL.extension.CertificateIssuer.numNames", "0");
- c.putString("ca.crl.MasterCRL.extension.CertificateIssuer.nameType0", "");
- c.putString("ca.crl.MasterCRL.extension.CertificateIssuer.name0", "");
+ * c.putString("ca.crl.MasterCRL.extension.CertificateIssuer.enable",
+ * "false");
+ * c.putString("ca.crl.MasterCRL.extension.CertificateIssuer.critical",
+ * "true");
+ * c.putString("ca.crl.MasterCRL.extension.CertificateIssuer.type",
+ * "CRLEntryExtension");
+ * c.putString("ca.crl.MasterCRL.extension.CertificateIssuer.class",
+ * "com.netscape.cms.crl.CMSCertificateIssuerExtension");
+ * c.putString("ca.crl.MasterCRL.extension.CertificateIssuer.numNames",
+ * "0");
+ * c.putString("ca.crl.MasterCRL.extension.CertificateIssuer.nameType0",
+ * "");
+ * c.putString("ca.crl.MasterCRL.extension.CertificateIssuer.name0",
+ * "");
*/
// FreshestCRL
@@ -310,34 +314,34 @@ public class Setup {
c.putString("ca.crl.MasterCRL.extension.FreshestCRL.critical", "false");
c.putString("ca.crl.MasterCRL.extension.FreshestCRL.type", "CRLExtension");
c.putString("ca.crl.MasterCRL.extension.FreshestCRL.class",
- "com.netscape.cms.crl.CMSFreshestCRLExtension");
+ "com.netscape.cms.crl.CMSFreshestCRLExtension");
c.putString("ca.crl.MasterCRL.extension.FreshestCRL.numPoints", "0");
c.putString("ca.crl.MasterCRL.extension.FreshestCRL.pointType0", "");
c.putString("ca.crl.MasterCRL.extension.FreshestCRL.pointName0", "");
}
public static void installCAPublishingImpls(IConfigStore c)
- throws EBaseException {
+ throws EBaseException {
for (int i = 0; i < caLdappublishImplsEntries.length; i++) {
c.putString(
- caLdappublishImplsEntries[i][0], caLdappublishImplsEntries[i][1]);
+ caLdappublishImplsEntries[i][0], caLdappublishImplsEntries[i][1]);
}
}
private static final String[][] caLdappublishImplsEntries = new String[][] {
- {"ca.publish.mapper.impl.LdapCaSimpleMap.class", "com.netscape.cms.publish.LdapCaSimpleMap"},
- {"ca.publish.mapper.impl.LdapSimpleMap.class", "com.netscape.cms.publish.LdapSimpleMap"},
- {"ca.publish.mapper.impl.LdapEnhancedMap.class", "com.netscape.cms.publish.LdapEnhancedMap"},
- {"ca.publish.mapper.impl.LdapDNCompsMap.class", "com.netscape.cms.publish.LdapCertCompsMap"},
- {"ca.publish.mapper.impl.LdapSubjAttrMap.class", "com.netscape.cms.publish.LdapCertSubjMap"},
- {"ca.publish.mapper.impl.LdapDNExactMap.class", "com.netscape.cms.publish.LdapCertExactMap"},
- //{"ca.publish.mapper.impl.LdapCrlIssuerCompsMap.class","com.netscape.cms.publish.LdapCrlIssuerCompsMap"},
- {"ca.publish.publisher.impl.LdapUserCertPublisher.class", "com.netscape.cms.publish.LdapUserCertPublisher"},
- {"ca.publish.publisher.impl.LdapCaCertPublisher.class", "com.netscape.cms.publish.LdapCaCertPublisher"},
- {"ca.publish.publisher.impl.LdapCrlPublisher.class", "com.netscape.cms.publish.LdapCrlPublisher"},
- {"ca.publish.publisher.impl.FileBasedPublisher.class", "com.netscape.cms.publish.FileBasedPublisher"},
- {"ca.publish.publisher.impl.OCSPPublisher.class", "com.netscape.cms.publish.OCSPPublisher"},
- {"ca.publish.rule.impl.Rule.class", "com.netscape.cmscore.ldap.LdapRule"},
+ { "ca.publish.mapper.impl.LdapCaSimpleMap.class", "com.netscape.cms.publish.LdapCaSimpleMap" },
+ { "ca.publish.mapper.impl.LdapSimpleMap.class", "com.netscape.cms.publish.LdapSimpleMap" },
+ { "ca.publish.mapper.impl.LdapEnhancedMap.class", "com.netscape.cms.publish.LdapEnhancedMap" },
+ { "ca.publish.mapper.impl.LdapDNCompsMap.class", "com.netscape.cms.publish.LdapCertCompsMap" },
+ { "ca.publish.mapper.impl.LdapSubjAttrMap.class", "com.netscape.cms.publish.LdapCertSubjMap" },
+ { "ca.publish.mapper.impl.LdapDNExactMap.class", "com.netscape.cms.publish.LdapCertExactMap" },
+ // {"ca.publish.mapper.impl.LdapCrlIssuerCompsMap.class","com.netscape.cms.publish.LdapCrlIssuerCompsMap"},
+ { "ca.publish.publisher.impl.LdapUserCertPublisher.class", "com.netscape.cms.publish.LdapUserCertPublisher" },
+ { "ca.publish.publisher.impl.LdapCaCertPublisher.class", "com.netscape.cms.publish.LdapCaCertPublisher" },
+ { "ca.publish.publisher.impl.LdapCrlPublisher.class", "com.netscape.cms.publish.LdapCrlPublisher" },
+ { "ca.publish.publisher.impl.FileBasedPublisher.class", "com.netscape.cms.publish.FileBasedPublisher" },
+ { "ca.publish.publisher.impl.OCSPPublisher.class", "com.netscape.cms.publish.OCSPPublisher" },
+ { "ca.publish.rule.impl.Rule.class", "com.netscape.cmscore.ldap.LdapRule" },
};
}
diff --git a/pki/base/common/src/com/netscape/cmscore/apps/Upgrade.java b/pki/base/common/src/com/netscape/cmscore/apps/Upgrade.java
index b77c8a7d..4fad2b4c 100644
--- a/pki/base/common/src/com/netscape/cmscore/apps/Upgrade.java
+++ b/pki/base/common/src/com/netscape/cmscore/apps/Upgrade.java
@@ -17,150 +17,147 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.apps;
-
import java.io.File;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.cmscore.util.OsSubsystem;
-
public final class Upgrade {
public static void perform422to45(IConfigStore c)
- throws EBaseException {
+ throws EBaseException {
jss3(c);
- c.putInteger("agentGateway.https.timeout", 120);
+ c.putInteger("agentGateway.https.timeout", 120);
IConfigStore cs = c.getSubStore("ca");
if (cs != null && cs.size() > 0) {
c.putString("ca.publish.mapper.impl.LdapEnhancedMap.class",
- "com.netscape.certsrv.ldap.LdapEnhancedMap");
+ "com.netscape.certsrv.ldap.LdapEnhancedMap");
}
c.putString("cms.version", "4.5");
c.commit(false);
}
public static void perform42to422(IConfigStore c)
- throws EBaseException {
+ throws EBaseException {
// upgrade CMS's configuration parameters
- c.putString("eeGateway.dynamicVariables",
- "serverdate=serverdate(),subsystemname=subsystemname(),http=http(),authmgrs=authmgrs(),clacrlurl=clacrlurl()");
+ c.putString("eeGateway.dynamicVariables",
+ "serverdate=serverdate(),subsystemname=subsystemname(),http=http(),authmgrs=authmgrs(),clacrlurl=clacrlurl()");
// new OCSP Publisher implemention
c.putString("ra.publish.publisher.impl.OCSPPublisher.class",
- "com.netscape.certsrv.ldap.OCSPPublisher");
+ "com.netscape.certsrv.ldap.OCSPPublisher");
c.putString("ca.publish.publisher.impl.OCSPPublisher.class",
- "com.netscape.certsrv.ldap.OCSPPublisher");
+ "com.netscape.certsrv.ldap.OCSPPublisher");
// new logging framework
c.putString("log.impl.file.class",
- "com.netscape.certsrv.logging.RollingLogFile");
+ "com.netscape.certsrv.logging.RollingLogFile");
- c.putString("log.instance.Audit.bufferSize",
- c.getString("logAudit.bufferSize"));
- c.putString("log.instance.Audit.enable",
- c.getString("logAudit.on"));
+ c.putString("log.instance.Audit.bufferSize",
+ c.getString("logAudit.bufferSize"));
+ c.putString("log.instance.Audit.enable",
+ c.getString("logAudit.on"));
// This feature doesnot work in the previous release
// But it works now. I don't want people to have their
// logs auto deleted without notice.It's dangerous.
- c.putString("log.instance.Audit.expirationTime",
- "0"); //Specifically turn it off.
- // c.getString("logAudit.expirationTime"));
- c.putString("log.instance.Audit.fileName",
- c.getString("logAudit.fileName"));
- c.putString("log.instance.Audit.flushInterval",
- c.getString("logAudit.flushInterval"));
- c.putString("log.instance.Audit.level",
- c.getString("logAudit.level"));
- c.putString("log.instance.Audit.maxFileSize",
- c.getString("logAudit.maxFileSize"));
- c.putString("log.instance.Audit.pluginName",
- "file");
- c.putString("log.instance.Audit.rolloverInterval",
- c.getString("logAudit.rolloverInterval"));
- c.putString("log.instance.Audit.type",
- "audit");
-
- c.putString("log.instance.Error.bufferSize",
- c.getString("logError.bufferSize"));
- c.putString("log.instance.Error.enable",
- c.getString("logError.on"));
- c.putString("log.instance.Error.expirationTime",
- "0"); //Specifically turn it off.
- // c.getString("logError.expirationTime"));
- c.putString("log.instance.Error.fileName",
- c.getString("logError.fileName"));
- c.putString("log.instance.Error.flushInterval",
- c.getString("logError.flushInterval"));
- c.putString("log.instance.Error.level",
- c.getString("logError.level"));
- c.putString("log.instance.Error.maxFileSize",
- c.getString("logError.maxFileSize"));
- c.putString("log.instance.Error.pluginName",
- "file");
- c.putString("log.instance.Error.rolloverInterval",
- c.getString("logError.rolloverInterval"));
- c.putString("log.instance.Error.type",
- "system");
-
- c.putString("log.instance.System.bufferSize",
- c.getString("logSystem.bufferSize"));
- c.putString("log.instance.System.enable",
- c.getString("logSystem.on"));
- c.putString("log.instance.System.expirationTime",
- "0"); //Specifically turn it off.
- // c.getString("logSystem.expirationTime"));
- c.putString("log.instance.System.fileName",
- c.getString("logSystem.fileName"));
- c.putString("log.instance.System.flushInterval",
- c.getString("logSystem.flushInterval"));
- c.putString("log.instance.System.level",
- c.getString("logSystem.level"));
- c.putString("log.instance.System.maxFileSize",
- c.getString("logSystem.maxFileSize"));
- c.putString("log.instance.System.pluginName",
- "file");
- c.putString("log.instance.System.rolloverInterval",
- c.getString("logSystem.rolloverInterval"));
- c.putString("log.instance.System.type",
- "system");
-
- if (!OsSubsystem.isUnix()) {
- c.putString("log.impl.NTEventLog.class",
- "com.netscape.certsrv.logging.NTEventLog");
-
- c.putString("log.instance.NTAudit.NTEventSourceName",
- c.getString("logNTAudit.NTEventSourceName"));
- c.putString("log.instance.NTAudit.enable",
- c.getString("logNTAudit.on"));
- c.putString("log.instance.NTAudit.level",
- c.getString("logNTAudit.level"));
- c.putString("log.instance.NTAudit.pluginName",
- "NTEventLog");
- c.putString("log.instance.NTAudit.type",
+ c.putString("log.instance.Audit.expirationTime",
+ "0"); // Specifically turn it off.
+ // c.getString("logAudit.expirationTime"));
+ c.putString("log.instance.Audit.fileName",
+ c.getString("logAudit.fileName"));
+ c.putString("log.instance.Audit.flushInterval",
+ c.getString("logAudit.flushInterval"));
+ c.putString("log.instance.Audit.level",
+ c.getString("logAudit.level"));
+ c.putString("log.instance.Audit.maxFileSize",
+ c.getString("logAudit.maxFileSize"));
+ c.putString("log.instance.Audit.pluginName",
+ "file");
+ c.putString("log.instance.Audit.rolloverInterval",
+ c.getString("logAudit.rolloverInterval"));
+ c.putString("log.instance.Audit.type",
+ "audit");
+
+ c.putString("log.instance.Error.bufferSize",
+ c.getString("logError.bufferSize"));
+ c.putString("log.instance.Error.enable",
+ c.getString("logError.on"));
+ c.putString("log.instance.Error.expirationTime",
+ "0"); // Specifically turn it off.
+ // c.getString("logError.expirationTime"));
+ c.putString("log.instance.Error.fileName",
+ c.getString("logError.fileName"));
+ c.putString("log.instance.Error.flushInterval",
+ c.getString("logError.flushInterval"));
+ c.putString("log.instance.Error.level",
+ c.getString("logError.level"));
+ c.putString("log.instance.Error.maxFileSize",
+ c.getString("logError.maxFileSize"));
+ c.putString("log.instance.Error.pluginName",
+ "file");
+ c.putString("log.instance.Error.rolloverInterval",
+ c.getString("logError.rolloverInterval"));
+ c.putString("log.instance.Error.type",
"system");
- c.putString("log.instance.NTSystem.NTEventSourceName",
- c.getString("logNTSystem.NTEventSourceName"));
- c.putString("log.instance.NTSystem.enable",
- c.getString("logNTSystem.on"));
- c.putString("log.instance.NTSystem.level",
- c.getString("logNTSystem.level"));
- c.putString("log.instance.NTSystem.pluginName",
- "NTEventLog");
- c.putString("log.instance.NTSystem.type",
+ c.putString("log.instance.System.bufferSize",
+ c.getString("logSystem.bufferSize"));
+ c.putString("log.instance.System.enable",
+ c.getString("logSystem.on"));
+ c.putString("log.instance.System.expirationTime",
+ "0"); // Specifically turn it off.
+ // c.getString("logSystem.expirationTime"));
+ c.putString("log.instance.System.fileName",
+ c.getString("logSystem.fileName"));
+ c.putString("log.instance.System.flushInterval",
+ c.getString("logSystem.flushInterval"));
+ c.putString("log.instance.System.level",
+ c.getString("logSystem.level"));
+ c.putString("log.instance.System.maxFileSize",
+ c.getString("logSystem.maxFileSize"));
+ c.putString("log.instance.System.pluginName",
+ "file");
+ c.putString("log.instance.System.rolloverInterval",
+ c.getString("logSystem.rolloverInterval"));
+ c.putString("log.instance.System.type",
"system");
+
+ if (!OsSubsystem.isUnix()) {
+ c.putString("log.impl.NTEventLog.class",
+ "com.netscape.certsrv.logging.NTEventLog");
+
+ c.putString("log.instance.NTAudit.NTEventSourceName",
+ c.getString("logNTAudit.NTEventSourceName"));
+ c.putString("log.instance.NTAudit.enable",
+ c.getString("logNTAudit.on"));
+ c.putString("log.instance.NTAudit.level",
+ c.getString("logNTAudit.level"));
+ c.putString("log.instance.NTAudit.pluginName",
+ "NTEventLog");
+ c.putString("log.instance.NTAudit.type",
+ "system");
+
+ c.putString("log.instance.NTSystem.NTEventSourceName",
+ c.getString("logNTSystem.NTEventSourceName"));
+ c.putString("log.instance.NTSystem.enable",
+ c.getString("logNTSystem.on"));
+ c.putString("log.instance.NTSystem.level",
+ c.getString("logNTSystem.level"));
+ c.putString("log.instance.NTSystem.pluginName",
+ "NTEventLog");
+ c.putString("log.instance.NTSystem.type",
+ "system");
}
c.putString("cms.version", "4.22");
c.commit(false);
}
/**
- * This method handles pre4.2 -> 4.2 configuration
- * upgrade.
+ * This method handles pre4.2 -> 4.2 configuration upgrade.
*/
public static void perform(IConfigStore c)
- throws EBaseException {
+ throws EBaseException {
boolean isCA = false;
boolean isRA = false;
boolean isKRA = false;
@@ -195,8 +192,8 @@ public final class Upgrade {
Setup.installPolicyImpls("ra", c);
}
- c.putString("eeGateway.dynamicVariables",
- "serverdate=serverdate(),subsystemname=subsystemname(),http=http(),authmgrs=authmgrs()");
+ c.putString("eeGateway.dynamicVariables",
+ "serverdate=serverdate(),subsystemname=subsystemname(),http=http(),authmgrs=authmgrs()");
c.putString("cms.version", "4.2");
// Assumed user backups (including CMS.cfg) the system before
@@ -205,56 +202,56 @@ public final class Upgrade {
}
/**
- * Upgrade publishing. This function upgrades both enabled
- * or disabled publishing configuration.
+ * Upgrade publishing. This function upgrades both enabled or disabled
+ * publishing configuration.
*/
public static void caPublishing(IConfigStore c)
- throws EBaseException {
- c.putString("ca.publish.enable",
- c.getString("ca.enableLdapPublish", "false"));
- c.putString("ca.publish.ldappublish.enable",
- c.getString("ca.enableLdapPublish", "false"));
- c.putString("ca.publish.ldappublish.ldap.ldapauth.authtype",
- c.getString("ca.ldappublish.ldap.ldapauth.authtype", "BasicAuth"));
- c.putString("ca.publish.ldappublish.ldap.ldapauth.bindDN",
- c.getString("ca.ldappublish.ldap.ldapauth.bindDN", ""));
- c.putString("ca.publish.ldappublish.ldap.ldapauth.bindPWPrompt",
- c.getString("ca.ldappublish.ldap.ldapauth.bindPWPrompt", "LDAP Publishing"));
- c.putString("ca.publish.ldappublish.ldap.ldapconn.host",
- c.getString("ca.ldappublish.ldap.ldapconn.host", ""));
- c.putString("ca.publish.ldappublish.ldap.ldapconn.port",
- c.getString("ca.ldappublish.ldap.ldapconn.port", ""));
- c.putString("ca.publish.ldappublish.ldap.ldapconn.secureConn",
- c.getString("ca.ldappublish.ldap.ldapconn.secureConn", "false"));
- c.putString("ca.publish.ldappublish.ldap.ldapconn.version",
- c.getString("ca.ldappublish.ldap.ldapconn.version", "2"));
+ throws EBaseException {
+ c.putString("ca.publish.enable",
+ c.getString("ca.enableLdapPublish", "false"));
+ c.putString("ca.publish.ldappublish.enable",
+ c.getString("ca.enableLdapPublish", "false"));
+ c.putString("ca.publish.ldappublish.ldap.ldapauth.authtype",
+ c.getString("ca.ldappublish.ldap.ldapauth.authtype", "BasicAuth"));
+ c.putString("ca.publish.ldappublish.ldap.ldapauth.bindDN",
+ c.getString("ca.ldappublish.ldap.ldapauth.bindDN", ""));
+ c.putString("ca.publish.ldappublish.ldap.ldapauth.bindPWPrompt",
+ c.getString("ca.ldappublish.ldap.ldapauth.bindPWPrompt", "LDAP Publishing"));
+ c.putString("ca.publish.ldappublish.ldap.ldapconn.host",
+ c.getString("ca.ldappublish.ldap.ldapconn.host", ""));
+ c.putString("ca.publish.ldappublish.ldap.ldapconn.port",
+ c.getString("ca.ldappublish.ldap.ldapconn.port", ""));
+ c.putString("ca.publish.ldappublish.ldap.ldapconn.secureConn",
+ c.getString("ca.ldappublish.ldap.ldapconn.secureConn", "false"));
+ c.putString("ca.publish.ldappublish.ldap.ldapconn.version",
+ c.getString("ca.ldappublish.ldap.ldapconn.version", "2"));
// mappers
- c.putString("ca.publish.mapper.instance.LdapCaCertMap.pluginName",
- "LdapDNCompsMap");
- c.putString("ca.publish.mapper.instance.LdapCaCertMap.dnComps",
- c.getString("ca.ldappublish.type.ca.mapper.dnComps"));
- c.putString("ca.publish.mapper.instance.LdapCaCertMap.filterComps",
- c.getString("ca.ldappublish.type.ca.mapper.filterComps"));
- c.putString("ca.publish.mapper.instance.LdapCaCertMap.baseDN",
- c.getString("ca.ldappublish.type.ca.mapper.baseDN"));
-
- c.putString("ca.publish.mapper.instance.LdapCrlMap.pluginName",
- "LdapDNCompsMap");
- c.putString("ca.publish.mapper.instance.LdapCrlMap.dnComps",
- c.getString("ca.ldappublish.type.crl.mapper.dnComps"));
- c.putString("ca.publish.mapper.instance.LdapCrlMap.filterComps",
- c.getString("ca.ldappublish.type.crl.mapper.filterComps"));
- c.putString("ca.publish.mapper.instance.LdapCrlMap.baseDN",
- c.getString("ca.ldappublish.type.crl.mapper.baseDN"));
- c.putString("ca.publish.mapper.instance.LdapUserCertMap.pluginName",
- "LdapDNCompsMap");
+ c.putString("ca.publish.mapper.instance.LdapCaCertMap.pluginName",
+ "LdapDNCompsMap");
+ c.putString("ca.publish.mapper.instance.LdapCaCertMap.dnComps",
+ c.getString("ca.ldappublish.type.ca.mapper.dnComps"));
+ c.putString("ca.publish.mapper.instance.LdapCaCertMap.filterComps",
+ c.getString("ca.ldappublish.type.ca.mapper.filterComps"));
+ c.putString("ca.publish.mapper.instance.LdapCaCertMap.baseDN",
+ c.getString("ca.ldappublish.type.ca.mapper.baseDN"));
+
+ c.putString("ca.publish.mapper.instance.LdapCrlMap.pluginName",
+ "LdapDNCompsMap");
+ c.putString("ca.publish.mapper.instance.LdapCrlMap.dnComps",
+ c.getString("ca.ldappublish.type.crl.mapper.dnComps"));
+ c.putString("ca.publish.mapper.instance.LdapCrlMap.filterComps",
+ c.getString("ca.ldappublish.type.crl.mapper.filterComps"));
+ c.putString("ca.publish.mapper.instance.LdapCrlMap.baseDN",
+ c.getString("ca.ldappublish.type.crl.mapper.baseDN"));
+ c.putString("ca.publish.mapper.instance.LdapUserCertMap.pluginName",
+ "LdapDNCompsMap");
c.putString("ca.publish.mapper.instance.LdapUserCertMap.dnComps",
- c.getString("ca.ldappublish.type.client.mapper.dnComps"));
+ c.getString("ca.ldappublish.type.client.mapper.dnComps"));
c.putString("ca.publish.mapper.instance.LdapUserCertMap.filterComps",
- c.getString("ca.ldappublish.type.client.mapper.filterComps"));
+ c.getString("ca.ldappublish.type.client.mapper.filterComps"));
c.putString("ca.publish.mapper.instance.LdapUserCertMap.baseDN",
- c.getString("ca.ldappublish.type.client.mapper.baseDN"));
+ c.getString("ca.ldappublish.type.client.mapper.baseDN"));
// publishers
c.putString("ca.publish.publisher.instance.LdapCaCertPublisher.caCertAttr", "caCertificate;binary");
@@ -266,51 +263,52 @@ public final class Upgrade {
c.putString("ca.publish.publisher.instance.LdapUserCertPublisher.pluginName", "LdapUserCertPublisher");
// rules
- c.putString("ca.publish.rule.instance.LdapCaCertRule.pluginName ",
- "Rule");
- c.putString("ca.publish.rule.instance.LdapCaCertRule.predicate",
- "");
- c.putString("ca.publish.rule.instance.LdapCaCertRule.publisher",
- "LdapCaCertPublisher");
- c.putString("ca.publish.rule.instance.LdapCaCertRule.type",
- "cacert");
- c.putString("ca.publish.rule.instance.LdapCaCertRule.enable",
- "true");
- c.putString("ca.publish.rule.instance.LdapCaCertRule.mapper",
- "LdapCaCertMap");
-
- c.putString("ca.publish.rule.instance.LdapCrlRule.pluginName",
- "Rule");
+ c.putString("ca.publish.rule.instance.LdapCaCertRule.pluginName ",
+ "Rule");
+ c.putString("ca.publish.rule.instance.LdapCaCertRule.predicate",
+ "");
+ c.putString("ca.publish.rule.instance.LdapCaCertRule.publisher",
+ "LdapCaCertPublisher");
+ c.putString("ca.publish.rule.instance.LdapCaCertRule.type",
+ "cacert");
+ c.putString("ca.publish.rule.instance.LdapCaCertRule.enable",
+ "true");
+ c.putString("ca.publish.rule.instance.LdapCaCertRule.mapper",
+ "LdapCaCertMap");
+
+ c.putString("ca.publish.rule.instance.LdapCrlRule.pluginName",
+ "Rule");
c.putString("ca.publish.rule.instance.LdapCrlRule.predicate", "");
- c.putString("ca.publish.rule.instance.LdapCrlRule.publisher",
- "LdapCrlPublisher");
+ c.putString("ca.publish.rule.instance.LdapCrlRule.publisher",
+ "LdapCrlPublisher");
c.putString("ca.publish.rule.instance.LdapCrlRule.type", "crl");
c.putString("ca.publish.rule.instance.LdapCrlRule.enable", "true");
- c.putString("ca.publish.rule.instance.LdapCrlRule.mapper",
- "LdapCrlMap");
+ c.putString("ca.publish.rule.instance.LdapCrlRule.mapper",
+ "LdapCrlMap");
- c.putString("ca.publish.rule.instance.LdapUserCertRule.pluginName",
- "Rule");
+ c.putString("ca.publish.rule.instance.LdapUserCertRule.pluginName",
+ "Rule");
c.putString("ca.publish.rule.instance.LdapUserCertRule.predicate", "");
- c.putString("ca.publish.rule.instance.LdapUserCertRule.publisher",
- "LdapUserCertPublisher");
+ c.putString("ca.publish.rule.instance.LdapUserCertRule.publisher",
+ "LdapUserCertPublisher");
c.putString("ca.publish.rule.instance.LdapUserCertRule.type", "certs");
c.putString("ca.publish.rule.instance.LdapUserCertRule.enable", "true");
- c.putString("ca.publish.rule.instance.LdapUserCertRule.mapper",
- "LdapUserCertMap");
+ c.putString("ca.publish.rule.instance.LdapUserCertRule.mapper",
+ "LdapUserCertMap");
c.removeSubStore("ca.ldappublish");
}
/**
- * Upgrade publishing. This function upgrades both enabled
- * or disabled publishing configuration.
+ * Upgrade publishing. This function upgrades both enabled or disabled
+ * publishing configuration.
*/
public static void jss3(IConfigStore c)
- throws EBaseException {
+ throws EBaseException {
String moddb = c.getString("jss.moddb");
- if (moddb == null) return;
+ if (moddb == null)
+ return;
int i = moddb.lastIndexOf("/");
String dir = moddb.substring(0, i);
@@ -322,7 +320,7 @@ public final class Upgrade {
i = certdb.lastIndexOf("/");
String instID = certdb.substring(i + 1);
String certPrefix = ".." + File.separator + ".." + File.separator + instID +
- File.separator + "config" + File.separator;
+ File.separator + "config" + File.separator;
String keyPrefix = certPrefix;
c.putString("jss.certPrefix", certPrefix.replace('\\', '/'));
diff --git a/pki/base/common/src/com/netscape/cmscore/authentication/AuthSubsystem.java b/pki/base/common/src/com/netscape/cmscore/authentication/AuthSubsystem.java
index 252d69d6..8f4e3734 100644
--- a/pki/base/common/src/com/netscape/cmscore/authentication/AuthSubsystem.java
+++ b/pki/base/common/src/com/netscape/cmscore/authentication/AuthSubsystem.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.authentication;
-
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
@@ -40,11 +39,10 @@ import com.netscape.certsrv.base.ISubsystem;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.cmscore.util.Debug;
-
/**
* Default authentication subsystem
* <P>
- *
+ *
* @author cfu
* @author lhsiao
* @version $Revision$, $Date$
@@ -73,29 +71,30 @@ public class AuthSubsystem implements IAuthSubsystem {
}
/**
- * Initializes the authentication subsystem from the config store.
- * Load Authentication manager plugins, create and initialize
- * initialize authentication manager instances.
+ * Initializes the authentication subsystem from the config store. Load
+ * Authentication manager plugins, create and initialize initialize
+ * authentication manager instances.
+ *
* @param owner The owner of this module.
* @param config The configuration store.
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
try {
mLogger = CMS.getLogger();
mConfig = config;
-
- // hardcode admin and agent plugins required for the server to be
+
+ // hardcode admin and agent plugins required for the server to be
// functional.
AuthMgrPlugin newPlugin = null;
- newPlugin = new AuthMgrPlugin(PASSWDUSERDB_PLUGIN_ID,
+ newPlugin = new AuthMgrPlugin(PASSWDUSERDB_PLUGIN_ID,
PasswdUserDBAuthentication.class.getName());
newPlugin.setVisible(false);
mAuthMgrPlugins.put(PASSWDUSERDB_PLUGIN_ID, newPlugin);
- newPlugin = new AuthMgrPlugin(CERTUSERDB_PLUGIN_ID,
+ newPlugin = new AuthMgrPlugin(CERTUSERDB_PLUGIN_ID,
CertUserDBAuthentication.class.getName());
newPlugin.setVisible(false);
mAuthMgrPlugins.put(CERTUSERDB_PLUGIN_ID, newPlugin);
@@ -106,12 +105,12 @@ public class AuthSubsystem implements IAuthSubsystem {
mAuthMgrPlugins.put(CHALLENGE_PLUGIN_ID, newPlugin);
// Bugscape #56659
- // Removed NullAuthMgr to harden CMS. Otherwise,
- // any request submitted for nullAuthMgr will
- // be approved automatically
+ // Removed NullAuthMgr to harden CMS. Otherwise,
+ // any request submitted for nullAuthMgr will
+ // be approved automatically
//
// newPlugin = new AuthMgrPlugin(NULL_PLUGIN_ID,
- // NullAuthentication.class.getName());
+ // NullAuthentication.class.getName());
// newPlugin.setVisible(false);
// mAuthMgrPlugins.put(NULL_PLUGIN_ID, newPlugin);
@@ -128,7 +127,7 @@ public class AuthSubsystem implements IAuthSubsystem {
while (mImpls.hasMoreElements()) {
String id = (String) mImpls.nextElement();
String pluginPath = c.getString(id + "." + PROP_CLASS);
-
+
AuthMgrPlugin plugin = new AuthMgrPlugin(id, pluginPath);
mAuthMgrPlugins.put(id, plugin);
@@ -143,8 +142,8 @@ public class AuthSubsystem implements IAuthSubsystem {
IAuthManager passwdUserDBAuth = new PasswdUserDBAuthentication();
passwdUserDBAuth.init(PASSWDUSERDB_AUTHMGR_ID, PASSWDUSERDB_PLUGIN_ID, null);
- mAuthMgrInsts.put(PASSWDUSERDB_AUTHMGR_ID, new
- AuthManagerProxy(true, passwdUserDBAuth));
+ mAuthMgrInsts.put(PASSWDUSERDB_AUTHMGR_ID, new
+ AuthManagerProxy(true, passwdUserDBAuth));
if (Debug.ON) {
Debug.trace("loaded password based auth manager");
}
@@ -164,7 +163,7 @@ public class AuthSubsystem implements IAuthSubsystem {
if (Debug.ON) {
Debug.trace("loaded challenge phrase auth manager");
}
-
+
IAuthManager cmcAuth = new com.netscape.cms.authentication.CMCAuth();
cmcAuth.init(CMCAUTH_AUTHMGR_ID, CMCAUTH_PLUGIN_ID, config);
@@ -172,14 +171,15 @@ public class AuthSubsystem implements IAuthSubsystem {
if (Debug.ON) {
Debug.trace("loaded cmc auth manager");
}
-
+
// #56659
// IAuthManager nullAuth = new NullAuthentication();
// nullAuth.init(NULL_AUTHMGR_ID, NULL_PLUGIN_ID, config);
- // mAuthMgrInsts.put(NULL_AUTHMGR_ID, new AuthManagerProxy(true, nullAuth));
+ // mAuthMgrInsts.put(NULL_AUTHMGR_ID, new AuthManagerProxy(true,
+ // nullAuth));
// if (Debug.ON) {
- // Debug.trace("loaded null auth manager");
+ // Debug.trace("loaded null auth manager");
// }
IAuthManager sslClientCertAuth = new SSLClientCertAuthentication();
@@ -197,8 +197,8 @@ public class AuthSubsystem implements IAuthSubsystem {
while (instances.hasMoreElements()) {
String insName = (String) instances.nextElement();
String implName = c.getString(insName + "." + PROP_PLUGIN);
- AuthMgrPlugin plugin =
- (AuthMgrPlugin) mAuthMgrPlugins.get(implName);
+ AuthMgrPlugin plugin =
+ (AuthMgrPlugin) mAuthMgrPlugins.get(implName);
if (plugin == null) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_AUTH_CANT_FIND_PLUGIN", implName));
@@ -211,8 +211,8 @@ public class AuthSubsystem implements IAuthSubsystem {
IAuthManager authMgrInst = null;
try {
- authMgrInst = (IAuthManager)
- Class.forName(className).newInstance();
+ authMgrInst = (IAuthManager)
+ Class.forName(className).newInstance();
IConfigStore authMgrConfig = c.getSubStore(insName);
authMgrInst.init(insName, implName, authMgrConfig);
@@ -221,16 +221,13 @@ public class AuthSubsystem implements IAuthSubsystem {
log(ILogger.LL_INFO, CMS.getLogMessage("CMSCORE_AUTH_ADD_AUTH_INSTANCE", insName));
} catch (ClassNotFoundException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_AUTH_AUTHSUB_ERROR", e.toString()));
- throw new
- EAuthException(CMS.getUserMessage("CMS_ACL_CLASS_LOAD_FAIL", className));
+ throw new EAuthException(CMS.getUserMessage("CMS_ACL_CLASS_LOAD_FAIL", className));
} catch (IllegalAccessException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_AUTH_AUTHSUB_ERROR", e.toString()));
- throw new
- EAuthException(CMS.getUserMessage("CMS_ACL_CLASS_LOAD_FAIL", className));
+ throw new EAuthException(CMS.getUserMessage("CMS_ACL_CLASS_LOAD_FAIL", className));
} catch (InstantiationException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_AUTH_AUTHSUB_ERROR", e.toString()));
- throw new
- EAuthException(CMS.getUserMessage("CMS_ACL_CLASS_LOAD_FAIL", className));
+ throw new EAuthException(CMS.getUserMessage("CMS_ACL_CLASS_LOAD_FAIL", className));
} catch (EBaseException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_AUTH_AUTH_INIT_ERROR", insName, e.toString()));
// Skip the authenticaiton instance if
@@ -245,8 +242,8 @@ public class AuthSubsystem implements IAuthSubsystem {
// fix the problem via console
}
// add manager instance to list.
- mAuthMgrInsts.put(insName, new
- AuthManagerProxy(isEnable, authMgrInst));
+ mAuthMgrInsts.put(insName, new
+ AuthManagerProxy(isEnable, authMgrInst));
if (Debug.ON) {
Debug.trace("loaded auth instance " + insName + " impl " + implName);
}
@@ -262,23 +259,24 @@ public class AuthSubsystem implements IAuthSubsystem {
/**
* Authenticate to the named authentication manager instance
* <p>
- * @param authCred authentication credentials subject to the
- * requirements of each authentication manager
+ *
+ * @param authCred authentication credentials subject to the requirements of
+ * each authentication manager
* @param authMgrName name of the authentication manager instance
- * @return authentication token with individualized authenticated
- * information.
+ * @return authentication token with individualized authenticated
+ * information.
* @exception EMissingCredential If a required credential for the
- * authentication manager is missing.
+ * authentication manager is missing.
* @exception EInvalidCredentials If the credentials cannot be authenticated
* @exception EAuthMgrNotFound The auth manager is not found.
* @exception EBaseException If an internal error occurred.
*/
public IAuthToken authenticate(
- IAuthCredentials authCred, String authMgrInstName)
- throws EMissingCredential, EInvalidCredentials,
+ IAuthCredentials authCred, String authMgrInstName)
+ throws EMissingCredential, EInvalidCredentials,
EAuthMgrNotFound, EBaseException {
AuthManagerProxy proxy = (AuthManagerProxy)
- mAuthMgrInsts.get(authMgrInstName);
+ mAuthMgrInsts.get(authMgrInstName);
if (proxy == null) {
throw new EAuthMgrNotFound(CMS.getUserMessage("CMS_AUTHENTICATION_AUTHMGR_NOT_FOUND", authMgrInstName));
@@ -295,11 +293,11 @@ public class AuthSubsystem implements IAuthSubsystem {
}
/**
- * Gets a list of required authentication credential names
- * of the specified authentication manager.
+ * Gets a list of required authentication credential names of the specified
+ * authentication manager.
*/
public String[] getRequiredCreds(String authMgrInstName)
- throws EAuthMgrNotFound {
+ throws EAuthMgrNotFound {
IAuthManager authMgrInst = get(authMgrInstName);
if (authMgrInst == null) {
@@ -309,13 +307,14 @@ public class AuthSubsystem implements IAuthSubsystem {
}
/**
- * Gets configuration parameters for the given
- * authentication manager plugin.
+ * Gets configuration parameters for the given authentication manager
+ * plugin.
+ *
* @param implName Name of the authentication plugin.
* @return Hashtable of required parameters.
*/
public String[] getConfigParams(String implName)
- throws EAuthMgrPluginNotFound, EBaseException {
+ throws EAuthMgrPluginNotFound, EBaseException {
// is this a registered implname?
AuthMgrPlugin plugin = (AuthMgrPlugin) mAuthMgrPlugins.get(implName);
@@ -334,21 +333,19 @@ public class AuthSubsystem implements IAuthSubsystem {
return (authMgrInst.getConfigParams());
} catch (InstantiationException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_AUTH_INSTANCE_NOT_CREATED", e.toString()));
- throw new
- EAuthException(CMS.getUserMessage("CMS_ACL_CLASS_LOAD_FAIL", className));
+ throw new EAuthException(CMS.getUserMessage("CMS_ACL_CLASS_LOAD_FAIL", className));
} catch (ClassNotFoundException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_AUTH_INSTANCE_NOT_CREATED", e.toString()));
- throw new
- EAuthException(CMS.getUserMessage("CMS_ACL_CLASS_LOAD_FAIL", className));
+ throw new EAuthException(CMS.getUserMessage("CMS_ACL_CLASS_LOAD_FAIL", className));
} catch (IllegalAccessException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_AUTH_INSTANCE_NOT_CREATED", e.toString()));
- throw new
- EAuthException(CMS.getUserMessage("CMS_ACL_CLASS_LOAD_FAIL", className));
+ throw new EAuthException(CMS.getUserMessage("CMS_ACL_CLASS_LOAD_FAIL", className));
}
}
/**
* Add an authentication manager instance.
+ *
* @param name name of the authentication manager instance
* @param authMgr the authentication manager instance to be added
*/
@@ -358,6 +355,7 @@ public class AuthSubsystem implements IAuthSubsystem {
/*
* Removes a authentication manager instance.
+ *
* @param name name of the authentication manager
*/
public void delete(String name) {
@@ -366,6 +364,7 @@ public class AuthSubsystem implements IAuthSubsystem {
/**
* Gets the authentication manager instance of the specified name.
+ *
* @param name name of the authentication manager instance
* @return the named authentication manager instance
*/
@@ -385,7 +384,7 @@ public class AuthSubsystem implements IAuthSubsystem {
Enumeration<String> e = mAuthMgrInsts.keys();
while (e.hasMoreElements()) {
- IAuthManager p = get( e.nextElement());
+ IAuthManager p = get(e.nextElement());
if (p != null) {
inst.addElement(p);
@@ -409,9 +408,9 @@ public class AuthSubsystem implements IAuthSubsystem {
}
/**
- * Retrieve a single auth manager instance
+ * Retrieve a single auth manager instance
*/
-
+
/* getconfigparams above should be recoded to use this func */
public IAuthManager getAuthManagerPlugin(String name) {
AuthMgrPlugin plugin = (AuthMgrPlugin) mAuthMgrPlugins.get(name);
@@ -429,16 +428,18 @@ public class AuthSubsystem implements IAuthSubsystem {
/**
* Retrieves id (name) of this subsystem.
+ *
* @return name of the authentication subsystem
*/
public String getId() {
return (mId);
}
-
+
/**
* Sets id string to this subsystem.
* <p>
- * Use with caution. Should not do it when sharing with others
+ * Use with caution. Should not do it when sharing with others
+ *
* @param id name to be applied to an authentication sybsystem
*/
public void setId(String id) throws EBaseException {
@@ -449,18 +450,17 @@ public class AuthSubsystem implements IAuthSubsystem {
* registers the administration servlet with the administration subsystem.
*/
public void startup() throws EBaseException {
- //remove the log since it's already logged from S_ADMIN
- //String infoMsg = "Auth subsystem administration Servlet registered";
- //log(ILogger.LL_INFO, infoMsg);
+ // remove the log since it's already logged from S_ADMIN
+ // String infoMsg = "Auth subsystem administration Servlet registered";
+ // log(ILogger.LL_INFO, infoMsg);
}
/**
- * shuts down authentication managers one by one.
+ * shuts down authentication managers one by one.
* <P>
*/
public void shutdown() {
- for (Enumeration<String> e = mAuthMgrInsts.keys();
- e.hasMoreElements();) {
+ for (Enumeration<String> e = mAuthMgrInsts.keys(); e.hasMoreElements();) {
IAuthManager mgr = (IAuthManager) get((String) e.nextElement());
@@ -486,7 +486,7 @@ public class AuthSubsystem implements IAuthSubsystem {
/**
* Returns the root configuration storage of this system.
* <P>
- *
+ *
* @return configuration store of this subsystem
*/
public IConfigStore getConfigStore() {
@@ -495,6 +495,7 @@ public class AuthSubsystem implements IAuthSubsystem {
/**
* gets the named authentication manager
+ *
* @param name of the authentication manager
* @return the named authentication manager
*/
@@ -509,7 +510,7 @@ public class AuthSubsystem implements IAuthSubsystem {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_AUTHENTICATION,
- level, msg);
+ level, msg);
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/authentication/CertUserDBAuthentication.java b/pki/base/common/src/com/netscape/cmscore/authentication/CertUserDBAuthentication.java
index c8214294..e23a02f8 100644
--- a/pki/base/common/src/com/netscape/cmscore/authentication/CertUserDBAuthentication.java
+++ b/pki/base/common/src/com/netscape/cmscore/authentication/CertUserDBAuthentication.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.authentication;
-
import java.security.cert.X509Certificate;
import netscape.security.x509.X509CertImpl;
@@ -38,13 +37,11 @@ import com.netscape.certsrv.usrgrp.ICertUserLocator;
import com.netscape.cmscore.usrgrp.ExactMatchCertUserLocator;
import com.netscape.cmscore.usrgrp.User;
-
/**
- * Certificate server agent authentication.
- * Maps a SSL client authenticate certificate to a user (agent) entry in the
- * internal database.
+ * Certificate server agent authentication. Maps a SSL client authenticate
+ * certificate to a user (agent) entry in the internal database.
* <P>
- *
+ *
* @author lhsiao
* @author cfu
* @version $Revision$, $Date$
@@ -81,15 +78,15 @@ public class CertUserDBAuthentication implements IAuthManager {
/**
* initializes the CertUserDBAuthentication auth manager
* <p>
- * called by AuthSubsystem init() method, when initializing
- * all available authentication managers.
- * @param owner - The authentication subsystem that hosts this
- * auth manager
- * @param config - The configuration store used by the
- * authentication subsystem
+ * called by AuthSubsystem init() method, when initializing all available
+ * authentication managers.
+ *
+ * @param owner - The authentication subsystem that hosts this auth manager
+ * @param config - The configuration store used by the authentication
+ * subsystem
*/
public void init(String name, String implName, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mName = name;
mImplName = implName;
mConfig = config;
@@ -112,7 +109,7 @@ public class CertUserDBAuthentication implements IAuthManager {
mCULocator = new ExactMatchCertUserLocator();
log(ILogger.LL_INFO, CMS.getLogMessage("INIT_DONE", name));
}
-
+
/**
* Gets the name of this authentication manager.
*/
@@ -126,28 +123,29 @@ public class CertUserDBAuthentication implements IAuthManager {
public String getImplName() {
return mImplName;
}
-
+
/**
* authenticates user(agent) by certificate
* <p>
- * called by other subsystems or their servlets to authenticate
- * users (agents)
- * @param authCred - authentication credential that contains
- * an usrgrp.Certificates of the user (agent)
+ * called by other subsystems or their servlets to authenticate users
+ * (agents)
+ *
+ * @param authCred - authentication credential that contains an
+ * usrgrp.Certificates of the user (agent)
* @return the authentication token that contains the following
- *
- * @exception com.netscape.certsrv.base.EAuthsException any
- * authentication failure or insufficient credentials
+ *
+ * @exception com.netscape.certsrv.base.EAuthsException any authentication
+ * failure or insufficient credentials
* @see com.netscape.certsrv.authentication.AuthToken
* @see com.netscape.certsrv.usrgrp.Certificates
*/
public IAuthToken authenticate(IAuthCredentials authCred)
- throws EMissingCredential, EInvalidCredentials, EBaseException {
+ throws EMissingCredential, EInvalidCredentials, EBaseException {
CMS.debug("CertUserDBAuth: started");
AuthToken authToken = new AuthToken(this);
CMS.debug("CertUserDBAuth: Retrieving client certificate");
- X509Certificate[] x509Certs =
- (X509Certificate[]) authCred.get(CRED_CERT);
+ X509Certificate[] x509Certs =
+ (X509Certificate[]) authCred.get(CRED_CERT);
if (x509Certs == null) {
CMS.debug("CertUserDBAuth: no client certificate found");
@@ -184,7 +182,7 @@ public class CertUserDBAuthentication implements IAuthManager {
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR", e.toString()));
}
- // any unexpected error occurs like internal db down,
+ // any unexpected error occurs like internal db down,
// UGSubsystem only returns null for user.
if (user == null) {
CMS.debug("Authentication: cannot map certificate to user");
@@ -198,7 +196,7 @@ public class CertUserDBAuthentication implements IAuthManager {
authToken.set(TOKEN_USER_DN, user.getUserDN());
authToken.set(TOKEN_USERID, user.getUserID());
authToken.set(TOKEN_UID, user.getUserID());
- authToken.set(CRED_CERT, certs);
+ authToken.set(CRED_CERT, certs);
log(ILogger.LL_INFO, CMS.getLogMessage("CMS_AUTH_AUTHENTICATED", user.getUserID()));
CMS.debug("authenticated " + user.getUserDN());
@@ -207,11 +205,12 @@ public class CertUserDBAuthentication implements IAuthManager {
}
/**
- * get the list of authentication credential attribute names
- * required by this authentication manager. Generally used by
- * the servlets that handle agent operations to authenticate its
- * users. It calls this method to know which are the
- * required credentials from the user (e.g. Javascript form data)
+ * get the list of authentication credential attribute names required by
+ * this authentication manager. Generally used by the servlets that handle
+ * agent operations to authenticate its users. It calls this method to know
+ * which are the required credentials from the user (e.g. Javascript form
+ * data)
+ *
* @return attribute names in Vector
*/
public String[] getRequiredCreds() {
@@ -219,15 +218,15 @@ public class CertUserDBAuthentication implements IAuthManager {
}
/**
- * get the list of configuration parameter names
- * required by this authentication manager. Generally used by
- * the Certificate Server Console to display the table for
- * configuration purposes. CertUserDBAuthentication is currently not
- * exposed in this case, so this method is not to be used.
- * @return configuration parameter names in Hashtable of Vectors
- * where each hashtable entry's key is the substore name, value is a
- * Vector of parameter names. If no substore, the parameter name
- * is the Hashtable key itself, with value same as key.
+ * get the list of configuration parameter names required by this
+ * authentication manager. Generally used by the Certificate Server Console
+ * to display the table for configuration purposes. CertUserDBAuthentication
+ * is currently not exposed in this case, so this method is not to be used.
+ *
+ * @return configuration parameter names in Hashtable of Vectors where each
+ * hashtable entry's key is the substore name, value is a Vector of
+ * parameter names. If no substore, the parameter name is the
+ * Hashtable key itself, with value same as key.
*/
public String[] getConfigParams() {
return (mConfigParams);
@@ -240,8 +239,8 @@ public class CertUserDBAuthentication implements IAuthManager {
}
/**
- * gets the configuretion substore used by this authentication
- * manager
+ * gets the configuretion substore used by this authentication manager
+ *
* @return configuration store
*/
public IConfigStore getConfigStore() {
@@ -252,7 +251,7 @@ public class CertUserDBAuthentication implements IAuthManager {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_AUTHENTICATION,
- level, msg);
+ level, msg);
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/authentication/ChallengePhraseAuthentication.java b/pki/base/common/src/com/netscape/cmscore/authentication/ChallengePhraseAuthentication.java
index 38901f3b..56db7194 100644
--- a/pki/base/common/src/com/netscape/cmscore/authentication/ChallengePhraseAuthentication.java
+++ b/pki/base/common/src/com/netscape/cmscore/authentication/ChallengePhraseAuthentication.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.authentication;
-
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@@ -50,14 +49,12 @@ import com.netscape.cmscore.dbs.CertRecord;
import com.netscape.cmscore.dbs.CertificateRepository;
import com.netscape.cmscore.util.Debug;
-
/**
- * Challenge phrase based authentication.
- * Maps a certificate to the request in the
- * internal database and further compares the challenge phrase with
- * that from the EE input.
+ * Challenge phrase based authentication. Maps a certificate to the request in
+ * the internal database and further compares the challenge phrase with that
+ * from the EE input.
* <P>
- *
+ *
* @author cfu chrisho
* @version $Revision$, $Date$
*/
@@ -69,7 +66,7 @@ public class ChallengePhraseAuthentication implements IAuthManager {
/* required credentials */
public static final String CRED_CERT_SERIAL = IAuthManager.CRED_CERT_SERIAL_TO_REVOKE;
public static final String CRED_CHALLENGE = "challengePhrase";
- protected String[] mRequiredCreds = { CRED_CERT_SERIAL, CRED_CHALLENGE};
+ protected String[] mRequiredCreds = { CRED_CERT_SERIAL, CRED_CHALLENGE };
/* config parameters to pass to console (none) */
protected static String[] mConfigParams = null;
@@ -86,7 +83,7 @@ public class ChallengePhraseAuthentication implements IAuthManager {
private Vector mID = null;
private MessageDigest mSHADigest = null;
- // request attributes hacks
+ // request attributes hacks
public static final String CHALLENGE_PHRASE = CRED_CHALLENGE;
public static final String SUBJECTNAME = "subjectName";
public static final String SERIALNUMBER = "serialNumber";
@@ -98,14 +95,15 @@ public class ChallengePhraseAuthentication implements IAuthManager {
/**
* initializes the ChallengePhraseAuthentication auth manager
* <p>
- * called by AuthSubsystem init() method, when initializing
- * all available authentication managers.
+ * called by AuthSubsystem init() method, when initializing all available
+ * authentication managers.
+ *
* @param name The name of this authentication manager instance.
* @param implName The name of the authentication manager plugin.
* @param config The configuration store for this authentication manager.
*/
public void init(String name, String implName, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mName = name;
mImplName = implName;
mConfig = config;
@@ -118,7 +116,7 @@ public class ChallengePhraseAuthentication implements IAuthManager {
log(ILogger.LL_INFO, CMS.getLogMessage("INIT_DONE", name));
}
-
+
/**
* Gets the name of this authentication manager.
*/
@@ -132,24 +130,25 @@ public class ChallengePhraseAuthentication implements IAuthManager {
public String getImplName() {
return mImplName;
}
-
+
/**
* authenticates revocation of a certification by a challenge phrase
* <p>
- * called by other subsystems or their servlets to authenticate
- * a revocation request
- * @param authCred - authentication credential that contains
- * a Certificate to revoke
+ * called by other subsystems or their servlets to authenticate a revocation
+ * request
+ *
+ * @param authCred - authentication credential that contains a Certificate
+ * to revoke
* @return the authentication token that contains the request id
- *
+ *
* @exception EMissingCredential If a required credential for this
- * authentication manager is missing.
+ * authentication manager is missing.
* @exception EInvalidCredentials If credentials cannot be authenticated.
* @exception EBaseException If an internal error occurred.
* @see com.netscape.certsrv.authentication.AuthToken
*/
public IAuthToken authenticate(IAuthCredentials authCred)
- throws EMissingCredential, EInvalidCredentials, EBaseException {
+ throws EMissingCredential, EInvalidCredentials, EBaseException {
mCA = (ICertificateAuthority)
SubsystemRegistry.getInstance().get("ca");
@@ -160,13 +159,10 @@ public class ChallengePhraseAuthentication implements IAuthManager {
AuthToken authToken = new AuthToken(this);
/*
- X509Certificate[] x509Certs =
- (X509Certificate[]) authCred.get(CRED_CERT);
- if (x509Certs == null) {
- log(ILogger.LL_FAILURE,
- " missing cert credential.");
- throw new EMissingCredential(CRED_CERT_SERIAL);
- }
+ * X509Certificate[] x509Certs = (X509Certificate[])
+ * authCred.get(CRED_CERT); if (x509Certs == null) {
+ * log(ILogger.LL_FAILURE, " missing cert credential."); throw new
+ * EMissingCredential(CRED_CERT_SERIAL); }
*/
String serialNumString = (String) authCred.get(CRED_CERT_SERIAL);
@@ -176,7 +172,7 @@ public class ChallengePhraseAuthentication implements IAuthManager {
if (serialNumString == null || serialNumString.equals(""))
throw new EMissingCredential(CMS.getUserMessage("CMS_AUTHENTICATION_NULL_CREDENTIAL", CRED_CERT_SERIAL));
else {
- //serialNumString = getDecimalStr(serialNumString);
+ // serialNumString = getDecimalStr(serialNumString);
try {
serialNumString = serialNumString.trim();
if (serialNumString.startsWith("0x") || serialNumString.startsWith("0X")) {
@@ -186,7 +182,7 @@ public class ChallengePhraseAuthentication implements IAuthManager {
serialNum = new
BigInteger(serialNumString);
}
-
+
} catch (NumberFormatException e) {
throw new EAuthUserError(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_ATTRIBUTE_VALUE", "Invalid serial number."));
}
@@ -203,13 +199,10 @@ public class ChallengePhraseAuthentication implements IAuthManager {
throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
}
- /* maybe later
- if (mCertDB.isCertificateRevoked(cert) != null) {
- log(ILogger.LL_FAILURE,
- "Certificate has already been revoked.");
- // throw something else...cfu
- throw new EInvalidCredentials();
- }
+ /*
+ * maybe later if (mCertDB.isCertificateRevoked(cert) != null) {
+ * log(ILogger.LL_FAILURE, "Certificate has already been revoked."); //
+ * throw something else...cfu throw new EInvalidCredentials(); }
*/
X509CertImpl[] certsToRevoke = null;
@@ -217,9 +210,9 @@ public class ChallengePhraseAuthentication implements IAuthManager {
// check challenge phrase against request
/*
- * map cert to a request: a cert serial number maps to a
- * cert record in the internal db, from the cert record,
- * where we'll find the challenge phrase
+ * map cert to a request: a cert serial number maps to a cert record in
+ * the internal db, from the cert record, where we'll find the challenge
+ * phrase
*/
if (mCertDB != null) { /* is CA */
CertRecord record = null;
@@ -240,7 +233,7 @@ public class ChallengePhraseAuthentication implements IAuthManager {
if (samepwd) {
bigIntArray = new BigInteger[1];
bigIntArray[0] = record.getSerialNumber();
- } else
+ } else
throw new EAuthUserError(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_ATTRIBUTE_VALUE", "Invalid password."));
} else {
@@ -283,7 +276,7 @@ public class ChallengePhraseAuthentication implements IAuthManager {
if (bigIntArray != null && bigIntArray.length > 0) {
if (Debug.ON) {
Debug.trace("challenge authentication serialno array not null");
- for (int i = 0; i < bigIntArray.length; i++)
+ for (int i = 0; i < bigIntArray.length; i++)
Debug.trace("challenge auth serialno " + bigIntArray[i]);
}
}
@@ -295,8 +288,8 @@ public class ChallengePhraseAuthentication implements IAuthManager {
return authToken;
}
- private boolean compareChallengePassword(CertRecord record, String pwd)
- throws EBaseException {
+ private boolean compareChallengePassword(CertRecord record, String pwd)
+ throws EBaseException {
MetaInfo metaInfo = (MetaInfo) record.get(CertRecord.ATTR_META_INFO);
if (metaInfo == null) {
@@ -312,8 +305,8 @@ public class ChallengePhraseAuthentication implements IAuthManager {
String hashpwd = hashPassword(pwd);
// got metaInfo
- String challengeString =
- (String) metaInfo.get(CertRecord.META_CHALLENGE_PHRASE);
+ String challengeString =
+ (String) metaInfo.get(CertRecord.META_CHALLENGE_PHRASE);
if (challengeString == null) {
if (Debug.ON) {
@@ -326,20 +319,21 @@ public class ChallengePhraseAuthentication implements IAuthManager {
return false;
/*
- log(ILogger.LL_FAILURE,
- "Incorrect challenge phrase password used for revocation");
- throw new EInvalidCredentials();
+ * log(ILogger.LL_FAILURE,
+ * "Incorrect challenge phrase password used for revocation"); throw
+ * new EInvalidCredentials();
*/
- } else
+ } else
return true;
}
/**
- * get the list of authentication credential attribute names
- * required by this authentication manager. Generally used by
- * the servlets that handle agent operations to authenticate its
- * users. It calls this method to know which are the
- * required credentials from the user (e.g. Javascript form data)
+ * get the list of authentication credential attribute names required by
+ * this authentication manager. Generally used by the servlets that handle
+ * agent operations to authenticate its users. It calls this method to know
+ * which are the required credentials from the user (e.g. Javascript form
+ * data)
+ *
* @return attribute names in Vector
*/
public String[] getRequiredCreds() {
@@ -347,15 +341,16 @@ public class ChallengePhraseAuthentication implements IAuthManager {
}
/**
- * get the list of configuration parameter names
- * required by this authentication manager. Generally used by
- * the Certificate Server Console to display the table for
- * configuration purposes. ChallengePhraseAuthentication is currently not
- * exposed in this case, so this method is not to be used.
- * @return configuration parameter names in Hashtable of Vectors
- * where each hashtable entry's key is the substore name, value is a
- * Vector of parameter names. If no substore, the parameter name
- * is the Hashtable key itself, with value same as key.
+ * get the list of configuration parameter names required by this
+ * authentication manager. Generally used by the Certificate Server Console
+ * to display the table for configuration purposes.
+ * ChallengePhraseAuthentication is currently not exposed in this case, so
+ * this method is not to be used.
+ *
+ * @return configuration parameter names in Hashtable of Vectors where each
+ * hashtable entry's key is the substore name, value is a Vector of
+ * parameter names. If no substore, the parameter name is the
+ * Hashtable key itself, with value same as key.
*/
public String[] getConfigParams() {
return (mConfigParams);
@@ -368,8 +363,8 @@ public class ChallengePhraseAuthentication implements IAuthManager {
}
/**
- * gets the configuretion substore used by this authentication
- * manager
+ * gets the configuretion substore used by this authentication manager
+ *
* @return configuration store
*/
public IConfigStore getConfigStore() {
@@ -380,7 +375,7 @@ public class ChallengePhraseAuthentication implements IAuthManager {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_AUTHENTICATION,
- level, msg);
+ level, msg);
}
private IRequestQueue getReqQueue() {
@@ -388,15 +383,15 @@ public class ChallengePhraseAuthentication implements IAuthManager {
try {
IRegistrationAuthority ra = (IRegistrationAuthority)
- SubsystemRegistry.getInstance().get("ra");
+ SubsystemRegistry.getInstance().get("ra");
if (ra != null) {
queue = ra.getRequestQueue();
mRequestor = IRequest.REQUESTOR_RA;
}
} catch (Exception e) {
- log(ILogger.LL_FAILURE,
- " cannot get access to the request queue.");
+ log(ILogger.LL_FAILURE,
+ " cannot get access to the request queue.");
}
return queue;
diff --git a/pki/base/common/src/com/netscape/cmscore/authentication/NullAuthentication.java b/pki/base/common/src/com/netscape/cmscore/authentication/NullAuthentication.java
index e9bcbcb6..d2095f84 100644
--- a/pki/base/common/src/com/netscape/cmscore/authentication/NullAuthentication.java
+++ b/pki/base/common/src/com/netscape/cmscore/authentication/NullAuthentication.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.authentication;
-
import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.authentication.AuthToken;
import com.netscape.certsrv.authentication.EInvalidCredentials;
@@ -29,10 +28,10 @@ import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.logging.ILogger;
-
/**
* This authentication does nothing but just returns an empty authToken.
* <P>
+ *
* @author chrisho
* @version $Revision$, $Date$
*/
@@ -53,15 +52,16 @@ public class NullAuthentication implements IAuthManager {
/**
* initializes the NullAuthentication auth manager
* <p>
- * called by AuthSubsystem init() method, when initializing
- * all available authentication managers.
+ * called by AuthSubsystem init() method, when initializing all available
+ * authentication managers.
+ *
* @param name - Name assigned to this authentication manager instance.
* @param implName - Name of the authentication plugin.
- * @param config - The configuration store used by the
- * authentication subsystem.
+ * @param config - The configuration store used by the authentication
+ * subsystem.
*/
public void init(String name, String implName, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mName = name;
mImplName = implName;
mConfig = config;
@@ -72,21 +72,22 @@ public class NullAuthentication implements IAuthManager {
/**
* authenticates nothing
* <p>
- * called by other subsystems or their servlets to authenticate administrators
- * @param authCred Authentication credentials.
- * "uid" and "pwd" are required.
+ * called by other subsystems or their servlets to authenticate
+ * administrators
+ *
+ * @param authCred Authentication credentials. "uid" and "pwd" are required.
* @return the authentication token (authToken) that contains the following
- * userdn = [userdn, in case of success]<br>
- * authMgrName = [authMgrName]<br>
- * @exception com.netscape.certsrv.base.MissingCredential If either
- * "uid" or "pwd" is missing from the given credentials.
- * @exception com.netscape.certsrv.base.InvalidCredentials If the
- * the credentials failed to authenticate.
- * @exception com.netscape.certsrv.base.EBaseException If an internal
- * error occurred.
+ * userdn = [userdn, in case of success]<br>
+ * authMgrName = [authMgrName]<br>
+ * @exception com.netscape.certsrv.base.MissingCredential If either "uid" or
+ * "pwd" is missing from the given credentials.
+ * @exception com.netscape.certsrv.base.InvalidCredentials If the the
+ * credentials failed to authenticate.
+ * @exception com.netscape.certsrv.base.EBaseException If an internal error
+ * occurred.
*/
public IAuthToken authenticate(IAuthCredentials authCred)
- throws EMissingCredential, EInvalidCredentials, EBaseException {
+ throws EMissingCredential, EInvalidCredentials, EBaseException {
AuthToken authToken = new AuthToken(this);
authToken.set("authType", "NOAUTH");
@@ -109,10 +110,11 @@ public class NullAuthentication implements IAuthManager {
}
/**
- * get the list of authentication credential attribute names
- * required by this authentication manager. Generally used by
- * servlets that use this authentication manager, to retrieve
- * required credentials from the user (e.g. Javascript form data)
+ * get the list of authentication credential attribute names required by
+ * this authentication manager. Generally used by servlets that use this
+ * authentication manager, to retrieve required credentials from the user
+ * (e.g. Javascript form data)
+ *
* @return attribute names in Vector
*/
public String[] getRequiredCreds() {
@@ -120,9 +122,10 @@ public class NullAuthentication implements IAuthManager {
}
/**
- * Get the list of configuration parameter names
- * required by this authentication manager. In this case, an empty list.
- * @return String array of configuration parameters.
+ * Get the list of configuration parameter names required by this
+ * authentication manager. In this case, an empty list.
+ *
+ * @return String array of configuration parameters.
*/
public String[] getConfigParams() {
return (mConfigParams);
@@ -135,8 +138,8 @@ public class NullAuthentication implements IAuthManager {
}
/**
- * gets the configuration substore used by this authentication
- * manager
+ * gets the configuration substore used by this authentication manager
+ *
* @return configuration store
*/
public IConfigStore getConfigStore() {
@@ -145,6 +148,7 @@ public class NullAuthentication implements IAuthManager {
/**
* Log a message.
+ *
* @param level The logging level.
* @param msg The message to log.
*/
@@ -152,6 +156,6 @@ public class NullAuthentication implements IAuthManager {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_AUTHENTICATION,
- level, msg);
+ level, msg);
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/authentication/PasswdUserDBAuthentication.java b/pki/base/common/src/com/netscape/cmscore/authentication/PasswdUserDBAuthentication.java
index 88dc7296..a6fcaadb 100644
--- a/pki/base/common/src/com/netscape/cmscore/authentication/PasswdUserDBAuthentication.java
+++ b/pki/base/common/src/com/netscape/cmscore/authentication/PasswdUserDBAuthentication.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.authentication;
-
import netscape.ldap.LDAPConnection;
import netscape.ldap.LDAPEntry;
import netscape.ldap.LDAPException;
@@ -43,13 +42,12 @@ import com.netscape.cmscore.ldapconn.LdapConnInfo;
import com.netscape.cmscore.usrgrp.UGSubsystem;
import com.netscape.cmscore.util.Debug;
-
/**
- * Certificate Server admin authentication.
- * Used to authenticate administrators in the Certificate Server Console.
- * Authentications by checking the uid and password against the
- * database.
+ * Certificate Server admin authentication. Used to authenticate administrators
+ * in the Certificate Server Console. Authentications by checking the uid and
+ * password against the database.
* <P>
+ *
* @author lhsiao, cfu
* @version $Revision$, $Date$
*/
@@ -81,15 +79,16 @@ public class PasswdUserDBAuthentication implements IAuthManager {
/**
* initializes the PasswdUserDBAuthentication auth manager
* <p>
- * called by AuthSubsystem init() method, when initializing
- * all available authentication managers.
+ * called by AuthSubsystem init() method, when initializing all available
+ * authentication managers.
+ *
* @param name - Name assigned to this authentication manager instance.
* @param implName - Name of the authentication plugin.
- * @param config - The configuration store used by the
- * authentication subsystem.
+ * @param config - The configuration store used by the authentication
+ * subsystem.
*/
public void init(String name, String implName, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mName = name;
mImplName = implName;
mConfig = config;
@@ -110,24 +109,25 @@ public class PasswdUserDBAuthentication implements IAuthManager {
/**
* authenticates administratrators by LDAP uid/pwd
* <p>
- * called by other subsystems or their servlets to authenticate administrators
- * @param authCred Authentication credentials.
- * "uid" and "pwd" are required.
+ * called by other subsystems or their servlets to authenticate
+ * administrators
+ *
+ * @param authCred Authentication credentials. "uid" and "pwd" are required.
* @return the authentication token (authToken) that contains the following
- * userdn = [userdn, in case of success]<br>
- * authMgrName = [authMgrName]<br>
- * @exception com.netscape.certsrv.base.MissingCredential If either
- * "uid" or "pwd" is missing from the given credentials.
- * @exception com.netscape.certsrv.base.InvalidCredentials If the
- * the credentials failed to authenticate.
- * @exception com.netscape.certsrv.base.EBaseException If an internal
- * error occurred.
+ * userdn = [userdn, in case of success]<br>
+ * authMgrName = [authMgrName]<br>
+ * @exception com.netscape.certsrv.base.MissingCredential If either "uid" or
+ * "pwd" is missing from the given credentials.
+ * @exception com.netscape.certsrv.base.InvalidCredentials If the the
+ * credentials failed to authenticate.
+ * @exception com.netscape.certsrv.base.EBaseException If an internal error
+ * occurred.
*/
public IAuthToken authenticate(IAuthCredentials authCred)
- throws EMissingCredential, EInvalidCredentials, EBaseException {
+ throws EMissingCredential, EInvalidCredentials, EBaseException {
AuthToken authToken = new AuthToken(this);
- // make sure the required credentials are provided
+ // make sure the required credentials are provided
String uid = (String) authCred.get(CRED_UID);
CMS.debug("Authentication: UID=" + uid);
if (uid == null) {
@@ -171,32 +171,32 @@ public class PasswdUserDBAuthentication implements IAuthManager {
log(ILogger.LL_SECURITY, CMS.getLogMessage("CMSCORE_AUTH_AUTH_FAILED", uid, e.toString()));
throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
} finally {
- if (conn != null)
+ if (conn != null)
mConnFactory.returnConn(conn);
- if (anonConn != null)
+ if (anonConn != null)
mAnonConnFactory.returnConn(anonConn);
}
UGSubsystem ug = UGSubsystem.getInstance();
authToken.set(TOKEN_USERDN, userdn);
- authToken.set(CRED_UID, uid); // return original uid for info
+ authToken.set(CRED_UID, uid); // return original uid for info
IUser user = null;
try {
user = ug.getUser(uid);
} catch (EBaseException e) {
- if (Debug.ON)
+ if (Debug.ON)
e.printStackTrace();
- // not a user in our user/group database.
+ // not a user in our user/group database.
log(ILogger.LL_SECURITY, CMS.getLogMessage("CMSCORE_AUTH_UID_NOT_FOUND", uid, e.toString()));
throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
}
authToken.set(TOKEN_USERDN, user.getUserDN());
authToken.set(TOKEN_USERID, user.getUserID());
log(ILogger.LL_INFO, CMS.getLogMessage("CMS_AUTH_AUTHENTICATED", uid));
-
+
return authToken;
}
@@ -215,10 +215,11 @@ public class PasswdUserDBAuthentication implements IAuthManager {
}
/**
- * get the list of authentication credential attribute names
- * required by this authentication manager. Generally used by
- * servlets that use this authentication manager, to retrieve
- * required credentials from the user (e.g. Javascript form data)
+ * get the list of authentication credential attribute names required by
+ * this authentication manager. Generally used by servlets that use this
+ * authentication manager, to retrieve required credentials from the user
+ * (e.g. Javascript form data)
+ *
* @return attribute names in Vector
*/
public String[] getRequiredCreds() {
@@ -226,9 +227,10 @@ public class PasswdUserDBAuthentication implements IAuthManager {
}
/**
- * Get the list of configuration parameter names
- * required by this authentication manager. In this case, an empty list.
- * @return String array of configuration parameters.
+ * Get the list of configuration parameter names required by this
+ * authentication manager. In this case, an empty list.
+ *
+ * @return String array of configuration parameters.
*/
public String[] getConfigParams() {
return (mConfigParams);
@@ -248,8 +250,8 @@ public class PasswdUserDBAuthentication implements IAuthManager {
}
/**
- * gets the configuretion substore used by this authentication
- * manager
+ * gets the configuretion substore used by this authentication manager
+ *
* @return configuration store
*/
public IConfigStore getConfigStore() {
@@ -258,6 +260,7 @@ public class PasswdUserDBAuthentication implements IAuthManager {
/**
* Log a message.
+ *
* @param level The logging level.
* @param msg The message to log.
*/
@@ -265,6 +268,6 @@ public class PasswdUserDBAuthentication implements IAuthManager {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_AUTHENTICATION,
- level, msg);
+ level, msg);
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/authentication/SSLClientCertAuthentication.java b/pki/base/common/src/com/netscape/cmscore/authentication/SSLClientCertAuthentication.java
index 56927537..c88050d4 100644
--- a/pki/base/common/src/com/netscape/cmscore/authentication/SSLClientCertAuthentication.java
+++ b/pki/base/common/src/com/netscape/cmscore/authentication/SSLClientCertAuthentication.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.authentication;
-
// ldap java sdk
// cert server imports.
@@ -47,10 +46,10 @@ import com.netscape.certsrv.request.IRequestQueue;
import com.netscape.certsrv.request.RequestStatus;
import com.netscape.cmscore.util.Debug;
-
/**
* SSL client based authentication.
* <P>
+ *
* @author chrisho
* @version $Revision$, $Date$
*/
@@ -70,13 +69,13 @@ public class SSLClientCertAuthentication implements IAuthManager {
private IConfigStore mConfig = null;
private String mRequestor = null;
- /* Holds configuration parameters accepted by this implementation.
- * This list is passed to the configuration console so configuration
- * for instances of this implementation can be configured through the
- * console.
+ /*
+ * Holds configuration parameters accepted by this implementation. This list
+ * is passed to the configuration console so configuration for instances of
+ * this implementation can be configured through the console.
*/
- protected static String[] mConfigParams =
- new String[] {};
+ protected static String[] mConfigParams =
+ new String[] {};
/**
* Default constructor, initialization must follow.
@@ -86,7 +85,7 @@ public class SSLClientCertAuthentication implements IAuthManager {
}
public void init(String name, String implName, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mName = name;
mImplName = implName;
mConfig = config;
@@ -95,18 +94,18 @@ public class SSLClientCertAuthentication implements IAuthManager {
}
public IAuthToken authenticate(IAuthCredentials authCred)
- throws EMissingCredential, EInvalidCredentials, EBaseException {
+ throws EMissingCredential, EInvalidCredentials, EBaseException {
AuthToken authToken = new AuthToken(this);
CMS.debug("SSLCertAuth: Retrieving client certificates");
X509Certificate[] x509Certs =
- (X509Certificate[]) authCred.get(CRED_CERT);
+ (X509Certificate[]) authCred.get(CRED_CERT);
if (x509Certs == null) {
CMS.debug("SSLCertAuth: No client certificate found");
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_AUTH_MISSING_CERT"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_AUTH_MISSING_CERT"));
throw new EMissingCredential(CMS.getUserMessage("CMS_AUTHENTICATION_NULL_CREDENTIAL", CRED_CERT));
}
CMS.debug("SSLCertAuth: Got client certificate");
@@ -118,17 +117,17 @@ public class SSLClientCertAuthentication implements IAuthManager {
}
X509CertImpl clientCert = (X509CertImpl) x509Certs[0];
-
+
BigInteger serialNum = null;
try {
serialNum = (BigInteger) clientCert.getSerialNumber();
- //serialNum = new BigInteger(s.substring(2), 16);
+ // serialNum = new BigInteger(s.substring(2), 16);
} catch (NumberFormatException e) {
throw new EAuthUserError(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_ATTRIBUTE_VALUE", "Invalid serial number."));
}
- String clientCertIssuerDN = clientCert.getIssuerDN().toString();
+ String clientCertIssuerDN = clientCert.getIssuerDN().toString();
BigInteger[] bigIntArray = null;
if (mCertDB != null) { /* is CA */
@@ -145,13 +144,13 @@ public class SSLClientCertAuthentication implements IAuthManager {
String status = record.getStatus();
if (status.equals("VALID")) {
-
+
X509CertImpl cacert = mCA.getCACert();
Principal p = cacert.getSubjectDN();
if (!p.toString().equals(clientCertIssuerDN)) {
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ISSUER_NAME"));
- }
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ISSUER_NAME"));
+ }
} else {
throw new EBaseException(
CMS.getUserMessage("CMS_BASE_INVALID_CERT_STATUS", status));
@@ -182,30 +181,30 @@ public class SSLClientCertAuthentication implements IAuthManager {
RequestStatus status = getCertStatusReq.getRequestStatus();
if (status == RequestStatus.COMPLETE) {
- String certStatus =
- getCertStatusReq.getExtDataInString(IRequest.CERT_STATUS);
+ String certStatus =
+ getCertStatusReq.getExtDataInString(IRequest.CERT_STATUS);
- if (certStatus == null) {
- String[] params = {"null status"};
+ if (certStatus == null) {
+ String[] params = { "null status" };
throw new EBaseException(
CMS.getUserMessage("CMS_BASE_INVALID_CERT_STATUS", params));
} else if (certStatus.equals("INVALIDCERTROOT")) {
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ISSUER_NAME"));
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ISSUER_NAME"));
} else if (!certStatus.equals("VALID")) {
- String[] params = {status.toString()};
+ String[] params = { status.toString() };
throw new EBaseException(
CMS.getUserMessage("CMS_BASE_INVALID_CERT_STATUS", params));
}
} else {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_AUTH_INCOMPLETE_REQUEST"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_AUTH_INCOMPLETE_REQUEST"));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_REQUEST_IN_BAD_STATE"));
}
} else {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_AUTH_FAILED_GET_QUEUE"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_AUTH_FAILED_GET_QUEUE"));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_GET_QUEUE_FAILED"));
}
} // else, ra
@@ -222,10 +221,10 @@ public class SSLClientCertAuthentication implements IAuthManager {
}
/**
- * Returns a list of configuration parameter names.
- * The list is passed to the configuration console so instances of
- * this implementation can be configured through the console.
- *
+ * Returns a list of configuration parameter names. The list is passed to
+ * the configuration console so instances of this implementation can be
+ * configured through the console.
+ *
* @return String array of configuration parameter names.
*/
public String[] getConfigParams() {
@@ -234,6 +233,7 @@ public class SSLClientCertAuthentication implements IAuthManager {
/**
* Returns array of required credentials for this authentication manager.
+ *
* @return Array of required credentials.
*/
public String[] getRequiredCreds() {
@@ -244,15 +244,15 @@ public class SSLClientCertAuthentication implements IAuthManager {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_AUTHENTICATION,
- level, msg);
+ level, msg);
}
private IRequestQueue getReqQueue() {
IRequestQueue queue = null;
try {
- IRegistrationAuthority ra =
- (IRegistrationAuthority) CMS.getSubsystem("ra");
+ IRegistrationAuthority ra =
+ (IRegistrationAuthority) CMS.getSubsystem("ra");
if (ra != null) {
queue = ra.getRequestQueue();
@@ -260,7 +260,7 @@ public class SSLClientCertAuthentication implements IAuthManager {
}
} catch (Exception e) {
log(ILogger.LL_FAILURE,
- " cannot get access to the request queue.");
+ " cannot get access to the request queue.");
}
return queue;
@@ -268,6 +268,7 @@ public class SSLClientCertAuthentication implements IAuthManager {
/**
* Gets the configuration substore used by this authentication manager
+ *
* @return configuration store
*/
public IConfigStore getConfigStore() {
@@ -288,4 +289,3 @@ public class SSLClientCertAuthentication implements IAuthManager {
return mImplName;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/authentication/VerifiedCert.java b/pki/base/common/src/com/netscape/cmscore/authentication/VerifiedCert.java
index 69192f3f..173d69f8 100644
--- a/pki/base/common/src/com/netscape/cmscore/authentication/VerifiedCert.java
+++ b/pki/base/common/src/com/netscape/cmscore/authentication/VerifiedCert.java
@@ -17,16 +17,14 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.authentication;
-
import java.math.BigInteger;
import java.util.Date;
import com.netscape.certsrv.apps.CMS;
-
-/**
+/**
* class storing verified certificate.
- *
+ *
* @version $Revision$, $Date$
*/
@@ -45,9 +43,9 @@ public class VerifiedCert {
/**
* Constructs verified certiificate record
*/
-
+
public VerifiedCert(BigInteger serialNumber, byte[] certEncoded,
- int status) {
+ int status) {
mStatus = status;
mSerialNumber = serialNumber;
mCertEncoded = certEncoded;
@@ -55,13 +53,13 @@ public class VerifiedCert {
}
public int check(BigInteger serialNumber, byte[] certEncoded,
- long interval, long unknownStateInterval) {
+ long interval, long unknownStateInterval) {
int status = UNKNOWN;
-
+
if (mSerialNumber.equals(serialNumber)) {
if (mCertEncoded != null) {
if (certEncoded != null &&
- mCertEncoded.length == certEncoded.length) {
+ mCertEncoded.length == certEncoded.length) {
int i;
for (i = 0; i < mCertEncoded.length; i++) {
@@ -90,4 +88,3 @@ public class VerifiedCert {
return status;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/authentication/VerifiedCerts.java b/pki/base/common/src/com/netscape/cmscore/authentication/VerifiedCerts.java
index ca0f63e5..0907bf62 100644
--- a/pki/base/common/src/com/netscape/cmscore/authentication/VerifiedCerts.java
+++ b/pki/base/common/src/com/netscape/cmscore/authentication/VerifiedCerts.java
@@ -17,15 +17,13 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.authentication;
-
import java.math.BigInteger;
import netscape.security.x509.X509CertImpl;
-
-/**
+/**
* class storing verified certificates.
- *
+ *
* @version $Revision$, $Date$
*/
@@ -38,11 +36,11 @@ public class VerifiedCerts {
private VerifiedCert[] mVCerts = null;
private long mInterval = 0;
private long mUnknownStateInterval = 0;
-
+
/**
* Constructs verified certiificates list
*/
-
+
public VerifiedCerts(int size, long interval) {
mVCerts = new VerifiedCert[size];
mInterval = interval;
@@ -64,8 +62,8 @@ public class VerifiedCerts {
} catch (Exception e) {
}
if ((certEncoded != null ||
- (status == VerifiedCert.CHECKED && mUnknownStateInterval > 0))
- && mInterval > 0) {
+ (status == VerifiedCert.CHECKED && mUnknownStateInterval > 0))
+ && mInterval > 0) {
update(cert.getSerialNumber(), certEncoded, status);
}
}
@@ -75,7 +73,7 @@ public class VerifiedCerts {
if ((status == VerifiedCert.NOT_REVOKED ||
status == VerifiedCert.REVOKED ||
(status == VerifiedCert.CHECKED && mUnknownStateInterval > 0))
- && mInterval > 0) {
+ && mInterval > 0) {
if (mLast == mNext && mFirst == mNext) { // empty
mVCerts[mNext] = new VerifiedCert(serialNumber, certEncoded, status);
mNext = next(mNext);
@@ -94,8 +92,8 @@ public class VerifiedCerts {
public int check(X509CertImpl cert) {
int status = VerifiedCert.UNKNOWN;
-
- if (mLast != mNext && mInterval > 0) { // if not empty and
+
+ if (mLast != mNext && mInterval > 0) { // if not empty and
if (cert != null) {
byte[] certEncoded = null;
@@ -116,10 +114,11 @@ public class VerifiedCerts {
int status = VerifiedCert.UNKNOWN;
int i = mLast;
- if (mVCerts != null && mLast != mNext && mInterval > 0) { // if not empty and
- while (status == VerifiedCert.UNKNOWN) {
- if (mVCerts[i] == null)
- return status;
+ if (mVCerts != null && mLast != mNext && mInterval > 0) { // if not
+ // empty and
+ while (status == VerifiedCert.UNKNOWN) {
+ if (mVCerts[i] == null)
+ return status;
status = mVCerts[i].check(serialNumber, certEncoded,
mInterval, mUnknownStateInterval);
if (status == VerifiedCert.EXPIRED) {
@@ -158,4 +157,3 @@ public class VerifiedCerts {
return i;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/authorization/AuthzSubsystem.java b/pki/base/common/src/com/netscape/cmscore/authorization/AuthzSubsystem.java
index 62351f1a..429aeda0 100644
--- a/pki/base/common/src/com/netscape/cmscore/authorization/AuthzSubsystem.java
+++ b/pki/base/common/src/com/netscape/cmscore/authorization/AuthzSubsystem.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.authorization;
-
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
@@ -38,11 +37,10 @@ import com.netscape.certsrv.base.ISubsystem;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.cmscore.util.Debug;
-
/**
* Default authorization subsystem
* <P>
- *
+ *
* @author cfu
* @version $Revision$, $Date$
*/
@@ -70,14 +68,15 @@ public class AuthzSubsystem implements IAuthzSubsystem {
}
/**
- * Initializes the authorization subsystem from the config store.
- * Load Authorization manager plugins, create and initialize
- * initialize authorization manager instances.
+ * Initializes the authorization subsystem from the config store. Load
+ * Authorization manager plugins, create and initialize initialize
+ * authorization manager instances.
+ *
* @param owner The owner of this module.
* @param config The configuration store.
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
try {
mLogger = CMS.getLogger();
mConfig = config;
@@ -90,7 +89,7 @@ public class AuthzSubsystem implements IAuthzSubsystem {
while (mImpls.hasMoreElements()) {
String id = (String) mImpls.nextElement();
String pluginPath = c.getString(id + "." + PROP_CLASS);
-
+
AuthzMgrPlugin plugin = new AuthzMgrPlugin(id, pluginPath);
mAuthzMgrPlugins.put(id, plugin);
@@ -107,16 +106,16 @@ public class AuthzSubsystem implements IAuthzSubsystem {
while (instances.hasMoreElements()) {
String insName = (String) instances.nextElement();
String implName = c.getString(insName + "." + PROP_PLUGIN);
- AuthzMgrPlugin plugin =
- (AuthzMgrPlugin) mAuthzMgrPlugins.get(implName);
+ AuthzMgrPlugin plugin =
+ (AuthzMgrPlugin) mAuthzMgrPlugins.get(implName);
if (plugin == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_AUTHZ_PLUGIN_NOT_FOUND", implName));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_AUTHZ_PLUGIN_NOT_FOUND", implName));
throw new EAuthzMgrPluginNotFound(CMS.getUserMessage("CMS_AUTHORIZATION_AUTHZMGR_PLUGIN_NOT_FOUND", implName));
} else {
CMS.debug(
- CMS.getLogMessage("CMSCORE_AUTHZ_PLUGIN_FOUND", implName));
+ CMS.getLogMessage("CMSCORE_AUTHZ_PLUGIN_FOUND", implName));
}
String className = plugin.getClassPath();
@@ -126,33 +125,30 @@ public class AuthzSubsystem implements IAuthzSubsystem {
IAuthzManager authzMgrInst = null;
try {
- authzMgrInst = (IAuthzManager)
- Class.forName(className).newInstance();
+ authzMgrInst = (IAuthzManager)
+ Class.forName(className).newInstance();
IConfigStore authzMgrConfig = c.getSubStore(insName);
authzMgrInst.init(insName, implName, authzMgrConfig);
isEnable = true;
- log(ILogger.LL_INFO,
- CMS.getLogMessage("CMSCORE_AUTHZ_INSTANCE_ADDED", insName));
+ log(ILogger.LL_INFO,
+ CMS.getLogMessage("CMSCORE_AUTHZ_INSTANCE_ADDED", insName));
} catch (ClassNotFoundException e) {
String errMsg = "AuthzSubsystem:: init()-" + e.toString();
log(ILogger.LL_FAILURE, CMS.getLogMessage("OPERATION_ERROR", errMsg));
- throw new
- EAuthzException(CMS.getUserMessage("CMS_AUTHORIZATION_LOAD_CLASS_FAIL", className));
+ throw new EAuthzException(CMS.getUserMessage("CMS_AUTHORIZATION_LOAD_CLASS_FAIL", className));
} catch (IllegalAccessException e) {
String errMsg = "AuthzSubsystem:: init()-" + e.toString();
log(ILogger.LL_FAILURE, CMS.getLogMessage("OPERATION_ERROR", errMsg));
- throw new
- EAuthzException(CMS.getUserMessage("CMS_AUTHORIZATION_LOAD_CLASS_FAIL", className));
+ throw new EAuthzException(CMS.getUserMessage("CMS_AUTHORIZATION_LOAD_CLASS_FAIL", className));
} catch (InstantiationException e) {
String errMsg = "AuthzSubsystem: init()-" + e.toString();
log(ILogger.LL_FAILURE, CMS.getLogMessage("OPERATION_ERROR", errMsg));
- throw new
- EAuthzException(CMS.getUserMessage("CMS_AUTHORIZATION_LOAD_CLASS_FAIL", className));
+ throw new EAuthzException(CMS.getUserMessage("CMS_AUTHORIZATION_LOAD_CLASS_FAIL", className));
} catch (EBaseException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_AUTHZ_PLUGIN_INIT_FAILED", insName, e.toString()));
// it is mis-configurated. This give
@@ -166,8 +162,8 @@ public class AuthzSubsystem implements IAuthzSubsystem {
// fix the problem via console
}
// add manager instance to list.
- mAuthzMgrInsts.put(insName, new
- AuthzManagerProxy(isEnable, authzMgrInst));
+ mAuthzMgrInsts.put(insName, new
+ AuthzManagerProxy(isEnable, authzMgrInst));
if (Debug.ON) {
Debug.trace("loaded authz instance " + insName + " impl " + implName);
}
@@ -182,16 +178,19 @@ public class AuthzSubsystem implements IAuthzSubsystem {
}
/**
- * authMgrzAccessInit is for servlets who want to initialize their
- * own authorization information before full operation. It is supposed
- * to be called during the init() method of a servlet.
+ * authMgrzAccessInit is for servlets who want to initialize their own
+ * authorization information before full operation. It is supposed to be
+ * called during the init() method of a servlet.
+ *
* @param authzMgrName The authorization manager name
- * @param accessInfo the access information to be initialized. currently it's acl string in the format specified in the authorization manager
+ * @param accessInfo the access information to be initialized. currently
+ * it's acl string in the format specified in the authorization
+ * manager
*/
public void authzMgrAccessInit(String authzMgrInstName, String accessInfo)
- throws EAuthzMgrNotFound, EBaseException {
+ throws EAuthzMgrNotFound, EBaseException {
AuthzManagerProxy proxy = (AuthzManagerProxy)
- mAuthzMgrInsts.get(authzMgrInstName);
+ mAuthzMgrInsts.get(authzMgrInstName);
if (proxy == null) {
throw new EAuthzMgrNotFound(CMS.getUserMessage("CMS_AUTHORIZATION_AUTHZMGR_NOT_FOUND", authzMgrInstName));
@@ -210,21 +209,22 @@ public class AuthzSubsystem implements IAuthzSubsystem {
/**
* Authorization to the named authorization manager instance
+ *
* @param authzMgrName The authorization manager name
* @param authToken the authenticaton token associated with a user
* @param resource the resource protected by the authorization system
- * @param operation the operation for resource protected by the authoriz
- n system
+ * @param operation the operation for resource protected by the authoriz n
+ * system
* @exception EBaseException If an error occurs during authorization.
* @return a authorization token.
*/
public AuthzToken authorize(
- String authzMgrInstName, IAuthToken authToken,
- String resource, String operation)
- throws EAuthzMgrNotFound, EBaseException {
+ String authzMgrInstName, IAuthToken authToken,
+ String resource, String operation)
+ throws EAuthzMgrNotFound, EBaseException {
AuthzManagerProxy proxy = (AuthzManagerProxy)
- mAuthzMgrInsts.get(authzMgrInstName);
+ mAuthzMgrInsts.get(authzMgrInstName);
if (proxy == null) {
throw new EAuthzMgrNotFound(CMS.getUserMessage("CMS_AUTHORIZATION_AUTHZMGR_NOT_FOUND", authzMgrInstName));
@@ -241,15 +241,15 @@ public class AuthzSubsystem implements IAuthzSubsystem {
}
public AuthzToken authorize(
- String authzMgrInstName, IAuthToken authToken, String exp)
- throws EAuthzMgrNotFound, EBaseException {
+ String authzMgrInstName, IAuthToken authToken, String exp)
+ throws EAuthzMgrNotFound, EBaseException {
AuthzManagerProxy proxy = (AuthzManagerProxy)
- mAuthzMgrInsts.get(authzMgrInstName);
+ mAuthzMgrInsts.get(authzMgrInstName);
if (proxy == null) {
throw new EAuthzMgrNotFound(CMS.getUserMessage("CMS_AUTHORIZATION_AUTHZMGR_NOT_FOUND", authzMgrInstName));
- }
+ }
if (!proxy.isEnable()) {
throw new EAuthzMgrNotFound(CMS.getUserMessage("CMS_AUTHORIZATION_AUTHZMGR_NOT_FOUND", authzMgrInstName));
}
@@ -262,13 +262,13 @@ public class AuthzSubsystem implements IAuthzSubsystem {
}
/**
- * Gets configuration parameters for the given
- * authorization manager plugin.
+ * Gets configuration parameters for the given authorization manager plugin.
+ *
* @param implName Name of the authorization plugin.
* @return Hashtable of required parameters.
*/
public String[] getConfigParams(String implName)
- throws EAuthzMgrPluginNotFound, EBaseException {
+ throws EAuthzMgrPluginNotFound, EBaseException {
// is this a registered implname?
AuthzMgrPlugin plugin = (AuthzMgrPlugin) mAuthzMgrPlugins.get(implName);
@@ -287,21 +287,19 @@ public class AuthzSubsystem implements IAuthzSubsystem {
return (authzMgrInst.getConfigParams());
} catch (InstantiationException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_AUTHZ_PLUGIN_NOT_CREATED", e.toString()));
- throw new
- EAuthzException(CMS.getUserMessage("CMS_AUTHORIZATION_LOAD_CLASS_FAIL", className));
+ throw new EAuthzException(CMS.getUserMessage("CMS_AUTHORIZATION_LOAD_CLASS_FAIL", className));
} catch (ClassNotFoundException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_AUTHZ_PLUGIN_NOT_CREATED", e.toString()));
- throw new
- EAuthzException(CMS.getUserMessage("CMS_AUTHORIZATION_LOAD_CLASS_FAIL", className));
+ throw new EAuthzException(CMS.getUserMessage("CMS_AUTHORIZATION_LOAD_CLASS_FAIL", className));
} catch (IllegalAccessException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_AUTHZ_PLUGIN_NOT_CREATED", e.toString()));
- throw new
- EAuthzException(CMS.getUserMessage("CMS_AUTHORIZATION_LOAD_CLASS_FAIL", className));
+ throw new EAuthzException(CMS.getUserMessage("CMS_AUTHORIZATION_LOAD_CLASS_FAIL", className));
}
}
/**
* Add an authorization manager instance.
+ *
* @param name name of the authorization manager instance
* @param authzMgr the authorization manager instance to be added
*/
@@ -311,6 +309,7 @@ public class AuthzSubsystem implements IAuthzSubsystem {
/*
* Removes a authorization manager instance.
+ *
* @param name name of the authorization manager
*/
public void delete(String name) {
@@ -319,6 +318,7 @@ public class AuthzSubsystem implements IAuthzSubsystem {
/**
* Gets the authorization manager instance of the specified name.
+ *
* @param name name of the authorization manager instance
* @return the named authorization manager instance
*/
@@ -362,9 +362,9 @@ public class AuthzSubsystem implements IAuthzSubsystem {
}
/**
- * Retrieve a single authz manager instance
+ * Retrieve a single authz manager instance
*/
-
+
/* getconfigparams above should be recoded to use this func */
public IAuthzManager getAuthzManagerPlugin(String name) {
AuthzMgrPlugin plugin = (AuthzMgrPlugin) mAuthzMgrPlugins.get(name);
@@ -382,16 +382,18 @@ public class AuthzSubsystem implements IAuthzSubsystem {
/**
* Retrieves id (name) of this subsystem.
+ *
* @return name of the authorization subsystem
*/
public String getId() {
return (mId);
}
-
+
/**
* Sets id string to this subsystem.
* <p>
- * Use with caution. Should not do it when sharing with others
+ * Use with caution. Should not do it when sharing with others
+ *
* @param id name to be applied to an authorization sybsystem
*/
public void setId(String id) throws EBaseException {
@@ -402,25 +404,24 @@ public class AuthzSubsystem implements IAuthzSubsystem {
* registers the administration servlet with the administration subsystem.
*/
public void startup() throws EBaseException {
- //remove the log since it's already logged from S_ADMIN
- //String infoMsg = "Authz subsystem administration Servlet registered";
- //log(ILogger.LL_INFO, infoMsg);
+ // remove the log since it's already logged from S_ADMIN
+ // String infoMsg = "Authz subsystem administration Servlet registered";
+ // log(ILogger.LL_INFO, infoMsg);
}
/**
- * shuts down authorization managers one by one.
+ * shuts down authorization managers one by one.
* <P>
*/
public void shutdown() {
- for (Enumeration<String> e = mAuthzMgrInsts.keys();
- e.hasMoreElements();) {
+ for (Enumeration<String> e = mAuthzMgrInsts.keys(); e.hasMoreElements();) {
IAuthzManager mgr = (IAuthzManager) get((String) e.nextElement());
- String infoMsg =
- "Shutting down authz manager instance " + mgr.getName();
+ String infoMsg =
+ "Shutting down authz manager instance " + mgr.getName();
- //log(ILogger.LL_INFO, infoMsg);
+ // log(ILogger.LL_INFO, infoMsg);
mgr.shutdown();
}
@@ -441,7 +442,7 @@ public class AuthzSubsystem implements IAuthzSubsystem {
/**
* Returns the root configuration storage of this system.
* <P>
- *
+ *
* @return configuration store of this subsystem
*/
public IConfigStore getConfigStore() {
@@ -450,6 +451,7 @@ public class AuthzSubsystem implements IAuthzSubsystem {
/**
* gets the named authorization manager
+ *
* @param name of the authorization manager
* @return the named authorization manager
*/
@@ -464,7 +466,7 @@ public class AuthzSubsystem implements IAuthzSubsystem {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_AUTHORIZATION,
- level, msg);
+ level, msg);
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/base/ArgBlock.java b/pki/base/common/src/com/netscape/cmscore/base/ArgBlock.java
index 8f29fc1b..d66059c9 100644
--- a/pki/base/common/src/com/netscape/cmscore/base/ArgBlock.java
+++ b/pki/base/common/src/com/netscape/cmscore/base/ArgBlock.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.base;
-
import java.io.IOException;
import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
@@ -34,12 +33,10 @@ import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IArgBlock;
import com.netscape.certsrv.base.KeyGenInfo;
-
/**
- * This class represents a set of indexed arguments.
- * Each argument is indexed by a key, which can be
- * used during the argument retrieval.
- *
+ * This class represents a set of indexed arguments. Each argument is indexed by
+ * a key, which can be used during the argument retrieval.
+ *
* @version $Revision$, $Date$
*/
public class ArgBlock implements IArgBlock {
@@ -48,48 +45,45 @@ public class ArgBlock implements IArgBlock {
*
*/
private static final long serialVersionUID = -6054531129316353282L;
- /*==========================================================
- * variables
- *==========================================================*/
- public static final String
- CERT_NEW_REQUEST_HEADER = "-----BEGIN NEW CERTIFICATE REQUEST-----";
- public static final String
- CERT_NEW_REQUEST_TRAILER = "-----END NEW CERTIFICATE REQUEST-----";
- public static final String
- CERT_REQUEST_HEADER = "-----BEGIN CERTIFICATE REQUEST-----";
- public static final String
- CERT_REQUEST_TRAILER = "-----END CERTIFICATE REQUEST-----";
- public static final String
- CERT_RENEWAL_HEADER = "-----BEGIN RENEWAL CERTIFICATE REQUEST-----";
- public static final String
- CERT_RENEWAL_TRAILER = "-----END RENEWAL CERTIFICATE REQUEST-----";
+ /*
+ * ========================================================== variables
+ * ==========================================================
+ */
+ public static final String CERT_NEW_REQUEST_HEADER = "-----BEGIN NEW CERTIFICATE REQUEST-----";
+ public static final String CERT_NEW_REQUEST_TRAILER = "-----END NEW CERTIFICATE REQUEST-----";
+ public static final String CERT_REQUEST_HEADER = "-----BEGIN CERTIFICATE REQUEST-----";
+ public static final String CERT_REQUEST_TRAILER = "-----END CERTIFICATE REQUEST-----";
+ public static final String CERT_RENEWAL_HEADER = "-----BEGIN RENEWAL CERTIFICATE REQUEST-----";
+ public static final String CERT_RENEWAL_TRAILER = "-----END RENEWAL CERTIFICATE REQUEST-----";
private Hashtable<String, Object> mArgs = new Hashtable<String, Object>();
- private String mType = "unspecified-argblock";
+ private String mType = "unspecified-argblock";
- /*==========================================================
- * constructors
- *==========================================================*/
+ /*
+ * ========================================================== constructors
+ * ==========================================================
+ */
/**
* Constructs an argument block with the given hashtable values.
+ *
* @param realm the type of argblock - used for debugging the values
*/
public ArgBlock(String realm, Hashtable<String, String> httpReq) {
- mType = realm;
- populate(httpReq);
- }
-
+ mType = realm;
+ populate(httpReq);
+ }
+
/**
* Constructs an argument block with the given hashtable values.
- *
+ *
* @param httpReq hashtable keys and values
*/
public ArgBlock(Hashtable<String, String> httpReq) {
- populate(httpReq);
- }
+ populate(httpReq);
+ }
- private void populate(Hashtable<String, String> httpReq) {
+ private void populate(Hashtable<String, String> httpReq) {
// Add all parameters from the request
Enumeration<String> e = httpReq.keys();
@@ -109,18 +103,19 @@ public class ArgBlock implements IArgBlock {
public ArgBlock() {
}
- /*==========================================================
- * public methods
- *==========================================================*/
+ /*
+ * ========================================================== public methods
+ * ==========================================================
+ */
/**
* Checks if this argument block contains the given key.
- *
+ *
* @param n key
* @return true if key is present
*/
public boolean isValuePresent(String n) {
- CMS.traceHashKey(mType, n);
+ CMS.traceHashKey(mType, n);
if (mArgs.get(n) != null) {
return true;
} else {
@@ -130,7 +125,7 @@ public class ArgBlock implements IArgBlock {
/**
* Adds string-based value into this argument block.
- *
+ *
* @param n key
* @param v value
* @return value
@@ -145,14 +140,14 @@ public class ArgBlock implements IArgBlock {
/**
* Retrieves argument value as string.
- *
+ *
* @param n key
* @return argument value as string
* @exception EBaseException failed to retrieve value
*/
public String getValueAsString(String n) throws EBaseException {
- String t= (String)mArgs.get(n);
- CMS.traceHashKey(mType, n, t);
+ String t = (String) mArgs.get(n);
+ CMS.traceHashKey(mType, n, t);
if (t != null) {
return t;
@@ -163,14 +158,14 @@ public class ArgBlock implements IArgBlock {
/**
* Retrieves argument value as string.
- *
+ *
* @param n key
* @param def default value to be returned if key is not present
* @return argument value as string
*/
public String getValueAsString(String n, String def) {
String val = (String) mArgs.get(n);
- CMS.traceHashKey(mType, n, val, def);
+ CMS.traceHashKey(mType, n, val, def);
if (val != null) {
return val;
@@ -181,14 +176,14 @@ public class ArgBlock implements IArgBlock {
/**
* Retrieves argument value as integer.
- *
+ *
* @param n key
* @return argument value as int
* @exception EBaseException failed to retrieve value
*/
public int getValueAsInt(String n) throws EBaseException {
if (mArgs.get(n) != null) {
- CMS.traceHashKey(mType, n, (String)mArgs.get(n));
+ CMS.traceHashKey(mType, n, (String) mArgs.get(n));
try {
return new Integer((String) mArgs.get(n)).intValue();
} catch (NumberFormatException e) {
@@ -196,20 +191,20 @@ public class ArgBlock implements IArgBlock {
CMS.getUserMessage("CMS_BASE_INVALID_ATTR_TYPE", n, e.toString()));
}
} else {
- CMS.traceHashKey(mType, n, "<notpresent>");
+ CMS.traceHashKey(mType, n, "<notpresent>");
throw new EBaseException(CMS.getUserMessage("CMS_BASE_ATTRIBUTE_NOT_FOUND", n));
}
}
/**
* Retrieves argument value as integer.
- *
+ *
* @param n key
* @param def default value to be returned if key is not present
* @return argument value as int
*/
public int getValueAsInt(String n, int def) {
- CMS.traceHashKey(mType, n, (String)mArgs.get(n), ""+def);
+ CMS.traceHashKey(mType, n, (String) mArgs.get(n), "" + def);
if (mArgs.get(n) != null) {
try {
return new Integer((String) mArgs.get(n)).intValue();
@@ -223,13 +218,13 @@ public class ArgBlock implements IArgBlock {
/**
* Retrieves argument value as big integer.
- *
+ *
* @param n key
* @return argument value as big integer
* @exception EBaseException failed to retrieve value
*/
public BigInteger getValueAsBigInteger(String n)
- throws EBaseException {
+ throws EBaseException {
String v = (String) mArgs.get(n);
if (v != null) {
@@ -250,7 +245,7 @@ public class ArgBlock implements IArgBlock {
/**
* Retrieves argument value as big integer.
- *
+ *
* @param n key
* @param def default value to be returned if key is not present
* @return argument value as big integer
@@ -265,7 +260,7 @@ public class ArgBlock implements IArgBlock {
/**
* Retrieves argument value as object
- *
+ *
* @param n key
* @return argument value as object
* @exception EBaseException failed to retrieve value
@@ -280,7 +275,7 @@ public class ArgBlock implements IArgBlock {
/**
* Retrieves argument value as object
- *
+ *
* @param n key
* @param def default value to be returned if key is not present
* @return argument value as object
@@ -295,18 +290,18 @@ public class ArgBlock implements IArgBlock {
/**
* Gets boolean value. They should be "true" or "false".
- *
+ *
* @param name name of the input type
* @return boolean type: <code>true</code> or <code>false</code>
* @exception EBaseException failed to retrieve value
*/
- public boolean getValueAsBoolean(String name) throws EBaseException {
+ public boolean getValueAsBoolean(String name) throws EBaseException {
String val = (String) mArgs.get(name);
- CMS.traceHashKey(mType, name, val);
+ CMS.traceHashKey(mType, name, val);
if (val != null) {
- if (val.equalsIgnoreCase("true") ||
- val.equalsIgnoreCase("on"))
+ if (val.equalsIgnoreCase("true") ||
+ val.equalsIgnoreCase("on"))
return true;
else
return false;
@@ -317,34 +312,34 @@ public class ArgBlock implements IArgBlock {
/**
* Gets boolean value. They should be "true" or "false".
- *
+ *
* @param name name of the input type
* @return boolean type: <code>true</code> or <code>false</code>
*/
public boolean getValueAsBoolean(String name, boolean def) {
boolean val;
- try {
- val = getValueAsBoolean(name);
+ try {
+ val = getValueAsBoolean(name);
return val;
- } catch (EBaseException e) {
- return def;
+ } catch (EBaseException e) {
+ return def;
}
}
/**
* Gets KeyGenInfo
- *
+ *
* @param name name of the input type
* @param verify true if signature validation is required
* @exception EBaseException
* @return KeyGenInfo object
*/
public KeyGenInfo getValueAsKeyGenInfo(String name, KeyGenInfo def)
- throws EBaseException {
+ throws EBaseException {
KeyGenInfo keyGenInfo;
- CMS.traceHashKey(mType, name);
+ CMS.traceHashKey(mType, name);
if (mArgs.get(name) != null) {
try {
keyGenInfo = new KeyGenInfo((String) mArgs.get(name));
@@ -359,9 +354,9 @@ public class ArgBlock implements IArgBlock {
}
/**
- * Gets PKCS10 request. This pkcs10 attribute does not
- * contain header information.
- *
+ * Gets PKCS10 request. This pkcs10 attribute does not contain header
+ * information.
+ *
* @param name name of the input type
* @return pkcs10 request
* @exception EBaseException failed to retrieve value
@@ -370,22 +365,22 @@ public class ArgBlock implements IArgBlock {
PKCS10 request;
if (mArgs.get(name) != null) {
- CMS.traceHashKey(mType, name, (String)mArgs.get(name));
+ CMS.traceHashKey(mType, name, (String) mArgs.get(name));
String tempStr = unwrap((String) mArgs.get(name), false);
if (tempStr == null) {
throw new EBaseException(
- CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE", name, "Empty Content"));
+ CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE", name, "Empty Content"));
}
try {
request = decodePKCS10(tempStr);
} catch (Exception e) {
throw new EBaseException(
- CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE", name, e.toString()));
+ CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE", name, e.toString()));
}
} else {
- CMS.traceHashKey(mType, name, "<notpresent>");
+ CMS.traceHashKey(mType, name, "<notpresent>");
throw new EBaseException(CMS.getUserMessage("CMS_BASE_ATTRIBUTE_NOT_FOUND", name));
}
@@ -393,19 +388,19 @@ public class ArgBlock implements IArgBlock {
}
/**
- * Gets PKCS10 request. This pkcs10 attribute does not
- * contain header information.
- *
+ * Gets PKCS10 request. This pkcs10 attribute does not contain header
+ * information.
+ *
* @param name name of the input type
* @param def default PKCS10
* @return pkcs10 request
* @exception EBaseException failed to retrieve value
*/
public PKCS10 getValueAsRawPKCS10(String name, PKCS10 def)
- throws EBaseException {
+ throws EBaseException {
PKCS10 request;
- CMS.traceHashKey(mType, name);
+ CMS.traceHashKey(mType, name);
if (mArgs.get(name) != null) {
String tempStr = unwrap((String) mArgs.get(name), false);
@@ -426,30 +421,30 @@ public class ArgBlock implements IArgBlock {
/**
* Retrieves PKCS10
- *
- * @param name name of the input type
+ *
+ * @param name name of the input type
* @param checkheader true if header must be present
* @return PKCS10 object
* @exception EBaseException failed to retrieve value
*/
- public PKCS10 getValueAsPKCS10(String name, boolean checkheader)
- throws EBaseException {
+ public PKCS10 getValueAsPKCS10(String name, boolean checkheader)
+ throws EBaseException {
PKCS10 request;
- CMS.traceHashKey(mType, name);
+ CMS.traceHashKey(mType, name);
if (mArgs.get(name) != null) {
String tempStr = unwrap((String) mArgs.get(name), checkheader);
if (tempStr == null) {
throw new EBaseException(
- CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE", name, "Empty Content"));
+ CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE", name, "Empty Content"));
}
try {
request = decodePKCS10(tempStr);
} catch (Exception e) {
throw new EBaseException(
- CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE", name, e.toString()));
+ CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE", name, e.toString()));
}
} else {
throw new EBaseException(CMS.getUserMessage("CMS_BASE_ATTRIBUTE_NOT_FOUND", name));
@@ -460,19 +455,19 @@ public class ArgBlock implements IArgBlock {
/**
* Retrieves PKCS10
- *
- * @param name name of the input type
+ *
+ * @param name name of the input type
* @param checkheader true if header must be present
* @param def default PKCS10
- * @return PKCS10 object
+ * @return PKCS10 object
* @exception EBaseException
*/
public PKCS10 getValueAsPKCS10(
- String name, boolean checkheader, PKCS10 def)
- throws EBaseException {
+ String name, boolean checkheader, PKCS10 def)
+ throws EBaseException {
PKCS10 request;
- CMS.traceHashKey(mType, name);
+ CMS.traceHashKey(mType, name);
if (mArgs.get(name) != null) {
@@ -495,17 +490,17 @@ public class ArgBlock implements IArgBlock {
/**
* Retrieves PKCS10
- *
- * @param name name of the input type
+ *
+ * @param name name of the input type
* @param def default PKCS10
- * @return PKCS10 object
+ * @return PKCS10 object
* @exception EBaseException
*/
- public PKCS10 getValuePKCS10(String name, PKCS10 def)
- throws EBaseException {
+ public PKCS10 getValuePKCS10(String name, PKCS10 def)
+ throws EBaseException {
PKCS10 request;
String p10b64 = (String) mArgs.get(name);
- CMS.traceHashKey(mType, name);
+ CMS.traceHashKey(mType, name);
if (p10b64 != null) {
@@ -522,7 +517,7 @@ public class ArgBlock implements IArgBlock {
/**
* Sets argument into this block.
- *
+ *
* @param name key
* @param ob value
*/
@@ -532,18 +527,18 @@ public class ArgBlock implements IArgBlock {
/**
* Retrieves argument.
- *
+ *
* @param name key
* @return object value
*/
public Object get(String name) {
- CMS.traceHashKey(mType, name);
+ CMS.traceHashKey(mType, name);
return mArgs.get(name);
}
/**
* Deletes argument by the given key.
- *
+ *
* @param name key
*/
public void delete(String name) {
@@ -552,7 +547,7 @@ public class ArgBlock implements IArgBlock {
/**
* Retrieves a list of argument keys.
- *
+ *
* @return a list of string-based keys
*/
public Enumeration<String> getElements() {
@@ -561,7 +556,7 @@ public class ArgBlock implements IArgBlock {
/**
* Retrieves a list of argument keys.
- *
+ *
* @return a list of string-based keys
*/
public Enumeration<String> elements() {
@@ -570,7 +565,7 @@ public class ArgBlock implements IArgBlock {
/**
* Adds long-type arguments to this block.
- *
+ *
* @param n key
* @param v value
* @return value
@@ -581,7 +576,7 @@ public class ArgBlock implements IArgBlock {
/**
* Adds integer-type arguments to this block.
- *
+ *
* @param n key
* @param v value
* @return value
@@ -592,7 +587,7 @@ public class ArgBlock implements IArgBlock {
/**
* Adds boolean-type arguments to this block.
- *
+ *
* @param n key
* @param v value
* @return value
@@ -607,7 +602,7 @@ public class ArgBlock implements IArgBlock {
/**
* Adds integer-type arguments to this block.
- *
+ *
* @param n key
* @param v value
* @param radix radix
@@ -617,20 +612,20 @@ public class ArgBlock implements IArgBlock {
return mArgs.put(n, v.toString(radix));
}
- /*==========================================================
- * private methods
- *==========================================================*/
-
+ /*
+ * ========================================================== private
+ * methods==========================================================
+ */
/**
* Unwrap PKCS10 Package
- *
+ *
* @param request string formated PKCS10 request
* @exception EBaseException
* @return Base64Encoded PKCS10 request
*/
private String unwrap(String request, boolean checkHeader)
- throws EBaseException {
+ throws EBaseException {
String unwrapped;
String header = null;
int head = -1;
@@ -655,7 +650,7 @@ public class ArgBlock implements IArgBlock {
// header.
if (!(head == -1 && trail == -1)) {
header = CERT_REQUEST_HEADER;
-
+
}
}
@@ -695,22 +690,22 @@ public class ArgBlock implements IArgBlock {
/**
* Decode Der encoded PKCS10 certifictae Request
- *
+ *
* @param base64Request Base64 Encoded Certificate Request
* @exception Exception
* @return PKCS10
*/
private PKCS10 decodePKCS10(String base64Request)
- throws EBaseException {
+ throws EBaseException {
PKCS10 pkcs10 = null;
try {
byte[] decodedBytes = com.netscape.osutil.OSUtil.AtoB(base64Request);
pkcs10 = new PKCS10(decodedBytes);
- } catch (NoSuchProviderException e) {
+ } catch (NoSuchProviderException e) {
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR", e.toString()));
- } catch (IOException e) {
+ } catch (IOException e) {
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR", e.toString()));
} catch (SignatureException e) {
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR", e.toString()));
diff --git a/pki/base/common/src/com/netscape/cmscore/base/FileConfigStore.java b/pki/base/common/src/com/netscape/cmscore/base/FileConfigStore.java
index a4b37114..ec7096c0 100644
--- a/pki/base/common/src/com/netscape/cmscore/base/FileConfigStore.java
+++ b/pki/base/common/src/com/netscape/cmscore/base/FileConfigStore.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.base;
-
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
@@ -33,21 +32,19 @@ import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.cmsutil.util.Utils;
-
/**
- * FileConfigStore:
- * Extends HashConfigStore with methods to load/save from/to file for
- * persistent storage. This is a configuration store agent who
- * reads data from a file.
+ * FileConfigStore: Extends HashConfigStore with methods to load/save from/to
+ * file for persistent storage. This is a configuration store agent who reads
+ * data from a file.
* <P>
- * Note that a LdapConfigStore can be implemented so that it reads
- * the configuration stores from the Ldap directory.
+ * Note that a LdapConfigStore can be implemented so that it reads the
+ * configuration stores from the Ldap directory.
* <P>
*
* @version $Revision$, $Date$
* @see PropConfigStore
*/
-public class FileConfigStore extends PropConfigStore implements
+public class FileConfigStore extends PropConfigStore implements
IConfigStore {
/**
@@ -59,7 +56,7 @@ public class FileConfigStore extends PropConfigStore implements
/**
* Constructs a file configuration store.
* <P>
- *
+ *
* @param fileName file name
* @exception EBaseException failed to create file configuration
*/
@@ -67,7 +64,7 @@ public class FileConfigStore extends PropConfigStore implements
super(null); // top-level store without a name
mFile = new File(fileName);
if (!mFile.exists()) {
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_NO_CONFIG_FILE",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_NO_CONFIG_FILE",
mFile.getPath()));
}
load(fileName);
@@ -76,7 +73,7 @@ public class FileConfigStore extends PropConfigStore implements
/**
* Loads property file into memory.
* <P>
- *
+ *
* @param fileName file name
* @exception EBaseException failed to load configuration
*/
@@ -93,11 +90,11 @@ public class FileConfigStore extends PropConfigStore implements
/**
* The original config file is copied to
- * <filename>.<current_time_in_milliseconds>.
- * Commits the current properties to the configuration file.
+ * <filename>.<current_time_in_milliseconds>. Commits the current properties
+ * to the configuration file.
* <P>
- *
- * @param backup
+ *
+ * @param backup
*/
public void commit(boolean createBackup) throws EBaseException {
if (createBackup) {
@@ -105,57 +102,56 @@ public class FileConfigStore extends PropConfigStore implements
Long.toString(System.currentTimeMillis()));
try {
- if( Utils.isNT() ) {
+ if (Utils.isNT()) {
// NT is very picky on the path
- Utils.exec( "copy " +
- mFile.getAbsolutePath().replace( '/', '\\' ) +
+ Utils.exec("copy " +
+ mFile.getAbsolutePath().replace('/', '\\') +
" " +
- newName.getAbsolutePath().replace( '/',
- '\\' ) );
+ newName.getAbsolutePath().replace('/',
+ '\\'));
} else {
// Create a copy of the original file which
// preserves the original file permissions.
- Utils.exec( "cp -p " + mFile.getAbsolutePath() + " " +
- newName.getAbsolutePath() );
+ Utils.exec("cp -p " + mFile.getAbsolutePath() + " " +
+ newName.getAbsolutePath());
}
// Proceed only if the backup copy was successful.
- if( !newName.exists() ) {
- throw new EBaseException( "backup copy failed" );
+ if (!newName.exists()) {
+ throw new EBaseException("backup copy failed");
} else {
// Make certain that the backup file has
// the correct permissions.
- if( !Utils.isNT() ) {
- Utils.exec( "chmod 00660 " + newName.getAbsolutePath() );
+ if (!Utils.isNT()) {
+ Utils.exec("chmod 00660 " + newName.getAbsolutePath());
}
}
- } catch( EBaseException e ) {
- throw new EBaseException( "backup copy failed" );
+ } catch (EBaseException e) {
+ throw new EBaseException("backup copy failed");
}
}
// Overwrite the contents of the original file
// to preserve the original file permissions.
- save( mFile.getPath() );
+ save(mFile.getPath());
try {
// Make certain that the original file retains
// the correct permissions.
- if( !Utils.isNT() ) {
- Utils.exec( "chmod 00660 " + mFile.getCanonicalPath() );
+ if (!Utils.isNT()) {
+ Utils.exec("chmod 00660 " + mFile.getCanonicalPath());
}
- } catch( Exception e ) {
+ } catch (Exception e) {
}
}
/**
* Saves in-memory properties to a specified file.
* <P>
- * Note that the superclass's save is synchronized. It
- * means no properties can be altered (inserted) at
- * the saving time.
+ * Note that the superclass's save is synchronized. It means no properties
+ * can be altered (inserted) at the saving time.
* <P>
- *
+ *
* @param fileName filename
* @exception EBaseException failed to save configuration
*/
@@ -173,7 +169,7 @@ public class FileConfigStore extends PropConfigStore implements
}
private void printSubStore(PrintWriter writer, IConfigStore store,
- String name) throws EBaseException,
+ String name) throws EBaseException,
IOException {
// print keys
Enumeration e0 = store.getPropertyNames();
@@ -220,7 +216,7 @@ public class FileConfigStore extends PropConfigStore implements
}
v.removeElementAt(j);
printSubStore(writer, store.getSubStore(pname), name +
- pname + ".");
+ pname + ".");
}
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/base/JDialogPasswordCallback.java b/pki/base/common/src/com/netscape/cmscore/base/JDialogPasswordCallback.java
index cd695967..9e7f6c8e 100644
--- a/pki/base/common/src/com/netscape/cmscore/base/JDialogPasswordCallback.java
+++ b/pki/base/common/src/com/netscape/cmscore/base/JDialogPasswordCallback.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.base;
-
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
@@ -44,19 +43,18 @@ import org.mozilla.jss.util.Password;
import org.mozilla.jss.util.PasswordCallback;
import org.mozilla.jss.util.PasswordCallbackInfo;
-
/**
* A class to retrieve passwords through a modal Java dialog box
*/
public class JDialogPasswordCallback implements PasswordCallback {
public Password getPasswordFirstAttempt(PasswordCallbackInfo info)
- throws PasswordCallback.GiveUpException {
+ throws PasswordCallback.GiveUpException {
return getPW(info, false);
}
public Password getPasswordAgain(PasswordCallbackInfo info)
- throws PasswordCallback.GiveUpException {
+ throws PasswordCallback.GiveUpException {
return getPW(info, true);
}
@@ -88,27 +86,27 @@ public class JDialogPasswordCallback implements PasswordCallback {
}
/**
- * This method does the work of displaying the dialog box,
- * extracting the information, and returning it.
+ * This method does the work of displaying the dialog box, extracting the
+ * information, and returning it.
*/
private Password getPW(PasswordCallbackInfo info, boolean retry)
- throws PasswordCallback.GiveUpException {
+ throws PasswordCallback.GiveUpException {
// These need to final so they can be accessed from action listeners
final PWHolder pwHolder = new PWHolder();
final JFrame f = new JFrame("Password Dialog");
final JPasswordField pwField = new JPasswordField(15);
- ///////////////////////////////////////////////////
+ // /////////////////////////////////////////////////
// Panel
- ///////////////////////////////////////////////////
+ // /////////////////////////////////////////////////
JPanel contentPane = new JPanel(new GridBagLayout());
contentPane.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
GridBagConstraints c = new GridBagConstraints();
- ////////////////////////////////////////////////////
+ // //////////////////////////////////////////////////
// Labels
- ////////////////////////////////////////////////////
+ // //////////////////////////////////////////////////
if (retry) {
JLabel warning = new JLabel("Password incorrect.");
@@ -119,46 +117,46 @@ public class JDialogPasswordCallback implements PasswordCallback {
c.gridwidth = GridBagConstraints.REMAINDER;
// Setting this to NULL causes nasty Exception stack traces
// to be printed, although the program still seems to work
- //warning.setHighlighter(null);
+ // warning.setHighlighter(null);
contentPane.add(warning, c);
}
-
+
String prompt = getPrompt(info);
JLabel label = new JLabel(prompt);
label.setForeground(Color.black);
// Setting this to NULL causes nasty Exception stack traces
// to be printed, although the program still seems to work
- //label.setHighlighter(null);
+ // label.setHighlighter(null);
resetGBC(c);
c.anchor = GridBagConstraints.NORTHWEST;
c.gridwidth = GridBagConstraints.REMAINDER;
contentPane.add(label, c);
- ///////////////////////////////////////////////////
+ // /////////////////////////////////////////////////
// Password text field
- ///////////////////////////////////////////////////
+ // /////////////////////////////////////////////////
// Listener for the text field
ActionListener getPasswordListener = new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- //input = (JPasswordField)e.getSource();
+ public void actionPerformed(ActionEvent e) {
+ // input = (JPasswordField)e.getSource();
- // XXX!!! Change to char[] in JDK 1.2
- String pwString = pwField.getText();
+ // XXX!!! Change to char[] in JDK 1.2
+ String pwString = pwField.getText();
- pwHolder.password = new Password(pwString.toCharArray());
- pwHolder.cancelled = false;
- f.dispose();
- }
- };
+ pwHolder.password = new Password(pwString.toCharArray());
+ pwHolder.cancelled = false;
+ f.dispose();
+ }
+ };
// There is a bug in JPasswordField. The cursor is advanced by the
// width of the character you type, but a '*' is echoed, so the
// cursor does not stay lined up with the end of the text.
// We use a monospaced font to workaround this.
- pwField.setFont(new Font("Monospaced", Font.PLAIN,
+ pwField.setFont(new Font("Monospaced", Font.PLAIN,
pwField.getFont().getSize()));
pwField.setEchoChar('*');
pwField.addActionListener(getPasswordListener);
@@ -167,12 +165,12 @@ public class JDialogPasswordCallback implements PasswordCallback {
c.fill = GridBagConstraints.NONE;
c.insets = new Insets(16, 0, 0, 0);
c.gridwidth = GridBagConstraints.REMAINDER;
- //c.gridy++;
+ // c.gridy++;
contentPane.add(pwField, c);
- ///////////////////////////////////////////////////
+ // /////////////////////////////////////////////////
// Cancel button
- ///////////////////////////////////////////////////
+ // /////////////////////////////////////////////////
JPanel buttonPanel = new JPanel(new GridBagLayout());
@@ -188,11 +186,11 @@ public class JDialogPasswordCallback implements PasswordCallback {
JButton cancel = new JButton("Cancel");
ActionListener buttonListener = new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- pwHolder.cancelled = true;
- f.dispose();
- }
- };
+ public void actionPerformed(ActionEvent e) {
+ pwHolder.cancelled = true;
+ f.dispose();
+ }
+ };
cancel.addActionListener(buttonListener);
resetGBC(c);
@@ -211,16 +209,16 @@ public class JDialogPasswordCallback implements PasswordCallback {
c.insets = new Insets(0, 0, 0, 0);
contentPane.add(buttonPanel, c);
- ///////////////////////////////////////////////////
+ // /////////////////////////////////////////////////
// Create modal dialog
- ///////////////////////////////////////////////////
+ // /////////////////////////////////////////////////
JDialog d = new JDialog(f, "Fedora Certificate System", true);
WindowListener windowListener = new WindowAdapter() {
- public void windowOpened(WindowEvent e) {
- pwField.requestFocus();
- }
- };
+ public void windowOpened(WindowEvent e) {
+ pwField.requestFocus();
+ }
+ };
d.addWindowListener(windowListener);
@@ -230,17 +228,17 @@ public class JDialogPasswordCallback implements PasswordCallback {
Dimension paneSize = d.getSize();
d.setLocation((screenSize.width - paneSize.width) / 2,
- (screenSize.height - paneSize.height) / 2);
+ (screenSize.height - paneSize.height) / 2);
d.getRootPane().setDefaultButton(ok);
// toFront seems to cause the dialog to go blank on unix!
- //d.toFront();
+ // d.toFront();
d.show();
- ///////////////////////////////////////////////////
+ // /////////////////////////////////////////////////
// Return results
- ///////////////////////////////////////////////////
+ // /////////////////////////////////////////////////
if (pwHolder.cancelled) {
throw new PasswordCallback.GiveUpException();
}
@@ -254,7 +252,7 @@ public class JDialogPasswordCallback implements PasswordCallback {
CryptoManager manager;
CryptoManager.InitializationValues iv = new
- CryptoManager.InitializationValues(args[0]);
+ CryptoManager.InitializationValues(args[0]);
CryptoManager.initialize(iv);
manager = CryptoManager.getInstance();
diff --git a/pki/base/common/src/com/netscape/cmscore/base/PropConfigStore.java b/pki/base/common/src/com/netscape/cmscore/base/PropConfigStore.java
index be8e7007..9b7b74ad 100644
--- a/pki/base/common/src/com/netscape/cmscore/base/PropConfigStore.java
+++ b/pki/base/common/src/com/netscape/cmscore/base/PropConfigStore.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.base;
-
import java.io.ByteArrayOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
@@ -38,23 +37,22 @@ import com.netscape.certsrv.base.EPropertyNotFound;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.base.ISourceConfigStore;
-
/**
- * A class represents a in-memory configuration store.
- * Note this class takes advantage of the recursive nature of
- * property names. The current property prefix is kept in
- * mStoreName and the mSource usually points back to another
+ * A class represents a in-memory configuration store. Note this class takes
+ * advantage of the recursive nature of property names. The current property
+ * prefix is kept in mStoreName and the mSource usually points back to another
* occurance of the same PropConfigStore, with longer mStoreName. IE
+ *
* <PRE>
- * cms.ca0.http.service0 -> mSource=PropConfigStore ->
- * cms.ca0.http -> mSource=PropConfigStore ->
- * cms.ca0 -> mSource=PropConfigStore ->
+ * cms.ca0.http.service0 -> mSource=PropConfigStore ->
+ * cms.ca0.http -> mSource=PropConfigStore ->
+ * cms.ca0 -> mSource=PropConfigStore ->
* cms -> mSource=SourceConfigStore -> Properties
* </PRE>
- * The chain ends when the store name is reduced down to it's original
- * value.
+ *
+ * The chain ends when the store name is reduced down to it's original value.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class PropConfigStore implements IConfigStore, Cloneable {
@@ -76,14 +74,13 @@ public class PropConfigStore implements IConfigStore, Cloneable {
*/
protected ISourceConfigStore mSource = null;
- private static String mDebugType="CS.cfg";
+ private static String mDebugType = "CS.cfg";
/**
- * Constructs a property configuration store. This must
- * be a brand new store without properties. The subclass
- * must be a ISourceConfigStore.
+ * Constructs a property configuration store. This must be a brand new store
+ * without properties. The subclass must be a ISourceConfigStore.
* <P>
- *
+ *
* @param storeName property store name
* @exception EBaseException failed to create configuration
*/
@@ -93,12 +90,11 @@ public class PropConfigStore implements IConfigStore, Cloneable {
}
/**
- * Constructs a configuration store. The constructor is
- * a helper class for substores. Source is the one
- * that stores all the parameters. Each substore only
- * store a substore name, and a reference to the source.
+ * Constructs a configuration store. The constructor is a helper class for
+ * substores. Source is the one that stores all the parameters. Each
+ * substore only store a substore name, and a reference to the source.
* <P>
- *
+ *
* @param storeName store name
* @param prop list of properties
* @exception EBaseException failed to create configuration
@@ -111,7 +107,7 @@ public class PropConfigStore implements IConfigStore, Cloneable {
/**
* Returns the name of this store.
* <P>
- *
+ *
* @return store name
*/
public String getName() {
@@ -121,7 +117,7 @@ public class PropConfigStore implements IConfigStore, Cloneable {
/**
* Retrieves a property from the configuration file.
* <P>
- *
+ *
* @param name property name
* @return property value
*/
@@ -130,10 +126,10 @@ public class PropConfigStore implements IConfigStore, Cloneable {
}
/**
- * Retrieves a property from the configuration file. Does not prepend
- * the config store name to the property.
+ * Retrieves a property from the configuration file. Does not prepend the
+ * config store name to the property.
* <P>
- *
+ *
* @param name property name
* @return property value
*/
@@ -142,11 +138,10 @@ public class PropConfigStore implements IConfigStore, Cloneable {
}
/**
- * Puts a property into the configuration file. The
- * values wont be updated to the file until save
- * method is invoked.
+ * Puts a property into the configuration file. The values wont be updated
+ * to the file until save method is invoked.
* <P>
- *
+ *
* @param name property name
* @param value property value
*/
@@ -156,16 +151,17 @@ public class PropConfigStore implements IConfigStore, Cloneable {
/**
* Removes a property from the configuration file.
- *
+ *
* @param name property name
*/
public void remove(String name) {
((SourceConfigStore) mSource).remove(getFullName(name));
- }
+ }
/**
* Returns an enumeration of the config store's keys, hidding the store
* name.
+ *
* @see java.util.Hashtable#elements
* @see java.util.Enumeration
*/
@@ -178,7 +174,7 @@ public class PropConfigStore implements IConfigStore, Cloneable {
/**
* Retrieves the hashtable where all the properties are kept.
- *
+ *
* @return hashtable
*/
public Hashtable hashtable() {
@@ -199,16 +195,16 @@ public class PropConfigStore implements IConfigStore, Cloneable {
}
/**
- * Fills the given hash table with all key/value pairs in the current
- * config store, removing the config store name prefix
+ * Fills the given hash table with all key/value pairs in the current config
+ * store, removing the config store name prefix
* <P>
- *
+ *
* @param h the hashtable
*/
private synchronized void enumerate(Hashtable h) {
Enumeration e = mSource.keys();
// We only want the keys which match the current substore name
- // without the current substore prefix. This code works even
+ // without the current substore prefix. This code works even
// if mStoreName is null.
String fullName = getFullName("");
int kIndex = fullName.length();
@@ -224,7 +220,7 @@ public class PropConfigStore implements IConfigStore, Cloneable {
/**
* Reads a config store from an input stream.
- *
+ *
* @param in input stream where properties are located
* @exception IOException failed to load
*/
@@ -234,7 +230,7 @@ public class PropConfigStore implements IConfigStore, Cloneable {
/**
* Stores this config store to the specified output stream.
- *
+ *
* @param out outputstream where the properties are saved
* @param header optional header information to be saved
*/
@@ -244,7 +240,7 @@ public class PropConfigStore implements IConfigStore, Cloneable {
/**
* Retrieves a property value.
- *
+ *
* @param name property key
* @return property value
* @exception EBaseException failed to retrieve value
@@ -253,12 +249,12 @@ public class PropConfigStore implements IConfigStore, Cloneable {
String str = (String) get(name);
if (str == null) {
- CMS.traceHashKey(mDebugType,getFullName(name),"<notpresent>");
+ CMS.traceHashKey(mDebugType, getFullName(name), "<notpresent>");
throw new EPropertyNotFound(CMS.getUserMessage("CMS_BASE_GET_PROPERTY_FAILED", getName() + "." + name));
}
- // should we check for empty string ?
+ // should we check for empty string ?
// if (str.length() == 0) {
- // throw new EPropertyNotDefined(getName() + "." + name);
+ // throw new EPropertyNotDefined(getName() + "." + name);
// }
String ret = null;
@@ -267,14 +263,14 @@ public class PropConfigStore implements IConfigStore, Cloneable {
} catch (java.io.UnsupportedEncodingException e) {
throw new EBaseException(CMS.getUserMessage("CMS_BASE_UTF8_NOT_SUPPORTED"));
}
- CMS.traceHashKey(mDebugType,getFullName(name),ret);
+ CMS.traceHashKey(mDebugType, getFullName(name), ret);
return ret;
}
/**
* Retrieves a String from the configuration file.
* <P>
- *
+ *
* @param name property name
* @param defval the default object to return if name does not exist
* @return property value
@@ -287,13 +283,13 @@ public class PropConfigStore implements IConfigStore, Cloneable {
} catch (EPropertyNotFound e) {
val = defval;
}
- CMS.traceHashKey(mDebugType,getFullName(name),val,defval);
+ CMS.traceHashKey(mDebugType, getFullName(name), val, defval);
return val;
}
/**
* Puts property value into this configuration store.
- *
+ *
* @param name property key
* @param value property value
*/
@@ -304,17 +300,17 @@ public class PropConfigStore implements IConfigStore, Cloneable {
/**
* Retrieves a byte array from the configuration file.
* <P>
- *
+ *
* @param name property name
* @exception IllegalArgumentException if name is not set or is null.
- *
+ *
* @return property value
*/
public byte[] getByteArray(String name) throws EBaseException {
byte[] arr = getByteArray(name, new byte[0]);
if (arr.length == 0) {
- CMS.traceHashKey(mDebugType,getFullName(name),"<notpresent>");
+ CMS.traceHashKey(mDebugType, getFullName(name), "<notpresent>");
throw new EPropertyNotFound(CMS.getUserMessage("CMS_BASE_GET_PROPERTY_FAILED", getName() + "." + name));
}
return arr;
@@ -323,34 +319,32 @@ public class PropConfigStore implements IConfigStore, Cloneable {
/**
* Retrieves a byte array from the configuration file.
* <P>
- *
+ *
* @param name property name
- * @param defval the default byte array to return if name does
- * not exist
- *
+ * @param defval the default byte array to return if name does not exist
+ *
* @return property value
*/
- public byte[] getByteArray(String name, byte defval[])
- throws EBaseException {
+ public byte[] getByteArray(String name, byte defval[])
+ throws EBaseException {
String str = (String) get(name);
- byte returnval;
+ byte returnval;
- if (str == null || str.length() == 0) {
- CMS.traceHashKey(mDebugType,getFullName(name),
- "<notpresent>","<bytearray>");
- return defval;
- }
- else {
- CMS.traceHashKey(mDebugType,getFullName(name),
- "<bytearray>","<bytearray>");
- return com.netscape.osutil.OSUtil.AtoB(str);
- }
+ if (str == null || str.length() == 0) {
+ CMS.traceHashKey(mDebugType, getFullName(name),
+ "<notpresent>", "<bytearray>");
+ return defval;
+ } else {
+ CMS.traceHashKey(mDebugType, getFullName(name),
+ "<bytearray>", "<bytearray>");
+ return com.netscape.osutil.OSUtil.AtoB(str);
+ }
}
/**
* Puts byte array into this configuration store.
- *
+ *
* @param name property key
* @param value byte array
*/
@@ -368,13 +362,13 @@ public class PropConfigStore implements IConfigStore, Cloneable {
put(name, output.toString("8859_1"));
} catch (IOException e) {
System.out.println("Warning: base-64 encoding of configuration " +
- "information failed");
+ "information failed");
}
}
/**
* Retrieves boolean-based property value.
- *
+ *
* @param name property key
* @return boolean value
* @exception EBaseException failed to retrieve
@@ -383,7 +377,7 @@ public class PropConfigStore implements IConfigStore, Cloneable {
String value = (String) get(name);
if (value == null) {
- CMS.traceHashKey(mDebugType,getFullName(name),"<notpresent>");
+ CMS.traceHashKey(mDebugType, getFullName(name), "<notpresent>");
throw new EPropertyNotFound(CMS.getUserMessage("CMS_BASE_GET_PROPERTY_FAILED", getName() + "." + name));
}
if (value.length() == 0) {
@@ -401,14 +395,14 @@ public class PropConfigStore implements IConfigStore, Cloneable {
/**
* Retrieves boolean-based property value.
- *
+ *
* @param name property key
* @param defval default value
* @return boolean value
* @exception EBaseException failed to retrieve
*/
- public boolean getBoolean(String name, boolean defval)
- throws EBaseException {
+ public boolean getBoolean(String name, boolean defval)
+ throws EBaseException {
boolean val;
try {
@@ -418,14 +412,14 @@ public class PropConfigStore implements IConfigStore, Cloneable {
} catch (EPropertyNotDefined e) {
val = defval;
}
- CMS.traceHashKey(mDebugType,getFullName(name),
- val?"true":"false", defval?"true":"false");
+ CMS.traceHashKey(mDebugType, getFullName(name),
+ val ? "true" : "false", defval ? "true" : "false");
return val;
}
/**
* Puts boolean value into the configuration store.
- *
+ *
* @param name property key
* @param value property value
*/
@@ -439,7 +433,7 @@ public class PropConfigStore implements IConfigStore, Cloneable {
/**
* Retrieves integer value.
- *
+ *
* @param name property key
* @return property value
* @exception EBaseException failed to retrieve value
@@ -448,14 +442,14 @@ public class PropConfigStore implements IConfigStore, Cloneable {
String value = (String) get(name);
if (value == null) {
- CMS.traceHashKey(mDebugType,getFullName(name),"<notpresent>");
+ CMS.traceHashKey(mDebugType, getFullName(name), "<notpresent>");
throw new EPropertyNotFound(CMS.getUserMessage("CMS_BASE_GET_PROPERTY_FAILED", getName() + "." + name));
}
if (value.length() == 0) {
throw new EPropertyNotDefined(CMS.getUserMessage("CMS_BASE_GET_PROPERTY_NOVALUE", getName() + "." + name));
}
try {
- CMS.traceHashKey(mDebugType,getFullName(name), value);
+ CMS.traceHashKey(mDebugType, getFullName(name), value);
return Integer.parseInt(value);
} catch (NumberFormatException e) {
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_PROPERTY_1", getName() + "." + name, "int", "number"));
@@ -464,7 +458,7 @@ public class PropConfigStore implements IConfigStore, Cloneable {
/**
* Retrieves integer value.
- *
+ *
* @param name property key
* @param defval default value
* @return property value
@@ -480,14 +474,14 @@ public class PropConfigStore implements IConfigStore, Cloneable {
} catch (EPropertyNotDefined e) {
val = defval;
}
- CMS.traceHashKey(mDebugType,getFullName(name),
- ""+val,""+defval);
+ CMS.traceHashKey(mDebugType, getFullName(name),
+ "" + val, "" + defval);
return val;
}
/**
* Puts an integer value.
- *
+ *
* @param name property key
* @param val property value
* @exception EBaseException failed to retrieve value
@@ -498,7 +492,7 @@ public class PropConfigStore implements IConfigStore, Cloneable {
/**
* Retrieves big integer value.
- *
+ *
* @param name property key
* @return property value
* @exception EBaseException failed to retrieve value
@@ -507,7 +501,7 @@ public class PropConfigStore implements IConfigStore, Cloneable {
String value = (String) get(name);
if (value == null) {
- CMS.traceHashKey(mDebugType,getFullName(name),"<notpresent>");
+ CMS.traceHashKey(mDebugType, getFullName(name), "<notpresent>");
throw new EPropertyNotFound(CMS.getUserMessage("CMS_BASE_GET_PROPERTY_FAILED", getName() + "." + name));
}
if (value.length() == 0) {
@@ -527,14 +521,14 @@ public class PropConfigStore implements IConfigStore, Cloneable {
/**
* Retrieves integer value.
- *
+ *
* @param name property key
* @param defval default value
* @return property value
* @exception EBaseException failed to retrieve value
*/
- public BigInteger getBigInteger(String name, BigInteger defval)
- throws EBaseException {
+ public BigInteger getBigInteger(String name, BigInteger defval)
+ throws EBaseException {
BigInteger val;
try {
@@ -549,7 +543,7 @@ public class PropConfigStore implements IConfigStore, Cloneable {
/**
* Puts a big integer value.
- *
+ *
* @param name property key
* @param val default value
*/
@@ -560,37 +554,33 @@ public class PropConfigStore implements IConfigStore, Cloneable {
/**
* Creates a new sub store.
* <P>
- *
+ *
* @param name substore name
* @return substore
*/
public IConfigStore makeSubStore(String name) {
/*
- String names=(String)mSource.get(getFullName(PROP_SUBSTORES));
-
- if (names==null) {
- names=name;
- }
- else {
- names=names+","+name;
- }
- mSource.put(getFullName(PROP_SUBSTORES), name);
+ * String names=(String)mSource.get(getFullName(PROP_SUBSTORES));
+ *
+ * if (names==null) { names=name; } else { names=names+","+name; }
+ * mSource.put(getFullName(PROP_SUBSTORES), name);
*/
return new PropConfigStore(getFullName(name), mSource);
}
/**
- * Removes a sub store.<p>
- *
+ * Removes a sub store.
+ * <p>
+ *
* @param name substore name
*/
public void removeSubStore(String name) {
// this operation is expensive!!!
-
+
Enumeration e = mSource.keys();
// We only want the keys which match the current substore name
- // without the current substore prefix. This code works even
+ // without the current substore prefix. This code works even
// if mStoreName is null.
String fullName = getFullName(name);
int kIndex = fullName.length();
@@ -605,20 +595,22 @@ public class PropConfigStore implements IConfigStore, Cloneable {
}
/**
- * Retrieves a sub store. A substore contains a list
- * of properties and substores. For example,
+ * Retrieves a sub store. A substore contains a list of properties and
+ * substores. For example,
+ *
* <PRE>
* cms.ldap.host=ds.netscape.com
* cms.ldap.port=389
* </PRE>
- * "ldap" is a substore in above example. If the
- * substore property itself is set, this method
- * will treat the value as a reference. For example,
+ *
+ * "ldap" is a substore in above example. If the substore property itself is
+ * set, this method will treat the value as a reference. For example,
+ *
* <PRE>
- * cms.ldap=kms.ldap
+ * cms.ldap = kms.ldap
* </PRE>
* <P>
- *
+ *
* @param name substore name
* @return substore
*/
@@ -639,7 +631,7 @@ public class PropConfigStore implements IConfigStore, Cloneable {
/**
* Retrieves a list of property names.
- *
+ *
* @return a list of string-based property names
*/
public Enumeration getPropertyNames() {
@@ -668,7 +660,7 @@ public class PropConfigStore implements IConfigStore, Cloneable {
/**
* Returns a list of sub store names.
* <P>
- *
+ *
* @return list of substore names
*/
public Enumeration getSubStoreNames() {
@@ -695,10 +687,9 @@ public class PropConfigStore implements IConfigStore, Cloneable {
}
/**
- * Retrieves the source configuration store where
- * the properties are stored.
+ * Retrieves the source configuration store where the properties are stored.
* <P>
- *
+ *
* @return source configuration store
*/
public ISourceConfigStore getSourceConfigStore() {
@@ -706,8 +697,7 @@ public class PropConfigStore implements IConfigStore, Cloneable {
}
/**
- * For debugging purposes. Prints properties of this
- * substore.
+ * For debugging purposes. Prints properties of this substore.
*/
public void printProperties() {
Enumeration keys = mSource.keys();
@@ -726,7 +716,7 @@ public class PropConfigStore implements IConfigStore, Cloneable {
/**
* Converts the substore parameters.
- *
+ *
* @param name property name
* @return fill property name
*/
@@ -739,7 +729,7 @@ public class PropConfigStore implements IConfigStore, Cloneable {
/**
* Cloning of property configuration store.
- *
+ *
* @return a new configuration store
*/
public Object clone() {
@@ -752,7 +742,7 @@ public class PropConfigStore implements IConfigStore, Cloneable {
while (subs.hasMoreElements()) {
IConfigStore sub = (IConfigStore)
- subs.nextElement();
+ subs.nextElement();
IConfigStore newSub = that.makeSubStore(
sub.getName());
Enumeration props = sub.getPropertyNames();
@@ -761,8 +751,8 @@ public class PropConfigStore implements IConfigStore, Cloneable {
String n = (String) props.nextElement();
try {
- newSub.putString(n,
- sub.getString(n));
+ newSub.putString(n,
+ sub.getString(n));
} catch (EBaseException ex) {
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/base/SimpleProperties.java b/pki/base/common/src/com/netscape/cmscore/base/SimpleProperties.java
index 4eb1c839..d6f9772b 100644
--- a/pki/base/common/src/com/netscape/cmscore/base/SimpleProperties.java
+++ b/pki/base/common/src/com/netscape/cmscore/base/SimpleProperties.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.base;
-
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
@@ -31,28 +30,26 @@ import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
-
/**
- * The <code>Properties</code> class represents a persistent set of
- * properties. The <code>Properties</code> can be saved to a stream
- * or loaded from a stream. Each key and its corresponding value in
- * the property list is a string.
+ * The <code>Properties</code> class represents a persistent set of properties.
+ * The <code>Properties</code> can be saved to a stream or loaded from a stream.
+ * Each key and its corresponding value in the property list is a string.
* <p>
- * A property list can contain another property list as its
- * "defaults"; this second property list is searched if
- * the property key is not found in the original property list.
- *
+ * A property list can contain another property list as its "defaults"; this
+ * second property list is searched if the property key is not found in the
+ * original property list.
+ *
* Because <code>Properties</code> inherits from <code>Hashtable</code>, the
* <code>put</code> and <code>putAll</code> methods can be applied to a
- * <code>Properties</code> object. Their use is strongly discouraged as they
+ * <code>Properties</code> object. Their use is strongly discouraged as they
* allow the caller to insert entries whose keys or values are not
- * <code>Strings</code>. The <code>setProperty</code> method should be used
- * instead. If the <code>store</code> or <code>save</code> method is called
- * on a "compromised" <code>Properties</code> object that contains a
- * non-<code>String</code> key or value, the call will fail.
- *
+ * <code>Strings</code>. The <code>setProperty</code> method should be used
+ * instead. If the <code>store</code> or <code>save</code> method is called on a
+ * "compromised" <code>Properties</code> object that contains a non-
+ * <code>String</code> key or value, the call will fail.
+ *
*/
-public class SimpleProperties extends Hashtable<String,String> {
+public class SimpleProperties extends Hashtable<String, String> {
/**
*
@@ -60,9 +57,9 @@ public class SimpleProperties extends Hashtable<String,String> {
private static final long serialVersionUID = -6129810287662322712L;
/**
- * A property list that contains default values for any keys not
- * found in this property list.
- *
+ * A property list that contains default values for any keys not found in
+ * this property list.
+ *
* @serial
*/
protected SimpleProperties defaults;
@@ -76,18 +73,19 @@ public class SimpleProperties extends Hashtable<String,String> {
/**
* Creates an empty property list with the specified defaults.
- *
- * @param defaults the defaults.
+ *
+ * @param defaults the defaults.
*/
public SimpleProperties(SimpleProperties defaults) {
this.defaults = defaults;
}
/**
- * Calls the hashtable method <code>put</code>. Provided for
- * parallelism with the getProperties method. Enforces use of
- * strings for property keys and values.
- * @since JDK1.2
+ * Calls the hashtable method <code>put</code>. Provided for parallelism
+ * with the getProperties method. Enforces use of strings for property keys
+ * and values.
+ *
+ * @since JDK1.2
*/
public synchronized Object setProperty(String key, String value) {
return put(key, value);
@@ -104,75 +102,83 @@ public class SimpleProperties extends Hashtable<String,String> {
/**
* Reads a property list (key and element pairs) from the input stream.
* <p>
- * Every property occupies one line of the input stream. Each line
- * is terminated by a line terminator (<code>\n</code> or <code>\r</code>
- * or <code>\r\n</code>). Lines from the input stream are processed until
- * end of file is reached on the input stream.
+ * Every property occupies one line of the input stream. Each line is
+ * terminated by a line terminator (<code>\n</code> or <code>\r</code> or
+ * <code>\r\n</code>). Lines from the input stream are processed until end
+ * of file is reached on the input stream.
* <p>
* A line that contains only whitespace or whose first non-whitespace
- * character is an ASCII <code>#</code> or <code>!</code> is ignored
- * (thus, <code>#</code> or <code>!</code> indicate comment lines).
+ * character is an ASCII <code>#</code> or <code>!</code> is ignored (thus,
+ * <code>#</code> or <code>!</code> indicate comment lines).
* <p>
* Every line other than a blank line or a comment line describes one
* property to be added to the table (except that if a line ends with \,
- * then the following line, if it exists, is treated as a continuation
- * line, as described
- * below). The key consists of all the characters in the line starting
- * with the first non-whitespace character and up to, but not including,
- * the first ASCII <code>=</code>, <code>:</code>, or whitespace
- * character. All of the key termination characters may be included in
- * the key by preceding them with a \.
- * Any whitespace after the key is skipped; if the first non-whitespace
- * character after the key is <code>=</code> or <code>:</code>, then it
- * is ignored and any whitespace characters after it are also skipped.
- * All remaining characters on the line become part of the associated
- * element string. Within the element string, the ASCII
- * escape sequences <code>\t</code>, <code>\n</code>,
- * <code>\r</code>, <code>\\</code>, <code>\"</code>, <code>\'</code>,
- * <code>\ &#32;</code> &#32;(a backslash and a space), and
- * <code>\\u</code><i>xxxx</i> are recognized and converted to single
- * characters. Moreover, if the last character on the line is
- * <code>\</code>, then the next line is treated as a continuation of the
- * current line; the <code>\</code> and line terminator are simply
- * discarded, and any leading whitespace characters on the continuation
- * line are also discarded and are not part of the element string.
+ * then the following line, if it exists, is treated as a continuation line,
+ * as described below). The key consists of all the characters in the line
+ * starting with the first non-whitespace character and up to, but not
+ * including, the first ASCII <code>=</code>, <code>:</code>, or whitespace
+ * character. All of the key termination characters may be included in the
+ * key by preceding them with a \. Any whitespace after the key is skipped;
+ * if the first non-whitespace character after the key is <code>=</code> or
+ * <code>:</code>, then it is ignored and any whitespace characters after it
+ * are also skipped. All remaining characters on the line become part of the
+ * associated element string. Within the element string, the ASCII escape
+ * sequences <code>\t</code>, <code>\n</code>, <code>\r</code>,
+ * <code>\\</code>, <code>\"</code>, <code>\'</code>, <code>\ &#32;</code>
+ * &#32;(a backslash and a space), and <code>\\u</code><i>xxxx</i> are
+ * recognized and converted to single characters. Moreover, if the last
+ * character on the line is <code>\</code>, then the next line is treated as
+ * a continuation of the current line; the <code>\</code> and line
+ * terminator are simply discarded, and any leading whitespace characters on
+ * the continuation line are also discarded and are not part of the element
+ * string.
* <p>
* As an example, each of the following four lines specifies the key
* <code>"Truth"</code> and the associated element value
* <code>"Beauty"</code>:
* <p>
+ *
* <pre>
* Truth = Beauty
- * Truth:Beauty
+ * Truth:Beauty
* Truth :Beauty
* </pre>
- * As another example, the following three lines specify a single
- * property:
+ *
+ * As another example, the following three lines specify a single property:
* <p>
+ *
* <pre>
* fruits apple, banana, pear, \
* cantaloupe, watermelon, \
* kiwi, mango
* </pre>
+ *
* The key is <code>"fruits"</code> and the associated element is:
* <p>
- * <pre>"apple, banana, pear, cantaloupe, watermelon,kiwi, mango"</pre>
- * Note that a space appears before each <code>\</code> so that a space
- * will appear after each comma in the final result; the <code>\</code>,
- * line terminator, and leading whitespace on the continuation line are
- * merely discarded and are <i>not</i> replaced by one or more other
- * characters.
+ *
+ * <pre>
+ * &quot;apple, banana, pear, cantaloupe, watermelon,kiwi, mango&quot;
+ * </pre>
+ *
+ * Note that a space appears before each <code>\</code> so that a space will
+ * appear after each comma in the final result; the <code>\</code>, line
+ * terminator, and leading whitespace on the continuation line are merely
+ * discarded and are <i>not</i> replaced by one or more other characters.
* <p>
* As a third example, the line:
* <p>
- * <pre>cheeses
+ *
+ * <pre>
+ * cheeses
* </pre>
+ *
* specifies that the key is <code>"cheeses"</code> and the associated
- * element is the empty string.<p>
- *
- * @param in the input stream.
- * @exception IOException if an error occurred when reading from the
- * input stream.
+ * element is the empty string.
+ * <p>
+ *
+ * @param in the input stream.
+ * @exception IOException if an error occurred when reading from the input
+ * stream.
*/
public synchronized void load(InputStream inStream) throws IOException {
@@ -232,12 +238,12 @@ public class SimpleProperties extends Hashtable<String,String> {
if (whiteSpaceChars.indexOf(line.charAt(valueIndex)) == -1)
break;
- // Skip over one non whitespace key value separators if any
+ // Skip over one non whitespace key value separators if any
if (valueIndex < len)
if (strictKeyValueSeparators.indexOf(line.charAt(valueIndex)) != -1)
valueIndex++;
- // Skip over white space after other separators if any
+ // Skip over white space after other separators if any
while (valueIndex < len) {
if (whiteSpaceChars.indexOf(line.charAt(valueIndex)) == -1)
break;
@@ -248,8 +254,8 @@ public class SimpleProperties extends Hashtable<String,String> {
// Convert then store key and value
// NETSCAPE: no need to convert escape characters
- // key = loadConvert(key);
- // value = loadConvert(value);
+ // key = loadConvert(key);
+ // value = loadConvert(value);
put(key, value);
}
}
@@ -257,8 +263,8 @@ public class SimpleProperties extends Hashtable<String,String> {
}
/*
- * Returns true if the given line is a line that must
- * be appended to the next line
+ * Returns true if the given line is a line that must be appended to the
+ * next line
*/
private boolean continueLine(String line) {
int slashCount = 0;
@@ -270,18 +276,20 @@ public class SimpleProperties extends Hashtable<String,String> {
}
/**
- * Calls the <code>store(OutputStream out, String header)</code> method
- * and suppresses IOExceptions that were thrown.
- *
+ * Calls the <code>store(OutputStream out, String header)</code> method and
+ * suppresses IOExceptions that were thrown.
+ *
* @deprecated This method does not throw an IOException if an I/O error
- * occurs while saving the property list. As of JDK 1.2, the preferred
- * way to save a properties list is via the <code>store(OutputStream out,
+ * occurs while saving the property list. As of JDK 1.2, the
+ * preferred way to save a properties list is via the
+ * <code>store(OutputStream out,
* String header)</code> method.
- *
- * @param out an output stream.
- * @param header a description of the property list.
- * @exception ClassCastException if this <code>Properties</code> object
- * contains any keys or values that are not <code>Strings</code>.
+ *
+ * @param out an output stream.
+ * @param header a description of the property list.
+ * @exception ClassCastException if this <code>Properties</code> object
+ * contains any keys or values that are not
+ * <code>Strings</code>.
*/
public synchronized void save(OutputStream out, String header) {
try {
@@ -296,44 +304,45 @@ public class SimpleProperties extends Hashtable<String,String> {
* for loading into a <code>Properties</code> table using the
* <code>load</code> method.
* <p>
- * Properties from the defaults table of this <code>Properties</code>
- * table (if any) are <i>not</i> written out by this method.
+ * Properties from the defaults table of this <code>Properties</code> table
+ * (if any) are <i>not</i> written out by this method.
* <p>
* If the header argument is not null, then an ASCII <code>#</code>
- * character, the header string, and a line separator are first written
- * to the output stream. Thus, the <code>header</code> can serve as an
+ * character, the header string, and a line separator are first written to
+ * the output stream. Thus, the <code>header</code> can serve as an
* identifying comment.
* <p>
* Next, a comment line is always written, consisting of an ASCII
- * <code>#</code> character, the current date and time (as if produced
- * by the <code>toString</code> method of <code>Date</code> for the
- * current time), and a line separator as generated by the Writer.
+ * <code>#</code> character, the current date and time (as if produced by
+ * the <code>toString</code> method of <code>Date</code> for the current
+ * time), and a line separator as generated by the Writer.
* <p>
* Then every entry in this <code>Properties</code> table is written out,
* one per line. For each entry the key string is written, then an ASCII
- * <code>=</code>, then the associated element string. Each character of
- * the element string is examined to see whether it should be rendered as
- * an escape sequence. The ASCII characters <code>\</code>, tab, newline,
- * and carriage return are written as <code>\\</code>, <code>\t</code>,
- * <code>\n</code>, and <code>\r</code>, respectively. Characters less
- * than <code>\u0020</code> and characters greater than
- * <code>\u007E</code> are written as <code>\\u</code><i>xxxx</i> for
- * the appropriate hexadecimal value <i>xxxx</i>. Space characters, but
- * not embedded or trailing space characters, are written with a preceding
- * <code>\</code>. The key and value characters <code>#</code>,
- * <code>!</code>, <code>=</code>, and <code>:</code> are written with a
- * preceding slash to ensure that they are properly loaded.
+ * <code>=</code>, then the associated element string. Each character of the
+ * element string is examined to see whether it should be rendered as an
+ * escape sequence. The ASCII characters <code>\</code>, tab, newline, and
+ * carriage return are written as <code>\\</code>, <code>\t</code>,
+ * <code>\n</code>, and <code>\r</code>, respectively. Characters less than
+ * <code>\u0020</code> and characters greater than <code>\u007E</code> are
+ * written as <code>\\u</code><i>xxxx</i> for the appropriate hexadecimal
+ * value <i>xxxx</i>. Space characters, but not embedded or trailing space
+ * characters, are written with a preceding <code>\</code>. The key and
+ * value characters <code>#</code>, <code>!</code>, <code>=</code>, and
+ * <code>:</code> are written with a preceding slash to ensure that they are
+ * properly loaded.
* <p>
- * After the entries have been written, the output stream is flushed. The
+ * After the entries have been written, the output stream is flushed. The
* output stream remains open after this method returns.
- *
- * @param out an output stream.
- * @param header a description of the property list.
- * @exception ClassCastException if this <code>Properties</code> object
- * contains any keys or values that are not <code>Strings</code>.
+ *
+ * @param out an output stream.
+ * @param header a description of the property list.
+ * @exception ClassCastException if this <code>Properties</code> object
+ * contains any keys or values that are not
+ * <code>Strings</code>.
*/
public synchronized void store(OutputStream out, String header)
- throws IOException {
+ throws IOException {
BufferedWriter awriter;
awriter = new BufferedWriter(new OutputStreamWriter(out, "8859_1"));
@@ -341,11 +350,11 @@ public class SimpleProperties extends Hashtable<String,String> {
writeln(awriter, "#" + header);
writeln(awriter, "#" + new Date().toString());
for (Enumeration<String> e = keys(); e.hasMoreElements();) {
- String key = e.nextElement();
- String val = get(key);
+ String key = e.nextElement();
+ String val = get(key);
- // key = saveConvert(key);
- // val = saveConvert(val);
+ // key = saveConvert(key);
+ // val = saveConvert(val);
writeln(awriter, key + "=" + val);
}
awriter.flush();
@@ -361,14 +370,14 @@ public class SimpleProperties extends Hashtable<String,String> {
* If the key is not found in this property list, the default property list,
* and its defaults, recursively, are then checked. The method returns
* <code>null</code> if the property is not found.
- *
- * @param key the property key.
- * @return the value in this property list with the specified key value.
- * @see java.util.Properties#defaults
+ *
+ * @param key the property key.
+ * @return the value in this property list with the specified key value.
+ * @see java.util.Properties#defaults
*/
public String getProperty(String key) {
String oval = super.get(key);
- String sval = (oval instanceof String) ? oval : null;
+ String sval = (oval instanceof String) ? oval : null;
return ((sval == null) && (defaults != null)) ? defaults.getProperty(key) : sval;
}
@@ -378,12 +387,12 @@ public class SimpleProperties extends Hashtable<String,String> {
* If the key is not found in this property list, the default property list,
* and its defaults, recursively, are then checked. The method returns the
* default value argument if the property is not found.
- *
- * @param key the hashtable key.
- * @param defaultValue a default value.
- *
- * @return the value in this property list with the specified key value.
- * @see java.util.Properties#defaults
+ *
+ * @param key the hashtable key.
+ * @param defaultValue a default value.
+ *
+ * @return the value in this property list with the specified key value.
+ * @see java.util.Properties#defaults
*/
public String getProperty(String key, String defaultValue) {
String val = getProperty(key);
@@ -394,11 +403,11 @@ public class SimpleProperties extends Hashtable<String,String> {
/**
* Returns an enumeration of all the keys in this property list, including
* the keys in the default property list.
- *
- * @return an enumeration of all the keys in this property list, including
- * the keys in the default property list.
- * @see java.util.Enumeration
- * @see java.util.Properties#defaults
+ *
+ * @return an enumeration of all the keys in this property list, including
+ * the keys in the default property list.
+ * @see java.util.Enumeration
+ * @see java.util.Properties#defaults
*/
public Enumeration<String> propertyNames() {
Hashtable<String, String> h = new Hashtable<String, String>();
@@ -408,10 +417,10 @@ public class SimpleProperties extends Hashtable<String,String> {
}
/**
- * Prints this property list out to the specified output stream.
- * This method is useful for debugging.
- *
- * @param out an output stream.
+ * Prints this property list out to the specified output stream. This method
+ * is useful for debugging.
+ *
+ * @param out an output stream.
*/
public void list(PrintStream out) {
out.println("-- listing properties --");
@@ -430,13 +439,13 @@ public class SimpleProperties extends Hashtable<String,String> {
}
/**
- * Prints this property list out to the specified output stream.
- * This method is useful for debugging.
- *
- * @param out an output stream.
- * @since JDK1.1
+ * Prints this property list out to the specified output stream. This method
+ * is useful for debugging.
+ *
+ * @param out an output stream.
+ * @since JDK1.1
*/
-
+
/*
* Rather than use an anonymous inner class to share common code, this
* method is duplicated in order to ensure that a non-1.1 compiler can
@@ -448,7 +457,7 @@ public class SimpleProperties extends Hashtable<String,String> {
enumerate(h);
for (Enumeration<String> e = h.keys(); e.hasMoreElements();) {
- String key = e.nextElement();
+ String key = e.nextElement();
String val = h.get(key);
if (val.length() > 40) {
@@ -460,6 +469,7 @@ public class SimpleProperties extends Hashtable<String,String> {
/**
* Enumerates all key/value pairs in the specified hastable.
+ *
* @param h the hashtable
*/
private synchronized void enumerate(Hashtable<String, String> h) {
@@ -467,7 +477,7 @@ public class SimpleProperties extends Hashtable<String,String> {
defaults.enumerate(h);
}
for (Enumeration<String> e = keys(); e.hasMoreElements();) {
- String key = e.nextElement();
+ String key = e.nextElement();
h.put(key, get(key));
}
diff --git a/pki/base/common/src/com/netscape/cmscore/base/SourceConfigStore.java b/pki/base/common/src/com/netscape/cmscore/base/SourceConfigStore.java
index 70af37ce..c647bb0b 100644
--- a/pki/base/common/src/com/netscape/cmscore/base/SourceConfigStore.java
+++ b/pki/base/common/src/com/netscape/cmscore/base/SourceConfigStore.java
@@ -17,14 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.base;
-
import com.netscape.certsrv.base.ISourceConfigStore;
-
/**
- * This class is is a wrapper to hide the Properties methods from
- * the PropConfigStore. Lucky for us, Properties already implements
- * almost every thing ISourceConfigStore requires.
+ * This class is is a wrapper to hide the Properties methods from the
+ * PropConfigStore. Lucky for us, Properties already implements almost every
+ * thing ISourceConfigStore requires.
*
* @version $Revision$, $Date$
* @see java.util.Properties
@@ -39,7 +37,7 @@ public class SourceConfigStore extends SimpleProperties implements ISourceConfig
/**
* Retrieves a property from the config store
* <P>
- *
+ *
* @param name property name
* @return property value
*/
@@ -50,10 +48,10 @@ public class SourceConfigStore extends SimpleProperties implements ISourceConfig
/**
* Puts a property into the config store.
* <P>
- *
+ *
* @param name property name
* @param value property value
- * @return
+ * @return
*/
public String put(String name, String value) {
return super.put(name, value); // from Properties->Hashtable
diff --git a/pki/base/common/src/com/netscape/cmscore/base/SubsystemLoader.java b/pki/base/common/src/com/netscape/cmscore/base/SubsystemLoader.java
index 83c74ebc..0dbeb4b5 100644
--- a/pki/base/common/src/com/netscape/cmscore/base/SubsystemLoader.java
+++ b/pki/base/common/src/com/netscape/cmscore/base/SubsystemLoader.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.base;
-
import java.util.Vector;
import com.netscape.certsrv.apps.CMS;
@@ -25,7 +24,6 @@ import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.base.ISubsystem;
-
/**
* A class represents a subsystem loader.
* <P>
@@ -34,7 +32,7 @@ import com.netscape.certsrv.base.ISubsystem;
* @version $Revision$, $Date$
*/
public class SubsystemLoader {
-
+
private static final String PROP_SUBSYSTEM = "subsystem";
private static final String PROP_CLASSNAME = "class";
private static final String PROP_ID = "id";
diff --git a/pki/base/common/src/com/netscape/cmscore/base/SubsystemRegistry.java b/pki/base/common/src/com/netscape/cmscore/base/SubsystemRegistry.java
index 72b4105a..adae6049 100644
--- a/pki/base/common/src/com/netscape/cmscore/base/SubsystemRegistry.java
+++ b/pki/base/common/src/com/netscape/cmscore/base/SubsystemRegistry.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.base;
-
import java.util.Hashtable;
import com.netscape.certsrv.base.ISubsystem;
@@ -38,7 +37,7 @@ public class SubsystemRegistry extends Hashtable<String, ISubsystem> {
}
public ISubsystem get(String key) {
- return super.get(key);
+ return super.get(key);
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/cert/CertDateCompare.java b/pki/base/common/src/com/netscape/cmscore/cert/CertDateCompare.java
index ed20d76f..d8b29812 100644
--- a/pki/base/common/src/com/netscape/cmscore/cert/CertDateCompare.java
+++ b/pki/base/common/src/com/netscape/cmscore/cert/CertDateCompare.java
@@ -17,16 +17,14 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.cert;
-
import java.util.Comparator;
import java.util.Date;
import netscape.security.x509.X509CertImpl;
-
/**
* Compares validity dates for use in sorting.
- *
+ *
* @author kanda
* @version $Revision$, $Date$
*/
@@ -44,11 +42,11 @@ public class CertDateCompare implements Comparator {
} catch (Exception e) {
e.printStackTrace();
}
- if (d1 == d2) return 0;
+ if (d1 == d2)
+ return 0;
if (d1.after(d2))
return 1;
else
return -1;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/cert/CertPrettyPrint.java b/pki/base/common/src/com/netscape/cmscore/cert/CertPrettyPrint.java
index 3168b92f..775ba9e4 100644
--- a/pki/base/common/src/com/netscape/cmscore/cert/CertPrettyPrint.java
+++ b/pki/base/common/src/com/netscape/cmscore/cert/CertPrettyPrint.java
@@ -17,16 +17,13 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.cert;
-
import java.security.cert.Certificate;
import com.netscape.certsrv.base.ICertPrettyPrint;
-
/**
- * This class will display the certificate content in predefined
- * format.
- *
+ * This class will display the certificate content in predefined format.
+ *
* @author Jack Pan-Chen
* @version $Revision$, $Date$
*/
diff --git a/pki/base/common/src/com/netscape/cmscore/cert/CertUtils.java b/pki/base/common/src/com/netscape/cmscore/cert/CertUtils.java
index 97db7921..c098ca9d 100644
--- a/pki/base/common/src/com/netscape/cmscore/cert/CertUtils.java
+++ b/pki/base/common/src/com/netscape/cmscore/cert/CertUtils.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.cert;
-
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
@@ -64,10 +63,9 @@ import com.netscape.certsrv.logging.ILogger;
import com.netscape.osutil.OSUtil;
/**
- * Utility class with assorted methods to check for
- * smime pairs, determining the type of cert - signature
- * or encryption ..etc.
- *
+ * Utility class with assorted methods to check for smime pairs, determining the
+ * type of cert - signature or encryption ..etc.
+ *
* @author kanda
* @version $Revision$, $Date$
*/
@@ -79,9 +77,9 @@ public class CertUtils {
public static final String CERT_RENEWAL_HEADER = "-----BEGIN RENEWAL CERTIFICATE REQUEST-----";
public static final String CERT_RENEWAL_TRAILER = "-----END RENEWAL CERTIFICATE REQUEST-----";
public static final String BEGIN_CRL_HEADER =
- "-----BEGIN CERTIFICATE REVOCATION LIST-----";
+ "-----BEGIN CERTIFICATE REVOCATION LIST-----";
public static final String END_CRL_HEADER =
- "-----END CERTIFICATE REVOCATION LIST-----";
+ "-----END CERTIFICATE REVOCATION LIST-----";
protected static ILogger mSignedAuditLogger = CMS.getSignedAuditLogger();
private final static String LOGGING_SIGNED_AUDIT_CIMC_CERT_VERIFICATION =
@@ -91,7 +89,7 @@ public class CertUtils {
* Remove the header and footer in the PKCS10 request.
*/
public static String unwrapPKCS10(String request, boolean checkHeader)
- throws EBaseException {
+ throws EBaseException {
String unwrapped;
String header = null;
int head = -1;
@@ -112,7 +110,8 @@ public class CertUtils {
head = request.indexOf(CERT_REQUEST_HEADER);
trail = request.indexOf(CERT_REQUEST_TRAILER);
- // If this is not a request header, check if this is a renewal header.
+ // If this is not a request header, check if this is a renewal
+ // header.
if (!(head == -1 && trail == -1)) {
header = CERT_REQUEST_HEADER;
@@ -167,8 +166,8 @@ public class CertUtils {
return pkcs10;
}
- public static void setRSAKeyToCertInfo(X509CertInfo info,
- byte encoded[]) throws EBaseException {
+ public static void setRSAKeyToCertInfo(X509CertInfo info,
+ byte encoded[]) throws EBaseException {
try {
if (info == null) {
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_OPERATION"));
@@ -183,20 +182,20 @@ public class CertUtils {
}
public static X509CertInfo createCertInfo(int ver,
- BigInteger serialno, String alg, String issuerName,
- Date notBefore, Date notAfter) throws EBaseException {
+ BigInteger serialno, String alg, String issuerName,
+ Date notBefore, Date notAfter) throws EBaseException {
try {
X509CertInfo info = new X509CertInfo();
info.set(X509CertInfo.VERSION, new CertificateVersion(ver));
- info.set(X509CertInfo.SERIAL_NUMBER, new
- CertificateSerialNumber(serialno));
- info.set(X509CertInfo.ALGORITHM_ID, new
- CertificateAlgorithmId(AlgorithmId.getAlgorithmId(alg)));
- info.set(X509CertInfo.ISSUER, new
- CertificateIssuerName(new X500Name(issuerName)));
- info.set(X509CertInfo.VALIDITY, new
- CertificateValidity(notBefore, notAfter));
+ info.set(X509CertInfo.SERIAL_NUMBER, new
+ CertificateSerialNumber(serialno));
+ info.set(X509CertInfo.ALGORITHM_ID, new
+ CertificateAlgorithmId(AlgorithmId.getAlgorithmId(alg)));
+ info.set(X509CertInfo.ISSUER, new
+ CertificateIssuerName(new X500Name(issuerName)));
+ info.set(X509CertInfo.VALIDITY, new
+ CertificateValidity(notBefore, notAfter));
return info;
} catch (Exception e) {
System.out.println(e.toString());
@@ -233,11 +232,12 @@ public class CertUtils {
return false;
else if (keyUsage.length == 3)
return keyUsage[2];
- else return keyUsage[2] || keyUsage[3];
+ else
+ return keyUsage[2] || keyUsage[3];
}
public static boolean haveSameValidityPeriod(X509CertImpl cert1,
- X509CertImpl cert2) {
+ X509CertImpl cert2) {
long notBefDiff = 0;
long notAfterDiff = 0;
@@ -264,7 +264,7 @@ public class CertUtils {
if (!sameSubjectDN(dn1, dn2))
return false;
}
-
+
// Check for the presence of signing and encryption certs.
boolean hasSigningCert = isSigningCert(cert1) || isSigningCert(cert2);
@@ -276,15 +276,15 @@ public class CertUtils {
if (!hasEncryptionCert)
return false;
- // If both certs have signing & encryption usage set, they are
- // not really pairs.
+ // If both certs have signing & encryption usage set, they are
+ // not really pairs.
if ((isSigningCert(cert1) && isEncryptionCert(cert1)) ||
- (isSigningCert(cert2) && isEncryptionCert(cert2)))
+ (isSigningCert(cert2) && isEncryptionCert(cert2)))
return false;
- // See if the certs have the same validity.
- boolean haveSameValidity =
- haveSameValidityPeriod(cert1, cert2);
+ // See if the certs have the same validity.
+ boolean haveSameValidity =
+ haveSameValidityPeriod(cert1, cert2);
return haveSameValidity;
}
@@ -358,7 +358,7 @@ public class CertUtils {
}
public static String getRenewedCertsDisplayInfo(String cn,
- X509CertImpl[] validCerts, X509CertImpl[] renewedCerts) {
+ X509CertImpl[] validCerts, X509CertImpl[] renewedCerts) {
StringBuffer sb = new StringBuffer(1024);
if (validCerts != null) {
@@ -397,11 +397,11 @@ public class CertUtils {
/**
* Returns the index of the given cert in an array of certs.
- *
- * Assumptions: The certs are issued by the same CA
- *
- * @param certArray The array of certs.
- * @param givenCert The certificate we are lokking for in the array.
+ *
+ * Assumptions: The certs are issued by the same CA
+ *
+ * @param certArray The array of certs.
+ * @param givenCert The certificate we are lokking for in the array.
* @return -1 if not found or the index of the given cert in the array.
*/
public static int getCertIndex(X509CertImpl[] certArray, X509CertImpl givenCert) {
@@ -418,21 +418,21 @@ public class CertUtils {
}
/**
- * Returns the most recently issued signing certificate from an
- * an array of certs.
- *
- * Assumptions: The certs are issued by the same CA
- *
- * @param certArray The array of certs.
- * @param givenCert The certificate we are lokking for in the array.
+ * Returns the most recently issued signing certificate from an an array of
+ * certs.
+ *
+ * Assumptions: The certs are issued by the same CA
+ *
+ * @param certArray The array of certs.
+ * @param givenCert The certificate we are lokking for in the array.
* @return null if there is no recent cert or the most recent cert.
*/
public static X509CertImpl getRecentSigningCert(X509CertImpl[] certArray,
- X509CertImpl currentCert) {
+ X509CertImpl currentCert) {
if (certArray == null || currentCert == null)
return null;
- // Sort the certificate array.
+ // Sort the certificate array.
Arrays.sort(certArray, new CertDateCompare());
// Get the index of the current cert in the array.
@@ -447,7 +447,7 @@ public class CertUtils {
// Check if it is a signing cert and has its
// NotAfter later than the current cert.
if (isSigningCert(certArray[i]) &&
- certArray[i].getNotAfter().after(recentCert.getNotAfter()))
+ certArray[i].getNotAfter().after(recentCert.getNotAfter()))
recentCert = certArray[i];
}
return ((recentCert == currentCert) ? null : recentCert);
@@ -467,13 +467,13 @@ public class CertUtils {
// Is is object signing cert?
try {
CertificateExtensions extns = (CertificateExtensions)
- cert.get(X509CertImpl.NAME + "." +
- X509CertImpl.INFO + "." +
- X509CertInfo.EXTENSIONS);
+ cert.get(X509CertImpl.NAME + "." +
+ X509CertImpl.INFO + "." +
+ X509CertInfo.EXTENSIONS);
if (extns != null) {
NSCertTypeExtension nsExtn = (NSCertTypeExtension)
- extns.get(NSCertTypeExtension.class.getSimpleName());
+ extns.get(NSCertTypeExtension.class.getSimpleName());
if (nsExtn != null) {
String nsType = getNSExtensionInfo(nsExtn);
@@ -485,7 +485,7 @@ public class CertUtils {
}
}
}
- }catch (Exception e) {
+ } catch (Exception e) {
}
return (sb.length() > 0) ? sb.toString() : null;
}
@@ -517,14 +517,14 @@ public class CertUtils {
res = (Boolean) nsExtn.get(NSCertTypeExtension.OBJECT_SIGNING_CA);
if (res.equals(Boolean.TRUE))
sb.append(" object_signing_CA");
- }catch (Exception e) {
+ } catch (Exception e) {
}
return (sb.length() > 0) ? sb.toString() : null;
}
public static byte[] readFromFile(String fileName)
- throws IOException {
+ throws IOException {
FileInputStream fin = new FileInputStream(fileName);
int available = fin.available();
byte[] ba = new byte[available];
@@ -537,7 +537,7 @@ public class CertUtils {
}
public static void storeInFile(String fileName, byte[] ba)
- throws IOException {
+ throws IOException {
FileOutputStream fout = new FileOutputStream(fileName);
fout.write(ba);
@@ -546,17 +546,16 @@ public class CertUtils {
public static String toMIME64(X509CertImpl cert) {
try {
- return
- "-----BEGIN CERTIFICATE-----\n" +
- com.netscape.osutil.OSUtil.BtoA(cert.getEncoded()) +
- "-----END CERTIFICATE-----\n";
+ return "-----BEGIN CERTIFICATE-----\n" +
+ com.netscape.osutil.OSUtil.BtoA(cert.getEncoded()) +
+ "-----END CERTIFICATE-----\n";
} catch (CertificateException e) {
}
return null;
}
- public static X509Certificate mapCert(String mime64)
- throws IOException {
+ public static X509Certificate mapCert(String mime64)
+ throws IOException {
mime64 = stripCertBrackets(mime64.trim());
String newval = normalizeCertStr(mime64);
byte rawPub[] = com.netscape.osutil.OSUtil.AtoB(newval);
@@ -569,8 +568,8 @@ public class CertUtils {
return cert;
}
- public static X509Certificate[] mapCertFromPKCS7(String mime64)
- throws IOException {
+ public static X509Certificate[] mapCertFromPKCS7(String mime64)
+ throws IOException {
mime64 = stripCertBrackets(mime64.trim());
String newval = normalizeCertStr(mime64);
byte rawPub[] = com.netscape.osutil.OSUtil.AtoB(newval);
@@ -584,8 +583,8 @@ public class CertUtils {
}
}
- public static X509CRL mapCRL(String mime64)
- throws IOException {
+ public static X509CRL mapCRL(String mime64)
+ throws IOException {
mime64 = stripCRLBrackets(mime64.trim());
String newval = normalizeCertStr(mime64);
byte rawPub[] = com.netscape.osutil.OSUtil.AtoB(newval);
@@ -598,8 +597,8 @@ public class CertUtils {
return crl;
}
- public static X509CRL mapCRL1(String mime64)
- throws IOException {
+ public static X509CRL mapCRL1(String mime64)
+ throws IOException {
mime64 = stripCRLBrackets(mime64.trim());
byte rawPub[] = OSUtil.AtoB(mime64);
X509CRL crl = null;
@@ -635,7 +634,7 @@ public class CertUtils {
return s;
}
if ((s.startsWith("-----BEGIN CERTIFICATE REVOCATION LIST-----")) &&
- (s.endsWith("-----END CERTIFICATE REVOCATION LIST-----"))) {
+ (s.endsWith("-----END CERTIFICATE REVOCATION LIST-----"))) {
return (s.substring(43, (s.length() - 41)));
}
return s;
@@ -643,8 +642,9 @@ public class CertUtils {
/**
* strips out the begin and end certificate brackets
+ *
* @param s the string potentially bracketed with
- * "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----"
+ * "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----"
* @return string without the brackets
*/
public static String stripCertBrackets(String s) {
@@ -653,13 +653,13 @@ public class CertUtils {
}
if ((s.startsWith("-----BEGIN CERTIFICATE-----")) &&
- (s.endsWith("-----END CERTIFICATE-----"))) {
+ (s.endsWith("-----END CERTIFICATE-----"))) {
return (s.substring(27, (s.length() - 25)));
}
// To support Thawte's header and footer
if ((s.startsWith("-----BEGIN PKCS #7 SIGNED DATA-----")) &&
- (s.endsWith("-----END PKCS #7 SIGNED DATA-----"))) {
+ (s.endsWith("-----END PKCS #7 SIGNED DATA-----"))) {
return (s.substring(35, (s.length() - 33)));
}
@@ -667,13 +667,14 @@ public class CertUtils {
}
/**
- * Returns a string that represents a cert's fingerprint.
- * The fingerprint is a MD5 digest of the DER encoded certificate.
- * @param cert Certificate to get the fingerprint of.
+ * Returns a string that represents a cert's fingerprint. The fingerprint is
+ * a MD5 digest of the DER encoded certificate.
+ *
+ * @param cert Certificate to get the fingerprint of.
* @return a String that represents the cert's fingerprint.
*/
- public static String getFingerPrint(Certificate cert)
- throws CertificateEncodingException, NoSuchAlgorithmException {
+ public static String getFingerPrint(Certificate cert)
+ throws CertificateEncodingException, NoSuchAlgorithmException {
byte certDer[] = cert.getEncoded();
MessageDigest md = MessageDigest.getInstance("MD5");
@@ -685,16 +686,17 @@ public class CertUtils {
sb.append(pp.toHexString(digestedCert, 4, 20));
return sb.toString();
}
-
+
/**
- * Returns a string that has the certificate's fingerprint using
- * MD5, MD2 and SHA1 hashes.
- * A certificate's fingerprint is a hash digest of the DER encoded
- * certificate.
+ * Returns a string that has the certificate's fingerprint using MD5, MD2
+ * and SHA1 hashes. A certificate's fingerprint is a hash digest of the DER
+ * encoded certificate.
+ *
* @param cert Certificate to get the fingerprints of.
* @return a String with fingerprints using the MD5, MD2 and SHA1 hashes.
- * For example,
- * <pre>
+ * For example,
+ *
+ * <pre>
* MD2: 78:7E:D1:F9:3E:AF:50:18:68:A7:29:50:C3:21:1F:71
*
* MD5: 0E:89:91:AC:40:50:F7:BE:6E:7B:39:4F:56:73:75:75
@@ -703,34 +705,33 @@ public class CertUtils {
* </pre>
*/
public static String getFingerPrints(Certificate cert)
- throws NoSuchAlgorithmException, CertificateEncodingException {
+ throws NoSuchAlgorithmException, CertificateEncodingException {
byte certDer[] = cert.getEncoded();
- /*
- String[] hashes = new String[] {"MD2", "MD5", "SHA1"};
- String certFingerprints = "";
- PrettyPrintFormat pp = new PrettyPrintFormat(":");
-
- for (int i = 0; i < hashes.length; i++) {
- MessageDigest md = MessageDigest.getInstance(hashes[i]);
-
- md.update(certDer);
- certFingerprints += " " + hashes[i] + ":" +
- pp.toHexString(md.digest(), 6 - hashes[i].length());
- }
- return certFingerprints;
- */
- return getFingerPrints(certDer);
+ /*
+ * String[] hashes = new String[] {"MD2", "MD5", "SHA1"}; String
+ * certFingerprints = ""; PrettyPrintFormat pp = new
+ * PrettyPrintFormat(":");
+ *
+ * for (int i = 0; i < hashes.length; i++) { MessageDigest md =
+ * MessageDigest.getInstance(hashes[i]);
+ *
+ * md.update(certDer); certFingerprints += " " + hashes[i] + ":" +
+ * pp.toHexString(md.digest(), 6 - hashes[i].length()); } return
+ * certFingerprints;
+ */
+ return getFingerPrints(certDer);
}
-
+
/**
- * Returns a string that has the certificate's fingerprint using
- * MD5, MD2 and SHA1 hashes.
- * A certificate's fingerprint is a hash digest of the DER encoded
- * certificate.
+ * Returns a string that has the certificate's fingerprint using MD5, MD2
+ * and SHA1 hashes. A certificate's fingerprint is a hash digest of the DER
+ * encoded certificate.
+ *
* @param cert Certificate to get the fingerprints of.
* @return a String with fingerprints using the MD5, MD2 and SHA1 hashes.
- * For example,
- * <pre>
+ * For example,
+ *
+ * <pre>
* MD2: 78:7E:D1:F9:3E:AF:50:18:68:A7:29:50:C3:21:1F:71
*
* MD5: 0E:89:91:AC:40:50:F7:BE:6E:7B:39:4F:56:73:75:75
@@ -739,9 +740,9 @@ public class CertUtils {
* </pre>
*/
public static String getFingerPrints(byte[] certDer)
- throws NoSuchAlgorithmException/*, CertificateEncodingException*/ {
- // byte certDer[] = cert.getEncoded();
- String[] hashes = new String[] {"MD2", "MD5", "SHA1", "SHA256", "SHA512"};
+ throws NoSuchAlgorithmException/* , CertificateEncodingException */{
+ // byte certDer[] = cert.getEncoded();
+ String[] hashes = new String[] { "MD2", "MD5", "SHA1", "SHA256", "SHA512" };
String certFingerprints = "";
PrettyPrintFormat pp = new PrettyPrintFormat(":");
@@ -756,19 +757,20 @@ public class CertUtils {
}
/**
- * Check if a object identifier in string form is valid,
- * that is a string in the form n.n.n.n and der encode and decode-able.
+ * Check if a object identifier in string form is valid, that is a string in
+ * the form n.n.n.n and der encode and decode-able.
+ *
* @param attrName attribute name (from the configuration file)
* @param value object identifier string.
- */
+ */
public static ObjectIdentifier checkOID(String attrName, String value)
- throws EBaseException {
+ throws EBaseException {
String msg = "value must be a object identifier in the form n.n.n.n";
String msg1 = "not a valid object identifier.";
ObjectIdentifier oid;
- try {
- oid = ObjectIdentifier.getObjectIdentifier(value);
+ try {
+ oid = ObjectIdentifier.getObjectIdentifier(value);
} catch (Exception e) {
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
attrName, msg));
@@ -776,7 +778,7 @@ public class CertUtils {
// if the OID isn't valid (ex. n.n) the error isn't caught til
// encoding time leaving a bad request in the request queue.
- try {
+ try {
DerOutputStream derOut = new DerOutputStream();
derOut.putOID(oid);
@@ -803,20 +805,20 @@ public class CertUtils {
return tmp.toString();
}
-
+
/*
- * verify a certificate by its nickname
- * returns true if it verifies; false if any not
+ * verify a certificate by its nickname returns true if it verifies; false
+ * if any not
*/
public static boolean verifySystemCertByNickname(String nickname, String certusage) {
boolean r = true;
- CertificateUsage cu = null;
+ CertificateUsage cu = null;
cu = getCertificateUsage(certusage);
int ccu = 0;
if (cu == null) {
- CMS.debug("CertUtils: verifySystemCertByNickname() failed: "+
- nickname + " with unsupported certusage ="+ certusage);
+ CMS.debug("CertUtils: verifySystemCertByNickname() failed: " +
+ nickname + " with unsupported certusage =" + certusage);
return false;
}
@@ -839,7 +841,7 @@ public class CertUtils {
if (ccu == CertificateUsage.basicCertificateUsages) {
/* cert is good for nothing */
r = false;
- CMS.debug("CertUtils: verifySystemCertByNickname() failed: cert is good for nothing:"+ nickname);
+ CMS.debug("CertUtils: verifySystemCertByNickname() failed: cert is good for nothing:" + nickname);
} else {
r = true;
CMS.debug("CertUtils: verifySystemCertByNickname() passed:" + nickname);
@@ -871,16 +873,16 @@ public class CertUtils {
}
}
} catch (Exception e) {
- CMS.debug("CertUtils: verifySystemCertByNickname() failed: "+
- e.toString());
+ CMS.debug("CertUtils: verifySystemCertByNickname() failed: " +
+ e.toString());
r = false;
}
return r;
}
/*
- * verify a certificate by its tag name
- * returns true if it verifies; false if any not
+ * verify a certificate by its tag name returns true if it verifies; false
+ * if any not
*/
public static boolean verifySystemCertByTag(String tag) {
String auditMessage = null;
@@ -905,12 +907,12 @@ public class CertUtils {
r = false;
return r;
}
- String nickname = config.getString(subsysType+".cert."+tag+".nickname", "");
+ String nickname = config.getString(subsysType + ".cert." + tag + ".nickname", "");
if (nickname.equals("")) {
CMS.debug("CertUtils: verifySystemCertByTag() nickname for cert tag " + tag + " undefined in CS.cfg");
r = false;
}
- String certusage = config.getString(subsysType+".cert."+tag+".certusage", "");
+ String certusage = config.getString(subsysType + ".cert." + tag + ".certusage", "");
if (certusage.equals("")) {
CMS.debug("CertUtils: verifySystemCertByTag() certusage for cert tag " + tag + " undefined in CS.cfg, getting current certificate usage");
}
@@ -918,9 +920,9 @@ public class CertUtils {
if (r == true) {
// audit here
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CIMC_CERT_VERIFICATION,
- ILogger.SYSTEM_UID,
- ILogger.SUCCESS,
+ LOGGING_SIGNED_AUDIT_CIMC_CERT_VERIFICATION,
+ ILogger.SYSTEM_UID,
+ ILogger.SUCCESS,
nickname);
audit(auditMessage);
@@ -935,8 +937,8 @@ public class CertUtils {
audit(auditMessage);
}
} catch (Exception e) {
- CMS.debug("CertUtils: verifySystemCertsByTag() failed: "+
- e.toString());
+ CMS.debug("CertUtils: verifySystemCertsByTag() failed: " +
+ e.toString());
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CIMC_CERT_VERIFICATION,
ILogger.SYSTEM_UID,
@@ -986,9 +988,8 @@ public class CertUtils {
}
/*
- * goes through all system certs and check to see if they are good
- * and audit the result
- * returns true if all verifies; false if any not
+ * goes through all system certs and check to see if they are good and audit
+ * the result returns true if all verifies; false if any not
*/
public static boolean verifySystemCerts() {
String auditMessage = null;
@@ -1022,9 +1023,9 @@ public class CertUtils {
r = false;
return r;
}
- String certlist = config.getString(subsysType+".cert.list", "");
+ String certlist = config.getString(subsysType + ".cert.list", "");
if (certlist.equals("")) {
- CMS.debug("CertUtils: verifySystemCerts() "+subsysType+ ".cert.list not defined in CS.cfg. System certificates verification not done");
+ CMS.debug("CertUtils: verifySystemCerts() " + subsysType + ".cert.list not defined in CS.cfg. System certificates verification not done");
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_CIMC_CERT_VERIFICATION,
ILogger.SYSTEM_UID,
@@ -1050,7 +1051,7 @@ public class CertUtils {
ILogger.FAILURE,
"");
- audit(auditMessage);
+ audit(auditMessage);
r = false;
CMS.debug("CertUtils: verifySystemCerts():" + e.toString());
}
@@ -1073,8 +1074,9 @@ public class CertUtils {
}
/**
- * Signed Audit Log
- * This method is called to store messages to the signed audit log.
+ * Signed Audit Log This method is called to store messages to the signed
+ * audit log.
+ *
* @param msg signed audit log message
*/
private static void audit(String msg) {
@@ -1085,11 +1087,10 @@ public class CertUtils {
}
mSignedAuditLogger.log(ILogger.EV_SIGNED_AUDIT,
- null,
- ILogger.S_SIGNED_AUDIT,
- ILogger.LL_SECURITY,
- msg);
+ null,
+ ILogger.S_SIGNED_AUDIT,
+ ILogger.LL_SECURITY,
+ msg);
}
-
}
diff --git a/pki/base/common/src/com/netscape/cmscore/cert/CertificatePair.java b/pki/base/common/src/com/netscape/cmscore/cert/CertificatePair.java
index effd86ed..c23fd5e0 100644
--- a/pki/base/common/src/com/netscape/cmscore/cert/CertificatePair.java
+++ b/pki/base/common/src/com/netscape/cmscore/cert/CertificatePair.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.cert;
-
import java.io.IOException;
import java.io.OutputStream;
import java.security.cert.CertificateException;
@@ -34,10 +33,9 @@ import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.ca.ICertificateAuthority;
import com.netscape.certsrv.cert.ICrossCertPairSubsystem;
-
/**
* This class implements CertificatePair used for Cross Certification
- *
+ *
* @author cfu
* @version $Revision$, $Date$
*/
@@ -47,14 +45,14 @@ public class CertificatePair implements ASN1Value {
private static final Tag TAG = SEQUENCE.TAG;
/**
- * construct a CertificatePair. It doesn't matter which is
- * forward and which is reverse in the parameters. It will figure
- * it out
+ * construct a CertificatePair. It doesn't matter which is forward and which
+ * is reverse in the parameters. It will figure it out
+ *
* @param cert1 one X509Certificate
* @param cert2 one X509Certificate
*/
- public CertificatePair (X509Certificate cert1, X509Certificate cert2)
- throws EBaseException {
+ public CertificatePair(X509Certificate cert1, X509Certificate cert2)
+ throws EBaseException {
if ((cert1 == null) || (cert2 == null))
throw new EBaseException("CertificatePair: both certs can not be null");
debug("in CertificatePair()");
@@ -74,14 +72,14 @@ public class CertificatePair implements ASN1Value {
}
/**
- * construct a CertificatePair. It doesn't matter which is
- * forward and which is reverse in the parameters. It will figure
- * it out
+ * construct a CertificatePair. It doesn't matter which is forward and which
+ * is reverse in the parameters. It will figure it out
+ *
* @param cert1 one certificate byte array
* @param cert2 one certificate byte array
*/
- public CertificatePair (byte[] cert1, byte[] cert2)
- throws EBaseException {
+ public CertificatePair(byte[] cert1, byte[] cert2)
+ throws EBaseException {
if ((cert1 == null) || (cert2 == null))
throw new EBaseException("CertificatePair: both certs can not be null");
boolean rightOrder = certOrders(cert1, cert2);
@@ -96,11 +94,11 @@ public class CertificatePair implements ASN1Value {
}
/*
- * returns true if c1 is forward and cert2 is reverse
- * returns false if c2 is forward and cert1 is reverse
+ * returns true if c1 is forward and cert2 is reverse returns false if c2 is
+ * forward and cert1 is reverse
*/
private boolean certOrders(X509Certificate c1, X509Certificate c2)
- throws EBaseException {
+ throws EBaseException {
debug("in certOrders() with X509Cert");
ICertificateAuthority ca = (ICertificateAuthority) CMS.getSubsystem("ca");
@@ -111,55 +109,43 @@ public class CertificatePair implements ASN1Value {
// more check really should be done here regarding the
// validity of the two certs...later
- /* It looks the DN's returned are not normalized and fail
- * comparison
-
- if ((c1.getIssuerDN().equals((Object) caCert.getSubjectDN())))
- debug("myCA signed c1");
- else {
- debug("c1 issuerDN="+c1.getIssuerDN().toString());
- debug("myCA subjectDN="+caCert.getSubjectDN().toString());
- }
-
- if(caCert.getSubjectDN().equals((Object) c2.getSubjectDN()))
- debug("myCA subject == c2 subject");
- else {
- debug("caCert subjectDN="+caCert.getSubjectDN().toString());
- debug("c2 subjectDN="+c2.getSubjectDN().toString());
- }
-
- if ((c2.getIssuerDN().equals((Object) caCert.getSubjectDN())))
- debug("myCA signed c2");
- else {
- debug("c2 issuerDN="+c1.getIssuerDN().toString());
- debug("myCA subjectDN="+caCert.getSubjectDN().toString());
- }
-
- if(caCert.getSubjectDN().equals((Object) c1.getSubjectDN()))
- debug("myCA subject == c1 subject");
- else {
- debug("caCert subjectDN="+caCert.getSubjectDN().toString());
- debug("c1 subjectDN="+c1.getSubjectDN().toString());
- }
-
- if ((c1.getIssuerDN().equals((Object) caCert.getSubjectDN()))
- && (caCert.getSubjectDN().equals((Object) c2.getSubjectDN())))
-
- {
- return false;
- } else if ((c2.getIssuerDN().equals((Object) caCert.getSubjectDN()))
- && (caCert.getSubjectDN().equals((Object) c1.getSubjectDN())))
- {
- return true;
- } else {
- throw new EBaseException("CertificatePair: need correct forward and reverse relationship to construct CertificatePair");
- }
+ /*
+ * It looks the DN's returned are not normalized and fail comparison
+ *
+ * if ((c1.getIssuerDN().equals((Object) caCert.getSubjectDN())))
+ * debug("myCA signed c1"); else {
+ * debug("c1 issuerDN="+c1.getIssuerDN().toString());
+ * debug("myCA subjectDN="+caCert.getSubjectDN().toString()); }
+ *
+ * if(caCert.getSubjectDN().equals((Object) c2.getSubjectDN()))
+ * debug("myCA subject == c2 subject"); else {
+ * debug("caCert subjectDN="+caCert.getSubjectDN().toString());
+ * debug("c2 subjectDN="+c2.getSubjectDN().toString()); }
+ *
+ * if ((c2.getIssuerDN().equals((Object) caCert.getSubjectDN())))
+ * debug("myCA signed c2"); else {
+ * debug("c2 issuerDN="+c1.getIssuerDN().toString());
+ * debug("myCA subjectDN="+caCert.getSubjectDN().toString()); }
+ *
+ * if(caCert.getSubjectDN().equals((Object) c1.getSubjectDN()))
+ * debug("myCA subject == c1 subject"); else {
+ * debug("caCert subjectDN="+caCert.getSubjectDN().toString());
+ * debug("c1 subjectDN="+c1.getSubjectDN().toString()); }
+ *
+ * if ((c1.getIssuerDN().equals((Object) caCert.getSubjectDN())) &&
+ * (caCert.getSubjectDN().equals((Object) c2.getSubjectDN())))
+ *
+ * { return false; } else if ((c2.getIssuerDN().equals((Object)
+ * caCert.getSubjectDN())) && (caCert.getSubjectDN().equals((Object)
+ * c1.getSubjectDN()))) { return true; } else { throw new
+ * EBaseException(
+ * "CertificatePair: need correct forward and reverse relationship to construct CertificatePair"
+ * ); }
*/
/*
- * my other attempt:
- * one of the certs has to share the same public key as this
- * CA, and that will be the "forward" cert; the other one is
+ * my other attempt: one of the certs has to share the same public key
+ * as this CA, and that will be the "forward" cert; the other one is
* assumed to be the "reverse" cert
*/
byte[] caCertBytes = caCert.getPublicKey().getEncoded();
@@ -220,14 +206,14 @@ public class CertificatePair implements ASN1Value {
}
/*
- * returns true if cert1 is forward and cert2 is reverse
- * returns false if cert2 is forward and cert1 is reverse
+ * returns true if cert1 is forward and cert2 is reverse returns false if
+ * cert2 is forward and cert1 is reverse
*/
private boolean certOrders(byte[] cert1, byte[] cert2)
- throws EBaseException {
+ throws EBaseException {
debug("in certOrders() with byte[]");
ICrossCertPairSubsystem ccps =
- (ICrossCertPairSubsystem) CMS.getSubsystem("CrossCertPair");
+ (ICrossCertPairSubsystem) CMS.getSubsystem("CrossCertPair");
X509Certificate c1 = null;
X509Certificate c2 = null;
diff --git a/pki/base/common/src/com/netscape/cmscore/cert/CrlCachePrettyPrint.java b/pki/base/common/src/com/netscape/cmscore/cert/CrlCachePrettyPrint.java
index 5c3c8001..92fbc9a1 100644
--- a/pki/base/common/src/com/netscape/cmscore/cert/CrlCachePrettyPrint.java
+++ b/pki/base/common/src/com/netscape/cmscore/cert/CrlCachePrettyPrint.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.cert;
-
import java.text.DateFormat;
import java.util.Iterator;
import java.util.Locale;
@@ -35,44 +34,45 @@ import com.netscape.certsrv.ca.ICRLIssuingPoint;
import com.netscape.certsrv.ca.ICertificateAuthority;
/**
- * This class will display the certificate content in predefined
- * format.
- *
+ * This class will display the certificate content in predefined format.
+ *
* @author Andrew Wnuk
* @version $Revision$, $Date$
*/
-public class CrlCachePrettyPrint implements ICRLPrettyPrint
-{
+public class CrlCachePrettyPrint implements ICRLPrettyPrint {
- /*==========================================================
- * constants
- *==========================================================*/
+ /*
+ * ========================================================== constants
+ * ==========================================================
+ */
private final static String CUSTOM_LOCALE = "Custom";
- /*==========================================================
- * variables
- *==========================================================*/
+ /*
+ * ========================================================== variables
+ * ==========================================================
+ */
private ICRLIssuingPoint mIP = null;
private PrettyPrintFormat pp = null;
- /*==========================================================
- * constructors
- *==========================================================*/
+ /*
+ * ========================================================== constructors
+ * ==========================================================
+ */
public CrlCachePrettyPrint(ICRLIssuingPoint ip) {
mIP = ip;
pp = new PrettyPrintFormat(":");
}
- /*==========================================================
- * public methods
- *==========================================================*/
+ /*
+ * ========================================================== public methods
+ * ==========================================================
+ */
/**
- * This method return string representation of the certificate
- * revocation list in predefined format using specified client
- * local. I18N Support.
- *
+ * This method return string representation of the certificate revocation
+ * list in predefined format using specified client local. I18N Support.
+ *
* @param clientLocale Locale to be used for localization
* @return string representation of the certificate
*/
@@ -82,12 +82,12 @@ public class CrlCachePrettyPrint implements ICRLPrettyPrint
public String toString(Locale clientLocale, long crlSize, long pageStart, long pageSize) {
- //get I18N resources
+ // get I18N resources
ResourceBundle resource = ResourceBundle.getBundle(
PrettyPrintResources.class.getName());
DateFormat dateFormater = DateFormat.getDateTimeInstance(
DateFormat.FULL, DateFormat.FULL, clientLocale);
- //get timezone and timezone ID
+ // get timezone and timezone ID
String tz = " ";
String tzid = " ";
@@ -107,8 +107,8 @@ public class CrlCachePrettyPrint implements ICRLPrettyPrint
}
sb.append(pp.indent(12) + resource.getString(
PrettyPrintResources.TOKEN_ISSUER) +
- ((ICertificateAuthority)(mIP.getCertificateAuthority()))
- .getCRLX500Name().toString() + "\n");
+ ((ICertificateAuthority) (mIP.getCertificateAuthority()))
+ .getCRLX500Name().toString() + "\n");
// Format thisUpdate
String thisUpdate = dateFormater.format(mIP.getLastUpdate());
@@ -124,17 +124,17 @@ public class CrlCachePrettyPrint implements ICRLPrettyPrint
if (tz.equals(tzid) || tzid.equals(CUSTOM_LOCALE)) {
// Do NOT append timezone ID
sb.append(pp.indent(12)
- + resource.getString(
- PrettyPrintResources.TOKEN_THIS_UPDATE)
- + thisUpdate
- + "\n");
+ + resource.getString(
+ PrettyPrintResources.TOKEN_THIS_UPDATE)
+ + thisUpdate
+ + "\n");
} else {
// Append timezone ID
sb.append(pp.indent(12)
- + resource.getString(
- PrettyPrintResources.TOKEN_THIS_UPDATE)
- + thisUpdate
- + " " + tzid + "\n");
+ + resource.getString(
+ PrettyPrintResources.TOKEN_THIS_UPDATE)
+ + thisUpdate
+ + " " + tzid + "\n");
}
// Check for presence of NextUpdate
if (mIP.getNextUpdate() != null) {
@@ -152,17 +152,17 @@ public class CrlCachePrettyPrint implements ICRLPrettyPrint
if (tz.equals(tzid) || tzid.equals(CUSTOM_LOCALE)) {
// Do NOT append timezone ID
sb.append(pp.indent(12)
- + resource.getString(
- PrettyPrintResources.TOKEN_NEXT_UPDATE)
- + nextUpdate
- + "\n");
+ + resource.getString(
+ PrettyPrintResources.TOKEN_NEXT_UPDATE)
+ + nextUpdate
+ + "\n");
} else {
// Append timezone ID
sb.append(pp.indent(12)
- + resource.getString(
- PrettyPrintResources.TOKEN_NEXT_UPDATE)
- + nextUpdate
- + " " + tzid + "\n");
+ + resource.getString(
+ PrettyPrintResources.TOKEN_NEXT_UPDATE)
+ + nextUpdate
+ + " " + tzid + "\n");
}
}
@@ -170,7 +170,7 @@ public class CrlCachePrettyPrint implements ICRLPrettyPrint
sb.append(pp.indent(12) + resource.getString(
PrettyPrintResources.TOKEN_REVOKED_CERTIFICATES) + crlSize + "\n");
} else if ((crlSize == 0 && pageStart == 0 && pageSize == 0) ||
- (crlSize > 0 && pageStart > 0 && pageSize > 0)) {
+ (crlSize > 0 && pageStart > 0 && pageSize > 0)) {
sb.append(pp.indent(12) + resource.getString(
PrettyPrintResources.TOKEN_REVOKED_CERTIFICATES));
long upperLimit = crlSize;
@@ -183,7 +183,7 @@ public class CrlCachePrettyPrint implements ICRLPrettyPrint
}
sb.append("\n");
- Set<RevokedCertificate> revokedCerts = mIP.getRevokedCertificates((int)(pageStart-1), (int)upperLimit);
+ Set<RevokedCertificate> revokedCerts = mIP.getRevokedCertificates((int) (pageStart - 1), (int) upperLimit);
if (revokedCerts != null) {
Iterator<RevokedCertificate> i = revokedCerts.iterator();
@@ -195,35 +195,35 @@ public class CrlCachePrettyPrint implements ICRLPrettyPrint
if ((crlSize == 0) || (upperLimit - pageStart + 1 >= l)) {
sb.append(pp.indent(16) + resource.getString(
PrettyPrintResources.TOKEN_SERIAL) + "0x" +
- revokedCert.getSerialNumber().toString(16).toUpperCase() + "\n");
+ revokedCert.getSerialNumber().toString(16).toUpperCase() + "\n");
String revocationDate =
- dateFormater.format(revokedCert.getRevocationDate());
+ dateFormater.format(revokedCert.getRevocationDate());
// re-get timezone
// (just in case it is different . . .)
if (TimeZone.getDefault() != null) {
tz = TimeZone.getDefault().getDisplayName(
TimeZone.getDefault().inDaylightTime(
- revokedCert.getRevocationDate()),
+ revokedCert.getRevocationDate()),
TimeZone.SHORT,
clientLocale);
}
// Specify revocationDate
if (tz.equals(tzid) ||
- tzid.equals(CUSTOM_LOCALE)) {
+ tzid.equals(CUSTOM_LOCALE)) {
// Do NOT append timezone ID
sb.append(pp.indent(16)
- + resource.getString(
- PrettyPrintResources.TOKEN_REVOCATION_DATE)
- + revocationDate
- + "\n");
+ + resource.getString(
+ PrettyPrintResources.TOKEN_REVOCATION_DATE)
+ + revocationDate
+ + "\n");
} else {
// Append timezone ID
sb.append(pp.indent(16)
- + resource.getString(
- PrettyPrintResources.TOKEN_REVOCATION_DATE)
- + revocationDate
- + " " + tzid + "\n");
+ + resource.getString(
+ PrettyPrintResources.TOKEN_REVOCATION_DATE)
+ + revocationDate
+ + " " + tzid + "\n");
}
if (revokedCert.hasExtensions()) {
sb.append(pp.indent(16) + resource.getString(
@@ -254,7 +254,7 @@ public class CrlCachePrettyPrint implements ICRLPrettyPrint
} catch (Exception e) {
sb.append("\n\n" + pp.indent(4) + resource.getString(
PrettyPrintResources.TOKEN_DECODING_ERROR) + "\n\n");
- CMS.debug("Exception="+e.toString());
+ CMS.debug("Exception=" + e.toString());
CMS.debugStackTrace();
}
diff --git a/pki/base/common/src/com/netscape/cmscore/cert/CrlPrettyPrint.java b/pki/base/common/src/com/netscape/cmscore/cert/CrlPrettyPrint.java
index 1a3969b4..1c24bf2c 100644
--- a/pki/base/common/src/com/netscape/cmscore/cert/CrlPrettyPrint.java
+++ b/pki/base/common/src/com/netscape/cmscore/cert/CrlPrettyPrint.java
@@ -17,16 +17,13 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.cert;
-
import netscape.security.x509.X509CRLImpl;
import com.netscape.certsrv.base.ICRLPrettyPrint;
-
/**
- * This class will display the certificate content in predefined
- * format.
- *
+ * This class will display the certificate content in predefined format.
+ *
* @author Andrew Wnuk
* @version $Revision$, $Date$
*/
diff --git a/pki/base/common/src/com/netscape/cmscore/cert/CrossCertPairSubsystem.java b/pki/base/common/src/com/netscape/cmscore/cert/CrossCertPairSubsystem.java
index 663585bf..17329ffe 100644
--- a/pki/base/common/src/com/netscape/cmscore/cert/CrossCertPairSubsystem.java
+++ b/pki/base/common/src/com/netscape/cmscore/cert/CrossCertPairSubsystem.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.cert;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -47,23 +46,21 @@ import com.netscape.certsrv.publish.IPublisherProcessor;
import com.netscape.certsrv.publish.IXcertPublisherProcessor;
import com.netscape.cmscore.ldapconn.LdapBoundConnFactory;
-
/**
- * Subsystem for handling cross certificate pairing and publishing
- * Intended use:
+ * Subsystem for handling cross certificate pairing and publishing Intended use:
* <ul>
- * <li> when signing a subordinate CA cert which is intended to be
- * part of the crossCertificatePair
- * <li> when this ca submits a request (with existing CA signing key
- * material to another ca for cross-signing
- *</ul>
- * In both cases, administrator needs to "import" the crossSigned
- * certificates via the admin console. When importCert() is called,
- * the imported cert will be stored in the internal db
- * first until it's pairing cert shows up.
- * If it happens that the above two cases finds its pairing
- * cert already there, then a CertifiatePair is created and put
- * in the internal db "crosscertificatepair;binary" attribute
+ * <li>when signing a subordinate CA cert which is intended to be part of the
+ * crossCertificatePair
+ * <li>when this ca submits a request (with existing CA signing key material to
+ * another ca for cross-signing
+ * </ul>
+ * In both cases, administrator needs to "import" the crossSigned certificates
+ * via the admin console. When importCert() is called, the imported cert will be
+ * stored in the internal db first until it's pairing cert shows up. If it
+ * happens that the above two cases finds its pairing cert already there, then a
+ * CertifiatePair is created and put in the internal db
+ * "crosscertificatepair;binary" attribute
+ *
* @author cfu
* @version $Revision$, $Date$
*/
@@ -100,7 +97,7 @@ public class CrossCertPairSubsystem implements ICrossCertPairSubsystem {
}
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
try {
mConfig = config;
mLogger = CMS.getLogger();
@@ -112,21 +109,21 @@ public class CrossCertPairSubsystem implements ICrossCertPairSubsystem {
if (ldapConfig == null) {
log(ILogger.LL_MISCONF,
- CMS.getLogMessage("CMSCORE_DBS_CONF_ERROR",
- PROP_LDAP));
+ CMS.getLogMessage("CMSCORE_DBS_CONF_ERROR",
+ PROP_LDAP));
return;
}
mBaseDN = ldapConfig.getString(PROP_BASEDN, null);
-
+
mLdapConnFactory = new LdapBoundConnFactory();
if (mLdapConnFactory != null)
mLdapConnFactory.init(ldapConfig);
else {
log(ILogger.LL_MISCONF,
- CMS.getLogMessage("CMSCORE_DBS_CONF_ERROR",
- PROP_LDAP));
+ CMS.getLogMessage("CMSCORE_DBS_CONF_ERROR",
+ PROP_LDAP));
return;
}
} catch (EBaseException e) {
@@ -137,14 +134,12 @@ public class CrossCertPairSubsystem implements ICrossCertPairSubsystem {
}
/**
- * "import" the CA cert cross-signed by another CA (potentially a
- * bridge CA) into internal ldap db.
- * the imported cert will be stored in the internal db
- * first until it's pairing cert shows up.
- * If it happens that it finds its pairing
- * cert already there, then a CertifiatePair is created and put
+ * "import" the CA cert cross-signed by another CA (potentially a bridge CA)
+ * into internal ldap db. the imported cert will be stored in the internal
+ * db first until it's pairing cert shows up. If it happens that it finds
+ * its pairing cert already there, then a CertifiatePair is created and put
* in the internal db "crosscertificatepair;binary" attribute
- *
+ *
* @param certBytes cert in byte array to be imported
*/
public void importCert(byte[] certBytes) throws EBaseException {
@@ -162,14 +157,12 @@ public class CrossCertPairSubsystem implements ICrossCertPairSubsystem {
}
/**
- * "import" the CA cert cross-signed by another CA (potentially a
- * bridge CA) into internal ldap db.
- * the imported cert will be stored in the internal db
- * first until it's pairing cert shows up.
- * If it happens that it finds its pairing
- * cert already there, then a CertifiatePair is created and put
+ * "import" the CA cert cross-signed by another CA (potentially a bridge CA)
+ * into internal ldap db. the imported cert will be stored in the internal
+ * db first until it's pairing cert shows up. If it happens that it finds
+ * its pairing cert already there, then a CertifiatePair is created and put
* in the internal db "crosscertificatepair;binary" attribute
- *
+ *
* @param certBytes cert in byte array to be imported
*/
public synchronized void importCert(Object certObj) throws EBaseException {
@@ -182,8 +175,8 @@ public class CrossCertPairSubsystem implements ICrossCertPairSubsystem {
// 1. does cert2 share the same key pair as this CA's signing
// cert
// 2. does cert2's subject match this CA's subject?
- // 3. other valididity checks: is this a ca cert? Is this
- // cert still valid? If the issuer is not yet trusted, let it
+ // 3. other valididity checks: is this a ca cert? Is this
+ // cert still valid? If the issuer is not yet trusted, let it
// be.
// get certs from internal db to see if we find a pair
@@ -208,7 +201,7 @@ public class CrossCertPairSubsystem implements ICrossCertPairSubsystem {
}
Enumeration en = caCerts.getByteValues();
-
+
if ((en == null) || (en.hasMoreElements() == false)) {
debug("1st potential xcert");
addCAcert(conn, cert.getEncoded());
@@ -232,8 +225,9 @@ public class CrossCertPairSubsystem implements ICrossCertPairSubsystem {
// caCertificate attr, and publish if so configured
debug("found a pair!");
CertificatePair cp = new
- // CertificatePair(inCert.getEncoded(), cert.getEncoded());
- CertificatePair(inCert, cert);
+ // CertificatePair(inCert.getEncoded(),
+ // cert.getEncoded());
+ CertificatePair(inCert, cert);
addXCertPair(conn, certPairs, cp);
deleteCAcert(conn, inCert.getEncoded());
@@ -242,7 +236,7 @@ public class CrossCertPairSubsystem implements ICrossCertPairSubsystem {
break;
}
}
- } //while
+ } // while
if (match == false) {
// don't find a pair, add it into
// caCertificate attr for later pairing
@@ -279,27 +273,28 @@ public class CrossCertPairSubsystem implements ICrossCertPairSubsystem {
/**
* are cert1 and cert2 cross-signed certs?
+ *
* @param cert1 the cert for comparison in our internal db
* @param cert2 the cert that's being considered
*/
protected boolean arePair(X509Certificate cert1, X509Certificate cert2) {
// 1. does cert1's issuer match cert2's subject?
// 2. does cert2's issuer match cert1's subject?
- if ((cert1.getIssuerDN().equals((Object) cert2.getSubjectDN()))
- && (cert2.getIssuerDN().equals((Object) cert1.getSubjectDN())))
+ if ((cert1.getIssuerDN().equals((Object) cert2.getSubjectDN()))
+ && (cert2.getIssuerDN().equals((Object) cert1.getSubjectDN())))
return true;
else
return false;
}
- public X509Certificate byteArray2X509Cert(byte[] certBytes)
- throws CertificateException {
+ public X509Certificate byteArray2X509Cert(byte[] certBytes)
+ throws CertificateException {
debug("in bytearray2X509Cert()");
ByteArrayInputStream inStream = new
- ByteArrayInputStream(certBytes);
+ ByteArrayInputStream(certBytes);
CertificateFactory cf =
- CertificateFactory.getInstance("X.509");
+ CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
@@ -308,12 +303,12 @@ public class CrossCertPairSubsystem implements ICrossCertPairSubsystem {
}
public synchronized void addXCertPair(LDAPConnection conn,
- LDAPAttribute certPairs, CertificatePair pair)
- throws LDAPException, IOException {
+ LDAPAttribute certPairs, CertificatePair pair)
+ throws LDAPException, IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
pair.encode(bos);
-
+
if (ByteValueExists(certPairs, bos.toByteArray()) == true) {
debug("cross cert pair exists in internal db, don't add again");
return;
@@ -322,9 +317,9 @@ public class CrossCertPairSubsystem implements ICrossCertPairSubsystem {
// add certificatePair
LDAPModificationSet modSet = new LDAPModificationSet();
- modSet.add(LDAPModification.ADD,
- new LDAPAttribute(LDAP_ATTR_XCERT_PAIR, bos.toByteArray()));
- conn.modify(DN_XCERTS + "," + mBaseDN, modSet);
+ modSet.add(LDAPModification.ADD,
+ new LDAPAttribute(LDAP_ATTR_XCERT_PAIR, bos.toByteArray()));
+ conn.modify(DN_XCERTS + "," + mBaseDN, modSet);
}
/**
@@ -366,24 +361,24 @@ public class CrossCertPairSubsystem implements ICrossCertPairSubsystem {
debug("exiting byteArraysAreEqual(): true");
return true;
}
-
+
public synchronized void addCAcert(LDAPConnection conn, byte[] certEnc)
- throws LDAPException {
+ throws LDAPException {
LDAPModificationSet modSet = new
- LDAPModificationSet();
-
+ LDAPModificationSet();
+
modSet.add(LDAPModification.ADD,
- new LDAPAttribute(LDAP_ATTR_CA_CERT, certEnc));
+ new LDAPAttribute(LDAP_ATTR_CA_CERT, certEnc));
conn.modify(DN_XCERTS + "," + mBaseDN, modSet);
}
public synchronized void deleteCAcert(LDAPConnection conn, byte[] certEnc)
- throws LDAPException {
+ throws LDAPException {
LDAPModificationSet modSet = new
- LDAPModificationSet();
+ LDAPModificationSet();
modSet.add(LDAPModification.DELETE,
- new LDAPAttribute(LDAP_ATTR_CA_CERT, certEnc));
+ new LDAPAttribute(LDAP_ATTR_CA_CERT, certEnc));
conn.modify(DN_XCERTS + "," + mBaseDN, modSet);
}
@@ -394,7 +389,7 @@ public class CrossCertPairSubsystem implements ICrossCertPairSubsystem {
LDAPConnection conn = null;
if ((mPublisherProcessor == null) ||
- !mPublisherProcessor.enabled())
+ !mPublisherProcessor.enabled())
return;
try {
@@ -421,7 +416,7 @@ public class CrossCertPairSubsystem implements ICrossCertPairSubsystem {
}
Enumeration en = xcerts.getByteValues();
-
+
if ((en == null) || (en.hasMoreElements() == false)) {
debug("publishCertPair found no pairs in internal db");
return;
@@ -435,7 +430,7 @@ public class CrossCertPairSubsystem implements ICrossCertPairSubsystem {
continue;
} else {
try {
- //found a cross cert pair, publish if we could
+ // found a cross cert pair, publish if we could
IXcertPublisherProcessor xp = null;
xp = (IXcertPublisherProcessor) mPublisherProcessor;
@@ -445,7 +440,7 @@ public class CrossCertPairSubsystem implements ICrossCertPairSubsystem {
}
}
}// while
- }//if
+ }// if
} catch (Exception e) {
throw new EBaseException("CrossCertPairSubsystem: publishCertPairs() failed:" + e.toString());
}
@@ -476,16 +471,15 @@ public class CrossCertPairSubsystem implements ICrossCertPairSubsystem {
try {
mLdapConnFactory.reset();
} catch (ELdapException e) {
- CMS.debug("CrossCertPairSubsystem shutdown exception: "+e.toString());
+ CMS.debug("CrossCertPairSubsystem shutdown exception: " + e.toString());
}
}
mLdapConnFactory = null;
}
/*
- * Returns the root configuration storage of this system.
- * <P>
- *
+ * Returns the root configuration storage of this system. <P>
+ *
* @return configuration store of this subsystem
*/
public IConfigStore getConfigStore() {
@@ -494,7 +488,7 @@ public class CrossCertPairSubsystem implements ICrossCertPairSubsystem {
protected void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM,
- ILogger.S_XCERT, level, msg);
+ ILogger.S_XCERT, level, msg);
}
private static void debug(String msg) {
diff --git a/pki/base/common/src/com/netscape/cmscore/cert/ExtPrettyPrint.java b/pki/base/common/src/com/netscape/cmscore/cert/ExtPrettyPrint.java
index ea9fabf2..a2ac04e4 100644
--- a/pki/base/common/src/com/netscape/cmscore/cert/ExtPrettyPrint.java
+++ b/pki/base/common/src/com/netscape/cmscore/cert/ExtPrettyPrint.java
@@ -17,16 +17,13 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.cert;
-
import netscape.security.x509.Extension;
import com.netscape.certsrv.base.IExtPrettyPrint;
-
/**
- * This class will display the certificate content in predefined
- * format.
- *
+ * This class will display the certificate content in predefined format.
+ *
* @author Andrew Wnuk
* @version $Revision$, $Date$
*/
@@ -36,4 +33,3 @@ public class ExtPrettyPrint extends netscape.security.util.ExtPrettyPrint implem
super(ext, indentSize);
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/cert/OidLoaderSubsystem.java b/pki/base/common/src/com/netscape/cmscore/cert/OidLoaderSubsystem.java
index 9353ae8f..42425c86 100644
--- a/pki/base/common/src/com/netscape/cmscore/cert/OidLoaderSubsystem.java
+++ b/pki/base/common/src/com/netscape/cmscore/cert/OidLoaderSubsystem.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.cert;
-
import java.security.cert.CertificateException;
import java.util.Enumeration;
@@ -38,7 +37,6 @@ import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.base.ISubsystem;
import com.netscape.cmscore.util.Debug;
-
/**
*
* @author stevep
@@ -47,7 +45,7 @@ import com.netscape.cmscore.util.Debug;
public class OidLoaderSubsystem implements ISubsystem {
private IConfigStore mConfig = null;
- public static final String ID = "oidmap";
+ public static final String ID = "oidmap";
private String mId = ID;
private static final String PROP_OID = "oid";
@@ -77,61 +75,56 @@ public class OidLoaderSubsystem implements ISubsystem {
public static OidLoaderSubsystem getInstance() {
return mInstance;
}
-
+
private static final int CertType_data[] = { 2, 16, 840, 1, 113730, 1, 1 };
/**
* Identifies the particular public key used to sign the certificate.
*/
public static final ObjectIdentifier CertType_Id = new
- ObjectIdentifier(CertType_data);
+ ObjectIdentifier(CertType_data);
private static final String[][] oidMapEntries = new String[][] {
- {NSCertTypeExtension.class.getName(),
- CertType_Id.toString(),
- NSCertTypeExtension.class.getSimpleName()},
- {CertificateRenewalWindowExtension.class.getName(),
- CertificateRenewalWindowExtension.ID.toString(),
- CertificateRenewalWindowExtension.class.getSimpleName()},
- {CertificateScopeOfUseExtension.class.getName(),
- CertificateScopeOfUseExtension.ID.toString(),
- CertificateScopeOfUseExtension.NAME},
- {DeltaCRLIndicatorExtension.class.getName(),
- DeltaCRLIndicatorExtension.OID,
- DeltaCRLIndicatorExtension.class.getSimpleName()},
- {HoldInstructionExtension.class.getName(),
- HoldInstructionExtension.OID,
- HoldInstructionExtension.class.getSimpleName()},
- {InvalidityDateExtension.class.getName(),
- InvalidityDateExtension.OID,
- InvalidityDateExtension.class.getSimpleName()},
- {IssuingDistributionPointExtension.class.getName(),
- IssuingDistributionPointExtension.OID,
- IssuingDistributionPointExtension.class.getSimpleName()},
- {FreshestCRLExtension.class.getName(),
- FreshestCRLExtension.OID,
- FreshestCRLExtension.class.getSimpleName()},
+ { NSCertTypeExtension.class.getName(),
+ CertType_Id.toString(),
+ NSCertTypeExtension.class.getSimpleName() },
+ { CertificateRenewalWindowExtension.class.getName(),
+ CertificateRenewalWindowExtension.ID.toString(),
+ CertificateRenewalWindowExtension.class.getSimpleName() },
+ { CertificateScopeOfUseExtension.class.getName(),
+ CertificateScopeOfUseExtension.ID.toString(),
+ CertificateScopeOfUseExtension.NAME },
+ { DeltaCRLIndicatorExtension.class.getName(),
+ DeltaCRLIndicatorExtension.OID,
+ DeltaCRLIndicatorExtension.class.getSimpleName() },
+ { HoldInstructionExtension.class.getName(),
+ HoldInstructionExtension.OID,
+ HoldInstructionExtension.class.getSimpleName() },
+ { InvalidityDateExtension.class.getName(),
+ InvalidityDateExtension.OID,
+ InvalidityDateExtension.class.getSimpleName() },
+ { IssuingDistributionPointExtension.class.getName(),
+ IssuingDistributionPointExtension.OID,
+ IssuingDistributionPointExtension.class.getSimpleName() },
+ { FreshestCRLExtension.class.getName(),
+ FreshestCRLExtension.OID,
+ FreshestCRLExtension.class.getSimpleName() },
};
/**
- * Initializes this subsystem with the given
- * configuration store.
- * It first initializes resident subsystems,
- * and it loads and initializes loadable
- * subsystem specified in the configuration
- * store.
+ * Initializes this subsystem with the given configuration store. It first
+ * initializes resident subsystems, and it loads and initializes loadable
+ * subsystem specified in the configuration store.
* <P>
- * Note that individual subsystem should be
- * initialized in a separated thread if
- * it has dependency on the initialization
- * of other subsystems.
+ * Note that individual subsystem should be initialized in a separated
+ * thread if it has dependency on the initialization of other subsystems.
* <P>
- *
+ *
* @param owner owner of this subsystem
* @param config configuration store
*/
public synchronized void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
if (Debug.ON) {
Debug.trace("OIDLoaderSubsystem started");
}
@@ -144,8 +137,8 @@ public class OidLoaderSubsystem implements ISubsystem {
for (int i = 0; i < oidMapEntries.length; i++) {
try {
OIDMap.addAttribute(oidMapEntries[i][0],
- oidMapEntries[i][1],
- oidMapEntries[i][2]);
+ oidMapEntries[i][1],
+ oidMapEntries[i][2]);
} catch (Exception e) {
}
}
@@ -161,8 +154,8 @@ public class OidLoaderSubsystem implements ISubsystem {
String classname = substore.getString(PROP_CLASS);
OIDMap.addAttribute(classname,
- oidname,
- substorename);
+ oidname,
+ substorename);
} catch (EPropertyNotFound e) {
// Log error
} catch (CertificateException e) {
@@ -181,9 +174,8 @@ public class OidLoaderSubsystem implements ISubsystem {
}
/*
- * Returns the root configuration storage of this system.
- * <P>
- *
+ * Returns the root configuration storage of this system. <P>
+ *
* @return configuration store of this subsystem
*/
public IConfigStore getConfigStore() {
diff --git a/pki/base/common/src/com/netscape/cmscore/cert/PrettyPrintFormat.java b/pki/base/common/src/com/netscape/cmscore/cert/PrettyPrintFormat.java
index 3ace3c67..cdde9939 100644
--- a/pki/base/common/src/com/netscape/cmscore/cert/PrettyPrintFormat.java
+++ b/pki/base/common/src/com/netscape/cmscore/cert/PrettyPrintFormat.java
@@ -17,40 +17,40 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.cert;
-
import com.netscape.certsrv.base.IPrettyPrintFormat;
-
/**
- * This class will display the certificate content in predefined
- * format.
- *
+ * This class will display the certificate content in predefined format.
+ *
* @author Andrew Wnuk
* @version $Revision$, $Date$
*/
public class PrettyPrintFormat implements IPrettyPrintFormat {
- /*==========================================================
- * variables
- *==========================================================*/
+ /*
+ * ========================================================== variables
+ * ==========================================================
+ */
private String mSeparator = "";
private int mIndentSize = 0;
private int mLineLen = 0;
- /*==========================================================
- * constants
- *
- *==========================================================*/
+ /*
+ * ========================================================== constants
+ *
+ * ==========================================================
+ */
private final static String spaces =
- " " +
- " " +
- " " +
- " " +
- " ";
-
- /*==========================================================
- * constructors
- *==========================================================*/
+ " " +
+ " " +
+ " " +
+ " " +
+ " ";
+
+ /*
+ * ========================================================== constructors
+ * ==========================================================
+ */
public PrettyPrintFormat(String separator) {
mSeparator = separator;
@@ -67,18 +67,20 @@ public class PrettyPrintFormat implements IPrettyPrintFormat {
mIndentSize = indentSize;
}
- /*==========================================================
- * Private methods
- *==========================================================*/
-
-
- /*==========================================================
- * public methods
- *==========================================================*/
+ /*
+ * ========================================================== Private
+ * methods==========================================================
+ */
+
+ /*
+ * ========================================================== public methods
+ * ==========================================================
+ */
/**
- * Provide white space indention
- * stevep - speed improvements. Factor of 10 improvement
+ * Provide white space indention stevep - speed improvements. Factor of 10
+ * improvement
+ *
* @param numSpace number of white space to be returned
* @return white spaces
*/
@@ -92,19 +94,19 @@ public class PrettyPrintFormat implements IPrettyPrintFormat {
};
/**
- * Convert Byte Array to Hex String Format
- * stevep - speedup by factor of 8
+ * Convert Byte Array to Hex String Format stevep - speedup by factor of 8
+ *
* @param byte array of data to hexify
* @param indentSize number of spaces to prepend before each line
- * @param lineLen number of bytes to output on each line (0
- means: put everything on one line
- * @param separator the first character of this string will be used as
- the separator between bytes.
+ * @param lineLen number of bytes to output on each line (0 means: put
+ * everything on one line
+ * @param separator the first character of this string will be used as the
+ * separator between bytes.
* @return string representation
*/
- public String toHexString(byte[] in, int indentSize,
- int lineLen, String separator) {
+ public String toHexString(byte[] in, int indentSize,
+ int lineLen, String separator) {
StringBuffer sb = new StringBuffer();
int hexCount = 0;
char c[];
@@ -144,7 +146,7 @@ public class PrettyPrintFormat implements IPrettyPrintFormat {
c[j++] = '\n';
sb.append(c, 0, j);
}
- // sb.append("\n");
+ // sb.append("\n");
return sb.toString();
}
diff --git a/pki/base/common/src/com/netscape/cmscore/cert/PrettyPrintResources.java b/pki/base/common/src/com/netscape/cmscore/cert/PrettyPrintResources.java
index 4bf1147a..d90a4558 100644
--- a/pki/base/common/src/com/netscape/cmscore/cert/PrettyPrintResources.java
+++ b/pki/base/common/src/com/netscape/cmscore/cert/PrettyPrintResources.java
@@ -17,21 +17,19 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.cert;
-
import java.util.ListResourceBundle;
import netscape.security.extensions.NSCertTypeExtension;
import netscape.security.x509.KeyUsageExtension;
-
/**
* Resource Boundle for the Pretty Print
- *
+ *
* @author Jack Pan-Chen
* @version $Revision$, $Date$
*/
-public class PrettyPrintResources extends ListResourceBundle {
+public class PrettyPrintResources extends ListResourceBundle {
/**
* Returns content
@@ -41,11 +39,10 @@ public class PrettyPrintResources extends ListResourceBundle {
}
/**
- * Constants. The suffix represents the number of
- * possible parameters.
+ * Constants. The suffix represents the number of possible parameters.
*/
- //certificate pretty print
+ // certificate pretty print
public final static String TOKEN_CERTIFICATE = "tokenCertificate";
public final static String TOKEN_DATA = "tokenData";
public final static String TOKEN_VERSION = "tokenVersion";
@@ -64,14 +61,14 @@ public class PrettyPrintResources extends ListResourceBundle {
public final static String TOKEN_EXTENSIONS = "tokenExtensions";
public final static String TOKEN_SIGNATURE = "tokenSignature";
- //extension pretty print
+ // extension pretty print
public final static String TOKEN_YES = "tokenYes";
public final static String TOKEN_NO = "tokenNo";
public final static String TOKEN_IDENTIFIER = "tokenIdentifier";
public final static String TOKEN_CRITICAL = "tokenCritical";
public final static String TOKEN_VALUE = "tokenValue";
- //specific extension token
+ // specific extension token
public final static String TOKEN_KEY_TYPE = "tokenKeyType";
public final static String TOKEN_CERT_TYPE = "tokenCertType";
public final static String TOKEN_SKI = "tokenSKI";
@@ -174,122 +171,122 @@ public class PrettyPrintResources extends ListResourceBundle {
public final static String TOKEN_CACHE_NOT_AVAILABLE = "cacheNotAvailable";
public final static String TOKEN_CACHE_IS_EMPTY = "cacheIsEmpty";
- //Tokens should have blank_space as trailer
+ // Tokens should have blank_space as trailer
static final Object[][] contents = {
- {TOKEN_CERTIFICATE, "Certificate: "},
- {TOKEN_DATA, "Data: "},
- {TOKEN_VERSION, "Version: "},
- {TOKEN_SERIAL, "Serial Number: "},
- {TOKEN_SIGALG, "Signature Algorithm: "},
- {TOKEN_ISSUER, "Issuer: "},
- {TOKEN_VALIDITY, "Validity: "},
- {TOKEN_NOT_BEFORE, "Not Before: "},
- {TOKEN_NOT_AFTER, "Not After: "},
- {TOKEN_SUBJECT, "Subject: "},
- {TOKEN_SPKI, "Subject Public Key Info: "},
- {TOKEN_ALGORITHM, "Algorithm: "},
- {TOKEN_PUBLIC_KEY, "Public Key: "},
- {TOKEN_PUBLIC_KEY_MODULUS, "Public Key Modulus: "},
- {TOKEN_PUBLIC_KEY_EXPONENT, "Exponent: "},
- {TOKEN_EXTENSIONS, "Extensions: "},
- {TOKEN_SIGNATURE, "Signature: "},
- {TOKEN_YES, "yes "},
- {TOKEN_NO, "no "},
- {TOKEN_IDENTIFIER, "Identifier: "},
- {TOKEN_CRITICAL, "Critical: "},
- {TOKEN_VALUE, "Value: "},
- {TOKEN_KEY_TYPE, "Key Type "},
- {TOKEN_CERT_TYPE, "Netscape Certificate Type "},
- {TOKEN_SKI, "Subject Key Identifier "},
- {TOKEN_AKI, "Authority Key Identifier "},
- {TOKEN_ACCESS_DESC, "Access Description: "},
- {TOKEN_OCSP_NOCHECK, "OCSP NoCheck: "},
- {TOKEN_EXTENDED_KEY_USAGE, "Extended Key Usage: "},
- {TOKEN_PRIVATE_KEY_USAGE, "Private Key Usage: "},
- {TOKEN_PRESENCE_SERVER, "Presence Server: "},
- {TOKEN_AIA, "Authority Info Access: "},
- {TOKEN_KEY_USAGE, "Key Usage: "},
- {KeyUsageExtension.DIGITAL_SIGNATURE, "Digital Signature "},
- {KeyUsageExtension.NON_REPUDIATION, "Non Repudiation "},
- {KeyUsageExtension.KEY_ENCIPHERMENT, "Key Encipherment "},
- {KeyUsageExtension.DATA_ENCIPHERMENT, "Data Encipherment "},
- {KeyUsageExtension.KEY_AGREEMENT, "Key Agreement "},
- {KeyUsageExtension.KEY_CERTSIGN, "Key CertSign "},
- {KeyUsageExtension.CRL_SIGN, "Crl Sign "},
- {KeyUsageExtension.ENCIPHER_ONLY, "Encipher Only "},
- {KeyUsageExtension.DECIPHER_ONLY, "Decipher Only "},
- {TOKEN_CERT_USAGE, "Certificate Usage: "},
- {NSCertTypeExtension.SSL_CLIENT, "SSL Client "},
- {NSCertTypeExtension.SSL_SERVER, "SSL Server "},
- {NSCertTypeExtension.EMAIL, "Secure Email "},
- {NSCertTypeExtension.OBJECT_SIGNING, "Object Signing "},
- {NSCertTypeExtension.SSL_CA, "SSL CA "},
- {NSCertTypeExtension.EMAIL_CA, "Secure Email CA "},
- {NSCertTypeExtension.OBJECT_SIGNING_CA, "ObjectSigning CA "},
- {TOKEN_KEY_ID, "Key Identifier: "},
- {TOKEN_AUTH_NAME, "Authority Name: "},
- {TOKEN_CRL, "Certificate Revocation List: "},
- {TOKEN_THIS_UPDATE, "This Update: "},
- {TOKEN_NEXT_UPDATE, "Next Update: "},
- {TOKEN_REVOKED_CERTIFICATES, "Revoked Certificates: "},
- {TOKEN_REVOCATION_DATE, "Revocation Date: "},
- {TOKEN_REVOCATION_REASON, "Revocation Reason "},
- {TOKEN_REASON, "Reason: "},
- {TOKEN_BASIC_CONSTRAINTS, "Basic Constraints "},
- {TOKEN_NAME_CONSTRAINTS, "Name Constraints "},
- {TOKEN_NSC_COMMENT, "Netscape Comment "},
- {TOKEN_IS_CA, "Is CA: "},
- {TOKEN_PATH_LEN, "Path Length Constraint: "},
- {TOKEN_PATH_LEN_UNLIMITED, "UNLIMITED"},
- {TOKEN_PATH_LEN_UNDEFINED, "UNDEFINED"},
- {TOKEN_PATH_LEN_INVALID, "INVALID"},
- {TOKEN_CRL_NUMBER, "CRL Number "},
- {TOKEN_NUMBER, "Number: "},
- {TOKEN_DELTA_CRL_INDICATOR, "Delta CRL Indicator "},
- {TOKEN_BASE_CRL_NUMBER, "Base CRL Number: "},
- {TOKEN_CERT_SCOPE_OF_USE, "Certificate Scope of Use "},
- {TOKEN_SCOPE_OF_USE, "Scope of Use: "},
- {TOKEN_PORT, "Port: "},
- {TOKEN_ISSUER_ALT_NAME, "Issuer Alternative Name "},
- {TOKEN_ISSUER_NAMES, "Issuer Names: "},
- {TOKEN_SUBJECT_ALT_NAME, "Subject Alternative Name "},
- {TOKEN_DECODING_ERROR, "Decoding Error"},
- {TOKEN_FRESHEST_CRL_EXT, "Freshest CRL "},
- {TOKEN_CRL_DP_EXT, "CRL Distribution Points "},
- {TOKEN_CRLDP_NUMPOINTS, "Number of Points: "},
- {TOKEN_CRLDP_POINTN, "Point "},
- {TOKEN_CRLDP_DISTPOINT, "Distribution Point: "},
- {TOKEN_CRLDP_REASONS, "Reason Flags: "},
- {TOKEN_CRLDP_CRLISSUER, "CRL Issuer: "},
- {TOKEN_ISSUING_DIST_POINT, "Issuing Distribution Point "},
- {TOKEN_DIST_POINT_NAME, "Distribution Point: "},
- {TOKEN_FULL_NAME, "Full Name: "},
- {TOKEN_RELATIVE_NAME, "Name Relative To CRL Issuer: "},
- {TOKEN_ONLY_USER_CERTS, "Only Contains User Certificates: "},
- {TOKEN_ONLY_CA_CERTS, "Only Contains CA Certificates: "},
- {TOKEN_ONLY_SOME_REASONS, "Only Some Reasons: "},
- {TOKEN_INDIRECT_CRL, "Indirect CRL: "},
- {TOKEN_INVALIDITY_DATE, "Invalidity Date "},
- {TOKEN_DATE_OF_INVALIDITY, "Invalidity Date: "},
- {TOKEN_CERTIFICATE_ISSUER, "Certificate Issuer "},
- {TOKEN_HOLD_INSTRUCTION, "Hold Instruction Code "},
- {TOKEN_HOLD_INSTRUCTION_CODE, "Hold Instruction Code: "},
- {TOKEN_POLICY_CONSTRAINTS, "Policy Constraints "},
- {TOKEN_INHIBIT_POLICY_MAPPING, "Inhibit Policy Mapping: "},
- {TOKEN_REQUIRE_EXPLICIT_POLICY, "Require Explicit Policy: "},
- {TOKEN_POLICY_MAPPINGS, "Policy Mappings "},
- {TOKEN_MAPPINGS, "Mappings: "},
- {TOKEN_MAP, "Map "},
- {TOKEN_ISSUER_DOMAIN_POLICY, "Issuer Domain Policy: "},
- {TOKEN_SUBJECT_DOMAIN_POLICY, "Subject Domain Policy: "},
- {TOKEN_SUBJECT_DIR_ATTR, "Subject Directory Attributes "},
- {TOKEN_ATTRIBUTES, "Attributes:" },
- {TOKEN_ATTRIBUTE, "Attribute "},
- {TOKEN_VALUES, "Values: "},
- {TOKEN_NOT_SET, "not set"},
- {TOKEN_NONE, "none"},
- {TOKEN_CACHE_NOT_AVAILABLE, "CRL cache is not available. "},
- {TOKEN_CACHE_IS_EMPTY, "CRL cache is empty. "},
+ { TOKEN_CERTIFICATE, "Certificate: " },
+ { TOKEN_DATA, "Data: " },
+ { TOKEN_VERSION, "Version: " },
+ { TOKEN_SERIAL, "Serial Number: " },
+ { TOKEN_SIGALG, "Signature Algorithm: " },
+ { TOKEN_ISSUER, "Issuer: " },
+ { TOKEN_VALIDITY, "Validity: " },
+ { TOKEN_NOT_BEFORE, "Not Before: " },
+ { TOKEN_NOT_AFTER, "Not After: " },
+ { TOKEN_SUBJECT, "Subject: " },
+ { TOKEN_SPKI, "Subject Public Key Info: " },
+ { TOKEN_ALGORITHM, "Algorithm: " },
+ { TOKEN_PUBLIC_KEY, "Public Key: " },
+ { TOKEN_PUBLIC_KEY_MODULUS, "Public Key Modulus: " },
+ { TOKEN_PUBLIC_KEY_EXPONENT, "Exponent: " },
+ { TOKEN_EXTENSIONS, "Extensions: " },
+ { TOKEN_SIGNATURE, "Signature: " },
+ { TOKEN_YES, "yes " },
+ { TOKEN_NO, "no " },
+ { TOKEN_IDENTIFIER, "Identifier: " },
+ { TOKEN_CRITICAL, "Critical: " },
+ { TOKEN_VALUE, "Value: " },
+ { TOKEN_KEY_TYPE, "Key Type " },
+ { TOKEN_CERT_TYPE, "Netscape Certificate Type " },
+ { TOKEN_SKI, "Subject Key Identifier " },
+ { TOKEN_AKI, "Authority Key Identifier " },
+ { TOKEN_ACCESS_DESC, "Access Description: " },
+ { TOKEN_OCSP_NOCHECK, "OCSP NoCheck: " },
+ { TOKEN_EXTENDED_KEY_USAGE, "Extended Key Usage: " },
+ { TOKEN_PRIVATE_KEY_USAGE, "Private Key Usage: " },
+ { TOKEN_PRESENCE_SERVER, "Presence Server: " },
+ { TOKEN_AIA, "Authority Info Access: " },
+ { TOKEN_KEY_USAGE, "Key Usage: " },
+ { KeyUsageExtension.DIGITAL_SIGNATURE, "Digital Signature " },
+ { KeyUsageExtension.NON_REPUDIATION, "Non Repudiation " },
+ { KeyUsageExtension.KEY_ENCIPHERMENT, "Key Encipherment " },
+ { KeyUsageExtension.DATA_ENCIPHERMENT, "Data Encipherment " },
+ { KeyUsageExtension.KEY_AGREEMENT, "Key Agreement " },
+ { KeyUsageExtension.KEY_CERTSIGN, "Key CertSign " },
+ { KeyUsageExtension.CRL_SIGN, "Crl Sign " },
+ { KeyUsageExtension.ENCIPHER_ONLY, "Encipher Only " },
+ { KeyUsageExtension.DECIPHER_ONLY, "Decipher Only " },
+ { TOKEN_CERT_USAGE, "Certificate Usage: " },
+ { NSCertTypeExtension.SSL_CLIENT, "SSL Client " },
+ { NSCertTypeExtension.SSL_SERVER, "SSL Server " },
+ { NSCertTypeExtension.EMAIL, "Secure Email " },
+ { NSCertTypeExtension.OBJECT_SIGNING, "Object Signing " },
+ { NSCertTypeExtension.SSL_CA, "SSL CA " },
+ { NSCertTypeExtension.EMAIL_CA, "Secure Email CA " },
+ { NSCertTypeExtension.OBJECT_SIGNING_CA, "ObjectSigning CA " },
+ { TOKEN_KEY_ID, "Key Identifier: " },
+ { TOKEN_AUTH_NAME, "Authority Name: " },
+ { TOKEN_CRL, "Certificate Revocation List: " },
+ { TOKEN_THIS_UPDATE, "This Update: " },
+ { TOKEN_NEXT_UPDATE, "Next Update: " },
+ { TOKEN_REVOKED_CERTIFICATES, "Revoked Certificates: " },
+ { TOKEN_REVOCATION_DATE, "Revocation Date: " },
+ { TOKEN_REVOCATION_REASON, "Revocation Reason " },
+ { TOKEN_REASON, "Reason: " },
+ { TOKEN_BASIC_CONSTRAINTS, "Basic Constraints " },
+ { TOKEN_NAME_CONSTRAINTS, "Name Constraints " },
+ { TOKEN_NSC_COMMENT, "Netscape Comment " },
+ { TOKEN_IS_CA, "Is CA: " },
+ { TOKEN_PATH_LEN, "Path Length Constraint: " },
+ { TOKEN_PATH_LEN_UNLIMITED, "UNLIMITED" },
+ { TOKEN_PATH_LEN_UNDEFINED, "UNDEFINED" },
+ { TOKEN_PATH_LEN_INVALID, "INVALID" },
+ { TOKEN_CRL_NUMBER, "CRL Number " },
+ { TOKEN_NUMBER, "Number: " },
+ { TOKEN_DELTA_CRL_INDICATOR, "Delta CRL Indicator " },
+ { TOKEN_BASE_CRL_NUMBER, "Base CRL Number: " },
+ { TOKEN_CERT_SCOPE_OF_USE, "Certificate Scope of Use " },
+ { TOKEN_SCOPE_OF_USE, "Scope of Use: " },
+ { TOKEN_PORT, "Port: " },
+ { TOKEN_ISSUER_ALT_NAME, "Issuer Alternative Name " },
+ { TOKEN_ISSUER_NAMES, "Issuer Names: " },
+ { TOKEN_SUBJECT_ALT_NAME, "Subject Alternative Name " },
+ { TOKEN_DECODING_ERROR, "Decoding Error" },
+ { TOKEN_FRESHEST_CRL_EXT, "Freshest CRL " },
+ { TOKEN_CRL_DP_EXT, "CRL Distribution Points " },
+ { TOKEN_CRLDP_NUMPOINTS, "Number of Points: " },
+ { TOKEN_CRLDP_POINTN, "Point " },
+ { TOKEN_CRLDP_DISTPOINT, "Distribution Point: " },
+ { TOKEN_CRLDP_REASONS, "Reason Flags: " },
+ { TOKEN_CRLDP_CRLISSUER, "CRL Issuer: " },
+ { TOKEN_ISSUING_DIST_POINT, "Issuing Distribution Point " },
+ { TOKEN_DIST_POINT_NAME, "Distribution Point: " },
+ { TOKEN_FULL_NAME, "Full Name: " },
+ { TOKEN_RELATIVE_NAME, "Name Relative To CRL Issuer: " },
+ { TOKEN_ONLY_USER_CERTS, "Only Contains User Certificates: " },
+ { TOKEN_ONLY_CA_CERTS, "Only Contains CA Certificates: " },
+ { TOKEN_ONLY_SOME_REASONS, "Only Some Reasons: " },
+ { TOKEN_INDIRECT_CRL, "Indirect CRL: " },
+ { TOKEN_INVALIDITY_DATE, "Invalidity Date " },
+ { TOKEN_DATE_OF_INVALIDITY, "Invalidity Date: " },
+ { TOKEN_CERTIFICATE_ISSUER, "Certificate Issuer " },
+ { TOKEN_HOLD_INSTRUCTION, "Hold Instruction Code " },
+ { TOKEN_HOLD_INSTRUCTION_CODE, "Hold Instruction Code: " },
+ { TOKEN_POLICY_CONSTRAINTS, "Policy Constraints " },
+ { TOKEN_INHIBIT_POLICY_MAPPING, "Inhibit Policy Mapping: " },
+ { TOKEN_REQUIRE_EXPLICIT_POLICY, "Require Explicit Policy: " },
+ { TOKEN_POLICY_MAPPINGS, "Policy Mappings " },
+ { TOKEN_MAPPINGS, "Mappings: " },
+ { TOKEN_MAP, "Map " },
+ { TOKEN_ISSUER_DOMAIN_POLICY, "Issuer Domain Policy: " },
+ { TOKEN_SUBJECT_DOMAIN_POLICY, "Subject Domain Policy: " },
+ { TOKEN_SUBJECT_DIR_ATTR, "Subject Directory Attributes " },
+ { TOKEN_ATTRIBUTES, "Attributes:" },
+ { TOKEN_ATTRIBUTE, "Attribute " },
+ { TOKEN_VALUES, "Values: " },
+ { TOKEN_NOT_SET, "not set" },
+ { TOKEN_NONE, "none" },
+ { TOKEN_CACHE_NOT_AVAILABLE, "CRL cache is not available. " },
+ { TOKEN_CACHE_IS_EMPTY, "CRL cache is empty. " },
};
}
diff --git a/pki/base/common/src/com/netscape/cmscore/cert/PubKeyPrettyPrint.java b/pki/base/common/src/com/netscape/cmscore/cert/PubKeyPrettyPrint.java
index 01e58fa1..ba5acdff 100644
--- a/pki/base/common/src/com/netscape/cmscore/cert/PubKeyPrettyPrint.java
+++ b/pki/base/common/src/com/netscape/cmscore/cert/PubKeyPrettyPrint.java
@@ -17,14 +17,11 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.cert;
-
import java.security.PublicKey;
-
/**
- * This class will display the certificate content in predefined
- * format.
- *
+ * This class will display the certificate content in predefined format.
+ *
* @author Jack Pan-Chen
* @author Andrew Wnuk
* @version $Revision$, $Date$
diff --git a/pki/base/common/src/com/netscape/cmscore/cert/X500NameSubsystem.java b/pki/base/common/src/com/netscape/cmscore/cert/X500NameSubsystem.java
index 539ec82b..acbdfea6 100644
--- a/pki/base/common/src/com/netscape/cmscore/cert/X500NameSubsystem.java
+++ b/pki/base/common/src/com/netscape/cmscore/cert/X500NameSubsystem.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.cert;
-
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.StringTokenizer;
@@ -35,13 +34,12 @@ import com.netscape.certsrv.base.ISubsystem;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.cmscore.util.Debug;
-
/**
- * Subsystem for configuring X500Name related things.
- * It is used for the following.
+ * Subsystem for configuring X500Name related things. It is used for the
+ * following.
* <ul>
- * <li>Add X500Name (string to oid) maps for attributes that
- * are not supported by default.
+ * <li>Add X500Name (string to oid) maps for attributes that are not supported
+ * by default.
* <li>Specify an order for encoding Directory Strings other than the default.
* </ul>
*
@@ -51,11 +49,10 @@ import com.netscape.cmscore.util.Debug;
public class X500NameSubsystem implements ISubsystem {
private IConfigStore mConfig = null;
- public static final String ID = "X500Name";
+ public static final String ID = "X500Name";
private String mId = ID;
- private static final String
- PROP_DIR_STR_ENCODING_ORDER = "directoryStringEncodingOrder";
+ private static final String PROP_DIR_STR_ENCODING_ORDER = "directoryStringEncodingOrder";
private static final String PROP_ATTR = "attr";
private static final String PROP_OID = "oid";
@@ -82,57 +79,62 @@ public class X500NameSubsystem implements ISubsystem {
public static X500NameSubsystem getInstance() {
return mInstance;
}
-
+
/**
- * Initializes this subsystem with the given configuration store.
- * All paramters are optional.
+ * Initializes this subsystem with the given configuration store. All
+ * paramters are optional.
* <ul>
- * <li>Change encoding order of Directory Strings:
+ * <li>Change encoding order of Directory Strings:
+ *
* <pre>
* X500Name.directoryStringEncodingOrder=order seperated by commas
* For example: Printable,BMPString,UniversalString.
* </pre>
- * Possible values are:
+ *
+ * Possible values are:
* <ul>
* <li>Printable
* <li>IA5String
* <li>UniversalString
* <li>BMPString
- * <li>UTF8String
+ * <li>UTF8String
* </ul>
* <p>
- * <li>Add X500Name attributes:
+ * <li>Add X500Name attributes:
+ *
* <pre>
* X500Name.attr.attribute-name.oid=n.n.n.n
- * X500Name.attr.attribute-name.class=value converter class
+ * X500Name.attr.attribute-name.class=value converter class
* </pre>
*
- * The value converter class converts a string to a ASN.1 value.
- * It must implement netscape.security.x509.AVAValueConverter interface.
- * Converter classes provided in CMS are:
+ * The value converter class converts a string to a ASN.1 value. It must
+ * implement netscape.security.x509.AVAValueConverter interface. Converter
+ * classes provided in CMS are:
+ *
* <pre>
* netscape.security.x509.PrintableConverter -
- * Converts to a Printable String value. String must have only
- * printable characters.
+ * Converts to a Printable String value. String must have only
+ * printable characters.
* netscape.security.x509.IA5StringConverter -
- * Converts to a IA5String value. String must have only IA5String
- * characters.
+ * Converts to a IA5String value. String must have only IA5String
+ * characters.
* netscape.security.x509.DirStrConverter -
- * Converts to a Directory (v3) String. String is expected to
- * be in Directory String format according to rfc2253.
+ * Converts to a Directory (v3) String. String is expected to
+ * be in Directory String format according to rfc2253.
* netscape.security.x509.GenericValueConverter -
- * Converts string character by character in the following order
- * from smaller character sets to broadest character set.
- * Printable, IA5String, BMPString, Universal String.
+ * Converts string character by character in the following order
+ * from smaller character sets to broadest character set.
+ * Printable, IA5String, BMPString, Universal String.
* </pre>
+ *
* </ul>
* <P>
- *
+ *
* @param owner owner of this subsystem
* @param config configuration store
*/
public synchronized void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mLogger = CMS.getLogger();
if (Debug.ON) {
Debug.trace(ID + " started");
@@ -142,16 +144,15 @@ public class X500NameSubsystem implements ISubsystem {
// get order for encoding directory strings if any.
setDirStrEncodingOrder();
- // load x500 name maps
+ // load x500 name maps
loadX500NameAttrMaps();
}
/**
- * Loads X500Name String to attribute maps.
- * Called from init.
+ * Loads X500Name String to attribute maps. Called from init.
*/
private void loadX500NameAttrMaps()
- throws EBaseException {
+ throws EBaseException {
X500NameAttrMap globalMap = X500NameAttrMap.getDefault();
IConfigStore attrSubStore = mConfig.getSubStore(PROP_ATTR);
Enumeration attrNames = attrSubStore.getSubStoreNames();
@@ -180,14 +181,13 @@ public class X500NameSubsystem implements ISubsystem {
}
/**
- * Set directory string encoding order.
- * Called from init().
+ * Set directory string encoding order. Called from init().
*/
- private void setDirStrEncodingOrder()
- throws EBaseException {
+ private void setDirStrEncodingOrder()
+ throws EBaseException {
String order = mConfig.getString(PROP_DIR_STR_ENCODING_ORDER, null);
- if (order == null || order.length() == 0) // nothing.
+ if (order == null || order.length() == 0) // nothing.
return;
StringTokenizer toker = new StringTokenizer(order, ", \t");
int numTokens = toker.countTokens();
@@ -196,7 +196,7 @@ public class X500NameSubsystem implements ISubsystem {
String msg = "must be a list of DER tag names seperated by commas.";
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CERT_DIR_STRING", PROP_DIR_STR_ENCODING_ORDER));
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
PROP_DIR_STR_ENCODING_ORDER, msg));
}
@@ -211,7 +211,7 @@ public class X500NameSubsystem implements ISubsystem {
String msg = "unknown DER tag '" + nextTag + "'.";
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CERT_UNKNOWN_TAG", PROP_DIR_STR_ENCODING_ORDER, nextTag));
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
PROP_DIR_STR_ENCODING_ORDER, msg));
}
}
@@ -230,27 +230,27 @@ public class X500NameSubsystem implements ISubsystem {
static {
mDerStr2TagHash.put(
- PRINTABLESTRING, Byte.valueOf(DerValue.tag_PrintableString));
+ PRINTABLESTRING, Byte.valueOf(DerValue.tag_PrintableString));
mDerStr2TagHash.put(
- IA5STRING, Byte.valueOf(DerValue.tag_IA5String));
+ IA5STRING, Byte.valueOf(DerValue.tag_IA5String));
mDerStr2TagHash.put(
- VISIBLESTRING, Byte.valueOf(DerValue.tag_VisibleString));
+ VISIBLESTRING, Byte.valueOf(DerValue.tag_VisibleString));
mDerStr2TagHash.put(
- T61STRING, Byte.valueOf(DerValue.tag_T61String));
+ T61STRING, Byte.valueOf(DerValue.tag_T61String));
mDerStr2TagHash.put(
- BMPSTRING, Byte.valueOf(DerValue.tag_BMPString));
+ BMPSTRING, Byte.valueOf(DerValue.tag_BMPString));
mDerStr2TagHash.put(
- UNIVERSALSTRING, Byte.valueOf(DerValue.tag_UniversalString));
+ UNIVERSALSTRING, Byte.valueOf(DerValue.tag_UniversalString));
mDerStr2TagHash.put(
- UFT8STRING, Byte.valueOf(DerValue.tag_UTF8String));
+ UFT8STRING, Byte.valueOf(DerValue.tag_UTF8String));
}
private byte derStr2Tag(String s) {
- if (s == null || s.length() == 0)
+ if (s == null || s.length() == 0)
throw new IllegalArgumentException();
Byte tag = (Byte) mDerStr2TagHash.get(s);
- if (tag == null)
+ if (tag == null)
throw new IllegalArgumentException();
return tag.byteValue();
}
@@ -265,9 +265,8 @@ public class X500NameSubsystem implements ISubsystem {
}
/*
- * Returns the root configuration storage of this system.
- * <P>
- *
+ * Returns the root configuration storage of this system. <P>
+ *
* @return configuration store of this subsystem
*/
public IConfigStore getConfigStore() {
@@ -278,7 +277,7 @@ public class X500NameSubsystem implements ISubsystem {
protected void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM,
- ILogger.S_ADMIN, level, msg);
+ ILogger.S_ADMIN, level, msg);
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/connector/HttpConnFactory.java b/pki/base/common/src/com/netscape/cmscore/connector/HttpConnFactory.java
index 5a607ee9..925c65b3 100644
--- a/pki/base/common/src/com/netscape/cmscore/connector/HttpConnFactory.java
+++ b/pki/base/common/src/com/netscape/cmscore/connector/HttpConnFactory.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.connector;
-
import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.authority.IAuthority;
import com.netscape.certsrv.base.EBaseException;
@@ -28,7 +27,6 @@ import com.netscape.certsrv.logging.ILogger;
import com.netscape.cmsutil.http.JssSSLSocketFactory;
import com.netscape.cmsutil.net.ISocketFactory;
-
/**
* Factory for getting HTTP Connections to a HTTPO server
*/
@@ -38,14 +36,14 @@ public class HttpConnFactory {
private ILogger mLogger = CMS.getLogger();
- private int mNumConns = 0; // number of available conns in array
- private int mTotal = 0; // total num conns
+ private int mNumConns = 0; // number of available conns in array
+ private int mTotal = 0; // total num conns
private IHttpConnection mMasterConn = null; // master connection object.
private IHttpConnection mConns[];
private IAuthority mSource = null;
private IRemoteAuthority mDest = null;
private String mNickname = "";
- private int mTimeout = 0;
+ private int mTimeout = 0;
/**
* default value for the above at init time.
@@ -53,20 +51,20 @@ public class HttpConnFactory {
private boolean mDefErrorIfDown = false;
/**
- * Constructor for initializing from the config store.
- * must be followed by init(IConfigStore)
+ * Constructor for initializing from the config store. must be followed by
+ * init(IConfigStore)
*/
public HttpConnFactory() {
}
/**
* Constructor for HttpConnFactory
+ *
* @param minConns minimum number of connections to have available
- * @param maxConns max number of connections to have available. This is
+ * @param maxConns max number of connections to have available. This is
* @param serverInfo server connection info - host, port, etc.
*/
- public HttpConnFactory(int minConns, int maxConns, IAuthority source, IRemoteAuthority dest, String nickname, int timeout
- ) throws EBaseException {
+ public HttpConnFactory(int minConns, int maxConns, IAuthority source, IRemoteAuthority dest, String nickname, int timeout) throws EBaseException {
CMS.debug("In HttpConnFactory constructor mTimeout " + timeout);
mSource = source;
@@ -78,21 +76,21 @@ public class HttpConnFactory {
}
/**
- * initialize parameters obtained from either constructor or
- * config store
+ * initialize parameters obtained from either constructor or config store
+ *
* @param minConns minimum number of connection handls to have available.
* @param maxConns maximum total number of connections to ever have.
* @param connInfo ldap connection info.
* @param authInfo ldap authentication info.
- * @exception ELdapException if any error occurs.
+ * @exception ELdapException if any error occurs.
*/
- private void init(int minConns, int maxConns
- )
- throws EBaseException {
+ private void init(int minConns, int maxConns
+ )
+ throws EBaseException {
CMS.debug("min conns " + minConns + " maxConns " + maxConns);
if (minConns <= 0 || maxConns <= 0 || minConns > maxConns) {
- CMS.debug("bad values from CMS.cfg");
+ CMS.debug("bad values from CMS.cfg");
} else {
@@ -109,11 +107,11 @@ public class HttpConnFactory {
CMS.debug("before makeConnection");
CMS.debug(
- "initializing HttpConnFactory with mininum " + mMinConns + " and maximum " + mMaxConns +
- " connections to ");
+ "initializing HttpConnFactory with mininum " + mMinConns + " and maximum " + mMaxConns +
+ " connections to ");
// initalize minimum number of connection handles available.
- //makeMinimum();
+ // makeMinimum();
CMS.debug("leaving HttpConnFactory init.");
}
@@ -126,21 +124,21 @@ public class HttpConnFactory {
try {
ISocketFactory tFactory = new JssSSLSocketFactory(mNickname);
-
+
if (mTimeout == 0) {
retConn = CMS.getHttpConnection(mDest, tFactory);
} else {
retConn = CMS.getHttpConnection(mDest, tFactory, mTimeout);
}
- } catch (Exception e) {
+ } catch (Exception e) {
CMS.debug("can't make new Htpp Connection");
throw new EBaseException(
- "Can't create new Http Connection");
+ "Can't create new Http Connection");
}
-
+
return retConn;
}
@@ -160,7 +158,7 @@ public class HttpConnFactory {
return;
CMS.debug(
- "increasing minimum connections by " + increment);
+ "increasing minimum connections by " + increment);
for (int i = increment - 1; i >= 0; i--) {
mConns[i] = (IHttpConnection) createConnection();
}
@@ -172,77 +170,71 @@ public class HttpConnFactory {
}
/**
- * gets a conenction from this factory.
- * All connections obtained from the factory must be returned by
- * returnConn() method.
- * The best thing to do is to put returnConn in a finally clause so it
- * always gets called. For example,
+ * gets a conenction from this factory. All connections obtained from the
+ * factory must be returned by returnConn() method. The best thing to do is
+ * to put returnConn in a finally clause so it always gets called. For
+ * example,
+ *
* <pre>
- * IHttpConnection c = null;
- * try {
- * c = factory.getConn();
- * myclass.do_something_with_c(c);
- * }
- * catch (EBaseException e) {
- * handle_error_here();
- * }
- * finally {
- * factory.returnConn(c);
- * }
+ * IHttpConnection c = null;
+ * try {
+ * c = factory.getConn();
+ * myclass.do_something_with_c(c);
+ * } catch (EBaseException e) {
+ * handle_error_here();
+ * } finally {
+ * factory.returnConn(c);
+ * }
* </pre>
*/
- public IHttpConnection getConn()
- throws EBaseException {
+ public IHttpConnection getConn()
+ throws EBaseException {
return getConn(true);
}
/**
- * Returns a Http connection - a clone of the master connection.
- * All connections should be returned to the factory using returnConn()
- * to recycle connection objects.
- * If not returned the limited max number is affected but if that
- * number is large not much harm is done.
- * Returns null if maximum number of connections reached.
- * The best thing to do is to put returnConn in a finally clause so it
- * always gets called. For example,
+ * Returns a Http connection - a clone of the master connection. All
+ * connections should be returned to the factory using returnConn() to
+ * recycle connection objects. If not returned the limited max number is
+ * affected but if that number is large not much harm is done. Returns null
+ * if maximum number of connections reached. The best thing to do is to put
+ * returnConn in a finally clause so it always gets called. For example,
+ *
* <pre>
- * IHttpConnnection c = null;
- * try {
- * c = factory.getConn();
- * myclass.do_something_with_c(c);
- * }
- * catch (EBaseException e) {
- * handle_error_here();
- * }
- * finally {
- * factory.returnConn(c);
- * }
+ * IHttpConnnection c = null;
+ * try {
+ * c = factory.getConn();
+ * myclass.do_something_with_c(c);
+ * } catch (EBaseException e) {
+ * handle_error_here();
+ * } finally {
+ * factory.returnConn(c);
+ * }
* </pre>
- */
- public synchronized IHttpConnection getConn(boolean waitForConn)
- throws EBaseException {
+ */
+ public synchronized IHttpConnection getConn(boolean waitForConn)
+ throws EBaseException {
boolean waited = false;
CMS.debug("In HttpConnFactory.getConn");
- if (mNumConns == 0)
+ if (mNumConns == 0)
makeMinimum();
if (mNumConns == 0) {
if (!waitForConn)
return null;
try {
CMS.debug("getConn: out of http connections");
- log(ILogger.LL_WARN,
- "Ran out of http connections available "
- );
+ log(ILogger.LL_WARN,
+ "Ran out of http connections available ");
waited = true;
CMS.debug("HttpConn:about to wait for a new http connection");
- while (mNumConns == 0)
+ while (mNumConns == 0)
wait();
CMS.debug("HttpConn:done waiting for new http connection");
} catch (InterruptedException e) {
}
- }
+ }
mNumConns--;
IHttpConnection conn = mConns[mNumConns];
@@ -250,9 +242,8 @@ public class HttpConnFactory {
if (waited) {
CMS.debug("HttpConn:had to wait for an available connection from pool");
- log(ILogger.LL_WARN,
- "Http connections are available again in http connection pool "
- );
+ log(ILogger.LL_WARN,
+ "Http connections are available again in http connection pool ");
}
CMS.debug("HttpgetConn: mNumConns now " + mNumConns);
@@ -260,22 +251,20 @@ public class HttpConnFactory {
}
/**
- * Teturn connection to the factory.
- * This is mandatory after a getConn().
+ * Teturn connection to the factory. This is mandatory after a getConn().
* The best thing to do is to put returnConn in a finally clause so it
- * always gets called. For example,
+ * always gets called. For example,
+ *
* <pre>
- * IHttpConnection c = null;
- * try {
- * c = factory.getConn();
- * myclass.do_something_with_c(c);
- * }
- * catch (EBaseException e) {
- * handle_error_here();
- * }
- * finally {
- * factory.returnConn(c);
- * }
+ * IHttpConnection c = null;
+ * try {
+ * c = factory.getConn();
+ * myclass.do_something_with_c(c);
+ * } catch (EBaseException e) {
+ * handle_error_here();
+ * } finally {
+ * factory.returnConn(c);
+ * }
* </pre>
*/
public synchronized void returnConn(IHttpConnection conn) {
@@ -289,7 +278,7 @@ public class HttpConnFactory {
for (int i = 0; i < mNumConns; i++) {
if (mConns[i] == conn) {
CMS.debug(
- "returnConn: previously returned connection. " + conn);
+ "returnConn: previously returned connection. " + conn);
}
}
@@ -303,11 +292,11 @@ public class HttpConnFactory {
*/
private void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_LDAP, level,
- "In Http (bound) connection pool to" +
- msg);
+ "In Http (bound) connection pool to" +
+ msg);
}
protected void finalize()
- throws Exception {
+ throws Exception {
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/connector/HttpConnection.java b/pki/base/common/src/com/netscape/cmscore/connector/HttpConnection.java
index e8b03542..cf0caf64 100644
--- a/pki/base/common/src/com/netscape/cmscore/connector/HttpConnection.java
+++ b/pki/base/common/src/com/netscape/cmscore/connector/HttpConnection.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.connector;
-
import java.io.IOException;
import java.util.StringTokenizer;
@@ -33,34 +32,32 @@ import com.netscape.cmsutil.http.HttpRequest;
import com.netscape.cmsutil.http.HttpResponse;
import com.netscape.cmsutil.net.ISocketFactory;
-
public class HttpConnection implements IHttpConnection {
protected IRemoteAuthority mDest = null;
protected HttpRequest mHttpreq = new HttpRequest();
protected IRequestEncoder mReqEncoder = null;
protected HttpClient mHttpClient = null;
- protected boolean Connect(String host, HttpClient client)
- {
- StringTokenizer st = new StringTokenizer(host, " ");
- while (st.hasMoreTokens()) {
- String hp = st.nextToken(); // host:port
- StringTokenizer st1 = new StringTokenizer(hp, ":");
- try {
- String h = st1.nextToken();
- int p = Integer.parseInt(st1.nextToken());
- client.connect(h, p);
- return true;
- } catch (Exception e) {
- // may want to log the failure
- }
- try {
- Thread.sleep(5000); // 5 seconds
- } catch (Exception e) {
- }
-
- }
- return false;
+ protected boolean Connect(String host, HttpClient client) {
+ StringTokenizer st = new StringTokenizer(host, " ");
+ while (st.hasMoreTokens()) {
+ String hp = st.nextToken(); // host:port
+ StringTokenizer st1 = new StringTokenizer(hp, ":");
+ try {
+ String h = st1.nextToken();
+ int p = Integer.parseInt(st1.nextToken());
+ client.connect(h, p);
+ return true;
+ } catch (Exception e) {
+ // may want to log the failure
+ }
+ try {
+ Thread.sleep(5000); // 5 seconds
+ } catch (Exception e) {
+ }
+
+ }
+ return false;
}
public HttpConnection(IRemoteAuthority dest, ISocketFactory factory) {
@@ -76,22 +73,22 @@ public class HttpConnection implements IHttpConnection {
CMS.debug("HttpConnection: connecting to " + dest.getHost() + ":" + dest.getPort());
String host = dest.getHost();
// we could have a list of host names in the host parameters
- // the format is, for example,
+ // the format is, for example,
// "directory.knowledge.com:1050 people.catalog.com 199.254.1.2"
if (host != null && host.indexOf(' ') != -1) {
- // try to do client-side failover
- boolean connected = false;
- do {
- connected = Connect(host, mHttpClient);
- } while (!connected);
+ // try to do client-side failover
+ boolean connected = false;
+ do {
+ connected = Connect(host, mHttpClient);
+ } while (!connected);
} else {
- mHttpClient.connect(host, dest.getPort());
+ mHttpClient.connect(host, dest.getPort());
}
CMS.debug("HttpConnection: connected to " + dest.getHost() + ":" + dest.getPort());
} catch (IOException e) {
// server's probably down. that's fine. try later.
- //System.out.println(
- //"Can't connect to server in connection creation");
+ // System.out.println(
+ // "Can't connect to server in connection creation");
}
}
@@ -110,19 +107,20 @@ public class HttpConnection implements IHttpConnection {
CMS.debug("HttpConnection: connected to " + dest.getHost() + ":" + dest.getPort() + " timeout:" + timeout);
} catch (IOException e) {
// server's probably down. that's fine. try later.
- //System.out.println(
- //"Can't connect to server in connection creation");
+ // System.out.println(
+ // "Can't connect to server in connection creation");
CMS.debug("CMSConn:IOException in creating HttpConnection " + e.toString());
}
}
// Insert end
- /**
+ /**
* sends a request to remote RA/CA, returning the result.
- * @throws EBaseException if request could not be encoded
+ *
+ * @throws EBaseException if request could not be encoded
*/
- public IPKIMessage send(IPKIMessage tomsg)
- throws EBaseException {
+ public IPKIMessage send(IPKIMessage tomsg)
+ throws EBaseException {
IPKIMessage replymsg = null;
CMS.debug("in HttpConnection.send " + this);
@@ -143,8 +141,8 @@ public class HttpConnection implements IHttpConnection {
}
boolean reconnect = false;
- mHttpreq.setHeader("Content-Length",
- Integer.toString(content.length()));
+ mHttpreq.setHeader("Content-Length",
+ Integer.toString(content.length()));
if (Debug.ON)
Debug.trace("request encoded length " + content.length());
mHttpreq.setContent(content);
@@ -220,8 +218,8 @@ public class HttpConnection implements IHttpConnection {
}
}
- // decode reply.
- // if reply is bad, error is thrown and request will be resent
+ // decode reply.
+ // if reply is bad, error is thrown and request will be resent
String pcontent = p.getContent();
if (Debug.ON) {
diff --git a/pki/base/common/src/com/netscape/cmscore/connector/HttpConnector.java b/pki/base/common/src/com/netscape/cmscore/connector/HttpConnector.java
index fefbe0f3..d7a73335 100644
--- a/pki/base/common/src/com/netscape/cmscore/connector/HttpConnector.java
+++ b/pki/base/common/src/com/netscape/cmscore/connector/HttpConnector.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.connector;
-
import java.util.Vector;
import com.netscape.certsrv.apps.CMS;
@@ -36,7 +35,6 @@ import com.netscape.certsrv.request.RequestStatus;
import com.netscape.cmsutil.http.JssSSLSocketFactory;
import com.netscape.cmsutil.net.ISocketFactory;
-
public class HttpConnector implements IConnector {
protected IAuthority mSource = null;
protected IRemoteAuthority mDest = null;
@@ -45,13 +43,14 @@ public class HttpConnector implements IConnector {
// XXX todo make this a pool.
// XXX use CMMF in the future.
protected IHttpConnection mConn = null;
- private Thread mResendThread = null;
+ private Thread mResendThread = null;
private IResender mResender = null;
private int mTimeout;
private HttpConnFactory mConnFactory = null;
+
public HttpConnector(IAuthority source, String nickName,
- IRemoteAuthority dest, int resendInterval, IConfigStore config) throws EBaseException {
+ IRemoteAuthority dest, int resendInterval, IConfigStore config) throws EBaseException {
mTimeout = 0;
mSource = source;
@@ -70,22 +69,22 @@ public class HttpConnector implements IConnector {
CMS.debug("can't create new HttpConnFactory " + e.toString());
}
- // mConn = CMS.getHttpConnection(dest, mFactory);
- // this will start resending past requests in parallel.
- mResender = CMS.getResender(mSource, nickName, dest, resendInterval);
+ // mConn = CMS.getHttpConnection(dest, mFactory);
+ // this will start resending past requests in parallel.
+ mResender = CMS.getResender(mSource, nickName, dest, resendInterval);
mResendThread = new Thread(mResender, "HttpConnector");
}
-
+
// Inserted by beomsuk
public HttpConnector(IAuthority source, String nickName,
- IRemoteAuthority dest, int resendInterval, IConfigStore config, int timeout) throws EBaseException {
+ IRemoteAuthority dest, int resendInterval, IConfigStore config, int timeout) throws EBaseException {
mSource = source;
mDest = dest;
mTimeout = timeout;
mFactory = new JssSSLSocketFactory(nickName);
int minConns = config.getInteger("minHttpConns", 1);
- int maxConns = config.getInteger("maxHttpConns", 15);
+ int maxConns = config.getInteger("maxHttpConns", 15);
CMS.debug("HttpConn: min " + minConns);
CMS.debug("HttpConn: max " + maxConns);
@@ -96,15 +95,15 @@ public class HttpConnector implements IConnector {
CMS.debug("can't create new HttpConnFactory");
}
- // this will start resending past requests in parallel.
- mResender = CMS.getResender(mSource, nickName, dest, resendInterval);
+ // this will start resending past requests in parallel.
+ mResender = CMS.getResender(mSource, nickName, dest, resendInterval);
mResendThread = new Thread(mResender, "HttpConnector");
}
// Insert end
-
- public boolean send(IRequest r)
- throws EBaseException {
+
+ public boolean send(IRequest r)
+ throws EBaseException {
IHttpConnection curConn = null;
try {
@@ -141,35 +140,35 @@ public class HttpConnector implements IConnector {
CMS.debug("reply status " + replyStatus);
// non terminal states.
- // XXX hack: don't resend get revocation info requests since
+ // XXX hack: don't resend get revocation info requests since
// resent results are ignored.
if ((!r.getRequestType().equals(
- IRequest.GETREVOCATIONINFO_REQUEST)) &&
- (replyStatus == RequestStatus.BEGIN ||
- replyStatus == RequestStatus.PENDING ||
- replyStatus == RequestStatus.SVC_PENDING ||
+ IRequest.GETREVOCATIONINFO_REQUEST)) &&
+ (replyStatus == RequestStatus.BEGIN ||
+ replyStatus == RequestStatus.PENDING ||
+ replyStatus == RequestStatus.SVC_PENDING ||
replyStatus == RequestStatus.APPROVED)) {
CMS.debug("HttpConn: remote request id still pending " +
- r.getRequestId() + " state " + replyStatus);
+ r.getRequestId() + " state " + replyStatus);
mSource.log(ILogger.LL_INFO, CMS.getLogMessage("CMSCORE_CONNECTOR_REQUEST_NOT_COMPLETED", r.getRequestId().toString()));
mResender.addRequest(r);
return false;
}
// request was completed.
- replymsg.toRequest(r); // this only copies contents.
+ replymsg.toRequest(r); // this only copies contents.
// terminal states other than completed
- if (replyStatus == RequestStatus.REJECTED ||
- replyStatus == RequestStatus.CANCELED) {
+ if (replyStatus == RequestStatus.REJECTED ||
+ replyStatus == RequestStatus.CANCELED) {
CMS.debug(
- "remote request id " + r.getRequestId() +
- " was rejected or cancelled.");
+ "remote request id " + r.getRequestId() +
+ " was rejected or cancelled.");
r.setExtData(IRequest.REMOTE_STATUS, replyStatus.toString());
r.setExtData(IRequest.RESULT, IRequest.RES_ERROR);
r.setExtData(IRequest.ERROR,
- new EBaseException(CMS.getUserMessage("CMS_BASE_REMOTE_AUTHORITY_ERROR")));
- // XXX overload svcerrors for now.
+ new EBaseException(CMS.getUserMessage("CMS_BASE_REMOTE_AUTHORITY_ERROR")));
+ // XXX overload svcerrors for now.
Vector policyErrors = r.getExtDataInStringVector(IRequest.ERRORS);
if (policyErrors != null && policyErrors.size() > 0) {
@@ -178,18 +177,18 @@ public class HttpConnector implements IConnector {
}
CMS.debug(
- "remote request id " + r.getRequestId() + " was completed");
+ "remote request id " + r.getRequestId() + " was completed");
return true;
} catch (EBaseException e) {
CMS.debug("HttpConn: inside EBaseException " + e.toString());
-
+
if (!r.getRequestType().equals(IRequest.GETREVOCATIONINFO_REQUEST))
mResender.addRequest(r);
CMS.debug("HttpConn: error sending request to cert " + e.toString());
mSource.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CONNECTOR_SEND_REQUEST", r.getRequestId().toString(), mDest.getHost(), Integer.toString(mDest.getPort())));
- // mSource.log(ILogger.LL_INFO,
- // "Queing " + r.getRequestId() + " for resend.");
+ // mSource.log(ILogger.LL_INFO,
+ // "Queing " + r.getRequestId() + " for resend.");
return false;
} finally {
diff --git a/pki/base/common/src/com/netscape/cmscore/connector/HttpPKIMessage.java b/pki/base/common/src/com/netscape/cmscore/connector/HttpPKIMessage.java
index e236655d..51e3ed8a 100644
--- a/pki/base/common/src/com/netscape/cmscore/connector/HttpPKIMessage.java
+++ b/pki/base/common/src/com/netscape/cmscore/connector/HttpPKIMessage.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.connector;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
@@ -32,9 +31,8 @@ import com.netscape.certsrv.connector.IHttpPKIMessage;
import com.netscape.certsrv.request.IRequest;
import com.netscape.cmscore.util.Debug;
-
/**
- * simple name/value pair message.
+ * simple name/value pair message.
*/
public class HttpPKIMessage implements IHttpPKIMessage {
/**
@@ -66,7 +64,7 @@ public class HttpPKIMessage implements IHttpPKIMessage {
* copy contents of request to make a simple name/value message.
*/
public void fromRequest(IRequest r) {
- // actually don't need to copy source id since
+ // actually don't need to copy source id since
reqType = r.getRequestType();
reqId = r.getRequestId().toString();
reqStatus = r.getRequestStatus().toString();
@@ -96,7 +94,7 @@ public class HttpPKIMessage implements IHttpPKIMessage {
* copy contents to request.
*/
public void toRequest(IRequest r) {
- // id, type and status
+ // id, type and status
// type had to have been set in instantiation.
// id is checked but not reset.
// request status cannot be set, but can be looked at.
@@ -118,16 +116,16 @@ public class HttpPKIMessage implements IHttpPKIMessage {
r.setExtData(key, (Hashtable) value);
} else {
CMS.debug("HttpPKIMessage.toRequest(): key: " + key +
- " has unexpected type " + value.getClass().toString());
+ " has unexpected type " + value.getClass().toString());
}
} catch (NoSuchElementException e) {
- CMS.debug("Incorrect pairing of name/value for " + key);
+ CMS.debug("Incorrect pairing of name/value for " + key);
}
}
}
private void writeObject(java.io.ObjectOutputStream out)
- throws IOException {
+ throws IOException {
CMS.debug("writeObject");
out.writeObject(reqType);
if (Debug.ON)
@@ -145,34 +143,34 @@ public class HttpPKIMessage implements IHttpPKIMessage {
Object val = null;
key = enum1.nextElement();
try {
- val = enum1.nextElement();
- // test if key and value are serializable
- ObjectOutputStream os =
- new ObjectOutputStream(new ByteArrayOutputStream());
- os.writeObject(key);
- os.writeObject(val);
-
- // ok, if we dont have problem serializing the objects,
- // then write the objects into the real object stream
- out.writeObject(key);
- out.writeObject(val);
+ val = enum1.nextElement();
+ // test if key and value are serializable
+ ObjectOutputStream os =
+ new ObjectOutputStream(new ByteArrayOutputStream());
+ os.writeObject(key);
+ os.writeObject(val);
+
+ // ok, if we dont have problem serializing the objects,
+ // then write the objects into the real object stream
+ out.writeObject(key);
+ out.writeObject(val);
} catch (Exception e) {
- // skip not serialiable attribute in DRM
- // DRM does not need to store the enrollment request anymore
- CMS.debug("HttpPKIMessage:skipped key=" +
- key.getClass().getName());
- if (val == null) {
- CMS.debug("HttpPKIMessage:skipped val= null");
- } else {
- CMS.debug("HttpPKIMessage:skipped val=" +
- val.getClass().getName());
- }
+ // skip not serialiable attribute in DRM
+ // DRM does not need to store the enrollment request anymore
+ CMS.debug("HttpPKIMessage:skipped key=" +
+ key.getClass().getName());
+ if (val == null) {
+ CMS.debug("HttpPKIMessage:skipped val= null");
+ } else {
+ CMS.debug("HttpPKIMessage:skipped val=" +
+ val.getClass().getName());
+ }
}
}
}
private void readObject(java.io.ObjectInputStream in)
- throws IOException, ClassNotFoundException, OptionalDataException {
+ throws IOException, ClassNotFoundException, OptionalDataException {
reqType = (String) in.readObject();
reqId = (String) in.readObject();
reqStatus = (String) in.readObject();
@@ -185,21 +183,21 @@ public class HttpPKIMessage implements IHttpPKIMessage {
while (true) {
boolean skipped = false;
try {
- keyorval = in.readObject();
+ keyorval = in.readObject();
} catch (OptionalDataException e) {
- throw e;
+ throw e;
} catch (IOException e) {
- // just skipped parameter
- CMS.debug("skipped attribute in request e="+e);
- if (!iskey) {
- int s = mNameVals.size();
- if (s > 0) {
- // remove previous key if this is value
- mNameVals.removeElementAt(s - 1);
- skipped = true;
- keyorval = "";
- }
- }
+ // just skipped parameter
+ CMS.debug("skipped attribute in request e=" + e);
+ if (!iskey) {
+ int s = mNameVals.size();
+ if (s > 0) {
+ // remove previous key if this is value
+ mNameVals.removeElementAt(s - 1);
+ skipped = true;
+ keyorval = "";
+ }
+ }
}
if (iskey) {
if (Debug.ON)
@@ -213,9 +211,9 @@ public class HttpPKIMessage implements IHttpPKIMessage {
if (Debug.ON)
Debug.trace("read " + keyorval);
if (!skipped) {
- if (keyorval == null)
- break;
- mNameVals.addElement(keyorval);
+ if (keyorval == null)
+ break;
+ mNameVals.addElement(keyorval);
}
}
} catch (OptionalDataException e) {
diff --git a/pki/base/common/src/com/netscape/cmscore/connector/HttpRequestEncoder.java b/pki/base/common/src/com/netscape/cmscore/connector/HttpRequestEncoder.java
index 4a762dd8..29c3b8d0 100644
--- a/pki/base/common/src/com/netscape/cmscore/connector/HttpRequestEncoder.java
+++ b/pki/base/common/src/com/netscape/cmscore/connector/HttpRequestEncoder.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.connector;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -28,13 +27,12 @@ import java.io.OptionalDataException;
import com.netscape.certsrv.connector.IRequestEncoder;
import com.netscape.cmscore.util.Debug;
-
/**
- * encodes a request by serializing it.
+ * encodes a request by serializing it.
*/
public class HttpRequestEncoder implements IRequestEncoder {
public String encode(Object r)
- throws IOException {
+ throws IOException {
String s = null;
byte[] serial;
ByteArrayOutputStream ba = new ByteArrayOutputStream();
@@ -47,7 +45,7 @@ public class HttpRequestEncoder implements IRequestEncoder {
}
public Object decode(String s)
- throws IOException {
+ throws IOException {
Object result = null;
byte[] serial = null;
@@ -59,7 +57,7 @@ public class HttpRequestEncoder implements IRequestEncoder {
result = is.readObject();
} catch (ClassNotFoundException e) {
- // XXX hack: change this
+ // XXX hack: change this
if (Debug.ON)
Debug.trace("class not found ex " + e + e.getMessage());
throw new IOException("Class Not Found " + e.getMessage());
diff --git a/pki/base/common/src/com/netscape/cmscore/connector/LocalConnector.java b/pki/base/common/src/com/netscape/cmscore/connector/LocalConnector.java
index 9272cc93..79f77e1a 100644
--- a/pki/base/common/src/com/netscape/cmscore/connector/LocalConnector.java
+++ b/pki/base/common/src/com/netscape/cmscore/connector/LocalConnector.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.connector;
-
import java.util.Hashtable;
import com.netscape.certsrv.apps.CMS;
@@ -36,7 +35,6 @@ import com.netscape.certsrv.request.RequestId;
import com.netscape.certsrv.request.RequestStatus;
import com.netscape.cmscore.util.Debug;
-
public class LocalConnector implements IConnector {
ILogger mLogger = CMS.getLogger();
ICertAuthority mSource = null;
@@ -46,45 +44,44 @@ public class LocalConnector implements IConnector {
public LocalConnector(ICertAuthority source, IAuthority dest) {
mSource = source;
// mSource.log(ILogger.LL_DEBUG, "Local connector setup for source " +
- // mSource.getId());
+ // mSource.getId());
mDest = dest;
CMS.debug("Local connector setup for dest " +
- mDest.getId());
+ mDest.getId());
// register for events.
mDest.registerRequestListener(new LocalConnListener());
CMS.debug("Connector inited");
}
/**
- * send request to local authority.
- * returns resulting request
+ * send request to local authority. returns resulting request
*/
public boolean send(IRequest r) throws EBaseException {
if (Debug.ON) {
Debug.print("send request type " + r.getRequestType() + " status=" + r.getRequestStatus() + " to " + mDest.getId() + " id=" + r.getRequestId() + "\n");
}
CMS.debug("send request type " + r.getRequestType() +
- " to " + mDest.getId());
+ " to " + mDest.getId());
IRequestQueue destQ = mDest.getRequestQueue();
IRequest destreq = destQ.newRequest(r.getRequestType());
CMS.debug("local connector dest req " +
- destreq.getRequestId() + " created for source rId " + r.getRequestId());
- // mSource.log(ILogger.LL_DEBUG,
- // "setting connector dest " + mDest.getId() +
- // " source id to " + r.getRequestId());
+ destreq.getRequestId() + " created for source rId " + r.getRequestId());
+ // mSource.log(ILogger.LL_DEBUG,
+ // "setting connector dest " + mDest.getId() +
+ // " source id to " + r.getRequestId());
- // XXX set context to the real identity later.
+ // XXX set context to the real identity later.
destreq.setSourceId(
- mSource.getX500Name().toString() + ":" + r.getRequestId().toString());
- //destreq.copyContents(r); // copy meta attributes in request.
+ mSource.getX500Name().toString() + ":" + r.getRequestId().toString());
+ // destreq.copyContents(r); // copy meta attributes in request.
transferRequest(r, destreq);
// XXX requestor type is not transferred on return.
destreq.setExtData(IRequest.REQUESTOR_TYPE,
- IRequest.REQUESTOR_RA);
+ IRequest.REQUESTOR_RA);
CMS.debug("connector dest " + mDest.getId() +
- " processing " + destreq.getRequestId());
+ " processing " + destreq.getRequestId());
// set context before calling process request so
// that request subsystem can record the creator
@@ -98,7 +95,7 @@ public class LocalConnector implements IConnector {
}
// Locally cache the source request so that we
- // can update it when the dest request is
+ // can update it when the dest request is
// processed (when LocalConnListener is being called).
mSourceReqs.put(r.getRequestId().toString(), r);
try {
@@ -111,8 +108,8 @@ public class LocalConnector implements IConnector {
}
CMS.debug("connector dest " + mDest.getId() +
- " processed " + destreq.getRequestId() +
- " status " + destreq.getRequestStatus());
+ " processed " + destreq.getRequestId() +
+ " status " + destreq.getRequestStatus());
if (destreq.getRequestStatus() == RequestStatus.COMPLETE) {
// no need to transfer contents if request wasn't complete.
@@ -126,7 +123,7 @@ public class LocalConnector implements IConnector {
public class LocalConnListener implements IRequestListener {
public void init(ISubsystem sys, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
}
public void set(String name, String val) {
@@ -136,36 +133,37 @@ public class LocalConnector implements IConnector {
if (Debug.ON) {
Debug.print("dest " + mDest.getId() + " done with " + destreq.getRequestId());
}
- CMS.debug(
- "dest " + mDest.getId() + " done with " + destreq.getRequestId());
+ CMS.debug(
+ "dest " + mDest.getId() + " done with " + destreq.getRequestId());
IRequestQueue sourceQ = mSource.getRequestQueue();
- // accept requests that only belong to us.
+ // accept requests that only belong to us.
// XXX review death scenarios here. - If system dies anywhere
- // here need to check all requests at next server startup.
+ // here need to check all requests at next server startup.
String sourceNameAndId = destreq.getSourceId();
String sourceName = mSource.getX500Name().toString();
- if (sourceNameAndId == null ||
- !sourceNameAndId.toString().regionMatches(0,
- sourceName, 0, sourceName.length())) {
+ if (sourceNameAndId == null ||
+ !sourceNameAndId.toString().regionMatches(0,
+ sourceName, 0, sourceName.length())) {
CMS.debug("request " + destreq.getRequestId() +
- " from " + sourceNameAndId + " not ours.");
+ " from " + sourceNameAndId + " not ours.");
return;
}
int index = sourceNameAndId.lastIndexOf(':');
if (index == -1) {
- mSource.log(ILogger.LL_FAILURE,
- "request " + destreq.getRequestId() +
- " for " + sourceNameAndId + " malformed.");
+ mSource.log(ILogger.LL_FAILURE,
+ "request " + destreq.getRequestId() +
+ " for " + sourceNameAndId + " malformed.");
return;
}
String sourceId = sourceNameAndId.substring(index + 1);
RequestId rId = new RequestId(sourceId);
- // mSource.log(ILogger.LL_DEBUG, mDest.getId() + " " +
- // destreq.getRequestId() + " mapped to " + mSource.getId() + " " + rId);
+ // mSource.log(ILogger.LL_DEBUG, mDest.getId() + " " +
+ // destreq.getRequestId() + " mapped to " + mSource.getId() + " " +
+ // rId);
IRequest r = null;
@@ -174,7 +172,7 @@ public class LocalConnector implements IConnector {
// performance enhancement, approved request will
// not be immediately available in the database. So
// retrieving the request from the queue within
- // the serviceRequest() function will have
+ // the serviceRequest() function will have
// diffculities.
// You may wonder what happen if the system crashes
// during the request servicing. Yes, the request
@@ -182,14 +180,14 @@ public class LocalConnector implements IConnector {
// resubmit their requests again.
// Note that the pending requests, on the other hand,
// are persistent before the servicing.
- // Please see stateEngine() function in
+ // Please see stateEngine() function in
// ARequestQueue.java for details.
r = (IRequest) mSourceReqs.get(rId);
if (r != null) {
if (r.getRequestStatus() != RequestStatus.SVC_PENDING) {
- mSource.log(ILogger.LL_FAILURE,
- "request state of " + rId + "not pending " +
- " from dest authority " + mDest.getId());
+ mSource.log(ILogger.LL_FAILURE,
+ "request state of " + rId + "not pending " +
+ " from dest authority " + mDest.getId());
sourceQ.releaseRequest(r);
return;
}
@@ -209,4 +207,3 @@ public class LocalConnector implements IConnector {
RequestTransfer.transfer(src, dest);
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/connector/RemoteAuthority.java b/pki/base/common/src/com/netscape/cmscore/connector/RemoteAuthority.java
index ddd02f82..48e722cf 100644
--- a/pki/base/common/src/com/netscape/cmscore/connector/RemoteAuthority.java
+++ b/pki/base/common/src/com/netscape/cmscore/connector/RemoteAuthority.java
@@ -17,23 +17,19 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.connector;
-
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.connector.IRemoteAuthority;
-
public class RemoteAuthority implements IRemoteAuthority {
String mHost = null;
int mPort = -1;
String mURI = null;
int mTimeout = 0;
-
+
/**
- * host parameter can be:
- * "directory.knowledge.com"
- * "199.254.1.2"
- * "directory.knowledge.com:1050 people.catalog.com 199.254.1.2"
+ * host parameter can be: "directory.knowledge.com" "199.254.1.2"
+ * "directory.knowledge.com:1050 people.catalog.com 199.254.1.2"
*/
public RemoteAuthority(String host, int port, String uri, int timeout) {
mHost = host;
@@ -46,7 +42,7 @@ public class RemoteAuthority implements IRemoteAuthority {
}
public void init(IConfigStore c)
- throws EBaseException {
+ throws EBaseException {
mHost = c.getString("host");
mPort = c.getInteger("port");
mURI = c.getString("uri");
diff --git a/pki/base/common/src/com/netscape/cmscore/connector/RequestTransfer.java b/pki/base/common/src/com/netscape/cmscore/connector/RequestTransfer.java
index b0095020..c00d5c8b 100644
--- a/pki/base/common/src/com/netscape/cmscore/connector/RequestTransfer.java
+++ b/pki/base/common/src/com/netscape/cmscore/connector/RequestTransfer.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.connector;
-
import java.util.Enumeration;
import java.util.Vector;
@@ -25,27 +24,26 @@ import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.request.IRequest;
import com.netscape.cmscore.authentication.ChallengePhraseAuthentication;
-
public class RequestTransfer {
private static final String DOT = ".";
- private static String[] transferAttributes = {
+ private static String[] transferAttributes = {
IRequest.HTTP_PARAMS,
- IRequest.AGENT_PARAMS,
- IRequest.CERT_INFO,
- IRequest.ISSUED_CERTS,
- IRequest.OLD_CERTS,
- IRequest.OLD_SERIALS,
- IRequest.REVOKED_CERTS,
- IRequest.CACERTCHAIN,
- IRequest.CRL,
- IRequest.ERRORS,
+ IRequest.AGENT_PARAMS,
+ IRequest.CERT_INFO,
+ IRequest.ISSUED_CERTS,
+ IRequest.OLD_CERTS,
+ IRequest.OLD_SERIALS,
+ IRequest.REVOKED_CERTS,
+ IRequest.CACERTCHAIN,
+ IRequest.CRL,
+ IRequest.ERRORS,
IRequest.RESULT,
IRequest.ERROR,
- IRequest.SVCERRORS,
- IRequest.REMOTE_STATUS,
- IRequest.REMOTE_REQID,
+ IRequest.SVCERRORS,
+ IRequest.REMOTE_STATUS,
+ IRequest.REMOTE_REQID,
IRequest.REVOKED_CERT_RECORDS,
IRequest.CERT_STATUS,
ChallengePhraseAuthentication.CHALLENGE_PHRASE,
@@ -53,11 +51,11 @@ public class RequestTransfer {
ChallengePhraseAuthentication.SERIALNUMBER,
ChallengePhraseAuthentication.SERIALNOARRAY,
IRequest.ISSUERDN,
- IRequest.CERT_FILTER,
+ IRequest.CERT_FILTER,
"keyRecord",
"uid", // UidPwdDirAuthentication.CRED_UID,
"udn", // UdnPwdDirAuthentication.CRED_UDN,
- };
+ };
public static boolean isProfileRequest(IRequest request) {
String profileId = request.getExtDataInString("profileId");
@@ -71,8 +69,8 @@ public class RequestTransfer {
public static String[] getTransferAttributes(IRequest r) {
if (isProfileRequest(r)) {
// copy everything in the request
- CMS.debug("RequestTransfer: profile request " +
- r.getRequestId().toString());
+ CMS.debug("RequestTransfer: profile request " +
+ r.getRequestId().toString());
Enumeration e = r.getExtDataKeys();
Vector v = new Vector();
@@ -108,8 +106,8 @@ public class RequestTransfer {
public static void transfer(IRequest src, IRequest dest) {
CMS.debug("Transfer srcId=" +
- src.getRequestId().toString() +
- " destId=" + dest.getRequestId().toString());
+ src.getRequestId().toString() +
+ " destId=" + dest.getRequestId().toString());
String attrs[] = getTransferAttributes(src);
for (int i = 0; i < attrs.length; i++) {
diff --git a/pki/base/common/src/com/netscape/cmscore/connector/Resender.java b/pki/base/common/src/com/netscape/cmscore/connector/Resender.java
index ad89a34a..ba5906e8 100644
--- a/pki/base/common/src/com/netscape/cmscore/connector/Resender.java
+++ b/pki/base/common/src/com/netscape/cmscore/connector/Resender.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.connector;
-
import java.io.IOException;
import java.util.Enumeration;
import java.util.Vector;
@@ -36,16 +35,15 @@ import com.netscape.certsrv.request.RequestStatus;
import com.netscape.cmscore.util.Debug;
import com.netscape.cmsutil.http.JssSSLSocketFactory;
-
/**
- * Resend requests at intervals to the server to check if it's been completed.
+ * Resend requests at intervals to the server to check if it's been completed.
* Default interval is 5 minutes.
*/
public class Resender implements IResender {
- public static final int SECOND = 1000; //milliseconds
- public static final int MINUTE = 60 * SECOND;
- public static final int HOUR = 60 * MINUTE;
- public static final int DAY = 24 * HOUR;
+ public static final int SECOND = 1000; // milliseconds
+ public static final int MINUTE = 60 * SECOND;
+ public static final int HOUR = 60 * MINUTE;
+ public static final int DAY = 24 * HOUR;
protected IAuthority mAuthority = null;
IRequestQueue mQueue = null;
@@ -61,44 +59,44 @@ public class Resender implements IResender {
// default interval.
// XXX todo add another interval for requests unsent because server
// was down (versus being serviced in request queue)
- protected int mInterval = 1 * MINUTE;
+ protected int mInterval = 1 * MINUTE;
public Resender(IAuthority authority, String nickName, IRemoteAuthority dest) {
mAuthority = authority;
mQueue = mAuthority.getRequestQueue();
mDest = dest;
mNickName = nickName;
-
- //mConn = new HttpConnection(dest,
- // new JssSSLSocketFactory(nickName));
+
+ // mConn = new HttpConnection(dest,
+ // new JssSSLSocketFactory(nickName));
}
public Resender(
- IAuthority authority, String nickName,
- IRemoteAuthority dest, int interval) {
+ IAuthority authority, String nickName,
+ IRemoteAuthority dest, int interval) {
mAuthority = authority;
mQueue = mAuthority.getRequestQueue();
mDest = dest;
if (interval > 0)
mInterval = interval * SECOND; // interval specified in seconds.
- //mConn = new HttpConnection(dest,
- // new JssSSLSocketFactory(nickName));
+ // mConn = new HttpConnection(dest,
+ // new JssSSLSocketFactory(nickName));
}
// must be done after a subsystem 'start' so queue is initialized.
private void initRequests() {
mQueue = mAuthority.getRequestQueue();
// get all requests in mAuthority that are still pending.
- IRequestList list =
- mQueue.listRequestsByStatus(RequestStatus.SVC_PENDING);
+ IRequestList list =
+ mQueue.listRequestsByStatus(RequestStatus.SVC_PENDING);
while (list != null && list.hasMoreElements()) {
RequestId rid = list.nextRequestId();
CMS.debug(
- "added request Id " + rid + " in init to resend queue.");
- // note these are added as strings
+ "added request Id " + rid + " in init to resend queue.");
+ // note these are added as strings
mRequestIds.addElement(rid.toString());
}
}
@@ -109,13 +107,13 @@ public class Resender implements IResender {
mRequestIds.addElement(r.getRequestId().toString());
}
CMS.debug(
- "added " + r.getRequestId() + " to resend queue");
+ "added " + r.getRequestId() + " to resend queue");
}
public void run() {
- CMS.debug("Resender: In resender Thread run:");
- mConn = new HttpConnection(mDest,
+ CMS.debug("Resender: In resender Thread run:");
+ mConn = new HttpConnection(mDest,
new JssSSLSocketFactory(mNickName));
initRequests();
@@ -127,8 +125,7 @@ public class Resender implements IResender {
mAuthority.log(ILogger.LL_INFO, CMS.getLogMessage("CMSCORE_CONNECTOR_RESENDER_INTERRUPTED"));
continue;
}
- }
- while (true);
+ } while (true);
}
private void resend() {
@@ -141,17 +138,17 @@ public class Resender implements IResender {
while (enum1.hasMoreElements()) {
// request ids are added as strings.
- String ridString = (String) enum1.nextElement();
+ String ridString = (String) enum1.nextElement();
RequestId rid = new RequestId(ridString);
IRequest r = null;
CMS.debug(
- "resend processing request id " + rid);
+ "resend processing request id " + rid);
try {
r = mQueue.findRequest(rid);
} catch (EBaseException e) {
- // XXX bad case. should we remove the rid now ?
+ // XXX bad case. should we remove the rid now ?
mAuthority.log(ILogger.LL_WARN, CMS.getLogMessage("CMSCORE_CONNECTOR_REQUEST_NOT_FOUND", rid.toString()));
continue;
}
@@ -160,7 +157,7 @@ public class Resender implements IResender {
// request not pending anymore - aborted or cancelled.
completedRids.addElement(rid);
CMS.debug(
- "request id " + rid + " no longer service pending");
+ "request id " + rid + " no longer service pending");
} else {
boolean completed = send(r);
@@ -175,8 +172,7 @@ public class Resender implements IResender {
// if connection is down, don't send the remaining request
// as it will sure fail.
mAuthority.log(ILogger.LL_WARN, CMS.getLogMessage("CMSCORE_CONNECTOR_DOWN"));
- if (e.toString().indexOf("connection not available")
- >= 0)
+ if (e.toString().indexOf("connection not available") >= 0)
break;
}
}
@@ -189,44 +185,44 @@ public class Resender implements IResender {
RequestId id = (RequestId) en.nextElement();
CMS.debug(
- "Connector: Removed request " + id + " from re-send queue");
+ "Connector: Removed request " + id + " from re-send queue");
mRequestIds.removeElement(id.toString());
CMS.debug(
- "Connector: mRequestIds now has " +
- mRequestIds.size() + " elements.");
+ "Connector: mRequestIds now has " +
+ mRequestIds.size() + " elements.");
}
}
}
// this is almost the same as connector's send.
private boolean send(IRequest r)
- throws IOException, EBaseException {
+ throws IOException, EBaseException {
IRequest reply = null;
-
+
try {
HttpPKIMessage tomsg = new HttpPKIMessage();
HttpPKIMessage replymsg = null;
tomsg.fromRequest(r);
replymsg = (HttpPKIMessage) mConn.send(tomsg);
- if(replymsg==null)
+ if (replymsg == null)
return false;
CMS.debug(
- r.getRequestId() + " resent to CA");
-
- RequestStatus replyStatus =
- RequestStatus.fromString(replymsg.reqStatus);
+ r.getRequestId() + " resent to CA");
+
+ RequestStatus replyStatus =
+ RequestStatus.fromString(replymsg.reqStatus);
int index = replymsg.reqId.lastIndexOf(':');
- RequestId replyRequestId =
- new RequestId(replymsg.reqId.substring(index + 1));
+ RequestId replyRequestId =
+ new RequestId(replymsg.reqId.substring(index + 1));
if (Debug.ON)
Debug.trace("reply request id " + replyRequestId +
- " for request " + r.getRequestId());
+ " for request " + r.getRequestId());
if (replyStatus != RequestStatus.COMPLETE) {
CMS.debug("resend " +
- r.getRequestId() + " still not completed.");
+ r.getRequestId() + " still not completed.");
return false;
}
@@ -237,7 +233,7 @@ public class Resender implements IResender {
mQueue.markAsServiced(r);
mQueue.releaseRequest(r);
CMS.debug(
- "resend released request " + r.getRequestId());
+ "resend released request " + r.getRequestId());
return true;
} catch (EBaseException e) {
// same as not having sent it, so still want to resend.
@@ -248,6 +244,5 @@ public class Resender implements IResender {
return false;
}
-
-}
+}
diff --git a/pki/base/common/src/com/netscape/cmscore/crmf/CRMFParser.java b/pki/base/common/src/com/netscape/cmscore/crmf/CRMFParser.java
index e2bee6d1..ec553393 100644
--- a/pki/base/common/src/com/netscape/cmscore/crmf/CRMFParser.java
+++ b/pki/base/common/src/com/netscape/cmscore/crmf/CRMFParser.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.crmf;
-
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Vector;
@@ -34,39 +33,38 @@ import org.mozilla.jss.pkix.primitive.AVA;
import com.netscape.certsrv.apps.CMS;
-
public class CRMFParser {
private static final OBJECT_IDENTIFIER PKIARCHIVEOPTIONS_OID =
- new OBJECT_IDENTIFIER(new long[] {1, 3, 6, 1, 5, 5, 7, 5, 1, 4}
- );
+ new OBJECT_IDENTIFIER(new long[] { 1, 3, 6, 1, 5, 5, 7, 5, 1, 4 }
+ );
/**
* Retrieves PKIArchiveOptions from CRMF request.
- *
+ *
* @param request CRMF request
* @return PKIArchiveOptions
* @exception failed to extrace option
*/
- public static PKIArchiveOptionsContainer[]
- getPKIArchiveOptions(String crmfBlob) throws IOException {
+ public static PKIArchiveOptionsContainer[]
+ getPKIArchiveOptions(String crmfBlob) throws IOException {
Vector options = new Vector();
byte[] crmfBerBlob = null;
- crmfBerBlob = CMS.AtoB(crmfBlob);
+ crmfBerBlob = CMS.AtoB(crmfBlob);
if (crmfBerBlob == null)
throw new IOException("no CRMF data found");
- ByteArrayInputStream crmfBerBlobIn = new
- ByteArrayInputStream(crmfBerBlob);
+ ByteArrayInputStream crmfBerBlobIn = new
+ ByteArrayInputStream(crmfBerBlob);
SEQUENCE crmfmsgs = null;
try {
- crmfmsgs = (SEQUENCE) new
- SEQUENCE.OF_Template(new
- CertReqMsg.Template()).decode(
- crmfBerBlobIn);
+ crmfmsgs = (SEQUENCE) new
+ SEQUENCE.OF_Template(new
+ CertReqMsg.Template()).decode(
+ crmfBerBlobIn);
} catch (IOException e) {
throw new IOException("[crmf msgs]" + e.toString());
} catch (InvalidBERException e) {
@@ -75,9 +73,9 @@ public class CRMFParser {
for (int z = 0; z < crmfmsgs.size(); z++) {
CertReqMsg certReqMsg = (CertReqMsg)
- crmfmsgs.elementAt(z);
- CertRequest certReq = certReqMsg.getCertReq();
-
+ crmfmsgs.elementAt(z);
+ CertRequest certReq = certReqMsg.getCertReq();
+
// try to locate PKIArchiveOption control
AVA archAva = null;
@@ -114,10 +112,10 @@ public class CRMFParser {
if (options.size() == 0) {
throw new IOException("no PKIArchiveOptions found");
} else {
- PKIArchiveOptionsContainer p[] = new PKIArchiveOptionsContainer[options.size()];
+ PKIArchiveOptionsContainer p[] = new PKIArchiveOptionsContainer[options.size()];
options.copyInto(p);
- // options.clear();
+ // options.clear();
return p;
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/crmf/PKIArchiveOptionsContainer.java b/pki/base/common/src/com/netscape/cmscore/crmf/PKIArchiveOptionsContainer.java
index d7899da3..4c5478da 100644
--- a/pki/base/common/src/com/netscape/cmscore/crmf/PKIArchiveOptionsContainer.java
+++ b/pki/base/common/src/com/netscape/cmscore/crmf/PKIArchiveOptionsContainer.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.crmf;
-
import org.mozilla.jss.pkix.crmf.PKIArchiveOptions;
-
public class PKIArchiveOptionsContainer {
public PKIArchiveOptions mAO = null;
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/BigIntegerMapper.java b/pki/base/common/src/com/netscape/cmscore/dbs/BigIntegerMapper.java
index 7cd563f9..4e8d0dcf 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/BigIntegerMapper.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/BigIntegerMapper.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.math.BigInteger;
import java.util.Enumeration;
import java.util.Vector;
@@ -29,14 +28,12 @@ import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.dbs.IDBAttrMapper;
import com.netscape.certsrv.dbs.IDBObj;
-
/**
- * A class represents ann attribute mapper that maps
- * a Java BigInteger object into LDAP attribute,
- * and vice versa.
- *
+ * A class represents ann attribute mapper that maps a Java BigInteger object
+ * into LDAP attribute, and vice versa.
+ *
* @author thomask
- * @version $Revision$, $Date$
+ * @version $Revision$, $Date$
*/
public class BigIntegerMapper implements IDBAttrMapper {
@@ -61,19 +58,18 @@ public class BigIntegerMapper implements IDBAttrMapper {
/**
* Maps object into ldap attribute set.
*/
- public void mapObjectToLDAPAttributeSet(IDBObj parent,
- String name, Object obj, LDAPAttributeSet attrs)
- throws EBaseException {
- attrs.add(new LDAPAttribute(mLdapName,
+ public void mapObjectToLDAPAttributeSet(IDBObj parent,
+ String name, Object obj, LDAPAttributeSet attrs)
+ throws EBaseException {
+ attrs.add(new LDAPAttribute(mLdapName,
BigIntegerToDB((BigInteger) obj)));
}
/**
- * Maps LDAP attributes into object, and put the object
- * into 'parent'.
+ * Maps LDAP attributes into object, and put the object into 'parent'.
*/
- public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
- String name, IDBObj parent) throws EBaseException {
+ public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
+ String name, IDBObj parent) throws EBaseException {
LDAPAttribute attr = attrs.getAttribute(mLdapName);
if (attr == null)
@@ -85,8 +81,8 @@ public class BigIntegerMapper implements IDBAttrMapper {
/**
* Maps search filters into LDAP search filter.
*/
- public String mapSearchFilter(String name, String op,
- String value) throws EBaseException {
+ public String mapSearchFilter(String name, String op,
+ String value) throws EBaseException {
String v = null;
try {
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/ByteArrayMapper.java b/pki/base/common/src/com/netscape/cmscore/dbs/ByteArrayMapper.java
index b8e5b73d..f57eba26 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/ByteArrayMapper.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/ByteArrayMapper.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.util.Enumeration;
import java.util.Vector;
@@ -29,14 +28,12 @@ import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.dbs.IDBAttrMapper;
import com.netscape.certsrv.dbs.IDBObj;
-
/**
- * A class represents ann attribute mapper that maps
- * a Java byte array object into LDAP attribute,
- * and vice versa.
- *
+ * A class represents ann attribute mapper that maps a Java byte array object
+ * into LDAP attribute, and vice versa.
+ *
* @author thomask
- * @version $Revision$, $Date$
+ * @version $Revision$, $Date$
*/
public class ByteArrayMapper implements IDBAttrMapper {
@@ -61,26 +58,25 @@ public class ByteArrayMapper implements IDBAttrMapper {
/**
* Maps object to ldap attribute set.
*/
- public void mapObjectToLDAPAttributeSet(IDBObj parent,
- String name, Object obj, LDAPAttributeSet attrs)
- throws EBaseException {
+ public void mapObjectToLDAPAttributeSet(IDBObj parent,
+ String name, Object obj, LDAPAttributeSet attrs)
+ throws EBaseException {
byte data[] = (byte[]) obj;
if (data == null) {
CMS.debug("ByteArrayMapper:mapObjectToLDAPAttributeSet " + name +
- " size=0");
+ " size=0");
} else {
CMS.debug("ByteArrayMapper:mapObjectToLDAPAttributeSet " + name +
- " size=" + data.length);
+ " size=" + data.length);
}
attrs.add(new LDAPAttribute(mLdapName, data));
}
/**
- * Maps LDAP attributes into object, and put the object
- * into 'parent'.
+ * Maps LDAP attributes into object, and put the object into 'parent'.
*/
- public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
- String name, IDBObj parent) throws EBaseException {
+ public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
+ String name, IDBObj parent) throws EBaseException {
LDAPAttribute attr = attrs.getAttribute(mLdapName);
if (attr == null)
@@ -91,8 +87,8 @@ public class ByteArrayMapper implements IDBAttrMapper {
/**
* Maps search filters into LDAP search filter.
*/
- public String mapSearchFilter(String name, String op,
- String value) throws EBaseException {
+ public String mapSearchFilter(String name, String op,
+ String value) throws EBaseException {
return mLdapName + op + value;
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/CRLDBSchema.java b/pki/base/common/src/com/netscape/cmscore/dbs/CRLDBSchema.java
index 58342a55..a47553fb 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/CRLDBSchema.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/CRLDBSchema.java
@@ -17,14 +17,10 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
-
-
/**
- * A class represents a collection of schema information
- * for CRL.
+ * A class represents a collection of schema information for CRL.
* <P>
- *
+ *
* @author thomask
* @version $Revision$, $Date$
*/
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/CRLIssuingPointRecord.java b/pki/base/common/src/com/netscape/cmscore/dbs/CRLIssuingPointRecord.java
index ea110d1c..239ba9b6 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/CRLIssuingPointRecord.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/CRLIssuingPointRecord.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.math.BigInteger;
import java.util.Date;
import java.util.Enumeration;
@@ -29,11 +28,10 @@ import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.dbs.IDBObj;
import com.netscape.certsrv.dbs.crldb.ICRLIssuingPointRecord;
-
/**
* A class represents a CRL issuing point record.
* <P>
- *
+ *
* @author thomask
* @version $Revision$, $Date$
*/
@@ -43,8 +41,8 @@ public class CRLIssuingPointRecord implements ICRLIssuingPointRecord, IDBObj {
*
*/
private static final long serialVersionUID = 400565044343905267L;
- protected String mId = null; // internal unique id
- protected BigInteger mCRLNumber = null; // CRL number
+ protected String mId = null; // internal unique id
+ protected BigInteger mCRLNumber = null; // CRL number
protected Long mCRLSize = null;
protected Date mThisUpdate = null;
protected Date mNextUpdate = null;
@@ -78,8 +76,8 @@ public class CRLIssuingPointRecord implements ICRLIssuingPointRecord, IDBObj {
}
/**
- * Constructs empty CRLIssuingPointRecord. This is
- * required in database framework.
+ * Constructs empty CRLIssuingPointRecord. This is required in database
+ * framework.
*/
public CRLIssuingPointRecord() {
}
@@ -87,8 +85,8 @@ public class CRLIssuingPointRecord implements ICRLIssuingPointRecord, IDBObj {
/**
* Constructs a CRLIssuingPointRecord
*/
- public CRLIssuingPointRecord(String id, BigInteger crlNumber, Long crlSize,
- Date thisUpdate, Date nextUpdate) {
+ public CRLIssuingPointRecord(String id, BigInteger crlNumber, Long crlSize,
+ Date thisUpdate, Date nextUpdate) {
mId = id;
mCRLNumber = crlNumber;
mCRLSize = crlSize;
@@ -106,9 +104,9 @@ public class CRLIssuingPointRecord implements ICRLIssuingPointRecord, IDBObj {
/**
* Constructs a CRLIssuingPointRecord
*/
- public CRLIssuingPointRecord(String id, BigInteger crlNumber, Long crlSize,
- Date thisUpdate, Date nextUpdate, BigInteger deltaCRLNumber, Long deltaCRLSize,
- Hashtable revokedCerts, Hashtable unrevokedCerts, Hashtable expiredCerts) {
+ public CRLIssuingPointRecord(String id, BigInteger crlNumber, Long crlSize,
+ Date thisUpdate, Date nextUpdate, BigInteger deltaCRLNumber, Long deltaCRLSize,
+ Hashtable revokedCerts, Hashtable unrevokedCerts, Hashtable expiredCerts) {
mId = id;
mCRLNumber = crlNumber;
mCRLSize = crlSize;
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/CRLRepository.java b/pki/base/common/src/com/netscape/cmscore/dbs/CRLRepository.java
index ba3ed5a7..3c70bf3d 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/CRLRepository.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/CRLRepository.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.math.BigInteger;
import java.util.Date;
import java.util.Hashtable;
@@ -36,10 +35,9 @@ import com.netscape.certsrv.dbs.crldb.ICRLIssuingPointRecord;
import com.netscape.certsrv.dbs.crldb.ICRLRepository;
/**
- * A class represents a CRL repository. It stores all the
- * CRL issuing points.
+ * A class represents a CRL repository. It stores all the CRL issuing points.
* <P>
- *
+ *
* @author thomask
* @version $Revision$, $Date$
*/
@@ -52,8 +50,8 @@ public class CRLRepository extends Repository implements ICRLRepository {
/**
* Constructs a CRL repository.
*/
- public CRLRepository(IDBSubsystem dbService, int increment, String baseDN)
- throws EDBException {
+ public CRLRepository(IDBSubsystem dbService, int increment, String baseDN)
+ throws EDBException {
super(dbService, increment, baseDN);
mBaseDN = baseDN;
mDBService = dbService;
@@ -61,22 +59,21 @@ public class CRLRepository extends Repository implements ICRLRepository {
IDBRegistry reg = dbService.getRegistry();
/**
- String crlRecordOC[] = new String[1];
- crlRecordOC[0] = Schema.LDAP_OC_CRL_RECORD;
- reg.registerObjectClass(CRLIssuingPointRecord.class.getName(),
- crlRecordOC);
- reg.registerAttribute(ICRLIssuingPointRecord.ATTR_ID, new
- StringMapper(Schema.LDAP_ATTR_CRL_ID));
- reg.registerAttribute(ICRLIssuingPointRecord.ATTR_CRL_NUMBER, new
- BigIntegerMapper(Schema.LDAP_ATTR_CRL_NUMBER));
- reg.registerAttribute(ICRLIssuingPointRecord.ATTR_CRL_SIZE, new
- LongMapper(Schema.LDAP_ATTR_CRL_SIZE));
- reg.registerAttribute(ICRLIssuingPointRecord.ATTR_THIS_UPDATE, new
- DateMapper(Schema.LDAP_ATTR_THIS_UPDATE));
- reg.registerAttribute(ICRLIssuingPointRecord.ATTR_NEXT_UPDATE, new
- DateMapper(Schema.LDAP_ATTR_NEXT_UPDATE));
- reg.registerAttribute(ICRLIssuingPointRecord.ATTR_CRL, new
- ByteArrayMapper(Schema.LDAP_ATTR_CRL));
+ * String crlRecordOC[] = new String[1]; crlRecordOC[0] =
+ * Schema.LDAP_OC_CRL_RECORD;
+ * reg.registerObjectClass(CRLIssuingPointRecord.class.getName(),
+ * crlRecordOC); reg.registerAttribute(ICRLIssuingPointRecord.ATTR_ID,
+ * new StringMapper(Schema.LDAP_ATTR_CRL_ID));
+ * reg.registerAttribute(ICRLIssuingPointRecord.ATTR_CRL_NUMBER, new
+ * BigIntegerMapper(Schema.LDAP_ATTR_CRL_NUMBER));
+ * reg.registerAttribute(ICRLIssuingPointRecord.ATTR_CRL_SIZE, new
+ * LongMapper(Schema.LDAP_ATTR_CRL_SIZE));
+ * reg.registerAttribute(ICRLIssuingPointRecord.ATTR_THIS_UPDATE, new
+ * DateMapper(Schema.LDAP_ATTR_THIS_UPDATE));
+ * reg.registerAttribute(ICRLIssuingPointRecord.ATTR_NEXT_UPDATE, new
+ * DateMapper(Schema.LDAP_ATTR_NEXT_UPDATE));
+ * reg.registerAttribute(ICRLIssuingPointRecord.ATTR_CRL, new
+ * ByteArrayMapper(Schema.LDAP_ATTR_CRL));
**/
}
@@ -97,24 +94,23 @@ public class CRLRepository extends Repository implements ICRLRepository {
/**
* Removes all objects with this repository.
*/
- public void removeAllObjects() throws EBaseException
- {
+ public void removeAllObjects() throws EBaseException {
}
/**
* Adds CRL issuing points.
*/
public void addCRLIssuingPointRecord(ICRLIssuingPointRecord rec)
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
try {
String name = mLdapCRLIssuingPointName + "=" +
- ((CRLIssuingPointRecord) rec).getId().toString() + "," + getDN();
+ ((CRLIssuingPointRecord) rec).getId().toString() + "," + getDN();
s.add(name, rec);
- } finally {
- if (s != null)
+ } finally {
+ if (s != null)
s.close();
}
}
@@ -125,21 +121,21 @@ public class CRLRepository extends Repository implements ICRLRepository {
public Vector getIssuingPointsNames() throws EBaseException {
IDBSSession s = mDBService.createSession();
try {
- String[] attrs = {ICRLIssuingPointRecord.ATTR_ID, "objectclass"};
+ String[] attrs = { ICRLIssuingPointRecord.ATTR_ID, "objectclass" };
String filter = "objectclass=" + CMS.getCRLIssuingPointRecordName();
IDBSearchResults res = s.search(getDN(), filter, attrs);
Vector v = new Vector();
while (res.hasMoreElements()) {
- ICRLIssuingPointRecord nextelement =
- (ICRLIssuingPointRecord)res.nextElement();
+ ICRLIssuingPointRecord nextelement =
+ (ICRLIssuingPointRecord) res.nextElement();
CMS.debug("CRLRepository getIssuingPointsNames(): name = "
- +nextelement.getId());
+ + nextelement.getId());
v.addElement(nextelement.getId());
}
return v;
} finally {
- if (s != null)
+ if (s != null)
s.close();
}
}
@@ -148,19 +144,20 @@ public class CRLRepository extends Repository implements ICRLRepository {
* Reads issuing point record.
*/
public ICRLIssuingPointRecord readCRLIssuingPointRecord(String id)
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
CRLIssuingPointRecord rec = null;
try {
String name = mLdapCRLIssuingPointName + "=" + id +
- "," + getDN();
+ "," + getDN();
if (s != null) {
rec = (CRLIssuingPointRecord) s.read(name);
}
- } finally {
- if (s != null) s.close();
+ } finally {
+ if (s != null)
+ s.close();
}
return rec;
}
@@ -169,31 +166,35 @@ public class CRLRepository extends Repository implements ICRLRepository {
* deletes issuing point record.
*/
public void deleteCRLIssuingPointRecord(String id)
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = null;
try {
s = mDBService.createSession();
String name = mLdapCRLIssuingPointName + "=" + id +
- "," + getDN();
+ "," + getDN();
- if (s != null) s.delete(name);
+ if (s != null)
+ s.delete(name);
} finally {
- if (s != null) s.close();
+ if (s != null)
+ s.close();
}
}
- public void modifyCRLIssuingPointRecord(String id,
- ModificationSet mods) throws EBaseException {
+ public void modifyCRLIssuingPointRecord(String id,
+ ModificationSet mods) throws EBaseException {
IDBSSession s = mDBService.createSession();
try {
String name = mLdapCRLIssuingPointName + "=" + id +
- "," + getDN();
+ "," + getDN();
- if (s != null) s.modify(name, mods);
- } finally {
- if (s != null) s.close();
+ if (s != null)
+ s.modify(name, mods);
+ } finally {
+ if (s != null)
+ s.close();
}
}
@@ -201,24 +202,24 @@ public class CRLRepository extends Repository implements ICRLRepository {
* Updates CRL issuing point record.
*/
public void updateCRLIssuingPointRecord(String id, byte[] newCRL,
- Date thisUpdate, Date nextUpdate, BigInteger crlNumber, Long crlSize)
- throws EBaseException {
+ Date thisUpdate, Date nextUpdate, BigInteger crlNumber, Long crlSize)
+ throws EBaseException {
ModificationSet mods = new ModificationSet();
if (newCRL != null) {
- mods.add(ICRLIssuingPointRecord.ATTR_CRL,
- Modification.MOD_REPLACE, newCRL);
+ mods.add(ICRLIssuingPointRecord.ATTR_CRL,
+ Modification.MOD_REPLACE, newCRL);
}
if (nextUpdate != null) {
- mods.add(ICRLIssuingPointRecord.ATTR_NEXT_UPDATE,
- Modification.MOD_REPLACE, nextUpdate);
+ mods.add(ICRLIssuingPointRecord.ATTR_NEXT_UPDATE,
+ Modification.MOD_REPLACE, nextUpdate);
}
- mods.add(ICRLIssuingPointRecord.ATTR_THIS_UPDATE,
- Modification.MOD_REPLACE, thisUpdate);
- mods.add(ICRLIssuingPointRecord.ATTR_CRL_NUMBER,
- Modification.MOD_REPLACE, crlNumber);
- mods.add(ICRLIssuingPointRecord.ATTR_CRL_SIZE,
- Modification.MOD_REPLACE, crlSize);
+ mods.add(ICRLIssuingPointRecord.ATTR_THIS_UPDATE,
+ Modification.MOD_REPLACE, thisUpdate);
+ mods.add(ICRLIssuingPointRecord.ATTR_CRL_NUMBER,
+ Modification.MOD_REPLACE, crlNumber);
+ mods.add(ICRLIssuingPointRecord.ATTR_CRL_SIZE,
+ Modification.MOD_REPLACE, crlSize);
modifyCRLIssuingPointRecord(id, mods);
}
@@ -226,40 +227,40 @@ public class CRLRepository extends Repository implements ICRLRepository {
* Updates CRL issuing point record.
*/
public void updateCRLIssuingPointRecord(String id, byte[] newCRL,
- Date thisUpdate, Date nextUpdate, BigInteger crlNumber, Long crlSize,
- Hashtable revokedCerts, Hashtable unrevokedCerts, Hashtable expiredCerts)
- throws EBaseException {
+ Date thisUpdate, Date nextUpdate, BigInteger crlNumber, Long crlSize,
+ Hashtable revokedCerts, Hashtable unrevokedCerts, Hashtable expiredCerts)
+ throws EBaseException {
ModificationSet mods = new ModificationSet();
if (newCRL != null) {
- mods.add(ICRLIssuingPointRecord.ATTR_CRL,
- Modification.MOD_REPLACE, newCRL);
+ mods.add(ICRLIssuingPointRecord.ATTR_CRL,
+ Modification.MOD_REPLACE, newCRL);
}
if (nextUpdate != null) {
- mods.add(ICRLIssuingPointRecord.ATTR_NEXT_UPDATE,
- Modification.MOD_REPLACE, nextUpdate);
+ mods.add(ICRLIssuingPointRecord.ATTR_NEXT_UPDATE,
+ Modification.MOD_REPLACE, nextUpdate);
}
- mods.add(ICRLIssuingPointRecord.ATTR_THIS_UPDATE,
- Modification.MOD_REPLACE, thisUpdate);
- mods.add(ICRLIssuingPointRecord.ATTR_CRL_NUMBER,
- Modification.MOD_REPLACE, crlNumber);
- mods.add(ICRLIssuingPointRecord.ATTR_CRL_SIZE,
- Modification.MOD_REPLACE, crlSize);
+ mods.add(ICRLIssuingPointRecord.ATTR_THIS_UPDATE,
+ Modification.MOD_REPLACE, thisUpdate);
+ mods.add(ICRLIssuingPointRecord.ATTR_CRL_NUMBER,
+ Modification.MOD_REPLACE, crlNumber);
+ mods.add(ICRLIssuingPointRecord.ATTR_CRL_SIZE,
+ Modification.MOD_REPLACE, crlSize);
if (revokedCerts != null) {
- mods.add(ICRLIssuingPointRecord.ATTR_REVOKED_CERTS,
- Modification.MOD_REPLACE, revokedCerts);
+ mods.add(ICRLIssuingPointRecord.ATTR_REVOKED_CERTS,
+ Modification.MOD_REPLACE, revokedCerts);
}
if (unrevokedCerts != null) {
- mods.add(ICRLIssuingPointRecord.ATTR_UNREVOKED_CERTS,
- Modification.MOD_REPLACE, unrevokedCerts);
+ mods.add(ICRLIssuingPointRecord.ATTR_UNREVOKED_CERTS,
+ Modification.MOD_REPLACE, unrevokedCerts);
}
if (expiredCerts != null) {
- mods.add(ICRLIssuingPointRecord.ATTR_EXPIRED_CERTS,
- Modification.MOD_REPLACE, expiredCerts);
+ mods.add(ICRLIssuingPointRecord.ATTR_EXPIRED_CERTS,
+ Modification.MOD_REPLACE, expiredCerts);
}
if (revokedCerts != null || unrevokedCerts != null) {
mods.add(ICRLIssuingPointRecord.ATTR_FIRST_UNSAVED,
- Modification.MOD_REPLACE, ICRLIssuingPointRecord.CLEAN_CACHE);
+ Modification.MOD_REPLACE, ICRLIssuingPointRecord.CLEAN_CACHE);
}
modifyCRLIssuingPointRecord(id, mods);
}
@@ -268,16 +269,16 @@ public class CRLRepository extends Repository implements ICRLRepository {
* Updates CRL issuing point record with recently revoked certificates info.
*/
public void updateRevokedCerts(String id, Hashtable revokedCerts,
- Hashtable unrevokedCerts)
- throws EBaseException {
+ Hashtable unrevokedCerts)
+ throws EBaseException {
ModificationSet mods = new ModificationSet();
- mods.add(ICRLIssuingPointRecord.ATTR_REVOKED_CERTS,
- Modification.MOD_REPLACE, revokedCerts);
- mods.add(ICRLIssuingPointRecord.ATTR_UNREVOKED_CERTS,
- Modification.MOD_REPLACE, unrevokedCerts);
+ mods.add(ICRLIssuingPointRecord.ATTR_REVOKED_CERTS,
+ Modification.MOD_REPLACE, revokedCerts);
+ mods.add(ICRLIssuingPointRecord.ATTR_UNREVOKED_CERTS,
+ Modification.MOD_REPLACE, unrevokedCerts);
mods.add(ICRLIssuingPointRecord.ATTR_FIRST_UNSAVED,
- Modification.MOD_REPLACE, ICRLIssuingPointRecord.CLEAN_CACHE);
+ Modification.MOD_REPLACE, ICRLIssuingPointRecord.CLEAN_CACHE);
modifyCRLIssuingPointRecord(id, mods);
}
@@ -285,11 +286,11 @@ public class CRLRepository extends Repository implements ICRLRepository {
* Updates CRL issuing point record with recently expired certificates info.
*/
public void updateExpiredCerts(String id, Hashtable expiredCerts)
- throws EBaseException {
+ throws EBaseException {
ModificationSet mods = new ModificationSet();
- mods.add(ICRLIssuingPointRecord.ATTR_EXPIRED_CERTS,
- Modification.MOD_REPLACE, expiredCerts);
+ mods.add(ICRLIssuingPointRecord.ATTR_EXPIRED_CERTS,
+ Modification.MOD_REPLACE, expiredCerts);
modifyCRLIssuingPointRecord(id, mods);
}
@@ -297,24 +298,24 @@ public class CRLRepository extends Repository implements ICRLRepository {
* Updates CRL issuing point record with CRL cache info.
*/
public void updateCRLCache(String id, Long crlSize,
- Hashtable revokedCerts,
- Hashtable unrevokedCerts,
- Hashtable expiredCerts)
- throws EBaseException {
+ Hashtable revokedCerts,
+ Hashtable unrevokedCerts,
+ Hashtable expiredCerts)
+ throws EBaseException {
ModificationSet mods = new ModificationSet();
if (crlSize != null) {
- mods.add(ICRLIssuingPointRecord.ATTR_CRL_SIZE,
- Modification.MOD_REPLACE, crlSize);
+ mods.add(ICRLIssuingPointRecord.ATTR_CRL_SIZE,
+ Modification.MOD_REPLACE, crlSize);
}
mods.add(ICRLIssuingPointRecord.ATTR_REVOKED_CERTS,
- Modification.MOD_REPLACE, revokedCerts);
+ Modification.MOD_REPLACE, revokedCerts);
mods.add(ICRLIssuingPointRecord.ATTR_UNREVOKED_CERTS,
- Modification.MOD_REPLACE, unrevokedCerts);
+ Modification.MOD_REPLACE, unrevokedCerts);
mods.add(ICRLIssuingPointRecord.ATTR_EXPIRED_CERTS,
- Modification.MOD_REPLACE, expiredCerts);
+ Modification.MOD_REPLACE, expiredCerts);
mods.add(ICRLIssuingPointRecord.ATTR_FIRST_UNSAVED,
- Modification.MOD_REPLACE, ICRLIssuingPointRecord.CLEAN_CACHE);
+ Modification.MOD_REPLACE, ICRLIssuingPointRecord.CLEAN_CACHE);
modifyCRLIssuingPointRecord(id, mods);
}
@@ -324,41 +325,41 @@ public class CRLRepository extends Repository implements ICRLRepository {
public void updateDeltaCRL(String id, BigInteger deltaCRLNumber,
Long deltaCRLSize, Date nextUpdate,
byte[] deltaCRL)
- throws EBaseException {
+ throws EBaseException {
ModificationSet mods = new ModificationSet();
if (deltaCRLNumber != null) {
mods.add(ICRLIssuingPointRecord.ATTR_DELTA_NUMBER,
- Modification.MOD_REPLACE, deltaCRLNumber);
+ Modification.MOD_REPLACE, deltaCRLNumber);
}
if (deltaCRLSize != null) {
- mods.add(ICRLIssuingPointRecord.ATTR_DELTA_SIZE,
- Modification.MOD_REPLACE, deltaCRLSize);
+ mods.add(ICRLIssuingPointRecord.ATTR_DELTA_SIZE,
+ Modification.MOD_REPLACE, deltaCRLSize);
}
if (nextUpdate != null) {
- mods.add(ICRLIssuingPointRecord.ATTR_NEXT_UPDATE,
- Modification.MOD_REPLACE, nextUpdate);
+ mods.add(ICRLIssuingPointRecord.ATTR_NEXT_UPDATE,
+ Modification.MOD_REPLACE, nextUpdate);
}
if (deltaCRL != null) {
- mods.add(ICRLIssuingPointRecord.ATTR_DELTA_CRL,
- Modification.MOD_REPLACE, deltaCRL);
+ mods.add(ICRLIssuingPointRecord.ATTR_DELTA_CRL,
+ Modification.MOD_REPLACE, deltaCRL);
}
modifyCRLIssuingPointRecord(id, mods);
}
public void updateFirstUnsaved(String id, String firstUnsaved)
- throws EBaseException {
+ throws EBaseException {
ModificationSet mods = new ModificationSet();
if (firstUnsaved != null) {
- mods.add(ICRLIssuingPointRecord.ATTR_FIRST_UNSAVED,
- Modification.MOD_REPLACE, firstUnsaved);
+ mods.add(ICRLIssuingPointRecord.ATTR_FIRST_UNSAVED,
+ Modification.MOD_REPLACE, firstUnsaved);
}
modifyCRLIssuingPointRecord(id, mods);
}
- public BigInteger getLastSerialNumberInRange(BigInteger serial_low_bound, BigInteger serial_upper_bound)
- throws EBaseException {
+ public BigInteger getLastSerialNumberInRange(BigInteger serial_low_bound, BigInteger serial_upper_bound)
+ throws EBaseException {
return null;
}
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/CertDBSchema.java b/pki/base/common/src/com/netscape/cmscore/dbs/CertDBSchema.java
index 83164aab..3718e504 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/CertDBSchema.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/CertDBSchema.java
@@ -17,14 +17,11 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
-
-
/**
- * A class represents a collection of certificate record
- * specific schema information.
+ * A class represents a collection of certificate record specific schema
+ * information.
* <P>
- *
+ *
* @author thomask
* @version $Revision$, $Date$
*/
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/CertRecord.java b/pki/base/common/src/com/netscape/cmscore/dbs/CertRecord.java
index 973ddc4f..e8d2c954 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/CertRecord.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/CertRecord.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.math.BigInteger;
import java.security.cert.Certificate;
import java.util.Date;
@@ -34,12 +33,11 @@ import com.netscape.certsrv.dbs.IDBObj;
import com.netscape.certsrv.dbs.certdb.ICertRecord;
import com.netscape.certsrv.dbs.certdb.IRevocationInfo;
-
/**
* A class represents a serializable certificate record.
* <P>
- *
- * @author thomask
+ *
+ * @author thomask
* @version $Revision$, $Date$
*/
public class CertRecord implements IDBObj, ICertRecord {
@@ -83,8 +81,7 @@ public class CertRecord implements IDBObj, ICertRecord {
}
/**
- * Constructs certiificate record with certificate
- * and meta info.
+ * Constructs certiificate record with certificate and meta info.
*/
public CertRecord(BigInteger id, Certificate cert, MetaInfo meta) {
mId = id;
@@ -205,14 +202,13 @@ public class CertRecord implements IDBObj, ICertRecord {
/**
* Retrieves revocation information.
*/
- public IRevocationInfo getRevocationInfo() {
- return mRevocationInfo;
+ public IRevocationInfo getRevocationInfo() {
+ return mRevocationInfo;
}
/**
- * Retrieves serial number of this record. Usually,
- * it is the same of the serial number of the
- * associated certificate.
+ * Retrieves serial number of this record. Usually, it is the same of the
+ * serial number of the associated certificate.
*/
public BigInteger getSerialNumber() {
return mId;
@@ -271,7 +267,7 @@ public class CertRecord implements IDBObj, ICertRecord {
public Date getModifyTime() {
return mModifyTime;
}
-
+
/**
* String representation
*/
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/CertRecordList.java b/pki/base/common/src/com/netscape/cmscore/dbs/CertRecordList.java
index 3477360e..e1e3e5c0 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/CertRecordList.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/CertRecordList.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.util.Enumeration;
import java.util.Vector;
@@ -27,11 +26,10 @@ import com.netscape.certsrv.dbs.IElementProcessor;
import com.netscape.certsrv.dbs.certdb.ICertRecord;
import com.netscape.certsrv.dbs.certdb.ICertRecordList;
-
/**
* A class represents a list of certificate records.
* <P>
- *
+ *
* @author thomask mzhao
* @version $Revision$, $Date$
*/
@@ -69,35 +67,33 @@ public class CertRecordList implements ICertRecordList {
}
/**
- * Process certificate record as soon as it is returned.
- * kmccarth: changed to ignore startidx and endidx because VLVs don't
- * provide a stable list.
+ * Process certificate record as soon as it is returned. kmccarth: changed
+ * to ignore startidx and endidx because VLVs don't provide a stable list.
*/
public void processCertRecords(int startidx, int endidx,
- IElementProcessor ep) throws EBaseException {
+ IElementProcessor ep) throws EBaseException {
int i = 0;
- while ( i<mVlist.getSize() ) {
- Object element = mVlist.getElementAt(i);
- if (element != null && (! (element instanceof String)) ) {
- ep.process(element);
- }
- i++;
+ while (i < mVlist.getSize()) {
+ Object element = mVlist.getElementAt(i);
+ if (element != null && (!(element instanceof String))) {
+ ep.process(element);
+ }
+ i++;
}
}
/**
- * Retrieves requests.
- * It's no good to call this if you didnt check
- * if the startidx, endidx are valid.
+ * Retrieves requests. It's no good to call this if you didnt check if the
+ * startidx, endidx are valid.
*/
public Enumeration<ICertRecord> getCertRecords(int startidx, int endidx)
- throws EBaseException {
+ throws EBaseException {
Vector<ICertRecord> entries = new Vector<ICertRecord>();
for (int i = startidx; i <= endidx; i++) {
ICertRecord element = mVlist.getElementAt(i);
- // CMS.debug("gerCertRecords[" + i + "] element: " + element);
+ // CMS.debug("gerCertRecords[" + i + "] element: " + element);
if (element != null) {
entries.addElement(element);
}
@@ -106,11 +102,10 @@ public class CertRecordList implements ICertRecordList {
}
public ICertRecord getCertRecord(int index)
- throws EBaseException {
+ throws EBaseException {
return mVlist.getElementAt(index);
-
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/CertRecordMapper.java b/pki/base/common/src/com/netscape/cmscore/dbs/CertRecordMapper.java
index 510da3c5..0c75e834 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/CertRecordMapper.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/CertRecordMapper.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.math.BigInteger;
import java.util.Enumeration;
import java.util.Vector;
@@ -34,13 +33,11 @@ import com.netscape.certsrv.dbs.certdb.ICertRecord;
import com.netscape.certsrv.dbs.certdb.ICertificateRepository;
import com.netscape.cmscore.util.Debug;
-
/**
- * A class represents a mapper to serialize
- * certificate record into database.
+ * A class represents a mapper to serialize certificate record into database.
* <P>
- *
- * @author thomask
+ *
+ * @author thomask
* @version $Revision$, $Date$
*/
public class CertRecordMapper implements IDBAttrMapper {
@@ -58,9 +55,9 @@ public class CertRecordMapper implements IDBAttrMapper {
return v.elements();
}
- public void mapObjectToLDAPAttributeSet(IDBObj parent, String name,
- Object obj, LDAPAttributeSet attrs)
- throws EBaseException {
+ public void mapObjectToLDAPAttributeSet(IDBObj parent, String name,
+ Object obj, LDAPAttributeSet attrs)
+ throws EBaseException {
try {
CertRecord rec = (CertRecord) obj;
@@ -74,9 +71,9 @@ public class CertRecordMapper implements IDBAttrMapper {
}
}
- public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
- String name, IDBObj parent) throws EBaseException {
- try {
+ public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
+ String name, IDBObj parent) throws EBaseException {
+ try {
LDAPAttribute attr = attrs.getAttribute(
CertDBSchema.LDAP_ATTR_CERT_RECORD_ID);
@@ -95,7 +92,7 @@ public class CertRecordMapper implements IDBAttrMapper {
}
public String mapSearchFilter(String name, String op, String value)
- throws EBaseException {
+ throws EBaseException {
return name + op + value;
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/CertificateRepository.java b/pki/base/common/src/com/netscape/cmscore/dbs/CertificateRepository.java
index bc3d279f..914da63a 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/CertificateRepository.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/CertificateRepository.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.io.Serializable;
import java.math.BigInteger;
import java.security.cert.Certificate;
@@ -57,18 +56,17 @@ import com.netscape.certsrv.dbs.certdb.IRevocationInfo;
import com.netscape.certsrv.dbs.repository.IRepository;
import com.netscape.certsrv.logging.ILogger;
-
/**
- * A class represents a certificate repository. It
- * stores all the issued certificate.
+ * A class represents a certificate repository. It stores all the issued
+ * certificate.
* <P>
- *
+ *
* @author thomask
* @author kanda
* @version $Revision$, $Date$
*/
public class CertificateRepository extends Repository
- implements ICertificateRepository {
+ implements ICertificateRepository {
public final String CERT_X509ATTRIBUTE = "x509signedcert";
@@ -88,10 +86,10 @@ public class CertificateRepository extends Repository
* Constructs a certificate repository.
*/
public CertificateRepository(IDBSubsystem dbService, String certRepoBaseDN, int increment, String baseDN)
- throws EDBException {
+ throws EDBException {
super(dbService, increment, baseDN);
mBaseDN = certRepoBaseDN;
-
+
mDBService = dbService;
// registers CMS database attributes
@@ -104,13 +102,12 @@ public class CertificateRepository extends Repository
return new CertRecord(id, cert, meta);
}
- public BigInteger getLastSerialNumberInRange(BigInteger serial_low_bound, BigInteger serial_upper_bound)
- throws EBaseException {
+ public BigInteger getLastSerialNumberInRange(BigInteger serial_low_bound, BigInteger serial_upper_bound)
+ throws EBaseException {
CMS.debug("CertificateRepository: in getLastSerialNumberInRange: low " + serial_low_bound + " high " + serial_upper_bound);
- if(serial_low_bound == null || serial_upper_bound == null || serial_low_bound.compareTo(serial_upper_bound) >= 0 )
- {
+ if (serial_low_bound == null || serial_upper_bound == null || serial_low_bound.compareTo(serial_upper_bound) >= 0) {
return null;
}
@@ -119,7 +116,7 @@ public class CertificateRepository extends Repository
String[] attrs = null;
- ICertRecordList recList = findCertRecordsInList(ldapfilter,attrs,serial_upper_bound.toString(10),"serialno", 5 * -1);
+ ICertRecordList recList = findCertRecordsInList(ldapfilter, attrs, serial_upper_bound.toString(10), "serialno", 5 * -1);
int size = recList.getSize();
@@ -130,13 +127,12 @@ public class CertificateRepository extends Repository
BigInteger ret = new BigInteger(serial_low_bound.toString(10));
- ret = ret.add(new BigInteger("-1"));
+ ret = ret.add(new BigInteger("-1"));
CMS.debug("CertificateRepository:getLastCertRecordSerialNo: returning " + ret);
return ret;
}
int ltSize = recList.getSizeBeforeJumpTo();
-
CMS.debug("CertificateRepository:getLastSerialNumberInRange: ltSize " + ltSize);
CertRecord curRec = null;
@@ -154,9 +150,8 @@ public class CertificateRepository extends Repository
CMS.debug("CertificateRepository:getLastCertRecordSerialNo: serialno " + serial);
- if( ((serial.compareTo(serial_low_bound) == 0) || (serial.compareTo(serial_low_bound) == 1) ) &&
- ((serial.compareTo(serial_upper_bound) == 0) || (serial.compareTo(serial_upper_bound) == -1) ))
- {
+ if (((serial.compareTo(serial_low_bound) == 0) || (serial.compareTo(serial_low_bound) == 1)) &&
+ ((serial.compareTo(serial_upper_bound) == 0) || (serial.compareTo(serial_upper_bound) == -1))) {
CMS.debug("getLastSerialNumberInRange returning: " + serial);
return serial;
}
@@ -164,24 +159,22 @@ public class CertificateRepository extends Repository
CMS.debug("getLastSerialNumberInRange:found null from getCertRecord");
}
}
-
BigInteger ret = new BigInteger(serial_low_bound.toString(10));
- ret = ret.add(new BigInteger("-1"));
+ ret = ret.add(new BigInteger("-1"));
CMS.debug("CertificateRepository:getLastCertRecordSerialNo: returning " + ret);
- return ret;
+ return ret;
}
/**
* Removes all objects with this repository.
*/
- public void removeCertRecords(BigInteger beginS, BigInteger endS) throws EBaseException
- {
+ public void removeCertRecords(BigInteger beginS, BigInteger endS) throws EBaseException {
String filter = "(" + CertRecord.ATTR_CERT_STATUS + "=*" + ")";
- ICertRecordList list =findCertRecordsInList(filter,
+ ICertRecordList list = findCertRecordsInList(filter,
null, "serialno", 10);
int size = list.getSize();
Enumeration<ICertRecord> e = list.getCertRecords(0, size - 1);
@@ -192,8 +185,8 @@ public class CertificateRepository extends Repository
BigInteger min = cur;
if (endS != null)
min = cur.min(endS);
- if (cur.equals(beginS) || cur.equals(endS) ||
- (cur.equals(max) && cur.equals(min)))
+ if (cur.equals(beginS) || cur.equals(endS) ||
+ (cur.equals(max) && cur.equals(min)))
deleteCertificateRecord(cur);
}
}
@@ -223,9 +216,7 @@ public class CertificateRepository extends Repository
}
/**
- * interval value: (in seconds)
- * 0 - disable
- * >0 - enable
+ * interval value: (in seconds) 0 - disable >0 - enable
*/
public CertStatusUpdateThread mCertStatusUpdateThread = null;
public RetrieveModificationsThread mRetrieveModificationsThread = null;
@@ -243,8 +234,8 @@ public class CertificateRepository extends Repository
return;
}
- CMS.debug("In setCertStatusUpdateInterval listenToCloneModifications="+listenToCloneModifications+
- " mRetrieveModificationsThread="+mRetrieveModificationsThread);
+ CMS.debug("In setCertStatusUpdateInterval listenToCloneModifications=" + listenToCloneModifications +
+ " mRetrieveModificationsThread=" + mRetrieveModificationsThread);
if (listenToCloneModifications && mRetrieveModificationsThread == null) {
CMS.debug("In setCertStatusUpdateInterval about to create RetrieveModificationsThread");
mRetrieveModificationsThread = new RetrieveModificationsThread(this, "RetrieveModificationsThread");
@@ -273,7 +264,6 @@ public class CertificateRepository extends Repository
}
}
-
/**
* Blocking method.
*/
@@ -281,21 +271,21 @@ public class CertificateRepository extends Repository
CMS.debug("In updateCertStatus()");
- CMS.getLogger().log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- CMS.getLogMessage("CMSCORE_DBS_START_VALID_SEARCH"));
+ CMS.getLogger().log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
+ CMS.getLogMessage("CMSCORE_DBS_START_VALID_SEARCH"));
transitInvalidCertificates();
CMS.getLogger().log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- CMS.getLogMessage("CMSCORE_DBS_FINISH_VALID_SEARCH"));
+ CMS.getLogMessage("CMSCORE_DBS_FINISH_VALID_SEARCH"));
CMS.getLogger().log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- CMS.getLogMessage("CMSCORE_DBS_START_EXPIRED_SEARCH"));
+ CMS.getLogMessage("CMSCORE_DBS_START_EXPIRED_SEARCH"));
transitValidCertificates();
CMS.getLogger().log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- CMS.getLogMessage("CMSCORE_DBS_FINISH_EXPIRED_SEARCH"));
+ CMS.getLogMessage("CMSCORE_DBS_FINISH_EXPIRED_SEARCH"));
CMS.getLogger().log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- CMS.getLogMessage("CMSCORE_DBS_START_REVOKED_EXPIRED_SEARCH"));
+ CMS.getLogMessage("CMSCORE_DBS_START_REVOKED_EXPIRED_SEARCH"));
transitRevokedExpiredCertificates();
CMS.getLogger().log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- CMS.getLogMessage("CMSCORE_DBS_FINISH_REVOKED_EXPIRED_SEARCH"));
+ CMS.getLogMessage("CMSCORE_DBS_FINISH_REVOKED_EXPIRED_SEARCH"));
}
/**
@@ -305,13 +295,14 @@ public class CertificateRepository extends Repository
return mBaseDN;
}
- public void setRequestDN( String requestDN ) {
+ public void setRequestDN(String requestDN) {
mRequestBaseDN = requestDN;
}
- public String getRequestDN() {
+ public String getRequestDN() {
return mRequestBaseDN;
}
+
/**
* Retrieves backend database handle.
*/
@@ -320,22 +311,21 @@ public class CertificateRepository extends Repository
}
/**
- * Adds a certificate record to the repository. Each certificate
- * record contains four parts: certificate, meta-attributes,
- * issue information and reovcation information.
+ * Adds a certificate record to the repository. Each certificate record
+ * contains four parts: certificate, meta-attributes, issue information and
+ * reovcation information.
* <P>
- *
+ *
* @param cert X.509 certificate
- * @exception EBaseException failed to add new certificate to
- * the repository
+ * @exception EBaseException failed to add new certificate to the repository
*/
public void addCertificateRecord(ICertRecord record)
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
try {
String name = "cn" + "=" +
- ((CertRecord) record).getSerialNumber().toString() + "," + getDN();
+ ((CertRecord) record).getSerialNumber().toString() + "," + getDN();
SessionContext ctx = SessionContext.getContext();
String uid = (String) ctx.get(SessionContext.USER_ID);
@@ -344,15 +334,15 @@ public class CertificateRepository extends Repository
record.set(CertRecord.ATTR_ISSUED_BY, "system");
/**
- System.out.println("XXX servlet should set USER_ID");
- throw new EBaseException(BaseResources.UNKNOWN_PRINCIPAL_1,
- "null");
+ * System.out.println("XXX servlet should set USER_ID"); throw
+ * new EBaseException(BaseResources.UNKNOWN_PRINCIPAL_1,
+ * "null");
**/
} else {
record.set(CertRecord.ATTR_ISSUED_BY, uid);
}
- // Check validity of this certificate. If it is not invalid,
+ // Check validity of this certificate. If it is not invalid,
// mark it so. We will have a thread to transit the status
// from INVALID to VALID.
X509CertImpl x509cert = (X509CertImpl) record.get(
@@ -363,11 +353,11 @@ public class CertificateRepository extends Repository
if (x509cert.getNotBefore().after(now)) {
// not yet valid
- record.set(ICertRecord.ATTR_CERT_STATUS,
- ICertRecord.STATUS_INVALID);
+ record.set(ICertRecord.ATTR_CERT_STATUS,
+ ICertRecord.STATUS_INVALID);
}
}
-
+
s.add(name, record);
} finally {
if (s != null)
@@ -376,21 +366,20 @@ public class CertificateRepository extends Repository
}
/**
- * Used by the Clone Master (CLA) to add a revoked certificate
- * record to the repository.
+ * Used by the Clone Master (CLA) to add a revoked certificate record to the
+ * repository.
* <p>
- *
+ *
* @param record a CertRecord
- * @exception EBaseException failed to add new certificate to
- * the repository
+ * @exception EBaseException failed to add new certificate to the repository
*/
public void addRevokedCertRecord(CertRecord record)
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
try {
String name = "cn" + "=" +
- record.getSerialNumber().toString() + "," + getDN();
+ record.getSerialNumber().toString() + "," + getDN();
s.add(name, record);
} finally {
@@ -400,8 +389,8 @@ public class CertificateRepository extends Repository
}
/**
- * This transits a certificate status from VALID to EXPIRED
- * if a certificate becomes expired.
+ * This transits a certificate status from VALID to EXPIRED if a certificate
+ * becomes expired.
*/
public void transitValidCertificates() throws EBaseException {
@@ -431,12 +420,13 @@ public class CertificateRepository extends Repository
for (i = 0; i < ltSize; i++) {
obj = recList.getCertRecord(i);
- if (obj != null) {
+ if (obj != null) {
curRec = (CertRecord) obj;
Date notAfter = curRec.getNotAfter();
- //CMS.debug("notAfter " + notAfter.toString() + " now " + now.toString());
+ // CMS.debug("notAfter " + notAfter.toString() + " now " +
+ // now.toString());
if (notAfter.after(now)) {
CMS.debug("Record does not qualify,notAfter " + notAfter.toString() + " date " + now.toString());
continue;
@@ -461,13 +451,13 @@ public class CertificateRepository extends Repository
}
/**
- * This transits a certificate status from REVOKED to REVOKED_EXPIRED
- * if an revoked certificate becomes expired.
+ * This transits a certificate status from REVOKED to REVOKED_EXPIRED if an
+ * revoked certificate becomes expired.
*/
public void transitRevokedExpiredCertificates() throws EBaseException {
Date now = CMS.getCurrentDate();
ICertRecordList recList = getRevokedCertsByNotAfterDate(now, -1 * mTransitRecordPageSize);
-
+
int size = recList.getSize();
if (size <= 0) {
@@ -495,7 +485,8 @@ public class CertificateRepository extends Repository
Date notAfter = curRec.getNotAfter();
- // CMS.debug("notAfter " + notAfter.toString() + " now " + now.toString());
+ // CMS.debug("notAfter " + notAfter.toString() + " now " +
+ // now.toString());
if (notAfter.after(now)) {
CMS.debug("Record does not qualify,notAfter " + notAfter.toString() + " date " + now.toString());
continue;
@@ -506,7 +497,7 @@ public class CertificateRepository extends Repository
} else {
cList.add(curRec.getSerialNumber());
}
- } else {
+ } else {
CMS.debug("found null record in getCertRecord");
}
}
@@ -516,8 +507,8 @@ public class CertificateRepository extends Repository
}
/**
- * This transits a certificate status from INVALID to VALID
- * if a certificate becomes valid.
+ * This transits a certificate status from INVALID to VALID if a certificate
+ * becomes valid.
*/
public void transitInvalidCertificates() throws EBaseException {
@@ -554,7 +545,8 @@ public class CertificateRepository extends Repository
Date notBefore = curRec.getNotBefore();
- //CMS.debug("notBefore " + notBefore.toString() + " now " + now.toString());
+ // CMS.debug("notBefore " + notBefore.toString() + " now " +
+ // now.toString());
if (notBefore.after(now)) {
CMS.debug("Record does not qualify,notBefore " + notBefore.toString() + " date " + now.toString());
continue;
@@ -600,8 +592,9 @@ public class CertificateRepository extends Repository
updateStatus(serial, newCertStatus);
if (newCertStatus.equals(CertRecord.STATUS_REVOKED_EXPIRED)) {
-
- // inform all CRLIssuingPoints about revoked and expired certificate
+
+ // inform all CRLIssuingPoints about revoked and expired
+ // certificate
Enumeration<ICRLIssuingPoint> eIPs = mCRLIssuingPoints.elements();
@@ -625,7 +618,7 @@ public class CertificateRepository extends Repository
* Reads the certificate identified by the given serial no.
*/
public X509CertImpl getX509Certificate(BigInteger serialNo)
- throws EBaseException {
+ throws EBaseException {
X509CertImpl cert = null;
ICertRecord cr = readCertificateRecord(serialNo);
@@ -636,16 +629,16 @@ public class CertificateRepository extends Repository
* Deletes certificate record.
*/
public void deleteCertificateRecord(BigInteger serialNo)
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
try {
String name = "cn" + "=" +
- serialNo.toString() + "," + getDN();
+ serialNo.toString() + "," + getDN();
s.delete(name);
} finally {
- if (s != null)
+ if (s != null)
s.close();
}
}
@@ -654,35 +647,35 @@ public class CertificateRepository extends Repository
* Reads certificate from repository.
*/
public ICertRecord readCertificateRecord(BigInteger serialNo)
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
CertRecord rec = null;
try {
String name = "cn" + "=" +
- serialNo.toString() + "," + getDN();
+ serialNo.toString() + "," + getDN();
rec = (CertRecord) s.read(name);
} finally {
- if (s != null)
+ if (s != null)
s.close();
}
return rec;
}
public synchronized void modifyCertificateRecord(BigInteger serialNo,
- ModificationSet mods) throws EBaseException {
+ ModificationSet mods) throws EBaseException {
IDBSSession s = mDBService.createSession();
try {
String name = "cn" + "=" +
- serialNo.toString() + "," + getDN();
+ serialNo.toString() + "," + getDN();
mods.add(CertRecord.ATTR_MODIFY_TIME, Modification.MOD_REPLACE,
- CMS.getCurrentDate());
+ CMS.getCurrentDate());
s.modify(name, mods);
} finally {
- if (s != null)
+ if (s != null)
s.close();
}
}
@@ -691,7 +684,7 @@ public class CertificateRepository extends Repository
* Checks if the specified certificate is in the repository.
*/
public boolean containsCertificate(BigInteger serialNo)
- throws EBaseException {
+ throws EBaseException {
try {
ICertRecord cr = readCertificateRecord(serialNo);
@@ -706,7 +699,7 @@ public class CertificateRepository extends Repository
* Marks certificate as revoked.
*/
public void markAsRevoked(BigInteger id, IRevocationInfo info)
- throws EBaseException {
+ throws EBaseException {
ModificationSet mods = new ModificationSet();
mods.add(CertRecord.ATTR_REVO_INFO, Modification.MOD_ADD, info);
@@ -715,15 +708,15 @@ public class CertificateRepository extends Repository
if (uid == null) {
mods.add(CertRecord.ATTR_REVOKED_BY, Modification.MOD_ADD,
- "system");
+ "system");
} else {
mods.add(CertRecord.ATTR_REVOKED_BY, Modification.MOD_ADD,
- uid);
+ uid);
}
mods.add(CertRecord.ATTR_REVOKED_ON, Modification.MOD_ADD,
- CMS.getCurrentDate());
+ CMS.getCurrentDate());
mods.add(CertRecord.ATTR_CERT_STATUS, Modification.MOD_REPLACE,
- CertRecord.STATUS_REVOKED);
+ CertRecord.STATUS_REVOKED);
modifyCertificateRecord(id, mods);
}
@@ -731,15 +724,15 @@ public class CertificateRepository extends Repository
* Unmarks revoked certificate.
*/
public void unmarkRevoked(BigInteger id, IRevocationInfo info,
- Date revokedOn, String revokedBy)
- throws EBaseException {
+ Date revokedOn, String revokedBy)
+ throws EBaseException {
ModificationSet mods = new ModificationSet();
mods.add(CertRecord.ATTR_REVO_INFO, Modification.MOD_DELETE, info);
mods.add(CertRecord.ATTR_REVOKED_BY, Modification.MOD_DELETE, revokedBy);
mods.add(CertRecord.ATTR_REVOKED_ON, Modification.MOD_DELETE, revokedOn);
mods.add(CertRecord.ATTR_CERT_STATUS, Modification.MOD_REPLACE,
- CertRecord.STATUS_VALID);
+ CertRecord.STATUS_VALID);
modifyCertificateRecord(id, mods);
}
@@ -747,17 +740,17 @@ public class CertificateRepository extends Repository
* Updates the certificiate record status to the specified.
*/
public void updateStatus(BigInteger id, String status)
- throws EBaseException {
+ throws EBaseException {
CMS.debug("updateStatus: " + id + " status " + status);
ModificationSet mods = new ModificationSet();
mods.add(CertRecord.ATTR_CERT_STATUS, Modification.MOD_REPLACE,
- status);
+ status);
modifyCertificateRecord(id, mods);
}
public Enumeration searchCertificates(String filter, int maxSize)
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
Enumeration e = null;
@@ -765,14 +758,14 @@ public class CertificateRepository extends Repository
try {
e = s.search(getDN(), filter, maxSize);
} finally {
- if (s != null)
+ if (s != null)
s.close();
}
return e;
}
public Enumeration searchCertificates(String filter, int maxSize, int timeLimit)
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
Enumeration e = null;
@@ -780,7 +773,7 @@ public class CertificateRepository extends Repository
try {
e = s.search(getDN(), filter, maxSize, timeLimit);
} finally {
- if (s != null)
+ if (s != null)
s.close();
}
return e;
@@ -788,39 +781,42 @@ public class CertificateRepository extends Repository
/**
* Returns a list of X509CertImp that satisfies the filter.
+ *
* @deprecated replaced by <code>findCertificatesInList</code>
*/
public Enumeration findCertRecs(String filter)
- throws EBaseException {
+ throws EBaseException {
CMS.debug("findCertRecs " + filter);
IDBSSession s = mDBService.createSession();
Enumeration e = null;
try {
e = s.search(getDN(), filter);
} finally {
- if (s != null) s.close();
+ if (s != null)
+ s.close();
}
return e;
}
public Enumeration findCertRecs(String filter, String[] attrs)
- throws EBaseException {
+ throws EBaseException {
- CMS.debug( "findCertRecs " + filter
- + "attrs " + Arrays.toString( attrs ) );
+ CMS.debug("findCertRecs " + filter
+ + "attrs " + Arrays.toString(attrs));
IDBSSession s = mDBService.createSession();
Enumeration e = null;
try {
e = s.search(getDN(), filter, attrs);
} finally {
- if (s != null) s.close();
+ if (s != null)
+ s.close();
}
return e;
}
public Enumeration<X509CertImpl> findCertificates(String filter)
- throws EBaseException {
+ throws EBaseException {
Enumeration e = findCertRecords(filter);
Vector<X509CertImpl> v = new Vector<X509CertImpl>();
@@ -833,18 +829,16 @@ public class CertificateRepository extends Repository
}
/**
- * Finds a list of certificate records that satisifies
- * the filter.
- * If you are going to process everything in the list,
- * use this.
+ * Finds a list of certificate records that satisifies the filter. If you
+ * are going to process everything in the list, use this.
*/
public Enumeration findCertRecords(String filter)
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
Enumeration e = null;
try {
- //e = s.search(getDN(), filter);
+ // e = s.search(getDN(), filter);
ICertRecordList list = null;
list = findCertRecordsInList(filter, null, "serialno", 10);
@@ -852,15 +846,16 @@ public class CertificateRepository extends Repository
e = list.getCertRecords(0, size - 1);
} finally {
- if (s != null)
+ if (s != null)
s.close();
}
return e;
}
/**
- * Finds certificate records. Here is a list of filter
- * attribute can be used:
+ * Finds certificate records. Here is a list of filter attribute can be
+ * used:
+ *
* <pre>
* certRecordId
* certMetaInfo
@@ -871,49 +866,50 @@ public class CertificateRepository extends Repository
* x509Cert.notAfter
* x509Cert.subject
* </pre>
- * The filter should follow RFC1558 LDAP filter syntax.
- * For example,
+ *
+ * The filter should follow RFC1558 LDAP filter syntax. For example,
+ *
* <pre>
* (&(certRecordId=5)(x509Cert.notBefore=934398398))
* </pre>
*/
- public ICertRecordList findCertRecordsInList(String filter,
- String attrs[], int pageSize) throws EBaseException {
- return findCertRecordsInList(filter, attrs, CertRecord.ATTR_ID,
+ public ICertRecordList findCertRecordsInList(String filter,
+ String attrs[], int pageSize) throws EBaseException {
+ return findCertRecordsInList(filter, attrs, CertRecord.ATTR_ID,
pageSize);
}
- public ICertRecordList findCertRecordsInList(String filter,
- String attrs[], String sortKey, int pageSize)
- throws EBaseException {
+ public ICertRecordList findCertRecordsInList(String filter,
+ String attrs[], String sortKey, int pageSize)
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
CMS.debug("In findCertRecordsInList");
CertRecordList list = null;
try {
- IDBVirtualList<ICertRecord> vlist = s.createVirtualList(getDN(), filter, attrs,
+ IDBVirtualList<ICertRecord> vlist = s.createVirtualList(getDN(), filter, attrs,
sortKey, pageSize);
list = new CertRecordList(vlist);
} finally {
- if (s != null)
+ if (s != null)
s.close();
}
return list;
}
- public ICertRecordList findCertRecordsInList(String filter,
- String attrs[], String jumpTo, String sortKey, int pageSize)
- throws EBaseException {
- return findCertRecordsInList(filter, attrs, jumpTo, false, sortKey, pageSize);
+ public ICertRecordList findCertRecordsInList(String filter,
+ String attrs[], String jumpTo, String sortKey, int pageSize)
+ throws EBaseException {
+ return findCertRecordsInList(filter, attrs, jumpTo, false, sortKey, pageSize);
}
- public ICertRecordList findCertRecordsInList(String filter,
- String attrs[], String jumpTo, boolean hardJumpTo,
- String sortKey, int pageSize)
- throws EBaseException {
+ public ICertRecordList findCertRecordsInList(String filter,
+ String attrs[], String jumpTo, boolean hardJumpTo,
+ String sortKey, int pageSize)
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
CertRecordList list = null;
@@ -921,33 +917,33 @@ public class CertificateRepository extends Repository
try {
String jumpToVal = null;
- if (hardJumpTo) {
- CMS.debug("In findCertRecordsInList with hardJumpto ");
- jumpToVal = "99";
- } else {
- int len = jumpTo.length();
-
- if (len > 9) {
- jumpToVal = Integer.toString(len) + jumpTo;
+ if (hardJumpTo) {
+ CMS.debug("In findCertRecordsInList with hardJumpto ");
+ jumpToVal = "99";
} else {
- jumpToVal = "0" + Integer.toString(len) + jumpTo;
+ int len = jumpTo.length();
+
+ if (len > 9) {
+ jumpToVal = Integer.toString(len) + jumpTo;
+ } else {
+ jumpToVal = "0" + Integer.toString(len) + jumpTo;
+ }
}
- }
- IDBVirtualList<ICertRecord> vlist = s.createVirtualList(getDN(), filter,
+ IDBVirtualList<ICertRecord> vlist = s.createVirtualList(getDN(), filter,
attrs, jumpToVal, sortKey, pageSize);
list = new CertRecordList(vlist);
} finally {
- if (s != null)
+ if (s != null)
s.close();
}
return list;
}
public ICertRecordList findCertRecordsInListRawJumpto(String filter,
- String attrs[], String jumpTo, String sortKey, int pageSize)
- throws EBaseException {
+ String attrs[], String jumpTo, String sortKey, int pageSize)
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
CertRecordList list = null;
@@ -955,7 +951,7 @@ public class CertificateRepository extends Repository
try {
- IDBVirtualList<ICertRecord> vlist = s.createVirtualList(getDN(), filter,
+ IDBVirtualList<ICertRecord> vlist = s.createVirtualList(getDN(), filter,
attrs, jumpTo, sortKey, pageSize);
list = new CertRecordList(vlist);
@@ -970,44 +966,44 @@ public class CertificateRepository extends Repository
* Marks certificate as renewable.
*/
public void markCertificateAsRenewable(ICertRecord record)
- throws EBaseException {
+ throws EBaseException {
changeRenewalAttribute(((CertRecord) record).getSerialNumber().toString(),
- CertRecord.AUTO_RENEWAL_ENABLED);
+ CertRecord.AUTO_RENEWAL_ENABLED);
}
/**
* Marks certificate as renewable.
*/
public void markCertificateAsNotRenewable(ICertRecord record)
- throws EBaseException {
+ throws EBaseException {
changeRenewalAttribute(((CertRecord) record).getSerialNumber().toString(),
- CertRecord.AUTO_RENEWAL_DISABLED);
+ CertRecord.AUTO_RENEWAL_DISABLED);
}
public void markCertificateAsRenewed(String serialNo)
- throws EBaseException {
+ throws EBaseException {
changeRenewalAttribute(serialNo, CertRecord.AUTO_RENEWAL_DONE);
}
public void markCertificateAsRenewalNotified(String serialNo)
- throws EBaseException {
+ throws EBaseException {
changeRenewalAttribute(serialNo, CertRecord.AUTO_RENEWAL_NOTIFIED);
}
private void changeRenewalAttribute(String serialno, String value)
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
try {
String name = "cn" + "=" + serialno +
- "," + getDN();
+ "," + getDN();
ModificationSet mods = new ModificationSet();
mods.add(CertRecord.ATTR_AUTO_RENEW, Modification.MOD_REPLACE,
- value);
+ value);
s.modify(name, mods);
} finally {
- if (s != null)
+ if (s != null)
s.close();
}
}
@@ -1018,6 +1014,7 @@ public class CertificateRepository extends Repository
public class RenewableCertificateCollection {
Vector<Object> mToRenew = null;
Vector<Object> mToNotify = null;
+
public RenewableCertificateCollection() {
}
@@ -1044,21 +1041,21 @@ public class CertificateRepository extends Repository
}
public Hashtable<String, RenewableCertificateCollection> getRenewableCertificates(String renewalTime)
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
Hashtable<String, RenewableCertificateCollection> tab = null;
try {
String filter = "(&(" + CertRecord.ATTR_CERT_STATUS + "=" +
- CertRecord.STATUS_VALID + ")("
- + CertRecord.ATTR_X509CERT +
- "." + CertificateValidity.NOT_AFTER + "<=" + renewalTime +
- ")(!(" + CertRecord.ATTR_AUTO_RENEW + "=" +
- CertRecord.AUTO_RENEWAL_DONE +
- "))(!(" + CertRecord.ATTR_AUTO_RENEW + "=" +
- CertRecord.AUTO_RENEWAL_NOTIFIED + ")))";
- //Enumeration e = s.search(getDN(), filter);
+ CertRecord.STATUS_VALID + ")("
+ + CertRecord.ATTR_X509CERT +
+ "." + CertificateValidity.NOT_AFTER + "<=" + renewalTime +
+ ")(!(" + CertRecord.ATTR_AUTO_RENEW + "=" +
+ CertRecord.AUTO_RENEWAL_DONE +
+ "))(!(" + CertRecord.ATTR_AUTO_RENEW + "=" +
+ CertRecord.AUTO_RENEWAL_NOTIFIED + ")))";
+ // Enumeration e = s.search(getDN(), filter);
ICertRecordList list = null;
list = findCertRecordsInList(filter, null, "serialno", 10);
@@ -1077,7 +1074,7 @@ public class CertificateRepository extends Repository
if ((val = tab.get(subjectDN)) == null) {
RenewableCertificateCollection collection =
- new RenewableCertificateCollection();
+ new RenewableCertificateCollection();
collection.addCertificate(renewalFlag, cert);
tab.put(subjectDN, collection);
@@ -1086,23 +1083,22 @@ public class CertificateRepository extends Repository
}
}
} finally {
- if (s != null)
+ if (s != null)
s.close();
}
return tab;
}
/**
- * Gets all valid and unexpired certificates pertaining
- * to a subject DN.
- *
- * @param subjectDN The distinguished name of the subject.
- * @param validityType The type of certificates to get.
+ * Gets all valid and unexpired certificates pertaining to a subject DN.
+ *
+ * @param subjectDN The distinguished name of the subject.
+ * @param validityType The type of certificates to get.
* @return An array of certificates.
*/
public X509CertImpl[] getX509Certificates(String subjectDN,
- int validityType) throws EBaseException {
+ int validityType) throws EBaseException {
IDBSSession s = mDBService.createSession();
X509CertImpl certs[] = null;
@@ -1110,7 +1106,7 @@ public class CertificateRepository extends Repository
try {
// XXX - not checking validityType...
String filter = "(&(" + CertRecord.ATTR_X509CERT +
- "." + X509CertInfo.SUBJECT + "=" + subjectDN;
+ "." + X509CertInfo.SUBJECT + "=" + subjectDN;
if (validityType == ALL_VALID_CERTS) {
filter += ")(" +
@@ -1126,7 +1122,7 @@ public class CertificateRepository extends Repository
}
filter += "))";
- //Enumeration e = s.search(getDN(), filter);
+ // Enumeration e = s.search(getDN(), filter);
ICertRecordList list = null;
list = findCertRecordsInList(filter, null, "serialno", 10);
@@ -1145,14 +1141,14 @@ public class CertificateRepository extends Repository
certs = new X509CertImpl[v.size()];
v.copyInto(certs);
} finally {
- if (s != null)
+ if (s != null)
s.close();
}
return certs;
}
public X509CertImpl[] getX509Certificates(String filter)
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
X509CertImpl certs[] = null;
@@ -1161,7 +1157,7 @@ public class CertificateRepository extends Repository
Enumeration e = null;
if (filter != null && filter.length() > 0) {
- //e = s.search(getDN(), filter);
+ // e = s.search(getDN(), filter);
ICertRecordList list = null;
list = findCertRecordsInList(filter, null, "serialno", 10);
@@ -1182,7 +1178,7 @@ public class CertificateRepository extends Repository
v.copyInto(certs);
}
} finally {
- if (s != null)
+ if (s != null)
s.close();
}
return certs;
@@ -1190,106 +1186,108 @@ public class CertificateRepository extends Repository
/**
* Retrives all valid certificates excluding ones already revoked.
- * @param from The starting point of the serial number range.
- * @param to The ending point of the serial number range.
+ *
+ * @param from The starting point of the serial number range.
+ * @param to The ending point of the serial number range.
*/
public Enumeration<CertRecord> getValidCertificates(String from, String to)
- throws EBaseException {
- IDBSSession s = mDBService.createSession();
- Vector<CertRecord> v = new Vector<CertRecord>();
+ throws EBaseException {
+ IDBSSession s = mDBService.createSession();
+ Vector<CertRecord> v = new Vector<CertRecord>();
- try {
+ try {
- // 'from' determines 'jumpto' value
- // 'to' determines where to stop looking
+ // 'from' determines 'jumpto' value
+ // 'to' determines where to stop looking
- String ldapfilter = "(certstatus=VALID)";
+ String ldapfilter = "(certstatus=VALID)";
- String fromVal = "0";
- try {
- if (from != null) {
- int fv = Integer.parseInt(from);
- fromVal = from;
- }
- } catch (Exception e1) {
- // from is not integer
+ String fromVal = "0";
+ try {
+ if (from != null) {
+ int fv = Integer.parseInt(from);
+ fromVal = from;
}
+ } catch (Exception e1) {
+ // from is not integer
+ }
- ICertRecordList list =
- findCertRecordsInList(ldapfilter, null, fromVal, "serialno", 40);
+ ICertRecordList list =
+ findCertRecordsInList(ldapfilter, null, fromVal, "serialno", 40);
- BigInteger toInt = null;
- if (to != null && !to.trim().equals("")) {
- toInt = new BigInteger(to);
- }
+ BigInteger toInt = null;
+ if (to != null && !to.trim().equals("")) {
+ toInt = new BigInteger(to);
+ }
- for (int i=0;; i++) {
- CertRecord rec = (CertRecord) list.getCertRecord(i);
- CMS.debug("processing record: "+i);
- if (rec == null) {
- break; // no element returned
- } else {
-
- CMS.debug("processing record: "+i+" "+rec.getSerialNumber());
- // Check if we are past the 'to' marker
- if (toInt != null) {
- if (rec.getSerialNumber().compareTo(toInt) > 0) {
- break;
- }
+ for (int i = 0;; i++) {
+ CertRecord rec = (CertRecord) list.getCertRecord(i);
+ CMS.debug("processing record: " + i);
+ if (rec == null) {
+ break; // no element returned
+ } else {
+
+ CMS.debug("processing record: " + i + " " + rec.getSerialNumber());
+ // Check if we are past the 'to' marker
+ if (toInt != null) {
+ if (rec.getSerialNumber().compareTo(toInt) > 0) {
+ break;
}
- v.addElement(rec);
- }
- }
-
- } finally {
- if (s != null)
- s.close();
- }
- CMS.debug("returning "+v.size()+" elements");
- return v.elements();
- }
+ }
+ v.addElement(rec);
+ }
+ }
+
+ } finally {
+ if (s != null)
+ s.close();
+ }
+ CMS.debug("returning " + v.size() + " elements");
+ return v.elements();
+ }
/**
* Retrives all valid certificates excluding ones already revoked.
*/
public Enumeration getAllValidCertificates()
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
Enumeration e = null;
try {
Date now = CMS.getCurrentDate();
String ldapfilter = "(&(!(" + CertRecord.ATTR_REVO_INFO + "=*))(" +
- CertRecord.ATTR_X509CERT + "." +
- CertificateValidity.NOT_BEFORE + "<=" +
- DateMapper.dateToDB(now) + ")(" +
- CertRecord.ATTR_X509CERT + "." +
- CertificateValidity.NOT_AFTER + ">=" +
- DateMapper.dateToDB(now) + "))";
- //e = s.search(getDN(), ldapfilter);
+ CertRecord.ATTR_X509CERT + "." +
+ CertificateValidity.NOT_BEFORE + "<=" +
+ DateMapper.dateToDB(now) + ")(" +
+ CertRecord.ATTR_X509CERT + "." +
+ CertificateValidity.NOT_AFTER + ">=" +
+ DateMapper.dateToDB(now) + "))";
+ // e = s.search(getDN(), ldapfilter);
ICertRecordList list = null;
list = findCertRecordsInList(ldapfilter, null, "serialno", 10);
int size = list.getSize();
e = list.getCertRecords(0, size - 1);
-
+
} finally {
// XXX - transaction is not done at this moment
- if (s != null)
+ if (s != null)
s.close();
}
return e;
}
/**
- * Retrives all valid not published certificates
- * excluding ones already revoked.
- * @param from The starting point of the serial number range.
- * @param to The ending point of the serial number range.
+ * Retrives all valid not published certificates excluding ones already
+ * revoked.
+ *
+ * @param from The starting point of the serial number range.
+ * @param to The ending point of the serial number range.
*/
public Enumeration getValidNotPublishedCertificates(String from, String to)
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
Enumeration e = null;
@@ -1311,53 +1309,53 @@ public class CertificateRepository extends Repository
"certMetainfo=" +
CertRecord.META_LDAPPUBLISH +
":true)))";
- //e = s.search(getDN(), ldapfilter);
+ // e = s.search(getDN(), ldapfilter);
ICertRecordList list = null;
list = findCertRecordsInList(ldapfilter, null, "serialno", 10);
int size = list.getSize();
e = list.getCertRecords(0, size - 1);
-
+
} finally {
- if (s != null)
+ if (s != null)
s.close();
}
return e;
}
/**
- * Retrives all valid not published certificates
- * excluding ones already revoked.
+ * Retrives all valid not published certificates excluding ones already
+ * revoked.
*/
public Enumeration getAllValidNotPublishedCertificates()
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
Enumeration e = null;
try {
Date now = CMS.getCurrentDate();
String ldapfilter = "(&(!(" + CertRecord.ATTR_REVO_INFO + "=*))(" +
- CertRecord.ATTR_X509CERT + "." +
- CertificateValidity.NOT_BEFORE + "<=" +
- DateMapper.dateToDB(now) + ")(" +
- CertRecord.ATTR_X509CERT + "." +
- CertificateValidity.NOT_AFTER + ">=" +
- DateMapper.dateToDB(now) + ")(!(" +
- "certMetainfo=" +
- CertRecord.META_LDAPPUBLISH +
- ":true)))";
- //e = s.search(getDN(), ldapfilter);
+ CertRecord.ATTR_X509CERT + "." +
+ CertificateValidity.NOT_BEFORE + "<=" +
+ DateMapper.dateToDB(now) + ")(" +
+ CertRecord.ATTR_X509CERT + "." +
+ CertificateValidity.NOT_AFTER + ">=" +
+ DateMapper.dateToDB(now) + ")(!(" +
+ "certMetainfo=" +
+ CertRecord.META_LDAPPUBLISH +
+ ":true)))";
+ // e = s.search(getDN(), ldapfilter);
ICertRecordList list = null;
list = findCertRecordsInList(ldapfilter, null, "serialno", 10);
int size = list.getSize();
e = list.getCertRecords(0, size - 1);
-
+
} finally {
// XXX - transaction is not done at this moment
- if (s != null)
+ if (s != null)
s.close();
}
return e;
@@ -1365,11 +1363,12 @@ public class CertificateRepository extends Repository
/**
* Retrives all expired certificates.
- * @param from The starting point of the serial number range.
- * @param to The ending point of the serial number range.
+ *
+ * @param from The starting point of the serial number range.
+ * @param to The ending point of the serial number range.
*/
public Enumeration getExpiredCertificates(String from, String to)
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
Enumeration e = null;
@@ -1384,17 +1383,17 @@ public class CertificateRepository extends Repository
ldapfilter += "!(" + CertRecord.ATTR_X509CERT + "." +
CertificateValidity.NOT_AFTER + ">=" +
DateMapper.dateToDB(now) + ")))";
- //e = s.search(getDN(), ldapfilter);
-
+ // e = s.search(getDN(), ldapfilter);
+
ICertRecordList list = null;
list = findCertRecordsInList(ldapfilter, null, "serialno", 10);
int size = list.getSize();
e = list.getCertRecords(0, size - 1);
- } finally {
+ } finally {
// XXX - transaction is not done at this moment
- if (s != null)
+ if (s != null)
s.close();
}
return e;
@@ -1404,26 +1403,26 @@ public class CertificateRepository extends Repository
* Retrives all expired certificates.
*/
public Enumeration getAllExpiredCertificates()
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
Enumeration e = null;
try {
Date now = CMS.getCurrentDate();
String ldapfilter = "(!(" + CertRecord.ATTR_X509CERT + "." +
- CertificateValidity.NOT_AFTER + ">=" +
- DateMapper.dateToDB(now) + "))";
- //e = s.search(getDN(), ldapfilter);
+ CertificateValidity.NOT_AFTER + ">=" +
+ DateMapper.dateToDB(now) + "))";
+ // e = s.search(getDN(), ldapfilter);
ICertRecordList list = null;
list = findCertRecordsInList(ldapfilter, null, "serialno", 10);
int size = list.getSize();
e = list.getCertRecords(0, size - 1);
-
- } finally {
+
+ } finally {
// XXX - transaction is not done at this moment
- if (s != null)
+ if (s != null)
s.close();
}
return e;
@@ -1431,11 +1430,12 @@ public class CertificateRepository extends Repository
/**
* Retrives all expired published certificates.
- * @param from The starting point of the serial number range.
- * @param to The ending point of the serial number range.
+ *
+ * @param from The starting point of the serial number range.
+ * @param to The ending point of the serial number range.
*/
public Enumeration getExpiredPublishedCertificates(String from, String to)
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
Enumeration e = null;
@@ -1449,22 +1449,22 @@ public class CertificateRepository extends Repository
ldapfilter += CertRecord.ATTR_ID + "<=" + to + ")(";
ldapfilter += "!(" + CertRecord.ATTR_X509CERT + "." +
CertificateValidity.NOT_AFTER + ">=" +
- //DateMapper.dateToDB(now) + ")))";
+ // DateMapper.dateToDB(now) + ")))";
DateMapper.dateToDB(now) + "))(" +
"certMetainfo=" +
CertRecord.META_LDAPPUBLISH +
":true))";
- //e = s.search(getDN(), ldapfilter);
-
+ // e = s.search(getDN(), ldapfilter);
+
ICertRecordList list = null;
list = findCertRecordsInList(ldapfilter, null, "serialno", 10);
int size = list.getSize();
e = list.getCertRecords(0, size - 1);
- } finally {
+ } finally {
// XXX - transaction is not done at this moment
- if (s != null)
+ if (s != null)
s.close();
}
return e;
@@ -1474,7 +1474,7 @@ public class CertificateRepository extends Repository
* Retrives all expired publishedcertificates.
*/
public Enumeration getAllExpiredPublishedCertificates()
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
Enumeration e = null;
@@ -1488,25 +1488,25 @@ public class CertificateRepository extends Repository
ldapfilter += "(certMetainfo=" +
CertRecord.META_LDAPPUBLISH +
":true))";
-
- //e = s.search(getDN(), ldapfilter);
+
+ // e = s.search(getDN(), ldapfilter);
ICertRecordList list = null;
list = findCertRecordsInList(ldapfilter, null, "serialno", 10);
int size = list.getSize();
e = list.getCertRecords(0, size - 1);
-
- } finally {
+
+ } finally {
// XXX - transaction is not done at this moment
- if (s != null)
+ if (s != null)
s.close();
}
return e;
}
public ICertRecordList getInvalidCertsByNotBeforeDate(Date date, int pageSize)
- throws EBaseException {
+ throws EBaseException {
String now = null;
@@ -1521,22 +1521,21 @@ public class CertificateRepository extends Repository
String[] attrs = null;
if (mConsistencyCheck == false) {
- attrs = new String[] { "objectclass", CertRecord.ATTR_ID, CertRecord.ATTR_X509CERT};
+ attrs = new String[] { "objectclass", CertRecord.ATTR_ID, CertRecord.ATTR_X509CERT };
}
CMS.debug("getInvalidCertificatesByNotBeforeDate filter " + ldapfilter);
- //e = s.search(getDN(), ldapfilter);
+ // e = s.search(getDN(), ldapfilter);
CMS.debug("getInvalidCertificatesByNotBeforeDate: about to call findCertRecordsInList");
list = findCertRecordsInListRawJumpto(ldapfilter, attrs,
DateMapper.dateToDB(date), "notBefore", pageSize);
- //e = list.getCertRecords(0, size - 1);
+ // e = list.getCertRecords(0, size - 1);
} finally {
// XXX - transaction is not done at this moment
-
CMS.debug("In getInvalidCertsByNotBeforeDate finally.");
if (s != null)
@@ -1547,7 +1546,7 @@ public class CertificateRepository extends Repository
}
public ICertRecordList getValidCertsByNotAfterDate(Date date, int pageSize)
- throws EBaseException {
+ throws EBaseException {
String now = null;
@@ -1560,11 +1559,11 @@ public class CertificateRepository extends Repository
String[] attrs = null;
if (mConsistencyCheck == false) {
- attrs = new String[] { "objectclass", CertRecord.ATTR_ID, CertRecord.ATTR_X509CERT};
+ attrs = new String[] { "objectclass", CertRecord.ATTR_ID, CertRecord.ATTR_X509CERT };
}
CMS.debug("getValidCertsByNotAfterDate filter " + ldapfilter);
- //e = s.search(getDN(), ldapfilter);
+ // e = s.search(getDN(), ldapfilter);
list = findCertRecordsInListRawJumpto(ldapfilter, attrs, DateMapper.dateToDB(date), "notAfter", pageSize);
} finally {
@@ -1577,7 +1576,7 @@ public class CertificateRepository extends Repository
}
public ICertRecordList getRevokedCertsByNotAfterDate(Date date, int pageSize)
- throws EBaseException {
+ throws EBaseException {
ICertRecordList list = null;
IDBSSession s = mDBService.createSession();
@@ -1589,11 +1588,11 @@ public class CertificateRepository extends Repository
if (mConsistencyCheck == false) {
attrs = new String[] { "objectclass", CertRecord.ATTR_REVOKED_ON, CertRecord.ATTR_ID,
- CertRecord.ATTR_REVO_INFO, CertificateValidity.NOT_AFTER, CertRecord.ATTR_X509CERT};
+ CertRecord.ATTR_REVO_INFO, CertificateValidity.NOT_AFTER, CertRecord.ATTR_X509CERT };
}
CMS.debug("getRevokedCertificatesByNotAfterDate filter " + ldapfilter);
- //e = s.search(getDN(), ldapfilter);
+ // e = s.search(getDN(), ldapfilter);
CMS.debug("getRevokedCertificatesByNotAfterDate: about to call findCertRecordsInList");
list = findCertRecordsInListRawJumpto(ldapfilter, attrs,
@@ -1602,21 +1601,21 @@ public class CertificateRepository extends Repository
} finally {
// XXX - transaction is not done at this moment
-
if (s != null)
s.close();
}
return list;
}
-
+
/**
- * Retrieves all revoked certificates in the serial number range.
- * @param from The starting point of the serial number range.
- * @param to The ending point of the serial number range.
+ * Retrieves all revoked certificates in the serial number range.
+ *
+ * @param from The starting point of the serial number range.
+ * @param to The ending point of the serial number range.
*/
public Enumeration getRevokedCertificates(String from, String to)
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
Enumeration e = null;
@@ -1628,7 +1627,7 @@ public class CertificateRepository extends Repository
if (to != null && to.length() > 0)
ldapfilter += "(" + CertRecord.ATTR_ID + "<=" + to + ")";
ldapfilter += ")";
- //e = s.search(getDN(), ldapfilter);
+ // e = s.search(getDN(), ldapfilter);
ICertRecordList list = null;
list = findCertRecordsInList(ldapfilter, null, "serialno", 10);
@@ -1637,24 +1636,29 @@ public class CertificateRepository extends Repository
e = list.getCertRecords(0, size - 1);
} finally {
// XXX - transaction is not done at this moment
- if (s != null)
+ if (s != null)
s.close();
}
return e;
}
/**
- * Retrives all revoked certificates including ones already expired or
- * not yet valid.
+ * Retrives all revoked certificates including ones already expired or not
+ * yet valid.
*/
public Enumeration getAllRevokedCertificates()
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
Enumeration e = null;
- String ldapfilter = "(|(" + CertRecord.ATTR_CERT_STATUS + "=" + CertRecord.STATUS_REVOKED + ")(" + CertRecord.ATTR_CERT_STATUS + "=" + CertRecord.STATUS_REVOKED_EXPIRED + "))"; // index is setup for this filter
+ String ldapfilter = "(|(" + CertRecord.ATTR_CERT_STATUS + "=" + CertRecord.STATUS_REVOKED + ")(" + CertRecord.ATTR_CERT_STATUS + "=" + CertRecord.STATUS_REVOKED_EXPIRED + "))"; // index
+ // is
+ // setup
+ // for
+ // this
+ // filter
try {
- //e = s.search(getDN(), ldapfilter);
+ // e = s.search(getDN(), ldapfilter);
ICertRecordList list = null;
list = findCertRecordsInList(ldapfilter, null, "serialno", 10);
@@ -1662,19 +1666,20 @@ public class CertificateRepository extends Repository
e = list.getCertRecords(0, size - 1);
} finally {
- if (s != null)
+ if (s != null)
s.close();
}
return e;
}
/**
- * Retrieves all revoked publishedcertificates in the serial number range.
- * @param from The starting point of the serial number range.
- * @param to The ending point of the serial number range.
+ * Retrieves all revoked publishedcertificates in the serial number range.
+ *
+ * @param from The starting point of the serial number range.
+ * @param to The ending point of the serial number range.
*/
public Enumeration getRevokedPublishedCertificates(String from, String to)
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
Enumeration e = null;
@@ -1685,11 +1690,11 @@ public class CertificateRepository extends Repository
ldapfilter += "(" + CertRecord.ATTR_ID + ">=" + from + ")";
if (to != null && to.length() > 0)
ldapfilter += "(" + CertRecord.ATTR_ID + "<=" + to + ")";
- //ldapfilter += ")";
+ // ldapfilter += ")";
ldapfilter += "(certMetainfo=" +
CertRecord.META_LDAPPUBLISH +
":true))";
- //e = s.search(getDN(), ldapfilter);
+ // e = s.search(getDN(), ldapfilter);
ICertRecordList list = null;
list = findCertRecordsInList(ldapfilter, null, "serialno", 10);
@@ -1698,27 +1703,32 @@ public class CertificateRepository extends Repository
e = list.getCertRecords(0, size - 1);
} finally {
// XXX - transaction is not done at this moment
- if (s != null)
+ if (s != null)
s.close();
}
return e;
}
/**
- * Retrives all revoked published certificates including ones
- * already expired or not yet valid.
+ * Retrives all revoked published certificates including ones already
+ * expired or not yet valid.
*/
public Enumeration getAllRevokedPublishedCertificates()
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
Enumeration e = null;
- String ldapfilter = "(&(|(" + CertRecord.ATTR_CERT_STATUS + "=" + CertRecord.STATUS_REVOKED + ")(" + CertRecord.ATTR_CERT_STATUS + "=" + CertRecord.STATUS_REVOKED_EXPIRED + "))"; // index is setup for this filter
+ String ldapfilter = "(&(|(" + CertRecord.ATTR_CERT_STATUS + "=" + CertRecord.STATUS_REVOKED + ")(" + CertRecord.ATTR_CERT_STATUS + "=" + CertRecord.STATUS_REVOKED_EXPIRED + "))"; // index
+ // is
+ // setup
+ // for
+ // this
+ // filter
ldapfilter += "(certMetainfo=" +
CertRecord.META_LDAPPUBLISH +
":true))";
try {
- //e = s.search(getDN(), ldapfilter);
+ // e = s.search(getDN(), ldapfilter);
ICertRecordList list = null;
list = findCertRecordsInList(ldapfilter, null, "serialno", 10);
@@ -1726,30 +1736,31 @@ public class CertificateRepository extends Repository
e = list.getCertRecords(0, size - 1);
} finally {
- if (s != null)
+ if (s != null)
s.close();
}
return e;
}
/**
- * Retrieves all revoked certificates that have not expired.
+ * Retrieves all revoked certificates that have not expired.
*/
public Enumeration getRevokedCertificates(Date asOfDate)
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
Enumeration e = null;
try {
- /*e = s.search(getDN(), "(&(" +
- CertRecord.ATTR_REVO_INFO + "=*)(" + CertRecord.ATTR_X509CERT +
- "." + CertificateValidity.NOT_AFTER + " >= " +
- DateMapper.dateToDB(asOfDate) + "))");*/
+ /*
+ * e = s.search(getDN(), "(&(" + CertRecord.ATTR_REVO_INFO + "=*)("
+ * + CertRecord.ATTR_X509CERT + "." + CertificateValidity.NOT_AFTER
+ * + " >= " + DateMapper.dateToDB(asOfDate) + "))");
+ */
String ldapfilter = "(&(" +
- CertRecord.ATTR_REVO_INFO + "=*)(" + CertRecord.ATTR_X509CERT +
- "." + CertificateValidity.NOT_AFTER + " >= " +
- DateMapper.dateToDB(asOfDate) + "))";
+ CertRecord.ATTR_REVO_INFO + "=*)(" + CertRecord.ATTR_X509CERT +
+ "." + CertificateValidity.NOT_AFTER + " >= " +
+ DateMapper.dateToDB(asOfDate) + "))";
ICertRecordList list = null;
list = findCertRecordsInList(ldapfilter, null, "serialno", 10);
@@ -1758,7 +1769,7 @@ public class CertificateRepository extends Repository
e = list.getCertRecords(0, size - 1);
} finally {
// XXX - transaction is not done at this moment
- if (s != null)
+ if (s != null)
s.close();
}
return e;
@@ -1768,13 +1779,18 @@ public class CertificateRepository extends Repository
* Retrives all revoked certificates excluing ones already expired.
*/
public Enumeration getAllRevokedNonExpiredCertificates()
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
Enumeration e = null;
- String ldapfilter = "(" + CertRecord.ATTR_CERT_STATUS + "=" + CertRecord.STATUS_REVOKED + ")"; // index is setup for this filter
+ String ldapfilter = "(" + CertRecord.ATTR_CERT_STATUS + "=" + CertRecord.STATUS_REVOKED + ")"; // index
+ // is
+ // setup
+ // for
+ // this
+ // filter
try {
- //e = s.search(getDN(), ldapfilter);
+ // e = s.search(getDN(), ldapfilter);
ICertRecordList list = null;
list = findCertRecordsInList(ldapfilter, null, "serialno", 10);
@@ -1782,14 +1798,14 @@ public class CertificateRepository extends Repository
e = list.getCertRecords(0, size - 1);
} finally {
- if (s != null)
+ if (s != null)
s.close();
}
return e;
}
private LDAPSearchResults startSearchForModifiedCertificateRecords()
- throws EBaseException {
+ throws EBaseException {
CMS.debug("startSearchForModifiedCertificateRecords");
LDAPSearchResults r = null;
IDBSSession s = mDBService.createSession();
@@ -1799,9 +1815,9 @@ public class CertificateRepository extends Repository
r = s.persistentSearch(getDN(), filter, null);
CMS.debug("startSearchForModifiedCertificateRecords persistentSearch started");
} catch (Exception e) {
- CMS.debug("startSearchForModifiedCertificateRecords persistentSearch Exception="+e);
+ CMS.debug("startSearchForModifiedCertificateRecords persistentSearch Exception=" + e);
r = null;
- if (s != null)
+ if (s != null)
s.close();
}
return r;
@@ -1809,20 +1825,20 @@ public class CertificateRepository extends Repository
public void getModifications(LDAPEntry entry) {
if (entry != null) {
- CMS.debug("getModifications entry DN="+entry.getDN());
+ CMS.debug("getModifications entry DN=" + entry.getDN());
LDAPAttributeSet entryAttrs = entry.getAttributeSet();
ICertRecord certRec = null;
try {
- certRec = (ICertRecord)mDBService.getRegistry().createObject(entryAttrs);
+ certRec = (ICertRecord) mDBService.getRegistry().createObject(entryAttrs);
} catch (Exception e) {
}
if (certRec != null) {
String status = certRec.getStatus();
- CMS.debug("getModifications serialNumber="+certRec.getSerialNumber()+
- " status="+status);
+ CMS.debug("getModifications serialNumber=" + certRec.getSerialNumber() +
+ " status=" + status);
if (status != null && (status.equals(ICertRecord.STATUS_VALID) ||
- status.equals(ICertRecord.STATUS_REVOKED))) {
+ status.equals(ICertRecord.STATUS_REVOKED))) {
Enumeration<ICRLIssuingPoint> eIPs = mCRLIssuingPoints.elements();
@@ -1834,7 +1850,7 @@ public class CertificateRepository extends Repository
IRevocationInfo rInfo = certRec.getRevocationInfo();
if (rInfo != null) {
ip.addRevokedCert(certRec.getSerialNumber(),
- new RevokedCertImpl(certRec.getSerialNumber(),
+ new RevokedCertImpl(certRec.getSerialNumber(),
rInfo.getRevocationDate(),
rInfo.getCRLEntryExtensions()));
}
@@ -1851,16 +1867,16 @@ public class CertificateRepository extends Repository
}
}
-
/**
- * Checks if the presented certificate belongs to the repository
- * and is revoked.
- *
- * @param cert certificate to verify.
- * @return RevocationInfo if the presented certificate is revoked otherwise null.
+ * Checks if the presented certificate belongs to the repository and is
+ * revoked.
+ *
+ * @param cert certificate to verify.
+ * @return RevocationInfo if the presented certificate is revoked otherwise
+ * null.
*/
public RevocationInfo isCertificateRevoked(X509CertImpl cert)
- throws EBaseException {
+ throws EBaseException {
RevocationInfo info = null;
// 615932
@@ -1885,8 +1901,8 @@ public class CertificateRepository extends Repository
}
if (certEncoded != null &&
- repCertEncoded != null &&
- certEncoded.length == repCertEncoded.length) {
+ repCertEncoded != null &&
+ certEncoded.length == repCertEncoded.length) {
int i;
for (i = 0; i < certEncoded.length; i++) {
@@ -1905,15 +1921,14 @@ public class CertificateRepository extends Repository
}
public void shutdown() {
- //if (mCertStatusUpdateThread != null)
- // mCertStatusUpdateThread.destroy();
+ // if (mCertStatusUpdateThread != null)
+ // mCertStatusUpdateThread.destroy();
- //if (mRetrieveModificationsThread != null)
- // mRetrieveModificationsThread.destroy();
+ // if (mRetrieveModificationsThread != null)
+ // mRetrieveModificationsThread.destroy();
}
}
-
class CertStatusUpdateThread extends Thread {
CertificateRepository _cr = null;
IRepository _rr = null;
@@ -1922,7 +1937,7 @@ class CertStatusUpdateThread extends Thread {
CertStatusUpdateThread(CertificateRepository cr, IRepository rr, String name) {
super(name);
CMS.debug("new CertStatusUpdateThread");
- //setName(name);
+ // setName(name);
_cr = cr;
_rr = rr;
@@ -1965,7 +1980,6 @@ class CertStatusUpdateThread extends Thread {
}
}
-
class RetrieveModificationsThread extends Thread {
CertificateRepository _cr = null;
LDAPSearchResults _results = null;
@@ -1973,7 +1987,7 @@ class RetrieveModificationsThread extends Thread {
RetrieveModificationsThread(CertificateRepository cr, String name) {
super(name);
CMS.debug("new RetrieveModificationsThread");
- //setName(name);
+ // setName(name);
_cr = cr;
}
@@ -1992,7 +2006,7 @@ class RetrieveModificationsThread extends Thread {
_cr.getModifications(entry);
}
} catch (LDAPException e) {
- CMS.debug("LDAPException: "+e.toString());
+ CMS.debug("LDAPException: " + e.toString());
}
} else {
CMS.debug("_results are null");
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/DBRegistry.java b/pki/base/common/src/com/netscape/cmscore/dbs/DBRegistry.java
index 65b1039d..21974918 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/DBRegistry.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/DBRegistry.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
@@ -37,22 +36,18 @@ import com.netscape.certsrv.dbs.IDBObj;
import com.netscape.certsrv.dbs.IDBRegistry;
import com.netscape.certsrv.dbs.IFilterConverter;
import com.netscape.certsrv.logging.ILogger;
-
/**
- * A class represents a registry where all the
- * schema (object classes and attribute) information
- * is stored.
- *
- * Attribute mappers can be registered with this
- * registry.
- *
- * Given the schema information stored, this registry
- * has knowledge to convert a Java object into a
- * LDAPAttributeSet or vice versa.
- *
+ * A class represents a registry where all the schema (object classes and
+ * attribute) information is stored.
+ *
+ * Attribute mappers can be registered with this registry.
+ *
+ * Given the schema information stored, this registry has knowledge to convert a
+ * Java object into a LDAPAttributeSet or vice versa.
+ *
* @author thomask
- * @version $Revision$, $Date$
+ * @version $Revision$, $Date$
*/
public class DBRegistry implements IDBRegistry, ISubsystem {
@@ -79,25 +74,24 @@ public class DBRegistry implements IDBRegistry, ISubsystem {
}
/**
- * Sets subsystem identifier. This is an internal
- * subsystem, and is not loadable.
+ * Sets subsystem identifier. This is an internal subsystem, and is not
+ * loadable.
*/
public void setId(String id) throws EBaseException {
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_OPERATION"));
}
/**
- * Initializes the internal registery. Connects to the
- * data source, and create a pool of connection of which
- * applications can use. Optionally, check the integrity
- * of the database.
+ * Initializes the internal registery. Connects to the data source, and
+ * create a pool of connection of which applications can use. Optionally,
+ * check the integrity of the database.
*/
- public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ public void init(ISubsystem owner, IConfigStore config)
+ throws EBaseException {
mConfig = config;
mConverter = new LdapFilterConverter(mAttrufNames);
}
-
+
/**
* Retrieves configuration store.
*/
@@ -128,24 +122,27 @@ public class DBRegistry implements IDBRegistry, ISubsystem {
* Registers object class.
*/
public void registerObjectClass(String className, String ldapNames[])
- throws EDBException {
+ throws EDBException {
try {
Class<?> c = Class.forName(className);
mOCclassNames.put(className, ldapNames);
mOCldapNames.put(sortAndConcate(
- ldapNames).toLowerCase(),
- new NameAndObject(className, c));
+ ldapNames).toLowerCase(),
+ new NameAndObject(className, c));
} catch (ClassNotFoundException e) {
- /*LogDoc
- *
+ /*
+ * LogDoc
+ *
* @phase db startup
+ *
* @reason failed to register object class
+ *
* @message DBRegistry: <exception thrown>
*/
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_DB,
- ILogger.LL_FAILURE, CMS.getLogMessage("OPERATION_ERROR", e.toString()));
+ ILogger.LL_FAILURE, CMS.getLogMessage("OPERATION_ERROR", e.toString()));
throw new EDBException(
CMS.getUserMessage("CMS_DBS_INVALID_CLASS_NAME", className));
}
@@ -161,8 +158,8 @@ public class DBRegistry implements IDBRegistry, ISubsystem {
/**
* Registers attribute mapper.
*/
- public void registerAttribute(String ufName, IDBAttrMapper mapper)
- throws EDBException {
+ public void registerAttribute(String ufName, IDBAttrMapper mapper)
+ throws EDBException {
// should not allows 'objectclass' as attribute; it has
// special meaning
mAttrufNames.put(ufName.toLowerCase(), mapper);
@@ -180,9 +177,9 @@ public class DBRegistry implements IDBRegistry, ISubsystem {
}
/**
- * Creates LDAP-based search filters with help of
- * registered mappers.
- * Parses filter from filter string specified in RFC1558.
+ * Creates LDAP-based search filters with help of registered mappers. Parses
+ * filter from filter string specified in RFC1558.
+ *
* <pre>
* <filter> ::= '(' <filtercomp> ')'
* <filtercomp> ::= <and> | <or> | <not> | <item>
@@ -209,37 +206,37 @@ public class DBRegistry implements IDBRegistry, ISubsystem {
return getFilter(filter, mConverter);
}
- public String getFilter(String filter, IFilterConverter c)
- throws EBaseException {
+ public String getFilter(String filter, IFilterConverter c)
+ throws EBaseException {
String f = filter;
f = f.trim();
if (f.startsWith("(") && f.endsWith(")")) {
- return "(" + getFilterComp(f.substring(1,
+ return "(" + getFilterComp(f.substring(1,
f.length() - 1), c) + ")";
} else {
return getFilterComp(filter, c);
}
}
- private String getFilterComp(String f, IFilterConverter c)
- throws EBaseException {
+ private String getFilterComp(String f, IFilterConverter c)
+ throws EBaseException {
f = f.trim();
- if (f.startsWith("&")) { // AND operation
- return "&" + getFilterList(f.substring(1,
+ if (f.startsWith("&")) { // AND operation
+ return "&" + getFilterList(f.substring(1,
f.length()), c);
} else if (f.startsWith("|")) { // OR operation
- return "|" + getFilterList(f.substring(1,
+ return "|" + getFilterList(f.substring(1,
f.length()), c);
} else if (f.startsWith("!")) { // NOT operation
return "!" + getFilter(f.substring(1, f.length()), c);
- } else { // item
+ } else { // item
return getFilterItem(f, c);
}
}
-
- private String getFilterList(String f, IFilterConverter c)
- throws EBaseException {
+
+ private String getFilterList(String f, IFilterConverter c)
+ throws EBaseException {
f = f.trim();
int level = 0;
int start = 0;
@@ -274,8 +271,8 @@ public class DBRegistry implements IDBRegistry, ISubsystem {
/**
* So, here we need to separate item into name, op, value.
*/
- private String getFilterItem(String f, IFilterConverter c)
- throws EBaseException {
+ private String getFilterItem(String f, IFilterConverter c)
+ throws EBaseException {
f = f.trim();
int idx = f.indexOf('=');
@@ -318,7 +315,7 @@ public class DBRegistry implements IDBRegistry, ISubsystem {
if (value.indexOf('*') == -1) {
if (type.equals("objectclass")) {
String ldapNames[] = (String[])
- mOCclassNames.get(value);
+ mOCclassNames.get(value);
if (ldapNames == null)
throw new EDBException(
@@ -326,8 +323,8 @@ public class DBRegistry implements IDBRegistry, ISubsystem {
String filter = "";
for (int g = 0; g < ldapNames.length; g++) {
- filter += "(objectclass=" +
- ldapNames[g] + ")";
+ filter += "(objectclass=" +
+ ldapNames[g] + ")";
}
return "&" + filter;
} else {
@@ -341,27 +338,26 @@ public class DBRegistry implements IDBRegistry, ISubsystem {
/**
* Maps object into LDAP attribute set.
*/
- public void mapObject(IDBObj parent, String name, Object obj,
- LDAPAttributeSet attrs) throws EBaseException {
+ public void mapObject(IDBObj parent, String name, Object obj,
+ LDAPAttributeSet attrs) throws EBaseException {
IDBAttrMapper mapper = (IDBAttrMapper) mAttrufNames.get(
name.toLowerCase());
if (mapper == null) {
return; // no mapper found, just skip this attribute
- }
+ }
mapper.mapObjectToLDAPAttributeSet(parent, name, obj, attrs);
}
/**
- * Retrieves a list of LDAP attributes that are associated
- * with the given attributes.
- * This method is used for searches, to map the database attributes
- * to LDAP attributes.
+ * Retrieves a list of LDAP attributes that are associated with the given
+ * attributes. This method is used for searches, to map the database
+ * attributes to LDAP attributes.
*/
- public String[] getLDAPAttributes(String attrs[])
- throws EBaseException {
+ public String[] getLDAPAttributes(String attrs[])
+ throws EBaseException {
IDBAttrMapper mapper;
-
+
if (attrs == null)
return null;
Vector<String> v = new Vector<String>();
@@ -391,10 +387,9 @@ public class DBRegistry implements IDBRegistry, ISubsystem {
} else {
IDBDynAttrMapper matchingDynAttrMapper = null;
// check if a dynamic mapper can handle the attribute
- for (Iterator<IDBDynAttrMapper> dynMapperIter = mDynAttrMappers.iterator();
- dynMapperIter.hasNext();) {
+ for (Iterator<IDBDynAttrMapper> dynMapperIter = mDynAttrMappers.iterator(); dynMapperIter.hasNext();) {
IDBDynAttrMapper dynAttrMapper =
- (IDBDynAttrMapper)dynMapperIter.next();
+ (IDBDynAttrMapper) dynMapperIter.next();
if (dynAttrMapper.supportsLDAPAttributeName(attrs[i])) {
matchingDynAttrMapper = dynAttrMapper;
break;
@@ -403,14 +398,17 @@ public class DBRegistry implements IDBRegistry, ISubsystem {
if (matchingDynAttrMapper != null) {
v.addElement(attrs[i]);
} else {
- /*LogDoc
- *
+ /*
+ * LogDoc
+ *
* @phase retrieve ldap attr
+ *
* @reason failed to get registered object class
+ *
* @message DBRegistry: <attr> is not registered
*/
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_DB,
- ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_DBS_ATTR_NOT_REGISTER", attrs[i]));
+ ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_DBS_ATTR_NOT_REGISTER", attrs[i]));
throw new EDBException(CMS.getLogMessage("CMSCORE_DBS_ATTR_NOT_REGISTER", attrs[i]));
}
}
@@ -427,8 +425,8 @@ public class DBRegistry implements IDBRegistry, ISubsystem {
/**
* Creates attribute set from object.
*/
- public LDAPAttributeSet createLDAPAttributeSet(IDBObj obj)
- throws EBaseException {
+ public LDAPAttributeSet createLDAPAttributeSet(IDBObj obj)
+ throws EBaseException {
Enumeration<String> e = obj.getSerializableAttrNames();
LDAPAttributeSet attrs = new LDAPAttributeSet();
@@ -453,17 +451,17 @@ public class DBRegistry implements IDBRegistry, ISubsystem {
* Creates object from attribute set.
*/
public IDBObj createObject(LDAPAttributeSet attrs)
- throws EBaseException {
+ throws EBaseException {
// map object class attribute to object
LDAPAttribute attr = attrs.getAttribute("objectclass");
- //CMS.debug("createObject: attrs " + attrs.toString());
+ // CMS.debug("createObject: attrs " + attrs.toString());
attrs.remove("objectclass");
// sort the object class values
@SuppressWarnings("unchecked")
- Enumeration<String> vals = attr.getStringValues();
+ Enumeration<String> vals = attr.getStringValues();
Vector<String> v = new Vector<String>();
while (vals.hasMoreElements()) {
@@ -488,27 +486,30 @@ public class DBRegistry implements IDBRegistry, ISubsystem {
while (ee.hasMoreElements()) {
String oname = (String) ee.nextElement();
IDBAttrMapper mapper = (IDBAttrMapper)
- mAttrufNames.get(
- oname.toLowerCase());
+ mAttrufNames.get(
+ oname.toLowerCase());
if (mapper == null) {
throw new EDBException(
CMS.getUserMessage("CMS_DBS_NO_MAPPER_FOUND", oname));
}
- mapper.mapLDAPAttributeSetToObject(attrs,
- oname, obj);
+ mapper.mapLDAPAttributeSetToObject(attrs,
+ oname, obj);
}
return obj;
} catch (Exception e) {
- /*LogDoc
- *
+ /*
+ * LogDoc
+ *
* @phase create ldap attr
+ *
* @reason failed to create object class
+ *
* @message DBRegistry: <attr> is not registered
*/
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_DB,
- ILogger.LL_FAILURE, CMS.getLogMessage("OPERATION_ERROR", e.toString()));
+ ILogger.LL_FAILURE, CMS.getLogMessage("OPERATION_ERROR", e.toString()));
throw new EDBException(CMS.getUserMessage("CMS_DBS_INVALID_ATTRS"));
}
}
@@ -543,7 +544,6 @@ public class DBRegistry implements IDBRegistry, ISubsystem {
}
}
-
/**
* Just a convenient container class.
*/
@@ -556,7 +556,7 @@ class NameAndObject {
mN = name;
mO = o;
}
-
+
public String getName() {
return mN;
}
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/DBSSession.java b/pki/base/common/src/com/netscape/cmscore/dbs/DBSSession.java
index 5b081d6c..b2a3b17f 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/DBSSession.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/DBSSession.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.util.Enumeration;
import netscape.ldap.LDAPAttribute;
@@ -47,14 +46,12 @@ import com.netscape.certsrv.dbs.Modification;
import com.netscape.certsrv.dbs.ModificationSet;
import com.netscape.certsrv.logging.ILogger;
-
/**
- * A class represents the database session. Operations
- * can be performed with a session.
- *
- * Transaction and Caching support can be integrated
- * into session.
- *
+ * A class represents the database session. Operations can be performed with a
+ * session.
+ *
+ * Transaction and Caching support can be integrated into session.
+ *
* @author thomask
* @version $Revision$, $Date$
*/
@@ -66,7 +63,7 @@ public class DBSSession implements IDBSSession {
/**
* Constructs a database session.
- *
+ *
* @param system the database subsytem
* @param c the ldap connection
*/
@@ -75,7 +72,7 @@ public class DBSSession implements IDBSSession {
mConn = c;
try {
// no limit
- mConn.setOption(LDAPv2.SIZELIMIT, Integer.valueOf(0));
+ mConn.setOption(LDAPv2.SIZELIMIT, Integer.valueOf(0));
} catch (LDAPException e) {
}
}
@@ -97,28 +94,31 @@ public class DBSSession implements IDBSSession {
/**
* Adds object to backend database. For example,
+ *
* <PRE>
- * session.add("cn=123459,o=certificate repository,o=airius.com",
- * certRec);
+ * session.add(&quot;cn=123459,o=certificate repository,o=airius.com&quot;,
+ * certRec);
* </PRE>
- *
+ *
* @param name the name of the ldap entry
* @param obj the DBobj that can be mapped to ldap attrubute set
*/
public void add(String name, IDBObj obj) throws EBaseException {
try {
LDAPAttributeSet attrs = mDBSystem.getRegistry(
- ).createLDAPAttributeSet(obj);
+ ).createLDAPAttributeSet(obj);
LDAPEntry e = new LDAPEntry(name, attrs);
- /*LogDoc
- *
+ /*
+ * LogDoc
+ *
* @phase local ldap add
+ *
* @message DBSSession: begin LDAP add <entry>
*/
mConn.add(e);
} catch (LDAPException e) {
- if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE)
+ if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE)
throw new EDBNotAvailException(
CMS.getUserMessage("CMS_DBS_INTERNAL_DIR_UNAVAILABLE"));
throw new EDBException(CMS.getUserMessage("CMS_DBS_LDAP_OP_FAILURE",
@@ -127,9 +127,8 @@ public class DBSSession implements IDBSSession {
}
/**
- * Reads an object from the database.
- * all attributes will be returned
- *
+ * Reads an object from the database. all attributes will be returned
+ *
* @param name the name of the ldap entry
*/
public IDBObj read(String name) throws EBaseException {
@@ -137,14 +136,14 @@ public class DBSSession implements IDBSSession {
}
/**
- * Reads an object from the database, and only populates
- * the selected attributes.
- *
+ * Reads an object from the database, and only populates the selected
+ * attributes.
+ *
* @param name the name of the ldap entry
* @param attrs the attributes to be selected
*/
public IDBObj read(String name, String attrs[])
- throws EBaseException {
+ throws EBaseException {
try {
String ldapattrs[] = null;
@@ -153,9 +152,11 @@ public class DBSSession implements IDBSSession {
).getLDAPAttributes(attrs);
}
- /*LogDoc
- *
+ /*
+ * LogDoc
+ *
* @phase local ldap read
+ *
* @message DBSSession: begin LDAP read <entry>
*/
LDAPSearchResults res = mConn.search(name,
@@ -167,16 +168,18 @@ public class DBSSession implements IDBSSession {
entry.getAttributeSet());
} catch (LDAPException e) {
- /*LogDoc
- *
+ /*
+ * LogDoc
+ *
* @phase local ldap read
+ *
* @message DBSSession: <exception thrown>
*/
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_DB, ILogger.LL_INFO, "DBSSession: " + e.toString());
- if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE)
+ if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE)
throw new EDBNotAvailException(
CMS.getUserMessage("CMS_DBS_INTERNAL_DIR_UNAVAILABLE"));
- if (e.getLDAPResultCode() == LDAPException.NO_SUCH_OBJECT)
+ if (e.getLDAPResultCode() == LDAPException.NO_SUCH_OBJECT)
throw new EDBRecordNotFoundException(
CMS.getUserMessage("CMS_DBS_RECORD_NOT_FOUND"));
throw new EDBException(CMS.getUserMessage("CMS_DBS_LDAP_OP_FAILURE",
@@ -191,7 +194,7 @@ public class DBSSession implements IDBSSession {
try {
mConn.delete(name);
} catch (LDAPException e) {
- if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE)
+ if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE)
throw new EDBNotAvailException(
CMS.getUserMessage("CMS_DBS_INTERNAL_DIR_UNAVAILABLE"));
throw new EDBException(CMS.getUserMessage("CMS_DBS_LDAP_OP_FAILURE",
@@ -203,36 +206,38 @@ public class DBSSession implements IDBSSession {
* Modify an object in the database.
*/
public void modify(String name, ModificationSet mods)
- throws EBaseException {
+ throws EBaseException {
try {
LDAPModificationSet ldapMods = new
- LDAPModificationSet();
+ LDAPModificationSet();
Enumeration<?> e = mods.getModifications();
while (e.hasMoreElements()) {
Modification mod = (Modification)
- e.nextElement();
+ e.nextElement();
LDAPAttributeSet attrs = new LDAPAttributeSet();
mDBSystem.getRegistry().mapObject(null,
- mod.getName(), mod.getValue(), attrs);
+ mod.getName(), mod.getValue(), attrs);
Enumeration<?> e0 = attrs.getAttributes();
while (e0.hasMoreElements()) {
ldapMods.add(toLdapModOp(mod.getOp()),
- (LDAPAttribute)
- e0.nextElement());
+ (LDAPAttribute)
+ e0.nextElement());
}
}
- /*LogDoc
- *
+ /*
+ * LogDoc
+ *
* @phase local ldap add
+ *
* @message DBSSession: begin LDAP modify <entry>
*/
mConn.modify(name, ldapMods);
} catch (LDAPException e) {
- if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE)
+ if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE)
throw new EDBNotAvailException(
CMS.getUserMessage("CMS_DBS_INTERNAL_DIR_UNAVAILABLE"));
throw new EDBException(CMS.getUserMessage("CMS_DBS_LDAP_OP_FAILURE",
@@ -256,20 +261,19 @@ public class DBSSession implements IDBSSession {
}
/**
- * Searchs for a list of objects that match the
- * filter.
+ * Searchs for a list of objects that match the filter.
*/
public IDBSearchResults search(String base, String filter)
- throws EBaseException {
+ throws EBaseException {
return search(base, filter, null);
}
public IDBSearchResults search(String base, String filter, int maxSize)
- throws EBaseException {
+ throws EBaseException {
try {
String ldapattrs[] = null;
String ldapfilter =
- mDBSystem.getRegistry().getFilter(filter);
+ mDBSystem.getRegistry().getFilter(filter);
LDAPSearchConstraints cons = new LDAPSearchConstraints();
@@ -281,22 +285,22 @@ public class DBSSession implements IDBSSession {
return new DBSearchResults(mDBSystem.getRegistry(),
res);
} catch (LDAPException e) {
- if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE)
+ if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE)
throw new EDBNotAvailException(
CMS.getUserMessage("CMS_DBS_INTERNAL_DIR_UNAVAILABLE"));
- // XXX error handling, should not raise exception if
- // entry not found
+ // XXX error handling, should not raise exception if
+ // entry not found
throw new EDBException(CMS.getUserMessage("CMS_DBS_LDAP_OP_FAILURE",
e.toString()));
}
}
public IDBSearchResults search(String base, String filter, int maxSize, int timeLimit)
- throws EBaseException {
+ throws EBaseException {
try {
String ldapattrs[] = null;
String ldapfilter =
- mDBSystem.getRegistry().getFilter(filter);
+ mDBSystem.getRegistry().getFilter(filter);
LDAPSearchConstraints cons = new LDAPSearchConstraints();
@@ -309,22 +313,21 @@ public class DBSSession implements IDBSSession {
return new DBSearchResults(mDBSystem.getRegistry(),
res);
} catch (LDAPException e) {
- if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE)
+ if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE)
throw new EDBNotAvailException(
CMS.getUserMessage("CMS_DBS_INTERNAL_DIR_UNAVAILABLE"));
- // XXX error handling, should not raise exception if
- // entry not found
+ // XXX error handling, should not raise exception if
+ // entry not found
throw new EDBException(CMS.getUserMessage("CMS_DBS_LDAP_OP_FAILURE",
e.toString()));
}
}
/**
- * Retrieves a list of object that satifies the given
- * filter.
+ * Retrieves a list of object that satifies the given filter.
*/
public IDBSearchResults search(String base, String filter,
- String attrs[]) throws EBaseException {
+ String attrs[]) throws EBaseException {
try {
String ldapattrs[] = null;
@@ -333,35 +336,37 @@ public class DBSSession implements IDBSSession {
).getLDAPAttributes(attrs);
}
String ldapfilter =
- mDBSystem.getRegistry().getFilter(filter);
+ mDBSystem.getRegistry().getFilter(filter);
- /*LogDoc
- *
+ /*
+ * LogDoc
+ *
* @phase local ldap add
+ *
* @message DBSSession: begin LDAP search <filter>
*/
LDAPSearchConstraints cons = new LDAPSearchConstraints();
- cons.setMaxResults(0);
-
+ cons.setMaxResults(0);
+
LDAPSearchResults res = mConn.search(base,
LDAPv2.SCOPE_ONE, ldapfilter, ldapattrs, false, cons);
return new DBSearchResults(mDBSystem.getRegistry(),
res);
} catch (LDAPException e) {
- if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE)
+ if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE)
throw new EDBNotAvailException(
CMS.getUserMessage("CMS_DBS_INTERNAL_DIR_UNAVAILABLE"));
- // XXX error handling, should not raise exception if
- // entry not found
+ // XXX error handling, should not raise exception if
+ // entry not found
throw new EDBException(CMS.getUserMessage("CMS_DBS_LDAP_OP_FAILURE",
e.toString()));
}
}
public LDAPSearchResults persistentSearch(String base, String filter, String attrs[])
- throws EBaseException {
+ throws EBaseException {
try {
String ldapattrs[] = null;
if (attrs != null) {
@@ -369,11 +374,11 @@ public class DBSSession implements IDBSSession {
).getLDAPAttributes(attrs);
}
String ldapfilter =
- mDBSystem.getRegistry().getFilter(filter);
+ mDBSystem.getRegistry().getFilter(filter);
- Integer version = (Integer)(mConn.getOption(LDAPv2.PROTOCOL_VERSION));
+ Integer version = (Integer) (mConn.getOption(LDAPv2.PROTOCOL_VERSION));
- // Only version 3 protocol supports persistent search.
+ // Only version 3 protocol supports persistent search.
if (version.intValue() == 2) {
mConn.setOption(LDAPv2.PROTOCOL_VERSION, Integer.valueOf(3));
}
@@ -384,22 +389,22 @@ public class DBSSession implements IDBSSession {
boolean returnControls = true;
boolean isCritical = true;
LDAPPersistSearchControl persistCtrl = new
- LDAPPersistSearchControl( op, changesOnly,
- returnControls, isCritical );
+ LDAPPersistSearchControl(op, changesOnly,
+ returnControls, isCritical);
LDAPSearchConstraints cons = new LDAPSearchConstraints();
cons.setBatchSize(0);
- cons.setServerControls( persistCtrl );
+ cons.setServerControls(persistCtrl);
LDAPSearchResults res = mConn.search(base,
LDAPv2.SCOPE_ONE, ldapfilter, ldapattrs, false, cons);
return res;
} catch (LDAPException e) {
- if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE)
+ if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE)
throw new EDBNotAvailException(
CMS.getUserMessage("CMS_DBS_INTERNAL_DIR_UNAVAILABLE"));
- // XXX error handling, should not raise exception if
- // entry not found
+ // XXX error handling, should not raise exception if
+ // entry not found
throw new EDBException(CMS.getUserMessage("CMS_DBS_LDAP_OP_FAILURE",
e.toString()));
}
@@ -409,7 +414,7 @@ public class DBSSession implements IDBSSession {
* Retrieves a list of objects.
*/
public <T> IDBVirtualList<T> createVirtualList(String base, String filter,
- String attrs[]) throws EBaseException {
+ String attrs[]) throws EBaseException {
return new DBVirtualList<T>(mDBSystem.getRegistry(), mConn, base,
filter, attrs);
}
@@ -418,7 +423,7 @@ public class DBSSession implements IDBSSession {
* Retrieves a list of objects.
*/
public <T> IDBVirtualList<T> createVirtualList(String base, String filter,
- String attrs[], String sortKey[]) throws EBaseException {
+ String attrs[], String sortKey[]) throws EBaseException {
return new DBVirtualList<T>(mDBSystem.getRegistry(), mConn, base,
filter, attrs, sortKey);
}
@@ -427,7 +432,7 @@ public class DBSSession implements IDBSSession {
* Retrieves a list of objects.
*/
public IDBVirtualList<?> createVirtualList(String base, String filter,
- String attrs[], String sortKey) throws EBaseException {
+ String attrs[], String sortKey) throws EBaseException {
return new DBVirtualList<Object>(mDBSystem.getRegistry(), mConn, base,
filter, attrs, sortKey);
}
@@ -436,7 +441,7 @@ public class DBSSession implements IDBSSession {
* Retrieves a list of objects.
*/
public IDBVirtualList<?> createVirtualList(String base, String filter,
- String attrs[], String sortKey[], int pageSize) throws EBaseException {
+ String attrs[], String sortKey[], int pageSize) throws EBaseException {
return new DBVirtualList<Object>(mDBSystem.getRegistry(), mConn, base,
filter, attrs, sortKey, pageSize);
}
@@ -445,21 +450,21 @@ public class DBSSession implements IDBSSession {
* Retrieves a list of objects.
*/
public IDBVirtualList<?> createVirtualList(String base, String filter,
- String attrs[], String sortKey, int pageSize) throws EBaseException {
+ String attrs[], String sortKey, int pageSize) throws EBaseException {
return new DBVirtualList<Object>(mDBSystem.getRegistry(), mConn, base,
filter, attrs, sortKey, pageSize);
}
public IDBVirtualList<?> createVirtualList(String base, String filter,
- String attrs[], String startFrom, String sortKey, int pageSize) throws EBaseException {
+ String attrs[], String startFrom, String sortKey, int pageSize) throws EBaseException {
return new DBVirtualList<Object>(mDBSystem.getRegistry(), mConn, base,
filter, attrs, startFrom, sortKey, pageSize);
}
/**
- * Releases object to this interface. This allows us to
- * use memory more efficiently.
+ * Releases object to this interface. This allows us to use memory more
+ * efficiently.
*/
public void release(Object obj) {
// not implemented
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/DBSUtil.java b/pki/base/common/src/com/netscape/cmscore/dbs/DBSUtil.java
index 123fb847..e18906ff 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/DBSUtil.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/DBSUtil.java
@@ -17,16 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
-
-
/**
- * A class represents ann attribute mapper that maps
- * a Java BigInteger object into LDAP attribute,
- * and vice versa.
- *
+ * A class represents ann attribute mapper that maps a Java BigInteger object
+ * into LDAP attribute, and vice versa.
+ *
* @author thomask
- * @version $Revision$, $Date$
+ * @version $Revision$, $Date$
*/
public class DBSUtil {
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/DBSearchResults.java b/pki/base/common/src/com/netscape/cmscore/dbs/DBSearchResults.java
index 8b5098dc..1fadbbf5 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/DBSearchResults.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/DBSearchResults.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.util.Enumeration;
import netscape.ldap.LDAPEntry;
@@ -27,15 +26,13 @@ import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.dbs.IDBRegistry;
import com.netscape.certsrv.dbs.IDBSearchResults;
import com.netscape.certsrv.logging.ILogger;
-
/**
- * A class represents the search results. A search
- * results object contain a enumeration of
- * Java objects that are just read from the database.
- *
+ * A class represents the search results. A search results object contain a
+ * enumeration of Java objects that are just read from the database.
+ *
* @author thomask
- * @version $Revision$, $Date$
+ * @version $Revision$, $Date$
*/
public class DBSearchResults implements IDBSearchResults {
@@ -71,24 +68,27 @@ public class DBSearchResults implements IDBSearchResults {
entry = (LDAPEntry) o;
return mRegistry.createObject(entry.getAttributeSet());
} else {
- if (o instanceof LDAPException)
+ if (o instanceof LDAPException)
;
- // doing nothing because the last object in the search
- // results is always LDAPException
+ // doing nothing because the last object in the search
+ // results is always LDAPException
else
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_DB,
- ILogger.LL_FAILURE, "DBSearchResults: result format error class=" + o.getClass().getName());
+ ILogger.LL_FAILURE, "DBSearchResults: result format error class=" + o.getClass().getName());
}
} catch (Exception e) {
- /*LogDoc
- *
+ /*
+ * LogDoc
+ *
* @phase local ldap search
+ *
* @reason failed to get next element
+ *
* @message DBSearchResults: <exception thrown>
*/
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_DB,
- ILogger.LL_FAILURE, "DBSearchResults: " + e.toString());
+ ILogger.LL_FAILURE, "DBSearchResults: " + e.toString());
}
return null;
}
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/DBSubsystem.java b/pki/base/common/src/com/netscape/cmscore/dbs/DBSubsystem.java
index 3208a23d..16fbecbc 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/DBSubsystem.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/DBSubsystem.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.math.BigInteger;
import java.util.Hashtable;
@@ -53,17 +52,15 @@ import com.netscape.cmscore.ldapconn.LdapAuthInfo;
import com.netscape.cmscore.ldapconn.LdapBoundConnFactory;
import com.netscape.cmscore.ldapconn.LdapConnInfo;
-
/**
- * A class represents the database subsystem that manages
- * the backend data storage.
- *
- * This subsystem maintains multiple sessions that allows
- * operations to be performed, and provide a registry
- * where all the schema information is stored.
- *
+ * A class represents the database subsystem that manages the backend data
+ * storage.
+ *
+ * This subsystem maintains multiple sessions that allows operations to be
+ * performed, and provide a registry where all the schema information is stored.
+ *
* @author thomask
- * @version $Revision$, $Date$
+ * @version $Revision$, $Date$
*/
public class DBSubsystem implements IDBSubsystem {
@@ -98,40 +95,40 @@ public class DBSubsystem implements IDBSubsystem {
private static final String KR_DN = "ou=keyRepository, ou=kra";
private static final String KRA_REQUESTS_DN = "ou=kra, ou=requests";
private static final String REPLICA_DN = "ou=replica";
- private static final String PROP_ENABLE_SERIAL_NUMBER_RECOVERY =
- "enableSerialNumberRecovery";
+ private static final String PROP_ENABLE_SERIAL_NUMBER_RECOVERY =
+ "enableSerialNumberRecovery";
// This value is only equal to the next Serial number that the CA's
// going to issue when cms just start up or it's just set from console.
// It doesn't record the next serial number at other time when cms's
// runing not to increase overhead when issuing certs.
- private static final String PROP_NEXT_SERIAL_NUMBER =
- "nextSerialNumber";
- private static final String PROP_MIN_SERIAL_NUMBER="beginSerialNumber";
+ private static final String PROP_NEXT_SERIAL_NUMBER =
+ "nextSerialNumber";
+ private static final String PROP_MIN_SERIAL_NUMBER = "beginSerialNumber";
private static final String PROP_MAX_SERIAL_NUMBER = "endSerialNumber";
- private static final String PROP_NEXT_MIN_SERIAL_NUMBER="nextBeginSerialNumber";
- private static final String PROP_NEXT_MAX_SERIAL_NUMBER ="nextEndSerialNumber";
- private static final String PROP_SERIAL_LOW_WATER_MARK="serialLowWaterMark";
- private static final String PROP_SERIAL_INCREMENT="serialIncrement";
- private static final String PROP_SERIAL_BASEDN="serialDN";
- private static final String PROP_SERIAL_RANGE_DN="serialRangeDN";
-
- private static final String PROP_MIN_REQUEST_NUMBER="beginRequestNumber";
- private static final String PROP_MAX_REQUEST_NUMBER="endRequestNumber";
- private static final String PROP_NEXT_MIN_REQUEST_NUMBER="nextBeginRequestNumber";
- private static final String PROP_NEXT_MAX_REQUEST_NUMBER="nextEndRequestNumber";
- private static final String PROP_REQUEST_LOW_WATER_MARK="requestLowWaterMark";
- private static final String PROP_REQUEST_INCREMENT="requestIncrement";
- private static final String PROP_REQUEST_BASEDN="requestDN";
- private static final String PROP_REQUEST_RANGE_DN="requestRangeDN";
-
- private static final String PROP_MIN_REPLICA_NUMBER="beginReplicaNumber";
+ private static final String PROP_NEXT_MIN_SERIAL_NUMBER = "nextBeginSerialNumber";
+ private static final String PROP_NEXT_MAX_SERIAL_NUMBER = "nextEndSerialNumber";
+ private static final String PROP_SERIAL_LOW_WATER_MARK = "serialLowWaterMark";
+ private static final String PROP_SERIAL_INCREMENT = "serialIncrement";
+ private static final String PROP_SERIAL_BASEDN = "serialDN";
+ private static final String PROP_SERIAL_RANGE_DN = "serialRangeDN";
+
+ private static final String PROP_MIN_REQUEST_NUMBER = "beginRequestNumber";
+ private static final String PROP_MAX_REQUEST_NUMBER = "endRequestNumber";
+ private static final String PROP_NEXT_MIN_REQUEST_NUMBER = "nextBeginRequestNumber";
+ private static final String PROP_NEXT_MAX_REQUEST_NUMBER = "nextEndRequestNumber";
+ private static final String PROP_REQUEST_LOW_WATER_MARK = "requestLowWaterMark";
+ private static final String PROP_REQUEST_INCREMENT = "requestIncrement";
+ private static final String PROP_REQUEST_BASEDN = "requestDN";
+ private static final String PROP_REQUEST_RANGE_DN = "requestRangeDN";
+
+ private static final String PROP_MIN_REPLICA_NUMBER = "beginReplicaNumber";
private static final String PROP_MAX_REPLICA_NUMBER = "endReplicaNumber";
- private static final String PROP_NEXT_MIN_REPLICA_NUMBER="nextBeginReplicaNumber";
- private static final String PROP_NEXT_MAX_REPLICA_NUMBER ="nextEndReplicaNumber";
- private static final String PROP_REPLICA_LOW_WATER_MARK="replicaLowWaterMark";
- private static final String PROP_REPLICA_INCREMENT="replicaIncrement";
- private static final String PROP_REPLICA_BASEDN="replicaDN";
- private static final String PROP_REPLICA_RANGE_DN="replicaRangeDN";
+ private static final String PROP_NEXT_MIN_REPLICA_NUMBER = "nextBeginReplicaNumber";
+ private static final String PROP_NEXT_MAX_REPLICA_NUMBER = "nextEndReplicaNumber";
+ private static final String PROP_REPLICA_LOW_WATER_MARK = "replicaLowWaterMark";
+ private static final String PROP_REPLICA_INCREMENT = "replicaIncrement";
+ private static final String PROP_REPLICA_BASEDN = "replicaDN";
+ private static final String PROP_REPLICA_RANGE_DN = "replicaRangeDN";
private static final String PROP_INFINITE_SERIAL_NUMBER = "1000000000";
private static final String PROP_INFINITE_REQUEST_NUMBER = "1000000000";
@@ -140,27 +137,27 @@ public class DBSubsystem implements IDBSubsystem {
private static final String PROP_LDAP = "ldap";
private static final String PROP_NEXT_RANGE = "nextRange";
private static final String PROP_ENABLE_SERIAL_MGMT = "enableSerialManagement";
-
+
// hash keys
- private static final String NAME="name";
- private static final String PROP_MIN="min";
- private static final String PROP_MIN_NAME="min_name";
+ private static final String NAME = "name";
+ private static final String PROP_MIN = "min";
+ private static final String PROP_MIN_NAME = "min_name";
private static final String PROP_MAX = "max";
private static final String PROP_MAX_NAME = "max_name";
- private static final String PROP_NEXT_MIN="next_min";
- private static final String PROP_NEXT_MIN_NAME="next_min_name";
+ private static final String PROP_NEXT_MIN = "next_min";
+ private static final String PROP_NEXT_MIN_NAME = "next_min_name";
private static final String PROP_NEXT_MAX = "next_max";
private static final String PROP_NEXT_MAX_NAME = "next_max_name";
- private static final String PROP_LOW_WATER_MARK="lowWaterMark";
- private static final String PROP_LOW_WATER_MARK_NAME="lowWaterMark_name";
+ private static final String PROP_LOW_WATER_MARK = "lowWaterMark";
+ private static final String PROP_LOW_WATER_MARK_NAME = "lowWaterMark_name";
private static final String PROP_INCREMENT = "increment";
private static final String PROP_INCREMENT_NAME = "increment_name";
- private static final String PROP_RANGE_DN="rangeDN";
+ private static final String PROP_RANGE_DN = "rangeDN";
private static final BigInteger BI_ONE = new BigInteger("1");
private ILogger mLogger = null;
-
+
// singleton enforcement
private static IDBSubsystem mInstance = new DBSubsystem();
@@ -170,9 +167,10 @@ public class DBSubsystem implements IDBSubsystem {
}
/**
- * This method is used for unit tests. It allows the underlying instance
- * to be stubbed out.
- * @param dbSubsystem The stubbed out subsystem to override with.
+ * This method is used for unit tests. It allows the underlying instance to
+ * be stubbed out.
+ *
+ * @param dbSubsystem The stubbed out subsystem to override with.
*/
public static void setInstance(IDBSubsystem dbSubsystem) {
mInstance = dbSubsystem;
@@ -191,7 +189,7 @@ public class DBSubsystem implements IDBSubsystem {
*/
public String getId() {
return IDBSubsystem.SUB_ID;
- }
+ }
/**
* Sets subsystem identifier.
@@ -214,14 +212,14 @@ public class DBSubsystem implements IDBSubsystem {
return mEnableSerialMgmt;
}
- public void setEnableSerialMgmt(boolean v)
- throws EBaseException {
+ public void setEnableSerialMgmt(boolean v)
+ throws EBaseException {
if (v) {
CMS.debug("DBSubsystem: Enabling Serial Number Management");
} else {
CMS.debug("DBSubsystem: Disabling Serial Number Management");
}
-
+
mDBConfig.putBoolean(PROP_ENABLE_SERIAL_MGMT, v);
IConfigStore rootStore = getOwner().getConfigStore();
rootStore.commit(false);
@@ -232,30 +230,29 @@ public class DBSubsystem implements IDBSubsystem {
return mNextSerialConfig;
}
- public void setNextSerialConfig(BigInteger serial)
- throws EBaseException {
+ public void setNextSerialConfig(BigInteger serial)
+ throws EBaseException {
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_DB,
- ILogger.LL_INFO, "DBSubsystem: " +
- "Setting next serial number: 0x" + serial.toString(16));
+ ILogger.LL_INFO, "DBSubsystem: " +
+ "Setting next serial number: 0x" + serial.toString(16));
mDBConfig.putString(PROP_NEXT_SERIAL_NUMBER,
- serial.toString(16));
+ serial.toString(16));
}
/**
* Gets minimum serial number limit in config file
- *
- * @param repo repo identifier
+ *
+ * @param repo repo identifier
* @return min serial number
*/
- public String getMinSerialConfig(int repo)
- {
+ public String getMinSerialConfig(int repo) {
return (String) (mRepos[repo]).get(PROP_MIN);
}
/**
* Gets maximum serial number limit in config file
- *
- * @param repo repo identifier
+ *
+ * @param repo repo identifier
* @return max serial number
*/
public String getMaxSerialConfig(int repo) {
@@ -264,41 +261,38 @@ public class DBSubsystem implements IDBSubsystem {
/**
* Gets minimum serial number limit in next range in config file
- *
- * @param repo repo identifier
+ *
+ * @param repo repo identifier
* @return min serial number in next range
*/
- public String getNextMinSerialConfig(int repo)
- {
+ public String getNextMinSerialConfig(int repo) {
String ret = (String) (mRepos[repo]).get(PROP_NEXT_MIN);
if (ret.equals("-1")) {
return null;
- }
- else {
+ } else {
return ret;
}
}
/**
* Gets maximum serial number limit in next range in config file
- *
- * @param repo repo identifier
+ *
+ * @param repo repo identifier
* @return max serial number in next range
*/
public String getNextMaxSerialConfig(int repo) {
String ret = (String) (mRepos[repo]).get(PROP_NEXT_MAX);
if (ret.equals("-1")) {
return null;
- }
- else {
+ } else {
return ret;
}
}
/**
* Gets low water mark limit in config file
- *
- * @param repo repo identifier
+ *
+ * @param repo repo identifier
* @return low water mark
*/
public String getLowWaterMarkConfig(int repo) {
@@ -307,28 +301,27 @@ public class DBSubsystem implements IDBSubsystem {
/**
* Gets range increment for next range in config file
- *
- * @param repo repo identifier
+ *
+ * @param repo repo identifier
* @return range increment
*/
- public String getIncrementConfig(int repo)
- {
+ public String getIncrementConfig(int repo) {
return (String) (mRepos[repo]).get(PROP_INCREMENT);
}
/**
* Sets maximum serial number limit in config file
- *
- * @param repo repo identifier
+ *
+ * @param repo repo identifier
* @param serial max serial number
- * @exception EBaseException failed to set
+ * @exception EBaseException failed to set
*/
- public void setMaxSerialConfig(int repo, String serial)
- throws EBaseException {
+ public void setMaxSerialConfig(int repo, String serial)
+ throws EBaseException {
Hashtable h = mRepos[repo];
CMS.debug("DBSubsystem: Setting max serial number for " + h.get(NAME) + ": " + serial);
- //persist to file
+ // persist to file
mDBConfig.putString((String) h.get(PROP_MAX_NAME), serial);
IConfigStore rootStore = getOwner().getConfigStore();
rootStore.commit(false);
@@ -339,17 +332,17 @@ public class DBSubsystem implements IDBSubsystem {
/**
* Sets minimum serial number limit in config file
- *
- * @param repo repo identifier
+ *
+ * @param repo repo identifier
* @param serial min serial number
- * @exception EBaseException failed to set
+ * @exception EBaseException failed to set
*/
- public void setMinSerialConfig(int repo, String serial)
- throws EBaseException {
+ public void setMinSerialConfig(int repo, String serial)
+ throws EBaseException {
Hashtable h = mRepos[repo];
CMS.debug("DBSubsystem: Setting min serial number for " + h.get(NAME) + ": " + serial);
- //persist to file
+ // persist to file
mDBConfig.putString((String) h.get(PROP_MIN_NAME), serial);
IConfigStore rootStore = getOwner().getConfigStore();
rootStore.commit(false);
@@ -360,13 +353,13 @@ public class DBSubsystem implements IDBSubsystem {
/**
* Sets maximum serial number limit for next range in config file
- *
- * @param repo repo identifier
+ *
+ * @param repo repo identifier
* @param serial max serial number for next range
- * @exception EBaseException failed to set
+ * @exception EBaseException failed to set
*/
- public void setNextMaxSerialConfig(int repo, String serial)
- throws EBaseException {
+ public void setNextMaxSerialConfig(int repo, String serial)
+ throws EBaseException {
Hashtable h = mRepos[repo];
if (serial == null) {
CMS.debug("DBSubsystem: Removing next max " + h.get(NAME) + " number");
@@ -387,13 +380,13 @@ public class DBSubsystem implements IDBSubsystem {
/**
* Sets minimum serial number limit for next range in config file
- *
- * @param repo repo identifier
+ *
+ * @param repo repo identifier
* @param serial min serial number for next range
- * @exception EBaseException failed to set
+ * @exception EBaseException failed to set
*/
public void setNextMinSerialConfig(int repo, String serial)
- throws EBaseException {
+ throws EBaseException {
Hashtable h = mRepos[repo];
if (serial == null) {
CMS.debug("DBSubsystem: Removing next min " + h.get(NAME) + " number");
@@ -405,19 +398,19 @@ public class DBSubsystem implements IDBSubsystem {
IConfigStore rootStore = getOwner().getConfigStore();
rootStore.commit(false);
if (serial == null) {
- Object o2 = h.remove(PROP_NEXT_MIN);
+ Object o2 = h.remove(PROP_NEXT_MIN);
} else {
- h.put(PROP_NEXT_MIN, serial);
+ h.put(PROP_NEXT_MIN, serial);
}
mRepos[repo] = h;
}
/**
- * Gets start of next range from database.
- * Increments the nextRange attribute and allocates
- * this range to the current instance by creating a pkiRange object.
- *
- * @param repo repo identifier
+ * Gets start of next range from database. Increments the nextRange
+ * attribute and allocates this range to the current instance by creating a
+ * pkiRange object.
+ *
+ * @param repo repo identifier
* @return start of next range
*/
public String getNextRange(int repo) {
@@ -430,28 +423,29 @@ public class DBSubsystem implements IDBSubsystem {
String rangeDN = (String) h.get(PROP_RANGE_DN) + "," + mBaseDN;
LDAPEntry entry = conn.read(dn);
- LDAPAttribute attr = entry.getAttribute(PROP_NEXT_RANGE);
+ LDAPAttribute attr = entry.getAttribute(PROP_NEXT_RANGE);
nextRange = (String) attr.getStringValues().nextElement();
BigInteger nextRangeNo = new BigInteger(nextRange);
BigInteger incrementNo = new BigInteger((String) h.get(PROP_INCREMENT));
- // To make sure attrNextRange always increments, first delete the current value and then
- // increment. Two operations in the same transaction
- LDAPAttribute attrNextRange = new LDAPAttribute(PROP_NEXT_RANGE, nextRangeNo.add(incrementNo).toString());
- LDAPModification [] mods = {
- new LDAPModification( LDAPModification.DELETE, attr),
- new LDAPModification( LDAPModification.ADD, attrNextRange ) };
- conn.modify( dn, mods );
+ // To make sure attrNextRange always increments, first delete the
+ // current value and then
+ // increment. Two operations in the same transaction
+ LDAPAttribute attrNextRange = new LDAPAttribute(PROP_NEXT_RANGE, nextRangeNo.add(incrementNo).toString());
+ LDAPModification[] mods = {
+ new LDAPModification(LDAPModification.DELETE, attr),
+ new LDAPModification(LDAPModification.ADD, attrNextRange) };
+ conn.modify(dn, mods);
// Add new range object
String endRange = nextRangeNo.add(incrementNo).subtract(BI_ONE).toString();
LDAPAttributeSet attrs = new LDAPAttributeSet();
attrs.add(new LDAPAttribute("objectClass", "top"));
attrs.add(new LDAPAttribute("objectClass", "pkiRange"));
- attrs.add(new LDAPAttribute("beginRange" , nextRange));
- attrs.add(new LDAPAttribute("endRange" , endRange));
+ attrs.add(new LDAPAttribute("beginRange", nextRange));
+ attrs.add(new LDAPAttribute("endRange", endRange));
attrs.add(new LDAPAttribute("cn", nextRange));
- attrs.add(new LDAPAttribute("host", CMS.getEESSLHost()));
+ attrs.add(new LDAPAttribute("host", CMS.getEESSLHost()));
attrs.add(new LDAPAttribute("securePort", CMS.getEESSLPort()));
String dn2 = "cn=" + nextRange + "," + rangeDN;
LDAPEntry rangeEntry = new LDAPEntry(dn2, attrs);
@@ -462,12 +456,11 @@ public class DBSubsystem implements IDBSubsystem {
nextRange = null;
} finally {
try {
- if ((conn != null) && (mLdapConnFactory!= null)) {
+ if ((conn != null) && (mLdapConnFactory != null)) {
CMS.debug("Releasing ldap connection");
mLdapConnFactory.returnConn(conn);
}
- }
- catch (Exception e) {
+ } catch (Exception e) {
CMS.debug("Error releasing the ldap connection" + e.toString());
}
}
@@ -475,31 +468,30 @@ public class DBSubsystem implements IDBSubsystem {
}
/**
- * Determines if a range conflict has been observed in database.
- * If so, delete the conflict entry and remove the next range.
- * When the next number is requested, if the number of certs is still
- * below the low water mark, then a new range will be requested.
+ * Determines if a range conflict has been observed in database. If so,
+ * delete the conflict entry and remove the next range. When the next number
+ * is requested, if the number of certs is still below the low water mark,
+ * then a new range will be requested.
*
- * @param repo repo identifier
+ * @param repo repo identifier
* @return true if range conflict, false otherwise
*/
- public boolean hasRangeConflict(int repo)
- {
+ public boolean hasRangeConflict(int repo) {
LDAPConnection conn = null;
boolean conflict = false;
try {
String nextRangeStart = getNextMinSerialConfig(repo);
- if (nextRangeStart == null) {
+ if (nextRangeStart == null) {
return false;
}
Hashtable h = mRepos[repo];
conn = mLdapConnFactory.getConn();
String rangedn = (String) h.get(PROP_RANGE_DN) + "," + mBaseDN;
String filter = "(&(nsds5ReplConflict=*)(objectClass=pkiRange)(host= " +
- CMS.getEESSLHost() + ")(SecurePort=" + CMS.getEESSLPort() +
- ")(beginRange=" + nextRangeStart + "))";
+ CMS.getEESSLHost() + ")(SecurePort=" + CMS.getEESSLPort() +
+ ")(beginRange=" + nextRangeStart + "))";
LDAPSearchResults results = conn.search(rangedn, LDAPv3.SCOPE_SUB,
- filter, null, false);
+ filter, null, false);
while (results.hasMoreElements()) {
conflict = true;
@@ -513,12 +505,11 @@ public class DBSubsystem implements IDBSubsystem {
e.printStackTrace();
} finally {
try {
- if ((conn != null) && (mLdapConnFactory!= null)) {
+ if ((conn != null) && (mLdapConnFactory != null)) {
CMS.debug("Releasing ldap connection");
mLdapConnFactory.returnConn(conn);
}
- }
- catch (Exception e) {
+ } catch (Exception e) {
CMS.debug("Error releasing the ldap connection" + e.toString());
}
}
@@ -530,14 +521,12 @@ public class DBSubsystem implements IDBSubsystem {
}
/**
- * Initializes the internal registery. Connects to the
- * data source, and create a pool of connection of which
- * applications can use. Optionally, check the integrity
- * of the database.
+ * Initializes the internal registery. Connects to the data source, and
+ * create a pool of connection of which applications can use. Optionally,
+ * check the integrity of the database.
*/
- public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
-
+ public void init(ISubsystem owner, IConfigStore config)
+ throws EBaseException {
mLogger = CMS.getLogger();
mDBConfig = config;
@@ -548,110 +537,109 @@ public class DBSubsystem implements IDBSubsystem {
try {
mBaseDN = mConfig.getString(PROP_BASEDN, "o=NetscapeCertificateServer");
- mOwner = owner;
+ mOwner = owner;
mNextSerialConfig = new BigInteger(mDBConfig.getString(
- PROP_NEXT_SERIAL_NUMBER, "0"), 16);
+ PROP_NEXT_SERIAL_NUMBER, "0"), 16);
mEnableSerialMgmt = mDBConfig.getBoolean(PROP_ENABLE_SERIAL_MGMT, false);
// populate the certs hash entry
Hashtable certs = new Hashtable();
certs.put(NAME, "certs");
- certs.put(PROP_BASEDN, mDBConfig.getString(PROP_SERIAL_BASEDN,""));
+ certs.put(PROP_BASEDN, mDBConfig.getString(PROP_SERIAL_BASEDN, ""));
certs.put(PROP_RANGE_DN, mDBConfig.getString(PROP_SERIAL_RANGE_DN, ""));
certs.put(PROP_MIN_NAME, PROP_MIN_SERIAL_NUMBER);
certs.put(PROP_MIN, mDBConfig.getString(
- PROP_MIN_SERIAL_NUMBER, "0"));
+ PROP_MIN_SERIAL_NUMBER, "0"));
certs.put(PROP_MAX_NAME, PROP_MAX_SERIAL_NUMBER);
certs.put(PROP_MAX, mDBConfig.getString(
- PROP_MAX_SERIAL_NUMBER, PROP_INFINITE_SERIAL_NUMBER));
+ PROP_MAX_SERIAL_NUMBER, PROP_INFINITE_SERIAL_NUMBER));
certs.put(PROP_NEXT_MIN_NAME, PROP_NEXT_MIN_SERIAL_NUMBER);
certs.put(PROP_NEXT_MIN, mDBConfig.getString(
- PROP_NEXT_MIN_SERIAL_NUMBER, "-1"));
+ PROP_NEXT_MIN_SERIAL_NUMBER, "-1"));
certs.put(PROP_NEXT_MAX_NAME, PROP_NEXT_MAX_SERIAL_NUMBER);
certs.put(PROP_NEXT_MAX, mDBConfig.getString(
- PROP_NEXT_MAX_SERIAL_NUMBER, "-1"));
+ PROP_NEXT_MAX_SERIAL_NUMBER, "-1"));
certs.put(PROP_LOW_WATER_MARK_NAME, PROP_SERIAL_LOW_WATER_MARK);
certs.put(PROP_LOW_WATER_MARK, mDBConfig.getString(
- PROP_SERIAL_LOW_WATER_MARK, "5000"));
+ PROP_SERIAL_LOW_WATER_MARK, "5000"));
certs.put(PROP_INCREMENT_NAME, PROP_SERIAL_INCREMENT);
certs.put(PROP_INCREMENT, mDBConfig.getString(
- PROP_SERIAL_INCREMENT, PROP_INFINITE_SERIAL_NUMBER));
+ PROP_SERIAL_INCREMENT, PROP_INFINITE_SERIAL_NUMBER));
- mRepos[CERTS]=certs;
+ mRepos[CERTS] = certs;
// populate the requests hash entry
Hashtable requests = new Hashtable();
requests.put(NAME, "requests");
- requests.put(PROP_BASEDN, mDBConfig.getString(PROP_REQUEST_BASEDN,""));
+ requests.put(PROP_BASEDN, mDBConfig.getString(PROP_REQUEST_BASEDN, ""));
requests.put(PROP_RANGE_DN, mDBConfig.getString(PROP_REQUEST_RANGE_DN, ""));
requests.put(PROP_MIN_NAME, PROP_MIN_REQUEST_NUMBER);
requests.put(PROP_MIN, mDBConfig.getString(
- PROP_MIN_REQUEST_NUMBER, "0"));
+ PROP_MIN_REQUEST_NUMBER, "0"));
requests.put(PROP_MAX_NAME, PROP_MAX_REQUEST_NUMBER);
requests.put(PROP_MAX, mDBConfig.getString(
- PROP_MAX_REQUEST_NUMBER, PROP_INFINITE_REQUEST_NUMBER));
+ PROP_MAX_REQUEST_NUMBER, PROP_INFINITE_REQUEST_NUMBER));
requests.put(PROP_NEXT_MIN_NAME, PROP_NEXT_MIN_REQUEST_NUMBER);
requests.put(PROP_NEXT_MIN, mDBConfig.getString(
- PROP_NEXT_MIN_REQUEST_NUMBER, "-1"));
+ PROP_NEXT_MIN_REQUEST_NUMBER, "-1"));
requests.put(PROP_NEXT_MAX_NAME, PROP_NEXT_MAX_REQUEST_NUMBER);
requests.put(PROP_NEXT_MAX, mDBConfig.getString(
- PROP_NEXT_MAX_REQUEST_NUMBER, "-1"));
+ PROP_NEXT_MAX_REQUEST_NUMBER, "-1"));
requests.put(PROP_LOW_WATER_MARK_NAME, PROP_REQUEST_LOW_WATER_MARK);
requests.put(PROP_LOW_WATER_MARK, mDBConfig.getString(
- PROP_REQUEST_LOW_WATER_MARK, "5000"));
+ PROP_REQUEST_LOW_WATER_MARK, "5000"));
requests.put(PROP_INCREMENT_NAME, PROP_REQUEST_INCREMENT);
requests.put(PROP_INCREMENT, mDBConfig.getString(
- PROP_REQUEST_INCREMENT, PROP_INFINITE_REQUEST_NUMBER));
+ PROP_REQUEST_INCREMENT, PROP_INFINITE_REQUEST_NUMBER));
mRepos[REQUESTS] = requests;
// populate replica ID hash entry
Hashtable replicaID = new Hashtable();
replicaID.put(NAME, "requests");
- replicaID.put(PROP_BASEDN, mDBConfig.getString(PROP_REPLICA_BASEDN,""));
+ replicaID.put(PROP_BASEDN, mDBConfig.getString(PROP_REPLICA_BASEDN, ""));
replicaID.put(PROP_RANGE_DN, mDBConfig.getString(PROP_REPLICA_RANGE_DN, ""));
replicaID.put(PROP_MIN_NAME, PROP_MIN_REPLICA_NUMBER);
replicaID.put(PROP_MIN, mDBConfig.getString(
- PROP_MIN_REPLICA_NUMBER, "1"));
+ PROP_MIN_REPLICA_NUMBER, "1"));
replicaID.put(PROP_MAX_NAME, PROP_MAX_REPLICA_NUMBER);
replicaID.put(PROP_MAX, mDBConfig.getString(
- PROP_MAX_REPLICA_NUMBER, PROP_INFINITE_REPLICA_NUMBER));
+ PROP_MAX_REPLICA_NUMBER, PROP_INFINITE_REPLICA_NUMBER));
replicaID.put(PROP_NEXT_MIN_NAME, PROP_NEXT_MIN_REPLICA_NUMBER);
replicaID.put(PROP_NEXT_MIN, mDBConfig.getString(
- PROP_NEXT_MIN_REPLICA_NUMBER, "-1"));
+ PROP_NEXT_MIN_REPLICA_NUMBER, "-1"));
replicaID.put(PROP_NEXT_MAX_NAME, PROP_NEXT_MAX_REPLICA_NUMBER);
replicaID.put(PROP_NEXT_MAX, mDBConfig.getString(
- PROP_NEXT_MAX_REPLICA_NUMBER, "-1"));
+ PROP_NEXT_MAX_REPLICA_NUMBER, "-1"));
replicaID.put(PROP_LOW_WATER_MARK_NAME, PROP_REPLICA_LOW_WATER_MARK);
replicaID.put(PROP_LOW_WATER_MARK, mDBConfig.getString(
- PROP_REPLICA_LOW_WATER_MARK, "10"));
+ PROP_REPLICA_LOW_WATER_MARK, "10"));
replicaID.put(PROP_INCREMENT_NAME, PROP_REPLICA_INCREMENT);
replicaID.put(PROP_INCREMENT, mDBConfig.getString(
- PROP_REPLICA_INCREMENT, PROP_INFINITE_REPLICA_NUMBER));
+ PROP_REPLICA_INCREMENT, PROP_INFINITE_REPLICA_NUMBER));
mRepos[REPLICA_ID] = replicaID;
-
// initialize registry
mRegistry = new DBRegistry();
mRegistry.init(this, null);
@@ -688,7 +676,7 @@ public class DBSubsystem implements IDBSubsystem {
try {
// registers CMS database attributes
IDBRegistry reg = getRegistry();
-
+
String certRecordOC[] = new String[2];
certRecordOC[0] = CertDBSchema.LDAP_OC_TOP;
@@ -696,61 +684,61 @@ public class DBSubsystem implements IDBSubsystem {
if (!reg.isObjectClassRegistered(CertRecord.class.getName())) {
reg.registerObjectClass(CertRecord.class.getName(),
- certRecordOC);
+ certRecordOC);
}
if (!reg.isAttributeRegistered(CertRecord.ATTR_ID)) {
reg.registerAttribute(CertRecord.ATTR_ID, new
- BigIntegerMapper(CertDBSchema.LDAP_ATTR_SERIALNO));
+ BigIntegerMapper(CertDBSchema.LDAP_ATTR_SERIALNO));
}
if (!reg.isAttributeRegistered(CertRecord.ATTR_META_INFO)) {
reg.registerAttribute(CertRecord.ATTR_META_INFO, new
- MetaInfoMapper(CertDBSchema.LDAP_ATTR_META_INFO));
+ MetaInfoMapper(CertDBSchema.LDAP_ATTR_META_INFO));
}
if (!reg.isAttributeRegistered(CertRecord.ATTR_REVO_INFO)) {
reg.registerAttribute(CertRecord.ATTR_REVO_INFO, new
- RevocationInfoMapper());
+ RevocationInfoMapper());
}
if (!reg.isAttributeRegistered(CertRecord.ATTR_X509CERT)) {
reg.registerAttribute(CertRecord.ATTR_X509CERT, new
- X509CertImplMapper());
+ X509CertImplMapper());
}
if (!reg.isAttributeRegistered(CertRecord.ATTR_CERT_STATUS)) {
reg.registerAttribute(CertRecord.ATTR_CERT_STATUS, new
- StringMapper(CertDBSchema.LDAP_ATTR_CERT_STATUS));
+ StringMapper(CertDBSchema.LDAP_ATTR_CERT_STATUS));
}
if (!reg.isAttributeRegistered(CertRecord.ATTR_AUTO_RENEW)) {
reg.registerAttribute(CertRecord.ATTR_AUTO_RENEW, new
- StringMapper(CertDBSchema.LDAP_ATTR_AUTO_RENEW));
+ StringMapper(CertDBSchema.LDAP_ATTR_AUTO_RENEW));
}
if (!reg.isAttributeRegistered(CertRecord.ATTR_CREATE_TIME)) {
reg.registerAttribute(CertRecord.ATTR_CREATE_TIME, new
- DateMapper(CertDBSchema.LDAP_ATTR_CREATE_TIME));
+ DateMapper(CertDBSchema.LDAP_ATTR_CREATE_TIME));
}
if (!reg.isAttributeRegistered(CertRecord.ATTR_MODIFY_TIME)) {
reg.registerAttribute(CertRecord.ATTR_MODIFY_TIME, new
- DateMapper(CertDBSchema.LDAP_ATTR_MODIFY_TIME));
+ DateMapper(CertDBSchema.LDAP_ATTR_MODIFY_TIME));
}
if (!reg.isAttributeRegistered(CertRecord.ATTR_ISSUED_BY)) {
reg.registerAttribute(CertRecord.ATTR_ISSUED_BY, new
- StringMapper(CertDBSchema.LDAP_ATTR_ISSUED_BY));
+ StringMapper(CertDBSchema.LDAP_ATTR_ISSUED_BY));
}
if (!reg.isAttributeRegistered(CertRecord.ATTR_REVOKED_BY)) {
reg.registerAttribute(CertRecord.ATTR_REVOKED_BY, new
- StringMapper(CertDBSchema.LDAP_ATTR_REVOKED_BY));
+ StringMapper(CertDBSchema.LDAP_ATTR_REVOKED_BY));
}
if (!reg.isAttributeRegistered(CertRecord.ATTR_REVOKED_ON)) {
reg.registerAttribute(CertRecord.ATTR_REVOKED_ON, new
- DateMapper(CertDBSchema.LDAP_ATTR_REVOKED_ON));
+ DateMapper(CertDBSchema.LDAP_ATTR_REVOKED_ON));
}
if (!reg.isAttributeRegistered(CertificateValidity.NOT_AFTER)) {
reg.registerAttribute(CertificateValidity.NOT_AFTER, new
- DateMapper(CertDBSchema.LDAP_ATTR_NOT_AFTER));
+ DateMapper(CertDBSchema.LDAP_ATTR_NOT_AFTER));
}
if (!reg.isAttributeRegistered(CertificateValidity.NOT_BEFORE)) {
reg.registerAttribute(CertificateValidity.NOT_BEFORE, new
- DateMapper(CertDBSchema.LDAP_ATTR_NOT_BEFORE));
+ DateMapper(CertDBSchema.LDAP_ATTR_NOT_BEFORE));
}
String crlRecordOC[] = new String[2];
@@ -758,54 +746,54 @@ public class DBSubsystem implements IDBSubsystem {
crlRecordOC[0] = CRLDBSchema.LDAP_OC_TOP;
crlRecordOC[1] = CRLDBSchema.LDAP_OC_CRL_RECORD;
reg.registerObjectClass(CRLIssuingPointRecord.class.getName(),
- crlRecordOC);
+ crlRecordOC);
reg.registerAttribute(ICRLIssuingPointRecord.ATTR_ID, new
- StringMapper(CRLDBSchema.LDAP_ATTR_CRL_ID));
+ StringMapper(CRLDBSchema.LDAP_ATTR_CRL_ID));
reg.registerAttribute(ICRLIssuingPointRecord.ATTR_CRL_NUMBER, new
- BigIntegerMapper(CRLDBSchema.LDAP_ATTR_CRL_NUMBER));
+ BigIntegerMapper(CRLDBSchema.LDAP_ATTR_CRL_NUMBER));
reg.registerAttribute(ICRLIssuingPointRecord.ATTR_DELTA_NUMBER, new
- BigIntegerMapper(CRLDBSchema.LDAP_ATTR_DELTA_NUMBER));
+ BigIntegerMapper(CRLDBSchema.LDAP_ATTR_DELTA_NUMBER));
reg.registerAttribute(ICRLIssuingPointRecord.ATTR_CRL_SIZE, new
- LongMapper(CRLDBSchema.LDAP_ATTR_CRL_SIZE));
+ LongMapper(CRLDBSchema.LDAP_ATTR_CRL_SIZE));
reg.registerAttribute(ICRLIssuingPointRecord.ATTR_DELTA_SIZE, new
- LongMapper(CRLDBSchema.LDAP_ATTR_DELTA_SIZE));
+ LongMapper(CRLDBSchema.LDAP_ATTR_DELTA_SIZE));
reg.registerAttribute(ICRLIssuingPointRecord.ATTR_THIS_UPDATE, new
- DateMapper(CRLDBSchema.LDAP_ATTR_THIS_UPDATE));
+ DateMapper(CRLDBSchema.LDAP_ATTR_THIS_UPDATE));
reg.registerAttribute(ICRLIssuingPointRecord.ATTR_NEXT_UPDATE, new
- DateMapper(CRLDBSchema.LDAP_ATTR_NEXT_UPDATE));
+ DateMapper(CRLDBSchema.LDAP_ATTR_NEXT_UPDATE));
reg.registerAttribute(ICRLIssuingPointRecord.ATTR_FIRST_UNSAVED, new
- StringMapper(CRLDBSchema.LDAP_ATTR_FIRST_UNSAVED));
+ StringMapper(CRLDBSchema.LDAP_ATTR_FIRST_UNSAVED));
reg.registerAttribute(ICRLIssuingPointRecord.ATTR_CRL, new
- ByteArrayMapper(CRLDBSchema.LDAP_ATTR_CRL));
+ ByteArrayMapper(CRLDBSchema.LDAP_ATTR_CRL));
reg.registerAttribute(ICRLIssuingPointRecord.ATTR_DELTA_CRL, new
- ByteArrayMapper(CRLDBSchema.LDAP_ATTR_DELTA_CRL));
+ ByteArrayMapper(CRLDBSchema.LDAP_ATTR_DELTA_CRL));
reg.registerAttribute(ICRLIssuingPointRecord.ATTR_CA_CERT, new
- ByteArrayMapper(CRLDBSchema.LDAP_ATTR_CA_CERT));
+ ByteArrayMapper(CRLDBSchema.LDAP_ATTR_CA_CERT));
reg.registerAttribute(ICRLIssuingPointRecord.ATTR_CRL_CACHE, new
- ObjectStreamMapper(CRLDBSchema.LDAP_ATTR_CRL_CACHE));
+ ObjectStreamMapper(CRLDBSchema.LDAP_ATTR_CRL_CACHE));
reg.registerAttribute(ICRLIssuingPointRecord.ATTR_REVOKED_CERTS, new
- ObjectStreamMapper(CRLDBSchema.LDAP_ATTR_REVOKED_CERTS));
+ ObjectStreamMapper(CRLDBSchema.LDAP_ATTR_REVOKED_CERTS));
reg.registerAttribute(ICRLIssuingPointRecord.ATTR_UNREVOKED_CERTS, new
- ObjectStreamMapper(CRLDBSchema.LDAP_ATTR_UNREVOKED_CERTS));
+ ObjectStreamMapper(CRLDBSchema.LDAP_ATTR_UNREVOKED_CERTS));
reg.registerAttribute(ICRLIssuingPointRecord.ATTR_EXPIRED_CERTS, new
- ObjectStreamMapper(CRLDBSchema.LDAP_ATTR_EXPIRED_CERTS));
+ ObjectStreamMapper(CRLDBSchema.LDAP_ATTR_EXPIRED_CERTS));
if (!reg.isObjectClassRegistered(
- RepositoryRecord.class.getName())) {
+ RepositoryRecord.class.getName())) {
String repRecordOC[] = new String[2];
repRecordOC[0] = RepositorySchema.LDAP_OC_TOP;
repRecordOC[1] = RepositorySchema.LDAP_OC_REPOSITORY;
reg.registerObjectClass(
- RepositoryRecord.class.getName(), repRecordOC);
+ RepositoryRecord.class.getName(), repRecordOC);
}
if (!reg.isAttributeRegistered(IRepositoryRecord.ATTR_SERIALNO)) {
reg.registerAttribute(IRepositoryRecord.ATTR_SERIALNO,
- new BigIntegerMapper(RepositorySchema.LDAP_ATTR_SERIALNO));
+ new BigIntegerMapper(RepositorySchema.LDAP_ATTR_SERIALNO));
}
if (!reg.isAttributeRegistered(IRepositoryRecord.ATTR_PUB_STATUS)) {
reg.registerAttribute(IRepositoryRecord.ATTR_PUB_STATUS,
- new StringMapper(RepositorySchema.LDAP_ATTR_PUB_STATUS));
+ new StringMapper(RepositorySchema.LDAP_ATTR_PUB_STATUS));
}
} catch (EBaseException e) {
@@ -820,7 +808,7 @@ public class DBSubsystem implements IDBSubsystem {
*/
public void startup() throws EBaseException {
}
-
+
/**
* Retrieves configuration store.
*/
@@ -861,16 +849,19 @@ public class DBSubsystem implements IDBSubsystem {
}
} catch (ELdapException e) {
- /*LogDoc
- *
+ /*
+ * LogDoc
+ *
* @phase shutdown server
+ *
* @reason shutdown db subsystem
+ *
* @message DBSubsystem: <exception thrown>
*/
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_DB,
- ILogger.LL_FAILURE, CMS.getLogMessage("OPERATION_ERROR", e.toString()));
+ ILogger.LL_FAILURE, CMS.getLogMessage("OPERATION_ERROR", e.toString()));
}
- if (mRegistry != null)
+ if (mRegistry != null)
mRegistry.shutdown();
}
@@ -905,11 +896,11 @@ public class DBSubsystem implements IDBSubsystem {
LDAPAttributeSchema.cis, false);
userType.add(conn);
}
-
+
// create new objectclass: cmsuser
dirSchema.fetchSchema(conn);
LDAPObjectClassSchema newObjClass = dirSchema.getObjectClass("cmsuser");
- String[] requiredAttrs = {"usertype"};
+ String[] requiredAttrs = { "usertype" };
String[] optionalAttrs = new String[0];
if (newObjClass == null) {
@@ -928,25 +919,26 @@ public class DBSubsystem implements IDBSubsystem {
CMS.getUserMessage("CMS_DBS_INTERNAL_DIR_UNAVAILABLE"));
}
- /*LogDoc
- *
+ /*
+ * LogDoc
+ *
* @phase create db session
*/
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_DB, ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_DBS_CONN_ERROR", e.toString()));
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_DB, ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_DBS_CONN_ERROR", e.toString()));
throw new EDBException(
CMS.getUserMessage("CMS_DBS_CONNECT_LDAP_FAILED", e.toString()));
} catch (LDAPException e) {
if (e.getLDAPResultCode() != 20) {
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_DB, ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_DBS_SCHEMA_ERROR", e.toString()));
+ CMS.getLogMessage("CMSCORE_DBS_SCHEMA_ERROR", e.toString()));
throw new EDBException(
CMS.getUserMessage("CMS_DBS_ADD_ENTRY_FAILED", e.toString()));
}
} catch (EBaseException e) {
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_DB, ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_DBS_CONF_ERROR",
- e.toString()));
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_DB, ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_DBS_CONF_ERROR",
+ e.toString()));
}
return new DBSSession(this, conn);
}
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/DBVirtualList.java b/pki/base/common/src/com/netscape/cmscore/dbs/DBVirtualList.java
index ddec63ce..350c78b6 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/DBVirtualList.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/DBVirtualList.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.util.Arrays;
import java.util.Vector;
@@ -38,12 +37,11 @@ import com.netscape.certsrv.dbs.IDBVirtualList;
import com.netscape.certsrv.dbs.IElementProcessor;
import com.netscape.certsrv.logging.ILogger;
-
/**
- * A class represents a virtual list of search results.
- * Note that this class must be used with DS4.0.
- *
- * @author thomask
+ * A class represents a virtual list of search results. Note that this class
+ * must be used with DS4.0.
+ *
+ * @author thomask
* @author mzhao
* @version $Revision$, $Date$
*/
@@ -71,63 +69,62 @@ public class DBVirtualList<E> implements IDBVirtualList<E> {
// the index of the first entry returned
private int mSelectedIndex = 0;
private int mJumpToIndex = 0;
- private int mJumpToInitialIndex = 0; // Initial index hit in jumpto operation
- private int mJumpToDirection = 1; // Do we proceed forward or backwards
- private String mJumpTo = null; // Determines if this is the jumpto case
+ private int mJumpToInitialIndex = 0; // Initial index hit in jumpto
+ // operation
+ private int mJumpToDirection = 1; // Do we proceed forward or backwards
+ private String mJumpTo = null; // Determines if this is the jumpto case
private ILogger mLogger = CMS.getLogger();
/**
- * Constructs a virtual list.
- * Be sure to setPageSize() later if your pageSize is not the default 10
- * Be sure to setSortKey() before fetchs
- *
- * param registry the registry of attribute mappers
- * param c the ldap connection. It has to be version 3 and upper
- * param base the base distinguished name to search from
- * param filter search filter specifying the search criteria
- * param attrs list of attributes that you want returned in the search results
+ * Constructs a virtual list. Be sure to setPageSize() later if your
+ * pageSize is not the default 10 Be sure to setSortKey() before fetchs
+ *
+ * param registry the registry of attribute mappers param c the ldap
+ * connection. It has to be version 3 and upper param base the base
+ * distinguished name to search from param filter search filter specifying
+ * the search criteria param attrs list of attributes that you want returned
+ * in the search results
*/
public DBVirtualList(IDBRegistry registry, LDAPConnection c,
- String base, String filter, String attrs[]) throws EBaseException {
+ String base, String filter, String attrs[]) throws EBaseException {
mRegistry = registry;
mFilter = filter;
mBase = base;
mAttrs = attrs;
- CMS.debug( "In DBVirtualList filter attrs filter: " + filter
- + " attrs: " + Arrays.toString( attrs ) );
+ CMS.debug("In DBVirtualList filter attrs filter: " + filter
+ + " attrs: " + Arrays.toString(attrs));
mPageControls = new LDAPControl[2];
try {
mConn = (LDAPConnection) c.clone();
} catch (Exception e) {
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_CONN_FAILED",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_CONN_FAILED",
e.toString()));
}
}
/**
- * Constructs a virtual list.
- * Be sure to setPageSize() later if your pageSize is not the default 10
- *
- * param registry the registry of attribute mappers
- * param c the ldap connection. It has to be version 3 and upper
- * param base the base distinguished name to search from
- * param filter search filter specifying the search criteria
- * param attrs list of attributes that you want returned in the search results
- * param sortKey the attributes to sort by
+ * Constructs a virtual list. Be sure to setPageSize() later if your
+ * pageSize is not the default 10
+ *
+ * param registry the registry of attribute mappers param c the ldap
+ * connection. It has to be version 3 and upper param base the base
+ * distinguished name to search from param filter search filter specifying
+ * the search criteria param attrs list of attributes that you want returned
+ * in the search results param sortKey the attributes to sort by
*/
public DBVirtualList(IDBRegistry registry, LDAPConnection c,
- String base, String filter, String attrs[], String sortKey[])
- throws EBaseException {
+ String base, String filter, String attrs[], String sortKey[])
+ throws EBaseException {
- CMS.debug( "In DBVirtualList filter attrs sotrKey[] filter: " + filter
- + " attrs: " + Arrays.toString( attrs ) );
+ CMS.debug("In DBVirtualList filter attrs sotrKey[] filter: " + filter
+ + " attrs: " + Arrays.toString(attrs));
mRegistry = registry;
mFilter = filter;
try {
mConn = (LDAPConnection) c.clone();
} catch (Exception e) {
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_CONN_FAILED",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_CONN_FAILED",
e.toString()));
}
mBase = base;
@@ -137,27 +134,26 @@ public class DBVirtualList<E> implements IDBVirtualList<E> {
}
/**
- * Constructs a virtual list.
- * Be sure to setPageSize() later if your pageSize is not the default 10
- *
- * param registry the registry of attribute mappers
- * param c the ldap connection. It has to be version 3 and upper
- * param base the base distinguished name to search from
- * param filter search filter specifying the search criteria
- * param attrs list of attributes that you want returned in the search results
- * param sortKey the attribute to sort by
+ * Constructs a virtual list. Be sure to setPageSize() later if your
+ * pageSize is not the default 10
+ *
+ * param registry the registry of attribute mappers param c the ldap
+ * connection. It has to be version 3 and upper param base the base
+ * distinguished name to search from param filter search filter specifying
+ * the search criteria param attrs list of attributes that you want returned
+ * in the search results param sortKey the attribute to sort by
*/
public DBVirtualList(IDBRegistry registry, LDAPConnection c,
- String base, String filter, String attrs[], String sortKey)
- throws EBaseException {
+ String base, String filter, String attrs[], String sortKey)
+ throws EBaseException {
- CMS.debug( "In DBVirtualList filter attrs sortKey filter: " + filter + " attrs: " + Arrays.toString( attrs ) );
+ CMS.debug("In DBVirtualList filter attrs sortKey filter: " + filter + " attrs: " + Arrays.toString(attrs));
mRegistry = registry;
mFilter = filter;
try {
mConn = (LDAPConnection) c.clone();
} catch (Exception e) {
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_CONN_FAILED",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_CONN_FAILED",
e.toString()));
}
mBase = base;
@@ -168,29 +164,28 @@ public class DBVirtualList<E> implements IDBVirtualList<E> {
/**
* Constructs a virtual list.
- *
- * param registry the registry of attribute mappers
- * param c the ldap connection. It has to be version 3 and upper
- * param base the base distinguished name to search from
- * param filter search filter specifying the search criteria
- * param attrs list of attributes that you want returned in the search results
- * param sortKey the attributes to sort by
- * param pageSize the size of a page. There is a 3*pageSize buffer maintained so
- * pageUp and pageDown won't invoke fetch from ldap server
+ *
+ * param registry the registry of attribute mappers param c the ldap
+ * connection. It has to be version 3 and upper param base the base
+ * distinguished name to search from param filter search filter specifying
+ * the search criteria param attrs list of attributes that you want returned
+ * in the search results param sortKey the attributes to sort by param
+ * pageSize the size of a page. There is a 3*pageSize buffer maintained so
+ * pageUp and pageDown won't invoke fetch from ldap server
*/
public DBVirtualList(IDBRegistry registry, LDAPConnection c,
- String base, String filter, String attrs[], String sortKey[],
- int pageSize) throws EBaseException {
+ String base, String filter, String attrs[], String sortKey[],
+ int pageSize) throws EBaseException {
- CMS.debug( "In DBVirtualList filter attrs sortKey[] pageSize filter: "
- + filter + " attrs: " + Arrays.toString( attrs )
- + " pageSize " + pageSize );
+ CMS.debug("In DBVirtualList filter attrs sortKey[] pageSize filter: "
+ + filter + " attrs: " + Arrays.toString(attrs)
+ + " pageSize " + pageSize);
mRegistry = registry;
mFilter = filter;
try {
mConn = (LDAPConnection) c.clone();
} catch (Exception e) {
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_CONN_FAILED",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_CONN_FAILED",
e.toString()));
}
mBase = base;
@@ -202,23 +197,22 @@ public class DBVirtualList<E> implements IDBVirtualList<E> {
/**
* Constructs a virtual list.
- *
- * param registry the registry of attribute mappers
- * param c the ldap connection. It has to be version 3 and upper
- * param base the base distinguished name to search from
- * param filter search filter specifying the search criteria
- * param attrs list of attributes that you want returned in the search results
- * param sortKey the attribute to sort by
- * param pageSize the size of a page. There is a 3*pageSize buffer maintained so
- * pageUp and pageDown won't invoke fetch from ldap server
+ *
+ * param registry the registry of attribute mappers param c the ldap
+ * connection. It has to be version 3 and upper param base the base
+ * distinguished name to search from param filter search filter specifying
+ * the search criteria param attrs list of attributes that you want returned
+ * in the search results param sortKey the attribute to sort by param
+ * pageSize the size of a page. There is a 3*pageSize buffer maintained so
+ * pageUp and pageDown won't invoke fetch from ldap server
*/
public DBVirtualList(IDBRegistry registry, LDAPConnection c,
- String base, String filter, String attrs[], String sortKey,
- int pageSize) throws EBaseException {
+ String base, String filter, String attrs[], String sortKey,
+ int pageSize) throws EBaseException {
- CMS.debug( "In DBVirtualList filter attrs sortKey pageSize filter: "
- + filter + " attrs: " + Arrays.toString( attrs )
- + " pageSize " + pageSize );
+ CMS.debug("In DBVirtualList filter attrs sortKey pageSize filter: "
+ + filter + " attrs: " + Arrays.toString(attrs)
+ + " pageSize " + pageSize);
mRegistry = registry;
mFilter = filter;
try {
@@ -235,20 +229,20 @@ public class DBVirtualList<E> implements IDBVirtualList<E> {
}
public DBVirtualList(IDBRegistry registry, LDAPConnection c,
- String base, String filter, String attrs[],
- String startFrom, String sortKey,
- int pageSize) throws EBaseException {
-
- CMS.debug( "In DBVirtualList filter attrs startFrom sortKey pageSize "
- + "filter: " + filter
- + " attrs: " + Arrays.toString( attrs )
- + " pageSize " + pageSize + " startFrom " + startFrom );
+ String base, String filter, String attrs[],
+ String startFrom, String sortKey,
+ int pageSize) throws EBaseException {
+
+ CMS.debug("In DBVirtualList filter attrs startFrom sortKey pageSize "
+ + "filter: " + filter
+ + " attrs: " + Arrays.toString(attrs)
+ + " pageSize " + pageSize + " startFrom " + startFrom);
mRegistry = registry;
mFilter = filter;
try {
mConn = (LDAPConnection) c.clone();
} catch (Exception e) {
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_CONN_FAILED",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_CONN_FAILED",
e.toString()));
}
mBase = base;
@@ -260,7 +254,7 @@ public class DBVirtualList<E> implements IDBVirtualList<E> {
if (pageSize < 0) {
mJumpToDirection = -1;
- }
+ }
mPageSize = pageSize;
mBeforeCount = 0;
@@ -268,11 +262,10 @@ public class DBVirtualList<E> implements IDBVirtualList<E> {
}
/**
- * Set the paging size of this virtual list.
- * The page size here is just a buffer size. A buffer is kept around
- * that is three times as large as the number of visible entries.
- * That way, you can scroll up/down several items(up to a page-full)
- * without refetching entries from the directory.
+ * Set the paging size of this virtual list. The page size here is just a
+ * buffer size. A buffer is kept around that is three times as large as the
+ * number of visible entries. That way, you can scroll up/down several
+ * items(up to a page-full) without refetching entries from the directory.
*
* @param size the page size
*/
@@ -283,15 +276,16 @@ public class DBVirtualList<E> implements IDBVirtualList<E> {
}
mPageSize = size;
- mBeforeCount = 0; //mPageSize;
+ mBeforeCount = 0; // mPageSize;
mAfterCount = mPageSize; // mPageSize + mPageSize;
- //CMS.debug("In setPageSize " + size + " mBeforeCount " + mBeforeCount + " mAfterCount " + mAfterCount);
+ // CMS.debug("In setPageSize " + size + " mBeforeCount " + mBeforeCount
+ // + " mAfterCount " + mAfterCount);
}
/**
* set the sort key
- *
+ *
* @param sortKey the attribute to sort by
*/
public void setSortKey(String sortKey) throws EBaseException {
@@ -303,7 +297,7 @@ public class DBVirtualList<E> implements IDBVirtualList<E> {
/**
* set the sort key
- *
+ *
* @param sortKey the attributes to sort by
*/
public void setSortKey(String[] sortKeys) throws EBaseException {
@@ -319,28 +313,31 @@ public class DBVirtualList<E> implements IDBVirtualList<E> {
}
} catch (Exception e) {
- /*LogDoc
- *
+ /*
+ * LogDoc
+ *
* @phase local ldap search
+ *
* @reason Failed at setSortKey.
+ *
* @message DBVirtualList: <exception thrown>
*/
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_DB, ILogger.LL_FAILURE,
- CMS.getLogMessage("OPERATION_ERROR", e.toString()));
+ CMS.getLogMessage("OPERATION_ERROR", e.toString()));
}
// Paged results also require a sort control
if (mKeys != null) {
mPageControls[0] =
new LDAPSortControl(mKeys, true);
- }else {
+ } else {
throw new EBaseException("sort keys cannot be null");
}
}
/**
- * Retrieves the size of this virtual list.
- * Recommend to call getSize() before getElementAt() or getElements()
- * since you'd better check if the index is out of bound first.
+ * Retrieves the size of this virtual list. Recommend to call getSize()
+ * before getElementAt() or getElements() since you'd better check if the
+ * index is out of bound first.
*/
public int getSize() {
if (!mInitialized) {
@@ -348,16 +345,18 @@ public class DBVirtualList<E> implements IDBVirtualList<E> {
// Do an initial search to get the virtual list size
// Keep one page before and one page after the start
if (mJumpTo == null) {
- mBeforeCount = 0; //mPageSize;
- mAfterCount = mPageSize; // mPageSize + mPageSize;
+ mBeforeCount = 0; // mPageSize;
+ mAfterCount = mPageSize; // mPageSize + mPageSize;
}
// Create the initial paged results control
- /* Since this one is only used to get the size of the virtual list;
- we don't care about the starting index. If there is no partial
- match, the first one before (or after, if none before) is returned
- as the index entry. Instead of "A", you could use the other
- constructor and specify 0 both for startIndex and for
- contentCount. */
+ /*
+ * Since this one is only used to get the size of the virtual list;
+ * we don't care about the starting index. If there is no partial
+ * match, the first one before (or after, if none before) is
+ * returned as the index entry. Instead of "A", you could use the
+ * other constructor and specify 0 both for startIndex and for
+ * contentCount.
+ */
LDAPVirtualListControl cont = null;
if (mJumpTo == null) {
@@ -368,7 +367,7 @@ public class DBVirtualList<E> implements IDBVirtualList<E> {
if (mPageSize < 0) {
mBeforeCount = mPageSize * -1;
- mAfterCount = 0;
+ mAfterCount = 0;
}
cont = new LDAPVirtualListControl(mJumpTo,
mBeforeCount,
@@ -382,21 +381,21 @@ public class DBVirtualList<E> implements IDBVirtualList<E> {
return mSize;
}
- public int getSizeBeforeJumpTo() {
+ public int getSizeBeforeJumpTo() {
if (!mInitialized || mJumpTo == null)
return 0;
int size = 0;
-
- if (mJumpToDirection < 0) {
+
+ if (mJumpToDirection < 0) {
size = mTop + mEntries.size();
} else {
size = mTop;
}
- return size;
+ return size;
}
@@ -410,7 +409,7 @@ public class DBVirtualList<E> implements IDBVirtualList<E> {
return size;
}
-
+
private synchronized boolean getEntries() {
// Specify necessary controls for vlist
// LDAPSearchConstraints cons = mConn.getSearchConstraints();
@@ -419,13 +418,13 @@ public class DBVirtualList<E> implements IDBVirtualList<E> {
cons.setMaxResults(0);
if (mPageControls != null) {
cons.setServerControls(mPageControls);
- //System.out.println( "setting vlist control" );
+ // System.out.println( "setting vlist control" );
}
// Empty the buffer
mEntries.removeAllElements();
// Do a search
try {
- //what happen if there is no matching?
+ // what happen if there is no matching?
String ldapFilter = mRegistry.getFilter(mFilter);
String ldapAttrs[] = null;
LDAPSearchResults result;
@@ -434,12 +433,10 @@ public class DBVirtualList<E> implements IDBVirtualList<E> {
ldapAttrs = mRegistry.getLDAPAttributes(mAttrs);
/*
- LDAPv2.SCOPE_BASE:
- (search only the base DN)
- LDAPv2.SCOPE_ONE:
- (search only entries under the base DN)
- LDAPv2.SCOPE_SUB:
- (search the base DN and all entries within its subtree)
+ * LDAPv2.SCOPE_BASE: (search only the base DN)
+ * LDAPv2.SCOPE_ONE: (search only entries under the base DN)
+ * LDAPv2.SCOPE_SUB: (search the base DN and all entries within
+ * its subtree)
*/
result = mConn.search(mBase,
LDAPConnection.SCOPE_ONE, ldapFilter, ldapAttrs,
@@ -459,47 +456,53 @@ public class DBVirtualList<E> implements IDBVirtualList<E> {
LDAPEntry entry = (LDAPEntry) result.nextElement();
try {
- //maintain mEntries as vector of LDAPEntry
+ // maintain mEntries as vector of LDAPEntry
@SuppressWarnings("unchecked")
- E o = (E)mRegistry.createObject(entry.getAttributeSet());
+ E o = (E) mRegistry.createObject(entry.getAttributeSet());
mEntries.addElement(o);
} catch (Exception e) {
CMS.debug("Exception " + e);
- /*LogDoc
- *
+ /*
+ * LogDoc
+ *
* @phase local ldap search
+ *
* @reason Failed to get enties.
+ *
* @message DBVirtualList: <exception thrown>
*/
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_DB, ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_DBS_VL_ADD", e.toString()));
+ CMS.getLogMessage("CMSCORE_DBS_VL_ADD", e.toString()));
// #539044
damageCounter++;
if (damageCounter > 100) {
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_DB, ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_DBS_VL_CORRUPTED_ENTRIES", Integer.toString(damageCounter)));
+ CMS.getLogMessage("CMSCORE_DBS_VL_CORRUPTED_ENTRIES", Integer.toString(damageCounter)));
return false;
}
}
}
} catch (Exception e) {
- /*LogDoc
- *
+ /*
+ * LogDoc
+ *
* @phase local ldap search
+ *
* @reason Failed to get enties.
+ *
* @message DBVirtualList: <exception thrown>
*/
CMS.debug("getEntries: exception " + e);
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_DB, ILogger.LL_FAILURE,
- CMS.getLogMessage("OPERATION_ERROR", e.toString()));
+ CMS.getLogMessage("OPERATION_ERROR", e.toString()));
}
- //System.out.println( "Returning " + mEntries.size() +
- // " entries" );
+ // System.out.println( "Returning " + mEntries.size() +
+ // " entries" );
CMS.debug("getEntries returning " + mEntries.size());
return true;
@@ -515,10 +518,10 @@ public class DBVirtualList<E> implements IDBVirtualList<E> {
if (!getEntries())
return false;
- // Check if we have a control returned
+ // Check if we have a control returned
LDAPControl[] c = mConn.getResponseControls();
LDAPVirtualListResponse nextCont =
- LDAPVirtualListResponse.parseResponse(c);
+ LDAPVirtualListResponse.parseResponse(c);
if (nextCont != null) {
mSelectedIndex = nextCont.getFirstPosition() - 1;
@@ -533,10 +536,10 @@ public class DBVirtualList<E> implements IDBVirtualList<E> {
mSize = nextCont.getContentCount();
((LDAPVirtualListControl) mPageControls[1]).setListSize(mSize);
mInitialized = true;
- //System.out.println( "Virtual window: " + mTop +
- // ".." + (mTop+mEntries.size()-1) +
- // " of " + mSize );
- } else {
+ // System.out.println( "Virtual window: " + mTop +
+ // ".." + (mTop+mEntries.size()-1) +
+ // " of " + mSize );
+ } else {
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_DB, ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_DBS_VL_NULL_RESPONSE"));
}
return true;
@@ -546,14 +549,15 @@ public class DBVirtualList<E> implements IDBVirtualList<E> {
}
}
- /** Get a page starting at "first" (although we may also fetch
- * some preceding entries)
- * Recommend to call getSize() before getElementAt() or getElements()
- * since you'd better check if the index is out of bound first.
- *
+ /**
+ * Get a page starting at "first" (although we may also fetch some preceding
+ * entries) Recommend to call getSize() before getElementAt() or
+ * getElements() since you'd better check if the index is out of bound
+ * first.
+ *
* @param first the index of the first entry of the page you want to fetch
*/
- public boolean getPage(int first) {
+ public boolean getPage(int first) {
CMS.debug("getPage " + first);
if (!mInitialized) {
LDAPVirtualListControl cont = new LDAPVirtualListControl(0,
@@ -563,116 +567,131 @@ public class DBVirtualList<E> implements IDBVirtualList<E> {
mPageControls[1] = cont;
}
- //CMS.debug("about to set range first " + first + " mBeforeCount " + mBeforeCount + " mAfterCount " + mAfterCount);
+ // CMS.debug("about to set range first " + first + " mBeforeCount " +
+ // mBeforeCount + " mAfterCount " + mAfterCount);
((LDAPVirtualListControl) mPageControls[1]).setRange(first, mBeforeCount, mAfterCount);
return getPage();
}
- /** Fetch a buffer
+ /**
+ * Fetch a buffer
*/
- private boolean getPage() {
+ private boolean getPage() {
// Get the actual entries
if (!getEntries())
return false;
- // Check if we have a control returned
+ // Check if we have a control returned
LDAPControl[] c = mConn.getResponseControls();
LDAPVirtualListResponse nextCont =
- LDAPVirtualListResponse.parseResponse(c);
+ LDAPVirtualListResponse.parseResponse(c);
if (nextCont != null) {
mSelectedIndex = nextCont.getFirstPosition() - 1;
mTop = Math.max(0, mSelectedIndex - mBeforeCount);
- //CMS.debug("New mTop: " + mTop + " mSelectedIndex " + mSelectedIndex);
+ // CMS.debug("New mTop: " + mTop + " mSelectedIndex " +
+ // mSelectedIndex);
// Now we know the total size of the virtual list box
mSize = nextCont.getContentCount();
((LDAPVirtualListControl) mPageControls[1]).setListSize(mSize);
mInitialized = true;
- //System.out.println( "Virtual window: " + mTop +
- // ".." + (mTop+mEntries.size()-1) +
- // " of " + mSize );
+ // System.out.println( "Virtual window: " + mTop +
+ // ".." + (mTop+mEntries.size()-1) +
+ // " of " + mSize );
} else {
- /*LogDoc
- *
+ /*
+ * LogDoc
+ *
* @phase local ldap search
*/
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_DB, ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_DBS_VL_NULL_RESPONSE"));
+ CMS.getLogMessage("CMSCORE_DBS_VL_NULL_RESPONSE"));
}
return true;
}
- /** Called by application to scroll the list with initial letters.
- * Consider text to be an initial substring of the attribute of the
- * primary sorting key(the first one specified in the sort key array)
- * of an entry.
- * If no entries match, the one just before(or after, if none before)
- * will be returned as mSelectedIndex
- *
+ /**
+ * Called by application to scroll the list with initial letters. Consider
+ * text to be an initial substring of the attribute of the primary sorting
+ * key(the first one specified in the sort key array) of an entry. If no
+ * entries match, the one just before(or after, if none before) will be
+ * returned as mSelectedIndex
+ *
* @param text the prefix of the first entry of the page you want to fetch
*/
public boolean getPage(String text) {
mPageControls[1] =
new LDAPVirtualListControl(text,
- mBeforeCount,
- mAfterCount);
- //System.out.println( "Setting requested start to " +
- // text + ", -" + mBeforeCount + ", +" +
- // mAfterCount );
+ mBeforeCount,
+ mAfterCount);
+ // System.out.println( "Setting requested start to " +
+ // text + ", -" + mBeforeCount + ", +" +
+ // mAfterCount );
return getPage();
}
- /**
- * fetch data of a single list item
- * Recommend to call getSize() before getElementAt() or getElements()
- * since you'd better check if the index is out of bound first.
- * If the index is out of range of the virtual list, an exception will be thrown
- * and return null
- *
+ /**
+ * fetch data of a single list item Recommend to call getSize() before
+ * getElementAt() or getElements() since you'd better check if the index is
+ * out of bound first. If the index is out of range of the virtual list, an
+ * exception will be thrown and return null
+ *
* @param index the index of the element to fetch
*/
public E getElementAt(int index) {
- /* mSize may not be init at this time! Bad !
- * the caller should really check the index is within bound before this
- * but I'll take care of this just in case they are too irresponsible
+ /*
+ * mSize may not be init at this time! Bad ! the caller should really
+ * check the index is within bound before this but I'll take care of
+ * this just in case they are too irresponsible
*/
int baseJumpTo = 0;
if (!mInitialized)
mSize = getSize();
- CMS.debug("getElementAt: " + index + " mTop " + mTop);
-
- //System.out.println( "need entry " + index );
+ CMS.debug("getElementAt: " + index + " mTop " + mTop);
+
+ // System.out.println( "need entry " + index );
if ((index < 0) || (index >= mSize)) {
CMS.debug("returning null");
return null;
}
- if (mJumpTo != null) { //Handle the explicit jumpto case
+ if (mJumpTo != null) { // Handle the explicit jumpto case
if (index == 0)
- mJumpToIndex = 0; // Keep a running jumpto index for this page of data
+ mJumpToIndex = 0; // Keep a running jumpto index for this page
+ // of data
else
mJumpToIndex++;
-
- //CMS.debug("getElementAtJT: " + index + " mTop " + mTop + " mEntries.size() " + mEntries.size());
-
- if ((mJumpToDirection > 0) && (mJumpToInitialIndex + index >= mSize)) // out of data in forward paging jumpto case
+
+ // CMS.debug("getElementAtJT: " + index + " mTop " + mTop +
+ // " mEntries.size() " + mEntries.size());
+
+ if ((mJumpToDirection > 0) && (mJumpToInitialIndex + index >= mSize)) // out
+ // of
+ // data
+ // in
+ // forward
+ // paging
+ // jumpto
+ // case
{
CMS.debug("mJumpTo virtual list exhausted mTop " + mTop + " mSize " + mSize);
return null;
}
-
- if (mJumpToIndex >= mEntries.size()) // In jumpto case, page of data has been exhausted
+
+ if (mJumpToIndex >= mEntries.size()) // In jumpto case, page of data
+ // has been exhausted
{
- mJumpToIndex = 0; // new page will be needed reset running count
+ mJumpToIndex = 0; // new page will be needed reset running count
- if (mJumpToDirection > 0) { //proceed in positive direction past hit point
- getPage(index + mJumpToInitialIndex + 1);
- } else { //proceed backwards from hit point
+ if (mJumpToDirection > 0) { // proceed in positive direction
+ // past hit point
+ getPage(index + mJumpToInitialIndex + 1);
+ } else { // proceed backwards from hit point
if (mTop == 0) {
getPage(0);
CMS.debug("asking for a page less than zero in reverse case, return null");
@@ -681,15 +700,16 @@ public class DBVirtualList<E> implements IDBVirtualList<E> {
CMS.debug("getting page reverse mJumptoIndex " + mJumpToIndex + " mTop " + mTop);
getPage(mTop);
-
+
}
}
- if (mJumpToDirection > 0) // handle getting entry in forward direction
+ if (mJumpToDirection > 0) // handle getting entry in forward
+ // direction
{
return mEntries.elementAt(mJumpToIndex);
- } else { // handle getting entry in reverse direction
+ } else { // handle getting entry in reverse direction
int reverse_index = mEntries.size() - mJumpToIndex - 1;
CMS.debug("reverse direction getting index " + reverse_index);
@@ -702,21 +722,24 @@ public class DBVirtualList<E> implements IDBVirtualList<E> {
}
}
- //CMS.debug("getElementAt noJumpto: " + index);
+ // CMS.debug("getElementAt noJumpto: " + index);
- if ((index < mTop) || (index >= mTop + mEntries.size())) { // handle the non jumpto case
- //fetch a new page
- //System.out.println( "fetching a page starting at " +
- // index );
- // CMS.debug("getElementAt noJumpto: getting page index: " + index + " mEntries.size() " + mEntries.size() + " mTop: " + mTop);
+ if ((index < mTop) || (index >= mTop + mEntries.size())) { // handle the
+ // non jumpto
+ // case
+ // fetch a new page
+ // System.out.println( "fetching a page starting at " +
+ // index );
+ // CMS.debug("getElementAt noJumpto: getting page index: " + index +
+ // " mEntries.size() " + mEntries.size() + " mTop: " + mTop);
getPage(index);
}
int offset = index - mTop;
if ((offset < 0) || (offset >= mEntries.size()))
- //XXX
- return null; //("No entry at " + index);
+ // XXX
+ return null; // ("No entry at " + index);
else
return mEntries.elementAt(offset);
}
@@ -726,20 +749,21 @@ public class DBVirtualList<E> implements IDBVirtualList<E> {
}
/**
- * This function processes elements as soon as it arrives. It is
- * more memory-efficient.
+ * This function processes elements as soon as it arrives. It is more
+ * memory-efficient.
*/
public void processElements(int startidx, int endidx, IElementProcessor ep)
- throws EBaseException {
+ throws EBaseException {
- /* mSize may not be init at this time! Bad !
- * the caller should really check the index is within bound before this
- * but I'll take care of this just in case they are too irresponsible
+ /*
+ * mSize may not be init at this time! Bad ! the caller should really
+ * check the index is within bound before this but I'll take care of
+ * this just in case they are too irresponsible
*/
if (!mInitialized)
mSize = getSize();
- // short-cut the existing code ... :(
+ // short-cut the existing code ... :(
if (mJumpTo != null) {
for (int i = startidx; i <= endidx; i++) {
Object element = getJumpToElementAt(i);
@@ -750,10 +774,10 @@ public class DBVirtualList<E> implements IDBVirtualList<E> {
return;
}
- //guess this is what you really mean to try to improve performance
+ // guess this is what you really mean to try to improve performance
if (startidx >= endidx) {
throw new EBaseException("startidx must be less than endidx");
- }else {
+ } else {
setPageSize(endidx - startidx);
getPage(startidx);
}
@@ -766,14 +790,14 @@ public class DBVirtualList<E> implements IDBVirtualList<E> {
}
}
- /**
+ /**
* get the virutal selected index
*/
public int getSelectedIndex() {
return mSelectedIndex;
}
- /**
+ /**
* get the top of the buffer
*/
public int getFirstIndex() {
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/DateArrayMapper.java b/pki/base/common/src/com/netscape/cmscore/dbs/DateArrayMapper.java
index b8df1240..d0ea2384 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/DateArrayMapper.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/DateArrayMapper.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.util.Date;
import java.util.Enumeration;
import java.util.Vector;
@@ -29,14 +28,12 @@ import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.dbs.IDBAttrMapper;
import com.netscape.certsrv.dbs.IDBObj;
-
/**
- * A class represents ann attribute mapper that maps
- * a Java Date array object into LDAP attribute,
- * and vice versa.
- *
+ * A class represents ann attribute mapper that maps a Java Date array object
+ * into LDAP attribute, and vice versa.
+ *
* @author thomask
- * @version $Revision$, $Date$
+ * @version $Revision$, $Date$
*/
public class DateArrayMapper implements IDBAttrMapper {
@@ -61,9 +58,9 @@ public class DateArrayMapper implements IDBAttrMapper {
/**
* Maps object to a set of attributes.
*/
- public void mapObjectToLDAPAttributeSet(IDBObj parent,
- String name, Object obj, LDAPAttributeSet attrs)
- throws EBaseException {
+ public void mapObjectToLDAPAttributeSet(IDBObj parent,
+ String name, Object obj, LDAPAttributeSet attrs)
+ throws EBaseException {
Date dates[] = (Date[]) obj;
if (dates == null)
@@ -77,11 +74,10 @@ public class DateArrayMapper implements IDBAttrMapper {
}
/**
- * Maps LDAP attributes into object, and put the object
- * into 'parent'.
+ * Maps LDAP attributes into object, and put the object into 'parent'.
*/
- public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
- String name, IDBObj parent) throws EBaseException {
+ public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
+ String name, IDBObj parent) throws EBaseException {
LDAPAttribute attr = attrs.getAttribute(mLdapName);
if (attr == null)
@@ -104,8 +100,8 @@ public class DateArrayMapper implements IDBAttrMapper {
/**
* Maps search filters into LDAP search filter.
*/
- public String mapSearchFilter(String name, String op,
- String value) throws EBaseException {
+ public String mapSearchFilter(String name, String op,
+ String value) throws EBaseException {
return mLdapName + op + value;
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/DateMapper.java b/pki/base/common/src/com/netscape/cmscore/dbs/DateMapper.java
index d547a445..0094159b 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/DateMapper.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/DateMapper.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
@@ -31,12 +30,10 @@ import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.dbs.IDBAttrMapper;
import com.netscape.certsrv.dbs.IDBObj;
-
/**
- * A class represents ann attribute mapper that maps
- * a Java Date object into LDAP attribute,
- * and vice versa.
- *
+ * A class represents ann attribute mapper that maps a Java Date object into
+ * LDAP attribute, and vice versa.
+ *
* @author thomask
* @version $Revision$, $Date$
*/
@@ -45,7 +42,7 @@ public class DateMapper implements IDBAttrMapper {
private String mLdapName = null;
private Vector v = new Vector();
private static SimpleDateFormat formatter = new
- SimpleDateFormat("yyyyMMddHHmmss'Z'");
+ SimpleDateFormat("yyyyMMddHHmmss'Z'");
/**
* Constructs date mapper.
@@ -66,18 +63,17 @@ public class DateMapper implements IDBAttrMapper {
* Maps object to ldap attribute set.
*/
public void mapObjectToLDAPAttributeSet(IDBObj parent,
- String name, Object obj, LDAPAttributeSet attrs)
- throws EBaseException {
- attrs.add(new LDAPAttribute(mLdapName,
+ String name, Object obj, LDAPAttributeSet attrs)
+ throws EBaseException {
+ attrs.add(new LDAPAttribute(mLdapName,
dateToDB((Date) obj)));
}
/**
- * Maps LDAP attributes into object, and put the object
- * into 'parent'.
+ * Maps LDAP attributes into object, and put the object into 'parent'.
*/
public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
- String name, IDBObj parent) throws EBaseException {
+ String name, IDBObj parent) throws EBaseException {
LDAPAttribute attr = attrs.getAttribute(mLdapName);
if (attr == null)
@@ -90,7 +86,7 @@ public class DateMapper implements IDBAttrMapper {
* Maps search filters into LDAP search filter.
*/
public String mapSearchFilter(String name, String op,
- String value) throws EBaseException {
+ String value) throws EBaseException {
String val = null;
try {
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/IntegerMapper.java b/pki/base/common/src/com/netscape/cmscore/dbs/IntegerMapper.java
index c5601a9b..2de316c6 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/IntegerMapper.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/IntegerMapper.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.util.Enumeration;
import java.util.Vector;
@@ -28,14 +27,12 @@ import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.dbs.IDBAttrMapper;
import com.netscape.certsrv.dbs.IDBObj;
-
/**
- * A class represents ann attribute mapper that maps
- * a Java Integer object into LDAP attribute,
- * and vice versa.
- *
+ * A class represents ann attribute mapper that maps a Java Integer object into
+ * LDAP attribute, and vice versa.
+ *
* @author thomask
- * @version $Revision$, $Date$
+ * @version $Revision$, $Date$
*/
public class IntegerMapper implements IDBAttrMapper {
@@ -60,19 +57,18 @@ public class IntegerMapper implements IDBAttrMapper {
/**
* Maps object to ldap attribute set.
*/
- public void mapObjectToLDAPAttributeSet(IDBObj parent,
- String name, Object obj, LDAPAttributeSet attrs)
- throws EBaseException {
- attrs.add(new LDAPAttribute(mLdapName,
+ public void mapObjectToLDAPAttributeSet(IDBObj parent,
+ String name, Object obj, LDAPAttributeSet attrs)
+ throws EBaseException {
+ attrs.add(new LDAPAttribute(mLdapName,
((Integer) obj).toString()));
}
/**
- * Maps LDAP attributes into object, and put the object
- * into 'parent'.
+ * Maps LDAP attributes into object, and put the object into 'parent'.
*/
- public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
- String name, IDBObj parent) throws EBaseException {
+ public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
+ String name, IDBObj parent) throws EBaseException {
LDAPAttribute attr = attrs.getAttribute(mLdapName);
if (attr == null)
@@ -84,8 +80,8 @@ public class IntegerMapper implements IDBAttrMapper {
/**
* Maps search filters into LDAP search filter.
*/
- public String mapSearchFilter(String name, String op,
- String value) throws EBaseException {
+ public String mapSearchFilter(String name, String op,
+ String value) throws EBaseException {
return mLdapName + op + value;
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/KeyDBSchema.java b/pki/base/common/src/com/netscape/cmscore/dbs/KeyDBSchema.java
index ff776424..e940a530 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/KeyDBSchema.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/KeyDBSchema.java
@@ -17,14 +17,10 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
-
-
/**
- * A class represents a collection of key record
- * specific schema information.
+ * A class represents a collection of key record specific schema information.
* <P>
- *
+ *
* @author thomask
* @version $Revision$, $Date$
*/
@@ -43,9 +39,9 @@ public class KeyDBSchema {
public static final String LDAP_ATTR_KEY_SIZE = "keySize";
public static final String LDAP_ATTR_ALGORITHM = "algorithm";
public static final String LDAP_ATTR_STATE = "keyState";
- public static final String LDAP_ATTR_DATE_OF_RECOVERY =
- "dateOfRecovery";
- public static final String LDAP_ATTR_PUBLIC_KEY_FORMAT =
- "publicKeyFormat";
+ public static final String LDAP_ATTR_DATE_OF_RECOVERY =
+ "dateOfRecovery";
+ public static final String LDAP_ATTR_PUBLIC_KEY_FORMAT =
+ "publicKeyFormat";
public static final String LDAP_ATTR_ARCHIVED_BY = "archivedBy";
}
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/KeyRecord.java b/pki/base/common/src/com/netscape/cmscore/dbs/KeyRecord.java
index 2c1265f7..eb16032b 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/KeyRecord.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/KeyRecord.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.math.BigInteger;
import java.util.Date;
import java.util.Enumeration;
@@ -29,14 +28,12 @@ import com.netscape.certsrv.dbs.IDBObj;
import com.netscape.certsrv.dbs.keydb.IKeyRecord;
import com.netscape.certsrv.dbs.keydb.KeyState;
-
/**
- * A class represents a Key record. It maintains the key
- * life cycle as well as other information about an
- * archived key. Namely, whether a key is inactive because
- * of compromise.
+ * A class represents a Key record. It maintains the key life cycle as well as
+ * other information about an archived key. Namely, whether a key is inactive
+ * because of compromise.
* <P>
- *
+ *
* @author thomask
* @version $Revision$, $Date$
*/
@@ -82,14 +79,14 @@ public class KeyRecord implements IDBObj, IKeyRecord {
}
/*
- * Constructs key record.
+ * Constructs key record.
*
* @param key key to be archived
*/
- public KeyRecord(BigInteger serialNo, byte publicData[],
- byte privateData[], String owner,
- String algorithm, String agentId)
- throws EBaseException {
+ public KeyRecord(BigInteger serialNo, byte publicData[],
+ byte privateData[], String owner,
+ String algorithm, String agentId)
+ throws EBaseException {
mSerialNo = serialNo;
mPublicKey = publicData;
mPrivateKey = privateData;
@@ -193,10 +190,10 @@ public class KeyRecord implements IDBObj, IKeyRecord {
}
/**
- * Retrieves serial number of the key record. Each key record
- * is uniquely identified by serial number.
+ * Retrieves serial number of the key record. Each key record is uniquely
+ * identified by serial number.
* <P>
- *
+ *
* @return serial number of this key record
*/
public BigInteger getSerialNumber() throws EBaseException {
@@ -211,10 +208,9 @@ public class KeyRecord implements IDBObj, IKeyRecord {
}
/**
- * Retrieves the key state. This gives key life cycle
- * information.
+ * Retrieves the key state. This gives key life cycle information.
* <P>
- *
+ *
* @return key state
*/
public KeyState getState() throws EBaseException {
@@ -239,7 +235,7 @@ public class KeyRecord implements IDBObj, IKeyRecord {
/**
* Retrieves key.
* <P>
- *
+ *
* @return archived key
*/
public byte[] getPrivateKeyData() throws EBaseException {
@@ -256,7 +252,7 @@ public class KeyRecord implements IDBObj, IKeyRecord {
/**
* Retrieves the key size.
* <P>
- *
+ *
* @return key size
*/
public Integer getKeySize() throws EBaseException {
@@ -280,7 +276,7 @@ public class KeyRecord implements IDBObj, IKeyRecord {
}
/**
- * Sets owner name.
+ * Sets owner name.
* <P>
*/
public void setOwnerName(String name) throws EBaseException {
@@ -338,8 +334,7 @@ public class KeyRecord implements IDBObj, IKeyRecord {
}
/**
- * Retrieves the last modification time of
- * this record.
+ * Retrieves the last modification time of this record.
*/
public Date getModifyTime() {
return mModifyTime;
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/KeyRecordList.java b/pki/base/common/src/com/netscape/cmscore/dbs/KeyRecordList.java
index f4882ffc..dd0c88a9 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/KeyRecordList.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/KeyRecordList.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.util.Enumeration;
import java.util.Vector;
@@ -26,11 +25,10 @@ import com.netscape.certsrv.dbs.IDBVirtualList;
import com.netscape.certsrv.dbs.keydb.IKeyRecord;
import com.netscape.certsrv.dbs.keydb.IKeyRecordList;
-
/**
* A class represents a list of key records.
* <P>
- *
+ *
* @author thomask
* @version $Revision$, $Date$
*/
@@ -46,13 +44,13 @@ public class KeyRecordList implements IKeyRecordList {
}
/**
- * Retrieves the size of key list.
+ * Retrieves the size of key list.
*/
public int getSize() {
return mVlist.getSize();
}
- public int getSizeBeforeJumpTo() {
+ public int getSizeBeforeJumpTo() {
return mVlist.getSizeBeforeJumpTo();
@@ -66,15 +64,17 @@ public class KeyRecordList implements IKeyRecordList {
public IKeyRecord getKeyRecord(int i) {
KeyRecord record = (KeyRecord) mVlist.getElementAt(i);
- if (record == null) return null;
+ if (record == null)
+ return null;
+
+ return record;
+ }
- return record;
- }
/**
* Retrieves requests.
*/
public Enumeration getKeyRecords(int startidx, int endidx)
- throws EBaseException {
+ throws EBaseException {
Vector entries = new Vector();
for (int i = startidx; i <= endidx; i++) {
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/KeyRecordMapper.java b/pki/base/common/src/com/netscape/cmscore/dbs/KeyRecordMapper.java
index 1cbd3229..9218abfd 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/KeyRecordMapper.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/KeyRecordMapper.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.math.BigInteger;
import java.util.Enumeration;
import java.util.Vector;
@@ -33,14 +32,12 @@ import com.netscape.certsrv.dbs.IDBObj;
import com.netscape.certsrv.dbs.keydb.IKeyRecord;
import com.netscape.certsrv.dbs.keydb.IKeyRepository;
import com.netscape.certsrv.logging.ILogger;
-
/**
- * A class represents a mapper to serialize
- * key record into database.
+ * A class represents a mapper to serialize key record into database.
* <P>
- *
- * @author thomask
+ *
+ * @author thomask
* @version $Revision$, $Date$
*/
public class KeyRecordMapper implements IDBAttrMapper {
@@ -59,8 +56,8 @@ public class KeyRecordMapper implements IDBAttrMapper {
return v.elements();
}
- public void mapObjectToLDAPAttributeSet(IDBObj parent, String name,
- Object obj, LDAPAttributeSet attrs) throws EBaseException {
+ public void mapObjectToLDAPAttributeSet(IDBObj parent, String name,
+ Object obj, LDAPAttributeSet attrs) throws EBaseException {
try {
KeyRecord rec = (KeyRecord) obj;
@@ -68,47 +65,51 @@ public class KeyRecordMapper implements IDBAttrMapper {
rec.getSerialNumber().toString()));
} catch (Exception e) {
- /*LogDoc
- *
- * @phase Maps object to ldap attribute set
+ /*
+ * LogDoc
+ *
+ * @phase Maps object to ldap attribute set
+ *
* @message KeyRecordMapper: <exception thrown>
*/
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_DB, ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_DBS_KEYRECORD_MAPPER_ERROR", e.toString()));
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_DB, ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_DBS_KEYRECORD_MAPPER_ERROR", e.toString()));
throw new EDBException(
CMS.getUserMessage("CMS_DBS_SERIALIZE_FAILED", name));
}
}
- public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
- String name, IDBObj parent) throws EBaseException {
- try {
+ public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
+ String name, IDBObj parent) throws EBaseException {
+ try {
LDAPAttribute attr = attrs.getAttribute(
KeyDBSchema.LDAP_ATTR_KEY_RECORD_ID);
if (attr == null)
return;
String serialno = (String) attr.getStringValues().nextElement();
- IKeyRecord rec = mDB.readKeyRecord(new
+ IKeyRecord rec = mDB.readKeyRecord(new
BigInteger(serialno));
parent.set(name, rec);
} catch (Exception e) {
- /*LogDoc
- *
- * @phase Maps ldap attribute set to object
+ /*
+ * LogDoc
+ *
+ * @phase Maps ldap attribute set to object
+ *
* @message KeyRecordMapper: <exception thrown>
*/
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_DB, ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_DBS_KEYRECORD_MAPPER_ERROR", e.toString()));
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_DB, ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_DBS_KEYRECORD_MAPPER_ERROR", e.toString()));
throw new EDBException(
CMS.getUserMessage("CMS_DBS_DESERIALIZE_FAILED", name));
}
}
public String mapSearchFilter(String name, String op, String value)
- throws EBaseException {
+ throws EBaseException {
return name + op + value;
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/KeyRepository.java b/pki/base/common/src/com/netscape/cmscore/dbs/KeyRepository.java
index f684718c..c1278888 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/KeyRepository.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/KeyRepository.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.math.BigInteger;
import java.security.PublicKey;
import java.util.Date;
@@ -39,12 +38,10 @@ import com.netscape.certsrv.dbs.keydb.IKeyRecordList;
import com.netscape.certsrv.dbs.keydb.IKeyRepository;
import com.netscape.certsrv.dbs.repository.IRepository;
-
/**
- * A class represents a Key repository. This is the container of
- * archived keys.
+ * A class represents a Key repository. This is the container of archived keys.
* <P>
- *
+ *
* @author thomask
* @version $Revision$, $Date$
*/
@@ -59,15 +56,15 @@ public class KeyRepository extends Repository implements IKeyRepository {
private String mBaseDN = null;
/**
- * Constructs a key repository. It checks if the key repository
- * does exist. If not, it creates the repository.
+ * Constructs a key repository. It checks if the key repository does exist.
+ * If not, it creates the repository.
* <P>
- *
+ *
* @param service db service
* @exception EBaseException failed to setup key repository
*/
public KeyRepository(IDBSubsystem service, int increment, String baseDN)
- throws EDBException {
+ throws EDBException {
super(service, increment, baseDN);
mBaseDN = baseDN;
mDBService = service;
@@ -81,55 +78,55 @@ public class KeyRepository extends Repository implements IKeyRepository {
if (!reg.isObjectClassRegistered(KeyRecord.class.getName())) {
reg.registerObjectClass(KeyRecord.class.getName(),
- keyRecordOC);
+ keyRecordOC);
}
if (!reg.isAttributeRegistered(KeyRecord.ATTR_ID)) {
reg.registerAttribute(KeyRecord.ATTR_ID, new
- BigIntegerMapper(KeyDBSchema.LDAP_ATTR_SERIALNO));
+ BigIntegerMapper(KeyDBSchema.LDAP_ATTR_SERIALNO));
}
if (!reg.isAttributeRegistered(KeyRecord.ATTR_ALGORITHM)) {
reg.registerAttribute(KeyRecord.ATTR_ALGORITHM, new
- StringMapper(KeyDBSchema.LDAP_ATTR_ALGORITHM));
+ StringMapper(KeyDBSchema.LDAP_ATTR_ALGORITHM));
}
if (!reg.isAttributeRegistered(KeyRecord.ATTR_STATE)) {
reg.registerAttribute(KeyRecord.ATTR_STATE, new
- KeyStateMapper(KeyDBSchema.LDAP_ATTR_STATE));
+ KeyStateMapper(KeyDBSchema.LDAP_ATTR_STATE));
}
if (!reg.isAttributeRegistered(KeyRecord.ATTR_KEY_SIZE)) {
reg.registerAttribute(KeyRecord.ATTR_KEY_SIZE, new
- IntegerMapper(KeyDBSchema.LDAP_ATTR_KEY_SIZE));
+ IntegerMapper(KeyDBSchema.LDAP_ATTR_KEY_SIZE));
}
if (!reg.isAttributeRegistered(KeyRecord.ATTR_OWNER_NAME)) {
reg.registerAttribute(KeyRecord.ATTR_OWNER_NAME, new
- StringMapper(KeyDBSchema.LDAP_ATTR_OWNER_NAME));
+ StringMapper(KeyDBSchema.LDAP_ATTR_OWNER_NAME));
}
if (!reg.isAttributeRegistered(KeyRecord.ATTR_PRIVATE_KEY_DATA)) {
reg.registerAttribute(KeyRecord.ATTR_PRIVATE_KEY_DATA, new
- ByteArrayMapper(KeyDBSchema.LDAP_ATTR_PRIVATE_KEY_DATA));
+ ByteArrayMapper(KeyDBSchema.LDAP_ATTR_PRIVATE_KEY_DATA));
}
if (!reg.isAttributeRegistered(KeyRecord.ATTR_PUBLIC_KEY_DATA)) {
reg.registerAttribute(KeyRecord.ATTR_PUBLIC_KEY_DATA, new
- PublicKeyMapper(KeyDBSchema.LDAP_ATTR_PUBLIC_KEY_DATA));
+ PublicKeyMapper(KeyDBSchema.LDAP_ATTR_PUBLIC_KEY_DATA));
}
if (!reg.isAttributeRegistered(KeyRecord.ATTR_DATE_OF_RECOVERY)) {
reg.registerAttribute(KeyRecord.ATTR_DATE_OF_RECOVERY, new
- DateArrayMapper(KeyDBSchema.LDAP_ATTR_DATE_OF_RECOVERY));
+ DateArrayMapper(KeyDBSchema.LDAP_ATTR_DATE_OF_RECOVERY));
}
if (!reg.isAttributeRegistered(KeyRecord.ATTR_CREATE_TIME)) {
reg.registerAttribute(KeyRecord.ATTR_CREATE_TIME, new
- DateMapper(KeyDBSchema.LDAP_ATTR_CREATE_TIME));
+ DateMapper(KeyDBSchema.LDAP_ATTR_CREATE_TIME));
}
if (!reg.isAttributeRegistered(KeyRecord.ATTR_MODIFY_TIME)) {
reg.registerAttribute(KeyRecord.ATTR_MODIFY_TIME, new
- DateMapper(KeyDBSchema.LDAP_ATTR_MODIFY_TIME));
+ DateMapper(KeyDBSchema.LDAP_ATTR_MODIFY_TIME));
}
if (!reg.isAttributeRegistered(KeyRecord.ATTR_META_INFO)) {
reg.registerAttribute(KeyRecord.ATTR_META_INFO, new
- MetaInfoMapper(KeyDBSchema.LDAP_ATTR_META_INFO));
+ MetaInfoMapper(KeyDBSchema.LDAP_ATTR_META_INFO));
}
if (!reg.isAttributeRegistered(KeyRecord.ATTR_ARCHIVED_BY)) {
reg.registerAttribute(KeyRecord.ATTR_ARCHIVED_BY, new
- StringMapper(KeyDBSchema.LDAP_ATTR_ARCHIVED_BY));
+ StringMapper(KeyDBSchema.LDAP_ATTR_ARCHIVED_BY));
}
}
@@ -147,7 +144,7 @@ public class KeyRepository extends Repository implements IKeyRepository {
CMS.debug("In setKeyStatusUpdateInterval mKeyStatusUpdateThread " + mKeyStatusUpdateThread);
if (mKeyStatusUpdateThread == null) {
CMS.debug("In setKeyStatusUpdateInterval about to create KeyStatusUpdateThread ");
- mKeyStatusUpdateThread = new KeyStatusUpdateThread(this, requestRepo, "KeyStatusUpdateThread");
+ mKeyStatusUpdateThread = new KeyStatusUpdateThread(this, requestRepo, "KeyStatusUpdateThread");
mKeyStatusUpdateThread.setInterval(interval);
mKeyStatusUpdateThread.start();
} else {
@@ -171,15 +168,14 @@ public class KeyRepository extends Repository implements IKeyRepository {
/**
* Removes all objects with this repository.
*/
- public void removeAllObjects() throws EBaseException
- {
+ public void removeAllObjects() throws EBaseException {
String filter = "(" + KeyRecord.ATTR_OWNER_NAME + "=*" + ")";
IKeyRecordList list = findKeyRecordsInList(filter,
null, "serialno", 10);
int size = list.getSize();
Enumeration<IKeyRecord> e = list.getKeyRecords(0, size - 1);
while (e.hasMoreElements()) {
- IKeyRecord rec = e.nextElement();
+ IKeyRecord rec = e.nextElement();
deleteKeyRecord(rec.getSerialNumber());
}
}
@@ -187,7 +183,7 @@ public class KeyRepository extends Repository implements IKeyRepository {
/**
* Archives a key to the repository.
* <P>
- *
+ *
* @param record key record
* @exception EBaseException failed to archive key
*/
@@ -196,34 +192,38 @@ public class KeyRepository extends Repository implements IKeyRepository {
try {
String name = "cn" + "=" +
- ((KeyRecord) record).getSerialNumber().toString() + "," + getDN();
+ ((KeyRecord) record).getSerialNumber().toString() + "," + getDN();
- if (s != null) s.add(name, (KeyRecord) record);
- } finally {
- if (s != null) s.close();
+ if (s != null)
+ s.add(name, (KeyRecord) record);
+ } finally {
+ if (s != null)
+ s.close();
}
}
/**
* Recovers an archived key by serial number.
* <P>
- *
+ *
* @param serialNo serial number
* @return key record
* @exception EBaseException failed to recover key
*/
public IKeyRecord readKeyRecord(BigInteger serialNo)
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
KeyRecord rec = null;
try {
String name = "cn" + "=" +
- serialNo.toString() + "," + getDN();
+ serialNo.toString() + "," + getDN();
- if (s != null) rec = (KeyRecord) s.read(name);
- } finally {
- if (s != null) s.close();
+ if (s != null)
+ rec = (KeyRecord) s.read(name);
+ } finally {
+ if (s != null)
+ s.close();
}
return rec;
}
@@ -231,26 +231,27 @@ public class KeyRepository extends Repository implements IKeyRepository {
/**
* Recovers an archived key by owner name.
* <P>
- *
+ *
* @param ownerName owner name
* @return key record
* @exception EBaseException failed to recover key
*/
public IKeyRecord readKeyRecord(X500Name ownerName)
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
KeyRecord keyRec = null;
try {
if (ownerName != null) {
String filter = "(" + KeyRecord.ATTR_OWNER_NAME + "=" +
- ownerName.toString() + ")";
+ ownerName.toString() + ")";
IDBSearchResults res = s.search(getDN(), filter);
keyRec = (KeyRecord) res.nextElement();
- }
- } finally {
- if (s != null) s.close();
+ }
+ } finally {
+ if (s != null)
+ s.close();
}
return keyRec;
}
@@ -259,7 +260,7 @@ public class KeyRepository extends Repository implements IKeyRepository {
* Recovers archived key using public key.
*/
public IKeyRecord readKeyRecord(PublicKey publicKey)
- throws EBaseException {
+ throws EBaseException {
// XXX - setup binary search attributes
byte data[] = publicKey.getEncoded();
@@ -270,39 +271,40 @@ public class KeyRepository extends Repository implements IKeyRepository {
try {
String filter = "(" + KeyRecord.ATTR_PUBLIC_KEY_DATA + "=" +
- escapeBinaryData(data) + ")";
- if( s != null ) {
+ escapeBinaryData(data) + ")";
+ if (s != null) {
IDBSearchResults res = s.search(getDN(), filter);
rec = (KeyRecord) res.nextElement();
}
- } finally {
- if (s != null) s.close();
+ } finally {
+ if (s != null)
+ s.close();
}
return rec;
}
-
/**
* Recovers archived key using b64 encoded cert
*/
public IKeyRecord readKeyRecord(String cert)
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
KeyRecord rec = null;
try {
- String filter = "(publicKey=x509cert#\"" +cert+"\")";
-CMS.debug("filter= " + filter);
+ String filter = "(publicKey=x509cert#\"" + cert + "\")";
+ CMS.debug("filter= " + filter);
- if( s != null ) {
+ if (s != null) {
IDBSearchResults res = s.search(getDN(), filter);
rec = (KeyRecord) res.nextElement();
}
- } finally {
- if (s != null) s.close();
+ } finally {
+ if (s != null)
+ s.close();
}
return rec;
}
@@ -311,32 +313,36 @@ CMS.debug("filter= " + filter);
* Modifies key record.
*/
public void modifyKeyRecord(BigInteger serialNo, ModificationSet mods)
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
try {
String name = "cn" + "=" +
- serialNo.toString() + "," + getDN();
+ serialNo.toString() + "," + getDN();
mods.add(KeyRecord.ATTR_MODIFY_TIME, Modification.MOD_REPLACE,
- new Date());
- if (s != null) s.modify(name, mods);
- } finally {
- if (s != null) s.close();
+ new Date());
+ if (s != null)
+ s.modify(name, mods);
+ } finally {
+ if (s != null)
+ s.close();
}
}
public void deleteKeyRecord(BigInteger serialNo)
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
try {
String name = "cn" + "=" +
- serialNo.toString() + "," + getDN();
+ serialNo.toString() + "," + getDN();
- if (s != null) s.delete(name);
- } finally {
- if (s != null) s.close();
+ if (s != null)
+ s.delete(name);
+ } finally {
+ if (s != null)
+ s.close();
}
}
@@ -353,7 +359,7 @@ CMS.debug("filter= " + filter);
}
public Enumeration<Object> searchKeys(String filter, int maxSize)
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
Enumeration<Object> e = null;
@@ -367,7 +373,7 @@ CMS.debug("filter= " + filter);
}
public Enumeration<Object> searchKeys(String filter, int maxSize, int timeLimit)
- throws EBaseException {
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
Enumeration<Object> e = null;
@@ -384,14 +390,14 @@ CMS.debug("filter= " + filter);
* Retrieves key record list.
*/
public IKeyRecordList findKeyRecordsInList(String filter,
- String attrs[], int pageSize) throws EBaseException {
+ String attrs[], int pageSize) throws EBaseException {
return findKeyRecordsInList(filter, attrs, IKeyRecord.ATTR_ID,
- pageSize);
+ pageSize);
}
public IKeyRecordList findKeyRecordsInList(String filter,
- String attrs[], String sortKey, int pageSize)
- throws EBaseException {
+ String attrs[], String sortKey, int pageSize)
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
IKeyRecordList list = null;
@@ -399,18 +405,19 @@ CMS.debug("filter= " + filter);
if (s != null) {
list = new KeyRecordList(
s.createVirtualList(getDN(), "(&(objectclass=" +
- KeyRecord.class.getName() + ")" + filter + ")",
- attrs, sortKey, pageSize));
+ KeyRecord.class.getName() + ")" + filter + ")",
+ attrs, sortKey, pageSize));
}
- } finally {
- if (s != null) s.close();
+ } finally {
+ if (s != null)
+ s.close();
}
return list;
}
public IKeyRecordList findKeyRecordsInList(String filter,
- String attrs[],String jumpTo, String sortKey, int pageSize)
- throws EBaseException {
+ String attrs[], String jumpTo, String sortKey, int pageSize)
+ throws EBaseException {
IDBSSession s = mDBService.createSession();
IKeyRecordList list = null;
@@ -419,92 +426,91 @@ CMS.debug("filter= " + filter);
String jumpToVal = null;
if (len > 9) {
- jumpToVal = Integer.toString(len) + jumpTo;
- } else {
- jumpToVal = "0" + Integer.toString(len) + jumpTo;
+ jumpToVal = Integer.toString(len) + jumpTo;
+ } else {
+ jumpToVal = "0" + Integer.toString(len) + jumpTo;
}
try {
if (s != null) {
list = new KeyRecordList(
s.createVirtualList(getDN(), "(&(objectclass=" +
- KeyRecord.class.getName() + ")" + filter + ")",
- attrs,jumpToVal, sortKey, pageSize));
+ KeyRecord.class.getName() + ")" + filter + ")",
+ attrs, jumpToVal, sortKey, pageSize));
}
} finally {
- if (s != null) s.close();
+ if (s != null)
+ s.close();
}
return list;
}
- public BigInteger getLastSerialNumberInRange(BigInteger serial_low_bound, BigInteger serial_upper_bound) throws
- EBaseException {
+ public BigInteger getLastSerialNumberInRange(BigInteger serial_low_bound, BigInteger serial_upper_bound) throws
+ EBaseException {
- CMS.debug("KeyRepository: in getLastSerialNumberInRange: low " + serial_low_bound + " high " + serial_upper_bound);
+ CMS.debug("KeyRepository: in getLastSerialNumberInRange: low " + serial_low_bound + " high " + serial_upper_bound);
- if(serial_low_bound == null || serial_upper_bound == null || serial_low_bound.compareTo(serial_upper_bound) >= 0)
- {
- return null;
- }
+ if (serial_low_bound == null || serial_upper_bound == null || serial_low_bound.compareTo(serial_upper_bound) >= 0) {
+ return null;
+ }
- String ldapfilter = "(" + "serialno" + "=*" + ")";
- String[] attrs = null;
+ String ldapfilter = "(" + "serialno" + "=*" + ")";
+ String[] attrs = null;
- KeyRecordList recList = (KeyRecordList) findKeyRecordsInList(ldapfilter,attrs,serial_upper_bound.toString(10),"serialno", 5 * -1);
+ KeyRecordList recList = (KeyRecordList) findKeyRecordsInList(ldapfilter, attrs, serial_upper_bound.toString(10), "serialno", 5 * -1);
- int size = recList.getSize();
+ int size = recList.getSize();
- CMS.debug("KeyRepository: getLastSerialNumberInRange: recList size " + size);
+ CMS.debug("KeyRepository: getLastSerialNumberInRange: recList size " + size);
- if (size <= 0) {
- CMS.debug("KeyRepository: getLastSerialNumberInRange: index may be empty");
+ if (size <= 0) {
+ CMS.debug("KeyRepository: getLastSerialNumberInRange: index may be empty");
- BigInteger ret = new BigInteger(serial_low_bound.toString(10));
+ BigInteger ret = new BigInteger(serial_low_bound.toString(10));
- ret = ret.add(new BigInteger("-1"));
+ ret = ret.add(new BigInteger("-1"));
- CMS.debug("KeyRepository: getLastSerialNumberInRange returning: " + ret );
- return ret;
- }
- int ltSize = recList.getSizeBeforeJumpTo();
+ CMS.debug("KeyRepository: getLastSerialNumberInRange returning: " + ret);
+ return ret;
+ }
+ int ltSize = recList.getSizeBeforeJumpTo();
- CMS.debug("KeyRepository:getLastSerialNumberInRange: ltSize " + ltSize);
+ CMS.debug("KeyRepository:getLastSerialNumberInRange: ltSize " + ltSize);
- int i;
- KeyRecord curRec = null;
+ int i;
+ KeyRecord curRec = null;
- for (i = 0; i < 5; i++) {
- curRec = (KeyRecord) recList.getKeyRecord(i);
+ for (i = 0; i < 5; i++) {
+ curRec = (KeyRecord) recList.getKeyRecord(i);
- if (curRec != null) {
+ if (curRec != null) {
- BigInteger serial = curRec.getSerialNumber();
+ BigInteger serial = curRec.getSerialNumber();
- CMS.debug("KeyRepository: getLastCertRecordSerialNo: serialno " + serial);
+ CMS.debug("KeyRepository: getLastCertRecordSerialNo: serialno " + serial);
- if( ((serial.compareTo(serial_low_bound) == 0) || (serial.compareTo(serial_low_bound) == 1) ) &&
- ((serial.compareTo(serial_upper_bound) == 0) || (serial.compareTo(serial_upper_bound) == -1) ))
- {
- CMS.debug("KeyRepository: getLastSerialNumberInRange returning: " + serial);
- return serial;
- }
- } else {
- CMS.debug("KeyRepository: getLastSerialNumberInRange:found null from getCertRecord");
- }
- }
+ if (((serial.compareTo(serial_low_bound) == 0) || (serial.compareTo(serial_low_bound) == 1)) &&
+ ((serial.compareTo(serial_upper_bound) == 0) || (serial.compareTo(serial_upper_bound) == -1))) {
+ CMS.debug("KeyRepository: getLastSerialNumberInRange returning: " + serial);
+ return serial;
+ }
+ } else {
+ CMS.debug("KeyRepository: getLastSerialNumberInRange:found null from getCertRecord");
+ }
+ }
- BigInteger ret = new BigInteger(serial_low_bound.toString(10));
+ BigInteger ret = new BigInteger(serial_low_bound.toString(10));
- ret = ret.add(new BigInteger("-1"));
+ ret = ret.add(new BigInteger("-1"));
- CMS.debug("KeyRepository: getLastSerialNumberInRange returning: " + ret );
- return ret ;
+ CMS.debug("KeyRepository: getLastSerialNumberInRange returning: " + ret);
+ return ret;
}
public void shutdown() {
- //if (mKeyStatusUpdateThread != null)
- // mKeyStatusUpdateThread.destroy();
+ // if (mKeyStatusUpdateThread != null)
+ // mKeyStatusUpdateThread.destroy();
}
}
@@ -538,7 +544,7 @@ class KeyStatusUpdateThread extends Thread {
CMS.debug("Starting key checkRanges");
_kr.checkRanges();
CMS.debug("key checkRanges done");
-
+
CMS.debug("Starting request checkRanges");
_rr.checkRanges();
CMS.debug("request checkRanges done");
@@ -553,5 +559,3 @@ class KeyStatusUpdateThread extends Thread {
}
}
}
-
-
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/KeyStateMapper.java b/pki/base/common/src/com/netscape/cmscore/dbs/KeyStateMapper.java
index 7f13c8ed..3da1c795 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/KeyStateMapper.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/KeyStateMapper.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.util.Enumeration;
import java.util.Vector;
@@ -29,13 +28,12 @@ import com.netscape.certsrv.dbs.IDBAttrMapper;
import com.netscape.certsrv.dbs.IDBObj;
import com.netscape.certsrv.dbs.keydb.KeyState;
-
/**
* A class represents a key state mapper.
* <P>
- *
+ *
* @author thomask
- * @version $Revision$, $Date$
+ * @version $Revision$, $Date$
*/
public class KeyStateMapper implements IDBAttrMapper {
@@ -52,19 +50,18 @@ public class KeyStateMapper implements IDBAttrMapper {
return v.elements();
}
- public void mapObjectToLDAPAttributeSet(IDBObj parent,
- String name, Object obj, LDAPAttributeSet attrs)
- throws EBaseException {
- attrs.add(new LDAPAttribute(mLdapName,
+ public void mapObjectToLDAPAttributeSet(IDBObj parent,
+ String name, Object obj, LDAPAttributeSet attrs)
+ throws EBaseException {
+ attrs.add(new LDAPAttribute(mLdapName,
((KeyState) obj).toString()));
}
/**
- * Maps LDAP attributes into object, and put the object
- * into 'parent'.
+ * Maps LDAP attributes into object, and put the object into 'parent'.
*/
- public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
- String name, IDBObj parent) throws EBaseException {
+ public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
+ String name, IDBObj parent) throws EBaseException {
LDAPAttribute attr = attrs.getAttribute(mLdapName);
if (attr == null) {
@@ -77,8 +74,8 @@ public class KeyStateMapper implements IDBAttrMapper {
/**
* Maps search filters into LDAP search filter.
*/
- public String mapSearchFilter(String name, String op,
- String value) throws EBaseException {
+ public String mapSearchFilter(String name, String op,
+ String value) throws EBaseException {
return mLdapName + op + value;
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/LdapFilterConverter.java b/pki/base/common/src/com/netscape/cmscore/dbs/LdapFilterConverter.java
index 909bf47e..1b7b9381 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/LdapFilterConverter.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/LdapFilterConverter.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.util.Hashtable;
import com.netscape.certsrv.base.AttributeNameHelper;
@@ -25,14 +24,12 @@ import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.dbs.IDBAttrMapper;
import com.netscape.certsrv.dbs.IFilterConverter;
-
/**
- * A class represents a filter converter
- * that understands how to convert a attribute
- * type from one defintion to another.
+ * A class represents a filter converter that understands how to convert a
+ * attribute type from one defintion to another.
*
* @author thomask
- * @version $Revision$, $Date$
+ * @version $Revision$, $Date$
*/
public class LdapFilterConverter implements IFilterConverter {
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/LongMapper.java b/pki/base/common/src/com/netscape/cmscore/dbs/LongMapper.java
index cdd9aeb7..a97f2703 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/LongMapper.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/LongMapper.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.util.Enumeration;
import java.util.Vector;
@@ -28,14 +27,12 @@ import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.dbs.IDBAttrMapper;
import com.netscape.certsrv.dbs.IDBObj;
-
/**
- * A class represents ann attribute mapper that maps
- * a Java Long object into LDAP attribute,
- * and vice versa.
- *
+ * A class represents ann attribute mapper that maps a Java Long object into
+ * LDAP attribute, and vice versa.
+ *
* @author thomask
- * @version $Revision$, $Date$
+ * @version $Revision$, $Date$
*/
public class LongMapper implements IDBAttrMapper {
@@ -60,19 +57,18 @@ public class LongMapper implements IDBAttrMapper {
/**
* Maps object into ldap attribute set.
*/
- public void mapObjectToLDAPAttributeSet(IDBObj parent,
- String name, Object obj, LDAPAttributeSet attrs)
- throws EBaseException {
- attrs.add(new LDAPAttribute(mLdapName,
+ public void mapObjectToLDAPAttributeSet(IDBObj parent,
+ String name, Object obj, LDAPAttributeSet attrs)
+ throws EBaseException {
+ attrs.add(new LDAPAttribute(mLdapName,
LongToDB((Long) obj)));
}
/**
- * Maps LDAP attributes into object, and put the object
- * into 'parent'.
+ * Maps LDAP attributes into object, and put the object into 'parent'.
*/
- public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
- String name, IDBObj parent) throws EBaseException {
+ public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
+ String name, IDBObj parent) throws EBaseException {
LDAPAttribute attr = attrs.getAttribute(mLdapName);
if (attr == null)
@@ -84,8 +80,8 @@ public class LongMapper implements IDBAttrMapper {
/**
* Maps search filters into LDAP search filter.
*/
- public String mapSearchFilter(String name, String op,
- String value) throws EBaseException {
+ public String mapSearchFilter(String name, String op,
+ String value) throws EBaseException {
String v = null;
try {
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/MetaInfoMapper.java b/pki/base/common/src/com/netscape/cmscore/dbs/MetaInfoMapper.java
index 605e2fad..8cd0656e 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/MetaInfoMapper.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/MetaInfoMapper.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.Vector;
@@ -30,20 +29,19 @@ import com.netscape.certsrv.base.MetaInfo;
import com.netscape.certsrv.dbs.IDBAttrMapper;
import com.netscape.certsrv.dbs.IDBObj;
-
/**
- * A class represent mapper for metainfo attribute. Metainfo
- * is in format of the following:
- *
+ * A class represent mapper for metainfo attribute. Metainfo is in format of the
+ * following:
+ *
* <PRE>
* metaInfoType:metaInfoValue
* metaInfoType:metaInfoValue
* metaInfoType:metaInfoValue
* metaInfoType:metaInfoValue
* </PRE>
- *
+ *
* @author thomask
- * @version $Revision$, $Date$
+ * @version $Revision$, $Date$
*/
public class MetaInfoMapper implements IDBAttrMapper {
@@ -71,8 +69,8 @@ public class MetaInfoMapper implements IDBAttrMapper {
* Maps object into ldap attribute set.
*/
public void mapObjectToLDAPAttributeSet(IDBObj parent,
- String name, Object obj, LDAPAttributeSet attrs)
- throws EBaseException {
+ String name, Object obj, LDAPAttributeSet attrs)
+ throws EBaseException {
MetaInfo info = (MetaInfo) obj;
Enumeration e = info.getElements();
@@ -92,11 +90,10 @@ public class MetaInfoMapper implements IDBAttrMapper {
}
/**
- * Maps LDAP attributes into object, and put the object into
- * 'parent'.
+ * Maps LDAP attributes into object, and put the object into 'parent'.
*/
public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
- String name, IDBObj parent) throws EBaseException {
+ String name, IDBObj parent) throws EBaseException {
LDAPAttribute attr = attrs.getAttribute(mLdapName);
if (attr == null)
@@ -114,12 +111,11 @@ public class MetaInfoMapper implements IDBAttrMapper {
}
/**
- * Map search filters into LDAP search filter.
- * Possible search filter:
+ * Map search filters into LDAP search filter. Possible search filter:
* (&(metaInfo=reserver0:value0)(metaInfo=reserved1:value1))
*/
public String mapSearchFilter(String name, String op,
- String value) throws EBaseException {
+ String value) throws EBaseException {
return mLdapName + op + value;
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/ObjectStreamMapper.java b/pki/base/common/src/com/netscape/cmscore/dbs/ObjectStreamMapper.java
index 46979715..f0aa6936 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/ObjectStreamMapper.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/ObjectStreamMapper.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -35,15 +34,13 @@ import com.netscape.certsrv.dbs.EDBException;
import com.netscape.certsrv.dbs.IDBAttrMapper;
import com.netscape.certsrv.dbs.IDBObj;
import com.netscape.certsrv.logging.ILogger;
-
/**
- * A class represents ann attribute mapper that maps
- * a Java object into LDAP attribute,
- * and vice versa.
- *
+ * A class represents ann attribute mapper that maps a Java object into LDAP
+ * attribute, and vice versa.
+ *
* @author thomask
- * @version $Revision$, $Date$
+ * @version $Revision$, $Date$
*/
public class ObjectStreamMapper implements IDBAttrMapper {
@@ -69,9 +66,9 @@ public class ObjectStreamMapper implements IDBAttrMapper {
/**
* Maps object to ldap attribute set.
*/
- public void mapObjectToLDAPAttributeSet(IDBObj parent, String name,
- Object obj, LDAPAttributeSet attrs)
- throws EBaseException {
+ public void mapObjectToLDAPAttributeSet(IDBObj parent, String name,
+ Object obj, LDAPAttributeSet attrs)
+ throws EBaseException {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(bos);
@@ -79,35 +76,36 @@ public class ObjectStreamMapper implements IDBAttrMapper {
os.writeObject(obj);
byte data[] = bos.toByteArray();
if (data == null) {
- CMS.debug("ObjectStreamMapper:mapObjectToLDAPAttributeSet " +
+ CMS.debug("ObjectStreamMapper:mapObjectToLDAPAttributeSet " +
name + " size=0");
} else {
- CMS.debug("ObjectStreamMapper:mapObjectToLDAPAttributeSet " +
+ CMS.debug("ObjectStreamMapper:mapObjectToLDAPAttributeSet " +
name + " size=" + data.length);
}
- attrs.add(new LDAPAttribute(mLdapName,
+ attrs.add(new LDAPAttribute(mLdapName,
data));
} catch (IOException e) {
- /*LogDoc
- *
+ /*
+ * LogDoc
+ *
* @phase Maps object to ldap attribute set
+ *
* @message ObjectStreamMapper: <exception thrown>
*/
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_DB, ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_DBS_OBJECTSTREAM_MAPPER_ERROR",
- e.toString()));
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_DB, ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_DBS_OBJECTSTREAM_MAPPER_ERROR",
+ e.toString()));
throw new EDBException(
CMS.getUserMessage("CMS_DBS_SERIALIZE_FAILED", name));
}
}
/**
- * Maps LDAP attributes into object, and put the object
- * into 'parent'.
+ * Maps LDAP attributes into object, and put the object into 'parent'.
*/
- public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
- String name, IDBObj parent) throws EBaseException {
+ public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
+ String name, IDBObj parent) throws EBaseException {
try {
LDAPAttribute attr = attrs.getAttribute(mLdapName);
@@ -131,8 +129,8 @@ public class ObjectStreamMapper implements IDBAttrMapper {
/**
* Maps search filters into LDAP search filter.
*/
- public String mapSearchFilter(String name, String op,
- String value) throws EBaseException {
+ public String mapSearchFilter(String name, String op,
+ String value) throws EBaseException {
return mLdapName + op + value;
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/PublicKeyMapper.java b/pki/base/common/src/com/netscape/cmscore/dbs/PublicKeyMapper.java
index 8a2d1f2d..88aeda3a 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/PublicKeyMapper.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/PublicKeyMapper.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
@@ -32,16 +31,14 @@ import com.netscape.certsrv.dbs.IDBAttrMapper;
import com.netscape.certsrv.dbs.IDBObj;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.cmscore.cert.CertUtils;
-
/**
- * A class represents an attribute mapper that maps
- * a public key data into LDAP attribute and
- * vice versa.
+ * A class represents an attribute mapper that maps a public key data into LDAP
+ * attribute and vice versa.
* <P>
- *
+ *
* @author thomask
- * @version $Revision$, $Date$
+ * @version $Revision$, $Date$
*/
public class PublicKeyMapper implements IDBAttrMapper {
@@ -68,18 +65,17 @@ public class PublicKeyMapper implements IDBAttrMapper {
/**
* Maps object to ldap attribute set.
*/
- public void mapObjectToLDAPAttributeSet(IDBObj parent,
- String name, Object obj, LDAPAttributeSet attrs)
- throws EBaseException {
+ public void mapObjectToLDAPAttributeSet(IDBObj parent,
+ String name, Object obj, LDAPAttributeSet attrs)
+ throws EBaseException {
attrs.add(new LDAPAttribute(mLdapName, (byte[]) obj));
}
/**
- * Maps LDAP attributes into object, and put the object
- * into 'parent'.
+ * Maps LDAP attributes into object, and put the object into 'parent'.
*/
- public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
- String name, IDBObj parent) throws EBaseException {
+ public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
+ String name, IDBObj parent) throws EBaseException {
LDAPAttribute attr = attrs.getAttribute(mLdapName);
if (attr == null) {
@@ -89,11 +85,11 @@ public class PublicKeyMapper implements IDBAttrMapper {
}
/**
- * Maps search filters into LDAP search filter. It knows
- * how to extract public key from the certificate.
+ * Maps search filters into LDAP search filter. It knows how to extract
+ * public key from the certificate.
*/
- public String mapSearchFilter(String name, String op,
- String value) throws EBaseException {
+ public String mapSearchFilter(String name, String op,
+ String value) throws EBaseException {
int i = value.indexOf("#");
if (i != -1) {
@@ -111,14 +107,16 @@ public class PublicKeyMapper implements IDBAttrMapper {
return mLdapName + op + escapeBinaryData(pub);
} catch (Exception e) {
- /*LogDoc
- *
+ /*
+ * LogDoc
+ *
* @phase Maps search filters into LDAP search filter
+ *
* @message PublicKeyMapper: <exception thrown>
*/
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_DB, ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_DBS_PUBLICKEY_MAPPER_ERROR",
- e.toString()));
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_DB, ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_DBS_PUBLICKEY_MAPPER_ERROR",
+ e.toString()));
}
}
return mLdapName + op + value;
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/ReplicaIDRepository.java b/pki/base/common/src/com/netscape/cmscore/dbs/ReplicaIDRepository.java
index 61beb423..4e79cd89 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/ReplicaIDRepository.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/ReplicaIDRepository.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.math.BigInteger;
import com.netscape.certsrv.apps.CMS;
@@ -27,15 +26,15 @@ import com.netscape.certsrv.dbs.IDBSubsystem;
import com.netscape.certsrv.dbs.replicadb.IReplicaIDRepository;
/**
- * A class represents a replica repository. It
- * creates unique managed replica IDs.
+ * A class represents a replica repository. It creates unique managed replica
+ * IDs.
* <P>
- *
+ *
* @author alee
* @version $Revision$, $Date$
*/
public class ReplicaIDRepository extends Repository
- implements IReplicaIDRepository {
+ implements IReplicaIDRepository {
private IDBSubsystem mDBService;
private String mBaseDN;
@@ -44,24 +43,23 @@ public class ReplicaIDRepository extends Repository
* Constructs a certificate repository.
*/
public ReplicaIDRepository(IDBSubsystem dbService, int increment, String baseDN)
- throws EDBException {
+ throws EDBException {
super(dbService, increment, baseDN);
mBaseDN = baseDN;
mDBService = dbService;
}
-
-
+
/**
* Returns last serial number in given range
*/
public BigInteger getLastSerialNumberInRange(BigInteger serial_low_bound, BigInteger serial_upper_bound)
- throws EBaseException {
- CMS.debug("ReplicaIDReposoitory: in getLastSerialNumberInRange: low " + serial_low_bound + " high " + serial_upper_bound);
- if(serial_low_bound == null || serial_upper_bound == null || serial_low_bound.compareTo(serial_upper_bound) >= 0 ) {
+ throws EBaseException {
+ CMS.debug("ReplicaIDReposoitory: in getLastSerialNumberInRange: low " + serial_low_bound + " high " + serial_upper_bound);
+ if (serial_low_bound == null || serial_upper_bound == null || serial_low_bound.compareTo(serial_upper_bound) >= 0) {
return null;
}
BigInteger ret = new BigInteger(getMinSerial());
- if ((ret==null) || (ret.compareTo(serial_upper_bound) >0) || (ret.compareTo(serial_low_bound) <0)) {
+ if ((ret == null) || (ret.compareTo(serial_upper_bound) > 0) || (ret.compareTo(serial_low_bound) < 0)) {
return null;
}
return ret;
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/Repository.java b/pki/base/common/src/com/netscape/cmscore/dbs/Repository.java
index 858e7a63..494da26c 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/Repository.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/Repository.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.math.BigInteger;
import com.netscape.certsrv.apps.CMS;
@@ -36,18 +35,17 @@ import com.netscape.certsrv.dbs.repository.IRepository;
import com.netscape.certsrv.dbs.repository.IRepositoryRecord;
/**
- * A class represents a generic repository. It maintains unique
- * serial number within repository.
+ * A class represents a generic repository. It maintains unique serial number
+ * within repository.
* <P>
- * To build domain specific repository, subclass should be
- * created.
+ * To build domain specific repository, subclass should be created.
* <P>
- *
+ *
* @author galperin
* @author thomask
* @version $Revision: 1.4
- *
- $, $Date$
+ *
+ * $, $Date$
*/
public abstract class Repository implements IRepository {
@@ -56,7 +54,7 @@ public abstract class Repository implements IRepository {
private BigInteger BI_INCREMENT = null;
private static final BigInteger BI_ZERO = new BigInteger("0");
// (the next serialNo to be issued) - 1
- private BigInteger mSerialNo = null;
+ private BigInteger mSerialNo = null;
// the serialNo attribute stored in db
private BigInteger mNext = null;
@@ -79,51 +77,45 @@ public abstract class Repository implements IRepository {
private int mRadix = 10;
private int mRepo = -1;
-
private BigInteger mLastSerialNo = null;
+
/**
* Constructs a repository.
* <P>
*/
- public Repository(IDBSubsystem db, int increment, String baseDN)
- throws EDBException {
+ public Repository(IDBSubsystem db, int increment, String baseDN)
+ throws EDBException {
mDB = db;
mBaseDN = baseDN;
-
BI_INCREMENT = new BigInteger(Integer.toString(increment));
// register schema
IDBRegistry reg = db.getRegistry();
/**
- if (!reg.isObjectClassRegistered(
- RepositoryRecord.class.getName())) {
- String repRecordOC[] = new String[2];
- repRecordOC[0] = RepositorySchema.LDAP_OC_TOP;
- repRecordOC[1] = RepositorySchema.LDAP_OC_REPOSITORY;
- reg.registerObjectClass(
- RepositoryRecord.class.getName(), repRecordOC);
- }
- if (!reg.isAttributeRegistered(RepositoryRecord.ATTR_SERIALNO)) {
- reg.registerAttribute(RepositoryRecord.ATTR_SERIALNO,
- new BigIntegerMapper(RepositorySchema.LDAP_ATTR_SERIALNO));
- }
+ * if (!reg.isObjectClassRegistered( RepositoryRecord.class.getName()))
+ * { String repRecordOC[] = new String[2]; repRecordOC[0] =
+ * RepositorySchema.LDAP_OC_TOP; repRecordOC[1] =
+ * RepositorySchema.LDAP_OC_REPOSITORY; reg.registerObjectClass(
+ * RepositoryRecord.class.getName(), repRecordOC); } if
+ * (!reg.isAttributeRegistered(RepositoryRecord.ATTR_SERIALNO)) {
+ * reg.registerAttribute(RepositoryRecord.ATTR_SERIALNO, new
+ * BigIntegerMapper(RepositorySchema.LDAP_ATTR_SERIALNO)); }
**/
}
/**
* Resets serial number.
*/
- public void resetSerialNumber(BigInteger serial) throws EBaseException
- {
+ public void resetSerialNumber(BigInteger serial) throws EBaseException {
IDBSSession s = mDB.createSession();
-
+
try {
String name = mBaseDN;
ModificationSet mods = new ModificationSet();
mods.add(IRepositoryRecord.ATTR_SERIALNO,
- Modification.MOD_REPLACE, serial);
+ Modification.MOD_REPLACE, serial);
s.modify(name, mods);
} finally {
if (s != null)
@@ -134,7 +126,7 @@ public abstract class Repository implements IRepository {
/**
* Retrieves the next serial number attr in db.
* <P>
- *
+ *
* @return next serial number
*/
protected BigInteger getSerialNumber() throws EBaseException {
@@ -144,21 +136,23 @@ public abstract class Repository implements IRepository {
RepositoryRecord rec = null;
try {
- if (s != null) rec = (RepositoryRecord) s.read(mBaseDN);
- } finally {
- if (s != null) s.close();
+ if (s != null)
+ rec = (RepositoryRecord) s.read(mBaseDN);
+ } finally {
+ if (s != null)
+ s.close();
}
- if( rec == null ) {
- CMS.debug( "Repository::getSerialNumber() - "
- + "- rec is null!" );
- throw new EBaseException( "rec is null" );
+ if (rec == null) {
+ CMS.debug("Repository::getSerialNumber() - "
+ + "- rec is null!");
+ throw new EBaseException("rec is null");
}
BigInteger serial = rec.getSerialNumber();
if (!mInit) {
- // cms may crash after issue a cert but before update
+ // cms may crash after issue a cert but before update
// the serial number record
try {
IDBObj obj = s.read("cn=" +
@@ -168,7 +162,7 @@ public abstract class Repository implements IRepository {
serial = serial.add(BI_ONE);
setSerialNumber(serial);
}
- }catch (EBaseException e) {
+ } catch (EBaseException e) {
// do nothing
}
mInit = true;
@@ -179,12 +173,12 @@ public abstract class Repository implements IRepository {
/**
* Updates the serial number to the specified in db.
* <P>
- *
+ *
* @param num serial number
*/
protected void setSerialNumber(BigInteger num) throws EBaseException {
- CMS.debug("Repository:setSerialNumber " + num.toString());
+ CMS.debug("Repository:setSerialNumber " + num.toString());
return;
@@ -211,8 +205,8 @@ public abstract class Repository implements IRepository {
maxSerial = new BigInteger(serial, mRadix);
if (maxSerial != null) {
- mMaxSerial = serial;
- mMaxSerialNo = maxSerial;
+ mMaxSerial = serial;
+ mMaxSerialNo = maxSerial;
}
}
@@ -229,7 +223,8 @@ public abstract class Repository implements IRepository {
* Set the maximum serial number in next range
*
* @param serial maximum number in next range
- * @exception EBaseException failed to set maximum serial number in next range
+ * @exception EBaseException failed to set maximum serial number in next
+ * range
*/
public void setNextMaxSerial(String serial) throws EBaseException {
BigInteger maxSerial = null;
@@ -237,23 +232,22 @@ public abstract class Repository implements IRepository {
maxSerial = new BigInteger(serial, mRadix);
if (maxSerial != null) {
- mNextMaxSerial = serial;
- mNextMaxSerialNo = maxSerial;
+ mNextMaxSerial = serial;
+ mNextMaxSerialNo = maxSerial;
}
return;
}
-
+
/**
* Get the minimum serial number.
*
* @return minimum serial number
*/
public String getMinSerial() {
- return mMinSerial;
+ return mMinSerial;
}
-
/**
* init serial number cache
*/
@@ -261,16 +255,17 @@ public abstract class Repository implements IRepository {
mNext = getSerialNumber();
BigInteger serialConfig = new BigInteger("0");
mRadix = 10;
-
+
CMS.debug("Repository: in InitCache");
if (this instanceof ICertificateRepository) {
CMS.debug("Repository: Instance of Certificate Repository.");
mRadix = 16;
mRepo = IDBSubsystem.CERTS;
- } else if (this instanceof IKeyRepository) {
- // Key Repository uses the same configuration parameters as Certificate
- // Repository. This is ok because they are on separate subsystems.
+ } else if (this instanceof IKeyRepository) {
+ // Key Repository uses the same configuration parameters as
+ // Certificate
+ // Repository. This is ok because they are on separate subsystems.
CMS.debug("Repository: Instance of Key Repository");
mRadix = 16;
mRepo = IDBSubsystem.CERTS;
@@ -278,7 +273,8 @@ public abstract class Repository implements IRepository {
CMS.debug("Repository: Instance of Replica ID repository");
mRepo = IDBSubsystem.REPLICA_ID;
} else {
- // CRLRepository subclasses this too, but does not use serial number stuff
+ // CRLRepository subclasses this too, but does not use serial number
+ // stuff
CMS.debug("Repository: Instance of Request Repository or CRLRepository.");
mRepo = IDBSubsystem.REQUESTS;
}
@@ -292,48 +288,47 @@ public abstract class Repository implements IRepository {
CMS.debug("Repository: minSerial " + mMinSerial + " maxSerial: " + mMaxSerial);
- if(mMinSerial != null)
- mMinSerialNo = new BigInteger(mMinSerial,mRadix);
+ if (mMinSerial != null)
+ mMinSerialNo = new BigInteger(mMinSerial, mRadix);
- if(mMaxSerial != null)
- mMaxSerialNo = new BigInteger(mMaxSerial,mRadix);
+ if (mMaxSerial != null)
+ mMaxSerialNo = new BigInteger(mMaxSerial, mRadix);
- if(mNextMinSerial != null)
- mNextMinSerialNo = new BigInteger(mNextMinSerial,mRadix);
+ if (mNextMinSerial != null)
+ mNextMinSerialNo = new BigInteger(mNextMinSerial, mRadix);
- if(mNextMaxSerial != null)
- mNextMaxSerialNo = new BigInteger(mNextMaxSerial,mRadix);
+ if (mNextMaxSerial != null)
+ mNextMaxSerialNo = new BigInteger(mNextMaxSerial, mRadix);
- if(lowWaterMark != null)
- mLowWaterMarkNo = new BigInteger(lowWaterMark,mRadix);
+ if (lowWaterMark != null)
+ mLowWaterMarkNo = new BigInteger(lowWaterMark, mRadix);
- if(increment != null)
- mIncrementNo = new BigInteger(increment,mRadix);
+ if (increment != null)
+ mIncrementNo = new BigInteger(increment, mRadix);
BigInteger theSerialNo = null;
- theSerialNo = getLastSerialNumberInRange(mMinSerialNo,mMaxSerialNo);
+ theSerialNo = getLastSerialNumberInRange(mMinSerialNo, mMaxSerialNo);
- if(theSerialNo != null) {
+ if (theSerialNo != null) {
mLastSerialNo = new BigInteger(theSerialNo.toString());
CMS.debug("Repository: mLastSerialNo: " + mLastSerialNo.toString());
- }
- else {
+ } else {
throw new EBaseException("Error in obtaining the last serial number in the repository!");
}
}
-
+
/**
* get the next serial number in cache
*/
public BigInteger getTheSerialNumber() throws EBaseException {
-
- CMS.debug("Repository:In getTheSerialNumber " );
- if (mLastSerialNo == null)
+
+ CMS.debug("Repository:In getTheSerialNumber ");
+ if (mLastSerialNo == null)
initCache();
BigInteger serial = new BigInteger((mLastSerialNo.add(BI_ONE)).toString());
@@ -346,7 +341,7 @@ public abstract class Repository implements IRepository {
/**
* Updates the serial number to the specified in db and cache.
* <P>
- *
+ *
* @param num serial number
*/
public void setTheSerialNumber(BigInteger num) throws EBaseException {
@@ -370,46 +365,45 @@ public abstract class Repository implements IRepository {
}
/**
- * Retrieves the next serial number, and also increase the
- * serial number by one.
+ * Retrieves the next serial number, and also increase the serial number by
+ * one.
* <P>
- *
+ *
* @return serial number
*/
public synchronized BigInteger getNextSerialNumber() throws
EBaseException {
CMS.debug("Repository: in getNextSerialNumber. ");
-
+
if (mLastSerialNo == null) {
initCache();
mLastSerialNo = mLastSerialNo.add(BI_ONE);
-
-
+
} else {
mLastSerialNo = mLastSerialNo.add(BI_ONE);
}
- if( mLastSerialNo == null ) {
- CMS.debug( "Repository::getNextSerialNumber() " +
- "- mLastSerialNo is null!" );
- throw new EBaseException( "mLastSerialNo is null" );
+ if (mLastSerialNo == null) {
+ CMS.debug("Repository::getNextSerialNumber() " +
+ "- mLastSerialNo is null!");
+ throw new EBaseException("mLastSerialNo is null");
}
// check if we have reached the end of the range
// if so, move to next range
- if (mLastSerialNo.compareTo( mMaxSerialNo ) > 0 ) {
+ if (mLastSerialNo.compareTo(mMaxSerialNo) > 0) {
if (mDB.getEnableSerialMgmt()) {
CMS.debug("Reached the end of the range. Attempting to move to next range");
mMinSerialNo = mNextMinSerialNo;
mMaxSerialNo = mNextMaxSerialNo;
mLastSerialNo = mMinSerialNo;
- mNextMinSerialNo = null;
- mNextMaxSerialNo = null;
+ mNextMinSerialNo = null;
+ mNextMaxSerialNo = null;
if ((mMaxSerialNo == null) || (mMinSerialNo == null)) {
throw new EDBException(CMS.getUserMessage("CMS_DBS_LIMIT_REACHED",
- mLastSerialNo.toString()));
+ mLastSerialNo.toString()));
}
// persist the changes
@@ -426,17 +420,16 @@ public abstract class Repository implements IRepository {
BigInteger retSerial = new BigInteger(mLastSerialNo.toString());
CMS.debug("Repository: getNextSerialNumber: returning retSerial " + retSerial);
- return retSerial;
+ return retSerial;
}
/**
- * Checks to see if a new range is needed, or if we have reached the end of the
- * current range, or if a range conflict has occurred.
- *
+ * Checks to see if a new range is needed, or if we have reached the end of
+ * the current range, or if a range conflict has occurred.
+ *
* @exception EBaseException failed to check next range for conflicts
*/
- public void checkRanges() throws EBaseException
- {
+ public void checkRanges() throws EBaseException {
if (!mDB.getEnableSerialMgmt()) {
CMS.debug("Serial Management not enabled. Returning .. ");
return;
@@ -464,7 +457,7 @@ public abstract class Repository implements IRepository {
CMS.debug("Serial Numbers available: " + numsAvail.toString());
}
- if ((numsAvail.compareTo(mLowWaterMarkNo) < 0) && (!CMS.isPreOpMode()) ) {
+ if ((numsAvail.compareTo(mLowWaterMarkNo) < 0) && (!CMS.isPreOpMode())) {
CMS.debug("Low water mark reached. Requesting next range");
mNextMinSerialNo = new BigInteger(mDB.getNextRange(mRepo), mRadix);
if (mNextMinSerialNo == null) {
@@ -478,31 +471,29 @@ public abstract class Repository implements IRepository {
}
}
- if (numsInRange.compareTo (mLowWaterMarkNo) < 0 ) {
+ if (numsInRange.compareTo(mLowWaterMarkNo) < 0) {
// check for a replication error
CMS.debug("Checking for a range conflict");
if (mDB.hasRangeConflict(mRepo)) {
- CMS.debug("Range Conflict found! Removing next range.");
- mNextMaxSerialNo = null;
- mNextMinSerialNo= null;
- mDB.setNextMinSerialConfig(mRepo, null);
- mDB.setNextMaxSerialConfig(mRepo, null);
+ CMS.debug("Range Conflict found! Removing next range.");
+ mNextMaxSerialNo = null;
+ mNextMinSerialNo = null;
+ mDB.setNextMinSerialConfig(mRepo, null);
+ mDB.setNextMaxSerialConfig(mRepo, null);
}
- }
+ }
}
/**
- * Sets whether serial number management is enabled for certs
- * and requests.
- *
- * @param value true/false
- * @exception EBaseException failed to set
+ * Sets whether serial number management is enabled for certs and requests.
+ *
+ * @param value true/false
+ * @exception EBaseException failed to set
*/
- public void setEnableSerialMgmt(boolean value) throws EBaseException
- {
+ public void setEnableSerialMgmt(boolean value) throws EBaseException {
mDB.setEnableSerialMgmt(value);
- }
+ }
- public abstract BigInteger getLastSerialNumberInRange(BigInteger serial_low_bound, BigInteger serial_upper_bound) throws
- EBaseException;
+ public abstract BigInteger getLastSerialNumberInRange(BigInteger serial_low_bound, BigInteger serial_upper_bound) throws
+ EBaseException;
}
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/RepositoryRecord.java b/pki/base/common/src/com/netscape/cmscore/dbs/RepositoryRecord.java
index 97cedac8..0a79b4b9 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/RepositoryRecord.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/RepositoryRecord.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.math.BigInteger;
import java.util.Enumeration;
import java.util.Vector;
@@ -26,11 +25,10 @@ import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.dbs.repository.IRepositoryRecord;
-
/**
* A class represents a repository record.
* <P>
- *
+ *
* @author thomask
* @version $Revision$, $Date$
*/
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/RepositorySchema.java b/pki/base/common/src/com/netscape/cmscore/dbs/RepositorySchema.java
index 67cc5c1c..a926187f 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/RepositorySchema.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/RepositorySchema.java
@@ -17,14 +17,10 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
-
-
/**
- * A class represents a collection of repository-specific
- * schema information.
+ * A class represents a collection of repository-specific schema information.
* <P>
- *
+ *
* @author thomask
* @version $Revision$, $Date$
*/
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/RevocationInfo.java b/pki/base/common/src/com/netscape/cmscore/dbs/RevocationInfo.java
index 001089fb..87da8b91 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/RevocationInfo.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/RevocationInfo.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.io.Serializable;
import java.util.Date;
@@ -26,13 +25,12 @@ import netscape.security.x509.CRLReasonExtension;
import com.netscape.certsrv.dbs.certdb.IRevocationInfo;
-
/**
- * A class represents a certificate revocation info. This
- * object is written as an attribute of certificate record
- * which essentially signifies a revocation act.
+ * A class represents a certificate revocation info. This object is written as
+ * an attribute of certificate record which essentially signifies a revocation
+ * act.
* <P>
- *
+ *
* @author galperin
* @version $Revision$, $Date$
*/
@@ -52,11 +50,10 @@ public class RevocationInfo implements IRevocationInfo, Serializable {
}
/**
- * Constructs revocation info used by revocation
- * request implementation.
- *
- * @param reason if not null contains CRL entry extension
- * that specifies revocation reason
+ * Constructs revocation info used by revocation request implementation.
+ *
+ * @param reason if not null contains CRL entry extension that specifies
+ * revocation reason
* @see CRLReasonExtension
*/
public RevocationInfo(Date revocationDate, CRLExtensions exts) {
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/RevocationInfoMapper.java b/pki/base/common/src/com/netscape/cmscore/dbs/RevocationInfoMapper.java
index c0949f66..d7198f6a 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/RevocationInfoMapper.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/RevocationInfoMapper.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.util.Date;
import java.util.Enumeration;
import java.util.Vector;
@@ -37,13 +36,12 @@ import com.netscape.certsrv.dbs.IDBAttrMapper;
import com.netscape.certsrv.dbs.IDBObj;
import com.netscape.cmscore.util.Debug;
-
/**
- * A class represents a mapper to serialize
- * revocation information into database.
+ * A class represents a mapper to serialize revocation information into
+ * database.
* <P>
- *
- * @author thomask
+ *
+ * @author thomask
* @version $Revision$, $Date$
*/
public class RevocationInfoMapper implements IDBAttrMapper {
@@ -63,9 +61,9 @@ public class RevocationInfoMapper implements IDBAttrMapper {
return mNames.elements();
}
- public void mapObjectToLDAPAttributeSet(IDBObj parent, String name,
- Object obj, LDAPAttributeSet attrs)
- throws EBaseException {
+ public void mapObjectToLDAPAttributeSet(IDBObj parent, String name,
+ Object obj, LDAPAttributeSet attrs)
+ throws EBaseException {
try {
// in format of <date>;<extensions>
String value = "";
@@ -82,22 +80,22 @@ public class RevocationInfoMapper implements IDBAttrMapper {
Extension ext = e.nextElement();
if (ext instanceof CRLReasonExtension) {
- RevocationReason reason =
- ((CRLReasonExtension) ext).getReason();
+ RevocationReason reason =
+ ((CRLReasonExtension) ext).getReason();
- value = value + ";CRLReasonExtension=" +
+ value = value + ";CRLReasonExtension=" +
Integer.toString(reason.toInt());
} else if (ext instanceof InvalidityDateExtension) {
- Date invalidityDate =
- ((InvalidityDateExtension) ext).getInvalidityDate();
+ Date invalidityDate =
+ ((InvalidityDateExtension) ext).getInvalidityDate();
- value = value + ";InvalidityDateExtension=" +
+ value = value + ";InvalidityDateExtension=" +
DateMapper.dateToDB(invalidityDate);
} else {
Debug.trace("XXX skipped extension");
}
}
- attrs.add(new LDAPAttribute(CertDBSchema.LDAP_ATTR_REVO_INFO,
+ attrs.add(new LDAPAttribute(CertDBSchema.LDAP_ATTR_REVO_INFO,
value));
} catch (Exception e) {
Debug.trace(e.toString());
@@ -106,8 +104,8 @@ public class RevocationInfoMapper implements IDBAttrMapper {
}
}
- public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
- String name, IDBObj parent) throws EBaseException {
+ public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
+ String name, IDBObj parent) throws EBaseException {
try {
LDAPAttribute attr = attrs.getAttribute(
CertDBSchema.LDAP_ATTR_REVO_INFO);
@@ -148,15 +146,14 @@ public class RevocationInfoMapper implements IDBAttrMapper {
String invalidityDateStr = str.substring(24);
Date invalidityDate = DateMapper.dateFromDB(invalidityDateStr);
InvalidityDateExtension ext =
- new InvalidityDateExtension(invalidityDate);
+ new InvalidityDateExtension(invalidityDate);
exts.set(InvalidityDateExtension.class.getSimpleName(), ext);
} else {
Debug.trace("XXX skipped extension");
}
- }
- while (i != -1);
- }
+ } while (i != -1);
+ }
RevocationInfo info = new RevocationInfo(d, exts);
parent.set(name, info);
@@ -168,7 +165,7 @@ public class RevocationInfoMapper implements IDBAttrMapper {
}
public String mapSearchFilter(String name, String op, String value)
- throws EBaseException {
+ throws EBaseException {
return CertDBSchema.LDAP_ATTR_REVO_INFO + op + value;
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/StringMapper.java b/pki/base/common/src/com/netscape/cmscore/dbs/StringMapper.java
index 39fdac87..c4a8ca96 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/StringMapper.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/StringMapper.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.util.Enumeration;
import java.util.NoSuchElementException;
import java.util.Vector;
@@ -29,14 +28,12 @@ import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.dbs.IDBAttrMapper;
import com.netscape.certsrv.dbs.IDBObj;
-
/**
- * A class represents ann attribute mapper that maps
- * a Java String object into LDAP attribute,
- * and vice versa.
- *
+ * A class represents ann attribute mapper that maps a Java String object into
+ * LDAP attribute, and vice versa.
+ *
* @author thomask
- * @version $Revision$, $Date$
+ * @version $Revision$, $Date$
*/
public class StringMapper implements IDBAttrMapper {
@@ -61,19 +58,18 @@ public class StringMapper implements IDBAttrMapper {
/**
* Maps attribute value to ldap attributes.
*/
- public void mapObjectToLDAPAttributeSet(IDBObj parent,
- String name, Object obj, LDAPAttributeSet attrs)
- throws EBaseException {
+ public void mapObjectToLDAPAttributeSet(IDBObj parent,
+ String name, Object obj, LDAPAttributeSet attrs)
+ throws EBaseException {
attrs.add(new LDAPAttribute(mLdapName, (String) obj));
}
/**
- * Maps LDAP attributes into object, and put the object
- * into 'parent'.
+ * Maps LDAP attributes into object, and put the object into 'parent'.
*/
- public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
- String name, IDBObj parent)
- throws EBaseException {
+ public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
+ String name, IDBObj parent)
+ throws EBaseException {
LDAPAttribute attr = attrs.getAttribute(mLdapName);
if (attr == null) {
@@ -81,7 +77,7 @@ public class StringMapper implements IDBAttrMapper {
}
try {
parent.set(name, (String)
- attr.getStringValues().nextElement());
+ attr.getStringValues().nextElement());
} catch (NoSuchElementException e) {
// attribute present, but without value
}
@@ -90,8 +86,8 @@ public class StringMapper implements IDBAttrMapper {
/**
* Maps search filters into LDAP search filter.
*/
- public String mapSearchFilter(String name, String op,
- String value) throws EBaseException {
+ public String mapSearchFilter(String name, String op,
+ String value) throws EBaseException {
return mLdapName + op + value;
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/StringVectorMapper.java b/pki/base/common/src/com/netscape/cmscore/dbs/StringVectorMapper.java
index d14470a2..3269e61a 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/StringVectorMapper.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/StringVectorMapper.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.util.Enumeration;
import java.util.Vector;
@@ -28,14 +27,12 @@ import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.dbs.IDBAttrMapper;
import com.netscape.certsrv.dbs.IDBObj;
-
/**
- * A class represents ann attribute mapper that maps
- * a Java String object into LDAP attribute,
- * and vice versa.
- *
+ * A class represents ann attribute mapper that maps a Java String object into
+ * LDAP attribute, and vice versa.
+ *
* @author thomask
- * @version $Revision$, $Date$
+ * @version $Revision$, $Date$
*/
public class StringVectorMapper implements IDBAttrMapper {
@@ -60,9 +57,9 @@ public class StringVectorMapper implements IDBAttrMapper {
/**
* Maps attribute value to ldap attributes.
*/
- public void mapObjectToLDAPAttributeSet(IDBObj parent,
- String name, Object obj, LDAPAttributeSet attrs)
- throws EBaseException {
+ public void mapObjectToLDAPAttributeSet(IDBObj parent,
+ String name, Object obj, LDAPAttributeSet attrs)
+ throws EBaseException {
Vector v = (Vector) obj;
int s = v.size();
@@ -78,11 +75,10 @@ public class StringVectorMapper implements IDBAttrMapper {
}
/**
- * Maps LDAP attributes into object, and put the object
- * into 'parent'.
+ * Maps LDAP attributes into object, and put the object into 'parent'.
*/
- public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
- String name, IDBObj parent) throws EBaseException {
+ public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
+ String name, IDBObj parent) throws EBaseException {
LDAPAttribute attr = attrs.getAttribute(mLdapName);
if (attr == null)
@@ -104,8 +100,8 @@ public class StringVectorMapper implements IDBAttrMapper {
/**
* Maps search filters into LDAP search filter.
*/
- public String mapSearchFilter(String name, String op,
- String value) throws EBaseException {
+ public String mapSearchFilter(String name, String op,
+ String value) throws EBaseException {
return mLdapName + op + value;
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/X500NameMapper.java b/pki/base/common/src/com/netscape/cmscore/dbs/X500NameMapper.java
index 963c2fdc..a2b2ea1c 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/X500NameMapper.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/X500NameMapper.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.io.IOException;
import java.util.Enumeration;
import java.util.Vector;
@@ -32,15 +31,13 @@ import com.netscape.certsrv.dbs.EDBException;
import com.netscape.certsrv.dbs.IDBAttrMapper;
import com.netscape.certsrv.dbs.IDBObj;
import com.netscape.certsrv.logging.ILogger;
-
/**
- * A class represents ann attribute mapper that maps
- * a Java X500Name object into LDAP attribute,
- * and vice versa.
- *
+ * A class represents ann attribute mapper that maps a Java X500Name object into
+ * LDAP attribute, and vice versa.
+ *
* @author thomask
- * @version $Revision$, $Date$
+ * @version $Revision$, $Date$
*/
public class X500NameMapper implements IDBAttrMapper {
@@ -67,19 +64,18 @@ public class X500NameMapper implements IDBAttrMapper {
/**
* Maps attribute value to ldap attributes.
*/
- public void mapObjectToLDAPAttributeSet(IDBObj parent,
- String name, Object obj, LDAPAttributeSet attrs)
- throws EBaseException {
- attrs.add(new LDAPAttribute(mLdapName,
+ public void mapObjectToLDAPAttributeSet(IDBObj parent,
+ String name, Object obj, LDAPAttributeSet attrs)
+ throws EBaseException {
+ attrs.add(new LDAPAttribute(mLdapName,
((X500Name) obj).toString()));
}
/**
- * Maps LDAP attributes into object, and put the object
- * into 'parent'.
+ * Maps LDAP attributes into object, and put the object into 'parent'.
*/
- public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
- String name, IDBObj parent) throws EBaseException {
+ public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
+ String name, IDBObj parent) throws EBaseException {
LDAPAttribute attr = attrs.getAttribute(mLdapName);
if (attr == null) {
@@ -90,14 +86,16 @@ public class X500NameMapper implements IDBAttrMapper {
attr.getStringValues().nextElement()));
} catch (IOException e) {
- /*LogDoc
- *
+ /*
+ * LogDoc
+ *
* @phase Maps LDAP attributes into object
+ *
* @message X500NameMapper: <exception thrown>
*/
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_DB, ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_DBS_X500NAME_MAPPER_ERROR",
- e.toString()));
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_DB, ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_DBS_X500NAME_MAPPER_ERROR",
+ e.toString()));
throw new EDBException(
CMS.getUserMessage("CMS_DBS_DESERIALIZE_FAILED", name));
}
@@ -106,8 +104,8 @@ public class X500NameMapper implements IDBAttrMapper {
/**
* Maps search filters into LDAP search filter.
*/
- public String mapSearchFilter(String name, String op,
- String value) throws EBaseException {
+ public String mapSearchFilter(String name, String op,
+ String value) throws EBaseException {
return mLdapName + op + value;
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/dbs/X509CertImplMapper.java b/pki/base/common/src/com/netscape/cmscore/dbs/X509CertImplMapper.java
index 9acf05f2..63ec1e12 100644
--- a/pki/base/common/src/com/netscape/cmscore/dbs/X509CertImplMapper.java
+++ b/pki/base/common/src/com/netscape/cmscore/dbs/X509CertImplMapper.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.dbs;
-
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.util.Date;
@@ -43,12 +42,10 @@ import com.netscape.certsrv.dbs.IDBAttrMapper;
import com.netscape.certsrv.dbs.IDBObj;
import com.netscape.certsrv.dbs.certdb.ICertRecord;
-
/**
- * A class represents a mapper to serialize
- * x509 certificate into database.
- *
- * @author thomask
+ * A class represents a mapper to serialize x509 certificate into database.
+ *
+ * @author thomask
* @version $Revision$, $Date$
*/
public class X509CertImplMapper implements IDBAttrMapper {
@@ -72,23 +69,23 @@ public class X509CertImplMapper implements IDBAttrMapper {
return v.elements();
}
- public void mapObjectToLDAPAttributeSet(IDBObj parent, String name,
- Object obj, LDAPAttributeSet attrs) throws EBaseException {
+ public void mapObjectToLDAPAttributeSet(IDBObj parent, String name,
+ Object obj, LDAPAttributeSet attrs) throws EBaseException {
try {
X509CertImpl cert = (X509CertImpl) obj;
// make information searchable
Date notBefore = cert.getNotBefore();
attrs.add(new LDAPAttribute(
- CertDBSchema.LDAP_ATTR_NOT_BEFORE,
+ CertDBSchema.LDAP_ATTR_NOT_BEFORE,
DateMapper.dateToDB(notBefore)));
Date notAfter = cert.getNotAfter();
- attrs.add(new LDAPAttribute(CertDBSchema.LDAP_ATTR_NOT_AFTER,
+ attrs.add(new LDAPAttribute(CertDBSchema.LDAP_ATTR_NOT_AFTER,
DateMapper.dateToDB(notAfter)));
- attrs.add(new LDAPAttribute(CertDBSchema.LDAP_ATTR_DURATION,
+ attrs.add(new LDAPAttribute(CertDBSchema.LDAP_ATTR_DURATION,
DBSUtil.longToDB(notAfter.getTime() - notBefore.getTime())));
- attrs.add(new LDAPAttribute(CertDBSchema.LDAP_ATTR_SUBJECT,
+ attrs.add(new LDAPAttribute(CertDBSchema.LDAP_ATTR_SUBJECT,
cert.getSubjectDN().getName()));
attrs.add(new LDAPAttribute(CertDBSchema.LDAP_ATTR_PUBLIC_KEY_DATA, cert.getPublicKey().getEncoded()));
// make extension searchable
@@ -119,7 +116,7 @@ public class X509CertImplMapper implements IDBAttrMapper {
if (critSet != null) {
for (Iterator<String> i = critSet.iterator(); i.hasNext();) {
- String oid = i.next();
+ String oid = i.next();
if (oid.equals("2.16.840.1.113730.1.1")) {
String extVal = getCertTypeExtensionInfo(cert);
@@ -145,19 +142,19 @@ public class X509CertImplMapper implements IDBAttrMapper {
// not know how to display the certificate in
// pretty print format.
attrs.add(new LDAPAttribute(
- CertDBSchema.LDAP_ATTR_SIGNED_CERT + ";binary",
+ CertDBSchema.LDAP_ATTR_SIGNED_CERT + ";binary",
cert.getEncoded()));
attrs.add(new LDAPAttribute(
- CertDBSchema.LDAP_ATTR_VERSION,
+ CertDBSchema.LDAP_ATTR_VERSION,
Integer.toString(cert.getVersion())));
X509Key pubKey = (X509Key) cert.getPublicKey();
attrs.add(new LDAPAttribute(
- CertDBSchema.LDAP_ATTR_ALGORITHM,
+ CertDBSchema.LDAP_ATTR_ALGORITHM,
pubKey.getAlgorithmId().getOID().toString()));
attrs.add(new LDAPAttribute(
- CertDBSchema.LDAP_ATTR_SIGNING_ALGORITHM,
+ CertDBSchema.LDAP_ATTR_SIGNING_ALGORITHM,
cert.getSigAlgOID()));
} catch (CertificateEncodingException e) {
throw new EDBException(
@@ -203,7 +200,7 @@ public class X509CertImplMapper implements IDBAttrMapper {
Boolean objectSigning = (Boolean) nsExt.get(
NSCertTypeExtension.OBJECT_SIGNING);
- result += "objectSigning=" +
+ result += "objectSigning=" +
objectSigning.toString();
return result;
} catch (Exception e) {
@@ -240,8 +237,8 @@ public class X509CertImplMapper implements IDBAttrMapper {
}
}
- public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
- String name, IDBObj parent) throws EBaseException {
+ public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
+ String name, IDBObj parent) throws EBaseException {
try {
// rebuild object quickly using binary image
// XXX bad! when we add this attribute,
@@ -249,8 +246,8 @@ public class X509CertImplMapper implements IDBAttrMapper {
// we retrieve it, DS returns it as
// userCertificate;binary. So I cannot do the
// following:
- // LDAPAttribute attr = attrs.getAttribute(
- // Schema.LDAP_ATTR_SIGNED_CERT);
+ // LDAPAttribute attr = attrs.getAttribute(
+ // Schema.LDAP_ATTR_SIGNED_CERT);
X509CertInfo certinfo = new X509CertInfo();
LDAPAttribute attr = attrs.getAttribute(
@@ -263,39 +260,39 @@ public class X509CertImplMapper implements IDBAttrMapper {
}
if (attr != null) {
byte der[] = (byte[])
- attr.getByteValues().nextElement();
+ attr.getByteValues().nextElement();
X509CertImpl impl = new X509CertImpl(der);
parent.set(name, impl);
}
} catch (CertificateException e) {
- //throw new EDBException(
- // DBResources.FAILED_TO_DESERIALIZE_1, name);
+ // throw new EDBException(
+ // DBResources.FAILED_TO_DESERIALIZE_1, name);
parent.set(name, null);
} catch (Exception e) {
- //throw new EDBException(
- // DBResources.FAILED_TO_DESERIALIZE_1, name);
+ // throw new EDBException(
+ // DBResources.FAILED_TO_DESERIALIZE_1, name);
parent.set(name, null);
-
+
}
}
public String mapSearchFilter(String name, String op, String value)
- throws EBaseException {
+ throws EBaseException {
AttributeNameHelper h = new AttributeNameHelper(name);
String suffix = h.getSuffix();
if (suffix.equalsIgnoreCase(ICertRecord.X509CERT_NOT_BEFORE)) {
name = CertDBSchema.LDAP_ATTR_NOT_BEFORE;
try {
- value = DateMapper.dateToDB(new
+ value = DateMapper.dateToDB(new
Date(Long.parseLong(value)));
} catch (NumberFormatException e) {
}
} else if (suffix.equalsIgnoreCase(ICertRecord.X509CERT_NOT_AFTER)) {
name = CertDBSchema.LDAP_ATTR_NOT_AFTER;
try {
- value = DateMapper.dateToDB(new
+ value = DateMapper.dateToDB(new
Date(Long.parseLong(value)));
} catch (NumberFormatException e) {
}
@@ -313,15 +310,15 @@ public class X509CertImplMapper implements IDBAttrMapper {
} else if (suffix.equalsIgnoreCase(ICertRecord.X509CERT_SIGNING_ALGORITHM)) {
name = CertDBSchema.LDAP_ATTR_SIGNING_ALGORITHM;
} else if (suffix.equalsIgnoreCase(ICertRecord.X509CERT_SERIAL_NUMBER)) {
- name = CertDBSchema.LDAP_ATTR_CERT_RECORD_ID;
+ name = CertDBSchema.LDAP_ATTR_CERT_RECORD_ID;
} else if (suffix.equalsIgnoreCase(ICertRecord.X509CERT_EXTENSION)) {
- name = CertDBSchema.LDAP_ATTR_EXTENSION;
+ name = CertDBSchema.LDAP_ATTR_EXTENSION;
} else if (suffix.equalsIgnoreCase(ICertRecord.ATTR_REVO_INFO)) {
- name = CertDBSchema.LDAP_ATTR_REVO_INFO;
+ name = CertDBSchema.LDAP_ATTR_REVO_INFO;
value = "*;CRLReasonExtension=" + value + "*";
} else if (suffix.equalsIgnoreCase("nsExtension.SSLClient")) {
// special case for NS cert type extension
- name = CertDBSchema.LDAP_ATTR_EXTENSION;
+ name = CertDBSchema.LDAP_ATTR_EXTENSION;
if (value.equals("on")) {
value = "2.16.840.1.113730.1.1;*SSLClient=true*";
} else {
@@ -329,7 +326,7 @@ public class X509CertImplMapper implements IDBAttrMapper {
}
} else if (suffix.equalsIgnoreCase("nsExtension.SSLServer")) {
// special case for NS cert type extension
- name = CertDBSchema.LDAP_ATTR_EXTENSION;
+ name = CertDBSchema.LDAP_ATTR_EXTENSION;
if (value.equals("on")) {
value = "2.16.840.1.113730.1.1;*SSLServer=true*";
} else {
@@ -337,7 +334,7 @@ public class X509CertImplMapper implements IDBAttrMapper {
}
} else if (suffix.equalsIgnoreCase("nsExtension.SecureEmail")) {
// special case for NS cert type extension
- name = CertDBSchema.LDAP_ATTR_EXTENSION;
+ name = CertDBSchema.LDAP_ATTR_EXTENSION;
if (value.equals("on")) {
value = "2.16.840.1.113730.1.1;*Email=true*";
} else {
@@ -345,7 +342,7 @@ public class X509CertImplMapper implements IDBAttrMapper {
}
} else if (suffix.equalsIgnoreCase("nsExtension.SubordinateSSLCA")) {
// special case for NS cert type extension
- name = CertDBSchema.LDAP_ATTR_EXTENSION;
+ name = CertDBSchema.LDAP_ATTR_EXTENSION;
if (value.equals("on")) {
value = "2.16.840.1.113730.1.1;*SSLCA=true*";
} else {
@@ -353,7 +350,7 @@ public class X509CertImplMapper implements IDBAttrMapper {
}
} else if (suffix.equalsIgnoreCase("nsExtension.SubordinateEmailCA")) {
// special case for NS cert type extension
- name = CertDBSchema.LDAP_ATTR_EXTENSION;
+ name = CertDBSchema.LDAP_ATTR_EXTENSION;
if (value.equals("on")) {
value = "2.16.840.1.113730.1.1;*EmailCA=true*";
} else {
@@ -361,7 +358,7 @@ public class X509CertImplMapper implements IDBAttrMapper {
}
} else if (suffix.equalsIgnoreCase("BasicConstraints.isCA")) {
// special case for Basic Constraints extension
- name = CertDBSchema.LDAP_ATTR_EXTENSION;
+ name = CertDBSchema.LDAP_ATTR_EXTENSION;
if (value.equals("on")) {
value = "2.5.29.19;*isCA=true*";
} else {
diff --git a/pki/base/common/src/com/netscape/cmscore/extensions/CMSExtensionsMap.java b/pki/base/common/src/com/netscape/cmscore/extensions/CMSExtensionsMap.java
index b0fe0432..a4e90f61 100644
--- a/pki/base/common/src/com/netscape/cmscore/extensions/CMSExtensionsMap.java
+++ b/pki/base/common/src/com/netscape/cmscore/extensions/CMSExtensionsMap.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.extensions;
-
import java.util.Enumeration;
import java.util.Hashtable;
@@ -30,10 +29,9 @@ import com.netscape.certsrv.base.ISubsystem;
import com.netscape.certsrv.extensions.EExtensionsException;
import com.netscape.certsrv.extensions.ICMSExtension;
-
-/**
- * Loads extension classes from configuration file and return
- * for a given extension name or OID.
+/**
+ * Loads extension classes from configuration file and return for a given
+ * extension name or OID.
*/
public class CMSExtensionsMap implements ISubsystem {
public static String ID = "extensions";
@@ -56,10 +54,11 @@ public class CMSExtensionsMap implements ISubsystem {
/**
* Create extensions from configuration store.
+ *
* @param config the configuration store.
*/
- public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ public void init(ISubsystem owner, IConfigStore config)
+ throws EBaseException {
mOwner = owner;
mConfig = config;
@@ -82,11 +81,11 @@ public class CMSExtensionsMap implements ISubsystem {
} catch (IllegalAccessException e) {
throw new EExtensionsException(
CMS.getUserMessage("CMS_EXTENSION_INSTANTIATE_ERROR",
- className, e.toString()));
+ className, e.toString()));
} catch (InstantiationException e) {
throw new EExtensionsException(
CMS.getUserMessage("CMS_EXTENSION_INSTANTIATE_ERROR",
- className, e.toString()));
+ className, e.toString()));
} catch (ClassCastException e) {
throw new EExtensionsException(
CMS.getUserMessage("CMS_EXTENSION_INVALID_IMPL", className));
@@ -101,7 +100,7 @@ public class CMSExtensionsMap implements ISubsystem {
if (name == null || oid == null) {
throw new EExtensionsException(
CMS.getUserMessage("CMS_EXTENSION_INCORRECT_IMPL",
- ext.getClass().getName()));
+ ext.getClass().getName()));
}
mName2Ext.put(name, ext);
mOID2Ext.put(oid.toString(), ext);
@@ -120,29 +119,30 @@ public class CMSExtensionsMap implements ISubsystem {
}
/**
- * Get configuration store.
+ * Get configuration store.
*/
public IConfigStore getConfigStore() {
return mConfig;
}
/**
- * Returns subsystem ID
+ * Returns subsystem ID
*/
public String getId() {
return ID;
}
/**
- * sets subsystem ID
+ * sets subsystem ID
*/
public void setId(String Id) {
}
/**
* Get the extension class by name.
+ *
* @param name name of the extension
- * @return the extension class.
+ * @return the extension class.
*/
public ICMSExtension getByName(String name) {
return (ICMSExtension) mName2Ext.get(name);
@@ -150,6 +150,7 @@ public class CMSExtensionsMap implements ISubsystem {
/**
* Get the extension class by its OID.
+ *
* @param oid - the OID of the extension.
* @return the extension class.
*/
diff --git a/pki/base/common/src/com/netscape/cmscore/extensions/KeyUsage.java b/pki/base/common/src/com/netscape/cmscore/extensions/KeyUsage.java
index 9b8e16cf..bba95949 100644
--- a/pki/base/common/src/com/netscape/cmscore/extensions/KeyUsage.java
+++ b/pki/base/common/src/com/netscape/cmscore/extensions/KeyUsage.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.extensions;
-
import java.io.IOException;
import netscape.security.util.DerOutputStream;
@@ -36,7 +35,6 @@ import com.netscape.certsrv.extensions.ICMSExtension;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.cmscore.util.Debug;
-
public class KeyUsage implements ICMSExtension {
private final static String NAME = "KeyUsageExtension";
private final static ObjectIdentifier OID = PKIXExtensions.KeyUsage_Id;
@@ -49,24 +47,24 @@ public class KeyUsage implements ICMSExtension {
public KeyUsage(boolean setDefault) {
mSetDefault = setDefault;
mLogger = CMS.getLogger();
- }
+ }
- public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ public void init(ISubsystem owner, IConfigStore config)
+ throws EBaseException {
// nothing to do here.
mConfig = config;
}
- public String getName() {
- return NAME;
+ public String getName() {
+ return NAME;
}
- public ObjectIdentifier getOID() {
- return OID;
+ public ObjectIdentifier getOID() {
+ return OID;
}
- protected static final boolean[] DEF_BITS =
- new boolean[KeyUsageExtension.NBITS];
+ protected static final boolean[] DEF_BITS =
+ new boolean[KeyUsageExtension.NBITS];
static {
// set default bits used when request missing key usage info.
@@ -84,10 +82,10 @@ public class KeyUsage implements ICMSExtension {
private static boolean getBoolean(Object value) {
String val = (String) value;
- if (val != null &&
- (val.equalsIgnoreCase("true") || val.equalsIgnoreCase("on")))
+ if (val != null &&
+ (val.equalsIgnoreCase("true") || val.equalsIgnoreCase("on")))
return true;
- else
+ else
return false;
}
@@ -120,13 +118,13 @@ public class KeyUsage implements ICMSExtension {
int i;
for (i = 0; i < KeyUsageExtension.NBITS; i++) {
- if (values[i] != null && (values[i] instanceof String))
+ if (values[i] != null && (values[i] instanceof String))
break;
}
if (i == KeyUsageExtension.NBITS && mSetDefault) {
// no key usage extension parameters are requested. set default.
CMS.debug(
- "No Key usage bits requested. Setting default.");
+ "No Key usage bits requested. Setting default.");
bits = DEF_BITS;
} else {
bit = KeyUsageExtension.DIGITAL_SIGNATURE_BIT;
@@ -171,15 +169,15 @@ public class KeyUsage implements ICMSExtension {
int j = 0;
for (j = 0; j < bits.length; j++) {
- if (bits[j])
+ if (bits[j])
break;
}
if (j == bits.length) {
- if (!mSetDefault)
+ if (!mSetDefault)
return null;
- else
+ else
bits = DEF_BITS;
- }
+ }
return new KeyUsageExtension(bits);
} catch (IOException e) {
throw new EExtensionsException(
@@ -188,7 +186,7 @@ public class KeyUsage implements ICMSExtension {
}
public IArgBlock getFormParams(Extension extension)
- throws EBaseException {
+ throws EBaseException {
KeyUsageExtension ext = null;
if (!extension.getExtensionId().equals(PKIXExtensions.KeyUsage_Id)) {
@@ -210,26 +208,25 @@ public class KeyUsage implements ICMSExtension {
IArgBlock params = CMS.createArgBlock();
boolean[] bits = ext.getBits();
- params.set(KeyUsageExtension.DIGITAL_SIGNATURE,
- String.valueOf(bits[KeyUsageExtension.DIGITAL_SIGNATURE_BIT]));
+ params.set(KeyUsageExtension.DIGITAL_SIGNATURE,
+ String.valueOf(bits[KeyUsageExtension.DIGITAL_SIGNATURE_BIT]));
params.set(KeyUsageExtension.NON_REPUDIATION,
- String.valueOf(bits[KeyUsageExtension.NON_REPUDIATION_BIT]));
+ String.valueOf(bits[KeyUsageExtension.NON_REPUDIATION_BIT]));
params.set(KeyUsageExtension.KEY_ENCIPHERMENT,
- String.valueOf(bits[KeyUsageExtension.KEY_ENCIPHERMENT_BIT]));
+ String.valueOf(bits[KeyUsageExtension.KEY_ENCIPHERMENT_BIT]));
params.set(KeyUsageExtension.DATA_ENCIPHERMENT,
- String.valueOf(bits[KeyUsageExtension.DATA_ENCIPHERMENT_BIT]));
+ String.valueOf(bits[KeyUsageExtension.DATA_ENCIPHERMENT_BIT]));
params.set(KeyUsageExtension.KEY_AGREEMENT,
- String.valueOf(bits[KeyUsageExtension.KEY_AGREEMENT_BIT]));
+ String.valueOf(bits[KeyUsageExtension.KEY_AGREEMENT_BIT]));
params.set(KeyUsageExtension.KEY_CERTSIGN,
- String.valueOf(bits[KeyUsageExtension.KEY_CERTSIGN_BIT]));
+ String.valueOf(bits[KeyUsageExtension.KEY_CERTSIGN_BIT]));
params.set(KeyUsageExtension.CRL_SIGN,
- String.valueOf(bits[KeyUsageExtension.CRL_SIGN_BIT]));
- params.set(KeyUsageExtension.ENCIPHER_ONLY,
- String.valueOf(bits[KeyUsageExtension.ENCIPHER_ONLY_BIT]));
+ String.valueOf(bits[KeyUsageExtension.CRL_SIGN_BIT]));
+ params.set(KeyUsageExtension.ENCIPHER_ONLY,
+ String.valueOf(bits[KeyUsageExtension.ENCIPHER_ONLY_BIT]));
params.set(KeyUsageExtension.DECIPHER_ONLY,
- String.valueOf(bits[KeyUsageExtension.DECIPHER_ONLY_BIT]));
+ String.valueOf(bits[KeyUsageExtension.DECIPHER_ONLY_BIT]));
return params;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/jobs/CronItem.java b/pki/base/common/src/com/netscape/cmscore/jobs/CronItem.java
index 4b248954..7bc14625 100644
--- a/pki/base/common/src/com/netscape/cmscore/jobs/CronItem.java
+++ b/pki/base/common/src/com/netscape/cmscore/jobs/CronItem.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.jobs;
-
import java.util.StringTokenizer;
import java.util.Vector;
@@ -25,15 +24,15 @@ import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.logging.ILogger;
-
/**
* class representing one Job cron item
- * <p>here, an "item" refers to one of the 5 fields in a cron string;
- * "element" refers to any comma-deliminated element in an
- * "item"...which includes both numbers and '-' separated ranges.
+ * <p>
+ * here, an "item" refers to one of the 5 fields in a cron string; "element"
+ * refers to any comma-deliminated element in an "item"...which includes both
+ * numbers and '-' separated ranges.
* <p>
* for each of the 5 cron fields, it's represented as a CronItem
- *
+ *
* @author cfu
* @version $Revision$, $Date$
*/
@@ -49,22 +48,22 @@ public class CronItem {
// store all elements in a field.
// elements can either be numbers or ranges (CronRange)
protected Vector<CronRange> mElements = new Vector<CronRange>();
-
+
public CronItem(int min, int max) {
mMin = min;
mMax = max;
}
-
+
/**
* parses and sets a string cron item
- * @param sItem the string representing an item of a cron string.
- * item can be potentially comma separated with ranges specified
- * with '-'s
+ *
+ * @param sItem the string representing an item of a cron string. item can
+ * be potentially comma separated with ranges specified with '-'s
*/
public void set(String sItem) throws EBaseException {
-
+
if (sItem.equals(ALL)) {
- // System.out.println("CronItem set(): item is ALL");
+ // System.out.println("CronItem set(): item is ALL");
CronRange cr = new CronRange();
cr.setBegin(mMin);
@@ -90,7 +89,7 @@ public class CronItem {
} catch (NumberFormatException e) {
// throw ...
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_JOBS_INVALID_TOKEN", tok, e.toString()));
+ CMS.getLogMessage("CMSCORE_JOBS_INVALID_TOKEN", tok, e.toString()));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_JOB_CRON"));
}
String sEnd = tok.substring(r + 1, tok.length());
@@ -100,7 +99,7 @@ public class CronItem {
} catch (NumberFormatException e) {
// throw ...
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_JOBS_INVALID_TOKEN", tok, e.toString()));
+ CMS.getLogMessage("CMSCORE_JOBS_INVALID_TOKEN", tok, e.toString()));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_JOB_CRON"));
}
// got both begin and end for range
@@ -112,11 +111,11 @@ public class CronItem {
if (!cr.isValidRange(mMin, mMax)) {
// throw...
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_JOBS_INVALID_RANGE",
- tok));
+ CMS.getLogMessage("CMSCORE_JOBS_INVALID_RANGE",
+ tok));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_JOB_CRON"));
}
- // System.out.println("CronItem set(): adding a range");
+ // System.out.println("CronItem set(): adding a range");
mElements.addElement(cr);
} else {
// number element, begin and end are the same
@@ -130,15 +129,15 @@ public class CronItem {
if (!cr.isValidRange(mMin, mMax)) {
// throw...
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_JOBS_INVALID_MIN_MAX_RANGE", Integer.toString(mMin), Integer.toString(mMax)));
+ CMS.getLogMessage("CMSCORE_JOBS_INVALID_MIN_MAX_RANGE", Integer.toString(mMin), Integer.toString(mMax)));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_JOB_CRON"));
}
- // System.out.println("CronItem set(): adding a number");
+ // System.out.println("CronItem set(): adding a number");
mElements.addElement(cr);
} catch (NumberFormatException e) {
// throw...
log(ILogger.LL_FAILURE,
- "invalid item in cron: " + tok);
+ "invalid item in cron: " + tok);
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_JOB_CRON"));
}
}
@@ -147,8 +146,9 @@ public class CronItem {
}
/**
- * get the vector stuffed with elements where each element is
- * represented as CronRange
+ * get the vector stuffed with elements where each element is represented as
+ * CronRange
+ *
* @return a vector of CronRanges
*/
public Vector<CronRange> getElements() {
@@ -162,7 +162,6 @@ public class CronItem {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- level, "jobs/CronItem: " + msg);
+ level, "jobs/CronItem: " + msg);
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/jobs/CronRange.java b/pki/base/common/src/com/netscape/cmscore/jobs/CronRange.java
index 59293ee1..0a90dbb2 100644
--- a/pki/base/common/src/com/netscape/cmscore/jobs/CronRange.java
+++ b/pki/base/common/src/com/netscape/cmscore/jobs/CronRange.java
@@ -17,27 +17,24 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.jobs;
-
-
-
/**
* class representing one Job cron element
- * <p>here, an "item" refers to one of the 5 fields in a cron string;
- * "element" refers to any comma-deliminated element in an
- * "item"...which includes both numbers and '-' separated ranges.
* <p>
- * an Element can contain either an integer number or a range
- * specified as CronRange. In case of integer numbers, begin
- * and end are of the same value
- *
+ * here, an "item" refers to one of the 5 fields in a cron string; "element"
+ * refers to any comma-deliminated element in an "item"...which includes both
+ * numbers and '-' separated ranges.
+ * <p>
+ * an Element can contain either an integer number or a range specified as
+ * CronRange. In case of integer numbers, begin and end are of the same value
+ *
* @author cfu
* @version $Revision$, $Date$
*/
public class CronRange {
int mBegin = 0;
int mEnd = 0;
-
- public CronRange () {
+
+ public CronRange() {
}
/**
@@ -46,7 +43,7 @@ public class CronRange {
public void setBegin(int i) {
mBegin = i;
}
-
+
/**
* gets the lower boundary value of the range
*/
@@ -69,17 +66,18 @@ public class CronRange {
}
/**
- * checks to see if the lower and higher boundary values are
- * within the min/max.
+ * checks to see if the lower and higher boundary values are within the
+ * min/max.
+ *
* @param min the minimum value one can specify in this field
* @param max the maximum value one can specify in this field
- * @return a boolean (true/false) on whether the begin/end values
- * are within the min/max passed in the params
+ * @return a boolean (true/false) on whether the begin/end values are within
+ * the min/max passed in the params
*/
public boolean isValidRange(int min, int max) {
if ((mEnd < mBegin) ||
- (mBegin < min) ||
- (mEnd > max))
+ (mBegin < min) ||
+ (mEnd > max))
return false;
else
return true;
diff --git a/pki/base/common/src/com/netscape/cmscore/jobs/JobCron.java b/pki/base/common/src/com/netscape/cmscore/jobs/JobCron.java
index 8272c448..828834a2 100644
--- a/pki/base/common/src/com/netscape/cmscore/jobs/JobCron.java
+++ b/pki/base/common/src/com/netscape/cmscore/jobs/JobCron.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.jobs;
-
import java.util.Calendar;
import java.util.Enumeration;
import java.util.StringTokenizer;
@@ -28,33 +27,28 @@ import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.jobs.IJobCron;
import com.netscape.certsrv.logging.ILogger;
-
/**
* class representing one Job cron information
- * <p>here, an "item" refers to one of the 5 fields in a cron string;
- * "element" refers to any comma-deliminated element in an
- * "item"...which includes both numbers and '-' separated ranges.
- * A cron string in the configuration takes the following format:
- * <i>minute (0-59),
- * hour (0-23),
- * day of the month (1-31),
- * month of the year (1-12),
- * day of the week (0-6 with 0=Sunday)</i>
* <p>
- * e.g. jobsScheduler.job.rnJob1.cron=30 11,23 * * 1-5
- * In this example, the job "rnJob1" will be executed from Monday
- * through Friday, at 11:30am and 11:30pm.
+ * here, an "item" refers to one of the 5 fields in a cron string; "element"
+ * refers to any comma-deliminated element in an "item"...which includes both
+ * numbers and '-' separated ranges. A cron string in the configuration takes
+ * the following format: <i>minute (0-59), hour (0-23), day of the month (1-31),
+ * month of the year (1-12), day of the week (0-6 with 0=Sunday)</i>
* <p>
- *
+ * e.g. jobsScheduler.job.rnJob1.cron=30 11,23 * * 1-5 In this example, the job
+ * "rnJob1" will be executed from Monday through Friday, at 11:30am and 11:30pm.
+ * <p>
+ *
* @author cfu
* @version $Revision$, $Date$
*/
public class JobCron implements IJobCron {
/**
- * CRON_MINUTE, CRON_HOUR, CRON_DAY_OF_MONTH, CRON_MONTH_OF_YEAR,
- * and CRON_DAY_OF_WEEK are to be used in <b>getItem()</b> to
- * retrieve the corresponding <b>CronItem</b>
+ * CRON_MINUTE, CRON_HOUR, CRON_DAY_OF_MONTH, CRON_MONTH_OF_YEAR, and
+ * CRON_DAY_OF_WEEK are to be used in <b>getItem()</b> to retrieve the
+ * corresponding <b>CronItem</b>
*/
public static final String CRON_MINUTE = "minute";
public static final String CRON_HOUR = "hour";
@@ -72,7 +66,7 @@ public class JobCron implements IJobCron {
CronItem cDOW = null;
public JobCron(String cronString)
- throws EBaseException {
+ throws EBaseException {
mCronString = cronString;
// create all 5 items in the cron
@@ -84,9 +78,9 @@ public class JobCron implements IJobCron {
cronToVals(mCronString);
}
-
- private void cronToVals(String cronString)
- throws EBaseException {
+
+ private void cronToVals(String cronString)
+ throws EBaseException {
StringTokenizer st = new StringTokenizer(cronString);
String sMinute = null;
@@ -101,8 +95,8 @@ public class JobCron implements IJobCron {
cMinute.set(sMinute);
}
} catch (EBaseException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_JOBS_INVALID_MIN", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_JOBS_INVALID_MIN", e.toString()));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_JOB_CRON"));
}
@@ -118,7 +112,7 @@ public class JobCron implements IJobCron {
if (st.hasMoreTokens()) {
sDayOMonth = st.nextToken();
- // cDOM.set(sDayOMonth);
+ // cDOM.set(sDayOMonth);
}
try {
@@ -133,24 +127,22 @@ public class JobCron implements IJobCron {
if (st.hasMoreTokens()) {
sDayOWeek = st.nextToken();
- // cDOW.set(sDayOWeek);
+ // cDOW.set(sDayOWeek);
}
/**
- * day-of-month or day-of-week, or both?
- * if only one of them is '*', the non '*' one prevails,
- * the '*' one will remain empty (no elements)
+ * day-of-month or day-of-week, or both? if only one of them is '*', the
+ * non '*' one prevails, the '*' one will remain empty (no elements)
*/
// day-of-week
- if ((sDayOMonth!= null) && sDayOMonth.equals(CronItem.ALL) && (sDayOWeek!= null) && !sDayOWeek.equals(CronItem.ALL)) {
+ if ((sDayOMonth != null) && sDayOMonth.equals(CronItem.ALL) && (sDayOWeek != null) && !sDayOWeek.equals(CronItem.ALL)) {
try {
cDOW.set(sDayOWeek);
} catch (EBaseException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_JOBS_INVALID_DAY_OF_WEEK", e.toString()));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_JOB_CRON"));
}
- } else
- if ((sDayOMonth!= null) && !sDayOMonth.equals(CronItem.ALL) && (sDayOWeek!= null) && sDayOWeek.equals(CronItem.ALL)) {
+ } else if ((sDayOMonth != null) && !sDayOMonth.equals(CronItem.ALL) && (sDayOWeek != null) && sDayOWeek.equals(CronItem.ALL)) {
try {
cDOM.set(sDayOMonth);
} catch (EBaseException e) {
@@ -159,7 +151,7 @@ public class JobCron implements IJobCron {
}
} else { // if both '*', every day, if neither is '*', do both
try {
- if (sDayOWeek!= null) {
+ if (sDayOWeek != null) {
cDOW.set(sDayOWeek);
}
} catch (EBaseException e) {
@@ -179,10 +171,11 @@ public class JobCron implements IJobCron {
/**
* retrieves the cron item
- * @param item name of the item. must be one of the <b>CRON_*</b>
- * strings defined in this class
- * @return an instance of the CronItem class which represents the
- * requested cron item
+ *
+ * @param item name of the item. must be one of the <b>CRON_*</b> strings
+ * defined in this class
+ * @return an instance of the CronItem class which represents the requested
+ * cron item
*/
public CronItem getItem(String item) {
if (item.equals(CRON_MINUTE)) {
@@ -204,10 +197,11 @@ public class JobCron implements IJobCron {
/**
* Does the element fit any element in the item
+ *
* @param element the element of "now" in cron format
* @param item the item consists of a vector of elements
- * @return boolean (true/false) on whether the element is one of
- * the elements in the item
+ * @return boolean (true/false) on whether the element is one of the
+ * elements in the item
*/
boolean isElement(int element, Vector<CronRange> item) {
// loop through all of the elements of an item
@@ -221,7 +215,7 @@ public class JobCron implements IJobCron {
}
} else { // is a range
if ((element >= cElement.getBegin()) &&
- (element <= cElement.getEnd())) {
+ (element <= cElement.getEnd())) {
return true;
}
}
@@ -231,11 +225,10 @@ public class JobCron implements IJobCron {
}
/**
- * convert the day of the week representation from Calendar to
- * cron
+ * convert the day of the week representation from Calendar to cron
+ *
* @param time the Calendar value represents a moment of time
- * @return an integer value that represents a cron Day-Of-Week
- * element
+ * @return an integer value that represents a cron Day-Of-Week element
*/
public int DOW_cal2cron(Calendar time) {
int calDow = time.get(Calendar.DAY_OF_WEEK);
@@ -280,9 +273,9 @@ public class JobCron implements IJobCron {
/**
* convert the month of year representation from Calendar to cron
+ *
* @param time the Calendar value represents a moment of time
- * @return an integer value that represents a cron Month-Of-Year
- * element
+ * @return an integer value that represents a cron Month-Of-Year element
*/
public int MOY_cal2cron(Calendar time) {
int calMoy = time.get(Calendar.MONTH);
@@ -352,6 +345,6 @@ public class JobCron implements IJobCron {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- level, msg);
+ level, msg);
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/jobs/JobsScheduler.java b/pki/base/common/src/com/netscape/cmscore/jobs/JobsScheduler.java
index ad6cf898..ed992c90 100644
--- a/pki/base/common/src/com/netscape/cmscore/jobs/JobsScheduler.java
+++ b/pki/base/common/src/com/netscape/cmscore/jobs/JobsScheduler.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.jobs;
-
import java.util.Calendar;
import java.util.Enumeration;
import java.util.Hashtable;
@@ -35,24 +34,21 @@ import com.netscape.certsrv.jobs.JobPlugin;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.cmscore.util.Debug;
-
/**
- * This is a daemon thread that handles scheduled jobs like cron would
- * do with different jobs. This daemon wakes up at a pre-configured
- * interval to see
- * if there is any job to be done, if so, a thread is created to execute
- * the job(s).
+ * This is a daemon thread that handles scheduled jobs like cron would do with
+ * different jobs. This daemon wakes up at a pre-configured interval to see if
+ * there is any job to be done, if so, a thread is created to execute the
+ * job(s).
* <p>
- * The interval <b>jobsScheduler.interval</b> in the configuration is
- * specified as number of minutes. If not set, the default is 1 minute.
- * Note that the cron specification for each job CAN NOT be finer than
- * the granularity of the Scheduler daemon interval. For example, if
- * the daemon interval is set to 5 minute, a job cron for every minute
- * at 7am on each Tuesday (e.g. * 7 * * 2) will result in the
- * execution of the job thread only once every 5 minutes during that
- * hour. <b>The inteval value is recommended at 1 minute, setting it
- * otherwise has the potential of forever missing the beat</b>. Use
- * with caution.
+ * The interval <b>jobsScheduler.interval</b> in the configuration is specified
+ * as number of minutes. If not set, the default is 1 minute. Note that the cron
+ * specification for each job CAN NOT be finer than the granularity of the
+ * Scheduler daemon interval. For example, if the daemon interval is set to 5
+ * minute, a job cron for every minute at 7am on each Tuesday (e.g. * 7 * * 2)
+ * will result in the execution of the job thread only once every 5 minutes
+ * during that hour. <b>The inteval value is recommended at 1 minute, setting it
+ * otherwise has the potential of forever missing the beat</b>. Use with
+ * caution.
*
* @author cfu
* @see JobCron
@@ -93,19 +89,19 @@ public class JobsScheduler implements Runnable, IJobsScheduler {
}
/**
- * read from the config file all implementations of Jobs,
- * register and initialize them
+ * read from the config file all implementations of Jobs, register and
+ * initialize them
* <p>
* the config params have the following formats:
* jobScheduler.impl.[implementation name].class=[package name]
* jobScheduler.job.[job name].pluginName=[implementation name]
- * jobScheduler.job.[job name].cron=[crontab format]
- * jobScheduler.job.[job name].[any job specific params]=[values]
+ * jobScheduler.job.[job name].cron=[crontab format] jobScheduler.job.[job
+ * name].[any job specific params]=[values]
*
* @param config jobsScheduler configStore
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException, EJobsException {
+ throws EBaseException, EJobsException {
mLogger = CMS.getLogger();
// read in config parameters and set variables
@@ -142,14 +138,13 @@ public class JobsScheduler implements Runnable, IJobsScheduler {
String jobName = (String) jobs.nextElement();
String implName = c.getString(jobName + "." + PROP_PLUGIN);
JobPlugin plugin =
- (JobPlugin) mJobPlugins.get(implName);
+ (JobPlugin) mJobPlugins.get(implName);
if (plugin == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_JOBS_CLASS_NOT_FOUND",
- implName));
- throw new
- EJobsException(CMS.getUserMessage("CMS_JOB_PLUGIN_NOT_FOUND", implName));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_JOBS_CLASS_NOT_FOUND",
+ implName));
+ throw new EJobsException(CMS.getUserMessage("CMS_JOB_PLUGIN_NOT_FOUND", implName));
}
String classPath = plugin.getClassPath();
@@ -169,20 +164,17 @@ public class JobsScheduler implements Runnable, IJobsScheduler {
String errMsg = "JobsScheduler:: init()-" + e.toString();
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_JOBS_INIT_ERROR", e.toString()));
- throw new
- EJobsException(CMS.getUserMessage("CMS_JOB_LOAD_CLASS_FAILED", classPath));
+ throw new EJobsException(CMS.getUserMessage("CMS_JOB_LOAD_CLASS_FAILED", classPath));
} catch (IllegalAccessException e) {
String errMsg = "JobsScheduler:: init()-" + e.toString();
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_JOBS_INIT_ERROR", e.toString()));
- throw new
- EJobsException(CMS.getUserMessage("CMS_JOB_LOAD_CLASS_FAILED", classPath));
+ throw new EJobsException(CMS.getUserMessage("CMS_JOB_LOAD_CLASS_FAILED", classPath));
} catch (InstantiationException e) {
String errMsg = "JobsScheduler: init()-" + e.toString();
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_JOBS_INIT_ERROR", e.toString()));
- throw new
- EJobsException(CMS.getUserMessage("CMS_JOB_LOAD_CLASS_FAILED", classPath));
+ throw new EJobsException(CMS.getUserMessage("CMS_JOB_LOAD_CLASS_FAILED", classPath));
} catch (EBaseException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_JOBS_INIT_ERROR", e.toString()));
throw e;
@@ -205,12 +197,10 @@ public class JobsScheduler implements Runnable, IJobsScheduler {
}
/**
- * when wake up:
- * . execute the scheduled job(s)
- * * if job still running from previous interval, skip it
- * . figure out when is the next wakeup time (every interval). If
- * current wakup time runs over the interval, skip the missed interval(s)
- * . sleep till the next wakeup time
+ * when wake up: . execute the scheduled job(s) * if job still running from
+ * previous interval, skip it . figure out when is the next wakeup time
+ * (every interval). If current wakup time runs over the interval, skip the
+ * missed interval(s) . sleep till the next wakeup time
*/
public void run() {
long wokeupTime = 0;
@@ -230,8 +220,8 @@ public class JobsScheduler implements Runnable, IJobsScheduler {
// just let it skip to next second, fine.
duration = (60 - second) * 1000 + 1000 - milliSec;
log(ILogger.LL_INFO,
- "adjustment for cron behavior: sleep for " +
- duration + " milliseconds");
+ "adjustment for cron behavior: sleep for " +
+ duration + " milliseconds");
} else {
// when is the next wakeup time for the JobsScheduler?
@@ -268,14 +258,13 @@ public class JobsScheduler implements Runnable, IJobsScheduler {
// get time now
cal = Calendar.getInstance();
-
+
/**
- * Get the current time outside the jobs while loop
- * to make sure that the rightful jobs are run
- * -- milliseconds from the epoch
+ * Get the current time outside the jobs while loop to make sure
+ * that the rightful jobs are run -- milliseconds from the epoch
*/
wokeupTime = cal.getTime().getTime();
-
+
IJob job = null;
for (Enumeration<IJob> e = mJobs.elements(); e.hasMoreElements();) {
@@ -296,7 +285,7 @@ public class JobsScheduler implements Runnable, IJobsScheduler {
// start the job thread if necessary
if (isShowTime(job, cal) == true) {
- // log(ILogger.LL_INFO, "show time for: "+job.getId());
+ // log(ILogger.LL_INFO, "show time for: "+job.getId());
// if previous thread still alive, skip
Thread jthread = (Thread) mJobThreads.get(job.getId());
@@ -310,14 +299,14 @@ public class JobsScheduler implements Runnable, IJobsScheduler {
} else {
// previous thread still alive, log it
log(ILogger.LL_INFO, "Job " + job.getId() +
- " still running...skipping this round");
+ " still running...skipping this round");
}
}
} // for
}
}
-
+
public IJobCron createJobCron(String cs) throws EBaseException {
return new JobCron(cs);
}
@@ -338,8 +327,8 @@ public class JobsScheduler implements Runnable, IJobsScheduler {
* is it the right month?
*/
Vector<CronRange> moy =
- jcron.getItem(JobCron.CRON_MONTH_OF_YEAR).getElements();
-
+ jcron.getItem(JobCron.CRON_MONTH_OF_YEAR).getElements();
+
int cronMoy = jcron.MOY_cal2cron(now);
if (jcron.isElement(cronMoy, moy) == false) {
@@ -361,7 +350,7 @@ public class JobsScheduler implements Runnable, IJobsScheduler {
int cronDow = jcron.DOW_cal2cron(now);
if ((jcron.isElement(cronDow, dow) == false) &&
- (jcron.isElement(now.get(Calendar.DAY_OF_MONTH), dom) == false)) {
+ (jcron.isElement(now.get(Calendar.DAY_OF_MONTH), dom) == false)) {
return false;
}
// is the right date!
@@ -384,23 +373,25 @@ public class JobsScheduler implements Runnable, IJobsScheduler {
if (jcron.isElement(now.get(Calendar.MINUTE), minute) == false) {
return false;
}
- // is the right minute! We're on!
+ // is the right minute! We're on!
return true;
}
/**
* Retrieves id (name) of this subsystem.
+ *
* @return name of the Jobs Scheduler subsystem
*/
public String getId() {
return (mId);
}
-
+
/**
* Sets id string to this subsystem.
* <p>
- * Use with caution. Should not do it when sharing with others
+ * Use with caution. Should not do it when sharing with others
+ *
* @param id name to be applied to an Jobs Scheduler subsystem
*/
public void setId(String id) throws EBaseException {
@@ -421,13 +412,14 @@ public class JobsScheduler implements Runnable, IJobsScheduler {
* registers the administration servlet with the administration subsystem.
*/
public void startup() throws EBaseException {
- //remove, already logged from S_ADMIN
- //String infoMsg = "Jobs Scheduler subsystem administration Servlet registered";
- //log(ILogger.LL_INFO, infoMsg);
+ // remove, already logged from S_ADMIN
+ // String infoMsg =
+ // "Jobs Scheduler subsystem administration Servlet registered";
+ // log(ILogger.LL_INFO, infoMsg);
}
/**
- * shuts down Jobs one by one.
+ * shuts down Jobs one by one.
* <P>
*/
public void shutdown() {
@@ -438,23 +430,23 @@ public class JobsScheduler implements Runnable, IJobsScheduler {
Enumeration<String> enums = mJobThreads.keys();
while (enums.hasMoreElements()) {
- String id = (String)enums.nextElement();
- Thread currthread = (Thread)mJobThreads.get(id);
- //if (currthread != null)
- // currthread.destroy();
+ String id = (String) enums.nextElement();
+ Thread currthread = (Thread) mJobThreads.get(id);
+ // if (currthread != null)
+ // currthread.destroy();
}
mJobThreads.clear();
mJobThreads = null;
- //if (mScheduleThread != null)
- // mScheduleThread.destroy();
+ // if (mScheduleThread != null)
+ // mScheduleThread.destroy();
}
/**
* Returns the root configuration storage of this system.
* <P>
- *
+ *
* @return configuration store of this subsystem
*/
public IConfigStore getConfigStore() {
@@ -462,29 +454,29 @@ public class JobsScheduler implements Runnable, IJobsScheduler {
}
/**
- * Gets configuration parameters for the given
- * job plugin.
+ * Gets configuration parameters for the given job plugin.
+ *
* @param implName Name of the job plugin.
* @return Hashtable of required parameters.
*/
public String[] getConfigParams(String implName)
- throws EJobsException {
+ throws EJobsException {
if (Debug.ON)
Debug.trace("in getCofigParams()");
- // is this a registered implname?
+ // is this a registered implname?
JobPlugin plugin = (JobPlugin) mJobPlugins.get(implName);
if (plugin == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_JOBS_CLASS_NOT_FOUND", implName));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_JOBS_CLASS_NOT_FOUND", implName));
if (Debug.ON)
Debug.trace("Job plugin " + implName + " not found.");
throw new EJobsException(CMS.getUserMessage("CMS_JOB_PLUGIN_NOT_FOUND",
implName));
}
- // XXX can find an instance of this plugin in existing
+ // XXX can find an instance of this plugin in existing
// auth manager instantces to avoid instantiation just for this.
// a temporary instance
@@ -500,26 +492,23 @@ public class JobsScheduler implements Runnable, IJobsScheduler {
Debug.trace("class instantiated");
return (jobInst.getConfigParams());
} catch (InstantiationException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_JOBS_CREATE_NEW", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_JOBS_CREATE_NEW", e.toString()));
if (Debug.ON)
Debug.trace("class NOT instantiated: " + e.toString());
- throw new
- EJobsException(CMS.getUserMessage("CMS_JOB_LOAD_CLASS_FAILED", className));
+ throw new EJobsException(CMS.getUserMessage("CMS_JOB_LOAD_CLASS_FAILED", className));
} catch (ClassNotFoundException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_JOBS_CREATE_NEW", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_JOBS_CREATE_NEW", e.toString()));
if (Debug.ON)
Debug.trace("class NOT instantiated: " + e.toString());
- throw new
- EJobsException(CMS.getUserMessage("CMS_JOB_LOAD_CLASS_FAILED", className));
+ throw new EJobsException(CMS.getUserMessage("CMS_JOB_LOAD_CLASS_FAILED", className));
} catch (IllegalAccessException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_JOBS_CREATE_NEW", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_JOBS_CREATE_NEW", e.toString()));
if (Debug.ON)
Debug.trace("class NOT instantiated: " + e.toString());
- throw new
- EJobsException(CMS.getUserMessage("CMS_JOB_LOAD_CLASS_FAILED", className));
+ throw new EJobsException(CMS.getUserMessage("CMS_JOB_LOAD_CLASS_FAILED", className));
}
}
@@ -534,7 +523,7 @@ public class JobsScheduler implements Runnable, IJobsScheduler {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- level, msg);
+ level, msg);
}
public Hashtable<String, JobPlugin> getJobPlugins() {
diff --git a/pki/base/common/src/com/netscape/cmscore/ldap/LdapAndExpression.java b/pki/base/common/src/com/netscape/cmscore/ldap/LdapAndExpression.java
index c41f361e..8f62aa0b 100644
--- a/pki/base/common/src/com/netscape/cmscore/ldap/LdapAndExpression.java
+++ b/pki/base/common/src/com/netscape/cmscore/ldap/LdapAndExpression.java
@@ -17,32 +17,31 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.ldap;
-
import com.netscape.certsrv.base.SessionContext;
import com.netscape.certsrv.ldap.ELdapException;
import com.netscape.certsrv.publish.ILdapExpression;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class represents an expression of the form
- * <var1 op val1 AND var2 op va2>.
- *
+ * This class represents an expression of the form <var1 op val1 AND var2 op
+ * va2>.
+ *
* Expressions are used as predicates for publishing rule selection.
- *
+ *
* @author mzhao
* @version $Revision$, $Date$
*/
public class LdapAndExpression implements ILdapExpression {
private ILdapExpression mExp1;
private ILdapExpression mExp2;
+
public LdapAndExpression(ILdapExpression exp1, ILdapExpression exp2) {
mExp1 = exp1;
mExp2 = exp2;
}
public boolean evaluate(SessionContext sc)
- throws ELdapException {
+ throws ELdapException {
// If an expression is missing we assume applicability.
if (mExp1 == null && mExp2 == null)
return true;
@@ -50,12 +49,13 @@ public class LdapAndExpression implements ILdapExpression {
return mExp1.evaluate(sc) && mExp2.evaluate(sc);
else if (mExp1 == null)
return mExp2.evaluate(sc);
- else // (if mExp2 == null)
+ else
+ // (if mExp2 == null)
return mExp1.evaluate(sc);
}
public boolean evaluate(IRequest req)
- throws ELdapException {
+ throws ELdapException {
// If an expression is missing we assume applicability.
if (mExp1 == null && mExp2 == null)
return true;
@@ -63,7 +63,8 @@ public class LdapAndExpression implements ILdapExpression {
return mExp1.evaluate(req) && mExp2.evaluate(req);
else if (mExp1 == null)
return mExp2.evaluate(req);
- else // (if mExp2 == null)
+ else
+ // (if mExp2 == null)
return mExp1.evaluate(req);
}
@@ -71,4 +72,3 @@ public class LdapAndExpression implements ILdapExpression {
return mExp1.toString() + " AND " + mExp2.toString();
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/ldap/LdapConnModule.java b/pki/base/common/src/com/netscape/cmscore/ldap/LdapConnModule.java
index 7574bf1b..56fa230e 100644
--- a/pki/base/common/src/com/netscape/cmscore/ldap/LdapConnModule.java
+++ b/pki/base/common/src/com/netscape/cmscore/ldap/LdapConnModule.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.ldap;
-
import netscape.ldap.LDAPConnection;
import com.netscape.certsrv.apps.CMS;
@@ -34,7 +33,6 @@ import com.netscape.cmscore.ldapconn.LdapAuthInfo;
import com.netscape.cmscore.ldapconn.LdapBoundConnFactory;
import com.netscape.cmscore.ldapconn.LdapConnInfo;
-
public class LdapConnModule implements ILdapConnModule {
protected IConfigStore mConfig = null;
protected LdapBoundConnFactory mLdapConnFactory = null;
@@ -42,7 +40,7 @@ public class LdapConnModule implements ILdapConnModule {
private boolean mInited = false;
/**
- * instantiate connection factory.
+ * instantiate connection factory.
*/
public static final String PROP_LDAP = "ldap";
@@ -58,22 +56,22 @@ public class LdapConnModule implements ILdapConnModule {
protected ISubsystem mPubProcessor;
public void init(ISubsystem p,
- IConfigStore config)
- throws EBaseException {
+ IConfigStore config)
+ throws EBaseException {
CMS.debug("LdapConnModule: init called");
if (mInited) {
CMS.debug("LdapConnModule: already initialized. return.");
- return;
+ return;
}
CMS.debug("LdapConnModule: init begins");
mPubProcessor = p;
mConfig = config;
/*
- mLdapConnFactory = new LdapBoundConnFactory();
- mLdapConnFactory.init(mConfig.getSubStore("ldap"));
- */
+ * mLdapConnFactory = new LdapBoundConnFactory();
+ * mLdapConnFactory.init(mConfig.getSubStore("ldap"));
+ */
// support publishing dirsrv with different pwd than internaldb
IConfigStore ldap = mConfig.getSubStore("ldap");
@@ -85,16 +83,16 @@ public class LdapConnModule implements ILdapConnModule {
ILdapConnInfo connInfo =
CMS.getLdapConnInfo(ldapconn);
LdapAuthInfo authInfo =
- new LdapAuthInfo(authinfo, ldapconn.getString("host"),
- ldapconn.getInteger("port"), connInfo.getSecure());
+ new LdapAuthInfo(authinfo, ldapconn.getString("host"),
+ ldapconn.getInteger("port"), connInfo.getSecure());
int minConns = mConfig.getInteger(ILdapBoundConnFactory.PROP_MINCONNS, 3);
int maxConns = mConfig.getInteger(ILdapBoundConnFactory.PROP_MAXCONNS, 15);
// must get authInfo from the config, don't default to internaldb!!!
- CMS.debug("Creating LdapBoundConnFactory for LdapConnModule.");
+ CMS.debug("Creating LdapBoundConnFactory for LdapConnModule.");
mLdapConnFactory =
- new LdapBoundConnFactory(minConns, maxConns, (LdapConnInfo)connInfo, authInfo);
+ new LdapBoundConnFactory(minConns, maxConns, (LdapConnInfo) connInfo, authInfo);
mInited = true;
@@ -102,15 +100,14 @@ public class LdapConnModule implements ILdapConnModule {
}
/**
- * Returns the internal ldap connection factory.
- * This can be useful to get a ldap connection to the
- * ldap publishing directory without having to get it again from the
- * config file. Note that this means sharing a ldap connection pool
- * with the ldap publishing module so be sure to return connections to pool.
- * Use ILdapConnFactory.getConn() to get a Ldap connection to the ldap
- * publishing directory.
- * Use ILdapConnFactory.returnConn() to return the connection.
- *
+ * Returns the internal ldap connection factory. This can be useful to get a
+ * ldap connection to the ldap publishing directory without having to get it
+ * again from the config file. Note that this means sharing a ldap
+ * connection pool with the ldap publishing module so be sure to return
+ * connections to pool. Use ILdapConnFactory.getConn() to get a Ldap
+ * connection to the ldap publishing directory. Use
+ * ILdapConnFactory.returnConn() to return the connection.
+ *
* @see com.netscape.certsrv.ldap.ILdapBoundConnFactory
* @see com.netscape.certsrv.ldap.ILdapConnFactory
*/
@@ -127,9 +124,8 @@ public class LdapConnModule implements ILdapConnModule {
}
public void log(int level, String msg) {
- mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_LDAP, level,
- "LdapPublishModule: " + msg);
+ mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_LDAP, level,
+ "LdapPublishModule: " + msg);
}
-
-}
+}
diff --git a/pki/base/common/src/com/netscape/cmscore/ldap/LdapOrExpression.java b/pki/base/common/src/com/netscape/cmscore/ldap/LdapOrExpression.java
index aaf9f35d..1264c4ce 100644
--- a/pki/base/common/src/com/netscape/cmscore/ldap/LdapOrExpression.java
+++ b/pki/base/common/src/com/netscape/cmscore/ldap/LdapOrExpression.java
@@ -17,51 +17,52 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.ldap;
-
import com.netscape.certsrv.base.SessionContext;
import com.netscape.certsrv.ldap.ELdapException;
import com.netscape.certsrv.publish.ILdapExpression;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class represents an Or expression of the form
- * (var1 op val1 OR var2 op val2).
- *
+ * This class represents an Or expression of the form (var1 op val1 OR var2 op
+ * val2).
+ *
* Expressions are used as predicates for publishing rule selection.
- *
+ *
* @author mzhao
* @version $Revision$, $Date$
*/
public class LdapOrExpression implements ILdapExpression {
private ILdapExpression mExp1;
private ILdapExpression mExp2;
+
public LdapOrExpression(ILdapExpression exp1, ILdapExpression exp2) {
mExp1 = exp1;
mExp2 = exp2;
}
public boolean evaluate(SessionContext sc)
- throws ELdapException {
+ throws ELdapException {
if (mExp1 == null && mExp2 == null)
return true;
else if (mExp1 != null && mExp2 != null)
return mExp1.evaluate(sc) || mExp2.evaluate(sc);
else if (mExp1 != null && mExp2 == null)
return mExp1.evaluate(sc);
- else // (mExp1 == null && mExp2 != null)
+ else
+ // (mExp1 == null && mExp2 != null)
return mExp2.evaluate(sc);
}
public boolean evaluate(IRequest req)
- throws ELdapException {
+ throws ELdapException {
if (mExp1 == null && mExp2 == null)
return true;
else if (mExp1 != null && mExp2 != null)
return mExp1.evaluate(req) || mExp2.evaluate(req);
else if (mExp1 != null && mExp2 == null)
return mExp1.evaluate(req);
- else // (mExp1 == null && mExp2 != null)
+ else
+ // (mExp1 == null && mExp2 != null)
return mExp2.evaluate(req);
}
@@ -72,8 +73,8 @@ public class LdapOrExpression implements ILdapExpression {
return mExp1.toString() + " OR " + mExp2.toString();
else if (mExp1 != null && mExp2 == null)
return mExp1.toString();
- else // (mExp1 == null && mExp2 != null)
+ else
+ // (mExp1 == null && mExp2 != null)
return mExp2.toString();
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/ldap/LdapPredicateParser.java b/pki/base/common/src/com/netscape/cmscore/ldap/LdapPredicateParser.java
index 3ac8f750..8c6be490 100644
--- a/pki/base/common/src/com/netscape/cmscore/ldap/LdapPredicateParser.java
+++ b/pki/base/common/src/com/netscape/cmscore/ldap/LdapPredicateParser.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.ldap;
-
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
@@ -29,19 +28,16 @@ import com.netscape.certsrv.ldap.ELdapException;
import com.netscape.certsrv.publish.ILdapExpression;
import com.netscape.cmscore.util.Debug;
-
/**
* Default implementation of predicate parser.
- *
+ *
* Limitations:
- *
- * 1. Currently parentheses are not suported.
- * 2. Only ==, != <, >, <= and >= operators are supported.
- * 3. The only boolean operators supported are AND and OR. AND takes precedence
- * over OR. Example: a AND b OR e OR c AND d
- * is treated as (a AND b) OR e OR (c AND d)
- * 4. If this is n't adequate, roll your own.
- *
+ *
+ * 1. Currently parentheses are not suported. 2. Only ==, != <, >, <= and >=
+ * operators are supported. 3. The only boolean operators supported are AND and
+ * OR. AND takes precedence over OR. Example: a AND b OR e OR c AND d is treated
+ * as (a AND b) OR e OR (c AND d) 4. If this is n't adequate, roll your own.
+ *
* @author mzhao
* @version $Revision$, $Date$
*/
@@ -57,22 +53,23 @@ public class LdapPredicateParser {
/**
* Parse the predicate expression and return a vector of expressions.
- *
- * @param predicateExp The predicate expression as read from the config file.
- * @return expVector The vector of expressions.
+ *
+ * @param predicateExp The predicate expression as read from the config
+ * file.
+ * @return expVector The vector of expressions.
*/
public static ILdapExpression parse(String predicateExpression)
- throws ELdapException {
- if (predicateExpression == null ||
- predicateExpression.length() == 0)
+ throws ELdapException {
+ if (predicateExpression == null ||
+ predicateExpression.length() == 0)
return null;
PredicateTokenizer pt = new PredicateTokenizer(predicateExpression);
if (pt == null || !pt.hasMoreTokens())
return null;
- // The first token cannot be an operator. We are not dealing with
- // reverse-polish notation.
+ // The first token cannot be an operator. We are not dealing with
+ // reverse-polish notation.
String token = pt.nextToken();
boolean opANDSeen;
boolean opORSeen;
@@ -92,7 +89,7 @@ public class LdapPredicateParser {
int curType = getOP(token);
if ((prevType != EXPRESSION && curType != EXPRESSION) ||
- (prevType == EXPRESSION && curType == EXPRESSION)) {
+ (prevType == EXPRESSION && curType == EXPRESSION)) {
malformed = true;
break;
}
@@ -103,7 +100,8 @@ public class LdapPredicateParser {
continue;
}
- // If the previous type was an OR token, add the current expression to
+ // If the previous type was an OR token, add the current expression
+ // to
// the expression set;
if (prevType == OP_OR) {
expSet.addElement(current);
@@ -122,8 +120,8 @@ public class LdapPredicateParser {
if (Debug.ON)
Debug.trace("Malformed expression: " + predicateExpression);
throw new ELdapException(
- CMS.getUserMessage("CMS_LDAP_BAD_LDAP_EXPRESSION",
- predicateExpression));
+ CMS.getUserMessage("CMS_LDAP_BAD_LDAP_EXPRESSION",
+ predicateExpression));
}
// Form an LdapOrExpression
@@ -135,7 +133,7 @@ public class LdapPredicateParser {
if (size == 0)
return null;
LdapOrExpression orExp = new
- LdapOrExpression((ILdapExpression) expSet.elementAt(0), null);
+ LdapOrExpression((ILdapExpression) expSet.elementAt(0), null);
for (int i = 1; i < size; i++)
orExp = new LdapOrExpression(orExp,
@@ -153,7 +151,7 @@ public class LdapPredicateParser {
}
private static ILdapExpression parseExpression(String input)
- throws ELdapException {
+ throws ELdapException {
// If the expression has multiple parts separated by commas
// we need to construct an AND expression. Else we will return a
// simple expression.
@@ -166,8 +164,8 @@ public class LdapPredicateParser {
while (commaIndex > 0) {
LdapSimpleExpression exp = (LdapSimpleExpression)
- LdapSimpleExpression.parse(input.substring(currentIndex,
- commaIndex));
+ LdapSimpleExpression.parse(input.substring(currentIndex,
+ commaIndex));
expVector.addElement(exp);
currentIndex = commaIndex + 1;
@@ -175,7 +173,7 @@ public class LdapPredicateParser {
}
if (currentIndex < (input.length() - 1)) {
LdapSimpleExpression exp = (LdapSimpleExpression)
- LdapSimpleExpression.parse(input.substring(currentIndex));
+ LdapSimpleExpression.parse(input.substring(currentIndex));
expVector.addElement(exp);
}
@@ -194,79 +192,40 @@ public class LdapPredicateParser {
public static void main(String[] args) {
/**
- AttributeSet req = new AttributeSet();
- try
- {
- req.set("ou", "people");
- req.set("cn", "John Doe");
- req.set("uid", "jdoes");
- req.set("o", "airius.com");
- req.set("certtype", "client");
- req.set("request", "issuance");
- req.set("id", new Integer(10));
- req.set("dualcerts", new Boolean(true));
-
- Vector v = new Vector();
- v.addElement("one");
- v.addElement("two");
- v.addElement("three");
- req.set("count", v);
- }
- catch (Exception e){e.printStackTrace();}
- String[] array = { "ou == people AND certtype == client",
- "ou == servergroup AND certtype == server",
- "uid == jdoes, ou==people, o==airius.com OR ou == people AND certType == client OR certType == server AND cn == needles.mcom.com",
- };
- for (int i = 0; i < array.length; i++)
- {
- System.out.println();
- System.out.println("String: " + array[i]);
- ILdapExpression exp = null;
- try
- {
- exp = parse(array[i]);
- if (exp != null)
- {
- System.out.println("Parsed Expression: " + exp);
- boolean result = exp.evaluate(req);
- System.out.println("Result: " + result);
- }
- }
- catch (Exception e) {e.printStackTrace(); }
- }
-
-
- try
- {
- BufferedReader rdr = new BufferedReader(
- new FileReader(args[0]));
- String line;
- while((line=rdr.readLine()) != null)
- {
- System.out.println();
- System.out.println("Line Read: " + line);
- ILdapExpression exp = null;
- try
- {
- exp = parse(line);
- if (exp != null)
- {
- System.out.println(exp);
- boolean result = exp.evaluate(req);
- System.out.println("Result: " + result);
- }
-
- }catch (Exception e){e.printStackTrace();}
- }
- }
- catch (Exception e){e.printStackTrace(); }
-
+ * AttributeSet req = new AttributeSet(); try { req.set("ou", "people");
+ * req.set("cn", "John Doe"); req.set("uid", "jdoes"); req.set("o",
+ * "airius.com"); req.set("certtype", "client"); req.set("request",
+ * "issuance"); req.set("id", new Integer(10)); req.set("dualcerts", new
+ * Boolean(true));
+ *
+ * Vector v = new Vector(); v.addElement("one"); v.addElement("two");
+ * v.addElement("three"); req.set("count", v); } catch (Exception
+ * e){e.printStackTrace();} String[] array = {
+ * "ou == people AND certtype == client",
+ * "ou == servergroup AND certtype == server",
+ * "uid == jdoes, ou==people, o==airius.com OR ou == people AND certType == client OR certType == server AND cn == needles.mcom.com"
+ * , }; for (int i = 0; i < array.length; i++) { System.out.println();
+ * System.out.println("String: " + array[i]); ILdapExpression exp =
+ * null; try { exp = parse(array[i]); if (exp != null) {
+ * System.out.println("Parsed Expression: " + exp); boolean result =
+ * exp.evaluate(req); System.out.println("Result: " + result); } } catch
+ * (Exception e) {e.printStackTrace(); } }
+ *
+ *
+ * try { BufferedReader rdr = new BufferedReader( new
+ * FileReader(args[0])); String line; while((line=rdr.readLine()) !=
+ * null) { System.out.println(); System.out.println("Line Read: " +
+ * line); ILdapExpression exp = null; try { exp = parse(line); if (exp
+ * != null) { System.out.println(exp); boolean result =
+ * exp.evaluate(req); System.out.println("Result: " + result); }
+ *
+ * }catch (Exception e){e.printStackTrace();} } } catch (Exception
+ * e){e.printStackTrace(); }
**/
}
}
-
class PredicateTokenizer {
String input;
int currentIndex;
@@ -348,30 +307,30 @@ class PredicateTokenizer {
}
}
-
class AttributeSet implements IAttrSet {
/**
*
*/
private static final long serialVersionUID = -3155846653754028803L;
Hashtable ht = new Hashtable();
+
public AttributeSet() {
}
public void delete(String name)
- throws EBaseException {
+ throws EBaseException {
Object ob = ht.get(name);
ht.remove(ob);
}
public Object get(String name)
- throws EBaseException {
+ throws EBaseException {
return ht.get(name);
}
public void set(String name, Object ob)
- throws EBaseException {
+ throws EBaseException {
ht.put(name, ob);
}
diff --git a/pki/base/common/src/com/netscape/cmscore/ldap/LdapPublishModule.java b/pki/base/common/src/com/netscape/cmscore/ldap/LdapPublishModule.java
index e9839f59..6fba2c37 100644
--- a/pki/base/common/src/com/netscape/cmscore/ldap/LdapPublishModule.java
+++ b/pki/base/common/src/com/netscape/cmscore/ldap/LdapPublishModule.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.ldap;
-
import java.io.IOException;
import java.math.BigInteger;
import java.security.cert.X509CRL;
@@ -56,7 +55,6 @@ import com.netscape.cmscore.dbs.CertRecord;
import com.netscape.cmscore.ldapconn.LdapBoundConnFactory;
import com.netscape.cmscore.util.Debug;
-
public class LdapPublishModule implements ILdapPublishModule {
protected IConfigStore mConfig = null;
protected LdapBoundConnFactory mLdapConnFactory = null;
@@ -64,28 +62,24 @@ public class LdapPublishModule implements ILdapPublishModule {
private boolean mInited = false;
protected ICertAuthority mAuthority = null;
- /**
- * hashtable of cert types to cert mappers and publishers.
- * cert types are client, server, ca, subca, ra, crl, etc.
- * XXX the cert types need to be consistently used.
- * for each, the mapper may be null, in which case the full subject
- * name is used to map the cert.
- * for crl, if the mapper is null the ca mapper is used. if that
- * is null, the full issuer name is used.
- * XXX if we support crl issuing points the issuing point should be used
- * to publish the crl.
- * When publishers are null, the certs are not published.
+ /**
+ * hashtable of cert types to cert mappers and publishers. cert types are
+ * client, server, ca, subca, ra, crl, etc. XXX the cert types need to be
+ * consistently used. for each, the mapper may be null, in which case the
+ * full subject name is used to map the cert. for crl, if the mapper is null
+ * the ca mapper is used. if that is null, the full issuer name is used. XXX
+ * if we support crl issuing points the issuing point should be used to
+ * publish the crl. When publishers are null, the certs are not published.
*/
- protected Hashtable mMappers = new Hashtable();
+ protected Hashtable mMappers = new Hashtable();
/**
- * handlers for request types (events)
- * values implement IRequestListener
+ * handlers for request types (events) values implement IRequestListener
*/
protected Hashtable mEventHandlers = new Hashtable();
/**
- * instantiate connection factory.
+ * instantiate connection factory.
*/
public static final String ATTR_LDAPPUBLISH_STATUS = "LdapPublishStatus";
public static final String PROP_LDAP = "ldap";
@@ -100,12 +94,10 @@ public class LdapPublishModule implements ILdapPublishModule {
public LdapPublishModule() {
}
- public void init(ISubsystem sub, IConfigStore config) throws EBaseException
- {
- }
+ public void init(ISubsystem sub, IConfigStore config) throws EBaseException {
+ }
- public void set(String name, String val)
- {
+ public void set(String name, String val) {
}
public LdapPublishModule(LdapBoundConnFactory factory) {
@@ -116,8 +108,8 @@ public class LdapPublishModule implements ILdapPublishModule {
protected IPublisherProcessor mPubProcessor;
public void init(ICertAuthority authority, IPublisherProcessor p,
- IConfigStore config)
- throws EBaseException {
+ IConfigStore config)
+ throws EBaseException {
if (mInited)
return;
@@ -133,9 +125,9 @@ public class LdapPublishModule implements ILdapPublishModule {
mAuthority.registerRequestListener(this);
}
- public void init(ICertAuthority authority, IConfigStore config)
- throws EBaseException {
- if (mInited)
+ public void init(ICertAuthority authority, IConfigStore config)
+ throws EBaseException {
+ if (mInited)
return;
mAuthority = authority;
@@ -150,15 +142,14 @@ public class LdapPublishModule implements ILdapPublishModule {
}
/**
- * Returns the internal ldap connection factory.
- * This can be useful to get a ldap connection to the
- * ldap publishing directory without having to get it again from the
- * config file. Note that this means sharing a ldap connection pool
- * with the ldap publishing module so be sure to return connections to pool.
- * Use ILdapConnFactory.getConn() to get a Ldap connection to the ldap
- * publishing directory.
- * Use ILdapConnFactory.returnConn() to return the connection.
- *
+ * Returns the internal ldap connection factory. This can be useful to get a
+ * ldap connection to the ldap publishing directory without having to get it
+ * again from the config file. Note that this means sharing a ldap
+ * connection pool with the ldap publishing module so be sure to return
+ * connections to pool. Use ILdapConnFactory.getConn() to get a Ldap
+ * connection to the ldap publishing directory. Use
+ * ILdapConnFactory.returnConn() to return the connection.
+ *
* @see com.netscape.certsrv.ldap.ILdapBoundConnFactory
* @see com.netscape.certsrv.ldap.ILdapConnFactory
*/
@@ -167,8 +158,8 @@ public class LdapPublishModule implements ILdapPublishModule {
}
/**
- * Returns the connection factory to the publishing directory.
- * Must return the connection once you return
+ * Returns the connection factory to the publishing directory. Must return
+ * the connection once you return
*/
protected LdapMappers getMappers(String certType) {
@@ -179,16 +170,16 @@ public class LdapPublishModule implements ILdapPublishModule {
} else {
mappers = (LdapMappers) mMappers.get(certType);
}
- return mappers;
+ return mappers;
}
protected void initMappers(IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
IConfigStore types = mConfig.getSubStore(PROP_TYPE);
if (types == null || types.size() <= 0) {
// nothing configured.
- if (Debug.ON)
+ if (Debug.ON)
System.out.println("No ldap publishing configurations.");
return;
}
@@ -198,9 +189,9 @@ public class LdapPublishModule implements ILdapPublishModule {
String certType = (String) substores.nextElement();
IConfigStore current = types.getSubStore(certType);
- if (current == null || current.size() <= 0) {
+ if (current == null || current.size() <= 0) {
CMS.debug(
- "No ldap publish configuration for " + certType + " found.");
+ "No ldap publish configuration for " + certType + " found.");
continue;
}
ILdapPlugin mapper = null, publisher = null;
@@ -212,53 +203,53 @@ public class LdapPublishModule implements ILdapPublishModule {
mapperClassName = mapperConf.getString(PROP_CLASS, null);
if (mapperClassName != null && mapperClassName.length() > 0) {
CMS.debug(
- "mapper " + mapperClassName + " for " + certType);
+ "mapper " + mapperClassName + " for " + certType);
mapper = (ILdapPlugin)
Class.forName(mapperClassName).newInstance();
mapper.init(mapperConf);
}
publisherConf = current.getSubStore(PROP_PUBLISHER);
publisherClassName = publisherConf.getString(PROP_CLASS, null);
- if (publisherClassName != null &&
- publisherClassName.length() > 0) {
+ if (publisherClassName != null &&
+ publisherClassName.length() > 0) {
CMS.debug(
- "publisher " + publisherClassName + " for " + certType);
+ "publisher " + publisherClassName + " for " + certType);
publisher = (ILdapPlugin)
Class.forName(publisherClassName).newInstance();
publisher.init(publisherConf);
}
mMappers.put(certType, new LdapMappers(mapper, publisher));
} catch (ClassNotFoundException e) {
- String missingClass = mapperClassName +
- ((publisherClassName == null) ? "" :
- (" or " + publisherClassName));
+ String missingClass = mapperClassName +
+ ((publisherClassName == null) ? "" :
+ (" or " + publisherClassName));
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAP_FIND_CLASS", missingClass));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_LDAP_FIND_CLASS", missingClass));
throw new ELdapException(
- CMS.getUserMessage("CMS_LDAP_CLASS_NOT_FOUND", missingClass));
+ CMS.getUserMessage("CMS_LDAP_CLASS_NOT_FOUND", missingClass));
} catch (InstantiationException e) {
- String badInstance = mapperClassName +
- ((publisherClassName == null) ? "" :
- (" or " + publisherClassName));
+ String badInstance = mapperClassName +
+ ((publisherClassName == null) ? "" :
+ (" or " + publisherClassName));
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAP_INST_CLASS",
- badInstance ,certType));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_LDAP_INST_CLASS",
+ badInstance, certType));
throw new ELdapException(
- CMS.getUserMessage("CMS_LDAP_INSTANTIATING_CLASS_FAILED", badInstance));
+ CMS.getUserMessage("CMS_LDAP_INSTANTIATING_CLASS_FAILED", badInstance));
} catch (IllegalAccessException e) {
- String badInstance = mapperClassName +
- ((publisherClassName == null) ? "" :
- (" or " + publisherClassName));
+ String badInstance = mapperClassName +
+ ((publisherClassName == null) ? "" :
+ (" or " + publisherClassName));
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAP_INSUFFICIENT_CREDENTIALS", badInstance, certType));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_LDAP_INSUFFICIENT_CREDENTIALS", badInstance, certType));
throw new ELdapException(
- CMS.getUserMessage("CMS_LDAP_INSUFFICIENT_CREDENTIALS", certType));
+ CMS.getUserMessage("CMS_LDAP_INSUFFICIENT_CREDENTIALS", certType));
} catch (EBaseException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAP_INIT_ERROR", certType, e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_LDAP_INIT_ERROR", certType, e.toString()));
throw e;
}
}
@@ -266,14 +257,14 @@ public class LdapPublishModule implements ILdapPublishModule {
}
protected void initHandlers() {
- mEventHandlers.put(IRequest.ENROLLMENT_REQUEST,
- new HandleEnrollment(this));
+ mEventHandlers.put(IRequest.ENROLLMENT_REQUEST,
+ new HandleEnrollment(this));
mEventHandlers.put(IRequest.RENEWAL_REQUEST,
- new HandleRenewal(this));
- mEventHandlers.put(IRequest.REVOCATION_REQUEST,
- new HandleRevocation(this));
- mEventHandlers.put(IRequest.UNREVOCATION_REQUEST,
- new HandleUnrevocation(this));
+ new HandleRenewal(this));
+ mEventHandlers.put(IRequest.REVOCATION_REQUEST,
+ new HandleRevocation(this));
+ mEventHandlers.put(IRequest.UNREVOCATION_REQUEST,
+ new HandleUnrevocation(this));
}
public void accept(IRequest r) {
@@ -284,14 +275,14 @@ public class LdapPublishModule implements ILdapPublishModule {
if (handler == null) {
CMS.debug(
- "Nothing to publish for request type " + type);
+ "Nothing to publish for request type " + type);
return;
}
handler.accept(r);
}
public void publish(String certType, X509Certificate cert)
- throws ELdapException {
+ throws ELdapException {
// get mapper and publisher for cert type.
LdapMappers mappers = getMappers(certType);
@@ -299,15 +290,15 @@ public class LdapPublishModule implements ILdapPublishModule {
CMS.debug("publisher for " + certType + " is null");
return;
}
- publish((ILdapMapper) mappers.mapper,
- (ILdapPublisher) mappers.publisher, cert);
+ publish((ILdapMapper) mappers.mapper,
+ (ILdapPublisher) mappers.publisher, cert);
// set the ldap published flag.
setPublishedFlag(cert.getSerialNumber(), true);
}
public void unpublish(String certType, X509Certificate cert)
- throws ELdapException {
+ throws ELdapException {
// get mapper and publisher for cert type.
LdapMappers mappers = getMappers(certType);
@@ -315,19 +306,19 @@ public class LdapPublishModule implements ILdapPublishModule {
CMS.debug("publisher for " + certType + " is null");
return;
}
- unpublish((ILdapMapper) mappers.mapper,
- (ILdapPublisher) mappers.publisher, cert);
+ unpublish((ILdapMapper) mappers.mapper,
+ (ILdapPublisher) mappers.publisher, cert);
// set the ldap published flag.
setPublishedFlag(cert.getSerialNumber(), false);
}
/**
- * set published flag - true when published, false when unpublished.
- * not exist means not published.
+ * set published flag - true when published, false when unpublished. not
+ * exist means not published.
*/
public void setPublishedFlag(BigInteger serialNo, boolean published) {
- if (!(mAuthority instanceof ICertificateAuthority))
+ if (!(mAuthority instanceof ICertificateAuthority))
return;
ICertificateAuthority ca = (ICertificateAuthority) mAuthority;
@@ -340,18 +331,18 @@ public class LdapPublishModule implements ILdapPublishModule {
metaInfo = new MetaInfo();
}
metaInfo.set(
- CertRecord.META_LDAPPUBLISH, String.valueOf(published));
+ CertRecord.META_LDAPPUBLISH, String.valueOf(published));
ModificationSet modSet = new ModificationSet();
- modSet.add(ICertRecord.ATTR_META_INFO,
- Modification.MOD_REPLACE, metaInfo);
+ modSet.add(ICertRecord.ATTR_META_INFO,
+ Modification.MOD_REPLACE, metaInfo);
certdb.modifyCertificateRecord(serialNo, modSet);
} catch (EBaseException e) {
// not fatal. just log warning.
- log(ILogger.LL_WARN,
- "Cannot mark cert 0x" + serialNo.toString(16) + " published as " + published +
- " in the ldap directory. Cert Record not found. Error: " +
- e.getMessage());
+ log(ILogger.LL_WARN,
+ "Cannot mark cert 0x" + serialNo.toString(16) + " published as " + published +
+ " in the ldap directory. Cert Record not found. Error: " +
+ e.getMessage());
}
}
@@ -364,8 +355,8 @@ public class LdapPublishModule implements ILdapPublishModule {
}
public void publish(ILdapMapper mapper, ILdapPublisher publisher,
- X509Certificate cert)
- throws ELdapException {
+ X509Certificate cert)
+ throws ELdapException {
LDAPConnection conn = null;
try {
@@ -376,17 +367,17 @@ public class LdapPublishModule implements ILdapPublishModule {
if (mapper == null) { // use the cert's subject name exactly
dirdn = cert.getSubjectDN().toString();
CMS.debug(
- "no mapper found. Using subject name exactly." +
- cert.getSubjectDN());
+ "no mapper found. Using subject name exactly." +
+ cert.getSubjectDN());
} else {
result = mapper.map(conn, cert);
dirdn = result;
- if (dirdn == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAP_PUBLISH_NOT_MATCH",
- cert.getSerialNumber().toString(16),
- cert.getSubjectDN().toString()));
- throw new ELdapException(CMS.getUserMessage("CMS_LDAP_NO_MATCH",
+ if (dirdn == null) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_LDAP_PUBLISH_NOT_MATCH",
+ cert.getSerialNumber().toString(16),
+ cert.getSubjectDN().toString()));
+ throw new ELdapException(CMS.getUserMessage("CMS_LDAP_NO_MATCH",
cert.getSubjectDN().toString()));
}
}
@@ -399,8 +390,8 @@ public class LdapPublishModule implements ILdapPublishModule {
}
public void unpublish(ILdapMapper mapper, ILdapPublisher publisher,
- X509Certificate cert)
- throws ELdapException {
+ X509Certificate cert)
+ throws ELdapException {
LDAPConnection conn = null;
try {
@@ -413,12 +404,12 @@ public class LdapPublishModule implements ILdapPublishModule {
} else {
result = mapper.map(conn, cert);
dirdn = result;
- if (dirdn == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAP_PUBLISH_NOT_MATCH",
- cert.getSerialNumber().toString(16),
- cert.getSubjectDN().toString()));
- throw new ELdapException(CMS.getUserMessage("CMS_LDAP_NO_MATCH",
+ if (dirdn == null) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_LDAP_PUBLISH_NOT_MATCH",
+ cert.getSerialNumber().toString(16),
+ cert.getSubjectDN().toString()));
+ throw new ELdapException(CMS.getUserMessage("CMS_LDAP_NO_MATCH",
cert.getSubjectDN().toString()));
}
}
@@ -431,11 +422,11 @@ public class LdapPublishModule implements ILdapPublishModule {
}
/**
- * publishes a crl by mapping the issuer name in the crl to an entry
- * and publishing it there. entry must be a certificate authority.
+ * publishes a crl by mapping the issuer name in the crl to an entry and
+ * publishing it there. entry must be a certificate authority.
*/
- public void publish(X509CRLImpl crl)
- throws ELdapException {
+ public void publish(X509CRLImpl crl)
+ throws ELdapException {
ILdapCrlMapper mapper = null;
ILdapPublisher publisher = null;
@@ -458,17 +449,17 @@ public class LdapPublishModule implements ILdapPublishModule {
} else {
result = ((ILdapMapper) mappers.mapper).map(conn, crl);
dn = result;
- if (dn == null) {
+ if (dn == null) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_LDAP_CRL_NOT_MATCH"));
- throw new ELdapException(CMS.getUserMessage("CMS_LDAP_NO_MATCH",
+ throw new ELdapException(CMS.getUserMessage("CMS_LDAP_NO_MATCH",
crl.getIssuerDN().toString()));
}
}
((ILdapPublisher) mappers.publisher).publish(conn, dn, crl);
} catch (ELdapException e) {
- //e.printStackTrace();
+ // e.printStackTrace();
CMS.debug(
- "Error publishing CRL to " + dn + ": " + e);
+ "Error publishing CRL to " + dn + ": " + e);
throw e;
} catch (IOException e) {
CMS.debug("Error publishing CRL to " + dn + ": " + e);
@@ -481,11 +472,11 @@ public class LdapPublishModule implements ILdapPublishModule {
}
/**
- * publishes a crl by mapping the issuer name in the crl to an entry
- * and publishing it there. entry must be a certificate authority.
+ * publishes a crl by mapping the issuer name in the crl to an entry and
+ * publishing it there. entry must be a certificate authority.
*/
- public void publish(String dn, X509CRL crl)
- throws ELdapException {
+ public void publish(String dn, X509CRL crl)
+ throws ELdapException {
LdapMappers mappers = getMappers(PROP_TYPE_CRL);
if (mappers == null || mappers.publisher == null) {
@@ -500,7 +491,7 @@ public class LdapPublishModule implements ILdapPublishModule {
((ILdapPublisher) mappers.publisher).publish(conn, dn, crl);
} catch (ELdapException e) {
CMS.debug(
- "Error publishing CRL to " + dn + ": " + e.toString());
+ "Error publishing CRL to " + dn + ": " + e.toString());
throw e;
} finally {
if (conn != null) {
@@ -510,23 +501,22 @@ public class LdapPublishModule implements ILdapPublishModule {
}
public void log(int level, String msg) {
- mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_LDAP, level,
- "LdapPublishModule: " + msg);
+ mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_LDAP, level,
+ "LdapPublishModule: " + msg);
}
-
-}
+}
class LdapMappers {
public LdapMappers(ILdapPlugin aMapper, ILdapPlugin aPublisher) {
mapper = aMapper;
publisher = aPublisher;
}
+
public ILdapPlugin mapper = null;
public ILdapPlugin publisher = null;
}
-
class HandleEnrollment implements IRequestListener {
LdapPublishModule mModule = null;
@@ -534,49 +524,47 @@ class HandleEnrollment implements IRequestListener {
mModule = module;
}
- public void set(String name, String val)
- {
+ public void set(String name, String val) {
}
- public void init(ISubsystem sub, IConfigStore config) throws EBaseException
- {
+ public void init(ISubsystem sub, IConfigStore config) throws EBaseException {
}
public void accept(IRequest r) {
CMS.debug(
- "handling publishing for enrollment request id " +
- r.getRequestId());
+ "handling publishing for enrollment request id " +
+ r.getRequestId());
// in case it's not meant for us
if (r.getExtDataInInteger(IRequest.RESULT) == null)
return;
- // check if request failed.
+ // check if request failed.
if ((r.getExtDataInInteger(IRequest.RESULT)).equals(IRequest.RES_ERROR)) {
CMS.debug("Request errored. " +
- "Nothing to publish for enrollment request id " +
- r.getRequestId());
+ "Nothing to publish for enrollment request id " +
+ r.getRequestId());
return;
}
CMS.debug("Checking publishing for request " +
- r.getRequestId());
+ r.getRequestId());
// check if issued certs is set.
X509CertImpl[] certs = r.getExtDataInCertArray(IRequest.ISSUED_CERTS);
if (certs == null || certs.length == 0 || certs[0] == null) {
CMS.debug(
- "No certs to publish for request id " + r.getRequestId());
+ "No certs to publish for request id " + r.getRequestId());
return;
}
// get mapper and publisher for client certs.
- LdapMappers mappers =
- mModule.getMappers(LdapPublishModule.PROP_TYPE_CLIENT);
+ LdapMappers mappers =
+ mModule.getMappers(LdapPublishModule.PROP_TYPE_CLIENT);
if (mappers == null || mappers.publisher == null) {
CMS.debug(
- "In publishing: No publisher for type " +
- LdapPublishModule.PROP_TYPE_CLIENT);
+ "In publishing: No publisher for type " +
+ LdapPublishModule.PROP_TYPE_CLIENT);
return;
}
@@ -586,18 +574,18 @@ class HandleEnrollment implements IRequestListener {
for (int i = 0; i < certs.length; i++) {
try {
- if (certs[i] == null)
+ if (certs[i] == null)
continue;
- mModule.publish((ILdapMapper) mappers.mapper,
- (ILdapPublisher) mappers.publisher, certs[i]);
+ mModule.publish((ILdapMapper) mappers.mapper,
+ (ILdapPublisher) mappers.publisher, certs[i]);
results[i] = IRequest.RES_SUCCESS;
CMS.debug(
- "Published cert serial no 0x" + certs[i].getSerialNumber().toString(16));
+ "Published cert serial no 0x" + certs[i].getSerialNumber().toString(16));
mModule.setPublishedFlag(certs[i].getSerialNumber(), true);
} catch (ELdapException e) {
- mModule.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAP_CERT_NOT_PUBLISH",
- certs[i].getSerialNumber().toString(16),e.toString()));
+ mModule.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_LDAP_CERT_NOT_PUBLISH",
+ certs[i].getSerialNumber().toString(16), e.toString()));
results[i] = IRequest.RES_ERROR;
}
r.setExtData("ldapPublishStatus", results);
@@ -605,40 +593,38 @@ class HandleEnrollment implements IRequestListener {
}
}
-
class HandleRenewal implements IRequestListener {
private LdapPublishModule mModule = null;
+
public HandleRenewal(LdapPublishModule module) {
mModule = module;
}
- public void init(ISubsystem sub, IConfigStore config) throws EBaseException
- {
- }
+ public void init(ISubsystem sub, IConfigStore config) throws EBaseException {
+ }
- public void set(String name, String val)
- {
+ public void set(String name, String val) {
}
public void accept(IRequest r) {
- // Note we do not remove old certs from directory during renewal
+ // Note we do not remove old certs from directory during renewal
X509CertImpl[] certs = r.getExtDataInCertArray(IRequest.ISSUED_CERTS);
if (certs == null || certs.length == 0) {
CMS.debug("no certs to publish for renewal " +
- "request " + r.getRequestId());
+ "request " + r.getRequestId());
return;
}
Integer results[] = new Integer[certs.length];
X509CertImpl cert = null;
// get mapper and publisher for cert type.
- LdapMappers mappers =
- mModule.getMappers(LdapPublishModule.PROP_TYPE_CLIENT);
+ LdapMappers mappers =
+ mModule.getMappers(LdapPublishModule.PROP_TYPE_CLIENT);
if (mappers == null || mappers.publisher == null) {
CMS.debug(
- "publisher for " + LdapPublishModule.PROP_TYPE_CLIENT + " is null");
+ "publisher for " + LdapPublishModule.PROP_TYPE_CLIENT + " is null");
return;
}
@@ -646,46 +632,44 @@ class HandleRenewal implements IRequestListener {
for (int i = 0; i < certs.length; i++) {
cert = (X509CertImpl) certs[i];
- if (cert == null)
+ if (cert == null)
continue; // there was an error issuing this cert.
try {
- mModule.publish((ILdapMapper) mappers.mapper,
- (ILdapPublisher) mappers.publisher, cert);
+ mModule.publish((ILdapMapper) mappers.mapper,
+ (ILdapPublisher) mappers.publisher, cert);
results[i] = IRequest.RES_SUCCESS;
- mModule.log(ILogger.LL_INFO,
- "Published cert serial no 0x" + cert.getSerialNumber().toString(16));
+ mModule.log(ILogger.LL_INFO,
+ "Published cert serial no 0x" + cert.getSerialNumber().toString(16));
} catch (ELdapException e) {
error = true;
- mModule.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAP_CERT_NOT_PUBLISH",
- cert.getSerialNumber().toString(16), e.getMessage()));
+ mModule.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_LDAP_CERT_NOT_PUBLISH",
+ cert.getSerialNumber().toString(16), e.getMessage()));
results[i] = IRequest.RES_ERROR;
}
}
r.setExtData("ldapPublishStatus", results);
r.setExtData("ldapPublishOverAllStatus",
- (error == true ? IRequest.RES_ERROR : IRequest.RES_SUCCESS));
+ (error == true ? IRequest.RES_ERROR : IRequest.RES_SUCCESS));
}
}
-
class HandleRevocation implements IRequestListener {
private LdapPublishModule mModule = null;
+
public HandleRevocation(LdapPublishModule module) {
mModule = module;
}
- public void init(ISubsystem sub, IConfigStore config) throws EBaseException
- {
- }
+ public void init(ISubsystem sub, IConfigStore config) throws EBaseException {
+ }
- public void set(String name, String val)
- {
+ public void set(String name, String val) {
}
public void accept(IRequest r) {
CMS.debug(
- "Handle publishing for revoke request id " + r.getRequestId());
+ "Handle publishing for revoke request id " + r.getRequestId());
// get fields in request.
X509CertImpl[] revcerts = r.getExtDataInCertArray(IRequest.OLD_CERTS);
@@ -693,18 +677,18 @@ class HandleRevocation implements IRequestListener {
if (revcerts == null || revcerts.length == 0 || revcerts[0] == null) {
// no certs in revoke.
CMS.debug(
- "Nothing to unpublish for revocation " +
- "request " + r.getRequestId());
+ "Nothing to unpublish for revocation " +
+ "request " + r.getRequestId());
return;
}
// get mapper and publisher for cert type.
- LdapMappers mappers =
- mModule.getMappers(LdapPublishModule.PROP_TYPE_CLIENT);
+ LdapMappers mappers =
+ mModule.getMappers(LdapPublishModule.PROP_TYPE_CLIENT);
if (mappers == null || mappers.publisher == null) {
CMS.debug(
- "publisher for " + LdapPublishModule.PROP_TYPE_CLIENT + " is null");
+ "publisher for " + LdapPublishModule.PROP_TYPE_CLIENT + " is null");
return;
}
@@ -716,41 +700,40 @@ class HandleRevocation implements IRequestListener {
results[i] = IRequest.RES_ERROR;
try {
- mModule.unpublish((ILdapMapper) mappers.mapper,
- (ILdapPublisher) mappers.publisher, cert);
+ mModule.unpublish((ILdapMapper) mappers.mapper,
+ (ILdapPublisher) mappers.publisher, cert);
results[i] = IRequest.RES_SUCCESS;
CMS.debug(
- "Unpublished cert serial no 0x" + cert.getSerialNumber().toString(16));
+ "Unpublished cert serial no 0x" + cert.getSerialNumber().toString(16));
} catch (ELdapException e) {
error = true;
- mModule.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAP_CERT_NOT_UNPUBLISH",
- cert.getSerialNumber().toString(16), e.getMessage()));
+ mModule.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_LDAP_CERT_NOT_UNPUBLISH",
+ cert.getSerialNumber().toString(16), e.getMessage()));
}
}
r.setExtData("ldapPublishStatus", results);
r.setExtData("ldapPublishOverAllStatus",
- (error == true ? IRequest.RES_ERROR : IRequest.RES_SUCCESS));
+ (error == true ? IRequest.RES_ERROR : IRequest.RES_SUCCESS));
}
}
-
class HandleUnrevocation implements IRequestListener {
private LdapPublishModule mModule = null;
+
public HandleUnrevocation(LdapPublishModule module) {
mModule = module;
}
- public void set(String name, String val)
- {
+ public void set(String name, String val) {
+ }
+
+ public void init(ISubsystem sub, IConfigStore config) throws EBaseException {
}
- public void init(ISubsystem sub, IConfigStore config) throws EBaseException
- {
- }
public void accept(IRequest r) {
CMS.debug(
- "Handle publishing for unrevoke request id " + r.getRequestId());
+ "Handle publishing for unrevoke request id " + r.getRequestId());
// get fields in request.
X509CertImpl[] certs = r.getExtDataInCertArray(IRequest.OLD_CERTS);
@@ -758,18 +741,18 @@ class HandleUnrevocation implements IRequestListener {
if (certs == null || certs.length == 0 || certs[0] == null) {
// no certs in unrevoke.
CMS.debug(
- "Nothing to publish for unrevocation " +
- "request " + r.getRequestId());
+ "Nothing to publish for unrevocation " +
+ "request " + r.getRequestId());
return;
}
// get mapper and publisher for cert type.
- LdapMappers mappers =
- mModule.getMappers(LdapPublishModule.PROP_TYPE_CLIENT);
+ LdapMappers mappers =
+ mModule.getMappers(LdapPublishModule.PROP_TYPE_CLIENT);
if (mappers == null || mappers.publisher == null) {
CMS.debug(
- "publisher for " + LdapPublishModule.PROP_TYPE_CLIENT + " is null");
+ "publisher for " + LdapPublishModule.PROP_TYPE_CLIENT + " is null");
return;
}
@@ -779,22 +762,21 @@ class HandleUnrevocation implements IRequestListener {
for (int i = 0; i < certs.length; i++) {
results[i] = IRequest.RES_ERROR;
try {
- mModule.publish((ILdapMapper) mappers.mapper,
- (ILdapPublisher) mappers.publisher, certs[i]);
+ mModule.publish((ILdapMapper) mappers.mapper,
+ (ILdapPublisher) mappers.publisher, certs[i]);
results[i] = IRequest.RES_SUCCESS;
CMS.debug(
- "Unpublished cert serial no 0x" + certs[i].getSerialNumber().toString(16));
+ "Unpublished cert serial no 0x" + certs[i].getSerialNumber().toString(16));
} catch (ELdapException e) {
error = true;
- mModule.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAP_CERT_NOT_UNPUBLISH",
- certs[i].getSerialNumber().toString(16), e.getMessage()));
+ mModule.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_LDAP_CERT_NOT_UNPUBLISH",
+ certs[i].getSerialNumber().toString(16), e.getMessage()));
}
}
r.setExtData("ldapPublishStatus", results);
r.setExtData("ldapPublishOverAllStatus",
- (error == true ? IRequest.RES_ERROR : IRequest.RES_SUCCESS));
+ (error == true ? IRequest.RES_ERROR : IRequest.RES_SUCCESS));
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/ldap/LdapRequestListener.java b/pki/base/common/src/com/netscape/cmscore/ldap/LdapRequestListener.java
index 6c1e1e8a..f67124a0 100644
--- a/pki/base/common/src/com/netscape/cmscore/ldap/LdapRequestListener.java
+++ b/pki/base/common/src/com/netscape/cmscore/ldap/LdapRequestListener.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.ldap;
-
import java.math.BigInteger;
import java.security.cert.Certificate;
import java.util.Hashtable;
@@ -42,13 +41,12 @@ import com.netscape.certsrv.request.IRequestListener;
import com.netscape.certsrv.request.RequestId;
import com.netscape.cmscore.dbs.CertRecord;
-
public class LdapRequestListener implements IRequestListener {
private boolean mInited = false;
/**
- * handlers for request types (events)
- * each handler implement IRequestListener
+ * handlers for request types (events) each handler implement
+ * IRequestListener
*/
private Hashtable mRequestListeners = new Hashtable();
@@ -57,23 +55,23 @@ public class LdapRequestListener implements IRequestListener {
public LdapRequestListener() {
}
- public void set(String name, String val)
- {
- }
+ public void set(String name, String val) {
+ }
public void init(ISubsystem sys, IConfigStore config) throws EBaseException {
- if (mInited) return;
+ if (mInited)
+ return;
- mPublisherProcessor = (IPublisherProcessor)sys;
+ mPublisherProcessor = (IPublisherProcessor) sys;
mRequestListeners.put(IRequest.ENROLLMENT_REQUEST,
- new LdapEnrollmentListener(mPublisherProcessor));
+ new LdapEnrollmentListener(mPublisherProcessor));
mRequestListeners.put(IRequest.RENEWAL_REQUEST,
- new LdapRenewalListener(mPublisherProcessor));
+ new LdapRenewalListener(mPublisherProcessor));
mRequestListeners.put(IRequest.REVOCATION_REQUEST,
- new LdapRevocationListener(mPublisherProcessor));
+ new LdapRevocationListener(mPublisherProcessor));
mRequestListeners.put(IRequest.UNREVOCATION_REQUEST,
- new LdapUnrevocationListener(mPublisherProcessor));
+ new LdapUnrevocationListener(mPublisherProcessor));
mInited = true;
}
@@ -86,33 +84,33 @@ public class LdapRequestListener implements IRequestListener {
if (r.getExtDataInInteger(IRequest.RESULT) == null)
return null;
- // check if request failed.
+ // check if request failed.
if ((r.getExtDataInInteger(IRequest.RESULT)).equals(IRequest.RES_ERROR)) {
CMS.debug("Request errored. " +
- "Nothing to publish for enrollment request id " +
- r.getRequestId());
+ "Nothing to publish for enrollment request id " +
+ r.getRequestId());
return null;
}
CMS.debug("Checking publishing for request " +
- r.getRequestId());
+ r.getRequestId());
// check if issued certs is set.
X509CertImpl[] certs = r.getExtDataInCertArray(IRequest.ISSUED_CERTS);
if (certs == null || certs.length == 0 || certs[0] == null) {
CMS.debug(
- "No certs to publish for request id " +
- r.getRequestId());
+ "No certs to publish for request id " +
+ r.getRequestId());
return null;
}
obj.setCerts(certs);
return obj;
} else if (type.equals(IRequest.RENEWAL_REQUEST)) {
- // Note we do not remove old certs from directory during renewal
+ // Note we do not remove old certs from directory during renewal
X509CertImpl[] certs = r.getExtDataInCertArray(IRequest.ISSUED_CERTS);
if (certs == null || certs.length == 0) {
CMS.debug("no certs to publish for renewal " +
- "request " + r.getRequestId());
+ "request " + r.getRequestId());
return null;
}
obj.setCerts(certs);
@@ -123,8 +121,8 @@ public class LdapRequestListener implements IRequestListener {
if (revcerts == null || revcerts.length == 0 || revcerts[0] == null) {
// no certs in revoke.
CMS.debug(
- "Nothing to unpublish for revocation " +
- "request " + r.getRequestId());
+ "Nothing to unpublish for revocation " +
+ "request " + r.getRequestId());
return null;
}
obj.setCerts(revcerts);
@@ -135,16 +133,16 @@ public class LdapRequestListener implements IRequestListener {
if (certs == null || certs.length == 0 || certs[0] == null) {
// no certs in unrevoke.
CMS.debug(
- "Nothing to publish for unrevocation " +
- "request " + r.getRequestId());
+ "Nothing to publish for unrevocation " +
+ "request " + r.getRequestId());
return null;
}
obj.setCerts(certs);
return obj;
} else {
CMS.debug("Request errored. " +
- "Nothing to publish for request id " +
- r.getRequestId());
+ "Nothing to publish for request id " +
+ r.getRequestId());
return null;
}
@@ -157,7 +155,7 @@ public class LdapRequestListener implements IRequestListener {
if (handler == null) {
CMS.debug(
- "Nothing to publish for request type " + type);
+ "Nothing to publish for request type " + type);
return;
}
handler.accept(r);
@@ -165,7 +163,6 @@ public class LdapRequestListener implements IRequestListener {
}
-
class LdapEnrollmentListener implements IRequestListener {
IPublisherProcessor mProcessor = null;
@@ -176,51 +173,50 @@ class LdapEnrollmentListener implements IRequestListener {
public void init(ISubsystem sys, IConfigStore config) throws EBaseException {
}
- public void set(String name, String val)
- {
+ public void set(String name, String val) {
}
public void accept(IRequest r) {
CMS.debug(
- "LdapRequestListener handling publishing for enrollment request id " +
- r.getRequestId());
+ "LdapRequestListener handling publishing for enrollment request id " +
+ r.getRequestId());
String profileId = r.getExtDataInString("profileId");
if (profileId == null) {
- // in case it's not meant for us
- if (r.getExtDataInInteger(IRequest.RESULT) == null)
- return;
+ // in case it's not meant for us
+ if (r.getExtDataInInteger(IRequest.RESULT) == null)
+ return;
// check if request failed.
- if ((r.getExtDataInInteger(IRequest.RESULT)).equals(IRequest.RES_ERROR)) {
- CMS.debug("Request errored. " +
- "Nothing to publish for enrollment request id " +
- r.getRequestId());
- return;
- }
- }
+ if ((r.getExtDataInInteger(IRequest.RESULT)).equals(IRequest.RES_ERROR)) {
+ CMS.debug("Request errored. " +
+ "Nothing to publish for enrollment request id " +
+ r.getRequestId());
+ return;
+ }
+ }
CMS.debug("Checking publishing for request " +
- r.getRequestId());
+ r.getRequestId());
// check if issued certs is set.
Certificate[] certs = null;
if (profileId == null) {
- certs = r.getExtDataInCertArray(IRequest.ISSUED_CERTS);
- } else {
- certs = new Certificate[1];
- certs[0] = r.getExtDataInCert(IEnrollProfile.REQUEST_ISSUED_CERT);
- }
+ certs = r.getExtDataInCertArray(IRequest.ISSUED_CERTS);
+ } else {
+ certs = new Certificate[1];
+ certs[0] = r.getExtDataInCert(IEnrollProfile.REQUEST_ISSUED_CERT);
+ }
if (certs == null || certs.length == 0 || certs[0] == null) {
CMS.debug(
- "No certs to publish for request id " + r.getRequestId());
+ "No certs to publish for request id " + r.getRequestId());
return;
}
-
+
if (certs[0] instanceof X509CertImpl)
acceptX509(r, certs);
}
-
+
public void acceptX509(IRequest r, Certificate[] certs) {
Integer results[] = new Integer[certs.length];
boolean error = false;
@@ -228,58 +224,57 @@ class LdapEnrollmentListener implements IRequestListener {
for (int i = 0; i < certs.length; i++) {
X509CertImpl xcert = (X509CertImpl) certs[i];
- if (xcert == null)
+ if (xcert == null)
continue;
try {
mProcessor.publishCert(xcert, r);
-
+
results[i] = IRequest.RES_SUCCESS;
CMS.debug(
- "acceptX509: Published cert serial no 0x" +
- xcert.getSerialNumber().toString(16));
- //mProcessor.setPublishedFlag(xcert.getSerialNumber(), true);
+ "acceptX509: Published cert serial no 0x" +
+ xcert.getSerialNumber().toString(16));
+ // mProcessor.setPublishedFlag(xcert.getSerialNumber(), true);
} catch (ELdapException e) {
- mProcessor.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAP_CERT_NOT_PUBLISH",
- xcert.getSerialNumber().toString(16), e.toString()));
+ mProcessor.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_LDAP_CERT_NOT_PUBLISH",
+ xcert.getSerialNumber().toString(16), e.toString()));
results[i] = IRequest.RES_ERROR;
error = true;
}
}
r.setExtData("ldapPublishStatus", results);
r.setExtData("ldapPublishOverAllStatus",
- (error == true ? IRequest.RES_ERROR : IRequest.RES_SUCCESS));
+ (error == true ? IRequest.RES_ERROR : IRequest.RES_SUCCESS));
}
}
-
class LdapRenewalListener implements IRequestListener {
private IPublisherProcessor mProcessor = null;
public LdapRenewalListener(IPublisherProcessor processor) {
mProcessor = processor;
}
+
public void init(ISubsystem sys, IConfigStore config) throws EBaseException {
}
- public void set(String name, String val)
- {
+ public void set(String name, String val) {
}
public void accept(IRequest r) {
- // Note we do not remove old certs from directory during renewal
+ // Note we do not remove old certs from directory during renewal
Certificate[] certs = r.getExtDataInCertArray(IRequest.ISSUED_CERTS);
if (certs == null || certs.length == 0) {
CMS.debug("no certs to publish for renewal " +
- "request " + r.getRequestId());
+ "request " + r.getRequestId());
return;
}
-
+
if (certs[0] instanceof X509CertImpl)
acceptX509(r, certs);
}
-
+
public void acceptX509(IRequest r, Certificate[] certs) {
X509CertImpl cert = null;
@@ -288,45 +283,44 @@ class LdapRenewalListener implements IRequestListener {
for (int i = 0; i < certs.length; i++) {
cert = (X509CertImpl) certs[i];
- if (cert == null)
+ if (cert == null)
continue; // there was an error issuing this cert.
try {
mProcessor.publishCert(cert, r);
results[i] = IRequest.RES_SUCCESS;
- mProcessor.log(ILogger.LL_INFO,
- "Published cert serial no 0x" +
- cert.getSerialNumber().toString(16));
+ mProcessor.log(ILogger.LL_INFO,
+ "Published cert serial no 0x" +
+ cert.getSerialNumber().toString(16));
} catch (ELdapException e) {
error = true;
- mProcessor.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAP_CERT_NOT_PUBLISH",
- cert.getSerialNumber().toString(16), e.toString()));
+ mProcessor.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_LDAP_CERT_NOT_PUBLISH",
+ cert.getSerialNumber().toString(16), e.toString()));
results[i] = IRequest.RES_ERROR;
}
}
r.setExtData("ldapPublishStatus", results);
r.setExtData("ldapPublishOverAllStatus",
- (error == true ? IRequest.RES_ERROR : IRequest.RES_SUCCESS));
+ (error == true ? IRequest.RES_ERROR : IRequest.RES_SUCCESS));
}
}
-
class LdapRevocationListener implements IRequestListener {
private IPublisherProcessor mProcessor = null;
public LdapRevocationListener(IPublisherProcessor processor) {
mProcessor = processor;
}
+
public void init(ISubsystem sys, IConfigStore config) throws EBaseException {
}
- public void set(String name, String val)
- {
+ public void set(String name, String val) {
}
public void accept(IRequest r) {
CMS.debug(
- "Handle publishing for revoke request id " + r.getRequestId());
+ "Handle publishing for revoke request id " + r.getRequestId());
// get fields in request.
Certificate[] certs = r.getExtDataInCertArray(IRequest.OLD_CERTS);
@@ -334,15 +328,15 @@ class LdapRevocationListener implements IRequestListener {
if (certs == null || certs.length == 0 || certs[0] == null) {
// no certs in revoke.
CMS.debug(
- "Nothing to unpublish for revocation " +
- "request " + r.getRequestId());
+ "Nothing to unpublish for revocation " +
+ "request " + r.getRequestId());
return;
}
-
+
if (certs[0] instanceof X509CertImpl)
acceptX509(r, certs);
}
-
+
public void acceptX509(IRequest r, Certificate[] revcerts) {
boolean error = false;
Integer results[] = new Integer[revcerts.length];
@@ -356,15 +350,15 @@ class LdapRevocationListener implements IRequestListener {
// We need the enrollment request to sort out predicate
BigInteger serial = cert.getSerialNumber();
ICertRecord certRecord = null;
- IAuthority auth = (IAuthority)mProcessor.getAuthority();
+ IAuthority auth = (IAuthority) mProcessor.getAuthority();
if (auth == null ||
- !(auth instanceof ICertificateAuthority)) {
+ !(auth instanceof ICertificateAuthority)) {
mProcessor.log(ILogger.LL_WARN,
- "Trying to get a certificate from non certificate authority.");
+ "Trying to get a certificate from non certificate authority.");
} else {
ICertificateRepository certdb =
- (ICertificateRepository) ((ICertificateAuthority) auth).getCertificateRepository();
+ (ICertificateRepository) ((ICertificateAuthority) auth).getCertificateRepository();
if (certdb == null) {
mProcessor.log(ILogger.LL_WARN, "Cert DB is null for " + auth);
@@ -373,72 +367,72 @@ class LdapRevocationListener implements IRequestListener {
certRecord = (ICertRecord) certdb.readCertificateRecord(serial);
} catch (EBaseException e) {
mProcessor.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAP_GET_CERT_RECORD",
- serial.toString(16), e.toString()));
+ CMS.getLogMessage("CMSCORE_LDAP_GET_CERT_RECORD",
+ serial.toString(16), e.toString()));
}
}
}
MetaInfo metaInfo = null;
String ridString = null;
-
+
if (certRecord != null)
- metaInfo =
+ metaInfo =
(MetaInfo) certRecord.get(ICertRecord.ATTR_META_INFO);
if (metaInfo == null) {
- mProcessor.log(ILogger.LL_FAILURE,
- "failed getting CertRecord.ATTR_META_INFO for cert serial number 0x" +
- serial.toString(16));
+ mProcessor.log(ILogger.LL_FAILURE,
+ "failed getting CertRecord.ATTR_META_INFO for cert serial number 0x" +
+ serial.toString(16));
} else {
ridString = (String) metaInfo.get(ICertRecord.META_REQUEST_ID);
}
-
+
IRequest req = null;
if (ridString != null) {
RequestId rid = new RequestId(ridString);
-
+
req = auth.getRequestQueue().findRequest(rid);
- }
+ }
mProcessor.unpublishCert(cert, req);
results[i] = IRequest.RES_SUCCESS;
CMS.debug(
- "Unpublished cert serial no 0x" +
- cert.getSerialNumber().toString(16));
+ "Unpublished cert serial no 0x" +
+ cert.getSerialNumber().toString(16));
} catch (ELdapException e) {
error = true;
- mProcessor.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAP_CERT_NOT_UNPUBLISH",
- cert.getSerialNumber().toString(16), e.toString()));
+ mProcessor.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_LDAP_CERT_NOT_UNPUBLISH",
+ cert.getSerialNumber().toString(16), e.toString()));
} catch (EBaseException e) {
error = true;
- mProcessor.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAP_CERT_NOT_FIND",
- cert.getSerialNumber().toString(16), e.toString()));
+ mProcessor.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_LDAP_CERT_NOT_FIND",
+ cert.getSerialNumber().toString(16), e.toString()));
}
}
r.setExtData("ldapPublishStatus", results);
r.setExtData("ldapPublishOverAllStatus",
- (error == true ? IRequest.RES_ERROR : IRequest.RES_SUCCESS));
+ (error == true ? IRequest.RES_ERROR : IRequest.RES_SUCCESS));
}
}
-
class LdapUnrevocationListener implements IRequestListener {
private IPublisherProcessor mProcessor = null;
public LdapUnrevocationListener(IPublisherProcessor processor) {
mProcessor = processor;
}
+
public void init(ISubsystem sys, IConfigStore config) throws EBaseException {
}
- public void set(String name, String val)
- {
+
+ public void set(String name, String val) {
}
public void accept(IRequest r) {
CMS.debug(
- "Handle publishing for unrevoke request id " + r.getRequestId());
+ "Handle publishing for unrevoke request id " + r.getRequestId());
// get fields in request.
Certificate[] certs = r.getExtDataInCertArray(IRequest.OLD_CERTS);
@@ -446,15 +440,15 @@ class LdapUnrevocationListener implements IRequestListener {
if (certs == null || certs.length == 0 || certs[0] == null) {
// no certs in unrevoke.
CMS.debug(
- "Nothing to publish for unrevocation " +
- "request " + r.getRequestId());
+ "Nothing to publish for unrevocation " +
+ "request " + r.getRequestId());
return;
}
-
+
if (certs[0] instanceof X509CertImpl)
acceptX509(r, certs);
}
-
+
public void acceptX509(IRequest r, Certificate[] certs) {
boolean error = false;
Integer results[] = new Integer[certs.length];
@@ -467,15 +461,15 @@ class LdapUnrevocationListener implements IRequestListener {
// We need the enrollment request to sort out predicate
BigInteger serial = xcert.getSerialNumber();
ICertRecord certRecord = null;
- IAuthority auth = (IAuthority)mProcessor.getAuthority();
+ IAuthority auth = (IAuthority) mProcessor.getAuthority();
if (auth == null ||
- !(auth instanceof ICertificateAuthority)) {
+ !(auth instanceof ICertificateAuthority)) {
mProcessor.log(ILogger.LL_WARN,
- "Trying to get a certificate from non certificate authority.");
+ "Trying to get a certificate from non certificate authority.");
} else {
ICertificateRepository certdb = (ICertificateRepository)
- ((ICertificateAuthority) auth).getCertificateRepository();
+ ((ICertificateAuthority) auth).getCertificateRepository();
if (certdb == null) {
mProcessor.log(ILogger.LL_WARN, "Cert DB is null for " + auth);
@@ -484,52 +478,51 @@ class LdapUnrevocationListener implements IRequestListener {
certRecord = (ICertRecord) certdb.readCertificateRecord(serial);
} catch (EBaseException e) {
mProcessor.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAP_GET_CERT_RECORD", serial.toString(16), e.toString()));
+ CMS.getLogMessage("CMSCORE_LDAP_GET_CERT_RECORD", serial.toString(16), e.toString()));
}
}
}
MetaInfo metaInfo = null;
String ridString = null;
-
+
if (certRecord != null)
- metaInfo =
+ metaInfo =
(MetaInfo) certRecord.get(CertRecord.ATTR_META_INFO);
if (metaInfo == null) {
- mProcessor.log(ILogger.LL_FAILURE,
- "Failed getting CertRecord.ATTR_META_INFO for cert serial number 0x" +
- serial.toString(16));
+ mProcessor.log(ILogger.LL_FAILURE,
+ "Failed getting CertRecord.ATTR_META_INFO for cert serial number 0x" +
+ serial.toString(16));
} else {
ridString = (String) metaInfo.get(CertRecord.META_REQUEST_ID);
}
-
+
IRequest req = null;
if (ridString != null) {
RequestId rid = new RequestId(ridString);
-
+
req = auth.getRequestQueue().findRequest(rid);
- }
+ }
mProcessor.publishCert(xcert, req);
results[i] = IRequest.RES_SUCCESS;
CMS.debug(
- "Published cert serial no 0x" +
- xcert.getSerialNumber().toString(16));
+ "Published cert serial no 0x" +
+ xcert.getSerialNumber().toString(16));
} catch (ELdapException e) {
error = true;
- mProcessor.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAP_CERT_NOT_PUBLISH",
- xcert.getSerialNumber().toString(16), e.toString()));
+ mProcessor.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_LDAP_CERT_NOT_PUBLISH",
+ xcert.getSerialNumber().toString(16), e.toString()));
} catch (EBaseException e) {
error = true;
- mProcessor.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAP_CERT_NOT_FIND",
- xcert.getSerialNumber().toString(16), e.toString()));
- }
+ mProcessor.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_LDAP_CERT_NOT_FIND",
+ xcert.getSerialNumber().toString(16), e.toString()));
+ }
}
r.setExtData("ldapPublishStatus", results);
r.setExtData("ldapPublishOverAllStatus",
- (error == true ? IRequest.RES_ERROR : IRequest.RES_SUCCESS));
+ (error == true ? IRequest.RES_ERROR : IRequest.RES_SUCCESS));
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/ldap/LdapRule.java b/pki/base/common/src/com/netscape/cmscore/ldap/LdapRule.java
index 233cbf87..53da0f35 100644
--- a/pki/base/common/src/com/netscape/cmscore/ldap/LdapRule.java
+++ b/pki/base/common/src/com/netscape/cmscore/ldap/LdapRule.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.ldap;
-
import java.util.Enumeration;
import java.util.Locale;
import java.util.Vector;
@@ -30,8 +29,7 @@ import com.netscape.certsrv.publish.ILdapRule;
import com.netscape.certsrv.publish.IPublisherProcessor;
import com.netscape.cmscore.util.Debug;
-
-/**
+/**
* The publishing rule that links mapper and publisher together.
*/
public class LdapRule implements ILdapRule, IExtendedPluginInfo {
@@ -43,15 +41,15 @@ public class LdapRule implements ILdapRule, IExtendedPluginInfo {
private IPublisherProcessor mProcessor = null;
- private static String[] epi_params = null; // extendedpluginInfo
+ private static String[] epi_params = null; // extendedpluginInfo
public IConfigStore getConfigStore() {
return mConfig;
}
public String[] getExtendedPluginInfo(Locale locale) {
- //dont know why it's null here.
- //if (mProcessor == null) System.out.println("p null");
+ // dont know why it's null here.
+ // if (mProcessor == null) System.out.println("p null");
if (Debug.ON) {
Debug.trace("LdapRule: getExtendedPluginInfo() - returning epi_params:");
@@ -61,7 +59,7 @@ public class LdapRule implements ILdapRule, IExtendedPluginInfo {
}
return epi_params;
}
-
+
public void init(IPublisherProcessor processor, IConfigStore config) throws EBaseException {
mConfig = config;
@@ -72,14 +70,14 @@ public class LdapRule implements ILdapRule, IExtendedPluginInfo {
String map = NOMAPPER;
for (; mappers.hasMoreElements();) {
- String name = mappers.nextElement();
+ String name = mappers.nextElement();
map = map + "," + name;
}
String publish = "";
for (; publishers.hasMoreElements();) {
- String name = publishers.nextElement();
+ String name = publishers.nextElement();
publish = publish + "," + name;
}
@@ -94,7 +92,7 @@ public class LdapRule implements ILdapRule, IExtendedPluginInfo {
// Read the predicate expression if any associated
// with the rule
- String exp = config.getString(IPublisherProcessor.PROP_PREDICATE, null);
+ String exp = config.getString(IPublisherProcessor.PROP_PREDICATE, null);
if (exp != null)
exp = exp.trim();
@@ -103,14 +101,13 @@ public class LdapRule implements ILdapRule, IExtendedPluginInfo {
setPredicate(filterExp);
}
- //if (mProcessor == null) System.out.println("null");
+ // if (mProcessor == null) System.out.println("null");
}
/**
- * The init method in ILdapPlugin
- * It can not set set mapper,publisher choice for console dynamicly
- * Should not use this method to init.
+ * The init method in ILdapPlugin It can not set set mapper,publisher choice
+ * for console dynamicly Should not use this method to init.
*/
public void init(IConfigStore config) throws EBaseException {
mConfig = config;
@@ -125,7 +122,7 @@ public class LdapRule implements ILdapRule, IExtendedPluginInfo {
// Read the predicate expression if any associated
// with the rule
- String exp = config.getString(IPublisherProcessor.PROP_PREDICATE, null);
+ String exp = config.getString(IPublisherProcessor.PROP_PREDICATE, null);
if (exp != null)
exp = exp.trim();
@@ -169,8 +166,8 @@ public class LdapRule implements ILdapRule, IExtendedPluginInfo {
* Returns the current instance parameters.
*/
public Vector<String> getInstanceParams() {
- //if (mProcessor == null) System.out.println("xxxxnull");
- //dont know why the processor was null in getExtendedPluginInfo()
+ // if (mProcessor == null) System.out.println("xxxxnull");
+ // dont know why the processor was null in getExtendedPluginInfo()
Enumeration<String> mappers = mProcessor.getMapperInsts().keys();
Enumeration<String> publishers = mProcessor.getPublisherInsts().keys();
String map = NOMAPPER;
@@ -189,31 +186,34 @@ public class LdapRule implements ILdapRule, IExtendedPluginInfo {
}
/*
- mExtendedPluginInfo = new NameValuePairs();
- mExtendedPluginInfo.add("type","choice(client,server,objSignClient,smime,ca,crl);The publishing object type");
- mExtendedPluginInfo.add("mapper","choice("+map+");Use the mapper to find the ldap dn \nto publish the certificate or crl");
- mExtendedPluginInfo.add("publisher","choice("+publish+");Use the publisher to publish the certificate or crl a directory etc");
- mExtendedPluginInfo.add("enable","boolean;");
- mExtendedPluginInfo.add("predicate","string;");
+ * mExtendedPluginInfo = new NameValuePairs();
+ * mExtendedPluginInfo.add("type",
+ * "choice(client,server,objSignClient,smime,ca,crl);The publishing object type"
+ * ); mExtendedPluginInfo.add("mapper","choice("+map+
+ * ");Use the mapper to find the ldap dn \nto publish the certificate or crl"
+ * ); mExtendedPluginInfo.add("publisher","choice("+publish+
+ * ");Use the publisher to publish the certificate or crl a directory etc"
+ * ); mExtendedPluginInfo.add("enable","boolean;");
+ * mExtendedPluginInfo.add("predicate","string;");
*/
Vector<String> v = new Vector<String>();
try {
- v.addElement(IPublisherProcessor.PROP_TYPE + "=" +
- mConfig.getString(IPublisherProcessor.PROP_TYPE, ""));
- v.addElement(IPublisherProcessor.PROP_PREDICATE + "=" +
- mConfig.getString(IPublisherProcessor.PROP_PREDICATE,
- ""));
- v.addElement(IPublisherProcessor.PROP_ENABLE + "=" +
- mConfig.getString(IPublisherProcessor.PROP_ENABLE,
- ""));
- v.addElement(IPublisherProcessor.PROP_MAPPER + "=" +
- mConfig.getString(IPublisherProcessor.PROP_MAPPER,
- ""));
- v.addElement(IPublisherProcessor.PROP_PUBLISHER + "=" +
- mConfig.getString(IPublisherProcessor.PROP_PUBLISHER,
- ""));
+ v.addElement(IPublisherProcessor.PROP_TYPE + "=" +
+ mConfig.getString(IPublisherProcessor.PROP_TYPE, ""));
+ v.addElement(IPublisherProcessor.PROP_PREDICATE + "=" +
+ mConfig.getString(IPublisherProcessor.PROP_PREDICATE,
+ ""));
+ v.addElement(IPublisherProcessor.PROP_ENABLE + "=" +
+ mConfig.getString(IPublisherProcessor.PROP_ENABLE,
+ ""));
+ v.addElement(IPublisherProcessor.PROP_MAPPER + "=" +
+ mConfig.getString(IPublisherProcessor.PROP_MAPPER,
+ ""));
+ v.addElement(IPublisherProcessor.PROP_PUBLISHER + "=" +
+ mConfig.getString(IPublisherProcessor.PROP_PUBLISHER,
+ ""));
} catch (EBaseException e) {
}
return v;
@@ -222,8 +222,8 @@ public class LdapRule implements ILdapRule, IExtendedPluginInfo {
/**
* Sets a predicate expression for rule matching.
* <P>
- *
- * @param exp The predicate expression for the rule.
+ *
+ * @param exp The predicate expression for the rule.
*/
public void setPredicate(ILdapExpression exp) {
mFilterExp = exp;
@@ -232,7 +232,7 @@ public class LdapRule implements ILdapRule, IExtendedPluginInfo {
/**
* Returns the predicate expression for the rule.
* <P>
- *
+ *
* @return The predicate expression for the rule.
*/
public ILdapExpression getPredicate() {
@@ -242,7 +242,7 @@ public class LdapRule implements ILdapRule, IExtendedPluginInfo {
public String getMapper() {
try {
String map =
- mConfig.getString(IPublisherProcessor.PROP_MAPPER, "");
+ mConfig.getString(IPublisherProcessor.PROP_MAPPER, "");
if (map != null)
map = map.trim();
@@ -275,10 +275,10 @@ public class LdapRule implements ILdapRule, IExtendedPluginInfo {
public boolean enabled() {
try {
- boolean enable =
- mConfig.getBoolean(IPublisherProcessor.PROP_ENABLE, false);
+ boolean enable =
+ mConfig.getBoolean(IPublisherProcessor.PROP_ENABLE, false);
- //System.out.println(enable);
+ // System.out.println(enable);
return enable;
} catch (EBaseException e) {
}
diff --git a/pki/base/common/src/com/netscape/cmscore/ldap/LdapSimpleExpression.java b/pki/base/common/src/com/netscape/cmscore/ldap/LdapSimpleExpression.java
index a2a7e558..1c9b074d 100644
--- a/pki/base/common/src/com/netscape/cmscore/ldap/LdapSimpleExpression.java
+++ b/pki/base/common/src/com/netscape/cmscore/ldap/LdapSimpleExpression.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.ldap;
-
import java.util.Enumeration;
import java.util.Vector;
@@ -28,13 +27,12 @@ import com.netscape.certsrv.publish.ILdapExpression;
import com.netscape.certsrv.request.IRequest;
import com.netscape.cmscore.util.AssertionException;
-
/**
- * This class represents an expression of the form var = val,
- * var != val, var < val, var > val, var <= val, var >= val.
- *
+ * This class represents an expression of the form var = val, var != val, var <
+ * val, var > val, var <= val, var >= val.
+ *
* Expressions are used as predicates for publishing rule selection.
- *
+ *
* @author mzhao
* @version $Revision$, $Date$
*/
@@ -47,11 +45,11 @@ public class LdapSimpleExpression implements ILdapExpression {
private boolean hasWildCard;
public static final char WILDCARD_CHAR = '*';
- // This is just for indicating a null expression.
+ // This is just for indicating a null expression.
public static LdapSimpleExpression NULL_EXPRESSION = new LdapSimpleExpression("null", OP_EQUAL, "null");
public static ILdapExpression parse(String input)
- throws ELdapException {
+ throws ELdapException {
// Get the index of operator
// Debug.trace("LdapSimpleExpression::input: " + input);
String var = null;
@@ -73,7 +71,7 @@ public class LdapSimpleExpression implements ILdapExpression {
comps = parseForLT(input);
if (comps == null)
throw new ELdapException(CMS.getUserMessage("CMS_LDAP_BAD_LDAP_EXPRESSION", input));
-
+
String pfx = null;
String rawVar = comps.getAttr();
int dotIdx = rawVar.indexOf('.');
@@ -119,23 +117,23 @@ public class LdapSimpleExpression implements ILdapExpression {
}
public boolean evaluate(SessionContext sc)
- throws ELdapException {
+ throws ELdapException {
Object givenVal;
try {
// Try exact case first.
givenVal = (String) sc.get(mVar);
- }catch (Exception e) {
+ } catch (Exception e) {
givenVal = (String) null;
}
// It is kind of a problem here if all letters are in
- // lowercase or in upperCase - for example in the case
+ // lowercase or in upperCase - for example in the case
// of directory attributes.
if (givenVal == null) {
try {
givenVal = (String) sc.get(mVar.toLowerCase());
- }catch (Exception e) {
+ } catch (Exception e) {
givenVal = (String) null;
}
}
@@ -143,12 +141,13 @@ public class LdapSimpleExpression implements ILdapExpression {
if (givenVal == null) {
try {
givenVal = (String) sc.get(mVar.toUpperCase());
- }catch (Exception e) {
+ } catch (Exception e) {
givenVal = (String) null;
}
}
- // Debug.trace("mVar: " + mVar + ",Given Value: " + givenVal + ", Value to compare with: " + mVal);
+ // Debug.trace("mVar: " + mVar + ",Given Value: " + givenVal +
+ // ", Value to compare with: " + mVal);
boolean result = false;
result = matchValue(givenVal);
@@ -158,7 +157,7 @@ public class LdapSimpleExpression implements ILdapExpression {
}
public boolean evaluate(IRequest req)
- throws ELdapException {
+ throws ELdapException {
boolean result = false;
// mPfx and mVar are looked up case-indendently
if (mPfx != null) {
@@ -170,7 +169,7 @@ public class LdapSimpleExpression implements ILdapExpression {
}
private boolean matchVector(Vector value)
- throws ELdapException {
+ throws ELdapException {
boolean result = false;
Enumeration e = (Enumeration) value.elements();
@@ -183,7 +182,7 @@ public class LdapSimpleExpression implements ILdapExpression {
}
private boolean matchStringArray(String[] value)
- throws ELdapException {
+ throws ELdapException {
boolean result = false;
for (int i = 0; i < value.length; i++) {
@@ -195,7 +194,7 @@ public class LdapSimpleExpression implements ILdapExpression {
}
private boolean matchValue(Object value)
- throws ELdapException {
+ throws ELdapException {
boolean result;
// There is nothing to compare with!
@@ -219,7 +218,7 @@ public class LdapSimpleExpression implements ILdapExpression {
}
private boolean matchStringValue(String givenVal)
- throws ELdapException {
+ throws ELdapException {
boolean result;
switch (mOp) {
@@ -260,7 +259,7 @@ public class LdapSimpleExpression implements ILdapExpression {
}
private boolean matchIntegerValue(Integer intVal)
- throws ELdapException {
+ throws ELdapException {
boolean result;
int storedVal;
int givenVal = intVal.intValue();
@@ -303,12 +302,11 @@ public class LdapSimpleExpression implements ILdapExpression {
}
private boolean matchBooleanValue(Boolean givenVal)
- throws ELdapException {
+ throws ELdapException {
boolean result;
Boolean storedVal;
- if (!(mVal.equalsIgnoreCase("true") ||
- mVal.equalsIgnoreCase("false")))
+ if (!(mVal.equalsIgnoreCase("true") || mVal.equalsIgnoreCase("false")))
throw new ELdapException(CMS.getUserMessage("CMS_LDAP_INVALID_ATTR_VALUE",
mVal));
storedVal = new Boolean(mVal);
@@ -359,7 +357,7 @@ public class LdapSimpleExpression implements ILdapExpression {
op = ILdapExpression.LE_STR;
break;
}
- if (mPfx != null && mPfx.length() > 0)
+ if (mPfx != null && mPfx.length() > 0)
return mPfx + "." + mVar + " " + op + " " + mVal;
else
return mVar + " " + op + " " + mVal;
@@ -450,7 +448,6 @@ public class LdapSimpleExpression implements ILdapExpression {
}
}
-
class ExpressionComps {
String attr;
int op;
@@ -474,4 +471,3 @@ class ExpressionComps {
return val;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/ldap/PublishObject.java b/pki/base/common/src/com/netscape/cmscore/ldap/PublishObject.java
index fc2ace23..940330d6 100644
--- a/pki/base/common/src/com/netscape/cmscore/ldap/PublishObject.java
+++ b/pki/base/common/src/com/netscape/cmscore/ldap/PublishObject.java
@@ -17,11 +17,9 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.ldap;
-
import netscape.security.x509.X509CRLImpl;
import netscape.security.x509.X509CertImpl;
-
/**
* The object to publish or unpublish: a certificate or a CRL
*/
@@ -32,7 +30,7 @@ public class PublishObject {
private String mObjectType = null;
private X509CertImpl mCert = null;
private X509CertImpl[] mCerts = null;
- private X509CRLImpl mCRL = null;
+ private X509CRLImpl mCRL = null;
private int mIndex = 0;
public PublishObject() {
diff --git a/pki/base/common/src/com/netscape/cmscore/ldap/PublisherProcessor.java b/pki/base/common/src/com/netscape/cmscore/ldap/PublisherProcessor.java
index 57e39aef..68519be2 100644
--- a/pki/base/common/src/com/netscape/cmscore/ldap/PublisherProcessor.java
+++ b/pki/base/common/src/com/netscape/cmscore/ldap/PublisherProcessor.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.ldap;
-
import java.math.BigInteger;
import java.security.cert.X509CRL;
import java.security.cert.X509Certificate;
@@ -61,9 +60,8 @@ import com.netscape.certsrv.request.IRequestNotifier;
import com.netscape.cmscore.dbs.CertRecord;
import com.netscape.cmscore.util.Debug;
-
public class PublisherProcessor implements
- IPublisherProcessor, IXcertPublisherProcessor {
+ IPublisherProcessor, IXcertPublisherProcessor {
public Hashtable<String, PublisherPlugin> mPublisherPlugins = new Hashtable<String, PublisherPlugin>();
public Hashtable<String, PublisherProxy> mPublisherInsts = new Hashtable<String, PublisherProxy>();
@@ -73,7 +71,7 @@ public class PublisherProcessor implements
public Hashtable<String, ILdapRule> mRuleInsts = new Hashtable<String, ILdapRule>();
/**
- protected PublishRuleSet mRuleSet = null;
+ * protected PublishRuleSet mRuleSet = null;
**/
protected LdapConnModule mLdapConnModule = null;
@@ -94,7 +92,7 @@ public class PublisherProcessor implements
public String getId() {
return mId;
}
-
+
public void setId(String id) {
mId = id;
}
@@ -104,7 +102,7 @@ public class PublisherProcessor implements
}
public void init(ISubsystem authority, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mConfig = config;
mAuthority = (ICertAuthority) authority;
@@ -124,20 +122,20 @@ public class PublisherProcessor implements
if (Debug.ON)
Debug.trace("loaded publisher plugins");
- // load publisher instances
+ // load publisher instances
c = publisherConfig.getSubStore(PROP_INSTANCE);
Enumeration<String> instances = c.getSubStoreNames();
while (instances.hasMoreElements()) {
String insName = (String) instances.nextElement();
- String implName = c.getString(insName + "." +
+ String implName = c.getString(insName + "." +
PROP_PLUGIN);
PublisherPlugin plugin =
- (PublisherPlugin) mPublisherPlugins.get(implName);
+ (PublisherPlugin) mPublisherPlugins.get(implName);
- if (plugin == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAP_PLUGIN_NOT_FIND", implName));
+ if (plugin == null) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_LDAP_PLUGIN_NOT_FIND", implName));
throw new ELdapException(implName);
}
String className = plugin.getClassPath();
@@ -149,8 +147,8 @@ public class PublisherProcessor implements
try {
publisherInst = (ILdapPublisher)
Class.forName(className).newInstance();
- IConfigStore pConfig =
- c.getSubStore(insName);
+ IConfigStore pConfig =
+ c.getSubStore(insName);
publisherInst.init(pConfig);
isEnable = true;
@@ -188,8 +186,8 @@ public class PublisherProcessor implements
}
// add publisher instance to list.
- mPublisherInsts.put(insName, new
- PublisherProxy(isEnable, publisherInst));
+ mPublisherInsts.put(insName, new
+ PublisherProxy(isEnable, publisherInst));
log(ILogger.LL_INFO, "publisher instance " + insName + " added");
if (Debug.ON)
Debug.trace("loaded publisher instance " + insName + " impl " + implName);
@@ -210,19 +208,19 @@ public class PublisherProcessor implements
if (Debug.ON)
Debug.trace("loaded mapper plugins");
- // load mapper instances
+ // load mapper instances
c = mapperConfig.getSubStore(PROP_INSTANCE);
instances = c.getSubStoreNames();
while (instances.hasMoreElements()) {
String insName = (String) instances.nextElement();
- String implName = c.getString(insName + "." +
+ String implName = c.getString(insName + "." +
PROP_PLUGIN);
MapperPlugin plugin =
- (MapperPlugin) mMapperPlugins.get(implName);
+ (MapperPlugin) mMapperPlugins.get(implName);
- if (plugin == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAP_MAPPER_NOT_FIND", implName));
+ if (plugin == null) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_LDAP_MAPPER_NOT_FIND", implName));
throw new ELdapException(implName);
}
String className = plugin.getClassPath();
@@ -230,15 +228,15 @@ public class PublisherProcessor implements
if (Debug.ON)
Debug.trace("loaded mapper className=" + className);
- // Instantiate and init the mapper
+ // Instantiate and init the mapper
boolean isEnable = false;
ILdapMapper mapperInst = null;
try {
mapperInst = (ILdapMapper)
Class.forName(className).newInstance();
- IConfigStore mConfig =
- c.getSubStore(insName);
+ IConfigStore mConfig =
+ c.getSubStore(insName);
mapperInst.init(mConfig);
isEnable = true;
@@ -294,19 +292,19 @@ public class PublisherProcessor implements
if (Debug.ON)
Debug.trace("loaded rule plugins");
- // load rule instances
+ // load rule instances
c = ruleConfig.getSubStore(PROP_INSTANCE);
instances = c.getSubStoreNames();
while (instances.hasMoreElements()) {
String insName = (String) instances.nextElement();
- String implName = c.getString(insName + "." +
+ String implName = c.getString(insName + "." +
PROP_PLUGIN);
RulePlugin plugin =
- (RulePlugin) mRulePlugins.get(implName);
+ (RulePlugin) mRulePlugins.get(implName);
- if (plugin == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAP_RULE_NOT_FIND", implName));
+ if (plugin == null) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_LDAP_RULE_NOT_FIND", implName));
throw new ELdapException(implName);
}
String className = plugin.getClassPath();
@@ -314,7 +312,7 @@ public class PublisherProcessor implements
if (Debug.ON)
Debug.trace("loaded rule className=" + className);
- // Instantiate and init the rule
+ // Instantiate and init the rule
IConfigStore mConfig = null;
try {
@@ -330,8 +328,8 @@ public class PublisherProcessor implements
if (Debug.ON)
Debug.trace("ADDING RULE " + insName + " " + ruleInst);
mRuleInsts.put(insName, ruleInst);
- log(ILogger.LL_INFO, "rule instance " +
- insName + " added");
+ log(ILogger.LL_INFO, "rule instance " +
+ insName + " added");
} catch (ClassNotFoundException e) {
String errMsg = "PublisherProcessor:: init()-" + e.toString();
@@ -351,8 +349,8 @@ public class PublisherProcessor implements
if (mConfig == null) {
throw new ELdapException(CMS.getUserMessage("CMS_LDAP_FAIL_LOAD_CLASS", className));
}
- mConfig.putString(ILdapRule.PROP_ENABLE,
- "false");
+ mConfig.putString(ILdapRule.PROP_ENABLE,
+ "false");
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_LDAP_SKIP_RULE", insName, e.toString()));
// Let the server continue if it is a
// mis-configuration. But the instance
@@ -372,40 +370,40 @@ public class PublisherProcessor implements
/**
* Retrieves LDAP connection module.
* <P>
- *
+ *
* @return LDAP connection instance
*/
public ILdapConnModule getLdapConnModule() {
return mLdapConnModule;
}
-
+
public void setLdapConnModule(ILdapConnModule m) {
- mLdapConnModule = (LdapConnModule)m;
+ mLdapConnModule = (LdapConnModule) m;
}
-
+
/**
* init ldap connection
*/
private void initLdapConn(IConfigStore ldapConfig)
- throws EBaseException {
+ throws EBaseException {
IConfigStore c = ldapConfig;
try {
- //c = authConfig.getSubStore(PROP_LDAP_PUBLISH_SUBSTORE);
+ // c = authConfig.getSubStore(PROP_LDAP_PUBLISH_SUBSTORE);
if (c != null && c.size() > 0) {
mLdapConnModule = new LdapConnModule();
mLdapConnModule.init(this, c);
CMS.debug("LdapPublishing connection inited");
} else {
- log(ILogger.LL_FAILURE,
- "No Ldap Module configuration found");
+ log(ILogger.LL_FAILURE,
+ "No Ldap Module configuration found");
throw new ELdapException(
- CMS.getUserMessage("CMS_LDAP_NO_LDAP_PUBLISH_CONFIG_FOUND"));
+ CMS.getUserMessage("CMS_LDAP_NO_LDAP_PUBLISH_CONFIG_FOUND"));
}
} catch (ELdapException e) {
- log(ILogger.LL_FAILURE,
- "Ldap Publishing Module failed with " + e);
+ log(ILogger.LL_FAILURE,
+ "Ldap Publishing Module failed with " + e);
throw new ELdapException(CMS.getUserMessage("CMS_LDAP_INIT_LDAP_PUBLISH_MODULE_FAILED", e.toString()));
}
}
@@ -434,9 +432,9 @@ public class PublisherProcessor implements
CMS.debug("PublisherProcessor: startup: Publishing Queue Enabled: " + isPublishingQueueEnabled +
" Priority Level: " + publishingQueuePriorityLevel +
" Maximum Number of Threads: " + maxNumberOfPublishingThreads +
- " Page Size: "+ publishingQueuePageSize);
- IRequestNotifier reqNotifier = ((ICertificateAuthority)mAuthority).getRequestNotifier();
- reqNotifier.setPublishingQueue (isPublishingQueueEnabled,
+ " Page Size: " + publishingQueuePageSize);
+ IRequestNotifier reqNotifier = ((ICertificateAuthority) mAuthority).getRequestNotifier();
+ reqNotifier.setPublishingQueue(isPublishingQueueEnabled,
publishingQueuePriorityLevel,
maxNumberOfPublishingThreads,
publishingQueuePageSize,
@@ -452,11 +450,11 @@ public class PublisherProcessor implements
mLdapConnModule.getLdapConnFactory().reset();
}
if (mLdapRequestListener != null) {
- //mLdapRequestListener.shutdown();
+ // mLdapRequestListener.shutdown();
mAuthority.removeRequestListener(mLdapRequestListener);
}
- } catch (Exception e) {
- // ignore
+ } catch (Exception e) {
+ // ignore
}
}
@@ -484,12 +482,12 @@ public class PublisherProcessor implements
return mPublisherInsts;
}
- //certType can be client,server,ca,crl,smime
- //XXXshould make it static to make it faster
+ // certType can be client,server,ca,crl,smime
+ // XXXshould make it static to make it faster
public Enumeration<ILdapRule> getRules(String publishingType) {
Vector<ILdapRule> rules = new Vector<ILdapRule>();
Enumeration<String> e = mRuleInsts.keys();
-
+
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
@@ -502,7 +500,7 @@ public class PublisherProcessor implements
Debug.trace("rule name is " + name);
}
- //this is the only rule we support now
+ // this is the only rule we support now
LdapRule rule = (LdapRule) (mRuleInsts.get(name));
if (rule.enabled() && rule.getType().equals(publishingType)) {
@@ -532,7 +530,7 @@ public class PublisherProcessor implements
Vector<ILdapRule> rules = new Vector<ILdapRule>();
Enumeration<String> e = mRuleInsts.keys();
-
+
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
@@ -545,7 +543,7 @@ public class PublisherProcessor implements
Debug.trace("rule name is " + name);
}
- //this is the only rule we support now
+ // this is the only rule we support now
LdapRule rule = (LdapRule) (mRuleInsts.get(name));
if (rule.enabled() && rule.getType().equals(publishingType)) {
@@ -562,17 +560,14 @@ public class PublisherProcessor implements
rules.addElement(rule);
if (Debug.ON)
Debug.trace("added rule " + name + " for " + publishingType +
- " request: " + req.getRequestId());
+ " request: " + req.getRequestId());
}
}
return rules.elements();
}
/**
- public PublishRuleSet getPublishRuleSet()
- {
- return mRuleSet;
- }
+ * public PublishRuleSet getPublishRuleSet() { return mRuleSet; }
**/
public Vector<String> getMapperDefaultParams(String implName) throws
@@ -582,13 +577,13 @@ public class PublisherProcessor implements
if (plugin == null) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAP_MAPPER_NOT_FIND", implName));
+ CMS.getLogMessage("CMSCORE_LDAP_MAPPER_NOT_FIND", implName));
throw new ELdapException(implName);
}
-
+
// XXX can find an instance of this plugin in existing
// mapper instances to avoid instantiation just for this.
-
+
// a temporary instance
ILdapMapper mapperInst = null;
String className = plugin.getClassPath();
@@ -632,17 +627,17 @@ public class PublisherProcessor implements
ELdapException {
// is this a registered implname?
PublisherPlugin plugin = (PublisherPlugin)
- mPublisherPlugins.get(implName);
+ mPublisherPlugins.get(implName);
if (plugin == null) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAP_PLUGIN_NOT_FIND", implName));
+ CMS.getLogMessage("CMSCORE_LDAP_PLUGIN_NOT_FIND", implName));
throw new ELdapException(implName);
}
-
+
// XXX can find an instance of this plugin in existing
// publisher instantces to avoid instantiation just for this.
-
+
// a temporary instance
ILdapPublisher publisherInst = null;
String className = plugin.getClassPath();
@@ -667,7 +662,7 @@ public class PublisherProcessor implements
public boolean isMapperInstanceEnable(String insName) {
MapperProxy proxy = (MapperProxy)
- mMapperInsts.get(insName);
+ mMapperInsts.get(insName);
if (proxy == null) {
return false;
@@ -696,7 +691,7 @@ public class PublisherProcessor implements
public boolean isPublisherInstanceEnable(String insName) {
PublisherProxy proxy = (PublisherProxy)
- mPublisherInsts.get(insName);
+ mPublisherInsts.get(insName);
if (proxy == null) {
return false;
@@ -706,20 +701,20 @@ public class PublisherProcessor implements
public ILdapPublisher getActivePublisherInstance(String insName) {
PublisherProxy proxy = (PublisherProxy)
- mPublisherInsts.get(insName);
+ mPublisherInsts.get(insName);
if (proxy == null) {
return null;
}
if (proxy.isEnable())
return proxy.getPublisher();
- else
+ else
return null;
}
public ILdapPublisher getPublisherInstance(String insName) {
PublisherProxy proxy = (PublisherProxy)
- mPublisherInsts.get(insName);
+ mPublisherInsts.get(insName);
if (proxy == null) {
return null;
@@ -746,13 +741,13 @@ public class PublisherProcessor implements
if (plugin == null) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAP_RULE_NOT_FIND", implName));
+ CMS.getLogMessage("CMSCORE_LDAP_RULE_NOT_FIND", implName));
throw new ELdapException(implName);
}
-
+
// XXX can find an instance of this plugin in existing
// rule instantces to avoid instantiation just for this.
-
+
// a temporary instance
ILdapRule ruleInst = null;
String className = plugin.getClassPath();
@@ -760,7 +755,7 @@ public class PublisherProcessor implements
try {
ruleInst = (ILdapRule)
Class.forName(className).newInstance();
-
+
Vector<String> v = ruleInst.getDefaultParams();
return v;
@@ -783,13 +778,13 @@ public class PublisherProcessor implements
if (plugin == null) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAP_RULE_NOT_FIND", implName));
+ CMS.getLogMessage("CMSCORE_LDAP_RULE_NOT_FIND", implName));
throw new ELdapException(implName);
}
-
+
// XXX can find an instance of this plugin in existing
// rule instantces to avoid instantiation just for this.
-
+
// a temporary instance
ILdapRule ruleInst = null;
String className = plugin.getClassPath();
@@ -814,11 +809,11 @@ public class PublisherProcessor implements
}
/**
- * set published flag - true when published, false when unpublished.
- * not exist means not published.
+ * set published flag - true when published, false when unpublished. not
+ * exist means not published.
*/
public void setPublishedFlag(BigInteger serialNo, boolean published) {
- if (!(mAuthority instanceof ICertificateAuthority))
+ if (!(mAuthority instanceof ICertificateAuthority))
return;
ICertificateAuthority ca = (ICertificateAuthority) mAuthority;
@@ -831,19 +826,19 @@ public class PublisherProcessor implements
metaInfo = new MetaInfo();
}
metaInfo.set(
- CertRecord.META_LDAPPUBLISH, String.valueOf(published));
+ CertRecord.META_LDAPPUBLISH, String.valueOf(published));
ModificationSet modSet = new ModificationSet();
- modSet.add(ICertRecord.ATTR_META_INFO,
- Modification.MOD_REPLACE, metaInfo);
+ modSet.add(ICertRecord.ATTR_META_INFO,
+ Modification.MOD_REPLACE, metaInfo);
certdb.modifyCertificateRecord(serialNo, modSet);
} catch (EBaseException e) {
// not fatal. just log warning.
- log(ILogger.LL_WARN,
- "Cannot mark cert 0x" + serialNo.toString(16) + " published as " + published +
- " in the ldap directory. Cert Record not found. Error: " +
- e.toString() +
- " Don't be alarmed if it's a subordinate ca or clone's ca siging cert. Otherwise your internal db may be corrupted.");
+ log(ILogger.LL_WARN,
+ "Cannot mark cert 0x" + serialNo.toString(16) + " published as " + published +
+ " in the ldap directory. Cert Record not found. Error: " +
+ e.toString() +
+ " Don't be alarmed if it's a subordinate ca or clone's ca siging cert. Otherwise your internal db may be corrupted.");
}
}
@@ -851,7 +846,7 @@ public class PublisherProcessor implements
* Publish ca cert, UpdateDir.java, jobs, request listeners
*/
public void publishCACert(X509Certificate cert)
- throws ELdapException {
+ throws ELdapException {
boolean error = false;
String errorRule = "";
@@ -860,7 +855,7 @@ public class PublisherProcessor implements
CMS.debug("PublishProcessor::publishCACert");
- // get mapper and publisher for cert type.
+ // get mapper and publisher for cert type.
Enumeration<ILdapRule> rules = getRules(PROP_LOCAL_CA);
if (rules == null || !rules.hasMoreElements()) {
@@ -869,23 +864,27 @@ public class PublisherProcessor implements
return;
} else {
Debug.trace(CMS.getLogMessage("CMSCORE_LDAP_NO_RULE_FOUND", PROP_LOCAL_CA));
- //log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_LDAP_NO_RULE_FOUND", PROP_LOCAL_CA));
- //throw new ELdapException(CMS.getUserMessage("CMS_LDAP_NO_RULE_MATCHED", PROP_LOCAL_CA));
+ // log(ILogger.LL_FAILURE,
+ // CMS.getLogMessage("CMSCORE_LDAP_NO_RULE_FOUND",
+ // PROP_LOCAL_CA));
+ // throw new
+ // ELdapException(CMS.getUserMessage("CMS_LDAP_NO_RULE_MATCHED",
+ // PROP_LOCAL_CA));
return;
}
}
while (rules.hasMoreElements()) {
LdapRule rule = (LdapRule) rules.nextElement();
- if( rule == null ) {
- CMS.debug( "PublisherProcessor::publishCACert() - "
- + "rule is null!" );
- throw new ELdapException( "rule is null" );
+ if (rule == null) {
+ CMS.debug("PublisherProcessor::publishCACert() - "
+ + "rule is null!");
+ throw new ELdapException("rule is null");
}
log(ILogger.LL_INFO, "publish certificate type=" + PROP_LOCAL_CA +
- " rule=" + rule.getInstanceName() + " publisher=" +
- rule.getPublisher());
+ " rule=" + rule.getInstanceName() + " publisher=" +
+ rule.getPublisher());
try {
ILdapMapper mapper = null;
@@ -893,16 +892,19 @@ public class PublisherProcessor implements
String mapperName = rule.getMapper();
if (mapperName != null &&
- !mapperName.trim().equals("")) {
+ !mapperName.trim().equals("")) {
mapper = getActiveMapperInstance(mapperName);
}
- publishNow(mapper, getActivePublisherInstance(rule.getPublisher()), null/* NO REQUEsT */, cert);
- log(ILogger.LL_INFO, "published certificate using rule=" +
- rule.getInstanceName());
+ publishNow(mapper, getActivePublisherInstance(rule.getPublisher()), null/*
+ * NO
+ * REQUEsT
+ */, cert);
+ log(ILogger.LL_INFO, "published certificate using rule=" +
+ rule.getInstanceName());
} catch (Exception e) {
// continue publishing even publisher has errors
- //log(ILogger.LL_WARN, e.toString());
+ // log(ILogger.LL_WARN, e.toString());
CMS.debug("PublisherProcessor::publishCACert returned error: " + e.toString());
error = true;
errorRule = errorRule + " " + rule.getInstanceName() +
@@ -913,24 +915,22 @@ public class PublisherProcessor implements
if (!error) {
setPublishedFlag(cert.getSerialNumber(), true);
} else {
- throw new
- ELdapException(CMS.getUserMessage("CMS_LDAP_PUBLISH_FAILED", errorRule));
+ throw new ELdapException(CMS.getUserMessage("CMS_LDAP_PUBLISH_FAILED", errorRule));
}
}
/**
- * This function is never called. CMS does not unpublish
- * CA certificate.
+ * This function is never called. CMS does not unpublish CA certificate.
*/
public void unpublishCACert(X509Certificate cert)
- throws ELdapException {
+ throws ELdapException {
boolean error = false;
String errorRule = "";
if (!enabled())
return;
- // get mapper and publisher for cert type.
+ // get mapper and publisher for cert type.
Enumeration<ILdapRule> rules = getRules(PROP_LOCAL_CA);
if (rules == null || !rules.hasMoreElements()) {
@@ -946,32 +946,35 @@ public class PublisherProcessor implements
while (rules.hasMoreElements()) {
LdapRule rule = (LdapRule) rules.nextElement();
- if( rule == null ) {
- CMS.debug( "PublisherProcessor::unpublishCACert() - "
- + "rule is null!" );
- throw new ELdapException( "rule is null" );
+ if (rule == null) {
+ CMS.debug("PublisherProcessor::unpublishCACert() - "
+ + "rule is null!");
+ throw new ELdapException("rule is null");
}
try {
log(ILogger.LL_INFO, "unpublish certificate type=" +
- PROP_LOCAL_CA + " rule=" + rule.getInstanceName() +
- " publisher=" + rule.getPublisher());
+ PROP_LOCAL_CA + " rule=" + rule.getInstanceName() +
+ " publisher=" + rule.getPublisher());
ILdapMapper mapper = null;
String mapperName = rule.getMapper();
if (mapperName != null &&
- !mapperName.trim().equals("")) {
+ !mapperName.trim().equals("")) {
mapper = getActiveMapperInstance(mapperName);
}
- unpublishNow(mapper, getActivePublisherInstance(rule.getPublisher()), null/* NO REQUEST */, cert);
- log(ILogger.LL_INFO, "unpublished certificate using rule=" +
- rule.getInstanceName());
+ unpublishNow(mapper, getActivePublisherInstance(rule.getPublisher()), null/*
+ * NO
+ * REQUEST
+ */, cert);
+ log(ILogger.LL_INFO, "unpublished certificate using rule=" +
+ rule.getInstanceName());
} catch (Exception e) {
// continue publishing even publisher has errors
- //log(ILogger.LL_WARN, e.toString());
+ // log(ILogger.LL_WARN, e.toString());
error = true;
errorRule = errorRule + " " + rule.getInstanceName();
}
@@ -989,15 +992,15 @@ public class PublisherProcessor implements
* Publish crossCertificatePair
*/
public void publishXCertPair(byte[] pair)
- throws ELdapException {
+ throws ELdapException {
boolean error = false;
String errorRule = "";
if (!enabled())
return;
- CMS.debug("PublisherProcessor: in publishXCertPair()");
+ CMS.debug("PublisherProcessor: in publishXCertPair()");
- // get mapper and publisher for cert type.
+ // get mapper and publisher for cert type.
Enumeration<ILdapRule> rules = getRules(PROP_XCERT);
if (rules == null || !rules.hasMoreElements()) {
@@ -1012,31 +1015,34 @@ public class PublisherProcessor implements
while (rules.hasMoreElements()) {
LdapRule rule = (LdapRule) rules.nextElement();
- if( rule == null ) {
- CMS.debug( "PublisherProcessor::publishXCertPair() - "
- + "rule is null!" );
- throw new ELdapException( "rule is null" );
+ if (rule == null) {
+ CMS.debug("PublisherProcessor::publishXCertPair() - "
+ + "rule is null!");
+ throw new ELdapException("rule is null");
}
log(ILogger.LL_INFO, "publish certificate type=" + PROP_XCERT +
- " rule=" + rule.getInstanceName() + " publisher=" +
- rule.getPublisher());
+ " rule=" + rule.getInstanceName() + " publisher=" +
+ rule.getPublisher());
try {
ILdapMapper mapper = null;
String mapperName = rule.getMapper();
if (mapperName != null &&
- !mapperName.trim().equals("")) {
+ !mapperName.trim().equals("")) {
mapper = getActiveMapperInstance(mapperName);
}
- publishNow(mapper, getActivePublisherInstance(rule.getPublisher()), null/* NO REQUEsT */, pair);
- log(ILogger.LL_INFO, "published Xcertificates using rule=" +
- rule.getInstanceName());
+ publishNow(mapper, getActivePublisherInstance(rule.getPublisher()), null/*
+ * NO
+ * REQUEsT
+ */, pair);
+ log(ILogger.LL_INFO, "published Xcertificates using rule=" +
+ rule.getInstanceName());
} catch (Exception e) {
// continue publishing even publisher has errors
- //log(ILogger.LL_WARN, e.toString());
+ // log(ILogger.LL_WARN, e.toString());
error = true;
errorRule = errorRule + " " + rule.getInstanceName() +
" error:" + e.toString();
@@ -1047,11 +1053,11 @@ public class PublisherProcessor implements
}
/**
- * Publishs regular user certificate based on the criteria
- * set in the request.
+ * Publishs regular user certificate based on the criteria set in the
+ * request.
*/
public void publishCert(X509Certificate cert, IRequest req)
- throws ELdapException {
+ throws ELdapException {
boolean error = false;
String errorRule = "";
@@ -1059,10 +1065,10 @@ public class PublisherProcessor implements
if (!enabled())
return;
- // get mapper and publisher for cert type.
+ // get mapper and publisher for cert type.
Enumeration<ILdapRule> rules = getRules("certs", req);
- // Bugscape #52306 - Remove superfluous log messages on failure
+ // Bugscape #52306 - Remove superfluous log messages on failure
if (rules == null || !rules.hasMoreElements()) {
CMS.debug("Publishing: can't find publishing rule,exiting routine.");
@@ -1074,10 +1080,10 @@ public class PublisherProcessor implements
LdapRule rule = (LdapRule) rules.nextElement();
try {
- log(ILogger.LL_INFO,
- "publish certificate (with request) type=" +
- "certs" + " rule=" + rule.getInstanceName() +
- " publisher=" + rule.getPublisher());
+ log(ILogger.LL_INFO,
+ "publish certificate (with request) type=" +
+ "certs" + " rule=" + rule.getInstanceName() +
+ " publisher=" + rule.getPublisher());
ILdapPublisher p = getActivePublisherInstance(rule.getPublisher());
ILdapMapper m = null;
String mapperName = rule.getMapper();
@@ -1086,11 +1092,11 @@ public class PublisherProcessor implements
m = getActiveMapperInstance(mapperName);
}
publishNow(m, p, req, cert);
- log(ILogger.LL_INFO, "published certificate using rule=" +
- rule.getInstanceName());
+ log(ILogger.LL_INFO, "published certificate using rule=" +
+ rule.getInstanceName());
} catch (Exception e) {
// continue publishing even publisher has errors
- //log(ILogger.LL_WARN, e.toString());
+ // log(ILogger.LL_WARN, e.toString());
error = true;
errorRule = errorRule + " " + rule.getInstanceName();
}
@@ -1099,24 +1105,23 @@ public class PublisherProcessor implements
if (!error) {
setPublishedFlag(cert.getSerialNumber(), true);
} else {
- CMS.debug("PublishProcessor::publishCert : " + CMS.getUserMessage("CMS_LDAP_PUBLISH_FAILED",errorRule));
+ CMS.debug("PublishProcessor::publishCert : " + CMS.getUserMessage("CMS_LDAP_PUBLISH_FAILED", errorRule));
throw new ELdapException(CMS.getUserMessage("CMS_LDAP_PUBLISH_FAILED", errorRule));
}
}
/**
- * Unpublish user certificate. This is used by
- * UnpublishExpiredJob.
+ * Unpublish user certificate. This is used by UnpublishExpiredJob.
*/
public void unpublishCert(X509Certificate cert, IRequest req)
- throws ELdapException {
+ throws ELdapException {
boolean error = false;
String errorRule = "";
if (!enabled())
return;
- // get mapper and publisher for cert type.
+ // get mapper and publisher for cert type.
Enumeration<ILdapRule> rules = getRules("certs", req);
if (rules == null || !rules.hasMoreElements()) {
@@ -1128,34 +1133,34 @@ public class PublisherProcessor implements
while (rules.hasMoreElements()) {
LdapRule rule = (LdapRule) rules.nextElement();
- if( rule == null ) {
- CMS.debug( "PublisherProcessor::unpublishCert() - "
- + "rule is null!" );
- throw new ELdapException( "rule is null" );
+ if (rule == null) {
+ CMS.debug("PublisherProcessor::unpublishCert() - "
+ + "rule is null!");
+ throw new ELdapException("rule is null");
}
try {
- log(ILogger.LL_INFO,
- "unpublish certificate (with request) type=" +
- "certs" + " rule=" + rule.getInstanceName() +
- " publisher=" + rule.getPublisher());
+ log(ILogger.LL_INFO,
+ "unpublish certificate (with request) type=" +
+ "certs" + " rule=" + rule.getInstanceName() +
+ " publisher=" + rule.getPublisher());
ILdapMapper mapper = null;
String mapperName = rule.getMapper();
if (mapperName != null &&
- !mapperName.trim().equals("")) {
+ !mapperName.trim().equals("")) {
mapper = getActiveMapperInstance(mapperName);
}
unpublishNow(mapper, getActivePublisherInstance(rule.getPublisher()),
- req, cert);
- log(ILogger.LL_INFO, "unpublished certificate using rule=" +
- rule.getInstanceName());
+ req, cert);
+ log(ILogger.LL_INFO, "unpublished certificate using rule=" +
+ rule.getInstanceName());
} catch (Exception e) {
// continue publishing even publisher has errors
- //log(ILogger.LL_WARN, e.toString());
+ // log(ILogger.LL_WARN, e.toString());
error = true;
errorRule = errorRule + " " + rule.getInstanceName();
}
@@ -1170,16 +1175,15 @@ public class PublisherProcessor implements
}
/**
- * publishes a crl by mapping the issuer name in the crl to an entry
- * and publishing it there. entry must be a certificate authority.
- * Note that this is used by cmsgateway/cert/UpdateDir.java
+ * publishes a crl by mapping the issuer name in the crl to an entry and
+ * publishing it there. entry must be a certificate authority. Note that
+ * this is used by cmsgateway/cert/UpdateDir.java
*/
- public void publishCRL(X509CRLImpl crl, String crlIssuingPointId)
- throws ELdapException {
+ public void publishCRL(X509CRLImpl crl, String crlIssuingPointId)
+ throws ELdapException {
boolean error = false;
String errorRule = "";
-
if (!enabled())
return;
ILdapMapper mapper = null;
@@ -1207,53 +1211,53 @@ public class PublisherProcessor implements
String result = null;
LdapRule rule = (LdapRule) rules.nextElement();
- log(ILogger.LL_INFO, "publish crl rule=" +
- rule.getInstanceName() + " publisher=" +
- rule.getPublisher());
+ log(ILogger.LL_INFO, "publish crl rule=" +
+ rule.getInstanceName() + " publisher=" +
+ rule.getPublisher());
try {
String mapperName = rule.getMapper();
if (mapperName != null &&
- !mapperName.trim().equals("")) {
+ !mapperName.trim().equals("")) {
mapper = getActiveMapperInstance(mapperName);
}
if (mapper == null || mapper.getImplName().equals("NoMap")) {
dn = ((X500Name) crl.getIssuerDN()).toLdapDNString();
- }else {
-
+ } else {
+
result = ((ILdapMapper) mapper).map(conn, crl);
dn = result;
if (!mCreateOwnDNEntry) {
- if (dn == null) {
+ if (dn == null) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_LDAP_MAPPER_NOT_MAP", rule.getMapper()));
- throw new ELdapException(CMS.getUserMessage("CMS_LDAP_NO_MATCH",
- crl.getIssuerDN().toString()));
-
+ throw new ELdapException(CMS.getUserMessage("CMS_LDAP_NO_MATCH",
+ crl.getIssuerDN().toString()));
+
}
}
}
publisher = getActivePublisherInstance(rule.getPublisher());
if (publisher != null) {
- if(publisher instanceof com.netscape.cms.publish.publishers.FileBasedPublisher)
- ((com.netscape.cms.publish.publishers.FileBasedPublisher)publisher).setIssuingPointId(crlIssuingPointId);
+ if (publisher instanceof com.netscape.cms.publish.publishers.FileBasedPublisher)
+ ((com.netscape.cms.publish.publishers.FileBasedPublisher) publisher).setIssuingPointId(crlIssuingPointId);
publisher.publish(conn, dn, crl);
log(ILogger.LL_INFO, "published crl using rule=" + rule.getInstanceName());
}
// continue publishing even publisher has errors
- }catch (Exception e) {
- //e.printStackTrace();
+ } catch (Exception e) {
+ // e.printStackTrace();
CMS.debug(
- "Error publishing CRL to " + dn + ": " + e);
+ "Error publishing CRL to " + dn + ": " + e);
error = true;
errorRule = errorRule + " " + rule.getInstanceName();
CMS.debug("PublisherProcessor::publishCRL: error: " + e.toString());
}
}
- }catch (ELdapException e) {
- //e.printStackTrace();
+ } catch (ELdapException e) {
+ // e.printStackTrace();
CMS.debug(
- "Error publishing CRL to " + dn + ": " + e);
+ "Error publishing CRL to " + dn + ": " + e);
throw e;
} finally {
if (conn != null) {
@@ -1265,17 +1269,17 @@ public class PublisherProcessor implements
}
/**
- * publishes a crl by mapping the issuer name in the crl to an entry
- * and publishing it there. entry must be a certificate authority.
+ * publishes a crl by mapping the issuer name in the crl to an entry and
+ * publishing it there. entry must be a certificate authority.
*/
- public void publishCRL(String dn, X509CRL crl)
- throws ELdapException {
+ public void publishCRL(String dn, X509CRL crl)
+ throws ELdapException {
boolean error = false;
String errorRule = "";
if (!enabled())
return;
- // get mapper and publisher for cert type.
+ // get mapper and publisher for cert type.
Enumeration<ILdapRule> rules = getRules(PROP_LOCAL_CRL);
if (rules == null || !rules.hasMoreElements()) {
@@ -1295,25 +1299,25 @@ public class PublisherProcessor implements
LdapRule rule = (LdapRule) rules.nextElement();
log(ILogger.LL_INFO, "publish crl dn=" + dn + " rule=" +
- rule.getInstanceName() + " publisher=" +
- rule.getPublisher());
+ rule.getInstanceName() + " publisher=" +
+ rule.getPublisher());
try {
publisher = getActivePublisherInstance(rule.getPublisher());
if (publisher != null) {
publisher.publish(conn, dn, crl);
log(ILogger.LL_INFO, "published crl using rule=" + rule.getInstanceName());
}
- }catch (Exception e) {
+ } catch (Exception e) {
CMS.debug(
- "Error publishing CRL to " + dn + ": " + e.toString());
+ "Error publishing CRL to " + dn + ": " + e.toString());
error = true;
errorRule = errorRule + " " + rule.getInstanceName();
- CMS.debug("PublisherProcessor::publishCRL: error: " + e.toString());
- }
+ CMS.debug("PublisherProcessor::publishCRL: error: " + e.toString());
+ }
}
} catch (ELdapException e) {
CMS.debug(
- "Error publishing CRL to " + dn + ": " + e.toString());
+ "Error publishing CRL to " + dn + ": " + e.toString());
throw e;
} finally {
if (conn != null) {
@@ -1325,7 +1329,7 @@ public class PublisherProcessor implements
}
private void publishNow(ILdapMapper mapper, ILdapPublisher publisher,
- IRequest r, Object obj) throws ELdapException {
+ IRequest r, Object obj) throws ELdapException {
if (!enabled())
return;
CMS.debug("PublisherProcessor: in publishNow()");
@@ -1340,16 +1344,16 @@ public class PublisherProcessor implements
if (mLdapConnModule != null) {
try {
conn = mLdapConnModule.getConn();
- } catch(ELdapException e) {
+ } catch (ELdapException e) {
throw e;
- }
+ }
}
try {
if ((mapper instanceof com.netscape.cms.publish.mappers.LdapCertSubjMap) &&
- ((com.netscape.cms.publish.mappers.LdapCertSubjMap)mapper).useAllEntries()) {
- dirdn = ((com.netscape.cms.publish.mappers.LdapCertSubjMap)mapper).mapAll(conn, r, obj);
+ ((com.netscape.cms.publish.mappers.LdapCertSubjMap) mapper).useAllEntries()) {
+ dirdn = ((com.netscape.cms.publish.mappers.LdapCertSubjMap) mapper).mapAll(conn, r, obj);
} else {
- dirdn = mapper.map(conn, r, obj);
+ dirdn = mapper.map(conn, r, obj);
}
} catch (Throwable e1) {
CMS.debug("Error mapping: mapper=" + mapper + " error=" + e1.toString());
@@ -1361,26 +1365,26 @@ public class PublisherProcessor implements
try {
if (dirdn instanceof Vector) {
- @SuppressWarnings("unchecked")
- Vector<String> dirdnVector = (Vector<String>)dirdn;
+ @SuppressWarnings("unchecked")
+ Vector<String> dirdnVector = (Vector<String>) dirdn;
int n = dirdnVector.size();
for (int i = 0; i < n; i++) {
publisher.publish(conn, dirdnVector.elementAt(i), cert);
}
- } else if (dirdn instanceof String ||
+ } else if (dirdn instanceof String ||
publisher instanceof com.netscape.cms.publish.publishers.FileBasedPublisher) {
- publisher.publish(conn, (String)dirdn, cert);
+ publisher.publish(conn, (String) dirdn, cert);
}
} catch (Throwable e1) {
CMS.debug("PublisherProcessor::publishNow : publisher=" + publisher + " error=" + e1.toString());
throw e1;
}
- log(ILogger.LL_INFO, "published certificate serial number: 0x" +
- cert.getSerialNumber().toString(16));
+ log(ILogger.LL_INFO, "published certificate serial number: 0x" +
+ cert.getSerialNumber().toString(16));
} catch (ELdapException e) {
throw e;
} catch (Throwable e) {
- throw new ELdapException(CMS.getUserMessage("CMS_LDAP_NO_MATCH", e.toString()));
+ throw new ELdapException(CMS.getUserMessage("CMS_LDAP_NO_MATCH", e.toString()));
} finally {
if (conn != null) {
mLdapConnModule.returnConn(conn);
@@ -1388,16 +1392,16 @@ public class PublisherProcessor implements
}
}
- // for crosscerts
+ // for crosscerts
private void publishNow(ILdapMapper mapper, ILdapPublisher publisher,
- IRequest r, byte[] bytes) throws ELdapException {
+ IRequest r, byte[] bytes) throws ELdapException {
if (!enabled())
return;
- CMS.debug("PublisherProcessor: in publishNow() for xcerts");
+ CMS.debug("PublisherProcessor: in publishNow() for xcerts");
- // use ca cert publishing map and rule
+ // use ca cert publishing map and rule
ICertificateAuthority ca = (ICertificateAuthority) mAuthority;
- X509Certificate caCert = (X509Certificate) ca.getCACert();
+ X509Certificate caCert = (X509Certificate) ca.getCACert();
LDAPConnection conn = null;
@@ -1411,8 +1415,8 @@ public class PublisherProcessor implements
conn = mLdapConnModule.getConn();
}
try {
- dirdn = mapper.map(conn, r, (Object) caCert);
- CMS.debug("PublisherProcessor: dirdn="+dirdn);
+ dirdn = mapper.map(conn, r, (Object) caCert);
+ CMS.debug("PublisherProcessor: dirdn=" + dirdn);
} catch (Throwable e1) {
CMS.debug("Error mapping: mapper=" + mapper + " error=" + e1.toString());
@@ -1421,7 +1425,7 @@ public class PublisherProcessor implements
}
try {
- CMS.debug("PublisherProcessor: publisher impl name="+publisher.getImplName());
+ CMS.debug("PublisherProcessor: publisher impl name=" + publisher.getImplName());
publisher.publish(conn, dirdn, bytes);
} catch (Throwable e1) {
@@ -1432,7 +1436,7 @@ public class PublisherProcessor implements
} catch (ELdapException e) {
throw e;
} catch (Throwable e) {
- throw new ELdapException(CMS.getUserMessage("CMS_LDAP_NO_MATCH", e.toString()));
+ throw new ELdapException(CMS.getUserMessage("CMS_LDAP_NO_MATCH", e.toString()));
} finally {
if (conn != null) {
mLdapConnModule.returnConn(conn);
@@ -1441,7 +1445,7 @@ public class PublisherProcessor implements
}
private void unpublishNow(ILdapMapper mapper, ILdapPublisher publisher,
- IRequest r, Object obj) throws ELdapException {
+ IRequest r, Object obj) throws ELdapException {
if (!enabled())
return;
LDAPConnection conn = null;
@@ -1455,13 +1459,13 @@ public class PublisherProcessor implements
if (mLdapConnModule != null) {
conn = mLdapConnModule.getConn();
}
- dirdn = mapper.map(conn, r, obj);
+ dirdn = mapper.map(conn, r, obj);
}
X509Certificate cert = (X509Certificate) obj;
publisher.unpublish(conn, dirdn, cert);
- log(ILogger.LL_INFO, "unpublished certificate serial number: 0x" +
- cert.getSerialNumber().toString(16));
+ log(ILogger.LL_INFO, "unpublished certificate serial number: 0x" +
+ cert.getSerialNumber().toString(16));
} catch (ELdapException e) {
throw e;
} finally {
@@ -1498,8 +1502,8 @@ public class PublisherProcessor implements
}
public boolean isClone() {
- if ((mAuthority instanceof ICertificateAuthority) &&
- ((ICertificateAuthority) mAuthority).isClone())
+ if ((mAuthority instanceof ICertificateAuthority) &&
+ ((ICertificateAuthority) mAuthority).isClone())
return true;
else
return false;
@@ -1511,7 +1515,7 @@ public class PublisherProcessor implements
public void log(int level, String msg) {
if (mLogger == null)
return;
- mLogger.log(ILogger.EV_SYSTEM,
- ILogger.S_LDAP, level, "Publishing: " + msg);
+ mLogger.log(ILogger.EV_SYSTEM,
+ ILogger.S_LDAP, level, "Publishing: " + msg);
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/ldapconn/LdapAnonConnFactory.java b/pki/base/common/src/com/netscape/cmscore/ldapconn/LdapAnonConnFactory.java
index fa400341..a91e1aa5 100644
--- a/pki/base/common/src/com/netscape/cmscore/ldapconn/LdapAnonConnFactory.java
+++ b/pki/base/common/src/com/netscape/cmscore/ldapconn/LdapAnonConnFactory.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.ldapconn;
-
import netscape.ldap.LDAPConnection;
import netscape.ldap.LDAPException;
import netscape.ldap.LDAPSocketFactory;
@@ -30,11 +29,10 @@ import com.netscape.certsrv.ldap.ELdapServerDownException;
import com.netscape.certsrv.ldap.ILdapConnFactory;
import com.netscape.certsrv.logging.ILogger;
-
/**
- * Factory for getting LDAP Connections to a LDAP server
- * each connection is a seperate thread that can be bound to a different
- * authentication dn and password.
+ * Factory for getting LDAP Connections to a LDAP server each connection is a
+ * seperate thread that can be bound to a different authentication dn and
+ * password.
*/
public class LdapAnonConnFactory implements ILdapConnFactory {
protected int mMinConns = 5;
@@ -49,8 +47,8 @@ public class LdapAnonConnFactory implements ILdapConnFactory {
public static final String PROP_ERROR_IF_DOWN = "errorIfDown";
- private int mNumConns = 0; // number of available conns in array
- private int mTotal = 0; // total num conns
+ private int mNumConns = 0; // number of available conns in array
+ private int mTotal = 0; // total num conns
private AnonConnection mConns[] = null;
private boolean mInited = false;
@@ -59,8 +57,8 @@ public class LdapAnonConnFactory implements ILdapConnFactory {
private boolean mDefErrorIfDown = false;
/**
- * Constructor for initializing from the config store.
- * must be followed by init(IConfigStore)
+ * Constructor for initializing from the config store. must be followed by
+ * init(IConfigStore)
*/
public LdapAnonConnFactory() {
}
@@ -71,13 +69,15 @@ public class LdapAnonConnFactory implements ILdapConnFactory {
/**
* Constructor for LdapAnonConnFactory
+ *
* @param minConns minimum number of connections to have available
- * @param maxConns max number of connections to have available. This is
- * the maximum number of clones of this connection one wants to allow.
+ * @param maxConns max number of connections to have available. This is the
+ * maximum number of clones of this connection one wants to
+ * allow.
* @param serverInfo server connection info - host, port, etc.
*/
- public LdapAnonConnFactory(int minConns, int maxConns,
- LdapConnInfo connInfo) throws ELdapException {
+ public LdapAnonConnFactory(int minConns, int maxConns,
+ LdapConnInfo connInfo) throws ELdapException {
init(minConns, maxConns, connInfo);
}
@@ -107,8 +107,8 @@ public class LdapAnonConnFactory implements ILdapConnFactory {
try {
minConns = Integer.parseInt(minStr);
} catch (NumberFormatException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAPCONN_MIN_CONN"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_LDAPCONN_MIN_CONN"));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_NUMBER_FORMAT_1", PROP_MINCONNS));
}
}
@@ -118,30 +118,30 @@ public class LdapAnonConnFactory implements ILdapConnFactory {
try {
maxConns = Integer.parseInt(maxStr);
} catch (NumberFormatException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAPCONN_MAX_CONN"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_LDAPCONN_MAX_CONN"));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_NUMBER_FORMAT_1", PROP_MAXCONNS));
}
}
mErrorIfDown = config.getBoolean(PROP_ERROR_IF_DOWN, mDefErrorIfDown);
- init(minConns, maxConns,
- new LdapConnInfo(config.getSubStore(PROP_LDAPCONNINFO)));
+ init(minConns, maxConns,
+ new LdapConnInfo(config.getSubStore(PROP_LDAPCONNINFO)));
}
/**
* initialize routine from parameters.
*/
protected void init(int minConns, int maxConns, LdapConnInfo connInfo)
- throws ELdapException {
- if (mInited)
- return; // XXX should throw exception here ?
+ throws ELdapException {
+ if (mInited)
+ return; // XXX should throw exception here ?
- if (minConns <= 0 || maxConns <= 0 || minConns > maxConns)
+ if (minConns <= 0 || maxConns <= 0 || minConns > maxConns)
throw new ELdapException(
CMS.getUserMessage("CMS_LDAP_INVALID_NUMCONN_PARAMETERS"));
- if (connInfo == null)
+ if (connInfo == null)
throw new IllegalArgumentException("connInfo is Null!");
mMinConns = minConns;
@@ -150,10 +150,10 @@ public class LdapAnonConnFactory implements ILdapConnFactory {
mConns = new AnonConnection[mMaxConns];
- log(ILogger.LL_INFO,
- "Created: min " + minConns + " max " + maxConns +
- " host " + connInfo.getHost() + " port " + connInfo.getPort() +
- " secure " + connInfo.getSecure());
+ log(ILogger.LL_INFO,
+ "Created: min " + minConns + " max " + maxConns +
+ " host " + connInfo.getHost() + " port " + connInfo.getPort() +
+ " secure " + connInfo.getSecure());
// initalize minimum number of connection handles available.
makeMinimum(mErrorIfDown);
@@ -161,7 +161,7 @@ public class LdapAnonConnFactory implements ILdapConnFactory {
}
/**
- * make the mininum configured connections
+ * make the mininum configured connections
*/
protected void makeMinimum(boolean errorIfDown) throws ELdapException {
try {
@@ -169,115 +169,111 @@ public class LdapAnonConnFactory implements ILdapConnFactory {
int increment = Math.min(mMinConns - mNumConns, mMaxConns - mTotal);
CMS.debug(
- "increasing minimum number of connections by " + increment);
+ "increasing minimum number of connections by " + increment);
for (int i = increment - 1; i >= 0; i--) {
mConns[i] = new AnonConnection(mConnInfo);
}
mTotal += increment;
mNumConns += increment;
CMS.debug(
- "new total number of connections " + mTotal);
+ "new total number of connections " + mTotal);
CMS.debug(
- "new total available connections " + mNumConns);
+ "new total available connections " + mNumConns);
}
} catch (LDAPException e) {
// XXX errorCodeToString() used here so users won't see message.
- // though why are messages from exceptions being displayed to
+ // though why are messages from exceptions being displayed to
// users ?
if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE) {
- // need to intercept this because message from LDAP is
+ // need to intercept this because message from LDAP is
// "DSA is unavailable" which confuses with DSA PKI.
log(ILogger.LL_FAILURE,
- "Cannot connect to Ldap server. Error: " +
- "Ldap Server host " + mConnInfo.getHost() +
- " int " + mConnInfo.getPort() + " is unavailable.");
+ "Cannot connect to Ldap server. Error: " +
+ "Ldap Server host " + mConnInfo.getHost() +
+ " int " + mConnInfo.getPort() + " is unavailable.");
if (errorIfDown) {
throw new ELdapServerDownException(
CMS.getUserMessage("CMS_LDAP_SERVER_UNAVAILABLE",
- mConnInfo.getHost(), "" + mConnInfo.getPort()));
+ mConnInfo.getHost(), "" + mConnInfo.getPort()));
}
} else {
- log(ILogger.LL_FAILURE,
- "Cannot connect to ldap server. error: " + e.toString());
+ log(ILogger.LL_FAILURE,
+ "Cannot connect to ldap server. error: " + e.toString());
String errmsg = e.errorCodeToString();
if (errmsg == null)
errmsg = e.toString();
throw new ELdapException(
CMS.getUserMessage("CMS_LDAP_CONNECT_TO_LDAP_SERVER_FAILED",
- mConnInfo.getHost(), "" + (Integer.valueOf(mConnInfo.getPort())), errmsg));
+ mConnInfo.getHost(), "" + (Integer.valueOf(mConnInfo.getPort())), errmsg));
}
}
}
/**
- * Gets connection from this factory.
- * All connections gotten from this factory must be returned.
- * If not the max number of connections may be reached prematurely.
- * The best thing to put returnConn in a finally clause so it
- * always gets called. For example,
+ * Gets connection from this factory. All connections gotten from this
+ * factory must be returned. If not the max number of connections may be
+ * reached prematurely. The best thing to put returnConn in a finally clause
+ * so it always gets called. For example,
+ *
* <pre>
- * LDAPConnection c = null;
- * try {
- * c = factory.getConn();
- * myclass.do_something_with_c(c);
- * }
- * catch (ELdapException e) {
- * handle_error_here();
- * }
- * finally {
- * factory.returnConn(c);
- * }
+ * LDAPConnection c = null;
+ * try {
+ * c = factory.getConn();
+ * myclass.do_something_with_c(c);
+ * } catch (ELdapException e) {
+ * handle_error_here();
+ * } finally {
+ * factory.returnConn(c);
+ * }
* </pre>
*/
public LDAPConnection getConn()
- throws ELdapException {
+ throws ELdapException {
return getConn(true);
}
/**
- * Returns a LDAP connection - a clone of the master connection.
- * All connections should be returned to the factory using returnConn()
- * to recycle connection objects.
- * If not returned the limited max number is affected but if that
- * number is large not much harm is done.
- * Returns null if maximum number of connections reached.
- * <p>
- * The best thing to put returnConn in a finally clause so it
- * always gets called. For example,
+ * Returns a LDAP connection - a clone of the master connection. All
+ * connections should be returned to the factory using returnConn() to
+ * recycle connection objects. If not returned the limited max number is
+ * affected but if that number is large not much harm is done. Returns null
+ * if maximum number of connections reached.
+ * <p>
+ * The best thing to put returnConn in a finally clause so it always gets
+ * called. For example,
+ *
* <pre>
- * LDAPConnection c = null;
- * try {
- * c = factory.getConn();
- * myclass.do_something_with_c(c);
- * }
- * catch (ELdapException e) {
- * handle_error_here();
- * }
- * finally {
- * factory.returnConn(c);
- * }
+ * LDAPConnection c = null;
+ * try {
+ * c = factory.getConn();
+ * myclass.do_something_with_c(c);
+ * } catch (ELdapException e) {
+ * handle_error_here();
+ * } finally {
+ * factory.returnConn(c);
+ * }
* </pre>
- */
- public synchronized LDAPConnection getConn(boolean waitForConn)
- throws ELdapException {
+ */
+ public synchronized LDAPConnection getConn(boolean waitForConn)
+ throws ELdapException {
boolean waited = false;
CMS.debug("LdapAnonConnFactory::getConn");
- if (mNumConns == 0)
+ if (mNumConns == 0)
makeMinimum(true);
if (mNumConns == 0) {
if (!waitForConn)
return null;
try {
CMS.debug("getConn(): out of ldap connections");
- log(ILogger.LL_WARN,
- "Ran out of ldap connections available " +
- "in ldap connection pool to " +
- mConnInfo.getHost() + ":" + mConnInfo.getPort() + ". " +
- "This could be a temporary condition or an indication of " +
- "something more serious that can cause the server to " +
- "hang.");
+ log(ILogger.LL_WARN,
+ "Ran out of ldap connections available " +
+ "in ldap connection pool to " +
+ mConnInfo.getHost() + ":" + mConnInfo.getPort() + ". " +
+ "This could be a temporary condition or an indication of " +
+ "something more serious that can cause the server to " +
+ "hang.");
waited = true;
while (mNumConns == 0) {
wait();
@@ -291,53 +287,52 @@ public class LdapAnonConnFactory implements ILdapConnFactory {
mConns[mNumConns] = null;
if (waited) {
- log(ILogger.LL_WARN,
- "Ldap connections are available again in ldap connection pool " +
- "to " + mConnInfo.getHost() + ":" + mConnInfo.getPort());
+ log(ILogger.LL_WARN,
+ "Ldap connections are available again in ldap connection pool " +
+ "to " + mConnInfo.getHost() + ":" + mConnInfo.getPort());
}
CMS.debug("LdapAnonConnFactory.getConn(): num avail conns now " + mNumConns);
- //Beginning of fix for Bugzilla #630176
+ // Beginning of fix for Bugzilla #630176
boolean isConnected = false;
- if(conn != null) {
+ if (conn != null) {
isConnected = conn.isConnected();
}
- if(!isConnected) {
+ if (!isConnected) {
CMS.debug("LdapAnonConnFactory.getConn(): selected conn is down, try to reconnect...");
conn = null;
try {
- conn = new AnonConnection(mConnInfo);
+ conn = new AnonConnection(mConnInfo);
} catch (LDAPException e) {
- CMS.debug("LdapAnonConnFactory.getConn(): error when trying to bring back a down connection.");
- throw new ELdapException(
+ CMS.debug("LdapAnonConnFactory.getConn(): error when trying to bring back a down connection.");
+ throw new ELdapException(
CMS.getUserMessage("CMS_LDAP_CONNECT_TO_LDAP_SERVER_FAILED",
- mConnInfo.getHost(), "" + (Integer.valueOf(mConnInfo.getPort())), e.toString()));
+ mConnInfo.getHost(), "" + (Integer.valueOf(mConnInfo.getPort())), e.toString()));
}
}
- //This is the end of the fix for Bugzilla #630176
+ // This is the end of the fix for Bugzilla #630176
return conn;
}
- /**
- * Returns a connection to the factory for recycling.
- * All connections gotten from this factory must be returned.
- * If not the max number of connections may be reached prematurely.
+ /**
+ * Returns a connection to the factory for recycling. All connections gotten
+ * from this factory must be returned. If not the max number of connections
+ * may be reached prematurely.
* <p>
- * The best thing to put returnConn in a finally clause so it
- * always gets called. For example,
+ * The best thing to put returnConn in a finally clause so it always gets
+ * called. For example,
+ *
* <pre>
- * LDAPConnection c = null;
- * try {
- * c = factory.getConn();
- * myclass.do_something_with_c(c);
- * }
- * catch (ELdapException e) {
- * handle_error_here();
- * }
- * finally {
- * factory.returnConn(c);
- * }
+ * LDAPConnection c = null;
+ * try {
+ * c = factory.getConn();
+ * myclass.do_something_with_c(c);
+ * } catch (ELdapException e) {
+ * handle_error_here();
+ * } finally {
+ * factory.returnConn(c);
+ * }
* </pre>
*/
public synchronized void returnConn(LDAPConnection conn) {
@@ -348,12 +343,12 @@ public class LdapAnonConnFactory implements ILdapConnFactory {
AnonConnection anon = (AnonConnection) conn;
if (anon.getFacId() != mConns) {
- // returning a connection not from this factory.
+ // returning a connection not from this factory.
log(ILogger.LL_WARN, "returnConn: unknown connection.");
/* swallow this error but see who's doing it. */
- ELdapException e =
- new ELdapException(CMS.getUserMessage("CMS_LDAP_UNKNOWN_RETURNED_CONN"));
+ ELdapException e =
+ new ELdapException(CMS.getUserMessage("CMS_LDAP_UNKNOWN_RETURNED_CONN"));
}
// check if conn has already been returned.
for (int i = 0; i < mNumConns; i++) {
@@ -361,10 +356,10 @@ public class LdapAnonConnFactory implements ILdapConnFactory {
if (mConns[i] == anon) {
/* swallow this error but see who's doing it. */
- log(ILogger.LL_WARN,
- "returnConn: previously returned connection.");
- ELdapException e =
- new ELdapException(CMS.getUserMessage("CMS_LDAP_BAD_RETURNED_CONN"));
+ log(ILogger.LL_WARN,
+ "returnConn: previously returned connection.");
+ ELdapException e =
+ new ELdapException(CMS.getUserMessage("CMS_LDAP_BAD_RETURNED_CONN"));
}
}
@@ -377,9 +372,9 @@ public class LdapAnonConnFactory implements ILdapConnFactory {
// return conn.
CMS.debug("returnConn: mNumConns now " + mNumConns);
} catch (LDAPException e) {
- log(ILogger.LL_WARN,
- "Could not re-authenticate ldap connection to anonymous." +
- " Error " + e);
+ log(ILogger.LL_WARN,
+ "Could not re-authenticate ldap connection to anonymous." +
+ " Error " + e);
}
// return the connection even if can't reauthentication anon.
// most likely server was down.
@@ -389,7 +384,7 @@ public class LdapAnonConnFactory implements ILdapConnFactory {
}
protected void finalize()
- throws Exception {
+ throws Exception {
reset();
}
@@ -401,30 +396,30 @@ public class LdapAnonConnFactory implements ILdapConnFactory {
}
/**
- * resets this factory - if no connections outstanding,
- * disconnections all connections and resets everything to 0 as if
- * no connections were ever made. intended to be called just before
- * shutdown or exit to disconnection & cleanup connections.
+ * resets this factory - if no connections outstanding, disconnections all
+ * connections and resets everything to 0 as if no connections were ever
+ * made. intended to be called just before shutdown or exit to disconnection
+ * & cleanup connections.
*/
// ok only if no connections outstanding.
- public synchronized void reset()
- throws ELdapException {
+ public synchronized void reset()
+ throws ELdapException {
if (mNumConns == mTotal) {
for (int i = 0; i < mNumConns; i++) {
try {
CMS.debug("disconnecting connection " + i);
mConns[i].disconnect();
} catch (LDAPException e) {
- log(ILogger.LL_INFO,
- "exception during disconnect: " + e.toString());
+ log(ILogger.LL_INFO,
+ "exception during disconnect: " + e.toString());
}
mConns[i] = null;
}
mTotal = 0;
mNumConns = 0;
} else {
- log(ILogger.LL_INFO,
- "Cannot reset() while connections not all returned");
+ log(ILogger.LL_INFO,
+ "Cannot reset() while connections not all returned");
throw new ELdapException(
CMS.getUserMessage("CMS_LDAP_CANNOT_RESET_CONNFAC"));
}
@@ -435,9 +430,9 @@ public class LdapAnonConnFactory implements ILdapConnFactory {
*/
private void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_LDAP, level,
- "In Ldap (anonymous) connection pool to" +
- " host " + mConnInfo.getHost() +
- " port " + mConnInfo.getPort() + ", " + msg);
+ "In Ldap (anonymous) connection pool to" +
+ " host " + mConnInfo.getHost() +
+ " port " + mConnInfo.getPort() + ", " + msg);
}
/**
@@ -450,27 +445,27 @@ public class LdapAnonConnFactory implements ILdapConnFactory {
private static final long serialVersionUID = 4813780131074412404L;
public AnonConnection(LdapConnInfo connInfo)
- throws LDAPException {
+ throws LDAPException {
super(connInfo);
}
-
- public AnonConnection(String host, int port, int version,
- LDAPSocketFactory fac)
- throws LDAPException {
+
+ public AnonConnection(String host, int port, int version,
+ LDAPSocketFactory fac)
+ throws LDAPException {
super(host, port, version, fac);
}
-
+
/**
* instantiates a non-secure connection to a ldap server
*/
public AnonConnection(String host, int port, int version)
- throws LDAPException {
+ throws LDAPException {
super(host, port, version);
}
/**
- * used only to identify the factory from which this came.
- * mConns to identify factory.
+ * used only to identify the factory from which this came. mConns to
+ * identify factory.
*/
public AnonConnection[] getFacId() {
return mConns;
diff --git a/pki/base/common/src/com/netscape/cmscore/ldapconn/LdapAnonConnection.java b/pki/base/common/src/com/netscape/cmscore/ldapconn/LdapAnonConnection.java
index 1d3996dd..5243c4fb 100644
--- a/pki/base/common/src/com/netscape/cmscore/ldapconn/LdapAnonConnection.java
+++ b/pki/base/common/src/com/netscape/cmscore/ldapconn/LdapAnonConnection.java
@@ -17,18 +17,16 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.ldapconn;
-
import netscape.ldap.LDAPConnection;
import netscape.ldap.LDAPException;
import netscape.ldap.LDAPSocketFactory;
import netscape.ldap.LDAPv2;
-
/**
- * A LDAP connection that is bound to a server host, port and secure type.
- * Makes a LDAP connection when instantiated.
- * Cannot establish another LDAP connection after construction.
- * LDAPConnection connect methods are overridden to prevent this.
+ * A LDAP connection that is bound to a server host, port and secure type. Makes
+ * a LDAP connection when instantiated. Cannot establish another LDAP connection
+ * after construction. LDAPConnection connect methods are overridden to prevent
+ * this.
*/
public class LdapAnonConnection extends LDAPConnection {
@@ -41,25 +39,25 @@ public class LdapAnonConnection extends LDAPConnection {
* instantiates a connection to a ldap server
*/
public LdapAnonConnection(LdapConnInfo connInfo)
- throws LDAPException {
+ throws LDAPException {
super(connInfo.getSecure() ? new LdapJssSSLSocketFactory() : null);
- // Set option to automatically follow referrals.
+ // Set option to automatically follow referrals.
// rebind info is also anonymous.
boolean followReferrals = connInfo.getFollowReferrals();
setOption(LDAPv2.REFERRALS, new Boolean(followReferrals));
- super.connect(connInfo.getVersion(),
- connInfo.getHost(), connInfo.getPort(), null, null);
+ super.connect(connInfo.getVersion(),
+ connInfo.getHost(), connInfo.getPort(), null, null);
}
/**
* instantiates a connection to a ldap server
*/
- public LdapAnonConnection(String host, int port, int version,
- LDAPSocketFactory fac)
- throws LDAPException {
+ public LdapAnonConnection(String host, int port, int version,
+ LDAPSocketFactory fac)
+ throws LDAPException {
super(fac);
super.connect(version, host, port, null, null);
}
@@ -68,14 +66,13 @@ public class LdapAnonConnection extends LDAPConnection {
* instantiates a non-secure connection to a ldap server
*/
public LdapAnonConnection(String host, int port, int version)
- throws LDAPException {
+ throws LDAPException {
super();
super.connect(version, host, port, null, null);
}
/**
- * overrides superclass connect.
- * does not allow reconnect.
+ * overrides superclass connect. does not allow reconnect.
*/
public void connect(String host, int port) throws LDAPException {
throw new RuntimeException(
@@ -83,11 +80,10 @@ public class LdapAnonConnection extends LDAPConnection {
}
/**
- * overrides superclass connect.
- * does not allow reconnect.
+ * overrides superclass connect. does not allow reconnect.
*/
- public void connect(int version, String host, int port,
- String dn, String pw) throws LDAPException {
+ public void connect(int version, String host, int port,
+ String dn, String pw) throws LDAPException {
throw new RuntimeException(
"this LdapAnonConnection already connected: connect(v,h,p)");
}
diff --git a/pki/base/common/src/com/netscape/cmscore/ldapconn/LdapAuthInfo.java b/pki/base/common/src/com/netscape/cmscore/ldapconn/LdapAuthInfo.java
index b499dd07..b853fb4b 100644
--- a/pki/base/common/src/com/netscape/cmscore/ldapconn/LdapAuthInfo.java
+++ b/pki/base/common/src/com/netscape/cmscore/ldapconn/LdapAuthInfo.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.ldapconn;
-
import java.util.Hashtable;
import netscape.ldap.LDAPConnection;
@@ -29,7 +28,6 @@ import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.ldap.ILdapAuthInfo;
import com.netscape.cmsutil.password.IPasswordStore;
-
/**
* class for reading ldap authentication info from config store
*/
@@ -56,28 +54,30 @@ public class LdapAuthInfo implements ILdapAuthInfo {
}
/**
- * constructs ldap auth info directly from config store, and verifies
- * the password by attempting to connect to the server.
+ * constructs ldap auth info directly from config store, and verifies the
+ * password by attempting to connect to the server.
*/
public LdapAuthInfo(IConfigStore config, String host, int port, boolean secure)
- throws EBaseException {
+ throws EBaseException {
init(config, host, port, secure);
}
- public String getPasswordFromStore (String prompt) {
+ public String getPasswordFromStore(String prompt) {
String pwd = null;
CMS.debug("LdapAuthInfo: getPasswordFromStore: try to get it from password store");
-// hey - should use password store interface to allow different implementations
-// but the problem is, other parts of the system just go directly to the file
-// so calling CMS.getPasswordStore() will give you an outdated one
-/*
- IConfigStore mainConfig = CMS.getConfigStore();
- String pwdFile = mainConfig.getString("passwordFile");
- FileConfigStore pstore = new FileConfigStore(pwdFile);
-*/
+ // hey - should use password store interface to allow different
+ // implementations
+ // but the problem is, other parts of the system just go directly to the
+ // file
+ // so calling CMS.getPasswordStore() will give you an outdated one
+ /*
+ * IConfigStore mainConfig = CMS.getConfigStore(); String pwdFile =
+ * mainConfig.getString("passwordFile"); FileConfigStore pstore = new
+ * FileConfigStore(pwdFile);
+ */
IPasswordStore pwdStore = CMS.getPasswordStore();
- CMS.debug("LdapAuthInfo: getPasswordFromStore: about to get from passwored store: "+prompt);
+ CMS.debug("LdapAuthInfo: getPasswordFromStore: about to get from passwored store: " + prompt);
// support publishing dirsrv with different pwd than internaldb
@@ -85,18 +85,18 @@ public class LdapAuthInfo implements ILdapAuthInfo {
if (pwdStore != null) {
CMS.debug("LdapAuthInfo: getPasswordFromStore: password store available");
pwd = pwdStore.getPassword(prompt);
-// pwd = pstore.getString(prompt);
- if ( pwd == null) {
- CMS.debug("LdapAuthInfo: getPasswordFromStore: password for "+prompt+
- " not found, trying internaldb");
+ // pwd = pstore.getString(prompt);
+ if (pwd == null) {
+ CMS.debug("LdapAuthInfo: getPasswordFromStore: password for " + prompt +
+ " not found, trying internaldb");
-// pwd = pstore.getString("internaldb");
+ // pwd = pstore.getString("internaldb");
- pwd = pwdStore.getPassword("internaldb"); // last resort
+ pwd = pwdStore.getPassword("internaldb"); // last resort
} else
- CMS.debug("LdapAuthInfo: getPasswordFromStore: password found for prompt in password store");
+ CMS.debug("LdapAuthInfo: getPasswordFromStore: password found for prompt in password store");
} else
- CMS.debug("LdapAuthInfo: getPasswordFromStore: password store not available: pwdStore is null");
+ CMS.debug("LdapAuthInfo: getPasswordFromStore: password store not available: pwdStore is null");
return pwd;
}
@@ -110,19 +110,19 @@ public class LdapAuthInfo implements ILdapAuthInfo {
/**
* initialize this class from the config store, and verify the password.
- *
- * @param host The host that the directory server is running on.
- * This will be used to verify the password by attempting to connect.
- * If it is <code>null</code>, the password will not be verified.
+ *
+ * @param host The host that the directory server is running on. This will
+ * be used to verify the password by attempting to connect. If it
+ * is <code>null</code>, the password will not be verified.
* @param port The port that the directory server is running on.
*/
public void init(IConfigStore config, String host, int port, boolean secure)
- throws EBaseException {
+ throws EBaseException {
CMS.debug("LdapAuthInfo: init()");
- if (mInited) {
+ if (mInited) {
CMS.debug("LdapAuthInfo: already initialized");
- return; // XXX throw exception here ?
+ return; // XXX throw exception here ?
}
CMS.debug("LdapAuthInfo: init begins");
@@ -144,30 +144,30 @@ public class LdapAuthInfo implements ILdapAuthInfo {
if (prompt == null) {
prompt = "LDAP Authentication";
- CMS.debug("LdapAuthInfo: init: prompt is null, change to "+prompt);
+ CMS.debug("LdapAuthInfo: init: prompt is null, change to " + prompt);
} else
- CMS.debug("LdapAuthInfo: init: prompt is "+prompt);
+ CMS.debug("LdapAuthInfo: init: prompt is " + prompt);
if (mParms[1] == null) {
CMS.debug("LdapAuthInfo: init: try getting from memory cache");
mParms[1] = (String) passwords.get(prompt);
-if (mParms[1] != null) {
- inMem = true;
-CMS.debug("LdapAuthInfo: init: got password from memory");
-} else
-CMS.debug("LdapAuthInfo: init: password not in memory");
+ if (mParms[1] != null) {
+ inMem = true;
+ CMS.debug("LdapAuthInfo: init: got password from memory");
+ } else
+ CMS.debug("LdapAuthInfo: init: password not in memory");
} else
-CMS.debug("LdapAuthInfo: init: found password from config");
+ CMS.debug("LdapAuthInfo: init: found password from config");
if (mParms[1] == null) {
mParms[1] = getPasswordFromStore(prompt);
- } else {
+ } else {
CMS.debug("LdapAuthInfo: init: password found for prompt.");
- }
+ }
// verify the password
- if ((mParms[1]!= null) && (!mParms[1].equals("")) && (host == null ||
- authInfoOK(host, port, secure, mParms[0], mParms[1]))) {
+ if ((mParms[1] != null) && (!mParms[1].equals("")) && (host == null ||
+ authInfoOK(host, port, secure, mParms[0], mParms[1]))) {
// The password is OK or uncheckable
CMS.debug("LdapAuthInfo: password ok: store in memory cache");
passwords.put(prompt, mParms[1]);
@@ -176,16 +176,17 @@ CMS.debug("LdapAuthInfo: init: found password from config");
CMS.debug("LdapAuthInfo: password not found");
else {
CMS.debug("LdapAuthInfo: password does not work");
-/* what do you know? Our IPasswordStore does not have a remove function.
- pstore.remove("internaldb");
-*/
+ /*
+ * what do you know? Our IPasswordStore does not have a
+ * remove function. pstore.remove("internaldb");
+ */
if (inMem) {
// this is for the case when admin changes pwd
// from console
mParms[1] = getPasswordFromStore(prompt);
- if(authInfoOK(host, port, secure, mParms[0], mParms[1])) {
- CMS.debug("LdapAuthInfo: password ok: store in memory cache");
- passwords.put(prompt, mParms[1]);
+ if (authInfoOK(host, port, secure, mParms[0], mParms[1])) {
+ CMS.debug("LdapAuthInfo: password ok: store in memory cache");
+ passwords.put(prompt, mParms[1]);
}
}
}
@@ -212,16 +213,17 @@ CMS.debug("LdapAuthInfo: init: found password from config");
/**
* Verifies the distinguished name and password by attempting to
- * authenticate to the server. If we connect to the server but cannot
- * authenticate, we conclude that the DN or password is invalid. If
- * we cannot connect at all, we don't know, so we return true
- * (there's no sense asking for the password again since we can't verify
- * it anyway). If we connect and authenticate successfully, we know
- * the DN and password are correct, so we return true.
+ * authenticate to the server. If we connect to the server but cannot
+ * authenticate, we conclude that the DN or password is invalid. If we
+ * cannot connect at all, we don't know, so we return true (there's no sense
+ * asking for the password again since we can't verify it anyway). If we
+ * connect and authenticate successfully, we know the DN and password are
+ * correct, so we return true.
*/
private static LDAPConnection conn = new LDAPConnection();
+
private static boolean
- authInfoOK(String host, int port, boolean secure, String dn, String pw) {
+ authInfoOK(String host, int port, boolean secure, String dn, String pw) {
// We dont perform auth checking if we are in SSL mode.
if (secure)
@@ -238,16 +240,13 @@ CMS.debug("LdapAuthInfo: init: found password from config");
}
/**
- * There is a bug in LDAP SDK. VM will crash on NT if
- * we connect and disconnect too many times.
+ * There is a bug in LDAP SDK. VM will crash on NT if we connect and
+ * disconnect too many times.
**/
-
+
/**
- if( connected ) {
- try {
- conn.disconnect();
- } catch( LDAPException e ) { }
- }
+ * if( connected ) { try { conn.disconnect(); } catch( LDAPException e )
+ * { } }
**/
if (connected && !authenticated) {
@@ -258,10 +257,11 @@ CMS.debug("LdapAuthInfo: init: found password from config");
}
/**
- * get authentication type.
+ * get authentication type.
+ *
* @return one of: <br>
- * LdapAuthInfo.LDAP_AUTHTYPE_BASICAUTH or
- * LdapAuthInfo.LDAP_AUTHTYPE_SSLCLIENTAUTH
+ * LdapAuthInfo.LDAP_AUTHTYPE_BASICAUTH or
+ * LdapAuthInfo.LDAP_AUTHTYPE_SSLCLIENTAUTH
*/
public int getAuthType() {
return mType;
@@ -269,6 +269,7 @@ CMS.debug("LdapAuthInfo: init: found password from config");
/**
* get params for authentication
+ *
* @return array of parameters for this authentication.
*/
public String[] getParms() {
@@ -281,7 +282,7 @@ CMS.debug("LdapAuthInfo: init: found password from config");
public void addPassword(String prompt, String pw) {
try {
passwords.put(prompt, pw);
- }catch (Exception e) {
+ } catch (Exception e) {
}
}
@@ -291,7 +292,7 @@ CMS.debug("LdapAuthInfo: init: found password from config");
public void removePassword(String prompt) {
try {
passwords.remove(prompt);
- }catch (Exception e) {
+ } catch (Exception e) {
}
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/ldapconn/LdapBoundConnFactory.java b/pki/base/common/src/com/netscape/cmscore/ldapconn/LdapBoundConnFactory.java
index a8a107ac..3a3b893a 100644
--- a/pki/base/common/src/com/netscape/cmscore/ldapconn/LdapBoundConnFactory.java
+++ b/pki/base/common/src/com/netscape/cmscore/ldapconn/LdapBoundConnFactory.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.ldapconn;
-
import netscape.ldap.LDAPConnection;
import netscape.ldap.LDAPException;
import netscape.ldap.LDAPSocketFactory;
@@ -30,12 +29,10 @@ import com.netscape.certsrv.ldap.ELdapServerDownException;
import com.netscape.certsrv.ldap.ILdapBoundConnFactory;
import com.netscape.certsrv.logging.ILogger;
-
/**
- * Factory for getting LDAP Connections to a LDAP server with the same
- * LDAP authentication.
- * XXX not sure how useful this is given that LDAPConnection itself can
- * be shared by multiple threads and cloned.
+ * Factory for getting LDAP Connections to a LDAP server with the same LDAP
+ * authentication. XXX not sure how useful this is given that LDAPConnection
+ * itself can be shared by multiple threads and cloned.
*/
public class LdapBoundConnFactory implements ILdapBoundConnFactory {
protected int mMinConns = 5;
@@ -52,10 +49,10 @@ public class LdapBoundConnFactory implements ILdapBoundConnFactory {
public static final String PROP_ERROR_IF_DOWN = "errorIfDown";
- private int mNumConns = 0; // number of available conns in array
- private int mTotal = 0; // total num conns
+ private int mNumConns = 0; // number of available conns in array
+ private int mTotal = 0; // total num conns
- private boolean doCloning=true;
+ private boolean doCloning = true;
private LdapBoundConnection mMasterConn = null; // master connection object.
private BoundConnection mConns[];
@@ -70,8 +67,8 @@ public class LdapBoundConnFactory implements ILdapBoundConnFactory {
private boolean mDefErrorIfDown = false;
/**
- * Constructor for initializing from the config store.
- * must be followed by init(IConfigStore)
+ * Constructor for initializing from the config store. must be followed by
+ * init(IConfigStore)
*/
public LdapBoundConnFactory() {
}
@@ -94,51 +91,53 @@ public class LdapBoundConnFactory implements ILdapBoundConnFactory {
/**
* Constructor for LdapBoundConnFactory
+ *
* @param minConns minimum number of connections to have available
- * @param maxConns max number of connections to have available. This is
- * the maximum number of clones of this connection or separate connections one wants to allow.
+ * @param maxConns max number of connections to have available. This is the
+ * maximum number of clones of this connection or separate
+ * connections one wants to allow.
* @param serverInfo server connection info - host, port, etc.
*/
- public LdapBoundConnFactory(int minConns, int maxConns,
- LdapConnInfo connInfo, LdapAuthInfo authInfo) throws ELdapException {
+ public LdapBoundConnFactory(int minConns, int maxConns,
+ LdapConnInfo connInfo, LdapAuthInfo authInfo) throws ELdapException {
init(minConns, maxConns, connInfo, authInfo);
}
/**
* Constructor for initialize
*/
- public void init(IConfigStore config)
- throws ELdapException, EBaseException {
+ public void init(IConfigStore config)
+ throws ELdapException, EBaseException {
CMS.debug("LdapBoundConnFactory: init ");
LdapConnInfo connInfo =
- new LdapConnInfo(config.getSubStore(PROP_LDAPCONNINFO));
+ new LdapConnInfo(config.getSubStore(PROP_LDAPCONNINFO));
mErrorIfDown = config.getBoolean(PROP_ERROR_IF_DOWN, mDefErrorIfDown);
- doCloning = config.getBoolean("doCloning",true);
+ doCloning = config.getBoolean("doCloning", true);
CMS.debug("LdapBoundConnFactory:doCloning " + doCloning);
init(config.getInteger(PROP_MINCONNS, mMinConns),
- config.getInteger(PROP_MAXCONNS, mMaxConns),
- connInfo,
- new LdapAuthInfo(config.getSubStore(PROP_LDAPAUTHINFO),
- connInfo.getHost(), connInfo.getPort(), connInfo.getSecure()));
+ config.getInteger(PROP_MAXCONNS, mMaxConns),
+ connInfo,
+ new LdapAuthInfo(config.getSubStore(PROP_LDAPAUTHINFO),
+ connInfo.getHost(), connInfo.getPort(), connInfo.getSecure()));
}
/**
- * initialize parameters obtained from either constructor or
- * config store
+ * initialize parameters obtained from either constructor or config store
+ *
* @param minConns minimum number of connection handls to have available.
* @param maxConns maximum total number of connections to ever have.
* @param connInfo ldap connection info.
* @param authInfo ldap authentication info.
- * @exception ELdapException if any error occurs.
+ * @exception ELdapException if any error occurs.
*/
- private void init(int minConns, int maxConns,
- LdapConnInfo connInfo, LdapAuthInfo authInfo)
- throws ELdapException {
- if (minConns <= 0 || maxConns <= 0 || minConns > maxConns)
+ private void init(int minConns, int maxConns,
+ LdapConnInfo connInfo, LdapAuthInfo authInfo)
+ throws ELdapException {
+ if (minConns <= 0 || maxConns <= 0 || minConns > maxConns)
throw new ELdapException(
CMS.getUserMessage("CMS_LDAP_INVALID_NUMCONN_PARAMETERS"));
if (connInfo == null || authInfo == null)
@@ -153,15 +152,15 @@ public class LdapBoundConnFactory implements ILdapBoundConnFactory {
// Create connection handle and make initial connection
CMS.debug(
- "init: before makeConnection errorIfDown is " + mErrorIfDown);
+ "init: before makeConnection errorIfDown is " + mErrorIfDown);
makeConnection(mErrorIfDown);
CMS.debug(
- "initializing with mininum " + mMinConns + " and maximum " + mMaxConns +
- " connections to " +
- "host " + mConnInfo.getHost() + " port " + mConnInfo.getPort() +
- ", secure connection, " + mConnInfo.getSecure() +
- ", authentication type " + mAuthInfo.getAuthType());
+ "initializing with mininum " + mMinConns + " and maximum " + mMaxConns +
+ " connections to " +
+ "host " + mConnInfo.getHost() + " port " + mConnInfo.getPort() +
+ ", secure connection, " + mConnInfo.getSecure() +
+ ", authentication type " + mAuthInfo.getAuthType());
// initalize minimum number of connection handles available.
makeMinimum();
@@ -169,6 +168,7 @@ public class LdapBoundConnFactory implements ILdapBoundConnFactory {
/**
* makes the initial master connection used to clone others..
+ *
* @exception ELdapException if any error occurs.
*/
protected void makeConnection(boolean errorIfDown) throws ELdapException {
@@ -179,31 +179,31 @@ public class LdapBoundConnFactory implements ILdapBoundConnFactory {
if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE) {
// need to intercept this because message from LDAP is
// "DSA is unavailable" which confuses with DSA PKI.
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAPCONN_CONNECT_SERVER",
- mConnInfo.getHost(),
- Integer.toString(mConnInfo.getPort())));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_LDAPCONN_CONNECT_SERVER",
+ mConnInfo.getHost(),
+ Integer.toString(mConnInfo.getPort())));
if (errorIfDown) {
throw new ELdapServerDownException(
CMS.getUserMessage("CMS_LDAP_SERVER_UNAVAILABLE",
- mConnInfo.getHost(), "" + mConnInfo.getPort()));
+ mConnInfo.getHost(), "" + mConnInfo.getPort()));
}
} else {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAPCONN_FAILED_SERVER", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_LDAPCONN_FAILED_SERVER", e.toString()));
throw new ELdapException(
- CMS.getUserMessage("CMS_LDAP_CONNECT_TO_LDAP_SERVER_FAILED",
- mConnInfo.getHost(), "" + (Integer.valueOf(mConnInfo.getPort())), e.toString()));
+ CMS.getUserMessage("CMS_LDAP_CONNECT_TO_LDAP_SERVER_FAILED",
+ mConnInfo.getHost(), "" + (Integer.valueOf(mConnInfo.getPort())), e.toString()));
}
}
}
-
/**
* makes subsequent connections if cloning is not used .
+ *
* @exception ELdapException if any error occurs.
*/
- private LdapBoundConnection makeNewConnection(boolean errorIfDown) throws ELdapException {
+ private LdapBoundConnection makeNewConnection(boolean errorIfDown) throws ELdapException {
CMS.debug("LdapBoundConnFactory:In makeNewConnection: errorIfDown " + errorIfDown);
LdapBoundConnection conn = null;
try {
@@ -213,46 +213,46 @@ public class LdapBoundConnFactory implements ILdapBoundConnFactory {
// need to intercept this because message from LDAP is
// "DSA is unavailable" which confuses with DSA PKI.
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAPCONN_CONNECT_SERVER",
- mConnInfo.getHost(),
- Integer.toString(mConnInfo.getPort())));
+ CMS.getLogMessage("CMSCORE_LDAPCONN_CONNECT_SERVER",
+ mConnInfo.getHost(),
+ Integer.toString(mConnInfo.getPort())));
if (errorIfDown) {
throw new ELdapServerDownException(
CMS.getUserMessage("CMS_LDAP_SERVER_UNAVAILABLE",
- mConnInfo.getHost(), "" + mConnInfo.getPort()));
+ mConnInfo.getHost(), "" + mConnInfo.getPort()));
}
} else {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAPCONN_FAILED_SERVER", e.toString()));
+ CMS.getLogMessage("CMSCORE_LDAPCONN_FAILED_SERVER", e.toString()));
throw new ELdapException(
CMS.getUserMessage("CMS_LDAP_CONNECT_TO_LDAP_SERVER_FAILED",
- mConnInfo.getHost(), "" + (Integer.valueOf(mConnInfo.getPort())), e.toString()));
+ mConnInfo.getHost(), "" + (Integer.valueOf(mConnInfo.getPort())), e.toString()));
}
}
return conn;
}
+
/**
* makes the minumum number of connections
*/
private void makeMinimum() throws ELdapException {
- if (mMasterConn == null || mMasterConn.isConnected() == false)
+ if (mMasterConn == null || mMasterConn.isConnected() == false)
return;
int increment;
if (mNumConns < mMinConns && mTotal <= mMaxConns) {
increment = Math.min(mMinConns - mNumConns, mMaxConns - mTotal);
CMS.debug(
- "increasing minimum connections by " + increment);
+ "increasing minimum connections by " + increment);
for (int i = increment - 1; i >= 0; i--) {
- if(doCloning == true) {
+ if (doCloning == true) {
mConns[i] = (BoundConnection) mMasterConn.clone();
- }
- else {
+ } else {
mConns[i] = (BoundConnection) makeNewConnection(true);
}
-
+
}
mTotal += increment;
mNumConns += increment;
@@ -262,132 +262,125 @@ public class LdapBoundConnFactory implements ILdapBoundConnFactory {
}
/**
- * gets a conenction from this factory.
- * All connections obtained from the factory must be returned by
- * returnConn() method.
- * The best thing to do is to put returnConn in a finally clause so it
- * always gets called. For example,
+ * gets a conenction from this factory. All connections obtained from the
+ * factory must be returned by returnConn() method. The best thing to do is
+ * to put returnConn in a finally clause so it always gets called. For
+ * example,
+ *
* <pre>
- * LDAPConnection c = null;
- * try {
- * c = factory.getConn();
- * myclass.do_something_with_c(c);
- * }
- * catch (ELdapException e) {
- * handle_error_here();
- * }
- * finally {
- * factory.returnConn(c);
- * }
+ * LDAPConnection c = null;
+ * try {
+ * c = factory.getConn();
+ * myclass.do_something_with_c(c);
+ * } catch (ELdapException e) {
+ * handle_error_here();
+ * } finally {
+ * factory.returnConn(c);
+ * }
* </pre>
*/
- public LDAPConnection getConn()
- throws ELdapException {
+ public LDAPConnection getConn()
+ throws ELdapException {
return getConn(true);
}
/**
- * Returns a LDAP connection - a clone of the master connection.
- * All connections should be returned to the factory using returnConn()
- * to recycle connection objects.
- * If not returned the limited max number is affected but if that
- * number is large not much harm is done.
- * Returns null if maximum number of connections reached.
- * The best thing to do is to put returnConn in a finally clause so it
- * always gets called. For example,
+ * Returns a LDAP connection - a clone of the master connection. All
+ * connections should be returned to the factory using returnConn() to
+ * recycle connection objects. If not returned the limited max number is
+ * affected but if that number is large not much harm is done. Returns null
+ * if maximum number of connections reached. The best thing to do is to put
+ * returnConn in a finally clause so it always gets called. For example,
+ *
* <pre>
- * LDAPConnection c = null;
- * try {
- * c = factory.getConn();
- * myclass.do_something_with_c(c);
- * }
- * catch (ELdapException e) {
- * handle_error_here();
- * }
- * finally {
- * factory.returnConn(c);
- * }
+ * LDAPConnection c = null;
+ * try {
+ * c = factory.getConn();
+ * myclass.do_something_with_c(c);
+ * } catch (ELdapException e) {
+ * handle_error_here();
+ * } finally {
+ * factory.returnConn(c);
+ * }
* </pre>
- */
- public synchronized LDAPConnection getConn(boolean waitForConn)
- throws ELdapException {
+ */
+ public synchronized LDAPConnection getConn(boolean waitForConn)
+ throws ELdapException {
boolean waited = false;
- CMS.debug("In LdapBoundConnFactory::getConn()");
- if(mMasterConn != null)
+ CMS.debug("In LdapBoundConnFactory::getConn()");
+ if (mMasterConn != null)
CMS.debug("masterConn is connected: " + mMasterConn.isConnected());
else
CMS.debug("masterConn is null.");
if (mMasterConn == null || !mMasterConn.isConnected()) {
try {
- makeConnection(true);
- } catch (ELdapException e) {
+ makeConnection(true);
+ } catch (ELdapException e) {
mMasterConn = null;
CMS.debug("Can't create master connection in LdapBoundConnFactory::getConn! " + e.toString());
throw e;
}
}
- if (mNumConns == 0)
+ if (mNumConns == 0)
makeMinimum();
if (mNumConns == 0) {
if (!waitForConn)
return null;
try {
CMS.debug("getConn: out of ldap connections");
- log(ILogger.LL_WARN,
- "Ran out of ldap connections available " +
- "in ldap connection pool to " +
- mConnInfo.getHost() + ":" + mConnInfo.getPort() + ". " +
- "This could be a temporary condition or an indication of " +
- "something more serious that can cause the server to " +
- "hang.");
+ log(ILogger.LL_WARN,
+ "Ran out of ldap connections available " +
+ "in ldap connection pool to " +
+ mConnInfo.getHost() + ":" + mConnInfo.getPort() + ". " +
+ "This could be a temporary condition or an indication of " +
+ "something more serious that can cause the server to " +
+ "hang.");
waited = true;
- while (mNumConns == 0)
+ while (mNumConns == 0)
wait();
} catch (InterruptedException e) {
}
- }
+ }
mNumConns--;
LDAPConnection conn = mConns[mNumConns];
boolean isConnected = false;
- if(conn != null) {
+ if (conn != null) {
isConnected = conn.isConnected();
}
CMS.debug("getConn: conn is connected " + isConnected);
- //If masterConn is still alive, lets try to bring this one
- //back to life
+ // If masterConn is still alive, lets try to bring this one
+ // back to life
- if((isConnected == false) && (mMasterConn != null)
- && (mMasterConn.isConnected() == true)) {
+ if ((isConnected == false) && (mMasterConn != null)
+ && (mMasterConn.isConnected() == true)) {
CMS.debug("Attempt to bring back down connection.");
- if(doCloning == true) {
+ if (doCloning == true) {
mConns[mNumConns] = (BoundConnection) mMasterConn.clone();
- }
- else {
+ } else {
try {
- mConns[mNumConns] = (BoundConnection) makeNewConnection(true);
+ mConns[mNumConns] = (BoundConnection) makeNewConnection(true);
+ } catch (ELdapException e) {
+ mConns[mNumConns] = null;
}
- catch (ELdapException e) {
- mConns[mNumConns] = null;
- }
- }
- conn = mConns[mNumConns];
+ }
+ conn = mConns[mNumConns];
- CMS.debug("Re-animated connection: " + conn);
- }
+ CMS.debug("Re-animated connection: " + conn);
+ }
- mConns[mNumConns] = null;
+ mConns[mNumConns] = null;
if (waited) {
- log(ILogger.LL_WARN,
- "Ldap connections are available again in ldap connection pool " +
- "to " + mConnInfo.getHost() + ":" + mConnInfo.getPort());
+ log(ILogger.LL_WARN,
+ "Ldap connections are available again in ldap connection pool " +
+ "to " + mConnInfo.getHost() + ":" + mConnInfo.getPort());
}
CMS.debug("getConn: mNumConns now " + mNumConns);
@@ -395,22 +388,20 @@ public class LdapBoundConnFactory implements ILdapBoundConnFactory {
}
/**
- * Teturn connection to the factory.
- * This is mandatory after a getConn().
+ * Teturn connection to the factory. This is mandatory after a getConn().
* The best thing to do is to put returnConn in a finally clause so it
- * always gets called. For example,
+ * always gets called. For example,
+ *
* <pre>
- * LDAPConnection c = null;
- * try {
- * c = factory.getConn();
- * myclass.do_something_with_c(c);
- * }
- * catch (ELdapException e) {
- * handle_error_here();
- * }
- * finally {
- * factory.returnConn(c);
- * }
+ * LDAPConnection c = null;
+ * try {
+ * c = factory.getConn();
+ * myclass.do_something_with_c(c);
+ * } catch (ELdapException e) {
+ * handle_error_here();
+ * } finally {
+ * factory.returnConn(c);
+ * }
* </pre>
*/
public synchronized void returnConn(LDAPConnection conn) {
@@ -423,17 +414,17 @@ public class LdapBoundConnFactory implements ILdapBoundConnFactory {
log(ILogger.LL_WARN, "returnConn: unknown connection.");
/* swallow this exception but see who's doing it. */
- ELdapException e =
- new ELdapException(CMS.getUserMessage("CMS_LDAP_UNKNOWN_RETURNED_CONN"));
+ ELdapException e =
+ new ELdapException(CMS.getUserMessage("CMS_LDAP_UNKNOWN_RETURNED_CONN"));
}
for (int i = 0; i < mNumConns; i++) {
if (mConns[i] == conn) {
CMS.debug(
- "returnConn: previously returned connection.");
+ "returnConn: previously returned connection.");
- /* swallow this exception but see who's doing it */
- ELdapException e =
- new ELdapException(CMS.getUserMessage("CMS_LDAP_BAD_RETURNED_CONN"));
+ /* swallow this exception but see who's doing it */
+ ELdapException e =
+ new ELdapException(CMS.getUserMessage("CMS_LDAP_BAD_RETURNED_CONN"));
}
}
mConns[mNumConns++] = boundconn;
@@ -446,24 +437,23 @@ public class LdapBoundConnFactory implements ILdapBoundConnFactory {
*/
private void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_LDAP, level,
- "In Ldap (bound) connection pool to" +
- " host " + mConnInfo.getHost() +
- " port " + mConnInfo.getPort() + ", " + msg);
+ "In Ldap (bound) connection pool to" +
+ " host " + mConnInfo.getHost() +
+ " port " + mConnInfo.getPort() + ", " + msg);
}
protected void finalize()
- throws Exception {
+ throws Exception {
reset();
}
/**
- * used for disconnecting all connections and reset everything to 0
- * as if connections were never made. used just before a subsystem
- * shutdown or process exit.
- * useful only if no connections are outstanding.
+ * used for disconnecting all connections and reset everything to 0 as if
+ * connections were never made. used just before a subsystem shutdown or
+ * process exit. useful only if no connections are outstanding.
*/
- public synchronized void reset()
- throws ELdapException {
+ public synchronized void reset()
+ throws ELdapException {
if (mNumConns == mTotal) {
for (int i = 0; i < mNumConns; i++) {
try {
@@ -477,9 +467,9 @@ public class LdapBoundConnFactory implements ILdapBoundConnFactory {
log(ILogger.LL_INFO, "disconnecting masterConn");
mMasterConn.disconnect();
} catch (LDAPException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAPCONN_CANNOT_RESET",
- e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_LDAPCONN_CANNOT_RESET",
+ e.toString()));
}
}
mMasterConn = null;
@@ -487,7 +477,7 @@ public class LdapBoundConnFactory implements ILdapBoundConnFactory {
mNumConns = 0;
} else {
CMS.debug(
- "Cannot reset factory: connections not all returned");
+ "Cannot reset factory: connections not all returned");
throw new ELdapException(CMS.getUserMessage("CMS_LDAP_CANNOT_RESET_CONNFAC"));
}
@@ -497,7 +487,7 @@ public class LdapBoundConnFactory implements ILdapBoundConnFactory {
}
/**
- * return ldap connection info
+ * return ldap connection info
*/
public LdapConnInfo getConnInfo() {
return mConnInfo;
@@ -520,17 +510,17 @@ public class LdapBoundConnFactory implements ILdapBoundConnFactory {
private static final long serialVersionUID = 1353616391879078337L;
public BoundConnection(LdapConnInfo connInfo, LdapAuthInfo authInfo)
- throws LDAPException {
+ throws LDAPException {
super(connInfo, authInfo);
}
-
- public BoundConnection(String host, int port, int version,
- LDAPSocketFactory fac,
- String bindDN, String bindPW)
- throws LDAPException {
+
+ public BoundConnection(String host, int port, int version,
+ LDAPSocketFactory fac,
+ String bindDN, String bindPW)
+ throws LDAPException {
super(host, port, version, fac, bindDN, bindPW);
}
-
+
/**
* used only to identify the factory from which this came.
*/
diff --git a/pki/base/common/src/com/netscape/cmscore/ldapconn/LdapBoundConnection.java b/pki/base/common/src/com/netscape/cmscore/ldapconn/LdapBoundConnection.java
index 82e0b315..57d4ddff 100644
--- a/pki/base/common/src/com/netscape/cmscore/ldapconn/LdapBoundConnection.java
+++ b/pki/base/common/src/com/netscape/cmscore/ldapconn/LdapBoundConnection.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.ldapconn;
-
import java.util.Properties;
import netscape.ldap.LDAPConnection;
@@ -29,13 +28,11 @@ import netscape.ldap.LDAPv2;
import com.netscape.certsrv.apps.CMS;
-
/**
- * A LDAP connection that is bound to a server host, port, secure type.
- * and authentication.
- * Makes a LDAP connection and authentication when instantiated.
- * Cannot establish another LDAP connection or authentication after
- * construction. LDAPConnection connect and authentication methods are
+ * A LDAP connection that is bound to a server host, port, secure type. and
+ * authentication. Makes a LDAP connection and authentication when instantiated.
+ * Cannot establish another LDAP connection or authentication after
+ * construction. LDAPConnection connect and authentication methods are
* overridden to prevent this.
*/
public class LdapBoundConnection extends LDAPConnection {
@@ -43,7 +40,7 @@ public class LdapBoundConnection extends LDAPConnection {
*
*/
private static final long serialVersionUID = -2242077674357271559L;
- // LDAPConnection calls authenticate so must set this for first
+ // LDAPConnection calls authenticate so must set this for first
// authenticate call.
private boolean mAuthenticated = false;
@@ -52,28 +49,28 @@ public class LdapBoundConnection extends LDAPConnection {
* connection with Ldap basic bind dn & pw authentication.
*/
public LdapBoundConnection(
- LdapConnInfo connInfo, LdapAuthInfo authInfo)
- throws LDAPException {
+ LdapConnInfo connInfo, LdapAuthInfo authInfo)
+ throws LDAPException {
// this LONG line to satisfy super being the first call. (yuk)
super(
- authInfo.getAuthType() == LdapAuthInfo.LDAP_AUTHTYPE_SSLCLIENTAUTH ?
- new LdapJssSSLSocketFactory(authInfo.getParms()[0]) :
- (connInfo.getSecure() ? new LdapJssSSLSocketFactory() : null));
+ authInfo.getAuthType() == LdapAuthInfo.LDAP_AUTHTYPE_SSLCLIENTAUTH ?
+ new LdapJssSSLSocketFactory(authInfo.getParms()[0]) :
+ (connInfo.getSecure() ? new LdapJssSSLSocketFactory() : null));
- // Set option to automatically follow referrals.
- // Use the same credentials to follow referrals; this is the easiest
- // thing to do without any complicated configuration using
+ // Set option to automatically follow referrals.
+ // Use the same credentials to follow referrals; this is the easiest
+ // thing to do without any complicated configuration using
// different hosts.
// If client auth is used don't have dn and pw to follow referrals.
boolean followReferrals = connInfo.getFollowReferrals();
setOption(LDAPv2.REFERRALS, new Boolean(followReferrals));
- if (followReferrals &&
- authInfo.getAuthType() != LdapAuthInfo.LDAP_AUTHTYPE_SSLCLIENTAUTH) {
- LDAPRebind rebindInfo =
- new ARebindInfo(authInfo.getParms()[0],
- authInfo.getParms()[1]);
+ if (followReferrals &&
+ authInfo.getAuthType() != LdapAuthInfo.LDAP_AUTHTYPE_SSLCLIENTAUTH) {
+ LDAPRebind rebindInfo =
+ new ARebindInfo(authInfo.getParms()[0],
+ authInfo.getParms()[1]);
setOption(LDAPv2.REFERRALS_REBIND_PROC, rebindInfo);
}
@@ -82,19 +79,19 @@ public class LdapBoundConnection extends LDAPConnection {
// will be bound to client auth cert mapped entry.
super.connect(connInfo.getHost(), connInfo.getPort());
CMS.debug(
- "Established LDAP connection with SSL client auth to " +
- connInfo.getHost() + ":" + connInfo.getPort());
- } else { // basic auth
+ "Established LDAP connection with SSL client auth to " +
+ connInfo.getHost() + ":" + connInfo.getPort());
+ } else { // basic auth
String binddn = authInfo.getParms()[0];
String bindpw = authInfo.getParms()[1];
- super.connect(connInfo.getVersion(),
- connInfo.getHost(), connInfo.getPort(), binddn, bindpw);
+ super.connect(connInfo.getVersion(),
+ connInfo.getHost(), connInfo.getPort(), binddn, bindpw);
CMS.debug(
- "Established LDAP connection using basic authentication to" +
- " host " + connInfo.getHost() +
- " port " + connInfo.getPort() +
- " as " + binddn);
+ "Established LDAP connection using basic authentication to" +
+ " host " + connInfo.getHost() +
+ " port " + connInfo.getPort() +
+ " as " + binddn);
}
}
@@ -102,26 +99,26 @@ public class LdapBoundConnection extends LDAPConnection {
* Instantiates a connection to a ldap server, secure or non-secure
* connection with Ldap basic bind dn & pw authentication.
*/
- public LdapBoundConnection(String host, int port, int version,
- LDAPSocketFactory fac,
- String bindDN, String bindPW)
- throws LDAPException {
+ public LdapBoundConnection(String host, int port, int version,
+ LDAPSocketFactory fac,
+ String bindDN, String bindPW)
+ throws LDAPException {
super(fac);
if (bindDN != null) {
- super.connect(version, host, port, bindDN, bindPW);
+ super.connect(version, host, port, bindDN, bindPW);
CMS.debug(
- "Established LDAP connection using basic authentication " +
- " as " + bindDN + " to " + host + ":" + port);
+ "Established LDAP connection using basic authentication " +
+ " as " + bindDN + " to " + host + ":" + port);
} else {
if (fac == null && bindDN == null) {
throw new IllegalArgumentException(
"Ldap bound connection must have authentication info.");
}
// automatically authenticated if it's ssl client auth.
- super.connect(version, host, port, null, null);
+ super.connect(version, host, port, null, null);
CMS.debug(
- "Established LDAP connection using SSL client authentication " +
- "to " + host + ":" + port);
+ "Established LDAP connection using SSL client authentication " +
+ "to " + host + ":" + port);
}
}
@@ -129,13 +126,11 @@ public class LdapBoundConnection extends LDAPConnection {
* Overrides same method in LDAPConnection to do prevent re-authentication.
*/
public void authenticate(int version, String dn, String pw)
- throws LDAPException {
+ throws LDAPException {
/**
- if (mAuthenticated) {
- throw new RuntimeException(
- "this LdapBoundConnection already authenticated: auth(v,dn,pw)");
- }
+ * if (mAuthenticated) { throw new RuntimeException(
+ * "this LdapBoundConnection already authenticated: auth(v,dn,pw)"); }
**/
super.authenticate(version, dn, pw);
mAuthenticated = true;
@@ -145,13 +140,11 @@ public class LdapBoundConnection extends LDAPConnection {
* Overrides same method in LDAPConnection to do prevent re-authentication.
*/
public void authenticate(String dn, String pw)
- throws LDAPException {
+ throws LDAPException {
/**
- if (mAuthenticated) {
- throw new RuntimeException(
- "this LdapBoundConnection already authenticated: auth(dn,pw)");
- }
+ * if (mAuthenticated) { throw new RuntimeException(
+ * "this LdapBoundConnection already authenticated: auth(dn,pw)"); }
**/
super.authenticate(3, dn, pw);
mAuthenticated = true;
@@ -160,15 +153,13 @@ public class LdapBoundConnection extends LDAPConnection {
/**
* Overrides same method in LDAPConnection to do prevent re-authentication.
*/
- public void authenticate(String dn, String mech, String packageName,
- Properties props, Object getter)
- throws LDAPException {
+ public void authenticate(String dn, String mech, String packageName,
+ Properties props, Object getter)
+ throws LDAPException {
/**
- if (mAuthenticated) {
- throw new RuntimeException(
- "this LdapBoundConnection already authenticated: auth(mech)");
- }
+ * if (mAuthenticated) { throw new RuntimeException(
+ * "this LdapBoundConnection already authenticated: auth(mech)"); }
**/
super.authenticate(dn, mech, packageName, props, getter);
mAuthenticated = true;
@@ -177,15 +168,13 @@ public class LdapBoundConnection extends LDAPConnection {
/**
* Overrides same method in LDAPConnection to do prevent re-authentication.
*/
- public void authenticate(String dn, String mechs[], String packageName,
- Properties props, Object getter)
- throws LDAPException {
+ public void authenticate(String dn, String mechs[], String packageName,
+ Properties props, Object getter)
+ throws LDAPException {
/**
- if (mAuthenticated) {
- throw new RuntimeException(
- "this LdapBoundConnection is already authenticated: auth(mechs)");
- }
+ * if (mAuthenticated) { throw new RuntimeException(
+ * "this LdapBoundConnection is already authenticated: auth(mechs)"); }
**/
super.authenticate(dn, mechs, packageName, props, getter);
mAuthenticated = true;
@@ -202,14 +191,13 @@ public class LdapBoundConnection extends LDAPConnection {
/**
* overrides parent's connect to prevent re-connect.
*/
- public void connect(int version, String host, int port,
- String dn, String pw) throws LDAPException {
+ public void connect(int version, String host, int port,
+ String dn, String pw) throws LDAPException {
throw new RuntimeException(
"this LdapBoundConnection is already connected: conn(version,h,p)");
}
}
-
class ARebindInfo implements LDAPRebind {
private LDAPRebindAuth mRebindAuthInfo = null;
diff --git a/pki/base/common/src/com/netscape/cmscore/ldapconn/LdapConnInfo.java b/pki/base/common/src/com/netscape/cmscore/ldapconn/LdapConnInfo.java
index 70361f87..ad8869ac 100644
--- a/pki/base/common/src/com/netscape/cmscore/ldapconn/LdapConnInfo.java
+++ b/pki/base/common/src/com/netscape/cmscore/ldapconn/LdapConnInfo.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.ldapconn;
-
import netscape.ldap.LDAPv2;
import com.netscape.certsrv.apps.CMS;
@@ -27,10 +26,9 @@ import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.ldap.ELdapException;
import com.netscape.certsrv.ldap.ILdapConnInfo;
-
/**
- * class for reading ldap connection from the config store.
- * ldap connection info: host, port, secure connection
+ * class for reading ldap connection from the config store. ldap connection
+ * info: host, port, secure connection
*/
public class LdapConnInfo implements ILdapConnInfo {
@@ -48,8 +46,7 @@ public class LdapConnInfo implements ILdapConnInfo {
}
/**
- * initializes an instance from a config store.
- * required parms: host, port
+ * initializes an instance from a config store. required parms: host, port
* optional parms: secure connection, authentication method & info.
*/
public void init(IConfigStore config) throws EBaseException, ELdapException {
@@ -58,8 +55,8 @@ public class LdapConnInfo implements ILdapConnInfo {
String version = (String) config.get(PROP_PROTOCOL);
if (version != null && version.equals("")) {
- // provide a default when this field is blank from the
- // configuration.
+ // provide a default when this field is blank from the
+ // configuration.
mVersion = LDAP_VERSION_3;
} else {
mVersion = config.getInteger(PROP_PROTOCOL, LDAP_VERSION_3);
@@ -75,43 +72,43 @@ public class LdapConnInfo implements ILdapConnInfo {
throw new EBaseException(
CMS.getUserMessage("CMS_BASE_INVALID_PROPERTY", PROP_PORT));
}
- mSecure = config.getBoolean(PROP_SECURE, false);
- mFollowReferrals = config.getBoolean(PROP_FOLLOW_REFERRALS, true);
+ mSecure = config.getBoolean(PROP_SECURE, false);
+ mFollowReferrals = config.getBoolean(PROP_FOLLOW_REFERRALS, true);
}
public LdapConnInfo(String host, int port, boolean secure) {
- mHost = host;
- mPort = port;
+ mHost = host;
+ mPort = port;
mSecure = secure;
if (mHost == null || mPort <= 0) {
- // XXX log something here
+ // XXX log something here
throw new IllegalArgumentException("LDAP host or port is null");
}
}
public LdapConnInfo(String host, int port) {
- mHost = host;
- mPort = port;
+ mHost = host;
+ mPort = port;
if (mHost == null || mPort <= 0) {
- // XXX log something here
+ // XXX log something here
throw new IllegalArgumentException("LDAP host or port is null");
}
}
- public String getHost() {
- return mHost;
+ public String getHost() {
+ return mHost;
}
- public int getPort() {
- return mPort;
+ public int getPort() {
+ return mPort;
}
- public int getVersion() {
- return mVersion;
+ public int getVersion() {
+ return mVersion;
}
- public boolean getSecure() {
- return mSecure;
+ public boolean getSecure() {
+ return mSecure;
}
public boolean getFollowReferrals() {
diff --git a/pki/base/common/src/com/netscape/cmscore/ldapconn/LdapJssSSLSocketFactory.java b/pki/base/common/src/com/netscape/cmscore/ldapconn/LdapJssSSLSocketFactory.java
index 8aa59e30..bbc208d3 100644
--- a/pki/base/common/src/com/netscape/cmscore/ldapconn/LdapJssSSLSocketFactory.java
+++ b/pki/base/common/src/com/netscape/cmscore/ldapconn/LdapJssSSLSocketFactory.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.ldapconn;
-
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
@@ -32,9 +31,9 @@ import org.mozilla.jss.ssl.SSLSocket;
import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.logging.ILogger;
-
/**
* Uses HCL ssl socket.
+ *
* @author Lily Hsiao lhsiao@netscape.com
*/
public class LdapJssSSLSocketFactory implements LDAPSSLSocketFactoryExt {
@@ -56,7 +55,7 @@ public class LdapJssSSLSocketFactory implements LDAPSSLSocketFactoryExt {
s = new SSLSocket(host, port);
s.setUseClientMode(true);
s.enableSSL2(false);
- //TODO Do we really want to set the default each time?
+ // TODO Do we really want to set the default each time?
SSLSocket.enableSSL2Default(false);
s.enableV2CompatibleHello(false);
@@ -68,14 +67,14 @@ public class LdapJssSSLSocketFactory implements LDAPSSLSocketFactoryExt {
if (mClientAuthCertNickname != null) {
mClientAuth = true;
CMS.debug(
- "LdapJssSSLSocket set client auth cert nickname" +
- mClientAuthCertNickname);
+ "LdapJssSSLSocket set client auth cert nickname" +
+ mClientAuthCertNickname);
s.setClientCertNickname(mClientAuthCertNickname);
}
s.forceHandshake();
} catch (UnknownHostException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_LDAPCONN_UNKNOWN_HOST"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_LDAPCONN_UNKNOWN_HOST"));
throw new LDAPException(
"Cannot Create JSS SSL Socket - Unknown host");
} catch (IOException e) {
@@ -102,10 +101,9 @@ public class LdapJssSSLSocketFactory implements LDAPSSLSocketFactoryExt {
public ClientHandshakeCB(Object sc) {
this.sc = sc;
}
-
+
public void handshakeCompleted(SSLHandshakeCompletedEvent event) {
CMS.debug("SSL handshake happened");
}
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/listeners/ListenerPlugin.java b/pki/base/common/src/com/netscape/cmscore/listeners/ListenerPlugin.java
index 181ea34b..7db8f2e1 100644
--- a/pki/base/common/src/com/netscape/cmscore/listeners/ListenerPlugin.java
+++ b/pki/base/common/src/com/netscape/cmscore/listeners/ListenerPlugin.java
@@ -17,13 +17,10 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.listeners;
-
-
-
/**
* This class represents a registered listener plugin.
* <P>
- *
+ *
* @author stevep
* @version $Revision$, $Date$
*/
@@ -34,16 +31,18 @@ public class ListenerPlugin {
/**
* Constructs a Listener plugin.
+ *
* @param id listener implementation name
* @param classPath class path
*/
public ListenerPlugin(String id, String classPath) {
- // if (id == null || classPath == null)
- // throw new AssertionException("Listener id or classpath can't be null");
+ // if (id == null || classPath == null)
+ // throw new
+ // AssertionException("Listener id or classpath can't be null");
mId = id;
mClassPath = classPath;
}
-
+
public String getId() {
return mId;
}
diff --git a/pki/base/common/src/com/netscape/cmscore/logging/AuditEventFactory.java b/pki/base/common/src/com/netscape/cmscore/logging/AuditEventFactory.java
index 46b42f04..438b3abb 100644
--- a/pki/base/common/src/com/netscape/cmscore/logging/AuditEventFactory.java
+++ b/pki/base/common/src/com/netscape/cmscore/logging/AuditEventFactory.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.logging;
-
import java.util.Properties;
import com.netscape.certsrv.logging.AuditEvent;
@@ -26,12 +25,11 @@ import com.netscape.certsrv.logging.ILogEvent;
import com.netscape.certsrv.logging.ILogEventFactory;
import com.netscape.certsrv.logging.ILogger;
-
/**
* A log event object for handling audit messages
* <P>
- *
- * @author mikep
+ *
+ * @author mikep
* @author mzhao
* @version $Revision$, $Date$
*/
@@ -60,7 +58,7 @@ public class AuditEventFactory implements ILogEventFactory {
* @param params the parameters in the detail log message
*/
public ILogEvent create(int evtClass, Properties prop, int source,
- int level, boolean multiline, String msg, Object params[]) {
+ int level, boolean multiline, String msg, Object params[]) {
if (evtClass != ILogger.EV_AUDIT)
return null;
AuditEvent event = new AuditEvent(msg, params);
@@ -74,8 +72,8 @@ public class AuditEventFactory implements ILogEventFactory {
/**
* Set the resource bundle of the log event.
- *
- * @param prop the properties
+ *
+ * @param prop the properties
* @param event the log event
*/
protected void setProperties(Properties prop, IBundleLogEvent event) {
@@ -92,7 +90,7 @@ public class AuditEventFactory implements ILogEventFactory {
/**
* Releases an log event.
- *
+ *
* @param e the log event
*/
public void release(ILogEvent e) {
diff --git a/pki/base/common/src/com/netscape/cmscore/logging/AuditFormat.java b/pki/base/common/src/com/netscape/cmscore/logging/AuditFormat.java
index 7d7f817f..60b53236 100644
--- a/pki/base/common/src/com/netscape/cmscore/logging/AuditFormat.java
+++ b/pki/base/common/src/com/netscape/cmscore/logging/AuditFormat.java
@@ -17,14 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.logging;
-
import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.request.IRequest;
-
/**
* Define audit log message format
- *
+ *
* @author mzhao
* @version $Revision$, $Date$
*/
@@ -43,68 +41,64 @@ public class AuditFormat {
/**
* initiative: the event is from agent
*/
- public static final String FROMAGENT = "fromAgent";
+ public static final String FROMAGENT = "fromAgent";
/**
* initiative: the event is from router
*/
- public static final String FROMROUTER = "fromRouter";
+ public static final String FROMROUTER = "fromRouter";
/**
* initiative: the event is from remote authority
*/
public static final String FROMRA = "fromRemoteAuthority";
-
+
/**
* authentication module: no Authentication manager
*/
public static final String NOAUTH = "noAuthManager";
// for ProcessCertReq.java ,kra
- /* 0: request type
- 1: request ID
- 2: initiative
- 3: auth module
- 4: status
- 5: cert dn
- 6: other info. eg cert serial number, violation policies
+ /*
+ * 0: request type 1: request ID 2: initiative 3: auth module 4: status 5:
+ * cert dn 6: other info. eg cert serial number, violation policies
*/
- public static final String FORMAT =
- "{0} reqID {1} {2} authenticated by {3} is {4} DN requested: {5} {6}";
- public static final String NODNFORMAT =
- "{0} reqID {1} {2} authenticated by {3} is {4}";
+ public static final String FORMAT =
+ "{0} reqID {1} {2} authenticated by {3} is {4} DN requested: {5} {6}";
+ public static final String NODNFORMAT =
+ "{0} reqID {1} {2} authenticated by {3} is {4}";
- public static final String ENROLLMENTFORMAT =
- IRequest.ENROLLMENT_REQUEST + " reqID {0} {1} authenticated by {2} is {3}. DN requested: {4} {5}";
- public static final String RENEWALFORMAT =
- IRequest.RENEWAL_REQUEST + " reqID {0} {1} authenticated by {2} is {3}. DN requested: {4} old serial number: 0x{5} {6}";
- public static final String REVOCATIONFORMAT =
- IRequest.REVOCATION_REQUEST + " reqID {0} {1} authenticated by {2} is {3}. DN requested: {4} serial number: 0x{5} revocation reason: {6} {7}";
+ public static final String ENROLLMENTFORMAT =
+ IRequest.ENROLLMENT_REQUEST + " reqID {0} {1} authenticated by {2} is {3}. DN requested: {4} {5}";
+ public static final String RENEWALFORMAT =
+ IRequest.RENEWAL_REQUEST + " reqID {0} {1} authenticated by {2} is {3}. DN requested: {4} old serial number: 0x{5} {6}";
+ public static final String REVOCATIONFORMAT =
+ IRequest.REVOCATION_REQUEST + " reqID {0} {1} authenticated by {2} is {3}. DN requested: {4} serial number: 0x{5} revocation reason: {6} {7}";
// 1: fromAgent AgentID: xxx authenticated by xxx
- public static final String DOREVOKEFORMAT =
- IRequest.REVOCATION_REQUEST + " reqID {0} {1} is {2}. DN requested: {3} serial number: 0x{4} revocation reason: {5}";
+ public static final String DOREVOKEFORMAT =
+ IRequest.REVOCATION_REQUEST + " reqID {0} {1} is {2}. DN requested: {3} serial number: 0x{4} revocation reason: {5}";
// 1: fromAgent AgentID: xxx authenticated by xxx
- public static final String DOUNREVOKEFORMAT =
- IRequest.UNREVOCATION_REQUEST + " reqID {0} {1} is {2}. DN requested: {3} serial number: 0x{4}";
+ public static final String DOUNREVOKEFORMAT =
+ IRequest.UNREVOCATION_REQUEST + " reqID {0} {1} is {2}. DN requested: {3} serial number: 0x{4}";
// 0:initiative
- public static final String CRLUPDATEFORMAT =
- "CRLUpdate request {0} authenticated by {1} is {2}. Id: {3}\ncrl Number: {4} last update time: {5} next update time: {6} number of entries in the CRL: {7}";
+ public static final String CRLUPDATEFORMAT =
+ "CRLUpdate request {0} authenticated by {1} is {2}. Id: {3}\ncrl Number: {4} last update time: {5} next update time: {6} number of entries in the CRL: {7}";
// audit user/group
public static final String ADDUSERFORMAT =
- "Admin UID: {0} added User UID: {1}";
+ "Admin UID: {0} added User UID: {1}";
public static final String REMOVEUSERFORMAT =
- "Admin UID: {0} removed User UID: {1} ";
+ "Admin UID: {0} removed User UID: {1} ";
public static final String MODIFYUSERFORMAT =
- "Admin UID: {0} modified User UID: {1}";
+ "Admin UID: {0} modified User UID: {1}";
public static final String ADDUSERCERTFORMAT =
- "Admin UID: {0} added cert for User UID: {1}. cert DN: {2} serial number: 0x{3}";
+ "Admin UID: {0} added cert for User UID: {1}. cert DN: {2} serial number: 0x{3}";
public static final String REMOVEUSERCERTFORMAT =
- "Admin UID: {0} removed cert of User UID: {1}. cert DN: {2} serial number: 0x{3}";
+ "Admin UID: {0} removed cert of User UID: {1}. cert DN: {2} serial number: 0x{3}";
public static final String ADDUSERGROUPFORMAT =
- "Admin UID: {0} added User UID: {1} to group: {2}";
+ "Admin UID: {0} added User UID: {1} to group: {2}";
public static final String REMOVEUSERGROUPFORMAT =
- "Admin UID: {0} removed User UID: {1} from group: {2}";
+ "Admin UID: {0} removed User UID: {1} from group: {2}";
}
diff --git a/pki/base/common/src/com/netscape/cmscore/logging/LogQueue.java b/pki/base/common/src/com/netscape/cmscore/logging/LogQueue.java
index faddc44d..2ddc57ad 100644
--- a/pki/base/common/src/com/netscape/cmscore/logging/LogQueue.java
+++ b/pki/base/common/src/com/netscape/cmscore/logging/LogQueue.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.logging;
-
import java.util.Vector;
import com.netscape.certsrv.logging.ELogException;
@@ -25,9 +24,8 @@ import com.netscape.certsrv.logging.ILogEvent;
import com.netscape.certsrv.logging.ILogEventListener;
import com.netscape.certsrv.logging.ILogQueue;
-
/**
- * A class represents a log queue.
+ * A class represents a log queue.
* <P>
*
* @author mzhao
@@ -51,11 +49,11 @@ public class LogQueue implements ILogQueue {
/**
* Initializes the log queue.
* <P>
- *
+ *
*/
public void init() {
mListeners = new Vector();
-
+
}
/**
@@ -63,7 +61,7 @@ public class LogQueue implements ILogQueue {
* <P>
*/
public void shutdown() {
- if (mListeners == null)
+ if (mListeners == null)
return;
for (int i = 0; i < mListeners.size(); i++) {
((ILogEventListener) mListeners.elementAt(i)).shutdown();
@@ -73,18 +71,18 @@ public class LogQueue implements ILogQueue {
/**
* Adds an event listener.
- *
+ *
* @param listener the log event listener
*/
public void addLogEventListener(ILogEventListener listener) {
- //Make sure we don't have duplicated listener
+ // Make sure we don't have duplicated listener
if (!mListeners.contains(listener))
mListeners.addElement(listener);
}
/**
* Removes an event listener.
- *
+ *
* @param listener the log event listener
*/
public void removeLogEventListener(ILogEventListener listener) {
@@ -93,30 +91,30 @@ public class LogQueue implements ILogQueue {
/**
* Logs an event, and notifies logger to reuse the event.
- *
+ *
* @param event the log event
*/
public void log(ILogEvent event) {
if (mListeners == null)
- return;
+ return;
for (int i = 0; i < mListeners.size(); i++) {
try {
((ILogEventListener) mListeners.elementAt(i)).log(event);
} catch (ELogException e) {
- // Raidzilla Bug #57592: Don't display potentially
- // incorrect log message.
- // ConsoleError.send(new SystemEvent(CMS.getUserMessage("CMS_LOG_EVENT_FAILED",
- // event.getEventType(), e.toString())));
-
- // Don't do this again.
- removeLogEventListener((ILogEventListener)
- mListeners.elementAt(i));
+ // Raidzilla Bug #57592: Don't display potentially
+ // incorrect log message.
+ // ConsoleError.send(new
+ // SystemEvent(CMS.getUserMessage("CMS_LOG_EVENT_FAILED",
+ // event.getEventType(), e.toString())));
+
+ // Don't do this again.
+ removeLogEventListener((ILogEventListener) mListeners.elementAt(i));
}
}
}
/**
- * Flushes the log buffers (if any)
+ * Flushes the log buffers (if any)
*/
public void flush() {
for (int i = 0; i < mListeners.size(); i++) {
@@ -124,4 +122,3 @@ public class LogQueue implements ILogQueue {
}
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/logging/LogSubsystem.java b/pki/base/common/src/com/netscape/cmscore/logging/LogSubsystem.java
index 05e4e91f..a8bc67c0 100644
--- a/pki/base/common/src/com/netscape/cmscore/logging/LogSubsystem.java
+++ b/pki/base/common/src/com/netscape/cmscore/logging/LogSubsystem.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.logging;
-
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
@@ -33,7 +32,6 @@ import com.netscape.certsrv.logging.ILogSubsystem;
import com.netscape.certsrv.logging.LogPlugin;
import com.netscape.cmscore.util.Debug;
-
/**
* A class represents a log subsystem.
* <P>
@@ -77,12 +75,12 @@ public class LogSubsystem implements ILogSubsystem {
/**
* Initializes the log subsystem.
* <P>
- *
+ *
* @param owner owner of this subsystem
* @param config configuration store
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mConfig = config;
mLogQueue.init();
@@ -100,18 +98,18 @@ public class LogSubsystem implements ILogSubsystem {
if (Debug.ON)
Debug.trace("loaded logger plugins");
- // load log instances
+ // load log instances
c = config.getSubStore(PROP_INSTANCE);
Enumeration<String> instances = c.getSubStoreNames();
while (instances.hasMoreElements()) {
String insName = (String) instances.nextElement();
- String implName = c.getString(insName + "." +
+ String implName = c.getString(insName + "." +
PROP_PLUGIN);
LogPlugin plugin =
- (LogPlugin) mLogPlugins.get(implName);
+ (LogPlugin) mLogPlugins.get(implName);
- if (plugin == null) {
+ if (plugin == null) {
throw new EBaseException(implName);
}
String className = plugin.getClassPath();
@@ -121,8 +119,8 @@ public class LogSubsystem implements ILogSubsystem {
try {
logInst = (ILogEventListener)
Class.forName(className).newInstance();
- IConfigStore pConfig =
- c.getSubStore(insName);
+ IConfigStore pConfig =
+ c.getSubStore(insName);
logInst.init(this, pConfig);
// for view from console
@@ -165,7 +163,7 @@ public class LogSubsystem implements ILogSubsystem {
Debug.trace("about to call inst=" + instName + " in LogSubsystem.startup()");
ILogEventListener inst = (ILogEventListener)
- mLogInsts.get(instName);
+ mLogInsts.get(instName);
inst.startup();
}
@@ -182,7 +180,7 @@ public class LogSubsystem implements ILogSubsystem {
/**
* Returns the root configuration storage of this system.
* <P>
- *
+ *
* @return configuration store of this subsystem
*/
public IConfigStore getConfigStore() {
@@ -232,12 +230,12 @@ public class LogSubsystem implements ILogSubsystem {
ELogException {
// is this a registered implname?
LogPlugin plugin = (LogPlugin)
- mLogPlugins.get(implName);
+ mLogPlugins.get(implName);
if (plugin == null) {
throw new ELogException(implName);
}
-
+
// a temporary instance
ILogEventListener LogInst = null;
String className = plugin.getClassPath();
@@ -272,4 +270,3 @@ public class LogSubsystem implements ILogSubsystem {
return v;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/logging/Logger.java b/pki/base/common/src/com/netscape/cmscore/logging/Logger.java
index 3c97023a..6682fd32 100644
--- a/pki/base/common/src/com/netscape/cmscore/logging/Logger.java
+++ b/pki/base/common/src/com/netscape/cmscore/logging/Logger.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.logging;
-
import java.util.Hashtable;
import java.util.Properties;
@@ -26,13 +25,11 @@ import com.netscape.certsrv.logging.ILogEventFactory;
import com.netscape.certsrv.logging.ILogQueue;
import com.netscape.certsrv.logging.ILogger;
-
/**
- * A class represents certificate server logger
- * implementation.
+ * A class represents certificate server logger implementation.
* <P>
- *
- * @author thomask
+ *
+ * @author thomask
* @author mzhao
* @version $Revision$, $Date$
*/
@@ -43,8 +40,8 @@ public class Logger implements ILogger {
protected Hashtable mFactories = new Hashtable();
/**
- * Constructs a generic logger, and registers a list
- * of resident event factories.
+ * Constructs a generic logger, and registers a list of resident event
+ * factories.
*/
public Logger() {
mLogQueue = LogSubsystem.getLogQueue();
@@ -63,7 +60,7 @@ public class Logger implements ILogger {
}
/**
- * Retrieves the associated log queue.
+ * Retrieves the associated log queue.
*/
public ILogQueue getLogQueue() {
return mLogQueue;
@@ -71,17 +68,19 @@ public class Logger implements ILogger {
/**
* Registers log factory.
- * @param evtClass the event class name: ILogger.EV_SYSTEM or ILogger.EV_AUDIT
+ *
+ * @param evtClass the event class name: ILogger.EV_SYSTEM or
+ * ILogger.EV_AUDIT
* @param f the event factory name
*/
public void register(int evtClass, ILogEventFactory f) {
mFactories.put(Integer.toString(evtClass), f);
}
- //************** default level ****************
+ // ************** default level ****************
/**
* Logs an event using default log level: ILogger.LL_INFO
- *
+ *
* @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM.
* @param source the source of the log event
* @param msg the one line detail message to be logged
@@ -92,7 +91,7 @@ public class Logger implements ILogger {
/**
* Logs an event using default log level: ILogger.LL_INFO
- *
+ *
* @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM.
* @param props the resource bundle used for the detailed message
* @param source the source of the log event
@@ -102,11 +101,11 @@ public class Logger implements ILogger {
log(evtClass, props, source, ILogger.LL_INFO, msg, null);
}
- //************** no param ****************
+ // ************** no param ****************
/**
* Logs an event to the log queue.
- *
+ *
* @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM.
* @param source the source of the log event
* @param level the level of the log event
@@ -118,7 +117,7 @@ public class Logger implements ILogger {
/**
* Logs an event to the log queue.
- *
+ *
* @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM.
* @param props the resource bundle used for the detailed message
* @param source the source of the log event
@@ -129,11 +128,11 @@ public class Logger implements ILogger {
log(evtClass, props, source, level, msg, null);
}
- //********************* one param **********************
+ // ********************* one param **********************
/**
* Logs an event to the log queue.
- *
+ *
* @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM.
* @param props the resource bundle used for the detailed message
* @param source the source of the log event
@@ -146,7 +145,7 @@ public class Logger implements ILogger {
/**
* Logs an event using default log level: ILogger.LL_INFO
- *
+ *
* @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM.
* @param props the resource bundle used for the detailed message
* @param source the source of the log event
@@ -159,7 +158,7 @@ public class Logger implements ILogger {
/**
* Logs an event to the log queue.
- *
+ *
* @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM.
* @param props the resource bundle used for the detailed message
* @param source the source of the log event
@@ -168,18 +167,18 @@ public class Logger implements ILogger {
* @param param the parameter in the detail message
*/
public void log(int evtClass, Properties props, int source, int level, String msg,
- Object param) {
+ Object param) {
Object o[] = new Object[1];
o[0] = param;
log(evtClass, props, source, level, msg, o);
}
- //******************* multiple param **************************
+ // ******************* multiple param **************************
/**
* Logs an event to the log queue.
- *
+ *
* @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM.
* @param source the source of the log event
* @param level the level of the log event
@@ -187,14 +186,14 @@ public class Logger implements ILogger {
* @param params the parameters in the detail message
*/
public void log(int evtClass, int source, int level, String msg,
- Object params[]) {
+ Object params[]) {
log(evtClass, null, source, level, msg, params);
}
- //*************** the real implementation *****************
+ // *************** the real implementation *****************
/**
* Logs an event to the log queue.
- *
+ *
* @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM.
* @param props the resource bundle used for the detailed message
* @param source the source of the log event
@@ -203,19 +202,20 @@ public class Logger implements ILogger {
* @param params the parameters in the detail message
*/
public void log(int evtClass, Properties prop, int source, int level, String msg,
- Object params[]) {
+ Object params[]) {
mLogQueue.log(create(evtClass, prop, source, level, msg, params, ILogger.L_SINGLELINE));
}
- //******************** multiline log *************************
- //************** default level ****************
+ // ******************** multiline log *************************
+ // ************** default level ****************
/**
* Logs an event using default log level: ILogger.LL_INFO
- *
+ *
* @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM.
* @param source the source of the log event
* @param msg the one line detail message to be logged
- * @param multiline true if the message has more than one line, otherwise false
+ * @param multiline true if the message has more than one line, otherwise
+ * false
*/
public void log(int evtClass, int source, String msg, boolean multiline) {
log(evtClass, null, source, ILogger.LL_INFO, msg, null, multiline);
@@ -223,27 +223,29 @@ public class Logger implements ILogger {
/**
* Logs an event using default log level: ILogger.LL_INFO
- *
+ *
* @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM.
* @param props the resource bundle used for the detailed message
* @param source the source of the log event
* @param msg the one line detail message to be logged
- * @param multiline true if the message has more than one line, otherwise false
+ * @param multiline true if the message has more than one line, otherwise
+ * false
*/
public void log(int evtClass, Properties props, int source, String msg, boolean multiline) {
log(evtClass, props, source, ILogger.LL_INFO, msg, null, multiline);
}
- //************** no param ****************
+ // ************** no param ****************
/**
* Logs an event to the log queue.
- *
+ *
* @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM.
* @param source the source of the log event
* @param level the level of the log event
* @param msg the one line detail message to be logged
- * @param multiline true if the message has more than one line, otherwise false
+ * @param multiline true if the message has more than one line, otherwise
+ * false
*/
public void log(int evtClass, int source, int level, String msg, boolean multiline) {
log(evtClass, null, source, level, msg, null, multiline);
@@ -251,29 +253,31 @@ public class Logger implements ILogger {
/**
* Logs an event to the log queue.
- *
+ *
* @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM.
* @param props the resource bundle used for the detailed message
* @param source the source of the log event
* @param level the level of the log event
* @param msg the one line detail message to be logged
- * @param multiline true if the message has more than one line, otherwise false
+ * @param multiline true if the message has more than one line, otherwise
+ * false
*/
public void log(int evtClass, Properties props, int source, int level, String msg, boolean multiline) {
log(evtClass, props, source, level, msg, null, multiline);
}
- //********************* one param **********************
+ // ********************* one param **********************
/**
* Logs an event to the log queue.
- *
+ *
* @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM.
* @param props the resource bundle used for the detailed message
* @param source the source of the log event
* @param msg the one line detail message to be logged
* @param param the parameter in the detail message
- * @param multiline true if the message has more than one line, otherwise false
+ * @param multiline true if the message has more than one line, otherwise
+ * false
*/
public void log(int evtClass, int source, int level, String msg, Object param, boolean multiline) {
log(evtClass, null, source, level, msg, param, multiline);
@@ -281,13 +285,14 @@ public class Logger implements ILogger {
/**
* Logs an event using default log level: ILogger.LL_INFO
- *
+ *
* @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM.
* @param props the resource bundle used for the detailed message
* @param source the source of the log event
* @param msg the one line detail message to be logged
* @param param the parameter in the detail message
- * @param multiline true if the message has more than one line, otherwise false
+ * @param multiline true if the message has more than one line, otherwise
+ * false
*/
public void log(int evtClass, Properties props, int source, String msg, Object param, boolean multiline) {
log(evtClass, props, source, ILogger.LL_INFO, msg, param, multiline);
@@ -295,67 +300,68 @@ public class Logger implements ILogger {
/**
* Logs an event to the log queue.
- *
+ *
* @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM.
* @param props the resource bundle used for the detailed message
* @param source the source of the log event
* @param level the level of the log event
* @param msg the one line detail message to be logged
* @param param the parameter in the detail message
- * @param multiline true if the message has more than one line, otherwise false
+ * @param multiline true if the message has more than one line, otherwise
+ * false
*/
public void log(int evtClass, Properties props, int source, int level, String msg,
- Object param, boolean multiline) {
+ Object param, boolean multiline) {
Object o[] = new Object[1];
o[0] = param;
log(evtClass, props, source, level, msg, o, multiline);
}
- //******************* multiple param **************************
+ // ******************* multiple param **************************
/**
* Logs an event to the log queue.
- *
+ *
* @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM.
* @param source the source of the log event
* @param level the level of the log event
* @param msg the one line detail message to be logged
* @param params the parameters in the detail message
- * @param multiline true if the message has more than one line, otherwise false
+ * @param multiline true if the message has more than one line, otherwise
+ * false
*/
public void log(int evtClass, int source, int level, String msg,
- Object params[], boolean multiline) {
+ Object params[], boolean multiline) {
log(evtClass, null, source, level, msg, params, multiline);
}
- //*************** the real implementation *****************
+ // *************** the real implementation *****************
/**
* Logs an event to the log queue.
- *
+ *
* @param evtClass What kind of event it is: EV_AUDIT or EV_SYSTEM.
* @param props the resource bundle used for the detailed message
* @param source the source of the log event
* @param level the level of the log event
* @param msg the one line detail message to be logged
* @param params the parameters in the detail message
- * @param multiline true if the message has more than one line, otherwise false
+ * @param multiline true if the message has more than one line, otherwise
+ * false
*/
public void log(int evtClass, Properties prop, int source, int level, String msg,
- Object params[], boolean multiline) {
+ Object params[], boolean multiline) {
mLogQueue.log(create(evtClass, prop, source, level, msg, params, multiline));
}
- //******************** end multiline log *************************
-
+ // ******************** end multiline log *************************
/**
- * Creates generic log event. If required, we can recycle
- * events here.
+ * Creates generic log event. If required, we can recycle events here.
*/
- //XXXXXXXXXXX prop is out dated!!!! XXXXXXXXXXXXXXX
+ // XXXXXXXXXXX prop is out dated!!!! XXXXXXXXXXXXXXX
public ILogEvent create(int evtClass, Properties prop, int source, int level,
- String msg, Object params[], boolean multiline) {
+ String msg, Object params[], boolean multiline) {
ILogEventFactory f = (ILogEventFactory) mFactories.get(
Integer.toString(evtClass));
@@ -365,8 +371,9 @@ public class Logger implements ILogger {
}
/**
- * Notifies logger to reuse the event. This framework
- * opens up possibility to reuse event.
+ * Notifies logger to reuse the event. This framework opens up possibility
+ * to reuse event.
+ *
* @param event a log event
*/
public void release(ILogEvent event) {
diff --git a/pki/base/common/src/com/netscape/cmscore/logging/SignedAuditEventFactory.java b/pki/base/common/src/com/netscape/cmscore/logging/SignedAuditEventFactory.java
index 970516c1..48570cad 100644
--- a/pki/base/common/src/com/netscape/cmscore/logging/SignedAuditEventFactory.java
+++ b/pki/base/common/src/com/netscape/cmscore/logging/SignedAuditEventFactory.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.logging;
-
import java.util.Properties;
import com.netscape.certsrv.logging.IBundleLogEvent;
@@ -27,12 +26,11 @@ import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.logging.SignedAuditEvent;
import com.netscape.cmscore.util.Debug;
-
/**
* A log event object for handling system messages
* <P>
- *
- * @author mikep
+ *
+ * @author mikep
* @author mzhao
* @author cfu
* @version $Revision$, $Date$
@@ -52,7 +50,7 @@ public class SignedAuditEventFactory implements ILogEventFactory {
/**
* Creates an log event.
- *
+ *
* @param evtClass the event type
* @param prop the resource bundle
* @param source the subsystem ID who creates the log event
@@ -60,10 +58,9 @@ public class SignedAuditEventFactory implements ILogEventFactory {
* @param multiline the log message has more than one line or not
* @param msg the detail message of the log
* @param params the parameters in the detail log message
-
*/
public ILogEvent create(int evtClass, Properties prop, int source,
- int level, boolean multiline, String msg, Object params[]) {
+ int level, boolean multiline, String msg, Object params[]) {
if (evtClass != ILogger.EV_SIGNED_AUDIT)
return null;
@@ -101,8 +98,8 @@ public class SignedAuditEventFactory implements ILogEventFactory {
/**
* Set the resource bundle of the log event.
- *
- * @param prop the properties
+ *
+ * @param prop the properties
* @param event the log event
*/
protected void setProperties(Properties prop, IBundleLogEvent event) {
@@ -119,7 +116,7 @@ public class SignedAuditEventFactory implements ILogEventFactory {
/**
* Releases an log event.
- *
+ *
* @param e the log event
*/
public void release(ILogEvent e) {
diff --git a/pki/base/common/src/com/netscape/cmscore/logging/SignedAuditLogger.java b/pki/base/common/src/com/netscape/cmscore/logging/SignedAuditLogger.java
index 013447ce..34af748d 100644
--- a/pki/base/common/src/com/netscape/cmscore/logging/SignedAuditLogger.java
+++ b/pki/base/common/src/com/netscape/cmscore/logging/SignedAuditLogger.java
@@ -17,23 +17,19 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.logging;
-
-
-
/**
- * A class represents certificate server logger
- * implementation.
+ * A class represents certificate server logger implementation.
* <P>
- *
- * @author thomask
+ *
+ * @author thomask
* @author mzhao
* @version $Revision$, $Date$
*/
public class SignedAuditLogger extends Logger {
/**
- * Constructs a generic logger, and registers a list
- * of resident event factories.
+ * Constructs a generic logger, and registers a list of resident event
+ * factories.
*/
public SignedAuditLogger() {
super();
diff --git a/pki/base/common/src/com/netscape/cmscore/logging/SystemEventFactory.java b/pki/base/common/src/com/netscape/cmscore/logging/SystemEventFactory.java
index 7bef282b..dfe25f03 100644
--- a/pki/base/common/src/com/netscape/cmscore/logging/SystemEventFactory.java
+++ b/pki/base/common/src/com/netscape/cmscore/logging/SystemEventFactory.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.logging;
-
import java.util.Properties;
import com.netscape.certsrv.logging.IBundleLogEvent;
@@ -26,12 +25,11 @@ import com.netscape.certsrv.logging.ILogEventFactory;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.logging.SystemEvent;
-
/**
* A log event object for handling system messages
* <P>
- *
- * @author mikep
+ *
+ * @author mikep
* @author mzhao
* @version $Revision$, $Date$
*/
@@ -50,7 +48,7 @@ public class SystemEventFactory implements ILogEventFactory {
/**
* Creates an log event.
- *
+ *
* @param evtClass the event type
* @param prop the resource bundle
* @param source the subsystem ID who creates the log event
@@ -58,10 +56,9 @@ public class SystemEventFactory implements ILogEventFactory {
* @param multiline the log message has more than one line or not
* @param msg the detail message of the log
* @param params the parameters in the detail log message
-
*/
public ILogEvent create(int evtClass, Properties prop, int source,
- int level, boolean multiline, String msg, Object params[]) {
+ int level, boolean multiline, String msg, Object params[]) {
if (evtClass != ILogger.EV_SYSTEM)
return null;
SystemEvent event = new SystemEvent(msg, params);
@@ -75,8 +72,8 @@ public class SystemEventFactory implements ILogEventFactory {
/**
* Set the resource bundle of the log event.
- *
- * @param prop the properties
+ *
+ * @param prop the properties
* @param event the log event
*/
protected void setProperties(Properties prop, IBundleLogEvent event) {
@@ -93,7 +90,7 @@ public class SystemEventFactory implements ILogEventFactory {
/**
* Releases an log event.
- *
+ *
* @param e the log event
*/
public void release(ILogEvent e) {
diff --git a/pki/base/common/src/com/netscape/cmscore/notification/EmailFormProcessor.java b/pki/base/common/src/com/netscape/cmscore/notification/EmailFormProcessor.java
index 770b5ba4..9f6b206a 100644
--- a/pki/base/common/src/com/netscape/cmscore/notification/EmailFormProcessor.java
+++ b/pki/base/common/src/com/netscape/cmscore/notification/EmailFormProcessor.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.notification;
-
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.StringTokenizer;
@@ -27,12 +26,12 @@ import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.notification.IEmailFormProcessor;
-
/**
- * formulates the final email. Escape character '\' is understood.
- * '$' is used preceeding a token name. A token name should not be a
- * substring of any other token name
+ * formulates the final email. Escape character '\' is understood. '$' is used
+ * preceeding a token name. A token name should not be a substring of any other
+ * token name
* <p>
+ *
* @author cfu
* @version $Revision$, $Date$
*/
@@ -78,16 +77,19 @@ public class EmailFormProcessor implements IEmailFormProcessor {
}
/*
- * takes the form template, parse and replace all $tokens with the
- * right values. It handles escape character '\'
+ * takes the form template, parse and replace all $tokens with the right
+ * values. It handles escape character '\'
+ *
* @param form The locale specific form template,
- * @param tok2vals a hashtable containing one to one mapping
- * from $tokens used by the admins in the form template to the real
- * values corresponding to the $tokens
+ *
+ * @param tok2vals a hashtable containing one to one mapping from $tokens
+ * used by the admins in the form template to the real values corresponding
+ * to the $tokens
+ *
* @return mail content
*/
public String getEmailContent(String form,
- Hashtable<String, Object> tok2vals) {
+ Hashtable<String, Object> tok2vals) {
mTok2vals = tok2vals;
if (form == null) {
@@ -104,11 +106,11 @@ public class EmailFormProcessor implements IEmailFormProcessor {
* first, take care of the escape characters '\'
*/
StringTokenizer es = new StringTokenizer(form, TOK_ESC);
-
+
if (es.hasMoreTokens() && !form.startsWith(TOK_ESC)) {
dollarProcess(es.nextToken());
}
-
+
// rest of them start with '\'
while (es.hasMoreTokens()) {
String t = es.nextToken();
@@ -140,16 +142,16 @@ public class EmailFormProcessor implements IEmailFormProcessor {
}
/*
- * all of the string tokens below begin with a '$'
- * match it one by one with the mTok2vals table
+ * all of the string tokens below begin with a '$' match it one by one
+ * with the mTok2vals table
*/
while (st.hasMoreTokens()) {
String t = st.nextToken();
/*
- * We don't know when a token ends. Compare with every
- * token in the table for the first match. Which means, a
- * token name should not be a substring of any token name
+ * We don't know when a token ends. Compare with every token in the
+ * table for the first match. Which means, a token name should not
+ * be a substring of any token name
*/
boolean matched = false;
String tok = null;
@@ -183,7 +185,7 @@ public class EmailFormProcessor implements IEmailFormProcessor {
matched = true;
// replaced! bail out.
- break;
+ break;
}
}
@@ -192,17 +194,17 @@ public class EmailFormProcessor implements IEmailFormProcessor {
// no match, put the token back, as is
// -- for bug 382162, don't remove the following line, in
- // case John changes his mind for the better
- // mContent.add(TOK_PREFIX+t);
+ // case John changes his mind for the better
+ // mContent.add(TOK_PREFIX+t);
int tl = token_keys.length;
for (int i = 0; i < token_keys.length; i++) {
if (t.startsWith(token_keys[i])) {
- // match, replace it with the TOK_VALUE_UNKNOWN
+ // match, replace it with the TOK_VALUE_UNKNOWN
mContent.add(TOK_VALUE_UNKNOWN);
-
+
// now, put the rest of the non-token string
- // in mContent
+ // in mContent
if (t.length() != token_keys[i].length()) {
mContent.add(t.substring(token_keys[i].length()));
}
@@ -228,7 +230,7 @@ public class EmailFormProcessor implements IEmailFormProcessor {
// initialize content with first element
if (e.hasMoreElements()) {
- content = e.nextElement();
+ content = e.nextElement();
}
while (e.hasMoreElements()) {
@@ -247,7 +249,6 @@ public class EmailFormProcessor implements IEmailFormProcessor {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_OTHER,
- level, "EmailFormProcessor: " + msg);
+ level, "EmailFormProcessor: " + msg);
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/notification/EmailResolverKeys.java b/pki/base/common/src/com/netscape/cmscore/notification/EmailResolverKeys.java
index 909ec484..6f22c026 100644
--- a/pki/base/common/src/com/netscape/cmscore/notification/EmailResolverKeys.java
+++ b/pki/base/common/src/com/netscape/cmscore/notification/EmailResolverKeys.java
@@ -17,18 +17,16 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.notification;
-
import java.util.Enumeration;
import java.util.Hashtable;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.notification.IEmailResolverKeys;
-
/**
* Email resolver keys as input to email resolvers
* <P>
- *
+ *
* @author cfu
* @version $Revision$, $Date$
*/
@@ -45,11 +43,12 @@ public class EmailResolverKeys implements IEmailResolverKeys {
/**
* sets a key with key name and the key
+ *
* @param name key name
* @param key key
* @exception com.netscape.certsrv.base.EBaseException NullPointerException
*/
- public void set(String name, Object key)throws EBaseException {
+ public void set(String name, Object key) throws EBaseException {
try {
mKeys.put(name, key);
} catch (NullPointerException e) {
@@ -59,8 +58,8 @@ public class EmailResolverKeys implements IEmailResolverKeys {
}
/**
- * returns the key to which the specified name is mapped in this
- * key set
+ * returns the key to which the specified name is mapped in this key set
+ *
* @param name key name
* @return the named email resolver key
*/
@@ -69,9 +68,9 @@ public class EmailResolverKeys implements IEmailResolverKeys {
}
/**
- * removes the name and its corresponding key from this
- * key set. This method does nothing if the named
- * key is not in the key set.
+ * removes the name and its corresponding key from this key set. This method
+ * does nothing if the named key is not in the key set.
+ *
* @param name key name
*/
public void delete(String name) {
@@ -79,9 +78,9 @@ public class EmailResolverKeys implements IEmailResolverKeys {
}
/**
- * returns an enumeration of the keys in this key
- * set. Use the Enumeration methods on the returned object to
- * fetch the elements sequentially.
+ * returns an enumeration of the keys in this key set. Use the Enumeration
+ * methods on the returned object to fetch the elements sequentially.
+ *
* @return an enumeration of the values in this key set
* @see java.util.Enumeration
*/
@@ -89,4 +88,3 @@ public class EmailResolverKeys implements IEmailResolverKeys {
return (mKeys.elements());
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/notification/EmailTemplate.java b/pki/base/common/src/com/netscape/cmscore/notification/EmailTemplate.java
index 5c9e9ae0..ac25616c 100644
--- a/pki/base/common/src/com/netscape/cmscore/notification/EmailTemplate.java
+++ b/pki/base/common/src/com/netscape/cmscore/notification/EmailTemplate.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.notification;
-
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
@@ -28,21 +27,21 @@ import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.notification.IEmailTemplate;
-
/**
- * Files to be processed and returned to the requested parties. It
- * is a template with $tokens to be used by the form/template processor.
- *
- *
+ * Files to be processed and returned to the requested parties. It is a template
+ * with $tokens to be used by the form/template processor.
+ *
+ *
* @author cfu
* @version $Revision$, $Date$
*/
public class EmailTemplate implements IEmailTemplate {
- /*==========================================================
- * variables
- *==========================================================*/
+ /*
+ * ========================================================== variables
+ * ==========================================================
+ */
/* private variables */
private String mTemplateFile = new String();
@@ -51,27 +50,29 @@ public class EmailTemplate implements IEmailTemplate {
/* public vaiables */
public String mFileContents;
- /*==========================================================
- * constructors
- *==========================================================*/
+ /*
+ * ========================================================== constructors
+ * ==========================================================
+ */
/**
* Default Constructor
- *
+ *
* @param templateFile File name of the template including the full path and
- * file extension
+ * file extension
*/
public EmailTemplate(String templatePath) {
mTemplateFile = templatePath;
}
- /*==========================================================
- * public methods
- *==========================================================*/
+ /*
+ * ========================================================== public methods
+ * ==========================================================
+ */
/*
* Load the template from the file
- *
+ *
* @return true if successful
*/
public boolean init() {
@@ -124,14 +125,14 @@ public class EmailTemplate implements IEmailTemplate {
return mTemplateFile;
}
- /**
+ /**
* @return true if template is an html file, false otherwise
*/
public boolean isHTML() {
if (mTemplateFile.endsWith(".html") ||
- mTemplateFile.endsWith(".HTML") ||
- mTemplateFile.endsWith(".htm") ||
- mTemplateFile.endsWith(".HTM"))
+ mTemplateFile.endsWith(".HTML") ||
+ mTemplateFile.endsWith(".htm") ||
+ mTemplateFile.endsWith(".HTM"))
return true;
else
return false;
@@ -144,9 +145,10 @@ public class EmailTemplate implements IEmailTemplate {
return mFileContents;
}
- /*==========================================================
- * private methods
- *==========================================================*/
+ /*
+ * ========================================================== private
+ * methods==========================================================
+ */
/* load file into string */
private String loadFile(FileReader input) {
@@ -178,7 +180,7 @@ public class EmailTemplate implements IEmailTemplate {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_OTHER,
- level, msg);
+ level, msg);
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/notification/ReqCertEmailResolver.java b/pki/base/common/src/com/netscape/cmscore/notification/ReqCertEmailResolver.java
index 04dd9b5f..4c62fa1e 100644
--- a/pki/base/common/src/com/netscape/cmscore/notification/ReqCertEmailResolver.java
+++ b/pki/base/common/src/com/netscape/cmscore/notification/ReqCertEmailResolver.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.notification;
-
import java.io.IOException;
import java.security.cert.X509Certificate;
@@ -31,11 +30,11 @@ import com.netscape.certsrv.notification.IEmailResolver;
import com.netscape.certsrv.notification.IEmailResolverKeys;
import com.netscape.certsrv.request.IRequest;
-
/**
- * An email resolver that first checks the request email, if none,
- * then follows by checking the subjectDN of the certificate
+ * An email resolver that first checks the request email, if none, then follows
+ * by checking the subjectDN of the certificate
* <p>
+ *
* @author cfu
* @version $Revision$, $Date$
*/
@@ -44,19 +43,21 @@ public class ReqCertEmailResolver implements IEmailResolver {
public static final String KEY_REQUEST = "request";
public static final String KEY_CERT = "cert";
+
// required keys for this resolver to figure out the email address
- // protected static String[] mRequiredKeys = {KEY_REQUEST, KEY_CERT};
+ // protected static String[] mRequiredKeys = {KEY_REQUEST, KEY_CERT};
public ReqCertEmailResolver() {
}
/**
- * returns an email address by using the resolver keys. The
- * return value can possibly be null
+ * returns an email address by using the resolver keys. The return value can
+ * possibly be null
+ *
* @param keys list of keys used for resolving the email address
*/
- public String getEmail(IEmailResolverKeys keys)
- throws EBaseException, ENotificationException {
+ public String getEmail(IEmailResolverKeys keys)
+ throws EBaseException, ENotificationException {
IRequest req = (IRequest) keys.get(KEY_REQUEST);
String mEmail = null;
@@ -84,14 +85,14 @@ public class ReqCertEmailResolver implements IEmailResolver {
if (cert != null) {
subjectDN =
(X500Name) cert.getSubjectDN();
-
+
try {
mEmail = subjectDN.getEmail();
} catch (IOException e) {
System.out.println("X500Name getEmail failed");
- throw new ENotificationException (
+ throw new ENotificationException(
CMS.getUserMessage("CMS_NOTIFICATION_EMAIL_RESOLVE_FAILED",
- subjectDN.toString()));
+ subjectDN.toString()));
}
} else {
log(ILogger.LL_INFO, "cert null in keys");
@@ -101,31 +102,31 @@ public class ReqCertEmailResolver implements IEmailResolver {
if (mEmail == null) {
if (cert != null) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_NOTIFY_NO_EMAIL", subjectDN.toString()));
+ CMS.getLogMessage("CMSCORE_NOTIFY_NO_EMAIL", subjectDN.toString()));
CMS.debug(
- "no email resolved, throwing NotificationResources.EMAIL_RESOLVE_FAILED_1 for " +
- subjectDN.toString());
- throw new ENotificationException (
+ "no email resolved, throwing NotificationResources.EMAIL_RESOLVE_FAILED_1 for " +
+ subjectDN.toString());
+ throw new ENotificationException(
CMS.getUserMessage("CMS_NOTIFICATION_EMAIL_RESOLVE_FAILED",
- "subjectDN= " + subjectDN.toString()));
+ "subjectDN= " + subjectDN.toString()));
} else if (req != null) {
log(ILogger.LL_FAILURE,
- "no email resolved for request id =" +
- req.getRequestId().toString());
+ "no email resolved for request id =" +
+ req.getRequestId().toString());
CMS.debug(
- "no email resolved, throwing NotificationResources.EMAIL_RESOLVE_FAILED_1 for request id =" +
- req.getRequestId().toString());
- throw new ENotificationException (
+ "no email resolved, throwing NotificationResources.EMAIL_RESOLVE_FAILED_1 for request id =" +
+ req.getRequestId().toString());
+ throw new ENotificationException(
CMS.getUserMessage("CMS_NOTIFICATION_EMAIL_RESOLVE_FAILED",
- "requestId= " + req.getRequestId().toString()));
+ "requestId= " + req.getRequestId().toString()));
} else {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_NOTIFY_NO_EMAIL_REQUEST"));
+ CMS.getLogMessage("CMSCORE_NOTIFY_NO_EMAIL_REQUEST"));
CMS.debug(
- "no email resolved, throwing NotificationResources.EMAIL_RESOLVE_FAILED_1. No request id or cert info found");
- throw new ENotificationException (
+ "no email resolved, throwing NotificationResources.EMAIL_RESOLVE_FAILED_1. No request id or cert info found");
+ throw new ENotificationException(
CMS.getUserMessage("CMS_NOTIFICATION_EMAIL_RESOLVE_FAILED",
- ": No request id or cert info found"));
+ ": No request id or cert info found"));
}
} else {
log(ILogger.LL_INFO, "email resolved: " + mEmail);
@@ -136,18 +137,19 @@ public class ReqCertEmailResolver implements IEmailResolver {
/**
* Returns array of required keys for this email resolver
+ *
* @return Array of required keys.
*/
-
- /* public String[] getRequiredKeys() {
- return mRequiredKeys;
- }*/
+
+ /*
+ * public String[] getRequiredKeys() { return mRequiredKeys; }
+ */
private void log(int level, String msg) {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_OTHER,
- level, "ReqCertEmailResolver: " + msg);
+ level, "ReqCertEmailResolver: " + msg);
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/notification/ReqCertSANameEmailResolver.java b/pki/base/common/src/com/netscape/cmscore/notification/ReqCertSANameEmailResolver.java
index 580c9e98..52eaeefd 100644
--- a/pki/base/common/src/com/netscape/cmscore/notification/ReqCertSANameEmailResolver.java
+++ b/pki/base/common/src/com/netscape/cmscore/notification/ReqCertSANameEmailResolver.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.notification;
-
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateParsingException;
@@ -43,12 +42,12 @@ import com.netscape.certsrv.notification.IEmailResolver;
import com.netscape.certsrv.notification.IEmailResolverKeys;
import com.netscape.certsrv.request.IRequest;
-
/**
- * An email resolver that first checks the request email, if none,
- * then follows by checking the subjectDN of the certificate, if none,
- * then follows by checking the subjectalternatename extension
+ * An email resolver that first checks the request email, if none, then follows
+ * by checking the subjectDN of the certificate, if none, then follows by
+ * checking the subjectalternatename extension
* <p>
+ *
* @author cfu
* @version $Revision$, $Date$
*/
@@ -59,18 +58,19 @@ public class ReqCertSANameEmailResolver implements IEmailResolver {
public static final String KEY_CERT = IEmailResolverKeys.KEY_CERT;
// required keys for this resolver to figure out the email address
- // protected static String[] mRequiredKeys = {KEY_REQUEST, KEY_CERT};
+ // protected static String[] mRequiredKeys = {KEY_REQUEST, KEY_CERT};
public ReqCertSANameEmailResolver() {
}
/**
- * returns an email address by using the resolver keys. The
- * return value can possibly be null
+ * returns an email address by using the resolver keys. The return value can
+ * possibly be null
+ *
* @param keys list of keys used for resolving the email address
*/
- public String getEmail(IEmailResolverKeys keys)
- throws EBaseException, ENotificationException {
+ public String getEmail(IEmailResolverKeys keys)
+ throws EBaseException, ENotificationException {
IRequest req = (IRequest) keys.get(KEY_REQUEST);
String mEmail = null;
@@ -102,30 +102,30 @@ public class ReqCertSANameEmailResolver implements IEmailResolver {
ICertificateRepository certDB = ca.getCertificateRepository();
cert = certDB.getX509Certificate(revCert.getSerialNumber());
- }else
+ } else
cert = (X509Certificate) request;
-
+
X500Name subjectDN = null;
if (cert != null) {
subjectDN =
(X500Name) cert.getSubjectDN();
-
+
try {
mEmail = subjectDN.getEmail();
if (mEmail != null) {
if (!mEmail.equals("")) {
log(ILogger.LL_INFO, "cert subjectDN E=" +
- mEmail);
+ mEmail);
}
} else {
log(ILogger.LL_INFO, "no E component in subjectDN ");
}
} catch (IOException e) {
System.out.println("X500Name getEmail failed");
- throw new ENotificationException (
+ throw new ENotificationException(
CMS.getUserMessage("CMS_NOTIFICATION_EMAIL_RESOLVE_FAILED",
- subjectDN.toString()));
+ subjectDN.toString()));
}
// try subjectalternatename
@@ -136,13 +136,13 @@ public class ReqCertSANameEmailResolver implements IEmailResolver {
try {
certInfo = (X509CertInfo)
((X509CertImpl) cert).get(
- X509CertImpl.NAME + "." + X509CertImpl.INFO);
+ X509CertImpl.NAME + "." + X509CertImpl.INFO);
} catch (CertificateParsingException ex) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_NOTIFY_NO_CERTINFO"));
- throw new ENotificationException (
+ CMS.getLogMessage("CMSCORE_NOTIFY_NO_CERTINFO"));
+ throw new ENotificationException(
CMS.getUserMessage("CMS_NOTIFICATION_EMAIL_RESOLVE_FAILED",
- "subjectDN= " + subjectDN.toString()));
+ "subjectDN= " + subjectDN.toString()));
}
CertificateExtensions exts;
@@ -152,47 +152,46 @@ public class ReqCertSANameEmailResolver implements IEmailResolver {
certInfo.get(CertificateExtensions.NAME);
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_NOTIFY_GET_EXT", e.toString()));
- throw new ENotificationException (
+ CMS.getLogMessage("CMSCORE_NOTIFY_GET_EXT", e.toString()));
+ throw new ENotificationException(
CMS.getUserMessage("CMS_NOTIFICATION_EMAIL_RESOLVE_FAILED",
- "subjectDN= " + subjectDN.toString()));
+ "subjectDN= " + subjectDN.toString()));
} catch (CertificateException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_NOTIFY_GET_EXT", e.toString()));
- throw new ENotificationException (
+ CMS.getLogMessage("CMSCORE_NOTIFY_GET_EXT", e.toString()));
+ throw new ENotificationException(
CMS.getUserMessage("CMS_NOTIFICATION_EMAIL_RESOLVE_FAILED",
- "subjectDN= " + subjectDN.toString()));
+ "subjectDN= " + subjectDN.toString()));
}
if (exts != null) {
SubjectAlternativeNameExtension ext;
try {
- ext =
+ ext =
(SubjectAlternativeNameExtension)
exts.get(SubjectAlternativeNameExtension.class.getSimpleName());
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_NOTIFY_GET_EXT", e.toString()));
- throw new ENotificationException (
+ CMS.getLogMessage("CMSCORE_NOTIFY_GET_EXT", e.toString()));
+ throw new ENotificationException(
CMS.getUserMessage("CMS_NOTIFICATION_EMAIL_RESOLVE_FAILED",
- "subjectDN= " + subjectDN.toString()));
-
+ "subjectDN= " + subjectDN.toString()));
+
}
try {
if (ext != null) {
GeneralNames gn =
- (GeneralNames) ext.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
+ (GeneralNames) ext.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
Enumeration<GeneralNameInterface> e = gn.elements();
while (e.hasMoreElements()) {
- GeneralNameInterface gni =e.nextElement();
+ GeneralNameInterface gni = e.nextElement();
- if (gni.getType() ==
- GeneralNameInterface.NAME_RFC822) {
+ if (gni.getType() == GeneralNameInterface.NAME_RFC822) {
CMS.debug("got an subjectalternatename email");
String nameString = gni.toString();
@@ -201,9 +200,9 @@ public class ReqCertSANameEmailResolver implements IEmailResolver {
mEmail =
nameString.substring(nameString.indexOf(' ') + 1);
log(ILogger.LL_INFO,
- "subjectalternatename email used:" +
- mEmail);
-
+ "subjectalternatename email used:" +
+ mEmail);
+
break;
} else {
CMS.debug("not an subjectalternatename email");
@@ -212,43 +211,43 @@ public class ReqCertSANameEmailResolver implements IEmailResolver {
}
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_NOTIFY_SUBJECTALTNAME"));
+ CMS.getLogMessage("CMSCORE_NOTIFY_SUBJECTALTNAME"));
}
}
}
} else {
log(ILogger.LL_INFO, "cert null in keys");
}
-
+
// log it
if (mEmail == null) {
if (cert != null) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_NOTIFY_NO_EMAIL", subjectDN.toString()));
+ CMS.getLogMessage("CMSCORE_NOTIFY_NO_EMAIL", subjectDN.toString()));
CMS.debug(
- "no email resolved, throwing NotificationResources.EMAIL_RESOLVE_FAILED_1 for " +
- subjectDN.toString());
- throw new ENotificationException (
+ "no email resolved, throwing NotificationResources.EMAIL_RESOLVE_FAILED_1 for " +
+ subjectDN.toString());
+ throw new ENotificationException(
CMS.getUserMessage("CMS_NOTIFICATION_EMAIL_RESOLVE_FAILED",
- "subjectDN= " + subjectDN.toString()));
+ "subjectDN= " + subjectDN.toString()));
} else if (req != null) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_NOTIFY_NO_EMAIL_ID",
- req.getRequestId().toString()));
+ CMS.getLogMessage("CMSCORE_NOTIFY_NO_EMAIL_ID",
+ req.getRequestId().toString()));
CMS.debug(
- "no email resolved, throwing NotificationResources.EMAIL_RESOLVE_FAILED_1 for request id =" +
- req.getRequestId().toString());
- throw new ENotificationException (
+ "no email resolved, throwing NotificationResources.EMAIL_RESOLVE_FAILED_1 for request id =" +
+ req.getRequestId().toString());
+ throw new ENotificationException(
CMS.getUserMessage("CMS_NOTIFICATION_EMAIL_RESOLVE_FAILED",
- "requestId= " + req.getRequestId().toString()));
+ "requestId= " + req.getRequestId().toString()));
} else {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_NOTIFY_NO_EMAIL_REQUEST"));
+ CMS.getLogMessage("CMSCORE_NOTIFY_NO_EMAIL_REQUEST"));
CMS.debug(
- "no email resolved, throwing NotificationResources.EMAIL_RESOLVE_FAILED_1. No request id or cert info found");
- throw new ENotificationException (
+ "no email resolved, throwing NotificationResources.EMAIL_RESOLVE_FAILED_1. No request id or cert info found");
+ throw new ENotificationException(
CMS.getUserMessage("CMS_NOTIFICATION_EMAIL_RESOLVE_FAILED",
- ": No request id or cert info found"));
+ ": No request id or cert info found"));
}
} else {
log(ILogger.LL_INFO, "email resolved: " + mEmail);
@@ -259,18 +258,19 @@ public class ReqCertSANameEmailResolver implements IEmailResolver {
/**
* Returns array of required keys for this email resolver
+ *
* @return Array of required keys.
*/
-
- /* public String[] getRequiredKeys() {
- return mRequiredKeys;
- }*/
+
+ /*
+ * public String[] getRequiredKeys() { return mRequiredKeys; }
+ */
private void log(int level, String msg) {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_OTHER,
- level, "ReqCertSANameEmailResolver: " + msg);
+ level, "ReqCertSANameEmailResolver: " + msg);
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/policy/AndExpression.java b/pki/base/common/src/com/netscape/cmscore/policy/AndExpression.java
index d58cfe13..974e2e86 100644
--- a/pki/base/common/src/com/netscape/cmscore/policy/AndExpression.java
+++ b/pki/base/common/src/com/netscape/cmscore/policy/AndExpression.java
@@ -17,31 +17,30 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.policy;
-
import com.netscape.certsrv.policy.EPolicyException;
import com.netscape.certsrv.policy.IExpression;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class represents an expression of the form
- * <var1 op val1 AND var2 op va2>.
- *
+ * This class represents an expression of the form <var1 op val1 AND var2 op
+ * va2>.
+ *
* Expressions are used as predicates for policy selection.
- *
+ *
* @author kanda
* @version $Revision$, $Date$
*/
public class AndExpression implements IExpression {
private IExpression mExp1;
private IExpression mExp2;
+
public AndExpression(IExpression exp1, IExpression exp2) {
mExp1 = exp1;
mExp2 = exp2;
}
public boolean evaluate(IRequest req)
- throws EPolicyException {
+ throws EPolicyException {
// If an expression is missing we assume applicability.
if (mExp1 == null && mExp2 == null)
return true;
@@ -49,7 +48,8 @@ public class AndExpression implements IExpression {
return mExp1.evaluate(req) && mExp2.evaluate(req);
else if (mExp1 == null)
return mExp2.evaluate(req);
- else // (if mExp2 == null)
+ else
+ // (if mExp2 == null)
return mExp1.evaluate(req);
}
diff --git a/pki/base/common/src/com/netscape/cmscore/policy/GeneralNameUtil.java b/pki/base/common/src/com/netscape/cmscore/policy/GeneralNameUtil.java
index 4587bca6..561cf01d 100644
--- a/pki/base/common/src/com/netscape/cmscore/policy/GeneralNameUtil.java
+++ b/pki/base/common/src/com/netscape/cmscore/policy/GeneralNameUtil.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.policy;
-
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Enumeration;
@@ -50,23 +49,22 @@ import com.netscape.certsrv.policy.IGeneralNamesConfig;
import com.netscape.certsrv.policy.ISubjAltNameConfig;
import com.netscape.cmscore.util.Debug;
-
-/**
- * Class that can be used to form general names from configuration file.
- * Used by policies and extension commands.
+/**
+ * Class that can be used to form general names from configuration file. Used by
+ * policies and extension commands.
*/
public class GeneralNameUtil implements IGeneralNameUtil {
private static final String DOT = ".";
/**
- * GeneralName can be used in the context of Constraints. Examples
- * are NameConstraints, CertificateScopeOfUse extensions. In such
- * cases, IPAddress may contain netmask component.
+ * GeneralName can be used in the context of Constraints. Examples are
+ * NameConstraints, CertificateScopeOfUse extensions. In such cases,
+ * IPAddress may contain netmask component.
*/
- static public GeneralName
- form_GeneralNameAsConstraints(String generalNameChoice, String value)
- throws EBaseException {
+ static public GeneralName
+ form_GeneralNameAsConstraints(String generalNameChoice, String value)
+ throws EBaseException {
try {
if (generalNameChoice.equalsIgnoreCase(GENNAME_CHOICE_IPADDRESS)) {
StringTokenizer st = new StringTokenizer(value, ",");
@@ -86,16 +84,17 @@ public class GeneralNameUtil implements IGeneralNameUtil {
}
/**
- * Form a General Name from a General Name choice and value.
- * The General Name choice must be one of the General Name Choice Strings
- * defined in this class.
- * @param generalNameChoice General Name choice. Must be one of the General
- * Name choices defined in this class.
+ * Form a General Name from a General Name choice and value. The General
+ * Name choice must be one of the General Name Choice Strings defined in
+ * this class.
+ *
+ * @param generalNameChoice General Name choice. Must be one of the General
+ * Name choices defined in this class.
* @param value String value of the general name to form.
*/
- static public GeneralName
- form_GeneralName(String generalNameChoice, String value)
- throws EBaseException {
+ static public GeneralName
+ form_GeneralName(String generalNameChoice, String value)
+ throws EBaseException {
GeneralNameInterface generalNameI = null;
DerValue derVal = null;
GeneralName generalName = null;
@@ -112,10 +111,12 @@ public class GeneralNameUtil implements IGeneralNameUtil {
} else if (generalNameChoice.equalsIgnoreCase(GENNAME_CHOICE_DNSNAME)) {
generalNameI = new DNSName(value);
Debug.trace("dnsName formed");
- } /** not supported -- no sun class
- else if (generalNameChoice.equalsIgnoreCase(GENNAME_CHOICE_X400ADDRESS)) {
- }
- **/ else if (generalNameChoice.equalsIgnoreCase(GENNAME_CHOICE_DIRECTORYNAME)) {
+ }/**
+ * not supported -- no sun class else if
+ * (generalNameChoice.equalsIgnoreCase(GENNAME_CHOICE_X400ADDRESS))
+ * { }
+ **/
+ else if (generalNameChoice.equalsIgnoreCase(GENNAME_CHOICE_DIRECTORYNAME)) {
generalNameI = new X500Name(value);
Debug.trace("X500Name formed");
} else if (generalNameChoice.equalsIgnoreCase(GENNAME_CHOICE_EDIPARTYNAME)) {
@@ -135,35 +136,38 @@ public class GeneralNameUtil implements IGeneralNameUtil {
} catch (Exception e) {
throw new EBaseException(
CMS.getUserMessage("CMS_BASE_INVALID_VALUE_FOR_TYPE",
- generalNameChoice,
- "value must be a valid OID in the form n.n.n.n"));
+ generalNameChoice,
+ "value must be a valid OID in the form n.n.n.n"));
}
generalNameI = new OIDName(oid);
Debug.trace("oidname formed");
} else {
throw new EBaseException(
CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
- new String[] {
- PROP_GENNAME_CHOICE,
- "value must be one of: " +
- GENNAME_CHOICE_OTHERNAME + ", " +
- GENNAME_CHOICE_RFC822NAME + ", " +
- GENNAME_CHOICE_DNSNAME + ", " +
-
- /* GENNAME_CHOICE_X400ADDRESS +", "+ */
- GENNAME_CHOICE_DIRECTORYNAME + ", " +
- GENNAME_CHOICE_EDIPARTYNAME + ", " +
- GENNAME_CHOICE_URL + ", " +
- GENNAME_CHOICE_IPADDRESS + ", or " +
- GENNAME_CHOICE_REGISTEREDID + "."
+ new String[] {
+ PROP_GENNAME_CHOICE,
+ "value must be one of: " +
+ GENNAME_CHOICE_OTHERNAME + ", " +
+ GENNAME_CHOICE_RFC822NAME + ", " +
+ GENNAME_CHOICE_DNSNAME + ", " +
+
+ /*
+ * GENNAME_CHOICE_X400ADDRESS
+ * +", "+
+ */
+ GENNAME_CHOICE_DIRECTORYNAME + ", " +
+ GENNAME_CHOICE_EDIPARTYNAME + ", " +
+ GENNAME_CHOICE_URL + ", " +
+ GENNAME_CHOICE_IPADDRESS + ", or " +
+ GENNAME_CHOICE_REGISTEREDID + "."
}
- ));
+ ));
}
} catch (IOException e) {
Debug.printStackTrace(e);
throw new EBaseException(
CMS.getUserMessage("CMS_BASE_INVALID_VALUE_FOR_TYPE",
- generalNameChoice, e.toString()));
+ generalNameChoice, e.toString()));
} catch (InvalidIPAddressException e) {
Debug.printStackTrace(e);
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_IP_ADDR", value));
@@ -187,62 +191,64 @@ public class GeneralNameUtil implements IGeneralNameUtil {
}
/**
- * Checks if given string is a valid General Name choice and returns
- * the actual string that can be passed into form_GeneralName().
+ * Checks if given string is a valid General Name choice and returns the
+ * actual string that can be passed into form_GeneralName().
+ *
* @param generalNameChoice a General Name choice string.
- * @return one of General Name choices defined in this class that can be
- * passed into form_GeneralName().
+ * @return one of General Name choices defined in this class that can be
+ * passed into form_GeneralName().
*/
- static public String check_GeneralNameChoice(String generalNameChoice)
- throws EBaseException {
+ static public String check_GeneralNameChoice(String generalNameChoice)
+ throws EBaseException {
String theGeneralNameChoice = null;
- if (generalNameChoice.equalsIgnoreCase(GENNAME_CHOICE_OTHERNAME))
+ if (generalNameChoice.equalsIgnoreCase(GENNAME_CHOICE_OTHERNAME))
theGeneralNameChoice = GENNAME_CHOICE_OTHERNAME;
- else if (generalNameChoice.equalsIgnoreCase(GENNAME_CHOICE_RFC822NAME))
+ else if (generalNameChoice.equalsIgnoreCase(GENNAME_CHOICE_RFC822NAME))
theGeneralNameChoice = GENNAME_CHOICE_RFC822NAME;
- else if (generalNameChoice.equalsIgnoreCase(GENNAME_CHOICE_DNSNAME))
+ else if (generalNameChoice.equalsIgnoreCase(GENNAME_CHOICE_DNSNAME))
theGeneralNameChoice = GENNAME_CHOICE_DNSNAME;
- /* X400Address not supported.
- else if (generalNameChoice.equalsIgnoreCase(GENNAME_CHOICE_X400ADDRESS))
- theGeneralNameChoice = GENNAME_CHOICE_X400ADDRESS;
- */
- else if (generalNameChoice.equalsIgnoreCase(GENNAME_CHOICE_DIRECTORYNAME))
+ /*
+ * X400Address not supported. else if
+ * (generalNameChoice.equalsIgnoreCase(GENNAME_CHOICE_X400ADDRESS))
+ * theGeneralNameChoice = GENNAME_CHOICE_X400ADDRESS;
+ */
+ else if (generalNameChoice.equalsIgnoreCase(GENNAME_CHOICE_DIRECTORYNAME))
theGeneralNameChoice = GENNAME_CHOICE_DIRECTORYNAME;
- else if (generalNameChoice.equalsIgnoreCase(GENNAME_CHOICE_EDIPARTYNAME))
+ else if (generalNameChoice.equalsIgnoreCase(GENNAME_CHOICE_EDIPARTYNAME))
theGeneralNameChoice = GENNAME_CHOICE_EDIPARTYNAME;
- else if (generalNameChoice.equalsIgnoreCase(GENNAME_CHOICE_URL))
+ else if (generalNameChoice.equalsIgnoreCase(GENNAME_CHOICE_URL))
theGeneralNameChoice = GENNAME_CHOICE_URL;
- else if (generalNameChoice.equalsIgnoreCase(GENNAME_CHOICE_IPADDRESS))
+ else if (generalNameChoice.equalsIgnoreCase(GENNAME_CHOICE_IPADDRESS))
theGeneralNameChoice = GENNAME_CHOICE_IPADDRESS;
- else if (generalNameChoice.equalsIgnoreCase(GENNAME_CHOICE_REGISTEREDID))
+ else if (generalNameChoice.equalsIgnoreCase(GENNAME_CHOICE_REGISTEREDID))
theGeneralNameChoice = GENNAME_CHOICE_REGISTEREDID;
else {
throw new EBaseException(
CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
- new String[] {
- PROP_GENNAME_CHOICE + "=" + generalNameChoice,
- "value must be one of: " +
- GENNAME_CHOICE_OTHERNAME + ", " +
- GENNAME_CHOICE_RFC822NAME + ", " +
- GENNAME_CHOICE_DNSNAME + ", " +
-
- /* GENNAME_CHOICE_X400ADDRESS +", "+ */
- GENNAME_CHOICE_DIRECTORYNAME + ", " +
- GENNAME_CHOICE_EDIPARTYNAME + ", " +
- GENNAME_CHOICE_URL + ", " +
- GENNAME_CHOICE_IPADDRESS + ", " +
- GENNAME_CHOICE_REGISTEREDID + "."
+ new String[] {
+ PROP_GENNAME_CHOICE + "=" + generalNameChoice,
+ "value must be one of: " +
+ GENNAME_CHOICE_OTHERNAME + ", " +
+ GENNAME_CHOICE_RFC822NAME + ", " +
+ GENNAME_CHOICE_DNSNAME + ", " +
+
+ /* GENNAME_CHOICE_X400ADDRESS +", "+ */
+ GENNAME_CHOICE_DIRECTORYNAME + ", " +
+ GENNAME_CHOICE_EDIPARTYNAME + ", " +
+ GENNAME_CHOICE_URL + ", " +
+ GENNAME_CHOICE_IPADDRESS + ", " +
+ GENNAME_CHOICE_REGISTEREDID + "."
}
- ));
+ ));
}
return theGeneralNameChoice;
}
static public class GeneralNamesConfig implements IGeneralNamesConfig {
public String mName = null; // substore name of config if any.
- public GeneralNameConfig[] mGenNameConfigs = null;
+ public GeneralNameConfig[] mGenNameConfigs = null;
public IConfigStore mConfig = null;
public boolean mIsValueConfigured = true;
public boolean mIsPolicyEnabled = true;
@@ -252,17 +258,17 @@ public class GeneralNameUtil implements IGeneralNameUtil {
private String mNameDotGeneralName = mName + DOT + PROP_GENERALNAME;
public GeneralNamesConfig(
- String name,
- IConfigStore config,
- boolean isValueConfigured,
- boolean isPolicyEnabled)
- throws EBaseException {
+ String name,
+ IConfigStore config,
+ boolean isValueConfigured,
+ boolean isPolicyEnabled)
+ throws EBaseException {
mIsValueConfigured = isValueConfigured;
mIsPolicyEnabled = isPolicyEnabled;
mName = name;
- if (mName != null)
+ if (mName != null)
mNameDotGeneralName = mName + DOT + PROP_GENERALNAME;
- else
+ else
mNameDotGeneralName = PROP_GENERALNAME;
mConfig = config;
@@ -271,19 +277,19 @@ public class GeneralNameUtil implements IGeneralNameUtil {
if (numGNs < 0) {
throw new EBaseException(
CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
- new String[] {
- PROP_NUM_GENERALNAMES + "=" + numGNs,
- "value must be greater than or equal to 0."}
- ));
+ new String[] {
+ PROP_NUM_GENERALNAMES + "=" + numGNs,
+ "value must be greater than or equal to 0." }
+ ));
}
mGenNameConfigs = new GeneralNameConfig[numGNs];
for (int i = 0; i < numGNs; i++) {
String storeName = mNameDotGeneralName + i;
- mGenNameConfigs[i] =
+ mGenNameConfigs[i] =
newGeneralNameConfig(
- storeName, mConfig.getSubStore(storeName),
- mIsValueConfigured, mIsPolicyEnabled);
+ storeName, mConfig.getSubStore(storeName),
+ mIsValueConfigured, mIsPolicyEnabled);
}
if (mIsValueConfigured && mIsPolicyEnabled) {
@@ -299,9 +305,9 @@ public class GeneralNameUtil implements IGeneralNameUtil {
}
protected GeneralNameConfig newGeneralNameConfig(
- String name, IConfigStore config,
- boolean isValueConfigured, boolean isPolicyEnabled)
- throws EBaseException {
+ String name, IConfigStore config,
+ boolean isValueConfigured, boolean isPolicyEnabled)
+ throws EBaseException {
return new GeneralNameConfig(
name, config, isValueConfigured, isPolicyEnabled);
}
@@ -334,20 +340,20 @@ public class GeneralNameUtil implements IGeneralNameUtil {
return mDefNumGenNames;
}
- /**
- * adds params to default
+ /**
+ * adds params to default
*/
public static void getDefaultParams(
- String name, boolean isValueConfigured, Vector<String> params) {
+ String name, boolean isValueConfigured, Vector<String> params) {
String nameDot = "";
- if (name != null)
+ if (name != null)
nameDot = name + DOT;
params.addElement(
- nameDot + PROP_NUM_GENERALNAMES + '=' + DEF_NUM_GENERALNAMES);
+ nameDot + PROP_NUM_GENERALNAMES + '=' + DEF_NUM_GENERALNAMES);
for (int i = 0; i < DEF_NUM_GENERALNAMES; i++) {
GeneralNameConfig.getDefaultParams(
- nameDot + PROP_GENERALNAME + i, isValueConfigured, params);
+ nameDot + PROP_GENERALNAME + i, isValueConfigured, params);
}
}
@@ -356,7 +362,7 @@ public class GeneralNameUtil implements IGeneralNameUtil {
*/
public void getInstanceParams(Vector<String> params) {
params.addElement(
- PROP_NUM_GENERALNAMES + '=' + mGenNameConfigs.length);
+ PROP_NUM_GENERALNAMES + '=' + mGenNameConfigs.length);
for (int i = 0; i < mGenNameConfigs.length; i++) {
mGenNameConfigs[i].getInstanceParams(params);
}
@@ -366,7 +372,7 @@ public class GeneralNameUtil implements IGeneralNameUtil {
* Get extended plugin info.
*/
public static void getExtendedPluginInfo(
- String name, boolean isValueConfigured, Vector<String> info) {
+ String name, boolean isValueConfigured, Vector<String> info) {
String nameDot = "";
if (name != null && name.length() > 0)
@@ -374,33 +380,31 @@ public class GeneralNameUtil implements IGeneralNameUtil {
info.addElement(PROP_NUM_GENERALNAMES + ";" + NUM_GENERALNAMES_INFO);
for (int i = 0; i < DEF_NUM_GENERALNAMES; i++) {
GeneralNameConfig.getExtendedPluginInfo(
- nameDot + PROP_GENERALNAME + i, isValueConfigured, info);
+ nameDot + PROP_GENERALNAME + i, isValueConfigured, info);
}
}
}
-
static public class GeneralNamesAsConstraintsConfig extends GeneralNamesConfig implements IGeneralNamesAsConstraintsConfig {
public GeneralNamesAsConstraintsConfig(
- String name,
- IConfigStore config,
- boolean isValueConfigured,
- boolean isPolicyEnabled)
- throws EBaseException {
+ String name,
+ IConfigStore config,
+ boolean isValueConfigured,
+ boolean isPolicyEnabled)
+ throws EBaseException {
super(name, config, isValueConfigured, isPolicyEnabled);
}
protected GeneralNameConfig newGeneralNameConfig(
- String name, IConfigStore config,
- boolean isValueConfigured, boolean isPolicyEnabled)
- throws EBaseException {
- return new GeneralNameAsConstraintsConfig(name, config,
+ String name, IConfigStore config,
+ boolean isValueConfigured, boolean isPolicyEnabled)
+ throws EBaseException {
+ return new GeneralNameAsConstraintsConfig(name, config,
isValueConfigured, isPolicyEnabled);
}
}
-
/**
* convenience class for policies use.
*/
@@ -418,11 +422,11 @@ public class GeneralNameUtil implements IGeneralNameUtil {
public String mNameDotValue = null;
public GeneralNameConfig(
- String name,
- IConfigStore config,
- boolean isValueConfigured,
- boolean isPolicyEnabled)
- throws EBaseException {
+ String name,
+ IConfigStore config,
+ boolean isValueConfigured,
+ boolean isPolicyEnabled)
+ throws EBaseException {
mIsValueConfigured = isValueConfigured;
mIsPolicyEnabled = isPolicyEnabled;
mName = name;
@@ -461,7 +465,7 @@ public class GeneralNameUtil implements IGeneralNameUtil {
mGeneralName = formGeneralName(mGenNameChoice, mValue);
} else {
mValue = mConfig.getString(PROP_GENNAME_VALUE, "");
- if (mValue != null && mValue.length() > 0)
+ if (mValue != null && mValue.length() > 0)
mGeneralName = formGeneralName(mGenNameChoice, mValue);
}
}
@@ -470,23 +474,23 @@ public class GeneralNameUtil implements IGeneralNameUtil {
/**
* Form a general name from the value string.
*/
- public GeneralName formGeneralName(String value)
- throws EBaseException {
+ public GeneralName formGeneralName(String value)
+ throws EBaseException {
return formGeneralName(mGenNameChoice, value);
}
- public GeneralName formGeneralName(String choice, String value)
- throws EBaseException {
+ public GeneralName formGeneralName(String choice, String value)
+ throws EBaseException {
return form_GeneralName(choice, value);
}
- /**
- * @return a vector of General names from a value that can be
- * either a Vector of strings, string array or just a string.
- * Returned Vector can be null if value is not of expected type.
+ /**
+ * @return a vector of General names from a value that can be either a
+ * Vector of strings, string array or just a string. Returned
+ * Vector can be null if value is not of expected type.
*/
- public Vector<GeneralName> formGeneralNames(Object value)
- throws EBaseException {
+ public Vector<GeneralName> formGeneralNames(Object value)
+ throws EBaseException {
Vector<GeneralName> gns = new Vector<GeneralName>();
GeneralName gn = null;
@@ -513,7 +517,7 @@ public class GeneralNameUtil implements IGeneralNameUtil {
Object val = n.nextElement();
if (val != null && (val instanceof String) &&
- ((String) (val = ((String) val).trim())).length() > 0) {
+ ((String) (val = ((String) val).trim())).length() > 0) {
gn = formGeneralName(mGenNameChoice, (String) val);
gns.addElement(gn);
}
@@ -539,10 +543,7 @@ public class GeneralNameUtil implements IGeneralNameUtil {
}
/*
- public GeneralNameInterface getGeneralName() {
- return mGeneralName;
- }
-
+ * public GeneralNameInterface getGeneralName() { return mGeneralName; }
*/
public boolean isValueConfigured() {
return mIsValueConfigured;
@@ -553,7 +554,7 @@ public class GeneralNameUtil implements IGeneralNameUtil {
*/
public static void getDefaultParams(
- String name, boolean isValueConfigured, Vector<String> params) {
+ String name, boolean isValueConfigured, Vector<String> params) {
String nameDot = "";
if (name != null)
@@ -565,14 +566,14 @@ public class GeneralNameUtil implements IGeneralNameUtil {
}
/**
- * Get instance params
+ * Get instance params
*/
public void getInstanceParams(Vector<String> params) {
String value = (mValue == null) ? "" : mValue;
String choice = (mGenNameChoice == null) ? "" : mGenNameChoice;
params.addElement(mNameDotChoice + "=" + choice);
- if (mIsValueConfigured)
+ if (mIsValueConfigured)
params.addElement(mNameDotValue + "=" + value);
}
@@ -580,31 +581,30 @@ public class GeneralNameUtil implements IGeneralNameUtil {
* Get extended plugin info
*/
public static void getExtendedPluginInfo(
- String name, boolean isValueConfigured, Vector<String> info) {
+ String name, boolean isValueConfigured, Vector<String> info) {
String nameDot = "";
- if (name != null && name.length() > 0)
+ if (name != null && name.length() > 0)
nameDot = name + ".";
info.addElement(
- nameDot + PROP_GENNAME_CHOICE + ";" + GENNAME_CHOICE_INFO);
- if (isValueConfigured)
+ nameDot + PROP_GENNAME_CHOICE + ";" + GENNAME_CHOICE_INFO);
+ if (isValueConfigured)
info.addElement(
- nameDot + PROP_GENNAME_VALUE + ";" + GENNAME_VALUE_INFO);
+ nameDot + PROP_GENNAME_VALUE + ";" + GENNAME_VALUE_INFO);
}
}
-
/**
* convenience class for policies use.
*/
static public class GeneralNameAsConstraintsConfig extends GeneralNameConfig implements IGeneralNameAsConstraintsConfig {
-
+
public GeneralNameAsConstraintsConfig(
- String name,
- IConfigStore config,
- boolean isValueConfigured,
- boolean isPolicyEnabled)
- throws EBaseException {
+ String name,
+ IConfigStore config,
+ boolean isValueConfigured,
+ boolean isPolicyEnabled)
+ throws EBaseException {
super(name, config, isValueConfigured, isPolicyEnabled);
}
@@ -615,18 +615,17 @@ public class GeneralNameUtil implements IGeneralNameUtil {
/**
* Form a general name from the value string.
*/
- public GeneralName formGeneralName(String choice, String value)
- throws EBaseException {
+ public GeneralName formGeneralName(String choice, String value)
+ throws EBaseException {
return form_GeneralNameAsConstraints(choice, value);
}
}
-
public static class SubjAltNameGN extends GeneralNameUtil.GeneralNameConfig implements ISubjAltNameConfig {
static final String REQUEST_ATTR_INFO =
- "string;Request attribute name. " +
- "The value of the request attribute will be used to form a " +
- "General Name in the Subject Alternative Name extension.";
+ "string;Request attribute name. " +
+ "The value of the request attribute will be used to form a " +
+ "General Name in the Subject Alternative Name extension.";
static final String PROP_REQUEST_ATTR = "requestAttr";
@@ -635,8 +634,8 @@ public class GeneralNameUtil implements IGeneralNameUtil {
String mAttr = null;
public SubjAltNameGN(
- String name, IConfigStore config, boolean isPolicyEnabled)
- throws EBaseException {
+ String name, IConfigStore config, boolean isPolicyEnabled)
+ throws EBaseException {
super(name, config, false, isPolicyEnabled);
mRequestAttr = mConfig.getString(PROP_REQUEST_ATTR, null);
@@ -645,7 +644,7 @@ public class GeneralNameUtil implements IGeneralNameUtil {
mRequestAttr = "";
}
if (isPolicyEnabled && mRequestAttr.length() == 0) {
- throw new EPropertyNotFound(CMS.getUserMessage("CMS_BASE_GET_PROPERTY_FAILED",
+ throw new EPropertyNotFound(CMS.getUserMessage("CMS_BASE_GET_PROPERTY_FAILED",
mConfig.getName() + "." + PROP_REQUEST_ATTR));
}
int x = mRequestAttr.indexOf('.');
diff --git a/pki/base/common/src/com/netscape/cmscore/policy/GenericPolicyProcessor.java b/pki/base/common/src/com/netscape/cmscore/policy/GenericPolicyProcessor.java
index 2b4d012c..ea4fd499 100644
--- a/pki/base/common/src/com/netscape/cmscore/policy/GenericPolicyProcessor.java
+++ b/pki/base/common/src/com/netscape/cmscore/policy/GenericPolicyProcessor.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.policy;
-
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.StringTokenizer;
@@ -48,20 +47,17 @@ import com.netscape.cmscore.request.ARequestQueue;
import com.netscape.cmscore.util.AssertionException;
import com.netscape.cmscore.util.Debug;
-
/**
- * This is a Generic policy processor. The three main functions of
- * this class are:
- * 1. To initialize policies by reading policy configuration from the
- * config file, and maintain 5 sets of policies - viz Enrollment,
- * Renewal, Revocation and KeyRecovery and KeyArchival.
- * 2. To apply the configured policies on the given request.
- * 3. To enable policy listing/configuration via MCC console.
- *
- * Since the policy processor also implements the IPolicy interface
- * the processor itself presents itself as one big policy to the
- * request processor.
- *
+ * This is a Generic policy processor. The three main functions of this class
+ * are: 1. To initialize policies by reading policy configuration from the
+ * config file, and maintain 5 sets of policies - viz Enrollment, Renewal,
+ * Revocation and KeyRecovery and KeyArchival. 2. To apply the configured
+ * policies on the given request. 3. To enable policy listing/configuration via
+ * MCC console.
+ *
+ * Since the policy processor also implements the IPolicy interface the
+ * processor itself presents itself as one big policy to the request processor.
+ *
* @author kanda
* @version $Revision$, $Date$
*/
@@ -71,12 +67,12 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
protected IAuthority mAuthority = null;
// Default System Policies
- public final static String[] DEF_POLICIES =
- {"com.netscape.cms.policy.constraints.ManualAuthentication"};
+ public final static String[] DEF_POLICIES =
+ { "com.netscape.cms.policy.constraints.ManualAuthentication" };
// Policies that can't be deleted nor disabled.
public final static Hashtable<String, IExpression> DEF_UNDELETABLE_POLICIES =
- new Hashtable<String, IExpression>();
+ new Hashtable<String, IExpression>();
private String mId = "Policy";
private Vector<String> mPolicyOrder = new Vector<String>();
@@ -125,9 +121,9 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
}
/**
- * Returns the configuration store.
+ * Returns the configuration store.
* <P>
- *
+ *
* @return configuration store
*/
public IConfigStore getConfigStore() {
@@ -137,24 +133,24 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
/**
* Initializes the PolicyProcessor
* <P>
- *
+ *
* @param owner owner of this subsystem
* @param config configuration of this subsystem
* @exception EBaseException failed to initialize this Subsystem.
*/
public synchronized void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
// Debug.trace("GenericPolicyProcessor::init");
CMS.debug("GenericPolicyProcessor::init begins");
mAuthority = (IAuthority) owner;
mConfig = config;
- mGlobalStore =
+ mGlobalStore =
SubsystemRegistry.getInstance().get("MAIN").getConfigStore();
try {
IConfigStore configStore = CMS.getConfigStore();
- String PKI_Subsystem = configStore.getString( "subsystem.0.id",
- null );
+ String PKI_Subsystem = configStore.getString("subsystem.0.id",
+ null);
// CMS 6.1 began utilizing the "Certificate Profiles" framework
// instead of the legacy "Certificate Policies" framework.
@@ -164,34 +160,34 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
// that this legacy "Certificate Policies" framework would be
// deprecated and disabled by default (see Bugzilla Bug #472597).
//
- // NOTE: The "Certificate Policies" framework ONLY applied to
- // to CA, KRA, and legacy RA (pre-CMS 7.0) subsystems.
+ // NOTE: The "Certificate Policies" framework ONLY applied to
+ // to CA, KRA, and legacy RA (pre-CMS 7.0) subsystems.
//
- if( PKI_Subsystem.trim().equalsIgnoreCase( "ca" ) ||
- PKI_Subsystem.trim().equalsIgnoreCase( "kra" ) ) {
+ if (PKI_Subsystem.trim().equalsIgnoreCase("ca") ||
+ PKI_Subsystem.trim().equalsIgnoreCase("kra")) {
String policyStatus = PKI_Subsystem.trim().toLowerCase()
+ "." + "Policy"
+ "." + IPolicyProcessor.PROP_ENABLE;
- if( configStore.getBoolean( policyStatus, true ) == true ) {
- // NOTE: If "<subsystem>.Policy.enable=<boolean>" is
- // missing, then the referenced instance existed
- // prior to this name=value pair existing in its
- // 'CS.cfg' file, and thus we err on the
- // side that the user may still need to
- // use the policy framework.
- CMS.debug( "GenericPolicyProcessor::init Certificate "
+ if (configStore.getBoolean(policyStatus, true) == true) {
+ // NOTE: If "<subsystem>.Policy.enable=<boolean>" is
+ // missing, then the referenced instance existed
+ // prior to this name=value pair existing in its
+ // 'CS.cfg' file, and thus we err on the
+ // side that the user may still need to
+ // use the policy framework.
+ CMS.debug("GenericPolicyProcessor::init Certificate "
+ "Policy Framework (deprecated) "
- + "is ENABLED" );
+ + "is ENABLED");
} else {
- // CS 8.1 Default: <subsystem>.Policy.enable=false
- CMS.debug( "GenericPolicyProcessor::init Certificate "
+ // CS 8.1 Default: <subsystem>.Policy.enable=false
+ CMS.debug("GenericPolicyProcessor::init Certificate "
+ "Policy Framework (deprecated) "
- + "is DISABLED" );
+ + "is DISABLED");
return;
}
}
- } catch( EBaseException e ) {
+ } catch (EBaseException e) {
throw e;
}
@@ -225,16 +221,16 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_SYSTEM_POLICY_CONFIG_ERROR", clPath));
- // Verify if the class is a valid implementation of
- // IPolicyRule
+ // Verify if the class is a valid implementation of
+ // IPolicyRule
try {
Object o = Class.forName(clPath).newInstance();
if (!(o instanceof IEnrollmentPolicy) &&
- !(o instanceof IRenewalPolicy) &&
- !(o instanceof IRevocationPolicy) &&
- !(o instanceof IKeyRecoveryPolicy) &&
- !(o instanceof IKeyArchivalPolicy))
+ !(o instanceof IRenewalPolicy) &&
+ !(o instanceof IRevocationPolicy) &&
+ !(o instanceof IKeyRecoveryPolicy) &&
+ !(o instanceof IKeyArchivalPolicy))
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_INVALID_POLICY_IMPL", clPath));
} catch (EBaseException e) {
@@ -247,7 +243,7 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
// Register the implementation.
RegisteredPolicy regPolicy =
- new RegisteredPolicy(id, clPath);
+ new RegisteredPolicy(id, clPath);
mImplTable.put(id, regPolicy);
}
@@ -291,7 +287,7 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
String enabledStr = c.getString(PROP_ENABLE, null);
if (enabledStr == null || enabledStr.trim().length() == 0 ||
- enabledStr.trim().equalsIgnoreCase("true"))
+ enabledStr.trim().equalsIgnoreCase("true"))
enabled = true;
else
enabled = false;
@@ -304,15 +300,15 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
// Make an instance of the specified policy.
RegisteredPolicy regPolicy =
- (RegisteredPolicy) mImplTable.get(implName);
+ (RegisteredPolicy) mImplTable.get(implName);
if (regPolicy == null) {
- String[] params = {implName, instanceName};
+ String[] params = { implName, instanceName };
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_IMPL_NOT_FOUND", params));
}
-
+
String classpath = regPolicy.getClassPath();
try {
@@ -323,7 +319,7 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
rule.init(this, c);
} catch (Throwable e) {
mAuthority.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_POLICY_INIT_FAILED", instanceName, e.toString()));
- // disable rule initialized if there is
+ // disable rule initialized if there is
// configuration error
enabled = false;
c.putString(PROP_ENABLE, "false");
@@ -332,8 +328,8 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
if (rule == null)
continue;
- // Read the predicate expression if any associated
- // with the rule
+ // Read the predicate expression if any associated
+ // with the rule
String exp = c.getString(GenericPolicyProcessor.PROP_PREDICATE, null);
if (exp != null)
@@ -345,13 +341,13 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
// Add the rule to the instance table
mInstanceTable.put(instanceName,
- new PolicyInstance(instanceName, implName, rule, enabled));
+ new PolicyInstance(instanceName, implName, rule, enabled));
if (!enabled)
continue;
- // Add the rule to the policy set according to category if a
- // rule is enabled.
+ // Add the rule to the policy set according to category if a
+ // rule is enabled.
addRule(instanceName, rule);
}
@@ -372,8 +368,8 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
/**
* Apply policies on the given request.
- *
- * @param IRequest The given request
+ *
+ * @param IRequest The given request
* @return The policy result object.
*/
public PolicyResult apply(IRequest req) {
@@ -383,18 +379,19 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
CMS.debug("GenericPolicyProcessor: apply begins");
if (op == null) {
CMS.debug("GenericPolicyProcessor: apply op null");
- // throw new AssertionException("Missing operation type in request. Can't happen!");
- // Return ACCEPTED for now. Looks like even get CA chain
- // is being passed in here with request type set elsewhere
- // on the request.
+ // throw new
+ // AssertionException("Missing operation type in request. Can't happen!");
+ // Return ACCEPTED for now. Looks like even get CA chain
+ // is being passed in here with request type set elsewhere
+ // on the request.
return PolicyResult.ACCEPTED;
}
if (isProfileRequest(req)) {
- Debug.trace("GenericPolicyProcessor: Profile-base Request " +
- req.getRequestId().toString());
+ Debug.trace("GenericPolicyProcessor: Profile-base Request " +
+ req.getRequestId().toString());
return PolicyResult.ACCEPTED;
}
- CMS.debug("GenericPolicyProcessor: apply not ProfileRequest. op="+op);
+ CMS.debug("GenericPolicyProcessor: apply not ProfileRequest. op=" + op);
if (op.equalsIgnoreCase(IRequest.ENROLLMENT_REQUEST))
rules = mEnrollmentRules;
@@ -409,7 +406,8 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
else {
// It aint' a CMP request. We don't care.
return PolicyResult.ACCEPTED;
- // throw new AssertionException("Invalid request type. Can't Happen!");
+ // throw new
+ // AssertionException("Invalid request type. Can't Happen!");
}
// ((PolicySet)rules).printPolicies();
@@ -421,11 +419,11 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
return PolicyResult.ACCEPTED;
/**
- setError(req, PolicyResources.NO_RULES_CONFIGURED, op);
- return PolicyResult.REJECTED;
+ * setError(req, PolicyResources.NO_RULES_CONFIGURED, op); return
+ * PolicyResult.REJECTED;
**/
}
- CMS.debug("GenericPolicyProcessor: apply: rules.count="+ rules.count());
+ CMS.debug("GenericPolicyProcessor: apply: rules.count=" + rules.count());
// request must be up to date or can't process it.
PolicyResult res = PolicyResult.ACCEPTED;
@@ -466,11 +464,11 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
try {
while (enum1.hasMoreElements()) {
RegisteredPolicy regPolicy =
- (RegisteredPolicy) enum1.nextElement();
+ (RegisteredPolicy) enum1.nextElement();
// Make an Instance of it
IPolicyRule ruleImpl = (IPolicyRule)
- Class.forName(regPolicy.getClassPath()).newInstance();
+ Class.forName(regPolicy.getClassPath()).newInstance();
impls.addElement(ruleImpl);
}
@@ -489,7 +487,7 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
try {
while (enum1.hasMoreElements()) {
RegisteredPolicy regPolicy =
- (RegisteredPolicy) enum1.nextElement();
+ (RegisteredPolicy) enum1.nextElement();
impls.addElement(regPolicy.getId());
@@ -503,7 +501,7 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
public IPolicyRule getPolicyImpl(String id) {
RegisteredPolicy regImpl = (RegisteredPolicy)
- mImplTable.get(id);
+ mImplTable.get(id);
if (regImpl == null)
return null;
@@ -523,7 +521,7 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
if (rp == null)
return null;
- Vector<String> v = rp.getDefaultParams();
+ Vector<String> v = rp.getDefaultParams();
if (v == null)
v = new Vector<String>();
@@ -533,16 +531,16 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
}
public void deletePolicyImpl(String id)
- throws EBaseException {
+ throws EBaseException {
// First check if the id is valid;
RegisteredPolicy regPolicy =
- (RegisteredPolicy) mImplTable.get(id);
+ (RegisteredPolicy) mImplTable.get(id);
if (regPolicy == null)
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_NO_POLICY_IMPL", id));
- // If any instance exists for this impl, can't delete it.
+ // If any instance exists for this impl, can't delete it.
boolean instanceExist = false;
Enumeration<PolicyInstance> e = mInstanceTable.elements();
@@ -558,12 +556,12 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_ACTIVE_POLICY_RULES_EXIST", id));
- // Else delete the implementation
+ // Else delete the implementation
mImplTable.remove(id);
- IConfigStore policyStore =
- mGlobalStore.getSubStore(getPolicySubstoreId());
- IConfigStore implStore =
- policyStore.getSubStore(PROP_IMPL);
+ IConfigStore policyStore =
+ mGlobalStore.getSubStore(getPolicySubstoreId());
+ IConfigStore implStore =
+ policyStore.getSubStore(PROP_IMPL);
implStore.removeSubStore(id);
@@ -572,7 +570,7 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
mGlobalStore.commit(true);
} catch (Exception ex) {
Debug.printStackTrace(ex);
- String[] params = {"implementation", id};
+ String[] params = { "implementation", id };
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_DELETING_POLICY_ERROR", params));
@@ -580,49 +578,49 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
}
public void addPolicyImpl(String id, String classPath)
- throws EBaseException {
+ throws EBaseException {
// See if the id is unique
if (mImplTable.containsKey(id))
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_DUPLICATE_IMPL_ID", id));
- // See if the classPath is ok
+ // See if the classPath is ok
Object impl = null;
try {
impl = Class.forName(classPath).newInstance();
- }catch (Exception e) {
+ } catch (Exception e) {
throw new EPolicyException(CMS.getUserMessage("CMS_POLICY_NO_POLICY_IMPL",
id));
}
// Does the class implement one of the four interfaces?
if (!(impl instanceof IEnrollmentPolicy) &&
- !(impl instanceof IRenewalPolicy) &&
- !(impl instanceof IRevocationPolicy) &&
- !(impl instanceof IKeyRecoveryPolicy) &&
- !(impl instanceof IKeyArchivalPolicy))
+ !(impl instanceof IRenewalPolicy) &&
+ !(impl instanceof IRevocationPolicy) &&
+ !(impl instanceof IKeyRecoveryPolicy) &&
+ !(impl instanceof IKeyArchivalPolicy))
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_INVALID_POLICY_IMPL", classPath));
- // Add the implementation to the registry
+ // Add the implementation to the registry
RegisteredPolicy regPolicy =
- new RegisteredPolicy(id, classPath);
+ new RegisteredPolicy(id, classPath);
mImplTable.put(id, regPolicy);
// Store the impl in the configuration.
- IConfigStore policyStore =
- mGlobalStore.getSubStore(getPolicySubstoreId());
- IConfigStore implStore =
- policyStore.getSubStore(PROP_IMPL);
+ IConfigStore policyStore =
+ mGlobalStore.getSubStore(getPolicySubstoreId());
+ IConfigStore implStore =
+ policyStore.getSubStore(PROP_IMPL);
IConfigStore newStore = implStore.makeSubStore(id);
newStore.put(PROP_CLASS, classPath);
try {
mGlobalStore.commit(true);
} catch (Exception e) {
- String[] params = {"implementation", id};
+ String[] params = { "implementation", id };
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_ADDING_POLICY_ERROR", params));
@@ -637,7 +635,7 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
try {
while (enum1.hasMoreElements()) {
PolicyInstance instance =
- (PolicyInstance) mInstanceTable.get((String) enum1.nextElement());
+ (PolicyInstance) mInstanceTable.get((String) enum1.nextElement());
rules.addElement(instance.getRule());
@@ -669,14 +667,14 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
public IPolicyRule getPolicyInstance(String id) {
PolicyInstance policyInstance = (PolicyInstance)
- mInstanceTable.get(id);
+ mInstanceTable.get(id);
return (policyInstance == null) ? null : policyInstance.getRule();
}
public Vector<String> getPolicyInstanceConfig(String id) {
PolicyInstance policyInstance = (PolicyInstance)
- mInstanceTable.get(id);
+ mInstanceTable.get(id);
if (policyInstance == null)
return null;
@@ -695,24 +693,24 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
}
public void deletePolicyInstance(String id)
- throws EBaseException {
+ throws EBaseException {
// If the rule is a persistent rule, we can't delete it.
if (mUndeletablePolicies.containsKey(id))
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_CANT_DELETE_PERSISTENT_POLICY", id));
- // First check if the instance is present.
+ // First check if the instance is present.
PolicyInstance instance =
- (PolicyInstance) mInstanceTable.get(id);
+ (PolicyInstance) mInstanceTable.get(id);
if (instance == null)
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_INVALID_POLICY_INSTANCE", id));
IConfigStore policyStore =
- mGlobalStore.getSubStore(getPolicySubstoreId());
- IConfigStore instanceStore =
- policyStore.getSubStore(PROP_RULE);
+ mGlobalStore.getSubStore(getPolicySubstoreId());
+ IConfigStore instanceStore =
+ policyStore.getSubStore(PROP_RULE);
instanceStore.removeSubStore(id);
@@ -732,7 +730,7 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
mPolicyOrder.insertElementAt(id, index);
Debug.printStackTrace(e);
- String[] params = {"instance", id};
+ String[] params = { "instance", id };
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_DELETING_POLICY_ERROR", params));
@@ -751,17 +749,17 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
if (rule instanceof IKeyArchivalPolicy)
mKeyArchivalRules.removeRule(id);
- // Delete the instance
+ // Delete the instance
mInstanceTable.remove(id);
}
public void addPolicyInstance(String id, Hashtable<String, String> ht)
- throws EBaseException {
+ throws EBaseException {
// The instance id should be unique
if (getPolicyInstance(id) != null)
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_DUPLICATE_INST_ID", id));
- // There should be an implmentation for this rule.
+ // There should be an implmentation for this rule.
String implName = (String) ht.get(IPolicyRule.PROP_IMPLNAME);
// See if there is an implementation with this name.
@@ -771,23 +769,23 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_NO_POLICY_IMPL", implName));
- // Prepare config file entries.
- IConfigStore policyStore =
- mGlobalStore.getSubStore(getPolicySubstoreId());
- IConfigStore instanceStore =
- policyStore.getSubStore(PROP_RULE);
+ // Prepare config file entries.
+ IConfigStore policyStore =
+ mGlobalStore.getSubStore(getPolicySubstoreId());
+ IConfigStore instanceStore =
+ policyStore.getSubStore(PROP_RULE);
IConfigStore newStore = instanceStore.makeSubStore(id);
for (Enumeration<String> keys = ht.keys(); keys.hasMoreElements();) {
String key = keys.nextElement();
- String val = ht.get(key);
+ String val = ht.get(key);
newStore.put(key, val);
}
// Set the order string.
policyStore.put(PROP_ORDER,
- getRuleOrderString(mPolicyOrder, id));
+ getRuleOrderString(mPolicyOrder, id));
// Try to initialize this rule.
rule.init(this, newStore);
@@ -797,10 +795,10 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
boolean active = false;
if (enabledStr == null || enabledStr.trim().length() == 0 ||
- enabledStr.equalsIgnoreCase("true"))
+ enabledStr.equalsIgnoreCase("true"))
active = true;
- // Set the predicate if any present on the rule.
+ // Set the predicate if any present on the rule.
String predicate = ((String) ht.get(IPolicyRule.PROP_PREDICATE)).trim();
IExpression exp = null;
@@ -812,7 +810,7 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
try {
mGlobalStore.commit(true);
} catch (Exception e) {
- String[] params = {"instance", id};
+ String[] params = { "instance", id };
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_ADDING_POLICY_ERROR", params));
@@ -835,10 +833,10 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
}
public void modifyPolicyInstance(String id, Hashtable<String, String> ht)
- throws EBaseException {
+ throws EBaseException {
// The instance id should be there already
PolicyInstance policyInstance = (PolicyInstance)
- mInstanceTable.get(id);
+ mInstanceTable.get(id);
if (policyInstance == null)
throw new EPolicyException(
@@ -851,38 +849,38 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
if (!implId.equals(policyInstance.getImplId()))
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_IMPLCHANGE_ERROR", id));
-
- // Make a new rule instance
+
+ // Make a new rule instance
IPolicyRule newRule = getPolicyImpl(implId);
if (newRule == null) // Can't happen, but just in case..
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_INVALID_POLICY_IMPL", implId));
-
- // Try to init this rule.
- IConfigStore policyStore =
- mGlobalStore.getSubStore(getPolicySubstoreId());
- IConfigStore instanceStore =
- policyStore.getSubStore(PROP_RULE);
+
+ // Try to init this rule.
+ IConfigStore policyStore =
+ mGlobalStore.getSubStore(getPolicySubstoreId());
+ IConfigStore instanceStore =
+ policyStore.getSubStore(PROP_RULE);
IConfigStore oldStore = instanceStore.getSubStore(id);
IConfigStore newStore = new PropConfigStore(id);
-
+
// See if the rule is disabled.
String enabledStr = (String) ht.get(IPolicyRule.PROP_ENABLE);
boolean active = false;
if (enabledStr == null || enabledStr.trim().length() == 0 ||
- enabledStr.equalsIgnoreCase("true"))
+ enabledStr.equalsIgnoreCase("true"))
active = true;
- // Set the predicate expression.
+ // Set the predicate expression.
String predicate = ((String) ht.get(IPolicyRule.PROP_PREDICATE)).trim();
IExpression exp = null;
if (predicate.trim().length() > 0)
exp = PolicyPredicateParser.parse(predicate.trim());
- // See if this a persistent rule.
+ // See if this a persistent rule.
if (mUndeletablePolicies.containsKey(id)) {
// A persistent rule can't be disabled.
if (!active) {
@@ -891,24 +889,24 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
}
IExpression defPred = (IExpression)
- mUndeletablePolicies.get(id);
+ mUndeletablePolicies.get(id);
if (defPred == SimpleExpression.NULL_EXPRESSION)
defPred = null;
if (exp == null && defPred != null) {
- String[] params = {id, defPred.toString(),
+ String[] params = { id, defPred.toString(),
"null" };
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_PERSISTENT_RULE_MISCONFIG", params));
} else if (exp != null && defPred == null) {
- String[] params = {id, "null", exp.toString()};
+ String[] params = { id, "null", exp.toString() };
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_PERSISTENT_RULE_MISCONFIG", params));
} else if (exp != null && defPred != null) {
if (!defPred.toString().equals(exp.toString())) {
- String[] params = {id, defPred.toString(),
+ String[] params = { id, defPred.toString(),
exp.toString() };
throw new EPolicyException(
@@ -920,9 +918,8 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
// Predicate for the persistent rule can't be changed.
ht.put(IPolicyRule.PROP_ENABLE, String.valueOf(active));
- // put old config store parameters first.
- for (Enumeration<String> oldkeys = oldStore.keys();
- oldkeys.hasMoreElements();) {
+ // put old config store parameters first.
+ for (Enumeration<String> oldkeys = oldStore.keys(); oldkeys.hasMoreElements();) {
String k = (String) oldkeys.nextElement();
String v = (String) oldStore.getString(k);
@@ -930,15 +927,14 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
}
// put modified params.
- for (Enumeration<String> newkeys = ht.keys();
- newkeys.hasMoreElements();) {
+ for (Enumeration<String> newkeys = ht.keys(); newkeys.hasMoreElements();) {
String k = (String) newkeys.nextElement();
String v = (String) ht.get(k);
Debug.trace("newstore key " + k + "=" + v);
if (v != null) {
if (!k.equals(Constants.OP_TYPE) && !k.equals(Constants.OP_SCOPE) &&
- !k.equals(Constants.RS_ID) && !k.equals("RULENAME")) {
+ !k.equals(Constants.RS_ID) && !k.equals("RULENAME")) {
Debug.trace("newstore.put(" + k + "=" + v + ")");
newStore.put(k, v);
}
@@ -948,19 +944,15 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
// include impl default params in case we missed any.
/*
- for (Enumeration keys = ht.keys(); keys.hasMoreElements();)
- {
- String key = (String)keys.nextElement();
- String val = (String)ht.get(key);
- newStore.put(key, val);
- }
+ * for (Enumeration keys = ht.keys(); keys.hasMoreElements();) { String
+ * key = (String)keys.nextElement(); String val = (String)ht.get(key);
+ * newStore.put(key, val); }
*/
-
// Try to initialize this rule.
newRule.init(this, newStore);
-
- // If we are successfully initialized, replace the rule
+
+ // If we are successfully initialized, replace the rule
// instance
policyInstance.setRule(newRule);
policyInstance.setActive(active);
@@ -969,21 +961,21 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
if (exp != null)
newRule.setPredicate(exp);
- // Store the changes in the file.
+ // Store the changes in the file.
try {
for (Enumeration<String> e = newStore.keys(); e.hasMoreElements();) {
String key = (String) e.nextElement();
if (key != null) {
Debug.trace(
- "oldstore.put(" + key + "," +
- (String) newStore.getString(key) + ")");
+ "oldstore.put(" + key + "," +
+ (String) newStore.getString(key) + ")");
oldStore.put(key, (String) newStore.getString(key));
}
}
mGlobalStore.commit(true);
} catch (Exception e) {
- String[] params = {"instance", id};
+ String[] params = { "instance", id };
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_ADDING_POLICY_ERROR", params));
@@ -1018,8 +1010,8 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
}
public synchronized void changePolicyInstanceOrdering(
- String policyOrderStr)
- throws EBaseException {
+ String policyOrderStr)
+ throws EBaseException {
Vector<String> policyOrder = new Vector<String>();
StringTokenizer tokens = new StringTokenizer(policyOrderStr, ",");
@@ -1053,9 +1045,9 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
String defRuleName = mSystemDefaults[i].substring(
mSystemDefaults[i].lastIndexOf('.') + 1);
IPolicyRule defRule = (IPolicyRule)
- Class.forName(mSystemDefaults[i]).newInstance();
- IConfigStore ruleConfig =
- mConfig.getSubStore(PROP_DEF_POLICIES + "." + defRuleName);
+ Class.forName(mSystemDefaults[i]).newInstance();
+ IConfigStore ruleConfig =
+ mConfig.getSubStore(PROP_DEF_POLICIES + "." + defRuleName);
defRule.init(this, ruleConfig);
if (defRule instanceof IEnrollmentPolicy)
@@ -1072,7 +1064,7 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
}
} catch (Throwable e) {
Debug.printStackTrace(e);
- EBaseException ex = new EBaseException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR",
+ EBaseException ex = new EBaseException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR",
"Cannot create default policy rule. Error: " + e.getMessage()));
mAuthority.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_POLICY_DEF_CREATE", e.toString()));
@@ -1080,17 +1072,16 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
}
// add rules specified in the new order.
- for (Enumeration<String> enum1 = policyOrder.elements();
- enum1.hasMoreElements();) {
+ for (Enumeration<String> enum1 = policyOrder.elements(); enum1.hasMoreElements();) {
String instanceName = (String) enum1.nextElement();
PolicyInstance pInstance = (PolicyInstance)
- mInstanceTable.get(instanceName);
-
+ mInstanceTable.get(instanceName);
+
if (!pInstance.isActive())
continue;
- // Add the rule to the policy set according to category if a
- // rule is enabled.
+ // Add the rule to the policy set according to category if a
+ // rule is enabled.
IPolicyRule rule = pInstance.getRule();
if (rule instanceof IEnrollmentPolicy)
@@ -1114,8 +1105,8 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
mPolicyOrder = policyOrder;
// Now change the ordering in the config file.
- IConfigStore policyStore =
- mGlobalStore.getSubStore(getPolicySubstoreId());
+ IConfigStore policyStore =
+ mGlobalStore.getSubStore(getPolicySubstoreId());
policyStore.put(PROP_ORDER, policyOrderStr);
@@ -1163,37 +1154,37 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
}
/**
- * Initializes the default system policies. Currently there is only
- * one policy - ManualAuthentication. More may be added later on.
- *
- * The default policies may be disabled - for example to over-ride
- * agent approval for testing the system by setting the following
- * property in the config file:
+ * Initializes the default system policies. Currently there is only one
+ * policy - ManualAuthentication. More may be added later on.
+ *
+ * The default policies may be disabled - for example to over-ride agent
+ * approval for testing the system by setting the following property in the
+ * config file:
+ *
+ * <subsystemId>.Policy.systemPolicies.enable=false
*
- * <subsystemId>.Policy.systemPolicies.enable=false
+ * By default the value for this property is true.
*
- * By default the value for this property is true.
- *
- * Users can over-ride the default system policies by listing their
- * 'custom' system policies under the following property:
+ * Users can over-ride the default system policies by listing their 'custom'
+ * system policies under the following property:
*
- * <subsystemId>.Policy.systemPolicies=<system policy1 class path>,
- * <system policy2 class path>
- *
- * There can only be one instance of the system policy in the system
- * and will apply to all requests, and hence predicates are not used
- * for a system policy. Due to the same reason, these properties are
- * not configurable using the Console.
+ * <subsystemId>.Policy.systemPolicies=<system policy1 class path>, <system
+ * policy2 class path>
+ *
+ * There can only be one instance of the system policy in the system and
+ * will apply to all requests, and hence predicates are not used for a
+ * system policy. Due to the same reason, these properties are not
+ * configurable using the Console.
*
* A System policy may read config properties from a subtree under
* <subsystemId>.Policy.systemPolicies.<ClassName>. An example is
* ra.Policy.systemPolicies.ManualAuthentication.param1=value
*/
private void initSystemPolicies(IConfigStore mConfig)
- throws EBaseException {
+ throws EBaseException {
// If system policies are disabled, return. No Deferral of
// requests may be done.
- String enable = mConfig.getString(PROP_DEF_POLICIES + "." +
+ String enable = mConfig.getString(PROP_DEF_POLICIES + "." +
PROP_ENABLE, "true").trim();
if (enable.equalsIgnoreCase("false")) {
@@ -1202,17 +1193,17 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
}
// Load default policies that are always present.
- String configuredDefaults = mConfig.getString(PROP_DEF_POLICIES,
+ String configuredDefaults = mConfig.getString(PROP_DEF_POLICIES,
null);
- if (configuredDefaults == null ||
- configuredDefaults.trim().length() == 0)
+ if (configuredDefaults == null ||
+ configuredDefaults.trim().length() == 0)
mSystemDefaults = DEF_POLICIES;
else {
Vector<String> rules = new Vector<String>();
- StringTokenizer tokenizer = new
- StringTokenizer(configuredDefaults.trim(), ",");
-
+ StringTokenizer tokenizer = new
+ StringTokenizer(configuredDefaults.trim(), ",");
+
while (tokenizer.hasMoreTokens()) {
String rule = tokenizer.nextToken().trim();
@@ -1221,11 +1212,11 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
if (rules.size() > 0) {
mSystemDefaults = new String[rules.size()];
rules.copyInto(mSystemDefaults);
- } else
+ } else
mSystemDefaults = DEF_POLICIES;
}
-
- // Now Initialize the rules. These defaults have only one
+
+ // Now Initialize the rules. These defaults have only one
// instance and the rule name is the name of the class itself.
// Any configuration parameters required could be read from
// <subsystemId>.Policy.default.RuleName.
@@ -1239,16 +1230,16 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
Object o = Class.forName(mSystemDefaults[i]).newInstance();
if (!(o instanceof IEnrollmentPolicy) &&
- !(o instanceof IRenewalPolicy) &&
- !(o instanceof IRevocationPolicy) &&
- !(o instanceof IKeyRecoveryPolicy) &&
- !(o instanceof IKeyArchivalPolicy))
+ !(o instanceof IRenewalPolicy) &&
+ !(o instanceof IRevocationPolicy) &&
+ !(o instanceof IKeyRecoveryPolicy) &&
+ !(o instanceof IKeyArchivalPolicy))
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_INVALID_POLICY_IMPL",
- mSystemDefaults[i]));
-
+ mSystemDefaults[i]));
+
IPolicyRule rule = (IPolicyRule) o;
-
+
// Initialize the rule.
ruleName = mSystemDefaults[i].substring(
mSystemDefaults[i].lastIndexOf('.') + 1);
@@ -1256,116 +1247,113 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
PROP_DEF_POLICIES + "." + ruleName);
rule.init(this, ruleConfig);
-
+
// Add the rule to the appropriate PolicySet.
addRule(ruleName, rule);
} catch (EBaseException e) {
throw e;
} catch (Exception e) {
Debug.printStackTrace(e);
- throw new EPolicyException(CMS.getUserMessage("CMS_POLICY_NO_POLICY_IMPL",
+ throw new EPolicyException(CMS.getUserMessage("CMS_POLICY_NO_POLICY_IMPL",
ruleName));
}
}
}
/**
- * Read list of undeletable policies if any configured in the
- * system.
- *
- * These are required to protect the system from being misconfigured
- * to the point that the requests wouldn't serialize or certain
- * fields in the certificate(s) being checked will go unchecked
- * ..etc.
- *
- * For now the following policies are undeletable:
- *
- * DirAuthRule: This is a default DirectoryAuthentication policy
- * for user certificates that interprets directory
- * credentials. The presence of this policy is needed
- * if the OOTB DirectoryAuthentication-based automatic
- * certificate issuance is supported.
- *
- * DefaultUserNameRule: This policy verifies/sets subjectDn for user
- * certificates.
- *
- * DefaultServerNameRule: This policy verifies/sets subjectDn for
- * server certificates.
- *
- * DefaultValidityRule: Verifies/sets validty for all certificates.
- *
- * DefaultRenewalValidityRule: Verifies/sets validity for certs being
- * renewed.
- *
- * The 'undeletables' cannot be deleted from the config file, nor
- * can the be disabled. If any predicates are associated with them
- * the predicates can't be changed either. But, other config parameters
- * such as maxValidity, renewalInterval ..etc can be changed to suit
- * local policy requirements.
- *
- * During start up the policy processor will verify if the undeletables
- * are present, and that they are enabled and that their predicates are
- * not changed.
- *
- * The rules mentioned above are currently hard coded. If these need to
- * read from the config file, the 'undeletables' can be configured as
- * as follows:
- *
- * <subsystemId>.Policy.undeletablePolicies=<comma separated rule names>
- * Example:
- * ra.Policy.undeletablePolicies=DirAuthRule, DefaultUserNameRule, DefaultServerNameRule, DefaultValidityRule, DefaultRenewalValidityRule
- *
- * The predicates if any associated with them may be configured as
- * follows:
- * <subsystemId>.Policy.undeletablePolicies.DirAuthRule.predicate= certType == client.
- *
- * where subsystemId is ra or ca.
- *
+ * Read list of undeletable policies if any configured in the system.
+ *
+ * These are required to protect the system from being misconfigured to the
+ * point that the requests wouldn't serialize or certain fields in the
+ * certificate(s) being checked will go unchecked ..etc.
+ *
+ * For now the following policies are undeletable:
+ *
+ * DirAuthRule: This is a default DirectoryAuthentication policy for user
+ * certificates that interprets directory credentials. The presence of this
+ * policy is needed if the OOTB DirectoryAuthentication-based automatic
+ * certificate issuance is supported.
+ *
+ * DefaultUserNameRule: This policy verifies/sets subjectDn for user
+ * certificates.
+ *
+ * DefaultServerNameRule: This policy verifies/sets subjectDn for server
+ * certificates.
+ *
+ * DefaultValidityRule: Verifies/sets validty for all certificates.
+ *
+ * DefaultRenewalValidityRule: Verifies/sets validity for certs being
+ * renewed.
+ *
+ * The 'undeletables' cannot be deleted from the config file, nor can the be
+ * disabled. If any predicates are associated with them the predicates can't
+ * be changed either. But, other config parameters such as maxValidity,
+ * renewalInterval ..etc can be changed to suit local policy requirements.
+ *
+ * During start up the policy processor will verify if the undeletables are
+ * present, and that they are enabled and that their predicates are not
+ * changed.
+ *
+ * The rules mentioned above are currently hard coded. If these need to read
+ * from the config file, the 'undeletables' can be configured as as follows:
+ *
+ * <subsystemId>.Policy.undeletablePolicies=<comma separated rule names>
+ * Example: ra.Policy.undeletablePolicies=DirAuthRule, DefaultUserNameRule,
+ * DefaultServerNameRule, DefaultValidityRule, DefaultRenewalValidityRule
+ *
+ * The predicates if any associated with them may be configured as follows:
+ * <subsystemId>.Policy.undeletablePolicies.DirAuthRule.predicate= certType
+ * == client.
+ *
+ * where subsystemId is ra or ca.
+ *
* If the undeletables are configured in the file,the configured entries
- * take precedence over the hardcoded ones in this file. If you are
- * configuring them in the file, please remember to configure the
- * predicates if applicable.
- *
- * During policy configuration from MCC, the policy processor will not
- * let you delete an 'undeletable', nor will it let you disable it.
- * You will not be able to change the predicate either. Other parameters
- * can be configured as needed.
- *
- * If a particular rule needs to be removed from the 'undeletables',
- * either remove it from the hard coded list above, or configure the
- * rules required rules only via the config file. The former needs
- * recompilation of the source. The later is flexible to be able to
- * make any rule an 'undeletable' or nor an 'undeletable'.
- *
- * Example: We want to use only manual forms for enrollment.
- * We do n't need to burn in DirAuthRule. We need to configure all
- * other rules except the DirAuthRule as follows:
- *
- * ra.Policy.undeletablePolicies = DefaultUserNameRule, DefaultServerNameRule, DefaultValidityRule, DefaultRenewalValidityRule
- *
+ * take precedence over the hardcoded ones in this file. If you are
+ * configuring them in the file, please remember to configure the predicates
+ * if applicable.
+ *
+ * During policy configuration from MCC, the policy processor will not let
+ * you delete an 'undeletable', nor will it let you disable it. You will not
+ * be able to change the predicate either. Other parameters can be
+ * configured as needed.
+ *
+ * If a particular rule needs to be removed from the 'undeletables', either
+ * remove it from the hard coded list above, or configure the rules required
+ * rules only via the config file. The former needs recompilation of the
+ * source. The later is flexible to be able to make any rule an
+ * 'undeletable' or nor an 'undeletable'.
+ *
+ * Example: We want to use only manual forms for enrollment. We do n't need
+ * to burn in DirAuthRule. We need to configure all other rules except the
+ * DirAuthRule as follows:
+ *
+ * ra.Policy.undeletablePolicies = DefaultUserNameRule,
+ * DefaultServerNameRule, DefaultValidityRule, DefaultRenewalValidityRule
+ *
* The following predicates are necessary:
- *
- * ra.Policy.undeletablePolicies.DefaultUserNameRule.predicate = certType == client
- * ra.Policy.undeletablePolicies.DefaultServerNameRule.predicate = certType == server
- *
- * The other two rules do not have any predicates.
+ *
+ * ra.Policy.undeletablePolicies.DefaultUserNameRule.predicate = certType ==
+ * client ra.Policy.undeletablePolicies.DefaultServerNameRule.predicate =
+ * certType == server
+ *
+ * The other two rules do not have any predicates.
*/
private void initUndeletablePolicies(IConfigStore mConfig)
- throws EBaseException {
+ throws EBaseException {
// Read undeletable policies if any configured.
- String configuredUndeletables =
- mConfig.getString(PROP_UNDELETABLE_POLICIES, null);
+ String configuredUndeletables =
+ mConfig.getString(PROP_UNDELETABLE_POLICIES, null);
- if (configuredUndeletables == null ||
- configuredUndeletables.trim().length() == 0) {
+ if (configuredUndeletables == null ||
+ configuredUndeletables.trim().length() == 0) {
mUndeletablePolicies = DEF_UNDELETABLE_POLICIES;
return;
}
Vector<String> rules = new Vector<String>();
- StringTokenizer tokenizer = new
- StringTokenizer(configuredUndeletables.trim(), ",");
-
+ StringTokenizer tokenizer = new
+ StringTokenizer(configuredUndeletables.trim(), ",");
+
while (tokenizer.hasMoreTokens()) {
String rule = tokenizer.nextToken().trim();
@@ -1377,18 +1365,18 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
return;
}
- // For each rule read from the config file, see if any
+ // For each rule read from the config file, see if any
// predicate is set.
mUndeletablePolicies = new Hashtable<String, IExpression>();
for (Enumeration<String> e = rules.elements(); e.hasMoreElements();) {
String urn = (String) e.nextElement();
-
+
// See if there is predicate in the file
String pred = mConfig.getString(PROP_UNDELETABLE_POLICIES +
"." + urn + "." + PROP_PREDICATE, null);
-
+
IExpression exp = SimpleExpression.NULL_EXPRESSION;
-
+
if (pred != null)
exp = PolicyPredicateParser.parse(pred);
mUndeletablePolicies.put(urn, exp);
@@ -1423,12 +1411,11 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
}
private void verifyDefaultPolicyConfig()
- throws EPolicyException {
+ throws EPolicyException {
// For each policy in undeletable list make sure that
// the policy is present, is not disabled and its predicate
// is not tampered with.
- for (Enumeration<String> e = mUndeletablePolicies.keys();
- e.hasMoreElements();) {
+ for (Enumeration<String> e = mUndeletablePolicies.keys(); e.hasMoreElements();) {
String urn = (String) e.nextElement();
// See if the rule is in the instance table.
@@ -1438,14 +1425,14 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_MISSING_PERSISTENT_RULE", urn));
- // See if the instance is disabled.
+ // See if the instance is disabled.
if (!inst.isActive())
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_PERSISTENT_RULE_INACTIVE", urn));
- // See if the predicated is misconfigured.
+ // See if the predicated is misconfigured.
IExpression defPred = (IExpression)
- mUndeletablePolicies.get(urn);
+ mUndeletablePolicies.get(urn);
// We used SimpleExpression.NULL_EXPRESSION to indicate a null.
if (defPred == SimpleExpression.NULL_EXPRESSION)
@@ -1453,19 +1440,19 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
IExpression confPred = inst.getRule().getPredicate();
if (defPred == null && confPred != null) {
- String[] params = {urn, "null", confPred.toString()};
+ String[] params = { urn, "null", confPred.toString() };
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_PERSISTENT_RULE_MISCONFIG", params));
} else if (defPred != null && confPred == null) {
- String[] params = {urn, defPred.toString(), "null"};
+ String[] params = { urn, defPred.toString(), "null" };
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_PERSISTENT_RULE_MISCONFIG", params));
} else if (defPred != null && confPred != null) {
if (!defPred.toString().equals(confPred.toString())) {
- String[] params = {urn, defPred.toString(),
- confPred.toString()};
+ String[] params = { urn, defPred.toString(),
+ confPred.toString() };
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_PERSISTENT_RULE_MISCONFIG", params));
@@ -1475,31 +1462,29 @@ public class GenericPolicyProcessor implements IPolicyProcessor {
}
}
-
/**
* Class to keep track of various configurable implementations.
*/
class RegisteredPolicy {
String mId;
String mClPath;
- public RegisteredPolicy (String id, String clPath) {
+
+ public RegisteredPolicy(String id, String clPath) {
if (id == null || clPath == null)
- throw new
- AssertionException("Policy id or classpath can't be null");
+ throw new AssertionException("Policy id or classpath can't be null");
mId = id;
mClPath = clPath;
}
-
+
public String getClassPath() {
return mClPath;
}
-
+
public String getId() {
return mId;
}
}
-
class PolicyInstance {
String mInstanceId;
String mImplId;
@@ -1507,7 +1492,7 @@ class PolicyInstance {
boolean mIsEnabled;
public PolicyInstance(String instanceId, String implId,
- IPolicyRule rule, boolean isEnabled) {
+ IPolicyRule rule, boolean isEnabled) {
mInstanceId = instanceId;
mImplId = implId;
mRule = rule;
@@ -1543,9 +1528,8 @@ class PolicyInstance {
public void setActive(boolean stat) {
mIsEnabled = stat;
}
-
+
public void setRule(IPolicyRule newRule) {
mRule = newRule;
}
-}
-
+}
diff --git a/pki/base/common/src/com/netscape/cmscore/policy/JavaScriptRequestProxy.java b/pki/base/common/src/com/netscape/cmscore/policy/JavaScriptRequestProxy.java
index fde12d04..e9a7371d 100644
--- a/pki/base/common/src/com/netscape/cmscore/policy/JavaScriptRequestProxy.java
+++ b/pki/base/common/src/com/netscape/cmscore/policy/JavaScriptRequestProxy.java
@@ -17,14 +17,13 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.policy;
-
import com.netscape.certsrv.policy.IPolicyRule;
import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
-
public class JavaScriptRequestProxy {
IRequest req;
+
public JavaScriptRequestProxy(IRequest r) {
req = r;
}
@@ -42,4 +41,3 @@ public class JavaScriptRequestProxy {
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/policy/OrExpression.java b/pki/base/common/src/com/netscape/cmscore/policy/OrExpression.java
index f1bb6457..00fbfab7 100644
--- a/pki/base/common/src/com/netscape/cmscore/policy/OrExpression.java
+++ b/pki/base/common/src/com/netscape/cmscore/policy/OrExpression.java
@@ -17,38 +17,38 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.policy;
-
import com.netscape.certsrv.policy.EPolicyException;
import com.netscape.certsrv.policy.IExpression;
import com.netscape.certsrv.request.IRequest;
-
/**
- * This class represents an Or expression of the form
- * (var1 op val1 OR var2 op val2).
- *
+ * This class represents an Or expression of the form (var1 op val1 OR var2 op
+ * val2).
+ *
* Expressions are used as predicates for policy selection.
- *
+ *
* @author kanda
* @version $Revision$, $Date$
*/
public class OrExpression implements IExpression {
private IExpression mExp1;
private IExpression mExp2;
+
public OrExpression(IExpression exp1, IExpression exp2) {
mExp1 = exp1;
mExp2 = exp2;
}
public boolean evaluate(IRequest req)
- throws EPolicyException {
+ throws EPolicyException {
if (mExp1 == null && mExp2 == null)
return true;
else if (mExp1 != null && mExp2 != null)
return mExp1.evaluate(req) || mExp2.evaluate(req);
else if (mExp1 != null && mExp2 == null)
return mExp1.evaluate(req);
- else // (mExp1 == null && mExp2 != null)
+ else
+ // (mExp1 == null && mExp2 != null)
return mExp2.evaluate(req);
}
@@ -59,7 +59,8 @@ public class OrExpression implements IExpression {
return mExp1.toString() + " OR " + mExp2.toString();
else if (mExp1 != null && mExp2 == null)
return mExp1.toString();
- else // (mExp1 == null && mExp2 != null)
+ else
+ // (mExp1 == null && mExp2 != null)
return mExp2.toString();
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/policy/PolicyPredicateParser.java b/pki/base/common/src/com/netscape/cmscore/policy/PolicyPredicateParser.java
index 0f00e815..91406776 100644
--- a/pki/base/common/src/com/netscape/cmscore/policy/PolicyPredicateParser.java
+++ b/pki/base/common/src/com/netscape/cmscore/policy/PolicyPredicateParser.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.policy;
-
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
@@ -29,19 +28,16 @@ import com.netscape.certsrv.policy.EPolicyException;
import com.netscape.certsrv.policy.IExpression;
import com.netscape.cmscore.util.Debug;
-
/**
* Default implementation of predicate parser.
- *
+ *
* Limitations:
- *
- * 1. Currently parentheses are not suported.
- * 2. Only ==, != <, >, <= and >= operators are supported.
- * 3. The only boolean operators supported are AND and OR. AND takes precedence
- * over OR. Example: a AND b OR e OR c AND d
- * is treated as (a AND b) OR e OR (c AND d)
- * 4. If this is n't adequate, roll your own.
- *
+ *
+ * 1. Currently parentheses are not suported. 2. Only ==, != <, >, <= and >=
+ * operators are supported. 3. The only boolean operators supported are AND and
+ * OR. AND takes precedence over OR. Example: a AND b OR e OR c AND d is treated
+ * as (a AND b) OR e OR (c AND d) 4. If this is n't adequate, roll your own.
+ *
* @author kanda
* @version $Revision$, $Date$
*/
@@ -57,22 +53,23 @@ public class PolicyPredicateParser {
/**
* Parse the predicate expression and return a vector of expressions.
- *
- * @param predicateExp The predicate expression as read from the config file.
- * @return expVector The vector of expressions.
+ *
+ * @param predicateExp The predicate expression as read from the config
+ * file.
+ * @return expVector The vector of expressions.
*/
public static IExpression parse(String predicateExpression)
- throws EPolicyException {
- if (predicateExpression == null ||
- predicateExpression.length() == 0)
+ throws EPolicyException {
+ if (predicateExpression == null ||
+ predicateExpression.length() == 0)
return null;
PredicateTokenizer pt = new PredicateTokenizer(predicateExpression);
if (pt == null || !pt.hasMoreTokens())
return null;
- // The first token cannot be an operator. We are not dealing with
- // reverse-polish notation.
+ // The first token cannot be an operator. We are not dealing with
+ // reverse-polish notation.
String token = pt.nextToken();
boolean opANDSeen;
boolean opORSeen;
@@ -92,7 +89,7 @@ public class PolicyPredicateParser {
int curType = getOP(token);
if ((prevType != EXPRESSION && curType != EXPRESSION) ||
- (prevType == EXPRESSION && curType == EXPRESSION)) {
+ (prevType == EXPRESSION && curType == EXPRESSION)) {
malformed = true;
break;
}
@@ -103,7 +100,8 @@ public class PolicyPredicateParser {
continue;
}
- // If the previous type was an OR token, add the current expression to
+ // If the previous type was an OR token, add the current expression
+ // to
// the expression set;
if (prevType == OP_OR) {
expSet.addElement(current);
@@ -123,7 +121,7 @@ public class PolicyPredicateParser {
Debug.trace("Malformed expression: " + predicateExpression);
throw new EPolicyException(
CMS.getUserMessage("CMS_POLICY_BAD_POLICY_EXPRESSION",
- predicateExpression));
+ predicateExpression));
}
// Form an ORExpression
@@ -135,7 +133,7 @@ public class PolicyPredicateParser {
if (size == 0)
return null;
OrExpression orExp = new
- OrExpression((IExpression) expSet.elementAt(0), null);
+ OrExpression((IExpression) expSet.elementAt(0), null);
for (int i = 1; i < size; i++)
orExp = new OrExpression(orExp,
@@ -153,7 +151,7 @@ public class PolicyPredicateParser {
}
private static IExpression parseExpression(String input)
- throws EPolicyException {
+ throws EPolicyException {
// If the expression has multiple parts separated by commas
// we need to construct an AND expression. Else we will return a
// simple expression.
@@ -166,8 +164,8 @@ public class PolicyPredicateParser {
while (commaIndex > 0) {
SimpleExpression exp = (SimpleExpression)
- SimpleExpression.parse(input.substring(currentIndex,
- commaIndex));
+ SimpleExpression.parse(input.substring(currentIndex,
+ commaIndex));
expVector.addElement(exp);
currentIndex = commaIndex + 1;
@@ -175,7 +173,7 @@ public class PolicyPredicateParser {
}
if (currentIndex < (input.length() - 1)) {
SimpleExpression exp = (SimpleExpression)
- SimpleExpression.parse(input.substring(currentIndex));
+ SimpleExpression.parse(input.substring(currentIndex));
expVector.addElement(exp);
}
@@ -194,79 +192,40 @@ public class PolicyPredicateParser {
public static void main(String[] args) {
/*********
- IRequest req = new IRequest();
- try
- {
- req.set("ou", "people");
- req.set("cn", "John Doe");
- req.set("uid", "jdoes");
- req.set("o", "airius.com");
- req.set("certtype", "client");
- req.set("request", "issuance");
- req.set("id", new Integer(10));
- req.set("dualcerts", new Boolean(true));
-
- Vector v = new Vector();
- v.addElement("one");
- v.addElement("two");
- v.addElement("three");
- req.set("count", v);
- }
- catch (Exception e){e.printStackTrace();}
- String[] array = { "ou == people AND certtype == client",
- "ou == servergroup AND certtype == server",
- "uid == jdoes, ou==people, o==airius.com OR ou == people AND certType == client OR certType == server AND cn == needles.mcom.com",
- };
- for (int i = 0; i < array.length; i++)
- {
- System.out.println();
- System.out.println("String: " + array[i]);
- IExpression exp = null;
- try
- {
- exp = parse(array[i]);
- if (exp != null)
- {
- System.out.println("Parsed Expression: " + exp);
- boolean result = exp.evaluate(req);
- System.out.println("Result: " + result);
- }
- }
- catch (Exception e) {e.printStackTrace(); }
- }
-
-
- try
- {
- BufferedReader rdr = new BufferedReader(
- new FileReader(args[0]));
- String line;
- while((line=rdr.readLine()) != null)
- {
- System.out.println();
- System.out.println("Line Read: " + line);
- IExpression exp = null;
- try
- {
- exp = parse(line);
- if (exp != null)
- {
- System.out.println(exp);
- boolean result = exp.evaluate(req);
- System.out.println("Result: " + result);
- }
-
- }catch (Exception e){e.printStackTrace();}
- }
- }
- catch (Exception e){e.printStackTrace(); }
-
+ * IRequest req = new IRequest(); try { req.set("ou", "people");
+ * req.set("cn", "John Doe"); req.set("uid", "jdoes"); req.set("o",
+ * "airius.com"); req.set("certtype", "client"); req.set("request",
+ * "issuance"); req.set("id", new Integer(10)); req.set("dualcerts", new
+ * Boolean(true));
+ *
+ * Vector v = new Vector(); v.addElement("one"); v.addElement("two");
+ * v.addElement("three"); req.set("count", v); } catch (Exception
+ * e){e.printStackTrace();} String[] array = {
+ * "ou == people AND certtype == client",
+ * "ou == servergroup AND certtype == server",
+ * "uid == jdoes, ou==people, o==airius.com OR ou == people AND certType == client OR certType == server AND cn == needles.mcom.com"
+ * , }; for (int i = 0; i < array.length; i++) { System.out.println();
+ * System.out.println("String: " + array[i]); IExpression exp = null;
+ * try { exp = parse(array[i]); if (exp != null) {
+ * System.out.println("Parsed Expression: " + exp); boolean result =
+ * exp.evaluate(req); System.out.println("Result: " + result); } } catch
+ * (Exception e) {e.printStackTrace(); } }
+ *
+ *
+ * try { BufferedReader rdr = new BufferedReader( new
+ * FileReader(args[0])); String line; while((line=rdr.readLine()) !=
+ * null) { System.out.println(); System.out.println("Line Read: " +
+ * line); IExpression exp = null; try { exp = parse(line); if (exp !=
+ * null) { System.out.println(exp); boolean result = exp.evaluate(req);
+ * System.out.println("Result: " + result); }
+ *
+ * }catch (Exception e){e.printStackTrace();} } } catch (Exception
+ * e){e.printStackTrace(); }
*******/
}
}
-
class PredicateTokenizer {
String input;
int currentIndex;
@@ -348,30 +307,30 @@ class PredicateTokenizer {
}
}
-
class AttributeSet implements IAttrSet {
/**
*
*/
private static final long serialVersionUID = -3985810281989018413L;
Hashtable ht = new Hashtable();
+
public AttributeSet() {
}
public void delete(String name)
- throws EBaseException {
+ throws EBaseException {
Object ob = ht.get(name);
ht.remove(ob);
}
public Object get(String name)
- throws EBaseException {
+ throws EBaseException {
return ht.get(name);
}
public void set(String name, Object ob)
- throws EBaseException {
+ throws EBaseException {
ht.put(name, ob);
}
diff --git a/pki/base/common/src/com/netscape/cmscore/policy/PolicySet.java b/pki/base/common/src/com/netscape/cmscore/policy/PolicySet.java
index 24918a33..7fe049c0 100644
--- a/pki/base/common/src/com/netscape/cmscore/policy/PolicySet.java
+++ b/pki/base/common/src/com/netscape/cmscore/policy/PolicySet.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.policy;
-
import java.util.Enumeration;
import java.util.Vector;
@@ -30,11 +29,10 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cmscore.util.Debug;
-
/**
- * Implements a policy set per IPolicySet interface. This class
- * uses a vector of ordered policies to enforce priority.
- *
+ * Implements a policy set per IPolicySet interface. This class uses a vector of
+ * ordered policies to enforce priority.
+ *
* @author kanda
* @version $Revision$, $Date$
*/
@@ -51,7 +49,7 @@ public class PolicySet implements IPolicySet {
/**
* Returns the name of the rule set.
* <P>
- *
+ *
* @return The name of the rule set.
*/
public String getName() {
@@ -61,6 +59,7 @@ public class PolicySet implements IPolicySet {
/**
* Returns the no of rules in a set.
* <P>
+ *
* @return the no of rules.
*/
public int count() {
@@ -70,9 +69,9 @@ public class PolicySet implements IPolicySet {
/**
* Add a policy rule.
* <P>
- *
- * @param ruleName The name of the rule to be added.
- * @param rule The rule to be added.
+ *
+ * @param ruleName The name of the rule to be added.
+ * @param rule The rule to be added.
*/
public void addRule(String ruleName, IPolicyRule rule) {
if (mRuleNames.indexOf(ruleName) >= 0)
@@ -88,9 +87,9 @@ public class PolicySet implements IPolicySet {
/**
* Remplaces a policy rule identified by the given name.
- *
- * @param name The name of the rule to be replaced.
- * @param rule The rule to be replaced.
+ *
+ * @param name The name of the rule to be replaced.
+ * @param rule The rule to be replaced.
*/
public void replaceRule(String ruleName, IPolicyRule rule) {
int index = mRuleNames.indexOf(ruleName);
@@ -99,22 +98,22 @@ public class PolicySet implements IPolicySet {
addRule(ruleName, rule);
return;
}
-
+
mRuleNames.setElementAt(ruleName, index);
mRules.setElementAt(rule, index);
}
/**
* Removes a policy rule identified by the given name.
- *
- * @param name The name of the rule to be removed.
+ *
+ * @param name The name of the rule to be removed.
*/
public void removeRule(String ruleName) {
int index = mRuleNames.indexOf(ruleName);
if (index < 0)
return; // XXX - throw an exception.
-
+
mRuleNames.removeElementAt(index);
mRules.removeElementAt(index);
}
@@ -122,8 +121,8 @@ public class PolicySet implements IPolicySet {
/**
* Returns the rule identified by a given name.
* <P>
- *
- * @param name The name of the rule to be return.
+ *
+ * @param name The name of the rule to be return.
* @return The rule identified by the given name or null if none exists.
*/
public IPolicyRule getRule(String ruleName) {
@@ -137,7 +136,7 @@ public class PolicySet implements IPolicySet {
/**
* Returns an enumeration of rules.
* <P>
- *
+ *
* @return An enumeration of rules.
*/
public Enumeration<IPolicyRule> getRules() {
@@ -145,10 +144,10 @@ public class PolicySet implements IPolicySet {
}
/**
- * Apply policies on a given request from a rule set.
- * The rules may modify the request.
- *
- * @param req The request to apply policies on.
+ * Apply policies on a given request from a rule set. The rules may modify
+ * the request.
+ *
+ * @param req The request to apply policies on.
* @return the PolicyResult.
*/
public PolicyResult apply(IRequest req) {
@@ -158,11 +157,11 @@ public class PolicySet implements IPolicySet {
if ((cnt = mRules.size()) == 0)
return PolicyResult.ACCEPTED;
- // All policies are applied before returning the result. Hence
- // if atleast one of the policies returns a REJECTED, we need to
- // return that status. If none of the policies REJECTED
- // the request, but atleast one of them DEFERRED the request, we
- // need to return DEFERRED.
+ // All policies are applied before returning the result. Hence
+ // if atleast one of the policies returns a REJECTED, we need to
+ // return that status. If none of the policies REJECTED
+ // the request, but atleast one of them DEFERRED the request, we
+ // need to return DEFERRED.
boolean rejected = false;
boolean deferred = false;
int size = mRules.size();
@@ -182,7 +181,7 @@ public class PolicySet implements IPolicySet {
e.printStackTrace();
}
- if (!typeMatched(rule, req))
+ if (!typeMatched(rule, req))
continue;
try {
@@ -200,16 +199,16 @@ public class PolicySet implements IPolicySet {
// we pass that info down the chain. For now use S_OTHER
// as the system id for the log entry.
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_POLICY_REJECT_RESULT", req.getRequestId().toString(), name));
+ ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_POLICY_REJECT_RESULT", req.getRequestId().toString(), name));
rejected = true;
} else if (result == PolicyResult.DEFERRED) {
// It is hard to find out the owner at the moment unless
// we pass that info down the chain. For now use S_OTHER
// as the system id for the log entry.
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- ILogger.LL_WARN,
- CMS.getLogMessage("CMSCORE_POLICY_DEFER_RESULT", req.getRequestId().toString(), name));
+ ILogger.LL_WARN,
+ CMS.getLogMessage("CMSCORE_POLICY_DEFER_RESULT", req.getRequestId().toString(), name));
deferred = true;
} else if (result == PolicyResult.ACCEPTED) {
// It is hard to find out the owner at the moment unless
@@ -221,9 +220,9 @@ public class PolicySet implements IPolicySet {
// we pass that info down the chain. For now use S_OTHER
// as the system id for the log entry.
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- ILogger.LL_INFO,
- "policy: Request " + req.getRequestId() + " - Result of applying rule: " + name +
- " is: " + getPolicyResult(result));
+ ILogger.LL_INFO,
+ "policy: Request " + req.getRequestId() + " - Result of applying rule: " + name +
+ " is: " + getPolicyResult(result));
}
} catch (Throwable ex) {
// Customer can install his own policies.
@@ -231,14 +230,14 @@ public class PolicySet implements IPolicySet {
// catch those problems and report
// them to the log
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_POLICY_ERROR_RESULT", req.getRequestId().toString(), name, ex.toString()));
- // treat as rejected to prevent request from going into
+ ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_POLICY_ERROR_RESULT", req.getRequestId().toString(), name, ex.toString()));
+ // treat as rejected to prevent request from going into
// a weird state. request queue doesn't handle this case.
rejected = true;
((IPolicyRule) rule).setError(
- req,
- CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR", rule.getName(), ex.toString()), null);
+ req,
+ CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR", rule.getName(), ex.toString()), null);
}
}
@@ -248,9 +247,9 @@ public class PolicySet implements IPolicySet {
return PolicyResult.DEFERRED;
} else {
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- ILogger.LL_INFO,
- "Request " + req.getRequestId() +
- " Policy result: successful");
+ ILogger.LL_INFO,
+ "Request " + req.getRequestId() +
+ " Policy result: successful");
return PolicyResult.ACCEPTED;
}
}
@@ -267,7 +266,7 @@ public class PolicySet implements IPolicySet {
System.out.println("Rule Name: " + ruleName);
System.out.println("Implementation: " +
- mRules.elementAt(index).getClass().getName());
+ mRules.elementAt(index).getClass().getName());
}
}
@@ -295,4 +294,3 @@ public class PolicySet implements IPolicySet {
return false;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/policy/SimpleExpression.java b/pki/base/common/src/com/netscape/cmscore/policy/SimpleExpression.java
index 5e6458be..677b0574 100644
--- a/pki/base/common/src/com/netscape/cmscore/policy/SimpleExpression.java
+++ b/pki/base/common/src/com/netscape/cmscore/policy/SimpleExpression.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.policy;
-
import java.util.Enumeration;
import java.util.Vector;
@@ -28,13 +27,12 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.cmscore.util.AssertionException;
import com.netscape.cmscore.util.Debug;
-
/**
- * This class represents an expression of the form var = val,
- * var != val, var < val, var > val, var <= val, var >= val.
- *
+ * This class represents an expression of the form var = val, var != val, var <
+ * val, var > val, var <= val, var >= val.
+ *
* Expressions are used as predicates for policy selection.
- *
+ *
* @author kanda
* @version $Revision$, $Date$
*/
@@ -47,11 +45,11 @@ public class SimpleExpression implements IExpression {
private boolean hasWildCard;
public static final char WILDCARD_CHAR = '*';
- // This is just for indicating a null expression.
+ // This is just for indicating a null expression.
public static SimpleExpression NULL_EXPRESSION = new SimpleExpression("null", OP_EQUAL, "null");
public static IExpression parse(String input)
- throws EPolicyException {
+ throws EPolicyException {
// Get the index of operator
// Debug.trace("SimpleExpression::input: " + input);
String var = null;
@@ -118,19 +116,19 @@ public class SimpleExpression implements IExpression {
}
public boolean evaluate(IRequest req)
- throws EPolicyException {
+ throws EPolicyException {
// mPfx and mVar are looked up case-indendently
String givenVal = req.getExtDataInString(mPfx, mVar);
if (Debug.ON)
- Debug.trace("mPfx: " + mPfx + " mVar: " + mVar +
- ",Given Value: " + givenVal + ", Value to compare with: " + mVal);
+ Debug.trace("mPfx: " + mPfx + " mVar: " + mVar +
+ ",Given Value: " + givenVal + ", Value to compare with: " + mVal);
return matchValue(givenVal);
}
private boolean matchVector(Vector value)
- throws EPolicyException {
+ throws EPolicyException {
boolean result = false;
Enumeration e = (Enumeration) value.elements();
@@ -143,7 +141,7 @@ public class SimpleExpression implements IExpression {
}
private boolean matchStringArray(String[] value)
- throws EPolicyException {
+ throws EPolicyException {
boolean result = false;
for (int i = 0; i < value.length; i++) {
@@ -155,23 +153,23 @@ public class SimpleExpression implements IExpression {
}
private boolean matchValue(Object value)
- throws EPolicyException {
+ throws EPolicyException {
boolean result;
// There is nothing to compare with!
if (value == null)
return false;
- // XXX - Kanda: We need a better way of handling this!.
+ // XXX - Kanda: We need a better way of handling this!.
if (value instanceof String)
result = matchStringValue((String) value);
else if (value instanceof Integer)
result = matchIntegerValue((Integer) value);
else if (value instanceof Boolean)
result = matchBooleanValue((Boolean) value);
- else if (value instanceof Vector)
+ else if (value instanceof Vector)
result = matchVector((Vector) value);
- else if (value instanceof String[])
+ else if (value instanceof String[])
result = matchStringArray((String[]) value);
else
throw new EPolicyException(CMS.getUserMessage("CMS_POLICY_INVALID_ATTR_VALUE",
@@ -180,7 +178,7 @@ public class SimpleExpression implements IExpression {
}
private boolean matchStringValue(String givenVal)
- throws EPolicyException {
+ throws EPolicyException {
boolean result;
switch (mOp) {
@@ -221,7 +219,7 @@ public class SimpleExpression implements IExpression {
}
private boolean matchIntegerValue(Integer intVal)
- throws EPolicyException {
+ throws EPolicyException {
boolean result;
int storedVal;
int givenVal = intVal.intValue();
@@ -264,12 +262,11 @@ public class SimpleExpression implements IExpression {
}
private boolean matchBooleanValue(Boolean givenVal)
- throws EPolicyException {
+ throws EPolicyException {
boolean result;
Boolean storedVal;
- if (!(mVal.equalsIgnoreCase("true") ||
- mVal.equalsIgnoreCase("false")))
+ if (!(mVal.equalsIgnoreCase("true") || mVal.equalsIgnoreCase("false")))
throw new EPolicyException(CMS.getUserMessage("CMS_POLICY_INVALID_ATTR_VALUE",
mVal));
storedVal = new Boolean(mVal);
@@ -320,9 +317,9 @@ public class SimpleExpression implements IExpression {
op = IExpression.LE_STR;
break;
}
- if (mPfx != null && mPfx.length() > 0)
+ if (mPfx != null && mPfx.length() > 0)
return mPfx + "." + mVar + " " + op + " " + mVal;
- else
+ else
return mVar + " " + op + " " + mVal;
}
@@ -411,7 +408,6 @@ public class SimpleExpression implements IExpression {
}
}
-
class ExpressionComps {
String attr;
int op;
@@ -435,4 +431,3 @@ class ExpressionComps {
return val;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/profile/ProfileSubsystem.java b/pki/base/common/src/com/netscape/cmscore/profile/ProfileSubsystem.java
index 4f386259..aa93f1ae 100644
--- a/pki/base/common/src/com/netscape/cmscore/profile/ProfileSubsystem.java
+++ b/pki/base/common/src/com/netscape/cmscore/profile/ProfileSubsystem.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.profile;
-
import java.io.File;
import java.util.Enumeration;
import java.util.Hashtable;
@@ -34,7 +33,6 @@ import com.netscape.certsrv.profile.IProfileSubsystem;
import com.netscape.certsrv.registry.IPluginInfo;
import com.netscape.certsrv.registry.IPluginRegistry;
-
public class ProfileSubsystem implements IProfileSubsystem {
private static final String PROP_LIST = "list";
private static final String PROP_CLASS_ID = "class_id";
@@ -54,7 +52,7 @@ public class ProfileSubsystem implements IProfileSubsystem {
* Retrieves the name of this subsystem.
*/
public String getId() {
- return null;
+ return null;
}
/**
@@ -64,19 +62,18 @@ public class ProfileSubsystem implements IProfileSubsystem {
}
/**
- * Initializes this subsystem with the given configuration
- * store.
+ * Initializes this subsystem with the given configuration store.
* <P>
- *
+ *
* @param owner owner of this subsystem
* @param config configuration store
* @exception EBaseException failed to initialize
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
CMS.debug("ProfileSubsystem: start init");
IPluginRegistry registry = (IPluginRegistry)
- CMS.getSubsystem(CMS.SUBSYSTEM_REGISTRY);
+ CMS.getSubsystem(CMS.SUBSYSTEM_REGISTRY);
mConfig = config;
mOwner = owner;
@@ -100,7 +97,7 @@ public class ProfileSubsystem implements IProfileSubsystem {
String configPath = subStore.getString(PROP_CONFIG);
CMS.debug("Start Profile Creation - " + id + " " + classid + " " + info.getClassName());
- IProfile profile = createProfile(id, classid, info.getClassName(),
+ IProfile profile = createProfile(id, classid, info.getClassName(),
configPath);
CMS.debug("Done Profile Creation - " + id);
@@ -112,15 +109,15 @@ public class ProfileSubsystem implements IProfileSubsystem {
String id = (String) ee.nextElement();
CMS.debug("Registered Confirmation - " + id);
- }
+ }
}
/**
* Creates a profile instance.
*/
- public IProfile createProfile(String id, String classid, String className,
- String configPath)
- throws EProfileException {
+ public IProfile createProfile(String id, String classid, String className,
+ String configPath)
+ throws EProfileException {
IProfile profile = null;
try {
@@ -143,11 +140,11 @@ public class ProfileSubsystem implements IProfileSubsystem {
}
public void deleteProfile(String id, String configPath) throws EProfileException {
-
+
if (isProfileEnable(id)) {
throw new EProfileException("CMS_PROFILE_DELETE_ENABLEPROFILE");
}
-
+
String ids = "";
try {
ids = mConfig.getString(PROP_LIST, "");
@@ -166,7 +163,7 @@ public class ProfileSubsystem implements IProfileSubsystem {
}
if (!list.equals(""))
list = list.substring(0, list.length() - 1);
-
+
mConfig.putString(PROP_LIST, list);
mConfig.removeSubStore(id);
File file1 = new File(configPath);
@@ -181,13 +178,13 @@ public class ProfileSubsystem implements IProfileSubsystem {
}
}
- public void createProfileConfig(String id, String classId,
- String configPath)
- throws EProfileException {
+ public void createProfileConfig(String id, String classId,
+ String configPath)
+ throws EProfileException {
try {
if (mProfiles.size() > 0) {
- mConfig.putString(PROP_LIST,
- mConfig.getString(PROP_LIST) + "," + id);
+ mConfig.putString(PROP_LIST,
+ mConfig.getString(PROP_LIST) + "," + id);
} else {
mConfig.putString(PROP_LIST, id);
}
@@ -207,8 +204,8 @@ public class ProfileSubsystem implements IProfileSubsystem {
}
/**
- * Stops this system. The owner may call shutdown
- * anytime after initialization.
+ * Stops this system. The owner may call shutdown anytime after
+ * initialization.
* <P>
*/
public void shutdown() {
@@ -222,7 +219,7 @@ public class ProfileSubsystem implements IProfileSubsystem {
/**
* Returns the root configuration storage of this system.
* <P>
- *
+ *
* @return configuration store of this subsystem
*/
public IConfigStore getConfigStore() {
@@ -233,7 +230,7 @@ public class ProfileSubsystem implements IProfileSubsystem {
* Adds a profile.
*/
public void addProfile(String id, IProfile profile)
- throws EProfileException {
+ throws EProfileException {
}
public boolean isProfileEnable(String id) {
@@ -267,7 +264,7 @@ public class ProfileSubsystem implements IProfileSubsystem {
* Enables a profile for execution.
*/
public void enableProfile(String id, String enableBy)
- throws EProfileException {
+ throws EProfileException {
IProfile profile = (IProfile) mProfiles.get(id);
profile.getConfigStore().putString(PROP_ENABLE, "true");
@@ -282,7 +279,7 @@ public class ProfileSubsystem implements IProfileSubsystem {
* Disables a profile for execution.
*/
public void disableProfile(String id)
- throws EProfileException {
+ throws EProfileException {
IProfile profile = (IProfile) mProfiles.get(id);
profile.getConfigStore().putString(PROP_ENABLE, "false");
@@ -296,7 +293,7 @@ public class ProfileSubsystem implements IProfileSubsystem {
* Retrieves a profile by id.
*/
public IProfile getProfile(String id)
- throws EProfileException {
+ throws EProfileException {
return (IProfile) mProfiles.get(id);
}
@@ -305,8 +302,7 @@ public class ProfileSubsystem implements IProfileSubsystem {
}
/**
- * Retrieves a list of profile ids. The return
- * list is of type String.
+ * Retrieves a list of profile ids. The return list is of type String.
*/
public Enumeration<String> getProfileIds() {
return mProfileIds.elements();
@@ -314,15 +310,14 @@ public class ProfileSubsystem implements IProfileSubsystem {
/**
* Checks if owner id should be enforced during profile approval.
- *
+ *
* @return true if approval should be checked
*/
- public boolean checkOwner()
- {
+ public boolean checkOwner() {
try {
- return mConfig.getBoolean(PROP_CHECK_OWNER, false);
+ return mConfig.getBoolean(PROP_CHECK_OWNER, false);
} catch (EBaseException e) {
- return false;
+ return false;
}
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/registry/PluginInfo.java b/pki/base/common/src/com/netscape/cmscore/registry/PluginInfo.java
index 2766bcdb..c65626a1 100644
--- a/pki/base/common/src/com/netscape/cmscore/registry/PluginInfo.java
+++ b/pki/base/common/src/com/netscape/cmscore/registry/PluginInfo.java
@@ -17,16 +17,13 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.registry;
-
import java.util.Locale;
import com.netscape.certsrv.registry.IPluginInfo;
-
/**
- * The plugin information includes id, name,
- * classname, and description.
- *
+ * The plugin information includes id, name, classname, and description.
+ *
* @author thomask
*/
public class PluginInfo implements IPluginInfo {
diff --git a/pki/base/common/src/com/netscape/cmscore/registry/PluginRegistry.java b/pki/base/common/src/com/netscape/cmscore/registry/PluginRegistry.java
index 20c9cef0..2f82248a 100644
--- a/pki/base/common/src/com/netscape/cmscore/registry/PluginRegistry.java
+++ b/pki/base/common/src/com/netscape/cmscore/registry/PluginRegistry.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.registry;
-
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Locale;
@@ -31,7 +30,6 @@ import com.netscape.certsrv.registry.ERegistryException;
import com.netscape.certsrv.registry.IPluginInfo;
import com.netscape.certsrv.registry.IPluginRegistry;
-
public class PluginRegistry implements IPluginRegistry {
private static final String PROP_TYPES = "types";
@@ -44,7 +42,7 @@ public class PluginRegistry implements IPluginRegistry {
private IConfigStore mConfig = null;
private IConfigStore mFileConfig = null;
private ISubsystem mOwner = null;
- private Hashtable<String, Hashtable <String ,IPluginInfo>> mTypes = new Hashtable<String, Hashtable<String, IPluginInfo>>();
+ private Hashtable<String, Hashtable<String, IPluginInfo>> mTypes = new Hashtable<String, Hashtable<String, IPluginInfo>>();
public PluginRegistry() {
}
@@ -53,7 +51,7 @@ public class PluginRegistry implements IPluginRegistry {
* Retrieves the name of this subsystem.
*/
public String getId() {
- return null;
+ return null;
}
/**
@@ -63,16 +61,15 @@ public class PluginRegistry implements IPluginRegistry {
}
/**
- * Initializes this subsystem with the given configuration
- * store.
+ * Initializes this subsystem with the given configuration store.
* <P>
- *
+ *
* @param owner owner of this subsystem
* @param config configuration store
* @exception EBaseException failed to initialize
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
CMS.debug("RegistrySubsystem: start init");
mConfig = config;
mOwner = owner;
@@ -103,7 +100,7 @@ public class PluginRegistry implements IPluginRegistry {
* Load plugins of the given type.
*/
public void loadPlugins(IConfigStore config, String type)
- throws EBaseException {
+ throws EBaseException {
String ids_str = null;
try {
@@ -122,7 +119,6 @@ public class PluginRegistry implements IPluginRegistry {
}
}
-
public IPluginInfo createPluginInfo(String name, String desc, String classPath) {
return new PluginInfo(name, desc, classPath);
}
@@ -131,7 +127,7 @@ public class PluginRegistry implements IPluginRegistry {
* Load plugins of the given type.
*/
public void loadPlugin(IConfigStore config, String type, String id)
- throws EBaseException {
+ throws EBaseException {
String name = null;
try {
@@ -147,7 +143,7 @@ public class PluginRegistry implements IPluginRegistry {
String classpath = null;
try {
- classpath = mFileConfig.getString(type + "." + id + "." + PROP_CLASSPATH,
+ classpath = mFileConfig.getString(type + "." + id + "." + PROP_CLASSPATH,
null);
} catch (EBaseException e) {
}
@@ -157,23 +153,23 @@ public class PluginRegistry implements IPluginRegistry {
}
public void removePluginInfo(String type, String id)
- throws ERegistryException {
+ throws ERegistryException {
Hashtable<String, IPluginInfo> plugins = mTypes.get(type);
if (plugins == null)
- return;
+ return;
plugins.remove(id);
Locale locale = Locale.getDefault();
rebuildConfigStore(locale);
}
public void addPluginInfo(String type, String id, IPluginInfo info)
- throws ERegistryException {
+ throws ERegistryException {
addPluginInfo(type, id, info, 1);
}
public void addPluginInfo(String type, String id, IPluginInfo info, int saveConfig)
- throws ERegistryException {
- Hashtable<String, IPluginInfo> plugins = mTypes.get(type);
+ throws ERegistryException {
+ Hashtable<String, IPluginInfo> plugins = mTypes.get(type);
if (plugins == null) {
plugins = new Hashtable<String, IPluginInfo>();
@@ -181,17 +177,18 @@ public class PluginRegistry implements IPluginRegistry {
}
Locale locale = Locale.getDefault();
- CMS.debug("added plugin " + type + " " + id + " " +
- info.getName(locale) + " " + info.getDescription(locale) + " " +
- info.getClassName());
+ CMS.debug("added plugin " + type + " " + id + " " +
+ info.getName(locale) + " " + info.getDescription(locale) + " " +
+ info.getClassName());
plugins.put(id, info);
// rebuild configuration store
- if (saveConfig == 1) rebuildConfigStore(locale);
+ if (saveConfig == 1)
+ rebuildConfigStore(locale);
}
public void rebuildConfigStore(Locale locale)
- throws ERegistryException {
+ throws ERegistryException {
Enumeration<String> types = mTypes.keys();
StringBuffer typesBuf = new StringBuffer();
@@ -215,20 +212,20 @@ public class PluginRegistry implements IPluginRegistry {
}
IPluginInfo plugin = (IPluginInfo) mPlugins.get(id);
- mFileConfig.putString(type + "." + id + ".class",
- plugin.getClassName());
- mFileConfig.putString(type + "." + id + ".name",
- plugin.getName(locale));
- mFileConfig.putString(type + "." + id + ".desc",
- plugin.getDescription(locale));
+ mFileConfig.putString(type + "." + id + ".class",
+ plugin.getClassName());
+ mFileConfig.putString(type + "." + id + ".name",
+ plugin.getName(locale));
+ mFileConfig.putString(type + "." + id + ".desc",
+ plugin.getDescription(locale));
}
mFileConfig.putString(type + ".ids", idsBuf.toString());
}
mFileConfig.putString("types", typesBuf.toString());
try {
- mFileConfig.commit(false);
+ mFileConfig.commit(false);
} catch (EBaseException e) {
- CMS.debug("PluginRegistry: failed to commit registry.cfg");
+ CMS.debug("PluginRegistry: failed to commit registry.cfg");
}
}
@@ -240,8 +237,8 @@ public class PluginRegistry implements IPluginRegistry {
}
/**
- * Stops this system. The owner may call shutdown
- * anytime after initialization.
+ * Stops this system. The owner may call shutdown anytime after
+ * initialization.
* <P>
*/
public void shutdown() {
@@ -252,7 +249,7 @@ public class PluginRegistry implements IPluginRegistry {
/**
* Returns the root configuration storage of this system.
* <P>
- *
+ *
* @return configuration store of this subsystem
*/
public IConfigStore getConfigStore() {
@@ -274,7 +271,7 @@ public class PluginRegistry implements IPluginRegistry {
* Returns a list of identifiers of the given type.
*/
public Enumeration<String> getIds(String type) {
- Hashtable<String, IPluginInfo> plugins = mTypes.get(type);
+ Hashtable<String, IPluginInfo> plugins = mTypes.get(type);
if (plugins == null)
return null;
@@ -285,7 +282,7 @@ public class PluginRegistry implements IPluginRegistry {
* Retrieves the plugin information.
*/
public IPluginInfo getPluginInfo(String type, String id) {
- Hashtable <String ,IPluginInfo> plugins = mTypes.get(type);
+ Hashtable<String, IPluginInfo> plugins = mTypes.get(type);
if (plugins == null)
return null;
diff --git a/pki/base/common/src/com/netscape/cmscore/request/ARequestQueue.java b/pki/base/common/src/com/netscape/cmscore/request/ARequestQueue.java
index 47418664..bb56a8b3 100644
--- a/pki/base/common/src/com/netscape/cmscore/request/ARequestQueue.java
+++ b/pki/base/common/src/com/netscape/cmscore/request/ARequestQueue.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.request;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -63,31 +62,30 @@ import com.netscape.certsrv.request.PolicyResult;
import com.netscape.certsrv.request.RequestId;
import com.netscape.certsrv.request.RequestStatus;
-
/**
- * The ARequestQueue class is an abstract class that implements
- * most portions of the IRequestQueue interface. This includes
- * the state engine as defined for processing IRequest objects.
+ * The ARequestQueue class is an abstract class that implements most portions of
+ * the IRequestQueue interface. This includes the state engine as defined for
+ * processing IRequest objects.
* <p>
* !Put state machine description here!
* <p>
- * This class defines several abstract protected functions that
- * need to be defined by the concrete implementation. In
- * particular, this class does not implement the operations
- * for storing requests persistantly.
+ * This class defines several abstract protected functions that need to be
+ * defined by the concrete implementation. In particular, this class does not
+ * implement the operations for storing requests persistantly.
* <p>
- * This class also provides several accessor functions for setting
- * fields in the IRequest object. These functions are provided
- * as an aid to saving and restoring the state in the database.
+ * This class also provides several accessor functions for setting fields in the
+ * IRequest object. These functions are provided as an aid to saving and
+ * restoring the state in the database.
* <p>
- * This class also implements the locking operations specified by
- * the IRequestQueue interface.
+ * This class also implements the locking operations specified by the
+ * IRequestQueue interface.
* <p>
+ *
* @author thayes
* @version $Revision$ $Date$
*/
public abstract class ARequestQueue
- implements IRequestQueue {
+ implements IRequestQueue {
/**
* global request version for tracking request changes.
@@ -97,37 +95,35 @@ public abstract class ARequestQueue
/**
* Create a new (unique) RequestId. (abstract)
* <p>
- * This method must be implemented by the specialized class to
- * generate a new id from data in the persistant store. This id
- * is used to create a new request object.
+ * This method must be implemented by the specialized class to generate a
+ * new id from data in the persistant store. This id is used to create a new
+ * request object.
* <p>
- * @return
- * a new RequestId object.
- * @exception EBaseException
- * indicates that creation of the new id could not be completed.
+ *
+ * @return a new RequestId object.
+ * @exception EBaseException indicates that creation of the new id could not
+ * be completed.
* @see RequestId
*/
protected abstract RequestId newRequestId()
- throws EBaseException;
+ throws EBaseException;
/**
* Read a request from the persistant store. (abstract)
* <p>
- * This function is called to create the in-memory version of
- * a request object.
+ * This function is called to create the in-memory version of a request
+ * object.
* <p>
- * The implementation of this object can use the createRequest
- * member function to create a new instance of an IRequest, and
- * use the setRequestStatus, setCreationTime and setModificationTime
- * functions to set those values.
+ * The implementation of this object can use the createRequest member
+ * function to create a new instance of an IRequest, and use the
+ * setRequestStatus, setCreationTime and setModificationTime functions to
+ * set those values.
* <p>
- * @param id
- * the id of the request to read.
- * @return
- * a new IRequest object. null is returned if the object cannot
- * be located.
- * @exception EBaseException
- * TODO: this is not implemented yet
+ *
+ * @param id the id of the request to read.
+ * @return a new IRequest object. null is returned if the object cannot be
+ * located.
+ * @exception EBaseException TODO: this is not implemented yet
* @see #createRequest
* @see #setRequestStatus
* @see #setModificationTime
@@ -138,56 +134,51 @@ public abstract class ARequestQueue
/**
* Add the request to the store. (abstract)
* <p>
- * This function is called when a new request immediately after
- * creating a new request.
+ * This function is called when a new request immediately after creating a
+ * new request.
* <p>
- * @param request
- * the request to add.
- * @exception EBaseException
- * TODO: this is not implemented yet
+ *
+ * @param request the request to add.
+ * @exception EBaseException TODO: this is not implemented yet
*/
protected abstract void addRequest(IRequest request) throws EBaseException;
/**
* Modify the request in the store. (abstract)
* <p>
- * Update the persistant copy of this request with the
- * current values in the object.
+ * Update the persistant copy of this request with the current values in the
+ * object.
* <p>
- * Currently there are no hints for what has changed, so
- * the entire request should be updated.
+ * Currently there are no hints for what has changed, so the entire request
+ * should be updated.
* <p>
+ *
* @param request
- * @exception EBaseException
- * TODO: this is not implemented yet
+ * @exception EBaseException TODO: this is not implemented yet
*/
protected abstract void modifyRequest(IRequest request);
/**
- * Get complete list of RequestId values found i this
- * queue.
+ * Get complete list of RequestId values found i this queue.
* <p>
- * This method can form the basis for creating other types
- * of search/list operations (although there are probably more
- * efficient ways of doing this. ARequestQueue implements
- * default versions of some of the searching by using this
- * method as a basis.
+ * This method can form the basis for creating other types of search/list
+ * operations (although there are probably more efficient ways of doing
+ * this. ARequestQueue implements default versions of some of the searching
+ * by using this method as a basis.
* <p>
- * TODO: return IRequestList -or- just use listRequests as
- * the basic engine.
+ * TODO: return IRequestList -or- just use listRequests as the basic engine.
* <p>
- * @return
- * an Enumeration that generates RequestId objects.
+ *
+ * @return an Enumeration that generates RequestId objects.
*/
abstract protected Enumeration<RequestId> getRawList();
/**
* protected access for setting the current state of a request.
* <p>
- * @param request
- * The request to be modified.
- * @param status
- * The new value for the request status.
+ *
+ * @param request The request to be modified.
+ * @param status The new value for the request status.
*/
protected final void setRequestStatus(IRequest request, RequestStatus status) {
Request r = (Request) request;
@@ -198,10 +189,9 @@ public abstract class ARequestQueue
/**
* protected access for setting the modification time of a request.
* <p>
- * @param request
- * The request to be modified.
- * @param date
- * The new value for the time.
+ *
+ * @param request The request to be modified.
+ * @param date The new value for the time.
*/
protected final void setModificationTime(IRequest request, Date date) {
Request r = (Request) request;
@@ -212,10 +202,9 @@ public abstract class ARequestQueue
/**
* protected access for setting the creation time of a request.
* <p>
- * @param request
- * The request to be modified.
- * @param date
- * The new value for the time.
+ *
+ * @param request The request to be modified.
+ * @param date The new value for the time.
*/
protected final void setCreationTime(IRequest request, Date date) {
Request r = (Request) request;
@@ -226,20 +215,19 @@ public abstract class ARequestQueue
/**
* protected access for creating a new Request object
* <p>
- * @param id
- * The identifier for the new request
- * @return
- * A new request object. The caller should fill in other data
- * values from the datastore.
+ *
+ * @param id The identifier for the new request
+ * @return A new request object. The caller should fill in other data values
+ * from the datastore.
*/
protected final IRequest createRequest(RequestId id, String requestType) {
Request r;
/*
* Determine the specialized class to create for this type
- *
- * TODO: this set of classes is an example only. The real set
- * needs to be determined and implemented.
+ *
+ * TODO: this set of classes is an example only. The real set needs to
+ * be determined and implemented.
*/
if (requestType != null && requestType.equals("enrollment")) {
r = new EnrollmentRequest(id);
@@ -251,12 +239,13 @@ public abstract class ARequestQueue
}
/**
- * Implements IRequestQueue.newRequest
+ * Implements IRequestQueue.newRequest
* <p>
+ *
* @see IRequestQueue#newRequest
*/
public IRequest newRequest(String requestType)
- throws EBaseException {
+ throws EBaseException {
if (requestType == null) {
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_REQUEST_TYPE", "null"));
}
@@ -288,16 +277,18 @@ public abstract class ARequestQueue
/**
* Implements IRequestQueue.cloneRequest
* <p>
+ *
* @see IRequestQueue#cloneRequest
*/
- public IRequest cloneRequest(IRequest r)
- throws EBaseException {
- // 1. check for valid state. (Are any invalid ?)
+ public IRequest cloneRequest(IRequest r)
+ throws EBaseException {
+ // 1. check for valid state. (Are any invalid ?)
RequestStatus rs = r.getRequestStatus();
- if (rs == RequestStatus.BEGIN) throw new EBaseException("Invalid Status");
+ if (rs == RequestStatus.BEGIN)
+ throw new EBaseException("Invalid Status");
- // 2. create new request
+ // 2. create new request
String reqType = r.getRequestType();
IRequest clone = newRequest(reqType);
@@ -317,10 +308,11 @@ public abstract class ARequestQueue
/**
* Implements IRequestQueue.findRequest
* <p>
+ *
* @see IRequestQueue#findRequest
*/
public IRequest findRequest(RequestId id)
- throws EBaseException {
+ throws EBaseException {
IRequest r;
// mTable.lock(id);
@@ -328,12 +320,12 @@ public abstract class ARequestQueue
r = readRequest(id);
// if (r == null) mTable.unlock(id);
-
+
return r;
}
private IRequestScheduler mRequestScheduler = null;
-
+
public void setRequestScheduler(IRequestScheduler scheduler) {
mRequestScheduler = scheduler;
}
@@ -345,10 +337,11 @@ public abstract class ARequestQueue
/**
* Implements IRequestQueue.processRequest
* <p>
+ *
* @see IRequestQueue#processRequest
*/
public final void processRequest(IRequest r)
- throws EBaseException {
+ throws EBaseException {
// #610553 Thread Scheduler
IRequestScheduler scheduler = getRequestScheduler();
@@ -361,7 +354,8 @@ public abstract class ARequestQueue
// 1. Check for valid state
RequestStatus rs = r.getRequestStatus();
- if (rs != RequestStatus.BEGIN) throw new EBaseException("Invalid Status");
+ if (rs != RequestStatus.BEGIN)
+ throw new EBaseException("Invalid Status");
stateEngine(r);
} finally {
@@ -374,19 +368,21 @@ public abstract class ARequestQueue
/**
* Implements IRequestQueue.markRequestPending
* <p>
+ *
* @see IRequestQueue#markRequestPending
*/
public final void markRequestPending(IRequest r)
- throws EBaseException {
+ throws EBaseException {
// 1. Check for valid state
RequestStatus rs = r.getRequestStatus();
- if (rs != RequestStatus.BEGIN) throw new EBaseException("Invalid Status");
+ if (rs != RequestStatus.BEGIN)
+ throw new EBaseException("Invalid Status");
- // 2. Change the request state. This method of making
- // a request PENDING does NOT invoke the PENDING notifiers.
- // To change this, just call stateEngine at the completion of this
- // routine.
+ // 2. Change the request state. This method of making
+ // a request PENDING does NOT invoke the PENDING notifiers.
+ // To change this, just call stateEngine at the completion of this
+ // routine.
setRequestStatus(r, RequestStatus.PENDING);
updateRequest(r);
@@ -396,10 +392,11 @@ public abstract class ARequestQueue
/**
* Implements IRequestQueue.cloneAndMarkPending
* <p>
+ *
* @see IRequestQueue#cloneAndMarkPending
*/
- public IRequest cloneAndMarkPending(IRequest r)
- throws EBaseException {
+ public IRequest cloneAndMarkPending(IRequest r)
+ throws EBaseException {
IRequest clone = cloneRequest(r);
markRequestPending(clone);
@@ -409,14 +406,16 @@ public abstract class ARequestQueue
/**
* Implements IRequestQueue.approveRequest
* <p>
+ *
* @see IRequestQueue#approveRequest
*/
public final void approveRequest(IRequest r)
- throws EBaseException {
+ throws EBaseException {
// 1. Check for valid state
RequestStatus rs = r.getRequestStatus();
- if (rs != RequestStatus.PENDING) throw new EBaseException("Invalid Status");
+ if (rs != RequestStatus.PENDING)
+ throw new EBaseException("Invalid Status");
AgentApprovals aas = AgentApprovals.fromStringVector(
r.getExtDataInStringVector(AgentApprovals.class.getName()));
@@ -427,17 +426,18 @@ public abstract class ARequestQueue
// Record agent who did this
String agentName = getUserIdentity();
- if (agentName == null) throw new EBaseException("Missing agent information");
+ if (agentName == null)
+ throw new EBaseException("Missing agent information");
aas.addApproval(agentName);
- r.setExtData(AgentApprovals.class.getName(), (Vector<?>)aas.toStringVector());
+ r.setExtData(AgentApprovals.class.getName(), (Vector<?>) aas.toStringVector());
PolicyResult pr = mPolicy.apply(r);
if (pr == PolicyResult.ACCEPTED) {
setRequestStatus(r, RequestStatus.APPROVED);
} else if (pr == PolicyResult.DEFERRED ||
- pr == PolicyResult.REJECTED) {
+ pr == PolicyResult.REJECTED) {
}
// Always update. The policy code may have made changes to the
@@ -450,16 +450,18 @@ public abstract class ARequestQueue
/**
* Implements IRequestQueue.rejectRequest
* <p>
+ *
* @see IRequestQueue#rejectRequest
*/
public final void rejectRequest(IRequest r)
- throws EBaseException {
+ throws EBaseException {
// 1. Check for valid state
RequestStatus rs = r.getRequestStatus();
- if (rs != RequestStatus.PENDING) throw new EBaseException("Invalid Status");
+ if (rs != RequestStatus.PENDING)
+ throw new EBaseException("Invalid Status");
- // 2. Change state
+ // 2. Change state
setRequestStatus(r, RequestStatus.REJECTED);
updateRequest(r);
@@ -470,10 +472,11 @@ public abstract class ARequestQueue
/**
* Implments IRequestQueue.cancelRequest
* <p>
+ *
* @see IRequestQueue#cancelRequest
*/
public final void cancelRequest(IRequest r)
- throws EBaseException {
+ throws EBaseException {
setRequestStatus(r, RequestStatus.CANCELED);
updateRequest(r);
@@ -489,7 +492,8 @@ public abstract class ARequestQueue
setRequestStatus(r, RequestStatus.COMPLETE);
updateRequest(r);
- if (mNotify != null) mNotify.notify(r);
+ if (mNotify != null)
+ mNotify.notify(r);
return;
}
@@ -497,10 +501,10 @@ public abstract class ARequestQueue
/**
* Implements IRequestQueue.listRequests
* <p>
- * Should be overridden by the specialized class if
- * a more efficient method is available for implementing
- * this operation.
+ * Should be overridden by the specialized class if a more efficient method
+ * is available for implementing this operation.
* <P>
+ *
* @see IRequestQueue#listRequests
*/
public IRequestList listRequests() {
@@ -510,10 +514,10 @@ public abstract class ARequestQueue
/**
* Implements IRequestQueue.listRequestsByStatus
* <p>
- * Should be overridden by the specialized class if
- * a more efficient method is available for implementing
- * this operation.
+ * Should be overridden by the specialized class if a more efficient method
+ * is available for implementing this operation.
* <P>
+ *
* @see IRequestQueue#listRequestsByStatus
*/
public IRequestList listRequestsByStatus(RequestStatus s) {
@@ -523,6 +527,7 @@ public abstract class ARequestQueue
/**
* Implements IRequestQueue.releaseRequest
* <p>
+ *
* @see IRequestQueue#releaseRequest
*/
public final void releaseRequest(IRequest request) {
@@ -534,17 +539,18 @@ public abstract class ARequestQueue
String name = getUserIdentity();
- if (name != null) r.setExtData(IRequest.UPDATED_BY, name);
+ if (name != null)
+ r.setExtData(IRequest.UPDATED_BY, name);
- // TODO: use a state flag to determine whether to call
- // addRequest or modifyRequest (see newRequest as well)
+ // TODO: use a state flag to determine whether to call
+ // addRequest or modifyRequest (see newRequest as well)
modifyRequest(r);
}
// PRIVATE functions
private final void stateEngine(IRequest r)
- throws EBaseException {
+ throws EBaseException {
boolean complete = false;
while (!complete) {
@@ -618,14 +624,14 @@ public abstract class ARequestQueue
// write the queue name and request id
// write who changed it
// write what change (which state change) was made
- // - new (processRequest)
- // - approve
- // - reject
+ // - new (processRequest)
+ // - approve
+ // - reject
// Ordering
- // - make change in memory
- // - log change and result
- // - update record
+ // - make change in memory
+ // - log change and result
+ // - update record
}
/**
@@ -644,15 +650,15 @@ public abstract class ARequestQueue
*/
public void recover() {
if (CMS.isRunningMode()) {
- RecoverThread t = new RecoverThread(this);
+ RecoverThread t = new RecoverThread(this);
- t.start();
+ t.start();
}
}
/**
- * recover from a crash. Resends all requests that are in
- * the APPROVED state.
+ * recover from a crash. Resends all requests that are in the APPROVED
+ * state.
*/
public void recoverWillBlock() {
// Get a list of all requests that are APPROVED
@@ -665,7 +671,7 @@ public abstract class ARequestQueue
try {
request = findRequest(rid);
- //if (request == null) log_error
+ // if (request == null) log_error
// Recheck the status - should be the same!!
if (request.getRequestStatus() == RequestStatus.APPROVED) {
@@ -685,7 +691,7 @@ public abstract class ARequestQueue
// Constructor
protected ARequestQueue(IPolicy policy, IService service, INotify notify,
- INotify pendingNotify) {
+ INotify pendingNotify) {
mPolicy = policy;
mService = service;
mNotify = notify;
@@ -705,44 +711,30 @@ public abstract class ARequestQueue
protected ILogger mLogger;
}
-
//
// Table of RequestId values that are currently in use by some thread.
// The fact that the request is in this table constitutes a lock
// on the value.
//
/*
- class RequestIDTable {
- public synchronized void lock(RequestId id) {
- while (true) {
- if (mHashtable.put(id, id) == null)
- break;
-
- try {
- wait();
- } catch (InterruptedException e) {
- };
- }
- }
-
- public synchronized void unlock(RequestId id) {
- mHashtable.remove(id);
-
- notifyAll();
- }
-
- // instance variables
- Hashtable mHashtable = new Hashtable();
- }
+ * class RequestIDTable { public synchronized void lock(RequestId id) { while
+ * (true) { if (mHashtable.put(id, id) == null) break;
+ *
+ * try { wait(); } catch (InterruptedException e) { }; } }
+ *
+ * public synchronized void unlock(RequestId id) { mHashtable.remove(id);
+ *
+ * notifyAll(); }
+ *
+ * // instance variables Hashtable mHashtable = new Hashtable(); }
*/
-
//
-// Request - implementation of the IRequest interface. This
+// Request - implementation of the IRequest interface. This
// version is returned by ARequestQueue (and its derivatives)
//
class Request
- implements IRequest {
+ implements IRequest {
// IRequest.getRequestId
public RequestId getRequestId() {
return mRequestId;
@@ -835,8 +827,8 @@ class Request
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
if (!key.equals(IRequest.ISSUED_CERTS) &&
- !key.equals(IRequest.ERRORS) &&
- !key.equals(IRequest.REMOTE_REQID)) {
+ !key.equals(IRequest.ERRORS) &&
+ !key.equals(IRequest.REMOTE_REQID)) {
if (req.isSimpleExtDataValue(key)) {
setExtData(key, req.getExtDataInString(key));
} else {
@@ -848,15 +840,15 @@ class Request
/**
* This function used to check that the keys obeyed LDAP attribute name
- * syntax rules. Keys are being encoded now, so it is changed to just
- * filter out null and empty string keys.
- *
- * @param key The key to check
- * @return false if invalid
+ * syntax rules. Keys are being encoded now, so it is changed to just filter
+ * out null and empty string keys.
+ *
+ * @param key The key to check
+ * @return false if invalid
*/
protected boolean isValidExtDataKey(String key) {
return key != null &&
- (! key.equals(""));
+ (!key.equals(""));
}
protected boolean isValidExtDataHashtableValue(Hashtable<String, Object> hash) {
@@ -866,15 +858,14 @@ class Request
Enumeration<String> keys = hash.keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
- if (! ((key instanceof String) &&
- isValidExtDataKey((String)key)) ) {
+ if (!((key instanceof String) && isValidExtDataKey((String) key))) {
return false;
}
/*
- * TODO should the Value type be String?
+ * TODO should the Value type be String?
*/
Object value = hash.get(key);
- if (! (value instanceof String)) {
+ if (!(value instanceof String)) {
return false;
}
}
@@ -883,7 +874,7 @@ class Request
}
public boolean setExtData(String key, String value) {
- if (! isValidExtDataKey(key)) {
+ if (!isValidExtDataKey(key)) {
return false;
}
if (value == null) {
@@ -895,8 +886,8 @@ class Request
}
@SuppressWarnings("unchecked")
- public boolean setExtData(String key, Hashtable<String, ?> value) {
- if ( !(isValidExtDataKey(key) && isValidExtDataHashtableValue((Hashtable<String, Object>) value)) ) {
+ public boolean setExtData(String key, Hashtable<String, ?> value) {
+ if (!(isValidExtDataKey(key) && isValidExtDataHashtableValue((Hashtable<String, Object>) value))) {
return false;
}
@@ -913,22 +904,22 @@ class Request
if (value == null) {
return null;
}
- if (! (value instanceof String)) {
+ if (!(value instanceof String)) {
return null;
}
- return (String)value;
+ return (String) value;
}
@SuppressWarnings("unchecked")
- public <V> Hashtable<String, V> getExtDataInHashtable(String key) {
+ public <V> Hashtable<String, V> getExtDataInHashtable(String key) {
Object value = mExtData.get(key);
if (value == null) {
return null;
}
- if (! (value instanceof Hashtable)) {
+ if (!(value instanceof Hashtable)) {
return null;
}
- return new ExtDataHashtable<V>((Map<? extends String, ? extends V>)value);
+ return new ExtDataHashtable<V>((Map<? extends String, ? extends V>) value);
}
public Enumeration<String> getExtDataKeys() {
@@ -940,7 +931,7 @@ class Request
}
public boolean setExtData(String key, String subkey, String value) {
- if (! (isValidExtDataKey(key) && isValidExtDataKey(subkey)) ) {
+ if (!(isValidExtDataKey(key) && isValidExtDataKey(subkey))) {
return false;
}
if (isSimpleExtDataValue(key)) {
@@ -951,7 +942,7 @@ class Request
}
@SuppressWarnings("unchecked")
- Hashtable<String, String> existingValue = (Hashtable<String, String>)mExtData.get(key);
+ Hashtable<String, String> existingValue = (Hashtable<String, String>) mExtData.get(key);
if (existingValue == null) {
existingValue = new ExtDataHashtable<String>();
mExtData.put(key, existingValue);
@@ -965,7 +956,7 @@ class Request
if (value == null) {
return null;
}
- return (String)value.get(subkey);
+ return (String) value.get(subkey);
}
public boolean setExtData(String key, Integer value) {
@@ -1229,7 +1220,7 @@ class Request
return false;
}
try {
- stringArray = (String[])stringVector.toArray(new String[0]);
+ stringArray = (String[]) stringVector.toArray(new String[0]);
} catch (ArrayStoreException e) {
return false;
}
@@ -1392,7 +1383,7 @@ class Request
listValue.set(index,
hashValue.get(arrayKey));
}
- return (String[])listValue.toArray(new String[0]);
+ return (String[]) listValue.toArray(new String[0]);
}
public IAttrSet asIAttrSet() {
@@ -1431,7 +1422,7 @@ class RequestIAttrSetWrapper implements IAttrSet {
public void set(String name, Object obj) throws EBaseException {
try {
- mRequest.setExtData(name, (String)obj);
+ mRequest.setExtData(name, (String) obj);
} catch (ClassCastException e) {
throw new EBaseException(e.toString());
}
@@ -1450,21 +1441,19 @@ class RequestIAttrSetWrapper implements IAttrSet {
}
}
-
/**
* Example of a specialized request class.
*/
class EnrollmentRequest
- extends Request
- implements IEnrollmentRequest {
+ extends Request
+ implements IEnrollmentRequest {
EnrollmentRequest(RequestId id) {
super(id);
}
}
-
class RequestListByStatus
- implements IRequestList {
+ implements IRequestList {
public boolean hasMoreElements() {
return (mNext != null);
}
@@ -1507,14 +1496,16 @@ class RequestListByStatus
mNext = null;
while (mNext == null) {
- if (!mEnumeration.hasMoreElements()) break;
-
- rId = mEnumeration.nextElement();
+ if (!mEnumeration.hasMoreElements())
+ break;
+
+ rId = mEnumeration.nextElement();
try {
IRequest r = mQueue.findRequest(rId);
- if (r.getRequestStatus() == mStatus) mNext = rId;
+ if (r.getRequestStatus() == mStatus)
+ mNext = rId;
mQueue.releaseRequest(r);
} catch (Exception e) {
@@ -1524,13 +1515,12 @@ class RequestListByStatus
protected RequestStatus mStatus;
protected IRequestQueue mQueue;
- protected Enumeration<RequestId> mEnumeration;
+ protected Enumeration<RequestId> mEnumeration;
protected RequestId mNext;
}
-
class RequestList
- implements IRequestList {
+ implements IRequestList {
public boolean hasMoreElements() {
return mEnumeration.hasMoreElements();
}
@@ -1555,10 +1545,9 @@ class RequestList
mEnumeration = e;
}
- protected Enumeration<RequestId> mEnumeration;
+ protected Enumeration<RequestId> mEnumeration;
}
-
class RecoverThread extends Thread {
private ARequestQueue mQ = null;
diff --git a/pki/base/common/src/com/netscape/cmscore/request/ARequestRecord.java b/pki/base/common/src/com/netscape/cmscore/request/ARequestRecord.java
index f85beca0..14a6cbcf 100644
--- a/pki/base/common/src/com/netscape/cmscore/request/ARequestRecord.java
+++ b/pki/base/common/src/com/netscape/cmscore/request/ARequestRecord.java
@@ -17,22 +17,19 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.request;
-
import java.util.Date;
import java.util.Hashtable;
import com.netscape.certsrv.request.RequestId;
import com.netscape.certsrv.request.RequestStatus;
-
/**
- * The low level (attributes only) version of the database
- * record object. This exists so that RecordAttr methods can use
- * this type definition,
+ * The low level (attributes only) version of the database record object. This
+ * exists so that RecordAttr methods can use this type definition,
*
* RequestRecord refers both to this class and to RecordAttr objects.
*/
-class ARequestRecord {
+class ARequestRecord {
RequestId mRequestId;
RequestStatus mRequestState;
Date mCreateTime;
diff --git a/pki/base/common/src/com/netscape/cmscore/request/CertRequestConstants.java b/pki/base/common/src/com/netscape/cmscore/request/CertRequestConstants.java
index 7494b5e4..134166f6 100644
--- a/pki/base/common/src/com/netscape/cmscore/request/CertRequestConstants.java
+++ b/pki/base/common/src/com/netscape/cmscore/request/CertRequestConstants.java
@@ -17,15 +17,13 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.request;
-
/**
- * temporary location for cert request constants.
- * XXX we really need to centralize all these but for now they are here
- * as needed.
+ * temporary location for cert request constants. XXX we really need to
+ * centralize all these but for now they are here as needed.
*/
public class CertRequestConstants {
- // request types - these have string values.
- // made to match policy constants.
+ // request types - these have string values.
+ // made to match policy constants.
public final static String GETCRL_REQUEST = "getCRL";
public final static String GETCACHAIN_REQUEST = "getCAChain";
public final static String GETREVOCATIONINFO_REQUEST = "getRevocationInfo";
@@ -51,7 +49,7 @@ public class CertRequestConstants {
// this has a CRLExtensions value.
public final static String CRLEXTS = "CRLExts";
- // this has a String value - it is either null or set.
+ // this has a String value - it is either null or set.
public final static String DOGETCACHAIN = "doGetCAChain";
// this has a CertificateChain value.
@@ -64,7 +62,7 @@ public class CertRequestConstants {
public final static String CERTIFICATE = "certificate";
// this is an array of EBaseException for service errors when
- // there's an error processing an array of something such as
+ // there's an error processing an array of something such as
// certs to renew, certs to revoke, etc.
public final static String SVCERRORS = "serviceErrors";
diff --git a/pki/base/common/src/com/netscape/cmscore/request/ExtDataHashtable.java b/pki/base/common/src/com/netscape/cmscore/request/ExtDataHashtable.java
index e3c1908e..8bc4d982 100644
--- a/pki/base/common/src/com/netscape/cmscore/request/ExtDataHashtable.java
+++ b/pki/base/common/src/com/netscape/cmscore/request/ExtDataHashtable.java
@@ -6,9 +6,9 @@ import java.util.Map;
import java.util.Set;
/**
- * Subclass of Hashtable returned by IRequest.getExtDataInHashtable. Its
- * purpose is to hide the fact that LDAP doesn't preserve the case of keys.
- * It does this by lowercasing all keys used to access the Hashtable.
+ * Subclass of Hashtable returned by IRequest.getExtDataInHashtable. Its purpose
+ * is to hide the fact that LDAP doesn't preserve the case of keys. It does this
+ * by lowercasing all keys used to access the Hashtable.
*/
public class ExtDataHashtable<V> extends Hashtable<String, V> {
@@ -38,7 +38,7 @@ public class ExtDataHashtable<V> extends Hashtable<String, V> {
public boolean containsKey(Object o) {
if (o instanceof String) {
- String key = (String)o;
+ String key = (String) o;
return super.containsKey(key.toLowerCase());
}
return super.containsKey(o);
@@ -46,7 +46,7 @@ public class ExtDataHashtable<V> extends Hashtable<String, V> {
public V get(Object o) {
if (o instanceof String) {
- String key = (String)o;
+ String key = (String) o;
return super.get(key.toLowerCase());
}
return super.get(o);
@@ -54,7 +54,7 @@ public class ExtDataHashtable<V> extends Hashtable<String, V> {
public V put(String oKey, V val) {
if (oKey instanceof String) {
- String key = (String)oKey;
+ String key = (String) oKey;
return super.put(key.toLowerCase(), val);
}
return super.put(oKey, val);
@@ -62,16 +62,15 @@ public class ExtDataHashtable<V> extends Hashtable<String, V> {
public void putAll(Map<? extends String, ? extends V> map) {
Set<? extends String> keys = map.keySet();
- for (Iterator<? extends String> i = keys.iterator();
- i.hasNext();) {
+ for (Iterator<? extends String> i = keys.iterator(); i.hasNext();) {
Object key = i.next();
- put((String)key, map.get(key));
+ put((String) key, map.get(key));
}
}
public V remove(Object o) {
if (o instanceof String) {
- String key = (String)o;
+ String key = (String) o;
return super.remove(key.toLowerCase());
}
return super.remove(o);
diff --git a/pki/base/common/src/com/netscape/cmscore/request/RequestAttr.java b/pki/base/common/src/com/netscape/cmscore/request/RequestAttr.java
index 4583a1fa..d7ac32be 100644
--- a/pki/base/common/src/com/netscape/cmscore/request/RequestAttr.java
+++ b/pki/base/common/src/com/netscape/cmscore/request/RequestAttr.java
@@ -17,28 +17,24 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.request;
-
import com.netscape.certsrv.dbs.IDBAttrMapper;
import com.netscape.certsrv.dbs.Modification;
import com.netscape.certsrv.dbs.ModificationSet;
import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.ldap.IRequestMod;
-
/**
- * The RequestAttr class defines the methods used
- * to transfer data between the various representations of
- * a request. The three forms are:
- * 1) LDAPAttributes (and Modifications)
- * 2) Database record IDBAttrSet
- * 3) IRequest (Request) object
+ * The RequestAttr class defines the methods used to transfer data between the
+ * various representations of a request. The three forms are: 1) LDAPAttributes
+ * (and Modifications) 2) Database record IDBAttrSet 3) IRequest (Request)
+ * object
*/
abstract class RequestAttr {
/**
*
*/
-
+
abstract void set(ARequestRecord r, Object o);
abstract Object get(ARequestRecord r);
diff --git a/pki/base/common/src/com/netscape/cmscore/request/RequestQueue.java b/pki/base/common/src/com/netscape/cmscore/request/RequestQueue.java
index b748f23b..b1a313c8 100644
--- a/pki/base/common/src/com/netscape/cmscore/request/RequestQueue.java
+++ b/pki/base/common/src/com/netscape/cmscore/request/RequestQueue.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.request;
-
import java.math.BigInteger;
import java.util.Date;
import java.util.Enumeration;
@@ -43,13 +42,12 @@ import com.netscape.certsrv.request.ldap.IRequestMod;
import com.netscape.cmscore.dbs.DBSubsystem;
import com.netscape.cmscore.util.Debug;
-
public class RequestQueue
- extends ARequestQueue
- implements IRequestMod {
+ extends ARequestQueue
+ implements IRequestMod {
// ARequestQueue.newRequestId
protected RequestId newRequestId()
- throws EBaseException {
+ throws EBaseException {
// get the next request Id
BigInteger next = mRepository.getNextSerialNumber();
@@ -63,7 +61,7 @@ public class RequestQueue
// String name = Schema.LDAP_ATTR_REQUEST_ID + "=" +
String name = "cn" + "=" +
- id + "," + mBaseDN;
+ id + "," + mBaseDN;
Object obj = null;
IDBSSession dbs = null;
@@ -71,29 +69,29 @@ public class RequestQueue
try {
dbs = mDB.createSession();
obj = dbs.read(name);
- } catch (EBaseException e) {
- Debug.trace("Error: " + e);
+ } catch (EBaseException e) {
+ Debug.trace("Error: " + e);
Debug.printStackTrace(e);
} finally {
// Close session - ignoring errors (UTIL)
- if (dbs != null) try {
+ if (dbs != null)
+ try {
dbs.close();
} catch (EBaseException e) {
}
}
// TODO Errors!!!
- if (obj == null || !(obj instanceof RequestRecord)) return null;
+ if (obj == null || !(obj instanceof RequestRecord))
+ return null;
record = (RequestRecord) obj;
/*
- setRequestStatus(r, record.mRequestState);
- r.setSourceId(record.mSourceId);
- r.setRequestOwner(record.mOwner);
- record.storeAttrs(r, record.mRequestAttrs);
- setModificationTime(r, record.mModifyTime);
- setCreationTime(r, record.mCreateTime);
+ * setRequestStatus(r, record.mRequestState);
+ * r.setSourceId(record.mSourceId); r.setRequestOwner(record.mOwner);
+ * record.storeAttrs(r, record.mRequestAttrs); setModificationTime(r,
+ * record.mModifyTime); setCreationTime(r, record.mCreateTime);
*/
return makeRequest(record);
}
@@ -107,20 +105,21 @@ public class RequestQueue
// compute the name of the object
// String name = Schema.LDAP_ATTR_REQUEST_ID + "=" +
String name = "cn" + "=" +
- record.mRequestId + "," + mBaseDN;
+ record.mRequestId + "," + mBaseDN;
IDBSSession dbs = null;
try {
dbs = mDB.createSession();
dbs.add(name, record);
- } catch (EBaseException e) {
- Debug.trace("Error: " + e);
+ } catch (EBaseException e) {
+ Debug.trace("Error: " + e);
Debug.printStackTrace(e);
throw e;
} finally {
// Close session - ignoring errors (UTIL)
- if (dbs != null) try {
+ if (dbs != null)
+ try {
dbs.close();
} catch (EBaseException e) {
}
@@ -150,39 +149,39 @@ public class RequestQueue
}
/*
- //
- mods.add(IRequestRecord.ATTR_REQUEST_STATE,
- Modification.MOD_REPLACE, r.getRequestStatus());
-
- mods.add(IRequestRecord.ATTR_SOURCE_ID,
- Modification.MOD_REPLACE, r.getSourceId());
-
- mods.add(IRequestRecord.ATTR_REQUEST_OWNER,
- Modification.MOD_REPLACE, r.getRequestOwner());
-
- mods.add(IRequestRecord.ATTR_MODIFY_TIME,
- Modification.MOD_REPLACE, r.getModificationTime());
-
- java.util.Hashtable ht = RequestRecord.loadAttrs(r);
- mods.add(RequestRecord.ATTR_REQUEST_ATTRS,
- Modification.MOD_REPLACE, ht);
+ * // mods.add(IRequestRecord.ATTR_REQUEST_STATE,
+ * Modification.MOD_REPLACE, r.getRequestStatus());
+ *
+ * mods.add(IRequestRecord.ATTR_SOURCE_ID, Modification.MOD_REPLACE,
+ * r.getSourceId());
+ *
+ * mods.add(IRequestRecord.ATTR_REQUEST_OWNER, Modification.MOD_REPLACE,
+ * r.getRequestOwner());
+ *
+ * mods.add(IRequestRecord.ATTR_MODIFY_TIME, Modification.MOD_REPLACE,
+ * r.getModificationTime());
+ *
+ * java.util.Hashtable ht = RequestRecord.loadAttrs(r);
+ * mods.add(RequestRecord.ATTR_REQUEST_ATTRS, Modification.MOD_REPLACE,
+ * ht);
*/
// String name = Schema.LDAP_ATTR_REQUEST_ID + "=" +
String name = "cn" + "=" +
- r.getRequestId() + "," + mBaseDN;
+ r.getRequestId() + "," + mBaseDN;
IDBSSession dbs = null;
try {
dbs = mDB.createSession();
dbs.modify(name, mods);
- } catch (EBaseException e) {
- Debug.trace("Error: " + e);
+ } catch (EBaseException e) {
+ Debug.trace("Error: " + e);
Debug.printStackTrace(e);
} finally {
// Close session - ignoring errors (UTIL)
- if (dbs != null) try {
+ if (dbs != null)
+ try {
dbs.close();
} catch (EBaseException e) {
}
@@ -218,34 +217,30 @@ public class RequestQueue
/**
* Resets serial number.
*/
- public void resetSerialNumber(BigInteger serial) throws EBaseException
- {
+ public void resetSerialNumber(BigInteger serial) throws EBaseException {
mRepository.resetSerialNumber(serial);
}
-
+
/**
* Removes all objects with this repository.
*/
- public void removeAllObjects() throws EBaseException
- {
+ public void removeAllObjects() throws EBaseException {
mRepository.removeAllObjects();
}
- public BigInteger getLastRequestIdInRange(BigInteger reqId_low_bound, BigInteger reqId_upper_bound)
- {
+ public BigInteger getLastRequestIdInRange(BigInteger reqId_low_bound, BigInteger reqId_upper_bound) {
CMS.debug("RequestQueue: getLastRequestId: low " + reqId_low_bound + " high " + reqId_upper_bound);
- if(reqId_low_bound == null || reqId_upper_bound == null || reqId_low_bound.compareTo(reqId_upper_bound) >= 0)
- {
+ if (reqId_low_bound == null || reqId_upper_bound == null || reqId_low_bound.compareTo(reqId_upper_bound) >= 0) {
CMS.debug("RequestQueue: getLastRequestId: bad upper and lower bound range.");
return null;
}
- String filter = "(" + "requeststate" + "=*" + ")";
+ String filter = "(" + "requeststate" + "=*" + ")";
RequestId fromId = new RequestId(reqId_upper_bound.toString(10));
CMS.debug("RequestQueue: getLastRequestId: filter " + filter + " fromId " + fromId);
- ListEnumeration recList = (ListEnumeration) getPagedRequestsByFilter(fromId,filter,5 * -1,"requestId");
+ ListEnumeration recList = (ListEnumeration) getPagedRequestsByFilter(fromId, filter, 5 * -1, "requestId");
int size = recList.getSize();
@@ -272,33 +267,29 @@ public class RequestQueue
String reqId = null;
- for(int i = 0; i < 5; i++)
- {
- curRec = recList.getElementAt(i);
-
- if(curRec != null) {
+ for (int i = 0; i < 5; i++) {
+ curRec = recList.getElementAt(i);
- curId = curRec.getRequestId();
+ if (curRec != null) {
- reqId = curId.toString();
+ curId = curRec.getRequestId();
- CMS.debug("RequestQueue: curReqId: " + reqId);
+ reqId = curId.toString();
- BigInteger curIdInt = new BigInteger(reqId);
+ CMS.debug("RequestQueue: curReqId: " + reqId);
+ BigInteger curIdInt = new BigInteger(reqId);
- if( ((curIdInt.compareTo(reqId_low_bound) == 0) || (curIdInt.compareTo(reqId_low_bound) == 1) ) &&
- ((curIdInt.compareTo(reqId_upper_bound) == 0) || (curIdInt.compareTo(reqId_upper_bound) == -1) ))
- {
- CMS.debug("RequestQueue: getLastRequestId : returning value " + curIdInt);
- return curIdInt;
- }
+ if (((curIdInt.compareTo(reqId_low_bound) == 0) || (curIdInt.compareTo(reqId_low_bound) == 1)) &&
+ ((curIdInt.compareTo(reqId_upper_bound) == 0) || (curIdInt.compareTo(reqId_upper_bound) == -1))) {
+ CMS.debug("RequestQueue: getLastRequestId : returning value " + curIdInt);
+ return curIdInt;
+ }
- }
+ }
}
-
BigInteger ret = new BigInteger(reqId_low_bound.toString(10));
ret = ret.add(new BigInteger("-1"));
@@ -311,12 +302,14 @@ public class RequestQueue
/**
* Implements IRequestQueue.findRequestBySourceId
* <p>
+ *
* @see com.netscape.certsrv.request.IRequestQueue#findRequestBySourceId
*/
public RequestId findRequestBySourceId(String id) {
IRequestList irl = findRequestsBySourceId(id);
- if (irl == null) return null;
+ if (irl == null)
+ return null;
return irl.nextRequestId();
}
@@ -324,6 +317,7 @@ public class RequestQueue
/**
* Implements IRequestQueue.findRequestsBySourceId
* <p>
+ *
* @see com.netscape.certsrv.request.IRequestQueue#findRequestsBySourceId
*/
public IRequestList findRequestsBySourceId(String id) {
@@ -343,13 +337,15 @@ public class RequestQueue
Debug.printStackTrace(e);
} finally {
// Close session - ignoring errors (UTIL)
- if (dbs != null) try {
+ if (dbs != null)
+ try {
dbs.close();
} catch (EBaseException e) {
}
}
- if (results == null || !results.hasMoreElements()) return null;
+ if (results == null || !results.hasMoreElements())
+ return null;
return new SearchEnumeration(this, results);
@@ -363,18 +359,20 @@ public class RequestQueue
try {
dbs = mDB.createSession();
results = dbs.search(mBaseDN, "(requestId=*)");
- } catch (EBaseException e) {
- Debug.trace("Error: " + e);
+ } catch (EBaseException e) {
+ Debug.trace("Error: " + e);
Debug.printStackTrace(e);
} finally {
// Close session - ignoring errors (UTIL)
- if (dbs != null) try {
+ if (dbs != null)
+ try {
dbs.close();
} catch (EBaseException e) {
}
}
- if (results == null) return null;
+ if (results == null)
+ return null;
return new SearchEnumeration(this, results);
}
@@ -389,18 +387,20 @@ public class RequestQueue
try {
dbs = mDB.createSession();
results = dbs.search(mBaseDN, f);
- } catch (EBaseException e) {
- Debug.trace("Error: " + e);
+ } catch (EBaseException e) {
+ Debug.trace("Error: " + e);
Debug.printStackTrace(e);
} finally {
// Close session - ignoring errors (UTIL)
- if (dbs != null) try {
+ if (dbs != null)
+ try {
dbs.close();
} catch (EBaseException e) {
}
}
- if (results == null) return null;
+ if (results == null)
+ return null;
return new SearchEnumeration(this, results);
}
@@ -411,7 +411,7 @@ public class RequestQueue
IDBSearchResults results = null;
IDBSSession dbs = null;
String attrs[] = { IRequestRecord.ATTR_REQUEST_ID };
-
+
try {
dbs = mDB.createSession();
results = dbs.search(mBaseDN, f, maxSize);
@@ -420,14 +420,16 @@ public class RequestQueue
Debug.printStackTrace(e);
} finally {
// Close session - ignoring errors (UTIL)
- if (dbs != null) try {
+ if (dbs != null)
+ try {
dbs.close();
} catch (EBaseException e) {
}
}
-
- if (results == null) return null;
-
+
+ if (results == null)
+ return null;
+
return new SearchEnumeration(this, results);
}
@@ -446,13 +448,15 @@ public class RequestQueue
Debug.printStackTrace(e);
} finally {
// Close session - ignoring errors (UTIL)
- if (dbs != null) try {
+ if (dbs != null)
+ try {
dbs.close();
} catch (EBaseException e) {
}
}
- if (results == null) return null;
+ if (results == null)
+ return null;
return new SearchEnumeration(this, results);
}
@@ -473,18 +477,20 @@ public class RequestQueue
dbs = mDB.createSession();
results = dbs.search(mBaseDN, f1);
- } catch (EBaseException e) {
- //System.err.println("Error: "+e);
- //e.printStackTrace();
+ } catch (EBaseException e) {
+ // System.err.println("Error: "+e);
+ // e.printStackTrace();
} finally {
// Close session - ignoring errors (UTIL)
- if (dbs != null) try {
+ if (dbs != null)
+ try {
dbs.close();
} catch (EBaseException e) {
}
}
- if (results == null) return null;
+ if (results == null)
+ return null;
return new SearchEnumeration(this, results);
}
@@ -500,19 +506,19 @@ public class RequestQueue
* Implements IRequestQueue.getPagedRequestsByFilter
*/
public IRequestVirtualList
- getPagedRequestsByFilter(String filter, int pageSize, String sortKey) {
+ getPagedRequestsByFilter(String filter, int pageSize, String sortKey) {
return getPagedRequestsByFilter(null, filter, pageSize, sortKey);
}
public IRequestVirtualList
- getPagedRequestsByFilter(RequestId from, String filter, int pageSize,
- String sortKey) {
- return getPagedRequestsByFilter(from, false, filter, pageSize, sortKey);
+ getPagedRequestsByFilter(RequestId from, String filter, int pageSize,
+ String sortKey) {
+ return getPagedRequestsByFilter(from, false, filter, pageSize, sortKey);
}
public IRequestVirtualList
- getPagedRequestsByFilter(RequestId from, boolean jumpToEnd, String filter, int pageSize,
- String sortKey) {
+ getPagedRequestsByFilter(RequestId from, boolean jumpToEnd, String filter, int pageSize,
+ String sortKey) {
IDBVirtualList results = null;
IDBSSession dbs = null;
@@ -525,24 +531,24 @@ public class RequestQueue
try {
if (from == null) {
- results = dbs.createVirtualList(mBaseDN, filter, (String[]) null,
+ results = dbs.createVirtualList(mBaseDN, filter, (String[]) null,
sortKey, pageSize);
} else {
int len = from.toString().length();
String internalRequestId = null;
if (jumpToEnd) {
- internalRequestId ="99";
- } else {
- if (len > 9) {
- internalRequestId = Integer.toString(len) + from.toString();
+ internalRequestId = "99";
} else {
- internalRequestId = "0" + Integer.toString(len) +
- from.toString();
+ if (len > 9) {
+ internalRequestId = Integer.toString(len) + from.toString();
+ } else {
+ internalRequestId = "0" + Integer.toString(len) +
+ from.toString();
+ }
}
- }
- results = dbs.createVirtualList(mBaseDN, filter, (String[]) null,
+ results = dbs.createVirtualList(mBaseDN, filter, (String[]) null,
internalRequestId, sortKey, pageSize);
}
} catch (EBaseException e) {
@@ -556,7 +562,7 @@ public class RequestQueue
try {
results.setSortKey(sortKey);
- } catch (EBaseException e) {//XXX
+ } catch (EBaseException e) {// XXX
System.out.println(e.toString());
return null;
}
@@ -565,14 +571,14 @@ public class RequestQueue
}
public RequestQueue(String name, int increment, IPolicy p, IService s, INotify n,
- INotify pendingNotify)
- throws EBaseException {
+ INotify pendingNotify)
+ throws EBaseException {
super(p, s, n, pendingNotify);
mDB = DBSubsystem.getInstance();
mBaseDN = "ou=" + name + ",ou=requests," + mDB.getBaseDN();
- mRepository = new RequestRepository(name, increment, mDB,this);
+ mRepository = new RequestRepository(name, increment, mDB, this);
}
@@ -591,8 +597,8 @@ public class RequestQueue
}
/*
- * return request repository
- */
+ * return request repository
+ */
public IRepository getRequestRepository() {
return (IRepository) mRepository;
}
@@ -610,15 +616,15 @@ public class RequestQueue
protected RequestRepository mRepository;
}
-
class SearchEnumeration
- implements IRequestList {
+ implements IRequestList {
public RequestId nextRequestId() {
Object obj;
obj = mResults.nextElement();
- if (obj == null || !(obj instanceof RequestRecord)) return null;
+ if (obj == null || !(obj instanceof RequestRecord))
+ return null;
RequestRecord r = (RequestRecord) obj;
@@ -647,7 +653,8 @@ class SearchEnumeration
obj = mResults.nextElement();
- if (obj == null || !(obj instanceof RequestRecord)) return null;
+ if (obj == null || !(obj instanceof RequestRecord))
+ return null;
RequestRecord r = (RequestRecord) obj;
@@ -655,7 +662,7 @@ class SearchEnumeration
}
public IRequest nextRequestObject() {
- RequestRecord record = (RequestRecord)nextRequest();
+ RequestRecord record = (RequestRecord) nextRequest();
if (record != null)
return mQueue.makeRequest(record);
return null;
@@ -665,13 +672,13 @@ class SearchEnumeration
protected RequestQueue mQueue;
}
-
class ListEnumeration
- implements IRequestVirtualList {
+ implements IRequestVirtualList {
public IRequest getElementAt(int i) {
RequestRecord record = (RequestRecord) mList.getElementAt(i);
- if (record == null) return null;
+ if (record == null)
+ return null;
return mQueue.makeRequest(record);
}
@@ -693,6 +700,7 @@ class ListEnumeration
return mList.getSizeAfterJumpTo();
}
+
ListEnumeration(RequestQueue queue, IDBVirtualList list) {
mQueue = queue;
mList = list;
diff --git a/pki/base/common/src/com/netscape/cmscore/request/RequestRecord.java b/pki/base/common/src/com/netscape/cmscore/request/RequestRecord.java
index 321e32ec..d7570ad9 100644
--- a/pki/base/common/src/com/netscape/cmscore/request/RequestRecord.java
+++ b/pki/base/common/src/com/netscape/cmscore/request/RequestRecord.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.request;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -53,15 +52,14 @@ import com.netscape.cmscore.dbs.DateMapper;
import com.netscape.cmscore.dbs.StringMapper;
import com.netscape.cmscore.util.Debug;
-
//
// A request record is the stored version of a request.
// It has a set of attributes that are mapped into LDAP
// attributes for actual directory operations.
//
public class RequestRecord
- extends ARequestRecord
- implements IRequestRecord, IDBObj {
+ extends ARequestRecord
+ implements IRequestRecord, IDBObj {
/**
*
*/
@@ -96,7 +94,8 @@ public class RequestRecord
else {
RequestAttr ra = (RequestAttr) mAttrTable.get(name);
- if (ra != null) return ra.get(this);
+ if (ra != null)
+ return ra.get(this);
}
return null;
@@ -104,7 +103,7 @@ public class RequestRecord
// IDBObj.set
@SuppressWarnings("unchecked")
- public void set(String name, Object o) {
+ public void set(String name, Object o) {
if (name.equals(IRequestRecord.ATTR_REQUEST_ID))
mRequestId = (RequestId) o;
else if (name.equals(IRequestRecord.ATTR_REQUEST_STATE))
@@ -120,17 +119,18 @@ public class RequestRecord
else if (name.equals(IRequestRecord.ATTR_REQUEST_OWNER))
mOwner = (String) o;
else if (name.equals(IRequestRecord.ATTR_EXT_DATA))
- mExtData = (Hashtable)o;
+ mExtData = (Hashtable) o;
else {
RequestAttr ra = (RequestAttr) mAttrTable.get(name);
- if (ra != null) ra.set(this, o);
+ if (ra != null)
+ ra.set(this, o);
}
}
// IDBObj.delete
public void delete(String name)
- throws EBaseException {
+ throws EBaseException {
throw new EBaseException("Invalid call to delete");
}
@@ -177,19 +177,19 @@ public class RequestRecord
static void mod(ModificationSet mods, IRequest r) throws EBaseException {
//
mods.add(IRequestRecord.ATTR_REQUEST_STATE,
- Modification.MOD_REPLACE, r.getRequestStatus());
+ Modification.MOD_REPLACE, r.getRequestStatus());
mods.add(IRequestRecord.ATTR_SOURCE_ID,
- Modification.MOD_REPLACE, r.getSourceId());
+ Modification.MOD_REPLACE, r.getSourceId());
mods.add(IRequestRecord.ATTR_REQUEST_OWNER,
- Modification.MOD_REPLACE, r.getRequestOwner());
+ Modification.MOD_REPLACE, r.getRequestOwner());
mods.add(IRequestRecord.ATTR_MODIFY_TIME,
- Modification.MOD_REPLACE, r.getModificationTime());
+ Modification.MOD_REPLACE, r.getModificationTime());
mods.add(IRequestRecord.ATTR_EXT_DATA,
- Modification.MOD_REPLACE, loadExtDataFromRequest(r));
+ Modification.MOD_REPLACE, loadExtDataFromRequest(r));
for (int i = 0; i < mRequestA.length; i++) {
mRequestA[i].mod(mods, r);
@@ -197,7 +197,7 @@ public class RequestRecord
}
static void register(IDBSubsystem db)
- throws EDBException {
+ throws EDBException {
IDBRegistry reg = db.getRegistry();
reg.registerObjectClass(RequestRecord.class.getName(), mOC);
@@ -205,13 +205,13 @@ public class RequestRecord
reg.registerAttribute(IRequestRecord.ATTR_REQUEST_ID, new RequestIdMapper());
reg.registerAttribute(IRequestRecord.ATTR_REQUEST_STATE, new RequestStateMapper());
reg.registerAttribute(IRequestRecord.ATTR_CREATE_TIME,
- new DateMapper(Schema.LDAP_ATTR_CREATE_TIME));
+ new DateMapper(Schema.LDAP_ATTR_CREATE_TIME));
reg.registerAttribute(IRequestRecord.ATTR_MODIFY_TIME,
- new DateMapper(Schema.LDAP_ATTR_MODIFY_TIME));
+ new DateMapper(Schema.LDAP_ATTR_MODIFY_TIME));
reg.registerAttribute(IRequestRecord.ATTR_SOURCE_ID,
- new StringMapper(Schema.LDAP_ATTR_SOURCE_ID));
+ new StringMapper(Schema.LDAP_ATTR_SOURCE_ID));
reg.registerAttribute(IRequestRecord.ATTR_REQUEST_OWNER,
- new StringMapper(Schema.LDAP_ATTR_REQUEST_OWNER));
+ new StringMapper(Schema.LDAP_ATTR_REQUEST_OWNER));
ExtAttrDynMapper extAttrMapper = new ExtAttrDynMapper();
reg.registerAttribute(IRequestRecord.ATTR_EXT_DATA, extAttrMapper);
reg.registerDynamicMapper(extAttrMapper);
@@ -248,9 +248,9 @@ public class RequestRecord
String key = (String) e.nextElement();
Object value = mExtData.get(key);
if (value instanceof String) {
- r.setExtData(key, (String)value);
+ r.setExtData(key, (String) value);
} else if (value instanceof Hashtable) {
- r.setExtData(key, (Hashtable)value);
+ r.setExtData(key, (Hashtable) value);
} else {
throw new EDBException("Illegal data value in RequestRecord: " +
r.toString());
@@ -263,40 +263,40 @@ public class RequestRecord
static Hashtable mAttrTable = new Hashtable();
/*
- * This table contains attribute handlers for attributes
- * of the request. These attributes are ones that are stored
- * apart from the generic name/value pairs supported by the get/set
- * interface plus the hashtable for the name/value pairs themselves.
- *
- * NOTE: Eventually, all attributes should be done here. Currently
- * only the last ones added are implemented this way.
+ * This table contains attribute handlers for attributes of the request.
+ * These attributes are ones that are stored apart from the generic
+ * name/value pairs supported by the get/set interface plus the hashtable
+ * for the name/value pairs themselves.
+ *
+ * NOTE: Eventually, all attributes should be done here. Currently only the
+ * last ones added are implemented this way.
*/
static RequestAttr mRequestA[] = {
- new RequestAttr(IRequest.ATTR_REQUEST_TYPE,
+ new RequestAttr(IRequest.ATTR_REQUEST_TYPE,
new StringMapper(Schema.LDAP_ATTR_REQUEST_TYPE)) {
- void set(ARequestRecord r, Object o) {
- r.mRequestType = (String) o;
- }
-
- Object get(ARequestRecord r) {
- return r.mRequestType;
- }
-
- void read(IRequestMod a, IRequest r, ARequestRecord rr) {
- r.setRequestType(rr.mRequestType);
- }
-
- void add(IRequest r, ARequestRecord rr) {
- rr.mRequestType = r.getRequestType();
- }
-
- void mod(ModificationSet mods, IRequest r) {
- addmod(mods, r.getRequestType());
- }
- }
+ void set(ARequestRecord r, Object o) {
+ r.mRequestType = (String) o;
+ }
+
+ Object get(ARequestRecord r) {
+ return r.mRequestType;
+ }
+
+ void read(IRequestMod a, IRequest r, ARequestRecord rr) {
+ r.setRequestType(rr.mRequestType);
+ }
+
+ void add(IRequest r, ARequestRecord rr) {
+ rr.mRequestType = r.getRequestType();
+ }
+
+ void mod(ModificationSet mods, IRequest r) {
+ addmod(mods, r.getRequestType());
+ }
+ }
- };
+ };
static {
mAttrs.add(IRequestRecord.ATTR_REQUEST_ID);
mAttrs.add(IRequestRecord.ATTR_REQUEST_STATE);
@@ -316,7 +316,6 @@ public class RequestRecord
}
-
//
// A mapper between an request state object and
// its LDAP attribute representation
@@ -326,7 +325,7 @@ public class RequestRecord
// @version $Revision$ $Date$
//
class RequestStateMapper
- implements IDBAttrMapper {
+ implements IDBAttrMapper {
// IDBAttrMapper methods
//
@@ -337,7 +336,7 @@ class RequestStateMapper
//
public void mapObjectToLDAPAttributeSet(IDBObj parent,
- String name, Object obj, LDAPAttributeSet attrs) {
+ String name, Object obj, LDAPAttributeSet attrs) {
RequestStatus rs = (RequestStatus) obj;
attrs.add(new LDAPAttribute(Schema.LDAP_ATTR_REQUEST_STATE,
@@ -345,11 +344,12 @@ class RequestStateMapper
}
public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
- String name, IDBObj parent)
- throws EBaseException {
+ String name, IDBObj parent)
+ throws EBaseException {
LDAPAttribute attr = attrs.getAttribute(Schema.LDAP_ATTR_REQUEST_STATE);
- if (attr == null) throw new EBaseException("schema violation");
+ if (attr == null)
+ throw new EBaseException("schema violation");
String value = (String) attr.getStringValues().nextElement();
@@ -367,7 +367,6 @@ class RequestStateMapper
}
}
-
//
// A mapper between an request id object and
// its LDAP attribute representation
@@ -377,7 +376,7 @@ class RequestStateMapper
// @version $Revision$ $Date$
//
class RequestIdMapper
- implements IDBAttrMapper {
+ implements IDBAttrMapper {
// IDBAttrMapper methods
//
@@ -388,7 +387,7 @@ class RequestIdMapper
//
public void mapObjectToLDAPAttributeSet(IDBObj parent,
- String name, Object obj, LDAPAttributeSet attrs) {
+ String name, Object obj, LDAPAttributeSet attrs) {
RequestId rid = (RequestId) obj;
String v = BigIntegerMapper.BigIntegerToDB(new BigInteger(rid.toString()));
@@ -397,11 +396,12 @@ class RequestIdMapper
}
public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
- String name, IDBObj parent)
- throws EBaseException {
+ String name, IDBObj parent)
+ throws EBaseException {
LDAPAttribute attr = attrs.getAttribute(Schema.LDAP_ATTR_REQUEST_ID);
- if (attr == null) throw new EBaseException("schema violation");
+ if (attr == null)
+ throw new EBaseException("schema violation");
String value = (String) attr.getStringValues().nextElement();
@@ -427,19 +427,18 @@ class RequestIdMapper
}
}
-
/**
* A mapper between an request attr set and its LDAP attribute representation.
- *
- * The attr attribute is no longer used. This class is kept for historical
- * and migration purposes.
- *
+ *
+ * The attr attribute is no longer used. This class is kept for historical and
+ * migration purposes.
+ *
* @author thayes
* @version $Revision$ $Date$
* @deprecated
*/
class RequestAttrsMapper
- implements IDBAttrMapper {
+ implements IDBAttrMapper {
// IDBAttrMapper methods
//
@@ -450,8 +449,8 @@ class RequestAttrsMapper
//
public void mapObjectToLDAPAttributeSet(IDBObj parent,
- String name, Object obj, LDAPAttributeSet attrs) {
- Hashtable ht = (Hashtable) obj;
+ String name, Object obj, LDAPAttributeSet attrs) {
+ Hashtable ht = (Hashtable) obj;
Enumeration e = ht.keys();
try {
@@ -473,13 +472,13 @@ class RequestAttrsMapper
} catch (NotSerializableException x) {
if (Debug.ON) {
System.err.println("Error: attribute '" + key + "' (" +
- x.getMessage() + ") is not serializable");
+ x.getMessage() + ") is not serializable");
x.printStackTrace();
}
} catch (Exception x) {
if (Debug.ON) {
System.err.println("Error: attribute '" + key +
- "' - error during serialization: " + x);
+ "' - error during serialization: " + x);
x.printStackTrace();
}
}
@@ -490,17 +489,17 @@ class RequestAttrsMapper
attrs.add(new LDAPAttribute(Schema.LDAP_ATTR_REQUEST_ATTRS,
bos.toByteArray()));
- } catch (Exception x) {
+ } catch (Exception x) {
Debug.trace("Output Mapping Error in requeset ID " +
- ((RequestRecord) parent).getRequestId().toString() + " : " + x);
- //if (Debug.ON) {
+ ((RequestRecord) parent).getRequestId().toString() + " : " + x);
+ // if (Debug.ON) {
Debug.printStackTrace(x);
- //}
+ // }
}
}
private byte[] encode(Object value)
- throws NotSerializableException, IOException {
+ throws NotSerializableException, IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(bos);
@@ -511,7 +510,7 @@ class RequestAttrsMapper
}
private Object decode(byte[] data)
- throws ObjectStreamException, IOException, ClassNotFoundException {
+ throws ObjectStreamException, IOException, ClassNotFoundException {
ByteArrayInputStream bis = new ByteArrayInputStream(data);
ObjectInputStream is = new ObjectInputStream(bis);
@@ -519,7 +518,7 @@ class RequestAttrsMapper
}
private Hashtable decodeHashtable(byte[] data)
- throws ObjectStreamException, IOException, ClassNotFoundException {
+ throws ObjectStreamException, IOException, ClassNotFoundException {
Hashtable ht = new Hashtable();
ByteArrayInputStream bis = new ByteArrayInputStream(data);
ObjectInputStream is = new ObjectInputStream(bis);
@@ -530,22 +529,23 @@ class RequestAttrsMapper
while (true) {
key = (String) is.readObject();
-
+
// end of table is marked with null
- if (key == null) break;
+ if (key == null)
+ break;
byte[] bytes = (byte[]) is.readObject();
ht.put(key, decode(bytes));
}
} catch (ObjectStreamException e) {
- Debug.trace("Key " + key); // would be nice to know object type.
+ Debug.trace("Key " + key); // would be nice to know object type.
throw e;
} catch (IOException e) {
- Debug.trace("Key " + key); // would be nice to know object type.
+ Debug.trace("Key " + key); // would be nice to know object type.
throw e;
} catch (ClassNotFoundException e) {
- Debug.trace("Key " + key); // would be nice to know object type.
+ Debug.trace("Key " + key); // would be nice to know object type.
throw e;
}
@@ -555,16 +555,17 @@ class RequestAttrsMapper
/**
* Implements IDBAttrMapper.mapLDAPAttributeSetToObject
* <p>
+ *
* @see IDBAttrMapper#mapLDAPAttributeSetToObject
*/
public void mapLDAPAttributeSetToObject(LDAPAttributeSet attrs,
- String name, IDBObj parent)
- throws EBaseException {
+ String name, IDBObj parent)
+ throws EBaseException {
Hashtable ht = null;
//
// Data is stored in a (single valued) binary attribute
- //
+ //
byte[] value;
LDAPAttribute attr = null;
@@ -581,11 +582,11 @@ class RequestAttrsMapper
}
} catch (Exception x) {
Debug.trace("Mapping error in request Id " +
- ((RequestRecord) parent).getRequestId().toString() + " : " + x);
+ ((RequestRecord) parent).getRequestId().toString() + " : " + x);
Debug.trace("Attr " + attr.getName());
- //if (Debug.ON) {
+ // if (Debug.ON) {
Debug.printStackTrace(x);
- //}
+ // }
}
parent.set(name, ht);
@@ -605,25 +606,18 @@ class RequestAttrsMapper
/**
* Maps dynamic data for the extData- prefix to and from the extData Hashtable
* in RequestRecord.
- *
- * The data in RequestRecord is stored in a Hashtable. It comes in two forms:
- * 1. String key1 => String value1
- * String key2 => String value2
- * This is stored in LDAP as:
- * extData-key1 => value1
- * extData-key2 => value2
- *
- * 2. String key => Hashtable value
- * where value stores:
- * String key2 => String value2
- * String key3 => String value3
- * This is stored in LDAP as:
- * extData-key;key2 => value2
- * extData-key;key3 => value3
- *
- * These can be mixed, but each top-level key can only be associated with
- * a String value or a Hashtable value.
- *
+ *
+ * The data in RequestRecord is stored in a Hashtable. It comes in two forms: 1.
+ * String key1 => String value1 String key2 => String value2 This is stored in
+ * LDAP as: extData-key1 => value1 extData-key2 => value2
+ *
+ * 2. String key => Hashtable value where value stores: String key2 => String
+ * value2 String key3 => String value3 This is stored in LDAP as:
+ * extData-key;key2 => value2 extData-key;key3 => value3
+ *
+ * These can be mixed, but each top-level key can only be associated with a
+ * String value or a Hashtable value.
+ *
*/
class ExtAttrDynMapper implements IDBDynAttrMapper {
@@ -636,17 +630,15 @@ class ExtAttrDynMapper implements IDBDynAttrMapper {
return mAttrs.elements();
}
-
/**
- * Decodes extdata encoded keys.
- * -- followed by a 4 digit hexadecimal string is decoded to the character
- * representing the hex string.
- *
- * The routine is written to be highly efficient. It only allocates
- * the StringBuffer if needed and copies the pieces in large chunks.
- *
- * @param key The key to decode
- * @return The decoded key.
+ * Decodes extdata encoded keys. -- followed by a 4 digit hexadecimal string
+ * is decoded to the character representing the hex string.
+ *
+ * The routine is written to be highly efficient. It only allocates the
+ * StringBuffer if needed and copies the pieces in large chunks.
+ *
+ * @param key The key to decode
+ * @return The decoded key.
*/
public String decodeKey(String key) {
StringBuffer output = null;
@@ -656,8 +648,8 @@ class ExtAttrDynMapper implements IDBDynAttrMapper {
int index = 0;
while (index < input.length) {
if (input[index] == '-') {
- if ( ((index + 1) < input.length) &&
- (input[index + 1] == '-')) {
+ if (((index + 1) < input.length) &&
+ (input[index + 1] == '-')) {
if (output == null) {
output = new StringBuffer(input.length);
}
@@ -665,10 +657,10 @@ class ExtAttrDynMapper implements IDBDynAttrMapper {
index += 2;
if ((index + 3) < input.length) {
output.append(
- Character.toChars(
- Integer.parseInt(new String(input, index, 4),
+ Character.toChars(
+ Integer.parseInt(new String(input, index, 4),
16))
- );
+ );
}
index += 4;
startCopyIndex = index;
@@ -690,26 +682,23 @@ class ExtAttrDynMapper implements IDBDynAttrMapper {
/**
* Encoded extdata keys for storage in LDAP.
- *
- * The rules for encoding are trickier than decoding. We want to allow
- * '-' by itself to be stored in the database (for the common case of keys
- * like 'Foo-Bar'. Therefore we are using '--' as the encoding character.
- * The rules are:
- * 1) All characters [^-a-zA-Z0-9] are encoded as --XXXX where XXXX is the
- * hex representation of the digit.
- * 2) [a-zA-Z0-9] are always passed through unencoded
- * 3) [-] is passed through as long as it is preceded and followed
- * by [a-zA-Z0-9] (or if it's at the beginning/end of the string)
- * 4) If [-] is preceded or followed by [^a-zA-Z0-9] then
- * the - as well as all following [^a-zA-Z0-9] characters are encoded
- * as --XXXX.
- *
+ *
+ * The rules for encoding are trickier than decoding. We want to allow '-'
+ * by itself to be stored in the database (for the common case of keys like
+ * 'Foo-Bar'. Therefore we are using '--' as the encoding character. The
+ * rules are: 1) All characters [^-a-zA-Z0-9] are encoded as --XXXX where
+ * XXXX is the hex representation of the digit. 2) [a-zA-Z0-9] are always
+ * passed through unencoded 3) [-] is passed through as long as it is
+ * preceded and followed by [a-zA-Z0-9] (or if it's at the beginning/end of
+ * the string) 4) If [-] is preceded or followed by [^a-zA-Z0-9] then the -
+ * as well as all following [^a-zA-Z0-9] characters are encoded as --XXXX.
+ *
* This routine tries to be as efficient as possible with StringBuffer and
- * large copies. However, the encoding unfortunately requires several
+ * large copies. However, the encoding unfortunately requires several
* objects to be allocated.
- *
+ *
* @param key The key to encode
- * @return The encoded key
+ * @return The encoded key
*/
public String encodeKey(String key) {
StringBuffer output = null;
@@ -718,10 +707,10 @@ class ExtAttrDynMapper implements IDBDynAttrMapper {
int index = 0;
while (index < input.length) {
- if (! isAlphaNum(input[index])) {
+ if (!isAlphaNum(input[index])) {
if ((input[index] == '-') &&
- ((index + 1) < input.length) &&
- (isAlphaNum(input[index + 1]))) {
+ ((index + 1) < input.length) &&
+ (isAlphaNum(input[index + 1]))) {
index += 2;
} else if ((input[index] == '-') &&
((index + 1) == input.length)) {
@@ -731,8 +720,8 @@ class ExtAttrDynMapper implements IDBDynAttrMapper {
output = new StringBuffer(input.length + 5);
}
output.append(input, startCopyIndex, index - startCopyIndex);
- while ( (index < input.length) &&
- (! isAlphaNum(input[index])) ) {
+ while ((index < input.length) &&
+ (!isAlphaNum(input[index]))) {
output.append("--");
String hexString = Integer.toHexString(input[index]);
int padding = 4 - hexString.length();
@@ -782,28 +771,28 @@ class ExtAttrDynMapper implements IDBDynAttrMapper {
String key = (String) e.nextElement();
Object value = ht.get(key);
if (value instanceof String) {
- String stringValue = (String)value;
+ String stringValue = (String) value;
attrs.add(new LDAPAttribute(
extAttrPrefix + encodeKey(key),
stringValue));
} else if (value instanceof Hashtable) {
- Hashtable innerHash = (Hashtable)value;
+ Hashtable innerHash = (Hashtable) value;
Enumeration innerHashEnum = innerHash.keys();
- while (innerHashEnum.hasMoreElements()){
- String innerKey = (String)innerHashEnum.nextElement();
- String innerValue = (String)innerHash.get(innerKey);
+ while (innerHashEnum.hasMoreElements()) {
+ String innerKey = (String) innerHashEnum.nextElement();
+ String innerValue = (String) innerHash.get(innerKey);
attrs.add(new LDAPAttribute(
- extAttrPrefix + encodeKey(key) + ";" + encodeKey(innerKey),
- innerValue));
+ extAttrPrefix + encodeKey(key) + ";" + encodeKey(innerKey),
+ innerValue));
}
}
}
} catch (Exception x) {
Debug.trace("Output Mapping Error in requeset ID " +
- ((IRequestRecord) parent).getRequestId().toString() + " : " + x);
- //if (Debug.ON) {
+ ((IRequestRecord) parent).getRequestId().toString() + " : " + x);
+ // if (Debug.ON) {
Debug.printStackTrace(x);
- //}
+ // }
}
}
@@ -815,7 +804,7 @@ class ExtAttrDynMapper implements IDBDynAttrMapper {
Enumeration attrEnum = attrs.getAttributes();
while (attrEnum.hasMoreElements()) {
- LDAPAttribute attr = (LDAPAttribute)attrEnum.nextElement();
+ LDAPAttribute attr = (LDAPAttribute) attrEnum.nextElement();
String baseName = attr.getBaseName();
if (baseName.toLowerCase().startsWith(extAttrPrefix)) {
String keyName = decodeKey(
@@ -824,7 +813,7 @@ class ExtAttrDynMapper implements IDBDynAttrMapper {
String[] values = attr.getStringValueArray();
if (values.length != 1) {
String message = "Output Mapping Error in request ID " +
- ((IRequestRecord) parent).getRequestId().toString() + " : " +
+ ((IRequestRecord) parent).getRequestId().toString() + " : " +
"more than one value returned for " +
keyName;
Debug.trace(message);
@@ -833,22 +822,22 @@ class ExtAttrDynMapper implements IDBDynAttrMapper {
if ((subTypes != null) && (subTypes.length > 0)) {
if (subTypes.length != 1) {
String message = "Output Mapping Error in request ID " +
- ((IRequestRecord) parent).getRequestId().toString() + " : " +
+ ((IRequestRecord) parent).getRequestId().toString() + " : " +
"more than one subType returned for " +
keyName;
Debug.trace(message);
throw new EBaseException(message);
}
Object value = ht.get(keyName);
- if ((value != null) && (! (value instanceof Hashtable))) {
+ if ((value != null) && (!(value instanceof Hashtable))) {
String message = "Output Mapping Error in request ID " +
- ((IRequestRecord) parent).getRequestId().toString() + " : " +
+ ((IRequestRecord) parent).getRequestId().toString() + " : " +
"combined no-subtype and subtype data for key " +
keyName;
Debug.trace(message);
throw new EBaseException(message);
}
- valueHashtable = (Hashtable)value;
+ valueHashtable = (Hashtable) value;
if (valueHashtable == null) {
valueHashtable = new Hashtable();
ht.put(keyName, valueHashtable);
diff --git a/pki/base/common/src/com/netscape/cmscore/request/RequestRepository.java b/pki/base/common/src/com/netscape/cmscore/request/RequestRepository.java
index 1dafc2a7..94274af0 100644
--- a/pki/base/common/src/com/netscape/cmscore/request/RequestRepository.java
+++ b/pki/base/common/src/com/netscape/cmscore/request/RequestRepository.java
@@ -32,30 +32,29 @@ import com.netscape.certsrv.request.IRequestQueue;
import com.netscape.cmscore.dbs.Repository;
import com.netscape.cmscore.dbs.RepositoryRecord;
-
/**
- * TODO: what does this class provide beyond the Repository
- * base class??
+ * TODO: what does this class provide beyond the Repository base class??
* <p>
+ *
* @author thayes
* @version $Revision$ $Date$
*/
class RequestRepository
- extends Repository {
+ extends Repository {
+
+ IDBSubsystem mDB = null;
+ IRequestQueue mRequestQueue = null;
- IDBSubsystem mDB = null;
- IRequestQueue mRequestQueue = null;
/**
* Create a request repository that uses the LDAP database
* <p>
- * @param name
- * the name of the repository. This String is used to
- * construct the DN for the repository's LDAP entry.
- * @param db
- * the LDAP database system.
+ *
+ * @param name the name of the repository. This String is used to construct
+ * the DN for the repository's LDAP entry.
+ * @param db the LDAP database system.
*/
public RequestRepository(String name, int increment, IDBSubsystem db)
- throws EDBException {
+ throws EDBException {
super(db, increment, "ou=" + name + ",ou=requests," + db.getBaseDN());
CMS.debug("RequestRepository: constructor 1");
@@ -67,8 +66,8 @@ class RequestRepository
mDB = db;
}
- public RequestRepository(String name, int increment, IDBSubsystem db,IRequestQueue requestQueue)
- throws EDBException {
+ public RequestRepository(String name, int increment, IDBSubsystem db, IRequestQueue requestQueue)
+ throws EDBException {
super(db, increment, "ou=" + name + ",ou=requests," + db.getBaseDN());
CMS.debug("RequestRepository: constructor2.");
@@ -82,12 +81,11 @@ class RequestRepository
}
/**
- * get the LDAP base DN for this repository. This
- * value can be used by the request queue to create the
- * name for the request records themselves.
+ * get the LDAP base DN for this repository. This value can be used by the
+ * request queue to create the name for the request records themselves.
* <p>
- * @return
- * the LDAP base DN.
+ *
+ * @return the LDAP base DN.
*/
public String getBaseDN() {
return mBaseDN;
@@ -96,34 +94,31 @@ class RequestRepository
/**
* Resets serial number.
*/
- public void resetSerialNumber(BigInteger serial) throws EBaseException
- {
+ public void resetSerialNumber(BigInteger serial) throws EBaseException {
setTheSerialNumber(serial);
}
-
+
/**
* Removes all objects with this repository.
*/
- public void removeAllObjects() throws EBaseException
- {
+ public void removeAllObjects() throws EBaseException {
IDBSSession s = mDB.createSession();
try {
- Enumeration e = s.search(getBaseDN(),
+ Enumeration e = s.search(getBaseDN(),
"(" + RequestRecord.ATTR_REQUEST_ID + "=*)");
while (e.hasMoreElements()) {
- RequestRecord r = (RequestRecord)e.nextElement();
- String name = "cn" + "=" +
- r.getRequestId().toString() + "," + getBaseDN();
- s.delete(name);
- }
+ RequestRecord r = (RequestRecord) e.nextElement();
+ String name = "cn" + "=" +
+ r.getRequestId().toString() + "," + getBaseDN();
+ s.delete(name);
+ }
} finally {
if (s != null)
s.close();
}
}
- public BigInteger getLastSerialNumberInRange(BigInteger min, BigInteger max)
- {
+ public BigInteger getLastSerialNumberInRange(BigInteger min, BigInteger max) {
CMS.debug("RequestRepository: in getLastSerialNumberInRange: min " + min + " max " + max);
@@ -131,26 +126,26 @@ class RequestRepository
BigInteger ret = null;
- if(mRequestQueue == null) {
+ if (mRequestQueue == null) {
CMS.debug("RequestRepository: mRequestQueue is null.");
- } else {
-
- CMS.debug("RequestRepository: about to call mRequestQueue.getLastRequestIdInRange");
- ret = mRequestQueue.getLastRequestIdInRange(min,max);
+ } else {
+
+ CMS.debug("RequestRepository: about to call mRequestQueue.getLastRequestIdInRange");
+ ret = mRequestQueue.getLastRequestIdInRange(min, max);
}
return ret;
}
+
/**
* the LDAP base DN for this repository
*/
protected String mBaseDN;
-
public String getPublishingStatus() {
RepositoryRecord record = null;
Object obj = null;
@@ -160,8 +155,8 @@ class RequestRepository
try {
dbs = mDB.createSession();
obj = dbs.read(mBaseDN);
- } catch (Exception e) {
- CMS.debug("RequestRepository: getPublishingStatus: Error: " + e);
+ } catch (Exception e) {
+ CMS.debug("RequestRepository: getPublishingStatus: Error: " + e);
CMS.debugStackTrace();
} finally {
// Close session - ignoring errors (UTIL)
@@ -169,7 +164,7 @@ class RequestRepository
try {
dbs.close();
} catch (Exception ex) {
- CMS.debug("RequestRepository: getPublishingStatus: Error: " + ex);
+ CMS.debug("RequestRepository: getPublishingStatus: Error: " + ex);
}
}
}
@@ -181,7 +176,7 @@ class RequestRepository
CMS.debug("RequestRepository: obj is NOT instanceof RepositoryRecord");
}
CMS.debug("RequestRepository: getPublishingStatus mBaseDN: " + mBaseDN +
- " status: " + ((status != null)?status:"null"));
+ " status: " + ((status != null) ? status : "null"));
return status;
}
@@ -193,14 +188,14 @@ class RequestRepository
ModificationSet mods = new ModificationSet();
if (status != null && status.length() > 0) {
- mods.add(IRepositoryRecord.ATTR_PUB_STATUS,
- Modification.MOD_REPLACE, status);
+ mods.add(IRepositoryRecord.ATTR_PUB_STATUS,
+ Modification.MOD_REPLACE, status);
try {
dbs = mDB.createSession();
dbs.modify(mBaseDN, mods);
- } catch (Exception e) {
- CMS.debug("RequestRepository: setPublishingStatus: Error: " + e);
+ } catch (Exception e) {
+ CMS.debug("RequestRepository: setPublishingStatus: Error: " + e);
CMS.debugStackTrace();
} finally {
// Close session - ignoring errors (UTIL)
@@ -208,7 +203,7 @@ class RequestRepository
try {
dbs.close();
} catch (Exception ex) {
- CMS.debug("RequestRepository: setPublishingStatus: Error: " + ex);
+ CMS.debug("RequestRepository: setPublishingStatus: Error: " + ex);
}
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/request/RequestSubsystem.java b/pki/base/common/src/com/netscape/cmscore/request/RequestSubsystem.java
index 90df9924..8a8387a7 100644
--- a/pki/base/common/src/com/netscape/cmscore/request/RequestSubsystem.java
+++ b/pki/base/common/src/com/netscape/cmscore/request/RequestSubsystem.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.request;
-
import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
@@ -32,24 +31,22 @@ import com.netscape.certsrv.request.IRequestSubsystem;
import com.netscape.certsrv.request.IService;
import com.netscape.cmscore.dbs.DBSubsystem;
-
/**
* RequestSubsystem
* <p>
- * This class is reponsible for managing storage of request objects
- * in the local database.
+ * This class is reponsible for managing storage of request objects in the local
+ * database.
* <p>
- * TODO: review this
- * It provides:
- * + registration of LDAP/JAVA mapping classes with the DBSubsystem
- * + creation of RequestQueue storage in the database
- * + retrieval of existing RequestQueue objects from the database
+ * TODO: review this It provides: + registration of LDAP/JAVA mapping classes
+ * with the DBSubsystem + creation of RequestQueue storage in the database +
+ * retrieval of existing RequestQueue objects from the database
* <p>
+ *
* @author thayes
* @version $Revision$, $Date$
*/
public class RequestSubsystem
- implements IRequestSubsystem, ISubsystem {
+ implements IRequestSubsystem, ISubsystem {
public final static String ID = IRequestSubsystem.SUB_ID;
@@ -67,49 +64,51 @@ public class RequestSubsystem
// end singleton enforcement.
//
- // Create a new request queue. The LDAP DN for the entry
+ // Create a new request queue. The LDAP DN for the entry
// in the database is supplied by the caller.
//
public void createRequestQueue(String name)
- throws EBaseException {
+ throws EBaseException {
/*
- String dbName = makeQueueName(name);
- IDBSSession dbs = createDBSSession();
-
- // Create Repository record here
-
- dbs.add(dbName, r);
- */
+ * String dbName = makeQueueName(name); IDBSSession dbs =
+ * createDBSSession();
+ *
+ * // Create Repository record here
+ *
+ * dbs.add(dbName, r);
+ */
}
public IRequestQueue
- getRequestQueue(String name, int increment, IPolicy p, IService s, INotify n)
- throws EBaseException {
+ getRequestQueue(String name, int increment, IPolicy p, IService s, INotify n)
+ throws EBaseException {
return getRequestQueue(name, increment, p, s, n, null);
}
public IRequestQueue
- getRequestQueue(String name, int increment, IPolicy p, IService s, INotify n,
- INotify pendingNotifier)
- throws EBaseException {
+ getRequestQueue(String name, int increment, IPolicy p, IService s, INotify n,
+ INotify pendingNotifier)
+ throws EBaseException {
RequestQueue rq = new RequestQueue(name, increment, p, s, n, pendingNotifier);
// can't do this here because the service depends on getting rq
- // (to get request) and since this method hasn't returned it's rq is null.
- //rq.recover();
+ // (to get request) and since this method hasn't returned it's rq is
+ // null.
+ // rq.recover();
return rq;
}
//
// ISubsystem methods:
- // getId, setId, init, startup, shutdown, getConfigStore
+ // getId, setId, init, startup, shutdown, getConfigStore
//
/**
* Implements ISubsystem.getId
* <p>
+ *
* @see ISubsystem#getId
*/
public String getId() {
@@ -118,7 +117,7 @@ public class RequestSubsystem
// ISubsystem.setId
public void setId(String id)
- throws EBaseException {
+ throws EBaseException {
mId = id;
}
@@ -127,18 +126,19 @@ public class RequestSubsystem
mParent = parent;
mConfig = config;
}
-
+
/**
* Implements ISubsystem.startup
* <p>
+ *
* @see ISubsystem#startup
*/
public void startup()
- throws EBaseException {
+ throws EBaseException {
mLogger = CMS.getLogger();
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_REQQUEUE, ILogger.LL_INFO,
- "Request subsystem started");
+ "Request subsystem started");
}
public void shutdown() {
@@ -146,7 +146,7 @@ public class RequestSubsystem
if (mLogger != null) {
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_REQQUEUE, ILogger.LL_INFO,
- "Request subsystem stopped");
+ "Request subsystem stopped");
}
}
@@ -166,7 +166,7 @@ public class RequestSubsystem
// system.
//
protected IDBSSession createDBSSession()
- throws EBaseException {
+ throws EBaseException {
return getDBSubsystem().createSession();
}
@@ -186,6 +186,5 @@ public class RequestSubsystem
private String mId = IRequestSubsystem.SUB_ID;
private IRequestQueue mRequestQueue;
- protected ILogger mLogger;
+ protected ILogger mLogger;
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/request/Schema.java b/pki/base/common/src/com/netscape/cmscore/request/Schema.java
index 182e3470..b18b3666 100644
--- a/pki/base/common/src/com/netscape/cmscore/request/Schema.java
+++ b/pki/base/common/src/com/netscape/cmscore/request/Schema.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.request;
-
//
// The Schema class contains constant string values for
// LDAP attribute and object class names used in this package
@@ -44,7 +43,7 @@ class Schema {
public static final String LDAP_ATTR_EXT_ATTR = "extAttr";
// Indicates a special state that may be searched for exactly
- // such as requiresAgentService. The idea is to reduce the space
+ // such as requiresAgentService. The idea is to reduce the space
// used in indexes to optimize common queries.
// NOT IMPLEMENTED
public static final String LDAP_ATTR_REQUEST_FLAG = "requestFlag";
diff --git a/pki/base/common/src/com/netscape/cmscore/security/CASigningCert.java b/pki/base/common/src/com/netscape/cmscore/security/CASigningCert.java
index 04f442a3..d750ea23 100644
--- a/pki/base/common/src/com/netscape/cmscore/security/CASigningCert.java
+++ b/pki/base/common/src/com/netscape/cmscore/security/CASigningCert.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.security;
-
import java.io.IOException;
import java.math.BigInteger;
import java.security.KeyPair;
@@ -34,7 +33,6 @@ import com.netscape.certsrv.common.ConfigConstants;
import com.netscape.certsrv.common.Constants;
import com.netscape.certsrv.security.KeyCertData;
-
/**
* CA signing certificate.
*
@@ -43,8 +41,8 @@ import com.netscape.certsrv.security.KeyCertData;
*/
public class CASigningCert extends CertificateInfo {
- public static final String SUBJECT_NAME =
- "CN=Certificate Authority, O=Netscape Communications, C=US";
+ public static final String SUBJECT_NAME =
+ "CN=Certificate Authority, O=Netscape Communications, C=US";
public CASigningCert(KeyCertData properties) {
this(properties, null);
@@ -52,15 +50,11 @@ public class CASigningCert extends CertificateInfo {
public CASigningCert(KeyCertData properties, KeyPair pair) {
super(properties, pair);
- /* included in console UI
- try {
- if (mProperties.get(Constants.PR_AKI) == null) {
- mProperties.put(Constants.PR_AKI, Constants.FALSE);
- }
- } catch (Exception e) {
- mProperties.put(Constants.PR_AKI, Constants.FALSE);
- }
- */
+ /*
+ * included in console UI try { if (mProperties.get(Constants.PR_AKI) ==
+ * null) { mProperties.put(Constants.PR_AKI, Constants.FALSE); } } catch
+ * (Exception e) { mProperties.put(Constants.PR_AKI, Constants.FALSE); }
+ */
try {
if (mProperties.get(Constants.PR_CERT_LEN) == null) {
mProperties.put(Constants.PR_CERT_LEN, "-1");
@@ -77,15 +71,11 @@ public class CASigningCert extends CertificateInfo {
// "null" mean no BasicConstriant
mProperties.put(Constants.PR_IS_CA, "null");
}
- /* included in console UI
- try {
- if (mProperties.get(Constants.PR_SKI) == null) {
- mProperties.put(Constants.PR_SKI, Constants.FALSE);
- }
- } catch (Exception e) {
- mProperties.put(Constants.PR_SKI, Constants.FALSE);
- }
- */
+ /*
+ * included in console UI try { if (mProperties.get(Constants.PR_SKI) ==
+ * null) { mProperties.put(Constants.PR_SKI, Constants.FALSE); } } catch
+ * (Exception e) { mProperties.put(Constants.PR_SKI, Constants.FALSE); }
+ */
}
public String getSubjectName() {
@@ -107,7 +97,7 @@ public class CASigningCert extends CertificateInfo {
BigInteger P = new BigInteger(p);
BigInteger Q = new BigInteger(q);
BigInteger G = new BigInteger(g);
- BigInteger pqgSeed = new BigInteger(seed);
+ BigInteger pqgSeed = new BigInteger(seed);
BigInteger pqgH = new BigInteger(H);
return new PQGParams(P, Q, G, pqgSeed, counter, pqgH);
@@ -135,7 +125,7 @@ public class CASigningCert extends CertificateInfo {
cmsFileTmp.putString("ca.signing.cacertnickname", nickname);
else
cmsFileTmp.putString("ca.signing.cacertnickname",
- tokenname + ":" + nickname);
+ tokenname + ":" + nickname);
cmsFileTmp.commit(false);
}
@@ -162,4 +152,3 @@ public class CASigningCert extends CertificateInfo {
return extension;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/security/CertificateInfo.java b/pki/base/common/src/com/netscape/cmscore/security/CertificateInfo.java
index 1b0c9f2f..2c31bdf9 100644
--- a/pki/base/common/src/com/netscape/cmscore/security/CertificateInfo.java
+++ b/pki/base/common/src/com/netscape/cmscore/security/CertificateInfo.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.security;
-
import java.io.IOException;
import java.math.BigInteger;
import java.security.InvalidKeyException;
@@ -60,7 +59,6 @@ import com.netscape.certsrv.common.ConfigConstants;
import com.netscape.certsrv.common.Constants;
import com.netscape.certsrv.security.KeyCertData;
-
/**
* This base class provides methods to import CA signing cert or get certificate
* request.
@@ -92,7 +90,7 @@ public abstract class CertificateInfo {
public abstract String getSubjectName();
- //public abstract SignatureAlgorithm getSigningAlgorithm();
+ // public abstract SignatureAlgorithm getSigningAlgorithm();
public abstract String getKeyAlgorithm();
public abstract String getNickname();
@@ -102,12 +100,12 @@ public abstract class CertificateInfo {
public CertificateValidity getCertificateValidity() throws EBaseException {
/*
- String period = (String)mProperties.get(Constants.PR_VALIDITY_PERIOD);
- Date notBeforeDate = CMS.getCurrentDate();
- Date notAfterDate = new Date(notBeforeDate.getYear(),
- notBeforeDate.getMonth(),
- notBeforeDate.getDate()+Integer.parseInt(period));
- return new CertificateValidity(notBeforeDate, notAfterDate);
+ * String period =
+ * (String)mProperties.get(Constants.PR_VALIDITY_PERIOD); Date
+ * notBeforeDate = CMS.getCurrentDate(); Date notAfterDate = new
+ * Date(notBeforeDate.getYear(), notBeforeDate.getMonth(),
+ * notBeforeDate.getDate()+Integer.parseInt(period)); return new
+ * CertificateValidity(notBeforeDate, notAfterDate);
*/
Date notBeforeDate = null;
Date notAfterDate = null;
@@ -118,30 +116,30 @@ public abstract class CertificateInfo {
notBeforeDate = new Date(Long.parseLong(notBeforeStr));
notAfterDate = new Date(Long.parseLong(notAfterStr));
} else {
- int beginYear =
- Integer.parseInt(mProperties.getBeginYear()) - 1900;
- int afterYear =
- Integer.parseInt(mProperties.getAfterYear()) - 1900;
+ int beginYear =
+ Integer.parseInt(mProperties.getBeginYear()) - 1900;
+ int afterYear =
+ Integer.parseInt(mProperties.getAfterYear()) - 1900;
int beginMonth =
- Integer.parseInt(mProperties.getBeginMonth());
+ Integer.parseInt(mProperties.getBeginMonth());
int afterMonth =
- Integer.parseInt(mProperties.getAfterMonth());
+ Integer.parseInt(mProperties.getAfterMonth());
int beginDate =
- Integer.parseInt(mProperties.getBeginDate());
- int afterDate =
- Integer.parseInt(mProperties.getAfterDate());
+ Integer.parseInt(mProperties.getBeginDate());
+ int afterDate =
+ Integer.parseInt(mProperties.getAfterDate());
int beginHour =
- Integer.parseInt(mProperties.getBeginHour());
+ Integer.parseInt(mProperties.getBeginHour());
int afterHour =
- Integer.parseInt(mProperties.getAfterHour());
+ Integer.parseInt(mProperties.getAfterHour());
int beginMin =
- Integer.parseInt(mProperties.getBeginMin());
+ Integer.parseInt(mProperties.getBeginMin());
int afterMin =
- Integer.parseInt(mProperties.getAfterMin());
+ Integer.parseInt(mProperties.getAfterMin());
int beginSec =
- Integer.parseInt(mProperties.getBeginSec());
+ Integer.parseInt(mProperties.getBeginSec());
int afterSec =
- Integer.parseInt(mProperties.getAfterSec());
+ Integer.parseInt(mProperties.getAfterSec());
Calendar calendar = Calendar.getInstance();
calendar.set(beginYear, beginMonth, beginDate,
@@ -159,11 +157,11 @@ public abstract class CertificateInfo {
try {
certInfo.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ new CertificateVersion(CertificateVersion.V3));
BigInteger serialNumber = mProperties.getSerialNumber();
certInfo.set(X509CertInfo.SERIAL_NUMBER,
- new CertificateSerialNumber(serialNumber));
+ new CertificateSerialNumber(serialNumber));
certInfo.set(X509CertInfo.EXTENSIONS, getExtensions());
certInfo.set(X509CertInfo.VALIDITY, getCertificateValidity());
String issuerName = mProperties.getIssuerName();
@@ -172,20 +170,20 @@ public abstract class CertificateInfo {
issuerName = getSubjectName();
}
- certInfo.set(X509CertInfo.ISSUER,
- new CertificateIssuerName(new X500Name(issuerName)));
+ certInfo.set(X509CertInfo.ISSUER,
+ new CertificateIssuerName(new X500Name(issuerName)));
certInfo.set(X509CertInfo.SUBJECT,
- new CertificateSubjectName(new X500Name(getSubjectName())));
- certInfo.set(X509CertInfo.VERSION,
- new CertificateVersion(CertificateVersion.V3));
+ new CertificateSubjectName(new X500Name(getSubjectName())));
+ certInfo.set(X509CertInfo.VERSION,
+ new CertificateVersion(CertificateVersion.V3));
PublicKey pubk = mKeyPair.getPublic();
X509Key xKey = KeyCertUtil.convertPublicKeyToX509Key(pubk);
certInfo.set(X509CertInfo.KEY, new CertificateX509Key(xKey));
- //SignatureAlgorithm algm = getSigningAlgorithm();
- SignatureAlgorithm algm =
- (SignatureAlgorithm) mProperties.get(Constants.PR_SIGNATURE_ALGORITHM);
+ // SignatureAlgorithm algm = getSigningAlgorithm();
+ SignatureAlgorithm algm =
+ (SignatureAlgorithm) mProperties.get(Constants.PR_SIGNATURE_ALGORITHM);
if (algm == null) {
String hashtype = (String) mProperties.get(ConfigConstants.PR_HASH_TYPE);
@@ -197,16 +195,16 @@ public abstract class CertificateInfo {
AlgorithmId sigAlgId = getAlgorithmId();
if (sigAlgId == null) {
- byte[]encodedOID = ASN1Util.encode(algm.toOID());
+ byte[] encodedOID = ASN1Util.encode(algm.toOID());
sigAlgId = new AlgorithmId(new ObjectIdentifier(
new DerInputStream(encodedOID)));
}
certInfo.set(X509CertInfo.ALGORITHM_ID,
- new CertificateAlgorithmId(sigAlgId));
+ new CertificateAlgorithmId(sigAlgId));
} catch (InvalidKeyException e) {
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY"));
- } catch (CertificateException e) {
+ } catch (CertificateException e) {
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_CERT", e.toString()));
} catch (IOException e) {
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_CERT", e.toString()));
@@ -225,7 +223,7 @@ public abstract class CertificateInfo {
KeyCertUtil.setDERExtension(exts, mProperties);
KeyCertUtil.setBasicConstraintsExtension(exts, mProperties);
KeyCertUtil.setSubjectKeyIdentifier(mKeyPair, exts, mProperties);
- //KeyCertUtil.setOCSPSigning(mKeyPair, exts, mProperties);
+ // KeyCertUtil.setOCSPSigning(mKeyPair, exts, mProperties);
KeyCertUtil.setAuthInfoAccess(mKeyPair, exts, mProperties);
KeyCertUtil.setOCSPNoCheck(mKeyPair, exts, mProperties);
KeyPair caKeyPair = (KeyPair) mProperties.get(Constants.PR_CA_KEYPAIR);
@@ -246,7 +244,7 @@ public abstract class CertificateInfo {
if (isKeyUsageEnabled) {
KeyCertUtil.setKeyUsageExtension(
- exts, getKeyUsageExtension());
+ exts, getKeyUsageExtension());
}
return exts;
}
@@ -256,7 +254,7 @@ public abstract class CertificateInfo {
}
public void setAuthorityKeyIdExt(CertificateExtensions caexts, CertificateExtensions ext)
- throws IOException, CertificateException, CertificateEncodingException,
+ throws IOException, CertificateException, CertificateEncodingException,
CertificateParsingException {
SubjectKeyIdentifierExtension subjKeyExt = null;
@@ -272,10 +270,9 @@ public abstract class CertificateInfo {
KeyIdentifier keyId = (KeyIdentifier) subjKeyExt.get(
SubjectKeyIdentifierExtension.KEY_ID);
AuthorityKeyIdentifierExtension authExt =
- new AuthorityKeyIdentifierExtension(false, keyId, null, null);
+ new AuthorityKeyIdentifierExtension(false, keyId, null, null);
ext.set(AuthorityKeyIdentifierExtension.class.getSimpleName(), authExt);
}
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/security/JssSubsystem.java b/pki/base/common/src/com/netscape/cmscore/security/JssSubsystem.java
index 372b966b..627b4022 100644
--- a/pki/base/common/src/com/netscape/cmscore/security/JssSubsystem.java
+++ b/pki/base/common/src/com/netscape/cmscore/security/JssSubsystem.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.security;
-
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
@@ -101,10 +100,10 @@ import com.netscape.cmscore.cert.CertUtils;
import com.netscape.cmscore.util.Debug;
import com.netscape.cmsutil.crypto.CryptoUtil;
-
/**
* Subsystem for initializing JSS>
* <P>
+ *
* @version $Revision$ $Date$
*/
public final class JssSubsystem implements ICryptoSubsystem {
@@ -131,13 +130,14 @@ public final class JssSubsystem implements ICryptoSubsystem {
private Hashtable<String, X509Certificate[]> mNicknameMapCertsTable = new Hashtable<String, X509Certificate[]>();
private Hashtable<String, X509Certificate[]> mNicknameMapUserCertsTable = new Hashtable<String, X509Certificate[]>();
- private FileInputStream devRandomInputStream=null;
+ private FileInputStream devRandomInputStream = null;
- // This date format is to format the date string of the certificate in such a way as
+ // This date format is to format the date string of the certificate in such
+ // a way as
// May 01, 1999 01:55:55.
private static SimpleDateFormat mFormatter = new SimpleDateFormat("MMMMM dd, yyyy HH:mm:ss");
- // SSL related variables.
+ // SSL related variables.
private IConfigStore mSSLConfig = null;
@@ -147,20 +147,20 @@ public final class JssSubsystem implements ICryptoSubsystem {
private static Hashtable<String, Integer> mCipherNames = new Hashtable<String, Integer>();
- /* default sslv2 and sslv3 cipher suites(all), set if no prefs in config.*/
- private static final String DEFAULT_CIPHERPREF =
- "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA," +
- "TLS_RSA_WITH_AES_128_CBC_SHA," +
- "TLS_RSA_WITH_AES_256_CBC_SHA," +
- "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA," +
- "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA," +
-// "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA," +
-// "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA," +
-// "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA," +
- "TLS_DHE_DSS_WITH_AES_128_CBC_SHA," +
- "TLS_DHE_DSS_WITH_AES_256_CBC_SHA," +
- "TLS_DHE_RSA_WITH_AES_128_CBC_SHA," +
- "TLS_DHE_RSA_WITH_AES_256_CBC_SHA";
+ /* default sslv2 and sslv3 cipher suites(all), set if no prefs in config. */
+ private static final String DEFAULT_CIPHERPREF =
+ "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA," +
+ "TLS_RSA_WITH_AES_128_CBC_SHA," +
+ "TLS_RSA_WITH_AES_256_CBC_SHA," +
+ "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA," +
+ "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA," +
+ // "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA," +
+ // "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA," +
+ // "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA," +
+ "TLS_DHE_DSS_WITH_AES_128_CBC_SHA," +
+ "TLS_DHE_DSS_WITH_AES_256_CBC_SHA," +
+ "TLS_DHE_RSA_WITH_AES_128_CBC_SHA," +
+ "TLS_DHE_RSA_WITH_AES_256_CBC_SHA";
/* list of all ciphers JSS supports */
private static final int mJSSCipherSuites[] = {
@@ -184,44 +184,45 @@ public final class JssSubsystem implements ICryptoSubsystem {
static {
/* set ssl cipher string names. */
- /* disallowing SSL2 ciphers to be turned on
- mCipherNames.put(Constants.PR_SSL2_RC4_128_WITH_MD5,
- Integer.valueOf(SSLSocket.SSL2_RC4_128_WITH_MD5));
- mCipherNames.put(Constants.PR_SSL2_RC4_128_EXPORT40_WITH_MD5,
- Integer.valueOf(SSLSocket.SSL2_RC4_128_EXPORT40_WITH_MD5));
- mCipherNames.put(Constants.PR_SSL2_RC2_128_CBC_WITH_MD5,
- Integer.valueOf(SSLSocket.SSL2_RC2_128_CBC_WITH_MD5));
- mCipherNames.put(Constants.PR_SSL2_RC2_128_CBC_EXPORT40_WITH_MD5,
- Integer.valueOf(SSLSocket.SSL2_RC2_128_CBC_EXPORT40_WITH_MD5));
- mCipherNames.put(Constants.PR_SSL2_DES_64_CBC_WITH_MD5,
- Integer.valueOf(SSLSocket.SSL2_DES_64_CBC_WITH_MD5));
- mCipherNames.put(Constants.PR_SSL2_DES_192_EDE3_CBC_WITH_MD5,
- Integer.valueOf(SSLSocket.SSL2_DES_192_EDE3_CBC_WITH_MD5));
- */
+ /*
+ * disallowing SSL2 ciphers to be turned on
+ * mCipherNames.put(Constants.PR_SSL2_RC4_128_WITH_MD5,
+ * Integer.valueOf(SSLSocket.SSL2_RC4_128_WITH_MD5));
+ * mCipherNames.put(Constants.PR_SSL2_RC4_128_EXPORT40_WITH_MD5,
+ * Integer.valueOf(SSLSocket.SSL2_RC4_128_EXPORT40_WITH_MD5));
+ * mCipherNames.put(Constants.PR_SSL2_RC2_128_CBC_WITH_MD5,
+ * Integer.valueOf(SSLSocket.SSL2_RC2_128_CBC_WITH_MD5));
+ * mCipherNames.put(Constants.PR_SSL2_RC2_128_CBC_EXPORT40_WITH_MD5,
+ * Integer.valueOf(SSLSocket.SSL2_RC2_128_CBC_EXPORT40_WITH_MD5));
+ * mCipherNames.put(Constants.PR_SSL2_DES_64_CBC_WITH_MD5,
+ * Integer.valueOf(SSLSocket.SSL2_DES_64_CBC_WITH_MD5));
+ * mCipherNames.put(Constants.PR_SSL2_DES_192_EDE3_CBC_WITH_MD5,
+ * Integer.valueOf(SSLSocket.SSL2_DES_192_EDE3_CBC_WITH_MD5));
+ */
mCipherNames.put(Constants.PR_SSL3_RSA_WITH_NULL_MD5,
- Integer.valueOf(SSLSocket.SSL3_RSA_WITH_NULL_MD5));
+ Integer.valueOf(SSLSocket.SSL3_RSA_WITH_NULL_MD5));
mCipherNames.put(Constants.PR_SSL3_RSA_EXPORT_WITH_RC4_40_MD5,
- Integer.valueOf(SSLSocket.SSL3_RSA_EXPORT_WITH_RC4_40_MD5));
+ Integer.valueOf(SSLSocket.SSL3_RSA_EXPORT_WITH_RC4_40_MD5));
mCipherNames.put(Constants.PR_SSL3_RSA_WITH_RC4_128_MD5,
- Integer.valueOf(SSLSocket.SSL3_RSA_WITH_RC4_128_MD5));
+ Integer.valueOf(SSLSocket.SSL3_RSA_WITH_RC4_128_MD5));
mCipherNames.put(Constants.PR_SSL3_RSA_EXPORT_WITH_RC2_CBC_40_MD5,
- Integer.valueOf(SSLSocket.SSL3_RSA_EXPORT_WITH_RC2_CBC_40_MD5));
+ Integer.valueOf(SSLSocket.SSL3_RSA_EXPORT_WITH_RC2_CBC_40_MD5));
mCipherNames.put(Constants.PR_SSL3_RSA_WITH_DES_CBC_SHA,
- Integer.valueOf(SSLSocket.SSL3_RSA_WITH_DES_CBC_SHA));
+ Integer.valueOf(SSLSocket.SSL3_RSA_WITH_DES_CBC_SHA));
mCipherNames.put(Constants.PR_SSL3_RSA_WITH_3DES_EDE_CBC_SHA,
- Integer.valueOf(SSLSocket.SSL3_RSA_WITH_3DES_EDE_CBC_SHA));
+ Integer.valueOf(SSLSocket.SSL3_RSA_WITH_3DES_EDE_CBC_SHA));
mCipherNames.put(Constants.PR_SSL3_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA,
- Integer.valueOf(SSLSocket.SSL3_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA));
+ Integer.valueOf(SSLSocket.SSL3_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA));
mCipherNames.put(Constants.PR_SSL3_FORTEZZA_DMS_WITH_RC4_128_SHA,
- Integer.valueOf(SSLSocket.SSL3_FORTEZZA_DMS_WITH_RC4_128_SHA));
+ Integer.valueOf(SSLSocket.SSL3_FORTEZZA_DMS_WITH_RC4_128_SHA));
mCipherNames.put(Constants.PR_SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA,
- Integer.valueOf(SSLSocket.SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA));
+ Integer.valueOf(SSLSocket.SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA));
mCipherNames.put(Constants.PR_SSL_RSA_FIPS_WITH_DES_CBC_SHA,
- Integer.valueOf(SSLSocket.SSL_RSA_FIPS_WITH_DES_CBC_SHA));
+ Integer.valueOf(SSLSocket.SSL_RSA_FIPS_WITH_DES_CBC_SHA));
mCipherNames.put(Constants.PR_TLS_RSA_EXPORT1024_WITH_RC4_56_SHA,
- Integer.valueOf(SSLSocket.TLS_RSA_EXPORT1024_WITH_RC4_56_SHA));
+ Integer.valueOf(SSLSocket.TLS_RSA_EXPORT1024_WITH_RC4_56_SHA));
mCipherNames.put(Constants.PR_TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA,
- Integer.valueOf(SSLSocket.TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA));
+ Integer.valueOf(SSLSocket.TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA));
}
public static JssSubsystem getInstance() {
@@ -243,40 +244,37 @@ public final class JssSubsystem implements ICryptoSubsystem {
}
- // Add entropy to the 'default' RNG token
- public void addEntropy(int bits)
- throws org.mozilla.jss.util.NotImplementedException,
- IOException,
- TokenException
- {
- int read=0;
- int bytes = (7+bits)/8;
- byte[] b = new byte[bytes];
- if (devRandomInputStream == null) {
- throw new IOException(CMS.getLogMessage("CMSCORE_SECURITY_NO_ENTROPY_STREAM"));
- }
- do {
- int c = devRandomInputStream.read(b,read,bytes-read);
- read += c;
- }
- while (read < bytes);
-
- CMS.debug("JssSubsystem adding "+bits+" bits ("+bytes+" bytes) of entropy to default RNG token");
- CMS.debug(b);
- PK11SecureRandom sr = new PK11SecureRandom();
- sr.setSeed(b);
- }
-
+ // Add entropy to the 'default' RNG token
+ public void addEntropy(int bits)
+ throws org.mozilla.jss.util.NotImplementedException,
+ IOException,
+ TokenException {
+ int read = 0;
+ int bytes = (7 + bits) / 8;
+ byte[] b = new byte[bytes];
+ if (devRandomInputStream == null) {
+ throw new IOException(CMS.getLogMessage("CMSCORE_SECURITY_NO_ENTROPY_STREAM"));
+ }
+ do {
+ int c = devRandomInputStream.read(b, read, bytes - read);
+ read += c;
+ } while (read < bytes);
+
+ CMS.debug("JssSubsystem adding " + bits + " bits (" + bytes + " bytes) of entropy to default RNG token");
+ CMS.debug(b);
+ PK11SecureRandom sr = new PK11SecureRandom();
+ sr.setSeed(b);
+ }
+
/**
- * Initializes the Jss security subsystem.
+ * Initializes the Jss security subsystem.
* <P>
*/
- public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ public void init(ISubsystem owner, IConfigStore config)
+ throws EBaseException {
mLogger = CMS.getLogger();
-
- if (mInited)
- {
+
+ if (mInited) {
// This used to throw an exeception (e.g. - on Solaris).
// If JSS is already initialized simply return.
CMS.debug("JssSubsystem already inited.. returning.");
@@ -309,9 +307,9 @@ public final class JssSubsystem implements ICryptoSubsystem {
String certDir;
certDir = config.getString(CONFIG_DIR, null);
-
- CryptoManager.InitializationValues vals =
- new CryptoManager.InitializationValues(certDir,
+
+ CryptoManager.InitializationValues vals =
+ new CryptoManager.InitializationValues(certDir,
"", "", "secmod.db");
vals.removeSunProvider = false;
@@ -321,7 +319,7 @@ public final class JssSubsystem implements ICryptoSubsystem {
} catch (AlreadyInitializedException e) {
// do nothing
} catch (Exception e) {
- String[] params = {mId, e.toString()};
+ String[] params = { mId, e.toString() };
EBaseException ex = new EBaseException(
CMS.getUserMessage("CMS_BASE_CREATE_SERVICE_FAILED", params));
@@ -333,19 +331,19 @@ public final class JssSubsystem implements ICryptoSubsystem {
mCryptoManager = CryptoManager.getInstance();
initSSL();
} catch (CryptoManager.NotInitializedException e) {
- String[] params = {mId, e.toString()};
+ String[] params = { mId, e.toString() };
EBaseException ex = new EBaseException(
CMS.getUserMessage("CMS_BASE_CREATE_SERVICE_FAILED", params));
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_GENERAL_ERROR", ex.toString()));
throw ex;
}
-
+
mInited = true;
}
public String getCipherVersion() throws EBaseException {
- return "cipherdomestic";
+ return "cipherdomestic";
}
public String getCipherPreferences() throws EBaseException {
@@ -370,9 +368,9 @@ public final class JssSubsystem implements ICryptoSubsystem {
}
public String isCipherFortezza() throws EBaseException {
- // we always display fortezza suites.
- // too much work to display tokens/certs corresponding to the
- // suites.
+ // we always display fortezza suites.
+ // too much work to display tokens/certs corresponding to the
+ // suites.
return "true";
}
@@ -383,13 +381,13 @@ public final class JssSubsystem implements ICryptoSubsystem {
if (position == -1) {
Debug.trace("Unable to install CMS provider");
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_SECURITY_INSTALL_PROVIDER"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_SECURITY_INSTALL_PROVIDER"));
}
}
- public void setCipherPreferences(String cipherPrefs)
- throws EBaseException {
+ public void setCipherPreferences(String cipherPrefs)
+ throws EBaseException {
if (mSSLConfig != null) {
if (cipherPrefs.equals(""))
throw new EBaseException(CMS.getUserMessage("CMS_BASE_NO_EMPTY_CIPHERPREFS"));
@@ -402,7 +400,7 @@ public final class JssSubsystem implements ICryptoSubsystem {
*
*/
private void initSSL() throws EBaseException {
- // JSS will AND what is set and what is allowed by export policy
+ // JSS will AND what is set and what is allowed by export policy
// so we can set what is requested.
try {
@@ -418,11 +416,11 @@ public final class JssSubsystem implements ICryptoSubsystem {
if (Debug.ON)
Debug.trace("configured ssl cipher prefs is " + sslCiphers);
- // first, disable all ciphers, since JSS defaults to all-enabled
+ // first, disable all ciphers, since JSS defaults to all-enabled
for (int i = mJSSCipherSuites.length - 1; i >= 0; i--) {
try {
SSLSocket.setCipherPreferenceDefault(mJSSCipherSuites[i],
- false);
+ false);
} catch (SocketException e) {
}
}
@@ -433,8 +431,8 @@ public final class JssSubsystem implements ICryptoSubsystem {
StringTokenizer ciphers = new StringTokenizer(sslCiphers, ",");
if (!ciphers.hasMoreTokens()) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_SECURITY_INVALID_CIPHER", sslCiphers));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_SECURITY_INVALID_CIPHER", sslCiphers));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_PROPERTY", PROP_SSL_CIPHERPREF));
}
while (ciphers.hasMoreTokens()) {
@@ -444,13 +442,13 @@ public final class JssSubsystem implements ICryptoSubsystem {
if (sslcipher != null) {
String msg = "setting ssl cipher " + cipher;
- CMS.debug("JSSSubsystem: initSSL(): "+msg);
+ CMS.debug("JSSSubsystem: initSSL(): " + msg);
log(ILogger.LL_INFO, msg);
if (Debug.ON)
Debug.trace(msg);
try {
SSLSocket.setCipherPreferenceDefault(
- sslcipher.intValue(), true);
+ sslcipher.intValue(), true);
} catch (SocketException e) {
}
}
@@ -458,7 +456,7 @@ public final class JssSubsystem implements ICryptoSubsystem {
}
}
-
+
/**
* Retrieves a configuration store of this subsystem.
* <P>
@@ -472,26 +470,26 @@ public final class JssSubsystem implements ICryptoSubsystem {
*/
public void startup() throws EBaseException {
}
-
+
/**
* Shutdowns this subsystem.
* <P>
*/
public void shutdown() {
try {
- // After talking to NSS teamm, we should not call close databases
- // which will call NSS_Shutdown. Web Server will call NSS_Shutdown
- boolean isClosing = mConfig.getBoolean("closeDatabases", false);
- if (isClosing) {
- JSSDatabaseCloser closer = new JSSDatabaseCloser();
- closer.closeDatabases();
- }
+ // After talking to NSS teamm, we should not call close databases
+ // which will call NSS_Shutdown. Web Server will call NSS_Shutdown
+ boolean isClosing = mConfig.getBoolean("closeDatabases", false);
+ if (isClosing) {
+ JSSDatabaseCloser closer = new JSSDatabaseCloser();
+ closer.closeDatabases();
+ }
} catch (Exception e) {
}
}
public void log(int level, String msg) {
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, level, "JSS " + msg);
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, level, "JSS " + msg);
}
public PasswordCallback getPWCB() {
@@ -505,7 +503,7 @@ public final class JssSubsystem implements ICryptoSubsystem {
try {
name = c.getName();
} catch (TokenException e) {
- String[] params = {mId, e.toString()};
+ String[] params = { mId, e.toString() };
EBaseException ex = new EBaseException(
CMS.getUserMessage("CMS_BASE_CREATE_SERVICE_FAILED", params));
@@ -519,12 +517,12 @@ public final class JssSubsystem implements ICryptoSubsystem {
public String getTokenList() throws EBaseException {
String tokenList = "";
@SuppressWarnings("unchecked")
- Enumeration<CryptoToken> tokens = mCryptoManager.getExternalTokens();
+ Enumeration<CryptoToken> tokens = mCryptoManager.getExternalTokens();
int num = 0;
try {
while (tokens.hasMoreElements()) {
- CryptoToken c = tokens.nextElement();
+ CryptoToken c = tokens.nextElement();
// skip builtin object token
if (c.getName() != null && c.getName().equals("Builtin Object Token")) {
@@ -532,12 +530,12 @@ public final class JssSubsystem implements ICryptoSubsystem {
}
if (num++ == 0)
- tokenList = tokenList + c.getName();
- else
+ tokenList = tokenList + c.getName();
+ else
tokenList = tokenList + "," + c.getName();
}
} catch (TokenException e) {
- String[] params = {mId, e.toString()};
+ String[] params = { mId, e.toString() };
EBaseException ex = new EBaseException(
CMS.getUserMessage("CMS_BASE_CREATE_SERVICE_FAILED", params));
@@ -545,8 +543,8 @@ public final class JssSubsystem implements ICryptoSubsystem {
throw ex;
}
- if (tokenList.equals(""))
- return Constants.PR_INTERNAL_TOKEN;
+ if (tokenList.equals(""))
+ return Constants.PR_INTERNAL_TOKEN;
else
return (tokenList + "," + Constants.PR_INTERNAL_TOKEN);
}
@@ -585,8 +583,8 @@ public final class JssSubsystem implements ICryptoSubsystem {
}
}
- public String getCertSubjectName(String tokenname, String nickname)
- throws EBaseException {
+ public String getCertSubjectName(String tokenname, String nickname)
+ throws EBaseException {
try {
return KeyCertUtil.getCertSubjectName(tokenname, nickname);
} catch (NoSuchTokenException e) {
@@ -609,7 +607,7 @@ public final class JssSubsystem implements ICryptoSubsystem {
try {
@SuppressWarnings("unchecked")
- Enumeration<CryptoToken> enums = mCryptoManager.getAllTokens();
+ Enumeration<CryptoToken> enums = mCryptoManager.getAllTokens();
while (enums.hasMoreElements()) {
CryptoToken token = enums.nextElement();
@@ -626,7 +624,7 @@ public final class JssSubsystem implements ICryptoSubsystem {
}
}
} catch (TokenException e) {
- String[] params = {mId, e.toString()};
+ String[] params = { mId, e.toString() };
EBaseException ex = new EBaseException(
CMS.getUserMessage("CMS_BASE_CREATE_SERVICE_FAILED", params));
@@ -655,7 +653,7 @@ public final class JssSubsystem implements ICryptoSubsystem {
if (list == null)
return "";
-
+
for (int i = 0; i < list.length; i++) {
String nickname = list[i].getNickname();
int index = nickname.indexOf(":");
@@ -672,14 +670,14 @@ public final class JssSubsystem implements ICryptoSubsystem {
return "";
} catch (TokenException e) {
- String[] params = {mId, e.toString()};
+ String[] params = { mId, e.toString() };
EBaseException ex = new EBaseException(
CMS.getUserMessage("CMS_BASE_CREATE_SERVICE_FAILED", params));
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_GENERAL_ERROR", ex.toString()));
throw ex;
} catch (NoSuchTokenException e) {
- String[] params = {mId, e.toString()};
+ String[] params = { mId, e.toString() };
EBaseException ex = new EBaseException(
CMS.getUserMessage("CMS_BASE_CREATE_SERVICE_FAILED", params));
@@ -706,7 +704,7 @@ public final class JssSubsystem implements ICryptoSubsystem {
if (list == null)
return "";
-
+
for (int i = 0; i < list.length; i++) {
String nickname = list[i].getNickname();
@@ -720,14 +718,14 @@ public final class JssSubsystem implements ICryptoSubsystem {
return "";
} catch (TokenException e) {
- String[] params = {mId, e.toString()};
+ String[] params = { mId, e.toString() };
EBaseException ex = new EBaseException(
CMS.getUserMessage("CMS_BASE_CREATE_SERVICE_FAILED", params));
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_GENERAL_ERROR", ex.toString()));
throw ex;
} catch (NoSuchTokenException e) {
- String[] params = {mId, e.toString()};
+ String[] params = { mId, e.toString() };
EBaseException ex = new EBaseException(
CMS.getUserMessage("CMS_BASE_CREATE_SERVICE_FAILED", params));
@@ -736,8 +734,8 @@ public final class JssSubsystem implements ICryptoSubsystem {
}
}
- public AlgorithmId getAlgorithmId(String algname, IConfigStore store)
- throws EBaseException {
+ public AlgorithmId getAlgorithmId(String algname, IConfigStore store)
+ throws EBaseException {
try {
if (algname.equals("DSA")) {
byte[] p = store.getByteArray("ca.dsaP", null);
@@ -760,8 +758,8 @@ public final class JssSubsystem implements ICryptoSubsystem {
public String getSignatureAlgorithm(String nickname) throws EBaseException {
try {
- X509Certificate cert =
- CryptoManager.getInstance().findCertByNickname(nickname);
+ X509Certificate cert =
+ CryptoManager.getInstance().findCertByNickname(nickname);
X509CertImpl impl = new X509CertImpl(cert.getEncoded());
return impl.getSigAlgName();
@@ -777,15 +775,15 @@ public final class JssSubsystem implements ICryptoSubsystem {
} catch (CertificateException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_ALG", e.toString()));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_ERROR", ""));
- }
+ }
}
public KeyPair getKeyPair(String nickname) throws EBaseException {
try {
- X509Certificate cert =
- CryptoManager.getInstance().findCertByNickname(nickname);
- PrivateKey priKey =
- CryptoManager.getInstance().findPrivKeyByCert(cert);
+ X509Certificate cert =
+ CryptoManager.getInstance().findCertByNickname(nickname);
+ PrivateKey priKey =
+ CryptoManager.getInstance().findPrivKeyByCert(cert);
PublicKey publicKey = cert.getPublicKey();
return new KeyPair(publicKey, priKey);
@@ -802,12 +800,12 @@ public final class JssSubsystem implements ICryptoSubsystem {
}
public KeyPair getKeyPair(String tokenName, String alg,
- int keySize) throws EBaseException {
+ int keySize) throws EBaseException {
return getKeyPair(tokenName, alg, keySize, null);
}
public KeyPair getKeyPair(String tokenName, String alg,
- int keySize, PQGParams pqg) throws EBaseException {
+ int keySize, PQGParams pqg) throws EBaseException {
String t = tokenName;
if (tokenName.equals(Constants.PR_INTERNAL_TOKEN))
@@ -815,12 +813,12 @@ public final class JssSubsystem implements ICryptoSubsystem {
CryptoToken token = null;
try {
- token = mCryptoManager.getTokenByName(t);
+ token = mCryptoManager.getTokenByName(t);
} catch (NoSuchTokenException e) {
log(ILogger.LL_FAILURE, "Generate Key Pair Error " + e);
throw new EBaseException(CMS.getUserMessage("CMS_BASE_TOKEN_NOT_FOUND", tokenName));
}
-
+
KeyPairAlgorithm kpAlg = null;
if (alg.equals("RSA"))
@@ -862,11 +860,11 @@ public final class JssSubsystem implements ICryptoSubsystem {
}
}
- public String getCertRequest(String subjectName, KeyPair kp)
- throws EBaseException {
+ public String getCertRequest(String subjectName, KeyPair kp)
+ throws EBaseException {
try {
netscape.security.pkcs.PKCS10 pkcs =
- KeyCertUtil.getCertRequest(subjectName, kp);
+ KeyCertUtil.getCertRequest(subjectName, kp);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(bs);
@@ -893,8 +891,8 @@ public final class JssSubsystem implements ICryptoSubsystem {
}
}
- public void importCert(String b64E, String nickname, String certType)
- throws EBaseException {
+ public void importCert(String b64E, String nickname, String certType)
+ throws EBaseException {
try {
KeyCertUtil.importCert(b64E, nickname, certType);
} catch (CertificateException e) {
@@ -931,7 +929,7 @@ public final class JssSubsystem implements ICryptoSubsystem {
String tmp = (String) properties.get(Constants.PR_TOKEN_NAME);
if ((tmp != null) &&
- (!tmp.equals(Constants.PR_INTERNAL_TOKEN)))
+ (!tmp.equals(Constants.PR_INTERNAL_TOKEN)))
tokenname = tmp;
tmp = (String) properties.get(Constants.PR_KEY_TYPE);
if (tmp != null)
@@ -953,9 +951,9 @@ public final class JssSubsystem implements ICryptoSubsystem {
KeyPair pair = null;
String tmp = (String) properties.get(Constants.PR_TOKEN_NAME);
- if (tmp != null)
+ if (tmp != null)
token = tmp;
-
+
tmp = (String) properties.get(Constants.PR_KEY_CURVENAME);
if (tmp != null)
keyCurve = tmp;
@@ -966,7 +964,7 @@ public final class JssSubsystem implements ICryptoSubsystem {
return pair;
}
-
+
public KeyPair getECCKeyPair(String token, String keyCurve, String certType) throws EBaseException {
KeyPair pair = null;
@@ -974,26 +972,26 @@ public final class JssSubsystem implements ICryptoSubsystem {
token = Constants.PR_INTERNAL_TOKEN_NAME;
if ((keyCurve == null) || (keyCurve.equals("")))
- keyCurve = "nistp512";
+ keyCurve = "nistp512";
String ectype = getECType(certType);
// ECDHE needs "SIGN" but no "DERIVE"
org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage usages_mask[] = {
- org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage.DERIVE
+ org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage.DERIVE
};
// ECDH needs "DERIVE" but no any kind of "SIGN"
org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage ECDH_usages_mask[] = {
- org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage.SIGN,
- org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage.SIGN_RECOVER,
+ org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage.SIGN,
+ org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage.SIGN_RECOVER,
};
try {
- if (ectype.equals("ECDHE"))
- pair = CryptoUtil.generateECCKeyPair(token, keyCurve, null, usages_mask);
+ if (ectype.equals("ECDHE"))
+ pair = CryptoUtil.generateECCKeyPair(token, keyCurve, null, usages_mask);
else
- pair = CryptoUtil.generateECCKeyPair(token, keyCurve, null, ECDH_usages_mask);
+ pair = CryptoUtil.generateECCKeyPair(token, keyCurve, null, ECDH_usages_mask);
} catch (NotInitializedException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_GET_ECC_KEY", e.toString()));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_CRYPTOMANAGER_UNINITIALIZED"));
@@ -1009,10 +1007,10 @@ public final class JssSubsystem implements ICryptoSubsystem {
}
return pair;
- }
+ }
public void importCert(X509CertImpl signedCert, String nickname,
- String certType) throws EBaseException {
+ String certType) throws EBaseException {
try {
KeyCertUtil.importCert(signedCert, nickname, certType);
@@ -1065,23 +1063,23 @@ public final class JssSubsystem implements ICryptoSubsystem {
}
public void deleteUserCert(String nickname, String serialno, String issuername)
- throws EBaseException {
+ throws EBaseException {
try {
X509Certificate cert = getCertificate(nickname, serialno, issuername);
if (cert instanceof TokenCertificate) {
TokenCertificate tcert = (TokenCertificate) cert;
CryptoStore store = tcert.getOwningToken().getCryptoStore();
-CMS.debug("*** deleting this token cert");
+ CMS.debug("*** deleting this token cert");
tcert.getOwningToken().getCryptoStore().deleteCert(tcert);
-CMS.debug("*** finish deleting this token cert");
+ CMS.debug("*** finish deleting this token cert");
} else {
- CryptoToken token = CryptoManager.getInstance().getInternalKeyStorageToken();
- CryptoStore store = token.getCryptoStore();
+ CryptoToken token = CryptoManager.getInstance().getInternalKeyStorageToken();
+ CryptoStore store = token.getCryptoStore();
-CMS.debug("*** deleting this interna cert");
- store.deleteCert(cert);
-CMS.debug("*** removing this interna cert");
+ CMS.debug("*** deleting this interna cert");
+ store.deleteCert(cert);
+ CMS.debug("*** removing this interna cert");
}
} catch (NotInitializedException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_DELETE_CERT", e.toString()));
@@ -1095,12 +1093,12 @@ CMS.debug("*** removing this interna cert");
}
}
- public void deleteRootCert(String nickname, String serialno,
- String issuername) throws EBaseException {
+ public void deleteRootCert(String nickname, String serialno,
+ String issuername) throws EBaseException {
int index = nickname.indexOf(":");
String tokenname = nickname.substring(0, index);
if (tokenname.equals(Constants.PR_INTERNAL_TOKEN_NAME)) {
- nickname = nickname.substring(index+1);
+ nickname = nickname.substring(index + 1);
}
try {
if (mNicknameMapCertsTable != null) {
@@ -1117,24 +1115,24 @@ CMS.debug("*** removing this interna cert");
X509CertImpl impl = new X509CertImpl(cert.getEncoded());
String num = impl.getSerialNumber().toString();
String issuer = impl.getIssuerDN().toString();
-CMS.debug("*** num "+num);
-CMS.debug("*** issuer "+issuer);
+ CMS.debug("*** num " + num);
+ CMS.debug("*** issuer " + issuer);
if (num.equals(serialno) && issuername.equals(issuer)) {
-CMS.debug("*** removing root cert");
+ CMS.debug("*** removing root cert");
if (cert instanceof TokenCertificate) {
TokenCertificate tcert = (TokenCertificate) cert;
CryptoStore store = tcert.getOwningToken().getCryptoStore();
-
-CMS.debug("*** deleting this token cert");
- tcert.getOwningToken().getCryptoStore().deleteCert(tcert);
-CMS.debug("*** finish deleting this token cert");
+
+ CMS.debug("*** deleting this token cert");
+ tcert.getOwningToken().getCryptoStore().deleteCert(tcert);
+ CMS.debug("*** finish deleting this token cert");
} else {
- CryptoToken token = CryptoManager.getInstance().getInternalKeyStorageToken();
+ CryptoToken token = CryptoManager.getInstance().getInternalKeyStorageToken();
CryptoStore store = token.getCryptoStore();
-
-CMS.debug("*** deleting this interna cert");
+
+ CMS.debug("*** deleting this interna cert");
store.deleteCert(cert);
-CMS.debug("*** removing this interna cert");
+ CMS.debug("*** removing this interna cert");
}
mNicknameMapCertsTable.remove(nickname);
break;
@@ -1162,7 +1160,7 @@ CMS.debug("*** removing this interna cert");
NameValuePairs nvps = new NameValuePairs();
try {
@SuppressWarnings("unchecked")
- Enumeration<CryptoToken> enums = mCryptoManager.getAllTokens();
+ Enumeration<CryptoToken> enums = mCryptoManager.getAllTokens();
if (mNicknameMapCertsTable != null)
mNicknameMapCertsTable.clear();
@@ -1178,21 +1176,21 @@ CMS.debug("*** removing this interna cert");
for (int i = 0; i < list.length; i++) {
try {
- PrivateKey key =
- CryptoManager.getInstance().findPrivKeyByCert(list[i]);
+ PrivateKey key =
+ CryptoManager.getInstance().findPrivKeyByCert(list[i]);
Debug.trace("JssSubsystem getRootCerts: find private key "
- +list[i].getNickname());
+ + list[i].getNickname());
} catch (ObjectNotFoundException e) {
String nickname = list[i].getNickname();
- if (tokenName.equals(Constants.PR_INTERNAL_TOKEN_NAME)) {
- nickname = Constants.PR_INTERNAL_TOKEN_NAME+":"+nickname;
+ if (tokenName.equals(Constants.PR_INTERNAL_TOKEN_NAME)) {
+ nickname = Constants.PR_INTERNAL_TOKEN_NAME + ":" + nickname;
}
X509CertImpl impl = null;
try {
Vector<X509Certificate> v;
if (vecTable.containsKey((Object) nickname) == true) {
- v = vecTable.get(nickname);
+ v = vecTable.get(nickname);
} else {
v = new Vector<X509Certificate>();
}
@@ -1206,20 +1204,20 @@ CMS.debug("*** removing this interna cert");
}
String serialno = impl.getSerialNumber().toString();
String issuer = impl.getIssuerDN().toString();
- nvps.add(nickname+","+serialno, issuer);
- Debug.trace("getRootCerts: nickname="+nickname+", serialno="+
- serialno+", issuer="+issuer);
+ nvps.add(nickname + "," + serialno, issuer);
+ Debug.trace("getRootCerts: nickname=" + nickname + ", serialno=" +
+ serialno + ", issuer=" + issuer);
continue;
} catch (CryptoManager.NotInitializedException e) {
continue;
}
- }
+ }
// convert hashtable of vectors to hashtable of arrays
Enumeration<String> elms = vecTable.keys();
while (elms.hasMoreElements()) {
String key = (String) elms.nextElement();
- Vector<X509Certificate> v = vecTable.get((Object) key);
+ Vector<X509Certificate> v = vecTable.get((Object) key);
X509Certificate[] a = new X509Certificate[v.size()];
v.copyInto((Object[]) a);
@@ -1239,7 +1237,7 @@ CMS.debug("*** removing this interna cert");
NameValuePairs nvps = new NameValuePairs();
try {
@SuppressWarnings("unchecked")
- Enumeration<CryptoToken> enums = mCryptoManager.getAllTokens();
+ Enumeration<CryptoToken> enums = mCryptoManager.getAllTokens();
while (enums.hasMoreElements()) {
CryptoToken token = (CryptoToken) enums.nextElement();
@@ -1250,16 +1248,16 @@ CMS.debug("*** removing this interna cert");
for (int i = 0; i < list.length; i++) {
try {
- PrivateKey key =
- CryptoManager.getInstance().findPrivKeyByCert(list[i]);
+ PrivateKey key =
+ CryptoManager.getInstance().findPrivKeyByCert(list[i]);
String nickname = list[i].getNickname();
if (tokenName.equals(Constants.PR_INTERNAL_TOKEN_NAME) ||
- tokenName.equals(Constants.PR_FULL_INTERNAL_TOKEN_NAME)) {
- nickname = Constants.PR_INTERNAL_TOKEN_NAME+":"+nickname;
+ tokenName.equals(Constants.PR_FULL_INTERNAL_TOKEN_NAME)) {
+ nickname = Constants.PR_INTERNAL_TOKEN_NAME + ":" + nickname;
}
X509CertImpl impl = null;
- try {
+ try {
impl = new X509CertImpl(list[i].getEncoded());
} catch (CertificateException e) {
// skip bad certificate
@@ -1268,17 +1266,17 @@ CMS.debug("*** removing this interna cert");
}
String serialno = impl.getSerialNumber().toString();
String issuer = impl.getIssuerDN().toString();
- nvps.add(nickname+","+serialno, issuer);
- Debug.trace("getUserCerts: nickname="+nickname+", serialno="+
- serialno+", issuer="+issuer);
+ nvps.add(nickname + "," + serialno, issuer);
+ Debug.trace("getUserCerts: nickname=" + nickname + ", serialno=" +
+ serialno + ", issuer=" + issuer);
} catch (ObjectNotFoundException e) {
Debug.trace("JssSubsystem getUserCerts: cant find private key "
- +list[i].getNickname());
+ + list[i].getNickname());
continue;
} catch (CryptoManager.NotInitializedException e) {
continue;
}
- }
+ }
}
} catch (TokenException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_GET_ALL_CERT", e.toString()));
@@ -1295,8 +1293,8 @@ CMS.debug("*** removing this interna cert");
public NameValuePairs getAllCertsManage() throws EBaseException {
/*
- * first get all CA certs (internal only),
- * then all user certs (both internal and external)
+ * first get all CA certs (internal only), then all user certs (both
+ * internal and external)
*/
NameValuePairs pairs = getCACerts();
@@ -1306,7 +1304,7 @@ CMS.debug("*** removing this interna cert");
try {
@SuppressWarnings("unchecked")
- Enumeration<CryptoToken> enums = mCryptoManager.getAllTokens();
+ Enumeration<CryptoToken> enums = mCryptoManager.getAllTokens();
while (enums.hasMoreElements()) {
CryptoToken token = (CryptoToken) enums.nextElement();
@@ -1317,14 +1315,14 @@ CMS.debug("*** removing this interna cert");
for (int i = 0; i < list.length; i++) {
String nickname = list[i].getNickname();
- X509Certificate[] certificates =
- CryptoManager.getInstance().findCertsByNickname(nickname);
+ X509Certificate[] certificates =
+ CryptoManager.getInstance().findCertsByNickname(nickname);
mNicknameMapUserCertsTable.put(nickname, certificates);
X509CertImpl impl = null;
- try {
+ try {
impl = new X509CertImpl(list[i].getEncoded());
} catch (CertificateException e) {
// skip bad certificate
@@ -1335,7 +1333,7 @@ CMS.debug("*** removing this interna cert");
String dateStr = mFormatter.format(date);
NameValuePair pair = pairs.getPair(nickname);
- /* always user cert here*/
+ /* always user cert here */
String certValue = dateStr + "," + "u";
if (pair == null)
@@ -1346,7 +1344,7 @@ CMS.debug("*** removing this interna cert");
if (vvalue.endsWith(",u")) {
pair.setValue(vvalue + ";" + certValue);
}
- }
+ }
}
} /* while */
@@ -1354,8 +1352,10 @@ CMS.debug("*** removing this interna cert");
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_GET_ALL_CERT", e.toString()));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_CRYPTOMANAGER_UNINITIALIZED"));
// } catch (CertificateException e) {
- // log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_GET_ALL_CERT", e.toString()));
- // throw new EBaseException(BaseResources.CERT_ERROR);
+ // log(ILogger.LL_FAILURE,
+ // CMS.getLogMessage("CMSCORE_SECURITY_GET_ALL_CERT",
+ // e.toString()));
+ // throw new EBaseException(BaseResources.CERT_ERROR);
} catch (TokenException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_GET_ALL_CERT", e.toString()));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_ERROR", ""));
@@ -1367,26 +1367,26 @@ CMS.debug("*** removing this interna cert");
public NameValuePairs getCACerts() throws EBaseException {
NameValuePairs pairs = new NameValuePairs();
- //InternalCertificate[] certs;
+ // InternalCertificate[] certs;
X509Certificate[] certs;
try {
- certs =
+ certs =
CryptoManager.getInstance().getCACerts();
} catch (NotInitializedException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_GET_CA_CERT", e.toString()));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_CRYPTOMANAGER_UNINITIALIZED"));
}
- if( mNicknameMapCertsTable == null ) {
- CMS.debug( "JssSubsystem::getCACerts() - "
- + "mNicknameMapCertsTable is null!" );
- throw new EBaseException( "mNicknameMapCertsTable is null" );
+ if (mNicknameMapCertsTable == null) {
+ CMS.debug("JssSubsystem::getCACerts() - "
+ + "mNicknameMapCertsTable is null!");
+ throw new EBaseException("mNicknameMapCertsTable is null");
} else {
mNicknameMapCertsTable.clear();
}
- // a temp hashtable with vectors
+ // a temp hashtable with vectors
Hashtable<String, Vector<X509Certificate>> vecTable = new Hashtable<String, Vector<X509Certificate>>();
for (int i = 0; i < certs.length; i++) {
@@ -1396,7 +1396,7 @@ CMS.debug("*** removing this interna cert");
Vector<X509Certificate> v;
if (vecTable.containsKey((Object) nickname) == true) {
- v = vecTable.get(nickname);
+ v = vecTable.get(nickname);
} else {
v = new Vector<X509Certificate>();
}
@@ -1409,19 +1409,19 @@ CMS.debug("*** removing this interna cert");
while (elms.hasMoreElements()) {
String key = (String) elms.nextElement();
- Vector<X509Certificate> v = vecTable.get((Object) key);
+ Vector<X509Certificate> v = vecTable.get((Object) key);
X509Certificate[] a = new X509Certificate[v.size()];
v.copyInto((Object[]) a);
mNicknameMapCertsTable.put(key, a);
}
- Enumeration<String> keys = mNicknameMapCertsTable.keys();
+ Enumeration<String> keys = mNicknameMapCertsTable.keys();
while (keys.hasMoreElements()) {
String nickname = (String) keys.nextElement();
X509Certificate[] value = (X509Certificate[]) mNicknameMapCertsTable.get(nickname);
-
+
for (int i = 0; i < value.length; i++) {
InternalCertificate icert = null;
@@ -1431,14 +1431,13 @@ CMS.debug("*** removing this interna cert");
Debug.trace("cert is not an InternalCertificate");
Debug.trace("nickname: " + nickname + " index " + i);
Debug.trace("cert: " + value[i]);
- continue;
+ continue;
}
-
+
int flag = icert.getSSLTrust();
String trust = "U";
- if ((InternalCertificate.TRUSTED_CLIENT_CA & flag) ==
- InternalCertificate.TRUSTED_CLIENT_CA)
+ if ((InternalCertificate.TRUSTED_CLIENT_CA & flag) == InternalCertificate.TRUSTED_CLIENT_CA)
trust = "T";
X509CertImpl impl = null;
@@ -1455,12 +1454,12 @@ CMS.debug("*** removing this interna cert");
String vvalue = pair.getValue();
pair.setValue(vvalue + ";" + certValue);
- }
+ }
} catch (CertificateException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_GET_CA_CERT_FOR", nickname, e.toString()));
// allow it to continue with other certs even if one blows
// up
- // throw new EBaseException(BaseResources.CERT_ERROR);
+ // throw new EBaseException(BaseResources.CERT_ERROR);
}
}
}
@@ -1489,8 +1488,8 @@ CMS.debug("*** removing this interna cert");
if (cert instanceof InternalCertificate) {
if (trust.equals("Trust")) {
int trustflag = InternalCertificate.TRUSTED_CA |
- InternalCertificate.TRUSTED_CLIENT_CA |
- InternalCertificate.VALID_CA;
+ InternalCertificate.TRUSTED_CLIENT_CA |
+ InternalCertificate.VALID_CA;
((InternalCertificate) cert).setSSLTrust(trustflag);
} else
@@ -1503,7 +1502,7 @@ CMS.debug("*** removing this interna cert");
}
}
}
- } catch (ParseException e) {
+ } catch (ParseException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_TRUST_CERT", e.toString()));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_ERROR", e.toString()));
} catch (CertificateException e) {
@@ -1514,12 +1513,14 @@ CMS.debug("*** removing this interna cert");
/**
* Delete the CA certificate from the perm database.
+ *
* @param nickname The nickname of the CA certificate.
- * @param notAfterTime The notAfter of the certificate. It is possible to get multiple
- * certificates under the same nickname. If one of the certificates match the notAfterTime,
- * then the certificate will get deleted. The format of the notAfterTime has to be
- * in "MMMMM dd, yyyy HH:mm:ss" format.
- */
+ * @param notAfterTime The notAfter of the certificate. It is possible to
+ * get multiple certificates under the same nickname. If one of
+ * the certificates match the notAfterTime, then the certificate
+ * will get deleted. The format of the notAfterTime has to be in
+ * "MMMMM dd, yyyy HH:mm:ss" format.
+ */
public void deleteCACert(String nickname, String notAfterTime) throws EBaseException {
try {
if (mNicknameMapCertsTable != null) {
@@ -1575,15 +1576,18 @@ CMS.debug("*** removing this interna cert");
/**
* Delete any certificate from the any token.
+ *
* @param nickname The nickname of the certificate.
- * @param notAfterTime The notAfter of the certificate. It is possible to get multiple
- * certificates under the same nickname. If one of the certificates match the notAfterTime,
- * then the certificate will get deleted. The format of the notAfterTime has to be
- * in "MMMMM dd, yyyy HH:mm:ss" format.
- */
+ * @param notAfterTime The notAfter of the certificate. It is possible to
+ * get multiple certificates under the same nickname. If one of
+ * the certificates match the notAfterTime, then the certificate
+ * will get deleted. The format of the notAfterTime has to be in
+ * "MMMMM dd, yyyy HH:mm:ss" format.
+ */
public void deleteCert(String nickname, String notAfterTime) throws EBaseException {
boolean isUserCert = false;
- X509Certificate[] certs = null;;
+ X509Certificate[] certs = null;
+ ;
try {
if (mNicknameMapCertsTable != null) {
@@ -1677,15 +1681,16 @@ CMS.debug("*** removing this interna cert");
CryptoStore store = tcert.getOwningToken().getCryptoStore();
tcert.getOwningToken().getCryptoStore().deleteCert(tcert);
- } else
+ } else
throw new EBaseException(CMS.getUserMessage("CMS_BASE_NOT_TOKEN_CERT"));
int index = nickname.indexOf(":");
-
- // the deleted certificate is on the hardware token. We should delete the same one from
+
+ // the deleted certificate is on the hardware token. We should
+ // delete the same one from
// the internal token.
if (index > 0) {
- CryptoToken cToken = CryptoManager.getInstance().getInternalKeyStorageToken();
+ CryptoToken cToken = CryptoManager.getInstance().getInternalKeyStorageToken();
CryptoStore store = cToken.getCryptoStore();
X509Certificate[] allcerts = CryptoManager.getInstance().getCACerts();
@@ -1721,7 +1726,7 @@ CMS.debug("*** removing this interna cert");
} catch (CertificateEncodingException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_DELETE_CERT", e.toString()));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_ERROR", e.toString()));
- } catch (IOException e) {
+ } catch (IOException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_DELETE_CERT", e.toString()));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_ERROR", e.toString()));
}
@@ -1730,7 +1735,7 @@ CMS.debug("*** removing this interna cert");
public String getSubjectDN(String nickname) throws EBaseException {
try {
X509Certificate cert =
- CryptoManager.getInstance().findCertByNickname(nickname);
+ CryptoManager.getInstance().findCertByNickname(nickname);
X509CertImpl impl = new X509CertImpl(cert.getEncoded());
return impl.getSubjectDN().getName();
@@ -1750,14 +1755,14 @@ CMS.debug("*** removing this interna cert");
}
public void setRootCertTrust(String nickname, String serialno,
- String issuerName, String trust) throws EBaseException {
-
+ String issuerName, String trust) throws EBaseException {
+
X509Certificate cert = getCertificate(nickname, serialno, issuerName);
if (cert instanceof InternalCertificate) {
if (trust.equals("trust")) {
int trustflag = InternalCertificate.TRUSTED_CA |
- InternalCertificate.TRUSTED_CLIENT_CA |
- InternalCertificate.VALID_CA;
+ InternalCertificate.TRUSTED_CLIENT_CA |
+ InternalCertificate.VALID_CA;
((InternalCertificate) cert).setSSLTrust(trustflag);
} else {
@@ -1767,31 +1772,31 @@ CMS.debug("*** removing this interna cert");
}
public X509Certificate getCertificate(String nickname, String serialno,
- String issuerName) throws EBaseException {
+ String issuerName) throws EBaseException {
int index = nickname.indexOf(":");
String tokenname = nickname.substring(0, index);
if (tokenname.equals(Constants.PR_INTERNAL_TOKEN_NAME)) {
- nickname = nickname.substring(index+1);
+ nickname = nickname.substring(index + 1);
}
try {
X509Certificate[] certs =
- CryptoManager.getInstance().findCertsByNickname(nickname);
+ CryptoManager.getInstance().findCertsByNickname(nickname);
X509CertImpl impl = null;
- int i=0;
+ int i = 0;
if (certs != null && certs.length > 0) {
for (; i < certs.length; i++) {
impl = new X509CertImpl(certs[i].getEncoded());
if (impl.getIssuerDN().toString().equals(issuerName) &&
- impl.getSerialNumber().toString().equals(serialno))
+ impl.getSerialNumber().toString().equals(serialno))
return certs[i];
}
} else {
EBaseException e =
- new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_NOT_FOUND"));
+ new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_NOT_FOUND"));
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_SECURITY_PRINT_CERT", e.toString()));
+ CMS.getLogMessage("CMSCORE_SECURITY_PRINT_CERT", e.toString()));
throw e;
}
} catch (NotInitializedException e) {
@@ -1799,50 +1804,50 @@ CMS.debug("*** removing this interna cert");
throw new EBaseException(CMS.getUserMessage("CMS_BASE_CRYPTOMANAGER_UNINITIALIZED"));
} catch (TokenException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_PRINT_CERT", e.toString()));
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_TOKEN_NOT_FOUND", "")); } catch (CertificateException e) {
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_TOKEN_NOT_FOUND", ""));
+ } catch (CertificateException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_PRINT_CERT", e.toString()));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_ERROR", e.toString()));
}
-
+
return null;
}
public String getRootCertTrustBit(String nickname, String serialno,
- String issuerName) throws EBaseException {
+ String issuerName) throws EBaseException {
int index = nickname.indexOf(":");
String tokenname = nickname.substring(0, index);
if (tokenname.equals(Constants.PR_INTERNAL_TOKEN_NAME)) {
- nickname = nickname.substring(index+1);
+ nickname = nickname.substring(index + 1);
}
try {
X509Certificate[] certs =
- CryptoManager.getInstance().findCertsByNickname(nickname);
+ CryptoManager.getInstance().findCertsByNickname(nickname);
X509CertImpl impl = null;
- int i=0;
+ int i = 0;
if (certs != null && certs.length > 0) {
for (; i < certs.length; i++) {
impl = new X509CertImpl(certs[i].getEncoded());
if (impl.getIssuerDN().toString().equals(issuerName) &&
- impl.getSerialNumber().toString().equals(serialno))
+ impl.getSerialNumber().toString().equals(serialno))
break;
}
} else {
EBaseException e =
- new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_NOT_FOUND"));
+ new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_NOT_FOUND"));
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_SECURITY_PRINT_CERT", e.toString()));
+ CMS.getLogMessage("CMSCORE_SECURITY_PRINT_CERT", e.toString()));
throw e;
}
String trust = "U";
if (certs[i] instanceof InternalCertificate) {
- InternalCertificate icert = (InternalCertificate)certs[i];
+ InternalCertificate icert = (InternalCertificate) certs[i];
int flag = icert.getSSLTrust();
- if ((InternalCertificate.TRUSTED_CLIENT_CA & flag) ==
- InternalCertificate.TRUSTED_CLIENT_CA)
+ if ((InternalCertificate.TRUSTED_CLIENT_CA & flag) == InternalCertificate.TRUSTED_CLIENT_CA)
trust = "T";
- } else
+ } else
trust = "N/A";
return trust;
} catch (NotInitializedException e) {
@@ -1850,36 +1855,37 @@ CMS.debug("*** removing this interna cert");
throw new EBaseException(CMS.getUserMessage("CMS_BASE_CRYPTOMANAGER_UNINITIALIZED"));
} catch (TokenException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_PRINT_CERT", e.toString()));
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_TOKEN_NOT_FOUND", "")); } catch (CertificateException e) {
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_TOKEN_NOT_FOUND", ""));
+ } catch (CertificateException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_PRINT_CERT", e.toString()));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_ERROR", e.toString()));
}
}
public String getCertPrettyPrint(String nickname, String serialno,
- String issuerName, Locale locale) throws EBaseException {
+ String issuerName, Locale locale) throws EBaseException {
int index = nickname.indexOf(":");
String tokenname = nickname.substring(0, index);
if (tokenname.equals(Constants.PR_INTERNAL_TOKEN_NAME)) {
- nickname = nickname.substring(index+1);
+ nickname = nickname.substring(index + 1);
}
try {
X509Certificate[] certs =
- CryptoManager.getInstance().findCertsByNickname(nickname);
+ CryptoManager.getInstance().findCertsByNickname(nickname);
X509CertImpl impl = null;
if (certs != null && certs.length > 0) {
for (int i = 0; i < certs.length; i++) {
impl = new X509CertImpl(certs[i].getEncoded());
if (impl.getIssuerDN().toString().equals(issuerName) &&
- impl.getSerialNumber().toString().equals(serialno))
+ impl.getSerialNumber().toString().equals(serialno))
break;
}
} else {
- EBaseException e =
- new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_NOT_FOUND"));
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_SECURITY_PRINT_CERT", e.toString()));
+ EBaseException e =
+ new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_NOT_FOUND"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_SECURITY_PRINT_CERT", e.toString()));
throw e;
}
CertPrettyPrint print = null;
@@ -1904,42 +1910,42 @@ CMS.debug("*** removing this interna cert");
}
public String getCertPrettyPrintAndFingerPrint(String nickname, String serialno,
- String issuerName, Locale locale) throws EBaseException {
+ String issuerName, Locale locale) throws EBaseException {
int index = nickname.indexOf(":");
String tokenname = nickname.substring(0, index);
if (tokenname.equals(Constants.PR_INTERNAL_TOKEN_NAME)) {
- nickname = nickname.substring(index+1);
+ nickname = nickname.substring(index + 1);
}
try {
X509Certificate[] certs =
- CryptoManager.getInstance().findCertsByNickname(nickname);
+ CryptoManager.getInstance().findCertsByNickname(nickname);
X509CertImpl impl = null;
if (certs != null && certs.length > 0) {
for (int i = 0; i < certs.length; i++) {
impl = new X509CertImpl(certs[i].getEncoded());
if (impl.getIssuerDN().toString().equals(issuerName) &&
- impl.getSerialNumber().toString().equals(serialno))
+ impl.getSerialNumber().toString().equals(serialno))
break;
}
} else {
- EBaseException e =
- new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_NOT_FOUND"));
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_SECURITY_PRINT_CERT", e.toString()));
+ EBaseException e =
+ new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_NOT_FOUND"));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_SECURITY_PRINT_CERT", e.toString()));
throw e;
}
CertPrettyPrint print = null;
- String fingerPrint = "";
+ String fingerPrint = "";
if (impl != null) {
print = new CertPrettyPrint(impl);
- fingerPrint = CMS.getFingerPrints(impl.getEncoded());
- }
+ fingerPrint = CMS.getFingerPrints(impl.getEncoded());
+ }
if ((print != null) && (fingerPrint != "")) {
- String pp = print.toString(locale) + "\n" +
- "Certificate Fingerprints:"+ '\n' + fingerPrint;
+ String pp = print.toString(locale) + "\n" +
+ "Certificate Fingerprints:" + '\n' + fingerPrint;
return pp;
} else
return null;
@@ -1958,14 +1964,14 @@ CMS.debug("*** removing this interna cert");
}
}
- public String getCertPrettyPrint(String nickname, String date,
- Locale locale) throws EBaseException {
+ public String getCertPrettyPrint(String nickname, String date,
+ Locale locale) throws EBaseException {
try {
X509Certificate[] certs =
- CryptoManager.getInstance().findCertsByNickname(nickname);
+ CryptoManager.getInstance().findCertsByNickname(nickname);
if ((certs == null || certs.length == 0) &&
- mNicknameMapCertsTable != null) {
+ mNicknameMapCertsTable != null) {
certs = (X509Certificate[]) mNicknameMapCertsTable.get(nickname);
}
if (certs == null) {
@@ -2010,7 +2016,7 @@ CMS.debug("*** removing this interna cert");
}
public String getCertPrettyPrint(String b64E, Locale locale) throws EBaseException {
- try {
+ try {
try {
byte[] b = KeyCertUtil.convertB64EToByteArray(b64E);
X509CertImpl impl = new X509CertImpl(b);
@@ -2026,7 +2032,7 @@ CMS.debug("*** removing this interna cert");
byte data[] = com.netscape.osutil.OSUtil.AtoB(normalized);
ContentInfo ci = (ContentInfo)
- ASN1Util.decode(ContentInfo.getTemplate(), data);
+ ASN1Util.decode(ContentInfo.getTemplate(), data);
if (!ci.getContentType().equals(ContentInfo.SIGNED_DATA)) {
throw new CertificateException(
@@ -2053,7 +2059,7 @@ CMS.debug("*** removing this interna cert");
}
} catch (InvalidBERException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_PRINT_CERT", e.toString()));
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_ERROR",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_ERROR",
"Failed to decode"));
} catch (CertificateException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_PRINT_CERT", e.toString()));
@@ -2064,8 +2070,8 @@ CMS.debug("*** removing this interna cert");
}
}
- public X509CertImpl getSignedCert(KeyCertData data, String certType, java.security.PrivateKey priKey)
- throws EBaseException {
+ public X509CertImpl getSignedCert(KeyCertData data, String certType, java.security.PrivateKey priKey)
+ throws EBaseException {
CertificateInfo cert = null;
if (certType.equals(Constants.PR_CA_SIGNING_CERT)) {
@@ -2087,8 +2093,8 @@ CMS.debug("*** removing this interna cert");
try {
certInfo = cert.getCertInfo();
- SignatureAlgorithm sigAlg =
- (SignatureAlgorithm) data.get(Constants.PR_SIGNATURE_ALGORITHM);
+ SignatureAlgorithm sigAlg =
+ (SignatureAlgorithm) data.get(Constants.PR_SIGNATURE_ALGORITHM);
signedCert = KeyCertUtil.signCert(priKey, certInfo, sigAlg);
} catch (NoSuchTokenException e) {
@@ -2115,15 +2121,15 @@ CMS.debug("*** removing this interna cert");
if (certinfo == null)
return false;
else {
- CertificateExtensions exts =
- (CertificateExtensions) certinfo.get(X509CertInfo.EXTENSIONS);
+ CertificateExtensions exts =
+ (CertificateExtensions) certinfo.get(X509CertInfo.EXTENSIONS);
if (exts == null)
return false;
else {
try {
BasicConstraintsExtension ext = (BasicConstraintsExtension)
- exts.get(BasicConstraintsExtension.class.getSimpleName());
+ exts.get(BasicConstraintsExtension.class.getSimpleName());
if (ext == null)
return false;
@@ -2155,8 +2161,8 @@ CMS.debug("*** removing this interna cert");
}
}
- public CertificateExtensions getExtensions(String tokenname, String nickname)
- throws EBaseException {
+ public CertificateExtensions getExtensions(String tokenname, String nickname)
+ throws EBaseException {
try {
return KeyCertUtil.getExtensions(tokenname, nickname);
} catch (NotInitializedException e) {
@@ -2182,7 +2188,8 @@ CMS.debug("*** removing this interna cert");
}
public void checkKeyLength(String keyType, int keyLength, String certType, int minRSAKeyLen) throws EBaseException {
- // KeyCertUtil.checkKeyLength(keyType, keyLength, certType, minRSAKeyLen);
+ // KeyCertUtil.checkKeyLength(keyType, keyLength, certType,
+ // minRSAKeyLen);
}
public PQGParams getPQG(int keysize) {
@@ -2190,25 +2197,24 @@ CMS.debug("*** removing this interna cert");
}
public PQGParams getCAPQG(int keysize, IConfigStore store)
- throws EBaseException {
+ throws EBaseException {
return KeyCertUtil.getCAPQG(keysize, store);
}
public CertificateExtensions getCertExtensions(String tokenname, String nickname)
- throws NotInitializedException, TokenException, ObjectNotFoundException,
+ throws NotInitializedException, TokenException, ObjectNotFoundException,
IOException, CertificateException {
return KeyCertUtil.getExtensions(tokenname, nickname);
}
}
-class JSSDatabaseCloser extends org.mozilla.jss.DatabaseCloser
-{
+class JSSDatabaseCloser extends org.mozilla.jss.DatabaseCloser {
public JSSDatabaseCloser() throws Exception {
- super();
+ super();
}
public void closeDatabases() {
- super.closeDatabases();
+ super.closeDatabases();
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/security/KRATransportCert.java b/pki/base/common/src/com/netscape/cmscore/security/KRATransportCert.java
index 35b7cdf2..b1294902 100644
--- a/pki/base/common/src/com/netscape/cmscore/security/KRATransportCert.java
+++ b/pki/base/common/src/com/netscape/cmscore/security/KRATransportCert.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.security;
-
import java.io.IOException;
import java.security.KeyPair;
@@ -29,16 +28,15 @@ import com.netscape.certsrv.common.ConfigConstants;
import com.netscape.certsrv.common.Constants;
import com.netscape.certsrv.security.KeyCertData;
-
/**
- * KRA transport certificate
+ * KRA transport certificate
*
* @author Christine Ho
* @version $Revision$, $Date$
*/
public class KRATransportCert extends CertificateInfo {
- public static final String SUBJECT_NAME =
- "CN=Data Recovery Manager, O=Netscape Communications, C=US";
+ public static final String SUBJECT_NAME =
+ "CN=Data Recovery Manager, O=Netscape Communications, C=US";
private String mTokenname = Constants.PR_INTERNAL_TOKEN_NAME;
public KRATransportCert(KeyCertData properties) {
@@ -49,8 +47,8 @@ public class KRATransportCert extends CertificateInfo {
super(properties, pair);
String tmp = (String) mProperties.get(Constants.PR_TOKEN_NAME);
- if ((tmp != null) &&
- (!tmp.equals(Constants.PR_INTERNAL_TOKEN)))
+ if ((tmp != null) &&
+ (!tmp.equals(Constants.PR_INTERNAL_TOKEN)))
mTokenname = tmp;
mProperties.put(Constants.PR_AKI, Constants.TRUE);
}
@@ -72,8 +70,8 @@ public class KRATransportCert extends CertificateInfo {
public String getNickname() {
String name = (String) mProperties.get(Constants.PR_NICKNAME);
- String instanceName =
- (String) mProperties.get(ConfigConstants.PR_CERT_INSTANCE_NAME);
+ String instanceName =
+ (String) mProperties.get(ConfigConstants.PR_CERT_INSTANCE_NAME);
if (name != null)
return name;
@@ -81,19 +79,14 @@ public class KRATransportCert extends CertificateInfo {
}
/*
- public SignatureAlgorithm getSigningAlgorithm() {
- SignatureAlgorithm sAlg =
- (SignatureAlgorithm)mProperties.get(Constants.PR_SIGNATURE_ALGORITHM);
- if (sAlg != null) {
- return sAlg;
- }
- String alg = (String)mProperties.get(Constants.PR_KEY_TYPE);
-
- if (alg.equals("RSA"))
- return SignatureAlgorithm.RSASignatureWithMD5Digest;
- else
- return SignatureAlgorithm.DSASignatureWithSHA1Digest;
- }
+ * public SignatureAlgorithm getSigningAlgorithm() { SignatureAlgorithm sAlg
+ * = (SignatureAlgorithm)mProperties.get(Constants.PR_SIGNATURE_ALGORITHM);
+ * if (sAlg != null) { return sAlg; } String alg =
+ * (String)mProperties.get(Constants.PR_KEY_TYPE);
+ *
+ * if (alg.equals("RSA")) return
+ * SignatureAlgorithm.RSASignatureWithMD5Digest; else return
+ * SignatureAlgorithm.DSASignatureWithSHA1Digest; }
*/
public String getKeyAlgorithm() {
@@ -107,4 +100,3 @@ public class KRATransportCert extends CertificateInfo {
return extension;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/security/KeyCertUtil.java b/pki/base/common/src/com/netscape/cmscore/security/KeyCertUtil.java
index c020fe8b..3b49d233 100644
--- a/pki/base/common/src/com/netscape/cmscore/security/KeyCertUtil.java
+++ b/pki/base/common/src/com/netscape/cmscore/security/KeyCertUtil.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.security;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FilterOutputStream;
@@ -116,7 +115,6 @@ import com.netscape.cmscore.dbs.DateMapper;
import com.netscape.cmscore.dbs.X509CertImplMapper;
import com.netscape.cmsutil.crypto.CryptoUtil;
-
/**
* This class provides all the base methods to generate the key for different
* kinds of certificates.
@@ -155,11 +153,11 @@ public class KeyCertUtil {
}
}
- public static String getTokenNames(CryptoManager manager)
- throws TokenException {
+ public static String getTokenNames(CryptoManager manager)
+ throws TokenException {
String tokenList = "";
@SuppressWarnings("unchecked")
- Enumeration<CryptoToken> tokens = manager.getExternalTokens();
+ Enumeration<CryptoToken> tokens = manager.getExternalTokens();
int num = 0;
while (tokens.hasMoreElements()) {
@@ -183,9 +181,9 @@ public class KeyCertUtil {
ByteArrayOutputStream output = new ByteArrayOutputStream();
Base64OutputStream b64 = new Base64OutputStream(new
PrintStream(new
- FilterOutputStream(output)
+ FilterOutputStream(output)
)
- );
+ );
b64.write(bytes);
b64.flush();
@@ -196,7 +194,7 @@ public class KeyCertUtil {
}
public static byte[] makeDSSParms(BigInteger P, BigInteger Q, BigInteger G)
- throws IOException {
+ throws IOException {
// Write P, Q, G to a DER stream
DerOutputStream contents = new DerOutputStream();
@@ -213,25 +211,25 @@ public class KeyCertUtil {
return sequence.toByteArray();
}
- public static PrivateKey getPrivateKey(String tokenname, String nickname)
- throws TokenException, EBaseException,
+ public static PrivateKey getPrivateKey(String tokenname, String nickname)
+ throws TokenException, EBaseException,
NoSuchTokenException, NotInitializedException, CertificateException,
CertificateEncodingException, EBaseException, ObjectNotFoundException {
/*
- String caNickname = store.getString("ca.signing.tokenname");
- String tokenName = store.getString("ca.signing.cacertnickname");
+ * String caNickname = store.getString("ca.signing.tokenname"); String
+ * tokenName = store.getString("ca.signing.cacertnickname");
*/
X509Certificate cert = getCertificate(tokenname, nickname);
-
+
return CryptoManager.getInstance().findPrivKeyByCert(cert);
}
- public static String getCertSubjectName(String tokenname, String nickname)
- throws TokenException, EBaseException, NoSuchTokenException,
+ public static String getCertSubjectName(String tokenname, String nickname)
+ throws TokenException, EBaseException, NoSuchTokenException,
NotInitializedException, CertificateException,
CertificateEncodingException, EBaseException {
-
+
X509Certificate cert = getCertificate(tokenname, nickname);
X509CertImpl impl = new X509CertImpl(cert.getEncoded());
@@ -239,16 +237,16 @@ public class KeyCertUtil {
}
public static X509CertImpl signCert(PrivateKey privateKey, X509CertInfo certInfo,
- SignatureAlgorithm sigAlg)
- throws NoSuchTokenException, EBaseException, NotInitializedException {
+ SignatureAlgorithm sigAlg)
+ throws NoSuchTokenException, EBaseException, NotInitializedException {
try {
CertificateAlgorithmId sId = (CertificateAlgorithmId)
- certInfo.get(X509CertInfo.ALGORITHM_ID);
+ certInfo.get(X509CertInfo.ALGORITHM_ID);
AlgorithmId sigAlgId =
- (AlgorithmId) sId.get(CertificateAlgorithmId.ALGORITHM);
+ (AlgorithmId) sId.get(CertificateAlgorithmId.ALGORITHM);
- org.mozilla.jss.crypto.PrivateKey priKey =
- (org.mozilla.jss.crypto.PrivateKey) privateKey;
+ org.mozilla.jss.crypto.PrivateKey priKey =
+ (org.mozilla.jss.crypto.PrivateKey) privateKey;
CryptoToken token = priKey.getOwningToken();
DerOutputStream tmp = new DerOutputStream();
@@ -283,7 +281,7 @@ public class KeyCertUtil {
} catch (CertificateException e) {
throw new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_ERROR", e.toString()));
}
- }
+ }
public static SignatureAlgorithm getSigningAlgorithm(String keyType) {
SignatureAlgorithm sAlg = null;
@@ -318,9 +316,9 @@ public class KeyCertUtil {
}
public static AlgorithmId getAlgorithmId(String algname, IConfigStore store)
- throws EBaseException {
+ throws EBaseException {
try {
-
+
if (algname.equals("DSA")) {
byte[] p = store.getByteArray("ca.dsaP", null);
byte[] q = store.getByteArray("ca.dsaQ", null);
@@ -341,10 +339,10 @@ public class KeyCertUtil {
}
public static X509Certificate getCertificate(String tokenname,
- String nickname) throws NotInitializedException, NoSuchTokenException,
+ String nickname) throws NotInitializedException, NoSuchTokenException,
EBaseException, TokenException {
CryptoManager manager = CryptoManager.getInstance();
- CryptoToken token = null;
+ CryptoToken token = null;
if (tokenname.equals(Constants.PR_INTERNAL_TOKEN_NAME)) {
token = manager.getInternalKeyStorageToken();
@@ -365,12 +363,12 @@ public class KeyCertUtil {
}
}
- public static KeyPair getKeyPair(String tokenname, String nickname)
- throws NotInitializedException, NoSuchTokenException, TokenException,
+ public static KeyPair getKeyPair(String tokenname, String nickname)
+ throws NotInitializedException, NoSuchTokenException, TokenException,
ObjectNotFoundException, EBaseException {
X509Certificate cert = getCertificate(tokenname, nickname);
PrivateKey priKey =
- CryptoManager.getInstance().findPrivKeyByCert(cert);
+ CryptoManager.getInstance().findPrivKeyByCert(cert);
PublicKey publicKey = cert.getPublicKey();
return new KeyPair(publicKey, priKey);
@@ -384,8 +382,8 @@ public class KeyCertUtil {
}
}
- public static PQGParams getCAPQG(int keysize, IConfigStore store)
- throws EBaseException {
+ public static PQGParams getCAPQG(int keysize, IConfigStore store)
+ throws EBaseException {
if (store != null) {
try {
int pqgKeySize = store.getInteger("ca.dsaPQG.keyLength", 0);
@@ -422,9 +420,9 @@ public class KeyCertUtil {
store.putInteger("ca.dsaCounter", pqg.getCounter());
store.putString("ca.dsaH", KeyCertUtil.base64Encode(
pqg.getH().toByteArray()));
- store.putString("ca.DSSParms",
- KeyCertUtil.base64Encode(
- KeyCertUtil.makeDSSParms(pqg.getP(), pqg.getQ(), pqg.getG())));
+ store.putString("ca.DSSParms",
+ KeyCertUtil.base64Encode(
+ KeyCertUtil.makeDSSParms(pqg.getP(), pqg.getQ(), pqg.getG())));
store.commit(false);
return pqg;
} catch (IOException ee) {
@@ -439,12 +437,12 @@ public class KeyCertUtil {
}
public static KeyPair generateKeyPair(CryptoToken token,
- KeyPairAlgorithm kpAlg, int keySize, PQGParams pqg)
- throws NoSuchAlgorithmException, TokenException, InvalidAlgorithmParameterException,
+ KeyPairAlgorithm kpAlg, int keySize, PQGParams pqg)
+ throws NoSuchAlgorithmException, TokenException, InvalidAlgorithmParameterException,
InvalidParameterException, PQGParamGenException {
KeyPairGenerator kpGen = token.getKeyPairGenerator(kpAlg);
-
+
if (kpAlg == KeyPairAlgorithm.DSA) {
if (pqg == null) {
kpGen.initialize(keySize);
@@ -464,18 +462,16 @@ public class KeyCertUtil {
do {
// 602548 NSS bug - to overcome it, we use isBadDSAKeyPair
kp = kpGen.genKeyPair();
- }
- while (isBadDSAKeyPair(kp));
+ } while (isBadDSAKeyPair(kp));
return kp;
}
}
/**
- * Test for a DSA key pair that will trigger a bug in NSS.
- * The problem occurs when the first byte of the key is 0. This
- * happens when the value otherwise would have been negative, and a
- * zero byte is prepended to force it to be positive.
- * This is blackflag bug 602548.
+ * Test for a DSA key pair that will trigger a bug in NSS. The problem
+ * occurs when the first byte of the key is 0. This happens when the value
+ * otherwise would have been negative, and a zero byte is prepended to force
+ * it to be positive. This is blackflag bug 602548.
*/
public static boolean isBadDSAKeyPair(KeyPair pair) {
try {
@@ -490,7 +486,7 @@ public class KeyCertUtil {
byte[] bits = bs.getBits();
ByteArrayInputStream bitstream = new ByteArrayInputStream(bs.getBits());
ASN1Header wrapper = new ASN1Header(bitstream);
- byte[] valBytes = new byte[ (int) wrapper.getContentLength() ];
+ byte[] valBytes = new byte[(int) wrapper.getContentLength()];
ASN1Util.readFully(valBytes, bitstream);
@@ -504,7 +500,7 @@ public class KeyCertUtil {
}
public static KeyPair generateKeyPair(String tokenName, String alg,
- int keySize, PQGParams pqg) throws EBaseException {
+ int keySize, PQGParams pqg) throws EBaseException {
CryptoToken token = null;
@@ -549,8 +545,8 @@ public class KeyCertUtil {
}
}
- public static PKCS10 getCertRequest(String subjectName, KeyPair keyPair)
- throws NoSuchAlgorithmException, NoSuchProviderException,
+ public static PKCS10 getCertRequest(String subjectName, KeyPair keyPair)
+ throws NoSuchAlgorithmException, NoSuchProviderException,
InvalidKeyException, IOException, CertificateException,
SignatureException {
PublicKey pubk = keyPair.getPublic();
@@ -565,7 +561,7 @@ public class KeyCertUtil {
alg = "DSA";
}
java.security.Signature sig =
- java.security.Signature.getInstance(alg, "Mozilla-JSS");
+ java.security.Signature.getInstance(alg, "Mozilla-JSS");
sig.initSign(keyPair.getPrivate());
@@ -580,9 +576,9 @@ public class KeyCertUtil {
}
public static PKCS10 getCertRequest(String subjectName, KeyPair
- keyPair, Extensions
- exts)
- throws NoSuchAlgorithmException, NoSuchProviderException,
+ keyPair, Extensions
+ exts)
+ throws NoSuchAlgorithmException, NoSuchProviderException,
InvalidKeyException, IOException, CertificateException,
SignatureException {
PublicKey pubk = keyPair.getPublic();
@@ -597,7 +593,7 @@ public class KeyCertUtil {
alg = "DSA";
}
java.security.Signature sig =
- java.security.Signature.getInstance(alg, "Mozilla-JSS");
+ java.security.Signature.getInstance(alg, "Mozilla-JSS");
sig.initSign(keyPair.getPrivate());
@@ -605,8 +601,8 @@ public class KeyCertUtil {
if (exts != null) {
PKCS10Attribute attr = new
- PKCS10Attribute(PKCS9Attribute.EXTENSION_REQUEST_OID,
- (CertAttrSet) exts);
+ PKCS10Attribute(PKCS9Attribute.EXTENSION_REQUEST_OID,
+ (CertAttrSet) exts);
PKCS10Attributes attrs = new PKCS10Attributes();
attrs.setAttribute(attr.getAttributeValue().getName(), attr);
@@ -624,8 +620,8 @@ public class KeyCertUtil {
return pkcs10;
}
- public static X509Key convertPublicKeyToX509Key(PublicKey pubk)
- throws InvalidKeyException {
+ public static X509Key convertPublicKeyToX509Key(PublicKey pubk)
+ throws InvalidKeyException {
X509Key xKey;
@@ -654,23 +650,23 @@ public class KeyCertUtil {
}
public static X509Certificate
- importCert(X509CertImpl signedCert, String nickname,
- String certType) throws NotInitializedException, TokenException,
- CertificateEncodingException, UserCertConflictException,
- NicknameConflictException, NoSuchItemOnTokenException, CertificateException {
-
+ importCert(X509CertImpl signedCert, String nickname,
+ String certType) throws NotInitializedException, TokenException,
+ CertificateEncodingException, UserCertConflictException,
+ NicknameConflictException, NoSuchItemOnTokenException, CertificateException {
+
return importCert(signedCert.getEncoded(), nickname, certType);
}
public static X509Certificate
- importCert(String b64E, String nickname, String certType)
- throws NotInitializedException, TokenException,
- CertificateEncodingException, UserCertConflictException,
- NicknameConflictException, NoSuchItemOnTokenException, CertificateException {
-
+ importCert(String b64E, String nickname, String certType)
+ throws NotInitializedException, TokenException,
+ CertificateEncodingException, UserCertConflictException,
+ NicknameConflictException, NoSuchItemOnTokenException, CertificateException {
+
byte b[] = b64E.getBytes();
X509Certificate cert = getInternalCertificate(b, nickname, certType);
-
+
if (cert instanceof InternalCertificate) {
setTrust(certType, (InternalCertificate) cert);
}
@@ -678,10 +674,10 @@ public class KeyCertUtil {
}
public static X509Certificate
- importCert(byte[] b, String nickname, String certType)
- throws NotInitializedException, TokenException,
- CertificateEncodingException, UserCertConflictException,
- NicknameConflictException, NoSuchItemOnTokenException, CertificateException {
+ importCert(byte[] b, String nickname, String certType)
+ throws NotInitializedException, TokenException,
+ CertificateEncodingException, UserCertConflictException,
+ NicknameConflictException, NoSuchItemOnTokenException, CertificateException {
X509Certificate cert = getInternalCertificate(b, nickname, certType);
@@ -691,8 +687,8 @@ public class KeyCertUtil {
return cert;
}
- public static X509Certificate getInternalCertificate(byte[] b, String nickname, String certType)
- throws NotInitializedException, TokenException, CertificateEncodingException,
+ public static X509Certificate getInternalCertificate(byte[] b, String nickname, String certType)
+ throws NotInitializedException, TokenException, CertificateEncodingException,
UserCertConflictException, NicknameConflictException, NoSuchItemOnTokenException,
CertificateException {
X509Certificate cert = null;
@@ -701,12 +697,12 @@ public class KeyCertUtil {
cert = CryptoManager.getInstance().importUserCACertPackage(b,
nickname);
} else if (certType.equals(Constants.PR_RA_SIGNING_CERT) ||
- certType.equals(Constants.PR_KRA_TRANSPORT_CERT) ||
- certType.equals(Constants.PR_OCSP_SIGNING_CERT) ||
- certType.equals(Constants.PR_SERVER_CERT) ||
- certType.equals(Constants.PR_SERVER_CERT_RADM) ||
- certType.equals(Constants.PR_OTHER_CERT) ||
- certType.equals(Constants.PR_SUBSYSTEM_CERT)) {
+ certType.equals(Constants.PR_KRA_TRANSPORT_CERT) ||
+ certType.equals(Constants.PR_OCSP_SIGNING_CERT) ||
+ certType.equals(Constants.PR_SERVER_CERT) ||
+ certType.equals(Constants.PR_SERVER_CERT_RADM) ||
+ certType.equals(Constants.PR_OTHER_CERT) ||
+ certType.equals(Constants.PR_SUBSYSTEM_CERT)) {
cert = CryptoManager.getInstance().importCertPackage(b,
nickname);
} else if (certType.equals(Constants.PR_SERVER_CERT_CHAIN)) {
@@ -719,15 +715,15 @@ public class KeyCertUtil {
cert = certchain[certchain.length - 1];
}
}
- return cert;
+ return cert;
}
public static void setTrust(String certType, InternalCertificate inCert) {
if (certType.equals(Constants.PR_CA_SIGNING_CERT)) {
int flag = InternalCertificate.VALID_CA |
- InternalCertificate.TRUSTED_CA |
- InternalCertificate.USER |
- InternalCertificate.TRUSTED_CLIENT_CA;
+ InternalCertificate.TRUSTED_CA |
+ InternalCertificate.USER |
+ InternalCertificate.TRUSTED_CLIENT_CA;
inCert.setSSLTrust(flag);
inCert.setObjectSigningTrust(flag);
@@ -737,72 +733,61 @@ public class KeyCertUtil {
inCert.setSSLTrust(flag);
inCert.setObjectSigningTrust(flag);
- inCert.setEmailTrust(flag);
+ inCert.setEmailTrust(flag);
} else if (certType.equals(Constants.PR_OCSP_SIGNING_CERT)) {
int flag = InternalCertificate.USER | InternalCertificate.VALID_CA;
inCert.setSSLTrust(flag);
inCert.setObjectSigningTrust(flag);
- inCert.setEmailTrust(flag);
+ inCert.setEmailTrust(flag);
} else if (certType.equals(Constants.PR_SERVER_CERT) ||
- certType.equals(Constants.PR_SUBSYSTEM_CERT)) {
+ certType.equals(Constants.PR_SUBSYSTEM_CERT)) {
int flag = InternalCertificate.USER | InternalCertificate.VALID_CA;
inCert.setSSLTrust(flag);
inCert.setObjectSigningTrust(flag);
- inCert.setEmailTrust(flag);
+ inCert.setEmailTrust(flag);
} else if (certType.equals(Constants.PR_TRUSTED_CA_CERT)) {
inCert.setSSLTrust(InternalCertificate.TRUSTED_CA | InternalCertificate.TRUSTED_CLIENT_CA |
- InternalCertificate.VALID_CA);
- //inCert.setEmailTrust(InternalCertificate.TRUSTED_CA);
+ InternalCertificate.VALID_CA);
+ // inCert.setEmailTrust(InternalCertificate.TRUSTED_CA);
- // cannot set this bit. If set, then the cert will not appear when you called getCACerts().
- //inCert.setObjectSigningTrust(InternalCertificate.TRUSTED_CA);
+ // cannot set this bit. If set, then the cert will not appear when
+ // you called getCACerts().
+ // inCert.setObjectSigningTrust(InternalCertificate.TRUSTED_CA);
}
}
public static byte[] convertB64EToByteArray(String b64E)
- throws CertificateException, IOException {
+ throws CertificateException, IOException {
String str = CertUtils.stripCertBrackets(b64E);
byte bCert[] = (byte[]) (com.netscape.osutil.OSUtil.AtoB(str));
/*
- java.security.cert.X509Certificate cert =
- java.security.cert.X509Certificate.getInstance(bCert);
- return cert;
+ * java.security.cert.X509Certificate cert =
+ * java.security.cert.X509Certificate.getInstance(bCert); return cert;
*/
return bCert;
}
/**
- * ASN.1 structure:
- * 0 30 142: SEQUENCE {
- * 3 30 69: SEQUENCE {
- * 5 06 3: OBJECT IDENTIFIER issuerAltName (2 5 29 18)
- * 10 04 62: OCTET STRING
- * : 30 3C 82 01 61 82 01 61 A4 10 30 0E 31 0C 30 0A
- * : 06 03 55 04 03 13 03 64 73 61 87 04 01 01 01 01
- * : 86 01 61 81 14 74 68 6F 6D 61 73 6B 40 6E 65 74
- * : 73 63 61 70 65 2E 63 6F 6D 88 03 29 01 01
- * : }
- * 74 30 69: SEQUENCE {
- * 76 06 3: OBJECT IDENTIFIER subjectAltName (2 5 29 17)
- * 81 04 62: OCTET STRING
- * : 30 3C 82 01 61 82 01 61 A4 10 30 0E 31 0C 30 0A
- * : 06 03 55 04 03 13 03 64 73 61 87 04 01 01 01 01
- * : 86 01 61 81 14 74 68 6F 6D 61 73 6B 40 6E 65 74
- * : 73 63 61 70 65 2E 63 6F 6D 88 03 29 01 01
- * : }
- * : }
- * Uses the following to test with configuration wizard:
+ * ASN.1 structure: 0 30 142: SEQUENCE { 3 30 69: SEQUENCE { 5 06 3: OBJECT
+ * IDENTIFIER issuerAltName (2 5 29 18) 10 04 62: OCTET STRING : 30 3C 82 01
+ * 61 82 01 61 A4 10 30 0E 31 0C 30 0A : 06 03 55 04 03 13 03 64 73 61 87 04
+ * 01 01 01 01 : 86 01 61 81 14 74 68 6F 6D 61 73 6B 40 6E 65 74 : 73 63 61
+ * 70 65 2E 63 6F 6D 88 03 29 01 01 : } 74 30 69: SEQUENCE { 76 06 3: OBJECT
+ * IDENTIFIER subjectAltName (2 5 29 17) 81 04 62: OCTET STRING : 30 3C 82
+ * 01 61 82 01 61 A4 10 30 0E 31 0C 30 0A : 06 03 55 04 03 13 03 64 73 61 87
+ * 04 01 01 01 01 : 86 01 61 81 14 74 68 6F 6D 61 73 6B 40 6E 65 74 : 73 63
+ * 61 70 65 2E 63 6F 6D 88 03 29 01 01 : } : } Uses the following to test
+ * with configuration wizard:
* MIGOMEUGA1UdEQQ+MDyCAWGCAWGkEDAOMQwwCgYDVQQDEwNkc2GHBAEBAQGGAWGB
* FHRob21hc2tAbmV0c2NhcGUuY29tiAMpAQEwRQYDVR0SBD4wPIIBYYIBYaQQMA4x
- * DDAKBgNVBAMTA2RzYYcEAQEBAYYBYYEUdGhvbWFza0BuZXRzY2FwZS5jb22IAykB
- * AQ==
+ * DDAKBgNVBAMTA2RzYYcEAQEBAYYBYYEUdGhvbWFza0BuZXRzY2FwZS5jb22IAykB AQ==
*/
public static void setDERExtension(
- CertificateExtensions ext, KeyCertData properties)
- throws IOException {
+ CertificateExtensions ext, KeyCertData properties)
+ throws IOException {
String b64E = properties.getDerExtension();
@@ -827,8 +812,8 @@ public class KeyCertUtil {
}
public static void setBasicConstraintsExtension(
- CertificateExtensions ext, KeyCertData properties)
- throws IOException {
+ CertificateExtensions ext, KeyCertData properties)
+ throws IOException {
String isCA = properties.isCA();
String certLen = properties.getCertLen();
@@ -844,12 +829,12 @@ public class KeyCertUtil {
else
len = Integer.parseInt(certLen);
- if ((isCA == null) || (isCA.equals("")) ||
- (isCA.equals(Constants.FALSE)))
+ if ((isCA == null) || (isCA.equals("")) ||
+ (isCA.equals(Constants.FALSE)))
bool = false;
else
bool = true;
-
+
BasicConstraintsExtension basic = new BasicConstraintsExtension(
bool, len);
@@ -857,17 +842,17 @@ public class KeyCertUtil {
}
public static void setExtendedKeyUsageExtension(
- CertificateExtensions ext, KeyCertData properties) throws IOException,
+ CertificateExtensions ext, KeyCertData properties) throws IOException,
CertificateException {
ExtendedKeyUsageExtension ns = new ExtendedKeyUsageExtension();
boolean anyExt = false;
-
+
String sslClient = properties.getSSLClientBit();
-
+
if ((sslClient != null) && (sslClient.equals(Constants.TRUE))) {
ns.addOID(new ObjectIdentifier("1.3.6.1.5.5.7.3.2"));
anyExt = true;
- }
+ }
String sslServer = properties.getSSLServerBit();
@@ -908,7 +893,7 @@ public class KeyCertUtil {
}
public static void setNetscapeCertificateExtension(
- CertificateExtensions ext, KeyCertData properties) throws IOException,
+ CertificateExtensions ext, KeyCertData properties) throws IOException,
CertificateException {
NSCertTypeExtension ns = new NSCertTypeExtension();
@@ -966,37 +951,37 @@ public class KeyCertUtil {
ext.set(NSCertTypeExtension.class.getSimpleName(), ns);
}
- public static void setOCSPNoCheck(KeyPair keypair,
- CertificateExtensions ext, KeyCertData properties) throws IOException,
+ public static void setOCSPNoCheck(KeyPair keypair,
+ CertificateExtensions ext, KeyCertData properties) throws IOException,
NoSuchAlgorithmException, InvalidKeyException {
String noCheck = properties.getOCSPNoCheck();
if ((noCheck != null) && (noCheck.equals(Constants.TRUE))) {
- OCSPNoCheckExtension noCheckExt =
- new OCSPNoCheckExtension();
+ OCSPNoCheckExtension noCheckExt =
+ new OCSPNoCheckExtension();
ext.set(OCSPNoCheckExtension.class.getSimpleName(), noCheckExt);
}
}
- public static void setOCSPSigning(KeyPair keypair,
- CertificateExtensions ext, KeyCertData properties) throws IOException,
+ public static void setOCSPSigning(KeyPair keypair,
+ CertificateExtensions ext, KeyCertData properties) throws IOException,
NoSuchAlgorithmException, InvalidKeyException {
String signing = properties.getOCSPSigning();
- if ((signing != null) && (signing.equals(Constants.TRUE))) {
- Vector<ObjectIdentifier> oidSet = new Vector<ObjectIdentifier>();
+ if ((signing != null) && (signing.equals(Constants.TRUE))) {
+ Vector<ObjectIdentifier> oidSet = new Vector<ObjectIdentifier>();
oidSet.addElement(
- ObjectIdentifier.getObjectIdentifier(
- ExtendedKeyUsageExtension.OID_OCSPSigning));
- ExtendedKeyUsageExtension ocspExt =
- new ExtendedKeyUsageExtension(false, oidSet);
+ ObjectIdentifier.getObjectIdentifier(
+ ExtendedKeyUsageExtension.OID_OCSPSigning));
+ ExtendedKeyUsageExtension ocspExt =
+ new ExtendedKeyUsageExtension(false, oidSet);
ext.set(ExtendedKeyUsageExtension.class.getSimpleName(), ocspExt);
}
}
- public static void setAuthInfoAccess(KeyPair keypair,
- CertificateExtensions ext, KeyCertData properties) throws IOException,
+ public static void setAuthInfoAccess(KeyPair keypair,
+ CertificateExtensions ext, KeyCertData properties) throws IOException,
NoSuchAlgorithmException, InvalidKeyException {
String aia = properties.getAIA();
@@ -1005,7 +990,7 @@ public class KeyCertUtil {
String port = CMS.getEENonSSLPort();
AuthInfoAccessExtension aiaExt = new AuthInfoAccessExtension(false);
if (hostname != null && port != null) {
- String location = "http://"+hostname+":"+port+"/ca/ocsp";
+ String location = "http://" + hostname + ":" + port + "/ca/ocsp";
GeneralName ocspName = new GeneralName(new URIName(location));
aiaExt.addAccessDescription(AuthInfoAccessExtension.METHOD_OCSP, ocspName);
}
@@ -1014,53 +999,53 @@ public class KeyCertUtil {
}
}
- public static void setAuthorityKeyIdentifier(KeyPair keypair,
- CertificateExtensions ext, KeyCertData properties) throws IOException,
+ public static void setAuthorityKeyIdentifier(KeyPair keypair,
+ CertificateExtensions ext, KeyCertData properties) throws IOException,
NoSuchAlgorithmException, InvalidKeyException {
String aki = properties.getAKI();
if ((aki != null) && (aki.equals(Constants.TRUE))) {
KeyIdentifier id = createKeyIdentifier(keypair);
- AuthorityKeyIdentifierExtension akiExt =
- new AuthorityKeyIdentifierExtension(id, null, null);
+ AuthorityKeyIdentifierExtension akiExt =
+ new AuthorityKeyIdentifierExtension(id, null, null);
ext.set(AuthorityKeyIdentifierExtension.class.getSimpleName(), akiExt);
}
}
- public static void setSubjectKeyIdentifier(KeyPair keypair,
- CertificateExtensions ext,
- KeyCertData properties) throws IOException, NoSuchAlgorithmException,
+ public static void setSubjectKeyIdentifier(KeyPair keypair,
+ CertificateExtensions ext,
+ KeyCertData properties) throws IOException, NoSuchAlgorithmException,
InvalidKeyException {
String ski = properties.getSKI();
if ((ski != null) && (ski.equals(Constants.TRUE))) {
KeyIdentifier id = createKeyIdentifier(keypair);
SubjectKeyIdentifierExtension skiExt =
- new SubjectKeyIdentifierExtension(id.getIdentifier());
+ new SubjectKeyIdentifierExtension(id.getIdentifier());
ext.set(SubjectKeyIdentifierExtension.class.getSimpleName(), skiExt);
}
}
public static void setKeyUsageExtension(CertificateExtensions ext,
- KeyUsageExtension keyUsage) throws IOException {
+ KeyUsageExtension keyUsage) throws IOException {
ext.set(KeyUsageExtension.class.getSimpleName(), keyUsage);
}
- public static KeyIdentifier createKeyIdentifier(KeyPair keypair)
- throws NoSuchAlgorithmException, InvalidKeyException {
+ public static KeyIdentifier createKeyIdentifier(KeyPair keypair)
+ throws NoSuchAlgorithmException, InvalidKeyException {
MessageDigest md = MessageDigest.getInstance("SHA-1");
X509Key subjectKeyInfo = convertPublicKeyToX509Key(
keypair.getPublic());
- //md.update(subjectKeyInfo.getEncoded());
+ // md.update(subjectKeyInfo.getEncoded());
md.update(subjectKeyInfo.getKey());
return new KeyIdentifier(md.digest());
}
- public static BigInteger getSerialNumber(LDAPConnection conn, String baseDN)
- throws LDAPException {
+ public static BigInteger getSerialNumber(LDAPConnection conn, String baseDN)
+ throws LDAPException {
String dn = "ou=certificateRepository,ou=ca," + baseDN;
BigInteger serialno = null;
LDAPEntry entry = conn.read(dn);
@@ -1080,9 +1065,9 @@ public class KeyCertUtil {
return serialno;
}
- public static void setSerialNumber(LDAPConnection conn,
- String baseDN, BigInteger serial)
- throws LDAPException {
+ public static void setSerialNumber(LDAPConnection conn,
+ String baseDN, BigInteger serial)
+ throws LDAPException {
String dn = "ou=certificateRepository,ou=ca," + baseDN;
LDAPAttribute attr = new LDAPAttribute("serialno");
@@ -1097,19 +1082,19 @@ public class KeyCertUtil {
}
public static void addCertToDB(LDAPConnection conn, String dn, X509CertImpl cert)
- throws LDAPException, EBaseException {
+ throws LDAPException, EBaseException {
BigInteger serialno = cert.getSerialNumber();
X509CertImplMapper mapper = new X509CertImplMapper();
LDAPAttributeSet attrs = new LDAPAttributeSet();
mapper.mapObjectToLDAPAttributeSet(null, null,
- cert, attrs);
+ cert, attrs);
attrs.add(new LDAPAttribute("objectclass", "top"));
attrs.add(new LDAPAttribute("objectclass",
"certificateRecord"));
attrs.add(new LDAPAttribute("serialno",
BigIntegerMapper.BigIntegerToDB(
- serialno)));
+ serialno)));
attrs.add(new LDAPAttribute("dateOfCreate",
DateMapper.dateToDB((CMS.getCurrentDate()))));
attrs.add(new LDAPAttribute("dateOfModify",
@@ -1125,12 +1110,12 @@ public class KeyCertUtil {
conn.add(entry);
}
- public static CertificateExtensions getExtensions(String tokenname, String nickname)
- throws NotInitializedException, TokenException, ObjectNotFoundException,
+ public static CertificateExtensions getExtensions(String tokenname, String nickname)
+ throws NotInitializedException, TokenException, ObjectNotFoundException,
IOException, CertificateException {
String fullnickname = nickname;
- if (!tokenname.equals(Constants.PR_INTERNAL_TOKEN_NAME))
+ if (!tokenname.equals(Constants.PR_INTERNAL_TOKEN_NAME))
fullnickname = tokenname + ":" + nickname;
CryptoManager manager = CryptoManager.getInstance();
X509Certificate cert = manager.findCertByNickname(fullnickname);
diff --git a/pki/base/common/src/com/netscape/cmscore/security/OCSPSigningCert.java b/pki/base/common/src/com/netscape/cmscore/security/OCSPSigningCert.java
index efeade92..7e77b201 100644
--- a/pki/base/common/src/com/netscape/cmscore/security/OCSPSigningCert.java
+++ b/pki/base/common/src/com/netscape/cmscore/security/OCSPSigningCert.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.security;
-
import java.io.IOException;
import java.math.BigInteger;
import java.security.KeyPair;
@@ -34,7 +33,6 @@ import com.netscape.certsrv.common.ConfigConstants;
import com.netscape.certsrv.common.Constants;
import com.netscape.certsrv.security.KeyCertData;
-
/**
* OCSP signing certificate.
*
@@ -42,8 +40,8 @@ import com.netscape.certsrv.security.KeyCertData;
* @version $Revision$, $Date$
*/
public class OCSPSigningCert extends CertificateInfo {
- public static final String SUBJECT_NAME =
- "CN=Certificate Authority, O=Netscape Communications, C=US";
+ public static final String SUBJECT_NAME =
+ "CN=Certificate Authority, O=Netscape Communications, C=US";
public OCSPSigningCert(KeyCertData properties) {
this(properties, null);
@@ -51,19 +49,16 @@ public class OCSPSigningCert extends CertificateInfo {
public OCSPSigningCert(KeyCertData properties, KeyPair pair) {
super(properties, pair);
- /* included in console UI
- try {
- if (mProperties.get(Constants.PR_OCSP_SIGNING) == null) {
- mProperties.put(Constants.PR_OCSP_SIGNING, Constants.TRUE);
- }
- if (mProperties.get(Constants.PR_OCSP_NOCHECK) == null) {
- mProperties.put(Constants.PR_OCSP_NOCHECK, Constants.TRUE);
- }
- } catch (Exception e) {
- mProperties.put(Constants.PR_OCSP_SIGNING, Constants.TRUE);
- mProperties.put(Constants.PR_OCSP_NOCHECK, Constants.TRUE);
- }
- */
+ /*
+ * included in console UI try { if
+ * (mProperties.get(Constants.PR_OCSP_SIGNING) == null) {
+ * mProperties.put(Constants.PR_OCSP_SIGNING, Constants.TRUE); } if
+ * (mProperties.get(Constants.PR_OCSP_NOCHECK) == null) {
+ * mProperties.put(Constants.PR_OCSP_NOCHECK, Constants.TRUE); } } catch
+ * (Exception e) { mProperties.put(Constants.PR_OCSP_SIGNING,
+ * Constants.TRUE); mProperties.put(Constants.PR_OCSP_NOCHECK,
+ * Constants.TRUE); }
+ */
}
public String getSubjectName() {
@@ -85,7 +80,7 @@ public class OCSPSigningCert extends CertificateInfo {
BigInteger P = new BigInteger(p);
BigInteger Q = new BigInteger(q);
BigInteger G = new BigInteger(g);
- BigInteger pqgSeed = new BigInteger(seed);
+ BigInteger pqgSeed = new BigInteger(seed);
BigInteger pqgH = new BigInteger(H);
return new PQGParams(P, Q, G, pqgSeed, counter, pqgH);
@@ -113,7 +108,7 @@ public class OCSPSigningCert extends CertificateInfo {
cmsFileTmp.putString("ca.signing.cacertnickname", nickname);
else
cmsFileTmp.putString("ca.signing.cacertnickname",
- tokenname + ":" + nickname);
+ tokenname + ":" + nickname);
cmsFileTmp.commit(false);
}
@@ -140,4 +135,3 @@ public class OCSPSigningCert extends CertificateInfo {
return extension;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/security/PWCBsdr.java b/pki/base/common/src/com/netscape/cmscore/security/PWCBsdr.java
index 48b19f62..99f8d1e4 100644
--- a/pki/base/common/src/com/netscape/cmscore/security/PWCBsdr.java
+++ b/pki/base/common/src/com/netscape/cmscore/security/PWCBsdr.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.security;
-
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
@@ -30,7 +29,6 @@ import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.cmscore.base.JDialogPasswordCallback;
-
/*
* A class to retrieve passwords from the SDR password cache
*
@@ -41,7 +39,7 @@ import com.netscape.cmscore.base.JDialogPasswordCallback;
public class PWCBsdr implements PasswordCallback {
InputStream in = null;
OutputStream out = null;
- String mprompt = "";
+ String mprompt = "";
boolean firsttime = true;
private PasswordCallback mCB = null;
private String mPWcachedb = null;
@@ -50,29 +48,28 @@ public class PWCBsdr implements PasswordCallback {
public PWCBsdr() {
this(null);
}
-
+
public PWCBsdr(String prompt) {
in = System.in;
out = System.out;
mprompt = prompt;
- /* to get the test program work
- System.out.println("before CMS.getLogger");
- try {
+ /*
+ * to get the test program work
+ * System.out.println("before CMS.getLogger"); try {
*/
mLogger = CMS.getLogger();
/*
- } catch (NullPointerException e) {
- System.out.println("after CMS.getLoggergot NullPointerException ... testing ok");
- }
- System.out.println("after CMS.getLogger");
+ * } catch (NullPointerException e) { System.out.println(
+ * "after CMS.getLoggergot NullPointerException ... testing ok"); }
+ * System.out.println("after CMS.getLogger");
*/
// get path to password cache
try {
mPWcachedb = CMS.getConfigStore().getString("pwCache");
CMS.debug("got pwCache from configstore: " +
- mPWcachedb);
+ mPWcachedb);
} catch (NullPointerException e) {
System.out.println("after CMS.getConfigStore got NullPointerException ... testing ok");
} catch (Exception e) {
@@ -80,8 +77,8 @@ public class PWCBsdr implements PasswordCallback {
// let it fall through
}
- // System.out.println("after CMS.getConfigStore");
- if (File.separator.equals("/")) {
+ // System.out.println("after CMS.getConfigStore");
+ if (File.separator.equals("/")) {
// Unix
mCB = new PWsdrConsolePasswordCallback(prompt);
} else {
@@ -90,33 +87,27 @@ public class PWCBsdr implements PasswordCallback {
}
// System.out.println( "Created PWCBsdr with prompt of "
- // + mprompt );
+ // + mprompt );
}
- /* We are now assuming that PasswordCallbackInfo.getname() returns
- * the tag we are hoping to match in the cache.
+ /*
+ * We are now assuming that PasswordCallbackInfo.getname() returns the tag
+ * we are hoping to match in the cache.
*/
public Password getPasswordFirstAttempt(PasswordCallbackInfo info)
- throws PasswordCallback.GiveUpException {
+ throws PasswordCallback.GiveUpException {
CMS.debug("in getPasswordFirstAttempt");
- /* debugging code to see if token is logged in
- try {
- CryptoManager cm = CryptoManager.getInstance();
- CryptoToken token =
- cm.getInternalKeyStorageToken();
- if (token.isLoggedIn() == false) {
- // missed it.
- CMS.debug("token not yet logged in!!");
- } else {
- CMS.debug("token logged in.");
- }
- } catch (Exception e) {
- CMS.debug("crypto manager error:"+e.toString());
- }
- CMS.debug("still in getPasswordFirstAttempt");
+ /*
+ * debugging code to see if token is logged in try { CryptoManager cm =
+ * CryptoManager.getInstance(); CryptoToken token =
+ * cm.getInternalKeyStorageToken(); if (token.isLoggedIn() == false) {
+ * // missed it. CMS.debug("token not yet logged in!!"); } else {
+ * CMS.debug("token logged in."); } } catch (Exception e) {
+ * CMS.debug("crypto manager error:"+e.toString()); }
+ * CMS.debug("still in getPasswordFirstAttempt");
*/
Password pw = null;
String tmpPrompt = info.getName();
@@ -144,7 +135,7 @@ public class PWCBsdr implements PasswordCallback {
if (tmpPrompt == null) { /* no name, fail */
System.out.println("Shouldn't get here");
throw new PasswordCallback.GiveUpException();
- } else { /* get password from password cache */
+ } else { /* get password from password cache */
CMS.debug("getting tag = " + tmpPrompt);
PWsdrCache pwc = new PWsdrCache(mPWcachedb, mLogger);
@@ -157,7 +148,7 @@ public class PWCBsdr implements PasswordCallback {
return (pw);
} else { /* password not found */
- // we don't want caller to do getPasswordAgain, for now
+ // we don't want caller to do getPasswordAgain, for now
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_THROW_CALLBACK"));
throw new PasswordCallback.GiveUpException();
}
@@ -169,12 +160,13 @@ public class PWCBsdr implements PasswordCallback {
}
}
- /* The password cache has failed to return a password (or a usable password.
- * Now we will try and get the password from the user and hopefully add
- * the password to the cache pw cache
+ /*
+ * The password cache has failed to return a password (or a usable password.
+ * Now we will try and get the password from the user and hopefully add the
+ * password to the cache pw cache
*/
public Password getPasswordAgain(PasswordCallbackInfo info)
- throws PasswordCallback.GiveUpException {
+ throws PasswordCallback.GiveUpException {
CMS.debug("in getPasswordAgain");
try {
@@ -198,7 +190,7 @@ public class PWCBsdr implements PasswordCallback {
}
} catch (Throwable e) {
// System.out.println( "BUG HERE!! in the password again!!"
- // + "!!!!!!!!!!!" );
+ // + "!!!!!!!!!!!" );
// e.printStackTrace();
throw new PasswordCallback.GiveUpException();
}
@@ -208,12 +200,11 @@ public class PWCBsdr implements PasswordCallback {
if (mLogger == null) {
System.out.println(msg);
} else {
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, level, "PWCBsdr " + msg);
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, level, "PWCBsdr " + msg);
}
}
}
-
class PWsdrConsolePasswordCallback implements PasswordCallback {
private String mPrompt = null;
@@ -226,7 +217,7 @@ class PWsdrConsolePasswordCallback implements PasswordCallback {
}
public Password getPasswordFirstAttempt(PasswordCallbackInfo info)
- throws PasswordCallback.GiveUpException {
+ throws PasswordCallback.GiveUpException {
if (mPrompt == null) {
System.out.println("Get password " + info.getName());
} else {
@@ -239,7 +230,7 @@ class PWsdrConsolePasswordCallback implements PasswordCallback {
}
public Password getPasswordAgain(PasswordCallbackInfo info)
- throws PasswordCallback.GiveUpException {
+ throws PasswordCallback.GiveUpException {
System.out.println("Password Incorrect.");
if (mPrompt == null) {
System.out.println("Get password " + info.getName());
@@ -253,7 +244,6 @@ class PWsdrConsolePasswordCallback implements PasswordCallback {
}
}
-
class PWsdrDialogPasswordCallback extends JDialogPasswordCallback {
private String mPrompt = null;
@@ -270,4 +260,3 @@ class PWsdrDialogPasswordCallback extends JDialogPasswordCallback {
}
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/security/PWUtil.java b/pki/base/common/src/com/netscape/cmscore/security/PWUtil.java
index 3be63691..b8d9d149 100644
--- a/pki/base/common/src/com/netscape/cmscore/security/PWUtil.java
+++ b/pki/base/common/src/com/netscape/cmscore/security/PWUtil.java
@@ -17,23 +17,20 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.security;
-
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.mozilla.jss.util.Password;
import org.mozilla.jss.util.PasswordCallback;
-
-public class
-PWUtil {
+public class PWUtil {
public static Password
- readPasswordFromStream()
- throws PasswordCallback.GiveUpException {
+ readPasswordFromStream()
+ throws PasswordCallback.GiveUpException {
BufferedReader in;
in = new BufferedReader(new InputStreamReader(System.in));
-
+
StringBuffer buf = new StringBuffer();
String passwordString = new String();
int c;
@@ -49,7 +46,7 @@ PWUtil {
if (ch != '\r') {
if (ch != '\n') {
buf.append(ch);
- } else {
+ } else {
passwordString = buf.toString();
buf.setLength(0);
break;
@@ -61,10 +58,10 @@ PWUtil {
}
// memory problem?
- // String passwordString = in.readLine();
- // System.out.println( "done read" );
- // System.out.println( " password recieved is ["
- // + passwordString + "]" );
+ // String passwordString = in.readLine();
+ // System.out.println( "done read" );
+ // System.out.println( " password recieved is ["
+ // + passwordString + "]" );
if (passwordString == null) {
throw new PasswordCallback.GiveUpException();
}
@@ -80,4 +77,3 @@ PWUtil {
}
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/security/PWsdrCache.java b/pki/base/common/src/com/netscape/cmscore/security/PWsdrCache.java
index 12412f59..1deb64e0 100644
--- a/pki/base/common/src/com/netscape/cmscore/security/PWsdrCache.java
+++ b/pki/base/common/src/com/netscape/cmscore/security/PWsdrCache.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.security;
-
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
@@ -46,7 +45,6 @@ import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.cmsutil.util.Utils;
-
/*
* A class for managing passwords in the SDR password cache
*
@@ -86,13 +84,13 @@ public class PWsdrCache {
try {
cm = CryptoManager.getInstance();
mTokenName = CMS.getConfigStore().getString(PROP_PWC_TOKEN_NAME);
- log (ILogger.LL_DEBUG, "pwcTokenname specified. Use token for SDR key. tokenname= "+mTokenName);
+ log(ILogger.LL_DEBUG, "pwcTokenname specified. Use token for SDR key. tokenname= " + mTokenName);
mToken = cm.getTokenByName(mTokenName);
} catch (NotInitializedException e) {
- log (ILogger.LL_FAILURE, e.toString());
+ log(ILogger.LL_FAILURE, e.toString());
throw new EBaseException(e.toString());
} catch (Exception e) {
- log (ILogger.LL_DEBUG, "no pwcTokenname specified, use internal token for SDR key");
+ log(ILogger.LL_DEBUG, "no pwcTokenname specified, use internal token for SDR key");
mToken = cm.getInternalKeyStorageToken();
}
}
@@ -103,11 +101,11 @@ public class PWsdrCache {
if (mKeyID == null) {
try {
String keyID = CMS.getConfigStore().getString(PROP_PWC_KEY_ID);
- log (ILogger.LL_DEBUG, "retrieved PWC SDR key");
+ log(ILogger.LL_DEBUG, "retrieved PWC SDR key");
mKeyID = base64Decode(keyID);
-
+
} catch (Exception e) {
- log (ILogger.LL_DEBUG, "no pwcSDRKey specified");
+ log(ILogger.LL_DEBUG, "no pwcSDRKey specified");
throw new EBaseException(e.toString());
}
}
@@ -131,10 +129,10 @@ public class PWsdrCache {
cm = CryptoManager.getInstance();
if (mTokenName != null) {
mToken = cm.getTokenByName(mTokenName);
- mToken = cm.getInternalKeyStorageToken();
- debug("PWsdrCache: mToken = "+mTokenName);
+ mToken = cm.getInternalKeyStorageToken();
+ debug("PWsdrCache: mToken = " + mTokenName);
} else {
- mToken = cm.getInternalKeyStorageToken();
+ mToken = cm.getInternalKeyStorageToken();
debug("PWsdrCache: mToken = internal");
}
}
@@ -147,50 +145,48 @@ public class PWsdrCache {
return mTokenName;
}
- public void deleteUniqueNamedKey( String nickName )
- throws Exception
- {
- KeyManager km = new KeyManager( mToken );
- km.deleteUniqueNamedKey( nickName );
+ public void deleteUniqueNamedKey(String nickName)
+ throws Exception {
+ KeyManager km = new KeyManager(mToken);
+ km.deleteUniqueNamedKey(nickName);
}
- public byte[] generateSDRKey () throws Exception {
- return generateSDRKeyWithNickName(PROP_PWC_NICKNAME);
+ public byte[] generateSDRKey() throws Exception {
+ return generateSDRKeyWithNickName(PROP_PWC_NICKNAME);
}
- public byte[] generateSDRKeyWithNickName (String nickName)
- throws Exception
- {
+ public byte[] generateSDRKeyWithNickName(String nickName)
+ throws Exception {
try {
if (mIsTool != true) {
// generate SDR key
KeyManager km = new KeyManager(mToken);
try {
- // Bugscape Bug #54838: Due to the CMS cloning feature,
- // we must check for the presence of
- // a uniquely named symmetric key
- // prior to making an attempt to
- // generate it!
+ // Bugscape Bug #54838: Due to the CMS cloning feature,
+ // we must check for the presence of
+ // a uniquely named symmetric key
+ // prior to making an attempt to
+ // generate it!
//
- if( !( km.uniqueNamedKeyExists( nickName ) ) ) {
- mKeyID = km.generateUniqueNamedKey( nickName );
+ if (!(km.uniqueNamedKeyExists(nickName))) {
+ mKeyID = km.generateUniqueNamedKey(nickName);
}
} catch (TokenException e) {
- log (0, "generateSDRKey() failed on "+e.toString());
+ log(0, "generateSDRKey() failed on " + e.toString());
throw e;
}
}
} catch (Exception e) {
- log (ILogger.LL_FAILURE, e.toString());
+ log(ILogger.LL_FAILURE, e.toString());
throw e;
}
return mKeyID;
}
public byte[] base64Decode(String s) throws IOException {
- byte[] d = com.netscape.osutil.OSUtil.AtoB(s);
- return d;
+ byte[] d = com.netscape.osutil.OSUtil.AtoB(s);
+ return d;
}
public static String base64Encode(byte[] bytes) throws IOException {
@@ -199,9 +195,9 @@ public class PWsdrCache {
ByteArrayOutputStream output = new ByteArrayOutputStream();
Base64OutputStream b64 = new Base64OutputStream(new
PrintStream(new
- FilterOutputStream(output)
+ FilterOutputStream(output)
)
- );
+ );
b64.write(bytes);
b64.flush();
@@ -211,10 +207,9 @@ public class PWsdrCache {
return output.toString("8859_1");
}
-
// for PWCBsdr
public PWsdrCache(String pwCache, ILogger logger) throws
- EBaseException {
+ EBaseException {
mLogger = logger;
mPWcachedb = pwCache;
initToken();
@@ -236,7 +231,7 @@ public class PWsdrCache {
* add passwd in pwcache.
*/
public void addEntry(String tag, String pwd, Hashtable tagPwds) throws EBaseException {
-
+
String stringToAdd = null;
String bufs = null;
@@ -249,7 +244,7 @@ public class PWsdrCache {
tag = (String) enum1.nextElement();
pwd = (String) tagPwds.get(tag);
debug("password tag: " + tag + " stored in " + mPWcachedb);
-
+
if (stringToAdd == null) {
stringToAdd = tag + ":" + pwd + "\n";
} else {
@@ -262,7 +257,7 @@ public class PWsdrCache {
if (dcrypts != null) {
// converts to Hashtable, replace if tag exists, add
- // if tag doesn't exist
+ // if tag doesn't exist
Hashtable ht = string2Hashtable(dcrypts);
if (ht.containsKey(tag) == false) {
@@ -277,7 +272,7 @@ public class PWsdrCache {
debug("adding new tag: " + tag);
bufs = stringToAdd;
}
-
+
// write update to cache
writePWcache(bufs);
}
@@ -292,7 +287,7 @@ public class PWsdrCache {
if (dcrypts != null) {
// converts to Hashtable, replace if tag exists, add
- // if tag doesn't exist
+ // if tag doesn't exist
Hashtable ht = string2Hashtable(dcrypts);
if (ht.containsKey(tag) == false) {
@@ -307,7 +302,7 @@ public class PWsdrCache {
debug("password cache contains no tags");
return;
}
-
+
// write update to cache
writePWcache(bufs);
}
@@ -394,35 +389,35 @@ public class PWsdrCache {
File origFile = new File(mPWcachedb);
try {
- if( Utils.isNT() ) {
+ if (Utils.isNT()) {
// NT is very picky on the path
- Utils.exec( "copy " +
- tmpPWcache.getAbsolutePath().replace( '/',
- '\\' ) +
+ Utils.exec("copy " +
+ tmpPWcache.getAbsolutePath().replace('/',
+ '\\') +
" " +
- origFile.getAbsolutePath().replace( '/',
- '\\' ) );
+ origFile.getAbsolutePath().replace('/',
+ '\\'));
} else {
// Create a copy of the original file which
// preserves the original file permissions.
- Utils.exec( "cp -p " + tmpPWcache.getAbsolutePath() + " " +
- origFile.getAbsolutePath() );
+ Utils.exec("cp -p " + tmpPWcache.getAbsolutePath() + " " +
+ origFile.getAbsolutePath());
}
// Remove the original file if and only if
// the backup copy was successful.
- if( origFile.exists() ) {
- if( !Utils.isNT() ) {
+ if (origFile.exists()) {
+ if (!Utils.isNT()) {
try {
- Utils.exec( "chmod 00660 " +
- origFile.getCanonicalPath() );
- } catch( IOException e ) {
- CMS.debug( "Unable to change file permissions on "
- + origFile.toString() );
+ Utils.exec("chmod 00660 " +
+ origFile.getCanonicalPath());
+ } catch (IOException e) {
+ CMS.debug("Unable to change file permissions on "
+ + origFile.toString());
}
}
tmpPWcache.delete();
- debug( "operation completed for " + mPWcachedb );
+ debug("operation completed for " + mPWcachedb);
}
} catch (Exception exx) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_PW_CACHE", exx.toString()));
@@ -447,7 +442,7 @@ public class PWsdrCache {
while (enum1.hasMoreElements()) {
String tag = (String) enum1.nextElement();
String pwd = (String) ht.get(tag);
-
+
if (returnString == null) {
returnString = tag + ":" + pwd + "\n";
} else {
@@ -475,14 +470,14 @@ public class PWsdrCache {
ht.put(tag.trim(), passwd.trim());
} else {
- //invalid format...log or throw...later
+ // invalid format...log or throw...later
}
}
return ht;
}
/*
- * get password from cache. This one supplies cache file name
+ * get password from cache. This one supplies cache file name
*/
public Password getEntry(String fileName, String tag) {
mPWcachedb = fileName;
@@ -490,8 +485,8 @@ public class PWsdrCache {
}
/*
- * if tag found with pwd, return it
- * if tag not found, return null, which will cause it to give up
+ * if tag found with pwd, return it if tag not found, return null, which
+ * will cause it to give up
*/
public Password getEntry(String tag) {
Hashtable pwTable = null;
@@ -532,7 +527,7 @@ public class PWsdrCache {
}
}
- //copied from IOUtil.java
+ // copied from IOUtil.java
/**
* Checks if this is NT.
*/
@@ -566,22 +561,17 @@ public class PWsdrCache {
if (process.exitValue() == 0) {
/**
- pOut = new BufferedReader(
- new InputStreamReader(process.getInputStream()));
- while ((l = pOut.readLine()) != null) {
- System.out.println(l);
- }
+ * pOut = new BufferedReader( new
+ * InputStreamReader(process.getInputStream())); while ((l =
+ * pOut.readLine()) != null) { System.out.println(l); }
**/
return true;
} else {
/**
- pOut = new BufferedReader(
- new InputStreamReader(process.getErrorStream()));
- l = null;
- while ((l = pOut.readLine()) != null) {
- System.out.println(l);
- }
+ * pOut = new BufferedReader( new
+ * InputStreamReader(process.getErrorStream())); l = null; while
+ * ((l = pOut.readLine()) != null) { System.out.println(l); }
**/
return false;
}
@@ -599,7 +589,7 @@ public class PWsdrCache {
public void log(int level, String msg) {
if (mLogger != null) {
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, level,
- "PWsdrCache " + msg);
+ "PWsdrCache " + msg);
} else if (mIsTool) {
System.out.println(msg);
} // else it's most likely the installation wizard...no logging
@@ -636,9 +626,9 @@ public class PWsdrCache {
line.length());
debug(tag.trim() +
- " : " + passwd.trim());
+ " : " + passwd.trim());
} else {
- //invalid format...log or throw...later
+ // invalid format...log or throw...later
debug("invalid format");
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/security/Provider.java b/pki/base/common/src/com/netscape/cmscore/security/Provider.java
index 0e7f8e2e..8c264142 100644
--- a/pki/base/common/src/com/netscape/cmscore/security/Provider.java
+++ b/pki/base/common/src/com/netscape/cmscore/security/Provider.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.security;
-
public class Provider extends java.security.Provider {
/**
@@ -27,11 +26,11 @@ public class Provider extends java.security.Provider {
public Provider() {
super("CMS", 1.4,
- "Provides Signature and Message Digesting");
+ "Provides Signature and Message Digesting");
- /////////////////////////////////////////////////////////////
+ // ///////////////////////////////////////////////////////////
// Signature
- /////////////////////////////////////////////////////////////
+ // ///////////////////////////////////////////////////////////
put("Signature.SHA1withDSA", "org.mozilla.jss.provider.DSASignature");
@@ -46,13 +45,13 @@ public class Provider extends java.security.Provider {
put("Signature.MD5/RSA", "org.mozilla.jss.provider.MD5RSASignature");
put("Signature.MD2/RSA", "org.mozilla.jss.provider.MD2RSASignature");
put("Signature.SHA-1/RSA",
- "org.mozilla.jss.provider.SHA1RSASignature");
+ "org.mozilla.jss.provider.SHA1RSASignature");
put("Alg.Alias.Signature.SHA1/RSA", "SHA-1/RSA");
- /////////////////////////////////////////////////////////////
+ // ///////////////////////////////////////////////////////////
// Message Digesting
- /////////////////////////////////////////////////////////////
+ // ///////////////////////////////////////////////////////////
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/security/RASigningCert.java b/pki/base/common/src/com/netscape/cmscore/security/RASigningCert.java
index 1ac8f0ea..bf7a4ef2 100644
--- a/pki/base/common/src/com/netscape/cmscore/security/RASigningCert.java
+++ b/pki/base/common/src/com/netscape/cmscore/security/RASigningCert.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.security;
-
import java.io.IOException;
import java.security.KeyPair;
@@ -29,16 +28,15 @@ import com.netscape.certsrv.common.ConfigConstants;
import com.netscape.certsrv.common.Constants;
import com.netscape.certsrv.security.KeyCertData;
-
/**
- * RA signing certificate
+ * RA signing certificate
*
* @author Christine Ho
* @version $Revision$, $Date$
*/
public class RASigningCert extends CertificateInfo {
- public static final String SUBJECT_NAME =
- "CN=Registration Authority, O=Netscape Communications, C=US";
+ public static final String SUBJECT_NAME =
+ "CN=Registration Authority, O=Netscape Communications, C=US";
private String mTokenname = Constants.PR_INTERNAL_TOKEN_NAME;
public RASigningCert(KeyCertData properties) {
@@ -49,8 +47,8 @@ public class RASigningCert extends CertificateInfo {
super(properties, pair);
String tmp = (String) mProperties.get(Constants.PR_TOKEN_NAME);
- if ((tmp != null) &&
- (!tmp.equals(Constants.PR_INTERNAL_TOKEN)))
+ if ((tmp != null) &&
+ (!tmp.equals(Constants.PR_INTERNAL_TOKEN)))
mTokenname = tmp;
try {
if (mProperties.get(Constants.PR_AKI) == null) {
@@ -79,7 +77,7 @@ public class RASigningCert extends CertificateInfo {
public String getNickname() {
String name = (String) mProperties.get(Constants.PR_NICKNAME);
String instanceName =
- (String) mProperties.get(ConfigConstants.PR_CERT_INSTANCE_NAME);
+ (String) mProperties.get(ConfigConstants.PR_CERT_INSTANCE_NAME);
if (name != null)
return name;
@@ -87,19 +85,14 @@ public class RASigningCert extends CertificateInfo {
}
/*
- public SignatureAlgorithm getSigningAlgorithm() {
- SignatureAlgorithm sAlg =
- (SignatureAlgorithm)mProperties.get(Constants.PR_SIGNATURE_ALGORITHM);
- if (sAlg != null) {
- return sAlg;
- }
- String alg = (String)mProperties.get(Constants.PR_KEY_TYPE);
-
- if (alg.equals("RSA"))
- return SignatureAlgorithm.RSASignatureWithMD5Digest;
- else
- return SignatureAlgorithm.DSASignatureWithSHA1Digest;
- }
+ * public SignatureAlgorithm getSigningAlgorithm() { SignatureAlgorithm sAlg
+ * = (SignatureAlgorithm)mProperties.get(Constants.PR_SIGNATURE_ALGORITHM);
+ * if (sAlg != null) { return sAlg; } String alg =
+ * (String)mProperties.get(Constants.PR_KEY_TYPE);
+ *
+ * if (alg.equals("RSA")) return
+ * SignatureAlgorithm.RSASignatureWithMD5Digest; else return
+ * SignatureAlgorithm.DSASignatureWithSHA1Digest; }
*/
public String getKeyAlgorithm() {
@@ -113,4 +106,3 @@ public class RASigningCert extends CertificateInfo {
return extension;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/security/SSLCert.java b/pki/base/common/src/com/netscape/cmscore/security/SSLCert.java
index eab48bdf..e978851d 100644
--- a/pki/base/common/src/com/netscape/cmscore/security/SSLCert.java
+++ b/pki/base/common/src/com/netscape/cmscore/security/SSLCert.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.security;
-
import java.io.IOException;
import java.security.KeyPair;
@@ -29,16 +28,15 @@ import com.netscape.certsrv.common.ConfigConstants;
import com.netscape.certsrv.common.Constants;
import com.netscape.certsrv.security.KeyCertData;
-
/**
- * SSL server certificate
+ * SSL server certificate
*
* @author Christine Ho
* @version $Revision$, $Date$
*/
public class SSLCert extends CertificateInfo {
- public static final String SUBJECT_NAME =
- "CN=SSL, O=Netscape Communications, C=US";
+ public static final String SUBJECT_NAME =
+ "CN=SSL, O=Netscape Communications, C=US";
private String mTokenname = Constants.PR_INTERNAL_TOKEN_NAME;
public SSLCert(KeyCertData properties) {
@@ -49,8 +47,8 @@ public class SSLCert extends CertificateInfo {
super(properties, pair);
String tmp = (String) mProperties.get(Constants.PR_TOKEN_NAME);
- if ((tmp != null) &&
- (!tmp.equals(Constants.PR_INTERNAL_TOKEN)))
+ if ((tmp != null) &&
+ (!tmp.equals(Constants.PR_INTERNAL_TOKEN)))
mTokenname = tmp;
try {
if (mProperties.get(Constants.PR_AKI) == null) {
@@ -62,7 +60,7 @@ public class SSLCert extends CertificateInfo {
// 020598: The server bit has to be turned on. Otherwise, it might
// crash jss.
- //mProperties.put(Constants.PR_SSL_SERVER_BIT, Constants.TRUE);
+ // mProperties.put(Constants.PR_SSL_SERVER_BIT, Constants.TRUE);
}
public void updateConfig(IConfigStore cmsFileTmp) throws EBaseException {
@@ -88,7 +86,7 @@ public class SSLCert extends CertificateInfo {
public String getNickname() {
String name = (String) mProperties.get(Constants.PR_NICKNAME);
String instanceName =
- (String) mProperties.get(ConfigConstants.PR_CERT_INSTANCE_NAME);
+ (String) mProperties.get(ConfigConstants.PR_CERT_INSTANCE_NAME);
if (name != null)
return name;
@@ -96,19 +94,14 @@ public class SSLCert extends CertificateInfo {
}
/*
- public SignatureAlgorithm getSigningAlgorithm() {
- SignatureAlgorithm sAlg =
- (SignatureAlgorithm)mProperties.get(Constants.PR_SIGNATURE_ALGORITHM);
- if (sAlg != null) {
- return sAlg;
- }
- String alg = (String)mProperties.get(Constants.PR_KEY_TYPE);
-
- if (alg.equals("RSA"))
- return SignatureAlgorithm.RSASignatureWithMD5Digest;
- else
- return SignatureAlgorithm.DSASignatureWithSHA1Digest;
- }
+ * public SignatureAlgorithm getSigningAlgorithm() { SignatureAlgorithm sAlg
+ * = (SignatureAlgorithm)mProperties.get(Constants.PR_SIGNATURE_ALGORITHM);
+ * if (sAlg != null) { return sAlg; } String alg =
+ * (String)mProperties.get(Constants.PR_KEY_TYPE);
+ *
+ * if (alg.equals("RSA")) return
+ * SignatureAlgorithm.RSASignatureWithMD5Digest; else return
+ * SignatureAlgorithm.DSASignatureWithSHA1Digest; }
*/
public String getKeyAlgorithm() {
@@ -125,4 +118,3 @@ public class SSLCert extends CertificateInfo {
return extension;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/security/SSLSelfSignedCert.java b/pki/base/common/src/com/netscape/cmscore/security/SSLSelfSignedCert.java
index ac7eb2ad..8494baf0 100644
--- a/pki/base/common/src/com/netscape/cmscore/security/SSLSelfSignedCert.java
+++ b/pki/base/common/src/com/netscape/cmscore/security/SSLSelfSignedCert.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.security;
-
import java.io.IOException;
import java.security.KeyPair;
@@ -29,16 +28,15 @@ import com.netscape.certsrv.common.ConfigConstants;
import com.netscape.certsrv.common.Constants;
import com.netscape.certsrv.security.KeyCertData;
-
/**
- * SSL server certificate
+ * SSL server certificate
*
* @author Christine Ho
* @version $Revision$, $Date$
*/
public class SSLSelfSignedCert extends CertificateInfo {
- public static final String SUBJECT_NAME =
- "CN=SSL, O=Netscape Communications, C=US";
+ public static final String SUBJECT_NAME =
+ "CN=SSL, O=Netscape Communications, C=US";
private String mTokenname = Constants.PR_INTERNAL_TOKEN_NAME;
public SSLSelfSignedCert(KeyCertData properties) {
@@ -49,8 +47,8 @@ public class SSLSelfSignedCert extends CertificateInfo {
super(properties, pair);
String tmp = (String) mProperties.get(Constants.PR_TOKEN_NAME);
- if ((tmp != null) &&
- (!tmp.equals(Constants.PR_INTERNAL_TOKEN)))
+ if ((tmp != null) &&
+ (!tmp.equals(Constants.PR_INTERNAL_TOKEN)))
mTokenname = tmp;
mProperties.remove(Constants.PR_AKI);
@@ -80,7 +78,7 @@ public class SSLSelfSignedCert extends CertificateInfo {
public String getNickname() {
String name = (String) mProperties.get(Constants.PR_NICKNAME);
String instanceName =
- (String) mProperties.get(ConfigConstants.PR_CERT_INSTANCE_NAME);
+ (String) mProperties.get(ConfigConstants.PR_CERT_INSTANCE_NAME);
if (name != null)
return name;
@@ -88,19 +86,14 @@ public class SSLSelfSignedCert extends CertificateInfo {
}
/*
- public SignatureAlgorithm getSigningAlgorithm() {
- SignatureAlgorithm sAlg =
- (SignatureAlgorithm)mProperties.get(Constants.PR_SIGNATURE_ALGORITHM);
- if (sAlg != null) {
- return sAlg;
- }
- String alg = (String)mProperties.get(Constants.PR_KEY_TYPE);
-
- if (alg.equals("RSA"))
- return SignatureAlgorithm.RSASignatureWithMD5Digest;
- else
- return SignatureAlgorithm.DSASignatureWithSHA1Digest;
- }
+ * public SignatureAlgorithm getSigningAlgorithm() { SignatureAlgorithm sAlg
+ * = (SignatureAlgorithm)mProperties.get(Constants.PR_SIGNATURE_ALGORITHM);
+ * if (sAlg != null) { return sAlg; } String alg =
+ * (String)mProperties.get(Constants.PR_KEY_TYPE);
+ *
+ * if (alg.equals("RSA")) return
+ * SignatureAlgorithm.RSASignatureWithMD5Digest; else return
+ * SignatureAlgorithm.DSASignatureWithSHA1Digest; }
*/
public String getKeyAlgorithm() {
@@ -114,9 +107,8 @@ public class SSLSelfSignedCert extends CertificateInfo {
KeyUsageExtension extension = new KeyUsageExtension();
extension.set(KeyUsageExtension.DIGITAL_SIGNATURE, new Boolean(true));
- //extension.set(KeyUsageExtension.NON_REPUDIATION, new Boolean(true));
+ // extension.set(KeyUsageExtension.NON_REPUDIATION, new Boolean(true));
extension.set(KeyUsageExtension.KEY_ENCIPHERMENT, new Boolean(true));
return extension;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/security/SubsystemCert.java b/pki/base/common/src/com/netscape/cmscore/security/SubsystemCert.java
index bd630de8..aede5e4d 100644
--- a/pki/base/common/src/com/netscape/cmscore/security/SubsystemCert.java
+++ b/pki/base/common/src/com/netscape/cmscore/security/SubsystemCert.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.security;
-
import java.io.IOException;
import java.security.KeyPair;
@@ -29,7 +28,6 @@ import com.netscape.certsrv.common.ConfigConstants;
import com.netscape.certsrv.common.Constants;
import com.netscape.certsrv.security.KeyCertData;
-
/**
* Subsystem certificate.
*
@@ -81,4 +79,3 @@ public class SubsystemCert extends CertificateInfo {
return extension;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/selftests/SelfTestOrderedInstance.java b/pki/base/common/src/com/netscape/cmscore/selftests/SelfTestOrderedInstance.java
index f462c2e2..5b06edc5 100644
--- a/pki/base/common/src/com/netscape/cmscore/selftests/SelfTestOrderedInstance.java
+++ b/pki/base/common/src/com/netscape/cmscore/selftests/SelfTestOrderedInstance.java
@@ -20,21 +20,19 @@
package com.netscape.cmscore.selftests;
-
///////////////////////
// import statements //
///////////////////////
import java.util.StringTokenizer;
-
//////////////////////
// class definition //
//////////////////////
/**
- * This class implements a single element in
- * an ordered list of self test instances.
+ * This class implements a single element in an ordered list of self test
+ * instances.
* <P>
*
* @author mharmsen
@@ -42,32 +40,32 @@ import java.util.StringTokenizer;
* @version $Revision$, $Date$
*/
public class SelfTestOrderedInstance {
- ////////////////////////
+ // //////////////////////
// default parameters //
- ////////////////////////
+ // //////////////////////
private static final String ELEMENT_DELIMITER = ":";
private static final String CRITICAL = "critical";
- ////////////////////////////////////////
+ // //////////////////////////////////////
// SelfTestOrderedInstance parameters //
- ////////////////////////////////////////
+ // //////////////////////////////////////
- private String mInstanceName = null;
+ private String mInstanceName = null;
private boolean mCritical = false;
- /////////////////////
+ // ///////////////////
// default methods //
- /////////////////////
+ // ///////////////////
/**
- * Constructs a single element within an ordered list of self tests.
- * A "listElement" contains a string of the form "[instanceName]" or
+ * Constructs a single element within an ordered list of self tests. A
+ * "listElement" contains a string of the form "[instanceName]" or
* "[instanceName]:critical".
* <P>
- *
- * @param listElement a string containing the "instanceName" and
- * information indictating whether or not the instance is "critical"
+ *
+ * @param listElement a string containing the "instanceName" and information
+ * indictating whether or not the instance is "critical"
*/
public SelfTestOrderedInstance(String listElement) {
// strip preceding/trailing whitespace
@@ -101,14 +99,14 @@ public class SelfTestOrderedInstance {
}
- /////////////////////////////////////
+ // ///////////////////////////////////
// SelfTestOrderedInstance methods //
- /////////////////////////////////////
+ // ///////////////////////////////////
/**
* Returns the name associated with this self test; may be null.
* <P>
- *
+ *
* @return instanceName of this self test
*/
public String getSelfTestName() {
@@ -118,9 +116,9 @@ public class SelfTestOrderedInstance {
/**
* Returns the criticality associated with this self test.
* <P>
- *
- * @return true if failure of this self test is fatal when
- * it is executed; otherwise return false
+ *
+ * @return true if failure of this self test is fatal when it is executed;
+ * otherwise return false
*/
public boolean isSelfTestCritical() {
return mCritical;
@@ -129,11 +127,10 @@ public class SelfTestOrderedInstance {
/**
* Sets/resets the criticality associated with this self test.
* <P>
- *
+ *
* @param criticalMode the criticality of this self test
*/
public void setSelfTestCriticalMode(boolean criticalMode) {
mCritical = criticalMode;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/selftests/SelfTestSubsystem.java b/pki/base/common/src/com/netscape/cmscore/selftests/SelfTestSubsystem.java
index 8104210d..a2eb1510 100644
--- a/pki/base/common/src/com/netscape/cmscore/selftests/SelfTestSubsystem.java
+++ b/pki/base/common/src/com/netscape/cmscore/selftests/SelfTestSubsystem.java
@@ -20,7 +20,6 @@
package com.netscape.cmscore.selftests;
-
///////////////////////
// import statements //
///////////////////////
@@ -49,7 +48,6 @@ import com.netscape.certsrv.selftests.ESelfTestException;
import com.netscape.certsrv.selftests.ISelfTest;
import com.netscape.certsrv.selftests.ISelfTestSubsystem;
-
//////////////////////
// class definition //
//////////////////////
@@ -63,22 +61,18 @@ import com.netscape.certsrv.selftests.ISelfTestSubsystem;
* @version $Revision$, $Date$
*/
public class SelfTestSubsystem
- implements ISelfTestSubsystem {
- ////////////////////////
+ implements ISelfTestSubsystem {
+ // //////////////////////
// default parameters //
- ////////////////////////
-
-
+ // //////////////////////
- ///////////////////////
+ // /////////////////////
// helper parameters //
- ///////////////////////
+ // /////////////////////
-
-
- //////////////////////////////////
+ // ////////////////////////////////
// SelfTestSubsystem parameters //
- //////////////////////////////////
+ // ////////////////////////////////
private ISubsystem mOwner = null;
private IConfigStore mConfig = null;
@@ -92,9 +86,9 @@ public class SelfTestSubsystem
public Vector mOnDemandOrder = new Vector();
public Vector mStartupOrder = new Vector();
- ///////////////////////////
+ // /////////////////////////
// ISubsystem parameters //
- ///////////////////////////
+ // /////////////////////////
private static final String LIST_DELIMITER = ",";
@@ -102,24 +96,22 @@ public class SelfTestSubsystem
private static final String CRITICAL = "critical";
private static final String LOGGING_SIGNED_AUDIT_SELFTESTS_EXECUTION =
- "LOGGING_SIGNED_AUDIT_SELFTESTS_EXECUTION_2";
+ "LOGGING_SIGNED_AUDIT_SELFTESTS_EXECUTION_2";
- /////////////////////
+ // ///////////////////
// default methods //
- /////////////////////
-
-
+ // ///////////////////
- ////////////////////
+ // //////////////////
// helper methods //
- ////////////////////
+ // //////////////////
/**
* Signed Audit Log
- *
+ *
* This helper method is called to store messages to the signed audit log.
* <P>
- *
+ *
* @param msg signed audit log message
*/
private void audit(String msg) {
@@ -131,10 +123,10 @@ public class SelfTestSubsystem
}
mSignedAuditLogger.log(ILogger.EV_SIGNED_AUDIT,
- null,
- ILogger.S_SIGNED_AUDIT,
- ILogger.LL_SECURITY,
- msg);
+ null,
+ ILogger.S_SIGNED_AUDIT,
+ ILogger.LL_SECURITY,
+ msg);
}
/**
@@ -142,13 +134,13 @@ public class SelfTestSubsystem
* substore name prepended in front of the plugin/parameter name). This
* method may return null.
* <P>
- *
+ *
* @param instancePrefix full name of configuration store
* @param instanceName instance name of self test
* @return fullname of this self test plugin
*/
private String getFullName(String instancePrefix,
- String instanceName) {
+ String instanceName) {
String instanceFullName = null;
// strip preceding/trailing whitespace
@@ -161,9 +153,9 @@ public class SelfTestSubsystem
}
if ((instancePrefix != null) &&
- (instancePrefix != "")) {
+ (instancePrefix != "")) {
if ((instanceName != null) &&
- (instanceName != "")) {
+ (instanceName != "")) {
instanceFullName = instancePrefix
+ "."
+ instanceName;
@@ -176,16 +168,16 @@ public class SelfTestSubsystem
}
/**
- * This helper method checks to see if an instance name/value
- * pair exists for the corresponding ordered list element.
+ * This helper method checks to see if an instance name/value pair exists
+ * for the corresponding ordered list element.
* <P>
- *
+ *
* @param element owner of this subsystem
* @param instanceName instance name of self test
* @exception EMissingSelfTestException subsystem has missing name/value
*/
private void checkInstance(SelfTestOrderedInstance element)
- throws EInvalidSelfTestException, EMissingSelfTestException {
+ throws EInvalidSelfTestException, EMissingSelfTestException {
String instanceFullName = null;
String instanceName = null;
String instanceValue = null;
@@ -200,8 +192,8 @@ public class SelfTestSubsystem
instanceName);
} else {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
throw new EMissingSelfTestException();
}
@@ -211,16 +203,15 @@ public class SelfTestSubsystem
instanceValue = instanceConfig.getString(instanceName);
if ((instanceValue == null) ||
- (instanceValue.equals(""))) {
+ (instanceValue.equals(""))) {
// self test plugin instance property name exists,
// but it contains no value(s)
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_MISSING_VALUES",
- instanceFullName));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_MISSING_VALUES",
+ instanceFullName));
- throw new
- EMissingSelfTestException(instanceFullName,
+ throw new EMissingSelfTestException(instanceFullName,
instanceValue);
} else {
instanceValue = instanceValue.trim();
@@ -229,27 +220,27 @@ public class SelfTestSubsystem
} catch (EPropertyNotFound e) {
// self test plugin instance property name is not present
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_MISSING_NAME",
- instanceFullName));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_MISSING_NAME",
+ instanceFullName));
throw new EMissingSelfTestException(instanceFullName);
} catch (EBaseException e) {
// self test plugin instance EBaseException
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_THREW_EBASEEXCEPTION",
- instanceFullName,
- instanceValue));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_THREW_EBASEEXCEPTION",
+ instanceFullName,
+ instanceValue));
throw new EInvalidSelfTestException(instanceFullName,
instanceValue);
}
}
- ///////////////////////////////
+ // /////////////////////////////
// SelfTestSubsystem methods //
- ///////////////////////////////
+ // /////////////////////////////
//
// methods associated with the list of on demand self tests
@@ -259,7 +250,7 @@ public class SelfTestSubsystem
* List the instance names of all the self tests enabled to run on demand
* (in execution order); may return null.
* <P>
- *
+ *
* @return list of self test instance names run on demand
*/
public String[] listSelfTestsEnabledOnDemand() {
@@ -271,7 +262,7 @@ public class SelfTestSubsystem
mList = new String[numElements];
} else {
return null;
- }
+ }
// loop through all self test plugin instances
// specified to be executed on demand
@@ -281,7 +272,7 @@ public class SelfTestSubsystem
while (instances.hasMoreElements()) {
SelfTestOrderedInstance instance = (SelfTestOrderedInstance)
- instances.nextElement();
+ instances.nextElement();
mList[i] = instance.getSelfTestName();
if (mList[i] != null) {
@@ -296,24 +287,24 @@ public class SelfTestSubsystem
/**
* Enable the specified self test to be executed on demand.
* <P>
- *
+ *
* @param instanceName instance name of self test
- * @param isCritical isCritical is either a critical failure (true) or
- * a non-critical failure (false)
+ * @param isCritical isCritical is either a critical failure (true) or a
+ * non-critical failure (false)
* @exception EInvalidSelfTestException subsystem has invalid name/value
* @exception EMissingSelfTestException subsystem has missing name/value
*/
public void enableSelfTestOnDemand(String instanceName,
- boolean isCritical)
- throws EInvalidSelfTestException, EMissingSelfTestException {
+ boolean isCritical)
+ throws EInvalidSelfTestException, EMissingSelfTestException {
// strip preceding/trailing whitespace
// from passed-in String parameters
if (instanceName != null) {
instanceName = instanceName.trim();
} else {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
throw new EMissingSelfTestException();
}
@@ -324,7 +315,7 @@ public class SelfTestSubsystem
while (instances.hasMoreElements()) {
SelfTestOrderedInstance instance = (SelfTestOrderedInstance)
- instances.nextElement();
+ instances.nextElement();
if (instanceName.equals(instance.getSelfTestName())) {
instance.setSelfTestCriticalMode(isCritical);
@@ -347,8 +338,8 @@ public class SelfTestSubsystem
element = new SelfTestOrderedInstance(elementName);
- // SANITY CHECK: find the corresponding instance property
- // name for this self test plugin
+ // SANITY CHECK: find the corresponding instance property
+ // name for this self test plugin
checkInstance(element);
// store this self test plugin in on-demand order
@@ -358,12 +349,12 @@ public class SelfTestSubsystem
/**
* Disable the specified self test from being able to be executed on demand.
* <P>
- *
+ *
* @param instanceName instance name of self test
* @exception EMissingSelfTestException subsystem has missing name
*/
public void disableSelfTestOnDemand(String instanceName)
- throws EMissingSelfTestException {
+ throws EMissingSelfTestException {
String instanceFullName = null;
// strip preceding/trailing whitespace
@@ -374,8 +365,8 @@ public class SelfTestSubsystem
instanceName);
} else {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
throw new EMissingSelfTestException();
}
@@ -386,7 +377,7 @@ public class SelfTestSubsystem
while (instances.hasMoreElements()) {
SelfTestOrderedInstance instance = (SelfTestOrderedInstance)
- instances.nextElement();
+ instances.nextElement();
if (instanceName.equals(instance.getSelfTestName())) {
mOnDemandOrder.remove(instance);
@@ -396,9 +387,9 @@ public class SelfTestSubsystem
// self test plugin instance property name is not present
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_MISSING_NAME",
- instanceFullName));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_MISSING_NAME",
+ instanceFullName));
throw new EMissingSelfTestException(instanceFullName);
}
@@ -406,21 +397,21 @@ public class SelfTestSubsystem
/**
* Determine if the specified self test is enabled to be executed on demand.
* <P>
- *
+ *
* @param instanceName instance name of self test
* @return true if the specified self test is enabled on demand
* @exception EMissingSelfTestException subsystem has missing name
*/
public boolean isSelfTestEnabledOnDemand(String instanceName)
- throws EMissingSelfTestException {
+ throws EMissingSelfTestException {
// strip preceding/trailing whitespace
// from passed-in String parameters
if (instanceName != null) {
instanceName = instanceName.trim();
} else {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
throw new EMissingSelfTestException();
}
@@ -431,7 +422,7 @@ public class SelfTestSubsystem
while (instances.hasMoreElements()) {
SelfTestOrderedInstance instance = (SelfTestOrderedInstance)
- instances.nextElement();
+ instances.nextElement();
if (instanceName.equals(instance.getSelfTestName())) {
return true;
@@ -442,17 +433,17 @@ public class SelfTestSubsystem
}
/**
- * Determine if failure of the specified self test is fatal when
- * it is executed on demand.
+ * Determine if failure of the specified self test is fatal when it is
+ * executed on demand.
* <P>
- *
+ *
* @param instanceName instance name of self test
- * @return true if failure of the specified self test is fatal when
- * it is executed on demand
+ * @return true if failure of the specified self test is fatal when it is
+ * executed on demand
* @exception EMissingSelfTestException subsystem has missing name
*/
public boolean isSelfTestCriticalOnDemand(String instanceName)
- throws EMissingSelfTestException {
+ throws EMissingSelfTestException {
String instanceFullName = null;
// strip preceding/trailing whitespace
@@ -463,8 +454,8 @@ public class SelfTestSubsystem
instanceName);
} else {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
throw new EMissingSelfTestException();
}
@@ -475,7 +466,7 @@ public class SelfTestSubsystem
while (instances.hasMoreElements()) {
SelfTestOrderedInstance instance = (SelfTestOrderedInstance)
- instances.nextElement();
+ instances.nextElement();
if (instanceName.equals(instance.getSelfTestName())) {
if (instance.isSelfTestCritical()) {
@@ -488,9 +479,9 @@ public class SelfTestSubsystem
// self test plugin instance property name is not present
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_MISSING_NAME",
- instanceFullName));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_MISSING_NAME",
+ instanceFullName));
throw new EMissingSelfTestException(instanceFullName);
}
@@ -498,15 +489,15 @@ public class SelfTestSubsystem
/**
* Execute all self tests specified to be run on demand.
* <P>
- *
+ *
* @exception EMissingSelfTestException subsystem has missing name
* @exception ESelfTestException self test exception
*/
public void runSelfTestsOnDemand()
- throws EMissingSelfTestException, ESelfTestException {
+ throws EMissingSelfTestException, ESelfTestException {
if (CMS.debugOn()) {
CMS.debug("SelfTestSubsystem::runSelfTestsOnDemand():"
- + " ENTERING . . .");
+ + " ENTERING . . .");
}
// loop through all self test plugin instances
@@ -515,7 +506,7 @@ public class SelfTestSubsystem
while (instances.hasMoreElements()) {
SelfTestOrderedInstance instance = (SelfTestOrderedInstance)
- instances.nextElement();
+ instances.nextElement();
String instanceFullName = null;
String instanceName = instance.getSelfTestName();
@@ -526,22 +517,22 @@ public class SelfTestSubsystem
instanceName);
} else {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
throw new EMissingSelfTestException();
}
if (mSelfTestInstances.containsKey(instanceName)) {
ISelfTest test = (ISelfTest)
- mSelfTestInstances.get(instanceName);
+ mSelfTestInstances.get(instanceName);
try {
if (CMS.debugOn()) {
CMS.debug("SelfTestSubsystem::runSelfTestsOnDemand():"
- + " running \""
- + test.getSelfTestName()
- + "\"");
+ + " running \""
+ + test.getSelfTestName()
+ + "\"");
}
test.runSelfTest(mLogger);
@@ -549,9 +540,9 @@ public class SelfTestSubsystem
// Check to see if the self test was critical:
if (isSelfTestCriticalOnDemand(instanceName)) {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_RUN_ON_DEMAND_FAILED",
- instanceFullName));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_RUN_ON_DEMAND_FAILED",
+ instanceFullName));
// shutdown the system gracefully
CMS.shutdown();
@@ -562,9 +553,9 @@ public class SelfTestSubsystem
} else {
// self test plugin instance property name is not present
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_MISSING_NAME",
- instanceFullName));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_MISSING_NAME",
+ instanceFullName));
throw new EMissingSelfTestException(instanceFullName);
}
@@ -572,7 +563,7 @@ public class SelfTestSubsystem
if (CMS.debugOn()) {
CMS.debug("SelfTestSubsystem::runSelfTestsOnDemand():"
- + " EXITING.");
+ + " EXITING.");
}
}
@@ -581,10 +572,10 @@ public class SelfTestSubsystem
//
/**
- * List the instance names of all the self tests enabled to run
- * at server startup (in execution order); may return null.
+ * List the instance names of all the self tests enabled to run at server
+ * startup (in execution order); may return null.
* <P>
- *
+ *
* @return list of self test instance names run at server startup
*/
public String[] listSelfTestsEnabledAtStartup() {
@@ -596,7 +587,7 @@ public class SelfTestSubsystem
mList = new String[numElements];
} else {
return null;
- }
+ }
// loop through all self test plugin instances
// specified to be executed at server startup
@@ -606,7 +597,7 @@ public class SelfTestSubsystem
while (instances.hasMoreElements()) {
SelfTestOrderedInstance instance = (SelfTestOrderedInstance)
- instances.nextElement();
+ instances.nextElement();
mList[i] = instance.getSelfTestName();
if (mList[i] != null) {
@@ -621,24 +612,24 @@ public class SelfTestSubsystem
/**
* Enable the specified self test at server startup.
* <P>
- *
+ *
* @param instanceName instance name of self test
- * @param isCritical isCritical is either a critical failure (true) or
- * a non-critical failure (false)
+ * @param isCritical isCritical is either a critical failure (true) or a
+ * non-critical failure (false)
* @exception EInvalidSelfTestException subsystem has invalid name/value
* @exception EMissingSelfTestException subsystem has missing name/value
*/
public void enableSelfTestAtStartup(String instanceName,
- boolean isCritical)
- throws EInvalidSelfTestException, EMissingSelfTestException {
+ boolean isCritical)
+ throws EInvalidSelfTestException, EMissingSelfTestException {
// strip preceding/trailing whitespace
// from passed-in String parameters
if (instanceName != null) {
instanceName = instanceName.trim();
} else {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
throw new EMissingSelfTestException();
}
@@ -649,7 +640,7 @@ public class SelfTestSubsystem
while (instances.hasMoreElements()) {
SelfTestOrderedInstance instance = (SelfTestOrderedInstance)
- instances.nextElement();
+ instances.nextElement();
if (instanceName.equals(instance.getSelfTestName())) {
instance.setSelfTestCriticalMode(isCritical);
@@ -672,8 +663,8 @@ public class SelfTestSubsystem
element = new SelfTestOrderedInstance(elementName);
- // SANITY CHECK: find the corresponding instance property
- // name for this self test plugin
+ // SANITY CHECK: find the corresponding instance property
+ // name for this self test plugin
checkInstance(element);
// store this self test plugin in startup order
@@ -683,12 +674,12 @@ public class SelfTestSubsystem
/**
* Disable the specified self test at server startup.
* <P>
- *
+ *
* @param instanceName instance name of self test
* @exception EMissingSelfTestException subsystem has missing name
*/
public void disableSelfTestAtStartup(String instanceName)
- throws EMissingSelfTestException {
+ throws EMissingSelfTestException {
String instanceFullName = null;
// strip preceding/trailing whitespace
@@ -699,8 +690,8 @@ public class SelfTestSubsystem
instanceName);
} else {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
throw new EMissingSelfTestException();
}
@@ -711,7 +702,7 @@ public class SelfTestSubsystem
while (instances.hasMoreElements()) {
SelfTestOrderedInstance instance = (SelfTestOrderedInstance)
- instances.nextElement();
+ instances.nextElement();
if (instanceName.equals(instance.getSelfTestName())) {
mStartupOrder.remove(instance);
@@ -721,32 +712,32 @@ public class SelfTestSubsystem
// self test plugin instance property name is not present
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_MISSING_NAME",
- instanceFullName));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_MISSING_NAME",
+ instanceFullName));
throw new EMissingSelfTestException(instanceFullName);
}
/**
- * Determine if the specified self test is executed automatically
- * at server startup.
+ * Determine if the specified self test is executed automatically at server
+ * startup.
* <P>
- *
+ *
* @param instanceName instance name of self test
* @return true if the specified self test is executed at server startup
* @exception EMissingSelfTestException subsystem has missing name
*/
public boolean isSelfTestEnabledAtStartup(String instanceName)
- throws EMissingSelfTestException {
+ throws EMissingSelfTestException {
// strip preceding/trailing whitespace
// from passed-in String parameters
if (instanceName != null) {
instanceName = instanceName.trim();
} else {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
throw new EMissingSelfTestException();
}
@@ -757,7 +748,7 @@ public class SelfTestSubsystem
while (instances.hasMoreElements()) {
SelfTestOrderedInstance instance = (SelfTestOrderedInstance)
- instances.nextElement();
+ instances.nextElement();
if (instanceName.equals(instance.getSelfTestName())) {
return true;
@@ -768,17 +759,17 @@ public class SelfTestSubsystem
}
/**
- * Determine if failure of the specified self test is fatal to
- * server startup.
+ * Determine if failure of the specified self test is fatal to server
+ * startup.
* <P>
- *
+ *
* @param instanceName instance name of self test
- * @return true if failure of the specified self test is fatal to
- * server startup
+ * @return true if failure of the specified self test is fatal to server
+ * startup
* @exception EMissingSelfTestException subsystem has missing name
*/
public boolean isSelfTestCriticalAtStartup(String instanceName)
- throws EMissingSelfTestException {
+ throws EMissingSelfTestException {
String instanceFullName = null;
// strip preceding/trailing whitespace
@@ -789,8 +780,8 @@ public class SelfTestSubsystem
instanceName);
} else {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
throw new EMissingSelfTestException();
}
@@ -801,7 +792,7 @@ public class SelfTestSubsystem
while (instances.hasMoreElements()) {
SelfTestOrderedInstance instance = (SelfTestOrderedInstance)
- instances.nextElement();
+ instances.nextElement();
if (instanceName.equals(instance.getSelfTestName())) {
if (instance.isSelfTestCritical()) {
@@ -814,9 +805,9 @@ public class SelfTestSubsystem
// self test plugin instance property name is not present
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_MISSING_NAME",
- instanceFullName));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_MISSING_NAME",
+ instanceFullName));
throw new EMissingSelfTestException(instanceFullName);
}
@@ -824,16 +815,17 @@ public class SelfTestSubsystem
/**
* Execute all self tests specified to be run at server startup.
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_SELFTESTS_EXECUTION used when self
* tests are run at server startup
* </ul>
+ *
* @exception EMissingSelfTestException subsystem has missing name
* @exception ESelfTestException self test exception
*/
public void runSelfTestsAtStartup()
- throws EMissingSelfTestException, ESelfTestException {
+ throws EMissingSelfTestException, ESelfTestException {
String auditMessage = null;
// ensure that any low-level exceptions are reported
@@ -841,7 +833,7 @@ public class SelfTestSubsystem
try {
if (CMS.debugOn()) {
CMS.debug("SelfTestSubsystem::runSelfTestsAtStartup():"
- + " ENTERING . . .");
+ + " ENTERING . . .");
}
// loop through all self test plugin instances
@@ -850,7 +842,7 @@ public class SelfTestSubsystem
while (instances.hasMoreElements()) {
SelfTestOrderedInstance instance = (SelfTestOrderedInstance)
- instances.nextElement();
+ instances.nextElement();
String instanceFullName = null;
String instanceName = instance.getSelfTestName();
@@ -861,8 +853,8 @@ public class SelfTestSubsystem
instanceName);
} else {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -877,14 +869,14 @@ public class SelfTestSubsystem
if (mSelfTestInstances.containsKey(instanceName)) {
ISelfTest test = (ISelfTest)
- mSelfTestInstances.get(instanceName);
+ mSelfTestInstances.get(instanceName);
try {
if (CMS.debugOn()) {
CMS.debug("SelfTestSubsystem::runSelfTestsAtStartup():"
- + " running \""
- + test.getSelfTestName()
- + "\"");
+ + " running \""
+ + test.getSelfTestName()
+ + "\"");
}
test.runSelfTest(mLogger);
@@ -892,9 +884,9 @@ public class SelfTestSubsystem
// Check to see if the self test was critical:
if (isSelfTestCriticalAtStartup(instanceName)) {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_RUN_AT_STARTUP_FAILED",
- instanceFullName));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_RUN_AT_STARTUP_FAILED",
+ instanceFullName));
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -913,9 +905,9 @@ public class SelfTestSubsystem
} else {
// self test plugin instance property name is not present
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_MISSING_NAME",
- instanceFullName));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_MISSING_NAME",
+ instanceFullName));
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
@@ -939,7 +931,7 @@ public class SelfTestSubsystem
if (CMS.debugOn()) {
CMS.debug("SelfTestSubsystem::runSelfTestsAtStartup():"
- + " EXITING.");
+ + " EXITING.");
}
} catch (EMissingSelfTestException eAudit1) {
// store a message in the signed audit log file
@@ -963,10 +955,10 @@ public class SelfTestSubsystem
//
/**
- * Retrieve an individual self test from the instances list
- * given its instance name. This method may return null.
+ * Retrieve an individual self test from the instances list given its
+ * instance name. This method may return null.
* <P>
- *
+ *
* @param instanceName instance name of self test
* @return individual self test
*/
@@ -998,10 +990,10 @@ public class SelfTestSubsystem
//
/**
- * Returns the ILogEventListener of this subsystem.
- * This method may return null.
+ * Returns the ILogEventListener of this subsystem. This method may return
+ * null.
* <P>
- *
+ *
* @return ILogEventListener of this subsystem
*/
public ILogEventListener getSelfTestLogger() {
@@ -1011,7 +1003,7 @@ public class SelfTestSubsystem
/**
* This method represents the log interface for the self test subsystem.
* <P>
- *
+ *
* @param logger log event listener
* @param msg self test log message
*/
@@ -1027,42 +1019,42 @@ public class SelfTestSubsystem
ev.setLevel(ILogger.LL_INFO);
try {
logger.log(ev);
- } catch( ELogException le ) {
+ } catch (ELogException le) {
// log the message to the "transactions" log
mErrorLogger.log(ILogger.EV_AUDIT,
- null,
- ILogger.S_OTHER,
- ILogger.LL_INFO,
- msg + " - " + le.toString() );
+ null,
+ ILogger.S_OTHER,
+ ILogger.LL_INFO,
+ msg + " - " + le.toString());
}
} else {
// log the message to the "transactions" log
mErrorLogger.log(ILogger.EV_AUDIT,
- null,
- ILogger.S_OTHER,
- ILogger.LL_INFO,
- msg);
+ null,
+ ILogger.S_OTHER,
+ ILogger.LL_INFO,
+ msg);
}
}
/**
- * Register an individual self test on the instances list AND
- * on the "on demand" list (note that the specified self test
- * will be appended to the end of each list).
+ * Register an individual self test on the instances list AND on the
+ * "on demand" list (note that the specified self test will be appended to
+ * the end of each list).
* <P>
- *
+ *
* @param instanceName instance name of self test
- * @param isCritical isCritical is either a critical failure (true) or
- * a non-critical failure (false)
+ * @param isCritical isCritical is either a critical failure (true) or a
+ * non-critical failure (false)
* @param instance individual self test
* @exception EDuplicateSelfTestException subsystem has duplicate name
* @exception EInvalidSelfTestException subsystem has invalid name/value
* @exception EMissingSelfTestException subsystem has missing name/value
*/
public void registerSelfTestOnDemand(String instanceName,
- boolean isCritical,
- ISelfTest instance)
- throws EDuplicateSelfTestException,
+ boolean isCritical,
+ ISelfTest instance)
+ throws EDuplicateSelfTestException,
EInvalidSelfTestException,
EMissingSelfTestException {
String instanceFullName = null;
@@ -1075,8 +1067,8 @@ public class SelfTestSubsystem
instanceName);
} else {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
throw new EMissingSelfTestException();
}
@@ -1084,9 +1076,9 @@ public class SelfTestSubsystem
if (mSelfTestInstances.containsKey(instanceName)) {
// self test plugin instance property name is a duplicate
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_DUPLICATE_NAME",
- instanceFullName));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_DUPLICATE_NAME",
+ instanceFullName));
throw new EDuplicateSelfTestException(instanceFullName);
} else {
@@ -1099,16 +1091,16 @@ public class SelfTestSubsystem
}
/**
- * Deregister an individual self test on the instances list AND
- * on the "on demand" list (note that the specified self test
- * will be removed from each list).
+ * Deregister an individual self test on the instances list AND on the
+ * "on demand" list (note that the specified self test will be removed from
+ * each list).
* <P>
- *
+ *
* @param instanceName instance name of self test
* @exception EMissingSelfTestException subsystem has missing name
*/
public void deregisterSelfTestOnDemand(String instanceName)
- throws EMissingSelfTestException {
+ throws EMissingSelfTestException {
String instanceFullName = null;
// strip preceding/trailing whitespace
@@ -1119,8 +1111,8 @@ public class SelfTestSubsystem
instanceName);
} else {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
throw new EMissingSelfTestException();
}
@@ -1131,9 +1123,9 @@ public class SelfTestSubsystem
if (test == null) {
// self test plugin instance property name is not present
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_MISSING_NAME",
- instanceFullName));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_MISSING_NAME",
+ instanceFullName));
throw new EMissingSelfTestException(instanceFullName);
} else {
@@ -1146,23 +1138,23 @@ public class SelfTestSubsystem
}
/**
- * Register an individual self test on the instances list AND
- * on the "startup" list (note that the specified self test
- * will be appended to the end of each list).
+ * Register an individual self test on the instances list AND on the
+ * "startup" list (note that the specified self test will be appended to the
+ * end of each list).
* <P>
- *
+ *
* @param instanceName instance name of self test
- * @param isCritical isCritical is either a critical failure (true) or
- * a non-critical failure (false)
+ * @param isCritical isCritical is either a critical failure (true) or a
+ * non-critical failure (false)
* @param instance individual self test
* @exception EDuplicateSelfTestException subsystem has duplicate name
* @exception EInvalidSelfTestException subsystem has invalid name/value
* @exception EMissingSelfTestException subsystem has missing name/value
*/
public void registerSelfTestAtStartup(String instanceName,
- boolean isCritical,
- ISelfTest instance)
- throws EDuplicateSelfTestException,
+ boolean isCritical,
+ ISelfTest instance)
+ throws EDuplicateSelfTestException,
EInvalidSelfTestException,
EMissingSelfTestException {
String instanceFullName = null;
@@ -1175,8 +1167,8 @@ public class SelfTestSubsystem
instanceName);
} else {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
throw new EMissingSelfTestException();
}
@@ -1184,9 +1176,9 @@ public class SelfTestSubsystem
if (mSelfTestInstances.containsKey(instanceName)) {
// self test plugin instance property name is a duplicate
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_DUPLICATE_NAME",
- instanceFullName));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_DUPLICATE_NAME",
+ instanceFullName));
throw new EDuplicateSelfTestException(instanceFullName);
} else {
@@ -1199,16 +1191,16 @@ public class SelfTestSubsystem
}
/**
- * Deregister an individual self test on the instances list AND
- * on the "startup" list (note that the specified self test
- * will be removed from each list).
+ * Deregister an individual self test on the instances list AND on the
+ * "startup" list (note that the specified self test will be removed from
+ * each list).
* <P>
- *
+ *
* @param instanceName instance name of self test
* @exception EMissingSelfTestException subsystem has missing name
*/
public void deregisterSelfTestAtStartup(String instanceName)
- throws EMissingSelfTestException {
+ throws EMissingSelfTestException {
String instanceFullName = null;
// strip preceding/trailing whitespace
@@ -1219,8 +1211,8 @@ public class SelfTestSubsystem
instanceName);
} else {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
throw new EMissingSelfTestException();
}
@@ -1231,9 +1223,9 @@ public class SelfTestSubsystem
if (test == null) {
// self test plugin instance property name is not present
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_MISSING_NAME",
- instanceFullName));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_MISSING_NAME",
+ instanceFullName));
throw new EMissingSelfTestException(instanceFullName);
} else {
@@ -1245,15 +1237,15 @@ public class SelfTestSubsystem
disableSelfTestAtStartup(instanceName);
}
- ////////////////////////
+ // //////////////////////
// ISubsystem methods //
- ////////////////////////
+ // //////////////////////
/**
- * This method retrieves the name of this subsystem. This method
- * may return null.
+ * This method retrieves the name of this subsystem. This method may return
+ * null.
* <P>
- *
+ *
* @return identification of this subsystem
*/
public String getId() {
@@ -1263,20 +1255,20 @@ public class SelfTestSubsystem
/**
* This method sets information specific to this subsystem.
* <P>
- *
+ *
* @param id identification of this subsystem
* @exception EBaseException base CMS exception
*/
public void setId(String id)
- throws EBaseException {
+ throws EBaseException {
// strip preceding/trailing whitespace
// from passed-in String parameters
if (id != null) {
id = id.trim();
} else {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
throw new EBaseException("id is null");
}
@@ -1287,45 +1279,45 @@ public class SelfTestSubsystem
/**
* This method initializes this subsystem.
* <P>
- *
+ *
* @param owner owner of this subsystem
* @param config configuration store
* @exception EBaseException base CMS exception
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
if (CMS.debugOn()) {
CMS.debug("SelfTestSubsystem::init():"
- + " ENTERING . . .");
+ + " ENTERING . . .");
}
- if( config == null ) {
- CMS.debug( "SelfTestSubsystem::init() - config is null!" );
- throw new EBaseException( "config is null" );
+ if (config == null) {
+ CMS.debug("SelfTestSubsystem::init() - config is null!");
+ throw new EBaseException("config is null");
}
mOwner = owner;
mConfig = config;
if ((mConfig != null) &&
- (mConfig.getName() != null) &&
- (mConfig.getName() != "")) {
+ (mConfig.getName() != null) &&
+ (mConfig.getName() != "")) {
mRootPrefix = mConfig.getName().trim();
}
int loadStatus = 0;
- // NOTE: Obviously, we must load the self test logger parameters
- // first, since the "selftests.log" log file does not
- // exist until this is accomplished!!!
+ // NOTE: Obviously, we must load the self test logger parameters
+ // first, since the "selftests.log" log file does not
+ // exist until this is accomplished!!!
- ////////////////////////////////////
+ // //////////////////////////////////
// loggerPropertyName=loggerValue //
- ////////////////////////////////////
+ // //////////////////////////////////
if (CMS.debugOn()) {
CMS.debug("SelfTestSubsystem::init():"
- + " loading self test logger parameters");
+ + " loading self test logger parameters");
}
String loggerPrefix = null;
@@ -1338,19 +1330,19 @@ public class SelfTestSubsystem
IConfigStore loggerConfig = mConfig.getSubStore(loggerPath);
if ((loggerConfig != null) &&
- (loggerConfig.getName() != null) &&
- (loggerConfig.getName() != "")) {
+ (loggerConfig.getName() != null) &&
+ (loggerConfig.getName() != "")) {
loggerPrefix = loggerConfig.getName().trim();
} else {
- // NOTE: These messages can only be logged to the "transactions"
- // log, since the "selftests.log" will not exist!
+ // NOTE: These messages can only be logged to the "transactions"
+ // log, since the "selftests.log" will not exist!
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_INITIALIZATION_NOTIFICATION"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_INITIALIZATION_NOTIFICATION"));
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
throw new EMissingSelfTestException();
}
@@ -1372,34 +1364,33 @@ public class SelfTestSubsystem
// self test plugin instance property name exists,
// but it contains no value(s)
- // NOTE: This message can only be logged to the
- // "transactions" log, since the "selftests.log"
- // will not exist!
+ // NOTE: This message can only be logged to the
+ // "transactions" log, since the "selftests.log"
+ // will not exist!
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_MISSING_VALUES",
- loggerFullName));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_MISSING_VALUES",
+ loggerFullName));
- throw new
- EMissingSelfTestException(loggerFullName,
+ throw new EMissingSelfTestException(loggerFullName,
loggerValue);
}
Object o = Class.forName(loggerValue).newInstance();
if (!(o instanceof ILogEventListener)) {
- // NOTE: These messages can only be logged to the
- // "transactions" log, since the "selftests.log"
- // will not exist!
+ // NOTE: These messages can only be logged to the
+ // "transactions" log, since the "selftests.log"
+ // will not exist!
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_INITIALIZATION_NOTIFICATION"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_INITIALIZATION_NOTIFICATION"));
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_INVALID_INSTANCE",
- loggerFullName,
- loggerValue));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_INVALID_INSTANCE",
+ loggerFullName,
+ loggerValue));
throw new EInvalidSelfTestException(loggerFullName,
loggerValue);
@@ -1411,34 +1402,34 @@ public class SelfTestSubsystem
} catch (EBaseException e) {
// self test property name EBaseException
- // NOTE: These messages can only be logged to the
- // "transactions" log, since the "selftests.log"
- // will not exist!
+ // NOTE: These messages can only be logged to the
+ // "transactions" log, since the "selftests.log"
+ // will not exist!
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_INITIALIZATION_NOTIFICATION"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_INITIALIZATION_NOTIFICATION"));
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_THREW_EBASEEXCEPTION",
- loggerFullName,
- loggerValue));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_THREW_EBASEEXCEPTION",
+ loggerFullName,
+ loggerValue));
throw new EInvalidSelfTestException(loggerFullName,
loggerValue);
} catch (Exception e) {
- // NOTE: These messages can only be logged to the
- // "transactions" log, since the "selftests.log"
- // will not exist!
+ // NOTE: These messages can only be logged to the
+ // "transactions" log, since the "selftests.log"
+ // will not exist!
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_INITIALIZATION_NOTIFICATION"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_INITIALIZATION_NOTIFICATION"));
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_THREW_EXCEPTION",
- loggerFullName,
- loggerValue));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_THREW_EXCEPTION",
+ loggerFullName,
+ loggerValue));
CMS.debugStackTrace();
@@ -1450,33 +1441,33 @@ public class SelfTestSubsystem
// Barring any exceptions thrown above, we begin logging messages
// to either the "transactions" log, or the "selftests.log" log.
if (loadStatus == 0) {
- // NOTE: These messages can only be logged to the
- // "transactions" log, since the "selftests.log"
- // will not exist!
+ // NOTE: These messages can only be logged to the
+ // "transactions" log, since the "selftests.log"
+ // will not exist!
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_INITIALIZATION_NOTIFICATION"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_INITIALIZATION_NOTIFICATION"));
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_DONT_LOAD_LOGGER_PARAMETERS"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_DONT_LOAD_LOGGER_PARAMETERS"));
} else {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_INITIALIZATION_NOTIFICATION"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_INITIALIZATION_NOTIFICATION"));
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_LOAD_LOGGER_PARAMETERS"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_LOAD_LOGGER_PARAMETERS"));
}
- ////////////////////////////////////////
+ // //////////////////////////////////////
// instancePropertyName=instanceValue //
- ////////////////////////////////////////
+ // //////////////////////////////////////
if (CMS.debugOn()) {
CMS.debug("SelfTestSubsystem::init():"
- + " loading self test plugins");
+ + " loading self test plugins");
}
// compose self test plugins instance property prefix
@@ -1484,13 +1475,13 @@ public class SelfTestSubsystem
IConfigStore instanceConfig = mConfig.getSubStore(instancePath);
if ((instanceConfig != null) &&
- (instanceConfig.getName() != null) &&
- (instanceConfig.getName() != "")) {
+ (instanceConfig.getName() != null) &&
+ (instanceConfig.getName() != "")) {
mPrefix = instanceConfig.getName().trim();
} else {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
throw new EMissingSelfTestException();
}
@@ -1499,12 +1490,12 @@ public class SelfTestSubsystem
if (instances.hasMoreElements()) {
loadStatus++;
-
+
log(mLogger,
- CMS.getLogMessage("CMSCORE_SELFTESTS_LOAD_PLUGINS"));
+ CMS.getLogMessage("CMSCORE_SELFTESTS_LOAD_PLUGINS"));
} else {
log(mLogger,
- CMS.getLogMessage("CMSCORE_SELFTESTS_DONT_LOAD_PLUGINS"));
+ CMS.getLogMessage("CMSCORE_SELFTESTS_DONT_LOAD_PLUGINS"));
}
// load all self test plugin instances
@@ -1522,8 +1513,8 @@ public class SelfTestSubsystem
instanceName);
} else {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_NAME_IS_NULL"));
throw new EMissingSelfTestException();
}
@@ -1531,9 +1522,9 @@ public class SelfTestSubsystem
if (mSelfTestInstances.containsKey(instanceName)) {
// self test plugin instance property name is a duplicate
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_DUPLICATE_NAME",
- instanceFullName));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_DUPLICATE_NAME",
+ instanceFullName));
throw new EDuplicateSelfTestException(instanceFullName);
}
@@ -1547,21 +1538,20 @@ public class SelfTestSubsystem
// self test plugin instance property name exists,
// but it contains no value(s)
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_MISSING_VALUES",
- instanceFullName));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_MISSING_VALUES",
+ instanceFullName));
- throw new
- EMissingSelfTestException(instanceFullName,
+ throw new EMissingSelfTestException(instanceFullName,
instanceValue);
}
} catch (EBaseException e) {
// self test property name EBaseException
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_THREW_EBASEEXCEPTION",
- instanceFullName,
- instanceValue));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_THREW_EBASEEXCEPTION",
+ instanceFullName,
+ instanceValue));
throw new EInvalidSelfTestException(instanceFullName,
instanceValue);
@@ -1575,20 +1565,20 @@ public class SelfTestSubsystem
if (!(o instanceof ISelfTest)) {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_INVALID_INSTANCE",
- instanceFullName,
- instanceValue));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_INVALID_INSTANCE",
+ instanceFullName,
+ instanceValue));
throw new EInvalidSelfTestException(instanceFullName,
instanceValue);
}
} catch (Exception e) {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_THREW_EXCEPTION",
- instanceFullName,
- instanceValue));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_THREW_EXCEPTION",
+ instanceFullName,
+ instanceValue));
CMS.debugStackTrace();
@@ -1603,12 +1593,12 @@ public class SelfTestSubsystem
if (CMS.debugOn()) {
CMS.debug("SelfTestSubsystem::init():"
- + " loading self test plugin parameters");
+ + " loading self test plugin parameters");
}
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_LOAD_PLUGIN_PARAMETERS"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_LOAD_PLUGIN_PARAMETERS"));
}
ISelfTest test = (ISelfTest) o;
@@ -1619,44 +1609,44 @@ public class SelfTestSubsystem
mSelfTestInstances.put(instanceName, test);
} catch (EDuplicateSelfTestException e) {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PLUGIN_DUPLICATE_PARAMETER",
- instanceFullName,
- e.getInstanceParameter()));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PLUGIN_DUPLICATE_PARAMETER",
+ instanceFullName,
+ e.getInstanceParameter()));
throw e;
} catch (EMissingSelfTestException e) {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PLUGIN_MISSING_PARAMETER",
- instanceFullName,
- e.getInstanceParameter()));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PLUGIN_MISSING_PARAMETER",
+ instanceFullName,
+ e.getInstanceParameter()));
throw e;
} catch (EInvalidSelfTestException e) {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PLUGIN_INVALID_PARAMETER",
- instanceFullName,
- e.getInstanceParameter()));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PLUGIN_INVALID_PARAMETER",
+ instanceFullName,
+ e.getInstanceParameter()));
throw e;
}
}
- //////////////////////////////////////////////////////////
+ // ////////////////////////////////////////////////////////
// onDemandOrderPropertyName=onDemandOrderValue1, . . . //
- //////////////////////////////////////////////////////////
+ // ////////////////////////////////////////////////////////
if (CMS.debugOn()) {
CMS.debug("SelfTestSubsystem::init():"
- + " loading on demand self tests");
+ + " loading on demand self tests");
}
// compose self test plugins on-demand ordering property name
String onDemandOrderName = PROP_CONTAINER + "."
- + PROP_ORDER + "."
- + PROP_ON_DEMAND;
+ + PROP_ORDER + "."
+ + PROP_ON_DEMAND;
String onDemandOrderFullName = getFullName(mRootPrefix,
onDemandOrderName);
String onDemandOrderValues = null;
@@ -1672,23 +1662,23 @@ public class SelfTestSubsystem
loadStatus++;
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_LOAD_PLUGINS_ON_DEMAND"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_LOAD_PLUGINS_ON_DEMAND"));
if ((onDemandOrderValues == null) ||
- (onDemandOrderValues.equals(""))) {
+ (onDemandOrderValues.equals(""))) {
// self test plugins on-demand ordering property name
// exists, but it contains no values, which means that
// no self tests are configured to run on-demand
- if( ( onDemandOrderFullName != null ) &&
- ( !onDemandOrderFullName.equals( "" ) ) ) {
+ if ((onDemandOrderFullName != null) &&
+ (!onDemandOrderFullName.equals(""))) {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_MISSING_ON_DEMAND_VALUES",
- onDemandOrderFullName));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_MISSING_ON_DEMAND_VALUES",
+ onDemandOrderFullName));
}
- throw new EBaseException( "onDemandOrderValues is null "
- + "or empty" );
+ throw new EBaseException("onDemandOrderValues is null "
+ + "or empty");
}
StringTokenizer tokens = new StringTokenizer(onDemandOrderValues,
@@ -1701,8 +1691,8 @@ public class SelfTestSubsystem
element = new SelfTestOrderedInstance(
tokens.nextToken().trim());
- // SANITY CHECK: find the corresponding instance property
- // name for this self test plugin
+ // SANITY CHECK: find the corresponding instance property
+ // name for this self test plugin
checkInstance(element);
// store this self test plugin in on-demand order
@@ -1715,35 +1705,35 @@ public class SelfTestSubsystem
// presently, we merely log this fact
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_DONT_LOAD_PLUGINS_ON_DEMAND"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_DONT_LOAD_PLUGINS_ON_DEMAND"));
// throw new EMissingSelfTestException( onDemandOrderFullName );
} catch (EBaseException e) {
// self test property name EBaseException
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_THREW_EBASEEXCEPTION",
- onDemandOrderFullName,
- onDemandOrderValues));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_THREW_EBASEEXCEPTION",
+ onDemandOrderFullName,
+ onDemandOrderValues));
throw new EInvalidSelfTestException(onDemandOrderFullName,
onDemandOrderValues);
}
- ////////////////////////////////////////////////////////
+ // //////////////////////////////////////////////////////
// startupOrderPropertyName=startupOrderValue1, . . . //
- ////////////////////////////////////////////////////////
+ // //////////////////////////////////////////////////////
if (CMS.debugOn()) {
CMS.debug("SelfTestSubsystem::init():"
- + " loading startup self tests");
+ + " loading startup self tests");
}
// compose self test plugins startup ordering property name
String startupOrderName = PROP_CONTAINER + "."
- + PROP_ORDER + "."
- + PROP_STARTUP;
+ + PROP_ORDER + "."
+ + PROP_STARTUP;
String startupOrderFullName = getFullName(mRootPrefix,
startupOrderName);
String startupOrderValues = null;
@@ -1759,20 +1749,20 @@ public class SelfTestSubsystem
loadStatus++;
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_LOAD_PLUGINS_AT_STARTUP"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_LOAD_PLUGINS_AT_STARTUP"));
if ((startupOrderValues == null) ||
- (startupOrderValues.equals(""))) {
+ (startupOrderValues.equals(""))) {
// self test plugins startup ordering property name
// exists, but it contains no values, which means that
// no self tests are configured to run at server startup
- if( ( startupOrderFullName != null ) &&
- ( !startupOrderFullName.equals( "" ) ) ) {
+ if ((startupOrderFullName != null) &&
+ (!startupOrderFullName.equals(""))) {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_MISSING_STARTUP_VALUES",
- startupOrderFullName));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_MISSING_STARTUP_VALUES",
+ startupOrderFullName));
}
}
@@ -1786,8 +1776,8 @@ public class SelfTestSubsystem
element = new SelfTestOrderedInstance(
tokens.nextToken().trim());
- // SANITY CHECK: find the corresponding instance property
- // name for this self test plugin
+ // SANITY CHECK: find the corresponding instance property
+ // name for this self test plugin
checkInstance(element);
// store this self test plugin in startup order
@@ -1800,17 +1790,17 @@ public class SelfTestSubsystem
// presently, we merely log this fact
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_DONT_LOAD_PLUGINS_AT_STARTUP"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_DONT_LOAD_PLUGINS_AT_STARTUP"));
// throw new EMissingSelfTestException( startupOrderFullName );
} catch (EBaseException e) {
// self test property name EBaseException
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PROPERTY_THREW_EBASEEXCEPTION",
- startupOrderFullName,
- startupOrderValues));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PROPERTY_THREW_EBASEEXCEPTION",
+ startupOrderFullName,
+ startupOrderValues));
throw new EInvalidSelfTestException(startupOrderFullName,
startupOrderValues);
@@ -1819,28 +1809,28 @@ public class SelfTestSubsystem
// notify user whether or not self test plugins have been loaded
if (loadStatus == 0) {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PLUGINS_NONE_LOADED"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PLUGINS_NONE_LOADED"));
} else {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_PLUGINS_LOADED"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_PLUGINS_LOADED"));
}
if (CMS.debugOn()) {
CMS.debug("SelfTestSubsystem::init():"
- + " EXITING.");
+ + " EXITING.");
}
}
/**
* Notifies this subsystem if owner is in running mode.
* <P>
- *
+ *
* @exception EBaseException base CMS exception
*/
public void startup()
- throws EBaseException {
+ throws EBaseException {
// loop through all self test plugin instances
Enumeration<ISelfTest> instances = mSelfTestInstances.elements();
@@ -1857,8 +1847,8 @@ public class SelfTestSubsystem
if (selftests.hasMoreElements()) {
// log that execution of startup self tests has begun
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_RUN_AT_STARTUP"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_RUN_AT_STARTUP"));
// execute all startup self tests
runSelfTestsAtStartup();
@@ -1866,24 +1856,24 @@ public class SelfTestSubsystem
// log that execution of all "critical" startup self tests
// has completed "successfully"
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_RUN_AT_STARTUP_SUCCEEDED"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_RUN_AT_STARTUP_SUCCEEDED"));
} else {
log(mLogger,
- CMS.getLogMessage(
- "CMSCORE_SELFTESTS_NOT_RUN_AT_STARTUP"));
+ CMS.getLogMessage(
+ "CMSCORE_SELFTESTS_NOT_RUN_AT_STARTUP"));
}
}
}
/**
- * Stops this subsystem. The owner may call shutdown
- * anytime after initialization.
+ * Stops this subsystem. The owner may call shutdown anytime after
+ * initialization.
* <P>
*/
public void shutdown() {
// reverse order of all self test plugin instances
- Collection<ISelfTest> collection = mSelfTestInstances.values();
+ Collection<ISelfTest> collection = mSelfTestInstances.values();
Vector<ISelfTest> list = new Vector<ISelfTest>(collection);
Collections.reverse(list);
@@ -1899,14 +1889,13 @@ public class SelfTestSubsystem
}
/**
- * Returns the root configuration storage of this subsystem.
- * This method may return null.
+ * Returns the root configuration storage of this subsystem. This method may
+ * return null.
* <P>
- *
+ *
* @return configuration store of this subsystem
*/
public IConfigStore getConfigStore() {
return mConfig;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/time/SimpleTimeSource.java b/pki/base/common/src/com/netscape/cmscore/time/SimpleTimeSource.java
index 082ae4be..ab832b7c 100644
--- a/pki/base/common/src/com/netscape/cmscore/time/SimpleTimeSource.java
+++ b/pki/base/common/src/com/netscape/cmscore/time/SimpleTimeSource.java
@@ -17,12 +17,10 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.time;
-
import java.util.Date;
import com.netscape.certsrv.base.ITimeSource;
-
public class SimpleTimeSource implements ITimeSource {
public Date getCurrentDate() {
diff --git a/pki/base/common/src/com/netscape/cmscore/usrgrp/CertDNCertUserLocator.java b/pki/base/common/src/com/netscape/cmscore/usrgrp/CertDNCertUserLocator.java
index 4bf348ff..3211be7f 100644
--- a/pki/base/common/src/com/netscape/cmscore/usrgrp/CertDNCertUserLocator.java
+++ b/pki/base/common/src/com/netscape/cmscore/usrgrp/CertDNCertUserLocator.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.usrgrp;
-
import java.security.cert.X509Certificate;
import netscape.ldap.LDAPException;
@@ -30,13 +29,11 @@ import com.netscape.certsrv.usrgrp.ICertUserLocator;
import com.netscape.certsrv.usrgrp.IUGSubsystem;
import com.netscape.certsrv.usrgrp.IUser;
-
/**
- * This interface defines a strategy on how to match
- * the incoming certificate(s) with the certificate(s)
- * in the scope. It matches the "certdn" field which contains
- * the subject dn of the certificate
- *
+ * This interface defines a strategy on how to match the incoming certificate(s)
+ * with the certificate(s) in the scope. It matches the "certdn" field which
+ * contains the subject dn of the certificate
+ *
* @author cfu
* @version $Revision$, $Date$
*/
@@ -54,9 +51,9 @@ public class CertDNCertUserLocator implements ICertUserLocator {
* Retrieves description.
*/
public String getDescription() {
- return "A subject is authenticated if its first" +
- " certificate can be matched with one of the" +
- " certificate in the scope";
+ return "A subject is authenticated if its first" +
+ " certificate can be matched with one of the" +
+ " certificate in the scope";
}
/**
@@ -72,7 +69,7 @@ public class CertDNCertUserLocator implements ICertUserLocator {
return null;
String filter = LDAP_ATTR_CERTDN + "=" +
- certificates[0].getSubjectDN();
+ certificates[0].getSubjectDN();
return mUG.findUsersByCert(filter);
}
diff --git a/pki/base/common/src/com/netscape/cmscore/usrgrp/ExactMatchCertUserLocator.java b/pki/base/common/src/com/netscape/cmscore/usrgrp/ExactMatchCertUserLocator.java
index a7aeeb1e..1aecc786 100644
--- a/pki/base/common/src/com/netscape/cmscore/usrgrp/ExactMatchCertUserLocator.java
+++ b/pki/base/common/src/com/netscape/cmscore/usrgrp/ExactMatchCertUserLocator.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.usrgrp;
-
import java.security.cert.X509Certificate;
import netscape.ldap.LDAPException;
@@ -30,13 +29,11 @@ import com.netscape.certsrv.usrgrp.ICertUserLocator;
import com.netscape.certsrv.usrgrp.IUGSubsystem;
import com.netscape.certsrv.usrgrp.IUser;
-
/**
- * This interface defines a strategy on how to match
- * the incoming certificate(s) with the certificate(s)
- * in the scope. It matches the "description" field which contains a
- * stringied certificate.
- *
+ * This interface defines a strategy on how to match the incoming certificate(s)
+ * with the certificate(s) in the scope. It matches the "description" field
+ * which contains a stringied certificate.
+ *
* @author thomask
* @author cfu
* @version $Revision$, $Date$
@@ -54,9 +51,9 @@ public class ExactMatchCertUserLocator implements ICertUserLocator {
* Retrieves description.
*/
public String getDescription() {
- return "A subject is authenticated if its first" +
- " certificate can be matched with one of the" +
- " certificate in the scope";
+ return "A subject is authenticated if its first" +
+ " certificate can be matched with one of the" +
+ " certificate in the scope";
}
/**
@@ -78,7 +75,7 @@ public class ExactMatchCertUserLocator implements ICertUserLocator {
}
String filter = "description=" +
- mUG.getCertificateString(certificates[pos]);
+ mUG.getCertificateString(certificates[pos]);
return mUG.findUsersByCert(filter);
}
diff --git a/pki/base/common/src/com/netscape/cmscore/usrgrp/Group.java b/pki/base/common/src/com/netscape/cmscore/usrgrp/Group.java
index d91eedf9..eee2afb4 100644
--- a/pki/base/common/src/com/netscape/cmscore/usrgrp/Group.java
+++ b/pki/base/common/src/com/netscape/cmscore/usrgrp/Group.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.usrgrp;
-
import java.util.Enumeration;
import java.util.Vector;
@@ -26,10 +25,9 @@ import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.usrgrp.IGroup;
import com.netscape.certsrv.usrgrp.IUsrGrp;
-
/**
* A class represents a group.
- *
+ *
* @author cfu
* @version $Revision$, $Date$
*/
@@ -91,7 +89,7 @@ public class Group implements IGroup {
}
@SuppressWarnings("unchecked")
- public void set(String name, Object object) throws EBaseException {
+ public void set(String name, Object object) throws EBaseException {
if (name.equals(ATTR_NAME)) {
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTRIBUTE", name));
} else if (name.equals(ATTR_ID)) {
diff --git a/pki/base/common/src/com/netscape/cmscore/usrgrp/UGSubsystem.java b/pki/base/common/src/com/netscape/cmscore/usrgrp/UGSubsystem.java
index 6b25410e..3d63144d 100644
--- a/pki/base/common/src/com/netscape/cmscore/usrgrp/UGSubsystem.java
+++ b/pki/base/common/src/com/netscape/cmscore/usrgrp/UGSubsystem.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.usrgrp;
-
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
@@ -53,12 +52,10 @@ import com.netscape.certsrv.usrgrp.IUsrGrp;
import com.netscape.cmscore.ldapconn.LdapBoundConnFactory;
import com.netscape.cmscore.util.Debug;
-
/**
- * This class defines low-level LDAP usr/grp management
- * usr/grp information is located remotely on another
- * LDAP server.
- *
+ * This class defines low-level LDAP usr/grp management usr/grp information is
+ * located remotely on another LDAP server.
+ *
* @author thomask
* @author cfu
* @version $Revision$, $Date$
@@ -74,7 +71,7 @@ public final class UGSubsystem implements IUGSubsystem {
protected static final String GROUP_ATTR_VALUE = "groupofuniquenames";
protected static final String LDAP_ATTR_USER_CERT_STRING = "description";
- // protected static final String LDAP_ATTR_CERTDN = "seeAlso";
+ // protected static final String LDAP_ATTR_CERTDN = "seeAlso";
protected static final String LDAP_ATTR_USER_CERT = "userCertificate";
protected static final String PROP_BASEDN = "basedn";
@@ -122,8 +119,8 @@ public final class UGSubsystem implements IUGSubsystem {
/**
* Connects to LDAP server.
*/
- public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ public void init(ISubsystem owner, IConfigStore config)
+ throws EBaseException {
mLogger = CMS.getLogger();
mConfig = config;
@@ -150,7 +147,7 @@ public final class UGSubsystem implements IUGSubsystem {
// register admin servlet
}
-
+
/**
* Disconnects usr/grp manager from the LDAP
*/
@@ -164,7 +161,7 @@ public final class UGSubsystem implements IUGSubsystem {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_LDAP_SHUT", e.toString()));
}
}
-
+
public IUser createUser(String id) {
return new User(this, id);
}
@@ -212,16 +209,16 @@ public final class UGSubsystem implements IUGSubsystem {
try {
ldapconn = getConn();
// read DN
- LDAPSearchResults res =
- ldapconn.search(userid,
- LDAPv2.SCOPE_SUB, "(objectclass=*)", null, false);
+ LDAPSearchResults res =
+ ldapconn.search(userid,
+ LDAPv2.SCOPE_SUB, "(objectclass=*)", null, false);
Enumeration<IUser> e = buildUsers(res);
if (e.hasMoreElements()) {
return (IUser) e.nextElement();
}
} finally {
- if (ldapconn != null)
+ if (ldapconn != null)
returnConn(ldapconn);
}
}
@@ -245,9 +242,9 @@ public final class UGSubsystem implements IUGSubsystem {
try {
ldapconn = getConn();
String filter = LDAP_ATTR_USER_CERT_STRING + "=" + getCertificateString(cert);
- LDAPSearchResults res =
- ldapconn.search(getUserBaseDN(),
- LDAPConnection.SCOPE_SUB, filter, null, false);
+ LDAPSearchResults res =
+ ldapconn.search(getUserBaseDN(),
+ LDAPConnection.SCOPE_SUB, filter, null, false);
Enumeration<IUser> e = buildUsers(res);
return (User) e.nextElement();
@@ -259,20 +256,20 @@ public final class UGSubsystem implements IUGSubsystem {
}
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_FIND_USER", e.toString()));
} catch (ELdapException e) {
- String errMsg =
- "find User: Could not get connection to internaldb. Error " + e;
+ String errMsg =
+ "find User: Could not get connection to internaldb. Error " + e;
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_INTERNAL_DB", e.toString()));
} finally {
- if (ldapconn != null)
+ if (ldapconn != null)
returnConn(ldapconn);
}
return null;
}
/**
- * Searchs for identities that matches the certificate locater
- * generated filter.
+ * Searchs for identities that matches the certificate locater generated
+ * filter.
*/
public IUser findUsersByCert(String filter) throws
EUsrGrpException, LDAPException {
@@ -290,8 +287,9 @@ public final class UGSubsystem implements IUGSubsystem {
hasSlash = up.indexOf('\\');
while (hasSlash != -1) {
- stripped += up.substring(0, hasSlash) +
- "\\5c";;
+ stripped += up.substring(0, hasSlash) +
+ "\\5c";
+ ;
up = up.substring(hasSlash + 1);
hasSlash = up.indexOf('\\');
}
@@ -303,7 +301,7 @@ public final class UGSubsystem implements IUGSubsystem {
try {
ldapconn = getConn();
LDAPSearchResults res = ldapconn.search(getUserBaseDN(),
- LDAPv2.SCOPE_SUB, "(" + filter + ")",
+ LDAPv2.SCOPE_SUB, "(" + filter + ")",
null, false);
Enumeration<IUser> e = buildUsers(res);
@@ -317,13 +315,13 @@ public final class UGSubsystem implements IUGSubsystem {
}
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_FIND_USER_BY_CERT", e.toString()));
} catch (ELdapException e) {
- String errMsg =
- "find Users By Cert: " +
- "Could not get connection to internaldb. Error " + e;
+ String errMsg =
+ "find Users By Cert: " +
+ "Could not get connection to internaldb. Error " + e;
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_FIND_USER_BY_CERT", e.toString()));
} finally {
- if (ldapconn != null)
+ if (ldapconn != null)
returnConn(ldapconn);
}
@@ -343,7 +341,7 @@ public final class UGSubsystem implements IUGSubsystem {
try {
ldapconn = getConn();
LDAPSearchResults res = ldapconn.search(getUserBaseDN(),
- LDAPv2.SCOPE_SUB, "(uid=" + filter + ")",
+ LDAPv2.SCOPE_SUB, "(uid=" + filter + ")",
null, false);
Enumeration<IUser> e = buildUsers(res);
@@ -357,12 +355,12 @@ public final class UGSubsystem implements IUGSubsystem {
}
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_FIND_USERS", e.toString()));
} catch (ELdapException e) {
- String errMsg =
- "find Users: Could not get connection to internaldb. Error " + e;
+ String errMsg =
+ "find Users: Could not get connection to internaldb. Error " + e;
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_FIND_USERS", e.toString()));
} finally {
- if (ldapconn != null)
+ if (ldapconn != null)
returnConn(ldapconn);
}
@@ -370,8 +368,8 @@ public final class UGSubsystem implements IUGSubsystem {
}
/**
- * Searchs for identities that matches the filter.
- * retrieves uid only, for efficiency of user listing
+ * Searchs for identities that matches the filter. retrieves uid only, for
+ * efficiency of user listing
*/
public Enumeration<IUser> listUsers(String filter) throws EUsrGrpException {
if (filter == null) {
@@ -447,11 +445,12 @@ public final class UGSubsystem implements IUGSubsystem {
}
/**
- * builds a User instance. Sets only uid for user entry retrieved
- * from LDAP server. for listing efficiency only.
+ * builds a User instance. Sets only uid for user entry retrieved from LDAP
+ * server. for listing efficiency only.
+ *
* @return the User entity.
*/
- protected IUser lbuildUser(LDAPEntry entry) throws EUsrGrpException {
+ protected IUser lbuildUser(LDAPEntry entry) throws EUsrGrpException {
IUser id = createUser(this, (String)
entry.getAttribute("uid").getStringValues().nextElement());
LDAPAttribute cnAttr = entry.getAttribute("cn");
@@ -462,16 +461,16 @@ public final class UGSubsystem implements IUGSubsystem {
if (cn != null) {
id.setFullName(cn);
}
-
+
}
LDAPAttribute certAttr =
- entry.getAttribute(LDAP_ATTR_USER_CERT);
+ entry.getAttribute(LDAP_ATTR_USER_CERT);
if (certAttr != null) {
Vector<X509Certificate> certVector = new Vector<X509Certificate>();
@SuppressWarnings("unchecked")
- Enumeration<byte[]> e = certAttr.getByteValues();
+ Enumeration<byte[]> e = certAttr.getByteValues();
try {
for (; e != null && e.hasMoreElements();) {
@@ -503,8 +502,9 @@ public final class UGSubsystem implements IUGSubsystem {
}
/**
- * builds a User instance. Set all attributes retrieved from
- * LDAP server and set them on User.
+ * builds a User instance. Set all attributes retrieved from LDAP server and
+ * set them on User.
+ *
* @return the User entity.
*/
protected IUser buildUser(LDAPEntry entry) throws EUsrGrpException {
@@ -524,9 +524,9 @@ public final class UGSubsystem implements IUGSubsystem {
if (userdn != null) {
id.setUserDN(userdn);
- } else { // the impossible
+ } else { // the impossible
String errMsg = "buildUser(): user DN not found: " +
- userdn;
+ userdn;
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_BUILD_USER"));
@@ -534,22 +534,19 @@ public final class UGSubsystem implements IUGSubsystem {
}
/*
- LDAPAttribute certdnAttr = entry.getAttribute(LDAP_ATTR_CERTDN);
- if (certdnAttr != null) {
- String cdn = (String)certdnAttr.getStringValues().nextElement();
- if (cdn != null) {
- id.setCertDN(cdn);
- }
- }
+ * LDAPAttribute certdnAttr = entry.getAttribute(LDAP_ATTR_CERTDN); if
+ * (certdnAttr != null) { String cdn =
+ * (String)certdnAttr.getStringValues().nextElement(); if (cdn != null)
+ * { id.setCertDN(cdn); } }
*/
LDAPAttribute mailAttr = entry.getAttribute("mail");
if (mailAttr != null) {
@SuppressWarnings("unchecked")
- Enumeration<String> en = mailAttr.getStringValues();
+ Enumeration<String> en = mailAttr.getStringValues();
if (en != null && en.hasMoreElements()) {
- String mail = en.nextElement();
+ String mail = en.nextElement();
if (mail != null) {
id.setEmail(mail);
@@ -573,7 +570,7 @@ public final class UGSubsystem implements IUGSubsystem {
if (phoneAttr != null) {
@SuppressWarnings("unchecked")
- Enumeration<String> en = phoneAttr.getStringValues();
+ Enumeration<String> en = phoneAttr.getStringValues();
if (en != null && en.hasMoreElements()) {
String phone = (String) en.nextElement();
@@ -589,20 +586,20 @@ public final class UGSubsystem implements IUGSubsystem {
LDAPAttribute userTypeAttr = entry.getAttribute("usertype");
- if (userTypeAttr == null)
+ if (userTypeAttr == null)
id.setUserType("");
else {
@SuppressWarnings("unchecked")
- Enumeration<String> en = userTypeAttr.getStringValues();
+ Enumeration<String> en = userTypeAttr.getStringValues();
if (en != null && en.hasMoreElements()) {
String userType = (String) en.nextElement();
- if ((userType != null) && (! userType.equals("undefined")))
+ if ((userType != null) && (!userType.equals("undefined")))
id.setUserType(userType);
else
id.setUserType("");
-
+
}
}
@@ -612,7 +609,7 @@ public final class UGSubsystem implements IUGSubsystem {
id.setState("");
else {
@SuppressWarnings("unchecked")
- Enumeration<String> en = userStateAttr.getStringValues();
+ Enumeration<String> en = userStateAttr.getStringValues();
if (en != null && en.hasMoreElements()) {
String userState = (String) en.nextElement();
@@ -621,17 +618,17 @@ public final class UGSubsystem implements IUGSubsystem {
id.setState(userState);
else
id.setState("");
-
+
}
}
LDAPAttribute certAttr =
- entry.getAttribute(LDAP_ATTR_USER_CERT);
+ entry.getAttribute(LDAP_ATTR_USER_CERT);
if (certAttr != null) {
Vector<X509Certificate> certVector = new Vector<X509Certificate>();
@SuppressWarnings("unchecked")
- Enumeration<byte[]> e = certAttr.getByteValues();
+ Enumeration<byte[]> e = certAttr.getByteValues();
try {
for (; e != null && e.hasMoreElements();) {
@@ -667,24 +664,21 @@ public final class UGSubsystem implements IUGSubsystem {
}
/**
- * Adds identity. Certificates handled by a separate call to
- * addUserCert()
+ * Adds identity. Certificates handled by a separate call to addUserCert()
*/
public void addUser(IUser identity) throws EUsrGrpException, LDAPException {
User id = (User) identity;
if (id == null) {
- throw new
- EUsrGrpException(CMS.getUserMessage("CMS_USRGRP_ADD_USER_FAIL"));
+ throw new EUsrGrpException(CMS.getUserMessage("CMS_USRGRP_ADD_USER_FAIL"));
}
if (id.getUserID() == null) {
- throw new
- EUsrGrpException(CMS.getUserMessage("CMS_USRGRP_ADD_USER_FAIL_NO_UID"));
+ throw new EUsrGrpException(CMS.getUserMessage("CMS_USRGRP_ADD_USER_FAIL_NO_UID"));
}
LDAPAttributeSet attrs = new LDAPAttributeSet();
- String oc[] = {"top", "person", "organizationalPerson",
+ String oc[] = { "top", "person", "organizationalPerson",
"inetOrgPerson", "cmsuser" };
attrs.add(new LDAPAttribute("objectclass", oc));
@@ -695,29 +689,30 @@ public final class UGSubsystem implements IUGSubsystem {
if (id.getPhone() != null) {
// DS syntax checking requires a value for PrintableString syntax
- if (! id.getPhone().equals("")) {
+ if (!id.getPhone().equals("")) {
attrs.add(new LDAPAttribute("telephonenumber", id.getPhone()));
}
}
- attrs.add(new LDAPAttribute("userpassword",
+ attrs.add(new LDAPAttribute("userpassword",
id.getPassword()));
if (id.getUserType() != null) {
// DS syntax checking requires a value for Directory String syntax
- // but usertype is a MUST attribute, so we need to add something here
+ // but usertype is a MUST attribute, so we need to add something
+ // here
// if it is undefined.
-
- if (! id.getUserType().equals("")) {
- attrs.add(new LDAPAttribute("usertype", id.getUserType()));
+
+ if (!id.getUserType().equals("")) {
+ attrs.add(new LDAPAttribute("usertype", id.getUserType()));
} else {
- attrs.add(new LDAPAttribute("usertype", "undefined"));
+ attrs.add(new LDAPAttribute("usertype", "undefined"));
}
}
if (id.getState() != null) {
// DS syntax checking requires a value for Directory String syntax
- if (! id.getState().equals("")) {
+ if (!id.getState().equals("")) {
attrs.add(new LDAPAttribute("userstate", id.getState()));
}
}
@@ -729,9 +724,9 @@ public final class UGSubsystem implements IUGSubsystem {
String adminId = (String) sessionContext.get(SessionContext.USER_ID);
mLogger.log(ILogger.EV_AUDIT, ILogger.S_USRGRP,
- AuditFormat.LEVEL, AuditFormat.ADDUSERFORMAT,
- new Object[] {adminId, id.getUserID()}
- );
+ AuditFormat.LEVEL, AuditFormat.ADDUSERFORMAT,
+ new Object[] { adminId, id.getUserID() }
+ );
LDAPConnection ldapconn = null;
@@ -739,12 +734,12 @@ public final class UGSubsystem implements IUGSubsystem {
ldapconn = getConn();
ldapconn.add(entry);
} catch (ELdapException e) {
- String errMsg =
- "add User: Could not get connection to internaldb. Error " + e;
+ String errMsg =
+ "add User: Could not get connection to internaldb. Error " + e;
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_ADD_USER", e.toString()));
} finally {
- if (ldapconn != null)
+ if (ldapconn != null)
returnConn(ldapconn);
}
}
@@ -764,27 +759,27 @@ public final class UGSubsystem implements IUGSubsystem {
LDAPModificationSet addCert = new LDAPModificationSet();
if ((cert = user.getX509Certificates()) != null) {
- LDAPAttribute attrCertStr = new
- LDAPAttribute(LDAP_ATTR_USER_CERT_STRING);
+ LDAPAttribute attrCertStr = new
+ LDAPAttribute(LDAP_ATTR_USER_CERT_STRING);
/*
- LDAPAttribute attrCertDNStr = new
- LDAPAttribute(LDAP_ATTR_CERTDN);
+ * LDAPAttribute attrCertDNStr = new
+ * LDAPAttribute(LDAP_ATTR_CERTDN);
*/
- LDAPAttribute attrCertBin = new
- LDAPAttribute(LDAP_ATTR_USER_CERT);
+ LDAPAttribute attrCertBin = new
+ LDAPAttribute(LDAP_ATTR_USER_CERT);
try {
attrCertBin.addValue(cert[0].getEncoded());
attrCertStr.addValue(getCertificateString(cert[0]));
- // attrCertDNStr.addValue(cert[0].getSubjectDN().toString());
+ // attrCertDNStr.addValue(cert[0].getSubjectDN().toString());
} catch (CertificateEncodingException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_ADD_USER_CERT", e.toString()));
throw new EUsrGrpException(CMS.getUserMessage("CMS_USRGRP_USR_CERT_ERROR"));
}
addCert.add(LDAPModification.ADD, attrCertStr);
- //addCert.add(LDAPModification.ADD, attrCertDNStr);
+ // addCert.add(LDAPModification.ADD, attrCertDNStr);
addCert.add(LDAPModification.ADD, attrCertBin);
LDAPConnection ldapconn = null;
@@ -792,17 +787,17 @@ public final class UGSubsystem implements IUGSubsystem {
try {
ldapconn = getConn();
ldapconn.modify("uid=" + user.getUserID() +
- "," + getUserBaseDN(), addCert);
+ "," + getUserBaseDN(), addCert);
// for audit log
SessionContext sessionContext = SessionContext.getContext();
String adminId = (String) sessionContext.get(SessionContext.USER_ID);
mLogger.log(ILogger.EV_AUDIT, ILogger.S_USRGRP,
- AuditFormat.LEVEL, AuditFormat.ADDUSERCERTFORMAT,
- new Object[] {adminId, user.getUserID(),
- cert[0].getSubjectDN().toString(),
- cert[0].getSerialNumber().toString(16)}
- );
+ AuditFormat.LEVEL, AuditFormat.ADDUSERCERTFORMAT,
+ new Object[] { adminId, user.getUserID(),
+ cert[0].getSubjectDN().toString(),
+ cert[0].getSerialNumber().toString(16) }
+ );
} catch (LDAPException e) {
if (Debug.ON) {
@@ -816,13 +811,13 @@ public final class UGSubsystem implements IUGSubsystem {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_ADD_USER", e.toString()));
throw e;
} catch (ELdapException e) {
- String errMsg =
- "add User Cert: " +
- "Could not get connection to internaldb. Error " + e;
+ String errMsg =
+ "add User Cert: " +
+ "Could not get connection to internaldb. Error " + e;
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_ADD_USER", e.toString()));
} finally {
- if (ldapconn != null)
+ if (ldapconn != null)
returnConn(ldapconn);
}
}
@@ -831,9 +826,9 @@ public final class UGSubsystem implements IUGSubsystem {
}
/**
- * Removes a user certificate for a user entry
- * given a user certificate DN (actually, a combination of version,
- * serialNumber, issuerDN, and SubjectDN), and it gets removed
+ * Removes a user certificate for a user entry given a user certificate DN
+ * (actually, a combination of version, serialNumber, issuerDN, and
+ * SubjectDN), and it gets removed
*/
public void removeUserCert(IUser identity) throws EUsrGrpException {
User user = (User) identity;
@@ -854,23 +849,21 @@ public final class UGSubsystem implements IUGSubsystem {
X509Certificate[] certs = ldapUser.getX509Certificates();
if (certs == null) {
- throw new
- EUsrGrpException(CMS.getUserMessage("CMS_USRGRP_CERT_NOT_FOUND"));
+ throw new EUsrGrpException(CMS.getUserMessage("CMS_USRGRP_CERT_NOT_FOUND"));
}
String delCertdn = user.getCertDN();
if (delCertdn == null) {
- throw new
- EUsrGrpException(CMS.getUserMessage("CMS_USRGRP_CERT_NOT_FOUND"));
+ throw new EUsrGrpException(CMS.getUserMessage("CMS_USRGRP_CERT_NOT_FOUND"));
}
LDAPAttribute certAttr = new
- LDAPAttribute(LDAP_ATTR_USER_CERT);
- LDAPAttribute certAttrS = new
- LDAPAttribute(LDAP_ATTR_USER_CERT_STRING);
+ LDAPAttribute(LDAP_ATTR_USER_CERT);
+ LDAPAttribute certAttrS = new
+ LDAPAttribute(LDAP_ATTR_USER_CERT_STRING);
- //LDAPAttribute certDNAttrS = new LDAPAttribute(LDAP_ATTR_CERTDN);
+ // LDAPAttribute certDNAttrS = new LDAPAttribute(LDAP_ATTR_CERTDN);
int certCount = 0;
@@ -888,74 +881,73 @@ public final class UGSubsystem implements IUGSubsystem {
try {
certAttr.addValue(certs[i].getEncoded());
certAttrS.addValue(getCertificateString(certs[i]));
- // certDNAttrS.addValue(certs[i].getSubjectDN().toString());
+ // certDNAttrS.addValue(certs[i].getSubjectDN().toString());
} catch (CertificateEncodingException e) {
throw new EUsrGrpException(CMS.getUserMessage("CMS_USRGRP_USR_CERT_ERROR"));
}
attrs.add(LDAPModification.DELETE, certAttr);
attrs.add(LDAPModification.DELETE, certAttrS);
- //attrs.add(LDAPModification.DELETE, certDNAttrS);
+ // attrs.add(LDAPModification.DELETE, certDNAttrS);
LDAPConnection ldapconn = null;
try {
ldapconn = getConn();
ldapconn.modify("uid=" + user.getUserID() +
- "," + getUserBaseDN(), attrs);
+ "," + getUserBaseDN(), attrs);
certCount++;
// for audit log
SessionContext sessionContext = SessionContext.getContext();
String adminId = (String) sessionContext.get(SessionContext.USER_ID);
- mLogger.log(ILogger.EV_AUDIT,
- ILogger.S_USRGRP,
- AuditFormat.LEVEL,
- AuditFormat.REMOVEUSERCERTFORMAT,
- new Object[] {adminId, user.getUserID(),
- certs[0].getSubjectDN().toString(),
- certs[i].getSerialNumber().toString(16)}
- );
+ mLogger.log(ILogger.EV_AUDIT,
+ ILogger.S_USRGRP,
+ AuditFormat.LEVEL,
+ AuditFormat.REMOVEUSERCERTFORMAT,
+ new Object[] { adminId, user.getUserID(),
+ certs[0].getSubjectDN().toString(),
+ certs[i].getSerialNumber().toString(16) }
+ );
} catch (LDAPException e) {
String errMsg = "removeUserCert():" + e;
if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE) {
- errMsg =
+ errMsg =
"removeUserCert: " + "Internal DB is unavailable";
}
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_REMOVE_USER", e.toString()));
throw new EUsrGrpException(CMS.getUserMessage("CMS_USRGRP_MOD_USER_FAIL"));
} catch (ELdapException e) {
- String errMsg =
- "remove User Cert: " +
- "Could not get connection to internaldb. Error " + e;
+ String errMsg =
+ "remove User Cert: " +
+ "Could not get connection to internaldb. Error " + e;
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_REMOVE_USER", e.toString()));
} finally {
- if (ldapconn != null)
+ if (ldapconn != null)
returnConn(ldapconn);
}
}
}
if (certCount == 0) {
- throw new
- EUsrGrpException(CMS.getUserMessage("CMS_USRGRP_CERT_NOT_FOUND"));
+ throw new EUsrGrpException(CMS.getUserMessage("CMS_USRGRP_CERT_NOT_FOUND"));
}
return;
}
- public void removeUserFromGroup(IGroup grp, String userid)
- throws EUsrGrpException {
-
+ public void removeUserFromGroup(IGroup grp, String userid)
+ throws EUsrGrpException {
+
LDAPConnection ldapconn = null;
try {
ldapconn = getConn();
- String groupDN = "cn=" + grp.getGroupID() +
- "," + getGroupBaseDN();
+ String groupDN = "cn=" + grp.getGroupID() +
+ "," + getGroupBaseDN();
LDAPAttribute memberAttr = new LDAPAttribute(
"uniquemember", "uid=" + userid + "," + getUserBaseDN());
LDAPModification singleChange = new LDAPModification(
@@ -972,12 +964,12 @@ public final class UGSubsystem implements IUGSubsystem {
throw new EUsrGrpException(CMS.getUserMessage("CMS_USRGRP_REMOVE_USER_FAIL"));
} catch (ELdapException e) {
- String errMsg =
- "removeUserFromGroup: Could not get connection to internaldb. Error " + e;
+ String errMsg =
+ "removeUserFromGroup: Could not get connection to internaldb. Error " + e;
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_REMOVE_USER_FROM_GROUP", e.toString()));
} finally {
- if (ldapconn != null)
+ if (ldapconn != null)
returnConn(ldapconn);
}
}
@@ -1000,9 +992,9 @@ public final class UGSubsystem implements IUGSubsystem {
String adminId = (String) sessionContext.get(SessionContext.USER_ID);
mLogger.log(ILogger.EV_AUDIT, ILogger.S_USRGRP,
- AuditFormat.LEVEL, AuditFormat.REMOVEUSERFORMAT,
- new Object[] {adminId, userid}
- );
+ AuditFormat.LEVEL, AuditFormat.REMOVEUSERFORMAT,
+ new Object[] { adminId, userid }
+ );
} catch (LDAPException e) {
String errMsg = "removeUser()" + e.toString();
@@ -1014,25 +1006,25 @@ public final class UGSubsystem implements IUGSubsystem {
throw new EUsrGrpException(CMS.getUserMessage("CMS_USRGRP_REMOVE_USER_FAIL"));
} catch (ELdapException e) {
- String errMsg =
- "remove User: Could not get connection to internaldb. Error " + e;
+ String errMsg =
+ "remove User: Could not get connection to internaldb. Error " + e;
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_REMOVE_USER", e.toString()));
} finally {
- if (ldapconn != null)
+ if (ldapconn != null)
returnConn(ldapconn);
}
}
/**
- * modifies user attributes. Certs are handled separately
+ * modifies user attributes. Certs are handled separately
*/
public void modifyUser(IUser identity) throws EUsrGrpException {
User user = (User) identity;
String st = null;
/**
- X509Certificate certs[] = null;
+ * X509Certificate certs[] = null;
**/
LDAPModificationSet attrs = new LDAPModificationSet();
@@ -1045,10 +1037,10 @@ public final class UGSubsystem implements IUGSubsystem {
try {
ldapconn = getConn();
if ((st = user.getFullName()) != null) {
- attrs.add(LDAPModification.REPLACE,
- new LDAPAttribute("sn", st));
- attrs.add(LDAPModification.REPLACE,
- new LDAPAttribute("cn", st));
+ attrs.add(LDAPModification.REPLACE,
+ new LDAPAttribute("sn", st));
+ attrs.add(LDAPModification.REPLACE,
+ new LDAPAttribute("cn", st));
}
if ((st = user.getEmail()) != null) {
LDAPAttribute ld = new LDAPAttribute("mail", st);
@@ -1057,37 +1049,37 @@ public final class UGSubsystem implements IUGSubsystem {
}
if ((st = user.getPassword()) != null && (!st.equals(""))) {
attrs.add(LDAPModification.REPLACE,
- new LDAPAttribute("userpassword", st));
+ new LDAPAttribute("userpassword", st));
}
if ((st = user.getPhone()) != null) {
- if (! st.equals("")) {
+ if (!st.equals("")) {
attrs.add(LDAPModification.REPLACE,
- new LDAPAttribute("telephonenumber", st));
+ new LDAPAttribute("telephonenumber", st));
} else {
try {
LDAPModification singleChange = new LDAPModification(
- LDAPModification.DELETE, new LDAPAttribute("telephonenumber"));
+ LDAPModification.DELETE, new LDAPAttribute("telephonenumber"));
ldapconn.modify("uid=" + user.getUserID() +
- "," + getUserBaseDN(), singleChange);
+ "," + getUserBaseDN(), singleChange);
} catch (LDAPException e) {
if (e.getLDAPResultCode() != LDAPException.NO_SUCH_ATTRIBUTE) {
CMS.debug("modifyUser: Error in deleting telephonenumber");
throw e;
}
}
- }
+ }
}
if ((st = user.getState()) != null) {
- if (! st.equals("")) {
+ if (!st.equals("")) {
attrs.add(LDAPModification.REPLACE,
- new LDAPAttribute("userstate", st));
+ new LDAPAttribute("userstate", st));
} else {
try {
LDAPModification singleChange = new LDAPModification(
- LDAPModification.DELETE, new LDAPAttribute("userstate"));
+ LDAPModification.DELETE, new LDAPAttribute("userstate"));
ldapconn.modify("uid=" + user.getUserID() +
- "," + getUserBaseDN(), singleChange);
+ "," + getUserBaseDN(), singleChange);
} catch (LDAPException e) {
if (e.getLDAPResultCode() != LDAPException.NO_SUCH_ATTRIBUTE) {
CMS.debug("modifyUser: Error in deleting userstate");
@@ -1095,45 +1087,39 @@ public final class UGSubsystem implements IUGSubsystem {
}
}
}
- }
+ }
/**
- if ((certs = user.getCertificates()) != null) {
- LDAPAttribute attrCertStr = new
- LDAPAttribute("description");
- LDAPAttribute attrCertBin = new
- LDAPAttribute(LDAP_ATTR_USER_CERT);
- for (int i = 0 ; i < certs.length; i++) {
- attrCertBin.addValue(certs[i].getEncoded());
- attrCertStr.addValue(getCertificateString(certs[i]));
- }
- attrs.add(attrCertStr);
-
- if (user.getCertOp() == OpDef.ADD) {
- attrs.add(LDAPModification.ADD, attrCertBin);
- } else if (user.getCertOp() == OpDef.DELETE) {
- attrs.add(LDAPModification.DELETE, attrCertBin);
- } else {
- throw new EUsrGrpException(UsrGrpResources.USR_MOD_ILL_CERT_OP);
- }
- }
+ * if ((certs = user.getCertificates()) != null) { LDAPAttribute
+ * attrCertStr = new LDAPAttribute("description"); LDAPAttribute
+ * attrCertBin = new LDAPAttribute(LDAP_ATTR_USER_CERT); for (int i
+ * = 0 ; i < certs.length; i++) {
+ * attrCertBin.addValue(certs[i].getEncoded());
+ * attrCertStr.addValue(getCertificateString(certs[i])); }
+ * attrs.add(attrCertStr);
+ *
+ * if (user.getCertOp() == OpDef.ADD) {
+ * attrs.add(LDAPModification.ADD, attrCertBin); } else if
+ * (user.getCertOp() == OpDef.DELETE) {
+ * attrs.add(LDAPModification.DELETE, attrCertBin); } else { throw
+ * new EUsrGrpException(UsrGrpResources.USR_MOD_ILL_CERT_OP); } }
**/
ldapconn.modify("uid=" + user.getUserID() +
- "," + getUserBaseDN(), attrs);
+ "," + getUserBaseDN(), attrs);
// for audit log
SessionContext sessionContext = SessionContext.getContext();
String adminId = (String) sessionContext.get(SessionContext.USER_ID);
mLogger.log(ILogger.EV_AUDIT, ILogger.S_USRGRP,
- AuditFormat.LEVEL, AuditFormat.MODIFYUSERFORMAT,
- new Object[] {adminId, user.getUserID()}
- );
+ AuditFormat.LEVEL, AuditFormat.MODIFYUSERFORMAT,
+ new Object[] { adminId, user.getUserID() }
+ );
} catch (Exception e) {
- //e.printStackTrace();
+ // e.printStackTrace();
throw new EUsrGrpException(CMS.getUserMessage("CMS_USRGRP_MOD_USER_FAIL"));
} finally {
- if (ldapconn != null)
+ if (ldapconn != null)
returnConn(ldapconn);
}
}
@@ -1161,15 +1147,15 @@ public final class UGSubsystem implements IUGSubsystem {
try {
ldapconn = getConn();
- LDAPSearchResults res =
- ldapconn.search(getGroupBaseDN(), LDAPv2.SCOPE_SUB,
- "(&(objectclass=groupofuniquenames)(cn=" + filter + "))",
- null, false);
+ LDAPSearchResults res =
+ ldapconn.search(getGroupBaseDN(), LDAPv2.SCOPE_SUB,
+ "(&(objectclass=groupofuniquenames)(cn=" + filter + "))",
+ null, false);
return buildGroups(res);
} catch (LDAPException e) {
- String errMsg =
- "findGroups: could not find group " + filter + ". Error " + e;
+ String errMsg =
+ "findGroups: could not find group " + filter + ". Error " + e;
if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE) {
errMsg = "findGroups: " + "Internal DB is unavailable";
@@ -1177,13 +1163,13 @@ public final class UGSubsystem implements IUGSubsystem {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_FIND_GROUPS", e.toString()));
return null;
} catch (ELdapException e) {
- String errMsg =
- "find Groups: Could not get connection to internaldb. Error " + e;
+ String errMsg =
+ "find Groups: Could not get connection to internaldb. Error " + e;
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_FIND_GROUPS", e.toString()));
return null;
} finally {
- if (ldapconn != null)
+ if (ldapconn != null)
returnConn(ldapconn);
}
}
@@ -1197,10 +1183,10 @@ public final class UGSubsystem implements IUGSubsystem {
}
/**
- * List groups. more efficient than find Groups. only retrieves
- * group names and description.
+ * List groups. more efficient than find Groups. only retrieves group names
+ * and description.
*/
- public Enumeration<IGroup> listGroups(String filter) throws EUsrGrpException {
+ public Enumeration<IGroup> listGroups(String filter) throws EUsrGrpException {
if (filter == null) {
return null;
}
@@ -1214,10 +1200,10 @@ public final class UGSubsystem implements IUGSubsystem {
attrs[1] = "description";
ldapconn = getConn();
- LDAPSearchResults res =
- ldapconn.search(getGroupBaseDN(), LDAPv2.SCOPE_SUB,
- "(&(objectclass=groupofuniquenames)(cn=" + filter + "))",
- attrs, false);
+ LDAPSearchResults res =
+ ldapconn.search(getGroupBaseDN(), LDAPv2.SCOPE_SUB,
+ "(&(objectclass=groupofuniquenames)(cn=" + filter + "))",
+ attrs, false);
return buildGroups(res);
} catch (LDAPException e) {
@@ -1228,12 +1214,12 @@ public final class UGSubsystem implements IUGSubsystem {
}
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_LIST_GROUPS", e.toString()));
} catch (ELdapException e) {
- String errMsg =
- "list Groups: Could not get connection to internaldb. Error " + e;
+ String errMsg =
+ "list Groups: Could not get connection to internaldb. Error " + e;
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_LIST_GROUPS", e.toString()));
} finally {
- if (ldapconn != null)
+ if (ldapconn != null)
returnConn(ldapconn);
}
return null;
@@ -1243,14 +1229,14 @@ public final class UGSubsystem implements IUGSubsystem {
* builds an instance of a Group entry
*/
protected IGroup buildGroup(LDAPEntry entry) {
- String groupName = (String)entry.getAttribute("cn").getStringValues().nextElement();
+ String groupName = (String) entry.getAttribute("cn").getStringValues().nextElement();
IGroup grp = createGroup(this, groupName);
-
+
LDAPAttribute grpDesc = entry.getAttribute("description");
if (grpDesc != null) {
@SuppressWarnings("unchecked")
- Enumeration<String> en = grpDesc.getStringValues();
+ Enumeration<String> en = grpDesc.getStringValues();
if (en != null && en.hasMoreElements()) {
String desc = (String) en.nextElement();
@@ -1282,26 +1268,26 @@ public final class UGSubsystem implements IUGSubsystem {
}
@SuppressWarnings("unchecked")
- Enumeration<String> e = attr.getStringValues();
+ Enumeration<String> e = attr.getStringValues();
while (e.hasMoreElements()) {
String v = (String) e.nextElement();
- // grp.addMemberName(v);
+ // grp.addMemberName(v);
// DOES NOT SUPPORT NESTED GROUPS...
- /* BAD_GROUP_MEMBER message goes to system log
- * We are testing unique member attribute for
- * 1. presence of uid string
- * 2. presence and sequence of equal sign and comma
- * 3. absence of equal sign between previously found equal sign and comma
- * 4. absence of non white space characters between uid string and equal sign
- */
+ /*
+ * BAD_GROUP_MEMBER message goes to system log We are testing unique
+ * member attribute for 1. presence of uid string 2. presence and
+ * sequence of equal sign and comma 3. absence of equal sign between
+ * previously found equal sign and comma 4. absence of non white
+ * space characters between uid string and equal sign
+ */
int i = -1;
int j = -1;
- if (v == null || v.length() < 3 || (!(v.substring(0,3)).equalsIgnoreCase("uid")) ||
- ((i = v.indexOf('=')) < 0) || ((j = v.indexOf(',')) < 0) || i > j ||
- (v.substring(i+1, j)).indexOf('=') > -1 || ((v.substring(3, i)).trim()).length() > 0) {
+ if (v == null || v.length() < 3 || (!(v.substring(0, 3)).equalsIgnoreCase("uid")) ||
+ ((i = v.indexOf('=')) < 0) || ((j = v.indexOf(',')) < 0) || i > j ||
+ (v.substring(i + 1, j)).indexOf('=') > -1 || ((v.substring(3, i)).trim()).length() > 0) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_BAD_GROUP_MEMBER", groupName, v));
} else {
grp.addMemberName(v.substring(v.indexOf('=') + 1, v.indexOf(',')));
@@ -1316,22 +1302,20 @@ public final class UGSubsystem implements IUGSubsystem {
}
/**
- * Retrieves a group from LDAP
- * NOTE - this takes just the group name.
+ * Retrieves a group from LDAP NOTE - this takes just the group name.
*/
public IGroup getGroupFromName(String name) {
return getGroup("cn=" + name + "," + getGroupBaseDN());
}
/**
- * Retrieves a group from LDAP
- * NOTE - LH This takes a full LDAP DN.
+ * Retrieves a group from LDAP NOTE - LH This takes a full LDAP DN.
*/
public IGroup getGroup(String name) {
if (name == null) {
return null;
}
-
+
LDAPConnection ldapconn = null;
try {
@@ -1372,7 +1356,7 @@ public final class UGSubsystem implements IUGSubsystem {
return false;
}
@SuppressWarnings("unchecked")
- Enumeration<String> en = attr.getStringValues();
+ Enumeration<String> en = attr.getStringValues();
for (; en.hasMoreElements();) {
String v = (String) en.nextElement();
@@ -1390,91 +1374,84 @@ public final class UGSubsystem implements IUGSubsystem {
return false;
}
- public boolean isMemberOf(String userid, String groupname)
- {
+ public boolean isMemberOf(String userid, String groupname) {
try {
- IUser user = getUser(userid);
- return isMemberOfLdapGroup(user.getUserDN(), groupname);
+ IUser user = getUser(userid);
+ return isMemberOfLdapGroup(user.getUserDN(), groupname);
} catch (Exception e) {
- /* do nothing */
+ /* do nothing */
}
return false;
}
/**
- * Checks if the given user is a member of the given group
- * (now runs an ldap search to find the user, instead of
- * fetching the entire group entry)
+ * Checks if the given user is a member of the given group (now runs an ldap
+ * search to find the user, instead of fetching the entire group entry)
*/
- public boolean isMemberOf(IUser id, String name) {
- if (id == null) {
- log(ILogger.LL_WARN, "isMemberOf(): id is null");
- return false;
+ public boolean isMemberOf(IUser id, String name) {
+ if (id == null) {
+ log(ILogger.LL_WARN, "isMemberOf(): id is null");
+ return false;
}
- if (name == null) {
- log(ILogger.LL_WARN, "isMemberOf(): name is null");
- return false;
+ if (name == null) {
+ log(ILogger.LL_WARN, "isMemberOf(): name is null");
+ return false;
}
- Debug.trace("UGSubsystem.isMemberOf() using new lookup code");
- return isMemberOfLdapGroup(id.getUserDN(),name);
+ Debug.trace("UGSubsystem.isMemberOf() using new lookup code");
+ return isMemberOfLdapGroup(id.getUserDN(), name);
}
-
/**
- * checks if the given user DN is in the specified group
- * by running an ldap search for the user in the group
+ * checks if the given user DN is in the specified group by running an ldap
+ * search for the user in the group
*/
- protected boolean isMemberOfLdapGroup(String userid,String groupname)
- {
- String basedn = "cn="+groupname+",ou=groups,"+mBaseDN;
+ protected boolean isMemberOfLdapGroup(String userid, String groupname) {
+ String basedn = "cn=" + groupname + ",ou=groups," + mBaseDN;
LDAPConnection ldapconn = null;
- boolean founduser=false;
+ boolean founduser = false;
try {
- // the group could potentially have many thousands
- // of members, (many values of the uniquemember
- // attribute). So, we don't want to fetch this
- // list each time. We'll just fetch the CN.
- String attrs[]= new String[1];
- attrs[0] = "cn";
+ // the group could potentially have many thousands
+ // of members, (many values of the uniquemember
+ // attribute). So, we don't want to fetch this
+ // list each time. We'll just fetch the CN.
+ String attrs[] = new String[1];
+ attrs[0] = "cn";
ldapconn = getConn();
-
- String filter = "(uniquemember="+userid+")";
- Debug.trace("authorization search base: "+basedn);
- Debug.trace("authorization search filter: "+filter);
+ String filter = "(uniquemember=" + userid + ")";
+ Debug.trace("authorization search base: " + basedn);
+ Debug.trace("authorization search filter: " + filter);
LDAPSearchResults res =
- ldapconn.search(basedn, LDAPv2.SCOPE_BASE,
- filter,
- attrs, false);
- // If the result had at least one entry, we know
- // that the filter matched, and so the user correctly
- // authenticated.
- if (res.hasMoreElements()) {
- // actually read the entry
- LDAPEntry entry = (LDAPEntry)res.nextElement();
- founduser=true;
- }
- Debug.trace("authorization result: "+founduser);
- } catch (LDAPException e) {
- String errMsg =
- "isMemberOfLdapGroup: could not find group "+groupname+". Error "+e;
- if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE) {
- errMsg = "isMemberOfLdapGroup: "+"Internal DB is unavailable";
- }
- Debug.trace("authorization exception: "+errMsg);
- // too chatty in system log
- // log(ILogger.LL_FAILURE, errMsg);
- }
- catch (ELdapException e) {
- String errMsg =
- "isMemberOfLdapGroup: Could not get connection to internaldb. Error "+e;
- Debug.trace("authorization exception: "+errMsg);
+ ldapconn.search(basedn, LDAPv2.SCOPE_BASE,
+ filter,
+ attrs, false);
+ // If the result had at least one entry, we know
+ // that the filter matched, and so the user correctly
+ // authenticated.
+ if (res.hasMoreElements()) {
+ // actually read the entry
+ LDAPEntry entry = (LDAPEntry) res.nextElement();
+ founduser = true;
+ }
+ Debug.trace("authorization result: " + founduser);
+ } catch (LDAPException e) {
+ String errMsg =
+ "isMemberOfLdapGroup: could not find group " + groupname + ". Error " + e;
+ if (e.getLDAPResultCode() == LDAPException.UNAVAILABLE) {
+ errMsg = "isMemberOfLdapGroup: " + "Internal DB is unavailable";
+ }
+ Debug.trace("authorization exception: " + errMsg);
+ // too chatty in system log
+ // log(ILogger.LL_FAILURE, errMsg);
+ } catch (ELdapException e) {
+ String errMsg =
+ "isMemberOfLdapGroup: Could not get connection to internaldb. Error " + e;
+ Debug.trace("authorization exception: " + errMsg);
log(ILogger.LL_FAILURE, errMsg);
- }
- finally {
+ } finally {
if (ldapconn != null)
returnConn(ldapconn);
}
@@ -1495,7 +1472,7 @@ public final class UGSubsystem implements IUGSubsystem {
try {
LDAPAttributeSet attrs = new LDAPAttributeSet();
- String oc[] = {"top", "groupOfUniqueNames"};
+ String oc[] = { "top", "groupOfUniqueNames" };
attrs.add(new LDAPAttribute("objectclass", oc));
attrs.add(new LDAPAttribute("cn", group.getGroupID()));
@@ -1509,8 +1486,8 @@ public final class UGSubsystem implements IUGSubsystem {
String name = (String) e.nextElement();
// DOES NOT SUPPORT NESTED GROUPS...
- attrMembers.addValue("uid=" + name + "," +
- getUserBaseDN());
+ attrMembers.addValue("uid=" + name + "," +
+ getUserBaseDN());
}
attrs.add(attrMembers);
}
@@ -1529,19 +1506,19 @@ public final class UGSubsystem implements IUGSubsystem {
throw new EUsrGrpException(CMS.getUserMessage("CMS_USRGRP_ADD_GROUP_FAIL"));
} catch (ELdapException e) {
- String errMsg =
- "add Group: Could not get connection to internaldb. Error " + e;
+ String errMsg =
+ "add Group: Could not get connection to internaldb. Error " + e;
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_ADD_GROUP", e.toString()));
throw new EUsrGrpException(CMS.getUserMessage("CMS_USRGRP_ADD_GROUP_FAIL"));
} finally {
- if (ldapconn != null)
+ if (ldapconn != null)
returnConn(ldapconn);
}
}
/**
- * Removes a group. Can't remove SUPER_CERT_ADMINS
+ * Removes a group. Can't remove SUPER_CERT_ADMINS
*/
public void removeGroup(String name) throws EUsrGrpException {
if (name == null) {
@@ -1566,9 +1543,9 @@ public final class UGSubsystem implements IUGSubsystem {
throw new EUsrGrpException(CMS.getUserMessage("CMS_USRGRP_REMOVE_GROUP_FAIL"));
} catch (ELdapException e) {
- String errMsg =
- "remove Group: Could not get connection to internaldb. " +
- "Error " + e;
+ String errMsg =
+ "remove Group: Could not get connection to internaldb. " +
+ "Error " + e;
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_REMOVE_GROUP", e.toString()));
} finally {
@@ -1594,8 +1571,8 @@ public final class UGSubsystem implements IUGSubsystem {
String desc = grp.getDescription();
if (desc != null) {
- mod.add(LDAPModification.REPLACE,
- new LDAPAttribute("description", desc));
+ mod.add(LDAPModification.REPLACE,
+ new LDAPAttribute("description", desc));
}
Enumeration<String> e = grp.getMemberNames();
@@ -1605,8 +1582,8 @@ public final class UGSubsystem implements IUGSubsystem {
String name = (String) e.nextElement();
// DOES NOT SUPPORT NESTED GROUPS...
- attrMembers.addValue("uid=" + name + "," +
- getUserBaseDN());
+ attrMembers.addValue("uid=" + name + "," +
+ getUserBaseDN());
}
mod.add(LDAPModification.REPLACE, attrMembers);
} else {
@@ -1614,14 +1591,13 @@ public final class UGSubsystem implements IUGSubsystem {
mod.add(LDAPModification.DELETE, attrMembers);
} else {
// not allowed
- throw new
- EUsrGrpException(CMS.getUserMessage("CMS_USRGRP_ILL_GRP_MOD"));
+ throw new EUsrGrpException(CMS.getUserMessage("CMS_USRGRP_ILL_GRP_MOD"));
}
}
ldapconn = getConn();
ldapconn.modify("cn=" + grp.getGroupID() +
- "," + getGroupBaseDN(), mod);
+ "," + getGroupBaseDN(), mod);
} catch (LDAPException e) {
String errMsg = " modifyGroup()" + e.toString();
@@ -1641,18 +1617,17 @@ public final class UGSubsystem implements IUGSubsystem {
}
/**
- * Evalutes the given context with the attribute
- * critieria.
+ * Evalutes the given context with the attribute critieria.
*/
- public boolean evaluate(String type, IUser id,
- String op, String value) {
+ public boolean evaluate(String type, IUser id,
+ String op, String value) {
if (op.equals("=")) {
if (type.equalsIgnoreCase("user")) {
if (isMatched(value, id.getName()))
return true;
}
if (type.equalsIgnoreCase("group")) {
- return isMemberOf(id, value);
+ return isMemberOf(id, value);
}
}
return false;
@@ -1682,21 +1657,20 @@ public final class UGSubsystem implements IUGSubsystem {
return entry.getDN();
}
} catch (ELdapException e) {
- String errMsg =
- "convertUIDtoDN: Could not get connection to internaldb. " +
- "Error " + e;
+ String errMsg =
+ "convertUIDtoDN: Could not get connection to internaldb. " +
+ "Error " + e;
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_CONVERT_UID", e.toString()));
} finally {
- if (ldapconn != null)
+ if (ldapconn != null)
returnConn(ldapconn);
}
return null;
}
/**
- * Checks if the given DNs are the same after
- * normalization.
+ * Checks if the given DNs are the same after normalization.
*/
protected boolean isMatched(String dn1, String dn2) {
String rdn1[] = LDAPDN.explodeDN(dn1, false);
@@ -1714,8 +1688,8 @@ public final class UGSubsystem implements IUGSubsystem {
}
/**
- * Converts certificate into string format.
- * should eventually go into the locator itself
+ * Converts certificate into string format. should eventually go into the
+ * locator itself
*/
protected String getCertificateStringWithoutVersion(X509Certificate cert) {
if (cert == null) {
@@ -1723,7 +1697,7 @@ public final class UGSubsystem implements IUGSubsystem {
}
// note that it did not represent a certificate fully
return "-1;" + cert.getSerialNumber().toString() +
- ";" + cert.getIssuerDN() + ";" + cert.getSubjectDN();
+ ";" + cert.getIssuerDN() + ";" + cert.getSubjectDN();
}
public String getCertificateString(X509Certificate cert) {
@@ -1733,7 +1707,7 @@ public final class UGSubsystem implements IUGSubsystem {
// note that it did not represent a certificate fully
return cert.getVersion() + ";" + cert.getSerialNumber().toString() +
- ";" + cert.getIssuerDN() + ";" + cert.getSubjectDN();
+ ";" + cert.getIssuerDN() + ";" + cert.getSubjectDN();
}
/**
@@ -1751,13 +1725,13 @@ public final class UGSubsystem implements IUGSubsystem {
}
protected LDAPConnection getConn() throws ELdapException {
- if (mLdapConnFactory == null)
+ if (mLdapConnFactory == null)
return null;
return mLdapConnFactory.getConn();
}
protected void returnConn(LDAPConnection conn) {
- if (mLdapConnFactory != null)
+ if (mLdapConnFactory != null)
mLdapConnFactory.returnConn(conn);
}
@@ -1765,7 +1739,7 @@ public final class UGSubsystem implements IUGSubsystem {
if (mLogger == null)
return;
mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_USRGRP,
- level, "UGSubsystem: " + msg);
+ level, "UGSubsystem: " + msg);
}
public ICertUserLocator getCertUserLocator() {
diff --git a/pki/base/common/src/com/netscape/cmscore/usrgrp/User.java b/pki/base/common/src/com/netscape/cmscore/usrgrp/User.java
index 5133eb23..013b1e52 100644
--- a/pki/base/common/src/com/netscape/cmscore/usrgrp/User.java
+++ b/pki/base/common/src/com/netscape/cmscore/usrgrp/User.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.usrgrp;
-
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import java.util.Vector;
@@ -27,10 +26,9 @@ import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.usrgrp.IUser;
import com.netscape.certsrv.usrgrp.IUsrGrp;
-
/**
* A class represents a user.
- *
+ *
* @author cfu
* @version $Revision$, $Date$
*/
@@ -61,7 +59,7 @@ public class User implements IUser {
mNames.addElement(ATTR_PASSWORD);
mNames.addElement(ATTR_STATE);
mNames.addElement(ATTR_EMAIL);
- // mNames.addElement(ATTR_PHONENUMBER);
+ // mNames.addElement(ATTR_PHONENUMBER);
mNames.addElement(ATTR_X509_CERTIFICATES);
mNames.addElement(ATTR_USERTYPE);
}
@@ -78,7 +76,7 @@ public class User implements IUser {
* Retrieves the name of this identity.
*/
public String getName() {
- // return mScope.getId() + "://" + mUserid;
+ // return mScope.getId() + "://" + mUserid;
return mUserid;
}
@@ -189,7 +187,7 @@ public class User implements IUser {
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTRIBUTE", name));
}
}
-
+
public Object get(String name) throws EBaseException {
if (name.equals(ATTR_NAME)) {
return getName();
diff --git a/pki/base/common/src/com/netscape/cmscore/util/Assert.java b/pki/base/common/src/com/netscape/cmscore/util/Assert.java
index afc38f49..24659929 100644
--- a/pki/base/common/src/com/netscape/cmscore/util/Assert.java
+++ b/pki/base/common/src/com/netscape/cmscore/util/Assert.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.util;
-
public class Assert {
public static final boolean ON = true;
diff --git a/pki/base/common/src/com/netscape/cmscore/util/AssertionException.java b/pki/base/common/src/com/netscape/cmscore/util/AssertionException.java
index 6a0d8e66..d2f3708d 100644
--- a/pki/base/common/src/com/netscape/cmscore/util/AssertionException.java
+++ b/pki/base/common/src/com/netscape/cmscore/util/AssertionException.java
@@ -17,10 +17,9 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.util;
-
/**
- * Assertion exceptions are thrown when assertion code is invoked
- * and fails to operate properly.
+ * Assertion exceptions are thrown when assertion code is invoked and fails to
+ * operate properly.
*/
public class AssertionException extends Error {
/**
diff --git a/pki/base/common/src/com/netscape/cmscore/util/Debug.java b/pki/base/common/src/com/netscape/cmscore/util/Debug.java
index 417f3159..9e0a0d82 100644
--- a/pki/base/common/src/com/netscape/cmscore/util/Debug.java
+++ b/pki/base/common/src/com/netscape/cmscore/util/Debug.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.util;
-
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
@@ -30,29 +29,28 @@ import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.base.ISubsystem;
import com.netscape.cmsutil.util.Utils;
-
public class Debug
- implements ISubsystem {
+ implements ISubsystem {
private static Debug mInstance = new Debug();
private static boolean mShowCaller = false;
-
- /* This dateformatter is used to put the date on each
- debug line. But the DateFormatter is not thread safe,
- so I create a thread-local DateFormatter for each thread
- */
+ /*
+ * This dateformatter is used to put the date on each debug line. But the
+ * DateFormatter is not thread safe, so I create a thread-local
+ * DateFormatter for each thread
+ */
private static String DATE_PATTERN = "dd/MMM/yyyy:HH:mm:ss";
private static ThreadLocal mFormatObject = new ThreadLocal() {
- protected synchronized Object initialValue() {
- return new SimpleDateFormat(DATE_PATTERN);
- }
- };
+ protected synchronized Object initialValue() {
+ return new SimpleDateFormat(DATE_PATTERN);
+ }
+ };
- /* the dateformatter should be accessed with this function */
- private static SimpleDateFormat getDateFormatter() {
- return ((SimpleDateFormat)(mFormatObject.get()));
- }
+ /* the dateformatter should be accessed with this function */
+ private static SimpleDateFormat getDateFormatter() {
+ return ((SimpleDateFormat) (mFormatObject.get()));
+ }
public static final boolean ON = false;
public static final int OBNOXIOUS = 10;
@@ -62,10 +60,10 @@ public class Debug
// the difference between this and 'ON' is that this is always
// guaranteed to log to 'mOut', whereas other parts of the server
// may do:
- // if (Debug.ON) {
- // System.out.println("..");
- // }
- // I want to make sure that any Debug.trace() is not logged to
+ // if (Debug.ON) {
+ // System.out.println("..");
+ // }
+ // I want to make sure that any Debug.trace() is not logged to
// System.out if the server is running under watchdog
private static boolean TRACE_ON = false;
@@ -73,7 +71,7 @@ public class Debug
private static int mDebugLevel = VERBOSE;
private static PrintStream mOut = null;
- private static Hashtable mHK = null;
+ private static Hashtable mHK = null;
static {
if (TRACE_ON == true) {
@@ -88,98 +86,104 @@ public class Debug
/**
* Output a debug message at the output stream sepcified in the init()
* method. This method is very lightweight if debugging is turned off, since
- * it will return immediately. However, the caller should be aware that
- * if the argument to Debug.trace() is an object whose toString() is
- * expensive, that this toString() will still be called in any case.
- * In such a case, it is wise to wrap the Debug.trace like this: <pre>
- * if (Debug.on()) { Debug.trace("obj is: "+obj); }
- * </pre>
+ * it will return immediately. However, the caller should be aware that if
+ * the argument to Debug.trace() is an object whose toString() is expensive,
+ * that this toString() will still be called in any case. In such a case, it
+ * is wise to wrap the Debug.trace like this:
+ *
+ * <pre>
+ * if (Debug.on()) {
+ * Debug.trace(&quot;obj is: &quot; + obj);
+ * }
+ * </pre>
+ *
* @param level the message level. If this is >= than the currently set
- * level (set with setLevel() ), the message is printed
+ * level (set with setLevel() ), the message is printed
* @param t the message to print
- * @param ignoreStack when walking the stack to determine the
- * location of the method that called the trace() method,
- * ignore any classes with this string in. Can be null
- * @param printCaller if true, (and if static mShowCaller is true)
- * dump caller information in this format:
- * (source-file:line) methodname():
+ * @param ignoreStack when walking the stack to determine the location of
+ * the method that called the trace() method, ignore any classes
+ * with this string in. Can be null
+ * @param printCaller if true, (and if static mShowCaller is true) dump
+ * caller information in this format: (source-file:line)
+ * methodname():
*/
public static void trace(int level, String t, String ignoreStack, boolean printCaller) {
- String callerinfo = "";
- if (!TRACE_ON) return;
+ String callerinfo = "";
+ if (!TRACE_ON)
+ return;
if (level >= mDebugLevel) {
if (mShowCaller && printCaller) {
String method = "";
String fileAndLine = "";
try {
- Throwable tr = new Throwable();
- StackTraceElement ste[] = tr.getStackTrace();
- int i=0;
- while ((i < ste.length) &&
- (ste[i].getMethodName().toLowerCase().indexOf("debug") >-1) ||
- (ste[i].getMethodName().toLowerCase().indexOf("hashkey") >-1) ||
- (ste[i].getClassName().toLowerCase().indexOf("propconfigstore") >-1) ||
- (ste[i].getClassName().toLowerCase().indexOf("argblock") >-1) ||
- (ste[i].getClassName().toLowerCase().indexOf("debug") >-1) ||
- (ste[i].getMethodName().toLowerCase().indexOf("trace") >-1)) i++;
-
- if (i < ste.length) {
- fileAndLine = ste[i].getFileName()+":"+
- ste[i].getLineNumber();
- method = ste[i].getMethodName()+"()";
- }
-
- callerinfo = fileAndLine +":"+ method + " ";
+ Throwable tr = new Throwable();
+ StackTraceElement ste[] = tr.getStackTrace();
+ int i = 0;
+ while ((i < ste.length) &&
+ (ste[i].getMethodName().toLowerCase().indexOf("debug") > -1) ||
+ (ste[i].getMethodName().toLowerCase().indexOf("hashkey") > -1) ||
+ (ste[i].getClassName().toLowerCase().indexOf("propconfigstore") > -1) ||
+ (ste[i].getClassName().toLowerCase().indexOf("argblock") > -1) ||
+ (ste[i].getClassName().toLowerCase().indexOf("debug") > -1) ||
+ (ste[i].getMethodName().toLowerCase().indexOf("trace") > -1))
+ i++;
+
+ if (i < ste.length) {
+ fileAndLine = ste[i].getFileName() + ":" +
+ ste[i].getLineNumber();
+ method = ste[i].getMethodName() + "()";
+ }
+
+ callerinfo = fileAndLine + ":" + method + " ";
} catch (Exception f) {
}
}
-
- outputTraceMessage(callerinfo + t);
+
+ outputTraceMessage(callerinfo + t);
}
}
-
- private static void outputTraceMessage(String t)
- {
- if (!TRACE_ON) return;
- SimpleDateFormat d = getDateFormatter();
+
+ private static void outputTraceMessage(String t) {
+ if (!TRACE_ON)
+ return;
+ SimpleDateFormat d = getDateFormatter();
if (mOut != null && d != null) {
mOut.println("[" + d.format(new Date()) + "][" + Thread.currentThread().getName() + "]: " + t);
mOut.flush();
- }
- }
+ }
+ }
- private static boolean hkdotype(String type)
- {
- if (mHK!= null && mHK.get(type) != null) {
- return true;
- } else {
- return false;
- }
- }
+ private static boolean hkdotype(String type) {
+ if (mHK != null && mHK.get(type) != null) {
+ return true;
+ } else {
+ return false;
+ }
+ }
public static void traceHashKey(String type, String key) {
- if (hkdotype(type)) {
- trace("GET r=" + type+ ",k=" + key);
+ if (hkdotype(type)) {
+ trace("GET r=" + type + ",k=" + key);
}
}
public static void traceHashKey(String type, String key, String val) {
- if (hkdotype(type)) {
- trace("GET r=" + type+ ",k=" + key + ",v=" + val);
+ if (hkdotype(type)) {
+ trace("GET r=" + type + ",k=" + key + ",v=" + val);
}
}
public static void traceHashKey(String type, String key, String val, String def) {
- if (hkdotype(type)) {
- trace("GET r=" + type+ ",k=" +
- key + ",v=" + val +",d="+def);
+ if (hkdotype(type)) {
+ trace("GET r=" + type + ",k=" +
+ key + ",v=" + val + ",d=" + def);
}
- }
+ }
public static void putHashKey(String type, String key, String value) {
- if (hkdotype(type)) {
- outputTraceMessage("PUT r=" + type+ ",k=" + key + ",v=" + value);
+ if (hkdotype(type)) {
+ outputTraceMessage("PUT r=" + type + ",k=" + key + ",v=" + value);
}
}
@@ -188,7 +192,8 @@ public class Debug
}
public static void print(int level, String t) {
- if (!TRACE_ON) return;
+ if (!TRACE_ON)
+ return;
if (mOut != null) {
if (level >= mDebugLevel)
mOut.print(t);
@@ -200,24 +205,30 @@ public class Debug
}
private static void printNybble(byte b) {
- if (mOut == null) return;
- if (b < 10) mOut.write('0' + b);
- else mOut.write('a' + b - 10);
+ if (mOut == null)
+ return;
+ if (b < 10)
+ mOut.write('0' + b);
+ else
+ mOut.write('a' + b - 10);
}
/**
- * If tracing enabled, dump a byte array to debugging printstream
- * as hex, colon-seperated bytes, 16 bytes to a line
+ * If tracing enabled, dump a byte array to debugging printstream as hex,
+ * colon-seperated bytes, 16 bytes to a line
*/
public static void print(byte[] b) {
- if (!TRACE_ON) return;
- if (mOut == null) return;
+ if (!TRACE_ON)
+ return;
+ if (mOut == null)
+ return;
for (int i = 0; i < b.length; i++) {
printNybble((byte) ((b[i] & 0xf0) >> 4));
printNybble((byte) (b[i] & 0x0f));
mOut.print(" ");
- if (((i % 16) == 15) && i != b.length) mOut.println("");
+ if (((i % 16) == 15) && i != b.length)
+ mOut.println("");
}
mOut.println("");
mOut.flush();
@@ -227,29 +238,35 @@ public class Debug
* Print the current stack trace to the debug printstream
*/
public static void printStackTrace() {
- if (!TRACE_ON) return;
+ if (!TRACE_ON)
+ return;
Exception e = new Exception("Debug");
printStackTrace(e);
}
/**
- * Print the stack trace of the named exception
- * to the debug printstream
+ * Print the stack trace of the named exception to the debug printstream
*/
public static void printStackTrace(Throwable e) {
- if (!TRACE_ON) return;
- if (mOut == null) return;
+ if (!TRACE_ON)
+ return;
+ if (mOut == null)
+ return;
e.printStackTrace(mOut);
}
/**
- * Set the current debugging level. You can use: <pre>
+ * Set the current debugging level. You can use:
+ *
+ * <pre>
* OBNOXIOUS = 10
* VERBOSE = 5
* INFORM = 1
- * </pre> Or another value
+ * </pre>
+ *
+ * Or another value
*/
public static void setLevel(int level) {
@@ -263,15 +280,15 @@ public class Debug
/**
* Test if debugging is on. Do NOT write to System.out in your debug code
*/
- public static boolean on() {
+ public static boolean on() {
return TRACE_ON;
}
- /* ISubsystem methods: */
+ /* ISubsystem methods: */
public static String ID = "debug";
private static IConfigStore mConfig = null;
-
+
public String getId() {
return ID;
}
@@ -288,8 +305,10 @@ public class Debug
private static final String PROP_APPEND = "append";
/**
- * Debug subsystem initialization. This subsystem is usually
- * given the following parameters: <pre>
+ * Debug subsystem initialization. This subsystem is usually given the
+ * following parameters:
+ *
+ * <pre>
* debug.enabled : (true|false) default false
* debug.filename : can be a pathname, or STDOUT
* debug.hashkeytypes: comma-separated list of hashkey types
@@ -301,7 +320,7 @@ public class Debug
mConfig = config;
String filename = null;
String hashkeytypes = null;
- boolean append=true;
+ boolean append = true;
try {
TRACE_ON = mConfig.getBoolean(PROP_ENABLED, false);
@@ -318,32 +337,32 @@ public class Debug
if (filename.equals("STDOUT")) {
mOut = System.out;
} else {
- if( !Utils.isNT() ) {
+ if (!Utils.isNT()) {
// Always insure that a physical file exists!
- Utils.exec( "touch " + filename );
- Utils.exec( "chmod 00640 " + filename );
+ Utils.exec("touch " + filename);
+ Utils.exec("chmod 00640 " + filename);
}
OutputStream os = new FileOutputStream(filename, append);
- mOut = new PrintStream(os, true); /* true == autoflush */
+ mOut = new PrintStream(os, true); /* true == autoflush */
}
if (hashkeytypes != null) {
- StringTokenizer st = new StringTokenizer(hashkeytypes,
- ",", false);
- mHK = new Hashtable();
- while (st.hasMoreElements()) {
- String hkr = st.nextToken();
- mHK.put(hkr, "true");
- }
+ StringTokenizer st = new StringTokenizer(hashkeytypes,
+ ",", false);
+ mHK = new Hashtable();
+ while (st.hasMoreElements()) {
+ String hkr = st.nextToken();
+ mHK.put(hkr, "true");
+ }
}
}
- outputTraceMessage("============================================");
- outputTraceMessage("===== DEBUG SUBSYSTEM INITIALIZED =======");
- outputTraceMessage("============================================");
+ outputTraceMessage("============================================");
+ outputTraceMessage("===== DEBUG SUBSYSTEM INITIALIZED =======");
+ outputTraceMessage("============================================");
int level = mConfig.getInteger(PROP_LEVEL, VERBOSE);
setLevel(level);
} catch (Exception e) {
// Don't do anything. Logging is not set up yet, and
- // we can't write to STDOUT.
+ // we can't write to STDOUT.
}
}
@@ -364,4 +383,3 @@ public class Debug
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/util/ExceptionFormatter.java b/pki/base/common/src/com/netscape/cmscore/util/ExceptionFormatter.java
index 8479c757..1ba708cb 100644
--- a/pki/base/common/src/com/netscape/cmscore/util/ExceptionFormatter.java
+++ b/pki/base/common/src/com/netscape/cmscore/util/ExceptionFormatter.java
@@ -17,21 +17,19 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.util;
-
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintWriter;
-
public class ExceptionFormatter {
/**
- * Routines for pretty-printing java exceptions
- * prints okay in a single-line.
+ * Routines for pretty-printing java exceptions prints okay in a
+ * single-line.
*/
/*
- * Take an exception stacktrace, and reformat it so that is
- * prints okay in a single-line.
+ * Take an exception stacktrace, and reformat it so that is prints okay in a
+ * single-line.
*/
public static String getStackTraceAsString(Throwable e) {
@@ -39,7 +37,7 @@ public class ExceptionFormatter {
try {
PipedOutputStream po = new PipedOutputStream();
- PipedInputStream pi = new PipedInputStream(po);
+ PipedInputStream pi = new PipedInputStream(po);
PrintWriter ps = new PrintWriter(po);
@@ -48,7 +46,7 @@ public class ExceptionFormatter {
int avail = pi.available();
byte[] b = new byte[avail];
-
+
pi.read(b, 0, avail);
returnvalue = new String(b);
} catch (Exception ex) {
@@ -60,7 +58,7 @@ public class ExceptionFormatter {
/* test code below */
public static void test()
- throws TestException {
+ throws TestException {
throw new TestException("** testexception **");
}
@@ -79,7 +77,6 @@ public class ExceptionFormatter {
}
-
class TestException extends Exception {
/**
@@ -95,4 +92,3 @@ class TestException extends Exception {
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/util/FileAsString.java b/pki/base/common/src/com/netscape/cmscore/util/FileAsString.java
index c0ae1faa..6b97353b 100644
--- a/pki/base/common/src/com/netscape/cmscore/util/FileAsString.java
+++ b/pki/base/common/src/com/netscape/cmscore/util/FileAsString.java
@@ -17,25 +17,22 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.util;
-
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
-
public class FileAsString {
protected String mFilename;
protected long mLastRead = 0;
-
+
private String fileContents = null;
private Object userObject = null;
-
+
/**
- * This class enables you to get treat a file as a string
- * If the file changes underneath you, it will automatically
- * be read
+ * This class enables you to get treat a file as a string If the file
+ * changes underneath you, it will automatically be read
*/
public FileAsString(String filename) throws IOException {
mFilename = filename;
@@ -50,7 +47,7 @@ public class FileAsString {
}
private void readFile()
- throws IOException {
+ throws IOException {
BufferedReader br = createBufferedReader(mFilename);
StringBuffer buf = new StringBuffer("");
int bytesread = 0;
@@ -63,15 +60,14 @@ public class FileAsString {
buf.append(cbuf, 0, bytesread);
}
String s = new String(buf);
- }
- while (bytesread != -1);
+ } while (bytesread != -1);
br.close();
fileContents = new String(buf);
}
-
- private BufferedReader createBufferedReader(String filename)
- throws IOException {
+
+ private BufferedReader createBufferedReader(String filename)
+ throws IOException {
Debug.trace("createBufferedReader(filename=" + filename + ")");
BufferedReader br = null;
FileReader fr = null;
@@ -84,13 +80,13 @@ public class FileAsString {
br = new BufferedReader(fr);
mFilename = filename;
} catch (IOException e) {
- throw e;
+ throw e;
}
return br;
}
-
- public String getAsString()
- throws IOException {
+
+ public String getAsString()
+ throws IOException {
if (fileHasChanged()) {
readFile();
}
@@ -111,9 +107,9 @@ public class FileAsString {
public void setUserObject(Object x) {
userObject = x;
}
-
+
public String getFilename() {
return mFilename;
}
-
+
}
diff --git a/pki/base/common/src/com/netscape/cmscore/util/FileDialogFilter.java b/pki/base/common/src/com/netscape/cmscore/util/FileDialogFilter.java
index 37410533..1277a8da 100644
--- a/pki/base/common/src/com/netscape/cmscore/util/FileDialogFilter.java
+++ b/pki/base/common/src/com/netscape/cmscore/util/FileDialogFilter.java
@@ -17,20 +17,18 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.util;
-
import java.io.File;
import java.io.FilenameFilter;
-
/**
- * checks the filename and directory with the specified filter
- * checks with multiple "*".
- * the filter has to start with a '*' character.
- * this to keep the search the same as in the motif version
+ * checks the filename and directory with the specified filter checks with
+ * multiple "*". the filter has to start with a '*' character. this to keep the
+ * search the same as in the motif version
* <P>
- * Copied verbatium from sun.awt.tiny.TinyFileDialogPeer. Used by
- * RollingLogFile expiration code
+ * Copied verbatium from sun.awt.tiny.TinyFileDialogPeer. Used by RollingLogFile
+ * expiration code
* <P>
+ *
* @author mikep
* @version $Revision$, $Date$
*/
@@ -50,25 +48,25 @@ public class FileDialogFilter implements FilenameFilter {
* return true if match
*/
public boolean accept(File dir, String fileName) {
-
+
File f = new File(dir, fileName);
-
+
if (f.isDirectory()) {
return true;
} else {
return searchPattern(fileName, filter);
}
}
-
- /**
- * start searching
+
+ /**
+ * start searching
*/
boolean searchPattern(String fileName, String filter) {
int filterCursor = 0;
int fileNameCursor = 0;
int filterChar = filter.charAt(filterCursor);
-
+
if (filterCursor == 0 && filterChar != '*') {
return false;
}
@@ -85,17 +83,17 @@ public class FileDialogFilter implements FilenameFilter {
int flLen = fileName.length();
char ftChar;
char flChar;
- int ftCur = 0;
- int flCur = 0;
+ int ftCur = 0;
+ int flCur = 0;
int c = 0;
-
+
if (ftLen == 0) {
return true;
}
while (c < flLen) {
- ftChar = filter.charAt(ftCur);
-
+ ftChar = filter.charAt(ftCur);
+
if (ftChar == '*') {
String ls = filter.substring(ftCur + 1);
String fs = fileName.substring(flCur);
@@ -109,11 +107,11 @@ public class FileDialogFilter implements FilenameFilter {
continue;
}
flChar = fileName.charAt(flCur);
-
+
if (ftChar == flChar) {
ftCur++;
flCur++;
-
+
if (flCur == flLen && ftCur == ftLen) {
return true;
}
@@ -134,9 +132,9 @@ public class FileDialogFilter implements FilenameFilter {
}
}
}
-
+
for (int i = ftCur; i < ftLen; i++) {
- ftChar = filter.charAt(i);
+ ftChar = filter.charAt(i);
if (ftChar != '*') {
return false;
}
@@ -144,4 +142,3 @@ public class FileDialogFilter implements FilenameFilter {
return true;
}
}
-
diff --git a/pki/base/common/src/com/netscape/cmscore/util/OsSubsystem.java b/pki/base/common/src/com/netscape/cmscore/util/OsSubsystem.java
index 05118b9e..5568974b 100644
--- a/pki/base/common/src/com/netscape/cmscore/util/OsSubsystem.java
+++ b/pki/base/common/src/com/netscape/cmscore/util/OsSubsystem.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.util;
-
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
@@ -36,13 +35,12 @@ import com.netscape.osutil.Signal;
import com.netscape.osutil.SignalListener;
import com.netscape.osutil.UserID;
-
/**
- * This object contains the OS independent interfaces. It's currently
- * used for Unix signal and user handling, but could eventually be extended
- * for NT interfaces.
+ * This object contains the OS independent interfaces. It's currently used for
+ * Unix signal and user handling, but could eventually be extended for NT
+ * interfaces.
* <P>
- *
+ *
* @author mikep
* @version $Revision$, $Date$
*/
@@ -86,16 +84,15 @@ public final class OsSubsystem implements ISubsystem {
}
/**
- * Initializes this subsystem with the given configuration
- * store.
+ * Initializes this subsystem with the given configuration store.
* <P>
- *
+ *
* @param owner owner of this subsystem
* @param config configuration store
* @exception EBaseException failed to initialize
*/
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mOwner = owner;
mConfig = config;
@@ -105,12 +102,12 @@ public final class OsSubsystem implements ISubsystem {
// We currently only deal with Unix and NT
if (isUnix()) {
- //initUnix();
+ // initUnix();
} else {
initNT();
}
try {
- //System.out.println(" The dir I'm seeing is " + mInstanceDir);
+ // System.out.println(" The dir I'm seeing is " + mInstanceDir);
String pidName = mInstanceDir + File.separator + "config" + File.separator + "cert-pid";
BufferedWriter pidOut = new BufferedWriter(new FileWriter(pidName));
int pid = OsSubsystem.getpid();
@@ -119,8 +116,8 @@ public final class OsSubsystem implements ISubsystem {
pidOut.close();
OSUtil.getFileWriteLock(pidName);
} catch (Exception e) {
- //XX to stderr XXXXXX
- //e.printStackTrace();
+ // XX to stderr XXXXXX
+ // e.printStackTrace();
}
}
@@ -149,20 +146,22 @@ public final class OsSubsystem implements ISubsystem {
fos.close();
} catch (IOException e) {
- /*LogDoc
- *
+ /*
+ * LogDoc
+ *
* @phase start OS subsystem
+ *
* @message OS: <exception thrown>
*/
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- ILogger.LL_FAILURE, "OS: " + e.toString());
+ ILogger.LL_FAILURE, "OS: " + e.toString());
}
}
}
/**
- * Returns the process ID of the Certificate Server process. Works
- * on Unix and NT.
+ * Returns the process ID of the Certificate Server process. Works on Unix
+ * and NT.
*/
public static int getpid() {
if (isUnix()) {
@@ -173,7 +172,7 @@ public final class OsSubsystem implements ISubsystem {
}
/**
- * Used to change the process user id usually called after the appropriate
+ * Used to change the process user id usually called after the appropriate
* network ports have been opened.
*/
public void setUserId() throws EBaseException {
@@ -188,42 +187,50 @@ public final class OsSubsystem implements ISubsystem {
// Change the userid to the prefered Unix user
if (userid == null) {
- /*LogDoc
- *
+ /*
+ * LogDoc
+ *
* @phase set user id
+ *
* @arg0 default user id
*/
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- ILogger.LL_FAILURE,
- "OS: No user id in config file. Running as {0}", id);
+ ILogger.LL_FAILURE,
+ "OS: No user id in config file. Running as {0}", id);
} else {
- Object[] params = {userid, id};
+ Object[] params = { userid, id };
try {
UserID.set(userid);
} catch (IllegalArgumentException e) {
- /*LogDoc
- *
+ /*
+ * LogDoc
+ *
* @phase set user id
+ *
* @arg0 supplied user id in config
+ *
* @arg1 default user id
*/
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- ILogger.LL_FAILURE,
- "OS: No such user as {0}. Running as {1}", params);
+ mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
+ ILogger.LL_FAILURE,
+ "OS: No such user as {0}. Running as {1}", params);
} catch (SecurityException e) {
- /*LogDoc
- *
+ /*
+ * LogDoc
+ *
* @phase set user id
+ *
* @arg0 supplied user id in config
+ *
* @arg1 default user id
*/
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- ILogger.LL_FAILURE,
- "OS: Can't change process uid to {0}. Running as {1}",
- params);
+ ILogger.LL_FAILURE,
+ "OS: Can't change process uid to {0}. Running as {1}",
+ params);
}
}
}
@@ -232,9 +239,8 @@ public final class OsSubsystem implements ISubsystem {
}
/**
- * Stops the watchdog. You need to call this if you want the
- * server to really shutdown, otherwise the watchdog will just
- * restart us.
+ * Stops the watchdog. You need to call this if you want the server to
+ * really shutdown, otherwise the watchdog will just restart us.
* <P>
*/
public static void stop() {
@@ -243,13 +249,14 @@ public final class OsSubsystem implements ISubsystem {
Signal.send(LibC.getppid(), Signal.SIGTERM);
} else {
- /*LogDoc
- *
+ /*
+ * LogDoc
+ *
* @phase stop watchdog
*/
CMS.getLogger().log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
- ILogger.LL_INFO,
- "OS: stop the NT watchdog!");
+ ILogger.LL_INFO,
+ "OS: stop the NT watchdog!");
}
}
@@ -272,15 +279,16 @@ public final class OsSubsystem implements ISubsystem {
private static void shutdownUnix() {
// Don't accidentally stop this thread
- //if (Thread.currentThread() != mSignalThread && mSignalThread != null) {
- // mSignalThread.stop();
- // mSignalThread = null;
- //}
-
- /* Don't release this signals to protect the process
- Signal.release(Signal.SIGHUP);
- Signal.release(Signal.SIGTERM);
- Signal.release(Signal.SIGINT);
+ // if (Thread.currentThread() != mSignalThread && mSignalThread != null)
+ // {
+ // mSignalThread.stop();
+ // mSignalThread = null;
+ // }
+
+ /*
+ * Don't release this signals to protect the process
+ * Signal.release(Signal.SIGHUP); Signal.release(Signal.SIGTERM);
+ * Signal.release(Signal.SIGINT);
*/
}
@@ -298,18 +306,14 @@ public final class OsSubsystem implements ISubsystem {
public void restart() {
/**
- if (isUnix()) {
- restartUnix();
- } else {
- restartNT();
- }
+ * if (isUnix()) { restartUnix(); } else { restartNT(); }
**/
}
/**
* Returns the root configuration storage of this system.
* <P>
- *
+ *
* @return configuration store of this subsystem
*/
public IConfigStore getConfigStore() {
@@ -317,10 +321,11 @@ public final class OsSubsystem implements ISubsystem {
}
/**
- * A universal routine to decide if we are Unix or something else.
- * This is mostly used for signal handling and uids.
- *
+ * A universal routine to decide if we are Unix or something else. This is
+ * mostly used for signal handling and uids.
+ *
* <P>
+ *
* @return true if these OS the JavaVM is running on is some Unix varient
*/
public static boolean isUnix() {
@@ -329,8 +334,8 @@ public final class OsSubsystem implements ISubsystem {
}
/**
- * Unix signal thread. Sleep for a second and then check on the
- * signals we're interested in. If one is set, do the right stuff
+ * Unix signal thread. Sleep for a second and then check on the signals
+ * we're interested in. If one is set, do the right stuff
*/
final class SignalThread extends Thread {
@@ -360,16 +365,17 @@ public final class OsSubsystem implements ISubsystem {
// wants us to exit?
if (Signal.caught(Signal.SIGINT) > 0 ||
- Signal.caught(Signal.SIGTERM) > 0) {
+ Signal.caught(Signal.SIGTERM) > 0) {
- /*LogDoc
- *
+ /*
+ * LogDoc
+ *
* @phase watchdog check
*/
- mLogger.log(ILogger.EV_SYSTEM,
- ILogger.S_OTHER,
- ILogger.LL_INFO,
- "OS: Received shutdown signal");
+ mLogger.log(ILogger.EV_SYSTEM,
+ ILogger.S_OTHER,
+ ILogger.LL_INFO,
+ "OS: Received shutdown signal");
SubsystemRegistry.getInstance().get("MAIN").shutdown();
return;
}
@@ -377,14 +383,15 @@ public final class OsSubsystem implements ISubsystem {
// Tell to restart us
if (Signal.caught(Signal.SIGHUP) > 0) {
- /*LogDoc
- *
+ /*
+ * LogDoc
+ *
* @phase watchdog check
*/
- mLogger.log(ILogger.EV_SYSTEM,
- ILogger.S_OTHER,
- ILogger.LL_INFO,
- "OS: Received restart signal");
+ mLogger.log(ILogger.EV_SYSTEM,
+ ILogger.S_OTHER,
+ ILogger.LL_INFO,
+ "OS: Received restart signal");
restart();
return;
}
@@ -395,9 +402,9 @@ public final class OsSubsystem implements ISubsystem {
}
}
-
class SIGTERMListener extends SignalListener {
private OsSubsystem mOS;
+
public SIGTERMListener(OsSubsystem os) {
mOS = os;
}
@@ -406,13 +413,13 @@ class SIGTERMListener extends SignalListener {
System.out.println("SIGTERMListener process");
// XXX - temp, should call shutdown
System.exit(0);
- //PKIServer.getPKIServer().shutdown();
+ // PKIServer.getPKIServer().shutdown();
}
}
-
class SIGINTListener extends SignalListener {
private OsSubsystem mOS;
+
public SIGINTListener(OsSubsystem os) {
mOS = os;
}
@@ -421,13 +428,13 @@ class SIGINTListener extends SignalListener {
System.out.println("SIGINTListener process");
// XXX - temp, should call shutdown
System.exit(0);
- //PKIServer.getPKIServer().shutdown();
+ // PKIServer.getPKIServer().shutdown();
}
}
-
class SIGHUPListener extends SignalListener {
private OsSubsystem mOS;
+
public SIGHUPListener(OsSubsystem os) {
mOS = os;
}
@@ -436,6 +443,6 @@ class SIGHUPListener extends SignalListener {
System.out.println("SIGHUPListener process");
// XXX - temp, should call shutdown
// System.exit(0);
- //PKIServer.getPKIServer().shutdown();
+ // PKIServer.getPKIServer().shutdown();
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/util/PFXUtils.java b/pki/base/common/src/com/netscape/cmscore/util/PFXUtils.java
index 7cde72cc..2107a28f 100644
--- a/pki/base/common/src/com/netscape/cmscore/util/PFXUtils.java
+++ b/pki/base/common/src/com/netscape/cmscore/util/PFXUtils.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.util;
-
import java.io.ByteArrayOutputStream;
import java.security.MessageDigest;
import java.security.cert.X509Certificate;
@@ -40,14 +39,13 @@ import org.mozilla.jss.pkix.primitive.PrivateKeyInfo;
import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.base.EBaseException;
-
public class PFXUtils {
/**
* Creates a PKCS12 package.
*/
- public static byte[] createPFX(String pwd, X509Certificate x509cert,
- byte privateKeyInfo[]) throws EBaseException {
+ public static byte[] createPFX(String pwd, X509Certificate x509cert,
+ byte privateKeyInfo[]) throws EBaseException {
try {
// add certificate
SEQUENCE encSafeContents = new SEQUENCE();
@@ -64,24 +62,24 @@ public class PFXUtils {
encSafeContents.addElement(certBag);
// add key
- org.mozilla.jss.util.Password pass = new
- org.mozilla.jss.util.Password(
- pwd.toCharArray());
+ org.mozilla.jss.util.Password pass = new
+ org.mozilla.jss.util.Password(
+ pwd.toCharArray());
SEQUENCE safeContents = new SEQUENCE();
- PasswordConverter passConverter = new
- PasswordConverter();
+ PasswordConverter passConverter = new
+ PasswordConverter();
// XXX - should generate salt
- byte salt[] = {0x01, 0x01, 0x01, 0x01};
+ byte salt[] = { 0x01, 0x01, 0x01, 0x01 };
PrivateKeyInfo pki = (PrivateKeyInfo)
- ASN1Util.decode(PrivateKeyInfo.getTemplate(),
- privateKeyInfo);
+ ASN1Util.decode(PrivateKeyInfo.getTemplate(),
+ privateKeyInfo);
ASN1Value key = EncryptedPrivateKeyInfo.createPBE(
- PBEAlgorithm.PBE_SHA1_DES3_CBC,
+ PBEAlgorithm.PBE_SHA1_DES3_CBC,
pass, salt, 1, passConverter, pki);
SET keyAttrs = createBagAttrs(
- x509cert.getSubjectDN().toString(),
+ x509cert.getSubjectDN().toString(),
localKeyId);
SafeBag keyBag = new SafeBag(
SafeBag.PKCS8_SHROUDED_KEY_BAG, key,
@@ -90,21 +88,21 @@ public class PFXUtils {
safeContents.addElement(keyBag);
// build contents
- AuthenticatedSafes authSafes = new
- AuthenticatedSafes();
+ AuthenticatedSafes authSafes = new
+ AuthenticatedSafes();
authSafes.addSafeContents(safeContents);
authSafes.addSafeContents(encSafeContents);
- // authSafes.addEncryptedSafeContents(
- // authSafes.DEFAULT_KEY_GEN_ALG,
- // pass, null, 1,
- // encSafeContents);
+ // authSafes.addEncryptedSafeContents(
+ // authSafes.DEFAULT_KEY_GEN_ALG,
+ // pass, null, 1,
+ // encSafeContents);
PFX pfx = new PFX(authSafes);
pfx.computeMacData(pass, null, 5); // ??
- ByteArrayOutputStream fos = new
- ByteArrayOutputStream();
+ ByteArrayOutputStream fos = new
+ ByteArrayOutputStream();
pfx.encode(fos);
pass.clear();
@@ -113,8 +111,8 @@ public class PFXUtils {
return fos.toByteArray();
} catch (Exception e) {
throw new EBaseException(
- CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR",
- "Failed to create PKCS12 - " + e.toString()));
+ CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR",
+ "Failed to create PKCS12 - " + e.toString()));
}
}
@@ -122,7 +120,7 @@ public class PFXUtils {
* Creates local key identifier.
*/
public static byte[] createLocalKeyId(X509Certificate cert)
- throws EBaseException {
+ throws EBaseException {
try {
byte certDer[] = cert.getEncoded();
MessageDigest md = MessageDigest.getInstance("SHA");
@@ -131,8 +129,8 @@ public class PFXUtils {
return md.digest();
} catch (Exception e) {
throw new EBaseException(
- CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR",
- "Failed to create Key ID - " + e.toString()));
+ CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR",
+ "Failed to create Key ID - " + e.toString()));
}
}
@@ -140,7 +138,7 @@ public class PFXUtils {
* Creates bag attributes.
*/
public static SET createBagAttrs(String nickName, byte localKeyId[])
- throws EBaseException {
+ throws EBaseException {
try {
SET attrs = new SET();
SEQUENCE nickNameAttr = new SEQUENCE();
@@ -163,7 +161,7 @@ public class PFXUtils {
} catch (Exception e) {
throw new EBaseException(
CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR",
- "Failed to create Key Bag - " + e.toString()));
+ "Failed to create Key Bag - " + e.toString()));
}
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/util/ProfileSubsystem.java b/pki/base/common/src/com/netscape/cmscore/util/ProfileSubsystem.java
index 2d8e63c9..9a86d828 100644
--- a/pki/base/common/src/com/netscape/cmscore/util/ProfileSubsystem.java
+++ b/pki/base/common/src/com/netscape/cmscore/util/ProfileSubsystem.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.util;
-
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.event.MouseAdapter;
@@ -39,11 +38,9 @@ import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.base.ISubsystem;
-
/**
- * A class represents a internal subsystem. This subsystem
- * can be loaded into cert server kernel to perform
- * run time system profiling.
+ * A class represents a internal subsystem. This subsystem can be loaded into
+ * cert server kernel to perform run time system profiling.
* <P>
*
* @author thomask
@@ -82,35 +79,30 @@ public class ProfileSubsystem extends Frame implements ISubsystem, Runnable {
}
/**
- * Initializes this subsystem with the given
- * configuration store.
- * It first initializes resident subsystems,
- * and it loads and initializes loadable
- * subsystem specified in the configuration
- * store.
+ * Initializes this subsystem with the given configuration store. It first
+ * initializes resident subsystems, and it loads and initializes loadable
+ * subsystem specified in the configuration store.
* <P>
- * Note that individual subsystem should be
- * initialized in a separated thread if
- * it has dependency on the initialization
- * of other subsystems.
+ * Note that individual subsystem should be initialized in a separated
+ * thread if it has dependency on the initialization of other subsystems.
* <P>
- *
+ *
* @param owner owner of this subsystem
* @param config configuration store
*/
public synchronized void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
JTabbedPane tabPane = new JTabbedPane();
// general panel
JPanel pane = new JPanel();
mTextArea = new TextArea();
- // mTextArea.setSize(500, 180);
- //mGC = new JButton("GC");
- // pane.setLayout(new GridLayout(2, 1));
+ // mTextArea.setSize(500, 180);
+ // mGC = new JButton("GC");
+ // pane.setLayout(new GridLayout(2, 1));
pane.add(mTextArea);
- // pane.add(mGC);
+ // pane.add(mGC);
mTextArea.setEditable(false);
tabPane.addTab("General", mTextArea);
tabPane.setSelectedIndex(0);
@@ -141,9 +133,8 @@ public class ProfileSubsystem extends Frame implements ISubsystem, Runnable {
}
/*
- * Returns the root configuration storage of this system.
- * <P>
- *
+ * Returns the root configuration storage of this system. <P>
+ *
* @return configuration store of this subsystem
*/
public IConfigStore getConfigStore() {
@@ -152,17 +143,17 @@ public class ProfileSubsystem extends Frame implements ISubsystem, Runnable {
public void updateGeneralPanel() {
Runtime.getRuntime().gc();
- String text =
- "JDK VM Information " + "\n" +
- "Total Memory: " +
- Runtime.getRuntime().totalMemory() + "\n" +
- "Used Memory: " +
- (Runtime.getRuntime().totalMemory() -
- Runtime.getRuntime().freeMemory()) + "\n" +
- "Free Memory: " +
- Runtime.getRuntime().freeMemory() + "\n" +
- "Number of threads: " +
- Thread.activeCount() + "\n";
+ String text =
+ "JDK VM Information " + "\n" +
+ "Total Memory: " +
+ Runtime.getRuntime().totalMemory() + "\n" +
+ "Used Memory: " +
+ (Runtime.getRuntime().totalMemory() -
+ Runtime.getRuntime().freeMemory()) + "\n" +
+ "Free Memory: " +
+ Runtime.getRuntime().freeMemory() + "\n" +
+ "Number of threads: " +
+ Thread.activeCount() + "\n";
mTextArea.setText(text);
}
@@ -197,7 +188,7 @@ public class ProfileSubsystem extends Frame implements ISubsystem, Runnable {
colNames.addElement("isCurrent");
colNames.addElement("isInterrupted");
colNames.addElement("isDaemon");
-
+
mThreadModel.setInfo(data, colNames);
if (mThreadTable != null) {
mThreadTable.setModel(mThreadModel);
@@ -219,8 +210,7 @@ public class ProfileSubsystem extends Frame implements ISubsystem, Runnable {
}
}
-
-class ThreadTableModel extends AbstractTableModel {
+class ThreadTableModel extends AbstractTableModel {
/**
*
*/
@@ -236,34 +226,33 @@ class ThreadTableModel extends AbstractTableModel {
columnNames = _columnNames;
}
- public String getColumnName(int column) {
- return columnNames.elementAt(column).toString();
- }
+ public String getColumnName(int column) {
+ return columnNames.elementAt(column).toString();
+ }
- public int getRowCount() {
- return rowData.size();
- }
+ public int getRowCount() {
+ return rowData.size();
+ }
- public int getColumnCount() {
- return columnNames.size();
- }
+ public int getColumnCount() {
+ return columnNames.size();
+ }
- public Object getValueAt(int row, int column) {
- return ((Vector) rowData.elementAt(row)).elementAt(column);
- }
+ public Object getValueAt(int row, int column) {
+ return ((Vector) rowData.elementAt(row)).elementAt(column);
+ }
- public boolean isCellEditable(int row, int column) {
- return false;
- }
+ public boolean isCellEditable(int row, int column) {
+ return false;
+ }
- public void setValueAt(Object value, int row, int column) {
- ((Vector) rowData.elementAt(row)).setElementAt(value, column);
- fireTableCellUpdated(row, column);
+ public void setValueAt(Object value, int row, int column) {
+ ((Vector) rowData.elementAt(row)).setElementAt(value, column);
+ fireTableCellUpdated(row, column);
}
}
-
-class ThreadTableEvent extends MouseAdapter {
+class ThreadTableEvent extends MouseAdapter {
private JTable mThreadTable = null;
@@ -271,8 +260,8 @@ class ThreadTableEvent extends MouseAdapter {
mThreadTable = table;
}
- public void mouseClicked(MouseEvent e) {
- if (e.getClickCount() == 2) {
+ public void mouseClicked(MouseEvent e) {
+ if (e.getClickCount() == 2) {
int row = mThreadTable.getSelectedRow();
if (row != -1) {
@@ -283,23 +272,23 @@ class ThreadTableEvent extends MouseAdapter {
field.setEditable(false);
- // get stack trace
+ // get stack trace
Thread threads[] = new Thread[100];
int numThreads = Thread.enumerate(threads);
- ByteArrayOutputStream outArray = new ByteArrayOutputStream();
+ ByteArrayOutputStream outArray = new ByteArrayOutputStream();
for (int i = 0; i < numThreads; i++) {
if (!threads[i].getName().equals(name))
continue;
- PrintStream err = System.err;
+ PrintStream err = System.err;
System.setErr(new PrintStream(outArray));
- //TODO remove. This was being called on the array object
- //But you can only dump stack on the current thread
- Thread.dumpStack();
-
- System.setErr(err);
+ // TODO remove. This was being called on the array object
+ // But you can only dump stack on the current thread
+ Thread.dumpStack();
+
+ System.setErr(err);
}
String str = outArray.toString();
@@ -312,7 +301,7 @@ class ThreadTableEvent extends MouseAdapter {
dialog.setContentPane(pane);
dialog.show();
}
- }
+ }
}
}
diff --git a/pki/base/common/src/com/netscape/cmscore/util/StatsSubsystem.java b/pki/base/common/src/com/netscape/cmscore/util/StatsSubsystem.java
index 4cc393e0..40d68fea 100644
--- a/pki/base/common/src/com/netscape/cmscore/util/StatsSubsystem.java
+++ b/pki/base/common/src/com/netscape/cmscore/util/StatsSubsystem.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.util;
-
import java.util.Date;
import java.util.Hashtable;
import java.util.Vector;
@@ -30,16 +29,14 @@ import com.netscape.certsrv.util.IStatsSubsystem;
import com.netscape.certsrv.util.StatsEvent;
/**
- * A class represents a internal subsystem. This subsystem
- * can be loaded into cert server kernel to perform
- * statistics collection.
+ * A class represents a internal subsystem. This subsystem can be loaded into
+ * cert server kernel to perform statistics collection.
* <P>
*
* @author thomask
* @version $Revision$, $Date$
*/
-public class StatsSubsystem implements IStatsSubsystem
-{
+public class StatsSubsystem implements IStatsSubsystem {
private String mId = null;
private StatsEvent mAllTrans = new StatsEvent(null);
private Date mStartTime = new Date();
@@ -64,101 +61,89 @@ public class StatsSubsystem implements IStatsSubsystem
}
/**
- * Initializes this subsystem with the given
- * configuration store.
- * It first initializes resident subsystems,
- * and it loads and initializes loadable
- * subsystem specified in the configuration
- * store.
+ * Initializes this subsystem with the given configuration store. It first
+ * initializes resident subsystems, and it loads and initializes loadable
+ * subsystem specified in the configuration store.
* <P>
- * Note that individual subsystem should be
- * initialized in a separated thread if
- * it has dependency on the initialization
- * of other subsystems.
+ * Note that individual subsystem should be initialized in a separated
+ * thread if it has dependency on the initialization of other subsystems.
* <P>
- *
+ *
* @param owner owner of this subsystem
* @param config configuration store
*/
public synchronized void init(ISubsystem owner, IConfigStore config)
- throws EBaseException
- {
- }
-
- public Date getStartTime()
- {
- return mStartTime;
- }
-
- public void startTiming(String id)
- {
- startTiming(id, false /* not the main */);
- }
-
- public void startTiming(String id, boolean mainAction)
- {
- Thread t = Thread.currentThread();
- Vector milestones = null;
- if (mHashtable.containsKey(t.toString())) {
- milestones = (Vector)mHashtable.get(t.toString());
- } else {
- milestones = new Vector();
- mHashtable.put(t.toString(), milestones);
- }
- long startTime = CMS.getCurrentDate().getTime();
- StatsEvent currentST = null;
- for (int i = 0; i < milestones.size(); i++) {
- StatsMilestone se = (StatsMilestone)milestones.elementAt(i);
- if (currentST == null) {
- currentST = mAllTrans.getSubEvent(se.getId());
+ throws EBaseException {
+ }
+
+ public Date getStartTime() {
+ return mStartTime;
+ }
+
+ public void startTiming(String id) {
+ startTiming(id, false /* not the main */);
+ }
+
+ public void startTiming(String id, boolean mainAction) {
+ Thread t = Thread.currentThread();
+ Vector milestones = null;
+ if (mHashtable.containsKey(t.toString())) {
+ milestones = (Vector) mHashtable.get(t.toString());
} else {
- currentST = currentST.getSubEvent(se.getId());
+ milestones = new Vector();
+ mHashtable.put(t.toString(), milestones);
+ }
+ long startTime = CMS.getCurrentDate().getTime();
+ StatsEvent currentST = null;
+ for (int i = 0; i < milestones.size(); i++) {
+ StatsMilestone se = (StatsMilestone) milestones.elementAt(i);
+ if (currentST == null) {
+ currentST = mAllTrans.getSubEvent(se.getId());
+ } else {
+ currentST = currentST.getSubEvent(se.getId());
+ }
+ }
+ if (currentST == null) {
+ if (!mainAction) {
+ return; /* ignore none main action */
+ }
+ currentST = mAllTrans;
+ }
+ StatsEvent newST = currentST.getSubEvent(id);
+ if (newST == null) {
+ newST = new StatsEvent(currentST);
+ newST.setName(id);
+ currentST.addSubEvent(newST);
+ }
+ milestones.addElement(new StatsMilestone(id, startTime, newST));
+ }
+
+ public void endTiming(String id) {
+ long endTime = CMS.getCurrentDate().getTime();
+ Thread t = Thread.currentThread();
+ if (!mHashtable.containsKey(t.toString())) {
+ return; /* error */
+ }
+ Vector milestones = (Vector) mHashtable.get(t.toString());
+ if (milestones.size() == 0) {
+ return; /* error */
+ }
+ StatsMilestone last = (StatsMilestone) milestones.remove(milestones.size() - 1);
+ StatsEvent st = last.getStatsEvent();
+ st.incNoOfOperations(1);
+ st.incTimeTaken(endTime - last.getStartTime());
+ if (milestones.size() == 0) {
+ mHashtable.remove(t.toString());
}
- }
- if (currentST == null) {
- if (!mainAction) {
- return; /* ignore none main action */
- }
- currentST = mAllTrans;
- }
- StatsEvent newST = currentST.getSubEvent(id);
- if (newST == null) {
- newST = new StatsEvent(currentST);
- newST.setName(id);
- currentST.addSubEvent(newST);
- }
- milestones.addElement(new StatsMilestone(id, startTime, newST));
- }
-
- public void endTiming(String id)
- {
- long endTime = CMS.getCurrentDate().getTime();
- Thread t = Thread.currentThread();
- if (!mHashtable.containsKey(t.toString())) {
- return; /* error */
- }
- Vector milestones = (Vector)mHashtable.get(t.toString());
- if (milestones.size() == 0) {
- return; /* error */
- }
- StatsMilestone last = (StatsMilestone)milestones.remove(milestones.size() - 1);
- StatsEvent st = last.getStatsEvent();
- st.incNoOfOperations(1);
- st.incTimeTaken(endTime - last.getStartTime());
- if (milestones.size() == 0) {
- mHashtable.remove(t.toString());
- }
- }
-
- public void resetCounters()
- {
- mStartTime = CMS.getCurrentDate();
- mAllTrans.resetCounters();
- }
-
- public StatsEvent getMainStatsEvent()
- {
- return mAllTrans;
+ }
+
+ public void resetCounters() {
+ mStartTime = CMS.getCurrentDate();
+ mAllTrans.resetCounters();
+ }
+
+ public StatsEvent getMainStatsEvent() {
+ return mAllTrans;
}
public void startup() throws EBaseException {
@@ -171,9 +156,8 @@ public class StatsSubsystem implements IStatsSubsystem
}
/*
- * Returns the root configuration storage of this system.
- * <P>
- *
+ * Returns the root configuration storage of this system. <P>
+ *
* @return configuration store of this subsystem
*/
public IConfigStore getConfigStore() {
@@ -181,31 +165,26 @@ public class StatsSubsystem implements IStatsSubsystem
}
}
-class StatsMilestone
-{
- private String mId = null;
- private long mStartTime = 0;
- private StatsEvent mST = null;
-
- public StatsMilestone(String id, long startTime, StatsEvent st)
- {
- mId = id;
- mStartTime = startTime;
- mST = st;
- }
-
- public String getId()
- {
- return mId;
- }
-
- public long getStartTime()
- {
- return mStartTime;
- }
-
- public StatsEvent getStatsEvent()
- {
- return mST;
- }
+class StatsMilestone {
+ private String mId = null;
+ private long mStartTime = 0;
+ private StatsEvent mST = null;
+
+ public StatsMilestone(String id, long startTime, StatsEvent st) {
+ mId = id;
+ mStartTime = startTime;
+ mST = st;
+ }
+
+ public String getId() {
+ return mId;
+ }
+
+ public long getStartTime() {
+ return mStartTime;
+ }
+
+ public StatsEvent getStatsEvent() {
+ return mST;
+ }
}
diff --git a/pki/base/common/src/com/netscape/cmscore/util/UtilMessage.java b/pki/base/common/src/com/netscape/cmscore/util/UtilMessage.java
index a69a976c..8f82c784 100644
--- a/pki/base/common/src/com/netscape/cmscore/util/UtilMessage.java
+++ b/pki/base/common/src/com/netscape/cmscore/util/UtilMessage.java
@@ -17,16 +17,14 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.util;
-
import java.util.Locale;
import com.netscape.certsrv.base.MessageFormatter;
-
/**
- * This object is used to easily create I18N messages for utility
- * classes and standalone programs.
- *
+ * This object is used to easily create I18N messages for utility classes and
+ * standalone programs.
+ *
* @author mikep
* @version $Revision$, $Date$
* @see com.netscape.certsrv.base.MessageFormatter
@@ -46,7 +44,7 @@ public class UtilMessage {
/**
* Constructs a message event
* <P>
- *
+ *
* @param msgFormat the message string
*/
public UtilMessage(String msgFormat) {
@@ -56,11 +54,12 @@ public class UtilMessage {
/**
* Constructs a message with a parameter. For example,
+ *
* <PRE>
- * new UtilMessage("failed to load {0}", fileName);
+ * new UtilMessage(&quot;failed to load {0}&quot;, fileName);
* </PRE>
* <P>
- *
+ *
* @param msgFormat details in message string format
* @param param message string parameter
*/
@@ -71,9 +70,9 @@ public class UtilMessage {
}
/**
- * Constructs a message from an exception. It can be used to carry
- * a system exception that may contain information about
- * the context. For example,
+ * Constructs a message from an exception. It can be used to carry a system
+ * exception that may contain information about the context. For example,
+ *
* <PRE>
* try {
* ...
@@ -82,7 +81,7 @@ public class UtilMessage {
* }
* </PRE>
* <P>
- *
+ *
* @param msgFormat exception details in message string format
* @param exception system exception
*/
@@ -95,6 +94,7 @@ public class UtilMessage {
/**
* Constructs a message from a base exception. This will use the msgFormat
* from the exception itself.
+ *
* <PRE>
* try {
* ...
@@ -103,7 +103,7 @@ public class UtilMessage {
* }
* </PRE>
* <P>
- *
+ *
* @param exception CMS exception
*/
public UtilMessage(Exception e) {
@@ -113,10 +113,10 @@ public class UtilMessage {
}
/**
- * Constructs a message event with a list of parameters
- * that will be substituted into the message format.
+ * Constructs a message event with a list of parameters that will be
+ * substituted into the message format.
* <P>
- *
+ *
* @param msgFormat message string format
* @param params list of message format parameters
*/
@@ -128,7 +128,7 @@ public class UtilMessage {
/**
* Returns the current message format string.
* <P>
- *
+ *
* @return details message
*/
public String getMessage() {
@@ -138,7 +138,7 @@ public class UtilMessage {
/**
* Returns a list of parameters.
* <P>
- *
+ *
* @return list of message format parameters
*/
public Object[] getParameters() {
@@ -146,10 +146,10 @@ public class UtilMessage {
}
/**
- * Returns localized message string. This method should
- * only be called if a localized string is necessary.
+ * Returns localized message string. This method should only be called if a
+ * localized string is necessary.
* <P>
- *
+ *
* @return details message
*/
public String toString() {
@@ -159,7 +159,7 @@ public class UtilMessage {
/**
* Returns the string based on the given locale.
* <P>
- *
+ *
* @param locale locale
* @return details message
*/
@@ -170,8 +170,8 @@ public class UtilMessage {
}
/**
- * Gets the resource bundle name for this class instance. This should
- * be overridden by subclasses who have their own resource bundles.
+ * Gets the resource bundle name for this class instance. This should be
+ * overridden by subclasses who have their own resource bundles.
*/
protected String getBundleName() {
return mBundleName;
diff --git a/pki/base/common/src/com/netscape/cmscore/util/UtilResources.java b/pki/base/common/src/com/netscape/cmscore/util/UtilResources.java
index 5892adc3..1e957cb9 100644
--- a/pki/base/common/src/com/netscape/cmscore/util/UtilResources.java
+++ b/pki/base/common/src/com/netscape/cmscore/util/UtilResources.java
@@ -17,14 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.util;
-
import java.util.ListResourceBundle;
-
/**
* A class represents a resource bundle for miscellanous utilities
* <P>
- *
+ *
* @author mikep
* @version $Revision$, $Date$
* @see java.util.ListResourceBundle
@@ -39,8 +37,7 @@ public class UtilResources extends ListResourceBundle {
}
/**
- * Constants. The suffix represents the number of
- * possible parameters.
+ * Constants. The suffix represents the number of possible parameters.
*/
public final static String HASH_FILE_CHECK_USAGE = "hashFileCheckUsage";
public final static String BAD_ARG_COUNT = "badArgCount";
@@ -57,18 +54,18 @@ public class UtilResources extends ListResourceBundle {
public final static String RESTART_SIG = "restartSignal";
static final Object[][] contents = {
- {HASH_FILE_CHECK_USAGE, "usage: HashFileCheck <filename>"},
- {BAD_ARG_COUNT, "incorrect number of arguments"},
- {NO_SUCH_FILE_1, "can''t find file {0}"},
- {FILE_TRUNCATED, "Log file has been truncated."},
- {DIGEST_MATCH_1, "Hash digest matches log file. {0} OK"},
- {DIGEST_DONT_MATCH_1, "Hash digest does NOT match log file. {0} and/or hash file is corrupt or the password is incorrect."},
- {EXCEPTION_1, "Caught unexpected exception {0}"},
- {LOG_PASSWORD, "Please enter the log file hash digest password: "},
- {NO_USERID, "No user id in config file. Running as {0}"},
- {NO_SUCH_USER_2, "No such user as {0}. Running as {1}"},
- {NO_UID_PERMISSION_2, "Can''t change process uid to {0}. Running as {1}"},
- {SHUTDOWN_SIG, "Received shutdown signal"},
- {RESTART_SIG, "Received restart signal"},
+ { HASH_FILE_CHECK_USAGE, "usage: HashFileCheck <filename>" },
+ { BAD_ARG_COUNT, "incorrect number of arguments" },
+ { NO_SUCH_FILE_1, "can''t find file {0}" },
+ { FILE_TRUNCATED, "Log file has been truncated." },
+ { DIGEST_MATCH_1, "Hash digest matches log file. {0} OK" },
+ { DIGEST_DONT_MATCH_1, "Hash digest does NOT match log file. {0} and/or hash file is corrupt or the password is incorrect." },
+ { EXCEPTION_1, "Caught unexpected exception {0}" },
+ { LOG_PASSWORD, "Please enter the log file hash digest password: " },
+ { NO_USERID, "No user id in config file. Running as {0}" },
+ { NO_SUCH_USER_2, "No such user as {0}. Running as {1}" },
+ { NO_UID_PERMISSION_2, "Can''t change process uid to {0}. Running as {1}" },
+ { SHUTDOWN_SIG, "Received shutdown signal" },
+ { RESTART_SIG, "Received restart signal" },
};
}
diff --git a/pki/base/common/test/com/netscape/certsrv/app/CMSEngineDefaultStub.java b/pki/base/common/test/com/netscape/certsrv/app/CMSEngineDefaultStub.java
index c01ec33e..d2ba6c19 100644
--- a/pki/base/common/test/com/netscape/certsrv/app/CMSEngineDefaultStub.java
+++ b/pki/base/common/test/com/netscape/certsrv/app/CMSEngineDefaultStub.java
@@ -126,7 +126,7 @@ public class CMSEngineDefaultStub implements ICMSEngine {
return false;
}
- public Enumeration <String> getSubsystemNames() {
+ public Enumeration<String> getSubsystemNames() {
return null;
}
@@ -261,14 +261,16 @@ public class CMSEngineDefaultStub implements ICMSEngine {
public String getFingerPrints(Certificate cert) throws NoSuchAlgorithmException, CertificateEncodingException {
return null;
}/*
- * Returns the finger print of the given certificate.
-*
-* @param certDer DER byte array of certificate
-* @return finger print of certificate
-*/
-public String getFingerPrints(byte[] certDer) throws NoSuchAlgorithmException {
- return null;
-}
+ * Returns the finger print of the given certificate.
+ *
+ * @param certDer DER byte array of certificate
+ *
+ * @return finger print of certificate
+ */
+
+ public String getFingerPrints(byte[] certDer) throws NoSuchAlgorithmException {
+ return null;
+ }
public IRepositoryRecord createRepositoryRecord() {
return null;
@@ -459,7 +461,6 @@ public String getFingerPrints(byte[] certDer) throws NoSuchAlgorithmException {
return null;
}
-
public IGeneralNamesConfig createGeneralNamesConfig(String name, IConfigStore config, boolean isValueConfigured, boolean isPolicyEnabled) throws EBaseException {
return null;
}
@@ -472,7 +473,6 @@ public String getFingerPrints(byte[] certDer) throws NoSuchAlgorithmException {
return null;
}
-
public ISubjAltNameConfig createSubjAltNameConfig(String name, IConfigStore config, boolean isValueConfigured) throws EBaseException {
return null;
}
@@ -511,7 +511,6 @@ public String getFingerPrints(byte[] certDer) throws NoSuchAlgorithmException {
return null;
}
-
public boolean isRevoked(X509Certificate[] certificates) {
return false;
}
@@ -537,89 +536,89 @@ public String getFingerPrints(byte[] certDer) throws NoSuchAlgorithmException {
return null;
}
- @Override
- public String getEEClientAuthSSLPort() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public boolean verifySystemCerts() {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public boolean verifySystemCertByTag(String tag) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public boolean verifySystemCertByNickname(String nickname,
- String certificateUsage) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public CertificateUsage getCertificateUsage(String certusage) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public void getGeneralNameConfigDefaultParams(String name,
- boolean isValueConfigured, Vector<String> params) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void getGeneralNamesConfigDefaultParams(String name,
- boolean isValueConfigured, Vector<String> params) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void getGeneralNameConfigExtendedPluginInfo(String name,
- boolean isValueConfigured, Vector<String> info) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void getGeneralNamesConfigExtendedPluginInfo(String name,
- boolean isValueConfigured, Vector<String> info) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void getSubjAltNameConfigDefaultParams(String name,
- Vector<String> params) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void getSubjAltNameConfigExtendedPluginInfo(String name,
- Vector<String> params) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public IArgBlock createArgBlock(String realm,
- Hashtable<String, String> httpReq) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public IArgBlock createArgBlock(Hashtable<String, String> httpReq) {
- // TODO Auto-generated method stub
- return null;
- }
+ @Override
+ public String getEEClientAuthSSLPort() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public boolean verifySystemCerts() {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public boolean verifySystemCertByTag(String tag) {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public boolean verifySystemCertByNickname(String nickname,
+ String certificateUsage) {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public CertificateUsage getCertificateUsage(String certusage) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public void getGeneralNameConfigDefaultParams(String name,
+ boolean isValueConfigured, Vector<String> params) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void getGeneralNamesConfigDefaultParams(String name,
+ boolean isValueConfigured, Vector<String> params) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void getGeneralNameConfigExtendedPluginInfo(String name,
+ boolean isValueConfigured, Vector<String> info) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void getGeneralNamesConfigExtendedPluginInfo(String name,
+ boolean isValueConfigured, Vector<String> info) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void getSubjAltNameConfigDefaultParams(String name,
+ Vector<String> params) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void getSubjAltNameConfigExtendedPluginInfo(String name,
+ Vector<String> params) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public IArgBlock createArgBlock(String realm,
+ Hashtable<String, String> httpReq) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public IArgBlock createArgBlock(Hashtable<String, String> httpReq) {
+ // TODO Auto-generated method stub
+ return null;
+ }
}
diff --git a/pki/base/common/test/com/netscape/certsrv/authentication/AuthTokenTest.java b/pki/base/common/test/com/netscape/certsrv/authentication/AuthTokenTest.java
index 3f83b3b0..2b8c0c25 100644
--- a/pki/base/common/test/com/netscape/certsrv/authentication/AuthTokenTest.java
+++ b/pki/base/common/test/com/netscape/certsrv/authentication/AuthTokenTest.java
@@ -48,7 +48,7 @@ public class AuthTokenTest extends CMSBaseTestCase {
assertEquals("value", authToken.mAttrs.get("key"));
assertEquals("value", authToken.getInString("key"));
- assertFalse(authToken.set("key", (String)null));
+ assertFalse(authToken.set("key", (String) null));
}
public void testGetSetByteArray() {
@@ -62,7 +62,7 @@ public class AuthTokenTest extends CMSBaseTestCase {
byte[] retval = authToken.getInByteArray("key");
assertEquals(data, retval);
- assertFalse(authToken.set("key2", (byte[])null));
+ assertFalse(authToken.set("key2", (byte[]) null));
}
public void testGetSetInteger() {
@@ -75,7 +75,7 @@ public class AuthTokenTest extends CMSBaseTestCase {
authToken.set("key2", "value");
assertNull(authToken.getInInteger("key2"));
- assertFalse(authToken.set("key3", (Integer)null));
+ assertFalse(authToken.set("key3", (Integer) null));
}
public void testGetSetBigIntegerArray() {
@@ -102,11 +102,11 @@ public class AuthTokenTest extends CMSBaseTestCase {
assertNull(authToken.getInBigIntegerArray("key3"));
// corner case test
- authToken.set("key",",");
+ authToken.set("key", ",");
retval = authToken.getInBigIntegerArray("key");
assertNull(retval);
- assertFalse(authToken.set("key4", (BigInteger[])null));
+ assertFalse(authToken.set("key4", (BigInteger[]) null));
}
public void testGetSetDate() {
@@ -123,7 +123,7 @@ public class AuthTokenTest extends CMSBaseTestCase {
authToken.set("key3", "oops");
assertNull(authToken.getInDate("key3"));
- assertFalse(authToken.set("key4", (Date)null));
+ assertFalse(authToken.set("key4", (Date) null));
}
public void testGetSetStringArray() throws IOException {
@@ -145,16 +145,15 @@ public class AuthTokenTest extends CMSBaseTestCase {
assertEquals(value[3], retval[3]);
// illegal value parsing
- authToken.set("key2", new byte[] { 1, 2, 3, 4});
+ authToken.set("key2", new byte[] { 1, 2, 3, 4 });
assertNull(authToken.getInStringArray("key2"));
-
DerOutputStream out = new DerOutputStream();
out.putPrintableString("testing");
authToken.set("key3", out.toByteArray());
assertNull(authToken.getInStringArray("key3"));
- assertFalse(authToken.set("key4", (String[])null));
+ assertFalse(authToken.set("key4", (String[]) null));
}
public void testGetSetCert() throws CertificateException {
@@ -170,7 +169,7 @@ public class AuthTokenTest extends CMSBaseTestCase {
assertNotNull(retval);
assertEquals(cert, retval);
- assertFalse(authToken.set("key2", (X509CertImpl)null));
+ assertFalse(authToken.set("key2", (X509CertImpl) null));
}
public void testGetSetCertExts() throws IOException {
@@ -191,13 +190,13 @@ public class AuthTokenTest extends CMSBaseTestCase {
assertNotNull(retval);
assertEquals(1, retval.size());
- assertFalse(authToken.set("key3", (CertificateExtensions)null));
+ assertFalse(authToken.set("key3", (CertificateExtensions) null));
}
public void testGetSetCertificates() throws CertificateException {
X509CertImpl cert1 = getFakeCert();
X509CertImpl cert2 = getFakeCert();
- X509CertImpl[] certArray = new X509CertImpl[] {cert1, cert2};
+ X509CertImpl[] certArray = new X509CertImpl[] { cert1, cert2 };
Certificates certs = new Certificates(certArray);
assertFalse(cmsStub.bToACalled);
@@ -214,14 +213,14 @@ public class AuthTokenTest extends CMSBaseTestCase {
assertEquals(cert1, retCerts[0]);
assertEquals(cert2, retCerts[1]);
- assertFalse(authToken.set("key2", (Certificates)null));
+ assertFalse(authToken.set("key2", (Certificates) null));
}
public void testGetSetByteArrayArray() {
byte[][] value = new byte[][] {
new byte[] { 1, 2, 3, 4 },
- new byte[] {12, 13, 14},
- new byte[] { 50, -12, 0, 100}
+ new byte[] { 12, 13, 14 },
+ new byte[] { 50, -12, 0, 100 }
};
assertFalse(cmsStub.bToACalled);
@@ -240,15 +239,15 @@ public class AuthTokenTest extends CMSBaseTestCase {
}
}
- assertFalse(authToken.set("key2", (byte[][])null));
+ assertFalse(authToken.set("key2", (byte[][]) null));
}
/**
* CMSMemoryStub
- *
+ *
* This class is used to help test methods that rely on setting and then
- * getting a value out. It assumes BtoA is always called first, stores
- * the value passed in, and then returns that value for BtoA.
+ * getting a value out. It assumes BtoA is always called first, stores the
+ * value passed in, and then returns that value for BtoA.
*/
class CMSMemoryStub extends CMSEngineDefaultStub {
boolean bToACalled = false;
diff --git a/pki/base/common/test/com/netscape/certsrv/logging/LoggerDefaultStub.java b/pki/base/common/test/com/netscape/certsrv/logging/LoggerDefaultStub.java
index b7772bb2..a0ffe5e0 100644
--- a/pki/base/common/test/com/netscape/certsrv/logging/LoggerDefaultStub.java
+++ b/pki/base/common/test/com/netscape/certsrv/logging/LoggerDefaultStub.java
@@ -56,7 +56,7 @@ public class LoggerDefaultStub implements ILogger {
public void log(int evtClass, Properties prop, int source, int level, String msg, Object params[], boolean multiline) {
}
-
+
public ILogEvent create(int evtClass, Properties prop, int source, int level, String msg, Object params[], boolean multiline) {
return null;
}
diff --git a/pki/base/common/test/com/netscape/certsrv/request/AgentApprovalsTest.java b/pki/base/common/test/com/netscape/certsrv/request/AgentApprovalsTest.java
index 28ea1669..0cd27840 100644
--- a/pki/base/common/test/com/netscape/certsrv/request/AgentApprovalsTest.java
+++ b/pki/base/common/test/com/netscape/certsrv/request/AgentApprovalsTest.java
@@ -48,15 +48,15 @@ public class AgentApprovalsTest extends CMSBaseTestCase {
assertNotNull(approvals);
assertEquals(3, approvals.mVector.size());
- AgentApproval approval = (AgentApproval)approvals.mVector.get(0);
+ AgentApproval approval = (AgentApproval) approvals.mVector.get(0);
assertEquals(approval1.getUserName(), approval.getUserName());
assertEquals(approval1.getDate(), approval.getDate());
- approval = (AgentApproval)approvals.mVector.get(1);
+ approval = (AgentApproval) approvals.mVector.get(1);
assertEquals(approval2.getUserName(), approval.getUserName());
assertEquals(approval2.getDate(), approval.getDate());
- approval = (AgentApproval)approvals.mVector.get(2);
+ approval = (AgentApproval) approvals.mVector.get(2);
assertEquals(approval3.getUserName(), approval.getUserName());
assertEquals(approval3.getDate(), approval.getDate());
diff --git a/pki/base/common/test/com/netscape/cmscore/dbs/CertRecordListTest.java b/pki/base/common/test/com/netscape/cmscore/dbs/CertRecordListTest.java
index 3fd6a96f..699a924d 100644
--- a/pki/base/common/test/com/netscape/cmscore/dbs/CertRecordListTest.java
+++ b/pki/base/common/test/com/netscape/cmscore/dbs/CertRecordListTest.java
@@ -40,7 +40,7 @@ public class CertRecordListTest extends CMSBaseTestCase {
return new TestSuite(CertRecordListTest.class);
}
- public void testProcessCertRecordsUsesSize() throws EBaseException {
+ public void testProcessCertRecordsUsesSize() throws EBaseException {
DBVirtualListStub dbList = new DBVirtualListStub();
dbList.size = 5;
@@ -57,7 +57,6 @@ public class CertRecordListTest extends CMSBaseTestCase {
assertEquals(7, dbList.lastIndexGetElementAtCalledWith);
}
-
public class DBVirtualListStub extends DBVirtualListDefaultStub {
public int size = 0;
public int getElementAtCallCount = 0;
diff --git a/pki/base/common/test/com/netscape/cmscore/dbs/DBRegistryDefaultStub.java b/pki/base/common/test/com/netscape/cmscore/dbs/DBRegistryDefaultStub.java
index 2095e162..9635129f 100644
--- a/pki/base/common/test/com/netscape/cmscore/dbs/DBRegistryDefaultStub.java
+++ b/pki/base/common/test/com/netscape/cmscore/dbs/DBRegistryDefaultStub.java
@@ -17,7 +17,6 @@ import com.netscape.certsrv.dbs.IFilterConverter;
*/
public class DBRegistryDefaultStub implements IDBRegistry {
-
public void registerObjectClass(String className, String ldapNames[]) throws EDBException {
}
diff --git a/pki/base/common/test/com/netscape/cmscore/dbs/DBRegistryTest.java b/pki/base/common/test/com/netscape/cmscore/dbs/DBRegistryTest.java
index 7b4681e5..c4564323 100644
--- a/pki/base/common/test/com/netscape/cmscore/dbs/DBRegistryTest.java
+++ b/pki/base/common/test/com/netscape/cmscore/dbs/DBRegistryTest.java
@@ -40,7 +40,7 @@ public class DBRegistryTest extends CMSBaseTestCase {
extAttrMapper = new DBDynAttrMapperStub();
try {
registry.registerObjectClass(requestRecordStub.getClass().getName(),
- new String[] {"ocvalue"} );
+ new String[] { "ocvalue" });
registry.registerAttribute(IRequestRecord.ATTR_EXT_DATA, extAttrMapper);
registry.registerAttribute(IRequestRecord.ATTR_SOURCE_ID,
new StringMapper("sourceIdOut"));
@@ -64,7 +64,7 @@ public class DBRegistryTest extends CMSBaseTestCase {
assertTrue(extAttrMapper.mapObjectCalled);
}
- public void testGetLDAPAttributesForExtData() throws EBaseException {
+ public void testGetLDAPAttributesForExtData() throws EBaseException {
String inAttrs[] = new String[] {
"extData-foo",
"extData-foo12",
@@ -79,9 +79,10 @@ public class DBRegistryTest extends CMSBaseTestCase {
assertTrue(TestHelper.contains(outAttrs, "sourceIdOut"));
try {
- registry.getLDAPAttributes(new String[] {"badattr"});
+ registry.getLDAPAttributes(new String[] { "badattr" });
fail("Should not be able to map badattr");
- } catch (EBaseException e) { /* good */ }
+ } catch (EBaseException e) { /* good */
+ }
}
public void testCreateLDAPAttributeSet() throws EBaseException {
@@ -109,7 +110,6 @@ public class DBRegistryTest extends CMSBaseTestCase {
assertTrue(extAttrMapper.mapLDAPAttrsCalled);
}
-
class DBSubsystemStub extends DBSubsystemDefaultStub {
DBRegistry registry;
@@ -118,7 +118,6 @@ public class DBRegistryTest extends CMSBaseTestCase {
}
}
-
class DBDynAttrMapperStub extends DBDynAttrMapperDefaultStub {
boolean mapObjectCalled = false;
Object mapObjectCalledWithObject = null;
@@ -146,10 +145,10 @@ public class DBRegistryTest extends CMSBaseTestCase {
/*
* This class is purposefully placed outside the test because
- * DBRegistry.createObject() calls Class.newInstance() to create
- * this stub. This fails if the class is nested.
+ * DBRegistry.createObject() calls Class.newInstance() to create this stub. This
+ * fails if the class is nested.
*/
- class RequestRecordStub extends RequestRecordDefaultStub {
+class RequestRecordStub extends RequestRecordDefaultStub {
/**
*
diff --git a/pki/base/common/test/com/netscape/cmscore/dbs/DBSubsystemDefaultStub.java b/pki/base/common/test/com/netscape/cmscore/dbs/DBSubsystemDefaultStub.java
index 68f24d50..fe19159d 100644
--- a/pki/base/common/test/com/netscape/cmscore/dbs/DBSubsystemDefaultStub.java
+++ b/pki/base/common/test/com/netscape/cmscore/dbs/DBSubsystemDefaultStub.java
@@ -17,7 +17,6 @@ import com.netscape.certsrv.dbs.IDBSubsystem;
*/
public class DBSubsystemDefaultStub implements IDBSubsystem {
-
public String getBaseDN() {
return null;
}
@@ -83,91 +82,91 @@ public class DBSubsystemDefaultStub implements IDBSubsystem {
return null;
}
- @Override
- public void setMaxSerialConfig(int repo, String serial)
- throws EBaseException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void setMinSerialConfig(int repo, String serial)
- throws EBaseException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void setNextMaxSerialConfig(int repo, String serial)
- throws EBaseException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void setNextMinSerialConfig(int repo, String serial)
- throws EBaseException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public String getMinSerialConfig(int repo) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getMaxSerialConfig(int repo) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getNextMaxSerialConfig(int repo) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getNextMinSerialConfig(int repo) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getLowWaterMarkConfig(int repo) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getIncrementConfig(int repo) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getNextRange(int repo) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public boolean hasRangeConflict(int repo) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public boolean getEnableSerialMgmt() {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public void setEnableSerialMgmt(boolean value) throws EBaseException {
- // TODO Auto-generated method stub
-
- }
+ @Override
+ public void setMaxSerialConfig(int repo, String serial)
+ throws EBaseException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void setMinSerialConfig(int repo, String serial)
+ throws EBaseException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void setNextMaxSerialConfig(int repo, String serial)
+ throws EBaseException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void setNextMinSerialConfig(int repo, String serial)
+ throws EBaseException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public String getMinSerialConfig(int repo) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getMaxSerialConfig(int repo) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getNextMaxSerialConfig(int repo) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getNextMinSerialConfig(int repo) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getLowWaterMarkConfig(int repo) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getIncrementConfig(int repo) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getNextRange(int repo) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public boolean hasRangeConflict(int repo) {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public boolean getEnableSerialMgmt() {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public void setEnableSerialMgmt(boolean value) throws EBaseException {
+ // TODO Auto-generated method stub
+
+ }
}
diff --git a/pki/base/common/test/com/netscape/cmscore/dbs/DBVirtualListDefaultStub.java b/pki/base/common/test/com/netscape/cmscore/dbs/DBVirtualListDefaultStub.java
index 45fda77d..294ae1df 100644
--- a/pki/base/common/test/com/netscape/cmscore/dbs/DBVirtualListDefaultStub.java
+++ b/pki/base/common/test/com/netscape/cmscore/dbs/DBVirtualListDefaultStub.java
@@ -22,11 +22,11 @@ import com.netscape.certsrv.dbs.IDBVirtualList;
import com.netscape.certsrv.dbs.IElementProcessor;
/**
- * A default stub ojbect for tests to extend.
- * This class helps test avoid the problem of test stubs having to
- * implement a new stub method every time the interface changes.
- * It also makes the tests clearer by not cluttered them with empty methods.
- *
+ * A default stub ojbect for tests to extend. This class helps test avoid the
+ * problem of test stubs having to implement a new stub method every time the
+ * interface changes. It also makes the tests clearer by not cluttered them with
+ * empty methods.
+ *
* Do not put any behaviour in this class.
*/
public class DBVirtualListDefaultStub implements IDBVirtualList {
@@ -73,7 +73,7 @@ public class DBVirtualListDefaultStub implements IDBVirtualList {
}
public void processElements(int startidx, int endidx, IElementProcessor ep)
- throws EBaseException {
+ throws EBaseException {
}
public int getSelectedIndex() {
diff --git a/pki/base/common/test/com/netscape/cmscore/request/ExtAttrDynMapperTest.java b/pki/base/common/test/com/netscape/cmscore/request/ExtAttrDynMapperTest.java
index f47cbe0a..a0ad0a8a 100644
--- a/pki/base/common/test/com/netscape/cmscore/request/ExtAttrDynMapperTest.java
+++ b/pki/base/common/test/com/netscape/cmscore/request/ExtAttrDynMapperTest.java
@@ -37,7 +37,7 @@ public class ExtAttrDynMapperTest extends CMSBaseTestCase {
public void testSupportLDAPAttributeName() {
assertNotNull(mapper);
-
+
assertTrue(mapper.supportsLDAPAttributeName("extData-green"));
assertTrue(mapper.supportsLDAPAttributeName("EXTDATA-green"));
assertTrue(mapper.supportsLDAPAttributeName("extData-foo;0"));
@@ -165,7 +165,6 @@ public class ExtAttrDynMapperTest extends CMSBaseTestCase {
assertTrue(attrBim.hasSubtype("bi--003bm"));
}
-
public void testMapLDAPAttributeSetToObject() throws EBaseException {
//
// Test simple key-value pairs
@@ -183,7 +182,7 @@ public class ExtAttrDynMapperTest extends CMSBaseTestCase {
requestRecord);
assertEquals(1, requestRecord.setCallCounter);
- Hashtable<?, ?> extData = (Hashtable<?, ?>)requestRecord.extAttrData.get(
+ Hashtable<?, ?> extData = (Hashtable<?, ?>) requestRecord.extAttrData.get(
IRequestRecord.ATTR_EXT_DATA);
assertNotNull(extData);
@@ -215,27 +214,27 @@ public class ExtAttrDynMapperTest extends CMSBaseTestCase {
requestRecord);
assertEquals(1, requestRecord.setCallCounter);
- extData = (Hashtable<?, ?>)requestRecord.extAttrData.get(
+ extData = (Hashtable<?, ?>) requestRecord.extAttrData.get(
IRequestRecord.ATTR_EXT_DATA);
assertNotNull(extData);
assertTrue(extData.containsKey("o;key1"));
- Hashtable<?, ?> okey1Data = (Hashtable<?, ?>)extData.get("o;key1");
+ Hashtable<?, ?> okey1Data = (Hashtable<?, ?>) extData.get("o;key1");
assertEquals(3, okey1Data.keySet().size());
assertTrue(okey1Data.containsKey("i;key11"));
- assertEquals("val11", (String)okey1Data.get("i;key11"));
+ assertEquals("val11", (String) okey1Data.get("i;key11"));
assertTrue(okey1Data.containsKey("ikey12"));
- assertEquals("val12", (String)okey1Data.get("ikey12"));
+ assertEquals("val12", (String) okey1Data.get("ikey12"));
assertTrue(okey1Data.containsKey("ikey13"));
- assertEquals("val13", (String)okey1Data.get("ikey13"));
+ assertEquals("val13", (String) okey1Data.get("ikey13"));
assertTrue(extData.containsKey("okey2"));
- Hashtable<?, ?> okey2Data = (Hashtable<?, ?>)extData.get("okey2");
+ Hashtable<?, ?> okey2Data = (Hashtable<?, ?>) extData.get("okey2");
assertEquals(2, okey2Data.keySet().size());
assertTrue(okey2Data.containsKey("ikey21"));
- assertEquals("val21", (String)okey2Data.get("ikey21"));
+ assertEquals("val21", (String) okey2Data.get("ikey21"));
assertTrue(okey2Data.containsKey("ikey22"));
- assertEquals("val22", (String)okey2Data.get("ikey22"));
+ assertEquals("val22", (String) okey2Data.get("ikey22"));
assertFalse(extData.containsKey("foo"));
@@ -260,13 +259,11 @@ public class ExtAttrDynMapperTest extends CMSBaseTestCase {
}
-
class RequestRecordStub extends RequestRecordDefaultStub {
private static final long serialVersionUID = 4106967075497999274L;
Hashtable<String, Object> extAttrData = new Hashtable<String, Object>();
int setCallCounter = 0;
-
public void set(String name, Object o) {
setCallCounter++;
if (IRequestRecord.ATTR_EXT_DATA.equals(name)) {
diff --git a/pki/base/common/test/com/netscape/cmscore/request/RequestDefaultStub.java b/pki/base/common/test/com/netscape/cmscore/request/RequestDefaultStub.java
index a835ba32..151f3d62 100644
--- a/pki/base/common/test/com/netscape/cmscore/request/RequestDefaultStub.java
+++ b/pki/base/common/test/com/netscape/cmscore/request/RequestDefaultStub.java
@@ -103,7 +103,7 @@ public class RequestDefaultStub implements IRequest {
return false;
}
- public boolean setExtData(String key, Hashtable<String, ?> value) {
+ public boolean setExtData(String key, Hashtable<String, ?> value) {
return false;
}
@@ -115,7 +115,7 @@ public class RequestDefaultStub implements IRequest {
return null;
}
- public <V> Hashtable<String, V> getExtDataInHashtable(String key){
+ public <V> Hashtable<String, V> getExtDataInHashtable(String key) {
return null;
}
diff --git a/pki/base/common/test/com/netscape/cmscore/request/RequestQueueTest.java b/pki/base/common/test/com/netscape/cmscore/request/RequestQueueTest.java
index 4ae5be9a..d69ac6a5 100644
--- a/pki/base/common/test/com/netscape/cmscore/request/RequestQueueTest.java
+++ b/pki/base/common/test/com/netscape/cmscore/request/RequestQueueTest.java
@@ -41,7 +41,7 @@ public class RequestQueueTest extends CMSBaseTestCase {
}
class RequestStub extends RequestDefaultStub {
- String[] keys = new String[] {"key1", "key2"};
+ String[] keys = new String[] { "key1", "key2" };
boolean getExtDataKeysCalled = false;
public Enumeration getExtDataKeys() {
diff --git a/pki/base/common/test/com/netscape/cmscore/request/RequestRecordTest.java b/pki/base/common/test/com/netscape/cmscore/request/RequestRecordTest.java
index ba3689fb..efdbfc20 100644
--- a/pki/base/common/test/com/netscape/cmscore/request/RequestRecordTest.java
+++ b/pki/base/common/test/com/netscape/cmscore/request/RequestRecordTest.java
@@ -69,7 +69,7 @@ public class RequestRecordTest extends CMSBaseTestCase {
requestRecord.add(request);
- assertEquals(request.mExtData, requestRecord.mExtData);
+ assertEquals(request.mExtData, requestRecord.mExtData);
assertNotSame(request.mExtData, requestRecord.mExtData);
}
@@ -83,7 +83,6 @@ public class RequestRecordTest extends CMSBaseTestCase {
requestRecord.set(IRequestRecord.ATTR_EXT_DATA, extData);
requestRecord.mRequestType = "foo";
-
requestRecord.read(new RequestModDefaultStub(), request);
// the request stores other attributes inside its mExtData when some
@@ -114,12 +113,11 @@ public class RequestRecordTest extends CMSBaseTestCase {
assertTrue(db.registry.registerObjectClassCalled);
assertTrue(TestHelper.contains(db.registry.registerObjectClassLdapNames,
"extensibleObject"));
-
+
assertTrue(db.registry.registerDynamicMapperCalled);
assertTrue(db.registry.dynamicMapper instanceof ExtAttrDynMapper);
}
-
class ModificationSetStub extends ModificationSet {
public boolean addCalledWithExtData = false;
public Object addExtDataObject = null;
@@ -132,17 +130,14 @@ public class RequestRecordTest extends CMSBaseTestCase {
}
}
-
class DBSubsystemStub extends DBSubsystemDefaultStub {
DBRegistryStub registry = new DBRegistryStub();
-
public IDBRegistry getRegistry() {
return registry;
}
}
-
class DBRegistryStub extends DBRegistryDefaultStub {
boolean registerCalledWithExtAttr = false;
IDBAttrMapper extAttrMapper = null;
diff --git a/pki/base/common/test/com/netscape/cmscore/request/RequestTest.java b/pki/base/common/test/com/netscape/cmscore/request/RequestTest.java
index dd1a1612..8d5132d9 100644
--- a/pki/base/common/test/com/netscape/cmscore/request/RequestTest.java
+++ b/pki/base/common/test/com/netscape/cmscore/request/RequestTest.java
@@ -69,7 +69,7 @@ public class RequestTest extends CMSBaseTestCase {
public void testIsSimpleExtDataValue() {
request.mExtData.put("simple1", "foo");
- request.mExtData.put("complex1", new Hashtable<String, Object> ());
+ request.mExtData.put("complex1", new Hashtable<String, Object>());
assertTrue(request.isSimpleExtDataValue("simple1"));
assertFalse(request.isSimpleExtDataValue("complex1"));
@@ -87,12 +87,12 @@ public class RequestTest extends CMSBaseTestCase {
request.setExtData("UPPER", "CASE");
assertEquals("CASE", request.mExtData.get("upper"));
-
- assertFalse(request.setExtData("key", (String)null));
+
+ assertFalse(request.setExtData("key", (String) null));
}
@SuppressWarnings({ "rawtypes", "unchecked" })
- public void testVerifyValidExtDataHashtable() {
+ public void testVerifyValidExtDataHashtable() {
Hashtable valueHash = new Hashtable();
valueHash.put("key1", "val1");
@@ -104,8 +104,8 @@ public class RequestTest extends CMSBaseTestCase {
assertFalse(request.isValidExtDataHashtableValue(valueHash));
valueHash.clear();
- //valueHash.put(new Integer("0"), "bar");
- //assertFalse(request.isValidExtDataHashtableValue(valueHash));
+ // valueHash.put(new Integer("0"), "bar");
+ // assertFalse(request.isValidExtDataHashtableValue(valueHash));
valueHash.clear();
valueHash.put("okay", new Integer(5));
@@ -114,7 +114,7 @@ public class RequestTest extends CMSBaseTestCase {
}
@SuppressWarnings({ "unchecked", "rawtypes" })
- public void testSetExtHashtableData() {
+ public void testSetExtHashtableData() {
Hashtable<String, String> valueHash = new Hashtable<String, String>();
valueHash.put("key1", "val1");
@@ -133,8 +133,8 @@ public class RequestTest extends CMSBaseTestCase {
valueHash.put("", "value");
assertFalse(request.setExtData("topkey2", valueHash));
-
- assertFalse(request.setExtData("topkey3", (Hashtable)null));
+
+ assertFalse(request.setExtData("topkey3", (Hashtable) null));
}
public void testGetExtDataInString() {
@@ -215,9 +215,9 @@ public class RequestTest extends CMSBaseTestCase {
assertFalse(value.containsKey(""));
// Illegal values
- assertFalse(request.setExtData((String)null, "b", "c"));
- assertFalse(request.setExtData("a", (String)null, "c"));
- assertFalse(request.setExtData("a", "b", (String)null));
+ assertFalse(request.setExtData((String) null, "b", "c"));
+ assertFalse(request.setExtData("a", (String) null, "c"));
+ assertFalse(request.setExtData("a", "b", (String) null));
}
public void testGetExtDataSubkeyValue() {
@@ -225,7 +225,7 @@ public class RequestTest extends CMSBaseTestCase {
value.put("subkey", "value");
request.setExtData("topkey", value);
-
+
assertEquals("value", request.getExtDataInString("topkey", "SUBKEY"));
assertNull(request.getExtDataInString("badkey", "subkey"));
assertNull(request.getExtDataInString("topkey", "badkey"));
@@ -244,7 +244,7 @@ public class RequestTest extends CMSBaseTestCase {
assertNull(request.getExtDataInInteger("strkey"));
assertNull(request.getExtDataInInteger("notfound"));
- assertFalse(request.setExtData("key", (Integer)null));
+ assertFalse(request.setExtData("key", (Integer) null));
}
public void testGetSetExtDataIntegerArray() {
@@ -267,7 +267,7 @@ public class RequestTest extends CMSBaseTestCase {
request.setExtData("topkey2", hashValue);
assertNull(request.getExtDataInIntegerArray("topkey2"));
- assertFalse(request.setExtData("key", (Integer[])null));
+ assertFalse(request.setExtData("key", (Integer[]) null));
}
public void testGetSetExtDataBigInteger() {
@@ -283,7 +283,7 @@ public class RequestTest extends CMSBaseTestCase {
assertNull(request.getExtDataInBigInteger("strkey"));
assertNull(request.getExtDataInBigInteger("notfound"));
- assertFalse(request.setExtData("key", (BigInteger)null));
+ assertFalse(request.setExtData("key", (BigInteger) null));
}
public void testGetSetExtDataBigIntegerArray() {
@@ -306,7 +306,7 @@ public class RequestTest extends CMSBaseTestCase {
request.setExtData("topkey2", hashValue);
assertNull(request.getExtDataInBigIntegerArray("topkey2"));
- assertFalse(request.setExtData("key", (BigInteger[])null));
+ assertFalse(request.setExtData("key", (BigInteger[]) null));
}
public void testSetExtDataThrowable() {
@@ -316,7 +316,7 @@ public class RequestTest extends CMSBaseTestCase {
assertEquals(e.toString(), request.mExtData.get("key"));
- assertFalse(request.setExtData("key", (Throwable)null));
+ assertFalse(request.setExtData("key", (Throwable) null));
}
public void testGetSetByteArray() {
@@ -332,7 +332,7 @@ public class RequestTest extends CMSBaseTestCase {
assertTrue(cmsStub.aToBCalled);
assertEquals(data, out);
- assertFalse(request.setExtData("key", (byte[])null));
+ assertFalse(request.setExtData("key", (byte[]) null));
}
public void testGetSetCert() throws CertificateException {
@@ -347,7 +347,7 @@ public class RequestTest extends CMSBaseTestCase {
assertTrue(cmsStub.aToBCalled);
assertEquals(cert, retval);
- assertFalse(request.setExtData("key", (X509CertImpl)null));
+ assertFalse(request.setExtData("key", (X509CertImpl) null));
}
public void testGetSetCertArray() throws CertificateException {
@@ -359,7 +359,7 @@ public class RequestTest extends CMSBaseTestCase {
};
assertTrue(request.setExtData("key", vals));
- Hashtable<?, ?> hashVals = (Hashtable<?, ?>)request.mExtData.get("key");
+ Hashtable<?, ?> hashVals = (Hashtable<?, ?>) request.mExtData.get("key");
assertEquals(2, hashVals.keySet().size());
assertFalse(cmsStub.aToBCalled);
@@ -370,16 +370,16 @@ public class RequestTest extends CMSBaseTestCase {
assertEquals(vals[0], retval[0]);
assertEquals(vals[1], retval[1]);
- assertFalse(request.setExtData("key", (X509CertImpl[])null));
+ assertFalse(request.setExtData("key", (X509CertImpl[]) null));
}
public void testGetSetStringArray() {
- String[] value = new String[] {"blue", "green", "red", "orange"};
+ String[] value = new String[] { "blue", "green", "red", "orange" };
assertTrue(request.setExtData("key", value));
assertTrue(request.mExtData.containsKey("key"));
@SuppressWarnings("unchecked")
- Hashtable<String, String> hashValue = (Hashtable<String, String>)request.mExtData.get("key");
+ Hashtable<String, String> hashValue = (Hashtable<String, String>) request.mExtData.get("key");
assertTrue(hashValue.containsKey("0"));
assertTrue(hashValue.containsKey("1"));
assertTrue(hashValue.containsKey("2"));
@@ -420,7 +420,7 @@ public class RequestTest extends CMSBaseTestCase {
request.setExtData("cory", hashValue);
assertNull(request.getExtDataInStringArray("cory"));
- assertFalse(request.setExtData("key", (String[])null));
+ assertFalse(request.setExtData("key", (String[]) null));
}
@@ -435,7 +435,7 @@ public class RequestTest extends CMSBaseTestCase {
assertTrue(request.mExtData.containsKey("key"));
@SuppressWarnings("unchecked")
- Hashtable<String, String> hashValue = (Hashtable<String, String>)request.mExtData.get("key");
+ Hashtable<String, String> hashValue = (Hashtable<String, String>) request.mExtData.get("key");
assertTrue(hashValue.containsKey("0"));
assertTrue(hashValue.containsKey("1"));
assertTrue(hashValue.containsKey("2"));
@@ -459,7 +459,7 @@ public class RequestTest extends CMSBaseTestCase {
request.setExtData("cory", hashValue);
assertNull(request.getExtDataInStringVector("cory"));
- assertFalse(request.setExtData("key", (Vector<?>)null));
+ assertFalse(request.setExtData("key", (Vector<?>) null));
}
public void testGetSetCertInfo() {
@@ -476,7 +476,7 @@ public class RequestTest extends CMSBaseTestCase {
request.getExtDataInCertInfo("key");
assertTrue(cmsStub.aToBCalled);
- assertFalse(request.setExtData("key", (X509CertInfo)null));
+ assertFalse(request.setExtData("key", (X509CertInfo) null));
}
public void testGetSetCertInfoArray() {
@@ -486,14 +486,14 @@ public class RequestTest extends CMSBaseTestCase {
};
assertTrue(request.setExtData("key", vals));
- Hashtable<?, ?> hashVals = (Hashtable<?, ?>)request.mExtData.get("key");
+ Hashtable<?, ?> hashVals = (Hashtable<?, ?>) request.mExtData.get("key");
assertEquals(2, hashVals.keySet().size());
assertFalse(cmsStub.aToBCalled);
request.getExtDataInCertInfoArray("key");
assertTrue(cmsStub.aToBCalled);
- assertFalse(request.setExtData("key", (X509CertInfo[])null));
+ assertFalse(request.setExtData("key", (X509CertInfo[]) null));
}
public void testGetBoolean() {
@@ -536,14 +536,14 @@ public class RequestTest extends CMSBaseTestCase {
};
assertTrue(request.setExtData("key", vals));
- Hashtable<?, ?> hashVals = (Hashtable<?, ?>)request.mExtData.get("key");
+ Hashtable<?, ?> hashVals = (Hashtable<?, ?>) request.mExtData.get("key");
assertEquals(2, hashVals.keySet().size());
assertFalse(cmsStub.aToBCalled);
request.getExtDataInCertInfoArray("key");
assertTrue(cmsStub.aToBCalled);
- assertFalse(request.setExtData("key", (RevokedCertImpl[])null));
+ assertFalse(request.setExtData("key", (RevokedCertImpl[]) null));
}
public void testGetSetCertExts() throws IOException {
@@ -564,7 +564,7 @@ public class RequestTest extends CMSBaseTestCase {
assertNotNull(retval);
assertEquals(1, retval.size());
- assertFalse(request.setExtData("key", (CertificateExtensions)null));
+ assertFalse(request.setExtData("key", (CertificateExtensions) null));
}
public void testGetSetCertSubjectName() throws IOException {
@@ -576,10 +576,10 @@ public class RequestTest extends CMSBaseTestCase {
CertificateSubjectName retval = request.getExtDataInCertSubjectName("key");
assertNotNull(retval);
// the 'CN=' is uppercased at some point
- assertEquals("cn=kevin",
+ assertEquals("cn=kevin",
retval.get(CertificateSubjectName.DN_NAME).toString().toLowerCase());
- assertFalse(request.setExtData("key", (CertificateSubjectName)null));
+ assertFalse(request.setExtData("key", (CertificateSubjectName) null));
}
public void testGetSetAuthToken() {
@@ -597,15 +597,15 @@ public class RequestTest extends CMSBaseTestCase {
assertEquals(token.getInString("key2"), retval.getInString("key2"));
assertEquals(token.getInInteger("key3"), retval.getInInteger("key3"));
- assertFalse(request.setExtData("key", (AuthToken)null));
+ assertFalse(request.setExtData("key", (AuthToken) null));
}
-
+
/**
* CMSMemoryStub
- *
+ *
* This class is used to help test methods that rely on setting and then
- * getting a value out. It assumes BtoA is always called first, stores
- * the value passed in, and then returns that value for BtoA.
+ * getting a value out. It assumes BtoA is always called first, stores the
+ * value passed in, and then returns that value for BtoA.
*/
class CMSMemoryStub extends CMSEngineDefaultStub {
boolean bToACalled = false;
@@ -650,7 +650,6 @@ public class RequestTest extends CMSBaseTestCase {
private static final long serialVersionUID = -9088436260566619005L;
boolean getEncodedCalled = false;
-
public byte[] getEncoded() throws CRLException {
getEncodedCalled = true;
return new byte[] {};
diff --git a/pki/base/common/test/com/netscape/cmscore/test/CMSBaseTestCase.java b/pki/base/common/test/com/netscape/cmscore/test/CMSBaseTestCase.java
index 7e1978e1..ab621847 100644
--- a/pki/base/common/test/com/netscape/cmscore/test/CMSBaseTestCase.java
+++ b/pki/base/common/test/com/netscape/cmscore/test/CMSBaseTestCase.java
@@ -18,9 +18,9 @@ import com.netscape.cmscore.dbs.DBSubsystem;
import com.netscape.cmscore.dbs.DBSubsystemDefaultStub;
/**
- * The base class for all CMS unit tests. This sets up some basic stubs
- * that allow unit tests to work without bumping into uninitialized subsystems
- * (like the CMS logging system).
+ * The base class for all CMS unit tests. This sets up some basic stubs that
+ * allow unit tests to work without bumping into uninitialized subsystems (like
+ * the CMS logging system).
*/
public abstract class CMSBaseTestCase extends TestCase {
CMSEngineStub engine;
@@ -56,26 +56,26 @@ public abstract class CMSBaseTestCase extends TestCase {
public X509CertImpl getFakeCert() throws CertificateException {
byte[] certData = new byte[] {
- 48, -126, 1, 18, 48, -127, -67, -96, 3, 2, 1, 2, 2, 1,
- 1, 48, 13, 6, 9, 42, -122, 72, -122, -9, 13, 1, 1, 4,
- 5, 0, 48, 18, 49, 16, 48, 14, 6, 3, 85, 4, 3, 19,
- 7, 116, 101, 115, 116, 105, 110, 103, 48, 30, 23, 13, 48, 55,
- 48, 55, 49, 50, 49, 55, 51, 56, 51, 52, 90, 23, 13, 48,
- 55, 49, 48, 49, 50, 49, 55, 51, 56, 51, 52, 90, 48, 18,
- 49, 16, 48, 14, 6, 3, 85, 4, 3, 19, 7, 116, 101, 115,
- 116, 105, 110, 103, 48, 92, 48, 13, 6, 9, 42, -122, 72, -122,
- -9, 13, 1, 1, 1, 5, 0, 3, 75, 0, 48, 72, 2, 65,
- 0, -65, 121, -119, -59, 105, 66, -122, -78, -30, -64, 63, -47, 44,
- -48, -104, 103, -47, -108, 42, -38, 46, -8, 32, 49, -29, -26, -112,
- -29, -86, 71, 24, -104, 78, -31, -75, -128, 90, -92, -34, -51, -125,
- -13, 80, 101, -78, 39, -119, -38, 117, 28, 67, -19, -71, -124, -85,
- 105, -53, -103, -59, -67, -38, -83, 118, 65, 2, 3, 1, 0, 1,
- 48, 13, 6, 9, 42, -122, 72, -122, -9, 13, 1, 1, 4, 5,
- 0, 3, 65, 0, -97, -62, 79, -28, 124, -81, 98, 119, -85, -49,
- 62, -81, 46, -25, -29, 78, -40, 118, -2, 114, -128, 74, -47, -68,
- 52, 11, -14, 30, -46, -95, -26, -108, -19, 110, -63, -70, 61, -75,
- 64, 74, -33, -65, -96, 120, -109, 37, 77, -76, 38, -114, 58, -80,
- -122, -39, -65, -31, 37, -30, -126, 126, 17, -82, 92, 64,
+ 48, -126, 1, 18, 48, -127, -67, -96, 3, 2, 1, 2, 2, 1,
+ 1, 48, 13, 6, 9, 42, -122, 72, -122, -9, 13, 1, 1, 4,
+ 5, 0, 48, 18, 49, 16, 48, 14, 6, 3, 85, 4, 3, 19,
+ 7, 116, 101, 115, 116, 105, 110, 103, 48, 30, 23, 13, 48, 55,
+ 48, 55, 49, 50, 49, 55, 51, 56, 51, 52, 90, 23, 13, 48,
+ 55, 49, 48, 49, 50, 49, 55, 51, 56, 51, 52, 90, 48, 18,
+ 49, 16, 48, 14, 6, 3, 85, 4, 3, 19, 7, 116, 101, 115,
+ 116, 105, 110, 103, 48, 92, 48, 13, 6, 9, 42, -122, 72, -122,
+ -9, 13, 1, 1, 1, 5, 0, 3, 75, 0, 48, 72, 2, 65,
+ 0, -65, 121, -119, -59, 105, 66, -122, -78, -30, -64, 63, -47, 44,
+ -48, -104, 103, -47, -108, 42, -38, 46, -8, 32, 49, -29, -26, -112,
+ -29, -86, 71, 24, -104, 78, -31, -75, -128, 90, -92, -34, -51, -125,
+ -13, 80, 101, -78, 39, -119, -38, 117, 28, 67, -19, -71, -124, -85,
+ 105, -53, -103, -59, -67, -38, -83, 118, 65, 2, 3, 1, 0, 1,
+ 48, 13, 6, 9, 42, -122, 72, -122, -9, 13, 1, 1, 4, 5,
+ 0, 3, 65, 0, -97, -62, 79, -28, 124, -81, 98, 119, -85, -49,
+ 62, -81, 46, -25, -29, 78, -40, 118, -2, 114, -128, 74, -47, -68,
+ 52, 11, -14, 30, -46, -95, -26, -108, -19, 110, -63, -70, 61, -75,
+ 64, 74, -33, -65, -96, 120, -109, 37, 77, -76, 38, -114, 58, -80,
+ -122, -39, -65, -31, 37, -30, -126, 126, 17, -82, 92, 64,
};
return new X509CertImpl(certData);
diff --git a/pki/base/java-tools/src/com/netscape/cmstools/AtoB.java b/pki/base/java-tools/src/com/netscape/cmstools/AtoB.java
index 78c20751..40996b54 100644
--- a/pki/base/java-tools/src/com/netscape/cmstools/AtoB.java
+++ b/pki/base/java-tools/src/com/netscape/cmstools/AtoB.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmstools;
-
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
@@ -26,33 +25,33 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
-
/**
- * The AtoB class is a utility program designed to "translate" an ASCII
- * BASE 64 encoded blob into a BINARY BASE 64 encoded blob. It assumes
- * that the name of a data file is passed to the program via the command line,
- * and that the contents contain a blob encoded in an ASCII BASE 64
- * format. Note that the data file may contain an optional "-----BEGIN" header
- * and/or an optional "-----END" trailer.
- *
+ * The AtoB class is a utility program designed to "translate" an ASCII BASE 64
+ * encoded blob into a BINARY BASE 64 encoded blob. It assumes that the name of
+ * a data file is passed to the program via the command line, and that the
+ * contents contain a blob encoded in an ASCII BASE 64 format. Note that the
+ * data file may contain an optional "-----BEGIN" header and/or an optional
+ * "-----END" trailer.
+ *
* <P>
* The program may be invoked as follows:
+ *
* <PRE>
- *
+ *
* AtoB &lt;input filename&gt; &lt;output filename&gt;
- *
+ *
* NOTE: &lt;input filename&gt; must contain an ASCII
* BASE 64 encoded blob
- *
+ *
* &lt;output filename&gt; contains a BINARY
* BASE 64 encoded blob
* </PRE>
- *
+ *
* @version $Revision$, $Date$
*/
public class AtoB {
// Define constants
- public static final int ARGC = 2;
+ public static final int ARGC = 2;
public static final String HEADER = "-----BEGIN";
public static final String TRAILER = "-----END";
@@ -67,40 +66,40 @@ public class AtoB {
// (1) Check that two arguments were submitted to the program
if (argv.length != ARGC) {
System.out.println("Usage: AtoB " +
- "<input filename> " +
- "<output filename>");
+ "<input filename> " +
+ "<output filename>");
return;
}
// (2) Create a DataInputStream() object to the BASE 64
- // encoded blob contained within the file
- // specified on the command line
+ // encoded blob contained within the file
+ // specified on the command line
try {
inputBlob = new BufferedReader(new InputStreamReader(
new BufferedInputStream(
- new FileInputStream(
- argv[0]))));
+ new FileInputStream(
+ argv[0]))));
} catch (FileNotFoundException e) {
System.out.println("AtoB(): can''t find file " +
- argv[0] + ":\n" + e);
+ argv[0] + ":\n" + e);
return;
}
// (3) Read the entire contents of the specified BASE 64 encoded
- // blob into a String() object throwing away any
- // headers beginning with HEADER and any trailers beginning
- // with TRAILER
+ // blob into a String() object throwing away any
+ // headers beginning with HEADER and any trailers beginning
+ // with TRAILER
try {
while ((asciiBASE64BlobChunk = inputBlob.readLine()) != null) {
if (!(asciiBASE64BlobChunk.startsWith(HEADER)) &&
- !(asciiBASE64BlobChunk.startsWith(TRAILER))) {
+ !(asciiBASE64BlobChunk.startsWith(TRAILER))) {
asciiBASE64Blob += asciiBASE64BlobChunk.trim();
}
}
} catch (IOException e) {
System.out.println("AtoB(): Unexpected BASE64 " +
- "encoded error encountered in readLine():\n" +
- e);
+ "encoded error encountered in readLine():\n" +
+ e);
}
// (4) Close the DataInputStream() object
@@ -108,21 +107,21 @@ public class AtoB {
inputBlob.close();
} catch (IOException e) {
System.out.println("AtoB(): Unexpected BASE64 " +
- "encoded error encountered in close():\n" + e);
+ "encoded error encountered in close():\n" + e);
}
-
+
// (5) Decode the ASCII BASE 64 blob enclosed in the
- // String() object into a BINARY BASE 64 byte[] object
+ // String() object into a BINARY BASE 64 byte[] object
binaryBASE64Blob = com.netscape.osutil.OSUtil.AtoB(asciiBASE64Blob);
// (6) Finally, print the actual AtoB blob to the
- // specified output file
+ // specified output file
try {
outputBlob = new FileOutputStream(argv[1]);
} catch (IOException e) {
System.out.println("AtoB(): unable to open file " +
- argv[1] + " for writing:\n" + e);
+ argv[1] + " for writing:\n" + e);
return;
}
@@ -130,17 +129,16 @@ public class AtoB {
outputBlob.write(binaryBASE64Blob);
} catch (IOException e) {
System.out.println("AtoB(): I/O error " +
- "encountered during write():\n" +
- e);
+ "encountered during write():\n" +
+ e);
}
try {
outputBlob.close();
} catch (IOException e) {
System.out.println("AtoB(): Unexpected error " +
- "encountered while attempting to close() " +
- argv[1] + ":\n" + e);
+ "encountered while attempting to close() " +
+ argv[1] + ":\n" + e);
}
}
}
-
diff --git a/pki/base/java-tools/src/com/netscape/cmstools/AuditVerify.java b/pki/base/java-tools/src/com/netscape/cmstools/AuditVerify.java
index aa8ffe9a..7ceb887c 100644
--- a/pki/base/java-tools/src/com/netscape/cmstools/AuditVerify.java
+++ b/pki/base/java-tools/src/com/netscape/cmstools/AuditVerify.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmstools;
-
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
@@ -69,34 +68,34 @@ public class AuditVerify {
}
private static void writeSigStatus(int linenum, String sigStartFile,
- int sigStartLine, String sigStopFile, int sigStopLine, String mesg)
- throws IOException
- {
+ int sigStartLine, String sigStopFile, int sigStopLine, String mesg)
+ throws IOException {
output(linenum, mesg + ": signature of " + sigStartFile + ":" +
- sigStartLine + " to " + sigStopFile + ":" + sigStopLine);
+ sigStartLine + " to " + sigStopFile + ":" + sigStopLine);
}
private static class PrefixFilter implements FilenameFilter {
private String prefix;
+
public PrefixFilter(String prefix) {
this.prefix = prefix;
}
+
public boolean accept(File dir, String name) {
// look for <prefix>cert* in this directory
- return( name.indexOf(prefix + "cert") != -1 );
+ return (name.indexOf(prefix + "cert") != -1);
}
}
public static boolean validPrefix(String configDir, String prefix)
- throws IOException
- {
+ throws IOException {
File dir = new File(configDir);
- if( ! dir.isDirectory() ) {
+ if (!dir.isDirectory()) {
System.out.println("ERROR: \"" + dir + "\" is not a directory");
usage();
}
- String matchingFiles[] = dir.list( new PrefixFilter(prefix) );
+ String matchingFiles[] = dir.list(new PrefixFilter(prefix));
// prefix may be valid if at least one file matched the pattern
return (matchingFiles.length > 0);
@@ -113,218 +112,221 @@ public class AuditVerify {
return (keyUsage == null) ? false : keyUsage[0];
}
-
public static void main(String args[]) {
- try {
-
- String dbdir = null;
- String logListFile = null;
- String signerNick = null;
- String prefix = null;
- boolean verbose = false;
-
- for(int i = 0; i < args.length; ++i) {
- if( args[i].equals("-d") ) {
- if( ++i >= args.length ) usage();
- dbdir = args[i];
- } else if( args[i].equals("-a") ) {
- if( ++i >= args.length ) usage();
- logListFile = args[i];
- } else if( args[i].equals("-n") ) {
- if( ++i >= args.length ) usage();
- signerNick = args[i];
- } else if( args[i].equals("-P") ) {
- if( ++i >= args.length ) usage();
- prefix = args[i];
- } else if( args[i].equals("-v") ) {
- verbose = true;
- } else {
- System.out.println("Unrecognized argument(" + i + "): "
- + args[i]);
+ try {
+
+ String dbdir = null;
+ String logListFile = null;
+ String signerNick = null;
+ String prefix = null;
+ boolean verbose = false;
+
+ for (int i = 0; i < args.length; ++i) {
+ if (args[i].equals("-d")) {
+ if (++i >= args.length)
+ usage();
+ dbdir = args[i];
+ } else if (args[i].equals("-a")) {
+ if (++i >= args.length)
+ usage();
+ logListFile = args[i];
+ } else if (args[i].equals("-n")) {
+ if (++i >= args.length)
+ usage();
+ signerNick = args[i];
+ } else if (args[i].equals("-P")) {
+ if (++i >= args.length)
+ usage();
+ prefix = args[i];
+ } else if (args[i].equals("-v")) {
+ verbose = true;
+ } else {
+ System.out.println("Unrecognized argument(" + i + "): "
+ + args[i]);
+ usage();
+ }
+ }
+ if (dbdir == null || logListFile == null || signerNick == null) {
+ System.out.println("Argument omitted");
usage();
}
- }
- if( dbdir == null || logListFile == null || signerNick == null) {
- System.out.println("Argument omitted");
- usage();
- }
- // get list of log files
- Vector logFiles = new Vector();
- BufferedReader r = new BufferedReader(new FileReader(logListFile));
- String listLine;
- while( (listLine = r.readLine()) != null ) {
- StringTokenizer tok = new StringTokenizer(listLine, ",");
- while( tok.hasMoreElements() ) {
- logFiles.addElement( ((String)tok.nextElement()).trim());
+ // get list of log files
+ Vector logFiles = new Vector();
+ BufferedReader r = new BufferedReader(new FileReader(logListFile));
+ String listLine;
+ while ((listLine = r.readLine()) != null) {
+ StringTokenizer tok = new StringTokenizer(listLine, ",");
+ while (tok.hasMoreElements()) {
+ logFiles.addElement(((String) tok.nextElement()).trim());
+ }
+ }
+ if (logFiles.size() == 0) {
+ System.out.println("Error: no log files listed in " + logListFile);
+ System.exit(1);
}
- }
- if( logFiles.size() == 0 ) {
- System.out.println("Error: no log files listed in " + logListFile);
- System.exit(1);
- }
- // initialize crypto stuff
- if( prefix == null ) {
- if( ! validPrefix(dbdir, "")) {
- System.out.println("ERROR: \"" + dbdir +
- "\" does not contain any security databases");
- usage();
+ // initialize crypto stuff
+ if (prefix == null) {
+ if (!validPrefix(dbdir, "")) {
+ System.out.println("ERROR: \"" + dbdir +
+ "\" does not contain any security databases");
+ usage();
+ }
+ CryptoManager.initialize(dbdir);
+ } else {
+ if (!validPrefix(dbdir, prefix)) {
+ System.out.println("ERROR: \"" + prefix +
+ "\" is not a valid prefix");
+ usage();
+ }
+ CryptoManager.initialize(
+ new CryptoManager.InitializationValues(dbdir, prefix, prefix,
+ "secmod.db")
+ );
}
- CryptoManager.initialize(dbdir);
- } else {
- if( ! validPrefix(dbdir, prefix) ) {
- System.out.println("ERROR: \"" + prefix +
- "\" is not a valid prefix");
- usage();
+ CryptoManager cm = CryptoManager.getInstance();
+ X509Certificate signerCert = cm.findCertByNickname(signerNick);
+
+ X509CertImpl cert_i = null;
+ if (signerCert != null) {
+ byte[] signerCert_b = signerCert.getEncoded();
+ cert_i = new X509CertImpl(signerCert_b);
+ } else {
+ System.out.println("ERROR: signing certificate not found");
+ System.exit(1);
}
- CryptoManager.initialize(
- new CryptoManager.InitializationValues(dbdir, prefix, prefix,
- "secmod.db")
- );
- }
- CryptoManager cm = CryptoManager.getInstance();
- X509Certificate signerCert = cm.findCertByNickname(signerNick);
-
- X509CertImpl cert_i = null;
- if (signerCert != null) {
- byte[] signerCert_b = signerCert.getEncoded();
- cert_i = new X509CertImpl(signerCert_b);
- } else {
- System.out.println("ERROR: signing certificate not found");
- System.exit(1);
- }
- // verify signer's certificate
- // not checking validity because we want to allow verifying old logs
- //
- if (!isSigningCert(cert_i)) {
- System.out.println("info: signing certificate is not a signing certificate");
- System.exit(1);
- }
+ // verify signer's certificate
+ // not checking validity because we want to allow verifying old logs
+ //
+ if (!isSigningCert(cert_i)) {
+ System.out.println("info: signing certificate is not a signing certificate");
+ System.exit(1);
+ }
- PublicKey pubk = signerCert.getPublicKey();
- String sigAlgorithm=null;
- if( pubk instanceof RSAPublicKey ) {
- sigAlgorithm = "SHA-256/RSA";
- } else if( pubk instanceof DSAPublicKey ) {
- sigAlgorithm = "SHA-256/DSA";
- } else {
- System.out.println("Error: unknown key type: " +
- pubk.getAlgorithm());
- System.exit(1);
- }
- Signature sig = Signature.getInstance(sigAlgorithm, CRYPTO_PROVIDER);
- sig.initVerify(pubk);
+ PublicKey pubk = signerCert.getPublicKey();
+ String sigAlgorithm = null;
+ if (pubk instanceof RSAPublicKey) {
+ sigAlgorithm = "SHA-256/RSA";
+ } else if (pubk instanceof DSAPublicKey) {
+ sigAlgorithm = "SHA-256/DSA";
+ } else {
+ System.out.println("Error: unknown key type: " +
+ pubk.getAlgorithm());
+ System.exit(1);
+ }
+ Signature sig = Signature.getInstance(sigAlgorithm, CRYPTO_PROVIDER);
+ sig.initVerify(pubk);
- int goodSigCount = 0;
- int badSigCount = 0;
+ int goodSigCount = 0;
+ int badSigCount = 0;
- int lastFileWritten = -1;
+ int lastFileWritten = -1;
- int sigStartLine = 1;
- int sigStopLine = 1;
- String sigStartFile = (String) logFiles.elementAt(0);
- String sigStopFile = null;
- int signedLines = 1;
+ int sigStartLine = 1;
+ int sigStopLine = 1;
+ String sigStartFile = (String) logFiles.elementAt(0);
+ String sigStopFile = null;
+ int signedLines = 1;
- boolean lastLineWasSig = false;
+ boolean lastLineWasSig = false;
- for( int curfile = 0; curfile < logFiles.size(); ++curfile) {
- String curfileName = (String) logFiles.elementAt(curfile);
- BufferedReader br = new BufferedReader(new FileReader(curfileName));
+ for (int curfile = 0; curfile < logFiles.size(); ++curfile) {
+ String curfileName = (String) logFiles.elementAt(curfile);
+ BufferedReader br = new BufferedReader(new FileReader(curfileName));
- if( verbose ) {
- writeFile(curfileName);
- lastFileWritten = curfile;
- }
+ if (verbose) {
+ writeFile(curfileName);
+ lastFileWritten = curfile;
+ }
- String curLine;
- int linenum = 0;
- while( (curLine = br.readLine()) != null ) {
- ++linenum;
- if( curLine.indexOf("AUDIT_LOG_SIGNING") != -1 ) {
- if( curfile == 0 && linenum == 1 ) {
- // Ignore the first signature of the first file,
- // since it signs data we don't have access to.
- if( verbose ) {
- output(linenum,
- "Ignoring first signature of log series");
- }
- } else {
- int sigStart = curLine.indexOf("sig: ") + 5;
- if( sigStart < 5 ) {
- output(linenum, "INVALID SIGNATURE");
- ++badSigCount;
+ String curLine;
+ int linenum = 0;
+ while ((curLine = br.readLine()) != null) {
+ ++linenum;
+ if (curLine.indexOf("AUDIT_LOG_SIGNING") != -1) {
+ if (curfile == 0 && linenum == 1) {
+ // Ignore the first signature of the first file,
+ // since it signs data we don't have access to.
+ if (verbose) {
+ output(linenum,
+ "Ignoring first signature of log series");
+ }
} else {
- byte[] logSig =
- base64decode(curLine.substring(sigStart));
-
- // verify the signature
- if( sig.verify(logSig) ) {
- // signature verifies correctly
- if( verbose ) {
- writeSigStatus(linenum, sigStartFile,
- sigStartLine, sigStopFile, sigStopLine,
- "verification succeeded");
- }
- ++goodSigCount;
+ int sigStart = curLine.indexOf("sig: ") + 5;
+ if (sigStart < 5) {
+ output(linenum, "INVALID SIGNATURE");
+ ++badSigCount;
} else {
- if( lastFileWritten < curfile ) {
- writeFile(curfileName);
- lastFileWritten = curfile;
+ byte[] logSig =
+ base64decode(curLine.substring(sigStart));
+
+ // verify the signature
+ if (sig.verify(logSig)) {
+ // signature verifies correctly
+ if (verbose) {
+ writeSigStatus(linenum, sigStartFile,
+ sigStartLine, sigStopFile, sigStopLine,
+ "verification succeeded");
+ }
+ ++goodSigCount;
+ } else {
+ if (lastFileWritten < curfile) {
+ writeFile(curfileName);
+ lastFileWritten = curfile;
+ }
+ writeSigStatus(linenum, sigStartFile,
+ sigStartLine, sigStopFile, sigStopLine,
+ "VERIFICATION FAILED");
+ ++badSigCount;
}
- writeSigStatus(linenum, sigStartFile,
- sigStartLine, sigStopFile, sigStopLine,
- "VERIFICATION FAILED");
- ++badSigCount;
}
+ sig.initVerify(pubk);
+ signedLines = 0;
+ sigStartLine = linenum;
+ sigStartFile = curfileName;
}
- sig.initVerify(pubk);
- signedLines = 0;
- sigStartLine = linenum;
- sigStartFile = curfileName;
}
+
+ byte[] lineBytes = curLine.getBytes("UTF-8");
+ sig.update(lineBytes);
+ sig.update(LINE_SEP_BYTE);
+ ++signedLines;
+ sigStopLine = linenum;
+ sigStopFile = curfileName;
}
- byte[] lineBytes = curLine.getBytes("UTF-8");
- sig.update(lineBytes);
- sig.update(LINE_SEP_BYTE);
- ++signedLines;
- sigStopLine = linenum;
- sigStopFile = curfileName;
}
- }
+ // Make sure there were no unsigned log entries at the end.
+ // The first signed line is the previous signature, but anything
+ // more than that is data.
+ if (signedLines > 1) {
+ System.out.println(
+ "ERROR: log entries after " + sigStartFile
+ + ":" + sigStartLine + " are UNSIGNED");
+ badSigCount++;
+ }
- // Make sure there were no unsigned log entries at the end.
- // The first signed line is the previous signature, but anything
- // more than that is data.
- if( signedLines > 1 ) {
- System.out.println(
- "ERROR: log entries after " + sigStartFile
- + ":" + sigStartLine + " are UNSIGNED");
- badSigCount++;
- }
+ System.out.println("\nVerification process complete.");
+ System.out.println("Valid signatures: " + goodSigCount);
+ System.out.println("Invalid signatures: " + badSigCount);
- System.out.println("\nVerification process complete.");
- System.out.println("Valid signatures: " + goodSigCount);
- System.out.println("Invalid signatures: " + badSigCount);
+ if (badSigCount > 0) {
+ System.exit(2);
+ } else {
+ System.exit(0);
+ }
- if( badSigCount > 0 ) {
- System.exit(2);
- } else {
- System.exit(0);
+ } catch (FileNotFoundException fnfe) {
+ System.out.println(fnfe);
+ } catch (ObjectNotFoundException onfe) {
+ System.out.println("ERROR: certificate not found");
+ } catch (Exception e) {
+ e.printStackTrace();
}
- } catch(FileNotFoundException fnfe) {
- System.out.println(fnfe);
- } catch(ObjectNotFoundException onfe) {
- System.out.println("ERROR: certificate not found");
- } catch(Exception e) {
- e.printStackTrace();
- }
-
System.out.println("Verification process FAILED.");
System.exit(1);
}
diff --git a/pki/base/java-tools/src/com/netscape/cmstools/BtoA.java b/pki/base/java-tools/src/com/netscape/cmstools/BtoA.java
index 2bc96a2f..4eb83662 100644
--- a/pki/base/java-tools/src/com/netscape/cmstools/BtoA.java
+++ b/pki/base/java-tools/src/com/netscape/cmstools/BtoA.java
@@ -17,70 +17,68 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmstools;
-
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
-
/**
- * The BtoA class is a utility program designed to "translate" a BINARY
- * BASE 64 encoded blob into an ASCII BASE 64 encoded blob. It assumes
- * that the name of a data file is passed to the program via the command line,
- * and that the contents contain a blob encoded in a BINARY BASE 64
- * format.
- *
+ * The BtoA class is a utility program designed to "translate" a BINARY BASE 64
+ * encoded blob into an ASCII BASE 64 encoded blob. It assumes that the name of
+ * a data file is passed to the program via the command line, and that the
+ * contents contain a blob encoded in a BINARY BASE 64 format.
+ *
* <P>
* The program may be invoked as follows:
+ *
* <PRE>
- *
+ *
* BtoA &lt;input filename&gt; &lt;output filename&gt;
- *
+ *
* NOTE: &lt;input filename&gt; must contain a BINARY
* BASE 64 encoded blob
- *
+ *
* &lt;output filename&gt; contains an ASCII
* BASE 64 encoded blob
* </PRE>
- *
+ *
* @version $Revision$, $Date$
*/
public class BtoA {
// Define constants
- public static final int ARGC = 2;
+ public static final int ARGC = 2;
public static void main(String argv[]) {
- FileInputStream inputBlob = null;
+ FileInputStream inputBlob = null;
FileOutputStream outputBlob = null;
// (1) Check that two arguments were submitted to the program
if (argv.length != ARGC) {
System.out.println("Usage: BtoA " +
- "<input filename> " +
- "<output filename>");
+ "<input filename> " +
+ "<output filename>");
return;
}
// (2) Create a DataInputStream() object to the BASE 64
- // encoded blob contained within the file
- // specified on the command line
+ // encoded blob contained within the file
+ // specified on the command line
try {
inputBlob = new FileInputStream(argv[0]);
} catch (FileNotFoundException e) {
System.out.println("BtoA(): can''t find file " +
- argv[0] + ":\n" + e);
+ argv[0] + ":\n" + e);
return;
}
// (3) Create a FileOutputStream() object to the BASE 64
- // specified output file
+ // specified output file
try {
outputBlob = new FileOutputStream(argv[1]);
} catch (IOException e) {
System.out.println("BtoA(): unable to open file " +
- argv[1] + " for writing:\n" + e);
+ argv[1] + " for writing:\n" + e);
return;
}
@@ -93,8 +91,8 @@ public class BtoA {
outputBlob.write(out.getBytes());
} catch (IOException e) {
System.out.println("BtoA(): Unexpected BASE64 " +
- "encoded error encountered:\n" +
- e);
+ "encoded error encountered:\n" +
+ e);
}
// (5) Close the DataInputStream() object
@@ -102,8 +100,8 @@ public class BtoA {
inputBlob.close();
} catch (IOException e) {
System.out.println("BtoA(): Unexpected input error " +
- "encountered while attempting to close() " +
- argv[0] + ":\n" + e);
+ "encountered while attempting to close() " +
+ argv[0] + ":\n" + e);
}
// (6) Close the FileOutputStream() object
@@ -111,9 +109,8 @@ public class BtoA {
outputBlob.close();
} catch (IOException e) {
System.out.println("BtoA(): Unexpected output error " +
- "encountered while attempting to close() " +
- argv[1] + ":\n" + e);
+ "encountered while attempting to close() " +
+ argv[1] + ":\n" + e);
}
}
}
-
diff --git a/pki/base/java-tools/src/com/netscape/cmstools/CMCEnroll.java b/pki/base/java-tools/src/com/netscape/cmstools/CMCEnroll.java
index 368ef827..de526cd1 100644
--- a/pki/base/java-tools/src/com/netscape/cmstools/CMCEnroll.java
+++ b/pki/base/java-tools/src/com/netscape/cmstools/CMCEnroll.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmstools;
-
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
@@ -67,32 +66,30 @@ import org.mozilla.jss.pkix.primitive.AlgorithmIdentifier;
import org.mozilla.jss.pkix.primitive.Name;
import org.mozilla.jss.util.Password;
-
-
/**
* Tool for signing PKCS #10 , return CMC enrollment request
*
* <P>
+ *
* @version $Revision$, $Date$
-
*/
public class CMCEnroll {
public static final String PR_REQUEST_CMC = "CMC";
public static final String PR_REQUEST_PKCS10 = "PKCS10";
- public static final int ARGC = 4;
+ public static final int ARGC = 4;
private static final String CERTDB = "cert8.db";
private static final String KEYDB = "key3.db";
public static final String HEADER = "-----BEGIN NEW CERTIFICATE REQUEST-----";
public static final String TRAILER = "-----END NEW CERTIFICATE REQUEST-----";
-
- void cleanArgs(String[] s) {
-
+
+ void cleanArgs(String[] s) {
+
}
public static X509Certificate getCertificate(String tokenname,
- String nickname) throws Exception {
+ String nickname) throws Exception {
CryptoManager manager = CryptoManager.getInstance();
CryptoToken token = null;
@@ -116,30 +113,31 @@ public class CMCEnroll {
}
public static java.security.PrivateKey getPrivateKey(String tokenname, String nickname)
- throws Exception {
+ throws Exception {
X509Certificate cert = getCertificate(tokenname, nickname);
return CryptoManager.getInstance().findPrivKeyByCert(cert);
}
+ /**
+ * getCMCBlob create and return the enrollent request.
+ * <P>
+ *
+ * @param signerCert the certificate of the authorized signer of the CMC
+ * revocation request.
+ * @param manager the crypto manger.
+ * @param nValue the nickname of the certificate inside the token.
+ * @param rValue request PKCS#10 file name.
+ * @return the CMC revocation request encoded in base64
+ */
+ static String getCMCBlob(X509Certificate signerCert, CryptoManager manager, String nValue, String rValue) {
- /**
- * getCMCBlob create and return the enrollent request.
- * <P>
- * @param signerCert the certificate of the authorized signer of the CMC revocation request.
- * @param manager the crypto manger.
- * @param nValue the nickname of the certificate inside the token.
- * @param rValue request PKCS#10 file name.
- * @return the CMC revocation request encoded in base64
- */
- static String getCMCBlob(X509Certificate signerCert,CryptoManager manager, String nValue, String rValue) {
-
String asciiBASE64Blob = rValue; // input pkcs10 blob
String tokenname = "internal";
try {
-
+
java.security.PrivateKey privKey = null;
PKCS10 pkcs = null;
SignerIdentifier si = null;
@@ -147,7 +145,7 @@ public class CMCEnroll {
try {
byte[] decodedBytes = com.netscape.osutil.OSUtil.AtoB(asciiBASE64Blob);
-
+
pkcs = new PKCS10(decodedBytes);
} catch (IOException e) {
throw new IOException("Internal Error - " + e.toString());
@@ -156,7 +154,7 @@ public class CMCEnroll {
} catch (NoSuchAlgorithmException e) {
throw new IOException("Internal Error - " + e.toString());
}
-
+
String hasSki = "true";
BigInteger serialno = signerCert.getSerialNumber();
@@ -164,35 +162,35 @@ public class CMCEnroll {
X509CertImpl impl = new X509CertImpl(certB);
X500Name issuerName = (X500Name) impl.getIssuerDN();
byte[] issuerByte = issuerName.getEncoded();
- ByteArrayInputStream istream = new ByteArrayInputStream(issuerByte);
-
+ ByteArrayInputStream istream = new ByteArrayInputStream(issuerByte);
+
Name issuer = (Name) Name.getTemplate().decode(istream);
IssuerAndSerialNumber ias = new IssuerAndSerialNumber(issuer, new INTEGER(serialno.toString()));
- si = new SignerIdentifier(SignerIdentifier.ISSUER_AND_SERIALNUMBER, ias, null);
+ si = new SignerIdentifier(SignerIdentifier.ISSUER_AND_SERIALNUMBER, ias, null);
privKey = getPrivateKey(tokenname, nValue);
-
+
// create CMC req
// transfer pkcs10 to jss class
int bpid = 1;
ByteArrayInputStream crInputStream = new ByteArrayInputStream(pkcs.toByteArray());
CertificationRequest cr = (CertificationRequest) CertificationRequest.getTemplate().decode(crInputStream);
-
+
TaggedCertificationRequest tcr = new
- TaggedCertificationRequest(new
- INTEGER(bpid++), cr);
+ TaggedCertificationRequest(new
+ INTEGER(bpid++), cr);
TaggedRequest trq = new
- TaggedRequest(TaggedRequest.PKCS10, tcr,
- null);
-
+ TaggedRequest(TaggedRequest.PKCS10, tcr,
+ null);
+
SEQUENCE reqSequence = new SEQUENCE();
reqSequence.addElement(trq);
-
+
// Add some control sequence
// Verisign has transactionID,senderNonce
SEQUENCE controlSeq = new SEQUENCE();
-
+
Date date = new Date();
String salt = "lala123" + date.toString();
byte[] dig;
@@ -206,14 +204,14 @@ public class CMCEnroll {
}
String sn = com.netscape.osutil.OSUtil.BtoA(dig);
-
+
TaggedAttribute senderNonce = new TaggedAttribute(new
INTEGER(bpid++),
OBJECT_IDENTIFIER.id_cmc_senderNonce,
new OCTET_STRING(sn.getBytes()));
controlSeq.addElement(senderNonce);
-
+
// Verisign recommend transactionId be MD5 hash of publicKey
byte[] transId;
@@ -224,19 +222,19 @@ public class CMCEnroll {
} catch (Exception ex) {
transId = salt.getBytes();
}
-
+
TaggedAttribute transactionId = new TaggedAttribute(new
INTEGER(bpid++),
OBJECT_IDENTIFIER.id_cmc_transactionId,
new INTEGER(1, transId));
controlSeq.addElement(transactionId);
-
+
PKIData pkidata = new PKIData(controlSeq, reqSequence, new SEQUENCE(), new SEQUENCE());
-
+
EncapsulatedContentInfo ci = new
- EncapsulatedContentInfo(OBJECT_IDENTIFIER.id_cct_PKIData,
- pkidata);
+ EncapsulatedContentInfo(OBJECT_IDENTIFIER.id_cct_PKIData,
+ pkidata);
// SHA1 is the default digest Alg for now.
DigestAlgorithm digestAlg = null;
SignatureAlgorithm signAlg = SignatureAlgorithm.RSASignatureWithSHA1Digest;
@@ -250,7 +248,7 @@ public class CMCEnroll {
try {
SHADigest = MessageDigest.getInstance("SHA1");
digestAlg = DigestAlgorithm.SHA1;
-
+
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
pkidata.encode((OutputStream) ostream);
@@ -258,12 +256,12 @@ public class CMCEnroll {
} catch (NoSuchAlgorithmException e) {
}
SignerInfo signInfo = new
- SignerInfo(si, null, null, OBJECT_IDENTIFIER.id_cct_PKIData, digest, signAlg,
- (org.mozilla.jss.crypto.PrivateKey) privKey);
+ SignerInfo(si, null, null, OBJECT_IDENTIFIER.id_cct_PKIData, digest, signAlg,
+ (org.mozilla.jss.crypto.PrivateKey) privKey);
SET signInfos = new SET();
signInfos.addElement(signInfo);
-
+
SET digestAlgs = new SET();
if (digestAlg != null) {
@@ -271,7 +269,7 @@ public class CMCEnroll {
digestAlgs.addElement(ai);
}
-
+
org.mozilla.jss.crypto.X509Certificate[] agentChain = manager.buildCertificateChain(signerCert);
SET certs = new SET();
@@ -287,13 +285,13 @@ public class CMCEnroll {
ByteArrayOutputStream bs = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(bs);
-
+
// format is PR_REQUEST_CMC
- ByteArrayOutputStream os = new ByteArrayOutputStream();
+ ByteArrayOutputStream os = new ByteArrayOutputStream();
- fullEnrollmentReq.encode(os);
- ps.print(com.netscape.osutil.OSUtil.BtoA(os.toByteArray()));
- //fullEnrollmentReq.print(ps); // no header/trailer
+ fullEnrollmentReq.encode(os);
+ ps.print(com.netscape.osutil.OSUtil.BtoA(os.toByteArray()));
+ // fullEnrollmentReq.print(ps); // no header/trailer
asciiBASE64Blob = bs.toString();
} catch (Exception e) {
e.printStackTrace();
@@ -303,74 +301,74 @@ public class CMCEnroll {
}
/** Creates a new instance of CMCEnroll */
- public static void main(String[]s) {
-
+ public static void main(String[] s) {
+
String dValue = null, nValue = null, rValue = null, pValue = null;
FileOutputStream outputBlob = null;
-
+
// default path is "."
String mPath = ".";
// default prefix is ""
String mPrefix = "";
-
+
boolean bWrongParam = false;
// (1) Check that two arguments were submitted to the program
if (s.length != (ARGC * 2)) {
System.out.println("Wrong number of parameters:" + s.length);
System.out.println("Usage: CMCEnroll " +
- "-d <dir to cert8.db, key3.db> " +
- "-n <nickname> " +
- "-r <request PKCS#10 file name> " +
- "-p <password>"
- );
+ "-d <dir to cert8.db, key3.db> " +
+ "-n <nickname> " +
+ "-r <request PKCS#10 file name> " +
+ "-p <password>"
+ );
bWrongParam = true;
- }else {
+ } else {
int length;
int i;
-
+
length = s.length;
for (i = 0; i < length; i++) {
if (s[i].equals("-d")) {
dValue = s[i + 1];
- } else if (s[i].equals("-n")) {
+ } else if (s[i].equals("-n")) {
nValue = s[i + 1];
- } else if (s[i].equals("-r")) {
+ } else if (s[i].equals("-r")) {
rValue = s[i + 1];
- } else if (s[i].equals("-p")) {
+ } else if (s[i].equals("-p")) {
pValue = s[i + 1];
}
if (s[i].equals(""))
bWrongParam = true;
-
+
}
-
- if (dValue == null || nValue == null || rValue == null || pValue == null )
+
+ if (dValue == null || nValue == null || rValue == null || pValue == null)
bWrongParam = true;
- else if (dValue.length() == 0 || nValue.length() == 0 || rValue.length() == 0 ||
- pValue.length() == 0 )
+ else if (dValue.length() == 0 || nValue.length() == 0 || rValue.length() == 0 ||
+ pValue.length() == 0)
bWrongParam = true;
if (bWrongParam == true) {
System.out.println("Usage: CMCEnroll " +
- "-d <dir to cert8.db, key3.db> " +
- "-n <nickname> " +
- "-r <request PKCS#10 file name> " +
- "-p <password>"
- );
+ "-d <dir to cert8.db, key3.db> " +
+ "-n <nickname> " +
+ "-r <request PKCS#10 file name> " +
+ "-p <password>"
+ );
System.exit(0);
- }
-
+ }
+
try {
// initialize CryptoManager
mPath = dValue;
System.out.println("cert/key prefix = " + mPrefix);
System.out.println("path = " + mPath);
CryptoManager.InitializationValues vals =
- new CryptoManager.InitializationValues(mPath, mPrefix,
- mPrefix, "secmod.db");
+ new CryptoManager.InitializationValues(mPath, mPrefix,
+ mPrefix, "secmod.db");
CryptoManager.initialize(vals);
-
+
CryptoManager cm = CryptoManager.getInstance();
CryptoToken token = cm.getInternalKeyStorageToken();
Password pass = new Password(pValue.toCharArray());
@@ -379,68 +377,68 @@ public class CMCEnroll {
CryptoStore store = token.getCryptoStore();
X509Certificate[] list = store.getCertificates();
X509Certificate signerCert = null;
-
+
signerCert = cm.findCertByNickname(nValue);
-
- BufferedReader inputBlob = null;
+
+ BufferedReader inputBlob = null;
try {
inputBlob = new BufferedReader(new InputStreamReader(
new BufferedInputStream(
- new FileInputStream(
- rValue))));
+ new FileInputStream(
+ rValue))));
} catch (FileNotFoundException e) {
System.out.println("CMCEnroll: can''t find file " +
- rValue + ":\n" + e);
+ rValue + ":\n" + e);
return;
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
// (3) Read the entire contents of the specified BASE 64 encoded
- // blob into a String() object throwing away any
- // headers beginning with HEADER and any trailers beginning
- // with TRAILER
+ // blob into a String() object throwing away any
+ // headers beginning with HEADER and any trailers beginning
+ // with TRAILER
String asciiBASE64BlobChunk = new String();
String asciiBASE64Blob = new String();
try {
while ((asciiBASE64BlobChunk = inputBlob.readLine()) != null) {
if (!(asciiBASE64BlobChunk.startsWith(HEADER)) &&
- !(asciiBASE64BlobChunk.startsWith(TRAILER))) {
+ !(asciiBASE64BlobChunk.startsWith(TRAILER))) {
asciiBASE64Blob += asciiBASE64BlobChunk.trim();
}
}
} catch (IOException e) {
System.out.println("CMCEnroll: Unexpected BASE64 " +
- "encoded error encountered in readLine():\n" +
- e);
+ "encoded error encountered in readLine():\n" +
+ e);
}
// (4) Close the DataInputStream() object
try {
inputBlob.close();
} catch (IOException e) {
System.out.println("CMCEnroll(): Unexpected BASE64 " +
- "encoded error encountered in close():\n" + e);
+ "encoded error encountered in close():\n" + e);
}
-
- asciiBASE64Blob = getCMCBlob(signerCert,cm, nValue, asciiBASE64Blob );
+
+ asciiBASE64Blob = getCMCBlob(signerCert, cm, nValue, asciiBASE64Blob);
// (5) Decode the ASCII BASE 64 blob enclosed in the
- // String() object into a BINARY BASE 64 byte[] object
+ // String() object into a BINARY BASE 64 byte[] object
byte binaryBASE64Blob[] = null;
binaryBASE64Blob = com.netscape.osutil.OSUtil.AtoB(asciiBASE64Blob);
-
+
// (6) Finally, print the actual CMCEnroll blob to the
- // specified output file
+ // specified output file
try {
outputBlob = new FileOutputStream(rValue + ".out");
} catch (IOException e) {
System.out.println("CMCEnroll: unable to open file " +
- rValue + ".out" + " for writing:\n" + e);
+ rValue + ".out" + " for writing:\n" + e);
return;
}
-
+
System.out.println(HEADER);
System.out.println(asciiBASE64Blob + TRAILER);
try {
@@ -448,23 +446,23 @@ public class CMCEnroll {
outputBlob.write(asciiBASE64Blob.getBytes());
} catch (IOException e) {
System.out.println("CMCEnroll: I/O error " +
- "encountered during write():\n" +
- e);
+ "encountered during write():\n" +
+ e);
}
-
+
try {
outputBlob.close();
} catch (IOException e) {
System.out.println("CMCEnroll: Unexpected error " +
- "encountered while attempting to close() " +
- "\n" + e);
+ "encountered while attempting to close() " +
+ "\n" + e);
}
-
- }catch (Exception e) {
+
+ } catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
-
+
return;
}
}
diff --git a/pki/base/java-tools/src/com/netscape/cmstools/CMCRequest.java b/pki/base/java-tools/src/com/netscape/cmstools/CMCRequest.java
index e7a23a85..aabce4f6 100644
--- a/pki/base/java-tools/src/com/netscape/cmstools/CMCRequest.java
+++ b/pki/base/java-tools/src/com/netscape/cmstools/CMCRequest.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmstools;
-
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
@@ -85,31 +84,31 @@ import org.mozilla.jss.util.Password;
import com.netscape.cmsutil.util.HMACDigest;
-
/**
* Tool for creating CMC full request
*
* <P>
+ *
* @version $Revision$, $Date$
- *
+ *
*/
public class CMCRequest {
public static final String PR_REQUEST_CMC = "CMC";
public static final String PR_REQUEST_CRMF = "CRMF";
- public static final int ARGC = 1;
+ public static final int ARGC = 1;
private static final String CERTDB = "cert8.db";
private static final String KEYDB = "key3.db";
public static final String HEADER = "-----BEGIN NEW CERTIFICATE REQUEST-----";
public static final String TRAILER = "-----END NEW CERTIFICATE REQUEST-----";
-
- void cleanArgs(String[] s) {
-
+
+ void cleanArgs(String[] s) {
+
}
public static X509Certificate getCertificate(String tokenname,
- String nickname) throws Exception {
+ String nickname) throws Exception {
CryptoManager manager = CryptoManager.getInstance();
CryptoToken token = null;
@@ -133,28 +132,29 @@ public class CMCRequest {
}
public static java.security.PrivateKey getPrivateKey(String tokenname, String nickname)
- throws Exception {
+ throws Exception {
X509Certificate cert = getCertificate(tokenname, nickname);
return CryptoManager.getInstance().findPrivKeyByCert(cert);
}
-
/**
* getCMCBlob create and return the enrollent request.
* <P>
- * @param signerCert the certificate of the authorized signer of the CMC revocation request.
+ *
+ * @param signerCert the certificate of the authorized signer of the CMC
+ * revocation request.
* @param nickname the nickname of the certificate inside the token.
* @param rValue CRMF/PKCS10 request.
- * @param format either crmf or pkcs10
+ * @param format either crmf or pkcs10
* @return the CMC enrollment request encoded in base64
*/
- static ContentInfo getCMCBlob(X509Certificate signerCert, String nickname,
- String[] rValue, String format, CryptoManager manager, String transactionMgtEnable,
- String transactionMgtId, String identityProofEnable, String identityProofSharedSecret,
- SEQUENCE controlSeq, SEQUENCE otherMsgSeq, int bpid) {
-
+ static ContentInfo getCMCBlob(X509Certificate signerCert, String nickname,
+ String[] rValue, String format, CryptoManager manager, String transactionMgtEnable,
+ String transactionMgtId, String identityProofEnable, String identityProofSharedSecret,
+ SEQUENCE controlSeq, SEQUENCE otherMsgSeq, int bpid) {
+
String tokenname = "internal";
ContentInfo fullEnrollmentReq = null;
@@ -167,59 +167,59 @@ public class CMCRequest {
X509CertImpl impl = new X509CertImpl(certB);
X500Name issuerName = (X500Name) impl.getIssuerDN();
byte[] issuerByte = issuerName.getEncoded();
- ByteArrayInputStream istream = new ByteArrayInputStream(issuerByte);
-
+ ByteArrayInputStream istream = new ByteArrayInputStream(issuerByte);
+
Name issuer = (Name) Name.getTemplate().decode(istream);
IssuerAndSerialNumber ias = new IssuerAndSerialNumber(
- issuer, new INTEGER(serialno.toString()));
+ issuer, new INTEGER(serialno.toString()));
- si = new SignerIdentifier(
- SignerIdentifier.ISSUER_AND_SERIALNUMBER, ias, null);
+ si = new SignerIdentifier(
+ SignerIdentifier.ISSUER_AND_SERIALNUMBER, ias, null);
privKey = getPrivateKey(tokenname, nickname);
TaggedRequest trq = null;
PKCS10 pkcs = null;
CertReqMsg certReqMsg = null;
-
+
// create CMC req
SEQUENCE reqSequence = new SEQUENCE();
try {
- for (int k=0; k<rValue.length; k++) {
- String asciiBASE64Blob = rValue[k];
+ for (int k = 0; k < rValue.length; k++) {
+ String asciiBASE64Blob = rValue[k];
byte[] decodedBytes = com.netscape.osutil.OSUtil.AtoB(asciiBASE64Blob);
-
+
if (format.equals("crmf")) {
- ByteArrayInputStream reqBlob =
- new ByteArrayInputStream(decodedBytes);
+ ByteArrayInputStream reqBlob =
+ new ByteArrayInputStream(decodedBytes);
SEQUENCE crmfMsgs = null;
- try {
- crmfMsgs = (SEQUENCE)new SEQUENCE.OF_Template(new
- CertReqMsg.Template()).decode(reqBlob);
+ try {
+ crmfMsgs = (SEQUENCE) new SEQUENCE.OF_Template(new
+ CertReqMsg.Template()).decode(reqBlob);
} catch (InvalidBERException ee) {
System.out.println("This is not a crmf request. Or this request has an error.");
System.exit(1);
}
int nummsgs = crmfMsgs.size();
- certReqMsg = (CertReqMsg)crmfMsgs.elementAt(0);
+ certReqMsg = (CertReqMsg) crmfMsgs.elementAt(0);
trq = new TaggedRequest(TaggedRequest.CRMF, null,
- certReqMsg);
+ certReqMsg);
} else if (format.equals("pkcs10")) {
try {
pkcs = new PKCS10(decodedBytes);
} catch (IllegalArgumentException e) {
System.out.println("This is not a PKCS10 request.");
System.exit(1);
- }
+ }
ByteArrayInputStream crInputStream = new ByteArrayInputStream(
- pkcs.toByteArray());
+ pkcs.toByteArray());
CertificationRequest cr = (CertificationRequest)
- CertificationRequest.getTemplate().decode(crInputStream);
+ CertificationRequest.getTemplate().decode(crInputStream);
TaggedCertificationRequest tcr = new TaggedCertificationRequest(
- new INTEGER(bpid++), cr);
+ new INTEGER(bpid++), cr);
trq = new
- TaggedRequest(TaggedRequest.PKCS10, tcr, null);
+ TaggedRequest(TaggedRequest.PKCS10, tcr, null);
} else {
- System.out.println("Unrecognized request format: "+format);
+ System.out.println("Unrecognized request format: " + format);
System.exit(1);
}
reqSequence.addElement(trq);
@@ -231,19 +231,19 @@ public class CMCRequest {
} catch (NoSuchAlgorithmException e) {
throw new IOException("Internal Error - " + e.toString());
}
-
+
if (transactionMgtEnable.equals("true"))
- bpid = addTransactionAttr(bpid, controlSeq, transactionMgtId, format,
- pkcs, certReqMsg);
+ bpid = addTransactionAttr(bpid, controlSeq, transactionMgtId, format,
+ pkcs, certReqMsg);
if (identityProofEnable.equals("true"))
- bpid = addIdentityProofAttr(bpid, controlSeq, reqSequence,
- identityProofSharedSecret);
+ bpid = addIdentityProofAttr(bpid, controlSeq, reqSequence,
+ identityProofSharedSecret);
PKIData pkidata = new PKIData(controlSeq, reqSequence, new SEQUENCE(), otherMsgSeq);
-
+
EncapsulatedContentInfo ci = new
- EncapsulatedContentInfo(OBJECT_IDENTIFIER.id_cct_PKIData, pkidata);
+ EncapsulatedContentInfo(OBJECT_IDENTIFIER.id_cct_PKIData, pkidata);
// SHA1 is the default digest Alg for now.
DigestAlgorithm digestAlg = null;
SignatureAlgorithm signAlg = SignatureAlgorithm.RSASignatureWithSHA1Digest;
@@ -253,11 +253,11 @@ public class CMCRequest {
signAlg = SignatureAlgorithm.DSASignatureWithSHA1Digest;
MessageDigest SHADigest = null;
- byte[] digest = null;
+ byte[] digest = null;
try {
SHADigest = MessageDigest.getInstance("SHA1");
digestAlg = DigestAlgorithm.SHA1;
-
+
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
pkidata.encode((OutputStream) ostream);
@@ -265,18 +265,18 @@ public class CMCRequest {
} catch (NoSuchAlgorithmException e) {
}
SignerInfo signInfo = new
- SignerInfo(si, null, null, OBJECT_IDENTIFIER.id_cct_PKIData, digest, signAlg,
- (org.mozilla.jss.crypto.PrivateKey) privKey);
+ SignerInfo(si, null, null, OBJECT_IDENTIFIER.id_cct_PKIData, digest, signAlg,
+ (org.mozilla.jss.crypto.PrivateKey) privKey);
SET signInfos = new SET();
signInfos.addElement(signInfo);
-
+
SET digestAlgs = new SET();
if (digestAlg != null) {
AlgorithmIdentifier ai = new AlgorithmIdentifier(digestAlg.toOID(), null);
digestAlgs.addElement(ai);
}
-
+
org.mozilla.jss.crypto.X509Certificate[] agentChain = manager.buildCertificateChain(signerCert);
SET certs = new SET();
@@ -288,7 +288,7 @@ public class CMCRequest {
fullEnrollmentReq = new ContentInfo(req);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(bs);
-
+
if (fullEnrollmentReq != null) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
@@ -300,7 +300,7 @@ public class CMCRequest {
System.out.println("");
System.out.println("The CMC enrollment request in base-64 encoded format:");
System.out.println("");
- System.out.println(asciiBASE64Blob);
+ System.out.println(asciiBASE64Blob);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
@@ -400,7 +400,7 @@ public class CMCRequest {
System.out.println("revRequest.serial=61");
System.out.println("");
System.out.println("#revRequest.reason: The reason for revoking this certificate: ");
- System.out.println("# unspecified, keyCompromise, caCompromise,");
+ System.out.println("# unspecified, keyCompromise, caCompromise,");
System.out.println("# affiliationChanged, superseded, cessationOfOperation,");
System.out.println("# certificateHold, removeFromCRL");
System.out.println("revRequest.reason=unspecified");
@@ -443,22 +443,22 @@ public class CMCRequest {
private static int addLraPopWitnessAttr(int bpid, SEQUENCE seq, String bodyPartIDs) {
StringTokenizer tokenizer = new StringTokenizer(bodyPartIDs, " ");
- SEQUENCE bodyList = new SEQUENCE();
+ SEQUENCE bodyList = new SEQUENCE();
while (tokenizer.hasMoreTokens()) {
- String s = (String)tokenizer.nextToken();
+ String s = (String) tokenizer.nextToken();
bodyList.addElement(new INTEGER(s));
}
LraPopWitness lra = new LraPopWitness(new INTEGER(0), bodyList);
TaggedAttribute cont = new TaggedAttribute(new
- INTEGER(bpid++), OBJECT_IDENTIFIER.id_cmc_lraPOPWitness, lra);
- System.out.println("Successfully create LRA POP witness control. bpid = "+(bpid-1));
- System.out.println("");
+ INTEGER(bpid++), OBJECT_IDENTIFIER.id_cmc_lraPOPWitness, lra);
+ System.out.println("Successfully create LRA POP witness control. bpid = " + (bpid - 1));
+ System.out.println("");
seq.addElement(cont);
return bpid;
}
- private static int addConfirmCertAttr(int bpid, SEQUENCE seq, String confirmCertIssuer,
- String confirmCertSerial) {
+ private static int addConfirmCertAttr(int bpid, SEQUENCE seq, String confirmCertIssuer,
+ String confirmCertSerial) {
try {
INTEGER serial = new INTEGER(confirmCertSerial);
X500Name issuername = new X500Name(confirmCertIssuer);
@@ -466,10 +466,10 @@ public class CMCRequest {
ANY issuern = new ANY(issuerbyte);
CMCCertId cmcCertId = new CMCCertId(issuern, serial, null);
TaggedAttribute cmcCertIdControl = new TaggedAttribute(new
- INTEGER(bpid++),
- OBJECT_IDENTIFIER.id_cmc_idConfirmCertAcceptance, cmcCertId);
- System.out.println("Successfully create confirm certificate acceptance control. bpid = "+(bpid-1));
- System.out.println("");
+ INTEGER(bpid++),
+ OBJECT_IDENTIFIER.id_cmc_idConfirmCertAcceptance, cmcCertId);
+ System.out.println("Successfully create confirm certificate acceptance control. bpid = " + (bpid - 1));
+ System.out.println("");
seq.addElement(cmcCertIdControl);
} catch (Exception e) {
System.out.println("Error in creating confirm certificate acceptance control. Check the parameters.");
@@ -501,10 +501,10 @@ public class CMCRequest {
System.exit(1);
return RevRequest.unspecified;
- }
+ }
- private static int addIdentityProofAttr(int bpid, SEQUENCE seq, SEQUENCE reqSequence,
- String sharedSecret) {
+ private static int addIdentityProofAttr(int bpid, SEQUENCE seq, SEQUENCE reqSequence,
+ String sharedSecret) {
byte[] b = ASN1Util.encode(reqSequence);
byte[] key = null;
byte[] finalDigest = null;
@@ -512,8 +512,8 @@ public class CMCRequest {
MessageDigest SHA1Digest = MessageDigest.getInstance("SHA1");
key = SHA1Digest.digest(sharedSecret.getBytes());
} catch (NoSuchAlgorithmException ex) {
- System.out.println( "CMCRequest::addIdentityProofAttr() - "
- + "No such algorithm!" );
+ System.out.println("CMCRequest::addIdentityProofAttr() - "
+ + "No such algorithm!");
return -1;
}
@@ -526,29 +526,29 @@ public class CMCRequest {
}
TaggedAttribute identityProof = new TaggedAttribute(new
- INTEGER(bpid++), OBJECT_IDENTIFIER.id_cmc_identityProof,
- new OCTET_STRING(finalDigest));
+ INTEGER(bpid++), OBJECT_IDENTIFIER.id_cmc_identityProof,
+ new OCTET_STRING(finalDigest));
seq.addElement(identityProof);
System.out.println("Identity Proof control: ");
System.out.print(" Value: ");
- for (int i=0; i<finalDigest.length; i++) {
- System.out.print(finalDigest[i]+" ");
- }
+ for (int i = 0; i < finalDigest.length; i++) {
+ System.out.print(finalDigest[i] + " ");
+ }
System.out.println("");
- System.out.println("Successfully create identityProof control. bpid = "+(bpid-1));
+ System.out.println("Successfully create identityProof control. bpid = " + (bpid - 1));
System.out.println("");
- return bpid;
+ return bpid;
}
- private static int addRevRequestAttr(int bpid, SEQUENCE seq, SEQUENCE otherMsgSeq, String nickname,
- String revRequestIssuer, String revRequestSerial, String revRequestReason,
- String revRequestSharedSecret, String revRequestComment, String invalidityDatePresent,
- CryptoManager manager) {
- try {
+ private static int addRevRequestAttr(int bpid, SEQUENCE seq, SEQUENCE otherMsgSeq, String nickname,
+ String revRequestIssuer, String revRequestSerial, String revRequestReason,
+ String revRequestSharedSecret, String revRequestComment, String invalidityDatePresent,
+ CryptoManager manager) {
+ try {
if (nickname.length() <= 0) {
System.out.println("The nickname for the certificate being revoked is null");
System.exit(1);
- }
+ }
String nickname1 = nickname;
UTF8String comment = null;
OCTET_STRING sharedSecret = null;
@@ -558,27 +558,27 @@ public class CMCRequest {
ENUMERATED reason = toCRLReason(revRequestReason);
if (revRequestSharedSecret.length() > 0)
sharedSecret = new OCTET_STRING(revRequestSharedSecret.getBytes());
- if (revRequestComment.length() > 0)
+ if (revRequestComment.length() > 0)
comment = new UTF8String(revRequestComment);
if (invalidityDatePresent.equals("true"))
d = new GeneralizedTime(new Date());
RevRequest revRequest =
- new RevRequest(new ANY(subjectname.getEncoded()), snumber,
- reason, d, sharedSecret, comment);
+ new RevRequest(new ANY(subjectname.getEncoded()), snumber,
+ reason, d, sharedSecret, comment);
int revokeBpid = bpid;
TaggedAttribute revRequestControl = new TaggedAttribute(
- new INTEGER(bpid++),
- OBJECT_IDENTIFIER.id_cmc_revokeRequest, revRequest);
+ new INTEGER(bpid++),
+ OBJECT_IDENTIFIER.id_cmc_revokeRequest, revRequest);
seq.addElement(revRequestControl);
if (sharedSecret != null) {
- System.out.println("Successfully create revRequest control. bpid = "+(bpid-1));
+ System.out.println("Successfully create revRequest control. bpid = " + (bpid - 1));
System.out.println("");
- return bpid;
+ return bpid;
}
EncapsulatedContentInfo revokeContent = new EncapsulatedContentInfo(
- OBJECT_IDENTIFIER.id_cct_PKIData, revRequestControl);
+ OBJECT_IDENTIFIER.id_cct_PKIData, revRequestControl);
DigestAlgorithm digestAlg1 = null;
SignatureAlgorithm signAlg1 = SignatureAlgorithm.RSASignatureWithSHA1Digest;
java.security.PrivateKey revokePrivKey = null;
@@ -586,12 +586,12 @@ public class CMCRequest {
try {
revokeCert = manager.findCertByNickname(nickname1);
} catch (ObjectNotFoundException e) {
- System.out.println("Certificate not found: "+nickname1);
+ System.out.println("Certificate not found: " + nickname1);
System.exit(1);
}
revokePrivKey = manager.findPrivKeyByCert(revokeCert);
org.mozilla.jss.crypto.PrivateKey.Type signingKeyType1 =
- ((org.mozilla.jss.crypto.PrivateKey) revokePrivKey).getType();
+ ((org.mozilla.jss.crypto.PrivateKey) revokePrivKey).getType();
if (signingKeyType1.equals(org.mozilla.jss.crypto.PrivateKey.Type.DSA))
signAlg1 = SignatureAlgorithm.DSASignatureWithSHA1Digest;
@@ -609,15 +609,15 @@ public class CMCRequest {
}
ByteArrayInputStream bistream =
- new ByteArrayInputStream(subjectname.getEncoded());
- Name iname = (Name)Name.getTemplate().decode(bistream);
+ new ByteArrayInputStream(subjectname.getEncoded());
+ Name iname = (Name) Name.getTemplate().decode(bistream);
IssuerAndSerialNumber ias1 = new IssuerAndSerialNumber(iname, snumber);
SignerIdentifier rsi = new SignerIdentifier(
- SignerIdentifier.ISSUER_AND_SERIALNUMBER, ias1, null);
+ SignerIdentifier.ISSUER_AND_SERIALNUMBER, ias1, null);
SignerInfo signInfo1 = new SignerInfo(rsi, null, null,
- OBJECT_IDENTIFIER.id_cct_PKIData, rdigest, signAlg1,
+ OBJECT_IDENTIFIER.id_cct_PKIData, rdigest, signAlg1,
(org.mozilla.jss.crypto.PrivateKey) revokePrivKey);
SET signInfos1 = new SET();
@@ -629,29 +629,29 @@ public class CMCRequest {
}
org.mozilla.jss.crypto.X509Certificate[] revokeCertChain =
- manager.buildCertificateChain(revokeCert);
+ manager.buildCertificateChain(revokeCert);
SET certs1 = new SET();
- for (int i=0; i<revokeCertChain.length; i++) {
+ for (int i = 0; i < revokeCertChain.length; i++) {
ANY cert1 = new ANY(revokeCertChain[i].getEncoded());
certs1.addElement(cert1);
}
- SignedData sData = new SignedData(digestAlgs1, revokeContent, certs1, null, signInfos1);
+ SignedData sData = new SignedData(digestAlgs1, revokeContent, certs1, null, signInfos1);
OBJECT_IDENTIFIER signedDataOID = new OBJECT_IDENTIFIER("1.2.840.113549.1.7.2");
ByteArrayOutputStream bos1 = new ByteArrayOutputStream();
sData.encode(bos1);
OtherMsg otherMsg = new OtherMsg(new INTEGER(revokeBpid), signedDataOID, new ANY(bos1.toByteArray()));
otherMsgSeq.addElement(otherMsg);
- System.out.println("Successfully create revRequest control. bpid = "+(bpid-1));
+ System.out.println("Successfully create revRequest control. bpid = " + (bpid - 1));
System.out.println("");
} catch (Exception e) {
System.out.println("Error in creating revRequest control. Check the parameters.");
System.exit(1);
}
-
+
return bpid;
}
-
+
private static int addGetCertAttr(int bpid, SEQUENCE seq, String issuer, String serial) {
try {
INTEGER serialno = new INTEGER(serial);
@@ -660,16 +660,16 @@ public class CMCRequest {
ANY issuern = new ANY(issuerbyte);
GetCert getCert = new GetCert(issuern, serialno);
TaggedAttribute getCertControl = new TaggedAttribute(new
- INTEGER(bpid++),
- OBJECT_IDENTIFIER.id_cmc_getCert, getCert);
- System.out.println("Successfully create get certificate control. bpid = "+(bpid-1));
+ INTEGER(bpid++),
+ OBJECT_IDENTIFIER.id_cmc_getCert, getCert);
+ System.out.println("Successfully create get certificate control. bpid = " + (bpid - 1));
System.out.println("");
seq.addElement(getCertControl);
} catch (Exception e) {
System.out.println("Error in creating get certificate control. Check the parameters.");
System.exit(1);
}
-
+
return bpid;
}
@@ -678,15 +678,15 @@ public class CMCRequest {
byte bvalue[] = str.getBytes();
System.out.println("Data Return Control: ");
String ss = " Value: ";
- for (int m=0; m<bvalue.length; m++) {
- ss = ss+bvalue[m]+" ";
+ for (int m = 0; m < bvalue.length; m++) {
+ ss = ss + bvalue[m] + " ";
}
System.out.println(ss);
OCTET_STRING s = new OCTET_STRING(bvalue);
TaggedAttribute dataReturnControl = new TaggedAttribute(new
- INTEGER(bpid++), OBJECT_IDENTIFIER.id_cmc_dataReturn, s);
+ INTEGER(bpid++), OBJECT_IDENTIFIER.id_cmc_dataReturn, s);
seq.addElement(dataReturnControl);
- System.out.println("Successfully create data return control. bpid = "+(bpid-1));
+ System.out.println("Successfully create data return control. bpid = " + (bpid - 1));
System.out.println("");
} catch (Exception e) {
System.out.println("Error in creating data return control. Check the parameters.");
@@ -696,8 +696,8 @@ public class CMCRequest {
return bpid;
}
- private static int addTransactionAttr(int bpid, SEQUENCE seq, String id, String format,
- PKCS10 pkcs, CertReqMsg certReqMsg) {
+ private static int addTransactionAttr(int bpid, SEQUENCE seq, String id, String format,
+ PKCS10 pkcs, CertReqMsg certReqMsg) {
byte[] transId = null;
Date date = new Date();
String salt = "lala123" + date.toString();
@@ -718,21 +718,21 @@ public class CMCRequest {
transId = salt.getBytes();
}
} else {
- transId = id.getBytes();
+ transId = id.getBytes();
}
- if( transId == null ) {
- System.out.println( "CMCRequest::addTransactionAttr() - "
- + "transId is null!" );
+ if (transId == null) {
+ System.out.println("CMCRequest::addTransactionAttr() - "
+ + "transId is null!");
return -1;
}
INTEGER ii = new INTEGER(1, transId);
TaggedAttribute transactionId = new TaggedAttribute(new
- INTEGER(bpid++), OBJECT_IDENTIFIER.id_cmc_transactionId, ii);
+ INTEGER(bpid++), OBJECT_IDENTIFIER.id_cmc_transactionId, ii);
System.out.println("Transaction ID control: ");
- System.out.println(" Value: "+ii.toString());
- System.out.println("Successfully create transaction management control. bpid = "+(bpid-1));
+ System.out.println(" Value: " + ii.toString());
+ System.out.println("Successfully create transaction management control. bpid = " + (bpid - 1));
System.out.println("");
seq.addElement(transactionId);
@@ -758,64 +758,64 @@ public class CMCRequest {
sn = com.netscape.osutil.OSUtil.BtoA(dig);
}
- byte bb[] = sn.getBytes();
+ byte bb[] = sn.getBytes();
System.out.println("SenderNonce control: ");
String ss = " Value: ";
- for (int m=0; m<bb.length; m++) {
- ss = ss+bb[m]+" ";
+ for (int m = 0; m < bb.length; m++) {
+ ss = ss + bb[m] + " ";
}
System.out.println(ss);
TaggedAttribute senderNonce = new TaggedAttribute(new
- INTEGER(bpid++), OBJECT_IDENTIFIER.id_cmc_senderNonce,
- new OCTET_STRING(sn.getBytes()));
- System.out.println("Successfully create sender nonce control. bpid = "+(bpid-1));
+ INTEGER(bpid++), OBJECT_IDENTIFIER.id_cmc_senderNonce,
+ new OCTET_STRING(sn.getBytes()));
+ System.out.println("Successfully create sender nonce control. bpid = " + (bpid - 1));
System.out.println("");
seq.addElement(senderNonce);
return bpid;
}
private static int addPopLinkWitnessAttr(int bpid, SEQUENCE controlSeq) {
-byte[] seed =
-{0x10, 0x53, 0x42, 0x24, 0x1a, 0x2a, 0x35, 0x3c,
- 0x7a, 0x52, 0x54, 0x56, 0x71, 0x65, 0x66, 0x4c,
- 0x51, 0x34, 0x35, 0x23, 0x3c, 0x42, 0x43, 0x45,
- 0x61, 0x4f, 0x6e, 0x43, 0x1e, 0x2a, 0x2b, 0x31,
- 0x32, 0x34, 0x35, 0x36, 0x55, 0x51, 0x48, 0x14,
- 0x16, 0x29, 0x41, 0x42, 0x43, 0x7b, 0x63, 0x44,
- 0x6a, 0x12, 0x6b, 0x3c, 0x4c, 0x3f, 0x00, 0x14,
- 0x51, 0x61, 0x15, 0x22, 0x23, 0x5f, 0x5e, 0x69};
+ byte[] seed =
+ { 0x10, 0x53, 0x42, 0x24, 0x1a, 0x2a, 0x35, 0x3c,
+ 0x7a, 0x52, 0x54, 0x56, 0x71, 0x65, 0x66, 0x4c,
+ 0x51, 0x34, 0x35, 0x23, 0x3c, 0x42, 0x43, 0x45,
+ 0x61, 0x4f, 0x6e, 0x43, 0x1e, 0x2a, 0x2b, 0x31,
+ 0x32, 0x34, 0x35, 0x36, 0x55, 0x51, 0x48, 0x14,
+ 0x16, 0x29, 0x41, 0x42, 0x43, 0x7b, 0x63, 0x44,
+ 0x6a, 0x12, 0x6b, 0x3c, 0x4c, 0x3f, 0x00, 0x14,
+ 0x51, 0x61, 0x15, 0x22, 0x23, 0x5f, 0x5e, 0x69 };
TaggedAttribute idPOPLinkRandom = new TaggedAttribute(new
- INTEGER(bpid++), OBJECT_IDENTIFIER.id_cmc_idPOPLinkRandom,
- new OCTET_STRING(seed));
+ INTEGER(bpid++), OBJECT_IDENTIFIER.id_cmc_idPOPLinkRandom,
+ new OCTET_STRING(seed));
controlSeq.addElement(idPOPLinkRandom);
- System.out.println("Successfully create PopLinkWitness control. bpid = "+(bpid-1));
- System.out.println("");
+ System.out.println("Successfully create PopLinkWitness control. bpid = " + (bpid - 1));
+ System.out.println("");
return bpid;
}
- public static void main(String[]s) {
- String numRequests=null;
- String dbdir=null, nickname=null;
- String ifilename=null, ofilename=null, password=null, format=null;
+ public static void main(String[] s) {
+ String numRequests = null;
+ String dbdir = null, nickname = null;
+ String ifilename = null, ofilename = null, password = null, format = null;
FileOutputStream outputBlob = null;
String confirmCertEnable = "false", confirmCertIssuer = null, confirmCertSerial = null;
String getCertEnable = "false", getCertIssuer = null, getCertSerial = null;
- String dataReturnEnable = "false", dataReturnData = null;
+ String dataReturnEnable = "false", dataReturnData = null;
String transactionMgtEnable = "false", transactionMgtId = null;
String senderNonceEnable = "false", senderNonce = null;
String revCertNickname = "";
- String revRequestEnable = "false", revRequestIssuer = null, revRequestSerial= null;
+ String revRequestEnable = "false", revRequestIssuer = null, revRequestSerial = null;
String revRequestReason = null, revRequestSharedSecret = null, revRequestComment = null;
String revRequestInvalidityDatePresent = "false";
String identityProofEnable = "false", identityProofSharedSecret = null;
String popLinkWitnessEnable = "false";
String bodyPartIDs = null, lraPopWitnessEnable = "false";
- System.out.println("");
+ System.out.println("");
// Check that the correct # of arguments were submitted to the program
- if( s.length != ( ARGC ) ) {
+ if (s.length != (ARGC)) {
System.out.println("Wrong number of parameters:" + s.length);
printUsage();
}
@@ -825,16 +825,16 @@ byte[] seed =
try {
reader = new BufferedReader(new InputStreamReader(
new BufferedInputStream(
- new FileInputStream(
- configFile))));
+ new FileInputStream(
+ configFile))));
} catch (FileNotFoundException e) {
- System.out.println("CMCRequest: can't find configuration file: "+configFile);
+ System.out.println("CMCRequest: can't find configuration file: " + configFile);
printUsage();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
-
+
try {
String str = "";
while ((str = reader.readLine()) != null) {
@@ -842,14 +842,14 @@ byte[] seed =
if (!str.startsWith("#") && str.length() > 0) {
int index = str.indexOf("=");
String name = "";
- String val = "";
+ String val = "";
if (index == -1) {
- System.out.println("Error in configuration file: "+str);
+ System.out.println("Error in configuration file: " + str);
System.exit(1);
}
name = str.substring(0, index);
- if (index != str.length()-1)
- val = str.substring(index+1);
+ if (index != str.length() - 1)
+ val = str.substring(index + 1);
if (name.equals("format")) {
format = val;
@@ -942,15 +942,15 @@ byte[] seed =
}
StringTokenizer tokenizer = new StringTokenizer(ifilename, " ");
- String[] ifiles = new String[num];
- for (int i=0; i<num; i++) {
- String ss = (String)tokenizer.nextToken();
+ String[] ifiles = new String[num];
+ for (int i = 0; i < num; i++) {
+ String ss = (String) tokenizer.nextToken();
ifiles[i] = ss;
if (ss == null) {
System.out.println("Missing input file for the request.");
System.exit(1);
}
- }
+ }
if (ofilename == null) {
System.out.println("Missing output filename for the CMC request.");
@@ -975,13 +975,13 @@ byte[] seed =
try {
// initialize CryptoManager
if (dbdir == null)
- dbdir = ".";
- String mPrefix = "";
+ dbdir = ".";
+ String mPrefix = "";
System.out.println("cert/key prefix = " + mPrefix);
System.out.println("path = " + dbdir);
CryptoManager.InitializationValues vals =
- new CryptoManager.InitializationValues(dbdir, mPrefix,
- mPrefix, "secmod.db");
+ new CryptoManager.InitializationValues(dbdir, mPrefix,
+ mPrefix, "secmod.db");
CryptoManager.initialize(vals);
CryptoManager cm = CryptoManager.getInstance();
@@ -992,51 +992,51 @@ byte[] seed =
CryptoStore store = token.getCryptoStore();
X509Certificate[] list = store.getCertificates();
X509Certificate signerCert = null;
-
+
signerCert = cm.findCertByNickname(nickname);
-
+
String[] requests = new String[num];
- for (int i=0; i<num; i++) {
+ for (int i = 0; i < num; i++) {
BufferedReader inputBlob = null;
try {
inputBlob = new BufferedReader(new InputStreamReader(
- new BufferedInputStream(new FileInputStream(ifiles[i]))));
+ new BufferedInputStream(new FileInputStream(ifiles[i]))));
} catch (FileNotFoundException e) {
System.out.println("CMCRequest: can't find file " +
- ifiles[i] + ":\n" + e);
+ ifiles[i] + ":\n" + e);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
// (3) Read the entire contents of the specified BASE 64 encoded
- // blob into a String() object throwing away any
- // headers beginning with HEADER and any trailers beginning
- // with TRAILER
+ // blob into a String() object throwing away any
+ // headers beginning with HEADER and any trailers beginning
+ // with TRAILER
String asciiBASE64BlobChunk = new String();
String asciiBASE64Blob = new String();
try {
while ((asciiBASE64BlobChunk = inputBlob.readLine()) != null) {
if (!(asciiBASE64BlobChunk.startsWith(HEADER)) &&
- !(asciiBASE64BlobChunk.startsWith(TRAILER))) {
+ !(asciiBASE64BlobChunk.startsWith(TRAILER))) {
asciiBASE64Blob += asciiBASE64BlobChunk.trim();
}
}
requests[i] = asciiBASE64Blob;
} catch (IOException e) {
System.out.println("CMCRequest: Unexpected BASE64 " +
- "encoded error encountered in readLine():\n" +
- e);
+ "encoded error encountered in readLine():\n" +
+ e);
}
// (4) Close the DataInputStream() object
try {
inputBlob.close();
} catch (IOException e) {
System.out.println("CMCRequest(): Unexpected BASE64 " +
- "encoded error encountered in close():\n" + e);
+ "encoded error encountered in close():\n" + e);
}
- }
-
+ }
+
SEQUENCE controlSeq = new SEQUENCE();
int bpid = 1;
if (confirmCertEnable.equalsIgnoreCase("true")) {
@@ -1047,13 +1047,13 @@ byte[] seed =
}
bpid = addConfirmCertAttr(bpid, controlSeq, confirmCertIssuer, confirmCertSerial);
}
-
+
if (lraPopWitnessEnable.equalsIgnoreCase("true")) {
if (bodyPartIDs.length() == 0) {
System.out.println("Illegal parameters for Lra Pop Witness control");
printUsage();
System.exit(1);
- }
+ }
bpid = addLraPopWitnessAttr(bpid, controlSeq, bodyPartIDs);
}
@@ -1064,7 +1064,7 @@ byte[] seed =
printUsage();
System.exit(1);
}
-
+
bpid = addGetCertAttr(bpid, controlSeq, getCertIssuer, getCertSerial);
}
@@ -1086,46 +1086,46 @@ byte[] seed =
SEQUENCE otherMsgSeq = new SEQUENCE();
if (revRequestEnable.equalsIgnoreCase("true")) {
- if (revRequestIssuer.length() == 0 || revRequestSerial.length() == 0 ||
- revRequestReason.length() == 0) {
+ if (revRequestIssuer.length() == 0 || revRequestSerial.length() == 0 ||
+ revRequestReason.length() == 0) {
System.out.println("Illegal parameters for revRequest control");
printUsage();
System.exit(1);
}
- bpid = addRevRequestAttr(bpid, controlSeq, otherMsgSeq, revCertNickname,
- revRequestIssuer, revRequestSerial, revRequestReason, revRequestSharedSecret,
- revRequestComment, revRequestInvalidityDatePresent, cm);
+ bpid = addRevRequestAttr(bpid, controlSeq, otherMsgSeq, revCertNickname,
+ revRequestIssuer, revRequestSerial, revRequestReason, revRequestSharedSecret,
+ revRequestComment, revRequestInvalidityDatePresent, cm);
}
-
- ContentInfo cmcblob = getCMCBlob(signerCert, nickname, requests, format,
- cm, transactionMgtEnable, transactionMgtId, identityProofEnable,
- identityProofSharedSecret, controlSeq, otherMsgSeq, bpid);
+
+ ContentInfo cmcblob = getCMCBlob(signerCert, nickname, requests, format,
+ cm, transactionMgtEnable, transactionMgtId, identityProofEnable,
+ identityProofSharedSecret, controlSeq, otherMsgSeq, bpid);
// (6) Finally, print the actual CMC blob to the
- // specified output file
- FileOutputStream os = null;
+ // specified output file
+ FileOutputStream os = null;
try {
os = new FileOutputStream(ofilename);
cmcblob.encode(os);
System.out.println("");
System.out.println("");
- System.out.println("The CMC enrollment request in binary format is stored in "+
- ofilename+".");
+ System.out.println("The CMC enrollment request in binary format is stored in " +
+ ofilename + ".");
} catch (IOException e) {
- System.out.println("CMCRequest: unable to open file " +ofilename+
- " for writing:\n" + e);
+ System.out.println("CMCRequest: unable to open file " + ofilename +
+ " for writing:\n" + e);
}
-
+
try {
os.close();
} catch (IOException e) {
System.out.println("CMCRequest: Unexpected error " +
- "encountered while attempting to close() " +
- "\n" + e);
+ "encountered while attempting to close() " +
+ "\n" + e);
}
-
- }catch (Exception e) {
+
+ } catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
diff --git a/pki/base/java-tools/src/com/netscape/cmstools/CMCResponse.java b/pki/base/java-tools/src/com/netscape/cmstools/CMCResponse.java
index 33fce125..16373cdc 100644
--- a/pki/base/java-tools/src/com/netscape/cmstools/CMCResponse.java
+++ b/pki/base/java-tools/src/com/netscape/cmstools/CMCResponse.java
@@ -44,11 +44,11 @@ import org.mozilla.jss.pkix.cms.EncapsulatedContentInfo;
* Tool for parsing a CMC response
*
* <P>
+ *
* @version $Revision$, $Date$
- *
+ *
*/
-public class CMCResponse
-{
+public class CMCResponse {
public CMCResponse() {
}
@@ -61,17 +61,17 @@ public class CMCResponse
while (fis.available() > 0)
fis.read(bb, 0, 10000);
} catch (Exception e) {
- System.out.println("Error reading the response. Exception: "+e.toString());
+ System.out.println("Error reading the response. Exception: " + e.toString());
System.exit(1);
}
try {
ByteArrayInputStream bis = new ByteArrayInputStream(bb);
org.mozilla.jss.pkix.cms.ContentInfo cii = (org.mozilla.jss.pkix.cms.ContentInfo)
- org.mozilla.jss.pkix.cms.ContentInfo.getTemplate().decode(bis);
+ org.mozilla.jss.pkix.cms.ContentInfo.getTemplate().decode(bis);
- org.mozilla.jss.pkix.cms.SignedData cmcFullResp =
- (org.mozilla.jss.pkix.cms.SignedData)cii.getInterpretedContent();
+ org.mozilla.jss.pkix.cms.SignedData cmcFullResp =
+ (org.mozilla.jss.pkix.cms.SignedData) cii.getInterpretedContent();
String content = "";
if (cmcFullResp.hasCertificates()) {
@@ -85,7 +85,7 @@ public class CMCResponse
content += print.toString(Locale.getDefault());
}
}
-
+
System.out.println("Certificates: ");
System.out.println(content);
System.out.println("");
@@ -94,7 +94,7 @@ public class CMCResponse
OBJECT_IDENTIFIER dataid = new OBJECT_IDENTIFIER("1.2.840.113549.1.7.1");
if (!id.equals(OBJECT_IDENTIFIER.id_cct_PKIResponse) && !id.equals(dataid)) {
System.out.println("Invalid CMC Response Format");
- }
+ }
if (!ci.hasContent())
return;
@@ -103,39 +103,39 @@ public class CMCResponse
ByteArrayInputStream bbis = new ByteArrayInputStream(content1.toByteArray());
ResponseBody responseBody = (ResponseBody) (new ResponseBody.Template()).decode(bbis);
SEQUENCE controlSequence = responseBody.getControlSequence();
-
+
int numControls = controlSequence.size();
- System.out.println("Number of controls is "+numControls);
+ System.out.println("Number of controls is " + numControls);
INTEGER bodyPartId = null;
String error = "";
- for (int i=0; i<numControls; i++) {
+ for (int i = 0; i < numControls; i++) {
TaggedAttribute taggedAttr = (TaggedAttribute) controlSequence.elementAt(i);
OBJECT_IDENTIFIER type = taggedAttr.getType();
if (type.equals(OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo)) {
- System.out.println("Control #"+i+": CMCStatusInfo");
- System.out.println(" OID: "+type.toString());
+ System.out.println("Control #" + i + ": CMCStatusInfo");
+ System.out.println(" OID: " + type.toString());
SET sts = taggedAttr.getValues();
int numSts = sts.size();
for (int j = 0; j < numSts; j++) {
- CMCStatusInfo cst = (CMCStatusInfo)ASN1Util.decode(CMCStatusInfo.getTemplate(),
- ASN1Util.encode(sts.elementAt(j)));
+ CMCStatusInfo cst = (CMCStatusInfo) ASN1Util.decode(CMCStatusInfo.getTemplate(),
+ ASN1Util.encode(sts.elementAt(j)));
SEQUENCE seq = cst.getBodyList();
-
+
String s = " BodyList: ";
- for (int k=0; k < seq.size(); k++) {
- INTEGER n = (INTEGER)seq.elementAt(k);
- s = s+n.toString()+" ";
- }
+ for (int k = 0; k < seq.size(); k++) {
+ INTEGER n = (INTEGER) seq.elementAt(k);
+ s = s + n.toString() + " ";
+ }
System.out.println(s);
int st = cst.getStatus();
if (st != CMCStatusInfo.SUCCESS && st != CMCStatusInfo.CONFIRM_REQUIRED) {
String stString = cst.getStatusString();
if (stString != null)
- System.out.println(" Status String: "+stString);
+ System.out.println(" Status String: " + stString);
OtherInfo oi = cst.getOtherInfo();
- OtherInfo.Type t = oi.getType();
+ OtherInfo.Type t = oi.getType();
if (t == OtherInfo.FAIL)
System.out.println(" OtherInfo type: FAIL");
else if (t == OtherInfo.PEND) {
@@ -147,7 +147,7 @@ public class CMCResponse
String datePattern = "dd/MMM/yyyy:HH:mm:ss z";
SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern);
Date d = pi.getPendTime().toDate();
- System.out.println(" Date: "+dateFormat.format(d));
+ System.out.println(" Date: " + dateFormat.format(d));
}
}
} else if (st == CMCStatusInfo.SUCCESS) {
@@ -155,63 +155,63 @@ public class CMCResponse
}
}
} else if (type.equals(OBJECT_IDENTIFIER.id_cmc_transactionId)) {
- System.out.println("Control #"+i+": CMC Transaction Id");
- System.out.println(" OID: "+type.toString());
- SET transIds = taggedAttr.getValues();
- INTEGER num = (INTEGER)(ASN1Util.decode(INTEGER.getTemplate(),
- ASN1Util.encode(transIds.elementAt(0))));
- System.out.println(" INTEGER: "+num);
+ System.out.println("Control #" + i + ": CMC Transaction Id");
+ System.out.println(" OID: " + type.toString());
+ SET transIds = taggedAttr.getValues();
+ INTEGER num = (INTEGER) (ASN1Util.decode(INTEGER.getTemplate(),
+ ASN1Util.encode(transIds.elementAt(0))));
+ System.out.println(" INTEGER: " + num);
} else if (type.equals(OBJECT_IDENTIFIER.id_cmc_recipientNonce)) {
- System.out.println("Control #"+i+": CMC Recipient Nonce");
- System.out.println(" OID: "+type.toString());
+ System.out.println("Control #" + i + ": CMC Recipient Nonce");
+ System.out.println(" OID: " + type.toString());
SET recipientN = taggedAttr.getValues();
- OCTET_STRING str =
- (OCTET_STRING)(ASN1Util.decode(OCTET_STRING.getTemplate(),
- ASN1Util.encode(recipientN.elementAt(0))));
+ OCTET_STRING str =
+ (OCTET_STRING) (ASN1Util.decode(OCTET_STRING.getTemplate(),
+ ASN1Util.encode(recipientN.elementAt(0))));
byte b[] = str.toByteArray();
String s = " Value: ";
- for (int m=0; m<b.length; m++) {
- s = s+b[m]+" ";
+ for (int m = 0; m < b.length; m++) {
+ s = s + b[m] + " ";
}
System.out.println(s);
} else if (type.equals(OBJECT_IDENTIFIER.id_cmc_senderNonce)) {
- System.out.println("Control #"+i+": CMC Sender Nonce");
- System.out.println(" OID: "+type.toString());
+ System.out.println("Control #" + i + ": CMC Sender Nonce");
+ System.out.println(" OID: " + type.toString());
SET senderN = taggedAttr.getValues();
- OCTET_STRING str =
- (OCTET_STRING)(ASN1Util.decode(OCTET_STRING.getTemplate(),
- ASN1Util.encode(senderN.elementAt(0))));
+ OCTET_STRING str =
+ (OCTET_STRING) (ASN1Util.decode(OCTET_STRING.getTemplate(),
+ ASN1Util.encode(senderN.elementAt(0))));
byte b[] = str.toByteArray();
String s = " Value: ";
- for (int m=0; m<b.length; m++) {
- s = s+b[m]+" ";
+ for (int m = 0; m < b.length; m++) {
+ s = s + b[m] + " ";
}
System.out.println(s);
} else if (type.equals(OBJECT_IDENTIFIER.id_cmc_dataReturn)) {
- System.out.println("Control #"+i+": CMC Data Return");
- System.out.println(" OID: "+type.toString());
+ System.out.println("Control #" + i + ": CMC Data Return");
+ System.out.println(" OID: " + type.toString());
SET dataReturn = taggedAttr.getValues();
- OCTET_STRING str =
- (OCTET_STRING)(ASN1Util.decode(OCTET_STRING.getTemplate(),
- ASN1Util.encode(dataReturn.elementAt(0))));
+ OCTET_STRING str =
+ (OCTET_STRING) (ASN1Util.decode(OCTET_STRING.getTemplate(),
+ ASN1Util.encode(dataReturn.elementAt(0))));
byte b[] = str.toByteArray();
String s = " Value: ";
- for (int m=0; m<b.length; m++) {
- s = s+b[m]+" ";
+ for (int m = 0; m < b.length; m++) {
+ s = s + b[m] + " ";
}
System.out.println(s);
}
}
} catch (Exception e) {
- System.out.println("Error found in the response. Exception: "+e.toString());
+ System.out.println("Error found in the response. Exception: " + e.toString());
System.exit(1);
-
+
}
}
private static void printUsage() {
System.out.println("");
- System.out.println("Usage: CMCResponse -d <pathname for cert8.db> -i <pathname for CMC response in binary format> ");
+ System.out.println("Usage: CMCResponse -d <pathname for cert8.db> -i <pathname for CMC response in binary format> ");
}
public static void main(String args[]) {
@@ -221,11 +221,11 @@ public class CMCResponse
System.exit(1);
}
- for (int i=0; i<args.length; i++) {
+ for (int i = 0; i < args.length; i++) {
if (args[i].equals("-d"))
- path = args[i+1];
+ path = args[i + 1];
else if (args[i].equals("-i"))
- filename = args[i+1];
+ filename = args[i + 1];
}
if (filename == null || path == null) {
diff --git a/pki/base/java-tools/src/com/netscape/cmstools/CMCRevoke.java b/pki/base/java-tools/src/com/netscape/cmstools/CMCRevoke.java
index 85bdf5b1..09afaf35 100644
--- a/pki/base/java-tools/src/com/netscape/cmstools/CMCRevoke.java
+++ b/pki/base/java-tools/src/com/netscape/cmstools/CMCRevoke.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmstools;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
@@ -61,27 +60,26 @@ import org.mozilla.jss.pkix.primitive.AlgorithmIdentifier;
import org.mozilla.jss.pkix.primitive.Name;
import org.mozilla.jss.util.Password;
-
-
/**
* Tool for signing a CMC revocation request with an agent's certificate.
*
* <P>
+ *
* @version $Revision$, $Date$
*/
public class CMCRevoke {
- public static final int ARGC = 7;
+ public static final int ARGC = 7;
private static final String CERTDB = "cert8.db";
private static final String KEYDB = "key3.db";
public static final String HEADER = "-----BEGIN NEW CERTIFICATE REQUEST-----";
public static final String TRAILER = "-----END NEW CERTIFICATE REQUEST-----";
static String dValue = null, nValue = null, iValue = null, sValue = null, mValue = null, hValue = null, cValue = null;
- public static final String CMS_BASE_CA_SIGNINGCERT_NOT_FOUND="CA signing certificate not found";
+ public static final String CMS_BASE_CA_SIGNINGCERT_NOT_FOUND = "CA signing certificate not found";
public static final String PR_INTERNAL_TOKEN_NAME = "internal";
public static final String PR_REQUEST_CMC = "CMC";
- static String cleanArgs(String s) {
+ static String cleanArgs(String s) {
if (s.startsWith("\"") && s.endsWith("\""))
return s.substring(1, s.length() - 2);
else if (s.startsWith("\'") && s.endsWith("\'"))
@@ -89,94 +87,94 @@ public class CMCRevoke {
else
return s;
}
-
+
/**
- * Creates a new instance of CMCRevoke.
+ * Creates a new instance of CMCRevoke.
*/
- public static void main(String[]s) {
-
+ public static void main(String[] s) {
+
FileOutputStream outputBlob = null;
-
+
// default path is "."
String mPath = ".";
// default prefix is ""
String mPrefix = "";
-
+
boolean bWrongParam = false;
// (1) Check that two arguments were submitted to the program
if (s.length != (ARGC) && s.length != (ARGC - 1)) {
-
+
bWrongParam = true;
System.out.println("Wrong number of parameters:" + s.length);
System.out.println("Usage: CMCRevoke " +
- "-d<dir to cert8.db, key3.db> " +
- "-n<nickname> " +
- "-i<issuerName> " +
- "-s<serialName> " +
- "-m<reason to revoke> " +
- "-h<password to db> " +
- "-c<comment> ");
+ "-d<dir to cert8.db, key3.db> " +
+ "-n<nickname> " +
+ "-i<issuerName> " +
+ "-s<serialName> " +
+ "-m<reason to revoke> " +
+ "-h<password to db> " +
+ "-c<comment> ");
for (int i = 0; i < s.length; i++) {
System.out.println(i + ":" + s[i]);
}
- }else {
+ } else {
int length;
int i;
-
+
length = s.length;
for (i = 0; i < length; i++) {
if (s[i].startsWith("-d")) {
dValue = cleanArgs(s[i].substring(2));
- } else if (s[i].startsWith("-n")) {
+ } else if (s[i].startsWith("-n")) {
nValue = cleanArgs(s[i].substring(2));
- } else if (s[i].startsWith("-i")) {
+ } else if (s[i].startsWith("-i")) {
iValue = cleanArgs(s[i].substring(2));
- } else if (s[i].startsWith("-s")) {
+ } else if (s[i].startsWith("-s")) {
sValue = cleanArgs(s[i].substring(2));
- } else if (s[i].startsWith("-m")) {
+ } else if (s[i].startsWith("-m")) {
mValue = cleanArgs(s[i].substring(2));
- } else if (s[i].startsWith("-h")) {
+ } else if (s[i].startsWith("-h")) {
hValue = cleanArgs(s[i].substring(2));
- } else if (s[i].startsWith("-c")) {
+ } else if (s[i].startsWith("-c")) {
cValue = cleanArgs(s[i].substring(2));
}
-
+
}
// optional parameter
if (cValue == null)
cValue = new String();
- if (dValue == null || nValue == null || iValue == null || sValue == null || mValue == null || hValue == null)
+ if (dValue == null || nValue == null || iValue == null || sValue == null || mValue == null || hValue == null)
bWrongParam = true;
- else if (dValue.length() == 0 || nValue.length() == 0 || iValue.length() == 0 ||
- sValue.length() == 0 || mValue.length() == 0 || hValue.length() == 0)
+ else if (dValue.length() == 0 || nValue.length() == 0 || iValue.length() == 0 ||
+ sValue.length() == 0 || mValue.length() == 0 || hValue.length() == 0)
bWrongParam = true;
-
+
if (bWrongParam == true) {
System.out.println("Usage: CMCRevoke " +
- "-d<dir to cert8.db, key3.db> " +
- "-n<nickname> " +
- "-i<issuerName> " +
- "-s<serialName> " +
- "-m<reason to revoke> " +
- "-h<password to db> " +
- "-c<comment> ");
+ "-d<dir to cert8.db, key3.db> " +
+ "-n<nickname> " +
+ "-i<issuerName> " +
+ "-s<serialName> " +
+ "-m<reason to revoke> " +
+ "-h<password to db> " +
+ "-c<comment> ");
for (i = 0; i < s.length; i++) {
System.out.println(i + ":" + s[i]);
}
System.exit(0);
}
-
+
try {
// initialize CryptoManager
mPath = dValue;
System.out.println("cert/key prefix = " + mPrefix);
System.out.println("path = " + mPath);
CryptoManager.InitializationValues vals =
- new CryptoManager.InitializationValues(mPath, mPrefix, mPrefix, "secmod.db");
+ new CryptoManager.InitializationValues(mPath, mPrefix, mPrefix, "secmod.db");
CryptoManager.initialize(vals);
-
+
CryptoManager cm = CryptoManager.getInstance();
CryptoToken token = cm.getInternalKeyStorageToken();
Password pass = new Password(hValue.toCharArray());
@@ -185,16 +183,16 @@ public class CMCRevoke {
CryptoStore store = token.getCryptoStore();
X509Certificate[] list = store.getCertificates();
X509Certificate signerCert = null;
-
+
signerCert = cm.findCertByNickname(nValue);
String outBlob = createRevokeReq(signerCert, cm, nValue);
printCMCRevokeRequest(outBlob);
- }catch (Exception e) {
+ } catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
-
+
return;
}
}
@@ -202,12 +200,13 @@ public class CMCRevoke {
/**
* printout CMC revoke request in Base64 encoding to a file CMCRevoke.out
* <P>
+ *
* @param asciiBASE64Blob the ascii string of the request
*/
static void printCMCRevokeRequest(String asciiBASE64Blob) {
-
+
// (6) Finally, print the actual CMCSigning blob to the
- // specified output file
+ // specified output file
FileOutputStream outputBlob = null;
try {
@@ -216,7 +215,7 @@ public class CMCRevoke {
System.out.println("CMCSigning: unable to open file CMCRevoke.out for writing:\n" + e);
return;
}
-
+
System.out.println(HEADER);
System.out.println(asciiBASE64Blob + TRAILER);
try {
@@ -224,29 +223,30 @@ public class CMCRevoke {
outputBlob.write(asciiBASE64Blob.getBytes());
} catch (IOException e) {
System.out.println("CMCSigning: I/O error " +
- "encountered during write():\n" +
- e);
+ "encountered during write():\n" +
+ e);
}
-
+
try {
outputBlob.close();
} catch (IOException e) {
System.out.println("CMCSigning: Unexpected error " +
- "encountered while attempting to close() " +
- "\n" + e);
+ "encountered while attempting to close() " +
+ "\n" + e);
}
}
/**
* getCertificate find the certicate inside the token by its nickname.
* <P>
+ *
* @param manager the CrytoManager
* @param tokenname the name of the token. it's set to "internal".
* @param nickname the nickname of the certificate inside the token.
* @return the X509Certificate.
*/
public static X509Certificate getCertificate(CryptoManager manager, String tokenname,
- String nickname) throws NoSuchTokenException,
+ String nickname) throws NoSuchTokenException,
Exception, TokenException {
CryptoToken token = null;
@@ -272,19 +272,21 @@ public class CMCRevoke {
/**
* createRevokeReq create and return the revocation request.
* <P>
- * @param signerCert the certificate of the authorized signer of the CMC revocation request.
+ *
+ * @param signerCert the certificate of the authorized signer of the CMC
+ * revocation request.
* @param manager the crypto manger.
* @param nValue the nickname of the certificate inside the token.
* @return the CMC revocation request encoded in base64
*/
- static String createRevokeReq(X509Certificate signerCert, CryptoManager manager, String nValue) {
+ static String createRevokeReq(X509Certificate signerCert, CryptoManager manager, String nValue) {
java.security.PrivateKey privKey = null;
SignerIdentifier si = null;
ContentInfo fullEnrollmentReq = null;
String tokenname = "internal";
String asciiBASE64Blob = new String();
-
+
try {
String hasSki = "true";
@@ -294,23 +296,23 @@ public class CMCRevoke {
X509CertImpl impl = new X509CertImpl(certB);
X500Name issuerName = (X500Name) impl.getIssuerDN();
byte[] issuerByte = issuerName.getEncoded();
- ByteArrayInputStream istream = new ByteArrayInputStream(issuerByte);
-
+ ByteArrayInputStream istream = new ByteArrayInputStream(issuerByte);
+
Name issuer = (Name) Name.getTemplate().decode(istream);
IssuerAndSerialNumber ias = new IssuerAndSerialNumber(issuer, new INTEGER(serialno.toString()));
- si = new SignerIdentifier(SignerIdentifier.ISSUER_AND_SERIALNUMBER, ias, null);
+ si = new SignerIdentifier(SignerIdentifier.ISSUER_AND_SERIALNUMBER, ias, null);
X509Certificate cert = getCertificate(manager, tokenname, nValue);
-
+
privKey = manager.findPrivKeyByCert(cert);
- if( privKey == null ) {
- System.out.println( "CMCRevoke::createRevokeReq() - " +
- "privKey is null!" );
+ if (privKey == null) {
+ System.out.println("CMCRevoke::createRevokeReq() - " +
+ "privKey is null!");
return "";
}
- int bpid = 1;
+ int bpid = 1;
// Add some control sequence
// Verisign has transactionID,senderNonce
SEQUENCE controlSeq = new SEQUENCE();
@@ -338,25 +340,27 @@ public class CMCRevoke {
subjectName.addCommonName(iValue);
org.mozilla.jss.pkix.cmmf.RevRequest lRevokeRequest = new org.mozilla.jss.pkix.cmmf.RevRequest(new ANY((new X500Name(iValue)).getEncoded()),
new INTEGER(sValue),
- //org.mozilla.jss.pkix.cmmf.RevRequest.unspecified,
- new ENUMERATED((new Integer(mValue)). longValue()),
- //new GeneralizedTime(new Date(lValue)),
+ // org.mozilla.jss.pkix.cmmf.RevRequest.unspecified,
+ new ENUMERATED((new Integer(mValue)).longValue()),
+ // new GeneralizedTime(new Date(lValue)),
new OCTET_STRING(hValue.getBytes()),
new UTF8String(cValue.toCharArray()));
- //byte[] encoded = ASN1Util.encode(lRevokeRequest);
- //org.mozilla.jss.asn1.ASN1Template template = new org.mozilla.jss.pkix.cmmf.RevRequest.Template();
- //org.mozilla.jss.pkix.cmmf.RevRequest revRequest = (org.mozilla.jss.pkix.cmmf.RevRequest)
- // template.decode(new java.io.ByteArrayInputStream(
- // encoded));
-
+ // byte[] encoded = ASN1Util.encode(lRevokeRequest);
+ // org.mozilla.jss.asn1.ASN1Template template = new
+ // org.mozilla.jss.pkix.cmmf.RevRequest.Template();
+ // org.mozilla.jss.pkix.cmmf.RevRequest revRequest =
+ // (org.mozilla.jss.pkix.cmmf.RevRequest)
+ // template.decode(new java.io.ByteArrayInputStream(
+ // encoded));
+
ByteArrayOutputStream os = new ByteArrayOutputStream();
- //lRevokeRequest.encode(os); // khai
+ // lRevokeRequest.encode(os); // khai
TaggedAttribute revokeRequestTag = new TaggedAttribute(new INTEGER(bpid++), OBJECT_IDENTIFIER.id_cmc_revokeRequest,
lRevokeRequest);
controlSeq.addElement(revokeRequestTag);
PKIData pkidata = new PKIData(controlSeq, new SEQUENCE(), new SEQUENCE(), new SEQUENCE());
-
+
EncapsulatedContentInfo ci = new EncapsulatedContentInfo(OBJECT_IDENTIFIER.id_cct_PKIData, pkidata);
// SHA1 is the default digest Alg for now.
DigestAlgorithm digestAlg = null;
@@ -371,7 +375,7 @@ public class CMCRevoke {
try {
SHADigest = MessageDigest.getInstance("SHA1");
digestAlg = DigestAlgorithm.SHA1;
-
+
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
pkidata.encode((OutputStream) ostream);
@@ -383,7 +387,7 @@ public class CMCRevoke {
SET signInfos = new SET();
signInfos.addElement(signInfo);
-
+
SET digestAlgs = new SET();
if (digestAlg != null) {
@@ -391,7 +395,7 @@ public class CMCRevoke {
digestAlgs.addElement(ai);
}
-
+
org.mozilla.jss.crypto.X509Certificate[] agentChain = manager.buildCertificateChain(signerCert);
SET certs = new SET();
@@ -403,16 +407,16 @@ public class CMCRevoke {
SignedData req = new SignedData(digestAlgs, ci, certs, null, signInfos);
fullEnrollmentReq = new ContentInfo(req);
-
+
ByteArrayOutputStream bs = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(bs);
-
+
if (fullEnrollmentReq != null) {
// format is PR_REQUEST_CMC
fullEnrollmentReq.encode(os);
ps.print(com.netscape.osutil.OSUtil.BtoA(os.toByteArray()));
- ////fullEnrollmentReq.print(ps); // no header/trailer
- }
+ // //fullEnrollmentReq.print(ps); // no header/trailer
+ }
asciiBASE64Blob = bs.toString();
} catch (Exception e) {
diff --git a/pki/base/java-tools/src/com/netscape/cmstools/CRMFPopClient.java b/pki/base/java-tools/src/com/netscape/cmstools/CRMFPopClient.java
index c2d22173..a4153d9b 100644
--- a/pki/base/java-tools/src/com/netscape/cmstools/CRMFPopClient.java
+++ b/pki/base/java-tools/src/com/netscape/cmstools/CRMFPopClient.java
@@ -69,49 +69,51 @@ import org.mozilla.jss.util.Password;
import com.netscape.cmsutil.util.HMACDigest;
-
/**
- * A command-line utility used to generate a Certificate Request Message
- * Format (CRMF) request with proof of possesion (POP).
- *
+ * A command-line utility used to generate a Certificate Request Message Format
+ * (CRMF) request with proof of possesion (POP).
+ *
* Usage:
+ *
* <pre>
* CRMFPopClient TOKEN_PWD
* PROFILE_NAME HOST PORT USER_NAME REQUESTOR_NAME
* POP_OPTION
* SUBJECT_DN [OUTPUT_CERT_REQ]
- *
+ *
* --- or ---
- *
+ *
* CRMFPopClient TOKEN_PWD
* POP_OPTION
* OUTPUT_CERT_REQ SUBJECT_DN
- *
- *
+ *
+ *
* where POP_OPTION can be [POP_SUCCESS or POP_FAIL or POP_NONE]
* </pre>
* <p>
* Examples:
+ *
* <pre>
* CRMFPopClient password123
* caEncUserCert host.example.com 1026 MyUid MyUid
* [POP_SUCCESS or POP_FAIL or POP_NONE]
* CN=MyTest,C=US,UID=MyUid
- *
+ *
* --- or ---
- *
+ *
* CRMFPopClient password123
* caEncUserCert host.example.com 1026 joe joe
* [POP_SUCCESS or POP_FAIL or POP_NONE]
* CN=MyTest,C=US,UID=MyUid OUTPUT_CERT_REQ
- *
+ *
* --- or ---
- *
+ *
* CRMFPopClient password123
* [POP_SUCCESS or POP_FAIL or POP_NONE]
* OUTPUT_CERT_REQ CN=MyTest,C=US,UID=MyUid
* </pre>
* <p>
+ *
* <pre>
* IMPORTANT: The file "transport.txt" needs to be created to contain the
* transport certificate in its base64 encoded format. This
@@ -119,543 +121,499 @@ import com.netscape.cmsutil.util.HMACDigest;
* in base64 encoded format with the header and footer removed.
* </pre>
* <p>
+ *
* @version $Revision$, $Date$
*/
-public class CRMFPopClient
-{
-
- private static void usage()
- {
- System.out.println("");
- System.out.println("Description: A command-line utility used to generate a");
- System.out.println(" Certificate Request Message Format (CRMF)");
- System.out.println(" request with proof of possesion (POP).\n\n");
- System.out.println("Usage:");
- System.out.println("");
- System.out.println(" CRMFPopClient TOKEN_PWD");
- System.out.println(" PROFILE_NAME HOST PORT USER_NAME REQUESTOR_NAME");
- System.out.println(" POP_OPTION");
- System.out.println(" SUBJECT_DN [OUTPUT_CERT_REQ] \n");
- System.out.println(" --- or ---\n");
- System.out.println(" CRMFPopClient TOKEN_PWD");
- System.out.println(" POP_OPTION");
- System.out.println(" OUTPUT_CERT_REQ SUBJECT_DN\n\n");
- System.out.println(" where POP_OPTION can be [POP_SUCCESS or POP_FAIL or POP_NONE]\n\n");
- System.out.println("Examples:");
- System.out.println("");
- System.out.println(" CRMFPopClient password123");
- System.out.println(" caEncUserCert host.example.com 1026 MyUid MyUid");
- System.out.println(" [POP_SUCCESS or POP_FAIL or POP_NONE]");
- System.out.println(" CN=MyTest,C=US,UID=MyUid\n");
- System.out.println(" --- or ---\n");
- System.out.println(" CRMFPopClient password123");
- System.out.println(" caEncUserCert host.example.com 1026 MyUid myUid");
- System.out.println(" [POP_SUCCESS or POP_FAIL or POP_NONE]");
- System.out.println(" CN=MyTest,C=US,UID=MyUid OUTPUT_CERT_REQ\n");
- System.out.println(" --- or ---\n");
- System.out.println(" CRMFPopClient password123");
- System.out.println(" [POP_SUCCESS or POP_FAIL or POP_NONE]");
- System.out.println(" OUTPUT_CERT_REQ CN=MyTest,C=US,UID=MyUid");
- System.out.println("\n");
- System.out.println("IMPORTANT: The file \"transport.txt\" needs to be created to contain the");
- System.out.println(" transport certificate in its base64 encoded format. This");
- System.out.println(" file should consist of one line containing a single certificate");
- System.out.println(" in base64 encoded format with the header and footer removed.\n");
- }
- private static int getRealArgsLength(String args[])
- {
-
- int len = args.length;
-
- String curArg = "";
- int finalLen = len;
-
- for(int i = 0; i < len; i++)
- {
+public class CRMFPopClient {
+
+ private static void usage() {
+ System.out.println("");
+ System.out.println("Description: A command-line utility used to generate a");
+ System.out.println(" Certificate Request Message Format (CRMF)");
+ System.out.println(" request with proof of possesion (POP).\n\n");
+ System.out.println("Usage:");
+ System.out.println("");
+ System.out.println(" CRMFPopClient TOKEN_PWD");
+ System.out.println(" PROFILE_NAME HOST PORT USER_NAME REQUESTOR_NAME");
+ System.out.println(" POP_OPTION");
+ System.out.println(" SUBJECT_DN [OUTPUT_CERT_REQ] \n");
+ System.out.println(" --- or ---\n");
+ System.out.println(" CRMFPopClient TOKEN_PWD");
+ System.out.println(" POP_OPTION");
+ System.out.println(" OUTPUT_CERT_REQ SUBJECT_DN\n\n");
+ System.out.println(" where POP_OPTION can be [POP_SUCCESS or POP_FAIL or POP_NONE]\n\n");
+ System.out.println("Examples:");
+ System.out.println("");
+ System.out.println(" CRMFPopClient password123");
+ System.out.println(" caEncUserCert host.example.com 1026 MyUid MyUid");
+ System.out.println(" [POP_SUCCESS or POP_FAIL or POP_NONE]");
+ System.out.println(" CN=MyTest,C=US,UID=MyUid\n");
+ System.out.println(" --- or ---\n");
+ System.out.println(" CRMFPopClient password123");
+ System.out.println(" caEncUserCert host.example.com 1026 MyUid myUid");
+ System.out.println(" [POP_SUCCESS or POP_FAIL or POP_NONE]");
+ System.out.println(" CN=MyTest,C=US,UID=MyUid OUTPUT_CERT_REQ\n");
+ System.out.println(" --- or ---\n");
+ System.out.println(" CRMFPopClient password123");
+ System.out.println(" [POP_SUCCESS or POP_FAIL or POP_NONE]");
+ System.out.println(" OUTPUT_CERT_REQ CN=MyTest,C=US,UID=MyUid");
+ System.out.println("\n");
+ System.out.println("IMPORTANT: The file \"transport.txt\" needs to be created to contain the");
+ System.out.println(" transport certificate in its base64 encoded format. This");
+ System.out.println(" file should consist of one line containing a single certificate");
+ System.out.println(" in base64 encoded format with the header and footer removed.\n");
+ }
+
+ private static int getRealArgsLength(String args[]) {
+
+ int len = args.length;
+
+ String curArg = "";
+ int finalLen = len;
+
+ for (int i = 0; i < len; i++) {
+
+ curArg = args[i];
+ // System.out.println("arg[" + i + "] " + curArg);
+
+ if (curArg == null || curArg.equalsIgnoreCase("")) {
+ finalLen--;
+ }
- curArg = args[i];
- // System.out.println("arg[" + i + "] " + curArg);
+ }
+ // System.out.println("getRealArgsLength: returning " + finalLen);
- if(curArg == null || curArg.equalsIgnoreCase("")) {
- finalLen --;
- }
+ if (finalLen < 0)
+ finalLen = 0;
- }
+ return finalLen;
- //System.out.println("getRealArgsLength: returning " + finalLen);
+ }
- if(finalLen < 0)
- finalLen = 0;
+ public static void main(String args[]) {
+ String USER_PREFIX = "user";
+ int argsLen = getRealArgsLength(args);
- return finalLen;
+ // System.out.println("args length " + argsLen);
+ System.out.println("\n\nProof Of Possession Utility....");
+ System.out.println("");
+ if (argsLen == 0 || (argsLen != 8 && argsLen != 9 && argsLen != 10 && argsLen != 4)) {
+ usage();
+ return;
}
- public static void main(String args[])
- {
- String USER_PREFIX = "user";
-
-
- int argsLen = getRealArgsLength(args);
-
- // System.out.println("args length " + argsLen);
+ String DB_DIR = "./";
+ String TOKEN_PWD = args[0];
+ int KEY_LEN = 1024;
- System.out.println("\n\nProof Of Possession Utility....");
- System.out.println("");
+ int PORT = 0;
+ String USER_NAME = null;
+ String REQUESTOR_NAME = null;
+ String PROFILE_NAME = null;
- if(argsLen == 0 || (argsLen != 8 && argsLen != 9 && argsLen !=10 && argsLen != 4))
- {
- usage();
- return;
- }
+ String HOST = null;
+ String SUBJ_DN = null;
- String DB_DIR = "./";
- String TOKEN_PWD = args[0];
- int KEY_LEN = 1024;
+ if (argsLen >= 8) {
+ PROFILE_NAME = args[1];
+ HOST = args[2];
+ PORT = Integer.parseInt(args[3]);
- int PORT = 0;
- String USER_NAME = null;
- String REQUESTOR_NAME = null;
- String PROFILE_NAME = null;
-
- String HOST = null;
- String SUBJ_DN = null;
-
- if(argsLen >= 8)
- {
- PROFILE_NAME = args[1];
- HOST = args[2];
-
- PORT = Integer.parseInt(args[3]);
+ USER_NAME = args[4];
+ REQUESTOR_NAME = args[5];
- USER_NAME = args[4];
- REQUESTOR_NAME = args[5];
+ SUBJ_DN = args[7];
- SUBJ_DN = args[7];
-
- }
-
- String POP_OPTION = null;
- String OUTPUT_CERT_REQ = null;
-
- if(argsLen == 4)
- POP_OPTION = args[1];
- else
- POP_OPTION = args[6];
+ }
+ String POP_OPTION = null;
+ String OUTPUT_CERT_REQ = null;
- int doServerHit = 1;
+ if (argsLen == 4)
+ POP_OPTION = args[1];
+ else
+ POP_OPTION = args[6];
- if(argsLen >= 9) {
- OUTPUT_CERT_REQ = args[8];
- }
+ int doServerHit = 1;
- if(argsLen == 4)
- {
- doServerHit = 0;
- OUTPUT_CERT_REQ = args[2];
- SUBJ_DN = args[3];
- }
+ if (argsLen >= 9) {
+ OUTPUT_CERT_REQ = args[8];
+ }
+ if (argsLen == 4) {
+ doServerHit = 0;
+ OUTPUT_CERT_REQ = args[2];
+ SUBJ_DN = args[3];
+ }
- int dont_do_pop = 0;
+ int dont_do_pop = 0;
- if(POP_OPTION.equals("POP_NONE"))
- {
- dont_do_pop = 1;
- }
+ if (POP_OPTION.equals("POP_NONE")) {
+ dont_do_pop = 1;
+ }
- URL url = null;
- URLConnection conn = null;
- InputStream is = null;
- BufferedReader reader = null;
- boolean success = false;
- int num = 1;
- long total_time = 0;
- KeyPair pair = null;
+ URL url = null;
+ URLConnection conn = null;
+ InputStream is = null;
+ BufferedReader reader = null;
+ boolean success = false;
+ int num = 1;
+ long total_time = 0;
+ KeyPair pair = null;
+
+ boolean foundTransport = false;
+ String transportCert = null;
+ try {
+ BufferedReader br = new BufferedReader(new FileReader("./transport.txt"));
+ transportCert = br.readLine();
+ foundTransport = true;
+ } catch (Exception e) {
+ System.out.println("ERROR: cannot find ./transport.txt, so no key archival");
+
+ return;
+ }
+ try {
+ CryptoManager.initialize(DB_DIR);
+ } catch (Exception e) {
+ // it is ok if it is already initialized
+ System.out.println("INITIALIZATION ERROR: " + e.toString());
+ // return;
+ }
- boolean foundTransport = false;
- String transportCert = null;
+ try {
+ CryptoManager manager = CryptoManager.getInstance();
+ String token_pwd = TOKEN_PWD;
+ CryptoToken token = manager.getInternalKeyStorageToken();
+ Password password = new Password(token_pwd.toCharArray());
try {
- BufferedReader br = new BufferedReader(new FileReader("./transport.txt"));
- transportCert = br.readLine();
- foundTransport = true;
+ token.login(password);
} catch (Exception e) {
- System.out.println("ERROR: cannot find ./transport.txt, so no key archival");
-
- return;
- }
-
-
-
- try {
- CryptoManager.initialize( DB_DIR );
- } catch (Exception e) {
- // it is ok if it is already initialized
- System.out.println("INITIALIZATION ERROR: " + e.toString());
- // return;
+ // System.out.println("login Exception: " + e.toString());
+ if (!token.isLoggedIn()) {
+ token.initPassword(password, password);
+ }
}
+ System.out.println("."); // "done with cryptomanager");
- try {
- CryptoManager manager = CryptoManager.getInstance();
- String token_pwd = TOKEN_PWD;
- CryptoToken token = manager.getInternalKeyStorageToken();
- Password password = new Password(token_pwd.toCharArray());
- try {
- token.login(password);
- } catch (Exception e) {
- //System.out.println("login Exception: " + e.toString());
- if (!token.isLoggedIn()) {
- token.initPassword(password, password);
- }
- }
-
- System.out.println("."); //"done with cryptomanager");
+ KeyPairGenerator kg = token.getKeyPairGenerator(
+ KeyPairAlgorithm.RSA);
+ kg.initialize(KEY_LEN);
- KeyPairGenerator kg = token.getKeyPairGenerator(
- KeyPairAlgorithm.RSA);
- kg.initialize(KEY_LEN);
+ String profileName = PROFILE_NAME;
+ pair = kg.genKeyPair();
- String profileName = PROFILE_NAME;
- pair = kg.genKeyPair();
+ System.out.println("."); // key pair generated");
- System.out.println("."); //key pair generated");
+ // wrap private key
+ byte transport[] = com.netscape.osutil.OSUtil.AtoB(transportCert);
- // wrap private key
- byte transport[] = com.netscape.osutil.OSUtil.AtoB(transportCert);
+ X509Certificate tcert = manager.importCACertPackage(transport);
- X509Certificate tcert = manager.importCACertPackage(transport);
+ byte iv[] = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 };
- byte iv[] = {0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1};
+ KeyGenerator kg1 = token.getKeyGenerator(KeyGenAlgorithm.DES3);
+ SymmetricKey sk = kg1.generate();
- KeyGenerator kg1 = token.getKeyGenerator(KeyGenAlgorithm.DES3);
- SymmetricKey sk = kg1.generate();
+ System.out.println("."); // before KeyWrapper");
- System.out.println("."); //before KeyWrapper");
+ // wrap private key using session
+ KeyWrapper wrapper1 =
+ token.getKeyWrapper(KeyWrapAlgorithm.DES3_CBC_PAD);
- // wrap private key using session
- KeyWrapper wrapper1 =
- token.getKeyWrapper(KeyWrapAlgorithm.DES3_CBC_PAD);
+ System.out.println("."); // key wrapper created");
- System.out.println("."); //key wrapper created");
+ wrapper1.initWrap(sk, new IVParameterSpec(iv));
- wrapper1.initWrap(sk, new IVParameterSpec(iv));
+ System.out.println("."); // key wrapper inited");
+ byte key_data[] = wrapper1.wrap((org.mozilla.jss.crypto.PrivateKey) pair.getPrivate());
- System.out.println("."); //key wrapper inited");
- byte key_data[] = wrapper1.wrap((org.mozilla.jss.crypto.PrivateKey)pair.getPrivate());
+ System.out.println("."); // key wrapper wrapped");
- System.out.println("."); //key wrapper wrapped");
+ // wrap session using transport
+ KeyWrapper rsaWrap = token.getKeyWrapper(
+ KeyWrapAlgorithm.RSA);
- // wrap session using transport
- KeyWrapper rsaWrap = token.getKeyWrapper(
- KeyWrapAlgorithm.RSA);
+ System.out.println("."); // got rsaWrapper");
- System.out.println("."); //got rsaWrapper");
+ rsaWrap.initWrap(tcert.getPublicKey(), null);
- rsaWrap.initWrap(tcert.getPublicKey(), null);
+ System.out.println("."); // rsaWrap inited");
- System.out.println("."); //rsaWrap inited");
+ byte session_data[] = rsaWrap.wrap(sk);
- byte session_data[] = rsaWrap.wrap(sk);
+ System.out.println("."); // rsaWrapped");
- System.out.println("."); //rsaWrapped");
-
- try {
- // create CRMF
- CertTemplate certTemplate = new CertTemplate();
- certTemplate.setVersion(new INTEGER(2));
-
- Name n1 = getJssName(SUBJ_DN);
-
-
- Name n = new Name();
-
- n.addCommonName("Me");
- n.addCountryName("US");
- n.addElement(new AVA(new OBJECT_IDENTIFIER("0.9.2342.19200300.100.1.1"), new PrintableString("MyUid")));
+ try {
+ // create CRMF
+ CertTemplate certTemplate = new CertTemplate();
+ certTemplate.setVersion(new INTEGER(2));
+
+ Name n1 = getJssName(SUBJ_DN);
+
+ Name n = new Name();
+
+ n.addCommonName("Me");
+ n.addCountryName("US");
+ n.addElement(new AVA(new OBJECT_IDENTIFIER("0.9.2342.19200300.100.1.1"), new PrintableString("MyUid")));
+
+ if (n1 != null)
+ certTemplate.setSubject(n1);
+ else
+ certTemplate.setSubject(n);
+
+ certTemplate.setPublicKey(new SubjectPublicKeyInfo(pair.getPublic()));
+ // set extension
+ AlgorithmIdentifier algS = new AlgorithmIdentifier(new OBJECT_IDENTIFIER("1.2.840.113549.3.7"), new OCTET_STRING(iv));
+ EncryptedValue encValue = new EncryptedValue(null, algS, new BIT_STRING(session_data, 0), null, null, new BIT_STRING(key_data, 0));
+ EncryptedKey key = new EncryptedKey(encValue);
+ PKIArchiveOptions opt = new PKIArchiveOptions(key);
+ SEQUENCE seq = new SEQUENCE();
+ if (foundTransport) {
+ seq.addElement(new AVA(new OBJECT_IDENTIFIER("1.3.6.1.5.5.7.5.1.4"), opt));
+ }
- if(n1 != null)
- certTemplate.setSubject(n1);
- else
- certTemplate.setSubject(n);
+ // Add idPOPLinkWitness control
+ String secretValue = "testing";
+ byte[] key1 = null;
+ byte[] finalDigest = null;
+ try {
+ MessageDigest SHA1Digest = MessageDigest.getInstance("SHA1");
+ key1 = SHA1Digest.digest(secretValue.getBytes());
+ } catch (NoSuchAlgorithmException ex) {
+ }
- certTemplate.setPublicKey(new SubjectPublicKeyInfo(pair.getPublic()));
- // set extension
- AlgorithmIdentifier algS = new AlgorithmIdentifier(new OBJECT_IDENTIFIER("1.2.840.113549.3.7"), new OCTET_STRING(iv));
- EncryptedValue encValue = new EncryptedValue(null, algS, new BIT_STRING(session_data, 0),null, null,new BIT_STRING(key_data, 0));
- EncryptedKey key = new EncryptedKey(encValue);
- PKIArchiveOptions opt = new PKIArchiveOptions(key);
- SEQUENCE seq = new SEQUENCE();
- if (foundTransport) {
- seq.addElement(new AVA(new OBJECT_IDENTIFIER("1.3.6.1.5.5.7.5.1.4"),opt));
- }
-
+ /* Example of adding the POP link witness control to CRMF */
+ byte[] b =
+ { 0x10, 0x53, 0x42, 0x24, 0x1a, 0x2a, 0x35, 0x3c,
+ 0x7a, 0x52, 0x54, 0x56, 0x71, 0x65, 0x66, 0x4c,
+ 0x51, 0x34, 0x35, 0x23, 0x3c, 0x42, 0x43, 0x45,
+ 0x61, 0x4f, 0x6e, 0x43, 0x1e, 0x2a, 0x2b, 0x31,
+ 0x32, 0x34, 0x35, 0x36, 0x55, 0x51, 0x48, 0x14,
+ 0x16, 0x29, 0x41, 0x42, 0x43, 0x7b, 0x63, 0x44,
+ 0x6a, 0x12, 0x6b, 0x3c, 0x4c, 0x3f, 0x00, 0x14,
+ 0x51, 0x61, 0x15, 0x22, 0x23, 0x5f, 0x5e, 0x69 };
- // Add idPOPLinkWitness control
- String secretValue = "testing";
- byte[] key1 = null;
- byte[] finalDigest = null;
- try {
- MessageDigest SHA1Digest = MessageDigest.getInstance("SHA1");
- key1 = SHA1Digest.digest(secretValue.getBytes());
- } catch (NoSuchAlgorithmException ex) {
- }
+ try {
+ MessageDigest SHA1Digest = MessageDigest.getInstance("SHA1");
+ HMACDigest hmacDigest = new HMACDigest(SHA1Digest, key1);
+ hmacDigest.update(b);
+ finalDigest = hmacDigest.digest();
+ } catch (NoSuchAlgorithmException ex) {
+ }
-/* Example of adding the POP link witness control to CRMF */
-byte[] b =
-{0x10, 0x53, 0x42, 0x24, 0x1a, 0x2a, 0x35, 0x3c,
- 0x7a, 0x52, 0x54, 0x56, 0x71, 0x65, 0x66, 0x4c,
- 0x51, 0x34, 0x35, 0x23, 0x3c, 0x42, 0x43, 0x45,
- 0x61, 0x4f, 0x6e, 0x43, 0x1e, 0x2a, 0x2b, 0x31,
- 0x32, 0x34, 0x35, 0x36, 0x55, 0x51, 0x48, 0x14,
- 0x16, 0x29, 0x41, 0x42, 0x43, 0x7b, 0x63, 0x44,
- 0x6a, 0x12, 0x6b, 0x3c, 0x4c, 0x3f, 0x00, 0x14,
- 0x51, 0x61, 0x15, 0x22, 0x23, 0x5f, 0x5e, 0x69};
+ OCTET_STRING ostr = new OCTET_STRING(finalDigest);
+ seq.addElement(new AVA(OBJECT_IDENTIFIER.id_cmc_idPOPLinkWitness, ostr));
+ CertRequest certReq = new CertRequest(new INTEGER(1), certTemplate, seq);
- try {
- MessageDigest SHA1Digest = MessageDigest.getInstance("SHA1");
- HMACDigest hmacDigest = new HMACDigest(SHA1Digest, key1);
- hmacDigest.update(b);
- finalDigest = hmacDigest.digest();
- } catch (NoSuchAlgorithmException ex) {
- }
-
+ System.out.println("."); // CertRequest created");
- OCTET_STRING ostr = new OCTET_STRING(finalDigest);
- seq.addElement(new AVA(OBJECT_IDENTIFIER.id_cmc_idPOPLinkWitness, ostr));
- CertRequest certReq = new CertRequest(new INTEGER(1), certTemplate, seq);
+ ByteArrayOutputStream bo = new ByteArrayOutputStream();
+ certReq.encode(bo);
+ byte[] toBeVerified = bo.toByteArray();
- System.out.println("."); //CertRequest created");
+ byte popdata[] = ASN1Util.encode(certReq);
+ byte signature[];
+ System.out.println("."); // CertRequest encoded");
- ByteArrayOutputStream bo = new ByteArrayOutputStream();
- certReq.encode(bo);
- byte[] toBeVerified = bo.toByteArray();
-
- byte popdata[] = ASN1Util.encode(certReq);
- byte signature[];
+ Signature signer = token.getSignatureContext(
+ SignatureAlgorithm.RSASignatureWithMD5Digest);
- System.out.println("."); //CertRequest encoded");
+ System.out.println("."); // signer created");
- Signature signer = token.getSignatureContext(
- SignatureAlgorithm.RSASignatureWithMD5Digest);
+ signer.initSign((org.mozilla.jss.crypto.PrivateKey) pair.getPrivate());
- System.out.println("."); //signer created");
+ System.out.println("."); // signer inited");
- signer.initSign((org.mozilla.jss.crypto.PrivateKey)pair.getPrivate());
+ System.out.println("."); // FAIL_OR_SUCC " + FAIL_OR_SUCC);
- System.out.println("."); //signer inited");
+ if (POP_OPTION.equals("POP_SUCCESS")) {
+ System.out.println("Generating Legal POP Data.....");
+ signer.update(toBeVerified);
+ } else if (POP_OPTION.equals("POP_FAIL")) {
+ System.out.println("Generating Illegal POP Data.....");
+ signer.update(iv);
+ } else if (dont_do_pop == 1) {
+ System.out.println("Generating NO POP Data.....");
+ }
- System.out.println("."); //FAIL_OR_SUCC " + FAIL_OR_SUCC);
+ System.out.println("."); // signer updated");
- if(POP_OPTION.equals("POP_SUCCESS"))
- {
- System.out.println("Generating Legal POP Data.....");
- signer.update(toBeVerified);
- }
- else if(POP_OPTION.equals("POP_FAIL"))
- {
- System.out.println("Generating Illegal POP Data.....");
- signer.update(iv);
- }
- else if(dont_do_pop == 1)
- {
- System.out.println("Generating NO POP Data.....");
- }
+ CertReqMsg crmfMsg = null;
- System.out.println("."); //signer updated");
+ if (dont_do_pop == 0) {
+ signature = signer.sign();
- CertReqMsg crmfMsg = null;
+ System.out.println("Signature completed...");
+ System.out.println("");
- if(dont_do_pop == 0)
- {
- signature = signer.sign();
+ AlgorithmIdentifier algID =
+ new AlgorithmIdentifier(SignatureAlgorithm.RSASignatureWithMD5Digest.toOID(), null);
+ POPOSigningKey popoKey = new POPOSigningKey(null, algID, new BIT_STRING(signature, 0));
- System.out.println("Signature completed...");
- System.out.println("");
+ ProofOfPossession pop = ProofOfPossession.createSignature(popoKey);
-
- AlgorithmIdentifier algID =
- new AlgorithmIdentifier(SignatureAlgorithm.RSASignatureWithMD5Digest.toOID(), null );
- POPOSigningKey popoKey = new POPOSigningKey(null,algID, new BIT_STRING(signature,0));
+ crmfMsg = new CertReqMsg(certReq, pop, null);
- ProofOfPossession pop = ProofOfPossession.createSignature(popoKey);
+ } else {
+ crmfMsg = new CertReqMsg(certReq, null, null);
- crmfMsg = new CertReqMsg(certReq, pop, null);
+ }
- }
- else
- {
- crmfMsg = new CertReqMsg(certReq, null, null);
+ // crmfMsg.verify();
- }
+ SEQUENCE s1 = new SEQUENCE();
+ s1.addElement(crmfMsg);
+ byte encoded[] = ASN1Util.encode(s1);
- //crmfMsg.verify();
+ String Req1 = com.netscape.osutil.OSUtil.BtoA(encoded);
- SEQUENCE s1 = new SEQUENCE();
- s1.addElement(crmfMsg);
- byte encoded[] = ASN1Util.encode(s1);
+ if (OUTPUT_CERT_REQ != null) {
+ System.out.println("Generated Cert Request: ...... ");
+ System.out.println("");
- String Req1 = com.netscape.osutil.OSUtil.BtoA(encoded);
+ System.out.println(Req1);
+ System.out.println("");
+ System.out.println("End Request:");
- if(OUTPUT_CERT_REQ != null)
- {
- System.out.println("Generated Cert Request: ...... ");
- System.out.println("");
+ if (doServerHit == 0)
+ return;
+ }
- System.out.println(Req1);
- System.out.println("");
- System.out.println("End Request:");
+ String Req = URLEncoder.encode(Req1);
- if(doServerHit == 0)
- return;
- }
-
- String Req = URLEncoder.encode(Req1);
+ // post PKCS10
- // post PKCS10
+ url = new URL("http://" + HOST + ":" + PORT + "/ca/ee/ca/profileSubmit?cert_request_type=crmf&cert_request=" + Req + "&renewal=false&uid=" + USER_NAME + "&xmlOutput=false&&profileId=" + profileName + "&sn_uid=" + USER_NAME + "&SubId=profile&requestor_name=" + REQUESTOR_NAME);
+ // System.out.println("Posting " + url);
- url = new URL("http://" + HOST + ":" + PORT + "/ca/ee/ca/profileSubmit?cert_request_type=crmf&cert_request=" + Req + "&renewal=false&uid=" + USER_NAME + "&xmlOutput=false&&profileId=" + profileName + "&sn_uid=" + USER_NAME +"&SubId=profile&requestor_name="+ REQUESTOR_NAME);
- //System.out.println("Posting " + url);
+ System.out.println("");
+ System.out.println("Server Response.....");
+ System.out.println("--------------------");
+ System.out.println("");
- System.out.println("");
- System.out.println("Server Response.....");
- System.out.println("--------------------");
+ long start_time = (new Date()).getTime();
+ conn = url.openConnection();
+ is = conn.getInputStream();
+ reader = new BufferedReader(new InputStreamReader(is));
+ String line = null;
+ while ((line = reader.readLine()) != null) {
+ System.out.println(line);
+ if (line.equals("CMS Enroll Request Success")) {
+ success = true;
+ System.out.println("Enrollment Successful: ......");
System.out.println("");
+ }
+ } /* while */
+ long end_time = (new Date()).getTime();
+ total_time += (end_time - start_time);
+ } catch (Exception e) {
+ System.out.println("WARNING: " + e.toString());
+ e.printStackTrace();
+ }
+ } catch (Exception e) {
+ System.out.println("ERROR: " + e.toString());
+ e.printStackTrace();
+ }
+ }
- long start_time = (new Date()).getTime();
- conn = url.openConnection();
- is = conn.getInputStream();
- reader = new BufferedReader(new InputStreamReader(is));
- String line = null;
- while ((line = reader.readLine()) != null) {
- System.out.println(line);
- if (line.equals("CMS Enroll Request Success")) {
- success = true;
- System.out.println("Enrollment Successful: ......");
- System.out.println("");
- }
- } /* while */
- long end_time = (new Date()).getTime();
- total_time += (end_time - start_time);
- } catch (Exception e) {
- System.out.println("WARNING: " + e.toString());
- e.printStackTrace();
- }
- } catch (Exception e) {
- System.out.println("ERROR: " + e.toString());
- e.printStackTrace();
- }
- }
-
- static Name getJssName(String dn)
- {
-
- X500Name x5Name = null;
+ static Name getJssName(String dn) {
- try {
- x5Name= new X500Name(dn);
+ X500Name x5Name = null;
- } catch(IOException e) {
+ try {
+ x5Name = new X500Name(dn);
- System.out.println("Illegal Subject Name: " + dn + " Error: " + e.toString());
- System.out.println("Filling in default Subject Name......");
- return null;
- }
+ } catch (IOException e) {
- Name ret = new Name();
+ System.out.println("Illegal Subject Name: " + dn + " Error: " + e.toString());
+ System.out.println("Filling in default Subject Name......");
+ return null;
+ }
- netscape.security.x509.RDN[] names = null;
+ Name ret = new Name();
- names = x5Name.getNames();
+ netscape.security.x509.RDN[] names = null;
- int nameLen = x5Name.getNamesLength();
+ names = x5Name.getNames();
- // System.out.println("x5Name len: " + nameLen);
+ int nameLen = x5Name.getNamesLength();
- netscape.security.x509.RDN cur = null;
+ // System.out.println("x5Name len: " + nameLen);
- for(int i = 0; i < nameLen ; i++)
- {
- cur = names[i];
+ netscape.security.x509.RDN cur = null;
- String rdnStr = cur.toString();
+ for (int i = 0; i < nameLen; i++) {
+ cur = names[i];
+ String rdnStr = cur.toString();
- String[] split = rdnStr.split("=");
+ String[] split = rdnStr.split("=");
- if(split.length != 2)
- continue;
+ if (split.length != 2)
+ continue;
- try {
+ try {
- if(split[0].equals("UID"))
- {
+ if (split[0].equals("UID")) {
- ret.addElement(new AVA(new OBJECT_IDENTIFIER("0.9.2342.19200300.100.1.1"), new PrintableString(split[1])));
- // System.out.println("UID found : " + split[1]);
+ ret.addElement(new AVA(new OBJECT_IDENTIFIER("0.9.2342.19200300.100.1.1"), new PrintableString(split[1])));
+ // System.out.println("UID found : " + split[1]);
}
- if(split[0].equals("C"))
- {
- ret.addCountryName(split[1]);
- // System.out.println("C found : " + split[1]);
- continue;
-
- }
+ if (split[0].equals("C")) {
+ ret.addCountryName(split[1]);
+ // System.out.println("C found : " + split[1]);
+ continue;
- if(split[0].equals("CN"))
- {
- ret.addCommonName(split[1]);
- // System.out.println("CN found : " + split[1]);
- continue;
}
- if(split[0].equals("L"))
- {
- ret.addLocalityName(split[1]);
- // System.out.println("L found : " + split[1]);
- continue;
+ if (split[0].equals("CN")) {
+ ret.addCommonName(split[1]);
+ // System.out.println("CN found : " + split[1]);
+ continue;
}
- if(split[0].equals("O"))
- {
- ret.addOrganizationName(split[1]);
- // System.out.println("O found : " + split[1]);
- continue;
+ if (split[0].equals("L")) {
+ ret.addLocalityName(split[1]);
+ // System.out.println("L found : " + split[1]);
+ continue;
}
- if(split[0].equals("ST"))
- {
- ret.addStateOrProvinceName(split[1]);
- // System.out.println("ST found : " + split[1]);
- continue;
+ if (split[0].equals("O")) {
+ ret.addOrganizationName(split[1]);
+ // System.out.println("O found : " + split[1]);
+ continue;
}
- if(split[0].equals("OU"))
- {
- ret.addOrganizationalUnitName(split[1]);
- // System.out.println("OU found : " + split[1]);
- continue;
+ if (split[0].equals("ST")) {
+ ret.addStateOrProvinceName(split[1]);
+ // System.out.println("ST found : " + split[1]);
+ continue;
}
- } catch (Exception e) {
- System.out.println("Error constructing RDN: " + rdnStr + " Error: " + e.toString());
+ if (split[0].equals("OU")) {
+ ret.addOrganizationalUnitName(split[1]);
+ // System.out.println("OU found : " + split[1]);
continue;
}
+ } catch (Exception e) {
+ System.out.println("Error constructing RDN: " + rdnStr + " Error: " + e.toString());
-
+ continue;
}
- return ret;
+ }
+ return ret;
- }
+ }
}
diff --git a/pki/base/java-tools/src/com/netscape/cmstools/DRMTool.java b/pki/base/java-tools/src/com/netscape/cmstools/DRMTool.java
index 20dfb42e..e9a67ed7 100644
--- a/pki/base/java-tools/src/com/netscape/cmstools/DRMTool.java
+++ b/pki/base/java-tools/src/com/netscape/cmstools/DRMTool.java
@@ -66,30 +66,31 @@ import org.mozilla.jss.pkcs11.PK11PubKey;
import org.mozilla.jss.util.Password;
/**
- * The DRMTool class is a utility program designed to operate on an LDIF file
- * to perform one or more of the following tasks:
+ * The DRMTool class is a utility program designed to operate on an LDIF file to
+ * perform one or more of the following tasks:
+ *
* <PRE>
* (A) Use a new storage key (e. g. - a 2048-bit key to replace a
* 1024-bit key) to rewrap the existing triple DES symmetric key
* that was used to wrap a user's private key.
- *
+ *
* STARTING INVENTORY:
- *
+ *
* (1) a DRMTOOL configuration file containing DRM LDIF record
* types and the processing status of their associated fields
- *
+ *
* (2) an LDIF file containing 'exported' DRM data
* (referred to as the "source" DRM)
- *
+ *
* NOTE: If this LDIF file contains data that was originally
* from a DRM instance that was prior to RHCS 8, it
* must have previously undergone the appropriate
* migration steps.
- *
+ *
* (3) the NSS security databases (e. g. - cert8.db, key3.db,
* and secmod.db) associated with the data contained in
* the source LDIF file
- *
+ *
* NOTE: If the storage key was located on an HSM, then the
* HSM must be available to the machine on which the
* DRMTool is being executed (since the RSA private
@@ -98,301 +99,302 @@ import org.mozilla.jss.util.Password;
* password may be required to unlock access to
* this key (e. g. - which may be located in
* the source DRM's 'password.conf' file).
- *
+ *
* (4) a file containing the ASCII BASE-64 storage certificate
* from the DRM instance for which the output LDIF file is
* intended (referred to as the "target")
- *
+ *
* ENDING INVENTORY:
- *
+ *
* (1) all items listed in the STARTING INVENTORY (unchanged)
- *
+ *
* (2) a log file containing information suitable for audit
* purposes
- *
+ *
* (3) an LDIF file containing the revised data suitable for
* 'import' into a new DRM (referred to as the "target" DRM)
- *
+ *
* DRMTool PARAMETERS:
- *
+ *
* (1) the name of the DRMTOOL configuration file containing
* DRM LDIF record types and the processing status of their
* associated fields
- *
+ *
* (2) the name of the input LDIF file containing data which was
* 'exported' from the source DRM instance
- *
+ *
* (3) the name of the output LDIF file intended to contain the
* revised data suitable for 'import' to a target DRM instance
- *
+ *
* (4) the name of the log file that may be used for auditing
* purposes
- *
+ *
* (5) the path to the security databases that were used by
* the source DRM instance
- *
+ *
* (6) the name of the token that was used by
* the source DRM instance
- *
+ *
* (7) the name of the storage certificate that was used by
* the source DRM instance
- *
+ *
* (8) the name of the file containing the ASCII BASE-64 storage
* certificate from the target DRM instance for which the
* output LDIF file is intended
- *
+ *
* (9) OPTIONALLY, the name of a file which ONLY contains the
* password needed to access the source DRM instance's
* security databases
- *
+ *
* (10) OPTIONALLY, choose to change the specified source DRM naming
* context to the specified target DRM naming context
- *
+ *
* (11) OPTIONALLY, choose to ONLY process CA enrollment requests,
* CA recovery requests, CA key records, TPS netkeyKeygen
* enrollment requests, TPS recovery requests, and
* TPS key records
- *
+ *
* DATA FIELDS AFFECTED (using default config file values):
- *
+ *
* (1) CA DRM enrollment request
- *
+ *
* (a) dateOfModify
* (b) extdata-requestnotes
- *
+ *
* (2) CA DRM key record
- *
+ *
* (a) dateOfModify
* (b) privateKeyData
- *
+ *
* (3) CA DRM recovery request
- *
+ *
* (a) dateOfModify
* (b) extdata-requestnotes (NEW)
- *
+ *
* (4) TPS DRM netkeyKeygen (enrollment) request
- *
+ *
* (a) dateOfModify
* (b) extdata-requestnotes (NEW)
- *
+ *
* (5) TPS DRM key record
- *
+ *
* (a) dateOfModify
* (b) privateKeyData
- *
+ *
* (6) TPS DRM recovery request
- *
+ *
* (a) dateOfModify
* (b) extdata-requestnotes (NEW)
- *
+ *
* (B) Specify an ID offset to append to existing numeric data
* (e. g. - to renumber data for use in DRM consolidation efforts).
- *
+ *
* STARTING INVENTORY:
- *
+ *
* (1) a DRMTOOL configuration file containing DRM LDIF record
* types and the processing status of their associated fields
- *
+ *
* (2) an LDIF file containing 'exported' DRM data
* (referred to as the "source" DRM)
- *
+ *
* NOTE: If this LDIF file contains data that was originally
* from a DRM instance that was prior to RHCS 8, it
* must have previously undergone the appropriate
* migration steps.
- *
+ *
* ENDING INVENTORY:
- *
+ *
* (1) all items listed in the STARTING INVENTORY (unchanged)
- *
+ *
* (2) a log file containing information suitable for audit
* purposes
- *
+ *
* (3) an LDIF file containing the revised data suitable for
* 'import' into a new DRM (referred to as the "target" DRM)
- *
+ *
* DRMTool PARAMETERS:
- *
+ *
* (1) the name of the DRMTOOL configuration file containing
* DRM LDIF record types and the processing status of their
* associated fields
- *
+ *
* (2) the name of the input LDIF file containing data which was
* 'exported' from the source DRM instance
- *
+ *
* (3) the name of the output LDIF file intended to contain the
* revised data suitable for 'import' to a target DRM instance
- *
+ *
* (4) the name of the log file that may be used for auditing
* purposes
- *
+ *
* (5) a large numeric ID offset (mask) to be appended to existing
* numeric data in the source DRM instance's LDIF file
- *
+ *
* (6) OPTIONALLY, choose to change the specified source DRM naming
* context to the specified target DRM naming context
- *
+ *
* (7) OPTIONALLY, choose to ONLY process CA enrollment requests,
* CA recovery requests, CA key records, TPS netkeyKeygen
* enrollment requests, TPS recovery requests, and
* TPS key records
- *
+ *
* DATA FIELDS AFFECTED (using default config file values):
- *
+ *
* (1) CA DRM enrollment request
- *
+ *
* (a) cn
* (b) dateOfModify
* (c) extdata-keyrecord
* (d) extdata-requestnotes
* (e) requestId
- *
+ *
* (2) CA DRM key record
- *
+ *
* (a) cn
* (b) dateOfModify
* (c) serialno
- *
+ *
* (3) CA DRM recovery request
- *
+ *
* (a) cn
* (b) dateOfModify
* (c) extdata-requestid
* (d) extdata-requestnotes (NEW)
* (e) extdata-serialnumber
* (f) requestId
- *
+ *
* (4) TPS DRM netkeyKeygen (enrollment) request
- *
+ *
* (a) cn
* (b) dateOfModify
* (c) extdata-keyrecord
* (d) extdata-requestid
* (e) extdata-requestnotes (NEW)
* (f) requestId
- *
+ *
* (5) TPS DRM key record
- *
+ *
* (a) cn
* (b) dateOfModify
* (c) serialno
- *
+ *
* (6) TPS DRM recovery request
- *
+ *
* (a) cn
* (b) dateOfModify
* (c) extdata-requestid
* (d) extdata-requestnotes (NEW)
* (e) extdata-serialnumber
* (f) requestId
- *
+ *
* (C) Specify an ID offset to be removed from existing numeric data
* (e. g. - to undo renumbering used in DRM consolidation efforts).
- *
+ *
* STARTING INVENTORY:
- *
+ *
* (1) a DRMTOOL configuration file containing DRM LDIF record
* types and the processing status of their associated fields
- *
+ *
* (2) an LDIF file containing 'exported' DRM data
* (referred to as the "source" DRM)
- *
+ *
* NOTE: If this LDIF file contains data that was originally
* from a DRM instance that was prior to RHCS 8, it
* must have previously undergone the appropriate
* migration steps.
- *
+ *
* ENDING INVENTORY:
- *
+ *
* (1) all items listed in the STARTING INVENTORY (unchanged)
- *
+ *
* (2) a log file containing information suitable for audit
* purposes
- *
+ *
* (3) an LDIF file containing the revised data suitable for
* 'import' into a new DRM (referred to as the "target" DRM)
- *
+ *
* DRMTool PARAMETERS:
- *
+ *
* (1) the name of the DRMTOOL configuration file containing
* DRM LDIF record types and the processing status of their
* associated fields
- *
+ *
* (2) the name of the input LDIF file containing data which was
* 'exported' from the source DRM instance
- *
+ *
* (3) the name of the output LDIF file intended to contain the
* revised data suitable for 'import' to a target DRM instance
- *
+ *
* (4) the name of the log file that may be used for auditing
* purposes
- *
+ *
* (5) a large numeric ID offset (mask) to be removed from existing
* numeric data in the source DRM instance's LDIF file
- *
+ *
* (6) OPTIONALLY, choose to change the specified source DRM naming
* context to the specified target DRM naming context
- *
+ *
* (7) OPTIONALLY, choose to ONLY process CA enrollment requests,
* CA recovery requests, CA key records, TPS netkeyKeygen
* enrollment requests, TPS recovery requests, and
* TPS key records
- *
+ *
* DATA FIELDS AFFECTED (using default config file values):
- *
+ *
* (1) CA DRM enrollment request
- *
+ *
* (a) cn
* (b) dateOfModify
* (c) extdata-keyrecord
* (d) extdata-requestnotes
* (e) requestId
- *
+ *
* (2) CA DRM key record
- *
+ *
* (a) cn
* (b) dateOfModify
* (c) serialno
- *
+ *
* (3) CA DRM recovery request
- *
+ *
* (a) cn
* (b) dateOfModify
* (c) extdata-requestid
* (d) extdata-requestnotes (NEW)
* (e) extdata-serialnumber
* (f) requestId
- *
+ *
* (4) TPS DRM netkeyKeygen (enrollment) request
- *
+ *
* (a) cn
* (b) dateOfModify
* (c) extdata-keyrecord
* (d) extdata-requestid
* (e) extdata-requestnotes (NEW)
* (f) requestId
- *
+ *
* (5) TPS DRM key record
- *
+ *
* (a) cn
* (b) dateOfModify
* (c) serialno
- *
+ *
* (6) TPS DRM recovery request
- *
+ *
* (a) cn
* (b) dateOfModify
* (c) extdata-requestid
* (d) extdata-requestnotes (NEW)
* (e) extdata-serialnumber
* (f) requestId
- *
+ *
* </PRE>
- *
+ *
* <P>
* DRMTool may be invoked as follows:
+ *
* <PRE>
- *
+ *
* DRMTool
* -drmtool_config_file &lt;path + drmtool config file&gt;
* -source_ldif_file &lt;path + source ldif file&gt;
@@ -408,96 +410,95 @@ import org.mozilla.jss.util.Password;
* [-source_drm_naming_context '&lt;original source DRM naming context&gt;']
* [-target_drm_naming_context '&lt;renamed target DRM naming context&gt;']
* [-process_requests_and_key_records_only]
- *
+ *
* where the following options are 'Mandatory':
- *
+ *
* -drmtool_config_file &lt;path + drmtool config file&gt;
* -source_ldif_file &lt;path + source ldif file&gt;
* -target_ldif_file &lt;path + target ldif file&gt;
* -log_file &lt;path + log file&gt;
- *
+ *
* AND at least ONE of the following are a 'Mandatory' set of options:
- *
+ *
* (a) options for using a new storage key for rewrapping:
- *
+ *
* [-source_pki_security_database_path
* &lt;path to PKI source database&gt;]
* [-source_storage_token_name '&lt;source token&gt;']
* [-source_storage_certificate_nickname '&lt;source nickname&gt;']
* [-target_storage_certificate_file
* &lt;path to target certificate file&gt;]
- *
+ *
* AND OPTIONALLY, specify the name of a file which ONLY contains
* the password needed to access the source DRM instance's
* security databases:
- *
+ *
* [-source_pki_security_database_pwdfile
* &lt;path to PKI password file&gt;]
- *
+ *
* AND OPTIONALLY, rename source DRM naming context --> target
* DRM naming context:
- *
+ *
* [-source_drm_naming_context '&lt;source DRM naming context&gt;']
* [-target_drm_naming_context '&lt;target DRM naming context&gt;']
- *
+ *
* AND OPTIONALLY, process requests and key records ONLY:
- *
+ *
* [-process_requests_and_key_records_only]
- *
+ *
* (b) option for appending the specified numeric ID offset
* to existing numerical data:
- *
+ *
* [-append_id_offset &lt;numeric offset&gt;]
- *
+ *
* AND OPTIONALLY, rename source DRM naming context --> target
* DRM naming context:
- *
+ *
* [-source_drm_naming_context '&lt;source DRM naming context&gt;']
* [-target_drm_naming_context '&lt;target DRM naming context&gt;']
- *
+ *
* AND OPTIONALLY, process requests and key records ONLY:
- *
+ *
* [-process_requests_and_key_records_only]
- *
+ *
* (c) option for removing the specified numeric ID offset
* from existing numerical data:
- *
+ *
* AND OPTIONALLY, rename source DRM naming context --> target
* DRM naming context:
- *
+ *
* [-source_drm_naming_context '&lt;source DRM naming context&gt;']
* [-target_drm_naming_context '&lt;target DRM naming context&gt;']
- *
+ *
* [-remove_id_offset &lt;numeric offset&gt;]
- *
+ *
* AND OPTIONALLY, process requests and key records ONLY:
- *
+ *
* [-process_requests_and_key_records_only]
- *
+ *
* (d) (a) rewrap AND (b) append ID offset
* [AND OPTIONALLY, rename source DRM naming context --> target
* DRM naming context]
* [AND OPTIONALLY process requests and key records ONLY]
- *
+ *
* (e) (a) rewrap AND (c) remove ID offset
* [AND OPTIONALLY, rename source DRM naming context --> target
* DRM naming context]
* [AND OPTIONALLY process requests and key records ONLY]
- *
+ *
* NOTE: Options (b) and (c) are mutually exclusive!
- *
+ *
* </PRE>
- *
+ *
* @author mharmsen
* @version $Revision$, $Date$
*/
-public class DRMTool
-{
+public class DRMTool {
/*************/
/* Constants */
/*************/
- // Constants: Miscellaneous
+ // Constants: Miscellaneous
private static final boolean FAILURE = false;
private static final boolean SUCCESS = true;
private static final String COLON = ":";
@@ -512,17 +513,14 @@ public class DRMTool
private static final String SPACE = " ";
private static final String TIC = "'";
-
- // Constants: Calendar
+ // Constants: Calendar
private static final String DATE_OF_MODIFY_PATTERN = "yyyyMMddHHmmss'Z'";
private static final String LOGGING_DATE_PATTERN = "dd/MMM/yyyy:HH:mm:ss z";
-
- // Constants: PKCS #11 Information
+ // Constants: PKCS #11 Information
private static final String INTERNAL_TOKEN = "Internal Key Storage Token";
-
- // Constants: Command-line Options
+ // Constants: Command-line Options
private static final int ID_OFFSET_NAME_VALUE_PAIRS = 1;
private static final int PWDFILE_NAME_VALUE_PAIRS = 1;
private static final int NAMING_CONTEXT_NAME_VALUE_PAIRS = 2;
@@ -532,116 +530,91 @@ public class DRMTool
private static final int REWRAP_ARGS = 16;
private static final int REWRAP_AND_ID_OFFSET_ARGS = 18;
-
- // Constants: Command-line Options (Mandatory)
+ // Constants: Command-line Options (Mandatory)
private static final String DRM_TOOL = "DRMTool";
- private static final String
- DRMTOOL_CFG_FILE = "-drmtool_config_file";
+ private static final String DRMTOOL_CFG_FILE = "-drmtool_config_file";
- private static final String
- DRMTOOL_CFG_DESCRIPTION = " <complete path to the drmtool config file"
+ private static final String DRMTOOL_CFG_DESCRIPTION = " <complete path to the drmtool config file"
+ NEWLINE
+ " "
+ " ending with the drmtool config file name>";
- private static final String
- DRMTOOL_CFG_FILE_EXAMPLE = DRMTOOL_CFG_FILE
+ private static final String DRMTOOL_CFG_FILE_EXAMPLE = DRMTOOL_CFG_FILE
+ " "
+ "/usr/share/pki/java-tools/DRMTool.cfg";
- private static final String
- SOURCE_LDIF_FILE = "-source_ldif_file";
+ private static final String SOURCE_LDIF_FILE = "-source_ldif_file";
- private static final String
- SOURCE_LDIF_DESCRIPTION = " <complete path to the source LDIF input file"
+ private static final String SOURCE_LDIF_DESCRIPTION = " <complete path to the source LDIF input file"
+ NEWLINE
+ " "
+ " ending with the source LDIF file name>";
- private static final String
- SOURCE_LDIF_FILE_EXAMPLE = SOURCE_LDIF_FILE
+ private static final String SOURCE_LDIF_FILE_EXAMPLE = SOURCE_LDIF_FILE
+ " "
+ "/export/pki/source.ldif";
- private static final String
- TARGET_LDIF_FILE = "-target_ldif_file";
+ private static final String TARGET_LDIF_FILE = "-target_ldif_file";
- private static final String
- TARGET_LDIF_DESCRIPTION = " <complete path to the target LDIF output file"
+ private static final String TARGET_LDIF_DESCRIPTION = " <complete path to the target LDIF output file"
+ NEWLINE
+ " "
+ " ending with the target LDIF file name>";
- private static final String
- TARGET_LDIF_FILE_EXAMPLE = TARGET_LDIF_FILE
+ private static final String TARGET_LDIF_FILE_EXAMPLE = TARGET_LDIF_FILE
+ " "
+ "/export/pki/target.ldif";
- private static final String
- LOG_FILE = "-log_file";
+ private static final String LOG_FILE = "-log_file";
- private static final String
- LOG_DESCRIPTION = " <complete path to the log file"
+ private static final String LOG_DESCRIPTION = " <complete path to the log file"
+ NEWLINE
+ " "
+ " ending with the log file name>";
- private static final String
- LOG_FILE_EXAMPLE = LOG_FILE
+ private static final String LOG_FILE_EXAMPLE = LOG_FILE
+ " "
+ "/export/pki/DRMTool.log";
+ // Constants: Command-line Options (Rewrap)
+ private static final String SOURCE_NSS_DB_PATH = "-source_pki_security_database_path";
- // Constants: Command-line Options (Rewrap)
- private static final String
- SOURCE_NSS_DB_PATH = "-source_pki_security_database_path";
-
- private static final String
- SOURCE_NSS_DB_DESCRIPTION = " <complete path to the "
+ private static final String SOURCE_NSS_DB_DESCRIPTION = " <complete path to the "
+ "source security databases"
+ NEWLINE
+ " "
+ " used by data in the source LDIF file>";
- private static final String
- SOURCE_NSS_DB_PATH_EXAMPLE = SOURCE_NSS_DB_PATH
+ private static final String SOURCE_NSS_DB_PATH_EXAMPLE = SOURCE_NSS_DB_PATH
+ " "
+ "/export/pki";
- private static final String
- SOURCE_STORAGE_TOKEN_NAME = "-source_storage_token_name";
+ private static final String SOURCE_STORAGE_TOKEN_NAME = "-source_storage_token_name";
- private static final String
- SOURCE_STORAGE_TOKEN_DESCRIPTION = " <name of the token containing "
+ private static final String SOURCE_STORAGE_TOKEN_DESCRIPTION = " <name of the token containing "
+ "the source storage token>";
- private static final String
- SOURCE_STORAGE_TOKEN_NAME_EXAMPLE = SOURCE_STORAGE_TOKEN_NAME
+ private static final String SOURCE_STORAGE_TOKEN_NAME_EXAMPLE = SOURCE_STORAGE_TOKEN_NAME
+ " "
+ TIC
+ "Internal Key Storage Token"
+ TIC;
- private static final String
- SOURCE_STORAGE_CERT_NICKNAME = "-source_storage_certificate_nickname";
+ private static final String SOURCE_STORAGE_CERT_NICKNAME = "-source_storage_certificate_nickname";
- private static final String
- SOURCE_STORAGE_CERT_NICKNAME_DESCRIPTION = " <nickname of the source "
+ private static final String SOURCE_STORAGE_CERT_NICKNAME_DESCRIPTION = " <nickname of the source "
+ "storage certificate>";
- private static final String
- SOURCE_STORAGE_CERT_NICKNAME_EXAMPLE = SOURCE_STORAGE_CERT_NICKNAME
+ private static final String SOURCE_STORAGE_CERT_NICKNAME_EXAMPLE = SOURCE_STORAGE_CERT_NICKNAME
+ " "
+ TIC
+ "storageCert cert-pki-kra"
+ TIC;
- private static final String
- TARGET_STORAGE_CERTIFICATE_FILE = "-target_storage_certificate_file";
+ private static final String TARGET_STORAGE_CERTIFICATE_FILE = "-target_storage_certificate_file";
- private static final String
- TARGET_STORAGE_CERTIFICATE_DESCRIPTION = " <complete path to the target "
+ private static final String TARGET_STORAGE_CERTIFICATE_DESCRIPTION = " <complete path to the target "
+ "storage certificate file"
+ NEWLINE
+ " "
@@ -656,88 +629,67 @@ public class DRMTool
+ " an ASCII format between a "
+ "header and footer>";
- private static final String
- TARGET_STORAGE_CERTIFICATE_FILE_EXAMPLE = TARGET_STORAGE_CERTIFICATE_FILE
+ private static final String TARGET_STORAGE_CERTIFICATE_FILE_EXAMPLE = TARGET_STORAGE_CERTIFICATE_FILE
+ " "
+ "/export/pki/target_storage.cert";
- private static final String
- SOURCE_NSS_DB_PWDFILE = "-source_pki_security_database_pwdfile";
+ private static final String SOURCE_NSS_DB_PWDFILE = "-source_pki_security_database_pwdfile";
- private static final String
- SOURCE_NSS_DB_PWDFILE_DESCRIPTION = " <complete path to the password "
+ private static final String SOURCE_NSS_DB_PWDFILE_DESCRIPTION = " <complete path to the password "
+ "file which ONLY contains the"
+ NEWLINE
+ " "
+ " password used to access the "
+ "source security databases>";
- private static final String
- SOURCE_NSS_DB_PWDFILE_EXAMPLE = SOURCE_NSS_DB_PWDFILE
+ private static final String SOURCE_NSS_DB_PWDFILE_EXAMPLE = SOURCE_NSS_DB_PWDFILE
+ " "
+ "/export/pki/pwdfile";
+ // Constants: Command-line Options (ID Offset)
+ private static final String APPEND_ID_OFFSET = "-append_id_offset";
-
- // Constants: Command-line Options (ID Offset)
- private static final String
- APPEND_ID_OFFSET = "-append_id_offset";
-
- private static final String
- APPEND_ID_OFFSET_DESCRIPTION = " <ID offset that is appended to "
+ private static final String APPEND_ID_OFFSET_DESCRIPTION = " <ID offset that is appended to "
+ "each record's source ID>";
- private static final String
- APPEND_ID_OFFSET_EXAMPLE = APPEND_ID_OFFSET
+ private static final String APPEND_ID_OFFSET_EXAMPLE = APPEND_ID_OFFSET
+ " "
+ "100000000000";
- private static final String
- REMOVE_ID_OFFSET = "-remove_id_offset";
+ private static final String REMOVE_ID_OFFSET = "-remove_id_offset";
- private static final String
- REMOVE_ID_OFFSET_DESCRIPTION = " <ID offset that is removed from "
+ private static final String REMOVE_ID_OFFSET_DESCRIPTION = " <ID offset that is removed from "
+ "each record's source ID>";
- private static final String
- REMOVE_ID_OFFSET_EXAMPLE = REMOVE_ID_OFFSET
+ private static final String REMOVE_ID_OFFSET_EXAMPLE = REMOVE_ID_OFFSET
+ " "
+ "100000000000";
+ // Constants: Command-line Options
+ private static final String SOURCE_DRM_NAMING_CONTEXT = "-source_drm_naming_context";
- // Constants: Command-line Options
- private static final String
- SOURCE_DRM_NAMING_CONTEXT = "-source_drm_naming_context";
+ private static final String SOURCE_DRM_NAMING_CONTEXT_DESCRIPTION = " <source DRM naming context>";
- private static final String
- SOURCE_DRM_NAMING_CONTEXT_DESCRIPTION = " <source DRM naming context>";
-
- private static final String
- SOURCE_DRM_NAMING_CONTEXT_EXAMPLE = SOURCE_DRM_NAMING_CONTEXT
+ private static final String SOURCE_DRM_NAMING_CONTEXT_EXAMPLE = SOURCE_DRM_NAMING_CONTEXT
+ " "
+ TIC
+ "alpha.example.com-pki-kra"
+ TIC;
- private static final String
- TARGET_DRM_NAMING_CONTEXT = "-target_drm_naming_context";
+ private static final String TARGET_DRM_NAMING_CONTEXT = "-target_drm_naming_context";
- private static final String
- TARGET_DRM_NAMING_CONTEXT_DESCRIPTION = " <target DRM naming context>";
+ private static final String TARGET_DRM_NAMING_CONTEXT_DESCRIPTION = " <target DRM naming context>";
- private static final String
- TARGET_DRM_NAMING_CONTEXT_EXAMPLE = TARGET_DRM_NAMING_CONTEXT
+ private static final String TARGET_DRM_NAMING_CONTEXT_EXAMPLE = TARGET_DRM_NAMING_CONTEXT
+ " "
+ TIC
+ "omega.example.com-pki-kra"
+ TIC;
- private static final String
- PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY =
- "-process_requests_and_key_records_only";
-
+ private static final String PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY =
+ "-process_requests_and_key_records_only";
- // Constants: DRMTOOL Config File
+ // Constants: DRMTOOL Config File
private static final String DRMTOOL_CFG_PREFIX = "drmtool.ldif";
private static final String DRMTOOL_CFG_ENROLLMENT = "caEnrollmentRequest";
private static final String DRMTOOL_CFG_CA_KEY_RECORD = "caKeyRecord";
@@ -745,235 +697,190 @@ public class DRMTool
private static final String DRMTOOL_CFG_TPS_KEY_RECORD = "tpsKeyRecord";
private static final String DRMTOOL_CFG_KEYGEN = "tpsNetkeyKeygenRequest";
-
- // Constants: DRMTOOL Config File (DRM CA Enrollment Request Fields)
- private static final String
- DRMTOOL_CFG_ENROLLMENT_CN = DRMTOOL_CFG_PREFIX
+ // Constants: DRMTOOL Config File (DRM CA Enrollment Request Fields)
+ private static final String DRMTOOL_CFG_ENROLLMENT_CN = DRMTOOL_CFG_PREFIX
+ DOT
+ DRMTOOL_CFG_ENROLLMENT
+ DOT
+ "cn";
- private static final String
- DRMTOOL_CFG_ENROLLMENT_DATE_OF_MODIFY = DRMTOOL_CFG_PREFIX
+ private static final String DRMTOOL_CFG_ENROLLMENT_DATE_OF_MODIFY = DRMTOOL_CFG_PREFIX
+ DOT
+ DRMTOOL_CFG_ENROLLMENT
+ DOT
+ "dateOfModify";
- private static final String
- DRMTOOL_CFG_ENROLLMENT_DN = DRMTOOL_CFG_PREFIX
+ private static final String DRMTOOL_CFG_ENROLLMENT_DN = DRMTOOL_CFG_PREFIX
+ DOT
+ DRMTOOL_CFG_ENROLLMENT
+ DOT
+ "dn";
- private static final String
- DRMTOOL_CFG_ENROLLMENT_EXTDATA_KEY_RECORD = DRMTOOL_CFG_PREFIX
+ private static final String DRMTOOL_CFG_ENROLLMENT_EXTDATA_KEY_RECORD = DRMTOOL_CFG_PREFIX
+ DOT
+ DRMTOOL_CFG_ENROLLMENT
+ DOT
+ "extdata.keyRecord";
- private static final String
- DRMTOOL_CFG_ENROLLMENT_EXTDATA_REQUEST_NOTES = DRMTOOL_CFG_PREFIX
+ private static final String DRMTOOL_CFG_ENROLLMENT_EXTDATA_REQUEST_NOTES = DRMTOOL_CFG_PREFIX
+ DOT
+ DRMTOOL_CFG_ENROLLMENT
+ DOT
+ "extdata.requestNotes";
- private static final String
- DRMTOOL_CFG_ENROLLMENT_REQUEST_ID = DRMTOOL_CFG_PREFIX
+ private static final String DRMTOOL_CFG_ENROLLMENT_REQUEST_ID = DRMTOOL_CFG_PREFIX
+ DOT
+ DRMTOOL_CFG_ENROLLMENT
+ DOT
+ "requestId";
-
- // Constants: DRMTOOL Config File (DRM CA Key Record Fields)
- private static final String
- DRMTOOL_CFG_CA_KEY_RECORD_CN = DRMTOOL_CFG_PREFIX
+ // Constants: DRMTOOL Config File (DRM CA Key Record Fields)
+ private static final String DRMTOOL_CFG_CA_KEY_RECORD_CN = DRMTOOL_CFG_PREFIX
+ DOT
+ DRMTOOL_CFG_CA_KEY_RECORD
+ DOT
+ "cn";
- private static final String
- DRMTOOL_CFG_CA_KEY_RECORD_DATE_OF_MODIFY = DRMTOOL_CFG_PREFIX
+ private static final String DRMTOOL_CFG_CA_KEY_RECORD_DATE_OF_MODIFY = DRMTOOL_CFG_PREFIX
+ DOT
+ DRMTOOL_CFG_CA_KEY_RECORD
+ DOT
+ "dateOfModify";
- private static final String
- DRMTOOL_CFG_CA_KEY_RECORD_DN = DRMTOOL_CFG_PREFIX
+ private static final String DRMTOOL_CFG_CA_KEY_RECORD_DN = DRMTOOL_CFG_PREFIX
+ DOT
+ DRMTOOL_CFG_ENROLLMENT
+ DOT
+ "dn";
- private static final String
- DRMTOOL_CFG_CA_KEY_RECORD_PRIVATE_KEY_DATA = DRMTOOL_CFG_PREFIX
+ private static final String DRMTOOL_CFG_CA_KEY_RECORD_PRIVATE_KEY_DATA = DRMTOOL_CFG_PREFIX
+ DOT
+ DRMTOOL_CFG_CA_KEY_RECORD
+ DOT
+ "privateKeyData";
- private static final String
- DRMTOOL_CFG_CA_KEY_RECORD_SERIAL_NO = DRMTOOL_CFG_PREFIX
+ private static final String DRMTOOL_CFG_CA_KEY_RECORD_SERIAL_NO = DRMTOOL_CFG_PREFIX
+ DOT
+ DRMTOOL_CFG_CA_KEY_RECORD
+ DOT
+ "serialno";
-
- // Constants: DRMTOOL Config File (DRM CA / TPS Recovery Request Fields)
- private static final String
- DRMTOOL_CFG_RECOVERY_CN = DRMTOOL_CFG_PREFIX
+ // Constants: DRMTOOL Config File (DRM CA / TPS Recovery Request Fields)
+ private static final String DRMTOOL_CFG_RECOVERY_CN = DRMTOOL_CFG_PREFIX
+ DOT
+ DRMTOOL_CFG_RECOVERY
+ DOT
+ "cn";
- private static final String
- DRMTOOL_CFG_RECOVERY_DATE_OF_MODIFY = DRMTOOL_CFG_PREFIX
+ private static final String DRMTOOL_CFG_RECOVERY_DATE_OF_MODIFY = DRMTOOL_CFG_PREFIX
+ DOT
+ DRMTOOL_CFG_RECOVERY
+ DOT
+ "dateOfModify";
- private static final String
- DRMTOOL_CFG_RECOVERY_DN = DRMTOOL_CFG_PREFIX
+ private static final String DRMTOOL_CFG_RECOVERY_DN = DRMTOOL_CFG_PREFIX
+ DOT
+ DRMTOOL_CFG_RECOVERY
+ DOT
+ "dn";
- private static final String
- DRMTOOL_CFG_RECOVERY_EXTDATA_REQUEST_ID = DRMTOOL_CFG_PREFIX
+ private static final String DRMTOOL_CFG_RECOVERY_EXTDATA_REQUEST_ID = DRMTOOL_CFG_PREFIX
+ DOT
+ DRMTOOL_CFG_RECOVERY
+ DOT
+ "extdata.requestId";
- private static final String
- DRMTOOL_CFG_RECOVERY_EXTDATA_REQUEST_NOTES = DRMTOOL_CFG_PREFIX
+ private static final String DRMTOOL_CFG_RECOVERY_EXTDATA_REQUEST_NOTES = DRMTOOL_CFG_PREFIX
+ DOT
+ DRMTOOL_CFG_RECOVERY
+ DOT
+ "extdata.requestNotes";
- private static final String
- DRMTOOL_CFG_RECOVERY_EXTDATA_SERIAL_NUMBER = DRMTOOL_CFG_PREFIX
+ private static final String DRMTOOL_CFG_RECOVERY_EXTDATA_SERIAL_NUMBER = DRMTOOL_CFG_PREFIX
+ DOT
+ DRMTOOL_CFG_RECOVERY
+ DOT
+ "extdata.serialnumber";
- private static final String
- DRMTOOL_CFG_RECOVERY_REQUEST_ID = DRMTOOL_CFG_PREFIX
+ private static final String DRMTOOL_CFG_RECOVERY_REQUEST_ID = DRMTOOL_CFG_PREFIX
+ DOT
+ DRMTOOL_CFG_RECOVERY
+ DOT
+ "requestId";
-
- // Constants: DRMTOOL Config File (DRM TPS Key Record Fields)
- private static final String
- DRMTOOL_CFG_TPS_KEY_RECORD_CN = DRMTOOL_CFG_PREFIX
+ // Constants: DRMTOOL Config File (DRM TPS Key Record Fields)
+ private static final String DRMTOOL_CFG_TPS_KEY_RECORD_CN = DRMTOOL_CFG_PREFIX
+ DOT
+ DRMTOOL_CFG_TPS_KEY_RECORD
+ DOT
+ "cn";
- private static final String
- DRMTOOL_CFG_TPS_KEY_RECORD_DATE_OF_MODIFY = DRMTOOL_CFG_PREFIX
+ private static final String DRMTOOL_CFG_TPS_KEY_RECORD_DATE_OF_MODIFY = DRMTOOL_CFG_PREFIX
+ DOT
+ DRMTOOL_CFG_TPS_KEY_RECORD
+ DOT
+ "dateOfModify";
- private static final String
- DRMTOOL_CFG_TPS_KEY_RECORD_DN = DRMTOOL_CFG_PREFIX
+ private static final String DRMTOOL_CFG_TPS_KEY_RECORD_DN = DRMTOOL_CFG_PREFIX
+ DOT
+ DRMTOOL_CFG_TPS_KEY_RECORD
+ DOT
+ "dn";
- private static final String
- DRMTOOL_CFG_TPS_KEY_RECORD_PRIVATE_KEY_DATA = DRMTOOL_CFG_PREFIX
+ private static final String DRMTOOL_CFG_TPS_KEY_RECORD_PRIVATE_KEY_DATA = DRMTOOL_CFG_PREFIX
+ DOT
+ DRMTOOL_CFG_TPS_KEY_RECORD
+ DOT
+ "privateKeyData";
- private static final String
- DRMTOOL_CFG_TPS_KEY_RECORD_SERIAL_NO = DRMTOOL_CFG_PREFIX
+ private static final String DRMTOOL_CFG_TPS_KEY_RECORD_SERIAL_NO = DRMTOOL_CFG_PREFIX
+ DOT
+ DRMTOOL_CFG_TPS_KEY_RECORD
+ DOT
+ "serialno";
-
- // Constants: DRMTOOL Config File (DRM TPS Netkey Keygen Request Fields)
- private static final String
- DRMTOOL_CFG_KEYGEN_CN = DRMTOOL_CFG_PREFIX
+ // Constants: DRMTOOL Config File (DRM TPS Netkey Keygen Request Fields)
+ private static final String DRMTOOL_CFG_KEYGEN_CN = DRMTOOL_CFG_PREFIX
+ DOT
+ DRMTOOL_CFG_KEYGEN
+ DOT
+ "cn";
- private static final String
- DRMTOOL_CFG_KEYGEN_DATE_OF_MODIFY = DRMTOOL_CFG_PREFIX
+ private static final String DRMTOOL_CFG_KEYGEN_DATE_OF_MODIFY = DRMTOOL_CFG_PREFIX
+ DOT
+ DRMTOOL_CFG_KEYGEN
+ DOT
+ "dateOfModify";
- private static final String
- DRMTOOL_CFG_KEYGEN_DN = DRMTOOL_CFG_PREFIX
+ private static final String DRMTOOL_CFG_KEYGEN_DN = DRMTOOL_CFG_PREFIX
+ DOT
+ DRMTOOL_CFG_KEYGEN
+ DOT
+ "dn";
- private static final String
- DRMTOOL_CFG_KEYGEN_EXTDATA_KEY_RECORD = DRMTOOL_CFG_PREFIX
+ private static final String DRMTOOL_CFG_KEYGEN_EXTDATA_KEY_RECORD = DRMTOOL_CFG_PREFIX
+ DOT
+ DRMTOOL_CFG_KEYGEN
+ DOT
+ "extdata.keyRecord";
- private static final String
- DRMTOOL_CFG_KEYGEN_EXTDATA_REQUEST_ID = DRMTOOL_CFG_PREFIX
+ private static final String DRMTOOL_CFG_KEYGEN_EXTDATA_REQUEST_ID = DRMTOOL_CFG_PREFIX
+ DOT
+ DRMTOOL_CFG_KEYGEN
+ DOT
+ "extdata.requestId";
- private static final String
- DRMTOOL_CFG_KEYGEN_EXTDATA_REQUEST_NOTES = DRMTOOL_CFG_PREFIX
+ private static final String DRMTOOL_CFG_KEYGEN_EXTDATA_REQUEST_NOTES = DRMTOOL_CFG_PREFIX
+ DOT
+ DRMTOOL_CFG_KEYGEN
+ DOT
+ "extdata.requestNotes";
- private static final String
- DRMTOOL_CFG_KEYGEN_REQUEST_ID = DRMTOOL_CFG_PREFIX
+ private static final String DRMTOOL_CFG_KEYGEN_REQUEST_ID = DRMTOOL_CFG_PREFIX
+ DOT
+ DRMTOOL_CFG_KEYGEN
+ DOT
+ "requestId";
-
- // Constants: Target Certificate Information
+ // Constants: Target Certificate Information
private static final String HEADER = "-----BEGIN";
private static final String TRAILER = "-----END";
private static final String X509_INFO = "x509.INFO";
-
- // Constants: DRM LDIF Record Fields
+ // Constants: DRM LDIF Record Fields
private static final String DRM_LDIF_ARCHIVED_BY = "archivedBy:";
private static final String DRM_LDIF_CN = "cn:";
private static final String DRM_LDIF_DATE_OF_MODIFY = "dateOfModify:";
private static final String DRM_LDIF_DN = "dn:";
private static final String DRM_LDIF_DN_EMBEDDED_CN_DATA = "dn: cn";
- private static final String
- DRM_LDIF_EXTDATA_AUTH_TOKEN_USER = "extdata-auth--005ftoken;user:";
- private static final String
- DRM_LDIF_EXTDATA_AUTH_TOKEN_USER_DN = "extdata-auth--005ftoken;userdn:";
- private static final String
- DRM_LDIF_EXTDATA_KEY_RECORD = "extdata-keyrecord:";
- private static final String
- DRM_LDIF_EXTDATA_REQUEST_ID = "extdata-requestid:";
- private static final String
- DRM_LDIF_EXTDATA_REQUEST_NOTES = "extdata-requestnotes:";
- private static final String
- DRM_LDIF_EXTDATA_REQUEST_TYPE = "extdata-requesttype:";
- private static final String
- DRM_LDIF_EXTDATA_SERIAL_NUMBER = "extdata-serialnumber:";
+ private static final String DRM_LDIF_EXTDATA_AUTH_TOKEN_USER = "extdata-auth--005ftoken;user:";
+ private static final String DRM_LDIF_EXTDATA_AUTH_TOKEN_USER_DN = "extdata-auth--005ftoken;userdn:";
+ private static final String DRM_LDIF_EXTDATA_KEY_RECORD = "extdata-keyrecord:";
+ private static final String DRM_LDIF_EXTDATA_REQUEST_ID = "extdata-requestid:";
+ private static final String DRM_LDIF_EXTDATA_REQUEST_NOTES = "extdata-requestnotes:";
+ private static final String DRM_LDIF_EXTDATA_REQUEST_TYPE = "extdata-requesttype:";
+ private static final String DRM_LDIF_EXTDATA_SERIAL_NUMBER = "extdata-serialnumber:";
private static final String DRM_LDIF_PRIVATE_KEY_DATA = "privateKeyData::";
private static final String DRM_LDIF_REQUEST_ID = "requestId:";
private static final String DRM_LDIF_REQUEST_TYPE = "requestType:";
private static final String DRM_LDIF_SERIAL_NO = "serialno:";
-
- // Constants: DRM LDIF Record Values
+ // Constants: DRM LDIF Record Values
private static final int INITIAL_LDIF_RECORD_CAPACITY = 0;
private static final int EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH = 56;
private static final int PRIVATE_KEY_DATA_FIRST_LINE_DATA_LENGTH = 60;
@@ -984,8 +891,7 @@ public class DRMTool
private static final String DRM_LDIF_RECOVERY = "recovery";
private static final String DRM_LDIF_TPS_KEY_RECORD = "TPS";
-
- // Constants: DRM LDIF Record Messages
+ // Constants: DRM LDIF Record Messages
private static final String DRM_LDIF_REWRAP_MESSAGE = "REWRAPPED the '"
+ "existing DES3 "
+ "symmetric "
@@ -997,7 +903,7 @@ public class DRMTool
+ "certificate";
private static final String DRM_LDIF_USED_PWDFILE_MESSAGE =
"USED source PKI security database "
- + "password file";
+ + "password file";
private static final String DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE =
"APPENDED ID offset";
private static final String DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE =
@@ -1006,19 +912,16 @@ public class DRMTool
"RENAMED source DRM naming context '";
private static final String DRM_LDIF_TARGET_NAME_CONTEXT_MESSAGE =
"' to target DRM naming context '";
- private static final String
- DRM_LDIF_PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY_MESSAGE =
+ private static final String DRM_LDIF_PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY_MESSAGE =
"PROCESSED requests and key records ONLY!";
-
/*************/
/* Variables */
/*************/
- // Variables: Calendar
+ // Variables: Calendar
private static String mDateOfModify = null;
-
// Variables: Command-Line Options
private static boolean mMandatoryFlag = false;
private static boolean mRewrapFlag = false;
@@ -1034,14 +937,12 @@ public class DRMTool
private static int mRemoveIdOffsetNameValuePairs = 0;
private static int mDrmNamingContextNameValuePairs = 0;
-
// Variables: Command-Line Values (Mandatory)
private static String mDrmtoolCfgFilename = null;
private static String mSourceLdifFilename = null;
private static String mTargetLdifFilename = null;
private static String mLogFilename = null;
-
// Variables: Command-Line Values (Rewrap)
private static String mSourcePKISecurityDatabasePath = null;
private static String mSourceStorageTokenName = null;
@@ -1055,41 +956,34 @@ public class DRMTool
private static BigInteger mAppendIdOffset = null;
private static BigInteger mRemoveIdOffset = null;
-
// Variables: Command-Line Values (DRM Naming Contexts)
private static String mSourceDrmNamingContext = null;
private static String mTargetDrmNamingContext = null;
-
- // Variables: DRMTOOL Config File Parameters of Interest
+ // Variables: DRMTOOL Config File Parameters of Interest
private static Hashtable<String, Boolean> drmtoolCfg = null;
-
- // Variables: DRMTOOL LDIF File Parameters of Interest
+ // Variables: DRMTOOL LDIF File Parameters of Interest
private static Vector<String> record = null;
private static Iterator<String> ldif_record = null;
-
- // Variables: Logging
- private static boolean mDebug = false; // set 'true' for debug messages
+ // Variables: Logging
+ private static boolean mDebug = false; // set 'true' for debug messages
private static PrintWriter logger = null;
private static String current_date_and_time = null;
-
- // Variables: PKCS #11 Information
+ // Variables: PKCS #11 Information
private static CryptoToken mSourceToken = null;
private static X509Certificate mUnwrapCert = null;
private static PrivateKey mUnwrapPrivateKey = null;
private static PublicKey mWrapPublicKey = null;
private static int mPublicKeySize = 0;
-
- // Variables: DRM LDIF Record Messages
+ // Variables: DRM LDIF Record Messages
private static String mSourcePKISecurityDatabasePwdfileMessage = null;
private static String mDrmNamingContextMessage = null;
private static String mProcessRequestsAndKeyRecordsOnlyMessage = null;
-
/********************/
/* Calendar Methods */
/********************/
@@ -1097,27 +991,26 @@ public class DRMTool
/**
* This method is used to get the current date and time.
* <P>
- *
+ *
* @param pattern string containing desired format of date and time
* @return a formatted string containing the current date and time
*/
- private static String now( String pattern ) {
+ private static String now(String pattern) {
Calendar cal = Calendar.getInstance();
- SimpleDateFormat sdf = new SimpleDateFormat( pattern );
- return sdf.format( cal.getTime() );
+ SimpleDateFormat sdf = new SimpleDateFormat(pattern);
+ return sdf.format(cal.getTime());
}
-
/*****************/
/* Usage Methods */
/*****************/
/**
- * This method prints out the proper command-line usage required to
- * execute DRMTool.
+ * This method prints out the proper command-line usage required to execute
+ * DRMTool.
*/
private static void printUsage() {
- System.out.println( "Usage: "
+ System.out.println("Usage: "
+ DRM_TOOL
+ NEWLINE
+ " "
@@ -1220,9 +1113,9 @@ public class DRMTool
+ "["
+ PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY
+ "]"
- + NEWLINE );
+ + NEWLINE);
- System.out.println( "Example of 'Rewrap and Append ID Offset':"
+ System.out.println("Example of 'Rewrap and Append ID Offset':"
+ NEWLINE
+ NEWLINE
+ " "
@@ -1266,9 +1159,9 @@ public class DRMTool
+ NEWLINE
+ " "
+ PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY
- + NEWLINE );
+ + NEWLINE);
- System.out.println( "Example of 'Rewrap and Remove ID Offset':"
+ System.out.println("Example of 'Rewrap and Remove ID Offset':"
+ NEWLINE
+ NEWLINE
+ " "
@@ -1312,9 +1205,9 @@ public class DRMTool
+ NEWLINE
+ " "
+ PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY
- + NEWLINE );
+ + NEWLINE);
- System.out.println( "Example of 'Rewrap':"
+ System.out.println("Example of 'Rewrap':"
+ NEWLINE
+ NEWLINE
+ " "
@@ -1355,9 +1248,9 @@ public class DRMTool
+ NEWLINE
+ " "
+ PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY
- + NEWLINE );
+ + NEWLINE);
- System.out.println( "Example of 'Append ID Offset':"
+ System.out.println("Example of 'Append ID Offset':"
+ NEWLINE
+ NEWLINE
+ " "
@@ -1386,9 +1279,9 @@ public class DRMTool
+ NEWLINE
+ " "
+ PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY
- + NEWLINE );
+ + NEWLINE);
- System.out.println( "Example of 'Remove ID Offset':"
+ System.out.println("Example of 'Remove ID Offset':"
+ NEWLINE
+ NEWLINE
+ " "
@@ -1417,10 +1310,9 @@ public class DRMTool
+ NEWLINE
+ " "
+ PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY
- + NEWLINE );
+ + NEWLINE);
}
-
/*******************/
/* Logging Methods */
/*******************/
@@ -1428,83 +1320,80 @@ public class DRMTool
/**
* This method opens a new log file for writing.
* <P>
- *
+ *
* @param logfile string containing the name of the log file to be opened
*/
- private static void open_log( String logfile ) {
+ private static void open_log(String logfile) {
try {
logger = new PrintWriter(
new BufferedWriter(
- new FileWriter( logfile ) ) );
- } catch( IOException eFile ) {
- System.err.println( "ERROR: Unable to open file '"
+ new FileWriter(logfile)));
+ } catch (IOException eFile) {
+ System.err.println("ERROR: Unable to open file '"
+ logfile
+ "' for writing: '"
+ eFile.toString()
+ "'"
- + NEWLINE );
- System.exit( 0 );
+ + NEWLINE);
+ System.exit(0);
}
}
-
/**
* This method closes the specified log file.
* <P>
- *
+ *
* @param logfile string containing the name of the log file to be closed
*/
- private static void close_log( String logfile ) {
+ private static void close_log(String logfile) {
logger.close();
}
-
/**
- * This method writes the specified message to the log file, and also
- * to 'stderr' if the boolean flag is set to 'true'.
+ * This method writes the specified message to the log file, and also to
+ * 'stderr' if the boolean flag is set to 'true'.
* <P>
- *
+ *
* @param msg string containing the message to be written to the log file
* @param stderr boolean which also writes the message to 'stderr' if 'true'
*/
- private static void log( String msg, boolean stderr ) {
- current_date_and_time = now( LOGGING_DATE_PATTERN );
- if( stderr ) {
- System.err.println( msg );
+ private static void log(String msg, boolean stderr) {
+ current_date_and_time = now(LOGGING_DATE_PATTERN);
+ if (stderr) {
+ System.err.println(msg);
}
- logger.write( "["
+ logger.write("["
+ current_date_and_time
+ "]: "
- + msg );
+ + msg);
logger.flush();
}
-
/*********************************************/
- /* PKCS #11: Rewrap RSA Storage Key Methods */
+ /* PKCS #11: Rewrap RSA Storage Key Methods */
/*********************************************/
/**
* Helper method to determine if two arrays contain the same values.
- *
+ *
* This method is based upon code from 'com.netscape.kra.StorageKeyUnit'.
* <P>
- *
+ *
* @param bytes first array of bytes
* @param ints second array of bytes
* @return true if the two arrays are identical
*/
- private static boolean arraysEqual( byte[] bytes, byte[] ints ) {
- if( bytes == null || ints == null ) {
+ private static boolean arraysEqual(byte[] bytes, byte[] ints) {
+ if (bytes == null || ints == null) {
return false;
}
- if( bytes.length != ints.length ) {
+ if (bytes.length != ints.length) {
return false;
}
- for( int i = 0; i < bytes.length; i++ ) {
- if( bytes[i] != ints[i] ) {
+ for (int i = 0; i < bytes.length; i++) {
+ if (bytes[i] != ints[i]) {
return false;
}
}
@@ -1512,49 +1401,47 @@ public class DRMTool
return true;
}
-
/**
- * This method is used to obtain the private RSA storage key from
- * the "source" DRM instance's security databases.
- *
+ * This method is used to obtain the private RSA storage key from the
+ * "source" DRM instance's security databases.
+ *
* This method is based upon code from 'com.netscape.kra.StorageKeyUnit'.
* <P>
- *
+ *
* @return the private RSA storage key from the "source" DRM
*/
private static PrivateKey getPrivateKey() {
try {
- PrivateKey pk[] = mSourceToken.getCryptoStore().getPrivateKeys();
-
- for( int i = 0; i < pk.length; i++ ) {
- if( arraysEqual( pk[i].getUniqueID(),
- ( ( TokenCertificate )
- mUnwrapCert ).getUniqueID() ) ) {
- return pk[i];
- }
- }
- } catch( TokenException exToken ) {
- log( "ERROR: Getting private key - "
- + "TokenException: '"
- + exToken.toString()
- + "'"
- + NEWLINE, true );
- System.exit( 0 );
+ PrivateKey pk[] = mSourceToken.getCryptoStore().getPrivateKeys();
+
+ for (int i = 0; i < pk.length; i++) {
+ if (arraysEqual(pk[i].getUniqueID(),
+ ((TokenCertificate)
+ mUnwrapCert).getUniqueID())) {
+ return pk[i];
+ }
+ }
+ } catch (TokenException exToken) {
+ log("ERROR: Getting private key - "
+ + "TokenException: '"
+ + exToken.toString()
+ + "'"
+ + NEWLINE, true);
+ System.exit(0);
}
return null;
}
-
/**
- * This method gets the public key from the certificate stored
- * in the "target" DRM storage certificate file. It also obtains
- * the keysize of this RSA key.
- *
+ * This method gets the public key from the certificate stored in the
+ * "target" DRM storage certificate file. It also obtains the keysize of
+ * this RSA key.
+ *
* This method is based upon code from
* 'com.netscape.cmstools.PrettyPrintCert'.
* <P>
- *
+ *
* @return the public RSA storage key from the "target" DRM
*/
private static PublicKey getPublicKey() {
@@ -1572,19 +1459,19 @@ public class DRMTool
try {
inputCert = new BufferedReader(
new InputStreamReader(
- new BufferedInputStream(
- new FileInputStream(
- mTargetStorageCertificateFilename
- ) ) ) );
- } catch( FileNotFoundException exWrapFileNotFound ) {
- log( "ERROR: No target storage "
- + "certificate file named '"
- + mTargetStorageCertificateFilename
- + "' exists! FileNotFoundException: '"
- + exWrapFileNotFound.toString()
- + "'"
- + NEWLINE, true );
- System.exit( 0 );
+ new BufferedInputStream(
+ new FileInputStream(
+ mTargetStorageCertificateFilename
+ ))));
+ } catch (FileNotFoundException exWrapFileNotFound) {
+ log("ERROR: No target storage "
+ + "certificate file named '"
+ + mTargetStorageCertificateFilename
+ + "' exists! FileNotFoundException: '"
+ + exWrapFileNotFound.toString()
+ + "'"
+ + NEWLINE, true);
+ System.exit(0);
}
// Read the entire contents of the specified BASE 64 encoded
@@ -1592,78 +1479,78 @@ public class DRMTool
// headers beginning with HEADER and any trailers beginning
// with TRAILER
try {
- while( ( encodedBASE64CertChunk = inputCert.readLine() ) != null ) {
- if( !( encodedBASE64CertChunk.startsWith( HEADER ) ) &&
- !( encodedBASE64CertChunk.startsWith( TRAILER ) ) ) {
+ while ((encodedBASE64CertChunk = inputCert.readLine()) != null) {
+ if (!(encodedBASE64CertChunk.startsWith(HEADER)) &&
+ !(encodedBASE64CertChunk.startsWith(TRAILER))) {
encodedBASE64Cert += encodedBASE64CertChunk.trim();
}
}
- } catch( IOException exWrapReadLineIO ) {
- log( "ERROR: Unexpected BASE64 "
- + "encoded error encountered while reading '"
- + mTargetStorageCertificateFilename
- + "'! IOException: '"
- + exWrapReadLineIO.toString()
- + "'"
- + NEWLINE, true );
- System.exit( 0 );
+ } catch (IOException exWrapReadLineIO) {
+ log("ERROR: Unexpected BASE64 "
+ + "encoded error encountered while reading '"
+ + mTargetStorageCertificateFilename
+ + "'! IOException: '"
+ + exWrapReadLineIO.toString()
+ + "'"
+ + NEWLINE, true);
+ System.exit(0);
}
// Close the DataInputStream() object
try {
inputCert.close();
- } catch( IOException exWrapCloseIO ) {
- log( "ERROR: Unexpected BASE64 "
- + "encoded error encountered in closing '"
- + mTargetStorageCertificateFilename
- + "'! IOException: '"
- + exWrapCloseIO.toString()
- + "'"
- + NEWLINE, true );
- System.exit( 0 );
+ } catch (IOException exWrapCloseIO) {
+ log("ERROR: Unexpected BASE64 "
+ + "encoded error encountered in closing '"
+ + mTargetStorageCertificateFilename
+ + "'! IOException: '"
+ + exWrapCloseIO.toString()
+ + "'"
+ + NEWLINE, true);
+ System.exit(0);
}
// Decode the ASCII BASE 64 certificate enclosed in the
// String() object into a BINARY BASE 64 byte[] object
decodedBASE64Cert = com.netscape.osutil.OSUtil.AtoB(
- encodedBASE64Cert );
+ encodedBASE64Cert);
// Create an X509CertImpl() object from
// the BINARY BASE 64 byte[] object
try {
- cert = new X509CertImpl( decodedBASE64Cert );
- } catch( CertificateException exWrapCertificate ) {
- log( "ERROR: Error encountered "
- + "in parsing certificate in '"
- + mTargetStorageCertificateFilename
- + "' CertificateException: '"
- + exWrapCertificate.toString()
- + "'"
- + NEWLINE, true );
- System.exit( 0 );
+ cert = new X509CertImpl(decodedBASE64Cert);
+ } catch (CertificateException exWrapCertificate) {
+ log("ERROR: Error encountered "
+ + "in parsing certificate in '"
+ + mTargetStorageCertificateFilename
+ + "' CertificateException: '"
+ + exWrapCertificate.toString()
+ + "'"
+ + NEWLINE, true);
+ System.exit(0);
}
// Extract the Public Key
key = cert.getPublicKey();
- if( key == null ) {
- log( "ERROR: Unable to extract public key "
- + "from certificate that was stored in '"
- + mTargetStorageCertificateFilename
- + "'."
- + NEWLINE, true );
- System.exit( 0 );
+ if (key == null) {
+ log("ERROR: Unable to extract public key "
+ + "from certificate that was stored in '"
+ + mTargetStorageCertificateFilename
+ + "'."
+ + NEWLINE, true);
+ System.exit(0);
}
// Convert this X.509 public key --> RSA public key
try {
- rsakey = new RSAPublicKey( key.getEncoded() );
- } catch( InvalidKeyException exInvalidKey ) {
- log( "ERROR: Converting X.509 public key --> RSA public key - "
- + "InvalidKeyException: '"
- + exInvalidKey.toString()
- + "'"
- + NEWLINE, true );
- System.exit( 0 );
+ rsakey = new RSAPublicKey(key.getEncoded());
+ } catch (InvalidKeyException exInvalidKey) {
+ log("ERROR: Converting X.509 public key --> RSA public key - "
+ + "InvalidKeyException: '"
+ + exInvalidKey.toString()
+ + "'"
+ + NEWLINE, true);
+ System.exit(0);
}
// Obtain the Public Key's keysize
@@ -1672,14 +1559,12 @@ public class DRMTool
return key;
}
-
/**
- * This method is used to obtain the private RSA storage key
- * from the "source" DRM instance's security databases and
- * the public RSA storage key from the certificate stored in
- * the "target" DRM storage certificate file.
+ * This method is used to obtain the private RSA storage key from the
+ * "source" DRM instance's security databases and the public RSA storage key
+ * from the certificate stored in the "target" DRM storage certificate file.
* <P>
- *
+ *
* @return true if successfully able to obtain both keys
*/
private static boolean obtain_RSA_rewrapping_keys() {
@@ -1687,67 +1572,67 @@ public class DRMTool
// Initialize the source security databases
try {
- log( "Initializing source PKI security databases in '"
- + mSourcePKISecurityDatabasePath + "'."
- + NEWLINE, true );
-
- CryptoManager.initialize( mSourcePKISecurityDatabasePath );
- } catch( KeyDatabaseException exKey ) {
- log( "ERROR: source_pki_security_database_path='"
- + mSourcePKISecurityDatabasePath
- + "' KeyDatabaseException: '"
- + exKey.toString()
- + "'"
- + NEWLINE, true );
- System.exit( 0 );
- } catch( CertDatabaseException exCert ) {
- log( "ERROR: source_pki_security_database_path='"
- + mSourcePKISecurityDatabasePath
- + "' CertDatabaseException: '"
- + exCert.toString()
- + "'"
- + NEWLINE, true );
- System.exit( 0 );
- } catch( AlreadyInitializedException exAlreadyInitialized ) {
- log( "ERROR: source_pki_security_database_path='"
- + mSourcePKISecurityDatabasePath
- + "' AlreadyInitializedException: '"
- + exAlreadyInitialized.toString()
- + "'"
- + NEWLINE, true );
- System.exit( 0 );
- } catch( GeneralSecurityException exSecurity ) {
- log( "ERROR: source_pki_security_database_path='"
- + mSourcePKISecurityDatabasePath
- + "' GeneralSecurityException: '"
- + exSecurity.toString()
- + "'"
- + NEWLINE, true );
- System.exit( 0 );
+ log("Initializing source PKI security databases in '"
+ + mSourcePKISecurityDatabasePath + "'."
+ + NEWLINE, true);
+
+ CryptoManager.initialize(mSourcePKISecurityDatabasePath);
+ } catch (KeyDatabaseException exKey) {
+ log("ERROR: source_pki_security_database_path='"
+ + mSourcePKISecurityDatabasePath
+ + "' KeyDatabaseException: '"
+ + exKey.toString()
+ + "'"
+ + NEWLINE, true);
+ System.exit(0);
+ } catch (CertDatabaseException exCert) {
+ log("ERROR: source_pki_security_database_path='"
+ + mSourcePKISecurityDatabasePath
+ + "' CertDatabaseException: '"
+ + exCert.toString()
+ + "'"
+ + NEWLINE, true);
+ System.exit(0);
+ } catch (AlreadyInitializedException exAlreadyInitialized) {
+ log("ERROR: source_pki_security_database_path='"
+ + mSourcePKISecurityDatabasePath
+ + "' AlreadyInitializedException: '"
+ + exAlreadyInitialized.toString()
+ + "'"
+ + NEWLINE, true);
+ System.exit(0);
+ } catch (GeneralSecurityException exSecurity) {
+ log("ERROR: source_pki_security_database_path='"
+ + mSourcePKISecurityDatabasePath
+ + "' GeneralSecurityException: '"
+ + exSecurity.toString()
+ + "'"
+ + NEWLINE, true);
+ System.exit(0);
}
// Retrieve the source storage token by its name
try {
- log( "Retrieving token from CryptoManager."
- + NEWLINE, true );
+ log("Retrieving token from CryptoManager."
+ + NEWLINE, true);
cm = CryptoManager.getInstance();
- log( "Retrieving source storage token called '"
- + mSourceStorageTokenName
- + "'."
- + NEWLINE, true );
+ log("Retrieving source storage token called '"
+ + mSourceStorageTokenName
+ + "'."
+ + NEWLINE, true);
- if( mSourceStorageTokenName.equals( INTERNAL_TOKEN ) ) {
+ if (mSourceStorageTokenName.equals(INTERNAL_TOKEN)) {
mSourceToken = cm.getInternalKeyStorageToken();
} else {
- mSourceToken = cm.getTokenByName( mSourceStorageTokenName );
+ mSourceToken = cm.getTokenByName(mSourceStorageTokenName);
}
- if( mSourceToken == null ) {
+ if (mSourceToken == null) {
return FAILURE;
}
- if( mPwdfileFlag ) {
+ if (mPwdfileFlag) {
BufferedReader in = null;
String pwd = null;
Password mPwd = null;
@@ -1755,177 +1640,170 @@ public class DRMTool
try {
in = new BufferedReader(
new FileReader(
- mSourcePKISecurityDatabasePwdfile ) );
+ mSourcePKISecurityDatabasePwdfile));
pwd = in.readLine();
- mPwd = new Password( pwd.toCharArray() );
-
- mSourceToken.login( mPwd );
- } catch( Exception exReadPwd ) {
- log( "ERROR: Failed to read the keydb password from "
- + "the file '"
- + mSourcePKISecurityDatabasePwdfile
- + "'. Exception: '"
- + exReadPwd.toString()
- + "'"
- + NEWLINE, true );
- System.exit( 0 );
+ mPwd = new Password(pwd.toCharArray());
+
+ mSourceToken.login(mPwd);
+ } catch (Exception exReadPwd) {
+ log("ERROR: Failed to read the keydb password from "
+ + "the file '"
+ + mSourcePKISecurityDatabasePwdfile
+ + "'. Exception: '"
+ + exReadPwd.toString()
+ + "'"
+ + NEWLINE, true);
+ System.exit(0);
}
}
- } catch( Exception exUninitialized ) {
- log( "ERROR: Uninitialized CryptoManager - '"
- + exUninitialized.toString()
- + "'"
- + NEWLINE, true );
- System.exit( 0 );
+ } catch (Exception exUninitialized) {
+ log("ERROR: Uninitialized CryptoManager - '"
+ + exUninitialized.toString()
+ + "'"
+ + NEWLINE, true);
+ System.exit(0);
}
// Retrieve the source storage cert by its nickname
try {
- if( mSourceStorageTokenName.equals( INTERNAL_TOKEN ) ) {
- log( "Retrieving source storage cert with nickname of '"
- + mSourceStorageCertNickname
- + "'."
- + NEWLINE, true );
+ if (mSourceStorageTokenName.equals(INTERNAL_TOKEN)) {
+ log("Retrieving source storage cert with nickname of '"
+ + mSourceStorageCertNickname
+ + "'."
+ + NEWLINE, true);
- mUnwrapCert = cm.findCertByNickname( mSourceStorageCertNickname
+ mUnwrapCert = cm.findCertByNickname(mSourceStorageCertNickname
);
} else {
- log( "Retrieving source storage cert with nickname of '"
- + mSourceStorageTokenName
- + ":"
- + mSourceStorageCertNickname
- + "'. "
- + NEWLINE, true );
- mUnwrapCert = cm.findCertByNickname( mSourceStorageTokenName
+ log("Retrieving source storage cert with nickname of '"
+ + mSourceStorageTokenName
+ + ":"
+ + mSourceStorageCertNickname
+ + "'. "
+ + NEWLINE, true);
+ mUnwrapCert = cm.findCertByNickname(mSourceStorageTokenName
+ ":"
+ mSourceStorageCertNickname
);
}
- if( mUnwrapCert == null ) {
+ if (mUnwrapCert == null) {
return FAILURE;
}
- } catch( ObjectNotFoundException exUnwrapObjectNotFound ) {
- if( mSourceStorageTokenName.equals( INTERNAL_TOKEN ) ) {
- log( "ERROR: No internal "
- + "source storage cert named '"
- + mSourceStorageCertNickname
- + "' exists! ObjectNotFoundException: '"
- + exUnwrapObjectNotFound.toString()
- + "'"
- + NEWLINE, true );
+ } catch (ObjectNotFoundException exUnwrapObjectNotFound) {
+ if (mSourceStorageTokenName.equals(INTERNAL_TOKEN)) {
+ log("ERROR: No internal "
+ + "source storage cert named '"
+ + mSourceStorageCertNickname
+ + "' exists! ObjectNotFoundException: '"
+ + exUnwrapObjectNotFound.toString()
+ + "'"
+ + NEWLINE, true);
} else {
- log( "ERROR: No "
- + "source storage cert named '"
- + mSourceStorageTokenName
- + ":"
- + mSourceStorageCertNickname
- + "' exists! ObjectNotFoundException: '"
- + exUnwrapObjectNotFound
- + "'"
- + NEWLINE, true );
+ log("ERROR: No "
+ + "source storage cert named '"
+ + mSourceStorageTokenName
+ + ":"
+ + mSourceStorageCertNickname
+ + "' exists! ObjectNotFoundException: '"
+ + exUnwrapObjectNotFound
+ + "'"
+ + NEWLINE, true);
}
- System.exit( 0 );
- } catch( TokenException exUnwrapToken ) {
- if( mSourceStorageTokenName.equals( INTERNAL_TOKEN ) ) {
- log( "ERROR: No internal "
- + "source storage cert named '"
- + mSourceStorageCertNickname
- + "' exists! TokenException: '"
- + exUnwrapToken.toString()
- + "'"
- + NEWLINE, true );
+ System.exit(0);
+ } catch (TokenException exUnwrapToken) {
+ if (mSourceStorageTokenName.equals(INTERNAL_TOKEN)) {
+ log("ERROR: No internal "
+ + "source storage cert named '"
+ + mSourceStorageCertNickname
+ + "' exists! TokenException: '"
+ + exUnwrapToken.toString()
+ + "'"
+ + NEWLINE, true);
} else {
- log( "ERROR: No "
- + "source storage cert named '"
- + mSourceStorageTokenName
- + ":"
- + mSourceStorageCertNickname
- + "' exists! TokenException: '"
- + exUnwrapToken
- + "'"
- + NEWLINE, true );
+ log("ERROR: No "
+ + "source storage cert named '"
+ + mSourceStorageTokenName
+ + ":"
+ + mSourceStorageCertNickname
+ + "' exists! TokenException: '"
+ + exUnwrapToken
+ + "'"
+ + NEWLINE, true);
}
- System.exit( 0 );
+ System.exit(0);
}
-
// Extract the private key from the source storage token
- log( "BEGIN: Obtaining the private key from "
- + "the source storage token . . ."
- + NEWLINE, true );
+ log("BEGIN: Obtaining the private key from "
+ + "the source storage token . . ."
+ + NEWLINE, true);
mUnwrapPrivateKey = getPrivateKey();
- if( mUnwrapPrivateKey == null ) {
- log( "ERROR: Failed extracting "
- + "private key from the source storage token."
- + NEWLINE, true );
- System.exit( 0 );
+ if (mUnwrapPrivateKey == null) {
+ log("ERROR: Failed extracting "
+ + "private key from the source storage token."
+ + NEWLINE, true);
+ System.exit(0);
}
- log( "FINISHED: Obtaining the private key from "
- + "the source storage token."
- + NEWLINE, true );
-
+ log("FINISHED: Obtaining the private key from "
+ + "the source storage token."
+ + NEWLINE, true);
// Extract the public key from the target storage certificate
try {
- log( "BEGIN: Obtaining the public key from "
- + "the target storage certificate . . ."
- + NEWLINE, true );
-
- mWrapPublicKey = ( PublicKey )
- ( PK11PubKey.fromSPKI(
- getPublicKey().getEncoded() ) );
-
- if( mWrapPublicKey == null ) {
- log( "ERROR: Failed extracting "
- + "public key from target storage certificate stored in '"
- + mTargetStorageCertificateFilename
- + "'"
- + NEWLINE, true );
- System.exit( 0 );
+ log("BEGIN: Obtaining the public key from "
+ + "the target storage certificate . . ."
+ + NEWLINE, true);
+
+ mWrapPublicKey = (PublicKey)
+ (PK11PubKey.fromSPKI(
+ getPublicKey().getEncoded()));
+
+ if (mWrapPublicKey == null) {
+ log("ERROR: Failed extracting "
+ + "public key from target storage certificate stored in '"
+ + mTargetStorageCertificateFilename
+ + "'"
+ + NEWLINE, true);
+ System.exit(0);
}
- log( "FINISHED: Obtaining the public key from "
- + "the target storage certificate."
- + NEWLINE, true );
- } catch( InvalidKeyFormatException exInvalidPublicKey ) {
- log( "ERROR: Failed extracting "
- + "public key from target storage certificate stored in '"
- + mTargetStorageCertificateFilename
- + "' InvalidKeyFormatException '"
- + exInvalidPublicKey.toString()
- + "'"
- + NEWLINE, true );
- System.exit( 0 );
+ log("FINISHED: Obtaining the public key from "
+ + "the target storage certificate."
+ + NEWLINE, true);
+ } catch (InvalidKeyFormatException exInvalidPublicKey) {
+ log("ERROR: Failed extracting "
+ + "public key from target storage certificate stored in '"
+ + mTargetStorageCertificateFilename
+ + "' InvalidKeyFormatException '"
+ + exInvalidPublicKey.toString()
+ + "'"
+ + NEWLINE, true);
+ System.exit(0);
}
return SUCCESS;
}
-
/**
* This method basically rewraps the "wrappedKeyData" by implementiing
* "mStorageUnit.decryptInternalPrivate( byte wrappedKeyData[] )" and
* "mStorageUnit.encryptInternalPrivate( byte priKey[] )", where
* "wrappedKeyData" uses the following structure:
- *
- * SEQUENCE {
- * encryptedSession OCTET STRING,
- * encryptedPrivate OCTET STRING
- * }
- *
- * This method is based upon code from
- * 'com.netscape.kra.EncryptionUnit'.
+ *
+ * SEQUENCE { encryptedSession OCTET STRING, encryptedPrivate OCTET STRING }
+ *
+ * This method is based upon code from 'com.netscape.kra.EncryptionUnit'.
* <P>
- *
+ *
* @return a byte[] containing the rewrappedKeyData
*/
- private static byte[] rewrap_wrapped_key_data( byte[] wrappedKeyData )
- throws Exception {
+ private static byte[] rewrap_wrapped_key_data(byte[] wrappedKeyData)
+ throws Exception {
DerValue val = null;
DerInputStream in = null;
DerValue dSession = null;
@@ -1944,75 +1822,75 @@ public class DRMTool
// mStorageUnit.decryptInternalPrivate( byte wrappedKeyData[] );
// throws EBaseException
try {
- val = new DerValue( wrappedKeyData );
+ val = new DerValue(wrappedKeyData);
in = val.data;
dSession = in.getDerValue();
source_session = dSession.getOctetString();
dPri = in.getDerValue();
pri = dPri.getOctetString();
source_rsaWrap = mSourceToken.getKeyWrapper(
- KeyWrapAlgorithm.RSA );
- source_rsaWrap.initUnwrap( mUnwrapPrivateKey, null );
- sk = source_rsaWrap.unwrapSymmetric( source_session,
+ KeyWrapAlgorithm.RSA);
+ source_rsaWrap.initUnwrap(mUnwrapPrivateKey, null);
+ sk = source_rsaWrap.unwrapSymmetric(source_session,
SymmetricKey.DES3,
SymmetricKey.Usage.DECRYPT,
- 0 );
- if( mDebug ) {
- log( "DEBUG: sk = '"
- + com.netscape.osutil.OSUtil.BtoA( sk.getEncoded() )
- + "' length = '"
- + sk.getEncoded().length
- + "'"
- + NEWLINE, false );
- log( "DEBUG: pri = '"
- + com.netscape.osutil.OSUtil.BtoA( pri )
- + "' length = '"
- + pri.length
- + "'"
- + NEWLINE, false );
+ 0);
+ if (mDebug) {
+ log("DEBUG: sk = '"
+ + com.netscape.osutil.OSUtil.BtoA(sk.getEncoded())
+ + "' length = '"
+ + sk.getEncoded().length
+ + "'"
+ + NEWLINE, false);
+ log("DEBUG: pri = '"
+ + com.netscape.osutil.OSUtil.BtoA(pri)
+ + "' length = '"
+ + pri.length
+ + "'"
+ + NEWLINE, false);
}
- } catch( IOException exUnwrapIO ) {
- log( "ERROR: Unwrapping key data - "
- + "IOException: '"
- + exUnwrapIO.toString()
- + "'"
- + NEWLINE, true );
- System.exit( 0 );
- } catch( NoSuchAlgorithmException exUnwrapAlgorithm ) {
- log( "ERROR: Unwrapping key data - "
- + "NoSuchAlgorithmException: '"
- + exUnwrapAlgorithm.toString()
- + "'"
- + NEWLINE, true );
- System.exit( 0 );
- } catch( TokenException exUnwrapToken ) {
- log( "ERROR: Unwrapping key data - "
- + "TokenException: '"
- + exUnwrapToken.toString()
- + "'"
- + NEWLINE, true );
- System.exit( 0 );
- } catch( InvalidKeyException exUnwrapInvalidKey ) {
- log( "ERROR: Unwrapping key data - "
- + "InvalidKeyException: '"
- + exUnwrapInvalidKey.toString()
- + "'"
- + NEWLINE, true );
- System.exit( 0 );
- } catch( InvalidAlgorithmParameterException exUnwrapInvalidAlgorithm ) {
- log( "ERROR: Unwrapping key data - "
- + "InvalidAlgorithmParameterException: '"
- + exUnwrapInvalidAlgorithm.toString()
- + "'"
- + NEWLINE, true );
- System.exit( 0 );
- } catch( IllegalStateException exUnwrapState ) {
- log( "ERROR: Unwrapping key data - "
- + "InvalidStateException: '"
- + exUnwrapState.toString()
- + "'"
- + NEWLINE, true );
- System.exit( 0 );
+ } catch (IOException exUnwrapIO) {
+ log("ERROR: Unwrapping key data - "
+ + "IOException: '"
+ + exUnwrapIO.toString()
+ + "'"
+ + NEWLINE, true);
+ System.exit(0);
+ } catch (NoSuchAlgorithmException exUnwrapAlgorithm) {
+ log("ERROR: Unwrapping key data - "
+ + "NoSuchAlgorithmException: '"
+ + exUnwrapAlgorithm.toString()
+ + "'"
+ + NEWLINE, true);
+ System.exit(0);
+ } catch (TokenException exUnwrapToken) {
+ log("ERROR: Unwrapping key data - "
+ + "TokenException: '"
+ + exUnwrapToken.toString()
+ + "'"
+ + NEWLINE, true);
+ System.exit(0);
+ } catch (InvalidKeyException exUnwrapInvalidKey) {
+ log("ERROR: Unwrapping key data - "
+ + "InvalidKeyException: '"
+ + exUnwrapInvalidKey.toString()
+ + "'"
+ + NEWLINE, true);
+ System.exit(0);
+ } catch (InvalidAlgorithmParameterException exUnwrapInvalidAlgorithm) {
+ log("ERROR: Unwrapping key data - "
+ + "InvalidAlgorithmParameterException: '"
+ + exUnwrapInvalidAlgorithm.toString()
+ + "'"
+ + NEWLINE, true);
+ System.exit(0);
+ } catch (IllegalStateException exUnwrapState) {
+ log("ERROR: Unwrapping key data - "
+ + "InvalidStateException: '"
+ + exUnwrapState.toString()
+ + "'"
+ + NEWLINE, true);
+ System.exit(0);
}
// public byte[]
@@ -2021,82 +1899,81 @@ public class DRMTool
try {
// Use "mSourceToken" to get "KeyWrapAlgorithm.RSA"
target_rsaWrap = mSourceToken.getKeyWrapper(
- KeyWrapAlgorithm.RSA );
- target_rsaWrap.initWrap( mWrapPublicKey, null );
- target_session = target_rsaWrap.wrap( sk );
+ KeyWrapAlgorithm.RSA);
+ target_rsaWrap.initWrap(mWrapPublicKey, null);
+ target_session = target_rsaWrap.wrap(sk);
tmp = new DerOutputStream();
out = new DerOutputStream();
- tmp.putOctetString( target_session );
- tmp.putOctetString( pri );
- out.write( DerValue.tag_Sequence, tmp );
+ tmp.putOctetString(target_session);
+ tmp.putOctetString(pri);
+ out.write(DerValue.tag_Sequence, tmp);
rewrappedKeyData = out.toByteArray();
- } catch( NoSuchAlgorithmException exWrapAlgorithm ) {
- log( "ERROR: Wrapping key data - "
- + "NoSuchAlgorithmException: '"
- + exWrapAlgorithm.toString()
- + "'"
- + NEWLINE, true );
- System.exit( 0 );
- } catch( TokenException exWrapToken ) {
- log( "ERROR: Wrapping key data - "
- + "TokenException: '"
- + exWrapToken.toString()
- + "'"
- + NEWLINE, true );
- System.exit( 0 );
- } catch( InvalidKeyException exWrapInvalidKey ) {
- log( "ERROR: Wrapping key data - "
- + "InvalidKeyException: '"
- + exWrapInvalidKey.toString()
- + "'"
- + NEWLINE, true );
- System.exit( 0 );
- } catch( InvalidAlgorithmParameterException exWrapInvalidAlgorithm ) {
- log( "ERROR: Wrapping key data - "
- + "InvalidAlgorithmParameterException: '"
- + exWrapInvalidAlgorithm.toString()
- + "'"
- + NEWLINE, true );
- System.exit( 0 );
- } catch( IllegalStateException exWrapState ) {
- log( "ERROR: Wrapping key data - "
- + "InvalidStateException: '"
- + exWrapState.toString()
- + "'"
- + NEWLINE, true );
- System.exit( 0 );
- } catch( IOException exWrapIO ) {
- log( "ERROR: Wrapping key data - "
- + "IOException: '"
- + exWrapIO.toString()
- + "'"
- + NEWLINE, true );
- System.exit( 0 );
+ } catch (NoSuchAlgorithmException exWrapAlgorithm) {
+ log("ERROR: Wrapping key data - "
+ + "NoSuchAlgorithmException: '"
+ + exWrapAlgorithm.toString()
+ + "'"
+ + NEWLINE, true);
+ System.exit(0);
+ } catch (TokenException exWrapToken) {
+ log("ERROR: Wrapping key data - "
+ + "TokenException: '"
+ + exWrapToken.toString()
+ + "'"
+ + NEWLINE, true);
+ System.exit(0);
+ } catch (InvalidKeyException exWrapInvalidKey) {
+ log("ERROR: Wrapping key data - "
+ + "InvalidKeyException: '"
+ + exWrapInvalidKey.toString()
+ + "'"
+ + NEWLINE, true);
+ System.exit(0);
+ } catch (InvalidAlgorithmParameterException exWrapInvalidAlgorithm) {
+ log("ERROR: Wrapping key data - "
+ + "InvalidAlgorithmParameterException: '"
+ + exWrapInvalidAlgorithm.toString()
+ + "'"
+ + NEWLINE, true);
+ System.exit(0);
+ } catch (IllegalStateException exWrapState) {
+ log("ERROR: Wrapping key data - "
+ + "InvalidStateException: '"
+ + exWrapState.toString()
+ + "'"
+ + NEWLINE, true);
+ System.exit(0);
+ } catch (IOException exWrapIO) {
+ log("ERROR: Wrapping key data - "
+ + "IOException: '"
+ + exWrapIO.toString()
+ + "'"
+ + NEWLINE, true);
+ System.exit(0);
}
return rewrappedKeyData;
}
-
/**
- * Helper method used to remove all EOLs ('\n' and '\r')
- * from the passed in string.
+ * Helper method used to remove all EOLs ('\n' and '\r') from the passed in
+ * string.
* <P>
- *
+ *
* @param data consisting of a string containing EOLs
* @return a string consisting of a string with no EOLs
*/
- private static String stripEOL( String data ) {
+ private static String stripEOL(String data) {
StringBuffer buffer = new StringBuffer();
String revised_data = null;
- for( int i = 0; i < data.length(); i++ ) {
- if( ( data.charAt(i) != '\n' ) &&
- ( data.charAt(i) != '\r' ) ) {
- buffer.append( data.charAt( i ) );
+ for (int i = 0; i < data.length(); i++) {
+ if ((data.charAt(i) != '\n') &&
+ (data.charAt(i) != '\r')) {
+ buffer.append(data.charAt(i));
}
}
@@ -2105,25 +1982,23 @@ public class DRMTool
return revised_data;
}
-
/**
- * Helper method used to format a string containing unformatted data
- * into a string containing formatted data suitable as an entry for
- * an LDIF file.
+ * Helper method used to format a string containing unformatted data into a
+ * string containing formatted data suitable as an entry for an LDIF file.
* <P>
- *
+ *
* @param length the length of the first line of data
* @param data a string containing unformatted data
* @return formatted data consisting of data formatted for an LDIF record
- * suitable for an LDIF file
+ * suitable for an LDIF file
*/
- private static String format_ldif_data( int length, String data ) {
+ private static String format_ldif_data(int length, String data) {
String revised_data = "";
- if( data.length() > length ) {
+ if (data.length() > length) {
// process first line
- for( int i = 0; i < length; i++ ) {
- revised_data += data.charAt( i );
+ for (int i = 0; i < length; i++) {
+ revised_data += data.charAt(i);
}
// terminate first line
@@ -2131,104 +2006,101 @@ public class DRMTool
// process remaining lines
int j = 0;
- for( int i = length; i < data.length(); i++ ) {
- if( j == 0 ) {
+ for (int i = length; i < data.length(); i++) {
+ if (j == 0) {
revised_data += ' ';
}
- revised_data += data.charAt( i );
+ revised_data += data.charAt(i);
j++;
- if( j == 76 ) {
+ if (j == 76) {
revised_data += '\n';
j = 0;
}
}
}
- return revised_data.replaceAll( "\\s+$", "" );
+ return revised_data.replaceAll("\\s+$", "");
}
-
/*********************/
/* ID Offset Methods */
/*********************/
/**
- * Helper method which converts an "indexed" BigInteger into
- * its String representation.
- *
+ * Helper method which converts an "indexed" BigInteger into its String
+ * representation.
+ *
* <PRE>
- *
+ *
* NOTE: Indexed data means that the numeric data
* is stored with a prepended length
* (e. g. - record '73' is stored as '0273').
- *
+ *
* Indexed data is currently limited to '99' digits
* (an index of '00' is invalid). See
* 'com.netscape.cmscore.dbs.BigIntegerMapper.java'
* for details.
- *
+ *
* </PRE>
- *
+ *
* This method is based upon code from
* 'com.netscape.cmscore.dbs.BigIntegerMapper'.
* <P>
- *
+ *
* @param i an "indexed " BigInteger
* @return the string representation of the "indexed" BigInteger
*/
- private static String BigIntegerToDB( BigInteger i ) {
+ private static String BigIntegerToDB(BigInteger i) {
int len = i.toString().length();
String ret = null;
- if( len < 10 ) {
- ret = "0" + Integer.toString( len ) + i.toString();
+ if (len < 10) {
+ ret = "0" + Integer.toString(len) + i.toString();
} else {
- ret = Integer.toString( len ) + i.toString();
+ ret = Integer.toString(len) + i.toString();
}
return ret;
}
-
/**
- * Helper method which converts the string representation of an
- * "indexed" integer into a BigInteger.
- *
+ * Helper method which converts the string representation of an "indexed"
+ * integer into a BigInteger.
+ *
* <PRE>
* NOTE: Indexed data means that the numeric data
* is stored with a prepended length
* (e. g. - record '73' is stored as '0273').
- *
+ *
* Indexed data is currently limited to '99' digits
* (an index of '00' is invalid). See
* 'com.netscape.cmscore.dbs.BigIntegerMapper.java'
* for details.
* </PRE>
- *
+ *
* This method is based upon code from
* 'com.netscape.cmscore.dbs.BigIntegerMapper'.
* <P>
- *
+ *
* @param i the string representation of the "indexed" integer
* @return an "indexed " BigInteger
*/
- private static BigInteger BigIntegerFromDB( String i ) {
- String s = i.substring( 2 );
+ private static BigInteger BigIntegerFromDB(String i) {
+ String s = i.substring(2);
// possibly check length
- return new BigInteger( s );
+ return new BigInteger(s);
}
-
/**
* This method accepts an "attribute", its "delimiter", a string
- * representation of numeric data, and a flag indicating whether
- * or not the string representation is "indexed".
- *
+ * representation of numeric data, and a flag indicating whether or not the
+ * string representation is "indexed".
+ *
* An "attribute" consists of one of the following values:
- *
+ *
* <PRE>
* DRM_LDIF_CN = "cn:";
* DRM_LDIF_DN_EMBEDDED_CN_DATA = "dn: cn";
@@ -2237,31 +2109,31 @@ public class DRMTool
* DRM_LDIF_EXTDATA_SERIAL_NUMBER = "extdata-serialnumber:";
* DRM_LDIF_REQUEST_ID = "requestId:";
* DRM_LDIF_SERIAL_NO = "serialno:";
- *
- *
+ *
+ *
* NOTE: Indexed data means that the numeric data
* is stored with a prepended length
* (e. g. - record '73' is stored as '0273').
- *
+ *
* Indexed data is currently limited to '99' digits
* (an index of '00' is invalid). See
* 'com.netscape.cmscore.dbs.BigIntegerMapper.java'
* for details.
* </PRE>
- *
+ *
* <P>
- *
+ *
* @param attribute the string representation of the "name"
* @param delimiter the separator between the attribute and its contents
* @param source_line the string containing the "name" and "value"
* @param indexed boolean flag indicating if the "value" is "indexed"
* @return a revised line containing the "name" and "value" with the
- * specified ID offset applied as a "mask" to the "value"
+ * specified ID offset applied as a "mask" to the "value"
*/
- private static String compose_numeric_line( String attribute,
+ private static String compose_numeric_line(String attribute,
String delimiter,
String source_line,
- boolean indexed ) {
+ boolean indexed) {
String target_line = null;
String data = null;
String revised_data = null;
@@ -2269,84 +2141,84 @@ public class DRMTool
// Since both "-append_id_offset" and "-remove_id_offset" are OPTIONAL
// parameters, first check to see if either has been selected
- if( !mAppendIdOffsetFlag &&
- !mRemoveIdOffsetFlag ) {
+ if (!mAppendIdOffsetFlag &&
+ !mRemoveIdOffsetFlag) {
return source_line;
}
try {
// extract the data
- data = source_line.substring( attribute.length() + 1 ).trim();
+ data = source_line.substring(attribute.length() + 1).trim();
// skip values which are non-numeric
- if( !data.matches( "[0-9]++" ) ) {
+ if (!data.matches("[0-9]++")) {
// set the target_line to the unchanged source_line
target_line = source_line;
// log this information
- log( "Skipped changing non-numeric line '"
- + source_line
- + "'."
- + NEWLINE, false );
+ log("Skipped changing non-numeric line '"
+ + source_line
+ + "'."
+ + NEWLINE, false);
} else {
// if indexed, first strip the index from the data
- if( indexed ) {
- // NOTE: Indexed data means that the numeric data
- // is stored with a prepended length
- // (e. g. - record '73' is stored as '0273').
+ if (indexed) {
+ // NOTE: Indexed data means that the numeric data
+ // is stored with a prepended length
+ // (e. g. - record '73' is stored as '0273').
//
- // Indexed data is currently limited to '99' digits
- // (an index of '00' is invalid). See
- // 'com.netscape.cmscore.dbs.BigIntegerMapper.java'
- // for details.
- value = BigIntegerFromDB( data );
+ // Indexed data is currently limited to '99' digits
+ // (an index of '00' is invalid). See
+ // 'com.netscape.cmscore.dbs.BigIntegerMapper.java'
+ // for details.
+ value = BigIntegerFromDB(data);
} else {
- value = new BigInteger( data );
+ value = new BigInteger(data);
}
// compare the specified target ID offset
// with the actual value of the attribute
- if( mAppendIdOffsetFlag ) {
- if( mAppendIdOffset.compareTo( value ) == 1 ) {
+ if (mAppendIdOffsetFlag) {
+ if (mAppendIdOffset.compareTo(value) == 1) {
// add the target ID offset to this value
- if( indexed ) {
+ if (indexed) {
revised_data = BigIntegerToDB(
- value.add( mAppendIdOffset )
+ value.add(mAppendIdOffset)
).toString();
} else {
revised_data = value.add(
- mAppendIdOffset ).toString();
+ mAppendIdOffset).toString();
}
} else {
- log( "ERROR: attribute='"
- + attribute
- + "' is greater than the specified "
- + "append_id_offset='"
- + mAppendIdOffset.toString()
- + "'!"
- + NEWLINE, true );
- System.exit( 0 );
+ log("ERROR: attribute='"
+ + attribute
+ + "' is greater than the specified "
+ + "append_id_offset='"
+ + mAppendIdOffset.toString()
+ + "'!"
+ + NEWLINE, true);
+ System.exit(0);
}
- } else if( mRemoveIdOffsetFlag ) {
- if( mRemoveIdOffset.compareTo( value ) <= 0 ) {
+ } else if (mRemoveIdOffsetFlag) {
+ if (mRemoveIdOffset.compareTo(value) <= 0) {
// subtract the target ID offset to this value
- if( indexed ) {
+ if (indexed) {
revised_data = BigIntegerToDB(
- value.subtract( mRemoveIdOffset )
+ value.subtract(mRemoveIdOffset)
).toString();
} else {
- revised_data = value.subtract( mRemoveIdOffset
+ revised_data = value.subtract(mRemoveIdOffset
).toString();
}
} else {
- log( "ERROR: attribute='"
- + attribute
- + "' is less than the specified "
- + "remove_id_offset='"
- + mRemoveIdOffset.toString()
- + "'!"
- + NEWLINE, true );
- System.exit( 0 );
+ log("ERROR: attribute='"
+ + attribute
+ + "' is less than the specified "
+ + "remove_id_offset='"
+ + mRemoveIdOffset.toString()
+ + "'!"
+ + NEWLINE, true);
+ System.exit(0);
}
}
@@ -2354,35 +2226,34 @@ public class DRMTool
target_line = attribute + delimiter + revised_data;
// log this information
- log( "Changed numeric data '"
- + data
- + "' to '"
- + revised_data
- + "'."
- + NEWLINE, false );
+ log("Changed numeric data '"
+ + data
+ + "' to '"
+ + revised_data
+ + "'."
+ + NEWLINE, false);
}
- } catch( IndexOutOfBoundsException exBounds ) {
- log( "ERROR: source_line='"
- + source_line
- + "' IndexOutOfBoundsException: '"
- + exBounds.toString()
- + "'"
- + NEWLINE, true );
- System.exit( 0 );
- } catch( PatternSyntaxException exPattern ) {
- log( "ERROR: data='"
- + data
- + "' PatternSyntaxException: '"
- + exPattern.toString()
- + "'"
- + NEWLINE, true );
- System.exit( 0 );
+ } catch (IndexOutOfBoundsException exBounds) {
+ log("ERROR: source_line='"
+ + source_line
+ + "' IndexOutOfBoundsException: '"
+ + exBounds.toString()
+ + "'"
+ + NEWLINE, true);
+ System.exit(0);
+ } catch (PatternSyntaxException exPattern) {
+ log("ERROR: data='"
+ + data
+ + "' PatternSyntaxException: '"
+ + exPattern.toString()
+ + "'"
+ + NEWLINE, true);
+ System.exit(0);
}
return target_line;
}
-
/***********************/
/* LDIF Parser Methods */
/***********************/
@@ -2390,189 +2261,187 @@ public class DRMTool
/**
* Helper method which composes the output line for DRM_LDIF_CN.
* <P>
- *
+ *
* @param record_type the string representation of the input record type
* @param line the string representation of the input line
* @return the composed output line
*/
- private static String output_cn( String record_type,
- String line ) {
+ private static String output_cn(String record_type,
+ String line) {
String output = null;
- if( record_type.equals( DRM_LDIF_ENROLLMENT ) ) {
- if( drmtoolCfg.get( DRMTOOL_CFG_ENROLLMENT_CN ) ) {
- output = compose_numeric_line( DRM_LDIF_CN,
+ if (record_type.equals(DRM_LDIF_ENROLLMENT)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_ENROLLMENT_CN)) {
+ output = compose_numeric_line(DRM_LDIF_CN,
SPACE,
line,
- false );
+ false);
} else {
output = line;
}
- } else if( record_type.equals( DRM_LDIF_CA_KEY_RECORD ) ) {
- if( drmtoolCfg.get( DRMTOOL_CFG_CA_KEY_RECORD_CN ) ) {
- output = compose_numeric_line( DRM_LDIF_CN,
+ } else if (record_type.equals(DRM_LDIF_CA_KEY_RECORD)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_CA_KEY_RECORD_CN)) {
+ output = compose_numeric_line(DRM_LDIF_CN,
SPACE,
line,
- false );
+ false);
} else {
output = line;
}
- } else if( record_type.equals( DRM_LDIF_RECOVERY ) ) {
- if( drmtoolCfg.get( DRMTOOL_CFG_RECOVERY_CN ) ) {
- output = compose_numeric_line( DRM_LDIF_CN,
+ } else if (record_type.equals(DRM_LDIF_RECOVERY)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_RECOVERY_CN)) {
+ output = compose_numeric_line(DRM_LDIF_CN,
SPACE,
line,
- false );
+ false);
} else {
output = line;
}
- } else if( record_type.equals( DRM_LDIF_TPS_KEY_RECORD ) ) {
- if( drmtoolCfg.get( DRMTOOL_CFG_TPS_KEY_RECORD_CN ) ) {
- output = compose_numeric_line( DRM_LDIF_CN,
+ } else if (record_type.equals(DRM_LDIF_TPS_KEY_RECORD)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_TPS_KEY_RECORD_CN)) {
+ output = compose_numeric_line(DRM_LDIF_CN,
SPACE,
line,
- false );
+ false);
} else {
output = line;
}
- } else if( record_type.equals( DRM_LDIF_KEYGEN ) ) {
- if( drmtoolCfg.get( DRMTOOL_CFG_KEYGEN_CN ) ) {
- output = compose_numeric_line( DRM_LDIF_CN,
+ } else if (record_type.equals(DRM_LDIF_KEYGEN)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_KEYGEN_CN)) {
+ output = compose_numeric_line(DRM_LDIF_CN,
SPACE,
line,
- false );
+ false);
} else {
output = line;
}
- } else if( record_type.equals( DRM_LDIF_RECORD ) ) {
+ } else if (record_type.equals(DRM_LDIF_RECORD)) {
// Non-Request / Non-Key Record:
- // Pass through the original
- // 'cn' line UNCHANGED
- // so that it is ALWAYS written
+ // Pass through the original
+ // 'cn' line UNCHANGED
+ // so that it is ALWAYS written
output = line;
} else {
- log( "ERROR: Mismatched record field='"
- + DRM_LDIF_CN
- + "' for record type='"
- + record_type
- + "'!"
- + NEWLINE, true );
+ log("ERROR: Mismatched record field='"
+ + DRM_LDIF_CN
+ + "' for record type='"
+ + record_type
+ + "'!"
+ + NEWLINE, true);
}
return output;
}
-
/**
* Helper method which composes the output line for DRM_LDIF_DATE_OF_MODIFY.
* <P>
- *
+ *
* @param record_type the string representation of the input record type
* @param line the string representation of the input line
* @return the composed output line
*/
- private static String output_date_of_modify( String record_type,
- String line ) {
+ private static String output_date_of_modify(String record_type,
+ String line) {
String output = null;
- if( record_type.equals( DRM_LDIF_ENROLLMENT ) ) {
- if( drmtoolCfg.get( DRMTOOL_CFG_ENROLLMENT_DATE_OF_MODIFY ) ) {
+ if (record_type.equals(DRM_LDIF_ENROLLMENT)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_ENROLLMENT_DATE_OF_MODIFY)) {
output = DRM_LDIF_DATE_OF_MODIFY
- + SPACE
- + mDateOfModify;
-
- log( "Changed '"
- + line
- + "' to '"
- + output
- + "'."
- + NEWLINE, false );
+ + SPACE
+ + mDateOfModify;
+
+ log("Changed '"
+ + line
+ + "' to '"
+ + output
+ + "'."
+ + NEWLINE, false);
} else {
output = line;
}
- } else if( record_type.equals( DRM_LDIF_CA_KEY_RECORD ) ) {
- if( drmtoolCfg.get( DRMTOOL_CFG_CA_KEY_RECORD_DATE_OF_MODIFY ) ) {
+ } else if (record_type.equals(DRM_LDIF_CA_KEY_RECORD)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_CA_KEY_RECORD_DATE_OF_MODIFY)) {
output = DRM_LDIF_DATE_OF_MODIFY
- + SPACE
- + mDateOfModify;
-
- log( "Changed '"
- + line
- + "' to '"
- + output
- + "'."
- + NEWLINE, false );
+ + SPACE
+ + mDateOfModify;
+
+ log("Changed '"
+ + line
+ + "' to '"
+ + output
+ + "'."
+ + NEWLINE, false);
} else {
output = line;
}
- } else if( record_type.equals( DRM_LDIF_RECOVERY ) ) {
- if( drmtoolCfg.get( DRMTOOL_CFG_RECOVERY_DATE_OF_MODIFY ) ) {
+ } else if (record_type.equals(DRM_LDIF_RECOVERY)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_RECOVERY_DATE_OF_MODIFY)) {
output = DRM_LDIF_DATE_OF_MODIFY
- + SPACE
- + mDateOfModify;
-
- log( "Changed '"
- + line
- + "' to '"
- + output
- + "'."
- + NEWLINE, false );
+ + SPACE
+ + mDateOfModify;
+
+ log("Changed '"
+ + line
+ + "' to '"
+ + output
+ + "'."
+ + NEWLINE, false);
} else {
output = line;
}
- } else if( record_type.equals( DRM_LDIF_TPS_KEY_RECORD ) ) {
- if( drmtoolCfg.get( DRMTOOL_CFG_TPS_KEY_RECORD_DATE_OF_MODIFY ) ) {
+ } else if (record_type.equals(DRM_LDIF_TPS_KEY_RECORD)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_TPS_KEY_RECORD_DATE_OF_MODIFY)) {
output = DRM_LDIF_DATE_OF_MODIFY
- + SPACE
- + mDateOfModify;
-
- log( "Changed '"
- + line
- + "' to '"
- + output
- + "'."
- + NEWLINE, false );
+ + SPACE
+ + mDateOfModify;
+
+ log("Changed '"
+ + line
+ + "' to '"
+ + output
+ + "'."
+ + NEWLINE, false);
} else {
output = line;
}
- } else if( record_type.equals( DRM_LDIF_KEYGEN ) ) {
- if( drmtoolCfg.get( DRMTOOL_CFG_KEYGEN_DATE_OF_MODIFY ) ) {
+ } else if (record_type.equals(DRM_LDIF_KEYGEN)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_KEYGEN_DATE_OF_MODIFY)) {
output = DRM_LDIF_DATE_OF_MODIFY
- + SPACE
- + mDateOfModify;
-
- log( "Changed '"
- + line
- + "' to '"
- + output
- + "'."
- + NEWLINE, false );
+ + SPACE
+ + mDateOfModify;
+
+ log("Changed '"
+ + line
+ + "' to '"
+ + output
+ + "'."
+ + NEWLINE, false);
} else {
output = line;
}
} else {
- log( "ERROR: Mismatched record field='"
- + DRM_LDIF_DATE_OF_MODIFY
- + "' for record type='"
- + record_type
- + "'!"
- + NEWLINE, true );
+ log("ERROR: Mismatched record field='"
+ + DRM_LDIF_DATE_OF_MODIFY
+ + "' for record type='"
+ + record_type
+ + "'!"
+ + NEWLINE, true);
}
return output;
}
-
/**
* Helper method which composes the output line for DRM_LDIF_DN.
* <P>
- *
+ *
* @param record_type the string representation of the input record type
* @param line the string representation of the input line
* @return the composed output line
*/
- private static String output_dn( String record_type,
- String line ) {
+ private static String output_dn(String record_type,
+ String line) {
String data = null;
String embedded_cn_data[] = null;
String embedded_cn_output = null;
@@ -2580,27 +2449,27 @@ public class DRMTool
String output = null;
try {
- if( record_type.equals( DRM_LDIF_ENROLLMENT ) ) {
- if( drmtoolCfg.get( DRMTOOL_CFG_ENROLLMENT_DN ) ) {
+ if (record_type.equals(DRM_LDIF_ENROLLMENT)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_ENROLLMENT_DN)) {
// First check for an embedded "cn=<value>"
// name-value pair
- if( line.startsWith( DRM_LDIF_DN_EMBEDDED_CN_DATA ) ) {
+ if (line.startsWith(DRM_LDIF_DN_EMBEDDED_CN_DATA)) {
// At this point, always extract
// the embedded "cn=<value>" name-value pair
// which will ALWAYS be the first
// portion of the "dn: " attribute
- embedded_cn_data = line.split( COMMA, 2 );
+ embedded_cn_data = line.split(COMMA, 2);
embedded_cn_output = compose_numeric_line(
DRM_LDIF_DN_EMBEDDED_CN_DATA,
EQUAL_SIGN,
embedded_cn_data[0],
- false );
+ false);
input = embedded_cn_output
- + COMMA
- + embedded_cn_data[1];
+ + COMMA
+ + embedded_cn_data[1];
} else {
input = line;
}
@@ -2609,36 +2478,36 @@ public class DRMTool
// "-target_drm_naming_context" are OPTIONAL
// parameters, ONLY process this portion of the field
// if both of these options have been selected
- if( mDrmNamingContextsFlag ) {
- output = input.replace( mSourceDrmNamingContext,
- mTargetDrmNamingContext );
+ if (mDrmNamingContextsFlag) {
+ output = input.replace(mSourceDrmNamingContext,
+ mTargetDrmNamingContext);
} else {
output = input;
}
} else {
output = line;
}
- } else if( record_type.equals( DRM_LDIF_CA_KEY_RECORD ) ) {
- if( drmtoolCfg.get( DRMTOOL_CFG_CA_KEY_RECORD_DN ) ) {
+ } else if (record_type.equals(DRM_LDIF_CA_KEY_RECORD)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_CA_KEY_RECORD_DN)) {
// First check for an embedded "cn=<value>"
// name-value pair
- if( line.startsWith( DRM_LDIF_DN_EMBEDDED_CN_DATA ) ) {
+ if (line.startsWith(DRM_LDIF_DN_EMBEDDED_CN_DATA)) {
// At this point, always extract
// the embedded "cn=<value>" name-value pair
// which will ALWAYS be the first
// portion of the "dn: " attribute
- embedded_cn_data = line.split( COMMA, 2 );
+ embedded_cn_data = line.split(COMMA, 2);
embedded_cn_output = compose_numeric_line(
DRM_LDIF_DN_EMBEDDED_CN_DATA,
EQUAL_SIGN,
embedded_cn_data[0],
- false );
+ false);
input = embedded_cn_output
- + COMMA
- + embedded_cn_data[1];
+ + COMMA
+ + embedded_cn_data[1];
} else {
input = line;
}
@@ -2647,36 +2516,36 @@ public class DRMTool
// "-target_drm_naming_context" are OPTIONAL
// parameters, ONLY process this portion of the field
// if both of these options have been selected
- if( mDrmNamingContextsFlag ) {
- output = input.replace( mSourceDrmNamingContext,
- mTargetDrmNamingContext );
+ if (mDrmNamingContextsFlag) {
+ output = input.replace(mSourceDrmNamingContext,
+ mTargetDrmNamingContext);
} else {
output = input;
}
} else {
output = line;
}
- } else if( record_type.equals( DRM_LDIF_RECOVERY ) ) {
- if( drmtoolCfg.get( DRMTOOL_CFG_RECOVERY_DN ) ) {
+ } else if (record_type.equals(DRM_LDIF_RECOVERY)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_RECOVERY_DN)) {
// First check for an embedded "cn=<value>"
// name-value pair
- if( line.startsWith( DRM_LDIF_DN_EMBEDDED_CN_DATA ) ) {
+ if (line.startsWith(DRM_LDIF_DN_EMBEDDED_CN_DATA)) {
// At this point, always extract
// the embedded "cn=<value>" name-value pair
// which will ALWAYS be the first
// portion of the "dn: " attribute
- embedded_cn_data = line.split( COMMA, 2 );
+ embedded_cn_data = line.split(COMMA, 2);
embedded_cn_output = compose_numeric_line(
DRM_LDIF_DN_EMBEDDED_CN_DATA,
EQUAL_SIGN,
embedded_cn_data[0],
- false );
+ false);
input = embedded_cn_output
- + COMMA
- + embedded_cn_data[1];
+ + COMMA
+ + embedded_cn_data[1];
} else {
input = line;
}
@@ -2685,36 +2554,36 @@ public class DRMTool
// "-target_drm_naming_context" are OPTIONAL
// parameters, ONLY process this portion of the field
// if both of these options have been selected
- if( mDrmNamingContextsFlag ) {
- output = input.replace( mSourceDrmNamingContext,
- mTargetDrmNamingContext );
+ if (mDrmNamingContextsFlag) {
+ output = input.replace(mSourceDrmNamingContext,
+ mTargetDrmNamingContext);
} else {
output = input;
}
} else {
output = line;
}
- } else if( record_type.equals( DRM_LDIF_TPS_KEY_RECORD ) ) {
- if( drmtoolCfg.get( DRMTOOL_CFG_TPS_KEY_RECORD_DN ) ) {
+ } else if (record_type.equals(DRM_LDIF_TPS_KEY_RECORD)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_TPS_KEY_RECORD_DN)) {
// First check for an embedded "cn=<value>"
// name-value pair
- if( line.startsWith( DRM_LDIF_DN_EMBEDDED_CN_DATA ) ) {
+ if (line.startsWith(DRM_LDIF_DN_EMBEDDED_CN_DATA)) {
// At this point, always extract
// the embedded "cn=<value>" name-value pair
// which will ALWAYS be the first
// portion of the "dn: " attribute
- embedded_cn_data = line.split( COMMA, 2 );
+ embedded_cn_data = line.split(COMMA, 2);
embedded_cn_output = compose_numeric_line(
DRM_LDIF_DN_EMBEDDED_CN_DATA,
EQUAL_SIGN,
embedded_cn_data[0],
- false );
+ false);
input = embedded_cn_output
- + COMMA
- + embedded_cn_data[1];
+ + COMMA
+ + embedded_cn_data[1];
} else {
input = line;
}
@@ -2723,36 +2592,36 @@ public class DRMTool
// "-target_drm_naming_context" are OPTIONAL
// parameters, ONLY process this portion of the field
// if both of these options have been selected
- if( mDrmNamingContextsFlag ) {
- output = input.replace( mSourceDrmNamingContext,
- mTargetDrmNamingContext );
+ if (mDrmNamingContextsFlag) {
+ output = input.replace(mSourceDrmNamingContext,
+ mTargetDrmNamingContext);
} else {
output = input;
}
} else {
output = line;
}
- } else if( record_type.equals( DRM_LDIF_KEYGEN ) ) {
- if( drmtoolCfg.get( DRMTOOL_CFG_KEYGEN_DN ) ) {
+ } else if (record_type.equals(DRM_LDIF_KEYGEN)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_KEYGEN_DN)) {
// First check for an embedded "cn=<value>"
// name-value pair
- if( line.startsWith( DRM_LDIF_DN_EMBEDDED_CN_DATA ) ) {
+ if (line.startsWith(DRM_LDIF_DN_EMBEDDED_CN_DATA)) {
// At this point, always extract
// the embedded "cn=<value>" name-value pair
// which will ALWAYS be the first
// portion of the "dn: " attribute
- embedded_cn_data = line.split( COMMA, 2 );
+ embedded_cn_data = line.split(COMMA, 2);
embedded_cn_output = compose_numeric_line(
DRM_LDIF_DN_EMBEDDED_CN_DATA,
EQUAL_SIGN,
embedded_cn_data[0],
- false );
+ false);
input = embedded_cn_output
- + COMMA
- + embedded_cn_data[1];
+ + COMMA
+ + embedded_cn_data[1];
} else {
input = line;
}
@@ -2761,155 +2630,152 @@ public class DRMTool
// "-target_drm_naming_context" are OPTIONAL
// parameters, ONLY process this portion of the field
// if both of these options have been selected
- if( mDrmNamingContextsFlag ) {
- output = input.replace( mSourceDrmNamingContext,
- mTargetDrmNamingContext );
+ if (mDrmNamingContextsFlag) {
+ output = input.replace(mSourceDrmNamingContext,
+ mTargetDrmNamingContext);
} else {
output = input;
}
} else {
output = line;
}
- } else if( record_type.equals( DRM_LDIF_RECORD ) ) {
+ } else if (record_type.equals(DRM_LDIF_RECORD)) {
// Non-Request / Non-Key Record:
- // Pass through the original
- // 'dn' line UNCHANGED
- // so that it is ALWAYS written
+ // Pass through the original
+ // 'dn' line UNCHANGED
+ // so that it is ALWAYS written
output = line;
} else {
- log( "ERROR: Mismatched record field='"
- + DRM_LDIF_DN
- + "' for record type='"
- + record_type
- + "'!"
- + NEWLINE, true );
+ log("ERROR: Mismatched record field='"
+ + DRM_LDIF_DN
+ + "' for record type='"
+ + record_type
+ + "'!"
+ + NEWLINE, true);
}
- } catch( PatternSyntaxException exDnEmbeddedCnNameValuePattern ) {
- log( "ERROR: line='"
- + line
- + "' PatternSyntaxException: '"
- + exDnEmbeddedCnNameValuePattern.toString()
- + "'"
- + NEWLINE, true );
- } catch( NullPointerException exNullPointerException ) {
- log( "ERROR: Unable to replace source DRM naming context '"
- + mSourceDrmNamingContext
- + "' with target DRM naming context '"
- + mTargetDrmNamingContext
- + "' NullPointerException: '"
- + exNullPointerException.toString()
- + "'"
- + NEWLINE, true );
+ } catch (PatternSyntaxException exDnEmbeddedCnNameValuePattern) {
+ log("ERROR: line='"
+ + line
+ + "' PatternSyntaxException: '"
+ + exDnEmbeddedCnNameValuePattern.toString()
+ + "'"
+ + NEWLINE, true);
+ } catch (NullPointerException exNullPointerException) {
+ log("ERROR: Unable to replace source DRM naming context '"
+ + mSourceDrmNamingContext
+ + "' with target DRM naming context '"
+ + mTargetDrmNamingContext
+ + "' NullPointerException: '"
+ + exNullPointerException.toString()
+ + "'"
+ + NEWLINE, true);
}
return output;
}
-
/**
* Helper method which composes the output line for
* DRM_LDIF_EXTDATA_KEY_RECORD.
* <P>
- *
+ *
* @param record_type the string representation of the input record type
* @param line the string representation of the input line
* @return the composed output line
*/
- private static String output_extdata_key_record( String record_type,
- String line ) {
+ private static String output_extdata_key_record(String record_type,
+ String line) {
String output = null;
- if( record_type.equals( DRM_LDIF_ENROLLMENT ) ) {
- if( drmtoolCfg.get( DRMTOOL_CFG_ENROLLMENT_EXTDATA_KEY_RECORD ) ) {
- output = compose_numeric_line( DRM_LDIF_EXTDATA_KEY_RECORD,
+ if (record_type.equals(DRM_LDIF_ENROLLMENT)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_ENROLLMENT_EXTDATA_KEY_RECORD)) {
+ output = compose_numeric_line(DRM_LDIF_EXTDATA_KEY_RECORD,
SPACE,
line,
- false );
+ false);
} else {
output = line;
}
- } else if( record_type.equals( DRM_LDIF_KEYGEN ) ) {
- if( drmtoolCfg.get( DRMTOOL_CFG_KEYGEN_EXTDATA_KEY_RECORD ) ) {
- output = compose_numeric_line( DRM_LDIF_EXTDATA_KEY_RECORD,
+ } else if (record_type.equals(DRM_LDIF_KEYGEN)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_KEYGEN_EXTDATA_KEY_RECORD)) {
+ output = compose_numeric_line(DRM_LDIF_EXTDATA_KEY_RECORD,
SPACE,
line,
- false );
+ false);
} else {
output = line;
}
} else {
- log( "ERROR: Mismatched record field='"
- + DRM_LDIF_EXTDATA_KEY_RECORD
- + "' for record type='"
- + record_type
- + "'!"
- + NEWLINE, true );
+ log("ERROR: Mismatched record field='"
+ + DRM_LDIF_EXTDATA_KEY_RECORD
+ + "' for record type='"
+ + record_type
+ + "'!"
+ + NEWLINE, true);
}
return output;
}
-
/**
* Helper method which composes the output line for
* DRM_LDIF_EXTDATA_REQUEST_ID.
* <P>
- *
+ *
* @param record_type the string representation of the input record type
* @param line the string representation of the input line
* @return the composed output line
*/
- private static String output_extdata_request_id( String record_type,
- String line ) {
+ private static String output_extdata_request_id(String record_type,
+ String line) {
String output = null;
- if( record_type.equals( DRM_LDIF_ENROLLMENT ) ) {
+ if (record_type.equals(DRM_LDIF_ENROLLMENT)) {
// ALWAYS pass-through "extdata-requestId" for
// DRM_LDIF_ENROLLMENT records UNCHANGED because the
// value in this field is associated with the issuing CA!
output = line;
- } else if( record_type.equals( DRM_LDIF_RECOVERY ) ) {
- if( drmtoolCfg.get( DRMTOOL_CFG_RECOVERY_EXTDATA_REQUEST_ID ) ) {
- output = compose_numeric_line( DRM_LDIF_EXTDATA_REQUEST_ID,
+ } else if (record_type.equals(DRM_LDIF_RECOVERY)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_RECOVERY_EXTDATA_REQUEST_ID)) {
+ output = compose_numeric_line(DRM_LDIF_EXTDATA_REQUEST_ID,
SPACE,
line,
- false );
+ false);
} else {
output = line;
}
- } else if( record_type.equals( DRM_LDIF_KEYGEN ) ) {
- if( drmtoolCfg.get( DRMTOOL_CFG_KEYGEN_EXTDATA_REQUEST_ID ) ) {
- output = compose_numeric_line( DRM_LDIF_EXTDATA_REQUEST_ID,
+ } else if (record_type.equals(DRM_LDIF_KEYGEN)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_KEYGEN_EXTDATA_REQUEST_ID)) {
+ output = compose_numeric_line(DRM_LDIF_EXTDATA_REQUEST_ID,
SPACE,
line,
- false );
+ false);
} else {
output = line;
}
} else {
- log( "ERROR: Mismatched record field='"
- + DRM_LDIF_EXTDATA_REQUEST_ID
- + "' for record type='"
- + record_type
- + "'!"
- + NEWLINE, true );
+ log("ERROR: Mismatched record field='"
+ + DRM_LDIF_EXTDATA_REQUEST_ID
+ + "' for record type='"
+ + record_type
+ + "'!"
+ + NEWLINE, true);
}
return output;
}
-
/**
* Helper method which composes the output line for
* DRM_LDIF_EXTDATA_REQUEST_NOTES.
* <P>
- *
+ *
* @param record_type the string representation of the input record type
* @param line the string representation of the input line
* @return the composed output line
*/
- private static String output_extdata_request_notes( String record_type,
- String line ) {
+ private static String output_extdata_request_notes(String record_type,
+ String line) {
String input = null;
String data = null;
String unformatted_data = null;
@@ -2917,7 +2783,7 @@ public class DRMTool
String next_line = null;
// extract the data
- if( line.length() > DRM_LDIF_EXTDATA_REQUEST_NOTES.length() ) {
+ if (line.length() > DRM_LDIF_EXTDATA_REQUEST_NOTES.length()) {
input = line.substring(
DRM_LDIF_EXTDATA_REQUEST_NOTES.length() + 1
).trim();
@@ -2927,879 +2793,876 @@ public class DRMTool
).trim();
}
- while( ( line = ldif_record.next() ) != null ) {
- if( line.startsWith( SPACE ) ) {
+ while ((line = ldif_record.next()) != null) {
+ if (line.startsWith(SPACE)) {
// Do NOT use "trim()";
// remove single leading space and
// trailing carriage returns and newlines ONLY!
- input += line.replaceFirst(" ","").replace('\r','\0').replace('\n','\0');
+ input += line.replaceFirst(" ", "").replace('\r', '\0').replace('\n', '\0');
} else {
next_line = line;
break;
}
}
- if( record_type.equals( DRM_LDIF_ENROLLMENT ) ) {
- if(drmtoolCfg.get( DRMTOOL_CFG_ENROLLMENT_EXTDATA_REQUEST_NOTES )) {
+ if (record_type.equals(DRM_LDIF_ENROLLMENT)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_ENROLLMENT_EXTDATA_REQUEST_NOTES)) {
// write out a revised 'extdata-requestnotes' line
- if( mRewrapFlag && mAppendIdOffsetFlag ) {
+ if (mRewrapFlag && mAppendIdOffsetFlag) {
data = input
- + SPACE
- + LEFT_BRACE
- + mDateOfModify
- + RIGHT_BRACE
- + COLON + SPACE
- + DRM_LDIF_REWRAP_MESSAGE
- + mPublicKeySize
- + DRM_LDIF_RSA_MESSAGE
- + mSourcePKISecurityDatabasePwdfileMessage
- + SPACE
- + PLUS + SPACE
- + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE
- + SPACE
- + TIC
- + mAppendIdOffset.toString()
- + TIC
- + mDrmNamingContextMessage
- + mProcessRequestsAndKeyRecordsOnlyMessage;
+ + SPACE
+ + LEFT_BRACE
+ + mDateOfModify
+ + RIGHT_BRACE
+ + COLON + SPACE
+ + DRM_LDIF_REWRAP_MESSAGE
+ + mPublicKeySize
+ + DRM_LDIF_RSA_MESSAGE
+ + mSourcePKISecurityDatabasePwdfileMessage
+ + SPACE
+ + PLUS + SPACE
+ + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE
+ + SPACE
+ + TIC
+ + mAppendIdOffset.toString()
+ + TIC
+ + mDrmNamingContextMessage
+ + mProcessRequestsAndKeyRecordsOnlyMessage;
// Unformat the data
- unformatted_data = stripEOL( data );
+ unformatted_data = stripEOL(data);
// Format the unformatted_data
// to match the desired LDIF format
output = DRM_LDIF_EXTDATA_REQUEST_NOTES
- + SPACE
- + format_ldif_data(
- EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
- unformatted_data );
- } else if( mRewrapFlag && mRemoveIdOffsetFlag ) {
+ + SPACE
+ + format_ldif_data(
+ EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
+ unformatted_data);
+ } else if (mRewrapFlag && mRemoveIdOffsetFlag) {
data = input
- + SPACE
- + LEFT_BRACE
- + mDateOfModify
- + RIGHT_BRACE
- + COLON + SPACE
- + DRM_LDIF_REWRAP_MESSAGE
- + mPublicKeySize
- + DRM_LDIF_RSA_MESSAGE
- + mSourcePKISecurityDatabasePwdfileMessage
- + SPACE
- + PLUS + SPACE
- + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE
- + SPACE
- + TIC
- + mRemoveIdOffset.toString()
- + TIC
- + mDrmNamingContextMessage
- + mProcessRequestsAndKeyRecordsOnlyMessage;
+ + SPACE
+ + LEFT_BRACE
+ + mDateOfModify
+ + RIGHT_BRACE
+ + COLON + SPACE
+ + DRM_LDIF_REWRAP_MESSAGE
+ + mPublicKeySize
+ + DRM_LDIF_RSA_MESSAGE
+ + mSourcePKISecurityDatabasePwdfileMessage
+ + SPACE
+ + PLUS + SPACE
+ + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE
+ + SPACE
+ + TIC
+ + mRemoveIdOffset.toString()
+ + TIC
+ + mDrmNamingContextMessage
+ + mProcessRequestsAndKeyRecordsOnlyMessage;
// Unformat the data
- unformatted_data = stripEOL( data );
+ unformatted_data = stripEOL(data);
// Format the unformatted_data
// to match the desired LDIF format
output = DRM_LDIF_EXTDATA_REQUEST_NOTES
- + SPACE
- + format_ldif_data(
- EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
- unformatted_data );
- } else if( mRewrapFlag ) {
+ + SPACE
+ + format_ldif_data(
+ EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
+ unformatted_data);
+ } else if (mRewrapFlag) {
data = input
- + SPACE
- + LEFT_BRACE
- + mDateOfModify
- + RIGHT_BRACE
- + COLON + SPACE
- + DRM_LDIF_REWRAP_MESSAGE
- + mPublicKeySize
- + DRM_LDIF_RSA_MESSAGE
- + mSourcePKISecurityDatabasePwdfileMessage
- + mDrmNamingContextMessage
- + mProcessRequestsAndKeyRecordsOnlyMessage;
+ + SPACE
+ + LEFT_BRACE
+ + mDateOfModify
+ + RIGHT_BRACE
+ + COLON + SPACE
+ + DRM_LDIF_REWRAP_MESSAGE
+ + mPublicKeySize
+ + DRM_LDIF_RSA_MESSAGE
+ + mSourcePKISecurityDatabasePwdfileMessage
+ + mDrmNamingContextMessage
+ + mProcessRequestsAndKeyRecordsOnlyMessage;
// Unformat the data
- unformatted_data = stripEOL( data );
+ unformatted_data = stripEOL(data);
// Format the unformatted_data
// to match the desired LDIF format
output = DRM_LDIF_EXTDATA_REQUEST_NOTES
- + SPACE
- + format_ldif_data(
- EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
- unformatted_data );
- } else if( mAppendIdOffsetFlag ) {
+ + SPACE
+ + format_ldif_data(
+ EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
+ unformatted_data);
+ } else if (mAppendIdOffsetFlag) {
data = input
- + SPACE
- + LEFT_BRACE
- + mDateOfModify
- + RIGHT_BRACE
- + COLON + SPACE
- + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE
- + SPACE
- + TIC
- + mAppendIdOffset.toString()
- + TIC
- + mDrmNamingContextMessage
- + mProcessRequestsAndKeyRecordsOnlyMessage;
+ + SPACE
+ + LEFT_BRACE
+ + mDateOfModify
+ + RIGHT_BRACE
+ + COLON + SPACE
+ + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE
+ + SPACE
+ + TIC
+ + mAppendIdOffset.toString()
+ + TIC
+ + mDrmNamingContextMessage
+ + mProcessRequestsAndKeyRecordsOnlyMessage;
// Unformat the data
- unformatted_data = stripEOL( data );
+ unformatted_data = stripEOL(data);
// Format the unformatted_data
// to match the desired LDIF format
output = DRM_LDIF_EXTDATA_REQUEST_NOTES
- + SPACE
- + format_ldif_data(
- EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
- unformatted_data );
- } else if( mRemoveIdOffsetFlag ) {
+ + SPACE
+ + format_ldif_data(
+ EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
+ unformatted_data);
+ } else if (mRemoveIdOffsetFlag) {
data = input
- + SPACE
- + LEFT_BRACE
- + mDateOfModify
- + RIGHT_BRACE
- + COLON + SPACE
- + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE
- + SPACE
- + TIC
- + mRemoveIdOffset.toString()
- + TIC
- + mDrmNamingContextMessage
- + mProcessRequestsAndKeyRecordsOnlyMessage;
+ + SPACE
+ + LEFT_BRACE
+ + mDateOfModify
+ + RIGHT_BRACE
+ + COLON + SPACE
+ + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE
+ + SPACE
+ + TIC
+ + mRemoveIdOffset.toString()
+ + TIC
+ + mDrmNamingContextMessage
+ + mProcessRequestsAndKeyRecordsOnlyMessage;
// Unformat the data
- unformatted_data = stripEOL( data );
+ unformatted_data = stripEOL(data);
// Format the unformatted_data
// to match the desired LDIF format
output = DRM_LDIF_EXTDATA_REQUEST_NOTES
- + SPACE
- + format_ldif_data(
- EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
- unformatted_data );
+ + SPACE
+ + format_ldif_data(
+ EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
+ unformatted_data);
}
// log this information
- log( "Changed:"
- + NEWLINE
- + TIC
- + DRM_LDIF_EXTDATA_REQUEST_NOTES
- + SPACE
- + format_ldif_data(
- EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
- input )
- + TIC
- + NEWLINE
- + "--->"
- + NEWLINE
- + TIC
- + output
- + TIC
- + NEWLINE, false );
+ log("Changed:"
+ + NEWLINE
+ + TIC
+ + DRM_LDIF_EXTDATA_REQUEST_NOTES
+ + SPACE
+ + format_ldif_data(
+ EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
+ input)
+ + TIC
+ + NEWLINE
+ + "--->"
+ + NEWLINE
+ + TIC
+ + output
+ + TIC
+ + NEWLINE, false);
} else {
output = line;
}
- } else if( record_type.equals( DRM_LDIF_RECOVERY ) ) {
- if( drmtoolCfg.get( DRMTOOL_CFG_RECOVERY_EXTDATA_REQUEST_NOTES ) ) {
+ } else if (record_type.equals(DRM_LDIF_RECOVERY)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_RECOVERY_EXTDATA_REQUEST_NOTES)) {
// write out a revised 'extdata-requestnotes' line
- if( mRewrapFlag && mAppendIdOffsetFlag ) {
+ if (mRewrapFlag && mAppendIdOffsetFlag) {
data = input
- + SPACE
- + LEFT_BRACE
- + mDateOfModify
- + RIGHT_BRACE
- + COLON + SPACE
- + DRM_LDIF_REWRAP_MESSAGE
- + mPublicKeySize
- + DRM_LDIF_RSA_MESSAGE
- + mSourcePKISecurityDatabasePwdfileMessage
- + SPACE
- + PLUS + SPACE
- + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE
- + SPACE
- + TIC
- + mAppendIdOffset.toString()
- + TIC
- + mDrmNamingContextMessage
- + mProcessRequestsAndKeyRecordsOnlyMessage;
+ + SPACE
+ + LEFT_BRACE
+ + mDateOfModify
+ + RIGHT_BRACE
+ + COLON + SPACE
+ + DRM_LDIF_REWRAP_MESSAGE
+ + mPublicKeySize
+ + DRM_LDIF_RSA_MESSAGE
+ + mSourcePKISecurityDatabasePwdfileMessage
+ + SPACE
+ + PLUS + SPACE
+ + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE
+ + SPACE
+ + TIC
+ + mAppendIdOffset.toString()
+ + TIC
+ + mDrmNamingContextMessage
+ + mProcessRequestsAndKeyRecordsOnlyMessage;
// Unformat the data
- unformatted_data = stripEOL( data );
+ unformatted_data = stripEOL(data);
// Format the unformatted_data
// to match the desired LDIF format
output = DRM_LDIF_EXTDATA_REQUEST_NOTES
- + SPACE
- + format_ldif_data(
- EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
- unformatted_data );
- } else if( mRewrapFlag && mRemoveIdOffsetFlag ) {
+ + SPACE
+ + format_ldif_data(
+ EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
+ unformatted_data);
+ } else if (mRewrapFlag && mRemoveIdOffsetFlag) {
data = input
- + SPACE
- + LEFT_BRACE
- + mDateOfModify
- + RIGHT_BRACE
- + COLON + SPACE
- + DRM_LDIF_REWRAP_MESSAGE
- + mPublicKeySize
- + DRM_LDIF_RSA_MESSAGE
- + mSourcePKISecurityDatabasePwdfileMessage
- + SPACE
- + PLUS + SPACE
- + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE
- + SPACE
- + TIC
- + mRemoveIdOffset.toString()
- + TIC
- + mDrmNamingContextMessage
- + mProcessRequestsAndKeyRecordsOnlyMessage;
+ + SPACE
+ + LEFT_BRACE
+ + mDateOfModify
+ + RIGHT_BRACE
+ + COLON + SPACE
+ + DRM_LDIF_REWRAP_MESSAGE
+ + mPublicKeySize
+ + DRM_LDIF_RSA_MESSAGE
+ + mSourcePKISecurityDatabasePwdfileMessage
+ + SPACE
+ + PLUS + SPACE
+ + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE
+ + SPACE
+ + TIC
+ + mRemoveIdOffset.toString()
+ + TIC
+ + mDrmNamingContextMessage
+ + mProcessRequestsAndKeyRecordsOnlyMessage;
// Unformat the data
- unformatted_data = stripEOL( data );
+ unformatted_data = stripEOL(data);
// Format the unformatted_data
// to match the desired LDIF format
output = DRM_LDIF_EXTDATA_REQUEST_NOTES
- + SPACE
- + format_ldif_data(
- EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
- unformatted_data );
- } else if( mRewrapFlag ) {
+ + SPACE
+ + format_ldif_data(
+ EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
+ unformatted_data);
+ } else if (mRewrapFlag) {
data = input
- + SPACE
- + LEFT_BRACE
- + mDateOfModify
- + RIGHT_BRACE
- + COLON + SPACE
- + DRM_LDIF_REWRAP_MESSAGE
- + mPublicKeySize
- + DRM_LDIF_RSA_MESSAGE
- + mSourcePKISecurityDatabasePwdfileMessage
- + mDrmNamingContextMessage
- + mProcessRequestsAndKeyRecordsOnlyMessage;
+ + SPACE
+ + LEFT_BRACE
+ + mDateOfModify
+ + RIGHT_BRACE
+ + COLON + SPACE
+ + DRM_LDIF_REWRAP_MESSAGE
+ + mPublicKeySize
+ + DRM_LDIF_RSA_MESSAGE
+ + mSourcePKISecurityDatabasePwdfileMessage
+ + mDrmNamingContextMessage
+ + mProcessRequestsAndKeyRecordsOnlyMessage;
// Unformat the data
- unformatted_data = stripEOL( data );
+ unformatted_data = stripEOL(data);
// Format the unformatted_data
// to match the desired LDIF format
output = DRM_LDIF_EXTDATA_REQUEST_NOTES
- + SPACE
- + format_ldif_data(
- EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
- unformatted_data );
- } else if( mAppendIdOffsetFlag ) {
+ + SPACE
+ + format_ldif_data(
+ EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
+ unformatted_data);
+ } else if (mAppendIdOffsetFlag) {
data = input
- + SPACE
- + LEFT_BRACE
- + mDateOfModify
- + RIGHT_BRACE
- + COLON + SPACE
- + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE
- + SPACE
- + TIC
- + mAppendIdOffset.toString()
- + TIC
- + mDrmNamingContextMessage
- + mProcessRequestsAndKeyRecordsOnlyMessage;
+ + SPACE
+ + LEFT_BRACE
+ + mDateOfModify
+ + RIGHT_BRACE
+ + COLON + SPACE
+ + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE
+ + SPACE
+ + TIC
+ + mAppendIdOffset.toString()
+ + TIC
+ + mDrmNamingContextMessage
+ + mProcessRequestsAndKeyRecordsOnlyMessage;
// Unformat the data
- unformatted_data = stripEOL( data );
+ unformatted_data = stripEOL(data);
// Format the unformatted_data
// to match the desired LDIF format
output = DRM_LDIF_EXTDATA_REQUEST_NOTES
- + SPACE
- + format_ldif_data(
- EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
- unformatted_data );
- } else if( mRemoveIdOffsetFlag ) {
+ + SPACE
+ + format_ldif_data(
+ EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
+ unformatted_data);
+ } else if (mRemoveIdOffsetFlag) {
data = input
- + SPACE
- + LEFT_BRACE
- + mDateOfModify
- + RIGHT_BRACE
- + COLON + SPACE
- + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE
- + SPACE
- + TIC
- + mRemoveIdOffset.toString()
- + TIC
- + mDrmNamingContextMessage
- + mProcessRequestsAndKeyRecordsOnlyMessage;
+ + SPACE
+ + LEFT_BRACE
+ + mDateOfModify
+ + RIGHT_BRACE
+ + COLON + SPACE
+ + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE
+ + SPACE
+ + TIC
+ + mRemoveIdOffset.toString()
+ + TIC
+ + mDrmNamingContextMessage
+ + mProcessRequestsAndKeyRecordsOnlyMessage;
// Unformat the data
- unformatted_data = stripEOL( data );
+ unformatted_data = stripEOL(data);
// Format the unformatted_data
// to match the desired LDIF format
output = DRM_LDIF_EXTDATA_REQUEST_NOTES
- + SPACE
- + format_ldif_data(
- EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
- unformatted_data );
+ + SPACE
+ + format_ldif_data(
+ EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
+ unformatted_data);
}
// log this information
- log( "Changed:"
- + NEWLINE
- + TIC
- + DRM_LDIF_EXTDATA_REQUEST_NOTES
- + SPACE
- + format_ldif_data(
- EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
- input )
- + TIC
- + NEWLINE
- + "--->"
- + NEWLINE
- + TIC
- + output
- + TIC
- + NEWLINE, false );
+ log("Changed:"
+ + NEWLINE
+ + TIC
+ + DRM_LDIF_EXTDATA_REQUEST_NOTES
+ + SPACE
+ + format_ldif_data(
+ EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
+ input)
+ + TIC
+ + NEWLINE
+ + "--->"
+ + NEWLINE
+ + TIC
+ + output
+ + TIC
+ + NEWLINE, false);
} else {
output = line;
}
- } else if( record_type.equals( DRM_LDIF_KEYGEN ) ) {
- if( drmtoolCfg.get( DRMTOOL_CFG_KEYGEN_EXTDATA_REQUEST_NOTES ) ) {
+ } else if (record_type.equals(DRM_LDIF_KEYGEN)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_KEYGEN_EXTDATA_REQUEST_NOTES)) {
// write out a revised 'extdata-requestnotes' line
- if( mRewrapFlag && mAppendIdOffsetFlag ) {
+ if (mRewrapFlag && mAppendIdOffsetFlag) {
data = input
- + SPACE
- + LEFT_BRACE
- + mDateOfModify
- + RIGHT_BRACE
- + COLON + SPACE
- + DRM_LDIF_REWRAP_MESSAGE
- + mPublicKeySize
- + DRM_LDIF_RSA_MESSAGE
- + mSourcePKISecurityDatabasePwdfileMessage
- + SPACE
- + PLUS + SPACE
- + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE
- + SPACE
- + TIC
- + mAppendIdOffset.toString()
- + TIC
- + mDrmNamingContextMessage
- + mProcessRequestsAndKeyRecordsOnlyMessage;
+ + SPACE
+ + LEFT_BRACE
+ + mDateOfModify
+ + RIGHT_BRACE
+ + COLON + SPACE
+ + DRM_LDIF_REWRAP_MESSAGE
+ + mPublicKeySize
+ + DRM_LDIF_RSA_MESSAGE
+ + mSourcePKISecurityDatabasePwdfileMessage
+ + SPACE
+ + PLUS + SPACE
+ + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE
+ + SPACE
+ + TIC
+ + mAppendIdOffset.toString()
+ + TIC
+ + mDrmNamingContextMessage
+ + mProcessRequestsAndKeyRecordsOnlyMessage;
// Unformat the data
- unformatted_data = stripEOL( data );
+ unformatted_data = stripEOL(data);
// Format the unformatted_data
// to match the desired LDIF format
output = DRM_LDIF_EXTDATA_REQUEST_NOTES
- + SPACE
- + format_ldif_data(
- EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
- unformatted_data );
- } else if( mRewrapFlag && mRemoveIdOffsetFlag ) {
+ + SPACE
+ + format_ldif_data(
+ EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
+ unformatted_data);
+ } else if (mRewrapFlag && mRemoveIdOffsetFlag) {
data = input
- + SPACE
- + LEFT_BRACE
- + mDateOfModify
- + RIGHT_BRACE
- + COLON + SPACE
- + DRM_LDIF_REWRAP_MESSAGE
- + mPublicKeySize
- + DRM_LDIF_RSA_MESSAGE
- + mSourcePKISecurityDatabasePwdfileMessage
- + SPACE
- + PLUS + SPACE
- + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE
- + SPACE
- + TIC
- + mRemoveIdOffset.toString()
- + TIC
- + mDrmNamingContextMessage
- + mProcessRequestsAndKeyRecordsOnlyMessage;
+ + SPACE
+ + LEFT_BRACE
+ + mDateOfModify
+ + RIGHT_BRACE
+ + COLON + SPACE
+ + DRM_LDIF_REWRAP_MESSAGE
+ + mPublicKeySize
+ + DRM_LDIF_RSA_MESSAGE
+ + mSourcePKISecurityDatabasePwdfileMessage
+ + SPACE
+ + PLUS + SPACE
+ + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE
+ + SPACE
+ + TIC
+ + mRemoveIdOffset.toString()
+ + TIC
+ + mDrmNamingContextMessage
+ + mProcessRequestsAndKeyRecordsOnlyMessage;
// Unformat the data
- unformatted_data = stripEOL( data );
+ unformatted_data = stripEOL(data);
// Format the unformatted_data
// to match the desired LDIF format
output = DRM_LDIF_EXTDATA_REQUEST_NOTES
- + SPACE
- + format_ldif_data(
- EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
- unformatted_data );
- } else if( mRewrapFlag ) {
+ + SPACE
+ + format_ldif_data(
+ EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
+ unformatted_data);
+ } else if (mRewrapFlag) {
data = input
- + SPACE
- + LEFT_BRACE
- + mDateOfModify
- + RIGHT_BRACE
- + COLON + SPACE
- + DRM_LDIF_REWRAP_MESSAGE
- + mPublicKeySize
- + DRM_LDIF_RSA_MESSAGE
- + mSourcePKISecurityDatabasePwdfileMessage
- + mDrmNamingContextMessage
- + mProcessRequestsAndKeyRecordsOnlyMessage;
+ + SPACE
+ + LEFT_BRACE
+ + mDateOfModify
+ + RIGHT_BRACE
+ + COLON + SPACE
+ + DRM_LDIF_REWRAP_MESSAGE
+ + mPublicKeySize
+ + DRM_LDIF_RSA_MESSAGE
+ + mSourcePKISecurityDatabasePwdfileMessage
+ + mDrmNamingContextMessage
+ + mProcessRequestsAndKeyRecordsOnlyMessage;
// Unformat the data
- unformatted_data = stripEOL( data );
+ unformatted_data = stripEOL(data);
// Format the unformatted_data
// to match the desired LDIF format
output = DRM_LDIF_EXTDATA_REQUEST_NOTES
- + SPACE
- + format_ldif_data(
- EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
- unformatted_data );
- } else if( mAppendIdOffsetFlag ) {
+ + SPACE
+ + format_ldif_data(
+ EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
+ unformatted_data);
+ } else if (mAppendIdOffsetFlag) {
data = input
- + SPACE
- + LEFT_BRACE
- + mDateOfModify
- + RIGHT_BRACE
- + COLON + SPACE
- + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE
- + SPACE
- + TIC
- + mAppendIdOffset.toString()
- + TIC
- + mDrmNamingContextMessage
- + mProcessRequestsAndKeyRecordsOnlyMessage;
+ + SPACE
+ + LEFT_BRACE
+ + mDateOfModify
+ + RIGHT_BRACE
+ + COLON + SPACE
+ + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE
+ + SPACE
+ + TIC
+ + mAppendIdOffset.toString()
+ + TIC
+ + mDrmNamingContextMessage
+ + mProcessRequestsAndKeyRecordsOnlyMessage;
// Unformat the data
- unformatted_data = stripEOL( data );
+ unformatted_data = stripEOL(data);
// Format the unformatted_data
// to match the desired LDIF format
output = DRM_LDIF_EXTDATA_REQUEST_NOTES
- + SPACE
- + format_ldif_data(
- EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
- unformatted_data );
- } else if( mRemoveIdOffsetFlag ) {
+ + SPACE
+ + format_ldif_data(
+ EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
+ unformatted_data);
+ } else if (mRemoveIdOffsetFlag) {
data = input
- + SPACE
- + LEFT_BRACE
- + mDateOfModify
- + RIGHT_BRACE
- + COLON + SPACE
- + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE
- + SPACE
- + TIC
- + mRemoveIdOffset.toString()
- + TIC
- + mDrmNamingContextMessage
- + mProcessRequestsAndKeyRecordsOnlyMessage;
+ + SPACE
+ + LEFT_BRACE
+ + mDateOfModify
+ + RIGHT_BRACE
+ + COLON + SPACE
+ + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE
+ + SPACE
+ + TIC
+ + mRemoveIdOffset.toString()
+ + TIC
+ + mDrmNamingContextMessage
+ + mProcessRequestsAndKeyRecordsOnlyMessage;
// Unformat the data
- unformatted_data = stripEOL( data );
+ unformatted_data = stripEOL(data);
// Format the unformatted_data
// to match the desired LDIF format
output = DRM_LDIF_EXTDATA_REQUEST_NOTES
- + SPACE
- + format_ldif_data(
- EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
- unformatted_data );
+ + SPACE
+ + format_ldif_data(
+ EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
+ unformatted_data);
}
// log this information
- log( "Changed:"
- + NEWLINE
- + TIC
- + DRM_LDIF_EXTDATA_REQUEST_NOTES
- + SPACE
- + format_ldif_data(
- EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
- input )
- + TIC
- + NEWLINE
- + "--->"
- + NEWLINE
- + TIC
- + output
- + TIC
- + NEWLINE, false );
+ log("Changed:"
+ + NEWLINE
+ + TIC
+ + DRM_LDIF_EXTDATA_REQUEST_NOTES
+ + SPACE
+ + format_ldif_data(
+ EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
+ input)
+ + TIC
+ + NEWLINE
+ + "--->"
+ + NEWLINE
+ + TIC
+ + output
+ + TIC
+ + NEWLINE, false);
} else {
output = line;
}
} else {
- log( "ERROR: Mismatched record field='"
- + DRM_LDIF_EXTDATA_REQUEST_NOTES
- + "' for record type='"
- + record_type
- + "'!"
- + NEWLINE, true );
+ log("ERROR: Mismatched record field='"
+ + DRM_LDIF_EXTDATA_REQUEST_NOTES
+ + "' for record type='"
+ + record_type
+ + "'!"
+ + NEWLINE, true);
}
- if( output != null ) {
+ if (output != null) {
output += NEWLINE + next_line;
}
return output;
}
-
/**
* Helper method which composes the output line for
* DRM_LDIF_EXTDATA_REQUEST_NOTES.
* <P>
- *
+ *
* @param record_type the string representation of the input record type
* @param previous_line the string representation of the previous input line
* @param writer the PrintWriter used to output this new LDIF line
* @return the composed output line
*/
- private static void create_extdata_request_notes( String record_type,
+ private static void create_extdata_request_notes(String record_type,
String previous_line,
- PrintWriter writer ) {
+ PrintWriter writer) {
String data = null;
String unformatted_data = null;
String output = null;
- if( record_type.equals( DRM_LDIF_RECOVERY ) ) {
- if( drmtoolCfg.get( DRMTOOL_CFG_RECOVERY_EXTDATA_REQUEST_NOTES ) ) {
- if(!previous_line.startsWith( DRM_LDIF_EXTDATA_REQUEST_NOTES)) {
+ if (record_type.equals(DRM_LDIF_RECOVERY)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_RECOVERY_EXTDATA_REQUEST_NOTES)) {
+ if (!previous_line.startsWith(DRM_LDIF_EXTDATA_REQUEST_NOTES)) {
// write out the missing 'extdata-requestnotes' line
- if( mRewrapFlag && mAppendIdOffsetFlag ) {
+ if (mRewrapFlag && mAppendIdOffsetFlag) {
data = LEFT_BRACE
- + mDateOfModify
- + RIGHT_BRACE
- + COLON + SPACE
- + DRM_LDIF_REWRAP_MESSAGE
- + mPublicKeySize
- + DRM_LDIF_RSA_MESSAGE
- + mSourcePKISecurityDatabasePwdfileMessage
- + SPACE
- + PLUS + SPACE
- + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE
- + SPACE
- + TIC
- + mAppendIdOffset.toString()
- + TIC
- + mDrmNamingContextMessage
- + mProcessRequestsAndKeyRecordsOnlyMessage;
+ + mDateOfModify
+ + RIGHT_BRACE
+ + COLON + SPACE
+ + DRM_LDIF_REWRAP_MESSAGE
+ + mPublicKeySize
+ + DRM_LDIF_RSA_MESSAGE
+ + mSourcePKISecurityDatabasePwdfileMessage
+ + SPACE
+ + PLUS + SPACE
+ + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE
+ + SPACE
+ + TIC
+ + mAppendIdOffset.toString()
+ + TIC
+ + mDrmNamingContextMessage
+ + mProcessRequestsAndKeyRecordsOnlyMessage;
// Unformat the data
- unformatted_data = stripEOL( data );
+ unformatted_data = stripEOL(data);
// Format the unformatted_data
// to match the desired LDIF format
output = DRM_LDIF_EXTDATA_REQUEST_NOTES
- + SPACE
- + format_ldif_data(
- EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
- unformatted_data );
- } else if( mRewrapFlag && mRemoveIdOffsetFlag ) {
+ + SPACE
+ + format_ldif_data(
+ EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
+ unformatted_data);
+ } else if (mRewrapFlag && mRemoveIdOffsetFlag) {
data = LEFT_BRACE
- + mDateOfModify
- + RIGHT_BRACE
- + COLON + SPACE
- + DRM_LDIF_REWRAP_MESSAGE
- + mPublicKeySize
- + DRM_LDIF_RSA_MESSAGE
- + mSourcePKISecurityDatabasePwdfileMessage
- + SPACE
- + PLUS + SPACE
- + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE
- + SPACE
- + TIC
- + mRemoveIdOffset.toString()
- + TIC
- + mDrmNamingContextMessage
- + mProcessRequestsAndKeyRecordsOnlyMessage;
+ + mDateOfModify
+ + RIGHT_BRACE
+ + COLON + SPACE
+ + DRM_LDIF_REWRAP_MESSAGE
+ + mPublicKeySize
+ + DRM_LDIF_RSA_MESSAGE
+ + mSourcePKISecurityDatabasePwdfileMessage
+ + SPACE
+ + PLUS + SPACE
+ + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE
+ + SPACE
+ + TIC
+ + mRemoveIdOffset.toString()
+ + TIC
+ + mDrmNamingContextMessage
+ + mProcessRequestsAndKeyRecordsOnlyMessage;
// Unformat the data
- unformatted_data = stripEOL( data );
+ unformatted_data = stripEOL(data);
// Format the unformatted_data
// to match the desired LDIF format
output = DRM_LDIF_EXTDATA_REQUEST_NOTES
- + SPACE
- + format_ldif_data(
- EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
- unformatted_data );
- } else if( mRewrapFlag ) {
+ + SPACE
+ + format_ldif_data(
+ EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
+ unformatted_data);
+ } else if (mRewrapFlag) {
data = LEFT_BRACE
- + mDateOfModify
- + RIGHT_BRACE
- + COLON + SPACE
- + DRM_LDIF_REWRAP_MESSAGE
- + mPublicKeySize
- + DRM_LDIF_RSA_MESSAGE
- + mSourcePKISecurityDatabasePwdfileMessage
- + mDrmNamingContextMessage
- + mProcessRequestsAndKeyRecordsOnlyMessage;
+ + mDateOfModify
+ + RIGHT_BRACE
+ + COLON + SPACE
+ + DRM_LDIF_REWRAP_MESSAGE
+ + mPublicKeySize
+ + DRM_LDIF_RSA_MESSAGE
+ + mSourcePKISecurityDatabasePwdfileMessage
+ + mDrmNamingContextMessage
+ + mProcessRequestsAndKeyRecordsOnlyMessage;
// Unformat the data
- unformatted_data = stripEOL( data );
+ unformatted_data = stripEOL(data);
// Format the unformatted_data
// to match the desired LDIF format
output = DRM_LDIF_EXTDATA_REQUEST_NOTES
- + SPACE
- + format_ldif_data(
- EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
- unformatted_data );
- } else if( mAppendIdOffsetFlag ) {
+ + SPACE
+ + format_ldif_data(
+ EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
+ unformatted_data);
+ } else if (mAppendIdOffsetFlag) {
data = LEFT_BRACE
- + mDateOfModify
- + RIGHT_BRACE
- + COLON + SPACE
- + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE
- + SPACE
- + TIC
- + mAppendIdOffset.toString()
- + TIC
- + mDrmNamingContextMessage
- + mProcessRequestsAndKeyRecordsOnlyMessage;
+ + mDateOfModify
+ + RIGHT_BRACE
+ + COLON + SPACE
+ + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE
+ + SPACE
+ + TIC
+ + mAppendIdOffset.toString()
+ + TIC
+ + mDrmNamingContextMessage
+ + mProcessRequestsAndKeyRecordsOnlyMessage;
// Unformat the data
- unformatted_data = stripEOL( data );
+ unformatted_data = stripEOL(data);
// Format the unformatted_data
// to match the desired LDIF format
output = DRM_LDIF_EXTDATA_REQUEST_NOTES
- + SPACE
- + format_ldif_data(
- EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
- unformatted_data );
- } else if( mRemoveIdOffsetFlag ) {
+ + SPACE
+ + format_ldif_data(
+ EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
+ unformatted_data);
+ } else if (mRemoveIdOffsetFlag) {
data = LEFT_BRACE
- + mDateOfModify
- + RIGHT_BRACE
- + COLON + SPACE
- + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE
- + SPACE
- + TIC
- + mRemoveIdOffset.toString()
- + TIC
- + mDrmNamingContextMessage
- + mProcessRequestsAndKeyRecordsOnlyMessage;
+ + mDateOfModify
+ + RIGHT_BRACE
+ + COLON + SPACE
+ + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE
+ + SPACE
+ + TIC
+ + mRemoveIdOffset.toString()
+ + TIC
+ + mDrmNamingContextMessage
+ + mProcessRequestsAndKeyRecordsOnlyMessage;
// Unformat the data
- unformatted_data = stripEOL( data );
+ unformatted_data = stripEOL(data);
// Format the unformatted_data
// to match the desired LDIF format
output = DRM_LDIF_EXTDATA_REQUEST_NOTES
- + SPACE
- + format_ldif_data(
- EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
- unformatted_data );
+ + SPACE
+ + format_ldif_data(
+ EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
+ unformatted_data);
}
// log this information
- log( "Created:"
- + NEWLINE
- + TIC
- + output
- + TIC
- + NEWLINE, false );
+ log("Created:"
+ + NEWLINE
+ + TIC
+ + output
+ + TIC
+ + NEWLINE, false);
// Write out this revised line
// and flush the buffer
- writer.write( output + NEWLINE );
+ writer.write(output + NEWLINE);
writer.flush();
- System.out.print( "." );
+ System.out.print(".");
}
}
- } else if( record_type.equals( DRM_LDIF_KEYGEN ) ) {
- if( drmtoolCfg.get( DRMTOOL_CFG_KEYGEN_EXTDATA_REQUEST_NOTES ) ) {
- if(!previous_line.startsWith( DRM_LDIF_EXTDATA_REQUEST_NOTES)) {
+ } else if (record_type.equals(DRM_LDIF_KEYGEN)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_KEYGEN_EXTDATA_REQUEST_NOTES)) {
+ if (!previous_line.startsWith(DRM_LDIF_EXTDATA_REQUEST_NOTES)) {
// write out the missing 'extdata-requestnotes' line
- if( mRewrapFlag && mAppendIdOffsetFlag ) {
+ if (mRewrapFlag && mAppendIdOffsetFlag) {
data = LEFT_BRACE
- + mDateOfModify
- + RIGHT_BRACE
- + COLON + SPACE
- + DRM_LDIF_REWRAP_MESSAGE
- + mPublicKeySize
- + DRM_LDIF_RSA_MESSAGE
- + mSourcePKISecurityDatabasePwdfileMessage
- + SPACE
- + PLUS + SPACE
- + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE
- + SPACE
- + TIC
- + mAppendIdOffset.toString()
- + TIC
- + mDrmNamingContextMessage
- + mProcessRequestsAndKeyRecordsOnlyMessage;
+ + mDateOfModify
+ + RIGHT_BRACE
+ + COLON + SPACE
+ + DRM_LDIF_REWRAP_MESSAGE
+ + mPublicKeySize
+ + DRM_LDIF_RSA_MESSAGE
+ + mSourcePKISecurityDatabasePwdfileMessage
+ + SPACE
+ + PLUS + SPACE
+ + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE
+ + SPACE
+ + TIC
+ + mAppendIdOffset.toString()
+ + TIC
+ + mDrmNamingContextMessage
+ + mProcessRequestsAndKeyRecordsOnlyMessage;
// Unformat the data
- unformatted_data = stripEOL( data );
+ unformatted_data = stripEOL(data);
// Format the unformatted_data
// to match the desired LDIF format
output = DRM_LDIF_EXTDATA_REQUEST_NOTES
- + SPACE
- + format_ldif_data(
- EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
- unformatted_data );
- } else if( mRewrapFlag && mRemoveIdOffsetFlag ) {
+ + SPACE
+ + format_ldif_data(
+ EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
+ unformatted_data);
+ } else if (mRewrapFlag && mRemoveIdOffsetFlag) {
data = LEFT_BRACE
- + mDateOfModify
- + RIGHT_BRACE
- + COLON + SPACE
- + DRM_LDIF_REWRAP_MESSAGE
- + mPublicKeySize
- + DRM_LDIF_RSA_MESSAGE
- + mSourcePKISecurityDatabasePwdfileMessage
- + SPACE
- + PLUS + SPACE
- + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE
- + SPACE
- + TIC
- + mRemoveIdOffset.toString()
- + TIC
- + mDrmNamingContextMessage
- + mProcessRequestsAndKeyRecordsOnlyMessage;
+ + mDateOfModify
+ + RIGHT_BRACE
+ + COLON + SPACE
+ + DRM_LDIF_REWRAP_MESSAGE
+ + mPublicKeySize
+ + DRM_LDIF_RSA_MESSAGE
+ + mSourcePKISecurityDatabasePwdfileMessage
+ + SPACE
+ + PLUS + SPACE
+ + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE
+ + SPACE
+ + TIC
+ + mRemoveIdOffset.toString()
+ + TIC
+ + mDrmNamingContextMessage
+ + mProcessRequestsAndKeyRecordsOnlyMessage;
// Unformat the data
- unformatted_data = stripEOL( data );
+ unformatted_data = stripEOL(data);
// Format the unformatted_data
// to match the desired LDIF format
output = DRM_LDIF_EXTDATA_REQUEST_NOTES
- + SPACE
- + format_ldif_data(
- EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
- unformatted_data );
- } else if( mRewrapFlag ) {
+ + SPACE
+ + format_ldif_data(
+ EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
+ unformatted_data);
+ } else if (mRewrapFlag) {
data = LEFT_BRACE
- + mDateOfModify
- + RIGHT_BRACE
- + COLON + SPACE
- + DRM_LDIF_REWRAP_MESSAGE
- + mPublicKeySize
- + DRM_LDIF_RSA_MESSAGE
- + mSourcePKISecurityDatabasePwdfileMessage
- + mDrmNamingContextMessage
- + mProcessRequestsAndKeyRecordsOnlyMessage;
+ + mDateOfModify
+ + RIGHT_BRACE
+ + COLON + SPACE
+ + DRM_LDIF_REWRAP_MESSAGE
+ + mPublicKeySize
+ + DRM_LDIF_RSA_MESSAGE
+ + mSourcePKISecurityDatabasePwdfileMessage
+ + mDrmNamingContextMessage
+ + mProcessRequestsAndKeyRecordsOnlyMessage;
// Unformat the data
- unformatted_data = stripEOL( data );
+ unformatted_data = stripEOL(data);
// Format the unformatted_data
// to match the desired LDIF format
output = DRM_LDIF_EXTDATA_REQUEST_NOTES
- + SPACE
- + format_ldif_data(
- EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
- unformatted_data );
- } else if( mAppendIdOffsetFlag ) {
+ + SPACE
+ + format_ldif_data(
+ EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
+ unformatted_data);
+ } else if (mAppendIdOffsetFlag) {
data = LEFT_BRACE
- + mDateOfModify
- + RIGHT_BRACE
- + COLON + SPACE
- + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE
- + SPACE
- + TIC
- + mAppendIdOffset.toString()
- + TIC
- + mDrmNamingContextMessage
- + mProcessRequestsAndKeyRecordsOnlyMessage;
+ + mDateOfModify
+ + RIGHT_BRACE
+ + COLON + SPACE
+ + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE
+ + SPACE
+ + TIC
+ + mAppendIdOffset.toString()
+ + TIC
+ + mDrmNamingContextMessage
+ + mProcessRequestsAndKeyRecordsOnlyMessage;
// Unformat the data
- unformatted_data = stripEOL( data );
+ unformatted_data = stripEOL(data);
// Format the unformatted_data
// to match the desired LDIF format
output = DRM_LDIF_EXTDATA_REQUEST_NOTES
- + SPACE
- + format_ldif_data(
- EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
- unformatted_data );
- } else if( mRemoveIdOffsetFlag ) {
+ + SPACE
+ + format_ldif_data(
+ EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
+ unformatted_data);
+ } else if (mRemoveIdOffsetFlag) {
data = LEFT_BRACE
- + mDateOfModify
- + RIGHT_BRACE
- + COLON + SPACE
- + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE
- + SPACE
- + TIC
- + mRemoveIdOffset.toString()
- + TIC
- + mDrmNamingContextMessage
- + mProcessRequestsAndKeyRecordsOnlyMessage;
+ + mDateOfModify
+ + RIGHT_BRACE
+ + COLON + SPACE
+ + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE
+ + SPACE
+ + TIC
+ + mRemoveIdOffset.toString()
+ + TIC
+ + mDrmNamingContextMessage
+ + mProcessRequestsAndKeyRecordsOnlyMessage;
// Unformat the data
- unformatted_data = stripEOL( data );
+ unformatted_data = stripEOL(data);
// Format the unformatted_data
// to match the desired LDIF format
output = DRM_LDIF_EXTDATA_REQUEST_NOTES
- + SPACE
- + format_ldif_data(
- EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
- unformatted_data );
+ + SPACE
+ + format_ldif_data(
+ EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH,
+ unformatted_data);
}
// log this information
- log( "Created:"
- + NEWLINE
- + TIC
- + output
- + TIC
- + NEWLINE, false );
+ log("Created:"
+ + NEWLINE
+ + TIC
+ + output
+ + TIC
+ + NEWLINE, false);
// Write out this revised line
// and flush the buffer
- writer.write( output + NEWLINE );
+ writer.write(output + NEWLINE);
writer.flush();
- System.out.print( "." );
+ System.out.print(".");
}
}
}
}
-
/**
* Helper method which composes the output line for
* DRM_LDIF_EXTDATA_SERIAL_NUMBER.
* <P>
- *
+ *
* @param record_type the string representation of the input record type
* @param line the string representation of the input line
* @return the composed output line
*/
- private static String output_extdata_serial_number( String record_type,
- String line ) {
+ private static String output_extdata_serial_number(String record_type,
+ String line) {
String output = null;
- if( record_type.equals( DRM_LDIF_RECOVERY ) ) {
- if( drmtoolCfg.get( DRMTOOL_CFG_RECOVERY_EXTDATA_SERIAL_NUMBER ) ) {
- output = compose_numeric_line( DRM_LDIF_EXTDATA_SERIAL_NUMBER,
+ if (record_type.equals(DRM_LDIF_RECOVERY)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_RECOVERY_EXTDATA_SERIAL_NUMBER)) {
+ output = compose_numeric_line(DRM_LDIF_EXTDATA_SERIAL_NUMBER,
SPACE,
line,
- false );
+ false);
} else {
output = line;
}
} else {
- log( "ERROR: Mismatched record field='"
- + DRM_LDIF_EXTDATA_SERIAL_NUMBER
- + "' for record type='"
- + record_type
- + "'!"
- + NEWLINE, true );
+ log("ERROR: Mismatched record field='"
+ + DRM_LDIF_EXTDATA_SERIAL_NUMBER
+ + "' for record type='"
+ + record_type
+ + "'!"
+ + NEWLINE, true);
}
return output;
}
-
/**
* Helper method which composes the output line for
* DRM_LDIF_PRIVATE_KEY_DATA.
* <P>
- *
+ *
* @param record_type the string representation of the input record type
* @param line the string representation of the input line
* @return the composed output line
*/
- private static String output_private_key_data( String record_type,
- String line ) {
+ private static String output_private_key_data(String record_type,
+ String line) {
byte source_wrappedKeyData[] = null;
byte target_wrappedKeyData[] = null;
String data = null;
@@ -3809,22 +3672,22 @@ public class DRMTool
String output = null;
try {
- if( record_type.equals( DRM_LDIF_CA_KEY_RECORD ) ) {
- if(drmtoolCfg.get(DRMTOOL_CFG_CA_KEY_RECORD_PRIVATE_KEY_DATA)) {
+ if (record_type.equals(DRM_LDIF_CA_KEY_RECORD)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_CA_KEY_RECORD_PRIVATE_KEY_DATA)) {
// Since "-source_pki_security_database_path",
// "-source_storage_token_name",
// "-source_storage_certificate_nickname", and
// "-target_storage_certificate_file" are OPTIONAL
// parameters, ONLY process this field if all of
// these options have been selected
- if( mRewrapFlag ) {
+ if (mRewrapFlag) {
// extract the data
data = line.substring(
DRM_LDIF_PRIVATE_KEY_DATA.length() + 1
- ).trim();
+ ).trim();
- while( ( line = ldif_record.next() ) != null ) {
- if( line.startsWith( SPACE ) ) {
+ while ((line = ldif_record.next()) != null) {
+ if (line.startsWith(SPACE)) {
data += line.trim();
} else {
break;
@@ -3835,70 +3698,70 @@ public class DRMTool
// enclosed in the String() object
// into a BINARY BASE 64 byte[] object
source_wrappedKeyData =
- com.netscape.osutil.OSUtil.AtoB( data );
+ com.netscape.osutil.OSUtil.AtoB(data);
// rewrap the source wrapped private key data
target_wrappedKeyData = rewrap_wrapped_key_data(
- source_wrappedKeyData );
+ source_wrappedKeyData);
// Encode the BINARY BASE 64 byte[] object
// into an ASCII BASE 64 certificate
// enclosed in a String() object
revised_data = com.netscape.osutil.OSUtil.BtoA(
- target_wrappedKeyData );
+ target_wrappedKeyData);
// Unformat the ASCII BASE 64 certificate
// for the log file
- unformatted_data = stripEOL( revised_data );
+ unformatted_data = stripEOL(revised_data);
// Format the ASCII BASE 64 certificate
// to match the desired LDIF format
formatted_data = format_ldif_data(
- PRIVATE_KEY_DATA_FIRST_LINE_DATA_LENGTH,
- unformatted_data );
+ PRIVATE_KEY_DATA_FIRST_LINE_DATA_LENGTH,
+ unformatted_data);
// construct a revised 'privateKeyData' line
output = DRM_LDIF_PRIVATE_KEY_DATA
- + SPACE
- + formatted_data
- + NEWLINE
- + line;
+ + SPACE
+ + formatted_data
+ + NEWLINE
+ + line;
// log this information
- log( "Changed 'privateKeyData' from:"
- + NEWLINE
- + TIC
- + data
- + TIC
- + NEWLINE
- + " to:"
- + NEWLINE
- + TIC
- + unformatted_data
- + TIC
- + NEWLINE, false );
+ log("Changed 'privateKeyData' from:"
+ + NEWLINE
+ + TIC
+ + data
+ + TIC
+ + NEWLINE
+ + " to:"
+ + NEWLINE
+ + TIC
+ + unformatted_data
+ + TIC
+ + NEWLINE, false);
} else {
output = line;
}
} else {
output = line;
}
- } else if( record_type.equals( DRM_LDIF_TPS_KEY_RECORD ) ) {
- if(drmtoolCfg.get(DRMTOOL_CFG_TPS_KEY_RECORD_PRIVATE_KEY_DATA)){
+ } else if (record_type.equals(DRM_LDIF_TPS_KEY_RECORD)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_TPS_KEY_RECORD_PRIVATE_KEY_DATA)) {
// Since "-source_pki_security_database_path",
// "-source_storage_token_name",
// "-source_storage_certificate_nickname", and
// "-target_storage_certificate_file" are OPTIONAL
// parameters, ONLY process this field if all of
// these options have been selected
- if( mRewrapFlag ) {
+ if (mRewrapFlag) {
// extract the data
data = line.substring(
DRM_LDIF_PRIVATE_KEY_DATA.length() + 1
- ).trim();
+ ).trim();
- while( ( line = ldif_record.next() ) != null ) {
- if( line.startsWith( SPACE ) ) {
+ while ((line = ldif_record.next()) != null) {
+ if (line.startsWith(SPACE)) {
data += line.trim();
} else {
break;
@@ -3909,48 +3772,48 @@ public class DRMTool
// enclosed in the String() object
// into a BINARY BASE 64 byte[] object
source_wrappedKeyData =
- com.netscape.osutil.OSUtil.AtoB( data );
+ com.netscape.osutil.OSUtil.AtoB(data);
// rewrap the source wrapped private key data
target_wrappedKeyData = rewrap_wrapped_key_data(
- source_wrappedKeyData );
+ source_wrappedKeyData);
// Encode the BINARY BASE 64 byte[] object
// into an ASCII BASE 64 certificate
// enclosed in a String() object
revised_data = com.netscape.osutil.OSUtil.BtoA(
- target_wrappedKeyData );
+ target_wrappedKeyData);
// Unformat the ASCII BASE 64 certificate
// for the log file
- unformatted_data = stripEOL( revised_data );
+ unformatted_data = stripEOL(revised_data);
// Format the ASCII BASE 64 certificate
// to match the desired LDIF format
formatted_data = format_ldif_data(
- PRIVATE_KEY_DATA_FIRST_LINE_DATA_LENGTH,
- unformatted_data );
+ PRIVATE_KEY_DATA_FIRST_LINE_DATA_LENGTH,
+ unformatted_data);
// construct a revised 'privateKeyData' line
output = DRM_LDIF_PRIVATE_KEY_DATA
- + SPACE
- + formatted_data
- + NEWLINE
- + line;
+ + SPACE
+ + formatted_data
+ + NEWLINE
+ + line;
// log this information
- log( "Changed 'privateKeyData' from:"
- + NEWLINE
- + TIC
- + data
- + TIC
- + NEWLINE
- + " to:"
- + NEWLINE
- + TIC
- + unformatted_data
- + TIC
- + NEWLINE, false );
+ log("Changed 'privateKeyData' from:"
+ + NEWLINE
+ + TIC
+ + data
+ + TIC
+ + NEWLINE
+ + " to:"
+ + NEWLINE
+ + TIC
+ + unformatted_data
+ + TIC
+ + NEWLINE, false);
} else {
output = line;
}
@@ -3958,229 +3821,224 @@ public class DRMTool
output = line;
}
} else {
- log( "ERROR: Mismatched record field='"
- + DRM_LDIF_PRIVATE_KEY_DATA
- + "' for record type='"
- + record_type
- + "'!"
- + NEWLINE, true );
+ log("ERROR: Mismatched record field='"
+ + DRM_LDIF_PRIVATE_KEY_DATA
+ + "' for record type='"
+ + record_type
+ + "'!"
+ + NEWLINE, true);
}
- } catch( Exception exRewrap ) {
- log( "ERROR: Unable to rewrap BINARY BASE 64 data. "
- + "Exception: '"
- + exRewrap.toString()
- + "'"
- + NEWLINE, true );
+ } catch (Exception exRewrap) {
+ log("ERROR: Unable to rewrap BINARY BASE 64 data. "
+ + "Exception: '"
+ + exRewrap.toString()
+ + "'"
+ + NEWLINE, true);
}
return output;
}
-
/**
* Helper method which composes the output line for DRM_LDIF_REQUEST_ID.
* <P>
- *
+ *
* @param record_type the string representation of the input record type
* @param line the string representation of the input line
* @return the composed output line
*/
- private static String output_request_id( String record_type,
- String line ) {
+ private static String output_request_id(String record_type,
+ String line) {
String output = null;
- if( record_type.equals( DRM_LDIF_ENROLLMENT ) ) {
- if( drmtoolCfg.get( DRMTOOL_CFG_ENROLLMENT_REQUEST_ID ) ) {
- output = compose_numeric_line( DRM_LDIF_REQUEST_ID,
+ if (record_type.equals(DRM_LDIF_ENROLLMENT)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_ENROLLMENT_REQUEST_ID)) {
+ output = compose_numeric_line(DRM_LDIF_REQUEST_ID,
SPACE,
line,
- true );
+ true);
} else {
output = line;
}
- } else if( record_type.equals( DRM_LDIF_RECOVERY ) ) {
- if( drmtoolCfg.get( DRMTOOL_CFG_RECOVERY_REQUEST_ID ) ) {
- output = compose_numeric_line( DRM_LDIF_REQUEST_ID,
+ } else if (record_type.equals(DRM_LDIF_RECOVERY)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_RECOVERY_REQUEST_ID)) {
+ output = compose_numeric_line(DRM_LDIF_REQUEST_ID,
SPACE,
line,
- true );
+ true);
} else {
output = line;
}
- } else if( record_type.equals( DRM_LDIF_KEYGEN ) ) {
- if( drmtoolCfg.get( DRMTOOL_CFG_KEYGEN_REQUEST_ID ) ) {
- output = compose_numeric_line( DRM_LDIF_REQUEST_ID,
+ } else if (record_type.equals(DRM_LDIF_KEYGEN)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_KEYGEN_REQUEST_ID)) {
+ output = compose_numeric_line(DRM_LDIF_REQUEST_ID,
SPACE,
line,
- true );
+ true);
} else {
output = line;
}
} else {
- log( "ERROR: Mismatched record field='"
- + DRM_LDIF_REQUEST_ID
- + "' for record type='"
- + record_type
- + "'!"
- + NEWLINE, true );
+ log("ERROR: Mismatched record field='"
+ + DRM_LDIF_REQUEST_ID
+ + "' for record type='"
+ + record_type
+ + "'!"
+ + NEWLINE, true);
}
return output;
}
-
/**
* Helper method which composes the output line for DRM_LDIF_SERIAL_NO.
* <P>
- *
+ *
* @param record_type the string representation of the input record type
* @param line the string representation of the input line
* @return the composed output line
*/
- private static String output_serial_no( String record_type,
- String line ) {
+ private static String output_serial_no(String record_type,
+ String line) {
String output = null;
- if( record_type.equals( DRM_LDIF_CA_KEY_RECORD ) ) {
- if( drmtoolCfg.get( DRMTOOL_CFG_CA_KEY_RECORD_SERIAL_NO ) ) {
- output = compose_numeric_line( DRM_LDIF_SERIAL_NO,
+ if (record_type.equals(DRM_LDIF_CA_KEY_RECORD)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_CA_KEY_RECORD_SERIAL_NO)) {
+ output = compose_numeric_line(DRM_LDIF_SERIAL_NO,
SPACE,
line,
- true );
+ true);
} else {
output = line;
}
- } else if( record_type.equals( DRM_LDIF_TPS_KEY_RECORD ) ) {
- if( drmtoolCfg.get( DRMTOOL_CFG_TPS_KEY_RECORD_SERIAL_NO ) ) {
- output = compose_numeric_line( DRM_LDIF_SERIAL_NO,
+ } else if (record_type.equals(DRM_LDIF_TPS_KEY_RECORD)) {
+ if (drmtoolCfg.get(DRMTOOL_CFG_TPS_KEY_RECORD_SERIAL_NO)) {
+ output = compose_numeric_line(DRM_LDIF_SERIAL_NO,
SPACE,
line,
- true );
+ true);
} else {
output = line;
}
- } else if( record_type.equals( DRM_LDIF_RECORD ) ) {
+ } else if (record_type.equals(DRM_LDIF_RECORD)) {
// Non-Request / Non-Key Record:
- // Pass through the original
- // 'serialno' line UNCHANGED
- // so that it is ALWAYS written
+ // Pass through the original
+ // 'serialno' line UNCHANGED
+ // so that it is ALWAYS written
output = line;
} else {
- log( "ERROR: Mismatched record field='"
- + DRM_LDIF_SERIAL_NO
- + "' for record type='"
- + record_type
- + "'!"
- + NEWLINE, true );
+ log("ERROR: Mismatched record field='"
+ + DRM_LDIF_SERIAL_NO
+ + "' for record type='"
+ + record_type
+ + "'!"
+ + NEWLINE, true);
}
return output;
}
-
/**
* Helper method which composes the output line for
* DRM_LDIF_EXTDATA_AUTH_TOKEN_USER.
* <P>
- *
+ *
* @param record_type the string representation of the input record type
* @param line the string representation of the input line
* @return the composed output line
*/
- private static String output_extdata_auth_token_user( String record_type,
- String line ) {
+ private static String output_extdata_auth_token_user(String record_type,
+ String line) {
String data = null;
String output = null;
try {
- if( record_type.equals( DRM_LDIF_ENROLLMENT ) ) {
+ if (record_type.equals(DRM_LDIF_ENROLLMENT)) {
// Since "-source_drm_naming_context", and
// "-target_drm_naming_context" are OPTIONAL
// parameters, ONLY process this field if both of
// these options have been selected
- if( mDrmNamingContextsFlag ) {
- output = line.replace( mSourceDrmNamingContext,
- mTargetDrmNamingContext );
+ if (mDrmNamingContextsFlag) {
+ output = line.replace(mSourceDrmNamingContext,
+ mTargetDrmNamingContext);
} else {
output = line;
}
} else {
- log( "ERROR: Mismatched record field='"
- + DRM_LDIF_EXTDATA_AUTH_TOKEN_USER
- + "' for record type='"
- + record_type
- + "'!"
- + NEWLINE, true );
+ log("ERROR: Mismatched record field='"
+ + DRM_LDIF_EXTDATA_AUTH_TOKEN_USER
+ + "' for record type='"
+ + record_type
+ + "'!"
+ + NEWLINE, true);
}
- } catch( NullPointerException exNullPointerException ) {
- log( "ERROR: Unable to replace source DRM naming context '"
- + mSourceDrmNamingContext
- + "' with target DRM naming context '"
- + mTargetDrmNamingContext
- + "' NullPointerException: '"
- + exNullPointerException.toString()
- + "'"
- + NEWLINE, true );
+ } catch (NullPointerException exNullPointerException) {
+ log("ERROR: Unable to replace source DRM naming context '"
+ + mSourceDrmNamingContext
+ + "' with target DRM naming context '"
+ + mTargetDrmNamingContext
+ + "' NullPointerException: '"
+ + exNullPointerException.toString()
+ + "'"
+ + NEWLINE, true);
}
return output;
}
-
/**
* Helper method which composes the output line for
* DRM_LDIF_EXTDATA_AUTH_TOKEN_USER_DN.
* <P>
- *
+ *
* @param record_type the string representation of the input record type
* @param line the string representation of the input line
* @return the composed output line
*/
- private static String output_extdata_auth_token_user_dn( String record_type,
- String line ) {
+ private static String output_extdata_auth_token_user_dn(String record_type,
+ String line) {
String data = null;
String output = null;
try {
- if( record_type.equals( DRM_LDIF_ENROLLMENT ) ) {
+ if (record_type.equals(DRM_LDIF_ENROLLMENT)) {
// Since "-source_drm_naming_context", and
// "-target_drm_naming_context" are OPTIONAL
// parameters, ONLY process this field if both of
// these options have been selected
- if( mDrmNamingContextsFlag ) {
- output = line.replace( mSourceDrmNamingContext,
- mTargetDrmNamingContext );
+ if (mDrmNamingContextsFlag) {
+ output = line.replace(mSourceDrmNamingContext,
+ mTargetDrmNamingContext);
} else {
output = line;
}
} else {
- log( "ERROR: Mismatched record field='"
- + DRM_LDIF_EXTDATA_AUTH_TOKEN_USER_DN
- + "' for record type='"
- + record_type
- + "'!"
- + NEWLINE, true );
+ log("ERROR: Mismatched record field='"
+ + DRM_LDIF_EXTDATA_AUTH_TOKEN_USER_DN
+ + "' for record type='"
+ + record_type
+ + "'!"
+ + NEWLINE, true);
}
- } catch( NullPointerException exNullPointerException ) {
- log( "ERROR: Unable to replace source DRM naming context '"
- + mSourceDrmNamingContext
- + "' with target DRM naming context '"
- + mTargetDrmNamingContext
- + "' NullPointerException: '"
- + exNullPointerException.toString()
- + "'"
- + NEWLINE, true );
+ } catch (NullPointerException exNullPointerException) {
+ log("ERROR: Unable to replace source DRM naming context '"
+ + mSourceDrmNamingContext
+ + "' with target DRM naming context '"
+ + mTargetDrmNamingContext
+ + "' NullPointerException: '"
+ + exNullPointerException.toString()
+ + "'"
+ + NEWLINE, true);
}
return output;
}
-
/**
- * This method performs the actual parsing of the "source" LDIF file
- * and produces the "target" LDIF file.
+ * This method performs the actual parsing of the "source" LDIF file and
+ * produces the "target" LDIF file.
* <P>
- *
+ *
* @return true if the "target" LDIF file is successfully created
*/
private static boolean convert_source_ldif_to_target_ldif() {
@@ -4194,80 +4052,80 @@ public class DRMTool
String data = null;
String record_type = null;
- if( mRewrapFlag ) {
+ if (mRewrapFlag) {
success = obtain_RSA_rewrapping_keys();
- if( !success ) {
+ if (!success) {
return FAILURE;
}
}
// Create a vector for LDIF input
- record = new Vector<String>( INITIAL_LDIF_RECORD_CAPACITY );
+ record = new Vector<String>(INITIAL_LDIF_RECORD_CAPACITY);
// Process each line in the source LDIF file
// and store it in the target LDIF file
try {
// Open source LDIF file for reading
reader = new BufferedReader(
- new FileReader( mSourceLdifFilename ) );
+ new FileReader(mSourceLdifFilename));
// Open target LDIF file for writing
writer = new PrintWriter(
new BufferedWriter(
- new FileWriter( mTargetLdifFilename ) ) );
+ new FileWriter(mTargetLdifFilename)));
- System.out.print( "PROCESSING: " );
- while( ( input = reader.readLine() ) != null ) {
+ System.out.print("PROCESSING: ");
+ while ((input = reader.readLine()) != null) {
// Read in a record from the source LDIF file and
// add this line of input into the record vector
- success = record.add( input );
- if( !success ) {
+ success = record.add(input);
+ if (!success) {
return FAILURE;
}
// Check for the end of an LDIF record
- if( !input.equals( "" ) ) {
+ if (!input.equals("")) {
// Check to see if input line identifies the record type
- if( input.startsWith( DRM_LDIF_REQUEST_TYPE ) ) {
+ if (input.startsWith(DRM_LDIF_REQUEST_TYPE)) {
// set the record type:
//
- // * DRM_LDIF_ENROLLMENT
- // * DRM_LDIF_KEYGEN
- // * DRM_LDIF_RECOVERY
+ // * DRM_LDIF_ENROLLMENT
+ // * DRM_LDIF_KEYGEN
+ // * DRM_LDIF_RECOVERY
//
record_type = input.substring(
DRM_LDIF_REQUEST_TYPE.length() + 1
).trim();
- if( !record_type.equals( DRM_LDIF_ENROLLMENT ) &&
- !record_type.equals( DRM_LDIF_KEYGEN ) &&
- !record_type.equals( DRM_LDIF_RECOVERY ) ) {
- log( "ERROR: Unknown LDIF record type='"
- + record_type
- + "'!"
- + NEWLINE, true );
+ if (!record_type.equals(DRM_LDIF_ENROLLMENT) &&
+ !record_type.equals(DRM_LDIF_KEYGEN) &&
+ !record_type.equals(DRM_LDIF_RECOVERY)) {
+ log("ERROR: Unknown LDIF record type='"
+ + record_type
+ + "'!"
+ + NEWLINE, true);
return FAILURE;
}
- } else if( input.startsWith( DRM_LDIF_ARCHIVED_BY ) ) {
+ } else if (input.startsWith(DRM_LDIF_ARCHIVED_BY)) {
// extract the data
data = input.substring(
DRM_LDIF_ARCHIVED_BY.length() + 1
- ).trim();
+ ).trim();
// set the record type:
//
- // * DRM_LDIF_CA_KEY_RECORD
- // * DRM_LDIF_TPS_KEY_RECORD
+ // * DRM_LDIF_CA_KEY_RECORD
+ // * DRM_LDIF_TPS_KEY_RECORD
//
- if( data.startsWith( DRM_LDIF_TPS_KEY_RECORD ) ) {
+ if (data.startsWith(DRM_LDIF_TPS_KEY_RECORD)) {
record_type = DRM_LDIF_TPS_KEY_RECORD;
- } else if( data.startsWith( DRM_LDIF_CA_KEY_RECORD ) ) {
+ } else if (data.startsWith(DRM_LDIF_CA_KEY_RECORD)) {
record_type = DRM_LDIF_CA_KEY_RECORD;
} else {
- log( "ERROR: Unable to determine LDIF record type "
- + "from data='"
- + data
- + "'!"
- + NEWLINE, true );
+ log("ERROR: Unable to determine LDIF record type "
+ + "from data='"
+ + data
+ + "'!"
+ + NEWLINE, true);
return FAILURE;
}
}
@@ -4280,24 +4138,24 @@ public class DRMTool
// an LDIF request record nor an LDIF key record; check
// to see if it needs to be written out to the target
// LDIF file or thrown away.
- if( ( record_type == null ) &&
- mProcessRequestsAndKeyRecordsOnlyFlag ) {
+ if ((record_type == null) &&
+ mProcessRequestsAndKeyRecordsOnlyFlag) {
// Mark each removed record with an 'x'
- System.out.print( "x" );
+ System.out.print("x");
// log this information
- log( "INFO: Throwing away an LDIF record which is "
- + "neither a Request nor a Key Record!"
- + NEWLINE, false );
+ log("INFO: Throwing away an LDIF record which is "
+ + "neither a Request nor a Key Record!"
+ + NEWLINE, false);
// clear this LDIF record from the record vector
record.clear();
- // NOTE: there is no need to reset the record type
+ // NOTE: there is no need to reset the record type
// begin adding input lines into a new record
continue;
- } else if( record_type == null ) {
+ } else if (record_type == null) {
// Set record type to specify a "generic" LDIF record
record_type = DRM_LDIF_RECORD;
}
@@ -4305,98 +4163,98 @@ public class DRMTool
ldif_record = record.iterator();
// Process each line of the record:
- // * If LDIF Record Type for this line is 'valid'
- // * If DRMTOOL Configuration File Parameter is 'true'
- // * Process this data
- // * Else If DRMTOOL Configuration File Parameter is 'false'
- // * Pass through this data unchanged
- // * Else If LDIF Record Type for this line is 'invalid'
- // * Log error and leave method returning 'false'
- while( ldif_record.hasNext() ) {
+ // * If LDIF Record Type for this line is 'valid'
+ // * If DRMTOOL Configuration File Parameter is 'true'
+ // * Process this data
+ // * Else If DRMTOOL Configuration File Parameter is 'false'
+ // * Pass through this data unchanged
+ // * Else If LDIF Record Type for this line is 'invalid'
+ // * Log error and leave method returning 'false'
+ while (ldif_record.hasNext()) {
line = ldif_record.next();
- if( line.startsWith( DRM_LDIF_CN ) ) {
- output = output_cn( record_type, line );
- if( output == null ) {
+ if (line.startsWith(DRM_LDIF_CN)) {
+ output = output_cn(record_type, line);
+ if (output == null) {
return FAILURE;
}
- } else if( line.startsWith( DRM_LDIF_DATE_OF_MODIFY ) ) {
- output = output_date_of_modify( record_type, line );
- if( output == null ) {
+ } else if (line.startsWith(DRM_LDIF_DATE_OF_MODIFY)) {
+ output = output_date_of_modify(record_type, line);
+ if (output == null) {
return FAILURE;
}
- } else if( line.startsWith( DRM_LDIF_DN ) ) {
- output = output_dn( record_type, line );
- if( output == null ) {
+ } else if (line.startsWith(DRM_LDIF_DN)) {
+ output = output_dn(record_type, line);
+ if (output == null) {
return FAILURE;
}
- } else if(line.startsWith( DRM_LDIF_EXTDATA_KEY_RECORD )) {
- output = output_extdata_key_record( record_type,
- line );
- if( output == null ) {
+ } else if (line.startsWith(DRM_LDIF_EXTDATA_KEY_RECORD)) {
+ output = output_extdata_key_record(record_type,
+ line);
+ if (output == null) {
return FAILURE;
}
- } else if(line.startsWith( DRM_LDIF_EXTDATA_REQUEST_ID )) {
- output = output_extdata_request_id( record_type,
- line );
- if( output == null ) {
+ } else if (line.startsWith(DRM_LDIF_EXTDATA_REQUEST_ID)) {
+ output = output_extdata_request_id(record_type,
+ line);
+ if (output == null) {
return FAILURE;
}
- } else if(line.startsWith(DRM_LDIF_EXTDATA_REQUEST_NOTES)) {
- output = output_extdata_request_notes( record_type,
- line );
- if( output == null ) {
+ } else if (line.startsWith(DRM_LDIF_EXTDATA_REQUEST_NOTES)) {
+ output = output_extdata_request_notes(record_type,
+ line);
+ if (output == null) {
return FAILURE;
}
- } else if(line.startsWith(DRM_LDIF_EXTDATA_REQUEST_TYPE)) {
+ } else if (line.startsWith(DRM_LDIF_EXTDATA_REQUEST_TYPE)) {
// if one is not already present,
// compose and write out the missing
// 'extdata_requestnotes' line
- create_extdata_request_notes( record_type,
+ create_extdata_request_notes(record_type,
previous_line,
- writer );
+ writer);
// ALWAYS pass through the original
// 'extdata-requesttype' line UNCHANGED
// so that it is ALWAYS written
output = line;
- } else if(line.startsWith(DRM_LDIF_EXTDATA_SERIAL_NUMBER)) {
- output = output_extdata_serial_number( record_type,
- line );
- if( output == null ) {
+ } else if (line.startsWith(DRM_LDIF_EXTDATA_SERIAL_NUMBER)) {
+ output = output_extdata_serial_number(record_type,
+ line);
+ if (output == null) {
return FAILURE;
}
- } else if( line.startsWith( DRM_LDIF_PRIVATE_KEY_DATA ) ) {
- output = output_private_key_data( record_type,
- line );
- if( output == null ) {
+ } else if (line.startsWith(DRM_LDIF_PRIVATE_KEY_DATA)) {
+ output = output_private_key_data(record_type,
+ line);
+ if (output == null) {
return FAILURE;
}
- } else if( line.startsWith( DRM_LDIF_REQUEST_ID ) ) {
- output = output_request_id( record_type, line );
- if( output == null ) {
+ } else if (line.startsWith(DRM_LDIF_REQUEST_ID)) {
+ output = output_request_id(record_type, line);
+ if (output == null) {
return FAILURE;
}
- } else if( line.startsWith( DRM_LDIF_SERIAL_NO ) ) {
- output = output_serial_no( record_type, line );
- if( output == null ) {
+ } else if (line.startsWith(DRM_LDIF_SERIAL_NO)) {
+ output = output_serial_no(record_type, line);
+ if (output == null) {
return FAILURE;
}
- } else if( previous_line != null &&
+ } else if (previous_line != null &&
previous_line.startsWith(
- DRM_LDIF_EXTDATA_AUTH_TOKEN_USER ) ) {
- output = output_extdata_auth_token_user( record_type,
- line );
- if( output == null ) {
+ DRM_LDIF_EXTDATA_AUTH_TOKEN_USER)) {
+ output = output_extdata_auth_token_user(record_type,
+ line);
+ if (output == null) {
return FAILURE;
}
- } else if( previous_line != null &&
+ } else if (previous_line != null &&
previous_line.startsWith(
- DRM_LDIF_EXTDATA_AUTH_TOKEN_USER_DN ) ) {
- output = output_extdata_auth_token_user_dn( record_type,
- line );
- if( output == null ) {
+ DRM_LDIF_EXTDATA_AUTH_TOKEN_USER_DN)) {
+ output = output_extdata_auth_token_user_dn(record_type,
+ line);
+ if (output == null) {
return FAILURE;
}
} else {
@@ -4408,42 +4266,41 @@ public class DRMTool
previous_line = output;
// Always write out the output line and flush the buffer
- writer.write( output + NEWLINE );
+ writer.write(output + NEWLINE);
writer.flush();
- System.out.print( "." );
+ System.out.print(".");
}
// Mark the end of the LDIF record
- System.out.print( "!" );
+ System.out.print("!");
// clear this LDIF record from the record vector
record.clear();
}
- System.out.println( " FINISHED." + NEWLINE );
- } catch( IOException exIO ) {
- log( "ERROR: line='"
- + line
- + "' OR output='"
- + output
- + "' IOException: '"
- + exIO.toString()
- + "'"
- + NEWLINE, true );
+ System.out.println(" FINISHED." + NEWLINE);
+ } catch (IOException exIO) {
+ log("ERROR: line='"
+ + line
+ + "' OR output='"
+ + output
+ + "' IOException: '"
+ + exIO.toString()
+ + "'"
+ + NEWLINE, true);
return FAILURE;
}
return SUCCESS;
}
-
/**************************************/
/* DRMTOOL Config File Parser Methods */
/**************************************/
/**
- * This method performs the actual parsing of the DRMTOOL config file
- * and initializes how the DRM Record Fields should be processed.
+ * This method performs the actual parsing of the DRMTOOL config file and
+ * initializes how the DRM Record Fields should be processed.
* <P>
- *
+ *
* @return true if the DRMTOOL config file is successfully processed
*/
private static boolean process_drmtool_config_file() {
@@ -4459,94 +4316,93 @@ public class DRMTool
try {
// Open DRMTOOL config file for reading
reader = new BufferedReader(
- new FileReader( mDrmtoolCfgFilename ) );
+ new FileReader(mDrmtoolCfgFilename));
// Create a hashtable for relevant name/value pairs
drmtoolCfg = new Hashtable<String, Boolean>();
- System.out.print( "PROCESSING DRMTOOL CONFIG FILE: " );
- while( ( line = reader.readLine() ) != null ) {
- if( line.startsWith( DRMTOOL_CFG_PREFIX ) ) {
+ System.out.print("PROCESSING DRMTOOL CONFIG FILE: ");
+ while ((line = reader.readLine()) != null) {
+ if (line.startsWith(DRMTOOL_CFG_PREFIX)) {
// obtain "name=value" pair
- name_value_pair = line.split( EQUAL_SIGN );
+ name_value_pair = line.split(EQUAL_SIGN);
// obtain "name"
name = name_value_pair[0];
// compute "boolean" value
- if( name_value_pair[1].equals( "true" ) ) {
+ if (name_value_pair[1].equals("true")) {
value = Boolean.TRUE;
} else {
value = Boolean.FALSE;
}
// store relevant DRM LDIF fields for processing
- if( name.equals( DRMTOOL_CFG_ENROLLMENT_CN )
- || name.equals( DRMTOOL_CFG_ENROLLMENT_DATE_OF_MODIFY )
- || name.equals( DRMTOOL_CFG_ENROLLMENT_DN )
- || name.equals( DRMTOOL_CFG_ENROLLMENT_EXTDATA_KEY_RECORD )
- || name.equals( DRMTOOL_CFG_ENROLLMENT_EXTDATA_REQUEST_NOTES )
- || name.equals( DRMTOOL_CFG_ENROLLMENT_REQUEST_ID )
- || name.equals( DRMTOOL_CFG_CA_KEY_RECORD_CN )
- || name.equals( DRMTOOL_CFG_CA_KEY_RECORD_DATE_OF_MODIFY )
- || name.equals( DRMTOOL_CFG_CA_KEY_RECORD_DN )
- || name.equals( DRMTOOL_CFG_CA_KEY_RECORD_PRIVATE_KEY_DATA )
- || name.equals( DRMTOOL_CFG_CA_KEY_RECORD_SERIAL_NO )
- || name.equals( DRMTOOL_CFG_RECOVERY_CN )
- || name.equals( DRMTOOL_CFG_RECOVERY_DATE_OF_MODIFY )
- || name.equals( DRMTOOL_CFG_RECOVERY_DN )
- || name.equals( DRMTOOL_CFG_RECOVERY_EXTDATA_REQUEST_ID )
- || name.equals( DRMTOOL_CFG_RECOVERY_EXTDATA_REQUEST_NOTES )
- || name.equals( DRMTOOL_CFG_RECOVERY_EXTDATA_SERIAL_NUMBER )
- || name.equals( DRMTOOL_CFG_RECOVERY_REQUEST_ID )
- || name.equals( DRMTOOL_CFG_TPS_KEY_RECORD_CN )
- || name.equals( DRMTOOL_CFG_TPS_KEY_RECORD_DATE_OF_MODIFY )
- || name.equals( DRMTOOL_CFG_TPS_KEY_RECORD_DN )
- || name.equals( DRMTOOL_CFG_TPS_KEY_RECORD_PRIVATE_KEY_DATA )
- || name.equals( DRMTOOL_CFG_TPS_KEY_RECORD_SERIAL_NO )
- || name.equals( DRMTOOL_CFG_KEYGEN_CN )
- || name.equals( DRMTOOL_CFG_KEYGEN_DATE_OF_MODIFY )
- || name.equals( DRMTOOL_CFG_KEYGEN_DN )
- || name.equals( DRMTOOL_CFG_KEYGEN_EXTDATA_KEY_RECORD )
- || name.equals( DRMTOOL_CFG_KEYGEN_EXTDATA_REQUEST_ID )
- || name.equals( DRMTOOL_CFG_KEYGEN_EXTDATA_REQUEST_NOTES )
- || name.equals( DRMTOOL_CFG_KEYGEN_REQUEST_ID ) ) {
- drmtoolCfg.put( name, value );
- System.out.print( "." );
+ if (name.equals(DRMTOOL_CFG_ENROLLMENT_CN)
+ || name.equals(DRMTOOL_CFG_ENROLLMENT_DATE_OF_MODIFY)
+ || name.equals(DRMTOOL_CFG_ENROLLMENT_DN)
+ || name.equals(DRMTOOL_CFG_ENROLLMENT_EXTDATA_KEY_RECORD)
+ || name.equals(DRMTOOL_CFG_ENROLLMENT_EXTDATA_REQUEST_NOTES)
+ || name.equals(DRMTOOL_CFG_ENROLLMENT_REQUEST_ID)
+ || name.equals(DRMTOOL_CFG_CA_KEY_RECORD_CN)
+ || name.equals(DRMTOOL_CFG_CA_KEY_RECORD_DATE_OF_MODIFY)
+ || name.equals(DRMTOOL_CFG_CA_KEY_RECORD_DN)
+ || name.equals(DRMTOOL_CFG_CA_KEY_RECORD_PRIVATE_KEY_DATA)
+ || name.equals(DRMTOOL_CFG_CA_KEY_RECORD_SERIAL_NO)
+ || name.equals(DRMTOOL_CFG_RECOVERY_CN)
+ || name.equals(DRMTOOL_CFG_RECOVERY_DATE_OF_MODIFY)
+ || name.equals(DRMTOOL_CFG_RECOVERY_DN)
+ || name.equals(DRMTOOL_CFG_RECOVERY_EXTDATA_REQUEST_ID)
+ || name.equals(DRMTOOL_CFG_RECOVERY_EXTDATA_REQUEST_NOTES)
+ || name.equals(DRMTOOL_CFG_RECOVERY_EXTDATA_SERIAL_NUMBER)
+ || name.equals(DRMTOOL_CFG_RECOVERY_REQUEST_ID)
+ || name.equals(DRMTOOL_CFG_TPS_KEY_RECORD_CN)
+ || name.equals(DRMTOOL_CFG_TPS_KEY_RECORD_DATE_OF_MODIFY)
+ || name.equals(DRMTOOL_CFG_TPS_KEY_RECORD_DN)
+ || name.equals(DRMTOOL_CFG_TPS_KEY_RECORD_PRIVATE_KEY_DATA)
+ || name.equals(DRMTOOL_CFG_TPS_KEY_RECORD_SERIAL_NO)
+ || name.equals(DRMTOOL_CFG_KEYGEN_CN)
+ || name.equals(DRMTOOL_CFG_KEYGEN_DATE_OF_MODIFY)
+ || name.equals(DRMTOOL_CFG_KEYGEN_DN)
+ || name.equals(DRMTOOL_CFG_KEYGEN_EXTDATA_KEY_RECORD)
+ || name.equals(DRMTOOL_CFG_KEYGEN_EXTDATA_REQUEST_ID)
+ || name.equals(DRMTOOL_CFG_KEYGEN_EXTDATA_REQUEST_NOTES)
+ || name.equals(DRMTOOL_CFG_KEYGEN_REQUEST_ID)) {
+ drmtoolCfg.put(name, value);
+ System.out.print(".");
}
}
}
- System.out.println( " FINISHED." + NEWLINE );
- } catch( FileNotFoundException exDrmtoolCfgFileNotFound ) {
- log( "ERROR: No DRMTOOL config file named '"
- + mDrmtoolCfgFilename
- + "' exists! FileNotFoundException: '"
- + exDrmtoolCfgFileNotFound.toString()
- + "'"
- + NEWLINE, true );
+ System.out.println(" FINISHED." + NEWLINE);
+ } catch (FileNotFoundException exDrmtoolCfgFileNotFound) {
+ log("ERROR: No DRMTOOL config file named '"
+ + mDrmtoolCfgFilename
+ + "' exists! FileNotFoundException: '"
+ + exDrmtoolCfgFileNotFound.toString()
+ + "'"
+ + NEWLINE, true);
return FAILURE;
- } catch( IOException exDrmtoolCfgIO ) {
- log( "ERROR: line='"
- + line
- + "' IOException: '"
- + exDrmtoolCfgIO.toString()
- + "'"
- + NEWLINE, true );
+ } catch (IOException exDrmtoolCfgIO) {
+ log("ERROR: line='"
+ + line
+ + "' IOException: '"
+ + exDrmtoolCfgIO.toString()
+ + "'"
+ + NEWLINE, true);
return FAILURE;
- } catch( PatternSyntaxException exDrmtoolCfgNameValuePattern ) {
- log( "ERROR: line='"
- + line
- + "' PatternSyntaxException: '"
- + exDrmtoolCfgNameValuePattern.toString()
- + "'"
- + NEWLINE, true );
+ } catch (PatternSyntaxException exDrmtoolCfgNameValuePattern) {
+ log("ERROR: line='"
+ + line
+ + "' PatternSyntaxException: '"
+ + exDrmtoolCfgNameValuePattern.toString()
+ + "'"
+ + NEWLINE, true);
return FAILURE;
}
return SUCCESS;
}
-
/************/
/* DRM Tool */
/************/
@@ -4554,10 +4410,10 @@ public class DRMTool
/**
* The main DRMTool method.
* <P>
- *
+ *
* @param args DRMTool options
*/
- public static void main( String[] args ) {
+ public static void main(String[] args) {
// Variables
String append_id_offset = null;
String remove_id_offset = null;
@@ -4574,155 +4430,154 @@ public class DRMTool
boolean success = false;
// Get current date and time
- mDateOfModify = now( DATE_OF_MODIFY_PATTERN );
+ mDateOfModify = now(DATE_OF_MODIFY_PATTERN);
// Check that the correct number of arguments were
// submitted to the program
- if( ( args.length != ID_OFFSET_ARGS ) &&
- ( args.length != ( ID_OFFSET_ARGS + 1 ) ) &&
- ( args.length != ( ID_OFFSET_ARGS + 4 ) ) &&
- ( args.length != ( ID_OFFSET_ARGS + 5 ) ) &&
- ( args.length != REWRAP_ARGS ) &&
- ( args.length != ( REWRAP_ARGS + 1 ) ) &&
- ( args.length != ( REWRAP_ARGS + 2 ) ) &&
- ( args.length != ( REWRAP_ARGS + 3 ) ) &&
- ( args.length != ( REWRAP_ARGS + 4 ) ) &&
- ( args.length != ( REWRAP_ARGS + 5 ) ) &&
- ( args.length != ( REWRAP_ARGS + 6 ) ) &&
- ( args.length != ( REWRAP_ARGS + 7 ) ) &&
- ( args.length != REWRAP_AND_ID_OFFSET_ARGS ) &&
- ( args.length != ( REWRAP_AND_ID_OFFSET_ARGS + 1 ) ) &&
- ( args.length != ( REWRAP_AND_ID_OFFSET_ARGS + 2 ) ) &&
- ( args.length != ( REWRAP_AND_ID_OFFSET_ARGS + 3 ) ) &&
- ( args.length != ( REWRAP_AND_ID_OFFSET_ARGS + 4 ) ) &&
- ( args.length != ( REWRAP_AND_ID_OFFSET_ARGS + 5 ) ) &&
- ( args.length != ( REWRAP_AND_ID_OFFSET_ARGS + 6 ) ) &&
- ( args.length != ( REWRAP_AND_ID_OFFSET_ARGS + 7 ) ) ) {
- System.err.println( "ERROR: Incorrect number of arguments!"
- + NEWLINE );
+ if ((args.length != ID_OFFSET_ARGS) &&
+ (args.length != (ID_OFFSET_ARGS + 1)) &&
+ (args.length != (ID_OFFSET_ARGS + 4)) &&
+ (args.length != (ID_OFFSET_ARGS + 5)) &&
+ (args.length != REWRAP_ARGS) &&
+ (args.length != (REWRAP_ARGS + 1)) &&
+ (args.length != (REWRAP_ARGS + 2)) &&
+ (args.length != (REWRAP_ARGS + 3)) &&
+ (args.length != (REWRAP_ARGS + 4)) &&
+ (args.length != (REWRAP_ARGS + 5)) &&
+ (args.length != (REWRAP_ARGS + 6)) &&
+ (args.length != (REWRAP_ARGS + 7)) &&
+ (args.length != REWRAP_AND_ID_OFFSET_ARGS) &&
+ (args.length != (REWRAP_AND_ID_OFFSET_ARGS + 1)) &&
+ (args.length != (REWRAP_AND_ID_OFFSET_ARGS + 2)) &&
+ (args.length != (REWRAP_AND_ID_OFFSET_ARGS + 3)) &&
+ (args.length != (REWRAP_AND_ID_OFFSET_ARGS + 4)) &&
+ (args.length != (REWRAP_AND_ID_OFFSET_ARGS + 5)) &&
+ (args.length != (REWRAP_AND_ID_OFFSET_ARGS + 6)) &&
+ (args.length != (REWRAP_AND_ID_OFFSET_ARGS + 7))) {
+ System.err.println("ERROR: Incorrect number of arguments!"
+ + NEWLINE);
printUsage();
- System.exit( 0 );
+ System.exit(0);
}
// Process command-line arguments
- for( int i = 0; i < args.length; i += 2 ) {
- if( args[i].equals( DRMTOOL_CFG_FILE ) ) {
+ for (int i = 0; i < args.length; i += 2) {
+ if (args[i].equals(DRMTOOL_CFG_FILE)) {
mDrmtoolCfgFilename = args[i + 1];
mMandatoryNameValuePairs++;
- } else if( args[i].equals( SOURCE_LDIF_FILE ) ) {
+ } else if (args[i].equals(SOURCE_LDIF_FILE)) {
mSourceLdifFilename = args[i + 1];
mMandatoryNameValuePairs++;
- } else if( args[i].equals( TARGET_LDIF_FILE ) ) {
+ } else if (args[i].equals(TARGET_LDIF_FILE)) {
mTargetLdifFilename = args[i + 1];
mMandatoryNameValuePairs++;
- } else if( args[i].equals( LOG_FILE ) ) {
+ } else if (args[i].equals(LOG_FILE)) {
mLogFilename = args[i + 1];
mMandatoryNameValuePairs++;
- } else if( args[i].equals( SOURCE_NSS_DB_PATH ) ) {
+ } else if (args[i].equals(SOURCE_NSS_DB_PATH)) {
mSourcePKISecurityDatabasePath = args[i + 1];
mRewrapNameValuePairs++;
- } else if( args[i].equals( SOURCE_STORAGE_TOKEN_NAME ) ) {
+ } else if (args[i].equals(SOURCE_STORAGE_TOKEN_NAME)) {
mSourceStorageTokenName = args[i + 1];
mRewrapNameValuePairs++;
- } else if( args[i].equals( SOURCE_STORAGE_CERT_NICKNAME ) ) {
+ } else if (args[i].equals(SOURCE_STORAGE_CERT_NICKNAME)) {
mSourceStorageCertNickname = args[i + 1];
mRewrapNameValuePairs++;
- } else if( args[i].equals( TARGET_STORAGE_CERTIFICATE_FILE ) ) {
+ } else if (args[i].equals(TARGET_STORAGE_CERTIFICATE_FILE)) {
mTargetStorageCertificateFilename = args[i + 1];
mRewrapNameValuePairs++;
- } else if( args[i].equals( SOURCE_NSS_DB_PWDFILE ) ) {
+ } else if (args[i].equals(SOURCE_NSS_DB_PWDFILE)) {
mSourcePKISecurityDatabasePwdfile = args[i + 1];
mPKISecurityDatabasePwdfileNameValuePairs++;
- } else if( args[i].equals( APPEND_ID_OFFSET ) ) {
+ } else if (args[i].equals(APPEND_ID_OFFSET)) {
append_id_offset = args[i + 1];
mAppendIdOffsetNameValuePairs++;
- } else if( args[i].equals( REMOVE_ID_OFFSET ) ) {
+ } else if (args[i].equals(REMOVE_ID_OFFSET)) {
remove_id_offset = args[i + 1];
mRemoveIdOffsetNameValuePairs++;
- } else if( args[i].equals( SOURCE_DRM_NAMING_CONTEXT ) ) {
+ } else if (args[i].equals(SOURCE_DRM_NAMING_CONTEXT)) {
mSourceDrmNamingContext = args[i + 1];
mDrmNamingContextNameValuePairs++;
- } else if( args[i].equals( TARGET_DRM_NAMING_CONTEXT ) ) {
+ } else if (args[i].equals(TARGET_DRM_NAMING_CONTEXT)) {
mTargetDrmNamingContext = args[i + 1];
mDrmNamingContextNameValuePairs++;
- } else if( args[i].equals( PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY ) )
- {
+ } else if (args[i].equals(PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY)) {
mProcessRequestsAndKeyRecordsOnlyFlag = true;
i -= 1;
} else {
- System.err.println( "ERROR: Unknown argument '"
+ System.err.println("ERROR: Unknown argument '"
+ args[i]
+ "'!"
- + NEWLINE );
+ + NEWLINE);
printUsage();
- System.exit( 0 );
+ System.exit(0);
}
}
// Verify that correct number of valid mandatory
// arguments were submitted to the program
- if( mMandatoryNameValuePairs != MANDATORY_NAME_VALUE_PAIRS ||
- mDrmtoolCfgFilename == null ||
- mDrmtoolCfgFilename.length() == 0 ||
- mSourceLdifFilename == null ||
- mSourceLdifFilename.length() == 0 ||
- mTargetLdifFilename == null ||
- mTargetLdifFilename.length() == 0 ||
- mLogFilename == null ||
- mLogFilename.length() == 0 ) {
- System.err.println( "ERROR: Missing mandatory arguments!"
- + NEWLINE );
+ if (mMandatoryNameValuePairs != MANDATORY_NAME_VALUE_PAIRS ||
+ mDrmtoolCfgFilename == null ||
+ mDrmtoolCfgFilename.length() == 0 ||
+ mSourceLdifFilename == null ||
+ mSourceLdifFilename.length() == 0 ||
+ mTargetLdifFilename == null ||
+ mTargetLdifFilename.length() == 0 ||
+ mLogFilename == null ||
+ mLogFilename.length() == 0) {
+ System.err.println("ERROR: Missing mandatory arguments!"
+ + NEWLINE);
printUsage();
- System.exit( 0 );
+ System.exit(0);
} else {
// Check for a valid DRMTOOL config file
- cfgFile = new File( mDrmtoolCfgFilename );
- if( !cfgFile.exists() ||
- !cfgFile.isFile() ||
- ( cfgFile.length() == 0 ) ) {
- System.err.println( "ERROR: '"
+ cfgFile = new File(mDrmtoolCfgFilename);
+ if (!cfgFile.exists() ||
+ !cfgFile.isFile() ||
+ (cfgFile.length() == 0)) {
+ System.err.println("ERROR: '"
+ mDrmtoolCfgFilename
+ "' does NOT exist, is NOT a file, "
+ "or is empty!"
- + NEWLINE );
+ + NEWLINE);
printUsage();
- System.exit( 0 );
+ System.exit(0);
}
// Check for a valid source LDIF file
- sourceFile = new File( mSourceLdifFilename );
- if( !sourceFile.exists() ||
- !sourceFile.isFile() ||
- ( sourceFile.length() == 0 ) ) {
- System.err.println( "ERROR: '"
+ sourceFile = new File(mSourceLdifFilename);
+ if (!sourceFile.exists() ||
+ !sourceFile.isFile() ||
+ (sourceFile.length() == 0)) {
+ System.err.println("ERROR: '"
+ mSourceLdifFilename
+ "' does NOT exist, is NOT a file, "
+ "or is empty!"
- + NEWLINE );
+ + NEWLINE);
printUsage();
- System.exit( 0 );
+ System.exit(0);
}
// Check that the target LDIF file does NOT exist
- targetFile = new File( mTargetLdifFilename );
- if( targetFile.exists() ) {
- System.err.println( "ERROR: '"
+ targetFile = new File(mTargetLdifFilename);
+ if (targetFile.exists()) {
+ System.err.println("ERROR: '"
+ mTargetLdifFilename
+ "' ALREADY exists!"
- + NEWLINE );
+ + NEWLINE);
printUsage();
- System.exit( 0 );
+ System.exit(0);
}
// Check that the log file does NOT exist
- logFile = new File( mLogFilename );
- if( logFile.exists() ) {
- System.err.println( "ERROR: '"
+ logFile = new File(mLogFilename);
+ if (logFile.exists()) {
+ System.err.println("ERROR: '"
+ mLogFilename
+ "' ALREADY exists!"
- + NEWLINE );
+ + NEWLINE);
printUsage();
- System.exit( 0 );
+ System.exit(0);
}
// Mark the 'Mandatory' flag true
@@ -4731,47 +4586,47 @@ public class DRMTool
// Check to see that if the 'Rewrap' command-line options were
// specified, that they are all present and accounted for
- if( mRewrapNameValuePairs > 0 ) {
- if( mRewrapNameValuePairs != REWRAP_NAME_VALUE_PAIRS ||
- mSourcePKISecurityDatabasePath == null ||
- mSourcePKISecurityDatabasePath.length() == 0 ||
- mSourceStorageTokenName == null ||
- mSourceStorageTokenName.length() == 0 ||
- mSourceStorageCertNickname == null ||
- mSourceStorageCertNickname.length() == 0 ||
- mTargetStorageCertificateFilename == null ||
- mTargetStorageCertificateFilename.length() == 0 ) {
- System.err.println( "ERROR: Missing 'Rewrap' arguments!"
- + NEWLINE );
+ if (mRewrapNameValuePairs > 0) {
+ if (mRewrapNameValuePairs != REWRAP_NAME_VALUE_PAIRS ||
+ mSourcePKISecurityDatabasePath == null ||
+ mSourcePKISecurityDatabasePath.length() == 0 ||
+ mSourceStorageTokenName == null ||
+ mSourceStorageTokenName.length() == 0 ||
+ mSourceStorageCertNickname == null ||
+ mSourceStorageCertNickname.length() == 0 ||
+ mTargetStorageCertificateFilename == null ||
+ mTargetStorageCertificateFilename.length() == 0) {
+ System.err.println("ERROR: Missing 'Rewrap' arguments!"
+ + NEWLINE);
printUsage();
- System.exit( 0 );
+ System.exit(0);
} else {
// Check for a valid path to the PKI security databases
- sourceDBPath = new File( mSourcePKISecurityDatabasePath );
- if( !sourceDBPath.exists() ||
- !sourceDBPath.isDirectory() ) {
- System.err.println( "ERROR: '"
+ sourceDBPath = new File(mSourcePKISecurityDatabasePath);
+ if (!sourceDBPath.exists() ||
+ !sourceDBPath.isDirectory()) {
+ System.err.println("ERROR: '"
+ mSourcePKISecurityDatabasePath
+ "' does NOT exist or "
+ "'is NOT a directory!"
- + NEWLINE );
+ + NEWLINE);
printUsage();
- System.exit( 0 );
+ System.exit(0);
}
// Check for a valid target storage certificate file
targetStorageCertFile = new File(
- mTargetStorageCertificateFilename );
- if( !targetStorageCertFile.exists() ||
- !targetStorageCertFile.isFile() ||
- ( targetStorageCertFile.length() == 0 ) ) {
- System.err.println( "ERROR: '"
+ mTargetStorageCertificateFilename);
+ if (!targetStorageCertFile.exists() ||
+ !targetStorageCertFile.isFile() ||
+ (targetStorageCertFile.length() == 0)) {
+ System.err.println("ERROR: '"
+ mTargetStorageCertificateFilename
+ "' does NOT exist, is NOT a file, "
+ "or is empty!"
- + NEWLINE );
+ + NEWLINE);
printUsage();
- System.exit( 0 );
+ System.exit(0);
}
// Mark the 'Rewrap' flag true
@@ -4782,139 +4637,139 @@ public class DRMTool
// Check to see that BOTH append 'ID Offset' command-line options
// and remove 'ID Offset' command-line options were NOT specified
// since these two command-line options are mutually exclusive!
- if( ( mAppendIdOffsetNameValuePairs > 0 ) &&
- ( mRemoveIdOffsetNameValuePairs > 0 ) ) {
- System.err.println( "ERROR: The 'append ID Offset' option "
+ if ((mAppendIdOffsetNameValuePairs > 0) &&
+ (mRemoveIdOffsetNameValuePairs > 0)) {
+ System.err.println("ERROR: The 'append ID Offset' option "
+ "and the 'remove ID Offset' option are "
+ "mutually exclusive!"
- + NEWLINE );
- printUsage();
- System.exit( 0 );
+ + NEWLINE);
+ printUsage();
+ System.exit(0);
}
// Check to see that if the 'append ID Offset' command-line options
// were specified, that they are all present and accounted for
- if( mAppendIdOffsetNameValuePairs > 0 ) {
- if( mAppendIdOffsetNameValuePairs == ID_OFFSET_NAME_VALUE_PAIRS &&
- append_id_offset != null &&
- append_id_offset.length() != 0 ) {
+ if (mAppendIdOffsetNameValuePairs > 0) {
+ if (mAppendIdOffsetNameValuePairs == ID_OFFSET_NAME_VALUE_PAIRS &&
+ append_id_offset != null &&
+ append_id_offset.length() != 0) {
try {
- if( !append_id_offset.matches( "[0-9]++" ) ) {
- System.err.println( "ERROR: '"
+ if (!append_id_offset.matches("[0-9]++")) {
+ System.err.println("ERROR: '"
+ append_id_offset
+ "' contains non-numeric "
+ "characters!"
- + NEWLINE );
+ + NEWLINE);
printUsage();
- System.exit( 0 );
+ System.exit(0);
} else {
mAppendIdOffset = new BigInteger(
- append_id_offset );
+ append_id_offset);
// Mark the 'append ID Offset' flag true
mAppendIdOffsetFlag = true;
}
- } catch( PatternSyntaxException exAppendPattern ) {
- System.err.println( "ERROR: append_id_offset='"
+ } catch (PatternSyntaxException exAppendPattern) {
+ System.err.println("ERROR: append_id_offset='"
+ append_id_offset
+ "' PatternSyntaxException: '"
+ exAppendPattern.toString()
+ "'"
- + NEWLINE );
- System.exit( 0 );
+ + NEWLINE);
+ System.exit(0);
}
} else {
- System.err.println( "ERROR: Missing "
+ System.err.println("ERROR: Missing "
+ "'append ID Offset' arguments!"
- + NEWLINE );
+ + NEWLINE);
printUsage();
- System.exit( 0 );
+ System.exit(0);
}
}
// Check to see that if the 'remove ID Offset' command-line options
// were specified, that they are all present and accounted for
- if( mRemoveIdOffsetNameValuePairs > 0 ) {
- if( mRemoveIdOffsetNameValuePairs == ID_OFFSET_NAME_VALUE_PAIRS &&
- remove_id_offset != null &&
- remove_id_offset.length() != 0 ) {
+ if (mRemoveIdOffsetNameValuePairs > 0) {
+ if (mRemoveIdOffsetNameValuePairs == ID_OFFSET_NAME_VALUE_PAIRS &&
+ remove_id_offset != null &&
+ remove_id_offset.length() != 0) {
try {
- if( !remove_id_offset.matches( "[0-9]++" ) ) {
- System.err.println( "ERROR: '"
+ if (!remove_id_offset.matches("[0-9]++")) {
+ System.err.println("ERROR: '"
+ remove_id_offset
+ "' contains non-numeric "
+ "characters!"
- + NEWLINE );
+ + NEWLINE);
printUsage();
- System.exit( 0 );
+ System.exit(0);
} else {
mRemoveIdOffset = new BigInteger(
- remove_id_offset );
+ remove_id_offset);
// Mark the 'remove ID Offset' flag true
mRemoveIdOffsetFlag = true;
}
- } catch( PatternSyntaxException exRemovePattern ) {
- System.err.println( "ERROR: remove_id_offset='"
+ } catch (PatternSyntaxException exRemovePattern) {
+ System.err.println("ERROR: remove_id_offset='"
+ remove_id_offset
+ "' PatternSyntaxException: '"
+ exRemovePattern.toString()
+ "'"
- + NEWLINE );
- System.exit( 0 );
+ + NEWLINE);
+ System.exit(0);
}
} else {
- System.err.println( "ERROR: Missing "
+ System.err.println("ERROR: Missing "
+ "'remove ID Offset' arguments!"
- + NEWLINE );
+ + NEWLINE);
printUsage();
- System.exit( 0 );
+ System.exit(0);
}
}
// Make certain that at least one of the "Rewrap", "Append ID Offset",
// or "Remove ID Offset" options has been specified
- if( !mRewrapFlag &&
- !mAppendIdOffsetFlag &&
- !mRemoveIdOffsetFlag ) {
- System.err.println( "ERROR: At least one of the 'rewrap', "
+ if (!mRewrapFlag &&
+ !mAppendIdOffsetFlag &&
+ !mRemoveIdOffsetFlag) {
+ System.err.println("ERROR: At least one of the 'rewrap', "
+ "'append ID Offset', or 'remove ID Offset' "
+ "options MUST be specified!"
- + NEWLINE );
+ + NEWLINE);
printUsage();
- System.exit( 0 );
+ System.exit(0);
}
// Check to see that if the OPTIONAL
// 'PKI Security Database Password File'
// command-line options were specified,
// that they are all present and accounted for
- if( mPKISecurityDatabasePwdfileNameValuePairs > 0 ) {
- if( mPKISecurityDatabasePwdfileNameValuePairs !=
- PWDFILE_NAME_VALUE_PAIRS ||
- mSourcePKISecurityDatabasePwdfile == null ||
- mSourcePKISecurityDatabasePwdfile.length() == 0 ) {
- System.err.println( "ERROR: Missing 'Password File' "
+ if (mPKISecurityDatabasePwdfileNameValuePairs > 0) {
+ if (mPKISecurityDatabasePwdfileNameValuePairs !=
+ PWDFILE_NAME_VALUE_PAIRS ||
+ mSourcePKISecurityDatabasePwdfile == null ||
+ mSourcePKISecurityDatabasePwdfile.length() == 0) {
+ System.err.println("ERROR: Missing 'Password File' "
+ "arguments!"
- + NEWLINE );
+ + NEWLINE);
printUsage();
- System.exit( 0 );
+ System.exit(0);
} else {
- if( mRewrapFlag ) {
+ if (mRewrapFlag) {
// Check for a valid source PKI
// security database password file
sourceDBPwdfile = new
- File( mSourcePKISecurityDatabasePwdfile );
- if( !sourceDBPwdfile.exists() ||
- !sourceDBPwdfile.isFile() ||
- ( sourceDBPwdfile.length() == 0 ) ) {
- System.err.println( "ERROR: '"
+ File(mSourcePKISecurityDatabasePwdfile);
+ if (!sourceDBPwdfile.exists() ||
+ !sourceDBPwdfile.isFile() ||
+ (sourceDBPwdfile.length() == 0)) {
+ System.err.println("ERROR: '"
+ mSourcePKISecurityDatabasePwdfile
+ "' does NOT exist, is NOT a file, "
+ "or is empty!"
- + NEWLINE );
+ + NEWLINE);
printUsage();
- System.exit( 0 );
+ System.exit(0);
}
use_PKI_security_database_pwdfile = SPACE
@@ -4932,15 +4787,15 @@ public class DRMTool
// Mark the 'Password File' flag true
mPwdfileFlag = true;
} else {
- System.err.println( "ERROR: The "
+ System.err.println("ERROR: The "
+ TIC
+ SOURCE_NSS_DB_PWDFILE
+ TIC
+ " option is ONLY valid when "
+ "performing rewrapping."
- + NEWLINE );
+ + NEWLINE);
printUsage();
- System.exit( 0 );
+ System.exit(0);
}
}
} else {
@@ -4950,19 +4805,19 @@ public class DRMTool
// Check to see that if the OPTIONAL 'DRM Naming Context' command-line
// options were specified, that they are all present and accounted for
- if( mDrmNamingContextNameValuePairs > 0 ) {
- if( mDrmNamingContextNameValuePairs !=
- NAMING_CONTEXT_NAME_VALUE_PAIRS ||
- mSourceDrmNamingContext == null ||
- mSourceDrmNamingContext.length() == 0 ||
- mTargetDrmNamingContext == null ||
- mTargetDrmNamingContext.length() == 0 ) {
- System.err.println( "ERROR: Both 'source DRM naming context' "
+ if (mDrmNamingContextNameValuePairs > 0) {
+ if (mDrmNamingContextNameValuePairs !=
+ NAMING_CONTEXT_NAME_VALUE_PAIRS ||
+ mSourceDrmNamingContext == null ||
+ mSourceDrmNamingContext.length() == 0 ||
+ mTargetDrmNamingContext == null ||
+ mTargetDrmNamingContext.length() == 0) {
+ System.err.println("ERROR: Both 'source DRM naming context' "
+ "and 'target DRM naming context' "
+ "options MUST be specified!"
- + NEWLINE );
+ + NEWLINE);
printUsage();
- System.exit( 0 );
+ System.exit(0);
} else {
process_drm_naming_context_fields = SPACE
+ SOURCE_DRM_NAMING_CONTEXT
@@ -4995,268 +4850,267 @@ public class DRMTool
}
// Check for OPTIONAL "Process Requests and Key Records ONLY" option
- if( mProcessRequestsAndKeyRecordsOnlyFlag ) {
+ if (mProcessRequestsAndKeyRecordsOnlyFlag) {
process_requests_and_key_records_only = SPACE
+ PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY;
mProcessRequestsAndKeyRecordsOnlyMessage = SPACE + PLUS + SPACE +
- DRM_LDIF_PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY_MESSAGE;
+ DRM_LDIF_PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY_MESSAGE;
} else {
process_requests_and_key_records_only = "";
mProcessRequestsAndKeyRecordsOnlyMessage = "";
}
// Enable logging process . . .
- open_log( mLogFilename );
+ open_log(mLogFilename);
// Begin logging progress . . .
- if( mRewrapFlag && mAppendIdOffsetFlag ) {
- log( "BEGIN \""
- + DRM_TOOL + SPACE
- + DRMTOOL_CFG_FILE + SPACE
- + mDrmtoolCfgFilename + SPACE
- + SOURCE_LDIF_FILE + SPACE
- + mSourceLdifFilename + SPACE
- + TARGET_LDIF_FILE + SPACE
- + mTargetLdifFilename + SPACE
- + LOG_FILE + SPACE
- + mLogFilename + SPACE
- + SOURCE_NSS_DB_PATH + SPACE
- + mSourcePKISecurityDatabasePath + SPACE
- + SOURCE_STORAGE_TOKEN_NAME + SPACE
- + TIC + mSourceStorageTokenName + TIC + SPACE
- + SOURCE_STORAGE_CERT_NICKNAME + SPACE
- + TIC + mSourceStorageCertNickname + TIC + SPACE
- + TARGET_STORAGE_CERTIFICATE_FILE + SPACE
- + mTargetStorageCertificateFilename + SPACE
- + use_PKI_security_database_pwdfile
- + APPEND_ID_OFFSET + SPACE
- + append_id_offset
- + process_drm_naming_context_fields
- + process_requests_and_key_records_only
- + "\" . . ."
- + NEWLINE, true );
- } else if( mRewrapFlag && mRemoveIdOffsetFlag ) {
- log( "BEGIN \""
- + DRM_TOOL + SPACE
- + DRMTOOL_CFG_FILE + SPACE
- + mDrmtoolCfgFilename + SPACE
- + SOURCE_LDIF_FILE + SPACE
- + mSourceLdifFilename + SPACE
- + TARGET_LDIF_FILE + SPACE
- + mTargetLdifFilename + SPACE
- + LOG_FILE + SPACE
- + mLogFilename + SPACE
- + SOURCE_NSS_DB_PATH + SPACE
- + mSourcePKISecurityDatabasePath + SPACE
- + SOURCE_STORAGE_TOKEN_NAME + SPACE
- + TIC + mSourceStorageTokenName + TIC + SPACE
- + SOURCE_STORAGE_CERT_NICKNAME + SPACE
- + TIC + mSourceStorageCertNickname + TIC + SPACE
- + TARGET_STORAGE_CERTIFICATE_FILE + SPACE
- + mTargetStorageCertificateFilename + SPACE
- + use_PKI_security_database_pwdfile
- + REMOVE_ID_OFFSET + SPACE
- + remove_id_offset
- + process_drm_naming_context_fields
- + process_requests_and_key_records_only
- + "\" . . ."
- + NEWLINE, true );
- } else if( mRewrapFlag ) {
- log( "BEGIN \""
- + DRM_TOOL + SPACE
- + DRMTOOL_CFG_FILE + SPACE
- + mDrmtoolCfgFilename + SPACE
- + SOURCE_LDIF_FILE + SPACE
- + mSourceLdifFilename + SPACE
- + TARGET_LDIF_FILE + SPACE
- + mTargetLdifFilename + SPACE
- + LOG_FILE + SPACE
- + mLogFilename + SPACE
- + SOURCE_NSS_DB_PATH + SPACE
- + mSourcePKISecurityDatabasePath + SPACE
- + SOURCE_STORAGE_TOKEN_NAME + SPACE
- + TIC + mSourceStorageTokenName + TIC + SPACE
- + SOURCE_STORAGE_CERT_NICKNAME + SPACE
- + TIC + mSourceStorageCertNickname + TIC + SPACE
- + TARGET_STORAGE_CERTIFICATE_FILE + SPACE
- + mTargetStorageCertificateFilename
- + use_PKI_security_database_pwdfile
- + process_drm_naming_context_fields
- + process_requests_and_key_records_only
- + "\" . . ."
- + NEWLINE, true );
- } else if( mAppendIdOffsetFlag ) {
- log( "BEGIN \""
- + DRM_TOOL + SPACE
- + DRMTOOL_CFG_FILE + SPACE
- + mDrmtoolCfgFilename + SPACE
- + SOURCE_LDIF_FILE + SPACE
- + mSourceLdifFilename + SPACE
- + TARGET_LDIF_FILE + SPACE
- + mTargetLdifFilename + SPACE
- + LOG_FILE + SPACE
- + mLogFilename + SPACE
- + APPEND_ID_OFFSET + SPACE
- + append_id_offset
- + process_drm_naming_context_fields
- + process_requests_and_key_records_only
- + "\" . . ."
- + NEWLINE, true );
- } else if( mRemoveIdOffsetFlag ) {
- log( "BEGIN \""
- + DRM_TOOL + SPACE
- + DRMTOOL_CFG_FILE + SPACE
- + mDrmtoolCfgFilename + SPACE
- + SOURCE_LDIF_FILE + SPACE
- + mSourceLdifFilename + SPACE
- + TARGET_LDIF_FILE + SPACE
- + mTargetLdifFilename + SPACE
- + LOG_FILE + SPACE
- + mLogFilename + SPACE
- + REMOVE_ID_OFFSET + SPACE
- + remove_id_offset
- + process_drm_naming_context_fields
- + process_requests_and_key_records_only
- + "\" . . ."
- + NEWLINE, true );
+ if (mRewrapFlag && mAppendIdOffsetFlag) {
+ log("BEGIN \""
+ + DRM_TOOL + SPACE
+ + DRMTOOL_CFG_FILE + SPACE
+ + mDrmtoolCfgFilename + SPACE
+ + SOURCE_LDIF_FILE + SPACE
+ + mSourceLdifFilename + SPACE
+ + TARGET_LDIF_FILE + SPACE
+ + mTargetLdifFilename + SPACE
+ + LOG_FILE + SPACE
+ + mLogFilename + SPACE
+ + SOURCE_NSS_DB_PATH + SPACE
+ + mSourcePKISecurityDatabasePath + SPACE
+ + SOURCE_STORAGE_TOKEN_NAME + SPACE
+ + TIC + mSourceStorageTokenName + TIC + SPACE
+ + SOURCE_STORAGE_CERT_NICKNAME + SPACE
+ + TIC + mSourceStorageCertNickname + TIC + SPACE
+ + TARGET_STORAGE_CERTIFICATE_FILE + SPACE
+ + mTargetStorageCertificateFilename + SPACE
+ + use_PKI_security_database_pwdfile
+ + APPEND_ID_OFFSET + SPACE
+ + append_id_offset
+ + process_drm_naming_context_fields
+ + process_requests_and_key_records_only
+ + "\" . . ."
+ + NEWLINE, true);
+ } else if (mRewrapFlag && mRemoveIdOffsetFlag) {
+ log("BEGIN \""
+ + DRM_TOOL + SPACE
+ + DRMTOOL_CFG_FILE + SPACE
+ + mDrmtoolCfgFilename + SPACE
+ + SOURCE_LDIF_FILE + SPACE
+ + mSourceLdifFilename + SPACE
+ + TARGET_LDIF_FILE + SPACE
+ + mTargetLdifFilename + SPACE
+ + LOG_FILE + SPACE
+ + mLogFilename + SPACE
+ + SOURCE_NSS_DB_PATH + SPACE
+ + mSourcePKISecurityDatabasePath + SPACE
+ + SOURCE_STORAGE_TOKEN_NAME + SPACE
+ + TIC + mSourceStorageTokenName + TIC + SPACE
+ + SOURCE_STORAGE_CERT_NICKNAME + SPACE
+ + TIC + mSourceStorageCertNickname + TIC + SPACE
+ + TARGET_STORAGE_CERTIFICATE_FILE + SPACE
+ + mTargetStorageCertificateFilename + SPACE
+ + use_PKI_security_database_pwdfile
+ + REMOVE_ID_OFFSET + SPACE
+ + remove_id_offset
+ + process_drm_naming_context_fields
+ + process_requests_and_key_records_only
+ + "\" . . ."
+ + NEWLINE, true);
+ } else if (mRewrapFlag) {
+ log("BEGIN \""
+ + DRM_TOOL + SPACE
+ + DRMTOOL_CFG_FILE + SPACE
+ + mDrmtoolCfgFilename + SPACE
+ + SOURCE_LDIF_FILE + SPACE
+ + mSourceLdifFilename + SPACE
+ + TARGET_LDIF_FILE + SPACE
+ + mTargetLdifFilename + SPACE
+ + LOG_FILE + SPACE
+ + mLogFilename + SPACE
+ + SOURCE_NSS_DB_PATH + SPACE
+ + mSourcePKISecurityDatabasePath + SPACE
+ + SOURCE_STORAGE_TOKEN_NAME + SPACE
+ + TIC + mSourceStorageTokenName + TIC + SPACE
+ + SOURCE_STORAGE_CERT_NICKNAME + SPACE
+ + TIC + mSourceStorageCertNickname + TIC + SPACE
+ + TARGET_STORAGE_CERTIFICATE_FILE + SPACE
+ + mTargetStorageCertificateFilename
+ + use_PKI_security_database_pwdfile
+ + process_drm_naming_context_fields
+ + process_requests_and_key_records_only
+ + "\" . . ."
+ + NEWLINE, true);
+ } else if (mAppendIdOffsetFlag) {
+ log("BEGIN \""
+ + DRM_TOOL + SPACE
+ + DRMTOOL_CFG_FILE + SPACE
+ + mDrmtoolCfgFilename + SPACE
+ + SOURCE_LDIF_FILE + SPACE
+ + mSourceLdifFilename + SPACE
+ + TARGET_LDIF_FILE + SPACE
+ + mTargetLdifFilename + SPACE
+ + LOG_FILE + SPACE
+ + mLogFilename + SPACE
+ + APPEND_ID_OFFSET + SPACE
+ + append_id_offset
+ + process_drm_naming_context_fields
+ + process_requests_and_key_records_only
+ + "\" . . ."
+ + NEWLINE, true);
+ } else if (mRemoveIdOffsetFlag) {
+ log("BEGIN \""
+ + DRM_TOOL + SPACE
+ + DRMTOOL_CFG_FILE + SPACE
+ + mDrmtoolCfgFilename + SPACE
+ + SOURCE_LDIF_FILE + SPACE
+ + mSourceLdifFilename + SPACE
+ + TARGET_LDIF_FILE + SPACE
+ + mTargetLdifFilename + SPACE
+ + LOG_FILE + SPACE
+ + mLogFilename + SPACE
+ + REMOVE_ID_OFFSET + SPACE
+ + remove_id_offset
+ + process_drm_naming_context_fields
+ + process_requests_and_key_records_only
+ + "\" . . ."
+ + NEWLINE, true);
}
// Process the DRMTOOL config file
success = process_drmtool_config_file();
- if( !success ) {
- log( "FAILED processing drmtool config file!"
- + NEWLINE, true );
+ if (!success) {
+ log("FAILED processing drmtool config file!"
+ + NEWLINE, true);
} else {
- log( "SUCCESSFULLY processed drmtool config file!"
- + NEWLINE, true );
+ log("SUCCESSFULLY processed drmtool config file!"
+ + NEWLINE, true);
// Convert the source LDIF file to a target LDIF file
success = convert_source_ldif_to_target_ldif();
- if( !success ) {
- log( "FAILED converting source LDIF file --> target LDIF file!"
- + NEWLINE, true );
+ if (!success) {
+ log("FAILED converting source LDIF file --> target LDIF file!"
+ + NEWLINE, true);
} else {
- log( "SUCCESSFULLY converted source LDIF file --> "
- + "target LDIF file!"
- + NEWLINE, true );
+ log("SUCCESSFULLY converted source LDIF file --> "
+ + "target LDIF file!"
+ + NEWLINE, true);
}
}
// Finish logging progress
- if( mRewrapFlag && mAppendIdOffsetFlag ) {
- log( "FINISHED \""
- + DRM_TOOL + SPACE
- + DRMTOOL_CFG_FILE + SPACE
- + mDrmtoolCfgFilename + SPACE
- + SOURCE_LDIF_FILE + SPACE
- + mSourceLdifFilename + SPACE
- + TARGET_LDIF_FILE + SPACE
- + mTargetLdifFilename + SPACE
- + LOG_FILE + SPACE
- + mLogFilename + SPACE
- + SOURCE_NSS_DB_PATH + SPACE
- + mSourcePKISecurityDatabasePath + SPACE
- + SOURCE_STORAGE_TOKEN_NAME + SPACE
- + TIC + mSourceStorageTokenName + TIC + SPACE
- + SOURCE_STORAGE_CERT_NICKNAME + SPACE
- + TIC + mSourceStorageCertNickname + TIC + SPACE
- + TARGET_STORAGE_CERTIFICATE_FILE + SPACE
- + mTargetStorageCertificateFilename + SPACE
- + use_PKI_security_database_pwdfile
- + APPEND_ID_OFFSET + SPACE
- + append_id_offset
- + process_drm_naming_context_fields
- + process_requests_and_key_records_only
- + "\"."
- + NEWLINE, true );
- } else if( mRewrapFlag && mRemoveIdOffsetFlag ) {
- log( "FINISHED \""
- + DRM_TOOL + SPACE
- + DRMTOOL_CFG_FILE + SPACE
- + mDrmtoolCfgFilename + SPACE
- + SOURCE_LDIF_FILE + SPACE
- + mSourceLdifFilename + SPACE
- + TARGET_LDIF_FILE + SPACE
- + mTargetLdifFilename + SPACE
- + LOG_FILE + SPACE
- + mLogFilename + SPACE
- + SOURCE_NSS_DB_PATH + SPACE
- + mSourcePKISecurityDatabasePath + SPACE
- + SOURCE_STORAGE_TOKEN_NAME + SPACE
- + TIC + mSourceStorageTokenName + TIC + SPACE
- + SOURCE_STORAGE_CERT_NICKNAME + SPACE
- + TIC + mSourceStorageCertNickname + TIC + SPACE
- + TARGET_STORAGE_CERTIFICATE_FILE + SPACE
- + mTargetStorageCertificateFilename + SPACE
- + use_PKI_security_database_pwdfile
- + REMOVE_ID_OFFSET + SPACE
- + remove_id_offset
- + process_drm_naming_context_fields
- + process_requests_and_key_records_only
- + "\"."
- + NEWLINE, true );
- } else if( mRewrapFlag ) {
- log( "FINISHED \""
- + DRM_TOOL + SPACE
- + DRMTOOL_CFG_FILE + SPACE
- + mDrmtoolCfgFilename + SPACE
- + SOURCE_LDIF_FILE + SPACE
- + mSourceLdifFilename + SPACE
- + TARGET_LDIF_FILE + SPACE
- + mTargetLdifFilename + SPACE
- + LOG_FILE + SPACE
- + mLogFilename + SPACE
- + SOURCE_NSS_DB_PATH + SPACE
- + mSourcePKISecurityDatabasePath + SPACE
- + SOURCE_STORAGE_TOKEN_NAME + SPACE
- + TIC + mSourceStorageTokenName + TIC + SPACE
- + SOURCE_STORAGE_CERT_NICKNAME + SPACE
- + TIC + mSourceStorageCertNickname + TIC + SPACE
- + TARGET_STORAGE_CERTIFICATE_FILE + SPACE
- + mTargetStorageCertificateFilename
- + use_PKI_security_database_pwdfile
- + process_drm_naming_context_fields
- + process_requests_and_key_records_only
- + "\"."
- + NEWLINE, true );
- } else if( mAppendIdOffsetFlag ) {
- log( "FINISHED \""
- + DRM_TOOL + SPACE
- + DRMTOOL_CFG_FILE + SPACE
- + mDrmtoolCfgFilename + SPACE
- + SOURCE_LDIF_FILE + SPACE
- + mSourceLdifFilename + SPACE
- + TARGET_LDIF_FILE + SPACE
- + mTargetLdifFilename + SPACE
- + LOG_FILE + SPACE
- + mLogFilename + SPACE
- + APPEND_ID_OFFSET + SPACE
- + append_id_offset
- + process_drm_naming_context_fields
- + process_requests_and_key_records_only
- + "\"."
- + NEWLINE, true );
- } else if( mRemoveIdOffsetFlag ) {
- log( "FINISHED \""
- + DRM_TOOL + SPACE
- + DRMTOOL_CFG_FILE + SPACE
- + mDrmtoolCfgFilename + SPACE
- + SOURCE_LDIF_FILE + SPACE
- + mSourceLdifFilename + SPACE
- + TARGET_LDIF_FILE + SPACE
- + mTargetLdifFilename + SPACE
- + LOG_FILE + SPACE
- + mLogFilename + SPACE
- + REMOVE_ID_OFFSET + SPACE
- + remove_id_offset
- + process_drm_naming_context_fields
- + process_requests_and_key_records_only
- + "\"."
- + NEWLINE, true );
+ if (mRewrapFlag && mAppendIdOffsetFlag) {
+ log("FINISHED \""
+ + DRM_TOOL + SPACE
+ + DRMTOOL_CFG_FILE + SPACE
+ + mDrmtoolCfgFilename + SPACE
+ + SOURCE_LDIF_FILE + SPACE
+ + mSourceLdifFilename + SPACE
+ + TARGET_LDIF_FILE + SPACE
+ + mTargetLdifFilename + SPACE
+ + LOG_FILE + SPACE
+ + mLogFilename + SPACE
+ + SOURCE_NSS_DB_PATH + SPACE
+ + mSourcePKISecurityDatabasePath + SPACE
+ + SOURCE_STORAGE_TOKEN_NAME + SPACE
+ + TIC + mSourceStorageTokenName + TIC + SPACE
+ + SOURCE_STORAGE_CERT_NICKNAME + SPACE
+ + TIC + mSourceStorageCertNickname + TIC + SPACE
+ + TARGET_STORAGE_CERTIFICATE_FILE + SPACE
+ + mTargetStorageCertificateFilename + SPACE
+ + use_PKI_security_database_pwdfile
+ + APPEND_ID_OFFSET + SPACE
+ + append_id_offset
+ + process_drm_naming_context_fields
+ + process_requests_and_key_records_only
+ + "\"."
+ + NEWLINE, true);
+ } else if (mRewrapFlag && mRemoveIdOffsetFlag) {
+ log("FINISHED \""
+ + DRM_TOOL + SPACE
+ + DRMTOOL_CFG_FILE + SPACE
+ + mDrmtoolCfgFilename + SPACE
+ + SOURCE_LDIF_FILE + SPACE
+ + mSourceLdifFilename + SPACE
+ + TARGET_LDIF_FILE + SPACE
+ + mTargetLdifFilename + SPACE
+ + LOG_FILE + SPACE
+ + mLogFilename + SPACE
+ + SOURCE_NSS_DB_PATH + SPACE
+ + mSourcePKISecurityDatabasePath + SPACE
+ + SOURCE_STORAGE_TOKEN_NAME + SPACE
+ + TIC + mSourceStorageTokenName + TIC + SPACE
+ + SOURCE_STORAGE_CERT_NICKNAME + SPACE
+ + TIC + mSourceStorageCertNickname + TIC + SPACE
+ + TARGET_STORAGE_CERTIFICATE_FILE + SPACE
+ + mTargetStorageCertificateFilename + SPACE
+ + use_PKI_security_database_pwdfile
+ + REMOVE_ID_OFFSET + SPACE
+ + remove_id_offset
+ + process_drm_naming_context_fields
+ + process_requests_and_key_records_only
+ + "\"."
+ + NEWLINE, true);
+ } else if (mRewrapFlag) {
+ log("FINISHED \""
+ + DRM_TOOL + SPACE
+ + DRMTOOL_CFG_FILE + SPACE
+ + mDrmtoolCfgFilename + SPACE
+ + SOURCE_LDIF_FILE + SPACE
+ + mSourceLdifFilename + SPACE
+ + TARGET_LDIF_FILE + SPACE
+ + mTargetLdifFilename + SPACE
+ + LOG_FILE + SPACE
+ + mLogFilename + SPACE
+ + SOURCE_NSS_DB_PATH + SPACE
+ + mSourcePKISecurityDatabasePath + SPACE
+ + SOURCE_STORAGE_TOKEN_NAME + SPACE
+ + TIC + mSourceStorageTokenName + TIC + SPACE
+ + SOURCE_STORAGE_CERT_NICKNAME + SPACE
+ + TIC + mSourceStorageCertNickname + TIC + SPACE
+ + TARGET_STORAGE_CERTIFICATE_FILE + SPACE
+ + mTargetStorageCertificateFilename
+ + use_PKI_security_database_pwdfile
+ + process_drm_naming_context_fields
+ + process_requests_and_key_records_only
+ + "\"."
+ + NEWLINE, true);
+ } else if (mAppendIdOffsetFlag) {
+ log("FINISHED \""
+ + DRM_TOOL + SPACE
+ + DRMTOOL_CFG_FILE + SPACE
+ + mDrmtoolCfgFilename + SPACE
+ + SOURCE_LDIF_FILE + SPACE
+ + mSourceLdifFilename + SPACE
+ + TARGET_LDIF_FILE + SPACE
+ + mTargetLdifFilename + SPACE
+ + LOG_FILE + SPACE
+ + mLogFilename + SPACE
+ + APPEND_ID_OFFSET + SPACE
+ + append_id_offset
+ + process_drm_naming_context_fields
+ + process_requests_and_key_records_only
+ + "\"."
+ + NEWLINE, true);
+ } else if (mRemoveIdOffsetFlag) {
+ log("FINISHED \""
+ + DRM_TOOL + SPACE
+ + DRMTOOL_CFG_FILE + SPACE
+ + mDrmtoolCfgFilename + SPACE
+ + SOURCE_LDIF_FILE + SPACE
+ + mSourceLdifFilename + SPACE
+ + TARGET_LDIF_FILE + SPACE
+ + mTargetLdifFilename + SPACE
+ + LOG_FILE + SPACE
+ + mLogFilename + SPACE
+ + REMOVE_ID_OFFSET + SPACE
+ + remove_id_offset
+ + process_drm_naming_context_fields
+ + process_requests_and_key_records_only
+ + "\"."
+ + NEWLINE, true);
}
// Shutdown logging process
- close_log( mLogFilename );
+ close_log(mLogFilename);
}
}
-
diff --git a/pki/base/java-tools/src/com/netscape/cmstools/ExtJoiner.java b/pki/base/java-tools/src/com/netscape/cmstools/ExtJoiner.java
index f7f90a52..0dde4377 100644
--- a/pki/base/java-tools/src/com/netscape/cmstools/ExtJoiner.java
+++ b/pki/base/java-tools/src/com/netscape/cmstools/ExtJoiner.java
@@ -17,31 +17,29 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmstools;
-
import java.io.FileInputStream;
import java.io.IOException;
import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
-
/**
- * This program joins a sequence of extensions together
- * so that the final output can be used in configuration
- * wizard for specifing extra extensions in default
+ * This program joins a sequence of extensions together so that the final output
+ * can be used in configuration wizard for specifing extra extensions in default
* certificates (i.e. CA certificate, SSL certificate).
- *
+ *
* Usage:
+ *
* <pre>
* ExtJoiner \
* &lt;ext_file0&gt; &lt;ext_file1&gt; ... &lt;ext_fileN&gt;
- *
+ *
* where,
* &lt;ext_file&gt; is a file that has the base64
* encoded DER encoding of an X509 Extension
*
* ExtensionSequence ::= SEQUENCE OF Extension;
- *
+ *
* 0 30 142: SEQUENCE {
* 3 30 69: SEQUENCE {
* 5 06 3: OBJECT IDENTIFIER issuerAltName (2 5 29 18)
@@ -61,7 +59,7 @@ import netscape.security.util.DerValue;
* : }
* : }
* </pre>
- *
+ *
* @version $Revision$, $Date$
*/
public class ExtJoiner {
@@ -88,8 +86,8 @@ public class ExtJoiner {
}
}
- public static byte[] getFileData(String fileName)
- throws IOException {
+ public static byte[] getFileData(String fileName)
+ throws IOException {
FileInputStream fis = new FileInputStream(fileName);
byte data[] = new byte[fis.available()];
@@ -98,6 +96,6 @@ public class ExtJoiner {
} finally {
fis.close();
}
- return com.netscape.osutil.OSUtil.AtoB(new String(data));
+ return com.netscape.osutil.OSUtil.AtoB(new String(data));
}
}
diff --git a/pki/base/java-tools/src/com/netscape/cmstools/GenExtKeyUsage.java b/pki/base/java-tools/src/com/netscape/cmstools/GenExtKeyUsage.java
index 9fffce3f..97f5f9c3 100644
--- a/pki/base/java-tools/src/com/netscape/cmstools/GenExtKeyUsage.java
+++ b/pki/base/java-tools/src/com/netscape/cmstools/GenExtKeyUsage.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmstools;
-
import java.util.Vector;
import netscape.security.util.DerOutputStream;
@@ -25,14 +24,12 @@ import netscape.security.util.DerValue;
import netscape.security.util.ObjectIdentifier;
import netscape.security.x509.Extension;
-
/**
- * Generates a DER-encoded Extended Key Usage extension.
- * The first parameter is the criticality of the extension, true or false.
- * The OIDs to be included in the extension are passed as command-line
- * arguments. The OIDs are described in RFC 2459. For example,
- * the OID for code signing is 1.3.6.1.5.5.7.3.3.
- *
+ * Generates a DER-encoded Extended Key Usage extension. The first parameter is
+ * the criticality of the extension, true or false. The OIDs to be included in
+ * the extension are passed as command-line arguments. The OIDs are described in
+ * RFC 2459. For example, the OID for code signing is 1.3.6.1.5.5.7.3.3.
+ *
* @version $Revision$, $Date$
*/
public class GenExtKeyUsage {
@@ -42,7 +39,7 @@ public class GenExtKeyUsage {
if (args.length < 2) {
System.out.println("Usage: GenExtKeyUsage [true|false] <OID> ...");
System.exit(-1);
- }
+ }
boolean critical = false;
diff --git a/pki/base/java-tools/src/com/netscape/cmstools/GenIssuerAltNameExt.java b/pki/base/java-tools/src/com/netscape/cmstools/GenIssuerAltNameExt.java
index 60913224..4006e885 100644
--- a/pki/base/java-tools/src/com/netscape/cmstools/GenIssuerAltNameExt.java
+++ b/pki/base/java-tools/src/com/netscape/cmstools/GenIssuerAltNameExt.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmstools;
-
import java.io.ByteArrayOutputStream;
import java.net.InetAddress;
@@ -32,17 +31,16 @@ import netscape.security.x509.RFC822Name;
import netscape.security.x509.URIName;
import netscape.security.x509.X500Name;
-
/**
- * This program generates an issuer alternative name extension
- * in base-64 encoding. The encoding output can be used with
- * the configuration wizard.
- *
+ * This program generates an issuer alternative name extension in base-64
+ * encoding. The encoding output can be used with the configuration wizard.
+ *
* Usage:
+ *
* <pre>
* GenIssuerAltNameExt \
* &lt;general_type0&gt; &lt;general_name0&gt; ... &lt;general_typeN&gt; &lt;general_nameN&gt;
- *
+ *
* where,
* &lt;general_type&gt; can be one of the following string:
* DNSName
@@ -54,7 +52,7 @@ import netscape.security.x509.X500Name;
* X500Name
* &lt;general_name&gt; is string
* </pre>
- *
+ *
* @version $Revision$, $Date$
*/
public class GenIssuerAltNameExt {
@@ -68,15 +66,15 @@ public class GenIssuerAltNameExt {
GeneralNames gns = new GeneralNames();
for (int i = 0; i < args.length; i += 2) {
- GeneralNameInterface gni =
- buildGeneralNameInterface(
- args[i], args[i + 1]);
+ GeneralNameInterface gni =
+ buildGeneralNameInterface(
+ args[i], args[i + 1]);
gns.addElement(gni);
}
- IssuerAlternativeNameExtension sane =
- new IssuerAlternativeNameExtension(gns);
+ IssuerAlternativeNameExtension sane =
+ new IssuerAlternativeNameExtension(gns);
output(sane);
} catch (Exception e) {
@@ -85,14 +83,14 @@ public class GenIssuerAltNameExt {
}
public static void output(IssuerAlternativeNameExtension ext)
- throws Exception {
- ByteArrayOutputStream os = new ByteArrayOutputStream();
+ throws Exception {
+ ByteArrayOutputStream os = new ByteArrayOutputStream();
ext.encode(os);
System.out.println(
- com.netscape.osutil.OSUtil.BtoA(os.toByteArray())
- );
+ com.netscape.osutil.OSUtil.BtoA(os.toByteArray())
+ );
}
public static void doUsage() {
@@ -111,7 +109,7 @@ public class GenIssuerAltNameExt {
}
public static GeneralNameInterface buildGeneralNameInterface(
- String type, String value) throws Exception {
+ String type, String value) throws Exception {
if (type.equals("DNSName")) {
return new DNSName(value);
} else if (type.equals("EDIPartyName")) {
@@ -129,8 +127,8 @@ public class GenIssuerAltNameExt {
} else if (type.equals("X500Name")) {
return new X500Name(value);
} else {
- System.out.println("Error: unknown general_type " +
- type);
+ System.out.println("Error: unknown general_type " +
+ type);
doUsage();
System.exit(0);
return null;
diff --git a/pki/base/java-tools/src/com/netscape/cmstools/GenSubjectAltNameExt.java b/pki/base/java-tools/src/com/netscape/cmstools/GenSubjectAltNameExt.java
index 52fefe57..81efda4c 100644
--- a/pki/base/java-tools/src/com/netscape/cmstools/GenSubjectAltNameExt.java
+++ b/pki/base/java-tools/src/com/netscape/cmstools/GenSubjectAltNameExt.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmstools;
-
import java.io.ByteArrayOutputStream;
import java.net.InetAddress;
@@ -32,17 +31,16 @@ import netscape.security.x509.SubjectAlternativeNameExtension;
import netscape.security.x509.URIName;
import netscape.security.x509.X500Name;
-
/**
- * This program generates an subject alternative name extension
- * in base-64 encoding. The encoding output can be used with
- * the configuration wizard.
- *
+ * This program generates an subject alternative name extension in base-64
+ * encoding. The encoding output can be used with the configuration wizard.
+ *
* Usage:
+ *
* <pre>
* GenSubjectAltNameExt \
* &lt;general_type0&gt; &lt;general_name0&gt; ... &lt;general_typeN&gt; &lt;general_nameN&gt;
- *
+ *
* where,
* &lt;general_type&gt; can be one of the following string:
* DNSName
@@ -54,7 +52,7 @@ import netscape.security.x509.X500Name;
* X500Name
* &lt;general_name&gt; is string
* </pre>
- *
+ *
* @version $Revision$, $Date$
*/
public class GenSubjectAltNameExt {
@@ -68,15 +66,15 @@ public class GenSubjectAltNameExt {
GeneralNames gns = new GeneralNames();
for (int i = 0; i < args.length; i += 2) {
- GeneralNameInterface gni =
- buildGeneralNameInterface(
- args[i], args[i + 1]);
+ GeneralNameInterface gni =
+ buildGeneralNameInterface(
+ args[i], args[i + 1]);
gns.addElement(gni);
}
- SubjectAlternativeNameExtension sane =
- new SubjectAlternativeNameExtension(gns);
+ SubjectAlternativeNameExtension sane =
+ new SubjectAlternativeNameExtension(gns);
output(sane);
} catch (Exception e) {
@@ -85,14 +83,14 @@ public class GenSubjectAltNameExt {
}
public static void output(SubjectAlternativeNameExtension ext)
- throws Exception {
- ByteArrayOutputStream os = new ByteArrayOutputStream();
+ throws Exception {
+ ByteArrayOutputStream os = new ByteArrayOutputStream();
ext.encode(os);
System.out.println(
- com.netscape.osutil.OSUtil.BtoA(os.toByteArray())
- );
+ com.netscape.osutil.OSUtil.BtoA(os.toByteArray())
+ );
}
public static void doUsage() {
@@ -111,7 +109,7 @@ public class GenSubjectAltNameExt {
}
public static GeneralNameInterface buildGeneralNameInterface(
- String type, String value) throws Exception {
+ String type, String value) throws Exception {
if (type.equals("DNSName")) {
return new DNSName(value);
} else if (type.equals("EDIPartyName")) {
@@ -129,8 +127,8 @@ public class GenSubjectAltNameExt {
} else if (type.equals("X500Name")) {
return new X500Name(value);
} else {
- System.out.println("Error: unknown general_type " +
- type);
+ System.out.println("Error: unknown general_type " +
+ type);
doUsage();
System.exit(0);
return null;
diff --git a/pki/base/java-tools/src/com/netscape/cmstools/HttpClient.java b/pki/base/java-tools/src/com/netscape/cmstools/HttpClient.java
index 0b9d3932..965bb2ca 100644
--- a/pki/base/java-tools/src/com/netscape/cmstools/HttpClient.java
+++ b/pki/base/java-tools/src/com/netscape/cmstools/HttpClient.java
@@ -42,19 +42,17 @@ import org.mozilla.jss.ssl.SSLHandshakeCompletedListener;
import org.mozilla.jss.ssl.SSLSocket;
import org.mozilla.jss.util.Password;
-
/**
* This class implements a CMC Enroll client for testing.
- *
+ *
* @version $Revision$, $Date$
*/
-public class HttpClient
-{
+public class HttpClient {
private String _host = null;
private int _port = 0;
private boolean _secure = false;
- public static final int ARGC = 1;
+ public static final int ARGC = 1;
static final int cipherSuites[] = {
SSLSocket.SSL3_RSA_WITH_RC4_128_MD5,
SSLSocket.SSL3_RSA_WITH_3DES_EDE_CBC_SHA,
@@ -65,9 +63,8 @@ public class HttpClient
0
};
- public HttpClient(String host, int port, String secure)
- throws Exception
- {
+ public HttpClient(String host, int port, String secure)
+ throws Exception {
_host = host;
_port = port;
if (secure.equals("true"))
@@ -81,81 +78,77 @@ public class HttpClient
long length = file.length();
if (length > Integer.MAX_VALUE) {
- throw new IOException("Input file " + filename +
- " is too large. Must be smaller than " + Integer.MAX_VALUE);
+ throw new IOException("Input file " + filename +
+ " is too large. Must be smaller than " + Integer.MAX_VALUE);
}
- byte[] bytes = new byte[(int)length];
+ byte[] bytes = new byte[(int) length];
int offset = 0;
int numRead = 0;
while (offset < bytes.length
- && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
+ && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
if (offset < bytes.length) {
- throw new IOException("Could not completely read file "+filename);
+ throw new IOException("Could not completely read file " + filename);
}
is.close();
return bytes;
}
+ public void send(String ifilename, String ofilename, String dbdir,
+ String nickname, String password, String servlet, String clientmode)
+ throws Exception {
+ byte[] b = getBytesFromFile(ifilename);
- public void send(String ifilename, String ofilename, String dbdir,
- String nickname, String password, String servlet, String clientmode)
- throws Exception
- {
- byte[] b = getBytesFromFile(ifilename);
-
- System.out.println("Total number of bytes read = "+b.length);
+ System.out.println("Total number of bytes read = " + b.length);
DataOutputStream dos = null;
InputStream is = null;
if (_secure) {
try {
CryptoManager.InitializationValues vals =
- new CryptoManager.InitializationValues(dbdir, "", "", "secmod.db");
+ new CryptoManager.InitializationValues(dbdir, "", "", "secmod.db");
CryptoManager.initialize(vals);
SSLSocket socket = new SSLSocket(_host, _port);
int i;
- for (i = SSLSocket.SSL2_RC4_128_WITH_MD5;
- i <= SSLSocket.SSL2_RC2_128_CBC_EXPORT40_WITH_MD5; ++i) {
+ for (i = SSLSocket.SSL2_RC4_128_WITH_MD5; i <= SSLSocket.SSL2_RC2_128_CBC_EXPORT40_WITH_MD5; ++i) {
try {
socket.setCipherPreference(i, true);
- } catch( SocketException e) {
+ } catch (SocketException e) {
}
}
- //skip SSL_EN_IDEA_128_EDE3_CBC_WITH_MD5
- for (i = SSLSocket.SSL2_DES_64_CBC_WITH_MD5;
- i <= SSLSocket.SSL2_DES_192_EDE3_CBC_WITH_MD5; ++i) {
- try {
+ // skip SSL_EN_IDEA_128_EDE3_CBC_WITH_MD5
+ for (i = SSLSocket.SSL2_DES_64_CBC_WITH_MD5; i <= SSLSocket.SSL2_DES_192_EDE3_CBC_WITH_MD5; ++i) {
+ try {
socket.setCipherPreference(i, true);
- } catch( SocketException e) {
+ } catch (SocketException e) {
}
}
for (i = 0; cipherSuites[i] != 0; ++i) {
try {
socket.setCipherPreference(cipherSuites[i], true);
- } catch( SocketException e) {
+ } catch (SocketException e) {
}
}
SSLHandshakeCompletedListener listener = new ClientHandshakeCB(this);
- socket.addHandshakeCompletedListener(listener);
+ socket.addHandshakeCompletedListener(listener);
if (clientmode != null && clientmode.equals("true")) {
CryptoManager cm = CryptoManager.getInstance();
CryptoToken token = cm.getInternalKeyStorageToken();
- Password pass = new Password(password.toCharArray());
+ Password pass = new Password(password.toCharArray());
token.login(pass);
- CryptoStore store = token.getCryptoStore();
- X509Certificate cert = cm.findCertByNickname(nickname);
+ CryptoStore store = token.getCryptoStore();
+ X509Certificate cert = cm.findCertByNickname(nickname);
if (cert == null)
- System.out.println("client cert is null");
+ System.out.println("client cert is null");
else
- System.out.println("client cert is not null");
+ System.out.println("client cert is not null");
socket.setUseClientMode(true);
socket.setClientCertNickname(nickname);
}
@@ -164,7 +157,7 @@ public class HttpClient
dos = new DataOutputStream(socket.getOutputStream());
is = socket.getInputStream();
} catch (Exception e) {
- System.out.println("Exception: "+e.toString());
+ System.out.println("Exception: " + e.toString());
return;
}
} else {
@@ -173,17 +166,17 @@ public class HttpClient
is = socket.getInputStream();
}
- // send request
+ // send request
if (servlet == null) {
System.out.println("Missing servlet name.");
printUsage();
} else {
- String s = "POST "+servlet+" HTTP/1.0\r\n";
+ String s = "POST " + servlet + " HTTP/1.0\r\n";
dos.writeBytes(s);
- }
- dos.writeBytes("Content-length: " + b.length + "\r\n");
- dos.writeBytes("\r\n");
- dos.write(b);
+ }
+ dos.writeBytes("Content-length: " + b.length + "\r\n");
+ dos.writeBytes("\r\n");
+ dos.write(b);
dos.flush();
FileOutputStream fof = new FileOutputStream(ofilename);
@@ -191,8 +184,7 @@ public class HttpClient
int sum = 0;
boolean hack = false;
try {
- while (true)
- {
+ while (true) {
int r = is.read();
if (r == -1)
break;
@@ -217,7 +209,7 @@ public class HttpClient
fof.close();
byte[] bout = getBytesFromFile(ofilename);
- System.out.println("Total number of bytes read = "+ bout.length);
+ System.out.println("Total number of bytes read = " + bout.length);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(bs);
@@ -225,7 +217,7 @@ public class HttpClient
System.out.println(bs.toString());
System.out.println("");
- System.out.println("The response in binary format is stored in "+ofilename);
+ System.out.println("The response in binary format is stored in " + ofilename);
System.out.println("");
}
@@ -273,17 +265,16 @@ public class HttpClient
System.exit(0);
}
- public static void main(String args[])
- {
- String host = null, portstr = null, secure = null, dbdir = null, nickname = null ;
+ public static void main(String args[]) {
+ String host = null, portstr = null, secure = null, dbdir = null, nickname = null;
String password = null, ofilename = null, ifilename = null;
String servlet = null;
String clientmode = null;
- System.out.println("");
+ System.out.println("");
// Check that the correct # of arguments were submitted to the program
- if( args.length != ( ARGC ) ) {
+ if (args.length != (ARGC)) {
System.out.println("Wrong number of parameters:" + args.length);
printUsage();
}
@@ -293,9 +284,9 @@ public class HttpClient
try {
reader = new BufferedReader(new InputStreamReader(
new BufferedInputStream(
- new FileInputStream(configFile))));
+ new FileInputStream(configFile))));
} catch (FileNotFoundException e) {
- System.out.println("HttpClient: can't find configuration file: "+configFile);
+ System.out.println("HttpClient: can't find configuration file: " + configFile);
printUsage();
System.exit(1);
} catch (Exception e) {
@@ -314,7 +305,7 @@ public class HttpClient
String name = tokenizer.nextToken();
String val = null;
if (tokenizer.countTokens() > 0)
- val = tokenizer.nextToken();
+ val = tokenizer.nextToken();
if (name.equals("host")) {
host = val;
} else if (name.equals("port")) {
@@ -370,7 +361,7 @@ public class HttpClient
}
int port = Integer.parseInt(portstr);
-
+
if (secure != null && secure.equals("true")) {
if (dbdir == null) {
System.out.println("Missing directory name for the cert7.db.");
@@ -390,8 +381,8 @@ public class HttpClient
}
try {
- HttpClient client =
- new HttpClient(host, port, secure);
+ HttpClient client =
+ new HttpClient(host, port, secure);
client.send(ifilename, ofilename, dbdir, nickname, password, servlet, clientmode);
} catch (Exception e) {
System.out.println("Error: " + e.toString());
diff --git a/pki/base/java-tools/src/com/netscape/cmstools/OCSPClient.java b/pki/base/java-tools/src/com/netscape/cmstools/OCSPClient.java
index df18a3e5..82ec0fec 100644
--- a/pki/base/java-tools/src/com/netscape/cmstools/OCSPClient.java
+++ b/pki/base/java-tools/src/com/netscape/cmstools/OCSPClient.java
@@ -56,232 +56,221 @@ import com.netscape.cmsutil.ocsp.SingleResponse;
import com.netscape.cmsutil.ocsp.TBSRequest;
import com.netscape.cmsutil.ocsp.UnknownInfo;
-
/**
* This class implements a OCSP client for testing.
- *
+ *
* @version $Revision$, $Date$
*/
-public class OCSPClient
-{
+public class OCSPClient {
private String _host = null;
private int _port = 0;
- public OCSPClient(String host, int port, String dbdir)
- throws Exception
- {
+ public OCSPClient(String host, int port, String dbdir)
+ throws Exception {
_host = host;
_port = port;
CryptoManager.initialize(dbdir);
}
- public void send(String uri, String nickname, int serialno, String output)
- throws Exception
- {
- CryptoManager manager = CryptoManager.getInstance();
+ public void send(String uri, String nickname, int serialno, String output)
+ throws Exception {
+ CryptoManager manager = CryptoManager.getInstance();
X509Certificate caCert = manager.findCertByNickname(nickname);
OCSPRequest request = getOCSPRequest(caCert, serialno);
- ByteArrayOutputStream os = new ByteArrayOutputStream();
- request.encode(os);
- byte request_data[] = os.toByteArray();
+ ByteArrayOutputStream os = new ByteArrayOutputStream();
+ request.encode(os);
+ byte request_data[] = os.toByteArray();
sendOCSPRequest(uri, _host, _port, request_data, output);
}
- public void sendRequestData(String uri, String nickname, byte request_data[], String output)
- throws Exception
- {
+ public void sendRequestData(String uri, String nickname, byte request_data[], String output)
+ throws Exception {
sendOCSPRequest(uri, _host, _port, request_data, output);
}
- public OCSPRequest getOCSPRequest(X509Certificate caCert, int serialno)
- throws Exception
- {
+ public OCSPRequest getOCSPRequest(X509Certificate caCert, int serialno)
+ throws Exception {
MessageDigest md = MessageDigest.getInstance("SHA");
- // calculate issuer key hash
+ // calculate issuer key hash
X509CertImpl x509Cert = new X509CertImpl(caCert.getEncoded());
- X509Key x509key = (X509Key)x509Cert.getPublicKey();
+ X509Key x509key = (X509Key) x509Cert.getPublicKey();
byte issuerKeyHash[] = md.digest(x509key.getKey());
// calculate name hash
- X500Name name = (X500Name)x509Cert.getSubjectDN();
+ X500Name name = (X500Name) x509Cert.getSubjectDN();
byte issuerNameHash[] = md.digest(name.getEncoded());
// constructing the OCSP request
CertID certid = new CertID(
- new AlgorithmIdentifier(
- new OBJECT_IDENTIFIER("1.3.14.3.2.26"), new NULL()),
- new OCTET_STRING(issuerNameHash),
- new OCTET_STRING(issuerKeyHash),
+ new AlgorithmIdentifier(
+ new OBJECT_IDENTIFIER("1.3.14.3.2.26"), new NULL()),
+ new OCTET_STRING(issuerNameHash),
+ new OCTET_STRING(issuerKeyHash),
new INTEGER(serialno));
Request request = new Request(certid, null);
SEQUENCE requestList = new SEQUENCE();
requestList.addElement(request);
- TBSRequest tbsRequest = new TBSRequest(null,null,requestList,null);
+ TBSRequest tbsRequest = new TBSRequest(null, null, requestList, null);
return new OCSPRequest(tbsRequest, null);
}
- public void sendOCSPRequest(String uri, String host, int port,
- byte request_data[], String output) throws Exception
- {
+ public void sendOCSPRequest(String uri, String host, int port,
+ byte request_data[], String output) throws Exception {
Socket socket = new Socket(host, port);
- // send request
+ // send request
System.out.println("URI: " + uri);
- DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
- dos.writeBytes("POST " + uri + " HTTP/1.0\r\n");
- dos.writeBytes("Content-length: " + request_data.length + "\r\n");
- dos.writeBytes("\r\n");
- dos.write(request_data);
+ DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
+ dos.writeBytes("POST " + uri + " HTTP/1.0\r\n");
+ dos.writeBytes("Content-length: " + request_data.length + "\r\n");
+ dos.writeBytes("\r\n");
+ dos.write(request_data);
dos.flush();
System.out.println("Data Length: " + request_data.length);
System.out.println("Data: " + com.netscape.osutil.OSUtil.BtoA(request_data));
- InputStream iiss = socket.getInputStream();
+ InputStream iiss = socket.getInputStream();
FileOutputStream fof = new FileOutputStream(output);
- boolean startSaving = false;
- int sum = 0;
- boolean hack = false;
- try {
- while (true)
- {
- int r = iiss.read();
- if (r == -1)
- break;
- if (r == 10) {
- sum++;
- }
- if (sum == 6) {
- startSaving = true;
- continue;
- }
- if (startSaving) {
- if (hack) {
- fof.write(r);
- }
- if (hack == false) {
- hack = true;
- }
- }
- } // while
- } catch (IOException e) {
- }
+ boolean startSaving = false;
+ int sum = 0;
+ boolean hack = false;
+ try {
+ while (true) {
+ int r = iiss.read();
+ if (r == -1)
+ break;
+ if (r == 10) {
+ sum++;
+ }
+ if (sum == 6) {
+ startSaving = true;
+ continue;
+ }
+ if (startSaving) {
+ if (hack) {
+ fof.write(r);
+ }
+ if (hack == false) {
+ hack = true;
+ }
+ }
+ } // while
+ } catch (IOException e) {
+ }
fof.close();
- // parse OCSPResponse
+ // parse OCSPResponse
BufferedInputStream fis =
- new BufferedInputStream(
- new FileInputStream(output));
+ new BufferedInputStream(
+ new FileInputStream(output));
OCSPResponse resp = (OCSPResponse)
- OCSPResponse.getTemplate().decode(fis);
- OCSPResponseStatus status = resp.getResponseStatus();
+ OCSPResponse.getTemplate().decode(fis);
+ OCSPResponseStatus status = resp.getResponseStatus();
ResponseBytes bytes = resp.getResponseBytes();
- BasicOCSPResponse basic = (BasicOCSPResponse)
- BasicOCSPResponse.getTemplate().decode(
- new ByteArrayInputStream(bytes.getResponse().toByteArray()));
+ BasicOCSPResponse basic = (BasicOCSPResponse)
+ BasicOCSPResponse.getTemplate().decode(
+ new ByteArrayInputStream(bytes.getResponse().toByteArray()));
ResponseData rd = basic.getResponseData();
for (int i = 0; i < rd.getResponseCount(); i++) {
- SingleResponse rd1 = rd.getResponseAt(i);
- System.out.println("CertID.serialNumber=" +
- rd1.getCertID().getSerialNumber());
- CertStatus status1 = rd1.getCertStatus();
- if (status1 instanceof GoodInfo) {
- System.out.println("CertStatus=Good");
- }
- if (status1 instanceof UnknownInfo) {
- System.out.println("CertStatus=Unknown");
- }
- if (status1 instanceof RevokedInfo) {
- System.out.println("CertStatus=Revoked");
- }
+ SingleResponse rd1 = rd.getResponseAt(i);
+ System.out.println("CertID.serialNumber=" +
+ rd1.getCertID().getSerialNumber());
+ CertStatus status1 = rd1.getCertStatus();
+ if (status1 instanceof GoodInfo) {
+ System.out.println("CertStatus=Good");
+ }
+ if (status1 instanceof UnknownInfo) {
+ System.out.println("CertStatus=Unknown");
+ }
+ if (status1 instanceof RevokedInfo) {
+ System.out.println("CertStatus=Revoked");
+ }
}
}
- public static void printUsage()
- {
- System.out.println("Usage: OCSPClient " +
- "<host> <port> <dbdir> <nickname> <serialno_or_filename> <output> <times>");
- System.out.println(" <host> = OCSP server hostname");
- System.out.println(" <port> = OCSP server port number");
- System.out.println(" <dbdir> = Certificate Database Directory");
- System.out.println(" <nickname> = Nickname of CA Certificate");
- System.out.println(" <serialno_or_filename> = Serial Number Being Checked, Or Name of file that contains the request");
- System.out.println(" <output> = Filename of Response in DER encoding");
- System.out.println(" <times> = Submit Request Multiple Times");
- System.out.println(" [<uri>] = OCSP Service URI (i.e. /ocsp/ee/ocsp)");
+ public static void printUsage() {
+ System.out.println("Usage: OCSPClient " +
+ "<host> <port> <dbdir> <nickname> <serialno_or_filename> <output> <times>");
+ System.out.println(" <host> = OCSP server hostname");
+ System.out.println(" <port> = OCSP server port number");
+ System.out.println(" <dbdir> = Certificate Database Directory");
+ System.out.println(" <nickname> = Nickname of CA Certificate");
+ System.out.println(" <serialno_or_filename> = Serial Number Being Checked, Or Name of file that contains the request");
+ System.out.println(" <output> = Filename of Response in DER encoding");
+ System.out.println(" <times> = Submit Request Multiple Times");
+ System.out.println(" [<uri>] = OCSP Service URI (i.e. /ocsp/ee/ocsp)");
}
- public static void main(String args[])
- {
- if (args.length != 7 && args.length !=8 )
- {
+ public static void main(String args[]) {
+ if (args.length != 7 && args.length != 8) {
System.out.println("ERROR: Invalid number of arguments - got "
+ args.length + " expected 7!");
for (int i = 0; i < args.length; i++) {
- System.out.println("arg[" + i + "]=" + args[i]);
+ System.out.println("arg[" + i + "]=" + args[i]);
}
printUsage();
- System.exit(0);
+ System.exit(0);
}
String host = args[0];
int port = -1;
try {
- port = Integer.parseInt(args[1]);
+ port = Integer.parseInt(args[1]);
} catch (Exception e) {
- System.out.println("Error: Invalid Port Number");
- printUsage();
- System.exit(0);
+ System.out.println("Error: Invalid Port Number");
+ printUsage();
+ System.exit(0);
}
String dbdir = args[2];
String nickname = args[3];
int serialno = -1;
byte data[] = null;
try {
- serialno = Integer.parseInt(args[4]);
+ serialno = Integer.parseInt(args[4]);
} catch (Exception e) {
- try {
- System.out.println("Warning: Serial Number not found. It may be a filename.");
- /* it could be a file name */
- FileInputStream fis = new FileInputStream(args[4]);
- System.out.println("File Size: " + fis.available());
- data = new byte[fis.available()];
- fis.read(data);
- } catch (Exception e1) {
- System.out.println("Error: Invalid Serial Number or File Name");
- printUsage();
- System.exit(0);
- }
+ try {
+ System.out.println("Warning: Serial Number not found. It may be a filename.");
+ /* it could be a file name */
+ FileInputStream fis = new FileInputStream(args[4]);
+ System.out.println("File Size: " + fis.available());
+ data = new byte[fis.available()];
+ fis.read(data);
+ } catch (Exception e1) {
+ System.out.println("Error: Invalid Serial Number or File Name");
+ printUsage();
+ System.exit(0);
+ }
}
String output = args[5];
int times = 1;
try {
- times = Integer.parseInt(args[6]);
+ times = Integer.parseInt(args[6]);
} catch (Exception e) {
- System.out.println("Error: Invalid Times");
- printUsage();
- System.exit(0);
+ System.out.println("Error: Invalid Times");
+ printUsage();
+ System.exit(0);
}
String uri = "/ocsp/ee/ocsp";
if (args.length > 7) {
- uri = args[7];
+ uri = args[7];
}
try {
- OCSPClient client =
- new OCSPClient(host, port, dbdir);
- for (int i = 0; i < times; i ++) {
- if (data != null) {
- client.sendRequestData(uri, nickname, data, output);
- } else {
- client.send(uri, nickname, serialno, output);
- }
+ OCSPClient client =
+ new OCSPClient(host, port, dbdir);
+ for (int i = 0; i < times; i++) {
+ if (data != null) {
+ client.sendRequestData(uri, nickname, data, output);
+ } else {
+ client.send(uri, nickname, serialno, output);
+ }
}
System.out.println("Success: Output " + output);
} catch (Exception e) {
System.out.println("Error: " + e.toString());
printUsage();
- System.exit(0);
+ System.exit(0);
}
}
}
diff --git a/pki/base/java-tools/src/com/netscape/cmstools/PKCS10Client.java b/pki/base/java-tools/src/com/netscape/cmstools/PKCS10Client.java
index 5f099911..064f1a46 100644
--- a/pki/base/java-tools/src/com/netscape/cmstools/PKCS10Client.java
+++ b/pki/base/java-tools/src/com/netscape/cmstools/PKCS10Client.java
@@ -46,32 +46,30 @@ import org.mozilla.jss.util.Password;
import com.netscape.cmsutil.util.HMACDigest;
-
/**
* Generates a 1024-bit RSA key pair in the security database, constructs a
- * PKCS#10 certificate request with the public key, and outputs the request
- * to a file.
+ * PKCS#10 certificate request with the public key, and outputs the request to a
+ * file.
* <p>
- * PKCS #10 is a certification request syntax standard defined by RSA. A CA
- * may support multiple types of certificate requests. The Certificate System
- * CA supports KEYGEN, PKCS#10, CRMF, and CMC.
+ * PKCS #10 is a certification request syntax standard defined by RSA. A CA may
+ * support multiple types of certificate requests. The Certificate System CA
+ * supports KEYGEN, PKCS#10, CRMF, and CMC.
* <p>
* To get a certificate from the CA, the certificate request needs to be
* submitted to and approved by a CA agent. Once approved, a certificate is
- * created for the request, and certificate attributes, such as extensions,
- * are populated according to certificate profiles.
+ * created for the request, and certificate attributes, such as extensions, are
+ * populated according to certificate profiles.
* <p>
+ *
* @version $Revision$, $Date$
*/
-public class PKCS10Client
-{
-
+public class PKCS10Client {
+
private static void printUsage() {
System.out.println("Usage: PKCS10Client -p <certdb password> -d <location of certdb> -o <output file which saves the base64 PKCS10> -s <subjectDN>\n");
}
- public static void main(String args[])
- {
+ public static void main(String args[]) {
String dbdir = null, ofilename = null, password = null, subjectName = null;
if (args.length != 8) {
@@ -79,33 +77,33 @@ public class PKCS10Client
System.exit(1);
}
- for (int i=0; i<args.length; i++) {
+ for (int i = 0; i < args.length; i++) {
String name = args[i];
if (name.equals("-p")) {
- password = args[i+1];
+ password = args[i + 1];
} else if (name.equals("-d")) {
- dbdir = args[i+1];
+ dbdir = args[i + 1];
} else if (name.equals("-o")) {
- ofilename = args[i+1];
+ ofilename = args[i + 1];
} else if (name.equals("-s")) {
- subjectName = args[i+1];
+ subjectName = args[i + 1];
}
}
-
+
if (password == null || ofilename == null || subjectName == null) {
System.out.println("Illegal input parameters.");
printUsage();
System.exit(1);
}
-
+
if (dbdir == null)
dbdir = ".";
- try {
+ try {
String mPrefix = "";
CryptoManager.InitializationValues vals =
- new CryptoManager.InitializationValues(dbdir, mPrefix,
- mPrefix, "secmod.db");
+ new CryptoManager.InitializationValues(dbdir, mPrefix,
+ mPrefix, "secmod.db");
CryptoManager.initialize(vals);
CryptoManager cm = CryptoManager.getInstance();
@@ -113,9 +111,9 @@ public class PKCS10Client
Password pass = new Password(password.toCharArray());
token.login(pass);
- KeyPairGenerator kg = token.getKeyPairGenerator(KeyPairAlgorithm.RSA);
+ KeyPairGenerator kg = token.getKeyPairGenerator(KeyPairAlgorithm.RSA);
kg.initialize(1024);
- KeyPair pair = kg.genKeyPair();
+ KeyPair pair = kg.genKeyPair();
// Add idPOPLinkWitness control
String secretValue = "testing";
@@ -124,16 +122,16 @@ public class PKCS10Client
MessageDigest SHA1Digest = MessageDigest.getInstance("SHA1");
key1 = SHA1Digest.digest(secretValue.getBytes());
-/* seed */
-byte[] b =
-{0x10, 0x53, 0x42, 0x24, 0x1a, 0x2a, 0x35, 0x3c,
- 0x7a, 0x52, 0x54, 0x56, 0x71, 0x65, 0x66, 0x4c,
- 0x51, 0x34, 0x35, 0x23, 0x3c, 0x42, 0x43, 0x45,
- 0x61, 0x4f, 0x6e, 0x43, 0x1e, 0x2a, 0x2b, 0x31,
- 0x32, 0x34, 0x35, 0x36, 0x55, 0x51, 0x48, 0x14,
- 0x16, 0x29, 0x41, 0x42, 0x43, 0x7b, 0x63, 0x44,
- 0x6a, 0x12, 0x6b, 0x3c, 0x4c, 0x3f, 0x00, 0x14,
- 0x51, 0x61, 0x15, 0x22, 0x23, 0x5f, 0x5e, 0x69};
+ /* seed */
+ byte[] b =
+ { 0x10, 0x53, 0x42, 0x24, 0x1a, 0x2a, 0x35, 0x3c,
+ 0x7a, 0x52, 0x54, 0x56, 0x71, 0x65, 0x66, 0x4c,
+ 0x51, 0x34, 0x35, 0x23, 0x3c, 0x42, 0x43, 0x45,
+ 0x61, 0x4f, 0x6e, 0x43, 0x1e, 0x2a, 0x2b, 0x31,
+ 0x32, 0x34, 0x35, 0x36, 0x55, 0x51, 0x48, 0x14,
+ 0x16, 0x29, 0x41, 0x42, 0x43, 0x7b, 0x63, 0x44,
+ 0x6a, 0x12, 0x6b, 0x3c, 0x4c, 0x3f, 0x00, 0x14,
+ 0x51, 0x61, 0x15, 0x22, 0x23, 0x5f, 0x5e, 0x69 };
HMACDigest hmacDigest = new HMACDigest(SHA1Digest, key1);
hmacDigest.update(b);
@@ -141,26 +139,26 @@ byte[] b =
OCTET_STRING ostr = new OCTET_STRING(finalDigest);
Attribute attr = new Attribute(OBJECT_IDENTIFIER.id_cmc_idPOPLinkWitness, ostr);
-
+
SET attributes = new SET();
attributes.addElement(attr);
Name n = getJssName(subjectName);
- SubjectPublicKeyInfo subjectPub = new SubjectPublicKeyInfo(pair.getPublic());
- CertificationRequestInfo certReqInfo =
- new CertificationRequestInfo(new INTEGER(0), n, subjectPub, attributes);
+ SubjectPublicKeyInfo subjectPub = new SubjectPublicKeyInfo(pair.getPublic());
+ CertificationRequestInfo certReqInfo =
+ new CertificationRequestInfo(new INTEGER(0), n, subjectPub, attributes);
CertificationRequest certRequest = new CertificationRequest(certReqInfo,
- pair.getPrivate(), SignatureAlgorithm.RSASignatureWithMD5Digest);
+ pair.getPrivate(), SignatureAlgorithm.RSASignatureWithMD5Digest);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
certRequest.encode(bos);
byte[] bb = bos.toByteArray();
String b64E = com.netscape.osutil.OSUtil.BtoA(bb);
-
+
System.out.println("");
System.out.println(b64E);
System.out.println("");
-
+
PrintStream ps = null;
ps = new PrintStream(new FileOutputStream(ofilename));
ps.println(b64E);
@@ -170,86 +168,77 @@ byte[] b =
}
}
- static Name getJssName(String dn)
- {
+ static Name getJssName(String dn) {
X500Name x5Name = null;
try {
- x5Name= new X500Name(dn);
- } catch(IOException e) {
+ x5Name = new X500Name(dn);
+ } catch (IOException e) {
- System.out.println("Illegal Subject Name: " + dn + " Error: " + e.toString());
+ System.out.println("Illegal Subject Name: " + dn + " Error: " + e.toString());
System.out.println("Filling in default Subject Name......");
return null;
}
Name ret = new Name();
netscape.security.x509.RDN[] names = null;
- names = x5Name.getNames();
+ names = x5Name.getNames();
int nameLen = x5Name.getNamesLength();
netscape.security.x509.RDN cur = null;
- for(int i = 0; i < nameLen ; i++)
- {
+ for (int i = 0; i < nameLen; i++) {
cur = names[i];
String rdnStr = cur.toString();
String[] split = rdnStr.split("=");
- if(split.length != 2)
+ if (split.length != 2)
continue;
try {
- if(split[0].equals("UID"))
- {
- ret.addElement(new AVA(new OBJECT_IDENTIFIER("0.9.2342.19200300.100.1.1"), new PrintableString(split[1])));
- // System.out.println("UID found : " + split[1]);
+ if (split[0].equals("UID")) {
+ ret.addElement(new AVA(new OBJECT_IDENTIFIER("0.9.2342.19200300.100.1.1"), new PrintableString(split[1])));
+ // System.out.println("UID found : " + split[1]);
}
- if(split[0].equals("C"))
- {
+ if (split[0].equals("C")) {
ret.addCountryName(split[1]);
- // System.out.println("C found : " + split[1]);
+ // System.out.println("C found : " + split[1]);
continue;
}
- if(split[0].equals("CN"))
- {
+ if (split[0].equals("CN")) {
ret.addCommonName(split[1]);
- // System.out.println("CN found : " + split[1]);
+ // System.out.println("CN found : " + split[1]);
continue;
}
- if(split[0].equals("L"))
- {
+ if (split[0].equals("L")) {
ret.addLocalityName(split[1]);
- // System.out.println("L found : " + split[1]);
+ // System.out.println("L found : " + split[1]);
continue;
}
- if(split[0].equals("O"))
- {
+ if (split[0].equals("O")) {
ret.addOrganizationName(split[1]);
- // System.out.println("O found : " + split[1]);
+ // System.out.println("O found : " + split[1]);
continue;
}
- if(split[0].equals("ST"))
- {
+ if (split[0].equals("ST")) {
ret.addStateOrProvinceName(split[1]);
- // System.out.println("ST found : " + split[1]);
+ // System.out.println("ST found : " + split[1]);
continue;
}
- if(split[0].equals("OU"))
- {
+ if (split[0].equals("OU")) {
ret.addOrganizationalUnitName(split[1]);
- // System.out.println("OU found : " + split[1]);
+ // System.out.println("OU found : " + split[1]);
continue;
}
- } catch (Exception e) {
- System.out.println("Error constructing RDN: " + rdnStr + " Error: " + e.toString());
+ } catch (Exception e) {
+ System.out.println("Error constructing RDN: " + rdnStr + " Error: " + e.toString());
continue;
}
}
diff --git a/pki/base/java-tools/src/com/netscape/cmstools/PKCS12Export.java b/pki/base/java-tools/src/com/netscape/cmstools/PKCS12Export.java
index 38b3e162..e30cfdb2 100644
--- a/pki/base/java-tools/src/com/netscape/cmstools/PKCS12Export.java
+++ b/pki/base/java-tools/src/com/netscape/cmstools/PKCS12Export.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmstools;
-
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
@@ -53,13 +52,13 @@ import org.mozilla.jss.pkix.primitive.EncryptedPrivateKeyInfo;
import org.mozilla.jss.pkix.primitive.PrivateKeyInfo;
import org.mozilla.jss.util.Password;
-
/**
* Tool for creating PKCS12 file
*
* <P>
+ *
* @version $Revision$, $Date$
- *
+ *
*/
public class PKCS12Export {
@@ -67,7 +66,7 @@ public class PKCS12Export {
private static void debug(String s) {
if (debugMode)
- System.out.println("PKCS12Export debug: " + s);
+ System.out.println("PKCS12Export debug: " + s);
}
private static void printUsage() {
@@ -84,7 +83,7 @@ public class PKCS12Export {
KeyGenerator kg = token.getKeyGenerator(KeyGenAlgorithm.DES3);
SymmetricKey sk = kg.generate();
KeyWrapper wrapper = token.getKeyWrapper(KeyWrapAlgorithm.DES3_CBC_PAD);
- byte iv[] = {0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1};
+ byte iv[] = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 };
IVParameterSpec param = new IVParameterSpec(iv);
wrapper.initWrap(sk, param);
byte[] enckey = wrapper.wrap(pkey);
@@ -93,7 +92,7 @@ public class PKCS12Export {
byte[] recovered = c.doFinal(enckey);
return recovered;
} catch (Exception e) {
- debug("PKCS12Export getEncodedKey: Exception="+e.toString());
+ debug("PKCS12Export getEncodedKey: Exception=" + e.toString());
System.exit(1);
}
@@ -101,30 +100,30 @@ public class PKCS12Export {
}
private static void addKeyBag(org.mozilla.jss.crypto.PrivateKey pkey, X509Certificate x509cert,
- Password pass, byte[] localKeyId, SEQUENCE safeContents) {
+ Password pass, byte[] localKeyId, SEQUENCE safeContents) {
try {
PasswordConverter passConverter = new PasswordConverter();
- byte salt[] = {0x01, 0x01, 0x01, 0x01};
+ byte salt[] = { 0x01, 0x01, 0x01, 0x01 };
byte[] priData = getEncodedKey(pkey);
PrivateKeyInfo pki = (PrivateKeyInfo)
- ASN1Util.decode(PrivateKeyInfo.getTemplate(), priData);
+ ASN1Util.decode(PrivateKeyInfo.getTemplate(), priData);
ASN1Value key = EncryptedPrivateKeyInfo.createPBE(
- PBEAlgorithm.PBE_SHA1_DES3_CBC,
- pass, salt, 1, passConverter, pki);
+ PBEAlgorithm.PBE_SHA1_DES3_CBC,
+ pass, salt, 1, passConverter, pki);
SET keyAttrs = createBagAttrs(
- x509cert.getSubjectDN().toString(), localKeyId);
+ x509cert.getSubjectDN().toString(), localKeyId);
SafeBag keyBag = new SafeBag(SafeBag.PKCS8_SHROUDED_KEY_BAG,
- key, keyAttrs);
+ key, keyAttrs);
safeContents.addElement(keyBag);
} catch (Exception e) {
- debug("PKCS12Export addKeyBag: Exception="+e.toString());
+ debug("PKCS12Export addKeyBag: Exception=" + e.toString());
System.exit(1);
}
}
private static byte[] addCertBag(X509Certificate x509cert, String nickname,
- SEQUENCE safeContents) throws IOException {
+ SEQUENCE safeContents) throws IOException {
byte[] localKeyId = null;
try {
ASN1Value cert = new OCTET_STRING(x509cert.getEncoded());
@@ -133,10 +132,10 @@ public class PKCS12Export {
if (nickname != null)
certAttrs = createBagAttrs(nickname, localKeyId);
SafeBag certBag = new SafeBag(SafeBag.CERT_BAG,
- new CertBag(CertBag.X509_CERT_TYPE, cert), certAttrs);
+ new CertBag(CertBag.X509_CERT_TYPE, cert), certAttrs);
safeContents.addElement(certBag);
} catch (Exception e) {
- debug("PKCS12Export addCertBag: "+e.toString());
+ debug("PKCS12Export addCertBag: " + e.toString());
System.exit(1);
}
@@ -153,7 +152,7 @@ public class PKCS12Export {
md.update(certDer);
return md.digest();
} catch (Exception e) {
- debug("PKCS12Export createLocalKeyId: Exception: "+e.toString());
+ debug("PKCS12Export createLocalKeyId: Exception: " + e.toString());
System.exit(1);
}
@@ -161,7 +160,7 @@ public class PKCS12Export {
}
private static SET createBagAttrs(String nickName, byte localKeyId[])
- throws IOException {
+ throws IOException {
try {
SET attrs = new SET();
SEQUENCE nickNameAttr = new SEQUENCE();
@@ -182,7 +181,7 @@ public class PKCS12Export {
attrs.addElement(localKeyAttr);
return attrs;
} catch (Exception e) {
- debug("PKCS12Export createBagAttrs: Exception="+e.toString());
+ debug("PKCS12Export createBagAttrs: Exception=" + e.toString());
System.exit(1);
}
@@ -200,24 +199,24 @@ public class PKCS12Export {
String snickname = null;
String pk12pwdfile = null;
String pk12output = null;
- for (int i=0; i<args.length; i++) {
+ for (int i = 0; i < args.length; i++) {
if (args[i].equals("-d")) {
- dir = args[i+1];
+ dir = args[i + 1];
} else if (args[i].equals("-p")) {
- pwdfile = args[i+1];
+ pwdfile = args[i + 1];
} else if (args[i].equals("-s")) {
- snickname = args[i+1];
+ snickname = args[i + 1];
} else if (args[i].equals("-w")) {
- pk12pwdfile = args[i+1];
+ pk12pwdfile = args[i + 1];
} else if (args[i].equals("-o")) {
- pk12output = args[i+1];
+ pk12output = args[i + 1];
} else if (args[i].equals("-debug")) {
debugMode = true;
}
}
- debug("The directory for certdb/keydb is "+dir);
- debug("The password file for keydb is "+pwdfile);
+ debug("The directory for certdb/keydb is " + dir);
+ debug("The password file for keydb is " + pwdfile);
// get password
String pwd = null;
@@ -225,7 +224,7 @@ public class PKCS12Export {
BufferedReader in = new BufferedReader(new FileReader(pwdfile));
pwd = in.readLine();
} catch (Exception e) {
- debug("Failed to read the keydb password from the file. Exception: "+e.toString());
+ debug("Failed to read the keydb password from the file. Exception: " + e.toString());
System.exit(1);
}
@@ -234,14 +233,14 @@ public class PKCS12Export {
BufferedReader in = new BufferedReader(new FileReader(pk12pwdfile));
pk12pwd = in.readLine();
} catch (Exception e) {
- debug("Failed to read the keydb password from the file. Exception: "+e.toString());
+ debug("Failed to read the keydb password from the file. Exception: " + e.toString());
System.exit(1);
}
CryptoManager cm = null;
try {
- CryptoManager.InitializationValues vals =
- new CryptoManager.InitializationValues(dir, "", "", "secmod.db");
+ CryptoManager.InitializationValues vals =
+ new CryptoManager.InitializationValues(dir, "", "", "secmod.db");
CryptoManager.initialize(vals);
cm = CryptoManager.getInstance();
} catch (Exception e) {
@@ -257,16 +256,16 @@ public class PKCS12Export {
token.login(pass);
CryptoStore store = token.getCryptoStore();
X509Certificate[] certs = store.getCertificates();
- debug("Number of user certificates = "+certs.length);
+ debug("Number of user certificates = " + certs.length);
Password pass12 = new Password(pk12pwd.toCharArray());
- for (int i=0; i<certs.length; i++) {
+ for (int i = 0; i < certs.length; i++) {
String nickname = certs[i].getNickname();
- debug("Certificate nickname = "+nickname);
+ debug("Certificate nickname = " + nickname);
org.mozilla.jss.crypto.PrivateKey prikey = null;
try {
prikey = cm.findPrivKeyByCert(certs[i]);
} catch (Exception e) {
- debug("PKCS12Export Exception: "+e.toString());
+ debug("PKCS12Export Exception: " + e.toString());
}
if (prikey == null) {
@@ -274,8 +273,8 @@ public class PKCS12Export {
byte[] localKeyId = addCertBag(certs[i], null, safeContents);
} else {
debug("Private key is not null");
- byte localKeyId[] =
- addCertBag(certs[i], nickname, safeContents);
+ byte localKeyId[] =
+ addCertBag(certs[i], nickname, safeContents);
addKeyBag(prikey, certs[i], pass12, localKeyId, encSafeContents);
}
}
@@ -294,7 +293,7 @@ public class PKCS12Export {
pass.clear();
pass12.clear();
} catch (Exception e) {
- debug("PKCS12Export Exception: "+e.toString());
+ debug("PKCS12Export Exception: " + e.toString());
System.exit(1);
}
}
diff --git a/pki/base/java-tools/src/com/netscape/cmstools/PasswordCache.java b/pki/base/java-tools/src/com/netscape/cmstools/PasswordCache.java
index cd0351ae..82e9dd3e 100644
--- a/pki/base/java-tools/src/com/netscape/cmstools/PasswordCache.java
+++ b/pki/base/java-tools/src/com/netscape/cmstools/PasswordCache.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmstools;
-
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
@@ -43,18 +42,18 @@ import org.mozilla.jss.util.Base64OutputStream;
import org.mozilla.jss.util.Password;
/**
- * Tool for interacting with the PWcache
+ * Tool for interacting with the PWcache
*
* @version $Revision$, $Date$
*/
public class PasswordCache {
- /* These are the tags that identify various passwords
- * They should probably be converted instances of some
- * class so that we can expose an API to add additional
- * TAG's for use if I want to add a password for use
- * with my own authenticaion module
+ /*
+ * These are the tags that identify various passwords They should probably
+ * be converted instances of some class so that we can expose an API to add
+ * additional TAG's for use if I want to add a password for use with my own
+ * authenticaion module
*/
public static final String PROP_PWC_NICKNAME = "sso_key";
public static final String PW_TAG_INTERNAL_LDAP_DB = "Internal LDAP Database";
@@ -63,15 +62,15 @@ public class PasswordCache {
private static final String KEYDB = "key3.db";
private static void usage() {
- System.out.println("This tool has to be run from the same directory where pwcache.db file resides, normally <cms instance>/config directory, unless the file's full path is specified in the -c option..\nUsage: PasswordCache <SSO_PASSWORD> <-d cert/key db directory> <-h tokenName> <-P cert/key db prefix> <-c pwcache.db_file_full_path> <-k file containing Base64EncodedKeyID> <COMMAND> ...");
- System.out.println(" commands:");
- System.out.println(" 'add <password_name> <password>'");
- System.out.println(" 'change <password_name> <password>'");
- System.out.println(" 'delete <password_name>'");
- System.out.println(" 'rekey'");
- System.out.println(" 'list'");
- System.out.println("\nExample:\n\tPasswordCache thePassword1 -d /usr/netscape/servers/cms/alias -P cert-instance1-machine1- -c pwcache.db -k keyidFile list");
- System.exit(1);
+ System.out.println("This tool has to be run from the same directory where pwcache.db file resides, normally <cms instance>/config directory, unless the file's full path is specified in the -c option..\nUsage: PasswordCache <SSO_PASSWORD> <-d cert/key db directory> <-h tokenName> <-P cert/key db prefix> <-c pwcache.db_file_full_path> <-k file containing Base64EncodedKeyID> <COMMAND> ...");
+ System.out.println(" commands:");
+ System.out.println(" 'add <password_name> <password>'");
+ System.out.println(" 'change <password_name> <password>'");
+ System.out.println(" 'delete <password_name>'");
+ System.out.println(" 'rekey'");
+ System.out.println(" 'list'");
+ System.out.println("\nExample:\n\tPasswordCache thePassword1 -d /usr/netscape/servers/cms/alias -P cert-instance1-machine1- -c pwcache.db -k keyidFile list");
+ System.exit(1);
}
private static boolean debugMode = false;
@@ -79,26 +78,24 @@ public class PasswordCache {
public PasswordCache() {
}
- private static void debug (String s) {
+ private static void debug(String s) {
if (debugMode == true)
- System.out.println("PasswordCache debug: "+s);
+ System.out.println("PasswordCache debug: " + s);
}
/**
* clean up an argv by removing the trailing, empty arguments
- *
- * This is necessary to support the script wrapper which calls the
- * tool with arguments in quotes such as:
- * "$1" "$2"
- * if $2 is not specified, the empty arg "" gets passed, which causes
- * an error in the arg-count checking code.
+ *
+ * This is necessary to support the script wrapper which calls the tool with
+ * arguments in quotes such as: "$1" "$2" if $2 is not specified, the empty
+ * arg "" gets passed, which causes an error in the arg-count checking code.
*/
private static String[] cleanArgs(String[] s) {
int length;
int i;
length = s.length;
- debug("before cleanArgs argv length ="+length);
+ debug("before cleanArgs argv length =" + length);
for (i = length - 1; i >= 0; i--) {
if (s[i].equals("")) {
@@ -111,16 +108,16 @@ public class PasswordCache {
String[] new_av = new String[length];
for (i = 0; i < length; i++) {
new_av[i] = s[i];
- debug("arg "+i+" is "+new_av[i]);
+ debug("arg " + i + " is " + new_av[i]);
}
- debug("after cleanArgs argv length ="+length);
+ debug("after cleanArgs argv length =" + length);
return new_av;
}
public static byte[] base64Decode(String s) throws IOException {
- byte[] d = com.netscape.osutil.OSUtil.AtoB(s);
- return d;
+ byte[] d = com.netscape.osutil.OSUtil.AtoB(s);
+ return d;
}
public static String base64Encode(byte[] bytes) throws IOException {
@@ -129,9 +126,9 @@ public class PasswordCache {
ByteArrayOutputStream output = new ByteArrayOutputStream();
Base64OutputStream b64 = new Base64OutputStream(new
PrintStream(new
- FilterOutputStream(output)
+ FilterOutputStream(output)
)
- );
+ );
b64.write(bytes);
b64.flush();
@@ -141,7 +138,7 @@ public class PasswordCache {
return output.toString("8859_1");
}
- public static void main(String[]av) {
+ public static void main(String[] av) {
// default path is "."
String mPath = ".";
String mTokenName = null;
@@ -173,28 +170,33 @@ public class PasswordCache {
String aPasswd = "";
int i = 0;
- for ( i = 1; i < argv.length; ++i) {
- if( argv[i].equals("-d") ) {
- if( ++i >= argv.length ) usage();
+ for (i = 1; i < argv.length; ++i) {
+ if (argv[i].equals("-d")) {
+ if (++i >= argv.length)
+ usage();
mPath = argv[i];
- } else if( argv[i].equals("-h") ) {
- if( ++i >= argv.length ) usage();
+ } else if (argv[i].equals("-h")) {
+ if (++i >= argv.length)
+ usage();
mTokenName = argv[i];
- } else if( argv[i].equals("-P") ) {
- if( ++i >= argv.length ) usage();
+ } else if (argv[i].equals("-P")) {
+ if (++i >= argv.length)
+ usage();
mPrefix = argv[i];
- } else if( argv[i].equals("-c") ) {
- if( ++i >= argv.length ) usage();
+ } else if (argv[i].equals("-c")) {
+ if (++i >= argv.length)
+ usage();
mCacheFile = argv[i];
- } else if (argv[i].equals("-k") ) {
- if( ++i >= argv.length ) usage();
+ } else if (argv[i].equals("-k")) {
+ if (++i >= argv.length)
+ usage();
String keyFile = argv[i];
try {
- BufferedReader r = new BufferedReader(new FileReader(keyFile));
- String listLine;
- mKeyIdString = r.readLine();
+ BufferedReader r = new BufferedReader(new FileReader(keyFile));
+ String listLine;
+ mKeyIdString = r.readLine();
} catch (Exception e) {
- System.out.println("Error: "+e.toString());
+ System.out.println("Error: " + e.toString());
System.exit(1);
}
@@ -209,13 +211,13 @@ public class PasswordCache {
}
} else {
command = argv[i++];
- debug("command = "+command);
+ debug("command = " + command);
if ((command.equals("add")) ||
(command.equals("change"))) {
aTag = argv[i++];
aPasswd = argv[i];
- debug("command is "+command+" "+aTag+":"+aPasswd);
+ debug("command is " + command + " " + aTag + ":" + aPasswd);
} else if (command.equals("delete")) {
aTag = argv[i];
} else if (command.equals("list")) {
@@ -231,9 +233,9 @@ public class PasswordCache {
System.out.println("cert/key db path = " + mPath);
System.out.println("password cache file = " + mCacheFile);
- CryptoManager.InitializationValues vals =
- new CryptoManager.InitializationValues(mPath, mPrefix,
- mPrefix, "secmod.db");
+ CryptoManager.InitializationValues vals =
+ new CryptoManager.InitializationValues(mPath, mPrefix,
+ mPrefix, "secmod.db");
CryptoManager.initialize(vals);
@@ -244,7 +246,7 @@ public class PasswordCache {
System.out.println("token name = internal");
} else {
token = cm.getTokenByName(mTokenName);
- System.out.println("token name = "+ mTokenName);
+ System.out.println("token name = " + mTokenName);
}
token.login(pass);
@@ -259,31 +261,31 @@ public class PasswordCache {
PWsdrCache cache = null;
try {
// compose instance name
- File passwordCacheDB = new File( mCacheFile );
+ File passwordCacheDB = new File(mCacheFile);
pwdPath = passwordCacheDB.getAbsolutePath();
- int beginIndex = pwdPath.lastIndexOf( "cert-" );
- instancePath = pwdPath.substring( beginIndex );
+ int beginIndex = pwdPath.lastIndexOf("cert-");
+ instancePath = pwdPath.substring(beginIndex);
int endIndex = 0;
- endIndex = instancePath.lastIndexOf( "config" );
- instanceName = instancePath.substring( 0, ( endIndex - 1 ) );
+ endIndex = instancePath.lastIndexOf("config");
+ instanceName = instancePath.substring(0, (endIndex - 1));
- cache = new PWsdrCache(mCacheFile, mTokenName, null, true);
- cache.deleteUniqueNamedKey( PROP_PWC_NICKNAME
+ cache = new PWsdrCache(mCacheFile, mTokenName, null, true);
+ cache.deleteUniqueNamedKey(PROP_PWC_NICKNAME
+ " "
- + instanceName );
+ + instanceName);
byte[] newKeyId = cache.generateSDRKeyWithNickName(
PROP_PWC_NICKNAME
- + " "
- + instanceName );
+ + " "
+ + instanceName);
if (newKeyId != null) {
String newKeyIDString = base64Encode(newKeyId);
- System.out.println("key generated successfully with key id = "+
+ System.out.println("key generated successfully with key id = " +
newKeyIDString);
System.out.println("Save the VALUE portion of this key id in a local file,");
System.out.println("and under variable \"pwcKeyid\" in CS.cfg !!");
System.out.println("If you have not already done so,");
- System.out.println("remove the old pwcache.db and use this local file to add passwords.");
- // job is done
+ System.out.println("remove the old pwcache.db and use this local file to add passwords.");
+ // job is done
System.exit(0);
} else {
System.out.println("key expected to be generated but wasn't");
@@ -297,10 +299,10 @@ public class PasswordCache {
PWsdrCache cache = null;
try {
- cache = new PWsdrCache(mCacheFile, mTokenName, mKeyId, true);
+ cache = new PWsdrCache(mCacheFile, mTokenName, mKeyId, true);
} catch (Exception e) {
System.out.println(e.toString());
- System.exit(1);
+ System.exit(1);
}
if ((command.equals("add")) || (command.equals("change"))) {
@@ -310,12 +312,12 @@ public class PasswordCache {
System.exit(1);
}
- try {
- System.out.println("adding "+aTag+":"+aPasswd);
- cache.addEntry(aTag, aPasswd);
- } catch (Exception e) {
- System.out.println("--failed--"+ e.toString());
- }
+ try {
+ System.out.println("adding " + aTag + ":" + aPasswd);
+ cache.addEntry(aTag, aPasswd);
+ } catch (Exception e) {
+ System.out.println("--failed--" + e.toString());
+ }
} else if (command.equals("list")) {
cache.pprint();
} else if (command.equals("delete")) {
@@ -325,11 +327,11 @@ public class PasswordCache {
System.exit(1);
}
- try {
- cache.deleteEntry(aTag);
- } catch (Exception e) {
- System.out.println("User not found");
- }
+ try {
+ cache.deleteEntry(aTag);
+ } catch (Exception e) {
+ System.out.println("User not found");
+ }
} else {
System.out.println("Illegal command: " + command);
System.exit(1);
@@ -337,11 +339,11 @@ public class PasswordCache {
}
}
-
-/*
+/*
* A class for managing passwords in the SDR password cache
- *
+ *
* @author Christina Fu
+ *
* @version $Revision$, $Date$
*/
class PWsdrCache {
@@ -371,9 +373,9 @@ class PWsdrCache {
cm = CryptoManager.getInstance();
if (mTokenName != null) {
mToken = cm.getTokenByName(mTokenName);
- debug("PWsdrCache: mToken = "+mTokenName);
+ debug("PWsdrCache: mToken = " + mTokenName);
} else {
- mToken = cm.getInternalKeyStorageToken();
+ mToken = cm.getInternalKeyStorageToken();
debug("PWsdrCache: mToken = internal");
}
}
@@ -386,42 +388,40 @@ class PWsdrCache {
return mTokenName;
}
- public void deleteUniqueNamedKey( String nickName )
- throws Exception
- {
- KeyManager km = new KeyManager( mToken );
- km.deleteUniqueNamedKey( nickName );
+ public void deleteUniqueNamedKey(String nickName)
+ throws Exception {
+ KeyManager km = new KeyManager(mToken);
+ km.deleteUniqueNamedKey(nickName);
}
public byte[] generateSDRKey() throws Exception {
- return generateSDRKeyWithNickName(PROP_PWC_NICKNAME);
+ return generateSDRKeyWithNickName(PROP_PWC_NICKNAME);
}
- public byte[] generateSDRKeyWithNickName( String nickName )
- throws Exception
- {
+ public byte[] generateSDRKeyWithNickName(String nickName)
+ throws Exception {
try {
if (mIsTool == true) {
// generate SDR key
- KeyManager km = new KeyManager(mToken);
+ KeyManager km = new KeyManager(mToken);
try {
- // Bugscape Bug #54838: Due to the CMS cloning feature,
- // we must check for the presence of
- // a uniquely named symmetric key
- // prior to making an attempt to
- // generate it!
+ // Bugscape Bug #54838: Due to the CMS cloning feature,
+ // we must check for the presence of
+ // a uniquely named symmetric key
+ // prior to making an attempt to
+ // generate it!
//
- if( !( km.uniqueNamedKeyExists( nickName ) ) ) {
- mKeyID = km.generateUniqueNamedKey( nickName );
+ if (!(km.uniqueNamedKeyExists(nickName))) {
+ mKeyID = km.generateUniqueNamedKey(nickName);
debug("PWsdrCache: SDR key generated");
}
} catch (TokenException e) {
- log (0, "generateSDRKey() failed on "+e.toString());
+ log(0, "generateSDRKey() failed on " + e.toString());
throw e;
}
}
} catch (Exception e) {
- log (0, e.toString());
+ log(0, e.toString());
throw e;
}
return mKeyID;
@@ -442,7 +442,7 @@ class PWsdrCache {
* add passwd in pwcache.
*/
public void addEntry(String tag, String pwd, Hashtable tagPwds) throws IOException {
- System.out.println("PWsdrCache: in addEntry");
+ System.out.println("PWsdrCache: in addEntry");
String stringToAdd = null;
String bufs = null;
@@ -455,7 +455,7 @@ class PWsdrCache {
tag = (String) enum1.nextElement();
pwd = (String) tagPwds.get(tag);
debug("password tag: " + tag + " stored in " + mPWcachedb);
-
+
if (stringToAdd == null) {
stringToAdd = tag + ":" + pwd + "\n";
} else {
@@ -468,7 +468,7 @@ class PWsdrCache {
System.out.println("PWsdrCache: after readPWcache()");
if (dcrypts != null) {
// converts to Hashtable, replace if tag exists, add
- // if tag doesn't exist
+ // if tag doesn't exist
Hashtable ht = string2Hashtable(dcrypts);
if (ht.containsKey(tag) == false) {
@@ -483,7 +483,7 @@ class PWsdrCache {
debug("adding new tag: " + tag);
bufs = stringToAdd;
}
-
+
// write update to cache
writePWcache(bufs);
}
@@ -498,7 +498,7 @@ class PWsdrCache {
if (dcrypts != null) {
// converts to Hashtable, replace if tag exists, add
- // if tag doesn't exist
+ // if tag doesn't exist
Hashtable ht = string2Hashtable(dcrypts);
if (ht.containsKey(tag) == false) {
@@ -513,7 +513,7 @@ class PWsdrCache {
debug("password cache contains no tags");
return;
}
-
+
// write update to cache
writePWcache(bufs);
}
@@ -584,7 +584,6 @@ class PWsdrCache {
*/
public void writePWcache(String bufs) throws IOException {
-
try {
Encryptor sdr = new Encryptor(mToken, mKeyID,
Encryptor.DEFAULT_ENCRYPTION_ALG);
@@ -613,46 +612,46 @@ class PWsdrCache {
// Make certain that this temporary file has
// the correct permissions.
- if( !isNT() ) {
- exec( "chmod 00660 " + tmpPWcache.getAbsolutePath() );
+ if (!isNT()) {
+ exec("chmod 00660 " + tmpPWcache.getAbsolutePath());
}
File origFile = new File(mPWcachedb);
try {
// Always remove any pre-existing target file
- if( origFile.exists() ) {
+ if (origFile.exists()) {
origFile.delete();
}
if (isNT()) {
// NT is very picky on the path
exec("copy " +
- tmpPWcache.getAbsolutePath().replace('/', '\\') + " " +
- origFile.getAbsolutePath().replace('/', '\\'));
+ tmpPWcache.getAbsolutePath().replace('/', '\\') + " " +
+ origFile.getAbsolutePath().replace('/', '\\'));
} else {
// Create a copy of the temporary file which
// preserves the temporary file's permissions.
exec("cp -p " + tmpPWcache.getAbsolutePath() + " " +
- origFile.getAbsolutePath());
+ origFile.getAbsolutePath());
}
// Remove the temporary file if and only if
// the "rename" was successful.
- if( origFile.exists() ) {
+ if (origFile.exists()) {
tmpPWcache.delete();
// Make certain that the final file has
// the correct permissions.
- if( !isNT() ) {
- exec( "chmod 00660 " + origFile.getAbsolutePath() );
+ if (!isNT()) {
+ exec("chmod 00660 " + origFile.getAbsolutePath());
}
// report success
- debug( "Renaming operation completed for " + mPWcachedb );
+ debug("Renaming operation completed for " + mPWcachedb);
} else {
// report failure and exit
- debug( "Renaming operation failed for " + mPWcachedb );
+ debug("Renaming operation failed for " + mPWcachedb);
System.exit(1);
}
} catch (IOException exx) {
@@ -678,7 +677,7 @@ class PWsdrCache {
while (enum1.hasMoreElements()) {
String tag = (String) enum1.nextElement();
String pwd = (String) ht.get(tag);
-
+
if (returnString == null) {
returnString = tag + ":" + pwd + "\n";
} else {
@@ -706,14 +705,14 @@ class PWsdrCache {
ht.put(tag.trim(), passwd.trim());
} else {
- //invalid format...log or throw...later
+ // invalid format...log or throw...later
}
}
return ht;
}
/*
- * get password from cache. This one supplies cache file name
+ * get password from cache. This one supplies cache file name
*/
public Password getEntry(String fileName, String tag) {
mPWcachedb = fileName;
@@ -721,8 +720,8 @@ class PWsdrCache {
}
/*
- * if tag found with pwd, return it
- * if tag not found, return null, which will cause it to give up
+ * if tag found with pwd, return it if tag not found, return null, which
+ * will cause it to give up
*/
public Password getEntry(String tag) {
Hashtable pwTable = null;
@@ -763,7 +762,7 @@ class PWsdrCache {
}
}
- //copied from IOUtil.java
+ // copied from IOUtil.java
/**
* Checks if this is NT.
*/
@@ -797,22 +796,17 @@ class PWsdrCache {
if (process.exitValue() == 0) {
/**
- pOut = new BufferedReader(
- new InputStreamReader(process.getInputStream()));
- while ((l = pOut.readLine()) != null) {
- System.out.println(l);
- }
+ * pOut = new BufferedReader( new
+ * InputStreamReader(process.getInputStream())); while ((l =
+ * pOut.readLine()) != null) { System.out.println(l); }
**/
return true;
} else {
/**
- pOut = new BufferedReader(
- new InputStreamReader(process.getErrorStream()));
- l = null;
- while ((l = pOut.readLine()) != null) {
- System.out.println(l);
- }
+ * pOut = new BufferedReader( new
+ * InputStreamReader(process.getErrorStream())); l = null; while
+ * ((l = pOut.readLine()) != null) { System.out.println(l); }
**/
return false;
}
@@ -860,9 +854,9 @@ class PWsdrCache {
line.length());
debug(tag.trim() +
- " : " + passwd.trim());
+ " : " + passwd.trim());
} else {
- //invalid format...log or throw...later
+ // invalid format...log or throw...later
debug("invalid format");
}
}
diff --git a/pki/base/java-tools/src/com/netscape/cmstools/PrettyPrintCert.java b/pki/base/java-tools/src/com/netscape/cmstools/PrettyPrintCert.java
index f67f787e..fbebddd7 100644
--- a/pki/base/java-tools/src/com/netscape/cmstools/PrettyPrintCert.java
+++ b/pki/base/java-tools/src/com/netscape/cmstools/PrettyPrintCert.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmstools;
-
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
@@ -36,41 +35,41 @@ import netscape.security.x509.X500Name;
import netscape.security.x509.X509CertImpl;
import netscape.security.x509.X509CertInfo;
-
/**
- * The PrettyPrintCert class is a utility program designed to "pretty print"
- * a certificate. It assumes that the name of a data file is passed to the
- * program via the command line, and that the contents contain a certificate
- * encoded in an ASCII BASE 64 format. Note that the data file may contain
- * an optional "-----BEGIN" header and/or an optional "-----END" trailer.
- *
+ * The PrettyPrintCert class is a utility program designed to "pretty print" a
+ * certificate. It assumes that the name of a data file is passed to the program
+ * via the command line, and that the contents contain a certificate encoded in
+ * an ASCII BASE 64 format. Note that the data file may contain an optional
+ * "-----BEGIN" header and/or an optional "-----END" trailer.
+ *
* <P>
* The program may be invoked as follows:
+ *
* <PRE>
- *
+ *
* PrettyPrintCert &lt;input filename&gt; [output filename]
- *
+ *
* NOTE: &lt;input filename&gt; must contain an ASCII
* BASE 64 encoded certificate
- *
+ *
* &lt;output filename&gt; contains a certificate displayed
* in a "pretty print" ASCII format
* </PRE>
- *
+ *
* @version $Revision$, $Date$
*/
public class PrettyPrintCert {
// Define constants
- public static final int ARGC = 2;
+ public static final int ARGC = 2;
public static final String HEADER = "-----BEGIN";
public static final String TRAILER = "-----END";
public static void usageAndExit() {
System.out.println("Usage: PrettyPrintCert " +
- "[options] " +
- "<input filename> " +
- "[output filename]");
+ "[options] " +
+ "<input filename> " +
+ "[output filename]");
System.out.println("\n options: ");
System.out.println(" -simpleinfo : prints limited cert info in easy to parse format");
System.exit(0);
@@ -87,7 +86,7 @@ public class PrettyPrintCert {
CertPrettyPrint certDetails = null;
String pp = new String();
FileOutputStream outputCert = null;
- boolean mSimpleInfo = false;
+ boolean mSimpleInfo = false;
String inputfile = null;
String outputfile = null;
@@ -130,36 +129,36 @@ public class PrettyPrintCert {
if (inputfile == null) {
usageAndExit();
}
-
+
// (2) Create a DataInputStream() object to the BASE 64
- // encoded certificate contained within the file
- // specified on the command line
+ // encoded certificate contained within the file
+ // specified on the command line
try {
inputCert = new BufferedReader(new InputStreamReader(
new BufferedInputStream(
- new FileInputStream(
- inputfile))));
+ new FileInputStream(
+ inputfile))));
} catch (FileNotFoundException e) {
System.out.println("PrettyPrintCert: can't find file " +
- inputfile + ":\n" + e);
+ inputfile + ":\n" + e);
return;
}
// (3) Read the entire contents of the specified BASE 64 encoded
- // certificate into a String() object throwing away any
- // headers beginning with HEADER and any trailers beginning
- // with TRAILER
+ // certificate into a String() object throwing away any
+ // headers beginning with HEADER and any trailers beginning
+ // with TRAILER
try {
while ((encodedBASE64CertChunk = inputCert.readLine()) != null) {
if (!(encodedBASE64CertChunk.startsWith(HEADER)) &&
- !(encodedBASE64CertChunk.startsWith(TRAILER))) {
+ !(encodedBASE64CertChunk.startsWith(TRAILER))) {
encodedBASE64Cert += encodedBASE64CertChunk.trim();
}
}
} catch (IOException e) {
System.out.println("PrettyPrintCert: Unexpected BASE64 " +
- "encoded error encountered in readLine():\n" +
- e);
+ "encoded error encountered in readLine():\n" +
+ e);
}
// (4) Close the DataInputStream() object
@@ -167,33 +166,33 @@ public class PrettyPrintCert {
inputCert.close();
} catch (IOException e) {
System.out.println("PrettyPrintCert: Unexpected BASE64 " +
- "encoded error encountered in close():\n" + e);
+ "encoded error encountered in close():\n" + e);
}
-
+
// (5) Decode the ASCII BASE 64 certificate enclosed in the
- // String() object into a BINARY BASE 64 byte[] object
+ // String() object into a BINARY BASE 64 byte[] object
decodedBASE64Cert = com.netscape.osutil.OSUtil.AtoB(encodedBASE64Cert);
// (6) Create an X509CertImpl() object from the BINARY BASE 64
- // byte[] object
+ // byte[] object
try {
cert = new X509CertImpl(decodedBASE64Cert);
} catch (CertificateException e) {
System.out.println("PrettyPrintCert: Error encountered " +
- "on parsing certificate :\n" + e);
+ "on parsing certificate :\n" + e);
}
if (mSimpleInfo) {
try {
X509CertInfo certinfo = (X509CertInfo) cert.get("x509.INFO");
-
+
CertificateSubjectName csn = (CertificateSubjectName)
- certinfo.get(X509CertInfo.SUBJECT);
+ certinfo.get(X509CertInfo.SUBJECT);
Enumeration<String> en = csn.getAttributeNames();
- X500Name dname = (X500Name) csn.get(CertificateSubjectName.DN_NAME);
+ X500Name dname = (X500Name) csn.get(CertificateSubjectName.DN_NAME);
pp = "";
RDN[] rdns = dname.getNames();
@@ -201,14 +200,14 @@ public class PrettyPrintCert {
for (int i = rdns.length - 1; i >= 0; i--) {
pp = pp + rdns[i] + "\n";
}
-
- } catch (Exception e) {
+
+ } catch (Exception e) {
System.out.println("ERROR");
e.printStackTrace();
- }
+ }
} else {
// (7) For this utility, always specify the default Locale
- aLocale = Locale.getDefault();
+ aLocale = Locale.getDefault();
// (8) Create a CertPrettyPrint() object
certDetails = new CertPrettyPrint(cert);
@@ -218,7 +217,7 @@ public class PrettyPrintCert {
}
// (10) Finally, "pretty print" the actual certificate to the console
- // unless an output file has been specified
+ // unless an output file has been specified
if (outputfile == null) {
System.out.println(pp);
} else {
@@ -226,7 +225,7 @@ public class PrettyPrintCert {
outputCert = new FileOutputStream(outputfile);
} catch (Exception e) {
System.out.println("PrettyPrintCert: unable to open file " +
- argv[1] + " for writing:\n" + e);
+ argv[1] + " for writing:\n" + e);
return;
}
@@ -234,18 +233,17 @@ public class PrettyPrintCert {
outputCert.write(pp.getBytes());
} catch (IOException e) {
System.out.println("PrettyPrintCert: Unexpected error " +
- "encountered while attempting to write() " +
- outputfile + ":\n" + e);
+ "encountered while attempting to write() " +
+ outputfile + ":\n" + e);
}
try {
outputCert.close();
} catch (IOException e) {
System.out.println("PrettyPrintCert: Unexpected error " +
- "encountered while attempting to close() " +
- outputfile + ":\n" + e);
+ "encountered while attempting to close() " +
+ outputfile + ":\n" + e);
}
}
}
}
-
diff --git a/pki/base/java-tools/src/com/netscape/cmstools/PrettyPrintCrl.java b/pki/base/java-tools/src/com/netscape/cmstools/PrettyPrintCrl.java
index b072867b..4726eed9 100644
--- a/pki/base/java-tools/src/com/netscape/cmstools/PrettyPrintCrl.java
+++ b/pki/base/java-tools/src/com/netscape/cmstools/PrettyPrintCrl.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmstools;
-
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
@@ -38,33 +37,33 @@ import netscape.security.x509.OIDMap;
import netscape.security.x509.X509CRLImpl;
import netscape.security.x509.X509ExtensionException;
-
/**
- * The PrettyPrintCrl class is a utility program designed to "pretty print"
- * a CRL. It assumes that the name of a data file is passed to the
- * program via the command line, and that the contents contain a CRL
- * encoded in an ASCII BASE 64 format. Note that the data file may contain
- * an optional "-----BEGIN" header and/or an optional "-----END" trailer.
- *
+ * The PrettyPrintCrl class is a utility program designed to "pretty print" a
+ * CRL. It assumes that the name of a data file is passed to the program via the
+ * command line, and that the contents contain a CRL encoded in an ASCII BASE 64
+ * format. Note that the data file may contain an optional "-----BEGIN" header
+ * and/or an optional "-----END" trailer.
+ *
* <P>
* The program may be invoked as follows:
+ *
* <PRE>
- *
+ *
* PrettyPrintCrl &lt;input filename&gt; [output filename]
- *
+ *
* NOTE: &lt;input filename&gt; must contain an ASCII
* BASE 64 encoded CRL
- *
+ *
* &lt;output filename&gt; contains a CRL displayed
* in a "pretty print" ASCII format
* </PRE>
- *
+ *
* @version $Revision$, $Date$
*/
public class PrettyPrintCrl {
// Define constants
- public static final int ARGC = 2;
+ public static final int ARGC = 2;
public static final String HEADER = "-----BEGIN";
public static final String TRAILER = "-----END";
@@ -83,65 +82,65 @@ public class PrettyPrintCrl {
// (1) Check that at least one argument was submitted to the program
if ((argv.length < 1) || (argv.length > ARGC)) {
System.out.println("Usage: PrettyPrintCrl " +
- "<input filename> " +
- "[output filename]");
+ "<input filename> " +
+ "[output filename]");
return;
}
try {
OIDMap.addAttribute(DeltaCRLIndicatorExtension.class.getName(),
- DeltaCRLIndicatorExtension.OID,
- DeltaCRLIndicatorExtension.class.getSimpleName());
+ DeltaCRLIndicatorExtension.OID,
+ DeltaCRLIndicatorExtension.class.getSimpleName());
} catch (CertificateException e) {
}
try {
OIDMap.addAttribute(HoldInstructionExtension.class.getName(),
- HoldInstructionExtension.OID,
- HoldInstructionExtension.class.getSimpleName());
+ HoldInstructionExtension.OID,
+ HoldInstructionExtension.class.getSimpleName());
} catch (CertificateException e) {
}
try {
OIDMap.addAttribute(InvalidityDateExtension.class.getName(),
- InvalidityDateExtension.OID,
- InvalidityDateExtension.class.getSimpleName());
+ InvalidityDateExtension.OID,
+ InvalidityDateExtension.class.getSimpleName());
} catch (CertificateException e) {
}
try {
OIDMap.addAttribute(IssuingDistributionPointExtension.class.getName(),
- IssuingDistributionPointExtension.OID,
- IssuingDistributionPointExtension.class.getSimpleName());
+ IssuingDistributionPointExtension.OID,
+ IssuingDistributionPointExtension.class.getSimpleName());
} catch (CertificateException e) {
}
// (2) Create a DataInputStream() object to the BASE 64
- // encoded CRL contained within the file
- // specified on the command line
+ // encoded CRL contained within the file
+ // specified on the command line
try {
inputCrl = new BufferedReader(new InputStreamReader(
new BufferedInputStream(
- new FileInputStream(
- argv[0]))));
+ new FileInputStream(
+ argv[0]))));
} catch (FileNotFoundException e) {
System.out.println("PrettyPrintCrl(): can''t find file " +
- argv[0] + ":\n" + e);
+ argv[0] + ":\n" + e);
return;
}
// (3) Read the entire contents of the specified BASE 64 encoded
- // CRL into a String() object throwing away any
- // headers beginning with HEADER and any trailers beginning
- // with TRAILER
+ // CRL into a String() object throwing away any
+ // headers beginning with HEADER and any trailers beginning
+ // with TRAILER
try {
while ((encodedBASE64CrlChunk = inputCrl.readLine()) != null) {
if (!(encodedBASE64CrlChunk.startsWith(HEADER)) &&
- !(encodedBASE64CrlChunk.startsWith(TRAILER))) {
+ !(encodedBASE64CrlChunk.startsWith(TRAILER))) {
encodedBASE64Crl += encodedBASE64CrlChunk.trim();
}
}
} catch (IOException e) {
System.out.println("PrettyPrintCrl(): Unexpected BASE64 " +
- "encoded error encountered in readLine():\n" +
- e);
+ "encoded error encountered in readLine():\n" +
+ e);
}
// (4) Close the DataInputStream() object
@@ -149,28 +148,28 @@ public class PrettyPrintCrl {
inputCrl.close();
} catch (IOException e) {
System.out.println("PrettyPrintCrl(): Unexpected BASE64 " +
- "encoded error encountered in close():\n" + e);
+ "encoded error encountered in close():\n" + e);
}
-
+
// (5) Decode the ASCII BASE 64 CRL enclosed in the
- // String() object into a BINARY BASE 64 byte[] object
+ // String() object into a BINARY BASE 64 byte[] object
decodedBASE64Crl = com.netscape.osutil.OSUtil.AtoB(encodedBASE64Crl);
// (6) Create an X509CRLImpl() object from the BINARY BASE 64
- // byte[] object
+ // byte[] object
try {
crl = new X509CRLImpl(decodedBASE64Crl);
} catch (CRLException e) {
System.out.println("PrettyPrintCrl(): Error encountered " +
- "on parsing and initialization errors:\n" + e);
+ "on parsing and initialization errors:\n" + e);
} catch (X509ExtensionException e) {
System.out.println("PrettyPrintCrl(): Error encountered " +
- "on parsing and initialization errors:\n" + e);
+ "on parsing and initialization errors:\n" + e);
}
// (7) For this utility, always specify the default Locale
- aLocale = Locale.getDefault();
+ aLocale = Locale.getDefault();
// (8) Create a CrlPrettyPrint() object
CrlDetails = new CrlPrettyPrint(crl);
@@ -179,7 +178,7 @@ public class PrettyPrintCrl {
pp = CrlDetails.toString(aLocale);
// (10) Finally, "pretty print" the actual CRL to the console
- // unless an output file has been specified
+ // unless an output file has been specified
if (argv.length != ARGC) {
System.out.println(pp);
} else {
@@ -187,7 +186,7 @@ public class PrettyPrintCrl {
outputCrl = new FileOutputStream(argv[1]);
} catch (IOException e) {
System.out.println("PrettyPrintCrl(): unable to open file " +
- argv[1] + " for writing:\n" + e);
+ argv[1] + " for writing:\n" + e);
return;
}
@@ -195,18 +194,17 @@ public class PrettyPrintCrl {
outputCrl.write(pp.getBytes());
} catch (IOException e) {
System.out.println("PrettyPrintCrl(): I/O error " +
- "encountered during write():\n" +
- e);
+ "encountered during write():\n" +
+ e);
}
try {
outputCrl.close();
} catch (IOException e) {
System.out.println("PrettyPrintCrl(): Unexpected error " +
- "encountered while attempting to close() " +
- argv[1] + ":\n" + e);
+ "encountered while attempting to close() " +
+ argv[1] + ":\n" + e);
}
}
}
}
-
diff --git a/pki/base/java-tools/src/com/netscape/cmstools/TestCRLSigning.java b/pki/base/java-tools/src/com/netscape/cmstools/TestCRLSigning.java
index d43b3533..2be5d03a 100644
--- a/pki/base/java-tools/src/com/netscape/cmstools/TestCRLSigning.java
+++ b/pki/base/java-tools/src/com/netscape/cmstools/TestCRLSigning.java
@@ -34,19 +34,17 @@ import org.mozilla.jss.util.Password;
/**
* Tool used to test out signing a CRL
- *
+ *
* <p>
+ *
* @version $Revision$ Date: $
*/
-public class TestCRLSigning
-{
- public static void printUsage()
- {
- System.out.println("Command <dbdir> <numreovked> <keysize> <tokenname> <tokenpwd>");
+public class TestCRLSigning {
+ public static void printUsage() {
+ System.out.println("Command <dbdir> <numreovked> <keysize> <tokenname> <tokenpwd>");
}
- public static void main(String args[]) throws Exception
- {
+ public static void main(String args[]) throws Exception {
String dir = args[0];
String num = args[1];
String keysize = args[2];
@@ -56,18 +54,18 @@ public class TestCRLSigning
// initialize JSS
CryptoManager cm = null;
CryptoManager.InitializationValues vals =
- new CryptoManager.InitializationValues(dir, "", "", "secmod.db");
+ new CryptoManager.InitializationValues(dir, "", "", "secmod.db");
CryptoManager.initialize(vals);
cm = CryptoManager.getInstance();
- // Login to token
+ // Login to token
CryptoToken token = null;
if (tokenname.equals("internal")) {
- token = cm.getInternalKeyStorageToken();
+ token = cm.getInternalKeyStorageToken();
} else {
- token = cm.getTokenByName(tokenname);
+ token = cm.getTokenByName(tokenname);
}
- Password pass = new Password(tokenpwd.toCharArray());
+ Password pass = new Password(tokenpwd.toCharArray());
token.login(pass);
// generate key pair
@@ -81,13 +79,13 @@ public class TestCRLSigning
Hashtable badCerts = new Hashtable();
int n = Integer.parseInt(num);
for (int i = 0; i < n; i++) {
- badCerts.put(Integer.toString(i),
- new RevokedCertImpl(new BigInteger(Integer.toString(i)), curDate));
+ badCerts.put(Integer.toString(i),
+ new RevokedCertImpl(new BigInteger(Integer.toString(i)), curDate));
}
long endPutting = System.currentTimeMillis();
long startConstructing = System.currentTimeMillis();
- X509CRLImpl crl = new X509CRLImpl(
+ X509CRLImpl crl = new X509CRLImpl(
new X500Name("CN=Signer"),
null,
curDate,
@@ -96,7 +94,6 @@ public class TestCRLSigning
null);
long endConstructing = System.currentTimeMillis();
-
System.out.println("Start signing");
long startSigning = System.currentTimeMillis();
crl.sign(pair.getPrivate(), "SHA1withRSA");
diff --git a/pki/base/java-tools/src/com/netscape/cmstools/TokenInfo.java b/pki/base/java-tools/src/com/netscape/cmstools/TokenInfo.java
index ade2b467..d695dcfa 100644
--- a/pki/base/java-tools/src/com/netscape/cmstools/TokenInfo.java
+++ b/pki/base/java-tools/src/com/netscape/cmstools/TokenInfo.java
@@ -17,59 +17,57 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmstools;
-
import java.util.Enumeration;
import org.mozilla.jss.CryptoManager;
import org.mozilla.jss.crypto.CryptoToken;
import org.mozilla.jss.pkcs11.PK11Module;
-
-
/**
* Tool used to determine which external hardware tokens are visible to the
* Certificate System subsystem. This can be used to diagnose whether problems
* using tokens are related to the Certificate System being unable to detect it.
- *
+ *
* <p>
+ *
* @version $Revision$ Date: $
*/
public class TokenInfo {
-
+
/**
- * Creates a new instance of CMCRevoke.
+ * Creates a new instance of CMCRevoke.
*/
- public static void main(String[]args) {
+ public static void main(String[] args) {
try {
- if (args.length != 1) {
- System.out.println("Usage: TokenInfo <alias directory>");
- System.exit(0);
- }
- System.out.println("Database Path: " + args[0]);
+ if (args.length != 1) {
+ System.out.println("Usage: TokenInfo <alias directory>");
+ System.exit(0);
+ }
+ System.out.println("Database Path: " + args[0]);
- CryptoManager.InitializationValues vals =
- new CryptoManager.InitializationValues(args[0],
- "", "", "secmod.db");
+ CryptoManager.InitializationValues vals =
+ new CryptoManager.InitializationValues(args[0],
+ "", "", "secmod.db");
- CryptoManager.initialize(vals);
-
- CryptoManager cm = CryptoManager.getInstance();
- Enumeration modules = cm.getModules();
- while (modules.hasMoreElements()) {
- PK11Module m = (PK11Module)modules.nextElement();
- System.out.println("Found external module '" + m.getName() + "'");
- }
- Enumeration tokens = cm.getExternalTokens();
+ CryptoManager.initialize(vals);
- while (tokens.hasMoreElements()) {
- CryptoToken t = (CryptoToken)tokens.nextElement();
- System.out.println("Found external token '" + t.getName() + "'");
- }
+ CryptoManager cm = CryptoManager.getInstance();
+ Enumeration modules = cm.getModules();
+ while (modules.hasMoreElements()) {
+ PK11Module m = (PK11Module) modules.nextElement();
+ System.out.println("Found external module '" + m.getName() + "'");
+ }
+ Enumeration tokens = cm.getExternalTokens();
- }catch (Exception e) {
- e.printStackTrace();
- System.exit(1);
+ while (tokens.hasMoreElements()) {
+ CryptoToken t = (CryptoToken) tokens.nextElement();
+ System.out.println("Found external token '" + t.getName() + "'");
}
-
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ System.exit(1);
+ }
+
}
}
diff --git a/pki/base/kra/src/com/netscape/kra/EncryptionUnit.java b/pki/base/kra/src/com/netscape/kra/EncryptionUnit.java
index cbd3b7a3..32d1dd29 100644
--- a/pki/base/kra/src/com/netscape/kra/EncryptionUnit.java
+++ b/pki/base/kra/src/com/netscape/kra/EncryptionUnit.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.kra;
-
import java.io.CharConversionException;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
@@ -48,20 +47,20 @@ import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.security.IEncryptionUnit;
import com.netscape.cmscore.util.Debug;
-
/**
- * A class represents the transport key pair. This key pair
- * is used to protected EE's private key in transit.
- *
+ * A class represents the transport key pair. This key pair is used to protected
+ * EE's private key in transit.
+ *
* @author thomask
* @version $Revision$, $Date$
*/
public abstract class EncryptionUnit implements IEncryptionUnit {
- /* Establish one constant IV for base class, to be used for
- internal operations. Constant IV acceptable for symmetric keys.
- */
- private byte iv[] = {0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1};
+ /*
+ * Establish one constant IV for base class, to be used for internal
+ * operations. Constant IV acceptable for symmetric keys.
+ */
+ private byte iv[] = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 };
protected IVParameterSpec IV = null;
public EncryptionUnit() {
@@ -79,19 +78,18 @@ public abstract class EncryptionUnit implements IEncryptionUnit {
public abstract PrivateKey getPrivateKey();
/**
- * Protects the private key so that it can be stored in
- * internal database.
+ * Protects the private key so that it can be stored in internal database.
*/
- public byte[] encryptInternalPrivate(byte priKey[])
- throws EBaseException {
+ public byte[] encryptInternalPrivate(byte priKey[])
+ throws EBaseException {
try {
CMS.debug("EncryptionUnit.encryptInternalPrivate");
CryptoToken token = getToken();
CryptoToken internalToken = getInternalToken();
// (1) generate session key
- org.mozilla.jss.crypto.KeyGenerator kg =
- internalToken.getKeyGenerator(KeyGenAlgorithm.DES3);
+ org.mozilla.jss.crypto.KeyGenerator kg =
+ internalToken.getKeyGenerator(KeyGenAlgorithm.DES3);
SymmetricKey sk = kg.generate();
// (2) wrap private key with session key
@@ -110,17 +108,17 @@ public abstract class EncryptionUnit implements IEncryptionUnit {
// use MY own structure for now:
// SEQUENCE {
- // encryptedSession OCTET STRING,
- // encryptedPrivate OCTET STRING
+ // encryptedSession OCTET STRING,
+ // encryptedPrivate OCTET STRING
// }
-
+
DerOutputStream tmp = new DerOutputStream();
DerOutputStream out = new DerOutputStream();
tmp.putOctetString(session);
tmp.putOctetString(pri);
out.write(DerValue.tag_Sequence, tmp);
-
+
return out.toByteArray();
} catch (TokenException e) {
CMS.getLogger().log(ILogger.EV_SYSTEM, null, ILogger.S_KRA, ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_KRA_ENCRYPTION_INTERNAL", e.toString()));
@@ -171,16 +169,16 @@ public abstract class EncryptionUnit implements IEncryptionUnit {
CryptoToken token = getToken();
// (1) generate session key
- org.mozilla.jss.crypto.KeyGenerator kg =
- token.getKeyGenerator(KeyGenAlgorithm.DES3);
- // internalToken.getKeyGenerator(KeyGenAlgorithm.DES3);
+ org.mozilla.jss.crypto.KeyGenerator kg =
+ token.getKeyGenerator(KeyGenAlgorithm.DES3);
+ // internalToken.getKeyGenerator(KeyGenAlgorithm.DES3);
SymmetricKey.Usage usages[] = new SymmetricKey.Usage[2];
usages[0] = SymmetricKey.Usage.WRAP;
usages[1] = SymmetricKey.Usage.UNWRAP;
kg.setKeyUsages(usages);
kg.temporaryKeys(true);
SymmetricKey sk = kg.generate();
- CMS.debug("EncryptionUnit:wrap() session key generated on slot: "+token.getName());
+ CMS.debug("EncryptionUnit:wrap() session key generated on slot: " + token.getName());
// (2) wrap private key with session key
// KeyWrapper wrapper = internalToken.getKeyWrapper(
@@ -189,7 +187,7 @@ public abstract class EncryptionUnit implements IEncryptionUnit {
wrapper.initWrap(sk, IV);
byte pri[] = wrapper.wrap(priKey);
- CMS.debug("EncryptionUnit:wrap() privKey wrapped");
+ CMS.debug("EncryptionUnit:wrap() privKey wrapped");
// (3) wrap session with transport public
KeyWrapper rsaWrap = token.getKeyWrapper(
@@ -197,21 +195,21 @@ public abstract class EncryptionUnit implements IEncryptionUnit {
rsaWrap.initWrap(getPublicKey(), null);
byte session[] = rsaWrap.wrap(sk);
- CMS.debug("EncryptionUnit:wrap() sessin key wrapped");
+ CMS.debug("EncryptionUnit:wrap() sessin key wrapped");
// use MY own structure for now:
// SEQUENCE {
- // encryptedSession OCTET STRING,
- // encryptedPrivate OCTET STRING
+ // encryptedSession OCTET STRING,
+ // encryptedPrivate OCTET STRING
// }
-
+
DerOutputStream tmp = new DerOutputStream();
DerOutputStream out = new DerOutputStream();
tmp.putOctetString(session);
tmp.putOctetString(pri);
out.write(DerValue.tag_Sequence, tmp);
-
+
return out.toByteArray();
} catch (TokenException e) {
CMS.getLogger().log(ILogger.EV_SYSTEM, null, ILogger.S_KRA, ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_KRA_ENCRYPTION_WRAP", e.toString()));
@@ -245,18 +243,16 @@ public abstract class EncryptionUnit implements IEncryptionUnit {
}
/**
- * External unwrapping. Unwraps the data using
- * the transport private key.
+ * External unwrapping. Unwraps the data using the transport private key.
*/
- public SymmetricKey unwrap_sym(byte encSymmKey[], SymmetricKey.Usage usage)
- {
+ public SymmetricKey unwrap_sym(byte encSymmKey[], SymmetricKey.Usage usage) {
try {
CryptoToken token = getToken();
// (1) unwrap the session
PrivateKey priKey = getPrivateKey();
String priKeyAlgo = priKey.getAlgorithm();
- CMS.debug("EncryptionUnit::unwrap_sym() private key algo: " + priKeyAlgo);
+ CMS.debug("EncryptionUnit::unwrap_sym() private key algo: " + priKeyAlgo);
KeyWrapper keyWrapper = null;
if (priKeyAlgo.equals("EC")) {
keyWrapper = token.getKeyWrapper(KeyWrapAlgorithm.AES_ECB);
@@ -268,8 +264,8 @@ public abstract class EncryptionUnit implements IEncryptionUnit {
SymmetricKey sk = keyWrapper.unwrapSymmetric(encSymmKey,
SymmetricKey.DES3, usage,
0);
- CMS.debug("EncryptionUnit::unwrap_sym() unwrapped on slot: "
- +token.getName());
+ CMS.debug("EncryptionUnit::unwrap_sym() unwrapped on slot: "
+ + token.getName());
return sk;
} catch (Exception e) {
CMS.debug("EncryptionUnit::unwrap_sym() error:" +
@@ -278,23 +274,21 @@ public abstract class EncryptionUnit implements IEncryptionUnit {
}
}
- public SymmetricKey unwrap_sym(byte encSymmKey[])
- {
+ public SymmetricKey unwrap_sym(byte encSymmKey[]) {
return unwrap_sym(encSymmKey, SymmetricKey.Usage.WRAP);
}
-
- public SymmetricKey unwrap_encrypt_sym(byte encSymmKey[])
- {
+
+ public SymmetricKey unwrap_encrypt_sym(byte encSymmKey[]) {
return unwrap_sym(encSymmKey, SymmetricKey.Usage.ENCRYPT);
}
/**
* Decrypts the user private key.
*/
- public byte[] decryptExternalPrivate(byte encSymmKey[],
- String symmAlgOID, byte symmAlgParams[],
- byte encValue[])
- throws EBaseException {
+ public byte[] decryptExternalPrivate(byte encSymmKey[],
+ String symmAlgOID, byte symmAlgParams[],
+ byte encValue[])
+ throws EBaseException {
try {
CMS.debug("EncryptionUnit.decryptExternalPrivate");
@@ -312,7 +306,7 @@ public abstract class EncryptionUnit implements IEncryptionUnit {
// (2) unwrap the pri
Cipher cipher = token.getCipherContext(
EncryptionAlgorithm.DES3_CBC_PAD // XXX
- );
+ );
cipher.initDecrypt(sk, new IVParameterSpec(
symmAlgParams));
@@ -349,13 +343,12 @@ public abstract class EncryptionUnit implements IEncryptionUnit {
}
/**
- * External unwrapping. Unwraps the data using
- * the transport private key.
+ * External unwrapping. Unwraps the data using the transport private key.
*/
- public PrivateKey unwrap(byte encSymmKey[],
- String symmAlgOID, byte symmAlgParams[],
- byte encValue[], PublicKey pubKey)
- throws EBaseException {
+ public PrivateKey unwrap(byte encSymmKey[],
+ String symmAlgOID, byte symmAlgParams[],
+ byte encValue[], PublicKey pubKey)
+ throws EBaseException {
try {
CryptoToken token = getToken();
@@ -371,12 +364,12 @@ public abstract class EncryptionUnit implements IEncryptionUnit {
// (2) unwrap the pri
KeyWrapper wrapper = token.getKeyWrapper(
KeyWrapAlgorithm.DES3_CBC_PAD // XXX
- );
+ );
wrapper.initUnwrap(sk, new IVParameterSpec(
symmAlgParams));
- PrivateKey.Type keytype = null;
+ PrivateKey.Type keytype = null;
String alg = pubKey.getAlgorithm();
if (alg.equals("DSA")) {
keytype = PrivateKey.DSA;
@@ -386,7 +379,7 @@ public abstract class EncryptionUnit implements IEncryptionUnit {
keytype = PrivateKey.RSA;
}
PrivateKey pk = wrapper.unwrapTemporaryPrivate(encValue,
- keytype , pubKey);
+ keytype, pubKey);
return pk;
} catch (TokenException e) {
@@ -406,13 +399,13 @@ public abstract class EncryptionUnit implements IEncryptionUnit {
Debug.trace("EncryptionUnit::unwrap " + e.toString());
return null;
} catch (Exception e) {
- CMS.debug("EncryptionUnit.unwrap : Exception:"+e.toString());
+ CMS.debug("EncryptionUnit.unwrap : Exception:" + e.toString());
return null;
}
}
- public byte[] decryptInternalPrivate(byte wrappedKeyData[])
- throws EBaseException {
+ public byte[] decryptInternalPrivate(byte wrappedKeyData[])
+ throws EBaseException {
try {
CMS.debug("EncryptionUnit.decryptInternalPrivate");
DerValue val = new DerValue(wrappedKeyData);
@@ -426,7 +419,7 @@ public abstract class EncryptionUnit implements IEncryptionUnit {
CryptoToken token = getToken();
// (1) unwrap the session
- CMS.debug("decryptInternalPrivate(): getting key wrapper on slot:"+ token.getName());
+ CMS.debug("decryptInternalPrivate(): getting key wrapper on slot:" + token.getName());
KeyWrapper rsaWrap = token.getKeyWrapper(
KeyWrapAlgorithm.RSA);
@@ -478,16 +471,16 @@ public abstract class EncryptionUnit implements IEncryptionUnit {
/**
* Internal unwrapping.
*/
- public PrivateKey unwrap_temp(byte wrappedKeyData[], PublicKey pubKey)
- throws EBaseException {
+ public PrivateKey unwrap_temp(byte wrappedKeyData[], PublicKey pubKey)
+ throws EBaseException {
return _unwrap(wrappedKeyData, pubKey, true);
}
/**
* Internal unwrapping.
*/
- public PrivateKey unwrap(byte wrappedKeyData[], PublicKey pubKey)
- throws EBaseException {
+ public PrivateKey unwrap(byte wrappedKeyData[], PublicKey pubKey)
+ throws EBaseException {
return _unwrap(wrappedKeyData, pubKey, false);
}
@@ -495,8 +488,8 @@ public abstract class EncryptionUnit implements IEncryptionUnit {
* Internal unwrapping.
*/
private PrivateKey _unwrap(byte wrappedKeyData[], PublicKey
- pubKey, boolean temporary)
- throws EBaseException {
+ pubKey, boolean temporary)
+ throws EBaseException {
try {
DerValue val = new DerValue(wrappedKeyData);
// val.tag == DerValue.tag_Sequence
@@ -523,11 +516,11 @@ public abstract class EncryptionUnit implements IEncryptionUnit {
PrivateKey pk = null;
if (temporary) {
- pk = wrapper.unwrapTemporaryPrivate(pri,
- PrivateKey.RSA, pubKey);
+ pk = wrapper.unwrapTemporaryPrivate(pri,
+ PrivateKey.RSA, pubKey);
} else {
- pk = wrapper.unwrapPrivate(pri,
- PrivateKey.RSA, pubKey);
+ pk = wrapper.unwrapPrivate(pri,
+ PrivateKey.RSA, pubKey);
}
return pk;
} catch (TokenException e) {
@@ -553,7 +546,7 @@ public abstract class EncryptionUnit implements IEncryptionUnit {
return null;
} catch (Exception e) {
Debug.printStackTrace(e);
- return null;
+ return null;
}
}
@@ -564,4 +557,3 @@ public abstract class EncryptionUnit implements IEncryptionUnit {
EBaseException {
}
}
-
diff --git a/pki/base/kra/src/com/netscape/kra/EnrollmentService.java b/pki/base/kra/src/com/netscape/kra/EnrollmentService.java
index 6415e190..4ed45512 100644
--- a/pki/base/kra/src/com/netscape/kra/EnrollmentService.java
+++ b/pki/base/kra/src/com/netscape/kra/EnrollmentService.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.kra;
-
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigInteger;
@@ -76,21 +75,17 @@ import com.netscape.cmscore.crmf.CRMFParser;
import com.netscape.cmscore.crmf.PKIArchiveOptionsContainer;
import com.netscape.cmscore.dbs.KeyRecord;
-
/**
- * A class represents archival request processor. It
- * passes the request to the policy processor, and
- * process the request according to the policy decision.
+ * A class represents archival request processor. It passes the request to the
+ * policy processor, and process the request according to the policy decision.
* <P>
- * If policy returns ACCEPTED, the request will be
- * processed immediately.
+ * If policy returns ACCEPTED, the request will be processed immediately.
* <P>
- * Upon processing, the incoming user key is unwrapped
- * with the transport key of KRA, and then wrapped
- * with the storage key. The encrypted key is stored
- * in the internal database for long term storage.
+ * Upon processing, the incoming user key is unwrapped with the transport key of
+ * KRA, and then wrapped with the storage key. The encrypted key is stored in
+ * the internal database for long term storage.
* <P>
- *
+ *
* @author thomask (original)
* @author cfu (non-RSA keys; private keys secure handling);
* @version $Revision$, $Date$
@@ -100,27 +95,25 @@ public class EnrollmentService implements IService {
// constants
public static final String CRMF_REQUEST = "CRMFRequest";
public final static String ATTR_KEY_RECORD = "keyRecord";
- public final static String ATTR_PROOF_OF_ARCHIVAL =
- "proofOfArchival";
+ public final static String ATTR_PROOF_OF_ARCHIVAL =
+ "proofOfArchival";
- // private
+ // private
private IKeyRecoveryAuthority mKRA = null;
private ITransportKeyUnit mTransportUnit = null;
private IStorageKeyUnit mStorageUnit = null;
private ILogger mSignedAuditLogger = CMS.getSignedAuditLogger();
-
private final static byte EOL[] = { Character.LINE_SEPARATOR };
- private final static String
- LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST =
- "LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST_4";
- private final static String
- LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST_PROCESSED =
- "LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST_PROCESSED_3";
+ private final static String LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST =
+ "LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST_4";
+ private final static String LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST_PROCESSED =
+ "LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST_PROCESSED_3";
private final static String LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST =
- "LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_4";
+ "LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_4";
private final static String LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED =
- "LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED_4";
+ "LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED_4";
+
/**
* Constructs request processor.
* <P>
@@ -145,21 +138,21 @@ public class EnrollmentService implements IService {
}
return archOpts;
}
-
+
/**
* Services an enrollment/archival request.
* <P>
- *
+ *
* @param request enrollment request
* @return serving successful or not
* @exception EBaseException failed to serve
*/
- public boolean serviceRequest(IRequest request)
- throws EBaseException {
+ public boolean serviceRequest(IRequest request)
+ throws EBaseException {
- IStatsSubsystem statsSub = (IStatsSubsystem)CMS.getSubsystem("stats");
+ IStatsSubsystem statsSub = (IStatsSubsystem) CMS.getSubsystem("stats");
if (statsSub != null) {
- statsSub.startTiming("archival", true /* main action */);
+ statsSub.startTiming("archival", true /* main action */);
}
String auditMessage = null;
@@ -206,35 +199,35 @@ public class EnrollmentService implements IService {
} else {
// profile-based request
PKIArchiveOptions options = (PKIArchiveOptions)
- toPKIArchiveOptions(
+ toPKIArchiveOptions(
request.getExtDataInByteArray(IEnrollProfile.REQUEST_ARCHIVE_OPTIONS));
aOpts = new PKIArchiveOptionsContainer[1];
- aOpts[0] = new PKIArchiveOptionsContainer(options,
+ aOpts[0] = new PKIArchiveOptionsContainer(options,
0/* not matter */);
request.setExtData("dbStatus", "NOT_UPDATED");
- }
+ }
for (int i = 0; i < aOpts.length; i++) {
ArchiveOptions opts = new ArchiveOptions(aOpts[i].mAO);
if (statsSub != null) {
- statsSub.startTiming("decrypt_user_key");
+ statsSub.startTiming("decrypt_user_key");
}
mKRA.log(ILogger.LL_INFO, "KRA decrypts external private");
if (CMS.debugOn())
- CMS.debug("EnrollmentService::about to decryptExternalPrivate");
+ CMS.debug("EnrollmentService::about to decryptExternalPrivate");
unwrapped = mTransportUnit.decryptExternalPrivate(
- opts.getEncSymmKey(),
- opts.getSymmAlgOID(),
- opts.getSymmAlgParams(),
+ opts.getEncSymmKey(),
+ opts.getSymmAlgOID(),
+ opts.getSymmAlgParams(),
opts.getEncValue());
if (statsSub != null) {
- statsSub.endTiming("decrypt_user_key");
+ statsSub.endTiming("decrypt_user_key");
}
if (CMS.debugOn())
- CMS.debug("EnrollmentService::finished decryptExternalPrivate");
+ CMS.debug("EnrollmentService::finished decryptExternalPrivate");
if (unwrapped == null) {
mKRA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_KRA_UNWRAP_USER_KEY"));
@@ -255,9 +248,8 @@ public class EnrollmentService implements IService {
byte publicKeyData[] = publicKey.getEncoded();
if (publicKeyData == null) {
- mKRA.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_KRA_PUBLIC_NOT_FOUND"));
-
+ mKRA.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_KRA_PUBLIC_NOT_FOUND"));
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST,
@@ -271,15 +263,17 @@ public class EnrollmentService implements IService {
CMS.getUserMessage("CMS_KRA_INVALID_PUBLIC_KEY"));
}
- /* Bugscape #54948 - verify public and private key before archiving key */
+ /*
+ * Bugscape #54948 - verify public and private key before archiving
+ * key
+ */
if (statsSub != null) {
- statsSub.startTiming("verify_key");
+ statsSub.startTiming("verify_key");
}
if (verifyKeyPair(publicKeyData, unwrapped) == false) {
- mKRA.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_KRA_PUBLIC_NOT_FOUND"));
-
+ mKRA.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_KRA_PUBLIC_NOT_FOUND"));
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST,
@@ -293,11 +287,11 @@ public class EnrollmentService implements IService {
CMS.getUserMessage("CMS_KRA_INVALID_PUBLIC_KEY"));
}
if (statsSub != null) {
- statsSub.endTiming("verify_key");
+ statsSub.endTiming("verify_key");
}
/**
- mTransportKeyUnit.verify(pKey, unwrapped);
+ * mTransportKeyUnit.verify(pKey, unwrapped);
**/
// retrieve owner name
String owner = getOwnerName(request, aOpts[i].mReqPos);
@@ -318,18 +312,18 @@ public class EnrollmentService implements IService {
//
// privateKeyData ::= SEQUENCE {
- // sessionKey OCTET_STRING,
- // encKey OCTET_STRING,
- // }
+ // sessionKey OCTET_STRING,
+ // encKey OCTET_STRING,
+ // }
//
mKRA.log(ILogger.LL_INFO, "KRA encrypts internal private");
if (statsSub != null) {
- statsSub.startTiming("encrypt_user_key");
+ statsSub.startTiming("encrypt_user_key");
}
byte privateKeyData[] = mStorageUnit.encryptInternalPrivate(
unwrapped);
if (statsSub != null) {
- statsSub.endTiming("encrypt_user_key");
+ statsSub.endTiming("encrypt_user_key");
}
if (privateKeyData == null) {
@@ -348,8 +342,8 @@ public class EnrollmentService implements IService {
}
// create key record
- KeyRecord rec = new KeyRecord(null, publicKeyData,
- privateKeyData, owner,
+ KeyRecord rec = new KeyRecord(null, publicKeyData,
+ privateKeyData, owner,
publicKey.getAlgorithmId().getOID().toString(), agentId);
// we deal with RSA key only
@@ -370,13 +364,11 @@ public class EnrollmentService implements IService {
throw new EKRAException(CMS.getUserMessage("CMS_KRA_INVALID_KEYRECORD"));
}
-
// if record alreay has a serial number, yell out.
if (rec.getSerialNumber() != null) {
- mKRA.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_KRA_INVALID_SERIAL_NUMBER",
- rec.getSerialNumber().toString()));
-
+ mKRA.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_KRA_INVALID_SERIAL_NUMBER",
+ rec.getSerialNumber().toString()));
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST,
@@ -392,8 +384,8 @@ public class EnrollmentService implements IService {
BigInteger serialNo = storage.getNextSerialNumber();
if (serialNo == null) {
- mKRA.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_KRA_GET_NEXT_SERIAL"));
+ mKRA.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_KRA_GET_NEXT_SERIAL"));
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST,
@@ -415,43 +407,42 @@ public class EnrollmentService implements IService {
mKRA.log(ILogger.LL_INFO, "KRA adding key record " + serialNo);
if (statsSub != null) {
- statsSub.startTiming("store_key");
+ statsSub.startTiming("store_key");
}
storage.addKeyRecord(rec);
if (statsSub != null) {
- statsSub.endTiming("store_key");
+ statsSub.endTiming("store_key");
}
-
+
if (CMS.debugOn())
CMS.debug("EnrollmentService: key record 0x" + serialNo.toString(16)
- + " (" + owner + ") archived");
+ + " (" + owner + ") archived");
- mKRA.log(ILogger.LL_INFO, "key record 0x" +
- serialNo.toString(16)
- + " (" + owner + ") archived");
+ mKRA.log(ILogger.LL_INFO, "key record 0x" +
+ serialNo.toString(16)
+ + " (" + owner + ") archived");
// for audit log
String authMgr = AuditFormat.NOAUTH;
-
+
if (authToken != null) {
authMgr =
authToken.getInString(AuthToken.TOKEN_AUTHMGR_INST_NAME);
}
CMS.getLogger().log(ILogger.EV_AUDIT,
- ILogger.S_KRA,
- AuditFormat.LEVEL,
- AuditFormat.FORMAT,
- new Object[] {
- IRequest.KEYARCHIVAL_REQUEST,
- request.getRequestId(),
- AuditFormat.FROMAGENT + " agentID: " + agentId,
- authMgr,
- "completed",
- owner,
- "serial number: 0x" + serialNo.toString(16)}
- );
+ ILogger.S_KRA,
+ AuditFormat.LEVEL,
+ AuditFormat.FORMAT,
+ new Object[] {
+ IRequest.KEYARCHIVAL_REQUEST,
+ request.getRequestId(),
+ AuditFormat.FROMAGENT + " agentID: " + agentId,
+ authMgr,
+ "completed",
+ owner,
+ "serial number: 0x" + serialNo.toString(16) }
+ );
-
// store a message in the signed audit log file
auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST,
@@ -486,16 +477,16 @@ public class EnrollmentService implements IService {
request.setExtData(ATTR_PROOF_OF_ARCHIVAL + i,
mProofOut.toByteArray());
}
-
+
} // for
/*
- request.delete(IEnrollProfile.REQUEST_SUBJECT_NAME);
- request.delete(IEnrollProfile.REQUEST_EXTENSIONS);
- request.delete(IEnrollProfile.REQUEST_VALIDITY);
- request.delete(IEnrollProfile.REQUEST_KEY);
- request.delete(IEnrollProfile.REQUEST_SIGNING_ALGORITHM);
- request.delete(IEnrollProfile.REQUEST_LOCALE);
+ * request.delete(IEnrollProfile.REQUEST_SUBJECT_NAME);
+ * request.delete(IEnrollProfile.REQUEST_EXTENSIONS);
+ * request.delete(IEnrollProfile.REQUEST_VALIDITY);
+ * request.delete(IEnrollProfile.REQUEST_KEY);
+ * request.delete(IEnrollProfile.REQUEST_SIGNING_ALGORITHM);
+ * request.delete(IEnrollProfile.REQUEST_LOCALE);
*/
request.setExtData(IRequest.RESULT, IRequest.RES_SUCCESS);
@@ -505,65 +496,64 @@ public class EnrollmentService implements IService {
mKRA.getRequestQueue().updateRequest(request);
if (statsSub != null) {
- statsSub.endTiming("archival");
+ statsSub.endTiming("archival");
}
-
+
return true;
}
- public boolean verifyKeyPair(byte publicKeyData[], byte privateKeyData[])
- {
- try {
- DerValue publicKeyVal = new DerValue(publicKeyData);
- DerInputStream publicKeyIn = publicKeyVal.data;
- publicKeyIn.getSequence(0);
- DerValue publicKeyDer = new DerValue(publicKeyIn.getBitString());
- DerInputStream publicKeyDerIn = publicKeyDer.data;
- BigInt publicKeyModulus = publicKeyDerIn.getInteger();
- BigInt publicKeyExponent = publicKeyDerIn.getInteger();
-
- DerValue privateKeyVal = new DerValue(privateKeyData);
- if (privateKeyVal.tag != DerValue.tag_Sequence)
- return false;
- DerInputStream privateKeyIn = privateKeyVal.data;
- privateKeyIn.getInteger();
- privateKeyIn.getSequence(0);
- DerValue privateKeyDer = new DerValue(privateKeyIn.getOctetString());
- DerInputStream privateKeyDerIn = privateKeyDer.data;
- BigInt privateKeyVersion = privateKeyDerIn.getInteger();
- BigInt privateKeyModulus = privateKeyDerIn.getInteger();
- BigInt privateKeyExponent = privateKeyDerIn.getInteger();
-
- if (!publicKeyModulus.equals(privateKeyModulus)) {
- CMS.debug("verifyKeyPair modulus mismatch publicKeyModulus=" + publicKeyModulus + " privateKeyModulus=" + privateKeyModulus);
- return false;
- }
-
- if (!publicKeyExponent.equals(privateKeyExponent)) {
- CMS.debug("verifyKeyPair exponent mismatch publicKeyExponent=" + publicKeyExponent + " privateKeyExponent=" + privateKeyExponent);
- return false;
- }
-
- return true;
- } catch (Exception e) {
- CMS.debug("verifyKeyPair error " + e);
- return false;
- }
+ public boolean verifyKeyPair(byte publicKeyData[], byte privateKeyData[]) {
+ try {
+ DerValue publicKeyVal = new DerValue(publicKeyData);
+ DerInputStream publicKeyIn = publicKeyVal.data;
+ publicKeyIn.getSequence(0);
+ DerValue publicKeyDer = new DerValue(publicKeyIn.getBitString());
+ DerInputStream publicKeyDerIn = publicKeyDer.data;
+ BigInt publicKeyModulus = publicKeyDerIn.getInteger();
+ BigInt publicKeyExponent = publicKeyDerIn.getInteger();
+
+ DerValue privateKeyVal = new DerValue(privateKeyData);
+ if (privateKeyVal.tag != DerValue.tag_Sequence)
+ return false;
+ DerInputStream privateKeyIn = privateKeyVal.data;
+ privateKeyIn.getInteger();
+ privateKeyIn.getSequence(0);
+ DerValue privateKeyDer = new DerValue(privateKeyIn.getOctetString());
+ DerInputStream privateKeyDerIn = privateKeyDer.data;
+ BigInt privateKeyVersion = privateKeyDerIn.getInteger();
+ BigInt privateKeyModulus = privateKeyDerIn.getInteger();
+ BigInt privateKeyExponent = privateKeyDerIn.getInteger();
+
+ if (!publicKeyModulus.equals(privateKeyModulus)) {
+ CMS.debug("verifyKeyPair modulus mismatch publicKeyModulus=" + publicKeyModulus + " privateKeyModulus=" + privateKeyModulus);
+ return false;
+ }
+
+ if (!publicKeyExponent.equals(privateKeyExponent)) {
+ CMS.debug("verifyKeyPair exponent mismatch publicKeyExponent=" + publicKeyExponent + " privateKeyExponent=" + privateKeyExponent);
+ return false;
+ }
+
+ return true;
+ } catch (Exception e) {
+ CMS.debug("verifyKeyPair error " + e);
+ return false;
+ }
}
private static final OBJECT_IDENTIFIER PKIARCHIVEOPTIONS_OID =
- new OBJECT_IDENTIFIER(new long[] {1, 3, 6, 1, 5, 5, 7, 5, 1, 4}
- );
+ new OBJECT_IDENTIFIER(new long[] { 1, 3, 6, 1, 5, 5, 7, 5, 1, 4 }
+ );
/**
* Retrieves PKIArchiveOptions from CRMF request.
- *
+ *
* @param crmfBlob CRMF request
* @return PKIArchiveOptions
* @exception EBaseException failed to extrace option
*/
- public static PKIArchiveOptionsContainer[] getPKIArchiveOptions(String crmfBlob)
- throws EBaseException {
+ public static PKIArchiveOptionsContainer[] getPKIArchiveOptions(String crmfBlob)
+ throws EBaseException {
Vector options = new Vector();
if (CMS.debugOn())
@@ -571,15 +561,15 @@ public class EnrollmentService implements IService {
byte[] crmfBerBlob = null;
crmfBerBlob = com.netscape.osutil.OSUtil.AtoB(crmfBlob);
- ByteArrayInputStream crmfBerBlobIn = new
- ByteArrayInputStream(crmfBerBlob);
+ ByteArrayInputStream crmfBerBlobIn = new
+ ByteArrayInputStream(crmfBerBlob);
SEQUENCE crmfmsgs = null;
try {
- crmfmsgs = (SEQUENCE) new
- SEQUENCE.OF_Template(new
- CertReqMsg.Template()).decode(
- crmfBerBlobIn);
+ crmfmsgs = (SEQUENCE) new
+ SEQUENCE.OF_Template(new
+ CertReqMsg.Template()).decode(
+ crmfBerBlobIn);
} catch (IOException e) {
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTRIBUTE", "[crmf msgs]" + e.toString()));
} catch (InvalidBERException e) {
@@ -588,9 +578,9 @@ public class EnrollmentService implements IService {
for (int z = 0; z < crmfmsgs.size(); z++) {
CertReqMsg certReqMsg = (CertReqMsg)
- crmfmsgs.elementAt(z);
- CertRequest certReq = certReqMsg.getCertReq();
-
+ crmfmsgs.elementAt(z);
+ CertRequest certReq = certReqMsg.getCertReq();
+
// try to locate PKIArchiveOption control
AVA archAva = null;
@@ -627,7 +617,7 @@ public class EnrollmentService implements IService {
if (options.size() == 0) {
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTRIBUTE", "PKIArchiveOptions found"));
} else {
- PKIArchiveOptionsContainer p[] = new PKIArchiveOptionsContainer[options.size()];
+ PKIArchiveOptionsContainer p[] = new PKIArchiveOptionsContainer[options.size()];
options.copyInto(p);
return p;
@@ -636,7 +626,7 @@ public class EnrollmentService implements IService {
/**
* Retrieves public key from request.
- *
+ *
* @param request CRMF request
* @return JSS public key
* @exception EBaseException failed to retrieve public key
@@ -662,19 +652,19 @@ public class EnrollmentService implements IService {
// retrieve x509 Key from request
X509CertInfo certInfo[] =
- request.getExtDataInCertInfoArray(IRequest.CERT_INFO);
+ request.getExtDataInCertInfoArray(IRequest.CERT_INFO);
CertificateX509Key pX509Key = null;
try {
pX509Key = (CertificateX509Key)
certInfo[i].get(X509CertInfo.KEY);
} catch (IOException e) {
- mKRA.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_KRA_GET_PUBLIC_KEY", e.toString()));
+ mKRA.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_KRA_GET_PUBLIC_KEY", e.toString()));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTRIBUTE", "[" + X509CertInfo.KEY + "]" + e.toString()));
} catch (CertificateException e) {
- mKRA.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_KRA_GET_PUBLIC_KEY", e.toString()));
+ mKRA.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_KRA_GET_PUBLIC_KEY", e.toString()));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTRIBUTE", "[" + X509CertInfo.KEY + "]" + e.toString()));
}
X509Key pKey = null;
@@ -683,8 +673,8 @@ public class EnrollmentService implements IService {
pKey = (X509Key) pX509Key.get(
CertificateX509Key.KEY);
} catch (IOException e) {
- mKRA.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_KRA_GET_PUBLIC_KEY", e.toString()));
+ mKRA.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_KRA_GET_PUBLIC_KEY", e.toString()));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTRIBUTE", "[" + CertificateX509Key.KEY + "]" + e.toString()));
}
return pKey;
@@ -692,13 +682,13 @@ public class EnrollmentService implements IService {
/**
* Retrieves key's owner name from request.
- *
+ *
* @param request CRMF request
* @return owner name (subject name)
* @exception EBaseException failed to retrieve public key
*/
- private String getOwnerName(IRequest request, int i)
- throws EBaseException {
+ private String getOwnerName(IRequest request, int i)
+ throws EBaseException {
String profileId = request.getExtDataInString("profileId");
@@ -711,19 +701,19 @@ public class EnrollmentService implements IService {
}
X509CertInfo certInfo[] =
- request.getExtDataInCertInfoArray(IRequest.CERT_INFO);
+ request.getExtDataInCertInfoArray(IRequest.CERT_INFO);
CertificateSubjectName pSub = null;
try {
pSub = (CertificateSubjectName)
certInfo[0].get(X509CertInfo.SUBJECT);
} catch (IOException e) {
- mKRA.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_KRA_GET_OWNER_NAME", e.toString()));
+ mKRA.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_KRA_GET_OWNER_NAME", e.toString()));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTRIBUTE", "[" + X509CertInfo.SUBJECT + "]" + e.toString()));
} catch (CertificateException e) {
- mKRA.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_KRA_GET_OWNER_NAME", e.toString()));
+ mKRA.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_KRA_GET_OWNER_NAME", e.toString()));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTRIBUTE", "[" + X509CertInfo.SUBJECT + "]" + e.toString()));
}
String owner = pSub.toString();
@@ -733,11 +723,11 @@ public class EnrollmentService implements IService {
/**
* Signed Audit Log Public Key
- *
+ *
* This method is called to obtain the public key from the passed in
* "KeyRecord" for a signed audit log message.
* <P>
- *
+ *
* @param rec a Key Record
* @return key string containing the certificate's public key
*/
@@ -770,29 +760,30 @@ public class EnrollmentService implements IService {
// extract all line separators from the "base64Data"
StringTokenizer st = new StringTokenizer(base64Data, "\r\n");
while (st.hasMoreTokens()) {
- key += st.nextToken();
+ key += st.nextToken();
}
}
key = key.trim();
- if (key.equals("")) {
- return ILogger.SIGNED_AUDIT_EMPTY_VALUE;
- } else {
- return key;
- }
+ if (key.equals("")) {
+ return ILogger.SIGNED_AUDIT_EMPTY_VALUE;
+ } else {
+ return key;
+ }
}
+
/**
* Signed Audit Log Subject ID
- *
- * This method is called to obtain the "SubjectID" for
- * a signed audit log message.
+ *
+ * This method is called to obtain the "SubjectID" for a signed audit log
+ * message.
* <P>
- *
+ *
* @return id string containing the signed audit log message SubjectID
*/
- private String auditSubjectID() {
+ private String auditSubjectID() {
// if no signed audit object exists, bail
if (mSignedAuditLogger == null) {
return null;
@@ -818,13 +809,14 @@ public class EnrollmentService implements IService {
return subjectID;
}
+
/**
* Signed Audit Log Requester ID
- *
- * This method is called to obtain the "RequesterID" for
- * a signed audit log message.
+ *
+ * This method is called to obtain the "RequesterID" for a signed audit log
+ * message.
* <P>
- *
+ *
* @return id string containing the signed audit log message RequesterID
*/
private String auditRequesterID() {
@@ -856,10 +848,10 @@ public class EnrollmentService implements IService {
/**
* Signed Audit Log
- *
+ *
* This method is called to store messages to the signed audit log.
* <P>
- *
+ *
* @param msg signed audit log message
*/
private void audit(String msg) {
@@ -871,14 +863,13 @@ public class EnrollmentService implements IService {
}
mSignedAuditLogger.log(ILogger.EV_SIGNED_AUDIT,
- null,
- ILogger.S_SIGNED_AUDIT,
- ILogger.LL_SECURITY,
- msg);
+ null,
+ ILogger.S_SIGNED_AUDIT,
+ ILogger.LL_SECURITY,
+ msg);
}
}
-
/**
* Parsed and Flattened structure of PKIArchiveOptions.
*/
@@ -887,6 +878,7 @@ class ArchiveOptions {
private byte mSymmAlgParams[] = null;
private byte mEncSymmKey[] = null;
private byte mEncValue[] = null;
+
public ArchiveOptions(PKIArchiveOptions opts) throws EBaseException {
try {
EncryptedKey key = opts.getEncryptedKey();
@@ -901,7 +893,7 @@ class ArchiveOptions {
enveloped_val = key.getEnvelopedData();
byte[] env_b = enveloped_val.getEncoded();
EnvelopedData.Template env_template = new EnvelopedData.Template();
- EnvelopedData env_data =
+ EnvelopedData env_data =
(EnvelopedData) env_template.decode(new ByteArrayInputStream(env_b));
EncryptedContentInfo eCI = env_data.getEncryptedContentInfo();
symmAlg = eCI.getContentEncryptionAlgorithm();
@@ -910,12 +902,12 @@ class ArchiveOptions {
SET recipients = env_data.getRecipientInfos();
if (recipients.size() <= 0) {
- CMS.debug("EnrollService: ArchiveOptions() - missing recipient information ");
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTRIBUTE", "[PKIArchiveOptions] missing recipient information "));
+ CMS.debug("EnrollService: ArchiveOptions() - missing recipient information ");
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTRIBUTE", "[PKIArchiveOptions] missing recipient information "));
}
- //check recpient - later
- //we only handle one recipient here anyways. so, either the key
- //can be decrypted or it can't. No risk here.
+ // check recpient - later
+ // we only handle one recipient here anyways. so, either the key
+ // can be decrypted or it can't. No risk here.
RecipientInfo ri = (RecipientInfo) recipients.elementAt(0);
OCTET_STRING key_o = ri.getEncryptedKey();
mEncSymmKey = key_o.toByteArray();
@@ -948,11 +940,11 @@ class ArchiveOptions {
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTRIBUTE", "[PKIArchiveOptions]" + e.toString()));
} catch (IOException e) {
CMS.debug("EnrollService: ArchiveOptions(): " + e.toString());
- throw new EBaseException("ArchiveOptions() exception caught: "+
+ throw new EBaseException("ArchiveOptions() exception caught: " +
e.toString());
} catch (Exception e) {
CMS.debug("EnrollService: ArchiveOptions(): " + e.toString());
- throw new EBaseException("ArchiveOptions() exception caught: "+
+ throw new EBaseException("ArchiveOptions() exception caught: " +
e.toString());
}
diff --git a/pki/base/kra/src/com/netscape/kra/KRANotify.java b/pki/base/kra/src/com/netscape/kra/KRANotify.java
index 33c16456..abf7887e 100644
--- a/pki/base/kra/src/com/netscape/kra/KRANotify.java
+++ b/pki/base/kra/src/com/netscape/kra/KRANotify.java
@@ -17,16 +17,13 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.kra;
-
import com.netscape.certsrv.kra.IKeyRecoveryAuthority;
import com.netscape.certsrv.request.ARequestNotifier;
-
/**
- * A class represents a KRA request queue notify. This
- * object will be invoked by the request subsystem
- * when a request is requested for processing.
- *
+ * A class represents a KRA request queue notify. This object will be invoked by
+ * the request subsystem when a request is requested for processing.
+ *
* @author thomask
* @version $Revision$, $Date$
*/
diff --git a/pki/base/kra/src/com/netscape/kra/KRAPolicy.java b/pki/base/kra/src/com/netscape/kra/KRAPolicy.java
index dee18da4..f7d2ba13 100644
--- a/pki/base/kra/src/com/netscape/kra/KRAPolicy.java
+++ b/pki/base/kra/src/com/netscape/kra/KRAPolicy.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.kra;
-
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.base.ISubsystem;
@@ -30,7 +29,6 @@ import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cmscore.policy.GenericPolicyProcessor;
import com.netscape.cmscore.util.Debug;
-
/**
* KRA Policy.
*
@@ -46,7 +44,7 @@ public class KRAPolicy implements IPolicy {
}
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ throws EBaseException {
mKRA = (IKeyRecoveryAuthority) owner;
mConfig = config;
mPolicies.init(mKRA, mConfig);
@@ -77,4 +75,3 @@ public class KRAPolicy implements IPolicy {
}
}
-
diff --git a/pki/base/kra/src/com/netscape/kra/KRAService.java b/pki/base/kra/src/com/netscape/kra/KRAService.java
index a312a655..35983098 100644
--- a/pki/base/kra/src/com/netscape/kra/KRAService.java
+++ b/pki/base/kra/src/com/netscape/kra/KRAService.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.kra;
-
import java.util.Hashtable;
import com.netscape.certsrv.apps.CMS;
@@ -28,23 +27,20 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.IService;
import com.netscape.cmscore.util.Debug;
-
/**
- * A class represents a KRA request queue service. This
- * is the service object that is registered with
- * the request queue. And it acts as a broker to
- * distribute request into different KRA specific
- * services. This service registration allows us to support
- * new request easier.
+ * A class represents a KRA request queue service. This is the service object
+ * that is registered with the request queue. And it acts as a broker to
+ * distribute request into different KRA specific services. This service
+ * registration allows us to support new request easier.
* <P>
- *
+ *
* @author thomask
* @version $Revision$, $Date$
*/
public class KRAService implements IService {
- public final static String ENROLLMENT =
- IRequest.ENROLLMENT_REQUEST;
+ public final static String ENROLLMENT =
+ IRequest.ENROLLMENT_REQUEST;
public final static String RECOVERY = IRequest.KEYRECOVERY_REQUEST;
public final static String NETKEY_KEYGEN = IRequest.NETKEY_KEYGEN_REQUEST;
public final static String NETKEY_KEYRECOVERY = IRequest.NETKEY_KEYRECOVERY_REQUEST;
@@ -60,23 +56,22 @@ public class KRAService implements IService {
mKRA = kra;
mServices.put(ENROLLMENT, new EnrollmentService(kra));
mServices.put(RECOVERY, new RecoveryService(kra));
- mServices.put(NETKEY_KEYGEN, new NetkeyKeygenService(kra));
- mServices.put(NETKEY_KEYRECOVERY, new TokenKeyRecoveryService(kra));
+ mServices.put(NETKEY_KEYGEN, new NetkeyKeygenService(kra));
+ mServices.put(NETKEY_KEYRECOVERY, new TokenKeyRecoveryService(kra));
}
/**
- * Processes a KRA request. This method is invoked by
- * request subsystem.
- *
+ * Processes a KRA request. This method is invoked by request subsystem.
+ *
* @param r request from request subsystem
* @exception EBaseException failed to serve
*/
public boolean serviceRequest(IRequest r) throws EBaseException {
if (Debug.ON)
- Debug.trace("KRA services request " +
- r.getRequestId().toString());
+ Debug.trace("KRA services request " +
+ r.getRequestId().toString());
mKRA.log(ILogger.LL_INFO, "KRA services request " +
- r.getRequestId().toString());
+ r.getRequestId().toString());
IService s = (IService) mServices.get(
r.getRequestType());
@@ -91,7 +86,7 @@ public class KRAService implements IService {
} catch (EBaseException e) {
r.setExtData(IRequest.RESULT, IRequest.RES_ERROR);
r.setExtData(IRequest.ERROR, e);
- // return true;
+ // return true;
// #546508
return false;
}
diff --git a/pki/base/kra/src/com/netscape/kra/KeyRecoveryAuthority.java b/pki/base/kra/src/com/netscape/kra/KeyRecoveryAuthority.java
index 22a10998..111552dd 100644
--- a/pki/base/kra/src/com/netscape/kra/KeyRecoveryAuthority.java
+++ b/pki/base/kra/src/com/netscape/kra/KeyRecoveryAuthority.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.kra;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
@@ -74,14 +73,12 @@ import com.netscape.cmscore.dbs.KeyRepository;
import com.netscape.cmscore.dbs.ReplicaIDRepository;
import com.netscape.cmscore.request.RequestSubsystem;
-
/**
- * A class represents an key recovery authority (KRA). A KRA
- * is responsible to maintain key pairs that have been
- * escrowed. It provides archive and recovery key pairs
- * functionalities.
+ * A class represents an key recovery authority (KRA). A KRA is responsible to
+ * maintain key pairs that have been escrowed. It provides archive and recovery
+ * key pairs functionalities.
* <P>
- *
+ *
* @author thomask
* @version $Revision$, $Date$
*/
@@ -103,7 +100,6 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
private final static String KEY_RESP_NAME = "keyRepository";
private static final String PROP_REPLICAID_DN = "dbs.replicadn";
-
protected boolean mInitialized = false;
protected IConfigStore mConfig = null;
protected ILogger mLogger = CMS.getLogger();
@@ -126,15 +122,13 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
protected org.mozilla.jss.crypto.X509Certificate mJssCert = null;
protected CryptoToken mKeygenToken = null;
- // holds the number of bits of entropy to collect for each keygen
- private int mEntropyBitsPerKeyPair=0;
-
- // the number of milliseconds which it is acceptable to block while
- // getting entropy - anything longer will cause a warning.
- // 0 means this warning is disabled
- private int mEntropyBlockWarnMilliseconds = 0;
-
+ // holds the number of bits of entropy to collect for each keygen
+ private int mEntropyBitsPerKeyPair = 0;
+ // the number of milliseconds which it is acceptable to block while
+ // getting entropy - anything longer will cause a warning.
+ // 0 means this warning is disabled
+ private int mEntropyBlockWarnMilliseconds = 0;
// for the notification listener
public IRequestListener mReqInQListener = null;
@@ -142,20 +136,18 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
private ILogger mSignedAuditLogger = CMS.getSignedAuditLogger();
private final static byte EOL[] = { Character.LINE_SEPARATOR };
private final static String SIGNED_AUDIT_AGENT_DELIMITER = ", ";
- private final static String
- LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST =
- "LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST_4";
- private final static String
- LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST_PROCESSED =
- "LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST_PROCESSED_3";
+ private final static String LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST =
+ "LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST_4";
+ private final static String LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST_PROCESSED =
+ "LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST_PROCESSED_3";
private final static String LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST =
- "LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_4";
+ "LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_4";
private final static String LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_ASYNC =
- "LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_ASYNC_4";
+ "LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_ASYNC_4";
private final static String LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED =
- "LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED_4";
+ "LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED_4";
private final static String LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED_ASYNC =
- "LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED_ASYNC_4";
+ "LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED_ASYNC_4";
/**
* Constructs an escrow authority.
@@ -176,7 +168,7 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
/**
* Sets subsystem identifier.
- *
+ *
* @param id subsystem id
* @exception EBaseException failed to set id
*/
@@ -189,87 +181,82 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
}
// initialize entropy collection parameters
- private void initEntropy(IConfigStore config)
- {
+ private void initEntropy(IConfigStore config) {
mEntropyBitsPerKeyPair = 0;
mEntropyBlockWarnMilliseconds = 50;
// initialize entropy collection
IConfigStore ecs = config.getSubStore("entropy");
if (ecs != null) {
try {
- mEntropyBitsPerKeyPair = ecs.getInteger("bitsperkeypair",0);
- mEntropyBlockWarnMilliseconds = ecs.getInteger("blockwarnms",50);
+ mEntropyBitsPerKeyPair = ecs.getInteger("bitsperkeypair", 0);
+ mEntropyBlockWarnMilliseconds = ecs.getInteger("blockwarnms", 50);
} catch (EBaseException eb) {
// ok - we deal with missing parameters above
}
}
- CMS.debug("KeyRecoveryAuthority Entropy bits = "+mEntropyBitsPerKeyPair);
+ CMS.debug("KeyRecoveryAuthority Entropy bits = " + mEntropyBitsPerKeyPair);
if (mEntropyBitsPerKeyPair == 0) {
- //log(ILogger.LL_INFO,
- //CMS.getLogMessage("CMSCORE_KRA_ENTROPY_COLLECTION_DISABLED"));
+ // log(ILogger.LL_INFO,
+ // CMS.getLogMessage("CMSCORE_KRA_ENTROPY_COLLECTION_DISABLED"));
} else {
- //log(ILogger.LL_INFO,
- //CMS.getLogMessage("CMSCORE_KRA_ENTROPY_COLLECTION_ENABLED"));
- CMS.debug("KeyRecoveryAuthority about to add Entropy");
+ // log(ILogger.LL_INFO,
+ // CMS.getLogMessage("CMSCORE_KRA_ENTROPY_COLLECTION_ENABLED"));
+ CMS.debug("KeyRecoveryAuthority about to add Entropy");
addEntropy(false);
- CMS.debug("KeyRecoveryAuthority back from add Entropy");
+ CMS.debug("KeyRecoveryAuthority back from add Entropy");
}
}
-
public void addEntropy(boolean logflag) {
- CMS.debug("KeyRecoveryAuthority addEntropy()");
+ CMS.debug("KeyRecoveryAuthority addEntropy()");
if (mEntropyBitsPerKeyPair == 0) {
- CMS.debug("KeyRecoveryAuthority returning - disabled()");
- return;
- }
+ CMS.debug("KeyRecoveryAuthority returning - disabled()");
+ return;
+ }
long start = System.currentTimeMillis();
try {
com.netscape.cmscore.security.JssSubsystem.getInstance().
- addEntropy(mEntropyBitsPerKeyPair);
+ addEntropy(mEntropyBitsPerKeyPair);
} catch (Exception e) {
- CMS.debug("KeyRecoveryAuthority returning - error - see log file");
- CMS.debug("exception: "+e.getMessage());
- CMS.debug(e);
- if (logflag) {
- log(ILogger.LL_INFO,
- CMS.getLogMessage("CMSCORE_KRA_ENTROPY_ERROR",
- e.getMessage()));
- }
+ CMS.debug("KeyRecoveryAuthority returning - error - see log file");
+ CMS.debug("exception: " + e.getMessage());
+ CMS.debug(e);
+ if (logflag) {
+ log(ILogger.LL_INFO,
+ CMS.getLogMessage("CMSCORE_KRA_ENTROPY_ERROR",
+ e.getMessage()));
+ }
}
- long end = System.currentTimeMillis();
- long duration = end-start;
-
- if (mEntropyBlockWarnMilliseconds > 0 &&
- duration > mEntropyBlockWarnMilliseconds) {
-
- CMS.debug("KeyRecoveryAuthority returning - warning - entropy took too long (ms="+
- duration+")");
- if (logflag) {
- log(ILogger.LL_INFO,
- CMS.getLogMessage("CMSCORE_KRA_ENTROPY_BLOCKED_WARNING",
- ""+(int)duration));
- }
+ long end = System.currentTimeMillis();
+ long duration = end - start;
+
+ if (mEntropyBlockWarnMilliseconds > 0 &&
+ duration > mEntropyBlockWarnMilliseconds) {
+
+ CMS.debug("KeyRecoveryAuthority returning - warning - entropy took too long (ms=" +
+ duration + ")");
+ if (logflag) {
+ log(ILogger.LL_INFO,
+ CMS.getLogMessage("CMSCORE_KRA_ENTROPY_BLOCKED_WARNING",
+ "" + (int) duration));
+ }
}
- CMS.debug("KeyRecoveryAuthority returning ");
+ CMS.debug("KeyRecoveryAuthority returning ");
}
-
-
- /**
- * Starts this subsystem. It loads and initializes all
- * necessary components. This subsystem is started by
- * KRASubsystem.
+ /**
+ * Starts this subsystem. It loads and initializes all necessary components.
+ * This subsystem is started by KRASubsystem.
* <P>
*
* @param owner owner of this subsystem
* @param config configuration store for this subsystem
* @exception EBaseException failed to start subsystem
*/
- public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
- CMS.debug("KeyRecoveryAuthority init() begins");
+ public void init(ISubsystem owner, IConfigStore config)
+ throws EBaseException {
+ CMS.debug("KeyRecoveryAuthority init() begins");
if (mInitialized)
return;
@@ -285,26 +272,26 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
mKeyDB = new KeyRepository(getDBSubsystem(),
keydb_inc,
- "ou=" + KEY_RESP_NAME + ",ou=" +
- getId() + "," +
- getDBSubsystem().getBaseDN());
+ "ou=" + KEY_RESP_NAME + ",ou=" +
+ getId() + "," +
+ getDBSubsystem().getBaseDN());
// read transport key from internal database
mTransportKeyUnit = new TransportKeyUnit();
try {
- mTransportKeyUnit.init(this, mConfig.getSubStore(
- PROP_TRANSPORT_KEY));
+ mTransportKeyUnit.init(this, mConfig.getSubStore(
+ PROP_TRANSPORT_KEY));
} catch (EBaseException e) {
CMS.debug("KeyRecoveryAuthority: transport unit exception " + e.toString());
-//XXX throw e;
- return;
+ // XXX throw e;
+ return;
}
// retrieve the authority name from transport cert
try {
mJssCert = mTransportKeyUnit.getCertificate();
- X509CertImpl certImpl = new
- X509CertImpl(mJssCert.getEncoded());
+ X509CertImpl certImpl = new
+ X509CertImpl(mJssCert.getEncoded());
mName = (X500Name) certImpl.getSubjectDN();
} catch (CertificateEncodingException e) {
@@ -320,55 +307,55 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
// read transport key from storage key
mStorageKeyUnit = new StorageKeyUnit();
try {
- mStorageKeyUnit.init(this,
- mConfig.getSubStore(PROP_STORAGE_KEY));
+ mStorageKeyUnit.init(this,
+ mConfig.getSubStore(PROP_STORAGE_KEY));
} catch (EBaseException e) {
CMS.debug("KeyRecoveryAuthority: storage unit exception " + e.toString());
throw e;
}
- // setup token for server-side key generation for user enrollments
- String serverKeygenTokenName = mConfig.getString("serverKeygenTokenName", null);
- if (serverKeygenTokenName == null) {
- CMS.debug("serverKeygenTokenName set to nothing");
- if (mStorageKeyUnit.getToken() != null) {
- try {
- String storageToken = mStorageKeyUnit.getToken().getName();
- if (!storageToken.equals("internal")) {
- CMS.debug("Auto set serverKeygenTokenName to " + storageToken);
- serverKeygenTokenName = storageToken;
- }
- } catch (Exception e) {
- }
- }
- }
- if (serverKeygenTokenName == null) {
- serverKeygenTokenName = "internal";
- }
+ // setup token for server-side key generation for user enrollments
+ String serverKeygenTokenName = mConfig.getString("serverKeygenTokenName", null);
+ if (serverKeygenTokenName == null) {
+ CMS.debug("serverKeygenTokenName set to nothing");
+ if (mStorageKeyUnit.getToken() != null) {
+ try {
+ String storageToken = mStorageKeyUnit.getToken().getName();
+ if (!storageToken.equals("internal")) {
+ CMS.debug("Auto set serverKeygenTokenName to " + storageToken);
+ serverKeygenTokenName = storageToken;
+ }
+ } catch (Exception e) {
+ }
+ }
+ }
+ if (serverKeygenTokenName == null) {
+ serverKeygenTokenName = "internal";
+ }
if (serverKeygenTokenName.equalsIgnoreCase(PR_INTERNAL_TOKEN_NAME))
serverKeygenTokenName = PR_INTERNAL_TOKEN_NAME;
try {
if (serverKeygenTokenName.equalsIgnoreCase(PR_INTERNAL_TOKEN_NAME)) {
- CMS.debug("KeyRecoveryAuthority: getting internal crypto token for serverkeygen");
+ CMS.debug("KeyRecoveryAuthority: getting internal crypto token for serverkeygen");
mKeygenToken = CryptoManager.getInstance().getInternalKeyStorageToken();
} else {
- CMS.debug("KeyRecoveryAuthority: getting HSM token for serverkeygen");
+ CMS.debug("KeyRecoveryAuthority: getting HSM token for serverkeygen");
mKeygenToken = CryptoManager.getInstance().getTokenByName(serverKeygenTokenName);
}
- CMS.debug("KeyRecoveryAuthority: set up keygenToken");
+ CMS.debug("KeyRecoveryAuthority: set up keygenToken");
} catch (NoSuchTokenException e) {
throw new EBaseException(CMS.getUserMessage("CMS_BASE_TOKEN_NOT_FOUND", serverKeygenTokenName));
} catch (Exception e) {
throw new EBaseException(CMS.getUserMessage("CMS_BASE_CRYPTOMANAGER_UNINITIALIZED"));
}
- CMS.debug("KeyRecoveryAuthority: about to init entropy");
- initEntropy(mConfig);
- CMS.debug("KeyRecoveryAuthority: completed init of entropy");
+ CMS.debug("KeyRecoveryAuthority: about to init entropy");
+ initEntropy(mConfig);
+ CMS.debug("KeyRecoveryAuthority: completed init of entropy");
- getLogger().log(ILogger.EV_SYSTEM, ILogger.S_KRA,
- ILogger.LL_INFO, mName.toString() + " is started");
+ getLogger().log(ILogger.EV_SYSTEM, ILogger.S_KRA,
+ ILogger.LL_INFO, mName.toString() + " is started");
// setup the KRA request queue
IService service = new KRAService(this);
@@ -381,19 +368,20 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
mRequestQueue = reqSub.getRequestQueue(getId(), reqdb_inc,
mPolicy, service, mNotify, mPNotify);
- // set KeyStatusUpdateInterval to be 10 minutes if serial management is enabled.
+ // set KeyStatusUpdateInterval to be 10 minutes if serial management is
+ // enabled.
mKeyDB.setKeyStatusUpdateInterval(
- mRequestQueue.getRequestRepository(),
- mConfig.getInteger("keyStatusUpdateInterval", 10 * 60));
+ mRequestQueue.getRequestRepository(),
+ mConfig.getInteger("keyStatusUpdateInterval", 10 * 60));
// init request scheduler if configured
String schedulerClass =
- mConfig.getString("requestSchedulerClass", null);
+ mConfig.getString("requestSchedulerClass", null);
if (schedulerClass != null) {
try {
IRequestScheduler scheduler = (IRequestScheduler)
- Class.forName(schedulerClass).newInstance();
+ Class.forName(schedulerClass).newInstance();
mRequestQueue.setRequestScheduler(scheduler);
} catch (Exception e) {
@@ -404,17 +392,17 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
String replicaReposDN = mConfig.getString(PROP_REPLICAID_DN, null);
if (replicaReposDN == null) {
- replicaReposDN = "ou=Replica," + getDBSubsystem().getBaseDN();
+ replicaReposDN = "ou=Replica," + getDBSubsystem().getBaseDN();
}
mReplicaRepot = new ReplicaIDRepository(
- DBSubsystem.getInstance(), 1, replicaReposDN);
+ DBSubsystem.getInstance(), 1, replicaReposDN);
CMS.debug("Replica Repot inited");
}
public CryptoToken getKeygenToken() {
- return mKeygenToken;
+ return mKeygenToken;
}
public IRequestListener getRequestInQListener() {
@@ -433,28 +421,27 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
}
/**
- * Starts this service. When this method is called, all
- * service
- *
+ * Starts this service. When this method is called, all service
+ *
* @exception EBaseException failed to startup this subsystem
*/
public void startup() throws EBaseException {
- CMS.debug("KeyRecoveryAuthority startup() begins");
+ CMS.debug("KeyRecoveryAuthority startup() begins");
- if (mRequestQueue != null) {
- // setup administration operations if everything else is fine
- mRequestQueue.recover();
- CMS.debug("KeyRecoveryAuthority startup() call request Q recover");
+ if (mRequestQueue != null) {
+ // setup administration operations if everything else is fine
+ mRequestQueue.recover();
+ CMS.debug("KeyRecoveryAuthority startup() call request Q recover");
- // Note that we use our instance id for registration.
- // This helps us to support multiple instances
- // of a subsystem within server.
+ // Note that we use our instance id for registration.
+ // This helps us to support multiple instances
+ // of a subsystem within server.
- // register remote admin interface
- mInitialized = true;
- } else {
- CMS.debug("KeyRecoveryAuthority: mRequestQueue is null, could be in preop mode");
- }
+ // register remote admin interface
+ mInitialized = true;
+ } else {
+ CMS.debug("KeyRecoveryAuthority: mRequestQueue is null, could be in preop mode");
+ }
}
/**
@@ -470,15 +457,15 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
mKeyDB.shutdown();
mKeyDB = null;
}
- getLogger().log(ILogger.EV_SYSTEM, ILogger.S_KRA,
- ILogger.LL_INFO, mName.toString() + " is stopped");
+ getLogger().log(ILogger.EV_SYSTEM, ILogger.S_KRA,
+ ILogger.LL_INFO, mName.toString() + " is stopped");
mInitialized = false;
}
/**
* Retrieves the configuration store of this subsystem.
* <P>
- *
+ *
* @return configuration store
*/
public IConfigStore getConfigStore() {
@@ -487,7 +474,7 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
/**
* Changes the auto recovery state.
- *
+ *
* @param cs list of recovery agent credentials
* @param on turn of auto recovery or not
* @return operation success or not
@@ -508,7 +495,7 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
/**
* Retrieves the current auto recovery state.
- *
+ *
* @return enable or not
*/
public boolean getAutoRecoveryState() {
@@ -517,11 +504,9 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
}
/**
- * Returns a list of users who are in auto
- * recovery mode.
- *
- * @return list of user IDs that are accepted in the
- * auto recovery mode
+ * Returns a list of users who are in auto recovery mode.
+ *
+ * @return list of user IDs that are accepted in the auto recovery mode
*/
public Enumeration<String> getAutoRecoveryIDs() {
return mAutoRecovery.keys();
@@ -529,7 +514,7 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
/**
* Adds auto recovery mode to the given user id.
- *
+ *
* @param id new identifier to the auto recovery mode
* @param creds list of credentials
*/
@@ -539,9 +524,8 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
/**
* Removes auto recovery mode from the given user id.
- *
- * @param id id of user to be removed from auto
- * recovery mode
+ *
+ * @param id id of user to be removed from auto recovery mode
*/
public void removeAutoRecovery(String id) {
mAutoRecovery.remove(id);
@@ -549,7 +533,7 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
/**
* Retrieves logger from escrow authority.
- *
+ *
* @return logger
*/
public ILogger getLogger() {
@@ -557,29 +541,27 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
}
/**
- * Retrieves number of required agents for
- * recovery operation.
- *
+ * Retrieves number of required agents for recovery operation.
+ *
* @return number of required agents
* @exception EBaseException failed to retrieve info
*/
public int getNoOfRequiredAgents() throws EBaseException {
if (mConfig.getBoolean("keySplitting", false)) {
- return mStorageKeyUnit.getNoOfRequiredAgents();
+ return mStorageKeyUnit.getNoOfRequiredAgents();
} else {
int ret = -1;
- ret = mConfig.getInteger("noOfRequiredRecoveryAgents", 1);
+ ret = mConfig.getInteger("noOfRequiredRecoveryAgents", 1);
if (ret <= 0) {
- throw new EBaseException("Invalid parameter noOfRequiredecoveryAgents");
+ throw new EBaseException("Invalid parameter noOfRequiredecoveryAgents");
}
return ret;
}
}
/**
- * Sets number of required agents for
- * recovery operation
- *
+ * Sets number of required agents for recovery operation
+ *
* @return none
* @exception EBaseException invalid setting
*/
@@ -587,7 +569,7 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
if (mConfig.getBoolean("keySplitting")) {
mStorageKeyUnit.setNoOfRequiredAgents(number);
} else {
- mConfig.putInteger("noOfRequiredRecoveryAgents", number);
+ mConfig.putInteger("noOfRequiredRecoveryAgents", number);
}
}
@@ -599,7 +581,7 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
}
public Hashtable<String, Object> createRecoveryParams(String recoveryID)
- throws EBaseException {
+ throws EBaseException {
Hashtable<String, Object> h = new Hashtable<String, Object>();
h.put(PARAM_CREDS, new Vector<Credential>());
@@ -608,37 +590,37 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
return h;
}
- public void destroyRecoveryParams(String recoveryID)
- throws EBaseException {
+ public void destroyRecoveryParams(String recoveryID)
+ throws EBaseException {
mRecoveryParams.remove(recoveryID);
}
public Hashtable<String, Object> getRecoveryParams(String recoveryID)
- throws EBaseException {
+ throws EBaseException {
return (Hashtable<String, Object>) mRecoveryParams.get(recoveryID);
}
public void createPk12(String recoveryID, byte[] pk12)
- throws EBaseException {
+ throws EBaseException {
Hashtable<String, Object> h = getRecoveryParams(recoveryID);
h.put(PARAM_PK12, pk12);
}
public byte[] getPk12(String recoveryID)
- throws EBaseException {
+ throws EBaseException {
return (byte[]) getRecoveryParams(recoveryID).get(PARAM_PK12);
}
public void createError(String recoveryID, String error)
- throws EBaseException {
+ throws EBaseException {
Hashtable<String, Object> h = getRecoveryParams(recoveryID);
h.put(PARAM_ERROR, error);
}
public String getError(String recoveryID)
- throws EBaseException {
+ throws EBaseException {
return (String) getRecoveryParams(recoveryID).get(PARAM_ERROR);
}
@@ -646,30 +628,29 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
* Retrieve the current approval agents
*/
public Vector<Credential> getAppAgents(
- String recoveryID) throws EBaseException {
+ String recoveryID) throws EBaseException {
Hashtable<String, Object> h = getRecoveryParams(recoveryID);
@SuppressWarnings("unchecked")
- Vector<Credential> dc = (Vector<Credential>) h.get(PARAM_CREDS);
+ Vector<Credential> dc = (Vector<Credential>) h.get(PARAM_CREDS);
return dc;
}
/**
- * Retrieves a list credentials. This puts KRA in a waiting
- * mode, it never returns until all the necessary passwords
- * are collected.
+ * Retrieves a list credentials. This puts KRA in a waiting mode, it never
+ * returns until all the necessary passwords are collected.
*/
public Credential[] getDistributedCredentials(
- String recoveryID)
- throws EBaseException {
+ String recoveryID)
+ throws EBaseException {
Hashtable<String, Object> h = getRecoveryParams(recoveryID);
@SuppressWarnings("unchecked")
- Vector<Credential> dc = (Vector<Credential>) h.get(PARAM_CREDS);
+ Vector<Credential> dc = (Vector<Credential>) h.get(PARAM_CREDS);
Object lock = (Object) h.get(PARAM_LOCK);
synchronized (lock) {
- while (dc.size() < getNoOfRequiredAgents()) {
- CMS.debug("KeyRecoveryAuthority: cfu in synchronized lock for getDistributedCredentials");
+ while (dc.size() < getNoOfRequiredAgents()) {
+ CMS.debug("KeyRecoveryAuthority: cfu in synchronized lock for getDistributedCredentials");
try {
lock.wait();
} catch (InterruptedException e) {
@@ -685,21 +666,21 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
/**
* Verifies credential.
*/
- private void verifyCredential(Vector<Credential> creds, String uid,
- String pwd) throws EBaseException {
- // see if we have the uid already
+ private void verifyCredential(Vector<Credential> creds, String uid,
+ String pwd) throws EBaseException {
+ // see if we have the uid already
if (!mConfig.getBoolean("keySplitting")) {
- // check if the uid is in the specified group
+ // check if the uid is in the specified group
IUGSubsystem ug = (IUGSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_UG);
if (!ug.isMemberOf(uid, mConfig.getString("recoveryAgentGroup"))) {
- // invalid group
- throw new EBaseException(CMS.getUserMessage("CMS_KRA_CREDENTIALS_NOT_EXIST"));
+ // invalid group
+ throw new EBaseException(CMS.getUserMessage("CMS_KRA_CREDENTIALS_NOT_EXIST"));
}
}
for (int i = 0; i < creds.size(); i++) {
- Credential c = creds.elementAt(i);
+ Credential c = creds.elementAt(i);
if (c.getIdentifier().equals(uid)) {
// duplicated uid
@@ -707,18 +688,18 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
}
}
if (mConfig.getBoolean("keySplitting")) {
- mStorageKeyUnit.checkPassword(uid, pwd);
+ mStorageKeyUnit.checkPassword(uid, pwd);
}
}
/**
* Adds password.
*/
- public void addDistributedCredential(String recoveryID,
- String uid, String pwd) throws EBaseException {
+ public void addDistributedCredential(String recoveryID,
+ String uid, String pwd) throws EBaseException {
Hashtable<String, Object> h = getRecoveryParams(recoveryID);
@SuppressWarnings("unchecked")
- Vector<Credential> dc = (Vector<Credential> ) h.get(PARAM_CREDS);
+ Vector<Credential> dc = (Vector<Credential>) h.get(PARAM_CREDS);
Object lock = (Object) h.get(PARAM_LOCK);
synchronized (lock) {
@@ -731,26 +712,27 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
}
/**
- * Archives key. This creates a key record in the key
- * repository.
+ * Archives key. This creates a key record in the key repository.
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST used
- * whenever a user private key archive request is made (this is when the
- * DRM receives the request)
- * <li>signed.audit LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST_PROCESSED used
- * whenever a user private key archive request is processed (this is when
- * the DRM processes the request)
+ * whenever a user private key archive request is made (this is when the DRM
+ * receives the request)
+ * <li>signed.audit
+ * LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST_PROCESSED used whenever
+ * a user private key archive request is processed (this is when the DRM
+ * processes the request)
* </ul>
+ *
* @param rec key record to be archived
* @return executed request
* @exception EBaseException failed to archive key
* @return the request
- * <P>
+ * <P>
*/
- public IRequest archiveKey(KeyRecord rec)
- throws EBaseException {
+ public IRequest archiveKey(KeyRecord rec)
+ throws EBaseException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
String auditRequesterID = auditRequesterID();
@@ -835,7 +817,7 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
* async key recovery initiation
*/
public String initAsyncKeyRecovery(BigInteger kid, X509CertImpl cert, String agent)
- throws EBaseException {
+ throws EBaseException {
String auditPublicKey = auditPublicKey(cert);
String auditRecoveryID = "undefined";
@@ -880,16 +862,16 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
throw eAudit1;
}
- //NO call to queue.processRequest(r) because it is only initiating
+ // NO call to queue.processRequest(r) because it is only initiating
return r.getRequestId().toString();
}
- /**
- * is async recovery request status APPROVED -
- * i.e. all required # of recovery agents approved
- */
+ /**
+ * is async recovery request status APPROVED - i.e. all required # of
+ * recovery agents approved
+ */
public boolean isApprovedAsyncKeyRecovery(String reqID)
- throws EBaseException {
+ throws EBaseException {
IRequestQueue queue = null;
IRequest r = null;
@@ -902,11 +884,11 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
}
}
- /**
- * get async recovery request initiating agent
- */
+ /**
+ * get async recovery request initiating agent
+ */
public String getInitAgentAsyncKeyRecovery(String reqID)
- throws EBaseException {
+ throws EBaseException {
IRequestQueue queue = null;
IRequest r = null;
@@ -927,14 +909,13 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
return null;
}
- /**
- * add async recovery agent to approving agent list of the recovery request
- * record
- * This method will check to see if the agent belongs to the recovery group
- * first before adding.
- */
+ /**
+ * add async recovery agent to approving agent list of the recovery request
+ * record This method will check to see if the agent belongs to the recovery
+ * group first before adding.
+ */
public void addAgentAsyncKeyRecovery(String reqID, String agentID)
- throws EBaseException {
+ throws EBaseException {
IRequestQueue queue = null;
IRequest r = null;
@@ -956,17 +937,17 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
String a = st.nextToken();
// first one is the initiating agent
if ((count != 0) && a.equals(agentID)) {
- // duplicated uid
- throw new EBaseException(CMS.getUserMessage("CMS_KRA_CREDENTIALS_EXIST"));
+ // duplicated uid
+ throw new EBaseException(CMS.getUserMessage("CMS_KRA_CREDENTIALS_EXIST"));
}
count++;
}
// note: if count==1 and required agents is 1, it's good to add
// and it'd look like "agent1,agent1" - that's the only dup allowed
- if (count <= getNoOfRequiredAgents()) { //all good, add it
+ if (count <= getNoOfRequiredAgents()) { // all good, add it
r.setExtData(RecoveryService.ATTR_APPROVE_AGENTS,
- agents+","+agentID);
+ agents + "," + agentID);
if (count == getNoOfRequiredAgents()) {
r.setRequestStatus(RequestStatus.APPROVED);
} else {
@@ -980,34 +961,35 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
}
/**
- * Recovers key for administrators. This method is
- * invoked by the agent operation of the key recovery servlet.
+ * Recovers key for administrators. This method is invoked by the agent
+ * operation of the key recovery servlet.
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST used whenever
* a user private key recovery request is made (this is when the DRM
* receives the request)
- * <li>signed.audit LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED used whenever
- * a user private key recovery request is processed (this is when the DRM
- * processes the request)
+ * <li>signed.audit LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED used
+ * whenever a user private key recovery request is processed (this is when
+ * the DRM processes the request)
* </ul>
+ *
* @param kid key identifier
* @param creds list of recovery agent credentials
* @param password password of the PKCS12 package
* @param cert certficate that will be put in PKCS12
* @param delivery file, mail or something else
* @param nickname string containing the nickname of the id cert for this
- * subsystem
+ * subsystem
* @exception EBaseException failed to recover key
* @return a byte array containing the key
*/
public byte[] doKeyRecovery(BigInteger kid,
- Credential creds[], String password,
- X509CertImpl cert,
- String delivery, String nickname,
- String agent)
- throws EBaseException {
+ Credential creds[], String password,
+ X509CertImpl cert,
+ String delivery, String nickname,
+ String agent)
+ throws EBaseException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
String auditRecoveryID = auditRecoveryID();
@@ -1028,8 +1010,8 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
// set transient parameters
params = createVolatileRequest(r.getRequestId());
- if (mConfig.getBoolean("keySplitting")) {
- params.put(RecoveryService.ATTR_AGENT_CREDENTIALS, creds);
+ if (mConfig.getBoolean("keySplitting")) {
+ params.put(RecoveryService.ATTR_AGENT_CREDENTIALS, creds);
}
params.put(RecoveryService.ATTR_TRANSPORT_PWD, password);
@@ -1119,29 +1101,29 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
}
}
- /**
- * Async Recovers key for administrators. This method is
- * invoked by the agent operation of the key recovery servlet.
+ /**
+ * Async Recovers key for administrators. This method is invoked by the
+ * agent operation of the key recovery servlet.
* <P>
- *
+ *
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST used whenever
* a user private key recovery request is made (this is when the DRM
* receives the request)
- * <li>signed.audit LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED used whenever
- * a user private key recovery request is processed (this is when the DRM
- * processes the request)
+ * <li>signed.audit LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED used
+ * whenever a user private key recovery request is processed (this is when
+ * the DRM processes the request)
* </ul>
- * @param requestID request id
- * @param password password of the PKCS12 package
- * subsystem
+ *
+ * @param requestID request id
+ * @param password password of the PKCS12 package subsystem
* @exception EBaseException failed to recover key
* @return a byte array containing the key
*/
public byte[] doKeyRecovery(
- String reqID,
- String password)
- throws EBaseException {
+ String reqID,
+ String password)
+ throws EBaseException {
String auditMessage = null;
String auditSubjectID = auditSubjectID();
String auditRecoveryID = reqID;
@@ -1156,8 +1138,8 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
queue = getRequestQueue();
r = queue.findRequest(new RequestId(reqID));
- auditAgents =
- r.getExtDataInString(RecoveryService.ATTR_APPROVE_AGENTS);
+ auditAgents =
+ r.getExtDataInString(RecoveryService.ATTR_APPROVE_AGENTS);
// set transient parameters
params = createVolatileRequest(r.getRequestId());
@@ -1166,7 +1148,7 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
// ensure that any low-level exceptions are reported
// to the signed audit log and stored as failures
try {
- CMS.debug("KeyRecoveryAuthority: in asynchronous doKeyRecovery(), request state ="+ r.getRequestStatus().toString());
+ CMS.debug("KeyRecoveryAuthority: in asynchronous doKeyRecovery(), request state =" + r.getRequestStatus().toString());
// can only process requests in begin state
r.setRequestStatus(RequestStatus.BEGIN);
queue.processRequest(r);
@@ -1216,9 +1198,9 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
}
/**
- * Constructs a recovery request and submits it
- * to the request subsystem for processing.
- *
+ * Constructs a recovery request and submits it to the request subsystem for
+ * processing.
+ *
* @param kid key identifier
* @param creds list of recovery agent credentials
* @param password password of the PKCS12 package
@@ -1228,9 +1210,9 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
* @exception EBaseException failed to recover key
*/
public IRequest recoverKey(BigInteger kid,
- Credential creds[], String password,
- X509CertImpl cert,
- String delivery) throws EBaseException {
+ Credential creds[], String password,
+ X509CertImpl cert,
+ String delivery) throws EBaseException {
IRequestQueue queue = getRequestQueue();
IRequest r = queue.newRequest("recovery");
@@ -1244,7 +1226,7 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
/**
* Recovers key for end-entities.
- *
+ *
* @param creds list of credentials
* @param encryptionChain certificate chain
* @param signingCert signing cert
@@ -1254,9 +1236,9 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
* @exception EBaseException failed to recover key
*/
public IRequest recoverKey(Credential creds[], CertificateChain
- encryptionChain, X509CertImpl signingCert,
- X509CertImpl transportCert,
- X500Name ownerName) throws EBaseException {
+ encryptionChain, X509CertImpl signingCert,
+ X509CertImpl transportCert,
+ X500Name ownerName) throws EBaseException {
IRequestQueue queue = getRequestQueue();
IRequest r = queue.newRequest("recovery");
@@ -1267,7 +1249,7 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
certChainOut.toByteArray());
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- "Error encoding certificate chain");
+ "Error encoding certificate chain");
}
r.setExtData(RecoveryService.ATTR_SIGNING_CERT, signingCert);
@@ -1280,7 +1262,7 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
ownerNameOut.toByteArray());
} catch (IOException e) {
log(ILogger.LL_FAILURE,
- "Error encoding X500Name for owner name");
+ "Error encoding X500Name for owner name");
}
queue.processRequest(r);
@@ -1288,10 +1270,9 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
}
/**
- * Retrieves the storage key unit. The storage key
- * is used to wrap the user key for long term
- * storage.
- *
+ * Retrieves the storage key unit. The storage key is used to wrap the user
+ * key for long term storage.
+ *
* @return storage key unit.
*/
public IStorageKeyUnit getStorageKeyUnit() {
@@ -1300,7 +1281,7 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
/**
* Retrieves the transport key unit.
- *
+ *
* @return transport key unit
*/
public ITransportKeyUnit getTransportKeyUnit() {
@@ -1308,9 +1289,9 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
}
/**
- * Returns the name of this subsystem. This name is
- * extracted from the transport certificate.
- *
+ * Returns the name of this subsystem. This name is extracted from the
+ * transport certificate.
+ *
* @return KRA name
*/
public X500Name getX500Name() {
@@ -1322,9 +1303,8 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
}
/**
- * Returns the nickname for the id cert of this
- * subsystem.
- *
+ * Returns the nickname for the id cert of this subsystem.
+ *
* @return nickname of the transport certificate
*/
public String getNickname() {
@@ -1341,11 +1321,11 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
} catch (EBaseException e) {
}
}
-
+
public String getNewNickName() throws EBaseException {
return mConfig.getString(PROP_NEW_NICKNAME, "");
}
-
+
public void setNewNickName(String name) {
mConfig.putString(PROP_NEW_NICKNAME, name);
}
@@ -1357,7 +1337,7 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
/**
* Retrieves KRA request repository.
* <P>
- *
+ *
* @return request repository
*/
public IRequestQueue getRequestQueue() {
@@ -1365,8 +1345,7 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
}
/**
- * Retrieves the key repository. The key repository
- * stores archived keys.
+ * Retrieves the key repository. The key repository stores archived keys.
* <P>
*/
public IKeyRepository getKeyRepository() {
@@ -1376,18 +1355,17 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
/**
* Retrieves replica repository.
* <P>
- *
+ *
* @return replica repository
*/
public IReplicaIDRepository getReplicaRepository() {
return mReplicaRepot;
}
-
/**
* Retrieves the DN of this escrow authority.
* <P>
- *
+ *
* @return distinguished name
*/
protected String getDN() {
@@ -1403,23 +1381,23 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
/**
* Logs an event.
- *
+ *
* @param level log level
* @param msg message to log
*/
public void log(int level, String msg) {
- mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_KRA,
- level, msg);
+ mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_KRA,
+ level, msg);
}
/**
* Registers a request listener.
- *
+ *
* @param l request listener
*/
public void registerRequestListener(IRequestListener l) {
// it's initialized.
- if (mNotify != null)
+ if (mNotify != null)
mNotify.registerListener(l);
}
@@ -1428,8 +1406,8 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
}
/**
- * init notification related listeners -
- * right now only RequestInQueue listener is available for KRA
+ * init notification related listeners - right now only RequestInQueue
+ * listener is available for KRA
*/
private void initNotificationListeners() {
IConfigStore nc = null;
@@ -1447,60 +1425,48 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
mReqInQListener = (IRequestListener) Class.forName(requestInQListenerClassName).newInstance();
mReqInQListener.init(this, nc);
} catch (Exception e1) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_KRA_REGISTER_LISTENER", requestInQListenerClassName));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_KRA_REGISTER_LISTENER", requestInQListenerClassName));
}
} else {
- log(ILogger.LL_INFO,
- "No KRA notification Module configuration found");
+ log(ILogger.LL_INFO,
+ "No KRA notification Module configuration found");
}
} catch (EPropertyNotFound e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_KRA_NOTIFY_ERROR", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_KRA_NOTIFY_ERROR", e.toString()));
} catch (EListenersException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_KRA_NOTIFY_ERROR", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_KRA_NOTIFY_ERROR", e.toString()));
} catch (EBaseException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_KRA_NOTIFY_ERROR", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_KRA_NOTIFY_ERROR", e.toString()));
}
}
/**
* temporary accepted ras.
*/
- /* code no longer used
- public X500Name[] getAcceptedRAs() {
- // temporary. use usr/grp for real thing.
- X500Name radn = null;
- String raname = null;
-
- try {
- raname = mConfig.getString("acceptedRA", null);
- if (raname != null) {
- radn = new X500Name(raname);
- }
- } catch (IOException e) {
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_KRA,
- ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_KRA_INVALID_RA_NAME", raname, e.toString()));
- } catch (EBaseException e) {
- // ignore - set to null.
- mLogger.log(ILogger.EV_SYSTEM, ILogger.S_KRA,
- ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_KRA_INVALID_RA_SETUP", e.toString()));
- }
- return new X500Name[] { radn };
- }
- */
+ /*
+ * code no longer used public X500Name[] getAcceptedRAs() { // temporary.
+ * use usr/grp for real thing. X500Name radn = null; String raname = null;
+ *
+ * try { raname = mConfig.getString("acceptedRA", null); if (raname != null)
+ * { radn = new X500Name(raname); } } catch (IOException e) {
+ * mLogger.log(ILogger.EV_SYSTEM, ILogger.S_KRA, ILogger.LL_FAILURE,
+ * CMS.getLogMessage("CMSCORE_KRA_INVALID_RA_NAME", raname, e.toString()));
+ * } catch (EBaseException e) { // ignore - set to null.
+ * mLogger.log(ILogger.EV_SYSTEM, ILogger.S_KRA, ILogger.LL_FAILURE,
+ * CMS.getLogMessage("CMSCORE_KRA_INVALID_RA_SETUP", e.toString())); }
+ * return new X500Name[] { radn }; }
+ */
public Hashtable<String, Hashtable<String, Object>> mVolatileRequests = new Hashtable<String, Hashtable<String, Object>>();
/**
- * Creates a request object to store attributes that
- * will not be serialized. Currently, request queue
- * framework will try to serialize all the attribute into
- * persistent storage. Things like passwords are not
+ * Creates a request object to store attributes that will not be serialized.
+ * Currently, request queue framework will try to serialize all the
+ * attribute into persistent storage. Things like passwords are not
* desirable to be stored.
*/
public Hashtable<String, Object> createVolatileRequest(RequestId id) {
@@ -1524,10 +1490,10 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
/**
* Signed Audit Log
- *
+ *
* This method is called to store messages to the signed audit log.
* <P>
- *
+ *
* @param msg signed audit log message
*/
private void audit(String msg) {
@@ -1539,19 +1505,19 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
}
mSignedAuditLogger.log(ILogger.EV_SIGNED_AUDIT,
- null,
- ILogger.S_SIGNED_AUDIT,
- ILogger.LL_SECURITY,
- msg);
+ null,
+ ILogger.S_SIGNED_AUDIT,
+ ILogger.LL_SECURITY,
+ msg);
}
/**
* Signed Audit Log Subject ID
- *
- * This method is called to obtain the "SubjectID" for
- * a signed audit log message.
+ *
+ * This method is called to obtain the "SubjectID" for a signed audit log
+ * message.
* <P>
- *
+ *
* @return id string containing the signed audit log message SubjectID
*/
private String auditSubjectID() {
@@ -1583,11 +1549,11 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
/**
* Signed Audit Log Requester ID
- *
- * This method is called to obtain the "RequesterID" for
- * a signed audit log message.
+ *
+ * This method is called to obtain the "RequesterID" for a signed audit log
+ * message.
* <P>
- *
+ *
* @return id string containing the signed audit log message RequesterID
*/
private String auditRequesterID() {
@@ -1619,11 +1585,11 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
/**
* Signed Audit Log Recovery ID
- *
- * This method is called to obtain the "RecoveryID" for
- * a signed audit log message.
+ *
+ * This method is called to obtain the "RecoveryID" for a signed audit log
+ * message.
* <P>
- *
+ *
* @return id string containing the signed audit log message RecoveryID
*/
private String auditRecoveryID() {
@@ -1655,11 +1621,11 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
/**
* Signed Audit Log Public Key
- *
+ *
* This method is called to obtain the public key from the passed in
* "X509Certificate" for a signed audit log message.
* <P>
- *
+ *
* @param cert an X509Certificate
* @return key string containing the certificate's public key
*/
@@ -1695,11 +1661,11 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
/**
* Signed Audit Log Public Key
- *
+ *
* This method is called to obtain the public key from the passed in
* "KeyRecord" for a signed audit log message.
* <P>
- *
+ *
* @param rec a Key Record
* @return key string containing the certificate's public key
*/
@@ -1752,11 +1718,11 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
/**
* Signed Audit Agents
- *
+ *
* This method is called to extract agent uids from the passed in
* "Credentials[]" and return a string of comma-separated agent uids.
* <P>
- *
+ *
* @param creds array of credentials
* @return a comma-separated string of agent uids
*/
@@ -1781,7 +1747,7 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
}
if (uid != null &&
- !uid.equals("")) {
+ !uid.equals("")) {
if (i == 0) {
agents = uid;
@@ -1794,4 +1760,3 @@ public class KeyRecoveryAuthority implements IAuthority, IKeyService, IKeyRecove
return agents;
}
}
-
diff --git a/pki/base/kra/src/com/netscape/kra/NetkeyKeygenService.java b/pki/base/kra/src/com/netscape/kra/NetkeyKeygenService.java
index c69ab8c1..8457f5df 100644
--- a/pki/base/kra/src/com/netscape/kra/NetkeyKeygenService.java
+++ b/pki/base/kra/src/com/netscape/kra/NetkeyKeygenService.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.kra;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FilterOutputStream;
@@ -65,19 +64,16 @@ import com.netscape.cmscore.dbs.KeyRecord;
import com.netscape.cmscore.util.Debug;
/**
- * A class representing keygen/archival request procesor for requests
- * from netkey RAs.
- * the user private key of the encryption cert is wrapped with a
- * session symmetric key. The session symmetric key is wrapped with the
- * storage key and stored in the internal database for long term
- * storage.
- * The user private key of the encryption cert is to be wrapped with the
- * DES key which came in in the request wrapped with the KRA
- * transport cert. The wrapped user private key is then sent back to
- * the caller (netkey RA) ...netkey RA should already has kek-wrapped
- * des key from the TKS. They are to be sent together back to
- * the token.
- *
+ * A class representing keygen/archival request procesor for requests from
+ * netkey RAs. the user private key of the encryption cert is wrapped with a
+ * session symmetric key. The session symmetric key is wrapped with the storage
+ * key and stored in the internal database for long term storage. The user
+ * private key of the encryption cert is to be wrapped with the DES key which
+ * came in in the request wrapped with the KRA transport cert. The wrapped user
+ * private key is then sent back to the caller (netkey RA) ...netkey RA should
+ * already has kek-wrapped des key from the TKS. They are to be sent together
+ * back to the token.
+ *
* @author Christina Fu (cfu)
* @version $Revision$, $Date$
*/
@@ -85,31 +81,25 @@ import com.netscape.cmscore.util.Debug;
public class NetkeyKeygenService implements IService {
public final static String ATTR_KEY_RECORD = "keyRecord";
public final static String ATTR_PROOF_OF_ARCHIVAL =
- "proofOfArchival";
-
- // private
- private final static String
- LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST =
- "LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST_4";
- private final static String
- LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST_PROCESSED =
- "LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST_PROCESSED_3";
- // these need to be defined in LogMessages_en.properties later when we do this
- private final static String
- LOGGING_SIGNED_AUDIT_SERVER_SIDE_KEYGEN_REQUEST =
- "LOGGING_SIGNED_AUDIT_SERVER_SIDE_KEYGEN_REQUEST_3";
- private final static String
- LOGGING_SIGNED_AUDIT_SERVER_SIDE_KEYGEN_REQUEST_PROCESSED_SUCCESS =
- "LOGGING_SIGNED_AUDIT_SERVER_SIDE_KEYGEN_REQUEST_PROCESSED_SUCCESS_4";
- private final static String
- LOGGING_SIGNED_AUDIT_SERVER_SIDE_KEYGEN_REQUEST_PROCESSED_FAILURE =
- "LOGGING_SIGNED_AUDIT_SERVER_SIDE_KEYGEN_REQUEST_PROCESSED_FAILURE_3";
- private final static String
- LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_SUCCESS =
- "LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_SUCCESS_4";
- private final static String
- LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_FAILURE =
- "LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_FAILURE_4";
+ "proofOfArchival";
+
+ // private
+ private final static String LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST =
+ "LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST_4";
+ private final static String LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST_PROCESSED =
+ "LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST_PROCESSED_3";
+ // these need to be defined in LogMessages_en.properties later when we do
+ // this
+ private final static String LOGGING_SIGNED_AUDIT_SERVER_SIDE_KEYGEN_REQUEST =
+ "LOGGING_SIGNED_AUDIT_SERVER_SIDE_KEYGEN_REQUEST_3";
+ private final static String LOGGING_SIGNED_AUDIT_SERVER_SIDE_KEYGEN_REQUEST_PROCESSED_SUCCESS =
+ "LOGGING_SIGNED_AUDIT_SERVER_SIDE_KEYGEN_REQUEST_PROCESSED_SUCCESS_4";
+ private final static String LOGGING_SIGNED_AUDIT_SERVER_SIDE_KEYGEN_REQUEST_PROCESSED_FAILURE =
+ "LOGGING_SIGNED_AUDIT_SERVER_SIDE_KEYGEN_REQUEST_PROCESSED_FAILURE_3";
+ private final static String LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_SUCCESS =
+ "LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_SUCCESS_4";
+ private final static String LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_FAILURE =
+ "LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_FAILURE_4";
private IKeyRecoveryAuthority mKRA = null;
private ITransportKeyUnit mTransportUnit = null;
private IStorageKeyUnit mStorageUnit = null;
@@ -140,26 +130,21 @@ public class NetkeyKeygenService implements IService {
return archOpts;
}
- public KeyPair generateKeyPair(
- KeyPairAlgorithm kpAlg, int keySize, PQGParams pqg)
- throws NoSuchAlgorithmException, TokenException, InvalidAlgorithmParameterException,
+ public KeyPair generateKeyPair(
+ KeyPairAlgorithm kpAlg, int keySize, PQGParams pqg)
+ throws NoSuchAlgorithmException, TokenException, InvalidAlgorithmParameterException,
InvalidParameterException, PQGParamGenException {
CryptoToken token = mKRA.getKeygenToken();
-
- CMS.debug("NetkeyKeygenService: key pair is to be generated on slot: "+token.getName());
+
+ CMS.debug("NetkeyKeygenService: key pair is to be generated on slot: " + token.getName());
/*
- make it temporary so can work with HSM
- netHSM works with
- temporary == true
- sensitive == <do not specify>
- extractable == <do not specify>
- LunaSA2 works with
- temporary == true
- sensitive == true
- extractable == true
- */
+ * make it temporary so can work with HSM netHSM works with temporary ==
+ * true sensitive == <do not specify> extractable == <do not specify>
+ * LunaSA2 works with temporary == true sensitive == true extractable ==
+ * true
+ */
KeyPairGenerator kpGen = token.getKeyPairGenerator(kpAlg);
IConfigStore config = CMS.getConfigStore();
IConfigStore kgConfig = config.getSubStore("kra.keygen");
@@ -167,19 +152,19 @@ public class NetkeyKeygenService implements IService {
boolean sp = false;
boolean ep = false;
if (kgConfig != null) {
- try {
- tp = kgConfig.getBoolean("temporaryPairs", false);
- sp = kgConfig.getBoolean("sensitivePairs", false);
- ep = kgConfig.getBoolean("extractablePairs", false);
- // by default, let nethsm work
- if ((tp == false) && (sp == false) && (ep == false)) {
+ try {
+ tp = kgConfig.getBoolean("temporaryPairs", false);
+ sp = kgConfig.getBoolean("sensitivePairs", false);
+ ep = kgConfig.getBoolean("extractablePairs", false);
+ // by default, let nethsm work
+ if ((tp == false) && (sp == false) && (ep == false)) {
+ tp = true;
+ }
+ } catch (Exception e) {
+ CMS.debug("NetkeyKeygenService: kgConfig.getBoolean failed");
+ // by default, let nethsm work
tp = true;
}
- } catch (Exception e) {
- CMS.debug("NetkeyKeygenService: kgConfig.getBoolean failed");
- // by default, let nethsm work
- tp = true;
- }
} else {
// by default, let nethsm work
CMS.debug("NetkeyKeygenService: cannot find config store: kra.keygen, assume temporaryPairs==true");
@@ -187,18 +172,18 @@ public class NetkeyKeygenService implements IService {
}
/* only specified to "true" will it be set */
if (tp == true) {
- CMS.debug("NetkeyKeygenService: setting temporaryPairs to true");
- kpGen.temporaryPairs(true);
+ CMS.debug("NetkeyKeygenService: setting temporaryPairs to true");
+ kpGen.temporaryPairs(true);
}
if (sp == true) {
- CMS.debug("NetkeyKeygenService: setting sensitivePairs to true");
+ CMS.debug("NetkeyKeygenService: setting sensitivePairs to true");
kpGen.sensitivePairs(true);
}
if (ep == true) {
- CMS.debug("NetkeyKeygenService: setting extractablePairs to true");
+ CMS.debug("NetkeyKeygenService: setting extractablePairs to true");
kpGen.extractablePairs(true);
}
-
+
if (kpAlg == KeyPairAlgorithm.DSA) {
if (pqg == null) {
kpGen.initialize(keySize);
@@ -210,33 +195,29 @@ public class NetkeyKeygenService implements IService {
}
if (pqg == null) {
- KeyPair kp = null;
- synchronized (new Object()) {
+ KeyPair kp = null;
+ synchronized (new Object()) {
CMS.debug("NetkeyKeygenService: key pair generation begins");
- kp = kpGen.genKeyPair();
+ kp = kpGen.genKeyPair();
CMS.debug("NetkeyKeygenService: key pair generation done");
- mKRA.addEntropy(true);
- }
- return kp;
+ mKRA.addEntropy(true);
+ }
+ return kp;
} else {
// DSA
KeyPair kp = null;
- /* no DSA for now... netkey prototype
- do {
- // 602548 NSS bug - to overcome it, we use isBadDSAKeyPair
- kp = kpGen.genKeyPair();
- }
- while (isBadDSAKeyPair(kp));
- */
+ /*
+ * no DSA for now... netkey prototype do { // 602548 NSS bug - to
+ * overcome it, we use isBadDSAKeyPair kp = kpGen.genKeyPair(); }
+ * while (isBadDSAKeyPair(kp));
+ */
return kp;
}
}
-
-
- public KeyPair generateKeyPair( String alg,
- int keySize, PQGParams pqg) throws EBaseException {
+ public KeyPair generateKeyPair(String alg,
+ int keySize, PQGParams pqg) throws EBaseException {
KeyPairAlgorithm kpAlg = null;
@@ -246,7 +227,7 @@ public class NetkeyKeygenService implements IService {
kpAlg = KeyPairAlgorithm.DSA;
try {
- KeyPair kp = generateKeyPair( kpAlg, keySize, pqg);
+ KeyPair kp = generateKeyPair(kpAlg, keySize, pqg);
return kp;
} catch (InvalidParameterException e) {
@@ -270,9 +251,9 @@ public class NetkeyKeygenService implements IService {
ByteArrayOutputStream output = new ByteArrayOutputStream();
Base64OutputStream b64 = new Base64OutputStream(new
PrintStream(new
- FilterOutputStream(output)
+ FilterOutputStream(output)
)
- );
+ );
b64.write(bytes);
b64.flush();
@@ -284,33 +265,31 @@ public class NetkeyKeygenService implements IService {
// this encrypts bytes with a symmetric key
public byte[] encryptIt(byte[] toBeEncrypted, SymmetricKey symKey, CryptoToken token,
- IVParameterSpec IV)
- {
- try {
- Cipher cipher = token.getCipherContext(
+ IVParameterSpec IV) {
+ try {
+ Cipher cipher = token.getCipherContext(
EncryptionAlgorithm.DES3_CBC_PAD);
-
- cipher.initEncrypt(symKey, IV);
- byte pri[] = cipher.doFinal(toBeEncrypted);
- return pri;
- } catch (Exception e) {
- CMS.debug("NetkeyKeygenService:initEncrypt() threw exception: "+e.toString());
+
+ cipher.initEncrypt(symKey, IV);
+ byte pri[] = cipher.doFinal(toBeEncrypted);
+ return pri;
+ } catch (Exception e) {
+ CMS.debug("NetkeyKeygenService:initEncrypt() threw exception: " + e.toString());
return null;
}
}
-
/**
* Services an archival request from netkey.
* <P>
- *
+ *
* @param request enrollment request
* @return serving successful or not
* @exception EBaseException failed to serve
*/
- public boolean serviceRequest(IRequest request)
- throws EBaseException {
+ public boolean serviceRequest(IRequest request)
+ throws EBaseException {
String auditMessage = null;
String auditSubjectID = null;
String auditRequesterID = "TPSagent";
@@ -318,119 +297,121 @@ public class NetkeyKeygenService implements IService {
String auditPublicKey = ILogger.UNIDENTIFIED;
byte[] wrapped_des_key;
- byte iv[] = {0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1};
- String iv_s ="";
+ byte iv[] = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 };
+ String iv_s = "";
try {
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.nextBytes(iv);
} catch (Exception e) {
- CMS.debug("NetkeyKeygenService.serviceRequest: "+ e.toString());
+ CMS.debug("NetkeyKeygenService.serviceRequest: " + e.toString());
}
- IVParameterSpec algParam = new IVParameterSpec(iv);
+ IVParameterSpec algParam = new IVParameterSpec(iv);
wrapped_des_key = null;
- boolean archive = true;
- PK11SymKey sk= null;
- byte[] publicKeyData = null;;
- String PubKey = "";
+ boolean archive = true;
+ PK11SymKey sk = null;
+ byte[] publicKeyData = null;
+ ;
+ String PubKey = "";
String id = request.getRequestId().toString();
if (id != null) {
auditArchiveID = id.trim();
}
- String rArchive = request.getExtDataInString(IRequest.NETKEY_ATTR_ARCHIVE_FLAG);
- if (rArchive.equals("true")) {
- archive = true;
- CMS.debug("NetkeyKeygenService: serviceRequest " +"archival requested for serverSideKeyGen");
- } else {
- archive = false;
- CMS.debug("NetkeyKeygenService: serviceRequest " +"archival not requested for serverSideKeyGen");
+ String rArchive = request.getExtDataInString(IRequest.NETKEY_ATTR_ARCHIVE_FLAG);
+ if (rArchive.equals("true")) {
+ archive = true;
+ CMS.debug("NetkeyKeygenService: serviceRequest " + "archival requested for serverSideKeyGen");
+ } else {
+ archive = false;
+ CMS.debug("NetkeyKeygenService: serviceRequest " + "archival not requested for serverSideKeyGen");
}
String rCUID = request.getExtDataInString(IRequest.NETKEY_ATTR_CUID);
String rUserid = request.getExtDataInString(IRequest.NETKEY_ATTR_USERID);
- String rKeysize = request.getExtDataInString(IRequest.NETKEY_ATTR_KEY_SIZE);
- int keysize = Integer.parseInt(rKeysize);
- auditSubjectID=rCUID+":"+rUserid;
+ String rKeysize = request.getExtDataInString(IRequest.NETKEY_ATTR_KEY_SIZE);
+ int keysize = Integer.parseInt(rKeysize);
+ auditSubjectID = rCUID + ":" + rUserid;
SessionContext sContext = SessionContext.getContext();
- String agentId="";
+ String agentId = "";
if (sContext != null) {
agentId =
- (String) sContext.get(SessionContext.USER_ID);
+ (String) sContext.get(SessionContext.USER_ID);
}
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_SERVER_SIDE_KEYGEN_REQUEST,
- agentId,
- ILogger.SUCCESS,
- auditSubjectID);
+ LOGGING_SIGNED_AUDIT_SERVER_SIDE_KEYGEN_REQUEST,
+ agentId,
+ ILogger.SUCCESS,
+ auditSubjectID);
audit(auditMessage);
-
String rWrappedDesKeyString = request.getExtDataInString(IRequest.NETKEY_ATTR_DRMTRANS_DES_KEY);
- // CMS.debug("NetkeyKeygenService: received DRM-trans-wrapped DES key ="+rWrappedDesKeyString);
+ // CMS.debug("NetkeyKeygenService: received DRM-trans-wrapped DES key ="+rWrappedDesKeyString);
wrapped_des_key = com.netscape.cmsutil.util.Utils.SpecialDecode(rWrappedDesKeyString);
CMS.debug("NetkeyKeygenService: wrapped_des_key specialDecoded");
- // get the token for generating user keys
- CryptoToken keygenToken = mKRA.getKeygenToken();
- if (keygenToken == null) {
- CMS.debug("NetkeyKeygenService: failed getting keygenToken");
- request.setExtData(IRequest.RESULT, Integer.valueOf(10));
- return false;
- } else
- CMS.debug("NetkeyKeygenService: got keygenToken");
+ // get the token for generating user keys
+ CryptoToken keygenToken = mKRA.getKeygenToken();
+ if (keygenToken == null) {
+ CMS.debug("NetkeyKeygenService: failed getting keygenToken");
+ request.setExtData(IRequest.RESULT, Integer.valueOf(10));
+ return false;
+ } else
+ CMS.debug("NetkeyKeygenService: got keygenToken");
if ((wrapped_des_key != null) &&
- (wrapped_des_key.length > 0)) {
+ (wrapped_des_key.length > 0)) {
// unwrap the DES key
- sk= (PK11SymKey) mTransportUnit.unwrap_sym(wrapped_des_key);
+ sk = (PK11SymKey) mTransportUnit.unwrap_sym(wrapped_des_key);
- /* XXX could be done in HSM*/
+ /* XXX could be done in HSM */
KeyPair keypair = null;
CMS.debug("NetkeyKeygenService: about to generate key pair");
- keypair = generateKeyPair("RSA"/*alg*/,
- keysize /*Integer.parseInt(len)*/, null /*pqgParams*/);
+ keypair = generateKeyPair("RSA"/* alg */,
+ keysize /* Integer.parseInt(len) */, null /* pqgParams */);
if (keypair == null) {
- CMS.debug("NetkeyKeygenService: failed generating key pair for "+rCUID+":"+rUserid);
+ CMS.debug("NetkeyKeygenService: failed generating key pair for " + rCUID + ":" + rUserid);
request.setExtData(IRequest.RESULT, Integer.valueOf(4));
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_SERVER_SIDE_KEYGEN_REQUEST_PROCESSED_FAILURE,
+ LOGGING_SIGNED_AUDIT_SERVER_SIDE_KEYGEN_REQUEST_PROCESSED_FAILURE,
agentId,
ILogger.FAILURE,
- auditSubjectID);
+ auditSubjectID);
audit(auditMessage);
return false;
}
- CMS.debug("NetkeyKeygenService: finished generate key pair for " +rCUID+":"+rUserid);
+ CMS.debug("NetkeyKeygenService: finished generate key pair for " + rCUID + ":" + rUserid);
try {
- publicKeyData = keypair.getPublic().getEncoded();
- if (publicKeyData == null) {
- request.setExtData(IRequest.RESULT, Integer.valueOf(4));
- CMS.debug("NetkeyKeygenService: failed getting publickey encoded");
- return false;
- } else {
- //CMS.debug("NetkeyKeygenService: public key binary length ="+ publicKeyData.length);
- PubKey = base64Encode(publicKeyData);
-
- //CMS.debug("NetkeyKeygenService: public key length =" + PubKey.length());
- request.setExtData("public_key", PubKey);
- }
+ publicKeyData = keypair.getPublic().getEncoded();
+ if (publicKeyData == null) {
+ request.setExtData(IRequest.RESULT, Integer.valueOf(4));
+ CMS.debug("NetkeyKeygenService: failed getting publickey encoded");
+ return false;
+ } else {
+ // CMS.debug("NetkeyKeygenService: public key binary length ="+
+ // publicKeyData.length);
+ PubKey = base64Encode(publicKeyData);
+
+ // CMS.debug("NetkeyKeygenService: public key length =" +
+ // PubKey.length());
+ request.setExtData("public_key", PubKey);
+ }
auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_SERVER_SIDE_KEYGEN_REQUEST_PROCESSED_SUCCESS,
+ LOGGING_SIGNED_AUDIT_SERVER_SIDE_KEYGEN_REQUEST_PROCESSED_SUCCESS,
agentId,
ILogger.SUCCESS,
auditSubjectID,
@@ -438,9 +419,9 @@ public class NetkeyKeygenService implements IService {
audit(auditMessage);
- //...extract the private key handle (not privatekeydata)
+ // ...extract the private key handle (not privatekeydata)
java.security.PrivateKey privKey =
- keypair.getPrivate();
+ keypair.getPrivate();
if (privKey == null) {
request.setExtData(IRequest.RESULT, Integer.valueOf(4));
@@ -450,159 +431,158 @@ public class NetkeyKeygenService implements IService {
CMS.debug("NetkeyKeygenService: got private key");
}
- if (sk == null) {
- CMS.debug("NetkeyKeygenService: no DES key");
- request.setExtData(IRequest.RESULT, Integer.valueOf(4));
- return false;
- } else {
- CMS.debug("NetkeyKeygenService: received DES key");
- }
-
- // 3 wrapping should be done in HSM
- // wrap private key with DES
- KeyWrapper symWrap =
- keygenToken.getKeyWrapper(KeyWrapAlgorithm.DES3_CBC_PAD);
- CMS.debug("NetkeyKeygenService: wrapper token=" + keygenToken.getName());
- CMS.debug("NetkeyKeygenService: got key wrapper");
-
- CMS.debug("NetkeyKeygenService: key transport key is on slot: "+sk.getOwningToken().getName());
- symWrap.initWrap((SymmetricKey)sk, algParam);
- byte wrapped[] = symWrap.wrap((PrivateKey)privKey);
- /*
- CMS.debug("NetkeyKeygenService: wrap called");
- CMS.debug(wrapped);
- */
- /* This is for using with my decryption tool and ASN1
- decoder to see if the private key is indeed PKCS#8 format
- { // cfu debug
- String oFilePath = "/tmp/wrappedPrivKey.bin";
- File file = new File(oFilePath);
- FileOutputStream ostream = new FileOutputStream(oFilePath);
- ostream.write(wrapped);
- ostream.close();
- }
- */
- String wrappedPrivKeyString = /*base64Encode(wrapped);*/
- com.netscape.cmsutil.util.Utils.SpecialEncode(wrapped);
- if (wrappedPrivKeyString == null) {
- request.setExtData(IRequest.RESULT, Integer.valueOf(4));
- CMS.debug("NetkeyKeygenService: failed generating wrapped private key");
- auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_FAILURE,
- agentId,
- ILogger.FAILURE,
- auditSubjectID,
- PubKey);
-
- audit(auditMessage);
- return false;
- } else {
- request.setExtData("wrappedUserPrivate", wrappedPrivKeyString);
- auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_SUCCESS,
- agentId,
- ILogger.SUCCESS,
- auditSubjectID,
- PubKey);
-
- audit(auditMessage);
- }
-
- iv_s = /*base64Encode(iv);*/com.netscape.cmsutil.util.Utils.SpecialEncode(iv);
- request.setExtData("iv_s", iv_s);
-
- /*
- * archival - option flag "archive" controllable by the caller - TPS
- */
- if (archive) {
- //
- // privateKeyData ::= SEQUENCE {
- // sessionKey OCTET_STRING,
- // encKey OCTET_STRING,
- // }
- //
- // mKRA.log(ILogger.LL_INFO, "KRA encrypts internal private");
-
- auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST,
- agentId,
- ILogger.SUCCESS,
- auditSubjectID,
- auditArchiveID);
-
- audit(auditMessage);
- CMS.debug("KRA encrypts private key to put on internal ldap db");
- byte privateKeyData[] =
- mStorageUnit.wrap((org.mozilla.jss.crypto.PrivateKey) privKey);
-
- if (privateKeyData == null) {
- request.setExtData(IRequest.RESULT, Integer.valueOf(4));
- CMS.debug("NetkeyKeygenService: privatekey encryption by storage unit failed");
- return false;
- } else
- CMS.debug("NetkeyKeygenService: privatekey encryption by storage unit successful");
-
- // create key record
- KeyRecord rec = new KeyRecord(null, publicKeyData,
- privateKeyData, rCUID+":"+rUserid,
- keypair.getPublic().getAlgorithm(),
- agentId);
-
- CMS.debug("NetkeyKeygenService: got key record");
-
- // we deal with RSA key only
- try {
- RSAPublicKey rsaPublicKey = new RSAPublicKey(publicKeyData);
-
- rec.setKeySize(Integer.valueOf(rsaPublicKey.getKeySize()));
- } catch (InvalidKeyException e) {
- request.setExtData(IRequest.RESULT, Integer.valueOf(11));
- CMS.debug("NetkeyKeygenService: failed:InvalidKeyException");
- return false;
- }
- //??
- IKeyRepository storage = mKRA.getKeyRepository();
- BigInteger serialNo = storage.getNextSerialNumber();
-
- if (serialNo == null) {
- request.setExtData(IRequest.RESULT, Integer.valueOf(11));
- CMS.debug("NetkeyKeygenService: serialNo null");
- return false;
- }
- CMS.debug("NetkeyKeygenService: before addKeyRecord");
- rec.set(KeyRecord.ATTR_ID, serialNo);
- request.setExtData(ATTR_KEY_RECORD, serialNo);
- storage.addKeyRecord(rec);
- CMS.debug("NetkeyKeygenService: key archived for "+rCUID+":"+rUserid);
-
- auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST_PROCESSED,
- agentId,
- ILogger.SUCCESS,
- PubKey);
-
- audit(auditMessage);
-
- } //if archive
+ if (sk == null) {
+ CMS.debug("NetkeyKeygenService: no DES key");
+ request.setExtData(IRequest.RESULT, Integer.valueOf(4));
+ return false;
+ } else {
+ CMS.debug("NetkeyKeygenService: received DES key");
+ }
- request.setExtData(IRequest.RESULT, Integer.valueOf(1));
- } catch (Exception e) {
- CMS.debug("NetKeyKeygenService: " + e.toString());
- Debug.printStackTrace(e);
+ // 3 wrapping should be done in HSM
+ // wrap private key with DES
+ KeyWrapper symWrap =
+ keygenToken.getKeyWrapper(KeyWrapAlgorithm.DES3_CBC_PAD);
+ CMS.debug("NetkeyKeygenService: wrapper token=" + keygenToken.getName());
+ CMS.debug("NetkeyKeygenService: got key wrapper");
+
+ CMS.debug("NetkeyKeygenService: key transport key is on slot: " + sk.getOwningToken().getName());
+ symWrap.initWrap((SymmetricKey) sk, algParam);
+ byte wrapped[] = symWrap.wrap((PrivateKey) privKey);
+ /*
+ * CMS.debug("NetkeyKeygenService: wrap called");
+ * CMS.debug(wrapped);
+ */
+ /*
+ * This is for using with my decryption tool and ASN1 decoder to
+ * see if the private key is indeed PKCS#8 format { // cfu debug
+ * String oFilePath = "/tmp/wrappedPrivKey.bin"; File file = new
+ * File(oFilePath); FileOutputStream ostream = new
+ * FileOutputStream(oFilePath); ostream.write(wrapped);
+ * ostream.close(); }
+ */
+ String wrappedPrivKeyString = /* base64Encode(wrapped); */
+ com.netscape.cmsutil.util.Utils.SpecialEncode(wrapped);
+ if (wrappedPrivKeyString == null) {
request.setExtData(IRequest.RESULT, Integer.valueOf(4));
+ CMS.debug("NetkeyKeygenService: failed generating wrapped private key");
+ auditMessage = CMS.getLogMessage(
+ LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_FAILURE,
+ agentId,
+ ILogger.FAILURE,
+ auditSubjectID,
+ PubKey);
+
+ audit(auditMessage);
+ return false;
+ } else {
+ request.setExtData("wrappedUserPrivate", wrappedPrivKeyString);
+ auditMessage = CMS.getLogMessage(
+ LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_SUCCESS,
+ agentId,
+ ILogger.SUCCESS,
+ auditSubjectID,
+ PubKey);
+
+ audit(auditMessage);
}
- } else
+
+ iv_s = /* base64Encode(iv); */com.netscape.cmsutil.util.Utils.SpecialEncode(iv);
+ request.setExtData("iv_s", iv_s);
+
+ /*
+ * archival - option flag "archive" controllable by the caller -
+ * TPS
+ */
+ if (archive) {
+ //
+ // privateKeyData ::= SEQUENCE {
+ // sessionKey OCTET_STRING,
+ // encKey OCTET_STRING,
+ // }
+ //
+ // mKRA.log(ILogger.LL_INFO,
+ // "KRA encrypts internal private");
+
+ auditMessage = CMS.getLogMessage(
+ LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST,
+ agentId,
+ ILogger.SUCCESS,
+ auditSubjectID,
+ auditArchiveID);
+
+ audit(auditMessage);
+ CMS.debug("KRA encrypts private key to put on internal ldap db");
+ byte privateKeyData[] =
+ mStorageUnit.wrap((org.mozilla.jss.crypto.PrivateKey) privKey);
+
+ if (privateKeyData == null) {
+ request.setExtData(IRequest.RESULT, Integer.valueOf(4));
+ CMS.debug("NetkeyKeygenService: privatekey encryption by storage unit failed");
+ return false;
+ } else
+ CMS.debug("NetkeyKeygenService: privatekey encryption by storage unit successful");
+
+ // create key record
+ KeyRecord rec = new KeyRecord(null, publicKeyData,
+ privateKeyData, rCUID + ":" + rUserid,
+ keypair.getPublic().getAlgorithm(),
+ agentId);
+
+ CMS.debug("NetkeyKeygenService: got key record");
+
+ // we deal with RSA key only
+ try {
+ RSAPublicKey rsaPublicKey = new RSAPublicKey(publicKeyData);
+
+ rec.setKeySize(Integer.valueOf(rsaPublicKey.getKeySize()));
+ } catch (InvalidKeyException e) {
+ request.setExtData(IRequest.RESULT, Integer.valueOf(11));
+ CMS.debug("NetkeyKeygenService: failed:InvalidKeyException");
+ return false;
+ }
+ // ??
+ IKeyRepository storage = mKRA.getKeyRepository();
+ BigInteger serialNo = storage.getNextSerialNumber();
+
+ if (serialNo == null) {
+ request.setExtData(IRequest.RESULT, Integer.valueOf(11));
+ CMS.debug("NetkeyKeygenService: serialNo null");
+ return false;
+ }
+ CMS.debug("NetkeyKeygenService: before addKeyRecord");
+ rec.set(KeyRecord.ATTR_ID, serialNo);
+ request.setExtData(ATTR_KEY_RECORD, serialNo);
+ storage.addKeyRecord(rec);
+ CMS.debug("NetkeyKeygenService: key archived for " + rCUID + ":" + rUserid);
+
+ auditMessage = CMS.getLogMessage(
+ LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST_PROCESSED,
+ agentId,
+ ILogger.SUCCESS,
+ PubKey);
+
+ audit(auditMessage);
+
+ } // if archive
+
+ request.setExtData(IRequest.RESULT, Integer.valueOf(1));
+ } catch (Exception e) {
+ CMS.debug("NetKeyKeygenService: " + e.toString());
+ Debug.printStackTrace(e);
+ request.setExtData(IRequest.RESULT, Integer.valueOf(4));
+ }
+ } else
request.setExtData(IRequest.RESULT, Integer.valueOf(2));
-
+
return true;
- } //serviceRequest
+ } // serviceRequest
/**
- * Signed Audit Log
- *y
- * This method is called to store messages to the signed audit log.
+ * Signed Audit Log y This method is called to store messages to the signed
+ * audit log.
* <P>
- *
+ *
* @param msg signed audit log message
*/
private void audit(String msg) {
@@ -614,9 +594,9 @@ public class NetkeyKeygenService implements IService {
}
mSignedAuditLogger.log(ILogger.EV_SIGNED_AUDIT,
- null,
- ILogger.S_SIGNED_AUDIT,
- ILogger.LL_SECURITY,
- msg);
+ null,
+ ILogger.S_SIGNED_AUDIT,
+ ILogger.LL_SECURITY,
+ msg);
}
}
diff --git a/pki/base/kra/src/com/netscape/kra/RecoveryService.java b/pki/base/kra/src/com/netscape/kra/RecoveryService.java
index f364bf4f..569690f5 100644
--- a/pki/base/kra/src/com/netscape/kra/RecoveryService.java
+++ b/pki/base/kra/src/com/netscape/kra/RecoveryService.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.kra;
-
import java.io.ByteArrayOutputStream;
import java.io.CharConversionException;
import java.math.BigInteger;
@@ -71,16 +70,15 @@ import com.netscape.cmscore.dbs.KeyRecord;
import com.netscape.cmscore.util.Debug;
/**
- * A class represents recovery request processor. There
- * are 2 types of recovery modes: (1) administrator or
- * (2) end-entity.
+ * A class represents recovery request processor. There are 2 types of recovery
+ * modes: (1) administrator or (2) end-entity.
* <P>
- * Administrator recovery will create a PKCS12 file where
- * stores the certificate and the recovered key.
+ * Administrator recovery will create a PKCS12 file where stores the certificate
+ * and the recovered key.
* <P>
- * End Entity recovery will send RA or CA a response where
- * stores the recovered key.
- *
+ * End Entity recovery will send RA or CA a response where stores the recovered
+ * key.
+ *
* @author thomask (original)
* @author cfu (non-RSA keys; private keys secure handling);
* @version $Revision$, $Date$
@@ -96,12 +94,12 @@ public class RecoveryService implements IService {
public static final String ATTR_TRANSPORT_PWD = "transportPwd";
public static final String ATTR_SIGNING_CERT = "signingCert";
public static final String ATTR_PKCS12 = "pkcs12";
- public static final String ATTR_ENCRYPTION_CERTS =
- "encryptionCerts";
- public static final String ATTR_AGENT_CREDENTIALS =
- "agentCredentials";
+ public static final String ATTR_ENCRYPTION_CERTS =
+ "encryptionCerts";
+ public static final String ATTR_AGENT_CREDENTIALS =
+ "agentCredentials";
// same as encryption certs
- public static final String ATTR_USER_CERT = "cert";
+ public static final String ATTR_USER_CERT = "cert";
public static final String ATTR_DELIVERY = "delivery";
// for Async Key Recovery
@@ -121,11 +119,10 @@ public class RecoveryService implements IService {
}
/**
- * Processes a recovery request. Based on the recovery mode
- * (either Administrator or End-Entity), the method reads
- * the key record from the database, and tried to recover the
- * key with the storage key unit.
- *
+ * Processes a recovery request. Based on the recovery mode (either
+ * Administrator or End-Entity), the method reads the key record from the
+ * database, and tried to recover the key with the storage key unit.
+ *
* @param request recovery request
* @return operation success or not
* @exception EBaseException failed to serve
@@ -146,22 +143,22 @@ public class RecoveryService implements IService {
CMS.debug("RecoveryService: serviceRequest: use internal token ");
ct = cm.getInternalCryptoToken();
} else {
- CMS.debug("RecoveryService: serviceRequest: tokenName="+tokName);
+ CMS.debug("RecoveryService: serviceRequest: tokenName=" + tokName);
ct = cm.getTokenByName(tokName);
}
allowEncDecrypt_recovery = config.getBoolean("kra.allowEncDecrypt.recovery", false);
} catch (Exception e) {
CMS.debug("RecoveryService exception: use internal token :"
- + e.toString());
+ + e.toString());
ct = cm.getInternalCryptoToken();
}
if (ct == null) {
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_ERROR"+ "cannot get crypto token"));
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_ERROR" + "cannot get crypto token"));
}
- IStatsSubsystem statsSub = (IStatsSubsystem)CMS.getSubsystem("stats");
+ IStatsSubsystem statsSub = (IStatsSubsystem) CMS.getSubsystem("stats");
if (statsSub != null) {
- statsSub.startTiming("recovery", true /* main action */);
+ statsSub.startTiming("recovery", true /* main action */);
}
if (Debug.ON)
@@ -184,17 +181,17 @@ public class RecoveryService implements IService {
mKRA.log(ILogger.LL_INFO, "KRA reading key record");
if (statsSub != null) {
- statsSub.startTiming("get_key");
+ statsSub.startTiming("get_key");
}
KeyRecord keyRecord = (KeyRecord) mStorage.readKeyRecord(serialno);
if (statsSub != null) {
- statsSub.endTiming("get_key");
+ statsSub.endTiming("get_key");
}
// see if the certificate matches the key
byte pubData[] = keyRecord.getPublicKeyData();
- X509Certificate x509cert =
- request.getExtDataInCert(ATTR_USER_CERT);
+ X509Certificate x509cert =
+ request.getExtDataInCert(ATTR_USER_CERT);
byte inputPubData[] = x509cert.getPublicKey().getEncoded();
if (inputPubData.length != pubData.length) {
@@ -212,49 +209,50 @@ public class RecoveryService implements IService {
boolean isRSA = true;
String keyAlg = x509cert.getPublicKey().getAlgorithm();
- if (keyAlg != null) {
- CMS.debug("RecoveryService: publicKey alg ="+keyAlg);
- if (!keyAlg.equals("RSA")) isRSA = false;
+ if (keyAlg != null) {
+ CMS.debug("RecoveryService: publicKey alg =" + keyAlg);
+ if (!keyAlg.equals("RSA"))
+ isRSA = false;
}
// Unwrap the archived private key
byte privateKeyData[] = null;
X509Certificate transportCert =
- request.getExtDataInCert(ATTR_TRANSPORT_CERT);
+ request.getExtDataInCert(ATTR_TRANSPORT_CERT);
if (transportCert == null) {
if (statsSub != null) {
- statsSub.startTiming("recover_key");
+ statsSub.startTiming("recover_key");
}
PrivateKey privKey = null;
if (allowEncDecrypt_recovery == true) {
privateKeyData = recoverKey(params, keyRecord);
} else {
- privKey= recoverKey(params, keyRecord, isRSA);
+ privKey = recoverKey(params, keyRecord, isRSA);
}
if (statsSub != null) {
- statsSub.endTiming("recover_key");
+ statsSub.endTiming("recover_key");
}
if ((isRSA == true) && (allowEncDecrypt_recovery == true)) {
if (statsSub != null) {
- statsSub.startTiming("verify_key");
+ statsSub.startTiming("verify_key");
}
// verifyKeyPair() is RSA-centric
if (verifyKeyPair(pubData, privateKeyData) == false) {
mKRA.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_KRA_PUBLIC_NOT_FOUND"));
+ CMS.getLogMessage("CMSCORE_KRA_PUBLIC_NOT_FOUND"));
throw new EKRAException(
CMS.getUserMessage("CMS_KRA_INVALID_PUBLIC_KEY"));
}
if (statsSub != null) {
- statsSub.endTiming("verify_key");
+ statsSub.endTiming("verify_key");
}
}
if (statsSub != null) {
- statsSub.startTiming("create_p12");
+ statsSub.startTiming("create_p12");
}
if (allowEncDecrypt_recovery == true) {
createPFX(request, params, privateKeyData);
@@ -262,31 +260,31 @@ public class RecoveryService implements IService {
createPFX(request, params, privKey, ct);
}
if (statsSub != null) {
- statsSub.endTiming("create_p12");
+ statsSub.endTiming("create_p12");
}
} else {
if (CMS.getConfigStore().getBoolean("kra.keySplitting")) {
- Credential creds[] = (Credential[])
- params.get(ATTR_AGENT_CREDENTIALS);
- mKRA.getStorageKeyUnit().login(creds);
+ Credential creds[] = (Credential[])
+ params.get(ATTR_AGENT_CREDENTIALS);
+ mKRA.getStorageKeyUnit().login(creds);
}
if (statsSub != null) {
- statsSub.startTiming("unwrap_key");
+ statsSub.startTiming("unwrap_key");
}
PrivateKey privateKey = mKRA.getStorageKeyUnit().unwrap(
keyRecord.getPrivateKeyData(), null);
if (statsSub != null) {
- statsSub.endTiming("unwrap_key");
+ statsSub.endTiming("unwrap_key");
}
if (CMS.getConfigStore().getBoolean("kra.keySplitting")) {
- mKRA.getStorageKeyUnit().logout();
+ mKRA.getStorageKeyUnit().logout();
}
}
- mKRA.log(ILogger.LL_INFO, "key " +
- serialno.toString() +
- " recovered");
+ mKRA.log(ILogger.LL_INFO, "key " +
+ serialno.toString() +
+ " recovered");
// for audit log
String authMgr = AuditFormat.NOAUTH;
@@ -295,32 +293,32 @@ public class RecoveryService implements IService {
if (sContext != null) {
String agentId =
- (String) sContext.get(SessionContext.USER_ID);
+ (String) sContext.get(SessionContext.USER_ID);
initiative = AuditFormat.FROMAGENT + " agentID: " + agentId;
AuthToken authToken = (AuthToken) sContext.get(SessionContext.AUTH_TOKEN);
-
+
if (authToken != null) {
authMgr =
authToken.getInString(AuthToken.TOKEN_AUTHMGR_INST_NAME);
}
}
CMS.getLogger().log(ILogger.EV_AUDIT,
- ILogger.S_KRA,
- AuditFormat.LEVEL,
- AuditFormat.FORMAT,
- new Object[] {
- IRequest.KEYRECOVERY_REQUEST,
- request.getRequestId(),
- initiative,
- authMgr,
- "completed",
- ((X509CertImpl) x509cert).getSubjectDN(),
- "serial number: 0x" + serialno.toString(16)}
- );
+ ILogger.S_KRA,
+ AuditFormat.LEVEL,
+ AuditFormat.FORMAT,
+ new Object[] {
+ IRequest.KEYRECOVERY_REQUEST,
+ request.getRequestId(),
+ initiative,
+ authMgr,
+ "completed",
+ ((X509CertImpl) x509cert).getSubjectDN(),
+ "serial number: 0x" + serialno.toString(16) }
+ );
if (statsSub != null) {
- statsSub.endTiming("recovery");
+ statsSub.endTiming("recovery");
}
return true;
@@ -329,63 +327,62 @@ public class RecoveryService implements IService {
/*
* verifyKeyPair()- RSA-centric key verification
*/
- public boolean verifyKeyPair(byte publicKeyData[], byte privateKeyData[])
- {
- try {
- DerValue publicKeyVal = new DerValue(publicKeyData);
- DerInputStream publicKeyIn = publicKeyVal.data;
- publicKeyIn.getSequence(0);
- DerValue publicKeyDer = new DerValue(publicKeyIn.getBitString());
- DerInputStream publicKeyDerIn = publicKeyDer.data;
- BigInt publicKeyModulus = publicKeyDerIn.getInteger();
- BigInt publicKeyExponent = publicKeyDerIn.getInteger();
-
- DerValue privateKeyVal = new DerValue(privateKeyData);
- if (privateKeyVal.tag != DerValue.tag_Sequence)
- return false;
- DerInputStream privateKeyIn = privateKeyVal.data;
- privateKeyIn.getInteger();
- privateKeyIn.getSequence(0);
- DerValue privateKeyDer = new DerValue(privateKeyIn.getOctetString());
- DerInputStream privateKeyDerIn = privateKeyDer.data;
- BigInt privateKeyVersion = privateKeyDerIn.getInteger();
- BigInt privateKeyModulus = privateKeyDerIn.getInteger();
- BigInt privateKeyExponent = privateKeyDerIn.getInteger();
-
- if (!publicKeyModulus.equals(privateKeyModulus)) {
- CMS.debug("verifyKeyPair modulus mismatch publicKeyModulus=" + publicKeyModulus + " privateKeyModulus=" + privateKeyModulus);
- return false;
- }
-
- if (!publicKeyExponent.equals(privateKeyExponent)) {
- CMS.debug("verifyKeyPair exponent mismatch publicKeyExponent=" + publicKeyExponent + " privateKeyExponent=" + privateKeyExponent);
- return false;
- }
-
- return true;
- } catch (Exception e) {
- CMS.debug("verifyKeyPair error " + e);
- return false;
- }
+ public boolean verifyKeyPair(byte publicKeyData[], byte privateKeyData[]) {
+ try {
+ DerValue publicKeyVal = new DerValue(publicKeyData);
+ DerInputStream publicKeyIn = publicKeyVal.data;
+ publicKeyIn.getSequence(0);
+ DerValue publicKeyDer = new DerValue(publicKeyIn.getBitString());
+ DerInputStream publicKeyDerIn = publicKeyDer.data;
+ BigInt publicKeyModulus = publicKeyDerIn.getInteger();
+ BigInt publicKeyExponent = publicKeyDerIn.getInteger();
+
+ DerValue privateKeyVal = new DerValue(privateKeyData);
+ if (privateKeyVal.tag != DerValue.tag_Sequence)
+ return false;
+ DerInputStream privateKeyIn = privateKeyVal.data;
+ privateKeyIn.getInteger();
+ privateKeyIn.getSequence(0);
+ DerValue privateKeyDer = new DerValue(privateKeyIn.getOctetString());
+ DerInputStream privateKeyDerIn = privateKeyDer.data;
+ BigInt privateKeyVersion = privateKeyDerIn.getInteger();
+ BigInt privateKeyModulus = privateKeyDerIn.getInteger();
+ BigInt privateKeyExponent = privateKeyDerIn.getInteger();
+
+ if (!publicKeyModulus.equals(privateKeyModulus)) {
+ CMS.debug("verifyKeyPair modulus mismatch publicKeyModulus=" + publicKeyModulus + " privateKeyModulus=" + privateKeyModulus);
+ return false;
+ }
+
+ if (!publicKeyExponent.equals(privateKeyExponent)) {
+ CMS.debug("verifyKeyPair exponent mismatch publicKeyExponent=" + publicKeyExponent + " privateKeyExponent=" + privateKeyExponent);
+ return false;
+ }
+
+ return true;
+ } catch (Exception e) {
+ CMS.debug("verifyKeyPair error " + e);
+ return false;
+ }
}
/**
- * Recovers key. (using unwrapping/wrapping on token)
- * - used when allowEncDecrypt_recovery is false
+ * Recovers key. (using unwrapping/wrapping on token) - used when
+ * allowEncDecrypt_recovery is false
*/
- public synchronized PrivateKey recoverKey(Hashtable request, KeyRecord keyRecord, boolean isRSA)
- throws EBaseException {
+ public synchronized PrivateKey recoverKey(Hashtable request, KeyRecord keyRecord, boolean isRSA)
+ throws EBaseException {
- if (!isRSA) {
+ if (!isRSA) {
CMS.debug("RecoverService: recoverKey: currently, non-RSA keys are not supported when allowEncDecrypt_ is false");
throw new EKRAException(CMS.getUserMessage("CMS_KRA_RECOVERY_FAILED_1", "key type not supported"));
- }
- try {
+ }
+ try {
if (CMS.getConfigStore().getBoolean("kra.keySplitting")) {
- Credential creds[] = (Credential[])
- request.get(ATTR_AGENT_CREDENTIALS);
+ Credential creds[] = (Credential[])
+ request.get(ATTR_AGENT_CREDENTIALS);
- mStorageUnit.login(creds);
+ mStorageUnit.login(creds);
}
/* wrapped retrieve session key and private key */
@@ -400,50 +397,49 @@ public class RecoveryService implements IService {
byte publicKeyData[] = keyRecord.getPublicKeyData();
PublicKey pubkey = null;
try {
- pubkey = X509Key.parsePublicKey (new DerValue(publicKeyData));
+ pubkey = X509Key.parsePublicKey(new DerValue(publicKeyData));
} catch (Exception e) {
- CMS.debug("RecoverService: after parsePublicKey:"+e.toString());
+ CMS.debug("RecoverService: after parsePublicKey:" + e.toString());
throw new EKRAException(CMS.getUserMessage("CMS_KRA_RECOVERY_FAILED_1", "pubic key parsing failure"));
}
- byte iv[] = {0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1};
+ byte iv[] = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 };
PrivateKey privKey =
- mStorageUnit.unwrap(
- session,
- keyRecord.getAlgorithm(),
- iv,
- pri,
- (PublicKey) pubkey);
+ mStorageUnit.unwrap(
+ session,
+ keyRecord.getAlgorithm(),
+ iv,
+ pri,
+ (PublicKey) pubkey);
if (privKey == null) {
mKRA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_KRA_PRIVATE_KEY_NOT_FOUND"));
throw new EKRAException(CMS.getUserMessage("CMS_KRA_RECOVERY_FAILED_1", "private key unwrapping failure"));
}
if (CMS.getConfigStore().getBoolean("kra.keySplitting")) {
- mStorageUnit.logout();
+ mStorageUnit.logout();
}
return privKey;
} catch (Exception e) {
- CMS.debug("RecoverService: recoverKey() failed with allowEncDecrypt_recovery=false:"+e.toString());
- throw new EKRAException(CMS.getUserMessage("CMS_KRA_RECOVERY_FAILED_1", "recoverKey() failed with allowEncDecrypt_recovery=false:"+e.toString()));
+ CMS.debug("RecoverService: recoverKey() failed with allowEncDecrypt_recovery=false:" + e.toString());
+ throw new EKRAException(CMS.getUserMessage("CMS_KRA_RECOVERY_FAILED_1", "recoverKey() failed with allowEncDecrypt_recovery=false:" + e.toString()));
}
}
-
/**
- * Creates a PFX (PKCS12) file. (the unwrapping/wrapping way)
- * - used when allowEncDecrypt_recovery is false
- *
+ * Creates a PFX (PKCS12) file. (the unwrapping/wrapping way) - used when
+ * allowEncDecrypt_recovery is false
+ *
* @param request CRMF recovery request
* @param priKey private key handle
* @exception EBaseException failed to create P12 file
*/
- public void createPFX(IRequest request, Hashtable params,
- PrivateKey priKey, CryptoToken ct) throws EBaseException {
+ public void createPFX(IRequest request, Hashtable params,
+ PrivateKey priKey, CryptoToken ct) throws EBaseException {
CMS.debug("RecoverService: createPFX() allowEncDecrypt_recovery=false");
try {
// create p12
X509Certificate x509cert =
- request.getExtDataInCert(ATTR_USER_CERT);
+ request.getExtDataInCert(ATTR_USER_CERT);
String pwd = (String) params.get(ATTR_TRANSPORT_PWD);
// add certificate
@@ -461,7 +457,7 @@ public class RecoveryService implements IService {
nickname, localKeyId);
// attributes: user friendly name, Local Key ID
SafeBag certBag = new SafeBag(SafeBag.CERT_BAG,
- new CertBag(CertBag.X509_CERT_TYPE, cert),
+ new CertBag(CertBag.X509_CERT_TYPE, cert),
certAttrs);
encSafeContents.addElement(certBag);
@@ -469,21 +465,21 @@ public class RecoveryService implements IService {
// add key
mKRA.log(ILogger.LL_INFO, "KRA adds key to P12");
CMS.debug("RecoverService: createPFX() adds key to P12");
- org.mozilla.jss.util.Password pass = new
- org.mozilla.jss.util.Password(
- pwd.toCharArray());
+ org.mozilla.jss.util.Password pass = new
+ org.mozilla.jss.util.Password(
+ pwd.toCharArray());
SEQUENCE safeContents = new SEQUENCE();
- PasswordConverter passConverter = new
- PasswordConverter();
- byte salt[] = {0x01, 0x01, 0x01, 0x01};
+ PasswordConverter passConverter = new
+ PasswordConverter();
+ byte salt[] = { 0x01, 0x01, 0x01, 0x01 };
ASN1Value key = EncryptedPrivateKeyInfo.createPBE(
- PBEAlgorithm.PBE_SHA1_DES3_CBC,
+ PBEAlgorithm.PBE_SHA1_DES3_CBC,
pass, salt, 1, passConverter, priKey, ct);
SET keyAttrs = createBagAttrs(
- x509cert.getSubjectDN().toString(),
+ x509cert.getSubjectDN().toString(),
localKeyId);
SafeBag keyBag = new SafeBag(
@@ -493,25 +489,25 @@ public class RecoveryService implements IService {
safeContents.addElement(keyBag);
// build contents
- AuthenticatedSafes authSafes = new
- AuthenticatedSafes();
+ AuthenticatedSafes authSafes = new
+ AuthenticatedSafes();
authSafes.addSafeContents(
- safeContents
- );
+ safeContents
+ );
authSafes.addSafeContents(
- encSafeContents
- );
+ encSafeContents
+ );
- // authSafes.addEncryptedSafeContents(
- // authSafes.DEFAULT_KEY_GEN_ALG,
- // pass, null, 1,
- // encSafeContents);
+ // authSafes.addEncryptedSafeContents(
+ // authSafes.DEFAULT_KEY_GEN_ALG,
+ // pass, null, 1,
+ // encSafeContents);
PFX pfx = new PFX(authSafes);
pfx.computeMacData(pass, null, 5); // ??
- ByteArrayOutputStream fos = new
- ByteArrayOutputStream();
+ ByteArrayOutputStream fos = new
+ ByteArrayOutputStream();
pfx.encode(fos);
pass.clear();
@@ -527,26 +523,24 @@ public class RecoveryService implements IService {
mKRA.getRequestQueue().updateRequest(request);
}
-
/**
- * Recovers key.
- * - used when allowEncDecrypt_recovery is true
+ * Recovers key. - used when allowEncDecrypt_recovery is true
*/
- public synchronized byte[] recoverKey(Hashtable request, KeyRecord keyRecord)
- throws EBaseException {
+ public synchronized byte[] recoverKey(Hashtable request, KeyRecord keyRecord)
+ throws EBaseException {
if (CMS.getConfigStore().getBoolean("kra.keySplitting")) {
- Credential creds[] = (Credential[])
- request.get(ATTR_AGENT_CREDENTIALS);
+ Credential creds[] = (Credential[])
+ request.get(ATTR_AGENT_CREDENTIALS);
- mStorageUnit.login(creds);
+ mStorageUnit.login(creds);
}
mKRA.log(ILogger.LL_INFO, "KRA decrypts internal private");
- byte privateKeyData[] =
- mStorageUnit.decryptInternalPrivate(
- keyRecord.getPrivateKeyData());
+ byte privateKeyData[] =
+ mStorageUnit.decryptInternalPrivate(
+ keyRecord.getPrivateKeyData());
if (CMS.getConfigStore().getBoolean("kra.keySplitting")) {
- mStorageUnit.logout();
+ mStorageUnit.logout();
}
if (privateKeyData == null) {
mKRA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_KRA_PRIVATE_KEY_NOT_FOUND"));
@@ -556,20 +550,19 @@ public class RecoveryService implements IService {
}
/**
- * Creates a PFX (PKCS12) file.
- * - used when allowEncDecrypt_recovery is true
- *
+ * Creates a PFX (PKCS12) file. - used when allowEncDecrypt_recovery is true
+ *
* @param request CRMF recovery request
* @param priData decrypted private key (PrivateKeyInfo)
* @exception EBaseException failed to create P12 file
*/
- public void createPFX(IRequest request, Hashtable params,
- byte priData[]) throws EBaseException {
+ public void createPFX(IRequest request, Hashtable params,
+ byte priData[]) throws EBaseException {
CMS.debug("RecoverService: createPFX() allowEncDecrypt_recovery=true");
try {
// create p12
X509Certificate x509cert =
- request.getExtDataInCert(ATTR_USER_CERT);
+ request.getExtDataInCert(ATTR_USER_CERT);
String pwd = (String) params.get(ATTR_TRANSPORT_PWD);
// add certificate
@@ -586,29 +579,29 @@ public class RecoveryService implements IService {
nickname, localKeyId);
// attributes: user friendly name, Local Key ID
SafeBag certBag = new SafeBag(SafeBag.CERT_BAG,
- new CertBag(CertBag.X509_CERT_TYPE, cert),
+ new CertBag(CertBag.X509_CERT_TYPE, cert),
certAttrs);
encSafeContents.addElement(certBag);
// add key
mKRA.log(ILogger.LL_INFO, "KRA adds key to P12");
- org.mozilla.jss.util.Password pass = new
- org.mozilla.jss.util.Password(
- pwd.toCharArray());
+ org.mozilla.jss.util.Password pass = new
+ org.mozilla.jss.util.Password(
+ pwd.toCharArray());
SEQUENCE safeContents = new SEQUENCE();
- PasswordConverter passConverter = new
- PasswordConverter();
- byte salt[] = {0x01, 0x01, 0x01, 0x01};
+ PasswordConverter passConverter = new
+ PasswordConverter();
+ byte salt[] = { 0x01, 0x01, 0x01, 0x01 };
PrivateKeyInfo pki = (PrivateKeyInfo)
- ASN1Util.decode(PrivateKeyInfo.getTemplate(),
- priData);
+ ASN1Util.decode(PrivateKeyInfo.getTemplate(),
+ priData);
ASN1Value key = EncryptedPrivateKeyInfo.createPBE(
- PBEAlgorithm.PBE_SHA1_DES3_CBC,
+ PBEAlgorithm.PBE_SHA1_DES3_CBC,
pass, salt, 1, passConverter, pki);
SET keyAttrs = createBagAttrs(
- x509cert.getSubjectDN().toString(),
+ x509cert.getSubjectDN().toString(),
localKeyId);
SafeBag keyBag = new SafeBag(
SafeBag.PKCS8_SHROUDED_KEY_BAG, key,
@@ -617,25 +610,25 @@ public class RecoveryService implements IService {
safeContents.addElement(keyBag);
// build contents
- AuthenticatedSafes authSafes = new
- AuthenticatedSafes();
+ AuthenticatedSafes authSafes = new
+ AuthenticatedSafes();
authSafes.addSafeContents(
- safeContents
- );
+ safeContents
+ );
authSafes.addSafeContents(
- encSafeContents
- );
+ encSafeContents
+ );
- // authSafes.addEncryptedSafeContents(
- // authSafes.DEFAULT_KEY_GEN_ALG,
- // pass, null, 1,
- // encSafeContents);
+ // authSafes.addEncryptedSafeContents(
+ // authSafes.DEFAULT_KEY_GEN_ALG,
+ // pass, null, 1,
+ // encSafeContents);
PFX pfx = new PFX(authSafes);
pfx.computeMacData(pass, null, 5); // ??
- ByteArrayOutputStream fos = new
- ByteArrayOutputStream();
+ ByteArrayOutputStream fos = new
+ ByteArrayOutputStream();
pfx.encode(fos);
pass.clear();
@@ -655,7 +648,7 @@ public class RecoveryService implements IService {
* Creates local key identifier.
*/
public byte[] createLocalKeyId(X509Certificate cert)
- throws EBaseException {
+ throws EBaseException {
try {
// SHA1 hash of the X509Cert der encoding
byte certDer[] = cert.getEncoded();
@@ -666,12 +659,12 @@ public class RecoveryService implements IService {
md.update(certDer);
return md.digest();
} catch (CertificateEncodingException e) {
- mKRA.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_KRA_CREAT_KEY_ID", e.toString()));
+ mKRA.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_KRA_CREAT_KEY_ID", e.toString()));
throw new EKRAException(CMS.getUserMessage("CMS_KRA_KEYID_FAILED_1", e.toString()));
} catch (NoSuchAlgorithmException e) {
- mKRA.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_KRA_CREAT_KEY_ID", e.toString()));
+ mKRA.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_KRA_CREAT_KEY_ID", e.toString()));
throw new EKRAException(CMS.getUserMessage("CMS_KRA_KEYID_FAILED_1", e.toString()));
}
}
@@ -679,8 +672,8 @@ public class RecoveryService implements IService {
/**
* Creates bag attributes.
*/
- public SET createBagAttrs(String nickName, byte localKeyId[])
- throws EBaseException {
+ public SET createBagAttrs(String nickName, byte localKeyId[])
+ throws EBaseException {
try {
SET attrs = new SET();
SEQUENCE nickNameAttr = new SEQUENCE();
@@ -701,8 +694,8 @@ public class RecoveryService implements IService {
attrs.addElement(localKeyAttr);
return attrs;
} catch (CharConversionException e) {
- mKRA.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_KRA_CREAT_KEY_BAG", e.toString()));
+ mKRA.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_KRA_CREAT_KEY_BAG", e.toString()));
throw new EKRAException(CMS.getUserMessage("CMS_KRA_KEYBAG_FAILED_1", e.toString()));
}
}
diff --git a/pki/base/kra/src/com/netscape/kra/StorageKeyUnit.java b/pki/base/kra/src/com/netscape/kra/StorageKeyUnit.java
index 2c3ba716..1481808c 100644
--- a/pki/base/kra/src/com/netscape/kra/StorageKeyUnit.java
+++ b/pki/base/kra/src/com/netscape/kra/StorageKeyUnit.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.kra;
-
import java.io.CharConversionException;
import java.io.File;
import java.io.FileInputStream;
@@ -62,16 +61,14 @@ import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.security.Credential;
import com.netscape.certsrv.security.IStorageKeyUnit;
-
/**
- * A class represents a storage key unit. Currently, this
- * is implemented with cryptix, the final implementation
- * should be built on JSS/HCL.
- *
+ * A class represents a storage key unit. Currently, this is implemented with
+ * cryptix, the final implementation should be built on JSS/HCL.
+ *
* @author thomask
* @version $Revision$, $Date$
*/
-public class StorageKeyUnit extends EncryptionUnit implements
+public class StorageKeyUnit extends EncryptionUnit implements
ISubsystem, IStorageKeyUnit {
private IConfigStore mConfig = null;
@@ -89,7 +86,6 @@ public class StorageKeyUnit extends EncryptionUnit implements
private byte mPrivateKeyData[] = null;
private boolean mKeySplitting = false;
-
private static final String PROP_N = "n";
private static final String PROP_M = "m";
private static final String PROP_UID = "uid";
@@ -105,7 +101,7 @@ public class StorageKeyUnit extends EncryptionUnit implements
* Constructs this token.
*/
public StorageKeyUnit() {
- super();
+ super();
}
/**
@@ -116,35 +112,39 @@ public class StorageKeyUnit extends EncryptionUnit implements
}
/**
- * Sets subsystem identifier. Once the system is
- * loaded, system identifier cannot be changed
- * dynamically.
+ * Sets subsystem identifier. Once the system is loaded, system identifier
+ * cannot be changed dynamically.
*/
public void setId(String id) throws EBaseException {
throw new EBaseException(CMS.getUserMessage("CMS_INVALID_OPERATION"));
}
/**
- * return true if byte arrays are equal, false otherwise
+ * return true if byte arrays are equal, false otherwise
*/
private boolean byteArraysMatch(byte a[], byte b[]) {
- if (a==null || b==null) { return false; }
- if (a.length != b.length) { return false; }
- for (int i=0; i<a.length; i++) {
- if (a[i] != b[i]) { return false; }
- }
- return true;
+ if (a == null || b == null) {
+ return false;
+ }
+ if (a.length != b.length) {
+ return false;
+ }
+ for (int i = 0; i < a.length; i++) {
+ if (a[i] != b[i]) {
+ return false;
+ }
+ }
+ return true;
}
-
/**
* Initializes this subsystem.
*/
- public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ public void init(ISubsystem owner, IConfigStore config)
+ throws EBaseException {
mKRA = (IKeyRecoveryAuthority) owner;
mConfig = config;
-
+
mKeySplitting = owner.getConfigStore().getBoolean("keySplitting", false);
try {
@@ -154,154 +154,154 @@ public class StorageKeyUnit extends EncryptionUnit implements
mKRA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_KRA_STORAGE_INIT", e.toString()));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_ERROR", e.toString()));
}
-
+
if (mConfig.getString(PROP_HARDWARE, null) != null) {
System.setProperty("cms.skip_token", mConfig.getString(PROP_HARDWARE));
-// The strategy here is to read all the certs in the token
-// and cycle through them until we find one that matches the
-// kra-cert.db file
+ // The strategy here is to read all the certs in the token
+ // and cycle through them until we find one that matches the
+ // kra-cert.db file
- if (mKeySplitting) {
+ if (mKeySplitting) {
- byte certFileData[] = null;
- try {
- File certFile = new File(
- mConfig.getString(PROP_CERTDB));
+ byte certFileData[] = null;
+ try {
+ File certFile = new File(
+ mConfig.getString(PROP_CERTDB));
- certFileData = new byte[
- (Long.valueOf(certFile.length())).intValue()];
- FileInputStream fi = new FileInputStream(certFile);
+ certFileData = new byte[
+ (Long.valueOf(certFile.length())).intValue()];
+ FileInputStream fi = new FileInputStream(certFile);
- fi.read(certFileData);
- fi.close();
+ fi.read(certFileData);
+ fi.close();
- // pick up cert by nickName
+ // pick up cert by nickName
- } catch (IOException e) {
- mKRA.log(ILogger.LL_INFO,
- CMS.getLogMessage("CMSCORE_KRA_STORAGE_READ_CERT", e.toString()));
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_ERROR", e.toString()));
- }
+ } catch (IOException e) {
+ mKRA.log(ILogger.LL_INFO,
+ CMS.getLogMessage("CMSCORE_KRA_STORAGE_READ_CERT", e.toString()));
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_ERROR", e.toString()));
+ }
+
+ try {
+ X509Certificate certs[] =
+ getToken().getCryptoStore().getCertificates();
+ for (int i = 0; i < certs.length; i++) {
+ if (byteArraysMatch(certs[i].getEncoded(), certFileData)) {
+ mCert = certs[i];
+ }
+ }
+ if (mCert == null) {
+ mKRA.log(ILogger.LL_FAILURE, "Storage Cert could not be initialized. No cert in token matched kra-cert file");
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_ERROR", "mCert == null"));
+ } else {
+ mKRA.log(ILogger.LL_INFO, "Using Storage Cert " + mCert.getSubjectDN());
+ }
+ } catch (CertificateEncodingException e) {
+ mKRA.log(ILogger.LL_FAILURE, "Error encoding cert ");
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_ERROR", e.toString()));
+ } catch (TokenException e) {
+ mKRA.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_KRA_STORAGE_READ_CERT", e.toString()));
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_ERROR", e.toString()));
+ }
+ }
- try {
- X509Certificate certs[] =
- getToken().getCryptoStore().getCertificates();
- for (int i=0;i <certs.length;i++) {
- if (byteArraysMatch(certs[i].getEncoded(),certFileData)) {
- mCert = certs[i];
- }
- }
- if (mCert == null) {
- mKRA.log(ILogger.LL_FAILURE, "Storage Cert could not be initialized. No cert in token matched kra-cert file");
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_ERROR", "mCert == null"));
- } else {
- mKRA.log(ILogger.LL_INFO, "Using Storage Cert "+mCert.getSubjectDN());
- }
- } catch (CertificateEncodingException e) {
- mKRA.log(ILogger.LL_FAILURE, "Error encoding cert ");
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_ERROR", e.toString()));
- } catch (TokenException e) {
- mKRA.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_KRA_STORAGE_READ_CERT", e.toString()));
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_ERROR", e.toString()));
- }
- }
-
} else {
// read certificate from file
byte certData[] = null;
try {
- if (mKeySplitting) {
- File certFile = new File(
- mConfig.getString(PROP_CERTDB));
+ if (mKeySplitting) {
+ File certFile = new File(
+ mConfig.getString(PROP_CERTDB));
- certData = new byte[
- (Long.valueOf(certFile.length())).intValue()];
- FileInputStream fi = new FileInputStream(certFile);
+ certData = new byte[
+ (Long.valueOf(certFile.length())).intValue()];
+ FileInputStream fi = new FileInputStream(certFile);
- fi.read(certData);
- fi.close();
+ fi.read(certData);
+ fi.close();
- // pick up cert by nickName
- mCert = mManager.findCertByNickname(
+ // pick up cert by nickName
+ mCert = mManager.findCertByNickname(
config.getString(PROP_NICKNAME));
- } else {
- mCert = mManager.findCertByNickname(
+ } else {
+ mCert = mManager.findCertByNickname(
config.getString(PROP_NICKNAME));
- }
+ }
} catch (IOException e) {
- mKRA.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_KRA_STORAGE_READ_CERT", e.toString()));
+ mKRA.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_KRA_STORAGE_READ_CERT", e.toString()));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_ERROR", e.toString()));
} catch (TokenException e) {
- mKRA.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_KRA_STORAGE_READ_CERT", e.toString()));
+ mKRA.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_KRA_STORAGE_READ_CERT", e.toString()));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_ERROR", e.toString()));
} catch (ObjectNotFoundException e) {
- mKRA.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_KRA_STORAGE_READ_CERT", e.toString()));
+ mKRA.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_KRA_STORAGE_READ_CERT", e.toString()));
// XXX - this import wont work
try {
- mCert = mManager.importCertPackage(certData,
+ mCert = mManager.importCertPackage(certData,
"kraStorageCert");
} catch (Exception ex) {
- mKRA.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_KRA_STORAGE_IMPORT_CERT", e.toString()));
+ mKRA.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_KRA_STORAGE_IMPORT_CERT", e.toString()));
throw new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_ERROR", ex.toString()));
}
}
-
- if (mKeySplitting) {
- // read private key from the file
- try {
- File priFile = new File(mConfig.getString(PROP_KEYDB));
-
- mPrivateKeyData = new byte[
- (Long.valueOf(priFile.length())).intValue()];
- FileInputStream fi = new FileInputStream(priFile);
- fi.read(mPrivateKeyData);
- fi.close();
- } catch (IOException e) {
- mKRA.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_KRA_STORAGE_READ_PRIVATE", e.toString()));
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1", e.toString()));
+ if (mKeySplitting) {
+ // read private key from the file
+ try {
+ File priFile = new File(mConfig.getString(PROP_KEYDB));
+
+ mPrivateKeyData = new byte[
+ (Long.valueOf(priFile.length())).intValue()];
+ FileInputStream fi = new FileInputStream(priFile);
+
+ fi.read(mPrivateKeyData);
+ fi.close();
+ } catch (IOException e) {
+ mKRA.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_KRA_STORAGE_READ_PRIVATE", e.toString()));
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1", e.toString()));
+ }
}
- }
-
+
}
- if (mKeySplitting) {
- // open internal data storage configuration
- mTokenFile = mConfig.getString(PROP_MN);
- try {
- // read m, n and no of identifier
- mStorageConfig = CMS.createFileConfigStore(mTokenFile);
- } catch (EBaseException e) {
- mKRA.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_KRA_STORAGE_READ_MN",
- e.toString()));
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_OPERATION"));
+ if (mKeySplitting) {
+ // open internal data storage configuration
+ mTokenFile = mConfig.getString(PROP_MN);
+ try {
+ // read m, n and no of identifier
+ mStorageConfig = CMS.createFileConfigStore(mTokenFile);
+ } catch (EBaseException e) {
+ mKRA.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_KRA_STORAGE_READ_MN",
+ e.toString()));
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_OPERATION"));
+ }
}
- }
- try {
- if (mCert == null) {
- CMS.debug("mCert is null...retrieving "+ config.getString(PROP_NICKNAME));
- mCert = mManager.findCertByNickname(
- config.getString(PROP_NICKNAME));
- CMS.debug("mCert = "+mCert);
- }
- } catch (Exception e) {
- mKRA.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_KRA_STORAGE_READ_CERT", e.toString()));
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_ERROR", e.toString()));
- }
+ try {
+ if (mCert == null) {
+ CMS.debug("mCert is null...retrieving " + config.getString(PROP_NICKNAME));
+ mCert = mManager.findCertByNickname(
+ config.getString(PROP_NICKNAME));
+ CMS.debug("mCert = " + mCert);
+ }
+ } catch (Exception e) {
+ mKRA.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_KRA_STORAGE_READ_CERT", e.toString()));
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_ERROR", e.toString()));
+ }
}
@@ -316,7 +316,7 @@ public class StorageKeyUnit extends EncryptionUnit implements
*/
public void shutdown() {
}
-
+
/**
* Returns the configuration store of this token.
*/
@@ -325,7 +325,7 @@ public class StorageKeyUnit extends EncryptionUnit implements
}
public static SymmetricKey buildSymmetricKeyWithInternalStorage(
- String pin) throws EBaseException {
+ String pin) throws EBaseException {
try {
return buildSymmetricKey(CryptoManager.getInstance().getInternalKeyStorageToken(), pin);
} catch (Exception e) {
@@ -336,8 +336,8 @@ public class StorageKeyUnit extends EncryptionUnit implements
/**
* Builds symmetric key from the given password.
*/
- public static SymmetricKey buildSymmetricKey(CryptoToken token,
- String pin) throws EBaseException {
+ public static SymmetricKey buildSymmetricKey(CryptoToken token,
+ String pin) throws EBaseException {
try {
Password pass = new Password(pin.toCharArray());
@@ -345,8 +345,8 @@ public class StorageKeyUnit extends EncryptionUnit implements
kg = token.getKeyGenerator(
PBEAlgorithm.PBE_SHA1_DES3_CBC);
- byte salt[] = {0x01, 0x01, 0x01, 0x01,
- 0x01, 0x01, 0x01, 0x01};
+ byte salt[] = { 0x01, 0x01, 0x01, 0x01,
+ 0x01, 0x01, 0x01, 0x01 };
PBEKeyGenParams kgp = new PBEKeyGenParams(pass,
salt, 5);
@@ -354,21 +354,21 @@ public class StorageKeyUnit extends EncryptionUnit implements
kg.initialize(kgp);
return kg.generate();
} catch (TokenException e) {
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
"buildSymmetricKey:" +
- e.toString()));
+ e.toString()));
} catch (NoSuchAlgorithmException e) {
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
"buildSymmetricKey:" +
- e.toString()));
+ e.toString()));
} catch (InvalidAlgorithmParameterException e) {
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
"buildSymmetricKey:" +
- e.toString()));
+ e.toString()));
} catch (CharConversionException e) {
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
"buildSymmetricKey:" +
- e.toString()));
+ e.toString()));
}
}
@@ -376,49 +376,49 @@ public class StorageKeyUnit extends EncryptionUnit implements
* Unwraps the storage key with the given symmetric key.
*/
public PrivateKey unwrapStorageKey(CryptoToken token,
- SymmetricKey sk, byte wrapped[],
- PublicKey pubKey)
- throws EBaseException {
+ SymmetricKey sk, byte wrapped[],
+ PublicKey pubKey)
+ throws EBaseException {
try {
CMS.debug("StorageKeyUnit.unwrapStorageKey.");
KeyWrapper wrapper = token.getKeyWrapper(
KeyWrapAlgorithm.DES3_CBC_PAD);
-
- wrapper.initUnwrap(sk, IV);
+
+ wrapper.initUnwrap(sk, IV);
// XXX - it does not like the public key that is
// not a crypto X509Certificate
- PrivateKey pk = wrapper.unwrapTemporaryPrivate(wrapped,
+ PrivateKey pk = wrapper.unwrapTemporaryPrivate(wrapped,
PrivateKey.RSA, pubKey);
return pk;
} catch (TokenException e) {
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
"unwrapStorageKey:" +
- e.toString()));
+ e.toString()));
} catch (NoSuchAlgorithmException e) {
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
"unwrapStorageKey:" +
- e.toString()));
+ e.toString()));
} catch (InvalidKeyException e) {
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
"unwrapStorageKey:" +
- e.toString()));
+ e.toString()));
} catch (InvalidAlgorithmParameterException e) {
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
"unwrapStorageKey:" +
- e.toString()));
+ e.toString()));
}
}
-
+
/**
* Used by config-cert.
*/
public byte[] wrapStorageKey(CryptoToken token,
- SymmetricKey sk, PrivateKey pri)
- throws EBaseException {
+ SymmetricKey sk, PrivateKey pri)
+ throws EBaseException {
CMS.debug("StorageKeyUnit.wrapStorageKey.");
try {
// move public & private to config/storage.dat
@@ -432,21 +432,21 @@ public class StorageKeyUnit extends EncryptionUnit implements
wrapper.initWrap(sk, IV);
return wrapper.wrap(pri);
} catch (TokenException e) {
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
"wrapStorageKey:" +
- e.toString()));
+ e.toString()));
} catch (NoSuchAlgorithmException e) {
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
"wrapStorageKey:" +
- e.toString()));
+ e.toString()));
} catch (InvalidKeyException e) {
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
"wrapStorageKey:" +
- e.toString()));
+ e.toString()));
} catch (InvalidAlgorithmParameterException e) {
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
"wrapStorageKey:" +
- e.toString()));
+ e.toString()));
}
}
@@ -460,7 +460,7 @@ public class StorageKeyUnit extends EncryptionUnit implements
PrivateKey pk[] = getToken().getCryptoStore().getPrivateKeys();
for (int i = 0; i < pk.length; i++) {
- if (arraysEqual(pk[i].getUniqueID(),
+ if (arraysEqual(pk[i].getUniqueID(),
((TokenCertificate) mCert).getUniqueID())) {
mPrivateKey = pk[i];
}
@@ -473,7 +473,7 @@ public class StorageKeyUnit extends EncryptionUnit implements
try {
SymmetricKey sk = buildSymmetricKey(mToken, pin);
- mPrivateKey = unwrapStorageKey(mToken, sk,
+ mPrivateKey = unwrapStorageKey(mToken, sk,
mPrivateKeyData, getPublicKey());
} catch (Exception e) {
mKRA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_KRA_STORAGE_LOGIN", e.toString()));
@@ -487,8 +487,8 @@ public class StorageKeyUnit extends EncryptionUnit implements
/**
* Logins to this token.
*/
- public void login(Credential creds[])
- throws EBaseException {
+ public void login(Credential creds[])
+ throws EBaseException {
String pwd = constructPassword(creds);
login(pwd);
@@ -500,9 +500,9 @@ public class StorageKeyUnit extends EncryptionUnit implements
public void logout() {
try {
if (mConfig.getString(PROP_HARDWARE, null) != null) {
- if (mConfig.getBoolean(PROP_LOGOUT, false)) {
- getToken().logout();
- }
+ if (mConfig.getBoolean(PROP_LOGOUT, false)) {
+ getToken().logout();
+ }
}
} catch (Exception e) {
mKRA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_KRA_STORAGE_LOGOUT", e.toString()));
@@ -519,8 +519,8 @@ public class StorageKeyUnit extends EncryptionUnit implements
for (int i = 0;; i++) {
try {
- String uid =
- mStorageConfig.getString(PROP_UID + i);
+ String uid =
+ mStorageConfig.getString(PROP_UID + i);
if (uid == null)
break;
@@ -535,13 +535,13 @@ public class StorageKeyUnit extends EncryptionUnit implements
/**
* Changes agent password.
*/
- public boolean changeAgentPassword(String id, String oldpwd,
- String newpwd) throws EBaseException {
+ public boolean changeAgentPassword(String id, String oldpwd,
+ String newpwd) throws EBaseException {
// locate the id(s)
for (int i = 0;; i++) {
try {
- String uid =
- mStorageConfig.getString(PROP_UID + i);
+ String uid =
+ mStorageConfig.getString(PROP_UID + i);
if (uid == null)
break;
@@ -549,8 +549,8 @@ public class StorageKeyUnit extends EncryptionUnit implements
byte share[] = decryptShareWithInternalStorage(mStorageConfig.getString(PROP_SHARE + i), oldpwd);
mStorageConfig.putString(PROP_SHARE + i,
- encryptShareWithInternalStorage(
- share, newpwd));
+ encryptShareWithInternalStorage(
+ share, newpwd));
mStorageConfig.commit(false);
return true;
}
@@ -564,10 +564,10 @@ public class StorageKeyUnit extends EncryptionUnit implements
/**
* Changes the m out of n recovery schema.
*/
- public boolean changeAgentMN(int new_n, int new_m,
- Credential oldcreds[],
- Credential newcreds[])
- throws EBaseException {
+ public boolean changeAgentMN(int new_n, int new_m,
+ Credential oldcreds[],
+ Credential newcreds[])
+ throws EBaseException {
if (new_n != newcreds.length) {
throw new EKRAException(CMS.getUserMessage("CMS_KRA_INVALID_N"));
@@ -587,22 +587,22 @@ public class StorageKeyUnit extends EncryptionUnit implements
IShare s = null;
try {
- String className = mConfig.getString("share_class",
+ String className = mConfig.getString("share_class",
"com.netscape.cms.shares.OldShare");
- s = (IShare)Class.forName(className).newInstance();
+ s = (IShare) Class.forName(className).newInstance();
} catch (Exception e) {
- CMS.debug("Loading Shares error " + e);
+ CMS.debug("Loading Shares error " + e);
}
if (s == null) {
- CMS.debug("Share plugin is not found");
- return false;
+ CMS.debug("Share plugin is not found");
+ return false;
}
try {
- s.initialize(secret.getBytes(), new_m);
+ s.initialize(secret.getBytes(), new_m);
} catch (Exception e) {
- CMS.debug("Failed to initialize Share plugin");
- return false;
+ CMS.debug("Failed to initialize Share plugin");
+ return false;
}
for (int i = 0; i < newcreds.length; i++) {
@@ -615,20 +615,20 @@ public class StorageKeyUnit extends EncryptionUnit implements
mStorageConfig.putInteger(PROP_N, new_n);
mStorageConfig.putInteger(PROP_M, new_m);
for (int i = 0; i < newcreds.length; i++) {
- mStorageConfig.putString(PROP_UID + i,
- newcreds[i].getIdentifier());
+ mStorageConfig.putString(PROP_UID + i,
+ newcreds[i].getIdentifier());
// use password to encrypt shares...
- mStorageConfig.putString(PROP_SHARE + i,
- encryptShareWithInternalStorage(shares[i],
- newcreds[i].getPassword()));
+ mStorageConfig.putString(PROP_SHARE + i,
+ encryptShareWithInternalStorage(shares[i],
+ newcreds[i].getPassword()));
}
try {
mStorageConfig.commit(false);
return true;
} catch (EBaseException e) {
- mKRA.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_KRA_STORAGE_CHANGE_MN", e.toString()));
+ mKRA.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_KRA_STORAGE_CHANGE_MN", e.toString()));
}
return false;
}
@@ -641,8 +641,7 @@ public class StorageKeyUnit extends EncryptionUnit implements
}
/**
- * Returns number of recovery agents required for
- * recovery operation.
+ * Returns number of recovery agents required for recovery operation.
*/
public int getNoOfRequiredAgents() throws EBaseException {
return mStorageConfig.getInteger(PROP_M);
@@ -683,33 +682,33 @@ public class StorageKeyUnit extends EncryptionUnit implements
public PrivateKey getPrivateKey() {
if (!mKeySplitting) {
- try {
- PrivateKey pk[] = getToken().getCryptoStore().getPrivateKeys();
- for (int i = 0; i < pk.length; i++) {
- if (arraysEqual(pk[i].getUniqueID(),
+ try {
+ PrivateKey pk[] = getToken().getCryptoStore().getPrivateKeys();
+ for (int i = 0; i < pk.length; i++) {
+ if (arraysEqual(pk[i].getUniqueID(),
((TokenCertificate) mCert).getUniqueID())) {
return pk[i];
}
- }
- } catch (TokenException e) {
- }
- return null;
- } else {
- return mPrivateKey;
- }
+ }
+ } catch (TokenException e) {
+ }
+ return null;
+ } else {
+ return mPrivateKey;
+ }
}
/**
* Verifies the integrity of the given key pairs.
*/
public void verify(byte publicKey[], PrivateKey privateKey)
- throws EBaseException {
+ throws EBaseException {
// XXX
}
public String encryptShareWithInternalStorage(
- byte share[], String pwd)
- throws EBaseException {
+ byte share[], String pwd)
+ throws EBaseException {
try {
return encryptShare(CryptoManager.getInstance().getInternalKeyStorageToken(), share, pwd);
} catch (Exception e) {
@@ -721,8 +720,8 @@ public class StorageKeyUnit extends EncryptionUnit implements
* Protectes the share with the given password.
*/
public String encryptShare(CryptoToken token,
- byte share[], String pwd)
- throws EBaseException {
+ byte share[], String pwd)
+ throws EBaseException {
try {
CMS.debug("StorageKeyUnit.encryptShare");
Cipher cipher = token.getCipherContext(
@@ -737,22 +736,22 @@ public class StorageKeyUnit extends EncryptionUnit implements
// configuration
return com.netscape.osutil.OSUtil.BtoA(enc).trim();
} catch (NoSuchAlgorithmException e) {
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
e.toString()));
} catch (TokenException e) {
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
e.toString()));
} catch (InvalidKeyException e) {
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
e.toString()));
} catch (InvalidAlgorithmParameterException e) {
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
e.toString()));
} catch (BadPaddingException e) {
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
e.toString()));
} catch (IllegalBlockSizeException e) {
- throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
+ throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1",
e.toString()));
}
}
@@ -798,21 +797,21 @@ public class StorageKeyUnit extends EncryptionUnit implements
}
if (uid.equals(userid)) {
byte data[] = decryptShareWithInternalStorage(
- mStorageConfig.getString(PROP_SHARE + i),
- pwd);
- if (data == null) {
- throw new EBaseException(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
+ mStorageConfig.getString(PROP_SHARE + i),
+ pwd);
+ if (data == null) {
+ throw new EBaseException(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
}
return;
}
}
throw new EBaseException(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
-
+
}
public byte[] decryptShareWithInternalStorage(
- String encoding, String pwd)
- throws EBaseException {
+ String encoding, String pwd)
+ throws EBaseException {
try {
return decryptShare(CryptoManager.getInstance().getInternalKeyStorageToken(), encoding, pwd);
} catch (Exception e) {
@@ -824,8 +823,8 @@ public class StorageKeyUnit extends EncryptionUnit implements
* Decrypts shares with the given password.
*/
public byte[] decryptShare(CryptoToken token,
- String encoding, String pwd)
- throws EBaseException {
+ String encoding, String pwd)
+ throws EBaseException {
try {
CMS.debug("StorageKeyUnit.decryptShare");
byte share[] = CMS.AtoB(encoding);
@@ -851,25 +850,25 @@ public class StorageKeyUnit extends EncryptionUnit implements
//
// e.printStackTrace();
//
- throw new EBaseException(CMS.getUserMessage("CMS_KRA_INVALID_PASSWORD",
+ throw new EBaseException(CMS.getUserMessage("CMS_KRA_INVALID_PASSWORD",
e.toString()));
} catch (TokenException e) {
- throw new EBaseException(CMS.getUserMessage("CMS_KRA_INVALID_PASSWORD",
+ throw new EBaseException(CMS.getUserMessage("CMS_KRA_INVALID_PASSWORD",
e.toString()));
} catch (NoSuchAlgorithmException e) {
- throw new EBaseException(CMS.getUserMessage("CMS_KRA_INVALID_PASSWORD",
+ throw new EBaseException(CMS.getUserMessage("CMS_KRA_INVALID_PASSWORD",
e.toString()));
} catch (InvalidKeyException e) {
- throw new EBaseException(CMS.getUserMessage("CMS_KRA_INVALID_PASSWORD",
+ throw new EBaseException(CMS.getUserMessage("CMS_KRA_INVALID_PASSWORD",
e.toString()));
} catch (InvalidAlgorithmParameterException e) {
- throw new EBaseException(CMS.getUserMessage("CMS_KRA_INVALID_PASSWORD",
+ throw new EBaseException(CMS.getUserMessage("CMS_KRA_INVALID_PASSWORD",
e.toString()));
} catch (IllegalBlockSizeException e) {
- throw new EBaseException(CMS.getUserMessage("CMS_KRA_INVALID_PASSWORD",
+ throw new EBaseException(CMS.getUserMessage("CMS_KRA_INVALID_PASSWORD",
e.toString()));
} catch (BadPaddingException e) {
- throw new EBaseException(CMS.getUserMessage("CMS_KRA_INVALID_PASSWORD",
+ throw new EBaseException(CMS.getUserMessage("CMS_KRA_INVALID_PASSWORD",
e.toString()));
}
}
@@ -877,8 +876,8 @@ public class StorageKeyUnit extends EncryptionUnit implements
/**
* Reconstructs password from recovery agents.
*/
- private String constructPassword(Credential creds[])
- throws EBaseException {
+ private String constructPassword(Credential creds[])
+ throws EBaseException {
// sort the credential according to the order in
// configuration file
Hashtable v = new Hashtable();
@@ -897,7 +896,7 @@ public class StorageKeyUnit extends EncryptionUnit implements
if (uid.equals(creds[j].getIdentifier())) {
byte pwd[] = decryptShareWithInternalStorage(
mStorageConfig.getString(
- PROP_SHARE + i),
+ PROP_SHARE + i),
creds[j].getPassword());
if (pwd == null) {
throw new EBaseException(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
@@ -918,11 +917,11 @@ public class StorageKeyUnit extends EncryptionUnit implements
IJoinShares j = null;
try {
- String className = mConfig.getString("joinshares_class",
+ String className = mConfig.getString("joinshares_class",
"com.netscape.cms.shares.OldJoinShares");
- j = (IJoinShares)Class.forName(className).newInstance();
+ j = (IJoinShares) Class.forName(className).newInstance();
} catch (Exception e) {
- CMS.debug("JoinShares error " + e);
+ CMS.debug("JoinShares error " + e);
}
if (j == null) {
CMS.debug("JoinShares plugin is not found");
@@ -930,7 +929,7 @@ public class StorageKeyUnit extends EncryptionUnit implements
}
try {
- j.initialize(v.size());
+ j.initialize(v.size());
} catch (Exception e) {
CMS.debug("Failed to initialize JoinShares");
throw new EBaseException(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
@@ -940,8 +939,8 @@ public class StorageKeyUnit extends EncryptionUnit implements
while (e.hasMoreElements()) {
String next = (String) e.nextElement();
- j.addShare(Integer.parseInt(next) + 1,
- (byte[]) v.get(next));
+ j.addShare(Integer.parseInt(next) + 1,
+ (byte[]) v.get(next));
}
try {
byte secret[] = j.recoverSecret();
@@ -949,9 +948,9 @@ public class StorageKeyUnit extends EncryptionUnit implements
return pwd;
} catch (Exception ee) {
- mKRA.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_KRA_STORAGE_RECONSTRUCT", e.toString()));
- throw new EBaseException(CMS.getUserMessage("CMS_KRA_INVALID_PASSWORD",
+ mKRA.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_KRA_STORAGE_RECONSTRUCT", e.toString()));
+ throw new EBaseException(CMS.getUserMessage("CMS_KRA_INVALID_PASSWORD",
ee.toString()));
}
}
diff --git a/pki/base/kra/src/com/netscape/kra/TokenKeyRecoveryService.java b/pki/base/kra/src/com/netscape/kra/TokenKeyRecoveryService.java
index f9ff8385..e74ebd18 100644
--- a/pki/base/kra/src/com/netscape/kra/TokenKeyRecoveryService.java
+++ b/pki/base/kra/src/com/netscape/kra/TokenKeyRecoveryService.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.kra;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FilterOutputStream;
@@ -52,9 +51,9 @@ import com.netscape.certsrv.security.ITransportKeyUnit;
import com.netscape.cmscore.dbs.KeyRecord;
import com.netscape.cmsutil.util.Cert;
-
/**
* A class represents recovery request processor.
+ *
* @author Christina Fu (cfu)
* @version $Revision$, $Date$
*/
@@ -68,12 +67,12 @@ public class TokenKeyRecoveryService implements IService {
public static final String ATTR_TRANSPORT_PWD = "transportPwd";
public static final String ATTR_SIGNING_CERT = "signingCert";
public static final String ATTR_PKCS12 = "pkcs12";
- public static final String ATTR_ENCRYPTION_CERTS =
- "encryptionCerts";
- public static final String ATTR_AGENT_CREDENTIALS =
- "agentCredentials";
+ public static final String ATTR_ENCRYPTION_CERTS =
+ "encryptionCerts";
+ public static final String ATTR_AGENT_CREDENTIALS =
+ "agentCredentials";
// same as encryption certs
- public static final String ATTR_USER_CERT = "cert";
+ public static final String ATTR_USER_CERT = "cert";
public static final String ATTR_DELIVERY = "delivery";
private IKeyRecoveryAuthority mKRA = null;
@@ -81,13 +80,11 @@ public class TokenKeyRecoveryService implements IService {
private IStorageKeyUnit mStorageUnit = null;
private ITransportKeyUnit mTransportUnit = null;
- private final static String
- LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST =
- "LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_4";
+ private final static String LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST =
+ "LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_4";
- private final static String
- LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED =
- "LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED_4";
+ private final static String LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED =
+ "LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED_4";
private ILogger mSignedAuditLogger = CMS.getSignedAuditLogger();
/**
@@ -97,15 +94,15 @@ public class TokenKeyRecoveryService implements IService {
mKRA = kra;
mStorage = mKRA.getKeyRepository();
mStorageUnit = mKRA.getStorageKeyUnit();
- mTransportUnit = kra.getTransportKeyUnit();
+ mTransportUnit = kra.getTransportKeyUnit();
}
- /**
+ /**
* Process the HTTP request.
- *
+ *
* @param s The URL to decode
*/
- protected String URLdecode(String s) {
+ protected String URLdecode(String s) {
if (s == null)
return null;
ByteArrayOutputStream out = new ByteArrayOutputStream(s.length());
@@ -125,11 +122,11 @@ public class TokenKeyRecoveryService implements IService {
}
} // end for
return out.toString();
- }
+ }
public static String normalizeCertStr(String s) {
String val = "";
-
+
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '\\') {
i++;
@@ -153,9 +150,9 @@ public class TokenKeyRecoveryService implements IService {
ByteArrayOutputStream output = new ByteArrayOutputStream();
Base64OutputStream b64 = new Base64OutputStream(new
PrintStream(new
- FilterOutputStream(output)
+ FilterOutputStream(output)
)
- );
+ );
b64.write(bytes);
b64.flush();
@@ -167,34 +164,29 @@ public class TokenKeyRecoveryService implements IService {
// this encrypts bytes with a symmetric key
public byte[] encryptIt(byte[] toBeEncrypted, SymmetricKey symKey, CryptoToken token,
- IVParameterSpec IV)
- {
- try {
- Cipher cipher = token.getCipherContext(
+ IVParameterSpec IV) {
+ try {
+ Cipher cipher = token.getCipherContext(
EncryptionAlgorithm.DES3_CBC_PAD);
-
- cipher.initEncrypt(symKey, IV);
- byte pri[] = cipher.doFinal(toBeEncrypted);
- return pri;
- } catch (Exception e) {
- CMS.debug("initEncrypt() threw exception: "+e.toString());
+
+ cipher.initEncrypt(symKey, IV);
+ byte pri[] = cipher.doFinal(toBeEncrypted);
+ return pri;
+ } catch (Exception e) {
+ CMS.debug("initEncrypt() threw exception: " + e.toString());
return null;
}
}
-
/**
- * Processes a recovery request. The method reads
- * the key record from the database, and tries to recover the
- * key with the storage key unit. Once recovered, it wraps it
- * with desKey
- * In the params
- * - cert is used for recovery record search
- * - cuid may be used for additional validation check
- * - userid may be used for additional validation check
- * - wrappedDesKey is used for wrapping recovered private key
- *
+ * Processes a recovery request. The method reads the key record from the
+ * database, and tries to recover the key with the storage key unit. Once
+ * recovered, it wraps it with desKey In the params - cert is used for
+ * recovery record search - cuid may be used for additional validation check
+ * - userid may be used for additional validation check - wrappedDesKey is
+ * used for wrapping recovered private key
+ *
* @param request recovery request
* @return operation success or not
* @exception EBaseException failed to serve
@@ -205,56 +197,55 @@ public class TokenKeyRecoveryService implements IService {
String auditRequesterID = "TPSagent";
String auditRecoveryID = ILogger.UNIDENTIFIED;
String auditPublicKey = ILogger.UNIDENTIFIED;
- String iv_s ="";
+ String iv_s = "";
CMS.debug("KRA services token key recovery request");
byte[] wrapped_des_key;
- byte iv[] = {0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1};
+ byte iv[] = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 };
try {
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.nextBytes(iv);
} catch (Exception e) {
- CMS.debug("TokenKeyRecoveryService.serviceRequest: "+ e.toString());
+ CMS.debug("TokenKeyRecoveryService.serviceRequest: " + e.toString());
}
String id = request.getRequestId().toString();
if (id != null) {
auditRecoveryID = id.trim();
}
- SessionContext sContext = SessionContext.getContext();
- String agentId="";
- if (sContext != null) {
+ SessionContext sContext = SessionContext.getContext();
+ String agentId = "";
+ if (sContext != null) {
agentId =
- (String) sContext.get(SessionContext.USER_ID);
- }
+ (String) sContext.get(SessionContext.USER_ID);
+ }
Hashtable params = mKRA.getVolatileRequest(
request.getRequestId());
-
if (params == null) {
// possibly we are in recovery mode
- CMS.debug("getVolatileRequest params null");
- // return true;
+ CMS.debug("getVolatileRequest params null");
+ // return true;
}
wrapped_des_key = null;
- PK11SymKey sk= null;
+ PK11SymKey sk = null;
String rCUID = request.getExtDataInString(IRequest.NETKEY_ATTR_CUID);
String rUserid = request.getExtDataInString(IRequest.NETKEY_ATTR_USERID);
String rWrappedDesKeyString = request.getExtDataInString(IRequest.NETKEY_ATTR_DRMTRANS_DES_KEY);
- auditSubjectID=rCUID+":"+rUserid;
+ auditSubjectID = rCUID + ":" + rUserid;
- CMS.debug("TokenKeyRecoveryService: received DRM-trans-wrapped des key ="+rWrappedDesKeyString);
+ CMS.debug("TokenKeyRecoveryService: received DRM-trans-wrapped des key =" + rWrappedDesKeyString);
wrapped_des_key = com.netscape.cmsutil.util.Utils.SpecialDecode(rWrappedDesKeyString);
CMS.debug("TokenKeyRecoveryService: wrapped_des_key specialDecoded");
if ((wrapped_des_key != null) &&
- (wrapped_des_key.length > 0)) {
+ (wrapped_des_key.length > 0)) {
// unwrap the des key
sk = (PK11SymKey) mTransportUnit.unwrap_encrypt_sym(wrapped_des_key);
@@ -298,7 +289,7 @@ public class TokenKeyRecoveryService implements IService {
String cert = normalizeCertStr(cert_s);
java.security.cert.X509Certificate x509cert = null;
try {
- x509cert= (java.security.cert.X509Certificate) Cert.mapCert(cert);
+ x509cert = (java.security.cert.X509Certificate) Cert.mapCert(cert);
if (x509cert == null) {
CMS.debug("cert mapping failed");
request.setExtData(IRequest.RESULT, Integer.valueOf(5));
@@ -326,291 +317,291 @@ public class TokenKeyRecoveryService implements IService {
return false;
}
- try {
- /*
- CryptoToken internalToken =
- CryptoManager.getInstance().getInternalKeyStorageToken();
- */
- CryptoToken token = mStorageUnit.getToken();
- CMS.debug("TokenKeyRecoveryService: got token slot:"+token.getName());
- IVParameterSpec algParam = new IVParameterSpec(iv);
-
- Cipher cipher = token.getCipherContext(EncryptionAlgorithm.DES3_CBC_PAD);
-
- KeyRecord keyRecord = null;
- CMS.debug( "KRA reading key record");
- try {
- keyRecord = (KeyRecord) mStorage.readKeyRecord(cert);
- if (keyRecord != null)
- CMS.debug("read key record");
- else {
- CMS.debug("key record not found");
- request.setExtData(IRequest.RESULT, Integer.valueOf(8));
- auditMessage = CMS.getLogMessage(
+ try {
+ /*
+ * CryptoToken internalToken =
+ * CryptoManager.getInstance().getInternalKeyStorageToken();
+ */
+ CryptoToken token = mStorageUnit.getToken();
+ CMS.debug("TokenKeyRecoveryService: got token slot:" + token.getName());
+ IVParameterSpec algParam = new IVParameterSpec(iv);
+
+ Cipher cipher = token.getCipherContext(EncryptionAlgorithm.DES3_CBC_PAD);
+
+ KeyRecord keyRecord = null;
+ CMS.debug("KRA reading key record");
+ try {
+ keyRecord = (KeyRecord) mStorage.readKeyRecord(cert);
+ if (keyRecord != null)
+ CMS.debug("read key record");
+ else {
+ CMS.debug("key record not found");
+ request.setExtData(IRequest.RESULT, Integer.valueOf(8));
+ auditMessage = CMS.getLogMessage(
+ LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditRecoveryID,
+ agentId);
+
+ audit(auditMessage);
+ return false;
+ }
+ } catch (Exception e) {
+ com.netscape.cmscore.util.Debug.printStackTrace(e);
+ request.setExtData(IRequest.RESULT, Integer.valueOf(9));
+ auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED,
auditSubjectID,
ILogger.FAILURE,
auditRecoveryID,
agentId);
- audit(auditMessage);
- return false;
- }
- }catch (Exception e) {
- com.netscape.cmscore.util.Debug.printStackTrace(e);
- request.setExtData(IRequest.RESULT, Integer.valueOf(9));
- auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED,
- auditSubjectID,
- ILogger.FAILURE,
- auditRecoveryID,
- agentId);
+ audit(auditMessage);
+ return false;
+ }
- audit(auditMessage);
- return false;
- }
-
- // see if the owner name matches (cuid:userid) -XXX need make this optional
- String owner = keyRecord.getOwnerName();
- CMS.debug("TokenKeyRecoveryService: owner name on record =" +owner);
- CMS.debug("TokenKeyRecoveryService: owner name from TPS =" +rCUID+":"+rUserid);
- if (owner != null) {
- if (owner.equals(rCUID+":"+rUserid)) {
- CMS.debug("TokenKeyRecoveryService: owner name matches");
- } else {
- CMS.debug("TokenKeyRecoveryService: owner name mismatches");
- }
- }
-
- // see if the certificate matches the key
- byte pubData[] = keyRecord.getPublicKeyData();
- byte inputPubData[] = x509cert.getPublicKey().getEncoded();
-
- if (inputPubData.length != pubData.length) {
- mKRA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_KRA_PUBLIC_KEY_LEN"));
- auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED,
- auditSubjectID,
- ILogger.FAILURE,
- auditRecoveryID,
- agentId);
+ // see if the owner name matches (cuid:userid) -XXX need make this
+ // optional
+ String owner = keyRecord.getOwnerName();
+ CMS.debug("TokenKeyRecoveryService: owner name on record =" + owner);
+ CMS.debug("TokenKeyRecoveryService: owner name from TPS =" + rCUID + ":" + rUserid);
+ if (owner != null) {
+ if (owner.equals(rCUID + ":" + rUserid)) {
+ CMS.debug("TokenKeyRecoveryService: owner name matches");
+ } else {
+ CMS.debug("TokenKeyRecoveryService: owner name mismatches");
+ }
+ }
- audit(auditMessage);
- throw new EKRAException(
- CMS.getUserMessage("CMS_KRA_PUBLIC_KEY_NOT_MATCHED"));
- }
+ // see if the certificate matches the key
+ byte pubData[] = keyRecord.getPublicKeyData();
+ byte inputPubData[] = x509cert.getPublicKey().getEncoded();
- for (int i = 0; i < pubData.length; i++) {
- if (pubData[i] != inputPubData[i]) {
- mKRA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_KRA_PUBLIC_KEY_LEN"));
- auditMessage = CMS.getLogMessage(
+ if (inputPubData.length != pubData.length) {
+ mKRA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_KRA_PUBLIC_KEY_LEN"));
+ auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED,
auditSubjectID,
ILogger.FAILURE,
auditRecoveryID,
agentId);
- audit(auditMessage);
- throw new EKRAException(
- CMS.getUserMessage("CMS_KRA_PUBLIC_KEY_NOT_MATCHED"));
- }
- }
-
- // Unwrap the archived private key
- byte privateKeyData[] = null;
- privateKeyData = recoverKey(params, keyRecord);
- if (privateKeyData == null) {
- request.setExtData(IRequest.RESULT, Integer.valueOf(4));
- CMS.debug("TokenKeyRecoveryService: failed getting private key");
- auditMessage = CMS.getLogMessage(
+ audit(auditMessage);
+ throw new EKRAException(
+ CMS.getUserMessage("CMS_KRA_PUBLIC_KEY_NOT_MATCHED"));
+ }
+
+ for (int i = 0; i < pubData.length; i++) {
+ if (pubData[i] != inputPubData[i]) {
+ mKRA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_KRA_PUBLIC_KEY_LEN"));
+ auditMessage = CMS.getLogMessage(
+ LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED,
+ auditSubjectID,
+ ILogger.FAILURE,
+ auditRecoveryID,
+ agentId);
+
+ audit(auditMessage);
+ throw new EKRAException(
+ CMS.getUserMessage("CMS_KRA_PUBLIC_KEY_NOT_MATCHED"));
+ }
+ }
+
+ // Unwrap the archived private key
+ byte privateKeyData[] = null;
+ privateKeyData = recoverKey(params, keyRecord);
+ if (privateKeyData == null) {
+ request.setExtData(IRequest.RESULT, Integer.valueOf(4));
+ CMS.debug("TokenKeyRecoveryService: failed getting private key");
+ auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED,
auditSubjectID,
ILogger.FAILURE,
auditRecoveryID,
agentId);
- audit(auditMessage);
- return false;
- }
- CMS.debug("TokenKeyRecoveryService: got private key...about to verify");
-
- iv_s = /*base64Encode(iv);*/com.netscape.cmsutil.util.Utils.SpecialEncode(iv);
- request.setExtData("iv_s", iv_s);
-
- CMS.debug("request.setExtData: iv_s: " + iv_s);
-
- /* LunaSA returns data with padding which we need to remove */
- ByteArrayInputStream dis = new ByteArrayInputStream(privateKeyData);
- DerValue dv = new DerValue(dis);
- byte p[] = dv.toByteArray();
- int l = p.length;
- CMS.debug("length different data length=" + l +
- " real length=" + privateKeyData.length );
- if (l != privateKeyData.length) {
- privateKeyData = p;
- }
+ audit(auditMessage);
+ return false;
+ }
+ CMS.debug("TokenKeyRecoveryService: got private key...about to verify");
+
+ iv_s = /* base64Encode(iv); */com.netscape.cmsutil.util.Utils.SpecialEncode(iv);
+ request.setExtData("iv_s", iv_s);
+
+ CMS.debug("request.setExtData: iv_s: " + iv_s);
+
+ /* LunaSA returns data with padding which we need to remove */
+ ByteArrayInputStream dis = new ByteArrayInputStream(privateKeyData);
+ DerValue dv = new DerValue(dis);
+ byte p[] = dv.toByteArray();
+ int l = p.length;
+ CMS.debug("length different data length=" + l +
+ " real length=" + privateKeyData.length);
+ if (l != privateKeyData.length) {
+ privateKeyData = p;
+ }
- if (verifyKeyPair(pubData, privateKeyData) == false) {
- mKRA.log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_KRA_PUBLIC_NOT_FOUND"));
- auditMessage = CMS.getLogMessage(
+ if (verifyKeyPair(pubData, privateKeyData) == false) {
+ mKRA.log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_KRA_PUBLIC_NOT_FOUND"));
+ auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED,
auditSubjectID,
ILogger.FAILURE,
auditRecoveryID,
agentId);
- audit(auditMessage);
- throw new EKRAException(
- CMS.getUserMessage("CMS_KRA_INVALID_PUBLIC_KEY"));
- } else {
- CMS.debug("TokenKeyRecoveryService: private key verified with public key");
- }
+ audit(auditMessage);
+ throw new EKRAException(
+ CMS.getUserMessage("CMS_KRA_INVALID_PUBLIC_KEY"));
+ } else {
+ CMS.debug("TokenKeyRecoveryService: private key verified with public key");
+ }
- //encrypt and put in private key
- cipher.initEncrypt(sk, algParam);
- byte wrapped[] = cipher.doFinal(privateKeyData);
+ // encrypt and put in private key
+ cipher.initEncrypt(sk, algParam);
+ byte wrapped[] = cipher.doFinal(privateKeyData);
- String wrappedPrivKeyString =
+ String wrappedPrivKeyString =
com.netscape.cmsutil.util.Utils.SpecialEncode(wrapped);
- if (wrappedPrivKeyString == null) {
- request.setExtData(IRequest.RESULT, Integer.valueOf(4));
- CMS.debug("TokenKeyRecoveryService: failed generating wrapped private key");
- auditMessage = CMS.getLogMessage(
+ if (wrappedPrivKeyString == null) {
+ request.setExtData(IRequest.RESULT, Integer.valueOf(4));
+ CMS.debug("TokenKeyRecoveryService: failed generating wrapped private key");
+ auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED,
auditSubjectID,
ILogger.FAILURE,
auditRecoveryID,
agentId);
- audit(auditMessage);
- return false;
- } else {
- CMS.debug("TokenKeyRecoveryService: got private key data wrapped");
- request.setExtData("wrappedUserPrivate",
- wrappedPrivKeyString);
- request.setExtData(IRequest.RESULT, Integer.valueOf(1));
- CMS.debug( "TokenKeyRecoveryService: key for " +rCUID+":"+rUserid +" recovered");
- }
-
- //convert and put in the public key
- String b64PKey = base64Encode(pubData);
-
- auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST,
- auditSubjectID,
- ILogger.SUCCESS,
- auditRecoveryID,
- b64PKey);
-
audit(auditMessage);
-
- if (b64PKey == null) {
- request.setExtData(IRequest.RESULT, Integer.valueOf(4));
- CMS.debug("TokenKeyRecoveryService: failed getting publickey encoded");
+ return false;
+ } else {
+ CMS.debug("TokenKeyRecoveryService: got private key data wrapped");
+ request.setExtData("wrappedUserPrivate",
+ wrappedPrivKeyString);
+ request.setExtData(IRequest.RESULT, Integer.valueOf(1));
+ CMS.debug("TokenKeyRecoveryService: key for " + rCUID + ":" + rUserid + " recovered");
+ }
+
+ // convert and put in the public key
+ String b64PKey = base64Encode(pubData);
+
auditMessage = CMS.getLogMessage(
+ LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST,
+ auditSubjectID,
+ ILogger.SUCCESS,
+ auditRecoveryID,
+ b64PKey);
+
+ audit(auditMessage);
+
+ if (b64PKey == null) {
+ request.setExtData(IRequest.RESULT, Integer.valueOf(4));
+ CMS.debug("TokenKeyRecoveryService: failed getting publickey encoded");
+ auditMessage = CMS.getLogMessage(
LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED,
auditSubjectID,
ILogger.FAILURE,
auditRecoveryID,
agentId);
+ audit(auditMessage);
+ return false;
+ } else {
+ CMS.debug("TokenKeyRecoveryService: got publicKeyData b64 = " +
+ b64PKey);
+ }
+ request.setExtData("public_key", b64PKey);
+ auditMessage = CMS.getLogMessage(
+ LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED,
+ auditSubjectID,
+ ILogger.SUCCESS,
+ auditRecoveryID,
+ agentId);
+
audit(auditMessage);
- return false;
- } else {
- CMS.debug("TokenKeyRecoveryService: got publicKeyData b64 = "+
- b64PKey);
- }
- request.setExtData("public_key", b64PKey);
- auditMessage = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_KEY_RECOVERY_REQUEST_PROCESSED,
- auditSubjectID,
- ILogger.SUCCESS,
- auditRecoveryID,
- agentId);
-
- audit(auditMessage);
- return true;
+ return true;
- } catch (Exception e) {
- CMS.debug("TokenKeyRecoveryService: " + e.toString());
- request.setExtData(IRequest.RESULT, Integer.valueOf(4));
- }
+ } catch (Exception e) {
+ CMS.debug("TokenKeyRecoveryService: " + e.toString());
+ request.setExtData(IRequest.RESULT, Integer.valueOf(4));
+ }
return true;
}
- public boolean verifyKeyPair(byte publicKeyData[], byte privateKeyData[])
- {
- try {
- DerValue publicKeyVal = new DerValue(publicKeyData);
- DerInputStream publicKeyIn = publicKeyVal.data;
- publicKeyIn.getSequence(0);
- DerValue publicKeyDer = new DerValue(publicKeyIn.getBitString());
- DerInputStream publicKeyDerIn = publicKeyDer.data;
- BigInt publicKeyModulus = publicKeyDerIn.getInteger();
- BigInt publicKeyExponent = publicKeyDerIn.getInteger();
-
- DerValue privateKeyVal = new DerValue(privateKeyData);
- if (privateKeyVal.tag != DerValue.tag_Sequence)
- return false;
- DerInputStream privateKeyIn = privateKeyVal.data;
- privateKeyIn.getInteger();
- privateKeyIn.getSequence(0);
- DerValue privateKeyDer = new DerValue(privateKeyIn.getOctetString());
- DerInputStream privateKeyDerIn = privateKeyDer.data;
- BigInt privateKeyVersion = privateKeyDerIn.getInteger();
- BigInt privateKeyModulus = privateKeyDerIn.getInteger();
- BigInt privateKeyExponent = privateKeyDerIn.getInteger();
-
- if (!publicKeyModulus.equals(privateKeyModulus)) {
- CMS.debug("verifyKeyPair modulus mismatch publicKeyModulus=" + publicKeyModulus + " privateKeyModulus=" + privateKeyModulus);
- return false;
- }
-
- if (!publicKeyExponent.equals(privateKeyExponent)) {
- CMS.debug("verifyKeyPair exponent mismatch publicKeyExponent=" + publicKeyExponent + " privateKeyExponent=" + privateKeyExponent);
- return false;
- }
-
- return true;
- } catch (Exception e) {
- CMS.debug("verifyKeyPair error " + e);
- return false;
- }
+ public boolean verifyKeyPair(byte publicKeyData[], byte privateKeyData[]) {
+ try {
+ DerValue publicKeyVal = new DerValue(publicKeyData);
+ DerInputStream publicKeyIn = publicKeyVal.data;
+ publicKeyIn.getSequence(0);
+ DerValue publicKeyDer = new DerValue(publicKeyIn.getBitString());
+ DerInputStream publicKeyDerIn = publicKeyDer.data;
+ BigInt publicKeyModulus = publicKeyDerIn.getInteger();
+ BigInt publicKeyExponent = publicKeyDerIn.getInteger();
+
+ DerValue privateKeyVal = new DerValue(privateKeyData);
+ if (privateKeyVal.tag != DerValue.tag_Sequence)
+ return false;
+ DerInputStream privateKeyIn = privateKeyVal.data;
+ privateKeyIn.getInteger();
+ privateKeyIn.getSequence(0);
+ DerValue privateKeyDer = new DerValue(privateKeyIn.getOctetString());
+ DerInputStream privateKeyDerIn = privateKeyDer.data;
+ BigInt privateKeyVersion = privateKeyDerIn.getInteger();
+ BigInt privateKeyModulus = privateKeyDerIn.getInteger();
+ BigInt privateKeyExponent = privateKeyDerIn.getInteger();
+
+ if (!publicKeyModulus.equals(privateKeyModulus)) {
+ CMS.debug("verifyKeyPair modulus mismatch publicKeyModulus=" + publicKeyModulus + " privateKeyModulus=" + privateKeyModulus);
+ return false;
+ }
+
+ if (!publicKeyExponent.equals(privateKeyExponent)) {
+ CMS.debug("verifyKeyPair exponent mismatch publicKeyExponent=" + publicKeyExponent + " privateKeyExponent=" + privateKeyExponent);
+ return false;
+ }
+
+ return true;
+ } catch (Exception e) {
+ CMS.debug("verifyKeyPair error " + e);
+ return false;
+ }
}
-
+
/**
* Recovers key.
*/
- public synchronized byte[] recoverKey(Hashtable request, KeyRecord keyRecord)
- throws EBaseException {
- /*
- Credential creds[] = (Credential[])
- request.get(ATTR_AGENT_CREDENTIALS);
-
- mStorageUnit.login(creds);
- */
- CMS.debug( "KRA decrypts internal private");
- byte privateKeyData[] =
- mStorageUnit.decryptInternalPrivate(
- keyRecord.getPrivateKeyData());
- /*
- mStorageUnit.logout();
- */
+ public synchronized byte[] recoverKey(Hashtable request, KeyRecord keyRecord)
+ throws EBaseException {
+ /*
+ * Credential creds[] = (Credential[])
+ * request.get(ATTR_AGENT_CREDENTIALS);
+ *
+ * mStorageUnit.login(creds);
+ */
+ CMS.debug("KRA decrypts internal private");
+ byte privateKeyData[] =
+ mStorageUnit.decryptInternalPrivate(
+ keyRecord.getPrivateKeyData());
+ /*
+ * mStorageUnit.logout();
+ */
if (privateKeyData == null) {
mKRA.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_KRA_PRIVATE_KEY_NOT_FOUND"));
throw new EKRAException(CMS.getUserMessage("CMS_KRA_RECOVERY_FAILED_1", "no private key"));
}
return privateKeyData;
}
+
/**
- * Signed Audit Log
- *y
- * This method is called to store messages to the signed audit log.
+ * Signed Audit Log y This method is called to store messages to the signed
+ * audit log.
* <P>
- *
+ *
* @param msg signed audit log message
*/
private void audit(String msg) {
@@ -622,10 +613,10 @@ public class TokenKeyRecoveryService implements IService {
}
mSignedAuditLogger.log(ILogger.EV_SIGNED_AUDIT,
- null,
- ILogger.S_SIGNED_AUDIT,
- ILogger.LL_SECURITY,
- msg);
+ null,
+ ILogger.S_SIGNED_AUDIT,
+ ILogger.LL_SECURITY,
+ msg);
}
}
diff --git a/pki/base/kra/src/com/netscape/kra/TransportKeyUnit.java b/pki/base/kra/src/com/netscape/kra/TransportKeyUnit.java
index 86b2dbfc..fe51a77f 100644
--- a/pki/base/kra/src/com/netscape/kra/TransportKeyUnit.java
+++ b/pki/base/kra/src/com/netscape/kra/TransportKeyUnit.java
@@ -34,15 +34,14 @@ import com.netscape.certsrv.base.ISubsystem;
import com.netscape.certsrv.security.ITransportKeyUnit;
import com.netscape.cmsutil.util.Cert;
-
/**
- * A class represents the transport key pair. This key pair
- * is used to protected EE's private key in transit.
- *
+ * A class represents the transport key pair. This key pair is used to protected
+ * EE's private key in transit.
+ *
* @author thomask
* @version $Revision$, $Date$
*/
-public class TransportKeyUnit extends EncryptionUnit implements
+public class TransportKeyUnit extends EncryptionUnit implements
ISubsystem, ITransportKeyUnit {
public static final String PROP_NICKNAME = "nickName";
@@ -78,8 +77,8 @@ public class TransportKeyUnit extends EncryptionUnit implements
/**
* Initializes this subsystem.
*/
- public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ public void init(ISubsystem owner, IConfigStore config)
+ throws EBaseException {
mConfig = config;
try {
mManager = CryptoManager.getInstance();
@@ -87,11 +86,10 @@ public class TransportKeyUnit extends EncryptionUnit implements
String algo = config.getString("signingAlgorithm", "SHA256withRSA");
// #613795 - initialize this; otherwise JSS is not happy
- CryptoToken token = getToken();
+ CryptoToken token = getToken();
SignatureAlgorithm sigalg = Cert.mapAlgorithmToJss(algo);
- Signature signer = token.getSignatureContext(sigalg);
+ Signature signer = token.getSignatureContext(sigalg);
signer.initSign(getPrivateKey());
-
} catch (org.mozilla.jss.CryptoManager.NotInitializedException e) {
throw new EBaseException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR", e.toString()));
@@ -115,7 +113,7 @@ public class TransportKeyUnit extends EncryptionUnit implements
public CryptoToken getToken() {
// 390148: returning the token that owns the private
- // key.
+ // key.
return getPrivateKey().getOwningToken();
}
@@ -130,7 +128,7 @@ public class TransportKeyUnit extends EncryptionUnit implements
*/
public void shutdown() {
}
-
+
/**
* Returns the configuration store of this token.
*/
@@ -191,7 +189,7 @@ public class TransportKeyUnit extends EncryptionUnit implements
* Verifies the integrity of the given key pair.
*/
public void verify(byte publicKey[], PrivateKey privateKey)
- throws EBaseException {
+ throws EBaseException {
// XXX
}
}
diff --git a/pki/base/migrate/80/MigrateSecurityDomain.java b/pki/base/migrate/80/MigrateSecurityDomain.java
index 7ecdcd1e..09a3b514 100644
--- a/pki/base/migrate/80/MigrateSecurityDomain.java
+++ b/pki/base/migrate/80/MigrateSecurityDomain.java
@@ -37,8 +37,7 @@ import com.netscape.cmsutil.xml.XMLObject;
public class MigrateSecurityDomain {
private static LDAPConnection getLDAPConn(FileConfigStore cs, String passwd)
- throws IOException
- {
+ throws IOException {
String host = "";
String port = "";
@@ -67,11 +66,11 @@ public class MigrateSecurityDomain {
LDAPConnection conn = null;
if (security.equals("true")) {
- System.out.println("MigrateSecurityDomain getLDAPConn: creating secure (SSL) connection for internal ldap");
- conn = new LDAPConnection(new LdapJssSSLSocketFactory());
+ System.out.println("MigrateSecurityDomain getLDAPConn: creating secure (SSL) connection for internal ldap");
+ conn = new LDAPConnection(new LdapJssSSLSocketFactory());
} else {
- System.out.println("MigrateSecurityDomain getLDAPConn: creating non-secure (non-SSL) connection for internal ldap");
- conn = new LDAPConnection();
+ System.out.println("MigrateSecurityDomain getLDAPConn: creating non-secure (non-SSL) connection for internal ldap");
+ conn = new LDAPConnection();
}
System.out.println("MigrateSecurityDomain connecting to " + host + ":" + p);
@@ -82,15 +81,13 @@ public class MigrateSecurityDomain {
throw new IOException("Failed to connect to the internal database.");
}
- return conn;
+ return conn;
}
-
- public static void main(String args[]) throws Exception
- {
+ public static void main(String args[]) throws Exception {
if (args.length != 2) {
- System.out.println("Usage: MigrateSecurityDomain <instance root path> <directory manager password>");
- System.exit(0);
+ System.out.println("Usage: MigrateSecurityDomain <instance root path> <directory manager password>");
+ System.exit(0);
}
String instRoot = args[0];
@@ -103,8 +100,7 @@ public class MigrateSecurityDomain {
System.out.println("MigrateSecurityDomain: Reading domain.xml from file ...");
parser = new XMLObject(new FileInputStream(path));
- }
- catch (Exception e) {
+ } catch (Exception e) {
System.out.println("MigrateSecurityDomain: Unable to get domain info from domain.xml file");
System.out.println(e.toString());
System.exit(1);
@@ -113,21 +109,21 @@ public class MigrateSecurityDomain {
try {
String configFile = instRoot + "/conf/CS.cfg";
FileConfigStore cs = new FileConfigStore(configFile);
-
+
LDAPConnection conn = null;
conn = MigrateSecurityDomain.getLDAPConn(cs, dmPass);
if (conn == null) {
System.out.println("MigrateSecurityDomain: Failed to connect to internal database");
System.exit(1);
- }
+ }
// add new schema elements
String importFile = "./schema-add.ldif";
try {
LDAPUtil.importLDIF(conn, importFile);
} catch (Exception e) {
- System.out.println("MigrateSecurityDomain: Error in adding new schema elements");
- System.exit(1);
+ System.out.println("MigrateSecurityDomain: Error in adding new schema elements");
+ System.exit(1);
}
// create the containers
String basedn = cs.getString("internaldb.basedn");
@@ -142,7 +138,7 @@ public class MigrateSecurityDomain {
attrs = new LDAPAttributeSet();
attrs.add(new LDAPAttribute("objectclass", "top"));
attrs.add(new LDAPAttribute("objectclass", "organizationalUnit"));
- attrs.add(new LDAPAttribute("name", secdomain));
+ attrs.add(new LDAPAttribute("name", secdomain));
attrs.add(new LDAPAttribute("ou", "Security Domain"));
entry = new LDAPEntry(dn, attrs);
conn.add(entry);
@@ -154,8 +150,8 @@ public class MigrateSecurityDomain {
}
// create list containers
- String clist[] = {"CAList", "OCSPList", "KRAList", "RAList", "TKSList", "TPSList"};
- for (int i=0; i< 6; i++) {
+ String clist[] = { "CAList", "OCSPList", "KRAList", "RAList", "TKSList", "TPSList" };
+ for (int i = 0; i < 6; i++) {
LDAPEntry entry = null;
LDAPAttributeSet attrs = null;
String dn = "cn=" + clist[i] + ",ou=Security Domain," + basedn;
@@ -168,16 +164,16 @@ public class MigrateSecurityDomain {
conn.add(entry);
} catch (LDAPException e) {
if (e.getLDAPResultCode() != 68) {
- System.out.println("Unable to create security domain list entry " + dn +": "+ e.toString());
+ System.out.println("Unable to create security domain list entry " + dn + ": " + e.toString());
System.exit(1);
}
}
}
- // create system entries
- String tlist[] = {"CA", "OCSP", "KRA", "RA", "TKS", "TPS"};
+ // create system entries
+ String tlist[] = { "CA", "OCSP", "KRA", "RA", "TKS", "TPS" };
Document doc = parser.getDocument();
- for (int j=0; j<6; j++) {
+ for (int j = 0; j < 6; j++) {
String type = tlist[j];
NodeList nodeList = doc.getElementsByTagName(type);
int len = nodeList.getLength();
@@ -187,17 +183,17 @@ public class MigrateSecurityDomain {
Vector v_host = parser.getValuesFromContainer(nodeList.item(i), "Host");
Vector v_port = parser.getValuesFromContainer(nodeList.item(i), "SecurePort");
- String cn = (String)v_host.elementAt(0) + ":" + (String)v_port.elementAt(0);
- String dn = "cn=" + cn + ",cn=" + type +"List,ou=Security Domain," + basedn;
+ String cn = (String) v_host.elementAt(0) + ":" + (String) v_port.elementAt(0);
+ String dn = "cn=" + cn + ",cn=" + type + "List,ou=Security Domain," + basedn;
LDAPEntry entry = null;
LDAPAttributeSet attrs = null;
attrs = new LDAPAttributeSet();
attrs.add(new LDAPAttribute("objectclass", "top"));
attrs.add(new LDAPAttribute("objectclass", "pkiSubsystem"));
- attrs.add(new LDAPAttribute("Host", (String)v_host.elementAt(0)));
- attrs.add(new LDAPAttribute("SecurePort", (String)v_port.elementAt(0)));
- attrs.add(new LDAPAttribute("Clone", (String)v_clone.elementAt(0)));
- attrs.add(new LDAPAttribute("SubsystemName", (String)v_name.elementAt(0)));
+ attrs.add(new LDAPAttribute("Host", (String) v_host.elementAt(0)));
+ attrs.add(new LDAPAttribute("SecurePort", (String) v_port.elementAt(0)));
+ attrs.add(new LDAPAttribute("Clone", (String) v_clone.elementAt(0)));
+ attrs.add(new LDAPAttribute("SubsystemName", (String) v_name.elementAt(0)));
attrs.add(new LDAPAttribute("cn", cn));
attrs.add(new LDAPAttribute("DomainManager", "true"));
// Since the initial port separation feature didn't occur
@@ -205,16 +201,15 @@ public class MigrateSecurityDomain {
// value for BOTH the "SecureAgentPort" and the
// "SecureAdminPort", and DON'T store any values for the
// "UnSecurePort"
- attrs.add(new LDAPAttribute("SecureAgentPort", (String)v_port.elementAt(0)));
- attrs.add(new LDAPAttribute("SecureAdminPort", (String)v_port.elementAt(0)));
+ attrs.add(new LDAPAttribute("SecureAgentPort", (String) v_port.elementAt(0)));
+ attrs.add(new LDAPAttribute("SecureAdminPort", (String) v_port.elementAt(0)));
entry = new LDAPEntry(dn, attrs);
try {
conn.add(entry);
- }
- catch (LDAPException e) {
+ } catch (LDAPException e) {
if (e.getLDAPResultCode() != 68) {
- System.out.println("Unable to create entry " + dn +": "+ e.toString());
+ System.out.println("Unable to create entry " + dn + ": " + e.toString());
}
}
}
diff --git a/pki/base/ocsp/src/com/netscape/ocsp/EOCSPException.java b/pki/base/ocsp/src/com/netscape/ocsp/EOCSPException.java
index 4b06a1aa..231ab286 100644
--- a/pki/base/ocsp/src/com/netscape/ocsp/EOCSPException.java
+++ b/pki/base/ocsp/src/com/netscape/ocsp/EOCSPException.java
@@ -17,14 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.ocsp;
-
import com.netscape.certsrv.base.EBaseException;
-
/**
* A class represents a OCSP exception.
* <P>
- *
+ *
* @version $Revision$, $Date$
*/
public class EOCSPException extends EBaseException {
diff --git a/pki/base/ocsp/src/com/netscape/ocsp/OCSPAuthority.java b/pki/base/ocsp/src/com/netscape/ocsp/OCSPAuthority.java
index c8b53142..0e1375d3 100644
--- a/pki/base/ocsp/src/com/netscape/ocsp/OCSPAuthority.java
+++ b/pki/base/ocsp/src/com/netscape/ocsp/OCSPAuthority.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.ocsp;
-
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.MessageDigest;
@@ -67,12 +66,11 @@ import com.netscape.cmsutil.ocsp.OCSPResponse;
import com.netscape.cmsutil.ocsp.ResponderID;
import com.netscape.cmsutil.ocsp.ResponseData;
-
/**
- * A class represents a Certificate Authority that is
- * responsible for certificate specific operations.
+ * A class represents a Certificate Authority that is responsible for
+ * certificate specific operations.
* <P>
- *
+ *
* @author lhsiao
* @version $Revision$, $Date$
*/
@@ -91,7 +89,7 @@ public class OCSPAuthority implements IOCSPAuthority, IOCSPService, ISubsystem,
private X509CertImpl mCert = null;
private String[] mSigningAlgorithms = null;
private X500Name mName = null;
- private String mNickname = null;
+ private String mNickname = null;
private String[] mOCSPSigningAlgorithms = null;
private IOCSPStore mDefStore = null;
@@ -106,7 +104,7 @@ public class OCSPAuthority implements IOCSPAuthority, IOCSPService, ISubsystem,
/**
* Retrieves the name of this subsystem.
*/
- public String getId() {
+ public String getId() {
return mId;
}
@@ -118,16 +116,15 @@ public class OCSPAuthority implements IOCSPAuthority, IOCSPService, ISubsystem,
}
/**
- * Initializes this subsystem with the given configuration
- * store.
+ * Initializes this subsystem with the given configuration store.
* <P>
- *
+ *
* @param owner owner of this subsystem
* @param config configuration store
* @exception EBaseException failed to initialize
*/
- public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
+ public void init(ISubsystem owner, IConfigStore config)
+ throws EBaseException {
try {
mConfig = config;
@@ -207,18 +204,18 @@ public class OCSPAuthority implements IOCSPAuthority, IOCSPService, ISubsystem,
public ResponderID getResponderIDByHash() {
/*
- KeyHash ::= OCTET STRING --SHA-1 hash of responder's public key
- --(excluding the tag and length fields)
+ * KeyHash ::= OCTET STRING --SHA-1 hash of responder's public key
+ * --(excluding the tag and length fields)
*/
- PublicKey publicKey = getSigningUnit().getPublicKey();
+ PublicKey publicKey = getSigningUnit().getPublicKey();
MessageDigest md = null;
try {
- md = MessageDigest.getInstance("SHA1");
+ md = MessageDigest.getInstance("SHA1");
} catch (NoSuchAlgorithmException e) {
return null;
}
- md.update(publicKey.getEncoded());
+ md.update(publicKey.getEncoded());
byte digested[] = md.digest();
return new KeyHashID(new OCTET_STRING(digested));
@@ -239,47 +236,47 @@ public class OCSPAuthority implements IOCSPAuthority, IOCSPService, ISubsystem,
X509Key caPubKey = null;
try {
- caPubKey = (X509Key) mCert.get(X509CertImpl.PUBLIC_KEY);
+ caPubKey = (X509Key) mCert.get(X509CertImpl.PUBLIC_KEY);
} catch (CertificateParsingException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_OCSP_RETRIEVE_KEY", e.toString()));
}
if (caPubKey == null) {
- return null; // something seriously wrong.
+ return null; // something seriously wrong.
}
AlgorithmId alg = caPubKey.getAlgorithmId();
if (alg == null) {
- return null; // something seriously wrong.
+ return null; // something seriously wrong.
}
mOCSPSigningAlgorithms = AlgorithmId.getSigningAlgorithms(alg);
if (mOCSPSigningAlgorithms == null) {
CMS.debug(
- "OCSP - no signing algorithms for " + alg.getName());
+ "OCSP - no signing algorithms for " + alg.getName());
} else {
CMS.debug("OCSP First signing algorithm ");
}
return mOCSPSigningAlgorithms;
}
- public static final OBJECT_IDENTIFIER MD2 =
- new OBJECT_IDENTIFIER("1.2.840.113549.2.2");
- public static final OBJECT_IDENTIFIER MD5 =
- new OBJECT_IDENTIFIER("1.2.840.113549.2.5");
- public static final OBJECT_IDENTIFIER SHA1 =
- new OBJECT_IDENTIFIER("1.3.14.3.2.26");
+ public static final OBJECT_IDENTIFIER MD2 =
+ new OBJECT_IDENTIFIER("1.2.840.113549.2.2");
+ public static final OBJECT_IDENTIFIER MD5 =
+ new OBJECT_IDENTIFIER("1.2.840.113549.2.5");
+ public static final OBJECT_IDENTIFIER SHA1 =
+ new OBJECT_IDENTIFIER("1.3.14.3.2.26");
- public String getDigestName(AlgorithmIdentifier alg) {
- if (alg == null) {
- return null;
- } else if (alg.getOID().equals(MD2)) {
- return "MD2";
- } else if (alg.getOID().equals(MD5)) {
- return "MD5";
- } else if (alg.getOID().equals(SHA1)) {
- return "SHA1"; // 1.3.14.3.2.26
- } else {
- return null;
- }
+ public String getDigestName(AlgorithmIdentifier alg) {
+ if (alg == null) {
+ return null;
+ } else if (alg.getOID().equals(MD2)) {
+ return "MD2";
+ } else if (alg.getOID().equals(MD5)) {
+ return "MD5";
+ } else if (alg.getOID().equals(SHA1)) {
+ return "SHA1"; // 1.3.14.3.2.26
+ } else {
+ return null;
+ }
}
/**
@@ -303,11 +300,11 @@ public class OCSPAuthority implements IOCSPAuthority, IOCSPService, ISubsystem,
// init cert chain
CryptoManager manager = CryptoManager.getInstance();
org.mozilla.jss.crypto.X509Certificate[] chain =
- manager.buildCertificateChain(mSigningUnit.getCert());
+ manager.buildCertificateChain(mSigningUnit.getCert());
// XXX do this in case other subsyss expect a X509CertImpl
// until JSS implements all methods of X509Certificate
java.security.cert.X509Certificate[] implchain =
- new java.security.cert.X509Certificate[chain.length];
+ new java.security.cert.X509Certificate[chain.length];
for (int i = 0; i < chain.length; i++) {
implchain[i] = new X509CertImpl(chain[i].getEncoded());
@@ -325,17 +322,17 @@ public class OCSPAuthority implements IOCSPAuthority, IOCSPService, ISubsystem,
} catch (CryptoManager.NotInitializedException e) {
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_OCSP_SIGNING", e.toString()));
+ CMS.getLogMessage("CMSCORE_OCSP_SIGNING", e.toString()));
} catch (CertificateException e) {
if (Debug.ON)
e.printStackTrace();
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_OCSP_CHAIN", e.toString()));
+ CMS.getLogMessage("CMSCORE_OCSP_CHAIN", e.toString()));
} catch (TokenException e) {
if (Debug.ON)
e.printStackTrace();
log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_OCSP_CHAIN", e.toString()));
+ CMS.getLogMessage("CMSCORE_OCSP_CHAIN", e.toString()));
}
}
@@ -358,8 +355,8 @@ public class OCSPAuthority implements IOCSPAuthority, IOCSPService, ISubsystem,
/**
* Process OCSPRequest.
*/
- public OCSPResponse validate(OCSPRequest request)
- throws EBaseException {
+ public OCSPResponse validate(OCSPRequest request)
+ throws EBaseException {
long startTime = (CMS.getCurrentDate()).getTime();
OCSPResponse response = mDefStore.validate(request);
long endTime = (CMS.getCurrentDate()).getTime();
@@ -387,8 +384,8 @@ public class OCSPAuthority implements IOCSPAuthority, IOCSPService, ISubsystem,
}
/**
- * Stops this system. The owner may call shutdown
- * anytime after initialization.
+ * Stops this system. The owner may call shutdown anytime after
+ * initialization.
* <P>
*/
public void shutdown() {
@@ -397,7 +394,7 @@ public class OCSPAuthority implements IOCSPAuthority, IOCSPService, ISubsystem,
/**
* Returns the root configuration storage of this system.
* <P>
- *
+ *
* @return configuration store of this subsystem
*/
public IConfigStore getConfigStore() {
@@ -410,21 +407,22 @@ public class OCSPAuthority implements IOCSPAuthority, IOCSPService, ISubsystem,
/**
* logs a message in the CA area.
+ *
* @param level the debug level.
* @param msg the message to debug.
*/
public void log(int event, int level, String msg) {
mLogger.log(event, ILogger.S_OCSP,
- level, msg);
+ level, msg);
}
public void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OCSP,
- level, msg);
+ level, msg);
}
- public void setDefaultAlgorithm(String algorithm)
- throws EBaseException {
+ public void setDefaultAlgorithm(String algorithm)
+ throws EBaseException {
mSigningUnit.setDefaultAlgorithm(algorithm);
}
@@ -432,16 +430,16 @@ public class OCSPAuthority implements IOCSPAuthority, IOCSPService, ISubsystem,
* Signs the Response Data.
*/
public BasicOCSPResponse sign(ResponseData rd)
- throws EBaseException {
+ throws EBaseException {
try {
DerOutputStream out = new DerOutputStream();
DerOutputStream tmp = new DerOutputStream();
- String algname = mSigningUnit.getDefaultAlgorithm();
+ String algname = mSigningUnit.getDefaultAlgorithm();
byte rd_data[] = ASN1Util.encode(rd);
if (rd_data != null) {
- mTotalData += rd_data.length;
+ mTotalData += rd_data.length;
}
rd.encode(tmp);
AlgorithmId.get(algname).encode(tmp);
@@ -451,23 +449,22 @@ public class OCSPAuthority implements IOCSPAuthority, IOCSPService, ISubsystem,
tmp.putBitString(signature);
// XXX - optional, put the certificate chains in also
-
DerOutputStream tmpChain = new DerOutputStream();
DerOutputStream tmp1 = new DerOutputStream();
DerOutputStream outChain = new DerOutputStream();
java.security.cert.X509Certificate chains[] =
- mCertChain.getChain();
+ mCertChain.getChain();
for (int i = 0; i < chains.length; i++) {
tmpChain.putDerValue(new DerValue(chains[i].getEncoded()));
}
tmp1.write(DerValue.tag_Sequence, tmpChain);
tmp.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0),
- tmp1);
+ tmp1);
out.write(DerValue.tag_Sequence, tmp);
-
- BasicOCSPResponse response = new BasicOCSPResponse(out.toByteArray());
+
+ BasicOCSPResponse response = new BasicOCSPResponse(out.toByteArray());
return response;
} catch (Exception e) {
@@ -482,7 +479,7 @@ public class OCSPAuthority implements IOCSPAuthority, IOCSPService, ISubsystem,
/**
* Returns default signing unit used by this CA
* <P>
- *
+ *
* @return request identifier
*/
public ISigningUnit getSigningUnit() {
@@ -492,6 +489,7 @@ public class OCSPAuthority implements IOCSPAuthority, IOCSPService, ISubsystem,
/**
* Retrieves the request queue for the Authority.
* <P>
+ *
* @return the request queue.
*/
public IRequestQueue getRequestQueue() {
@@ -541,115 +539,90 @@ public class OCSPAuthority implements IOCSPAuthority, IOCSPService, ISubsystem,
*/
/**
- public OCSPResponse processOCSPRequest(OCSPRequest req, OCSPReqProcessor p)
- throws EBaseException
- {
- try {
- log(ILogger.LL_INFO, "start OCSP request");
- TBSRequest tbsReq = request.getTBSRequest();
-
- Vector singleResponses = new Vector();
- for (int i = 0; i < tbsReq.getRequestCount(); i++)
- {
- com.netscape.certsrv.ocsp.asn1.Request req =
- tbsReq.getRequestAt(i);
- CertID cid = req.getCertID();
- SingleResponse sr = p.process(cid);
- singleResponses.addElement(sr);
- }
-
-
- SingleResponse res[] = new SingleResponse[singleResponses.size()];
- singleResponses.copyInto(res);
-
- X500Name name = getName();
- Name.Template nameTemplate = new Name.Template();
- NameID rid = new NameID((Name)nameTemplate.decode(
- new ByteArrayInputStream(name.getEncoded())));
- ResponseData rd = new ResponseData(rid, new GeneralizedTime(
- CMS.getCurrentDate()), res);
-
- BasicOCSPResponse basicRes = sign(rd);
-
- OCSPResponse response = new OCSPResponse(
- OCSPResponseStatus.SUCCESSFUL,
- new ResponseBytes(ResponseBytes.OCSP_BASIC,
- new OCTET_STRING(ASN1Util.encode(basicRes))));
-
- log(ILogger.LL_INFO, "done OCSP request");
- return response;
- } catch (Exception e) {
- log(ILogger.LL_FAILURE, "request processing failure " + e);
- return null;
- }
- }
+ * public OCSPResponse processOCSPRequest(OCSPRequest req, OCSPReqProcessor
+ * p) throws EBaseException { try { log(ILogger.LL_INFO,
+ * "start OCSP request"); TBSRequest tbsReq = request.getTBSRequest();
+ *
+ * Vector singleResponses = new Vector(); for (int i = 0; i <
+ * tbsReq.getRequestCount(); i++) { com.netscape.certsrv.ocsp.asn1.Request
+ * req = tbsReq.getRequestAt(i); CertID cid = req.getCertID();
+ * SingleResponse sr = p.process(cid); singleResponses.addElement(sr); }
+ *
+ *
+ * SingleResponse res[] = new SingleResponse[singleResponses.size()];
+ * singleResponses.copyInto(res);
+ *
+ * X500Name name = getName(); Name.Template nameTemplate = new
+ * Name.Template(); NameID rid = new NameID((Name)nameTemplate.decode( new
+ * ByteArrayInputStream(name.getEncoded()))); ResponseData rd = new
+ * ResponseData(rid, new GeneralizedTime( CMS.getCurrentDate()), res);
+ *
+ * BasicOCSPResponse basicRes = sign(rd);
+ *
+ * OCSPResponse response = new OCSPResponse( OCSPResponseStatus.SUCCESSFUL,
+ * new ResponseBytes(ResponseBytes.OCSP_BASIC, new
+ * OCTET_STRING(ASN1Util.encode(basicRes))));
+ *
+ * log(ILogger.LL_INFO, "done OCSP request"); return response; } catch
+ * (Exception e) { log(ILogger.LL_FAILURE, "request processing failure " +
+ * e); return null; } }
**/
/**
* Returns the in-memory count of the processed OCSP requests.
- *
+ *
* @return number of processed OCSP requests in memory
*/
- public long getNumOCSPRequest()
- {
+ public long getNumOCSPRequest() {
return mNumOCSPRequest;
}
/**
- * Returns the in-memory time (in mini-second) of
- * the processed time for OCSP requests.
- *
+ * Returns the in-memory time (in mini-second) of the processed time for
+ * OCSP requests.
+ *
* @return processed times for OCSP requests
*/
- public long getOCSPRequestTotalTime()
- {
- return mTotalTime;
+ public long getOCSPRequestTotalTime() {
+ return mTotalTime;
}
/**
- * Returns the in-memory time (in mini-second) of
- * the signing time for OCSP requests.
- *
+ * Returns the in-memory time (in mini-second) of the signing time for OCSP
+ * requests.
+ *
* @return processed times for OCSP requests
*/
- public long getOCSPTotalSignTime()
- {
- return mSignTime;
+ public long getOCSPTotalSignTime() {
+ return mSignTime;
}
- public long getOCSPTotalLookupTime()
- {
- return mLookupTime;
+ public long getOCSPTotalLookupTime() {
+ return mLookupTime;
}
/**
- * Returns the total data signed
- * for OCSP requests.
- *
+ * Returns the total data signed for OCSP requests.
+ *
* @return processed times for OCSP requests
*/
- public long getOCSPTotalData()
- {
- return mTotalData;
+ public long getOCSPTotalData() {
+ return mTotalData;
}
- public void incTotalTime(long inc)
- {
+ public void incTotalTime(long inc) {
mTotalTime += inc;
}
- public void incSignTime(long inc)
- {
+ public void incSignTime(long inc) {
mSignTime += inc;
- }
+ }
- public void incLookupTime(long inc)
- {
+ public void incLookupTime(long inc) {
mLookupTime += inc;
- }
+ }
- public void incNumOCSPRequest(long inc)
- {
+ public void incNumOCSPRequest(long inc) {
mNumOCSPRequest += inc;
}
}
diff --git a/pki/base/ocsp/src/com/netscape/ocsp/OCSPResources.java b/pki/base/ocsp/src/com/netscape/ocsp/OCSPResources.java
index 6c9032f1..5c3439c6 100644
--- a/pki/base/ocsp/src/com/netscape/ocsp/OCSPResources.java
+++ b/pki/base/ocsp/src/com/netscape/ocsp/OCSPResources.java
@@ -17,14 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.ocsp;
-
import java.util.ListResourceBundle;
-
/**
* A class represents a resource bundle for OCSP subsystem.
* <P>
- *
+ *
* @version $Revision$ $Date$
*/
public class OCSPResources extends ListResourceBundle {
@@ -37,8 +35,7 @@ public class OCSPResources extends ListResourceBundle {
}
/**
- * Constants. The suffix represents the number of
- * possible parameters.
+ * Constants. The suffix represents the number of possible parameters.
*/
static final Object[][] contents = {};
}
diff --git a/pki/base/ocsp/src/com/netscape/ocsp/SigningUnit.java b/pki/base/ocsp/src/com/netscape/ocsp/SigningUnit.java
index d1447de2..83b48096 100644
--- a/pki/base/ocsp/src/com/netscape/ocsp/SigningUnit.java
+++ b/pki/base/ocsp/src/com/netscape/ocsp/SigningUnit.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.ocsp;
-
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
@@ -51,7 +50,7 @@ import com.netscape.cmsutil.util.Cert;
/**
* OCSP signing unit based on JSS.
- *
+ *
* $Revision$ $Date$
*/
@@ -76,8 +75,8 @@ public final class SigningUnit implements ISigningUnit {
private ISubsystem mOwner = null;
- private String mDefSigningAlgname = null;
- private SignatureAlgorithm mDefSigningAlgorithm = null;
+ private String mDefSigningAlgname = null;
+ private SignatureAlgorithm mDefSigningAlgorithm = null;
public SigningUnit() {
}
@@ -124,8 +123,8 @@ public final class SigningUnit implements ISigningUnit {
}
public void init(ISubsystem owner, IConfigStore config)
- throws EBaseException {
- mOwner = owner;
+ throws EBaseException {
+ mOwner = owner;
mConfig = config;
String tokenname = null;
@@ -139,7 +138,7 @@ public final class SigningUnit implements ISigningUnit {
tokenname = config.getString(PROP_TOKEN_NAME);
if (tokenname.equalsIgnoreCase(Constants.PR_INTERNAL_TOKEN) ||
- tokenname.equalsIgnoreCase("Internal Key Storage Token")) {
+ tokenname.equalsIgnoreCase("Internal Key Storage Token")) {
mToken = mManager.getInternalKeyStorageToken();
} else {
mToken = mManager.getTokenByName(tokenname);
@@ -149,12 +148,12 @@ public final class SigningUnit implements ISigningUnit {
CMS.debug(config.getName() + " Signing Unit nickname " + mNickname);
CMS.debug("Got token " + tokenname + " by name");
- PasswordCallback cb = JssSubsystem.getInstance().getPWCB();
+ PasswordCallback cb = JssSubsystem.getInstance().getPWCB();
mToken.login(cb); // ONE_TIME by default.
mCert = mManager.findCertByNickname(mNickname);
- CMS.debug("Found cert by nickname: '"+mNickname+"' with serial number: "+mCert.getSerialNumber());
+ CMS.debug("Found cert by nickname: '" + mNickname + "' with serial number: " + mCert.getSerialNumber());
mCertImpl = new X509CertImpl(mCert.getEncoded());
CMS.debug("converted to x509CertImpl");
@@ -167,22 +166,22 @@ public final class SigningUnit implements ISigningUnit {
// get def alg and check if def sign alg is valid for token.
mDefSigningAlgname = config.getString(PROP_DEFAULT_SIGNALG);
- mDefSigningAlgorithm =
+ mDefSigningAlgorithm =
checkSigningAlgorithmFromName(mDefSigningAlgname);
CMS.debug(
- "got signing algorithm " + mDefSigningAlgorithm);
+ "got signing algorithm " + mDefSigningAlgorithm);
mInited = true;
} catch (java.security.cert.CertificateException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_OCSP_CONVERT_X509", e.getMessage()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_OCSP_CONVERT_X509", e.getMessage()));
throw new EOCSPException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR", e.toString()));
} catch (CryptoManager.NotInitializedException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_OCSP_SIGNING", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_OCSP_SIGNING", e.toString()));
throw new EOCSPException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR", e.toString()));
} catch (IncorrectPasswordException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_OCSP_INCORRECT_PWD", e.toString()));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_OCSP_INCORRECT_PWD", e.toString()));
throw new EOCSPException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR", e.toString()));
} catch (NoSuchTokenException e) {
log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_OCSP_TOKEN_NOT_FOUND", tokenname, e.toString()));
@@ -206,14 +205,14 @@ public final class SigningUnit implements ISigningUnit {
* @exception EBaseException if signing algorithm is not supported.
*/
public SignatureAlgorithm checkSigningAlgorithmFromName(String algname)
- throws EBaseException {
+ throws EBaseException {
try {
SignatureAlgorithm sigalg = null;
sigalg = mapAlgorithmToJss(algname);
if (sigalg == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_OCSP_SIGN_ALG_NOT_SUPPORTED", algname));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_OCSP_SIGN_ALG_NOT_SUPPORTED", algname));
throw new EOCSPException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR", ""));
}
Signature signer = mToken.getSignatureContext(sigalg);
@@ -221,17 +220,17 @@ public final class SigningUnit implements ISigningUnit {
signer.initSign(mPrivk);
return sigalg;
} catch (NoSuchAlgorithmException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_OCSP_SIGN_ALG_NOT_SUPPORTED", algname));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_OCSP_SIGN_ALG_NOT_SUPPORTED", algname));
throw new EOCSPException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR", e.toString()));
} catch (TokenException e) {
// from get signature context or from initSign
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_OCSP_SIGN_ALG_NOT_SUPPORTED", algname));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_OCSP_SIGN_ALG_NOT_SUPPORTED", algname));
throw new EOCSPException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR", e.toString()));
} catch (InvalidKeyException e) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_OCSP_SIGN_ALG_NOT_SUPPORTED", algname));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_OCSP_SIGN_ALG_NOT_SUPPORTED", algname));
throw new EOCSPException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR", e.toString()));
}
}
@@ -240,7 +239,7 @@ public final class SigningUnit implements ISigningUnit {
* @param algname is expected to be one of JCA's algorithm names.
*/
public byte[] sign(byte[] data, String algname)
- throws EBaseException {
+ throws EBaseException {
if (!mInited) {
throw new EBaseException("OCSPSigningUnit not initialized!");
}
@@ -253,10 +252,10 @@ public final class SigningUnit implements ISigningUnit {
signAlg = checkSigningAlgorithmFromName(algname);
}
- // XXX use a pool of signers based on alg ?
+ // XXX use a pool of signers based on alg ?
// XXX Map algor. name to id. hack: use hardcoded define for now.
CMS.debug(
- "Getting algorithm context for " + algname + " " + signAlg);
+ "Getting algorithm context for " + algname + " " + signAlg);
Signature signer = mToken.getSignatureContext(signAlg);
signer.initSign(mPrivk);
@@ -280,7 +279,7 @@ public final class SigningUnit implements ISigningUnit {
}
public boolean verify(byte[] data, byte[] signature, String algname)
- throws EBaseException {
+ throws EBaseException {
if (!mInited) {
throw new EBaseException("OCSPSigningUnit not initialized!");
}
@@ -288,8 +287,8 @@ public final class SigningUnit implements ISigningUnit {
SignatureAlgorithm signAlg = mapAlgorithmToJss(algname);
if (signAlg == null) {
- log(ILogger.LL_FAILURE,
- CMS.getLogMessage("CMSCORE_OCSP_SIGN_ALG_NOT_SUPPORTED", algname));
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSCORE_OCSP_SIGN_ALG_NOT_SUPPORTED", algname));
throw new EOCSPException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR", ""));
}
// XXX make this configurable. hack: use hardcoded for now.
@@ -317,8 +316,8 @@ public final class SigningUnit implements ISigningUnit {
private void log(int level, String msg) {
if (mLogger == null)
return;
- mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_OCSP,
- level, "OCSPSigningUnit: " + msg);
+ mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_OCSP,
+ level, "OCSPSigningUnit: " + msg);
}
/**
@@ -336,15 +335,15 @@ public final class SigningUnit implements ISigningUnit {
}
public void setDefaultAlgorithm(String algorithm) throws EBaseException {
- mConfig.putString(PROP_DEFAULT_SIGNALG, algorithm);
+ mConfig.putString(PROP_DEFAULT_SIGNALG, algorithm);
mDefSigningAlgname = algorithm;
- log(ILogger.LL_INFO,
- "Default signing algorithm is set to " + algorithm);
+ log(ILogger.LL_INFO,
+ "Default signing algorithm is set to " + algorithm);
}
/**
* get all possible algorithms for the OCSP signing key type.
- */
+ */
public String[] getAllAlgorithms() throws EBaseException {
byte[] keybytes = mPubk.getEncoded();
X509Key key = new X509Key();
@@ -369,4 +368,3 @@ public final class SigningUnit implements ISigningUnit {
return Cert.mapAlgorithmToJss(algname);
}
}
-
diff --git a/pki/base/silent/src/com/netscape/pkisilent/ConfigureCA.java b/pki/base/silent/src/com/netscape/pkisilent/ConfigureCA.java
index 337bf927..285b61b8 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/ConfigureCA.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/ConfigureCA.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -17,7 +18,6 @@ package com.netscape.pkisilent;
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
-
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
@@ -41,10 +41,8 @@ import com.netscape.pkisilent.common.ParseXML;
import com.netscape.pkisilent.http.HTTPClient;
import com.netscape.pkisilent.http.HTTPResponse;
-
public class ConfigureCA {
-
// global constants
public static final String DEFAULT_KEY_TYPE = "RSA";
public static final String DEFAULT_KEY_SIZE = "2048";
@@ -57,7 +55,7 @@ public class ConfigureCA {
// define global variables
public static HTTPClient hc = null;
-
+
public static String login_uri = "/ca/admin/console/config/login";
public static String wizard_uri = "/ca/admin/console/config/wizard";
public static String admin_uri = "/ca/admin/ca/getBySerial";
@@ -77,7 +75,7 @@ public class ConfigureCA {
public static String sd_admin_name = null;
public static String sd_admin_password = null;
- // Login Panel
+ // Login Panel
public static String pin = null;
public static String domain_name = null;
@@ -162,7 +160,7 @@ public class ConfigureCA {
public static String ca_audit_signing_cert_pp = null;
public static String ca_audit_signing_cert_cert = null;
- // names
+ // names
public static String ca_sign_cert_subject_name = null;
public static String ca_subsystem_cert_subject_name = null;
public static String ca_ocsp_cert_subject_name = null;
@@ -171,7 +169,7 @@ public class ConfigureCA {
public static String subsystem_name = null;
- public static String external_ca= null;
+ public static String external_ca = null;
public static String ext_ca_cert_file = null;
public static String ext_ca_cert_chain_file = null;
public static String ext_csr_file = null;
@@ -182,10 +180,9 @@ public class ConfigureCA {
public static String clone_p12_passwd = null;
public static String clone_p12_file = null;
- //for correct selection of CA to be cloned
+ // for correct selection of CA to be cloned
public static String urls;
-
public ConfigureCA() {// do nothing :)
}
@@ -206,34 +203,33 @@ public class ConfigureCA {
public boolean checkStatus(HTTPResponse hr, String name,
String expected, String location) {
- return checkStatus(hr,name, new String[] {expected}, location);
- }
+ return checkStatus(hr, name, new String[] { expected }, location);
+ }
- public boolean checkStatus(HTTPResponse hr, String name,
+ public boolean checkStatus(HTTPResponse hr, String name,
String[] expected, String location) {
String status = getStatus(hr, name);
if (status == null) {
- System.out.println("Error in " + location + ": " + name +
+ System.out.println("Error in " + location + ": " + name +
" value is null");
return false;
- }
- for (int i=0; i< expected.length; i++) {
+ }
+ for (int i = 0; i < expected.length; i++) {
if (status.equals(expected[i])) {
return true;
}
}
- System.out.println("Error in " + location + ": " + name +
+ System.out.println("Error in " + location + ": " + name +
" returns " + status);
return false;
- }
-
+ }
public boolean LoginPanel() {
try {
boolean st = false;
HTTPResponse hr = null;
- String query_string = "pin=" + pin + "&xml=true";
+ String query_string = "pin=" + pin + "&xml=true";
hr = hc.sslConnect(cs_hostname, cs_port, login_uri, query_string);
System.out.println("xml returned: " + hr.getHTML());
@@ -250,8 +246,8 @@ public class ConfigureCA {
hr = null;
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
- "p=0&op=next&xml=true");
- if (! checkStatus(hr, "status", "display", "LoginPanel()")) {
+ "p=0&op=next&xml=true");
+ if (!checkStatus(hr, "status", "display", "LoginPanel()")) {
return false;
}
@@ -272,27 +268,27 @@ public class ConfigureCA {
// Software Token
if (token_name.equalsIgnoreCase("internal")) {
query_string = "p=1" + "&op=next" + "&xml=true" + "&choice="
- + URLEncoder.encode("Internal Key Storage Token") + "";
+ + URLEncoder.encode("Internal Key Storage Token") + "";
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- if (! checkStatus(hr, "updateStatus", SUCCESS, "TokenChoicePanel()")) {
+ if (!checkStatus(hr, "updateStatus", SUCCESS, "TokenChoicePanel()")) {
return false;
}
} // HSM
else {
// login to hsm first
query_string = "p=2" + "&op=next" + "&xml=true" + "&uTokName="
- + URLEncoder.encode(token_name) + "&__uPasswd="
- + URLEncoder.encode(token_pwd) + "";
+ + URLEncoder.encode(token_name) + "&__uPasswd="
+ + URLEncoder.encode(token_pwd) + "";
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- if (! checkStatus(hr, "updateStatus", SUCCESS, "TokenChoicePanel()")) {
+ if (!checkStatus(hr, "updateStatus", SUCCESS, "TokenChoicePanel()")) {
return false;
}
-
+
// choice with token name now
query_string = "p=1" + "&op=next" + "&xml=true" + "&choice="
- + URLEncoder.encode(token_name) + "";
+ + URLEncoder.encode(token_name) + "";
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- if (! checkStatus(hr, "updateStatus", SUCCESS, "TokenChoicePanel()")) {
+ if (!checkStatus(hr, "updateStatus", SUCCESS, "TokenChoicePanel()")) {
return false;
}
}
@@ -310,19 +306,19 @@ public class ConfigureCA {
String domain_url = "https://" + cs_hostname + ":" + cs_port;
String query_string = null;
- if (! clone) {
+ if (!clone) {
query_string = "sdomainURL=" + URLEncoder.encode(domain_url)
- + "&sdomainName=" + URLEncoder.encode(domain_name)
- + "&choice=newdomain" + "&p=3" + "&op=next" + "&xml=true";
+ + "&sdomainName=" + URLEncoder.encode(domain_name)
+ + "&choice=newdomain" + "&p=3" + "&op=next" + "&xml=true";
} else {
- domain_url = "https://" + sd_hostname + ":" + sd_admin_port ;
+ domain_url = "https://" + sd_hostname + ":" + sd_admin_port;
query_string = "sdomainURL=" + URLEncoder.encode(domain_url)
- + "&sdomainName="
- + "&choice=existingdomain" + "&p=3" + "&op=next" + "&xml=true";
+ + "&sdomainName="
+ + "&choice=existingdomain" + "&p=3" + "&op=next" + "&xml=true";
}
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- if (! checkStatus(hr, "updateStatus", SUCCESS, "DomainPanel()")) {
+ if (!checkStatus(hr, "updateStatus", SUCCESS, "DomainPanel()")) {
return false;
}
@@ -338,7 +334,7 @@ public class ConfigureCA {
try {
HTTPResponse hr = null;
String query_string = "p=4" + "&op=next" + "&xml=true";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
return true;
} catch (Exception e) {
System.out.println("Exception in DisplayCertChainPanel(): " + e.toString());
@@ -353,42 +349,42 @@ public class ConfigureCA {
HTTPResponse hr = null;
String subca_url = "https://" + cs_hostname + ":" + cs_port +
- "/ca/admin/console/config/wizard" + "?p=5&subsystem=CA" ;
+ "/ca/admin/console/config/wizard" + "?p=5&subsystem=CA";
String query_string = "url=" + URLEncoder.encode(subca_url);
- hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_login_uri,query_string);
+ hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_login_uri, query_string);
String query_string_1 = "uid=" + sd_admin_name + "&pwd=" + URLEncoder.encode(sd_admin_password) +
- "&url=" + URLEncoder.encode(subca_url) ;
+ "&url=" + URLEncoder.encode(subca_url);
- hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_get_cookie_uri,
+ hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_get_cookie_uri,
query_string_1);
// get session id from security domain
-
+
String subca_session_id = hr.getContentValue("header.session_id");
String subca_url_1 = hr.getContentValue("header.url");
-
- System.out.println("SUBCA_SESSION_ID=" + subca_session_id );
- System.out.println("SUBCA_URL=" + subca_url_1 );
+
+ System.out.println("SUBCA_SESSION_ID=" + subca_session_id);
+ System.out.println("SUBCA_URL=" + subca_url_1);
// use session id to connect back to subCA
String query_string_2 = "p=5" + "&subsystem=CA" +
- "&session_id=" + subca_session_id + "&xml=true" ;
-
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri, query_string_2);
+ "&session_id=" + subca_session_id + "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string_2);
urls = hr.getHTML();
int indx = urls.indexOf(clone_uri);
if (indx < 0) {
throw new Exception("Invalid clone_uri");
}
- urls = urls.substring(urls.lastIndexOf("<option" , indx), indx);
+ urls = urls.substring(urls.lastIndexOf("<option", indx), indx);
urls = urls.split("\"")[1];
System.out.println("urls =" + urls);
- return true;
+ return true;
} catch (Exception e) {
System.out.println("Exception in SecurityDomainLoginPanel(): " + e.toString());
e.printStackTrace();
@@ -397,33 +393,33 @@ public class ConfigureCA {
}
public boolean CreateCAPanel() {
- try {
+ try {
boolean st = false;
HTTPResponse hr = null;
String query_string = null;
if (!clone) {
query_string = "p=5" + "&op=next" + "&xml=true"
- + "&choice=newsubsystem" + "&subsystemName="
- + URLEncoder.encode(subsystem_name);
+ + "&choice=newsubsystem" + "&subsystemName="
+ + URLEncoder.encode(subsystem_name);
} else {
query_string = "p=5" + "&op=next" + "&xml=true"
- + "&choice=clonesubsystem" + "&subsystemName="
- + URLEncoder.encode(subsystem_name)
- + "&urls=" + urls + "";
+ + "&choice=clonesubsystem" + "&subsystemName="
+ + URLEncoder.encode(subsystem_name)
+ + "&urls=" + urls + "";
}
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- if (! checkStatus(hr, "updateStatus", SUCCESS, "CreateCAPanel()")) {
+ if (!checkStatus(hr, "updateStatus", SUCCESS, "CreateCAPanel()")) {
return false;
}
if (clone) {
hr = null;
- query_string = "p=6" + "&op=next" + "&xml=true";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
- if (! checkStatus(hr, "updateStatus", SUCCESS, "CreateCAPanel(2)")) {
+ query_string = "p=6" + "&op=next" + "&xml=true";
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ if (!checkStatus(hr, "updateStatus", SUCCESS, "CreateCAPanel(2)")) {
return false;
}
}
@@ -440,12 +436,12 @@ public class ConfigureCA {
try {
HTTPResponse hr = null;
- String query_string = "p=7" + "&op=next" + "&xml=true"
- + "&__password=" + URLEncoder.encode(clone_p12_passwd)
- + "&path=" + URLEncoder.encode(clone_p12_file) + "";
+ String query_string = "p=7" + "&op=next" + "&xml=true"
+ + "&__password=" + URLEncoder.encode(clone_p12_passwd)
+ + "&path=" + URLEncoder.encode(clone_p12_file) + "";
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- if (! checkStatus(hr, "updateStatus", SUCCESS, "RestoreKeyCertPanel()")) {
+ if (!checkStatus(hr, "updateStatus", SUCCESS, "RestoreKeyCertPanel()")) {
return false;
}
return true;
@@ -455,21 +451,20 @@ public class ConfigureCA {
return false;
}
}
-
public boolean HierarchyPanel() {
- try {
+ try {
boolean st = false;
HTTPResponse hr = null;
- String query_string = "p=8" + "&op=next" + "&xml=true" ;
- if (external_ca.equalsIgnoreCase("true"))
+ String query_string = "p=8" + "&op=next" + "&xml=true";
+ if (external_ca.equalsIgnoreCase("true"))
query_string += "&choice=join";
else
- query_string += "&choice=root";
+ query_string += "&choice=root";
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- if (! checkStatus(hr, "updateStatus", SUCCESS, "HierarchyPanel()")) {
+ if (!checkStatus(hr, "updateStatus", SUCCESS, "HierarchyPanel()")) {
return false;
}
@@ -488,19 +483,19 @@ public class ConfigureCA {
HTTPResponse hr = null;
String query_string = "p=9" + "&op=next" + "&xml=true" + "&host="
- + URLEncoder.encode(ldap_host) + "&port="
- + URLEncoder.encode(ldap_port) + "&binddn="
- + URLEncoder.encode(bind_dn) + "&__bindpwd="
- + URLEncoder.encode(bind_password) + "&basedn="
- + URLEncoder.encode(base_dn) + "&database="
- + URLEncoder.encode(db_name) + "&display="
- + URLEncoder.encode("$displayStr")
- + (secure_conn.equals("true")? "&secureConn=on": "")
- + (clone_start_tls.equals("true")? "&cloneStartTLS=on": "")
- + (remove_data.equals("true")? "&removeData=true": "");
+ + URLEncoder.encode(ldap_host) + "&port="
+ + URLEncoder.encode(ldap_port) + "&binddn="
+ + URLEncoder.encode(bind_dn) + "&__bindpwd="
+ + URLEncoder.encode(bind_password) + "&basedn="
+ + URLEncoder.encode(base_dn) + "&database="
+ + URLEncoder.encode(db_name) + "&display="
+ + URLEncoder.encode("$displayStr")
+ + (secure_conn.equals("true") ? "&secureConn=on" : "")
+ + (clone_start_tls.equals("true") ? "&cloneStartTLS=on" : "")
+ + (remove_data.equals("true") ? "&removeData=true" : "");
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- if (! checkStatus(hr, "updateStatus", SUCCESS, "LdapConnectionPanel()")) {
+ if (!checkStatus(hr, "updateStatus", SUCCESS, "LdapConnectionPanel()")) {
return false;
}
@@ -521,48 +516,48 @@ public class ConfigureCA {
ArrayList<String> al = null;
String query_string = null;
if (clone) {
- query_string = "p=10" + "&op=next" + "&xml=true"
- + "&sslserver_custom_size=" + sslserver_key_size
- + "&sslserver_custom_curvename=" + sslserver_key_curvename
- + "&sslserver_choice=custom"
- + "&sslserver_keytype=" + sslserver_key_type
- + "&choice=custom" + "&keytype=" + key_type
- + "&custom_size=" + key_size;
+ query_string = "p=10" + "&op=next" + "&xml=true"
+ + "&sslserver_custom_size=" + sslserver_key_size
+ + "&sslserver_custom_curvename=" + sslserver_key_curvename
+ + "&sslserver_choice=custom"
+ + "&sslserver_keytype=" + sslserver_key_type
+ + "&choice=custom" + "&keytype=" + key_type
+ + "&custom_size=" + key_size;
} else {
query_string = "p=10" + "&op=next" + "&xml=true"
- + "&subsystem_custom_size=" + subsystem_key_size
- + "&subsystem_custom_curvename=" + subsystem_key_curvename
- + "&subsystem_keytype=" + subsystem_key_type
- + "&subsystem_choice=custom"
- + "&sslserver_custom_size=" + sslserver_key_size
- + "&sslserver_custom_curvename=" + sslserver_key_curvename
- + "&sslserver_keytype=" + sslserver_key_type
- + "&sslserver_choice=custom"
- + "&signing_custom_size=" + signing_key_size
- + "&signing_custom_curvename=" + signing_key_curvename
- + "&signing_keytype=" + signing_key_type
- + "&signing_choice=custom"
- + "&signing_keyalgorithm=" + key_algorithm
- + "&signing_signingalgorithm=" + signing_signingalgorithm
- + "&ocsp_signing_custom_size=" + ocsp_signing_key_size
- + "&ocsp_signing_custom_curvename=" + ocsp_signing_key_curvename
- + "&ocsp_signing_keytype=" + ocsp_signing_key_type
- + "&ocsp_signing_choice=custom"
- + "&ocsp_signing_signingalgorithm=" + ocsp_signing_signingalgorithm
- + "&audit_signing_custom_size=" + audit_signing_key_size
- + "&audit_signing_custom_curvename=" + audit_signing_key_curvename
- + "&audit_signing_keytype=" + audit_signing_key_type
- + "&audit_signing_choice=custom"
- + "&custom_size=" + key_size
- + "&custom_curvename=" + key_curvename
- + "&keytype=" + key_type
- + "&choice=custom"
- + "&signingalgorithm=" + signing_algorithm
- + "&keyalgorithm=" + key_algorithm;
+ + "&subsystem_custom_size=" + subsystem_key_size
+ + "&subsystem_custom_curvename=" + subsystem_key_curvename
+ + "&subsystem_keytype=" + subsystem_key_type
+ + "&subsystem_choice=custom"
+ + "&sslserver_custom_size=" + sslserver_key_size
+ + "&sslserver_custom_curvename=" + sslserver_key_curvename
+ + "&sslserver_keytype=" + sslserver_key_type
+ + "&sslserver_choice=custom"
+ + "&signing_custom_size=" + signing_key_size
+ + "&signing_custom_curvename=" + signing_key_curvename
+ + "&signing_keytype=" + signing_key_type
+ + "&signing_choice=custom"
+ + "&signing_keyalgorithm=" + key_algorithm
+ + "&signing_signingalgorithm=" + signing_signingalgorithm
+ + "&ocsp_signing_custom_size=" + ocsp_signing_key_size
+ + "&ocsp_signing_custom_curvename=" + ocsp_signing_key_curvename
+ + "&ocsp_signing_keytype=" + ocsp_signing_key_type
+ + "&ocsp_signing_choice=custom"
+ + "&ocsp_signing_signingalgorithm=" + ocsp_signing_signingalgorithm
+ + "&audit_signing_custom_size=" + audit_signing_key_size
+ + "&audit_signing_custom_curvename=" + audit_signing_key_curvename
+ + "&audit_signing_keytype=" + audit_signing_key_type
+ + "&audit_signing_choice=custom"
+ + "&custom_size=" + key_size
+ + "&custom_curvename=" + key_curvename
+ + "&keytype=" + key_type
+ + "&choice=custom"
+ + "&signingalgorithm=" + signing_algorithm
+ + "&keyalgorithm=" + key_algorithm;
}
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- if (! checkStatus(hr, "updateStatus", SUCCESS, "KeyPanel()")) {
+ if (!checkStatus(hr, "updateStatus", SUCCESS, "KeyPanel()")) {
return false;
}
@@ -574,7 +569,7 @@ public class ConfigureCA {
// get ca cert subject name
if (al != null) {
for (int i = 0; i < al.size(); i++) {
- String temp = al.get(i);
+ String temp = al.get(i);
if (temp.indexOf("Certificate Authority") > 0) {
ca_cert_name = temp;
@@ -589,13 +584,13 @@ public class ConfigureCA {
}
}
}
-
+
System.out.println("default: ca_cert_name=" + ca_cert_name);
System.out.println("default: ocsp_cert_name=" + ocsp_cert_name);
System.out.println(
- "default: ca_subsystem_cert_name=" + ca_subsystem_cert_name);
+ "default: ca_subsystem_cert_name=" + ca_subsystem_cert_name);
System.out.println(
- "default: ca_audit_signing_cert_name=" + ca_audit_signing_cert_name);
+ "default: ca_audit_signing_cert_name=" + ca_audit_signing_cert_name);
System.out.println("default: server_cert_name=" + server_cert_name);
return true;
} catch (Exception e) {
@@ -620,27 +615,27 @@ public class ConfigureCA {
if (!clone) {
query_string = "p=11" + "&op=next" + "&xml=true" + "&subsystem="
- + URLEncoder.encode(ca_subsystem_cert_subject_name)
- + "&ocsp_signing="
- + URLEncoder.encode(ca_ocsp_cert_subject_name) + "&signing="
- + URLEncoder.encode(ca_sign_cert_subject_name) + "&sslserver="
- + URLEncoder.encode(ca_server_cert_subject_name) + "&audit_signing="
- + URLEncoder.encode(ca_audit_signing_cert_subject_name) + "&urls=0"
- + "";
+ + URLEncoder.encode(ca_subsystem_cert_subject_name)
+ + "&ocsp_signing="
+ + URLEncoder.encode(ca_ocsp_cert_subject_name) + "&signing="
+ + URLEncoder.encode(ca_sign_cert_subject_name) + "&sslserver="
+ + URLEncoder.encode(ca_server_cert_subject_name) + "&audit_signing="
+ + URLEncoder.encode(ca_audit_signing_cert_subject_name) + "&urls=0"
+ + "";
} else {
query_string = "p=11" + "&op=next" + "&xml=true" + "&sslserver="
- + URLEncoder.encode(ca_server_cert_subject_name) + "&urls=0"
- + "";
- }
+ + URLEncoder.encode(ca_server_cert_subject_name) + "&urls=0"
+ + "";
+ }
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- if (! checkStatus(hr, "updateStatus", SUCCESS, "CertSubjectPanel()")) {
+ if (!checkStatus(hr, "updateStatus", SUCCESS, "CertSubjectPanel()")) {
return false;
}
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
-
+
req_list = px.constructValueList("CertReqPair", "Request");
cert_list = px.constructValueList("CertReqPair", "Certificate");
dn_list = px.constructValueList("CertReqPair", "Nickname");
@@ -652,46 +647,44 @@ public class ConfigureCA {
if (external_ca.equalsIgnoreCase("true")) {
if ((req_list != null) && (dn_list != null)) {
for (int i = 0; i < dn_list.size(); i++) {
- String temp = dn_list.get(i);
+ String temp = dn_list.get(i);
if (temp.indexOf("caSigningCert") >= 0) {
- ca_cert_req = req_list.get(i);
+ ca_cert_req = req_list.get(i);
}
}
}
if (ext_ca_cert_file == null) {
- try {
+ try {
FileOutputStream fos = new FileOutputStream(ext_csr_file);
- PrintStream p = new PrintStream( fos );
+ PrintStream p = new PrintStream(fos);
p.println(ca_cert_req);
p.close();
return true;
} catch (Exception e) {
- System.out.println("CertSubjectPanel: Unable to write CSR for external CA to "+ ext_csr_file);
+ System.out.println("CertSubjectPanel: Unable to write CSR for external CA to " + ext_csr_file);
System.out.println(e.toString());
- return false;
- }
- }
- else {
- try {
+ return false;
+ }
+ } else {
+ try {
ca_cert_cert = "";
FileInputStream fis = new FileInputStream(ext_ca_cert_file);
DataInputStream in = new DataInputStream(fis);
- while (in.available() !=0) {
+ while (in.available() != 0) {
ca_cert_cert += in.readLine();
}
in.close();
-
+
signing_cc = "";
fis = new FileInputStream(ext_ca_cert_chain_file);
in = new DataInputStream(fis);
- while (in.available() !=0) {
+ while (in.available() != 0) {
signing_cc += in.readLine();
}
in.close();
return true;
- }
- catch (Exception e) {
+ } catch (Exception e) {
System.out.println("CertSubjectPanel: Unable to read in external approved CA cert or certificate chain.");
System.out.println(e.toString());
return false;
@@ -701,32 +694,32 @@ public class ConfigureCA {
if (req_list != null && cert_list != null && dn_list != null) {
for (int i = 0; i < dn_list.size(); i++) {
- String temp = dn_list.get(i);
-
+ String temp = dn_list.get(i);
+
if (temp.indexOf("caSigningCert") >= 0) {
- ca_cert_req = req_list.get(i);
- ca_cert_cert = cert_list.get(i);
+ ca_cert_req = req_list.get(i);
+ ca_cert_cert = cert_list.get(i);
} else if (temp.indexOf("ocspSigningCert") >= 0) {
- ocsp_cert_req = req_list.get(i);
- ocsp_cert_cert = cert_list.get(i);
+ ocsp_cert_req = req_list.get(i);
+ ocsp_cert_cert = cert_list.get(i);
} else if (temp.indexOf("subsystemCert") >= 0) {
- ca_subsystem_cert_req = req_list.get(i);
- ca_subsystem_cert_cert = cert_list.get(i);
- } else if (temp.indexOf("auditSigningCert") >=0) {
- ca_audit_signing_cert_req = req_list.get(i);
- ca_audit_signing_cert_cert = cert_list.get(i);
+ ca_subsystem_cert_req = req_list.get(i);
+ ca_subsystem_cert_cert = cert_list.get(i);
+ } else if (temp.indexOf("auditSigningCert") >= 0) {
+ ca_audit_signing_cert_req = req_list.get(i);
+ ca_audit_signing_cert_cert = cert_list.get(i);
} else {
- server_cert_req = req_list.get(i);
- server_cert_cert = cert_list.get(i);
+ server_cert_req = req_list.get(i);
+ server_cert_cert = cert_list.get(i);
}
}
}
-
- // print out subject names
+
+ // print out subject names
System.out.println("ca_cert_name=" + ca_sign_cert_subject_name);
System.out.println("ocsp_cert_name=" + ca_ocsp_cert_subject_name);
System.out.println(
- "ca_subsystem_cert_name=" + ca_subsystem_cert_subject_name);
+ "ca_subsystem_cert_name=" + ca_subsystem_cert_subject_name);
System.out.println("server_cert_name=" + ca_server_cert_subject_name);
System.out.println("audit_signing_cert_name=" + ca_audit_signing_cert_subject_name);
@@ -759,17 +752,17 @@ public class ConfigureCA {
HTTPResponse hr = null;
String query_string = "p=12" + "&op=next" + "&xml=true" + "&subsystem="
- + URLEncoder.encode(ca_subsystem_cert_cert) + "&subsystem_cc="
- + "&ocsp_signing=" + URLEncoder.encode(ocsp_cert_cert)
- + "&ocsp_signing_cc=" + "&signing="
- + URLEncoder.encode(ca_cert_cert) + "&signing_cc="
- + "&audit_signing=" + URLEncoder.encode(ca_audit_signing_cert_cert)
- + "&audit_signing_cc="
- + "&sslserver=" + URLEncoder.encode(server_cert_cert)
- + "&sslserver_cc=" + "";
+ + URLEncoder.encode(ca_subsystem_cert_cert) + "&subsystem_cc="
+ + "&ocsp_signing=" + URLEncoder.encode(ocsp_cert_cert)
+ + "&ocsp_signing_cc=" + "&signing="
+ + URLEncoder.encode(ca_cert_cert) + "&signing_cc="
+ + "&audit_signing=" + URLEncoder.encode(ca_audit_signing_cert_cert)
+ + "&audit_signing_cc="
+ + "&sslserver=" + URLEncoder.encode(server_cert_cert)
+ + "&sslserver_cc=" + "";
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- if (! checkStatus(hr, "updateStatus", SUCCESS, "CertificatePanel()")) {
+ if (!checkStatus(hr, "updateStatus", SUCCESS, "CertificatePanel()")) {
return false;
}
@@ -795,18 +788,18 @@ public class ConfigureCA {
String genString = "...certificate be generated internally...";
String query_string = "p=12" + "&op=apply" + "&xml=true" + "&subsystem="
- + URLEncoder.encode(genString) + "&subsystem_cc="
- + "&ocsp_signing=" + URLEncoder.encode(genString)
- + "&ocsp_signing_cc=" + "&signing="
- + URLEncoder.encode(ca_cert_cert) + "&signing_cc="
- + URLEncoder.encode(signing_cc)
- + "&audit_signing=" + URLEncoder.encode(genString)
- + "&audit_signing_cc="
- + "&sslserver=" + URLEncoder.encode(genString)
- + "&sslserver_cc=" + "";
+ + URLEncoder.encode(genString) + "&subsystem_cc="
+ + "&ocsp_signing=" + URLEncoder.encode(genString)
+ + "&ocsp_signing_cc=" + "&signing="
+ + URLEncoder.encode(ca_cert_cert) + "&signing_cc="
+ + URLEncoder.encode(signing_cc)
+ + "&audit_signing=" + URLEncoder.encode(genString)
+ + "&audit_signing_cc="
+ + "&sslserver=" + URLEncoder.encode(genString)
+ + "&sslserver_cc=" + "";
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- if (! checkStatus(hr, "updateStatus", SUCCESS, "CertificatePanelExternal()")) {
+ if (!checkStatus(hr, "updateStatus", SUCCESS, "CertificatePanelExternal()")) {
return false;
}
@@ -824,23 +817,23 @@ public class ConfigureCA {
if (req_list != null && cert_list != null && dn_list != null) {
for (int i = 0; i < dn_list.size(); i++) {
- String temp = dn_list.get(i);
+ String temp = dn_list.get(i);
if (temp.indexOf("caSigningCert") >= 0) {
- ca_cert_req = req_list.get(i);
- ca_cert_cert = cert_list.get(i);
+ ca_cert_req = req_list.get(i);
+ ca_cert_cert = cert_list.get(i);
} else if (temp.indexOf("ocspSigningCert") >= 0) {
- ocsp_cert_req = req_list.get(i);
- ocsp_cert_cert = cert_list.get(i);
+ ocsp_cert_req = req_list.get(i);
+ ocsp_cert_cert = cert_list.get(i);
} else if (temp.indexOf("subsystemCert") >= 0) {
- ca_subsystem_cert_req = req_list.get(i);
- ca_subsystem_cert_cert = cert_list.get(i);
+ ca_subsystem_cert_req = req_list.get(i);
+ ca_subsystem_cert_cert = cert_list.get(i);
} else if (temp.indexOf("auditSigningCert") >= 0) {
- ca_audit_signing_cert_req = req_list.get(i);
- ca_audit_signing_cert_cert = cert_list.get(i);
+ ca_audit_signing_cert_req = req_list.get(i);
+ ca_audit_signing_cert_cert = cert_list.get(i);
} else {
- server_cert_req = req_list.get(i);
- server_cert_cert = cert_list.get(i);
+ server_cert_req = req_list.get(i);
+ server_cert_cert = cert_list.get(i);
}
}
}
@@ -849,10 +842,10 @@ public class ConfigureCA {
System.out.println("ca_cert_name=" + ca_sign_cert_subject_name);
System.out.println("ocsp_cert_name=" + ca_ocsp_cert_subject_name);
System.out.println(
- "ca_subsystem_cert_name=" + ca_subsystem_cert_subject_name);
+ "ca_subsystem_cert_name=" + ca_subsystem_cert_subject_name);
System.out.println("server_cert_name=" + ca_server_cert_subject_name);
System.out.println(
- "ca_audit_signing_cert_name=" + ca_audit_signing_cert_subject_name);
+ "ca_audit_signing_cert_name=" + ca_audit_signing_cert_subject_name);
// print out requests
System.out.println("ca_cert_req=" + ca_cert_req);
@@ -884,15 +877,15 @@ public class ConfigureCA {
if (save_p12.equalsIgnoreCase("true")) {
String query_string = "p=13" + "&op=next" + "&xml=true"
- + "&choice=backupkey" + "&__pwd=" + URLEncoder.encode(backup_pwd)
- + "&__pwdagain=" + URLEncoder.encode(backup_pwd);
+ + "&choice=backupkey" + "&__pwd=" + URLEncoder.encode(backup_pwd)
+ + "&__pwdagain=" + URLEncoder.encode(backup_pwd);
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- if (! checkStatus(hr, "updateStatus", SUCCESS, "BackupPanel()")) {
+ if (!checkStatus(hr, "updateStatus", SUCCESS, "BackupPanel()")) {
return false;
}
- query_string = "";
+ query_string = "";
hr = hc.sslConnect(cs_hostname, cs_port, pkcs12_uri, query_string);
@@ -905,13 +898,13 @@ public class ConfigureCA {
fos.close();
// set file to permissions 600
- String rtParams[] = { "chmod","600", backup_fname};
+ String rtParams[] = { "chmod", "600", backup_fname };
Process proc = Runtime.getRuntime().exec(rtParams);
BufferedReader br = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String line = null;
- while ( (line = br.readLine()) != null)
- System.out.println("Error: " + line);
+ while ((line = br.readLine()) != null)
+ System.out.println("Error: " + line);
int exitVal = proc.waitFor();
// verify p12 file
@@ -928,7 +921,7 @@ public class ConfigureCA {
SEQUENCE asSeq = authSafes.getSequence();
System.out.println(
- "AuthSafes has " + asSeq.size() + " SafeContents");
+ "AuthSafes has " + asSeq.size() + " SafeContents");
fis.close();
} catch (Exception e) {
@@ -950,12 +943,12 @@ public class ConfigureCA {
HTTPResponse hr = null;
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
- "p=14&op=next&xml=true");
- if (! checkStatus(hr, "updateStatus", SUCCESS, "BackupContinuePanel()")) {
+ "p=14&op=next&xml=true");
+ if (!checkStatus(hr, "updateStatus", SUCCESS, "BackupContinuePanel()")) {
return false;
}
- return true;
+ return true;
} catch (Exception e) {
System.out.println("Exception in BackupContinuePanel(): " + e.toString());
e.printStackTrace();
@@ -968,12 +961,12 @@ public class ConfigureCA {
HTTPResponse hr = null;
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
- "p=15&op=next&xml=true");
- if (! checkStatus(hr, "updateStatus", SUCCESS, "ImportCACertPanel()")) {
+ "p=15&op=next&xml=true");
+ if (!checkStatus(hr, "updateStatus", SUCCESS, "ImportCACertPanel()")) {
return false;
}
- return true;
+ return true;
} catch (Exception e) {
System.out.println("Exception in ImportCACertPanel(): " + e.toString());
e.printStackTrace();
@@ -990,7 +983,7 @@ public class ConfigureCA {
String admin_cert_request = null;
ComCrypto cCrypt = new ComCrypto(client_certdb_dir, client_certdb_pwd,
- agent_cert_subject, agent_key_size, agent_key_type);
+ agent_cert_subject, agent_key_size, agent_key_type);
cCrypt.setDebug(true);
cCrypt.setGenerateRequest(true);
@@ -1008,25 +1001,25 @@ public class ConfigureCA {
admin_cert_request = crmf_request;
String query_string = "p=16" + "&op=next" + "&xml=true"
- + "&cert_request_type=" + "crmf" + "&uid=" + admin_user
- + "&name=" + admin_user + "&__pwd=" + URLEncoder.encode(admin_password)
- + "&__admin_password_again=" + URLEncoder.encode(admin_password) + "&profileId="
- + "caAdminCert" + "&email=" + URLEncoder.encode(admin_email)
- + "&cert_request=" + URLEncoder.encode(admin_cert_request)
- + "&subject=" + URLEncoder.encode(agent_cert_subject)
- + "&clone=new"
- + "&import=true" + "&securitydomain="
- + URLEncoder.encode(domain_name) + "";
+ + "&cert_request_type=" + "crmf" + "&uid=" + admin_user
+ + "&name=" + admin_user + "&__pwd=" + URLEncoder.encode(admin_password)
+ + "&__admin_password_again=" + URLEncoder.encode(admin_password) + "&profileId="
+ + "caAdminCert" + "&email=" + URLEncoder.encode(admin_email)
+ + "&cert_request=" + URLEncoder.encode(admin_cert_request)
+ + "&subject=" + URLEncoder.encode(agent_cert_subject)
+ + "&clone=new"
+ + "&import=true" + "&securitydomain="
+ + URLEncoder.encode(domain_name) + "";
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- if (! checkStatus(hr, "updateStatus", SUCCESS, "AdminCertReqPanel()")) {
+ if (!checkStatus(hr, "updateStatus", SUCCESS, "AdminCertReqPanel()")) {
return false;
}
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
-
+
admin_serial_number = px.getvalue("serialNumber");
return true;
@@ -1045,15 +1038,15 @@ public class ConfigureCA {
String cert_to_import = null;
String query_string = "&serialNumber=" + admin_serial_number
- + "&importCert=true" + "";
+ + "&importCert=true" + "";
hr = hc.sslConnect(cs_hostname, cs_port, admin_uri, query_string);
-
+
try {
// get response data
// Convert a byte array to base64 string
// cert_to_import = new sun.misc.BASE64Encoder().encode(
- // hr.getResponseData());
+ // hr.getResponseData());
cert_to_import = OSUtil.BtoA(hr.getResponseData());
// Convert base64 string to a byte array
@@ -1066,7 +1059,7 @@ public class ConfigureCA {
System.out.println("Cert to Import =" + cert_to_import);
ComCrypto cCrypt = new ComCrypto(client_certdb_dir, client_certdb_pwd,
- null, null, null);
+ null, null, null);
cCrypt.setDebug(true);
cCrypt.setGenerateRequest(true);
@@ -1078,7 +1071,7 @@ public class ConfigureCA {
st = cCrypt.importCert(start + cert_to_import + end, agent_name);
if (!st) {
System.out.println(
- "ERROR: AdminCertImportPanel() during cert import");
+ "ERROR: AdminCertImportPanel() during cert import");
return false;
}
@@ -1099,18 +1092,18 @@ public class ConfigureCA {
ParseXML px = new ParseXML();
String query_string = "p=17" + "&op=next" + "&xml=true" + "&caHost="
- + URLEncoder.encode("/") + "&caPort=" + URLEncoder.encode("/")
- + "";
+ + URLEncoder.encode("/") + "&caPort=" + URLEncoder.encode("/")
+ + "";
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- if (! checkStatus(hr, "updateStatus", SUCCESS, "UpdateDomainPanel()")) {
+ if (!checkStatus(hr, "updateStatus", SUCCESS, "UpdateDomainPanel()")) {
return false;
}
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
-
+
String caHost = px.getvalue("host");
String caPort = px.getvalue("port");
String systemType = px.getvalue("systemType");
@@ -1118,7 +1111,7 @@ public class ConfigureCA {
System.out.println("caHost=" + caHost);
System.out.println("caPort=" + caPort);
System.out.println("systemType=" + systemType);
-
+
return true;
} catch (Exception e) {
System.out.println("Exception in UpdateDomainPanel(): " + e.toString());
@@ -1173,14 +1166,13 @@ public class ConfigureCA {
// 4. display cert chain panel and security domain login
if (clone) {
boolean disp_st = DisplayCertChainPanel();
- if(!disp_st) {
+ if (!disp_st) {
System.out.println("ERROR: ConfigureCA: DisplayCertChainPanel() failure");
return false;
}
boolean sd_st = SecurityDomainLoginPanel();
- if(! sd_st)
- {
+ if (!sd_st) {
System.out.println("ERROR: ConfigureSubCA: SecurityDomainLoginPanel() failure");
return false;
}
@@ -1205,7 +1197,7 @@ public class ConfigureCA {
}
// 7. hierarchy panel
- if (! clone) {
+ if (!clone) {
boolean disp_h = HierarchyPanel();
if (!disp_h) {
@@ -1251,12 +1243,11 @@ public class ConfigureCA {
System.out.println("ERROR: ConfigureCA: CertificatePanelExternal() failure");
return false;
}
- }
- else {
- // first pass - cacert file not defined
- System.out.println("A Certificate Request has been generated and stored in " + ext_csr_file);
- System.out.println("Please submit this CSR to your external CA and obtain the CA Cert and CA Cert Chain");
- return true;
+ } else {
+ // first pass - cacert file not defined
+ System.out.println("A Certificate Request has been generated and stored in " + ext_csr_file);
+ System.out.println("Please submit this CSR to your external CA and obtain the CA Cert and CA Cert Chain");
+ return true;
}
}
@@ -1283,7 +1274,6 @@ public class ConfigureCA {
return false;
}
-
// 15. Import CA Cert panel
boolean disp_import_cacert = ImportCACertPanel();
@@ -1291,13 +1281,12 @@ public class ConfigureCA {
System.out.println("ERROR: ConfigureCA: ImportCACertPanel() failure");
return false;
}
-
- if (clone) {
+
+ if (clone) {
// no other panels required for clone
return true;
}
-
// 16. Admin Cert Req Panel
boolean disp_adm = AdminCertReqPanel();
@@ -1350,7 +1339,7 @@ public class ConfigureCA {
StringHolder x_admin_email = new StringHolder();
StringHolder x_admin_password = new StringHolder();
- // ldap
+ // ldap
StringHolder x_ldap_host = new StringHolder();
StringHolder x_ldap_port = new StringHolder();
StringHolder x_bind_dn = new StringHolder();
@@ -1379,7 +1368,7 @@ public class ConfigureCA {
StringHolder x_ocsp_signing_key_type = new StringHolder();
StringHolder x_ocsp_signing_key_curvename = new StringHolder();
StringHolder x_ocsp_signing_signingalgorithm = new StringHolder();
-
+
// key properties (custom - audit_signing)
StringHolder x_audit_signing_key_size = new StringHolder();
StringHolder x_audit_signing_key_type = new StringHolder();
@@ -1421,17 +1410,17 @@ public class ConfigureCA {
// external CA cert
StringHolder x_external_ca = new StringHolder();
- StringHolder x_ext_ca_cert_file = new StringHolder();
- StringHolder x_ext_ca_cert_chain_file = new StringHolder();
- StringHolder x_ext_csr_file = new StringHolder();
+ StringHolder x_ext_ca_cert_file = new StringHolder();
+ StringHolder x_ext_ca_cert_chain_file = new StringHolder();
+ StringHolder x_ext_csr_file = new StringHolder();
- //clone parameters
+ // clone parameters
StringHolder x_clone = new StringHolder();
StringHolder x_clone_uri = new StringHolder();
StringHolder x_clone_p12_file = new StringHolder();
StringHolder x_clone_p12_passwd = new StringHolder();
- //security domain
+ // security domain
StringHolder x_sd_hostname = new StringHolder();
StringHolder x_sd_ssl_port = new StringHolder();
StringHolder x_sd_agent_port = new StringHolder();
@@ -1439,105 +1428,108 @@ public class ConfigureCA {
StringHolder x_sd_admin_name = new StringHolder();
StringHolder x_sd_admin_password = new StringHolder();
-
// parse the args
ArgParser parser = new ArgParser("ConfigureCA");
- parser.addOption("-cs_hostname %s #CS Hostname", x_cs_hostname);
- parser.addOption("-cs_port %s #CS SSL Admin port", x_cs_port);
+ parser.addOption("-cs_hostname %s #CS Hostname", x_cs_hostname);
+ parser.addOption("-cs_port %s #CS SSL Admin port", x_cs_port);
parser.addOption("-client_certdb_dir %s #Client CertDB dir",
- x_client_certdb_dir);
+ x_client_certdb_dir);
parser.addOption("-client_certdb_pwd %s #client certdb password",
- x_client_certdb_pwd);
- parser.addOption("-preop_pin %s #pre op pin", x_preop_pin);
- parser.addOption("-domain_name %s #domain name", x_domain_name);
- parser.addOption("-admin_user %s #Admin User Name", x_admin_user);
- parser.addOption("-admin_email %s #Admin email", x_admin_email);
- parser.addOption("-admin_password %s #Admin password", x_admin_password);
- parser.addOption("-agent_name %s #Agent Cert Nickname", x_agent_name);
+ x_client_certdb_pwd);
+ parser.addOption("-preop_pin %s #pre op pin", x_preop_pin);
+ parser.addOption("-domain_name %s #domain name", x_domain_name);
+ parser.addOption("-admin_user %s #Admin User Name", x_admin_user);
+ parser.addOption("-admin_email %s #Admin email", x_admin_email);
+ parser.addOption("-admin_password %s #Admin password", x_admin_password);
+ parser.addOption("-agent_name %s #Agent Cert Nickname", x_agent_name);
parser.addOption("-agent_key_size %s #Agent Cert Key size",
- x_agent_key_size);
+ x_agent_key_size);
parser.addOption("-agent_key_type %s #Agent Cert Key type [rsa]",
- x_agent_key_type);
+ x_agent_key_type);
parser.addOption("-agent_cert_subject %s #Agent Certificate Subject",
- x_agent_cert_subject);
+ x_agent_cert_subject);
- parser.addOption("-ldap_host %s #ldap host", x_ldap_host);
- parser.addOption("-ldap_port %s #ldap port", x_ldap_port);
- parser.addOption("-bind_dn %s #ldap bind dn", x_bind_dn);
+ parser.addOption("-ldap_host %s #ldap host", x_ldap_host);
+ parser.addOption("-ldap_port %s #ldap port", x_ldap_port);
+ parser.addOption("-bind_dn %s #ldap bind dn", x_bind_dn);
parser.addOption("-bind_password %s #ldap bind password",
- x_bind_password);
- parser.addOption("-base_dn %s #base dn", x_base_dn);
- parser.addOption("-db_name %s #db name", x_db_name);
- parser.addOption("-secure_conn %s #use ldaps port (optional, default is false)", x_secure_conn);
- parser.addOption("-remove_data %s #remove existing data under base_dn (optional, default is false) ", x_remove_data);
- parser.addOption("-clone_start_tls %s #use startTLS for cloning replication agreement (optional, default is false)", x_clone_start_tls);
+ x_bind_password);
+ parser.addOption("-base_dn %s #base dn", x_base_dn);
+ parser.addOption("-db_name %s #db name", x_db_name);
+ parser.addOption("-secure_conn %s #use ldaps port (optional, default is false)", x_secure_conn);
+ parser.addOption("-remove_data %s #remove existing data under base_dn (optional, default is false) ", x_remove_data);
+ parser.addOption("-clone_start_tls %s #use startTLS for cloning replication agreement (optional, default is false)", x_clone_start_tls);
// key and algorithm options (default)
- parser.addOption("-key_type %s #Key type [RSA,ECC] (optional, default is RSA)", x_key_type);
- parser.addOption("-key_size %s #Key Size (optional, for RSA default is 2048)", x_key_size);
- parser.addOption("-key_curvename %s #Key Curve Name (optional, for ECC default is nistp256)", x_key_curvename);
+ parser.addOption("-key_type %s #Key type [RSA,ECC] (optional, default is RSA)", x_key_type);
+ parser.addOption("-key_size %s #Key Size (optional, for RSA default is 2048)", x_key_size);
+ parser.addOption("-key_curvename %s #Key Curve Name (optional, for ECC default is nistp256)", x_key_curvename);
parser.addOption("-key_algorithm %s #Key algorithm of the CA certificate (optional, default is SHA256withRSA for RSA and SHA256withEC for ECC)", x_key_algorithm);
parser.addOption("-signing_algorithm %s #Signing algorithm (optional, default is key_algorithm)", x_signing_algorithm);
// key and algorithm options for signing certificate (overrides default)
- parser.addOption("-signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_signing_key_type);
- parser.addOption("-signing_key_size %s #Key Size (optional, for RSA default is key_size)", x_signing_key_size);
- parser.addOption("-signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_signing_key_curvename);
+ parser.addOption("-signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_signing_key_type);
+ parser.addOption("-signing_key_size %s #Key Size (optional, for RSA default is key_size)", x_signing_key_size);
+ parser.addOption("-signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_signing_key_curvename);
parser.addOption("-signing_signingalgorithm %s #Algorithm used be CA cert to sign objects (optional, default is signing_algorithm)", x_signing_signingalgorithm);
- // key and algorithm options for ocsp_signing certificate (overrides default)
- parser.addOption("-ocsp_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_ocsp_signing_key_type);
- parser.addOption("-ocsp_signing_key_size %s #Key Size (optional, for RSA default is key_size)", x_ocsp_signing_key_size);
- parser.addOption("-ocsp_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_ocsp_signing_key_curvename);
+ // key and algorithm options for ocsp_signing certificate (overrides
+ // default)
+ parser.addOption("-ocsp_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_ocsp_signing_key_type);
+ parser.addOption("-ocsp_signing_key_size %s #Key Size (optional, for RSA default is key_size)", x_ocsp_signing_key_size);
+ parser.addOption("-ocsp_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_ocsp_signing_key_curvename);
parser.addOption("-ocsp_signing_signingalgorithm %s #Algorithm used by the OCSP signing cert to sign objects (optional, default is signing_algorithm)", x_ocsp_signing_signingalgorithm);
- // key and algorithm options for audit_signing certificate (overrides default)
- parser.addOption("-audit_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_audit_signing_key_type);
- parser.addOption("-audit_signing_key_size %s #Key Size (optional, for RSA default is key_size)", x_audit_signing_key_size);
- parser.addOption("-audit_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_audit_signing_key_curvename);
-
- // key and algorithm options for subsystem certificate (overrides default)
- parser.addOption("-subsystem_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_subsystem_key_type);
- parser.addOption("-subsystem_key_size %s #Key Size (optional, for RSA default is key_size)", x_subsystem_key_size);
- parser.addOption("-subsystem_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_subsystem_key_curvename);
-
- // key and algorithm options for sslserver certificate (overrides default)
- parser.addOption("-sslserver_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_sslserver_key_type);
- parser.addOption("-sslserver_key_size %s #Key Size (optional, for RSA default is key_size)", x_sslserver_key_size);
- parser.addOption("-sslserver_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_sslserver_key_curvename);
-
- parser.addOption("-token_name %s #HSM/Software Token name", x_token_name);
+ // key and algorithm options for audit_signing certificate (overrides
+ // default)
+ parser.addOption("-audit_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_audit_signing_key_type);
+ parser.addOption("-audit_signing_key_size %s #Key Size (optional, for RSA default is key_size)", x_audit_signing_key_size);
+ parser.addOption("-audit_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_audit_signing_key_curvename);
+
+ // key and algorithm options for subsystem certificate (overrides
+ // default)
+ parser.addOption("-subsystem_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_subsystem_key_type);
+ parser.addOption("-subsystem_key_size %s #Key Size (optional, for RSA default is key_size)", x_subsystem_key_size);
+ parser.addOption("-subsystem_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_subsystem_key_curvename);
+
+ // key and algorithm options for sslserver certificate (overrides
+ // default)
+ parser.addOption("-sslserver_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_sslserver_key_type);
+ parser.addOption("-sslserver_key_size %s #Key Size (optional, for RSA default is key_size)", x_sslserver_key_size);
+ parser.addOption("-sslserver_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_sslserver_key_curvename);
+
+ parser.addOption("-token_name %s #HSM/Software Token name", x_token_name);
parser.addOption("-token_pwd %s #HSM/Software Token password (optional - only required for HSM)",
- x_token_pwd);
+ x_token_pwd);
parser.addOption("-save_p12 %s #Enable/Disable p12 Export[true,false]",
- x_save_p12);
- parser.addOption("-backup_pwd %s #Backup Password for p12 (optional, only required if -save_p12 = true)", x_backup_pwd);
+ x_save_p12);
+ parser.addOption("-backup_pwd %s #Backup Password for p12 (optional, only required if -save_p12 = true)", x_backup_pwd);
parser.addOption("-backup_fname %s #Backup File for p12, (optional, default is /root/tmp-ca.p12)", x_backup_fname);
parser.addOption("-ca_sign_cert_subject_name %s #CA cert subject name",
x_ca_sign_cert_subject_name);
parser.addOption(
"-ca_subsystem_cert_subject_name %s #CA subsystem cert subject name",
- x_ca_subsystem_cert_subject_name);
+ x_ca_subsystem_cert_subject_name);
parser.addOption(
"-ca_ocsp_cert_subject_name %s #CA ocsp cert subject name",
- x_ca_ocsp_cert_subject_name);
+ x_ca_ocsp_cert_subject_name);
parser.addOption(
"-ca_server_cert_subject_name %s #CA server cert subject name",
- x_ca_server_cert_subject_name);
+ x_ca_server_cert_subject_name);
parser.addOption(
"-ca_audit_signing_cert_subject_name %s #CA audit signing cert subject name",
- x_ca_audit_signing_cert_subject_name);
+ x_ca_audit_signing_cert_subject_name);
parser.addOption("-subsystem_name %s #CA subsystem name",
- x_subsystem_name);
-
+ x_subsystem_name);
+
parser.addOption("-external %s #Subordinate to external CA [true,false] (optional, default false)",
- x_external_ca);
+ x_external_ca);
parser.addOption("-ext_ca_cert_file %s #File with CA cert from external CA (optional)",
- x_ext_ca_cert_file);
+ x_ext_ca_cert_file);
parser.addOption("-ext_ca_cert_chain_file %s #File with CA cert from external CA (optional)",
x_ext_ca_cert_chain_file);
parser.addOption("-ext_csr_file %s #File to save the CSR for submission to an external CA (optional)",
@@ -1548,15 +1540,14 @@ public class ConfigureCA {
parser.addOption("-clone_p12_file %s #File containing pk12 keys of Master CA (optional, required if -clone=true)", x_clone_p12_file);
parser.addOption("-clone_p12_password %s #Password for pk12 file (optional, required if -clone=true)", x_clone_p12_passwd);
- parser.addOption ("-sd_hostname %s #Security Domain Hostname (optional, required if -clone=true)", x_sd_hostname);
- parser.addOption ("-sd_ssl_port %s #Security Domain SSL EE port (optional, required if -clone=true)", x_sd_ssl_port);
- parser.addOption ("-sd_agent_port %s #Security Domain SSL Agent port (optional, required if -clone=true)", x_sd_agent_port);
- parser.addOption ("-sd_admin_port %s #Security Domain SSL Admin port (optional, required if -clone=true)", x_sd_admin_port);
- parser.addOption ("-sd_admin_name %s #Security Domain admin name (optional, required if -clone=true)",
- x_sd_admin_name);
- parser.addOption ("-sd_admin_password %s #Security Domain admin password (optional, required if -clone=true)",
- x_sd_admin_password);
-
+ parser.addOption("-sd_hostname %s #Security Domain Hostname (optional, required if -clone=true)", x_sd_hostname);
+ parser.addOption("-sd_ssl_port %s #Security Domain SSL EE port (optional, required if -clone=true)", x_sd_ssl_port);
+ parser.addOption("-sd_agent_port %s #Security Domain SSL Agent port (optional, required if -clone=true)", x_sd_agent_port);
+ parser.addOption("-sd_admin_port %s #Security Domain SSL Admin port (optional, required if -clone=true)", x_sd_admin_port);
+ parser.addOption("-sd_admin_name %s #Security Domain admin name (optional, required if -clone=true)",
+ x_sd_admin_name);
+ parser.addOption("-sd_admin_password %s #Security Domain admin password (optional, required if -clone=true)",
+ x_sd_admin_password);
// and then match the arguments
String[] unmatched = null;
@@ -1618,11 +1609,11 @@ public class ConfigureCA {
} else {
key_algorithm = set_default(x_key_algorithm.value, DEFAULT_KEY_ALGORITHM_ECC);
}
-
+
signing_algorithm = set_default(x_signing_algorithm.value, key_algorithm);
signing_signingalgorithm = set_default(x_signing_signingalgorithm.value, signing_algorithm);
ocsp_signing_signingalgorithm = set_default(x_ocsp_signing_signingalgorithm.value, signing_algorithm);
-
+
token_name = x_token_name.value;
token_pwd = x_token_pwd.value;
save_p12 = x_save_p12.value;
@@ -1638,9 +1629,9 @@ public class ConfigureCA {
ca_ocsp_cert_subject_name = x_ca_ocsp_cert_subject_name.value;
ca_server_cert_subject_name = x_ca_server_cert_subject_name.value;
ca_audit_signing_cert_subject_name = x_ca_audit_signing_cert_subject_name.value;
-
+
subsystem_name = x_subsystem_name.value;
-
+
external_ca = set_default(x_external_ca.value, "false");
ext_ca_cert_file = x_ext_ca_cert_file.value;
ext_ca_cert_chain_file = x_ext_ca_cert_chain_file.value;
@@ -1663,18 +1654,15 @@ public class ConfigureCA {
sd_admin_password = x_sd_admin_password.value;
boolean st = ca.ConfigureCAInstance();
-
+
if (!st) {
System.out.println("ERROR: unable to create CA");
System.exit(-1);
}
-
+
System.out.println("Certificate System - CA Instance Configured.");
System.exit(0);
-
- }
-
-}
+ }
-;
+};
diff --git a/pki/base/silent/src/com/netscape/pkisilent/ConfigureDRM.java b/pki/base/silent/src/com/netscape/pkisilent/ConfigureDRM.java
index c79ec4ed..45e417cc 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/ConfigureDRM.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/ConfigureDRM.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -17,7 +18,6 @@ package com.netscape.pkisilent;
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
-
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
@@ -39,8 +39,7 @@ import com.netscape.pkisilent.common.ParseXML;
import com.netscape.pkisilent.http.HTTPClient;
import com.netscape.pkisilent.http.HTTPResponse;
-public class ConfigureDRM
-{
+public class ConfigureDRM {
// global constants
public static final String DEFAULT_KEY_TYPE = "RSA";
@@ -52,7 +51,7 @@ public class ConfigureDRM
// define global variables
public static HTTPClient hc = null;
-
+
public static String login_uri = "/kra/admin/console/config/login";
public static String wizard_uri = "/kra/admin/console/config/wizard";
public static String admin_uri = "/ca/admin/ca/getBySerial";
@@ -78,7 +77,7 @@ public class ConfigureDRM
public static String client_certdb_dir = null;
public static String client_certdb_pwd = null;
- // Login Panel
+ // Login Panel
public static String pin = null;
public static String domain_name = null;
@@ -160,14 +159,13 @@ public class ConfigureDRM
public static String backup_pwd = null;
public static String backup_fname = null;
- // cert subject names
+ // cert subject names
public static String drm_transport_cert_subject_name = null;
public static String drm_subsystem_cert_subject_name = null;
public static String drm_storage_cert_subject_name = null;
public static String drm_server_cert_subject_name = null;
public static String drm_audit_signing_cert_subject_name = null;
-
public static String subsystem_name = null;
// cloning
@@ -176,38 +174,32 @@ public class ConfigureDRM
public static String clone_p12_passwd = null;
public static String clone_p12_file = null;
- //for correct selection of CA to be cloned
+ // for correct selection of CA to be cloned
public static String urls;
-
- public ConfigureDRM ()
- {
+
+ public ConfigureDRM() {
// do nothing :)
}
- public void sleep_time()
- {
- try
- {
+ public void sleep_time() {
+ try {
System.out.println("Sleeping for 5 secs..");
Thread.sleep(5000);
- }
- catch(Exception e)
- {
+ } catch (Exception e) {
System.out.println("ERROR: sleep problem");
}
}
- public boolean LoginPanel()
- {
+ public boolean LoginPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "pin=" + pin + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname,cs_port,login_uri,query_string);
+ String query_string = "pin=" + pin + "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, login_uri, query_string);
System.out.println("xml returned: " + hr.getHTML());
// parse xml here - nothing to parse
@@ -215,14 +207,14 @@ public class ConfigureDRM
// get cookie
String temp = hr.getCookieValue("JSESSIONID");
- if (temp!=null) {
+ if (temp != null) {
int index = temp.indexOf(";");
- HTTPClient.j_session_id = temp.substring(0,index);
+ HTTPClient.j_session_id = temp.substring(0, index);
st = true;
}
hr = null;
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri, "p=0&op=next&xml=true");
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, "p=0&op=next&xml=true");
// parse xml here
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
@@ -232,8 +224,7 @@ public class ConfigureDRM
return st;
}
- public boolean TokenChoicePanel()
- {
+ public boolean TokenChoicePanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -244,9 +235,9 @@ public class ConfigureDRM
// Software Token
if (token_name.equalsIgnoreCase("internal")) {
query_string = "p=1" + "&op=next" + "&xml=true" +
- "&choice=" +
+ "&choice=" +
URLEncoder.encode("Internal Key Storage Token");
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
@@ -255,22 +246,22 @@ public class ConfigureDRM
} else {
// login to hsm first
query_string = "p=2" + "&op=next" + "&xml=true" +
- "&uTokName=" +
+ "&uTokName=" +
URLEncoder.encode(token_name) +
- "&__uPasswd=" +
- URLEncoder.encode(token_pwd);
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ "&__uPasswd=" +
+ URLEncoder.encode(token_pwd);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
+
// choice with token name now
query_string = "p=1" + "&op=next" + "&xml=true" +
- "&choice=" +
+ "&choice=" +
URLEncoder.encode(token_name);
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
@@ -281,24 +272,22 @@ public class ConfigureDRM
return true;
}
- public boolean DomainPanel()
- {
+ public boolean DomainPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
-
- String domain_url = "https://" + sd_hostname + ":" + sd_admin_port ;
+ String domain_url = "https://" + sd_hostname + ":" + sd_admin_port;
String query_string = "sdomainURL=" +
URLEncoder.encode(domain_url) +
- "&choice=existingdomain"+
+ "&choice=existingdomain" +
"&p=3" +
"&op=next" +
- "&xml=true";
+ "&xml=true";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
@@ -309,23 +298,21 @@ public class ConfigureDRM
}
- public boolean DisplayChainPanel()
- {
+ public boolean DisplayChainPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
String query_string = null;
- query_string = "p=4" + "&op=next" + "&xml=true";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ query_string = "p=4" + "&op=next" + "&xml=true";
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
return true;
}
- public boolean SecurityDomainLoginPanel()
- {
+ public boolean SecurityDomainLoginPanel() {
try {
boolean st = false;
HTTPResponse hr = null;
@@ -334,17 +321,17 @@ public class ConfigureDRM
String kra_url = "https://" + cs_hostname + ":" + cs_port +
"/kra/admin/console/config/wizard" +
- "?p=5&subsystem=KRA" ;
+ "?p=5&subsystem=KRA";
- String query_string = "url=" + URLEncoder.encode(kra_url);
+ String query_string = "url=" + URLEncoder.encode(kra_url);
- hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_login_uri,query_string);
+ hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_login_uri, query_string);
String query_string_1 = "uid=" + sd_admin_name +
"&pwd=" + URLEncoder.encode(sd_admin_password) +
- "&url=" + URLEncoder.encode(kra_url) ;
+ "&url=" + URLEncoder.encode(kra_url);
- hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_get_cookie_uri,
+ hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_get_cookie_uri,
query_string_1);
// get session id from security domain
@@ -360,9 +347,9 @@ public class ConfigureDRM
String query_string_2 = "p=5" +
"&subsystem=KRA" +
"&session_id=" + kra_session_id +
- "&xml=true" ;
+ "&xml=true";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
query_string_2);
if (clone) {
@@ -372,7 +359,7 @@ public class ConfigureDRM
if (indx < 0) {
throw new Exception("Invalid clone_uri");
}
- urls = urls.substring(urls.lastIndexOf("<option" , indx), indx);
+ urls = urls.substring(urls.lastIndexOf("<option", indx), indx);
urls = urls.split("\"")[1];
System.out.println("urls =" + urls);
@@ -385,9 +372,8 @@ public class ConfigureDRM
return false;
}
}
-
- public boolean SubsystemPanel()
- {
+
+ public boolean SubsystemPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -395,16 +381,16 @@ public class ConfigureDRM
String query_string = null;
if (!clone) {
query_string = "p=5" + "&op=next" + "&xml=true"
- + "&choice=newsubsystem" + "&subsystemName="
- + URLEncoder.encode(subsystem_name);
+ + "&choice=newsubsystem" + "&subsystemName="
+ + URLEncoder.encode(subsystem_name);
} else {
query_string = "p=5" + "&op=next" + "&xml=true"
- + "&choice=clonesubsystem" + "&subsystemName="
- + URLEncoder.encode(subsystem_name)
- + "&urls=" + urls;
+ + "&choice=clonesubsystem" + "&subsystemName="
+ + URLEncoder.encode(subsystem_name)
+ + "&urls=" + urls;
}
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
@@ -420,8 +406,8 @@ public class ConfigureDRM
ParseXML px = new ParseXML();
String query_string = "p=6" + "&op=next" + "&xml=true"
- + "&__password=" + URLEncoder.encode(clone_p12_passwd)
- + "&path=" + URLEncoder.encode(clone_p12_file) + "";
+ + "&__password=" + URLEncoder.encode(clone_p12_passwd)
+ + "&path=" + URLEncoder.encode(clone_p12_file) + "";
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
@@ -437,27 +423,25 @@ public class ConfigureDRM
}
}
- public boolean LdapConnectionPanel()
- {
+ public boolean LdapConnectionPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
-
String query_string = "p=7" + "&op=next" + "&xml=true" +
- "&host=" + URLEncoder.encode(ldap_host) +
+ "&host=" + URLEncoder.encode(ldap_host) +
"&port=" + URLEncoder.encode(ldap_port) +
"&binddn=" + URLEncoder.encode(bind_dn) +
"&__bindpwd=" + URLEncoder.encode(bind_password) +
"&basedn=" + URLEncoder.encode(base_dn) +
"&database=" + URLEncoder.encode(db_name) +
- "&display=" + URLEncoder.encode("$displayStr") +
- (secure_conn.equals("true")? "&secureConn=on": "") +
- (clone_start_tls.equals("true")? "&cloneStartTLS=on": "") +
- (remove_data.equals("true")? "&removeData=true": "");
+ "&display=" + URLEncoder.encode("$displayStr") +
+ (secure_conn.equals("true") ? "&secureConn=on" : "") +
+ (clone_start_tls.equals("true") ? "&cloneStartTLS=on" : "") +
+ (remove_data.equals("true") ? "&removeData=true" : "");
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
@@ -467,8 +451,7 @@ public class ConfigureDRM
return true;
}
- public boolean KeyPanel()
- {
+ public boolean KeyPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -479,55 +462,55 @@ public class ConfigureDRM
if (!clone) {
query_string = "p=8" + "&op=next" + "&xml=true" +
- "&transport_custom_size=" + transport_key_size +
- "&storage_custom_size=" + storage_key_size +
- "&subsystem_custom_size=" + subsystem_key_size +
- "&sslserver_custom_size=" + sslserver_key_size +
- "&audit_signing_custom_size=" + key_size +
- "&custom_size=" + key_size +
- "&transport_custom_curvename=" + transport_key_curvename +
- "&storage_custom_curvename=" + storage_key_curvename +
- "&subsystem_custom_curvename=" + subsystem_key_curvename +
- "&sslserver_custom_curvename=" + sslserver_key_curvename +
- "&audit_signing_custom_curvename=" + audit_signing_key_curvename +
- "&custom_curvename=" + key_curvename +
- "&transport_keytype=" + transport_key_type +
- "&storage_keytype=" + storage_key_type +
- "&subsystem_keytype=" + subsystem_key_type +
- "&sslserver_keytype=" + sslserver_key_type +
- "&audit_signing_keytype=" + audit_signing_key_type +
- "&keytype=" + key_type +
- "&transport_choice=custom"+
- "&storage_choice=custom"+
- "&subsystem_choice=custom"+
- "&sslserver_choice=custom"+
- "&choice=custom"+
- "&audit_signing_choice=custom" +
- "&signingalgorithm=" + signing_algorithm +
- "&transport_signingalgorithm=" + transport_signingalgorithm;
+ "&transport_custom_size=" + transport_key_size +
+ "&storage_custom_size=" + storage_key_size +
+ "&subsystem_custom_size=" + subsystem_key_size +
+ "&sslserver_custom_size=" + sslserver_key_size +
+ "&audit_signing_custom_size=" + key_size +
+ "&custom_size=" + key_size +
+ "&transport_custom_curvename=" + transport_key_curvename +
+ "&storage_custom_curvename=" + storage_key_curvename +
+ "&subsystem_custom_curvename=" + subsystem_key_curvename +
+ "&sslserver_custom_curvename=" + sslserver_key_curvename +
+ "&audit_signing_custom_curvename=" + audit_signing_key_curvename +
+ "&custom_curvename=" + key_curvename +
+ "&transport_keytype=" + transport_key_type +
+ "&storage_keytype=" + storage_key_type +
+ "&subsystem_keytype=" + subsystem_key_type +
+ "&sslserver_keytype=" + sslserver_key_type +
+ "&audit_signing_keytype=" + audit_signing_key_type +
+ "&keytype=" + key_type +
+ "&transport_choice=custom" +
+ "&storage_choice=custom" +
+ "&subsystem_choice=custom" +
+ "&sslserver_choice=custom" +
+ "&choice=custom" +
+ "&audit_signing_choice=custom" +
+ "&signingalgorithm=" + signing_algorithm +
+ "&transport_signingalgorithm=" + transport_signingalgorithm;
} else {
query_string = "p=8" + "&op=next" + "&xml=true" +
- "&sslserver_custom_size=" + sslserver_key_size +
- "&sslserver_keytype=" + sslserver_key_type +
- "&sslserver_choice=custom" +
- "&custom_size=" + key_size +
- "&keytype=" + key_type +
- "&choice=custom";
- }
+ "&sslserver_custom_size=" + sslserver_key_size +
+ "&sslserver_keytype=" + sslserver_key_type +
+ "&sslserver_choice=custom" +
+ "&custom_size=" + key_size +
+ "&keytype=" + key_type +
+ "&choice=custom";
+ }
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
- al = px.constructValueList("CertReqPair","DN");
+
+ al = px.constructValueList("CertReqPair", "DN");
// get ca cert subject name
if (al != null) {
- for (int i=0; i < al.size(); i++) {
- String temp = al.get(i);
+ for (int i = 0; i < al.size(); i++) {
+ String temp = al.get(i);
if (temp.indexOf("DRM Transport") > 0) {
drm_transport_cert_name = temp;
} else if (temp.indexOf("DRM Storage") > 0) {
@@ -541,23 +524,22 @@ public class ConfigureDRM
}
}
}
-
- System.out.println("default: drm_transport_cert_name=" +
- drm_transport_cert_name);
- System.out.println("default: drm_storage_cert_name=" +
- drm_storage_cert_name);
- System.out.println("default: drm_subsystem_cert_name=" +
- drm_subsystem_cert_name);
+
+ System.out.println("default: drm_transport_cert_name=" +
+ drm_transport_cert_name);
+ System.out.println("default: drm_storage_cert_name=" +
+ drm_storage_cert_name);
+ System.out.println("default: drm_subsystem_cert_name=" +
+ drm_subsystem_cert_name);
System.out.println("default: drm_audit_signing_cert_name=" +
- drm_audit_signing_cert_name);
+ drm_audit_signing_cert_name);
- System.out.println("default: server_cert_name=" +
- server_cert_name);
+ System.out.println("default: server_cert_name=" +
+ server_cert_name);
return true;
}
- public boolean CertSubjectPanel()
- {
+ public boolean CertSubjectPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -567,69 +549,68 @@ public class ConfigureDRM
ArrayList<String> dn_list = null;
String query_string = null;
- String domain_url = "https://" + ca_hostname + ":" + ca_ssl_port ;
+ String domain_url = "https://" + ca_hostname + ":" + ca_ssl_port;
if (!clone) {
query_string = "p=9" + "&op=next" + "&xml=true" +
- "&subsystem=" +
- URLEncoder.encode(drm_subsystem_cert_subject_name) +
- "&transport=" +
- URLEncoder.encode(drm_transport_cert_subject_name) +
- "&storage=" +
- URLEncoder.encode(drm_storage_cert_subject_name) +
- "&sslserver=" +
- URLEncoder.encode(drm_server_cert_subject_name) +
- "&audit_signing=" +
- URLEncoder.encode(drm_audit_signing_cert_subject_name) +
- "&urls=" +
- URLEncoder.encode(domain_url);
+ "&subsystem=" +
+ URLEncoder.encode(drm_subsystem_cert_subject_name) +
+ "&transport=" +
+ URLEncoder.encode(drm_transport_cert_subject_name) +
+ "&storage=" +
+ URLEncoder.encode(drm_storage_cert_subject_name) +
+ "&sslserver=" +
+ URLEncoder.encode(drm_server_cert_subject_name) +
+ "&audit_signing=" +
+ URLEncoder.encode(drm_audit_signing_cert_subject_name) +
+ "&urls=" +
+ URLEncoder.encode(domain_url);
} else {
query_string = "p=9" + "&op=next" + "&xml=true" +
- "&sslserver=" +
- URLEncoder.encode(drm_server_cert_subject_name) +
- "&urls=" +
- URLEncoder.encode(domain_url);
+ "&sslserver=" +
+ URLEncoder.encode(drm_server_cert_subject_name) +
+ "&urls=" +
+ URLEncoder.encode(domain_url);
}
-
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
- req_list = px.constructValueList("CertReqPair","Request");
- cert_list = px.constructValueList("CertReqPair","Certificate");
- dn_list = px.constructValueList("CertReqPair","Nickname");
+
+ req_list = px.constructValueList("CertReqPair", "Request");
+ cert_list = px.constructValueList("CertReqPair", "Certificate");
+ dn_list = px.constructValueList("CertReqPair", "Nickname");
if (req_list != null && cert_list != null && dn_list != null) {
- for (int i=0; i < dn_list.size(); i++) {
- String temp = dn_list.get(i);
+ for (int i = 0; i < dn_list.size(); i++) {
+ String temp = dn_list.get(i);
if (temp.indexOf("transportCert") >= 0) {
- drm_transport_cert_req = req_list.get(i);
- drm_transport_cert_cert = cert_list.get(i);
+ drm_transport_cert_req = req_list.get(i);
+ drm_transport_cert_cert = cert_list.get(i);
} else if (temp.indexOf("storageCert") >= 0) {
- drm_storage_cert_req = req_list.get(i);
- drm_storage_cert_cert = cert_list.get(i);
+ drm_storage_cert_req = req_list.get(i);
+ drm_storage_cert_cert = cert_list.get(i);
} else if (temp.indexOf("subsystemCert") >= 0) {
- drm_subsystem_cert_req = req_list.get(i);
- drm_subsystem_cert_cert = cert_list.get(i);
- } else if (temp.indexOf("auditSigningCert") >=0) {
- drm_audit_signing_cert_req = req_list.get(i);
- drm_audit_signing_cert_cert = cert_list.get(i);
+ drm_subsystem_cert_req = req_list.get(i);
+ drm_subsystem_cert_cert = cert_list.get(i);
+ } else if (temp.indexOf("auditSigningCert") >= 0) {
+ drm_audit_signing_cert_req = req_list.get(i);
+ drm_audit_signing_cert_cert = cert_list.get(i);
} else {
- server_cert_req = req_list.get(i);
- server_cert_cert = cert_list.get(i);
+ server_cert_req = req_list.get(i);
+ server_cert_cert = cert_list.get(i);
}
}
}
-
+
return true;
}
- public boolean CertificatePanel()
- {
+ public boolean CertificatePanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -639,68 +620,63 @@ public class ConfigureDRM
ArrayList<String> dn_list = null;
ArrayList<String> pp_list = null;
-
String query_string = "p=10" + "&op=next" + "&xml=true" +
- "&subsystem=" +
+ "&subsystem=" +
URLEncoder.encode(drm_subsystem_cert_cert) +
- "&subsystem_cc=" +
- "&transport=" +
+ "&subsystem_cc=" +
+ "&transport=" +
URLEncoder.encode(drm_transport_cert_cert) +
- "&transport_cc=" +
- "&storage=" +
- URLEncoder.encode(drm_storage_cert_cert) +
- "&storage_cc=" +
- "&sslserver=" +
- URLEncoder.encode(server_cert_cert) +
- "&sslserver_cc=" +
- "&audit_signing=" +
+ "&transport_cc=" +
+ "&storage=" +
+ URLEncoder.encode(drm_storage_cert_cert) +
+ "&storage_cc=" +
+ "&sslserver=" +
+ URLEncoder.encode(server_cert_cert) +
+ "&sslserver_cc=" +
+ "&audit_signing=" +
URLEncoder.encode(drm_audit_signing_cert_cert) +
"&audit_signing_cc=";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
+
return true;
}
- public boolean BackupPanel()
- {
+ public boolean BackupPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
-
String query_string = "p=11" + "&op=next" + "&xml=true" +
- "&choice=backupkey" +
+ "&choice=backupkey" +
"&__pwd=" + URLEncoder.encode(backup_pwd) +
"&__pwdagain=" + URLEncoder.encode(backup_pwd);
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
+
return true;
}
- public boolean SavePKCS12Panel()
- {
+ public boolean SavePKCS12Panel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
+ String query_string = "";
- String query_string = "";
-
- hr = hc.sslConnect(cs_hostname,cs_port,pkcs12_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, pkcs12_uri, query_string);
// dump hr.getResponseData() to file
try {
@@ -709,17 +685,17 @@ public class ConfigureDRM
fos.close();
// set file to permissions 600
- String rtParams[] = { "chmod","600", backup_fname};
+ String rtParams[] = { "chmod", "600", backup_fname };
Process proc = Runtime.getRuntime().exec(rtParams);
BufferedReader br = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String line = null;
- while ( (line = br.readLine()) != null)
- System.out.println("Error: " + line);
+ while ((line = br.readLine()) != null)
+ System.out.println("Error: " + line);
int exitVal = proc.waitFor();
-
+
// verify p12 file
-
+
// Decode the P12 file
FileInputStream fis = new FileInputStream(backup_fname);
PFX.Template pfxt = new PFX.Template();
@@ -727,17 +703,17 @@ public class ConfigureDRM
System.out.println("Decoded PFX");
// now peruse it for interesting info
- System.out.println("Version: "+pfx.getVersion());
+ System.out.println("Version: " + pfx.getVersion());
AuthenticatedSafes authSafes = pfx.getAuthSafes();
SEQUENCE asSeq = authSafes.getSequence();
- System.out.println("AuthSafes has "+
- asSeq.size()+" SafeContents");
+ System.out.println("AuthSafes has " +
+ asSeq.size() + " SafeContents");
fis.close();
if (clone) {
query_string = "p=12" + "&op=next" + "&xml=true";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
@@ -752,8 +728,7 @@ public class ConfigureDRM
return true;
}
- public boolean AdminCertReqPanel()
- {
+ public boolean AdminCertReqPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -775,7 +750,7 @@ public class ConfigureDRM
if (crmf_request == null) {
System.out.println("ERROR: AdminCertReqPanel() cert req gen failed");
- return false;
+ return false;
}
admin_cert_request = crmf_request;
@@ -787,31 +762,30 @@ public class ConfigureDRM
"&__pwd=" + URLEncoder.encode(admin_password) +
"&__admin_password_again=" + URLEncoder.encode(admin_password) +
"&profileId=" + "caAdminCert" +
- "&email=" +
+ "&email=" +
URLEncoder.encode(admin_email) +
- "&cert_request=" +
+ "&cert_request=" +
URLEncoder.encode(admin_cert_request) +
"&subject=" +
URLEncoder.encode(agent_cert_subject) +
"&clone=new" +
"&import=true" +
"&securitydomain=" +
- URLEncoder.encode(domain_name);
+ URLEncoder.encode(domain_name);
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
- admin_serial_number = px.getvalue("serialNumber");
+
+ admin_serial_number = px.getvalue("serialNumber");
return true;
}
- public boolean AdminCertImportPanel()
- {
+ public boolean AdminCertImportPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -820,13 +794,13 @@ public class ConfigureDRM
String query_string = "serialNumber=" + admin_serial_number +
"&importCert=" + "true";
- hr = hc.sslConnect(sd_hostname,sd_admin_port,admin_uri,query_string);
-
+ hr = hc.sslConnect(sd_hostname, sd_admin_port, admin_uri, query_string);
+
// get response data
- // String cert_to_import =
- // new sun.misc.BASE64Encoder().encode(hr.getResponseData());
- String cert_to_import =
- OSUtil.BtoA(hr.getResponseData());
+ // String cert_to_import =
+ // new sun.misc.BASE64Encoder().encode(hr.getResponseData());
+ String cert_to_import =
+ OSUtil.BtoA(hr.getResponseData());
System.out.println("Imported Cert=" + cert_to_import);
ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
@@ -838,10 +812,10 @@ public class ConfigureDRM
cCrypt.setGenerateRequest(true);
cCrypt.loginDB();
- String start = "-----BEGIN CERTIFICATE-----\r\n" ;
- String end = "\r\n-----END CERTIFICATE-----" ;
+ String start = "-----BEGIN CERTIFICATE-----\r\n";
+ String end = "\r\n-----END CERTIFICATE-----";
- st = cCrypt.importCert(start+cert_to_import+end,agent_name);
+ st = cCrypt.importCert(start + cert_to_import + end, agent_name);
if (!st) {
System.out.println("ERROR: AdminCertImportPanel() during cert import");
return false;
@@ -851,8 +825,7 @@ public class ConfigureDRM
return true;
}
- public boolean UpdateDomainPanel()
- {
+ public boolean UpdateDomainPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -862,18 +835,17 @@ public class ConfigureDRM
"&caHost=" + URLEncoder.encode(sd_hostname) +
"&caPort=" + URLEncoder.encode(sd_agent_port);
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
+
return true;
}
- public boolean ConfigureDRMInstance()
- {
+ public boolean ConfigureDRMInstance() {
// 0. login to cert db
ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
client_certdb_pwd,
@@ -1034,8 +1006,7 @@ public class ConfigureDRM
}
}
- public static void main(String args[])
- {
+ public static void main(String args[]) {
ConfigureDRM ca = new ConfigureDRM();
// set variables
@@ -1063,7 +1034,7 @@ public class ConfigureDRM
StringHolder x_admin_email = new StringHolder();
StringHolder x_admin_password = new StringHolder();
- // ldap
+ // ldap
StringHolder x_ldap_host = new StringHolder();
StringHolder x_ldap_port = new StringHolder();
StringHolder x_bind_dn = new StringHolder();
@@ -1127,7 +1098,7 @@ public class ConfigureDRM
// subsystemName
StringHolder x_subsystem_name = new StringHolder();
- //clone parameters
+ // clone parameters
StringHolder x_clone = new StringHolder();
StringHolder x_clone_uri = new StringHolder();
StringHolder x_clone_p12_file = new StringHolder();
@@ -1136,63 +1107,63 @@ public class ConfigureDRM
// parse the args
ArgParser parser = new ArgParser("ConfigureDRM");
- parser.addOption ("-cs_hostname %s #CS Hostname",
- x_cs_hostname);
- parser.addOption ("-cs_port %s #CS SSL Admin port",
- x_cs_port);
-
- parser.addOption ("-sd_hostname %s #Security Domain Hostname",
- x_sd_hostname);
- parser.addOption ("-sd_ssl_port %s #Security Domain SSL EE port",
- x_sd_ssl_port);
- parser.addOption ("-sd_agent_port %s #Security Domain SSL Agent port",
- x_sd_agent_port);
- parser.addOption ("-sd_admin_port %s #Security Domain SSL Admin port",
- x_sd_admin_port);
- parser.addOption ("-sd_admin_name %s #Security Domain username",
- x_sd_admin_name);
- parser.addOption ("-sd_admin_password %s #Security Domain password",
- x_sd_admin_password);
-
- parser.addOption ("-ca_hostname %s #CA Hostname",
- x_ca_hostname);
- parser.addOption ("-ca_port %s #CA non-SSL EE port",
- x_ca_port);
- parser.addOption ("-ca_ssl_port %s #CA SSL EE port",
- x_ca_ssl_port);
-
- parser.addOption ("-client_certdb_dir %s #Client CertDB dir",
- x_client_certdb_dir);
- parser.addOption ("-client_certdb_pwd %s #client certdb password",
- x_client_certdb_pwd);
- parser.addOption ("-preop_pin %s #pre op pin",
- x_preop_pin);
- parser.addOption ("-domain_name %s #domain name",
- x_domain_name);
- parser.addOption ("-admin_user %s #Admin User Name",
- x_admin_user);
- parser.addOption ("-admin_email %s #Admin email",
- x_admin_email);
- parser.addOption ("-admin_password %s #Admin password",
- x_admin_password);
- parser.addOption ("-agent_name %s #Agent Cert Nickname",
- x_agent_name);
-
- parser.addOption ("-ldap_host %s #ldap host",
- x_ldap_host);
- parser.addOption ("-ldap_port %s #ldap port",
- x_ldap_port);
- parser.addOption ("-bind_dn %s #ldap bind dn",
- x_bind_dn);
- parser.addOption ("-bind_password %s #ldap bind password",
- x_bind_password);
- parser.addOption ("-base_dn %s #base dn",
- x_base_dn);
- parser.addOption ("-db_name %s #db name",
- x_db_name);
- parser.addOption("-secure_conn %s #use ldaps port (optional, default is false)", x_secure_conn);
- parser.addOption("-remove_data %s #remove existing data under base_dn (optional, default is false) ", x_remove_data);
- parser.addOption("-clone_start_tls %s #use startTLS for cloning replication agreement (optional, default is false)", x_clone_start_tls);
+ parser.addOption("-cs_hostname %s #CS Hostname",
+ x_cs_hostname);
+ parser.addOption("-cs_port %s #CS SSL Admin port",
+ x_cs_port);
+
+ parser.addOption("-sd_hostname %s #Security Domain Hostname",
+ x_sd_hostname);
+ parser.addOption("-sd_ssl_port %s #Security Domain SSL EE port",
+ x_sd_ssl_port);
+ parser.addOption("-sd_agent_port %s #Security Domain SSL Agent port",
+ x_sd_agent_port);
+ parser.addOption("-sd_admin_port %s #Security Domain SSL Admin port",
+ x_sd_admin_port);
+ parser.addOption("-sd_admin_name %s #Security Domain username",
+ x_sd_admin_name);
+ parser.addOption("-sd_admin_password %s #Security Domain password",
+ x_sd_admin_password);
+
+ parser.addOption("-ca_hostname %s #CA Hostname",
+ x_ca_hostname);
+ parser.addOption("-ca_port %s #CA non-SSL EE port",
+ x_ca_port);
+ parser.addOption("-ca_ssl_port %s #CA SSL EE port",
+ x_ca_ssl_port);
+
+ parser.addOption("-client_certdb_dir %s #Client CertDB dir",
+ x_client_certdb_dir);
+ parser.addOption("-client_certdb_pwd %s #client certdb password",
+ x_client_certdb_pwd);
+ parser.addOption("-preop_pin %s #pre op pin",
+ x_preop_pin);
+ parser.addOption("-domain_name %s #domain name",
+ x_domain_name);
+ parser.addOption("-admin_user %s #Admin User Name",
+ x_admin_user);
+ parser.addOption("-admin_email %s #Admin email",
+ x_admin_email);
+ parser.addOption("-admin_password %s #Admin password",
+ x_admin_password);
+ parser.addOption("-agent_name %s #Agent Cert Nickname",
+ x_agent_name);
+
+ parser.addOption("-ldap_host %s #ldap host",
+ x_ldap_host);
+ parser.addOption("-ldap_port %s #ldap port",
+ x_ldap_port);
+ parser.addOption("-bind_dn %s #ldap bind dn",
+ x_bind_dn);
+ parser.addOption("-bind_password %s #ldap bind password",
+ x_bind_password);
+ parser.addOption("-base_dn %s #base dn",
+ x_base_dn);
+ parser.addOption("-db_name %s #db name",
+ x_db_name);
+ parser.addOption("-secure_conn %s #use ldaps port (optional, default is false)", x_secure_conn);
+ parser.addOption("-remove_data %s #remove existing data under base_dn (optional, default is false) ", x_remove_data);
+ parser.addOption("-clone_start_tls %s #use startTLS for cloning replication agreement (optional, default is false)", x_clone_start_tls);
// key and algorithm options (default)
parser.addOption("-key_type %s #Key type [RSA,ECC] (optional, default is RSA)", x_key_type);
@@ -1200,7 +1171,8 @@ public class ConfigureDRM
parser.addOption("-key_curvename %s #Key Curve Name (optional, for ECC default is nistp256)", x_key_curvename);
parser.addOption("-signing_algorithm %s #Signing algorithm (optional, default is SHA256withRSA for RSA and SHA256withEC for ECC)", x_signing_algorithm);
- // key and algorithm options for transport certificate (overrides default)
+ // key and algorithm options for transport certificate (overrides
+ // default)
parser.addOption("-transport_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_transport_key_type);
parser.addOption("-transport_key_size %s #Key Size (optional, for RSA default is key_size)", x_transport_key_size);
parser.addOption("-transport_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_transport_key_curvename);
@@ -1211,58 +1183,61 @@ public class ConfigureDRM
parser.addOption("-storage_key_size %s #Key Size (optional, for RSA default is key_size)", x_storage_key_size);
parser.addOption("-storage_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_storage_key_curvename);
- // key and algorithm options for audit_signing certificate (overrides default)
+ // key and algorithm options for audit_signing certificate (overrides
+ // default)
parser.addOption("-audit_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_audit_signing_key_type);
parser.addOption("-audit_signing_key_size %s #Key Size (optional, for RSA default is key_size)", x_audit_signing_key_size);
parser.addOption("-audit_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_audit_signing_key_curvename);
- // key and algorithm options for subsystem certificate (overrides default)
+ // key and algorithm options for subsystem certificate (overrides
+ // default)
parser.addOption("-subsystem_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_subsystem_key_type);
parser.addOption("-subsystem_key_size %s #Key Size (optional, for RSA default is key_size)", x_subsystem_key_size);
parser.addOption("-subsystem_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_subsystem_key_curvename);
- // key and algorithm options for sslserver certificate (overrides default)
+ // key and algorithm options for sslserver certificate (overrides
+ // default)
parser.addOption("-sslserver_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_sslserver_key_type);
parser.addOption("-sslserver_key_size %s #Key Size (optional, for RSA default is key_size)", x_sslserver_key_size);
parser.addOption("-sslserver_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_sslserver_key_curvename);
- parser.addOption ("-token_name %s #HSM/Software Token name",
- x_token_name);
- parser.addOption ("-token_pwd %s #HSM/Software Token password (optional, required for HSM)",
- x_token_pwd);
+ parser.addOption("-token_name %s #HSM/Software Token name",
+ x_token_name);
+ parser.addOption("-token_pwd %s #HSM/Software Token password (optional, required for HSM)",
+ x_token_pwd);
- parser.addOption ("-agent_key_size %s #Agent Cert Key Size",
- x_agent_key_size);
- parser.addOption ("-agent_key_type %s #Agent Cert Key type [rsa]",
- x_agent_key_type);
- parser.addOption ("-agent_cert_subject %s #Agent Cert Subject ",
- x_agent_cert_subject);
+ parser.addOption("-agent_key_size %s #Agent Cert Key Size",
+ x_agent_key_size);
+ parser.addOption("-agent_key_type %s #Agent Cert Key type [rsa]",
+ x_agent_key_type);
+ parser.addOption("-agent_cert_subject %s #Agent Cert Subject ",
+ x_agent_cert_subject);
- parser.addOption ("-backup_pwd %s #PKCS12 password",
- x_backup_pwd);
+ parser.addOption("-backup_pwd %s #PKCS12 password",
+ x_backup_pwd);
- parser.addOption("-backup_fname %s #Backup File for p12, (optional, default /root/tmp-kra.p12)",
+ parser.addOption("-backup_fname %s #Backup File for p12, (optional, default /root/tmp-kra.p12)",
x_backup_fname);
- parser.addOption (
- "-drm_transport_cert_subject_name %s #DRM transport cert subject name",
+ parser.addOption(
+ "-drm_transport_cert_subject_name %s #DRM transport cert subject name",
x_drm_transport_cert_subject_name);
- parser.addOption (
- "-drm_subsystem_cert_subject_name %s #DRM subsystem cert subject name",
- x_drm_subsystem_cert_subject_name);
- parser.addOption (
- "-drm_storage_cert_subject_name %s #DRM storage cert subject name",
- x_drm_storage_cert_subject_name);
- parser.addOption (
- "-drm_server_cert_subject_name %s #DRM server cert subject name",
- x_drm_server_cert_subject_name);
-
- parser.addOption (
- "-subsystem_name %s #CA subsystem name",
- x_subsystem_name);
+ parser.addOption(
+ "-drm_subsystem_cert_subject_name %s #DRM subsystem cert subject name",
+ x_drm_subsystem_cert_subject_name);
+ parser.addOption(
+ "-drm_storage_cert_subject_name %s #DRM storage cert subject name",
+ x_drm_storage_cert_subject_name);
+ parser.addOption(
+ "-drm_server_cert_subject_name %s #DRM server cert subject name",
+ x_drm_server_cert_subject_name);
parser.addOption(
- "-drm_audit_signing_cert_subject_name %s #DRM audit signing cert subject name",
+ "-subsystem_name %s #CA subsystem name",
+ x_subsystem_name);
+
+ parser.addOption(
+ "-drm_audit_signing_cert_subject_name %s #DRM audit signing cert subject name",
x_drm_audit_signing_cert_subject_name);
parser.addOption("-clone %s #Clone of another KRA [true, false] (optional, default false)", x_clone);
@@ -1271,10 +1246,10 @@ public class ConfigureDRM
parser.addOption("-clone_p12_password %s #Password for pk12 file (optional, required if -clone=true)", x_clone_p12_passwd);
// and then match the arguments
- String [] unmatched = null;
- unmatched = parser.matchAllArgs (args,0,ArgParser.EXIT_ON_UNMATCHED);
+ String[] unmatched = null;
+ unmatched = parser.matchAllArgs(args, 0, ArgParser.EXIT_ON_UNMATCHED);
- if (unmatched!=null) {
+ if (unmatched != null) {
System.out.println("ERROR: Argument Mismatch");
System.exit(-1);
}
@@ -1354,15 +1329,15 @@ public class ConfigureDRM
backup_pwd = x_backup_pwd.value;
backup_fname = set_default(x_backup_fname.value, "/root/tmp-kra.p12");
-
- drm_transport_cert_subject_name =
- x_drm_transport_cert_subject_name.value ;
- drm_subsystem_cert_subject_name =
- x_drm_subsystem_cert_subject_name.value;
- drm_storage_cert_subject_name = x_drm_storage_cert_subject_name.value ;
- drm_server_cert_subject_name = x_drm_server_cert_subject_name.value ;
- drm_audit_signing_cert_subject_name = x_drm_audit_signing_cert_subject_name.value;
-
+
+ drm_transport_cert_subject_name =
+ x_drm_transport_cert_subject_name.value;
+ drm_subsystem_cert_subject_name =
+ x_drm_subsystem_cert_subject_name.value;
+ drm_storage_cert_subject_name = x_drm_storage_cert_subject_name.value;
+ drm_server_cert_subject_name = x_drm_server_cert_subject_name.value;
+ drm_audit_signing_cert_subject_name = x_drm_audit_signing_cert_subject_name.value;
+
subsystem_name = x_subsystem_name.value;
if ((x_clone.value != null) && (x_clone.value.equalsIgnoreCase("true"))) {
@@ -1375,12 +1350,12 @@ public class ConfigureDRM
clone_p12_passwd = x_clone_p12_passwd.value;
boolean st = ca.ConfigureDRMInstance();
-
+
if (!st) {
System.out.println("ERROR: unable to create DRM");
System.exit(-1);
}
-
+
System.out.println("Certificate System - DRM Instance Configured");
System.exit(0);
}
diff --git a/pki/base/silent/src/com/netscape/pkisilent/ConfigureOCSP.java b/pki/base/silent/src/com/netscape/pkisilent/ConfigureOCSP.java
index f237b0c7..7b99af00 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/ConfigureOCSP.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/ConfigureOCSP.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -38,8 +39,7 @@ import com.netscape.pkisilent.common.ParseXML;
import com.netscape.pkisilent.http.HTTPClient;
import com.netscape.pkisilent.http.HTTPResponse;
-public class ConfigureOCSP
-{
+public class ConfigureOCSP {
public static final String DEFAULT_KEY_TYPE = "RSA";
public static final String DEFAULT_KEY_SIZE = "2048";
public static final String DEFAULT_KEY_CURVENAME = "nistp256";
@@ -49,7 +49,7 @@ public class ConfigureOCSP
// define global variables
public static HTTPClient hc = null;
-
+
public static String login_uri = "/ocsp/admin/console/config/login";
public static String wizard_uri = "/ocsp/admin/console/config/wizard";
public static String admin_uri = "/ca/admin/ca/getBySerial";
@@ -75,7 +75,7 @@ public class ConfigureOCSP
public static String client_certdb_dir = null;
public static String client_certdb_pwd = null;
- // Login Panel
+ // Login Panel
public static String pin = null;
public static String domain_name = null;
@@ -148,42 +148,37 @@ public class ConfigureOCSP
public static String backup_pwd = null;
public static String backup_fname = null;
- // cert subject names
+ // cert subject names
public static String ocsp_sign_cert_subject_name = null;
public static String ocsp_subsystem_cert_subject_name = null;
public static String ocsp_server_cert_subject_name = null;
public static String ocsp_audit_signing_cert_subject_name = null;
public static String subsystem_name = null;
- public ConfigureOCSP ()
- {
+
+ public ConfigureOCSP() {
// do nothing :)
}
- public void sleep_time()
- {
- try
- {
+ public void sleep_time() {
+ try {
System.out.println("Sleeping for 5 secs..");
Thread.sleep(5000);
- }
- catch(Exception e)
- {
+ } catch (Exception e) {
System.out.println("ERROR: sleep problem");
}
}
- public boolean LoginPanel()
- {
+ public boolean LoginPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "pin=" + pin + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname,cs_port,login_uri,query_string);
+ String query_string = "pin=" + pin + "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, login_uri, query_string);
System.out.println("xml returned: " + hr.getHTML());
// parse xml here - nothing to parse
@@ -191,14 +186,14 @@ public class ConfigureOCSP
// get cookie
String temp = hr.getCookieValue("JSESSIONID");
- if (temp!=null) {
+ if (temp != null) {
int index = temp.indexOf(";");
- HTTPClient.j_session_id = temp.substring(0,index);
+ HTTPClient.j_session_id = temp.substring(0, index);
st = true;
}
hr = null;
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
"p=0&op=next&xml=true");
// parse xml here
@@ -211,8 +206,7 @@ public class ConfigureOCSP
return st;
}
- public boolean TokenChoicePanel()
- {
+ public boolean TokenChoicePanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -223,10 +217,10 @@ public class ConfigureOCSP
// Software Token
if (token_name.equalsIgnoreCase("internal")) {
query_string = "p=1" + "&op=next" + "&xml=true" +
- "&choice=" +
+ "&choice=" +
URLEncoder.encode("Internal Key Storage Token") +
- "";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ "";
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
@@ -236,23 +230,23 @@ public class ConfigureOCSP
else {
// login to hsm first
query_string = "p=2" + "&op=next" + "&xml=true" +
- "&uTokName=" +
+ "&uTokName=" +
URLEncoder.encode(token_name) +
- "&__uPasswd=" +
+ "&__uPasswd=" +
URLEncoder.encode(token_pwd) +
- "";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ "";
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
+
// choice with token name now
query_string = "p=1" + "&op=next" + "&xml=true" +
- "&choice=" +
+ "&choice=" +
URLEncoder.encode(token_name) +
- "";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ "";
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
@@ -262,24 +256,22 @@ public class ConfigureOCSP
return true;
}
- public boolean DomainPanel()
- {
+ public boolean DomainPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
-
- String domain_url = "https://" + sd_hostname + ":" + sd_admin_port ;
+ String domain_url = "https://" + sd_hostname + ":" + sd_admin_port;
String query_string = "sdomainURL=" +
URLEncoder.encode(domain_url) +
- "&choice=existingdomain"+
+ "&choice=existingdomain" +
"&p=3" +
"&op=next" +
- "&xml=true";
+ "&xml=true";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
@@ -290,16 +282,15 @@ public class ConfigureOCSP
}
- public boolean DisplayChainPanel()
- {
+ public boolean DisplayChainPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
String query_string = null;
- query_string = "p=4" + "&op=next" + "&xml=true";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ query_string = "p=4" + "&op=next" + "&xml=true";
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
// bais = new ByteArrayInputStream(hr.getHTML().getBytes());
// px.parse(bais);
@@ -309,27 +300,25 @@ public class ConfigureOCSP
}
- public boolean SecurityDomainLoginPanel()
- {
+ public boolean SecurityDomainLoginPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
-
String ocsp_url = "https://" + cs_hostname + ":" + cs_port +
"/ocsp/admin/console/config/wizard" +
- "?p=5&subsystem=OCSP" ;
+ "?p=5&subsystem=OCSP";
- String query_string = "url=" + URLEncoder.encode(ocsp_url);
+ String query_string = "url=" + URLEncoder.encode(ocsp_url);
- hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_login_uri,query_string);
+ hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_login_uri, query_string);
String query_string_1 = "uid=" + sd_admin_name +
"&pwd=" + URLEncoder.encode(sd_admin_password) +
- "&url=" + URLEncoder.encode(ocsp_url) ;
+ "&url=" + URLEncoder.encode(ocsp_url);
- hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_get_cookie_uri,
+ hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_get_cookie_uri,
query_string_1);
// get session id from security domain
@@ -337,17 +326,17 @@ public class ConfigureOCSP
String ocsp_session_id = hr.getContentValue("header.session_id");
String ocsp_url_1 = hr.getContentValue("header.url");
- System.out.println("OCSP_SESSION_ID=" + ocsp_session_id );
- System.out.println("OCSP_URL=" + ocsp_url_1 );
+ System.out.println("OCSP_SESSION_ID=" + ocsp_session_id);
+ System.out.println("OCSP_URL=" + ocsp_url_1);
// use session id to connect back to OCSP
String query_string_2 = "p=5" +
"&subsystem=OCSP" +
"&session_id=" + ocsp_session_id +
- "&xml=true" ;
+ "&xml=true";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
query_string_2);
// parse xml
@@ -358,20 +347,19 @@ public class ConfigureOCSP
return true;
}
-
- public boolean SubsystemPanel()
- {
+
+ public boolean SubsystemPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "p=5" + "&op=next" + "&xml=true" +
+ String query_string = "p=5" + "&op=next" + "&xml=true" +
"&subsystemName=" +
- URLEncoder.encode(subsystem_name) +
- "&choice=newsubsystem" ;
+ URLEncoder.encode(subsystem_name) +
+ "&choice=newsubsystem";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
@@ -380,27 +368,25 @@ public class ConfigureOCSP
return true;
}
- public boolean LdapConnectionPanel()
- {
+ public boolean LdapConnectionPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
-
String query_string = "p=7" + "&op=next" + "&xml=true" +
- "&host=" + URLEncoder.encode(ldap_host) +
+ "&host=" + URLEncoder.encode(ldap_host) +
"&port=" + URLEncoder.encode(ldap_port) +
"&binddn=" + URLEncoder.encode(bind_dn) +
"&__bindpwd=" + URLEncoder.encode(bind_password) +
"&basedn=" + URLEncoder.encode(base_dn) +
"&database=" + URLEncoder.encode(db_name) +
"&display=" + URLEncoder.encode("$displayStr") +
- (secure_conn.equals("true")? "&secureConn=on": "") +
- (clone_start_tls.equals("true")? "&cloneStartTLS=on": "") +
- (remove_data.equals("true")? "&removeData=true": "");
+ (secure_conn.equals("true") ? "&secureConn=on" : "") +
+ (clone_start_tls.equals("true") ? "&cloneStartTLS=on" : "") +
+ (remove_data.equals("true") ? "&removeData=true" : "");
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
@@ -410,8 +396,7 @@ public class ConfigureOCSP
return true;
}
- public boolean KeyPanel()
- {
+ public boolean KeyPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -429,31 +414,31 @@ public class ConfigureOCSP
"&sslserver_custom_curvename=" + sslserver_key_curvename +
"&audit_signing_custom_curvename=" + audit_signing_key_curvename +
"&custom_curvename=" + key_curvename +
- "&signing_keytype=" + signing_key_type +
+ "&signing_keytype=" + signing_key_type +
"&subsystem_keytype=" + subsystem_key_type +
"&sslserver_keytype=" + sslserver_key_type +
"&audit_signing_keytype=" + audit_signing_key_type +
"&keytype=" + key_type +
- "&signing_choice=custom"+
- "&subsystem_choice=custom"+
- "&sslserver_choice=custom"+
+ "&signing_choice=custom" +
+ "&subsystem_choice=custom" +
+ "&sslserver_choice=custom" +
"&audit_signing_choice=custom" +
"&signingalgorithm=" + signing_algorithm +
"&signing_signingalgorithm=" + signing_signingalgorithm +
"&choice=custom";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
- al = px.constructValueList("CertReqPair","DN");
+
+ al = px.constructValueList("CertReqPair", "DN");
// get ca cert subject name
if (al != null) {
- for (int i=0; i < al.size(); i++) {
- String temp = al.get(i);
+ for (int i = 0; i < al.size(); i++) {
+ String temp = al.get(i);
if (temp.indexOf("OCSP Signing") > 0) {
ocsp_signing_cert_name = temp;
} else if (temp.indexOf("OCSP Subsystem") > 0) {
@@ -465,7 +450,7 @@ public class ConfigureOCSP
}
}
}
-
+
System.out.println("default: ocsp_signing_cert_name=" + ocsp_signing_cert_name);
System.out.println("default: ocsp_subsystem_cert_name=" + ocsp_subsystem_cert_name);
System.out.println("default: server_cert_name=" + server_cert_name);
@@ -474,8 +459,7 @@ public class ConfigureOCSP
return true;
}
- public boolean CertSubjectPanel()
- {
+ public boolean CertSubjectPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -484,57 +468,56 @@ public class ConfigureOCSP
ArrayList<String> cert_list = null;
ArrayList<String> dn_list = null;
- String domain_url = "https://" + ca_hostname + ":" + ca_ssl_port ;
+ String domain_url = "https://" + ca_hostname + ":" + ca_ssl_port;
String query_string = "p=9" + "&op=next" + "&xml=true" +
- "&subsystem=" +
+ "&subsystem=" +
URLEncoder.encode(ocsp_subsystem_cert_subject_name) +
- "&signing=" +
- URLEncoder.encode(ocsp_sign_cert_subject_name) +
- "&sslserver=" +
- URLEncoder.encode(ocsp_server_cert_subject_name) +
+ "&signing=" +
+ URLEncoder.encode(ocsp_sign_cert_subject_name) +
+ "&sslserver=" +
+ URLEncoder.encode(ocsp_server_cert_subject_name) +
"&audit_signing=" +
URLEncoder.encode(ocsp_audit_signing_cert_subject_name) +
- "&urls=" +
- URLEncoder.encode(domain_url) +
- "";
+ "&urls=" +
+ URLEncoder.encode(domain_url) +
+ "";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
- req_list = px.constructValueList("CertReqPair","Request");
- cert_list = px.constructValueList("CertReqPair","Certificate");
- dn_list = px.constructValueList("CertReqPair","Nickname");
+
+ req_list = px.constructValueList("CertReqPair", "Request");
+ cert_list = px.constructValueList("CertReqPair", "Certificate");
+ dn_list = px.constructValueList("CertReqPair", "Nickname");
if (req_list != null && cert_list != null && dn_list != null) {
- for (int i=0; i < dn_list.size(); i++) {
- String temp = dn_list.get(i);
-
- if (temp.indexOf("ocspSigningCert") >= 0 ) {
- ocsp_signing_cert_req = req_list.get(i);
- ocsp_signing_cert_cert = cert_list.get(i);
- } else if (temp.indexOf("subsystemCert") >= 0 ) {
- ocsp_subsystem_cert_req = req_list.get(i);
- ocsp_subsystem_cert_cert = cert_list.get(i);
- } else if (temp.indexOf("auditSigningCert") >=0) {
- ocsp_audit_signing_cert_req = req_list.get(i);
- ocsp_audit_signing_cert_cert = cert_list.get(i);
+ for (int i = 0; i < dn_list.size(); i++) {
+ String temp = dn_list.get(i);
+
+ if (temp.indexOf("ocspSigningCert") >= 0) {
+ ocsp_signing_cert_req = req_list.get(i);
+ ocsp_signing_cert_cert = cert_list.get(i);
+ } else if (temp.indexOf("subsystemCert") >= 0) {
+ ocsp_subsystem_cert_req = req_list.get(i);
+ ocsp_subsystem_cert_cert = cert_list.get(i);
+ } else if (temp.indexOf("auditSigningCert") >= 0) {
+ ocsp_audit_signing_cert_req = req_list.get(i);
+ ocsp_audit_signing_cert_cert = cert_list.get(i);
} else {
- server_cert_req = req_list.get(i);
- server_cert_cert = cert_list.get(i);
+ server_cert_req = req_list.get(i);
+ server_cert_cert = cert_list.get(i);
}
}
}
-
+
return true;
}
- public boolean CertificatePanel()
- {
+ public boolean CertificatePanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -544,69 +527,64 @@ public class ConfigureOCSP
ArrayList<String> dn_list = null;
ArrayList<String> pp_list = null;
-
String query_string = "p=10" + "&op=next" + "&xml=true" +
- "&subsystem=" +
+ "&subsystem=" +
URLEncoder.encode(ocsp_subsystem_cert_cert) +
- "&subsystem_cc=" +
- "&signing=" +
- URLEncoder.encode(ocsp_signing_cert_cert) +
- "&signing_cc=" +
- "&sslserver=" +
- URLEncoder.encode(server_cert_cert) +
- "&sslserver_cc=" +
- "&audit_signing=" +
+ "&subsystem_cc=" +
+ "&signing=" +
+ URLEncoder.encode(ocsp_signing_cert_cert) +
+ "&signing_cc=" +
+ "&sslserver=" +
+ URLEncoder.encode(server_cert_cert) +
+ "&sslserver_cc=" +
+ "&audit_signing=" +
URLEncoder.encode(ocsp_audit_signing_cert_cert) +
"&audit_signing_cc=" +
- "";
+ "";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
-
+
System.out.println("html returned=" + hr.getHTML());
px.parse(bais);
px.prettyprintxml();
-
+
return true;
}
- public boolean BackupPanel()
- {
+ public boolean BackupPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
-
String query_string = "p=11" + "&op=next" + "&xml=true" +
- "&choice=backupkey" +
+ "&choice=backupkey" +
"&__pwd=" + URLEncoder.encode(backup_pwd) +
"&__pwdagain=" + URLEncoder.encode(backup_pwd);
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
+
return true;
}
- public boolean SavePKCS12Panel()
- {
+ public boolean SavePKCS12Panel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
+ String query_string = "";
- String query_string = "";
-
- hr = hc.sslConnect(cs_hostname,cs_port,pkcs12_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, pkcs12_uri, query_string);
// dump hr.getResponseData() to file
@@ -616,17 +594,17 @@ public class ConfigureOCSP
fos.close();
// set file to permissions 600
- String rtParams[] = { "chmod","600", backup_fname};
+ String rtParams[] = { "chmod", "600", backup_fname };
Process proc = Runtime.getRuntime().exec(rtParams);
BufferedReader br = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String line = null;
- while ( (line = br.readLine()) != null)
- System.out.println("Error: " + line);
+ while ((line = br.readLine()) != null)
+ System.out.println("Error: " + line);
int exitVal = proc.waitFor();
-
+
// verify p12 file
-
+
// Decode the P12 file
FileInputStream fis = new FileInputStream(backup_fname);
PFX.Template pfxt = new PFX.Template();
@@ -634,14 +612,14 @@ public class ConfigureOCSP
System.out.println("Decoded PFX");
// now peruse it for interesting info
- System.out.println("Version: "+pfx.getVersion());
+ System.out.println("Version: " + pfx.getVersion());
AuthenticatedSafes authSafes = pfx.getAuthSafes();
SEQUENCE asSeq = authSafes.getSequence();
- System.out.println("AuthSafes has "+
- asSeq.size()+" SafeContents");
+ System.out.println("AuthSafes has " +
+ asSeq.size() + " SafeContents");
fis.close();
- } catch(Exception e) {
+ } catch (Exception e) {
System.out.println("ERROR: Exception=" + e.getMessage());
return false;
}
@@ -649,15 +627,13 @@ public class ConfigureOCSP
return true;
}
- public boolean AdminCertReqPanel()
- {
+ public boolean AdminCertReqPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
String admin_cert_request = null;
-
String cert_subject = "CN=ocsp-" + admin_user;
ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
@@ -687,9 +663,9 @@ public class ConfigureOCSP
"&__pwd=" + URLEncoder.encode(admin_password) +
"&__admin_password_again=" + URLEncoder.encode(admin_password) +
"&profileId=" + "caAdminCert" +
- "&email=" +
+ "&email=" +
URLEncoder.encode(admin_email) +
- "&cert_request=" +
+ "&cert_request=" +
URLEncoder.encode(admin_cert_request) +
"&subject=" +
URLEncoder.encode(agent_cert_subject) +
@@ -697,22 +673,21 @@ public class ConfigureOCSP
"&import=true" +
"&securitydomain=" +
URLEncoder.encode(domain_name) +
- "";
+ "";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
- admin_serial_number = px.getvalue("serialNumber");
+
+ admin_serial_number = px.getvalue("serialNumber");
return true;
}
- public boolean AdminCertImportPanel()
- {
+ public boolean AdminCertImportPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -720,14 +695,14 @@ public class ConfigureOCSP
String query_string = "serialNumber=" + admin_serial_number +
"&importCert=" + "true" +
- "";
+ "";
+
+ hr = hc.sslConnect(sd_hostname, sd_admin_port, admin_uri, query_string);
- hr = hc.sslConnect(sd_hostname,sd_admin_port,admin_uri,query_string);
-
// get response data
- // String cert_to_import =
- // new sun.misc.BASE64Encoder().encode(hr.getResponseData());
- String cert_to_import =
+ // String cert_to_import =
+ // new sun.misc.BASE64Encoder().encode(hr.getResponseData());
+ String cert_to_import =
OSUtil.BtoA(hr.getResponseData());
System.out.println("Imported Cert=" + cert_to_import);
@@ -740,10 +715,10 @@ public class ConfigureOCSP
cCrypt.setGenerateRequest(true);
cCrypt.loginDB();
- String start = "-----BEGIN CERTIFICATE-----\r\n" ;
- String end = "\r\n-----END CERTIFICATE-----" ;
+ String start = "-----BEGIN CERTIFICATE-----\r\n";
+ String end = "\r\n-----END CERTIFICATE-----";
- st = cCrypt.importCert(start+cert_to_import+end,agent_name);
+ st = cCrypt.importCert(start + cert_to_import + end, agent_name);
if (!st) {
System.out.println("ERROR: AdminCertImportPanel() during cert import");
return false;
@@ -753,8 +728,7 @@ public class ConfigureOCSP
return true;
}
- public boolean UpdateDomainPanel()
- {
+ public boolean UpdateDomainPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -763,21 +737,19 @@ public class ConfigureOCSP
String query_string = "p=14" + "&op=next" + "&xml=true" +
"&caHost=" + URLEncoder.encode(sd_hostname) +
"&caPort=" + URLEncoder.encode(sd_agent_port) +
- "";
+ "";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
+
return true;
}
-
- public boolean ConfigureOCSPInstance()
- {
+ public boolean ConfigureOCSPInstance() {
// 0. login to cert db
ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
client_certdb_pwd,
@@ -802,7 +774,7 @@ public class ConfigureOCSP
// 2. Token Choice Panel
boolean disp_token = TokenChoicePanel();
if (!disp_token) {
- System.out.println("ERROR: ConfigureOCSP: TokenChoicePanel() failure");
+ System.out.println("ERROR: ConfigureOCSP: TokenChoicePanel() failure");
return false;
}
@@ -837,7 +809,7 @@ public class ConfigureOCSP
System.out.println("ERROR: ConfigureOCSP: SubsystemPanel() failure");
return false;
}
-
+
sleep_time();
// 7. ldap connection panel
boolean disp_ldap = LdapConnectionPanel();
@@ -923,8 +895,7 @@ public class ConfigureOCSP
}
}
- public static void main(String args[])
- {
+ public static void main(String args[]) {
ConfigureOCSP ca = new ConfigureOCSP();
// set variables
@@ -952,7 +923,7 @@ public class ConfigureOCSP
StringHolder x_admin_email = new StringHolder();
StringHolder x_admin_password = new StringHolder();
- // ldap
+ // ldap
StringHolder x_ldap_host = new StringHolder();
StringHolder x_ldap_port = new StringHolder();
StringHolder x_bind_dn = new StringHolder();
@@ -1013,63 +984,63 @@ public class ConfigureOCSP
// parse the args
ArgParser parser = new ArgParser("ConfigureOCSP");
- parser.addOption ("-cs_hostname %s #CS Hostname",
- x_cs_hostname);
- parser.addOption ("-cs_port %s #CS SSL Admin port",
- x_cs_port);
-
- parser.addOption ("-sd_hostname %s #Security Domain Hostname",
- x_sd_hostname);
- parser.addOption ("-sd_ssl_port %s #Security Domain SSL EE port",
- x_sd_ssl_port);
- parser.addOption ("-sd_agent_port %s #Security Domain SSL Agent port",
- x_sd_agent_port);
- parser.addOption ("-sd_admin_port %s #Security Domain SSL Admin port",
- x_sd_admin_port);
- parser.addOption ("-sd_admin_name %s #Security Domain Admin Name",
- x_sd_admin_name);
- parser.addOption ("-sd_admin_password %s #Security Domain Admin password",
- x_sd_admin_password);
-
- parser.addOption ("-ca_hostname %s #CA Hostname",
- x_ca_hostname);
- parser.addOption ("-ca_port %s #CA non-SSL EE port",
- x_ca_port);
- parser.addOption ("-ca_ssl_port %s #CA SSL EE port",
- x_ca_ssl_port);
-
- parser.addOption ("-client_certdb_dir %s #Client CertDB dir",
- x_client_certdb_dir);
- parser.addOption ("-client_certdb_pwd %s #client certdb password",
- x_client_certdb_pwd);
- parser.addOption ("-preop_pin %s #pre op pin",
- x_preop_pin);
- parser.addOption ("-domain_name %s #domain name",
- x_domain_name);
- parser.addOption ("-admin_user %s #Admin User Name",
- x_admin_user);
- parser.addOption ("-admin_email %s #Admin email",
- x_admin_email);
- parser.addOption ("-admin_password %s #Admin password",
- x_admin_password);
- parser.addOption ("-agent_name %s #Agent Cert Nickname",
- x_agent_name);
-
- parser.addOption ("-ldap_host %s #ldap host",
- x_ldap_host);
- parser.addOption ("-ldap_port %s #ldap port",
- x_ldap_port);
- parser.addOption ("-bind_dn %s #ldap bind dn",
- x_bind_dn);
- parser.addOption ("-bind_password %s #ldap bind password",
- x_bind_password);
- parser.addOption ("-base_dn %s #base dn",
- x_base_dn);
- parser.addOption ("-db_name %s #db name",
- x_db_name);
- parser.addOption("-secure_conn %s #use ldaps port (optional, default is false)", x_secure_conn);
- parser.addOption("-remove_data %s #remove existing data under base_dn (optional, default is false) ", x_remove_data);
- parser.addOption("-clone_start_tls %s #use startTLS for cloning replication agreement (optional, default is false)", x_clone_start_tls);
+ parser.addOption("-cs_hostname %s #CS Hostname",
+ x_cs_hostname);
+ parser.addOption("-cs_port %s #CS SSL Admin port",
+ x_cs_port);
+
+ parser.addOption("-sd_hostname %s #Security Domain Hostname",
+ x_sd_hostname);
+ parser.addOption("-sd_ssl_port %s #Security Domain SSL EE port",
+ x_sd_ssl_port);
+ parser.addOption("-sd_agent_port %s #Security Domain SSL Agent port",
+ x_sd_agent_port);
+ parser.addOption("-sd_admin_port %s #Security Domain SSL Admin port",
+ x_sd_admin_port);
+ parser.addOption("-sd_admin_name %s #Security Domain Admin Name",
+ x_sd_admin_name);
+ parser.addOption("-sd_admin_password %s #Security Domain Admin password",
+ x_sd_admin_password);
+
+ parser.addOption("-ca_hostname %s #CA Hostname",
+ x_ca_hostname);
+ parser.addOption("-ca_port %s #CA non-SSL EE port",
+ x_ca_port);
+ parser.addOption("-ca_ssl_port %s #CA SSL EE port",
+ x_ca_ssl_port);
+
+ parser.addOption("-client_certdb_dir %s #Client CertDB dir",
+ x_client_certdb_dir);
+ parser.addOption("-client_certdb_pwd %s #client certdb password",
+ x_client_certdb_pwd);
+ parser.addOption("-preop_pin %s #pre op pin",
+ x_preop_pin);
+ parser.addOption("-domain_name %s #domain name",
+ x_domain_name);
+ parser.addOption("-admin_user %s #Admin User Name",
+ x_admin_user);
+ parser.addOption("-admin_email %s #Admin email",
+ x_admin_email);
+ parser.addOption("-admin_password %s #Admin password",
+ x_admin_password);
+ parser.addOption("-agent_name %s #Agent Cert Nickname",
+ x_agent_name);
+
+ parser.addOption("-ldap_host %s #ldap host",
+ x_ldap_host);
+ parser.addOption("-ldap_port %s #ldap port",
+ x_ldap_port);
+ parser.addOption("-bind_dn %s #ldap bind dn",
+ x_bind_dn);
+ parser.addOption("-bind_password %s #ldap bind password",
+ x_bind_password);
+ parser.addOption("-base_dn %s #base dn",
+ x_base_dn);
+ parser.addOption("-db_name %s #db name",
+ x_db_name);
+ parser.addOption("-secure_conn %s #use ldaps port (optional, default is false)", x_secure_conn);
+ parser.addOption("-remove_data %s #remove existing data under base_dn (optional, default is false) ", x_remove_data);
+ parser.addOption("-clone_start_tls %s #use startTLS for cloning replication agreement (optional, default is false)", x_clone_start_tls);
// key and algorithm options (default)
parser.addOption("-key_type %s #Key type [RSA,ECC] (optional, default is RSA)", x_key_type);
@@ -1083,62 +1054,65 @@ public class ConfigureOCSP
parser.addOption("-signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_signing_key_curvename);
parser.addOption("-signing_signingalgorithm %s #Algorithm used be ocsp signing cert to sign objects (optional, default is signing_algorithm)", x_signing_signingalgorithm);
- // key and algorithm options for audit_signing certificate (overrides default)
+ // key and algorithm options for audit_signing certificate (overrides
+ // default)
parser.addOption("-audit_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_audit_signing_key_type);
parser.addOption("-audit_signing_key_size %s #Key Size (optional, for RSA default is key_size)", x_audit_signing_key_size);
parser.addOption("-audit_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_audit_signing_key_curvename);
- // key and algorithm options for subsystem certificate (overrides default)
+ // key and algorithm options for subsystem certificate (overrides
+ // default)
parser.addOption("-subsystem_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_subsystem_key_type);
parser.addOption("-subsystem_key_size %s #Key Size (optional, for RSA default is key_size)", x_subsystem_key_size);
parser.addOption("-subsystem_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_subsystem_key_curvename);
- // key and algorithm options for sslserver certificate (overrides default)
+ // key and algorithm options for sslserver certificate (overrides
+ // default)
parser.addOption("-sslserver_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_sslserver_key_type);
parser.addOption("-sslserver_key_size %s #Key Size (optional, for RSA default is key_size)", x_sslserver_key_size);
parser.addOption("-sslserver_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_sslserver_key_curvename);
- parser.addOption ("-token_name %s #HSM/Software Token name",
- x_token_name);
- parser.addOption ("-token_pwd %s #HSM/Software Token password (optional, required for HSM)",
- x_token_pwd);
+ parser.addOption("-token_name %s #HSM/Software Token name",
+ x_token_name);
+ parser.addOption("-token_pwd %s #HSM/Software Token password (optional, required for HSM)",
+ x_token_pwd);
- parser.addOption ("-agent_key_size %s #Agent Cert Key Size",
- x_agent_key_size);
- parser.addOption ("-agent_key_type %s #Agent Cert Key type [rsa]",
- x_agent_key_type);
- parser.addOption ("-agent_cert_subject %s #Agent Cert Subject",
- x_agent_cert_subject);
+ parser.addOption("-agent_key_size %s #Agent Cert Key Size",
+ x_agent_key_size);
+ parser.addOption("-agent_key_type %s #Agent Cert Key type [rsa]",
+ x_agent_key_type);
+ parser.addOption("-agent_cert_subject %s #Agent Cert Subject",
+ x_agent_cert_subject);
- parser.addOption ("-backup_pwd %s #PKCS12 password",
- x_backup_pwd);
+ parser.addOption("-backup_pwd %s #PKCS12 password",
+ x_backup_pwd);
- parser.addOption (
- "-ocsp_sign_cert_subject_name %s #OCSP cert subject name",
+ parser.addOption(
+ "-ocsp_sign_cert_subject_name %s #OCSP cert subject name",
x_ocsp_sign_cert_subject_name);
- parser.addOption (
- "-ocsp_subsystem_cert_subject_name %s #OCSP subsystem cert subject name",
- x_ocsp_subsystem_cert_subject_name);
- parser.addOption (
- "-ocsp_server_cert_subject_name %s #OCSP server cert subject name",
- x_ocsp_server_cert_subject_name);
-
- parser.addOption("-backup_fname %s #Backup File for p12, (optional, default /root/tmp-ocsp.p12",
+ parser.addOption(
+ "-ocsp_subsystem_cert_subject_name %s #OCSP subsystem cert subject name",
+ x_ocsp_subsystem_cert_subject_name);
+ parser.addOption(
+ "-ocsp_server_cert_subject_name %s #OCSP server cert subject name",
+ x_ocsp_server_cert_subject_name);
+
+ parser.addOption("-backup_fname %s #Backup File for p12, (optional, default /root/tmp-ocsp.p12",
x_backup_fname);
- parser.addOption (
- "-subsystem_name %s #OCSP subsystem name",
- x_subsystem_name);
+ parser.addOption(
+ "-subsystem_name %s #OCSP subsystem name",
+ x_subsystem_name);
parser.addOption(
- "-ocsp_audit_signing_cert_subject_name %s #OCSP audit signing cert subject name",
+ "-ocsp_audit_signing_cert_subject_name %s #OCSP audit signing cert subject name",
x_ocsp_audit_signing_cert_subject_name);
// and then match the arguments
- String [] unmatched = null;
- unmatched = parser.matchAllArgs (args,0,ArgParser.EXIT_ON_UNMATCHED);
+ String[] unmatched = null;
+ unmatched = parser.matchAllArgs(args, 0, ArgParser.EXIT_ON_UNMATCHED);
- if (unmatched!=null) {
+ if (unmatched != null) {
System.out.println("ERROR: Argument Mismatch");
System.exit(-1);
}
@@ -1214,26 +1188,25 @@ public class ConfigureOCSP
backup_pwd = x_backup_pwd.value;
backup_fname = set_default(x_backup_fname.value, "/root/tmp-ocsp.p12");
-
- ocsp_sign_cert_subject_name = x_ocsp_sign_cert_subject_name.value ;
- ocsp_subsystem_cert_subject_name =
- x_ocsp_subsystem_cert_subject_name.value;
- ocsp_server_cert_subject_name = x_ocsp_server_cert_subject_name.value ;
- ocsp_audit_signing_cert_subject_name = x_ocsp_audit_signing_cert_subject_name.value;
-
- subsystem_name = x_subsystem_name.value ;
+ ocsp_sign_cert_subject_name = x_ocsp_sign_cert_subject_name.value;
+ ocsp_subsystem_cert_subject_name =
+ x_ocsp_subsystem_cert_subject_name.value;
+ ocsp_server_cert_subject_name = x_ocsp_server_cert_subject_name.value;
+ ocsp_audit_signing_cert_subject_name = x_ocsp_audit_signing_cert_subject_name.value;
+
+ subsystem_name = x_subsystem_name.value;
boolean st = ca.ConfigureOCSPInstance();
-
+
if (!st) {
System.out.println("ERROR: unable to create OCSP");
System.exit(-1);
}
-
+
System.out.println("Certificate System - OCSP Instance Configured");
System.exit(0);
-
+
}
};
diff --git a/pki/base/silent/src/com/netscape/pkisilent/ConfigureRA.java b/pki/base/silent/src/com/netscape/pkisilent/ConfigureRA.java
index fc28e8b4..68978884 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/ConfigureRA.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/ConfigureRA.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -29,927 +30,875 @@ import com.netscape.pkisilent.common.ParseXML;
import com.netscape.pkisilent.http.HTTPClient;
import com.netscape.pkisilent.http.HTTPResponse;
-public class ConfigureRA
-{
-
-
- // define global variables
-
- public static HTTPClient hc = null;
-
- public static String login_uri = "/ra/admin/console/config/login";
- public static String wizard_uri = "/ra/admin/console/config/wizard";
- public static String admin_uri = "/ca/admin/ca/getBySerial";
-
- public static String sd_login_uri = "/ca/admin/ca/securityDomainLogin";
- public static String sd_get_cookie_uri = "/ca/admin/ca/getCookie";
- public static String sd_update_domain_uri = "/ca/agent/ca/updateDomainXML";
- public static String pkcs12_uri = "/ra/admin/console/config/savepkcs12";
-
- public static String cs_hostname = null;
- public static String cs_port = null;
- public static String cs_clientauth_port = null;
-
- public static String sd_hostname = null;
- public static String sd_ssl_port = null;
- public static String sd_agent_port = null;
- public static String sd_admin_port = null;
- public static String sd_admin_name = null;
- public static String sd_admin_password = null;
-
- public static String ca_hostname = null;
- public static String ca_port = null;
- public static String ca_ssl_port = null;
- public static String ca_admin_port = null;
-
- public static String client_certdb_dir = null;
- public static String client_certdb_pwd = null;
-
- // Login Panel
- public static String pin = null;
-
- public static String domain_name = null;
-
- public static String admin_user = null;
- public static String admin_email = null;
- public static String admin_password = null;
- public static String admin_serial_number = null;
- public static String agent_name = null;
-
- public static String key_size = null;
- public static String key_type = null;
- public static String token_name = null;
- public static String token_pwd = null;
-
- public static String agent_key_size = null;
- public static String agent_key_type = null;
- public static String agent_cert_subject = null;
-
- public static String server_cert_name = null;
- public static String server_cert_req = null;
- public static String server_cert_pp = null;
- public static String server_cert_cert = null;
-
- public static String ra_subsystem_cert_name = null;
- public static String ra_subsystem_cert_req = null;
- public static String ra_subsystem_cert_pp = null;
- public static String ra_subsystem_cert_cert = null;
-
- // names
- public static String ra_server_cert_subject_name = null;
- public static String ra_server_cert_nickname = null;
- public static String ra_subsystem_cert_subject_name = null;
- public static String ra_subsystem_cert_nickname = null;
- public static String subsystem_name = null;
-
- // Security Domain Login Panel
- public static String ra_session_id = null;
-
- // Admin Certificate Request Panel
- public static String requestor_name = null;
-
- public ConfigureRA ()
- {
- // do nothing :)
- }
-
- public void sleep_time()
- {
- try
- {
- System.out.println("Sleeping for 5 secs..");
- Thread.sleep(5000);
- }
- catch(Exception e)
- {
- System.out.println("ERROR: sleep problem");
- }
-
- }
+public class ConfigureRA {
+
+ // define global variables
+
+ public static HTTPClient hc = null;
+
+ public static String login_uri = "/ra/admin/console/config/login";
+ public static String wizard_uri = "/ra/admin/console/config/wizard";
+ public static String admin_uri = "/ca/admin/ca/getBySerial";
+
+ public static String sd_login_uri = "/ca/admin/ca/securityDomainLogin";
+ public static String sd_get_cookie_uri = "/ca/admin/ca/getCookie";
+ public static String sd_update_domain_uri = "/ca/agent/ca/updateDomainXML";
+ public static String pkcs12_uri = "/ra/admin/console/config/savepkcs12";
+
+ public static String cs_hostname = null;
+ public static String cs_port = null;
+ public static String cs_clientauth_port = null;
+
+ public static String sd_hostname = null;
+ public static String sd_ssl_port = null;
+ public static String sd_agent_port = null;
+ public static String sd_admin_port = null;
+ public static String sd_admin_name = null;
+ public static String sd_admin_password = null;
+
+ public static String ca_hostname = null;
+ public static String ca_port = null;
+ public static String ca_ssl_port = null;
+ public static String ca_admin_port = null;
+
+ public static String client_certdb_dir = null;
+ public static String client_certdb_pwd = null;
+
+ // Login Panel
+ public static String pin = null;
+
+ public static String domain_name = null;
+
+ public static String admin_user = null;
+ public static String admin_email = null;
+ public static String admin_password = null;
+ public static String admin_serial_number = null;
+ public static String agent_name = null;
+
+ public static String key_size = null;
+ public static String key_type = null;
+ public static String token_name = null;
+ public static String token_pwd = null;
+
+ public static String agent_key_size = null;
+ public static String agent_key_type = null;
+ public static String agent_cert_subject = null;
+
+ public static String server_cert_name = null;
+ public static String server_cert_req = null;
+ public static String server_cert_pp = null;
+ public static String server_cert_cert = null;
+
+ public static String ra_subsystem_cert_name = null;
+ public static String ra_subsystem_cert_req = null;
+ public static String ra_subsystem_cert_pp = null;
+ public static String ra_subsystem_cert_cert = null;
+
+ // names
+ public static String ra_server_cert_subject_name = null;
+ public static String ra_server_cert_nickname = null;
+ public static String ra_subsystem_cert_subject_name = null;
+ public static String ra_subsystem_cert_nickname = null;
+ public static String subsystem_name = null;
+
+ // Security Domain Login Panel
+ public static String ra_session_id = null;
+
+ // Admin Certificate Request Panel
+ public static String requestor_name = null;
+
+ public ConfigureRA() {
+ // do nothing :)
+ }
+
+ public void sleep_time() {
+ try {
+ System.out.println("Sleeping for 5 secs..");
+ Thread.sleep(5000);
+ } catch (Exception e) {
+ System.out.println("ERROR: sleep problem");
+ }
+
+ }
+
+ public boolean LoginPanel() {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+
+ String query_string = "pin=" + pin + "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, login_uri, query_string);
+ System.out.println("xml returned: " + hr.getHTML());
+
+ // parse xml here - nothing to parse
+
+ // no cookie for ra
+ // get cookie
+ String temp = hr.getCookieValue("pin");
+
+ if (temp != null) {
+ int index = temp.indexOf(";");
+ HTTPClient.j_session_id = temp.substring(0, index);
+ st = true;
+ }
+
+ hr = null;
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
+ "p=0&op=next&xml=true");
+
+ // parse xml here
+
+ bais = new ByteArrayInputStream(
+ hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ st = true;
+ return st;
+ }
+
+ public boolean DomainPanel() {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+
+ String domain_url = "https://" + sd_hostname + ":" + sd_admin_port;
+
+ String query_string = "p=1" +
+ "&choice=existingdomain" +
+ "&sdomainURL=" +
+ URLEncoder.encode(domain_url) +
+ "&op=next" +
+ "&xml=true";
- public boolean LoginPanel()
- {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
-
- String query_string = "pin=" + pin + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname,cs_port,login_uri,query_string);
- System.out.println("xml returned: " + hr.getHTML());
-
- // parse xml here - nothing to parse
-
- // no cookie for ra
- // get cookie
- String temp = hr.getCookieValue("pin");
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- if(temp!=null)
- {
- int index = temp.indexOf(";");
- HTTPClient.j_session_id = temp.substring(0,index);
- st = true;
- }
-
- hr = null;
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,
- "p=0&op=next&xml=true");
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
- // parse xml here
+ return true;
- bais = new ByteArrayInputStream(
- hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
+ }
- st = true;
- return st;
- }
+ public boolean DisplayChainPanel() {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+ String query_string = null;
- public boolean DomainPanel()
- {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
-
-
- String domain_url = "https://" + sd_hostname + ":" + sd_admin_port ;
-
- String query_string = "p=1" +
- "&choice=existingdomain" +
- "&sdomainURL=" +
- URLEncoder.encode(domain_url) +
- "&op=next" +
- "&xml=true" ;
-
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
-
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- return true;
-
- }
-
- public boolean DisplayChainPanel()
- {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
- String query_string = null;
-
- query_string = "p=2" + "&op=next" + "&xml=true";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
-
- return true;
+ query_string = "p=2" + "&op=next" + "&xml=true";
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- }
+ return true;
- public boolean SecurityDomainLoginPanel()
- {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
+ }
+ public boolean SecurityDomainLoginPanel() {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
- String ra_url = "https://" + cs_hostname + ":" + cs_port +
- "/ra/admin/console/config/wizard" +
- "?p=3&subsystem=RA" ;
+ String ra_url = "https://" + cs_hostname + ":" + cs_port +
+ "/ra/admin/console/config/wizard" +
+ "?p=3&subsystem=RA";
- String query_string = "url=" + URLEncoder.encode(ra_url) + "";
+ String query_string = "url=" + URLEncoder.encode(ra_url) + "";
- hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_login_uri,query_string);
+ hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_login_uri, query_string);
- String query_string_1 = "uid=" + sd_admin_name +
- "&pwd=" + URLEncoder.encode(sd_admin_password) +
- "&url=" + URLEncoder.encode(ra_url) +
- "" ;
+ String query_string_1 = "uid=" + sd_admin_name +
+ "&pwd=" + URLEncoder.encode(sd_admin_password) +
+ "&url=" + URLEncoder.encode(ra_url) +
+ "";
- hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_get_cookie_uri,
- query_string_1);
+ hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_get_cookie_uri,
+ query_string_1);
- // get session id from security domain
- sleep_time();
+ // get session id from security domain
+ sleep_time();
- ra_session_id = hr.getContentValue("header.session_id");
- String ra_url_1 = hr.getContentValue("header.url");
+ ra_session_id = hr.getContentValue("header.session_id");
+ String ra_url_1 = hr.getContentValue("header.url");
- System.out.println("RA_SESSION_ID=" + ra_session_id );
- System.out.println("RA_URL=" + ra_url_1 );
+ System.out.println("RA_SESSION_ID=" + ra_session_id);
+ System.out.println("RA_URL=" + ra_url_1);
- // use session id to connect back to RA
+ // use session id to connect back to RA
- String query_string_2 = "p=3" +
- "&subsystem=RA" +
- "&session_id=" + ra_session_id +
- "&xml=true" ;
-
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,
- query_string_2);
-
- // parse xml - no parsing
-
- return true;
-
- }
-
- public boolean SubsystemPanel()
- {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
-
- sleep_time();
- String query_string = "p=3" +
- "&choice=newsubsystem" +
- "&subsystemName=" +
- URLEncoder.encode(subsystem_name) +
- "&op=next" +
- "&xml=true" ;
-
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- sleep_time();
- String ca_url = "https://" + ca_hostname + ":" + ca_ssl_port ;
-
- // CA choice panel
- query_string = "p=4" +
- "&urls=0" +
- "&op=next" +
- "&xml=true" ;
-
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- return true;
- }
-
- public boolean DBPanel()
- {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
-
-
- // SQL LITE PANEL
-
- String query_string = "p=5" + "&op=next" + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
-
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- return true;
- }
-
- public boolean TokenChoicePanel()
- {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
-
- ////////////////////////////////////////////////////////
- String query_string = null;
-
- // Software Token
- if(token_name.equalsIgnoreCase("internal"))
- {
- query_string = "p=6" +
- "&choice=" +
- URLEncoder.encode("NSS Certificate DB") +
- "&op=next" +
- "&xml=true" ;
-
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
- }
- // HSM
- else
- {
- // login to hsm first
- query_string = "p=7" +
- "&uTokName=" +
- URLEncoder.encode(token_name) +
- "&__uPasswd=" +
- URLEncoder.encode(token_pwd) +
- "&op=next" +
- "&xml=true" ;
-
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- // choice with token name now
- query_string = "p=6" +
- "&choice=" +
- URLEncoder.encode(token_name) +
- "&op=next" +
- "&xml=true" ;
-
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- }
-
-
- return true;
- }
-
- public boolean KeyPanel()
- {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
-
-
- String query_string = "p=8" +
- "&keytype=" + key_type +
- "&choice=default"+
- "&custom_size=" + key_size +
- "&sslserver_keytype=" + key_type +
- "&sslserver_choice=custom" +
- "&sslserver_custom_size=" + key_size +
- "&subsystem_keytype=" + key_type +
- "&subsystem_choice=custom" +
- "&subsystem_custom_size=" + key_size +
- "&op=next" +
- "&xml=true" ;
-
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
-
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- return true;
- }
-
- public boolean CertSubjectPanel()
- {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
- ArrayList<String> req_list = null;
- ArrayList<String> cert_list = null;
- ArrayList<String> dn_list = null;
-
- String ca_url = "https://" + ca_hostname + ":" + ca_ssl_port ;
-
- String query_string = "p=9" +
- "&sslserver=" +
- URLEncoder.encode(ra_server_cert_subject_name) +
- "&sslserver_nick=" +
- URLEncoder.encode(ra_server_cert_nickname) +
- "&subsystem=" +
- URLEncoder.encode(ra_subsystem_cert_subject_name) +
- "&subsystem_nick=" +
- URLEncoder.encode(ra_subsystem_cert_nickname) +
- "&urls=0" +
- "&op=next" +
- "&xml=true" ;
-
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
-
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- return true;
- }
-
- public boolean CertificatePanel()
- {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
-
-
- String query_string = "p=10" +
- "&sslserver=" +
- "&sslserver_cc=" +
- "&subsystem=" +
- "&subsystem_cc=" +
- "&op=next" +
- "&xml=true" ;
-
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
-
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- return true;
- }
-
- public boolean AdminCertReqPanel()
- {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
- String admin_cert_request = null;
-
- requestor_name = "RA-" + cs_hostname + "-" + cs_clientauth_port;
-
- ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
- client_certdb_pwd,
- agent_cert_subject,
- agent_key_size,
- agent_key_type);
- cCrypt.setDebug(true);
- cCrypt.setGenerateRequest(true);
- cCrypt.setTransportCert(null);
- cCrypt.setDualKey(false);
- cCrypt.loginDB();
-
- String crmf_request = cCrypt.generateCRMFrequest();
-
- if(crmf_request == null)
- {
- System.out.println("ERROR: AdminCertReqPanel() cert req gen failed");
- return false;
- }
-
- admin_cert_request = crmf_request;
-
- String query_string = "p=11" +
- "&uid=" + admin_user +
- "&name=" +
- URLEncoder.encode("RA Administrator") +
- "&email=" +
- URLEncoder.encode(admin_email) +
- "&__pwd=" + URLEncoder.encode(admin_password) +
- "&__admin_password_again=" + URLEncoder.encode(admin_password) +
- "&cert_request=" +
- URLEncoder.encode(admin_cert_request) +
- "&display=0" +
- "&profileId=" + "caAdminCert" +
- "&cert_request_type=" + "crmf" +
- "&import=true" +
- "&uid=" + admin_user +
- "&clone=0" +
- "&securitydomain=" +
- URLEncoder.encode(domain_name) +
- "&subject=" +
- URLEncoder.encode(agent_cert_subject) +
- "&requestor_name=" +
- URLEncoder.encode( requestor_name ) +
- "&sessionID=" + ra_session_id +
- "&auth_hostname=" + ca_hostname +
- "&auth_port=" + ca_ssl_port +
- "&op=next" +
- "&xml=true" ;
-
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
-
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- admin_serial_number = px.getvalue("serialNumber");
-
- return true;
- }
-
- public boolean AdminCertImportPanel()
- {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
- String cert_to_import = null;
-
- String query_string = "serialNumber=" + admin_serial_number +
- "&importCert=" + "true" +
- "" ;
-
- // NOTE: CA, DRM, OCSP, and TKS use the Security Domain Admin Port;
- // whereas RA and TPS use the CA Admin Port associated with
- // the 'CA choice panel' as invoked from the SubsystemPanel()
- // which MAY or MAY NOT be the same CA as the CA specified
- // by the Security Domain.
- hr = hc.sslConnect(ca_hostname,ca_admin_port,admin_uri,query_string);
-
- try
- {
- // cert_to_import =
- // new sun.misc.BASE64Encoder().encode(hr.getResponseData());
- cert_to_import =
- OSUtil.BtoA(hr.getResponseData());
-
- }
- catch (Exception e)
- {
- System.out.println("ERROR: failed to retrieve cert");
- }
-
- System.out.println("Imported Cert=" + cert_to_import);
-
- ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
- client_certdb_pwd,
- null,
- null,
- null);
- cCrypt.setDebug(true);
- cCrypt.setGenerateRequest(true);
- cCrypt.loginDB();
-
- String start = "-----BEGIN CERTIFICATE-----\r\n" ;
- String end = "\r\n-----END CERTIFICATE-----" ;
-
- st = cCrypt.importCert(start+cert_to_import+end,agent_name);
- if(!st)
- {
- System.out.println("ERROR: AdminCertImportPanel() during cert import");
- return false;
- }
-
- System.out.println("SUCCESS: imported admin user cert");
-
- String query_string_1 = "p=12" +
- "&serialNumber=" + admin_serial_number +
- "&caHost=" +
- URLEncoder.encode( ca_hostname ) +
- "&caPort=" + ca_admin_port +
- "&op=next" +
- "&xml=true" ;
-
- hr = hc.sslConnect( cs_hostname, cs_port, wizard_uri ,query_string_1 );
-
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- return true;
- }
-
- public boolean ConfigureRAInstance()
- {
- // 0. login to cert db
- ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
- client_certdb_pwd,
- null,
- null,
- null);
- cCrypt.setDebug(true);
- cCrypt.setGenerateRequest(true);
- cCrypt.loginDB();
-
- // instantiate http client
- hc = new HTTPClient();
-
- sleep_time();
- // 1. Login panel
- boolean log_st = LoginPanel();
- if(!log_st)
- {
- System.out.println("ERROR: JSESSIONID not found.");
- System.out.println("ERROR: ConfigureRA: LoginPanel() failure");
- return false;
- }
-
- sleep_time();
- // 2. domain panel
- boolean dom_st = DomainPanel();
- if(!dom_st)
- {
- System.out.println("ERROR: ConfigureRA: DomainPanel() failure");
- return false;
- }
-
- sleep_time();
- // 3. display cert chain panel
- boolean disp_st = DisplayChainPanel();
- if(!disp_st)
- {
- System.out.println("ERROR: ConfigureRA: DisplayChainPanel() failure");
- return false;
- }
-
- sleep_time();
- // security domain login panel
- boolean disp_sd = SecurityDomainLoginPanel();
- if(!disp_sd)
- {
- System.out.println("ERROR: ConfigureRA: SecurityDomainLoginPanel() failure");
- return false;
- }
-
- sleep_time();
- // 4. subsystem panel
- boolean disp_ss = SubsystemPanel();
- if(!disp_ss)
- {
- System.out.println("ERROR: ConfigureRA: SubsystemPanel() failure");
- return false;
- }
-
- sleep_time();
- // 5. ldap connection panel
- boolean disp_ldap = DBPanel();
- if(!disp_ldap)
- {
- System.out.println("ERROR: ConfigureRA: DBPanel() failure");
- return false;
- }
-
- sleep_time();
- // 6. Token Choice Panel
- boolean disp_token = TokenChoicePanel();
- if(!disp_token)
- {
- System.out.println("ERROR: ConfigureRA: TokenChoicePanel() failure");
- return false;
- }
-
- sleep_time();
- // 8. Key Panel
- boolean disp_key = KeyPanel();
- if(!disp_key)
- {
- System.out.println("ERROR: ConfigureRA: KeyPanel() failure");
- return false;
- }
-
- sleep_time();
- // 9. Cert Subject Panel
- boolean disp_csubj = CertSubjectPanel();
- if(!disp_csubj)
- {
- System.out.println("ERROR: ConfigureRA: CertSubjectPanel() failure");
- return false;
- }
-
- sleep_time();
- // 10. Certificate Panel
- boolean disp_cp = CertificatePanel();
- if(!disp_cp)
- {
- System.out.println("ERROR: ConfigureRA: CertificatePanel() failure");
- return false;
- }
-
- sleep_time();
- // 11. Admin Cert Req Panel
- boolean disp_adm = AdminCertReqPanel();
- if(!disp_adm)
- {
- System.out.println("ERROR: ConfigureRA: AdminCertReqPanel() failure");
- return false;
- }
-
- sleep_time();
- // 12. Admin Cert import Panel
- boolean disp_im = AdminCertImportPanel();
- if(!disp_im)
- {
- System.out.println("ERROR: ConfigureRA: AdminCertImportPanel() failure");
- return false;
- }
-
- return true;
- }
-
- public static void main(String args[])
- {
- ConfigureRA ca = new ConfigureRA();
-
- // set variables
- StringHolder x_cs_hostname = new StringHolder();
- StringHolder x_cs_port = new StringHolder();
- StringHolder x_cs_clientauth_port = new StringHolder();
-
- StringHolder x_sd_hostname = new StringHolder();
- StringHolder x_sd_ssl_port = new StringHolder();
- StringHolder x_sd_agent_port = new StringHolder();
- StringHolder x_sd_admin_port = new StringHolder();
- StringHolder x_sd_admin_name = new StringHolder();
- StringHolder x_sd_admin_password = new StringHolder();
-
- StringHolder x_ca_hostname = new StringHolder();
- StringHolder x_ca_port = new StringHolder();
- StringHolder x_ca_ssl_port = new StringHolder();
- StringHolder x_ca_admin_port = new StringHolder();
-
- StringHolder x_client_certdb_dir = new StringHolder();
- StringHolder x_client_certdb_pwd = new StringHolder();
- StringHolder x_preop_pin = new StringHolder();
-
- StringHolder x_domain_name = new StringHolder();
-
- StringHolder x_admin_user = new StringHolder();
- StringHolder x_admin_email = new StringHolder();
- StringHolder x_admin_password = new StringHolder();
-
- // key size
- StringHolder x_token_name = new StringHolder();
- StringHolder x_token_pwd = new StringHolder();
- StringHolder x_key_size = new StringHolder();
- StringHolder x_key_type = new StringHolder();
-
- StringHolder x_agent_key_size = new StringHolder();
- StringHolder x_agent_key_type = new StringHolder();
- StringHolder x_agent_cert_subject = new StringHolder();
-
- StringHolder x_agent_name = new StringHolder();
-
- // ra cert subject name params
- StringHolder x_ra_server_cert_subject_name = new StringHolder();
- StringHolder x_ra_server_cert_nickname = new StringHolder();
- StringHolder x_ra_subsystem_cert_subject_name = new StringHolder();
- StringHolder x_ra_subsystem_cert_nickname = new StringHolder();
-
- // subsystemName
- StringHolder x_subsystem_name = new StringHolder();
-
-
- // parse the args
- ArgParser parser = new ArgParser("ConfigureRA");
-
- parser.addOption ("-cs_hostname %s #CS Hostname",
- x_cs_hostname);
- parser.addOption ("-cs_port %s #CS SSL port",
- x_cs_port);
- parser.addOption ("-cs_clientauth_port %s #CS SSL port",
- x_cs_clientauth_port);
-
- parser.addOption ("-sd_hostname %s #Security Domain Hostname",
- x_sd_hostname);
- parser.addOption ("-sd_ssl_port %s #Security Domain SSL EE port",
- x_sd_ssl_port);
- parser.addOption ("-sd_agent_port %s #Security Domain SSL Agent port",
- x_sd_agent_port);
- parser.addOption ("-sd_admin_port %s #Security Domain SSL Admin port",
- x_sd_admin_port);
- parser.addOption ("-sd_admin_name %s #Security Domain username",
- x_sd_admin_name);
- parser.addOption ("-sd_admin_password %s #Security Domain password",
- x_sd_admin_password);
-
- parser.addOption ("-ca_hostname %s #CA Hostname",
- x_ca_hostname);
- parser.addOption ("-ca_port %s #CA non-SSL port",
- x_ca_port);
- parser.addOption ("-ca_ssl_port %s #CA SSL port",
- x_ca_ssl_port);
- parser.addOption ("-ca_admin_port %s #CA SSL Admin port",
- x_ca_admin_port);
-
- parser.addOption ("-client_certdb_dir %s #Client CertDB dir",
- x_client_certdb_dir);
- parser.addOption ("-client_certdb_pwd %s #client certdb password",
- x_client_certdb_pwd);
- parser.addOption ("-preop_pin %s #pre op pin",
- x_preop_pin);
- parser.addOption ("-domain_name %s #domain name",
- x_domain_name);
- parser.addOption ("-admin_user %s #Admin User Name",
- x_admin_user);
- parser.addOption ("-admin_email %s #Admin email",
- x_admin_email);
- parser.addOption ("-admin_password %s #Admin password",
- x_admin_password);
- parser.addOption ("-agent_name %s #Agent Cert Nickname",
- x_agent_name);
-
- parser.addOption ("-token_name %s #HSM/Software Token name",
- x_token_name);
- parser.addOption ("-token_pwd %s #HSM/Software Token password",
- x_token_pwd);
- parser.addOption ("-key_size %s #Key Size",
- x_key_size);
- parser.addOption ("-key_type %s #Key type [rsa,ecc]",
- x_key_type);
-
- parser.addOption ("-agent_key_size %s #Agent Cert Key Size",
- x_agent_key_size);
- parser.addOption ("-agent_key_type %s #Agent cert Key type [rsa]",
- x_agent_key_type);
- parser.addOption ("-agent_cert_subject %s #Agent cert Subject",
- x_agent_cert_subject);
-
- parser.addOption (
- "-ra_server_cert_subject_name %s #RA server cert subject name",
- x_ra_server_cert_subject_name);
- parser.addOption (
- "-ra_server_cert_nickname %s #RA server cert nickname",
- x_ra_server_cert_nickname);
- parser.addOption (
- "-ra_subsystem_cert_subject_name %s #RA subsystem cert subject name",
- x_ra_subsystem_cert_subject_name);
- parser.addOption (
- "-ra_subsystem_cert_nickname %s #RA subsystem cert nickname",
- x_ra_subsystem_cert_nickname);
-
- parser.addOption (
- "-subsystem_name %s #RA subsystem name",
- x_subsystem_name);
-
- // and then match the arguments
- String [] unmatched = null;
- unmatched = parser.matchAllArgs (args,0,ArgParser.EXIT_ON_UNMATCHED);
-
- if(unmatched!=null)
- {
- System.out.println("ERROR: Argument Mismatch");
- System.exit(-1);
- }
-
- // set variables
- cs_hostname = x_cs_hostname.value;
- cs_port = x_cs_port.value;
- cs_clientauth_port = x_cs_clientauth_port.value;
-
- sd_hostname = x_sd_hostname.value;
- sd_ssl_port = x_sd_ssl_port.value;
- sd_agent_port = x_sd_agent_port.value;
- sd_admin_port = x_sd_admin_port.value;
- sd_admin_name = x_sd_admin_name.value;
- sd_admin_password = x_sd_admin_password.value;
-
- ca_hostname = x_ca_hostname.value;
- ca_port = x_ca_port.value;
- ca_ssl_port = x_ca_ssl_port.value;
- ca_admin_port = x_ca_admin_port.value;
-
- client_certdb_dir = x_client_certdb_dir.value;
- client_certdb_pwd = x_client_certdb_pwd.value;
- pin = x_preop_pin.value;
- domain_name = x_domain_name.value;
-
- admin_user = x_admin_user.value;
- admin_email = x_admin_email.value;
- admin_password = x_admin_password.value;
- agent_name = x_agent_name.value;
-
- key_size = x_key_size.value;
- key_type = x_key_type.value;
- token_name = x_token_name.value;
- token_pwd = x_token_pwd.value;
-
- agent_key_size = x_agent_key_size.value;
- agent_key_type = x_agent_key_type.value;
- agent_cert_subject = x_agent_cert_subject.value;
-
- ra_server_cert_subject_name =
- x_ra_server_cert_subject_name.value ;
- ra_server_cert_nickname =
- x_ra_server_cert_nickname.value ;
- ra_subsystem_cert_subject_name =
- x_ra_subsystem_cert_subject_name.value;
- ra_subsystem_cert_nickname =
- x_ra_subsystem_cert_nickname.value;
-
- subsystem_name = x_subsystem_name.value ;
-
-
-
- boolean st = ca.ConfigureRAInstance();
-
- if (!st)
- {
- System.out.println("ERROR: unable to create RA");
- System.exit(-1);
- }
-
- System.out.println("Certificate System - RA Instance Configured");
- System.exit(0);
-
- }
+ String query_string_2 = "p=3" +
+ "&subsystem=RA" +
+ "&session_id=" + ra_session_id +
+ "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
+ query_string_2);
+
+ // parse xml - no parsing
+
+ return true;
+
+ }
+
+ public boolean SubsystemPanel() {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+
+ sleep_time();
+ String query_string = "p=3" +
+ "&choice=newsubsystem" +
+ "&subsystemName=" +
+ URLEncoder.encode(subsystem_name) +
+ "&op=next" +
+ "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ sleep_time();
+ String ca_url = "https://" + ca_hostname + ":" + ca_ssl_port;
+
+ // CA choice panel
+ query_string = "p=4" +
+ "&urls=0" +
+ "&op=next" +
+ "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ return true;
+ }
+
+ public boolean DBPanel() {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+
+ // SQL LITE PANEL
+
+ String query_string = "p=5" + "&op=next" + "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ return true;
+ }
+
+ public boolean TokenChoicePanel() {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+
+ // //////////////////////////////////////////////////////
+ String query_string = null;
+
+ // Software Token
+ if (token_name.equalsIgnoreCase("internal")) {
+ query_string = "p=6" +
+ "&choice=" +
+ URLEncoder.encode("NSS Certificate DB") +
+ "&op=next" +
+ "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+ }
+ // HSM
+ else {
+ // login to hsm first
+ query_string = "p=7" +
+ "&uTokName=" +
+ URLEncoder.encode(token_name) +
+ "&__uPasswd=" +
+ URLEncoder.encode(token_pwd) +
+ "&op=next" +
+ "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ // choice with token name now
+ query_string = "p=6" +
+ "&choice=" +
+ URLEncoder.encode(token_name) +
+ "&op=next" +
+ "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ }
+
+ return true;
+ }
+
+ public boolean KeyPanel() {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+
+ String query_string = "p=8" +
+ "&keytype=" + key_type +
+ "&choice=default" +
+ "&custom_size=" + key_size +
+ "&sslserver_keytype=" + key_type +
+ "&sslserver_choice=custom" +
+ "&sslserver_custom_size=" + key_size +
+ "&subsystem_keytype=" + key_type +
+ "&subsystem_choice=custom" +
+ "&subsystem_custom_size=" + key_size +
+ "&op=next" +
+ "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ return true;
+ }
+
+ public boolean CertSubjectPanel() {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+ ArrayList<String> req_list = null;
+ ArrayList<String> cert_list = null;
+ ArrayList<String> dn_list = null;
+
+ String ca_url = "https://" + ca_hostname + ":" + ca_ssl_port;
+
+ String query_string = "p=9" +
+ "&sslserver=" +
+ URLEncoder.encode(ra_server_cert_subject_name) +
+ "&sslserver_nick=" +
+ URLEncoder.encode(ra_server_cert_nickname) +
+ "&subsystem=" +
+ URLEncoder.encode(ra_subsystem_cert_subject_name) +
+ "&subsystem_nick=" +
+ URLEncoder.encode(ra_subsystem_cert_nickname) +
+ "&urls=0" +
+ "&op=next" +
+ "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ return true;
+ }
+
+ public boolean CertificatePanel() {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+
+ String query_string = "p=10" +
+ "&sslserver=" +
+ "&sslserver_cc=" +
+ "&subsystem=" +
+ "&subsystem_cc=" +
+ "&op=next" +
+ "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ return true;
+ }
+
+ public boolean AdminCertReqPanel() {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+ String admin_cert_request = null;
+
+ requestor_name = "RA-" + cs_hostname + "-" + cs_clientauth_port;
+
+ ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
+ client_certdb_pwd,
+ agent_cert_subject,
+ agent_key_size,
+ agent_key_type);
+ cCrypt.setDebug(true);
+ cCrypt.setGenerateRequest(true);
+ cCrypt.setTransportCert(null);
+ cCrypt.setDualKey(false);
+ cCrypt.loginDB();
+
+ String crmf_request = cCrypt.generateCRMFrequest();
+
+ if (crmf_request == null) {
+ System.out.println("ERROR: AdminCertReqPanel() cert req gen failed");
+ return false;
+ }
+
+ admin_cert_request = crmf_request;
+
+ String query_string = "p=11" +
+ "&uid=" + admin_user +
+ "&name=" +
+ URLEncoder.encode("RA Administrator") +
+ "&email=" +
+ URLEncoder.encode(admin_email) +
+ "&__pwd=" + URLEncoder.encode(admin_password) +
+ "&__admin_password_again=" + URLEncoder.encode(admin_password) +
+ "&cert_request=" +
+ URLEncoder.encode(admin_cert_request) +
+ "&display=0" +
+ "&profileId=" + "caAdminCert" +
+ "&cert_request_type=" + "crmf" +
+ "&import=true" +
+ "&uid=" + admin_user +
+ "&clone=0" +
+ "&securitydomain=" +
+ URLEncoder.encode(domain_name) +
+ "&subject=" +
+ URLEncoder.encode(agent_cert_subject) +
+ "&requestor_name=" +
+ URLEncoder.encode(requestor_name) +
+ "&sessionID=" + ra_session_id +
+ "&auth_hostname=" + ca_hostname +
+ "&auth_port=" + ca_ssl_port +
+ "&op=next" +
+ "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ admin_serial_number = px.getvalue("serialNumber");
+
+ return true;
+ }
+
+ public boolean AdminCertImportPanel() {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+ String cert_to_import = null;
+
+ String query_string = "serialNumber=" + admin_serial_number +
+ "&importCert=" + "true" +
+ "";
+
+ // NOTE: CA, DRM, OCSP, and TKS use the Security Domain Admin Port;
+ // whereas RA and TPS use the CA Admin Port associated with
+ // the 'CA choice panel' as invoked from the SubsystemPanel()
+ // which MAY or MAY NOT be the same CA as the CA specified
+ // by the Security Domain.
+ hr = hc.sslConnect(ca_hostname, ca_admin_port, admin_uri, query_string);
+
+ try {
+ // cert_to_import =
+ // new sun.misc.BASE64Encoder().encode(hr.getResponseData());
+ cert_to_import =
+ OSUtil.BtoA(hr.getResponseData());
+
+ } catch (Exception e) {
+ System.out.println("ERROR: failed to retrieve cert");
+ }
+
+ System.out.println("Imported Cert=" + cert_to_import);
+
+ ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
+ client_certdb_pwd,
+ null,
+ null,
+ null);
+ cCrypt.setDebug(true);
+ cCrypt.setGenerateRequest(true);
+ cCrypt.loginDB();
+
+ String start = "-----BEGIN CERTIFICATE-----\r\n";
+ String end = "\r\n-----END CERTIFICATE-----";
+
+ st = cCrypt.importCert(start + cert_to_import + end, agent_name);
+ if (!st) {
+ System.out.println("ERROR: AdminCertImportPanel() during cert import");
+ return false;
+ }
+
+ System.out.println("SUCCESS: imported admin user cert");
+
+ String query_string_1 = "p=12" +
+ "&serialNumber=" + admin_serial_number +
+ "&caHost=" +
+ URLEncoder.encode(ca_hostname) +
+ "&caPort=" + ca_admin_port +
+ "&op=next" +
+ "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string_1);
+
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ return true;
+ }
+
+ public boolean ConfigureRAInstance() {
+ // 0. login to cert db
+ ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
+ client_certdb_pwd,
+ null,
+ null,
+ null);
+ cCrypt.setDebug(true);
+ cCrypt.setGenerateRequest(true);
+ cCrypt.loginDB();
+
+ // instantiate http client
+ hc = new HTTPClient();
+
+ sleep_time();
+ // 1. Login panel
+ boolean log_st = LoginPanel();
+ if (!log_st) {
+ System.out.println("ERROR: JSESSIONID not found.");
+ System.out.println("ERROR: ConfigureRA: LoginPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 2. domain panel
+ boolean dom_st = DomainPanel();
+ if (!dom_st) {
+ System.out.println("ERROR: ConfigureRA: DomainPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 3. display cert chain panel
+ boolean disp_st = DisplayChainPanel();
+ if (!disp_st) {
+ System.out.println("ERROR: ConfigureRA: DisplayChainPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // security domain login panel
+ boolean disp_sd = SecurityDomainLoginPanel();
+ if (!disp_sd) {
+ System.out.println("ERROR: ConfigureRA: SecurityDomainLoginPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 4. subsystem panel
+ boolean disp_ss = SubsystemPanel();
+ if (!disp_ss) {
+ System.out.println("ERROR: ConfigureRA: SubsystemPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 5. ldap connection panel
+ boolean disp_ldap = DBPanel();
+ if (!disp_ldap) {
+ System.out.println("ERROR: ConfigureRA: DBPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 6. Token Choice Panel
+ boolean disp_token = TokenChoicePanel();
+ if (!disp_token) {
+ System.out.println("ERROR: ConfigureRA: TokenChoicePanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 8. Key Panel
+ boolean disp_key = KeyPanel();
+ if (!disp_key) {
+ System.out.println("ERROR: ConfigureRA: KeyPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 9. Cert Subject Panel
+ boolean disp_csubj = CertSubjectPanel();
+ if (!disp_csubj) {
+ System.out.println("ERROR: ConfigureRA: CertSubjectPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 10. Certificate Panel
+ boolean disp_cp = CertificatePanel();
+ if (!disp_cp) {
+ System.out.println("ERROR: ConfigureRA: CertificatePanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 11. Admin Cert Req Panel
+ boolean disp_adm = AdminCertReqPanel();
+ if (!disp_adm) {
+ System.out.println("ERROR: ConfigureRA: AdminCertReqPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 12. Admin Cert import Panel
+ boolean disp_im = AdminCertImportPanel();
+ if (!disp_im) {
+ System.out.println("ERROR: ConfigureRA: AdminCertImportPanel() failure");
+ return false;
+ }
+
+ return true;
+ }
+
+ public static void main(String args[]) {
+ ConfigureRA ca = new ConfigureRA();
+
+ // set variables
+ StringHolder x_cs_hostname = new StringHolder();
+ StringHolder x_cs_port = new StringHolder();
+ StringHolder x_cs_clientauth_port = new StringHolder();
+
+ StringHolder x_sd_hostname = new StringHolder();
+ StringHolder x_sd_ssl_port = new StringHolder();
+ StringHolder x_sd_agent_port = new StringHolder();
+ StringHolder x_sd_admin_port = new StringHolder();
+ StringHolder x_sd_admin_name = new StringHolder();
+ StringHolder x_sd_admin_password = new StringHolder();
+
+ StringHolder x_ca_hostname = new StringHolder();
+ StringHolder x_ca_port = new StringHolder();
+ StringHolder x_ca_ssl_port = new StringHolder();
+ StringHolder x_ca_admin_port = new StringHolder();
+
+ StringHolder x_client_certdb_dir = new StringHolder();
+ StringHolder x_client_certdb_pwd = new StringHolder();
+ StringHolder x_preop_pin = new StringHolder();
+
+ StringHolder x_domain_name = new StringHolder();
+
+ StringHolder x_admin_user = new StringHolder();
+ StringHolder x_admin_email = new StringHolder();
+ StringHolder x_admin_password = new StringHolder();
+
+ // key size
+ StringHolder x_token_name = new StringHolder();
+ StringHolder x_token_pwd = new StringHolder();
+ StringHolder x_key_size = new StringHolder();
+ StringHolder x_key_type = new StringHolder();
+
+ StringHolder x_agent_key_size = new StringHolder();
+ StringHolder x_agent_key_type = new StringHolder();
+ StringHolder x_agent_cert_subject = new StringHolder();
+
+ StringHolder x_agent_name = new StringHolder();
+
+ // ra cert subject name params
+ StringHolder x_ra_server_cert_subject_name = new StringHolder();
+ StringHolder x_ra_server_cert_nickname = new StringHolder();
+ StringHolder x_ra_subsystem_cert_subject_name = new StringHolder();
+ StringHolder x_ra_subsystem_cert_nickname = new StringHolder();
+
+ // subsystemName
+ StringHolder x_subsystem_name = new StringHolder();
+
+ // parse the args
+ ArgParser parser = new ArgParser("ConfigureRA");
+
+ parser.addOption("-cs_hostname %s #CS Hostname",
+ x_cs_hostname);
+ parser.addOption("-cs_port %s #CS SSL port",
+ x_cs_port);
+ parser.addOption("-cs_clientauth_port %s #CS SSL port",
+ x_cs_clientauth_port);
+
+ parser.addOption("-sd_hostname %s #Security Domain Hostname",
+ x_sd_hostname);
+ parser.addOption("-sd_ssl_port %s #Security Domain SSL EE port",
+ x_sd_ssl_port);
+ parser.addOption("-sd_agent_port %s #Security Domain SSL Agent port",
+ x_sd_agent_port);
+ parser.addOption("-sd_admin_port %s #Security Domain SSL Admin port",
+ x_sd_admin_port);
+ parser.addOption("-sd_admin_name %s #Security Domain username",
+ x_sd_admin_name);
+ parser.addOption("-sd_admin_password %s #Security Domain password",
+ x_sd_admin_password);
+
+ parser.addOption("-ca_hostname %s #CA Hostname",
+ x_ca_hostname);
+ parser.addOption("-ca_port %s #CA non-SSL port",
+ x_ca_port);
+ parser.addOption("-ca_ssl_port %s #CA SSL port",
+ x_ca_ssl_port);
+ parser.addOption("-ca_admin_port %s #CA SSL Admin port",
+ x_ca_admin_port);
+
+ parser.addOption("-client_certdb_dir %s #Client CertDB dir",
+ x_client_certdb_dir);
+ parser.addOption("-client_certdb_pwd %s #client certdb password",
+ x_client_certdb_pwd);
+ parser.addOption("-preop_pin %s #pre op pin",
+ x_preop_pin);
+ parser.addOption("-domain_name %s #domain name",
+ x_domain_name);
+ parser.addOption("-admin_user %s #Admin User Name",
+ x_admin_user);
+ parser.addOption("-admin_email %s #Admin email",
+ x_admin_email);
+ parser.addOption("-admin_password %s #Admin password",
+ x_admin_password);
+ parser.addOption("-agent_name %s #Agent Cert Nickname",
+ x_agent_name);
+
+ parser.addOption("-token_name %s #HSM/Software Token name",
+ x_token_name);
+ parser.addOption("-token_pwd %s #HSM/Software Token password",
+ x_token_pwd);
+ parser.addOption("-key_size %s #Key Size",
+ x_key_size);
+ parser.addOption("-key_type %s #Key type [rsa,ecc]",
+ x_key_type);
+
+ parser.addOption("-agent_key_size %s #Agent Cert Key Size",
+ x_agent_key_size);
+ parser.addOption("-agent_key_type %s #Agent cert Key type [rsa]",
+ x_agent_key_type);
+ parser.addOption("-agent_cert_subject %s #Agent cert Subject",
+ x_agent_cert_subject);
+
+ parser.addOption(
+ "-ra_server_cert_subject_name %s #RA server cert subject name",
+ x_ra_server_cert_subject_name);
+ parser.addOption(
+ "-ra_server_cert_nickname %s #RA server cert nickname",
+ x_ra_server_cert_nickname);
+ parser.addOption(
+ "-ra_subsystem_cert_subject_name %s #RA subsystem cert subject name",
+ x_ra_subsystem_cert_subject_name);
+ parser.addOption(
+ "-ra_subsystem_cert_nickname %s #RA subsystem cert nickname",
+ x_ra_subsystem_cert_nickname);
+
+ parser.addOption(
+ "-subsystem_name %s #RA subsystem name",
+ x_subsystem_name);
+
+ // and then match the arguments
+ String[] unmatched = null;
+ unmatched = parser.matchAllArgs(args, 0, ArgParser.EXIT_ON_UNMATCHED);
+
+ if (unmatched != null) {
+ System.out.println("ERROR: Argument Mismatch");
+ System.exit(-1);
+ }
+
+ // set variables
+ cs_hostname = x_cs_hostname.value;
+ cs_port = x_cs_port.value;
+ cs_clientauth_port = x_cs_clientauth_port.value;
+
+ sd_hostname = x_sd_hostname.value;
+ sd_ssl_port = x_sd_ssl_port.value;
+ sd_agent_port = x_sd_agent_port.value;
+ sd_admin_port = x_sd_admin_port.value;
+ sd_admin_name = x_sd_admin_name.value;
+ sd_admin_password = x_sd_admin_password.value;
+
+ ca_hostname = x_ca_hostname.value;
+ ca_port = x_ca_port.value;
+ ca_ssl_port = x_ca_ssl_port.value;
+ ca_admin_port = x_ca_admin_port.value;
+
+ client_certdb_dir = x_client_certdb_dir.value;
+ client_certdb_pwd = x_client_certdb_pwd.value;
+ pin = x_preop_pin.value;
+ domain_name = x_domain_name.value;
+
+ admin_user = x_admin_user.value;
+ admin_email = x_admin_email.value;
+ admin_password = x_admin_password.value;
+ agent_name = x_agent_name.value;
+
+ key_size = x_key_size.value;
+ key_type = x_key_type.value;
+ token_name = x_token_name.value;
+ token_pwd = x_token_pwd.value;
+
+ agent_key_size = x_agent_key_size.value;
+ agent_key_type = x_agent_key_type.value;
+ agent_cert_subject = x_agent_cert_subject.value;
+
+ ra_server_cert_subject_name =
+ x_ra_server_cert_subject_name.value;
+ ra_server_cert_nickname =
+ x_ra_server_cert_nickname.value;
+ ra_subsystem_cert_subject_name =
+ x_ra_subsystem_cert_subject_name.value;
+ ra_subsystem_cert_nickname =
+ x_ra_subsystem_cert_nickname.value;
+
+ subsystem_name = x_subsystem_name.value;
+
+ boolean st = ca.ConfigureRAInstance();
+
+ if (!st) {
+ System.out.println("ERROR: unable to create RA");
+ System.exit(-1);
+ }
+
+ System.out.println("Certificate System - RA Instance Configured");
+ System.exit(0);
+
+ }
};
diff --git a/pki/base/silent/src/com/netscape/pkisilent/ConfigureSubCA.java b/pki/base/silent/src/com/netscape/pkisilent/ConfigureSubCA.java
index 93d115fc..4e348537 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/ConfigureSubCA.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/ConfigureSubCA.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -29,8 +30,7 @@ import com.netscape.pkisilent.common.ParseXML;
import com.netscape.pkisilent.http.HTTPClient;
import com.netscape.pkisilent.http.HTTPResponse;
-public class ConfigureSubCA
-{
+public class ConfigureSubCA {
// global constants
public static final String DEFAULT_KEY_TYPE = "RSA";
@@ -42,7 +42,7 @@ public class ConfigureSubCA
// define global variables
public static HTTPClient hc = null;
-
+
public static String login_uri = "/ca/admin/console/config/login";
public static String wizard_uri = "/ca/admin/console/config/wizard";
public static String admin_uri = "/ca/admin/ca/getBySerial";
@@ -68,7 +68,7 @@ public class ConfigureSubCA
public static String client_certdb_dir = null;
public static String client_certdb_pwd = null;
- // Login Panel
+ // Login Panel
public static String pin = null;
public static String domain_name = null;
@@ -153,42 +153,36 @@ public class ConfigureSubCA
public static String subsystem_name = null;
- // names
+ // names
public static String subca_sign_cert_subject_name = null;
public static String subca_subsystem_cert_subject_name = null;
public static String subca_ocsp_cert_subject_name = null;
public static String subca_server_cert_subject_name = null;
public static String subca_audit_signing_cert_subject_name = null;
- public ConfigureSubCA ()
- {
+ public ConfigureSubCA() {
// do nothing :)
}
- public void sleep_time()
- {
- try
- {
+ public void sleep_time() {
+ try {
System.out.println("Sleeping for 5 secs..");
Thread.sleep(5000);
- }
- catch(Exception e)
- {
+ } catch (Exception e) {
System.out.println("ERROR: sleep problem");
}
}
- public boolean LoginPanel()
- {
+ public boolean LoginPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "pin=" + pin + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname,cs_port,login_uri,query_string);
+ String query_string = "pin=" + pin + "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, login_uri, query_string);
System.out.println("xml returned: " + hr.getHTML());
// parse xml here - nothing to parse
@@ -196,15 +190,14 @@ public class ConfigureSubCA
// get cookie
String temp = hr.getCookieValue("JSESSIONID");
- if (temp!=null)
- {
+ if (temp != null) {
int index = temp.indexOf(";");
- HTTPClient.j_session_id = temp.substring(0,index);
+ HTTPClient.j_session_id = temp.substring(0, index);
st = true;
}
hr = null;
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
"p=0&op=next&xml=true");
// parse xml here
@@ -217,51 +210,48 @@ public class ConfigureSubCA
return st;
}
- public boolean TokenChoicePanel()
- {
+ public boolean TokenChoicePanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- ///////////////////////////////////////////////////////
+ // /////////////////////////////////////////////////////
String query_string = null;
// Software Token
- if (token_name.equalsIgnoreCase("internal"))
- {
+ if (token_name.equalsIgnoreCase("internal")) {
query_string = "p=1" + "&op=next" + "&xml=true" +
- "&choice=" +
+ "&choice=" +
URLEncoder.encode("Internal Key Storage Token") +
- "";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ "";
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
}
// HSM
- else
- {
+ else {
// login to hsm first
query_string = "p=2" + "&op=next" + "&xml=true" +
- "&uTokName=" +
+ "&uTokName=" +
URLEncoder.encode(token_name) +
- "&__uPasswd=" +
+ "&__uPasswd=" +
URLEncoder.encode(token_pwd) +
- "";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ "";
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
+
// choice with token name now
query_string = "p=1" + "&op=next" + "&xml=true" +
- "&choice=" +
+ "&choice=" +
URLEncoder.encode(token_name) +
- "";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ "";
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
@@ -272,26 +262,24 @@ public class ConfigureSubCA
return true;
}
- public boolean DomainPanel()
- {
+ public boolean DomainPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
-
- String domain_url = "https://" + sd_hostname + ":" + sd_admin_port ;
+ String domain_url = "https://" + sd_hostname + ":" + sd_admin_port;
String query_string = "sdomainURL=" +
URLEncoder.encode(domain_url) +
- "&sdomainName="+
+ "&sdomainName=" +
URLEncoder.encode(domain_name) +
- "&choice=existingdomain"+
+ "&choice=existingdomain" +
"&p=3" +
"&op=next" +
- "&xml=true";
+ "&xml=true";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
@@ -300,35 +288,33 @@ public class ConfigureSubCA
String query_string_1 = "p=4" +
"&op=next" +
- "&xml=true";
+ "&xml=true";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string_1);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string_1);
return true;
}
- public boolean SecurityDomainLoginPanel()
- {
+ public boolean SecurityDomainLoginPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
-
String subca_url = "https://" + cs_hostname + ":" + cs_port +
"/ca/admin/console/config/wizard" +
- "?p=5&subsystem=CA" ;
+ "?p=5&subsystem=CA";
- String query_string = "url=" + URLEncoder.encode(subca_url);
+ String query_string = "url=" + URLEncoder.encode(subca_url);
- hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_login_uri,query_string);
+ hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_login_uri, query_string);
String query_string_1 = "uid=" + sd_admin_name +
"&pwd=" + URLEncoder.encode(sd_admin_password) +
- "&url=" + URLEncoder.encode(subca_url) ;
+ "&url=" + URLEncoder.encode(subca_url);
- hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_get_cookie_uri,
+ hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_get_cookie_uri,
query_string_1);
// get session id from security domain
@@ -336,25 +322,24 @@ public class ConfigureSubCA
String subca_session_id = hr.getContentValue("header.session_id");
String subca_url_1 = hr.getContentValue("header.url");
- System.out.println("SUBCA_SESSION_ID=" + subca_session_id );
- System.out.println("SUBCA_URL=" + subca_url_1 );
+ System.out.println("SUBCA_SESSION_ID=" + subca_session_id);
+ System.out.println("SUBCA_URL=" + subca_url_1);
// use session id to connect back to subCA
String query_string_2 = "p=5" +
"&subsystem=CA" +
"&session_id=" + subca_session_id +
- "&xml=true" ;
+ "&xml=true";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
query_string_2);
return true;
}
- public boolean DisplayChainPanel()
- {
+ public boolean DisplayChainPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -367,8 +352,8 @@ public class ConfigureSubCA
URLEncoder.encode(subsystem_name) +
"&subsystemName=" +
URLEncoder.encode(subsystem_name) +
- "&urls=0" ;
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ "&urls=0";
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
// bais = new ByteArrayInputStream(hr.getHTML().getBytes());
// px.parse(bais);
@@ -377,50 +362,45 @@ public class ConfigureSubCA
return true;
}
- public boolean HierarchyPanel()
- {
+ public boolean HierarchyPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
-
String query_string = "p=8" + "&op=next" + "&xml=true" +
- "&choice=join" ;
+ "&choice=join";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
return true;
}
- public boolean LdapConnectionPanel()
- {
+ public boolean LdapConnectionPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
-
String query_string = "p=9" + "&op=next" + "&xml=true" +
- "&host=" + URLEncoder.encode(ldap_host) +
+ "&host=" + URLEncoder.encode(ldap_host) +
"&port=" + URLEncoder.encode(ldap_port) +
"&basedn=" + URLEncoder.encode(base_dn) +
"&database=" + URLEncoder.encode(db_name) +
"&binddn=" + URLEncoder.encode(bind_dn) +
"&__bindpwd=" + URLEncoder.encode(bind_password) +
"&display=" + URLEncoder.encode("$displayStr") +
- (secure_conn.equals("true")? "&secureConn=on": "") +
- (clone_start_tls.equals("true")? "&cloneStartTLS=on": "") +
- (remove_data.equals("true")? "&removeData=true": "");
+ (secure_conn.equals("true") ? "&secureConn=on" : "") +
+ (clone_start_tls.equals("true") ? "&cloneStartTLS=on" : "") +
+ (remove_data.equals("true") ? "&removeData=true" : "");
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
@@ -430,8 +410,7 @@ public class ConfigureSubCA
return true;
}
- public boolean KeyPanel()
- {
+ public boolean KeyPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -469,23 +448,23 @@ public class ConfigureSubCA
+ "&signingalgorithm=" + signing_algorithm
+ "&keyalgorithm=" + key_algorithm;
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
- al = px.constructValueList("CertReqPair","DN");
+
+ al = px.constructValueList("CertReqPair", "DN");
// get ca cert subject name
if (al != null) {
- for (int i=0; i < al.size(); i++) {
- String temp = al.get(i);
- if (temp.indexOf("Certificate Authority") > 0 ) {
+ for (int i = 0; i < al.size(); i++) {
+ String temp = al.get(i);
+ if (temp.indexOf("Certificate Authority") > 0) {
ca_cert_name = temp;
- } else if (temp.indexOf("OCSP Signing Certificate") > 0 ) {
+ } else if (temp.indexOf("OCSP Signing Certificate") > 0) {
ocsp_cert_name = temp;
- } else if (temp.indexOf("Subsystem Certificate") > 0 ) {
+ } else if (temp.indexOf("Subsystem Certificate") > 0) {
ca_subsystem_cert_name = temp;
} else if (temp.indexOf("Audit Signing Certificate") > 0) {
ca_audit_signing_cert_name = temp;
@@ -494,19 +473,18 @@ public class ConfigureSubCA
}
}
}
-
+
System.out.println("default: ca_cert_name=" + ca_cert_name);
System.out.println("default: ocsp_cert_name=" + ocsp_cert_name);
- System.out.println("default: ca_subsystem_cert_name=" +
+ System.out.println("default: ca_subsystem_cert_name=" +
ca_subsystem_cert_name);
System.out.println("default: server_cert_name=" + server_cert_name);
- System.out.println("default: ca_audit_signing_cert_name=" +
+ System.out.println("default: ca_audit_signing_cert_name=" +
ca_audit_signing_cert_name);
return true;
}
- public boolean CertSubjectPanel()
- {
+ public boolean CertSubjectPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -515,89 +493,87 @@ public class ConfigureSubCA
ArrayList<String> cert_list = null;
ArrayList<String> dn_list = null;
- String domain_url = "https://" + ca_hostname + ":" + ca_ssl_port ;
-
+ String domain_url = "https://" + ca_hostname + ":" + ca_ssl_port;
String query_string = "p=11" + "&op=next" + "&xml=true" +
- "&signing=" +
- URLEncoder.encode(subca_sign_cert_subject_name) +
- "&ocsp_signing=" +
- URLEncoder.encode(subca_ocsp_cert_subject_name) +
- "&sslserver=" +
- URLEncoder.encode(subca_server_cert_subject_name) +
- "&subsystem=" +
- URLEncoder.encode(subca_subsystem_cert_subject_name) +
- "&audit_signing=" +
- URLEncoder.encode(subca_audit_signing_cert_subject_name) +
- "&urls=0" +
- "";
-
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ "&signing=" +
+ URLEncoder.encode(subca_sign_cert_subject_name) +
+ "&ocsp_signing=" +
+ URLEncoder.encode(subca_ocsp_cert_subject_name) +
+ "&sslserver=" +
+ URLEncoder.encode(subca_server_cert_subject_name) +
+ "&subsystem=" +
+ URLEncoder.encode(subca_subsystem_cert_subject_name) +
+ "&audit_signing=" +
+ URLEncoder.encode(subca_audit_signing_cert_subject_name) +
+ "&urls=0" +
+ "";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
- req_list = px.constructValueList("CertReqPair","Request");
- cert_list = px.constructValueList("CertReqPair","Certificate");
- dn_list = px.constructValueList("CertReqPair","Nickname");
+
+ req_list = px.constructValueList("CertReqPair", "Request");
+ cert_list = px.constructValueList("CertReqPair", "Certificate");
+ dn_list = px.constructValueList("CertReqPair", "Nickname");
System.out.println("req_list_size=" + req_list.size());
System.out.println("cert_list_size=" + cert_list.size());
System.out.println("dn_list_size=" + dn_list.size());
if (req_list != null && cert_list != null && dn_list != null) {
- for (int i=0; i < dn_list.size(); i++) {
- String temp = dn_list.get(i);
-
- if (temp.indexOf("caSigningCert") >= 0 ) {
- ca_cert_req = req_list.get(i);
- ca_cert_cert = cert_list.get(i);
- } else if (temp.indexOf("ocspSigningCert") >= 0 ) {
- ocsp_cert_req = req_list.get(i);
- ocsp_cert_cert = cert_list.get(i);
- } else if (temp.indexOf("subsystemCert") >= 0 ) {
- ca_subsystem_cert_req = req_list.get(i);
- ca_subsystem_cert_cert = cert_list.get(i);
- } else if (temp.indexOf("auditSigningCert") >=0) {
- ca_audit_signing_cert_req = req_list.get(i);
- ca_audit_signing_cert_cert = cert_list.get(i);
+ for (int i = 0; i < dn_list.size(); i++) {
+ String temp = dn_list.get(i);
+
+ if (temp.indexOf("caSigningCert") >= 0) {
+ ca_cert_req = req_list.get(i);
+ ca_cert_cert = cert_list.get(i);
+ } else if (temp.indexOf("ocspSigningCert") >= 0) {
+ ocsp_cert_req = req_list.get(i);
+ ocsp_cert_cert = cert_list.get(i);
+ } else if (temp.indexOf("subsystemCert") >= 0) {
+ ca_subsystem_cert_req = req_list.get(i);
+ ca_subsystem_cert_cert = cert_list.get(i);
+ } else if (temp.indexOf("auditSigningCert") >= 0) {
+ ca_audit_signing_cert_req = req_list.get(i);
+ ca_audit_signing_cert_cert = cert_list.get(i);
} else {
- server_cert_req = req_list.get(i);
- server_cert_cert = cert_list.get(i);
+ server_cert_req = req_list.get(i);
+ server_cert_cert = cert_list.get(i);
}
}
}
-
+
System.out.println("ca_cert_name=" + subca_sign_cert_subject_name);
System.out.println("ocsp_cert_name=" + subca_ocsp_cert_subject_name);
- System.out.println("ca_subsystem_cert_name=" +
- subca_subsystem_cert_subject_name);
- System.out.println("server_cert_name=" +
- subca_server_cert_subject_name);
+ System.out.println("ca_subsystem_cert_name=" +
+ subca_subsystem_cert_subject_name);
+ System.out.println("server_cert_name=" +
+ subca_server_cert_subject_name);
System.out.println("audit_signing_cert_name=" +
- subca_audit_signing_cert_subject_name);
+ subca_audit_signing_cert_subject_name);
System.out.println("ca_cert_req=" + ca_cert_req);
System.out.println("ocsp_cert_req=" + ocsp_cert_req);
System.out.println("ca_subsystem_cert_req=" + ca_subsystem_cert_req);
System.out.println("server_cert_req=" + server_cert_req);
System.out.println("ca_audit_siging_cert_req=" +
- ca_audit_signing_cert_req);
+ ca_audit_signing_cert_req);
System.out.println("ca_cert_cert=" + ca_cert_cert);
System.out.println("ocsp_cert_cert=" + ocsp_cert_cert);
System.out.println("ca_subsystem_cert_cert=" + ca_subsystem_cert_cert);
System.out.println("server_cert_cert=" + server_cert_cert);
System.out.println("ca_audit_signing_cert_cert=" +
- ca_audit_signing_cert_cert);
+ ca_audit_signing_cert_cert);
return true;
}
- public boolean CertificatePanel()
- {
+ public boolean CertificatePanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -607,55 +583,52 @@ public class ConfigureSubCA
ArrayList<String> dn_list = null;
ArrayList<String> pp_list = null;
-
String query_string = "p=12" + "&op=next" + "&xml=true" +
- "&signing=" +
- URLEncoder.encode(ca_cert_cert) +
- "&signing_cc=" +
- "&ocsp_signing=" +
+ "&signing=" +
+ URLEncoder.encode(ca_cert_cert) +
+ "&signing_cc=" +
+ "&ocsp_signing=" +
URLEncoder.encode(ocsp_cert_cert) +
- "&ocsp_signing_cc=" +
- "&sslserver=" +
- URLEncoder.encode(server_cert_cert) +
- "&sslserver_cc=" +
- "&subsystem=" +
+ "&ocsp_signing_cc=" +
+ "&sslserver=" +
+ URLEncoder.encode(server_cert_cert) +
+ "&sslserver_cc=" +
+ "&subsystem=" +
URLEncoder.encode(ca_subsystem_cert_cert) +
- "&subsystem_cc=" +
- "&audit_signing=" +
+ "&subsystem_cc=" +
+ "&audit_signing=" +
URLEncoder.encode(ca_audit_signing_cert_cert) +
"&audit_signing_cc=" +
- "";
+ "";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
+
return true;
}
- public boolean BackupPanel()
- {
+ public boolean BackupPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
-
String query_string = "p=13" + "&op=next" + "&xml=true" +
- "&choice=backupkey" +
+ "&choice=backupkey" +
"&__pwd=" + URLEncoder.encode(backup_pwd) +
"&__pwdagain=" + URLEncoder.encode(backup_pwd);
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
+
return true;
}
@@ -666,7 +639,7 @@ public class ConfigureSubCA
ParseXML px = new ParseXML();
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
- "p=15&op=next&xml=true");
+ "p=15&op=next&xml=true");
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
@@ -680,15 +653,13 @@ public class ConfigureSubCA
}
}
- public boolean AdminCertReqPanel()
- {
+ public boolean AdminCertReqPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
String admin_cert_request = null;
-
String cert_subject = "CN=" + "subca-" + admin_user;
ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
@@ -706,19 +677,19 @@ public class ConfigureSubCA
if (crmf_request == null) {
System.out.println("ERROR: AdminCertReqPanel() cert req gen failed");
- return false;
+ return false;
}
admin_cert_request = crmf_request;
String query_string = "p=16" + "&op=next" + "&xml=true" +
"&uid=" + admin_user +
- "&name=" + URLEncoder.encode( agent_name ) +
- "&email=" +
+ "&name=" + URLEncoder.encode(agent_name) +
+ "&email=" +
URLEncoder.encode(admin_email) +
"&__pwd=" + URLEncoder.encode(admin_password) +
"&__admin_password_again=" + URLEncoder.encode(admin_password) +
- "&cert_request=" +
+ "&cert_request=" +
URLEncoder.encode(admin_cert_request) +
"&display=" + URLEncoder.encode("$displayStr") +
"&profileId=" + "caAdminCert" +
@@ -726,25 +697,24 @@ public class ConfigureSubCA
"&import=true" +
"&uid=" + admin_user +
"&securitydomain=" +
- URLEncoder.encode( domain_name ) +
+ URLEncoder.encode(domain_name) +
"&subject=" +
URLEncoder.encode(agent_cert_subject) +
- "";
+ "";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
- admin_serial_number = px.getvalue("serialNumber");
+
+ admin_serial_number = px.getvalue("serialNumber");
return true;
}
- public boolean AdminCertImportPanel()
- {
+ public boolean AdminCertImportPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -752,14 +722,14 @@ public class ConfigureSubCA
String query_string = "serialNumber=" + admin_serial_number +
"&importCert=" + "true" +
- "";
+ "";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, admin_uri, query_string);
- hr = hc.sslConnect(cs_hostname,cs_port,admin_uri,query_string);
-
// get response data
- // String cert_to_import =
- // new sun.misc.BASE64Encoder().encode(hr.getResponseData());
- String cert_to_import =
+ // String cert_to_import =
+ // new sun.misc.BASE64Encoder().encode(hr.getResponseData());
+ String cert_to_import =
OSUtil.BtoA(hr.getResponseData());
System.out.println("Imported Cert=" + cert_to_import);
@@ -772,13 +742,12 @@ public class ConfigureSubCA
cCrypt.setGenerateRequest(true);
cCrypt.loginDB();
- String start = "-----BEGIN CERTIFICATE-----\r\n" ;
- String end = "\r\n-----END CERTIFICATE-----" ;
+ String start = "-----BEGIN CERTIFICATE-----\r\n";
+ String end = "\r\n-----END CERTIFICATE-----";
- st = cCrypt.importCert(start+cert_to_import+end,agent_name);
- if (!st)
- {
- System.out.println("ERROR: AdminCertImportPanel() during cert import");
+ st = cCrypt.importCert(start + cert_to_import + end, agent_name);
+ if (!st) {
+ System.out.println("ERROR: AdminCertImportPanel() during cert import");
return false;
}
@@ -787,8 +756,7 @@ public class ConfigureSubCA
return true;
}
- public boolean UpdateDomainPanel()
- {
+ public boolean UpdateDomainPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -800,15 +768,15 @@ public class ConfigureSubCA
"&caPort=" + URLEncoder.encode(sd_admin_port) +
"&importCert=" + "true" +
"&op=next" + "&xml=true" +
- "";
+ "";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
+
String caHost = px.getvalue("host");
String caPort = px.getvalue("port");
String systemType = px.getvalue("systemType");
@@ -816,12 +784,11 @@ public class ConfigureSubCA
System.out.println("caHost=" + caHost);
System.out.println("caPort=" + caPort);
System.out.println("systemType=" + systemType);
-
+
return true;
}
- public boolean ConfigureSubCAInstance()
- {
+ public boolean ConfigureSubCAInstance() {
// 0. login to cert db
ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
client_certdb_pwd,
@@ -966,8 +933,7 @@ public class ConfigureSubCA
}
}
- public static void main(String args[])
- {
+ public static void main(String args[]) {
ConfigureSubCA ca = new ConfigureSubCA();
// set variables
@@ -995,7 +961,7 @@ public class ConfigureSubCA
StringHolder x_admin_email = new StringHolder();
StringHolder x_admin_password = new StringHolder();
- // ldap
+ // ldap
StringHolder x_ldap_host = new StringHolder();
StringHolder x_ldap_port = new StringHolder();
StringHolder x_bind_dn = new StringHolder();
@@ -1024,7 +990,7 @@ public class ConfigureSubCA
StringHolder x_ocsp_signing_key_type = new StringHolder();
StringHolder x_ocsp_signing_key_curvename = new StringHolder();
StringHolder x_ocsp_signing_signingalgorithm = new StringHolder();
-
+
// key properties (custom - audit_signing)
StringHolder x_audit_signing_key_size = new StringHolder();
StringHolder x_audit_signing_key_type = new StringHolder();
@@ -1058,142 +1024,146 @@ public class ConfigureSubCA
StringHolder x_subca_subsystem_cert_subject_name = new StringHolder();
StringHolder x_subca_ocsp_cert_subject_name = new StringHolder();
StringHolder x_subca_server_cert_subject_name = new StringHolder();
- StringHolder x_subca_audit_signing_cert_subject_name = new StringHolder();
+ StringHolder x_subca_audit_signing_cert_subject_name = new StringHolder();
// parse the args
ArgParser parser = new ArgParser("ConfigureSubCA");
- parser.addOption ("-cs_hostname %s #CS Hostname",
- x_cs_hostname);
- parser.addOption ("-cs_port %s #CS SSL port",
- x_cs_port);
-
- parser.addOption ("-sd_hostname %s #Security Domain Hostname",
- x_sd_hostname);
- parser.addOption ("-sd_ssl_port %s #Security Domain SSL EE port",
- x_sd_ssl_port);
- parser.addOption ("-sd_agent_port %s #Security Domain SSL Agent port",
- x_sd_agent_port);
- parser.addOption ("-sd_admin_port %s #Security Domain SSL Admin port",
- x_sd_admin_port);
- parser.addOption ("-sd_admin_name %s #Security Domain admin name",
- x_sd_admin_name);
- parser.addOption ("-sd_admin_password %s #Security Domain admin password",
- x_sd_admin_password);
-
- parser.addOption ("-ca_hostname %s #CA Hostname",
- x_ca_hostname);
- parser.addOption ("-ca_port %s #CA non-SSL port",
- x_ca_port);
- parser.addOption ("-ca_ssl_port %s #CA SSL port",
- x_ca_ssl_port);
-
- parser.addOption ("-client_certdb_dir %s #Client CertDB dir",
- x_client_certdb_dir);
- parser.addOption ("-client_certdb_pwd %s #client certdb password",
- x_client_certdb_pwd);
- parser.addOption ("-preop_pin %s #pre op pin",
- x_preop_pin);
- parser.addOption ("-domain_name %s #domain name",
- x_domain_name);
- parser.addOption ("-admin_user %s #Admin User Name",
- x_admin_user);
- parser.addOption ("-admin_email %s #Admin email",
- x_admin_email);
- parser.addOption ("-admin_password %s #Admin password",
- x_admin_password);
- parser.addOption ("-agent_name %s #Agent Cert Nickname",
- x_agent_name);
-
- parser.addOption ("-ldap_host %s #ldap host",
- x_ldap_host);
- parser.addOption ("-ldap_port %s #ldap port",
- x_ldap_port);
- parser.addOption ("-bind_dn %s #ldap bind dn",
- x_bind_dn);
- parser.addOption ("-bind_password %s #ldap bind password",
- x_bind_password);
- parser.addOption ("-base_dn %s #base dn",
- x_base_dn);
- parser.addOption ("-db_name %s #db name",
- x_db_name);
- parser.addOption("-secure_conn %s #use ldaps port (optional, default is false)", x_secure_conn);
- parser.addOption("-remove_data %s #remove existing data under base_dn (optional, default is false) ", x_remove_data);
- parser.addOption("-clone_start_tls %s #use startTLS for cloning replication agreement (optional, default is false)", x_clone_start_tls);
+ parser.addOption("-cs_hostname %s #CS Hostname",
+ x_cs_hostname);
+ parser.addOption("-cs_port %s #CS SSL port",
+ x_cs_port);
+
+ parser.addOption("-sd_hostname %s #Security Domain Hostname",
+ x_sd_hostname);
+ parser.addOption("-sd_ssl_port %s #Security Domain SSL EE port",
+ x_sd_ssl_port);
+ parser.addOption("-sd_agent_port %s #Security Domain SSL Agent port",
+ x_sd_agent_port);
+ parser.addOption("-sd_admin_port %s #Security Domain SSL Admin port",
+ x_sd_admin_port);
+ parser.addOption("-sd_admin_name %s #Security Domain admin name",
+ x_sd_admin_name);
+ parser.addOption("-sd_admin_password %s #Security Domain admin password",
+ x_sd_admin_password);
+
+ parser.addOption("-ca_hostname %s #CA Hostname",
+ x_ca_hostname);
+ parser.addOption("-ca_port %s #CA non-SSL port",
+ x_ca_port);
+ parser.addOption("-ca_ssl_port %s #CA SSL port",
+ x_ca_ssl_port);
+
+ parser.addOption("-client_certdb_dir %s #Client CertDB dir",
+ x_client_certdb_dir);
+ parser.addOption("-client_certdb_pwd %s #client certdb password",
+ x_client_certdb_pwd);
+ parser.addOption("-preop_pin %s #pre op pin",
+ x_preop_pin);
+ parser.addOption("-domain_name %s #domain name",
+ x_domain_name);
+ parser.addOption("-admin_user %s #Admin User Name",
+ x_admin_user);
+ parser.addOption("-admin_email %s #Admin email",
+ x_admin_email);
+ parser.addOption("-admin_password %s #Admin password",
+ x_admin_password);
+ parser.addOption("-agent_name %s #Agent Cert Nickname",
+ x_agent_name);
+
+ parser.addOption("-ldap_host %s #ldap host",
+ x_ldap_host);
+ parser.addOption("-ldap_port %s #ldap port",
+ x_ldap_port);
+ parser.addOption("-bind_dn %s #ldap bind dn",
+ x_bind_dn);
+ parser.addOption("-bind_password %s #ldap bind password",
+ x_bind_password);
+ parser.addOption("-base_dn %s #base dn",
+ x_base_dn);
+ parser.addOption("-db_name %s #db name",
+ x_db_name);
+ parser.addOption("-secure_conn %s #use ldaps port (optional, default is false)", x_secure_conn);
+ parser.addOption("-remove_data %s #remove existing data under base_dn (optional, default is false) ", x_remove_data);
+ parser.addOption("-clone_start_tls %s #use startTLS for cloning replication agreement (optional, default is false)", x_clone_start_tls);
// key and algorithm options (default)
- parser.addOption("-key_type %s #Key type [RSA,ECC] (optional, default is RSA)", x_key_type);
- parser.addOption("-key_size %s #Key Size (optional, for RSA default is 2048)", x_key_size);
- parser.addOption("-key_curvename %s #Key Curve Name (optional, for ECC default is nistp256)", x_key_curvename);
+ parser.addOption("-key_type %s #Key type [RSA,ECC] (optional, default is RSA)", x_key_type);
+ parser.addOption("-key_size %s #Key Size (optional, for RSA default is 2048)", x_key_size);
+ parser.addOption("-key_curvename %s #Key Curve Name (optional, for ECC default is nistp256)", x_key_curvename);
parser.addOption("-key_algorithm %s #Key algorithm of the CA certificate (optional, default is SHA256withRSA for RSA and SHA256withEC for ECC)", x_key_algorithm);
parser.addOption("-signing_algorithm %s #Signing algorithm (optional, default is key_algorithm)", x_signing_algorithm);
// key and algorithm options for signing certificate (overrides default)
- parser.addOption("-signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_signing_key_type);
- parser.addOption("-signing_key_size %s #Key Size (optional, for RSA default is key_size)", x_signing_key_size);
- parser.addOption("-signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_signing_key_curvename);
+ parser.addOption("-signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_signing_key_type);
+ parser.addOption("-signing_key_size %s #Key Size (optional, for RSA default is key_size)", x_signing_key_size);
+ parser.addOption("-signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_signing_key_curvename);
parser.addOption("-signing_signingalgorithm %s #Algorithm used be CA cert to sign objects (optional, default is signing_algorithm)", x_signing_signingalgorithm);
- // key and algorithm options for ocsp_signing certificate (overrides default)
- parser.addOption("-ocsp_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_ocsp_signing_key_type);
- parser.addOption("-ocsp_signing_key_size %s #Key Size (optional, for RSA default is key_size)", x_ocsp_signing_key_size);
- parser.addOption("-ocsp_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_ocsp_signing_key_curvename);
+ // key and algorithm options for ocsp_signing certificate (overrides
+ // default)
+ parser.addOption("-ocsp_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_ocsp_signing_key_type);
+ parser.addOption("-ocsp_signing_key_size %s #Key Size (optional, for RSA default is key_size)", x_ocsp_signing_key_size);
+ parser.addOption("-ocsp_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_ocsp_signing_key_curvename);
parser.addOption("-ocsp_signing_signingalgorithm %s #Algorithm used by the OCSP signing cert to sign objects (optional, default is signing_algorithm)", x_ocsp_signing_signingalgorithm);
- // key and algorithm options for audit_signing certificate (overrides default)
- parser.addOption("-audit_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_audit_signing_key_type);
- parser.addOption("-audit_signing_key_size %s #Key Size (optional, for RSA default is key_size)", x_audit_signing_key_size);
- parser.addOption("-audit_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_audit_signing_key_curvename);
-
- // key and algorithm options for subsystem certificate (overrides default)
- parser.addOption("-subsystem_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_subsystem_key_type);
- parser.addOption("-subsystem_key_size %s #Key Size (optional, for RSA default is key_size)", x_subsystem_key_size);
- parser.addOption("-subsystem_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_subsystem_key_curvename);
-
- // key and algorithm options for sslserver certificate (overrides default)
- parser.addOption("-sslserver_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_sslserver_key_type);
- parser.addOption("-sslserver_key_size %s #Key Size (optional, for RSA default is key_size)", x_sslserver_key_size);
- parser.addOption("-sslserver_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_sslserver_key_curvename);
-
- parser.addOption ("-token_name %s #HSM/Software Token name",
- x_token_name);
- parser.addOption ("-token_pwd %s #HSM/Software Token password (optional - required for HSM)",
- x_token_pwd);
-
- parser.addOption ("-agent_key_size %s #Agent Cert Key Size",
- x_agent_key_size);
- parser.addOption ("-agent_key_type %s #Agent Cert Key type [rsa]",
- x_agent_key_type);
- parser.addOption ("-agent_cert_subject %s #Agent Cert Subject",
- x_agent_cert_subject);
-
- parser.addOption ("-backup_pwd %s #PKCS12 backup password",
- x_backup_pwd);
-
- parser.addOption ("-subsystem_name %s #Subsystem name",
- x_subsystem_name);
-
- parser.addOption (
- "-subca_sign_cert_subject_name %s #subCA cert subject name",
+ // key and algorithm options for audit_signing certificate (overrides
+ // default)
+ parser.addOption("-audit_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_audit_signing_key_type);
+ parser.addOption("-audit_signing_key_size %s #Key Size (optional, for RSA default is key_size)", x_audit_signing_key_size);
+ parser.addOption("-audit_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_audit_signing_key_curvename);
+
+ // key and algorithm options for subsystem certificate (overrides
+ // default)
+ parser.addOption("-subsystem_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_subsystem_key_type);
+ parser.addOption("-subsystem_key_size %s #Key Size (optional, for RSA default is key_size)", x_subsystem_key_size);
+ parser.addOption("-subsystem_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_subsystem_key_curvename);
+
+ // key and algorithm options for sslserver certificate (overrides
+ // default)
+ parser.addOption("-sslserver_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_sslserver_key_type);
+ parser.addOption("-sslserver_key_size %s #Key Size (optional, for RSA default is key_size)", x_sslserver_key_size);
+ parser.addOption("-sslserver_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_sslserver_key_curvename);
+
+ parser.addOption("-token_name %s #HSM/Software Token name",
+ x_token_name);
+ parser.addOption("-token_pwd %s #HSM/Software Token password (optional - required for HSM)",
+ x_token_pwd);
+
+ parser.addOption("-agent_key_size %s #Agent Cert Key Size",
+ x_agent_key_size);
+ parser.addOption("-agent_key_type %s #Agent Cert Key type [rsa]",
+ x_agent_key_type);
+ parser.addOption("-agent_cert_subject %s #Agent Cert Subject",
+ x_agent_cert_subject);
+
+ parser.addOption("-backup_pwd %s #PKCS12 backup password",
+ x_backup_pwd);
+
+ parser.addOption("-subsystem_name %s #Subsystem name",
+ x_subsystem_name);
+
+ parser.addOption(
+ "-subca_sign_cert_subject_name %s #subCA cert subject name",
x_subca_sign_cert_subject_name);
- parser.addOption (
- "-subca_subsystem_cert_subject_name %s #subCA subsystem cert subject name",
- x_subca_subsystem_cert_subject_name);
- parser.addOption (
- "-subca_ocsp_cert_subject_name %s #subCA ocsp cert subject name",
- x_subca_ocsp_cert_subject_name);
- parser.addOption (
- "-subca_server_cert_subject_name %s #subCA server cert subject name",
- x_subca_server_cert_subject_name);
- parser.addOption(
+ parser.addOption(
+ "-subca_subsystem_cert_subject_name %s #subCA subsystem cert subject name",
+ x_subca_subsystem_cert_subject_name);
+ parser.addOption(
+ "-subca_ocsp_cert_subject_name %s #subCA ocsp cert subject name",
+ x_subca_ocsp_cert_subject_name);
+ parser.addOption(
+ "-subca_server_cert_subject_name %s #subCA server cert subject name",
+ x_subca_server_cert_subject_name);
+ parser.addOption(
"-subca_audit_signing_cert_subject_name %s #CA audit signing cert subject name",
x_subca_audit_signing_cert_subject_name);
// and then match the arguments
- String [] unmatched = null;
- unmatched = parser.matchAllArgs (args,0,ArgParser.EXIT_ON_UNMATCHED);
+ String[] unmatched = null;
+ unmatched = parser.matchAllArgs(args, 0, ArgParser.EXIT_ON_UNMATCHED);
- if (unmatched!=null) {
+ if (unmatched != null) {
System.out.println("ERROR: Argument Mismatch");
System.exit(-1);
}
@@ -1274,24 +1244,24 @@ public class ConfigureSubCA
backup_pwd = x_backup_pwd.value;
subsystem_name = x_subsystem_name.value;
-
- subca_sign_cert_subject_name = x_subca_sign_cert_subject_name.value ;
- subca_subsystem_cert_subject_name =
+
+ subca_sign_cert_subject_name = x_subca_sign_cert_subject_name.value;
+ subca_subsystem_cert_subject_name =
x_subca_subsystem_cert_subject_name.value;
- subca_ocsp_cert_subject_name = x_subca_ocsp_cert_subject_name.value ;
- subca_server_cert_subject_name = x_subca_server_cert_subject_name.value ;
+ subca_ocsp_cert_subject_name = x_subca_ocsp_cert_subject_name.value;
+ subca_server_cert_subject_name = x_subca_server_cert_subject_name.value;
subca_audit_signing_cert_subject_name = x_subca_audit_signing_cert_subject_name.value;
boolean st = ca.ConfigureSubCAInstance();
-
+
if (!st) {
System.out.println("ERROR: unable to create Subordinate CA");
System.exit(-1);
}
-
+
System.out.println("Certificate System - Subordinate CA Instance Configured.");
System.exit(0);
-
+
}
};
diff --git a/pki/base/silent/src/com/netscape/pkisilent/ConfigureTKS.java b/pki/base/silent/src/com/netscape/pkisilent/ConfigureTKS.java
index d89fb5dd..789609a8 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/ConfigureTKS.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/ConfigureTKS.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -38,8 +39,7 @@ import com.netscape.pkisilent.common.ParseXML;
import com.netscape.pkisilent.http.HTTPClient;
import com.netscape.pkisilent.http.HTTPResponse;
-public class ConfigureTKS
-{
+public class ConfigureTKS {
public static final String DEFAULT_KEY_TYPE = "RSA";
public static final String DEFAULT_KEY_SIZE = "2048";
@@ -48,7 +48,7 @@ public class ConfigureTKS
// define global variables
public static HTTPClient hc = null;
-
+
public static String login_uri = "/tks/admin/console/config/login";
public static String wizard_uri = "/tks/admin/console/config/wizard";
public static String admin_uri = "/ca/admin/ca/getBySerial";
@@ -74,7 +74,7 @@ public class ConfigureTKS
public static String client_certdb_dir = null;
public static String client_certdb_pwd = null;
- // Login Panel
+ // Login Panel
public static String pin = null;
public static String domain_name = null;
@@ -132,41 +132,38 @@ public class ConfigureTKS
public static String tks_audit_signing_cert_req = null;
public static String tks_audit_signing_cert_pp = null;
public static String tks_audit_signing_cert_cert = null;
-
+
public static String backup_pwd = null;
public static String backup_fname = null;
- // names
+ // names
public static String tks_subsystem_cert_subject_name = null;
public static String tks_server_cert_subject_name = null;
public static String subsystem_name = null;
public static String tks_audit_signing_cert_subject_name = null;
- public ConfigureTKS ()
- {
+ public ConfigureTKS() {
// do nothing :)
}
- public void sleep_time()
- {
+ public void sleep_time() {
try {
System.out.println("Sleeping for 5 secs..");
Thread.sleep(5000);
- } catch(Exception e) {
+ } catch (Exception e) {
System.out.println("ERROR: sleep problem");
}
}
- public boolean LoginPanel()
- {
+ public boolean LoginPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "pin=" + pin + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname,cs_port,login_uri,query_string);
+ String query_string = "pin=" + pin + "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, login_uri, query_string);
System.out.println("xml returned: " + hr.getHTML());
// parse xml here - nothing to parse
@@ -174,14 +171,14 @@ public class ConfigureTKS
// get cookie
String temp = hr.getCookieValue("JSESSIONID");
- if (temp!=null) {
+ if (temp != null) {
int index = temp.indexOf(";");
- HTTPClient.j_session_id = temp.substring(0,index);
+ HTTPClient.j_session_id = temp.substring(0, index);
st = true;
}
hr = null;
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
"p=0&op=next&xml=true");
// parse xml here
@@ -194,8 +191,7 @@ public class ConfigureTKS
return st;
}
- public boolean TokenChoicePanel()
- {
+ public boolean TokenChoicePanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -206,10 +202,10 @@ public class ConfigureTKS
// Software Token
if (token_name.equalsIgnoreCase("internal")) {
query_string = "p=1" + "&op=next" + "&xml=true" +
- "&choice=" +
+ "&choice=" +
URLEncoder.encode("Internal Key Storage Token") +
- "";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ "";
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
@@ -219,23 +215,23 @@ public class ConfigureTKS
else {
// login to hsm first
query_string = "p=2" + "&op=next" + "&xml=true" +
- "&uTokName=" +
+ "&uTokName=" +
URLEncoder.encode(token_name) +
- "&__uPasswd=" +
+ "&__uPasswd=" +
URLEncoder.encode(token_pwd) +
- "";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ "";
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
+
// choice with token name now
query_string = "p=1" + "&op=next" + "&xml=true" +
- "&choice=" +
+ "&choice=" +
URLEncoder.encode(token_name) +
- "";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ "";
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
@@ -245,24 +241,22 @@ public class ConfigureTKS
return true;
}
- public boolean DomainPanel()
- {
+ public boolean DomainPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
-
- String domain_url = "https://" + sd_hostname + ":" + sd_admin_port ;
+ String domain_url = "https://" + sd_hostname + ":" + sd_admin_port;
String query_string = "sdomainURL=" +
URLEncoder.encode(domain_url) +
- "&choice=existingdomain"+
+ "&choice=existingdomain" +
"&p=3" +
"&op=next" +
- "&xml=true";
+ "&xml=true";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
@@ -273,16 +267,15 @@ public class ConfigureTKS
}
- public boolean DisplayChainPanel()
- {
+ public boolean DisplayChainPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
String query_string = null;
- query_string = "p=4" + "&op=next" + "&xml=true";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ query_string = "p=4" + "&op=next" + "&xml=true";
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
// bais = new ByteArrayInputStream(hr.getHTML().getBytes());
// px.parse(bais);
@@ -292,27 +285,25 @@ public class ConfigureTKS
}
- public boolean SecurityDomainLoginPanel()
- {
+ public boolean SecurityDomainLoginPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
-
String tks_url = "https://" + cs_hostname + ":" + cs_port +
"/tks/admin/console/config/wizard" +
- "?p=5&subsystem=TKS" ;
+ "?p=5&subsystem=TKS";
- String query_string = "url=" + URLEncoder.encode(tks_url);
+ String query_string = "url=" + URLEncoder.encode(tks_url);
- hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_login_uri,query_string);
+ hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_login_uri, query_string);
String query_string_1 = "uid=" + sd_admin_name +
"&pwd=" + URLEncoder.encode(sd_admin_password) +
- "&url=" + URLEncoder.encode(tks_url) ;
+ "&url=" + URLEncoder.encode(tks_url);
- hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_get_cookie_uri,
+ hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_get_cookie_uri,
query_string_1);
// get session id from security domain
@@ -320,17 +311,17 @@ public class ConfigureTKS
String tks_session_id = hr.getContentValue("header.session_id");
String tks_url_1 = hr.getContentValue("header.url");
- System.out.println("TKS_SESSION_ID=" + tks_session_id );
- System.out.println("TKS_URL=" + tks_url_1 );
+ System.out.println("TKS_SESSION_ID=" + tks_session_id);
+ System.out.println("TKS_URL=" + tks_url_1);
// use session id to connect back to TKS
String query_string_2 = "p=5" +
"&subsystem=TKS" +
"&session_id=" + tks_session_id +
- "&xml=true" ;
+ "&xml=true";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
query_string_2);
// parse xml
@@ -341,20 +332,19 @@ public class ConfigureTKS
return true;
}
-
- public boolean SubsystemPanel()
- {
+
+ public boolean SubsystemPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "p=5" + "&op=next" + "&xml=true" +
+ String query_string = "p=5" + "&op=next" + "&xml=true" +
"&subsystemName=" +
URLEncoder.encode(subsystem_name) +
- "&choice=newsubsystem" ;
+ "&choice=newsubsystem";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
@@ -363,27 +353,25 @@ public class ConfigureTKS
return true;
}
- public boolean LdapConnectionPanel()
- {
+ public boolean LdapConnectionPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
-
String query_string = "p=7" + "&op=next" + "&xml=true" +
- "&host=" + URLEncoder.encode(ldap_host) +
+ "&host=" + URLEncoder.encode(ldap_host) +
"&port=" + URLEncoder.encode(ldap_port) +
"&binddn=" + URLEncoder.encode(bind_dn) +
"&__bindpwd=" + URLEncoder.encode(bind_password) +
"&basedn=" + URLEncoder.encode(base_dn) +
"&database=" + URLEncoder.encode(db_name) +
"&display=" + URLEncoder.encode("$displayStr") +
- (secure_conn.equals("true")? "&secureConn=on": "") +
- (clone_start_tls.equals("true")? "&cloneStartTLS=on": "") +
- (remove_data.equals("true")? "&removeData=true": "");
+ (secure_conn.equals("true") ? "&secureConn=on" : "") +
+ (clone_start_tls.equals("true") ? "&cloneStartTLS=on" : "") +
+ (remove_data.equals("true") ? "&removeData=true" : "");
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
@@ -393,15 +381,13 @@ public class ConfigureTKS
return true;
}
- public boolean KeyPanel()
- {
+ public boolean KeyPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
ArrayList<String> al = null;
-
String query_string = "p=8" + "&op=next" + "&xml=true" +
"&subsystem_custom_size=" + subsystem_key_size +
"&sslserver_custom_size=" + sslserver_key_size +
@@ -411,28 +397,28 @@ public class ConfigureTKS
"&sslserver_custom_curvename=" + sslserver_key_curvename +
"&audit_signing_custom_curvename=" + audit_signing_key_curvename +
"&custom_curvename=" + key_curvename +
- "&subsystem_keytype=" + subsystem_key_type +
- "&sslserver_keytype=" + sslserver_key_type +
+ "&subsystem_keytype=" + subsystem_key_type +
+ "&sslserver_keytype=" + sslserver_key_type +
"&audit_signing_keytype=" + audit_signing_key_type +
- "&keytype=" + key_type +
- "&subsystem_choice=custom"+
- "&sslserver_choice=custom"+
+ "&keytype=" + key_type +
+ "&subsystem_choice=custom" +
+ "&sslserver_choice=custom" +
"&audit_signing_choice=custom" +
"&choice=custom";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
- al = px.constructValueList("CertReqPair","DN");
+
+ al = px.constructValueList("CertReqPair", "DN");
// get ca cert subject name
if (al != null) {
- for (int i=0; i < al.size(); i++) {
- String temp = al.get(i);
- if (temp.indexOf("TKS Subsystem") > 0 ) {
+ for (int i = 0; i < al.size(); i++) {
+ String temp = al.get(i);
+ if (temp.indexOf("TKS Subsystem") > 0) {
tks_subsystem_cert_name = temp;
} else if (temp.indexOf("Audit Signing Certificate") > 0) {
tks_audit_signing_cert_name = temp;
@@ -441,17 +427,16 @@ public class ConfigureTKS
}
}
}
-
- System.out.println("default: tks_subsystem_cert_name=" +
+
+ System.out.println("default: tks_subsystem_cert_name=" +
tks_subsystem_cert_name);
- System.out.println("default: server_cert_name=" +
+ System.out.println("default: server_cert_name=" +
server_cert_name);
System.out.println("default: tks_audit_signing_cert_name=" + tks_audit_signing_cert_name);
return true;
}
- public boolean CertSubjectPanel()
- {
+ public boolean CertSubjectPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -460,52 +445,51 @@ public class ConfigureTKS
ArrayList<String> cert_list = null;
ArrayList<String> dn_list = null;
- String domain_url = "https://" + ca_hostname + ":" + ca_ssl_port ;
+ String domain_url = "https://" + ca_hostname + ":" + ca_ssl_port;
String query_string = "p=9" + "&op=next" + "&xml=true" +
- "&subsystem=" +
+ "&subsystem=" +
URLEncoder.encode(tks_subsystem_cert_subject_name) +
- "&sslserver=" +
+ "&sslserver=" +
URLEncoder.encode(tks_server_cert_subject_name) +
"&audit_signing=" +
URLEncoder.encode(tks_audit_signing_cert_subject_name) +
- "&urls=" +
- URLEncoder.encode(domain_url) +
- "";
+ "&urls=" +
+ URLEncoder.encode(domain_url) +
+ "";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
- req_list = px.constructValueList("CertReqPair","Request");
- cert_list = px.constructValueList("CertReqPair","Certificate");
- dn_list = px.constructValueList("CertReqPair","Nickname");
+
+ req_list = px.constructValueList("CertReqPair", "Request");
+ cert_list = px.constructValueList("CertReqPair", "Certificate");
+ dn_list = px.constructValueList("CertReqPair", "Nickname");
if (req_list != null && cert_list != null && dn_list != null) {
- for (int i=0; i < dn_list.size(); i++) {
- String temp = dn_list.get(i);
-
- if (temp.indexOf("subsystemCert") >= 0 ) {
- tks_subsystem_cert_req = req_list.get(i);
- tks_subsystem_cert_cert = cert_list.get(i);
- } else if (temp.indexOf("auditSigningCert") >=0) {
- tks_audit_signing_cert_req = req_list.get(i);
- tks_audit_signing_cert_cert = cert_list.get(i);
+ for (int i = 0; i < dn_list.size(); i++) {
+ String temp = dn_list.get(i);
+
+ if (temp.indexOf("subsystemCert") >= 0) {
+ tks_subsystem_cert_req = req_list.get(i);
+ tks_subsystem_cert_cert = cert_list.get(i);
+ } else if (temp.indexOf("auditSigningCert") >= 0) {
+ tks_audit_signing_cert_req = req_list.get(i);
+ tks_audit_signing_cert_cert = cert_list.get(i);
} else {
- server_cert_req = req_list.get(i);
- server_cert_cert = cert_list.get(i);
+ server_cert_req = req_list.get(i);
+ server_cert_cert = cert_list.get(i);
}
}
}
-
+
return true;
}
- public boolean CertificatePanel()
- {
+ public boolean CertificatePanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -515,85 +499,79 @@ public class ConfigureTKS
ArrayList<String> dn_list = null;
ArrayList<String> pp_list = null;
-
String query_string = "p=10" + "&op=next" + "&xml=true" +
- "&subsystem=" +
+ "&subsystem=" +
URLEncoder.encode(tks_subsystem_cert_cert) +
- "&subsystem_cc=" +
- "&sslserver=" +
- URLEncoder.encode(server_cert_cert) +
- "&sslserver_cc=" +
+ "&subsystem_cc=" +
+ "&sslserver=" +
+ URLEncoder.encode(server_cert_cert) +
+ "&sslserver_cc=" +
"&audit_signing=" +
URLEncoder.encode(tks_audit_signing_cert_cert) +
"&audit_signing_cc=" +
- "";
+ "";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
-
+
px.parse(bais);
px.prettyprintxml();
-
+
return true;
}
- public boolean BackupPanel()
- {
+ public boolean BackupPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
-
String query_string = "p=11" + "&op=next" + "&xml=true" +
- "&choice=backupkey" +
+ "&choice=backupkey" +
"&__pwd=" + URLEncoder.encode(backup_pwd) +
- "&__pwdagain=" + URLEncoder.encode(backup_pwd);
+ "&__pwdagain=" + URLEncoder.encode(backup_pwd);
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
+
return true;
}
- public boolean SavePKCS12Panel()
- {
+ public boolean SavePKCS12Panel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
+ String query_string = "";
- String query_string = "";
-
- hr = hc.sslConnect(cs_hostname,cs_port,pkcs12_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, pkcs12_uri, query_string);
// dump hr.getResponseData() to file
- try
- {
+ try {
FileOutputStream fos = new FileOutputStream(backup_fname);
fos.write(hr.getResponseData());
fos.close();
// set file to permissions 600
- String rtParams[] = { "chmod","600", backup_fname};
+ String rtParams[] = { "chmod", "600", backup_fname };
Process proc = Runtime.getRuntime().exec(rtParams);
BufferedReader br = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String line = null;
- while ( (line = br.readLine()) != null)
- System.out.println("Error: " + line);
+ while ((line = br.readLine()) != null)
+ System.out.println("Error: " + line);
int exitVal = proc.waitFor();
-
+
// verify p12 file
-
+
// Decode the P12 file
FileInputStream fis = new FileInputStream(backup_fname);
PFX.Template pfxt = new PFX.Template();
@@ -601,14 +579,14 @@ public class ConfigureTKS
System.out.println("Decoded PFX");
// now peruse it for interesting info
- System.out.println("Version: "+pfx.getVersion());
+ System.out.println("Version: " + pfx.getVersion());
AuthenticatedSafes authSafes = pfx.getAuthSafes();
SEQUENCE asSeq = authSafes.getSequence();
- System.out.println("AuthSafes has "+
- asSeq.size()+" SafeContents");
+ System.out.println("AuthSafes has " +
+ asSeq.size() + " SafeContents");
fis.close();
- } catch(Exception e) {
+ } catch (Exception e) {
System.out.println("ERROR: Exception=" + e.getMessage());
return false;
}
@@ -616,15 +594,13 @@ public class ConfigureTKS
return true;
}
- public boolean AdminCertReqPanel()
- {
+ public boolean AdminCertReqPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
String admin_cert_request = null;
-
String cert_subject = "CN=tks-" + admin_user;
ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
@@ -640,9 +616,8 @@ public class ConfigureTKS
String crmf_request = cCrypt.generateCRMFrequest();
- if (crmf_request == null)
- {
- System.out.println("ERROR: AdminCertReqPanel() cert req gen failed");
+ if (crmf_request == null) {
+ System.out.println("ERROR: AdminCertReqPanel() cert req gen failed");
return false;
}
@@ -655,9 +630,9 @@ public class ConfigureTKS
"&__pwd=" + URLEncoder.encode(admin_password) +
"&__admin_password_again=" + URLEncoder.encode(admin_password) +
"&profileId=" + "caAdminCert" +
- "&email=" +
+ "&email=" +
URLEncoder.encode(admin_email) +
- "&cert_request=" +
+ "&cert_request=" +
URLEncoder.encode(admin_cert_request) +
"&subject=" +
URLEncoder.encode(agent_cert_subject) +
@@ -665,22 +640,21 @@ public class ConfigureTKS
"&import=true" +
"&securitydomain=" +
URLEncoder.encode(domain_name) +
- "";
+ "";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
- admin_serial_number = px.getvalue("serialNumber");
+
+ admin_serial_number = px.getvalue("serialNumber");
return true;
}
- public boolean AdminCertImportPanel()
- {
+ public boolean AdminCertImportPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -688,14 +662,14 @@ public class ConfigureTKS
String query_string = "serialNumber=" + admin_serial_number +
"&importCert=" + "true" +
- "";
+ "";
+
+ hr = hc.sslConnect(sd_hostname, sd_admin_port, admin_uri, query_string);
- hr = hc.sslConnect(sd_hostname,sd_admin_port,admin_uri,query_string);
-
// get response data
- // String cert_to_import =
- // new sun.misc.BASE64Encoder().encode(hr.getResponseData());
- String cert_to_import =
+ // String cert_to_import =
+ // new sun.misc.BASE64Encoder().encode(hr.getResponseData());
+ String cert_to_import =
OSUtil.BtoA(hr.getResponseData());
System.out.println("Imported Cert=" + cert_to_import);
@@ -708,10 +682,10 @@ public class ConfigureTKS
cCrypt.setGenerateRequest(true);
cCrypt.loginDB();
- String start = "-----BEGIN CERTIFICATE-----\r\n" ;
- String end = "\r\n-----END CERTIFICATE-----" ;
+ String start = "-----BEGIN CERTIFICATE-----\r\n";
+ String end = "\r\n-----END CERTIFICATE-----";
- st = cCrypt.importCert(start+cert_to_import+end,agent_name);
+ st = cCrypt.importCert(start + cert_to_import + end, agent_name);
if (!st) {
System.out.println("ERROR: AdminCertImportPanel() during cert import");
return false;
@@ -721,8 +695,7 @@ public class ConfigureTKS
return true;
}
- public boolean UpdateDomainPanel()
- {
+ public boolean UpdateDomainPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -731,21 +704,19 @@ public class ConfigureTKS
String query_string = "p=14" + "&op=next" + "&xml=true" +
"&caHost=" + URLEncoder.encode(sd_hostname) +
"&caPort=" + URLEncoder.encode(sd_agent_port) +
- "";
+ "";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
+
return true;
}
-
- public boolean ConfigureTKSInstance()
- {
+ public boolean ConfigureTKSInstance() {
// 0. login to cert db
ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
client_certdb_pwd,
@@ -806,7 +777,7 @@ public class ConfigureTKS
System.out.println("ERROR: ConfigureTKS: SubsystemPanel() failure");
return false;
}
-
+
sleep_time();
// 7. ldap connection panel
boolean disp_ldap = LdapConnectionPanel();
@@ -892,8 +863,7 @@ public class ConfigureTKS
}
}
- public static void main(String args[])
- {
+ public static void main(String args[]) {
ConfigureTKS ca = new ConfigureTKS();
// set variables
@@ -921,7 +891,7 @@ public class ConfigureTKS
StringHolder x_admin_email = new StringHolder();
StringHolder x_admin_password = new StringHolder();
- // ldap
+ // ldap
StringHolder x_ldap_host = new StringHolder();
StringHolder x_ldap_port = new StringHolder();
StringHolder x_bind_dn = new StringHolder();
@@ -974,122 +944,125 @@ public class ConfigureTKS
// parse the args
ArgParser parser = new ArgParser("ConfigureTKS");
- parser.addOption ("-cs_hostname %s #CS Hostname",
- x_cs_hostname);
- parser.addOption ("-cs_port %s #CS SSL Admin port",
- x_cs_port);
-
- parser.addOption ("-sd_hostname %s #Security Domain Hostname",
- x_sd_hostname);
- parser.addOption ("-sd_ssl_port %s #Security Domain SSL EE port",
- x_sd_ssl_port);
- parser.addOption ("-sd_agent_port %s #Security Domain SSL Agent port",
- x_sd_agent_port);
- parser.addOption ("-sd_admin_port %s #Security Domain SSL Admin port",
- x_sd_admin_port);
- parser.addOption ("-sd_admin_name %s #Security Domain Admin Name",
- x_sd_admin_name);
- parser.addOption ("-sd_admin_password %s #Security Domain Admin password",
- x_sd_admin_password);
-
- parser.addOption ("-ca_hostname %s #CA Hostname",
- x_ca_hostname);
- parser.addOption ("-ca_port %s #CA non-SSL EE port",
- x_ca_port);
- parser.addOption ("-ca_ssl_port %s #CA SSL EE port",
- x_ca_ssl_port);
-
- parser.addOption ("-client_certdb_dir %s #Client CertDB dir",
- x_client_certdb_dir);
- parser.addOption ("-client_certdb_pwd %s #client certdb password",
- x_client_certdb_pwd);
- parser.addOption ("-preop_pin %s #pre op pin",
- x_preop_pin);
- parser.addOption ("-domain_name %s #domain name",
- x_domain_name);
- parser.addOption ("-admin_user %s #Admin User Name",
- x_admin_user);
- parser.addOption ("-admin_email %s #Admin email",
- x_admin_email);
- parser.addOption ("-admin_password %s #Admin password",
- x_admin_password);
- parser.addOption ("-agent_name %s #Agent Cert Nickname",
- x_agent_name);
-
- parser.addOption ("-ldap_host %s #ldap host",
- x_ldap_host);
- parser.addOption ("-ldap_port %s #ldap port",
- x_ldap_port);
- parser.addOption ("-bind_dn %s #ldap bind dn",
- x_bind_dn);
- parser.addOption ("-bind_password %s #ldap bind password",
- x_bind_password);
- parser.addOption ("-base_dn %s #base dn",
- x_base_dn);
- parser.addOption ("-db_name %s #db name",
- x_db_name);
- parser.addOption("-secure_conn %s #use ldaps port (optional, default is false)", x_secure_conn);
- parser.addOption("-remove_data %s #remove existing data under base_dn (optional, default is false) ", x_remove_data);
- parser.addOption("-clone_start_tls %s #use startTLS for cloning replication agreement (optional, default is false)", x_clone_start_tls);
+ parser.addOption("-cs_hostname %s #CS Hostname",
+ x_cs_hostname);
+ parser.addOption("-cs_port %s #CS SSL Admin port",
+ x_cs_port);
+
+ parser.addOption("-sd_hostname %s #Security Domain Hostname",
+ x_sd_hostname);
+ parser.addOption("-sd_ssl_port %s #Security Domain SSL EE port",
+ x_sd_ssl_port);
+ parser.addOption("-sd_agent_port %s #Security Domain SSL Agent port",
+ x_sd_agent_port);
+ parser.addOption("-sd_admin_port %s #Security Domain SSL Admin port",
+ x_sd_admin_port);
+ parser.addOption("-sd_admin_name %s #Security Domain Admin Name",
+ x_sd_admin_name);
+ parser.addOption("-sd_admin_password %s #Security Domain Admin password",
+ x_sd_admin_password);
+
+ parser.addOption("-ca_hostname %s #CA Hostname",
+ x_ca_hostname);
+ parser.addOption("-ca_port %s #CA non-SSL EE port",
+ x_ca_port);
+ parser.addOption("-ca_ssl_port %s #CA SSL EE port",
+ x_ca_ssl_port);
+
+ parser.addOption("-client_certdb_dir %s #Client CertDB dir",
+ x_client_certdb_dir);
+ parser.addOption("-client_certdb_pwd %s #client certdb password",
+ x_client_certdb_pwd);
+ parser.addOption("-preop_pin %s #pre op pin",
+ x_preop_pin);
+ parser.addOption("-domain_name %s #domain name",
+ x_domain_name);
+ parser.addOption("-admin_user %s #Admin User Name",
+ x_admin_user);
+ parser.addOption("-admin_email %s #Admin email",
+ x_admin_email);
+ parser.addOption("-admin_password %s #Admin password",
+ x_admin_password);
+ parser.addOption("-agent_name %s #Agent Cert Nickname",
+ x_agent_name);
+
+ parser.addOption("-ldap_host %s #ldap host",
+ x_ldap_host);
+ parser.addOption("-ldap_port %s #ldap port",
+ x_ldap_port);
+ parser.addOption("-bind_dn %s #ldap bind dn",
+ x_bind_dn);
+ parser.addOption("-bind_password %s #ldap bind password",
+ x_bind_password);
+ parser.addOption("-base_dn %s #base dn",
+ x_base_dn);
+ parser.addOption("-db_name %s #db name",
+ x_db_name);
+ parser.addOption("-secure_conn %s #use ldaps port (optional, default is false)", x_secure_conn);
+ parser.addOption("-remove_data %s #remove existing data under base_dn (optional, default is false) ", x_remove_data);
+ parser.addOption("-clone_start_tls %s #use startTLS for cloning replication agreement (optional, default is false)", x_clone_start_tls);
// key and algorithm options (default)
parser.addOption("-key_type %s #Key type [RSA,ECC] (optional, default is RSA)", x_key_type);
parser.addOption("-key_size %s #Key Size (optional, for RSA default is 2048)", x_key_size);
parser.addOption("-key_curvename %s #Key Curve Name (optional, for ECC default is nistp256)", x_key_curvename);
- // key and algorithm options for audit_signing certificate (overrides default)
+ // key and algorithm options for audit_signing certificate (overrides
+ // default)
parser.addOption("-audit_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_audit_signing_key_type);
parser.addOption("-audit_signing_key_size %s #Key Size (optional, for RSA default is key_size)", x_audit_signing_key_size);
parser.addOption("-audit_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_audit_signing_key_curvename);
- // key and algorithm options for subsystem certificate (overrides default)
+ // key and algorithm options for subsystem certificate (overrides
+ // default)
parser.addOption("-subsystem_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_subsystem_key_type);
parser.addOption("-subsystem_key_size %s #Key Size (optional, for RSA default is key_size)", x_subsystem_key_size);
parser.addOption("-subsystem_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_subsystem_key_curvename);
- // key and algorithm options for sslserver certificate (overrides default)
+ // key and algorithm options for sslserver certificate (overrides
+ // default)
parser.addOption("-sslserver_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_sslserver_key_type);
parser.addOption("-sslserver_key_size %s #Key Size (optional, for RSA default is key_size)", x_sslserver_key_size);
parser.addOption("-sslserver_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_sslserver_key_curvename);
- parser.addOption ("-token_name %s #HSM/Software Token name",
- x_token_name);
- parser.addOption ("-token_pwd %s #HSM/Software Token password (optional, required for HSM)",
- x_token_pwd);
-
- parser.addOption ("-agent_key_size %s #Agent Cert Key Size",
- x_agent_key_size);
- parser.addOption ("-agent_key_type %s #Agent Cert Key type [rsa]",
- x_agent_key_type);
- parser.addOption ("-agent_cert_subject %s #Agent Cert Subject",
- x_agent_cert_subject);
-
- parser.addOption ("-backup_pwd %s #PKCS12 password",
- x_backup_pwd);
-
- parser.addOption (
- "-tks_subsystem_cert_subject_name %s #TKS subsystem cert subject name",
- x_tks_subsystem_cert_subject_name);
- parser.addOption (
- "-tks_server_cert_subject_name %s #TKS server cert subject name",
- x_tks_server_cert_subject_name);
-
- parser.addOption("-backup_fname %s #Backup File for p12, (optional, default /root/tmp-tks.p12",
+ parser.addOption("-token_name %s #HSM/Software Token name",
+ x_token_name);
+ parser.addOption("-token_pwd %s #HSM/Software Token password (optional, required for HSM)",
+ x_token_pwd);
+
+ parser.addOption("-agent_key_size %s #Agent Cert Key Size",
+ x_agent_key_size);
+ parser.addOption("-agent_key_type %s #Agent Cert Key type [rsa]",
+ x_agent_key_type);
+ parser.addOption("-agent_cert_subject %s #Agent Cert Subject",
+ x_agent_cert_subject);
+
+ parser.addOption("-backup_pwd %s #PKCS12 password",
+ x_backup_pwd);
+
+ parser.addOption(
+ "-tks_subsystem_cert_subject_name %s #TKS subsystem cert subject name",
+ x_tks_subsystem_cert_subject_name);
+ parser.addOption(
+ "-tks_server_cert_subject_name %s #TKS server cert subject name",
+ x_tks_server_cert_subject_name);
+
+ parser.addOption("-backup_fname %s #Backup File for p12, (optional, default /root/tmp-tks.p12",
x_backup_fname);
- parser.addOption (
- "-subsystem_name %s #CA subsystem name",
- x_subsystem_name);
+ parser.addOption(
+ "-subsystem_name %s #CA subsystem name",
+ x_subsystem_name);
parser.addOption(
- "-tks_audit_signing_cert_subject_name %s #TKS audit signing cert subject name",
+ "-tks_audit_signing_cert_subject_name %s #TKS audit signing cert subject name",
x_tks_audit_signing_cert_subject_name);
// and then match the arguments
- String [] unmatched = null;
- unmatched = parser.matchAllArgs (args,0,ArgParser.EXIT_ON_UNMATCHED);
+ String[] unmatched = null;
+ unmatched = parser.matchAllArgs(args, 0, ArgParser.EXIT_ON_UNMATCHED);
- if (unmatched!=null) {
+ if (unmatched != null) {
System.out.println("ERROR: Argument Mismatch");
System.exit(-1);
}
@@ -1155,25 +1128,25 @@ public class ConfigureTKS
backup_pwd = x_backup_pwd.value;
backup_fname = set_default(x_backup_fname.value, "/root/tmp-tks.p12");
-
- tks_subsystem_cert_subject_name =
- x_tks_subsystem_cert_subject_name.value;
- tks_server_cert_subject_name =
- x_tks_server_cert_subject_name.value ;
-
- subsystem_name = x_subsystem_name.value ;
+
+ tks_subsystem_cert_subject_name =
+ x_tks_subsystem_cert_subject_name.value;
+ tks_server_cert_subject_name =
+ x_tks_server_cert_subject_name.value;
+
+ subsystem_name = x_subsystem_name.value;
tks_audit_signing_cert_subject_name = x_tks_audit_signing_cert_subject_name.value;
boolean st = ca.ConfigureTKSInstance();
-
+
if (!st) {
System.out.println("ERROR: unable to create TKS");
System.exit(-1);
}
-
+
System.out.println("Certificate System - TKS Instance Configured.");
System.exit(0);
-
+
}
};
diff --git a/pki/base/silent/src/com/netscape/pkisilent/ConfigureTPS.java b/pki/base/silent/src/com/netscape/pkisilent/ConfigureTPS.java
index 5273fda7..b3c50eb4 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/ConfigureTPS.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/ConfigureTPS.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -29,1155 +30,1098 @@ import com.netscape.pkisilent.common.ParseXML;
import com.netscape.pkisilent.http.HTTPClient;
import com.netscape.pkisilent.http.HTTPResponse;
-public class ConfigureTPS
-{
- // define global variables
-
- public static HTTPClient hc = null;
-
- public static String login_uri = "/tps/admin/console/config/login";
- public static String wizard_uri = "/tps/admin/console/config/wizard";
- public static String admin_uri = "/ca/admin/ca/getBySerial";
-
- public static String sd_login_uri = "/ca/admin/ca/securityDomainLogin";
- public static String sd_get_cookie_uri = "/ca/admin/ca/getCookie";
- public static String sd_update_domain_uri = "/ca/agent/ca/updateDomainXML";
- public static String pkcs12_uri = "/tps/admin/console/config/savepkcs12";
-
- public static String cs_hostname = null;
- public static String cs_port = null;
- public static String cs_clientauth_port = null;
-
- public static String sd_hostname = null;
- public static String sd_ssl_port = null;
- public static String sd_agent_port = null;
- public static String sd_admin_port = null;
- public static String sd_admin_name = null;
- public static String sd_admin_password = null;
-
- public static String ca_hostname = null;
- public static String ca_port = null;
- public static String ca_ssl_port = null;
- public static String ca_admin_port = null;
-
- public static String drm_hostname = null;
- public static String drm_ssl_port = null;
-
- public static String tks_hostname = null;
- public static String tks_ssl_port = null;
-
- public static String client_certdb_dir = null;
- public static String client_certdb_pwd = null;
-
- // Login Panel
- public static String pin = null;
-
- public static String domain_name = null;
-
- public static String admin_user = null;
- public static String admin_email = null;
- public static String admin_password = null;
- public static String admin_serial_number = null;
- public static String agent_name = null;
-
- public static String ldap_auth_host = null;
- public static String ldap_auth_port = null;
- public static String ldap_auth_base_dn = null;
-
- public static String ldap_host = null;
- public static String ldap_port = null;
- public static String bind_dn = null;
- public static String bind_password = null;
- public static String base_dn = null;
- public static String db_name = null;
-
- public static String key_size = null;
- public static String key_type = null;
- public static String token_name = null;
- public static String token_pwd = null;
-
- public static String agent_key_size = null;
- public static String agent_key_type = null;
- public static String agent_cert_subject = null;
-
- public static String tps_transport_cert_name = null;
- public static String tps_transport_cert_req = null;
- public static String tps_transport_cert_pp = null;
- public static String tps_transport_cert_cert = null;
-
- public static String tps_storage_cert_name = null;
- public static String tps_storage_cert_req = null;
- public static String tps_storage_cert_pp = null;
- public static String tps_storage_cert_cert = null;
-
- public static String server_cert_name = null;
- public static String server_cert_req = null;
- public static String server_cert_pp = null;
- public static String server_cert_cert = null;
-
- public static String tps_subsystem_cert_name = null;
- public static String tps_subsystem_cert_req = null;
- public static String tps_subsystem_cert_pp = null;
- public static String tps_subsystem_cert_cert = null;
-
- public static String tps_audit_signing_cert_name = null;
- public static String tps_audit_signing_cert_req = null;
- public static String tps_audit_signing_cert_pp = null;
- public static String tps_audit_signing_cert_cert = null;
-
- public static String ss_keygen = null;
-
- // names
- public static String tps_server_cert_subject_name = null;
- public static String tps_server_cert_nickname = null;
- public static String tps_subsystem_cert_subject_name = null;
- public static String tps_subsystem_cert_nickname = null;
- public static String tps_audit_signing_cert_subject_name = null;
- public static String tps_audit_signing_cert_nickname = null;
- public static String subsystem_name = null;
-
- // Security Domain Login Panel
- public static String tps_session_id = null;
-
- // Admin Certificate Request Panel
- public static String requestor_name = null;
-
- public ConfigureTPS ()
- {
- // do nothing :)
- }
-
- public void sleep_time()
- {
- try
- {
- System.out.println("Sleeping for 5 secs..");
- Thread.sleep(5000);
- }
- catch(Exception e)
- {
- System.out.println("ERROR: sleep problem");
- }
-
- }
-
- public boolean LoginPanel()
- {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
-
- String query_string = "pin=" + pin + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname,cs_port,login_uri,query_string);
- System.out.println("xml returned: " + hr.getHTML());
-
- // parse xml here - nothing to parse
-
- // no cookie for tps
- // get cookie
- String temp = hr.getCookieValue("pin");
-
- if(temp!=null)
- {
- int index = temp.indexOf(";");
- HTTPClient.j_session_id = temp.substring(0,index);
- st = true;
- }
-
- hr = null;
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,
- "p=0&op=next&xml=true");
+public class ConfigureTPS {
+ // define global variables
+
+ public static HTTPClient hc = null;
+
+ public static String login_uri = "/tps/admin/console/config/login";
+ public static String wizard_uri = "/tps/admin/console/config/wizard";
+ public static String admin_uri = "/ca/admin/ca/getBySerial";
+
+ public static String sd_login_uri = "/ca/admin/ca/securityDomainLogin";
+ public static String sd_get_cookie_uri = "/ca/admin/ca/getCookie";
+ public static String sd_update_domain_uri = "/ca/agent/ca/updateDomainXML";
+ public static String pkcs12_uri = "/tps/admin/console/config/savepkcs12";
+
+ public static String cs_hostname = null;
+ public static String cs_port = null;
+ public static String cs_clientauth_port = null;
+
+ public static String sd_hostname = null;
+ public static String sd_ssl_port = null;
+ public static String sd_agent_port = null;
+ public static String sd_admin_port = null;
+ public static String sd_admin_name = null;
+ public static String sd_admin_password = null;
+
+ public static String ca_hostname = null;
+ public static String ca_port = null;
+ public static String ca_ssl_port = null;
+ public static String ca_admin_port = null;
+
+ public static String drm_hostname = null;
+ public static String drm_ssl_port = null;
+
+ public static String tks_hostname = null;
+ public static String tks_ssl_port = null;
+
+ public static String client_certdb_dir = null;
+ public static String client_certdb_pwd = null;
+
+ // Login Panel
+ public static String pin = null;
+
+ public static String domain_name = null;
+
+ public static String admin_user = null;
+ public static String admin_email = null;
+ public static String admin_password = null;
+ public static String admin_serial_number = null;
+ public static String agent_name = null;
+
+ public static String ldap_auth_host = null;
+ public static String ldap_auth_port = null;
+ public static String ldap_auth_base_dn = null;
+
+ public static String ldap_host = null;
+ public static String ldap_port = null;
+ public static String bind_dn = null;
+ public static String bind_password = null;
+ public static String base_dn = null;
+ public static String db_name = null;
+
+ public static String key_size = null;
+ public static String key_type = null;
+ public static String token_name = null;
+ public static String token_pwd = null;
+
+ public static String agent_key_size = null;
+ public static String agent_key_type = null;
+ public static String agent_cert_subject = null;
+
+ public static String tps_transport_cert_name = null;
+ public static String tps_transport_cert_req = null;
+ public static String tps_transport_cert_pp = null;
+ public static String tps_transport_cert_cert = null;
+
+ public static String tps_storage_cert_name = null;
+ public static String tps_storage_cert_req = null;
+ public static String tps_storage_cert_pp = null;
+ public static String tps_storage_cert_cert = null;
+
+ public static String server_cert_name = null;
+ public static String server_cert_req = null;
+ public static String server_cert_pp = null;
+ public static String server_cert_cert = null;
+
+ public static String tps_subsystem_cert_name = null;
+ public static String tps_subsystem_cert_req = null;
+ public static String tps_subsystem_cert_pp = null;
+ public static String tps_subsystem_cert_cert = null;
+
+ public static String tps_audit_signing_cert_name = null;
+ public static String tps_audit_signing_cert_req = null;
+ public static String tps_audit_signing_cert_pp = null;
+ public static String tps_audit_signing_cert_cert = null;
+
+ public static String ss_keygen = null;
+
+ // names
+ public static String tps_server_cert_subject_name = null;
+ public static String tps_server_cert_nickname = null;
+ public static String tps_subsystem_cert_subject_name = null;
+ public static String tps_subsystem_cert_nickname = null;
+ public static String tps_audit_signing_cert_subject_name = null;
+ public static String tps_audit_signing_cert_nickname = null;
+ public static String subsystem_name = null;
+
+ // Security Domain Login Panel
+ public static String tps_session_id = null;
+
+ // Admin Certificate Request Panel
+ public static String requestor_name = null;
+
+ public ConfigureTPS() {
+ // do nothing :)
+ }
+
+ public void sleep_time() {
+ try {
+ System.out.println("Sleeping for 5 secs..");
+ Thread.sleep(5000);
+ } catch (Exception e) {
+ System.out.println("ERROR: sleep problem");
+ }
+
+ }
+
+ public boolean LoginPanel() {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+
+ String query_string = "pin=" + pin + "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, login_uri, query_string);
+ System.out.println("xml returned: " + hr.getHTML());
+
+ // parse xml here - nothing to parse
+
+ // no cookie for tps
+ // get cookie
+ String temp = hr.getCookieValue("pin");
+
+ if (temp != null) {
+ int index = temp.indexOf(";");
+ HTTPClient.j_session_id = temp.substring(0, index);
+ st = true;
+ }
+
+ hr = null;
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
+ "p=0&op=next&xml=true");
+
+ // parse xml here
+
+ bais = new ByteArrayInputStream(
+ hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ st = true;
+ return st;
+ }
+
+ public boolean DomainPanel() {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+
+ String domain_url = "https://" + sd_hostname + ":" + sd_admin_port;
+
+ String query_string = "p=3" +
+ "&choice=existingdomain" +
+ "&sdomainURL=" +
+ URLEncoder.encode(domain_url) +
+ "&op=next" +
+ "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ return true;
+
+ }
+
+ public boolean DisplayChainPanel() {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+ String query_string = null;
+
+ query_string = "p=4" + "&op=next" + "&xml=true";
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+
+ return true;
+
+ }
+
+ public boolean SecurityDomainLoginPanel() {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+
+ String tps_url = "https://" + cs_hostname + ":" + cs_port +
+ "/tps/admin/console/config/wizard" +
+ "?p=3&subsystem=TPS";
+
+ String query_string = "url=" + URLEncoder.encode(tps_url) + "";
+
+ hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_login_uri, query_string);
+
+ String query_string_1 = "uid=" + sd_admin_name +
+ "&pwd=" + URLEncoder.encode(sd_admin_password) +
+ "&url=" + URLEncoder.encode(tps_url) +
+ "";
+
+ hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_get_cookie_uri,
+ query_string_1);
+
+ // get session id from security domain
+ sleep_time();
- // parse xml here
+ tps_session_id = hr.getContentValue("header.session_id");
+ String tps_url_1 = hr.getContentValue("header.url");
- bais = new ByteArrayInputStream(
- hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- st = true;
- return st;
- }
-
- public boolean DomainPanel()
- {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
-
-
- String domain_url = "https://" + sd_hostname + ":" + sd_admin_port ;
-
- String query_string = "p=3" +
- "&choice=existingdomain" +
- "&sdomainURL=" +
- URLEncoder.encode(domain_url) +
- "&op=next" +
- "&xml=true" ;
-
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
-
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- return true;
-
- }
-
- public boolean DisplayChainPanel()
- {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
- String query_string = null;
-
- query_string = "p=4" + "&op=next" + "&xml=true";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
-
- return true;
-
- }
-
- public boolean SecurityDomainLoginPanel()
- {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
-
-
- String tps_url = "https://" + cs_hostname + ":" + cs_port +
- "/tps/admin/console/config/wizard" +
- "?p=3&subsystem=TPS" ;
-
- String query_string = "url=" + URLEncoder.encode(tps_url) + "";
-
- hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_login_uri,query_string);
-
- String query_string_1 = "uid=" + sd_admin_name +
- "&pwd=" + URLEncoder.encode(sd_admin_password) +
- "&url=" + URLEncoder.encode(tps_url) +
- "" ;
-
- hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_get_cookie_uri,
- query_string_1);
-
- // get session id from security domain
- sleep_time();
-
- tps_session_id = hr.getContentValue("header.session_id");
- String tps_url_1 = hr.getContentValue("header.url");
-
- System.out.println("TPS_SESSION_ID=" + tps_session_id );
- System.out.println("TPS_URL=" + tps_url_1 );
-
- // use session id to connect back to TPS
-
- String query_string_2 = "p=5" +
- "&subsystem=TPS" +
- "&session_id=" + tps_session_id +
- "&xml=true" ;
-
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,
- query_string_2);
-
- // parse xml - no parsing
-
- return true;
-
- }
-
- public boolean SubsystemPanel()
- {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
-
- sleep_time();
- String query_string = "p=5" +
- "&choice=newsubsystem" +
- "&subsystemName=" +
- URLEncoder.encode(subsystem_name) +
- "&op=next" +
- "&xml=true" ;
-
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- sleep_time();
- String ca_url = "https://" + ca_hostname + ":" + ca_ssl_port ;
-
- // CA choice panel
- query_string = "p=6" +
- "&urls=0" +
- "&op=next" +
- "&xml=true" ;
-
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- sleep_time();
- // TKS choice panel
- String tks_url = "https://" + tks_hostname + ":" + tks_ssl_port ;
- query_string = "p=7" +
- "&urls=0" +
- "&op=next" +
- "&xml=true" ;
-
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- // DRM / server side keygen panel
-
- sleep_time();
- if(ss_keygen.equalsIgnoreCase("true"))
- {
- ss_keygen = "keygen";
- }
-
- String drm_url = "https://" + drm_hostname + ":" + drm_ssl_port ;
-
- query_string = "p=8" +
- "&choice=" + ss_keygen +
- "&urls=0" +
- "&op=next" +
- "&xml=true" ;
-
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- return true;
- }
-
- public boolean LdapAuthConnectionPanel()
- {
- // auth db
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
-
-
- String query_string = "p=9" +
- "&host=" +
- URLEncoder.encode(ldap_auth_host) +
- "&port=" +
- URLEncoder.encode(ldap_auth_port) +
- "&basedn=" +
- URLEncoder.encode(ldap_auth_base_dn) +
- "&op=next" +
- "&xml=true" ;
-
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
-
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- return true;
- }
-
- public boolean LdapConnectionPanel()
- {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
-
-
- String query_string = "p=10" +
- "&host=" +
- URLEncoder.encode(ldap_host) +
- "&port=" +
- URLEncoder.encode(ldap_port) +
- "&binddn=" +
- URLEncoder.encode(bind_dn) +
- "&__bindpwd=" +
- URLEncoder.encode(bind_password) +
- "&basedn=" +
- URLEncoder.encode(base_dn) +
- "&database=" +
- URLEncoder.encode(db_name) +
- "&display=" +
- URLEncoder.encode("") +
- "&op=next" +
- "&xml=true" ;
-
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
-
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- return true;
- }
-
- public boolean TokenChoicePanel()
- {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
-
- ////////////////////////////////////////////////////////
- String query_string = null;
-
- // Software Token
- if(token_name.equalsIgnoreCase("internal"))
- {
- query_string = "p=1" +
- "&choice=" +
- URLEncoder.encode("NSS Certificate DB") +
- "&op=next" +
- "&xml=true" ;
-
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
- }
- // HSM
- else
- {
- // login to hsm first
- query_string = "p=2" +
- "&uTokName=" +
- URLEncoder.encode(token_name) +
- "&__uPasswd=" +
- URLEncoder.encode(token_pwd) +
- "&op=next" +
- "&xml=true" ;
-
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- // choice with token name now
- query_string = "p=1" +
- "&choice=" +
- URLEncoder.encode(token_name) +
- "&op=next" +
- "&xml=true" ;
-
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- }
-
-
- return true;
- }
-
- public boolean KeyPanel()
- {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
- ArrayList<String> friendly_list = null;
- ArrayList<String> dn_list = null;
-
-
- String query_string = "p=11" +
- "&keytype=" + key_type +
- "&choice=default" +
- "&custom_size=" + key_size +
- "&sslserver_keytype=" + key_type +
- "&sslserver_choice=custom" +
- "&sslserver_custom_size=" + key_size +
- "&subsystem_keytype=" + key_type +
- "&subsystem_choice=custom"+
- "&subsystem_custom_size=" + key_size +
- "&audit_signing_keytype=" + key_type +
- "&audit_signing_choice=default" +
- "&audit_signing_custom_size=" + key_size +
- "&op=next" +
- "&xml=true" ;
-
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
-
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- return true;
- }
-
- public boolean CertSubjectPanel()
- {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
- ArrayList<String> req_list = null;
- ArrayList<String> cert_list = null;
- ArrayList<String> dn_list = null;
- ArrayList<String> friendly_list = null;
-
- String ca_url = "https://" + ca_hostname + ":" + ca_ssl_port ;
-
- String query_string = "p=12" +
- "&sslserver=" +
- URLEncoder.encode(tps_server_cert_subject_name) +
- "&sslserver_nick=" +
- URLEncoder.encode(tps_server_cert_nickname) +
- "&subsystem=" +
- URLEncoder.encode(tps_subsystem_cert_subject_name) +
- "&subsystem_nick=" +
- URLEncoder.encode(tps_subsystem_cert_nickname) +
- "&audit_signing=" +
- URLEncoder.encode(tps_audit_signing_cert_subject_name) +
- "&audit_signing_nick=" +
- URLEncoder.encode(tps_audit_signing_cert_nickname) +
- "&urls=0" +
- "&op=next" +
- "&xml=true" ;
-
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
-
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- // parse the certs if needed
-
- return true;
- }
-
- public boolean CertificatePanel()
- {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
- ArrayList<String> req_list = null;
- ArrayList<String> cert_list = null;
- ArrayList<String> dn_list = null;
- ArrayList<String> pp_list = null;
-
-
- String query_string = "p=13" +
- "&sslserver=" +
- "&sslserver_cc=" +
- "&subsystem=" +
- "&subsystem_cc=" +
- "&audit_signing=" +
- "&audit_signing_cc=" +
- "&op=next" +
- "&xml=true" ;
-
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
-
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- return true;
- }
-
- public boolean AdminCertReqPanel()
- {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
- String admin_cert_request = null;
-
- requestor_name = "TPS-" + cs_hostname + "-" + cs_clientauth_port;
-
- ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
- client_certdb_pwd,
- agent_cert_subject,
- agent_key_size,
- agent_key_type);
- cCrypt.setDebug(true);
- cCrypt.setGenerateRequest(true);
- cCrypt.setTransportCert(null);
- cCrypt.setDualKey(false);
- cCrypt.loginDB();
-
- String crmf_request = cCrypt.generateCRMFrequest();
-
- if(crmf_request == null)
- {
- System.out.println("ERROR: AdminCertReqPanel() cert req gen failed");
- return false;
- }
-
- admin_cert_request = crmf_request;
-
- String query_string = "p=14" +
- "&uid=" + admin_user +
- "&name=" +
- URLEncoder.encode("TPS Administrator") +
- "&email=" +
- URLEncoder.encode(admin_email) +
- "&__pwd=" + URLEncoder.encode(admin_password) +
- "&__admin_password_again=" + URLEncoder.encode(admin_password) +
- "&cert_request=" +
- URLEncoder.encode(admin_cert_request) +
- "&display=0" +
- "&profileId=" + "caAdminCert" +
- "&cert_request_type=" + "crmf" +
- "&import=true" +
- "&uid=" + admin_user +
- "&clone=0" +
- "&securitydomain=" +
- URLEncoder.encode(domain_name) +
- "&subject=" +
- URLEncoder.encode(agent_cert_subject) +
- "&requestor_name=" +
- URLEncoder.encode( requestor_name ) +
- "&sessionID=" + tps_session_id +
- "&auth_hostname=" + ca_hostname +
- "&auth_port=" + ca_ssl_port +
- "&op=next" +
- "&xml=true" ;
-
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
-
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- admin_serial_number = px.getvalue("serialNumber");
-
- return true;
- }
-
- public boolean AdminCertImportPanel()
- {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
- String cert_to_import = null;
-
- String query_string = "serialNumber=" + admin_serial_number +
- "&importCert=" + "true" +
- "" ;
-
- // NOTE: CA, DRM, OCSP, and TKS use the Security Domain Admin Port;
- // whereas RA and TPS use the CA Admin Port associated with
- // the 'CA choice panel' as invoked from the SubsystemPanel()
- // which MAY or MAY NOT be the same CA as the CA specified
- // by the Security Domain.
- hr = hc.sslConnect(ca_hostname,ca_admin_port,admin_uri,query_string);
-
- try
- {
- // cert_to_import =
- // new sun.misc.BASE64Encoder().encode(hr.getResponseData());
- cert_to_import =
- OSUtil.BtoA(hr.getResponseData());
-
- }
- catch (Exception e)
- {
- System.out.println("ERROR: failed to retrieve cert");
- }
-
- System.out.println("Imported Cert=" + cert_to_import);
-
- ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
- client_certdb_pwd,
- null,
- null,
- null);
- cCrypt.setDebug(true);
- cCrypt.setGenerateRequest(true);
- cCrypt.loginDB();
-
- String start = "-----BEGIN CERTIFICATE-----\r\n" ;
- String end = "\r\n-----END CERTIFICATE-----" ;
-
- st = cCrypt.importCert(start+cert_to_import+end,agent_name);
- if(!st)
- {
- System.out.println("ERROR: AdminCertImportPanel() during cert import");
- return false;
- }
-
- System.out.println("SUCCESS: imported admin user cert");
-
- String query_string_1 = "p=15" +
- "&serialNumber=" + admin_serial_number +
- "&caHost=" +
- URLEncoder.encode( ca_hostname ) +
- "&caPort=" + ca_admin_port +
- "&op=next" +
- "&xml=true" ;
-
- hr = hc.sslConnect( cs_hostname, cs_port, wizard_uri ,query_string_1 );
-
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- return true;
- }
-
- public boolean ConfigureTPSInstance()
- {
- // 0. login to cert db
- ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
- client_certdb_pwd,
- null,
- null,
- null);
- cCrypt.setDebug(true);
- cCrypt.setGenerateRequest(true);
- cCrypt.loginDB();
-
- // instantiate http client
- hc = new HTTPClient();
-
- sleep_time();
- // 1. Login panel
- boolean log_st = LoginPanel();
- if(!log_st)
- {
- System.out.println("ERROR: JSESSIONID not found.");
- System.out.println("ERROR: ConfigureTPS: LoginPanel() failure");
- return false;
- }
-
- sleep_time();
- // 2. Token Choice Panel
- boolean disp_token = TokenChoicePanel();
- if(!disp_token)
- {
- System.out.println("ERROR: ConfigureTPS: TokenChoicePanel() failure");
- return false;
- }
-
- sleep_time();
- // 3. domain panel
- boolean dom_st = DomainPanel();
- if(!dom_st)
- {
- System.out.println("ERROR: ConfigureTPS: DomainPanel() failure");
- return false;
- }
-
- sleep_time();
- // 4. display cert chain panel
- boolean disp_st = DisplayChainPanel();
- if(!disp_st)
- {
- System.out.println("ERROR: ConfigureTPS: DisplayChainPanel() failure");
- return false;
- }
-
- sleep_time();
- // 5. security domain login panel
- boolean disp_sd = SecurityDomainLoginPanel();
- if(!disp_sd)
- {
- System.out.println("ERROR: ConfigureTPS: SecurityDomainLoginPanel() failure");
- return false;
- }
-
- sleep_time();
- // 6. subsystem panel
- boolean disp_ss = SubsystemPanel();
- if(!disp_ss)
- {
- System.out.println("ERROR: ConfigureTPS: SubsystemPanel() failure");
- return false;
- }
-
- sleep_time();
- // 7. ldap auth connection panel
- boolean disp_ldap_auth = LdapAuthConnectionPanel();
- if(!disp_ldap_auth)
- {
- System.out.println("ERROR: ConfigureTPS: LdapAuthConnectionPanel() failure");
- return false;
- }
-
- sleep_time();
- // 8. ldap connection panel
- boolean disp_ldap = LdapConnectionPanel();
- if(!disp_ldap)
- {
- System.out.println("ERROR: ConfigureTPS: LdapConnectionPanel() failure");
- return false;
- }
-
- sleep_time();
- // 11. Key Panel
- boolean disp_key = KeyPanel();
- if(!disp_key)
- {
- System.out.println("ERROR: ConfigureTPS: KeyPanel() failure");
- return false;
- }
-
- sleep_time();
- // 12. Cert Subject Panel
- boolean disp_csubj = CertSubjectPanel();
- if(!disp_csubj)
- {
- System.out.println("ERROR: ConfigureTPS: CertSubjectPanel() failure");
- return false;
- }
-
- sleep_time();
- // 13. Certificate Panel
- boolean disp_cp = CertificatePanel();
- if(!disp_cp)
- {
- System.out.println("ERROR: ConfigureTPS: CertificatePanel() failure");
- return false;
- }
-
- sleep_time();
- // 14. Admin Cert Req Panel
- boolean disp_adm = AdminCertReqPanel();
- if(!disp_adm)
- {
- System.out.println("ERROR: ConfigureTPS: AdminCertReqPanel() failure");
- return false;
- }
-
- sleep_time();
- // 15. Admin Cert import Panel
- boolean disp_im = AdminCertImportPanel();
- if(!disp_im)
- {
- System.out.println("ERROR: ConfigureTPS: AdminCertImportPanel() failure");
- return false;
- }
-
- return true;
- }
-
- public static void main(String args[])
- {
- ConfigureTPS ca = new ConfigureTPS();
-
- // set variables
- StringHolder x_cs_hostname = new StringHolder();
- StringHolder x_cs_port = new StringHolder();
- StringHolder x_cs_clientauth_port = new StringHolder();
-
- StringHolder x_sd_hostname = new StringHolder();
- StringHolder x_sd_ssl_port = new StringHolder();
- StringHolder x_sd_agent_port = new StringHolder();
- StringHolder x_sd_admin_port = new StringHolder();
- StringHolder x_sd_admin_name = new StringHolder();
- StringHolder x_sd_admin_password = new StringHolder();
-
- StringHolder x_ca_hostname = new StringHolder();
- StringHolder x_ca_port = new StringHolder();
- StringHolder x_ca_ssl_port = new StringHolder();
- StringHolder x_ca_admin_port = new StringHolder();
-
- StringHolder x_drm_hostname = new StringHolder();
- StringHolder x_drm_ssl_port = new StringHolder();
-
- StringHolder x_tks_hostname = new StringHolder();
- StringHolder x_tks_ssl_port = new StringHolder();
-
- StringHolder x_client_certdb_dir = new StringHolder();
- StringHolder x_client_certdb_pwd = new StringHolder();
- StringHolder x_preop_pin = new StringHolder();
-
- StringHolder x_domain_name = new StringHolder();
-
- StringHolder x_admin_user = new StringHolder();
- StringHolder x_admin_email = new StringHolder();
- StringHolder x_admin_password = new StringHolder();
-
- // ldap
-
- StringHolder x_ldap_host = new StringHolder();
- StringHolder x_ldap_port = new StringHolder();
- StringHolder x_bind_dn = new StringHolder();
- StringHolder x_bind_password = new StringHolder();
- StringHolder x_base_dn = new StringHolder();
- StringHolder x_db_name = new StringHolder();
-
- StringHolder x_ldap_auth_host = new StringHolder();
- StringHolder x_ldap_auth_port = new StringHolder();
- StringHolder x_ldap_auth_base_dn = new StringHolder();
-
- // key size
- StringHolder x_token_name = new StringHolder();
- StringHolder x_token_pwd = new StringHolder();
- StringHolder x_key_size = new StringHolder();
- StringHolder x_key_type = new StringHolder();
-
- StringHolder x_agent_key_size = new StringHolder();
- StringHolder x_agent_key_type = new StringHolder();
- StringHolder x_agent_cert_subject = new StringHolder();
-
- StringHolder x_agent_name = new StringHolder();
-
- StringHolder x_ss_keygen = new StringHolder();
-
- // tps cert subject name params
- StringHolder x_tps_server_cert_subject_name = new StringHolder();
- StringHolder x_tps_server_cert_nickname = new StringHolder();
- StringHolder x_tps_subsystem_cert_subject_name = new StringHolder();
- StringHolder x_tps_subsystem_cert_nickname = new StringHolder();
- StringHolder x_tps_audit_signing_cert_subject_name = new StringHolder();
- StringHolder x_tps_audit_signing_cert_nickname = new StringHolder();
-
- // subsystemName
- StringHolder x_subsystem_name = new StringHolder();
-
-
- // parse the args
- ArgParser parser = new ArgParser("ConfigureTPS");
-
- parser.addOption ("-cs_hostname %s #CS Hostname",
- x_cs_hostname);
- parser.addOption ("-cs_port %s #CS SSL port",
- x_cs_port);
- parser.addOption ("-cs_clientauth_port %s #CS SSL port",
- x_cs_clientauth_port);
-
- parser.addOption ("-sd_hostname %s #Security Domain Hostname",
- x_sd_hostname);
- parser.addOption ("-sd_ssl_port %s #Security Domain SSL EE port",
- x_sd_ssl_port);
- parser.addOption ("-sd_agent_port %s #Security Domain SSL Agent port",
- x_sd_agent_port);
- parser.addOption ("-sd_admin_port %s #Security Domain SSL Admin port",
- x_sd_admin_port);
- parser.addOption ("-sd_admin_name %s #Security Domain username",
- x_sd_admin_name);
- parser.addOption ("-sd_admin_password %s #Security Domain password",
- x_sd_admin_password);
-
- parser.addOption ("-ca_hostname %s #CA Hostname",
- x_ca_hostname);
- parser.addOption ("-ca_port %s #CA non-SSL port",
- x_ca_port);
- parser.addOption ("-ca_ssl_port %s #CA SSL port",
- x_ca_ssl_port);
- parser.addOption ("-ca_admin_port %s #CA SSL Admin port",
- x_ca_admin_port);
-
- parser.addOption ("-drm_hostname %s #DRM Hostname",
- x_drm_hostname);
- parser.addOption ("-drm_ssl_port %s #DRM SSL port",
- x_drm_ssl_port);
- parser.addOption ("-ss_keygen %s #Enable Server Side Keygen [true,false]",
- x_ss_keygen);
-
- parser.addOption ("-tks_hostname %s #TKS Hostname",
- x_tks_hostname);
- parser.addOption ("-tks_ssl_port %s #TKS SSL port",
- x_tks_ssl_port);
-
- parser.addOption ("-client_certdb_dir %s #Client CertDB dir",
- x_client_certdb_dir);
- parser.addOption ("-client_certdb_pwd %s #client certdb password",
- x_client_certdb_pwd);
- parser.addOption ("-preop_pin %s #pre op pin",
- x_preop_pin);
- parser.addOption ("-domain_name %s #domain name",
- x_domain_name);
- parser.addOption ("-admin_user %s #Admin User Name",
- x_admin_user);
- parser.addOption ("-admin_email %s #Admin email",
- x_admin_email);
- parser.addOption ("-admin_password %s #Admin password",
- x_admin_password);
- parser.addOption ("-agent_name %s #Agent Cert Nickname",
- x_agent_name);
-
- parser.addOption ("-ldap_host %s #ldap host",
- x_ldap_host);
- parser.addOption ("-ldap_port %s #ldap port",
- x_ldap_port);
- parser.addOption ("-bind_dn %s #ldap bind dn",
- x_bind_dn);
- parser.addOption ("-bind_password %s #ldap bind password",
- x_bind_password);
- parser.addOption ("-base_dn %s #base dn",
- x_base_dn);
- parser.addOption ("-db_name %s #db name",
- x_db_name);
-
- parser.addOption ("-token_name %s #HSM/Software Token name",
- x_token_name);
- parser.addOption ("-token_pwd %s #HSM/Software Token password (optional, required for HSM)",
- x_token_pwd);
- parser.addOption ("-key_size %s #Key Size",
- x_key_size);
- parser.addOption ("-key_type %s #Key type [rsa,ecc]",
- x_key_type);
-
- parser.addOption ("-agent_key_size %s #Agent Cert Key Size",
- x_agent_key_size);
- parser.addOption ("-agent_key_type %s #Agent cert Key type [rsa]",
- x_agent_key_type);
- parser.addOption ("-agent_cert_subject %s #Agent cert Subject",
- x_agent_cert_subject);
-
-
- parser.addOption ("-ldap_auth_host %s #ldap auth host",
- x_ldap_auth_host);
- parser.addOption ("-ldap_auth_port %s #ldap auth port",
- x_ldap_auth_port);
- parser.addOption ("-ldap_auth_base_dn %s #ldap auth base dn",
- x_ldap_auth_base_dn);
-
- parser.addOption (
- "-tps_server_cert_subject_name %s #TPS server cert subject name",
- x_tps_server_cert_subject_name);
- parser.addOption (
- "-tps_server_cert_nickname %s #TPS server cert nickname",
- x_tps_server_cert_nickname);
- parser.addOption (
- "-tps_subsystem_cert_subject_name %s #TPS subsystem cert subject name",
- x_tps_subsystem_cert_subject_name);
- parser.addOption (
- "-tps_subsystem_cert_nickname %s #TPS subsystem cert nickname",
- x_tps_subsystem_cert_nickname);
- parser.addOption(
- "-tps_audit_signing_cert_subject_name %s #TPS audit signing cert subject name",
- x_tps_audit_signing_cert_subject_name);
- parser.addOption(
- "-tps_audit_signing_cert_nickname %s #TPS audit signing cert nickname",
- x_tps_audit_signing_cert_nickname);
-
- parser.addOption (
- "-subsystem_name %s #CA subsystem name",
- x_subsystem_name);
-
-
- // and then match the arguments
- String [] unmatched = null;
- unmatched = parser.matchAllArgs (args,0,ArgParser.EXIT_ON_UNMATCHED);
-
- if(unmatched!=null)
- {
- System.out.println("ERROR: Argument Mismatch");
- System.exit(-1);
- }
-
- parser.checkRequiredArgs();
-
- // set variables
- cs_hostname = x_cs_hostname.value;
- cs_port = x_cs_port.value;
- cs_clientauth_port = x_cs_clientauth_port.value;
-
- sd_hostname = x_sd_hostname.value;
- sd_ssl_port = x_sd_ssl_port.value;
- sd_agent_port = x_sd_agent_port.value;
- sd_admin_port = x_sd_admin_port.value;
- sd_admin_name = x_sd_admin_name.value;
- sd_admin_password = x_sd_admin_password.value;
-
- ca_hostname = x_ca_hostname.value;
- ca_port = x_ca_port.value;
- ca_ssl_port = x_ca_ssl_port.value;
- ca_admin_port = x_ca_admin_port.value;
-
- tks_hostname = x_tks_hostname.value;
- tks_ssl_port = x_tks_ssl_port.value;
-
- drm_hostname = x_drm_hostname.value;
- drm_ssl_port = x_drm_ssl_port.value;
-
- client_certdb_dir = x_client_certdb_dir.value;
- client_certdb_pwd = x_client_certdb_pwd.value;
- pin = x_preop_pin.value;
- domain_name = x_domain_name.value;
-
- admin_user = x_admin_user.value;
- admin_email = x_admin_email.value;
- admin_password = x_admin_password.value;
- agent_name = x_agent_name.value;
-
- ldap_host = x_ldap_host.value;
- ldap_port = x_ldap_port.value;
- bind_dn = x_bind_dn.value;
- bind_password = x_bind_password.value;
- base_dn = x_base_dn.value;
- db_name = x_db_name.value;
-
- ldap_auth_host = x_ldap_auth_host.value;
- ldap_auth_port = x_ldap_auth_port.value;
- ldap_auth_base_dn = x_ldap_auth_base_dn.value;
-
- key_size = x_key_size.value;
- key_type = x_key_type.value;
- token_name = x_token_name.value;
- token_pwd = x_token_pwd.value;
-
- agent_key_size = x_agent_key_size.value;
- agent_key_type = x_agent_key_type.value;
- agent_cert_subject = x_agent_cert_subject.value;
-
- ss_keygen = x_ss_keygen.value;
-
- tps_server_cert_subject_name =
- x_tps_server_cert_subject_name.value ;
- tps_server_cert_nickname =
- x_tps_server_cert_nickname.value ;
- tps_subsystem_cert_subject_name =
- x_tps_subsystem_cert_subject_name.value;
- tps_subsystem_cert_nickname =
- x_tps_subsystem_cert_nickname.value;
- tps_audit_signing_cert_subject_name =
- x_tps_audit_signing_cert_subject_name.value;
- tps_audit_signing_cert_nickname =
- x_tps_audit_signing_cert_nickname.value;
-
- subsystem_name = x_subsystem_name.value ;
-
-
-
- boolean st = ca.ConfigureTPSInstance();
-
- if (!st)
- {
- System.out.println("ERROR: unable to create TPS");
- System.exit(-1);
- }
-
- System.out.println("Certificate System - TPS Instance Configured");
- System.exit(0);
-
- }
+ System.out.println("TPS_SESSION_ID=" + tps_session_id);
+ System.out.println("TPS_URL=" + tps_url_1);
+
+ // use session id to connect back to TPS
+
+ String query_string_2 = "p=5" +
+ "&subsystem=TPS" +
+ "&session_id=" + tps_session_id +
+ "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
+ query_string_2);
+
+ // parse xml - no parsing
+
+ return true;
+
+ }
+
+ public boolean SubsystemPanel() {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+
+ sleep_time();
+ String query_string = "p=5" +
+ "&choice=newsubsystem" +
+ "&subsystemName=" +
+ URLEncoder.encode(subsystem_name) +
+ "&op=next" +
+ "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ sleep_time();
+ String ca_url = "https://" + ca_hostname + ":" + ca_ssl_port;
+
+ // CA choice panel
+ query_string = "p=6" +
+ "&urls=0" +
+ "&op=next" +
+ "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ sleep_time();
+ // TKS choice panel
+ String tks_url = "https://" + tks_hostname + ":" + tks_ssl_port;
+ query_string = "p=7" +
+ "&urls=0" +
+ "&op=next" +
+ "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ // DRM / server side keygen panel
+
+ sleep_time();
+ if (ss_keygen.equalsIgnoreCase("true")) {
+ ss_keygen = "keygen";
+ }
+
+ String drm_url = "https://" + drm_hostname + ":" + drm_ssl_port;
+
+ query_string = "p=8" +
+ "&choice=" + ss_keygen +
+ "&urls=0" +
+ "&op=next" +
+ "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ return true;
+ }
+
+ public boolean LdapAuthConnectionPanel() {
+ // auth db
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+
+ String query_string = "p=9" +
+ "&host=" +
+ URLEncoder.encode(ldap_auth_host) +
+ "&port=" +
+ URLEncoder.encode(ldap_auth_port) +
+ "&basedn=" +
+ URLEncoder.encode(ldap_auth_base_dn) +
+ "&op=next" +
+ "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ return true;
+ }
+
+ public boolean LdapConnectionPanel() {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+
+ String query_string = "p=10" +
+ "&host=" +
+ URLEncoder.encode(ldap_host) +
+ "&port=" +
+ URLEncoder.encode(ldap_port) +
+ "&binddn=" +
+ URLEncoder.encode(bind_dn) +
+ "&__bindpwd=" +
+ URLEncoder.encode(bind_password) +
+ "&basedn=" +
+ URLEncoder.encode(base_dn) +
+ "&database=" +
+ URLEncoder.encode(db_name) +
+ "&display=" +
+ URLEncoder.encode("") +
+ "&op=next" +
+ "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ return true;
+ }
+
+ public boolean TokenChoicePanel() {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+
+ // //////////////////////////////////////////////////////
+ String query_string = null;
+
+ // Software Token
+ if (token_name.equalsIgnoreCase("internal")) {
+ query_string = "p=1" +
+ "&choice=" +
+ URLEncoder.encode("NSS Certificate DB") +
+ "&op=next" +
+ "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+ }
+ // HSM
+ else {
+ // login to hsm first
+ query_string = "p=2" +
+ "&uTokName=" +
+ URLEncoder.encode(token_name) +
+ "&__uPasswd=" +
+ URLEncoder.encode(token_pwd) +
+ "&op=next" +
+ "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ // choice with token name now
+ query_string = "p=1" +
+ "&choice=" +
+ URLEncoder.encode(token_name) +
+ "&op=next" +
+ "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ }
+
+ return true;
+ }
+
+ public boolean KeyPanel() {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+ ArrayList<String> friendly_list = null;
+ ArrayList<String> dn_list = null;
+
+ String query_string = "p=11" +
+ "&keytype=" + key_type +
+ "&choice=default" +
+ "&custom_size=" + key_size +
+ "&sslserver_keytype=" + key_type +
+ "&sslserver_choice=custom" +
+ "&sslserver_custom_size=" + key_size +
+ "&subsystem_keytype=" + key_type +
+ "&subsystem_choice=custom" +
+ "&subsystem_custom_size=" + key_size +
+ "&audit_signing_keytype=" + key_type +
+ "&audit_signing_choice=default" +
+ "&audit_signing_custom_size=" + key_size +
+ "&op=next" +
+ "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ return true;
+ }
+
+ public boolean CertSubjectPanel() {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+ ArrayList<String> req_list = null;
+ ArrayList<String> cert_list = null;
+ ArrayList<String> dn_list = null;
+ ArrayList<String> friendly_list = null;
+
+ String ca_url = "https://" + ca_hostname + ":" + ca_ssl_port;
+
+ String query_string = "p=12" +
+ "&sslserver=" +
+ URLEncoder.encode(tps_server_cert_subject_name) +
+ "&sslserver_nick=" +
+ URLEncoder.encode(tps_server_cert_nickname) +
+ "&subsystem=" +
+ URLEncoder.encode(tps_subsystem_cert_subject_name) +
+ "&subsystem_nick=" +
+ URLEncoder.encode(tps_subsystem_cert_nickname) +
+ "&audit_signing=" +
+ URLEncoder.encode(tps_audit_signing_cert_subject_name) +
+ "&audit_signing_nick=" +
+ URLEncoder.encode(tps_audit_signing_cert_nickname) +
+ "&urls=0" +
+ "&op=next" +
+ "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ // parse the certs if needed
+
+ return true;
+ }
+
+ public boolean CertificatePanel() {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+ ArrayList<String> req_list = null;
+ ArrayList<String> cert_list = null;
+ ArrayList<String> dn_list = null;
+ ArrayList<String> pp_list = null;
+
+ String query_string = "p=13" +
+ "&sslserver=" +
+ "&sslserver_cc=" +
+ "&subsystem=" +
+ "&subsystem_cc=" +
+ "&audit_signing=" +
+ "&audit_signing_cc=" +
+ "&op=next" +
+ "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ return true;
+ }
+
+ public boolean AdminCertReqPanel() {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+ String admin_cert_request = null;
+
+ requestor_name = "TPS-" + cs_hostname + "-" + cs_clientauth_port;
+
+ ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
+ client_certdb_pwd,
+ agent_cert_subject,
+ agent_key_size,
+ agent_key_type);
+ cCrypt.setDebug(true);
+ cCrypt.setGenerateRequest(true);
+ cCrypt.setTransportCert(null);
+ cCrypt.setDualKey(false);
+ cCrypt.loginDB();
+
+ String crmf_request = cCrypt.generateCRMFrequest();
+
+ if (crmf_request == null) {
+ System.out.println("ERROR: AdminCertReqPanel() cert req gen failed");
+ return false;
+ }
+
+ admin_cert_request = crmf_request;
+
+ String query_string = "p=14" +
+ "&uid=" + admin_user +
+ "&name=" +
+ URLEncoder.encode("TPS Administrator") +
+ "&email=" +
+ URLEncoder.encode(admin_email) +
+ "&__pwd=" + URLEncoder.encode(admin_password) +
+ "&__admin_password_again=" + URLEncoder.encode(admin_password) +
+ "&cert_request=" +
+ URLEncoder.encode(admin_cert_request) +
+ "&display=0" +
+ "&profileId=" + "caAdminCert" +
+ "&cert_request_type=" + "crmf" +
+ "&import=true" +
+ "&uid=" + admin_user +
+ "&clone=0" +
+ "&securitydomain=" +
+ URLEncoder.encode(domain_name) +
+ "&subject=" +
+ URLEncoder.encode(agent_cert_subject) +
+ "&requestor_name=" +
+ URLEncoder.encode(requestor_name) +
+ "&sessionID=" + tps_session_id +
+ "&auth_hostname=" + ca_hostname +
+ "&auth_port=" + ca_ssl_port +
+ "&op=next" +
+ "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ admin_serial_number = px.getvalue("serialNumber");
+
+ return true;
+ }
+
+ public boolean AdminCertImportPanel() {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+ String cert_to_import = null;
+
+ String query_string = "serialNumber=" + admin_serial_number +
+ "&importCert=" + "true" +
+ "";
+
+ // NOTE: CA, DRM, OCSP, and TKS use the Security Domain Admin Port;
+ // whereas RA and TPS use the CA Admin Port associated with
+ // the 'CA choice panel' as invoked from the SubsystemPanel()
+ // which MAY or MAY NOT be the same CA as the CA specified
+ // by the Security Domain.
+ hr = hc.sslConnect(ca_hostname, ca_admin_port, admin_uri, query_string);
+
+ try {
+ // cert_to_import =
+ // new sun.misc.BASE64Encoder().encode(hr.getResponseData());
+ cert_to_import =
+ OSUtil.BtoA(hr.getResponseData());
+
+ } catch (Exception e) {
+ System.out.println("ERROR: failed to retrieve cert");
+ }
+
+ System.out.println("Imported Cert=" + cert_to_import);
+
+ ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
+ client_certdb_pwd,
+ null,
+ null,
+ null);
+ cCrypt.setDebug(true);
+ cCrypt.setGenerateRequest(true);
+ cCrypt.loginDB();
+
+ String start = "-----BEGIN CERTIFICATE-----\r\n";
+ String end = "\r\n-----END CERTIFICATE-----";
+
+ st = cCrypt.importCert(start + cert_to_import + end, agent_name);
+ if (!st) {
+ System.out.println("ERROR: AdminCertImportPanel() during cert import");
+ return false;
+ }
+
+ System.out.println("SUCCESS: imported admin user cert");
+
+ String query_string_1 = "p=15" +
+ "&serialNumber=" + admin_serial_number +
+ "&caHost=" +
+ URLEncoder.encode(ca_hostname) +
+ "&caPort=" + ca_admin_port +
+ "&op=next" +
+ "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string_1);
+
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ return true;
+ }
+
+ public boolean ConfigureTPSInstance() {
+ // 0. login to cert db
+ ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
+ client_certdb_pwd,
+ null,
+ null,
+ null);
+ cCrypt.setDebug(true);
+ cCrypt.setGenerateRequest(true);
+ cCrypt.loginDB();
+
+ // instantiate http client
+ hc = new HTTPClient();
+
+ sleep_time();
+ // 1. Login panel
+ boolean log_st = LoginPanel();
+ if (!log_st) {
+ System.out.println("ERROR: JSESSIONID not found.");
+ System.out.println("ERROR: ConfigureTPS: LoginPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 2. Token Choice Panel
+ boolean disp_token = TokenChoicePanel();
+ if (!disp_token) {
+ System.out.println("ERROR: ConfigureTPS: TokenChoicePanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 3. domain panel
+ boolean dom_st = DomainPanel();
+ if (!dom_st) {
+ System.out.println("ERROR: ConfigureTPS: DomainPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 4. display cert chain panel
+ boolean disp_st = DisplayChainPanel();
+ if (!disp_st) {
+ System.out.println("ERROR: ConfigureTPS: DisplayChainPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 5. security domain login panel
+ boolean disp_sd = SecurityDomainLoginPanel();
+ if (!disp_sd) {
+ System.out.println("ERROR: ConfigureTPS: SecurityDomainLoginPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 6. subsystem panel
+ boolean disp_ss = SubsystemPanel();
+ if (!disp_ss) {
+ System.out.println("ERROR: ConfigureTPS: SubsystemPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 7. ldap auth connection panel
+ boolean disp_ldap_auth = LdapAuthConnectionPanel();
+ if (!disp_ldap_auth) {
+ System.out.println("ERROR: ConfigureTPS: LdapAuthConnectionPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 8. ldap connection panel
+ boolean disp_ldap = LdapConnectionPanel();
+ if (!disp_ldap) {
+ System.out.println("ERROR: ConfigureTPS: LdapConnectionPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 11. Key Panel
+ boolean disp_key = KeyPanel();
+ if (!disp_key) {
+ System.out.println("ERROR: ConfigureTPS: KeyPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 12. Cert Subject Panel
+ boolean disp_csubj = CertSubjectPanel();
+ if (!disp_csubj) {
+ System.out.println("ERROR: ConfigureTPS: CertSubjectPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 13. Certificate Panel
+ boolean disp_cp = CertificatePanel();
+ if (!disp_cp) {
+ System.out.println("ERROR: ConfigureTPS: CertificatePanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 14. Admin Cert Req Panel
+ boolean disp_adm = AdminCertReqPanel();
+ if (!disp_adm) {
+ System.out.println("ERROR: ConfigureTPS: AdminCertReqPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 15. Admin Cert import Panel
+ boolean disp_im = AdminCertImportPanel();
+ if (!disp_im) {
+ System.out.println("ERROR: ConfigureTPS: AdminCertImportPanel() failure");
+ return false;
+ }
+
+ return true;
+ }
+
+ public static void main(String args[]) {
+ ConfigureTPS ca = new ConfigureTPS();
+
+ // set variables
+ StringHolder x_cs_hostname = new StringHolder();
+ StringHolder x_cs_port = new StringHolder();
+ StringHolder x_cs_clientauth_port = new StringHolder();
+
+ StringHolder x_sd_hostname = new StringHolder();
+ StringHolder x_sd_ssl_port = new StringHolder();
+ StringHolder x_sd_agent_port = new StringHolder();
+ StringHolder x_sd_admin_port = new StringHolder();
+ StringHolder x_sd_admin_name = new StringHolder();
+ StringHolder x_sd_admin_password = new StringHolder();
+
+ StringHolder x_ca_hostname = new StringHolder();
+ StringHolder x_ca_port = new StringHolder();
+ StringHolder x_ca_ssl_port = new StringHolder();
+ StringHolder x_ca_admin_port = new StringHolder();
+
+ StringHolder x_drm_hostname = new StringHolder();
+ StringHolder x_drm_ssl_port = new StringHolder();
+
+ StringHolder x_tks_hostname = new StringHolder();
+ StringHolder x_tks_ssl_port = new StringHolder();
+
+ StringHolder x_client_certdb_dir = new StringHolder();
+ StringHolder x_client_certdb_pwd = new StringHolder();
+ StringHolder x_preop_pin = new StringHolder();
+
+ StringHolder x_domain_name = new StringHolder();
+
+ StringHolder x_admin_user = new StringHolder();
+ StringHolder x_admin_email = new StringHolder();
+ StringHolder x_admin_password = new StringHolder();
+
+ // ldap
+
+ StringHolder x_ldap_host = new StringHolder();
+ StringHolder x_ldap_port = new StringHolder();
+ StringHolder x_bind_dn = new StringHolder();
+ StringHolder x_bind_password = new StringHolder();
+ StringHolder x_base_dn = new StringHolder();
+ StringHolder x_db_name = new StringHolder();
+
+ StringHolder x_ldap_auth_host = new StringHolder();
+ StringHolder x_ldap_auth_port = new StringHolder();
+ StringHolder x_ldap_auth_base_dn = new StringHolder();
+
+ // key size
+ StringHolder x_token_name = new StringHolder();
+ StringHolder x_token_pwd = new StringHolder();
+ StringHolder x_key_size = new StringHolder();
+ StringHolder x_key_type = new StringHolder();
+
+ StringHolder x_agent_key_size = new StringHolder();
+ StringHolder x_agent_key_type = new StringHolder();
+ StringHolder x_agent_cert_subject = new StringHolder();
+
+ StringHolder x_agent_name = new StringHolder();
+
+ StringHolder x_ss_keygen = new StringHolder();
+
+ // tps cert subject name params
+ StringHolder x_tps_server_cert_subject_name = new StringHolder();
+ StringHolder x_tps_server_cert_nickname = new StringHolder();
+ StringHolder x_tps_subsystem_cert_subject_name = new StringHolder();
+ StringHolder x_tps_subsystem_cert_nickname = new StringHolder();
+ StringHolder x_tps_audit_signing_cert_subject_name = new StringHolder();
+ StringHolder x_tps_audit_signing_cert_nickname = new StringHolder();
+
+ // subsystemName
+ StringHolder x_subsystem_name = new StringHolder();
+
+ // parse the args
+ ArgParser parser = new ArgParser("ConfigureTPS");
+
+ parser.addOption("-cs_hostname %s #CS Hostname",
+ x_cs_hostname);
+ parser.addOption("-cs_port %s #CS SSL port",
+ x_cs_port);
+ parser.addOption("-cs_clientauth_port %s #CS SSL port",
+ x_cs_clientauth_port);
+
+ parser.addOption("-sd_hostname %s #Security Domain Hostname",
+ x_sd_hostname);
+ parser.addOption("-sd_ssl_port %s #Security Domain SSL EE port",
+ x_sd_ssl_port);
+ parser.addOption("-sd_agent_port %s #Security Domain SSL Agent port",
+ x_sd_agent_port);
+ parser.addOption("-sd_admin_port %s #Security Domain SSL Admin port",
+ x_sd_admin_port);
+ parser.addOption("-sd_admin_name %s #Security Domain username",
+ x_sd_admin_name);
+ parser.addOption("-sd_admin_password %s #Security Domain password",
+ x_sd_admin_password);
+
+ parser.addOption("-ca_hostname %s #CA Hostname",
+ x_ca_hostname);
+ parser.addOption("-ca_port %s #CA non-SSL port",
+ x_ca_port);
+ parser.addOption("-ca_ssl_port %s #CA SSL port",
+ x_ca_ssl_port);
+ parser.addOption("-ca_admin_port %s #CA SSL Admin port",
+ x_ca_admin_port);
+
+ parser.addOption("-drm_hostname %s #DRM Hostname",
+ x_drm_hostname);
+ parser.addOption("-drm_ssl_port %s #DRM SSL port",
+ x_drm_ssl_port);
+ parser.addOption("-ss_keygen %s #Enable Server Side Keygen [true,false]",
+ x_ss_keygen);
+
+ parser.addOption("-tks_hostname %s #TKS Hostname",
+ x_tks_hostname);
+ parser.addOption("-tks_ssl_port %s #TKS SSL port",
+ x_tks_ssl_port);
+
+ parser.addOption("-client_certdb_dir %s #Client CertDB dir",
+ x_client_certdb_dir);
+ parser.addOption("-client_certdb_pwd %s #client certdb password",
+ x_client_certdb_pwd);
+ parser.addOption("-preop_pin %s #pre op pin",
+ x_preop_pin);
+ parser.addOption("-domain_name %s #domain name",
+ x_domain_name);
+ parser.addOption("-admin_user %s #Admin User Name",
+ x_admin_user);
+ parser.addOption("-admin_email %s #Admin email",
+ x_admin_email);
+ parser.addOption("-admin_password %s #Admin password",
+ x_admin_password);
+ parser.addOption("-agent_name %s #Agent Cert Nickname",
+ x_agent_name);
+
+ parser.addOption("-ldap_host %s #ldap host",
+ x_ldap_host);
+ parser.addOption("-ldap_port %s #ldap port",
+ x_ldap_port);
+ parser.addOption("-bind_dn %s #ldap bind dn",
+ x_bind_dn);
+ parser.addOption("-bind_password %s #ldap bind password",
+ x_bind_password);
+ parser.addOption("-base_dn %s #base dn",
+ x_base_dn);
+ parser.addOption("-db_name %s #db name",
+ x_db_name);
+
+ parser.addOption("-token_name %s #HSM/Software Token name",
+ x_token_name);
+ parser.addOption("-token_pwd %s #HSM/Software Token password (optional, required for HSM)",
+ x_token_pwd);
+ parser.addOption("-key_size %s #Key Size",
+ x_key_size);
+ parser.addOption("-key_type %s #Key type [rsa,ecc]",
+ x_key_type);
+
+ parser.addOption("-agent_key_size %s #Agent Cert Key Size",
+ x_agent_key_size);
+ parser.addOption("-agent_key_type %s #Agent cert Key type [rsa]",
+ x_agent_key_type);
+ parser.addOption("-agent_cert_subject %s #Agent cert Subject",
+ x_agent_cert_subject);
+
+ parser.addOption("-ldap_auth_host %s #ldap auth host",
+ x_ldap_auth_host);
+ parser.addOption("-ldap_auth_port %s #ldap auth port",
+ x_ldap_auth_port);
+ parser.addOption("-ldap_auth_base_dn %s #ldap auth base dn",
+ x_ldap_auth_base_dn);
+
+ parser.addOption(
+ "-tps_server_cert_subject_name %s #TPS server cert subject name",
+ x_tps_server_cert_subject_name);
+ parser.addOption(
+ "-tps_server_cert_nickname %s #TPS server cert nickname",
+ x_tps_server_cert_nickname);
+ parser.addOption(
+ "-tps_subsystem_cert_subject_name %s #TPS subsystem cert subject name",
+ x_tps_subsystem_cert_subject_name);
+ parser.addOption(
+ "-tps_subsystem_cert_nickname %s #TPS subsystem cert nickname",
+ x_tps_subsystem_cert_nickname);
+ parser.addOption(
+ "-tps_audit_signing_cert_subject_name %s #TPS audit signing cert subject name",
+ x_tps_audit_signing_cert_subject_name);
+ parser.addOption(
+ "-tps_audit_signing_cert_nickname %s #TPS audit signing cert nickname",
+ x_tps_audit_signing_cert_nickname);
+
+ parser.addOption(
+ "-subsystem_name %s #CA subsystem name",
+ x_subsystem_name);
+
+ // and then match the arguments
+ String[] unmatched = null;
+ unmatched = parser.matchAllArgs(args, 0, ArgParser.EXIT_ON_UNMATCHED);
+
+ if (unmatched != null) {
+ System.out.println("ERROR: Argument Mismatch");
+ System.exit(-1);
+ }
+
+ parser.checkRequiredArgs();
+
+ // set variables
+ cs_hostname = x_cs_hostname.value;
+ cs_port = x_cs_port.value;
+ cs_clientauth_port = x_cs_clientauth_port.value;
+
+ sd_hostname = x_sd_hostname.value;
+ sd_ssl_port = x_sd_ssl_port.value;
+ sd_agent_port = x_sd_agent_port.value;
+ sd_admin_port = x_sd_admin_port.value;
+ sd_admin_name = x_sd_admin_name.value;
+ sd_admin_password = x_sd_admin_password.value;
+
+ ca_hostname = x_ca_hostname.value;
+ ca_port = x_ca_port.value;
+ ca_ssl_port = x_ca_ssl_port.value;
+ ca_admin_port = x_ca_admin_port.value;
+
+ tks_hostname = x_tks_hostname.value;
+ tks_ssl_port = x_tks_ssl_port.value;
+
+ drm_hostname = x_drm_hostname.value;
+ drm_ssl_port = x_drm_ssl_port.value;
+
+ client_certdb_dir = x_client_certdb_dir.value;
+ client_certdb_pwd = x_client_certdb_pwd.value;
+ pin = x_preop_pin.value;
+ domain_name = x_domain_name.value;
+
+ admin_user = x_admin_user.value;
+ admin_email = x_admin_email.value;
+ admin_password = x_admin_password.value;
+ agent_name = x_agent_name.value;
+
+ ldap_host = x_ldap_host.value;
+ ldap_port = x_ldap_port.value;
+ bind_dn = x_bind_dn.value;
+ bind_password = x_bind_password.value;
+ base_dn = x_base_dn.value;
+ db_name = x_db_name.value;
+
+ ldap_auth_host = x_ldap_auth_host.value;
+ ldap_auth_port = x_ldap_auth_port.value;
+ ldap_auth_base_dn = x_ldap_auth_base_dn.value;
+
+ key_size = x_key_size.value;
+ key_type = x_key_type.value;
+ token_name = x_token_name.value;
+ token_pwd = x_token_pwd.value;
+
+ agent_key_size = x_agent_key_size.value;
+ agent_key_type = x_agent_key_type.value;
+ agent_cert_subject = x_agent_cert_subject.value;
+
+ ss_keygen = x_ss_keygen.value;
+
+ tps_server_cert_subject_name =
+ x_tps_server_cert_subject_name.value;
+ tps_server_cert_nickname =
+ x_tps_server_cert_nickname.value;
+ tps_subsystem_cert_subject_name =
+ x_tps_subsystem_cert_subject_name.value;
+ tps_subsystem_cert_nickname =
+ x_tps_subsystem_cert_nickname.value;
+ tps_audit_signing_cert_subject_name =
+ x_tps_audit_signing_cert_subject_name.value;
+ tps_audit_signing_cert_nickname =
+ x_tps_audit_signing_cert_nickname.value;
+
+ subsystem_name = x_subsystem_name.value;
+
+ boolean st = ca.ConfigureTPSInstance();
+
+ if (!st) {
+ System.out.println("ERROR: unable to create TPS");
+ System.exit(-1);
+ }
+
+ System.out.println("Certificate System - TPS Instance Configured");
+ System.exit(0);
+
+ }
};
diff --git a/pki/base/silent/src/com/netscape/pkisilent/CreateInstance.java b/pki/base/silent/src/com/netscape/pkisilent/CreateInstance.java
index c1a9a7be..ddc356a0 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/CreateInstance.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/CreateInstance.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -21,7 +22,6 @@ import java.net.URLEncoder;
import com.netscape.pkisilent.common.PostQuery;
-
public class CreateInstance {
private static String host;
@@ -95,7 +95,7 @@ public class CreateInstance {
adminDomain = args[8];
}
-
+
boolean st = newinstance.CreateInstance();
if (!st) {
@@ -105,10 +105,7 @@ public class CreateInstance {
System.out.println("Certificate System - Instance created");
System.exit(0);
-
- }
-
-}
+ }
-;
+};
diff --git a/pki/base/silent/src/com/netscape/pkisilent/PKISilent.java b/pki/base/silent/src/com/netscape/pkisilent/PKISilent.java
index e61af61f..70528023 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/PKISilent.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/PKISilent.java
@@ -4,57 +4,56 @@ import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
-
public class PKISilent {
- private static void usage() {
- System.out.print("usage: java " + PKISilent.class.getCanonicalName());
- boolean first = true;
- for (Class<?> c : classes) {
- if (first) {
- System.out.println(" [ ");
- } else {
- System.out.println(" | ");
- }
- first = false;
- System.out.print(" " + c.getSimpleName());
- }
- System.out.println(" ] ");
- }
+ private static void usage() {
+ System.out.print("usage: java " + PKISilent.class.getCanonicalName());
+ boolean first = true;
+ for (Class<?> c : classes) {
+ if (first) {
+ System.out.println(" [ ");
+ } else {
+ System.out.println(" | ");
+ }
+ first = false;
+ System.out.print(" " + c.getSimpleName());
+ }
+ System.out.println(" ] ");
+ }
- static Class<?>[] classes = { ConfigureCA.class, ConfigureDRM.class,
- ConfigureOCSP.class, ConfigureRA.class, ConfigureSubCA.class,
- ConfigureTKS.class, ConfigureTPS.class, CreateInstance.class, };
+ static Class<?>[] classes = { ConfigureCA.class, ConfigureDRM.class,
+ ConfigureOCSP.class, ConfigureRA.class, ConfigureSubCA.class,
+ ConfigureTKS.class, ConfigureTPS.class, CreateInstance.class, };
- public static final void main(String[] args) {
- HashMap<String, Method> classMap = new HashMap<String, Method>();
- for (Class<?> c : classes) {
- try {
- classMap.put(c.getSimpleName(),
- c.getMethod("main", String[].class));
- } catch (Exception e) {
- // The set of classes listed above is guaranteed to have a
- // method 'main'
- e.printStackTrace();
- }
- }
- if (args.length == 0) {
- usage();
- System.exit(-1);
- }
- Method mainMethod = classMap.get(args[0]);
- if (mainMethod == null) {
- usage();
- System.exit(-1);
- }
- String[] innerArgs = {};
- if (args.length > 1) {
- innerArgs = Arrays.copyOfRange(args, 1, args.length);
- }
+ public static final void main(String[] args) {
+ HashMap<String, Method> classMap = new HashMap<String, Method>();
+ for (Class<?> c : classes) {
+ try {
+ classMap.put(c.getSimpleName(),
+ c.getMethod("main", String[].class));
+ } catch (Exception e) {
+ // The set of classes listed above is guaranteed to have a
+ // method 'main'
+ e.printStackTrace();
+ }
+ }
+ if (args.length == 0) {
+ usage();
+ System.exit(-1);
+ }
+ Method mainMethod = classMap.get(args[0]);
+ if (mainMethod == null) {
+ usage();
+ System.exit(-1);
+ }
+ String[] innerArgs = {};
+ if (args.length > 1) {
+ innerArgs = Arrays.copyOfRange(args, 1, args.length);
+ }
- try {
- mainMethod.invoke(null, (Object) innerArgs);
- } catch (Exception e) {
- // exception is guaranteed to have the static main method
- }
- }
+ try {
+ mainMethod.invoke(null, (Object) innerArgs);
+ } catch (Exception e) {
+ // exception is guaranteed to have the static main method
+ }
+ }
}
diff --git a/pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParseException.java b/pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParseException.java
index c2b927cc..3a78e5ce 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParseException.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParseException.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.argparser;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -18,37 +19,35 @@ package com.netscape.pkisilent.argparser;
// --- END COPYRIGHT BLOCK ---
import java.io.IOException;
-/**
- * Exception class used by <code>ArgParser</code> when
- * command line arguments contain an error.
- *
- * @author John E. Lloyd, Fall 2004
- * @see ArgParser
- */
-public class ArgParseException extends IOException
-{
- /**
+/**
+ * Exception class used by <code>ArgParser</code> when command line arguments
+ * contain an error.
+ *
+ * @author John E. Lloyd, Fall 2004
+ * @see ArgParser
+ */
+public class ArgParseException extends IOException {
+ /**
*
*/
private static final long serialVersionUID = -604960834535589460L;
/**
- * Creates a new ArgParseException with the given message.
- *
- * @param msg Exception message
- */
- public ArgParseException (String msg)
- { super (msg);
- }
+ * Creates a new ArgParseException with the given message.
+ *
+ * @param msg Exception message
+ */
+ public ArgParseException(String msg) {
+ super(msg);
+ }
- /**
- * Creates a new ArgParseException from the given
- * argument and message.
- *
- * @param arg Offending argument
- * @param msg Error message
- */
- public ArgParseException (String arg, String msg)
- { super (arg + ": " + msg);
- }
+ /**
+ * Creates a new ArgParseException from the given argument and message.
+ *
+ * @param arg Offending argument
+ * @param msg Error message
+ */
+ public ArgParseException(String arg, String msg) {
+ super(arg + ": " + msg);
+ }
}
diff --git a/pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParser.java b/pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParser.java
index a205d101..ff231499 100755
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParser.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParser.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.argparser;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -18,17 +19,17 @@ package com.netscape.pkisilent.argparser;
// --- END COPYRIGHT BLOCK ---
/**
- * Copyright John E. Lloyd, 2004. All rights reserved. Permission to use,
- * copy, modify and redistribute is granted, provided that this copyright
- * notice is retained and the author is given credit whenever appropriate.
- *
- * This software is distributed "as is", without any warranty, including
- * any implied warranty of merchantability or fitness for a particular
- * use. The author assumes no responsibility for, and shall not be liable
- * for, any special, indirect, or consequential damages, or any damages
- * whatsoever, arising out of or in connection with the use of this
- * software.
- */
+ * Copyright John E. Lloyd, 2004. All rights reserved. Permission to use,
+ * copy, modify and redistribute is granted, provided that this copyright
+ * notice is retained and the author is given credit whenever appropriate.
+ *
+ * This software is distributed "as is", without any warranty, including
+ * any implied warranty of merchantability or fitness for a particular
+ * use. The author assumes no responsibility for, and shall not be liable
+ * for, any special, indirect, or consequential damages, or any damages
+ * whatsoever, arising out of or in connection with the use of this
+ * software.
+ */
import java.io.File;
import java.io.FileReader;
@@ -40,191 +41,200 @@ import java.lang.reflect.Array;
import java.util.Vector;
/**
- * ArgParser is used to parse the command line arguments for a java
- * application program. It provides a compact way to specify options and match
- * them against command line arguments, with support for
- * <a href=#rangespec>range checking</a>,
- * <a href=#multipleOptionNames>multiple option names</a> (aliases),
- * <a href=#singleWordOptions>single word options</a>,
- * <a href=#multipleOptionValues>multiple values associated with an option</a>,
- * <a href=#multipleOptionInvocation>multiple option invocation</a>,
- * <a href=#helpInfo>generating help information</a>,
- * <a href=#customArgParsing>custom argument parsing</a>, and
- * <a href=#argsFromAFile>reading arguments from a file</a>. The
- * last feature is particularly useful and makes it
- * easy to create ad-hoc configuration files for an application.
- *
+ * ArgParser is used to parse the command line arguments for a java application
+ * program. It provides a compact way to specify options and match them against
+ * command line arguments, with support for <a href=#rangespec>range
+ * checking</a>, <a href=#multipleOptionNames>multiple option names</a>
+ * (aliases), <a href=#singleWordOptions>single word options</a>, <a
+ * href=#multipleOptionValues>multiple values associated with an option</a>, <a
+ * href=#multipleOptionInvocation>multiple option invocation</a>, <a
+ * href=#helpInfo>generating help information</a>, <a
+ * href=#customArgParsing>custom argument parsing</a>, and <a
+ * href=#argsFromAFile>reading arguments from a file</a>. The last feature is
+ * particularly useful and makes it easy to create ad-hoc configuration files
+ * for an application.
+ *
* <h3><a name="example">Basic Example</a></h3>
- *
- * <p>Here is a simple example in which an application has three
- * command line options:
- * <code>-theta</code> (followed by a floating point value),
- * <code>-file</code> (followed by a string value), and
- * <code>-debug</code>, which causes a boolean value to be set.
+ *
+ * <p>
+ * Here is a simple example in which an application has three command line
+ * options: <code>-theta</code> (followed by a floating point value),
+ * <code>-file</code> (followed by a string value), and <code>-debug</code>,
+ * which causes a boolean value to be set.
*
* <pre>
- *
- * static public void main (String[] args)
- * {
- * // create holder objects for storing results ...
*
- * DoubleHolder theta = new DoubleHolder();
- * StringHolder fileName = new StringHolder();
- * BooleanHolder debug = new BooleanHolder();
+ * static public void main(String[] args) {
+ * // create holder objects for storing results ...
*
- * // create the parser and specify the allowed options ...
+ * DoubleHolder theta = new DoubleHolder();
+ * StringHolder fileName = new StringHolder();
+ * BooleanHolder debug = new BooleanHolder();
*
- * ArgParser parser = new ArgParser("java argparser.SimpleExample");
- * parser.addOption ("-theta %f #theta value (in degrees)", theta);
- * parser.addOption ("-file %s #name of the operating file", fileName);
- * parser.addOption ("-debug %v #enables display of debugging info", debug);
- *
- * // match the arguments ...
+ * // create the parser and specify the allowed options ...
*
- * parser.matchAllArgs (args);
- *
- * // and print out the values
- *
- * System.out.println ("theta=" + theta.value);
- * System.out.println ("fileName=" + fileName.value);
- * System.out.println ("debug=" + debug.value);
- * }
+ * ArgParser parser = new ArgParser(&quot;java argparser.SimpleExample&quot;);
+ * parser.addOption(&quot;-theta %f #theta value (in degrees)&quot;, theta);
+ * parser.addOption(&quot;-file %s #name of the operating file&quot;, fileName);
+ * parser.addOption(&quot;-debug %v #enables display of debugging info&quot;, debug);
+ *
+ * // match the arguments ...
+ *
+ * parser.matchAllArgs(args);
+ *
+ * // and print out the values
+ *
+ * System.out.println(&quot;theta=&quot; + theta.value);
+ * System.out.println(&quot;fileName=&quot; + fileName.value);
+ * System.out.println(&quot;debug=&quot; + debug.value);
+ * }
* </pre>
- * <p>A command line specifying all three options might look like this:
+ * <p>
+ * A command line specifying all three options might look like this:
+ *
* <pre>
- * java argparser.SimpleExample -theta 7.8 -debug -file /ai/lloyd/bar
+ * java argparser.SimpleExample -theta 7.8 -debug -file /ai/lloyd/bar
* </pre>
*
- * <p>The application creates an instance of ArgParser and then adds
- * descriptions of the allowed options using {@link #addOption addOption}. The
- * method {@link #matchAllArgs(String[]) matchAllArgs} is then used to match
- * these options against the command line arguments. Values associated with
- * each option are returned in the <code>value</code> field of special
- * ``holder'' classes (e.g., {@link argparser.DoubleHolder DoubleHolder},
+ * <p>
+ * The application creates an instance of ArgParser and then adds descriptions
+ * of the allowed options using {@link #addOption addOption}. The method
+ * {@link #matchAllArgs(String[]) matchAllArgs} is then used to match these
+ * options against the command line arguments. Values associated with each
+ * option are returned in the <code>value</code> field of special ``holder''
+ * classes (e.g., {@link argparser.DoubleHolder DoubleHolder},
* {@link argparser.StringHolder StringHolder}, etc.).
- *
- * <p> The first argument to {@link #addOption addOption} is a string that
- * specifies (1) the option's name, (2) a conversion code for its associated
- * value (e.g., <code>%f</code> for floating point, <code>%s</code> for a
- * string, <code>%v</code> for a boolean flag), and (3) an optional description
+ *
+ * <p>
+ * The first argument to {@link #addOption addOption} is a string that specifies
+ * (1) the option's name, (2) a conversion code for its associated value (e.g.,
+ * <code>%f</code> for floating point, <code>%s</code> for a string,
+ * <code>%v</code> for a boolean flag), and (3) an optional description
* (following the <code>#</code> character) which is used for generating help
- * messages. The second argument is the holder object through which the value
- * is returned. This may be either a type-specific object (such as {@link
- * argparser.DoubleHolder DoubleHolder} or {@link argparser.StringHolder
- * StringHolder}), an array of the appropriate type, or
- * <a href=#multipleOptionInvocation> an instance of
- * <code>java.util.Vector</code></a>.
- *
- * <p>By default, arguments that don't match the specified options, are <a
+ * messages. The second argument is the holder object through which the value is
+ * returned. This may be either a type-specific object (such as
+ * {@link argparser.DoubleHolder DoubleHolder} or {@link argparser.StringHolder
+ * StringHolder}), an array of the appropriate type, or <a
+ * href=#multipleOptionInvocation> an instance of <code>java.util.Vector</code>
+ * </a>.
+ *
+ * <p>
+ * By default, arguments that don't match the specified options, are <a
* href=#rangespec>out of range</a>, or are otherwise formatted incorrectly,
- * will cause <code>matchAllArgs</code> to print a message and exit the
- * program. Alternatively, an application can use {@link
- * #matchAllArgs(String[],int,int) matchAllArgs(args,idx,exitFlags)} to obtain
- * an array of unmatched arguments which can then be
- * <a href=#customArgParsing>processed separately</a>
- *
+ * will cause <code>matchAllArgs</code> to print a message and exit the program.
+ * Alternatively, an application can use {@link #matchAllArgs(String[],int,int)
+ * matchAllArgs(args,idx,exitFlags)} to obtain an array of unmatched arguments
+ * which can then be <a href=#customArgParsing>processed separately</a>
+ *
* <h3><a name="rangespec">Range Specification</a></h3>
- *
+ *
* The values associated with options can also be given range specifications. A
* range specification appears in curly braces immediately following the
- * conversion code. In the code fragment below, we show how to specify an
- * option <code>-name</code> that expects to be provided with one of three
- * string values (<code>john</code>, <code>mary</code>, or <code>jane</code>),
- * an option <code>-index</code> that expects to be supplied with a integer
- * value in the range 1 to 256, an option <code>-size</code> that expects to be
+ * conversion code. In the code fragment below, we show how to specify an option
+ * <code>-name</code> that expects to be provided with one of three string
+ * values (<code>john</code>, <code>mary</code>, or <code>jane</code>), an
+ * option <code>-index</code> that expects to be supplied with a integer value
+ * in the range 1 to 256, an option <code>-size</code> that expects to be
* supplied with integer values of either 1, 2, 4, 8, or 16, and an option
* <code>-foo</code> that expects to be supplied with floating point values in
* the ranges -99 < foo <= -50, or 50 <= foo < 99.
- *
+ *
* <pre>
- * StringHolder name = new StringHolder();
- * IntHolder index = new IntHolder();
- * IntHolder size = new IntHolder();
- * DoubleHolder foo = new DoubleHolder();
- *
- * parser.addOption ("-name %s {john,mary,jane}", name);
- * parser.addOption ("-index %d {[1,256]}", index);
- * parser.addOption ("-size %d {1,2,4,8,16}", size);
- * parser.addOption ("-foo %f {(-99,-50],[50,99)}", foo);
+ * StringHolder name = new StringHolder();
+ * IntHolder index = new IntHolder();
+ * IntHolder size = new IntHolder();
+ * DoubleHolder foo = new DoubleHolder();
+ *
+ * parser.addOption(&quot;-name %s {john,mary,jane}&quot;, name);
+ * parser.addOption(&quot;-index %d {[1,256]}&quot;, index);
+ * parser.addOption(&quot;-size %d {1,2,4,8,16}&quot;, size);
+ * parser.addOption(&quot;-foo %f {(-99,-50],[50,99)}&quot;, foo);
* </pre>
- *
+ *
* If an argument value does not lie within a specified range, an error is
* generated.
- *
+ *
* <h3><a name="multipleOptionNames">Multiple Option Names</a></h3>
- *
- * An option may be given several names, or aliases, in the form of
- * a comma seperated list:
- *
+ *
+ * An option may be given several names, or aliases, in the form of a comma
+ * seperated list:
+ *
* <pre>
- * parser.addOption ("-v,--verbose %v #print lots of info");
- * parser.addOption ("-of,-outfile,-outputFile %s #output file");
+ * parser.addOption(&quot;-v,--verbose %v #print lots of info&quot;);
+ * parser.addOption(&quot;-of,-outfile,-outputFile %s #output file&quot;);
* </pre>
- *
+ *
* <h3><a name="singleWordOptions">Single Word Options</a></h3>
- *
- * Normally, options are assumed to be "multi-word", meaning
- * that any associated value must follow the option as a
- * separate argument string. For
- * example,
+ *
+ * Normally, options are assumed to be "multi-word", meaning that any associated
+ * value must follow the option as a separate argument string. For example,
+ *
* <pre>
- * parser.addOption ("-file %s #file name");
+ * parser.addOption(&quot;-file %s #file name&quot;);
* </pre>
- * will cause the parser to look for two strings in the argument list
- * of the form
+ *
+ * will cause the parser to look for two strings in the argument list of the
+ * form
+ *
* <pre>
* -file someFileName
* </pre>
- * However, if there is no white space separting the option's name from
- * it's conversion code, then values associated with that
- * option will be assumed to be part of the same argument
- * string as the option itself. For example,
+ *
+ * However, if there is no white space separting the option's name from it's
+ * conversion code, then values associated with that option will be assumed to
+ * be part of the same argument string as the option itself. For example,
+ *
* <pre>
- * parser.addOption ("-file=%s #file name");
+ * parser.addOption(&quot;-file=%s #file name&quot;);
* </pre>
- * will cause the parser to look for a single string in the argument
- * list of the form
+ *
+ * will cause the parser to look for a single string in the argument list of the
+ * form
+ *
* <pre>
* -file=someFileName
* </pre>
+ *
* Such an option is called a "single word" option.
- *
+ *
* <p>
- * In cases where an option has multiple names, then this single
- * word behavior is invoked if there is no white space between
- * the last indicated name and the conversion code. However, previous
- * names in the list will still be given multi-word behavior
- * if there is white space between the name and the
+ * In cases where an option has multiple names, then this single word behavior
+ * is invoked if there is no white space between the last indicated name and the
+ * conversion code. However, previous names in the list will still be given
+ * multi-word behavior if there is white space between the name and the
* following comma. For example,
+ *
* <pre>
- * parser.addOption ("-nb=,-number ,-n%d #number of blocks");
+ * parser.addOption(&quot;-nb=,-number ,-n%d #number of blocks&quot;);
* </pre>
- * will cause the parser to look for one, two, and one word constructions
- * of the forms
+ *
+ * will cause the parser to look for one, two, and one word constructions of the
+ * forms
+ *
* <pre>
* -nb=N
* -number N
* -nN
* </pre>
- *
+ *
* <h3><a name="multipleOptionValues">Multiple Option Values</a></h3>
- *
- * If may be useful for an option to be followed by several values.
- * For instance, we might have an option <code>-velocity</code>
- * which should be followed by three numbers denoting
- * the x, y, and z components of a velocity vector.
- * We can require multiple values for an option
- * by placing a <i>multiplier</i> specification,
- * of the form <code>X</code>N, where N is an integer,
- * after the conversion code (or range specification, if present).
- * For example,
+ *
+ * If may be useful for an option to be followed by several values. For
+ * instance, we might have an option <code>-velocity</code> which should be
+ * followed by three numbers denoting the x, y, and z components of a velocity
+ * vector. We can require multiple values for an option by placing a
+ * <i>multiplier</i> specification, of the form <code>X</code>N, where N is an
+ * integer, after the conversion code (or range specification, if present). For
+ * example,
*
* <pre>
- * double[] pos = new double[3];
- *
- * addOption ("-position %fX3 #position of the object", pos);
+ * double[] pos = new double[3];
+ *
+ * addOption(&quot;-position %fX3 #position of the object&quot;, pos);
* </pre>
+ *
* will cause the parser to look for
+ *
* <pre>
* -position xx yy zz
* </pre>
@@ -232,52 +242,53 @@ import java.util.Vector;
* in the argument list, where <code>xx</code>, <code>yy</code>, and
* <code>zz</code> are numbers. The values are stored in the array
* <code>pos</code>.
- *
- * Options requiring multiple values must use arrays to
- * return their values, and cannot be used in single word format.
- *
+ *
+ * Options requiring multiple values must use arrays to return their values, and
+ * cannot be used in single word format.
+ *
* <h3><a name="multipleOptionInvocation">Multiple Option Invocation</a></h3>
- *
- * Normally, if an option appears twice in the command list, the
- * value associated with the second instance simply overwrites the
- * value associated with the first instance.
- *
+ *
+ * Normally, if an option appears twice in the command list, the value
+ * associated with the second instance simply overwrites the value associated
+ * with the first instance.
+ *
* However, the application can instead arrange for the storage of <i>all</i>
- * values associated with multiple option invocation, by supplying a instance
- * of <code>java.util.Vector</code> to serve as the value holder. Then every
- * time the option appears in the argument list, the parser will create a value
- * holder of appropriate type, set it to the current value, and store the
- * holder in the vector. For example, the construction
- *
+ * values associated with multiple option invocation, by supplying a instance of
+ * <code>java.util.Vector</code> to serve as the value holder. Then every time
+ * the option appears in the argument list, the parser will create a value
+ * holder of appropriate type, set it to the current value, and store the holder
+ * in the vector. For example, the construction
+ *
* <pre>
- * Vector vec = new Vector(10);
- *
- * parser.addOption ("-foo %f", vec);
- * parser.matchAllArgs(args);
+ * Vector vec = new Vector(10);
+ *
+ * parser.addOption(&quot;-foo %f&quot;, vec);
+ * parser.matchAllArgs(args);
* </pre>
+ *
* when supplied with an argument list that contains
+ *
* <pre>
* -foo 1.2 -foo 1000 -foo -78
* </pre>
*
* will create three instances of {@link argparser.DoubleHolder DoubleHolder},
- * initialized to <code>1.2</code>, <code>1000</code>, and <code>-78</code>,
- * and store them in <code>vec</code>.
- *
+ * initialized to <code>1.2</code>, <code>1000</code>, and <code>-78</code>, and
+ * store them in <code>vec</code>.
+ *
* <h3><a name="helpInfo">Generating help information</a></h3>
- *
+ *
* ArgParser automatically generates help information for the options, and this
* information may be printed in response to a <i>help</i> option, or may be
- * queried by the application using {@link #getHelpMessage getHelpMessage}.
- * The information for each option consists of the option's name(s), it's
- * required value(s), and an application-supplied description. Value
- * information is generated automaticlly from the conversion code, range, and
- * multiplier specifications (although this can be overriden, as
- * <a href=#valueInfo>described below</a>).
- * The application-supplied description is whatever
- * appears in the specification string after the optional <code>#</code>
- * character. The string returned by {@link #getHelpMessage getHelpMessage} for
- * the <a href=#example>first example above</a> would be
+ * queried by the application using {@link #getHelpMessage getHelpMessage}. The
+ * information for each option consists of the option's name(s), it's required
+ * value(s), and an application-supplied description. Value information is
+ * generated automaticlly from the conversion code, range, and multiplier
+ * specifications (although this can be overriden, as <a
+ * href=#valueInfo>described below</a>). The application-supplied description is
+ * whatever appears in the specification string after the optional
+ * <code>#</code> character. The string returned by {@link #getHelpMessage
+ * getHelpMessage} for the <a href=#example>first example above</a> would be
*
* <pre>
* Usage: java argparser.SimpleExample
@@ -291,48 +302,47 @@ import java.util.Vector;
*
* The options <code>-help</code> and <code>-?</code> are including in the
* parser by default as help options, and they automatically cause the help
- * message to be printed. To exclude these
- * options, one should use the constructor {@link #ArgParser(String,boolean)
- * ArgParser(synopsis,false)}.
- * Help options can also be specified by the application using {@link
- * #addOption addOption} and the conversion code <code>%h</code>. Help options
- * can be disabled using {@link #setHelpOptionsEnabled
+ * message to be printed. To exclude these options, one should use the
+ * constructor {@link #ArgParser(String,boolean) ArgParser(synopsis,false)}.
+ * Help options can also be specified by the application using
+ * {@link #addOption addOption} and the conversion code <code>%h</code>. Help
+ * options can be disabled using {@link #setHelpOptionsEnabled
* setHelpOptionsEnabled(false)}.
- *
- * <p><a name=valueInfo>
- * A description of the required values for an option can be
- * specified explicitly
- * by placing a second <code>#</code> character in the specification
- * string. Everything between the first and second <code>#</code>
- * characters then becomes the value description, and everything
- * after the second <code>#</code> character becomes the option
- * description.
- * For example, if the <code>-theta</code> option
- * above was specified with
+ *
+ * <p>
+ * <a name=valueInfo> A description of the required values for an option can be
+ * specified explicitly by placing a second <code>#</code> character in the
+ * specification string. Everything between the first and second <code>#</code>
+ * characters then becomes the value description, and everything after the
+ * second <code>#</code> character becomes the option description. For example,
+ * if the <code>-theta</code> option above was specified with
+ *
* <pre>
- * parser.addOption ("-theta %f #NUMBER#theta value (in degrees)",theta);
+ * parser.addOption(&quot;-theta %f #NUMBER#theta value (in degrees)&quot;, theta);
* </pre>
+ *
* instead of
+ *
* <pre>
- * parser.addOption ("-theta %f #theta value (in degrees)", theta);
+ * parser.addOption(&quot;-theta %f #theta value (in degrees)&quot;, theta);
* </pre>
- * then the corresponding entry in the help message would look
- * like
+ *
+ * then the corresponding entry in the help message would look like
+ *
* <pre>
* -theta NUMBER theta value (in degrees)
* </pre>
- *
+ *
* <h3><a name="customArgParsing">Custom Argument Parsing</a></h3>
*
- * An application may find it necessary to handle arguments that
- * don't fit into the framework of this class. There are a couple
- * of ways to do this.
- *
+ * An application may find it necessary to handle arguments that don't fit into
+ * the framework of this class. There are a couple of ways to do this.
+ *
* <p>
* First, the method {@link #matchAllArgs(String[],int,int)
- * matchAllArgs(args,idx,exitFlags)} returns an array of
- * all unmatched arguments, which can then be handled
- * specially:
+ * matchAllArgs(args,idx,exitFlags)} returns an array of all unmatched
+ * arguments, which can then be handled specially:
+ *
* <pre>
* String[] unmatched =
* parser.matchAllArgs (args, 0, parser.EXIT_ON_ERROR);
@@ -342,12 +352,13 @@ import java.util.Vector;
* </pre>
*
* For instance, this would be useful for an applicatoon that accepts an
- * arbitrary number of input file names. The options can be parsed using
- * <code>matchAllArgs</code>, and the remaining unmatched arguments
- * give the file names.
- *
- * <p> If we need more control over the parsing, we can parse arguments one at
- * a time using {@link #matchArg matchArg}:
+ * arbitrary number of input file names. The options can be parsed using
+ * <code>matchAllArgs</code>, and the remaining unmatched arguments give the
+ * file names.
+ *
+ * <p>
+ * If we need more control over the parsing, we can parse arguments one at a
+ * time using {@link #matchArg matchArg}:
*
* <pre>
* int idx = 0;
@@ -365,1936 +376,1787 @@ import java.util.Vector;
* }
* }
* </pre>
- *
+ *
* {@link #matchArg matchArg(args,idx)} matches one option at location
* <code>idx</code> in the argument list, and then returns the location value
- * that should be used for the next match. If an argument does
- * not match any option,
- * {@link #getUnmatchedArgument getUnmatchedArgument} will return a copy of the
- * unmatched argument.
- *
+ * that should be used for the next match. If an argument does not match any
+ * option, {@link #getUnmatchedArgument getUnmatchedArgument} will return a copy
+ * of the unmatched argument.
+ *
* <h3><a name="argsFromAFile">Reading Arguments From a File</a></h3>
- *
- * The method {@link #prependArgs prependArgs} can be used to automatically
- * read in a set of arguments from a file and prepend them onto an existing
- * argument list. Argument words correspond to white-space-delimited strings,
- * and the file may contain the comment character <code>#</code> (which
- * comments out everything to the end of the current line). A typical usage
- * looks like this:
- *
+ *
+ * The method {@link #prependArgs prependArgs} can be used to automatically read
+ * in a set of arguments from a file and prepend them onto an existing argument
+ * list. Argument words correspond to white-space-delimited strings, and the
+ * file may contain the comment character <code>#</code> (which comments out
+ * everything to the end of the current line). A typical usage looks like this:
+ *
* <pre>
* ... create parser and add options ...
*
* args = parser.prependArgs (new File(".configFile"), args);
- *
+ *
* parser.matchAllArgs (args);
* </pre>
- *
- * This makes it easy to generate simple configuration files for an
- * application.
- *
+ *
+ * This makes it easy to generate simple configuration files for an application.
+ *
* @author John E. Lloyd, Fall 2004
*/
-public class ArgParser
-{
- Vector<Record> matchList;
-// int tabSpacing = 8;
- String synopsisString;
- boolean helpOptionsEnabled = true;
- Record defaultHelpOption = null;
- Record firstHelpOption = null;
- PrintStream printStream = System.out;
- int helpIndent = 24;
- String errMsg = null;
- String unmatchedArg = null;
-
- static String validConversionCodes = "iodxcbfsvh";
-
- /**
- * Indicates that the program should exit with an appropriate message
- * in the event of an erroneous or malformed argument.*/
- public static int EXIT_ON_ERROR = 1;
-
- /**
- * Indicates that the program should exit with an appropriate message
- * in the event of an unmatched argument.*/
- public static int EXIT_ON_UNMATCHED = 2;
-
- /**
- * Returns a string containing the valid conversion codes. These
- * are the characters which may follow the <code>%</code> character in
- * the specification string of {@link #addOption addOption}.
- *
- * @return Valid conversion codes
- * @see #addOption
- */
- public static String getValidConversionCodes()
- {
- return validConversionCodes;
- }
-
- static class NameDesc
- {
- String name;
- // oneWord implies that any value associated with
- // option is concatenated onto the argument string itself
- boolean oneWord;
- NameDesc next = null;
- }
-
- static class RangePnt
- {
- double dval = 0;
- long lval = 0;
- String sval = null;
- boolean bval = true;
- boolean closed = true;
-
- RangePnt (String s, boolean closed)
- { sval = s;
- this.closed = closed;
- }
-
- RangePnt (double d, boolean closed)
- { dval = d;
- this.closed = closed;
- }
-
- RangePnt (long l, boolean closed)
- { lval = l;
- this.closed = closed;
- }
-
- RangePnt (boolean b, boolean closed)
- { bval = b;
- this.closed = closed;
- }
-
- RangePnt (StringScanner scanner, int type)
- throws IllegalArgumentException
- {
- String typeName = null;
- try
- { switch (type)
- {
- case Record.CHAR:
- { typeName = "character";
- lval = scanner.scanChar();
- break;
- }
- case Record.INT:
- case Record.LONG:
- { typeName = "integer";
- lval = scanner.scanInt();
- break;
- }
- case Record.FLOAT:
- case Record.DOUBLE:
- { typeName = "float";
- dval = scanner.scanDouble();
- break;
- }
- case Record.STRING:
- { typeName = "string";
- sval = scanner.scanString();
- break;
- }
- case Record.BOOLEAN:
- { typeName = "boolean";
- bval = scanner.scanBoolean();
- break;
- }
- }
- }
- catch (StringScanException e)
- { throw new IllegalArgumentException (
- "Malformed " + typeName + " '" +
- scanner.substring(scanner.getIndex(),
- e.getFailIndex()+1) +
- "' in range spec");
- }
-// this.closed = closed;
- }
-
- void setClosed (boolean closed)
- { this.closed = closed;
- }
-
- boolean getClosed()
- { return closed;
- }
-
- int compareTo (double d)
- { if (dval < d)
- { return -1;
- }
- else if (d == dval)
- { return 0;
- }
- else
- { return 1;
- }
- }
-
- int compareTo (long l)
- { if (lval < l)
- { return -1;
- }
- else if (l == lval)
- { return 0;
- }
- else
- { return 1;
- }
- }
-
- int compareTo (String s)
- { return sval.compareTo (s);
- }
-
- int compareTo (boolean b)
- { if (b == bval)
- { return 0;
- }
- else
- { return 1;
- }
- }
-
- public String toString()
- { return "{ dval=" + dval + ", lval=" + lval +
- ", sval=" + sval + ", bval=" + bval +
- ", closed=" + closed + "}";
- }
- }
-
- class RangeAtom
- {
- RangePnt low = null;
- RangePnt high = null;
- RangeAtom next = null;
-
- RangeAtom (RangePnt p0, RangePnt p1, int type)
- throws IllegalArgumentException
- {
- int cmp = 0;
- switch (type)
- {
- case Record.CHAR:
- case Record.INT:
- case Record.LONG:
- { cmp = p0.compareTo (p1.lval);
- break;
- }
- case Record.FLOAT:
- case Record.DOUBLE:
- { cmp = p0.compareTo (p1.dval);
- break;
- }
- case Record.STRING:
- { cmp = p0.compareTo (p1.sval);
- break;
- }
- }
- if (cmp > 0)
- { // then switch high and low
- low = p1;
- high = p0;
- }
- else
- { low = p0;
- high = p1;
- }
- }
-
- RangeAtom (RangePnt p0)
- throws IllegalArgumentException
- {
- low = p0;
- }
-
- boolean match (double d)
- { int lc = low.compareTo(d);
- if (high != null)
- { int hc = high.compareTo(d);
- return (lc*hc < 0 ||
- (low.closed && lc==0) ||
- (high.closed && hc==0));
- }
- else
- { return lc == 0;
- }
- }
-
- boolean match (long l)
- { int lc = low.compareTo(l);
- if (high != null)
- { int hc = high.compareTo(l);
- return (lc*hc < 0 ||
- (low.closed && lc==0) ||
- (high.closed && hc==0));
- }
- else
- { return lc == 0;
- }
- }
-
- boolean match (String s)
- { int lc = low.compareTo(s);
- if (high != null)
- { int hc = high.compareTo(s);
- return (lc*hc < 0 ||
- (low.closed && lc==0) ||
- (high.closed && hc==0));
- }
- else
- { return lc == 0;
- }
- }
-
- boolean match (boolean b)
- { return low.compareTo(b) == 0;
- }
-
- public String toString()
- { return "low=" + (low==null ? "null" : low.toString()) +
- ", high=" + (high==null ? "null" : high.toString());
- }
- }
-
- class Record
- {
- NameDesc nameList;
- static final int NOTYPE = 0;
- static final int BOOLEAN = 1;
- static final int CHAR = 2;
- static final int INT = 3;
- static final int LONG = 4;
- static final int FLOAT = 5;
- static final int DOUBLE = 6;
- static final int STRING = 7;
- int type;
- int numValues;
- boolean vectorResult = false;
- boolean required = true;
-
- String helpMsg = null;
- String valueDesc = null;
- String rangeDesc = null;
- Object resHolder = null;
- RangeAtom rangeList = null;
- RangeAtom rangeTail = null;
- char convertCode;
- boolean vval = true; // default value for now
-
- NameDesc firstNameDesc()
- {
- return nameList;
- }
-
- RangeAtom firstRangeAtom()
- {
- return rangeList;
- }
-
- int numRangeAtoms()
- { int cnt = 0;
- for (RangeAtom ra=rangeList; ra!=null; ra=ra.next)
- { cnt++;
- }
- return cnt;
- }
-
- void addRangeAtom (RangeAtom ra)
- { if (rangeList == null)
- { rangeList = ra;
- }
- else
- { rangeTail.next = ra;
- }
- rangeTail = ra;
- }
-
- boolean withinRange (double d)
- {
- if (rangeList == null)
- { return true;
- }
- for (RangeAtom ra=rangeList; ra!=null; ra=ra.next)
- { if (ra.match (d))
- { return true;
- }
- }
- return false;
- }
-
- boolean withinRange (long l)
- {
- if (rangeList == null)
- { return true;
- }
- for (RangeAtom ra=rangeList; ra!=null; ra=ra.next)
- { if (ra.match (l))
- { return true;
- }
- }
- return false;
- }
-
- boolean withinRange (String s)
- {
- if (rangeList == null)
- { return true;
- }
- for (RangeAtom ra=rangeList; ra!=null; ra=ra.next)
- { if (ra.match (s))
- { return true;
- }
- }
- return false;
- }
-
- boolean withinRange (boolean b)
- {
- if (rangeList == null)
- { return true;
- }
- for (RangeAtom ra=rangeList; ra!=null; ra=ra.next)
- { if (ra.match (b))
- { return true;
- }
- }
- return false;
- }
-
- String valTypeName()
- {
- switch (convertCode)
- {
- case 'i':
- { return ("integer");
- }
- case 'o':
- { return ("octal integer");
- }
- case 'd':
- { return ("decimal integer");
- }
- case 'x':
- { return ("hex integer");
- }
- case 'c':
- { return ("char");
- }
- case 'b':
- { return ("boolean");
- }
- case 'f':
- { return ("float");
- }
- case 's':
- { return ("string");
- }
- }
- return ("unknown");
- }
-
- void scanValue (Object result, String name, String s, int resultIdx)
- throws ArgParseException
- {
- double dval = 0;
- String sval = null;
- long lval = 0;
- boolean bval = false;
-
- if (s.length()==0)
- { throw new ArgParseException
- (name, "requires a contiguous value");
- }
- StringScanner scanner = new StringScanner(s);
- try
- {
- switch (convertCode)
- {
- case 'i':
- { lval = scanner.scanInt();
- break;
- }
- case 'o':
- { lval = scanner.scanInt (8, false);
- break;
- }
- case 'd':
- { lval = scanner.scanInt (10, false);
- break;
- }
- case 'x':
- { lval = scanner.scanInt (16, false);
- break;
- }
- case 'c':
- { lval = scanner.scanChar();
- break;
- }
- case 'b':
- { bval = scanner.scanBoolean();
- break;
- }
- case 'f':
- { dval = scanner.scanDouble();
- break;
- }
- case 's':
- { sval = scanner.getString();
- break;
- }
- }
- }
- catch (StringScanException e)
- { throw new ArgParseException (
- name, "malformed " + valTypeName() + " '" + s + "'");
- }
- scanner.skipWhiteSpace();
- if (!scanner.atEnd())
- { throw new ArgParseException (
- name, "malformed " + valTypeName() + " '" + s + "'");
- }
- boolean outOfRange = false;
- switch (type)
- {
- case CHAR:
- case INT:
- case LONG:
- { outOfRange = !withinRange (lval);
- break;
- }
- case FLOAT:
- case DOUBLE:
- { outOfRange = !withinRange (dval);
- break;
- }
- case STRING:
- { outOfRange = !withinRange (sval);
- break;
- }
- case BOOLEAN:
- { outOfRange = !withinRange (bval);
- break;
- }
- }
- if (outOfRange)
- { String errmsg = "value " + s + " not in range ";
- throw new ArgParseException (
- name, "value '" + s + "' not in range " + rangeDesc);
- }
- if (result.getClass().isArray())
- {
- switch (type)
- {
- case BOOLEAN:
- { ((boolean[])result)[resultIdx] = bval;
- break;
- }
- case CHAR:
- { ((char[])result)[resultIdx] = (char)lval;
- break;
- }
- case INT:
- { ((int[])result)[resultIdx] = (int)lval;
- break;
- }
- case LONG:
- { ((long[])result)[resultIdx] = lval;
- break;
- }
- case FLOAT:
- { ((float[])result)[resultIdx] = (float)dval;
- break;
- }
- case DOUBLE:
- { ((double[])result)[resultIdx] = dval;
- break;
- }
- case STRING:
- { ((String[])result)[resultIdx] = sval;
- break;
- }
- }
- }
- else
- {
- switch (type)
- {
- case BOOLEAN:
- { ((BooleanHolder)result).value = bval;
- break;
- }
- case CHAR:
- { ((CharHolder)result).value = (char)lval;
- break;
- }
- case INT:
- { ((IntHolder)result).value = (int)lval;
- break;
- }
- case LONG:
- { ((LongHolder)result).value = lval;
- break;
- }
- case FLOAT:
- { ((FloatHolder)result).value = (float)dval;
- break;
- }
- case DOUBLE:
- { ((DoubleHolder)result).value = dval;
- break;
- }
- case STRING:
- { ((StringHolder)result).value = sval;
- break;
- }
- }
- }
- }
- }
-
- private String firstHelpOptionName()
- {
- if (firstHelpOption != null)
- { return firstHelpOption.nameList.name;
- }
- else
- { return null;
- }
- }
-
- /**
- * Creates an <code>ArgParser</code> with a synopsis
- * string, and the default help options <code>-help</code> and
- * <code>-&#063;</code>.
- *
- * @param synopsisString string that briefly describes program usage,
- * for use by {@link #getHelpMessage getHelpMessage}.
- * @see ArgParser#getSynopsisString
- * @see ArgParser#getHelpMessage
- */
- public ArgParser(String synopsisString)
- {
- this (synopsisString, true);
- }
-
- /**
- * Creates an <code>ArgParser</code> with a synopsis
- * string. The help options <code>-help</code> and
- * <code>-?</code> are added if <code>defaultHelp</code>
- * is true.
- *
- * @param synopsisString string that briefly describes program usage,
- * for use by {@link #getHelpMessage getHelpMessage}.
- * @param defaultHelp if true, adds the default help options
- * @see ArgParser#getSynopsisString
- * @see ArgParser#getHelpMessage
- */
- public ArgParser(String synopsisString, boolean defaultHelp)
- {
- matchList = new Vector<Record>(128);
- this.synopsisString = synopsisString;
- if (defaultHelp)
- { addOption ("-help,-? %h #displays help information", null);
- defaultHelpOption = firstHelpOption = matchList.get(0);
- }
- }
-
- /**
- * Returns the synopsis string used by the parser.
- * The synopsis string is a short description of how to invoke
- * the program, and usually looks something like
- * <p>
- * <prec>
- * "java somepackage.SomeClass [options] files ..."
- * </prec>
- *
- * <p> It is used in help and error messages.
- *
- * @return synopsis string
- * @see ArgParser#setSynopsisString
- * @see ArgParser#getHelpMessage
- */
- public String getSynopsisString ()
- {
- return synopsisString;
- }
-
- /**
- * Sets the synopsis string used by the parser.
- *
- * @param s new synopsis string
- * @see ArgParser#getSynopsisString
- * @see ArgParser#getHelpMessage
- */
- public void setSynopsisString (String s)
- {
- synopsisString = s;
- }
-
- /**
- * Indicates whether or not help options are enabled.
- *
- * @return true if help options are enabled
- * @see ArgParser#setHelpOptionsEnabled
- * @see ArgParser#addOption
- */
- public boolean getHelpOptionsEnabled ()
- {
- return helpOptionsEnabled;
- }
-
- /**
- * Enables or disables help options. Help options are those
- * associated with a conversion code of <code>%h</code>. If
- * help options are enabled, and a help option is matched,
- * then the string produced by
- * {@link #getHelpMessage getHelpMessage}
- * is printed to the default print stream and the program
- * exits with code 0. Otherwise, arguments which match help
- * options are ignored.
- *
- * @param enable enables help options if <code>true</code>.
- * @see ArgParser#getHelpOptionsEnabled
- * @see ArgParser#addOption
- * @see ArgParser#setDefaultPrintStream */
- public void setHelpOptionsEnabled(boolean enable)
- { helpOptionsEnabled = enable;
- }
-
- /**
- * Returns the default print stream used for outputting help
- * and error information.
- *
- * @return default print stream
- * @see ArgParser#setDefaultPrintStream
- */
- public PrintStream getDefaultPrintStream()
- { return printStream;
- }
-
- /**
- * Sets the default print stream used for outputting help
- * and error information.
- *
- * @param stream new default print stream
- * @see ArgParser#getDefaultPrintStream
- */
- public void setDefaultPrintStream (PrintStream stream)
- {
- printStream = stream;
- }
-
- /**
- * Gets the indentation used by {@link #getHelpMessage
- * getHelpMessage}.
- *
- * @return number of indentation columns
- * @see ArgParser#setHelpIndentation
- * @see ArgParser#getHelpMessage
- */
- public int getHelpIndentation()
- {
- return helpIndent;
- }
-
- /**
- * Sets the indentation used by {@link #getHelpMessage
- * getHelpMessage}. This is the number of columns that an option's help
- * information is indented. If the option's name and value information
- * can fit within this number of columns, then all information about
- * the option is placed on one line. Otherwise, the indented help
- * information is placed on a separate line.
- *
- * @param indent number of indentation columns
- * @see ArgParser#getHelpIndentation
- * @see ArgParser#getHelpMessage
- */
- public void setHelpIndentation (int indent)
- { helpIndent = indent;
- }
-
-// public void setTabSpacing (int n)
-// { tabSpacing = n;
-// }
-
-// public int getTabSpacing ()
-// { return tabSpacing;
-// }
-
- private void scanRangeSpec (Record rec, String s)
- throws IllegalArgumentException
- {
- StringScanner scanner = new StringScanner (s);
- int i0, i = 1;
- char c, c0, c1;
-
- scanner.setStringDelimiters (")],}");
- c = scanner.getc(); // swallow the first '{'
- scanner.skipWhiteSpace();
- while ((c=scanner.peekc()) != '}')
- { RangePnt p0, p1;
-
- if (c == '[' || c == '(')
- {
- if (rec.convertCode == 'v' || rec.convertCode == 'b')
- { throw new IllegalArgumentException
- ("Sub ranges not supported for %b or %v");
- }
- c0 = scanner.getc(); // record & swallow character
- scanner.skipWhiteSpace();
- p0 = new RangePnt (scanner, rec.type);
- scanner.skipWhiteSpace();
- if (scanner.getc() != ',')
- { throw new IllegalArgumentException
- ("Missing ',' in subrange specification");
- }
- p1 = new RangePnt (scanner, rec.type);
- scanner.skipWhiteSpace();
- if ((c1=scanner.getc()) != ']' && c1 != ')')
- { throw new IllegalArgumentException
- ("Unterminated subrange");
- }
- if (c0 == '(')
- { p0.setClosed (false);
- }
- if (c1 == ')')
- { p1.setClosed (false);
- }
- rec.addRangeAtom (new RangeAtom (p0, p1, rec.type));
- }
- else
- { scanner.skipWhiteSpace();
- p0 = new RangePnt (scanner, rec.type);
- rec.addRangeAtom (new RangeAtom (p0));
- }
- scanner.skipWhiteSpace();
- if ((c=scanner.peekc()) == ',')
- { scanner.getc();
- scanner.skipWhiteSpace();
- }
- else if (c != '}')
- {
- throw new IllegalArgumentException
- ("Range spec: ',' or '}' expected");
- }
- }
- if (rec.numRangeAtoms()==1)
- { rec.rangeDesc = s.substring (1, s.length()-1);
- }
- else
- { rec.rangeDesc = s;
- }
- }
-
- private int defaultResultType (char convertCode)
- {
- switch (convertCode)
- {
- case 'i':
- case 'o':
- case 'd':
- case 'x':
- { return Record.LONG;
- }
- case 'c':
- { return Record.CHAR;
- }
- case 'v':
- case 'b':
- { return Record.BOOLEAN;
- }
- case 'f':
- { return Record.DOUBLE;
- }
- case 's':
- { return Record.STRING;
- }
- }
- return Record.NOTYPE;
- }
-
- /**
- * Adds a new option description to the parser. The method takes two
- * arguments: a specification string, and a result holder in which to
- * store the associated value.
- *
- * <p>The specification string has the general form
- *
- * <p> <var>optionNames</var>
- * <code>%</code><var>conversionCode</var>
- * [<code>{</code><var>rangeSpec</var><code>}</code>]
- * [<code>X</code><var>multiplier</var>]
- * [<code>#</code><var>valueDescription</var>]
- * [<code>#</code><var>optionDescription</var>] </code>
- *
- * <p>
- * where
- * <ul> <p><li><var>optionNames</var> is a
- * comma-separated list of names for the option
- * (such as <code>-f, --file</code>).
- *
- * <p><li><var>conversionCode</var> is a single letter,
- * following a <code>%</code> character, specifying
- * information about what value the option requires:
- *
- * <table>
- * <tr><td><code>%f</code></td><td>a floating point number</td>
- * <tr><td><code>%i</code></td><td>an integer, in either decimal,
- * hex (if preceeded by <code>0x</code>), or
- * octal (if preceeded by <code>0</code>)</td>
- * <tr valign=top>
- * <td><code>%d</code></td><td>a decimal integer</td>
- * <tr valign=top>
- * <td><code>%o</code></td><td>an octal integer</td>
- * <tr valign=top>
- * <td><code>%h</code></td><td>a hex integer (without the
- * preceeding <code>0x</code>)</td>
- * <tr valign=top>
- * <td><code>%c</code></td><td>a single character, including
- * escape sequences (such as <code>\n</code> or <code>\007</code>),
- * and optionally enclosed in single quotes
- * <tr valign=top>
- * <td><code>%b</code></td><td>a boolean value (<code>true</code>
- * or <code>false</code>)</td>
- * <tr valign=top>
- * <td><code>%s</code></td><td>a string. This will
- * be the argument string itself (or its remainder, in
- * the case of a single word option)</td>
- * <tr valign=top>
- * <td><code>%v</code></td><td>no explicit value is expected,
- * but a boolean value of <code>true</code> (by default)
- * will be stored into the associated result holder if this
- * option is matched. If one wishes to have a value of
- * <code>false</code> stored instead, then the <code>%v</code>
- * should be followed by a "range spec" containing
- * <code>false</code>, as in <code>%v{false}</code>.
- * </table>
- *
- * <p><li><var>rangeSpec</var> is an optional range specification,
- * placed inside curly braces, consisting of a
- * comma-separated list of range items each specifying
- * permissible values for the option. A range item may be an
- * individual value, or it may itself be a subrange,
- * consisting of two individual values, separated by a comma,
- * and enclosed in square or round brackets. Square and round
- * brackets denote closed and open endpoints of a subrange, indicating
- * that the associated endpoint value is included or excluded
- * from the subrange.
- * The values specified in the range spec need to be
- * consistent with the type of value expected by the option.
- *
- * <p><b>Examples:</b>
- *
- * <p>A range spec of <code>{2,4,8,16}</code> for an integer
- * value will allow the integers 2, 4, 8, or 16.
- *
- * <p>A range spec of <code>{[-1.0,1.0]}</code> for a floating
- * point value will allow any floating point number in the
- * range -1.0 to 1.0.
- *
- * <p>A range spec of <code>{(-88,100],1000}</code> for an integer
- * value will allow values > -88 and <= 100, as well as 1000.
- *
- * <p>A range spec of <code>{"foo", "bar", ["aaa","zzz")} </code> for a
- * string value will allow strings equal to <code>"foo"</code> or
- * <code>"bar"</code>, plus any string lexically greater than or equal
- * to <code>"aaa"</code> but less then <code>"zzz"</code>.
- *
- * <p><li><var>multiplier</var> is an optional integer,
- * following a <code>X</code> character,
- * indicating the number of values which the option expects.
- * If the multiplier is not specified, it is assumed to be
- * 1. If the multiplier value is greater than 1, then the
- * result holder should be either an array (of appropriate
- * type) with a length greater than or equal to the multiplier
- * value, or a <code>java.util.Vector</code>
- * <a href=#vectorHolder>as discussed below</a>.
- *
- * <p><li><var>valueDescription</var> is an optional
- * description of the option's value requirements,
- * and consists of all
- * characters between two <code>#</code> characters.
- * The final <code>#</code> character initiates the
- * <i>option description</i>, which may be empty.
- * The value description is used in
- * <a href=#helpInfo>generating help messages</a>.
- *
- * <p><li><var>optionDescription</var> is an optional
- * description of the option itself, consisting of all
- * characters between a <code>#</code> character
- * and the end of the specification string.
- * The option description is used in
- * <a href=#helpInfo>generating help messages</a>.
- * </ul>
- *
- * <p>The result holder must be an object capable of holding
- * a value compatible with the conversion code,
- * or it must be a <code>java.util.Vector</code>.
- * When the option is matched, its associated value is
- * placed in the result holder. If the same option is
- * matched repeatedly, the result holder value will be overwritten,
- * unless the result holder is a <code>java.util.Vector</code>,
- * in which
- * case new holder objects for each match will be allocated
- * and added to the vector. Thus if
- * multiple instances of an option are desired by the
- * program, the result holder should be a
- * <code>java.util.Vector</code>.
- *
- * <p>If the result holder is not a <code>Vector</code>, then
- * it must correspond as follows to the conversion code:
- *
- * <table>
- * <tr valign=top>
- * <td><code>%i</code>, <code>%d</code>, <code>%x</code>,
- * <code>%o</code></td>
- * <td>{@link argparser.IntHolder IntHolder},
- * {@link argparser.LongHolder LongHolder}, <code>int[]</code>, or
- * <code>long[]</code></td>
- * </tr>
- *
- * <tr valign=top>
- * <td><code>%f</code></td>
- * <td>{@link argparser.FloatHolder FloatHolder},
- * {@link argparser.DoubleHolder DoubleHolder},
- * <code>float[]</code>, or
- * <code>double[]</code></td>
- * </tr>
- *
- * <tr valign=top>
- * <td><code>%b</code>, <code>%v</code></td>
- * <td>{@link argparser.BooleanHolder BooleanHolder} or
- * <code>boolean[]</code></td>
- * </tr>
- *
- * <tr valign=top>
- * <td><code>%s</code></td>
- * <td>{@link argparser.StringHolder StringHolder} or
- * <code>String[]</code></td>
- * </tr>
- *
- * <tr valign=top>
- * <td><code>%c</code></td>
- * <td>{@link argparser.CharHolder CharHolder} or
- * <code>char[]</code></td>
- * </tr>
- * </table>
- *
- * <p>In addition, if the multiplier is greater than 1,
- * then only the array type indicated above may be used,
- * and the array must be at least as long as the multiplier.
- *
- * <p><a name=vectorHolder>If the result holder is a
- * <code>Vector</code>, then the system will create an appropriate
- * result holder object and add it to the vector. Multiple occurances
- * of the option will cause multiple results to be added to the vector.
- *
- * <p>The object allocated by the system to store the result
- * will correspond to the conversion code as follows:
- *
- * <table>
- * <tr valign=top>
- * <td><code>%i</code>, <code>%d</code>, <code>%x</code>,
- * <code>%o</code></td>
- * <td>{@link argparser.LongHolder LongHolder}, or
- * <code>long[]</code> if the multiplier value exceeds 1</td>
- * </tr>
- *
- * <tr valign=top>
- * <td><code>%f</code></td>
- * <td>{@link argparser.DoubleHolder DoubleHolder}, or
- * <code>double[]</code> if the multiplier value exceeds 1</td>
- * </tr>
- *
- * <tr valign=top>
- * <td><code>%b</code>, <code>%v</code></td>
- * <td>{@link argparser.BooleanHolder BooleanHolder}, or
- * <code>boolean[]</code>
- * if the multiplier value exceeds 1</td>
- * </tr>
- *
- * <tr valign=top>
- * <td><code>%s</code></td>
- * <td>{@link argparser.StringHolder StringHolder}, or
- * <code>String[]</code>
- * if the multiplier value exceeds 1</td>
- * </tr>
- *
- * <tr valign=top>
- * <td><code>%c</code></td>
- * <td>{@link argparser.CharHolder CharHolder}, or <code>char[]</code>
- * if the multiplier value exceeds 1</td>
- * </tr>
- * </table>
- *
- * @param spec the specification string
- * @param resHolder object in which to store the associated
- * value
- * @throws IllegalArgumentException if there is an error in
- * the specification or if the result holder is of an invalid
- * type. */
- public void addOption (String spec, Object resHolder)
- throws IllegalArgumentException
- {
- // null terminated string is easier to parse
- StringScanner scanner = new StringScanner(spec);
- Record rec = null;
- NameDesc nameTail = null;
- NameDesc ndesc;
- int i0, i1;
- char c;
-
- do
- { ndesc = new NameDesc();
- boolean nameEndsInWhiteSpace = false;
-
- scanner.skipWhiteSpace();
- i0 = scanner.getIndex();
- while (!Character.isWhitespace(c=scanner.getc()) &&
- c != ',' && c != '%' && c != '\000')
- ;
- i1 = scanner.getIndex();
- if (c!='\000')
- { i1--;
- }
- if (i0==i1)
- { // then c is one of ',' '%' or '\000'
- throw new IllegalArgumentException
- ("Null option name given");
- }
- if (Character.isWhitespace(c))
- { nameEndsInWhiteSpace = true;
- scanner.skipWhiteSpace();
- c = scanner.getc();
- }
- if (c=='\000')
- { throw new IllegalArgumentException
- ("No conversion character given");
- }
- if (c != ',' && c != '%')
- { throw new IllegalArgumentException
- ("Names not separated by ','");
- }
- ndesc.name = scanner.substring (i0, i1);
- if (rec == null)
- { rec = new Record();
- rec.nameList = ndesc;
- }
- else
- { nameTail.next = ndesc;
- }
- nameTail = ndesc;
- ndesc.oneWord = !nameEndsInWhiteSpace;
- }
- while (c != '%');
-
- if (!nameTail.oneWord)
- { for (ndesc=rec.nameList; ndesc!=null; ndesc=ndesc.next)
- { ndesc.oneWord = false;
- }
- }
- c = scanner.getc();
- if (c=='\000')
- { throw new IllegalArgumentException
- ("No conversion character given");
- }
- if (validConversionCodes.indexOf(c) == -1)
- { throw new IllegalArgumentException
- ("Conversion code '" + c + "' not one of '" +
- validConversionCodes + "'");
- }
- rec.convertCode = c;
-
- if (resHolder instanceof Vector)
- { rec.vectorResult = true;
- rec.type = defaultResultType (rec.convertCode);
- }
- else
- {
- switch (rec.convertCode)
- {
- case 'i':
- case 'o':
- case 'd':
- case 'x':
- { if (resHolder instanceof LongHolder ||
- resHolder instanceof long[])
- { rec.type = Record.LONG;
- }
- else if (resHolder instanceof IntHolder ||
- resHolder instanceof int[])
- { rec.type = Record.INT;
- }
- else
- { throw new IllegalArgumentException (
- "Invalid result holder for %" + c);
- }
- break;
- }
- case 'c':
- { if (!(resHolder instanceof CharHolder) &&
- !(resHolder instanceof char[]))
- { throw new IllegalArgumentException (
- "Invalid result holder for %c");
- }
- rec.type = Record.CHAR;
- break;
- }
- case 'v':
- case 'b':
- { if (!(resHolder instanceof BooleanHolder) &&
- !(resHolder instanceof boolean[]))
- { throw new IllegalArgumentException (
- "Invalid result holder for %" + c);
- }
- rec.type = Record.BOOLEAN;
- break;
- }
- case 'f':
- { if (resHolder instanceof DoubleHolder ||
- resHolder instanceof double[])
- { rec.type = Record.DOUBLE;
- }
- else if (resHolder instanceof FloatHolder ||
- resHolder instanceof float[])
- { rec.type = Record.FLOAT;
- }
- else
- { throw new IllegalArgumentException (
- "Invalid result holder for %f");
- }
- break;
- }
- case 's':
- { if (!(resHolder instanceof StringHolder) &&
- !(resHolder instanceof String[]))
- { throw new IllegalArgumentException (
- "Invalid result holder for %s");
- }
- rec.type = Record.STRING;
- break;
- }
- case 'h':
- { // resHolder is ignored for this type
- break;
- }
- }
- }
- if (rec.convertCode == 'h')
- { rec.resHolder = null;
- }
- else
- { rec.resHolder = resHolder;
- }
-
- scanner.skipWhiteSpace();
- // get the range specification, if any
- if (scanner.peekc() == '{')
- {
- if (rec.convertCode == 'h')
- { throw new IllegalArgumentException
- ("Ranges not supported for %h");
- }
-// int bcnt = 0;
- i0 = scanner.getIndex(); // beginning of range spec
- do
- { c = scanner.getc();
- if (c=='\000')
- { throw new IllegalArgumentException
- ("Unterminated range specification");
- }
-// else if (c=='[' || c=='(')
-// { bcnt++;
-// }
-// else if (c==']' || c==')')
-// { bcnt--;
-// }
-// if ((rec.convertCode=='v'||rec.convertCode=='b') && bcnt>1)
-// { throw new IllegalArgumentException
-// ("Sub ranges not supported for %b or %v");
-// }
- }
- while (c != '}');
-// if (c != ']')
-// { throw new IllegalArgumentException
-// ("Range specification must end with ']'");
-// }
- i1 = scanner.getIndex(); // end of range spec
- scanRangeSpec (rec, scanner.substring (i0, i1));
- if (rec.convertCode == 'v' && rec.rangeList!=null)
- { rec.vval = rec.rangeList.low.bval;
- }
- }
- // check for value multiplicity information, if any
- if (scanner.peekc() == 'X')
- {
- if (rec.convertCode == 'h')
- { throw new IllegalArgumentException
- ("Multipliers not supported for %h");
- }
- scanner.getc();
- try
- { rec.numValues = (int)scanner.scanInt();
- }
- catch (StringScanException e)
- { throw new IllegalArgumentException
- ("Malformed value multiplier");
- }
- if (rec.numValues <= 0)
- { throw new IllegalArgumentException
- ("Value multiplier number must be > 0");
- }
- }
- else
- { rec.numValues = 1;
- }
- if (rec.numValues > 1)
- { for (ndesc=rec.nameList; ndesc!=null; ndesc=ndesc.next)
- { if (ndesc.oneWord)
- { throw new IllegalArgumentException (
-"Multiplier value incompatible with one word option " + ndesc.name);
- }
- }
- }
- if (resHolder != null && resHolder.getClass().isArray())
- { if (Array.getLength(resHolder) < rec.numValues)
- { throw new IllegalArgumentException (
-"Result holder array must have a length >= " + rec.numValues);
- }
- }
- else
- { if (rec.numValues > 1 && !(resHolder instanceof Vector))
- { throw new IllegalArgumentException (
-"Multiplier requires result holder to be an array of length >= "
-+ rec.numValues);
- }
- }
-
- // skip white space following conversion information
- scanner.skipWhiteSpace();
-
- // get the help message, if any
-
- if (!scanner.atEnd())
- { if (scanner.getc() != '#')
- { throw new IllegalArgumentException
- ("Illegal character(s), expecting '#'");
- }
- String helpInfo = scanner.substring (scanner.getIndex());
- // look for second '#'. If there is one, then info
- // between the first and second '#' is the value descriptor.
- int k = helpInfo.indexOf ("#");
- if (k != -1)
- { rec.valueDesc = helpInfo.substring (0, k);
- rec.helpMsg = helpInfo.substring (k+1);
- }
- else
- { rec.helpMsg = helpInfo;
- }
- }
- else
- { rec.helpMsg = "";
- }
-
- // parse helpMsg for required/optional information if present
- // default to required
- if (rec.helpMsg.indexOf("(optional") != -1) {
- rec.required = false;
- }
-
- // add option information to match list
- if (rec.convertCode == 'h' && firstHelpOption == defaultHelpOption)
- { matchList.remove (defaultHelpOption);
- firstHelpOption = rec;
- }
- matchList.add (rec);
- }
-
- Record lastMatchRecord ()
- { return (Record)matchList.lastElement();
- }
-
- private Record getRecord (String arg, ObjectHolder ndescHolder)
- {
- NameDesc ndesc;
- for (int i=0; i<matchList.size(); i++)
- { Record rec = (Record)matchList.get(i);
- for (ndesc=rec.nameList; ndesc!=null; ndesc=ndesc.next)
- { if (rec.convertCode != 'v' && ndesc.oneWord)
- { if (arg.startsWith (ndesc.name))
- { if (ndescHolder != null)
- { ndescHolder.value = ndesc;
- }
- return rec;
- }
- }
- else
- { if (arg.equals (ndesc.name))
- { if (ndescHolder != null)
- { ndescHolder.value = ndesc;
- }
- return rec;
- }
- }
- }
- }
- return null;
- }
-
- public void checkRequiredArgs() {
- for (int i=1; i<matchList.size(); i++) {
- Record rec = (Record)matchList.get(i);
- StringHolder myString = (StringHolder) rec.resHolder;
- if (((myString.value == null) || (myString.value.equals(""))) && (rec.required)) {
- printErrorAndExit("Required parameter " + rec.nameList.name + " is not specified.");
+public class ArgParser {
+ Vector<Record> matchList;
+ // int tabSpacing = 8;
+ String synopsisString;
+ boolean helpOptionsEnabled = true;
+ Record defaultHelpOption = null;
+ Record firstHelpOption = null;
+ PrintStream printStream = System.out;
+ int helpIndent = 24;
+ String errMsg = null;
+ String unmatchedArg = null;
+
+ static String validConversionCodes = "iodxcbfsvh";
+
+ /**
+ * Indicates that the program should exit with an appropriate message in the
+ * event of an erroneous or malformed argument.
+ */
+ public static int EXIT_ON_ERROR = 1;
+
+ /**
+ * Indicates that the program should exit with an appropriate message in the
+ * event of an unmatched argument.
+ */
+ public static int EXIT_ON_UNMATCHED = 2;
+
+ /**
+ * Returns a string containing the valid conversion codes. These are the
+ * characters which may follow the <code>%</code> character in the
+ * specification string of {@link #addOption addOption}.
+ *
+ * @return Valid conversion codes
+ * @see #addOption
+ */
+ public static String getValidConversionCodes() {
+ return validConversionCodes;
+ }
+
+ static class NameDesc {
+ String name;
+ // oneWord implies that any value associated with
+ // option is concatenated onto the argument string itself
+ boolean oneWord;
+ NameDesc next = null;
+ }
+
+ static class RangePnt {
+ double dval = 0;
+ long lval = 0;
+ String sval = null;
+ boolean bval = true;
+ boolean closed = true;
+
+ RangePnt(String s, boolean closed) {
+ sval = s;
+ this.closed = closed;
+ }
+
+ RangePnt(double d, boolean closed) {
+ dval = d;
+ this.closed = closed;
+ }
+
+ RangePnt(long l, boolean closed) {
+ lval = l;
+ this.closed = closed;
+ }
+
+ RangePnt(boolean b, boolean closed) {
+ bval = b;
+ this.closed = closed;
+ }
+
+ RangePnt(StringScanner scanner, int type)
+ throws IllegalArgumentException {
+ String typeName = null;
+ try {
+ switch (type) {
+ case Record.CHAR: {
+ typeName = "character";
+ lval = scanner.scanChar();
+ break;
+ }
+ case Record.INT:
+ case Record.LONG: {
+ typeName = "integer";
+ lval = scanner.scanInt();
+ break;
+ }
+ case Record.FLOAT:
+ case Record.DOUBLE: {
+ typeName = "float";
+ dval = scanner.scanDouble();
+ break;
+ }
+ case Record.STRING: {
+ typeName = "string";
+ sval = scanner.scanString();
+ break;
}
+ case Record.BOOLEAN: {
+ typeName = "boolean";
+ bval = scanner.scanBoolean();
+ break;
+ }
+ }
+ } catch (StringScanException e) {
+ throw new IllegalArgumentException(
+ "Malformed " + typeName + " '" +
+ scanner.substring(scanner.getIndex(),
+ e.getFailIndex() + 1) +
+ "' in range spec");
}
- }
-
-
- Object getResultHolder (String arg)
- {
- Record rec = getRecord(arg, null);
- return (rec != null) ? rec.resHolder : null;
- }
-
- String getOptionName (String arg)
- {
- ObjectHolder ndescHolder = new ObjectHolder();
- Record rec = getRecord(arg, ndescHolder);
- return (rec != null) ? ((NameDesc)ndescHolder.value).name : null;
- }
-
- String getOptionRangeDesc (String arg)
- {
- Record rec = getRecord(arg, null);
- return (rec != null) ? rec.rangeDesc : null;
- }
-
- String getOptionTypeName (String arg)
- {
- Record rec = getRecord(arg, null);
- return (rec != null) ? rec.valTypeName() : null;
- }
-
- private Object createResultHolder (Record rec)
- {
- if (rec.numValues == 1)
- { switch (rec.type)
- { case Record.LONG:
- { return new LongHolder();
- }
- case Record.CHAR:
- { return new CharHolder();
- }
- case Record.BOOLEAN:
- { return new BooleanHolder();
- }
- case Record.DOUBLE:
- { return new DoubleHolder();
- }
- case Record.STRING:
- { return new StringHolder();
- }
- }
- }
- else
- { switch (rec.type)
- { case Record.LONG:
- { return new long[rec.numValues];
- }
- case Record.CHAR:
- { return new char[rec.numValues];
- }
- case Record.BOOLEAN:
- { return new boolean[rec.numValues];
- }
- case Record.DOUBLE:
- { return new double[rec.numValues];
- }
- case Record.STRING:
- { return new String[rec.numValues];
- }
- }
- }
- return null; // can't happen
- }
-
- static void stringToArgs (Vector<String> vec, String s,
- boolean allowQuotedStrings)
- throws StringScanException
- {
- StringScanner scanner = new StringScanner(s);
- scanner.skipWhiteSpace();
- while (!scanner.atEnd())
- { if (allowQuotedStrings)
- { vec.add (scanner.scanString());
- }
- else
- { vec.add (scanner.scanNonWhiteSpaceString());
- }
- scanner.skipWhiteSpace();
- }
- }
-
- /**
- * Reads in a set of strings from a reader and prepends them to an
- * argument list. Strings are delimited by either whitespace or
- * double quotes <code>"</code>. The character <code>#</code> acts as
- * a comment character, causing input to the end of the current line to
- * be ignored.
- *
- * @param reader Reader from which to read the strings
- * @param args Initial set of argument values. Can be
- * specified as <code>null</code>.
- * @throws IOException if an error occured while reading.
- */
- public static String[] prependArgs (Reader reader, String[] args)
- throws IOException
- {
- if (args == null)
- { args = new String[0];
- }
- LineNumberReader lineReader = new LineNumberReader (reader);
- Vector<String> vec = new Vector<String>(100, 100);
- String line;
- int i, k;
-
- while ((line = lineReader.readLine()) != null)
- { int commentIdx = line.indexOf ("#");
- if (commentIdx != -1)
- { line = line.substring (0, commentIdx);
- }
- try
- { stringToArgs (vec, line, /*allowQuotedStings=*/true);
- }
- catch (StringScanException e)
- { throw new IOException (
- "malformed string, line "+lineReader.getLineNumber());
- }
- }
- String[] result = new String[vec.size()+args.length];
- for (i=0; i<vec.size(); i++)
- { result[i] = (String)vec.get(i);
- }
- for (k=0; k<args.length; k++)
- { result[i++] = args[k];
- }
- return result;
- }
-
- /**
- * Reads in a set of strings from a file and prepends them to an
- * argument list. Strings are delimited by either whitespace or double
- * quotes <code>"</code>. The character <code>#</code> acts as a
- * comment character, causing input to the end of the current line to
- * be ignored.
- *
- * @param file File to be read
- * @param args Initial set of argument values. Can be
- * specified as <code>null</code>.
- * @throws IOException if an error occured while reading the file.
- */
- public static String[] prependArgs (File file, String[] args)
- throws IOException
- {
- if (args == null)
- { args = new String[0];
- }
- if (!file.canRead())
- { return args;
- }
- try
- { return prependArgs (new FileReader (file), args);
- }
- catch (IOException e)
- { throw new IOException (
-"File " + file.getName() + ": " + e.getMessage());
- }
- }
-
- /**
- * Sets the parser's error message.
- *
- * @param s Error message
- */
- protected void setError (String msg)
- {
- errMsg = msg;
- }
-
- /**
- * Prints an error message, along with a pointer to help options,
- * if available, and causes the program to exit with code 1.
- */
- public void printErrorAndExit (String msg)
- {
- if (helpOptionsEnabled && firstHelpOptionName() != null)
- { msg += "\nUse "+firstHelpOptionName()+" for help information";
- }
- if (printStream != null)
- { printStream.println (msg);
- }
- System.exit(1);
- }
-
- /**
- * Matches arguments within an argument list.
- *
- * <p>In the event of an erroneous or unmatched argument, the method
- * prints a message and exits the program with code 1.
- *
- * <p>If help options are enabled and one of the arguments matches a
- * help option, then the result of {@link #getHelpMessage
- * getHelpMessage} is printed to the default print stream and the
- * program exits with code 0. If help options are not enabled, they
- * are ignored.
- *
- * @param args argument list
- * @see ArgParser#getDefaultPrintStream
- */
- public void matchAllArgs (String[] args)
- {
- matchAllArgs (args, 0, EXIT_ON_UNMATCHED | EXIT_ON_ERROR);
- }
-
- /**
- * Matches arguments within an argument list and returns
- * those which were not matched. The matching starts at a location
- * in <code>args</code> specified by <code>idx</code>, and
- * unmatched arguments are returned in a String array.
- *
- * <p>In the event of an erroneous argument, the method either prints a
- * message and exits the program (if {@link #EXIT_ON_ERROR} is
- * set in <code>exitFlags</code>)
- * or terminates the matching and creates a error message that
- * can be retrieved by {@link #getErrorMessage}.
- *
- * <p>In the event of an umatched argument, the method will print a
- * message and exit if {@link #EXIT_ON_UNMATCHED} is set
- * in <code>errorFlags</code>.
- * Otherwise, the unmatched argument will be appended to the returned
- * array of unmatched values, and the matching will continue at the
- * next location.
- *
- * <p>If help options are enabled and one of the arguments matches a
- * help option, then the result of {@link #getHelpMessage
- * getHelpMessage} is printed to the the default print stream and the
- * program exits with code 0. If help options are not enabled, then
- * they will not be matched.
- *
- * @param args argument list
- * @param idx starting location in list
- * @param exitFlags conditions causing the program to exit. Should be
- * an or-ed combintion of {@link #EXIT_ON_ERROR} or {@link
- * #EXIT_ON_UNMATCHED}.
- * @return array of arguments that were not matched, or
- * <code>null</code> if all arguments were successfully matched
- * @see ArgParser#getErrorMessage
- * @see ArgParser#getDefaultPrintStream
- */
- public String[] matchAllArgs (String[] args, int idx, int exitFlags)
- {
- Vector<String> unmatched = new Vector<String>(10);
-
- while (idx < args.length)
- { try
- { idx = matchArg (args, idx);
- if (unmatchedArg != null)
- { if ((exitFlags & EXIT_ON_UNMATCHED) != 0)
- { printErrorAndExit (
- "Unrecognized argument: " + unmatchedArg);
- }
- else
- { unmatched.add (unmatchedArg);
- }
- }
- }
- catch (ArgParseException e)
- { if ((exitFlags & EXIT_ON_ERROR) != 0)
- { printErrorAndExit (e.getMessage());
- }
- break;
- }
- }
- if (unmatched.size() == 0)
- { return null;
- }
- else
- { return (String[])unmatched.toArray(new String[0]);
- }
- }
-
- /**
- * Matches one option starting at a specified location in an argument
- * list. The method returns the location in the list where the next
- * match should begin.
- *
- * <p>In the event of an erroneous argument, the method throws
- * an {@link argparser.ArgParseException ArgParseException}
- * with an appropriate error message. This error
- * message can also be retrieved using
- * {@link #getErrorMessage getErrorMessage}.
- *
- * <p>In the event of an umatched argument, the method will return idx
- * + 1, and {@link #getUnmatchedArgument getUnmatchedArgument} will
- * return a copy of the unmatched argument. If an argument is matched,
- * {@link #getUnmatchedArgument getUnmatchedArgument} will return
- * <code>null</code>.
- *
- * <p>If help options are enabled and the argument matches a help
- * option, then the result of {@link #getHelpMessage getHelpMessage} is printed to
- * the the default print stream and the program exits with code 0. If
- * help options are not enabled, then they are ignored.
- *
- * @param args argument list
- * @param idx location in list where match should start
- * @return location in list where next match should start
- * @throws ArgParseException if there was an error performing
- * the match (such as improper or insufficient values).
- * @see ArgParser#setDefaultPrintStream
- * @see ArgParser#getHelpOptionsEnabled
- * @see ArgParser#getErrorMessage
- * @see ArgParser#getUnmatchedArgument
- */
- @SuppressWarnings("unchecked")
- public int matchArg (String[] args, int idx)
- throws ArgParseException
- {
- unmatchedArg = null;
- setError (null);
- try
- { ObjectHolder ndescHolder = new ObjectHolder();
- Record rec = getRecord (args[idx], ndescHolder);
- if (rec == null || (rec.convertCode=='h' && !helpOptionsEnabled))
- { // didn't match
- unmatchedArg = new String(args[idx]);
- return idx+1;
- }
- NameDesc ndesc = (NameDesc)ndescHolder.value;
- Object result;
- if (rec.resHolder instanceof Vector)
- { result = createResultHolder (rec);
- }
- else
- { result = rec.resHolder;
- }
- if (rec.convertCode == 'h')
- { if (helpOptionsEnabled)
- { printStream.println (getHelpMessage());
- System.exit (0);
- }
- else
- { return idx+1;
- }
- }
- else if (rec.convertCode != 'v')
- { if (ndesc.oneWord)
- { rec.scanValue (
- result, ndesc.name,
- args[idx].substring (ndesc.name.length()), 0);
- }
- else
- { if (idx+rec.numValues >= args.length)
- { throw new ArgParseException (
- ndesc.name, "requires " + rec.numValues + " value" +
- (rec.numValues > 1 ? "s" : ""));
- }
- for (int k=0; k<rec.numValues; k++)
- { rec.scanValue (result, ndesc.name, args[++idx], k);
- }
- }
- }
- else
- { if (rec.resHolder instanceof BooleanHolder)
- { ((BooleanHolder)result).value = rec.vval;
- }
- else
- { for (int k=0; k<rec.numValues; k++)
- { ((boolean[])result)[k] = rec.vval;
- }
- }
- }
- if (rec.resHolder instanceof Vector)
- { ((Vector<Object>)rec.resHolder).add (result);
- }
- }
- catch (ArgParseException e)
- { setError (e.getMessage());
- throw e;
- }
- return idx+1;
- }
-
- private String spaceString (int n)
- {
- StringBuffer sbuf = new StringBuffer(n);
- for (int i=0; i<n; i++)
- { sbuf.append(' ');
- }
- return sbuf.toString();
- }
-
-// public String getShortHelpMessage ()
-// {
-// String s;
-// Record rec;
-// NameDesc ndesc;
-// int initialIndent = 8;
-// int col = initialIndent;
-
-// if (maxcols <= 0)
-// { maxcols = 80;
-// }
-// if (matchList.size() > 0)
-// { ps.print (spaceString(initialIndent));
-// }
-// for (int i=0; i<matchList.size(); i++)
-// { rec = (Record)matchList.get(i);
-// s = "[";
-// for (ndesc=rec.nameList; ndesc!=null; ndesc=ndesc.next)
-// { s = s + ndesc.name;
-// if (ndesc.oneWord == false)
-// { s = s + " ";
-// }
-// if (ndesc.next != null)
-// { s = s + ",";
-// }
-// }
-// if (rec.convertCode != 'v' && rec.convertCode != 'h')
-// { if (rec.valueDesc != null)
-// { s += rec.valueDesc;
-// }
-// else
-// { s = s + "<" + rec.valTypeName() + ">";
-// if (rec.numValues > 1)
-// { s += "X" + rec.numValues;
-// }
-// }
-// }
-// s = s + "]";
-// /*
-// (col+=s.length()) > (maxcols-1) => we will spill over edge.
-// we use (maxcols-1) because if we go right to the edge
-// (maxcols), we get wrap new line inserted "for us".
-// i != 0 means we print the first entry, no matter
-// how long it is. Subsequent entries are printed
-// full length anyway. */
-
-// if ((col+=s.length()) > (maxcols-1) && i != 0)
-// { col = initialIndent+s.length();
-// ps.print ("\n" + spaceString(initialIndent));
-// }
-// ps.print (s);
-// }
-// if (matchList.size() > 0)
-// { ps.print ('\n');
-// ps.flush();
-// }
-// }
-
- /**
- * Returns a string describing the allowed options
- * in detail.
- *
- * @return help information string.
- */
- public String getHelpMessage ()
- {
- Record rec;
- NameDesc ndesc;
- boolean hasOneWordAlias = false;
- String s;
-
- s = "Usage: " + synopsisString + "\n";
- s += "Options include:\n\n";
- for (int i=0; i<matchList.size(); i++)
- { String optionInfo = "";
- rec = (Record)matchList.get(i);
- if (rec.convertCode=='h' && !helpOptionsEnabled)
- { continue;
- }
- for (ndesc=rec.nameList; ndesc!=null; ndesc=ndesc.next)
- { if (ndesc.oneWord)
- { hasOneWordAlias = true;
- break;
- }
- }
- for (ndesc=rec.nameList; ndesc!=null; ndesc=ndesc.next)
- { optionInfo += ndesc.name;
- if (hasOneWordAlias && !ndesc.oneWord)
- { optionInfo += " ";
- }
- if (ndesc.next != null)
- { optionInfo += ",";
- }
- }
- if (!hasOneWordAlias)
- { optionInfo += " ";
- }
- if (rec.convertCode != 'v' && rec.convertCode != 'h')
- { if (rec.valueDesc != null)
- { optionInfo += rec.valueDesc;
- }
- else
- { if (rec.rangeDesc != null)
- { optionInfo += "<" + rec.valTypeName() + " "
- + rec.rangeDesc + ">";
- }
- else
- { optionInfo += "<" + rec.valTypeName() + ">";
- }
- }
- }
- if (rec.numValues > 1)
- { optionInfo += "X" + rec.numValues;
- }
- s += optionInfo;
- if (rec.helpMsg.length() > 0)
- { int pad = helpIndent - optionInfo.length();
- if (pad < 2)
- { //s += '\n';
- pad = helpIndent;
- }
-// s += spaceString(pad) + rec.helpMsg;
- s += spaceString(4) + rec.helpMsg;
- }
- s += '\n';
- }
- return s;
- }
-
- /**
- * Returns the parser's error message. This is automatically
- * set whenever an error is encountered in <code>matchArg</code>
- * or <code>matchAllArgs</code>, and is automatically set to
- * <code>null</code> at the beginning of these methods.
- *
- * @return error message
- */
- public String getErrorMessage()
- {
- return errMsg;
- }
-
- /**
- * Returns the value of an unmatched argument discovered {@link
- * #matchArg matchArg} or {@link #matchAllArgs(String[],int,int)
- * matchAllArgs}. If there was no unmatched argument,
- * <code>null</code> is returned.
- *
- * @return unmatched argument
- */
- public String getUnmatchedArgument()
- {
- return unmatchedArg;
- }
-}
+ // this.closed = closed;
+ }
+
+ void setClosed(boolean closed) {
+ this.closed = closed;
+ }
+
+ boolean getClosed() {
+ return closed;
+ }
+
+ int compareTo(double d) {
+ if (dval < d) {
+ return -1;
+ } else if (d == dval) {
+ return 0;
+ } else {
+ return 1;
+ }
+ }
+
+ int compareTo(long l) {
+ if (lval < l) {
+ return -1;
+ } else if (l == lval) {
+ return 0;
+ } else {
+ return 1;
+ }
+ }
+
+ int compareTo(String s) {
+ return sval.compareTo(s);
+ }
+ int compareTo(boolean b) {
+ if (b == bval) {
+ return 0;
+ } else {
+ return 1;
+ }
+ }
+
+ public String toString() {
+ return "{ dval=" + dval + ", lval=" + lval +
+ ", sval=" + sval + ", bval=" + bval +
+ ", closed=" + closed + "}";
+ }
+ }
+
+ class RangeAtom {
+ RangePnt low = null;
+ RangePnt high = null;
+ RangeAtom next = null;
+
+ RangeAtom(RangePnt p0, RangePnt p1, int type)
+ throws IllegalArgumentException {
+ int cmp = 0;
+ switch (type) {
+ case Record.CHAR:
+ case Record.INT:
+ case Record.LONG: {
+ cmp = p0.compareTo(p1.lval);
+ break;
+ }
+ case Record.FLOAT:
+ case Record.DOUBLE: {
+ cmp = p0.compareTo(p1.dval);
+ break;
+ }
+ case Record.STRING: {
+ cmp = p0.compareTo(p1.sval);
+ break;
+ }
+ }
+ if (cmp > 0) { // then switch high and low
+ low = p1;
+ high = p0;
+ } else {
+ low = p0;
+ high = p1;
+ }
+ }
+
+ RangeAtom(RangePnt p0)
+ throws IllegalArgumentException {
+ low = p0;
+ }
+
+ boolean match(double d) {
+ int lc = low.compareTo(d);
+ if (high != null) {
+ int hc = high.compareTo(d);
+ return (lc * hc < 0 ||
+ (low.closed && lc == 0) || (high.closed && hc == 0));
+ } else {
+ return lc == 0;
+ }
+ }
+
+ boolean match(long l) {
+ int lc = low.compareTo(l);
+ if (high != null) {
+ int hc = high.compareTo(l);
+ return (lc * hc < 0 ||
+ (low.closed && lc == 0) || (high.closed && hc == 0));
+ } else {
+ return lc == 0;
+ }
+ }
+
+ boolean match(String s) {
+ int lc = low.compareTo(s);
+ if (high != null) {
+ int hc = high.compareTo(s);
+ return (lc * hc < 0 ||
+ (low.closed && lc == 0) || (high.closed && hc == 0));
+ } else {
+ return lc == 0;
+ }
+ }
+
+ boolean match(boolean b) {
+ return low.compareTo(b) == 0;
+ }
+
+ public String toString() {
+ return "low=" + (low == null ? "null" : low.toString()) +
+ ", high=" + (high == null ? "null" : high.toString());
+ }
+ }
+
+ class Record {
+ NameDesc nameList;
+ static final int NOTYPE = 0;
+ static final int BOOLEAN = 1;
+ static final int CHAR = 2;
+ static final int INT = 3;
+ static final int LONG = 4;
+ static final int FLOAT = 5;
+ static final int DOUBLE = 6;
+ static final int STRING = 7;
+ int type;
+ int numValues;
+ boolean vectorResult = false;
+ boolean required = true;
+
+ String helpMsg = null;
+ String valueDesc = null;
+ String rangeDesc = null;
+ Object resHolder = null;
+ RangeAtom rangeList = null;
+ RangeAtom rangeTail = null;
+ char convertCode;
+ boolean vval = true; // default value for now
+
+ NameDesc firstNameDesc() {
+ return nameList;
+ }
+
+ RangeAtom firstRangeAtom() {
+ return rangeList;
+ }
+
+ int numRangeAtoms() {
+ int cnt = 0;
+ for (RangeAtom ra = rangeList; ra != null; ra = ra.next) {
+ cnt++;
+ }
+ return cnt;
+ }
+
+ void addRangeAtom(RangeAtom ra) {
+ if (rangeList == null) {
+ rangeList = ra;
+ } else {
+ rangeTail.next = ra;
+ }
+ rangeTail = ra;
+ }
+
+ boolean withinRange(double d) {
+ if (rangeList == null) {
+ return true;
+ }
+ for (RangeAtom ra = rangeList; ra != null; ra = ra.next) {
+ if (ra.match(d)) {
+ return true;
+ }
+ }
+ return false;
+ }
+ boolean withinRange(long l) {
+ if (rangeList == null) {
+ return true;
+ }
+ for (RangeAtom ra = rangeList; ra != null; ra = ra.next) {
+ if (ra.match(l)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ boolean withinRange(String s) {
+ if (rangeList == null) {
+ return true;
+ }
+ for (RangeAtom ra = rangeList; ra != null; ra = ra.next) {
+ if (ra.match(s)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ boolean withinRange(boolean b) {
+ if (rangeList == null) {
+ return true;
+ }
+ for (RangeAtom ra = rangeList; ra != null; ra = ra.next) {
+ if (ra.match(b)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ String valTypeName() {
+ switch (convertCode) {
+ case 'i': {
+ return ("integer");
+ }
+ case 'o': {
+ return ("octal integer");
+ }
+ case 'd': {
+ return ("decimal integer");
+ }
+ case 'x': {
+ return ("hex integer");
+ }
+ case 'c': {
+ return ("char");
+ }
+ case 'b': {
+ return ("boolean");
+ }
+ case 'f': {
+ return ("float");
+ }
+ case 's': {
+ return ("string");
+ }
+ }
+ return ("unknown");
+ }
+
+ void scanValue(Object result, String name, String s, int resultIdx)
+ throws ArgParseException {
+ double dval = 0;
+ String sval = null;
+ long lval = 0;
+ boolean bval = false;
+
+ if (s.length() == 0) {
+ throw new ArgParseException(name, "requires a contiguous value");
+ }
+ StringScanner scanner = new StringScanner(s);
+ try {
+ switch (convertCode) {
+ case 'i': {
+ lval = scanner.scanInt();
+ break;
+ }
+ case 'o': {
+ lval = scanner.scanInt(8, false);
+ break;
+ }
+ case 'd': {
+ lval = scanner.scanInt(10, false);
+ break;
+ }
+ case 'x': {
+ lval = scanner.scanInt(16, false);
+ break;
+ }
+ case 'c': {
+ lval = scanner.scanChar();
+ break;
+ }
+ case 'b': {
+ bval = scanner.scanBoolean();
+ break;
+ }
+ case 'f': {
+ dval = scanner.scanDouble();
+ break;
+ }
+ case 's': {
+ sval = scanner.getString();
+ break;
+ }
+ }
+ } catch (StringScanException e) {
+ throw new ArgParseException(
+ name, "malformed " + valTypeName() + " '" + s + "'");
+ }
+ scanner.skipWhiteSpace();
+ if (!scanner.atEnd()) {
+ throw new ArgParseException(
+ name, "malformed " + valTypeName() + " '" + s + "'");
+ }
+ boolean outOfRange = false;
+ switch (type) {
+ case CHAR:
+ case INT:
+ case LONG: {
+ outOfRange = !withinRange(lval);
+ break;
+ }
+ case FLOAT:
+ case DOUBLE: {
+ outOfRange = !withinRange(dval);
+ break;
+ }
+ case STRING: {
+ outOfRange = !withinRange(sval);
+ break;
+ }
+ case BOOLEAN: {
+ outOfRange = !withinRange(bval);
+ break;
+ }
+ }
+ if (outOfRange) {
+ String errmsg = "value " + s + " not in range ";
+ throw new ArgParseException(
+ name, "value '" + s + "' not in range " + rangeDesc);
+ }
+ if (result.getClass().isArray()) {
+ switch (type) {
+ case BOOLEAN: {
+ ((boolean[]) result)[resultIdx] = bval;
+ break;
+ }
+ case CHAR: {
+ ((char[]) result)[resultIdx] = (char) lval;
+ break;
+ }
+ case INT: {
+ ((int[]) result)[resultIdx] = (int) lval;
+ break;
+ }
+ case LONG: {
+ ((long[]) result)[resultIdx] = lval;
+ break;
+ }
+ case FLOAT: {
+ ((float[]) result)[resultIdx] = (float) dval;
+ break;
+ }
+ case DOUBLE: {
+ ((double[]) result)[resultIdx] = dval;
+ break;
+ }
+ case STRING: {
+ ((String[]) result)[resultIdx] = sval;
+ break;
+ }
+ }
+ } else {
+ switch (type) {
+ case BOOLEAN: {
+ ((BooleanHolder) result).value = bval;
+ break;
+ }
+ case CHAR: {
+ ((CharHolder) result).value = (char) lval;
+ break;
+ }
+ case INT: {
+ ((IntHolder) result).value = (int) lval;
+ break;
+ }
+ case LONG: {
+ ((LongHolder) result).value = lval;
+ break;
+ }
+ case FLOAT: {
+ ((FloatHolder) result).value = (float) dval;
+ break;
+ }
+ case DOUBLE: {
+ ((DoubleHolder) result).value = dval;
+ break;
+ }
+ case STRING: {
+ ((StringHolder) result).value = sval;
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ private String firstHelpOptionName() {
+ if (firstHelpOption != null) {
+ return firstHelpOption.nameList.name;
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Creates an <code>ArgParser</code> with a synopsis string, and the default
+ * help options <code>-help</code> and <code>-&#063;</code>.
+ *
+ * @param synopsisString string that briefly describes program usage, for
+ * use by {@link #getHelpMessage getHelpMessage}.
+ * @see ArgParser#getSynopsisString
+ * @see ArgParser#getHelpMessage
+ */
+ public ArgParser(String synopsisString) {
+ this(synopsisString, true);
+ }
+
+ /**
+ * Creates an <code>ArgParser</code> with a synopsis string. The help
+ * options <code>-help</code> and <code>-?</code> are added if
+ * <code>defaultHelp</code> is true.
+ *
+ * @param synopsisString string that briefly describes program usage, for
+ * use by {@link #getHelpMessage getHelpMessage}.
+ * @param defaultHelp if true, adds the default help options
+ * @see ArgParser#getSynopsisString
+ * @see ArgParser#getHelpMessage
+ */
+ public ArgParser(String synopsisString, boolean defaultHelp) {
+ matchList = new Vector<Record>(128);
+ this.synopsisString = synopsisString;
+ if (defaultHelp) {
+ addOption("-help,-? %h #displays help information", null);
+ defaultHelpOption = firstHelpOption = matchList.get(0);
+ }
+ }
+
+ /**
+ * Returns the synopsis string used by the parser. The synopsis string is a
+ * short description of how to invoke the program, and usually looks
+ * something like
+ * <p>
+ * <prec> "java somepackage.SomeClass [options] files ..." </prec>
+ *
+ * <p>
+ * It is used in help and error messages.
+ *
+ * @return synopsis string
+ * @see ArgParser#setSynopsisString
+ * @see ArgParser#getHelpMessage
+ */
+ public String getSynopsisString() {
+ return synopsisString;
+ }
+
+ /**
+ * Sets the synopsis string used by the parser.
+ *
+ * @param s new synopsis string
+ * @see ArgParser#getSynopsisString
+ * @see ArgParser#getHelpMessage
+ */
+ public void setSynopsisString(String s) {
+ synopsisString = s;
+ }
+
+ /**
+ * Indicates whether or not help options are enabled.
+ *
+ * @return true if help options are enabled
+ * @see ArgParser#setHelpOptionsEnabled
+ * @see ArgParser#addOption
+ */
+ public boolean getHelpOptionsEnabled() {
+ return helpOptionsEnabled;
+ }
+
+ /**
+ * Enables or disables help options. Help options are those associated with
+ * a conversion code of <code>%h</code>. If help options are enabled, and a
+ * help option is matched, then the string produced by
+ * {@link #getHelpMessage getHelpMessage} is printed to the default print
+ * stream and the program exits with code 0. Otherwise, arguments which
+ * match help options are ignored.
+ *
+ * @param enable enables help options if <code>true</code>.
+ * @see ArgParser#getHelpOptionsEnabled
+ * @see ArgParser#addOption
+ * @see ArgParser#setDefaultPrintStream
+ */
+ public void setHelpOptionsEnabled(boolean enable) {
+ helpOptionsEnabled = enable;
+ }
+
+ /**
+ * Returns the default print stream used for outputting help and error
+ * information.
+ *
+ * @return default print stream
+ * @see ArgParser#setDefaultPrintStream
+ */
+ public PrintStream getDefaultPrintStream() {
+ return printStream;
+ }
+
+ /**
+ * Sets the default print stream used for outputting help and error
+ * information.
+ *
+ * @param stream new default print stream
+ * @see ArgParser#getDefaultPrintStream
+ */
+ public void setDefaultPrintStream(PrintStream stream) {
+ printStream = stream;
+ }
+
+ /**
+ * Gets the indentation used by {@link #getHelpMessage getHelpMessage}.
+ *
+ * @return number of indentation columns
+ * @see ArgParser#setHelpIndentation
+ * @see ArgParser#getHelpMessage
+ */
+ public int getHelpIndentation() {
+ return helpIndent;
+ }
+
+ /**
+ * Sets the indentation used by {@link #getHelpMessage getHelpMessage}. This
+ * is the number of columns that an option's help information is indented.
+ * If the option's name and value information can fit within this number of
+ * columns, then all information about the option is placed on one line.
+ * Otherwise, the indented help information is placed on a separate line.
+ *
+ * @param indent number of indentation columns
+ * @see ArgParser#getHelpIndentation
+ * @see ArgParser#getHelpMessage
+ */
+ public void setHelpIndentation(int indent) {
+ helpIndent = indent;
+ }
+
+ // public void setTabSpacing (int n)
+ // { tabSpacing = n;
+ // }
+
+ // public int getTabSpacing ()
+ // { return tabSpacing;
+ // }
+
+ private void scanRangeSpec(Record rec, String s)
+ throws IllegalArgumentException {
+ StringScanner scanner = new StringScanner(s);
+ int i0, i = 1;
+ char c, c0, c1;
+
+ scanner.setStringDelimiters(")],}");
+ c = scanner.getc(); // swallow the first '{'
+ scanner.skipWhiteSpace();
+ while ((c = scanner.peekc()) != '}') {
+ RangePnt p0, p1;
+
+ if (c == '[' || c == '(') {
+ if (rec.convertCode == 'v' || rec.convertCode == 'b') {
+ throw new IllegalArgumentException("Sub ranges not supported for %b or %v");
+ }
+ c0 = scanner.getc(); // record & swallow character
+ scanner.skipWhiteSpace();
+ p0 = new RangePnt(scanner, rec.type);
+ scanner.skipWhiteSpace();
+ if (scanner.getc() != ',') {
+ throw new IllegalArgumentException("Missing ',' in subrange specification");
+ }
+ p1 = new RangePnt(scanner, rec.type);
+ scanner.skipWhiteSpace();
+ if ((c1 = scanner.getc()) != ']' && c1 != ')') {
+ throw new IllegalArgumentException("Unterminated subrange");
+ }
+ if (c0 == '(') {
+ p0.setClosed(false);
+ }
+ if (c1 == ')') {
+ p1.setClosed(false);
+ }
+ rec.addRangeAtom(new RangeAtom(p0, p1, rec.type));
+ } else {
+ scanner.skipWhiteSpace();
+ p0 = new RangePnt(scanner, rec.type);
+ rec.addRangeAtom(new RangeAtom(p0));
+ }
+ scanner.skipWhiteSpace();
+ if ((c = scanner.peekc()) == ',') {
+ scanner.getc();
+ scanner.skipWhiteSpace();
+ } else if (c != '}') {
+ throw new IllegalArgumentException("Range spec: ',' or '}' expected");
+ }
+ }
+ if (rec.numRangeAtoms() == 1) {
+ rec.rangeDesc = s.substring(1, s.length() - 1);
+ } else {
+ rec.rangeDesc = s;
+ }
+ }
+
+ private int defaultResultType(char convertCode) {
+ switch (convertCode) {
+ case 'i':
+ case 'o':
+ case 'd':
+ case 'x': {
+ return Record.LONG;
+ }
+ case 'c': {
+ return Record.CHAR;
+ }
+ case 'v':
+ case 'b': {
+ return Record.BOOLEAN;
+ }
+ case 'f': {
+ return Record.DOUBLE;
+ }
+ case 's': {
+ return Record.STRING;
+ }
+ }
+ return Record.NOTYPE;
+ }
+
+ /**
+ * Adds a new option description to the parser. The method takes two
+ * arguments: a specification string, and a result holder in which to store
+ * the associated value.
+ *
+ * <p>
+ * The specification string has the general form
+ *
+ * <p>
+ * <var>optionNames</var> <code>%</code><var>conversionCode</var> [
+ * <code>{</code><var>rangeSpec</var><code>}</code>] [<code>X</code>
+ * <var>multiplier</var>] [<code>#</code><var>valueDescription</var>] [
+ * <code>#</code><var>optionDescription</var>] </code>
+ *
+ * <p>
+ * where
+ * <ul>
+ * <p>
+ * <li><var>optionNames</var> is a comma-separated list of names for the
+ * option (such as <code>-f, --file</code>).
+ *
+ * <p>
+ * <li><var>conversionCode</var> is a single letter, following a
+ * <code>%</code> character, specifying information about what value the
+ * option requires:
+ *
+ * <table>
+ * <tr>
+ * <td><code>%f</code></td>
+ * <td>a floating point number</td>
+ * <tr>
+ * <td><code>%i</code></td>
+ * <td>an integer, in either decimal, hex (if preceeded by <code>0x</code>),
+ * or octal (if preceeded by <code>0</code>)</td>
+ * <tr valign=top>
+ * <td><code>%d</code></td>
+ * <td>a decimal integer</td>
+ * <tr valign=top>
+ * <td><code>%o</code></td>
+ * <td>an octal integer</td>
+ * <tr valign=top>
+ * <td><code>%h</code></td>
+ * <td>a hex integer (without the preceeding <code>0x</code>)</td>
+ * <tr valign=top>
+ * <td><code>%c</code></td>
+ * <td>a single character, including escape sequences (such as
+ * <code>\n</code> or <code>\007</code>), and optionally enclosed in single
+ * quotes
+ * <tr valign=top>
+ * <td><code>%b</code></td>
+ * <td>a boolean value (<code>true</code> or <code>false</code>)</td>
+ * <tr valign=top>
+ * <td><code>%s</code></td>
+ * <td>a string. This will be the argument string itself (or its remainder,
+ * in the case of a single word option)</td>
+ * <tr valign=top>
+ * <td><code>%v</code></td>
+ * <td>no explicit value is expected, but a boolean value of
+ * <code>true</code> (by default) will be stored into the associated result
+ * holder if this option is matched. If one wishes to have a value of
+ * <code>false</code> stored instead, then the <code>%v</code> should be
+ * followed by a "range spec" containing <code>false</code>, as in
+ * <code>%v{false}</code>.
+ * </table>
+ *
+ * <p>
+ * <li><var>rangeSpec</var> is an optional range specification, placed
+ * inside curly braces, consisting of a comma-separated list of range items
+ * each specifying permissible values for the option. A range item may be an
+ * individual value, or it may itself be a subrange, consisting of two
+ * individual values, separated by a comma, and enclosed in square or round
+ * brackets. Square and round brackets denote closed and open endpoints of a
+ * subrange, indicating that the associated endpoint value is included or
+ * excluded from the subrange. The values specified in the range spec need
+ * to be consistent with the type of value expected by the option.
+ *
+ * <p>
+ * <b>Examples:</b>
+ *
+ * <p>
+ * A range spec of <code>{2,4,8,16}</code> for an integer value will allow
+ * the integers 2, 4, 8, or 16.
+ *
+ * <p>
+ * A range spec of <code>{[-1.0,1.0]}</code> for a floating point value will
+ * allow any floating point number in the range -1.0 to 1.0.
+ *
+ * <p>
+ * A range spec of <code>{(-88,100],1000}</code> for an integer value will
+ * allow values > -88 and <= 100, as well as 1000.
+ *
+ * <p>
+ * A range spec of <code>{"foo", "bar", ["aaa","zzz")} </code> for a string
+ * value will allow strings equal to <code>"foo"</code> or
+ * <code>"bar"</code>, plus any string lexically greater than or equal to
+ * <code>"aaa"</code> but less then <code>"zzz"</code>.
+ *
+ * <p>
+ * <li><var>multiplier</var> is an optional integer, following a
+ * <code>X</code> character, indicating the number of values which the
+ * option expects. If the multiplier is not specified, it is assumed to be
+ * 1. If the multiplier value is greater than 1, then the result holder
+ * should be either an array (of appropriate type) with a length greater
+ * than or equal to the multiplier value, or a <code>java.util.Vector</code>
+ * <a href=#vectorHolder>as discussed below</a>.
+ *
+ * <p>
+ * <li><var>valueDescription</var> is an optional description of the
+ * option's value requirements, and consists of all characters between two
+ * <code>#</code> characters. The final <code>#</code> character initiates
+ * the <i>option description</i>, which may be empty. The value description
+ * is used in <a href=#helpInfo>generating help messages</a>.
+ *
+ * <p>
+ * <li><var>optionDescription</var> is an optional description of the option
+ * itself, consisting of all characters between a <code>#</code> character
+ * and the end of the specification string. The option description is used
+ * in <a href=#helpInfo>generating help messages</a>.
+ * </ul>
+ *
+ * <p>
+ * The result holder must be an object capable of holding a value compatible
+ * with the conversion code, or it must be a <code>java.util.Vector</code>.
+ * When the option is matched, its associated value is placed in the result
+ * holder. If the same option is matched repeatedly, the result holder value
+ * will be overwritten, unless the result holder is a
+ * <code>java.util.Vector</code>, in which case new holder objects for each
+ * match will be allocated and added to the vector. Thus if multiple
+ * instances of an option are desired by the program, the result holder
+ * should be a <code>java.util.Vector</code>.
+ *
+ * <p>
+ * If the result holder is not a <code>Vector</code>, then it must
+ * correspond as follows to the conversion code:
+ *
+ * <table>
+ * <tr valign=top>
+ * <td><code>%i</code>, <code>%d</code>, <code>%x</code>, <code>%o</code></td>
+ * <td>{@link argparser.IntHolder IntHolder}, {@link argparser.LongHolder
+ * LongHolder}, <code>int[]</code>, or <code>long[]</code></td>
+ * </tr>
+ *
+ * <tr valign=top>
+ * <td><code>%f</code></td>
+ * <td>{@link argparser.FloatHolder FloatHolder},
+ * {@link argparser.DoubleHolder DoubleHolder}, <code>float[]</code>, or
+ * <code>double[]</code></td>
+ * </tr>
+ *
+ * <tr valign=top>
+ * <td><code>%b</code>, <code>%v</code></td>
+ * <td>{@link argparser.BooleanHolder BooleanHolder} or
+ * <code>boolean[]</code></td>
+ * </tr>
+ *
+ * <tr valign=top>
+ * <td><code>%s</code></td>
+ * <td>{@link argparser.StringHolder StringHolder} or <code>String[]</code></td>
+ * </tr>
+ *
+ * <tr valign=top>
+ * <td><code>%c</code></td>
+ * <td>{@link argparser.CharHolder CharHolder} or <code>char[]</code></td>
+ * </tr>
+ * </table>
+ *
+ * <p>
+ * In addition, if the multiplier is greater than 1, then only the array
+ * type indicated above may be used, and the array must be at least as long
+ * as the multiplier.
+ *
+ * <p>
+ * <a name=vectorHolder>If the result holder is a <code>Vector</code>, then
+ * the system will create an appropriate result holder object and add it to
+ * the vector. Multiple occurances of the option will cause multiple results
+ * to be added to the vector.
+ *
+ * <p>
+ * The object allocated by the system to store the result will correspond to
+ * the conversion code as follows:
+ *
+ * <table>
+ * <tr valign=top>
+ * <td><code>%i</code>, <code>%d</code>, <code>%x</code>, <code>%o</code></td>
+ * <td>{@link argparser.LongHolder LongHolder}, or <code>long[]</code> if
+ * the multiplier value exceeds 1</td>
+ * </tr>
+ *
+ * <tr valign=top>
+ * <td><code>%f</code></td>
+ * <td>{@link argparser.DoubleHolder DoubleHolder}, or <code>double[]</code>
+ * if the multiplier value exceeds 1</td>
+ * </tr>
+ *
+ * <tr valign=top>
+ * <td><code>%b</code>, <code>%v</code></td>
+ * <td>{@link argparser.BooleanHolder BooleanHolder}, or
+ * <code>boolean[]</code> if the multiplier value exceeds 1</td>
+ * </tr>
+ *
+ * <tr valign=top>
+ * <td><code>%s</code></td>
+ * <td>{@link argparser.StringHolder StringHolder}, or <code>String[]</code>
+ * if the multiplier value exceeds 1</td>
+ * </tr>
+ *
+ * <tr valign=top>
+ * <td><code>%c</code></td>
+ * <td>{@link argparser.CharHolder CharHolder}, or <code>char[]</code> if
+ * the multiplier value exceeds 1</td>
+ * </tr>
+ * </table>
+ *
+ * @param spec the specification string
+ * @param resHolder object in which to store the associated value
+ * @throws IllegalArgumentException if there is an error in the
+ * specification or if the result holder is of an invalid type.
+ */
+ public void addOption(String spec, Object resHolder)
+ throws IllegalArgumentException {
+ // null terminated string is easier to parse
+ StringScanner scanner = new StringScanner(spec);
+ Record rec = null;
+ NameDesc nameTail = null;
+ NameDesc ndesc;
+ int i0, i1;
+ char c;
+
+ do {
+ ndesc = new NameDesc();
+ boolean nameEndsInWhiteSpace = false;
+
+ scanner.skipWhiteSpace();
+ i0 = scanner.getIndex();
+ while (!Character.isWhitespace(c = scanner.getc()) &&
+ c != ',' && c != '%' && c != '\000')
+ ;
+ i1 = scanner.getIndex();
+ if (c != '\000') {
+ i1--;
+ }
+ if (i0 == i1) { // then c is one of ',' '%' or '\000'
+ throw new IllegalArgumentException("Null option name given");
+ }
+ if (Character.isWhitespace(c)) {
+ nameEndsInWhiteSpace = true;
+ scanner.skipWhiteSpace();
+ c = scanner.getc();
+ }
+ if (c == '\000') {
+ throw new IllegalArgumentException("No conversion character given");
+ }
+ if (c != ',' && c != '%') {
+ throw new IllegalArgumentException("Names not separated by ','");
+ }
+ ndesc.name = scanner.substring(i0, i1);
+ if (rec == null) {
+ rec = new Record();
+ rec.nameList = ndesc;
+ } else {
+ nameTail.next = ndesc;
+ }
+ nameTail = ndesc;
+ ndesc.oneWord = !nameEndsInWhiteSpace;
+ } while (c != '%');
+
+ if (!nameTail.oneWord) {
+ for (ndesc = rec.nameList; ndesc != null; ndesc = ndesc.next) {
+ ndesc.oneWord = false;
+ }
+ }
+ c = scanner.getc();
+ if (c == '\000') {
+ throw new IllegalArgumentException("No conversion character given");
+ }
+ if (validConversionCodes.indexOf(c) == -1) {
+ throw new IllegalArgumentException("Conversion code '" + c + "' not one of '" +
+ validConversionCodes + "'");
+ }
+ rec.convertCode = c;
+
+ if (resHolder instanceof Vector) {
+ rec.vectorResult = true;
+ rec.type = defaultResultType(rec.convertCode);
+ } else {
+ switch (rec.convertCode) {
+ case 'i':
+ case 'o':
+ case 'd':
+ case 'x': {
+ if (resHolder instanceof LongHolder ||
+ resHolder instanceof long[]) {
+ rec.type = Record.LONG;
+ } else if (resHolder instanceof IntHolder ||
+ resHolder instanceof int[]) {
+ rec.type = Record.INT;
+ } else {
+ throw new IllegalArgumentException(
+ "Invalid result holder for %" + c);
+ }
+ break;
+ }
+ case 'c': {
+ if (!(resHolder instanceof CharHolder) &&
+ !(resHolder instanceof char[])) {
+ throw new IllegalArgumentException(
+ "Invalid result holder for %c");
+ }
+ rec.type = Record.CHAR;
+ break;
+ }
+ case 'v':
+ case 'b': {
+ if (!(resHolder instanceof BooleanHolder) &&
+ !(resHolder instanceof boolean[])) {
+ throw new IllegalArgumentException(
+ "Invalid result holder for %" + c);
+ }
+ rec.type = Record.BOOLEAN;
+ break;
+ }
+ case 'f': {
+ if (resHolder instanceof DoubleHolder ||
+ resHolder instanceof double[]) {
+ rec.type = Record.DOUBLE;
+ } else if (resHolder instanceof FloatHolder ||
+ resHolder instanceof float[]) {
+ rec.type = Record.FLOAT;
+ } else {
+ throw new IllegalArgumentException(
+ "Invalid result holder for %f");
+ }
+ break;
+ }
+ case 's': {
+ if (!(resHolder instanceof StringHolder) &&
+ !(resHolder instanceof String[])) {
+ throw new IllegalArgumentException(
+ "Invalid result holder for %s");
+ }
+ rec.type = Record.STRING;
+ break;
+ }
+ case 'h': { // resHolder is ignored for this type
+ break;
+ }
+ }
+ }
+ if (rec.convertCode == 'h') {
+ rec.resHolder = null;
+ } else {
+ rec.resHolder = resHolder;
+ }
+
+ scanner.skipWhiteSpace();
+ // get the range specification, if any
+ if (scanner.peekc() == '{') {
+ if (rec.convertCode == 'h') {
+ throw new IllegalArgumentException("Ranges not supported for %h");
+ }
+ // int bcnt = 0;
+ i0 = scanner.getIndex(); // beginning of range spec
+ do {
+ c = scanner.getc();
+ if (c == '\000') {
+ throw new IllegalArgumentException("Unterminated range specification");
+ }
+ // else if (c=='[' || c=='(')
+ // { bcnt++;
+ // }
+ // else if (c==']' || c==')')
+ // { bcnt--;
+ // }
+ // if ((rec.convertCode=='v'||rec.convertCode=='b') && bcnt>1)
+ // { throw new IllegalArgumentException
+ // ("Sub ranges not supported for %b or %v");
+ // }
+ } while (c != '}');
+ // if (c != ']')
+ // { throw new IllegalArgumentException
+ // ("Range specification must end with ']'");
+ // }
+ i1 = scanner.getIndex(); // end of range spec
+ scanRangeSpec(rec, scanner.substring(i0, i1));
+ if (rec.convertCode == 'v' && rec.rangeList != null) {
+ rec.vval = rec.rangeList.low.bval;
+ }
+ }
+ // check for value multiplicity information, if any
+ if (scanner.peekc() == 'X') {
+ if (rec.convertCode == 'h') {
+ throw new IllegalArgumentException("Multipliers not supported for %h");
+ }
+ scanner.getc();
+ try {
+ rec.numValues = (int) scanner.scanInt();
+ } catch (StringScanException e) {
+ throw new IllegalArgumentException("Malformed value multiplier");
+ }
+ if (rec.numValues <= 0) {
+ throw new IllegalArgumentException("Value multiplier number must be > 0");
+ }
+ } else {
+ rec.numValues = 1;
+ }
+ if (rec.numValues > 1) {
+ for (ndesc = rec.nameList; ndesc != null; ndesc = ndesc.next) {
+ if (ndesc.oneWord) {
+ throw new IllegalArgumentException(
+ "Multiplier value incompatible with one word option " + ndesc.name);
+ }
+ }
+ }
+ if (resHolder != null && resHolder.getClass().isArray()) {
+ if (Array.getLength(resHolder) < rec.numValues) {
+ throw new IllegalArgumentException(
+ "Result holder array must have a length >= " + rec.numValues);
+ }
+ } else {
+ if (rec.numValues > 1 && !(resHolder instanceof Vector)) {
+ throw new IllegalArgumentException(
+ "Multiplier requires result holder to be an array of length >= "
+ + rec.numValues);
+ }
+ }
+
+ // skip white space following conversion information
+ scanner.skipWhiteSpace();
+
+ // get the help message, if any
+
+ if (!scanner.atEnd()) {
+ if (scanner.getc() != '#') {
+ throw new IllegalArgumentException("Illegal character(s), expecting '#'");
+ }
+ String helpInfo = scanner.substring(scanner.getIndex());
+ // look for second '#'. If there is one, then info
+ // between the first and second '#' is the value descriptor.
+ int k = helpInfo.indexOf("#");
+ if (k != -1) {
+ rec.valueDesc = helpInfo.substring(0, k);
+ rec.helpMsg = helpInfo.substring(k + 1);
+ } else {
+ rec.helpMsg = helpInfo;
+ }
+ } else {
+ rec.helpMsg = "";
+ }
+
+ // parse helpMsg for required/optional information if present
+ // default to required
+ if (rec.helpMsg.indexOf("(optional") != -1) {
+ rec.required = false;
+ }
+
+ // add option information to match list
+ if (rec.convertCode == 'h' && firstHelpOption == defaultHelpOption) {
+ matchList.remove(defaultHelpOption);
+ firstHelpOption = rec;
+ }
+ matchList.add(rec);
+ }
+
+ Record lastMatchRecord() {
+ return (Record) matchList.lastElement();
+ }
+
+ private Record getRecord(String arg, ObjectHolder ndescHolder) {
+ NameDesc ndesc;
+ for (int i = 0; i < matchList.size(); i++) {
+ Record rec = (Record) matchList.get(i);
+ for (ndesc = rec.nameList; ndesc != null; ndesc = ndesc.next) {
+ if (rec.convertCode != 'v' && ndesc.oneWord) {
+ if (arg.startsWith(ndesc.name)) {
+ if (ndescHolder != null) {
+ ndescHolder.value = ndesc;
+ }
+ return rec;
+ }
+ } else {
+ if (arg.equals(ndesc.name)) {
+ if (ndescHolder != null) {
+ ndescHolder.value = ndesc;
+ }
+ return rec;
+ }
+ }
+ }
+ }
+ return null;
+ }
+
+ public void checkRequiredArgs() {
+ for (int i = 1; i < matchList.size(); i++) {
+ Record rec = (Record) matchList.get(i);
+ StringHolder myString = (StringHolder) rec.resHolder;
+ if (((myString.value == null) || (myString.value.equals(""))) && (rec.required)) {
+ printErrorAndExit("Required parameter " + rec.nameList.name + " is not specified.");
+ }
+ }
+ }
+
+ Object getResultHolder(String arg) {
+ Record rec = getRecord(arg, null);
+ return (rec != null) ? rec.resHolder : null;
+ }
+
+ String getOptionName(String arg) {
+ ObjectHolder ndescHolder = new ObjectHolder();
+ Record rec = getRecord(arg, ndescHolder);
+ return (rec != null) ? ((NameDesc) ndescHolder.value).name : null;
+ }
+
+ String getOptionRangeDesc(String arg) {
+ Record rec = getRecord(arg, null);
+ return (rec != null) ? rec.rangeDesc : null;
+ }
+
+ String getOptionTypeName(String arg) {
+ Record rec = getRecord(arg, null);
+ return (rec != null) ? rec.valTypeName() : null;
+ }
+
+ private Object createResultHolder(Record rec) {
+ if (rec.numValues == 1) {
+ switch (rec.type) {
+ case Record.LONG: {
+ return new LongHolder();
+ }
+ case Record.CHAR: {
+ return new CharHolder();
+ }
+ case Record.BOOLEAN: {
+ return new BooleanHolder();
+ }
+ case Record.DOUBLE: {
+ return new DoubleHolder();
+ }
+ case Record.STRING: {
+ return new StringHolder();
+ }
+ }
+ } else {
+ switch (rec.type) {
+ case Record.LONG: {
+ return new long[rec.numValues];
+ }
+ case Record.CHAR: {
+ return new char[rec.numValues];
+ }
+ case Record.BOOLEAN: {
+ return new boolean[rec.numValues];
+ }
+ case Record.DOUBLE: {
+ return new double[rec.numValues];
+ }
+ case Record.STRING: {
+ return new String[rec.numValues];
+ }
+ }
+ }
+ return null; // can't happen
+ }
+
+ static void stringToArgs(Vector<String> vec, String s,
+ boolean allowQuotedStrings)
+ throws StringScanException {
+ StringScanner scanner = new StringScanner(s);
+ scanner.skipWhiteSpace();
+ while (!scanner.atEnd()) {
+ if (allowQuotedStrings) {
+ vec.add(scanner.scanString());
+ } else {
+ vec.add(scanner.scanNonWhiteSpaceString());
+ }
+ scanner.skipWhiteSpace();
+ }
+ }
+
+ /**
+ * Reads in a set of strings from a reader and prepends them to an argument
+ * list. Strings are delimited by either whitespace or double quotes
+ * <code>"</code>. The character <code>#</code> acts as a comment character,
+ * causing input to the end of the current line to be ignored.
+ *
+ * @param reader Reader from which to read the strings
+ * @param args Initial set of argument values. Can be specified as
+ * <code>null</code>.
+ * @throws IOException if an error occured while reading.
+ */
+ public static String[] prependArgs(Reader reader, String[] args)
+ throws IOException {
+ if (args == null) {
+ args = new String[0];
+ }
+ LineNumberReader lineReader = new LineNumberReader(reader);
+ Vector<String> vec = new Vector<String>(100, 100);
+ String line;
+ int i, k;
+
+ while ((line = lineReader.readLine()) != null) {
+ int commentIdx = line.indexOf("#");
+ if (commentIdx != -1) {
+ line = line.substring(0, commentIdx);
+ }
+ try {
+ stringToArgs(vec, line, /* allowQuotedStings= */true);
+ } catch (StringScanException e) {
+ throw new IOException(
+ "malformed string, line " + lineReader.getLineNumber());
+ }
+ }
+ String[] result = new String[vec.size() + args.length];
+ for (i = 0; i < vec.size(); i++) {
+ result[i] = (String) vec.get(i);
+ }
+ for (k = 0; k < args.length; k++) {
+ result[i++] = args[k];
+ }
+ return result;
+ }
+
+ /**
+ * Reads in a set of strings from a file and prepends them to an argument
+ * list. Strings are delimited by either whitespace or double quotes
+ * <code>"</code>. The character <code>#</code> acts as a comment character,
+ * causing input to the end of the current line to be ignored.
+ *
+ * @param file File to be read
+ * @param args Initial set of argument values. Can be specified as
+ * <code>null</code>.
+ * @throws IOException if an error occured while reading the file.
+ */
+ public static String[] prependArgs(File file, String[] args)
+ throws IOException {
+ if (args == null) {
+ args = new String[0];
+ }
+ if (!file.canRead()) {
+ return args;
+ }
+ try {
+ return prependArgs(new FileReader(file), args);
+ } catch (IOException e) {
+ throw new IOException(
+ "File " + file.getName() + ": " + e.getMessage());
+ }
+ }
+
+ /**
+ * Sets the parser's error message.
+ *
+ * @param s Error message
+ */
+ protected void setError(String msg) {
+ errMsg = msg;
+ }
+
+ /**
+ * Prints an error message, along with a pointer to help options, if
+ * available, and causes the program to exit with code 1.
+ */
+ public void printErrorAndExit(String msg) {
+ if (helpOptionsEnabled && firstHelpOptionName() != null) {
+ msg += "\nUse " + firstHelpOptionName() + " for help information";
+ }
+ if (printStream != null) {
+ printStream.println(msg);
+ }
+ System.exit(1);
+ }
+
+ /**
+ * Matches arguments within an argument list.
+ *
+ * <p>
+ * In the event of an erroneous or unmatched argument, the method prints a
+ * message and exits the program with code 1.
+ *
+ * <p>
+ * If help options are enabled and one of the arguments matches a help
+ * option, then the result of {@link #getHelpMessage getHelpMessage} is
+ * printed to the default print stream and the program exits with code 0. If
+ * help options are not enabled, they are ignored.
+ *
+ * @param args argument list
+ * @see ArgParser#getDefaultPrintStream
+ */
+ public void matchAllArgs(String[] args) {
+ matchAllArgs(args, 0, EXIT_ON_UNMATCHED | EXIT_ON_ERROR);
+ }
+
+ /**
+ * Matches arguments within an argument list and returns those which were
+ * not matched. The matching starts at a location in <code>args</code>
+ * specified by <code>idx</code>, and unmatched arguments are returned in a
+ * String array.
+ *
+ * <p>
+ * In the event of an erroneous argument, the method either prints a message
+ * and exits the program (if {@link #EXIT_ON_ERROR} is set in
+ * <code>exitFlags</code>) or terminates the matching and creates a error
+ * message that can be retrieved by {@link #getErrorMessage}.
+ *
+ * <p>
+ * In the event of an umatched argument, the method will print a message and
+ * exit if {@link #EXIT_ON_UNMATCHED} is set in <code>errorFlags</code>.
+ * Otherwise, the unmatched argument will be appended to the returned array
+ * of unmatched values, and the matching will continue at the next location.
+ *
+ * <p>
+ * If help options are enabled and one of the arguments matches a help
+ * option, then the result of {@link #getHelpMessage getHelpMessage} is
+ * printed to the the default print stream and the program exits with code
+ * 0. If help options are not enabled, then they will not be matched.
+ *
+ * @param args argument list
+ * @param idx starting location in list
+ * @param exitFlags conditions causing the program to exit. Should be an
+ * or-ed combintion of {@link #EXIT_ON_ERROR} or
+ * {@link #EXIT_ON_UNMATCHED}.
+ * @return array of arguments that were not matched, or <code>null</code> if
+ * all arguments were successfully matched
+ * @see ArgParser#getErrorMessage
+ * @see ArgParser#getDefaultPrintStream
+ */
+ public String[] matchAllArgs(String[] args, int idx, int exitFlags) {
+ Vector<String> unmatched = new Vector<String>(10);
+
+ while (idx < args.length) {
+ try {
+ idx = matchArg(args, idx);
+ if (unmatchedArg != null) {
+ if ((exitFlags & EXIT_ON_UNMATCHED) != 0) {
+ printErrorAndExit("Unrecognized argument: " + unmatchedArg);
+ } else {
+ unmatched.add(unmatchedArg);
+ }
+ }
+ } catch (ArgParseException e) {
+ if ((exitFlags & EXIT_ON_ERROR) != 0) {
+ printErrorAndExit(e.getMessage());
+ }
+ break;
+ }
+ }
+ if (unmatched.size() == 0) {
+ return null;
+ } else {
+ return (String[]) unmatched.toArray(new String[0]);
+ }
+ }
+
+ /**
+ * Matches one option starting at a specified location in an argument list.
+ * The method returns the location in the list where the next match should
+ * begin.
+ *
+ * <p>
+ * In the event of an erroneous argument, the method throws an
+ * {@link argparser.ArgParseException ArgParseException} with an appropriate
+ * error message. This error message can also be retrieved using
+ * {@link #getErrorMessage getErrorMessage}.
+ *
+ * <p>
+ * In the event of an umatched argument, the method will return idx + 1, and
+ * {@link #getUnmatchedArgument getUnmatchedArgument} will return a copy of
+ * the unmatched argument. If an argument is matched,
+ * {@link #getUnmatchedArgument getUnmatchedArgument} will return
+ * <code>null</code>.
+ *
+ * <p>
+ * If help options are enabled and the argument matches a help option, then
+ * the result of {@link #getHelpMessage getHelpMessage} is printed to the
+ * the default print stream and the program exits with code 0. If help
+ * options are not enabled, then they are ignored.
+ *
+ * @param args argument list
+ * @param idx location in list where match should start
+ * @return location in list where next match should start
+ * @throws ArgParseException if there was an error performing the match
+ * (such as improper or insufficient values).
+ * @see ArgParser#setDefaultPrintStream
+ * @see ArgParser#getHelpOptionsEnabled
+ * @see ArgParser#getErrorMessage
+ * @see ArgParser#getUnmatchedArgument
+ */
+ @SuppressWarnings("unchecked")
+ public int matchArg(String[] args, int idx)
+ throws ArgParseException {
+ unmatchedArg = null;
+ setError(null);
+ try {
+ ObjectHolder ndescHolder = new ObjectHolder();
+ Record rec = getRecord(args[idx], ndescHolder);
+ if (rec == null || (rec.convertCode == 'h' && !helpOptionsEnabled)) { // didn't
+ // match
+ unmatchedArg = new String(args[idx]);
+ return idx + 1;
+ }
+ NameDesc ndesc = (NameDesc) ndescHolder.value;
+ Object result;
+ if (rec.resHolder instanceof Vector) {
+ result = createResultHolder(rec);
+ } else {
+ result = rec.resHolder;
+ }
+ if (rec.convertCode == 'h') {
+ if (helpOptionsEnabled) {
+ printStream.println(getHelpMessage());
+ System.exit(0);
+ } else {
+ return idx + 1;
+ }
+ } else if (rec.convertCode != 'v') {
+ if (ndesc.oneWord) {
+ rec.scanValue(
+ result, ndesc.name,
+ args[idx].substring(ndesc.name.length()), 0);
+ } else {
+ if (idx + rec.numValues >= args.length) {
+ throw new ArgParseException(
+ ndesc.name, "requires " + rec.numValues + " value" +
+ (rec.numValues > 1 ? "s" : ""));
+ }
+ for (int k = 0; k < rec.numValues; k++) {
+ rec.scanValue(result, ndesc.name, args[++idx], k);
+ }
+ }
+ } else {
+ if (rec.resHolder instanceof BooleanHolder) {
+ ((BooleanHolder) result).value = rec.vval;
+ } else {
+ for (int k = 0; k < rec.numValues; k++) {
+ ((boolean[]) result)[k] = rec.vval;
+ }
+ }
+ }
+ if (rec.resHolder instanceof Vector) {
+ ((Vector<Object>) rec.resHolder).add(result);
+ }
+ } catch (ArgParseException e) {
+ setError(e.getMessage());
+ throw e;
+ }
+ return idx + 1;
+ }
+
+ private String spaceString(int n) {
+ StringBuffer sbuf = new StringBuffer(n);
+ for (int i = 0; i < n; i++) {
+ sbuf.append(' ');
+ }
+ return sbuf.toString();
+ }
+
+ // public String getShortHelpMessage ()
+ // {
+ // String s;
+ // Record rec;
+ // NameDesc ndesc;
+ // int initialIndent = 8;
+ // int col = initialIndent;
+
+ // if (maxcols <= 0)
+ // { maxcols = 80;
+ // }
+ // if (matchList.size() > 0)
+ // { ps.print (spaceString(initialIndent));
+ // }
+ // for (int i=0; i<matchList.size(); i++)
+ // { rec = (Record)matchList.get(i);
+ // s = "[";
+ // for (ndesc=rec.nameList; ndesc!=null; ndesc=ndesc.next)
+ // { s = s + ndesc.name;
+ // if (ndesc.oneWord == false)
+ // { s = s + " ";
+ // }
+ // if (ndesc.next != null)
+ // { s = s + ",";
+ // }
+ // }
+ // if (rec.convertCode != 'v' && rec.convertCode != 'h')
+ // { if (rec.valueDesc != null)
+ // { s += rec.valueDesc;
+ // }
+ // else
+ // { s = s + "<" + rec.valTypeName() + ">";
+ // if (rec.numValues > 1)
+ // { s += "X" + rec.numValues;
+ // }
+ // }
+ // }
+ // s = s + "]";
+ // /*
+ // (col+=s.length()) > (maxcols-1) => we will spill over edge.
+ // we use (maxcols-1) because if we go right to the edge
+ // (maxcols), we get wrap new line inserted "for us".
+ // i != 0 means we print the first entry, no matter
+ // how long it is. Subsequent entries are printed
+ // full length anyway. */
+
+ // if ((col+=s.length()) > (maxcols-1) && i != 0)
+ // { col = initialIndent+s.length();
+ // ps.print ("\n" + spaceString(initialIndent));
+ // }
+ // ps.print (s);
+ // }
+ // if (matchList.size() > 0)
+ // { ps.print ('\n');
+ // ps.flush();
+ // }
+ // }
+
+ /**
+ * Returns a string describing the allowed options in detail.
+ *
+ * @return help information string.
+ */
+ public String getHelpMessage() {
+ Record rec;
+ NameDesc ndesc;
+ boolean hasOneWordAlias = false;
+ String s;
+
+ s = "Usage: " + synopsisString + "\n";
+ s += "Options include:\n\n";
+ for (int i = 0; i < matchList.size(); i++) {
+ String optionInfo = "";
+ rec = (Record) matchList.get(i);
+ if (rec.convertCode == 'h' && !helpOptionsEnabled) {
+ continue;
+ }
+ for (ndesc = rec.nameList; ndesc != null; ndesc = ndesc.next) {
+ if (ndesc.oneWord) {
+ hasOneWordAlias = true;
+ break;
+ }
+ }
+ for (ndesc = rec.nameList; ndesc != null; ndesc = ndesc.next) {
+ optionInfo += ndesc.name;
+ if (hasOneWordAlias && !ndesc.oneWord) {
+ optionInfo += " ";
+ }
+ if (ndesc.next != null) {
+ optionInfo += ",";
+ }
+ }
+ if (!hasOneWordAlias) {
+ optionInfo += " ";
+ }
+ if (rec.convertCode != 'v' && rec.convertCode != 'h') {
+ if (rec.valueDesc != null) {
+ optionInfo += rec.valueDesc;
+ } else {
+ if (rec.rangeDesc != null) {
+ optionInfo += "<" + rec.valTypeName() + " "
+ + rec.rangeDesc + ">";
+ } else {
+ optionInfo += "<" + rec.valTypeName() + ">";
+ }
+ }
+ }
+ if (rec.numValues > 1) {
+ optionInfo += "X" + rec.numValues;
+ }
+ s += optionInfo;
+ if (rec.helpMsg.length() > 0) {
+ int pad = helpIndent - optionInfo.length();
+ if (pad < 2) { // s += '\n';
+ pad = helpIndent;
+ }
+ // s += spaceString(pad) + rec.helpMsg;
+ s += spaceString(4) + rec.helpMsg;
+ }
+ s += '\n';
+ }
+ return s;
+ }
+
+ /**
+ * Returns the parser's error message. This is automatically set whenever an
+ * error is encountered in <code>matchArg</code> or
+ * <code>matchAllArgs</code>, and is automatically set to <code>null</code>
+ * at the beginning of these methods.
+ *
+ * @return error message
+ */
+ public String getErrorMessage() {
+ return errMsg;
+ }
+
+ /**
+ * Returns the value of an unmatched argument discovered {@link #matchArg
+ * matchArg} or {@link #matchAllArgs(String[],int,int) matchAllArgs}. If
+ * there was no unmatched argument, <code>null</code> is returned.
+ *
+ * @return unmatched argument
+ */
+ public String getUnmatchedArgument() {
+ return unmatchedArg;
+ }
+}
diff --git a/pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParserTest.java b/pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParserTest.java
index 579f0f59..762f4f15 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParserTest.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParserTest.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.argparser;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -18,17 +19,17 @@ package com.netscape.pkisilent.argparser;
// --- END COPYRIGHT BLOCK ---
/**
- * Copyright John E. Lloyd, 2004. All rights reserved. Permission to use,
- * copy, modify and redistribute is granted, provided that this copyright
- * notice is retained and the author is given credit whenever appropriate.
- *
- * This software is distributed "as is", without any warranty, including
- * any implied warranty of merchantability or fitness for a particular
- * use. The author assumes no responsibility for, and shall not be liable
- * for, any special, indirect, or consequential damages, or any damages
- * whatsoever, arising out of or in connection with the use of this
- * software.
- */
+ * Copyright John E. Lloyd, 2004. All rights reserved. Permission to use,
+ * copy, modify and redistribute is granted, provided that this copyright
+ * notice is retained and the author is given credit whenever appropriate.
+ *
+ * This software is distributed "as is", without any warranty, including
+ * any implied warranty of merchantability or fitness for a particular
+ * use. The author assumes no responsibility for, and shall not be liable
+ * for, any special, indirect, or consequential damages, or any damages
+ * whatsoever, arising out of or in connection with the use of this
+ * software.
+ */
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
@@ -36,1537 +37,1477 @@ import java.lang.reflect.Array;
import java.util.Vector;
/**
- * Testing class for the class ArgParser. Executing the <code>main</code>
- * method of this class will perform a suite of tests to help verify correct
- * operation of the parser class.
- *
+ * Testing class for the class ArgParser. Executing the <code>main</code> method
+ * of this class will perform a suite of tests to help verify correct operation
+ * of the parser class.
+ *
* @author John E. Lloyd, Fall 2004
* @see ArgParser
*/
-public class ArgParserTest
-{
- ArgParser parser;
-
- static final boolean CLOSED = true;
- static final boolean OPEN = false;
-
- static final boolean ONE_WORD = true;
- static final boolean MULTI_WORD = false;
-
- private static void verify (boolean ok, String msg)
- { if (!ok)
- { Throwable e = new Throwable();
- System.out.println ("Verification failed:" + msg);
- e.printStackTrace();
- System.exit(1);
- }
- }
-
- private static String[] argsFromString (String s)
- {
- Vector<String> vec = new Vector<String>(100);
- try
- { ArgParser.stringToArgs (vec, s, /*allowQuotedStings=*/false);
- }
- catch (StringScanException e)
- { e.printStackTrace();
- System.exit (1);
- }
- String[] result = new String[vec.size()];
- for (int i=0; i<vec.size(); i++)
- { result[i] = (String)vec.get(i);
- }
- return result;
- }
-
- static class RngCheck
- {
- ArgParser.RangePnt low = null;
- ArgParser.RangePnt high = null;
- int type;
-
- RngCheck (String s)
- { low = new ArgParser.RangePnt (s, CLOSED);
- type = 's';
- }
-
- RngCheck (double d)
- { low = new ArgParser.RangePnt (d, CLOSED);
- type = 'd';
- }
-
- RngCheck (long l)
- { low = new ArgParser.RangePnt (l, CLOSED);
- type = 'l';
- }
-
- RngCheck (boolean b)
- { low = new ArgParser.RangePnt (b, CLOSED);
- type = 'b';
- }
-
- RngCheck (String s1, boolean c1, String s2, boolean c2)
- { low = new ArgParser.RangePnt (s1, c1);
- high = new ArgParser.RangePnt (s2, c2);
- type = 's';
- }
-
- RngCheck (double d1, boolean c1, double d2, boolean c2)
- { low = new ArgParser.RangePnt (d1, c1);
- high = new ArgParser.RangePnt (d2, c2);
- type = 'd';
- }
-
- RngCheck (long l1, boolean c1, long l2, boolean c2)
- { low = new ArgParser.RangePnt (l1, c1);
- high = new ArgParser.RangePnt (l2, c2);
- type = 'l';
- }
-
- void check (ArgParser.RangeAtom ra)
- {
- verify ((ra.low==null) == (low==null),
- "(ra.low==null)=" + (ra.low==null) +
- "(low==null)=" + (low==null));
- verify ((ra.high==null) == (high==null),
- "(ra.high==null)=" + (ra.high==null) +
- "(high==null)=" + (high==null));
-
- if (ra.low != null)
- { switch (type)
- { case 'l':
- { verify (ra.low.lval==low.lval,
- "ra.low=" + ra.low + " low=" + low);
- break;
- }
- case 'd':
- { verify (ra.low.dval==low.dval,
- "ra.low=" + ra.low + " low=" + low);
- break;
- }
- case 's':
- { verify (ra.low.sval.equals (low.sval),
- "ra.low=" + ra.low + " low=" + low);
- break;
- }
- case 'b':
- { verify (ra.low.bval==low.bval,
- "ra.low=" + ra.low + " low=" + low);
- break;
- }
- }
- verify (ra.low.closed==low.closed,
- "ra.low=" + ra.low + " low=" + low);
- }
- if (ra.high != null)
- { switch (type)
- { case 'l':
- { verify (ra.high.lval==high.lval,
- "ra.high=" + ra.high + " high=" + high);
- break;
- }
- case 'd':
- { verify (ra.high.dval==high.dval,
- "ra.high=" + ra.high + " high=" + high);
- break;
- }
- case 's':
- { verify (ra.high.sval.equals (high.sval),
- "ra.high=" + ra.high + " high=" + high);
- break;
- }
- case 'b':
- { verify (ra.high.bval==high.bval,
- "ra.high=" + ra.high + " high=" + high);
- break;
- }
- }
- verify (ra.high.closed==high.closed,
- "ra.high=" + ra.high + " high=" + high);
- }
- }
- }
-
- ArgParserTest ()
- { parser = new ArgParser("fubar");
- }
-
- static void checkException (Exception e, String errmsg)
- { if (errmsg != null)
- { if (!e.getMessage().equals(errmsg))
- { System.out.println (
-"Expecting exception '" + errmsg + "' but got '" +
- e.getMessage() + "'");
- e.printStackTrace();
- (new Throwable()).printStackTrace();
- System.exit(1);
- }
- }
- else
- { System.out.println (
-"Unexpected exception '" + e.getMessage() + "'");
- e.printStackTrace();
- (new Throwable()).printStackTrace();
- System.exit(1);
- }
- }
-
- void checkPrintHelp (String msg)
- {
- ByteArrayOutputStream buf = new ByteArrayOutputStream(0x10000);
- PrintStream ps = new PrintStream(buf);
- ps.println (parser.getHelpMessage());
- System.out.print (buf.toString());
- }
-
-// void checkGetSynopsis (String msg)
-// {
-// ByteArrayOutputStream buf = new ByteArrayOutputStream(0x10000);
-// PrintStream ps = new PrintStream(buf);
-// parser.printSynopsis (ps, 80);
-// System.out.print (buf.toString());
-// }
-
- void checkAdd (String s, Object resHolder, String errmsg)
- {
- checkAdd (s, resHolder, 0, 0, null, null, null, errmsg);
- }
-
- void add (String s, Object resHolder)
- { try
- { parser.addOption (s, resHolder);
- }
- catch (Exception e)
- { e.printStackTrace();
- System.exit (1);
- }
- }
-
- void checkStringArray (String msg, String[] strs, String[] check)
- {
- boolean dontMatch = false;
- if (strs.length != check.length)
- { dontMatch = true;
- }
- else
- { for (int i=0; i<strs.length; i++)
- { if (!strs[i].equals (check[i]))
- { dontMatch = true;
- break;
- }
- }
- }
- if (dontMatch)
- { System.out.println (msg);
- System.out.print ("Expected: ");
- for (int i=0; i<check.length; i++)
- { System.out.print ("'" + check[i] + "'");
- if (i<check.length-1)
- { System.out.print (" ");
- }
- }
- System.out.println ("");
- System.out.print ("Got: ");
- for (int i=0; i<strs.length; i++)
- { System.out.print ("'" + strs[i] + "'");
- if (i<strs.length-1)
- { System.out.print (" ");
- }
- }
- System.out.println ("");
- System.exit(1);
- }
- }
-
- void checkAdd (String s, Object resHolder, int code, int numValues,
- Object names, RngCheck[] rngCheck,
- String helpMsg, String errmsg)
- {
- boolean exceptionThrown = false;
- String[] namelist = null;
- try
- { parser.addOption (s, resHolder);
- }
- catch (Exception e)
- { exceptionThrown = true;
- checkException (e, errmsg);
- }
- if (names instanceof String)
- { namelist = new String[] { (String)names };
- }
- else
- { namelist = (String[])names;
- }
- if (!exceptionThrown)
- { verify (errmsg == null,
- "Expecting exception " + errmsg);
- ArgParser.Record rec = parser.lastMatchRecord();
- verify (rec.convertCode==code,
- "code=" + rec.convertCode + ", expecting " + code);
- ArgParser.NameDesc nd;
- int i=0;
- for (nd=rec.firstNameDesc(); nd!=null; nd=nd.next)
- { i++;
- }
- verify (i==namelist.length,
- "numNames=" + i + ", expecting " +namelist.length);
- i=0;
- for (nd=rec.firstNameDesc(); nd!=null; nd=nd.next)
- { String ss;
- if (!nd.oneWord)
- { ss = new String(nd.name) + ' ';
- }
- else
- { ss = nd.name;
- }
- verify (ss.equals(namelist[i]),
- "have name '"+ss+"', expecting '"+namelist[i]+"'");
- i++;
- }
- ArgParser.RangeAtom ra;
- i=0;
- for (ra=rec.firstRangeAtom(); ra!=null; ra=ra.next)
- { i++;
- }
- int expectedRangeNum = 0;
- if (rngCheck!=null)
- { expectedRangeNum = rngCheck.length;
- }
- verify (i==expectedRangeNum,
- "numRangeAtoms="+i+", expecting "+expectedRangeNum);
- i=0;
- for (ra=rec.firstRangeAtom(); ra!=null; ra=ra.next)
- { rngCheck[i++].check(ra);
- }
- verify (rec.helpMsg.equals(helpMsg),
- "helpMsg="+rec.helpMsg+", expecting "+helpMsg);
- verify (rec.numValues==numValues,
- "numValues="+rec.numValues+", expecting "+numValues);
- }
- }
-
- double getDoubleValue (Object obj, int k)
- {
- if (obj instanceof DoubleHolder)
- { return ((DoubleHolder)obj).value;
- }
- else if (obj instanceof FloatHolder)
- { return ((FloatHolder)obj).value;
- }
- else if (obj instanceof double[])
- { return ((double[])obj)[k];
- }
- else if (obj instanceof float[])
- { return ((float[])obj)[k];
- }
- else
- { verify (false, "object doesn't contain double values");
- return 0;
- }
- }
-
- long getLongValue (Object obj, int k)
- {
- if (obj instanceof LongHolder)
- { return ((LongHolder)obj).value;
- }
- else if (obj instanceof IntHolder)
- { return ((IntHolder)obj).value;
- }
- else if (obj instanceof long[])
- { return ((long[])obj)[k];
- }
- else if (obj instanceof int[])
- { return ((int[])obj)[k];
- }
- else
- { verify (false, "object doesn't contain long values");
- return 0;
- }
- }
-
- String getStringValue (Object obj, int k)
- {
- if (obj instanceof StringHolder)
- { return ((StringHolder)obj).value;
- }
- else if (obj instanceof String[])
- { return ((String[])obj)[k];
- }
- else
- { verify (false, "object doesn't contain String values");
- return null;
- }
- }
-
- boolean getBooleanValue (Object obj, int k)
- {
- if (obj instanceof BooleanHolder)
- { return ((BooleanHolder)obj).value;
- }
- else if (obj instanceof boolean[])
- { return ((boolean[])obj)[k];
- }
- else
- { verify (false, "object doesn't contain boolean values");
- return false;
- }
- }
-
- char getCharValue (Object obj, int k)
- {
- if (obj instanceof CharHolder)
- { return ((CharHolder)obj).value;
- }
- else if (obj instanceof char[])
- { return ((char[])obj)[k];
- }
- else
- { verify (false, "object doesn't contain char values");
- return 0;
- }
- }
-
- static class MErr
- {
- int code;
- String valStr;
-
- MErr (int code, String valStr)
- { this.code = code;
- this.valStr = valStr;
- }
- }
-
- static class MTest
- {
- String args;
- Object result;
- int resultIdx;
-
- MTest (String args, Object result)
- { this (args, result, -1);
- }
-
- MTest (String args, Object result, int resultIdx)
- { this.args = args;
- this.result = result;
- this.resultIdx = resultIdx;
- }
- };
-
- void checkMatch (String args[], int idx, String errMsg)
- { getMatchResult (args, idx, -1, errMsg, -1);
- }
-
- void checkMatch (String args[], int idx, int cnt,
- long check, int resultIdx)
- { Object rholder = getMatchResult (args, idx, cnt, null, resultIdx);
- long result = getLongValue(rholder,0);
- verify (result==check, "result " + result + " vs. " + check);
- }
-
- void checkMatch (String args[], int idx, int cnt,
- double check, int resultIdx)
- { Object rholder = getMatchResult (args, idx, cnt, null, resultIdx);
- double result = getDoubleValue(rholder,0);
- verify (result==check, "result " + result + " vs. " + check);
- }
-
- void checkMatch (String args[], int idx, int cnt,
- String check, int resultIdx)
- { Object rholder = getMatchResult (args, idx, cnt, null, resultIdx);
- String result = getStringValue(rholder,0);
- verify (result.equals(check), "result " + result + " vs. " + check);
- }
-
- void checkMatch (String args[], int idx, int cnt,
- boolean check, int resultIdx)
- { Object rholder = getMatchResult (args, idx, cnt, null, resultIdx);
- boolean result = getBooleanValue(rholder,0);
- verify (result==check, "result " + result + " vs. " + check);
- }
-
- void checkMatch (String args[], int idx, int cnt,
- char check, int resultIdx)
- { Object rholder = getMatchResult (args, idx, cnt, null, resultIdx);
- char result = getCharValue(rholder,0);
- verify (result==check, "result " + result + " vs. " + check);
- }
-
- void checkMatch (String args[], int idx, int cnt,
- Object checkArray, int resultIdx)
- { Object rholder = getMatchResult (args, idx, cnt, null, resultIdx);
- if (!checkArray.getClass().isArray())
- { verify (false, "check is not an array");
- }
- for (int i=0; i<Array.getLength(checkArray); i++)
- { if (checkArray instanceof long[])
- { long result = getLongValue(rholder,i);
- long check = ((long[])checkArray)[i];
- verify (result==check,
- "result ["+i+"] " + result + " vs. " + check);
- }
- else if (checkArray instanceof double[])
- { double result = getDoubleValue(rholder,i);
- double check = ((double[])checkArray)[i];
- verify (result==check,
- "result ["+i+"] " + result + " vs. " + check);
- }
- else if (checkArray instanceof String[])
- { String result = getStringValue(rholder,i);
- String check = ((String[])checkArray)[i];
- verify (result.equals(check),
- "result ["+i+"] " + result + " vs. " + check);
- }
- else if (checkArray instanceof boolean[])
- { boolean result = getBooleanValue(rholder,i);
- boolean check = ((boolean[])checkArray)[i];
- verify (result==check,
- "result ["+i+"] " + result + " vs. " + check);
- }
- else if (checkArray instanceof char[])
- { char result = getCharValue(rholder,i);
- char check = ((char[])checkArray)[i];
- verify (result==check,
- "result ["+i+"] " + result + " vs. " + check);
- }
- else
- { verify (false, "unknown type for checkArray");
- }
- }
- }
-
- void checkMatch (MTest test, boolean oneWord)
- { String[] argv;
- if (oneWord)
- { argv = new String[1];
- argv[0] = test.args;
- }
- else
- { argv = argsFromString(test.args);
- }
- if (test.result instanceof Long)
- { checkMatch (argv, 0, argv.length,
- ((Long)test.result).longValue(),
- test.resultIdx);
- }
- else if (test.result instanceof Double)
- { checkMatch (argv, 0, argv.length,
- ((Double)test.result).doubleValue(),
- test.resultIdx);
- }
- else if (test.result instanceof String)
- { checkMatch (argv, 0, argv.length,
- (String)test.result,
- test.resultIdx);
- }
- else if (test.result instanceof Boolean)
- { checkMatch (argv, 0, argv.length,
- ((Boolean)test.result).booleanValue(),
- test.resultIdx);
- }
- else if (test.result instanceof Character)
- { checkMatch (argv, 0, argv.length,
- ((Character)test.result).charValue(),
- test.resultIdx);
- }
- else if (test.result.getClass().isArray())
- { checkMatch (argv, 0, argv.length, test.result,
- test.resultIdx);
- }
- else if (test.result instanceof MErr)
- { MErr err = (MErr)test.result;
- String argname = parser.getOptionName (argv[0]);
- String msg = "";
-
- switch (err.code)
- { case 'c':
- { msg = "requires a contiguous value";
- break;
- }
- case 'm':
- { msg = "malformed " + parser.getOptionTypeName(argv[0]) +
- " '" + err.valStr + "'";
- break;
- }
- case 'r':
- { msg = "value '" + err.valStr + "' not in range " +
- parser.getOptionRangeDesc(argv[0]);
- break;
- }
- case 'v':
- { msg = "requires " + err.valStr + " values";
- break;
- }
- }
- checkMatch (argv, 0, argname + ": " + msg);
- }
- else
- { verify (false, "Unknown result type");
- }
- }
-
- void checkMatches (MTest[] tests, boolean oneWord)
- { for (int i=0; i<tests.length; i++)
- { checkMatch (tests[i], oneWord);
- }
- }
-
- Object getMatchResult (String args[], int idx, int cnt,
- String errMsg, int resultIdx)
- {
- boolean exceptionThrown = false;
- int k = 0;
- try
- { k = parser.matchArg (args, idx);
- }
- catch (Exception e)
- { exceptionThrown = true;
- checkException (e, errMsg);
- }
- if (!exceptionThrown)
- { verify (k==idx+cnt,
- "Expecting result index " + (idx+cnt) + ", got " + k);
- Object result = parser.getResultHolder(args[0]);
- if (resultIdx >= 0)
- { verify (result instanceof Vector,
- "Expecting result to be stored in a vector");
- Vector<?> vec = (Vector<?>)result;
- verify (vec.size()==resultIdx+1,
- "Expecting result vector size " + (resultIdx+1));
- return vec.get(resultIdx);
- }
- else
- { return result;
- }
- }
- else
- { return null;
- }
- }
-
- /**
- * Runs a set of tests to verify correct operation of the
- * ArgParser class. If all the tests run correctly, the
- * program prints the message <code>Passed</code> and terminates.
- * Otherwise, diagnostic information is printed at the first
- * point of failure.
- */
- public static void main (String[] args)
- {
- ArgParserTest test = new ArgParserTest();
-
- BooleanHolder bh = new BooleanHolder();
- boolean[] b3 = new boolean[3];
- CharHolder ch = new CharHolder();
- char[] c3 = new char[3];
- IntHolder ih = new IntHolder();
- int[] i3 = new int[3];
- LongHolder lh = new LongHolder();
- long[] l3 = new long[3];
- FloatHolder fh = new FloatHolder();
- float[] f3 = new float[3];
- DoubleHolder dh = new DoubleHolder();
- double[] d3 = new double[3];
- StringHolder sh = new StringHolder();
- String[] s3 = new String[3];
-
- test.checkAdd ("-foo %i{[0,10)}X3 #sets the value of foo",
-// 0123456789012345
- i3, 'i', 3, new String[] { "-foo " },
- new RngCheck[] {
- new RngCheck(0, CLOSED, 10, OPEN) },
- "sets the value of foo", null);
-
- test.checkAdd ("-arg1,,", null, "Null option name given");
- test.checkAdd ("-arg1,,goo %f ", null, "Null option name given");
- test.checkAdd (" ", null, "Null option name given");
- test.checkAdd ("", null, "Null option name given");
- test.checkAdd (" %v", null, "Null option name given");
- test.checkAdd ("-foo ", null, "No conversion character given");
- test.checkAdd ("-foo %", null, "No conversion character given");
- test.checkAdd ("foo, aaa bbb ",null,"Names not separated by ','");
- test.checkAdd (" foo aaa %d", null, "Names not separated by ','");
- test.checkAdd ("-arg1,-b,", null, "Null option name given");
- test.checkAdd ("-arg1,-b", null, "No conversion character given");
- test.checkAdd ("-arg1 ", null, "No conversion character given");
- test.checkAdd ("-arg1, %v", null, "Null option name given");
- test.checkAdd ("-arg1,%v", null, "Null option name given");
- test.checkAdd ("-foo %V", null,
- "Conversion code 'V' not one of 'iodxcbfsvh'");
- test.checkAdd ("-h %hX5",null,"Multipliers not supported for %h");
- test.checkAdd ("-h %h{}",null,"Ranges not supported for %h");
- test.checkAdd ("-help, -h %h #here is how we help you",
- null, 'h', 1, new String[] {"-help ", "-h " },
- null, "here is how we help you", null);
-
- test.checkAdd (
- "-arg1 ,-arg2=%d{0,3,(7,16]}X1 #x3 test",
- l3, 'd', 1, new String[] { "-arg1 ", "-arg2=" },
- new RngCheck[]
- { new RngCheck(0),
- new RngCheck(3),
- new RngCheck(7, OPEN, 16, CLOSED),
- },
- "x3 test", null);
-
- test.checkAdd (
- "bbb,ccc%x{[1,2]} #X3 x3 test",
- l3, 'x', 1, new String[] { "bbb", "ccc" },
- new RngCheck[]
- { new RngCheck(1, CLOSED, 2, CLOSED),
- },
- "X3 x3 test", null);
-
- test.checkAdd (
- " bbb ,ccc, ddd ,e , f=%bX1 #x3 test",
- b3, 'b', 1, new String[] { "bbb ", "ccc", "ddd ", "e ", "f=" },
- null,
- "x3 test", null);
-
- test.checkAdd (
- " bbb ,ccc, ddd ,e , f= %bX3 #x3 test",
- b3, 'b', 3, new String[] { "bbb ", "ccc ", "ddd ", "e ","f= " },
- null,
- "x3 test", null);
-
- test.checkAdd (
- "-b,--bar %s{[\"john\",\"jerry\"),fred,\"harry\"} #sets bar",
- sh, 's', 1, new String[] { "-b ", "--bar " },
- new RngCheck[] {
- new RngCheck("jerry",OPEN,"john",CLOSED),
- new RngCheck("fred"),
- new RngCheck("harry") },
- "sets bar", null);
-
- test.checkAdd (
- "-c ,coven%f{0.0,9.0,(6,5],[-9.1,10.2]} ",
- dh, 'f', 1, new String[] { "-c ", "coven" },
- new RngCheck[] {
- new RngCheck(0.0),
- new RngCheck(9.0),
- new RngCheck(5.0,CLOSED,6.0,OPEN),
- new RngCheck(-9.1,CLOSED,10.2,CLOSED) },
- "", null);
-
- test.checkAdd (
- "-b %b #a boolean value ",
- bh, 'b', 1, new String[] { "-b "},
- new RngCheck[] { },
- "a boolean value ", null);
-
- test.checkAdd ("-a %i", ih, 'i', 1, "-a ", null, "", null);
- test.checkAdd ("-a %o", lh, 'o', 1, "-a ", null, "", null);
- test.checkAdd ("-a %d", i3, 'd', 1, "-a ", null, "", null);
- test.checkAdd ("-a %x", l3, 'x', 1, "-a ", null, "", null);
- test.checkAdd ("-a %c", ch, 'c', 1, "-a ", null, "", null);
- test.checkAdd ("-a %c", c3, 'c', 1, "-a ", null, "", null);
- test.checkAdd ("-a %v", bh, 'v', 1, "-a ", null, "", null);
- test.checkAdd ("-a %b", b3, 'b', 1, "-a ", null, "", null);
- test.checkAdd ("-a %f", fh, 'f', 1, "-a ", null, "", null);
- test.checkAdd ("-a %f", f3, 'f', 1, "-a ", null, "", null);
- test.checkAdd ("-a %f", dh, 'f', 1, "-a ", null, "", null);
- test.checkAdd ("-a %f", d3, 'f', 1, "-a ", null, "", null);
-
- test.checkAdd ("-a %i", fh, 'i', 1, "-a ", null, "",
- "Invalid result holder for %i");
- test.checkAdd ("-a %c", i3, 'c', 1, "-a ", null, "",
- "Invalid result holder for %c");
- test.checkAdd ("-a %v", d3, 'v', 1, "-a ", null, "",
- "Invalid result holder for %v");
- test.checkAdd ("-a %f", sh, 'f', 1, "-a ", null, "",
- "Invalid result holder for %f");
- test.checkAdd ("-a %s", l3, 's', 1, "-a ", null, "",
- "Invalid result holder for %s");
-
- test.checkAdd ("-foo %i{} ", ih, 'i', 1, "-foo ", null, "", null);
- test.checkAdd ("-foo%i{}", ih, 'i', 1, "-foo", null, "", null);
- test.checkAdd ("-foo%i{ }", ih, 'i', 1, "-foo", null, "", null);
- test.checkAdd ("-foo%i{ }}", ih,
- "Illegal character(s), expecting '#'");
- test.checkAdd ("-foo%i{ ", ih,"Unterminated range specification");
- test.checkAdd ("-foo%i{", ih, "Unterminated range specification");
- test.checkAdd ("-foo%i{0,9", ih, "Unterminated range specification");
- test.checkAdd ("-foo%i{1,2,3)", ih,
- "Unterminated range specification");
-
- test.checkAdd ("-b %f{0.9}", fh, 'f', 1, "-b ",
- new RngCheck[] { new RngCheck(0.9) },
- "", null);
- test.checkAdd ("-b %f{ 0.9 ,7, -0.5,-4 ,6 }", fh, 'f', 1, "-b ",
- new RngCheck[] { new RngCheck(0.9),
- new RngCheck(7.0),
- new RngCheck(-0.5),
- new RngCheck(-4.0),
- new RngCheck(6.0) },
- "", null);
- test.checkAdd ("-b %f{ [0.9,7), (-0.5,-4),[9,6] , (10,13.4] }",
- fh, 'f', 1, "-b ",
- new RngCheck[] { new RngCheck(0.9,CLOSED,7.0,OPEN),
- new RngCheck(-4.0,OPEN,-.5,OPEN),
- new RngCheck(6.0,CLOSED,9.0,CLOSED),
- new RngCheck(10.0,OPEN,13.4,CLOSED),
- },
- "", null);
- test.checkAdd ("-b %f{(8 9]}", fh,
- "Missing ',' in subrange specification");
- test.checkAdd ("-b %f{(8,9,]}", fh,
- "Unterminated subrange");
- test.checkAdd ("-b %f{(8,9 ,]}", fh,
- "Unterminated subrange");
- test.checkAdd ("-b %f{(8,9 8]}", fh,
- "Unterminated subrange");
- test.checkAdd ("-b %f{8 9}", fh,
- "Range spec: ',' or '}' expected");
- test.checkAdd ("-b %f{8 *}", fh,
- "Range spec: ',' or '}' expected");
-
- test.checkAdd ("-b %f{8y}", fh,
- "Range spec: ',' or '}' expected");
- test.checkAdd ("-b %f{.}", fh,
- "Malformed float '.}' in range spec");
- test.checkAdd ("-b %f{1.0e}", fh,
- "Malformed float '1.0e}' in range spec");
- test.checkAdd ("-b %f{[*]}", fh,
- "Malformed float '*' in range spec");
- test.checkAdd ("-b %f{1.2e5t}", fh,
- "Range spec: ',' or '}' expected");
-
-
- test.checkAdd ("-b %i{8}", ih, 'i', 1, "-b ",
- new RngCheck[] { new RngCheck(8) },
- "", null);
- test.checkAdd ("-b %i{8, 9,10 }", ih, 'i', 1, "-b ",
- new RngCheck[] { new RngCheck(8),
- new RngCheck(9),
- new RngCheck(10) },
- "", null);
- test.checkAdd ("-b %i{8, [-9,10),[-17,15],(2,-33),(8,9] }",
- ih, 'i', 1, "-b ",
- new RngCheck[] { new RngCheck(8),
- new RngCheck(-9,CLOSED,10,OPEN),
- new RngCheck(-17,CLOSED,15,CLOSED),
- new RngCheck(-33,OPEN,2,OPEN),
- new RngCheck(8,OPEN,9,CLOSED),
- },
- "", null);
- test.checkAdd ("-b %i{8.7}", ih,
- "Range spec: ',' or '}' expected");
- test.checkAdd ("-b %i{6,[*]}", ih,
- "Malformed integer '*' in range spec");
- test.checkAdd ("-b %i{g76}", ih,
- "Malformed integer 'g' in range spec");
-
- test.checkAdd ("-b %s{foobar}", sh, 's', 1, "-b ",
- new RngCheck[] { new RngCheck("foobar") },
- "", null);
- test.checkAdd ("-b %s{foobar, 0x233,\" \"}", sh, 's', 1, "-b ",
- new RngCheck[] { new RngCheck("foobar"),
- new RngCheck("0x233"),
- new RngCheck(" ") },
- "", null);
- test.checkAdd ("-b %s{foobar,(bb,aa], [\"01\",02]}",
- sh, 's', 1, "-b ",
- new RngCheck[]
- { new RngCheck("foobar"),
- new RngCheck("aa",CLOSED,"bb",OPEN),
- new RngCheck("01",CLOSED,"02",CLOSED),
- },
- "", null);
-
- test.checkAdd ("-b %c{'a'}", ch, 'c', 1, "-b ",
- new RngCheck[] { new RngCheck('a') },
- "", null);
- test.checkAdd ("-b %c{'\\n', '\\002', 'B'}", ch, 'c', 1, "-b ",
- new RngCheck[] { new RngCheck('\n'),
- new RngCheck('\002'),
- new RngCheck('B') },
- "", null);
- test.checkAdd ("-b %c{'q',('g','a'], ['\t','\\003']}",
- ch, 'c', 1, "-b ",
- new RngCheck[]
- { new RngCheck('q'),
- new RngCheck('a',CLOSED,'g',OPEN),
- new RngCheck('\003',CLOSED,'\t',CLOSED),
- },
- "", null);
-
- test.checkAdd ("-b %b{true}X2", b3, 'b', 2, "-b ",
- new RngCheck[] { new RngCheck(true) },
- "", null);
- test.checkAdd ("-b %b{ true , false, true }", bh, 'b', 1, "-b ",
- new RngCheck[] { new RngCheck(true),
- new RngCheck(false),
- new RngCheck(true) },
- "", null);
- test.checkAdd ("-b %v{true,[true,false)}", bh,
- "Sub ranges not supported for %b or %v");
- test.checkAdd ("-b %v{true,[]}", bh,
- "Sub ranges not supported for %b or %v");
- test.checkAdd ("-b %b{tru}", bh,
- "Malformed boolean 'tru}' in range spec");
-
- test.checkAdd ("-b %iX2", i3, 'i', 2, "-b ", null, "", null);
- test.checkAdd ("-b %vX3", b3, 'v', 3, "-b ", null, "", null);
- test.checkAdd ("-b %v{ }X3", b3, 'v', 3, "-b ", null, "", null);
-
- test.checkAdd ("-b=%iX2", i3, 'i', 2, "-b", null, "",
-"Multiplier value incompatible with one word option -b=");
- test.checkAdd ("-b %iX0", i3, 'i', 0, "-b ", null, "",
- "Value multiplier number must be > 0");
- test.checkAdd ("-b %iX-6", i3, 'i', 0, "-b ", null, "",
- "Value multiplier number must be > 0");
- test.checkAdd ("-b %iXy", i3, 'i', 0, "-b ", null, "",
- "Malformed value multiplier");
- test.checkAdd ("-b %iX4", i3, 'i', 4, "-b ", null, "",
- "Result holder array must have a length >= 4");
- test.checkAdd ("-b %iX4", ih, 'i', 4, "-b ", null, "",
-"Multiplier requires result holder to be an array of length >= 4");
-
- test.checkAdd ("-b %i #X4", ih, 'i', 1, "-b ", null, "X4", null);
- test.checkAdd ("-b %i #[}X4",ih, 'i', 1, "-b ", null, "[}X4", null);
-
-// test.checkPrintHelp("");
-// test.checkPrintUsage("");
-
- test = new ArgParserTest();
-
- test.checkAdd (
- "-intarg %i{1,2,(9,18],[22,27],[33,38),(45,48)} #test int arg",
- ih, 'i', 1, "-intarg ",
- new RngCheck[]
- { new RngCheck (1),
- new RngCheck (2),
- new RngCheck (9,OPEN,18,CLOSED),
- new RngCheck (22,CLOSED,27,CLOSED),
- new RngCheck (33,CLOSED,38,OPEN),
- new RngCheck (45,OPEN,48,OPEN),
- },
- "test int arg", null);
-
- MTest[] tests;
-
- tests = new MTest[]
- {
- new MTest("-intarg 1", new Long(1) ),
- new MTest("-intarg 3", new MErr ('r', "3") ),
- new MTest("-intarg 9", new MErr ('r', "9") ),
- new MTest("-intarg 11", new Long(11) ),
- new MTest("-intarg 18", new Long(18)),
- new MTest("-intarg 22", new Long(22)),
- new MTest("-intarg 25", new Long(25)),
- new MTest("-intarg 27", new Long(27)),
- new MTest("-intarg 33", new Long(33)),
- new MTest("-intarg 35", new Long(35)),
- new MTest("-intarg 38", new MErr ('r', "38") ),
- new MTest("-intarg 45", new MErr ('r', "45")),
- new MTest("-intarg 46", new Long(46)),
- new MTest("-intarg 48", new MErr ('r', "48")),
- new MTest("-intarg 100", new MErr ('r', "100")),
- new MTest("-intarg 0xbeef", new MErr ('r', "0xbeef")),
- new MTest("-intarg 0x2f", new Long (0x2f)),
- new MTest("-intarg 041", new Long(041) ),
- };
- test.checkMatches (tests, MULTI_WORD);
-
- test.checkAdd (
- "-farg %f{1,2,(9,18],[22,27],[33,38),(45,48)} #test float arg",
- dh, 'f', 1, "-farg ",
- new RngCheck[]
- {
- new RngCheck (1.0),
- new RngCheck (2.0),
- new RngCheck (9.0,OPEN,18.0,CLOSED),
- new RngCheck (22.0,CLOSED,27.0,CLOSED),
- new RngCheck (33.0,CLOSED,38.0,OPEN),
- new RngCheck (45.0,OPEN,48.0,OPEN),
- },
- "test float arg", null);
-
- tests = new MTest[]
- {
- new MTest("-farg 1", new Double(1)),
- new MTest("-farg 3", new MErr('r', "3")),
- new MTest("-farg 9", new MErr('r', "9")),
- new MTest("-farg 9.0001", new Double(9.0001)),
- new MTest("-farg 11", new Double(11)),
- new MTest("-farg 18", new Double(18)),
- new MTest("-farg 22", new Double(22)),
- new MTest("-farg 25", new Double(25)),
- new MTest("-farg 27", new Double(27)),
- new MTest("-farg 33", new Double(33)),
- new MTest("-farg 35", new Double(35)),
- new MTest("-farg 37.9999",new Double(37.9999)),
- new MTest("-farg 38", new MErr('r', "38")),
- new MTest("-farg 45", new MErr('r', "45")),
- new MTest("-farg 45.0001", new Double(45.0001)),
- new MTest("-farg 46",new Double(46)),
- new MTest("-farg 47.9999",new Double(47.9999)),
- new MTest("-farg 48", new MErr('r', "48")),
- new MTest("-farg 100", new MErr('r', "100")),
- new MTest("-farg 0", new MErr('r', "0")),
- };
- test.checkMatches (tests, MULTI_WORD);
-
- test.checkAdd (
- "-sarg %s{1,2,(AA,AZ],[BB,BX],[C3,C8),(d5,d8)} #test string arg",
- s3, 's', 1, "-sarg ",
- new RngCheck[]
- { new RngCheck ("1"),
- new RngCheck ("2"),
- new RngCheck ("AA",OPEN,"AZ",CLOSED),
- new RngCheck ("BB",CLOSED,"BX",CLOSED),
- new RngCheck ("C3",CLOSED,"C8",OPEN),
- new RngCheck ("d5",OPEN,"d8",OPEN),
- },
- "test string arg", null);
-
- tests = new MTest[]
- {
- new MTest ("-sarg 1", "1"),
- new MTest ("-sarg 3", new MErr('r',"3")),
- new MTest ("-sarg AA", new MErr('r',"AA")),
- new MTest ("-sarg AM", "AM"),
- new MTest ("-sarg AZ", "AZ"),
- new MTest ("-sarg BB", "BB"),
- new MTest ("-sarg BL", "BL"),
- new MTest ("-sarg BX", "BX"),
- new MTest ("-sarg C3", "C3"),
- new MTest ("-sarg C6", "C6"),
- new MTest ("-sarg C8", new MErr('r',"C8")),
- new MTest ("-sarg d5", new MErr('r',"d5")),
- new MTest ("-sarg d6", "d6"),
- new MTest ("-sarg d8", new MErr('r',"d8")),
- new MTest ("-sarg zzz", new MErr('r',"zzz")),
- new MTest ("-sarg 0", new MErr('r',"0")),
- };
- test.checkMatches (tests, MULTI_WORD);
-
- test = new ArgParserTest();
-
- test.checkAdd (
- "-carg %c{1,2,(a,z],['A','Z'],['\\001',\\007),(4,8)}",
- c3, 'c', 1, "-carg ",
- new RngCheck[]
- { new RngCheck ('1'),
- new RngCheck ('2'),
- new RngCheck ('a',OPEN,'z',CLOSED),
- new RngCheck ('A',CLOSED,'Z',CLOSED),
- new RngCheck ('\001',CLOSED,'\007',OPEN),
- new RngCheck ('4',OPEN,'8',OPEN),
- },
- "", null);
-
- tests = new MTest[]
- {
- new MTest ("-carg 1", new Character('1')),
- new MTest ("-carg 3", new MErr('r',"3")),
- new MTest ("-carg a", new MErr('r',"a")),
- new MTest ("-carg m", new Character('m')),
- new MTest ("-carg z", new Character('z')),
- new MTest ("-carg A", new Character('A')),
- new MTest ("-carg 'L'", new Character('L')),
- new MTest ("-carg 'Z'", new Character('Z')),
- new MTest ("-carg \\001", new Character('\001')),
- new MTest ("-carg \\005", new Character('\005')),
- new MTest ("-carg '\\007'", new MErr('r',"'\\007'")),
- new MTest ("-carg '4'", new MErr('r',"'4'")),
- new MTest ("-carg 6", new Character('6')),
- new MTest ("-carg 8", new MErr('r',"8")),
- new MTest ("-carg '\\012'", new MErr('r',"'\\012'")),
- new MTest ("-carg 0", new MErr('r',"0")),
- };
- test.checkMatches (tests, MULTI_WORD);
-
- test.checkAdd (
- "-foo=%i{[-50,100]}", ih, 'i', 1, "-foo=",
- new RngCheck[]
- { new RngCheck (-50,CLOSED,100,CLOSED),
- },
- "", null);
-
- tests = new MTest[]
- {
- new MTest ("-foo=-51", new MErr('r',"-51")),
- new MTest ("-foo=-0x32", new Long(-0x32)),
- new MTest ("-foo=-0x33", new MErr('r',"-0x33")),
- new MTest ("-foo=-0777", new MErr('r',"-0777")),
- new MTest ("-foo=-07", new Long(-07)),
- new MTest ("-foo=0", new Long(0)),
- new MTest ("-foo=100", new Long(100)),
- new MTest ("-foo=0x5e", new Long(0x5e)),
- new MTest ("-foo=066", new Long(066)),
- new MTest ("-foo=06677", new MErr('r',"06677")),
- new MTest ("-foo=0xbeef", new MErr('r',"0xbeef")),
- new MTest ("-foo=foo", new MErr('m',"foo")),
- new MTest ("-foo=-51d", new MErr('m',"-51d")),
- };
- test.checkMatches (tests, ONE_WORD);
-
- test.checkAdd ("-foo2=%i", ih, 'i', 1, "-foo2=", null, "", null);
- tests = new MTest[]
- {
- new MTest ("-foo2=-51", new Long(-51)),
- new MTest ("-foo2=-0x33", new Long(-0x33)),
- new MTest ("-foo2=-0777", new Long(-0777)),
- new MTest ("-foo2=06677", new Long(06677)),
- new MTest ("-foo2=0xbeef", new Long(0xbeef)),
- new MTest ("-foo2=foo", new MErr('m',"foo")),
- new MTest ("-foo2=-51d", new MErr('m',"-51d")),
- new MTest ("-foo2=-51", new Long(-51)),
- };
- test.checkMatches (tests, ONE_WORD);
-
- test.checkAdd ("-foo3 %iX3", i3, 'i', 3, "-foo3 ", null, "", null);
- tests = new MTest[]
- {
- new MTest ("-foo3 -51 678 0x45",
- new long[] { -51, 678, 0x45 }),
- new MTest ("-foo3 55 16f 55", new MErr ('m', "16f")),
- new MTest ("-foo3 55 16", new MErr ('v', "3")),
- };
- test.checkMatches (tests, MULTI_WORD);
-
- Vector<String> vec = new Vector<String>(100);
-
- test.checkAdd ("-foov3 %iX3", vec,'i',3,"-foov3 ",null,"",null);
- tests = new MTest[]
- { new MTest ("-foov3 -1 2 4", new long[] {-1, 2, 4}, 0),
- new MTest ("-foov3 10 3 9", new long[] {10, 3, 9}, 1),
- new MTest ("-foov3 123 1 0", new long[] {123, 1, 0}, 2),
- };
- vec.clear();
- test.checkMatches (tests, MULTI_WORD);
- test.checkAdd ("-foov %i", vec,'i',1,"-foov ",null,"",null);
- tests = new MTest[]
- { new MTest ("-foov 11", new Long(11), 0),
- new MTest ("-foov 12", new Long(12), 1),
- new MTest ("-foov 13", new Long(13), 2),
- };
- vec.clear();
- test.checkMatches (tests, MULTI_WORD);
-
- test.checkAdd (
- "-foo4 %i{[-50,100]}X2", i3, 'i', 2, "-foo4 ",
- new RngCheck[]
- { new RngCheck (-50,CLOSED,100,CLOSED),
- },
- "", null);
- tests = new MTest[]
- {
- new MTest ("-foo4 -49 78",
- new long[] { -49, 78 }),
- new MTest ("-foo4 -48 102", new MErr ('r', "102")),
- };
- test.checkMatches (tests, MULTI_WORD);
-
- test.checkAdd (
- "-oct=%o{[-062,0144]}", ih, 'o', 1, "-oct=",
- new RngCheck[]
- { new RngCheck (-50,CLOSED,100,CLOSED),
- },
- "", null);
-
- tests = new MTest[]
- {
- new MTest ("-oct=-063", new MErr('r',"-063")),
- new MTest ("-oct=-0x32", new MErr('m',"-0x32")),
- new MTest ("-oct=-0777", new MErr('r',"-0777")),
- new MTest ("-oct=-07", new Long(-07)),
- new MTest ("-oct=0", new Long(0)),
- new MTest ("-oct=100", new Long(64)),
- new MTest ("-oct=0xae", new MErr('m',"0xae")),
- new MTest ("-oct=66", new Long(066)),
- new MTest ("-oct=06677", new MErr('r',"06677")),
- new MTest ("-oct=0xbeef", new MErr('m',"0xbeef")),
- new MTest ("-oct=foo", new MErr('m',"foo")),
- new MTest ("-oct=-51d", new MErr('m',"-51d")),
- new MTest ("-oct=78", new MErr('m',"78")),
- };
- test.checkMatches (tests, ONE_WORD);
-
- test.checkAdd ("-oct2=%o", ih, 'o', 1, "-oct2=", null, "", null);
- tests = new MTest[]
- {
- new MTest ("-oct2=-063", new Long(-063)),
- new MTest ("-oct2=-0777", new Long(-0777)),
- new MTest ("-oct2=06677", new Long(06677)),
- };
- test.checkMatches (tests, ONE_WORD);
-
- test.checkAdd (
- "-dec=%d{[-0x32,0x64]}", ih, 'd', 1, "-dec=",
- new RngCheck[]
- { new RngCheck (-50,CLOSED,100,CLOSED),
- },
- "", null);
-
- tests = new MTest[]
- {
- new MTest ("-dec=-063", new MErr('r',"-063")),
- new MTest ("-dec=-0x32", new MErr('m',"-0x32")),
- new MTest ("-dec=-0777", new MErr('r',"-0777")),
- new MTest ("-dec=-07", new Long(-07)),
- new MTest ("-dec=0", new Long(0)),
- new MTest ("-dec=100", new Long(100)),
- new MTest ("-dec=0xae", new MErr('m',"0xae")),
- new MTest ("-dec=66", new Long(66)),
- new MTest ("-dec=06677", new MErr('r',"06677")),
- new MTest ("-dec=0xbeef", new MErr('m',"0xbeef")),
- new MTest ("-dec=foo", new MErr('m',"foo")),
- new MTest ("-dec=-51d", new MErr('m',"-51d")),
- };
- test.checkMatches (tests, ONE_WORD);
-
- test.checkAdd ("-dec2=%d", ih, 'd', 1, "-dec2=", null, "", null);
- tests = new MTest[]
- {
- new MTest ("-dec2=-063", new Long(-63)),
- new MTest ("-dec2=-0777", new Long(-777)),
- new MTest ("-dec2=06677", new Long(6677)),
- };
- test.checkMatches (tests, ONE_WORD);
-
- test.checkAdd (
- "-hex=%x{[-0x32,0x64]}", ih, 'x', 1, "-hex=",
- new RngCheck[]
- { new RngCheck (-50,CLOSED,100,CLOSED),
- },
- "", null);
-
- tests = new MTest[]
- {
- new MTest ("-hex=-06", new Long(-0x6)),
- new MTest ("-hex=-0x3g2", new MErr('m',"-0x3g2")),
- new MTest ("-hex=-0777", new MErr('r',"-0777")),
- new MTest ("-hex=-017", new Long(-0x17)),
- new MTest ("-hex=0", new Long(0)),
- new MTest ("-hex=64", new Long(0x64)),
- new MTest ("-hex=5e", new Long(0x5e)),
- new MTest ("-hex=66", new MErr('r',"66")),
- new MTest ("-hex=06677", new MErr('r',"06677")),
- new MTest ("-hex=0xbeef", new MErr('m',"0xbeef")),
- new MTest ("-hex=foo", new MErr('m',"foo")),
- new MTest ("-hex=-51d", new MErr('r',"-51d")),
- new MTest ("-hex=-51g", new MErr('m',"-51g")),
- new MTest ("-hex=", new MErr('c',"")),
- };
- test.checkMatches (tests, ONE_WORD);
-
- test.checkAdd ("-hex2=%x", ih, 'x', 1, "-hex2=", null, "", null);
- tests = new MTest[]
- {
- new MTest ("-hex2=-0777", new Long(-0x777)),
- new MTest ("-hex2=66", new Long(0x66)),
- new MTest ("-hex2=06677", new Long(0x6677)),
- new MTest ("-hex2=-51d", new Long(-0x51d)),
- };
- test.checkMatches (tests, ONE_WORD);
-
- test.checkAdd (
- "-char=%c{['b','m']}", ch, 'c', 1, "-char=",
- new RngCheck[]
- { new RngCheck ('b',CLOSED,'m',CLOSED),
- },
- "", null);
-
- tests = new MTest[]
- {
- new MTest ("-char=a", new MErr('r',"a")),
- new MTest ("-char=b", new Character('b')),
- new MTest ("-char='b'", new Character('b')),
- new MTest ("-char='\142'", new Character('b')),
- new MTest ("-char='\141'", new MErr('r',"'\141'")),
- new MTest ("-char=\142", new Character('b')),
- new MTest ("-char=\141", new MErr('r',"\141")),
- new MTest ("-char=m", new Character('m')),
- new MTest ("-char=z", new MErr('r', "z")),
- new MTest ("-char=bb", new MErr('m', "bb")),
- new MTest ("-char='b", new MErr('m', "'b")),
- new MTest ("-char='", new MErr('m', "'")),
- new MTest ("-char=a'", new MErr('m', "a'")),
- };
- test.checkMatches (tests, ONE_WORD);
-
- test.checkAdd ("-char2=%c", ch, 'c', 1, "-char2=",null,"",null);
- tests = new MTest[]
- {
- new MTest ("-char2=a", new Character('a')),
- new MTest ("-char2='\141'", new Character('\141')),
- new MTest ("-char2=\141", new Character('\141')),
- new MTest ("-char2=z", new Character('z')),
- };
- test.checkMatches (tests, ONE_WORD);
-
- test.checkAdd ("-charv3 %cX3", vec,'c',3,"-charv3 ",null,"",null);
- tests = new MTest[]
- { new MTest ("-charv3 a b c", new char[] {'a', 'b', 'c'}, 0),
- new MTest ("-charv3 'g' f '\\n'", new char[]{'g','f','\n'}, 1),
- new MTest ("-charv3 1 \001 3", new char[] {'1', '\001', '3'}, 2),
- };
- vec.clear();
- test.checkMatches (tests, MULTI_WORD);
- test.checkAdd ("-charv=%c", vec,'c',1,"-charv=",null,"",null);
- tests = new MTest[]
- { new MTest ("-charv=d", new Character('d'), 0),
- new MTest ("-charv='g'", new Character('g'), 1),
- new MTest ("-charv=\111", new Character('\111'), 2),
- };
- vec.clear();
- test.checkMatches (tests, ONE_WORD);
-
- test.checkAdd (
- "-bool=%b{true}", bh, 'b', 1, "-bool=",
- new RngCheck[]
- { new RngCheck (true),
- },
- "", null);
-
- tests = new MTest[]
- {
- new MTest ("-bool=true", new Boolean(true)),
- new MTest ("-bool=false", new MErr('r', "false")),
- new MTest ("-bool=fals", new MErr('m', "fals")),
- new MTest ("-bool=falsem", new MErr('m', "falsem")),
- new MTest ("-bool=truex", new MErr('m', "truex")),
- new MTest ("-bool=foo", new MErr('m', "foo")),
- new MTest ("-bool=1", new MErr('m', "1")),
- };
- test.checkMatches (tests, ONE_WORD);
-
- test.checkAdd (
- "-boo2=%b{true,false}", bh, 'b', 1, "-boo2=",
- new RngCheck[]
- { new RngCheck (true),
- new RngCheck (false),
- },
- "", null);
-
- tests = new MTest[]
- {
- new MTest ("-boo2=true", new Boolean(true)),
- new MTest ("-boo2=false", new Boolean(false)),
- };
- test.checkMatches (tests, ONE_WORD);
-
- test.checkAdd ("-boo3=%b", bh, 'b', 1, "-boo3=", null, "", null);
- tests = new MTest[]
- {
- new MTest ("-boo3=true", new Boolean(true)),
- new MTest ("-boo3=false", new Boolean(false)),
- };
- test.checkMatches (tests, ONE_WORD);
-
- test.checkAdd ("-boo3 %bX3", b3, 'b', 3, "-boo3 ", null, "", null);
- tests = new MTest[]
- {
- new MTest ("-boo3 true false true",
- new boolean[] { true, false, true }),
- new MTest ("-boo3 true fals true", new MErr ('m', "fals")),
- };
- test.checkMatches (tests, MULTI_WORD);
-
- test.checkAdd ("-boov3 %bX3", vec,'b',3,"-boov3 ",null,"",null);
- tests = new MTest[]
- { new MTest ("-boov3 true true false",
- new boolean [] { true, true, false }, 0),
- new MTest ("-boov3 false false true",
- new boolean [] { false, false, true }, 1),
- };
- vec.clear();
- test.checkMatches (tests, MULTI_WORD);
- test.checkAdd ("-boov %b", vec,'b',1,"-boov ",null,"",null);
- tests = new MTest[]
- { new MTest ("-boov true", new Boolean (true), 0),
- new MTest ("-boov false", new Boolean (false), 1),
- new MTest ("-boov true", new Boolean (true), 2),
- };
- vec.clear();
- test.checkMatches (tests, MULTI_WORD);
-
-
- test.checkAdd ("-v3 %vX2", b3, 'v', 2, "-v3 ", null, "", null);
- tests = new MTest[]
- { new MTest ("-v3", new boolean[] { true, true }),
- };
- test.checkMatches (tests, MULTI_WORD);
-
- test.checkAdd (
- "-vf %v{false,true}X2", b3, 'v', 2, "-vf ",
- new RngCheck[]
- { new RngCheck(false),
- new RngCheck(true),
- },
- "", null);
- tests = new MTest[]
- { new MTest ("-vf", new boolean[] { false, false }),
- };
- test.checkMatches (tests, MULTI_WORD);
-
- test.checkAdd (
- "-str=%s{(john,zzzz]}", sh, 's', 1, "-str=",
- new RngCheck[]
- { new RngCheck ("john", OPEN, "zzzz", CLOSED),
- },
- "", null);
-
- tests = new MTest[]
- {
- new MTest ("-str=john", new MErr ('r', "john")),
- new MTest ("-str=joho ", "joho "),
- new MTest ("-str=joho ", "joho "),
- new MTest ("-str=zzzz", "zzzz"),
- new MTest ("-str= joho", new MErr ('r', " joho")),
- new MTest ("-str=jnhn ", new MErr ('r', "jnhn ")),
- new MTest ("-str=zzzzz", new MErr ('r', "zzzzz")),
- new MTest ("-str=\"joho\"", new MErr ('r', "\"joho\"")),
- new MTest ("-str=\"joho", new MErr('r', "\"joho")),
- new MTest ("-str=joho j", "joho j"), // new MErr('m', "joho j")),
- };
- test.checkMatches (tests, ONE_WORD);
-
- test.checkAdd ("-str2=%s", sh,'s',1,"-str2=",null,"",null);
- tests = new MTest[]
- {
- new MTest ("-str2= jnhn", " jnhn"),
- new MTest ("-str2=zzzzz", "zzzzz"),
- };
- test.checkMatches (tests, ONE_WORD);
-
- test.checkAdd ("-str3 %sX3",s3,'s',3,"-str3 ",null,"",null);
- tests = new MTest[]
- {
- new MTest ("-str3 foo bar johnny",
- new String[] { "foo", "bar", "johnny" }),
- new MTest ("-str3 zzzzz \"bad foo",
- new String[] { "zzzzz", "\"bad", "foo"
- }), // new MErr('m', "\"bad")),
- };
- test.checkMatches (tests, MULTI_WORD);
-
- test.checkAdd ("-strv3 %sX3", vec,'s',3,"-strv3 ",null,"",null);
- tests = new MTest[]
- { new MTest ("-strv3 foo bar \"hihi\"",
- new String[] {"foo", "bar", "\"hihi\""}, 0),
- new MTest ("-strv3 a 123 gg",
- new String[]{"a", "123", "gg"}, 1),
- };
- vec.clear();
- test.checkMatches (tests, MULTI_WORD);
- test.checkAdd ("-strv=%s", vec,'s',1,"-strv=",null,"",null);
- tests = new MTest[]
- { new MTest ("-strv=d", "d", 0),
- new MTest ("-strv='g'", "'g'", 1),
- new MTest ("-strv=\\111", "\\111", 2),
- };
- vec.clear();
- test.checkMatches (tests, ONE_WORD);
-
- test.checkAdd (
- "-float=%f{(-0.001,1000.0]}", dh, 'f', 1, "-float=",
- new RngCheck[]
- { new RngCheck (-0.001, OPEN, 1000.0, CLOSED),
- },
- "", null);
-
- tests = new MTest[]
- {
- new MTest ("-float=-0.000999", new Double(-0.000999)),
- new MTest ("-float=1e-3", new Double(0.001)),
- new MTest ("-float=12.33e1", new Double(123.3)),
- new MTest ("-float=1e3", new Double(1e3)),
- new MTest ("-float=1000.000", new Double(1000.0)),
- new MTest ("-float=-0.001", new MErr('r', "-0.001")),
- new MTest ("-float=-1e-3", new MErr('r', "-1e-3")),
- new MTest ("-float=1000.001", new MErr('r', "1000.001")),
- new MTest ("-float=.", new MErr('m', ".")),
- new MTest ("-float= 124.5 ", new Double (124.5)),
- new MTest ("-float=124.5x", new MErr('m', "124.5x")),
- new MTest ("-float= foo ", new MErr('m', " foo ")),
- new MTest ("-float=1e1", new Double(10)),
- new MTest ("-float=1e ", new MErr('m', "1e ")),
- };
- test.checkMatches (tests, ONE_WORD);
-
- test.checkAdd ("-float2=%f", dh,'f',1,"-float2=",null,"",null);
- tests = new MTest[]
- {
- new MTest ("-float2=-0.001", new Double(-0.001)),
- new MTest ("-float2=-1e-3", new Double(-1e-3)),
- new MTest ("-float2=1000.001", new Double(1000.001)),
- };
- test.checkMatches (tests, ONE_WORD);
-
- test.checkAdd ("-f3 %fX3", d3,'f',3,"-f3 ",null,"",null);
- tests = new MTest[]
- {
- new MTest ("-f3 -0.001 1.23e5 -9.88e-4",
- new double[] { -0.001, 1.23e5, -9.88e-4 }),
- new MTest ("-f3 7.88 foo 9.0", new MErr ('m', "foo")),
- new MTest ("-f3 7.88 . 9.0", new MErr ('m', ".")),
- new MTest ("-f3 7.88 3.0 9.0x", new MErr ('m', "9.0x")),
- };
- test.checkMatches (tests, MULTI_WORD);
-
- test.checkAdd ("-fv3 %fX3", vec,'f',3,"-fv3 ",null,"",null);
- tests = new MTest[]
- { new MTest ("-fv3 1.0 3.444 6.7",
- new double[] {1.0, 3.444, 6.7}, 0),
- new MTest ("-fv3 13e-5 145.678 0.0001e45",
- new double[]{13e-5, 145.678, 0.0001e45}, 1),
- new MTest ("-fv3 11.11 3.1245 -1e-4",
- new double[] {11.11, 3.1245, -1e-4}, 2),
- new MTest ("-fv3 1.0 2 3",
- new double[] { 1.0, 2.0, 3.0 }, 3),
- };
- vec.clear();
- test.checkMatches (tests, MULTI_WORD);
- test.checkAdd ("-fv %f", vec,'f',1,"-fv ",null,"",null);
- tests = new MTest[]
- { new MTest ("-fv -15.1234", new Double(-15.1234), 0),
- new MTest ("-fv -1.234e-7", new Double(-1.234e-7), 1),
- new MTest ("-fv 0.001111", new Double(0.001111), 2),
- };
- vec.clear();
- test.checkMatches (tests, MULTI_WORD);
-
-
- IntHolder intHolder = new IntHolder();
- StringHolder strHolder = new StringHolder();
-
- ArgParser parser = new ArgParser ("test");
- parser.addOption ("-foo %d #an int", intHolder);
- parser.addOption ("-bar %s #a string", strHolder);
- args = new String[]
- { "zzz", "-cat", "-foo", "123", "yyy", "-bar", "xxxx", "xxx"
- };
-
- String[] unmatchedCheck = new String[]
- { "zzz", "-cat", "yyy", "xxx"
- };
-
- String[] unmatched = parser.matchAllArgs (args, 0, 0);
- test.checkStringArray (
- "Unmatched args:", unmatched, unmatchedCheck);
-
- vec.clear();
- for (int i=0; i<args.length; )
- { try
- { i = parser.matchArg (args, i);
- if (parser.getUnmatchedArgument() != null)
- { vec.add (parser.getUnmatchedArgument());
- }
- }
- catch (Exception e)
- {
- }
- }
- unmatched = (String[])vec.toArray(new String[0]);
- test.checkStringArray (
- "My unmatched args:", unmatched, unmatchedCheck);
-
- System.out.println ("\nPassed\n");
-
- }
+public class ArgParserTest {
+ ArgParser parser;
+
+ static final boolean CLOSED = true;
+ static final boolean OPEN = false;
+
+ static final boolean ONE_WORD = true;
+ static final boolean MULTI_WORD = false;
+
+ private static void verify(boolean ok, String msg) {
+ if (!ok) {
+ Throwable e = new Throwable();
+ System.out.println("Verification failed:" + msg);
+ e.printStackTrace();
+ System.exit(1);
+ }
+ }
+
+ private static String[] argsFromString(String s) {
+ Vector<String> vec = new Vector<String>(100);
+ try {
+ ArgParser.stringToArgs(vec, s, /* allowQuotedStings= */false);
+ } catch (StringScanException e) {
+ e.printStackTrace();
+ System.exit(1);
+ }
+ String[] result = new String[vec.size()];
+ for (int i = 0; i < vec.size(); i++) {
+ result[i] = (String) vec.get(i);
+ }
+ return result;
+ }
+
+ static class RngCheck {
+ ArgParser.RangePnt low = null;
+ ArgParser.RangePnt high = null;
+ int type;
+
+ RngCheck(String s) {
+ low = new ArgParser.RangePnt(s, CLOSED);
+ type = 's';
+ }
+
+ RngCheck(double d) {
+ low = new ArgParser.RangePnt(d, CLOSED);
+ type = 'd';
+ }
+
+ RngCheck(long l) {
+ low = new ArgParser.RangePnt(l, CLOSED);
+ type = 'l';
+ }
+
+ RngCheck(boolean b) {
+ low = new ArgParser.RangePnt(b, CLOSED);
+ type = 'b';
+ }
+
+ RngCheck(String s1, boolean c1, String s2, boolean c2) {
+ low = new ArgParser.RangePnt(s1, c1);
+ high = new ArgParser.RangePnt(s2, c2);
+ type = 's';
+ }
+
+ RngCheck(double d1, boolean c1, double d2, boolean c2) {
+ low = new ArgParser.RangePnt(d1, c1);
+ high = new ArgParser.RangePnt(d2, c2);
+ type = 'd';
+ }
+
+ RngCheck(long l1, boolean c1, long l2, boolean c2) {
+ low = new ArgParser.RangePnt(l1, c1);
+ high = new ArgParser.RangePnt(l2, c2);
+ type = 'l';
+ }
+
+ void check(ArgParser.RangeAtom ra) {
+ verify((ra.low == null) == (low == null),
+ "(ra.low==null)=" + (ra.low == null) +
+ "(low==null)=" + (low == null));
+ verify((ra.high == null) == (high == null),
+ "(ra.high==null)=" + (ra.high == null) +
+ "(high==null)=" + (high == null));
+
+ if (ra.low != null) {
+ switch (type) {
+ case 'l': {
+ verify(ra.low.lval == low.lval,
+ "ra.low=" + ra.low + " low=" + low);
+ break;
+ }
+ case 'd': {
+ verify(ra.low.dval == low.dval,
+ "ra.low=" + ra.low + " low=" + low);
+ break;
+ }
+ case 's': {
+ verify(ra.low.sval.equals(low.sval),
+ "ra.low=" + ra.low + " low=" + low);
+ break;
+ }
+ case 'b': {
+ verify(ra.low.bval == low.bval,
+ "ra.low=" + ra.low + " low=" + low);
+ break;
+ }
+ }
+ verify(ra.low.closed == low.closed,
+ "ra.low=" + ra.low + " low=" + low);
+ }
+ if (ra.high != null) {
+ switch (type) {
+ case 'l': {
+ verify(ra.high.lval == high.lval,
+ "ra.high=" + ra.high + " high=" + high);
+ break;
+ }
+ case 'd': {
+ verify(ra.high.dval == high.dval,
+ "ra.high=" + ra.high + " high=" + high);
+ break;
+ }
+ case 's': {
+ verify(ra.high.sval.equals(high.sval),
+ "ra.high=" + ra.high + " high=" + high);
+ break;
+ }
+ case 'b': {
+ verify(ra.high.bval == high.bval,
+ "ra.high=" + ra.high + " high=" + high);
+ break;
+ }
+ }
+ verify(ra.high.closed == high.closed,
+ "ra.high=" + ra.high + " high=" + high);
+ }
+ }
+ }
+
+ ArgParserTest() {
+ parser = new ArgParser("fubar");
+ }
+
+ static void checkException(Exception e, String errmsg) {
+ if (errmsg != null) {
+ if (!e.getMessage().equals(errmsg)) {
+ System.out.println(
+ "Expecting exception '" + errmsg + "' but got '" +
+ e.getMessage() + "'");
+ e.printStackTrace();
+ (new Throwable()).printStackTrace();
+ System.exit(1);
+ }
+ } else {
+ System.out.println(
+ "Unexpected exception '" + e.getMessage() + "'");
+ e.printStackTrace();
+ (new Throwable()).printStackTrace();
+ System.exit(1);
+ }
+ }
+
+ void checkPrintHelp(String msg) {
+ ByteArrayOutputStream buf = new ByteArrayOutputStream(0x10000);
+ PrintStream ps = new PrintStream(buf);
+ ps.println(parser.getHelpMessage());
+ System.out.print(buf.toString());
+ }
+
+ // void checkGetSynopsis (String msg)
+ // {
+ // ByteArrayOutputStream buf = new ByteArrayOutputStream(0x10000);
+ // PrintStream ps = new PrintStream(buf);
+ // parser.printSynopsis (ps, 80);
+ // System.out.print (buf.toString());
+ // }
+
+ void checkAdd(String s, Object resHolder, String errmsg) {
+ checkAdd(s, resHolder, 0, 0, null, null, null, errmsg);
+ }
+
+ void add(String s, Object resHolder) {
+ try {
+ parser.addOption(s, resHolder);
+ } catch (Exception e) {
+ e.printStackTrace();
+ System.exit(1);
+ }
+ }
+
+ void checkStringArray(String msg, String[] strs, String[] check) {
+ boolean dontMatch = false;
+ if (strs.length != check.length) {
+ dontMatch = true;
+ } else {
+ for (int i = 0; i < strs.length; i++) {
+ if (!strs[i].equals(check[i])) {
+ dontMatch = true;
+ break;
+ }
+ }
+ }
+ if (dontMatch) {
+ System.out.println(msg);
+ System.out.print("Expected: ");
+ for (int i = 0; i < check.length; i++) {
+ System.out.print("'" + check[i] + "'");
+ if (i < check.length - 1) {
+ System.out.print(" ");
+ }
+ }
+ System.out.println("");
+ System.out.print("Got: ");
+ for (int i = 0; i < strs.length; i++) {
+ System.out.print("'" + strs[i] + "'");
+ if (i < strs.length - 1) {
+ System.out.print(" ");
+ }
+ }
+ System.out.println("");
+ System.exit(1);
+ }
+ }
+
+ void checkAdd(String s, Object resHolder, int code, int numValues,
+ Object names, RngCheck[] rngCheck,
+ String helpMsg, String errmsg) {
+ boolean exceptionThrown = false;
+ String[] namelist = null;
+ try {
+ parser.addOption(s, resHolder);
+ } catch (Exception e) {
+ exceptionThrown = true;
+ checkException(e, errmsg);
+ }
+ if (names instanceof String) {
+ namelist = new String[] { (String) names };
+ } else {
+ namelist = (String[]) names;
+ }
+ if (!exceptionThrown) {
+ verify(errmsg == null,
+ "Expecting exception " + errmsg);
+ ArgParser.Record rec = parser.lastMatchRecord();
+ verify(rec.convertCode == code,
+ "code=" + rec.convertCode + ", expecting " + code);
+ ArgParser.NameDesc nd;
+ int i = 0;
+ for (nd = rec.firstNameDesc(); nd != null; nd = nd.next) {
+ i++;
+ }
+ verify(i == namelist.length,
+ "numNames=" + i + ", expecting " + namelist.length);
+ i = 0;
+ for (nd = rec.firstNameDesc(); nd != null; nd = nd.next) {
+ String ss;
+ if (!nd.oneWord) {
+ ss = new String(nd.name) + ' ';
+ } else {
+ ss = nd.name;
+ }
+ verify(ss.equals(namelist[i]),
+ "have name '" + ss + "', expecting '" + namelist[i] + "'");
+ i++;
+ }
+ ArgParser.RangeAtom ra;
+ i = 0;
+ for (ra = rec.firstRangeAtom(); ra != null; ra = ra.next) {
+ i++;
+ }
+ int expectedRangeNum = 0;
+ if (rngCheck != null) {
+ expectedRangeNum = rngCheck.length;
+ }
+ verify(i == expectedRangeNum,
+ "numRangeAtoms=" + i + ", expecting " + expectedRangeNum);
+ i = 0;
+ for (ra = rec.firstRangeAtom(); ra != null; ra = ra.next) {
+ rngCheck[i++].check(ra);
+ }
+ verify(rec.helpMsg.equals(helpMsg),
+ "helpMsg=" + rec.helpMsg + ", expecting " + helpMsg);
+ verify(rec.numValues == numValues,
+ "numValues=" + rec.numValues + ", expecting " + numValues);
+ }
+ }
+
+ double getDoubleValue(Object obj, int k) {
+ if (obj instanceof DoubleHolder) {
+ return ((DoubleHolder) obj).value;
+ } else if (obj instanceof FloatHolder) {
+ return ((FloatHolder) obj).value;
+ } else if (obj instanceof double[]) {
+ return ((double[]) obj)[k];
+ } else if (obj instanceof float[]) {
+ return ((float[]) obj)[k];
+ } else {
+ verify(false, "object doesn't contain double values");
+ return 0;
+ }
+ }
+
+ long getLongValue(Object obj, int k) {
+ if (obj instanceof LongHolder) {
+ return ((LongHolder) obj).value;
+ } else if (obj instanceof IntHolder) {
+ return ((IntHolder) obj).value;
+ } else if (obj instanceof long[]) {
+ return ((long[]) obj)[k];
+ } else if (obj instanceof int[]) {
+ return ((int[]) obj)[k];
+ } else {
+ verify(false, "object doesn't contain long values");
+ return 0;
+ }
+ }
+
+ String getStringValue(Object obj, int k) {
+ if (obj instanceof StringHolder) {
+ return ((StringHolder) obj).value;
+ } else if (obj instanceof String[]) {
+ return ((String[]) obj)[k];
+ } else {
+ verify(false, "object doesn't contain String values");
+ return null;
+ }
+ }
+
+ boolean getBooleanValue(Object obj, int k) {
+ if (obj instanceof BooleanHolder) {
+ return ((BooleanHolder) obj).value;
+ } else if (obj instanceof boolean[]) {
+ return ((boolean[]) obj)[k];
+ } else {
+ verify(false, "object doesn't contain boolean values");
+ return false;
+ }
+ }
+
+ char getCharValue(Object obj, int k) {
+ if (obj instanceof CharHolder) {
+ return ((CharHolder) obj).value;
+ } else if (obj instanceof char[]) {
+ return ((char[]) obj)[k];
+ } else {
+ verify(false, "object doesn't contain char values");
+ return 0;
+ }
+ }
+
+ static class MErr {
+ int code;
+ String valStr;
+
+ MErr(int code, String valStr) {
+ this.code = code;
+ this.valStr = valStr;
+ }
+ }
+
+ static class MTest {
+ String args;
+ Object result;
+ int resultIdx;
+
+ MTest(String args, Object result) {
+ this(args, result, -1);
+ }
+
+ MTest(String args, Object result, int resultIdx) {
+ this.args = args;
+ this.result = result;
+ this.resultIdx = resultIdx;
+ }
+ };
+
+ void checkMatch(String args[], int idx, String errMsg) {
+ getMatchResult(args, idx, -1, errMsg, -1);
+ }
+
+ void checkMatch(String args[], int idx, int cnt,
+ long check, int resultIdx) {
+ Object rholder = getMatchResult(args, idx, cnt, null, resultIdx);
+ long result = getLongValue(rholder, 0);
+ verify(result == check, "result " + result + " vs. " + check);
+ }
+
+ void checkMatch(String args[], int idx, int cnt,
+ double check, int resultIdx) {
+ Object rholder = getMatchResult(args, idx, cnt, null, resultIdx);
+ double result = getDoubleValue(rholder, 0);
+ verify(result == check, "result " + result + " vs. " + check);
+ }
+
+ void checkMatch(String args[], int idx, int cnt,
+ String check, int resultIdx) {
+ Object rholder = getMatchResult(args, idx, cnt, null, resultIdx);
+ String result = getStringValue(rholder, 0);
+ verify(result.equals(check), "result " + result + " vs. " + check);
+ }
+
+ void checkMatch(String args[], int idx, int cnt,
+ boolean check, int resultIdx) {
+ Object rholder = getMatchResult(args, idx, cnt, null, resultIdx);
+ boolean result = getBooleanValue(rholder, 0);
+ verify(result == check, "result " + result + " vs. " + check);
+ }
+
+ void checkMatch(String args[], int idx, int cnt,
+ char check, int resultIdx) {
+ Object rholder = getMatchResult(args, idx, cnt, null, resultIdx);
+ char result = getCharValue(rholder, 0);
+ verify(result == check, "result " + result + " vs. " + check);
+ }
+
+ void checkMatch(String args[], int idx, int cnt,
+ Object checkArray, int resultIdx) {
+ Object rholder = getMatchResult(args, idx, cnt, null, resultIdx);
+ if (!checkArray.getClass().isArray()) {
+ verify(false, "check is not an array");
+ }
+ for (int i = 0; i < Array.getLength(checkArray); i++) {
+ if (checkArray instanceof long[]) {
+ long result = getLongValue(rholder, i);
+ long check = ((long[]) checkArray)[i];
+ verify(result == check,
+ "result [" + i + "] " + result + " vs. " + check);
+ } else if (checkArray instanceof double[]) {
+ double result = getDoubleValue(rholder, i);
+ double check = ((double[]) checkArray)[i];
+ verify(result == check,
+ "result [" + i + "] " + result + " vs. " + check);
+ } else if (checkArray instanceof String[]) {
+ String result = getStringValue(rholder, i);
+ String check = ((String[]) checkArray)[i];
+ verify(result.equals(check),
+ "result [" + i + "] " + result + " vs. " + check);
+ } else if (checkArray instanceof boolean[]) {
+ boolean result = getBooleanValue(rholder, i);
+ boolean check = ((boolean[]) checkArray)[i];
+ verify(result == check,
+ "result [" + i + "] " + result + " vs. " + check);
+ } else if (checkArray instanceof char[]) {
+ char result = getCharValue(rholder, i);
+ char check = ((char[]) checkArray)[i];
+ verify(result == check,
+ "result [" + i + "] " + result + " vs. " + check);
+ } else {
+ verify(false, "unknown type for checkArray");
+ }
+ }
+ }
+
+ void checkMatch(MTest test, boolean oneWord) {
+ String[] argv;
+ if (oneWord) {
+ argv = new String[1];
+ argv[0] = test.args;
+ } else {
+ argv = argsFromString(test.args);
+ }
+ if (test.result instanceof Long) {
+ checkMatch(argv, 0, argv.length,
+ ((Long) test.result).longValue(),
+ test.resultIdx);
+ } else if (test.result instanceof Double) {
+ checkMatch(argv, 0, argv.length,
+ ((Double) test.result).doubleValue(),
+ test.resultIdx);
+ } else if (test.result instanceof String) {
+ checkMatch(argv, 0, argv.length,
+ (String) test.result,
+ test.resultIdx);
+ } else if (test.result instanceof Boolean) {
+ checkMatch(argv, 0, argv.length,
+ ((Boolean) test.result).booleanValue(),
+ test.resultIdx);
+ } else if (test.result instanceof Character) {
+ checkMatch(argv, 0, argv.length,
+ ((Character) test.result).charValue(),
+ test.resultIdx);
+ } else if (test.result.getClass().isArray()) {
+ checkMatch(argv, 0, argv.length, test.result,
+ test.resultIdx);
+ } else if (test.result instanceof MErr) {
+ MErr err = (MErr) test.result;
+ String argname = parser.getOptionName(argv[0]);
+ String msg = "";
+
+ switch (err.code) {
+ case 'c': {
+ msg = "requires a contiguous value";
+ break;
+ }
+ case 'm': {
+ msg = "malformed " + parser.getOptionTypeName(argv[0]) +
+ " '" + err.valStr + "'";
+ break;
+ }
+ case 'r': {
+ msg = "value '" + err.valStr + "' not in range " +
+ parser.getOptionRangeDesc(argv[0]);
+ break;
+ }
+ case 'v': {
+ msg = "requires " + err.valStr + " values";
+ break;
+ }
+ }
+ checkMatch(argv, 0, argname + ": " + msg);
+ } else {
+ verify(false, "Unknown result type");
+ }
+ }
+
+ void checkMatches(MTest[] tests, boolean oneWord) {
+ for (int i = 0; i < tests.length; i++) {
+ checkMatch(tests[i], oneWord);
+ }
+ }
+
+ Object getMatchResult(String args[], int idx, int cnt,
+ String errMsg, int resultIdx) {
+ boolean exceptionThrown = false;
+ int k = 0;
+ try {
+ k = parser.matchArg(args, idx);
+ } catch (Exception e) {
+ exceptionThrown = true;
+ checkException(e, errMsg);
+ }
+ if (!exceptionThrown) {
+ verify(k == idx + cnt,
+ "Expecting result index " + (idx + cnt) + ", got " + k);
+ Object result = parser.getResultHolder(args[0]);
+ if (resultIdx >= 0) {
+ verify(result instanceof Vector,
+ "Expecting result to be stored in a vector");
+ Vector<?> vec = (Vector<?>) result;
+ verify(vec.size() == resultIdx + 1,
+ "Expecting result vector size " + (resultIdx + 1));
+ return vec.get(resultIdx);
+ } else {
+ return result;
+ }
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Runs a set of tests to verify correct operation of the ArgParser class.
+ * If all the tests run correctly, the program prints the message
+ * <code>Passed</code> and terminates. Otherwise, diagnostic information is
+ * printed at the first point of failure.
+ */
+ public static void main(String[] args) {
+ ArgParserTest test = new ArgParserTest();
+
+ BooleanHolder bh = new BooleanHolder();
+ boolean[] b3 = new boolean[3];
+ CharHolder ch = new CharHolder();
+ char[] c3 = new char[3];
+ IntHolder ih = new IntHolder();
+ int[] i3 = new int[3];
+ LongHolder lh = new LongHolder();
+ long[] l3 = new long[3];
+ FloatHolder fh = new FloatHolder();
+ float[] f3 = new float[3];
+ DoubleHolder dh = new DoubleHolder();
+ double[] d3 = new double[3];
+ StringHolder sh = new StringHolder();
+ String[] s3 = new String[3];
+
+ test.checkAdd("-foo %i{[0,10)}X3 #sets the value of foo",
+ // 0123456789012345
+ i3, 'i', 3, new String[] { "-foo " },
+ new RngCheck[] {
+ new RngCheck(0, CLOSED, 10, OPEN) },
+ "sets the value of foo", null);
+
+ test.checkAdd("-arg1,,", null, "Null option name given");
+ test.checkAdd("-arg1,,goo %f ", null, "Null option name given");
+ test.checkAdd(" ", null, "Null option name given");
+ test.checkAdd("", null, "Null option name given");
+ test.checkAdd(" %v", null, "Null option name given");
+ test.checkAdd("-foo ", null, "No conversion character given");
+ test.checkAdd("-foo %", null, "No conversion character given");
+ test.checkAdd("foo, aaa bbb ", null, "Names not separated by ','");
+ test.checkAdd(" foo aaa %d", null, "Names not separated by ','");
+ test.checkAdd("-arg1,-b,", null, "Null option name given");
+ test.checkAdd("-arg1,-b", null, "No conversion character given");
+ test.checkAdd("-arg1 ", null, "No conversion character given");
+ test.checkAdd("-arg1, %v", null, "Null option name given");
+ test.checkAdd("-arg1,%v", null, "Null option name given");
+ test.checkAdd("-foo %V", null,
+ "Conversion code 'V' not one of 'iodxcbfsvh'");
+ test.checkAdd("-h %hX5", null, "Multipliers not supported for %h");
+ test.checkAdd("-h %h{}", null, "Ranges not supported for %h");
+ test.checkAdd("-help, -h %h #here is how we help you",
+ null, 'h', 1, new String[] { "-help ", "-h " },
+ null, "here is how we help you", null);
+
+ test.checkAdd(
+ "-arg1 ,-arg2=%d{0,3,(7,16]}X1 #x3 test",
+ l3, 'd', 1, new String[] { "-arg1 ", "-arg2=" },
+ new RngCheck[]
+ { new RngCheck(0),
+ new RngCheck(3),
+ new RngCheck(7, OPEN, 16, CLOSED),
+ },
+ "x3 test", null);
+
+ test.checkAdd(
+ "bbb,ccc%x{[1,2]} #X3 x3 test",
+ l3, 'x', 1, new String[] { "bbb", "ccc" },
+ new RngCheck[]
+ { new RngCheck(1, CLOSED, 2, CLOSED),
+ },
+ "X3 x3 test", null);
+
+ test.checkAdd(
+ " bbb ,ccc, ddd ,e , f=%bX1 #x3 test",
+ b3, 'b', 1, new String[] { "bbb ", "ccc", "ddd ", "e ", "f=" },
+ null,
+ "x3 test", null);
+
+ test.checkAdd(
+ " bbb ,ccc, ddd ,e , f= %bX3 #x3 test",
+ b3, 'b', 3, new String[] { "bbb ", "ccc ", "ddd ", "e ", "f= " },
+ null,
+ "x3 test", null);
+
+ test.checkAdd(
+ "-b,--bar %s{[\"john\",\"jerry\"),fred,\"harry\"} #sets bar",
+ sh, 's', 1, new String[] { "-b ", "--bar " },
+ new RngCheck[] {
+ new RngCheck("jerry", OPEN, "john", CLOSED),
+ new RngCheck("fred"),
+ new RngCheck("harry") },
+ "sets bar", null);
+
+ test.checkAdd(
+ "-c ,coven%f{0.0,9.0,(6,5],[-9.1,10.2]} ",
+ dh, 'f', 1, new String[] { "-c ", "coven" },
+ new RngCheck[] {
+ new RngCheck(0.0),
+ new RngCheck(9.0),
+ new RngCheck(5.0, CLOSED, 6.0, OPEN),
+ new RngCheck(-9.1, CLOSED, 10.2, CLOSED) },
+ "", null);
+
+ test.checkAdd(
+ "-b %b #a boolean value ",
+ bh, 'b', 1, new String[] { "-b " },
+ new RngCheck[] {},
+ "a boolean value ", null);
+
+ test.checkAdd("-a %i", ih, 'i', 1, "-a ", null, "", null);
+ test.checkAdd("-a %o", lh, 'o', 1, "-a ", null, "", null);
+ test.checkAdd("-a %d", i3, 'd', 1, "-a ", null, "", null);
+ test.checkAdd("-a %x", l3, 'x', 1, "-a ", null, "", null);
+ test.checkAdd("-a %c", ch, 'c', 1, "-a ", null, "", null);
+ test.checkAdd("-a %c", c3, 'c', 1, "-a ", null, "", null);
+ test.checkAdd("-a %v", bh, 'v', 1, "-a ", null, "", null);
+ test.checkAdd("-a %b", b3, 'b', 1, "-a ", null, "", null);
+ test.checkAdd("-a %f", fh, 'f', 1, "-a ", null, "", null);
+ test.checkAdd("-a %f", f3, 'f', 1, "-a ", null, "", null);
+ test.checkAdd("-a %f", dh, 'f', 1, "-a ", null, "", null);
+ test.checkAdd("-a %f", d3, 'f', 1, "-a ", null, "", null);
+
+ test.checkAdd("-a %i", fh, 'i', 1, "-a ", null, "",
+ "Invalid result holder for %i");
+ test.checkAdd("-a %c", i3, 'c', 1, "-a ", null, "",
+ "Invalid result holder for %c");
+ test.checkAdd("-a %v", d3, 'v', 1, "-a ", null, "",
+ "Invalid result holder for %v");
+ test.checkAdd("-a %f", sh, 'f', 1, "-a ", null, "",
+ "Invalid result holder for %f");
+ test.checkAdd("-a %s", l3, 's', 1, "-a ", null, "",
+ "Invalid result holder for %s");
+
+ test.checkAdd("-foo %i{} ", ih, 'i', 1, "-foo ", null, "", null);
+ test.checkAdd("-foo%i{}", ih, 'i', 1, "-foo", null, "", null);
+ test.checkAdd("-foo%i{ }", ih, 'i', 1, "-foo", null, "", null);
+ test.checkAdd("-foo%i{ }}", ih,
+ "Illegal character(s), expecting '#'");
+ test.checkAdd("-foo%i{ ", ih, "Unterminated range specification");
+ test.checkAdd("-foo%i{", ih, "Unterminated range specification");
+ test.checkAdd("-foo%i{0,9", ih, "Unterminated range specification");
+ test.checkAdd("-foo%i{1,2,3)", ih,
+ "Unterminated range specification");
+
+ test.checkAdd("-b %f{0.9}", fh, 'f', 1, "-b ",
+ new RngCheck[] { new RngCheck(0.9) },
+ "", null);
+ test.checkAdd("-b %f{ 0.9 ,7, -0.5,-4 ,6 }", fh, 'f', 1, "-b ",
+ new RngCheck[] { new RngCheck(0.9),
+ new RngCheck(7.0),
+ new RngCheck(-0.5),
+ new RngCheck(-4.0),
+ new RngCheck(6.0) },
+ "", null);
+ test.checkAdd("-b %f{ [0.9,7), (-0.5,-4),[9,6] , (10,13.4] }",
+ fh, 'f', 1, "-b ",
+ new RngCheck[] { new RngCheck(0.9, CLOSED, 7.0, OPEN),
+ new RngCheck(-4.0, OPEN, -.5, OPEN),
+ new RngCheck(6.0, CLOSED, 9.0, CLOSED),
+ new RngCheck(10.0, OPEN, 13.4, CLOSED),
+ },
+ "", null);
+ test.checkAdd("-b %f{(8 9]}", fh,
+ "Missing ',' in subrange specification");
+ test.checkAdd("-b %f{(8,9,]}", fh,
+ "Unterminated subrange");
+ test.checkAdd("-b %f{(8,9 ,]}", fh,
+ "Unterminated subrange");
+ test.checkAdd("-b %f{(8,9 8]}", fh,
+ "Unterminated subrange");
+ test.checkAdd("-b %f{8 9}", fh,
+ "Range spec: ',' or '}' expected");
+ test.checkAdd("-b %f{8 *}", fh,
+ "Range spec: ',' or '}' expected");
+
+ test.checkAdd("-b %f{8y}", fh,
+ "Range spec: ',' or '}' expected");
+ test.checkAdd("-b %f{.}", fh,
+ "Malformed float '.}' in range spec");
+ test.checkAdd("-b %f{1.0e}", fh,
+ "Malformed float '1.0e}' in range spec");
+ test.checkAdd("-b %f{[*]}", fh,
+ "Malformed float '*' in range spec");
+ test.checkAdd("-b %f{1.2e5t}", fh,
+ "Range spec: ',' or '}' expected");
+
+ test.checkAdd("-b %i{8}", ih, 'i', 1, "-b ",
+ new RngCheck[] { new RngCheck(8) },
+ "", null);
+ test.checkAdd("-b %i{8, 9,10 }", ih, 'i', 1, "-b ",
+ new RngCheck[] { new RngCheck(8),
+ new RngCheck(9),
+ new RngCheck(10) },
+ "", null);
+ test.checkAdd("-b %i{8, [-9,10),[-17,15],(2,-33),(8,9] }",
+ ih, 'i', 1, "-b ",
+ new RngCheck[] { new RngCheck(8),
+ new RngCheck(-9, CLOSED, 10, OPEN),
+ new RngCheck(-17, CLOSED, 15, CLOSED),
+ new RngCheck(-33, OPEN, 2, OPEN),
+ new RngCheck(8, OPEN, 9, CLOSED),
+ },
+ "", null);
+ test.checkAdd("-b %i{8.7}", ih,
+ "Range spec: ',' or '}' expected");
+ test.checkAdd("-b %i{6,[*]}", ih,
+ "Malformed integer '*' in range spec");
+ test.checkAdd("-b %i{g76}", ih,
+ "Malformed integer 'g' in range spec");
+
+ test.checkAdd("-b %s{foobar}", sh, 's', 1, "-b ",
+ new RngCheck[] { new RngCheck("foobar") },
+ "", null);
+ test.checkAdd("-b %s{foobar, 0x233,\" \"}", sh, 's', 1, "-b ",
+ new RngCheck[] { new RngCheck("foobar"),
+ new RngCheck("0x233"),
+ new RngCheck(" ") },
+ "", null);
+ test.checkAdd("-b %s{foobar,(bb,aa], [\"01\",02]}",
+ sh, 's', 1, "-b ",
+ new RngCheck[]
+ { new RngCheck("foobar"),
+ new RngCheck("aa", CLOSED, "bb", OPEN),
+ new RngCheck("01", CLOSED, "02", CLOSED),
+ },
+ "", null);
+
+ test.checkAdd("-b %c{'a'}", ch, 'c', 1, "-b ",
+ new RngCheck[] { new RngCheck('a') },
+ "", null);
+ test.checkAdd("-b %c{'\\n', '\\002', 'B'}", ch, 'c', 1, "-b ",
+ new RngCheck[] { new RngCheck('\n'),
+ new RngCheck('\002'),
+ new RngCheck('B') },
+ "", null);
+ test.checkAdd("-b %c{'q',('g','a'], ['\t','\\003']}",
+ ch, 'c', 1, "-b ",
+ new RngCheck[]
+ { new RngCheck('q'),
+ new RngCheck('a', CLOSED, 'g', OPEN),
+ new RngCheck('\003', CLOSED, '\t', CLOSED),
+ },
+ "", null);
+
+ test.checkAdd("-b %b{true}X2", b3, 'b', 2, "-b ",
+ new RngCheck[] { new RngCheck(true) },
+ "", null);
+ test.checkAdd("-b %b{ true , false, true }", bh, 'b', 1, "-b ",
+ new RngCheck[] { new RngCheck(true),
+ new RngCheck(false),
+ new RngCheck(true) },
+ "", null);
+ test.checkAdd("-b %v{true,[true,false)}", bh,
+ "Sub ranges not supported for %b or %v");
+ test.checkAdd("-b %v{true,[]}", bh,
+ "Sub ranges not supported for %b or %v");
+ test.checkAdd("-b %b{tru}", bh,
+ "Malformed boolean 'tru}' in range spec");
+
+ test.checkAdd("-b %iX2", i3, 'i', 2, "-b ", null, "", null);
+ test.checkAdd("-b %vX3", b3, 'v', 3, "-b ", null, "", null);
+ test.checkAdd("-b %v{ }X3", b3, 'v', 3, "-b ", null, "", null);
+
+ test.checkAdd("-b=%iX2", i3, 'i', 2, "-b", null, "",
+ "Multiplier value incompatible with one word option -b=");
+ test.checkAdd("-b %iX0", i3, 'i', 0, "-b ", null, "",
+ "Value multiplier number must be > 0");
+ test.checkAdd("-b %iX-6", i3, 'i', 0, "-b ", null, "",
+ "Value multiplier number must be > 0");
+ test.checkAdd("-b %iXy", i3, 'i', 0, "-b ", null, "",
+ "Malformed value multiplier");
+ test.checkAdd("-b %iX4", i3, 'i', 4, "-b ", null, "",
+ "Result holder array must have a length >= 4");
+ test.checkAdd("-b %iX4", ih, 'i', 4, "-b ", null, "",
+ "Multiplier requires result holder to be an array of length >= 4");
+
+ test.checkAdd("-b %i #X4", ih, 'i', 1, "-b ", null, "X4", null);
+ test.checkAdd("-b %i #[}X4", ih, 'i', 1, "-b ", null, "[}X4", null);
+
+ // test.checkPrintHelp("");
+ // test.checkPrintUsage("");
+
+ test = new ArgParserTest();
+
+ test.checkAdd(
+ "-intarg %i{1,2,(9,18],[22,27],[33,38),(45,48)} #test int arg",
+ ih, 'i', 1, "-intarg ",
+ new RngCheck[]
+ { new RngCheck(1),
+ new RngCheck(2),
+ new RngCheck(9, OPEN, 18, CLOSED),
+ new RngCheck(22, CLOSED, 27, CLOSED),
+ new RngCheck(33, CLOSED, 38, OPEN),
+ new RngCheck(45, OPEN, 48, OPEN),
+ },
+ "test int arg", null);
+
+ MTest[] tests;
+
+ tests = new MTest[]
+ {
+ new MTest("-intarg 1", new Long(1)),
+ new MTest("-intarg 3", new MErr('r', "3")),
+ new MTest("-intarg 9", new MErr('r', "9")),
+ new MTest("-intarg 11", new Long(11)),
+ new MTest("-intarg 18", new Long(18)),
+ new MTest("-intarg 22", new Long(22)),
+ new MTest("-intarg 25", new Long(25)),
+ new MTest("-intarg 27", new Long(27)),
+ new MTest("-intarg 33", new Long(33)),
+ new MTest("-intarg 35", new Long(35)),
+ new MTest("-intarg 38", new MErr('r', "38")),
+ new MTest("-intarg 45", new MErr('r', "45")),
+ new MTest("-intarg 46", new Long(46)),
+ new MTest("-intarg 48", new MErr('r', "48")),
+ new MTest("-intarg 100", new MErr('r', "100")),
+ new MTest("-intarg 0xbeef", new MErr('r', "0xbeef")),
+ new MTest("-intarg 0x2f", new Long(0x2f)),
+ new MTest("-intarg 041", new Long(041)),
+ };
+ test.checkMatches(tests, MULTI_WORD);
+
+ test.checkAdd(
+ "-farg %f{1,2,(9,18],[22,27],[33,38),(45,48)} #test float arg",
+ dh, 'f', 1, "-farg ",
+ new RngCheck[]
+ {
+ new RngCheck(1.0),
+ new RngCheck(2.0),
+ new RngCheck(9.0, OPEN, 18.0, CLOSED),
+ new RngCheck(22.0, CLOSED, 27.0, CLOSED),
+ new RngCheck(33.0, CLOSED, 38.0, OPEN),
+ new RngCheck(45.0, OPEN, 48.0, OPEN),
+ },
+ "test float arg", null);
+
+ tests = new MTest[]
+ {
+ new MTest("-farg 1", new Double(1)),
+ new MTest("-farg 3", new MErr('r', "3")),
+ new MTest("-farg 9", new MErr('r', "9")),
+ new MTest("-farg 9.0001", new Double(9.0001)),
+ new MTest("-farg 11", new Double(11)),
+ new MTest("-farg 18", new Double(18)),
+ new MTest("-farg 22", new Double(22)),
+ new MTest("-farg 25", new Double(25)),
+ new MTest("-farg 27", new Double(27)),
+ new MTest("-farg 33", new Double(33)),
+ new MTest("-farg 35", new Double(35)),
+ new MTest("-farg 37.9999", new Double(37.9999)),
+ new MTest("-farg 38", new MErr('r', "38")),
+ new MTest("-farg 45", new MErr('r', "45")),
+ new MTest("-farg 45.0001", new Double(45.0001)),
+ new MTest("-farg 46", new Double(46)),
+ new MTest("-farg 47.9999", new Double(47.9999)),
+ new MTest("-farg 48", new MErr('r', "48")),
+ new MTest("-farg 100", new MErr('r', "100")),
+ new MTest("-farg 0", new MErr('r', "0")),
+ };
+ test.checkMatches(tests, MULTI_WORD);
+
+ test.checkAdd(
+ "-sarg %s{1,2,(AA,AZ],[BB,BX],[C3,C8),(d5,d8)} #test string arg",
+ s3, 's', 1, "-sarg ",
+ new RngCheck[]
+ { new RngCheck("1"),
+ new RngCheck("2"),
+ new RngCheck("AA", OPEN, "AZ", CLOSED),
+ new RngCheck("BB", CLOSED, "BX", CLOSED),
+ new RngCheck("C3", CLOSED, "C8", OPEN),
+ new RngCheck("d5", OPEN, "d8", OPEN),
+ },
+ "test string arg", null);
+
+ tests = new MTest[]
+ {
+ new MTest("-sarg 1", "1"),
+ new MTest("-sarg 3", new MErr('r', "3")),
+ new MTest("-sarg AA", new MErr('r', "AA")),
+ new MTest("-sarg AM", "AM"),
+ new MTest("-sarg AZ", "AZ"),
+ new MTest("-sarg BB", "BB"),
+ new MTest("-sarg BL", "BL"),
+ new MTest("-sarg BX", "BX"),
+ new MTest("-sarg C3", "C3"),
+ new MTest("-sarg C6", "C6"),
+ new MTest("-sarg C8", new MErr('r', "C8")),
+ new MTest("-sarg d5", new MErr('r', "d5")),
+ new MTest("-sarg d6", "d6"),
+ new MTest("-sarg d8", new MErr('r', "d8")),
+ new MTest("-sarg zzz", new MErr('r', "zzz")),
+ new MTest("-sarg 0", new MErr('r', "0")),
+ };
+ test.checkMatches(tests, MULTI_WORD);
+
+ test = new ArgParserTest();
+
+ test.checkAdd(
+ "-carg %c{1,2,(a,z],['A','Z'],['\\001',\\007),(4,8)}",
+ c3, 'c', 1, "-carg ",
+ new RngCheck[]
+ { new RngCheck('1'),
+ new RngCheck('2'),
+ new RngCheck('a', OPEN, 'z', CLOSED),
+ new RngCheck('A', CLOSED, 'Z', CLOSED),
+ new RngCheck('\001', CLOSED, '\007', OPEN),
+ new RngCheck('4', OPEN, '8', OPEN),
+ },
+ "", null);
+
+ tests = new MTest[]
+ {
+ new MTest("-carg 1", new Character('1')),
+ new MTest("-carg 3", new MErr('r', "3")),
+ new MTest("-carg a", new MErr('r', "a")),
+ new MTest("-carg m", new Character('m')),
+ new MTest("-carg z", new Character('z')),
+ new MTest("-carg A", new Character('A')),
+ new MTest("-carg 'L'", new Character('L')),
+ new MTest("-carg 'Z'", new Character('Z')),
+ new MTest("-carg \\001", new Character('\001')),
+ new MTest("-carg \\005", new Character('\005')),
+ new MTest("-carg '\\007'", new MErr('r', "'\\007'")),
+ new MTest("-carg '4'", new MErr('r', "'4'")),
+ new MTest("-carg 6", new Character('6')),
+ new MTest("-carg 8", new MErr('r', "8")),
+ new MTest("-carg '\\012'", new MErr('r', "'\\012'")),
+ new MTest("-carg 0", new MErr('r', "0")),
+ };
+ test.checkMatches(tests, MULTI_WORD);
+
+ test.checkAdd(
+ "-foo=%i{[-50,100]}", ih, 'i', 1, "-foo=",
+ new RngCheck[]
+ { new RngCheck(-50, CLOSED, 100, CLOSED),
+ },
+ "", null);
+
+ tests = new MTest[]
+ {
+ new MTest("-foo=-51", new MErr('r', "-51")),
+ new MTest("-foo=-0x32", new Long(-0x32)),
+ new MTest("-foo=-0x33", new MErr('r', "-0x33")),
+ new MTest("-foo=-0777", new MErr('r', "-0777")),
+ new MTest("-foo=-07", new Long(-07)),
+ new MTest("-foo=0", new Long(0)),
+ new MTest("-foo=100", new Long(100)),
+ new MTest("-foo=0x5e", new Long(0x5e)),
+ new MTest("-foo=066", new Long(066)),
+ new MTest("-foo=06677", new MErr('r', "06677")),
+ new MTest("-foo=0xbeef", new MErr('r', "0xbeef")),
+ new MTest("-foo=foo", new MErr('m', "foo")),
+ new MTest("-foo=-51d", new MErr('m', "-51d")),
+ };
+ test.checkMatches(tests, ONE_WORD);
+
+ test.checkAdd("-foo2=%i", ih, 'i', 1, "-foo2=", null, "", null);
+ tests = new MTest[]
+ {
+ new MTest("-foo2=-51", new Long(-51)),
+ new MTest("-foo2=-0x33", new Long(-0x33)),
+ new MTest("-foo2=-0777", new Long(-0777)),
+ new MTest("-foo2=06677", new Long(06677)),
+ new MTest("-foo2=0xbeef", new Long(0xbeef)),
+ new MTest("-foo2=foo", new MErr('m', "foo")),
+ new MTest("-foo2=-51d", new MErr('m', "-51d")),
+ new MTest("-foo2=-51", new Long(-51)),
+ };
+ test.checkMatches(tests, ONE_WORD);
+
+ test.checkAdd("-foo3 %iX3", i3, 'i', 3, "-foo3 ", null, "", null);
+ tests = new MTest[]
+ {
+ new MTest("-foo3 -51 678 0x45",
+ new long[] { -51, 678, 0x45 }),
+ new MTest("-foo3 55 16f 55", new MErr('m', "16f")),
+ new MTest("-foo3 55 16", new MErr('v', "3")),
+ };
+ test.checkMatches(tests, MULTI_WORD);
+
+ Vector<String> vec = new Vector<String>(100);
+
+ test.checkAdd("-foov3 %iX3", vec, 'i', 3, "-foov3 ", null, "", null);
+ tests = new MTest[]
+ { new MTest("-foov3 -1 2 4", new long[] { -1, 2, 4 }, 0),
+ new MTest("-foov3 10 3 9", new long[] { 10, 3, 9 }, 1),
+ new MTest("-foov3 123 1 0", new long[] { 123, 1, 0 }, 2),
+ };
+ vec.clear();
+ test.checkMatches(tests, MULTI_WORD);
+ test.checkAdd("-foov %i", vec, 'i', 1, "-foov ", null, "", null);
+ tests = new MTest[]
+ { new MTest("-foov 11", new Long(11), 0),
+ new MTest("-foov 12", new Long(12), 1),
+ new MTest("-foov 13", new Long(13), 2),
+ };
+ vec.clear();
+ test.checkMatches(tests, MULTI_WORD);
+
+ test.checkAdd(
+ "-foo4 %i{[-50,100]}X2", i3, 'i', 2, "-foo4 ",
+ new RngCheck[]
+ { new RngCheck(-50, CLOSED, 100, CLOSED),
+ },
+ "", null);
+ tests = new MTest[]
+ {
+ new MTest("-foo4 -49 78",
+ new long[] { -49, 78 }),
+ new MTest("-foo4 -48 102", new MErr('r', "102")),
+ };
+ test.checkMatches(tests, MULTI_WORD);
+
+ test.checkAdd(
+ "-oct=%o{[-062,0144]}", ih, 'o', 1, "-oct=",
+ new RngCheck[]
+ { new RngCheck(-50, CLOSED, 100, CLOSED),
+ },
+ "", null);
+
+ tests = new MTest[]
+ {
+ new MTest("-oct=-063", new MErr('r', "-063")),
+ new MTest("-oct=-0x32", new MErr('m', "-0x32")),
+ new MTest("-oct=-0777", new MErr('r', "-0777")),
+ new MTest("-oct=-07", new Long(-07)),
+ new MTest("-oct=0", new Long(0)),
+ new MTest("-oct=100", new Long(64)),
+ new MTest("-oct=0xae", new MErr('m', "0xae")),
+ new MTest("-oct=66", new Long(066)),
+ new MTest("-oct=06677", new MErr('r', "06677")),
+ new MTest("-oct=0xbeef", new MErr('m', "0xbeef")),
+ new MTest("-oct=foo", new MErr('m', "foo")),
+ new MTest("-oct=-51d", new MErr('m', "-51d")),
+ new MTest("-oct=78", new MErr('m', "78")),
+ };
+ test.checkMatches(tests, ONE_WORD);
+
+ test.checkAdd("-oct2=%o", ih, 'o', 1, "-oct2=", null, "", null);
+ tests = new MTest[]
+ {
+ new MTest("-oct2=-063", new Long(-063)),
+ new MTest("-oct2=-0777", new Long(-0777)),
+ new MTest("-oct2=06677", new Long(06677)),
+ };
+ test.checkMatches(tests, ONE_WORD);
+
+ test.checkAdd(
+ "-dec=%d{[-0x32,0x64]}", ih, 'd', 1, "-dec=",
+ new RngCheck[]
+ { new RngCheck(-50, CLOSED, 100, CLOSED),
+ },
+ "", null);
+
+ tests = new MTest[]
+ {
+ new MTest("-dec=-063", new MErr('r', "-063")),
+ new MTest("-dec=-0x32", new MErr('m', "-0x32")),
+ new MTest("-dec=-0777", new MErr('r', "-0777")),
+ new MTest("-dec=-07", new Long(-07)),
+ new MTest("-dec=0", new Long(0)),
+ new MTest("-dec=100", new Long(100)),
+ new MTest("-dec=0xae", new MErr('m', "0xae")),
+ new MTest("-dec=66", new Long(66)),
+ new MTest("-dec=06677", new MErr('r', "06677")),
+ new MTest("-dec=0xbeef", new MErr('m', "0xbeef")),
+ new MTest("-dec=foo", new MErr('m', "foo")),
+ new MTest("-dec=-51d", new MErr('m', "-51d")),
+ };
+ test.checkMatches(tests, ONE_WORD);
+
+ test.checkAdd("-dec2=%d", ih, 'd', 1, "-dec2=", null, "", null);
+ tests = new MTest[]
+ {
+ new MTest("-dec2=-063", new Long(-63)),
+ new MTest("-dec2=-0777", new Long(-777)),
+ new MTest("-dec2=06677", new Long(6677)),
+ };
+ test.checkMatches(tests, ONE_WORD);
+
+ test.checkAdd(
+ "-hex=%x{[-0x32,0x64]}", ih, 'x', 1, "-hex=",
+ new RngCheck[]
+ { new RngCheck(-50, CLOSED, 100, CLOSED),
+ },
+ "", null);
+
+ tests = new MTest[]
+ {
+ new MTest("-hex=-06", new Long(-0x6)),
+ new MTest("-hex=-0x3g2", new MErr('m', "-0x3g2")),
+ new MTest("-hex=-0777", new MErr('r', "-0777")),
+ new MTest("-hex=-017", new Long(-0x17)),
+ new MTest("-hex=0", new Long(0)),
+ new MTest("-hex=64", new Long(0x64)),
+ new MTest("-hex=5e", new Long(0x5e)),
+ new MTest("-hex=66", new MErr('r', "66")),
+ new MTest("-hex=06677", new MErr('r', "06677")),
+ new MTest("-hex=0xbeef", new MErr('m', "0xbeef")),
+ new MTest("-hex=foo", new MErr('m', "foo")),
+ new MTest("-hex=-51d", new MErr('r', "-51d")),
+ new MTest("-hex=-51g", new MErr('m', "-51g")),
+ new MTest("-hex=", new MErr('c', "")),
+ };
+ test.checkMatches(tests, ONE_WORD);
+
+ test.checkAdd("-hex2=%x", ih, 'x', 1, "-hex2=", null, "", null);
+ tests = new MTest[]
+ {
+ new MTest("-hex2=-0777", new Long(-0x777)),
+ new MTest("-hex2=66", new Long(0x66)),
+ new MTest("-hex2=06677", new Long(0x6677)),
+ new MTest("-hex2=-51d", new Long(-0x51d)),
+ };
+ test.checkMatches(tests, ONE_WORD);
+
+ test.checkAdd(
+ "-char=%c{['b','m']}", ch, 'c', 1, "-char=",
+ new RngCheck[]
+ { new RngCheck('b', CLOSED, 'm', CLOSED),
+ },
+ "", null);
+
+ tests = new MTest[]
+ {
+ new MTest("-char=a", new MErr('r', "a")),
+ new MTest("-char=b", new Character('b')),
+ new MTest("-char='b'", new Character('b')),
+ new MTest("-char='\142'", new Character('b')),
+ new MTest("-char='\141'", new MErr('r', "'\141'")),
+ new MTest("-char=\142", new Character('b')),
+ new MTest("-char=\141", new MErr('r', "\141")),
+ new MTest("-char=m", new Character('m')),
+ new MTest("-char=z", new MErr('r', "z")),
+ new MTest("-char=bb", new MErr('m', "bb")),
+ new MTest("-char='b", new MErr('m', "'b")),
+ new MTest("-char='", new MErr('m', "'")),
+ new MTest("-char=a'", new MErr('m', "a'")),
+ };
+ test.checkMatches(tests, ONE_WORD);
+
+ test.checkAdd("-char2=%c", ch, 'c', 1, "-char2=", null, "", null);
+ tests = new MTest[]
+ {
+ new MTest("-char2=a", new Character('a')),
+ new MTest("-char2='\141'", new Character('\141')),
+ new MTest("-char2=\141", new Character('\141')),
+ new MTest("-char2=z", new Character('z')),
+ };
+ test.checkMatches(tests, ONE_WORD);
+
+ test.checkAdd("-charv3 %cX3", vec, 'c', 3, "-charv3 ", null, "", null);
+ tests = new MTest[]
+ { new MTest("-charv3 a b c", new char[] { 'a', 'b', 'c' }, 0),
+ new MTest("-charv3 'g' f '\\n'", new char[] { 'g', 'f', '\n' }, 1),
+ new MTest("-charv3 1 \001 3", new char[] { '1', '\001', '3' }, 2),
+ };
+ vec.clear();
+ test.checkMatches(tests, MULTI_WORD);
+ test.checkAdd("-charv=%c", vec, 'c', 1, "-charv=", null, "", null);
+ tests = new MTest[]
+ { new MTest("-charv=d", new Character('d'), 0),
+ new MTest("-charv='g'", new Character('g'), 1),
+ new MTest("-charv=\111", new Character('\111'), 2),
+ };
+ vec.clear();
+ test.checkMatches(tests, ONE_WORD);
+
+ test.checkAdd(
+ "-bool=%b{true}", bh, 'b', 1, "-bool=",
+ new RngCheck[]
+ { new RngCheck(true),
+ },
+ "", null);
+
+ tests = new MTest[]
+ {
+ new MTest("-bool=true", new Boolean(true)),
+ new MTest("-bool=false", new MErr('r', "false")),
+ new MTest("-bool=fals", new MErr('m', "fals")),
+ new MTest("-bool=falsem", new MErr('m', "falsem")),
+ new MTest("-bool=truex", new MErr('m', "truex")),
+ new MTest("-bool=foo", new MErr('m', "foo")),
+ new MTest("-bool=1", new MErr('m', "1")),
+ };
+ test.checkMatches(tests, ONE_WORD);
+
+ test.checkAdd(
+ "-boo2=%b{true,false}", bh, 'b', 1, "-boo2=",
+ new RngCheck[]
+ { new RngCheck(true),
+ new RngCheck(false),
+ },
+ "", null);
+
+ tests = new MTest[]
+ {
+ new MTest("-boo2=true", new Boolean(true)),
+ new MTest("-boo2=false", new Boolean(false)),
+ };
+ test.checkMatches(tests, ONE_WORD);
+
+ test.checkAdd("-boo3=%b", bh, 'b', 1, "-boo3=", null, "", null);
+ tests = new MTest[]
+ {
+ new MTest("-boo3=true", new Boolean(true)),
+ new MTest("-boo3=false", new Boolean(false)),
+ };
+ test.checkMatches(tests, ONE_WORD);
+
+ test.checkAdd("-boo3 %bX3", b3, 'b', 3, "-boo3 ", null, "", null);
+ tests = new MTest[]
+ {
+ new MTest("-boo3 true false true",
+ new boolean[] { true, false, true }),
+ new MTest("-boo3 true fals true", new MErr('m', "fals")),
+ };
+ test.checkMatches(tests, MULTI_WORD);
+
+ test.checkAdd("-boov3 %bX3", vec, 'b', 3, "-boov3 ", null, "", null);
+ tests = new MTest[]
+ { new MTest("-boov3 true true false",
+ new boolean[] { true, true, false }, 0),
+ new MTest("-boov3 false false true",
+ new boolean[] { false, false, true }, 1),
+ };
+ vec.clear();
+ test.checkMatches(tests, MULTI_WORD);
+ test.checkAdd("-boov %b", vec, 'b', 1, "-boov ", null, "", null);
+ tests = new MTest[]
+ { new MTest("-boov true", new Boolean(true), 0),
+ new MTest("-boov false", new Boolean(false), 1),
+ new MTest("-boov true", new Boolean(true), 2),
+ };
+ vec.clear();
+ test.checkMatches(tests, MULTI_WORD);
+
+ test.checkAdd("-v3 %vX2", b3, 'v', 2, "-v3 ", null, "", null);
+ tests = new MTest[]
+ { new MTest("-v3", new boolean[] { true, true }),
+ };
+ test.checkMatches(tests, MULTI_WORD);
+
+ test.checkAdd(
+ "-vf %v{false,true}X2", b3, 'v', 2, "-vf ",
+ new RngCheck[]
+ { new RngCheck(false),
+ new RngCheck(true),
+ },
+ "", null);
+ tests = new MTest[]
+ { new MTest("-vf", new boolean[] { false, false }),
+ };
+ test.checkMatches(tests, MULTI_WORD);
+
+ test.checkAdd(
+ "-str=%s{(john,zzzz]}", sh, 's', 1, "-str=",
+ new RngCheck[]
+ { new RngCheck("john", OPEN, "zzzz", CLOSED),
+ },
+ "", null);
+
+ tests = new MTest[]
+ {
+ new MTest("-str=john", new MErr('r', "john")),
+ new MTest("-str=joho ", "joho "),
+ new MTest("-str=joho ", "joho "),
+ new MTest("-str=zzzz", "zzzz"),
+ new MTest("-str= joho", new MErr('r', " joho")),
+ new MTest("-str=jnhn ", new MErr('r', "jnhn ")),
+ new MTest("-str=zzzzz", new MErr('r', "zzzzz")),
+ new MTest("-str=\"joho\"", new MErr('r', "\"joho\"")),
+ new MTest("-str=\"joho", new MErr('r', "\"joho")),
+ new MTest("-str=joho j", "joho j"), // new MErr('m', "joho j")),
+ };
+ test.checkMatches(tests, ONE_WORD);
+
+ test.checkAdd("-str2=%s", sh, 's', 1, "-str2=", null, "", null);
+ tests = new MTest[]
+ {
+ new MTest("-str2= jnhn", " jnhn"),
+ new MTest("-str2=zzzzz", "zzzzz"),
+ };
+ test.checkMatches(tests, ONE_WORD);
+
+ test.checkAdd("-str3 %sX3", s3, 's', 3, "-str3 ", null, "", null);
+ tests = new MTest[]
+ {
+ new MTest("-str3 foo bar johnny",
+ new String[] { "foo", "bar", "johnny" }),
+ new MTest("-str3 zzzzz \"bad foo",
+ new String[] { "zzzzz", "\"bad", "foo"
+ }), // new MErr('m', "\"bad")),
+ };
+ test.checkMatches(tests, MULTI_WORD);
+
+ test.checkAdd("-strv3 %sX3", vec, 's', 3, "-strv3 ", null, "", null);
+ tests = new MTest[]
+ { new MTest("-strv3 foo bar \"hihi\"",
+ new String[] { "foo", "bar", "\"hihi\"" }, 0),
+ new MTest("-strv3 a 123 gg",
+ new String[] { "a", "123", "gg" }, 1),
+ };
+ vec.clear();
+ test.checkMatches(tests, MULTI_WORD);
+ test.checkAdd("-strv=%s", vec, 's', 1, "-strv=", null, "", null);
+ tests = new MTest[]
+ { new MTest("-strv=d", "d", 0),
+ new MTest("-strv='g'", "'g'", 1),
+ new MTest("-strv=\\111", "\\111", 2),
+ };
+ vec.clear();
+ test.checkMatches(tests, ONE_WORD);
+
+ test.checkAdd(
+ "-float=%f{(-0.001,1000.0]}", dh, 'f', 1, "-float=",
+ new RngCheck[]
+ { new RngCheck(-0.001, OPEN, 1000.0, CLOSED),
+ },
+ "", null);
+
+ tests = new MTest[]
+ {
+ new MTest("-float=-0.000999", new Double(-0.000999)),
+ new MTest("-float=1e-3", new Double(0.001)),
+ new MTest("-float=12.33e1", new Double(123.3)),
+ new MTest("-float=1e3", new Double(1e3)),
+ new MTest("-float=1000.000", new Double(1000.0)),
+ new MTest("-float=-0.001", new MErr('r', "-0.001")),
+ new MTest("-float=-1e-3", new MErr('r', "-1e-3")),
+ new MTest("-float=1000.001", new MErr('r', "1000.001")),
+ new MTest("-float=.", new MErr('m', ".")),
+ new MTest("-float= 124.5 ", new Double(124.5)),
+ new MTest("-float=124.5x", new MErr('m', "124.5x")),
+ new MTest("-float= foo ", new MErr('m', " foo ")),
+ new MTest("-float=1e1", new Double(10)),
+ new MTest("-float=1e ", new MErr('m', "1e ")),
+ };
+ test.checkMatches(tests, ONE_WORD);
+
+ test.checkAdd("-float2=%f", dh, 'f', 1, "-float2=", null, "", null);
+ tests = new MTest[]
+ {
+ new MTest("-float2=-0.001", new Double(-0.001)),
+ new MTest("-float2=-1e-3", new Double(-1e-3)),
+ new MTest("-float2=1000.001", new Double(1000.001)),
+ };
+ test.checkMatches(tests, ONE_WORD);
+
+ test.checkAdd("-f3 %fX3", d3, 'f', 3, "-f3 ", null, "", null);
+ tests = new MTest[]
+ {
+ new MTest("-f3 -0.001 1.23e5 -9.88e-4",
+ new double[] { -0.001, 1.23e5, -9.88e-4 }),
+ new MTest("-f3 7.88 foo 9.0", new MErr('m', "foo")),
+ new MTest("-f3 7.88 . 9.0", new MErr('m', ".")),
+ new MTest("-f3 7.88 3.0 9.0x", new MErr('m', "9.0x")),
+ };
+ test.checkMatches(tests, MULTI_WORD);
+
+ test.checkAdd("-fv3 %fX3", vec, 'f', 3, "-fv3 ", null, "", null);
+ tests = new MTest[]
+ { new MTest("-fv3 1.0 3.444 6.7",
+ new double[] { 1.0, 3.444, 6.7 }, 0),
+ new MTest("-fv3 13e-5 145.678 0.0001e45",
+ new double[] { 13e-5, 145.678, 0.0001e45 }, 1),
+ new MTest("-fv3 11.11 3.1245 -1e-4",
+ new double[] { 11.11, 3.1245, -1e-4 }, 2),
+ new MTest("-fv3 1.0 2 3",
+ new double[] { 1.0, 2.0, 3.0 }, 3),
+ };
+ vec.clear();
+ test.checkMatches(tests, MULTI_WORD);
+ test.checkAdd("-fv %f", vec, 'f', 1, "-fv ", null, "", null);
+ tests = new MTest[]
+ { new MTest("-fv -15.1234", new Double(-15.1234), 0),
+ new MTest("-fv -1.234e-7", new Double(-1.234e-7), 1),
+ new MTest("-fv 0.001111", new Double(0.001111), 2),
+ };
+ vec.clear();
+ test.checkMatches(tests, MULTI_WORD);
+
+ IntHolder intHolder = new IntHolder();
+ StringHolder strHolder = new StringHolder();
+
+ ArgParser parser = new ArgParser("test");
+ parser.addOption("-foo %d #an int", intHolder);
+ parser.addOption("-bar %s #a string", strHolder);
+ args = new String[]
+ { "zzz", "-cat", "-foo", "123", "yyy", "-bar", "xxxx", "xxx"
+ };
+
+ String[] unmatchedCheck = new String[]
+ { "zzz", "-cat", "yyy", "xxx"
+ };
+
+ String[] unmatched = parser.matchAllArgs(args, 0, 0);
+ test.checkStringArray(
+ "Unmatched args:", unmatched, unmatchedCheck);
+
+ vec.clear();
+ for (int i = 0; i < args.length;) {
+ try {
+ i = parser.matchArg(args, i);
+ if (parser.getUnmatchedArgument() != null) {
+ vec.add(parser.getUnmatchedArgument());
+ }
+ } catch (Exception e) {
+ }
+ }
+ unmatched = (String[]) vec.toArray(new String[0]);
+ test.checkStringArray(
+ "My unmatched args:", unmatched, unmatchedCheck);
+
+ System.out.println("\nPassed\n");
+
+ }
}
diff --git a/pki/base/silent/src/com/netscape/pkisilent/argparser/BooleanHolder.java b/pki/base/silent/src/com/netscape/pkisilent/argparser/BooleanHolder.java
index c5dece11..dba72b6d 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/BooleanHolder.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/BooleanHolder.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.argparser;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -18,37 +19,34 @@ package com.netscape.pkisilent.argparser;
// --- END COPYRIGHT BLOCK ---
/**
- * Wrapper class which ``holds'' a boolean value,
- * enabling methods to return boolean values through
- * arguments.
- */
-public class BooleanHolder implements java.io.Serializable
-{
- /**
+ * Wrapper class which ``holds'' a boolean value, enabling methods to return
+ * boolean values through arguments.
+ */
+public class BooleanHolder implements java.io.Serializable {
+ /**
*
*/
private static final long serialVersionUID = -2863748864787121510L;
/**
- * Value of the boolean, set and examined
- * by the application as needed.
- */
- public boolean value;
+ * Value of the boolean, set and examined by the application as needed.
+ */
+ public boolean value;
- /**
- * Constructs a new <code>BooleanHolder</code> with an initial
- * value of <code>false</code>.
- */
- public BooleanHolder ()
- { value = false;
- }
+ /**
+ * Constructs a new <code>BooleanHolder</code> with an initial value of
+ * <code>false</code>.
+ */
+ public BooleanHolder() {
+ value = false;
+ }
- /**
- * Constructs a new <code>BooleanHolder</code> with a
- * specific initial value.
- *
- * @param b Initial boolean value.
- */
- public BooleanHolder (boolean b)
- { value = b;
- }
+ /**
+ * Constructs a new <code>BooleanHolder</code> with a specific initial
+ * value.
+ *
+ * @param b Initial boolean value.
+ */
+ public BooleanHolder(boolean b) {
+ value = b;
+ }
}
diff --git a/pki/base/silent/src/com/netscape/pkisilent/argparser/CharHolder.java b/pki/base/silent/src/com/netscape/pkisilent/argparser/CharHolder.java
index b30259b4..eed57892 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/CharHolder.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/CharHolder.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.argparser;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -18,39 +19,32 @@ package com.netscape.pkisilent.argparser;
// --- END COPYRIGHT BLOCK ---
/**
- * Wrapper class which ``holds'' a character value,
- * enabling methods to return character values through
- * arguments.
- */
-public class CharHolder implements java.io.Serializable
-{
- /**
+ * Wrapper class which ``holds'' a character value, enabling methods to return
+ * character values through arguments.
+ */
+public class CharHolder implements java.io.Serializable {
+ /**
*
*/
private static final long serialVersionUID = 7340010668929015745L;
/**
- * Value of the character, set and examined
- * by the application as needed.
- */
- public char value;
+ * Value of the character, set and examined by the application as needed.
+ */
+ public char value;
- /**
- * Constructs a new <code>CharHolder</code> with an initial
- * value of 0.
- */
- public CharHolder ()
- { value = 0;
- }
+ /**
+ * Constructs a new <code>CharHolder</code> with an initial value of 0.
+ */
+ public CharHolder() {
+ value = 0;
+ }
- /**
- * Constructs a new <code>CharHolder</code> with a
- * specific initial value.
- *
- * @param c Initial character value.
- */
- public CharHolder (char c)
- { value = c;
- }
+ /**
+ * Constructs a new <code>CharHolder</code> with a specific initial value.
+ *
+ * @param c Initial character value.
+ */
+ public CharHolder(char c) {
+ value = c;
+ }
}
-
-
diff --git a/pki/base/silent/src/com/netscape/pkisilent/argparser/DoubleHolder.java b/pki/base/silent/src/com/netscape/pkisilent/argparser/DoubleHolder.java
index 293a9cc7..b75f9f15 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/DoubleHolder.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/DoubleHolder.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.argparser;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -18,38 +19,32 @@ package com.netscape.pkisilent.argparser;
// --- END COPYRIGHT BLOCK ---
/**
- * Wrapper class which ``holds'' a double value,
- * enabling methods to return double values through
- * arguments.
- */
-public class DoubleHolder implements java.io.Serializable
-{
- /**
+ * Wrapper class which ``holds'' a double value, enabling methods to return
+ * double values through arguments.
+ */
+public class DoubleHolder implements java.io.Serializable {
+ /**
*
*/
private static final long serialVersionUID = 5461991811517552431L;
/**
- * Value of the double, set and examined
- * by the application as needed.
- */
- public double value;
+ * Value of the double, set and examined by the application as needed.
+ */
+ public double value;
- /**
- * Constructs a new <code>DoubleHolder</code> with an initial
- * value of 0.
- */
- public DoubleHolder ()
- { value = 0;
- }
+ /**
+ * Constructs a new <code>DoubleHolder</code> with an initial value of 0.
+ */
+ public DoubleHolder() {
+ value = 0;
+ }
- /**
- * Constructs a new <code>DoubleHolder</code> with a
- * specific initial value.
- *
- * @param d Initial double value.
- */
- public DoubleHolder (double d)
- { value = d;
- }
+ /**
+ * Constructs a new <code>DoubleHolder</code> with a specific initial value.
+ *
+ * @param d Initial double value.
+ */
+ public DoubleHolder(double d) {
+ value = d;
+ }
}
-
diff --git a/pki/base/silent/src/com/netscape/pkisilent/argparser/FloatHolder.java b/pki/base/silent/src/com/netscape/pkisilent/argparser/FloatHolder.java
index 0fbcc45a..14a13d9e 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/FloatHolder.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/FloatHolder.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.argparser;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -18,39 +19,32 @@ package com.netscape.pkisilent.argparser;
// --- END COPYRIGHT BLOCK ---
/**
- * Wrapper class which ``holds'' a float value,
- * enabling methods to return float values through
- * arguments.
- */
-public class FloatHolder implements java.io.Serializable
-{
- /**
+ * Wrapper class which ``holds'' a float value, enabling methods to return float
+ * values through arguments.
+ */
+public class FloatHolder implements java.io.Serializable {
+ /**
*
*/
private static final long serialVersionUID = -7962968109874934361L;
/**
- * Value of the float, set and examined
- * by the application as needed.
- */
- public float value;
+ * Value of the float, set and examined by the application as needed.
+ */
+ public float value;
- /**
- * Constructs a new <code>FloatHolder</code> with an initial
- * value of 0.
- */
- public FloatHolder ()
- { value = 0;
- }
+ /**
+ * Constructs a new <code>FloatHolder</code> with an initial value of 0.
+ */
+ public FloatHolder() {
+ value = 0;
+ }
- /**
- * Constructs a new <code>FloatHolder</code> with a
- * specific initial value.
- *
- * @param f Initial float value.
- */
- public FloatHolder (float f)
- { value = f;
- }
+ /**
+ * Constructs a new <code>FloatHolder</code> with a specific initial value.
+ *
+ * @param f Initial float value.
+ */
+ public FloatHolder(float f) {
+ value = f;
+ }
}
-
-
diff --git a/pki/base/silent/src/com/netscape/pkisilent/argparser/IntHolder.java b/pki/base/silent/src/com/netscape/pkisilent/argparser/IntHolder.java
index efd6d1bf..446af9eb 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/IntHolder.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/IntHolder.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.argparser;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -18,38 +19,32 @@ package com.netscape.pkisilent.argparser;
// --- END COPYRIGHT BLOCK ---
/**
- * Wrapper class which ``holds'' an integer value,
- * enabling methods to return integer values through
- * arguments.
- */
-public class IntHolder implements java.io.Serializable
-{
- /**
+ * Wrapper class which ``holds'' an integer value, enabling methods to return
+ * integer values through arguments.
+ */
+public class IntHolder implements java.io.Serializable {
+ /**
*
*/
private static final long serialVersionUID = -5303361328570056819L;
/**
- * Value of the integer, set and examined
- * by the application as needed.
- */
- public int value;
+ * Value of the integer, set and examined by the application as needed.
+ */
+ public int value;
- /**
- * Constructs a new <code>IntHolder</code> with an initial
- * value of 0.
- */
- public IntHolder ()
- { value = 0;
- }
+ /**
+ * Constructs a new <code>IntHolder</code> with an initial value of 0.
+ */
+ public IntHolder() {
+ value = 0;
+ }
- /**
- * Constructs a new <code>IntHolder</code> with a
- * specific initial value.
- *
- * @param i Initial integer value.
- */
- public IntHolder (int i)
- { value = i;
- }
+ /**
+ * Constructs a new <code>IntHolder</code> with a specific initial value.
+ *
+ * @param i Initial integer value.
+ */
+ public IntHolder(int i) {
+ value = i;
+ }
}
-
diff --git a/pki/base/silent/src/com/netscape/pkisilent/argparser/LongHolder.java b/pki/base/silent/src/com/netscape/pkisilent/argparser/LongHolder.java
index 84752d60..37aa1c91 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/LongHolder.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/LongHolder.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.argparser;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -18,38 +19,32 @@ package com.netscape.pkisilent.argparser;
// --- END COPYRIGHT BLOCK ---
/**
- * Wrapper class which ``holds'' a long value,
- * enabling methods to return long values through
- * arguments.
- */
-public class LongHolder implements java.io.Serializable
-{
- /**
+ * Wrapper class which ``holds'' a long value, enabling methods to return long
+ * values through arguments.
+ */
+public class LongHolder implements java.io.Serializable {
+ /**
*
*/
private static final long serialVersionUID = 1559599139421340971L;
/**
- * Value of the long, set and examined
- * by the application as needed.
- */
- public long value;
+ * Value of the long, set and examined by the application as needed.
+ */
+ public long value;
- /**
- * Constructs a new <code>LongHolder</code> with an initial
- * value of 0.
- */
- public LongHolder ()
- { value = 0;
- }
+ /**
+ * Constructs a new <code>LongHolder</code> with an initial value of 0.
+ */
+ public LongHolder() {
+ value = 0;
+ }
- /**
- * Constructs a new <code>LongHolder</code> with a
- * specific initial value.
- *
- * @param l Initial long value.
- */
- public LongHolder (long l)
- { value = l;
- }
+ /**
+ * Constructs a new <code>LongHolder</code> with a specific initial value.
+ *
+ * @param l Initial long value.
+ */
+ public LongHolder(long l) {
+ value = l;
+ }
}
-
diff --git a/pki/base/silent/src/com/netscape/pkisilent/argparser/ObjectHolder.java b/pki/base/silent/src/com/netscape/pkisilent/argparser/ObjectHolder.java
index cc8361d9..edb835ee 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/ObjectHolder.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/ObjectHolder.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.argparser;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -18,37 +19,34 @@ package com.netscape.pkisilent.argparser;
// --- END COPYRIGHT BLOCK ---
/**
- * Wrapper class which ``holds'' an Object reference,
- * enabling methods to return Object references through
- * arguments.
- */
-public class ObjectHolder implements java.io.Serializable
-{
- /**
+ * Wrapper class which ``holds'' an Object reference, enabling methods to return
+ * Object references through arguments.
+ */
+public class ObjectHolder implements java.io.Serializable {
+ /**
*
*/
private static final long serialVersionUID = 1825881254530066307L;
/**
- * Value of the Object reference, set and examined
- * by the application as needed.
- */
- public Object value;
+ * Value of the Object reference, set and examined by the application as
+ * needed.
+ */
+ public Object value;
- /**
- * Constructs a new <code>ObjectHolder</code> with an initial
- * value of <code>null</code>.
- */
- public ObjectHolder ()
- { value = null;
- }
+ /**
+ * Constructs a new <code>ObjectHolder</code> with an initial value of
+ * <code>null</code>.
+ */
+ public ObjectHolder() {
+ value = null;
+ }
- /**
- * Constructs a new <code>ObjectHolder</code> with a
- * specific initial value.
- *
- * @param o Initial Object reference.
- */
- public ObjectHolder (Object o)
- { value = o;
- }
+ /**
+ * Constructs a new <code>ObjectHolder</code> with a specific initial value.
+ *
+ * @param o Initial Object reference.
+ */
+ public ObjectHolder(Object o) {
+ value = o;
+ }
}
diff --git a/pki/base/silent/src/com/netscape/pkisilent/argparser/SimpleExample.java b/pki/base/silent/src/com/netscape/pkisilent/argparser/SimpleExample.java
index 8086131b..1fc11524 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/SimpleExample.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/SimpleExample.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.argparser;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -18,39 +19,36 @@ package com.netscape.pkisilent.argparser;
// --- END COPYRIGHT BLOCK ---
/**
- * Gives a very simple example of the use of
- * {@link argparser.ArgParser ArgParser}.
+ * Gives a very simple example of the use of {@link argparser.ArgParser
+ * ArgParser}.
*/
-public class SimpleExample
-{
- /**
- * Run this to invoke command line parsing.
- */
- public static void main (String[] args)
- {
- // create holder objects for storing results ...
-
- DoubleHolder theta = new DoubleHolder();
- StringHolder fileName = new StringHolder();
- BooleanHolder debug = new BooleanHolder();
-
- // create the parser and specify the allowed options ...
-
- ArgParser parser = new ArgParser("java argparser.SimpleExample");
- parser.addOption ("-theta %f #theta value (in degrees)", theta);
- parser.addOption ("-file %s #name of the operating file", fileName);
- parser.addOption ("-debug %v #enables display of debugging info",
- debug);
-
- // and then match the arguments
-
- parser.matchAllArgs (args);
-
- // now print out the values
-
- System.out.println ("theta=" + theta.value);
- System.out.println ("fileName=" + fileName.value);
- System.out.println ("debug=" + debug.value);
- }
-}
+public class SimpleExample {
+ /**
+ * Run this to invoke command line parsing.
+ */
+ public static void main(String[] args) {
+ // create holder objects for storing results ...
+
+ DoubleHolder theta = new DoubleHolder();
+ StringHolder fileName = new StringHolder();
+ BooleanHolder debug = new BooleanHolder();
+
+ // create the parser and specify the allowed options ...
+
+ ArgParser parser = new ArgParser("java argparser.SimpleExample");
+ parser.addOption("-theta %f #theta value (in degrees)", theta);
+ parser.addOption("-file %s #name of the operating file", fileName);
+ parser.addOption("-debug %v #enables display of debugging info",
+ debug);
+ // and then match the arguments
+
+ parser.matchAllArgs(args);
+
+ // now print out the values
+
+ System.out.println("theta=" + theta.value);
+ System.out.println("fileName=" + fileName.value);
+ System.out.println("debug=" + debug.value);
+ }
+}
diff --git a/pki/base/silent/src/com/netscape/pkisilent/argparser/StringHolder.java b/pki/base/silent/src/com/netscape/pkisilent/argparser/StringHolder.java
index 9b41b6a2..ea85c7d0 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/StringHolder.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/StringHolder.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.argparser;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -18,38 +19,34 @@ package com.netscape.pkisilent.argparser;
// --- END COPYRIGHT BLOCK ---
/**
- * Wrapper class which ``holds'' a String reference,
- * enabling methods to return String references through
- * arguments.
- */
-public class StringHolder implements java.io.Serializable
-{
- /**
+ * Wrapper class which ``holds'' a String reference, enabling methods to return
+ * String references through arguments.
+ */
+public class StringHolder implements java.io.Serializable {
+ /**
*
*/
private static final long serialVersionUID = -3184348746223759310L;
/**
- * Value of the String reference, set and examined
- * by the application as needed.
- */
- public String value;
+ * Value of the String reference, set and examined by the application as
+ * needed.
+ */
+ public String value;
- /**
- * Constructs a new <code>StringHolder</code> with an
- * initial value of <code>null</code>.
- */
- public StringHolder ()
- { value = null;
- }
+ /**
+ * Constructs a new <code>StringHolder</code> with an initial value of
+ * <code>null</code>.
+ */
+ public StringHolder() {
+ value = null;
+ }
- /**
- * Constructs a new <code>StringHolder</code> with a
- * specific initial value.
- *
- * @param s Initial String reference.
- */
- public StringHolder (String s)
- { value = s;
- }
+ /**
+ * Constructs a new <code>StringHolder</code> with a specific initial value.
+ *
+ * @param s Initial String reference.
+ */
+ public StringHolder(String s) {
+ value = s;
+ }
}
-
diff --git a/pki/base/silent/src/com/netscape/pkisilent/argparser/StringScanException.java b/pki/base/silent/src/com/netscape/pkisilent/argparser/StringScanException.java
index 4b71a0f2..9d942f0d 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/StringScanException.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/StringScanException.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.argparser;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -19,40 +20,37 @@ package com.netscape.pkisilent.argparser;
import java.io.IOException;
-/**
- * Exception class used by <code>StringScanner</code> when
- * command line arguments do not parse correctly.
- *
- * @author John E. Lloyd, Winter 2001
- * @see StringScanner
- */
-class StringScanException extends IOException
-{
- /**
+/**
+ * Exception class used by <code>StringScanner</code> when command line
+ * arguments do not parse correctly.
+ *
+ * @author John E. Lloyd, Winter 2001
+ * @see StringScanner
+ */
+class StringScanException extends IOException {
+ /**
*
*/
private static final long serialVersionUID = 4923445904507805754L;
int failIdx;
- /**
- * Creates a new StringScanException with the given message.
- *
- * @param msg Error message
- * @see StringScanner
- */
+ /**
+ * Creates a new StringScanException with the given message.
+ *
+ * @param msg Error message
+ * @see StringScanner
+ */
- public StringScanException (String msg)
- { super (msg);
- }
+ public StringScanException(String msg) {
+ super(msg);
+ }
- public StringScanException (int idx, String msg)
- {
- super (msg);
- failIdx = idx;
- }
+ public StringScanException(int idx, String msg) {
+ super(msg);
+ failIdx = idx;
+ }
- public int getFailIndex()
- {
- return failIdx;
- }
+ public int getFailIndex() {
+ return failIdx;
+ }
}
diff --git a/pki/base/silent/src/com/netscape/pkisilent/argparser/StringScanner.java b/pki/base/silent/src/com/netscape/pkisilent/argparser/StringScanner.java
index 6153f180..56cc2a26 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/StringScanner.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/StringScanner.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.argparser;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -18,626 +19,549 @@ package com.netscape.pkisilent.argparser;
// --- END COPYRIGHT BLOCK ---
/**
- * Copyright John E. Lloyd, 2004. All rights reserved. Permission to use,
- * copy, modify and redistribute is granted, provided that this copyright
- * notice is retained and the author is given credit whenever appropriate.
- *
- * This software is distributed "as is", without any warranty, including
- * any implied warranty of merchantability or fitness for a particular
- * use. The author assumes no responsibility for, and shall not be liable
- * for, any special, indirect, or consequential damages, or any damages
- * whatsoever, arising out of or in connection with the use of this
- * software.
- */
-
-class StringScanner
-{
- private char[] buf;
- private int idx;
- private int len;
- private String stringDelimiters = "";
-
- public StringScanner (String s)
- {
- buf = new char[s.length()+1];
- s.getChars (0, s.length(), buf, 0);
- len = s.length();
- buf[len] = 0;
- idx = 0;
- }
-
- public int getIndex()
- { return idx;
- }
-
- public void setIndex(int i)
- { if (i < 0)
- { idx = 0;
- }
- else if (i > len)
- { idx = len;
- }
- else
- { idx = i;
- }
- }
-
- public void setStringDelimiters (String s)
- { stringDelimiters = s;
- }
-
- public String getStringDelimiters()
- { return stringDelimiters;
- }
-
- public char scanChar ()
- throws StringScanException
- {
- int idxSave = idx;
- skipWhiteSpace();
- try
- { if (buf[idx] == '\'')
- { return scanQuotedChar();
- }
- else
- { return scanUnquotedChar();
- }
- }
- catch (StringScanException e)
- { idx = idxSave;
- throw e;
- }
- }
-
- public char scanQuotedChar ()
- throws StringScanException
- {
- StringScanException exception = null;
- char retval = 0;
- int idxSave = idx;
-
- skipWhiteSpace();
- if (idx == len)
- { exception = new StringScanException (idx, "end of input");
- }
- else if (buf[idx++] == '\'')
- { try
- { retval = scanUnquotedChar();
- }
- catch (StringScanException e)
- { exception = e;
- }
- if (exception==null)
- { if (idx==len)
- { exception = new StringScanException
- (idx, "end of input");
- }
- else if (buf[idx++] != '\'')
- { exception = new StringScanException
- (idx-1, "unclosed quoted character");
- }
- }
- }
- else
- { exception = new StringScanException
- (idx-1, "uninitialized quoted character");
- }
- if (exception!=null)
- { idx = idxSave;
- throw exception;
- }
- return retval;
- }
-
- public char scanUnquotedChar ()
- throws StringScanException
- {
- StringScanException exception = null;
- char c, retval = 0;
- int idxSave = idx;
-
- if (idx == len)
- { exception = new StringScanException (idx, "end of input");
- }
- else if ((c = buf[idx++]) == '\\')
- { if (idx == len)
- { exception = new StringScanException (idx, "end of input");
- }
- else
- {
- c = buf[idx++];
- if (c == '"')
- { retval = '"';
- }
- else if (c == '\'')
- { retval = '\'';
- }
- else if (c == '\\')
- { retval = '\\';
- }
- else if (c == 'n')
- { retval = '\n';
- }
- else if (c == 't')
- { retval = '\t';
- }
- else if (c == 'b')
- { retval = '\b';
- }
- else if (c == 'r')
- { retval = '\r';
- }
- else if (c == 'f')
- { retval = '\f';
- }
- else if ('0' <= c && c < '8')
- { int v = c - '0';
- for (int j=0; j<2; j++)
- { if (idx==len)
- { break;
- }
- c = buf[idx];
- if ('0' <= c && c < '8' && (v*8 + (c-'0')) <= 255)
- { v = v*8 + (c-'0');
- idx++;
- }
- else
- { break;
- }
- }
- retval = (char)v;
- }
- else
- { exception = new StringScanException
- (idx-1, "illegal escape character '" + c + "'");
- }
- }
- }
- else
- { retval = c;
- }
- if (exception!=null)
- { idx = idxSave;
- throw exception;
- }
- return retval;
- }
-
- public String scanQuotedString ()
- throws StringScanException
- {
- StringScanException exception = null;
- StringBuffer sbuf = new StringBuffer(len);
- char c;
- int idxSave = idx;
-
- skipWhiteSpace();
- if (idx == len)
- { exception = new StringScanException (idx, "end of input");
- }
- else if ((c=buf[idx++]) == '"')
- { while (idx<len && (c=buf[idx]) != '"' && c != '\n')
- { if (c == '\\')
- { try
- { c = scanUnquotedChar();
- }
- catch (StringScanException e)
- { exception = e;
- break;
- }
- }
- else
- { idx++;
- }
- sbuf.append (c);
- }
- if (exception == null && idx>=len)
- { exception = new StringScanException (len, "end of input");
- }
- else if (exception == null && c == '\n')
- { exception = new StringScanException
- (idx, "unclosed quoted string");
- }
- else
- { idx++;
- }
- }
- else
- { exception = new StringScanException (idx-1,
-"quoted string must start with \"");
- }
- if (exception != null)
- { idx = idxSave;
- throw exception;
- }
- return sbuf.toString();
- }
-
- public String scanNonWhiteSpaceString()
- throws StringScanException
- {
- StringBuffer sbuf = new StringBuffer(len);
- int idxSave = idx;
- char c;
-
- skipWhiteSpace();
- if (idx == len)
- { StringScanException e = new StringScanException (
- idx, "end of input");
- idx = idxSave;
- throw e;
- }
- else
- { c = buf[idx++];
- while (idx<len && !Character.isWhitespace(c)
- && stringDelimiters.indexOf(c) == -1)
- { sbuf.append(c);
- c = buf[idx++];
- }
- if (Character.isWhitespace(c) ||
- stringDelimiters.indexOf(c) != -1)
- { idx--;
- }
- else
- { sbuf.append(c);
- }
- }
- return sbuf.toString();
- }
-
- public String scanString ()
- throws StringScanException
- {
- int idxSave = idx;
- skipWhiteSpace();
- try
- { if (buf[idx] == '"')
- { return scanQuotedString();
- }
- else
- { return scanNonWhiteSpaceString();
- }
- }
- catch (StringScanException e)
- { idx = idxSave;
- throw e;
- }
- }
-
- public String getString ()
- throws StringScanException
- {
- StringBuffer sbuf = new StringBuffer(len);
- while (idx < len)
- { sbuf.append (buf[idx++]);
- }
- return sbuf.toString();
- }
-
- public long scanInt ()
- throws StringScanException
- {
- int idxSave = idx;
- char c;
- int sign = 1;
-
- skipWhiteSpace();
- if ((c=buf[idx]) == '-' || c == '+')
- { sign = (c == '-' ? -1 : 1);
- idx++;
- }
- try
- { if (idx==len)
- { throw new StringScanException (len, "end of input");
- }
- else if ((c=buf[idx]) == '0')
- { if ((c=buf[idx+1]) == 'x' || c == 'X')
- { idx += 2;
- return sign*scanInt (16, false);
- }
- else
- { return sign*scanInt (8, false);
- }
- }
- else
- { return sign*scanInt (10, false);
- }
- }
- catch (StringScanException e)
- { idx = idxSave;
- throw e;
- }
- }
-
- public long scanInt (int radix)
- throws StringScanException
- {
- return scanInt (radix, /*skipWhite=*/true);
- }
-
- private String baseDesc (int radix)
- {
- switch (radix)
- { case 10:
- { return "decimal";
- }
- case 8:
- { return "octal";
- }
- case 16:
- { return "hex";
- }
- default:
- { return "base " + radix;
- }
- }
- }
-
- public long scanInt (int radix, boolean skipWhite)
- throws StringScanException
- {
- StringScanException exception = null;
- int charval, idxSave = idx;
- char c;
- long val = 0;
- boolean negate = false;
-
- if (skipWhite)
- { skipWhiteSpace();
- }
- if ((c=buf[idx]) == '-' || c == '+')
- { negate = (c == '-');
- idx++;
- }
- if (idx >= len)
- { exception = new StringScanException (len, "end of input");
- }
- else if ((charval=Character.digit(buf[idx++],radix)) == -1)
- { exception = new StringScanException
- (idx-1, "malformed " + baseDesc(radix) + " integer");
- }
- else
- { val = charval;
- while ((charval=Character.digit(buf[idx],radix)) != -1)
- { val = val*radix + charval;
- idx++;
- }
- if (Character.isLetter(c=buf[idx]) ||
- Character.isDigit(c) || c == '_')
- { exception = new StringScanException
- (idx, "malformed " + baseDesc(radix) + " integer");
- }
- }
- if (exception != null)
- { idx = idxSave;
- throw exception;
- }
- return negate ? -val : val;
- }
-
- public double scanDouble ()
- throws StringScanException
- {
- StringScanException exception = null;
- int idxSave = idx;
- char c;
- // parse [-][0-9]*[.][0-9]*[eE][-][0-9]*
- boolean hasDigits = false;
- boolean signed;
- double value = 0;
-
- skipWhiteSpace();
- if (idx == len)
- { exception = new StringScanException ("end of input");
- }
- else
- {
- if ((c=buf[idx]) == '-' || c == '+')
- { signed = true;
- idx++;
- }
- if (matchDigits())
- { hasDigits = true;
- }
- if (buf[idx] == '.')
- { idx++;
- }
- if (!hasDigits && (buf[idx] < '0' || buf[idx] > '9'))
- { if (idx==len)
- { exception = new StringScanException (idx, "end of input");
- }
- else
- { exception = new StringScanException (
- idx, "malformed floating number: no digits");
- }
- }
- else
- { matchDigits();
-
- if ((c=buf[idx]) == 'e' || c == 'E')
- { idx++;
- if ((c=buf[idx]) == '-' || c == '+')
- { signed = true;
- idx++;
- }
- if (buf[idx] < '0' || buf[idx] > '9')
- { if (idx==len)
- { exception = new StringScanException(
- idx, "end of input");
- }
- else
- { exception = new StringScanException (idx,
-"malformed floating number: no digits in exponent");
- }
- }
- else
- { matchDigits();
- }
- }
- }
- }
- if (exception == null)
- {
-// if (Character.isLetterOrDigit(c=buf[idx]) || c == '_')
-// { exception = new StringScanException (idx,
-//"malformed floating number");
-// }
-// else
- {
- try
- { value = Double.parseDouble(new String(buf, idxSave,
- idx-idxSave));
- }
- catch (NumberFormatException e)
- { exception = new StringScanException (
- idx, "malformed floating number");
- }
- }
- }
- if (exception != null)
- { idx = idxSave;
- throw exception;
- }
- return value;
- }
-
- public boolean scanBoolean ()
- throws StringScanException
- {
- StringScanException exception = null;
- int idxSave = idx;
- String testStr = "false";
- boolean testval = false;
- char c;
-
- skipWhiteSpace();
- if (buf[idx] == 't')
- { testStr = "true";
- testval = true;
- }
- else
- { testval = false;
- }
- int i = 0;
- for (i=0; i<testStr.length(); i++)
- { if (testStr.charAt(i) != buf[idx])
- { if (idx==len)
- { exception = new StringScanException (idx, "end of input");
- }
- break;
- }
- idx++;
- }
- if (exception==null)
- { if (i<testStr.length() ||
- Character.isLetterOrDigit(c=buf[idx]) || c == '_')
- { exception = new StringScanException (idx, "illegal boolean");
- }
- }
- if (exception != null)
- { idx = idxSave;
- throw exception;
- }
- return testval;
- }
-
- public boolean matchString (String s)
- {
- int k = idx;
- for (int i=0; i<s.length(); i++)
- { if (k >= len || s.charAt(i) != buf[k++])
- { return false;
- }
- }
- idx = k;
- return true;
- }
-
- public boolean matchDigits ()
- {
- int k = idx;
- char c;
-
- while ((c=buf[k]) >= '0' && c <= '9')
- { k++;
- }
- if (k > idx)
- { idx = k;
- return true;
- }
- else
- { return false;
- }
- }
-
- public void skipWhiteSpace()
- {
- while (Character.isWhitespace(buf[idx]))
- { idx++;
- }
- }
-
- public boolean atEnd()
- {
- return idx == len;
- }
-
- public boolean atBeginning()
- {
- return idx == 0;
- }
-
- public void ungetc()
- {
- if (idx > 0)
- { idx--;
- }
- }
-
- public char getc()
- {
- char c = buf[idx];
- if (idx < len)
- { idx++;
- }
- return c;
- }
-
- public char peekc()
- {
- return buf[idx];
- }
-
- public String substring (int i0, int i1)
- {
- if (i0 < 0)
- { i0 = 0;
- }
- else if (i0 >= len)
- { i0= len-1;
- }
- if (i1 < 0)
- { i1 = 0;
- }
- else if (i1 > len)
- { i1= len;
- }
- if (i1 <= i0)
- { return "";
- }
- return new String (buf, i0, i1-i0);
- }
-
- public String substring (int i0)
- {
- if (i0 < 0)
- { i0 = 0;
- }
- if (i0 >= len)
- { return "";
- }
- else
- { return new String (buf, i0, len-i0);
- }
- }
+ * Copyright John E. Lloyd, 2004. All rights reserved. Permission to use, copy,
+ * modify and redistribute is granted, provided that this copyright notice is
+ * retained and the author is given credit whenever appropriate.
+ *
+ * This software is distributed "as is", without any warranty, including any
+ * implied warranty of merchantability or fitness for a particular use. The
+ * author assumes no responsibility for, and shall not be liable for, any
+ * special, indirect, or consequential damages, or any damages whatsoever,
+ * arising out of or in connection with the use of this software.
+ */
+
+class StringScanner {
+ private char[] buf;
+ private int idx;
+ private int len;
+ private String stringDelimiters = "";
+
+ public StringScanner(String s) {
+ buf = new char[s.length() + 1];
+ s.getChars(0, s.length(), buf, 0);
+ len = s.length();
+ buf[len] = 0;
+ idx = 0;
+ }
+
+ public int getIndex() {
+ return idx;
+ }
+
+ public void setIndex(int i) {
+ if (i < 0) {
+ idx = 0;
+ } else if (i > len) {
+ idx = len;
+ } else {
+ idx = i;
+ }
+ }
+
+ public void setStringDelimiters(String s) {
+ stringDelimiters = s;
+ }
+
+ public String getStringDelimiters() {
+ return stringDelimiters;
+ }
+
+ public char scanChar()
+ throws StringScanException {
+ int idxSave = idx;
+ skipWhiteSpace();
+ try {
+ if (buf[idx] == '\'') {
+ return scanQuotedChar();
+ } else {
+ return scanUnquotedChar();
+ }
+ } catch (StringScanException e) {
+ idx = idxSave;
+ throw e;
+ }
+ }
+
+ public char scanQuotedChar()
+ throws StringScanException {
+ StringScanException exception = null;
+ char retval = 0;
+ int idxSave = idx;
+
+ skipWhiteSpace();
+ if (idx == len) {
+ exception = new StringScanException(idx, "end of input");
+ } else if (buf[idx++] == '\'') {
+ try {
+ retval = scanUnquotedChar();
+ } catch (StringScanException e) {
+ exception = e;
+ }
+ if (exception == null) {
+ if (idx == len) {
+ exception = new StringScanException
+ (idx, "end of input");
+ } else if (buf[idx++] != '\'') {
+ exception = new StringScanException
+ (idx - 1, "unclosed quoted character");
+ }
+ }
+ } else {
+ exception = new StringScanException
+ (idx - 1, "uninitialized quoted character");
+ }
+ if (exception != null) {
+ idx = idxSave;
+ throw exception;
+ }
+ return retval;
+ }
+
+ public char scanUnquotedChar()
+ throws StringScanException {
+ StringScanException exception = null;
+ char c, retval = 0;
+ int idxSave = idx;
+
+ if (idx == len) {
+ exception = new StringScanException(idx, "end of input");
+ } else if ((c = buf[idx++]) == '\\') {
+ if (idx == len) {
+ exception = new StringScanException(idx, "end of input");
+ } else {
+ c = buf[idx++];
+ if (c == '"') {
+ retval = '"';
+ } else if (c == '\'') {
+ retval = '\'';
+ } else if (c == '\\') {
+ retval = '\\';
+ } else if (c == 'n') {
+ retval = '\n';
+ } else if (c == 't') {
+ retval = '\t';
+ } else if (c == 'b') {
+ retval = '\b';
+ } else if (c == 'r') {
+ retval = '\r';
+ } else if (c == 'f') {
+ retval = '\f';
+ } else if ('0' <= c && c < '8') {
+ int v = c - '0';
+ for (int j = 0; j < 2; j++) {
+ if (idx == len) {
+ break;
+ }
+ c = buf[idx];
+ if ('0' <= c && c < '8' && (v * 8 + (c - '0')) <= 255) {
+ v = v * 8 + (c - '0');
+ idx++;
+ } else {
+ break;
+ }
+ }
+ retval = (char) v;
+ } else {
+ exception = new StringScanException
+ (idx - 1, "illegal escape character '" + c + "'");
+ }
+ }
+ } else {
+ retval = c;
+ }
+ if (exception != null) {
+ idx = idxSave;
+ throw exception;
+ }
+ return retval;
+ }
+
+ public String scanQuotedString()
+ throws StringScanException {
+ StringScanException exception = null;
+ StringBuffer sbuf = new StringBuffer(len);
+ char c;
+ int idxSave = idx;
+
+ skipWhiteSpace();
+ if (idx == len) {
+ exception = new StringScanException(idx, "end of input");
+ } else if ((c = buf[idx++]) == '"') {
+ while (idx < len && (c = buf[idx]) != '"' && c != '\n') {
+ if (c == '\\') {
+ try {
+ c = scanUnquotedChar();
+ } catch (StringScanException e) {
+ exception = e;
+ break;
+ }
+ } else {
+ idx++;
+ }
+ sbuf.append(c);
+ }
+ if (exception == null && idx >= len) {
+ exception = new StringScanException(len, "end of input");
+ } else if (exception == null && c == '\n') {
+ exception = new StringScanException
+ (idx, "unclosed quoted string");
+ } else {
+ idx++;
+ }
+ } else {
+ exception = new StringScanException(idx - 1,
+ "quoted string must start with \"");
+ }
+ if (exception != null) {
+ idx = idxSave;
+ throw exception;
+ }
+ return sbuf.toString();
+ }
+
+ public String scanNonWhiteSpaceString()
+ throws StringScanException {
+ StringBuffer sbuf = new StringBuffer(len);
+ int idxSave = idx;
+ char c;
+
+ skipWhiteSpace();
+ if (idx == len) {
+ StringScanException e = new StringScanException(
+ idx, "end of input");
+ idx = idxSave;
+ throw e;
+ } else {
+ c = buf[idx++];
+ while (idx < len && !Character.isWhitespace(c)
+ && stringDelimiters.indexOf(c) == -1) {
+ sbuf.append(c);
+ c = buf[idx++];
+ }
+ if (Character.isWhitespace(c) ||
+ stringDelimiters.indexOf(c) != -1) {
+ idx--;
+ } else {
+ sbuf.append(c);
+ }
+ }
+ return sbuf.toString();
+ }
+
+ public String scanString()
+ throws StringScanException {
+ int idxSave = idx;
+ skipWhiteSpace();
+ try {
+ if (buf[idx] == '"') {
+ return scanQuotedString();
+ } else {
+ return scanNonWhiteSpaceString();
+ }
+ } catch (StringScanException e) {
+ idx = idxSave;
+ throw e;
+ }
+ }
+
+ public String getString()
+ throws StringScanException {
+ StringBuffer sbuf = new StringBuffer(len);
+ while (idx < len) {
+ sbuf.append(buf[idx++]);
+ }
+ return sbuf.toString();
+ }
+
+ public long scanInt()
+ throws StringScanException {
+ int idxSave = idx;
+ char c;
+ int sign = 1;
+
+ skipWhiteSpace();
+ if ((c = buf[idx]) == '-' || c == '+') {
+ sign = (c == '-' ? -1 : 1);
+ idx++;
+ }
+ try {
+ if (idx == len) {
+ throw new StringScanException(len, "end of input");
+ } else if ((c = buf[idx]) == '0') {
+ if ((c = buf[idx + 1]) == 'x' || c == 'X') {
+ idx += 2;
+ return sign * scanInt(16, false);
+ } else {
+ return sign * scanInt(8, false);
+ }
+ } else {
+ return sign * scanInt(10, false);
+ }
+ } catch (StringScanException e) {
+ idx = idxSave;
+ throw e;
+ }
+ }
+
+ public long scanInt(int radix)
+ throws StringScanException {
+ return scanInt(radix, /* skipWhite= */true);
+ }
+
+ private String baseDesc(int radix) {
+ switch (radix) {
+ case 10: {
+ return "decimal";
+ }
+ case 8: {
+ return "octal";
+ }
+ case 16: {
+ return "hex";
+ }
+ default: {
+ return "base " + radix;
+ }
+ }
+ }
+
+ public long scanInt(int radix, boolean skipWhite)
+ throws StringScanException {
+ StringScanException exception = null;
+ int charval, idxSave = idx;
+ char c;
+ long val = 0;
+ boolean negate = false;
+
+ if (skipWhite) {
+ skipWhiteSpace();
+ }
+ if ((c = buf[idx]) == '-' || c == '+') {
+ negate = (c == '-');
+ idx++;
+ }
+ if (idx >= len) {
+ exception = new StringScanException(len, "end of input");
+ } else if ((charval = Character.digit(buf[idx++], radix)) == -1) {
+ exception = new StringScanException
+ (idx - 1, "malformed " + baseDesc(radix) + " integer");
+ } else {
+ val = charval;
+ while ((charval = Character.digit(buf[idx], radix)) != -1) {
+ val = val * radix + charval;
+ idx++;
+ }
+ if (Character.isLetter(c = buf[idx]) ||
+ Character.isDigit(c) || c == '_') {
+ exception = new StringScanException
+ (idx, "malformed " + baseDesc(radix) + " integer");
+ }
+ }
+ if (exception != null) {
+ idx = idxSave;
+ throw exception;
+ }
+ return negate ? -val : val;
+ }
+
+ public double scanDouble()
+ throws StringScanException {
+ StringScanException exception = null;
+ int idxSave = idx;
+ char c;
+ // parse [-][0-9]*[.][0-9]*[eE][-][0-9]*
+ boolean hasDigits = false;
+ boolean signed;
+ double value = 0;
+
+ skipWhiteSpace();
+ if (idx == len) {
+ exception = new StringScanException("end of input");
+ } else {
+ if ((c = buf[idx]) == '-' || c == '+') {
+ signed = true;
+ idx++;
+ }
+ if (matchDigits()) {
+ hasDigits = true;
+ }
+ if (buf[idx] == '.') {
+ idx++;
+ }
+ if (!hasDigits && (buf[idx] < '0' || buf[idx] > '9')) {
+ if (idx == len) {
+ exception = new StringScanException(idx, "end of input");
+ } else {
+ exception = new StringScanException(
+ idx, "malformed floating number: no digits");
+ }
+ } else {
+ matchDigits();
+
+ if ((c = buf[idx]) == 'e' || c == 'E') {
+ idx++;
+ if ((c = buf[idx]) == '-' || c == '+') {
+ signed = true;
+ idx++;
+ }
+ if (buf[idx] < '0' || buf[idx] > '9') {
+ if (idx == len) {
+ exception = new StringScanException(
+ idx, "end of input");
+ } else {
+ exception = new StringScanException(idx,
+ "malformed floating number: no digits in exponent");
+ }
+ } else {
+ matchDigits();
+ }
+ }
+ }
+ }
+ if (exception == null) {
+ // if (Character.isLetterOrDigit(c=buf[idx]) || c == '_')
+ // { exception = new StringScanException (idx,
+ // "malformed floating number");
+ // }
+ // else
+ {
+ try {
+ value = Double.parseDouble(new String(buf, idxSave,
+ idx - idxSave));
+ } catch (NumberFormatException e) {
+ exception = new StringScanException(
+ idx, "malformed floating number");
+ }
+ }
+ }
+ if (exception != null) {
+ idx = idxSave;
+ throw exception;
+ }
+ return value;
+ }
+
+ public boolean scanBoolean()
+ throws StringScanException {
+ StringScanException exception = null;
+ int idxSave = idx;
+ String testStr = "false";
+ boolean testval = false;
+ char c;
+
+ skipWhiteSpace();
+ if (buf[idx] == 't') {
+ testStr = "true";
+ testval = true;
+ } else {
+ testval = false;
+ }
+ int i = 0;
+ for (i = 0; i < testStr.length(); i++) {
+ if (testStr.charAt(i) != buf[idx]) {
+ if (idx == len) {
+ exception = new StringScanException(idx, "end of input");
+ }
+ break;
+ }
+ idx++;
+ }
+ if (exception == null) {
+ if (i < testStr.length() ||
+ Character.isLetterOrDigit(c = buf[idx]) || c == '_') {
+ exception = new StringScanException(idx, "illegal boolean");
+ }
+ }
+ if (exception != null) {
+ idx = idxSave;
+ throw exception;
+ }
+ return testval;
+ }
+
+ public boolean matchString(String s) {
+ int k = idx;
+ for (int i = 0; i < s.length(); i++) {
+ if (k >= len || s.charAt(i) != buf[k++]) {
+ return false;
+ }
+ }
+ idx = k;
+ return true;
+ }
+
+ public boolean matchDigits() {
+ int k = idx;
+ char c;
+
+ while ((c = buf[k]) >= '0' && c <= '9') {
+ k++;
+ }
+ if (k > idx) {
+ idx = k;
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public void skipWhiteSpace() {
+ while (Character.isWhitespace(buf[idx])) {
+ idx++;
+ }
+ }
+
+ public boolean atEnd() {
+ return idx == len;
+ }
+
+ public boolean atBeginning() {
+ return idx == 0;
+ }
+
+ public void ungetc() {
+ if (idx > 0) {
+ idx--;
+ }
+ }
+
+ public char getc() {
+ char c = buf[idx];
+ if (idx < len) {
+ idx++;
+ }
+ return c;
+ }
+
+ public char peekc() {
+ return buf[idx];
+ }
+
+ public String substring(int i0, int i1) {
+ if (i0 < 0) {
+ i0 = 0;
+ } else if (i0 >= len) {
+ i0 = len - 1;
+ }
+ if (i1 < 0) {
+ i1 = 0;
+ } else if (i1 > len) {
+ i1 = len;
+ }
+ if (i1 <= i0) {
+ return "";
+ }
+ return new String(buf, i0, i1 - i0);
+ }
+
+ public String substring(int i0) {
+ if (i0 < 0) {
+ i0 = 0;
+ }
+ if (i0 >= len) {
+ return "";
+ } else {
+ return new String(buf, i0, len - i0);
+ }
+ }
}
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/AutoInstaller.java b/pki/base/silent/src/com/netscape/pkisilent/common/AutoInstaller.java
index 925e04dc..41affca0 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/AutoInstaller.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/AutoInstaller.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.common;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -26,20 +27,17 @@ import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Properties;
-
-
/**
- * CMS Test Framework.
- * Use this class to Configure a CA, RA,DRM,OCSP and SubCA subsystem.
- * This simulartes the installation wizard functions and helps to configure a CMS subsystem.
+ * CMS Test Framework. Use this class to Configure a CA, RA,DRM,OCSP and SubCA
+ * subsystem. This simulartes the installation wizard functions and helps to
+ * configure a CMS subsystem.
*/
-
public class AutoInstaller {
private static Properties props = null;
- // Admin Server and InternalDB varialbes
+ // Admin Server and InternalDB varialbes
private String adminDomain, adminID, adminPWD, adminPort, machineName, host, serverID, instanceID, serverRoot, sieURL, dbConnPort, dbConnHost, dbInstanceName, dbPassword, dbLDAPauthDN, dbmode, ldapServerDB;
// CMS Subsystem info
@@ -49,15 +47,15 @@ public class AutoInstaller {
// CA info
private String caHostname, caPortnum, caTimeout, caEEPort, enpropfile, cdir, tokenpwd, CAadminId, CAadminPwd, CAcertnickname, caAgentPortnum, cloneInstanceId;
- // Program variables
+ // Program variables
private int i;
private String configURL, deamonURL, certInstID;
private String inputLine;
private boolean st = false;
-
+
private String postQuery = null;
private String propFileName;
- private StringBuffer spage = new StringBuffer();
+ private StringBuffer spage = new StringBuffer();
// 4.5 server String CERTtokenName="Internal Key Storage Token";
private String CERTtokenName = "internal";
@@ -68,9 +66,10 @@ public class AutoInstaller {
private boolean subca = false;
- // / Constructors
+ // / Constructors
- public AutoInstaller() {}
+ public AutoInstaller() {
+ }
/**
* Constructor . Takes parameter Server Root .
@@ -81,7 +80,9 @@ public class AutoInstaller {
// Set InternalDBVInfo
/**
- * Set Internal Database Information . Takes parameters internaldatabase hostname, internaldatabase port, internaldatabase name, internaldatabase binddn, internaldatabase password
+ * Set Internal Database Information . Takes parameters internaldatabase
+ * hostname, internaldatabase port, internaldatabase name, internaldatabase
+ * binddn, internaldatabase password
*/
public void setInternalDBInfo(String dbh, String dbp, String dbname, String dbdn, String dbpswd) {
@@ -94,7 +95,7 @@ public class AutoInstaller {
ldapServerDB = "userRoot";
}
- // Create Password file
+ // Create Password file
private boolean CreatePasswordFile() {
String s = "internal: " + SingleSignOnPWD;
OutputStream f0 = null;
@@ -109,7 +110,8 @@ public class AutoInstaller {
} catch (Exception e) {
System.out.println("exception " + e.getMessage());
try {
- if (f0 != null) f0.close();
+ if (f0 != null)
+ f0.close();
} catch (IOException ioe) {
System.out.println("IO Exception: " + ioe.getMessage());
}
@@ -137,26 +139,28 @@ public class AutoInstaller {
f2.write(b);
f1.close();
- f2.close();
+ f2.close();
return true;
} catch (Exception e) {
System.out.println("exception " + e.getMessage());
try {
- if (f1 != null) f1.close();
+ if (f1 != null)
+ f1.close();
} catch (IOException ioe) {
System.out.println("IO Exception: " + ioe.getMessage());
}
try {
- if (f2 != null) f2.close();
+ if (f2 != null)
+ f2.close();
} catch (IOException ioe) {
System.out.println("IO Exception: " + ioe.getMessage());
}
return false;
}
-
+
}
- // Get RaSigning Cert
+ // Get RaSigning Cert
public String getRASigningCert() {
return raSigningCert;
@@ -170,7 +174,8 @@ public class AutoInstaller {
// Set Admin Server Info
/**
- * Set Admin Server Information . Takes parameters : hostname, adminserver portnumber , adminId , adminPassword
+ * Set Admin Server Information . Takes parameters : hostname, adminserver
+ * portnumber , adminId , adminPassword
*/
public void setAdminInfo(String h, String p, String adDN, String id, String adpwd) {
adminDomain = adDN;
@@ -181,9 +186,10 @@ public class AutoInstaller {
}
- // Set CA Server Info
+ // Set CA Server Info
/**
- * Set CA server Information . Takes parametrers :CAhostname, CAEEPORT, CAAGENTPORT , CAAdminUID, CAAdminPassword
+ * Set CA server Information . Takes parametrers :CAhostname, CAEEPORT,
+ * CAAGENTPORT , CAAdminUID, CAAdminPassword
*/
public void setCAInfo(String cah, String caeep, String caagp, String caaduid, String caadpwd) {
@@ -199,8 +205,9 @@ public class AutoInstaller {
// Set ClientDB Info;
/**
- * Sets Client Database information . Takes paramters : certdbdir, certdbpasswd, certnickanme
- */
+ * Sets Client Database information . Takes paramters : certdbdir,
+ * certdbpasswd, certnickanme
+ */
public void setClientDBInfo(String cd, String pwd, String nickname) {
@@ -220,10 +227,14 @@ public class AutoInstaller {
}
- // Set Subsystem Information for Configuring
+ // Set Subsystem Information for Configuring
/**
- * Takes parameters - sID- ServerID e.x cert1, sRoot- ServerRootK kT- keyType "RSA/DSA" , kL - keylength (1024.2048) , cVD- certificate validity dates e.g 365 for 1 year, sdn - subsystems dn, sAdp - subsystem's Admin port, sAgp - subsystems's Agentport,seSP- subsystem's ee SSL port , sep- Subsystems ee port.
+ * Takes parameters - sID- ServerID e.x cert1, sRoot- ServerRootK kT-
+ * keyType "RSA/DSA" , kL - keylength (1024.2048) , cVD- certificate
+ * validity dates e.g 365 for 1 year, sdn - subsystems dn, sAdp -
+ * subsystem's Admin port, sAgp - subsystems's Agentport,seSP- subsystem's
+ * ee SSL port , sep- Subsystems ee port.
*/
public void setSubSystemInfo(String sID, String sRoot, String kT, String kL, String hT, String cVD, String sdn, String sAdP, String sAgP, String seSP, String seP) {
@@ -243,10 +254,11 @@ public class AutoInstaller {
caOComponent = "test";
}
- // // Configure CMS Subsystems
+ // // Configure CMS Subsystems
/**
- * Confiures a CA Subsystem .Takes parameter : adminSubjectDN, adminUID, AdminPasswd, SingleSignonPasswd
+ * Confiures a CA Subsystem .Takes parameter : adminSubjectDN, adminUID,
+ * AdminPasswd, SingleSignonPasswd
*/
public boolean ConfigureCA(String adn, String aduid, String adp, String ssonpwd) {
certAdminName = adn;
@@ -286,7 +298,7 @@ public class AutoInstaller {
certAdminUid = aduid;
certAdminPWD = adp;
SingleSignOnPWD = ssonpwd;
- signingCert = "raSigningCert";
+ signingCert = "raSigningCert";
certType = signingCert;
subsystems = "tks";
ra = "false";
@@ -314,7 +326,7 @@ public class AutoInstaller {
}
private boolean ConfTKS() {
- // Start Configuring
+ // Start Configuring
// Step 1. Start Deamon
@@ -346,14 +358,14 @@ public class AutoInstaller {
return false;
}
- // Step 3. Create Admin Values
+ // Step 3. Create Admin Values
if (!createAdminValues()) {
System.out.println(
"Configuring Cert Instance: error configuring admin values ");
return false;
}
- // Step 4. SubSystems
+ // Step 4. SubSystems
if (!selectSubSystem()) {
System.out.println(
@@ -395,7 +407,7 @@ public class AutoInstaller {
return false;
}
- // Step 9 : CheckDN
+ // Step 9 : CheckDN
if (!checkDN()) {
System.out.println(
"Configuring Cert Instance: error checking deamon");
@@ -409,24 +421,24 @@ public class AutoInstaller {
return false;
}
- // After creating ssl cert
+ // After creating ssl cert
tokenPWD = mtokenPWD;
- // Step 11
+ // Step 11
if (!singleSignON()) {
System.out.println(
"Configuring Cert Instance: error setting up singlesignon");
return false;
}
- // Step 11
+ // Step 11
if (!doMisc()) {
System.out.println(
"Configuring Cert Instance: error setting up miscell");
return false;
}
- // Step 12
+ // Step 12
if (!exitDeamon()) {
System.out.println(
"Configuring Cert Instance: Unable to exit deamon");
@@ -437,10 +449,10 @@ public class AutoInstaller {
}
/**
- * Confiures a RA Subsystem .Takes parameter : adminSubjectDN, adminUID, AdminPasswd, SingleSignonPasswd
+ * Confiures a RA Subsystem .Takes parameter : adminSubjectDN, adminUID,
+ * AdminPasswd, SingleSignonPasswd
*/
-
public boolean ConfigureRA(String adn, String aduid, String adp, String ssonpwd) {
certAdminName = adn;
certAdminUid = aduid;
@@ -474,10 +486,10 @@ public class AutoInstaller {
}
/**
- * Confiures a OCSP Subsystem .Takes parameter : adminSubjectDN, adminUID, AdminPasswd, SingleSignonPasswd
+ * Confiures a OCSP Subsystem .Takes parameter : adminSubjectDN, adminUID,
+ * AdminPasswd, SingleSignonPasswd
*/
-
public boolean ConfigureOCSP(String adn, String aduid, String adp, String ssonpwd) {
certAdminName = adn;
certAdminUid = aduid;
@@ -510,10 +522,10 @@ public class AutoInstaller {
}
/**
- * Confiures a KRA Subsystem .Takes parameter : adminSubjectDN, adminUID, AdminPasswd, SingleSignonPasswd
+ * Confiures a KRA Subsystem .Takes parameter : adminSubjectDN, adminUID,
+ * AdminPasswd, SingleSignonPasswd
*/
-
public boolean ConfigureKRA(String adn, String aduid, String adp, String ssonpwd) {
certAdminName = adn;
certAdminUid = aduid;
@@ -545,10 +557,10 @@ public class AutoInstaller {
}
/**
- * Confiures a SubCA Subsystem .Takes parameter : adminSubjectDN, adminUID, AdminPasswd, SingleSignonPasswd
+ * Confiures a SubCA Subsystem .Takes parameter : adminSubjectDN, adminUID,
+ * AdminPasswd, SingleSignonPasswd
*/
-
public boolean ConfigureSubCA(String adn, String aduid, String adp, String ssonpwd) {
certAdminName = adn;
certAdminUid = aduid;
@@ -594,7 +606,8 @@ public class AutoInstaller {
System.out.println("exception " + e.getMessage());
}
try {
- if (fis != null) fis.close();
+ if (fis != null)
+ fis.close();
} catch (IOException ioe) {
System.out.println("IO Exception: " + ioe.getMessage());
}
@@ -618,8 +631,8 @@ public class AutoInstaller {
}
private boolean Connect(String myStringUrl) {
- // / This functions connects to the URL and POST HTTP Request .
- // It compares with NMC_STATUS and return the status.
+ // / This functions connects to the URL and POST HTTP Request .
+ // It compares with NMC_STATUS and return the status.
System.out.println(myStringUrl);
st = false;
@@ -629,9 +642,10 @@ public class AutoInstaller {
spage = sm.getPage();
return st;
}
-
+
private boolean startDeamon() {
- // Set StringURL to connect , set the query string and Connect .Get the result
+ // Set StringURL to connect , set the query string and Connect .Get the
+ // result
System.out.println("Log Info - configuring Cert Instance : Start Deamon");
setDeamonURL();
String myStringUrl = "http://" + host + "." + adminDomain + ":"
@@ -726,13 +740,13 @@ public class AutoInstaller {
query += "&opType=" + URLEncoder.encode("OP_MODIFY");
query += "&taskID=" + URLEncoder.encode("selectSubsystems");
query += "&cmsSeed=0";
-
+
if (subsystems.equals("ca")) {
query += "&internaldb.ldapconn.host="
+ URLEncoder.encode(dbConnHost);
query += "&internaldb.ldapconn.port="
+ URLEncoder.encode(dbConnPort);
-
+
}
if (subsystems.equals("ra")) {
query += "&caHostname=" + caHostname;
@@ -978,8 +992,8 @@ public class AutoInstaller {
query += "&aki=true";
query += "&keyUsage=true";
query += "&caSigningCertReqFormat=PKCS10";
- }
-
+ }
+
if (subsystems.equals("ra")) {
query += "&aki=" + URLEncoder.encode(aki);
query += "&keyUsage=" + URLEncoder.encode("true");
@@ -1013,7 +1027,7 @@ public class AutoInstaller {
query += "&taskID=" + URLEncoder.encode("certRequest");
query += "&caHostname=" + caHostname;
query += "&caEEPort=" + caEEPort;
- query += "&cmsSeed=0";
+ query += "&cmsSeed=0";
setPostQueryString(query);
if (!Connect(myStringUrl)) {
@@ -1082,7 +1096,7 @@ public class AutoInstaller {
query += "&serverRoot=" + URLEncoder.encode(serverRoot);
query += "&caEEPort=" + caEEPort;
query += "&caHostname=" + host;
- query += "&caEEType=https";
+ query += "&caEEType=https";
query += "&opType=" + URLEncoder.encode("OP_MODIFY");
query += "&taskID=" + URLEncoder.encode("reqSuccess");
query += "&cmsSeed=0";
@@ -1103,7 +1117,7 @@ public class AutoInstaller {
// install cert
System.out.println(
- "configuring Cert Instance : install cert :" + cert);
+ "configuring Cert Instance : install cert :" + cert);
setConfigURL();
myStringUrl = "http://" + host + ":" + adminPort + configURL;
System.out.println(myStringUrl);
@@ -1115,7 +1129,7 @@ public class AutoInstaller {
if (certType.equals("raSigningCert")) {
query += "&nickname="
- + URLEncoder.encode(certType + " " + instanceID);
+ + URLEncoder.encode(certType + " " + instanceID);
raSigningCert = "-----BEGIN CERTIFICATE-----" + "\n"
+ cr.getCert() + "\n"
+ "-----END CERTIFICATE-----\n";
@@ -1128,30 +1142,30 @@ public class AutoInstaller {
kraTransportCert = cCrypto.normalize(cr.getCert());
}
- if (certType.equals("serverCert")) {
+ if (certType.equals("serverCert")) {
query += "&nickname="
- + URLEncoder.encode("Server-Cert" + " " + instanceID);
+ + URLEncoder.encode("Server-Cert" + " " + instanceID);
}
if (certType.equals("ocspSigningCert")) {
query += "&nickname="
+ URLEncoder.encode(certType + " " + instanceID);
}
-
+
query += "&pkcs10=" + URLEncoder.encode(cert);
query += "&opType=" + URLEncoder.encode("OP_MODIFY");
query += "&taskID=" + URLEncoder.encode("installCert");
query += "&cmsSeed=0";
setPostQueryString(query);
- return(Connect(myStringUrl));
+ return (Connect(myStringUrl));
}
} else {
System.out.println("Error: Request is not approved");
return false;
}
- return true;
+ return true;
}
private String getString(int m) {
@@ -1163,19 +1177,19 @@ public class AutoInstaller {
private boolean createCert() {
System.out.println("configuring Cert Instance : Create Cert");
-
+
// clauclate the validity dates for the cert.
GregorianCalendar begin = new GregorianCalendar();
GregorianCalendar end = new GregorianCalendar();
Integer days = new Integer(certValidityDays);
end.add(GregorianCalendar.DATE, days.intValue());
-
+
setConfigURL();
String myStringUrl = "http://" + host + ":" + adminPort + configURL;
System.out.println(myStringUrl);
-
+
String query = "AdminUserPassword=" + URLEncoder.encode(adminPWD);
query += "&";
@@ -1225,7 +1239,7 @@ public class AutoInstaller {
if (certType.equals("serverCert")) {
query += "&sslServerBit=" + URLEncoder.encode("true");
query += "&sslClientBit=" + URLEncoder.encode("true");
-
+
} else {
query += "&caOComponent=" + URLEncoder.encode(caOComponent);
query += "&caCComponent=" + URLEncoder.encode("us");
@@ -1237,7 +1251,7 @@ public class AutoInstaller {
query += "&mailCABit=" + URLEncoder.encode(mailCABit);
query += "&objectSigningCABit="
+ URLEncoder.encode(objectSigningCABit);
-
+
}
query += "&hashType=" + URLEncoder.encode(hashType);
@@ -1271,7 +1285,7 @@ public class AutoInstaller {
query += "&pwcTokenname=" + URLEncoder.encode("internal");
query += "&singlesignon=" + URLEncoder.encode(tokenPWD);
-
+
query += "&opType=" + URLEncoder.encode("OP_MODIFY");
query += "&taskID=" + URLEncoder.encode("singleSignon");
query += "&cmsSeed=0";
@@ -1308,7 +1322,7 @@ public class AutoInstaller {
}
private boolean exitDeamon() {
-
+
System.out.println("configuring Cert Instance : Exit Deamon");
setDeamonURL();
String myStringUrl = "http://" + host + ":" + adminPort + configURL;
@@ -1401,7 +1415,7 @@ public class AutoInstaller {
return false;
}
- // Step 9 : certRequest and Install
+ // Step 9 : certRequest and Install
if (!certRequest(false)) {
System.out.println("Configuring Cert Instance: error getting cert");
return false;
@@ -1498,7 +1512,7 @@ public class AutoInstaller {
}
private boolean ConfRA() {
- // Start Configuring
+ // Start Configuring
// Step 1. Start Deamon
@@ -1530,14 +1544,14 @@ public class AutoInstaller {
return false;
}
- // Step 3. Create Admin Values
+ // Step 3. Create Admin Values
if (!createAdminValues()) {
System.out.println(
"Configuring Cert Instance: error configuring admin values ");
return false;
}
- // Step 4. SubSystems
+ // Step 4. SubSystems
if (!selectSubSystem()) {
System.out.println(
@@ -1566,14 +1580,15 @@ public class AutoInstaller {
return false;
}
- // Step 8 : CheckDN
+ // Step 8 : CheckDN
if (!checkDN()) {
System.out.println(
"Configuring Cert Instance: error checking deamon");
return false;
}
- // Step 9 : certRequest and Install i.e approve the request as a trusted manager
+ // Step 9 : certRequest and Install i.e approve the request as a trusted
+ // manager
if (!certRequest(true)) {
System.out.println("Configuring Cert Instance: error getting cert");
return false;
@@ -1606,7 +1621,7 @@ public class AutoInstaller {
return false;
}
- // Step 9 : CheckDN
+ // Step 9 : CheckDN
if (!checkDN()) {
System.out.println(
"Configuring Cert Instance: error checking deamon");
@@ -1620,24 +1635,24 @@ public class AutoInstaller {
return false;
}
- // After creating ssl cert
+ // After creating ssl cert
tokenPWD = mtokenPWD;
- // Step 11
+ // Step 11
if (!singleSignON()) {
System.out.println(
"Configuring Cert Instance: error setting up singlesignon");
return false;
}
- // Step 11
+ // Step 11
if (!doMisc()) {
System.out.println(
"Configuring Cert Instance: error setting up miscell");
return false;
}
- // Step 12
+ // Step 12
if (!exitDeamon()) {
System.out.println(
"Configuring Cert Instance: Unable to exit deamon");
@@ -1648,7 +1663,7 @@ public class AutoInstaller {
}
private boolean ConfKRA() {
- // Start Configuring
+ // Start Configuring
// Step 1. Start Deamon
@@ -1680,14 +1695,14 @@ public class AutoInstaller {
return false;
}
- // Step 3. Create Admin Values
+ // Step 3. Create Admin Values
if (!createAdminValues()) {
System.out.println(
"Configuring Cert Instance: error configuring admin values ");
return false;
}
- // Step 4. SubSystems
+ // Step 4. SubSystems
if (!selectSubSystem()) {
System.out.println(
@@ -1716,14 +1731,15 @@ public class AutoInstaller {
return false;
}
- // Step 8 : CheckDN
+ // Step 8 : CheckDN
if (!checkDN()) {
System.out.println(
"Configuring Cert Instance: error checking deamon");
return false;
}
- // Step 9 : certRequest and Install i.e approve the request as a trusted manager
+ // Step 9 : certRequest and Install i.e approve the request as a trusted
+ // manager
if (!certRequest(true)) {
System.out.println("Configuring Cert Instance: error getting cert");
return false;
@@ -1737,8 +1753,9 @@ public class AutoInstaller {
// no need to do this from 7.1 due to new acl based key recovery
/*
- if (!setupKRAAgents())
- { System.out.println("Configuring Cert Instance: error configuring storage key"); return false;}
+ * if (!setupKRAAgents()) { System.out.println(
+ * "Configuring Cert Instance: error configuring storage key"); return
+ * false;}
*/
// Create a SSL signing cert
@@ -1768,7 +1785,7 @@ public class AutoInstaller {
return false;
}
- // Step 9 : CheckDN
+ // Step 9 : CheckDN
if (!checkDN()) {
System.out.println(
"Configuring Cert Instance: error checking deamon");
@@ -1782,24 +1799,24 @@ public class AutoInstaller {
return false;
}
- // After creating ssl cert
+ // After creating ssl cert
tokenPWD = mtokenPWD;
- // Step 11
+ // Step 11
if (!singleSignON()) {
System.out.println(
"Configuring Cert Instance: error setting up singlesignon");
return false;
}
- // Step 11
+ // Step 11
if (!doMisc()) {
System.out.println(
"Configuring Cert Instance: error setting up miscell");
return false;
}
- // Step 12
+ // Step 12
if (!exitDeamon()) {
System.out.println(
"Configuring Cert Instance: Unable to exit deamon");
@@ -1887,7 +1904,8 @@ public class AutoInstaller {
return false;
}
- // Step 9 : certRequest and Install i.e approve the request as a trusted manager
+ // Step 9 : certRequest and Install i.e approve the request as a trusted
+ // manager
if (!certRequest(false)) {
System.out.println("Configuring Cert Instance: error getting cert");
return false;
@@ -1965,7 +1983,7 @@ public class AutoInstaller {
// org
private boolean ConfCA() {
- // Start Configuring
+ // Start Configuring
// Step 1. Start Deamon
@@ -1997,14 +2015,14 @@ public class AutoInstaller {
return false;
}
- // Step 3. Create Admin Values
+ // Step 3. Create Admin Values
if (!createAdminValues()) {
System.out.println(
"Configuring Cert Instance: error configuring admin values ");
return false;
}
- // Step 4. SubSystems
+ // Step 4. SubSystems
if (!selectSubSystem()) {
System.out.println(
@@ -2012,7 +2030,7 @@ public class AutoInstaller {
return false;
}
- // SetSerial Number
+ // SetSerial Number
if (!setSerial("1", "1000000")) {
System.out.println(
"Configuring Cert Instance: error setting serial number");
@@ -2032,10 +2050,12 @@ public class AutoInstaller {
return false;
}
- // Step 6. setting up Server Migration
+ // Step 6. setting up Server Migration
// if (!serverMigration())
- // { System.out.println("Configuring Cert Instance: error configuring server migration"); return false;}
+ // {
+ // System.out.println("Configuring Cert Instance: error configuring server migration");
+ // return false;}
// Step 7: Initialize Token
if (!initializeToken()) {
@@ -2051,7 +2071,7 @@ public class AutoInstaller {
return false;
}
- // Step 9 : CheckDN
+ // Step 9 : CheckDN
if (!checkDN()) {
System.out.println(
"Configuring Cert Instance: error checking deamon");
@@ -2089,7 +2109,7 @@ public class AutoInstaller {
return false;
}
- // Step 9 : CheckDN
+ // Step 9 : CheckDN
if (!checkDN()) {
System.out.println(
"Configuring Cert Instance: error checking deamon");
@@ -2102,24 +2122,24 @@ public class AutoInstaller {
return false;
}
- // After creating ssl cert
+ // After creating ssl cert
tokenPWD = mtokenPWD;
- // Step 11
+ // Step 11
if (!singleSignON()) {
System.out.println(
"Configuring Cert Instance: error setting up singlesignon");
return false;
}
- // Step 11
+ // Step 11
if (!doMisc()) {
System.out.println(
"Configuring Cert Instance: error setting up miscell");
return false;
}
- // Step 12
+ // Step 12
if (!exitDeamon()) {
System.out.println(
"Configuring Cert Instance: Unable to exit deamon");
@@ -2129,7 +2149,7 @@ public class AutoInstaller {
return true;
}
- // Configure Clone
+ // Configure Clone
public boolean readProperties() {
// Read the properties file and assign values to variables .
@@ -2140,7 +2160,7 @@ public class AutoInstaller {
"exception reading Properties File " + e.getMessage());
}
- // read all properties
+ // read all properties
adminDomain = props.getProperty("inst.admin.domain");
adminID = props.getProperty("inst.admin.uid");
@@ -2212,12 +2232,12 @@ public class AutoInstaller {
}
if (subsystems.equals("ocsp")) {
return ConfOCSP();
- }
+ }
if (subsystems.equals("kra")) {
return ConfKRA();
}
if (subsystems.equals("subca")) {
- subca = true;
+ subca = true;
subsystems = "ca";
return ConfSubCA();
}
@@ -2227,9 +2247,8 @@ public class AutoInstaller {
public static void main(String args[]) {
// Exit Status - (-1) for error
- // - 1 Configured and server Alive
- // - 0 Configured bur could not sart server
-
+ // - 1 Configured and server Alive
+ // - 0 Configured bur could not sart server
AutoInstaller t = new AutoInstaller();
@@ -2239,13 +2258,13 @@ public class AutoInstaller {
if (args.length < 1) {
System.out.println("Usage : PropertiesFilePath");
System.exit(-1);
- }
-
+ }
+
System.out.println("configuring Cert Instance : Start");
boolean st = t.readProperties();
- if (st) {
+ if (st) {
System.out.println("Configuring Cert Instance : Successful");
System.exit(1);
} else {
@@ -2255,5 +2274,5 @@ public class AutoInstaller {
}
}
-} // end of class
+} // end of class
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/BaseState.java b/pki/base/silent/src/com/netscape/pkisilent/common/BaseState.java
index a3ceec31..b3f0a711 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/BaseState.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/BaseState.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.common;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -17,40 +18,38 @@ package com.netscape.pkisilent.common;
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
-
-
/**
- * CMS Test framework .
- * This class reads and sets the values for a CMS subsytems Config file (CS.cfg)
- * Using this class you can set the server to a base state.
+ * CMS Test framework . This class reads and sets the values for a CMS subsytems
+ * Config file (CS.cfg) Using this class you can set the server to a base state.
*/
-
-
public class BaseState {
private String CMSConfigFile;
private CMSConfig cmscfg = null;
private String ldapbase, ldaphost, ldapport, ldapdn, ldapdnpw;
private boolean ldapsecConn = false;
- // Constructor
+ // Constructor
-
- public BaseState() {}
+ public BaseState() {
+ }
/**
- * Constructor . Takes the parameter CMSConfigfilename ( with fullpath)
+ * Constructor . Takes the parameter CMSConfigfilename ( with fullpath)
+ *
* @param CMSConfigfile.
*/
- public BaseState(String cmscfilename) {
+ public BaseState(String cmscfilename) {
CMSConfigFile = cmscfilename;
}
/**
- * Set the publishing directory information . Takes the paramters ldaphost,ldapport,ldapDN, ldapDN password, BaseDN , Secure coonection (true/false)
+ * Set the publishing directory information . Takes the paramters
+ * ldaphost,ldapport,ldapDN, ldapDN password, BaseDN , Secure coonection
+ * (true/false)
*/
public void setLDAPInfo(String h, String p, String dn, String pw, String base, boolean sc) {
ldaphost = h;
@@ -63,8 +62,8 @@ public class BaseState {
}
/**
- * Enable SSL Client authentication for Directory enrollment and publishing
- */
+ * Enable SSL Client authentication for Directory enrollment and publishing
+ */
public void EnableSSLClientAuth() {
ldapsecConn = true;
@@ -79,7 +78,8 @@ public class BaseState {
}
/**
- * Set to CA 's base state . Enables Directory based enrollment , publishing and Portal enrollment
+ * Set to CA 's base state . Enables Directory based enrollment , publishing
+ * and Portal enrollment
*/
public void CABaseState() {
@@ -98,10 +98,10 @@ public class BaseState {
}
/**
- * Set to RA 's base state . Enables Directory based enrollment and Portal enrollment
+ * Set to RA 's base state . Enables Directory based enrollment and Portal
+ * enrollment
*/
-
public void RABaseState() {
cmscfg = new CMSConfig(CMSConfigFile);
cmscfg.EnableAdminEnrollment();
@@ -114,6 +114,7 @@ public class BaseState {
}
- public static void main(String args[]) {}// end of function main
+ public static void main(String args[]) {
+ }// end of function main
}
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/CMSConfig.java b/pki/base/silent/src/com/netscape/pkisilent/common/CMSConfig.java
index 94c57a62..37569417 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/CMSConfig.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/CMSConfig.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.common;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -20,20 +21,17 @@ package com.netscape.pkisilent.common;
import java.io.FileInputStream;
import java.io.FileOutputStream;
-
/**
- * CMS Test framework .
- * This class reads,modifies and saves CS.cfg file
+ * CMS Test framework . This class reads,modifies and saves CS.cfg file
*/
-
-public class CMSConfig extends ServerInfo {
+public class CMSConfig extends ServerInfo {
/**
- * Constructor . Reads the CS.cfg file .Takes the parameter for Configfile ( Provide fullpath)
+ * Constructor . Reads the CS.cfg file .Takes the parameter for Configfile (
+ * Provide fullpath)
*/
-
public CMSConfig(String confFile) {
CMSConfigFile = confFile;
System.out.println(CMSConfigFile);
@@ -57,7 +55,7 @@ public class CMSConfig extends ServerInfo {
}
/**
- * Saves the config file
+ * Saves the config file
**/
public void saveCMSConfig() {
@@ -83,12 +81,12 @@ public class CMSConfig extends ServerInfo {
}
- // Authentication
-
+ // Authentication
// Enable DirectoryBased Authentication
/**
- * Takes parameters : secureConnection( true/false), basedn, ldaphostname, lapdaportnumber ( in case of secured connection give ldap secured port)
+ * Takes parameters : secureConnection( true/false), basedn, ldaphostname,
+ * lapdaportnumber ( in case of secured connection give ldap secured port)
*/
public void EnableDirEnrollment(boolean secureConn, String ldapbase, String lhost, String lport) {
@@ -149,7 +147,9 @@ public class CMSConfig extends ServerInfo {
}
/**
- * Takes parameters : secureConnection( true/false), ldapbinddn, ldapbindnpassword,ldaphostname, lapdaportnumber ( in case of secured connection give ldap secured port), basedn (e.g ou=people,o=mcom.com)
+ * Takes parameters : secureConnection( true/false), ldapbinddn,
+ * ldapbindnpassword,ldaphostname, lapdaportnumber ( in case of secured
+ * connection give ldap secured port), basedn (e.g ou=people,o=mcom.com)
*/
void EnablePortalAuth(boolean secureConn, String ldaprootDN, String ldaprootDNPW, String lhost, String lport, String lbsuffix) {
@@ -207,9 +207,11 @@ public class CMSConfig extends ServerInfo {
}
- // Publishing
+ // Publishing
/**
- * Takes parameters : secureConnection( true/false), ldapbinddn, ldapbindnpassword,ldaphostname, lapdaportnumber ( in case of secured connection give ldap secured port)
+ * Takes parameters : secureConnection( true/false), ldapbinddn,
+ * ldapbindnpassword,ldaphostname, lapdaportnumber ( in case of secured
+ * connection give ldap secured port)
*/
public void EnablePublishing(boolean secureConn, String ldaprootDN, String ldaprootDNPW, String lhost, String lport) {
@@ -412,7 +414,7 @@ public class CMSConfig extends ServerInfo {
}
public void CreateOCSPPublisher(String OCSPHost, String OCSPPort, String OCSPEEPort) {
- // Set host nmae with fully qualified hostname
+ // Set host nmae with fully qualified hostname
String location = "http://" + OCSPHost + ":" + OCSPEEPort + "/ocsp";
CMSprops.setProperty("ca.crl.MasterCRL.alwaysUpdate", "true");
@@ -503,7 +505,7 @@ public class CMSConfig extends ServerInfo {
CMSprops.setProperty("cardcryptogram.validate.enable", "false");
}
- // Policies
+ // Policies
public void DefaultValidityRule(String SubsystemType, String lagtime, String leadtime, String maxValidity) {
if (SubsystemType.equals("ca")) {
CMSprops.setProperty("ca.Policy.rule.DefaultValidityRule.enable",
@@ -558,10 +560,10 @@ public class CMSConfig extends ServerInfo {
CMSConfig s = new CMSConfig(args[0]);
boolean secureC = false;
- // s.EnableDirEnrollment(secureC);
+ // s.EnableDirEnrollment(secureC);
s.saveCMSConfig();
-
+
}// end of function main
-} // end of class
+} // end of class
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/CMSInstance.java b/pki/base/silent/src/com/netscape/pkisilent/common/CMSInstance.java
index 0687bc2a..fe611dbd 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/CMSInstance.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/CMSInstance.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.common;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -25,7 +26,6 @@ import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URLEncoder;
-
public class CMSInstance {
private int i;
@@ -33,13 +33,15 @@ public class CMSInstance {
private String host, port, AdminDN, AdminDNPW, serverRoot, instanceID, sieurl, adminDomain, machineName;
/**
- * CMS Test framework .
- * This class Creates and Removes a CMS server instance
+ * CMS Test framework . This class Creates and Removes a CMS server instance
*/
-
/**
- * Constructor. Takes parameters hostname, adminserverport, adminDN, adminDNpassword, Dominanname, ServerRoot( full path) , instanceID, mnameand sieURL. mname is the fully qualified name of the server ( jupiter2.nscp.aoltw.net) sieURL is ("ldap://jupiter2.nscp.aoltw.net:(ConfigLADPPort)/o=NetscapeRoot"
+ * Constructor. Takes parameters hostname, adminserverport, adminDN,
+ * adminDNpassword, Dominanname, ServerRoot( full path) , instanceID,
+ * mnameand sieURL. mname is the fully qualified name of the server (
+ * jupiter2.nscp.aoltw.net) sieURL is
+ * ("ldap://jupiter2.nscp.aoltw.net:(ConfigLADPPort)/o=NetscapeRoot"
*/
private String cs_server_root, cs_tps_root, tps_hostname, tps_fqdn, tps_instanceid, tps_ee_port, tps_agent_port, tps_auth_ldap_host, tps_auth_ldap_port, tps_auth_ldap_suffix, ca_hostname, ca_ee_port, tks_hostname, tks_agent_port, token_db_hostname, token_db_port, token_db_suffix, token_db_passwd;
@@ -101,7 +103,7 @@ public class CMSInstance {
// steps
// 1. create .cfg file
// 2. run create.pl with that .cfg file
-
+
FileOutputStream out = new FileOutputStream(
cs_server_root + "/tps_auto_config.cfg");
BufferedWriter awriter;
@@ -150,14 +152,16 @@ public class CMSInstance {
try {
Process p = null;
Runtime r = Runtime.getRuntime();
- // String[] se = {"perl", cs_server_root+"/bin/cert/tps/setup/create.pl" , "-i", cs_server_root+"/tps_auto_config.cfg" };
+ // String[] se = {"perl",
+ // cs_server_root+"/bin/cert/tps/setup/create.pl" , "-i",
+ // cs_server_root+"/tps_auto_config.cfg" };
String[] se = {
- "perl",
- "/home/ckannan/cms/src/ns/netkeyra/setup/create.pl", "-i",
- cs_server_root + "/tps_auto_config.cfg" };
+ "perl",
+ "/home/ckannan/cms/src/ns/netkeyra/setup/create.pl", "-i",
+ cs_server_root + "/tps_auto_config.cfg" };
System.out.println(se);
- p = r.exec(se);
+ p = r.exec(se);
p.waitFor();
String line;
@@ -192,7 +196,7 @@ public class CMSInstance {
+ startURL;
System.out.println(myStringUrl);
-
+
String query = "serverRoot=" + URLEncoder.encode(serverRoot);
query += "&instanceID=" + URLEncoder.encode(instanceID);
@@ -205,7 +209,7 @@ public class CMSInstance {
PostQuery sm = new PostQuery(myStringUrl, AdminDN, AdminDNPW, query);
return (sm.Send());
-
+
}
public boolean RemoveInstance() {
@@ -214,11 +218,11 @@ public class CMSInstance {
String myStringUrl = "http://" + host + ":" + port + startURL;
System.out.println(myStringUrl);
-
+
String query = "serverRoot=" + URLEncoder.encode(serverRoot);
query += "&instanceID=" + URLEncoder.encode(instanceID);
-
+
PostQuery sm = new PostQuery(myStringUrl, AdminDN, AdminDNPW, query);
st = sm.Send();
@@ -233,15 +237,15 @@ public class CMSInstance {
myStringUrl = "http://" + host + ":" + port + startURL;
System.out.println(myStringUrl);
-
+
query = "serverRoot=" + URLEncoder.encode(serverRoot);
query += "&InstanceName=" + URLEncoder.encode(instanceID + "-db");
-
+
PostQuery rmdb = new PostQuery(myStringUrl, AdminDN, AdminDNPW, query);
rmdb.setNMCStatus("NMC_Status: 0");
return (rmdb.Send());
-
+
}
public static void main(String args[]) {
@@ -250,38 +254,38 @@ public class CMSInstance {
// Exit Status - (-1) for error
// - 0 FAIL
// - 1 PASS
-
+
boolean st;
-
+
System.out.println(args.length);
if (args.length < 10) {
System.out.println(
"Usage : <task:Create/REmove> host port AdminDN AdminDNPW adminDomain serverRoot instanceID machineName sieURL");
System.exit(-1);
- }
+ }
int task = 0;
args[0] = args[0].toLowerCase();
- if (args[0].equals("create")) {
+ if (args[0].equals("create")) {
task = 0;
}
if (args[0].equals("remove")) {
task = 1;
}
-
+
CMSInstance t = new CMSInstance(args[1], args[2], args[3], args[4],
args[5], args[6], args[7], args[8], args[9]);
switch (task) {
-
+
case 0:
st = t.CreateInstance();
- if (st) {
+ if (st) {
System.out.println("server Instance created ");
System.exit(1);
} else {
-
+
System.out.println("Error: Server Instance could not be created");
System.exit(0);
}
@@ -289,11 +293,11 @@ public class CMSInstance {
case 1:
st = t.RemoveInstance();
- if (st) {
+ if (st) {
System.out.println("Server instance removed");
System.exit(1);
} else {
-
+
System.out.println("Server instance could not be removed");
System.exit(0);
}
@@ -306,5 +310,5 @@ public class CMSInstance {
} // end of switch
}// end of function main
-} // end of class
+} // end of class
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/CMSLDAP.java b/pki/base/silent/src/com/netscape/pkisilent/common/CMSLDAP.java
index 038ec42f..9948bc1c 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/CMSLDAP.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/CMSLDAP.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.common;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -31,15 +32,12 @@ import netscape.ldap.LDAPModificationSet;
import netscape.ldap.LDAPSearchResults;
import netscape.ldap.LDAPv2;
-
/**
- * CMS Test framework .
- * Using this class you can add a user and user certificate to LDAP server.
- * You can also check if a certificate / CRL is published in LDAP server
- * USe this class to turn of SSL and turn on SSL in a LDAP server.
+ * CMS Test framework . Using this class you can add a user and user certificate
+ * to LDAP server. You can also check if a certificate / CRL is published in
+ * LDAP server USe this class to turn of SSL and turn on SSL in a LDAP server.
*/
-
public class CMSLDAP {
private String HOST, DN, BASEDN, PASSWORD;
@@ -47,7 +45,8 @@ public class CMSLDAP {
private LDAPConnection conn = new LDAPConnection();
- public CMSLDAP() {}
+ public CMSLDAP() {
+ }
/**
* Constructor. Takes parametes ldaphost, ldapport
@@ -58,7 +57,8 @@ public class CMSLDAP {
}
/**
- * Cosntructor. Takes parameters ldaphost,ldapport,ldapbinddn, ldapbindnpassword.
+ * Cosntructor. Takes parameters ldaphost,ldapport,ldapbinddn,
+ * ldapbindnpassword.
*/
public CMSLDAP(String h, String p, String dn, String pwd) {
HOST = h;
@@ -68,7 +68,7 @@ public class CMSLDAP {
}
/**
- * Connect to ldap server
+ * Connect to ldap server
*/
public boolean connect() {
@@ -99,12 +99,13 @@ public class CMSLDAP {
}
/**
- * Search for certificaterevocationList attribute. Takes basedn and filter as parameters
- */
+ * Search for certificaterevocationList attribute. Takes basedn and filter
+ * as parameters
+ */
- public boolean searchCRL(String basedn, String filter) throws LDAPException {
+ public boolean searchCRL(String basedn, String filter) throws LDAPException {
int searchScope = LDAPv2.SCOPE_SUB;
- String getAttrs[] = { "certificateRevocationList;binary"};
+ String getAttrs[] = { "certificateRevocationList;binary" };
LDAPSearchResults results = conn.search(basedn, searchScope, filter,
getAttrs, false);
@@ -135,11 +136,9 @@ public class CMSLDAP {
* Search for attriburte usercertificate. Takes parameters basedn and filter
*/
-
-
- public boolean searchUserCert(String basedn, String filter) throws LDAPException {
+ public boolean searchUserCert(String basedn, String filter) throws LDAPException {
int searchScope = LDAPv2.SCOPE_SUB;
- String getAttrs[] = { "usercertificate;binary"};
+ String getAttrs[] = { "usercertificate;binary" };
LDAPSearchResults results = conn.search(basedn, searchScope, filter,
getAttrs, false);
@@ -166,7 +165,8 @@ public class CMSLDAP {
}
/**
- * Adds a user to direcrtory server . Takes parameters basedn, cn,sn,uid and passwd
+ * Adds a user to direcrtory server . Takes parameters basedn, cn,sn,uid and
+ * passwd
*/
public boolean userAdd(String basedn, String cn, String sn, String uid, String pwd) {
@@ -175,9 +175,9 @@ public class CMSLDAP {
attrSet.add(
new LDAPAttribute("objectclass",
- new String[] {
- "top", "person", "organizationalPerson",
- "inetorgperson"}));
+ new String[] {
+ "top", "person", "organizationalPerson",
+ "inetorgperson" }));
attrSet.add(new LDAPAttribute("cn", cn));
attrSet.add(new LDAPAttribute("mail", uid + "@netscape.com"));
attrSet.add(new LDAPAttribute("userpassword", pwd));
@@ -225,7 +225,7 @@ public class CMSLDAP {
val += ',';
i++;
continue;
- } else {
+ } else {
val += s.charAt(i);
}
}
@@ -233,8 +233,8 @@ public class CMSLDAP {
}
/**
- * Returns the SerialNumber;issuerDN;SubjectDN string.
- * Takes certificate as parameter
+ * Returns the SerialNumber;issuerDN;SubjectDN string. Takes certificate as
+ * parameter
*/
public String getCertificateString(X509Certificate cert) {
@@ -258,19 +258,20 @@ public class CMSLDAP {
}
/**
- * Adds a user of objectclass cmsuser . Takes cn,sn,uid,password,certificate as parameters.
+ * Adds a user of objectclass cmsuser . Takes cn,sn,uid,password,certificate
+ * as parameters.
*/
public boolean CMSuserAdd(String cn, String sn, String uid, String pwd, byte[] certpack) {
try {
X509Certificate cert = getXCertificate(certpack);
-
+
LDAPAttributeSet attrSet = new LDAPAttributeSet();
attrSet.add(
new LDAPAttribute("objectclass",
- new String[] {
- "top", "person", "organizationalPerson",
- "inetorgperson", "cmsuser"}));
+ new String[] {
+ "top", "person", "organizationalPerson",
+ "inetorgperson", "cmsuser" }));
attrSet.add(new LDAPAttribute("cn", cn));
attrSet.add(new LDAPAttribute("mail", uid + "@netscape.com"));
attrSet.add(new LDAPAttribute("userpassword", pwd));
@@ -301,7 +302,8 @@ public class CMSLDAP {
}
/**
- * Adds a user of objectclass cmsuser . Takes cn,sn,uid,password,certificate as parameters.
+ * Adds a user of objectclass cmsuser . Takes cn,sn,uid,password,certificate
+ * as parameters.
*/
public boolean CMSuserAdd(String cn, String sn, String uid, String pwd, X509Certificate cert) {
@@ -310,10 +312,10 @@ public class CMSLDAP {
LDAPAttributeSet attrSet = new LDAPAttributeSet();
attrSet.add(
- new LDAPAttribute("objectclass",
- new String[] {
- "top", "person", "organizationalPerson",
- "inetorgperson", "cmsuser"}));
+ new LDAPAttribute("objectclass",
+ new String[] {
+ "top", "person", "organizationalPerson",
+ "inetorgperson", "cmsuser" }));
attrSet.add(new LDAPAttribute("cn", cn));
attrSet.add(new LDAPAttribute("mail", uid + "@netscape.com"));
attrSet.add(new LDAPAttribute("userpassword", pwd));
@@ -345,7 +347,7 @@ public class CMSLDAP {
}
/**
- * adds a cms user to Trusted Manager Group. Takes uid as parameter.
+ * adds a cms user to Trusted Manager Group. Takes uid as parameter.
*/
public boolean addCMSUserToTMGroup(String uid) {
@@ -370,7 +372,8 @@ public class CMSLDAP {
}
/**
- * adds a cms user to Agent Group. Takes subsytem (ca/ra/ocsp/kra) and uid as parameters .
+ * adds a cms user to Agent Group. Takes subsytem (ca/ra/ocsp/kra) and uid
+ * as parameters .
*/
public boolean addCMSUserToAgentGroup(String subsystem, String uid) {
@@ -415,7 +418,7 @@ public class CMSLDAP {
}
/**
- * Will trun of SSL in LDAP server
+ * Will trun of SSL in LDAP server
**/
public boolean TurnOffSSL() {
@@ -428,8 +431,7 @@ public class CMSLDAP {
LDAPAttribute cfile = new LDAPAttribute("nscertfile", "alias/");
LDAPAttribute cauth = new LDAPAttribute("nssslclientauth", "allowed");
- // conn.delete("cn=RSA,cn=encryption,cn=config");
-
+ // conn.delete("cn=RSA,cn=encryption,cn=config");
mods.add(LDAPModification.REPLACE, ssl3);
mods.add(LDAPModification.DELETE, ssl3ciphers);
@@ -462,9 +464,10 @@ public class CMSLDAP {
}
/**
- * Will Turn ON SSL in LDAP server . Takes certPrefix, certificatenickanme and sslport as parameters.
+ * Will Turn ON SSL in LDAP server . Takes certPrefix, certificatenickanme
+ * and sslport as parameters.
**/
-
+
public boolean TurnOnSSL(String certPrefix, String certName, String sslport) {
String dn;
String CIPHERS = "-rsa_null_md5,+rsa_fips_3des_sha,+rsa_fips_des_sha,+rsa_3des_sha,+rsa_rc4_128_md5,+rsa_des_sha,+rsa_rc2_40_md5,+rsa_rc4_40_md5";
@@ -472,8 +475,8 @@ public class CMSLDAP {
try {
boolean found = false;
int searchScope = LDAPv2.SCOPE_SUB;
- String getAttrs[] = { "nssslactivation"};
-
+ String getAttrs[] = { "nssslactivation" };
+
LDAPModificationSet mods = new LDAPModificationSet();
LDAPAttribute sec = new LDAPAttribute("nsslapd-security", "on");
LDAPAttribute sp = new LDAPAttribute("nsslapd-securePort", sslport);
@@ -481,7 +484,7 @@ public class CMSLDAP {
mods.add(LDAPModification.REPLACE, sec);
mods.add(LDAPModification.REPLACE, sp);
conn.modify("cn=config", mods);
- mods.removeElementAt(1);
+ mods.removeElementAt(1);
mods.removeElementAt(0);
LDAPAttribute ssl3 = new LDAPAttribute("nsssl3", "on");
@@ -500,14 +503,14 @@ public class CMSLDAP {
mods.add(LDAPModification.REPLACE, cauth);
conn.modify("cn=encryption,cn=config", mods);
- int i = 4;
+ int i = 4;
while (i >= 0) {
mods.removeElementAt(i);
i--;
}
- // conn.delete("cn=RSA,cn=encryption,cn=config");
+ // conn.delete("cn=RSA,cn=encryption,cn=config");
try {
LDAPSearchResults results = conn.search(
"cn=RSA,cn=encryption,cn=config", searchScope, null,
@@ -532,7 +535,7 @@ public class CMSLDAP {
attrSet.add(
new LDAPAttribute("objectclass",
- new String[] { "top", "nsEncryptionModule"}));
+ new String[] { "top", "nsEncryptionModule" }));
attrSet.add(new LDAPAttribute("cn", "RSA"));
attrSet.add(
new LDAPAttribute("nsssltoken", "internal (software)"));
@@ -571,13 +574,13 @@ public class CMSLDAP {
System.out.println(HOST + PORT + DN + PASSWORD + BASEDN);
CMSLDAP caIdb = new CMSLDAP(HOST, PORT, DN, PASSWORD);
- /* FileInputStream fis = new FileInputStream("t1");
- DataInputStream dis = new DataInputStream(fis);
-
- byte[] bytes = new byte[dis.available()];
- dis.readFully(bytes);
-
- // bytes=s.getBytes();
+ /*
+ * FileInputStream fis = new FileInputStream("t1"); DataInputStream
+ * dis = new DataInputStream(fis);
+ *
+ * byte[] bytes = new byte[dis.available()]; dis.readFully(bytes);
+ *
+ * // bytes=s.getBytes();
*/
if (!caIdb.connect()) {
@@ -590,17 +593,22 @@ public class CMSLDAP {
// if(!caIdb.searchUserCert("o=mcom.com","uid=test"))
// System.out.println("USer cert is not published");
-
- // if (!caIdb.CMSuserAdd("ra-trust" ,"ra-trust","ra-trust","netscape",bytes))
+
+ // if (!caIdb.CMSuserAdd("ra-trust"
+ // ,"ra-trust","ra-trust","netscape",bytes))
// {System.out.println("Trusted MAnager user Could not be add ");}
// if(!caIdb.addCMSUserToTMGroup("ra-trust"))
- // {System.out.println("CMS user Could not be added to Trusted manager group "); }
+ // {System.out.println("CMS user Could not be added to Trusted manager group ");
+ // }
// if(!caIdb.addCMSUserToAgentGroup("ra","ra-agent"))
- // {System.out.println("CMS user Could not be added to Trusted manager group "); }
- /* if(!caIdb.userAdd(BASEDN,"raeetest1","raeetest1","raeetest1","netscape"))
- {System.out.println("CMS user Could not be added to Trusted manager group "); }
+ // {System.out.println("CMS user Could not be added to Trusted manager group ");
+ // }
+ /*
+ * if(!caIdb.userAdd(BASEDN,"raeetest1","raeetest1","raeetest1",
+ * "netscape")) {System.out.println(
+ * "CMS user Could not be added to Trusted manager group "); }
*/
} catch (Exception e) {
@@ -609,4 +617,3 @@ public class CMSLDAP {
}
}
-
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/CMSProperties.java b/pki/base/silent/src/com/netscape/pkisilent/common/CMSProperties.java
index bae3e420..b8d9db48 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/CMSProperties.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/CMSProperties.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.common;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -40,45 +41,44 @@ import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
-
/**
- * The <code>Properties</code> class represents a persistent set of
- * properties. The <code>Properties</code> can be saved to a stream
- * or loaded from a stream. Each key and its corresponding value in
- * the property list is a string.
+ * The <code>Properties</code> class represents a persistent set of properties.
+ * The <code>Properties</code> can be saved to a stream or loaded from a stream.
+ * Each key and its corresponding value in the property list is a string.
* <p>
- * A property list can contain another property list as its
- * "defaults"; this second property list is searched if
- * the property key is not found in the original property list.
+ * A property list can contain another property list as its "defaults"; this
+ * second property list is searched if the property key is not found in the
+ * original property list.
* <p>
* Because <code>Properties</code> inherits from <code>Hashtable</code>, the
* <code>put</code> and <code>putAll</code> methods can be applied to a
- * <code>Properties</code> object. Their use is strongly discouraged as they
+ * <code>Properties</code> object. Their use is strongly discouraged as they
* allow the caller to insert entries whose keys or values are not
- * <code>Strings</code>. The <code>setProperty</code> method should be used
- * instead. If the <code>store</code> or <code>save</code> method is called
- * on a "compromised" <code>Properties</code> object that contains a
- * non-<code>String</code> key or value, the call will fail.
+ * <code>Strings</code>. The <code>setProperty</code> method should be used
+ * instead. If the <code>store</code> or <code>save</code> method is called on a
+ * "compromised" <code>Properties</code> object that contains a non-
+ * <code>String</code> key or value, the call will fail.
* <p>
- * <a name="encoding"></a>
- * When saving properties to a stream or loading them from a stream, the
- * ISO 8859-1 character encoding is used. For characters that cannot be directly
- * represented in this encoding,
- * <a href="http://java.sun.com/docs/books/jls/html/3.doc.html#100850">Unicode escapes</a>
- * are used; however, only a single 'u' character is allowed in an escape sequence.
- * The native2ascii tool can be used to convert property files to and from
- * other character encodings.
+ * <a name="encoding"></a> When saving properties to a stream or loading them
+ * from a stream, the ISO 8859-1 character encoding is used. For characters that
+ * cannot be directly represented in this encoding, <a
+ * href="http://java.sun.com/docs/books/jls/html/3.doc.html#100850">Unicode
+ * escapes</a> are used; however, only a single 'u' character is allowed in an
+ * escape sequence. The native2ascii tool can be used to convert property files
+ * to and from other character encodings.
*
- * @see <a href="../../../tooldocs/solaris/native2ascii.html">native2ascii tool for Solaris</a>
- * @see <a href="../../../tooldocs/win32/native2ascii.html">native2ascii tool for Windows</a>
- *
- * @author Arthur van Hoff
- * @author Michael McCloskey
+ * @see <a href="../../../tooldocs/solaris/native2ascii.html">native2ascii tool
+ * for Solaris</a>
+ * @see <a href="../../../tooldocs/win32/native2ascii.html">native2ascii tool
+ * for Windows</a>
+ *
+ * @author Arthur van Hoff
+ * @author Michael McCloskey
* @version 1.60, 02/02/00
- * @since JDK1.0
+ * @since JDK1.0
*/
-class CMSProperties extends Hashtable<String,String> {
+class CMSProperties extends Hashtable<String, String> {
/**
* use serialVersionUID from JDK 1.1.X for interoperability
@@ -86,9 +86,9 @@ class CMSProperties extends Hashtable<String,String> {
private static final long serialVersionUID = 4112578634029874840L;
/**
- * A property list that contains default values for any keys not
- * found in this property list.
- *
+ * A property list that contains default values for any keys not found in
+ * this property list.
+ *
* @serial
*/
protected CMSProperties defaults;
@@ -102,22 +102,22 @@ class CMSProperties extends Hashtable<String,String> {
/**
* Creates an empty property list with the specified defaults.
- *
- * @param defaults the defaults.
+ *
+ * @param defaults the defaults.
*/
public CMSProperties(CMSProperties defaults) {
this.defaults = defaults;
}
/**
- * Calls the hashtable method <code>put</code>. Provided for
- * parallelism with the <tt>getProperty</tt> method. Enforces use of
- * strings for property keys and values.
- *
+ * Calls the hashtable method <code>put</code>. Provided for parallelism
+ * with the <tt>getProperty</tt> method. Enforces use of strings for
+ * property keys and values.
+ *
* @param key the key to be placed into this property list.
* @param value the value corresponding to <tt>key</tt>.
* @see #getProperty
- * @since 1.2
+ * @since 1.2
*/
public synchronized Object setProperty(String key, String value) {
return put(key, value);
@@ -132,78 +132,86 @@ class CMSProperties extends Hashtable<String,String> {
private static final String whiteSpaceChars = " \t\r\n\f";
/**
- * Reads a property list (key and element pairs) from the input stream.
- * The stream is assumed to be using the ISO 8859-1 character encoding.
+ * Reads a property list (key and element pairs) from the input stream. The
+ * stream is assumed to be using the ISO 8859-1 character encoding.
* <p>
- * Every property occupies one line of the input stream. Each line
- * is terminated by a line terminator (<code>\n</code> or <code>\r</code>
- * or <code>\r\n</code>). Lines from the input stream are processed until
- * end of file is reached on the input stream.
+ * Every property occupies one line of the input stream. Each line is
+ * terminated by a line terminator (<code>\n</code> or <code>\r</code> or
+ * <code>\r\n</code>). Lines from the input stream are processed until end
+ * of file is reached on the input stream.
* <p>
* A line that contains only whitespace or whose first non-whitespace
- * character is an ASCII <code>#</code> or <code>!</code> is ignored
- * (thus, <code>#</code> or <code>!</code> indicate comment lines).
+ * character is an ASCII <code>#</code> or <code>!</code> is ignored (thus,
+ * <code>#</code> or <code>!</code> indicate comment lines).
* <p>
* Every line other than a blank line or a comment line describes one
* property to be added to the table (except that if a line ends with \,
- * then the following line, if it exists, is treated as a continuation
- * line, as described
- * below). The key consists of all the characters in the line starting
- * with the first non-whitespace character and up to, but not including,
- * the first ASCII <code>=</code>, <code>:</code>, or whitespace
- * character. All of the key termination characters may be included in
- * the key by preceding them with a \.
- * Any whitespace after the key is skipped; if the first non-whitespace
- * character after the key is <code>=</code> or <code>:</code>, then it
- * is ignored and any whitespace characters after it are also skipped.
- * All remaining characters on the line become part of the associated
- * element string. Within the element string, the ASCII
- * escape sequences <code>\t</code>, <code>\n</code>,
- * <code>\r</code>, <code>\\</code>, <code>\"</code>, <code>\'</code>,
- * <code>\ &#32;</code> &#32;(a backslash and a space), and
- * <code>&#92;u</code><i>xxxx</i> are recognized and converted to single
- * characters. Moreover, if the last character on the line is
- * <code>\</code>, then the next line is treated as a continuation of the
- * current line; the <code>\</code> and line terminator are simply
- * discarded, and any leading whitespace characters on the continuation
- * line are also discarded and are not part of the element string.
+ * then the following line, if it exists, is treated as a continuation line,
+ * as described below). The key consists of all the characters in the line
+ * starting with the first non-whitespace character and up to, but not
+ * including, the first ASCII <code>=</code>, <code>:</code>, or whitespace
+ * character. All of the key termination characters may be included in the
+ * key by preceding them with a \. Any whitespace after the key is skipped;
+ * if the first non-whitespace character after the key is <code>=</code> or
+ * <code>:</code>, then it is ignored and any whitespace characters after it
+ * are also skipped. All remaining characters on the line become part of the
+ * associated element string. Within the element string, the ASCII escape
+ * sequences <code>\t</code>, <code>\n</code>, <code>\r</code>,
+ * <code>\\</code>, <code>\"</code>, <code>\'</code>, <code>\ &#32;</code>
+ * &#32;(a backslash and a space), and <code>&#92;u</code><i>xxxx</i> are
+ * recognized and converted to single characters. Moreover, if the last
+ * character on the line is <code>\</code>, then the next line is treated as
+ * a continuation of the current line; the <code>\</code> and line
+ * terminator are simply discarded, and any leading whitespace characters on
+ * the continuation line are also discarded and are not part of the element
+ * string.
* <p>
* As an example, each of the following four lines specifies the key
* <code>"Truth"</code> and the associated element value
* <code>"Beauty"</code>:
* <p>
+ *
* <pre>
* Truth = Beauty
- * Truth:Beauty
+ * Truth:Beauty
* Truth :Beauty
* </pre>
- * As another example, the following three lines specify a single
- * property:
+ *
+ * As another example, the following three lines specify a single property:
* <p>
+ *
* <pre>
* fruits apple, banana, pear, \
* cantaloupe, watermelon, \
* kiwi, mango
* </pre>
+ *
* The key is <code>"fruits"</code> and the associated element is:
* <p>
- * <pre>"apple, banana, pear, cantaloupe, watermelon,kiwi, mango"</pre>
- * Note that a space appears before each <code>\</code> so that a space
- * will appear after each comma in the final result; the <code>\</code>,
- * line terminator, and leading whitespace on the continuation line are
- * merely discarded and are <i>not</i> replaced by one or more other
- * characters.
+ *
+ * <pre>
+ * &quot;apple, banana, pear, cantaloupe, watermelon,kiwi, mango&quot;
+ * </pre>
+ *
+ * Note that a space appears before each <code>\</code> so that a space will
+ * appear after each comma in the final result; the <code>\</code>, line
+ * terminator, and leading whitespace on the continuation line are merely
+ * discarded and are <i>not</i> replaced by one or more other characters.
* <p>
* As a third example, the line:
* <p>
- * <pre>cheeses
+ *
+ * <pre>
+ * cheeses
* </pre>
+ *
* specifies that the key is <code>"cheeses"</code> and the associated
- * element is the empty string.<p>
- *
- * @param inStream the input stream.
- * @exception IOException if an error occurred when reading from the
- * input stream.
+ * element is the empty string.
+ * <p>
+ *
+ * @param inStream the input stream.
+ * @exception IOException if an error occurred when reading from the input
+ * stream.
*/
public synchronized void load(InputStream inStream) throws IOException {
@@ -235,8 +243,7 @@ class CMSProperties extends Hashtable<String,String> {
for (startIndex = 0; startIndex < nextLine.length(); startIndex++) {
if (whiteSpaceChars.indexOf(
- nextLine.charAt(startIndex))
- == -1) {
+ nextLine.charAt(startIndex)) == -1) {
break;
}
}
@@ -277,8 +284,7 @@ class CMSProperties extends Hashtable<String,String> {
int valueIndex;
for (valueIndex = separatorIndex; valueIndex < len; valueIndex++) {
- if (whiteSpaceChars.indexOf(line.charAt(valueIndex))
- == -1) {
+ if (whiteSpaceChars.indexOf(line.charAt(valueIndex)) == -1) {
break;
}
}
@@ -286,16 +292,14 @@ class CMSProperties extends Hashtable<String,String> {
// Skip over one non whitespace key value separators if any
if (valueIndex < len) {
if (strictKeyValueSeparators.indexOf(
- line.charAt(valueIndex))
- != -1) {
+ line.charAt(valueIndex)) != -1) {
valueIndex++;
}
}
// Skip over white space after other separators if any
while (valueIndex < len) {
- if (whiteSpaceChars.indexOf(line.charAt(valueIndex))
- == -1) {
+ if (whiteSpaceChars.indexOf(line.charAt(valueIndex)) == -1) {
break;
}
valueIndex++;
@@ -315,8 +319,8 @@ class CMSProperties extends Hashtable<String,String> {
}
/*
- * Returns true if the given line is a line that must
- * be appended to the next line
+ * Returns true if the given line is a line that must be appended to the
+ * next line
*/
private boolean continueLine(String line) {
int slashCount = 0;
@@ -329,8 +333,8 @@ class CMSProperties extends Hashtable<String,String> {
}
/*
- * Converts encoded &#92;uxxxx to unicode chars
- * and changes special saved chars to their original forms
+ * Converts encoded &#92;uxxxx to unicode chars and changes special saved
+ * chars to their original forms
*/
private String loadConvert(String theString) {
char aChar;
@@ -405,9 +409,8 @@ class CMSProperties extends Hashtable<String,String> {
}
/*
- * Converts unicodes to encoded &#92;uxxxx
- * and writes out any of the characters in specialSaveChars
- * with a preceding slash
+ * Converts unicodes to encoded &#92;uxxxx and writes out any of the
+ * characters in specialSaveChars with a preceding slash
*/
private String saveConvert(String theString, boolean escapeSpace) {
int len = theString.length();
@@ -418,7 +421,7 @@ class CMSProperties extends Hashtable<String,String> {
switch (aChar) {
case ' ':
- if (x == 0 || escapeSpace) {
+ if (x == 0 || escapeSpace) {
outBuffer.append('\\');
}
@@ -470,53 +473,56 @@ class CMSProperties extends Hashtable<String,String> {
}
/**
- * Calls the <code>store(OutputStream out, String header)</code> method
- * and suppresses IOExceptions that were thrown.
- *
+ * Calls the <code>store(OutputStream out, String header)</code> method and
+ * suppresses IOExceptions that were thrown.
+ *
* @deprecated This method does not throw an IOException if an I/O error
- * occurs while saving the property list. As of the Java 2 platform v1.2, the preferred
- * way to save a properties list is via the <code>store(OutputStream out,
+ * occurs while saving the property list. As of the Java 2
+ * platform v1.2, the preferred way to save a properties list is
+ * via the <code>store(OutputStream out,
* String header)</code> method.
- *
- * @param out an output stream.
- * @param header a description of the property list.
- * @exception ClassCastException if this <code>Properties</code> object
- * contains any keys or values that are not <code>Strings</code>.
+ *
+ * @param out an output stream.
+ * @param header a description of the property list.
+ * @exception ClassCastException if this <code>Properties</code> object
+ * contains any keys or values that are not
+ * <code>Strings</code>.
*/
public synchronized void save(OutputStream out, String header) {
try {
store(out, header);
- } catch (IOException e) {}
+ } catch (IOException e) {
+ }
}
/**
* Writes this property list (key and element pairs) in this
* <code>Properties</code> table to the output stream in a format suitable
* for loading into a <code>Properties</code> table using the
- * <code>load</code> method.
- * The stream is written using the ISO 8859-1 character encoding.
+ * <code>load</code> method. The stream is written using the ISO 8859-1
+ * character encoding.
* <p>
- * Properties from the defaults table of this <code>Properties</code>
- * table (if any) are <i>not</i> written out by this method.
+ * Properties from the defaults table of this <code>Properties</code> table
+ * (if any) are <i>not</i> written out by this method.
* <p>
* If the header argument is not null, then an ASCII <code>#</code>
- * character, the header string, and a line separator are first written
- * to the output stream. Thus, the <code>header</code> can serve as an
+ * character, the header string, and a line separator are first written to
+ * the output stream. Thus, the <code>header</code> can serve as an
* identifying comment.
* <p>
* Next, a comment line is always written, consisting of an ASCII
- * <code>#</code> character, the current date and time (as if produced
- * by the <code>toString</code> method of <code>Date</code> for the
- * current time), and a line separator as generated by the Writer.
+ * <code>#</code> character, the current date and time (as if produced by
+ * the <code>toString</code> method of <code>Date</code> for the current
+ * time), and a line separator as generated by the Writer.
* <p>
* Then every entry in this <code>Properties</code> table is written out,
* one per line. For each entry the key string is written, then an ASCII
- * <code>=</code>, then the associated element string. Each character of
- * the element string is examined to see whether it should be rendered as
- * an escape sequence. The ASCII characters <code>\</code>, tab, newline,
- * and carriage return are written as <code>\\</code>, <code>\t</code>,
- * <code>\n</code>, and <code>\r</code>, respectively. Characters less
- * than <code>&#92;u0020</code> and characters greater than
+ * <code>=</code>, then the associated element string. Each character of the
+ * element string is examined to see whether it should be rendered as an
+ * escape sequence. The ASCII characters <code>\</code>, tab, newline, and
+ * carriage return are written as <code>\\</code>, <code>\t</code>,
+ * <code>\n</code>, and <code>\r</code>, respectively. Characters less than
+ * <code>&#92;u0020</code> and characters greater than
* <code>&#92;u007E</code> are written as <code>&#92;u</code><i>xxxx</i> for
* the appropriate hexadecimal value <i>xxxx</i>. Leading space characters,
* but not embedded or trailing space characters, are written with a
@@ -524,18 +530,19 @@ class CMSProperties extends Hashtable<String,String> {
* <code>!</code>, <code>=</code>, and <code>:</code> are written with a
* preceding slash to ensure that they are properly loaded.
* <p>
- * After the entries have been written, the output stream is flushed. The
+ * After the entries have been written, the output stream is flushed. The
* output stream remains open after this method returns.
- *
- * @param out an output stream.
- * @param header a description of the property list.
- * @exception IOException if writing this property list to the specified
- * output stream throws an <tt>IOException</tt>.
- * @exception ClassCastException if this <code>Properties</code> object
- * contains any keys or values that are not <code>Strings</code>.
+ *
+ * @param out an output stream.
+ * @param header a description of the property list.
+ * @exception IOException if writing this property list to the specified
+ * output stream throws an <tt>IOException</tt>.
+ * @exception ClassCastException if this <code>Properties</code> object
+ * contains any keys or values that are not
+ * <code>Strings</code>.
*/
public synchronized void store(OutputStream out, String header)
- throws IOException {
+ throws IOException {
BufferedWriter awriter;
awriter = new BufferedWriter(new OutputStreamWriter(out, "8859_1"));
@@ -544,12 +551,13 @@ class CMSProperties extends Hashtable<String,String> {
}
writeln(awriter, "#" + new Date().toString());
for (Enumeration<String> e = keys(); e.hasMoreElements();) {
- String key = e.nextElement();
- String val = get(key);
+ String key = e.nextElement();
+ String val = get(key);
key = saveConvert(key, true);
- /* No need to escape embedded and trailing spaces for value, hence
+ /*
+ * No need to escape embedded and trailing spaces for value, hence
* pass false to flag.
*/
val = saveConvert(val, false);
@@ -568,15 +576,15 @@ class CMSProperties extends Hashtable<String,String> {
* If the key is not found in this property list, the default property list,
* and its defaults, recursively, are then checked. The method returns
* <code>null</code> if the property is not found.
- *
- * @param key the property key.
- * @return the value in this property list with the specified key value.
- * @see #setProperty
- * @see #defaults
+ *
+ * @param key the property key.
+ * @return the value in this property list with the specified key value.
+ * @see #setProperty
+ * @see #defaults
*/
public String getProperty(String key) {
String oval = super.get(key);
- String sval = (oval instanceof String) ? oval : null;
+ String sval = (oval instanceof String) ? oval : null;
return ((sval == null) && (defaults != null))
? defaults.getProperty(key)
@@ -588,13 +596,13 @@ class CMSProperties extends Hashtable<String,String> {
* If the key is not found in this property list, the default property list,
* and its defaults, recursively, are then checked. The method returns the
* default value argument if the property is not found.
- *
- * @param key the hashtable key.
- * @param defaultValue a default value.
- *
- * @return the value in this property list with the specified key value.
- * @see #setProperty
- * @see #defaults
+ *
+ * @param key the hashtable key.
+ * @param defaultValue a default value.
+ *
+ * @return the value in this property list with the specified key value.
+ * @see #setProperty
+ * @see #defaults
*/
public String getProperty(String key, String defaultValue) {
String val = getProperty(key);
@@ -605,11 +613,11 @@ class CMSProperties extends Hashtable<String,String> {
/**
* Returns an enumeration of all the keys in this property list, including
* the keys in the default property list.
- *
- * @return an enumeration of all the keys in this property list, including
- * the keys in the default property list.
- * @see java.util.Enumeration
- * @see java.util.Properties#defaults
+ *
+ * @return an enumeration of all the keys in this property list, including
+ * the keys in the default property list.
+ * @see java.util.Enumeration
+ * @see java.util.Properties#defaults
*/
public Enumeration<String> propertyNames() {
Hashtable<String, String> h = new Hashtable<String, String>();
@@ -619,10 +627,10 @@ class CMSProperties extends Hashtable<String,String> {
}
/**
- * Prints this property list out to the specified output stream.
- * This method is useful for debugging.
- *
- * @param out an output stream.
+ * Prints this property list out to the specified output stream. This method
+ * is useful for debugging.
+ *
+ * @param out an output stream.
*/
public void list(PrintStream out) {
out.println("-- listing properties --");
@@ -630,8 +638,8 @@ class CMSProperties extends Hashtable<String,String> {
enumerate(h);
for (Enumeration<String> e = h.keys(); e.hasMoreElements();) {
- String key = e.nextElement();
- String val = h.get(key);
+ String key = e.nextElement();
+ String val = h.get(key);
if (val.length() > 40) {
val = val.substring(0, 37) + "...";
@@ -641,13 +649,13 @@ class CMSProperties extends Hashtable<String,String> {
}
/**
- * Prints this property list out to the specified output stream.
- * This method is useful for debugging.
- *
- * @param out an output stream.
- * @since JDK1.1
+ * Prints this property list out to the specified output stream. This method
+ * is useful for debugging.
+ *
+ * @param out an output stream.
+ * @since JDK1.1
*/
-
+
/*
* Rather than use an anonymous inner class to share common code, this
* method is duplicated in order to ensure that a non-1.1 compiler can
@@ -659,8 +667,8 @@ class CMSProperties extends Hashtable<String,String> {
enumerate(h);
for (Enumeration<String> e = h.keys(); e.hasMoreElements();) {
- String key = e.nextElement();
- String val = h.get(key);
+ String key = e.nextElement();
+ String val = h.get(key);
if (val.length() > 40) {
val = val.substring(0, 37) + "...";
@@ -671,6 +679,7 @@ class CMSProperties extends Hashtable<String,String> {
/**
* Enumerates all key/value pairs in the specified hastable.
+ *
* @param h the hashtable
*/
private synchronized void enumerate(Hashtable<String, String> h) {
@@ -678,7 +687,7 @@ class CMSProperties extends Hashtable<String,String> {
defaults.enumerate(h);
}
for (Enumeration<String> e = keys(); e.hasMoreElements();) {
- String key = e.nextElement();
+ String key = e.nextElement();
h.put(key, get(key));
}
@@ -686,7 +695,8 @@ class CMSProperties extends Hashtable<String,String> {
/**
* Convert a nibble to a hex character
- * @param nibble the nibble to convert.
+ *
+ * @param nibble the nibble to convert.
*/
private static char toHex(int nibble) {
return hexDigit[(nibble & 0xF)];
@@ -694,7 +704,7 @@ class CMSProperties extends Hashtable<String,String> {
/** A table of hex digits */
private static final char[] hexDigit = {
- '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
- 'E', 'F'
+ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
+ 'E', 'F'
};
}
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/CMSTask.java b/pki/base/silent/src/com/netscape/pkisilent/common/CMSTask.java
index 593de383..5f2dcb4f 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/CMSTask.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/CMSTask.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.common;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -24,10 +25,8 @@ import java.io.InputStreamReader;
import com.netscape.pkisilent.argparser.ArgParser;
import com.netscape.pkisilent.argparser.StringHolder;
-
/**
- * CS Test framework .
- * This class starts and stops CS server from command line
+ * CS Test framework . This class starts and stops CS server from command line
*/
public class CMSTask {
@@ -38,8 +37,8 @@ public class CMSTask {
private Process p = null;
/**
- * Constructor . Takes CMS server root as parameter
- * for example (/export/qa/cert-jupiter2)
+ * Constructor . Takes CMS server root as parameter for example
+ * (/export/qa/cert-jupiter2)
**/
public CMSTask() {// do nothing
@@ -63,7 +62,7 @@ public class CMSTask {
try {
while ((s = br.readLine()) != null) {
- if (s.indexOf("started") > 0) {
+ if (s.indexOf("started") > 0) {
return true;
}
// do something
@@ -175,7 +174,7 @@ public class CMSTask {
// set variables
serverRoot = x_instance_root.value;
operation = x_operation.value;
-
+
boolean st = prof.task();
if (!st) {
@@ -186,5 +185,5 @@ public class CMSTask {
} // end of function main
-} // end of class
+} // end of class
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/CertificateRecord.java b/pki/base/silent/src/com/netscape/pkisilent/common/CertificateRecord.java
index c636b0a1..9599eb6d 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/CertificateRecord.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/CertificateRecord.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.common;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -17,8 +18,6 @@ package com.netscape.pkisilent.common;
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
-
-
public class CertificateRecord {
public String revokedOn = null;
@@ -42,7 +41,4 @@ public class CertificateRecord {
public CertificateRecord() {// Do nothing
}
-}
-
-
-;
+};
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/ComCrypto.java b/pki/base/silent/src/com/netscape/pkisilent/common/ComCrypto.java
index 46bd9664..68922532 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/ComCrypto.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/ComCrypto.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.common;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -64,13 +65,11 @@ import org.mozilla.jss.util.Password;
import com.netscape.osutil.OSUtil;
-
/**
- * CMS Test framework .
- * Use this class to initalize,add a certificate ,generate a certificate request from certificate database.
+ * CMS Test framework . Use this class to initalize,add a certificate ,generate
+ * a certificate request from certificate database.
*/
-
public class ComCrypto {
private String cdir, certnickname, keysize, keytype, tokenpwd;
@@ -98,19 +97,20 @@ public class ComCrypto {
private String certprefix = null;
- public ComCrypto() {}
- ;
+ public ComCrypto() {
+ };
/**
- * Constructor . Takes the parameter certificatedbdirectory , passwordfor cert database, certificatenickname,keysize, keytype(RSA/DSA)
+ * Constructor . Takes the parameter certificatedbdirectory , passwordfor
+ * cert database, certificatenickname,keysize, keytype(RSA/DSA)
+ *
* @param certdbdirectory.
- * @param certdbpassword
- * @param certnickname
+ * @param certdbpassword
+ * @param certnickname
* @param keysize (1024/2048/4096)
* @param keytype (RSA/DSA)
*/
-
public ComCrypto(String cd, String tpwd, String cn, String ks, String kt) {
cdir = cd;
tokenpwd = tpwd;
@@ -119,7 +119,7 @@ public class ComCrypto {
keytype = kt;
}
- // Set and Get functions
+ // Set and Get functions
public void setCertDir(String cd) {
cdir = cd;
@@ -158,10 +158,9 @@ public class ComCrypto {
}
/*
- * setTransportCert() should only be called when the calling profile
- * needs to do key archivals with the DRM and make sure the function
- * generateCRMFtransport() is called for the CRMF request generation
- * part.
+ * setTransportCert() should only be called when the calling profile needs
+ * to do key archivals with the DRM and make sure the function
+ * generateCRMFtransport() is called for the CRMF request generation part.
*/
public void setTransportCert(String tcert) {
transportcert = tcert;
@@ -176,7 +175,8 @@ public class ComCrypto {
}
/**
- * Parses the Certificate and returns SubjectDN . Takes certificate as parameter
+ * Parses the Certificate and returns SubjectDN . Takes certificate as
+ * parameter
*/
public String getCertificateString(X509Certificate cert) {
@@ -190,10 +190,9 @@ public class ComCrypto {
}
/**
- * Finds and returns Certificate . Takes certificatenickname as parameter.
+ * Finds and returns Certificate . Takes certificatenickname as parameter.
*/
-
public X509Certificate findCert(String certname) {
try {
@@ -209,10 +208,10 @@ public class ComCrypto {
}
/**
- * Imports a certificate to Certificate Database. Takes certificate and nickname as parameters.
+ * Imports a certificate to Certificate Database. Takes certificate and
+ * nickname as parameters.
*/
-
public boolean importCert(X509Certificate xcert, String nickname) {
try {
@@ -232,10 +231,10 @@ public class ComCrypto {
}
/**
- * Imports a certificate to Certificate Database. Takes certificate and nickname as parameters.
+ * Imports a certificate to Certificate Database. Takes certificate and
+ * nickname as parameters.
*/
-
public boolean importCert(String cpack, String cn) {
System.out.println("importCert string: importing with nickname: " + cn);
@@ -243,7 +242,7 @@ public class ComCrypto {
String tmp = normalize(cpack);
- if (DBlogin) {
+ if (DBlogin) {
System.out.println("Already logged into to DB");
}
@@ -264,7 +263,8 @@ public class ComCrypto {
}
- /* imports CA certificate
+ /*
+ * imports CA certificate
*/
public boolean importCACert(String cpack) {
@@ -272,10 +272,10 @@ public class ComCrypto {
try {
String tmp = normalize(cpack);
- if (DBlogin) {
+ if (DBlogin) {
System.out.println("Already logged into to DB");
}
-
+
if (manager == null) {
System.out.println("Manager object is null");
}
@@ -293,10 +293,10 @@ public class ComCrypto {
}
/**
- * Normalizes a given certificate string . Removes the extra \\ in the certificate returned by CMS server.
+ * Normalizes a given certificate string . Removes the extra \\ in the
+ * certificate returned by CMS server.
*/
-
public String normalize(String s) {
String val = "";
@@ -318,10 +318,10 @@ public class ComCrypto {
}
/**
- * Normalizes a given certificate string . Removes the extra \\ in the certificate returned by CMS server.
+ * Normalizes a given certificate string . Removes the extra \\ in the
+ * certificate returned by CMS server.
*/
-
public String normalizeForLDAP(String s) {
String val = "";
@@ -346,7 +346,6 @@ public class ComCrypto {
* Convert to pkcs7 format
*/
-
public String pkcs7Convertcert(String s) {
String val = "";
@@ -396,14 +395,13 @@ public class ComCrypto {
* Creates a new certificate database
**/
-
public boolean CreateCertDB() {
return loginDB();
}
/**
- * Login to cert database
+ * Login to cert database
**/
public boolean loginDB() {
@@ -439,15 +437,15 @@ public class ComCrypto {
token.login(pass1);
pass1.clear();
- } catch (AlreadyInitializedException e) {
+ } catch (AlreadyInitializedException e) {
if (debug) {
System.out.println("Crypto manager already initialized");
}
} catch (Exception e) {
- try {
+ try {
if (!token.isLoggedIn()) {
token.initPassword(pass1, pass1);
- }
+ }
return true;
} catch (Exception er) {
System.err.println("some exception:" + e);
@@ -507,35 +505,35 @@ public class ComCrypto {
int num = 1;
long total_time = 0;
KeyPair pair = null;
-
- System.out.println("Debug : initialize crypto Manager");
+
+ System.out.println("Debug : initialize crypto Manager");
try {
// Step 1. initialize crypto Manager
- try {
+ try {
CryptoManager.initialize(cdir);
- } catch (Exception e) {
- // it is ok if it is already initialized
+ } catch (Exception e) {
+ // it is ok if it is already initialized
System.out.println("INITIALIZATION ERROR: " + e.toString());
System.out.println("cdir = " + cdir);
}
- // Step 2 log into database
+ // Step 2 log into database
try {
System.out.println("Debug : before getInstance");
- manager = CryptoManager.getInstance();
+ manager = CryptoManager.getInstance();
String token_pwd = tokenpwd;
System.out.println("Debug : before get token");
- token = manager.getInternalKeyStorageToken();
- password = new Password(token_pwd.toCharArray());
+ token = manager.getInternalKeyStorageToken();
+ password = new Password(token_pwd.toCharArray());
System.out.println("Debug : before login password");
- token.login(password);
+ token.login(password);
System.out.println("Debug : after login password");
} catch (Exception e) {
@@ -546,9 +544,9 @@ public class ComCrypto {
}
}
- // Generating CRMF request
+ // Generating CRMF request
- KeyPairGenerator kg = token.getKeyPairGenerator(KeyPairAlgorithm.RSA);
+ KeyPairGenerator kg = token.getKeyPairGenerator(KeyPairAlgorithm.RSA);
Integer x = new Integer(keysize);
int key_len = x.intValue();
@@ -556,7 +554,7 @@ public class ComCrypto {
kg.initialize(key_len);
// 1st key pair
- pair = kg.genKeyPair();
+ pair = kg.genKeyPair();
// create CRMF
CertTemplate certTemplate = new CertTemplate();
@@ -565,7 +563,7 @@ public class ComCrypto {
if (certnickname != null) {
X500Name name = new X500Name(certnickname);
- ByteArrayInputStream cs = new ByteArrayInputStream(name.getEncoded());
+ ByteArrayInputStream cs = new ByteArrayInputStream(name.getEncoded());
Name n = (Name) Name.getTemplate().decode(cs);
certTemplate.setSubject(n);
}
@@ -575,7 +573,7 @@ public class ComCrypto {
SEQUENCE seq = new SEQUENCE();
CertRequest certReq = new CertRequest(new INTEGER(1), certTemplate,
seq);
- byte popdata[] = { 0x0, 0x3, 0x0};
+ byte popdata[] = { 0x0, 0x3, 0x0 };
ProofOfPossession pop = ProofOfPossession.createKeyEncipherment(
POPOPrivKey.createThisMessage(new BIT_STRING(popdata, 3)));
@@ -583,35 +581,35 @@ public class ComCrypto {
CertReqMsg crmfMsg = new CertReqMsg(certReq, pop, null);
SEQUENCE s1 = new SEQUENCE();
-
- // 1st : Encryption key
+
+ // 1st : Encryption key
s1.addElement(crmfMsg);
// 2nd : Signing Key
-
+
if (dualkey) {
System.out.println("dualkey = true");
SEQUENCE seq1 = new SEQUENCE();
CertRequest certReqSigning = new CertRequest(new INTEGER(1),
certTemplate, seq1);
- CertReqMsg signingMsg = new CertReqMsg(certReqSigning, pop, null);
+ CertReqMsg signingMsg = new CertReqMsg(certReqSigning, pop, null);
s1.addElement(signingMsg);
- }
+ }
- byte encoded[] = ASN1Util.encode(s1);
+ byte encoded[] = ASN1Util.encode(s1);
- // BASE64Encoder encoder = new BASE64Encoder();
+ // BASE64Encoder encoder = new BASE64Encoder();
// String Req1 = encoder.encodeBuffer(encoded);
String Req1 = OSUtil.BtoA(encoded);
- // Set CRMF_REQUEST variable
+ // Set CRMF_REQUEST variable
CRMF_REQUEST = Req1;
System.out.println("CRMF_REQUEST = " + CRMF_REQUEST);
- } catch (Exception e) {
+ } catch (Exception e) {
System.out.println("ERROR: " + e.toString());
e.printStackTrace();
return null;
@@ -621,10 +619,10 @@ public class ComCrypto {
}
/*
- * This function is used to Generated CRMF requests wrapped with the
- * transport cert so that we can do key archival with the drm.
- * This function expects transportcert variable to be set in this class.
- * Use setTransportCert() to do the same.
+ * This function is used to Generated CRMF requests wrapped with the
+ * transport cert so that we can do key archival with the drm. This function
+ * expects transportcert variable to be set in this class. Use
+ * setTransportCert() to do the same.
*/
public String generateCRMFtransport() {
@@ -636,30 +634,30 @@ public class ComCrypto {
try {
// Step 1. initialize crypto Manager
- try {
+ try {
CryptoManager.initialize(cdir);
- } catch (Exception e) {
- // it is ok if it is already initialized
+ } catch (Exception e) {
+ // it is ok if it is already initialized
System.out.println("INITIALIZATION ERROR: " + e.toString());
System.out.println("cdir = " + cdir);
}
- // Step 2 log into database
+ // Step 2 log into database
try {
System.out.println("Debug : before getInstance");
-
- manager = CryptoManager.getInstance();
+
+ manager = CryptoManager.getInstance();
String token_pwd = tokenpwd;
-
+
System.out.println("Debug : before get token");
-
- token = manager.getInternalKeyStorageToken();
- password = new Password(token_pwd.toCharArray());
+
+ token = manager.getInternalKeyStorageToken();
+ password = new Password(token_pwd.toCharArray());
System.out.println("Debug : before login password");
- token.login(password);
+ token.login(password);
System.out.println("Debug : after login password");
} catch (Exception e) {
@@ -669,7 +667,7 @@ public class ComCrypto {
token.initPassword(password, password);
}
}
-
+
// Key Pair Generation
KeyPairGenerator kg = token.getKeyPairGenerator(KeyPairAlgorithm.RSA);
Integer x = new Integer(keysize);
@@ -686,7 +684,7 @@ public class ComCrypto {
X509Certificate tcert = manager.importCACertPackage(transport);
- byte iv[] = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1};
+ byte iv[] = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 };
KeyGenerator kg1 = token.getKeyGenerator(KeyGenAlgorithm.DES3);
SymmetricKey sk = kg1.generate();
@@ -742,7 +740,7 @@ public class ComCrypto {
seq);
// Adding proof of possesion data
- byte popdata[] = { 0x0, 0x3, 0x0};
+ byte popdata[] = { 0x0, 0x3, 0x0 };
ProofOfPossession pop = ProofOfPossession.createKeyEncipherment(
POPOPrivKey.createThisMessage(new BIT_STRING(popdata, 3)));
@@ -750,23 +748,23 @@ public class ComCrypto {
SEQUENCE s1 = new SEQUENCE();
- // 1st : Encryption key
+ // 1st : Encryption key
s1.addElement(crmfMsg);
// 2nd : Signing Key
-
+
if (dualkey) {
System.out.println("dualkey = true");
SEQUENCE seq1 = new SEQUENCE();
CertRequest certReqSigning = new CertRequest(new INTEGER(1),
certTemplate, seq1);
- CertReqMsg signingMsg = new CertReqMsg(certReqSigning, pop, null);
+ CertReqMsg signingMsg = new CertReqMsg(certReqSigning, pop, null);
s1.addElement(signingMsg);
- }
+ }
byte encoded[] = ASN1Util.encode(s1);
-
+
// BASE64Encoder encoder = new BASE64Encoder();
// CRMF_REQUEST = encoder.encodeBuffer(encoded);
@@ -781,9 +779,9 @@ public class ComCrypto {
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
-
+
return CRMF_REQUEST;
}
-} // end of class
+} // end of class
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/Con2Agent.java b/pki/base/silent/src/com/netscape/pkisilent/common/Con2Agent.java
index 6be4daf4..231ce1b3 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/Con2Agent.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/Con2Agent.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.common;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -35,10 +36,9 @@ import org.mozilla.jss.ssl.SSLClientCertificateSelectionCallback;
import org.mozilla.jss.ssl.SSLSocket;
import org.mozilla.jss.util.Password;
-
/**
- * CMS Test framework .
- * Submits a requests to agent port with sslclient authentication.
+ * CMS Test framework . Submits a requests to agent port with sslclient
+ * authentication.
*/
public class Con2Agent implements SSLClientCertificateSelectionCallback,
@@ -51,18 +51,20 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
private BufferedReader stdin = null;
private StringBuffer stdout = new StringBuffer();
- public Con2Agent() {}
+ public Con2Agent() {
+ }
/**
- *Constructor. Takes hostname , portnumber , certificate nickname, token password ,client certdb directory
- * @param hostname
+ * Constructor. Takes hostname , portnumber , certificate nickname, token
+ * password ,client certdb directory
+ *
+ * @param hostname
* @param portnumber
* @param agent cert nickname
- * @param token password
+ * @param token password
* @param certdb directory
*/
-
public Con2Agent(String hs, int p, String cname, String tpwd, String cdir) {
host = hs;
port = p;
@@ -95,10 +97,10 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
}
- // Get and Set methods
+ // Get and Set methods
/*
- * Get the page returned by the server
+ * Get the page returned by the server
*/
public StringBuffer getPage() {
@@ -106,7 +108,7 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
}
/*
- * Set the query string to be submitted to the server
+ * Set the query string to be submitted to the server
*/
public void setQueryString(String qu) {
@@ -114,7 +116,7 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
}
/*
- *Set token password
+ * Set token password
*/
public void setTokenPassword(String pwd) {
@@ -138,7 +140,7 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
}
/*
- * set Agent port number
+ * set Agent port number
*/
public void setPort(int p) {
@@ -146,7 +148,7 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
}
/*
- * Set Agent cert nickname
+ * Set Agent cert nickname
*/
public void setCertNickName(String cname) {
@@ -154,21 +156,21 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
}
/*
- * Set action URL
+ * Set action URL
*/
public void setActionURL(String url) {
ACTIONURL = url;
}
- // Submit requests
+ // Submit requests
public boolean Send() {
boolean st = false;
try {
- if (!loginCertDB()) {
+ if (!loginCertDB()) {
return false;
}
@@ -184,7 +186,7 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
OutputStream rawos = socket.getOutputStream();
BufferedOutputStream os = new BufferedOutputStream(rawos);
PrintStream ps = new PrintStream(os);
-
+
System.out.println(ACTIONURL);
System.out.println("Query :" + query);
ps.println("POST " + ACTIONURL + " HTTP/1.0");
@@ -205,8 +207,9 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
System.out.println(line);
}
- // Send Connection: close to let the server close the connection.
- // Else the socket on the server side continues to remain in TIME_WAIT state
+ // Send Connection: close to let the server close the connection.
+ // Else the socket on the server side continues to remain in
+ // TIME_WAIT state
ps.println("Connection: close");
ps.flush();
@@ -239,12 +242,12 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
try {
System.out.println("Step 1: Initializing CryptoManager");
CryptoManager.initialize(certdir);
-
- System.out.println("Step 2: Login to Cert Database");
+
+ System.out.println("Step 2: Login to Cert Database");
manager = CryptoManager.getInstance();
CryptoToken token = (PK11Token) manager.getInternalKeyStorageToken();
- if (token.isLoggedIn()) {
+ if (token.isLoggedIn()) {
System.out.println("Con2Agent: Logged in incorrect");
}
@@ -256,12 +259,12 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
pass1 = new Password((char[]) passchar1.clone());
token.login(pass1);
- X509Certificate cert2 = manager.findCertByNickname(certnickname);
+ X509Certificate cert2 = manager.findCertByNickname(certnickname);
certname = cert2.getNickname();
return true;
- } catch (AlreadyInitializedException e) {
+ } catch (AlreadyInitializedException e) {
System.out.println("Crypto manager already initialized");
return true;
} catch (NumberFormatException e) {
@@ -276,7 +279,7 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
e.printStackTrace();
return false;
}
-
+
}
public boolean Send_withGET() {
@@ -285,7 +288,7 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
try {
- if (!loginCertDB()) {
+ if (!loginCertDB()) {
return false;
}
@@ -297,7 +300,7 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
OutputStream rawos = socket.getOutputStream();
BufferedOutputStream os = new BufferedOutputStream(rawos);
PrintStream ps = new PrintStream(os);
-
+
System.out.println("Query in con2agent :" + query);
System.out.println("ACTIONURL in con2agent : " + ACTIONURL);
@@ -326,4 +329,4 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
}
-} // end of class
+} // end of class
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/DirEnroll.java b/pki/base/silent/src/com/netscape/pkisilent/common/DirEnroll.java
index 59820fe7..723485b8 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/DirEnroll.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/DirEnroll.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.common;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -17,7 +18,6 @@ package com.netscape.pkisilent.common;
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
-
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
@@ -29,15 +29,13 @@ import java.util.GregorianCalendar;
import org.mozilla.jss.ssl.SSLSocket;
-
-
/**
- * CMS Test framework - Legacyenrollment forms for Directory based enrollmnet and Portal based enrollment .
- * Certificate issuance through Legacy Directory based enrollment and Portal based enrollment form.
- *<P>
+ * CMS Test framework - Legacyenrollment forms for Directory based enrollmnet
+ * and Portal based enrollment . Certificate issuance through Legacy Directory
+ * based enrollment and Portal based enrollment form.
+ * <P>
*/
-
public class DirEnroll extends TestClient {
private int i;
@@ -53,7 +51,8 @@ public class DirEnroll extends TestClient {
/**
* Constructor . Takes the parameter for Properties file name
* <p>
- * @param propfilename name of the parameter file
+ *
+ * @param propfilename name of the parameter file
*/
public DirEnroll(String pfile) {
@@ -63,6 +62,7 @@ public class DirEnroll extends TestClient {
/**
* Constructor. Takes hostname , EESSLportnumber as parameter
* <p>
+ *
* @param hostname
* @param portnumber
*/
@@ -73,8 +73,11 @@ public class DirEnroll extends TestClient {
}
/**
- * Constructor. Takes hostname,EESSLportnumber,uid,password,certdbdirectorypath,certdbpassword,certificatenickname,keysize,teytype
+ * Constructor. Takes
+ * hostname,EESSLportnumber,uid,password,certdbdirectorypath
+ * ,certdbpassword,certificatenickname,keysize,teytype
* <p>
+ *
* @param hostname
* @param portnumber
* @param subjectdn
@@ -82,7 +85,6 @@ public class DirEnroll extends TestClient {
* @param adminpassword
*/
-
public DirEnroll(String hs, String p, String uid, String pw, String certdir, String certtokenpwd, String nickname, String ksz, String kt) {
host = hs;
@@ -96,18 +98,18 @@ public class DirEnroll extends TestClient {
keytype = "RSA";
}
- // Set and Get functions
+ // Set and Get functions
/**
- * Use this method to set User Info
- */
+ * Use this method to set User Info
+ */
public void setUIDInfo(String uid, String pw) {
UID = uid;
PWD = pw;
}
/**
- * Returns a string "UserDir" / "Portal"
+ * Returns a string "UserDir" / "Portal"
*/
public String getAuthenticator() {
@@ -115,16 +117,16 @@ public class DirEnroll extends TestClient {
}
/**
- * Valid values for s - UserDir for Directory based Authntication
- * Portal for Portal based Authentication
+ * Valid values for s - UserDir for Directory based Authntication Portal for
+ * Portal based Authentication
*/
- public void setAuthenticator(String s) {
+ public void setAuthenticator(String s) {
Authenticator = s;
}
public boolean enroll_load() {
buildquery();
- return(Send());
+ return (Send());
}
private boolean pkcs10() {
@@ -134,7 +136,7 @@ public class DirEnroll extends TestClient {
cCrypt.setKeySize(keysize);
cCrypt.setKeyType(keytype);
cCrypt.setTokenPWD(tokenpwd);
-
+
cCrypt.setDebug(debug);
cCrypt.setGenerateRequest(true);
if (!cCrypt.generateRequest()) {
@@ -147,7 +149,7 @@ public class DirEnroll extends TestClient {
buildquery();
System.out.println(query);
setStatusString("Congratulations, your certificate has been issued.");
- return(Send());
+ return (Send());
} catch (Exception e) {
System.err.println("some exception:" + e);
}
@@ -157,10 +159,11 @@ public class DirEnroll extends TestClient {
}
/**
- * Enroll for certificate . Before calling this mentod SetAuthenticator and setUIDInfo
+ * Enroll for certificate . Before calling this mentod SetAuthenticator and
+ * setUIDInfo
*/
public boolean enroll() {
- return(pkcs10());
+ return (pkcs10());
}
private boolean readProperties() {
@@ -212,7 +215,7 @@ public class DirEnroll extends TestClient {
return true;
}
- // Private functions
+ // Private functions
private boolean importCert(String certpack) {
@@ -310,7 +313,7 @@ public class DirEnroll extends TestClient {
}
if (line.indexOf("record.base64Cert=") > -1) {
- String baseCert = line;
+ String baseCert = line;
System.out.println("BaseCert : " + baseCert);
if (importcert.equals("true")) {
@@ -352,13 +355,13 @@ public class DirEnroll extends TestClient {
}
return st;
-
+
}
private void buildquery() {
StringBuffer queryStrBuf = new StringBuffer();
-
+
queryStrBuf.append("certType=client");
queryStrBuf.append("&importCert=off");
queryStrBuf.append("&non_repudiation=true");
@@ -376,7 +379,7 @@ public class DirEnroll extends TestClient {
queryStrBuf.append(URLEncoder.encode(UID));
queryStrBuf.append("&pwd=");
queryStrBuf.append(URLEncoder.encode(PWD));
- queryStrBuf.append("&email=true");
+ queryStrBuf.append("&email=true");
queryStrBuf.append("&cryptprovider=1");
}
@@ -412,7 +415,7 @@ public class DirEnroll extends TestClient {
queryStrBuf.append("&l=");
queryStrBuf.append(URLEncoder.encode(L));
- queryStrBuf.append("&email=true");
+ queryStrBuf.append("&email=true");
}
@@ -423,7 +426,7 @@ public class DirEnroll extends TestClient {
queryStrBuf.append(URLEncoder.encode(UID));
queryStrBuf.append("&pwd=");
queryStrBuf.append(URLEncoder.encode(PWD));
- queryStrBuf.append("&email=true");
+ queryStrBuf.append("&email=true");
}
@@ -432,25 +435,25 @@ public class DirEnroll extends TestClient {
query = queryStrBuf.toString();
System.out.println(query);
-
+
}
public static void main(String args[]) {
// Exit Status - (0) for error/Fail
// - requestId Pass
boolean st;
-
+
System.out.println(args.length);
if (args.length < 1) {
System.out.println("Usage : propertiesfile");
System.exit(0);
- }
+ }
DirEnroll t = new DirEnroll(args[0]);
t.readProperties();
st = t.enroll();
- if (st) {
+ if (st) {
System.out.println(
t.getAuthenticator() + " based enrollment successfull. ");
System.exit(1);
@@ -464,5 +467,5 @@ public class DirEnroll extends TestClient {
}
}// end of function main
-} // end of class
+} // end of class
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/ParseXML.java b/pki/base/silent/src/com/netscape/pkisilent/common/ParseXML.java
index 79be5c35..22c1c402 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/ParseXML.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/ParseXML.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.common;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -31,7 +32,6 @@ import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
-
public class ParseXML {
Document dom = null;
@@ -77,7 +77,7 @@ public class ParseXML {
// get the root elememt
Element docEle = dom.getDocumentElement();
-
+
// get a nodelist of <employee> elements
NodeList nl = docEle.getElementsByTagName(tag);
@@ -107,9 +107,10 @@ public class ParseXML {
XMLSerializer serializer = new XMLSerializer(System.out, format);
serializer.serialize(dom);
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
}
-
+
private String getTextValue(Element ele, String tagName) {
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
@@ -132,7 +133,7 @@ public class ParseXML {
try {
// get the root elememt
Element docEle = dom.getDocumentElement();
-
+
// get a nodelist of <employee> elements
NodeList nl = docEle.getElementsByTagName(first);
@@ -163,10 +164,8 @@ public class ParseXML {
px.parse(fiscfg);
px.prettyprintxml();
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
}
-}
-
-
-; // end class
+}; // end class
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/PostQuery.java b/pki/base/silent/src/com/netscape/pkisilent/common/PostQuery.java
index 87fcf500..550386d5 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/PostQuery.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/PostQuery.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.common;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -29,12 +30,11 @@ import java.net.URL;
import com.netscape.osutil.OSUtil;
/**
- * CMS Test framework .
- * This class submits request to admin server after authenticating with UID and Password. You can get back the response by calling the method. getPage().
+ * CMS Test framework . This class submits request to admin server after
+ * authenticating with UID and Password. You can get back the response by
+ * calling the method. getPage().
*/
-
-
public class PostQuery {
private boolean st;
@@ -45,10 +45,13 @@ public class PostQuery {
private StringBuffer stdout = new StringBuffer();
/**
- * Constructor . Takes the parameters urlstring("http://hostname:<portnumber> , Id for authenticating to the server, password for authentication to the server and query which needs to be submitted to the server
+ * Constructor . Takes the parameters
+ * urlstring("http://hostname:<portnumber> , Id for authenticating to the
+ * server, password for authentication to the server and query which needs
+ * to be submitted to the server
*/
- public PostQuery(String urlstr, String authid, String authpwd, String querystring) {
+ public PostQuery(String urlstr, String authid, String authpwd, String querystring) {
URLString = urlstr;
adminID = authid;
@@ -75,21 +78,21 @@ public class PostQuery {
}
public boolean Send() {
- // / This functions connects to the URL and POST HTTP Request .
- // It compares with NMC_STATUS and return the status.
+ // / This functions connects to the URL and POST HTTP Request .
+ // It compares with NMC_STATUS and return the status.
System.out.println(URLString);
st = false;
try {
- BufferedReader mbufferedReader = null;
+ BufferedReader mbufferedReader = null;
URL myUrl = new URL(URLString);
String userPassword = adminID + ":" + adminPWD;
System.out.println("adminid=" + adminID);
System.out.println("adminpwd=" + adminPWD);
// String encoding = new sun.misc.BASE64Encoder().encode(
- // userPassword.getBytes());
+ // userPassword.getBytes());
String encoding = OSUtil.BtoA(
userPassword.getBytes());
HttpURLConnection URLCon = (HttpURLConnection) myUrl.openConnection();
@@ -103,7 +106,7 @@ public class PostQuery {
// URLCon.setRequestMethod("POST");
System.out.println("After post");
- DataOutputStream os = new DataOutputStream(URLCon.getOutputStream());
+ DataOutputStream os = new DataOutputStream(URLCon.getOutputStream());
System.out.println("Query: " + postQuery);
@@ -112,7 +115,7 @@ public class PostQuery {
os.writeBytes(postQuery);
os.flush();
os.close();
-
+
InputStream Content = (InputStream) URLCon.getInputStream();
System.out.println("Configuring Cert Instance : Return Response");
@@ -127,12 +130,12 @@ public class PostQuery {
if (st) {
break;
}
- }
+ }
URLCon.disconnect();
- } // try
+ } // try
catch (MalformedURLException e) {
System.out.println(URLString + " is not a valid URL.");
-
+
} catch (IOException e) {
System.out.println("exception : " + e.getMessage());
}
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/Request.java b/pki/base/silent/src/com/netscape/pkisilent/common/Request.java
index 9ddc9970..ef4c73dd 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/Request.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/Request.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.common;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -17,28 +18,24 @@ package com.netscape.pkisilent.common;
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
-
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Vector;
-
-
/**
- * CMS Test framework .
- * Submits List,Approve,Reject,cancel requests to agent port
+ * CMS Test framework . Submits List,Approve,Reject,cancel requests to agent
+ * port
*/
-
public class Request extends TestClient {
private String validityperiod;
private String approveseqnum, type, reqType, reqState, agenttype;
private int i;
- // Program variables
+ // Program variables
private String ACTION_PROCESS_CERT_REQUEST = null;
private String ACTION_LISTREQUEST = "/queryReq";
private int reqtype = 1;
@@ -52,29 +49,30 @@ public class Request extends TestClient {
private Vector<String> seqNum = new Vector<String>();
private String AUTH_ID = null;
- // Cert Detail variables
+ // Cert Detail variables
private String csrRequestorName, csrRequestorPhone, csrRequestorEmail, subject, subjectdn, reqStatus, certType;
private String requestType, requestID, sslclient, clientcert, servercert, emailcert, objectsigningcert, sslcacert, objectsigningcacert, emailcacert, sigAlgo, totalRecord, validitylength, trustedManager;
private int totalNumApproved = 0;
- // Constructors
+ // Constructors
/**
* Constructor . Takes the parameter for Properties file name
- * @param propfileName name of the parameter file.
+ *
+ * @param propfileName name of the parameter file.
*/
-
public Request(String pfile) {
propfileName = pfile;
}
/**
- * Constructor . Takes the parameter host , port and "angent type - ca/ra"
+ * Constructor . Takes the parameter host , port and "angent type - ca/ra"
+ *
* @param hostname.
- * @param port
+ * @param port
* @param agenttype Whether ca or ra agent
*/
@@ -85,9 +83,10 @@ public class Request extends TestClient {
}
/**
- * Constructor . Takes the following parmaters
- * @param hostName .
- * @param port
+ * Constructor . Takes the following parmaters
+ *
+ * @param hostName .
+ * @param port
* @param adminuid
* @param adminpwd
* @param agentcertnickname
@@ -97,13 +96,12 @@ public class Request extends TestClient {
* @param ApproveSequenceNumberFrom
* @param ApproveSequnceNumberTo
* @param type
- * @param reqtype enrollment/revoked
- * @param requestState complete/pending
- * @param agentType ra/ca
- * @param trustedManager true/false
+ * @param reqtype enrollment/revoked
+ * @param requestState complete/pending
+ * @param agentType ra/ca
+ * @param trustedManager true/false
*/
-
public Request(String h, String p, String aid, String apwd, String cname, String cd, String ctpwd, String snum, String sfrom, String sto, String ty, String rty, String rstate, String aty, String tm) {
host = h;
ports = p;
@@ -142,15 +140,17 @@ public class Request extends TestClient {
}
/**
- * Set Agent Cert nick name
+ * Set Agent Cert nick name
*/
public void setAgentCertName(String s) {
certnickname = s;
}
/**
- * List all pending enrollment request. Takes parameters fromRequestNumber,toRequestNumber
- * @param fromrequest number
+ * List all pending enrollment request. Takes parameters
+ * fromRequestNumber,toRequestNumber
+ *
+ * @param fromrequest number
* @param endrequestnumber.
*/
@@ -164,12 +164,13 @@ public class Request extends TestClient {
}
/**
- * List all pending request. Takes parameters fromRequestNumber,toRequestNumber
- * @param fromrequest number
+ * List all pending request. Takes parameters
+ * fromRequestNumber,toRequestNumber
+ *
+ * @param fromrequest number
* @param endrequestnumber.
*/
-
public Vector<String> ListAllRequests(String fromRequestNumber, String toRequestNumber) {
reqState = "showAll";
reqType = "enrollment";
@@ -181,10 +182,10 @@ public class Request extends TestClient {
/**
* Approve pending enrollment request. Takes parameters RequestNumber
- * @param request number
+ *
+ * @param request number
*/
-
public int ApproveRequests(String requestNumber) {
reqState = "showWaiting";
reqType = "enrollment";
@@ -201,8 +202,10 @@ public class Request extends TestClient {
}
/**
- * Approve profile based pending enrollment request. Takes parameters RequestNumber
- * @param request number
+ * Approve profile based pending enrollment request. Takes parameters
+ * RequestNumber
+ *
+ * @param request number
*/
public int ApproveProfileRequests(String RequestNumber) {
@@ -222,22 +225,23 @@ public class Request extends TestClient {
}
public boolean Approve_cadualcert_Profile_Request(String RequestNumber, String name) {
-
+
approveseqnum = RequestNumber;
approveseqnumFrom = RequestNumber;
approveseqnumTo = RequestNumber;
cadualcert_name = name;
- // reqtype = 7 means cadualcert profile request
- // this is just a convention that we follow within this file to distinguish
+ // reqtype = 7 means cadualcert profile request
+ // this is just a convention that we follow within this file to
+ // distinguish
// bet'n the different requests
reqtype = 7;
buildquery();
- if (!Send()) {
+ if (!Send()) {
System.out.println("Error: Approving request " + approveseqnum);
return false;
}
@@ -247,11 +251,12 @@ public class Request extends TestClient {
}
/**
- * Reject profile based pending enrollment request. Takes parameters RequestNumber
- * @param request number
+ * Reject profile based pending enrollment request. Takes parameters
+ * RequestNumber
+ *
+ * @param request number
*/
-
public int RejectProfileRequests(String RequestNumber) {
approveseqnum = RequestNumber;
@@ -269,8 +274,10 @@ public class Request extends TestClient {
}
/**
- * Cancel profile based pending enrollment request. Takes parameters RequestNumber
- * @param request number
+ * Cancel profile based pending enrollment request. Takes parameters
+ * RequestNumber
+ *
+ * @param request number
*/
public int CancelProfileRequests(String RequestNumber) {
@@ -289,7 +296,7 @@ public class Request extends TestClient {
}
- // private methods
+ // private methods
private boolean RetrieveProfileCancel(StringBuffer s) {
String res = s.toString();
int ret = 0;
@@ -354,14 +361,14 @@ public class Request extends TestClient {
AUTH_ID = res.substring(ret + AUTHID.length() + 1,
res.indexOf(";", ret) - 1);
while (ret > 0) {
- if ((ret = res.indexOf(seqnum, ret)) > -1) {
- int bi = ret + seqnum.length() + 2;
+ if ((ret = res.indexOf(seqnum, ret)) > -1) {
+ int bi = ret + seqnum.length() + 2;
int be = res.indexOf(";", ret) - 1;
seqNum.addElement(res.substring(bi, be));
ret++;
- }
-
+ }
+
}
}
@@ -462,9 +469,9 @@ public class Request extends TestClient {
res.indexOf(";", ret) - 1);
}
- } // end of for loop
+ } // end of for loop
- // System.out.println("Debug : Retrieving cert details");
+ // System.out.println("Debug : Retrieving cert details");
ret = res.indexOf("header.subject =");
if (ret > 0) {
@@ -481,7 +488,6 @@ public class Request extends TestClient {
}
// System.out.println("Debug : Retrieving cert details ");
-
ret = res.indexOf("header.ext_ssl_client =");
if (ret > 0) {
clientcert = res.substring(
@@ -574,7 +580,7 @@ public class Request extends TestClient {
System.out.println(res);
}
- // Find th Server_ATTRS paramteter value of reqStatus
+ // Find th Server_ATTRS paramteter value of reqStatus
int i = 1;
int ret;
@@ -587,17 +593,17 @@ public class Request extends TestClient {
"requestStatus")) {
i = t;
break;
- }
+ }
}
-
+
String req = "header.SERVER_ATTRS[" + i + "].value=";
ret = res.indexOf(req);
reqStatus = res.substring(ret + req.length() + 1,
res.indexOf(";", ret) - 1);
- if (reqStatus != null) {
+ if (reqStatus != null) {
reqStatus.toLowerCase();
if (reqStatus.equals("complete")) {
return true;
@@ -627,7 +633,7 @@ public class Request extends TestClient {
con.setQueryString(query);
con.setActionURL(ACTION_STRING);
con.Send();
- StringBuffer s = new StringBuffer();
+ StringBuffer s = new StringBuffer();
s = con.getPage();
String line;
@@ -645,7 +651,7 @@ public class Request extends TestClient {
break;
case 3:
- st = approveRequestStatus(s);
+ st = approveRequestStatus(s);
break;
case 4:
@@ -665,7 +671,7 @@ public class Request extends TestClient {
break;
default:
- System.out.println("reqtype not recognized");
+ System.out.println("reqtype not recognized");
}
} catch (Exception e) {
System.err.println("exception: in Send routine" + e);
@@ -685,7 +691,7 @@ public class Request extends TestClient {
query += "&reqState=" + reqState;
}
-
+
if (reqtype == 2) { // get cert details
ACTION_PROCESS_CERT_REQUEST = "/" + AUTH_ID + "/processCertReq";
ACTION_STRING = ACTION_PROCESS_CERT_REQUEST;
@@ -699,7 +705,7 @@ public class Request extends TestClient {
Integer x = new Integer(validityperiod);
validperiod = x.intValue();
- } else {
+ } else {
validperiod = 180;
}
@@ -719,7 +725,7 @@ public class Request extends TestClient {
if (csrRequestorPhone != null) {
query += "&csrRequestorPhone=" + csrRequestorPhone;
}
-
+
if (csrRequestorEmail != null) {
query += "&csrRequestorEmail=" + csrRequestorEmail;
}
@@ -746,7 +752,7 @@ public class Request extends TestClient {
query += "&certTypeSSLServer=" + servercert;
}
- if (emailcert.equals("true")) {
+ if (emailcert.equals("true")) {
query += "&certTypeEmail=" + emailcert;
}
@@ -758,13 +764,15 @@ public class Request extends TestClient {
}
- if ((reqtype == 4) || (reqtype == 5) || (reqtype == 6)) { // profile based cert request
+ if ((reqtype == 4) || (reqtype == 5) || (reqtype == 6)) { // profile
+ // based cert
+ // request
if (validityperiod != null) {
Integer x = new Integer(validityperiod);
validperiod = x.intValue();
- } else {
+ } else {
validperiod = 180;
}
@@ -871,19 +879,30 @@ public class Request extends TestClient {
+ "&keyUsageKeyAgreement=false"
+ "&keyUsageKeyCertSign=false" + "&keyUsageCrlSign=false"
+ "&keyUsageEncipherOnly=false"
- + "&keyUsageDecipherOnly=false" + /* -- For Older CMS 6.x servers use these
- "&nsCertCritical=false" +
- "&nsCertSSLClient=true" +
- "&nsCertSSLServer=false" +
- "&nsCertEmail=true" +
- "&nsCertObjectSigning=false" +
- "&nsCertSSLCA=false" +
- "&nsCertEmailCA=false" +
- "&nsCertObjectSigningCA=false" +
- "&subjAltNameExtCritical=false" +
- "&subjAltNames=RFC822Name: null" +
- "&signingAlg=MD5withRSA" +
- */ // For newer CS 7.x servers use these
+ + "&keyUsageDecipherOnly=false" + /*
+ * -- For Older CMS 6.x
+ * servers use these
+ * "&nsCertCritical=false"
+ * +
+ * "&nsCertSSLClient=true"
+ * +
+ * "&nsCertSSLServer=false"
+ * + "&nsCertEmail=true" +
+ * "&nsCertObjectSigning=false"
+ * + "&nsCertSSLCA=false"
+ * +
+ * "&nsCertEmailCA=false"
+ * +
+ * "&nsCertObjectSigningCA=false"
+ * +
+ * "&subjAltNameExtCritical=false"
+ * +
+ * "&subjAltNames=RFC822Name: null"
+ * +
+ * "&signingAlg=MD5withRSA"
+ * +
+ */// For newer CS 7.x
+ // servers use these
"&exKeyUsageCritical=false"
+ "&exKeyUsageOIDs=1.3.6.1.5.5.7.3.2,1.3.6.1.5.5.7.3.4"
+ "&subjAltNameExtCritical=false"
@@ -892,7 +911,7 @@ public class Request extends TestClient {
+ "&op=approve" + "&submit=submit";
}
-
+
}
private void readProperties() {
@@ -968,14 +987,14 @@ public class Request extends TestClient {
maxCount = 50;
} else {
maxCount = y.intValue() - x.intValue();
- }
+ }
if (maxCount == 0) {
maxCount = 1;
- }
+ }
reqtype = 1;
buildquery();
- return(Send());
+ return (Send());
}
private boolean approveRequest() {
@@ -989,7 +1008,7 @@ public class Request extends TestClient {
return false;
}
- if (approveseqnum.length() > 0) {
+ if (approveseqnum.length() > 0) {
if (seqNum.contains(approveseqnum)) {
seqNum.removeAllElements();
seqNum.addElement(approveseqnum);
@@ -1002,7 +1021,7 @@ public class Request extends TestClient {
System.out.println(
" Seq num not specified . Approving all pending request From : "
+ approveseqnumFrom + " To : " + approveseqnumTo);
- }
+ }
boolean flag = true;
@@ -1015,7 +1034,7 @@ public class Request extends TestClient {
while (i < seqNum.size()) {
approveseqnum = (seqNum.elementAt(i)).toString();
- // Get request details
+ // Get request details
reqtype = 2;
buildquery();
if (!Send()) {
@@ -1023,44 +1042,43 @@ public class Request extends TestClient {
i++;
continue;
}
-
+
if (debug) {
System.out.println(
csrRequestorName + " " + csrRequestorPhone + " "
- + csrRequestorEmail + " " + requestID + " "
- + subject);
+ + csrRequestorEmail + " " + requestID + " "
+ + subject);
}
- // Now for pending status - approve the request
+ // Now for pending status - approve the request
reqtype = 3;
buildquery();
if (!Send()) {
System.out.println(
- "Error: Approving request " + approveseqnum);
+ "Error: Approving request " + approveseqnum);
i++;
continue;
}
System.out.println("Request " + approveseqnum + " is approved ");
totalNumApproved++;
- i++;
+ i++;
}
Integer x = new Integer(approveseqnum);
- if (x.intValue() >= torequest) {
+ if (x.intValue() >= torequest) {
flag = false;
- } else {
+ } else {
listRequest(approveseqnum, approveseqnumTo);
}
-
+
}
return st;
}
/**
- * Use this method when you need to use properties file.
+ * Use this method when you need to use properties file.
*/
-
- public int processRequest() {
+ public int processRequest() {
if (propfileName != null) {
readProperties();
}
@@ -1090,7 +1108,7 @@ public class Request extends TestClient {
} else {
return 0;
}
- } else {
+ } else {
return -1;
}
@@ -1103,11 +1121,11 @@ public class Request extends TestClient {
// Exit Status - (0) for error
// - any number > 0 Pass
int st = 0;
-
+
if (args.length < 1) {
System.out.println("Usage : propertiesfile");
System.exit(0);
- }
+ }
Request t = new Request(args[0]);
@@ -1120,5 +1138,5 @@ public class Request extends TestClient {
}// end of function main
-} // end of class
+} // end of class
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/ServerInfo.java b/pki/base/silent/src/com/netscape/pkisilent/common/ServerInfo.java
index c353c4ae..250c90bf 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/ServerInfo.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/ServerInfo.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.common;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -23,13 +24,13 @@ import java.io.FileReader;
import java.net.InetAddress;
import java.util.StringTokenizer;
-
/**
- * CMS Test framework .
- * This class fetches all the necssary ServerInformation to run the test . For example AdminServer information linke port , hsotname, Config LDAP server port, CMS servers Agentport,AdminPort, EESSL port, EE port etc..
+ * CMS Test framework . This class fetches all the necssary ServerInformation to
+ * run the test . For example AdminServer information linke port , hsotname,
+ * Config LDAP server port, CMS servers Agentport,AdminPort, EESSL port, EE port
+ * etc..
*/
-
public class ServerInfo {
public String serverRoot, instanceRoot, instanceID;
@@ -41,14 +42,16 @@ public class ServerInfo {
public static CMSProperties props = null;
public static CMSProperties CMSprops = null;
- // Private variables
+ // Private variables
private int i;
public String CMSConfigFile, AdminConfigFile;
- public ServerInfo() {}
+ public ServerInfo() {
+ }
/**
- * Constructor. Takes Server root as parameter for example ( /export/qa). Reads and collects information about adminserver and Config LDAP server.
+ * Constructor. Takes Server root as parameter for example ( /export/qa).
+ * Reads and collects information about adminserver and Config LDAP server.
*/
public ServerInfo(String sroot) {
serverRoot = sroot;
@@ -58,10 +61,11 @@ public class ServerInfo {
}
/**
- * Constructor. Takes Serverroot ( /export/qa) and instanceRoot (/export/qa/cert-jupiter2) as parameters . Reads and collects information about Admin Server , Config LDAP server and CMS server .
+ * Constructor. Takes Serverroot ( /export/qa) and instanceRoot
+ * (/export/qa/cert-jupiter2) as parameters . Reads and collects information
+ * about Admin Server , Config LDAP server and CMS server .
*/
-
public ServerInfo(String sroot, String instRoot) {
serverRoot = sroot;
instanceRoot = instRoot;
@@ -82,10 +86,10 @@ public class ServerInfo {
return ldapPort;
}
- public String GetHostName() {
+ public String GetHostName() {
if (domain.indexOf(".") > 0) {
return domain.substring(0, domain.indexOf("."));
- } else {
+ } else {
return domain;
}
}
@@ -98,8 +102,8 @@ public class ServerInfo {
return CMSConfigFile;
}
- public String GetDomainName() {
- return ldapHost.substring(ldapHost.indexOf(".") + 1);
+ public String GetDomainName() {
+ return ldapHost.substring(ldapHost.indexOf(".") + 1);
}
public String GetAgentPort() {
@@ -148,15 +152,15 @@ public class ServerInfo {
readCMSConfig();
}
- // Private functions
+ // Private functions
private void SystemInfo() {
try {
- domain = InetAddress.getLocalHost().getHostName();
+ domain = InetAddress.getLocalHost().getHostName();
System.out.println("Debu:SystemInfo " + domain);
} catch (Exception e) {
System.out.println("Exception InetAddress : " + e.getMessage());
}
-
+
}
private void parseServerXML() {
@@ -165,7 +169,7 @@ public class ServerInfo {
int EE_SSL = 3;
int EE_NON_SSL = 4;
int IP = 5;
- int PORT = 6;
+ int PORT = 6;
BufferedReader in = null;
try {
@@ -209,11 +213,11 @@ public class ServerInfo {
} else if (token.equals(" port=")) {
index2 = PORT;
}
-
+
if (index1 != 5 && index2 == IP && !token.equals(" ip=")) {
String ip = token;
} else if (index2 == PORT && !token.equals(" port=")) {
-
+
switch (index1) {
case 1:
CMSAgentPort = token;
@@ -232,7 +236,7 @@ public class ServerInfo {
break;
default:
- break;
+ break;
}
@@ -247,10 +251,11 @@ public class ServerInfo {
if (in != null) {
try {
in.close();
- } catch (Exception ex) {}
+ } catch (Exception ex) {
+ }
}
}
- }
+ }
private String stripSpace(String s) {
@@ -260,7 +265,7 @@ public class ServerInfo {
if ((s.charAt(i) == ' ')) {
i++;
continue;
- } else {
+ } else {
val += s.charAt(i);
}
}
@@ -280,7 +285,7 @@ public class ServerInfo {
if (fis.read(b) != b.length) {
System.out.println("Could not read ");
- } else {
+ } else {
String tmpstr = new String(b, 0, b.length);
int ret;
@@ -305,7 +310,7 @@ public class ServerInfo {
}
}
-
+
fis.close();
} catch (Exception e) {
System.out.println("exception " + e.getMessage());
@@ -333,7 +338,7 @@ public class ServerInfo {
ServerCertNickName = "Server-Cert cert-" + instanceID;
}
IDBPort = CMSprops.getProperty("internaldb.ldapconn.port");
-
+
fis.close();
} catch (Exception e) {
System.out.println("exception " + e.getMessage());
@@ -347,18 +352,18 @@ public class ServerInfo {
System.out.println(" Admin Port : " + s.GetAdminPort());
System.out.println(" LDAP Port : " + s.GetConfigLDAPPort());
System.out.println("Hostname " + s.GetHostName());
- System.out.println("InstanceID" + s.GetInstanceID());
- System.out.println(" doamin name : " + s.GetDomainName());
+ System.out.println("InstanceID" + s.GetInstanceID());
+ System.out.println(" doamin name : " + s.GetDomainName());
System.out.println("AgentPort " + s.GetAgentPort());
System.out.println("EESSLPort " + s.GetEESSLPort());
System.out.println("EEPort " + s.GetEEPort());
- System.out.println("CMSAdminPort :" + s.GetCMSAdminPort());
+ System.out.println("CMSAdminPort :" + s.GetCMSAdminPort());
System.out.println("CAAuthority : " + s.GetCertAuthority());
System.out.println("CASigningCert:" + s.GetCASigningCert());
System.out.println("RASigningCert:" + s.GetRASigningCert());
System.out.println("ServerCert" + s.GetServerCertNickName());
-
+
}// end of function main
-} // end of class
+} // end of class
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/TestClient.java b/pki/base/silent/src/com/netscape/pkisilent/common/TestClient.java
index d711e409..264b6f8c 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/TestClient.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/TestClient.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.common;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -26,15 +27,11 @@ import java.util.Properties;
import org.mozilla.jss.crypto.X509Certificate;
import org.mozilla.jss.ssl.SSLCertificateApprovalCallback;
-
-
/**
- * CMS Test framework .
- * Before createing an instance of this class make sure you havae set an environment variable TEST_CONFIG_FILE.
+ * CMS Test framework . Before createing an instance of this class make sure you
+ * havae set an environment variable TEST_CONFIG_FILE.
*/
-
-
public class TestClient implements SSLCertificateApprovalCallback {
public int port;
@@ -50,20 +47,20 @@ public class TestClient implements SSLCertificateApprovalCallback {
public String ACTION_STRING;
public String query;
public boolean debug = false;
- // Certificate nicknames to be used by Test Clients
+ // Certificate nicknames to be used by Test Clients
private int i;
private String testConfigFile;
- public String caAgentCertName = "ca-agent";
- public String raAgentCertName = "ra-agent";
- public String ocspAgentCertName = "ocsp-agent";
- public String kraAgentCertName = "kra-agent";
- public String tksAgentCertName = "tks-agent";
- public String singleSignOnPWD = "secret12";
+ public String caAgentCertName = "ca-agent";
+ public String raAgentCertName = "ra-agent";
+ public String ocspAgentCertName = "ocsp-agent";
+ public String kraAgentCertName = "kra-agent";
+ public String tksAgentCertName = "tks-agent";
+ public String singleSignOnPWD = "secret12";
public String adminCertName = "cn=admin";
private String ldapBaseSuffix = "dc=netscape,dc=com";
- private String admDN = "admin";
- private String admDNPW = "admin";
+ private String admDN = "admin";
+ private String admDNPW = "admin";
private String TmpDir;
private String TestLogFile;
private String startupTests, cleanupTests;
@@ -74,7 +71,7 @@ public class TestClient implements SSLCertificateApprovalCallback {
public String UID, OU, O, DN, E, CN, C, GN, SN, L, MAIL;
// Enroll
protected String PWD;
- // CRypto
+ // CRypto
public ComCrypto cCrypt = new ComCrypto();
public String pkcs10request = null;
@@ -82,19 +79,18 @@ public class TestClient implements SSLCertificateApprovalCallback {
public String ErrorDetail;
- private String serverKeyType, serverKeySize, serverKeyAlgo;
+ private String serverKeyType, serverKeySize, serverKeyAlgo;
private String unauth[] = {
- "Unauthorized Access", "Server Error",
- "Not Found", "Generic Unauthorized"};
+ "Unauthorized Access", "Server Error",
+ "Not Found", "Generic Unauthorized" };
public boolean approve(X509Certificate x509, SSLCertificateApprovalCallback.ValidityStatus status) {
SSLServerCert = x509;
return true;
}
- // Constructor
-
+ // Constructor
public TestClient() {
keysize = "1024";
@@ -102,15 +98,16 @@ public class TestClient implements SSLCertificateApprovalCallback {
}
/**
- * Constructor . Takes the parameter for keysize and keytype .
- * Before creating a new instance of this class make sure you have set TEST_CONFIG_FILE variable in your environnemt.
- * Reads the TEST_CONFIG_FILE . Initializes the certificate database. See engage.cfg file for example.
+ * Constructor . Takes the parameter for keysize and keytype . Before
+ * creating a new instance of this class make sure you have set
+ * TEST_CONFIG_FILE variable in your environnemt. Reads the TEST_CONFIG_FILE
+ * . Initializes the certificate database. See engage.cfg file for example.
+ *
* @param keysize
- * @param keytype
+ * @param keytype
*/
-
- public TestClient(String ks, String kt) {
+ public TestClient(String ks, String kt) {
testConfigFile = ReadEnv("TEST_CONFIG_FILE");
@@ -147,7 +144,8 @@ public class TestClient implements SSLCertificateApprovalCallback {
}
/**
- * Imports certificate to cert database.Takes parameters Certpackage and certnickname
+ * Imports certificate to cert database.Takes parameters Certpackage and
+ * certnickname
*/
boolean importCert(String cp, String nickname) {
@@ -175,7 +173,6 @@ public class TestClient implements SSLCertificateApprovalCallback {
* This function returns true if you choose to executeCleanupTests
*/
-
public boolean executeCleanupTests() {
if (cleanupTests == null) {
@@ -214,7 +211,7 @@ public class TestClient implements SSLCertificateApprovalCallback {
public String GetLDAPDNPW() {
return ldaprootDNPW;
- }
+ }
public String GetLDAPBASE() {
return ldapBaseSuffix;
@@ -298,10 +295,10 @@ public class TestClient implements SSLCertificateApprovalCallback {
public void setTestLogFile(String s) {
TestLogFile = s;
- }
+ }
/**
- * parses a http page and returns true if any error is returned by server
+ * parses a http page and returns true if any error is returned by server
**/
public boolean getError(String line) {
@@ -352,7 +349,7 @@ public class TestClient implements SSLCertificateApprovalCallback {
ErrorDetail = line.substring(ret + ("errorReason=").length());
return true;
}
-
+
return false;
}
@@ -372,7 +369,7 @@ public class TestClient implements SSLCertificateApprovalCallback {
}
- public String ReadEnv(String str) {
+ public String ReadEnv(String str) {
try {
Process p = null;
Runtime r = Runtime.getRuntime();
@@ -424,7 +421,7 @@ public class TestClient implements SSLCertificateApprovalCallback {
}
ldaprootDN = props.getProperty("LDAPROOTDN");
- // Strip of th e quotes "cn=directory manager" string
+ // Strip of th e quotes "cn=directory manager" string
if (ldaprootDN.indexOf("\"") > -1) {
ldaprootDN = ldaprootDN.substring(1, ldaprootDN.length() - 1);
}
@@ -467,7 +464,8 @@ public class TestClient implements SSLCertificateApprovalCallback {
}
/**
- * returns FreePort in this machine . Takes a parmater portnumber. For example getFreePort("4026").
+ * returns FreePort in this machine . Takes a parmater portnumber. For
+ * example getFreePort("4026").
*/
public String getFreePort(String s) {
Integer x = new Integer(s);
@@ -490,7 +488,7 @@ public class TestClient implements SSLCertificateApprovalCallback {
return (getString(p));
}
- // This following method doesn't Always get a free port.
+ // This following method doesn't Always get a free port.
// while (st) {
// if(isSocketUnused(host,p) )
// st=false;
@@ -501,7 +499,7 @@ public class TestClient implements SSLCertificateApprovalCallback {
}
/**
- * Reads a file and returns the cert request as string
+ * Reads a file and returns the cert request as string
**/
public String readRequest(String filename) {
@@ -528,73 +526,70 @@ public class TestClient implements SSLCertificateApprovalCallback {
TestClient t = new TestClient("1024", "RSA");
/*
- *******************************************************************
- * Sample programs to initialze calsses
- *******************************************************************
+ * ******************************************************************
+ * Sample programs to initialze calsses
+ * ******************************************************************
*/
-
/*
- ********************************************************************
- * To Test AutoInstaller
- *******************************************************************
+ * *******************************************************************
+ * To Test AutoInstaller
+ * ******************************************************************
*/
-
/*
- AutoInstaller a = new AutoInstaller(t.GetServerRoot());
-
- ServerInfo s = new ServerInfo(t.GetServerRoot());
- System.out.println (" Admin Port : " + s.GetAdminPort());
- System.out.println (" LDAP Port : "+ s.GetConfigLDAPPort());
- System.out.println( "Hostname " + s.GetHostName());
- System.out.println(" doamin name : " + s.GetDomainName());
-
- t.setHostName(s.GetHostName());
- // Set adminServer Info
- a.setAdminInfo(s.GetHostName(),s.GetAdminPort(),s.GetDomainName(),"admin","admin");
- a.setAdminInfo(s.GetHostName(),s.GetAdminPort(),"mcom.com","admin","admin");
-
- // setCAInfo
- a.setCAInfo(s.GetHostName(),"1027","8100","admin","secret12");
- //setInternalDB info
- String dp = t.getFreePort("38900");
- a.setInternalDBInfo(s.GetHostName(),"38907","ca-db","cn=directory manager","secret12" );
-
- // set tokenInfo
-
- a.setTokenInfo("Internal","secret12");
-
- // set Subsystem info
- String agp = t.getFreePort("8100");
- String adp = t.getFreePort("8200");
- String eesp = t.getFreePort("1027");
- String eep = t.getFreePort("1100");
-
- System.out.println(agp);
-
- a.setSubSystemInfo("testra",t.GetServerRoot(),"RSA","1024","MD5","365","cn=certificate manager,ou=test,o=test",adp,agp,eesp,eep);
-
- a.setClientDBInfo(t.GetClientCertDB(),"secret12",t.GetAdminCertName());
-
- a.ConfigureCA("admin","admin","secret12","secret12");
-
- // a.ConfigureRA("admin","admin","secret12","secret12");
-
+ * AutoInstaller a = new AutoInstaller(t.GetServerRoot());
+ *
+ * ServerInfo s = new ServerInfo(t.GetServerRoot()); System.out.println
+ * (" Admin Port : " + s.GetAdminPort()); System.out.println
+ * (" LDAP Port : "+ s.GetConfigLDAPPort()); System.out.println(
+ * "Hostname " + s.GetHostName()); System.out.println(" doamin name : "
+ * + s.GetDomainName());
+ *
+ * t.setHostName(s.GetHostName()); // Set adminServer Info
+ * a.setAdminInfo
+ * (s.GetHostName(),s.GetAdminPort(),s.GetDomainName(),"admin","admin");
+ * a
+ * .setAdminInfo(s.GetHostName(),s.GetAdminPort(),"mcom.com","admin","admin"
+ * );
+ *
+ * // setCAInfo
+ * a.setCAInfo(s.GetHostName(),"1027","8100","admin","secret12");
+ * //setInternalDB info String dp = t.getFreePort("38900");
+ * a.setInternalDBInfo
+ * (s.GetHostName(),"38907","ca-db","cn=directory manager","secret12" );
+ *
+ * // set tokenInfo
+ *
+ * a.setTokenInfo("Internal","secret12");
+ *
+ * // set Subsystem info String agp = t.getFreePort("8100"); String adp
+ * = t.getFreePort("8200"); String eesp = t.getFreePort("1027"); String
+ * eep = t.getFreePort("1100");
+ *
+ * System.out.println(agp);
+ *
+ * a.setSubSystemInfo("testra",t.GetServerRoot(),"RSA","1024","MD5","365"
+ * ,"cn=certificate manager,ou=test,o=test",adp,agp,eesp,eep);
+ *
+ * a.setClientDBInfo(t.GetClientCertDB(),"secret12",t.GetAdminCertName())
+ * ;
+ *
+ * a.ConfigureCA("admin","admin","secret12","secret12");
+ *
+ * // a.ConfigureRA("admin","admin","secret12","secret12");
*/
/*
- ******************************************************
- * Example to Get Server Details
- ******************************************************
+ * *****************************************************
+ * Example to Get Server Details
+ * *****************************************************
*/
-
-
ServerInfo s = new ServerInfo(t.GetServerRoot(), t.GetInstanceRoot());
t.setHostName(s.GetHostName());
-
+
System.out.println("AgentPort " + s.GetAgentPort());
System.out.println("EESSLPort " + s.GetEESSLPort());
System.out.println("EEPort " + s.GetEEPort());
@@ -604,8 +599,8 @@ public class TestClient implements SSLCertificateApprovalCallback {
System.out.println("CASigningCert:" + s.GetCASigningCert());
System.out.println("RASigningCert:" + s.GetRASigningCert());
System.out.println("ServerCert" + s.GetServerCertNickName());
- System.out.println("------------------------------------------");
- System.out.println(" Internal Database Test:");
+ System.out.println("------------------------------------------");
+ System.out.println(" Internal Database Test:");
System.out.println(" LDAP Port : " + s.GetConfigLDAPPort());
System.out.println("Hostname " + s.GetHostName());
@@ -617,341 +612,318 @@ public class TestClient implements SSLCertificateApprovalCallback {
/* ****************************************************************
* CMC Enroll
- ***************************************************************
+ * **************************************************************
*/
- /* CMSUtils cmsutils = new CMSUtils(t.GetServerRoot());
- String requestfile="/u/lgopal/work/tetCMS/ns/tetframework/testcases/CMS/6.0/acceptance/data/basic/cmcreq/cmctest1.req";
- cmsutils.runCMCEnroll(t.GetClientCertDB(),"cn=admin",t.GetClientCertDBPW(),requestfile);
- Profiles pr = new Profiles(s.GetHostName(),s.GetEESSLPort());
- pr.setProfileType("caCMCUserCert");
- pr.setCertAuthority("ca");
-
- String request = t.readRequest(requestfile+".out");
- String bstr = "-----BEGIN NEW CERTIFICATE REQUEST-----";
- String estr="-----END NEW CERTIFICATE REQUEST-----";
- String Blob1 = request.substring(bstr.length() + 1);
- String Blob2 = Blob1.substring(0,Blob1.indexOf(estr));
- request=Blob2;
-
-
- pr.setRequest(request);
-
- pr.setUserInfo("UID=test1,Ou=netscape,o=aol","test","test","test","netscape","aol");
- pr.clientCertEnroll();
+ /*
+ * CMSUtils cmsutils = new CMSUtils(t.GetServerRoot()); String
+ * requestfile=
+ * "/u/lgopal/work/tetCMS/ns/tetframework/testcases/CMS/6.0/acceptance/data/basic/cmcreq/cmctest1.req"
+ * ;
+ * cmsutils.runCMCEnroll(t.GetClientCertDB(),"cn=admin",t.GetClientCertDBPW
+ * (),requestfile); Profiles pr = new
+ * Profiles(s.GetHostName(),s.GetEESSLPort());
+ * pr.setProfileType("caCMCUserCert"); pr.setCertAuthority("ca");
+ *
+ * String request = t.readRequest(requestfile+".out"); String bstr =
+ * "-----BEGIN NEW CERTIFICATE REQUEST-----"; String
+ * estr="-----END NEW CERTIFICATE REQUEST-----"; String Blob1 =
+ * request.substring(bstr.length() + 1); String Blob2 =
+ * Blob1.substring(0,Blob1.indexOf(estr)); request=Blob2;
+ *
+ *
+ * pr.setRequest(request);
+ *
+ * pr.setUserInfo("UID=test1,Ou=netscape,o=aol","test","test","test",
+ * "netscape","aol"); pr.clientCertEnroll();
*/
-
/* ****************************************************************
* OCSP Client stuff
- ************************************************************
+ * ***********************************************************
*/
/*
- String ip= "10.169.25.26";
- OCSPClient ocspclient= new OCSPClient(s.GetHostName(),ip,s.GetEEPort(),t.GetClientCertDB(),t.GetClientCertDBPW(),"cn=admin" ,"/tmp/ocsp.out","4");
- ocspclient.setCert(t.findCertByNickname("ocsp-agent"));
-
- ocspclient.SendOCSPRequest();
+ * String ip= "10.169.25.26"; OCSPClient ocspclient= new
+ * OCSPClient(s.GetHostName
+ * (),ip,s.GetEEPort(),t.GetClientCertDB(),t.GetClientCertDBPW
+ * (),"cn=admin" ,"/tmp/ocsp.out","4");
+ * ocspclient.setCert(t.findCertByNickname("ocsp-agent"));
+ *
+ * ocspclient.SendOCSPRequest();
*/
-
/*
- *****************************************************
+ * ****************************************************
* Test CRMFcleint and KRA REcovery and Archival
- *****************************************************
+ * ****************************************************
*/
/*
- *********************************************************
+ * ********************************************************
* OCSP Agent stuff
- *********************************************************
+ * ********************************************************
*/
-
- /* Retrieval rtr = new Retrieval(s.GetHostName(),s.GetEESSLPort());
- rtr.getCACert();
- System.out.println("CA Cert chain" + rtr.getCert());
-
- OcspAgent ocspAgent= new OcspAgent(s.GetHostName(),"8111");
- ocspAgent.setAgentCertName(t.GetOCSPAgentCertName());
-
- String cert = "-----BEGIN CERTIFICATE-----"+"\n"+rtr.getCert()+"\n"+"-----END CERTIFICATE-----\n";
-
- ocspAgent.setCACert(cert);
- ocspAgent.addCA();
+ /*
+ * Retrieval rtr = new Retrieval(s.GetHostName(),s.GetEESSLPort());
+ * rtr.getCACert(); System.out.println("CA Cert chain" + rtr.getCert());
+ *
+ * OcspAgent ocspAgent= new OcspAgent(s.GetHostName(),"8111");
+ * ocspAgent.setAgentCertName(t.GetOCSPAgentCertName());
+ *
+ * String cert = "-----BEGIN CERTIFICATE-----"+"\n"+rtr.getCert()+"\n"+
+ * "-----END CERTIFICATE-----\n";
+ *
+ * ocspAgent.setCACert(cert); ocspAgent.addCA();
*/
-
/*
- ***************************************************************
- Submit Profile based request
- *********************************************************
+ * **************************************************************
+ * Submit Profile based request
+ * ********************************************************
*/
/*
- Profiles pr = new Profiles(s.GetHostName(),s.GetEESSLPort());
- pr.setProfileType("caUserCert");
- // pr.setProfileType("caDirUserCert");
-
- pr.setCertAuthority("ca");
- pr.setUserInfo("UID=test1,Ou=netscape,o=aol","test","test","test","netscape","aol");
- //pr.setDirUserInfo("test","netscape");
- pr.clientCertEnroll();
- System.out.println("Request ID is " + pr.getRequestID());
-
-
- Request re = new Request (s.GetHostName(),s.GetAgentPort(),"ca");
- re.setAgentCertName(t.GetAdminCertName());
- re.ApproveProfileRequests(pr.getRequestID());
+ * Profiles pr = new Profiles(s.GetHostName(),s.GetEESSLPort());
+ * pr.setProfileType("caUserCert"); //
+ * pr.setProfileType("caDirUserCert");
+ *
+ * pr.setCertAuthority("ca");
+ * pr.setUserInfo("UID=test1,Ou=netscape,o=aol"
+ * ,"test","test","test","netscape","aol");
+ * //pr.setDirUserInfo("test","netscape"); pr.clientCertEnroll();
+ * System.out.println("Request ID is " + pr.getRequestID());
+ *
+ *
+ * Request re = new Request (s.GetHostName(),s.GetAgentPort(),"ca");
+ * re.setAgentCertName(t.GetAdminCertName());
+ * re.ApproveProfileRequests(pr.getRequestID());
*/
/*
- String TransportCert="MIICJTCCAY6gAwIBAgIBBTANBgkqhkiG9w0BAQQFADBDMRswGQYDVQQKExJhY2NlcHRhY25ldGVzdDEwMjQxFzAVBgNVBAsTDmFjY2VwdGFuY2V0ZXN0MQswCQYDVQQDEwJjYTAeFw0wMzA0MjMyMTM3NTFaFw0wNDA0MjIwOTMzMzFaMDkxETAPBgNVBAoTCHRlc3QxMDI0MRcwFQYDVQQLEw5hY2NlcHRhbmNldGVzdDELMAkGA1UEAxMCcmEwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANVW81T7GatHIB25kF0jdY4h4hOF1NAlAHE2YdN/UEyXuU22CfwrIltA3x/6sKFHhbbFysn6nGJlgKipPJqJDwyYTIv07hgoXqgcUu8fSYQg4BDHYhpHJxsUt3BSfADTjxAUHize7C2F8TVhBIcWW043FSkwvAiUjJb7uqQRKn7lAgMBAAGjMzAxMA4GA1UdDwEB/wQEAwIFIDAfBgNVHSMEGDAWgBTqvc3UPGDSWq+21DZGSUABNGIUbDANBgkqhkiG9w0BAQQFAAOBgQCNLJivNDHTTmCb2vDefUwLMxXNjuHwrbjVqymHPFqUjredTq2Yp+Ed1zxj+mxRovzegd65Tbnx+MV84j8K3Qc1kWOC+kbohAY9svSPsN3o5Q5BB19+5nUPC5Gk/mxkWJWWJLOnpKJGiAHMZIr58TH7hF8KQWXWMN9ikSFkPj0a/g==";
-
-
- CRMFClient CrmfClient = new CRMFClient(s.GetHostName(),s.GetEEPort());
- CrmfClient.setDBInfo(t.GetClientCertDB(),t.GetClientCertDBPW());
- CrmfClient.setTransportCert(TransportCert);
- CrmfClient.setUserInfo("user","netscape");
- CrmfClient.setLDAPInfo(t.GetLDAPDN(),t.GetLDAPDNPW());
- CrmfClient.setDualKey(true);
-
- if(!CrmfClient.Enroll())
- {System.out.println("CRMFClient : could not submit request");}
-
-
- checkRequest cr = new checkRequest(s.GetHostName(),s.GetEESSLPort(),t.getString(CrmfClient.getRequestId()),"false");
- cr.checkRequestStatus();
- System.out.println("Serial num " + cr.getSerialNumber());
- System.out.println("cert pack " + cr.getCert());
-
- KraAgent kraAgent = new KraAgent(s.GetHostName(),"8111");
- kraAgent.setAgentCertName("cn=admin");
- System.out.println("KRAAgent List archival");
-
- Vector aReq= kraAgent.ListArchivalRequests();
- int i=0;
- while(i < aReq.size() )
- {
- System.out.print(aReq.elementAt(i) + " ");
- i++;
- }
-
- kraAgent.setCertificate(cr.getCert());
- kraAgent.setLocalAgent(false);
- kraAgent.recoverKeys();
+ * String TransportCert=
+ * "MIICJTCCAY6gAwIBAgIBBTANBgkqhkiG9w0BAQQFADBDMRswGQYDVQQKExJhY2NlcHRhY25ldGVzdDEwMjQxFzAVBgNVBAsTDmFjY2VwdGFuY2V0ZXN0MQswCQYDVQQDEwJjYTAeFw0wMzA0MjMyMTM3NTFaFw0wNDA0MjIwOTMzMzFaMDkxETAPBgNVBAoTCHRlc3QxMDI0MRcwFQYDVQQLEw5hY2NlcHRhbmNldGVzdDELMAkGA1UEAxMCcmEwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANVW81T7GatHIB25kF0jdY4h4hOF1NAlAHE2YdN/UEyXuU22CfwrIltA3x/6sKFHhbbFysn6nGJlgKipPJqJDwyYTIv07hgoXqgcUu8fSYQg4BDHYhpHJxsUt3BSfADTjxAUHize7C2F8TVhBIcWW043FSkwvAiUjJb7uqQRKn7lAgMBAAGjMzAxMA4GA1UdDwEB/wQEAwIFIDAfBgNVHSMEGDAWgBTqvc3UPGDSWq+21DZGSUABNGIUbDANBgkqhkiG9w0BAQQFAAOBgQCNLJivNDHTTmCb2vDefUwLMxXNjuHwrbjVqymHPFqUjredTq2Yp+Ed1zxj+mxRovzegd65Tbnx+MV84j8K3Qc1kWOC+kbohAY9svSPsN3o5Q5BB19+5nUPC5Gk/mxkWJWWJLOnpKJGiAHMZIr58TH7hF8KQWXWMN9ikSFkPj0a/g=="
+ * ;
+ *
+ *
+ * CRMFClient CrmfClient = new
+ * CRMFClient(s.GetHostName(),s.GetEEPort());
+ * CrmfClient.setDBInfo(t.GetClientCertDB(),t.GetClientCertDBPW());
+ * CrmfClient.setTransportCert(TransportCert);
+ * CrmfClient.setUserInfo("user","netscape");
+ * CrmfClient.setLDAPInfo(t.GetLDAPDN(),t.GetLDAPDNPW());
+ * CrmfClient.setDualKey(true);
+ *
+ * if(!CrmfClient.Enroll())
+ * {System.out.println("CRMFClient : could not submit request");}
+ *
+ *
+ * checkRequest cr = new
+ * checkRequest(s.GetHostName(),s.GetEESSLPort(),t.
+ * getString(CrmfClient.getRequestId()),"false");
+ * cr.checkRequestStatus(); System.out.println("Serial num " +
+ * cr.getSerialNumber()); System.out.println("cert pack " +
+ * cr.getCert());
+ *
+ * KraAgent kraAgent = new KraAgent(s.GetHostName(),"8111");
+ * kraAgent.setAgentCertName("cn=admin");
+ * System.out.println("KRAAgent List archival");
+ *
+ * Vector aReq= kraAgent.ListArchivalRequests(); int i=0; while(i <
+ * aReq.size() ) { System.out.print(aReq.elementAt(i) + " "); i++; }
+ *
+ * kraAgent.setCertificate(cr.getCert()); kraAgent.setLocalAgent(false);
+ * kraAgent.recoverKeys();
*/
/*
- *************************************************************
- * Example to Connect oto Config Directory port
- *************************************************************
- */
-
- /*
- CMSLDAP cmsldap = new CMSLDAP(s.GetHostName(),s.GetConfigLDAPPort(),t.GetLDAPDN(),t.GetLDAPDNPW());
- if(cmsldap.connect())
- System.out.println("LDAP Connection successful");
- else
- System.out.println("Error Connecting to LDAPSERVER");
-
- // Add user to config directoory
- if (cmsldap.userAdd("ou=people,"+t.GetLDAPBASE(),"t2","t2","t2","netscape"))
- System.out.println("Added user to Config directory");
+ * ************************************************************
+ * Example to Connect oto Config Directory port
+ * ************************************************************
+ */
+ /*
+ * CMSLDAP cmsldap = new
+ * CMSLDAP(s.GetHostName(),s.GetConfigLDAPPort(),t.
+ * GetLDAPDN(),t.GetLDAPDNPW()); if(cmsldap.connect())
+ * System.out.println("LDAP Connection successful"); else
+ * System.out.println("Error Connecting to LDAPSERVER");
+ *
+ * // Add user to config directoory if
+ * (cmsldap.userAdd("ou=people,"+t.GetLDAPBASE
+ * (),"t2","t2","t2","netscape"))
+ * System.out.println("Added user to Config directory");
*/
-
/*
- *************************************************************
- * Example to Submit a CRMFCleint request to CA
- *************************************************************
- */
+ * ************************************************************
+ * Example to Submit a CRMFCleint request to CA
+ * ************************************************************
+ */
String TransportCert = "MIICJTCCAY6gAwIBAgIBBTANBgkqhkiG9w0BAQQFADBDMRswGQYDVQQKExJhY2NlcHRhY25ldGVzdDEwMjQxFzAVBgNVBAsTDmFjY2VwdGFuY2V0ZXN0MQswCQYDVQQDEwJjYTAeFw0wMzA0MTgyMjMwMDhaFw0wNDA0MTcxMDI2MDhaMDkxETAPBgNVBAoTCHRlc3QxMDI0MRcwFQYDVQQLEw5hY2NlcHRhbmNldGVzdDELMAkGA1UEAxMCcmEwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAN6sQ3mSU8mL6i6gTZIXDLzOZPhYOkQLpnJjit5hcPZ0JMn0CQVXo4QjKN1xvuZv8qVlZoQw9czmzp/knTa0sCDgFKd0r+u0TnLeZkJMSimgFnma9CnChlaDHnBd8Beu4vyaHmo7rJ0xA4etn7HjhmKbaQZOcv/aP0SW9JXRga7ZAgMBAAGjMzAxMA4GA1UdDwEB/wQEAwIFIDAfBgNVHSMEGDAWgBSC3fsQHb7fddr2vL0UdkM2dAmUWzANBgkqhkiG9w0BAQQFAAOBgQBkAGbgd9HIqwoLKAr+V6bj9oWesDmDH80gPPxj10qyWSQYIs8PofOs/75yGS9nxhydtgSMFoBgCPdroUI31kZQQlFzxtudGoKD+5MWSXho79XzPwpjheOBYgpX6ch+L4tMLFDpqeraB1yZESO5EEeKm20DGVBOKVWxHhddO1BenA==";
/*
- CRMFClient CrmfClient = new CRMFClient(s.GetHostName(),s.GetEEPort());
- CrmfClient.setDBInfo(t.GetClientCertDB(),t.GetClientCertDBPW());
- CrmfClient.setTransportCert(TransportCert);
- CrmfClient.setUserInfo("user","netscape");
- CrmfClient.setLDAPInfo(t.GetLDAPDN(),t.GetLDAPDNPW());
- CrmfClient.setDualKey(true);
-
- if(!CrmfClient.Enroll())
- {System.out.println("CRMFClient : could not submit request");}
+ * CRMFClient CrmfClient = new
+ * CRMFClient(s.GetHostName(),s.GetEEPort());
+ * CrmfClient.setDBInfo(t.GetClientCertDB(),t.GetClientCertDBPW());
+ * CrmfClient.setTransportCert(TransportCert);
+ * CrmfClient.setUserInfo("user","netscape");
+ * CrmfClient.setLDAPInfo(t.GetLDAPDN(),t.GetLDAPDNPW());
+ * CrmfClient.setDualKey(true);
+ *
+ * if(!CrmfClient.Enroll())
+ * {System.out.println("CRMFClient : could not submit request");}
*/
-
+
/* KRA Agent list archived request */
- /* ServerInfo KRAsvrInfo = new ServerInfo(t.GetServerRoot());
- String KRAinstanceRoot=t.GetServerRoot() + "/cert-" + "KRARSA1024" ;
- KRAsvrInfo.setInstanceRoot(KRAinstanceRoot);*/
-
- /* System.out.println("KRAAgent ");
- KraAgent kraAgent = new KraAgent(s.GetHostName(),s.GetAgentPort());
- kraAgent.setAgentCertName(t.GetKRAAgentCertName());
- System.out.println("KRAAgent List archival");
-
- Vector aReq= kraAgent.ListArchivalRequests();
- int i=0;
- while(i < aReq.size() )
- {
- System.out.print(aReq.elementAt(i) + " ");
- i++;
- }
+ /*
+ * ServerInfo KRAsvrInfo = new ServerInfo(t.GetServerRoot()); String
+ * KRAinstanceRoot=t.GetServerRoot() + "/cert-" + "KRARSA1024" ;
+ * KRAsvrInfo.setInstanceRoot(KRAinstanceRoot);
+ */
+ /*
+ * System.out.println("KRAAgent "); KraAgent kraAgent = new
+ * KraAgent(s.GetHostName(),s.GetAgentPort());
+ * kraAgent.setAgentCertName(t.GetKRAAgentCertName());
+ * System.out.println("KRAAgent List archival");
+ *
+ * Vector aReq= kraAgent.ListArchivalRequests(); int i=0; while(i <
+ * aReq.size() ) { System.out.print(aReq.elementAt(i) + " "); i++; }
*/
-
// cmsldap.disconnect();
/*
- *************************************************************
- * Example to submit manual user enrollment request
- *************************************************************
- /*
-
-
- /*
- UserEnroll ue = new UserEnroll(s.GetHostName(),"1029");
- ue.setUserInfo("E=testman,CN=testman,OU=netscape,O=aol,UID=testman1,C=US","testman", "testman", "testman1", "netscape","t");
-
- boolean flag = ue.clientCertEnroll();
- if(flag)
- System.out.println("Success submitted request");
+ * ************************************************************
+ * Example to submit manual user enrollment request
+ * ************************************************************ /*
+ *
+ *
+ * /* UserEnroll ue = new UserEnroll(s.GetHostName(),"1029");
+ * ue.setUserInfo
+ * ("E=testman,CN=testman,OU=netscape,O=aol,UID=testman1,C=US"
+ * ,"testman", "testman", "testman1", "netscape","t");
+ *
+ * boolean flag = ue.clientCertEnroll(); if(flag)
+ * System.out.println("Success submitted request");
*/
/*
- *************************************************************
- * Example to submit Directory based enroolemt request
- *************************************************************
- /*
-
- /*
- // Add user to config directoory
- if (cmsldap.userAdd("dc=netscape,dc=com","t2","t2","t2","netscape"))
- System.out.println("Success ");
-
- if(cmsldap.TurnOnSSL("slapd-jupiter2","Server-Cert cert-jupiter2","7000"))
- System.out.println("Turned on ssl");
- else
- return;
-
- cmsldap.TurnOffSSL();
-
- cmsldap.disconnect();
-
- DirEnroll de = new DirEnroll(s.GetHostName(),s.GetEESSLPort());
- de.setUIDInfo("t2","netscape");
- de.enroll();
-
+ * ************************************************************
+ * Example to submit Directory based enroolemt request
+ * ************************************************************ /*
+ *
+ * /* // Add user to config directoory if
+ * (cmsldap.userAdd("dc=netscape,dc=com","t2","t2","t2","netscape"))
+ * System.out.println("Success ");
+ *
+ * if(cmsldap.TurnOnSSL("slapd-jupiter2","Server-Cert cert-jupiter2","7000"
+ * )) System.out.println("Turned on ssl"); else return;
+ *
+ * cmsldap.TurnOffSSL();
+ *
+ * cmsldap.disconnect();
+ *
+ * DirEnroll de = new DirEnroll(s.GetHostName(),s.GetEESSLPort());
+ * de.setUIDInfo("t2","netscape"); de.enroll();
*/
/*
- *************************************************************
- * Example to submit Admin Enrollment request
- *************************************************************
- /*
-
- /*
-
- AdminEnroll ade = new AdminEnroll("jupiter2","8200","cn=CMS Administrator,UID=admin,C=US","admin", "secret12");
- flag = ade.Enroll();
- if (flag)
- System.out.println("adminEnrolled Successfully");
+ * ************************************************************
+ * Example to submit Admin Enrollment request
+ * ************************************************************ /*
+ *
+ * /*
+ *
+ * AdminEnroll ade = new
+ * AdminEnroll("jupiter2","8200","cn=CMS Administrator,UID=admin,C=US"
+ * ,"admin", "secret12"); flag = ade.Enroll(); if (flag)
+ * System.out.println("adminEnrolled Successfully");
*/
/*
- *************************************************************
- * Example gent List Pending request
- *************************************************************
- /*
-
- /*
-
- // Agent List and Approve Request
- Request re = new Request (s.GetHostName(),s.GetAgentPort(),s.GetCertAuthority());
- re.setAgentCertName(t.GetAdminCertName());
- re.ListPendingRequests("2","70");
- re.ApproveRequests(t.getString(ue.getRequestId()));
+ * ************************************************************
+ * Example gent List Pending request
+ * ************************************************************ /*
+ *
+ * /*
+ *
+ * // Agent List and Approve Request Request re = new Request
+ * (s.GetHostName(),s.GetAgentPort(),s.GetCertAuthority());
+ * re.setAgentCertName(t.GetAdminCertName());
+ * re.ListPendingRequests("2","70");
+ * re.ApproveRequests(t.getString(ue.getRequestId()));
*/
/*
- *************************************************************
- * Example for CheckRequest Status and add the certificate to internal db
- *************************************************************
- /*
-
- /*
- // check request status and Revoke cert
- checkRequest cr = new checkRequest(s.GetHostName(),s.GetEESSLPort(),t.getString(ue.getRequestId()),"false");
- checkRequest cr = new checkRequest(s.GetHostName(),s.GetEESSLPort(),"1","false");
-
- cr.checkRequestStatus();
- System.out.println("Serial num " + cr.getSerialNumber());
- System.out.println("cert pack " + cr.getCert());
-
- String st= "-----BEGIN CERTIFICATE-----"+"\n"+cr.getCert()+"\n"+"-----END CERTIFICATE-----\n";
- System.out.println("cert pack " + st);
-
- cmsldap.getXCertificate(st.getBytes());
-
+ * ************************************************************
+ * Example for CheckRequest Status and add the certificate to internal
+ * db************************************************************ /*
+ *
+ * /* // check request status and Revoke cert checkRequest cr = new
+ * checkRequest
+ * (s.GetHostName(),s.GetEESSLPort(),t.getString(ue.getRequestId
+ * ()),"false"); checkRequest cr = new
+ * checkRequest(s.GetHostName(),s.GetEESSLPort(),"1","false");
+ *
+ * cr.checkRequestStatus(); System.out.println("Serial num " +
+ * cr.getSerialNumber()); System.out.println("cert pack " +
+ * cr.getCert());
+ *
+ * String st= "-----BEGIN CERTIFICATE-----"+"\n"+cr.getCert()+"\n"+
+ * "-----END CERTIFICATE-----\n"; System.out.println("cert pack " + st);
+ *
+ * cmsldap.getXCertificate(st.getBytes());
*/
-
/*
- *************************************************************
- * Example agent ro revoke request
- *************************************************************
- /*
-
- /*
- Revoke rr = new Revoke (s.GetHostName(),s.GetAgentPort(),s.GetCertAuthority(),t.getString(cr.getSerialNumber()));
- rr.revokeCerts();
+ * ************************************************************
+ * Example agent ro revoke request
+ * ************************************************************ /*
+ *
+ * /* Revoke rr = new Revoke
+ * (s.GetHostName(),s.GetAgentPort(),s.GetCertAuthority
+ * (),t.getString(cr.getSerialNumber())); rr.revokeCerts();
*/
/*
- *************************************************************
- * Example Agent update CRL
- *************************************************************
- /*
-
- /*
- // Update CRLand DISPLAY it
-
- System.out.println("Displayin CRL");
- CRL crl = new CRL (s.GetHostName(),s.GetAgentPort(),"/tmp/crlfile");
- crl.setAgentCertName(t.GetAdminCertName());
- crl.updateCRL();
- crl.displayCRL();
- crl.getRevokedCerts();
+ * ************************************************************
+ * Example Agent update CRL
+ * ************************************************************ /*
+ *
+ * /* // Update CRLand DISPLAY it
+ *
+ * System.out.println("Displayin CRL"); CRL crl = new CRL
+ * (s.GetHostName(),s.GetAgentPort(),"/tmp/crlfile");
+ * crl.setAgentCertName(t.GetAdminCertName()); crl.updateCRL();
+ * crl.displayCRL(); crl.getRevokedCerts();
*/
// Update CRL in Directory
- /* UpdateDir dcrl = new UpdateDir(s.GetHostName(),s.GetEESSLPort());
- dcrl.updateDir();*/
-
/*
- *************************************************************
- * Example for stopping and starting servers
- *************************************************************
+ * UpdateDir dcrl = new UpdateDir(s.GetHostName(),s.GetEESSLPort());
+ * dcrl.updateDir();
*/
/*
- DSTask idb = new DSTask(t.GetServerRoot()+"/slapd-jupiter2-db");
- if (idb.ldapStop()) System.out.println("IDB stopped");
- if(idb.ldapStart()) System.out.println("IDB Started");
-
- System.out.println("------------------------------------------");
- System.out.println(" CMS Test:");
- CMSTask task = new CMSTask(t.GetInstanceRoot());
- task.CMSStop();
- task.CMSStart();
+ * ************************************************************
+ * Example for stopping and starting servers
+ * ************************************************************
*/
-
+ /*
+ * DSTask idb = new DSTask(t.GetServerRoot()+"/slapd-jupiter2-db"); if
+ * (idb.ldapStop()) System.out.println("IDB stopped");
+ * if(idb.ldapStart()) System.out.println("IDB Started");
+ *
+ * System.out.println("------------------------------------------");
+ * System.out.println(" CMS Test:"); CMSTask task = new
+ * CMSTask(t.GetInstanceRoot()); task.CMSStop(); task.CMSStart();
+ */
}// end of function main
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/UserEnroll.java b/pki/base/silent/src/com/netscape/pkisilent/common/UserEnroll.java
index cd6ebd87..4061b4f9 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/UserEnroll.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/UserEnroll.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.common;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -17,7 +18,6 @@ package com.netscape.pkisilent.common;
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
-
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
@@ -29,15 +29,12 @@ import java.util.GregorianCalendar;
import org.mozilla.jss.ssl.SSLSocket;
-
-
/**
- * CMS Test framework .
- * Submits Legacy Manual User Enrollment request from EESSL port. Parses the response from server and return RequestID.
- *<P>
+ * CMS Test framework . Submits Legacy Manual User Enrollment request from EESSL
+ * port. Parses the response from server and return RequestID.
+ * <P>
*/
-
public class UserEnroll extends TestClient {
private int i;
@@ -46,15 +43,14 @@ public class UserEnroll extends TestClient {
private long elapsedTime;
// Constructor
- public UserEnroll() {}
+ public UserEnroll() {
+ }
/**
- * Constructor . Takes the parameter hostname and EESSLport
+ * Constructor . Takes the parameter hostname and EESSLport
* <p>
*/
-
-
public UserEnroll(String h, String p) {
host = h;
ports = p;
@@ -63,23 +59,25 @@ public class UserEnroll extends TestClient {
/**
* Constructor . Takes the parameter for Properties file name
* <p>
- * @param propfilename name of the parameter file
+ *
+ * @param propfilename name of the parameter file
*/
-
public UserEnroll(String pfile) {
propfileName = pfile;
}
/**
- * Constructor . Takes the parameter for hostname, EESSLportnumber, subjectdn, E, CN,UID,OU,O, CertdbDirecrory(fullpath) , certdbPassword, keysize, keytype, requestorName,requestorEmail and Certtype.
- * valid values for Certtype - "ca","ra","ocsp"
+ * Constructor . Takes the parameter for hostname, EESSLportnumber,
+ * subjectdn, E, CN,UID,OU,O, CertdbDirecrory(fullpath) , certdbPassword,
+ * keysize, keytype, requestorName,requestorEmail and Certtype. valid values
+ * for Certtype - "ca","ra","ocsp"
* <p>
- * @param propfilename name of the parameter file
+ *
+ * @param propfilename name of the parameter file
*/
-
- public UserEnroll(String h, String p, String dn, String e, String cn, String uid, String ou, String o, String cd, String tpwd, String sslcl, String ksize, String keyty, String reqname, String reqemail, String ctype) {
+ public UserEnroll(String h, String p, String dn, String e, String cn, String uid, String ou, String o, String cd, String tpwd, String sslcl, String ksize, String keyty, String reqname, String reqemail, String ctype) {
host = h;
ports = p;
@@ -115,7 +113,8 @@ public class UserEnroll extends TestClient {
}
/**
- * Set Certificate Request information. Takes parameters - subjectdn,E,CN,UID,OU,O
+ * Set Certificate Request information. Takes parameters -
+ * subjectdn,E,CN,UID,OU,O
*/
public void setUserInfo(String dn, String e, String cn, String uid, String ou, String o) {
@@ -149,7 +148,8 @@ public class UserEnroll extends TestClient {
}
/**
- * Set Certificat Type for which you want to submit a request . Valid values - "ca"/"ra"/"ocsp"
+ * Set Certificat Type for which you want to submit a request . Valid values
+ * - "ca"/"ra"/"ocsp"
*/
public void setCertType(String ct) {
certType = ct;
@@ -158,20 +158,21 @@ public class UserEnroll extends TestClient {
public boolean enroll_load() {
buildquery();
setStatusString("");
- return(Send());
+ return (Send());
}
private boolean pkcs10() {
System.out.println(" In pkcs10 Keysize , key type " + keysize + keytype);
- // ComCrypto cCrypt = new ComCrypto(cdir,tokenpwd,certnickname,keysize,keytype);
+ // ComCrypto cCrypt = new
+ // ComCrypto(cdir,tokenpwd,certnickname,keysize,keytype);
cCrypt.setCertDir(cdir);
cCrypt.setCertnickname(adminCertName);
cCrypt.setKeySize(keysize);
cCrypt.setKeyType(keytype);
cCrypt.setTokenPWD(tokenpwd);
cCrypt.setDebug(true);
- if (pkcs10request != null) {
+ if (pkcs10request != null) {
cCrypt.setGenerateRequest(false);
cCrypt.loginDB();
} else {
@@ -190,12 +191,12 @@ public class UserEnroll extends TestClient {
System.out.println(query);
}
setStatusString("");
- return(Send());
+ return (Send());
} catch (Exception e) {
System.err.println("some exception:" + e);
}
- return(false);
+ return (false);
}
@@ -222,7 +223,7 @@ public class UserEnroll extends TestClient {
try {
- if (debug) {
+ if (debug) {
System.out.println("Step 3 : Socket initialize");
}
@@ -268,7 +269,7 @@ public class UserEnroll extends TestClient {
if (line.indexOf("fixed.requestId = ") != -1) {
requestId = line.substring("fixed.requestId = ".length() + 1,
line.indexOf(";") - 1);
- }
+ }
if (getError(line)) {
st = false;
@@ -296,7 +297,7 @@ public class UserEnroll extends TestClient {
}
return st;
-
+
}
private void buildquery() {
@@ -331,12 +332,12 @@ public class UserEnroll extends TestClient {
queryStrBuf.append("&csrRequestorEmail=");
queryStrBuf.append(URLEncoder.encode(requestorEmail));
queryStrBuf.append("&email=true");
-
+
} else {
queryStrBuf.append("&email=false");
}
-
- if (requestorPhone.length() > 0) {
+
+ if (requestorPhone.length() > 0) {
queryStrBuf.append("&csrRequestorPhone=");
queryStrBuf.append(URLEncoder.encode(requestorPhone));
}
@@ -344,7 +345,7 @@ public class UserEnroll extends TestClient {
queryStrBuf.append("&csrRequestorComments=");
queryStrBuf.append(URLEncoder.encode(requestorComments));
}
- System.out.println("buidlquery client E ");
+ System.out.println("buidlquery client E ");
if (E.length() > 0) {
queryStrBuf.append("&E=");
queryStrBuf.append(E);
@@ -362,8 +363,10 @@ public class UserEnroll extends TestClient {
queryStrBuf.append("&OU=");
queryStrBuf.append(OU);
}
- // if(O.length() > 0) { queryStrBuf.append("&O=");queryStrBuf.append(O);}
- // if(C.length() >0) { queryStrBuf.append("&C=");queryStrBuf.append(C);}
+ // if(O.length() > 0) {
+ // queryStrBuf.append("&O=");queryStrBuf.append(O);}
+ // if(C.length() >0) {
+ // queryStrBuf.append("&C=");queryStrBuf.append(C);}
System.out.println("buidlquery client dn ");
queryStrBuf.append("&subject=");
queryStrBuf.append(URLEncoder.encode(DN));
@@ -412,7 +415,7 @@ public class UserEnroll extends TestClient {
query = queryStrBuf.toString();
System.out.println(query);
- queryStrBuf = null;
+ queryStrBuf = null;
}
public int getRequestId() {
@@ -430,16 +433,16 @@ public class UserEnroll extends TestClient {
certType = "client";
ssl_client = "true";
debug = true;
- return(pkcs10());
+ return (pkcs10());
}
public boolean Enroll() {
debug = true;
- return(pkcs10());
+ return (pkcs10());
}
/**
- * Read the properties file
+ * Read the properties file
**/
public boolean readProperties() {
@@ -493,12 +496,12 @@ public class UserEnroll extends TestClient {
debug = false;
} else if (de.equals("true")) {
debug = true;
- } else {
+ } else {
debug = false;
}
// Enroll using a pkscks10 request
- return(pkcs10());
+ return (pkcs10());
}
public static void main(String args[]) {
@@ -512,27 +515,20 @@ public class UserEnroll extends TestClient {
"secret12", "true", "1024", "RSA", "rn", "re", "client");
e.clientCertEnroll();
-
- /* if ( args.length < 1)
- {
- System.out.println("Usage : propertiesfile");
- System.exit(0);
- }
-
-
- UserEnroll t = new UserEnroll(args[0]);
- st=t.enroll();
- if (st){
- System.out.println("User Enrolled successfully . RequestId is "+t.getrequestId());
- System.exit(t.getRequestId());
- }
- else{
-
- System.out.println("Error: " + t.getErrorDetail());
- System.exit(0);
- }
+
+ /*
+ * if ( args.length < 1) { System.out.println("Usage : propertiesfile");
+ * System.exit(0); }
+ *
+ *
+ * UserEnroll t = new UserEnroll(args[0]); st=t.enroll(); if (st){
+ * System
+ * .out.println("User Enrolled successfully . RequestId is "+t.getrequestId
+ * ()); System.exit(t.getRequestId()); } else{
+ *
+ * System.out.println("Error: " + t.getErrorDetail()); System.exit(0); }
*/
}// end of function main
-} // end of class
+} // end of class
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/Utilities.java b/pki/base/silent/src/com/netscape/pkisilent/common/Utilities.java
index 3d90c841..d754fb11 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/Utilities.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/Utilities.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.common;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -79,7 +80,7 @@ public class Utilities {
StringBuffer buf = new StringBuffer();
int end = token.length();
int begin = 0;
-
+
if (token.endsWith(";")) {
end--;
}
@@ -154,10 +155,8 @@ public class Utilities {
}
/*
- * format of the file should be like this:
- * -----BEGIN CERTIFICATE-----
- * base64 encoded certificate
- * -----END CERTIFICATE-----
+ * format of the file should be like this: -----BEGIN CERTIFICATE-----
+ * base64 encoded certificate -----END CERTIFICATE-----
*/
public String getcertfromfile(String filename) {
StringBuffer tempBuffer = new StringBuffer();
@@ -175,7 +174,7 @@ public class Utilities {
}
tempBuffer.append(temp);
}
-
+
return tempBuffer.toString();
} catch (Exception e) {
System.out.println("ERROR: getcertfromfile" + e.toString());
@@ -205,10 +204,8 @@ public class Utilities {
}
/*
- * format of the file should be like this:
- * -----BEGIN CERTIFICATE REVOCATION LIST-----
- * base64 encoded CRL
- * -----END CERTIFICATE REVOCATION LIST-----
+ * format of the file should be like this: -----BEGIN CERTIFICATE REVOCATION
+ * LIST----- base64 encoded CRL -----END CERTIFICATE REVOCATION LIST-----
*/
public String getcrlfromfile(String filename) {
StringBuffer tempBuffer = new StringBuffer();
@@ -222,7 +219,7 @@ public class Utilities {
tempBuffer.append(temp);
}
-
+
return tempBuffer.toString();
} catch (Exception e) {
System.out.println("ERROR: getcrlfromfile" + e.toString());
@@ -232,10 +229,8 @@ public class Utilities {
}
/*
- * format of the file should be like this:
- * -----BEGIN CERTIFICATE-----
- * base64 encoded certificate
- * -----END CERTIFICATE-----
+ * format of the file should be like this: -----BEGIN CERTIFICATE-----
+ * base64 encoded certificate -----END CERTIFICATE-----
*/
public String getcafromfile(String filename) {
StringBuffer tempBuffer = new StringBuffer();
@@ -249,7 +244,7 @@ public class Utilities {
tempBuffer.append(temp);
}
-
+
return tempBuffer.toString();
} catch (Exception e) {
System.out.println("ERROR: getcafromfile" + e.toString());
@@ -259,12 +254,12 @@ public class Utilities {
}
/*
- * function for RFC 2254. converts a x509 certificate given as
- * a binary array[] to a Ldap filter string
+ * function for RFC 2254. converts a x509 certificate given as a binary
+ * array[] to a Ldap filter string
*/
public static String escapeBinaryData(byte data[]) {
String result = "";
-
+
for (int i = 0; i < data.length; i++) {
String s = Integer.toHexString((int) (0xff & data[i]));
@@ -313,15 +308,16 @@ public class Utilities {
certinfo.get(X509CertInfo.SERIAL_NUMBER);
SerialNumber sn = (SerialNumber) csn.get("NUMBER");
- // just adding serialnumber for add.
- // we can add mode here like subject name, extensions,issuer to this record.
+ // just adding serialnumber for add.
+ // we can add mode here like subject name, extensions,issuer to this
+ // record.
cr.serialNumber = sn.getNumber().toString().trim();
/* Get Subject Name */
CertificateSubjectName csn1 = (CertificateSubjectName)
certinfo.get(X509CertInfo.SUBJECT);
-
+
X500Name dname = (X500Name) csn1.get(CertificateSubjectName.DN_NAME);
String pp = "";
@@ -343,7 +339,4 @@ public class Utilities {
}
-}
-
-
-; // end class
+}; // end class
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/checkRequest.java b/pki/base/silent/src/com/netscape/pkisilent/common/checkRequest.java
index c67689e4..376ad5c9 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/checkRequest.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/checkRequest.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.common;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -17,7 +18,6 @@ package com.netscape.pkisilent.common;
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
-
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
@@ -29,15 +29,13 @@ import java.util.GregorianCalendar;
import org.mozilla.jss.ssl.SSLSocket;
-
-
/**
- * CMS Test framework .
- * Submits a checkRequestStatus request to the server. parses the response from server and can import cert to the specified client database.
- *<P>
+ * CMS Test framework . Submits a checkRequestStatus request to the server.
+ * parses the response from server and can import cert to the specified client
+ * database.
+ * <P>
*/
-
public class checkRequest extends TestClient {
private int i;
@@ -57,32 +55,32 @@ public class checkRequest extends TestClient {
private String tokenpwd;
private String cdir;
- // public methods
+ // public methods
/**
* Constructor . Takes the parameter for Properties file name
* <p>
- * @param propfilename name of the parameter file
+ *
+ * @param propfilename name of the parameter file
*/
-
public checkRequest(String pfile) {
propfileName = pfile;
}
/**
- * Constructor . Takes the parameter for hostname and EESSLportnumber
+ * Constructor . Takes the parameter for hostname and EESSLportnumber
* <p>
*/
public checkRequest(String h, String p) {
host = h;
ports = p;
- }
- ;
+ };
/**
- * Constructor . Takes the parameter for hostname , EESSLportnumber , Requestnumber and ImportCert ( true/false)
+ * Constructor . Takes the parameter for hostname , EESSLportnumber ,
+ * Requestnumber and ImportCert ( true/false)
* <p>
*/
@@ -94,11 +92,12 @@ public class checkRequest extends TestClient {
}
/**
- * Constructor . Takes the parameter for hostname , EESSLportnumber , certdbdir, certdbpassword, Requestnumber ,certnickname and ImportCert ( true/false)
+ * Constructor . Takes the parameter for hostname , EESSLportnumber ,
+ * certdbdir, certdbpassword, Requestnumber ,certnickname and ImportCert (
+ * true/false)
* <p>
*/
-
public checkRequest(String hs, String pt, String certdir, String certtokenpwd, String seqnum, String nickname, String impc) {
host = hs;
ports = pt;
@@ -154,11 +153,10 @@ public class checkRequest extends TestClient {
}
/**
- * returns the hex serial number of the certificate
+ * returns the hex serial number of the certificate
**/
-
- public String getSerialNumberHex() {
+ public String getSerialNumberHex() {
return serialNumber;
}
@@ -166,7 +164,7 @@ public class checkRequest extends TestClient {
* returns the serial number as interger
**/
- public int getSerialNumber() {
+ public int getSerialNumber() {
if (serialNumber != null) {
Integer y = new Integer(Integer.parseInt(serialNumber, 16));
@@ -189,9 +187,9 @@ public class checkRequest extends TestClient {
cCrypt.setTokenPWD(tokenpwd);
cCrypt.setDebug(debug);
- if (!cCrypt.loginDB()) {
- System.out.println("Error : Login certdb failed ");
- System.err.println("FAIL : Login certdb failed ");
+ if (!cCrypt.loginDB()) {
+ System.out.println("Error : Login certdb failed ");
+ System.err.println("FAIL : Login certdb failed ");
return false;
}
@@ -235,9 +233,7 @@ public class checkRequest extends TestClient {
return false;
}
-
-
- // Private functions
+ // Private functions
private void setElapsedTime(long dif) {
elapsedTime = dif;
@@ -271,12 +267,12 @@ public class checkRequest extends TestClient {
tmp = cCrypt.normalizeForLDAP(getCert());
if (debug) {
System.out.println(tmp);
- }
+ }
fos.write(("usercertificate:: ").getBytes());
fos.write(tmp.getBytes());
fos.close();
} else {
- String tmp = cCrypt.normalize(getCert());
+ String tmp = cCrypt.normalize(getCert());
if (debug) {
System.out.println(tmp);
@@ -285,21 +281,21 @@ public class checkRequest extends TestClient {
fos.close();
}
-
+
} catch (Exception e) {
System.out.println(
"exception in writeCert2File: " + e.getMessage());
return false;
}
- }
+ }
return true;
}
private boolean importCert(String certpack) {
- if (importcert.equals("false")) {
+ if (importcert.equals("false")) {
return true;
}
@@ -380,8 +376,8 @@ public class checkRequest extends TestClient {
boolean st = true;
String retriveStr[] = {
- "record.base64Cert=", "record.certPrettyPrint=",
- "header.certChainBase64 = ", "header.certPrettyPrint = "};
+ "record.base64Cert=", "record.certPrettyPrint=",
+ "header.certChainBase64 = ", "header.certPrettyPrint = " };
String baseCertStr, certPrettyprintStr;
if (AUTH.equals("ra")) {
@@ -391,19 +387,19 @@ public class checkRequest extends TestClient {
baseCertStr = retriveStr[2];
certPrettyprintStr = retriveStr[3];
}
-
+
if (line.indexOf(baseCertStr) != -1) {
// if status is complete retrieve cert
baseCert = line.substring(baseCertStr.length() + 1,
line.indexOf(";", 10) - 1);
if (importcert.equals("true")) {
- if (importCert(baseCert)) {
+ if (importCert(baseCert)) {
st = true;
}
} else {
st = true;
- }
+ }
}
if (line.indexOf(certPrettyprintStr) != -1) {
@@ -475,9 +471,9 @@ public class checkRequest extends TestClient {
while ((line = stdin.readLine()) != null) {
switch (type) {
- case 1:
+ case 1:
RetrieveRequestDetail(line);
- st = true;
+ st = true;
break;
case 2:
@@ -488,7 +484,7 @@ public class checkRequest extends TestClient {
System.out.println("invalid format");
}
-
+
}
stdin.close();
socket.close();
@@ -517,9 +513,9 @@ public class checkRequest extends TestClient {
if (debug) {
System.out.println(serialNumber);
}
-
+
return st;
-
+
}
private void buildquery() {
@@ -527,7 +523,7 @@ public class checkRequest extends TestClient {
StringBuffer queryStrBuf = new StringBuffer();
if (type == 1) {
- ACTION_STRING = "/checkRequest";
+ ACTION_STRING = "/checkRequest";
queryStrBuf.append("requestId=");
queryStrBuf.append(requestId);
queryStrBuf.append("&importCert=true");
@@ -592,23 +588,23 @@ public class checkRequest extends TestClient {
}
// Enroll using a pkscks10 request
- return(checkRequestStatus());
+ return (checkRequestStatus());
}
public static void main(String args[]) {
// Exit Status - (0) for error/Fail
// - requestId Pass
boolean st;
-
+
if (args.length < 1) {
System.out.println("Usage : propertiesfile");
System.exit(0);
- }
+ }
checkRequest t = new checkRequest(args[0]);
st = t.readProperties();
- if (st) {
+ if (st) {
System.exit(t.getSerialNumber());
} else {
@@ -619,5 +615,5 @@ public class checkRequest extends TestClient {
}
}// end of function main
-} // end of class
+} // end of class
diff --git a/pki/base/silent/src/com/netscape/pkisilent/http/CertSelection.java b/pki/base/silent/src/com/netscape/pkisilent/http/CertSelection.java
index 078bb588..ff541b6c 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/http/CertSelection.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/http/CertSelection.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.http;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -21,28 +22,24 @@ import java.util.Vector;
import org.mozilla.jss.ssl.SSLClientCertificateSelectionCallback;
+public class CertSelection implements SSLClientCertificateSelectionCallback {
-public class CertSelection implements SSLClientCertificateSelectionCallback
-{
-
- // make the select() call to use this client cert
- public static String client_cert = null;
+ // make the select() call to use this client cert
+ public static String client_cert = null;
- public void setClientCert(String nickname)
- {
- client_cert = nickname;
- }
+ public void setClientCert(String nickname) {
+ client_cert = nickname;
+ }
- public String select(@SuppressWarnings("rawtypes") Vector nicknames)
- {
+ public String select(@SuppressWarnings("rawtypes") Vector nicknames) {
- // when this method is called by SSLSocket we get a vector
- // of nicknames to select similar to the way the browser presents
- // the list.
+ // when this method is called by SSLSocket we get a vector
+ // of nicknames to select similar to the way the browser presents
+ // the list.
- // We will just use the one thats set by setClientCert()
+ // We will just use the one thats set by setClientCert()
- return client_cert;
- }
+ return client_cert;
+ }
}; // end class
diff --git a/pki/base/silent/src/com/netscape/pkisilent/http/HTMLDocument.java b/pki/base/silent/src/com/netscape/pkisilent/http/HTMLDocument.java
index df95f861..44afe824 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/http/HTMLDocument.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/http/HTMLDocument.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.http;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -25,727 +26,578 @@ import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-
-
-public class HTMLDocument
-{
- // Indicates whether this HTML document has been parsed.
- boolean parsed;
-
- // A list of URLs of files that should be retrieved along with the main
- // contents of the document. This may include any images contained in the
- // document, and possibly any external stylesheets.
- LinkedHashSet<String> associatedFiles;
-
- // A list of URLs of frames that are contained in the document.
- LinkedHashSet<String> documentFrames;
-
- // A list of URLs of links that are contained in the document.
- LinkedHashSet<String> documentLinks;
-
- // A list of URLs of images that are contained in the document.
- LinkedHashSet<String> documentImages;
-
- // A regular expression pattern that can be used to extract a URI from an HREF
- // tag.
- Pattern hrefPattern;
-
- // A regular expression pattern that can be used to extract a URI from a SRC
- // tag.
- Pattern srcPattern;
-
- // The base URL for relative links in this document.
- String baseURL;
-
- // The URL that may be used to access this document.
- String documentURL;
-
- // The actual contents of the page.
- String htmlData;
-
- // The contents of the page converted to lowercase for easier matching.
- String lowerData;
-
- // The URL for this document with only protocol, host, and port (i.e., no
- // file).
- String protocolHostPort;
-
- // A string buffer containing the contents of the page with tags removed.
- StringBuffer textData;
-
-
- // A set of private variables used for internal processing.
- private boolean lastElementIsAssociatedFile;
- private boolean lastElementIsChunk;
- private boolean lastElementIsComment;
- private boolean lastElementIsFrame;
- private boolean lastElementIsImage;
- private boolean lastElementIsLink;
- private boolean lastElementIsText;
- private int lastElementEndPos;
- private int lastElementStartPos;
- private String lastURL;
-
- // constructor that helps to parse without url stuff
- public HTMLDocument(String htmlData)
- {
- this.documentURL = null;
- this.htmlData = htmlData;
- lowerData = htmlData.toLowerCase();
- associatedFiles = null;
- documentLinks = null;
- documentImages = null;
- textData = null;
- parsed = false;
-
-
- // Create the regex patterns that we will use for extracting URIs from tags.
- hrefPattern = Pattern.compile(".*?[hH][rR][eE][fF][\\s=\\\"\\']+" +
+public class HTMLDocument {
+ // Indicates whether this HTML document has been parsed.
+ boolean parsed;
+
+ // A list of URLs of files that should be retrieved along with the main
+ // contents of the document. This may include any images contained in the
+ // document, and possibly any external stylesheets.
+ LinkedHashSet<String> associatedFiles;
+
+ // A list of URLs of frames that are contained in the document.
+ LinkedHashSet<String> documentFrames;
+
+ // A list of URLs of links that are contained in the document.
+ LinkedHashSet<String> documentLinks;
+
+ // A list of URLs of images that are contained in the document.
+ LinkedHashSet<String> documentImages;
+
+ // A regular expression pattern that can be used to extract a URI from an
+ // HREF
+ // tag.
+ Pattern hrefPattern;
+
+ // A regular expression pattern that can be used to extract a URI from a SRC
+ // tag.
+ Pattern srcPattern;
+
+ // The base URL for relative links in this document.
+ String baseURL;
+
+ // The URL that may be used to access this document.
+ String documentURL;
+
+ // The actual contents of the page.
+ String htmlData;
+
+ // The contents of the page converted to lowercase for easier matching.
+ String lowerData;
+
+ // The URL for this document with only protocol, host, and port (i.e., no
+ // file).
+ String protocolHostPort;
+
+ // A string buffer containing the contents of the page with tags removed.
+ StringBuffer textData;
+
+ // A set of private variables used for internal processing.
+ private boolean lastElementIsAssociatedFile;
+ private boolean lastElementIsChunk;
+ private boolean lastElementIsComment;
+ private boolean lastElementIsFrame;
+ private boolean lastElementIsImage;
+ private boolean lastElementIsLink;
+ private boolean lastElementIsText;
+ private int lastElementEndPos;
+ private int lastElementStartPos;
+ private String lastURL;
+
+ // constructor that helps to parse without url stuff
+ public HTMLDocument(String htmlData) {
+ this.documentURL = null;
+ this.htmlData = htmlData;
+ lowerData = htmlData.toLowerCase();
+ associatedFiles = null;
+ documentLinks = null;
+ documentImages = null;
+ textData = null;
+ parsed = false;
+
+ // Create the regex patterns that we will use for extracting URIs from
+ // tags.
+ hrefPattern = Pattern.compile(".*?[hH][rR][eE][fF][\\s=\\\"\\']+" +
"([^\\s\\\"\\'\\>]+).*", Pattern.DOTALL);
- srcPattern = Pattern.compile(".*?[sS][rR][cC][\\s=\\\"\\']+" +
+ srcPattern = Pattern.compile(".*?[sS][rR][cC][\\s=\\\"\\']+" +
"([^\\s\\\"\\'\\>]+).*", Pattern.DOTALL);
- }
-
-
- /**
- * Creates a new HTML document using the provided data.
- *
- * @param documentURL The URL for this document.
- * @param htmlData The actual data contained in the HTML document.
- */
- public HTMLDocument(String documentURL, String htmlData)
- throws MalformedURLException
- {
- this.documentURL = documentURL;
- this.htmlData = htmlData;
- lowerData = htmlData.toLowerCase();
- associatedFiles = null;
- documentLinks = null;
- documentImages = null;
- textData = null;
- parsed = false;
-
-
- // Create the regex patterns that we will use for extracting URIs from tags.
- hrefPattern = Pattern.compile(".*?[hH][rR][eE][fF][\\s=\\\"\\']+" +
+ }
+
+ /**
+ * Creates a new HTML document using the provided data.
+ *
+ * @param documentURL The URL for this document.
+ * @param htmlData The actual data contained in the HTML document.
+ */
+ public HTMLDocument(String documentURL, String htmlData)
+ throws MalformedURLException {
+ this.documentURL = documentURL;
+ this.htmlData = htmlData;
+ lowerData = htmlData.toLowerCase();
+ associatedFiles = null;
+ documentLinks = null;
+ documentImages = null;
+ textData = null;
+ parsed = false;
+
+ // Create the regex patterns that we will use for extracting URIs from
+ // tags.
+ hrefPattern = Pattern.compile(".*?[hH][rR][eE][fF][\\s=\\\"\\']+" +
"([^\\s\\\"\\'\\>]+).*", Pattern.DOTALL);
- srcPattern = Pattern.compile(".*?[sS][rR][cC][\\s=\\\"\\']+" +
+ srcPattern = Pattern.compile(".*?[sS][rR][cC][\\s=\\\"\\']+" +
"([^\\s\\\"\\'\\>]+).*", Pattern.DOTALL);
- URL url = new URL(documentURL);
- String urlPath = url.getPath();
- if ((urlPath == null) || (urlPath.length() == 0))
- {
- baseURL = documentURL;
- protocolHostPort = documentURL;
- }
- else if (urlPath.equals("/"))
- {
- baseURL = documentURL;
- protocolHostPort = documentURL.substring(0, documentURL.length()-1);
- }
- else if (urlPath.endsWith("/"))
- {
- baseURL = documentURL;
-
- int port = url.getPort();
- if (port > 0)
- {
- protocolHostPort = url.getProtocol() + "://" + url.getHost() + ":" +
+ URL url = new URL(documentURL);
+ String urlPath = url.getPath();
+ if ((urlPath == null) || (urlPath.length() == 0)) {
+ baseURL = documentURL;
+ protocolHostPort = documentURL;
+ } else if (urlPath.equals("/")) {
+ baseURL = documentURL;
+ protocolHostPort = documentURL.substring(0, documentURL.length() - 1);
+ } else if (urlPath.endsWith("/")) {
+ baseURL = documentURL;
+
+ int port = url.getPort();
+ if (port > 0) {
+ protocolHostPort = url.getProtocol() + "://" + url.getHost() + ":" +
port;
- }
- else
- {
- protocolHostPort = url.getProtocol() + "://" + url.getHost();
- }
- }
- else
- {
- int port = url.getPort();
- if (port > 0)
- {
- protocolHostPort = url.getProtocol() + "://" + url.getHost() + ":" +
+ } else {
+ protocolHostPort = url.getProtocol() + "://" + url.getHost();
+ }
+ } else {
+ int port = url.getPort();
+ if (port > 0) {
+ protocolHostPort = url.getProtocol() + "://" + url.getHost() + ":" +
port;
- }
- else
- {
- protocolHostPort = url.getProtocol() + "://" + url.getHost();
- }
-
- File urlFile = new File(urlPath);
- String parentDirectory = urlFile.getParent();
- if ((parentDirectory == null) || (parentDirectory.length() == 0))
- {
- parentDirectory = "/";
- }
- else if (! parentDirectory.startsWith("/"))
- {
- parentDirectory = "/" + parentDirectory;
- }
-
- baseURL = protocolHostPort + parentDirectory;
- }
-
- if (! baseURL.endsWith("/"))
- {
- baseURL = baseURL + "/";
- }
- }
-
-
-
- /**
- * Actually parses the HTML document and extracts useful elements from it.
- *
- * @return <CODE>true</CODE> if the page could be parsed successfully, or
- * <CODE>false</CODE> if not.
- */
- public boolean parse()
- {
- if (parsed)
- {
- return true;
- }
+ } else {
+ protocolHostPort = url.getProtocol() + "://" + url.getHost();
+ }
+ File urlFile = new File(urlPath);
+ String parentDirectory = urlFile.getParent();
+ if ((parentDirectory == null) || (parentDirectory.length() == 0)) {
+ parentDirectory = "/";
+ } else if (!parentDirectory.startsWith("/")) {
+ parentDirectory = "/" + parentDirectory;
+ }
- try
- {
- associatedFiles = new LinkedHashSet<String>();
- documentFrames = new LinkedHashSet<String>();
- documentLinks = new LinkedHashSet<String>();
- documentImages = new LinkedHashSet<String>();
- textData = new StringBuffer();
-
- lastElementStartPos = 0;
- lastElementEndPos = -1;
- String element;
- while ((element = nextDocumentElement()) != null)
- {
- if (element.length() == 0)
- {
- continue;
+ baseURL = protocolHostPort + parentDirectory;
}
- if (lastElementIsText)
- {
- char lastChar;
- if (textData.length() == 0)
- {
- lastChar = ' ';
- }
- else
- {
- lastChar = textData.charAt(textData.length()-1);
- }
- char firstChar = element.charAt(0);
- if (! ((lastChar == ' ') || (lastChar == '\t') ||
- (lastChar == '\r') || (lastChar == '\n')) ||
- (firstChar == ' ') || (firstChar == '\t') ||
- (firstChar == '\r') || (firstChar == '\n'))
- {
- textData.append(" ");
- }
-
- textData.append(element);
- }
- else if (lastElementIsImage)
- {
- if (lastURL != null)
- {
- documentImages.add(lastURL);
- associatedFiles.add(lastURL);
- }
+ if (!baseURL.endsWith("/")) {
+ baseURL = baseURL + "/";
}
- else if (lastElementIsFrame)
- {
- if (lastURL != null)
- {
- documentFrames.add(lastURL);
- associatedFiles.add(lastURL);
- }
- }
- else if (lastElementIsLink)
- {
- if (lastURL != null)
- {
- documentLinks.add(lastURL);
- }
- }
- else if (lastElementIsAssociatedFile)
- {
- if (lastURL != null)
- {
- associatedFiles.add(lastURL);
- }
- }
- else if (lastElementIsChunk || lastElementIsComment)
- {
- // Don't need to do anything with this.
- }
- else
- {
- // Also don't need anything here.
- }
- }
-
- parsed = true;
- }
- catch (Exception e)
- {
- associatedFiles = null;
- documentLinks = null;
- documentImages = null;
- textData = null;
- parsed = false;
}
- return parsed;
- }
+ /**
+ * Actually parses the HTML document and extracts useful elements from it.
+ *
+ * @return <CODE>true</CODE> if the page could be parsed successfully, or
+ * <CODE>false</CODE> if not.
+ */
+ public boolean parse() {
+ if (parsed) {
+ return true;
+ }
+ try {
+ associatedFiles = new LinkedHashSet<String>();
+ documentFrames = new LinkedHashSet<String>();
+ documentLinks = new LinkedHashSet<String>();
+ documentImages = new LinkedHashSet<String>();
+ textData = new StringBuffer();
+
+ lastElementStartPos = 0;
+ lastElementEndPos = -1;
+ String element;
+ while ((element = nextDocumentElement()) != null) {
+ if (element.length() == 0) {
+ continue;
+ }
+
+ if (lastElementIsText) {
+ char lastChar;
+ if (textData.length() == 0) {
+ lastChar = ' ';
+ } else {
+ lastChar = textData.charAt(textData.length() - 1);
+ }
+ char firstChar = element.charAt(0);
+ if (!((lastChar == ' ') || (lastChar == '\t') ||
+ (lastChar == '\r') || (lastChar == '\n')) ||
+ (firstChar == ' ') || (firstChar == '\t') ||
+ (firstChar == '\r') || (firstChar == '\n')) {
+ textData.append(" ");
+ }
+
+ textData.append(element);
+ } else if (lastElementIsImage) {
+ if (lastURL != null) {
+ documentImages.add(lastURL);
+ associatedFiles.add(lastURL);
+ }
+ } else if (lastElementIsFrame) {
+ if (lastURL != null) {
+ documentFrames.add(lastURL);
+ associatedFiles.add(lastURL);
+ }
+ } else if (lastElementIsLink) {
+ if (lastURL != null) {
+ documentLinks.add(lastURL);
+ }
+ } else if (lastElementIsAssociatedFile) {
+ if (lastURL != null) {
+ associatedFiles.add(lastURL);
+ }
+ } else if (lastElementIsChunk || lastElementIsComment) {
+ // Don't need to do anything with this.
+ } else {
+ // Also don't need anything here.
+ }
+ }
+ parsed = true;
+ } catch (Exception e) {
+ associatedFiles = null;
+ documentLinks = null;
+ documentImages = null;
+ textData = null;
+ parsed = false;
+ }
- /**
- * Retrieves the next element from the HTML document. An HTML element can
- * include a string of plain text, a single HTML tag, or a larger chunk of
- * HTML including a start and end tag, all of which should be considered a
- * single element.
- */
- private String nextDocumentElement()
- {
- // If we're at the end of the HTML, then return null.
- if (lastElementEndPos >= htmlData.length())
- {
- return null;
+ return parsed;
}
+ /**
+ * Retrieves the next element from the HTML document. An HTML element can
+ * include a string of plain text, a single HTML tag, or a larger chunk of
+ * HTML including a start and end tag, all of which should be considered a
+ * single element.
+ */
+ private String nextDocumentElement() {
+ // If we're at the end of the HTML, then return null.
+ if (lastElementEndPos >= htmlData.length()) {
+ return null;
+ }
- // Initialize the variables we will use for the search.
- lastElementStartPos = lastElementEndPos+1;
- lastElementIsAssociatedFile = false;
- lastElementIsChunk = false;
- lastElementIsComment = false;
- lastElementIsFrame = false;
- lastElementIsImage = false;
- lastElementIsLink = false;
- lastElementIsText = false;
- lastURL = null;
-
-
- // Find the location of the next open angle bracket. If there is none, then
- // the rest of the document must be plain text.
- int openPos = lowerData.indexOf('<', lastElementStartPos);
- if (openPos < 0)
- {
- lastElementEndPos = htmlData.length();
- lastElementIsText = true;
- return htmlData.substring(lastElementStartPos);
- }
+ // Initialize the variables we will use for the search.
+ lastElementStartPos = lastElementEndPos + 1;
+ lastElementIsAssociatedFile = false;
+ lastElementIsChunk = false;
+ lastElementIsComment = false;
+ lastElementIsFrame = false;
+ lastElementIsImage = false;
+ lastElementIsLink = false;
+ lastElementIsText = false;
+ lastURL = null;
+
+ // Find the location of the next open angle bracket. If there is none,
+ // then
+ // the rest of the document must be plain text.
+ int openPos = lowerData.indexOf('<', lastElementStartPos);
+ if (openPos < 0) {
+ lastElementEndPos = htmlData.length();
+ lastElementIsText = true;
+ return htmlData.substring(lastElementStartPos);
+ }
+ // If the location of the next open tag is not we started looking, then
+ // read
+ // everything up to that tag as text.
+ if (openPos > lastElementStartPos) {
+ lastElementEndPos = openPos - 1;
+ lastElementIsText = true;
+ return htmlData.substring(lastElementStartPos, openPos);
+ }
- // If the location of the next open tag is not we started looking, then read
- // everything up to that tag as text.
- if (openPos > lastElementStartPos)
- {
- lastElementEndPos = openPos-1;
- lastElementIsText = true;
- return htmlData.substring(lastElementStartPos, openPos);
- }
+ // The start position is an open tag. See if the tag is actually "<!--",
+ // which indicates an HTML comment. If that's the case, then find the
+ // closing "-->".
+ if (openPos == lowerData.indexOf("<!--", lastElementStartPos)) {
+ int closePos = lowerData.indexOf("-->", openPos + 1);
+ if (closePos < 0) {
+ // This looks like an unterminated comment. We can't do much
+ // else
+ // here, so just stop parsing.
+ return null;
+ } else {
+ lastElementEndPos = closePos + 2;
+ lastElementIsComment = true;
+ return htmlData.substring(lastElementStartPos, lastElementEndPos + 1);
+ }
+ }
+ // Find the location of the next close angle bracket. If there is none,
+ // then we have an unmatched open tag. What to do here? I guess just
+ // treat
+ // the rest of the document as text.
+ int closePos = lowerData.indexOf('>', openPos + 1);
+ if (closePos < 0) {
+ lastElementEndPos = htmlData.length();
+ lastElementIsText = true;
+ return htmlData.substring(lastElementStartPos);
+ }
- // The start position is an open tag. See if the tag is actually "<!--",
- // which indicates an HTML comment. If that's the case, then find the
- // closing "-->".
- if (openPos == lowerData.indexOf("<!--", lastElementStartPos))
- {
- int closePos = lowerData.indexOf("-->", openPos+1);
- if (closePos < 0)
- {
- // This looks like an unterminated comment. We can't do much else
- // here, so just stop parsing.
- return null;
- }
- else
- {
- lastElementEndPos = closePos + 2;
- lastElementIsComment = true;
- return htmlData.substring(lastElementStartPos, lastElementEndPos+1);
- }
- }
+ // Grab the contents of the tag in both normal and lowercase.
+ String tag = htmlData.substring(openPos, closePos + 1);
+ String strippedTag = htmlData.substring(openPos + 1, closePos).trim();
+ StringTokenizer tokenizer = new StringTokenizer(strippedTag, " \t\r\n=\"'");
+ lastElementEndPos = closePos;
+ if (!tokenizer.hasMoreTokens()) {
+ return tag;
+ }
- // Find the location of the next close angle bracket. If there is none,
- // then we have an unmatched open tag. What to do here? I guess just treat
- // the rest of the document as text.
- int closePos = lowerData.indexOf('>', openPos+1);
- if (closePos < 0)
- {
- lastElementEndPos = htmlData.length();
- lastElementIsText = true;
- return htmlData.substring(lastElementStartPos);
- }
+ String token = tokenizer.nextToken();
+ String lowerToken = token.toLowerCase();
+
+ if (lowerToken.equals("a") || lowerToken.equals("area")) {
+ while (tokenizer.hasMoreTokens()) {
+ token = tokenizer.nextToken();
+ if (token.equalsIgnoreCase("href")) {
+ try {
+ Matcher matcher = hrefPattern.matcher(tag);
+ lastURL = uriToURL(matcher.replaceAll("$1"));
+ if (lastURL != null) {
+ lastElementIsLink = true;
+ }
+ } catch (Exception e) {
+ }
+ break;
+ }
+ }
+ } else if (lowerToken.equals("base")) {
+ while (tokenizer.hasMoreTokens()) {
+ token = tokenizer.nextToken();
+ if (token.equalsIgnoreCase("href")) {
+ try {
+ Matcher matcher = hrefPattern.matcher(tag);
+ String uri = matcher.replaceAll("$1");
+ if (!uri.endsWith("/")) {
+ uri = uri + "/";
+ }
+
+ baseURL = uri;
+ } catch (Exception e) {
+ }
+ break;
+ }
+ }
+ } else if (lowerToken.equals("frame") || lowerToken.equals("iframe") ||
+ lowerToken.equals("input")) {
+ while (tokenizer.hasMoreTokens()) {
+ token = tokenizer.nextToken();
+ if (token.equalsIgnoreCase("src")) {
+ try {
+ Matcher matcher = srcPattern.matcher(tag);
+ String uri = matcher.replaceAll("$1");
+ lastURL = uriToURL(uri);
+ if (lastURL != null) {
+ lastElementIsFrame = true;
+ lastElementIsAssociatedFile = true;
+ }
+ } catch (Exception e) {
+ }
+ break;
+ }
+ }
+ } else if (lowerToken.equals("img")) {
+ while (tokenizer.hasMoreTokens()) {
+ token = tokenizer.nextToken();
+ if (token.equalsIgnoreCase("src")) {
+ try {
+ Matcher matcher = srcPattern.matcher(tag);
+ String uri = matcher.replaceAll("$1");
+ lastURL = uriToURL(uri);
+ if (lastURL != null) {
+ lastElementIsImage = true;
+ }
+ } catch (Exception e) {
+ }
+ break;
+ }
+ }
+ } else if (lowerToken.equals("link")) {
+ boolean isStyleSheet = false;
+
+ while (tokenizer.hasMoreTokens()) {
+ token = tokenizer.nextToken();
+ if (token.equalsIgnoreCase("href")) {
+ try {
+ Matcher matcher = hrefPattern.matcher(tag);
+ String uri = matcher.replaceAll("$1");
+ lastURL = uriToURL(uri);
+ if (lastURL != null) {
+ lastElementIsLink = true;
+ }
+ } catch (Exception e) {
+ }
+ break;
+ } else if (token.equalsIgnoreCase("rel")) {
+ if (tokenizer.hasMoreTokens()) {
+ String relType = tokenizer.nextToken();
+ if (relType.equalsIgnoreCase("stylesheet")) {
+ isStyleSheet = true;
+ }
+ }
+ }
+ }
+ if (lastURL != null) {
+ if (isStyleSheet) {
+ lastElementIsAssociatedFile = true;
+ } else {
+ lastElementIsLink = true;
+ }
+ }
+ } else if (lowerToken.equals("script")) {
+ while (tokenizer.hasMoreTokens()) {
+ token = tokenizer.nextToken();
+ if (token.equalsIgnoreCase("src")) {
+ try {
+ Matcher matcher = srcPattern.matcher(tag);
+ String uri = matcher.replaceAll("$1");
+ lastURL = uriToURL(uri);
+ } catch (Exception e) {
+ }
+ break;
+ }
+ }
- // Grab the contents of the tag in both normal and lowercase.
- String tag = htmlData.substring(openPos, closePos+1);
- String strippedTag = htmlData.substring(openPos+1, closePos).trim();
- StringTokenizer tokenizer = new StringTokenizer(strippedTag, " \t\r\n=\"'");
- lastElementEndPos = closePos;
+ if (lastURL == null) {
+ int endScriptPos = lowerData.indexOf("</script>", lastElementEndPos + 1);
+ if (endScriptPos > 0) {
+ lastElementEndPos = endScriptPos + 8;
+ tag = htmlData.substring(lastElementStartPos, lastElementEndPos + 1);
+ lastElementIsChunk = true;
+ }
+ } else {
+ lastElementIsAssociatedFile = true;
+ }
+ }
- if (! tokenizer.hasMoreTokens())
- {
- return tag;
+ return tag;
}
- String token = tokenizer.nextToken();
- String lowerToken = token.toLowerCase();
-
- if (lowerToken.equals("a") || lowerToken.equals("area"))
- {
- while (tokenizer.hasMoreTokens())
- {
- token = tokenizer.nextToken();
- if (token.equalsIgnoreCase("href"))
- {
- try
- {
- Matcher matcher = hrefPattern.matcher(tag);
- lastURL = uriToURL(matcher.replaceAll("$1"));
- if (lastURL != null)
- {
- lastElementIsLink = true;
+ /**
+ * Converts the provided URI to a URL. The provided URI may be a URL
+ * already, or it may also be an absolute path on the server or a path
+ * relative to the base URL.
+ *
+ * @param uri The URI to convert to a URL.
+ *
+ * @return The URL based on the provided URI.
+ */
+ private String uriToURL(String uri) {
+ String url = null;
+
+ if (uri.indexOf("://") > 0) {
+ if (uri.startsWith("http")) {
+ url = uri;
}
- } catch (Exception e) {}
- break;
+ } else if (uri.startsWith("/")) {
+ url = protocolHostPort + uri;
+ } else {
+ url = baseURL + uri;
}
- }
+
+ return url;
}
- else if (lowerToken.equals("base"))
- {
- while (tokenizer.hasMoreTokens())
- {
- token = tokenizer.nextToken();
- if (token.equalsIgnoreCase("href"))
- {
- try
- {
- Matcher matcher = hrefPattern.matcher(tag);
- String uri = matcher.replaceAll("$1");
- if (! uri.endsWith("/"))
- {
- uri = uri + "/";
- }
- baseURL = uri;
- } catch (Exception e) {}
- break;
- }
- }
+ /**
+ * Retrieves the URL of this HTML document.
+ *
+ * @return The URL of this HTML document.
+ */
+ public String getDocumentURL() {
+ return documentURL;
}
- else if (lowerToken.equals("frame") || lowerToken.equals("iframe") ||
- lowerToken.equals("input"))
- {
- while (tokenizer.hasMoreTokens())
- {
- token = tokenizer.nextToken();
- if (token.equalsIgnoreCase("src"))
- {
- try
- {
- Matcher matcher = srcPattern.matcher(tag);
- String uri = matcher.replaceAll("$1");
- lastURL = uriToURL(uri);
- if (lastURL != null)
- {
- lastElementIsFrame = true;
- lastElementIsAssociatedFile = true;
- }
- } catch (Exception e) {}
- break;
- }
- }
+
+ /**
+ * Retrieves the original HTML data used to create this document.
+ *
+ * @return The orginal HTML data used to create this document.
+ */
+ public String getHTMLData() {
+ return htmlData;
}
- else if (lowerToken.equals("img"))
- {
- while (tokenizer.hasMoreTokens())
- {
- token = tokenizer.nextToken();
- if (token.equalsIgnoreCase("src"))
- {
- try
- {
- Matcher matcher = srcPattern.matcher(tag);
- String uri = matcher.replaceAll("$1");
- lastURL = uriToURL(uri);
- if (lastURL != null)
- {
- lastElementIsImage = true;
+
+ /**
+ * Retrieves the contents of the HTML document with all tags removed.
+ *
+ * @return The contents of the HTML document with all tags removed, or
+ * <CODE>null</CODE> if a problem occurs while trying to parse the
+ * HTML.
+ */
+ public String getTextData() {
+ if (!parsed) {
+ if (!parse()) {
+ return null;
}
- } catch (Exception e) {}
- break;
}
- }
+
+ return textData.toString();
}
- else if (lowerToken.equals("link"))
- {
- boolean isStyleSheet = false;
-
- while (tokenizer.hasMoreTokens())
- {
- token = tokenizer.nextToken();
- if (token.equalsIgnoreCase("href"))
- {
- try
- {
- Matcher matcher = hrefPattern.matcher(tag);
- String uri = matcher.replaceAll("$1");
- lastURL = uriToURL(uri);
- if (lastURL != null)
- {
- lastElementIsLink = true;
- }
- } catch (Exception e) {}
- break;
- }
- else if (token.equalsIgnoreCase("rel"))
- {
- if (tokenizer.hasMoreTokens())
- {
- String relType = tokenizer.nextToken();
- if (relType.equalsIgnoreCase("stylesheet"))
- {
- isStyleSheet = true;
+
+ /**
+ * Retrieves an array containing a set of URLs parsed from the HTML document
+ * that reference files that would normally be downloaded as part of
+ * retrieving a page in a browser. This includes images and external style
+ * sheets.
+ *
+ * @return An array containing a set of URLs to files associated with the
+ * HTML document, or <CODE>null</CODE> if a problem occurs while
+ * trying to parse the HTML.
+ */
+ public String[] getAssociatedFiles() {
+ if (!parsed) {
+ if (!parse()) {
+ return null;
}
- }
}
- }
- if (lastURL != null)
- {
- if (isStyleSheet)
- {
- lastElementIsAssociatedFile = true;
- }
- else
- {
- lastElementIsLink = true;
- }
- }
- }
- else if (lowerToken.equals("script"))
- {
- while (tokenizer.hasMoreTokens())
- {
- token = tokenizer.nextToken();
- if (token.equalsIgnoreCase("src"))
- {
- try
- {
- Matcher matcher = srcPattern.matcher(tag);
- String uri = matcher.replaceAll("$1");
- lastURL = uriToURL(uri);
- } catch (Exception e) {}
- break;
- }
- }
-
- if (lastURL == null)
- {
- int endScriptPos = lowerData.indexOf("</script>", lastElementEndPos+1);
- if (endScriptPos > 0)
- {
- lastElementEndPos = endScriptPos + 8;
- tag = htmlData.substring(lastElementStartPos, lastElementEndPos+1);
- lastElementIsChunk = true;
- }
- }
- else
- {
- lastElementIsAssociatedFile = true;
- }
+ String[] urlArray = new String[associatedFiles.size()];
+ associatedFiles.toArray(urlArray);
+ return urlArray;
}
- return tag;
- }
-
-
-
- /**
- * Converts the provided URI to a URL. The provided URI may be a URL already,
- * or it may also be an absolute path on the server or a path relative to the
- * base URL.
- *
- * @param uri The URI to convert to a URL.
- *
- * @return The URL based on the provided URI.
- */
- private String uriToURL(String uri)
- {
- String url = null;
-
- if (uri.indexOf("://") > 0)
- {
- if (uri.startsWith("http"))
- {
- url = uri;
- }
- }
- else if (uri.startsWith("/"))
- {
- url = protocolHostPort + uri;
- }
- else
- {
- url = baseURL + uri;
- }
+ /**
+ * Retrieves an array containing a set of URLs parsed from the HTML document
+ * that are in the form of links to other content.
+ *
+ * @return An array containing a set of URLs parsed from the HTML document
+ * that are in the form of links to other content, or
+ * <CODE>null</CODE> if a problem occurs while trying to parse the
+ * HTML.
+ */
+ public String[] getDocumentLinks() {
+ if (!parsed) {
+ if (!parse()) {
+ return null;
+ }
+ }
- return url;
- }
-
-
-
- /**
- * Retrieves the URL of this HTML document.
- *
- * @return The URL of this HTML document.
- */
- public String getDocumentURL()
- {
- return documentURL;
- }
-
-
-
- /**
- * Retrieves the original HTML data used to create this document.
- *
- * @return The orginal HTML data used to create this document.
- */
- public String getHTMLData()
- {
- return htmlData;
- }
-
-
-
- /**
- * Retrieves the contents of the HTML document with all tags removed.
- *
- * @return The contents of the HTML document with all tags removed, or
- * <CODE>null</CODE> if a problem occurs while trying to parse the
- * HTML.
- */
- public String getTextData()
- {
- if (! parsed)
- {
- if (! parse())
- {
- return null;
- }
+ String[] urlArray = new String[documentLinks.size()];
+ documentLinks.toArray(urlArray);
+ return urlArray;
}
- return textData.toString();
- }
-
-
-
- /**
- * Retrieves an array containing a set of URLs parsed from the HTML document
- * that reference files that would normally be downloaded as part of
- * retrieving a page in a browser. This includes images and external style
- * sheets.
- *
- * @return An array containing a set of URLs to files associated with the
- * HTML document, or <CODE>null</CODE> if a problem occurs while
- * trying to parse the HTML.
- */
- public String[] getAssociatedFiles()
- {
- if (! parsed)
- {
- if (! parse())
- {
- return null;
- }
- }
+ /**
+ * Retrieves an array containing a set of URLs parsed from the HTML document
+ * that reference images used in the document.
+ *
+ * @return An array containing a set of URLs parsed from the HTML document
+ * that reference images used in the document.
+ */
+ public String[] getDocumentImages() {
+ if (!parsed) {
+ if (!parse()) {
+ return null;
+ }
+ }
- String[] urlArray = new String[associatedFiles.size()];
- associatedFiles.toArray(urlArray);
- return urlArray;
- }
-
-
-
- /**
- * Retrieves an array containing a set of URLs parsed from the HTML document
- * that are in the form of links to other content.
- *
- * @return An array containing a set of URLs parsed from the HTML document
- * that are in the form of links to other content, or
- * <CODE>null</CODE> if a problem occurs while trying to parse the
- * HTML.
- */
- public String[] getDocumentLinks()
- {
- if (! parsed)
- {
- if (! parse())
- {
- return null;
- }
+ String[] urlArray = new String[documentImages.size()];
+ documentImages.toArray(urlArray);
+ return urlArray;
}
- String[] urlArray = new String[documentLinks.size()];
- documentLinks.toArray(urlArray);
- return urlArray;
- }
-
-
-
- /**
- * Retrieves an array containing a set of URLs parsed from the HTML document
- * that reference images used in the document.
- *
- * @return An array containing a set of URLs parsed from the HTML document
- * that reference images used in the document.
- */
- public String[] getDocumentImages()
- {
- if (! parsed)
- {
- if (! parse())
- {
- return null;
- }
- }
+ /**
+ * Retrieves an array containing a set of URLs parsed from the HTML document
+ * that reference frames used in the document.
+ *
+ * @return An array containing a set of URLs parsed from the HTML document
+ * that reference frames used in the document.
+ */
+ public String[] getDocumentFrames() {
+ if (!parsed) {
+ if (!parse()) {
+ return null;
+ }
+ }
- String[] urlArray = new String[documentImages.size()];
- documentImages.toArray(urlArray);
- return urlArray;
- }
-
-
-
- /**
- * Retrieves an array containing a set of URLs parsed from the HTML document
- * that reference frames used in the document.
- *
- * @return An array containing a set of URLs parsed from the HTML document
- * that reference frames used in the document.
- */
- public String[] getDocumentFrames()
- {
- if (! parsed)
- {
- if (! parse())
- {
- return null;
- }
+ String[] urlArray = new String[documentFrames.size()];
+ documentFrames.toArray(urlArray);
+ return urlArray;
}
-
- String[] urlArray = new String[documentFrames.size()];
- documentFrames.toArray(urlArray);
- return urlArray;
- }
}
-
diff --git a/pki/base/silent/src/com/netscape/pkisilent/http/HTTPClient.java b/pki/base/silent/src/com/netscape/pkisilent/http/HTTPClient.java
index 066fb0b4..f22cb5c4 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/http/HTTPClient.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/http/HTTPClient.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.http;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -42,1367 +43,1203 @@ import com.netscape.pkisilent.argparser.ArgParser;
import com.netscape.pkisilent.argparser.StringHolder;
import com.netscape.pkisilent.common.ComCrypto;
+public class HTTPClient implements SSLCertificateApprovalCallback {
+
+ public static final int BUFFER_SIZE = 4096;
+ public boolean debugMode = true;
+
+ public static String basic_auth_header_value = null;
+
+ public static String cs_hostname = null;
+ public static String cs_port = null;
+ public static String ssl = null;
+ public static String client_certdb_dir = null;
+ public static String client_certdb_pwd = null;
+ public static String client_cert_nickname = null;
+ public static String uri = null;
+ public static String query = null;
+ public static String request_type = null;
+ public static String user_id = null;
+ public static String user_password = null;
+ public static String auth_type = null;
+ public static String debug = null;
+
+ public static boolean parse_xml = false;
+
+ public static X509Certificate server_cert = null;
-public class HTTPClient implements SSLCertificateApprovalCallback
-{
-
- public static final int BUFFER_SIZE = 4096;
- public boolean debugMode = true;
-
- public static String basic_auth_header_value = null;
-
- public static String cs_hostname = null;
- public static String cs_port = null;
- public static String ssl = null;
- public static String client_certdb_dir = null;
- public static String client_certdb_pwd = null;
- public static String client_cert_nickname = null;
- public static String uri = null;
- public static String query = null;
- public static String request_type = null;
- public static String user_id = null;
- public static String user_password = null;
- public static String auth_type = null;
- public static String debug = null;
-
- public static boolean parse_xml = false;
-
- public static X509Certificate server_cert = null;
-
- // cookie variable for CS install UI
- public static String j_session_id = null;
- public static boolean ecc_support = false;
-
-
-
-
- public HTTPClient()
- {
- // constructor
- // turn off ecc by default
- ecc_support = true;
- }
-
-
- public HTTPClient(boolean ecc)
- {
- ecc_support = ecc;
- }
-
- public boolean setCipherPref(SSLSocket socket)
- {
-
- if(ecc_support)
- {
- int ecc_Ciphers[] = {
- SSLSocket.TLS_ECDH_ECDSA_WITH_NULL_SHA, SSLSocket.TLS_ECDH_ECDSA_WITH_RC4_128_SHA,
- SSLSocket.TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, SSLSocket.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
- SSLSocket.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, SSLSocket.TLS_ECDHE_ECDSA_WITH_NULL_SHA,
- SSLSocket.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, SSLSocket.TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,
- SSLSocket.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, SSLSocket.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
- SSLSocket.TLS_ECDH_RSA_WITH_NULL_SHA, SSLSocket.TLS_ECDH_RSA_WITH_RC4_128_SHA,
- SSLSocket.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, SSLSocket.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,
- SSLSocket.TLS_ECDHE_RSA_WITH_NULL_SHA, SSLSocket.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
- SSLSocket.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSLSocket.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
- SSLSocket.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
- 0 };
-
- try
- {
- for (int i=0; i < ecc_Ciphers.length; i++)
- {
- if(ecc_Ciphers[i] > 0)
- socket.setCipherPreference(
- ecc_Ciphers[i],true);
- }
- }
- catch(Exception e)
- {
- System.out.println("ERROR: unable to set ECC Cipher List");
- System.out.println("ERROR: Exception = " + e.getMessage());
- }
-
- }
- return true;
- }
-
- public boolean disableSSL2(SSLSocket socket)
- {
- try
- {
- SSLSocket.enableSSL3Default(true);
- socket.enableSSL3(true);
- socket.enableSSL2(false);
- SSLSocket.enableSSL2Default(false);
+ // cookie variable for CS install UI
+ public static String j_session_id = null;
+ public static boolean ecc_support = false;
+
+ public HTTPClient() {
+ // constructor
+ // turn off ecc by default
+ ecc_support = true;
+ }
+
+ public HTTPClient(boolean ecc) {
+ ecc_support = ecc;
+ }
+
+ public boolean setCipherPref(SSLSocket socket) {
+
+ if (ecc_support) {
+ int ecc_Ciphers[] = {
+ SSLSocket.TLS_ECDH_ECDSA_WITH_NULL_SHA, SSLSocket.TLS_ECDH_ECDSA_WITH_RC4_128_SHA,
+ SSLSocket.TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, SSLSocket.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
+ SSLSocket.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, SSLSocket.TLS_ECDHE_ECDSA_WITH_NULL_SHA,
+ SSLSocket.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, SSLSocket.TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,
+ SSLSocket.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, SSLSocket.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
+ SSLSocket.TLS_ECDH_RSA_WITH_NULL_SHA, SSLSocket.TLS_ECDH_RSA_WITH_RC4_128_SHA,
+ SSLSocket.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, SSLSocket.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,
+ SSLSocket.TLS_ECDHE_RSA_WITH_NULL_SHA, SSLSocket.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
+ SSLSocket.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSLSocket.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
+ SSLSocket.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
+ 0 };
+
+ try {
+ for (int i = 0; i < ecc_Ciphers.length; i++) {
+ if (ecc_Ciphers[i] > 0)
+ socket.setCipherPreference(
+ ecc_Ciphers[i], true);
+ }
+ } catch (Exception e) {
+ System.out.println("ERROR: unable to set ECC Cipher List");
+ System.out.println("ERROR: Exception = " + e.getMessage());
+ }
+
+ }
+ return true;
+ }
+
+ public boolean disableSSL2(SSLSocket socket) {
+ try {
+ SSLSocket.enableSSL3Default(true);
+ socket.enableSSL3(true);
+ socket.enableSSL2(false);
+ SSLSocket.enableSSL2Default(false);
socket.enableV2CompatibleHello(false);
- }
- catch(Exception e)
- {
- System.out.println("ERROR: Exception = " + e.getMessage());
- }
- return true;
- }
-
- public X509Certificate getServerCert()
- {
- return server_cert;
- }
-
- public void set_parse_xml(boolean b)
- {
- parse_xml = b;
- }
-
- public boolean approve(X509Certificate cert,
- SSLCertificateApprovalCallback.ValidityStatus status)
- {
-
- // when this method is called by SSLSocket we get the server cert
- // we can capture this for future use.
- server_cert = cert;
- return true;
- }
-
- public boolean testsslConnect(String hostname, String portnumber)
- {
- boolean st = true;
-
- try
- {
-
- System.out.println("#############################################");
- System.out.println("Attempting to connect to: " + hostname + ":" +
- portnumber);
-
- Integer x = new Integer(portnumber);
- int port = x.intValue();
-
-
- SSLClientCertificateSelectionCallback certSelectionCallback =
- new TestClientCertificateSelectionCallback();
-
- Socket js = new Socket(InetAddress.getByName(hostname), port);
- SSLSocket socket = new SSLSocket(js, hostname, this,
- certSelectionCallback );
- setCipherPref(socket);
- disableSSL2(socket);
- socket.forceHandshake();
- System.out.println("Connected.");
- socket.setUseClientMode(true);
-
- // test connection to obtain server cert. close it.
- socket.close();
-
-
- }
-
- catch(Exception e)
- {
- System.err.println("Exception: Unable to Send Request:" +e);
- e.printStackTrace();
- st = false;
- }
-
- if(!st)
- return false;
- else
- return true;
- }
-
- // performs ssl connect to given host/port requiring client auth
- // posts the given query data
- // returns HTTPResponse
- public HTTPResponse sslConnectClientAuth(String hostname, String portnumber,
- String client_cert,String url,String query)
- {
-
- boolean st = true;
- HTTPResponse hr = null;
-
- try
- {
-
- System.out.println("#############################################");
- System.out.println("Attempting to connect to: " + hostname + ":" +
- portnumber);
-
- Integer x = new Integer(portnumber);
- int port = x.intValue();
-
-
- SSLCertificateApprovalCallback approvalCallback =
- new TestCertApprovalCallback();
- CertSelection certSelectionCallback =
- new CertSelection();
-
- // Client Cert for Auth is set here
- certSelectionCallback.setClientCert(client_cert);
-
- Socket js = new Socket(InetAddress.getByName(hostname), port);
- SSLSocket socket = new SSLSocket(js, hostname, approvalCallback,
- certSelectionCallback );
- disableSSL2(socket);
- setCipherPref(socket);
- socket.forceHandshake();
- System.out.println("Connected.");
- socket.setUseClientMode(true);
-
- System.out.println("Posting Query = " +
- "https://" + hostname +
- ":" + portnumber +
- "/" + url +
- "?" + query);
-
- OutputStream rawos = socket.getOutputStream();
- BufferedOutputStream os = new BufferedOutputStream(rawos);
- PrintStream ps = new PrintStream(os);
-
- ps.println("POST " + url + " HTTP/1.0");
- ps.println("Connection: Keep-Alive");
- ps.println("Content-type: application/x-www-form-urlencoded");
- ps.println("Content-length: " +query.length());
- ps.println("");
- ps.print(query);
- ps.flush();
- os.flush();
-
- try
- {
- hr = readResponse(socket.getInputStream());
- hr.parseContent();
-
- }
- catch (Exception e)
- {
- System.out.println("Exception");
- e.printStackTrace();
- st = false;
- }
-
- socket.close();
- os.close();
- rawos.close();
- ps.close();
-
- os=null;
- rawos=null;
- ps=null;
-
- }
-
- catch(Exception e)
- {
- System.err.println("Exception: Unable to Send Request:" +e);
- e.printStackTrace();
- st = false;
- }
-
- if(!st)
- return null;
- else
- return hr;
- }
-
- // performs ssl connect to given host/port
- // posts the given query data
- // returns HTTPResponse
- public HTTPResponse sslConnect(String hostname, String portnumber,
- String url, String query)
- {
-
- boolean st = true;
- HTTPResponse hr = null;
-
- try
- {
-
- System.out.println("#############################################");
- System.out.println("Attempting to connect to: " + hostname + ":" +
- portnumber);
-
- Integer x = new Integer(portnumber);
- int port = x.intValue();
-
-
- SSLCertificateApprovalCallback approvalCallback =
- new TestCertApprovalCallback();
- SSLClientCertificateSelectionCallback certSelectionCallback =
- new TestClientCertificateSelectionCallback();
-
- Socket js = new Socket(InetAddress.getByName(hostname), port);
- SSLSocket socket = new SSLSocket(js, hostname, approvalCallback,
- certSelectionCallback );
- setCipherPref(socket);
- disableSSL2(socket);
- socket.forceHandshake();
- System.out.println("Connected.");
- socket.setUseClientMode(true);
-
- System.out.println("Posting Query = " +
- "https://" + hostname +
- ":" + portnumber +
- "/" + url +
- "?" + query);
-
- OutputStream rawos = socket.getOutputStream();
- BufferedOutputStream os = new BufferedOutputStream(rawos);
- PrintStream ps = new PrintStream(os);
-
-
- ps.println("POST " + url + " HTTP/1.0");
-
- // check to see if we have a cookie to send
- if(j_session_id != null )
- ps.println("Cookie: " + j_session_id);
-
- ps.println("Content-type: application/x-www-form-urlencoded");
- ps.println("Content-length: " +query.length());
- ps.println("Connection: Keep-Alive");
-
- // special header posting if available
- if(basic_auth_header_value != null)
- {
- System.out.println("basic_auth = " + basic_auth_header_value );
- ps.println("Authorization: Basic " + basic_auth_header_value );
- }
-
- ps.println("");
- ps.println(query);
- ps.println("\r");
- ps.flush();
- os.flush();
-
- try
- {
- hr = readResponse(socket.getInputStream());
- hr.parseContent();
-
- }
- catch (Exception e)
- {
- System.out.println("Exception");
- e.printStackTrace();
- st = false;
- }
-
- socket.close();
- os.close();
- rawos.close();
- ps.close();
-
- os=null;
- rawos=null;
- ps=null;
-
- }
-
- catch(Exception e)
- {
- System.err.println("Exception: Unable to Send Request:" +e);
- e.printStackTrace();
- st = false;
- }
-
- if(!st)
- return null;
- else
- return hr;
- }
-
- // performs non ssl connect to given host/port
- // posts the given query data
- // returns HTTPResponse
- public HTTPResponse nonsslConnect(String hostname, String portnumber,
- String url, String query)
- {
-
- boolean st = true;
- HTTPResponse hr = null;
-
- try
- {
-
- System.out.println("#############################################");
- System.out.println("Attempting to connect to: " + hostname + ":" +
- portnumber);
-
- Integer x = new Integer(portnumber);
- int port = x.intValue();
-
- Socket socket = new Socket(hostname, port);
-
- System.out.println("Posting Query = " +
- "http://" + hostname +
- ":" + portnumber +
- "/" + url +
- "?" + query);
-
- OutputStream rawos = socket.getOutputStream();
- BufferedOutputStream os = new BufferedOutputStream(rawos);
- PrintStream ps = new PrintStream(os);
-
- System.out.println("Connected.");
-
- ps.println("POST " + url + " HTTP/1.0");
-
- // check to see if we have a cookie to send
- if(j_session_id != null )
- ps.println("Cookie: " + j_session_id);
-
- ps.println("Content-type: application/x-www-form-urlencoded");
- ps.println("Content-length: " +query.length());
- ps.println("Connection: Keep-Alive");
-
- // special header posting if available
- if(basic_auth_header_value != null)
- {
- System.out.println("basic_auth = " + basic_auth_header_value );
- ps.println("Authorization: Basic " + basic_auth_header_value );
- }
-
- ps.println("");
- ps.println(query);
- ps.println("\r");
- ps.flush();
- os.flush();
-
- try
- {
- hr = readResponse(socket.getInputStream());
- hr.parseContent();
-
- }
- catch (Exception e)
- {
- System.out.println("Exception");
- e.printStackTrace();
- st = false;
- }
-
- socket.close();
- os.close();
- rawos.close();
- ps.close();
-
- os=null;
- rawos=null;
- ps=null;
-
- }
-
- catch(Exception e)
- {
- System.err.println("Exception: Unable to Send Request:" +e);
- e.printStackTrace();
- st = false;
- }
-
- if(!st)
- return null;
- else
- return hr;
- }
-
- public HTTPResponse readResponse(InputStream inputStream)
- throws Exception
- {
- // read response from http input stream and return HTTPResponse
- byte[] buffer = new byte[BUFFER_SIZE];
- HTTPResponse response = null;
- int statusCode = 0;
-
- // Read an initial chunk of the response from the server.
- int bytesRead = inputStream.read(buffer);
- if (bytesRead < 0)
- {
- throw new IOException("Unexpected end of input stream from server");
+ } catch (Exception e) {
+ System.out.println("ERROR: Exception = " + e.getMessage());
+ }
+ return true;
+ }
+
+ public X509Certificate getServerCert() {
+ return server_cert;
+ }
+
+ public void set_parse_xml(boolean b) {
+ parse_xml = b;
+ }
+
+ public boolean approve(X509Certificate cert,
+ SSLCertificateApprovalCallback.ValidityStatus status) {
+
+ // when this method is called by SSLSocket we get the server cert
+ // we can capture this for future use.
+ server_cert = cert;
+ return true;
}
- // Hopefully, this initial chunk will contain the entire header, so look for
- // it. Technically, HTTP is supposed to use CRLF as the end-of-line
- // character, so look for that first, but also check for LF by itself just
- // in case.
- int headerEndPos = -1;
- int dataStartPos = -1;
- for (int i=0; i < (bytesRead-3); i++)
- {
- if ((buffer[i] == '\r') && (buffer[i+1] == '\n') &&
- (buffer[i+2] == '\r') && (buffer[i+3] == '\n'))
- {
- headerEndPos = i;
- dataStartPos = i+4;
- break;
- }
+ public boolean testsslConnect(String hostname, String portnumber) {
+ boolean st = true;
+
+ try {
+
+ System.out.println("#############################################");
+ System.out.println("Attempting to connect to: " + hostname + ":" +
+ portnumber);
+
+ Integer x = new Integer(portnumber);
+ int port = x.intValue();
+
+ SSLClientCertificateSelectionCallback certSelectionCallback =
+ new TestClientCertificateSelectionCallback();
+
+ Socket js = new Socket(InetAddress.getByName(hostname), port);
+ SSLSocket socket = new SSLSocket(js, hostname, this,
+ certSelectionCallback);
+ setCipherPref(socket);
+ disableSSL2(socket);
+ socket.forceHandshake();
+ System.out.println("Connected.");
+ socket.setUseClientMode(true);
+
+ // test connection to obtain server cert. close it.
+ socket.close();
+
+ }
+
+ catch (Exception e) {
+ System.err.println("Exception: Unable to Send Request:" + e);
+ e.printStackTrace();
+ st = false;
+ }
+
+ if (!st)
+ return false;
+ else
+ return true;
}
- if (headerEndPos < 0)
- {
- for (int i=0; i < (bytesRead-1); i++)
- {
- if ((buffer[i] == '\n') && (buffer[i+1] == '\n'))
- {
- headerEndPos = i;
- dataStartPos = i+2;
- break;
+ // performs ssl connect to given host/port requiring client auth
+ // posts the given query data
+ // returns HTTPResponse
+ public HTTPResponse sslConnectClientAuth(String hostname, String portnumber,
+ String client_cert, String url, String query) {
+
+ boolean st = true;
+ HTTPResponse hr = null;
+
+ try {
+
+ System.out.println("#############################################");
+ System.out.println("Attempting to connect to: " + hostname + ":" +
+ portnumber);
+
+ Integer x = new Integer(portnumber);
+ int port = x.intValue();
+
+ SSLCertificateApprovalCallback approvalCallback =
+ new TestCertApprovalCallback();
+ CertSelection certSelectionCallback =
+ new CertSelection();
+
+ // Client Cert for Auth is set here
+ certSelectionCallback.setClientCert(client_cert);
+
+ Socket js = new Socket(InetAddress.getByName(hostname), port);
+ SSLSocket socket = new SSLSocket(js, hostname, approvalCallback,
+ certSelectionCallback);
+ disableSSL2(socket);
+ setCipherPref(socket);
+ socket.forceHandshake();
+ System.out.println("Connected.");
+ socket.setUseClientMode(true);
+
+ System.out.println("Posting Query = " +
+ "https://" + hostname +
+ ":" + portnumber +
+ "/" + url +
+ "?" + query);
+
+ OutputStream rawos = socket.getOutputStream();
+ BufferedOutputStream os = new BufferedOutputStream(rawos);
+ PrintStream ps = new PrintStream(os);
+
+ ps.println("POST " + url + " HTTP/1.0");
+ ps.println("Connection: Keep-Alive");
+ ps.println("Content-type: application/x-www-form-urlencoded");
+ ps.println("Content-length: " + query.length());
+ ps.println("");
+ ps.print(query);
+ ps.flush();
+ os.flush();
+
+ try {
+ hr = readResponse(socket.getInputStream());
+ hr.parseContent();
+
+ } catch (Exception e) {
+ System.out.println("Exception");
+ e.printStackTrace();
+ st = false;
+ }
+
+ socket.close();
+ os.close();
+ rawos.close();
+ ps.close();
+
+ os = null;
+ rawos = null;
+ ps = null;
+
}
- }
+
+ catch (Exception e) {
+ System.err.println("Exception: Unable to Send Request:" + e);
+ e.printStackTrace();
+ st = false;
+ }
+
+ if (!st)
+ return null;
+ else
+ return hr;
}
+ // performs ssl connect to given host/port
+ // posts the given query data
+ // returns HTTPResponse
+ public HTTPResponse sslConnect(String hostname, String portnumber,
+ String url, String query) {
+
+ boolean st = true;
+ HTTPResponse hr = null;
+
+ try {
+
+ System.out.println("#############################################");
+ System.out.println("Attempting to connect to: " + hostname + ":" +
+ portnumber);
+
+ Integer x = new Integer(portnumber);
+ int port = x.intValue();
+
+ SSLCertificateApprovalCallback approvalCallback =
+ new TestCertApprovalCallback();
+ SSLClientCertificateSelectionCallback certSelectionCallback =
+ new TestClientCertificateSelectionCallback();
+
+ Socket js = new Socket(InetAddress.getByName(hostname), port);
+ SSLSocket socket = new SSLSocket(js, hostname, approvalCallback,
+ certSelectionCallback);
+ setCipherPref(socket);
+ disableSSL2(socket);
+ socket.forceHandshake();
+ System.out.println("Connected.");
+ socket.setUseClientMode(true);
+
+ System.out.println("Posting Query = " +
+ "https://" + hostname +
+ ":" + portnumber +
+ "/" + url +
+ "?" + query);
+
+ OutputStream rawos = socket.getOutputStream();
+ BufferedOutputStream os = new BufferedOutputStream(rawos);
+ PrintStream ps = new PrintStream(os);
+
+ ps.println("POST " + url + " HTTP/1.0");
+
+ // check to see if we have a cookie to send
+ if (j_session_id != null)
+ ps.println("Cookie: " + j_session_id);
+
+ ps.println("Content-type: application/x-www-form-urlencoded");
+ ps.println("Content-length: " + query.length());
+ ps.println("Connection: Keep-Alive");
+
+ // special header posting if available
+ if (basic_auth_header_value != null) {
+ System.out.println("basic_auth = " + basic_auth_header_value);
+ ps.println("Authorization: Basic " + basic_auth_header_value);
+ }
+
+ ps.println("");
+ ps.println(query);
+ ps.println("\r");
+ ps.flush();
+ os.flush();
+
+ try {
+ hr = readResponse(socket.getInputStream());
+ hr.parseContent();
+
+ } catch (Exception e) {
+ System.out.println("Exception");
+ e.printStackTrace();
+ st = false;
+ }
+
+ socket.close();
+ os.close();
+ rawos.close();
+ ps.close();
+
+ os = null;
+ rawos = null;
+ ps = null;
- // In the event that we didn't get the entire header in the first pass, keep
- // reading until we do have enough.
- if (headerEndPos < 0)
- {
- byte[] buffer2 = new byte[BUFFER_SIZE];
- while (headerEndPos < 0)
- {
- int startPos = bytesRead;
- int moreBytesRead = inputStream.read(buffer2);
- if (moreBytesRead < 0)
- {
- throw new IOException("Unexpected end of input stream from server " +
- "when reading more data from response");
}
- byte[] newBuffer = new byte[bytesRead + moreBytesRead];
- System.arraycopy(buffer, 0, newBuffer, 0, bytesRead);
- System.arraycopy(buffer2, 0, newBuffer, bytesRead, moreBytesRead);
- buffer = newBuffer;
- bytesRead += moreBytesRead;
-
- for (int i=startPos; i < (bytesRead-3); i++)
- {
- if ((buffer[i] == '\r') && (buffer[i+1] == '\n') &&
- (buffer[i+2] == '\r') && (buffer[i+3] == '\n'))
- {
- headerEndPos = i;
- dataStartPos = i+4;
- break;
- }
+ catch (Exception e) {
+ System.err.println("Exception: Unable to Send Request:" + e);
+ e.printStackTrace();
+ st = false;
}
- if (headerEndPos < 0)
- {
- for (int i=startPos; i < (bytesRead-1); i++)
- {
- if ((buffer[i] == '\n') && (buffer[i+1] == '\n'))
- {
- headerEndPos = i;
- dataStartPos = i+2;
- break;
+ if (!st)
+ return null;
+ else
+ return hr;
+ }
+
+ // performs non ssl connect to given host/port
+ // posts the given query data
+ // returns HTTPResponse
+ public HTTPResponse nonsslConnect(String hostname, String portnumber,
+ String url, String query) {
+
+ boolean st = true;
+ HTTPResponse hr = null;
+
+ try {
+
+ System.out.println("#############################################");
+ System.out.println("Attempting to connect to: " + hostname + ":" +
+ portnumber);
+
+ Integer x = new Integer(portnumber);
+ int port = x.intValue();
+
+ Socket socket = new Socket(hostname, port);
+
+ System.out.println("Posting Query = " +
+ "http://" + hostname +
+ ":" + portnumber +
+ "/" + url +
+ "?" + query);
+
+ OutputStream rawos = socket.getOutputStream();
+ BufferedOutputStream os = new BufferedOutputStream(rawos);
+ PrintStream ps = new PrintStream(os);
+
+ System.out.println("Connected.");
+
+ ps.println("POST " + url + " HTTP/1.0");
+
+ // check to see if we have a cookie to send
+ if (j_session_id != null)
+ ps.println("Cookie: " + j_session_id);
+
+ ps.println("Content-type: application/x-www-form-urlencoded");
+ ps.println("Content-length: " + query.length());
+ ps.println("Connection: Keep-Alive");
+
+ // special header posting if available
+ if (basic_auth_header_value != null) {
+ System.out.println("basic_auth = " + basic_auth_header_value);
+ ps.println("Authorization: Basic " + basic_auth_header_value);
+ }
+
+ ps.println("");
+ ps.println(query);
+ ps.println("\r");
+ ps.flush();
+ os.flush();
+
+ try {
+ hr = readResponse(socket.getInputStream());
+ hr.parseContent();
+
+ } catch (Exception e) {
+ System.out.println("Exception");
+ e.printStackTrace();
+ st = false;
}
- }
+
+ socket.close();
+ os.close();
+ rawos.close();
+ ps.close();
+
+ os = null;
+ rawos = null;
+ ps = null;
+
+ }
+
+ catch (Exception e) {
+ System.err.println("Exception: Unable to Send Request:" + e);
+ e.printStackTrace();
+ st = false;
}
- }
+
+ if (!st)
+ return null;
+ else
+ return hr;
}
+ public HTTPResponse readResponse(InputStream inputStream)
+ throws Exception {
+ // read response from http input stream and return HTTPResponse
+ byte[] buffer = new byte[BUFFER_SIZE];
+ HTTPResponse response = null;
+ int statusCode = 0;
+
+ // Read an initial chunk of the response from the server.
+ int bytesRead = inputStream.read(buffer);
+ if (bytesRead < 0) {
+ throw new IOException("Unexpected end of input stream from server");
+ }
+
+ // Hopefully, this initial chunk will contain the entire header, so look
+ // for
+ // it. Technically, HTTP is supposed to use CRLF as the end-of-line
+ // character, so look for that first, but also check for LF by itself
+ // just
+ // in case.
+ int headerEndPos = -1;
+ int dataStartPos = -1;
+ for (int i = 0; i < (bytesRead - 3); i++) {
+ if ((buffer[i] == '\r') && (buffer[i + 1] == '\n') &&
+ (buffer[i + 2] == '\r') && (buffer[i + 3] == '\n')) {
+ headerEndPos = i;
+ dataStartPos = i + 4;
+ break;
+ }
+ }
+
+ if (headerEndPos < 0) {
+ for (int i = 0; i < (bytesRead - 1); i++) {
+ if ((buffer[i] == '\n') && (buffer[i + 1] == '\n')) {
+ headerEndPos = i;
+ dataStartPos = i + 2;
+ break;
+ }
+ }
+ }
+
+ // In the event that we didn't get the entire header in the first pass,
+ // keep
+ // reading until we do have enough.
+ if (headerEndPos < 0) {
+ byte[] buffer2 = new byte[BUFFER_SIZE];
+ while (headerEndPos < 0) {
+ int startPos = bytesRead;
+ int moreBytesRead = inputStream.read(buffer2);
+ if (moreBytesRead < 0) {
+ throw new IOException("Unexpected end of input stream from server " +
+ "when reading more data from response");
+ }
+
+ byte[] newBuffer = new byte[bytesRead + moreBytesRead];
+ System.arraycopy(buffer, 0, newBuffer, 0, bytesRead);
+ System.arraycopy(buffer2, 0, newBuffer, bytesRead, moreBytesRead);
+ buffer = newBuffer;
+ bytesRead += moreBytesRead;
+
+ for (int i = startPos; i < (bytesRead - 3); i++) {
+ if ((buffer[i] == '\r') && (buffer[i + 1] == '\n') &&
+ (buffer[i + 2] == '\r') && (buffer[i + 3] == '\n')) {
+ headerEndPos = i;
+ dataStartPos = i + 4;
+ break;
+ }
+ }
+
+ if (headerEndPos < 0) {
+ for (int i = startPos; i < (bytesRead - 1); i++) {
+ if ((buffer[i] == '\n') && (buffer[i + 1] == '\n')) {
+ headerEndPos = i;
+ dataStartPos = i + 2;
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ // At this point, we should have the entire header, so read and analyze
+ // it.
+ String headerStr = new String(buffer, 0, headerEndPos);
+ StringTokenizer tokenizer = new StringTokenizer(headerStr, "\r\n");
+ if (tokenizer.hasMoreTokens()) {
+ String statusLine = tokenizer.nextToken();
+ if (debugMode) {
+ System.out.println("RESPONSE STATUS: " + statusLine);
+ }
- // At this point, we should have the entire header, so read and analyze it.
- String headerStr = new String(buffer, 0, headerEndPos);
- StringTokenizer tokenizer = new StringTokenizer(headerStr, "\r\n");
- if (tokenizer.hasMoreTokens())
- {
- String statusLine = tokenizer.nextToken();
- if (debugMode)
- {
- System.out.println("RESPONSE STATUS: " + statusLine);
- }
-
- int spacePos = statusLine.indexOf(' ');
- if (spacePos < 0)
- {
- System.out.println("ERROR: Unable to parse response header -- could " +
+ int spacePos = statusLine.indexOf(' ');
+ if (spacePos < 0) {
+ System.out.println("ERROR: Unable to parse response header -- could " +
"not find protocol/version delimiter");
- return null;
-
- }
-
- String protocolVersion = statusLine.substring(0, spacePos);
- int spacePos2 = statusLine.indexOf(' ', spacePos+1);
- if (spacePos2 < 0)
- {
- System.out.println("ERROR: Unable to parse response header -- could " +
+ return null;
+
+ }
+
+ String protocolVersion = statusLine.substring(0, spacePos);
+ int spacePos2 = statusLine.indexOf(' ', spacePos + 1);
+ if (spacePos2 < 0) {
+ System.out.println("ERROR: Unable to parse response header -- could " +
"not find response code delimiter");
- return null;
- }
+ return null;
+ }
- try
- {
- statusCode = Integer.parseInt(statusLine.substring(spacePos+1,
+ try {
+ statusCode = Integer.parseInt(statusLine.substring(spacePos + 1,
spacePos2));
- }
- catch (NumberFormatException nfe)
- {
- System.out.println("Unable to parse response header -- could " +
+ } catch (NumberFormatException nfe) {
+ System.out.println("Unable to parse response header -- could " +
"not interpret status code as an integer");
- return null;
- }
+ return null;
+ }
- String responseMessage = statusLine.substring(spacePos2+1);
- response = new HTTPResponse(statusCode, protocolVersion,
+ String responseMessage = statusLine.substring(spacePos2 + 1);
+ response = new HTTPResponse(statusCode, protocolVersion,
responseMessage);
- while (tokenizer.hasMoreTokens())
- {
- String headerLine = tokenizer.nextToken();
- if (debugMode)
- {
- System.out.println("RESPONSE HEADER: " + headerLine);
- }
-
- int colonPos = headerLine.indexOf(':');
- if (colonPos < 0)
- {
- if (headerLine.toLowerCase().startsWith("http/"))
- {
- // This is a direct violation of RFC 2616, but certain HTTP servers
- // seem to immediately follow a 100 continue with a 200 ok without
- // the required CRLF in between.
- System.out.println("ERROR: Found illegal status line '" + headerLine +
+ while (tokenizer.hasMoreTokens()) {
+ String headerLine = tokenizer.nextToken();
+ if (debugMode) {
+ System.out.println("RESPONSE HEADER: " + headerLine);
+ }
+
+ int colonPos = headerLine.indexOf(':');
+ if (colonPos < 0) {
+ if (headerLine.toLowerCase().startsWith("http/")) {
+ // This is a direct violation of RFC 2616, but certain
+ // HTTP servers
+ // seem to immediately follow a 100 continue with a 200
+ // ok without
+ // the required CRLF in between.
+ System.out.println("ERROR: Found illegal status line '" + headerLine +
"'in the middle of a response -- attempting " +
"to deal with it as the start of a new " +
"response.");
- statusLine = headerLine;
- spacePos = statusLine.indexOf(' ');
- if (spacePos < 0)
- {
- System.out.println("ERROR: Unable to parse response header -- " +
+ statusLine = headerLine;
+ spacePos = statusLine.indexOf(' ');
+ if (spacePos < 0) {
+ System.out.println("ERROR: Unable to parse response header -- " +
"could not find protocol/version " +
"delimiter");
- return null;
- }
+ return null;
+ }
- protocolVersion = statusLine.substring(0, spacePos);
- spacePos2 = statusLine.indexOf(' ', spacePos+1);
- if (spacePos2 < 0)
- {
- System.out.println("ERROR: Unable to parse response header -- " +
+ protocolVersion = statusLine.substring(0, spacePos);
+ spacePos2 = statusLine.indexOf(' ', spacePos + 1);
+ if (spacePos2 < 0) {
+ System.out.println("ERROR: Unable to parse response header -- " +
"could not find response code delimiter");
- return null;
- }
+ return null;
+ }
- try
- {
- statusCode = Integer.parseInt(statusLine.substring(spacePos+1,
+ try {
+ statusCode = Integer.parseInt(statusLine.substring(spacePos + 1,
spacePos2));
- }
- catch (NumberFormatException nfe)
- {
- System.out.println("ERROR: Unable to parse response header -- " +
+ } catch (NumberFormatException nfe) {
+ System.out.println("ERROR: Unable to parse response header -- " +
"could not interpret status code as an " +
"integer");
- return null;
- }
+ return null;
+ }
- responseMessage = statusLine.substring(spacePos2+1);
- response = new HTTPResponse(statusCode, protocolVersion,
+ responseMessage = statusLine.substring(spacePos2 + 1);
+ response = new HTTPResponse(statusCode, protocolVersion,
responseMessage);
- continue;
- }
- else
- {
- System.out.println("ERROR: Unable to parse response header -- no " +
+ continue;
+ } else {
+ System.out.println("ERROR: Unable to parse response header -- no " +
"colon found on header line \"" +
headerLine + "\"");
- }
- }
+ }
+ }
- String headerName = headerLine.substring(0, colonPos);
- String headerValue = headerLine.substring(colonPos+1).trim();
- response.addHeader(headerName, headerValue);
- }
- }
- else
- {
- // This should never happen -- an empty response
- System.out.println("Unable to parse response header -- empty " +
+ String headerName = headerLine.substring(0, colonPos);
+ String headerValue = headerLine.substring(colonPos + 1).trim();
+ response.addHeader(headerName, headerValue);
+ }
+ } else {
+ // This should never happen -- an empty response
+ System.out.println("Unable to parse response header -- empty " +
"header");
- }
-
-
- // If the status code was 100 (continue), then it was an intermediate header
- // and we need to keep reading until we get the real response header.
- while (response.getStatusCode() == 100)
- {
- if (dataStartPos < bytesRead)
- {
- byte[] newBuffer = new byte[bytesRead - dataStartPos];
- System.arraycopy(buffer, dataStartPos, newBuffer, 0, newBuffer.length);
- buffer = newBuffer;
- bytesRead = buffer.length;
-
- headerEndPos = -1;
- for (int i=0; i < (bytesRead-3); i++)
- {
- if ((buffer[i] == '\r') && (buffer[i+1] == '\n') &&
- (buffer[i+2] == '\r') && (buffer[i+3] == '\n'))
- {
- headerEndPos = i;
- dataStartPos = i+4;
- break;
- }
}
- if (headerEndPos < 0)
- {
- for (int i=0; i < (bytesRead-1); i++)
- {
- if ((buffer[i] == '\n') && (buffer[i+1] == '\n'))
- {
- headerEndPos = i;
- dataStartPos = i+2;
- break;
+ // If the status code was 100 (continue), then it was an intermediate
+ // header
+ // and we need to keep reading until we get the real response header.
+ while (response.getStatusCode() == 100) {
+ if (dataStartPos < bytesRead) {
+ byte[] newBuffer = new byte[bytesRead - dataStartPos];
+ System.arraycopy(buffer, dataStartPos, newBuffer, 0, newBuffer.length);
+ buffer = newBuffer;
+ bytesRead = buffer.length;
+
+ headerEndPos = -1;
+ for (int i = 0; i < (bytesRead - 3); i++) {
+ if ((buffer[i] == '\r') && (buffer[i + 1] == '\n') &&
+ (buffer[i + 2] == '\r') && (buffer[i + 3] == '\n')) {
+ headerEndPos = i;
+ dataStartPos = i + 4;
+ break;
+ }
+ }
+
+ if (headerEndPos < 0) {
+ for (int i = 0; i < (bytesRead - 1); i++) {
+ if ((buffer[i] == '\n') && (buffer[i + 1] == '\n')) {
+ headerEndPos = i;
+ dataStartPos = i + 2;
+ break;
+ }
+ }
+ }
+ } else {
+ buffer = new byte[0];
+ bytesRead = 0;
+ headerEndPos = -1;
}
- }
- }
- }
- else
- {
- buffer = new byte[0];
- bytesRead = 0;
- headerEndPos = -1;
- }
-
-
- byte[] buffer2 = new byte[BUFFER_SIZE];
- while (headerEndPos < 0)
- {
- int startPos = bytesRead;
- int moreBytesRead = inputStream.read(buffer2);
-
- if (moreBytesRead < 0)
- {
- throw new IOException("Unexpected end of input stream from server " +
- "when reading more data from response");
- }
- byte[] newBuffer = new byte[bytesRead + moreBytesRead];
- System.arraycopy(buffer, 0, newBuffer, 0, bytesRead);
- System.arraycopy(buffer2, 0, newBuffer, bytesRead, moreBytesRead);
- buffer = newBuffer;
- bytesRead += moreBytesRead;
-
- for (int i=startPos; i < (bytesRead-3); i++)
- {
- if ((buffer[i] == '\r') && (buffer[i+1] == '\n') &&
- (buffer[i+2] == '\r') && (buffer[i+3] == '\n'))
- {
- headerEndPos = i;
- dataStartPos = i+4;
- break;
- }
- }
+ byte[] buffer2 = new byte[BUFFER_SIZE];
+ while (headerEndPos < 0) {
+ int startPos = bytesRead;
+ int moreBytesRead = inputStream.read(buffer2);
- if (headerEndPos < 0)
- {
- for (int i=startPos; i < (bytesRead-1); i++)
- {
- if ((buffer[i] == '\n') && (buffer[i+1] == '\n'))
- {
- headerEndPos = i;
- dataStartPos = i+2;
- break;
+ if (moreBytesRead < 0) {
+ throw new IOException("Unexpected end of input stream from server " +
+ "when reading more data from response");
+ }
+
+ byte[] newBuffer = new byte[bytesRead + moreBytesRead];
+ System.arraycopy(buffer, 0, newBuffer, 0, bytesRead);
+ System.arraycopy(buffer2, 0, newBuffer, bytesRead, moreBytesRead);
+ buffer = newBuffer;
+ bytesRead += moreBytesRead;
+
+ for (int i = startPos; i < (bytesRead - 3); i++) {
+ if ((buffer[i] == '\r') && (buffer[i + 1] == '\n') &&
+ (buffer[i + 2] == '\r') && (buffer[i + 3] == '\n')) {
+ headerEndPos = i;
+ dataStartPos = i + 4;
+ break;
+ }
+ }
+
+ if (headerEndPos < 0) {
+ for (int i = startPos; i < (bytesRead - 1); i++) {
+ if ((buffer[i] == '\n') && (buffer[i + 1] == '\n')) {
+ headerEndPos = i;
+ dataStartPos = i + 2;
+ break;
+ }
+ }
+ }
}
- }
- }
- }
-
-
- // We should now have the next header, so examine it.
- headerStr = new String(buffer, 0, headerEndPos);
- tokenizer = new StringTokenizer(headerStr, "\r\n");
- if (tokenizer.hasMoreTokens())
- {
- String statusLine = tokenizer.nextToken();
- if (debugMode)
- {
- System.out.println("RESPONSE STATUS: " + statusLine);
- }
- int spacePos = statusLine.indexOf(' ');
- if (spacePos < 0)
- {
- System.out.println("Unable to parse response header -- could " +
+ // We should now have the next header, so examine it.
+ headerStr = new String(buffer, 0, headerEndPos);
+ tokenizer = new StringTokenizer(headerStr, "\r\n");
+ if (tokenizer.hasMoreTokens()) {
+ String statusLine = tokenizer.nextToken();
+ if (debugMode) {
+ System.out.println("RESPONSE STATUS: " + statusLine);
+ }
+
+ int spacePos = statusLine.indexOf(' ');
+ if (spacePos < 0) {
+ System.out.println("Unable to parse response header -- could " +
"not find protocol/version delimiter");
- }
+ }
- String protocolVersion = statusLine.substring(0, spacePos);
- int spacePos2 = statusLine.indexOf(' ', spacePos+1);
- if (spacePos2 < 0)
- {
- System.out.println("Unable to parse response header -- could " +
+ String protocolVersion = statusLine.substring(0, spacePos);
+ int spacePos2 = statusLine.indexOf(' ', spacePos + 1);
+ if (spacePos2 < 0) {
+ System.out.println("Unable to parse response header -- could " +
"not find response code delimiter");
- }
+ }
- try
- {
- statusCode = Integer.parseInt(statusLine.substring(spacePos+1,
+ try {
+ statusCode = Integer.parseInt(statusLine.substring(spacePos + 1,
spacePos2));
- }
- catch (NumberFormatException nfe)
- {
- System.out.println("Unable to parse response header -- could " +
+ } catch (NumberFormatException nfe) {
+ System.out.println("Unable to parse response header -- could " +
"not interpret status code as an integer");
- }
+ }
- String responseMessage = statusLine.substring(spacePos2+1);
- response = new HTTPResponse(statusCode, protocolVersion,
+ String responseMessage = statusLine.substring(spacePos2 + 1);
+ response = new HTTPResponse(statusCode, protocolVersion,
responseMessage);
- while (tokenizer.hasMoreTokens())
- {
- String headerLine = tokenizer.nextToken();
- if (debugMode)
- {
- System.out.println("RESPONSE HEADER: " + headerLine);
- }
-
- int colonPos = headerLine.indexOf(':');
- if (colonPos < 0)
- {
- System.out.println("Unable to parse response header -- no " +
+ while (tokenizer.hasMoreTokens()) {
+ String headerLine = tokenizer.nextToken();
+ if (debugMode) {
+ System.out.println("RESPONSE HEADER: " + headerLine);
+ }
+
+ int colonPos = headerLine.indexOf(':');
+ if (colonPos < 0) {
+ System.out.println("Unable to parse response header -- no " +
"colon found on header line \"" +
headerLine + "\"");
- }
-
- String headerName = headerLine.substring(0, colonPos);
- String headerValue = headerLine.substring(colonPos+1).trim();
- response.addHeader(headerName, headerValue);
- }
- }
- else
- {
- // This should never happen -- an empty response
- System.out.println("Unable to parse response header -- empty " +
+ }
+
+ String headerName = headerLine.substring(0, colonPos);
+ String headerValue = headerLine.substring(colonPos + 1).trim();
+ response.addHeader(headerName, headerValue);
+ }
+ } else {
+ // This should never happen -- an empty response
+ System.out.println("Unable to parse response header -- empty " +
"header");
- }
- }
-
-
- // Now that we have parsed the header, use it to determine how much data
- // there is. If we're lucky, the server will have told us using the
- // "Content-Length" header.
- int contentLength = response.getContentLength();
+ }
+ }
+ // Now that we have parsed the header, use it to determine how much data
+ // there is. If we're lucky, the server will have told us using the
+ // "Content-Length" header.
+ int contentLength = response.getContentLength();
- if (contentLength >= 0)
- {
- readContentDataUsingLength(response, inputStream, contentLength, buffer,
+ if (contentLength >= 0) {
+ readContentDataUsingLength(response, inputStream, contentLength, buffer,
dataStartPos, bytesRead);
- }
- else
- {
- // It's not chunked encoding, so our last hope is that the connection
- // will be closed when all the data has been sent.
- String connectionStr = response.getHeader("connection");
- if ((connectionStr != null) &&
- (! connectionStr.equalsIgnoreCase("close")))
- {
- System.out.println("ERROR:Unable to determine how to find when the " +
+ } else {
+ // It's not chunked encoding, so our last hope is that the
+ // connection
+ // will be closed when all the data has been sent.
+ String connectionStr = response.getHeader("connection");
+ if ((connectionStr != null) &&
+ (!connectionStr.equalsIgnoreCase("close"))) {
+ System.out.println("ERROR:Unable to determine how to find when the " +
"end of the data has been reached (no " +
"content length, not chunked encoding, " +
"connection string is \"" + connectionStr +
"\" rather than \"close\")");
- }
- else
- {
- readContentDataUsingConnectionClose(response, inputStream, buffer,
+ } else {
+ readContentDataUsingConnectionClose(response, inputStream, buffer,
dataStartPos, bytesRead);
+ }
}
+ // Finally, return the response to the caller.
+ return response;
}
- // Finally, return the response to the caller.
- return response;
- }
-
- /**
- * Reads the actual data of the response based on the content length provided
- * by the server in the response header.
- *
- * @param response The response with which the data is associated.
- * @param inputStream The input stream from which to read the response.
- * @param contentLength The number of bytes that the server said are in the
- * response.
- * @param dataRead The data that we have already read. This includes
- * the header data, but may also include some or all of
- * the content data as well.
- * @param dataStartPos The position in the provided array at which the
- * content data starts.
- * @param dataBytesRead The total number of valid bytes in the provided
- * array that should be considered part of the
- * response (the number of header bytes is included in
- * this count).
- *
- * @throws IOException If a problem occurs while reading data from the
- * server.
- */
- private void readContentDataUsingLength(HTTPResponse response,
+
+ /**
+ * Reads the actual data of the response based on the content length
+ * provided by the server in the response header.
+ *
+ * @param response The response with which the data is associated.
+ * @param inputStream The input stream from which to read the response.
+ * @param contentLength The number of bytes that the server said are in the
+ * response.
+ * @param dataRead The data that we have already read. This includes the
+ * header data, but may also include some or all of the content
+ * data as well.
+ * @param dataStartPos The position in the provided array at which the
+ * content data starts.
+ * @param dataBytesRead The total number of valid bytes in the provided
+ * array that should be considered part of the response (the
+ * number of header bytes is included in this count).
+ *
+ * @throws IOException If a problem occurs while reading data from the
+ * server.
+ */
+ private void readContentDataUsingLength(HTTPResponse response,
InputStream inputStream,
int contentLength, byte[] dataRead,
int dataStartPos, int dataBytesRead)
- throws IOException
- {
- if (contentLength <= 0)
- {
- response.setResponseData(new byte[0]);
- return;
- }
-
+ throws IOException {
+ if (contentLength <= 0) {
+ response.setResponseData(new byte[0]);
+ return;
+ }
- byte[] contentBytes = new byte[contentLength];
- int startPos = 0;
- if (dataBytesRead > dataStartPos)
- {
- // We've already got some data to include in the header, so copy that into
- // the content array. Make sure the server didn't do something stupid
- // like return more data than it told us was in the response.
- int bytesToCopy = Math.min(contentBytes.length,
+ byte[] contentBytes = new byte[contentLength];
+ int startPos = 0;
+ if (dataBytesRead > dataStartPos) {
+ // We've already got some data to include in the header, so copy
+ // that into
+ // the content array. Make sure the server didn't do something
+ // stupid
+ // like return more data than it told us was in the response.
+ int bytesToCopy = Math.min(contentBytes.length,
(dataBytesRead - dataStartPos));
- System.arraycopy(dataRead, dataStartPos, contentBytes, 0, bytesToCopy);
- startPos = bytesToCopy;
- }
+ System.arraycopy(dataRead, dataStartPos, contentBytes, 0, bytesToCopy);
+ startPos = bytesToCopy;
+ }
- byte[] buffer = new byte[BUFFER_SIZE];
- while (startPos < contentBytes.length)
- {
- int bytesRead = inputStream.read(buffer);
- if (bytesRead < 0)
- {
- throw new IOException("Unexpected end of input stream reached when " +
+ byte[] buffer = new byte[BUFFER_SIZE];
+ while (startPos < contentBytes.length) {
+ int bytesRead = inputStream.read(buffer);
+ if (bytesRead < 0) {
+ throw new IOException("Unexpected end of input stream reached when " +
"reading data from the server");
- }
+ }
- System.arraycopy(buffer, 0, contentBytes, startPos, bytesRead);
- startPos += bytesRead;
- }
+ System.arraycopy(buffer, 0, contentBytes, startPos, bytesRead);
+ startPos += bytesRead;
+ }
+ response.setResponseData(contentBytes);
+ }
- response.setResponseData(contentBytes);
- }
-
- /**
- * Reads the actual data of the response using chunked encoding, which is a
- * way for the server to provide the data in several chunks rather than all at
- * once.
- *
- * @param response The response with which the data is associated.
- * @param inputStream The input stream from which to read the response.
- * @param dataRead The data that we have already read. This includes
- * the header data, but may also include some or all of
- * the content data as well.
- * @param dataStartPos The position in the provided array at which the
- * content data starts.
- * @param dataBytesRead The total number of valid bytes in the provided
- * array that should be considered part of the
- * response (the number of header bytes is included in
- * this count).
- *
- * @throws IOException If a problem occurs while reading data from the
- * server.
- */
- private void readContentDataUsingConnectionClose(HTTPResponse response,
+ /**
+ * Reads the actual data of the response using chunked encoding, which is a
+ * way for the server to provide the data in several chunks rather than all
+ * at once.
+ *
+ * @param response The response with which the data is associated.
+ * @param inputStream The input stream from which to read the response.
+ * @param dataRead The data that we have already read. This includes the
+ * header data, but may also include some or all of the content
+ * data as well.
+ * @param dataStartPos The position in the provided array at which the
+ * content data starts.
+ * @param dataBytesRead The total number of valid bytes in the provided
+ * array that should be considered part of the response (the
+ * number of header bytes is included in this count).
+ *
+ * @throws IOException If a problem occurs while reading data from the
+ * server.
+ */
+ private void readContentDataUsingConnectionClose(HTTPResponse response,
InputStream inputStream,
byte[] dataRead,
int dataStartPos,
int dataBytesRead)
- throws IOException
- {
- // Create an array list that we will use to hold the chunks of information
- // read from the server.
- ArrayList<ByteBuffer> bufferList = new ArrayList<ByteBuffer>();
+ throws IOException {
+ // Create an array list that we will use to hold the chunks of
+ // information
+ // read from the server.
+ ArrayList<ByteBuffer> bufferList = new ArrayList<ByteBuffer>();
+
+ // Create a variable to hold the total number of bytes in the data.
+ int totalBytes = 0;
+
+ // See if we have unread data in the array already provided.
+ int existingBytes = dataBytesRead - dataStartPos;
+ if (existingBytes > 0) {
+ ByteBuffer byteBuffer = ByteBuffer.allocate(existingBytes);
+ byteBuffer.put(dataRead, dataStartPos, existingBytes);
+ bufferList.add(byteBuffer);
+ totalBytes += existingBytes;
+ }
+ // Keep reading until we hit the end of the input stream.
+ byte[] buffer = new byte[BUFFER_SIZE];
+ while (true) {
+ try {
+ int bytesRead = inputStream.read(buffer);
+ if (bytesRead < 0) {
+ // We've hit the end of the stream and therefore the end of
+ // the
+ // document.
+ break;
+ } else if (bytesRead > 0) {
+ ByteBuffer byteBuffer = ByteBuffer.allocate(bytesRead);
+ byteBuffer.put(buffer, 0, bytesRead);
+ bufferList.add(byteBuffer);
+ totalBytes += bytesRead;
+ }
+ } catch (IOException ioe) {
+ // In this case we'll assume that the end of the stream has been
+ // reached. It's possible that there was some other error, but
+ // we can't
+ // do anything about it so try to process what we've got so far.
+ System.out.println("ERROR: unable to read until end of stream");
+ System.out.println("ERROR: " + ioe.getMessage());
+ break;
+ }
+ }
- // Create a variable to hold the total number of bytes in the data.
- int totalBytes = 0;
+ // Assemble the contents of all the buffers into a big array and store
+ // that
+ // array in the response.
+ int startPos = 0;
+ byte[] contentData = new byte[totalBytes];
+ for (int i = 0; i < bufferList.size(); i++) {
+ ByteBuffer byteBuffer = (ByteBuffer) bufferList.get(i);
+ byteBuffer.flip();
+ byteBuffer.get(contentData, startPos, byteBuffer.limit());
+ startPos += byteBuffer.limit();
+ }
+ response.setResponseData(contentData);
+ }
+ // performs ssl connect to given host/port
+ // posts the given query data - format - a byte array
+ // returns HTTPResponse
+
+ public HTTPResponse sslConnect(String hostname, String portnumber,
+ String url, byte[] data) {
+
+ boolean st = true;
+ HTTPResponse hr = null;
+
+ try {
+
+ System.out.println("#############################################");
+ System.out.println("Attempting to connect to: " + hostname + ":" +
+ portnumber);
+
+ Integer x = new Integer(portnumber);
+ int port = x.intValue();
+
+ SSLCertificateApprovalCallback approvalCallback =
+ new TestCertApprovalCallback();
+ SSLClientCertificateSelectionCallback certSelectionCallback =
+ new TestClientCertificateSelectionCallback();
+
+ Socket js = new Socket(InetAddress.getByName(hostname), port);
+ SSLSocket socket = new SSLSocket(js, hostname, approvalCallback,
+ certSelectionCallback);
+ setCipherPref(socket);
+ disableSSL2(socket);
+ socket.forceHandshake();
+ System.out.println("Connected.");
+ socket.setUseClientMode(true);
+
+ DataOutputStream dos =
+ new DataOutputStream(socket.getOutputStream());
+ dos.writeBytes("POST /ocsp HTTP/1.0\r\n");
+ dos.writeBytes("Content-length: " + data.length + "\r\n");
+ dos.writeBytes("\r\n");
+ dos.write(data);
+ dos.writeBytes("\r\n");
+ dos.flush();
+
+ try {
+ hr = readResponse(socket.getInputStream());
+ hr.parseContent();
+ } catch (Exception e) {
+ System.out.println("Exception");
+ e.printStackTrace();
+ st = false;
+ }
+
+ socket.close();
+ dos.close();
+
+ }
+
+ catch (Exception e) {
+ System.err.println("Exception: Unable to Send Request:" + e);
+ e.printStackTrace();
+ st = false;
+ }
- // See if we have unread data in the array already provided.
- int existingBytes = dataBytesRead - dataStartPos;
- if (existingBytes > 0)
- {
- ByteBuffer byteBuffer = ByteBuffer.allocate(existingBytes);
- byteBuffer.put(dataRead, dataStartPos, existingBytes);
- bufferList.add(byteBuffer);
- totalBytes += existingBytes;
+ if (!st)
+ return null;
+ else
+ return hr;
}
+ // performs non ssl connect to given host/port
+ // posts the given query data
+ // returns HTTPResponse
+ public HTTPResponse nonsslConnect(String hostname, String portnumber,
+ String url, byte[] data) {
+
+ boolean st = true;
+ HTTPResponse hr = null;
+
+ try {
+
+ System.out.println("#############################################");
+ System.out.println("Attempting to connect to: " + hostname + ":" +
+ portnumber);
+
+ Integer x = new Integer(portnumber);
+ int port = x.intValue();
+
+ Socket socket = new Socket(hostname, port);
+
+ System.out.println("Posting Query = " +
+ "http://" + hostname +
+ ":" + portnumber +
+ "/" + url);
+
+ System.out.println("Connected.");
+
+ DataOutputStream dos =
+ new DataOutputStream(socket.getOutputStream());
+ dos.writeBytes("POST " + url + " HTTP/1.0\r\n");
+ dos.writeBytes("Content-length: " + data.length + "\r\n");
+ dos.writeBytes("\r\n");
+ dos.write(data);
+ dos.writeBytes("\r\n");
+ dos.flush();
+
+ try {
+ hr = readResponse(socket.getInputStream());
+ hr.parseContent();
+ } catch (Exception e) {
+ System.out.println("Exception");
+ e.printStackTrace();
+ st = false;
+ }
- // Keep reading until we hit the end of the input stream.
- byte[] buffer = new byte[BUFFER_SIZE];
- while (true)
- {
- try
- {
- int bytesRead = inputStream.read(buffer);
- if (bytesRead < 0)
- {
- // We've hit the end of the stream and therefore the end of the
- // document.
- break;
+ socket.close();
+ dos.close();
+
+ }
+
+ catch (Exception e) {
+ System.err.println("Exception: Unable to Send Request:" + e);
+ e.printStackTrace();
+ st = false;
}
- else if (bytesRead > 0)
- {
- ByteBuffer byteBuffer = ByteBuffer.allocate(bytesRead);
- byteBuffer.put(buffer, 0, bytesRead);
- bufferList.add(byteBuffer);
- totalBytes += bytesRead;
+
+ if (!st)
+ return null;
+ else
+ return hr;
+ }
+
+ public static boolean init_nss() {
+ try {
+
+ ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
+ client_certdb_pwd,
+ null,
+ null,
+ null);
+ cCrypt.setDebug(true);
+ cCrypt.setGenerateRequest(false);
+ cCrypt.loginDB();
+ } catch (Exception e) {
+ System.out.println("ERROR: unable to login to : " +
+ client_certdb_dir);
+ return false;
}
- }
- catch (IOException ioe)
- {
- // In this case we'll assume that the end of the stream has been
- // reached. It's possible that there was some other error, but we can't
- // do anything about it so try to process what we've got so far.
- System.out.println("ERROR: unable to read until end of stream");
- System.out.println("ERROR: "+ ioe.getMessage());
- break;
- }
+
+ return true;
}
+ public static void main(String args[]) {
+ HTTPClient hc = new HTTPClient();
+ HTTPResponse hr = null;
+ byte[] responseData = null;
+
+ // parse args
+ StringHolder x_hostname = new StringHolder();
+ StringHolder x_port = new StringHolder();
+ StringHolder x_ssl = new StringHolder();
+ StringHolder x_client_certdb_dir = new StringHolder();
+ StringHolder x_client_certdb_pwd = new StringHolder();
+ StringHolder x_client_cert_nickname = new StringHolder();
+ StringHolder x_uri = new StringHolder();
+ StringHolder x_query = new StringHolder();
+ StringHolder x_request_type = new StringHolder();
+ StringHolder x_auth_type = new StringHolder();
+ StringHolder x_user_id = new StringHolder();
+ StringHolder x_user_password = new StringHolder();
+ StringHolder x_debug = new StringHolder();
+ StringHolder x_decode = new StringHolder();
+
+ // parse the args
+ ArgParser parser = new ArgParser("HTTPClient");
+
+ parser.addOption("-hostname %s #Hostname",
+ x_hostname);
+ parser.addOption("-port %s #port number",
+ x_port);
+ parser.addOption("-ssl %s #HTTP or HTTPS[true or false]",
+ x_ssl);
+ parser.addOption("-client_certdb_dir %s #CertDB dir",
+ x_client_certdb_dir);
+ parser.addOption("-client_certdb_pwd %s #CertDB password",
+ x_client_certdb_pwd);
+ parser.addOption("-client_cert_nickname %s #client cert nickname",
+ x_client_cert_nickname);
+ parser.addOption("-uri %s #URI",
+ x_uri);
+ parser.addOption("-query %s #URL encoded query string[note: url encode value part only for CS operations]",
+ x_query);
+ parser.addOption("-request_type %s #Request Type [ post ]",
+ x_request_type);
+ parser.addOption("-user_id %s #user id for authorization",
+ x_user_id);
+ parser.addOption("-user_password %s #password for authorization",
+ x_user_password);
+ parser.addOption("-auth_type %s #type of authorization [ BASIC ]",
+ x_auth_type);
+ parser.addOption("-debug %s #enables display of debugging info",
+ x_debug);
+ parser.addOption("-decode %s #URL Decode the resulting output",
+ x_decode);
+
+ // and then match the arguments
+ String[] unmatched = null;
+ unmatched = parser.matchAllArgs(args, 0, ArgParser.EXIT_ON_UNMATCHED);
+
+ if (unmatched != null) {
+ System.out.println("ERROR: Argument Mismatch");
+ System.exit(-1);
+ }
+
+ // set variables
+ cs_hostname = x_hostname.value;
+ cs_port = x_port.value;
+ ssl = x_ssl.value;
+ client_certdb_dir = x_client_certdb_dir.value;
+ client_certdb_pwd = x_client_certdb_pwd.value;
+ client_cert_nickname = x_client_cert_nickname.value;
+ uri = x_uri.value;
+ query = x_query.value;
+ request_type = x_request_type.value;
+ user_id = x_user_id.value;
+ user_password = x_user_password.value;
+ auth_type = x_auth_type.value;
+ debug = x_debug.value;
+
+ String decode = x_decode.value;
+
+ // init_nss if needed
+ boolean st = init_nss();
+ if (!st)
+ System.exit(-1);
+
+ // set basic auth if needed
+ if (auth_type != null && auth_type.equalsIgnoreCase("BASIC")) {
+ // BASE64Encoder encoder = new BASE64Encoder();
+
+ // String temp = encoder.encodeBuffer((user_id +
+ // ":" + user_password).getBytes());
+ String temp = OSUtil.BtoA((user_id +
+ ":" + user_password).getBytes());
+
+ // note: temp already contains \r and \n.
+ // remove \r and \n from the base64 encoded string.
+ // causes problems when sending http post requests
+ // using PrintStream.println()
+
+ temp = temp.replaceAll("\\r", "");
+ temp = temp.replaceAll("\\n", "");
+
+ basic_auth_header_value = temp;
+ }
+
+ // route to proper function
+
+ if (ssl != null && ssl.equalsIgnoreCase("true")) {
+ if (client_cert_nickname != null &&
+ !client_cert_nickname.equalsIgnoreCase("null")) {
+ // ssl client auth call
+
+ hr = hc.sslConnectClientAuth(cs_hostname, cs_port,
+ client_cert_nickname,
+ uri, query);
+ }
+
+ else {
+ // ssl client call
+ hr = hc.sslConnect(cs_hostname, cs_port, uri, query);
+ }
+ } else if (ssl != null && ssl.equalsIgnoreCase("false")) {
+ // non ssl connect
+ hr = hc.nonsslConnect(cs_hostname, cs_port, uri, query);
+ } else {
+ System.out.println("ERROR: ssl parameter is null");
+ System.exit(-1);
+ }
+
+ // collect and print response
+
+ responseData = hr.getResponseData();
+
+ if (hr.getStatusCode() == 200)
+ System.out.println("Response from Host:" + cs_hostname + " OK");
+ else {
+ System.out.println("ERROR: unable to get response from host:" +
+ cs_hostname);
+ System.exit(-1);
+ }
+
+ String responseValue = null;
+ if (decode.equalsIgnoreCase("true"))
+ responseValue = URLDecoder.decode(hr.getHTML());
+ else
+ responseValue = hr.getHTML();
+
+ System.out.println("###############################");
+ System.out.println("RESULT=" + responseValue);
+ System.out.println("###############################");
- // Assemble the contents of all the buffers into a big array and store that
- // array in the response.
- int startPos = 0;
- byte[] contentData = new byte[totalBytes];
- for (int i=0; i < bufferList.size(); i++)
- {
- ByteBuffer byteBuffer = (ByteBuffer) bufferList.get(i);
- byteBuffer.flip();
- byteBuffer.get(contentData, startPos, byteBuffer.limit());
- startPos += byteBuffer.limit();
}
- response.setResponseData(contentData);
- }
-
- // performs ssl connect to given host/port
- // posts the given query data - format - a byte array
- // returns HTTPResponse
-
- public HTTPResponse sslConnect(String hostname, String portnumber,
- String url, byte[] data)
- {
-
- boolean st = true;
- HTTPResponse hr = null;
-
- try
- {
-
- System.out.println("#############################################");
- System.out.println("Attempting to connect to: " + hostname + ":" +
- portnumber);
-
- Integer x = new Integer(portnumber);
- int port = x.intValue();
-
-
- SSLCertificateApprovalCallback approvalCallback =
- new TestCertApprovalCallback();
- SSLClientCertificateSelectionCallback certSelectionCallback =
- new TestClientCertificateSelectionCallback();
-
- Socket js = new Socket(InetAddress.getByName(hostname), port);
- SSLSocket socket = new SSLSocket(js, hostname, approvalCallback,
- certSelectionCallback );
- setCipherPref(socket);
- disableSSL2(socket);
- socket.forceHandshake();
- System.out.println("Connected.");
- socket.setUseClientMode(true);
-
- DataOutputStream dos =
- new DataOutputStream(socket.getOutputStream());
- dos.writeBytes("POST /ocsp HTTP/1.0\r\n");
- dos.writeBytes("Content-length: " + data.length + "\r\n");
- dos.writeBytes("\r\n");
- dos.write(data);
- dos.writeBytes("\r\n");
- dos.flush();
-
- try
- {
- hr = readResponse(socket.getInputStream());
- hr.parseContent();
- }
- catch (Exception e)
- {
- System.out.println("Exception");
- e.printStackTrace();
- st = false;
- }
-
- socket.close();
- dos.close();
-
- }
-
- catch(Exception e)
- {
- System.err.println("Exception: Unable to Send Request:" +e);
- e.printStackTrace();
- st = false;
- }
-
- if(!st)
- return null;
- else
- return hr;
- }
-
- // performs non ssl connect to given host/port
- // posts the given query data
- // returns HTTPResponse
- public HTTPResponse nonsslConnect(String hostname, String portnumber,
- String url, byte[] data)
- {
-
- boolean st = true;
- HTTPResponse hr = null;
-
- try
- {
-
- System.out.println("#############################################");
- System.out.println("Attempting to connect to: " + hostname + ":" +
- portnumber);
-
- Integer x = new Integer(portnumber);
- int port = x.intValue();
-
- Socket socket = new Socket(hostname, port);
-
- System.out.println("Posting Query = " +
- "http://" + hostname +
- ":" + portnumber +
- "/" + url );
-
- System.out.println("Connected.");
-
- DataOutputStream dos =
- new DataOutputStream(socket.getOutputStream());
- dos.writeBytes("POST " + url + " HTTP/1.0\r\n");
- dos.writeBytes("Content-length: " + data.length + "\r\n");
- dos.writeBytes("\r\n");
- dos.write(data);
- dos.writeBytes("\r\n");
- dos.flush();
-
- try
- {
- hr = readResponse(socket.getInputStream());
- hr.parseContent();
- }
- catch (Exception e)
- {
- System.out.println("Exception");
- e.printStackTrace();
- st = false;
- }
-
- socket.close();
- dos.close();
-
- }
-
- catch(Exception e)
- {
- System.err.println("Exception: Unable to Send Request:" +e);
- e.printStackTrace();
- st = false;
- }
-
- if(!st)
- return null;
- else
- return hr;
- }
-
- public static boolean init_nss()
- {
- try
- {
-
- ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
- client_certdb_pwd,
- null,
- null,
- null);
- cCrypt.setDebug(true);
- cCrypt.setGenerateRequest(false);
- cCrypt.loginDB();
- }
- catch(Exception e)
- {
- System.out.println("ERROR: unable to login to : " +
- client_certdb_dir );
- return false;
- }
-
- return true;
- }
-
- public static void main(String args[])
- {
- HTTPClient hc = new HTTPClient();
- HTTPResponse hr = null;
- byte[] responseData = null;
-
- // parse args
- StringHolder x_hostname = new StringHolder();
- StringHolder x_port = new StringHolder();
- StringHolder x_ssl = new StringHolder();
- StringHolder x_client_certdb_dir = new StringHolder();
- StringHolder x_client_certdb_pwd = new StringHolder();
- StringHolder x_client_cert_nickname = new StringHolder();
- StringHolder x_uri = new StringHolder();
- StringHolder x_query = new StringHolder();
- StringHolder x_request_type = new StringHolder();
- StringHolder x_auth_type = new StringHolder();
- StringHolder x_user_id = new StringHolder();
- StringHolder x_user_password = new StringHolder();
- StringHolder x_debug = new StringHolder();
- StringHolder x_decode = new StringHolder();
-
- // parse the args
- ArgParser parser = new ArgParser("HTTPClient");
-
- parser.addOption ("-hostname %s #Hostname",
- x_hostname);
- parser.addOption ("-port %s #port number",
- x_port);
- parser.addOption ("-ssl %s #HTTP or HTTPS[true or false]",
- x_ssl);
- parser.addOption ("-client_certdb_dir %s #CertDB dir",
- x_client_certdb_dir);
- parser.addOption ("-client_certdb_pwd %s #CertDB password",
- x_client_certdb_pwd);
- parser.addOption ("-client_cert_nickname %s #client cert nickname",
- x_client_cert_nickname);
- parser.addOption ("-uri %s #URI",
- x_uri);
- parser.addOption ("-query %s #URL encoded query string[note: url encode value part only for CS operations]",
- x_query);
- parser.addOption ("-request_type %s #Request Type [ post ]",
- x_request_type);
- parser.addOption ("-user_id %s #user id for authorization",
- x_user_id);
- parser.addOption ("-user_password %s #password for authorization",
- x_user_password);
- parser.addOption ("-auth_type %s #type of authorization [ BASIC ]",
- x_auth_type);
- parser.addOption ("-debug %s #enables display of debugging info",
- x_debug);
- parser.addOption ("-decode %s #URL Decode the resulting output" ,
- x_decode);
-
- // and then match the arguments
- String [] unmatched = null;
- unmatched = parser.matchAllArgs (args,0,ArgParser.EXIT_ON_UNMATCHED);
-
- if(unmatched!=null)
- {
- System.out.println("ERROR: Argument Mismatch");
- System.exit(-1);
- }
-
- // set variables
- cs_hostname = x_hostname.value;
- cs_port = x_port.value;
- ssl = x_ssl.value;
- client_certdb_dir = x_client_certdb_dir.value;
- client_certdb_pwd = x_client_certdb_pwd.value;
- client_cert_nickname = x_client_cert_nickname.value;
- uri = x_uri.value;
- query = x_query.value;
- request_type = x_request_type.value;
- user_id = x_user_id.value;
- user_password = x_user_password.value;
- auth_type = x_auth_type.value;
- debug = x_debug.value;
-
- String decode = x_decode.value;
-
- // init_nss if needed
- boolean st = init_nss();
- if(!st)
- System.exit(-1);
-
- // set basic auth if needed
- if(auth_type != null && auth_type.equalsIgnoreCase("BASIC"))
- {
- // BASE64Encoder encoder = new BASE64Encoder();
-
- // String temp = encoder.encodeBuffer((user_id +
- // ":" + user_password).getBytes());
- String temp = OSUtil.BtoA((user_id +
- ":" + user_password).getBytes());
-
- // note: temp already contains \r and \n.
- // remove \r and \n from the base64 encoded string.
- // causes problems when sending http post requests
- // using PrintStream.println()
-
- temp = temp.replaceAll("\\r" , "");
- temp = temp.replaceAll("\\n" , "");
-
- basic_auth_header_value = temp;
- }
-
- // route to proper function
-
- if(ssl != null && ssl.equalsIgnoreCase("true"))
- {
- if(client_cert_nickname != null &&
- !client_cert_nickname.equalsIgnoreCase("null"))
- {
- // ssl client auth call
-
- hr = hc.sslConnectClientAuth(cs_hostname,cs_port,
- client_cert_nickname,
- uri,query);
- }
-
- else
- {
- // ssl client call
- hr = hc.sslConnect(cs_hostname,cs_port,uri,query);
- }
- }
- else if(ssl!=null && ssl.equalsIgnoreCase("false"))
- {
- // non ssl connect
- hr = hc.nonsslConnect(cs_hostname,cs_port,uri,query);
- }
- else
- {
- System.out.println("ERROR: ssl parameter is null");
- System.exit(-1);
- }
-
-
- // collect and print response
-
- responseData = hr.getResponseData();
-
- if(hr.getStatusCode() == 200)
- System.out.println("Response from Host:" + cs_hostname + " OK");
- else
- {
- System.out.println("ERROR: unable to get response from host:" +
- cs_hostname);
- System.exit(-1);
- }
-
- String responseValue = null;
- if(decode.equalsIgnoreCase("true"))
- responseValue = URLDecoder.decode(hr.getHTML());
- else
- responseValue = hr.getHTML();
-
-
- System.out.println("###############################");
- System.out.println("RESULT=" + responseValue);
- System.out.println("###############################");
-
- }
};
diff --git a/pki/base/silent/src/com/netscape/pkisilent/http/HTTPResponse.java b/pki/base/silent/src/com/netscape/pkisilent/http/HTTPResponse.java
index 08358f35..49122f3e 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/http/HTTPResponse.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/http/HTTPResponse.java
@@ -1,4 +1,5 @@
package com.netscape.pkisilent.http;
+
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -17,369 +18,299 @@ package com.netscape.pkisilent.http;
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
-
import java.util.ArrayList;
import java.util.StringTokenizer;
import com.netscape.pkisilent.common.Utilities;
+public class HTTPResponse {
+ // The set of cookie values included in this response.
+ ArrayList<String> cookieValueList;
+
+ // The names of the headers included in this response.
+ ArrayList<String> headerNameList;
+
+ // The values of the headers included in this response.
+ ArrayList<String> headerValueList;
+
+ // The actual data associated with this response.
+ byte[] responseData;
+
+ // The HTML document included in the response, if appropriate.
+ HTMLDocument htmlDocument;
+
+ // The number of bytes contained in the content of the response.
+ int contentLength;
+
+ // The HTTP status code for the response.
+ int statusCode;
+
+ // The MIME type of the response.
+ String contentType;
+
+ // The protocol version string for this response.
+ String protolVersion;
+
+ // The response message for this response.
+ String responseMessage;
+
+ // Parsed Content Name/Value pair info
+ ArrayList<String> contentName;
+ ArrayList<String> contentValue;
+
+ /**
+ * Creates a new HTTP response with the provided status code.
+ *
+ * @param statusCode The HTTP status code for this response.
+ * @param protocolVersion The protocol and version for this response.
+ * @param responseMessage The message associated with this response.
+ */
+ public HTTPResponse(int statusCode, String protocolVersion,
+ String responseMessage) {
+ this.statusCode = statusCode;
+ this.protolVersion = protocolVersion;
+ this.responseMessage = responseMessage;
+
+ htmlDocument = null;
+ contentType = null;
+ contentLength = -1;
+ responseData = new byte[0];
+ cookieValueList = new ArrayList<String>();
+ headerNameList = new ArrayList<String>();
+ headerValueList = new ArrayList<String>();
+ contentName = new ArrayList<String>();
+ contentValue = new ArrayList<String>();
+ }
+
+ /**
+ * Retrieves the status code for this HTTP response.
+ *
+ * @return The status code for this HTTP response.
+ */
+ public int getStatusCode() {
+ return statusCode;
+ }
+
+ /**
+ * Retrieves the protocol version for this HTTP response.
+ *
+ * @return The protocol version for this HTTP response.
+ */
+ public String getProtocolVersion() {
+ return protolVersion;
+ }
+
+ /**
+ * Retrieves the response message for this HTTP response.
+ *
+ * @return The response message for this HTTP response.
+ */
+ public String getResponseMessage() {
+ return responseMessage;
+ }
-public class HTTPResponse
-{
- // The set of cookie values included in this response.
- ArrayList<String> cookieValueList;
+ /**
+ * Retrieves the value of the header with the specified name. If the
+ * specified header has more than one value, then only the first will be
+ * retrieved.
+ *
+ * @return The value of the header with the specified name, or
+ * <CODE>null</CODE> if no such header is available.
+ */
+ public String getHeader(String headerName) {
+ String lowerName = headerName.toLowerCase();
+
+ for (int i = 0; i < headerNameList.size(); i++) {
+ if (lowerName.equals(headerNameList.get(i))) {
+ return headerValueList.get(i);
+ }
+ }
+
+ return null;
+ }
- // The names of the headers included in this response.
- ArrayList<String> headerNameList;
+ /**
+ * Retrieves the set of values for the specified header.
+ *
+ * @return The set of values for the specified header.
+ */
+ public String[] getHeaderValues(String headerName) {
+ ArrayList<String> valueList = new ArrayList<String>();
+ String lowerName = headerName.toLowerCase();
+
+ for (int i = 0; i < headerNameList.size(); i++) {
+ if (lowerName.equals(headerNameList.get(i))) {
+ valueList.add(headerValueList.get(i));
+ }
+ }
+
+ String[] values = new String[valueList.size()];
+ valueList.toArray(values);
+ return values;
+ }
- // The values of the headers included in this response.
- ArrayList<String> headerValueList;
+ /**
+ * Adds a header with the given name and value to this response.
+ *
+ * @param headerName The name of the header to add to this response.
+ * @param headerValue The value of the header to add to this response.
+ */
+ public void addHeader(String headerName, String headerValue) {
+ String lowerName = headerName.toLowerCase();
+ headerNameList.add(lowerName);
+ headerValueList.add(headerValue);
+
+ if (lowerName.equals("content-length")) {
+ try {
+ contentLength = Integer.parseInt(headerValue);
+ } catch (NumberFormatException nfe) {
+ }
+ } else if (lowerName.equals("content-type")) {
+ contentType = headerValue;
+ } else if (lowerName.equals("set-cookie")) {
+ cookieValueList.add(headerValue);
+ }
+ }
+
+ /**
+ * Retrieves a two-dimensional array containing the header data for this
+ * response, with each element being an array containing a name/value pair.
+ *
+ * @return A two-dimensional array containing the header data for this
+ * response.
+ */
+ public String[][] getHeaderElements() {
+ String[][] headerElements = new String[headerNameList.size()][2];
+ for (int i = 0; i < headerNameList.size(); i++) {
+ headerElements[i][0] = headerNameList.get(i);
+ headerElements[i][1] = headerValueList.get(i);
+ }
+
+ return headerElements;
+ }
- // The actual data associated with this response.
- byte[] responseData;
+ /**
+ * Retrieves the raw data included in this HTTP response. If the response
+ * did not include any data, an empty array will be returned.
+ *
+ * @return The raw data included in this HTTP response.
+ */
+ public byte[] getResponseData() {
+ return responseData;
+ }
- // The HTML document included in the response, if appropriate.
- HTMLDocument htmlDocument;
+ public String getHTML() {
+ String htmlString = new String(responseData);
+ return htmlString;
+ }
- // The number of bytes contained in the content of the response.
- int contentLength;
-
- // The HTTP status code for the response.
- int statusCode;
-
- // The MIME type of the response.
- String contentType;
-
- // The protocol version string for this response.
- String protolVersion;
-
- // The response message for this response.
- String responseMessage;
-
- // Parsed Content Name/Value pair info
- ArrayList<String> contentName;
- ArrayList<String> contentValue;
-
-
-
- /**
- * Creates a new HTTP response with the provided status code.
- *
- * @param statusCode The HTTP status code for this response.
- * @param protocolVersion The protocol and version for this response.
- * @param responseMessage The message associated with this response.
- */
- public HTTPResponse(int statusCode, String protocolVersion,
- String responseMessage)
- {
- this.statusCode = statusCode;
- this.protolVersion = protocolVersion;
- this.responseMessage = responseMessage;
-
- htmlDocument = null;
- contentType = null;
- contentLength = -1;
- responseData = new byte[0];
- cookieValueList = new ArrayList<String>();
- headerNameList = new ArrayList<String>();
- headerValueList = new ArrayList<String>();
- contentName = new ArrayList<String>();
- contentValue = new ArrayList<String>();
- }
-
-
-
- /**
- * Retrieves the status code for this HTTP response.
- *
- * @return The status code for this HTTP response.
- */
- public int getStatusCode()
- {
- return statusCode;
- }
-
-
-
- /**
- * Retrieves the protocol version for this HTTP response.
- *
- * @return The protocol version for this HTTP response.
- */
- public String getProtocolVersion()
- {
- return protolVersion;
- }
-
-
-
- /**
- * Retrieves the response message for this HTTP response.
- *
- * @return The response message for this HTTP response.
- */
- public String getResponseMessage()
- {
- return responseMessage;
- }
-
-
-
- /**
- * Retrieves the value of the header with the specified name. If the
- * specified header has more than one value, then only the first will be
- * retrieved.
- *
- * @return The value of the header with the specified name, or
- * <CODE>null</CODE> if no such header is available.
- */
- public String getHeader(String headerName)
- {
- String lowerName = headerName.toLowerCase();
-
- for (int i=0; i < headerNameList.size(); i++)
- {
- if (lowerName.equals(headerNameList.get(i)))
- {
- return headerValueList.get(i);
- }
+ public String getHTMLwithoutTags() {
+ String htmlString = new String(responseData);
+ HTMLDocument htmldocument = new HTMLDocument(htmlString);
+ return htmldocument.getTextData();
}
- return null;
- }
+ public void parseContent() {
+ // parse the responseData byte[] buffer and split content into name
+ // value pair
+ String htmlString = new String(responseData);
+ StringTokenizer st = new StringTokenizer(htmlString, "\n");
+ Utilities ut = new Utilities();
+ while (st.hasMoreTokens()) {
+ String line = st.nextToken();
+ // format for line assumed to be name="value"; format
+ int eqPos = line.indexOf('=');
+ if (eqPos != -1) {
+ String name = line.substring(0, eqPos);
+ String tempval = line.substring(eqPos + 1).trim();
+ String value = ut.cleanupQuotes(ut.removechar(tempval));
- /**
- * Retrieves the set of values for the specified header.
- *
- * @return The set of values for the specified header.
- */
- public String[] getHeaderValues(String headerName)
- {
- ArrayList<String> valueList = new ArrayList<String>();
- String lowerName = headerName.toLowerCase();
+ // add to array
+ this.contentName.add(name.trim());
+ this.contentValue.add(value);
+ }
+
+ }
- for (int i=0; i < headerNameList.size(); i++)
- {
- if (lowerName.equals(headerNameList.get(i)))
- {
- valueList.add(headerValueList.get(i));
- }
}
- String[] values = new String[valueList.size()];
- valueList.toArray(values);
- return values;
- }
-
-
-
- /**
- * Adds a header with the given name and value to this response.
- *
- * @param headerName The name of the header to add to this response.
- * @param headerValue The value of the header to add to this response.
- */
- public void addHeader(String headerName, String headerValue)
- {
- String lowerName = headerName.toLowerCase();
- headerNameList.add(lowerName);
- headerValueList.add(headerValue);
-
- if (lowerName.equals("content-length"))
- {
- try
- {
- contentLength = Integer.parseInt(headerValue);
- } catch (NumberFormatException nfe) {}
+ public String getContentValue(String headerName) {
+ for (int i = 0; i < contentName.size(); i++) {
+ if (headerName.equals(contentName.get(i))) {
+ return contentValue.get(i);
+ }
+ }
+
+ return null;
}
- else if (lowerName.equals("content-type"))
- {
- contentType = headerValue;
+
+ public ArrayList<String> getContentNames() {
+ return contentName;
+ }
+
+ public ArrayList<String> getContentValues() {
+ return contentValue;
}
- else if (lowerName.equals("set-cookie"))
- {
- cookieValueList.add(headerValue);
+
+ /**
+ * Sets the actual data associated with this response.
+ *
+ * @param responseData The actual data associated with this response.
+ */
+ public void setResponseData(byte[] responseData) {
+ if (responseData == null) {
+ this.responseData = new byte[0];
+ } else {
+ this.responseData = responseData;
+ }
}
- }
-
-
-
- /**
- * Retrieves a two-dimensional array containing the header data for this
- * response, with each element being an array containing a name/value pair.
- *
- * @return A two-dimensional array containing the header data for this
- * response.
- */
- public String[][] getHeaderElements()
- {
- String[][] headerElements = new String[headerNameList.size()][2];
- for (int i=0; i < headerNameList.size(); i++)
- {
- headerElements[i][0] = headerNameList.get(i);
- headerElements[i][1] = headerValueList.get(i);
+
+ /**
+ * Retrieves the content length associated with this response.
+ *
+ * @return The content length associated with this response, or -1 if no
+ * content length is available.
+ */
+ public int getContentLength() {
+ return contentLength;
}
- return headerElements;
- }
-
-
-
- /**
- * Retrieves the raw data included in this HTTP response. If the response did
- * not include any data, an empty array will be returned.
- *
- * @return The raw data included in this HTTP response.
- */
- public byte[] getResponseData()
- {
- return responseData;
- }
-
-
- public String getHTML()
- {
- String htmlString = new String(responseData);
- return htmlString;
- }
-
- public String getHTMLwithoutTags()
- {
- String htmlString = new String(responseData);
- HTMLDocument htmldocument = new HTMLDocument(htmlString);
- return htmldocument.getTextData();
- }
- public void parseContent()
- {
- // parse the responseData byte[] buffer and split content into name
- // value pair
- String htmlString = new String(responseData);
- StringTokenizer st = new StringTokenizer(htmlString, "\n");
- Utilities ut = new Utilities();
-
- while(st.hasMoreTokens())
- {
- String line = st.nextToken();
- // format for line assumed to be name="value"; format
-
- int eqPos = line.indexOf('=') ;
- if(eqPos != -1)
- {
- String name = line.substring(0,eqPos);
- String tempval = line.substring(eqPos+1).trim();
- String value = ut.cleanupQuotes(ut.removechar(tempval));
-
- // add to array
- this.contentName.add(name.trim());
- this.contentValue.add(value);
- }
-
- }
-
- }
-
-
-
- public String getContentValue(String headerName)
- {
- for (int i=0; i < contentName.size(); i++)
- {
- if (headerName.equals(contentName.get(i)))
- {
- return contentValue.get(i);
- }
- }
-
- return null;
- }
-
- public ArrayList<String> getContentNames()
- {
- return contentName;
- }
-
- public ArrayList<String> getContentValues()
- {
- return contentValue;
- }
-
- /**
- * Sets the actual data associated with this response.
- *
- * @param responseData The actual data associated with this response.
- */
- public void setResponseData(byte[] responseData)
- {
- if (responseData == null)
- {
- this.responseData = new byte[0];
+ /**
+ * Retrieves the content type associated with this response.
+ *
+ * @return The content type associated with this response, or
+ * <CODE>null</CODE> if no content type is available.
+ */
+ public String getContentType() {
+ return contentType;
}
- else
- {
- this.responseData = responseData;
+
+ /**
+ * Retrieves an array containing the values of the cookies that should be
+ * set based on the information in this response.
+ *
+ * @return An array containing the values of the cookies that should be set
+ * based on the information in this response.
+ */
+ public String[] getCookieValues() {
+ String[] cookieValues = new String[cookieValueList.size()];
+ cookieValueList.toArray(cookieValues);
+ return cookieValues;
}
- }
-
-
-
- /**
- * Retrieves the content length associated with this response.
- *
- * @return The content length associated with this response, or -1 if no
- * content length is available.
- */
- public int getContentLength()
- {
- return contentLength;
- }
-
-
-
- /**
- * Retrieves the content type associated with this response.
- *
- * @return The content type associated with this response, or
- * <CODE>null</CODE> if no content type is available.
- */
- public String getContentType()
- {
- return contentType;
- }
-
-
-
- /**
- * Retrieves an array containing the values of the cookies that should be set
- * based on the information in this response.
- *
- * @return An array containing the values of the cookies that should be set
- * based on the information in this response.
- */
- public String[] getCookieValues()
- {
- String[] cookieValues = new String[cookieValueList.size()];
- cookieValueList.toArray(cookieValues);
- return cookieValues;
- }
-
- public String getCookieValue(String headerName)
- {
- for (int i=0; i < cookieValueList.size(); i++)
- {
- System.out.println("cookie list: " + cookieValueList.get(i));
-
- String temp = cookieValueList.get(i);
- if (temp.startsWith(headerName))
- {
- return cookieValueList.get(i);
- }
- }
-
- return null;
- }
+ public String getCookieValue(String headerName) {
+ for (int i = 0; i < cookieValueList.size(); i++) {
+ System.out.println("cookie list: " + cookieValueList.get(i));
-}
+ String temp = cookieValueList.get(i);
+ if (temp.startsWith(headerName)) {
+ return cookieValueList.get(i);
+ }
+ }
+ return null;
+ }
+
+}
diff --git a/pki/base/symkey/src/com/netscape/symkey/SessionKey.java b/pki/base/symkey/src/com/netscape/symkey/SessionKey.java
index 3a00c835..e14e686b 100644
--- a/pki/base/symkey/src/com/netscape/symkey/SessionKey.java
+++ b/pki/base/symkey/src/com/netscape/symkey/SessionKey.java
@@ -18,22 +18,18 @@
package com.netscape.symkey;
-
import org.mozilla.jss.pkcs11.PK11SymKey;
-
/**
- * This object contains the OS independent interfaces.
+ * This object contains the OS independent interfaces.
*/
-public class SessionKey
-{
- static boolean tryLoad( String filename )
- {
+public class SessionKey {
+ static boolean tryLoad(String filename) {
try {
- System.load( filename );
- } catch( Exception e ) {
+ System.load(filename);
+ } catch (Exception e) {
return false;
- } catch( UnsatisfiedLinkError e ) {
+ } catch (UnsatisfiedLinkError e) {
return false;
}
@@ -43,43 +39,45 @@ public class SessionKey
// Load native library
static {
boolean mNativeLibrariesLoaded = false;
- String os = System.getProperty( "os.name" );
- if( ( os.equals( "Linux" ) ) ) {
+ String os = System.getProperty("os.name");
+ if ((os.equals("Linux"))) {
// Check for 64-bit library availability
// prior to 32-bit library availability.
mNativeLibrariesLoaded =
- tryLoad( "/usr/lib64/symkey/libsymkey.so" );
- if( mNativeLibrariesLoaded ) {
- System.out.println( "64-bit symkey library loaded" );
+ tryLoad("/usr/lib64/symkey/libsymkey.so");
+ if (mNativeLibrariesLoaded) {
+ System.out.println("64-bit symkey library loaded");
} else {
- // REMINDER: May be trying to run a 32-bit app
- // on 64-bit platform.
+ // REMINDER: May be trying to run a 32-bit app
+ // on 64-bit platform.
mNativeLibrariesLoaded =
- tryLoad( "/usr/lib/symkey/libsymkey.so" );
- if( mNativeLibrariesLoaded ) {
- System.out.println( "32-bit symkey library loaded");
+ tryLoad("/usr/lib/symkey/libsymkey.so");
+ if (mNativeLibrariesLoaded) {
+ System.out.println("32-bit symkey library loaded");
} else {
- System.out.println( "FAILED loading symkey library!");
- System.exit( -1 );
+ System.out.println("FAILED loading symkey library!");
+ System.exit(-1);
}
}
} else {
try {
- System.loadLibrary( "symkey" );
- System.out.println( "symkey library loaded" );
+ System.loadLibrary("symkey");
+ System.out.println("symkey library loaded");
mNativeLibrariesLoaded = true;
- } catch( Throwable t ) {
+ } catch (Throwable t) {
// This is bad news, the program is doomed at this point
t.printStackTrace();
}
}
}
-
// external calls from RA
- public static native byte[] ComputeKeyCheck(PK11SymKey desKey ); /* byte data[] ); */
+ public static native byte[] ComputeKeyCheck(PK11SymKey desKey); /*
+ * byte
+ * data[] );
+ */
- public static native byte[] ComputeSessionKey( String tokenName,
+ public static native byte[] ComputeSessionKey(String tokenName,
String keyName,
byte[] card_challenge,
byte[] host_challenge,
@@ -88,9 +86,9 @@ public class SessionKey
byte[] macKeyArray,
String useSoftToken,
String keySet,
- String sharedSecretKeyName );
+ String sharedSecretKeyName);
- public static native byte[] ComputeEncSessionKey( String tokenName,
+ public static native byte[] ComputeEncSessionKey(String tokenName,
String keyName,
byte[] card_challenge,
byte[] host_challenge,
@@ -98,9 +96,9 @@ public class SessionKey
byte[] CUID,
byte[] encKeyArray,
String useSoftToken,
- String keySet );
+ String keySet);
- public static native PK11SymKey ComputeKekSessionKey( String tokenName,
+ public static native PK11SymKey ComputeKekSessionKey(String tokenName,
String keyName,
byte[] card_challenge,
byte[] host_challenge,
@@ -108,21 +106,22 @@ public class SessionKey
byte[] CUID,
byte[] kekKeyArray,
String useSoftToken,
- String keySet );
+ String keySet);
- public static native PK11SymKey ComputeKekKey( String tokenName,
+ public static native PK11SymKey ComputeKekKey(String tokenName,
String keyName,
byte[] card_challenge,
byte[] host_challenge,
byte[] keyInfo,
byte[] CUID,
byte[] kekKeyArray,
- String useSoftToken, String keySet );
+ String useSoftToken, String keySet);
- public static native byte[] ECBencrypt( PK11SymKey key,
- PK11SymKey desKey ); //byte[] data );
+ public static native byte[] ECBencrypt(PK11SymKey key,
+ PK11SymKey desKey); // byte[] data
+ // );
- public static native PK11SymKey GenerateSymkey( String tokenName );
+ public static native PK11SymKey GenerateSymkey(String tokenName);
/*
* DRM_SUPPORT_DEBUG
@@ -130,7 +129,7 @@ public class SessionKey
// public static native PK11SymKey bytes2PK11SymKey( byte[] symKeyBytes );
- public static native byte[] ComputeCryptogram( String tokenName,
+ public static native byte[] ComputeCryptogram(String tokenName,
String keyName,
byte[] card_challenge,
byte[] host_challenge,
@@ -138,36 +137,35 @@ public class SessionKey
byte[] CUID,
int type,
byte[] authKeyArray,
- String useSoftToken, String keySet );
+ String useSoftToken, String keySet);
- public static native byte[] EncryptData( String tokenName,
+ public static native byte[] EncryptData(String tokenName,
String keyName,
byte[] in,
byte[] keyInfo,
byte[] CUID,
byte[] kekKeyArray,
- String useSoftToken, String keySet );
+ String useSoftToken, String keySet);
- public static native byte[] DiversifyKey( String tokenName,
+ public static native byte[] DiversifyKey(String tokenName,
String newTokenName,
String oldMasterKeyName,
String newMasterKeyName,
String keyInfo,
byte[] CUIDValue,
byte[] kekKeyArray,
- String useSoftToken, String keySet );
+ String useSoftToken, String keySet);
// internal calls from config TKS keys tab
- public static native String GenMasterKey( String token,
- String keyName );
+ public static native String GenMasterKey(String token,
+ String keyName);
- public static native String DeleteSymmetricKey( String token,
- String keyName );
+ public static native String DeleteSymmetricKey(String token,
+ String keyName);
- public static native String ListSymmetricKeys( String token );
+ public static native String ListSymmetricKeys(String token);
- // set when called from the config TKS tab to create master key
- // get when called from the RA to create session key
- public static native void SetDefaultPrefix( String masterPrefix );
+ // set when called from the config TKS tab to create master key
+ // get when called from the RA to create session key
+ public static native void SetDefaultPrefix(String masterPrefix);
}
-
diff --git a/pki/base/test/src/com/netscape/test/TestListener.java b/pki/base/test/src/com/netscape/test/TestListener.java
index af6c9bf7..96c4c906 100644
--- a/pki/base/test/src/com/netscape/test/TestListener.java
+++ b/pki/base/test/src/com/netscape/test/TestListener.java
@@ -118,9 +118,9 @@ public class TestListener extends RunListener {
testSuiteElement.setAttribute("name", testSuiteName);
testSuiteElement.setAttribute("timestamp",
- dateFormat.format(new Date(testSuiteStartTime)));
+ dateFormat.format(new Date(testSuiteStartTime)));
testSuiteElement.setAttribute("hostname",
- InetAddress.getLocalHost().getHostName());
+ InetAddress.getLocalHost().getHostName());
// system properties
Element propertiesElement = document.createElement("properties");
@@ -168,20 +168,20 @@ public class TestListener extends RunListener {
testSuiteElement.appendChild(systemOutElement);
systemOutElement.appendChild(
- document.createCDATASection(out.toString())
- );
+ document.createCDATASection(out.toString())
+ );
Element systemErrElement = document.createElement("system-err");
testSuiteElement.appendChild(systemErrElement);
systemErrElement.appendChild(
- document.createCDATASection(err.toString())
- );
+ document.createCDATASection(err.toString())
+ );
// write to file
FileWriter fw = new FileWriter(
- reportsDir + File.separator + "TEST-" + currentTestSuiteName + ".xml"
- );
+ reportsDir + File.separator + "TEST-" + currentTestSuiteName + ".xml"
+ );
StreamResult sr = new StreamResult(fw);
DOMSource source = new DOMSource(document);
trans.transform(source, sr);
@@ -223,12 +223,13 @@ public class TestListener extends RunListener {
failureElement.setAttribute("type", exceptionName);
Text messageElement = document.createTextNode(
- exceptionName + ": " +failure.getMessage() + "\n"
- );
+ exceptionName + ": " + failure.getMessage() + "\n"
+ );
// print stack trace
for (StackTraceElement element : exception.getStackTrace()) {
- if (!element.getClassName().equals(description.getClassName())) continue;
+ if (!element.getClassName().equals(description.getClassName()))
+ continue;
String source = "Unknown Source";
if (element.getFileName() != null && element.getLineNumber() >= 0) {
@@ -236,9 +237,9 @@ public class TestListener extends RunListener {
}
messageElement.appendData("\tat " +
- element.getClassName() + "." + element.getMethodName() +
- "(" + source + ")\n"
- );
+ element.getClassName() + "." + element.getMethodName() +
+ "(" + source + ")\n"
+ );
}
failureElement.appendChild(messageElement);
diff --git a/pki/base/tks/src/com/netscape/tks/TKSAuthority.java b/pki/base/tks/src/com/netscape/tks/TKSAuthority.java
index 0dd6876e..2c8142a2 100644
--- a/pki/base/tks/src/com/netscape/tks/TKSAuthority.java
+++ b/pki/base/tks/src/com/netscape/tks/TKSAuthority.java
@@ -27,43 +27,47 @@ import com.netscape.certsrv.request.IRequestListener;
import com.netscape.certsrv.request.IRequestQueue;
public class TKSAuthority implements IAuthority, ISubsystem {
- protected ILogger mLogger = CMS.getLogger();
- private String mNickname = null;
- private ISubsystem mOwner;
- private IConfigStore mConfig = null;
- protected String mId = null;
- public static final String PROP_NICKNAME = "nickName";
-
- /**
+ protected ILogger mLogger = CMS.getLogger();
+ private String mNickname = null;
+ private ISubsystem mOwner;
+ private IConfigStore mConfig = null;
+ protected String mId = null;
+ public static final String PROP_NICKNAME = "nickName";
+
+ /**
* Retrieves the request queue for the Authority.
* <P>
+ *
* @return the request queue.
*/
public IRequestQueue getRequestQueue() {
return null;
}
+
/**
* Registers request completed class.
*/
public void registerRequestListener(IRequestListener listener) {
}
- /**
+ /**
* Registers pending request class.
*/
public void registerPendingListener(IRequestListener listener) {
}
- /**
+
+ /**
* log interface
*/
- public void log(int level, String msg) {
+ public void log(int level, String msg) {
mLogger.log(ILogger.EV_SYSTEM, ILogger.S_TKS,
- level, msg);
+ level, msg);
}
- /**
+
+ /**
* nickname of signing (id) cert
*/
- public void setNickname( String nickname ) {
+ public void setNickname(String nickname) {
mNickname = nickname;
}
@@ -71,14 +75,15 @@ public class TKSAuthority implements IAuthority, ISubsystem {
CMS.debug("Error: TKSAuthority::getNickname - nickname of signing (id) cert");
return mNickname;
}
+
public String getOfficialName() {
return "tks";
}
-
- /**
+
+ /**
* Initializes this subsystem.
* <P>
- *
+ *
* @param owner owner of this subsystem
* @param config configuration of this subsystem
* @exception EBaseException failed to initialize this RA
@@ -88,14 +93,15 @@ public class TKSAuthority implements IAuthority, ISubsystem {
mOwner = owner;
mConfig = config;
- //mNickname = mConfig.getString(PROP_NICKNAME);
- CMS.debug("TKS Authority (" +
- getId() + "): " + "Initialized Request Processor.");
+ // mNickname = mConfig.getString(PROP_NICKNAME);
+ CMS.debug("TKS Authority (" +
+ getId() + "): " + "Initialized Request Processor.");
}
- /**
+
+ /**
* Notifies this subsystem if owner is in running mode.
- *
+ *
* @exception EBaseException failed to start up
*/
public void startup() throws EBaseException {
@@ -105,42 +111,46 @@ public class TKSAuthority implements IAuthority, ISubsystem {
// of a subsystem within server.
}
+
/**
- * Stops this system. The owner may call shutdown
- * anytime after initialization.
+ * Stops this system. The owner may call shutdown anytime after
+ * initialization.
* <P>
*/
- public void shutdown() {
+ public void shutdown() {
- getLogger().log(ILogger.EV_SYSTEM, ILogger.S_TKS,
- ILogger.LL_INFO, "TKSAuthority is stopped");
+ getLogger().log(ILogger.EV_SYSTEM, ILogger.S_TKS,
+ ILogger.LL_INFO, "TKSAuthority is stopped");
}
+
/**
* Returns the root configuration storage of this system.
* <P>
- *
+ *
* @return configuration store of this subsystem
*/
public IConfigStore getConfigStore() {
return mConfig;
}
+
public String getId() {
return mId;
}
- /**
+ /**
* Sets subsystem identifier.
- *
+ *
* @param id subsystem id
* @exception EBaseException failed to set id
*/
public void setId(String id) throws EBaseException {
mId = id;
}
- /**
+
+ /**
* Retrieves logger from escrow authority.
- *
+ *
* @return logger
*/
public ILogger getLogger() {
diff --git a/pki/base/util/src/com/netscape/cmsutil/crypto/CryptoUtil.java b/pki/base/util/src/com/netscape/cmsutil/crypto/CryptoUtil.java
index 29a1ffb3..b682190f 100644
--- a/pki/base/util/src/com/netscape/cmsutil/crypto/CryptoUtil.java
+++ b/pki/base/util/src/com/netscape/cmsutil/crypto/CryptoUtil.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.crypto;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.CharConversionException;
@@ -109,27 +108,27 @@ public class CryptoUtil {
/*
* encodes cert
*/
- // private static BASE64Encoder mEncoder = new BASE64Encoder();
+ // private static BASE64Encoder mEncoder = new BASE64Encoder();
public static String toMIME64(X509CertImpl cert) {
try {
- return
- "-----BEGIN CERTIFICATE-----\n"
- // + mEncoder.encodeBuffer(cert.getEncoded())
- + OSUtil.BtoA( cert.getEncoded() )
+ return "-----BEGIN CERTIFICATE-----\n"
+ // + mEncoder.encodeBuffer(cert.getEncoded())
+ + OSUtil.BtoA(cert.getEncoded())
+ "-----END CERTIFICATE-----\n";
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
return null;
}
-
+
public static boolean arraysEqual(byte[] bytes, byte[] ints) {
if (bytes == null || ints == null) {
return false;
}
-
+
if (bytes.length != ints.length) {
return false;
}
-
+
for (int i = 0; i < bytes.length; i++) {
if (bytes[i] != ints[i]) {
return false;
@@ -142,7 +141,7 @@ public class CryptoUtil {
* Retrieves handle to a JSS token.
*/
public static CryptoToken getTokenByName(String token)
- throws CryptoManager.NotInitializedException,
+ throws CryptoManager.NotInitializedException,
NoSuchTokenException {
CryptoManager cm = CryptoManager.getInstance();
CryptoToken t = null;
@@ -159,7 +158,7 @@ public class CryptoUtil {
* Generates a RSA key pair.
*/
public static KeyPair generateRSAKeyPair(String token, int keysize)
- throws CryptoManager.NotInitializedException,
+ throws CryptoManager.NotInitializedException,
NoSuchTokenException,
NoSuchAlgorithmException,
TokenException {
@@ -172,21 +171,20 @@ public class CryptoUtil {
return pair;
}
- public static boolean isECCKey(X509Key key)
- {
+ public static boolean isECCKey(X509Key key) {
String keyAlgo = key.getAlgorithm();
- if (keyAlgo.equals("EC") ||
+ if (keyAlgo.equals("EC") ||
keyAlgo.equals("OID.1.2.840.10045.44")) { // ECC
- return true;
- }
- return false;
+ return true;
+ }
+ return false;
}
/**
* Generates an ecc key pair.
*/
public static KeyPair generateECCKeyPair(String token, int keysize)
- throws CryptoManager.NotInitializedException,
+ throws CryptoManager.NotInitializedException,
NoSuchTokenException,
NoSuchAlgorithmException,
TokenException {
@@ -194,9 +192,9 @@ public class CryptoUtil {
}
public static KeyPair generateECCKeyPair(String token, int keysize,
- org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage[] usage_ops,
- org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage[] usage_mask)
- throws CryptoManager.NotInitializedException,
+ org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage[] usage_ops,
+ org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage[] usage_mask)
+ throws CryptoManager.NotInitializedException,
NoSuchTokenException,
NoSuchAlgorithmException,
TokenException {
@@ -217,7 +215,7 @@ public class CryptoUtil {
* Generates an ecc key pair by curve name
*/
public static KeyPair generateECCKeyPair(String token, String curveName)
- throws CryptoManager.NotInitializedException,
+ throws CryptoManager.NotInitializedException,
NoSuchTokenException,
NoSuchAlgorithmException,
TokenException {
@@ -225,7 +223,7 @@ public class CryptoUtil {
}
public static KeyPair generateECCKeyPair(CryptoToken token, String curveName)
- throws CryptoManager.NotInitializedException,
+ throws CryptoManager.NotInitializedException,
NoSuchTokenException,
NoSuchAlgorithmException,
TokenException {
@@ -233,9 +231,9 @@ public class CryptoUtil {
}
public static KeyPair generateECCKeyPair(String token, String curveName,
- org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage[] usage_ops,
- org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage[] usage_mask)
- throws CryptoManager.NotInitializedException,
+ org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage[] usage_ops,
+ org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage[] usage_mask)
+ throws CryptoManager.NotInitializedException,
NoSuchTokenException,
NoSuchAlgorithmException,
TokenException {
@@ -244,9 +242,9 @@ public class CryptoUtil {
}
public static KeyPair generateECCKeyPair(CryptoToken token, String curveName,
- org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage[] usage_ops,
- org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage[] usage_mask)
- throws CryptoManager.NotInitializedException,
+ org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage[] usage_ops,
+ org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage[] usage_mask)
+ throws CryptoManager.NotInitializedException,
NoSuchTokenException,
NoSuchAlgorithmException,
TokenException {
@@ -255,17 +253,17 @@ public class CryptoUtil {
g.setKeyPairUsages(usage_ops, usage_mask);
- System.out.println("CryptoUtil: generateECCKeyPair: curve = "+ curveName);
+ System.out.println("CryptoUtil: generateECCKeyPair: curve = " + curveName);
int curveCode = 0;
try {
curveCode = g.getCurveCodeByName(curveName);
} catch (Exception e) {
- System.out.println("CryptoUtil: generateECCKeyPair: "+ e.toString());
+ System.out.println("CryptoUtil: generateECCKeyPair: " + e.toString());
throw new NoSuchAlgorithmException();
}
g.initialize(curveCode);
- System.out.println("CryptoUtil: generateECCKeyPair: after KeyPairGenerator initialize with:"+ curveName);
+ System.out.println("CryptoUtil: generateECCKeyPair: after KeyPairGenerator initialize with:" + curveName);
KeyPair pair = g.genKeyPair();
return pair;
@@ -289,21 +287,21 @@ public class CryptoUtil {
ByteArrayOutputStream output = new ByteArrayOutputStream();
Base64OutputStream b64 = new Base64OutputStream(new
PrintStream(new
- FilterOutputStream(output)));
-
+ FilterOutputStream(output)));
+
b64.write(bytes);
b64.flush();
-
+
// This is internationally safe because Base64 chars are
// contained within 8859_1
return output.toString("8859_1");
}
-
+
public static byte[] base64Decode(String s) throws IOException {
- // BASE64Decoder base64 = new BASE64Decoder();
- // byte[] d = base64.decodeBuffer(s);
- byte[] d = OSUtil.AtoB( s );
-
+ // BASE64Decoder base64 = new BASE64Decoder();
+ // byte[] d = base64.decodeBuffer(s);
+ byte[] d = OSUtil.AtoB(s);
+
return d;
}
@@ -313,10 +311,10 @@ public class CryptoUtil {
public static String reqFormat(String content) {
int beginIndex = CERTREQ_BEGIN_HEADING.length();
int endIndex = CERTREQ_END_HEADING.length();
-
+
String result = CERTREQ_BEGIN_HEADING + "\n";
int index = 0;
-
+
while (content.length() >= LINE_COUNT) {
result = result + content.substring(0, LINE_COUNT) + "\n";
content = content.substring(LINE_COUNT);
@@ -326,11 +324,11 @@ public class CryptoUtil {
} else {
result = result + CERTREQ_END_HEADING;
}
-
+
return result;
}
-
- public static String getPKCS10FromKey(String dn,
+
+ public static String getPKCS10FromKey(String dn,
byte modulus[], byte exponent[], byte prikdata[])
throws IOException,
InvalidKeyException,
@@ -339,8 +337,7 @@ public class CryptoUtil {
CertificateException,
SignatureException,
CryptoManager.NotInitializedException,
- NoSuchAlgorithmException
- {
+ NoSuchAlgorithmException {
X509Key x509key = getPublicX509Key(modulus, exponent);
PrivateKey prik = findPrivateKeyFromID(prikdata);
PKCS10 pkcs10 = createCertificationRequest(dn, x509key, prik);
@@ -350,7 +347,7 @@ public class CryptoUtil {
return bs.toString();
}
- public static String getPKCS10FromKey(String dn,
+ public static String getPKCS10FromKey(String dn,
byte modulus[], byte exponent[], byte prikdata[], String alg)
throws IOException,
InvalidKeyException,
@@ -359,8 +356,7 @@ public class CryptoUtil {
CertificateException,
SignatureException,
CryptoManager.NotInitializedException,
- NoSuchAlgorithmException
- {
+ NoSuchAlgorithmException {
X509Key x509key = getPublicX509Key(modulus, exponent);
PrivateKey prik = findPrivateKeyFromID(prikdata);
PKCS10 pkcs10 = createCertificationRequest(dn, x509key, prik, alg);
@@ -379,10 +375,10 @@ public class CryptoUtil {
}
int beginIndex = CERT_BEGIN_HEADING.length();
int endIndex = CERT_END_HEADING.length();
-
+
String result = CERT_BEGIN_HEADING + "\n";
int index = 0;
-
+
while (content.length() >= LINE_COUNT) {
result = result + content.substring(0, LINE_COUNT) + "\n";
content = content.substring(LINE_COUNT);
@@ -392,31 +388,32 @@ public class CryptoUtil {
} else {
result = result + CERT_END_HEADING;
}
-
+
return result;
}
/**
* strips out the begin and end certificate brackets
+ *
* @param s the string potentially bracketed with
- * "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----"
+ * "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----"
* @return string without the brackets
*/
public static String stripCertBrackets(String s) {
if (s == null) {
return s;
}
-
+
if (s.startsWith(CERT_BEGIN_HEADING) && s.endsWith(CERT_END_HEADING)) {
return (s.substring(27, (s.length() - 25)));
}
-
+
// To support Thawte's header and footer
if ((s.startsWith("-----BEGIN PKCS #7 SIGNED DATA-----"))
&& (s.endsWith("-----END PKCS #7 SIGNED DATA-----"))) {
return (s.substring(35, (s.length() - 33)));
}
-
+
return s;
}
@@ -430,13 +427,13 @@ public class CryptoUtil {
s = s.replaceAll("-----END NEW CERTIFICATE REQUEST-----", "");
s = s.replaceAll("-----BEGIN CERTIFICATE-----", "");
s = s.replaceAll("-----END CERTIFICATE-----", "");
-
+
StringBuffer sb = new StringBuffer();
StringTokenizer st = new StringTokenizer(s, "\r\n ");
-
+
while (st.hasMoreTokens()) {
String nextLine = st.nextToken();
-
+
nextLine = nextLine.trim();
if (nextLine.equals("-----BEGIN CERTIFICATE REQUEST-----")) {
continue;
@@ -460,10 +457,10 @@ public class CryptoUtil {
}
return sb.toString();
}
-
+
public static String normalizeCertStr(String s) {
String val = "";
-
+
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '\n') {
continue;
@@ -484,61 +481,58 @@ public class CryptoUtil {
CryptoManager.NotInitializedException,
TokenException,
CertificateEncodingException,
- CertificateException
- {
+ CertificateException {
byte[] blah = base64Decode(certchain);
CryptoManager manager = CryptoManager.getInstance();
PKCS7 pkcs7 = null;
- try {
- // try PKCS7 first
- pkcs7 = new PKCS7(blah);
+ try {
+ // try PKCS7 first
+ pkcs7 = new PKCS7(blah);
} catch (Exception e) {
}
X509Certificate cert = null;
if (pkcs7 == null) {
- cert = manager.importCACertPackage(blah);
- } else {
- java.security.cert.X509Certificate certsInP7[] =
- pkcs7.getCertificates();
- if (certsInP7 == null) {
cert = manager.importCACertPackage(blah);
- } else {
- for (int i = 0; i < certsInP7.length; i++) {
- // import P7 one by one
- cert = manager.importCACertPackage(certsInP7[i].getEncoded());
+ } else {
+ java.security.cert.X509Certificate certsInP7[] =
+ pkcs7.getCertificates();
+ if (certsInP7 == null) {
+ cert = manager.importCACertPackage(blah);
+ } else {
+ for (int i = 0; i < certsInP7.length; i++) {
+ // import P7 one by one
+ cert = manager.importCACertPackage(certsInP7[i].getEncoded());
+ }
}
- }
}
- X509Certificate[] certchains =
- CryptoManager.getInstance().buildCertificateChain(cert);
-
+ X509Certificate[] certchains =
+ CryptoManager.getInstance().buildCertificateChain(cert);
+
if (certchains != null) {
- cert = certchains[certchains.length - 1];
+ cert = certchains[certchains.length - 1];
}
InternalCertificate icert = (InternalCertificate) cert;
- icert.setSSLTrust( InternalCertificate.TRUSTED_CA
+ icert.setSSLTrust(InternalCertificate.TRUSTED_CA
| InternalCertificate.TRUSTED_CLIENT_CA
| InternalCertificate.VALID_CA);
}
public static SEQUENCE parseCRMFMsgs(byte cert_request[])
- throws IOException, InvalidBERException
- {
- ByteArrayInputStream crmfBlobIn =
- new ByteArrayInputStream(cert_request);
+ throws IOException, InvalidBERException {
+ ByteArrayInputStream crmfBlobIn =
+ new ByteArrayInputStream(cert_request);
SEQUENCE crmfMsgs = (SEQUENCE)
- new SEQUENCE.OF_Template(new CertReqMsg.Template()).decode(
+ new SEQUENCE.OF_Template(new CertReqMsg.Template()).decode(
crmfBlobIn);
return crmfMsgs;
}
- public static X509Key getX509KeyFromCRMFMsgs(SEQUENCE crmfMsgs)
- throws IOException, NoSuchAlgorithmException,
- InvalidKeyException, InvalidKeyFormatException
- {
+ public static X509Key getX509KeyFromCRMFMsgs(SEQUENCE crmfMsgs)
+ throws IOException, NoSuchAlgorithmException,
+ InvalidKeyException, InvalidKeyFormatException {
int nummsgs = crmfMsgs.size();
if (nummsgs <= 0) {
- throw new IOException("invalid certificate requests");
+ throw new IOException("invalid certificate requests");
}
CertReqMsg msg = (CertReqMsg) crmfMsgs.elementAt(0);
CertRequest certreq = msg.getCertReq();
@@ -549,28 +543,28 @@ public class CryptoUtil {
return x509key;
}
- public static X509Key getPublicX509Key(byte modulus[], byte exponent[])
- throws InvalidKeyException {
+ public static X509Key getPublicX509Key(byte modulus[], byte exponent[])
+ throws InvalidKeyException {
return new netscape.security.provider.RSAPublicKey(new BigInt(modulus),
new BigInt(exponent));
}
public static X509Key getPublicX509ECCKey(byte encoded[])
- throws InvalidKeyException {
- try {
- return X509Key.parse(new DerValue(encoded));
- } catch (IOException e) {
- throw new InvalidKeyException();
- }
+ throws InvalidKeyException {
+ try {
+ return X509Key.parse(new DerValue(encoded));
+ } catch (IOException e) {
+ throw new InvalidKeyException();
+ }
}
public static X509Key convertPublicKeyToX509Key(PublicKey pubk)
- throws InvalidKeyException {
+ throws InvalidKeyException {
X509Key xKey;
-
+
if (pubk instanceof RSAPublicKey) {
RSAPublicKey rsaKey = (RSAPublicKey) pubk;
-
+
xKey = new netscape.security.provider.RSAPublicKey(
new BigInt(rsaKey.getModulus()),
new BigInt(rsaKey.getPublicExponent()));
@@ -578,18 +572,18 @@ public class CryptoUtil {
// Assert.assert(pubk instanceof DSAPublicKey);
DSAPublicKey dsaKey = (DSAPublicKey) pubk;
DSAParams params = dsaKey.getParams();
-
+
xKey = new netscape.security.provider.DSAPublicKey(dsaKey.getY(),
params.getP(), params.getQ(), params.getG());
}
return xKey;
}
- public static String getSubjectName(SEQUENCE crmfMsgs)
- throws IOException {
+ public static String getSubjectName(SEQUENCE crmfMsgs)
+ throws IOException {
int nummsgs = crmfMsgs.size();
if (nummsgs <= 0) {
- throw new IOException("invalid certificate requests");
+ throw new IOException("invalid certificate requests");
}
CertReqMsg msg = (CertReqMsg) crmfMsgs.elementAt(0);
CertRequest certreq = msg.getCertReq();
@@ -597,7 +591,7 @@ public class CryptoUtil {
Name n = certTemplate.getSubject();
ByteArrayOutputStream subjectEncStream = new ByteArrayOutputStream();
n.encode(subjectEncStream);
-
+
byte[] b = subjectEncStream.toByteArray();
X500Name subject = new X500Name(b);
return subject.toString();
@@ -607,46 +601,46 @@ public class CryptoUtil {
* Creates a Certificate template.
*/
public static X509CertInfo createX509CertInfo(KeyPair pair,
- int serialno, String issuername, String subjname,
+ int serialno, String issuername, String subjname,
Date notBefore, Date notAfter)
- throws IOException,
- CertificateException,
+ throws IOException,
+ CertificateException,
InvalidKeyException {
- return createX509CertInfo(convertPublicKeyToX509Key(pair.getPublic()),
+ return createX509CertInfo(convertPublicKeyToX509Key(pair.getPublic()),
serialno, issuername, subjname, notBefore, notAfter);
}
public static X509CertInfo createX509CertInfo(PublicKey publickey,
- int serialno, String issuername, String subjname,
+ int serialno, String issuername, String subjname,
Date notBefore, Date notAfter)
- throws IOException,
- CertificateException,
+ throws IOException,
+ CertificateException,
InvalidKeyException {
return createX509CertInfo(convertPublicKeyToX509Key(publickey), serialno,
issuername, subjname, notBefore, notAfter);
}
public static X509CertInfo createX509CertInfo(X509Key x509key,
- int serialno, String issuername, String subjname,
+ int serialno, String issuername, String subjname,
Date notBefore, Date notAfter)
- throws IOException,
- CertificateException,
+ throws IOException,
+ CertificateException,
InvalidKeyException {
// set default; use the other call with "alg" to set algorithm
String alg = "SHA256withRSA";
try {
- return createX509CertInfo (x509key, serialno, issuername, subjname, notBefore, notAfter, alg);
+ return createX509CertInfo(x509key, serialno, issuername, subjname, notBefore, notAfter, alg);
} catch (NoSuchAlgorithmException ex) {
- // for those that calls the old call without alg
- throw new CertificateException("createX509CertInfo old call should not be here");
+ // for those that calls the old call without alg
+ throw new CertificateException("createX509CertInfo old call should not be here");
}
}
public static X509CertInfo createX509CertInfo(X509Key x509key,
- int serialno, String issuername, String subjname,
+ int serialno, String issuername, String subjname,
Date notBefore, Date notAfter, String alg)
- throws IOException,
- CertificateException,
+ throws IOException,
+ CertificateException,
InvalidKeyException,
NoSuchAlgorithmException {
X509CertInfo info = new X509CertInfo();
@@ -668,10 +662,9 @@ public class CryptoUtil {
return info;
}
-
- public static X509CertImpl signECCCert(PrivateKey privateKey,
+ public static X509CertImpl signECCCert(PrivateKey privateKey,
X509CertInfo certInfo)
- throws NoSuchTokenException,
+ throws NoSuchTokenException,
CryptoManager.NotInitializedException,
NoSuchAlgorithmException,
NoSuchTokenException,
@@ -679,16 +672,15 @@ public class CryptoUtil {
InvalidKeyException,
SignatureException,
IOException,
- CertificateException
- {
+ CertificateException {
// set default; use the other call with "alg" to specify algorithm
String alg = "SHA256withEC";
return signECCCert(privateKey, certInfo, alg);
}
- public static X509CertImpl signECCCert(PrivateKey privateKey,
+ public static X509CertImpl signECCCert(PrivateKey privateKey,
X509CertInfo certInfo, String alg)
- throws NoSuchTokenException,
+ throws NoSuchTokenException,
CryptoManager.NotInitializedException,
NoSuchAlgorithmException,
NoSuchTokenException,
@@ -696,18 +688,17 @@ public class CryptoUtil {
InvalidKeyException,
SignatureException,
IOException,
- CertificateException
- {
- return signCert(privateKey, certInfo,
+ CertificateException {
+ return signCert(privateKey, certInfo,
Cert.mapAlgorithmToJss(alg));
}
/**
* Signs certificate.
*/
- public static X509CertImpl signCert(PrivateKey privateKey,
+ public static X509CertImpl signCert(PrivateKey privateKey,
X509CertInfo certInfo, String alg)
- throws NoSuchTokenException,
+ throws NoSuchTokenException,
CryptoManager.NotInitializedException,
NoSuchAlgorithmException,
NoSuchTokenException,
@@ -716,13 +707,13 @@ public class CryptoUtil {
SignatureException,
IOException,
CertificateException {
- return signCert (privateKey, certInfo,
+ return signCert(privateKey, certInfo,
Cert.mapAlgorithmToJss(alg));
}
- public static X509CertImpl signCert(PrivateKey privateKey,
+ public static X509CertImpl signCert(PrivateKey privateKey,
X509CertInfo certInfo, SignatureAlgorithm sigAlg)
- throws NoSuchTokenException,
+ throws NoSuchTokenException,
CryptoManager.NotInitializedException,
NoSuchAlgorithmException,
NoSuchTokenException,
@@ -735,28 +726,28 @@ public class CryptoUtil {
DerInputStream ds = new DerInputStream(ASN1Util.encode(sigAlg.toOID()));
ObjectIdentifier sigAlgOID = new ObjectIdentifier(ds);
AlgorithmId aid = new AlgorithmId(sigAlgOID);
- certInfo.set(X509CertInfo.ALGORITHM_ID,
- new CertificateAlgorithmId(aid));
-
- org.mozilla.jss.crypto.PrivateKey priKey =
- (org.mozilla.jss.crypto.PrivateKey) privateKey;
+ certInfo.set(X509CertInfo.ALGORITHM_ID,
+ new CertificateAlgorithmId(aid));
+
+ org.mozilla.jss.crypto.PrivateKey priKey =
+ (org.mozilla.jss.crypto.PrivateKey) privateKey;
CryptoToken token = priKey.getOwningToken();
-
+
DerOutputStream tmp = new DerOutputStream();
DerOutputStream out = new DerOutputStream();
-
+
certInfo.encode(tmp);
Signature signer = token.getSignatureContext(sigAlg);
-
+
signer.initSign(priKey);
signer.update(tmp.toByteArray());
byte signed[] = signer.sign();
-
+
aid.encode(tmp);
tmp.putBitString(signed);
out.write(DerValue.tag_Sequence, tmp);
X509CertImpl signedCert = new X509CertImpl(out.toByteArray());
-
+
return signedCert;
}
@@ -765,20 +756,20 @@ public class CryptoUtil {
*/
public static PKCS10 createCertificationRequest(String subjectName,
X509Key pubk, PrivateKey prik)
- throws NoSuchAlgorithmException, NoSuchProviderException,
+ throws NoSuchAlgorithmException, NoSuchProviderException,
InvalidKeyException, IOException, CertificateException,
SignatureException {
// give default
String alg = "SHA256withRSA";
if (isECCKey(pubk)) {
- alg = "SHA256withEC";
+ alg = "SHA256withEC";
}
return createCertificationRequest(subjectName, pubk, prik, alg);
}
public static PKCS10 createCertificationRequest(String subjectName,
X509Key pubk, PrivateKey prik, String alg)
- throws NoSuchAlgorithmException, NoSuchProviderException,
+ throws NoSuchAlgorithmException, NoSuchProviderException,
InvalidKeyException, IOException, CertificateException,
SignatureException {
X509Key key = pubk;
@@ -799,7 +790,7 @@ public class CryptoUtil {
*/
public static PKCS10 createCertificationRequest(String subjectName,
KeyPair keyPair)
- throws NoSuchAlgorithmException, NoSuchProviderException,
+ throws NoSuchAlgorithmException, NoSuchProviderException,
InvalidKeyException, IOException, CertificateException,
SignatureException {
String alg;
@@ -813,45 +804,45 @@ public class CryptoUtil {
// Assert.assert(pubk instanceof DSAPublicKey);
alg = "DSA";
}
- return createCertificationRequest(subjectName,keyPair, alg);
+ return createCertificationRequest(subjectName, keyPair, alg);
}
public static PKCS10 createCertificationRequest(String subjectName,
KeyPair keyPair, String alg)
- throws NoSuchAlgorithmException, NoSuchProviderException,
+ throws NoSuchAlgorithmException, NoSuchProviderException,
InvalidKeyException, IOException, CertificateException,
SignatureException {
PublicKey pubk = keyPair.getPublic();
X509Key key = convertPublicKeyToX509Key(pubk);
-
+
java.security.Signature sig = java.security.Signature.getInstance(alg,
"Mozilla-JSS");
-
+
sig.initSign(keyPair.getPrivate());
-
+
PKCS10 pkcs10 = new PKCS10(key);
-
+
X500Name name = new X500Name(subjectName);
X500Signer signer = new X500Signer(sig, name);
-
+
pkcs10.encodeAndSign(signer);
-
+
return pkcs10;
}
public static void unTrustCert(InternalCertificate cert) {
// remove TRUSTED_CA
int flag = cert.getSSLTrust();
-
+
flag ^= InternalCertificate.VALID_CA;
cert.setSSLTrust(flag);
}
-
+
/**
* Trusts a certificate by nickname.
*/
- public static void trustCertByNickname(String nickname)
- throws CryptoManager.NotInitializedException,
+ public static void trustCertByNickname(String nickname)
+ throws CryptoManager.NotInitializedException,
TokenException {
CryptoManager cm = CryptoManager.getInstance();
X509Certificate certs[] = cm.findCertsByNickname(nickname);
@@ -871,15 +862,14 @@ public class CryptoUtil {
int flag = InternalCertificate.VALID_CA | InternalCertificate.TRUSTED_CA
| InternalCertificate.USER
| InternalCertificate.TRUSTED_CLIENT_CA;
-
+
cert.setSSLTrust(flag);
cert.setObjectSigningTrust(flag);
cert.setEmailTrust(flag);
}
-
+
/**
- * To certificate server point of view, SSL trust is
- * what we referring.
+ * To certificate server point of view, SSL trust is what we referring.
*/
public static boolean isCertTrusted(InternalCertificate cert) {
if (isTrust(cert.getSSLTrust()) && isTrust(cert.getObjectSigningTrust())
@@ -889,7 +879,7 @@ public class CryptoUtil {
return false;
}
}
-
+
public static boolean isTrust(int flag) {
if (((flag & InternalCertificate.VALID_CA) > 0)
&& ((flag & InternalCertificate.TRUSTED_CA) > 0)
@@ -906,11 +896,11 @@ public class CryptoUtil {
*/
public static SymmetricKey generateKey(CryptoToken token,
KeyGenAlgorithm alg)
- throws TokenException, NoSuchAlgorithmException,
+ throws TokenException, NoSuchAlgorithmException,
IllegalStateException {
try {
KeyGenerator kg = token.getKeyGenerator(alg);
-
+
return kg.generate();
} catch (CharConversionException e) {
throw new RuntimeException(
@@ -950,18 +940,18 @@ public class CryptoUtil {
/**
* Retrieves a private key from a unique key ID.
*/
- public static PrivateKey findPrivateKeyFromID(byte id[])
- throws CryptoManager.NotInitializedException,
+ public static PrivateKey findPrivateKeyFromID(byte id[])
+ throws CryptoManager.NotInitializedException,
TokenException {
CryptoManager cm = CryptoManager.getInstance();
@SuppressWarnings("unchecked")
- Enumeration<CryptoToken> enums = cm.getAllTokens();
+ Enumeration<CryptoToken> enums = cm.getAllTokens();
while (enums.hasMoreElements()) {
- CryptoToken token = enums.nextElement();
+ CryptoToken token = enums.nextElement();
String tokenName = token.getName();
CryptoStore store = token.getCryptoStore();
- PrivateKey keys[] = store.getPrivateKeys();
+ PrivateKey keys[] = store.getPrivateKeys();
if (keys != null) {
for (int i = 0; i < keys.length; i++) {
@@ -978,20 +968,20 @@ public class CryptoUtil {
* Retrieves all user certificates from all tokens.
*/
public static X509CertImpl[] getAllUserCerts()
- throws CryptoManager.NotInitializedException,
+ throws CryptoManager.NotInitializedException,
TokenException {
Vector<X509CertImpl> certs = new Vector<X509CertImpl>();
CryptoManager cm = CryptoManager.getInstance();
@SuppressWarnings("unchecked")
- Enumeration<CryptoToken> enums = cm.getAllTokens();
+ Enumeration<CryptoToken> enums = cm.getAllTokens();
while (enums.hasMoreElements()) {
CryptoToken token = (CryptoToken) enums.nextElement();
String tokenName = token.getName();
-
+
CryptoStore store = token.getCryptoStore();
org.mozilla.jss.crypto.X509Certificate list[] = store.getCertificates();
-
+
for (int i = 0; i < list.length; i++) {
try {
PrivateKey key = cm.findPrivKeyByCert(list[i]);
@@ -1024,7 +1014,7 @@ public class CryptoUtil {
* Deletes a private key.
*/
public static void deletePrivateKey(PrivateKey prikey)
- throws CryptoManager.NotInitializedException, TokenException {
+ throws CryptoManager.NotInitializedException, TokenException {
CryptoManager cm = CryptoManager.getInstance();
try {
@@ -1032,21 +1022,23 @@ public class CryptoUtil {
CryptoStore store = token.getCryptoStore();
store.deletePrivateKey(prikey);
- } catch (NoSuchItemOnTokenException e) {}
+ } catch (NoSuchItemOnTokenException e) {
+ }
}
/**
* Retrieves a private key by nickname.
*/
public static PrivateKey getPrivateKey(String nickname)
- throws CryptoManager.NotInitializedException, TokenException {
+ throws CryptoManager.NotInitializedException, TokenException {
try {
CryptoManager cm = CryptoManager.getInstance();
X509Certificate cert = cm.findCertByNickname(nickname);
org.mozilla.jss.crypto.PrivateKey prikey = cm.findPrivKeyByCert(cert);
return prikey;
- } catch (ObjectNotFoundException e) {}
+ } catch (ObjectNotFoundException e) {
+ }
return null;
}
@@ -1054,7 +1046,7 @@ public class CryptoUtil {
* Deletes all certificates by a nickname.
*/
public static void deleteAllCertificates(String nickname)
- throws CryptoManager.NotInitializedException, TokenException {
+ throws CryptoManager.NotInitializedException, TokenException {
CryptoManager cm = CryptoManager.getInstance();
X509Certificate certs[] = cm.findCertsByNickname(nickname);
@@ -1070,18 +1062,20 @@ public class CryptoUtil {
CryptoStore store = token.getCryptoStore();
store.deleteCert(cert);
- } catch (NoSuchItemOnTokenException e) {} catch (ObjectNotFoundException e) {}
+ } catch (NoSuchItemOnTokenException e) {
+ } catch (ObjectNotFoundException e) {
+ }
}
}
/**
- * Imports a PKCS#7 certificate chain that includes the user
- * certificate, and trusts the certificate.
+ * Imports a PKCS#7 certificate chain that includes the user certificate,
+ * and trusts the certificate.
*/
- public static X509Certificate importUserCertificateChain(String c,
+ public static X509Certificate importUserCertificateChain(String c,
String nickname)
- throws CryptoManager.NotInitializedException,
- CryptoManager.NicknameConflictException,
+ throws CryptoManager.NotInitializedException,
+ CryptoManager.NicknameConflictException,
CryptoManager.UserCertConflictException,
NoSuchItemOnTokenException,
TokenException,
@@ -1097,7 +1091,7 @@ public class CryptoUtil {
* Imports a user certificate, and trusts the certificate.
*/
public static void importUserCertificate(X509CertImpl cert, String nickname)
- throws CryptoManager.NotInitializedException,
+ throws CryptoManager.NotInitializedException,
CertificateEncodingException,
NoSuchItemOnTokenException,
TokenException,
@@ -1110,8 +1104,8 @@ public class CryptoUtil {
}
public static void importUserCertificate(X509CertImpl cert, String nickname,
- boolean trust)
- throws CryptoManager.NotInitializedException,
+ boolean trust)
+ throws CryptoManager.NotInitializedException,
CertificateEncodingException,
NoSuchItemOnTokenException,
TokenException,
@@ -1129,34 +1123,31 @@ public class CryptoUtil {
CertificateChain certchain = new CertificateChain();
certchain.decode(bis);
- java.security.cert.X509Certificate[] certs = certchain.getChain();
+ java.security.cert.X509Certificate[] certs = certchain.getChain();
return certs;
}
}
// START ENABLE_ECC
-// This following can be removed when JSS with ECC capability
+// This following can be removed when JSS with ECC capability
// is integrated.
-class CryptoAlgorithm extends Algorithm
-{
+class CryptoAlgorithm extends Algorithm {
protected CryptoAlgorithm(int oidIndex, String name) {
super(oidIndex, name);
}
}
-class CryptoKeyPairAlgorithm extends KeyPairAlgorithm
-{
- protected CryptoKeyPairAlgorithm(int oidIndex, String name, Algorithm algFamily) { super(oidIndex, name, algFamily);
+class CryptoKeyPairAlgorithm extends KeyPairAlgorithm {
+ protected CryptoKeyPairAlgorithm(int oidIndex, String name, Algorithm algFamily) {
+ super(oidIndex, name, algFamily);
}
}
-class CryptoSignatureAlgorithm extends SignatureAlgorithm
-{
+class CryptoSignatureAlgorithm extends SignatureAlgorithm {
protected CryptoSignatureAlgorithm(int oidIndex, String name,
- SignatureAlgorithm signingAlg, DigestAlgorithm digestAlg,
- OBJECT_IDENTIFIER oid)
- {
+ SignatureAlgorithm signingAlg, DigestAlgorithm digestAlg,
+ OBJECT_IDENTIFIER oid) {
super(oidIndex, name, signingAlg, digestAlg, oid);
}
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/crypto/Module.java b/pki/base/util/src/com/netscape/cmsutil/crypto/Module.java
index e7971ea7..16f948fd 100644
--- a/pki/base/util/src/com/netscape/cmsutil/crypto/Module.java
+++ b/pki/base/util/src/com/netscape/cmsutil/crypto/Module.java
@@ -31,34 +31,34 @@ public class Module {
private Vector mTokens = null;
private boolean mFound = false;
- public Module (String name, String printName) {
- mCommonName = name;
- mUserFriendlyName = printName;
- mTokens = new Vector();
+ public Module(String name, String printName) {
+ mCommonName = name;
+ mUserFriendlyName = printName;
+ mTokens = new Vector();
}
- public Module (String name, String printName, String image) {
- mCommonName = name;
- mUserFriendlyName = printName;
- mImagePath = image;
- mTokens = new Vector();
+ public Module(String name, String printName, String image) {
+ mCommonName = name;
+ mUserFriendlyName = printName;
+ mImagePath = image;
+ mTokens = new Vector();
}
public void addToken(CryptoToken t) {
- Token token = new Token(t);
- mTokens.addElement(token);
+ Token token = new Token(t);
+ mTokens.addElement(token);
}
public String getCommonName() {
- return mCommonName;
+ return mCommonName;
}
public String getUserFriendlyName() {
- return mUserFriendlyName;
+ return mUserFriendlyName;
}
public String getImagePath() {
- return mImagePath;
+ return mImagePath;
}
public boolean isFound() {
@@ -70,6 +70,6 @@ public class Module {
}
public Vector getTokens() {
- return mTokens;
+ return mTokens;
}
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/crypto/Token.java b/pki/base/util/src/com/netscape/cmsutil/crypto/Token.java
index f86e49bd..c6f5a5e3 100644
--- a/pki/base/util/src/com/netscape/cmsutil/crypto/Token.java
+++ b/pki/base/util/src/com/netscape/cmsutil/crypto/Token.java
@@ -22,36 +22,36 @@ import org.mozilla.jss.crypto.CryptoToken;
public class Token {
CryptoToken mToken;
- public Token (CryptoToken token) {
- mToken = token;
+ public Token(CryptoToken token) {
+ mToken = token;
}
public String getNickName() {
- String nickName="";
+ String nickName = "";
try {
- nickName = mToken.getName();
+ nickName = mToken.getName();
} catch (Exception e) {
}
- return nickName;
+ return nickName;
}
public boolean isLoggedIn() {
boolean isLoggedIn = false;
try {
- isLoggedIn = mToken.isLoggedIn();
+ isLoggedIn = mToken.isLoggedIn();
} catch (Exception e) {
}
- return isLoggedIn;
+ return isLoggedIn;
}
public boolean isPresent() {
boolean isPresent = false;
try {
- isPresent = mToken.isPresent();
+ isPresent = mToken.isPresent();
} catch (Exception e) {
}
- return isPresent;
+ return isPresent;
}
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/http/ConnectAsync.java b/pki/base/util/src/com/netscape/cmsutil/http/ConnectAsync.java
index 8922f38d..ca230ca2 100644
--- a/pki/base/util/src/com/netscape/cmsutil/http/ConnectAsync.java
+++ b/pki/base/util/src/com/netscape/cmsutil/http/ConnectAsync.java
@@ -17,12 +17,10 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.http;
-
import java.net.SocketException;
import com.netscape.cmsutil.net.ISocketFactory;
-
public class ConnectAsync extends Thread {
String host = null;
int port = 0;
@@ -33,9 +31,9 @@ public class ConnectAsync extends Thread {
this.host = host;
this.port = port;
this.obj = sock;
- setName("ConnectAsync");
+ setName("ConnectAsync");
}
-
+
public void run() {
try {
obj.makeSocket(host, port);
@@ -46,4 +44,3 @@ public class ConnectAsync extends Thread {
}
}
}
-
diff --git a/pki/base/util/src/com/netscape/cmsutil/http/Http.java b/pki/base/util/src/com/netscape/cmsutil/http/Http.java
index acece15d..2cda7fd1 100644
--- a/pki/base/util/src/com/netscape/cmsutil/http/Http.java
+++ b/pki/base/util/src/com/netscape/cmsutil/http/Http.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.http;
-
public class Http {
public static final String HttpVers = "HTTP/1.0";
diff --git a/pki/base/util/src/com/netscape/cmsutil/http/HttpClient.java b/pki/base/util/src/com/netscape/cmsutil/http/HttpClient.java
index 130d747d..84094ebc 100644
--- a/pki/base/util/src/com/netscape/cmsutil/http/HttpClient.java
+++ b/pki/base/util/src/com/netscape/cmsutil/http/HttpClient.java
@@ -30,9 +30,8 @@ import org.mozilla.jss.ssl.SSLCertificateApprovalCallback;
import com.netscape.cmsutil.net.ISocketFactory;
/**
- * basic http client.
- * not optimized for performance.
- * handles only string content.
+ * basic http client. not optimized for performance. handles only string
+ * content.
*/
public class HttpClient {
protected ISocketFactory mFactory = null;
@@ -60,7 +59,7 @@ public class HttpClient {
}
public void connect(String host, int port)
- throws IOException {
+ throws IOException {
if (mFactory != null) {
if (mCertApprovalCallback == null) {
mSocket = mFactory.makeSocket(host, port);
@@ -76,7 +75,7 @@ public class HttpClient {
throw e;
}
-
+
mInputStream = mSocket.getInputStream();
mOutputStream = mSocket.getOutputStream();
mInputStreamReader = new InputStreamReader(mInputStream, "UTF8");
@@ -87,7 +86,7 @@ public class HttpClient {
// Inserted by beomsuk
public void connect(String host, int port, int timeout)
- throws IOException {
+ throws IOException {
if (mFactory != null) {
mSocket = mFactory.makeSocket(host, port, timeout);
} else {
@@ -99,7 +98,7 @@ public class HttpClient {
throw e;
}
-
+
mInputStream = mSocket.getInputStream();
mOutputStream = mSocket.getOutputStream();
mInputStreamReader = new InputStreamReader(mInputStream, "UTF8");
@@ -114,14 +113,12 @@ public class HttpClient {
}
/**
- * Sends a request to http server.
- * Returns a http response.
+ * Sends a request to http server. Returns a http response.
*/
- public HttpResponse send(HttpRequest request)
- throws IOException {
+ public HttpResponse send(HttpRequest request)
+ throws IOException {
HttpResponse resp = new HttpResponse();
-
if (mOutputStream == null)
throw new IOException("Output stream not initialized");
request.write(mOutputStreamWriter);
@@ -137,7 +134,7 @@ public class HttpClient {
}
public void disconnect()
- throws IOException {
+ throws IOException {
mSocket.close();
mInputStream = null;
mOutputStream = null;
@@ -172,7 +169,7 @@ public class HttpClient {
* unit test
*/
public static void main(String args[])
- throws Exception {
+ throws Exception {
HttpClient c = new HttpClient();
HttpRequest req = new HttpRequest();
HttpResponse resp = null;
@@ -182,7 +179,7 @@ public class HttpClient {
req.setMethod("GET");
req.setURI(args[2]);
- if (args.length >= 4)
+ if (args.length >= 4)
req.setHeader("Connection", args[3]);
resp = c.send(req);
@@ -191,29 +188,30 @@ public class HttpClient {
System.out.println("reason " + resp.getReasonPhrase());
System.out.println("content " + resp.getContent());
- //String lenstr = resp.getHeader("Content-Length");
- //System.out.println("content len is "+lenstr);
- //int length = Integer.parseInt(lenstr);
- //char[] content = new char[length];
- //c.mBufferedReader.read(content, 0, content.length);
- //System.out.println(content);
+ // String lenstr = resp.getHeader("Content-Length");
+ // System.out.println("content len is "+lenstr);
+ // int length = Integer.parseInt(lenstr);
+ // char[] content = new char[length];
+ // c.mBufferedReader.read(content, 0, content.length);
+ // System.out.println(content);
if (args.length >= 4 && args[3].equalsIgnoreCase("keep-alive")) {
int len;
char[] msgbody;
for (int i = 0; i < 2; i++) {
- if (i == 1) req.setHeader("Connection", "Close");
+ if (i == 1)
+ req.setHeader("Connection", "Close");
resp = c.send(req);
System.out.println("version " + resp.getHttpVers());
System.out.println("status code " + resp.getStatusCode());
System.out.println("reason " + resp.getReasonPhrase());
System.out.println("content " + resp.getContent());
- //len = Integer.parseInt(resp.getHeader("Content-Length"));
- //System.out.println("content len is "+len);
- //msgbody = new char[len];
- //c.mBufferedReader.read(msgbody, 0, len);
- //System.out.println(content);
+ // len = Integer.parseInt(resp.getHeader("Content-Length"));
+ // System.out.println("content len is "+len);
+ // msgbody = new char[len];
+ // c.mBufferedReader.read(msgbody, 0, len);
+ // System.out.println(content);
}
}
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/http/HttpEofException.java b/pki/base/util/src/com/netscape/cmsutil/http/HttpEofException.java
index e5573612..824b9ea2 100644
--- a/pki/base/util/src/com/netscape/cmsutil/http/HttpEofException.java
+++ b/pki/base/util/src/com/netscape/cmsutil/http/HttpEofException.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.http;
-
import java.io.IOException;
-
public class HttpEofException extends IOException {
/**
*
diff --git a/pki/base/util/src/com/netscape/cmsutil/http/HttpMessage.java b/pki/base/util/src/com/netscape/cmsutil/http/HttpMessage.java
index 93eeef68..741f45f2 100644
--- a/pki/base/util/src/com/netscape/cmsutil/http/HttpMessage.java
+++ b/pki/base/util/src/com/netscape/cmsutil/http/HttpMessage.java
@@ -17,21 +17,18 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.http;
-
import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Enumeration;
import java.util.Hashtable;
-
/**
- * Basic HTTP Message, excluding message body.
- * Not optimized for performance.
+ * Basic HTTP Message, excluding message body. Not optimized for performance.
* Set fields or parse from input.
*/
public class HttpMessage {
- protected String mLine = null; // request or response line.
+ protected String mLine = null; // request or response line.
protected Hashtable mHeaders = null;
protected String mContent = null; // arbitrary content chars assumed.
@@ -42,14 +39,14 @@ public class HttpMessage {
mHeaders = new Hashtable();
}
- /**
+ /**
* Set a header field. <br>
* Content-length is automatically set on write.<br>
- * If value spans multiple lines must be in proper http format for
- * multiple lines.
+ * If value spans multiple lines must be in proper http format for multiple
+ * lines.
*/
public void setHeader(String name, String value) {
- if (mHeaders == null)
+ if (mHeaders == null)
mHeaders = new Hashtable();
mHeaders.put(name.toLowerCase(), value);
}
@@ -62,11 +59,10 @@ public class HttpMessage {
}
/**
- * write http headers
- * does not support values of more than one line
+ * write http headers does not support values of more than one line
*/
public void writeHeaders(OutputStreamWriter writer)
- throws IOException {
+ throws IOException {
if (mHeaders != null) {
Enumeration keys = mHeaders.keys();
String header, value;
@@ -81,11 +77,11 @@ public class HttpMessage {
}
/**
- * read http headers.
- * does not support values of more than one line or multivalue headers.
+ * read http headers. does not support values of more than one line or
+ * multivalue headers.
*/
public void readHeaders(BufferedReader reader)
- throws IOException {
+ throws IOException {
mHeaders = new Hashtable();
int colon;
@@ -93,7 +89,7 @@ public class HttpMessage {
while (true) {
line = reader.readLine();
- if (line == null || line.equals(""))
+ if (line == null || line.equals(""))
break;
colon = line.indexOf(':');
if (colon == -1) {
@@ -107,7 +103,7 @@ public class HttpMessage {
}
public void write(OutputStreamWriter writer)
- throws IOException {
+ throws IOException {
writer.write(mLine + Http.CRLF);
writeHeaders(writer);
writer.flush();
@@ -118,12 +114,12 @@ public class HttpMessage {
}
public void parse(BufferedReader reader)
- throws IOException {
+ throws IOException {
String line = reader.readLine();
-// if (line == null) {
- // throw new HttpEofException("End of stream reached");
- // }
+ // if (line == null) {
+ // throw new HttpEofException("End of stream reached");
+ // }
if (line.equals("")) {
throw new HttpProtocolException("Bad Http req/resp line " + line);
}
@@ -143,7 +139,7 @@ public class HttpMessage {
done = reader.read(cbuf, total, len - total);
total += done;
}
-
+
mContent = new String(cbuf);
}
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/http/HttpProtocolException.java b/pki/base/util/src/com/netscape/cmsutil/http/HttpProtocolException.java
index 6b2fc75f..b5ceb1d7 100644
--- a/pki/base/util/src/com/netscape/cmsutil/http/HttpProtocolException.java
+++ b/pki/base/util/src/com/netscape/cmsutil/http/HttpProtocolException.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.http;
-
import java.io.IOException;
-
public class HttpProtocolException extends IOException {
/**
*
diff --git a/pki/base/util/src/com/netscape/cmsutil/http/HttpRequest.java b/pki/base/util/src/com/netscape/cmsutil/http/HttpRequest.java
index 76232a2d..0e635260 100644
--- a/pki/base/util/src/com/netscape/cmsutil/http/HttpRequest.java
+++ b/pki/base/util/src/com/netscape/cmsutil/http/HttpRequest.java
@@ -17,16 +17,13 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.http;
-
import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
-
/**
- * Basic HTTP Request. not optimized for performance.
- * Set fields or parse from input.
- * Handles text content.
+ * Basic HTTP Request. not optimized for performance. Set fields or parse from
+ * input. Handles text content.
*/
public class HttpRequest extends HttpMessage {
public static final String GET = "GET";
@@ -48,9 +45,9 @@ public class HttpRequest extends HttpMessage {
* set set request method.
*/
public void setMethod(String method)
- throws HttpProtocolException {
- if (!method.equals(GET) && !method.equals(HEAD) &&
- !method.equals(POST))
+ throws HttpProtocolException {
+ if (!method.equals(GET) && !method.equals(HEAD) &&
+ !method.equals(POST))
throw new HttpProtocolException("No such method " + method);
mMethod = method;
}
@@ -66,12 +63,12 @@ public class HttpRequest extends HttpMessage {
* write request to the http client
*/
public void write(OutputStreamWriter writer)
- throws IOException {
+ throws IOException {
if (mMethod == null || mURI == null) {
HttpProtocolException e = new HttpProtocolException(
"Http request method or uri not initialized");
- //e.printStackTrace();
+ // e.printStackTrace();
throw e;
}
@@ -83,17 +80,17 @@ public class HttpRequest extends HttpMessage {
* parse a http request from a http client
*/
public void parse(BufferedReader reader)
- throws IOException {
+ throws IOException {
super.parse(reader);
int method = mLine.indexOf(Http.SP);
mMethod = mLine.substring(0, method);
- if (!mMethod.equals(GET) && !mMethod.equals(POST) &&
- !mMethod.equals(HEAD)) {
+ if (!mMethod.equals(GET) && !mMethod.equals(POST) &&
+ !mMethod.equals(HEAD)) {
reset();
throw new HttpProtocolException("Bad Http request method");
- }
+ }
int uri = mLine.lastIndexOf(Http.SP);
@@ -101,8 +98,8 @@ public class HttpRequest extends HttpMessage {
mHttpVers = mLine.substring(uri + 1);
if (!mHttpVers.equals("")) {
- if (!mHttpVers.equals(Http.Vers1_0) &&
- !mHttpVers.equals(Http.Vers1_1)) {
+ if (!mHttpVers.equals(Http.Vers1_0) &&
+ !mHttpVers.equals(Http.Vers1_1)) {
reset();
throw new HttpProtocolException("Bad Http version in request");
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/http/HttpResponse.java b/pki/base/util/src/com/netscape/cmsutil/http/HttpResponse.java
index 09d8e562..a0e2c36b 100644
--- a/pki/base/util/src/com/netscape/cmsutil/http/HttpResponse.java
+++ b/pki/base/util/src/com/netscape/cmsutil/http/HttpResponse.java
@@ -17,16 +17,13 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.http;
-
import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
-
/**
- * Basic HTTP Response.
- * Set fields or parse from input.
- * Handles only text content.
+ * Basic HTTP Response. Set fields or parse from input. Handles only text
+ * content.
*/
public class HttpResponse extends HttpMessage {
protected String mStatusCode = null;
@@ -72,11 +69,11 @@ public class HttpResponse extends HttpMessage {
* write the response out to the http client
*/
public void write(OutputStreamWriter writer)
- throws IOException {
+ throws IOException {
if (mStatusCode == null) {
throw new HttpProtocolException("status code not set in response");
}
- // write status-line
+ // write status-line
mLine = Http.HttpVers + " " + mStatusCode + " ";
if (mReasonPhrase != null)
mLine += mReasonPhrase;
@@ -88,7 +85,7 @@ public class HttpResponse extends HttpMessage {
* parse a http response from a http server
*/
public void parse(BufferedReader reader)
- throws IOException {
+ throws IOException {
mHttpVers = null;
mStatusCode = null;
mReasonPhrase = null;
@@ -102,8 +99,8 @@ public class HttpResponse extends HttpMessage {
throw new HttpProtocolException("no Http version in response");
}
mHttpVers = mLine.substring(0, httpvers);
- if (!mHttpVers.equals(Http.Vers1_0) &&
- !mHttpVers.equals(Http.Vers1_1)) {
+ if (!mHttpVers.equals(Http.Vers1_0) &&
+ !mHttpVers.equals(Http.Vers1_1)) {
reset();
throw new HttpProtocolException("Bad Http version in response");
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/http/JssSSLSocketFactory.java b/pki/base/util/src/com/netscape/cmsutil/http/JssSSLSocketFactory.java
index 501886b5..3ed1f827 100644
--- a/pki/base/util/src/com/netscape/cmsutil/http/JssSSLSocketFactory.java
+++ b/pki/base/util/src/com/netscape/cmsutil/http/JssSSLSocketFactory.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.http;
-
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
@@ -35,12 +34,12 @@ import com.netscape.cmsutil.net.ISocketFactory;
/**
* Uses NSS ssl socket.
- *
+ *
* @version $Revision$ $Date$
*/
public class JssSSLSocketFactory implements ISocketFactory {
private String mClientAuthCertNickname = null;
- private SSLSocket s = null;
+ private SSLSocket s = null;
public JssSSLSocketFactory() {
}
@@ -62,66 +61,64 @@ public class JssSSLSocketFactory implements ISocketFactory {
SSLSocket.TLS_RSA_WITH_AES_256_CBC_SHA,
SSLSocket.TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,
SSLSocket.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
- //SSLSocket.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
- //SSLSocket.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
- //SSLSocket.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
+ // SSLSocket.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
+ // SSLSocket.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
+ // SSLSocket.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
SSLSocket.TLS_DHE_DSS_WITH_AES_128_CBC_SHA,
SSLSocket.TLS_DHE_DSS_WITH_AES_256_CBC_SHA,
SSLSocket.TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
SSLSocket.TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
0
};
-
+
static {
int i;
- for (i = SSLSocket.SSL2_RC4_128_WITH_MD5;
- i <= SSLSocket.SSL2_RC2_128_CBC_EXPORT40_WITH_MD5; ++i) {
+ for (i = SSLSocket.SSL2_RC4_128_WITH_MD5; i <= SSLSocket.SSL2_RC2_128_CBC_EXPORT40_WITH_MD5; ++i) {
try {
SSLSocket.setCipherPreferenceDefault(i, false);
- } catch( SocketException e) {
+ } catch (SocketException e) {
}
}
- //skip SSL_EN_IDEA_128_EDE3_CBC_WITH_MD5
- for (i = SSLSocket.SSL2_DES_64_CBC_WITH_MD5;
- i <= SSLSocket.SSL2_DES_192_EDE3_CBC_WITH_MD5; ++i) {
+ // skip SSL_EN_IDEA_128_EDE3_CBC_WITH_MD5
+ for (i = SSLSocket.SSL2_DES_64_CBC_WITH_MD5; i <= SSLSocket.SSL2_DES_192_EDE3_CBC_WITH_MD5; ++i) {
try {
SSLSocket.setCipherPreferenceDefault(i, false);
- } catch( SocketException e) {
+ } catch (SocketException e) {
}
}
for (i = 0; cipherSuites[i] != 0; ++i) {
try {
SSLSocket.setCipherPreferenceDefault(cipherSuites[i], true);
- } catch( SocketException e) {
+ } catch (SocketException e) {
}
}
}
- public Socket makeSocket(String host, int port)
- throws IOException, UnknownHostException {
+ public Socket makeSocket(String host, int port)
+ throws IOException, UnknownHostException {
return makeSocket(host, port, null, null);
}
- public Socket makeSocket(String host, int port,
- SSLCertificateApprovalCallback certApprovalCallback,
- SSLClientCertificateSelectionCallback clientCertCallback)
- throws IOException, UnknownHostException {
+ public Socket makeSocket(String host, int port,
+ SSLCertificateApprovalCallback certApprovalCallback,
+ SSLClientCertificateSelectionCallback clientCertCallback)
+ throws IOException, UnknownHostException {
try {
s = new SSLSocket(host, port, null, 0, certApprovalCallback,
- clientCertCallback);
+ clientCertCallback);
for (int i = 0; cipherSuites[i] != 0; ++i) {
try {
SSLSocket.setCipherPreferenceDefault(cipherSuites[i], true);
- } catch( SocketException e) {
+ } catch (SocketException e) {
}
}
s.setUseClientMode(true);
s.enableSSL2(false);
- //TODO Do we rally want to set the default each time?
+ // TODO Do we rally want to set the default each time?
SSLSocket.enableSSL2Default(false);
s.enableV2CompatibleHello(false);
@@ -154,8 +151,8 @@ public class JssSSLSocketFactory implements ISocketFactory {
return s;
}
- public Socket makeSocket(String host, int port, int timeout)
- throws IOException, UnknownHostException {
+ public Socket makeSocket(String host, int port, int timeout)
+ throws IOException, UnknownHostException {
Thread t = new ConnectAsync(this, host, port);
t.start();
@@ -163,7 +160,7 @@ public class JssSSLSocketFactory implements ISocketFactory {
t.join(1000 * timeout);
} catch (InterruptedException e) {
}
-
+
if (t.isAlive()) {
}
@@ -179,9 +176,8 @@ public class JssSSLSocketFactory implements ISocketFactory {
public ClientHandshakeCB(Object sc) {
this.sc = sc;
}
-
+
public void handshakeCompleted(SSLHandshakeCompletedEvent event) {
}
}
}
-
diff --git a/pki/base/util/src/com/netscape/cmsutil/ldap/LDAPUtil.java b/pki/base/util/src/com/netscape/cmsutil/ldap/LDAPUtil.java
index eaae0007..132e65e6 100644
--- a/pki/base/util/src/com/netscape/cmsutil/ldap/LDAPUtil.java
+++ b/pki/base/util/src/com/netscape/cmsutil/ldap/LDAPUtil.java
@@ -44,18 +44,18 @@ public class LDAPUtil {
LDIFContent content = record.getContent();
int type = content.getType();
if (type == LDIFContent.ATTRIBUTE_CONTENT) {
- LDIFAttributeContent c = (LDIFAttributeContent)content;
+ LDIFAttributeContent c = (LDIFAttributeContent) content;
LDAPAttribute[] attrs = c.getAttributes();
LDAPAttributeSet myAttrs = new LDAPAttributeSet();
- for (int i=0; i<attrs.length; i++)
+ for (int i = 0; i < attrs.length; i++)
myAttrs.add(attrs[i]);
LDAPEntry entry = new LDAPEntry(dn, myAttrs);
try {
conn.add(entry);
} catch (LDAPException ee) {
}
- } else if (type == LDIFContent.MODIFICATION_CONTENT) {
- LDIFModifyContent c = (LDIFModifyContent)content;
+ } else if (type == LDIFContent.MODIFICATION_CONTENT) {
+ LDIFModifyContent c = (LDIFModifyContent) content;
LDAPModification[] mods = c.getModifications();
try {
conn.modify(dn, mods);
diff --git a/pki/base/util/src/com/netscape/cmsutil/net/ISocketFactory.java b/pki/base/util/src/com/netscape/cmsutil/net/ISocketFactory.java
index 9227f591..18f6cac8 100644
--- a/pki/base/util/src/com/netscape/cmsutil/net/ISocketFactory.java
+++ b/pki/base/util/src/com/netscape/cmsutil/net/ISocketFactory.java
@@ -24,15 +24,15 @@ import java.net.UnknownHostException;
import org.mozilla.jss.ssl.SSLCertificateApprovalCallback;
import org.mozilla.jss.ssl.SSLClientCertificateSelectionCallback;
-public interface ISocketFactory
-{
- Socket makeSocket(String host, int port)
- throws IOException, UnknownHostException;
- Socket makeSocket(String host, int port, int timeout)
- throws IOException, UnknownHostException;
- Socket makeSocket(String host, int port,
- SSLCertificateApprovalCallback certApprovalCallback,
- SSLClientCertificateSelectionCallback clientCertCallback)
- throws IOException, UnknownHostException;
-}
+public interface ISocketFactory {
+ Socket makeSocket(String host, int port)
+ throws IOException, UnknownHostException;
+
+ Socket makeSocket(String host, int port, int timeout)
+ throws IOException, UnknownHostException;
+ Socket makeSocket(String host, int port,
+ SSLCertificateApprovalCallback certApprovalCallback,
+ SSLClientCertificateSelectionCallback clientCertCallback)
+ throws IOException, UnknownHostException;
+}
diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/BasicOCSPResponse.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/BasicOCSPResponse.java
index f6306b78..11ae7f15 100644
--- a/pki/base/util/src/com/netscape/cmsutil/ocsp/BasicOCSPResponse.java
+++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/BasicOCSPResponse.java
@@ -35,7 +35,7 @@ import org.mozilla.jss.pkix.primitive.AlgorithmIdentifier;
/**
* RFC 2560:
- *
+ *
* <pre>
* BasicOCSPResponse ::= SEQUENCE {
* tbsResponseData ResponseData,
@@ -43,11 +43,10 @@ import org.mozilla.jss.pkix.primitive.AlgorithmIdentifier;
* signature BIT STRING,
* certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL }
* </pre>
- *
+ *
* @version $Revision$ $Date$
*/
-public class BasicOCSPResponse implements Response
-{
+public class BasicOCSPResponse implements Response {
private byte mData[] = null;
private ResponseData _rd = null;
private AlgorithmIdentifier _signAlg = null;
@@ -55,21 +54,18 @@ public class BasicOCSPResponse implements Response
private Certificate _certs[] = null;
public BasicOCSPResponse(ResponseData rd, AlgorithmIdentifier signAlg,
- BIT_STRING signature, Certificate certs[])
- {
+ BIT_STRING signature, Certificate certs[]) {
_rd = rd;
_signAlg = signAlg;
_signature = signature;
_certs = certs;
}
- public BasicOCSPResponse(OCTET_STRING os)
- {
+ public BasicOCSPResponse(OCTET_STRING os) {
this(os.toByteArray());
}
- public BasicOCSPResponse(byte data[])
- {
+ public BasicOCSPResponse(byte data[]) {
mData = data;
// extract _rd, _signAlg, _signature and _certs
@@ -79,23 +75,21 @@ public class BasicOCSPResponse implements Response
_signAlg = resp.getSignatureAlgorithm();
_signature = resp.getSignature();
_certs = resp.getCerts();
- } catch (Exception e) {
+ } catch (Exception e) {
// exception in decoding byte data
- }
+ }
}
private static final Tag TAG = SEQUENCE.TAG;
- public Tag getTag()
- {
+ public Tag getTag() {
return TAG;
}
- public void encode(Tag t, OutputStream os) throws IOException
- {
- if (mData != null) {
- os.write(mData);
- } else {
+ public void encode(Tag t, OutputStream os) throws IOException {
+ if (mData != null) {
+ os.write(mData);
+ } else {
SEQUENCE seq = new SEQUENCE();
seq.addElement(_rd);
seq.addElement(_signAlg);
@@ -105,50 +99,42 @@ public class BasicOCSPResponse implements Response
for (Certificate c : _certs) {
certsSeq.addElement(c);
}
- EXPLICIT certsExplicit = new EXPLICIT(new Tag(0),certsSeq);
+ EXPLICIT certsExplicit = new EXPLICIT(new Tag(0), certsSeq);
seq.addElement(certsExplicit);
}
- seq.encode(t,os);
- }
+ seq.encode(t, os);
+ }
}
- public void encode(OutputStream os) throws IOException
- {
+ public void encode(OutputStream os) throws IOException {
encode(TAG, os);
}
- public OCTET_STRING getBytes()
- {
+ public OCTET_STRING getBytes() {
return null;
}
- public ResponseData getResponseData()
- {
+ public ResponseData getResponseData() {
return _rd;
}
- public AlgorithmIdentifier getSignatureAlgorithm()
- {
+ public AlgorithmIdentifier getSignatureAlgorithm() {
return _signAlg;
}
- public BIT_STRING getSignature()
- {
+ public BIT_STRING getSignature() {
return _signature;
}
- public int getCertsCount()
- {
+ public int getCertsCount() {
return (_certs != null) ? _certs.length : 0;
}
- public Certificate[] getCerts()
- {
- return _certs;
+ public Certificate[] getCerts() {
+ return _certs;
}
- public Certificate getCertificateAt(int pos)
- {
+ public Certificate getCertificateAt(int pos) {
return (_certs != null) ? _certs[pos] : null;
}
@@ -161,54 +147,49 @@ public class BasicOCSPResponse implements Response
/**
* A Template for decoding <code>ResponseBytes</code>.
*/
- public static class Template implements ASN1Template
- {
+ public static class Template implements ASN1Template {
private SEQUENCE.Template seqt;
- public Template()
- {
- seqt = new SEQUENCE.Template();
- seqt.addElement( ResponseData.getTemplate() );
- seqt.addElement( AlgorithmIdentifier.getTemplate() );
- seqt.addElement( BIT_STRING.getTemplate() );
- seqt.addOptionalElement( new EXPLICIT.Template(
- new Tag(0), new SEQUENCE.OF_Template(
- Certificate.getTemplate())) );
- }
-
- public boolean tagMatch(Tag tag)
- {
- return TAG.equals(tag);
- }
-
- public ASN1Value decode(InputStream istream)
- throws InvalidBERException, IOException
- {
- return decode(TAG, istream);
- }
-
- public ASN1Value decode(Tag implicitTag, InputStream istream)
- throws InvalidBERException, IOException
- {
- SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag, istream);
-
- ResponseData rd = (ResponseData)seq.elementAt(0);
- AlgorithmIdentifier alg = (AlgorithmIdentifier)seq.elementAt(1);
- BIT_STRING bs = (BIT_STRING)seq.elementAt(2);
- Certificate[] certs = null;
- if (seq.size() == 4) {
- // optional certificates are present
- EXPLICIT certSeqExplicit = (EXPLICIT) seq.elementAt(3);
- SEQUENCE certSeq = (SEQUENCE) certSeqExplicit.getContent();
- if (certSeq != null) {
- certs = new Certificate[certSeq.size()];
- for (int x = 0; x < certSeq.size(); x++) {
- certs[x] = (Certificate) certSeq.elementAt(x);
- }
- }
- }
-
- return new BasicOCSPResponse(rd, alg, bs, certs);
- }
+ public Template() {
+ seqt = new SEQUENCE.Template();
+ seqt.addElement(ResponseData.getTemplate());
+ seqt.addElement(AlgorithmIdentifier.getTemplate());
+ seqt.addElement(BIT_STRING.getTemplate());
+ seqt.addOptionalElement(new EXPLICIT.Template(
+ new Tag(0), new SEQUENCE.OF_Template(
+ Certificate.getTemplate())));
+ }
+
+ public boolean tagMatch(Tag tag) {
+ return TAG.equals(tag);
+ }
+
+ public ASN1Value decode(InputStream istream)
+ throws InvalidBERException, IOException {
+ return decode(TAG, istream);
+ }
+
+ public ASN1Value decode(Tag implicitTag, InputStream istream)
+ throws InvalidBERException, IOException {
+ SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag, istream);
+
+ ResponseData rd = (ResponseData) seq.elementAt(0);
+ AlgorithmIdentifier alg = (AlgorithmIdentifier) seq.elementAt(1);
+ BIT_STRING bs = (BIT_STRING) seq.elementAt(2);
+ Certificate[] certs = null;
+ if (seq.size() == 4) {
+ // optional certificates are present
+ EXPLICIT certSeqExplicit = (EXPLICIT) seq.elementAt(3);
+ SEQUENCE certSeq = (SEQUENCE) certSeqExplicit.getContent();
+ if (certSeq != null) {
+ certs = new Certificate[certSeq.size()];
+ for (int x = 0; x < certSeq.size(); x++) {
+ certs[x] = (Certificate) certSeq.elementAt(x);
+ }
+ }
+ }
+
+ return new BasicOCSPResponse(rd, alg, bs, certs);
+ }
}
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/CertID.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/CertID.java
index 3c563d93..feef6d10 100644
--- a/pki/base/util/src/com/netscape/cmsutil/ocsp/CertID.java
+++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/CertID.java
@@ -32,7 +32,7 @@ import org.mozilla.jss.pkix.primitive.AlgorithmIdentifier;
/**
* RFC 2560:
- *
+ *
* <pre>
* CertID ::= SEQUENCE {
* hashAlgorithm AlgorithmIdentifier,
@@ -40,130 +40,116 @@ import org.mozilla.jss.pkix.primitive.AlgorithmIdentifier;
* issuerKeyHash OCTET STRING, -- Hash of Issuers public key
* serialNumber CertificateSerialNumber }
* </pre>
- *
+ *
* @version $Revision$ $Date$
*/
-public class CertID implements ASN1Value
-{
- ///////////////////////////////////////////////////////////////////////
- // Members and member access
- ///////////////////////////////////////////////////////////////////////
- private AlgorithmIdentifier hashAlgorithm;
- private OCTET_STRING issuerNameHash;
- private OCTET_STRING issuerKeyHash;
- private INTEGER serialNumber;
- private SEQUENCE sequence;
-
- public AlgorithmIdentifier getHashAlgorithm()
- {
- return hashAlgorithm;
- }
-
- public OCTET_STRING getIssuerNameHash()
- {
- return issuerNameHash;
- }
-
- public OCTET_STRING getIssuerKeyHash()
- {
- return issuerKeyHash;
- }
-
- public INTEGER getSerialNumber()
- {
- return serialNumber;
- }
-
- ///////////////////////////////////////////////////////////////////////
- // Constructors
- ///////////////////////////////////////////////////////////////////////
-
- public CertID(AlgorithmIdentifier hashAlgorithm,
- OCTET_STRING issuerNameHash, OCTET_STRING issuerKeyHash,
- INTEGER serialNumber)
- {
- sequence = new SEQUENCE();
-
- this.hashAlgorithm = hashAlgorithm;
- sequence.addElement(hashAlgorithm);
-
- this.issuerNameHash = issuerNameHash;
- sequence.addElement(issuerNameHash);
-
- this.issuerKeyHash = issuerKeyHash;
- sequence.addElement(issuerKeyHash);
-
- this.serialNumber = serialNumber;
- sequence.addElement(serialNumber);
- }
-
- ///////////////////////////////////////////////////////////////////////
- // encoding/decoding
- ///////////////////////////////////////////////////////////////////////
-
- private static final Tag TAG = SEQUENCE.TAG;
-
- public Tag getTag()
- {
- return TAG;
- }
-
- public void encode(OutputStream ostream) throws IOException
- {
- encode(TAG, ostream);
- }
-
- public void encode(Tag implicitTag, OutputStream ostream)
- throws IOException
- {
- sequence.encode(implicitTag, ostream);
- }
-
- private static final Template templateInstance = new Template();
-
- public static Template getTemplate() {
- return templateInstance;
- }
-
- /**
- * A Template for decoding a <code>CertID</code>.
- */
- public static class Template implements ASN1Template
- {
-
- private SEQUENCE.Template seqt;
-
- public Template()
- {
- seqt = new SEQUENCE.Template();
- seqt.addElement( AlgorithmIdentifier.getTemplate() );
- seqt.addElement( OCTET_STRING.getTemplate() );
- seqt.addElement( OCTET_STRING.getTemplate() );
- seqt.addElement( INTEGER.getTemplate() );
- }
-
- public boolean tagMatch(Tag tag)
- {
- return TAG.equals(tag);
- }
-
- public ASN1Value decode(InputStream istream)
- throws InvalidBERException, IOException
- {
- return decode(TAG, istream);
- }
-
- public ASN1Value decode(Tag implicitTag, InputStream istream)
- throws InvalidBERException, IOException
- {
- SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag, istream);
-
- return new CertID(
- (AlgorithmIdentifier) seq.elementAt(0),
- (OCTET_STRING) seq.elementAt(1),
- (OCTET_STRING) seq.elementAt(2),
- (INTEGER) seq.elementAt(3));
- }
- }
+public class CertID implements ASN1Value {
+ // /////////////////////////////////////////////////////////////////////
+ // Members and member access
+ // /////////////////////////////////////////////////////////////////////
+ private AlgorithmIdentifier hashAlgorithm;
+ private OCTET_STRING issuerNameHash;
+ private OCTET_STRING issuerKeyHash;
+ private INTEGER serialNumber;
+ private SEQUENCE sequence;
+
+ public AlgorithmIdentifier getHashAlgorithm() {
+ return hashAlgorithm;
+ }
+
+ public OCTET_STRING getIssuerNameHash() {
+ return issuerNameHash;
+ }
+
+ public OCTET_STRING getIssuerKeyHash() {
+ return issuerKeyHash;
+ }
+
+ public INTEGER getSerialNumber() {
+ return serialNumber;
+ }
+
+ // /////////////////////////////////////////////////////////////////////
+ // Constructors
+ // /////////////////////////////////////////////////////////////////////
+
+ public CertID(AlgorithmIdentifier hashAlgorithm,
+ OCTET_STRING issuerNameHash, OCTET_STRING issuerKeyHash,
+ INTEGER serialNumber) {
+ sequence = new SEQUENCE();
+
+ this.hashAlgorithm = hashAlgorithm;
+ sequence.addElement(hashAlgorithm);
+
+ this.issuerNameHash = issuerNameHash;
+ sequence.addElement(issuerNameHash);
+
+ this.issuerKeyHash = issuerKeyHash;
+ sequence.addElement(issuerKeyHash);
+
+ this.serialNumber = serialNumber;
+ sequence.addElement(serialNumber);
+ }
+
+ // /////////////////////////////////////////////////////////////////////
+ // encoding/decoding
+ // /////////////////////////////////////////////////////////////////////
+
+ private static final Tag TAG = SEQUENCE.TAG;
+
+ public Tag getTag() {
+ return TAG;
+ }
+
+ public void encode(OutputStream ostream) throws IOException {
+ encode(TAG, ostream);
+ }
+
+ public void encode(Tag implicitTag, OutputStream ostream)
+ throws IOException {
+ sequence.encode(implicitTag, ostream);
+ }
+
+ private static final Template templateInstance = new Template();
+
+ public static Template getTemplate() {
+ return templateInstance;
+ }
+
+ /**
+ * A Template for decoding a <code>CertID</code>.
+ */
+ public static class Template implements ASN1Template {
+
+ private SEQUENCE.Template seqt;
+
+ public Template() {
+ seqt = new SEQUENCE.Template();
+ seqt.addElement(AlgorithmIdentifier.getTemplate());
+ seqt.addElement(OCTET_STRING.getTemplate());
+ seqt.addElement(OCTET_STRING.getTemplate());
+ seqt.addElement(INTEGER.getTemplate());
+ }
+
+ public boolean tagMatch(Tag tag) {
+ return TAG.equals(tag);
+ }
+
+ public ASN1Value decode(InputStream istream)
+ throws InvalidBERException, IOException {
+ return decode(TAG, istream);
+ }
+
+ public ASN1Value decode(Tag implicitTag, InputStream istream)
+ throws InvalidBERException, IOException {
+ SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag, istream);
+
+ return new CertID(
+ (AlgorithmIdentifier) seq.elementAt(0),
+ (OCTET_STRING) seq.elementAt(1),
+ (OCTET_STRING) seq.elementAt(2),
+ (INTEGER) seq.elementAt(3));
+ }
+ }
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/CertStatus.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/CertStatus.java
index c6fe4b51..a90eb215 100644
--- a/pki/base/util/src/com/netscape/cmsutil/ocsp/CertStatus.java
+++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/CertStatus.java
@@ -21,16 +21,15 @@ import org.mozilla.jss.asn1.ASN1Value;
/**
* RFC 2560:
- *
+ *
* <pre>
* CertStatus ::= CHOICE {
* good [0] IMPLICIT NULL,
* revoked [1] IMPLICIT RevokedInfo,
* unknown [2] IMPLICIT UnknownInfo }
* </pre>
- *
+ *
* @version $Revision$ $Date$
*/
-public interface CertStatus extends ASN1Value
-{
+public interface CertStatus extends ASN1Value {
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/GoodInfo.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/GoodInfo.java
index c0b5015d..abf89267 100644
--- a/pki/base/util/src/com/netscape/cmsutil/ocsp/GoodInfo.java
+++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/GoodInfo.java
@@ -30,79 +30,69 @@ import org.mozilla.jss.asn1.Tag;
/**
* RFC 2560:
- *
+ *
* <pre>
* CertStatus ::= CHOICE {
* good [0] IMPLICIT NULL,
* revoked [1] IMPLICIT RevokedInfo,
* unknown [2] IMPLICIT UnknownInfo }
* </pre>
- *
+ *
* @version $Revision$ $Date$
*/
-public class GoodInfo implements CertStatus
-{
- private static final Tag TAG = SEQUENCE.TAG;
+public class GoodInfo implements CertStatus {
+ private static final Tag TAG = SEQUENCE.TAG;
- public GoodInfo()
- {
- }
+ public GoodInfo() {
+ }
- public Tag getTag()
- {
- return Tag.get(0);
- }
+ public Tag getTag() {
+ return Tag.get(0);
+ }
- public void encode(Tag t, OutputStream os) throws IOException
- {
- NULL.getInstance().encode(getTag(), os);
- }
+ public void encode(Tag t, OutputStream os) throws IOException {
+ NULL.getInstance().encode(getTag(), os);
+ }
- public void encode(OutputStream os) throws IOException
- {
- encode(getTag(), os);
- }
+ public void encode(OutputStream os) throws IOException {
+ encode(getTag(), os);
+ }
- private static final Template templateInstance = new Template();
+ private static final Template templateInstance = new Template();
- public static Template getTemplate() {
- return templateInstance;
- }
+ public static Template getTemplate() {
+ return templateInstance;
+ }
- /**
- * A Template for decoding <code>ResponseBytes</code>.
- */
- public static class Template implements ASN1Template
- {
+ /**
+ * A Template for decoding <code>ResponseBytes</code>.
+ */
+ public static class Template implements ASN1Template {
- private SEQUENCE.Template seqt;
+ private SEQUENCE.Template seqt;
- public Template()
- {
- seqt = new SEQUENCE.Template();
- seqt.addElement(new NULL.Template() );
+ public Template() {
+ seqt = new SEQUENCE.Template();
+ seqt.addElement(new NULL.Template());
- }
+ }
- public boolean tagMatch(Tag tag)
- {
- return TAG.equals(tag);
- }
+ public boolean tagMatch(Tag tag) {
+ return TAG.equals(tag);
+ }
- public ASN1Value decode(InputStream istream)
- throws InvalidBERException, IOException
- {
- return decode(TAG, istream);
- }
+ public ASN1Value decode(InputStream istream)
+ throws InvalidBERException, IOException {
+ return decode(TAG, istream);
+ }
- public ASN1Value decode(Tag implicitTag, InputStream istream)
- throws InvalidBERException, IOException
- {
- // SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag,
- // istream);
+ public ASN1Value decode(Tag implicitTag, InputStream istream)
+ throws InvalidBERException, IOException {
+ // SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag,
+ // istream);
- return new GoodInfo();
+ return new GoodInfo();
- }
}
+ }
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/KeyHashID.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/KeyHashID.java
index 96a3e44f..180162c9 100644
--- a/pki/base/util/src/com/netscape/cmsutil/ocsp/KeyHashID.java
+++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/KeyHashID.java
@@ -30,87 +30,76 @@ import org.mozilla.jss.asn1.Tag;
/**
* RFC 2560:
- *
+ *
* <pre>
* ResponderID ::= CHOICE {
* byName [1] EXPLICIT Name,
* byKey [2] EXPLICIT KeyHash }
* </pre>
- *
+ *
* @version $Revision$ $Date$
*/
-public class KeyHashID implements ResponderID
-{
- private OCTET_STRING _hash = null;
- private static final Tag TAG = SEQUENCE.TAG;
-
- public KeyHashID(OCTET_STRING hash)
- {
- _hash = hash;
- }
-
- public Tag getTag()
- {
- return Tag.get(2);
- }
-
- public void encode(Tag tag, OutputStream os) throws IOException
- {
- _hash.encode(os);
- }
-
- public void encode(OutputStream os) throws IOException
- {
- _hash.encode(os);
- }
-
- public OCTET_STRING getHash()
- {
- return _hash;
- }
-
- private static final Template templateInstance = new Template();
-
- public static Template getTemplate() {
- return templateInstance;
+public class KeyHashID implements ResponderID {
+ private OCTET_STRING _hash = null;
+ private static final Tag TAG = SEQUENCE.TAG;
+
+ public KeyHashID(OCTET_STRING hash) {
+ _hash = hash;
+ }
+
+ public Tag getTag() {
+ return Tag.get(2);
+ }
+
+ public void encode(Tag tag, OutputStream os) throws IOException {
+ _hash.encode(os);
+ }
+
+ public void encode(OutputStream os) throws IOException {
+ _hash.encode(os);
+ }
+
+ public OCTET_STRING getHash() {
+ return _hash;
+ }
+
+ private static final Template templateInstance = new Template();
+
+ public static Template getTemplate() {
+ return templateInstance;
+ }
+
+ /**
+ * A Template for decoding <code>ResponseBytes</code>.
+ */
+ public static class Template implements ASN1Template {
+
+ private SEQUENCE.Template seqt;
+
+ public Template() {
+ seqt = new SEQUENCE.Template();
+ // seqt.addElement(new EXPLICIT.Template(
+ // new Tag (2), new OCTET_STRING.Template()) );
+ seqt.addElement(new OCTET_STRING.Template());
+
+ }
+
+ public boolean tagMatch(Tag tag) {
+ return TAG.equals(tag);
+ }
+
+ public ASN1Value decode(InputStream istream)
+ throws InvalidBERException, IOException {
+ return decode(TAG, istream);
}
- /**
- * A Template for decoding <code>ResponseBytes</code>.
- */
- public static class Template implements ASN1Template
- {
-
- private SEQUENCE.Template seqt;
-
- public Template()
- {
- seqt = new SEQUENCE.Template();
-// seqt.addElement(new EXPLICIT.Template(
- // new Tag (2), new OCTET_STRING.Template()) );
- seqt.addElement(new OCTET_STRING.Template() );
-
- }
-
- public boolean tagMatch(Tag tag)
- {
- return TAG.equals(tag);
- }
-
- public ASN1Value decode(InputStream istream)
- throws InvalidBERException, IOException
- {
- return decode(TAG, istream);
- }
-
- public ASN1Value decode(Tag implicitTag, InputStream istream)
- throws InvalidBERException, IOException
- {
- SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag,
+ public ASN1Value decode(Tag implicitTag, InputStream istream)
+ throws InvalidBERException, IOException {
+ SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag,
istream);
- OCTET_STRING o = (OCTET_STRING)seq.elementAt(0);
- return new KeyHashID(o);
- }
- }
+ OCTET_STRING o = (OCTET_STRING) seq.elementAt(0);
+ return new KeyHashID(o);
+ }
+ }
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/NameID.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/NameID.java
index aa6ef1b5..149c64c0 100644
--- a/pki/base/util/src/com/netscape/cmsutil/ocsp/NameID.java
+++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/NameID.java
@@ -30,88 +30,77 @@ import org.mozilla.jss.pkix.primitive.Name;
/**
* RFC 2560:
- *
+ *
* <pre>
* ResponderID ::= CHOICE {
* byName [1] EXPLICIT Name,
* byKey [2] EXPLICIT KeyHash }
* </pre>
- *
+ *
* @version $Revision$ $Date$
*/
-public class NameID implements ResponderID
-{
- private Name _name = null;
- private static final Tag TAG = SEQUENCE.TAG;
-
- public NameID(Name n)
- {
- _name = n;
- }
-
- public Tag getTag()
- {
- return Tag.get(1);
- }
-
- public void encode(Tag tag, OutputStream os) throws IOException
- {
- _name.encode(os);
- }
-
- public void encode(OutputStream os) throws IOException
- {
- _name.encode(os);
- }
-
- public Name getName()
- {
- return _name;
- }
-
- private static final Template templateInstance = new Template();
-
- public static Template getTemplate() {
- return templateInstance;
+public class NameID implements ResponderID {
+ private Name _name = null;
+ private static final Tag TAG = SEQUENCE.TAG;
+
+ public NameID(Name n) {
+ _name = n;
+ }
+
+ public Tag getTag() {
+ return Tag.get(1);
+ }
+
+ public void encode(Tag tag, OutputStream os) throws IOException {
+ _name.encode(os);
+ }
+
+ public void encode(OutputStream os) throws IOException {
+ _name.encode(os);
+ }
+
+ public Name getName() {
+ return _name;
+ }
+
+ private static final Template templateInstance = new Template();
+
+ public static Template getTemplate() {
+ return templateInstance;
+ }
+
+ /**
+ * A Template for decoding <code>ResponseBytes</code>.
+ */
+ public static class Template implements ASN1Template {
+
+ private SEQUENCE.Template seqt;
+
+ public Template() {
+ seqt = new SEQUENCE.Template();
+ // seqt.addElement(new EXPLICIT.Template(
+ // new Tag (1), new Name.Template()) );
+ seqt.addElement(new Name.Template());
+
+ }
+
+ public boolean tagMatch(Tag tag) {
+ return TAG.equals(tag);
}
- /**
- * A Template for decoding <code>ResponseBytes</code>.
- */
- public static class Template implements ASN1Template
- {
-
- private SEQUENCE.Template seqt;
-
- public Template()
- {
- seqt = new SEQUENCE.Template();
- // seqt.addElement(new EXPLICIT.Template(
- // new Tag (1), new Name.Template()) );
- seqt.addElement(new Name.Template());
-
- }
-
- public boolean tagMatch(Tag tag)
- {
- return TAG.equals(tag);
- }
-
- public ASN1Value decode(InputStream istream)
- throws InvalidBERException, IOException
- {
- return decode(TAG, istream);
- }
-
- public ASN1Value decode(Tag implicitTag, InputStream istream)
- throws InvalidBERException, IOException
- {
- SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag,
+ public ASN1Value decode(InputStream istream)
+ throws InvalidBERException, IOException {
+ return decode(TAG, istream);
+ }
+
+ public ASN1Value decode(Tag implicitTag, InputStream istream)
+ throws InvalidBERException, IOException {
+ SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag,
istream);
-
- // EXPLICIT e_name = (EXPLICIT) seq.elementAt(0);
- Name name = (Name)seq.elementAt(0);
- return new NameID(name);
- }
- }
+
+ // EXPLICIT e_name = (EXPLICIT) seq.elementAt(0);
+ Name name = (Name) seq.elementAt(0);
+ return new NameID(name);
+ }
+ }
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/OCSPRequest.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/OCSPRequest.java
index ea2e5422..380eabd7 100644
--- a/pki/base/util/src/com/netscape/cmsutil/ocsp/OCSPRequest.java
+++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/OCSPRequest.java
@@ -30,125 +30,114 @@ import org.mozilla.jss.asn1.Tag;
/**
* RFC 2560:
- *
+ *
* <pre>
* OCSPRequest ::= SEQUENCE {
* tbsRequest TBSRequest,
* optionalSignature [0] EXPLICIT Signature OPTIONAL }
* </pre>
- *
+ *
* @version $Revision$ $Date$
*/
-public class OCSPRequest implements ASN1Value
-{
-
- ///////////////////////////////////////////////////////////////////////
- // Members and member access
- ///////////////////////////////////////////////////////////////////////
- private TBSRequest tbsRequest;
- private Signature optionalSignature;
- private SEQUENCE sequence;
-
- /**
- * Returns the <code>TBSRequest</code> field.
- */
- public TBSRequest getTBSRequest()
- {
- return tbsRequest;
- }
-
- /**
- * Returns the <code>Signature</code> field.
- */
- public Signature getSignature()
- {
- return optionalSignature;
- }
-
-
- /* THIS code is probably broken. It does not properly encode the explicit element */
-
- public OCSPRequest(TBSRequest tbsRequest, Signature optionalSignature)
- {
- sequence = new SEQUENCE();
-
- this.tbsRequest = tbsRequest;
- sequence.addElement(tbsRequest);
-
- this.optionalSignature = optionalSignature;
- if (optionalSignature != null) {
- sequence.addElement(optionalSignature);
- }
- }
-
- ///////////////////////////////////////////////////////////////////////
- // encoding/decoding
- ///////////////////////////////////////////////////////////////////////
- private static final Tag TAG = SEQUENCE.TAG;
-
- public Tag getTag()
- {
- return TAG;
- }
-
- public void encode(OutputStream ostream) throws IOException
- {
- encode(TAG, ostream);
- }
-
- public void encode(Tag implicitTag, OutputStream ostream)
- throws IOException
- {
- sequence.encode(implicitTag, ostream);
- }
-
- private static final Template templateInstance = new Template();
-
- public static Template getTemplate()
- {
- return templateInstance;
- }
-
- /**
- * A Template for decoding OCSPRequest.
- */
- public static class Template implements ASN1Template
- {
-
- private SEQUENCE.Template seqt;
-
- public Template()
- {
- seqt = new SEQUENCE.Template();
- seqt.addElement(TBSRequest.getTemplate());
- seqt.addOptionalElement( new EXPLICIT.Template( new Tag(0),
- new Signature.Template()) );
- }
-
- public boolean tagMatch(Tag tag)
- {
- return TAG.equals(tag);
- }
-
- public ASN1Value decode(InputStream istream)
- throws InvalidBERException, IOException
- {
- return decode(TAG, istream);
- }
-
- public ASN1Value decode(Tag implicitTag, InputStream istream)
- throws InvalidBERException, IOException
- {
- SEQUENCE seq = (SEQUENCE) seqt.decode(istream);
- Signature signature = null;
- if (seq.elementAt(1) != null) {
- signature = (Signature)((EXPLICIT)seq.elementAt(1)).getContent();
- }
-
- return new OCSPRequest(
- (TBSRequest) seq.elementAt(0),
- signature);
- }
- }
+public class OCSPRequest implements ASN1Value {
+
+ // /////////////////////////////////////////////////////////////////////
+ // Members and member access
+ // /////////////////////////////////////////////////////////////////////
+ private TBSRequest tbsRequest;
+ private Signature optionalSignature;
+ private SEQUENCE sequence;
+
+ /**
+ * Returns the <code>TBSRequest</code> field.
+ */
+ public TBSRequest getTBSRequest() {
+ return tbsRequest;
+ }
+
+ /**
+ * Returns the <code>Signature</code> field.
+ */
+ public Signature getSignature() {
+ return optionalSignature;
+ }
+
+ /*
+ * THIS code is probably broken. It does not properly encode the explicit
+ * element
+ */
+
+ public OCSPRequest(TBSRequest tbsRequest, Signature optionalSignature) {
+ sequence = new SEQUENCE();
+
+ this.tbsRequest = tbsRequest;
+ sequence.addElement(tbsRequest);
+
+ this.optionalSignature = optionalSignature;
+ if (optionalSignature != null) {
+ sequence.addElement(optionalSignature);
+ }
+ }
+
+ // /////////////////////////////////////////////////////////////////////
+ // encoding/decoding
+ // /////////////////////////////////////////////////////////////////////
+ private static final Tag TAG = SEQUENCE.TAG;
+
+ public Tag getTag() {
+ return TAG;
+ }
+
+ public void encode(OutputStream ostream) throws IOException {
+ encode(TAG, ostream);
+ }
+
+ public void encode(Tag implicitTag, OutputStream ostream)
+ throws IOException {
+ sequence.encode(implicitTag, ostream);
+ }
+
+ private static final Template templateInstance = new Template();
+
+ public static Template getTemplate() {
+ return templateInstance;
+ }
+
+ /**
+ * A Template for decoding OCSPRequest.
+ */
+ public static class Template implements ASN1Template {
+
+ private SEQUENCE.Template seqt;
+
+ public Template() {
+ seqt = new SEQUENCE.Template();
+ seqt.addElement(TBSRequest.getTemplate());
+ seqt.addOptionalElement(new EXPLICIT.Template(new Tag(0),
+ new Signature.Template()));
+ }
+
+ public boolean tagMatch(Tag tag) {
+ return TAG.equals(tag);
+ }
+
+ public ASN1Value decode(InputStream istream)
+ throws InvalidBERException, IOException {
+ return decode(TAG, istream);
+ }
+
+ public ASN1Value decode(Tag implicitTag, InputStream istream)
+ throws InvalidBERException, IOException {
+ SEQUENCE seq = (SEQUENCE) seqt.decode(istream);
+ Signature signature = null;
+ if (seq.elementAt(1) != null) {
+ signature = (Signature) ((EXPLICIT) seq.elementAt(1)).getContent();
+ }
+
+ return new OCSPRequest(
+ (TBSRequest) seq.elementAt(0),
+ signature);
+ }
+ }
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/OCSPResponse.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/OCSPResponse.java
index d8635fe2..85fd5b78 100644
--- a/pki/base/util/src/com/netscape/cmsutil/ocsp/OCSPResponse.java
+++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/OCSPResponse.java
@@ -30,118 +30,106 @@ import org.mozilla.jss.asn1.Tag;
/**
* RFC 2560:
- *
+ *
* <pre>
* OCSPResponse ::= SEQUENCE {
* responseStatus OCSPResponseStatus,
* responseBytes [0] EXPLICIT ResponseBytes OPTIONAL }
* </pre>
- *
+ *
* @version $Revision$ $Date$
*/
-public class OCSPResponse implements ASN1Value
-{
- ///////////////////////////////////////////////////////////////////////
- // Members and member access
- ///////////////////////////////////////////////////////////////////////
- private OCSPResponseStatus responseStatus = null;
- private ResponseBytes responseBytes = null;
- private SEQUENCE sequence;
-
- public OCSPResponseStatus getResponseStatus()
- {
- return responseStatus;
- }
-
- public ResponseBytes getResponseBytes()
- {
- return responseBytes;
- }
-
- public OCSPResponse(OCSPResponseStatus responseStatus,
- ResponseBytes responseBytes)
- {
- sequence = new SEQUENCE();
-
- this.responseStatus = responseStatus;
- sequence.addElement(responseStatus);
-
- this.responseBytes = responseBytes;
- sequence.addElement(new EXPLICIT(Tag.get(0), responseBytes));
- }
-
- ///////////////////////////////////////////////////////////////////////
- // encoding/decoding
- ///////////////////////////////////////////////////////////////////////
-
- private static final Tag TAG = SEQUENCE.TAG;
-
- public Tag getTag()
- {
- return TAG;
- }
-
- public void encode(OutputStream ostream) throws IOException
- {
- encode(TAG, ostream);
- }
-
- public void encode(Tag implicitTag, OutputStream ostream)
- throws IOException
- {
- sequence.encode(implicitTag, ostream);
- }
-
- private static final Template templateInstance = new Template();
-
- public static Template getTemplate() {
- return templateInstance;
- }
-
- /**
- * A Template for decoding an <code>OCSPResponse</code>.
- */
- public static class Template implements ASN1Template
- {
-
- private SEQUENCE.Template seqt;
-
- public Template()
- {
- seqt = new SEQUENCE.Template();
- seqt.addElement( OCSPResponseStatus.getTemplate() );
- seqt.addOptionalElement(
- new EXPLICIT.Template(
- new Tag (0), new ResponseBytes.Template()) );
-
- }
-
- public boolean tagMatch(Tag tag)
- {
- return TAG.equals(tag);
- }
-
- public ASN1Value decode(InputStream istream)
- throws InvalidBERException, IOException
- {
- return decode(TAG, istream);
- }
-
- public ASN1Value decode(Tag implicitTag, InputStream istream)
- throws InvalidBERException, IOException
- {
- SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag, istream);
-
- OCSPResponseStatus rs = (OCSPResponseStatus) seq.elementAt(0);
- ResponseBytes rb = null;
- ASN1Value val = seq.elementAt(1);
- if (val instanceof EXPLICIT) {
- EXPLICIT exp = (EXPLICIT)val;
- rb = (ResponseBytes)exp.getContent();
- } else {
- rb = (ResponseBytes)val;
- }
- return new OCSPResponse(rs, rb);
- }
- }
+public class OCSPResponse implements ASN1Value {
+ // /////////////////////////////////////////////////////////////////////
+ // Members and member access
+ // /////////////////////////////////////////////////////////////////////
+ private OCSPResponseStatus responseStatus = null;
+ private ResponseBytes responseBytes = null;
+ private SEQUENCE sequence;
+
+ public OCSPResponseStatus getResponseStatus() {
+ return responseStatus;
+ }
+
+ public ResponseBytes getResponseBytes() {
+ return responseBytes;
+ }
+
+ public OCSPResponse(OCSPResponseStatus responseStatus,
+ ResponseBytes responseBytes) {
+ sequence = new SEQUENCE();
+
+ this.responseStatus = responseStatus;
+ sequence.addElement(responseStatus);
+
+ this.responseBytes = responseBytes;
+ sequence.addElement(new EXPLICIT(Tag.get(0), responseBytes));
+ }
+
+ // /////////////////////////////////////////////////////////////////////
+ // encoding/decoding
+ // /////////////////////////////////////////////////////////////////////
+
+ private static final Tag TAG = SEQUENCE.TAG;
+
+ public Tag getTag() {
+ return TAG;
+ }
+
+ public void encode(OutputStream ostream) throws IOException {
+ encode(TAG, ostream);
+ }
+
+ public void encode(Tag implicitTag, OutputStream ostream)
+ throws IOException {
+ sequence.encode(implicitTag, ostream);
+ }
+
+ private static final Template templateInstance = new Template();
+
+ public static Template getTemplate() {
+ return templateInstance;
+ }
+
+ /**
+ * A Template for decoding an <code>OCSPResponse</code>.
+ */
+ public static class Template implements ASN1Template {
+
+ private SEQUENCE.Template seqt;
+
+ public Template() {
+ seqt = new SEQUENCE.Template();
+ seqt.addElement(OCSPResponseStatus.getTemplate());
+ seqt.addOptionalElement(
+ new EXPLICIT.Template(
+ new Tag(0), new ResponseBytes.Template()));
+
+ }
+
+ public boolean tagMatch(Tag tag) {
+ return TAG.equals(tag);
+ }
+
+ public ASN1Value decode(InputStream istream)
+ throws InvalidBERException, IOException {
+ return decode(TAG, istream);
+ }
+
+ public ASN1Value decode(Tag implicitTag, InputStream istream)
+ throws InvalidBERException, IOException {
+ SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag, istream);
+
+ OCSPResponseStatus rs = (OCSPResponseStatus) seq.elementAt(0);
+ ResponseBytes rb = null;
+ ASN1Value val = seq.elementAt(1);
+ if (val instanceof EXPLICIT) {
+ EXPLICIT exp = (EXPLICIT) val;
+ rb = (ResponseBytes) exp.getContent();
+ } else {
+ rb = (ResponseBytes) val;
+ }
+ return new OCSPResponse(rs, rb);
+ }
+ }
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/OCSPResponseStatus.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/OCSPResponseStatus.java
index 145fbe7d..71ef42d8 100644
--- a/pki/base/util/src/com/netscape/cmsutil/ocsp/OCSPResponseStatus.java
+++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/OCSPResponseStatus.java
@@ -29,7 +29,7 @@ import org.mozilla.jss.asn1.Tag;
/**
* RFC 2560:
- *
+ *
* <pre>
* OCSPResponseStatus ::= ENUMERATED {
* successful (0), --Response has valid confirmations
@@ -41,90 +41,80 @@ import org.mozilla.jss.asn1.Tag;
* unauthorized (6) --Request unauthorized
* }
* </pre>
- *
+ *
* @version $Revision$ $Date$
*/
-public class OCSPResponseStatus implements ASN1Value
-{
- ///////////////////////////////////////////////////////////////////////
- // Members and member access
- ///////////////////////////////////////////////////////////////////////
- public final static OCSPResponseStatus SUCCESSFUL =
- new OCSPResponseStatus(0);
- public final static OCSPResponseStatus MALFORMED_REQUEST =
- new OCSPResponseStatus(1);
- public final static OCSPResponseStatus INTERNAL_ERROR =
- new OCSPResponseStatus(2);
- public final static OCSPResponseStatus TRY_LATER =
- new OCSPResponseStatus(3);
- public final static OCSPResponseStatus SIG_REQUIRED =
- new OCSPResponseStatus(5);
- public final static OCSPResponseStatus UNAUTHORIZED =
- new OCSPResponseStatus(6);
-
- private ENUMERATED responseStatus;
-
- public long getValue()
- {
- return responseStatus.getValue();
- }
-
- public OCSPResponseStatus(long val)
- {
- responseStatus = new ENUMERATED(val);
- }
-
- ///////////////////////////////////////////////////////////////////////
- // encoding/decoding
- ///////////////////////////////////////////////////////////////////////
-
- private static final Tag TAG = ENUMERATED.TAG;
-
- public Tag getTag()
- {
- return TAG;
- }
-
- public void encode(OutputStream ostream) throws IOException
- {
- encode(TAG, ostream);
- }
-
- public void encode(Tag implicitTag, OutputStream ostream)
- throws IOException
- {
- responseStatus.encode(implicitTag, ostream);
- }
-
- private static final Template templateInstance = new Template();
-
- public static Template getTemplate() {
- return templateInstance;
- }
-
- /**
- * A Template for decoding an <code>OCSPResponseStatus</code>.
- */
- public static class Template implements ASN1Template
- {
- public boolean tagMatch(Tag tag)
- {
- return TAG.equals(tag);
- }
-
- public ASN1Value decode(InputStream istream)
- throws InvalidBERException, IOException
- {
- return decode(TAG, istream);
- }
-
- public ASN1Value decode(Tag implicitTag, InputStream istream)
- throws InvalidBERException, IOException
- {
- ENUMERATED.Template enumt = new ENUMERATED.Template();
- ENUMERATED enum1 = (ENUMERATED) enumt.decode(implicitTag, istream);
-
- return new OCSPResponseStatus(enum1.getValue());
- }
- }
+public class OCSPResponseStatus implements ASN1Value {
+ // /////////////////////////////////////////////////////////////////////
+ // Members and member access
+ // /////////////////////////////////////////////////////////////////////
+ public final static OCSPResponseStatus SUCCESSFUL =
+ new OCSPResponseStatus(0);
+ public final static OCSPResponseStatus MALFORMED_REQUEST =
+ new OCSPResponseStatus(1);
+ public final static OCSPResponseStatus INTERNAL_ERROR =
+ new OCSPResponseStatus(2);
+ public final static OCSPResponseStatus TRY_LATER =
+ new OCSPResponseStatus(3);
+ public final static OCSPResponseStatus SIG_REQUIRED =
+ new OCSPResponseStatus(5);
+ public final static OCSPResponseStatus UNAUTHORIZED =
+ new OCSPResponseStatus(6);
+
+ private ENUMERATED responseStatus;
+
+ public long getValue() {
+ return responseStatus.getValue();
+ }
+
+ public OCSPResponseStatus(long val) {
+ responseStatus = new ENUMERATED(val);
+ }
+
+ // /////////////////////////////////////////////////////////////////////
+ // encoding/decoding
+ // /////////////////////////////////////////////////////////////////////
+
+ private static final Tag TAG = ENUMERATED.TAG;
+
+ public Tag getTag() {
+ return TAG;
+ }
+
+ public void encode(OutputStream ostream) throws IOException {
+ encode(TAG, ostream);
+ }
+
+ public void encode(Tag implicitTag, OutputStream ostream)
+ throws IOException {
+ responseStatus.encode(implicitTag, ostream);
+ }
+
+ private static final Template templateInstance = new Template();
+
+ public static Template getTemplate() {
+ return templateInstance;
+ }
+
+ /**
+ * A Template for decoding an <code>OCSPResponseStatus</code>.
+ */
+ public static class Template implements ASN1Template {
+ public boolean tagMatch(Tag tag) {
+ return TAG.equals(tag);
+ }
+
+ public ASN1Value decode(InputStream istream)
+ throws InvalidBERException, IOException {
+ return decode(TAG, istream);
+ }
+
+ public ASN1Value decode(Tag implicitTag, InputStream istream)
+ throws InvalidBERException, IOException {
+ ENUMERATED.Template enumt = new ENUMERATED.Template();
+ ENUMERATED enum1 = (ENUMERATED) enumt.decode(implicitTag, istream);
+
+ return new OCSPResponseStatus(enum1.getValue());
+ }
+ }
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/Request.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/Request.java
index 9f277bb9..5e4009ec 100644
--- a/pki/base/util/src/com/netscape/cmsutil/ocsp/Request.java
+++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/Request.java
@@ -31,132 +31,117 @@ import org.mozilla.jss.pkix.cert.Extension;
/**
* RFC 2560:
- *
+ *
* <pre>
* Request ::= SEQUENCE {
* reqCert CertID,
* singleRequestExtensions [0] EXPLICIT Extensions OPTIONAL }
* </pre>
- *
+ *
* @version $Revision$ $Date$
*/
-public class Request implements ASN1Value
-{
- ///////////////////////////////////////////////////////////////////////
- // members and member access
- ///////////////////////////////////////////////////////////////////////
- private CertID reqCert = null;
- private SEQUENCE singleRequestExtensions = null;
- private SEQUENCE sequence = null;
-
- public CertID getCertID()
- {
- return reqCert;
- }
-
- public int getExtensionsCount()
- {
- if(singleRequestExtensions == null) {
- return 0;
- } else {
- return singleRequestExtensions.size();
- }
- }
-
- public Extension getRequestExtensionAt(int index)
- {
- if(singleRequestExtensions == null) {
- throw new ArrayIndexOutOfBoundsException();
- }
- return (Extension) singleRequestExtensions.elementAt(index);
- }
-
- public Request(CertID reqCert, SEQUENCE singleRequestExtensions)
- {
- sequence = new SEQUENCE();
-
- this.reqCert = reqCert;
- sequence.addElement(reqCert);
-
- if (singleRequestExtensions != null) {
- this.singleRequestExtensions = singleRequestExtensions;
- sequence.addElement(singleRequestExtensions);
- }
- }
-
- ///////////////////////////////////////////////////////////////////////
- // encode / decode
- ///////////////////////////////////////////////////////////////////////
- private static final Tag TAG = SEQUENCE.TAG;
-
- public Tag getTag()
- {
- return TAG;
- }
-
- public void encode(OutputStream ostream) throws IOException
- {
- encode(TAG, ostream);
- }
-
- public void encode(Tag implicitTag, OutputStream ostream)
- throws IOException
- {
- sequence.encode(implicitTag, ostream);
- }
-
- private static final Template templateInstance = new Template();
-
- public static Template getTemplate()
- {
- return templateInstance;
- }
-
- /**
- * A Template for decoding Request.
- */
- public static class Template implements ASN1Template
- {
-
- private SEQUENCE.Template seqt;
-
- public Template()
- {
- seqt = new SEQUENCE.Template();
- seqt.addElement( CertID.getTemplate() );
- seqt.addOptionalElement(new EXPLICIT.Template(new Tag(0),
- new SEQUENCE.OF_Template(new Extension.Template()) ));
- }
-
- public boolean tagMatch(Tag tag)
- {
- return TAG.equals(tag);
- }
-
- public ASN1Value decode(InputStream istream)
- throws InvalidBERException, IOException
- {
- return decode(TAG, istream);
- }
-
- public ASN1Value decode(Tag implicitTag, InputStream istream)
- throws InvalidBERException, IOException
- {
- SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag, istream);
-
- EXPLICIT tag = (EXPLICIT) seq.elementAt(1);
-
- if (tag == null) {
- return new Request(
- (CertID) seq.elementAt(0),
- (SEQUENCE) null);
- }
- else {
- return new Request(
- (CertID) seq.elementAt(0),
- (SEQUENCE) tag.getContent());
- }
- }
- }
+public class Request implements ASN1Value {
+ // /////////////////////////////////////////////////////////////////////
+ // members and member access
+ // /////////////////////////////////////////////////////////////////////
+ private CertID reqCert = null;
+ private SEQUENCE singleRequestExtensions = null;
+ private SEQUENCE sequence = null;
+
+ public CertID getCertID() {
+ return reqCert;
+ }
+
+ public int getExtensionsCount() {
+ if (singleRequestExtensions == null) {
+ return 0;
+ } else {
+ return singleRequestExtensions.size();
+ }
+ }
+
+ public Extension getRequestExtensionAt(int index) {
+ if (singleRequestExtensions == null) {
+ throw new ArrayIndexOutOfBoundsException();
+ }
+ return (Extension) singleRequestExtensions.elementAt(index);
+ }
+
+ public Request(CertID reqCert, SEQUENCE singleRequestExtensions) {
+ sequence = new SEQUENCE();
+
+ this.reqCert = reqCert;
+ sequence.addElement(reqCert);
+
+ if (singleRequestExtensions != null) {
+ this.singleRequestExtensions = singleRequestExtensions;
+ sequence.addElement(singleRequestExtensions);
+ }
+ }
+
+ // /////////////////////////////////////////////////////////////////////
+ // encode / decode
+ // /////////////////////////////////////////////////////////////////////
+ private static final Tag TAG = SEQUENCE.TAG;
+
+ public Tag getTag() {
+ return TAG;
+ }
+
+ public void encode(OutputStream ostream) throws IOException {
+ encode(TAG, ostream);
+ }
+
+ public void encode(Tag implicitTag, OutputStream ostream)
+ throws IOException {
+ sequence.encode(implicitTag, ostream);
+ }
+
+ private static final Template templateInstance = new Template();
+
+ public static Template getTemplate() {
+ return templateInstance;
+ }
+
+ /**
+ * A Template for decoding Request.
+ */
+ public static class Template implements ASN1Template {
+
+ private SEQUENCE.Template seqt;
+
+ public Template() {
+ seqt = new SEQUENCE.Template();
+ seqt.addElement(CertID.getTemplate());
+ seqt.addOptionalElement(new EXPLICIT.Template(new Tag(0),
+ new SEQUENCE.OF_Template(new Extension.Template())));
+ }
+
+ public boolean tagMatch(Tag tag) {
+ return TAG.equals(tag);
+ }
+
+ public ASN1Value decode(InputStream istream)
+ throws InvalidBERException, IOException {
+ return decode(TAG, istream);
+ }
+
+ public ASN1Value decode(Tag implicitTag, InputStream istream)
+ throws InvalidBERException, IOException {
+ SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag, istream);
+
+ EXPLICIT tag = (EXPLICIT) seq.elementAt(1);
+
+ if (tag == null) {
+ return new Request(
+ (CertID) seq.elementAt(0),
+ (SEQUENCE) null);
+ } else {
+ return new Request(
+ (CertID) seq.elementAt(0),
+ (SEQUENCE) tag.getContent());
+ }
+ }
+ }
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/ResponderID.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/ResponderID.java
index d5cfa680..02e30de0 100644
--- a/pki/base/util/src/com/netscape/cmsutil/ocsp/ResponderID.java
+++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/ResponderID.java
@@ -19,18 +19,16 @@ package com.netscape.cmsutil.ocsp;
import org.mozilla.jss.asn1.ASN1Value;
-
/**
* RFC 2560:
- *
+ *
* <pre>
* ResponderID ::= CHOICE {
* byName [1] EXPLICIT Name,
* byKey [2] EXPLICIT KeyHash }
* </pre>
- *
+ *
* @version $Revision$ $Date$
*/
-public interface ResponderID extends ASN1Value
-{
+public interface ResponderID extends ASN1Value {
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/Response.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/Response.java
index eb011e1c..0d363e81 100644
--- a/pki/base/util/src/com/netscape/cmsutil/ocsp/Response.java
+++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/Response.java
@@ -22,14 +22,13 @@ import org.mozilla.jss.asn1.OCTET_STRING;
/**
* RFC 2560:
- *
+ *
* <pre>
* response OCTET STRING
* </pre>
- *
+ *
* @version $Revision$ $Date$
*/
-public interface Response extends ASN1Value
-{
- public OCTET_STRING getBytes();
+public interface Response extends ASN1Value {
+ public OCTET_STRING getBytes();
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/ResponseBytes.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/ResponseBytes.java
index b5fed0d9..66af8fa2 100644
--- a/pki/base/util/src/com/netscape/cmsutil/ocsp/ResponseBytes.java
+++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/ResponseBytes.java
@@ -31,112 +31,100 @@ import org.mozilla.jss.asn1.Tag;
/**
* RFC 2560:
- *
+ *
* <pre>
* ResponseBytes ::= SEQUENCE {
* responseType OBJECT IDENTIFIER,
* response OCTET STRING }
* </pre>
- *
+ *
* @version $Revision$ $Date$
*/
-public class ResponseBytes implements ASN1Value
-{
- ///////////////////////////////////////////////////////////////////////
- // Members and member access
- ///////////////////////////////////////////////////////////////////////
- public final static OBJECT_IDENTIFIER OCSP =
- new OBJECT_IDENTIFIER("1.3.6.1.5.5.7.48.1");
- public final static OBJECT_IDENTIFIER OCSP_BASIC =
- new OBJECT_IDENTIFIER("1.3.6.1.5.5.7.48.1.1");
-
- private OBJECT_IDENTIFIER responseType = null;
- private OCTET_STRING response = null;
- private SEQUENCE sequence;
-
- public OBJECT_IDENTIFIER getObjectIdentifier()
- {
- return responseType;
- }
-
- public OCTET_STRING getResponse()
- {
- return response;
- }
-
- public ResponseBytes(OBJECT_IDENTIFIER responseType, OCTET_STRING response)
- {
- sequence = new SEQUENCE();
-
- this.responseType = responseType;
- sequence.addElement(responseType);
-
- this.response = response;
- sequence.addElement(response);
- }
-
- ///////////////////////////////////////////////////////////////////////
- // encoding/decoding
- ///////////////////////////////////////////////////////////////////////
-
- private static final Tag TAG = SEQUENCE.TAG;
-
- public Tag getTag()
- {
- return TAG;
- }
-
- public void encode(OutputStream ostream) throws IOException
- {
- encode(TAG, ostream);
- }
-
- public void encode(Tag implicitTag, OutputStream ostream)
- throws IOException
- {
- sequence.encode(implicitTag, ostream);
- }
-
- private static final Template templateInstance = new Template();
-
- public static Template getTemplate() {
- return templateInstance;
- }
-
- /**
- * A Template for decoding <code>ResponseBytes</code>.
- */
- public static class Template implements ASN1Template
- {
-
- private SEQUENCE.Template seqt;
-
- public Template()
- {
- seqt = new SEQUENCE.Template();
- seqt.addElement( OBJECT_IDENTIFIER.getTemplate() );
- seqt.addElement( OCTET_STRING.getTemplate() );
- }
-
- public boolean tagMatch(Tag tag)
- {
- return TAG.equals(tag);
- }
-
- public ASN1Value decode(InputStream istream)
- throws InvalidBERException, IOException
- {
- return decode(TAG, istream);
- }
-
- public ASN1Value decode(Tag implicitTag, InputStream istream)
- throws InvalidBERException, IOException
- {
- SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag, istream);
-
- return new ResponseBytes(
- (OBJECT_IDENTIFIER) seq.elementAt(0),
- (OCTET_STRING) seq.elementAt(1));
- }
- }
+public class ResponseBytes implements ASN1Value {
+ // /////////////////////////////////////////////////////////////////////
+ // Members and member access
+ // /////////////////////////////////////////////////////////////////////
+ public final static OBJECT_IDENTIFIER OCSP =
+ new OBJECT_IDENTIFIER("1.3.6.1.5.5.7.48.1");
+ public final static OBJECT_IDENTIFIER OCSP_BASIC =
+ new OBJECT_IDENTIFIER("1.3.6.1.5.5.7.48.1.1");
+
+ private OBJECT_IDENTIFIER responseType = null;
+ private OCTET_STRING response = null;
+ private SEQUENCE sequence;
+
+ public OBJECT_IDENTIFIER getObjectIdentifier() {
+ return responseType;
+ }
+
+ public OCTET_STRING getResponse() {
+ return response;
+ }
+
+ public ResponseBytes(OBJECT_IDENTIFIER responseType, OCTET_STRING response) {
+ sequence = new SEQUENCE();
+
+ this.responseType = responseType;
+ sequence.addElement(responseType);
+
+ this.response = response;
+ sequence.addElement(response);
+ }
+
+ // /////////////////////////////////////////////////////////////////////
+ // encoding/decoding
+ // /////////////////////////////////////////////////////////////////////
+
+ private static final Tag TAG = SEQUENCE.TAG;
+
+ public Tag getTag() {
+ return TAG;
+ }
+
+ public void encode(OutputStream ostream) throws IOException {
+ encode(TAG, ostream);
+ }
+
+ public void encode(Tag implicitTag, OutputStream ostream)
+ throws IOException {
+ sequence.encode(implicitTag, ostream);
+ }
+
+ private static final Template templateInstance = new Template();
+
+ public static Template getTemplate() {
+ return templateInstance;
+ }
+
+ /**
+ * A Template for decoding <code>ResponseBytes</code>.
+ */
+ public static class Template implements ASN1Template {
+
+ private SEQUENCE.Template seqt;
+
+ public Template() {
+ seqt = new SEQUENCE.Template();
+ seqt.addElement(OBJECT_IDENTIFIER.getTemplate());
+ seqt.addElement(OCTET_STRING.getTemplate());
+ }
+
+ public boolean tagMatch(Tag tag) {
+ return TAG.equals(tag);
+ }
+
+ public ASN1Value decode(InputStream istream)
+ throws InvalidBERException, IOException {
+ return decode(TAG, istream);
+ }
+
+ public ASN1Value decode(Tag implicitTag, InputStream istream)
+ throws InvalidBERException, IOException {
+ SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag, istream);
+
+ return new ResponseBytes(
+ (OBJECT_IDENTIFIER) seq.elementAt(0),
+ (OCTET_STRING) seq.elementAt(1));
+ }
+ }
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/ResponseData.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/ResponseData.java
index 81c5eee4..d59dd56d 100644
--- a/pki/base/util/src/com/netscape/cmsutil/ocsp/ResponseData.java
+++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/ResponseData.java
@@ -35,7 +35,7 @@ import org.mozilla.jss.pkix.cert.Extension;
/**
* RFC 2560:
- *
+ *
* <pre>
* ResponseData ::= SEQUENCE {
* version [0] EXPLICIT Version DEFAULT v1,
@@ -44,13 +44,12 @@ import org.mozilla.jss.pkix.cert.Extension;
* responses SEQUENCE OF SingleResponse,
* responseExtensions [1] EXPLICIT Extensions OPTIONAL }
* </pre>
- *
+ *
* @version $Revision$ $Date$
*/
-public class ResponseData implements ASN1Value
-{
+public class ResponseData implements ASN1Value {
private static final INTEGER v1 = new INTEGER(0);
- private INTEGER mVer;
+ private INTEGER mVer;
private ResponderID mRID = null;
private GeneralizedTime mProduced = null;
private SingleResponse mSR[] = null;
@@ -58,7 +57,7 @@ public class ResponseData implements ASN1Value
private static final Tag TAG = SEQUENCE.TAG;
- public ResponseData(INTEGER ver, ResponderID rid, GeneralizedTime produced,
+ public ResponseData(INTEGER ver, ResponderID rid, GeneralizedTime produced,
SingleResponse sr[], Extension exts[]) {
mVer = (ver != null) ? ver : v1;
mRID = rid;
@@ -67,30 +66,25 @@ public class ResponseData implements ASN1Value
mExts = exts;
}
- public ResponseData(ResponderID rid, GeneralizedTime produced,
- SingleResponse sr[])
- {
+ public ResponseData(ResponderID rid, GeneralizedTime produced,
+ SingleResponse sr[]) {
this(v1, rid, produced, sr, null);
}
- public ResponseData(ResponderID rid, GeneralizedTime produced,
- SingleResponse sr[], Extension exts[])
- {
+ public ResponseData(ResponderID rid, GeneralizedTime produced,
+ SingleResponse sr[], Extension exts[]) {
this(v1, rid, produced, sr, exts);
}
-
- public Tag getTag()
- {
+
+ public Tag getTag() {
return TAG;
}
- public void encode(OutputStream os) throws IOException
- {
+ public void encode(OutputStream os) throws IOException {
encode(null, os);
}
- public void encode(Tag t, OutputStream os) throws IOException
- {
+ public void encode(Tag t, OutputStream os) throws IOException {
SEQUENCE seq = new SEQUENCE();
if (mVer != v1) {
@@ -116,35 +110,29 @@ public class ResponseData implements ASN1Value
} else {
seq.encode(t, os);
}
- }
+ }
- public ResponderID getResponderID()
- {
+ public ResponderID getResponderID() {
return mRID;
}
- public GeneralizedTime getProducedAt()
- {
+ public GeneralizedTime getProducedAt() {
return mProduced;
}
- public int getResponseCount()
- {
+ public int getResponseCount() {
return (mSR != null) ? mSR.length : 0;
}
- public SingleResponse getResponseAt(int pos)
- {
+ public SingleResponse getResponseAt(int pos) {
return (mSR != null) ? mSR[pos] : null;
}
- public int getResponseExtensionCount()
- {
- return (mExts != null) ? mExts.length : 0;
+ public int getResponseExtensionCount() {
+ return (mExts != null) ? mExts.length : 0;
}
- public Extension getResponseExtensionAt(int pos)
- {
+ public Extension getResponseExtensionAt(int pos) {
return (mExts != null) ? mExts[pos] : null;
}
@@ -157,83 +145,78 @@ public class ResponseData implements ASN1Value
/**
* A Template for decoding <code>ResponseBytes</code>.
*/
- public static class Template implements ASN1Template
- {
+ public static class Template implements ASN1Template {
private SEQUENCE.Template seqt;
- public Template()
- {
- seqt = new SEQUENCE.Template();
- seqt.addOptionalElement(new EXPLICIT.Template(
- new Tag (0), new INTEGER.Template()) );
- seqt.addElement(new ANY.Template() );
- seqt.addElement(new GeneralizedTime.Template() );
+ public Template() {
+ seqt = new SEQUENCE.Template();
+ seqt.addOptionalElement(new EXPLICIT.Template(
+ new Tag(0), new INTEGER.Template()));
+ seqt.addElement(new ANY.Template());
+ seqt.addElement(new GeneralizedTime.Template());
seqt.addElement(new SEQUENCE.OF_Template(
- SingleResponse.getTemplate()));
+ SingleResponse.getTemplate()));
seqt.addOptionalElement(new EXPLICIT.Template(
- new Tag(1), new SEQUENCE.OF_Template(
- Extension.getTemplate())));
+ new Tag(1), new SEQUENCE.OF_Template(
+ Extension.getTemplate())));
}
- public boolean tagMatch(Tag tag)
- {
+ public boolean tagMatch(Tag tag) {
return TAG.equals(tag);
}
public ASN1Value decode(InputStream istream)
- throws InvalidBERException, IOException
- {
+ throws InvalidBERException, IOException {
return decode(TAG, istream);
}
public ASN1Value decode(Tag implicitTag, InputStream istream)
- throws InvalidBERException, IOException
- {
- SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag,
- istream);
+ throws InvalidBERException, IOException {
+ SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag,
+ istream);
INTEGER ver = v1;
- EXPLICIT e_ver = (EXPLICIT)seq.elementAt(0);
+ EXPLICIT e_ver = (EXPLICIT) seq.elementAt(0);
if (e_ver != null && e_ver.getTag().getNum() == 0) {
- ver = (INTEGER)e_ver.getContent();
+ ver = (INTEGER) e_ver.getContent();
}
ResponderID rid = null;
- ANY e_rid = (ANY)seq.elementAt(1);
+ ANY e_rid = (ANY) seq.elementAt(1);
if (e_rid.getTag().getNum() == 1) {
// name id
- rid = (NameID)
- NameID.getTemplate().decode(e_rid.getTag(),
- new ByteArrayInputStream(e_rid.getEncoded()));
+ rid = (NameID)
+ NameID.getTemplate().decode(e_rid.getTag(),
+ new ByteArrayInputStream(e_rid.getEncoded()));
} else if (e_rid.getTag().getNum() == 2) {
// key hash id
rid = (KeyHashID)
- KeyHashID.getTemplate().decode(e_rid.getTag(),
- new ByteArrayInputStream(e_rid.getEncoded()));
+ KeyHashID.getTemplate().decode(e_rid.getTag(),
+ new ByteArrayInputStream(e_rid.getEncoded()));
}
- GeneralizedTime producedAt = (GeneralizedTime) seq.elementAt(2);
- SEQUENCE responses = (SEQUENCE)seq.elementAt(3);
+ GeneralizedTime producedAt = (GeneralizedTime) seq.elementAt(2);
+ SEQUENCE responses = (SEQUENCE) seq.elementAt(3);
SingleResponse sr[] = null;
- if ((responses != null) && (responses.size() > 0)) {
+ if ((responses != null) && (responses.size() > 0)) {
sr = new SingleResponse[responses.size()];
for (int i = 0; i < responses.size(); i++) {
- sr[i] = (SingleResponse)responses.elementAt(i);
+ sr[i] = (SingleResponse) responses.elementAt(i);
}
}
- //decode response extension sequence
+ // decode response extension sequence
EXPLICIT extns_exp = (EXPLICIT) seq.elementAt(4);
SEQUENCE extns_seq;
Extension[] extns_array = null;
if (extns_exp != null) {
- extns_seq = (SEQUENCE)extns_exp.getContent();
+ extns_seq = (SEQUENCE) extns_exp.getContent();
extns_array = new Extension[extns_seq.size()];
- for (int x=0;x<extns_array.length;x++) {
+ for (int x = 0; x < extns_array.length; x++) {
extns_array[x] = (Extension) extns_seq.elementAt(x);
}
}
return new ResponseData(ver, rid, producedAt, sr, extns_array);
- }
- }
+ }
+ }
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/RevokedInfo.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/RevokedInfo.java
index b1b7489f..9b0b2d18 100644
--- a/pki/base/util/src/com/netscape/cmsutil/ocsp/RevokedInfo.java
+++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/RevokedInfo.java
@@ -32,94 +32,82 @@ import org.mozilla.jss.asn1.Tag;
/**
* RFC 2560:
- *
+ *
* <pre>
* RevokedInfo ::= SEQUENCE {
* revocationTime GeneralizedTime,
* revocationReason [0] EXPLICIT CRLReason OPTIONAL }
* </pre>
- *
+ *
* @version $Revision$ $Date$
*/
-public class RevokedInfo implements CertStatus
-{
- private static final Tag TAG = SEQUENCE.TAG;
+public class RevokedInfo implements CertStatus {
+ private static final Tag TAG = SEQUENCE.TAG;
- private GeneralizedTime mRevokedAt;
+ private GeneralizedTime mRevokedAt;
- public RevokedInfo(GeneralizedTime revokedAt)
- {
- mRevokedAt = revokedAt;
- }
+ public RevokedInfo(GeneralizedTime revokedAt) {
+ mRevokedAt = revokedAt;
+ }
- public Tag getTag()
- {
- return Tag.get(1);
- }
+ public Tag getTag() {
+ return Tag.get(1);
+ }
- public void encode(Tag t, OutputStream os) throws IOException
- {
- SEQUENCE seq = new SEQUENCE();
- seq.addElement(mRevokedAt);
- seq.encode(t, os);
- }
+ public void encode(Tag t, OutputStream os) throws IOException {
+ SEQUENCE seq = new SEQUENCE();
+ seq.addElement(mRevokedAt);
+ seq.encode(t, os);
+ }
- public void encode(OutputStream os) throws IOException
- {
- encode(getTag(), os);
- }
-
- public GeneralizedTime getRevocationTime()
- {
- return mRevokedAt;
- }
+ public void encode(OutputStream os) throws IOException {
+ encode(getTag(), os);
+ }
+
+ public GeneralizedTime getRevocationTime() {
+ return mRevokedAt;
+ }
+
+ private static final Template templateInstance = new Template();
+
+ public static Template getTemplate() {
+ return templateInstance;
+ }
+ /**
+ * A Template for decoding <code>ResponseBytes</code>.
+ */
+ public static class Template implements ASN1Template {
- private static final Template templateInstance = new Template();
+ private SEQUENCE.Template seqt;
+
+ public Template() {
+ seqt = new SEQUENCE.Template();
+ seqt.addElement(new GeneralizedTime.Template());
+ seqt.addOptionalElement(
+ new EXPLICIT.Template(new Tag(0),
+ new INTEGER.Template()));
+
+ }
+
+ public boolean tagMatch(Tag tag) {
+ return TAG.equals(tag);
+ }
- public static Template getTemplate() {
- return templateInstance;
+ public ASN1Value decode(InputStream istream)
+ throws InvalidBERException, IOException {
+ return decode(TAG, istream);
}
- /**
- * A Template for decoding <code>ResponseBytes</code>.
- */
- public static class Template implements ASN1Template
- {
-
- private SEQUENCE.Template seqt;
-
- public Template()
- {
- seqt = new SEQUENCE.Template();
- seqt.addElement(new GeneralizedTime.Template() );
- seqt.addOptionalElement(
- new EXPLICIT.Template( new Tag(0),
- new INTEGER.Template()) );
-
- }
-
- public boolean tagMatch(Tag tag)
- {
- return TAG.equals(tag);
- }
-
- public ASN1Value decode(InputStream istream)
- throws InvalidBERException, IOException
- {
- return decode(TAG, istream);
- }
-
- public ASN1Value decode(Tag implicitTag, InputStream istream)
- throws InvalidBERException, IOException
- {
- SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag,
+ public ASN1Value decode(Tag implicitTag, InputStream istream)
+ throws InvalidBERException, IOException {
+ SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag,
istream);
- GeneralizedTime revokedAt = (GeneralizedTime)
- seq.elementAt(0);
- return new RevokedInfo(revokedAt);
+ GeneralizedTime revokedAt = (GeneralizedTime)
+ seq.elementAt(0);
+ return new RevokedInfo(revokedAt);
- }
}
+ }
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/Signature.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/Signature.java
index d670dfe2..7b53f82d 100644
--- a/pki/base/util/src/com/netscape/cmsutil/ocsp/Signature.java
+++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/Signature.java
@@ -33,142 +33,127 @@ import org.mozilla.jss.pkix.primitive.AlgorithmIdentifier;
/**
* RFC 2560:
- *
+ *
* <pre>
* Signature ::= SEQUENCE {
* signatureAlgorithm AlgorithmIdentifier,
* signature BIT STRING,
* certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL }
* </pre>
- *
+ *
* @version $Revision$ $Date$
*/
-public class Signature implements ASN1Value
-{
- ///////////////////////////////////////////////////////////////////////
- // Members and member access
- ///////////////////////////////////////////////////////////////////////
- private AlgorithmIdentifier signatureAlgorithm;
- private BIT_STRING signature;
- private SEQUENCE certs;
- private SEQUENCE sequence;
-
- public AlgorithmIdentifier getSignatureAlgorithm()
- {
- return signatureAlgorithm;
- }
-
- public BIT_STRING getSignature()
- {
- return signature;
- }
-
- public int getCertificateCount()
- {
- if(certs == null) {
- return 0;
- } else {
- return certs.size();
- }
- }
-
- public Certificate getCertificateAt(int index)
- {
- if(certs == null) {
- throw new ArrayIndexOutOfBoundsException();
- }
- return (Certificate) certs.elementAt(index);
- }
-
- public Signature(AlgorithmIdentifier signatureAlgorithm,
- BIT_STRING signature, SEQUENCE certs)
- {
- sequence = new SEQUENCE();
-
- this.signatureAlgorithm = signatureAlgorithm;
- sequence.addElement(signatureAlgorithm);
-
- this.signature = signature;
- sequence.addElement(signature);
-
- this.certs = certs;
- sequence.addElement(certs);
- }
-
- ///////////////////////////////////////////////////////////////////////
- // encode / decode
- ///////////////////////////////////////////////////////////////////////
- private static final Tag TAG = SEQUENCE.TAG;
-
- public Tag getTag()
- {
- return TAG;
- }
-
- public void encode(OutputStream ostream) throws IOException
- {
- encode(TAG, ostream);
- }
-
- public void encode(Tag implicitTag, OutputStream ostream)
- throws IOException
- {
- sequence.encode(implicitTag, ostream);
- }
-
- private static final Template templateInstance = new Template();
-
- public static Template getTemplate()
- {
- return templateInstance;
- }
-
- /**
- * A Template for decoding Request.
- */
- public static class Template implements ASN1Template
- {
-
- private SEQUENCE.Template seqt;
-
- public Template()
- {
- seqt = new SEQUENCE.Template();
- seqt.addElement( AlgorithmIdentifier.getTemplate() );
- seqt.addElement( BIT_STRING.getTemplate() );
- seqt.addOptionalElement(
- new EXPLICIT.Template(
- new Tag(0),
- new SEQUENCE.OF_Template( new Certificate.Template())
- )
- );
- }
-
- public boolean tagMatch(Tag tag)
- {
- return TAG.equals(tag);
- }
-
- public ASN1Value decode(InputStream istream)
- throws InvalidBERException, IOException
- {
- return decode(TAG, istream);
- }
-
- public ASN1Value decode(Tag implicitTag, InputStream istream)
- throws InvalidBERException, IOException
- {
- SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag, istream);
- SEQUENCE certs=null;
- if( seq.elementAt(2) != null ) {
- certs = (SEQUENCE) ((EXPLICIT)seq.elementAt(2)).getContent();
- }
-
- return new Signature(
- (AlgorithmIdentifier) seq.elementAt(0),
- (BIT_STRING) seq.elementAt(1),
- certs);
- }
- }
+public class Signature implements ASN1Value {
+ // /////////////////////////////////////////////////////////////////////
+ // Members and member access
+ // /////////////////////////////////////////////////////////////////////
+ private AlgorithmIdentifier signatureAlgorithm;
+ private BIT_STRING signature;
+ private SEQUENCE certs;
+ private SEQUENCE sequence;
+
+ public AlgorithmIdentifier getSignatureAlgorithm() {
+ return signatureAlgorithm;
+ }
+
+ public BIT_STRING getSignature() {
+ return signature;
+ }
+
+ public int getCertificateCount() {
+ if (certs == null) {
+ return 0;
+ } else {
+ return certs.size();
+ }
+ }
+
+ public Certificate getCertificateAt(int index) {
+ if (certs == null) {
+ throw new ArrayIndexOutOfBoundsException();
+ }
+ return (Certificate) certs.elementAt(index);
+ }
+
+ public Signature(AlgorithmIdentifier signatureAlgorithm,
+ BIT_STRING signature, SEQUENCE certs) {
+ sequence = new SEQUENCE();
+
+ this.signatureAlgorithm = signatureAlgorithm;
+ sequence.addElement(signatureAlgorithm);
+
+ this.signature = signature;
+ sequence.addElement(signature);
+
+ this.certs = certs;
+ sequence.addElement(certs);
+ }
+
+ // /////////////////////////////////////////////////////////////////////
+ // encode / decode
+ // /////////////////////////////////////////////////////////////////////
+ private static final Tag TAG = SEQUENCE.TAG;
+
+ public Tag getTag() {
+ return TAG;
+ }
+
+ public void encode(OutputStream ostream) throws IOException {
+ encode(TAG, ostream);
+ }
+
+ public void encode(Tag implicitTag, OutputStream ostream)
+ throws IOException {
+ sequence.encode(implicitTag, ostream);
+ }
+
+ private static final Template templateInstance = new Template();
+
+ public static Template getTemplate() {
+ return templateInstance;
+ }
+
+ /**
+ * A Template for decoding Request.
+ */
+ public static class Template implements ASN1Template {
+
+ private SEQUENCE.Template seqt;
+
+ public Template() {
+ seqt = new SEQUENCE.Template();
+ seqt.addElement(AlgorithmIdentifier.getTemplate());
+ seqt.addElement(BIT_STRING.getTemplate());
+ seqt.addOptionalElement(
+ new EXPLICIT.Template(
+ new Tag(0),
+ new SEQUENCE.OF_Template(new Certificate.Template())
+ )
+ );
+ }
+
+ public boolean tagMatch(Tag tag) {
+ return TAG.equals(tag);
+ }
+
+ public ASN1Value decode(InputStream istream)
+ throws InvalidBERException, IOException {
+ return decode(TAG, istream);
+ }
+
+ public ASN1Value decode(Tag implicitTag, InputStream istream)
+ throws InvalidBERException, IOException {
+ SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag, istream);
+ SEQUENCE certs = null;
+ if (seq.elementAt(2) != null) {
+ certs = (SEQUENCE) ((EXPLICIT) seq.elementAt(2)).getContent();
+ }
+
+ return new Signature(
+ (AlgorithmIdentifier) seq.elementAt(0),
+ (BIT_STRING) seq.elementAt(1),
+ certs);
+ }
+ }
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/SingleResponse.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/SingleResponse.java
index 1ce72747..ab54e501 100644
--- a/pki/base/util/src/com/netscape/cmsutil/ocsp/SingleResponse.java
+++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/SingleResponse.java
@@ -34,7 +34,7 @@ import org.mozilla.jss.pkix.cert.Extension;
/**
* RFC 2560:
- *
+ *
* <pre>
* SingleResponse ::= SEQUENCE {
* certID CertID,
@@ -43,157 +43,140 @@ import org.mozilla.jss.pkix.cert.Extension;
* nextUpdate [0] EXPLICIT GeneralizedTime OPTIONAL,
* singleExtensions [1] EXPLICIT Extensions OPTIONAL }
* </pre>
- *
+ *
* @version $Revision$ $Date$
*/
-public class SingleResponse implements ASN1Value
-{
- private CertID mCID = null;
- private CertStatus mStatus = null;
- private GeneralizedTime mThisUpdate = null;
- private GeneralizedTime mNextUpdate = null;
-
- private static final Tag TAG = SEQUENCE.TAG;
-
- public SingleResponse(CertID cid, CertStatus s,
- GeneralizedTime thisUpdate, GeneralizedTime nextUpdate)
- {
- mCID = cid;
- mStatus = s;
- mThisUpdate = thisUpdate;
- mNextUpdate = nextUpdate;
- }
-
- public CertID getCertID()
- {
- return mCID;
- }
-
- public Tag getTag()
- {
- return null;
- }
-
- public void encode(Tag t, OutputStream os) throws IOException
- {
- SEQUENCE seq = new SEQUENCE();
- seq.addElement(mCID);
- seq.addElement(mStatus);
- seq.addElement(mThisUpdate);
- if (mNextUpdate != null)
- {
- seq.addElement(new EXPLICIT(Tag.get(0), mNextUpdate));
- }
- if (t == null) {
- seq.encode(os);
- } else {
- seq.encode(t, os);
- }
- }
-
- public void encode(OutputStream os) throws IOException
- {
- encode(null, os);
- }
-
- public CertStatus getCertStatus()
- {
- return mStatus;
- }
-
- public GeneralizedTime getThisUpdate()
- {
- return mThisUpdate;
- }
-
- public GeneralizedTime getNextUpdate()
- {
- return mNextUpdate;
- }
-
- public int getExtensionCount()
- {
- return 0;
- }
-
- public Extension getExtensionAt(int pos)
- {
- return null;
- }
-
- private static final Template templateInstance = new Template();
-
- public static Template getTemplate() {
- return templateInstance;
+public class SingleResponse implements ASN1Value {
+ private CertID mCID = null;
+ private CertStatus mStatus = null;
+ private GeneralizedTime mThisUpdate = null;
+ private GeneralizedTime mNextUpdate = null;
+
+ private static final Tag TAG = SEQUENCE.TAG;
+
+ public SingleResponse(CertID cid, CertStatus s,
+ GeneralizedTime thisUpdate, GeneralizedTime nextUpdate) {
+ mCID = cid;
+ mStatus = s;
+ mThisUpdate = thisUpdate;
+ mNextUpdate = nextUpdate;
+ }
+
+ public CertID getCertID() {
+ return mCID;
+ }
+
+ public Tag getTag() {
+ return null;
+ }
+
+ public void encode(Tag t, OutputStream os) throws IOException {
+ SEQUENCE seq = new SEQUENCE();
+ seq.addElement(mCID);
+ seq.addElement(mStatus);
+ seq.addElement(mThisUpdate);
+ if (mNextUpdate != null) {
+ seq.addElement(new EXPLICIT(Tag.get(0), mNextUpdate));
}
+ if (t == null) {
+ seq.encode(os);
+ } else {
+ seq.encode(t, os);
+ }
+ }
+
+ public void encode(OutputStream os) throws IOException {
+ encode(null, os);
+ }
+
+ public CertStatus getCertStatus() {
+ return mStatus;
+ }
+
+ public GeneralizedTime getThisUpdate() {
+ return mThisUpdate;
+ }
+
+ public GeneralizedTime getNextUpdate() {
+ return mNextUpdate;
+ }
+
+ public int getExtensionCount() {
+ return 0;
+ }
+
+ public Extension getExtensionAt(int pos) {
+ return null;
+ }
+
+ private static final Template templateInstance = new Template();
+
+ public static Template getTemplate() {
+ return templateInstance;
+ }
- /**
- * A Template for decoding <code>ResponseBytes</code>.
- */
- public static class Template implements ASN1Template
- {
-
- private SEQUENCE.Template seqt;
-
- public Template()
- {
- seqt = new SEQUENCE.Template();
- seqt.addElement(new CertID.Template() );
- seqt.addElement(new ANY.Template() );
- seqt.addElement(new GeneralizedTime.Template() );
- seqt.addOptionalElement(new EXPLICIT.Template(
+ /**
+ * A Template for decoding <code>ResponseBytes</code>.
+ */
+ public static class Template implements ASN1Template {
+
+ private SEQUENCE.Template seqt;
+
+ public Template() {
+ seqt = new SEQUENCE.Template();
+ seqt.addElement(new CertID.Template());
+ seqt.addElement(new ANY.Template());
+ seqt.addElement(new GeneralizedTime.Template());
+ seqt.addOptionalElement(new EXPLICIT.Template(
new Tag(0), new GeneralizedTime.Template()));
- seqt.addOptionalElement(new EXPLICIT.Template(new Tag(1),
+ seqt.addOptionalElement(new EXPLICIT.Template(new Tag(1),
new SEQUENCE.OF_Template(new Extension.Template())));
- }
-
- public boolean tagMatch(Tag tag)
- {
- return TAG.equals(tag);
- }
-
- public ASN1Value decode(InputStream istream)
- throws InvalidBERException, IOException
- {
- return decode(TAG, istream);
- }
-
- public ASN1Value decode(Tag implicitTag, InputStream istream)
- throws InvalidBERException, IOException
- {
- SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag,
- istream);
-
- CertID cid = (CertID)seq.elementAt(0);
- CertStatus status = null;
- ANY e_status = (ANY)seq.elementAt(1);
- if (e_status.getTag().getNum() == 0) {
- status = (GoodInfo)
+ }
+
+ public boolean tagMatch(Tag tag) {
+ return TAG.equals(tag);
+ }
+
+ public ASN1Value decode(InputStream istream)
+ throws InvalidBERException, IOException {
+ return decode(TAG, istream);
+ }
+
+ public ASN1Value decode(Tag implicitTag, InputStream istream)
+ throws InvalidBERException, IOException {
+ SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag,
+ istream);
+
+ CertID cid = (CertID) seq.elementAt(0);
+ CertStatus status = null;
+ ANY e_status = (ANY) seq.elementAt(1);
+ if (e_status.getTag().getNum() == 0) {
+ status = (GoodInfo)
GoodInfo.getTemplate().decode(
- e_status.getTag(),
- new ByteArrayInputStream(e_status.getEncoded()));
- // good
- } else if (e_status.getTag().getNum() == 1) {
- // revoked
- status = (RevokedInfo)
+ e_status.getTag(),
+ new ByteArrayInputStream(e_status.getEncoded()));
+ // good
+ } else if (e_status.getTag().getNum() == 1) {
+ // revoked
+ status = (RevokedInfo)
RevokedInfo.getTemplate().decode(
- e_status.getTag(),
- new ByteArrayInputStream(e_status.getEncoded()));
- } else if (e_status.getTag().getNum() == 2) {
- // unknown
- status = (UnknownInfo)
+ e_status.getTag(),
+ new ByteArrayInputStream(e_status.getEncoded()));
+ } else if (e_status.getTag().getNum() == 2) {
+ // unknown
+ status = (UnknownInfo)
UnknownInfo.getTemplate().decode(
- e_status.getTag(),
- new ByteArrayInputStream(e_status.getEncoded()));
- }
- GeneralizedTime thisUpdate = (GeneralizedTime)
- seq.elementAt(2);
- GeneralizedTime nextUpdate = null;
+ e_status.getTag(),
+ new ByteArrayInputStream(e_status.getEncoded()));
+ }
+ GeneralizedTime thisUpdate = (GeneralizedTime)
+ seq.elementAt(2);
+ GeneralizedTime nextUpdate = null;
- return new SingleResponse(cid, status, thisUpdate,
- nextUpdate);
+ return new SingleResponse(cid, status, thisUpdate,
+ nextUpdate);
- }
}
+ }
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/TBSRequest.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/TBSRequest.java
index ea23200d..d26c4f25 100644
--- a/pki/base/util/src/com/netscape/cmsutil/ocsp/TBSRequest.java
+++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/TBSRequest.java
@@ -33,7 +33,7 @@ import org.mozilla.jss.pkix.cert.Extension;
/**
* RFC 2560:
- *
+ *
* <pre>
* TBSRequest ::= SEQUENCE {
* version [0] EXPLICIT Version DEFAULT v1,
@@ -41,33 +41,29 @@ import org.mozilla.jss.pkix.cert.Extension;
* requestList SEQUENCE OF Request,
* requestExtensions [2] EXPLICIT Extensions OPTIONAL }
* </pre>
- *
+ *
* @version $Revision$ $Date$
*/
-public class TBSRequest implements ASN1Value
-{
- ///////////////////////////////////////////////////////////////////////
+public class TBSRequest implements ASN1Value {
+ // /////////////////////////////////////////////////////////////////////
// members and member access
- ///////////////////////////////////////////////////////////////////////
- private static final INTEGER v1 = new INTEGER (0);
+ // /////////////////////////////////////////////////////////////////////
+ private static final INTEGER v1 = new INTEGER(0);
private INTEGER version;
private ANY requestorName;
private SEQUENCE requestList;
private SEQUENCE requestExtensions;
- public INTEGER getVersion()
- {
+ public INTEGER getVersion() {
return version;
}
- public ANY getRequestorName()
- {
+ public ANY getRequestorName() {
return requestorName;
- }
+ }
- public int getRequestCount()
- {
+ public int getRequestCount() {
if (requestList == null) {
return 0;
} else {
@@ -75,13 +71,11 @@ public class TBSRequest implements ASN1Value
}
}
- public Request getRequestAt(int index)
- {
+ public Request getRequestAt(int index) {
return (Request) requestList.elementAt(index);
}
- public int getExtensionsCount()
- {
+ public int getExtensionsCount() {
if (requestExtensions == null) {
return 0;
} else {
@@ -89,43 +83,38 @@ public class TBSRequest implements ASN1Value
}
}
- public Extension getRequestExtensionAt(int index)
- {
+ public Extension getRequestExtensionAt(int index) {
return (Extension) requestExtensions.elementAt(index);
}
- ///////////////////////////////////////////////////////////////////////
+ // /////////////////////////////////////////////////////////////////////
// constructors
- ///////////////////////////////////////////////////////////////////////
-
+ // /////////////////////////////////////////////////////////////////////
+
public TBSRequest(INTEGER version, ANY requestorName,
- SEQUENCE requestList, SEQUENCE requestExtensions)
- {
+ SEQUENCE requestList, SEQUENCE requestExtensions) {
this.version = (version != null) ? version : v1;
this.requestorName = requestorName;
this.requestList = requestList;
this.requestExtensions = requestExtensions;
}
- ///////////////////////////////////////////////////////////////////////
+ // /////////////////////////////////////////////////////////////////////
// encode / decode
- ///////////////////////////////////////////////////////////////////////
+ // /////////////////////////////////////////////////////////////////////
public static final Tag TAG = SEQUENCE.TAG;
- public Tag getTag()
- {
+ public Tag getTag() {
return TAG;
}
public void encode(OutputStream ostream)
- throws IOException
- {
+ throws IOException {
encode(TAG, ostream);
}
public void encode(Tag implicitTag, OutputStream ostream)
- throws IOException
- {
+ throws IOException {
SEQUENCE seq = new SEQUENCE();
if (version != v1) {
@@ -150,52 +139,46 @@ public class TBSRequest implements ASN1Value
private static final Template templateInstance = new Template();
- public static Template getTemplate()
- {
+ public static Template getTemplate() {
return templateInstance;
}
/**
* A Template for decoding TBSRequest.
*/
- public static class Template implements ASN1Template
- {
+ public static class Template implements ASN1Template {
private SEQUENCE.Template seqt;
- public Template()
- {
+ public Template() {
seqt = new SEQUENCE.Template();
seqt.addElement(
- new EXPLICIT.Template(
- new Tag(0), new INTEGER.Template()),
- new EXPLICIT( new Tag(0), new INTEGER(0))
- );
+ new EXPLICIT.Template(
+ new Tag(0), new INTEGER.Template()),
+ new EXPLICIT(new Tag(0), new INTEGER(0))
+ );
seqt.addOptionalElement(
- new EXPLICIT.Template(
- new Tag (1), new ANY.Template()) );
- seqt.addElement( new SEQUENCE.OF_Template(new Request.Template()) );
+ new EXPLICIT.Template(
+ new Tag(1), new ANY.Template()));
+ seqt.addElement(new SEQUENCE.OF_Template(new Request.Template()));
seqt.addOptionalElement(new EXPLICIT.Template(new Tag(2),
- new SEQUENCE.OF_Template(new Extension.Template())) );
+ new SEQUENCE.OF_Template(new Extension.Template())));
}
- public boolean tagMatch(Tag tag)
- {
+ public boolean tagMatch(Tag tag) {
return TAG.equals(tag);
}
public ASN1Value decode(InputStream istream)
- throws InvalidBERException, IOException
- {
+ throws InvalidBERException, IOException {
return decode(TAG, istream);
}
public ASN1Value decode(Tag implicitTag, InputStream istream)
- throws InvalidBERException, IOException
- {
+ throws InvalidBERException, IOException {
SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag, istream);
- INTEGER v = v1; //assume default version
+ INTEGER v = v1; // assume default version
EXPLICIT e_ver = (EXPLICIT) seq.elementAt(0);
if (e_ver != null) {
v = (INTEGER) e_ver.getContent();
@@ -207,21 +190,21 @@ public class TBSRequest implements ASN1Value
requestorname = (ANY) e_requestorName.getContent();
}
- //request sequence (element 2) done below
+ // request sequence (element 2) done below
EXPLICIT exts = (EXPLICIT) seq.elementAt(3);
SEQUENCE exts_seq;
if (exts != null) {
- exts_seq = (SEQUENCE)exts.getContent();
+ exts_seq = (SEQUENCE) exts.getContent();
} else {
exts_seq = null;
}
return new TBSRequest(
- v,
- requestorname,
- (SEQUENCE) seq.elementAt(2),
- exts_seq);
+ v,
+ requestorname,
+ (SEQUENCE) seq.elementAt(2),
+ exts_seq);
}
}
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/UnknownInfo.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/UnknownInfo.java
index d9891f5a..97cdb6e2 100644
--- a/pki/base/util/src/com/netscape/cmsutil/ocsp/UnknownInfo.java
+++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/UnknownInfo.java
@@ -30,76 +30,66 @@ import org.mozilla.jss.asn1.Tag;
/**
* RFC 2560:
- *
+ *
* <pre>
* UnknownInfo ::= NULL -- this can be replaced with an enumeration
* </pre>
- *
+ *
* @version $Revision$ $Date$
*/
-public class UnknownInfo implements CertStatus
-{
- private static final Tag TAG = SEQUENCE.TAG;
+public class UnknownInfo implements CertStatus {
+ private static final Tag TAG = SEQUENCE.TAG;
- public UnknownInfo()
- {
- }
+ public UnknownInfo() {
+ }
- public Tag getTag()
- {
- return Tag.get(2);
- }
+ public Tag getTag() {
+ return Tag.get(2);
+ }
- public void encode(Tag t, OutputStream os) throws IOException
- {
- NULL.getInstance().encode(getTag(), os);
- }
+ public void encode(Tag t, OutputStream os) throws IOException {
+ NULL.getInstance().encode(getTag(), os);
+ }
- public void encode(OutputStream os) throws IOException
- {
- encode(getTag(), os);
- }
+ public void encode(OutputStream os) throws IOException {
+ encode(getTag(), os);
+ }
- private static final Template templateInstance = new Template();
+ private static final Template templateInstance = new Template();
- public static Template getTemplate() {
- return templateInstance;
- }
+ public static Template getTemplate() {
+ return templateInstance;
+ }
- /**
- * A Template for decoding <code>ResponseBytes</code>.
- */
- public static class Template implements ASN1Template
- {
+ /**
+ * A Template for decoding <code>ResponseBytes</code>.
+ */
+ public static class Template implements ASN1Template {
- private SEQUENCE.Template seqt;
+ private SEQUENCE.Template seqt;
- public Template()
- {
-// seqt = new SEQUENCE.Template();
- // seqt.addElement(new NULL.Template() );
+ public Template() {
+ // seqt = new SEQUENCE.Template();
+ // seqt.addElement(new NULL.Template() );
- }
+ }
- public boolean tagMatch(Tag tag)
- {
- return TAG.equals(tag);
- }
+ public boolean tagMatch(Tag tag) {
+ return TAG.equals(tag);
+ }
- public ASN1Value decode(InputStream istream)
- throws InvalidBERException, IOException
- {
- return decode(TAG, istream);
- }
+ public ASN1Value decode(InputStream istream)
+ throws InvalidBERException, IOException {
+ return decode(TAG, istream);
+ }
- public ASN1Value decode(Tag implicitTag, InputStream istream)
- throws InvalidBERException, IOException
- {
- // SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag,
- // istream);
+ public ASN1Value decode(Tag implicitTag, InputStream istream)
+ throws InvalidBERException, IOException {
+ // SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag,
+ // istream);
- return new UnknownInfo();
+ return new UnknownInfo();
- }
}
+ }
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/password/IPasswordReader.java b/pki/base/util/src/com/netscape/cmsutil/password/IPasswordReader.java
index 1a6a026b..357ae0a6 100644
--- a/pki/base/util/src/com/netscape/cmsutil/password/IPasswordReader.java
+++ b/pki/base/util/src/com/netscape/cmsutil/password/IPasswordReader.java
@@ -16,11 +16,14 @@
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.password;
+
import java.io.IOException;
import java.util.Enumeration;
public interface IPasswordReader {
public void init(String pwdPath) throws IOException;
+
public String getPassword(String tag);
+
public Enumeration getTags();
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/password/IPasswordStore.java b/pki/base/util/src/com/netscape/cmsutil/password/IPasswordStore.java
index 3d7a8d80..f2e9293d 100644
--- a/pki/base/util/src/com/netscape/cmsutil/password/IPasswordStore.java
+++ b/pki/base/util/src/com/netscape/cmsutil/password/IPasswordStore.java
@@ -22,9 +22,13 @@ import java.util.Enumeration;
public interface IPasswordStore {
public void init(String pwdPath) throws IOException;
+
public String getPassword(String tag);
+
public Enumeration getTags();
+
public Object putPassword(String tag, String password);
+
public void commit()
- throws IOException, ClassCastException, NullPointerException;
+ throws IOException, ClassCastException, NullPointerException;
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/password/IPasswordWriter.java b/pki/base/util/src/com/netscape/cmsutil/password/IPasswordWriter.java
index 2f42e02c..c9f9691e 100644
--- a/pki/base/util/src/com/netscape/cmsutil/password/IPasswordWriter.java
+++ b/pki/base/util/src/com/netscape/cmsutil/password/IPasswordWriter.java
@@ -16,12 +16,15 @@
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.password;
+
import java.io.IOException;
public interface IPasswordWriter {
public void init(String pwdPath)
- throws IOException;;
+ throws IOException;;
+
public Object putPassword(String tag, String password);
+
public void commit()
- throws IOException, ClassCastException, NullPointerException;
+ throws IOException, ClassCastException, NullPointerException;
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/password/PlainPasswordFile.java b/pki/base/util/src/com/netscape/cmsutil/password/PlainPasswordFile.java
index c9cec1df..c962e1c6 100644
--- a/pki/base/util/src/com/netscape/cmsutil/password/PlainPasswordFile.java
+++ b/pki/base/util/src/com/netscape/cmsutil/password/PlainPasswordFile.java
@@ -23,7 +23,7 @@ import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
-public class PlainPasswordFile implements IPasswordStore{
+public class PlainPasswordFile implements IPasswordStore {
private String mPwdPath = "";
private Properties mPwdStore;
private static final String PASSWORD_WRITER_HEADER = "";
@@ -32,24 +32,23 @@ public class PlainPasswordFile implements IPasswordStore{
}
public void init(String pwdPath)
- throws IOException
- {
- mPwdStore = new Properties();
- // initialize mPwdStore
- mPwdPath = pwdPath;
+ throws IOException {
+ mPwdStore = new Properties();
+ // initialize mPwdStore
+ mPwdPath = pwdPath;
- FileInputStream file = new FileInputStream(mPwdPath);
- mPwdStore.load(file);
- file.close();
+ FileInputStream file = new FileInputStream(mPwdPath);
+ mPwdStore.load(file);
+ file.close();
}
public String getPassword(String tag) {
- return (String) mPwdStore.getProperty(tag);
+ return (String) mPwdStore.getProperty(tag);
}
// return an array of String-based tag
public Enumeration getTags() {
- return mPwdStore.propertyNames();
+ return mPwdStore.propertyNames();
}
public Object putPassword(String tag, String password) {
@@ -57,8 +56,7 @@ public class PlainPasswordFile implements IPasswordStore{
}
public void commit()
- throws IOException, ClassCastException, NullPointerException
- {
+ throws IOException, ClassCastException, NullPointerException {
FileOutputStream file = new FileOutputStream(mPwdPath);
mPwdStore.store(file, PASSWORD_WRITER_HEADER);
file.close();
diff --git a/pki/base/util/src/com/netscape/cmsutil/password/PlainPasswordReader.java b/pki/base/util/src/com/netscape/cmsutil/password/PlainPasswordReader.java
index 27a39cb6..4065fd72 100644
--- a/pki/base/util/src/com/netscape/cmsutil/password/PlainPasswordReader.java
+++ b/pki/base/util/src/com/netscape/cmsutil/password/PlainPasswordReader.java
@@ -22,7 +22,7 @@ import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
-public class PlainPasswordReader implements IPasswordReader{
+public class PlainPasswordReader implements IPasswordReader {
private String mPwdPath = "";
private Properties mPwdStore;
@@ -30,24 +30,23 @@ public class PlainPasswordReader implements IPasswordReader{
}
public void init(String pwdPath)
- throws IOException
- {
- mPwdStore = new Properties();
- // initialize mPwdStore
- mPwdPath = pwdPath;
- mPwdStore = new Properties();
+ throws IOException {
+ mPwdStore = new Properties();
+ // initialize mPwdStore
+ mPwdPath = pwdPath;
+ mPwdStore = new Properties();
- FileInputStream file = new FileInputStream(mPwdPath);
- mPwdStore.load(file);
- file.close();
+ FileInputStream file = new FileInputStream(mPwdPath);
+ mPwdStore.load(file);
+ file.close();
}
public String getPassword(String tag) {
- return (String) mPwdStore.getProperty(tag);
+ return (String) mPwdStore.getProperty(tag);
}
// return an array of String-based tag
public Enumeration getTags() {
- return mPwdStore.propertyNames();
+ return mPwdStore.propertyNames();
}
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/password/PlainPasswordWriter.java b/pki/base/util/src/com/netscape/cmsutil/password/PlainPasswordWriter.java
index 0cd29a18..3ceac4bd 100644
--- a/pki/base/util/src/com/netscape/cmsutil/password/PlainPasswordWriter.java
+++ b/pki/base/util/src/com/netscape/cmsutil/password/PlainPasswordWriter.java
@@ -22,7 +22,7 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
-public class PlainPasswordWriter implements IPasswordWriter{
+public class PlainPasswordWriter implements IPasswordWriter {
private static final String PASSWORD_WRITER_HEADER = "";
private String mPwdPath = "";
private Properties mPwdStore;
@@ -31,28 +31,26 @@ public class PlainPasswordWriter implements IPasswordWriter{
}
public void init(String pwdPath)
- throws IOException
- {
- mPwdStore = new Properties();
- // initialize mPwdStore
- mPwdPath = pwdPath;
- mPwdStore = new Properties();
-
- FileInputStream file = new FileInputStream(mPwdPath);
- mPwdStore.load(file);
- file.close();
+ throws IOException {
+ mPwdStore = new Properties();
+ // initialize mPwdStore
+ mPwdPath = pwdPath;
+ mPwdStore = new Properties();
+
+ FileInputStream file = new FileInputStream(mPwdPath);
+ mPwdStore.load(file);
+ file.close();
}
public Object putPassword(String tag, String password) {
- return mPwdStore.setProperty(tag, password);
+ return mPwdStore.setProperty(tag, password);
}
public void commit()
- throws IOException, ClassCastException, NullPointerException
- {
- FileOutputStream file = new FileOutputStream(mPwdPath);
- mPwdStore.store(file, PASSWORD_WRITER_HEADER);
- file.close();
+ throws IOException, ClassCastException, NullPointerException {
+ FileOutputStream file = new FileOutputStream(mPwdPath);
+ mPwdStore.store(file, PASSWORD_WRITER_HEADER);
+ file.close();
}
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/AccessAccept.java b/pki/base/util/src/com/netscape/cmsutil/radius/AccessAccept.java
index c5f9828c..4824c885 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/AccessAccept.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/AccessAccept.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class AccessAccept extends ServerPacket {
public AccessAccept(byte data[]) throws IOException {
super(data);
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/AccessChallenge.java b/pki/base/util/src/com/netscape/cmsutil/radius/AccessChallenge.java
index bab34ffe..c06f809b 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/AccessChallenge.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/AccessChallenge.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class AccessChallenge extends ServerPacket {
public AccessChallenge(byte data[]) throws IOException {
super(data);
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/AccessReject.java b/pki/base/util/src/com/netscape/cmsutil/radius/AccessReject.java
index 12081a6b..5f32ef34 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/AccessReject.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/AccessReject.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class AccessReject extends ServerPacket {
public AccessReject(byte data[]) throws IOException {
super(data);
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/AccessRequest.java b/pki/base/util/src/com/netscape/cmsutil/radius/AccessRequest.java
index 5075f932..7856b0cc 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/AccessRequest.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/AccessRequest.java
@@ -17,9 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
-
-
public class AccessRequest extends NASPacket {
public AccessRequest(short id, Authenticator auth) {
super(ACCESS_REQUEST, id, auth);
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/Attribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/Attribute.java
index 33c1f392..5e79816e 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/Attribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/Attribute.java
@@ -17,13 +17,11 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
-
public abstract class Attribute {
- public static final int USER_NAME = 1;
+ public static final int USER_NAME = 1;
public static final int USER_PASSWORD = 2;
public static final int CHAP_PASSWORD = 3;
public static final int NAS_IP_ADDRESS = 4;
@@ -81,12 +79,12 @@ public abstract class Attribute {
return _t;
}
- public abstract byte[] getValue()
- throws IOException;
+ public abstract byte[] getValue()
+ throws IOException;
- public byte[] getData()
- throws IOException {
- ByteArrayOutputStream attrOS = new ByteArrayOutputStream();
+ public byte[] getData()
+ throws IOException {
+ ByteArrayOutputStream attrOS = new ByteArrayOutputStream();
attrOS.write(_t); // type
byte value[] = getValue();
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/AttributeFactory.java b/pki/base/util/src/com/netscape/cmsutil/radius/AttributeFactory.java
index bf236972..ec7fefaf 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/AttributeFactory.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/AttributeFactory.java
@@ -17,13 +17,11 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class AttributeFactory {
public static Attribute createAttribute(byte data[])
- throws IOException {
+ throws IOException {
switch (data[0] & 0xFF) {
case Attribute.USER_NAME: // 1
return new UserNameAttribute(data);
@@ -52,13 +50,13 @@ public class AttributeFactory {
case Attribute.FRAMED_IP_NETMASK: // 9
return new FramedIPNetmaskAttribute(data);
- case Attribute.FRAMED_ROUTING: // 10
+ case Attribute.FRAMED_ROUTING: // 10
return new FramedRoutingAttribute(data);
- case Attribute.FILTER_ID: // 11
+ case Attribute.FILTER_ID: // 11
return new FilterIdAttribute(data);
- case Attribute.FRAMED_MTU: // 12
+ case Attribute.FRAMED_MTU: // 12
return new FramedMTUAttribute(data);
case Attribute.FRAMED_COMPRESSION: // 13
@@ -79,73 +77,73 @@ public class AttributeFactory {
case Attribute.CALLBACK_NUMBER: // 19
return new CallbackNumberAttribute(data);
- case Attribute.CALLBACK_ID: // 20
+ case Attribute.CALLBACK_ID: // 20
return new CallbackIdAttribute(data);
- case Attribute.FRAMED_ROUTE: // 22
+ case Attribute.FRAMED_ROUTE: // 22
return new FramedRouteAttribute(data);
- case Attribute.FRAMED_IPX_NETWORK: // 23
+ case Attribute.FRAMED_IPX_NETWORK: // 23
return new FramedIPXNetworkAttribute(data);
- case Attribute.STATE: // 24
+ case Attribute.STATE: // 24
return new StateAttribute(data);
- case Attribute.NAS_CLASS: // 25
+ case Attribute.NAS_CLASS: // 25
return new NASClassAttribute(data);
- case Attribute.VENDOR_SPECIFIC: // 26
+ case Attribute.VENDOR_SPECIFIC: // 26
return new VendorSpecificAttribute(data);
- case Attribute.SESSION_TIMEOUT: // 27
+ case Attribute.SESSION_TIMEOUT: // 27
return new SessionTimeoutAttribute(data);
- case Attribute.IDLE_TIMEOUT: // 28
+ case Attribute.IDLE_TIMEOUT: // 28
return new IdleTimeoutAttribute(data);
- case Attribute.TERMINATION_ACTION: // 29
+ case Attribute.TERMINATION_ACTION: // 29
return new TerminationActionAttribute(data);
- case Attribute.CALLER_STATION_ID: // 30
+ case Attribute.CALLER_STATION_ID: // 30
return new CallerStationIdAttribute(data);
- case Attribute.CALLING_STATION_ID: // 31
+ case Attribute.CALLING_STATION_ID: // 31
return new CallingStationIdAttribute(data);
- case Attribute.NAS_IDENTIFIER: // 32
+ case Attribute.NAS_IDENTIFIER: // 32
return new NASIdentifierAttribute(data);
- case Attribute.PROXY_STATE: // 33
+ case Attribute.PROXY_STATE: // 33
return new ProxyStateAttribute(data);
- case Attribute.LOGIN_LAT_SERVICE: // 34
+ case Attribute.LOGIN_LAT_SERVICE: // 34
return new LoginLATServiceAttribute(data);
- case Attribute.LOGIN_LAT_NODE: // 35
+ case Attribute.LOGIN_LAT_NODE: // 35
return new LoginLATNodeAttribute(data);
- case Attribute.LOGIN_LAT_GROUP: // 36
+ case Attribute.LOGIN_LAT_GROUP: // 36
return new LoginLATGroupAttribute(data);
- case Attribute.FRAMED_APPLETALK_LINK: // 37
+ case Attribute.FRAMED_APPLETALK_LINK: // 37
return new FramedAppleTalkLinkAttribute(data);
- case Attribute.FRAMED_APPLETALK_NETWORK: // 38
+ case Attribute.FRAMED_APPLETALK_NETWORK: // 38
return new FramedAppleTalkNetworkAttribute(data);
- case Attribute.FRAMED_APPLETALK_ZONE: // 39
+ case Attribute.FRAMED_APPLETALK_ZONE: // 39
return new FramedAppleTalkZoneAttribute(data);
- case Attribute.CHAP_CHALLENGE: // 60
+ case Attribute.CHAP_CHALLENGE: // 60
return new CHAPChallengeAttribute(data);
- case Attribute.NAS_PORT_TYPE: // 61
+ case Attribute.NAS_PORT_TYPE: // 61
return new NASPortTypeAttribute(data);
- case Attribute.PORT_LIMIT: // 62
+ case Attribute.PORT_LIMIT: // 62
return new PortLimitAttribute(data);
- case Attribute.LOGIN_LAT_PORT: // 63
+ case Attribute.LOGIN_LAT_PORT: // 63
return new LoginLATPortAttribute(data);
default:
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/AttributeSet.java b/pki/base/util/src/com/netscape/cmsutil/radius/AttributeSet.java
index e79b96f7..46860de1 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/AttributeSet.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/AttributeSet.java
@@ -17,11 +17,9 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.util.Enumeration;
import java.util.Vector;
-
public class AttributeSet {
private Vector _attrs = new Vector();
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/Authenticator.java b/pki/base/util/src/com/netscape/cmsutil/radius/Authenticator.java
index 3236d9b6..008af489 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/Authenticator.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/Authenticator.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public abstract class Authenticator {
public abstract byte[] getData() throws IOException;
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/CHAPChallengeAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/CHAPChallengeAttribute.java
index 8b2655c2..cd715a03 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/CHAPChallengeAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/CHAPChallengeAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class CHAPChallengeAttribute extends Attribute {
private String _str = null;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/CHAPPasswordAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/CHAPPasswordAttribute.java
index 90ebea14..3f0ef179 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/CHAPPasswordAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/CHAPPasswordAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class CHAPPasswordAttribute extends Attribute {
private byte _value[] = null;
private int _ident = 0;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/CallbackIdAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/CallbackIdAttribute.java
index 894ae9c8..5fd80600 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/CallbackIdAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/CallbackIdAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class CallbackIdAttribute extends Attribute {
private byte _value[] = null;
private String _str = null;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/CallbackNumberAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/CallbackNumberAttribute.java
index 96e4af79..d6e45cec 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/CallbackNumberAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/CallbackNumberAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class CallbackNumberAttribute extends Attribute {
private byte _value[] = null;
private String _str = null;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/CallerStationIdAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/CallerStationIdAttribute.java
index 05e4836d..3b5eec80 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/CallerStationIdAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/CallerStationIdAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class CallerStationIdAttribute extends Attribute {
private byte _value[] = null;
private String _str = null;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/CallingStationIdAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/CallingStationIdAttribute.java
index b1f77b69..9a57f808 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/CallingStationIdAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/CallingStationIdAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class CallingStationIdAttribute extends Attribute {
private byte _value[] = null;
private String _str = null;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/ChallengeException.java b/pki/base/util/src/com/netscape/cmsutil/radius/ChallengeException.java
index de1222a3..b0580118 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/ChallengeException.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/ChallengeException.java
@@ -17,9 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
-
-
public class ChallengeException extends Exception {
/**
*
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/FilterIdAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/FilterIdAttribute.java
index c8d9abf8..879d7d5c 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/FilterIdAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/FilterIdAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class FilterIdAttribute extends Attribute {
private byte _value[] = null;
private String _str = null;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkLinkAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkLinkAttribute.java
index 2176fbc0..05273780 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkLinkAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkLinkAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class FramedAppleTalkLinkAttribute extends Attribute {
public static int UN_NUMBERED = 0;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkNetworkAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkNetworkAttribute.java
index 6ea0c05f..cea0d936 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkNetworkAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkNetworkAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class FramedAppleTalkNetworkAttribute extends Attribute {
private byte _value[] = null;
private int _type = 0;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkZoneAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkZoneAttribute.java
index 3ea8c654..54ee47c4 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkZoneAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkZoneAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class FramedAppleTalkZoneAttribute extends Attribute {
private byte _value[] = null;
private String _str = null;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/FramedCompressionAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/FramedCompressionAttribute.java
index cf21b9fd..b57c030b 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/FramedCompressionAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/FramedCompressionAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class FramedCompressionAttribute extends Attribute {
public static final int NONE = 1;
public static final int VJ_TCP_IP_HEADER = 2;
@@ -33,9 +31,9 @@ public class FramedCompressionAttribute extends Attribute {
public FramedCompressionAttribute(byte value[]) {
super();
_t = FRAMED_COMPRESSION;
- _type = value[5] & 0xFF;
- _type |= ((value[4] << 8) & 0xFF00);
- _type |= ((value[3] << 16) & 0xFF0000);
+ _type = value[5] & 0xFF;
+ _type |= ((value[4] << 8) & 0xFF00);
+ _type |= ((value[3] << 16) & 0xFF0000);
_type |= ((value[2] << 24) & 0xFF000000);
_value = value;
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/FramedIPAddressAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/FramedIPAddressAttribute.java
index 1fac0a3f..2f66ee8c 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/FramedIPAddressAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/FramedIPAddressAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class FramedIPAddressAttribute extends Attribute {
private byte _value[] = null;
private byte _addr[] = new byte[4];
@@ -28,10 +26,10 @@ public class FramedIPAddressAttribute extends Attribute {
public FramedIPAddressAttribute(byte value[]) {
super();
_t = FRAMED_IP_ADDRESS;
- _addr[0] = value[2];
- _addr[1] = value[3];
- _addr[2] = value[4];
- _addr[3] = value[5];
+ _addr[0] = value[2];
+ _addr[1] = value[3];
+ _addr[2] = value[4];
+ _addr[3] = value[5];
_value = value;
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/FramedIPNetmaskAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/FramedIPNetmaskAttribute.java
index 9350fac1..f8e1980c 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/FramedIPNetmaskAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/FramedIPNetmaskAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class FramedIPNetmaskAttribute extends Attribute {
private byte _value[] = null;
private byte _mask[] = new byte[4];
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/FramedIPXNetworkAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/FramedIPXNetworkAttribute.java
index 900c46c0..92f47eec 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/FramedIPXNetworkAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/FramedIPXNetworkAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class FramedIPXNetworkAttribute extends Attribute {
private byte _value[] = null;
private byte _net[] = new byte[4];
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/FramedMTUAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/FramedMTUAttribute.java
index b3a36233..5cd9551a 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/FramedMTUAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/FramedMTUAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class FramedMTUAttribute extends Attribute {
private byte _value[] = null;
private int _type = 0;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/FramedProtocolAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/FramedProtocolAttribute.java
index 1acee4ce..5af219b9 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/FramedProtocolAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/FramedProtocolAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class FramedProtocolAttribute extends Attribute {
public static final int PPP = 1;
public static final int SLIP = 2;
@@ -35,9 +33,9 @@ public class FramedProtocolAttribute extends Attribute {
public FramedProtocolAttribute(byte value[]) {
super();
_t = SERVICE_TYPE;
- _type = value[5] & 0xFF;
- _type |= ((value[4] << 8) & 0xFF00);
- _type |= ((value[3] << 16) & 0xFF0000);
+ _type = value[5] & 0xFF;
+ _type |= ((value[4] << 8) & 0xFF00);
+ _type |= ((value[3] << 16) & 0xFF0000);
_type |= ((value[2] << 24) & 0xFF000000);
_value = value;
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/FramedRouteAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/FramedRouteAttribute.java
index bc49adb0..9b123fe2 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/FramedRouteAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/FramedRouteAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class FramedRouteAttribute extends Attribute {
private byte _value[] = null;
private String _str = null;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/FramedRoutingAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/FramedRoutingAttribute.java
index 1ea4e334..14d2b0cc 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/FramedRoutingAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/FramedRoutingAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class FramedRoutingAttribute extends Attribute {
public static final int NONE = 0;
public static final int SEND_ROUTING_PACKETS = 1;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/GenericAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/GenericAttribute.java
index c368a271..ac1798ae 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/GenericAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/GenericAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class GenericAttribute extends Attribute {
private byte _value[] = null;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/IdleTimeoutAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/IdleTimeoutAttribute.java
index 38b45a6c..44b0c508 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/IdleTimeoutAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/IdleTimeoutAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class IdleTimeoutAttribute extends Attribute {
private int _timeout = 0;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/LoginIPHostAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/LoginIPHostAttribute.java
index 7bfe179f..0d1c0565 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/LoginIPHostAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/LoginIPHostAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class LoginIPHostAttribute extends Attribute {
public static final int NAS_ALLOW_SELECT = 0xFFFFFFFF;
public static final int NAS_SELECT = 0;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/LoginLATGroupAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/LoginLATGroupAttribute.java
index 93a50766..4cee6bc3 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/LoginLATGroupAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/LoginLATGroupAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class LoginLATGroupAttribute extends Attribute {
private byte _value[] = null;
private String _str = null;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/LoginLATNodeAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/LoginLATNodeAttribute.java
index 38b4b315..2c2d3411 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/LoginLATNodeAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/LoginLATNodeAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class LoginLATNodeAttribute extends Attribute {
private byte _value[] = null;
private String _str = null;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/LoginLATPortAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/LoginLATPortAttribute.java
index 056b0fc4..330161ec 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/LoginLATPortAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/LoginLATPortAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class LoginLATPortAttribute extends Attribute {
private byte _value[] = null;
private String _str = null;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/LoginLATServiceAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/LoginLATServiceAttribute.java
index 7409a83a..158630d2 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/LoginLATServiceAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/LoginLATServiceAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class LoginLATServiceAttribute extends Attribute {
private byte _value[] = null;
private String _str = null;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/LoginServiceAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/LoginServiceAttribute.java
index 88f5623b..73f49d39 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/LoginServiceAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/LoginServiceAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class LoginServiceAttribute extends Attribute {
public static final int TELNET = 0;
public static final int RLOGIN = 1;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/LoginTCPPortAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/LoginTCPPortAttribute.java
index 0c924f69..6b44f50c 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/LoginTCPPortAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/LoginTCPPortAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class LoginTCPPortAttribute extends Attribute {
private int _port = 0;
@@ -43,12 +41,12 @@ public class LoginTCPPortAttribute extends Attribute {
}
public byte[] getValue() throws IOException {
- byte[] p = new byte[4];
+ byte[] p = new byte[4];
- p[0] = (byte) ((_port >>> 24) & 0xFF);
- p[1] = (byte) ((_port >>> 16) & 0xFF);
- p[2] = (byte) ((_port >>> 8) & 0xFF);
- p[3] = (byte) (_port & 0xFF);
+ p[0] = (byte) ((_port >>> 24) & 0xFF);
+ p[1] = (byte) ((_port >>> 16) & 0xFF);
+ p[2] = (byte) ((_port >>> 8) & 0xFF);
+ p[3] = (byte) (_port & 0xFF);
return p;
}
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/NASClassAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/NASClassAttribute.java
index ba644f20..57b98302 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/NASClassAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/NASClassAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class NASClassAttribute extends Attribute {
private byte _value[] = null;
private String _str = null;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/NASIPAddressAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/NASIPAddressAttribute.java
index 42dc1a19..d4022b3d 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/NASIPAddressAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/NASIPAddressAttribute.java
@@ -17,11 +17,9 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
import java.net.InetAddress;
-
public class NASIPAddressAttribute extends Attribute {
private InetAddress _ip = null;
private byte _value[] = null;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/NASIdentifierAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/NASIdentifierAttribute.java
index 99917cac..0a3a62cd 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/NASIdentifierAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/NASIdentifierAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class NASIdentifierAttribute extends Attribute {
private byte _value[] = null;
private String _str = null;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/NASPacket.java b/pki/base/util/src/com/netscape/cmsutil/radius/NASPacket.java
index b270eadd..70d14398 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/NASPacket.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/NASPacket.java
@@ -17,11 +17,9 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
-
public abstract class NASPacket extends Packet {
public NASPacket(int c, short id, Authenticator auth) {
super(c, id, auth);
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/NASPortAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/NASPortAttribute.java
index 949fa475..0f7b31e7 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/NASPortAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/NASPortAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class NASPortAttribute extends Attribute {
private int _port = 0;
@@ -39,12 +37,12 @@ public class NASPortAttribute extends Attribute {
}
public byte[] getValue() throws IOException {
- byte[] p = new byte[4];
+ byte[] p = new byte[4];
- p[0] = (byte) ((_port >>> 24) & 0xFF);
- p[1] = (byte) ((_port >>> 16) & 0xFF);
- p[2] = (byte) ((_port >>> 8) & 0xFF);
- p[3] = (byte) (_port & 0xFF);
+ p[0] = (byte) ((_port >>> 24) & 0xFF);
+ p[1] = (byte) ((_port >>> 16) & 0xFF);
+ p[2] = (byte) ((_port >>> 8) & 0xFF);
+ p[3] = (byte) (_port & 0xFF);
return p;
}
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/NASPortTypeAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/NASPortTypeAttribute.java
index ca7cf7b0..84ccc3ae 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/NASPortTypeAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/NASPortTypeAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class NASPortTypeAttribute extends Attribute {
public static final int ASYNC = 0;
public static final int SYNC = 1;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/Packet.java b/pki/base/util/src/com/netscape/cmsutil/radius/Packet.java
index 4af44563..902da857 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/Packet.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/Packet.java
@@ -17,17 +17,14 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
-
-
public abstract class Packet {
- public static final int ACCESS_REQUEST = 1;
- public static final int ACCESS_ACCEPT = 2;
- public static final int ACCESS_REJECT = 3;
- // public static final int ACCOUNTING_REQUEST = 4;
- // public static final int ACCOUNTING_RESPONSE = 5;
+ public static final int ACCESS_REQUEST = 1;
+ public static final int ACCESS_ACCEPT = 2;
+ public static final int ACCESS_REJECT = 3;
+ // public static final int ACCOUNTING_REQUEST = 4;
+ // public static final int ACCOUNTING_RESPONSE = 5;
public static final int ACCESS_CHALLENGE = 11;
- public static final int RESERVED = 255;
+ public static final int RESERVED = 255;
protected int _c = 0;
protected short _id = 0;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/PacketFactory.java b/pki/base/util/src/com/netscape/cmsutil/radius/PacketFactory.java
index c9dd1620..8d2e20e7 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/PacketFactory.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/PacketFactory.java
@@ -17,13 +17,11 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class PacketFactory {
public static ServerPacket createServerPacket(byte data[])
- throws IOException {
+ throws IOException {
switch (data[0] & 0xFF) {
case Packet.ACCESS_ACCEPT:
return new AccessAccept(data);
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/PortLimitAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/PortLimitAttribute.java
index 602603cb..7903bb1f 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/PortLimitAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/PortLimitAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class PortLimitAttribute extends Attribute {
private int _port = 0;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/ProxyStateAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/ProxyStateAttribute.java
index ef04ae0c..83831b65 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/ProxyStateAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/ProxyStateAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class ProxyStateAttribute extends Attribute {
private byte _value[] = null;
private String _str = null;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/RadiusConn.java b/pki/base/util/src/com/netscape/cmsutil/radius/RadiusConn.java
index 1c09ea2c..1caf940d 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/RadiusConn.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/RadiusConn.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.DatagramPacket;
@@ -28,10 +27,9 @@ import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Properties;
-
/**
- * This class implements RFC2865 - Remote Authentication Dial In
- * User Service (RADIUS), June 2000.
+ * This class implements RFC2865 - Remote Authentication Dial In User Service
+ * (RADIUS), June 2000.
*/
public class RadiusConn {
public static int MAX_RETRIES = 10;
@@ -52,20 +50,20 @@ public class RadiusConn {
private int _maxRetries = MAX_RETRIES;
private SecureRandom _rand = null;
- public RadiusConn(String host1, String host2, int port, String secret,
- int timeout) throws SocketException {
+ public RadiusConn(String host1, String host2, int port, String secret,
+ int timeout) throws SocketException {
this(host1, port, host2, port, secret, timeout, null, null);
}
public RadiusConn(String host, int port, String secret, byte seed[],
- Properties options)
- throws SocketException {
+ Properties options)
+ throws SocketException {
this(host, port, host, port, secret, DEFAULT_TIMEOUT, seed, options);
}
- public RadiusConn(String host1, int port1, String host2, int port2,
- String secret, int timeout, byte seed[], Properties options)
- throws SocketException {
+ public RadiusConn(String host1, int port1, String host2, int port2,
+ String secret, int timeout, byte seed[], Properties options)
+ throws SocketException {
_host[0] = host1;
_port[0] = port1;
_host[1] = host2;
@@ -73,7 +71,7 @@ public class RadiusConn {
_selected = 0;
_secret = secret;
_options = options;
- _socket = new DatagramSocket();
+ _socket = new DatagramSocket();
_socket.setSoTimeout(timeout * 1000);
if (seed == null) {
_rand = new SecureRandom();
@@ -86,8 +84,8 @@ public class RadiusConn {
_socket.disconnect();
}
- public void authenticate(String name, String password)
- throws IOException, NoSuchAlgorithmException,
+ public void authenticate(String name, String password)
+ throws IOException, NoSuchAlgorithmException,
RejectException, ChallengeException {
int retries = 0;
Packet res = null;
@@ -104,7 +102,7 @@ public class RadiusConn {
send(req, _host[_selected], _port[_selected]);
try {
retries++;
- res = receive();
+ res = receive();
if (res instanceof AccessReject) {
throw new RejectException((AccessReject) res);
} else if (res instanceof AccessChallenge) {
@@ -121,24 +119,23 @@ public class RadiusConn {
}
// throw e;
}
-
+
}
- }
- while (res == null);
+ } while (res == null);
}
public void replyChallenge(String password, ChallengeException ce)
- throws IOException, NoSuchAlgorithmException,
+ throws IOException, NoSuchAlgorithmException,
RejectException, ChallengeException {
replyChallenge(null, password, ce);
}
- public void replyChallenge(String name, String password,
- ChallengeException ce)
- throws IOException, NoSuchAlgorithmException,
+ public void replyChallenge(String name, String password,
+ ChallengeException ce)
+ throws IOException, NoSuchAlgorithmException,
RejectException, ChallengeException {
StateAttribute state = (StateAttribute)
- ce.getAttributeSet().getAttributeByType(Attribute.STATE);
+ ce.getAttributeSet().getAttributeByType(Attribute.STATE);
if (state == null)
throw new IOException("State not found in challenge");
@@ -154,7 +151,7 @@ public class RadiusConn {
req.addAttribute(new NASPortAttribute(_socket.getLocalPort()));
send(req, _host[_selected], _port[_selected]);
- Packet res = receive();
+ Packet res = receive();
if (res instanceof AccessReject) {
throw new RejectException((AccessReject) res);
@@ -164,7 +161,7 @@ public class RadiusConn {
}
public void replyChallenge(String name, String password, String state)
- throws IOException, NoSuchAlgorithmException,
+ throws IOException, NoSuchAlgorithmException,
RejectException, ChallengeException {
if (state == null)
throw new IOException("State not found in challenge");
@@ -178,7 +175,7 @@ public class RadiusConn {
req.addAttribute(new NASPortAttribute(_socket.getLocalPort()));
send(req, _host[_selected], _port[_selected]);
- Packet res = receive();
+ Packet res = receive();
if (res instanceof AccessReject) {
throw new RejectException((AccessReject) res);
@@ -192,12 +189,12 @@ public class RadiusConn {
}
private void send(NASPacket packet, String host, int port)
- throws IOException {
- DatagramPacket dp = new DatagramPacket(new byte[4096], 4096);
+ throws IOException {
+ DatagramPacket dp = new DatagramPacket(new byte[4096], 4096);
- dp.setPort(port);
- dp.setAddress(InetAddress.getByName(host));
- byte data[] = packet.getData();
+ dp.setPort(port);
+ dp.setAddress(InetAddress.getByName(host));
+ byte data[] = packet.getData();
dp.setLength(data.length);
dp.setData(data);
@@ -207,10 +204,10 @@ public class RadiusConn {
}
private ServerPacket receive()
- throws IOException {
- DatagramPacket dp = new DatagramPacket(new byte[4096], 4096);
+ throws IOException {
+ DatagramPacket dp = new DatagramPacket(new byte[4096], 4096);
- _socket.receive(dp);
+ _socket.receive(dp);
byte data[] = dp.getData();
ServerPacket p = PacketFactory.createServerPacket(data);
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/RejectException.java b/pki/base/util/src/com/netscape/cmsutil/radius/RejectException.java
index d80b045e..1c4e7bea 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/RejectException.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/RejectException.java
@@ -17,9 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
-
-
public class RejectException extends Exception {
/**
*
@@ -37,5 +34,5 @@ public class RejectException extends Exception {
public String getReplyMessage() {
return ((ReplyMessageAttribute) (_res.getAttributeSet().getAttributeByType(Attribute.REPLY_MESSAGE))).getString();
- }
+ }
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/ReplyMessageAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/ReplyMessageAttribute.java
index 094a5173..5ec4ea05 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/ReplyMessageAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/ReplyMessageAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class ReplyMessageAttribute extends Attribute {
private byte _value[] = null;
private String _str = null;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/RequestAuthenticator.java b/pki/base/util/src/com/netscape/cmsutil/radius/RequestAuthenticator.java
index 108b5145..5d82752d 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/RequestAuthenticator.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/RequestAuthenticator.java
@@ -17,18 +17,16 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
-
public class RequestAuthenticator extends Authenticator {
private byte _ra[] = null;
- public RequestAuthenticator(SecureRandom rand, String secret)
- throws NoSuchAlgorithmException {
+ public RequestAuthenticator(SecureRandom rand, String secret)
+ throws NoSuchAlgorithmException {
byte[] authenticator = new byte[16];
rand.nextBytes(authenticator);
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/ResponseAuthenticator.java b/pki/base/util/src/com/netscape/cmsutil/radius/ResponseAuthenticator.java
index 93fd46c3..3c3de33c 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/ResponseAuthenticator.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/ResponseAuthenticator.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class ResponseAuthenticator extends Authenticator {
private byte _data[] = null;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/ServerPacket.java b/pki/base/util/src/com/netscape/cmsutil/radius/ServerPacket.java
index abbe255f..f7d7fa30 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/ServerPacket.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/ServerPacket.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public abstract class ServerPacket extends Packet {
public ServerPacket(byte data[]) throws IOException {
super();
@@ -41,8 +39,8 @@ public abstract class ServerPacket extends Packet {
int attrLen = (data[startp + 1] & 0xFF);
byte attrData[] = new byte[attrLen];
- System.arraycopy(data, startp, attrData, 0, attrData.length);
- addAttribute(AttributeFactory.createAttribute(attrData));
+ System.arraycopy(data, startp, attrData, 0, attrData.length);
+ addAttribute(AttributeFactory.createAttribute(attrData));
startp += attrData.length;
}
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/ServiceTypeAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/ServiceTypeAttribute.java
index 7ab143f7..f31c74f9 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/ServiceTypeAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/ServiceTypeAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class ServiceTypeAttribute extends Attribute {
public static final int LOGIN = 1;
public static final int FRAMED = 2;
@@ -40,9 +38,9 @@ public class ServiceTypeAttribute extends Attribute {
public ServiceTypeAttribute(byte value[]) {
super();
_t = SERVICE_TYPE;
- _type = value[5] & 0xFF;
- _type |= ((value[4] << 8) & 0xFF00);
- _type |= ((value[3] << 16) & 0xFF0000);
+ _type = value[5] & 0xFF;
+ _type |= ((value[4] << 8) & 0xFF00);
+ _type |= ((value[3] << 16) & 0xFF0000);
_type |= ((value[2] << 24) & 0xFF000000);
_value = value;
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/SessionTimeoutAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/SessionTimeoutAttribute.java
index fcbf6942..2809aee4 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/SessionTimeoutAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/SessionTimeoutAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class SessionTimeoutAttribute extends Attribute {
private int _timeout = 0;
@@ -39,12 +37,12 @@ public class SessionTimeoutAttribute extends Attribute {
}
public byte[] getValue() throws IOException {
- byte[] p = new byte[4];
+ byte[] p = new byte[4];
- p[0] = (byte) ((_timeout >>> 24) & 0xFF);
- p[1] = (byte) ((_timeout >>> 16) & 0xFF);
- p[2] = (byte) ((_timeout >>> 8) & 0xFF);
- p[3] = (byte) (_timeout & 0xFF);
+ p[0] = (byte) ((_timeout >>> 24) & 0xFF);
+ p[1] = (byte) ((_timeout >>> 16) & 0xFF);
+ p[2] = (byte) ((_timeout >>> 8) & 0xFF);
+ p[3] = (byte) (_timeout & 0xFF);
return p;
}
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/StateAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/StateAttribute.java
index 4408819a..027f9562 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/StateAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/StateAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class StateAttribute extends Attribute {
private byte _value[] = null;
private String _str = null;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/TerminationActionAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/TerminationActionAttribute.java
index 67f214ad..b47a70d8 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/TerminationActionAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/TerminationActionAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class TerminationActionAttribute extends Attribute {
public static final int DEFAULT = 0;
public static final int RADIUS_REQUEST = 1;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/UserNameAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/UserNameAttribute.java
index ccc715e5..af7ce6bb 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/UserNameAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/UserNameAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class UserNameAttribute extends Attribute {
private String _name = null;
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/UserPasswordAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/UserPasswordAttribute.java
index 938652e0..31c27cdf 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/UserPasswordAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/UserPasswordAttribute.java
@@ -17,12 +17,10 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
-
public class UserPasswordAttribute extends Attribute {
private Authenticator _ra = null;
private String _secret = null;
@@ -43,7 +41,7 @@ public class UserPasswordAttribute extends Attribute {
MessageDigest md5 = null;
try {
- md5 = MessageDigest.getInstance("MD5");
+ md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new IOException(e.getMessage());
}
@@ -57,7 +55,7 @@ public class UserPasswordAttribute extends Attribute {
for (int i = 0; i < ret.length; i++) {
if ((i % 16) == 0) {
- md5.reset();
+ md5.reset();
md5.update(_secret.getBytes());
}
if (i < up.length) {
diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/VendorSpecificAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/VendorSpecificAttribute.java
index e3f17416..5f3d9f17 100644
--- a/pki/base/util/src/com/netscape/cmsutil/radius/VendorSpecificAttribute.java
+++ b/pki/base/util/src/com/netscape/cmsutil/radius/VendorSpecificAttribute.java
@@ -17,10 +17,8 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.radius;
-
import java.io.IOException;
-
public class VendorSpecificAttribute extends Attribute {
private byte _value[] = null;
private String _id = null;
diff --git a/pki/base/util/src/com/netscape/cmsutil/scep/CRSPKIMessage.java b/pki/base/util/src/com/netscape/cmsutil/scep/CRSPKIMessage.java
index ae93d2b6..14a6fe7a 100644
--- a/pki/base/util/src/com/netscape/cmsutil/scep/CRSPKIMessage.java
+++ b/pki/base/util/src/com/netscape/cmsutil/scep/CRSPKIMessage.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.scep;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.CharConversionException;
@@ -51,70 +50,69 @@ import org.mozilla.jss.pkix.cert.Certificate;
import org.mozilla.jss.pkix.cert.CertificateInfo;
import org.mozilla.jss.pkix.primitive.AlgorithmIdentifier;
-
public class CRSPKIMessage {
-
+
// OIDs for authenticated attributes
- public static OBJECT_IDENTIFIER CRS_MESSAGETYPE =
- new OBJECT_IDENTIFIER(new long[] {2, 16, 840, 1, 113733, 1, 9, 2}
- );
- public static OBJECT_IDENTIFIER CRS_PKISTATUS =
- new OBJECT_IDENTIFIER(new long[] {2, 16, 840, 1, 113733, 1, 9, 3}
- );
- public static OBJECT_IDENTIFIER CRS_FAILINFO =
- new OBJECT_IDENTIFIER(new long[] {2, 16, 840, 1, 113733, 1, 9, 4}
- );
- public static OBJECT_IDENTIFIER CRS_SENDERNONCE =
- new OBJECT_IDENTIFIER(new long[] {2, 16, 840, 1, 113733, 1, 9, 5}
- );
- public static OBJECT_IDENTIFIER CRS_RECIPIENTNONCE =
- new OBJECT_IDENTIFIER(new long[] {2, 16, 840, 1, 113733, 1, 9, 6}
- );
- public static OBJECT_IDENTIFIER CRS_TRANSID =
- new OBJECT_IDENTIFIER(new long[] {2, 16, 840, 1, 113733, 1, 9, 7}
- );
+ public static OBJECT_IDENTIFIER CRS_MESSAGETYPE =
+ new OBJECT_IDENTIFIER(new long[] { 2, 16, 840, 1, 113733, 1, 9, 2 }
+ );
+ public static OBJECT_IDENTIFIER CRS_PKISTATUS =
+ new OBJECT_IDENTIFIER(new long[] { 2, 16, 840, 1, 113733, 1, 9, 3 }
+ );
+ public static OBJECT_IDENTIFIER CRS_FAILINFO =
+ new OBJECT_IDENTIFIER(new long[] { 2, 16, 840, 1, 113733, 1, 9, 4 }
+ );
+ public static OBJECT_IDENTIFIER CRS_SENDERNONCE =
+ new OBJECT_IDENTIFIER(new long[] { 2, 16, 840, 1, 113733, 1, 9, 5 }
+ );
+ public static OBJECT_IDENTIFIER CRS_RECIPIENTNONCE =
+ new OBJECT_IDENTIFIER(new long[] { 2, 16, 840, 1, 113733, 1, 9, 6 }
+ );
+ public static OBJECT_IDENTIFIER CRS_TRANSID =
+ new OBJECT_IDENTIFIER(new long[] { 2, 16, 840, 1, 113733, 1, 9, 7 }
+ );
public static OBJECT_IDENTIFIER CRS_EXTENSIONREQ =
- new OBJECT_IDENTIFIER(new long[] {2, 16, 840, 1, 113733, 1, 9, 8}
- );
-
+ new OBJECT_IDENTIFIER(new long[] { 2, 16, 840, 1, 113733, 1, 9, 8 }
+ );
+
// PKCS9 defined OIDs
public static OBJECT_IDENTIFIER PKCS9_CONTENT_TYPE =
- new OBJECT_IDENTIFIER(new long[] {1, 2, 840, 113549, 1, 9, 3}
- );
+ new OBJECT_IDENTIFIER(new long[] { 1, 2, 840, 113549, 1, 9, 3 }
+ );
public static OBJECT_IDENTIFIER PKCS9_MESSAGE_DIGEST =
- new OBJECT_IDENTIFIER(new long[] {1, 2, 840, 113549, 1, 9, 4}
- );
+ new OBJECT_IDENTIFIER(new long[] { 1, 2, 840, 113549, 1, 9, 4 }
+ );
/* PKCS 1 - rsaEncryption */
public static OBJECT_IDENTIFIER RSA_ENCRYPTION =
- new OBJECT_IDENTIFIER(new long[] {1, 2, 840, 113549, 1, 1, 1}
- );
-
+ new OBJECT_IDENTIFIER(new long[] { 1, 2, 840, 113549, 1, 1, 1 }
+ );
+
public static OBJECT_IDENTIFIER DES_CBC_ENCRYPTION =
- new OBJECT_IDENTIFIER(new long[] {1, 3, 14, 3, 2, 7}
- );
+ new OBJECT_IDENTIFIER(new long[] { 1, 3, 14, 3, 2, 7 }
+ );
public static OBJECT_IDENTIFIER DES_EDE3_CBC_ENCRYPTION =
- new OBJECT_IDENTIFIER(new long[] {1, 2, 840, 113549, 3, 7}
- );
+ new OBJECT_IDENTIFIER(new long[] { 1, 2, 840, 113549, 3, 7 }
+ );
- public static OBJECT_IDENTIFIER MD5_DIGEST =
- new OBJECT_IDENTIFIER(new long[] {1, 2, 840, 113549, 2, 5}
- );
+ public static OBJECT_IDENTIFIER MD5_DIGEST =
+ new OBJECT_IDENTIFIER(new long[] { 1, 2, 840, 113549, 2, 5 }
+ );
- public static OBJECT_IDENTIFIER SHA1_DIGEST =
- new OBJECT_IDENTIFIER(new long[] {1, 3, 14, 3, 2, 26}
- );
+ public static OBJECT_IDENTIFIER SHA1_DIGEST =
+ new OBJECT_IDENTIFIER(new long[] { 1, 3, 14, 3, 2, 26 }
+ );
- public static OBJECT_IDENTIFIER SHA256_DIGEST =
- new OBJECT_IDENTIFIER(new long[] {2, 16, 840, 1, 101, 3, 4, 2, 1}
- );
+ public static OBJECT_IDENTIFIER SHA256_DIGEST =
+ new OBJECT_IDENTIFIER(new long[] { 2, 16, 840, 1, 101, 3, 4, 2, 1 }
+ );
- public static OBJECT_IDENTIFIER SHA512_DIGEST =
- new OBJECT_IDENTIFIER(new long[] {2, 16, 840, 1, 101, 3, 4, 2, 3}
- );
+ public static OBJECT_IDENTIFIER SHA512_DIGEST =
+ new OBJECT_IDENTIFIER(new long[] { 2, 16, 840, 1, 101, 3, 4, 2, 3 }
+ );
// Strings given in 'messageType' authenticated attribute
public final static String mType_PKCSReq = "19";
@@ -122,12 +120,12 @@ public class CRSPKIMessage {
public final static String mType_GetCertInitial = "20";
public final static String mType_GetCert = "21";
public final static String mType_GetCRL = "22";
-
+
// Strings given in 'PKIStatus' authenticated attribute
public final static String mStatus_SUCCESS = "0";
public final static String mStatus_FAILURE = "2";
public final static String mStatus_PENDING = "3";
-
+
// Strings given in 'failInfo' authenticated attribute
public final static String mFailInfo_badAlg = "0";
public final static String mFailInfo_badMessageCheck = "1";
@@ -142,65 +140,66 @@ public class CRSPKIMessage {
public final static String mFailInfo_noKeyReuse = "10";
public final static String mFailInfo_internalCAError = "11";
public final static String mFailInfo_tryLater = "12";
-
+
// ************************************************************************
// These private members represent the flattened structure of the PKIMessage
// ************************************************************************
-
+
// top level is just a ContentInfo
- private ContentInfo crsci;
+ private ContentInfo crsci;
// it's content is a signedData
- private SignedData sd;
+ private SignedData sd;
// In the signed data, we have:
- private int sdv; // Version
- private ContentInfo data; // The data to be digested
- private EnvelopedData sded; // Enveloped data inside of signed data
- private byte[] signerCertBytes;
+ private int sdv; // Version
+ private ContentInfo data; // The data to be digested
+ private EnvelopedData sded; // Enveloped data inside of signed data
+ private byte[] signerCertBytes;
org.mozilla.jss.pkix.cert.Certificate signerCert;
- private SET sis; // set of SignerInfos
- private SignerInfo si; // First SignerInfo
+ private SET sis; // set of SignerInfos
+ private SignerInfo si; // First SignerInfo
private AlgorithmIdentifier digestAlgorithmId = null;
- private int siv; // Version
- private SET aa; // Authenticated Attributes
- private SET aa_old; // Authenticated Attributes
- private IssuerAndSerialNumber sgnIASN; // Signer's Issuer Name and Serialnum
- private OCTET_STRING aa_digest; // digest of the authenticated attrs
-
- private String messageType; // these are all authenticated attributes
- private String failInfo;
- private String pkiStatus;
- private String transactionID;
- private byte[] senderNonce;
- private byte[] recipientNonce;
+ private int siv; // Version
+ private SET aa; // Authenticated Attributes
+ private SET aa_old; // Authenticated Attributes
+ private IssuerAndSerialNumber sgnIASN; // Signer's Issuer Name and Serialnum
+ private OCTET_STRING aa_digest; // digest of the authenticated attrs
+
+ private String messageType; // these are all authenticated attributes
+ private String failInfo;
+ private String pkiStatus;
+ private String transactionID;
+ private byte[] senderNonce;
+ private byte[] recipientNonce;
private OCTET_STRING msg_digest; // digest of the message
// Inside the sded Enveloped data
- private RecipientInfo ri; // First RecipientInfo
- private int riv; // Version
- private AlgorithmIdentifier riAlgid; // alg that the bulk key is wrapped with
- private byte[] riKey; // bulk key, wrapped with above algorithm
- private byte[] cKey; // * 'clear', unwrapped key (not in ASN.1) *
- private IssuerAndSerialNumber rcpIASN; // Recipient's Issuer Name and Serial Number
+ private RecipientInfo ri; // First RecipientInfo
+ private int riv; // Version
+ private AlgorithmIdentifier riAlgid; // alg that the bulk key is wrapped
+ // with
+ private byte[] riKey; // bulk key, wrapped with above algorithm
+ private byte[] cKey; // * 'clear', unwrapped key (not in ASN.1) *
+ private IssuerAndSerialNumber rcpIASN; // Recipient's Issuer Name and Serial
+ // Number
private EncryptedContentInfo eci;
- private byte[] iv; // initialization vector for above key
- private byte[] ec; // encrypted content (P10, in case of request)
- private byte[] cc; // * 'clear' content (not in ASN.1) *
- private String encryptionAlgorithm = null;
+ private byte[] iv; // initialization vector for above key
+ private byte[] ec; // encrypted content (P10, in case of request)
+ private byte[] cc; // * 'clear' content (not in ASN.1) *
+ private String encryptionAlgorithm = null;
// For the CertRep, the enveloped content is another signed Data:
- private SignedData crsd;
- private int rsdVersion;
- private byte[] rsdCert; // certificate to send in response
+ private SignedData crsd;
+ private int rsdVersion;
+ private byte[] rsdCert; // certificate to send in response
- private PKCS10 myP10;
+ private PKCS10 myP10;
- private Hashtable<String, Object> attrs; // miscellanous
-
- // *** END *** //
+ private Hashtable<String, Object> attrs; // miscellanous
+ // *** END *** //
public void debug() {
}
@@ -213,30 +212,28 @@ public class CRSPKIMessage {
return attrs.get(a);
}
- private SignatureAlgorithm getSignatureAlgorithm (String hashAlgorithm)
- {
+ private SignatureAlgorithm getSignatureAlgorithm(String hashAlgorithm) {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.RSASignatureWithMD5Digest;
if (hashAlgorithm != null) {
if (hashAlgorithm.equals("SHA1")) {
signatureAlgorithm = SignatureAlgorithm.RSASignatureWithSHA1Digest;
} else if (hashAlgorithm.equals("SHA256")) {
signatureAlgorithm = SignatureAlgorithm.RSASignatureWithSHA256Digest;
- } else if (hashAlgorithm.equals("SHA512")) {
+ } else if (hashAlgorithm.equals("SHA512")) {
signatureAlgorithm = SignatureAlgorithm.RSASignatureWithSHA512Digest;
}
}
return signatureAlgorithm;
}
- private OBJECT_IDENTIFIER getAlgorithmOID (String hashAlgorithm)
- {
+ private OBJECT_IDENTIFIER getAlgorithmOID(String hashAlgorithm) {
OBJECT_IDENTIFIER oid = MD5_DIGEST;
if (hashAlgorithm != null) {
if (hashAlgorithm.equals("SHA1")) {
oid = SHA1_DIGEST;
} else if (hashAlgorithm.equals("SHA256")) {
oid = SHA256_DIGEST;
- } else if (hashAlgorithm.equals("SHA512")) {
+ } else if (hashAlgorithm.equals("SHA512")) {
oid = SHA512_DIGEST;
}
}
@@ -244,8 +241,7 @@ public class CRSPKIMessage {
}
// getHashAlgorithm is added to work around issue 636217
- private String getHashAlgorithm (OBJECT_IDENTIFIER algorithmOID)
- {
+ private String getHashAlgorithm(OBJECT_IDENTIFIER algorithmOID) {
String hashAlgorithm = null;
OBJECT_IDENTIFIER oid = MD5_DIGEST;
if (algorithmOID != null) {
@@ -255,7 +251,7 @@ public class CRSPKIMessage {
hashAlgorithm = "SHA1";
} else if (algorithmOID.equals(SHA256_DIGEST)) {
hashAlgorithm = "SHA256";
- } else if (algorithmOID.equals(SHA512_DIGEST)) {
+ } else if (algorithmOID.equals(SHA512_DIGEST)) {
hashAlgorithm = "SHA512";
}
}
@@ -265,33 +261,33 @@ public class CRSPKIMessage {
// These functions are used to initialize the various blobs
public void makeSignedData(int version,
- byte[] certificate, String hashAlgorithm) {
+ byte[] certificate, String hashAlgorithm) {
try {
SET digest_algs = new SET();
digest_algs.addElement(new AlgorithmIdentifier(getAlgorithmOID(hashAlgorithm), new NULL()));
-
- // SET certs = new SET();
- // certs.addElement(new ANY(certificate));
-
+
+ // SET certs = new SET();
+ // certs.addElement(new ANY(certificate));
+
SET sis = new SET();
sis.addElement(si);
-
+
ContentInfo data = this.data;
this.sd = new SignedData(
digest_algs,
data,
- null, // don't send the certs, he already has them
- null, // crl's
- sis);
+ null, // don't send the certs, he already has them
+ null, // crl's
+ sis);
} catch (Exception e) {
}
}
-
+
public byte[] getResponse() throws IOException, InvalidBERException {
crsci = new ContentInfo(ContentInfo.SIGNED_DATA,
@@ -304,39 +300,37 @@ public class CRSPKIMessage {
}
/*
- public void makeSignerInfo_old(int version,
- // issuer and serialnumber
- byte[] digest) {
-
- si = new SignerInfo(new INTEGER(version),
- sgnIASN, // issuer and serialnum
- new AlgorithmIdentifier(MD5_DIGEST, new NULL()), // digest algorithm
- this.aa, // Authenticated Attributes
- new AlgorithmIdentifier(RSA_ENCRYPTION,new NULL()), // digest encryption algorithm
- new OCTET_STRING(digest), // digest
- null); // unauthenticated attributes
-
- }
+ * public void makeSignerInfo_old(int version, // issuer and serialnumber
+ * byte[] digest) {
+ *
+ * si = new SignerInfo(new INTEGER(version), sgnIASN, // issuer and
+ * serialnum new AlgorithmIdentifier(MD5_DIGEST, new NULL()), // digest
+ * algorithm this.aa, // Authenticated Attributes new
+ * AlgorithmIdentifier(RSA_ENCRYPTION,new NULL()), // digest encryption
+ * algorithm new OCTET_STRING(digest), // digest null); // unauthenticated
+ * attributes
+ *
+ * }
*/
public void makeSignerInfo(int version,
- // issuer and serialnumber
- org.mozilla.jss.crypto.PrivateKey pk, String hashAlgorithm)
- throws java.security.NoSuchAlgorithmException,
+ // issuer and serialnumber
+ org.mozilla.jss.crypto.PrivateKey pk, String hashAlgorithm)
+ throws java.security.NoSuchAlgorithmException,
TokenException,
java.security.InvalidKeyException,
- java.security.SignatureException,
+ java.security.SignatureException,
org.mozilla.jss.CryptoManager.NotInitializedException {
- si = new SignerInfo(sgnIASN, // issuer and serialnum
- this.aa, // Authenticated Attributes
- null, // Unauthenticated Attrs
- ContentInfo.ENVELOPED_DATA, // content type
- msg_digest.toByteArray(), // digest
- getSignatureAlgorithm(hashAlgorithm),
+ si = new SignerInfo(sgnIASN, // issuer and serialnum
+ this.aa, // Authenticated Attributes
+ null, // Unauthenticated Attrs
+ ContentInfo.ENVELOPED_DATA, // content type
+ msg_digest.toByteArray(), // digest
+ getSignatureAlgorithm(hashAlgorithm),
pk);
}
-
+
public void makeAuthenticatedAttributes() {
aa = new SET();
@@ -348,28 +342,28 @@ public class CRSPKIMessage {
tidset.addElement((new PrintableString(transactionID)));
aa.addElement(new Attribute(CRS_TRANSID, tidset));
}
-
+
if (pkiStatus != null) {
SET pkistatusset = new SET();
pkistatusset.addElement(new PrintableString(pkiStatus));
aa.addElement(new Attribute(CRS_PKISTATUS, pkistatusset));
}
-
+
if (messageType != null) {
SET aaset = new SET();
aaset.addElement(new PrintableString(messageType));
- aa.addElement(new Attribute(CRS_MESSAGETYPE, aaset));
+ aa.addElement(new Attribute(CRS_MESSAGETYPE, aaset));
}
if (failInfo != null) {
SET fiset = new SET();
fiset.addElement(new PrintableString(failInfo));
- aa.addElement(new Attribute(CRS_FAILINFO, fiset));
+ aa.addElement(new Attribute(CRS_FAILINFO, fiset));
}
-
+
if (senderNonce != null) {
SET snset = new SET();
@@ -385,29 +379,29 @@ public class CRSPKIMessage {
}
// XXX sender nonce
-
+
} catch (CharConversionException e) {
}
}
-
+
public byte[] makeEnvelopedData(int version) {
byte[] r;
try {
-
+
if (this.ri != null) {
ContentInfo ci;
SET ris = new SET();
ris.addElement(this.ri);
-
+
this.sded = new EnvelopedData(
new INTEGER(version),
ris,
eci);
-
+
ci = new ContentInfo(ContentInfo.ENVELOPED_DATA,
sded);
ByteArrayOutputStream ba = new ByteArrayOutputStream();
@@ -423,7 +417,7 @@ public class CRSPKIMessage {
return r;
- // return this.sded.getEncodedContents();
+ // return this.sded.getEncodedContents();
} catch (Exception e) {
return null;
}
@@ -434,8 +428,8 @@ public class CRSPKIMessage {
this.riv = version;
this.riAlgid = new AlgorithmIdentifier(RSA_ENCRYPTION, new NULL());
- this.riKey = riKey;
-
+ this.riKey = riKey;
+
this.ri = new RecipientInfo(
new INTEGER(this.riv),
rcpIASN,
@@ -455,7 +449,8 @@ public class CRSPKIMessage {
AlgorithmIdentifier aid = new AlgorithmIdentifier(oid, new OCTET_STRING(iv));
- //eci = EncryptedContentInfo.createCRSCompatibleEncryptedContentInfo(
+ // eci =
+ // EncryptedContentInfo.createCRSCompatibleEncryptedContentInfo(
eci = new EncryptedContentInfo(ContentInfo.DATA,
aid,
new OCTET_STRING(ec)
@@ -471,19 +466,19 @@ public class CRSPKIMessage {
try {
SET certs = new SET();
ANY cert = new ANY(certificate);
-
+
certs.addElement(cert);
-
+
crsd = new SignedData(
- new SET(), // empty set of digestAlgorithmID's
- new ContentInfo(
- new OBJECT_IDENTIFIER(new long[] {1, 2, 840, 113549, 1, 7, 1}
+ new SET(), // empty set of digestAlgorithmID's
+ new ContentInfo(
+ new OBJECT_IDENTIFIER(new long[] { 1, 2, 840, 113549, 1, 7, 1 }
),
- null), //empty content
- certs,
- null, // no CRL's
- new SET() // empty SignerInfos
- );
+ null), // empty content
+ certs,
+ null, // no CRL's
+ new SET() // empty SignerInfos
+ );
ContentInfo wrap = new ContentInfo(ContentInfo.SIGNED_DATA,
crsd);
@@ -492,12 +487,12 @@ public class CRSPKIMessage {
wrap.encode(baos);
return baos.toByteArray();
- // return crsd.getEncodedContents();
+ // return crsd.getEncodedContents();
} catch (Exception e) {
return null;
}
}
-
+
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("{ messageType=");
@@ -509,15 +504,15 @@ public class CRSPKIMessage {
sb.append(", transactionID=");
sb.append(getTransactionID());
sb.append(", senderNonce=");
- sb.append( Arrays.toString( getSenderNonce() ) );
+ sb.append(Arrays.toString(getSenderNonce()));
sb.append(", recipientNonce=");
- sb.append( Arrays.toString( getRecipientNonce() ) );
+ sb.append(Arrays.toString(getRecipientNonce()));
sb.append(" }");
-
+
String s = sb.toString();
return s;
}
-
+
public String getMessageType() {
return messageType;
}
@@ -561,7 +556,7 @@ public class CRSPKIMessage {
public String getDigestAlgorithmName() {
String name = null;
if (digestAlgorithmId != null) {
- name = getHashAlgorithm(digestAlgorithmId.getOID());
+ name = getHashAlgorithm(digestAlgorithmId.getOID());
}
return name;
}
@@ -570,10 +565,10 @@ public class CRSPKIMessage {
try {
org.mozilla.jss.pkix.cert.Certificate.Template ct = new
- org.mozilla.jss.pkix.cert.Certificate.Template();
-
+ org.mozilla.jss.pkix.cert.Certificate.Template();
+
ByteArrayInputStream bais = new ByteArrayInputStream(this.signerCertBytes);
-
+
signerCert = (org.mozilla.jss.pkix.cert.Certificate) ct.decode(bais);
return signerCert.getInfo().getSubjectPublicKeyInfo().toPublicKey();
} catch (Exception e) {
@@ -593,7 +588,7 @@ public class CRSPKIMessage {
}
- public void setAA_old( SET auth_attrs ) {
+ public void setAA_old(SET auth_attrs) {
aa_old = auth_attrs;
}
@@ -613,15 +608,15 @@ public class CRSPKIMessage {
public byte[] getAADigest() {
return aa_digest.toByteArray();
}
-
+
public PKCS10 getP10() {
return myP10;
}
-
+
public void setP10(PKCS10 p10) {
myP10 = p10;
}
-
+
public void setSgnIssuerAndSerialNumber(IssuerAndSerialNumber iasn) {
this.sgnIASN = iasn;
}
@@ -631,7 +626,7 @@ public class CRSPKIMessage {
}
public IssuerAndSerialNumber getSgnIssuerAndSerialNumber() {
- return this.sgnIASN;
+ return this.sgnIASN;
}
public IssuerAndSerialNumber getRcpIssuerAndSerialNumber() {
@@ -662,8 +657,7 @@ public class CRSPKIMessage {
this.senderNonce = sn;
}
- // public void setCertificate(byte [] cert) { this.certificate = cert; }
-
+ // public void setCertificate(byte [] cert) { this.certificate = cert; }
public void setMsgDigest(byte[] digest) {
this.msg_digest = new OCTET_STRING(digest);
@@ -675,53 +669,53 @@ public class CRSPKIMessage {
public void setPending() {
// setIssuerAndSerialNumber();
-
+
setMessageType(mType_CertRep);
setPKIStatus(mStatus_PENDING);
};
-
+
public void setFailure(String failInfo) {
setMessageType(mType_CertRep);
setPKIStatus(mStatus_FAILURE);
setFailInfo(failInfo);
}
-
+
// Should add a Certificate to this call
public void setSuccess() {
setMessageType(mType_CertRep);
setPKIStatus(mStatus_SUCCESS);
}
-
+
/**
- * Gets a byte array which is the der-encoded blob
- * which gets sent back to the router.
+ * Gets a byte array which is the der-encoded blob which gets sent back to
+ * the router.
*/
-
+
public byte[] getEncoded() {
- //Assert.assert(messageType != null);
- //Assert.assert(pkiStatus != null);
-
- return new byte[1]; // blagh
+ // Assert.assert(messageType != null);
+ // Assert.assert(pkiStatus != null);
+
+ return new byte[1]; // blagh
}
-
- private void decodeCRSPKIMessage (ByteArrayInputStream bais) throws InvalidBERException, Exception {
+ private void decodeCRSPKIMessage(ByteArrayInputStream bais) throws InvalidBERException, Exception {
org.mozilla.jss.pkcs7.ContentInfo.Template crscit;
crscit = new ContentInfo.Template();
crsci = (ContentInfo) crscit.decode(bais);
-
- if (!ContentInfo.SIGNED_DATA.equals(crsci.getContentType())) {
+
+ if (!ContentInfo.SIGNED_DATA.equals(crsci.getContentType())) {
throw new Exception("ContentType wasn't signed data, it was" + crsci.getContentType());
}
-
- // Now that we know that the contentInfo is a SignedData, we can decode it
+
+ // Now that we know that the contentInfo is a SignedData, we can decode
+ // it
SignedData.Template sdt = new SignedData.Template();
-
+
sd = (SignedData) sdt.decode(
new ByteArrayInputStream(
- ((ANY) crsci.getContent()).getEncoded()
+ ((ANY) crsci.getContent()).getEncoded()
));
this.decodeSD();
}
@@ -729,34 +723,34 @@ public class CRSPKIMessage {
public CRSPKIMessage() {
attrs = new Hashtable<String, Object>();
}
-
- public CRSPKIMessage (ByteArrayInputStream bais) throws InvalidBERException, Exception {
+
+ public CRSPKIMessage(ByteArrayInputStream bais) throws InvalidBERException, Exception {
attrs = new Hashtable<String, Object>();
decodeCRSPKIMessage(bais);
}
private void decodeSD() throws Exception {
- ContentInfo sdci;
+ ContentInfo sdci;
sis = sd.getSignerInfos();
-
+
decodeSI();
sdci = sd.getContentInfo();
-
+
// HACK to work with CRS
ANY a = (ANY) sdci.getContent();
ByteArrayInputStream s = new ByteArrayInputStream(a.getEncoded());
OCTET_STRING os = (OCTET_STRING) (new OCTET_STRING.Template()).decode(s);
-
+
ByteArrayInputStream s2 = new ByteArrayInputStream(os.toByteArray());
ContentInfo ci = (ContentInfo) (new ContentInfo.Template()).decode(s2);
ByteArrayInputStream s3 = new ByteArrayInputStream(((ANY) ci.getContent()).getEncoded());
-
+
EnvelopedData.Template edt = new EnvelopedData.Template();
sded = (EnvelopedData) edt.decode(s3);
-
+
SET signerCerts = (SET) sd.getCertificates();
Certificate firstCert = (Certificate) signerCerts.elementAt(0);
@@ -766,10 +760,10 @@ public class CRSPKIMessage {
sgnIASN = new IssuerAndSerialNumber(firstCertInfo.getIssuer(),
firstCertInfo.getSerialNumber());
-
+
decodeED();
}
-
+
private void decodeSI() throws Exception {
if (sis.size() == 0) {
throw new Exception("SignerInfos is empty");
@@ -782,12 +776,12 @@ public class CRSPKIMessage {
aa_digest = new OCTET_STRING(si.getEncryptedDigest());
}
-
+
private void decodeED() throws Exception {
SET ris;
ris = (SET) sded.getRecipientInfos();
-
+
if (ris.size() == 0) {
throw new Exception("RecipientInfos is empty");
}
@@ -801,32 +795,30 @@ public class CRSPKIMessage {
} else {
throw new Exception("P10 encrypted alg is not supported (not DES): " + eci.getContentEncryptionAlgorithm().getOID());
}
-
+
ec = eci.getEncryptedContent().toByteArray();
OCTET_STRING.Template ost = new OCTET_STRING.Template();
-
+
OCTET_STRING os = (OCTET_STRING)
- ost.decode(new ByteArrayInputStream(
- ((ANY) eci.getContentEncryptionAlgorithm().getParameters()).getEncoded()
- )
- );
+ ost.decode(new ByteArrayInputStream(
+ ((ANY) eci.getContentEncryptionAlgorithm().getParameters()).getEncoded()
+ )
+ );
iv = os.toByteArray();
decodeRI();
}
-
+
/**
- * The PKCS10 request is encrypt with a symmetric key.
- * This key in turn is encrypted with the RSA key in the
- * CA certificate.
- *
- * riAlgid is the algorithm the symm key is encrypted with. It had
- * better be RSA
- * riKey is the encrypted symmetric key
+ * The PKCS10 request is encrypt with a symmetric key. This key in turn is
+ * encrypted with the RSA key in the CA certificate.
+ *
+ * riAlgid is the algorithm the symm key is encrypted with. It had better be
+ * RSA riKey is the encrypted symmetric key
*/
-
+
private void decodeRI() throws Exception {
// really should get issuer and serial number of our RI, as this
@@ -834,18 +826,18 @@ public class CRSPKIMessage {
// going to assume that the key is the Signing cert for the server.
riAlgid = ri.getKeyEncryptionAlgorithmID();
-
+
if (!riAlgid.getOID().equals(RSA_ENCRYPTION)) {
throw new Exception("Request is protected by a key which we can't decrypt");
}
-
+
riKey = ri.getEncryptedKey().toByteArray();
-
+
}
-
+
private void decodeAA() throws InvalidBERException, IOException {
aa = si.getAuthenticatedAttributes();
-
+
int count;
for (count = 0; count < aa.size(); count++) {
@@ -855,20 +847,20 @@ public class CRSPKIMessage {
PrintableString ps;
PrintableString.Template pst = new PrintableString.Template();
OCTET_STRING.Template ost = new OCTET_STRING.Template();
-
+
OBJECT_IDENTIFIER oid = a.getType();
if (oid.equals(CRS_MESSAGETYPE)) {
ps = (PrintableString) pst.decode(new ByteArrayInputStream(f.getEncoded()));
// We make a new string here
messageType = ps.toString();
-
+
} else if (oid.equals(CRS_PKISTATUS)) {
ps = (PrintableString) pst.decode(new ByteArrayInputStream(f.getEncoded()));
- pkiStatus = new String (ps.toString());
+ pkiStatus = new String(ps.toString());
} else if (oid.equals(CRS_FAILINFO)) {
ps = (PrintableString) pst.decode(new ByteArrayInputStream(f.getEncoded()));
- failInfo = new String (ps.toString());
+ failInfo = new String(ps.toString());
} else if (oid.equals(CRS_SENDERNONCE)) {
OCTET_STRING oss = (OCTET_STRING) ost.decode(new ByteArrayInputStream(f.getEncoded()));
@@ -879,18 +871,18 @@ public class CRSPKIMessage {
recipientNonce = osr.toByteArray();
} else if (oid.equals(CRS_TRANSID)) {
ps = (PrintableString) pst.decode(new ByteArrayInputStream(f.getEncoded()));
- transactionID = new String (ps.toString());
+ transactionID = new String(ps.toString());
}
-
+
}
-
- } // end of decodeAA();
-
+
+ } // end of decodeAA();
+
public String getMessageTypeString() {
if (messageType == null) {
return null;
}
-
+
if (messageType.equals(mType_PKCSReq)) {
return "PKCSReq";
}
@@ -907,8 +899,7 @@ public class CRSPKIMessage {
return "GetCRL";
}
// messageType should match one of the above
- //Assert.assert(false);
+ // Assert.assert(false);
return null;
}
-}
-
+}
diff --git a/pki/base/util/src/com/netscape/cmsutil/util/Cert.java b/pki/base/util/src/com/netscape/cmsutil/util/Cert.java
index d5689ac9..b280a760 100644
--- a/pki/base/util/src/com/netscape/cmsutil/util/Cert.java
+++ b/pki/base/util/src/com/netscape/cmsutil/util/Cert.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.util;
-
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509CRL;
@@ -63,13 +62,13 @@ public class Cert {
}
if ((s.startsWith("-----BEGIN CERTIFICATE-----")) &&
- (s.endsWith("-----END CERTIFICATE-----"))) {
+ (s.endsWith("-----END CERTIFICATE-----"))) {
return (s.substring(27, (s.length() - 25)));
}
// To support Thawte's header and footer
if ((s.startsWith("-----BEGIN PKCS #7 SIGNED DATA-----")) &&
- (s.endsWith("-----END PKCS #7 SIGNED DATA-----"))) {
+ (s.endsWith("-----END PKCS #7 SIGNED DATA-----"))) {
return (s.substring(35, (s.length() - 33)));
}
@@ -81,23 +80,23 @@ public class Cert {
return s;
}
if ((s.startsWith("-----BEGIN CERTIFICATE REVOCATION LIST-----")) &&
- (s.endsWith("-----END CERTIFICATE REVOCATION LIST-----"))) {
+ (s.endsWith("-----END CERTIFICATE REVOCATION LIST-----"))) {
return (s.substring(43, (s.length() - 41)));
}
return s;
}
public static String stripCertBrackets(String s) {
- return stripBrackets(s);
+ return stripBrackets(s);
}
- // private static BASE64Decoder mDecoder = new BASE64Decoder();
+ // private static BASE64Decoder mDecoder = new BASE64Decoder();
public static X509CertImpl mapCert(String mime64)
- throws IOException {
+ throws IOException {
mime64 = stripCertBrackets(mime64.trim());
String newval = normalizeCertStr(mime64);
- // byte rawPub[] = mDecoder.decodeBuffer(newval);
- byte rawPub[] = OSUtil.AtoB( newval );
+ // byte rawPub[] = mDecoder.decodeBuffer(newval);
+ byte rawPub[] = OSUtil.AtoB(newval);
X509CertImpl cert = null;
try {
@@ -108,27 +107,27 @@ public class Cert {
}
public static X509Certificate[] mapCertFromPKCS7(String mime64)
- throws IOException {
+ throws IOException {
mime64 = stripCertBrackets(mime64.trim());
String newval = normalizeCertStr(mime64);
- // byte rawPub[] = mDecoder.decodeBuffer(newval);
- byte rawPub[] = OSUtil.AtoB( newval );
+ // byte rawPub[] = mDecoder.decodeBuffer(newval);
+ byte rawPub[] = OSUtil.AtoB(newval);
PKCS7 p7 = null;
try {
p7 = new PKCS7(rawPub);
} catch (Exception e) {
- throw new IOException( "p7 is null" );
+ throw new IOException("p7 is null");
}
return p7.getCertificates();
}
public static X509CRL mapCRL(String mime64)
- throws IOException {
+ throws IOException {
mime64 = stripCRLBrackets(mime64.trim());
String newval = normalizeCertStr(mime64);
- // byte rawPub[] = mDecoder.decodeBuffer(newval);
- byte rawPub[] = OSUtil.AtoB( newval );
+ // byte rawPub[] = mDecoder.decodeBuffer(newval);
+ byte rawPub[] = OSUtil.AtoB(newval);
X509CRL crl = null;
try {
@@ -139,7 +138,7 @@ public class Cert {
}
public static X509CRL mapCRL1(String mime64)
- throws IOException {
+ throws IOException {
mime64 = stripCRLBrackets(mime64.trim());
byte rawPub[] = OSUtil.AtoB(mime64);
@@ -187,4 +186,3 @@ public class Cert {
return val;
}
}
-
diff --git a/pki/base/util/src/com/netscape/cmsutil/util/Fmt.java b/pki/base/util/src/com/netscape/cmsutil/util/Fmt.java
index 49b878c4..6e469737 100644
--- a/pki/base/util/src/com/netscape/cmsutil/util/Fmt.java
+++ b/pki/base/util/src/com/netscape/cmsutil/util/Fmt.java
@@ -45,7 +45,6 @@ package com.netscape.cmsutil.util;
// Visit the ACME Labs Java page for up-to-date versions of this and other
// fine Java utilities: http://www.acme.com/java/
-
/// Some simple single-arg sprintf-like routines.
// <P>
// It is apparently impossible to declare a Java method that accepts
@@ -110,13 +109,13 @@ package com.netscape.cmsutil.util;
public class Fmt {
// Flags.
- /// Zero-fill.
+ // / Zero-fill.
public static final int ZF = 1;
- /// Left justify.
+ // / Left justify.
public static final int LJ = 2;
- /// Hexadecimal.
+ // / Hexadecimal.
public static final int HX = 4;
- /// Octal.
+ // / Octal.
public static final int OC = 8;
// Was a number - internal use.
private static final int WN = 16;
@@ -205,7 +204,7 @@ public class Fmt {
if ((l & 0xf000000000000000L) != 0)
return fmt(
Long.toString(l >>> 60, 16) +
- fmt(l & 0x0fffffffffffffffL, 15, HX | ZF),
+ fmt(l & 0x0fffffffffffffffL, 15, HX | ZF),
minWidth, flags | WN);
else
return fmt(Long.toString(l, 16), minWidth, flags | WN);
@@ -213,7 +212,7 @@ public class Fmt {
if ((l & 0x8000000000000000L) != 0)
return fmt(
Long.toString(l >>> 63, 8) +
- fmt(l & 0x7fffffffffffffffL, 21, OC | ZF),
+ fmt(l & 0x7fffffffffffffffL, 21, OC | ZF),
minWidth, flags | WN);
else
return fmt(Long.toString(l, 8), minWidth, flags | WN);
@@ -276,7 +275,7 @@ public class Fmt {
public static String fmt(char c, int minWidth, int flags) {
// return fmt( Character.toString( c ), minWidth, flags );
- // Character currently lacks a static toString method. Workaround
+ // Character currently lacks a static toString method. Workaround
// is to make a temporary instance and use the instance toString.
return fmt(Character.valueOf(c).toString(), minWidth, flags);
}
@@ -375,8 +374,8 @@ public class Fmt {
int numFigs = number.length();
int fracFigs = fraction.length();
- if( ( numFigs == 0 || number.toString().equals( "0" ) ) &&
- fracFigs > 0 ) {
+ if ((numFigs == 0 || number.toString().equals("0")) &&
+ fracFigs > 0) {
// Don't count leading zeros in the fraction.
numFigs = 0;
for (int i = 0; i < fraction.length(); ++i) {
@@ -394,11 +393,11 @@ public class Fmt {
} else if (sigFigs < mantFigs && sigFigs >= numFigs) {
// Want fewer figures in the fraction; chop.
fraction.setLength(
- fraction.length() - (fracFigs - (sigFigs - numFigs)));
+ fraction.length() - (fracFigs - (sigFigs - numFigs)));
// Round?
} else if (sigFigs < numFigs) {
// Want fewer figures in the number; turn them to zeros.
- fraction.setLength(0); // should already be zero, but make sure
+ fraction.setLength(0); // should already be zero, but make sure
for (int i = sigFigs; i < numFigs; ++i)
number.setCharAt(i, '0');
// Round?
@@ -411,10 +410,10 @@ public class Fmt {
return sign + number + "." + fraction + exponent;
}
- /// Improved version of Double.toString(), returns more decimal places.
+ // / Improved version of Double.toString(), returns more decimal places.
// <P>
// The JDK 1.0.2 version of Double.toString() returns only six decimal
- // places on some systems. In JDK 1.1 full precision is returned on
+ // places on some systems. In JDK 1.1 full precision is returned on
// all platforms.
// @deprecated
// @see java.lang.Double.toString
@@ -427,7 +426,7 @@ public class Fmt {
if (d == Double.POSITIVE_INFINITY)
return "Inf";
- // Grab the sign, and then make the number positive for simplicity.
+ // Grab the sign, and then make the number positive for simplicity.
boolean negative = false;
if (d < 0.0D) {
@@ -471,19 +470,21 @@ public class Fmt {
else
num = Integer.parseInt(numStr);
- // Build the new mantissa.
+ // Build the new mantissa.
StringBuffer newMantBuf = new StringBuffer(numStr + ".");
double p = Math.pow(10, exp);
double frac = d - num * p;
String digits = "0123456789";
- int nDigits = 16 - numStr.length(); // about 16 digits in a double
+ int nDigits = 16 - numStr.length(); // about 16 digits in a double
for (int i = 0; i < nDigits; ++i) {
p /= 10.0D;
int dig = (int) (frac / p);
- if (dig < 0) dig = 0;
- if (dig > 9) dig = 9;
+ if (dig < 0)
+ dig = 0;
+ if (dig > 9)
+ dig = 9;
newMantBuf.append(digits.charAt(dig));
frac -= dig * p;
}
@@ -507,7 +508,7 @@ public class Fmt {
break;
}
if (roundMore) {
- // If this happens, we need to prepend a 1. But I haven't
+ // If this happens, we need to prepend a 1. But I haven't
// found a test case yet, so I'm leaving it out for now.
// But if you get this message, please let me know!
newMantBuf.append("ROUNDMORE");
@@ -519,86 +520,55 @@ public class Fmt {
while (newMantBuf.charAt(len - 1) == '0')
newMantBuf.setLength(--len);
- // And chop a trailing dot, if any.
+ // And chop a trailing dot, if any.
if (newMantBuf.charAt(len - 1) == '.')
newMantBuf.setLength(--len);
- // Done.
+ // Done.
return (negative ? "-" : "") +
- newMantBuf +
- (expStr.length() != 0 ? ("e" + expStr) : "");
+ newMantBuf +
+ (expStr.length() != 0 ? ("e" + expStr) : "");
}
/******************************************************************************
- /// Test program.
- public static void main( String[] args )
- {
- System.out.println( "Starting tests." );
- show( Fmt.fmt( "Hello there." ) );
- show( Fmt.fmt( 123 ) );
- show( Fmt.fmt( 123, 10 ) );
- show( Fmt.fmt( 123, 10, Fmt.ZF ) );
- show( Fmt.fmt( 123, 10, Fmt.LJ ) );
- show( Fmt.fmt( -123 ) );
- show( Fmt.fmt( -123, 10 ) );
- show( Fmt.fmt( -123, 10, Fmt.ZF ) );
- show( Fmt.fmt( -123, 10, Fmt.LJ ) );
- show( Fmt.fmt( (byte) 0xbe, 22, Fmt.OC ) );
- show( Fmt.fmt( (short) 0xbabe, 22, Fmt.OC ) );
- show( Fmt.fmt( 0xcafebabe, 22, Fmt.OC ) );
- show( Fmt.fmt( 0xdeadbeefcafebabeL, 22, Fmt.OC ) );
- show( Fmt.fmt( 0x8000000000000000L, 22, Fmt.OC ) );
- show( Fmt.fmt( (byte) 0xbe, 16, Fmt.HX ) );
- show( Fmt.fmt( (short) 0xbabe, 16, Fmt.HX ) );
- show( Fmt.fmt( 0xcafebabe, 16, Fmt.HX ) );
- show( Fmt.fmt( 0xdeadbeefcafebabeL, 16, Fmt.HX ) );
- show( Fmt.fmt( 0x8000000000000000L, 16, Fmt.HX ) );
- show( Fmt.fmt( 'c' ) );
- show( Fmt.fmt( new java.util.Date() ) );
- show( Fmt.fmt( 123.456F ) );
- show( Fmt.fmt( 123456000000000000.0F ) );
- show( Fmt.fmt( 123.456F, 0, 8 ) );
- show( Fmt.fmt( 123.456F, 0, 7 ) );
- show( Fmt.fmt( 123.456F, 0, 6 ) );
- show( Fmt.fmt( 123.456F, 0, 5 ) );
- show( Fmt.fmt( 123.456F, 0, 4 ) );
- show( Fmt.fmt( 123.456F, 0, 3 ) );
- show( Fmt.fmt( 123.456F, 0, 2 ) );
- show( Fmt.fmt( 123.456F, 0, 1 ) );
- show( Fmt.fmt( 123456000000000000.0F, 0, 4 ) );
- show( Fmt.fmt( -123.456F, 0, 4 ) );
- show( Fmt.fmt( -123456000000000000.0F, 0, 4 ) );
- show( Fmt.fmt( 123.0F ) );
- show( Fmt.fmt( 123.0D ) );
- show( Fmt.fmt( 1.234567890123456789F ) );
- show( Fmt.fmt( 1.234567890123456789D ) );
- show( Fmt.fmt( 1234567890123456789F ) );
- show( Fmt.fmt( 1234567890123456789D ) );
- show( Fmt.fmt( 0.000000000000000000001234567890123456789F ) );
- show( Fmt.fmt( 0.000000000000000000001234567890123456789D ) );
- show( Fmt.fmt( 12300.0F ) );
- show( Fmt.fmt( 12300.0D ) );
- show( Fmt.fmt( 123000.0F ) );
- show( Fmt.fmt( 123000.0D ) );
- show( Fmt.fmt( 1230000.0F ) );
- show( Fmt.fmt( 1230000.0D ) );
- show( Fmt.fmt( 12300000.0F ) );
- show( Fmt.fmt( 12300000.0D ) );
- show( Fmt.fmt( Float.NaN ) );
- show( Fmt.fmt( Float.POSITIVE_INFINITY ) );
- show( Fmt.fmt( Float.NEGATIVE_INFINITY ) );
- show( Fmt.fmt( Double.NaN ) );
- show( Fmt.fmt( Double.POSITIVE_INFINITY ) );
- show( Fmt.fmt( Double.NEGATIVE_INFINITY ) );
- show( Fmt.fmt( 1.0F / 8.0F ) );
- show( Fmt.fmt( 1.0D / 8.0D ) );
- System.out.println( "Done with tests." );
- }
-
- private static void show( String str )
- {
- System.out.println( "#" + str + "#" );
- }
- ******************************************************************************/
+ * /// Test program. public static void main( String[] args ) {
+ * System.out.println( "Starting tests." ); show( Fmt.fmt( "Hello there." )
+ * ); show( Fmt.fmt( 123 ) ); show( Fmt.fmt( 123, 10 ) ); show( Fmt.fmt(
+ * 123, 10, Fmt.ZF ) ); show( Fmt.fmt( 123, 10, Fmt.LJ ) ); show( Fmt.fmt(
+ * -123 ) ); show( Fmt.fmt( -123, 10 ) ); show( Fmt.fmt( -123, 10, Fmt.ZF )
+ * ); show( Fmt.fmt( -123, 10, Fmt.LJ ) ); show( Fmt.fmt( (byte) 0xbe, 22,
+ * Fmt.OC ) ); show( Fmt.fmt( (short) 0xbabe, 22, Fmt.OC ) ); show( Fmt.fmt(
+ * 0xcafebabe, 22, Fmt.OC ) ); show( Fmt.fmt( 0xdeadbeefcafebabeL, 22,
+ * Fmt.OC ) ); show( Fmt.fmt( 0x8000000000000000L, 22, Fmt.OC ) ); show(
+ * Fmt.fmt( (byte) 0xbe, 16, Fmt.HX ) ); show( Fmt.fmt( (short) 0xbabe, 16,
+ * Fmt.HX ) ); show( Fmt.fmt( 0xcafebabe, 16, Fmt.HX ) ); show( Fmt.fmt(
+ * 0xdeadbeefcafebabeL, 16, Fmt.HX ) ); show( Fmt.fmt( 0x8000000000000000L,
+ * 16, Fmt.HX ) ); show( Fmt.fmt( 'c' ) ); show( Fmt.fmt( new
+ * java.util.Date() ) ); show( Fmt.fmt( 123.456F ) ); show( Fmt.fmt(
+ * 123456000000000000.0F ) ); show( Fmt.fmt( 123.456F, 0, 8 ) ); show(
+ * Fmt.fmt( 123.456F, 0, 7 ) ); show( Fmt.fmt( 123.456F, 0, 6 ) ); show(
+ * Fmt.fmt( 123.456F, 0, 5 ) ); show( Fmt.fmt( 123.456F, 0, 4 ) ); show(
+ * Fmt.fmt( 123.456F, 0, 3 ) ); show( Fmt.fmt( 123.456F, 0, 2 ) ); show(
+ * Fmt.fmt( 123.456F, 0, 1 ) ); show( Fmt.fmt( 123456000000000000.0F, 0, 4 )
+ * ); show( Fmt.fmt( -123.456F, 0, 4 ) ); show( Fmt.fmt(
+ * -123456000000000000.0F, 0, 4 ) ); show( Fmt.fmt( 123.0F ) ); show(
+ * Fmt.fmt( 123.0D ) ); show( Fmt.fmt( 1.234567890123456789F ) ); show(
+ * Fmt.fmt( 1.234567890123456789D ) ); show( Fmt.fmt( 1234567890123456789F )
+ * ); show( Fmt.fmt( 1234567890123456789D ) ); show( Fmt.fmt(
+ * 0.000000000000000000001234567890123456789F ) ); show( Fmt.fmt(
+ * 0.000000000000000000001234567890123456789D ) ); show( Fmt.fmt( 12300.0F )
+ * ); show( Fmt.fmt( 12300.0D ) ); show( Fmt.fmt( 123000.0F ) ); show(
+ * Fmt.fmt( 123000.0D ) ); show( Fmt.fmt( 1230000.0F ) ); show( Fmt.fmt(
+ * 1230000.0D ) ); show( Fmt.fmt( 12300000.0F ) ); show( Fmt.fmt(
+ * 12300000.0D ) ); show( Fmt.fmt( Float.NaN ) ); show( Fmt.fmt(
+ * Float.POSITIVE_INFINITY ) ); show( Fmt.fmt( Float.NEGATIVE_INFINITY ) );
+ * show( Fmt.fmt( Double.NaN ) ); show( Fmt.fmt( Double.POSITIVE_INFINITY )
+ * ); show( Fmt.fmt( Double.NEGATIVE_INFINITY ) ); show( Fmt.fmt( 1.0F /
+ * 8.0F ) ); show( Fmt.fmt( 1.0D / 8.0D ) ); System.out.println(
+ * "Done with tests." ); }
+ *
+ * private static void show( String str ) { System.out.println( "#" + str +
+ * "#" ); }
+ ******************************************************************************/
}
diff --git a/pki/base/util/src/com/netscape/cmsutil/util/HMACDigest.java b/pki/base/util/src/com/netscape/cmsutil/util/HMACDigest.java
index e77e37a5..eae8cc5f 100644
--- a/pki/base/util/src/com/netscape/cmsutil/util/HMACDigest.java
+++ b/pki/base/util/src/com/netscape/cmsutil/util/HMACDigest.java
@@ -17,14 +17,12 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.util;
-
import java.security.MessageDigest;
-
/**
- * This class implements the HMAC algorithm specified in RFC 2104 using
- * any MessageDigest.
- *
+ * This class implements the HMAC algorithm specified in RFC 2104 using any
+ * MessageDigest.
+ *
* @author mikep
* @version $Revision$, $Date$
* @see java.security.MessageDigest
@@ -51,20 +49,20 @@ public class HMACDigest implements Cloneable {
/**
* Creates an HMACDigest
- *
- * @param md The MessageDigest to be used for the HMAC calculation. It
- * must be clonable.
+ *
+ * @param md The MessageDigest to be used for the HMAC calculation. It must
+ * be clonable.
*/
public HMACDigest(MessageDigest md) {
mMD = md;
}
/**
- * Creates an HMACDigest and initializes the HMAC function
- * with the given key.
- *
- * @param md The MessageDigest to be used for the HMAC calculation. It
- * must be clonable.
+ * Creates an HMACDigest and initializes the HMAC function with the given
+ * key.
+ *
+ * @param md The MessageDigest to be used for the HMAC calculation. It must
+ * be clonable.
* @param key The key value to be used in the HMAC calculation
*/
public HMACDigest(MessageDigest md, byte[] key) {
@@ -81,18 +79,16 @@ public class HMACDigest implements Cloneable {
/**
* Initialize the HMAC function
- *
+ *
* The HMAC transform looks like:
- *
- * hash(key XOR opad, hash(key XOR ipad, text))
- *
- * where key is an n byte key
- * ipad is the byte 0x36 repeated 64 times
- * opad is the byte 0x5c repeated 64 times
- * and text is the data being protected
- *
+ *
+ * hash(key XOR opad, hash(key XOR ipad, text))
+ *
+ * where key is an n byte key ipad is the byte 0x36 repeated 64 times opad
+ * is the byte 0x5c repeated 64 times and text is the data being protected
+ *
* This routine must be called after every reset.
- *
+ *
* @param key The password used to protect the hash value
*/
public void init(byte[] key) {
@@ -106,7 +102,7 @@ public class HMACDigest implements Cloneable {
mMD.reset(); // Redundant?
}
- // Copy the key. Truncate if key is too long
+ // Copy the key. Truncate if key is too long
for (i = 0; i < key.length && i < PAD_BYTES; i++) {
mKeyIpad[i] = key[i];
mKeyOpad[i] = key[i];
@@ -133,7 +129,7 @@ public class HMACDigest implements Cloneable {
/**
* Updates the digest using the specified array of bytes.
- *
+ *
* @param input the array of bytes.
*/
public void update(byte[] input) {
@@ -141,9 +137,9 @@ public class HMACDigest implements Cloneable {
}
/**
- * Completes the HMAC computation with the outer pad
- * The digest is reset after this call is made.
- *
+ * Completes the HMAC computation with the outer pad The digest is reset
+ * after this call is made.
+ *
* @return the array of bytes for the resulting hash value.
*/
public byte[] digest() {
@@ -175,16 +171,16 @@ public class HMACDigest implements Cloneable {
/**
* Clone the HMACDigest
- *
+ *
* @return a clone if the implementation is cloneable.
- * @exception CloneNotSupportedException if this is called on a
- * MessageDigest implementation that does not support
- * <code>Cloneable</code>.
+ * @exception CloneNotSupportedException if this is called on a
+ * MessageDigest implementation that does not support
+ * <code>Cloneable</code>.
*/
public Object clone() throws CloneNotSupportedException {
int i;
- HMACDigest hd = (HMACDigest) super.clone();
+ HMACDigest hd = (HMACDigest) super.clone();
hd.mKeyOpad = new byte[PAD_BYTES];
hd.mKeyIpad = new byte[PAD_BYTES];
diff --git a/pki/base/util/src/com/netscape/cmsutil/util/Utils.java b/pki/base/util/src/com/netscape/cmsutil/util/Utils.java
index 36933da8..c45fe439 100644
--- a/pki/base/util/src/com/netscape/cmsutil/util/Utils.java
+++ b/pki/base/util/src/com/netscape/cmsutil/util/Utils.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.util;
-
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
@@ -36,64 +35,59 @@ import java.util.Date;
import java.util.Vector;
public class Utils {
- /**
- * Checks if this is NT.
- */
- public static boolean isNT() {
- return ((File.separator).equals("\\"));
- }
+ /**
+ * Checks if this is NT.
+ */
+ public static boolean isNT() {
+ return ((File.separator).equals("\\"));
+ }
- public static boolean exec(String cmd) {
- try {
- String cmds[] = null;
- if (isNT()) {
- // NT
- cmds = new String[3];
- cmds[0] = "cmd";
- cmds[1] = "/c";
- cmds[2] = cmd;
- } else {
- // UNIX
- cmds = new String[3];
- cmds[0] = "/bin/sh";
- cmds[1] = "-c";
- cmds[2] = cmd;
- }
- Process process = Runtime.getRuntime().exec(cmds);
- process.waitFor();
- BufferedReader pOut = null;
- String l = null;
+ public static boolean exec(String cmd) {
+ try {
+ String cmds[] = null;
+ if (isNT()) {
+ // NT
+ cmds = new String[3];
+ cmds[0] = "cmd";
+ cmds[1] = "/c";
+ cmds[2] = cmd;
+ } else {
+ // UNIX
+ cmds = new String[3];
+ cmds[0] = "/bin/sh";
+ cmds[1] = "-c";
+ cmds[2] = cmd;
+ }
+ Process process = Runtime.getRuntime().exec(cmds);
+ process.waitFor();
+ BufferedReader pOut = null;
+ String l = null;
- if (process.exitValue() == 0) {
- /**
- pOut = new BufferedReader(
- new InputStreamReader(process.getInputStream()));
- while ((l = pOut.readLine()) != null) {
- System.out.println(l);
- }
- **/
- return true;
- } else {
- /**
- pOut = new BufferedReader(
- new InputStreamReader(process.getErrorStream()));
- l = null;
- while ((l = pOut.readLine()) != null) {
- System.out.println(l);
- }
- **/
- return false;
- }
- } catch (Exception e) {
- return false;
- }
- }
+ if (process.exitValue() == 0) {
+ /**
+ * pOut = new BufferedReader( new
+ * InputStreamReader(process.getInputStream())); while ((l =
+ * pOut.readLine()) != null) { System.out.println(l); }
+ **/
+ return true;
+ } else {
+ /**
+ * pOut = new BufferedReader( new
+ * InputStreamReader(process.getErrorStream())); l = null; while
+ * ((l = pOut.readLine()) != null) { System.out.println(l); }
+ **/
+ return false;
+ }
+ } catch (Exception e) {
+ return false;
+ }
+ }
- public static String SpecialURLDecode(String s) {
+ public static String SpecialURLDecode(String s) {
if (s == null)
return null;
ByteArrayOutputStream out = new ByteArrayOutputStream(s.length());
-
+
for (int i = 0; i < s.length(); i++) {
int c = (int) s.charAt(i);
@@ -111,11 +105,11 @@ public class Utils {
return out.toString();
}
- public static byte[] SpecialDecode(String s) {
+ public static byte[] SpecialDecode(String s) {
if (s == null)
return null;
ByteArrayOutputStream out = new ByteArrayOutputStream(s.length());
-
+
for (int i = 0; i < s.length(); i++) {
int c = (int) s.charAt(i);
@@ -133,17 +127,17 @@ public class Utils {
return out.toByteArray();
}
- public static String SpecialEncode(byte data[]) {
+ public static String SpecialEncode(byte data[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < data.length; i++) {
- sb.append("%");
- if ((data[i] & 0xff) < 16) {
- sb.append("0");
- }
- sb.append(Integer.toHexString((data[i] & 0xff)));
+ sb.append("%");
+ if ((data[i] & 0xff) < 16) {
+ sb.append("0");
+ }
+ sb.append(Integer.toHexString((data[i] & 0xff)));
}
return sb.toString().toUpperCase();
- }
+ }
public static void checkHost(String hostname) throws UnknownHostException {
InetAddress addr = InetAddress.getByName(hostname);
@@ -151,17 +145,17 @@ public class Utils {
public static void copy(String orig, String dest) {
try {
- BufferedReader in = new BufferedReader(new FileReader(orig));
- PrintWriter out = new PrintWriter(
- new BufferedWriter(new FileWriter(dest)));
- String line = "";
- while (in.ready()) {
- line = in.readLine();
- if (line != null)
- out.println(line);
- }
- in.close();
- out.close();
+ BufferedReader in = new BufferedReader(new FileReader(orig));
+ PrintWriter out = new PrintWriter(
+ new BufferedWriter(new FileWriter(dest)));
+ String line = "";
+ while (in.ready()) {
+ line = in.readLine();
+ if (line != null)
+ out.println(line);
+ }
+ in.close();
+ out.close();
} catch (Exception ee) {
}
}
@@ -184,8 +178,8 @@ public class Utils {
}
}
- /// Sorts an array of Strings.
- // Java currently has no general sort function. Sorting Strings is
+ // / Sorts an array of Strings.
+ // Java currently has no general sort function. Sorting Strings is
// common enough that it's worth making a special case.
public static void sortStrings(String[] strings) {
// Just does a bubblesort.
@@ -201,8 +195,8 @@ public class Utils {
}
}
- /// Returns a date string formatted in Unix ls style - if it's within
- // six months of now, Mmm dd hh:ss, else Mmm dd yyyy.
+ // / Returns a date string formatted in Unix ls style - if it's within
+ // six months of now, Mmm dd hh:ss, else Mmm dd yyyy.
public static String lsDateStr(Date date) {
long dateTime = date.getTime();
@@ -230,9 +224,10 @@ public class Utils {
}
return true;
}
-
+
/**
* strips out double quotes around String parameter
+ *
* @param s the string potentially bracketed with double quotes
* @return string stripped of surrounding double quotes
*/
@@ -249,9 +244,8 @@ public class Utils {
}
/**
- * returns an array of strings from a vector of Strings
- * there'll be trouble if the Vector contains something other
- * than just Strings
+ * returns an array of strings from a vector of Strings there'll be trouble
+ * if the Vector contains something other than just Strings
*/
public static String[] getStringArrayFromVector(Vector v) {
String s[] = new String[v.size()];
diff --git a/pki/base/util/src/com/netscape/cmsutil/xml/XMLObject.java b/pki/base/util/src/com/netscape/cmsutil/xml/XMLObject.java
index a012f1a0..203700a6 100644
--- a/pki/base/util/src/com/netscape/cmsutil/xml/XMLObject.java
+++ b/pki/base/util/src/com/netscape/cmsutil/xml/XMLObject.java
@@ -16,6 +16,7 @@
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.xml;
+
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
@@ -43,8 +44,7 @@ import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;
-public class XMLObject
-{
+public class XMLObject {
private Document mDoc = null;
public XMLObject() throws ParserConfigurationException {
@@ -53,15 +53,15 @@ public class XMLObject
mDoc = docBuilder.newDocument();
}
- public XMLObject(InputStream s)
- throws SAXException, IOException, ParserConfigurationException {
+ public XMLObject(InputStream s)
+ throws SAXException, IOException, ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = factory.newDocumentBuilder();
mDoc = docBuilder.parse(s);
}
- public XMLObject(File f)
- throws SAXException, IOException, ParserConfigurationException {
+ public XMLObject(File f)
+ throws SAXException, IOException, ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = factory.newDocumentBuilder();
mDoc = docBuilder.parse(f);
@@ -77,16 +77,16 @@ public class XMLObject
public Node createRoot(String name) {
Element root = mDoc.createElement(name);
mDoc.appendChild(root);
- return (Node)root;
+ return (Node) root;
}
public Node getRoot() {
return mDoc.getFirstChild();
}
- /**
- * If you have duplicate containers, then this method will return the
- * first container in the list.
+ /**
+ * If you have duplicate containers, then this method will return the first
+ * container in the list.
*/
public Node getContainer(String tagname) {
NodeList list = mDoc.getElementsByTagName(tagname);
@@ -98,7 +98,7 @@ public class XMLObject
public Node createContainer(Node containerParent, String containerName) {
Element node = mDoc.createElement(containerName);
containerParent.appendChild(node);
- return (Node)node;
+ return (Node) node;
}
public void addItemToContainer(Node container, String tagname, String value) {
@@ -109,7 +109,7 @@ public class XMLObject
}
public String getValue(String tagname) {
- Node n = getContainer(tagname);
+ Node n = getContainer(tagname);
if (n != null) {
NodeList c = n.getChildNodes();
@@ -125,7 +125,7 @@ public class XMLObject
public Vector getAllValues(String tagname) {
Vector v = new Vector();
NodeList nodes = mDoc.getElementsByTagName(tagname);
- for (int i=0; i<nodes.getLength(); i++) {
+ for (int i = 0; i < nodes.getLength(); i++) {
Node n = nodes.item(i);
NodeList c = n.getChildNodes();
if (c.getLength() > 0) {
@@ -141,7 +141,7 @@ public class XMLObject
Vector v = new Vector();
NodeList c = container.getChildNodes();
int len = c.getLength();
- for (int i=0; i<len; i++) {
+ for (int i = 0; i < len; i++) {
Node subchild = c.item(i);
if (subchild.getNodeName().equals(tagname)) {
NodeList grandchildren = subchild.getChildNodes();
@@ -166,8 +166,8 @@ public class XMLObject
return bos.toByteArray();
}
- public void output(OutputStream os)
- throws TransformerConfigurationException, TransformerException {
+ public void output(OutputStream os)
+ throws TransformerConfigurationException, TransformerException {
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();
Source src = new DOMSource(mDoc);
@@ -183,5 +183,5 @@ public class XMLObject
transformer.transform(src, dest);
String xmlString = dest.getWriter().toString();
return xmlString;
- }
+ }
}
diff --git a/pki/base/util/src/netscape/net/NetworkClient.java b/pki/base/util/src/netscape/net/NetworkClient.java
index c9d004d9..9f88efe5 100644
--- a/pki/base/util/src/netscape/net/NetworkClient.java
+++ b/pki/base/util/src/netscape/net/NetworkClient.java
@@ -27,60 +27,61 @@ import java.net.UnknownHostException;
/**
* This is the base class for network clients.
- *
- * @version 1.21, 08/07/97
- * @author Jonathan Payne
+ *
+ * @version 1.21, 08/07/97
+ * @author Jonathan Payne
*/
public class NetworkClient {
/** Socket for communicating with server. */
- protected Socket serverSocket = null;
+ protected Socket serverSocket = null;
/** Stream for printing to the server. */
- public PrintStream serverOutput;
+ public PrintStream serverOutput;
/** Buffered stream for reading replies from server. */
- public InputStream serverInput;
+ public InputStream serverInput;
/** Open a connection to the server. */
public void openServer(String server, int port)
- throws IOException, UnknownHostException {
- if (serverSocket != null)
- closeServer();
- serverSocket = doConnect (server, port);
- serverOutput = new PrintStream(new BufferedOutputStream(serverSocket.getOutputStream()),
- true);
- serverInput = new BufferedInputStream(serverSocket.getInputStream());
+ throws IOException, UnknownHostException {
+ if (serverSocket != null)
+ closeServer();
+ serverSocket = doConnect(server, port);
+ serverOutput = new PrintStream(new BufferedOutputStream(serverSocket.getOutputStream()),
+ true);
+ serverInput = new BufferedInputStream(serverSocket.getInputStream());
}
/**
- * Return a socket connected to the server, with any
- * appropriate options pre-established
+ * Return a socket connected to the server, with any appropriate options
+ * pre-established
*/
- protected Socket doConnect (String server, int port)
- throws IOException, UnknownHostException {
- return new Socket (server, port);
+ protected Socket doConnect(String server, int port)
+ throws IOException, UnknownHostException {
+ return new Socket(server, port);
}
/** Close an open connection to the server. */
public void closeServer() throws IOException {
- if (! serverIsOpen()) {
- return;
- }
- serverSocket.close();
- serverSocket = null;
- serverInput = null;
- serverOutput = null;
+ if (!serverIsOpen()) {
+ return;
+ }
+ serverSocket.close();
+ serverSocket = null;
+ serverInput = null;
+ serverOutput = null;
}
/** Return server connection status */
public boolean serverIsOpen() {
- return serverSocket != null;
+ return serverSocket != null;
}
/** Create connection with host <i>host</i> on port <i>port</i> */
public NetworkClient(String host, int port) throws IOException {
- openServer(host, port);
+ openServer(host, port);
}
- public NetworkClient() {}
+ public NetworkClient() {
+ }
}
diff --git a/pki/base/util/src/netscape/net/TransferProtocolClient.java b/pki/base/util/src/netscape/net/TransferProtocolClient.java
index 23f13317..d2b4f1af 100644
--- a/pki/base/util/src/netscape/net/TransferProtocolClient.java
+++ b/pki/base/util/src/netscape/net/TransferProtocolClient.java
@@ -21,105 +21,108 @@ import java.io.IOException;
import java.util.Vector;
/**
- * This class implements that basic intefaces of transfer protocols.
- * It is used by subclasses implementing specific protocols.
- *
- * @version 1.25, 08/07/97
- * @author Jonathan Payne
+ * This class implements that basic intefaces of transfer protocols. It is used
+ * by subclasses implementing specific protocols.
+ *
+ * @version 1.25, 08/07/97
+ * @author Jonathan Payne
*/
public class TransferProtocolClient extends NetworkClient {
static final boolean debug = false;
- /** Array of strings (usually 1 entry) for the last reply
- from the server. */
- protected Vector serverResponse = new Vector(1);
+ /**
+ * Array of strings (usually 1 entry) for the last reply from the server.
+ */
+ protected Vector serverResponse = new Vector(1);
/** code for last reply */
- protected int lastReplyCode;
-
+ protected int lastReplyCode;
/**
- * Pulls the response from the server and returns the code as a
- * number. Returns -1 on failure.
+ * Pulls the response from the server and returns the code as a number.
+ * Returns -1 on failure.
*/
public int readServerResponse() throws IOException {
- StringBuffer replyBuf = new StringBuffer(32);
- int c;
- int continuingCode = -1;
- int code;
- String response;
+ StringBuffer replyBuf = new StringBuffer(32);
+ int c;
+ int continuingCode = -1;
+ int code;
+ String response;
- serverResponse.setSize(0);
- while (true) {
- while ((c = serverInput.read()) != -1) {
- if (c == '\r') {
- if ((c = serverInput.read()) != '\n')
- replyBuf.append('\r');
- }
- replyBuf.append((char)c);
- if (c == '\n')
- break;
- }
- response = replyBuf.toString();
- replyBuf.setLength(0);
- if (debug) {
- System.out.print(response);
- }
- try {
- code = Integer.parseInt(response.substring(0, 3));
- } catch (NumberFormatException e) {
- code = -1;
- } catch (StringIndexOutOfBoundsException e) {
- /* this line doesn't contain a response code, so
- we just completely ignore it */
- continue;
- }
- serverResponse.addElement(response);
- if (continuingCode != -1) {
- /* we've seen a XXX- sequence */
- if (code != continuingCode ||
- (response.length() >= 4 && response.charAt(3) == '-')) {
- continue;
- } else {
- /* seen the end of code sequence */
- continuingCode = -1;
- break;
- }
- } else if (response.length() >= 4 && response.charAt(3) == '-') {
- continuingCode = code;
- continue;
- } else {
- break;
- }
- }
+ serverResponse.setSize(0);
+ while (true) {
+ while ((c = serverInput.read()) != -1) {
+ if (c == '\r') {
+ if ((c = serverInput.read()) != '\n')
+ replyBuf.append('\r');
+ }
+ replyBuf.append((char) c);
+ if (c == '\n')
+ break;
+ }
+ response = replyBuf.toString();
+ replyBuf.setLength(0);
+ if (debug) {
+ System.out.print(response);
+ }
+ try {
+ code = Integer.parseInt(response.substring(0, 3));
+ } catch (NumberFormatException e) {
+ code = -1;
+ } catch (StringIndexOutOfBoundsException e) {
+ /*
+ * this line doesn't contain a response code, so we just
+ * completely ignore it
+ */
+ continue;
+ }
+ serverResponse.addElement(response);
+ if (continuingCode != -1) {
+ /* we've seen a XXX- sequence */
+ if (code != continuingCode ||
+ (response.length() >= 4 && response.charAt(3) == '-')) {
+ continue;
+ } else {
+ /* seen the end of code sequence */
+ continuingCode = -1;
+ break;
+ }
+ } else if (response.length() >= 4 && response.charAt(3) == '-') {
+ continuingCode = code;
+ continue;
+ } else {
+ break;
+ }
+ }
- return lastReplyCode = code;
+ return lastReplyCode = code;
}
/** Sends command <i>cmd</i> to the server. */
public void sendServer(String cmd) {
- serverOutput.print(cmd);
- if (debug) {
- System.out.print("Sending: " + cmd);
- }
+ serverOutput.print(cmd);
+ if (debug) {
+ System.out.print("Sending: " + cmd);
+ }
}
/** converts the server response into a string. */
public String getResponseString() {
- return (String) serverResponse.elementAt(0);
+ return (String) serverResponse.elementAt(0);
}
/** Returns all server response strings. */
public Vector getResponseStrings() {
- return serverResponse;
+ return serverResponse;
}
/** standard constructor to host <i>host</i>, port <i>port</i>. */
public TransferProtocolClient(String host, int port) throws IOException {
- super(host, port);
+ super(host, port);
}
/** creates an uninitialized instance of this class. */
- public TransferProtocolClient() {}
+ public TransferProtocolClient() {
+ }
}
diff --git a/pki/base/util/src/netscape/net/smtp/SmtpClient.java b/pki/base/util/src/netscape/net/smtp/SmtpClient.java
index 83ff6c09..89ddafc1 100644
--- a/pki/base/util/src/netscape/net/smtp/SmtpClient.java
+++ b/pki/base/util/src/netscape/net/smtp/SmtpClient.java
@@ -25,15 +25,14 @@ import java.net.InetAddress;
import netscape.net.TransferProtocolClient;
/**
- * This class implements the SMTP client.
- * You can send a piece of mail by creating a new SmtpClient, calling
- * the "to" method to add destinations, calling "from" to name the
- * sender, calling startMessage to return a stream to which you write
- * the message (with RFC733 headers) and then you finally close the Smtp
- * Client.
- *
- * @version 1.17, 12 Dec 1994
- * @author James Gosling
+ * This class implements the SMTP client. You can send a piece of mail by
+ * creating a new SmtpClient, calling the "to" method to add destinations,
+ * calling "from" to name the sender, calling startMessage to return a stream to
+ * which you write the message (with RFC733 headers) and then you finally close
+ * the Smtp Client.
+ *
+ * @version 1.17, 12 Dec 1994
+ * @author James Gosling
*/
public class SmtpClient extends TransferProtocolClient {
@@ -43,122 +42,122 @@ public class SmtpClient extends TransferProtocolClient {
* issue the QUIT command to the SMTP server and close the connection.
*/
public void closeServer() throws IOException {
- if (serverIsOpen()) {
- closeMessage();
- issueCommand("QUIT\r\n", 221);
- super.closeServer();
- }
+ if (serverIsOpen()) {
+ closeMessage();
+ issueCommand("QUIT\r\n", 221);
+ super.closeServer();
+ }
}
void issueCommand(String cmd, int expect) throws IOException {
- sendServer(cmd);
- int reply;
- while ((reply = readServerResponse()) != expect)
- if (reply != 220) {
- throw new SmtpProtocolException(getResponseString());
- }
+ sendServer(cmd);
+ int reply;
+ while ((reply = readServerResponse()) != expect)
+ if (reply != 220) {
+ throw new SmtpProtocolException(getResponseString());
+ }
}
private void toCanonical(String s) throws IOException {
- issueCommand("rcpt to: " + s + "\r\n", 250);
+ issueCommand("rcpt to: " + s + "\r\n", 250);
}
public void to(String s) throws IOException {
- int st = 0;
- int limit = s.length();
- int pos = 0;
- int lastnonsp = 0;
- int parendepth = 0;
- boolean ignore = false;
- while (pos < limit) {
- int c = s.charAt(pos);
- if (parendepth > 0) {
- if (c == '(')
- parendepth++;
- else if (c == ')')
- parendepth--;
- if (parendepth == 0)
- if (lastnonsp > st)
- ignore = true;
- else
- st = pos + 1;
- } else if (c == '(')
- parendepth++;
- else if (c == '<')
- st = lastnonsp = pos + 1;
- else if (c == '>')
- ignore = true;
- else if (c == ',') {
- if (lastnonsp > st)
- toCanonical(s.substring(st, lastnonsp));
- st = pos + 1;
- ignore = false;
- } else {
- if (c > ' ' && !ignore)
- lastnonsp = pos + 1;
- else if (st == pos)
- st++;
- }
- pos++;
- }
- if (lastnonsp > st)
- toCanonical(s.substring(st, lastnonsp));
+ int st = 0;
+ int limit = s.length();
+ int pos = 0;
+ int lastnonsp = 0;
+ int parendepth = 0;
+ boolean ignore = false;
+ while (pos < limit) {
+ int c = s.charAt(pos);
+ if (parendepth > 0) {
+ if (c == '(')
+ parendepth++;
+ else if (c == ')')
+ parendepth--;
+ if (parendepth == 0)
+ if (lastnonsp > st)
+ ignore = true;
+ else
+ st = pos + 1;
+ } else if (c == '(')
+ parendepth++;
+ else if (c == '<')
+ st = lastnonsp = pos + 1;
+ else if (c == '>')
+ ignore = true;
+ else if (c == ',') {
+ if (lastnonsp > st)
+ toCanonical(s.substring(st, lastnonsp));
+ st = pos + 1;
+ ignore = false;
+ } else {
+ if (c > ' ' && !ignore)
+ lastnonsp = pos + 1;
+ else if (st == pos)
+ st++;
+ }
+ pos++;
+ }
+ if (lastnonsp > st)
+ toCanonical(s.substring(st, lastnonsp));
}
public void from(String s) throws IOException {
- issueCommand("mail from: " + s + "\r\n", 250);
+ issueCommand("mail from: " + s + "\r\n", 250);
}
/** open a SMTP connection to host <i>host</i>. */
private void openServer(String host) throws IOException {
- openServer(host, 25);
- issueCommand("helo "+InetAddress.getLocalHost().getHostName()+"\r\n", 250);
+ openServer(host, 25);
+ issueCommand("helo " + InetAddress.getLocalHost().getHostName() + "\r\n", 250);
}
public PrintStream startMessage() throws IOException {
- issueCommand("data\r\n", 354);
- return message = new SmtpPrintStream(serverOutput, this);
+ issueCommand("data\r\n", 354);
+ return message = new SmtpPrintStream(serverOutput, this);
}
void closeMessage() throws IOException {
- if (message != null)
- message.close();
+ if (message != null)
+ message.close();
}
/** New SMTP client connected to host <i>host</i>. */
- public SmtpClient (String host) throws IOException {
- super();
- if (host != null) {
- try {
- openServer(host);
- return;
- } catch(Exception e) {
- }
- }
- try {
- String s;
- try {
-// java.security.AccessController.beginPrivileged();
- s = System.getProperty("mail.host");
- } finally {
-// java.security.AccessController.endPrivileged();
- }
- if (s != null) {
- openServer(s);
- return;
- }
- } catch(Exception e) {
- }
- try {
- openServer("localhost");
- } catch(Exception e) {
- openServer("mailhost");
- }
+ public SmtpClient(String host) throws IOException {
+ super();
+ if (host != null) {
+ try {
+ openServer(host);
+ return;
+ } catch (Exception e) {
+ }
+ }
+ try {
+ String s;
+ try {
+ // java.security.AccessController.beginPrivileged();
+ s = System.getProperty("mail.host");
+ } finally {
+ // java.security.AccessController.endPrivileged();
+ }
+ if (s != null) {
+ openServer(s);
+ return;
+ }
+ } catch (Exception e) {
+ }
+ try {
+ openServer("localhost");
+ } catch (Exception e) {
+ openServer("mailhost");
+ }
}
/** Create an uninitialized SMTP client. */
- public SmtpClient () throws IOException {
- this(null);
+ public SmtpClient() throws IOException {
+ this(null);
}
}
@@ -166,69 +165,70 @@ class SmtpPrintStream extends java.io.PrintStream {
private SmtpClient target;
private int lastc = '\n';
- SmtpPrintStream (OutputStream fos, SmtpClient cl) {
- super(fos);
- target = cl;
+ SmtpPrintStream(OutputStream fos, SmtpClient cl) {
+ super(fos);
+ target = cl;
}
public void close() {
- if (target == null)
- return;
- if (lastc != '\n') {
- write('\r');
- write('\n');
- }
- try {
- target.issueCommand(".\r\n", 250);
- target.message = null;
- out = null;
- target = null;
- } catch (IOException e) {
- }
+ if (target == null)
+ return;
+ if (lastc != '\n') {
+ write('\r');
+ write('\n');
+ }
+ try {
+ target.issueCommand(".\r\n", 250);
+ target.message = null;
+ out = null;
+ target = null;
+ } catch (IOException e) {
+ }
}
public void write(int b) {
- try {
- // quote a dot at the beginning of a line
- if (lastc == '\n' && b == '.') {
- out.write('.');
- }
-
- // translate NL to CRLF
- if (b == '\n') {
- out.write('\r');
- }
- out.write(b);
- lastc = b;
- } catch (IOException e) {
- }
+ try {
+ // quote a dot at the beginning of a line
+ if (lastc == '\n' && b == '.') {
+ out.write('.');
+ }
+
+ // translate NL to CRLF
+ if (b == '\n') {
+ out.write('\r');
+ }
+ out.write(b);
+ lastc = b;
+ } catch (IOException e) {
+ }
}
public void write(byte b[], int off, int len) {
- try {
- int lc = lastc;
- while (--len >= 0) {
- int c = b[off++];
-
- // quote a dot at the beginning of a line
- if (lc == '\n' && c == '.')
- out.write('.');
-
- // translate NL to CRLF
- if (c == '\n') {
- out.write('\r');
- }
- out.write(c);
- lc = c;
- }
- lastc = lc;
- } catch (IOException e) {
- }
+ try {
+ int lc = lastc;
+ while (--len >= 0) {
+ int c = b[off++];
+
+ // quote a dot at the beginning of a line
+ if (lc == '\n' && c == '.')
+ out.write('.');
+
+ // translate NL to CRLF
+ if (c == '\n') {
+ out.write('\r');
+ }
+ out.write(c);
+ lc = c;
+ }
+ lastc = lc;
+ } catch (IOException e) {
+ }
}
+
public void print(String s) {
- int len = s.length();
- for (int i = 0; i < len; i++) {
- write(s.charAt(i));
- }
+ int len = s.length();
+ for (int i = 0; i < len; i++) {
+ write(s.charAt(i));
+ }
}
}
diff --git a/pki/base/util/src/netscape/net/smtp/SmtpProtocolException.java b/pki/base/util/src/netscape/net/smtp/SmtpProtocolException.java
index bb015f90..d438543f 100644
--- a/pki/base/util/src/netscape/net/smtp/SmtpProtocolException.java
+++ b/pki/base/util/src/netscape/net/smtp/SmtpProtocolException.java
@@ -20,8 +20,8 @@ package netscape.net.smtp;
import java.io.IOException;
/**
- * This exeception is thrown when unexpected results are returned during
- * an SMTP session.
+ * This exeception is thrown when unexpected results are returned during an SMTP
+ * session.
*/
public class SmtpProtocolException extends IOException {
/**
@@ -30,7 +30,6 @@ public class SmtpProtocolException extends IOException {
private static final long serialVersionUID = -5586603317525864401L;
SmtpProtocolException(String s) {
- super(s);
+ super(s);
}
}
-
diff --git a/pki/base/util/src/netscape/security/acl/AclEntryImpl.java b/pki/base/util/src/netscape/security/acl/AclEntryImpl.java
index 47186881..8609d52d 100644
--- a/pki/base/util/src/netscape/security/acl/AclEntryImpl.java
+++ b/pki/base/util/src/netscape/security/acl/AclEntryImpl.java
@@ -25,10 +25,11 @@ import java.util.Enumeration;
import java.util.Vector;
/**
- * This is a class that describes one entry that associates users
- * or groups with permissions in the ACL.
- * The entry may be used as a way of granting or denying permissions.
- * @author Satish Dharmaraj
+ * This is a class that describes one entry that associates users or groups with
+ * permissions in the ACL. The entry may be used as a way of granting or denying
+ * permissions.
+ *
+ * @author Satish Dharmaraj
*/
public class AclEntryImpl implements AclEntry {
private Principal user = null;
@@ -36,12 +37,13 @@ public class AclEntryImpl implements AclEntry {
private boolean negative = false;
/**
- * Construct an ACL entry that associates a user with permissions
- * in the ACL.
+ * Construct an ACL entry that associates a user with permissions in the
+ * ACL.
+ *
* @param user The user that is associated with this entry.
*/
public AclEntryImpl(Principal user) {
- this.user = user;
+ this.user = user;
}
/**
@@ -51,128 +53,126 @@ public class AclEntryImpl implements AclEntry {
}
/**
- * Sets the principal in the entity. If a group or a
- * principal had already been set, a false value is
- * returned, otherwise a true value is returned.
+ * Sets the principal in the entity. If a group or a principal had already
+ * been set, a false value is returned, otherwise a true value is returned.
+ *
* @param user The user that is associated with this entry.
- * @return true if the principal is set, false if there is
- * one already.
+ * @return true if the principal is set, false if there is one already.
*/
public boolean setPrincipal(Principal user) {
- if (this.user != null)
- return false;
- this.user = user;
- return true;
+ if (this.user != null)
+ return false;
+ this.user = user;
+ return true;
}
/**
- * This method sets the ACL to have negative permissions.
- * That is the user or group is denied the permission set
- * specified in the entry.
+ * This method sets the ACL to have negative permissions. That is the user
+ * or group is denied the permission set specified in the entry.
*/
public void setNegativePermissions() {
- negative = true;
+ negative = true;
}
/**
* Returns true if this is a negative ACL.
*/
public boolean isNegative() {
- return negative;
+ return negative;
}
/**
- * A principal or a group can be associated with multiple
- * permissions. This method adds a permission to the ACL entry.
- * @param permission The permission to be associated with
- * the principal or the group in the entry.
- * @return true if the permission was added, false if the
- * permission was already part of the permission set.
+ * A principal or a group can be associated with multiple permissions. This
+ * method adds a permission to the ACL entry.
+ *
+ * @param permission The permission to be associated with the principal or
+ * the group in the entry.
+ * @return true if the permission was added, false if the permission was
+ * already part of the permission set.
*/
public boolean addPermission(Permission permission) {
- if (permissionSet.contains(permission))
- return false;
+ if (permissionSet.contains(permission))
+ return false;
- permissionSet.addElement(permission);
+ permissionSet.addElement(permission);
- return true;
+ return true;
}
/**
- * The method disassociates the permission from the Principal
- * or the Group in this ACL entry.
- * @param permission The permission to be disassociated with
- * the principal or the group in the entry.
- * @return true if the permission is removed, false if the
- * permission is not part of the permission set.
+ * The method disassociates the permission from the Principal or the Group
+ * in this ACL entry.
+ *
+ * @param permission The permission to be disassociated with the principal
+ * or the group in the entry.
+ * @return true if the permission is removed, false if the permission is not
+ * part of the permission set.
*/
public boolean removePermission(Permission permission) {
- return permissionSet.removeElement(permission);
+ return permissionSet.removeElement(permission);
}
/**
- * Checks if the passed permission is part of the allowed
- * permission set in this entry.
- * @param permission The permission that has to be part of
- * the permission set in the entry.
- * @return true if the permission passed is part of the
- * permission set in the entry, false otherwise.
+ * Checks if the passed permission is part of the allowed permission set in
+ * this entry.
+ *
+ * @param permission The permission that has to be part of the permission
+ * set in the entry.
+ * @return true if the permission passed is part of the permission set in
+ * the entry, false otherwise.
*/
public boolean checkPermission(Permission permission) {
- return permissionSet.contains(permission);
+ return permissionSet.contains(permission);
}
/**
* return an enumeration of the permissions in this ACL entry.
*/
public Enumeration<Permission> permissions() {
- return permissionSet.elements();
+ return permissionSet.elements();
}
/**
- * Return a string representation of the contents of the ACL entry.
+ * Return a string representation of the contents of the ACL entry.
*/
public String toString() {
- StringBuffer s = new StringBuffer();
- if (negative)
- s.append("-");
- else
- s.append("+");
- if (user instanceof Group)
- s.append("Group.");
- else
- s.append("User.");
- s.append(user + "=");
- Enumeration<Permission> e = permissions();
- while(e.hasMoreElements()) {
- Permission p = (Permission) e.nextElement();
- s.append(p);
- if (e.hasMoreElements())
- s.append(",");
- }
- return new String(s);
+ StringBuffer s = new StringBuffer();
+ if (negative)
+ s.append("-");
+ else
+ s.append("+");
+ if (user instanceof Group)
+ s.append("Group.");
+ else
+ s.append("User.");
+ s.append(user + "=");
+ Enumeration<Permission> e = permissions();
+ while (e.hasMoreElements()) {
+ Permission p = (Permission) e.nextElement();
+ s.append(p);
+ if (e.hasMoreElements())
+ s.append(",");
+ }
+ return new String(s);
}
/**
* Clones an AclEntry.
*/
public synchronized Object clone() {
- AclEntryImpl cloned;
- cloned = new AclEntryImpl(user);
- cloned.permissionSet = new Vector<Permission>(permissionSet);
- cloned.negative = negative;
- return cloned;
+ AclEntryImpl cloned;
+ cloned = new AclEntryImpl(user);
+ cloned.permissionSet = new Vector<Permission>(permissionSet);
+ cloned.negative = negative;
+ return cloned;
}
/**
- * Return the Principal associated in this ACL entry.
- * The method returns null if the entry uses a group
- * instead of a principal.
+ * Return the Principal associated in this ACL entry. The method returns
+ * null if the entry uses a group instead of a principal.
*/
public Principal getPrincipal() {
- return user;
+ return user;
}
}
-
-
diff --git a/pki/base/util/src/netscape/security/acl/AclImpl.java b/pki/base/util/src/netscape/security/acl/AclImpl.java
index 6a5d4fd2..c70e3947 100644
--- a/pki/base/util/src/netscape/security/acl/AclImpl.java
+++ b/pki/base/util/src/netscape/security/acl/AclImpl.java
@@ -30,7 +30,8 @@ import java.util.Vector;
/**
* An Access Control List (ACL) is encapsulated by this class.
- * @author Satish Dharmaraj
+ *
+ * @author Satish Dharmaraj
*/
public class AclImpl extends OwnerImpl implements Acl {
//
@@ -43,313 +44,310 @@ public class AclImpl extends OwnerImpl implements Acl {
private Hashtable<Principal, AclEntry> deniedUsersTable = new Hashtable<Principal, AclEntry>(23);
private Hashtable<Principal, AclEntry> deniedGroupsTable = new Hashtable<Principal, AclEntry>(23);
private String aclName = null;
- private Vector<Permission> zeroSet = new Vector<Permission>(1,1);
-
+ private Vector<Permission> zeroSet = new Vector<Permission>(1, 1);
/**
* Constructor for creating an empty ACL.
*/
public AclImpl(Principal owner, String name) {
- super(owner);
- try {
- setName(owner, name);
- } catch (Exception e) {}
- }
+ super(owner);
+ try {
+ setName(owner, name);
+ } catch (Exception e) {
+ }
+ }
/**
* Sets the name of the ACL.
- * @param caller the principal who is invoking this method.
+ *
+ * @param caller the principal who is invoking this method.
* @param name the name of the ACL.
- * @exception NotOwnerException if the caller principal is
- * not on the owners list of the Acl.
+ * @exception NotOwnerException if the caller principal is not on the owners
+ * list of the Acl.
*/
public void setName(Principal caller, String name)
- throws NotOwnerException
- {
- if (!isOwner(caller))
- throw new NotOwnerException();
+ throws NotOwnerException {
+ if (!isOwner(caller))
+ throw new NotOwnerException();
- aclName = name;
+ aclName = name;
}
/**
- * Returns the name of the ACL.
+ * Returns the name of the ACL.
+ *
* @return the name of the ACL.
*/
public String getName() {
- return aclName;
+ return aclName;
}
/**
- * Adds an ACL entry to this ACL. An entry associates a
- * group or a principal with a set of permissions. Each
- * user or group can have one positive ACL entry and one
- * negative ACL entry. If there is one of the type (negative
- * or positive) already in the table, a false value is returned.
- * The caller principal must be a part of the owners list of
- * the ACL in order to invoke this method.
- * @param caller the principal who is invoking this method.
- * @param entry the ACL entry that must be added to the ACL.
+ * Adds an ACL entry to this ACL. An entry associates a group or a principal
+ * with a set of permissions. Each user or group can have one positive ACL
+ * entry and one negative ACL entry. If there is one of the type (negative
+ * or positive) already in the table, a false value is returned. The caller
+ * principal must be a part of the owners list of the ACL in order to invoke
+ * this method.
+ *
+ * @param caller the principal who is invoking this method.
+ * @param entry the ACL entry that must be added to the ACL.
* @return true on success, false if the entry is already present.
- * @exception NotOwnerException if the caller principal
- * is not on the owners list of the Acl.
+ * @exception NotOwnerException if the caller principal is not on the owners
+ * list of the Acl.
*/
- public synchronized boolean addEntry(Principal caller, AclEntry entry)
- throws NotOwnerException
- {
- if (!isOwner(caller))
- throw new NotOwnerException();
+ public synchronized boolean addEntry(Principal caller, AclEntry entry)
+ throws NotOwnerException {
+ if (!isOwner(caller))
+ throw new NotOwnerException();
- Hashtable<Principal, AclEntry> aclTable = findTable(entry);
- Principal key = entry.getPrincipal();
+ Hashtable<Principal, AclEntry> aclTable = findTable(entry);
+ Principal key = entry.getPrincipal();
- if (aclTable.get(key) != null)
- return false;
+ if (aclTable.get(key) != null)
+ return false;
- aclTable.put(key, entry);
- return true;
+ aclTable.put(key, entry);
+ return true;
}
/**
- * Removes an ACL entry from this ACL.
- * The caller principal must be a part of the owners list of the ACL
- * in order to invoke this method.
- * @param caller the principal who is invoking this method.
+ * Removes an ACL entry from this ACL. The caller principal must be a part
+ * of the owners list of the ACL in order to invoke this method.
+ *
+ * @param caller the principal who is invoking this method.
* @param entry the ACL entry that must be removed from the ACL.
* @return true on success, false if the entry is not part of the ACL.
- * @exception NotOwnerException if the caller principal is not
- * the owners list of the Acl.
+ * @exception NotOwnerException if the caller principal is not the owners
+ * list of the Acl.
*/
- public synchronized boolean removeEntry(Principal caller, AclEntry entry)
- throws NotOwnerException
- {
- if (!isOwner(caller))
- throw new NotOwnerException();
+ public synchronized boolean removeEntry(Principal caller, AclEntry entry)
+ throws NotOwnerException {
+ if (!isOwner(caller))
+ throw new NotOwnerException();
- Hashtable<Principal, AclEntry> aclTable = findTable(entry);
- Object key = entry.getPrincipal();
+ Hashtable<Principal, AclEntry> aclTable = findTable(entry);
+ Object key = entry.getPrincipal();
- Object o = aclTable.remove(key);
- return (o != null);
+ Object o = aclTable.remove(key);
+ return (o != null);
}
+
/**
- * This method returns the set of allowed permissions for the
- * specified principal. This set of allowed permissions is calculated
- * as follows:
- *
- * If there is no entry for a group or a principal an empty permission
- * set is assumed.
+ * This method returns the set of allowed permissions for the specified
+ * principal. This set of allowed permissions is calculated as follows:
+ *
+ * If there is no entry for a group or a principal an empty permission set
+ * is assumed.
+ *
+ * The group positive permission set is the union of all the positive
+ * permissions of each group that the individual belongs to. The group
+ * negative permission set is the union of all the negative permissions of
+ * each group that the individual belongs to. If there is a specific
+ * permission that occurs in both the postive permission set and the
+ * negative permission set, it is removed from both. The group positive and
+ * negatoive permission sets are calculated.
+ *
+ * The individial positive permission set and the individual negative
+ * permission set is then calculated. Again abscence of an entry means the
+ * empty set.
*
- * The group positive permission set is the union of all
- * the positive permissions of each group that the individual belongs to.
- * The group negative permission set is the union of all
- * the negative permissions of each group that the individual belongs to.
- * If there is a specific permission that occurs in both
- * the postive permission set and the negative permission set,
- * it is removed from both. The group positive and negatoive permission
- * sets are calculated.
- *
- * The individial positive permission set and the individual negative
- * permission set is then calculated. Again abscence of an entry means
- * the empty set.
- *
* The set of permissions granted to the principal is then calculated using
- * the simple rule: Individual permissions always override the Group permissions.
- * Specifically, individual negative permission set (specific
- * denial of permissions) overrides the group positive permission set.
- * And the individual positive permission set override the group negative
- * permission set.
- *
+ * the simple rule: Individual permissions always override the Group
+ * permissions. Specifically, individual negative permission set (specific
+ * denial of permissions) overrides the group positive permission set. And
+ * the individual positive permission set override the group negative
+ * permission set.
+ *
* @param user the principal for which the ACL entry is returned.
- * @return The resulting permission set that the principal is allowed.
+ * @return The resulting permission set that the principal is allowed.
*/
public synchronized Enumeration<Permission> getPermissions(Principal user) {
- Enumeration<Permission> individualPositive;
- Enumeration<Permission> individualNegative;
- Enumeration<Permission> groupPositive;
- Enumeration<Permission> groupNegative;
-
- //
- // canonicalize the sets. That is remove common permissions from
- // positive and negative sets.
- //
- groupPositive = subtract(getGroupPositive(user), getGroupNegative(user));
- groupNegative = subtract(getGroupNegative(user), getGroupPositive(user));
- individualPositive = subtract(getIndividualPositive(user), getIndividualNegative(user));
- individualNegative = subtract(getIndividualNegative(user), getIndividualPositive(user));
-
- //
- // net positive permissions is individual positive permissions
- // plus (group positive - individual negative).
- //
- Enumeration<Permission> temp1 = subtract(groupPositive, individualNegative);
- Enumeration<Permission> netPositive = union(individualPositive, temp1);
-
- // recalculate the enumeration since we lost it in performing the
- // subtraction
- //
- individualPositive = subtract(getIndividualPositive(user), getIndividualNegative(user));
- individualNegative = subtract(getIndividualNegative(user), getIndividualPositive(user));
-
- //
- // net negative permissions is individual negative permissions
- // plus (group negative - individual positive).
- //
- temp1 = subtract(groupNegative, individualPositive);
- Enumeration<Permission> netNegative = union(individualNegative, temp1);
-
- return subtract(netPositive, netNegative);
+ Enumeration<Permission> individualPositive;
+ Enumeration<Permission> individualNegative;
+ Enumeration<Permission> groupPositive;
+ Enumeration<Permission> groupNegative;
+
+ //
+ // canonicalize the sets. That is remove common permissions from
+ // positive and negative sets.
+ //
+ groupPositive = subtract(getGroupPositive(user), getGroupNegative(user));
+ groupNegative = subtract(getGroupNegative(user), getGroupPositive(user));
+ individualPositive = subtract(getIndividualPositive(user), getIndividualNegative(user));
+ individualNegative = subtract(getIndividualNegative(user), getIndividualPositive(user));
+
+ //
+ // net positive permissions is individual positive permissions
+ // plus (group positive - individual negative).
+ //
+ Enumeration<Permission> temp1 = subtract(groupPositive, individualNegative);
+ Enumeration<Permission> netPositive = union(individualPositive, temp1);
+
+ // recalculate the enumeration since we lost it in performing the
+ // subtraction
+ //
+ individualPositive = subtract(getIndividualPositive(user), getIndividualNegative(user));
+ individualNegative = subtract(getIndividualNegative(user), getIndividualPositive(user));
+
+ //
+ // net negative permissions is individual negative permissions
+ // plus (group negative - individual positive).
+ //
+ temp1 = subtract(groupNegative, individualPositive);
+ Enumeration<Permission> netNegative = union(individualNegative, temp1);
+
+ return subtract(netPositive, netNegative);
}
/**
- * This method checks whether or not the specified principal
- * has the required permission. If permission is denied
- * permission false is returned, a true value is returned otherwise.
- * This method does not authenticate the principal. It presumes that
- * the principal is a valid authenticated principal.
+ * This method checks whether or not the specified principal has the
+ * required permission. If permission is denied permission false is
+ * returned, a true value is returned otherwise. This method does not
+ * authenticate the principal. It presumes that the principal is a valid
+ * authenticated principal.
+ *
* @param principal the name of the authenticated principal
* @param permission the permission that the principal must have.
- * @return true of the principal has the permission desired, false
- * otherwise.
+ * @return true of the principal has the permission desired, false
+ * otherwise.
*/
- public boolean checkPermission(Principal principal, Permission permission)
- {
- Enumeration<Permission> permSet = getPermissions(principal);
- while (permSet.hasMoreElements()) {
- Permission p = (Permission) permSet.nextElement();
- if (p.equals(permission))
- return true;
- }
- return false;
+ public boolean checkPermission(Principal principal, Permission permission) {
+ Enumeration<Permission> permSet = getPermissions(principal);
+ while (permSet.hasMoreElements()) {
+ Permission p = (Permission) permSet.nextElement();
+ if (p.equals(permission))
+ return true;
+ }
+ return false;
}
/**
* returns an enumeration of the entries in this ACL.
*/
public synchronized Enumeration<AclEntry> entries() {
- return new AclEnumerator(this,
- allowedUsersTable, allowedGroupsTable,
- deniedUsersTable, deniedGroupsTable);
+ return new AclEnumerator(this,
+ allowedUsersTable, allowedGroupsTable,
+ deniedUsersTable, deniedGroupsTable);
}
/**
- * return a stringified version of the
- * ACL.
+ * return a stringified version of the ACL.
*/
public String toString() {
- StringBuffer sb = new StringBuffer();
- Enumeration<AclEntry> entries = entries();
- while (entries.hasMoreElements()) {
- AclEntry entry = (AclEntry) entries.nextElement();
- sb.append(entry.toString().trim());
- sb.append("\n");
- }
-
- return sb.toString();
+ StringBuffer sb = new StringBuffer();
+ Enumeration<AclEntry> entries = entries();
+ while (entries.hasMoreElements()) {
+ AclEntry entry = (AclEntry) entries.nextElement();
+ sb.append(entry.toString().trim());
+ sb.append("\n");
+ }
+
+ return sb.toString();
}
//
- // Find the table that this entry belongs to. There are 4
- // tables that are maintained. One each for postive and
- // negative ACLs and one each for groups and users.
- // This method figures out which
+ // Find the table that this entry belongs to. There are 4
+ // tables that are maintained. One each for postive and
+ // negative ACLs and one each for groups and users.
+ // This method figures out which
// table is the one that this AclEntry belongs to.
//
private Hashtable<Principal, AclEntry> findTable(AclEntry entry) {
- Hashtable<Principal, AclEntry> aclTable = null;
-
- Principal p = entry.getPrincipal();
- if (p instanceof Group) {
- if (entry.isNegative())
- aclTable = deniedGroupsTable;
- else
- aclTable = allowedGroupsTable;
- } else {
- if (entry.isNegative())
- aclTable = deniedUsersTable;
- else
- aclTable = allowedUsersTable;
- }
- return aclTable;
+ Hashtable<Principal, AclEntry> aclTable = null;
+
+ Principal p = entry.getPrincipal();
+ if (p instanceof Group) {
+ if (entry.isNegative())
+ aclTable = deniedGroupsTable;
+ else
+ aclTable = allowedGroupsTable;
+ } else {
+ if (entry.isNegative())
+ aclTable = deniedUsersTable;
+ else
+ aclTable = allowedUsersTable;
+ }
+ return aclTable;
}
//
// returns the set e1 U e2.
//
- private <T> Enumeration<T> union(Enumeration<T> e1, Enumeration<T> e2) {
- Vector<T> v = new Vector<T>(20, 20);
-
- while (e1.hasMoreElements())
- v.addElement(e1.nextElement());
-
- while (e2.hasMoreElements()) {
- T o = e2.nextElement();
- if (!v.contains(o))
- v.addElement(o);
- }
-
- return v.elements();
+ private <T> Enumeration<T> union(Enumeration<T> e1, Enumeration<T> e2) {
+ Vector<T> v = new Vector<T>(20, 20);
+
+ while (e1.hasMoreElements())
+ v.addElement(e1.nextElement());
+
+ while (e2.hasMoreElements()) {
+ T o = e2.nextElement();
+ if (!v.contains(o))
+ v.addElement(o);
+ }
+
+ return v.elements();
}
//
// returns the set e1 - e2.
//
private <T> Enumeration<T> subtract(Enumeration<T> e1, Enumeration<T> e2) {
- Vector<T> v = new Vector<T> (20, 20);
-
- while (e1.hasMoreElements())
- v.addElement(e1.nextElement());
-
- while (e2.hasMoreElements()) {
- T o = e2.nextElement();
- if (v.contains(o))
- v.removeElement(o);
- }
-
- return v.elements();
+ Vector<T> v = new Vector<T>(20, 20);
+
+ while (e1.hasMoreElements())
+ v.addElement(e1.nextElement());
+
+ while (e2.hasMoreElements()) {
+ T o = e2.nextElement();
+ if (v.contains(o))
+ v.removeElement(o);
+ }
+
+ return v.elements();
}
private Enumeration<Permission> getGroupPositive(Principal user) {
- Enumeration<Permission> groupPositive = zeroSet.elements();
- Enumeration<Principal> e = allowedGroupsTable.keys();
- while (e.hasMoreElements()) {
- Group g = (Group) e.nextElement();
- if (g.isMember(user)) {
- AclEntry ae = (AclEntry) allowedGroupsTable.get(g);
- groupPositive = union(ae.permissions(), groupPositive);
- }
- }
- return groupPositive;
+ Enumeration<Permission> groupPositive = zeroSet.elements();
+ Enumeration<Principal> e = allowedGroupsTable.keys();
+ while (e.hasMoreElements()) {
+ Group g = (Group) e.nextElement();
+ if (g.isMember(user)) {
+ AclEntry ae = (AclEntry) allowedGroupsTable.get(g);
+ groupPositive = union(ae.permissions(), groupPositive);
+ }
+ }
+ return groupPositive;
}
private Enumeration<Permission> getGroupNegative(Principal user) {
- Enumeration<Permission> groupNegative = zeroSet.elements();
- Enumeration<Principal> e = deniedGroupsTable.keys();
- while (e.hasMoreElements()) {
- Group g = (Group) e.nextElement();
- if (g.isMember(user)) {
- AclEntry ae = (AclEntry) deniedGroupsTable.get(g);
- groupNegative = union(ae.permissions(), groupNegative);
- }
- }
- return groupNegative;
+ Enumeration<Permission> groupNegative = zeroSet.elements();
+ Enumeration<Principal> e = deniedGroupsTable.keys();
+ while (e.hasMoreElements()) {
+ Group g = (Group) e.nextElement();
+ if (g.isMember(user)) {
+ AclEntry ae = (AclEntry) deniedGroupsTable.get(g);
+ groupNegative = union(ae.permissions(), groupNegative);
+ }
+ }
+ return groupNegative;
}
private Enumeration<Permission> getIndividualPositive(Principal user) {
- Enumeration<Permission> individualPositive = zeroSet.elements();
- AclEntry ae = (AclEntry) allowedUsersTable.get(user);
- if (ae != null)
- individualPositive = ae.permissions();
- return individualPositive;
+ Enumeration<Permission> individualPositive = zeroSet.elements();
+ AclEntry ae = (AclEntry) allowedUsersTable.get(user);
+ if (ae != null)
+ individualPositive = ae.permissions();
+ return individualPositive;
}
private Enumeration<Permission> getIndividualNegative(Principal user) {
- Enumeration<Permission> individualNegative = zeroSet.elements();
- AclEntry ae = (AclEntry) deniedUsersTable.get(user);
- if (ae != null)
- individualNegative = ae.permissions();
- return individualNegative;
+ Enumeration<Permission> individualNegative = zeroSet.elements();
+ AclEntry ae = (AclEntry) deniedUsersTable.get(user);
+ if (ae != null)
+ individualNegative = ae.permissions();
+ return individualNegative;
}
}
@@ -358,33 +356,31 @@ final class AclEnumerator implements Enumeration<AclEntry> {
Enumeration<AclEntry> u1, u2, g1, g2;
AclEnumerator(Acl acl, Hashtable<Principal, AclEntry> u1, Hashtable<Principal, AclEntry> g1,
- Hashtable<Principal, AclEntry> u2, Hashtable<Principal, AclEntry> g2) {
- this.acl = acl;
- this.u1 = u1.elements();
- this.u2 = u2.elements();
- this.g1 = g1.elements();
- this.g2 = g2.elements();
+ Hashtable<Principal, AclEntry> u2, Hashtable<Principal, AclEntry> g2) {
+ this.acl = acl;
+ this.u1 = u1.elements();
+ this.u2 = u2.elements();
+ this.g1 = g1.elements();
+ this.g2 = g2.elements();
}
public boolean hasMoreElements() {
- return (u1.hasMoreElements() ||
- u2.hasMoreElements() ||
- g1.hasMoreElements() ||
- g2.hasMoreElements());
+ return (u1.hasMoreElements() ||
+ u2.hasMoreElements() ||
+ g1.hasMoreElements() || g2.hasMoreElements());
}
- public AclEntry nextElement()
- {
- synchronized (acl) {
- if (u1.hasMoreElements())
- return u1.nextElement();
- if (u2.hasMoreElements())
- return u2.nextElement();
- if (g1.hasMoreElements())
- return g1.nextElement();
- if (g2.hasMoreElements())
- return g2.nextElement();
- }
- throw new NoSuchElementException("Acl Enumerator");
+ public AclEntry nextElement() {
+ synchronized (acl) {
+ if (u1.hasMoreElements())
+ return u1.nextElement();
+ if (u2.hasMoreElements())
+ return u2.nextElement();
+ if (g1.hasMoreElements())
+ return g1.nextElement();
+ if (g2.hasMoreElements())
+ return g2.nextElement();
+ }
+ throw new NoSuchElementException("Acl Enumerator");
}
}
diff --git a/pki/base/util/src/netscape/security/acl/AllPermissionsImpl.java b/pki/base/util/src/netscape/security/acl/AllPermissionsImpl.java
index 4f63712c..710bf4ec 100644
--- a/pki/base/util/src/netscape/security/acl/AllPermissionsImpl.java
+++ b/pki/base/util/src/netscape/security/acl/AllPermissionsImpl.java
@@ -21,21 +21,23 @@ import java.security.acl.Permission;
/**
* This class implements the principal interface for the set of all permissions.
+ *
* @author Satish Dharmaraj
*/
public class AllPermissionsImpl extends PermissionImpl {
public AllPermissionsImpl(String s) {
- super(s);
+ super(s);
}
/**
- * This function returns true if the permission passed matches the permission represented in
- * this interface.
+ * This function returns true if the permission passed matches the
+ * permission represented in this interface.
+ *
* @param another The Permission object to compare with.
* @return true always
*/
public boolean equals(Permission another) {
- return true;
+ return true;
}
}
diff --git a/pki/base/util/src/netscape/security/acl/GroupImpl.java b/pki/base/util/src/netscape/security/acl/GroupImpl.java
index 50c68bdb..f8184a42 100644
--- a/pki/base/util/src/netscape/security/acl/GroupImpl.java
+++ b/pki/base/util/src/netscape/security/acl/GroupImpl.java
@@ -24,7 +24,8 @@ import java.util.Vector;
/**
* This class implements a group of principals.
- * @author Satish Dharmaraj
+ *
+ * @author Satish Dharmaraj
*/
public class GroupImpl implements Group {
private Vector groupMembers = new Vector(50, 100);
@@ -32,136 +33,140 @@ public class GroupImpl implements Group {
/**
* Constructs a Group object with no members.
+ *
* @param groupName the name of the group
*/
public GroupImpl(String groupName) {
- this.group = groupName;
+ this.group = groupName;
}
/**
* adds the specified member to the group.
+ *
* @param user The principal to add to the group.
- * @return true if the member was added - false if the
- * member could not be added.
+ * @return true if the member was added - false if the member could not be
+ * added.
*/
public boolean addMember(Principal user) {
- if (groupMembers.contains(user))
- return false;
+ if (groupMembers.contains(user))
+ return false;
- // do not allow groups to be added to itself.
- if (group.equals(user.toString()))
- throw new IllegalArgumentException();
+ // do not allow groups to be added to itself.
+ if (group.equals(user.toString()))
+ throw new IllegalArgumentException();
- groupMembers.addElement(user);
- return true;
+ groupMembers.addElement(user);
+ return true;
}
/**
* removes the specified member from the group.
+ *
* @param user The principal to remove from the group.
- * @param true if the principal was removed false if
- * the principal was not a member
+ * @param true if the principal was removed false if the principal was not a
+ * member
*/
public boolean removeMember(Principal user) {
- return groupMembers.removeElement(user);
+ return groupMembers.removeElement(user);
}
/**
* returns the enumeration of the members in the group.
*/
public Enumeration members() {
- return groupMembers.elements();
+ return groupMembers.elements();
}
/**
- * This function returns true if the group passed matches
- * the group represented in this interface.
+ * This function returns true if the group passed matches the group
+ * represented in this interface.
+ *
* @param another The group to compare this group to.
*/
public boolean equals(Group another) {
- return group.equals(another.toString());
+ return group.equals(another.toString());
}
-
+
/**
* Prints a stringified version of the group.
*/
public String toString() {
- return group;
+ return group;
}
/**
* return a hashcode for the principal.
*/
public int hashCode() {
- return group.hashCode();
+ return group.hashCode();
}
/**
* returns true if the passed principal is a member of the group.
+ *
* @param member The principal whose membership must be checked for.
- * @return true if the principal is a member of this group,
- * false otherwise
+ * @return true if the principal is a member of this group, false otherwise
*/
public boolean isMember(Principal member) {
-
- //
- // if the member is part of the group (common case), return true.
- // if not, recursively search depth first in the group looking for the
- // principal.
- //
- if (groupMembers.contains(member)) {
- return true;
- } else {
- Vector alreadySeen = new Vector(10);
- return isMemberRecurse(member, alreadySeen);
- }
+
+ //
+ // if the member is part of the group (common case), return true.
+ // if not, recursively search depth first in the group looking for the
+ // principal.
+ //
+ if (groupMembers.contains(member)) {
+ return true;
+ } else {
+ Vector alreadySeen = new Vector(10);
+ return isMemberRecurse(member, alreadySeen);
+ }
}
/**
* return the name of the principal.
*/
public String getName() {
- return group;
+ return group;
}
//
// This function is the recursive search of groups for this
// implementation of the Group. The search proceeds building up
- // a vector of already seen groups. Only new groups are considered,
+ // a vector of already seen groups. Only new groups are considered,
// thereby avoiding loops.
//
boolean isMemberRecurse(Principal member, Vector alreadySeen) {
- Enumeration e = members();
- while (e.hasMoreElements()) {
- boolean mem = false;
- Principal p = (Principal) e.nextElement();
-
- // if the member is in this collection, return true
- if (p.equals(member)) {
- return true;
- } else if (p instanceof GroupImpl) {
- //
- // if not recurse if the group has not been checked already.
- // Can call method in this package only if the object is an
- // instance of this class. Otherwise call the method defined
- // in the interface. (This can lead to a loop if a mixture of
- // implementations form a loop, but we live with this improbable
- // case rather than clutter the interface by forcing the
- // implementation of this method.)
- //
- GroupImpl g = (GroupImpl) p;
- alreadySeen.addElement(this);
- if (!alreadySeen.contains(g))
- mem = g.isMemberRecurse(member, alreadySeen);
- } else if (p instanceof Group) {
- Group g = (Group) p;
- if (!alreadySeen.contains(g))
- mem = g.isMember(member);
- }
-
- if (mem)
- return mem;
- }
- return false;
+ Enumeration e = members();
+ while (e.hasMoreElements()) {
+ boolean mem = false;
+ Principal p = (Principal) e.nextElement();
+
+ // if the member is in this collection, return true
+ if (p.equals(member)) {
+ return true;
+ } else if (p instanceof GroupImpl) {
+ //
+ // if not recurse if the group has not been checked already.
+ // Can call method in this package only if the object is an
+ // instance of this class. Otherwise call the method defined
+ // in the interface. (This can lead to a loop if a mixture of
+ // implementations form a loop, but we live with this improbable
+ // case rather than clutter the interface by forcing the
+ // implementation of this method.)
+ //
+ GroupImpl g = (GroupImpl) p;
+ alreadySeen.addElement(this);
+ if (!alreadySeen.contains(g))
+ mem = g.isMemberRecurse(member, alreadySeen);
+ } else if (p instanceof Group) {
+ Group g = (Group) p;
+ if (!alreadySeen.contains(g))
+ mem = g.isMember(member);
+ }
+
+ if (mem)
+ return mem;
+ }
+ return false;
}
}
diff --git a/pki/base/util/src/netscape/security/acl/OwnerImpl.java b/pki/base/util/src/netscape/security/acl/OwnerImpl.java
index 7296590e..003bfa75 100644
--- a/pki/base/util/src/netscape/security/acl/OwnerImpl.java
+++ b/pki/base/util/src/netscape/security/acl/OwnerImpl.java
@@ -25,79 +25,79 @@ import java.security.acl.Owner;
import java.util.Enumeration;
/**
- * Class implementing the Owner interface. The
- * initial owner principal is configured as
- * part of the constructor.
- * @author Satish Dharmaraj
+ * Class implementing the Owner interface. The initial owner principal is
+ * configured as part of the constructor.
+ *
+ * @author Satish Dharmaraj
*/
public class OwnerImpl implements Owner {
private Group ownerGroup;
public OwnerImpl(Principal owner) {
- ownerGroup = new GroupImpl("AclOwners");
- ownerGroup.addMember(owner);
+ ownerGroup = new GroupImpl("AclOwners");
+ ownerGroup.addMember(owner);
}
/**
- * Adds an owner. Owners can modify ACL contents and can disassociate
- * ACLs from the objects they protect in the AclConfig interface.
- * The caller principal must be a part of the owners list of the ACL in
- * order to invoke this method. The initial owner is configured
- * at ACL construction time.
- * @param caller the principal who is invoking this method.
+ * Adds an owner. Owners can modify ACL contents and can disassociate ACLs
+ * from the objects they protect in the AclConfig interface. The caller
+ * principal must be a part of the owners list of the ACL in order to invoke
+ * this method. The initial owner is configured at ACL construction time.
+ *
+ * @param caller the principal who is invoking this method.
* @param owner The owner that should be added to the owners list.
* @return true if success, false if already an owner.
- * @exception NotOwnerException if the caller principal is not on
- * the owners list of the Acl.
+ * @exception NotOwnerException if the caller principal is not on the owners
+ * list of the Acl.
*/
public synchronized boolean addOwner(Principal caller, Principal owner)
- throws NotOwnerException
- {
- if (!isOwner(caller))
- throw new NotOwnerException();
+ throws NotOwnerException {
+ if (!isOwner(caller))
+ throw new NotOwnerException();
- ownerGroup.addMember(owner);
- return false;
+ ownerGroup.addMember(owner);
+ return false;
}
- /**
- * Delete owner. If this is the last owner in the ACL, an exception is
- * raised.
- * The caller principal must be a part of the owners list of the ACL in
- * order to invoke this method.
- * @param caller the principal who is invoking this method.
+ /**
+ * Delete owner. If this is the last owner in the ACL, an exception is
+ * raised. The caller principal must be a part of the owners list of the ACL
+ * in order to invoke this method.
+ *
+ * @param caller the principal who is invoking this method.
* @param owner The owner to be removed from the owners list.
- * @return true if the owner is removed, false if the owner is not part
- * of the owners list.
- * @exception NotOwnerException if the caller principal is not on
- * the owners list of the Acl.
- * @exception LastOwnerException if there is only one owner left in the group, then
- * deleteOwner would leave the ACL owner-less. This exception is raised in such a case.
+ * @return true if the owner is removed, false if the owner is not part of
+ * the owners list.
+ * @exception NotOwnerException if the caller principal is not on the owners
+ * list of the Acl.
+ * @exception LastOwnerException if there is only one owner left in the
+ * group, then deleteOwner would leave the ACL owner-less.
+ * This exception is raised in such a case.
*/
- public synchronized boolean deleteOwner(Principal caller, Principal owner)
- throws NotOwnerException, LastOwnerException
- {
- if (!isOwner(caller))
- throw new NotOwnerException();
-
- Enumeration<? extends Principal> e = ownerGroup.members();
- //
- // check if there is atleast 2 members left.
- //
- Object o = e.nextElement();
- if (e.hasMoreElements())
- return ownerGroup.removeMember(owner);
- else
- throw new LastOwnerException();
-
- }
+ public synchronized boolean deleteOwner(Principal caller, Principal owner)
+ throws NotOwnerException, LastOwnerException {
+ if (!isOwner(caller))
+ throw new NotOwnerException();
+
+ Enumeration<? extends Principal> e = ownerGroup.members();
+ //
+ // check if there is atleast 2 members left.
+ //
+ Object o = e.nextElement();
+ if (e.hasMoreElements())
+ return ownerGroup.removeMember(owner);
+ else
+ throw new LastOwnerException();
+
+ }
/**
* returns if the given principal belongs to the owner list.
+ *
* @param owner The owner to check if part of the owners list
* @return true if the passed principal is in the owner list, false if not.
*/
public synchronized boolean isOwner(Principal owner) {
- return ownerGroup.isMember(owner);
+ return ownerGroup.isMember(owner);
}
}
diff --git a/pki/base/util/src/netscape/security/acl/PermissionImpl.java b/pki/base/util/src/netscape/security/acl/PermissionImpl.java
index bfd8861c..2b4d4f47 100644
--- a/pki/base/util/src/netscape/security/acl/PermissionImpl.java
+++ b/pki/base/util/src/netscape/security/acl/PermissionImpl.java
@@ -20,8 +20,9 @@ package netscape.security.acl;
import java.security.acl.Permission;
/**
- * The PermissionImpl class implements the permission
- * interface for permissions that are strings.
+ * The PermissionImpl class implements the permission interface for permissions
+ * that are strings.
+ *
* @author Satish Dharmaraj
*/
public class PermissionImpl implements Permission {
@@ -30,33 +31,35 @@ public class PermissionImpl implements Permission {
/**
* Construct a permission object using a string.
+ *
* @param permission the stringified version of the permission.
*/
public PermissionImpl(String permission) {
- this.permission = permission;
+ this.permission = permission;
}
/**
- * This function returns true if the object passed matches the permission
+ * This function returns true if the object passed matches the permission
* represented in this interface.
+ *
* @param another The Permission object to compare with.
* @return true if the Permission objects are equal, false otherwise
*/
public boolean equals(Object another) {
- if (another instanceof Permission) {
- Permission p = (Permission) another;
- return permission.equals(p.toString());
- } else {
- return false;
- }
+ if (another instanceof Permission) {
+ Permission p = (Permission) another;
+ return permission.equals(p.toString());
+ } else {
+ return false;
+ }
}
-
+
/**
* Prints a stringified version of the permission.
+ *
* @return the string representation of the Permission.
*/
public String toString() {
- return permission;
+ return permission;
}
}
-
diff --git a/pki/base/util/src/netscape/security/acl/PrincipalImpl.java b/pki/base/util/src/netscape/security/acl/PrincipalImpl.java
index c2779abe..58b53d90 100644
--- a/pki/base/util/src/netscape/security/acl/PrincipalImpl.java
+++ b/pki/base/util/src/netscape/security/acl/PrincipalImpl.java
@@ -21,8 +21,8 @@ import java.security.Principal;
/**
* This class implements the principal interface.
- *
- * @author Satish Dharmaraj
+ *
+ * @author Satish Dharmaraj
*/
public class PrincipalImpl implements Principal {
@@ -30,53 +30,48 @@ public class PrincipalImpl implements Principal {
/**
* Construct a principal from a string user name.
+ *
* @param user The string form of the principal name.
*/
public PrincipalImpl(String user) {
- this.user = user;
+ this.user = user;
}
/**
- * This function returns true if the object passed matches
- * the principal represented in this implementation
+ * This function returns true if the object passed matches the principal
+ * represented in this implementation
+ *
* @param another the Principal to compare with.
- * @return true if the Principal passed is the same as that
- * encapsulated in this object, false otherwise
+ * @return true if the Principal passed is the same as that encapsulated in
+ * this object, false otherwise
*/
public boolean equals(Object another) {
- if (another instanceof PrincipalImpl) {
- PrincipalImpl p = (PrincipalImpl) another;
- return user.equals(p.toString());
- } else
- return false;
+ if (another instanceof PrincipalImpl) {
+ PrincipalImpl p = (PrincipalImpl) another;
+ return user.equals(p.toString());
+ } else
+ return false;
}
-
+
/**
* Prints a stringified version of the principal.
*/
public String toString() {
- return user;
+ return user;
}
/**
* return a hashcode for the principal.
*/
public int hashCode() {
- return user.hashCode();
+ return user.hashCode();
}
/**
* return the name of the principal.
*/
public String getName() {
- return user;
+ return user;
}
}
-
-
-
-
-
-
-
diff --git a/pki/base/util/src/netscape/security/acl/WorldGroupImpl.java b/pki/base/util/src/netscape/security/acl/WorldGroupImpl.java
index fa9c75bd..d1361763 100644
--- a/pki/base/util/src/netscape/security/acl/WorldGroupImpl.java
+++ b/pki/base/util/src/netscape/security/acl/WorldGroupImpl.java
@@ -21,20 +21,23 @@ import java.security.Principal;
/**
* This class implements a group of principals.
+ *
* @author Satish Dharmaraj
*/
public class WorldGroupImpl extends GroupImpl {
public WorldGroupImpl(String s) {
- super(s);
+ super(s);
}
/**
* returns true for all passed principals
- * @param member The principal whose membership must be checked in this Group.
+ *
+ * @param member The principal whose membership must be checked in this
+ * Group.
* @return true always since this is the "world" group.
*/
public boolean isMember(Principal member) {
- return true;
+ return true;
}
}
diff --git a/pki/base/util/src/netscape/security/extensions/AccessDescription.java b/pki/base/util/src/netscape/security/extensions/AccessDescription.java
index 89b4d829..2c1268bc 100644
--- a/pki/base/util/src/netscape/security/extensions/AccessDescription.java
+++ b/pki/base/util/src/netscape/security/extensions/AccessDescription.java
@@ -25,7 +25,6 @@ import netscape.security.util.DerValue;
import netscape.security.util.ObjectIdentifier;
import netscape.security.x509.GeneralName;
-
public class AccessDescription implements Serializable {
ObjectIdentifier mOID = null;
GeneralName mLocation = null;
@@ -44,12 +43,11 @@ public class AccessDescription implements Serializable {
}
/**
- * For serialization:
- * Note that GeneralName is not serializable. That is
- * why we need to define our own serialization method.
+ * For serialization: Note that GeneralName is not serializable. That is why
+ * we need to define our own serialization method.
*/
private void writeObject(java.io.ObjectOutputStream out)
- throws IOException {
+ throws IOException {
DerOutputStream seq = new DerOutputStream();
DerOutputStream tmp = new DerOutputStream();
@@ -60,12 +58,11 @@ public class AccessDescription implements Serializable {
}
/**
- * For serialization
- * Note that GeneralName is not serializable. That is
- * why we need to define our own serialization method.
+ * For serialization Note that GeneralName is not serializable. That is why
+ * we need to define our own serialization method.
*/
private void readObject(java.io.ObjectInputStream in)
- throws IOException {
+ throws IOException {
DerValue val = new DerValue(in);
DerValue seq = val.data.getDerValue();
diff --git a/pki/base/util/src/netscape/security/extensions/AuthInfoAccessExtension.java b/pki/base/util/src/netscape/security/extensions/AuthInfoAccessExtension.java
index 5f21db5b..4ffa8fe6 100644
--- a/pki/base/util/src/netscape/security/extensions/AuthInfoAccessExtension.java
+++ b/pki/base/util/src/netscape/security/extensions/AuthInfoAccessExtension.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package netscape.security.extensions;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -37,29 +36,24 @@ import netscape.security.x509.Extension;
import netscape.security.x509.GeneralName;
import netscape.security.x509.URIName;
-
/**
- * This represents the authority information access extension
- * as defined in RFC2459.
- *
+ * This represents the authority information access extension as defined in
+ * RFC2459.
+ *
* id-pkix OBJECT IDENTIFIER ::= { iso(1) identified-organization(3) dod(6)
- * internet(1) security(5) mechanisms(5)
- * pkix(7) } }
- * id-pe OBJECT IDENTIFIER ::= { id-pkix 1 }
- * id-pe-authorityInfoAccess OBJECT IDENTIFIER ::= { id-pe 1 }
+ * internet(1) security(5) mechanisms(5) pkix(7) } } id-pe OBJECT IDENTIFIER ::=
+ * { id-pkix 1 } id-pe-authorityInfoAccess OBJECT IDENTIFIER ::= { id-pe 1 }
* AuthorityInfoAccessSyntax ::= SEQUENCE SIZE (1..MAX) OF AccessDescription
- * AccessDescription ::= SEQUENCE {
- * accessMethod OBJECT IDENTIFIER,
- * accessLocation GeneralName
- * }
- * id-ad OBJECT IDENTIFIER ::= { id-pkix 48 }
- * id-ad-ocsp OBJECT IDENTIFIER ::= { id-ad 1 }
- * id-ad-caIssuers OBJECT IDENTIFIER ::= { id-ad 2 }
- *
+ * AccessDescription ::= SEQUENCE { accessMethod OBJECT IDENTIFIER,
+ * accessLocation GeneralName } id-ad OBJECT IDENTIFIER ::= { id-pkix 48 }
+ * id-ad-ocsp OBJECT IDENTIFIER ::= { id-ad 1 } id-ad-caIssuers OBJECT
+ * IDENTIFIER ::= { id-ad 2 }
+ *
* Need to make sure the following is added to CMS.cfg:
- * oidmap.auth_info_access.class=com.netscape.certsrv.cert.AuthInfoAccessExtension
+ * oidmap.auth_info_access.class
+ * =com.netscape.certsrv.cert.AuthInfoAccessExtension
* oidmap.auth_info_access.oid=1.3.6.1.5.5.7.1.1
- *
+ *
* @author thomask
* @version $Revision$, $Date$
*/
@@ -69,12 +63,12 @@ public class AuthInfoAccessExtension extends Extension implements CertAttrSet {
public static final String NAME2 = "AuthorityInformationAccess";
public static final int OID_OCSP[] = { 1, 3, 6, 1, 5, 5, 7, 48, 1 };
- public static final ObjectIdentifier METHOD_OCSP = new
- ObjectIdentifier(OID_OCSP);
+ public static final ObjectIdentifier METHOD_OCSP = new
+ ObjectIdentifier(OID_OCSP);
public static final int OID_CA_ISSUERS[] = { 1, 3, 6, 1, 5, 5, 7, 48, 2 };
- public static final ObjectIdentifier METHOD_CA_ISSUERS = new
- ObjectIdentifier(OID_CA_ISSUERS);
+ public static final ObjectIdentifier METHOD_CA_ISSUERS = new
+ ObjectIdentifier(OID_CA_ISSUERS);
public static final int OID[] = { 1, 3, 6, 1, 5, 5, 7, 1, 1 };
public static final ObjectIdentifier ID = new ObjectIdentifier(OID);
@@ -83,7 +77,7 @@ public class AuthInfoAccessExtension extends Extension implements CertAttrSet {
/**
* Create the extension from the passed DER encoded value of the same.
- *
+ *
* @param critical true if the extension is to be treated as critical.
* @param value Array of DER encoded bytes of the actual value.
* @exception IOException on error.
@@ -94,8 +88,8 @@ public class AuthInfoAccessExtension extends Extension implements CertAttrSet {
this.extensionValue = null; // build this when encodeThis() is called
}
- public AuthInfoAccessExtension(Boolean critical, Object value)
- throws IOException {
+ public AuthInfoAccessExtension(Boolean critical, Object value)
+ throws IOException {
this.extensionId = ID;
this.critical = critical.booleanValue();
this.extensionValue = (byte[]) ((byte[]) value).clone();
@@ -140,14 +134,13 @@ public class AuthInfoAccessExtension extends Extension implements CertAttrSet {
return null;
}
-
/**
* Adds Access Description.
*/
public void addAccessDescription(
- ObjectIdentifier method,
- GeneralName gn) {
- clearValue();
+ ObjectIdentifier method,
+ GeneralName gn) {
+ clearValue();
mDesc.addElement(new AccessDescription(method, gn));
}
@@ -177,7 +170,7 @@ public class AuthInfoAccessExtension extends Extension implements CertAttrSet {
}
}
- private void encodeThis() throws IOException {
+ private void encodeThis() throws IOException {
DerOutputStream seq = new DerOutputStream();
DerOutputStream tmp = new DerOutputStream();
@@ -192,10 +185,10 @@ public class AuthInfoAccessExtension extends Extension implements CertAttrSet {
seq.write(DerValue.tag_Sequence, tmp);
this.extensionValue = seq.toByteArray();
}
-
+
/**
* Write the extension to the DerOutputStream.
- *
+ *
* @param out the DerOutputStream to write the extension to.
* @exception IOException on encoding errors.
*/
@@ -234,7 +227,7 @@ public class AuthInfoAccessExtension extends Extension implements CertAttrSet {
GeneralName caIssuersName = new GeneralName(new
URIName("http://ocsp.netscape.com"));
- aia.addAccessDescription(METHOD_CA_ISSUERS, caIssuersName);
+ aia.addAccessDescription(METHOD_CA_ISSUERS, caIssuersName);
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
@@ -256,7 +249,7 @@ public class AuthInfoAccessExtension extends Extension implements CertAttrSet {
bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
AuthInfoAccessExtension clone = (AuthInfoAccessExtension)
- ois.readObject();
+ ois.readObject();
System.out.println(clone);
} catch (Exception e) {
diff --git a/pki/base/util/src/netscape/security/extensions/CertInfo.java b/pki/base/util/src/netscape/security/extensions/CertInfo.java
index 548a60f6..dabef560 100644
--- a/pki/base/util/src/netscape/security/extensions/CertInfo.java
+++ b/pki/base/util/src/netscape/security/extensions/CertInfo.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package netscape.security.extensions;
-
import java.io.IOException;
import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
@@ -34,10 +33,9 @@ import netscape.security.x509.CertificateVersion;
import netscape.security.x509.X500Name;
import netscape.security.x509.X509CertInfo;
-
/**
- * Extends X509CertInfo class so that minimal fields are initialized at
- * creation time so an object of this type is always serializable.
+ * Extends X509CertInfo class so that minimal fields are initialized at creation
+ * time so an object of this type is always serializable.
*/
public class CertInfo extends X509CertInfo {
/**
@@ -54,35 +52,35 @@ public class CertInfo extends X509CertInfo {
static {
try {
// force version 3
- FORCE_VERSION_3 =
+ FORCE_VERSION_3 =
new CertificateVersion(CertificateVersion.V3);
- SERIALIZE_SUBJECT =
+ SERIALIZE_SUBJECT =
new CertificateSubjectName(
- new X500Name("cn=uninitialized"));
- SERIALIZE_ISSUER =
+ new X500Name("cn=uninitialized"));
+ SERIALIZE_ISSUER =
new CertificateIssuerName(
- new X500Name("cn=uninitialized"));
- SERIALIZE_VALIDITY =
+ new X500Name("cn=uninitialized"));
+ SERIALIZE_VALIDITY =
new CertificateValidity(new Date(0), new Date(0));
- SERIALIZE_SERIALNO =
+ SERIALIZE_SERIALNO =
new CertificateSerialNumber(new BigInteger("0"));
- SERIALIZE_ALGOR =
+ SERIALIZE_ALGOR =
new CertificateAlgorithmId(
- AlgorithmId.getAlgorithmId("MD5withRSA"));
+ AlgorithmId.getAlgorithmId("MD5withRSA"));
} catch (IOException e) {
- // should never happen. If does, system is hosed.
+ // should never happen. If does, system is hosed.
System.out.println("**** Impossible Error encountered ****");
throw new RuntimeException(e.toString());
} catch (NoSuchAlgorithmException e) {
- // should never happen. If does, system is hosed.
+ // should never happen. If does, system is hosed.
System.out.println("**** Impossible Error encountered ****");
throw new RuntimeException(e.toString());
}
}
/**
- * Initializes most fields required by der encoding so object will
- * serialize properly.
+ * Initializes most fields required by der encoding so object will serialize
+ * properly.
*/
// XXX should write a class to use something else for serialization
// but this is faster and done now for the time crunch.
@@ -113,8 +111,8 @@ public class CertInfo extends X509CertInfo {
certinfo.set(X509CertInfo.SUBJECT, SERIALIZE_SUBJECT);
}
// key is set later in the request.
- } // these exceptions shouldn't happen here unless the
- // whole process is hosed.
+ } // these exceptions shouldn't happen here unless the
+ // whole process is hosed.
catch (CertificateException e) {
} catch (IOException e) {
}
diff --git a/pki/base/util/src/netscape/security/extensions/CertificateRenewalWindowExtension.java b/pki/base/util/src/netscape/security/extensions/CertificateRenewalWindowExtension.java
index 8a1e0a6f..c85f7084 100644
--- a/pki/base/util/src/netscape/security/extensions/CertificateRenewalWindowExtension.java
+++ b/pki/base/util/src/netscape/security/extensions/CertificateRenewalWindowExtension.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package netscape.security.extensions;
-
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -31,29 +30,27 @@ import netscape.security.util.ObjectIdentifier;
import netscape.security.x509.CertAttrSet;
import netscape.security.x509.Extension;
-
/**
- * This represents the CertificateRenewalWindow extension
- * as defined in draft-thayes-cert-renewal-00
- *
- * CertificateRenewalWindow ::= SEQUENCE {
- * beginTime GeneralizedTime,
- * endTime GeneralizedTime OPTIONAL }
- *
+ * This represents the CertificateRenewalWindow extension as defined in
+ * draft-thayes-cert-renewal-00
+ *
+ * CertificateRenewalWindow ::= SEQUENCE { beginTime GeneralizedTime, endTime
+ * GeneralizedTime OPTIONAL }
+ *
* @author thomask
* @version $Revision$, $Date$
*/
-public class CertificateRenewalWindowExtension extends Extension
- implements CertAttrSet {
+public class CertificateRenewalWindowExtension extends Extension
+ implements CertAttrSet {
private static final long serialVersionUID = 4470220533545299271L;
- public static final int OID[] = { 2, 16, 840, 1, 113730, 1, 15};
+ public static final int OID[] = { 2, 16, 840, 1, 113730, 1, 15 };
public static final ObjectIdentifier ID = new ObjectIdentifier(OID);
private Date mBeginTime = null;
private Date mEndTime = null; // optional
public CertificateRenewalWindowExtension(boolean critical, Date beginTime,
- Date endTime) throws IOException {
+ Date endTime) throws IOException {
this.extensionId = ID;
this.critical = critical;
mBeginTime = beginTime;
@@ -67,8 +64,8 @@ public class CertificateRenewalWindowExtension extends Extension
this.extensionValue = null; // build this when encodeThis() is called
}
- public CertificateRenewalWindowExtension(Boolean critical, Object value)
- throws IOException {
+ public CertificateRenewalWindowExtension(Boolean critical, Object value)
+ throws IOException {
this.extensionId = ID;
this.critical = critical.booleanValue();
this.extensionValue = (byte[]) ((byte[]) value).clone();
@@ -144,7 +141,7 @@ public class CertificateRenewalWindowExtension extends Extension
}
}
- private void encodeThis() throws IOException {
+ private void encodeThis() throws IOException {
DerOutputStream seq = new DerOutputStream();
DerOutputStream tmp = new DerOutputStream();
@@ -155,10 +152,10 @@ public class CertificateRenewalWindowExtension extends Extension
seq.write(DerValue.tag_Sequence, tmp);
this.extensionValue = seq.toByteArray();
}
-
+
/**
* Write the extension to the DerOutputStream.
- *
+ *
* @param out the DerOutputStream to write the extension to.
* @exception IOException on encoding errors.
*/
diff --git a/pki/base/util/src/netscape/security/extensions/CertificateScopeEntry.java b/pki/base/util/src/netscape/security/extensions/CertificateScopeEntry.java
index 39c87407..553df897 100644
--- a/pki/base/util/src/netscape/security/extensions/CertificateScopeEntry.java
+++ b/pki/base/util/src/netscape/security/extensions/CertificateScopeEntry.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package netscape.security.extensions;
-
import java.io.IOException;
import netscape.security.util.BigInt;
@@ -26,15 +25,13 @@ import netscape.security.util.DerValue;
import netscape.security.x509.GeneralName;
/**
- * This represents the CertificateScopeOfUse extension
- * as defined in draft-thayes-cert-scope-00
- *
- * CertificateScopeEntry ::= SEQUENCE {
- * name GeneralName, -- pattern, as for NameConstraints
- * portNumber INTEGER OPTIONAL
- * }
- * CertificateScopeOfUse ::= SEQUENCE OF CertificateScopeEntry
- *
+ * This represents the CertificateScopeOfUse extension as defined in
+ * draft-thayes-cert-scope-00
+ *
+ * CertificateScopeEntry ::= SEQUENCE { name GeneralName, -- pattern, as for
+ * NameConstraints portNumber INTEGER OPTIONAL } CertificateScopeOfUse ::=
+ * SEQUENCE OF CertificateScopeEntry
+ *
* @author thomask
* @version $Revision$, $Date$
*/
diff --git a/pki/base/util/src/netscape/security/extensions/CertificateScopeOfUseExtension.java b/pki/base/util/src/netscape/security/extensions/CertificateScopeOfUseExtension.java
index b50e55d9..e37c8f87 100644
--- a/pki/base/util/src/netscape/security/extensions/CertificateScopeOfUseExtension.java
+++ b/pki/base/util/src/netscape/security/extensions/CertificateScopeOfUseExtension.java
@@ -32,26 +32,24 @@ import netscape.security.x509.Extension;
import netscape.security.x509.OIDMap;
/**
- * This represents the CertificateScopeOfUse extension
- * as defined in draft-thayes-cert-scope-00
- *
- * CertificateScopeEntry ::= SEQUENCE {
- * name GeneralName, -- pattern, as for NameConstraints
- * portNumber INTEGER OPTIONAL
- * }
- * CertificateScopeOfUse ::= SEQUENCE OF CertificateScopeEntry
- *
+ * This represents the CertificateScopeOfUse extension as defined in
+ * draft-thayes-cert-scope-00
+ *
+ * CertificateScopeEntry ::= SEQUENCE { name GeneralName, -- pattern, as for
+ * NameConstraints portNumber INTEGER OPTIONAL } CertificateScopeOfUse ::=
+ * SEQUENCE OF CertificateScopeEntry
+ *
* @author thomask
* @version $Revision$, $Date$
*/
-public class CertificateScopeOfUseExtension extends Extension
- implements CertAttrSet {
+public class CertificateScopeOfUseExtension extends Extension
+ implements CertAttrSet {
/**
*
*/
private static final long serialVersionUID = 2143292831971567770L;
public static final String NAME = "CertificateScopeOfUse";
- public static final int OID[] = { 2, 16, 840, 1, 113730, 1, 17};
+ public static final int OID[] = { 2, 16, 840, 1, 113730, 1, 17 };
public static final ObjectIdentifier ID = new ObjectIdentifier(OID);
private Vector<CertificateScopeEntry> mEntries = null;
@@ -59,13 +57,13 @@ public class CertificateScopeOfUseExtension extends Extension
static {
try {
OIDMap.addAttribute(CertificateScopeOfUseExtension.class.getName(),
- ID.toString(), NAME);
+ ID.toString(), NAME);
} catch (CertificateException e) {
}
}
public CertificateScopeOfUseExtension(boolean critical, Vector<CertificateScopeEntry> scopeEntries)
- throws IOException {
+ throws IOException {
this.extensionId = ID;
this.critical = critical;
this.extensionValue = null; // build this when encodeThis() is called
@@ -79,8 +77,8 @@ public class CertificateScopeOfUseExtension extends Extension
this.extensionValue = null; // build this when encodeThis() is called
}
- public CertificateScopeOfUseExtension(Boolean critical, Object value)
- throws IOException {
+ public CertificateScopeOfUseExtension(Boolean critical, Object value)
+ throws IOException {
this.extensionId = ID;
this.critical = critical.booleanValue();
this.extensionValue = (byte[]) ((byte[]) value).clone();
@@ -142,7 +140,7 @@ public class CertificateScopeOfUseExtension extends Extension
}
}
- private void encodeThis() throws IOException {
+ private void encodeThis() throws IOException {
DerOutputStream seq = new DerOutputStream();
DerOutputStream tmp = new DerOutputStream();
@@ -151,7 +149,7 @@ public class CertificateScopeOfUseExtension extends Extension
for (int i = 0; i < mEntries.size(); i++) {
CertificateScopeEntry se = (CertificateScopeEntry)
- mEntries.elementAt(i);
+ mEntries.elementAt(i);
se.encode(tmp);
}
@@ -159,10 +157,10 @@ public class CertificateScopeOfUseExtension extends Extension
seq.write(DerValue.tag_Sequence, tmp);
this.extensionValue = seq.toByteArray();
}
-
+
/**
* Write the extension to the DerOutputStream.
- *
+ *
* @param out the DerOutputStream to write the extension to.
* @exception IOException on encoding errors.
*/
@@ -185,7 +183,7 @@ public class CertificateScopeOfUseExtension extends Extension
if (mEntries != null) {
for (int i = 0; i < mEntries.size(); i++) {
CertificateScopeEntry se = (CertificateScopeEntry)
- mEntries.elementAt(i);
+ mEntries.elementAt(i);
s += se.toString();
}
diff --git a/pki/base/util/src/netscape/security/extensions/ExtendedKeyUsageExtension.java b/pki/base/util/src/netscape/security/extensions/ExtendedKeyUsageExtension.java
index 73602f6b..5ed3feb7 100644
--- a/pki/base/util/src/netscape/security/extensions/ExtendedKeyUsageExtension.java
+++ b/pki/base/util/src/netscape/security/extensions/ExtendedKeyUsageExtension.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package netscape.security.extensions;
-
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -32,7 +31,6 @@ import netscape.security.x509.CertAttrSet;
import netscape.security.x509.Extension;
import netscape.security.x509.OIDMap;
-
/**
* This represents the extended key usage extension.
*/
@@ -46,15 +44,15 @@ public class ExtendedKeyUsageExtension extends Extension implements CertAttrSet
public static final String OID_OCSPSigning = "1.3.6.1.5.5.7.3.9";
public static final String OID_CODESigning = "1.3.6.1.5.5.7.3.3";
- public static final int OID_OCSP_SIGNING_STR[] =
+ public static final int OID_OCSP_SIGNING_STR[] =
{ 1, 3, 6, 1, 5, 5, 7, 3, 9 };
public static final ObjectIdentifier OID_OCSP_SIGNING = new
- ObjectIdentifier(OID_OCSP_SIGNING_STR);
+ ObjectIdentifier(OID_OCSP_SIGNING_STR);
- public static final int OID_CODE_SIGNING_STR[] =
+ public static final int OID_CODE_SIGNING_STR[] =
{ 1, 3, 6, 1, 5, 5, 7, 3, 3 };
public static final ObjectIdentifier OID_CODE_SIGNING = new
- ObjectIdentifier(OID_OCSP_SIGNING_STR);
+ ObjectIdentifier(OID_OCSP_SIGNING_STR);
private Vector<ObjectIdentifier> oidSet = null;
private byte mCached[] = null;
@@ -62,7 +60,7 @@ public class ExtendedKeyUsageExtension extends Extension implements CertAttrSet
static {
try {
OIDMap.addAttribute(ExtendedKeyUsageExtension.class.getName(),
- OID, ExtendedKeyUsageExtension.class.getSimpleName());
+ OID, ExtendedKeyUsageExtension.class.getSimpleName());
} catch (CertificateException e) {
}
}
@@ -74,7 +72,7 @@ public class ExtendedKeyUsageExtension extends Extension implements CertAttrSet
public ExtendedKeyUsageExtension(boolean crit, Vector<ObjectIdentifier> oids) {
try {
extensionId = ObjectIdentifier.getObjectIdentifier(OID);
- } catch (IOException e) {
+ } catch (IOException e) {
// never here
}
critical = crit;
@@ -86,8 +84,8 @@ public class ExtendedKeyUsageExtension extends Extension implements CertAttrSet
encodeExtValue();
}
- public ExtendedKeyUsageExtension(Boolean crit, Object byteVal)
- throws IOException {
+ public ExtendedKeyUsageExtension(Boolean crit, Object byteVal)
+ throws IOException {
extensionId = ObjectIdentifier.getObjectIdentifier(OID);
critical = crit.booleanValue();
extensionValue = (byte[]) ((byte[]) byteVal).clone();
@@ -100,7 +98,7 @@ public class ExtendedKeyUsageExtension extends Extension implements CertAttrSet
mCached = null;
}
}
-
+
public Enumeration<ObjectIdentifier> getOIDs() {
if (oidSet == null)
return null;
@@ -109,24 +107,25 @@ public class ExtendedKeyUsageExtension extends Extension implements CertAttrSet
public void deleteAllOIDs() {
if (oidSet == null)
- return;
- oidSet.clear();
+ return;
+ oidSet.clear();
}
public void addOID(ObjectIdentifier oid) {
if (oidSet == null) {
oidSet = new Vector<ObjectIdentifier>();
}
-
- if (oidSet.contains(oid)) return;
+
+ if (oidSet.contains(oid))
+ return;
oidSet.addElement(oid);
mCached = null;
}
-
+
public void encode(DerOutputStream out) throws IOException {
if (mCached == null) {
encodeExtValue();
- super.encode(out);
+ super.encode(out);
mCached = out.toByteArray();
}
}
@@ -143,17 +142,17 @@ public class ExtendedKeyUsageExtension extends Extension implements CertAttrSet
for (int i = 0; i < extensionValue.length; i++) {
extByteValue += (extensionValue[i] + " ");
}
- presentation += extByteValue;
+ presentation += extByteValue;
}
return presentation;
}
- public void decode(InputStream in)
- throws CertificateException, IOException {
+ public void decode(InputStream in)
+ throws CertificateException, IOException {
}
- public void encode(OutputStream out)
- throws CertificateException, IOException {
+ public void encode(OutputStream out)
+ throws CertificateException, IOException {
if (mCached == null) {
DerOutputStream temp = new DerOutputStream();
@@ -162,8 +161,8 @@ public class ExtendedKeyUsageExtension extends Extension implements CertAttrSet
out.write(mCached);
}
- public void set(String name, Object obj)
- throws CertificateException, IOException {
+ public void set(String name, Object obj)
+ throws CertificateException, IOException {
// NOT USED
}
@@ -176,9 +175,8 @@ public class ExtendedKeyUsageExtension extends Extension implements CertAttrSet
return null;
}
-
- public void delete(String name)
- throws CertificateException, IOException {
+ public void delete(String name)
+ throws CertificateException, IOException {
// NOT USED
}
@@ -186,8 +184,7 @@ public class ExtendedKeyUsageExtension extends Extension implements CertAttrSet
DerValue val = new DerValue(this.extensionValue);
if (val.tag != DerValue.tag_Sequence) {
- throw new IOException("Invalid encoding of AuthInfoAccess extension"
- );
+ throw new IOException("Invalid encoding of AuthInfoAccess extension");
}
if (oidSet == null)
oidSet = new Vector<ObjectIdentifier>();
@@ -201,7 +198,7 @@ public class ExtendedKeyUsageExtension extends Extension implements CertAttrSet
private void encodeExtValue() {
DerOutputStream out = new DerOutputStream();
DerOutputStream temp = new DerOutputStream();
-
+
if (!oidSet.isEmpty()) {
Enumeration<ObjectIdentifier> oidList = oidSet.elements();
diff --git a/pki/base/util/src/netscape/security/extensions/GenericASN1Extension.java b/pki/base/util/src/netscape/security/extensions/GenericASN1Extension.java
index 116977da..ac350339 100644
--- a/pki/base/util/src/netscape/security/extensions/GenericASN1Extension.java
+++ b/pki/base/util/src/netscape/security/extensions/GenericASN1Extension.java
@@ -38,13 +38,11 @@ import netscape.security.x509.CertAttrSet;
import netscape.security.x509.Extension;
import netscape.security.x509.OIDMap;
-
-
/**
* Represent the AsnInteger Extension.
*/
-public class GenericASN1Extension extends Extension
-implements CertAttrSet {
+public class GenericASN1Extension extends Extension
+ implements CertAttrSet {
public String getName() {
return name;
}
@@ -75,27 +73,24 @@ implements CertAttrSet {
protected static final String PROP_PREDICATE =
"predicate";
/**
- * Identifier for this attribute, to be used with the
- * get, set, delete methods of Certificate, x509 type.
- */
+ * Identifier for this attribute, to be used with the get, set, delete
+ * methods of Certificate, x509 type.
+ */
private String name;
public static String OID = null;
public static Hashtable<String, String> mConfig = null;
public static String pattern = null;
private int index = 0;
-
// Encode this value
- private void encodeThis()
- throws IOException, ParseException
- {
+ private void encodeThis()
+ throws IOException, ParseException {
this.extensionValue = encodePattern();
}
-
+
// Encode pattern
- private byte[] encodePattern()
- throws IOException, ParseException
- {
+ private byte[] encodePattern()
+ throws IOException, ParseException {
DerOutputStream os = new DerOutputStream();
DerOutputStream tmp = new DerOutputStream();
String type = null;
@@ -104,110 +99,100 @@ implements CertAttrSet {
while (index < pattern.length()) {
char ch = pattern.charAt(index);
switch (ch) {
- case '{' :
- index++;
- byte[] buff = encodePattern();
- tmp.putDerValue(new DerValue(buff));
- break;
- case '}' :
- os.write(DerValue.tag_Sequence, tmp);
- return os.toByteArray();
- default :
- type = (String)mConfig.get(PROP_ATTRIBUTE+"."+ch+"."+PROP_TYPE);
- if (type.equalsIgnoreCase("integer")) {
- int num = Integer.parseInt((String)mConfig.get(PROP_ATTRIBUTE+"."+ch+"."+PROP_VALUE));
- PutInteger(tmp, num);
- }
- else if (type.equalsIgnoreCase("ia5string")) {
- source = (String)mConfig.get(PROP_ATTRIBUTE+"."+ch+"."+PROP_SOURCE);
- value = (String)mConfig.get(PROP_ATTRIBUTE+"."+ch+"."+PROP_VALUE);
- if (source.equalsIgnoreCase("file"))
- PutIA5String(tmp, getFromFile(value));
- else
- PutIA5String(tmp, value);
- }
- else if (type.equalsIgnoreCase("octetstring")) {
- source = (String)mConfig.get(PROP_ATTRIBUTE+"."+ch+"."+PROP_SOURCE);
- value = (String)mConfig.get(PROP_ATTRIBUTE+"."+ch+"."+PROP_VALUE);
- // It should be colon seperated ASCII Hexdecimal String
- if (source.equalsIgnoreCase("file"))
- PutOctetString(tmp, getFromFile(value));
- else
- PutOctetString(tmp, value);
- }
- else if (type.equalsIgnoreCase("bmpstring")) {
- source = (String)mConfig.get(PROP_ATTRIBUTE+"."+ch+"."+PROP_SOURCE);
- value = (String)mConfig.get(PROP_ATTRIBUTE+"."+ch+"."+PROP_VALUE);
- if (source.equalsIgnoreCase("file"))
- PutBMPString(tmp, getFromFile(value));
- else
- PutBMPString(tmp, value);
- }
- else if (type.equalsIgnoreCase("printablestring")) {
- source = (String)mConfig.get(PROP_ATTRIBUTE+"."+ch+"."+PROP_SOURCE);
- value = (String)mConfig.get(PROP_ATTRIBUTE+"."+ch+"."+PROP_VALUE);
- if (source.equalsIgnoreCase("file"))
- PutPrintableString(tmp, getFromFile(value));
- else
- PutPrintableString(tmp, value);
- }
- else if (type.equalsIgnoreCase("visiblestring")) {
- source = (String)mConfig.get(PROP_ATTRIBUTE+"."+ch+"."+PROP_SOURCE);
- value = (String)mConfig.get(PROP_ATTRIBUTE+"."+ch+"."+PROP_VALUE);
- if (source.equalsIgnoreCase("file"))
- PutVisibleString(tmp, getFromFile(value));
- else
- PutVisibleString(tmp, value);
- }
- else if (type.equalsIgnoreCase("utctime")) {
- value = (String)mConfig.get(PROP_ATTRIBUTE+"."+ch+"."+PROP_VALUE);
- PutUTCtime(tmp, value);
- }
- else if (type.equalsIgnoreCase("oid")) {
- value = (String)mConfig.get(PROP_ATTRIBUTE+"."+ch+"."+PROP_VALUE);
- PutOID(tmp, value);
- }
- else if (type.equalsIgnoreCase("boolean")) {
- boolean bool = false;
- String b = (String)mConfig.get(PROP_ATTRIBUTE+"."+ch+"."+PROP_VALUE);
- if (b.equalsIgnoreCase("true"))
- bool = true;
- else
- bool = false;
- PutBoolean(tmp, bool);
- }
- else if (type.equalsIgnoreCase("null")) {
- tmp.putNull();
- }
- else {
- throw new ParseException("Unknown Attribute Type", 0);
- }
+ case '{':
+ index++;
+ byte[] buff = encodePattern();
+ tmp.putDerValue(new DerValue(buff));
+ break;
+ case '}':
+ os.write(DerValue.tag_Sequence, tmp);
+ return os.toByteArray();
+ default:
+ type = (String) mConfig.get(PROP_ATTRIBUTE + "." + ch + "." + PROP_TYPE);
+ if (type.equalsIgnoreCase("integer")) {
+ int num = Integer.parseInt((String) mConfig.get(PROP_ATTRIBUTE + "." + ch + "." + PROP_VALUE));
+ PutInteger(tmp, num);
+ } else if (type.equalsIgnoreCase("ia5string")) {
+ source = (String) mConfig.get(PROP_ATTRIBUTE + "." + ch + "." + PROP_SOURCE);
+ value = (String) mConfig.get(PROP_ATTRIBUTE + "." + ch + "." + PROP_VALUE);
+ if (source.equalsIgnoreCase("file"))
+ PutIA5String(tmp, getFromFile(value));
+ else
+ PutIA5String(tmp, value);
+ } else if (type.equalsIgnoreCase("octetstring")) {
+ source = (String) mConfig.get(PROP_ATTRIBUTE + "." + ch + "." + PROP_SOURCE);
+ value = (String) mConfig.get(PROP_ATTRIBUTE + "." + ch + "." + PROP_VALUE);
+ // It should be colon seperated ASCII Hexdecimal String
+ if (source.equalsIgnoreCase("file"))
+ PutOctetString(tmp, getFromFile(value));
+ else
+ PutOctetString(tmp, value);
+ } else if (type.equalsIgnoreCase("bmpstring")) {
+ source = (String) mConfig.get(PROP_ATTRIBUTE + "." + ch + "." + PROP_SOURCE);
+ value = (String) mConfig.get(PROP_ATTRIBUTE + "." + ch + "." + PROP_VALUE);
+ if (source.equalsIgnoreCase("file"))
+ PutBMPString(tmp, getFromFile(value));
+ else
+ PutBMPString(tmp, value);
+ } else if (type.equalsIgnoreCase("printablestring")) {
+ source = (String) mConfig.get(PROP_ATTRIBUTE + "." + ch + "." + PROP_SOURCE);
+ value = (String) mConfig.get(PROP_ATTRIBUTE + "." + ch + "." + PROP_VALUE);
+ if (source.equalsIgnoreCase("file"))
+ PutPrintableString(tmp, getFromFile(value));
+ else
+ PutPrintableString(tmp, value);
+ } else if (type.equalsIgnoreCase("visiblestring")) {
+ source = (String) mConfig.get(PROP_ATTRIBUTE + "." + ch + "." + PROP_SOURCE);
+ value = (String) mConfig.get(PROP_ATTRIBUTE + "." + ch + "." + PROP_VALUE);
+ if (source.equalsIgnoreCase("file"))
+ PutVisibleString(tmp, getFromFile(value));
+ else
+ PutVisibleString(tmp, value);
+ } else if (type.equalsIgnoreCase("utctime")) {
+ value = (String) mConfig.get(PROP_ATTRIBUTE + "." + ch + "." + PROP_VALUE);
+ PutUTCtime(tmp, value);
+ } else if (type.equalsIgnoreCase("oid")) {
+ value = (String) mConfig.get(PROP_ATTRIBUTE + "." + ch + "." + PROP_VALUE);
+ PutOID(tmp, value);
+ } else if (type.equalsIgnoreCase("boolean")) {
+ boolean bool = false;
+ String b = (String) mConfig.get(PROP_ATTRIBUTE + "." + ch + "." + PROP_VALUE);
+ if (b.equalsIgnoreCase("true"))
+ bool = true;
+ else
+ bool = false;
+ PutBoolean(tmp, bool);
+ } else if (type.equalsIgnoreCase("null")) {
+ tmp.putNull();
+ } else {
+ throw new ParseException("Unknown Attribute Type", 0);
+ }
}
index++;
- }
+ }
return tmp.toByteArray();
}
/**
- * Create a GenericASN1Extension with the value and oid.
- * The criticality is set to false.
- *
+ * Create a GenericASN1Extension with the value and oid. The criticality is
+ * set to false.
+ *
* @param the values to be set for the extension.
*/
public GenericASN1Extension(String name, String oid, String pattern, boolean critical, Hashtable<String, String> config)
- throws IOException, ParseException
- {
+ throws IOException, ParseException {
ObjectIdentifier tmpid = new ObjectIdentifier(oid);
this.name = name;
OID = oid;
mConfig = config;
this.pattern = pattern;
-
+
try {
if (OIDMap.getName(tmpid) == null)
OIDMap.addAttribute("netscape.security.x509.GenericASN1Extension", oid, name);
- } catch (CertificateException e) {}
+ } catch (CertificateException e) {
+ }
this.extensionId = tmpid;
this.critical = critical;
@@ -215,53 +200,52 @@ implements CertAttrSet {
}
/**
- * Create a GenericASN1Extension with the value and oid.
- * The criticality is set to false.
- *
+ * Create a GenericASN1Extension with the value and oid. The criticality is
+ * set to false.
+ *
* @param the values to be set for the extension.
*/
public GenericASN1Extension(Hashtable<String, String> config)
- throws IOException, ParseException
- {
+ throws IOException, ParseException {
mConfig = config;
- ObjectIdentifier tmpid = new ObjectIdentifier((String)mConfig.get(PROP_OID));
- this.name = (String)mConfig.get(PROP_NAME);
- OID = (String)mConfig.get(PROP_OID);
- pattern = (String)mConfig.get(PROP_PATTERN);
-
+ ObjectIdentifier tmpid = new ObjectIdentifier((String) mConfig.get(PROP_OID));
+ this.name = (String) mConfig.get(PROP_NAME);
+ OID = (String) mConfig.get(PROP_OID);
+ pattern = (String) mConfig.get(PROP_PATTERN);
+
try {
if (OIDMap.getName(tmpid) == null)
OIDMap.addAttribute("GenericASN1Extension", OID, this.name);
- } catch (CertificateException e) {}
+ } catch (CertificateException e) {
+ }
this.extensionId = tmpid;
this.critical = false;
- String b = (String)mConfig.get(PROP_CRITICAL);
- if (b.equalsIgnoreCase("true"))
- this.critical = true;
- else
- this.critical = false;
+ String b = (String) mConfig.get(PROP_CRITICAL);
+ if (b.equalsIgnoreCase("true"))
+ this.critical = true;
+ else
+ this.critical = false;
encodeThis();
}
/**
* Create the extension from the passed DER encoded value of the same.
- *
+ *
* @param critical true if the extension is to be treated as critical.
* @param value Array of DER encoded bytes of the actual value.
* @exception IOException on error.
*/
public GenericASN1Extension(Boolean critical, Object value)
- throws IOException
- {
+ throws IOException {
this.extensionId = new ObjectIdentifier(OID);
this.critical = critical.booleanValue();
int len = Array.getLength(value);
- byte[] extValue = new byte[len];
- for (int i = 0; i < len; i++) {
- extValue[i] = Array.getByte(value, i);
- }
+ byte[] extValue = new byte[len];
+ for (int i = 0; i < len; i++) {
+ extValue[i] = Array.getByte(value, i);
+ }
this.extensionValue = extValue;
}
@@ -295,7 +279,7 @@ implements CertAttrSet {
/**
* Decode the extension from the InputStream.
- *
+ *
* @param in the InputStream to unmarshal the contents from.
* @exception IOException on decoding or validity errors.
*/
@@ -305,14 +289,13 @@ implements CertAttrSet {
/**
* Write the extension to the DerOutputStream.
- *
+ *
* @param out the DerOutputStream to write the extension to.
* @exception IOException on encoding errors.
*/
- public void encode(OutputStream out)
- throws IOException
- {
- DerOutputStream tmp = new DerOutputStream();
+ public void encode(OutputStream out)
+ throws IOException {
+ DerOutputStream tmp = new DerOutputStream();
try {
if (this.extensionValue == null) {
@@ -320,106 +303,107 @@ implements CertAttrSet {
this.critical = true;
encodeThis();
}
+ } catch (ParseException e) {
}
- catch (ParseException e) {}
-
+
super.encode(tmp);
out.write(tmp.toByteArray());
}
-
/**
* Set the name of this attribute.
*/
- public void setName (String name) {
+ public void setName(String name) {
this.name = name;
}
-
+
/**
* Return the OID of this attribute.
*/
- public String getOID () {
+ public String getOID() {
return (OID);
}
+
/**
* Set the OID of this attribute.
*/
- public void setOID (String oid) {
+ public void setOID(String oid) {
OID = oid;
}
+
/**
* Return an enumeration of names of attributes existing within this
* attribute.
*/
- public Enumeration<String> getAttributeNames () {
+ public Enumeration<String> getAttributeNames() {
Vector<String> elements = new Vector<String>();
elements.addElement("octet");
- return (elements.elements());
+ return (elements.elements());
}
-
+
private void PutInteger(DerOutputStream os, int number)
- throws IOException, ParseException {
+ throws IOException, ParseException {
os.putInteger(new BigInt(number));
return;
}
-
- private void PutIA5String(DerOutputStream os, String value)
- throws IOException, ParseException {
+
+ private void PutIA5String(DerOutputStream os, String value)
+ throws IOException, ParseException {
os.putIA5String(value);
return;
}
- private void PutOctetString(DerOutputStream os, String value)
- throws IOException, ParseException {
+ private void PutOctetString(DerOutputStream os, String value)
+ throws IOException, ParseException {
StringTokenizer token = new StringTokenizer(value, ":");
byte[] octets = new byte[token.countTokens()];
for (int i = 0; token.hasMoreElements(); i++) {
- String num = (String)token.nextElement();
+ String num = (String) token.nextElement();
octets[i] = (byte) Integer.parseInt(num, 16);
}
-
+
os.putOctetString(octets);
return;
}
- private void PutBMPString(DerOutputStream os, String value)
- throws IOException, ParseException {
+ private void PutBMPString(DerOutputStream os, String value)
+ throws IOException, ParseException {
os.putBMPString(value);
return;
}
- private void PutPrintableString(DerOutputStream os, String value)
- throws IOException, ParseException {
+ private void PutPrintableString(DerOutputStream os, String value)
+ throws IOException, ParseException {
os.putPrintableString(value);
return;
}
- private void PutVisibleString(DerOutputStream os, String value)
- throws IOException, ParseException {
+ private void PutVisibleString(DerOutputStream os, String value)
+ throws IOException, ParseException {
os.putVisibleString(value);
return;
}
- private void PutUTCtime(DerOutputStream os, String value)
- throws IOException, ParseException {
+ private void PutUTCtime(DerOutputStream os, String value)
+ throws IOException, ParseException {
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
os.putUTCTime(df.parse(value));
return;
}
- private void PutOID(DerOutputStream os, String value)
- throws IOException, ParseException {
+ private void PutOID(DerOutputStream os, String value)
+ throws IOException, ParseException {
os.putOID(new ObjectIdentifier(value));
return;
}
private void PutBoolean(DerOutputStream os, boolean value)
- throws IOException, ParseException {
+ throws IOException, ParseException {
os.putBoolean(value);
return;
}
-
+
private String getFromFile(String fname) throws IOException {
String s = null;
byte[] buff = null;
@@ -427,33 +411,34 @@ implements CertAttrSet {
int j = 0;
if ((fname == null) || (fname.equals(""))) {
throw new IOException("File name is not provided.");
- }
-
+ }
+
FileInputStream fis = new FileInputStream(fname);
int n = 0;
while ((n = fis.available()) > 0) {
buff = new byte[n];
int result = fis.read(buff);
- if (result == -1) break;
+ if (result == -1)
+ break;
s = new String(buff);
}
-
+
for (i = 0, j = 0; j < s.length(); j++) {
- int ch = (int)s.charAt(j);
+ int ch = (int) s.charAt(j);
if (ch == 10 || ch == 13 || ch == 9)
continue;
i++;
- }
+ }
buff = new byte[i];
for (i = 0, j = 0; j < s.length(); j++) {
- int ch = (int)s.charAt(j);
+ int ch = (int) s.charAt(j);
if (ch == 10 || ch == 13 || ch == 9)
continue;
- buff[i++] = (byte)ch;
- }
-
+ buff[i++] = (byte) ch;
+ }
+
s = new String(buff);
-
- return s;
- }
+
+ return s;
+ }
}
diff --git a/pki/base/util/src/netscape/security/extensions/InhibitAnyPolicyExtension.java b/pki/base/util/src/netscape/security/extensions/InhibitAnyPolicyExtension.java
index ce1268ad..c1b9c2e8 100644
--- a/pki/base/util/src/netscape/security/extensions/InhibitAnyPolicyExtension.java
+++ b/pki/base/util/src/netscape/security/extensions/InhibitAnyPolicyExtension.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package netscape.security.extensions;
-
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -34,17 +33,16 @@ import netscape.security.x509.Extension;
import netscape.security.x509.OIDMap;
/**
- * RFC3280:
- *
- * id-ce-inhibitAnyPolicy OBJECT IDENTIFIER ::= { id-ce 54 }
+ * RFC3280:
+ *
+ * id-ce-inhibitAnyPolicy OBJECT IDENTIFIER ::= { id-ce 54 }
*
- * InhibitAnyPolicy ::= SkipCerts
+ * InhibitAnyPolicy ::= SkipCerts
*
- * SkipCerts ::= INTEGER (0..MAX)
+ * SkipCerts ::= INTEGER (0..MAX)
*/
-public class InhibitAnyPolicyExtension
- extends Extension implements CertAttrSet
-{
+public class InhibitAnyPolicyExtension
+ extends Extension implements CertAttrSet {
/**
*
@@ -57,7 +55,7 @@ public class InhibitAnyPolicyExtension
static {
try {
OIDMap.addAttribute(InhibitAnyPolicyExtension.class.getName(),
- OID, InhibitAnyPolicyExtension.class.getSimpleName());
+ OID, InhibitAnyPolicyExtension.class.getSimpleName());
} catch (CertificateException e) {
}
}
@@ -69,23 +67,23 @@ public class InhibitAnyPolicyExtension
public InhibitAnyPolicyExtension(boolean crit, BigInt skipCerts) {
try {
extensionId = ObjectIdentifier.getObjectIdentifier(OID);
- } catch (IOException e) {
+ } catch (IOException e) {
// never here
}
critical = crit;
- mSkipCerts = skipCerts;
+ mSkipCerts = skipCerts;
encodeExtValue();
}
- public InhibitAnyPolicyExtension(Boolean crit, Object value)
- throws IOException {
+ public InhibitAnyPolicyExtension(Boolean crit, Object value)
+ throws IOException {
extensionId = ObjectIdentifier.getObjectIdentifier(OID);
critical = crit.booleanValue();
- //extensionValue = (byte[]) ((byte[]) byteVal).clone();
+ // extensionValue = (byte[]) ((byte[]) byteVal).clone();
int len = Array.getLength(value);
byte[] extValue = new byte[len];
for (int i = 0; i < len; i++) {
- extValue[i] = Array.getByte(value, i);
+ extValue[i] = Array.getByte(value, i);
}
extensionValue = extValue;
@@ -97,7 +95,7 @@ public class InhibitAnyPolicyExtension
critical = newValue;
}
}
-
+
public BigInt getSkipCerts() {
return mSkipCerts;
}
@@ -113,17 +111,17 @@ public class InhibitAnyPolicyExtension
if (extensionValue != null) {
String extByteValue = new String(" skipCerts=" + mSkipCerts);
- presentation += extByteValue;
+ presentation += extByteValue;
}
return presentation;
}
- public void decode(InputStream in)
- throws CertificateException, IOException {
+ public void decode(InputStream in)
+ throws CertificateException, IOException {
}
- public void set(String name, Object obj)
- throws CertificateException, IOException {
+ public void set(String name, Object obj)
+ throws CertificateException, IOException {
// NOT USED
}
@@ -136,9 +134,8 @@ public class InhibitAnyPolicyExtension
return null;
}
-
- public void delete(String name)
- throws CertificateException, IOException {
+ public void delete(String name)
+ throws CertificateException, IOException {
// NOT USED
}
@@ -149,27 +146,27 @@ public class InhibitAnyPolicyExtension
}
public void encode(OutputStream out) throws IOException {
- DerOutputStream tmp = new DerOutputStream();
+ DerOutputStream tmp = new DerOutputStream();
- if (this.extensionValue == null) {
+ if (this.extensionValue == null) {
try {
extensionId = ObjectIdentifier.getObjectIdentifier(OID);
- } catch (IOException e) {
+ } catch (IOException e) {
// never here
}
DerOutputStream os = new DerOutputStream();
os.putInteger(mSkipCerts);
this.extensionValue = os.toByteArray();
- }
+ }
- super.encode(tmp);
- out.write(tmp.toByteArray());
+ super.encode(tmp);
+ out.write(tmp.toByteArray());
}
private void encodeExtValue() {
DerOutputStream out = new DerOutputStream();
try {
- out.putInteger(mSkipCerts);
+ out.putInteger(mSkipCerts);
} catch (IOException e) {
}
extensionValue = out.toByteArray();
diff --git a/pki/base/util/src/netscape/security/extensions/KerberosName.java b/pki/base/util/src/netscape/security/extensions/KerberosName.java
index 0aeda430..2997c1d9 100644
--- a/pki/base/util/src/netscape/security/extensions/KerberosName.java
+++ b/pki/base/util/src/netscape/security/extensions/KerberosName.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package netscape.security.extensions;
-
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
@@ -30,28 +29,23 @@ import netscape.security.util.DerValue;
import netscape.security.util.ObjectIdentifier;
/**
- * This represents a KerberosName as defined in
- * RFC 1510.
- *
- * KerberosName ::= SEQUENCE {
- * realm [0] Realm,
- * principalName [1] CertPrincipalName -- defined above
- * }
- *
- * CertPrincipalName ::= SEQUENCE {
- * name-type[0] INTEGER,
- * name-string[1] SEQUENCE OF UTF8String
- * }
- *
+ * This represents a KerberosName as defined in RFC 1510.
+ *
+ * KerberosName ::= SEQUENCE { realm [0] Realm, principalName [1]
+ * CertPrincipalName -- defined above }
+ *
+ * CertPrincipalName ::= SEQUENCE { name-type[0] INTEGER, name-string[1]
+ * SEQUENCE OF UTF8String }
+ *
* @author thomask
* @version $Revision$, $Date$
*/
public class KerberosName {
public static final int OID[] = { 1, 3, 6, 1, 5, 2, 2 };
- public static final ObjectIdentifier KRB5_PRINCIPAL_NAME = new
- ObjectIdentifier(OID);
-
+ public static final ObjectIdentifier KRB5_PRINCIPAL_NAME = new
+ ObjectIdentifier(OID);
+
private String m_realm = null;
private int m_name_type = 0;
private Vector<String> m_name_strings = null;
@@ -64,7 +58,7 @@ public class KerberosName {
/**
* Write the extension to the DerOutputStream.
- *
+ *
* @param out the DerOutputStream to write the extension to.
* @exception IOException on encoding errors.
*/
@@ -75,48 +69,48 @@ public class KerberosName {
DerOutputStream realm = new DerOutputStream();
realm.putGeneralString(m_realm);
tmp.write(DerValue.createTag(DerValue.TAG_CONTEXT,
- true, (byte)0), realm);
+ true, (byte) 0), realm);
DerOutputStream seq1 = new DerOutputStream();
DerOutputStream tmp1 = new DerOutputStream();
DerOutputStream name_type = new DerOutputStream();
name_type.putInteger(new BigInt(m_name_type));
tmp1.write(DerValue.createTag(DerValue.TAG_CONTEXT,
- true, (byte)0), name_type);
+ true, (byte) 0), name_type);
DerOutputStream name_strings = new DerOutputStream();
DerOutputStream name_string = new DerOutputStream();
for (int i = 0; i < m_name_strings.size(); i++) {
- name_string.putGeneralString((String)m_name_strings.elementAt(i));
+ name_string.putGeneralString((String) m_name_strings.elementAt(i));
}
name_strings.write(DerValue.tag_SequenceOf, name_string);
tmp1.write(DerValue.createTag(DerValue.TAG_CONTEXT,
- true, (byte)1), name_strings);
+ true, (byte) 1), name_strings);
seq1.write(DerValue.tag_Sequence, tmp1);
tmp.write(DerValue.createTag(DerValue.TAG_CONTEXT,
- true, (byte)1), seq1);
+ true, (byte) 1), seq1);
seq.write(DerValue.tag_Sequence, tmp);
out.write(seq.toByteArray());
}
public byte[] toByteArray() throws IOException {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- encode(bos);
- return bos.toByteArray();
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ encode(bos);
+ return bos.toByteArray();
}
public String toString() {
- String strings = null;
- for (int i = 0; i < m_name_strings.size(); i++) {
- if (strings == null) {
- strings = (String)m_name_strings.elementAt(i);
- } else {
- strings += ",";
- strings += (String)m_name_strings.elementAt(i);
- }
- }
- return "Realm: " + m_realm + " Name Type: " + m_name_type + " Name String(s):" + strings;
+ String strings = null;
+ for (int i = 0; i < m_name_strings.size(); i++) {
+ if (strings == null) {
+ strings = (String) m_name_strings.elementAt(i);
+ } else {
+ strings += ",";
+ strings += (String) m_name_strings.elementAt(i);
+ }
+ }
+ return "Realm: " + m_realm + " Name Type: " + m_name_type + " Name String(s):" + strings;
}
public static void main(String[] argv) {
@@ -126,11 +120,11 @@ public class KerberosName {
System.out.println(k.toString());
try {
- FileOutputStream os = new FileOutputStream("/tmp/out.der");
- k.encode(os);
- os.close();
+ FileOutputStream os = new FileOutputStream("/tmp/out.der");
+ k.encode(os);
+ os.close();
} catch (Exception e) {
- System.out.println(e.toString());
+ System.out.println(e.toString());
}
}
}
diff --git a/pki/base/util/src/netscape/security/extensions/NSCertTypeExtension.java b/pki/base/util/src/netscape/security/extensions/NSCertTypeExtension.java
index f8b357e8..9da5b661 100644
--- a/pki/base/util/src/netscape/security/extensions/NSCertTypeExtension.java
+++ b/pki/base/util/src/netscape/security/extensions/NSCertTypeExtension.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package netscape.security.extensions;
-
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -32,14 +31,13 @@ import netscape.security.x509.CertAttrSet;
import netscape.security.x509.Extension;
/**
- * NSCertTypeExtension
- * Represents Netscape Certificate Type Extension
- *
- * <p>This deprecated extension, if present, defines both the purpose
- * (e.g., encipherment, signature, certificate signing) and the application
- * (e.g., SSL, S/Mime or Object Signing of the key contained in the
- * certificate.
- *
+ * NSCertTypeExtension Represents Netscape Certificate Type Extension
+ *
+ * <p>
+ * This deprecated extension, if present, defines both the purpose (e.g.,
+ * encipherment, signature, certificate signing) and the application (e.g., SSL,
+ * S/Mime or Object Signing of the key contained in the certificate.
+ *
* @author galperin
* @version $Revision$, $Date$
*/
@@ -57,36 +55,36 @@ public class NSCertTypeExtension extends Extension implements CertAttrSet {
* Identifies the particular public key used to sign the certificate.
*/
public static final ObjectIdentifier CertType_Id = new
- ObjectIdentifier(CertType_data);
-
- /**
- * Attribute names.
- */
- public static final String SSL_CLIENT = "ssl_client";
- public static final String SSL_SERVER = "ssl_server";
- public static final String EMAIL = "email";
- public static final String OBJECT_SIGNING = "object_signing";
- public static final String SSL_CA = "ssl_ca";
- public static final String EMAIL_CA = "email_ca";
- public static final String OBJECT_SIGNING_CA = "object_signing_ca";
-
- /**
- * Attribute names.
- */
- public static final int SSL_CLIENT_BIT = 0;
- public static final int SSL_SERVER_BIT = 1;
- public static final int EMAIL_BIT = 2;
- public static final int OBJECT_SIGNING_BIT = 3;
- // 4 is reserved.
- public static final int SSL_CA_BIT = 5;
- public static final int EMAIL_CA_BIT = 6;
- public static final int OBJECT_SIGNING_CA_BIT = 7;
-
- public static final int NBITS = 8;
+ ObjectIdentifier(CertType_data);
/**
- * Identifier for this attribute, to be used with the
- * get, set, delete methods of Certificate, x509 type.
+ * Attribute names.
+ */
+ public static final String SSL_CLIENT = "ssl_client";
+ public static final String SSL_SERVER = "ssl_server";
+ public static final String EMAIL = "email";
+ public static final String OBJECT_SIGNING = "object_signing";
+ public static final String SSL_CA = "ssl_ca";
+ public static final String EMAIL_CA = "email_ca";
+ public static final String OBJECT_SIGNING_CA = "object_signing_ca";
+
+ /**
+ * Attribute names.
+ */
+ public static final int SSL_CLIENT_BIT = 0;
+ public static final int SSL_SERVER_BIT = 1;
+ public static final int EMAIL_BIT = 2;
+ public static final int OBJECT_SIGNING_BIT = 3;
+ // 4 is reserved.
+ public static final int SSL_CA_BIT = 5;
+ public static final int EMAIL_CA_BIT = 6;
+ public static final int OBJECT_SIGNING_CA_BIT = 7;
+
+ public static final int NBITS = 8;
+
+ /**
+ * Identifier for this attribute, to be used with the get, set, delete
+ * methods of Certificate, x509 type.
*/
public static final String IDENT = "x509.info.extensions.NSCertType";
@@ -105,14 +103,14 @@ public class NSCertTypeExtension extends Extension implements CertAttrSet {
private static MapEntry[] mMapData =
{
- new MapEntry(SSL_CLIENT, 0),
- new MapEntry(SSL_SERVER, 1),
- new MapEntry(EMAIL, 2),
- new MapEntry(OBJECT_SIGNING, 3),
- // note that bit 4 is reserved
- new MapEntry(SSL_CA, 5),
- new MapEntry(EMAIL_CA, 6),
- new MapEntry(OBJECT_SIGNING_CA, 7),
+ new MapEntry(SSL_CLIENT, 0),
+ new MapEntry(SSL_SERVER, 1),
+ new MapEntry(EMAIL, 2),
+ new MapEntry(OBJECT_SIGNING, 3),
+ // note that bit 4 is reserved
+ new MapEntry(SSL_CA, 5),
+ new MapEntry(EMAIL_CA, 6),
+ new MapEntry(OBJECT_SIGNING_CA, 7),
};
private static Vector<String> mAttributeNames = new Vector<String>();
@@ -143,7 +141,7 @@ public class NSCertTypeExtension extends Extension implements CertAttrSet {
/**
* Check if bit is set.
- *
+ *
* @param position the position in the bit string to check.
*/
public boolean isSet(int position) {
@@ -176,8 +174,8 @@ public class NSCertTypeExtension extends Extension implements CertAttrSet {
}
/**
- * Create NSCertTypeExtension from boolean array.
- * The criticality is set to false.
+ * Create NSCertTypeExtension from boolean array. The criticality is set to
+ * false.
*/
public NSCertTypeExtension(boolean critical, boolean[] bits) {
this.extensionId = CertType_Id;
@@ -200,9 +198,9 @@ public class NSCertTypeExtension extends Extension implements CertAttrSet {
}
/**
- * Create a NSCertTypeExtension with the passed bit settings.
- * The criticality is set to false.
- *
+ * Create a NSCertTypeExtension with the passed bit settings. The
+ * criticality is set to false.
+ *
* @param bitString the bits to be set for the extension.
*/
public NSCertTypeExtension(boolean critical, byte[] bitString) throws IOException {
@@ -221,19 +219,17 @@ public class NSCertTypeExtension extends Extension implements CertAttrSet {
/**
* Create the extension from the passed DER encoded value of the same.
- *
+ *
* @param critical true if the extension is to be treated as critical.
* @param value Array of DER encoded bytes of the actual value.
* @exception IOException on error.
*/
public NSCertTypeExtension(Boolean critical, Object value)
- throws IOException {
+ throws IOException {
/**
- Debug.trace("NSCertTypeExtension");
- this.mBitString = new byte[1];
- this.mBitString[0] = (byte)0x00;
- return;
+ * Debug.trace("NSCertTypeExtension"); this.mBitString = new byte[1];
+ * this.mBitString[0] = (byte)0x00; return;
**/
this.extensionId = CertType_Id;
@@ -253,10 +249,10 @@ public class NSCertTypeExtension extends Extension implements CertAttrSet {
this.extensionId = CertType_Id;
this.critical = false;
this.mBitString = new byte[0];
- try {
- encodeThis();
- } catch (Exception e) {
- }
+ try {
+ encodeThis();
+ } catch (Exception e) {
+ }
}
/**
@@ -264,8 +260,7 @@ public class NSCertTypeExtension extends Extension implements CertAttrSet {
*/
public void set(String name, Object obj) throws CertificateException {
if (!(obj instanceof Boolean)) {
- throw new CertificateException
- ("Attribute must be of type Boolean.");
+ throw new CertificateException("Attribute must be of type Boolean.");
}
boolean val = ((Boolean) obj).booleanValue();
@@ -333,7 +328,7 @@ public class NSCertTypeExtension extends Extension implements CertAttrSet {
/**
* Decode the extension from the InputStream.
- *
+ *
* @param in the InputStream to unmarshal the contents from.
* @exception IOException on decoding or validity errors.
*/
@@ -343,12 +338,12 @@ public class NSCertTypeExtension extends Extension implements CertAttrSet {
/**
* Write the extension to the DerOutputStream.
- *
+ *
* @param out the DerOutputStream to write the extension to.
* @exception IOException on encoding errors.
*/
public void encode(OutputStream out) throws IOException {
- DerOutputStream tmp = new DerOutputStream();
+ DerOutputStream tmp = new DerOutputStream();
encodeThis();
if (this.extensionValue == null) {
@@ -367,7 +362,6 @@ public class NSCertTypeExtension extends Extension implements CertAttrSet {
return mAttributeNames.elements();
}
-
public static void main(String[] argv) {
}
}
diff --git a/pki/base/util/src/netscape/security/extensions/OCSPNoCheckExtension.java b/pki/base/util/src/netscape/security/extensions/OCSPNoCheckExtension.java
index 544d5959..0a308d8e 100644
--- a/pki/base/util/src/netscape/security/extensions/OCSPNoCheckExtension.java
+++ b/pki/base/util/src/netscape/security/extensions/OCSPNoCheckExtension.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package netscape.security.extensions;
-
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -30,7 +29,6 @@ import netscape.security.x509.CertAttrSet;
import netscape.security.x509.Extension;
import netscape.security.x509.OIDMap;
-
/**
* This represents the OCSPNoCheck extension.
*/
@@ -47,7 +45,7 @@ public class OCSPNoCheckExtension extends Extension implements CertAttrSet {
static {
try {
OIDMap.addAttribute(OCSPNoCheckExtension.class.getName(),
- OID, OCSPNoCheckExtension.class.getSimpleName());
+ OID, OCSPNoCheckExtension.class.getSimpleName());
} catch (CertificateException e) {
}
}
@@ -81,7 +79,7 @@ public class OCSPNoCheckExtension extends Extension implements CertAttrSet {
critical = crit.booleanValue();
extensionValue = (byte[]) ((byte[]) byteVal).clone();
}
-
+
public void setCritical(boolean newValue) {
if (critical != newValue) {
critical = newValue;
@@ -95,7 +93,7 @@ public class OCSPNoCheckExtension extends Extension implements CertAttrSet {
mCached = out.toByteArray();
}
}
-
+
public String toString() {
String presentation = "oid=" + OID + " ";
@@ -108,18 +106,18 @@ public class OCSPNoCheckExtension extends Extension implements CertAttrSet {
for (int i = 0; i < extensionValue.length; i++) {
extByteValue += (extensionValue[i] + " ");
}
- presentation += extByteValue;
+ presentation += extByteValue;
}
return presentation;
}
- public void decode(InputStream in)
- throws CertificateException, IOException {
+ public void decode(InputStream in)
+ throws CertificateException, IOException {
// NOT USED
}
- public void encode(OutputStream out)
- throws CertificateException, IOException {
+ public void encode(OutputStream out)
+ throws CertificateException, IOException {
if (mCached == null) {
DerOutputStream temp = new DerOutputStream();
@@ -128,8 +126,8 @@ public class OCSPNoCheckExtension extends Extension implements CertAttrSet {
out.write(mCached);
}
- public void set(String name, Object obj)
- throws CertificateException, IOException {
+ public void set(String name, Object obj)
+ throws CertificateException, IOException {
// NOT USED
}
@@ -143,8 +141,8 @@ public class OCSPNoCheckExtension extends Extension implements CertAttrSet {
return null;
}
- public void delete(String name)
- throws CertificateException, IOException {
+ public void delete(String name)
+ throws CertificateException, IOException {
// NOT USED
}
}
diff --git a/pki/base/util/src/netscape/security/extensions/PresenceServerExtension.java b/pki/base/util/src/netscape/security/extensions/PresenceServerExtension.java
index ecd8f4f6..8935db83 100644
--- a/pki/base/util/src/netscape/security/extensions/PresenceServerExtension.java
+++ b/pki/base/util/src/netscape/security/extensions/PresenceServerExtension.java
@@ -33,8 +33,7 @@ import netscape.security.util.ObjectIdentifier;
import netscape.security.x509.CertAttrSet;
import netscape.security.x509.Extension;
-public class PresenceServerExtension extends Extension implements CertAttrSet
-{
+public class PresenceServerExtension extends Extension implements CertAttrSet {
/**
*
*/
@@ -53,173 +52,159 @@ public class PresenceServerExtension extends Extension implements CertAttrSet
public static final String OID = "2.16.840.1.113730.1.18";
-/*
- public PresenceServerExtension()
- {
- }
-*/
+ /*
+ * public PresenceServerExtension() { }
+ */
public PresenceServerExtension(Boolean critical, Object value)
- throws IOException {
- this.extensionId = new ObjectIdentifier(OID);
- this.critical = critical.booleanValue();
- this.extensionValue = (byte[]) ((byte[]) value).clone();
- decodeThis();
- }
+ throws IOException {
+ this.extensionId = new ObjectIdentifier(OID);
+ this.critical = critical.booleanValue();
+ this.extensionValue = (byte[]) ((byte[]) value).clone();
+ decodeThis();
+ }
public PresenceServerExtension(
- boolean critical,
- int version,
- String streetAddress,
- String telephoneNumber,
- String rfc822Name,
- String ID,
- String hostName,
- int portNumber,
- int maxUsers,
- int serviceLevel)
- throws IOException
- {
- mCritical = critical;
- mVersion = version;
- mStreetAddress = streetAddress;
- mTelephoneNumber = telephoneNumber;
- mRFC822Name = rfc822Name;
- mID = ID;
- mHostName = hostName;
- mPortNumber = portNumber;
- mMaxUsers = maxUsers;
- mServiceLevel = serviceLevel;
-
- this.extensionId = new ObjectIdentifier(OID);
- this.critical = mCritical;
- encodeThis();
+ boolean critical,
+ int version,
+ String streetAddress,
+ String telephoneNumber,
+ String rfc822Name,
+ String ID,
+ String hostName,
+ int portNumber,
+ int maxUsers,
+ int serviceLevel)
+ throws IOException {
+ mCritical = critical;
+ mVersion = version;
+ mStreetAddress = streetAddress;
+ mTelephoneNumber = telephoneNumber;
+ mRFC822Name = rfc822Name;
+ mID = ID;
+ mHostName = hostName;
+ mPortNumber = portNumber;
+ mMaxUsers = maxUsers;
+ mServiceLevel = serviceLevel;
+
+ this.extensionId = new ObjectIdentifier(OID);
+ this.critical = mCritical;
+ encodeThis();
+ }
+
+ public int getVersion() {
+ return mVersion;
+ }
+
+ public String getStreetAddress() {
+ return mStreetAddress;
+ }
+
+ public String getTelephoneNumber() {
+ return mTelephoneNumber;
+ }
+
+ public String getRFC822() {
+ return mRFC822Name;
}
- public int getVersion()
- {
- return mVersion;
- }
-
- public String getStreetAddress()
- {
- return mStreetAddress;
- }
-
- public String getTelephoneNumber()
- {
- return mTelephoneNumber;
- }
-
- public String getRFC822()
- {
- return mRFC822Name;
- }
-
- public String getID()
- {
- return mID;
- }
-
- public String getHostName()
- {
- return mHostName;
- }
-
- public int getPortNumber()
- {
- return mPortNumber;
- }
-
- public int getMaxUsers()
- {
- return mMaxUsers;
- }
-
- public int getServiceLevel()
- {
- return mServiceLevel;
- }
-
- public void encodeThis() throws IOException
- {
- DerOutputStream out = new DerOutputStream();
- DerOutputStream temp = new DerOutputStream();
- temp.putInteger(new BigInt(mVersion));
- temp.putOctetString(mStreetAddress.getBytes());
- temp.putOctetString(mTelephoneNumber.getBytes());
- temp.putOctetString(mRFC822Name.getBytes());
- temp.putOctetString(mID.getBytes());
- temp.putOctetString(mHostName.getBytes());
- temp.putInteger(new BigInt(mPortNumber));
- temp.putInteger(new BigInt(mMaxUsers));
- temp.putInteger(new BigInt(mServiceLevel));
- out.write(DerValue.tag_Sequence, temp);
- this.extensionValue = out.toByteArray();
+ public String getID() {
+ return mID;
}
- public void decodeThis() throws IOException
- {
- DerInputStream val = new DerInputStream(this.extensionValue);
- byte data[] = null;
- DerValue seq[] = val.getSequence(0);
+ public String getHostName() {
+ return mHostName;
+ }
+
+ public int getPortNumber() {
+ return mPortNumber;
+ }
+
+ public int getMaxUsers() {
+ return mMaxUsers;
+ }
+
+ public int getServiceLevel() {
+ return mServiceLevel;
+ }
+
+ public void encodeThis() throws IOException {
+ DerOutputStream out = new DerOutputStream();
+ DerOutputStream temp = new DerOutputStream();
+ temp.putInteger(new BigInt(mVersion));
+ temp.putOctetString(mStreetAddress.getBytes());
+ temp.putOctetString(mTelephoneNumber.getBytes());
+ temp.putOctetString(mRFC822Name.getBytes());
+ temp.putOctetString(mID.getBytes());
+ temp.putOctetString(mHostName.getBytes());
+ temp.putInteger(new BigInt(mPortNumber));
+ temp.putInteger(new BigInt(mMaxUsers));
+ temp.putInteger(new BigInt(mServiceLevel));
+ out.write(DerValue.tag_Sequence, temp);
+ this.extensionValue = out.toByteArray();
+ }
+
+ public void decodeThis() throws IOException {
+ DerInputStream val = new DerInputStream(this.extensionValue);
+ byte data[] = null;
+ DerValue seq[] = val.getSequence(0);
mVersion = seq[0].getInteger().toInt();
- data = null;
- if (seq[1].length() > 0) {
- data = seq[1].getOctetString();
- }
- if (data == null) {
- mStreetAddress = "";
- } else {
- mStreetAddress = new String(data);
- }
- data = null;
- if (seq[2].length() > 0)
- data = seq[2].getOctetString();
- if (data == null) {
- mTelephoneNumber = "";
- } else {
- mTelephoneNumber = new String(data);
- }
- data = null;
- if (seq[3].length() > 0)
- data = seq[3].getOctetString();
- if (data == null) {
- mRFC822Name = "";
- } else {
- mRFC822Name = new String(data);
- }
- data = null;
- if (seq[4].length() > 0)
- data = seq[4].getOctetString();
- if (data == null) {
- mID = "";
- } else {
- mID = new String(data);
- }
- data = null;
- if (seq[5].length() > 0)
- data = seq[5].getOctetString();
- if (data == null) {
- mHostName = "";
- } else {
- mHostName = new String(data);
- }
+ data = null;
+ if (seq[1].length() > 0) {
+ data = seq[1].getOctetString();
+ }
+ if (data == null) {
+ mStreetAddress = "";
+ } else {
+ mStreetAddress = new String(data);
+ }
+ data = null;
+ if (seq[2].length() > 0)
+ data = seq[2].getOctetString();
+ if (data == null) {
+ mTelephoneNumber = "";
+ } else {
+ mTelephoneNumber = new String(data);
+ }
+ data = null;
+ if (seq[3].length() > 0)
+ data = seq[3].getOctetString();
+ if (data == null) {
+ mRFC822Name = "";
+ } else {
+ mRFC822Name = new String(data);
+ }
+ data = null;
+ if (seq[4].length() > 0)
+ data = seq[4].getOctetString();
+ if (data == null) {
+ mID = "";
+ } else {
+ mID = new String(data);
+ }
+ data = null;
+ if (seq[5].length() > 0)
+ data = seq[5].getOctetString();
+ if (data == null) {
+ mHostName = "";
+ } else {
+ mHostName = new String(data);
+ }
mPortNumber = seq[6].getInteger().toInt();
mMaxUsers = seq[7].getInteger().toInt();
mServiceLevel = seq[8].getInteger().toInt();
}
- public void decode(InputStream in)
- throws CertificateException, IOException {
+ public void decode(InputStream in)
+ throws CertificateException, IOException {
}
public void encode(OutputStream out)
- throws CertificateException, IOException {
- DerOutputStream dos = new DerOutputStream();
- super.encode(dos);
- out.write(dos.toByteArray());
+ throws CertificateException, IOException {
+ DerOutputStream dos = new DerOutputStream();
+ super.encode(dos);
+ out.write(dos.toByteArray());
}
/**
@@ -243,84 +228,69 @@ public class PresenceServerExtension extends Extension implements CertAttrSet
throw new IOException("Method not to be called directly.");
}
- public Enumeration<String> getAttributeNames () {
- return null;
+ public Enumeration<String> getAttributeNames() {
+ return null;
}
/**
* Set the name of this attribute.
*/
- public void setName (String name) {
+ public void setName(String name) {
}
/**
* Return the OID of this attribute.
*/
- public String getOID () {
- return OID;
+ public String getOID() {
+ return OID;
}
/**
* Set the OID of this attribute.
*/
- public void setOID (String oid) {
+ public void setOID(String oid) {
}
- public static void main(String args[]) throws Exception
- {
-/*
- 0 30 115: SEQUENCE {
- 2 06 9: OBJECT IDENTIFIER '2 16 840 1 113730 1 100'
- 13 04 102: OCTET STRING, encapsulates {
- 15 30 100: SEQUENCE {
- 17 02 1: INTEGER 0
- 20 04 31: OCTET STRING
- : 34 30 31 45 20 4D 69 64 64 6C 65 66 69 65 6C 64
- : 20 52 64 2E 2C 4D 56 2C 43 41 39 34 30 34 31
- 53 04 12: OCTET STRING
- : 36 35 30 2D 31 31 31 2D 31 31 31 31
- 67 04 18: OCTET STRING
- : 61 64 6D 69 6E 40 6E 65 74 73 63 61 70 65 2E 63
- : 6F 6D
- 87 04 10: OCTET STRING
- : 70 73 2D 63 61 70 69 74 6F 6C
- 99 04 7: OCTET STRING
- : 63 61 70 69 74 6F 6C
- 108 02 1: INTEGER 80
- 111 02 1: INTEGER 10
- 114 02 1: INTEGER 1
- : }
- : }
- : }
- */
- boolean critical = false;
- int version = 1;
- String streetAddress = "401E Middlefield Rd.,MV,CA94041";
- String telephoneNumber = "650-111-1111";
- String rfc822Name = "admin@netscape.com";
- String ID = "ps-capitol";
- String hostName = "capitol";
- int portNumber = 80;
- int maxUsers = 10;
- int serviceLevel = 1;
-
- PresenceServerExtension ext = new PresenceServerExtension(
- critical,
- version, streetAddress, telephoneNumber,
- rfc822Name, ID, hostName, portNumber,
- maxUsers, serviceLevel);
-
- // encode
-
- ByteArrayOutputStream dos = new ByteArrayOutputStream();
- ext.encode(dos);
- FileOutputStream fos = new FileOutputStream("pse.der");
- fos.write(dos.toByteArray());
- fos.close();
-
- Extension ext1 = new Extension(new DerValue(dos.toByteArray()));
- PresenceServerExtension ext2 = new PresenceServerExtension(
- new Boolean(false), ext1.getExtensionValue());
+ public static void main(String args[]) throws Exception {
+ /*
+ * 0 30 115: SEQUENCE { 2 06 9: OBJECT IDENTIFIER '2 16 840 1 113730 1
+ * 100' 13 04 102: OCTET STRING, encapsulates { 15 30 100: SEQUENCE { 17
+ * 02 1: INTEGER 0 20 04 31: OCTET STRING : 34 30 31 45 20 4D 69 64 64
+ * 6C 65 66 69 65 6C 64 : 20 52 64 2E 2C 4D 56 2C 43 41 39 34 30 34 31
+ * 53 04 12: OCTET STRING : 36 35 30 2D 31 31 31 2D 31 31 31 31 67 04
+ * 18: OCTET STRING : 61 64 6D 69 6E 40 6E 65 74 73 63 61 70 65 2E 63 :
+ * 6F 6D 87 04 10: OCTET STRING : 70 73 2D 63 61 70 69 74 6F 6C 99 04 7:
+ * OCTET STRING : 63 61 70 69 74 6F 6C 108 02 1: INTEGER 80 111 02 1:
+ * INTEGER 10 114 02 1: INTEGER 1 : } : } : }
+ */
+ boolean critical = false;
+ int version = 1;
+ String streetAddress = "401E Middlefield Rd.,MV,CA94041";
+ String telephoneNumber = "650-111-1111";
+ String rfc822Name = "admin@netscape.com";
+ String ID = "ps-capitol";
+ String hostName = "capitol";
+ int portNumber = 80;
+ int maxUsers = 10;
+ int serviceLevel = 1;
+
+ PresenceServerExtension ext = new PresenceServerExtension(
+ critical,
+ version, streetAddress, telephoneNumber,
+ rfc822Name, ID, hostName, portNumber,
+ maxUsers, serviceLevel);
+
+ // encode
+
+ ByteArrayOutputStream dos = new ByteArrayOutputStream();
+ ext.encode(dos);
+ FileOutputStream fos = new FileOutputStream("pse.der");
+ fos.write(dos.toByteArray());
+ fos.close();
+
+ Extension ext1 = new Extension(new DerValue(dos.toByteArray()));
+ PresenceServerExtension ext2 = new PresenceServerExtension(
+ new Boolean(false), ext1.getExtensionValue());
}
}
diff --git a/pki/base/util/src/netscape/security/extensions/SubjectInfoAccessExtension.java b/pki/base/util/src/netscape/security/extensions/SubjectInfoAccessExtension.java
index 36be1fff..645ea2ae 100644
--- a/pki/base/util/src/netscape/security/extensions/SubjectInfoAccessExtension.java
+++ b/pki/base/util/src/netscape/security/extensions/SubjectInfoAccessExtension.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package netscape.security.extensions;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -37,11 +36,10 @@ import netscape.security.x509.Extension;
import netscape.security.x509.GeneralName;
import netscape.security.x509.URIName;
-
/**
- * This represents the subject information access extension
- * as defined in RFC3280.
- *
+ * This represents the subject information access extension as defined in
+ * RFC3280.
+ *
* @author thomask
* @version $Revision$, $Date$
*/
@@ -49,12 +47,12 @@ public class SubjectInfoAccessExtension extends Extension implements CertAttrSet
private static final long serialVersionUID = 7237321566602583325L;
public static final int OID_OCSP[] = { 1, 3, 6, 1, 5, 5, 7, 48, 1 };
- public static final ObjectIdentifier METHOD_OCSP = new
- ObjectIdentifier(OID_OCSP);
+ public static final ObjectIdentifier METHOD_OCSP = new
+ ObjectIdentifier(OID_OCSP);
public static final int OID_CA_ISSUERS[] = { 1, 3, 6, 1, 5, 5, 7, 48, 2 };
- public static final ObjectIdentifier METHOD_CA_ISSUERS = new
- ObjectIdentifier(OID_CA_ISSUERS);
+ public static final ObjectIdentifier METHOD_CA_ISSUERS = new
+ ObjectIdentifier(OID_CA_ISSUERS);
public static final int OID[] = { 1, 3, 6, 1, 5, 5, 7, 1, 11 };
public static final ObjectIdentifier ID = new ObjectIdentifier(OID);
@@ -63,7 +61,7 @@ public class SubjectInfoAccessExtension extends Extension implements CertAttrSet
/**
* Create the extension from the passed DER encoded value of the same.
- *
+ *
* @param critical true if the extension is to be treated as critical.
* @param value Array of DER encoded bytes of the actual value.
* @exception IOException on error.
@@ -74,8 +72,8 @@ public class SubjectInfoAccessExtension extends Extension implements CertAttrSet
this.extensionValue = null; // build this when encodeThis() is called
}
- public SubjectInfoAccessExtension(Boolean critical, Object value)
- throws IOException {
+ public SubjectInfoAccessExtension(Boolean critical, Object value)
+ throws IOException {
this.extensionId = ID;
this.critical = critical.booleanValue();
this.extensionValue = (byte[]) ((byte[]) value).clone();
@@ -120,14 +118,13 @@ public class SubjectInfoAccessExtension extends Extension implements CertAttrSet
return null;
}
-
/**
* Adds Access Description.
*/
public void addAccessDescription(
- ObjectIdentifier method,
- GeneralName gn) {
- clearValue();
+ ObjectIdentifier method,
+ GeneralName gn) {
+ clearValue();
mDesc.addElement(new AccessDescription(method, gn));
}
@@ -157,7 +154,7 @@ public class SubjectInfoAccessExtension extends Extension implements CertAttrSet
}
}
- private void encodeThis() throws IOException {
+ private void encodeThis() throws IOException {
DerOutputStream seq = new DerOutputStream();
DerOutputStream tmp = new DerOutputStream();
@@ -172,10 +169,10 @@ public class SubjectInfoAccessExtension extends Extension implements CertAttrSet
seq.write(DerValue.tag_Sequence, tmp);
this.extensionValue = seq.toByteArray();
}
-
+
/**
* Write the extension to the DerOutputStream.
- *
+ *
* @param out the DerOutputStream to write the extension to.
* @exception IOException on encoding errors.
*/
@@ -214,7 +211,7 @@ public class SubjectInfoAccessExtension extends Extension implements CertAttrSet
GeneralName caIssuersName = new GeneralName(new
URIName("http://ocsp.netscape.com"));
- aia.addAccessDescription(METHOD_CA_ISSUERS, caIssuersName);
+ aia.addAccessDescription(METHOD_CA_ISSUERS, caIssuersName);
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
@@ -236,7 +233,7 @@ public class SubjectInfoAccessExtension extends Extension implements CertAttrSet
bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
AuthInfoAccessExtension clone = (AuthInfoAccessExtension)
- ois.readObject();
+ ois.readObject();
System.out.println(clone);
} catch (Exception e) {
diff --git a/pki/base/util/src/netscape/security/pkcs/ContentInfo.java b/pki/base/util/src/netscape/security/pkcs/ContentInfo.java
index f09f4b62..dd1c6f76 100644
--- a/pki/base/util/src/netscape/security/pkcs/ContentInfo.java
+++ b/pki/base/util/src/netscape/security/pkcs/ContentInfo.java
@@ -26,130 +26,130 @@ import netscape.security.util.ObjectIdentifier;
/**
* A ContentInfo type, as defined in PKCS#7.
- *
+ *
* @version 1.12
- * @author Benjamin Renaud
+ * @author Benjamin Renaud
*/
public class ContentInfo {
// pkcs7 pre-defined content types
- private static int[] pkcs7 = {1, 2, 840, 113549, 1, 7};
- private static int[] data = {1, 2, 840, 113549, 1, 7, 1};
- private static int[] sdata = {1, 2, 840, 113549, 1, 7, 2};
- private static int[] edata = {1, 2, 840, 113549, 1, 7, 3};
- private static int[] sedata = {1, 2, 840, 113549, 1, 7, 4};
- private static int[] ddata = {1, 2, 840, 113549, 1, 7, 5};
- private static int[] crdata = {1, 2, 840, 113549, 1, 7, 6};
-
- public static final ObjectIdentifier PKCS7_OID =
- new ObjectIdentifier(pkcs7);
-
- public static final ObjectIdentifier DATA_OID =
- new ObjectIdentifier(data);
-
- public static final ObjectIdentifier SIGNED_DATA_OID =
- new ObjectIdentifier(sdata);
+ private static int[] pkcs7 = { 1, 2, 840, 113549, 1, 7 };
+ private static int[] data = { 1, 2, 840, 113549, 1, 7, 1 };
+ private static int[] sdata = { 1, 2, 840, 113549, 1, 7, 2 };
+ private static int[] edata = { 1, 2, 840, 113549, 1, 7, 3 };
+ private static int[] sedata = { 1, 2, 840, 113549, 1, 7, 4 };
+ private static int[] ddata = { 1, 2, 840, 113549, 1, 7, 5 };
+ private static int[] crdata = { 1, 2, 840, 113549, 1, 7, 6 };
+
+ public static final ObjectIdentifier PKCS7_OID =
+ new ObjectIdentifier(pkcs7);
+
+ public static final ObjectIdentifier DATA_OID =
+ new ObjectIdentifier(data);
+
+ public static final ObjectIdentifier SIGNED_DATA_OID =
+ new ObjectIdentifier(sdata);
public static final ObjectIdentifier ENVELOPED_DATA_OID =
- new ObjectIdentifier(edata);
+ new ObjectIdentifier(edata);
public static final ObjectIdentifier SIGNED_AND_ENVELOPED_DATA_OID =
- new ObjectIdentifier(sedata);
+ new ObjectIdentifier(sedata);
- public static final ObjectIdentifier DIGESTED_DATA_OID =
- new ObjectIdentifier(ddata);
+ public static final ObjectIdentifier DIGESTED_DATA_OID =
+ new ObjectIdentifier(ddata);
- public static final ObjectIdentifier ENCRYPTED_DATA_OID =
- new ObjectIdentifier(crdata);
+ public static final ObjectIdentifier ENCRYPTED_DATA_OID =
+ new ObjectIdentifier(crdata);
ObjectIdentifier contentType;
DerValue content; // OPTIONAL
public ContentInfo(ObjectIdentifier contentType, DerValue content) {
- this.contentType = contentType;
- this.content = content;
+ this.contentType = contentType;
+ this.content = content;
}
/**
* Make a contentInfo of type data.
*/
public ContentInfo(byte[] bytes) {
- DerValue octetString = new DerValue(DerValue.tag_OctetString, bytes);
- this.contentType = DATA_OID;
- this.content = octetString;
+ DerValue octetString = new DerValue(DerValue.tag_OctetString, bytes);
+ this.contentType = DATA_OID;
+ this.content = octetString;
}
- public ContentInfo(DerInputStream derin)
- throws IOException, ParsingException {
+ public ContentInfo(DerInputStream derin)
+ throws IOException, ParsingException {
DerInputStream disType;
- DerInputStream disTaggedContent;
- DerValue type;
- DerValue taggedContent;
- DerValue[] typeAndContent;
- DerValue[] contents;
-
- typeAndContent = derin.getSequence(2);
-
- // Parse the content type
- type = typeAndContent[0];
- disType = new DerInputStream(type.toByteArray());
- contentType = disType.getOID();
-
- // Parse the content (OPTIONAL field).
- // Skip the [0] EXPLICIT tag by pretending that the content is the one
- // and only element in an implicitly tagged set
- if (typeAndContent.length > 1) { // content is OPTIONAL
- taggedContent = typeAndContent[1];
- disTaggedContent = new DerInputStream(taggedContent.toByteArray());
- contents = disTaggedContent.getSet(1, true);
- content = contents[0];
- }
+ DerInputStream disTaggedContent;
+ DerValue type;
+ DerValue taggedContent;
+ DerValue[] typeAndContent;
+ DerValue[] contents;
+
+ typeAndContent = derin.getSequence(2);
+
+ // Parse the content type
+ type = typeAndContent[0];
+ disType = new DerInputStream(type.toByteArray());
+ contentType = disType.getOID();
+
+ // Parse the content (OPTIONAL field).
+ // Skip the [0] EXPLICIT tag by pretending that the content is the one
+ // and only element in an implicitly tagged set
+ if (typeAndContent.length > 1) { // content is OPTIONAL
+ taggedContent = typeAndContent[1];
+ disTaggedContent = new DerInputStream(taggedContent.toByteArray());
+ contents = disTaggedContent.getSet(1, true);
+ content = contents[0];
+ }
}
public DerValue getContent() {
- return content;
+ return content;
}
public byte[] getData() throws IOException {
- if (contentType.equals(DATA_OID)) {
- return content.getOctetString();
- }
- throw new IOException("content type is not DATA: " + contentType);
+ if (contentType.equals(DATA_OID)) {
+ return content.getOctetString();
+ }
+ throw new IOException("content type is not DATA: " + contentType);
}
public void encode(DerOutputStream out) throws IOException {
- DerOutputStream contentDerCode;
- DerOutputStream seq;
- DerValue taggedContent;
+ DerOutputStream contentDerCode;
+ DerOutputStream seq;
+ DerValue taggedContent;
- contentDerCode = new DerOutputStream();
- content.encode(contentDerCode);
- // Add the [0] EXPLICIT tag in front of the content encoding
- taggedContent = new DerValue((byte)0xA0,
- contentDerCode.toByteArray());
+ contentDerCode = new DerOutputStream();
+ content.encode(contentDerCode);
+ // Add the [0] EXPLICIT tag in front of the content encoding
+ taggedContent = new DerValue((byte) 0xA0,
+ contentDerCode.toByteArray());
- seq = new DerOutputStream();
- seq.putOID(contentType);
- seq.putDerValue(taggedContent);
+ seq = new DerOutputStream();
+ seq.putOID(contentType);
+ seq.putDerValue(taggedContent);
- out.write(DerValue.tag_Sequence, seq);
+ out.write(DerValue.tag_Sequence, seq);
}
/**
- * Returns a byte array representation of the data held in
- * the content field.
+ * Returns a byte array representation of the data held in the content
+ * field.
*/
public byte[] getContentBytes() throws IOException {
- DerInputStream dis = new DerInputStream(content.toByteArray());
- return dis.getOctetString();
+ DerInputStream dis = new DerInputStream(content.toByteArray());
+ return dis.getOctetString();
}
-
+
public String toString() {
- String out = "";
-
- out += "Content Info Sequence\n\tContent type: " + contentType + "\n";
- out += "\tContent: " + content;
- return out;
+ String out = "";
+
+ out += "Content Info Sequence\n\tContent type: " + contentType + "\n";
+ out += "\tContent: " + content;
+ return out;
}
}
diff --git a/pki/base/util/src/netscape/security/pkcs/EncodingException.java b/pki/base/util/src/netscape/security/pkcs/EncodingException.java
index 6ccd1d40..cb495e99 100644
--- a/pki/base/util/src/netscape/security/pkcs/EncodingException.java
+++ b/pki/base/util/src/netscape/security/pkcs/EncodingException.java
@@ -24,10 +24,10 @@ public class EncodingException extends Exception {
private static final long serialVersionUID = -6126764125859196917L;
public EncodingException() {
- super();
+ super();
}
public EncodingException(String s) {
- super(s);
+ super(s);
}
}
diff --git a/pki/base/util/src/netscape/security/pkcs/PKCS10.java b/pki/base/util/src/netscape/security/pkcs/PKCS10.java
index dc28c7e9..f36d1c53 100644
--- a/pki/base/util/src/netscape/security/pkcs/PKCS10.java
+++ b/pki/base/util/src/netscape/security/pkcs/PKCS10.java
@@ -37,22 +37,23 @@ import netscape.security.x509.X509Key;
/**
* PKCS #10 certificate requests are created and sent to Certificate
- * Authorities, which then create X.509 certificates and return them to
- * the entity which created the certificate request. These cert requests
- * basically consist of the subject's X.500 name and public key, signed
- * using the corresponding private key.
- *
+ * Authorities, which then create X.509 certificates and return them to the
+ * entity which created the certificate request. These cert requests basically
+ * consist of the subject's X.500 name and public key, signed using the
+ * corresponding private key.
+ *
* The ASN.1 syntax for a Certification Request is:
+ *
* <pre>
* CertificationRequest ::= SEQUENCE {
* certificationRequestInfo CertificationRequestInfo,
* signatureAlgorithm SignatureAlgorithmIdentifier,
* signature Signature
* }
- *
+ *
* SignatureAlgorithmIdentifier ::= AlgorithmIdentifier
* Signature ::= BIT STRING
- *
+ *
* CertificationRequestInfo ::= SEQUENCE {
* version Version,
* subject Name,
@@ -61,298 +62,282 @@ import netscape.security.x509.X509Key;
* }
* Attributes ::= SET OF Attribute
* </pre>
- *
+ *
* @author David Brownell
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.28
*/
-public class PKCS10
-{
+public class PKCS10 {
/**
- * Constructs an unsigned PKCS #10 certificate request. Before this
- * request may be used, it must be encoded and signed. Then it
- * must be retrieved in some conventional format (e.g. string).
+ * Constructs an unsigned PKCS #10 certificate request. Before this request
+ * may be used, it must be encoded and signed. Then it must be retrieved in
+ * some conventional format (e.g. string).
*
- * @param publicKey the public key that should be placed
- * into the certificate generated by the CA.
+ * @param publicKey the public key that should be placed into the
+ * certificate generated by the CA.
*/
- public PKCS10 (X509Key publicKey)
- {
- subjectPublicKeyInfo = publicKey;
- attributeSet = new PKCS10Attributes();
+ public PKCS10(X509Key publicKey) {
+ subjectPublicKeyInfo = publicKey;
+ attributeSet = new PKCS10Attributes();
}
-
/**
- * Constructs an unsigned PKCS #10 certificate request. Before this
- * request may be used, it must be encoded and signed. Then it
- * must be retrieved in some conventional format (e.g. string).
+ * Constructs an unsigned PKCS #10 certificate request. Before this request
+ * may be used, it must be encoded and signed. Then it must be retrieved in
+ * some conventional format (e.g. string).
*
- * @param publicKey the public key that should be placed
- * into the certificate generated by the CA.
- * @param attributes additonal set of PKCS10 attributes requested
- * for in the certificate.
+ * @param publicKey the public key that should be placed into the
+ * certificate generated by the CA.
+ * @param attributes additonal set of PKCS10 attributes requested for in the
+ * certificate.
*/
- public PKCS10 (X509Key publicKey, PKCS10Attributes attributes)
- {
- subjectPublicKeyInfo = publicKey;
- if (attributes != null)
- attributeSet = attributes;
- else
- attributeSet = new PKCS10Attributes();
+ public PKCS10(X509Key publicKey, PKCS10Attributes attributes) {
+ subjectPublicKeyInfo = publicKey;
+ if (attributes != null)
+ attributeSet = attributes;
+ else
+ attributeSet = new PKCS10Attributes();
}
-
/**
- * Parses an encoded, signed PKCS #10 certificate request, verifying
- * the request's signature as it does so. This constructor would
- * typically be used by a Certificate Authority, from which a new
- * certificate would then be constructed.
- *
+ * Parses an encoded, signed PKCS #10 certificate request, verifying the
+ * request's signature as it does so. This constructor would typically be
+ * used by a Certificate Authority, from which a new certificate would then
+ * be constructed.
+ *
* @param data the DER-encoded PKCS #10 request.
* @param sigver boolean specifies signature verification enabled or not
* @exception IOException for low level errors reading the data
* @exception SignatureException when the signature is invalid
- * @exception NoSuchAlgorithmException when the signature
- * algorithm is not supported in this environment
+ * @exception NoSuchAlgorithmException when the signature algorithm is not
+ * supported in this environment
*/
- public PKCS10 (byte data [], boolean sigver)
- throws IOException, SignatureException, NoSuchAlgorithmException,java.security.NoSuchProviderException
- {
- DerInputStream in;
- DerValue seq [];
- AlgorithmId id;
- byte sigData [];
- Signature sig;
-
- certificateRequest = data;
-
- //
- // Outer sequence: request, signature algorithm, signature.
- // Parse, and prepare to verify later.
- //
- in = new DerInputStream (data);
- seq = in.getSequence (3);
-
- if (seq.length != 3)
- throw new IllegalArgumentException ("not a PKCS #10 request");
-
- data = seq [0].toByteArray (); // reusing this variable
- certRequestInfo = seq[0].toByteArray(); // make a copy
- id = AlgorithmId.parse (seq [1]);
- sigData = seq [2].getBitString ();
-
- //
- // Inner sequence: version, name, key, attributes
- //
- BigInt serial;
- DerValue val;
-
- serial = seq [0].data.getInteger ();
-/*
- if (serial.toInt () != 0)
- throw new IllegalArgumentException ("not PKCS #10 v1");
-*/
-
- subject = new X500Name (seq [0].data);
-
-
- byte val1[] = seq [0].data.getDerValue ().toByteArray();
- subjectPublicKeyInfo = X509Key.parse (new DerValue(val1));
- PublicKey publicKey = X509Key.parsePublicKey (new DerValue(val1));
-
- String keystr = subjectPublicKeyInfo.toString();
-
- // Cope with a somewhat common illegal PKCS #10 format
- if (seq [0].data.available () != 0)
- attributeSet = new PKCS10Attributes(seq [0].data);
- else
- attributeSet = new PKCS10Attributes();
-
- //
- // OK, we parsed it all ... validate the signature using the
- // key and signature algorithm we found.
- // temporary commented out
- try {
- String idName = id.getName ();
- if(idName.equals("MD5withRSA"))
- idName = "MD5/RSA";
- else if(idName.equals("MD2withRSA"))
- idName = "MD2/RSA";
- else if(idName.equals("SHA1withRSA"))
- idName = "SHA1/RSA";
- else if(idName.equals("SHA1withDSA"))
- idName = "SHA1/DSA";
- else if(idName.equals("SHA1withEC"))
- idName = "SHA1/EC";
- else if(idName.equals("SHA256withEC"))
- idName = "SHA256/EC";
- else if(idName.equals("SHA384withEC"))
- idName = "SHA384/EC";
- else if(idName.equals("SHA512withEC"))
- idName = "SHA512/EC";
-
- if (sigver) {
- sig = Signature.getInstance(idName,"Mozilla-JSS");
-
- sig.initVerify (publicKey);
- sig.update (data);
- if (!sig.verify (sigData))
- throw new SignatureException ("Invalid PKCS #10 signature");
+ public PKCS10(byte data[], boolean sigver)
+ throws IOException, SignatureException, NoSuchAlgorithmException, java.security.NoSuchProviderException {
+ DerInputStream in;
+ DerValue seq[];
+ AlgorithmId id;
+ byte sigData[];
+ Signature sig;
+
+ certificateRequest = data;
+
+ //
+ // Outer sequence: request, signature algorithm, signature.
+ // Parse, and prepare to verify later.
+ //
+ in = new DerInputStream(data);
+ seq = in.getSequence(3);
+
+ if (seq.length != 3)
+ throw new IllegalArgumentException("not a PKCS #10 request");
+
+ data = seq[0].toByteArray(); // reusing this variable
+ certRequestInfo = seq[0].toByteArray(); // make a copy
+ id = AlgorithmId.parse(seq[1]);
+ sigData = seq[2].getBitString();
+
+ //
+ // Inner sequence: version, name, key, attributes
+ //
+ BigInt serial;
+ DerValue val;
+
+ serial = seq[0].data.getInteger();
+ /*
+ * if (serial.toInt () != 0) throw new IllegalArgumentException
+ * ("not PKCS #10 v1");
+ */
+
+ subject = new X500Name(seq[0].data);
+
+ byte val1[] = seq[0].data.getDerValue().toByteArray();
+ subjectPublicKeyInfo = X509Key.parse(new DerValue(val1));
+ PublicKey publicKey = X509Key.parsePublicKey(new DerValue(val1));
+
+ String keystr = subjectPublicKeyInfo.toString();
+
+ // Cope with a somewhat common illegal PKCS #10 format
+ if (seq[0].data.available() != 0)
+ attributeSet = new PKCS10Attributes(seq[0].data);
+ else
+ attributeSet = new PKCS10Attributes();
+
+ //
+ // OK, we parsed it all ... validate the signature using the
+ // key and signature algorithm we found.
+ // temporary commented out
+ try {
+ String idName = id.getName();
+ if (idName.equals("MD5withRSA"))
+ idName = "MD5/RSA";
+ else if (idName.equals("MD2withRSA"))
+ idName = "MD2/RSA";
+ else if (idName.equals("SHA1withRSA"))
+ idName = "SHA1/RSA";
+ else if (idName.equals("SHA1withDSA"))
+ idName = "SHA1/DSA";
+ else if (idName.equals("SHA1withEC"))
+ idName = "SHA1/EC";
+ else if (idName.equals("SHA256withEC"))
+ idName = "SHA256/EC";
+ else if (idName.equals("SHA384withEC"))
+ idName = "SHA384/EC";
+ else if (idName.equals("SHA512withEC"))
+ idName = "SHA512/EC";
+
+ if (sigver) {
+ sig = Signature.getInstance(idName, "Mozilla-JSS");
+
+ sig.initVerify(publicKey);
+ sig.update(data);
+ if (!sig.verify(sigData))
+ throw new SignatureException("Invalid PKCS #10 signature");
+ }
+ } catch (InvalidKeyException e) {
+ throw new SignatureException("invalid key");
}
- } catch (InvalidKeyException e) {
- throw new SignatureException ("invalid key");
- }
}
- public PKCS10 (byte data [])
- throws IOException, SignatureException, NoSuchAlgorithmException,java.security.NoSuchProviderException
- {
+ public PKCS10(byte data[])
+ throws IOException, SignatureException, NoSuchAlgorithmException, java.security.NoSuchProviderException {
this(data, true);
}
/**
- * Create the signed certificate request. This will later be
- * retrieved in either string or binary format.
- *
- * @param requester identifies the signer (by X.500 name)
- * and provides the private key used to sign.
+ * Create the signed certificate request. This will later be retrieved in
+ * either string or binary format.
+ *
+ * @param requester identifies the signer (by X.500 name) and provides the
+ * private key used to sign.
* @exception IOException on errors.
* @exception CertificateException on certificate handling errors.
* @exception SignatureException on signature handling errors.
*/
- public void encodeAndSign (X500Signer requester)
- throws CertificateException, IOException, SignatureException
- {
- DerOutputStream out, scratch;
- byte certificateRequestInfo [];
- byte sig [];
-
- if (certificateRequest != null)
- throw new SignatureException ("request is already signed");
-
- subject = requester.getSigner ();
-
- /*
- * Encode cert request info, wrap in a sequence for signing
- */
- scratch = new DerOutputStream ();
- scratch.putInteger (new BigInt (0)); // version zero
- subject.encode (scratch); // X.500 name
- subjectPublicKeyInfo.encode (scratch); // public key
- attributeSet.encode (scratch);
-
- out = new DerOutputStream ();
- out.write (DerValue.tag_Sequence, scratch); // wrap it!
- certificateRequestInfo = out.toByteArray ();
- scratch = out;
-
- /*
- * Sign it ...
- */
- requester.update (certificateRequestInfo, 0,
- certificateRequestInfo.length);
- sig = requester.sign ();
-
- /*
- * Build guts of SIGNED macro
- */
- requester.getAlgorithmId ().encode (scratch); // sig algorithm
- scratch.putBitString (sig); // sig
-
- /*
- * Wrap those guts in a sequence
- */
- out = new DerOutputStream ();
- out.write (DerValue.tag_Sequence, scratch);
- certificateRequest = out.toByteArray ();
+ public void encodeAndSign(X500Signer requester)
+ throws CertificateException, IOException, SignatureException {
+ DerOutputStream out, scratch;
+ byte certificateRequestInfo[];
+ byte sig[];
+
+ if (certificateRequest != null)
+ throw new SignatureException("request is already signed");
+
+ subject = requester.getSigner();
+
+ /*
+ * Encode cert request info, wrap in a sequence for signing
+ */
+ scratch = new DerOutputStream();
+ scratch.putInteger(new BigInt(0)); // version zero
+ subject.encode(scratch); // X.500 name
+ subjectPublicKeyInfo.encode(scratch); // public key
+ attributeSet.encode(scratch);
+
+ out = new DerOutputStream();
+ out.write(DerValue.tag_Sequence, scratch); // wrap it!
+ certificateRequestInfo = out.toByteArray();
+ scratch = out;
+
+ /*
+ * Sign it ...
+ */
+ requester.update(certificateRequestInfo, 0,
+ certificateRequestInfo.length);
+ sig = requester.sign();
+
+ /*
+ * Build guts of SIGNED macro
+ */
+ requester.getAlgorithmId().encode(scratch); // sig algorithm
+ scratch.putBitString(sig); // sig
+
+ /*
+ * Wrap those guts in a sequence
+ */
+ out = new DerOutputStream();
+ out.write(DerValue.tag_Sequence, scratch);
+ certificateRequest = out.toByteArray();
}
-
/**
* Returns the subject's name.
*/
- public X500Name getSubjectName ()
- { return subject; }
-
+ public X500Name getSubjectName() {
+ return subject;
+ }
/**
* Returns the subject's public key.
*/
- public X509Key getSubjectPublicKeyInfo ()
- { return subjectPublicKeyInfo; }
-
+ public X509Key getSubjectPublicKeyInfo() {
+ return subjectPublicKeyInfo;
+ }
/**
* Returns the additional attributes requested.
*/
- public PKCS10Attributes getAttributes ()
- { return attributeSet; }
+ public PKCS10Attributes getAttributes() {
+ return attributeSet;
+ }
/**
- * Returns the encoded and signed certificate request as a
- * DER-encoded byte array.
- *
- * @return the certificate request, or null if encodeAndSign()
- * has not yet been called.
+ * Returns the encoded and signed certificate request as a DER-encoded byte
+ * array.
+ *
+ * @return the certificate request, or null if encodeAndSign() has not yet
+ * been called.
*/
- public byte [] toByteArray ()
- {
- return certificateRequest;
+ public byte[] toByteArray() {
+ return certificateRequest;
}
-
/**
* Prints an E-Mailable version of the certificate request on the print
- * stream passed. The format is a common base64 encoded one, supported
- * by most Certificate Authorities because Netscape web servers have
- * used this for some time. Some certificate authorities expect some
- * more information, in particular contact information for the web
- * server administrator.
- *
- * @param out the print stream where the certificate request
- * will be printed.
+ * stream passed. The format is a common base64 encoded one, supported by
+ * most Certificate Authorities because Netscape web servers have used this
+ * for some time. Some certificate authorities expect some more information,
+ * in particular contact information for the web server administrator.
+ *
+ * @param out the print stream where the certificate request will be
+ * printed.
* @exception IOException when an output operation failed
- * @exception SignatureException when the certificate request was
- * not yet signed.
+ * @exception SignatureException when the certificate request was not yet
+ * signed.
*/
- public void print (PrintStream out)
- throws IOException, SignatureException
- {
- if (certificateRequest == null)
- throw new SignatureException ("Cert request was not signed");
-
-
- out.println ("-----BEGIN NEW CERTIFICATE REQUEST-----");
- out.println (com.netscape.osutil.OSUtil.BtoA(certificateRequest));
- out.println ("-----END NEW CERTIFICATE REQUEST-----");
+ public void print(PrintStream out)
+ throws IOException, SignatureException {
+ if (certificateRequest == null)
+ throw new SignatureException("Cert request was not signed");
+
+ out.println("-----BEGIN NEW CERTIFICATE REQUEST-----");
+ out.println(com.netscape.osutil.OSUtil.BtoA(certificateRequest));
+ out.println("-----END NEW CERTIFICATE REQUEST-----");
}
/**
* Provides a short description of this request.
*/
- public String toString ()
- {
- return "[PKCS #10 certificate request:\n"
- + subjectPublicKeyInfo.toString()
- + " subject: <" + subject + ">" + "\n"
- + " attributes: " + attributeSet.toString()
- + "\n]";
+ public String toString() {
+ return "[PKCS #10 certificate request:\n"
+ + subjectPublicKeyInfo.toString()
+ + " subject: <" + subject + ">" + "\n"
+ + " attributes: " + attributeSet.toString()
+ + "\n]";
}
/**
* Retrieve the PKCS10 CertificateRequestInfo as a byte array
*/
- public byte[] getCertRequestInfo()
- {
- return certRequestInfo;
+ public byte[] getCertRequestInfo() {
+ return certRequestInfo;
}
- private X500Name subject;
- private X509Key subjectPublicKeyInfo;
- private PKCS10Attributes attributeSet;
+ private X500Name subject;
+ private X509Key subjectPublicKeyInfo;
+ private PKCS10Attributes attributeSet;
- private byte certificateRequest []; // signed
- private byte certRequestInfo []; // inner content signed
+ private byte certificateRequest[]; // signed
+ private byte certRequestInfo[]; // inner content signed
}
diff --git a/pki/base/util/src/netscape/security/pkcs/PKCS10Attribute.java b/pki/base/util/src/netscape/security/pkcs/PKCS10Attribute.java
index dd74ead9..830303ec 100644
--- a/pki/base/util/src/netscape/security/pkcs/PKCS10Attribute.java
+++ b/pki/base/util/src/netscape/security/pkcs/PKCS10Attribute.java
@@ -35,19 +35,21 @@ import netscape.security.x509.CertAttrSet;
import netscape.security.x509.Extensions;
import netscape.security.x509.OIDMap;
-
/**
* Represent a PKCS Attribute.
- *
- * <p>Attributes are addiitonal attributes which can be inserted in a PKCS
+ *
+ * <p>
+ * Attributes are addiitonal attributes which can be inserted in a PKCS
* certificate request. For example a "Driving License Certificate" could have
* the driving license number as a attribute.
- *
- * <p>Attributes are represented as a sequence of the attribute identifier
- * (Object Identifier) and a set of DER encoded attribute values. The current
+ *
+ * <p>
+ * Attributes are represented as a sequence of the attribute identifier (Object
+ * Identifier) and a set of DER encoded attribute values. The current
* implementation only supports one value per attribute.
- *
+ *
* ASN.1 definition of Attribute:
+ *
* <pre>
* Attribute :: SEQUENCE {
* type AttributeValue,
@@ -55,7 +57,7 @@ import netscape.security.x509.OIDMap;
* }
* AttributeValue ::= ANY
* </pre>
- *
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.13
@@ -65,11 +67,11 @@ public class PKCS10Attribute implements DerEncoder, Serializable {
*
*/
private static final long serialVersionUID = 2002480042340316170L;
- protected ObjectIdentifier attributeId = null;
- protected CertAttrSet attributeValue = null;
+ protected ObjectIdentifier attributeId = null;
+ protected CertAttrSet attributeValue = null;
/**
- * Default constructor. Used only by sub-classes.
+ * Default constructor. Used only by sub-classes.
*/
public PKCS10Attribute() {
}
@@ -79,65 +81,63 @@ public class PKCS10Attribute implements DerEncoder, Serializable {
*/
public PKCS10Attribute(DerValue derVal) throws IOException {
if (derVal.tag != DerValue.tag_Sequence) {
- throw new IOException("Sequence tag missing for PKCS10Attribute.");
- }
+ throw new IOException("Sequence tag missing for PKCS10Attribute.");
+ }
DerInputStream in = derVal.toDerInputStream();
// Object identifier
attributeId = in.getOID();
- // System.out.println("attribute ID in pkcs10 "+attributeId.toString());
-
- // Rest of the stuff is attribute value(s), wrapped in a SET.
- // For now, assume there is only one attribute value present.
- DerValue[] inAttrValues = in.getSet(1);
- int attrValueNum = inAttrValues.length;
- if (attrValueNum > 1) {
- throw new IOException("More than one value per attribute not supported");
- }
-
- // Read the first attribute value
- DerValue inAttrValue = inAttrValues[0];
-
- if (attributeId.equals(PKCS9Attribute.EXTENSION_REQUEST_OID)) {
- //pkcs9 extensionAttr
- try{
- // remove the tag
- //DerValue dv = inAttrValue.data.getDerValue();
- // hack. toDerInputStream only gives one extension.
- DerInputStream fi = new DerInputStream(inAttrValue.toByteArray());
- attributeValue = (CertAttrSet) new
- Extensions(fi);
- //CertificateExtensions(fi);
- return;
- } catch(Exception e) {
- throw new IOException(e.toString());
- }
- }
- byte[] val = inAttrValue.toByteArray();
+ // System.out.println("attribute ID in pkcs10 "+attributeId.toString());
+
+ // Rest of the stuff is attribute value(s), wrapped in a SET.
+ // For now, assume there is only one attribute value present.
+ DerValue[] inAttrValues = in.getSet(1);
+ int attrValueNum = inAttrValues.length;
+ if (attrValueNum > 1) {
+ throw new IOException("More than one value per attribute not supported");
+ }
+
+ // Read the first attribute value
+ DerValue inAttrValue = inAttrValues[0];
+
+ if (attributeId.equals(PKCS9Attribute.EXTENSION_REQUEST_OID)) {
+ // pkcs9 extensionAttr
+ try {
+ // remove the tag
+ // DerValue dv = inAttrValue.data.getDerValue();
+ // hack. toDerInputStream only gives one extension.
+ DerInputStream fi = new DerInputStream(inAttrValue.toByteArray());
+ attributeValue = (CertAttrSet) new
+ Extensions(fi);
+ // CertificateExtensions(fi);
+ return;
+ } catch (Exception e) {
+ throw new IOException(e.toString());
+ }
+ }
+ byte[] val = inAttrValue.toByteArray();
Class<?>[] params = { Object.class };
try {
- @SuppressWarnings("unchecked")
- Class<CertAttrSet> extClass = (Class<CertAttrSet>) OIDMap.getClass(attributeId);
- if (extClass != null) {
- Constructor<CertAttrSet> cons = (Constructor<CertAttrSet>) extClass.getConstructor(params);
- Object value = Array.newInstance(byte.class,val.length);
- for (int i = 0; i < val.length; i++) {
- Array.setByte(value,i,val[i]);
- }
- Object[] passed = new Object[] {value};
- attributeValue = cons.newInstance(passed);
- } else {
- // attribute classes are usable for PKCS10 attributes.
- // this is used where the attributes are not actual
- // implemented extensions.
- attributeValue = new ACertAttrSet(inAttrValue);
- }
- }
- catch (InvocationTargetException invk) {
- throw new IOException(invk.getTargetException().getMessage());
- }
- catch (Exception e) {
- throw new IOException(e.toString());
+ @SuppressWarnings("unchecked")
+ Class<CertAttrSet> extClass = (Class<CertAttrSet>) OIDMap.getClass(attributeId);
+ if (extClass != null) {
+ Constructor<CertAttrSet> cons = (Constructor<CertAttrSet>) extClass.getConstructor(params);
+ Object value = Array.newInstance(byte.class, val.length);
+ for (int i = 0; i < val.length; i++) {
+ Array.setByte(value, i, val[i]);
+ }
+ Object[] passed = new Object[] { value };
+ attributeValue = cons.newInstance(passed);
+ } else {
+ // attribute classes are usable for PKCS10 attributes.
+ // this is used where the attributes are not actual
+ // implemented extensions.
+ attributeValue = new ACertAttrSet(inAttrValue);
+ }
+ } catch (InvocationTargetException invk) {
+ throw new IOException(invk.getTargetException().getMessage());
+ } catch (Exception e) {
+ throw new IOException(e.toString());
}
}
@@ -155,8 +155,8 @@ public class PKCS10Attribute implements DerEncoder, Serializable {
}
/**
- * Constructs an attribute from another attribute. To be used for
- * creating decoded subclasses.
+ * Constructs an attribute from another attribute. To be used for creating
+ * decoded subclasses.
*
* @param attr the attribute to create from.
*/
@@ -167,52 +167,50 @@ public class PKCS10Attribute implements DerEncoder, Serializable {
/**
* Write the output to the DerOutputStream.
- *
+ *
* @param out the OutputStream to write the attribute to.
* @exception CertificateException on certificate encoding errors.
* @exception IOException on encoding errors.
*/
public void encode(OutputStream out)
- throws CertificateException, IOException {
+ throws CertificateException, IOException {
// Encode the attribute value
- DerOutputStream outAttrValue = new DerOutputStream();
- attributeValue.encode(outAttrValue);
+ DerOutputStream outAttrValue = new DerOutputStream();
+ attributeValue.encode(outAttrValue);
- // Wrap the encoded attribute value into a SET
- DerValue outAttrValueSet = new DerValue(DerValue.tag_Set,
- outAttrValue.toByteArray());
+ // Wrap the encoded attribute value into a SET
+ DerValue outAttrValueSet = new DerValue(DerValue.tag_Set,
+ outAttrValue.toByteArray());
- // Create the attribute
+ // Create the attribute
DerOutputStream outAttr = new DerOutputStream();
outAttr.putOID(attributeId);
- outAttr.putDerValue(outAttrValueSet);
+ outAttr.putDerValue(outAttrValueSet);
- // Wrap the OID and the set of attribute values into a SEQUENCE
+ // Wrap the OID and the set of attribute values into a SEQUENCE
DerOutputStream tmp = new DerOutputStream();
tmp.write(DerValue.tag_Sequence, outAttr);
- // write the results to out
- out.write(tmp.toByteArray());
+ // write the results to out
+ out.write(tmp.toByteArray());
}
/**
- * DER encode this object onto an output stream.
- * Implements the <code>DerEncoder</code> interface.
- *
- * @param out
- * the OutputStream on which to write the DER encoding.
- *
+ * DER encode this object onto an output stream. Implements the
+ * <code>DerEncoder</code> interface.
+ *
+ * @param out the OutputStream on which to write the DER encoding.
+ *
* @exception IOException on encoding errors.
*/
- public void derEncode (OutputStream out) throws IOException
- {
- try {
- encode(out);
- } catch (CertificateException ce) {
- IOException ioe = new IOException(ce.toString());
- ioe.fillInStackTrace();
- throw ioe;
- }
+ public void derEncode(OutputStream out) throws IOException {
+ try {
+ encode(out);
+ } catch (CertificateException ce) {
+ IOException ioe = new IOException(ce.toString());
+ ioe.fillInStackTrace();
+ throw ioe;
+ }
}
/**
@@ -234,11 +232,8 @@ public class PKCS10Attribute implements DerEncoder, Serializable {
*/
public String toString() {
String s = "AttributeId: " + attributeId.toString() + "\n";
- s += "AttributeValue: " + attributeValue.toString();
+ s += "AttributeValue: " + attributeValue.toString();
return (s);
}
}
-
-
-
diff --git a/pki/base/util/src/netscape/security/pkcs/PKCS10Attributes.java b/pki/base/util/src/netscape/security/pkcs/PKCS10Attributes.java
index 441d7da2..e118243a 100644
--- a/pki/base/util/src/netscape/security/pkcs/PKCS10Attributes.java
+++ b/pki/base/util/src/netscape/security/pkcs/PKCS10Attributes.java
@@ -30,7 +30,7 @@ import netscape.security.util.DerValue;
/**
* This class defines the PKCS10 attributes for the request.
- *
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.10
@@ -52,55 +52,54 @@ public class PKCS10Attributes extends Vector implements DerEncoder {
/**
* Create the object, decoding the values from the passed DER stream.
- *
+ *
* @param in the DerInputStream to read the attributes from.
* @exception IOException on decoding errors.
*/
public PKCS10Attributes(DerInputStream in)
- throws IOException {
+ throws IOException {
map = new Hashtable();
- DerValue [] attrs = in.getSet(5,true);
-
- if (attrs != null) {
- for (int i = 0; i < attrs.length; i++) {
- PKCS10Attribute attr = new PKCS10Attribute(attrs[i]);
- addElement(attr);
- map.put(attr.getAttributeValue().getName(),attr);
- }
- }
+ DerValue[] attrs = in.getSet(5, true);
+
+ if (attrs != null) {
+ for (int i = 0; i < attrs.length; i++) {
+ PKCS10Attribute attr = new PKCS10Attribute(attrs[i]);
+ addElement(attr);
+ map.put(attr.getAttributeValue().getName(), attr);
+ }
+ }
}
-
/**
* Encode the attributes in DER form to the stream.
- *
+ *
* @param out the OutputStream to marshal the contents to.
- *
+ *
* @exception IOException on encoding errors.
*/
public void encode(OutputStream out)
- throws IOException {
- derEncode(out);
- }
+ throws IOException {
+ derEncode(out);
+ }
/**
- * Encode the attributes in DER form to the stream.
- * Implements the <code>DerEncoder</code> interface.
- *
+ * Encode the attributes in DER form to the stream. Implements the
+ * <code>DerEncoder</code> interface.
+ *
* @param out the OutputStream to marshal the contents to.
* @exception IOException on encoding errors.
*/
public void derEncode(OutputStream out)
- throws IOException {
+ throws IOException {
- // first copy the elements into an array
- PKCS10Attribute[] attribs = new PKCS10Attribute[size()];
- copyInto(attribs);
+ // first copy the elements into an array
+ PKCS10Attribute[] attribs = new PKCS10Attribute[size()];
+ copyInto(attribs);
- DerOutputStream attrOut = new DerOutputStream();
- attrOut.putOrderedSetOf(DerValue.createTag(DerValue.TAG_CONTEXT,true,(byte)0),
- attribs);
+ DerOutputStream attrOut = new DerOutputStream();
+ attrOut.putOrderedSetOf(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0),
+ attribs);
out.write(attrOut.toByteArray());
}
@@ -109,7 +108,7 @@ public class PKCS10Attributes extends Vector implements DerEncoder {
* Set the attribute value.
*/
public void setAttribute(String name, Object obj) throws IOException {
- map.put(name,obj);
+ map.put(name, obj);
addElement(obj);
}
@@ -118,11 +117,10 @@ public class PKCS10Attributes extends Vector implements DerEncoder {
*/
public Object getAttribute(String name) throws IOException {
Object obj = map.get(name);
- /*
- if (obj == null) {
- throw new IOException("No attribute found with name " + name);
- }
- */
+ /*
+ * if (obj == null) { throw new
+ * IOException("No attribute found with name " + name); }
+ */
return (obj);
}
@@ -142,7 +140,7 @@ public class PKCS10Attributes extends Vector implements DerEncoder {
* Return an enumeration of names of attributes existing within this
* attribute.
*/
- public Enumeration getElements () {
+ public Enumeration getElements() {
return (map.elements());
}
}
diff --git a/pki/base/util/src/netscape/security/pkcs/PKCS7.java b/pki/base/util/src/netscape/security/pkcs/PKCS7.java
index c31e1245..db1869a7 100644
--- a/pki/base/util/src/netscape/security/pkcs/PKCS7.java
+++ b/pki/base/util/src/netscape/security/pkcs/PKCS7.java
@@ -38,14 +38,13 @@ import netscape.security.x509.X500Name;
import netscape.security.x509.X509CertImpl;
/**
- * PKCS7 as defined in RSA Laboratories PKCS7 Technical Note. Profile
- * Supports only <tt>SignedData</tt> ContentInfo
- * type, where to the type of data signed is plain Data.
- * For signedData, <tt>crls</tt>, <tt>attributes</tt> and
- * PKCS#6 Extended Certificates are not supported.
- *
+ * PKCS7 as defined in RSA Laboratories PKCS7 Technical Note. Profile Supports
+ * only <tt>SignedData</tt> ContentInfo type, where to the type of data signed
+ * is plain Data. For signedData, <tt>crls</tt>, <tt>attributes</tt> and PKCS#6
+ * Extended Certificates are not supported.
+ *
* @version 1.33 97/12/10
- * @author Benjamin Renaud
+ * @author Benjamin Renaud
*/
public class PKCS7 {
@@ -59,392 +58,390 @@ public class PKCS7 {
private SignerInfo[] signerInfos;
/**
- * Unmarshals a PKCS7 block from its encoded form, parsing the
- * encoded bytes from the InputStream.
- *
+ * Unmarshals a PKCS7 block from its encoded form, parsing the encoded bytes
+ * from the InputStream.
+ *
* @param in an input stream holding at least one PKCS7 block.
* @exception ParsingException on parsing errors.
* @exception IOException on other errors.
*/
public PKCS7(InputStream in) throws ParsingException, IOException {
- DataInputStream dis = new DataInputStream(in);
-
- int len = 0;
- byte[] newbuf = new byte[len];
- byte[] oldbuf = new byte[len];
- byte[] data = new byte[len];
-
- do {
- newbuf = new byte[dis.available()];
- len += dis.available();
- dis.readFully(newbuf);
- data = new byte[len];
-
- System.arraycopy(oldbuf, 0, data, 0, oldbuf.length);
- System.arraycopy(newbuf, 0, data, oldbuf.length, newbuf.length);
- oldbuf = new byte[len];
- System.arraycopy(data, 0, oldbuf, 0, data.length);
-
- } while (dis.available() > 0);
-
- parse(new DerInputStream(data));
+ DataInputStream dis = new DataInputStream(in);
+
+ int len = 0;
+ byte[] newbuf = new byte[len];
+ byte[] oldbuf = new byte[len];
+ byte[] data = new byte[len];
+
+ do {
+ newbuf = new byte[dis.available()];
+ len += dis.available();
+ dis.readFully(newbuf);
+ data = new byte[len];
+
+ System.arraycopy(oldbuf, 0, data, 0, oldbuf.length);
+ System.arraycopy(newbuf, 0, data, oldbuf.length, newbuf.length);
+ oldbuf = new byte[len];
+ System.arraycopy(data, 0, oldbuf, 0, data.length);
+
+ } while (dis.available() > 0);
+
+ parse(new DerInputStream(data));
}
-
+
/**
- * Unmarshals a PKCS7 block from its encoded form, parsing the
- * encoded bytes from the DerInputStream.
- *
+ * Unmarshals a PKCS7 block from its encoded form, parsing the encoded bytes
+ * from the DerInputStream.
+ *
* @param derin a DerInputStream holding at least one PKCS7 block.
* @exception ParsingException on parsing errors.
*/
public PKCS7(DerInputStream derin) throws ParsingException {
- parse(derin);
+ parse(derin);
}
/**
- * Unmarshals a PKCS7 block from its encoded form, parsing the
- * encoded bytes.
- *
+ * Unmarshals a PKCS7 block from its encoded form, parsing the encoded
+ * bytes.
+ *
* @param bytes the encoded bytes.
* @exception ParsingException on parsing errors.
*/
public PKCS7(byte[] bytes) throws ParsingException {
- DerInputStream derin = new DerInputStream(bytes);
- parse(derin);
+ DerInputStream derin = new DerInputStream(bytes);
+ parse(derin);
}
private void parse(DerInputStream derin) throws ParsingException {
- try {
- ContentInfo contentInfo = new ContentInfo(derin);
- contentType = contentInfo.contentType;
- if (contentType.equals(ContentInfo.SIGNED_DATA_OID)) {
- parseSignedData(contentInfo.getContent());
- } else {
- throw new ParsingException("content type " + contentType +
- " not supported.");
- }
- } catch (IOException e) {
- ParsingException pe =
- new ParsingException("IOException: " + e.getMessage());
- pe.fillInStackTrace();
- throw pe;
- }
+ try {
+ ContentInfo contentInfo = new ContentInfo(derin);
+ contentType = contentInfo.contentType;
+ if (contentType.equals(ContentInfo.SIGNED_DATA_OID)) {
+ parseSignedData(contentInfo.getContent());
+ } else {
+ throw new ParsingException("content type " + contentType +
+ " not supported.");
+ }
+ } catch (IOException e) {
+ ParsingException pe =
+ new ParsingException("IOException: " + e.getMessage());
+ pe.fillInStackTrace();
+ throw pe;
+ }
}
/**
- * Construct an initialized PKCS7 block.
- *
+ * Construct an initialized PKCS7 block.
+ *
* @param digestAlgorithmIds the message digest algorithm identifiers.
* @param contentInfo the content information.
* @param certificates an array of X.509 certificates.
* @param signerInfos an array of signer information.
*/
public PKCS7(AlgorithmId[] digestAlgorithmIds,
- ContentInfo contentInfo,
- X509Certificate[] certificates,
- SignerInfo[] signerInfos) {
-
- version = new BigInt(1);
- this.digestAlgorithmIds = digestAlgorithmIds;
- this.contentInfo = contentInfo;
- this.certificates = certificates;
- this.signerInfos = signerInfos;
+ ContentInfo contentInfo,
+ X509Certificate[] certificates,
+ SignerInfo[] signerInfos) {
+
+ version = new BigInt(1);
+ this.digestAlgorithmIds = digestAlgorithmIds;
+ this.contentInfo = contentInfo;
+ this.certificates = certificates;
+ this.signerInfos = signerInfos;
}
private void parseSignedData(DerValue val)
- throws ParsingException, IOException {
-
- DerInputStream dis = val.toDerInputStream();
-
- // Version
- version = dis.getInteger();
-
- // digestAlgorithmIds
- DerValue[] digestAlgorithmIdVals = dis.getSet(1);
- int len = digestAlgorithmIdVals.length;
- digestAlgorithmIds = new AlgorithmId[len];
- try {
- for (int i = 0; i < len; i++) {
- DerValue oid = digestAlgorithmIdVals[i];
- digestAlgorithmIds[i] = AlgorithmId.parse(oid);
- }
-
- } catch (IOException e) {
- ParsingException pe =
- new ParsingException("Error parsing digest AlgorithmId IDs: " +
- e.getMessage());
- pe.fillInStackTrace();
- throw pe;
- }
- // contentInfo
- contentInfo = new ContentInfo(dis);
-
- /*
- * check if certificates (implicit tag) are provided
- * (certificates are OPTIONAL)
- */
- if ((byte)(dis.peekByte()) == (byte)0xA0) {
- DerValue[] certificateVals = dis.getSet(2, true);
-
- len = certificateVals.length;
- certificates = new X509Certificate[len];
-
- for (int i = 0; i < len; i++) {
- try {
- X509Certificate cert = (X509Certificate) new
+ throws ParsingException, IOException {
+
+ DerInputStream dis = val.toDerInputStream();
+
+ // Version
+ version = dis.getInteger();
+
+ // digestAlgorithmIds
+ DerValue[] digestAlgorithmIdVals = dis.getSet(1);
+ int len = digestAlgorithmIdVals.length;
+ digestAlgorithmIds = new AlgorithmId[len];
+ try {
+ for (int i = 0; i < len; i++) {
+ DerValue oid = digestAlgorithmIdVals[i];
+ digestAlgorithmIds[i] = AlgorithmId.parse(oid);
+ }
+
+ } catch (IOException e) {
+ ParsingException pe =
+ new ParsingException("Error parsing digest AlgorithmId IDs: " +
+ e.getMessage());
+ pe.fillInStackTrace();
+ throw pe;
+ }
+ // contentInfo
+ contentInfo = new ContentInfo(dis);
+
+ /*
+ * check if certificates (implicit tag) are provided (certificates are
+ * OPTIONAL)
+ */
+ if ((byte) (dis.peekByte()) == (byte) 0xA0) {
+ DerValue[] certificateVals = dis.getSet(2, true);
+
+ len = certificateVals.length;
+ certificates = new X509Certificate[len];
+
+ for (int i = 0; i < len; i++) {
+ try {
+ X509Certificate cert = (X509Certificate) new
X509CertImpl(certificateVals[i]);
- certificates[i] = cert;
- } catch (CertificateException e) {
- ParsingException pe =
- new ParsingException("CertificateException: " +
- e.getMessage());
- pe.fillInStackTrace();
- throw pe;
- }
- }
- }
-
- // check if crls (implicit tag) are provided (crls are OPTIONAL)
- if ((byte)(dis.peekByte()) == (byte)0xA1) {
- dis.getSet(0, true);
- }
-
- // signerInfos
- DerValue[] signerInfoVals = dis.getSet(1);
-
- len = signerInfoVals.length;
- signerInfos = new SignerInfo[len];
-
- for (int i = 0; i < len; i++) {
- DerInputStream in = signerInfoVals[i].toDerInputStream();
- signerInfos[i] = new SignerInfo(in);
- }
+ certificates[i] = cert;
+ } catch (CertificateException e) {
+ ParsingException pe =
+ new ParsingException("CertificateException: " +
+ e.getMessage());
+ pe.fillInStackTrace();
+ throw pe;
+ }
+ }
+ }
+
+ // check if crls (implicit tag) are provided (crls are OPTIONAL)
+ if ((byte) (dis.peekByte()) == (byte) 0xA1) {
+ dis.getSet(0, true);
+ }
+
+ // signerInfos
+ DerValue[] signerInfoVals = dis.getSet(1);
+
+ len = signerInfoVals.length;
+ signerInfos = new SignerInfo[len];
+
+ for (int i = 0; i < len; i++) {
+ DerInputStream in = signerInfoVals[i].toDerInputStream();
+ signerInfos[i] = new SignerInfo(in);
+ }
}
/**
* Encodes the signed data to an output stream.
- *
+ *
* @param out the output stream to write the encoded data to.
* @exception IOException on encoding errors.
*/
public void encodeSignedData(OutputStream out) throws IOException {
- DerOutputStream derout = new DerOutputStream();
- encodeSignedData(derout, true);
- out.write(derout.toByteArray());
+ DerOutputStream derout = new DerOutputStream();
+ encodeSignedData(derout, true);
+ out.write(derout.toByteArray());
}
/**
- * Like method above but not sorted.
+ * Like method above but not sorted.
*/
- public void encodeSignedData(OutputStream out, boolean sort)
- throws IOException {
- DerOutputStream derout = new DerOutputStream();
- encodeSignedData(derout, sort);
- out.write(derout.toByteArray());
+ public void encodeSignedData(OutputStream out, boolean sort)
+ throws IOException {
+ DerOutputStream derout = new DerOutputStream();
+ encodeSignedData(derout, sort);
+ out.write(derout.toByteArray());
}
/**
* encode signed data, sort certs by default.
*/
public void encodeSignedData(DerOutputStream out)
- throws IOException {
- encodeSignedData(out, true);
+ throws IOException {
+ encodeSignedData(out, true);
}
/**
* Encodes the signed data to a DerOutputStream.
- *
+ *
* @param out the DerOutputStream to write the encoded data to.
* @exception IOException on encoding errors.
*/
- public void encodeSignedData(DerOutputStream out, boolean sort)
- throws IOException {
+ public void encodeSignedData(DerOutputStream out, boolean sort)
+ throws IOException {
- DerOutputStream signedData = new DerOutputStream();
+ DerOutputStream signedData = new DerOutputStream();
- // version
- signedData.putInteger(version);
-
- // digestAlgorithmIds
- signedData.putOrderedSetOf(DerValue.tag_Set, digestAlgorithmIds);
+ // version
+ signedData.putInteger(version);
- // contentInfo
- contentInfo.encode(signedData);
-
- // certificates
- DerOutputStream certs = new DerOutputStream();
+ // digestAlgorithmIds
+ signedData.putOrderedSetOf(DerValue.tag_Set, digestAlgorithmIds);
- // cast to X509CertImpl[] since X509CertImpl implements DerEncoder
+ // contentInfo
+ contentInfo.encode(signedData);
+
+ // certificates
+ DerOutputStream certs = new DerOutputStream();
+
+ // cast to X509CertImpl[] since X509CertImpl implements DerEncoder
X509CertImpl implCerts[] = new X509CertImpl[certificates.length];
- try {
- for (int i = 0; i < certificates.length; i++) {
- implCerts[i] = (X509CertImpl) certificates[i];
+ try {
+ for (int i = 0; i < certificates.length; i++) {
+ implCerts[i] = (X509CertImpl) certificates[i];
}
- } catch (ClassCastException e) {
- IOException ioe =
- new IOException("Certificates in PKCS7 " +
- "must be of class " +
- "netscape.security.X509CertImpl");
- ioe.fillInStackTrace();
- }
-
- // Add the certificate set (tagged with [0] IMPLICIT)
- // to the signed data
- if (sort) {
- signedData.putOrderedSetOf((byte)0xA0, implCerts);
- }
- else {
- signedData.putSet((byte)0xA0, implCerts);
- }
-
- // no crls (OPTIONAL field)
-
- // signerInfos
- signedData.putOrderedSetOf(DerValue.tag_Set, signerInfos);
-
- // making it a signed data block
- DerValue signedDataSeq = new DerValue(DerValue.tag_Sequence,
- signedData.toByteArray());
-
- // making it a content info sequence
- ContentInfo block = new ContentInfo(ContentInfo.SIGNED_DATA_OID,
- signedDataSeq);
-
- // writing out the contentInfo sequence
- block.encode(out);
+ } catch (ClassCastException e) {
+ IOException ioe =
+ new IOException("Certificates in PKCS7 " +
+ "must be of class " +
+ "netscape.security.X509CertImpl");
+ ioe.fillInStackTrace();
+ }
+
+ // Add the certificate set (tagged with [0] IMPLICIT)
+ // to the signed data
+ if (sort) {
+ signedData.putOrderedSetOf((byte) 0xA0, implCerts);
+ } else {
+ signedData.putSet((byte) 0xA0, implCerts);
+ }
+
+ // no crls (OPTIONAL field)
+
+ // signerInfos
+ signedData.putOrderedSetOf(DerValue.tag_Set, signerInfos);
+
+ // making it a signed data block
+ DerValue signedDataSeq = new DerValue(DerValue.tag_Sequence,
+ signedData.toByteArray());
+
+ // making it a content info sequence
+ ContentInfo block = new ContentInfo(ContentInfo.SIGNED_DATA_OID,
+ signedDataSeq);
+
+ // writing out the contentInfo sequence
+ block.encode(out);
}
/**
* This verifies a given SignerInfo.
- *
+ *
* @param info the signer information.
* @param bytes the DER encoded content information.
- *
+ *
* @exception NoSuchAlgorithmException on unrecognized algorithms.
* @exception SignatureException on signature handling errors.
*/
- public SignerInfo verify(SignerInfo info, byte[] bytes)
- throws NoSuchAlgorithmException, SignatureException {
- return info.verify(this, bytes);
+ public SignerInfo verify(SignerInfo info, byte[] bytes)
+ throws NoSuchAlgorithmException, SignatureException {
+ return info.verify(this, bytes);
}
- /**
+ /**
* Returns all signerInfos which self-verify.
- *
+ *
* @param bytes the DER encoded content information.
- *
+ *
* @exception NoSuchAlgorithmException on unrecognized algorithms.
* @exception SignatureException on signature handling errors.
*/
public SignerInfo[] verify(byte[] bytes)
- throws NoSuchAlgorithmException, SignatureException {
-
- Vector intResult = new Vector();
- for (int i = 0; i < signerInfos.length; i++) {
-
- SignerInfo signerInfo = verify(signerInfos[i], bytes);
- if (signerInfo != null) {
- intResult.addElement(signerInfo);
- }
- }
- if (intResult.size() != 0) {
-
- SignerInfo[] result = new SignerInfo[intResult.size()];
- intResult.copyInto(result);
- return result;
- }
- return null;
+ throws NoSuchAlgorithmException, SignatureException {
+
+ Vector intResult = new Vector();
+ for (int i = 0; i < signerInfos.length; i++) {
+
+ SignerInfo signerInfo = verify(signerInfos[i], bytes);
+ if (signerInfo != null) {
+ intResult.addElement(signerInfo);
+ }
+ }
+ if (intResult.size() != 0) {
+
+ SignerInfo[] result = new SignerInfo[intResult.size()];
+ intResult.copyInto(result);
+ return result;
+ }
+ return null;
}
- /**
+ /**
* Returns all signerInfos which self-verify.
- *
+ *
* @exception NoSuchAlgorithmException on unrecognized algorithms.
* @exception SignatureException on signature handling errors.
*/
- public SignerInfo[] verify()
- throws NoSuchAlgorithmException, SignatureException {
- return verify(null);
+ public SignerInfo[] verify()
+ throws NoSuchAlgorithmException, SignatureException {
+ return verify(null);
}
-
- /**
+
+ /**
* Returns the version number of this PKCS7 block.
*/
- public BigInt getVersion() {
- return version;
+ public BigInt getVersion() {
+ return version;
}
- /**
+ /**
* Returns the message digest algorithms specified in this PKCS7 block.
*/
public AlgorithmId[] getDigestAlgorithmIds() {
- return digestAlgorithmIds;
+ return digestAlgorithmIds;
}
- /**
+ /**
* Returns the content information specified in this PKCS7 block.
*/
public ContentInfo getContentInfo() {
- return contentInfo;
+ return contentInfo;
}
- /**
+ /**
* Returns the X.509 certificates listed in this PKCS7 block.
*/
public X509Certificate[] getCertificates() {
- return certificates;
+ return certificates;
}
- /**
+ /**
* Returns the signer's information specified in this PKCS7 block.
*/
public SignerInfo[] getSignerInfos() {
- return signerInfos;
+ return signerInfos;
}
- /**
- * Returns the X.509 certificate listed in this PKCS7 block
- * which has a matching serial number and Issuer name, or
- * null if one is not found.
- *
+ /**
+ * Returns the X.509 certificate listed in this PKCS7 block which has a
+ * matching serial number and Issuer name, or null if one is not found.
+ *
* @param serial the serial number of the certificate to retrieve.
* @param name the Distinguished Name of the Issuer.
*/
public X509Certificate getCertificate(BigInt serial, X500Name name) {
- for (int i = 0; i < certificates.length; i++) {
- X509Certificate cert = certificates[i];
- X500Name thisName = (X500Name)cert.getIssuerDN();
- BigInteger tmpSerial = (BigInteger)cert.getSerialNumber();
- BigInt thisSerial = new BigInt(tmpSerial);
- if (serial.equals(thisSerial) && name.equals(thisName)) {
- return cert;
- }
- }
- return null;
+ for (int i = 0; i < certificates.length; i++) {
+ X509Certificate cert = certificates[i];
+ X500Name thisName = (X500Name) cert.getIssuerDN();
+ BigInteger tmpSerial = (BigInteger) cert.getSerialNumber();
+ BigInt thisSerial = new BigInt(tmpSerial);
+ if (serial.equals(thisSerial) && name.equals(thisName)) {
+ return cert;
+ }
+ }
+ return null;
}
- /**
+ /**
* Returns the PKCS7 block in a printable string form.
*/
public String toString() {
- String out = "";
-
- out += "PKCS7 :: version: " + version + "\n";
- out += "PKCS7 :: digest AlgorithmIds: \n";
- for (int i = 0; i < digestAlgorithmIds.length; i++) {
- out += "\t" + digestAlgorithmIds[i] + "\n";
- }
- out += contentInfo + "\n";
- out += "PKCS7 :: certificates: \n";
- for (int i = 0; i < certificates.length; i++) {
- out += "\t" + i + ". " + certificates[i] + "\n";
- }
- out += "PKCS7 :: signer infos: \n";
- for (int i = 0; i < signerInfos.length; i++) {
- out += ("\t" + i + ". " + signerInfos[i] + "\n");
- }
- return out;
+ String out = "";
+
+ out += "PKCS7 :: version: " + version + "\n";
+ out += "PKCS7 :: digest AlgorithmIds: \n";
+ for (int i = 0; i < digestAlgorithmIds.length; i++) {
+ out += "\t" + digestAlgorithmIds[i] + "\n";
+ }
+ out += contentInfo + "\n";
+ out += "PKCS7 :: certificates: \n";
+ for (int i = 0; i < certificates.length; i++) {
+ out += "\t" + i + ". " + certificates[i] + "\n";
+ }
+ out += "PKCS7 :: signer infos: \n";
+ for (int i = 0; i < signerInfos.length; i++) {
+ out += ("\t" + i + ". " + signerInfos[i] + "\n");
+ }
+ return out;
}
}
diff --git a/pki/base/util/src/netscape/security/pkcs/PKCS8Key.java b/pki/base/util/src/netscape/security/pkcs/PKCS8Key.java
index eb4478fc..4d79ebf0 100644
--- a/pki/base/util/src/netscape/security/pkcs/PKCS8Key.java
+++ b/pki/base/util/src/netscape/security/pkcs/PKCS8Key.java
@@ -40,7 +40,7 @@ import netscape.security.x509.AlgorithmId;
/**
* Holds a PKCS#8 key, for example a private key
- *
+ *
* @version 1.30, 97/12/10
* @author Dave Brownell
* @author Benjamin Renaud
@@ -61,382 +61,378 @@ public class PKCS8Key implements PrivateKey {
/* The version for this key */
public static final BigInteger VERSION = BigInteger.valueOf(0);
-
+
/**
- * Default constructor. The key constructed must have its key
- * and algorithm initialized before it may be used, for example
- * by using <code>decode</code>.
+ * Default constructor. The key constructed must have its key and algorithm
+ * initialized before it may be used, for example by using
+ * <code>decode</code>.
*/
- public PKCS8Key() { }
+ public PKCS8Key() {
+ }
/**
- * Construct PKCS#8 subject public key from a DER value. If
- * the runtime environment is configured with a specific class for
- * this kind of key, a subclass is returned. Otherwise, a generic
- * PKCS8Key object is returned.
+ * Construct PKCS#8 subject public key from a DER value. If the runtime
+ * environment is configured with a specific class for this kind of key, a
+ * subclass is returned. Otherwise, a generic PKCS8Key object is returned.
+ *
+ * <P>
+ * This mechanism gurantees that keys (and algorithms) may be freely
+ * manipulated and transferred, without risk of losing information. Also,
+ * when a key (or algorithm) needs some special handling, that specific need
+ * can be accomodated.
*
- * <P>This mechanism gurantees that keys (and algorithms) may be
- * freely manipulated and transferred, without risk of losing
- * information. Also, when a key (or algorithm) needs some special
- * handling, that specific need can be accomodated.
- *
* @param in the DER-encoded SubjectPublicKeyInfo value
* @exception IOException on data format errors
*/
- public static PKCS8Key parse (DerValue in) throws IOException
- {
- AlgorithmId algorithm;
- PKCS8Key subjectKey;
-
- if (in.tag != DerValue.tag_Sequence)
- throw new IOException ("corrupt private key");
-
- BigInteger parsedVersion = in.data.getInteger().toBigInteger();
- if (!VERSION.equals(parsedVersion)) {
- throw new IOException("version mismatch: (supported: " +
- VERSION + ", parsed: " +
- parsedVersion);
- }
-
- algorithm = AlgorithmId.parse (in.data.getDerValue ());
-
- try {
- subjectKey = buildPKCS8Key (algorithm, in.data.getOctetString ());
-
- } catch (InvalidKeyException e) {
- throw new IOException("corrupt private key");
- }
-
- if (in.data.available () != 0)
- throw new IOException ("excess private key");
- return subjectKey;
+ public static PKCS8Key parse(DerValue in) throws IOException {
+ AlgorithmId algorithm;
+ PKCS8Key subjectKey;
+
+ if (in.tag != DerValue.tag_Sequence)
+ throw new IOException("corrupt private key");
+
+ BigInteger parsedVersion = in.data.getInteger().toBigInteger();
+ if (!VERSION.equals(parsedVersion)) {
+ throw new IOException("version mismatch: (supported: " +
+ VERSION + ", parsed: " +
+ parsedVersion);
+ }
+
+ algorithm = AlgorithmId.parse(in.data.getDerValue());
+
+ try {
+ subjectKey = buildPKCS8Key(algorithm, in.data.getOctetString());
+
+ } catch (InvalidKeyException e) {
+ throw new IOException("corrupt private key");
+ }
+
+ if (in.data.available() != 0)
+ throw new IOException("excess private key");
+ return subjectKey;
}
/**
- * Parse the key bits. This may be redefined by subclasses to take
- * advantage of structure within the key. For example, RSA public
- * keys encapsulate two unsigned integers (modulus and exponent) as
- * DER values within the <code>key</code> bits; Diffie-Hellman and
- * DSS/DSA keys encapsulate a single unsigned integer.
- *
- * <P>This function is called when creating PKCS#8 SubjectPublicKeyInfo
- * values using the PKCS8Key member functions, such as <code>parse</code>
- * and <code>decode</code>.
- *
+ * Parse the key bits. This may be redefined by subclasses to take advantage
+ * of structure within the key. For example, RSA public keys encapsulate two
+ * unsigned integers (modulus and exponent) as DER values within the
+ * <code>key</code> bits; Diffie-Hellman and DSS/DSA keys encapsulate a
+ * single unsigned integer.
+ *
+ * <P>
+ * This function is called when creating PKCS#8 SubjectPublicKeyInfo values
+ * using the PKCS8Key member functions, such as <code>parse</code> and
+ * <code>decode</code>.
+ *
* @exception IOException if a parsing error occurs.
* @exception InvalidKeyException if the key encoding is invalid.
*/
- protected void parseKeyBits () throws IOException, InvalidKeyException {
- encode();
+ protected void parseKeyBits() throws IOException, InvalidKeyException {
+ encode();
}
/*
- * Factory interface, building the kind of key associated with this
- * specific algorithm ID or else returning this generic base class.
- * See the description above.
+ * Factory interface, building the kind of key associated with this specific
+ * algorithm ID or else returning this generic base class. See the
+ * description above.
*/
- public static PKCS8Key buildPKCS8Key (AlgorithmId algid, byte[] key)
- throws IOException, InvalidKeyException
- {
- /*
- * Use the algid and key parameters to produce the ASN.1 encoding
- * of the key, which will then be used as the input to the
- * key factory.
- */
- DerOutputStream pkcs8EncodedKeyStream = new DerOutputStream();
- encode(pkcs8EncodedKeyStream, algid, key);
- PKCS8EncodedKeySpec pkcs8KeySpec
- = new PKCS8EncodedKeySpec(pkcs8EncodedKeyStream.toByteArray());
-
- try {
- // Instantiate the key factory of the appropriate algorithm
- KeyFactory keyFac = KeyFactory.getInstance(algid.getName());
-
- // Generate the private key
- PrivateKey privKey = keyFac.generatePrivate(pkcs8KeySpec);
-
- if (privKey instanceof PKCS8Key) {
- /*
- * Return specialized PKCS8Key, where the structure within the
- * key has been parsed
- */
- return (PKCS8Key)privKey;
- }
- } catch (NoSuchAlgorithmException e) {
- // Return generic PKCS8Key with opaque key data (see below)
- } catch (InvalidKeySpecException e) {
- // Return generic PKCS8Key with opaque key data (see below)
- }
-
- /*
- * Try again using JDK1.1-style for backwards compatibility.
- */
- String classname = "";
- try {
- Properties props;
- String keytype;
- Provider sunProvider;
-
- sunProvider = Security.getProvider("SUN");
- if (sunProvider == null)
- throw new InstantiationException();
- classname = sunProvider.getProperty("PrivateKey.PKCS#8." +
- algid.getName());
- if (classname == null) {
- throw new InstantiationException();
- }
-
- Class keyClass = Class.forName(classname);
- Object inst;
- PKCS8Key result;
-
- inst = keyClass.newInstance();
- if (inst instanceof PKCS8Key) {
- result = (PKCS8Key) inst;
- result.algid = algid;
- result.key = key;
- result.parseKeyBits();
- return result;
- }
- } catch (ClassNotFoundException e) {
- } catch (InstantiationException e) {
- } catch (IllegalAccessException e) {
- // this should not happen.
- throw new IOException (classname + " [internal error]");
- }
-
- PKCS8Key result = new PKCS8Key();
- result.algid = algid;
- result.key = key;
- return result;
+ public static PKCS8Key buildPKCS8Key(AlgorithmId algid, byte[] key)
+ throws IOException, InvalidKeyException {
+ /*
+ * Use the algid and key parameters to produce the ASN.1 encoding of the
+ * key, which will then be used as the input to the key factory.
+ */
+ DerOutputStream pkcs8EncodedKeyStream = new DerOutputStream();
+ encode(pkcs8EncodedKeyStream, algid, key);
+ PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(pkcs8EncodedKeyStream.toByteArray());
+
+ try {
+ // Instantiate the key factory of the appropriate algorithm
+ KeyFactory keyFac = KeyFactory.getInstance(algid.getName());
+
+ // Generate the private key
+ PrivateKey privKey = keyFac.generatePrivate(pkcs8KeySpec);
+
+ if (privKey instanceof PKCS8Key) {
+ /*
+ * Return specialized PKCS8Key, where the structure within the
+ * key has been parsed
+ */
+ return (PKCS8Key) privKey;
+ }
+ } catch (NoSuchAlgorithmException e) {
+ // Return generic PKCS8Key with opaque key data (see below)
+ } catch (InvalidKeySpecException e) {
+ // Return generic PKCS8Key with opaque key data (see below)
+ }
+
+ /*
+ * Try again using JDK1.1-style for backwards compatibility.
+ */
+ String classname = "";
+ try {
+ Properties props;
+ String keytype;
+ Provider sunProvider;
+
+ sunProvider = Security.getProvider("SUN");
+ if (sunProvider == null)
+ throw new InstantiationException();
+ classname = sunProvider.getProperty("PrivateKey.PKCS#8." +
+ algid.getName());
+ if (classname == null) {
+ throw new InstantiationException();
+ }
+
+ Class keyClass = Class.forName(classname);
+ Object inst;
+ PKCS8Key result;
+
+ inst = keyClass.newInstance();
+ if (inst instanceof PKCS8Key) {
+ result = (PKCS8Key) inst;
+ result.algid = algid;
+ result.key = key;
+ result.parseKeyBits();
+ return result;
+ }
+ } catch (ClassNotFoundException e) {
+ } catch (InstantiationException e) {
+ } catch (IllegalAccessException e) {
+ // this should not happen.
+ throw new IOException(classname + " [internal error]");
+ }
+
+ PKCS8Key result = new PKCS8Key();
+ result.algid = algid;
+ result.key = key;
+ return result;
}
/**
* Returns the algorithm to be used with this key.
*/
- public String getAlgorithm() {
- return algid.getName();
+ public String getAlgorithm() {
+ return algid.getName();
}
/**
* Returns the algorithm ID to be used with this key.
*/
- public AlgorithmId getAlgorithmId () { return algid; }
+ public AlgorithmId getAlgorithmId() {
+ return algid;
+ }
/**
* PKCS#8 sequence on the DER output stream.
*/
- public final void encode(DerOutputStream out) throws IOException
- {
- encode(out, this.algid, this.key);
+ public final void encode(DerOutputStream out) throws IOException {
+ encode(out, this.algid, this.key);
}
/**
* Returns the DER-encoded form of the key as a byte array.
*/
public synchronized byte[] getEncoded() {
- byte[] result = null;
- try {
- result = encode();
- } catch (InvalidKeyException e) {
- }
- return result;
+ byte[] result = null;
+ try {
+ result = encode();
+ } catch (InvalidKeyException e) {
+ }
+ return result;
}
/**
* Returns the format for this key: "PKCS#8"
*/
public String getFormat() {
- return "PKCS#8";
+ return "PKCS#8";
}
/**
* Returns the DER-encoded form of the key as a byte array.
- *
+ *
* @exception InvalidKeyException if an encoding error occurs.
*/
public byte[] encode() throws InvalidKeyException {
- if (encodedKey == null) {
- try {
- DerOutputStream out;
-
- out = new DerOutputStream ();
- encode (out);
- encodedKey = out.toByteArray();
-
- } catch (IOException e) {
- throw new InvalidKeyException ("IOException : " +
- e.getMessage());
- }
- }
- return copyEncodedKey(encodedKey);
+ if (encodedKey == null) {
+ try {
+ DerOutputStream out;
+
+ out = new DerOutputStream();
+ encode(out);
+ encodedKey = out.toByteArray();
+
+ } catch (IOException e) {
+ throw new InvalidKeyException("IOException : " +
+ e.getMessage());
+ }
+ }
+ return copyEncodedKey(encodedKey);
}
/*
* Returns a printable representation of the key
*/
- public String toString ()
- {
- netscape.security.util.PrettyPrintFormat pp =
- new netscape.security.util.PrettyPrintFormat(" ", 20);
- String keybits = pp.toHexString(key);
-
- return "algorithm = " + algid.toString ()
- + ", unparsed keybits = \n" + keybits;
+ public String toString() {
+ netscape.security.util.PrettyPrintFormat pp =
+ new netscape.security.util.PrettyPrintFormat(" ", 20);
+ String keybits = pp.toHexString(key);
+
+ return "algorithm = " + algid.toString()
+ + ", unparsed keybits = \n" + keybits;
}
- /**
- * Initialize an PKCS8Key object from an input stream. The data
- * on that input stream must be encoded using DER, obeying the
- * PKCS#8 format: a sequence consisting of a version, an algorithm
- * ID and a bit string which holds the key. (That bit string is
- * often used to encapsulate another DER encoded sequence.)
- *
- * <P>Subclasses should not normally redefine this method; they should
- * instead provide a <code>parseKeyBits</code> method to parse any
- * fields inside the <code>key</code> member.
- *
- * @param in an input stream with a DER-encoded PKCS#8
- * SubjectPublicKeyInfo value
- *
+ /**
+ * Initialize an PKCS8Key object from an input stream. The data on that
+ * input stream must be encoded using DER, obeying the PKCS#8 format: a
+ * sequence consisting of a version, an algorithm ID and a bit string which
+ * holds the key. (That bit string is often used to encapsulate another DER
+ * encoded sequence.)
+ *
+ * <P>
+ * Subclasses should not normally redefine this method; they should instead
+ * provide a <code>parseKeyBits</code> method to parse any fields inside the
+ * <code>key</code> member.
+ *
+ * @param in an input stream with a DER-encoded PKCS#8 SubjectPublicKeyInfo
+ * value
+ *
* @exception InvalidKeyException if a parsing error occurs.
*/
- public void decode(InputStream in) throws InvalidKeyException
- {
- DerValue val;
-
- try {
- val = new DerValue (in);
- if (val.tag != DerValue.tag_Sequence)
- throw new InvalidKeyException ("invalid key format");
-
-
- BigInteger version = val.data.getInteger().toBigInteger();
- if (!version.equals(PKCS8Key.VERSION)) {
- throw new IOException("version mismatch: (supported: " +
- PKCS8Key.VERSION + ", parsed: " +
- version);
- }
- algid = AlgorithmId.parse (val.data.getDerValue ());
- key = val.data.getOctetString ();
- parseKeyBits ();
- if (val.data.available () != 0)
- throw new InvalidKeyException ("excess key data");
-
- } catch (IOException e) {
- // e.printStackTrace ();
- throw new InvalidKeyException("IOException : " +
- e.getMessage());
- }
+ public void decode(InputStream in) throws InvalidKeyException {
+ DerValue val;
+
+ try {
+ val = new DerValue(in);
+ if (val.tag != DerValue.tag_Sequence)
+ throw new InvalidKeyException("invalid key format");
+
+ BigInteger version = val.data.getInteger().toBigInteger();
+ if (!version.equals(PKCS8Key.VERSION)) {
+ throw new IOException("version mismatch: (supported: " +
+ PKCS8Key.VERSION + ", parsed: " +
+ version);
+ }
+ algid = AlgorithmId.parse(val.data.getDerValue());
+ key = val.data.getOctetString();
+ parseKeyBits();
+ if (val.data.available() != 0)
+ throw new InvalidKeyException("excess key data");
+
+ } catch (IOException e) {
+ // e.printStackTrace ();
+ throw new InvalidKeyException("IOException : " +
+ e.getMessage());
+ }
}
public void decode(byte[] encodedKey) throws InvalidKeyException {
- decode(new ByteArrayInputStream(encodedKey));
+ decode(new ByteArrayInputStream(encodedKey));
}
/**
- * Serialization write ... PKCS#8 keys serialize as
- * themselves, and they're parsed when they get read back.
+ * Serialization write ... PKCS#8 keys serialize as themselves, and they're
+ * parsed when they get read back.
*/
private synchronized void
- writeObject (java.io.ObjectOutputStream stream)
- throws IOException {
- stream.write(getEncoded());
+ writeObject(java.io.ObjectOutputStream stream)
+ throws IOException {
+ stream.write(getEncoded());
}
/**
- * Serialization read ... PKCS#8 keys serialize as
- * themselves, and they're parsed when they get read back.
+ * Serialization read ... PKCS#8 keys serialize as themselves, and they're
+ * parsed when they get read back.
*/
- private synchronized void readObject (ObjectInputStream stream)
- throws IOException {
+ private synchronized void readObject(ObjectInputStream stream)
+ throws IOException {
- try {
- decode(stream);
+ try {
+ decode(stream);
- } catch (InvalidKeyException e) {
- e.printStackTrace();
- throw new IOException("deserialized key is invalid: " +
- e.getMessage());
- }
+ } catch (InvalidKeyException e) {
+ e.printStackTrace();
+ throw new IOException("deserialized key is invalid: " +
+ e.getMessage());
+ }
}
/*
* Make a copy of the encoded key.
*/
private byte[] copyEncodedKey(byte[] encodedKey) {
- int len = encodedKey.length;
- byte[] copy = new byte[len];
- System.arraycopy(encodedKey, 0, copy, 0, len);
- return copy;
+ int len = encodedKey.length;
+ byte[] copy = new byte[len];
+ System.arraycopy(encodedKey, 0, copy, 0, len);
+ return copy;
}
/*
* Produce PKCS#8 encoding from algorithm id and key material.
*/
static void encode(DerOutputStream out, AlgorithmId algid, byte[] key)
- throws IOException {
- DerOutputStream tmp = new DerOutputStream();
- tmp.putInteger(new BigInt(VERSION.toByteArray()));
- algid.encode(tmp);
- tmp.putOctetString(key);
- out.write(DerValue.tag_Sequence, tmp);
+ throws IOException {
+ DerOutputStream tmp = new DerOutputStream();
+ tmp.putInteger(new BigInt(VERSION.toByteArray()));
+ algid.encode(tmp);
+ tmp.putOctetString(key);
+ out.write(DerValue.tag_Sequence, tmp);
}
/**
- * Compares two private keys. This returns false if the object with which
- * to compare is not of type <code>Key</code>.
- * Otherwise, the encoding of this key object is compared with the
- * encoding of the given key object.
- *
+ * Compares two private keys. This returns false if the object with which to
+ * compare is not of type <code>Key</code>. Otherwise, the encoding of this
+ * key object is compared with the encoding of the given key object.
+ *
* @param object the object with which to compare
- * @return <code>true</code> if this key has the same encoding as the
- * object argument; <code>false</code> otherwise.
+ * @return <code>true</code> if this key has the same encoding as the object
+ * argument; <code>false</code> otherwise.
*/
public boolean equals(Object object) {
- if (this == object) {
- return true;
- }
-
- if (object instanceof Key) {
-
- // this encoding
- byte[] b1;
- if (encodedKey != null) {
- b1 = encodedKey;
- } else {
- b1 = getEncoded();
- }
-
- // that encoding
- byte[] b2 = ((Key)object).getEncoded();
-
- // do the comparison
- int i;
- if (b1.length != b2.length)
- return false;
- for (i = 0; i < b1.length; i++) {
- if (b1[i] != b2[i]) {
- return false;
- }
- }
- return true;
- }
-
- return false;
+ if (this == object) {
+ return true;
+ }
+
+ if (object instanceof Key) {
+
+ // this encoding
+ byte[] b1;
+ if (encodedKey != null) {
+ b1 = encodedKey;
+ } else {
+ b1 = getEncoded();
+ }
+
+ // that encoding
+ byte[] b2 = ((Key) object).getEncoded();
+
+ // do the comparison
+ int i;
+ if (b1.length != b2.length)
+ return false;
+ for (i = 0; i < b1.length; i++) {
+ if (b1[i] != b2[i]) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ return false;
}
/**
- * Calculates a hash code value for this object. Objects
- * which are equal will also have the same hashcode.
+ * Calculates a hash code value for this object. Objects which are equal
+ * will also have the same hashcode.
*/
public int hashCode() {
int retval = 0;
- byte[] b1 = getEncoded();
+ byte[] b1 = getEncoded();
for (int i = 1; i < b1.length; i++) {
retval += b1[i] * i;
}
- return(retval);
+ return (retval);
}
}
diff --git a/pki/base/util/src/netscape/security/pkcs/PKCS9Attribute.java b/pki/base/util/src/netscape/security/pkcs/PKCS9Attribute.java
index fc25e8d8..211ef401 100644
--- a/pki/base/util/src/netscape/security/pkcs/PKCS9Attribute.java
+++ b/pki/base/util/src/netscape/security/pkcs/PKCS9Attribute.java
@@ -31,10 +31,10 @@ import netscape.security.util.ObjectIdentifier;
import netscape.security.x509.CertificateExtensions;
/**
- * Class supporting any PKCS9 attribute except
- * ExtendedCertificateAttribute. Supports DER decoding and access to
- * attribute values, but not DER encoding or setting of values.
- *
+ * Class supporting any PKCS9 attribute except ExtendedCertificateAttribute.
+ * Supports DER decoding and access to attribute values, but not DER encoding or
+ * setting of values.
+ *
* @version 1.2 97/12/10
* @author Douglas Hoover
*/
@@ -50,17 +50,17 @@ public class PKCS9Attribute implements DerEncoder {
/**
* Array of attribute OIDs defined in PKCS9, by number.
*/
- static final ObjectIdentifier[] PKCS9_OIDS =
- //new ObjectIdentifier[10];
- // There are some Obsolete(?) attribute identifiers.
- // This is mainly for extensionRequest (14) in pkcs10.
- // We just add the other 4 as by products.
- new ObjectIdentifier[15];
-
- static { // static initializer for PKCS9_OIDS
- for (int i = 1; i < PKCS9_OIDS.length; i++) {
- PKCS9_OIDS[i] = new ObjectIdentifier(PKCS9_str + "." + i);
- }
+ static final ObjectIdentifier[] PKCS9_OIDS =
+ // new ObjectIdentifier[10];
+ // There are some Obsolete(?) attribute identifiers.
+ // This is mainly for extensionRequest (14) in pkcs10.
+ // We just add the other 4 as by products.
+ new ObjectIdentifier[15];
+
+ static { // static initializer for PKCS9_OIDS
+ for (int i = 1; i < PKCS9_OIDS.length; i++) {
+ PKCS9_OIDS[i] = new ObjectIdentifier(PKCS9_str + "." + i);
+ }
}
public static final ObjectIdentifier EMAIL_ADDRESS_OID = PKCS9_OIDS[1];
@@ -71,19 +71,13 @@ public class PKCS9Attribute implements DerEncoder {
public static final ObjectIdentifier COUNTERSIGNATURE_OID = PKCS9_OIDS[6];
public static final ObjectIdentifier CHALLENGE_PASSWORD_OID = PKCS9_OIDS[7];
public static final ObjectIdentifier UNSTRUCTURED_ADDRESS_OID = PKCS9_OIDS[8];
- public static final ObjectIdentifier
- EXTENDED_CERTIFICATE_ATTRIBUTES_OID = PKCS9_OIDS[9];
-
- public static final ObjectIdentifier
- ISSUER_AND_SERIALNUMBER_OID = PKCS9_OIDS[10];
- public static final ObjectIdentifier
- PASSWORD_CHECK_OID = PKCS9_OIDS[11];
- public static final ObjectIdentifier
- PUBLIC_KEY_OID = PKCS9_OIDS[12];
- public static final ObjectIdentifier
- SIGNING_DESCRIPTION_OID = PKCS9_OIDS[13];
- public static final ObjectIdentifier
- EXTENSION_REQUEST_OID = PKCS9_OIDS[14];
+ public static final ObjectIdentifier EXTENDED_CERTIFICATE_ATTRIBUTES_OID = PKCS9_OIDS[9];
+
+ public static final ObjectIdentifier ISSUER_AND_SERIALNUMBER_OID = PKCS9_OIDS[10];
+ public static final ObjectIdentifier PASSWORD_CHECK_OID = PKCS9_OIDS[11];
+ public static final ObjectIdentifier PUBLIC_KEY_OID = PKCS9_OIDS[12];
+ public static final ObjectIdentifier SIGNING_DESCRIPTION_OID = PKCS9_OIDS[13];
+ public static final ObjectIdentifier EXTENSION_REQUEST_OID = PKCS9_OIDS[14];
public static final String EMAIL_ADDRESS_STR = "EmailAddress";
public static final String UNSTRUCTURED_NAME_STR = "UnstructuredName";
@@ -93,1052 +87,1045 @@ public class PKCS9Attribute implements DerEncoder {
public static final String COUNTERSIGNATURE_STR = "Countersignature";
public static final String CHALLENGE_PASSWORD_STR = "ChallengePassword";
public static final String UNSTRUCTURED_ADDRESS_STR = "UnstructuredAddress";
- public static final String
- EXTENDED_CERTIFICATE_ATTRIBUTES_STR = "ExtendedCertificateAttributes";
-
- public static final String
- ISSUER_AND_SERIALNUMBER_STR = "IssuerAndSerialNumber";
- public static final String
- PASSWORD_CHECK_STR = "PasswordCheck";
- public static final String
- PUBLIC_KEY_STR = "PublicKey";
- public static final String
- SIGNING_DESCRIPTION_STR = "SigningDescription";
- public static final String
- EXTENSION_REQUEST_STR = "ExtensionRequest";
-
- /**
- * Hashtable mapping names and variant names of supported
- * attributes to their OIDs. This table contains all name forms
- * that occur in PKCS9, in lower case.
+ public static final String EXTENDED_CERTIFICATE_ATTRIBUTES_STR = "ExtendedCertificateAttributes";
+
+ public static final String ISSUER_AND_SERIALNUMBER_STR = "IssuerAndSerialNumber";
+ public static final String PASSWORD_CHECK_STR = "PasswordCheck";
+ public static final String PUBLIC_KEY_STR = "PublicKey";
+ public static final String SIGNING_DESCRIPTION_STR = "SigningDescription";
+ public static final String EXTENSION_REQUEST_STR = "ExtensionRequest";
+
+ /**
+ * Hashtable mapping names and variant names of supported attributes to
+ * their OIDs. This table contains all name forms that occur in PKCS9, in
+ * lower case.
*/
private static final Hashtable<String, ObjectIdentifier> NAME_OID_TABLE = new Hashtable<String, ObjectIdentifier>(28);
static { // static initializer for PCKS9_NAMES
- NAME_OID_TABLE.put("emailaddress", PKCS9_OIDS[1]);
- NAME_OID_TABLE.put("unstructuredname", PKCS9_OIDS[2]);
- NAME_OID_TABLE.put("contenttype", PKCS9_OIDS[3]);
- NAME_OID_TABLE.put("messagedigest", PKCS9_OIDS[4]);
- NAME_OID_TABLE.put("signingtime", PKCS9_OIDS[5]);
- NAME_OID_TABLE.put("countersignature", PKCS9_OIDS[6]);
- NAME_OID_TABLE.put("challengepassword", PKCS9_OIDS[7]);
- NAME_OID_TABLE.put("unstructuredaddress", PKCS9_OIDS[8]);
- NAME_OID_TABLE.put("extendedcertificateattributes", PKCS9_OIDS[9]);
-
- NAME_OID_TABLE.put("issuerandserialNumber", PKCS9_OIDS[10]);
- NAME_OID_TABLE.put("passwordcheck", PKCS9_OIDS[11]);
- NAME_OID_TABLE.put("publickey", PKCS9_OIDS[12]);
- NAME_OID_TABLE.put("signingdescription", PKCS9_OIDS[13]);
- NAME_OID_TABLE.put("extensionrequest", PKCS9_OIDS[14]);
+ NAME_OID_TABLE.put("emailaddress", PKCS9_OIDS[1]);
+ NAME_OID_TABLE.put("unstructuredname", PKCS9_OIDS[2]);
+ NAME_OID_TABLE.put("contenttype", PKCS9_OIDS[3]);
+ NAME_OID_TABLE.put("messagedigest", PKCS9_OIDS[4]);
+ NAME_OID_TABLE.put("signingtime", PKCS9_OIDS[5]);
+ NAME_OID_TABLE.put("countersignature", PKCS9_OIDS[6]);
+ NAME_OID_TABLE.put("challengepassword", PKCS9_OIDS[7]);
+ NAME_OID_TABLE.put("unstructuredaddress", PKCS9_OIDS[8]);
+ NAME_OID_TABLE.put("extendedcertificateattributes", PKCS9_OIDS[9]);
+
+ NAME_OID_TABLE.put("issuerandserialNumber", PKCS9_OIDS[10]);
+ NAME_OID_TABLE.put("passwordcheck", PKCS9_OIDS[11]);
+ NAME_OID_TABLE.put("publickey", PKCS9_OIDS[12]);
+ NAME_OID_TABLE.put("signingdescription", PKCS9_OIDS[13]);
+ NAME_OID_TABLE.put("extensionrequest", PKCS9_OIDS[14]);
};
/**
- * Hashtable mapping attribute OIDs defined in PKCS9 to the
- * corresponding attribute value type.
+ * Hashtable mapping attribute OIDs defined in PKCS9 to the corresponding
+ * attribute value type.
*/
private static final Hashtable<ObjectIdentifier, String> OID_NAME_TABLE = new Hashtable<ObjectIdentifier, String>(14);
- static {
- OID_NAME_TABLE.put(PKCS9_OIDS[1], EMAIL_ADDRESS_STR);
- OID_NAME_TABLE.put(PKCS9_OIDS[2], UNSTRUCTURED_NAME_STR);
- OID_NAME_TABLE.put(PKCS9_OIDS[3], CONTENT_TYPE_STR);
- OID_NAME_TABLE.put(PKCS9_OIDS[4], MESSAGE_DIGEST_STR);
- OID_NAME_TABLE.put(PKCS9_OIDS[5], SIGNING_TIME_STR);
- OID_NAME_TABLE.put(PKCS9_OIDS[6], COUNTERSIGNATURE_STR);
- OID_NAME_TABLE.put(PKCS9_OIDS[7], CHALLENGE_PASSWORD_STR);
- OID_NAME_TABLE.put(PKCS9_OIDS[8], UNSTRUCTURED_ADDRESS_STR);
- OID_NAME_TABLE.put(PKCS9_OIDS[9], EXTENDED_CERTIFICATE_ATTRIBUTES_STR);
-
- OID_NAME_TABLE.put(PKCS9_OIDS[10], ISSUER_AND_SERIALNUMBER_STR);
- OID_NAME_TABLE.put(PKCS9_OIDS[11], PASSWORD_CHECK_STR);
- OID_NAME_TABLE.put(PKCS9_OIDS[12], PUBLIC_KEY_STR);
- OID_NAME_TABLE.put(PKCS9_OIDS[13], SIGNING_DESCRIPTION_STR);
- OID_NAME_TABLE.put(PKCS9_OIDS[14], EXTENSION_REQUEST_STR);
+ static {
+ OID_NAME_TABLE.put(PKCS9_OIDS[1], EMAIL_ADDRESS_STR);
+ OID_NAME_TABLE.put(PKCS9_OIDS[2], UNSTRUCTURED_NAME_STR);
+ OID_NAME_TABLE.put(PKCS9_OIDS[3], CONTENT_TYPE_STR);
+ OID_NAME_TABLE.put(PKCS9_OIDS[4], MESSAGE_DIGEST_STR);
+ OID_NAME_TABLE.put(PKCS9_OIDS[5], SIGNING_TIME_STR);
+ OID_NAME_TABLE.put(PKCS9_OIDS[6], COUNTERSIGNATURE_STR);
+ OID_NAME_TABLE.put(PKCS9_OIDS[7], CHALLENGE_PASSWORD_STR);
+ OID_NAME_TABLE.put(PKCS9_OIDS[8], UNSTRUCTURED_ADDRESS_STR);
+ OID_NAME_TABLE.put(PKCS9_OIDS[9], EXTENDED_CERTIFICATE_ATTRIBUTES_STR);
+
+ OID_NAME_TABLE.put(PKCS9_OIDS[10], ISSUER_AND_SERIALNUMBER_STR);
+ OID_NAME_TABLE.put(PKCS9_OIDS[11], PASSWORD_CHECK_STR);
+ OID_NAME_TABLE.put(PKCS9_OIDS[12], PUBLIC_KEY_STR);
+ OID_NAME_TABLE.put(PKCS9_OIDS[13], SIGNING_DESCRIPTION_STR);
+ OID_NAME_TABLE.put(PKCS9_OIDS[14], EXTENSION_REQUEST_STR);
}
/**
- * Acceptable ASN.1 tags for DER encodings of values of PKCS9
- * attributes, by index in <code>PKCS9_OIDS</code>.
- * Sets of acceptable tags are represented as arrays.
+ * Acceptable ASN.1 tags for DER encodings of values of PKCS9 attributes, by
+ * index in <code>PKCS9_OIDS</code>. Sets of acceptable tags are represented
+ * as arrays.
*/
private static final Byte[][] PKCS9_VALUE_TAGS = {
- null,
- {Byte.valueOf(DerValue.tag_IA5String)}, // EMailAddress
- {Byte.valueOf(DerValue.tag_IA5String)}, // UnstructuredName
- {Byte.valueOf(DerValue.tag_ObjectId)}, // ContentType
- {Byte.valueOf(DerValue.tag_OctetString)}, // MessageDigest
- {Byte.valueOf(DerValue.tag_UtcTime)}, // SigningTime
- {Byte.valueOf(DerValue.tag_Sequence)}, // Countersignature
- {Byte.valueOf(DerValue.tag_PrintableString),
- Byte.valueOf(DerValue.tag_T61String)}, // ChallengePassword
- {Byte.valueOf(DerValue.tag_PrintableString),
- Byte.valueOf(DerValue.tag_T61String)}, // UnstructuredAddress
- {Byte.valueOf(DerValue.tag_SetOf)}, // ExtendedCertificateAttributes
-
- null, //IssuerAndSerialNumber
- null, //PasswordCheck
- null, //PublicKey
- null, //SigningDescription
- {Byte.valueOf(DerValue.tag_Sequence)} //ExtensionRequest
+ null,
+ { Byte.valueOf(DerValue.tag_IA5String) }, // EMailAddress
+ { Byte.valueOf(DerValue.tag_IA5String) }, // UnstructuredName
+ { Byte.valueOf(DerValue.tag_ObjectId) }, // ContentType
+ { Byte.valueOf(DerValue.tag_OctetString) }, // MessageDigest
+ { Byte.valueOf(DerValue.tag_UtcTime) }, // SigningTime
+ { Byte.valueOf(DerValue.tag_Sequence) }, // Countersignature
+ { Byte.valueOf(DerValue.tag_PrintableString),
+ Byte.valueOf(DerValue.tag_T61String) }, // ChallengePassword
+ { Byte.valueOf(DerValue.tag_PrintableString),
+ Byte.valueOf(DerValue.tag_T61String) }, // UnstructuredAddress
+ { Byte.valueOf(DerValue.tag_SetOf) }, // ExtendedCertificateAttributes
+
+ null, // IssuerAndSerialNumber
+ null, // PasswordCheck
+ null, // PublicKey
+ null, // SigningDescription
+ { Byte.valueOf(DerValue.tag_Sequence) } // ExtensionRequest
};
- /**
- * Class types required for values for a given PKCS9
- * attribute type.
- *
- * <P> The following table shows the correspondence between
- * attribute types and value component classes.
- *
+ /**
+ * Class types required for values for a given PKCS9 attribute type.
+ *
+ * <P>
+ * The following table shows the correspondence between attribute types and
+ * value component classes.
+ *
* <P>
* <TABLE BORDER CELLPADDING=8 ALIGN=CENTER>
- *
+ *
* <TR>
* <TH>OID</TH>
* <TH>Attribute Type Name</TH>
* <TH>Kind</TH>
* <TH>Value Class</TH>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.1</TD>
* <TD>EmailAddress</TD>
* <TD>Multiple-valued</TD>
* <TD><code>String[]</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.2</TD>
* <TD>UnstructuredName</TD>
* <TD>Multiple-valued</TD>
* <TD><code>String</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.3</TD>
* <TD>ContentType</TD>
* <TD>Single-valued</TD>
* <TD><code>ObjectIdentifier</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.4</TD>
* <TD>MessageDigest</TD>
* <TD>Single-valued</TD>
* <TD><code>byte[]</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.5</TD>
* <TD>SigningTime</TD>
* <TD>Single-valued</TD>
* <TD><code>Date</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.6</TD>
* <TD>Countersignature</TD>
* <TD>Multiple-valued</TD>
* <TD><code>SignerInfo</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.7</TD>
* <TD>ChallengePassword</TD>
* <TD>Single-valued</TD>
* <TD><code>String</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.8</TD>
* <TD>UnstructuredAddress</TD>
* <TD>Single-valued</TD>
* <TD><code>String</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.9</TD>
* <TD>ExtendedCertificateAttributes</TD>
* <TD>Multiple-valued</TD>
* <TD>(not supported)</TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.10</TD>
* <TD>IssuerAndSerialNumber</TD>
* <TD>Single-valued</TD>
* <TD>(not supported)</TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.11</TD>
* <TD>PasswordCheck</TD>
* <TD>Single-valued</TD>
* <TD>(not supported)</TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.12</TD>
* <TD>PublicKey</TD>
* <TD>Single-valued</TD>
* <TD>(not supported)</TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.13</TD>
* <TD>SigningDescription</TD>
* <TD>Single-valued</TD>
* <TD>(not supported)</TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.14</TD>
* <TD>ExtensionRequest</TD>
* <TD>Single-valued</TD>
* <TD><code>Sequence</code></TD>
* </TR>
- *
+ *
* </TABLE>
*/
private static final Class<?>[] VALUE_CLASSES = new Class[15];
static {
- try {
- VALUE_CLASSES[0] = null; // not used
- VALUE_CLASSES[1] = java.lang.String.class; // EMailAddress
- VALUE_CLASSES[2] = java.lang.String.class; // UnstructuredName
- VALUE_CLASSES[3] = // ContentType
- Class.forName("netscape.security.util.ObjectIdentifier");
- VALUE_CLASSES[4] = Class.forName("[B"); // MessageDigest (byte[])
- VALUE_CLASSES[5] = Class.forName("java.util.Date"); // SigningTime
- VALUE_CLASSES[6] = // Countersignature
- Class.forName("[Lnetscape.security.pkcs.SignerInfo;");
- VALUE_CLASSES[7] = // ChallengePassword
- Class.forName("java.lang.String");
- VALUE_CLASSES[8] = java.lang.String.class; // UnstructuredAddress
- VALUE_CLASSES[9] = null; // ExtendedCertificateAttributes
-
- VALUE_CLASSES[10] = null; // IssuerAndSerialNumber
- VALUE_CLASSES[11] = null; // PasswordCheck
- VALUE_CLASSES[12] = null; // PublicKey
- VALUE_CLASSES[13] = null; // SigningDescription
- VALUE_CLASSES[14] = // ExtensionRequest
- Class.forName("netscape.security.x509.CertificateExtensions"); //xxxx
- } catch (ClassNotFoundException e) {
- throw new ExceptionInInitializerError(e.toString());
- }
+ try {
+ VALUE_CLASSES[0] = null; // not used
+ VALUE_CLASSES[1] = java.lang.String.class; // EMailAddress
+ VALUE_CLASSES[2] = java.lang.String.class; // UnstructuredName
+ VALUE_CLASSES[3] = // ContentType
+ Class.forName("netscape.security.util.ObjectIdentifier");
+ VALUE_CLASSES[4] = Class.forName("[B"); // MessageDigest (byte[])
+ VALUE_CLASSES[5] = Class.forName("java.util.Date"); // SigningTime
+ VALUE_CLASSES[6] = // Countersignature
+ Class.forName("[Lnetscape.security.pkcs.SignerInfo;");
+ VALUE_CLASSES[7] = // ChallengePassword
+ Class.forName("java.lang.String");
+ VALUE_CLASSES[8] = java.lang.String.class; // UnstructuredAddress
+ VALUE_CLASSES[9] = null; // ExtendedCertificateAttributes
+
+ VALUE_CLASSES[10] = null; // IssuerAndSerialNumber
+ VALUE_CLASSES[11] = null; // PasswordCheck
+ VALUE_CLASSES[12] = null; // PublicKey
+ VALUE_CLASSES[13] = null; // SigningDescription
+ VALUE_CLASSES[14] = // ExtensionRequest
+ Class.forName("netscape.security.x509.CertificateExtensions"); // xxxx
+ } catch (ClassNotFoundException e) {
+ throw new ExceptionInInitializerError(e.toString());
+ }
}
/**
- * Array indicating which PKCS9 attributes are single-valued,
- * by index in <code>PKCS9_OIDS</code>.
+ * Array indicating which PKCS9 attributes are single-valued, by index in
+ * <code>PKCS9_OIDS</code>.
*/
- private static final boolean[] SINGLE_VALUED =
- { false,
- false, // EMailAddress
- false, // UnstructuredName
- true, // ContentType
- true, // MessageDigest
- true, // SigningTime
- false, // Countersignature
- true, // ChallengePassword
- false, // UnstructuredAddress
- false, // ExtendedCertificateAttributes
-
- true, // IssuerAndSerialNumber
- true, // PasswordCheck
- true, // PublicKey
- true, // SigningDescription
- true // ExtensionRequest
+ private static final boolean[] SINGLE_VALUED =
+ { false,
+ false, // EMailAddress
+ false, // UnstructuredName
+ true, // ContentType
+ true, // MessageDigest
+ true, // SigningTime
+ false, // Countersignature
+ true, // ChallengePassword
+ false, // UnstructuredAddress
+ false, // ExtendedCertificateAttributes
+
+ true, // IssuerAndSerialNumber
+ true, // PasswordCheck
+ true, // PublicKey
+ true, // SigningDescription
+ true // ExtensionRequest
};
/**
* The OID of this attribute is <code>PKCS9_OIDS[index]</code>.
*/
private int index;
-
+
/**
- * Value set of this attribute. Its class is given by
+ * Value set of this attribute. Its class is given by
* <code>VALUE_CLASSES[index]</code>.
*/
private Object value;
- /**
- * Construct an attribute object from the attribute's OID and
- * value. If the attribute is single-valued, provide only one
- * value. If the attribute is
- * multiple-valued, provide an array containing all the values.
- * Arrays of length zero are accepted, though probably useless.
- *
- * <P> The following table gives the class that <code>value</code>
- * must have for a given attribute.
- *
+ /**
+ * Construct an attribute object from the attribute's OID and value. If the
+ * attribute is single-valued, provide only one value. If the attribute is
+ * multiple-valued, provide an array containing all the values. Arrays of
+ * length zero are accepted, though probably useless.
+ *
+ * <P>
+ * The following table gives the class that <code>value</code> must have for
+ * a given attribute.
+ *
* <P>
* <TABLE BORDER CELLPADDING=8 ALIGN=CENTER>
- *
+ *
* <TR>
* <TH>OID</TH>
* <TH>Attribute Type Name</TH>
* <TH>Kind</TH>
* <TH>Value Class</TH>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.1</TD>
* <TD>EmailAddress</TD>
* <TD>Multiple-valued</TD>
* <TD><code>String[]</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.2</TD>
* <TD>UnstructuredName</TD>
* <TD>Multiple-valued</TD>
* <TD><code>String[]</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.3</TD>
* <TD>ContentType</TD>
* <TD>Single-valued</TD>
* <TD><code>ObjectIdentifier</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.4</TD>
* <TD>MessageDigest</TD>
* <TD>Single-valued</TD>
* <TD><code>byte[]</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.5</TD>
* <TD>SigningTime</TD>
* <TD>Single-valued</TD>
* <TD><code>Date</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.6</TD>
* <TD>Countersignature</TD>
* <TD>Multiple-valued</TD>
* <TD><code>SignerInfo[]</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.7</TD>
* <TD>ChallengePassword</TD>
* <TD>Single-valued</TD>
* <TD><code>String</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.8</TD>
* <TD>UnstructuredAddress</TD>
* <TD>Single-valued</TD>
* <TD><code>String[]</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.9</TD>
* <TD>ExtendedCertificateAttributes</TD>
* <TD>Multiple-valued</TD>
* <TD>(not supported)</TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.10</TD>
* <TD>IssuerAndSerialNumber</TD>
* <TD>Single-valued</TD>
* <TD>(not supported)</TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.11</TD>
* <TD>PasswordCheck</TD>
* <TD>Single-valued</TD>
* <TD>(not supported)</TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.12</TD>
* <TD>PublicKey</TD>
* <TD>Single-valued</TD>
* <TD>(not supported)</TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.13</TD>
* <TD>SigningDescription</TD>
* <TD>Single-valued</TD>
* <TD>(not supported)</TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.14</TD>
* <TD>ExtensionRequest</TD>
* <TD>Single-valued</TD>
* <TD><code>Sequence</code></TD>
* </TR>
- *
+ *
* </TABLE>
*/
- public PKCS9Attribute(ObjectIdentifier oid, Object value)
- throws IllegalArgumentException {
+ public PKCS9Attribute(ObjectIdentifier oid, Object value)
+ throws IllegalArgumentException {
- init(oid, value);
+ init(oid, value);
}
- /**
- * Construct an attribute object from the attribute's name and
- * value. If the attribute is single-valued, provide only one
- * value. If the attribute is
- * multiple-valued, provide an array containing all the values.
- * Arrays of length zero are accepted, though probably useless.
- *
- * <P> The following table gives the class that <code>value</code>
- * must have for a given attribute. Reasonable variants of these
- * attributes are accepted; in particular, case does not matter.
- *
+ /**
+ * Construct an attribute object from the attribute's name and value. If the
+ * attribute is single-valued, provide only one value. If the attribute is
+ * multiple-valued, provide an array containing all the values. Arrays of
+ * length zero are accepted, though probably useless.
+ *
+ * <P>
+ * The following table gives the class that <code>value</code> must have for
+ * a given attribute. Reasonable variants of these attributes are accepted;
+ * in particular, case does not matter.
+ *
* <P>
* <TABLE BORDER CELLPADDING=8 ALIGN=CENTER>
- *
+ *
* <TR>
* <TH>OID</TH>
* <TH>Attribute Type Name</TH>
* <TH>Kind</TH>
* <TH>Value Class</TH>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.1</TD>
* <TD>EmailAddress</TD>
* <TD>Multiple-valued</TD>
* <TD><code>String[]</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.2</TD>
* <TD>UnstructuredName</TD>
* <TD>Multiple-valued</TD>
* <TD><code>String[]</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.3</TD>
* <TD>ContentType</TD>
* <TD>Single-valued</TD>
* <TD><code>ObjectIdentifier</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.4</TD>
* <TD>MessageDigest</TD>
* <TD>Single-valued</TD>
* <TD><code>byte[]</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.5</TD>
* <TD>SigningTime</TD>
* <TD>Single-valued</TD>
* <TD><code>Date</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.6</TD>
* <TD>Countersignature</TD>
* <TD>Multiple-valued</TD>
* <TD><code>SignerInfo[]</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.7</TD>
* <TD>ChallengePassword</TD>
* <TD>Single-valued</TD>
* <TD><code>String</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.8</TD>
* <TD>UnstructuredAddress</TD>
* <TD>Single-valued</TD>
* <TD><code>String[]</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.9</TD>
* <TD>ExtendedCertificateAttributes</TD>
* <TD>Multiple-valued</TD>
* <TD>(not supported)</TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.10</TD>
* <TD>IssuerAndSerialNumber</TD>
* <TD>Single-valued</TD>
* <TD>(not supported)</TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.11</TD>
* <TD>PasswordCheck</TD>
* <TD>Single-valued</TD>
* <TD>(not supported)</TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.12</TD>
* <TD>PublicKey</TD>
* <TD>Single-valued</TD>
* <TD>(not supported)</TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.13</TD>
* <TD>SigningDescription</TD>
* <TD>Single-valued</TD>
* <TD>(not supported)</TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.14</TD>
* <TD>ExtensionRequest</TD>
* <TD>Single-valued</TD>
* <TD><code>Sequence</code></TD>
* </TR>
- *
+ *
* </TABLE>
- *
- * @exception IllegalArgumentException
- * if the <code>name</code> is not recognized of the
- * <code>value</code> has the wrong type.
+ *
+ * @exception IllegalArgumentException if the <code>name</code> is not
+ * recognized of the <code>value</code> has the wrong type.
*/
- public PKCS9Attribute(String name, Object value)
- throws IllegalArgumentException {
- ObjectIdentifier oid = getOID(name);
+ public PKCS9Attribute(String name, Object value)
+ throws IllegalArgumentException {
+ ObjectIdentifier oid = getOID(name);
- if (oid == null)
- throw new IllegalArgumentException(
- "Unrecognized attribute name " + name +
- " constructing PKCS9Attribute.");
+ if (oid == null)
+ throw new IllegalArgumentException(
+ "Unrecognized attribute name " + name +
+ " constructing PKCS9Attribute.");
- init(oid,value);
+ init(oid, value);
}
- private void init(ObjectIdentifier oid, Object value)
- throws IllegalArgumentException {
-
- index = indexOf(oid,PKCS9_OIDS,1);
-
- if (index == -1)
- throw new IllegalArgumentException(
- "Unsupported OID " + oid +
- " constructing PKCS9Attribute.");
-
- if (!VALUE_CLASSES[index].isInstance(value))
- throw new IllegalArgumentException(
- "Wrong value class " +
- " for attribute " + oid +
- " constructing PKCS9Attribute; was " +
- value.getClass().toString() + ", should be " +
- VALUE_CLASSES[index].toString());
-
- this.value = value;
- }
+ private void init(ObjectIdentifier oid, Object value)
+ throws IllegalArgumentException {
+ index = indexOf(oid, PKCS9_OIDS, 1);
- /**
- * Construct a PKCS9Attribute from its encoding on an input
- * stream.
- *
+ if (index == -1)
+ throw new IllegalArgumentException(
+ "Unsupported OID " + oid +
+ " constructing PKCS9Attribute.");
+
+ if (!VALUE_CLASSES[index].isInstance(value))
+ throw new IllegalArgumentException(
+ "Wrong value class " +
+ " for attribute " + oid +
+ " constructing PKCS9Attribute; was " +
+ value.getClass().toString() + ", should be " +
+ VALUE_CLASSES[index].toString());
+
+ this.value = value;
+ }
+
+ /**
+ * Construct a PKCS9Attribute from its encoding on an input stream.
+ *
* @exception IOException on parsing error.
*/
public PKCS9Attribute(DerValue derVal) throws IOException {
- decode(derVal);
+ decode(derVal);
}
/**
* Decode a PKCS9 attribute.
- *
- * @param val
- * the DerValue representing the DER encoding of the attribute.
+ *
+ * @param val the DerValue representing the DER encoding of the attribute.
*/
private void decode(DerValue derVal) throws IOException {
- DerInputStream derIn = new DerInputStream(derVal.toByteArray());
- DerValue[] val = derIn.getSequence(2);
-
- if (derIn.available() != 0)
- throw new IOException("Excess data parsing PKCS9Attribute");
-
- if (val.length != 2)
- throw new IOException("PKCS9Attribute doesn't have two components");
-
- DerValue[] elems;
-
- // get the oid
- ObjectIdentifier oid = val[0].getOID();
-
- index = indexOf(oid,PKCS9_OIDS,1);
- Byte tag;
-
- if (index == -1)
- throw new IOException("Invalid OID for PKCS9 attribute: " +
- oid);
-
- elems = new DerInputStream(val[1].toByteArray()).getSet(1);
-
- // check single valued have only one value
- if (SINGLE_VALUED[index] && elems.length > 1)
- throwSingleValuedException();
-
- // check for illegal element tags
- for (int i=0; i < elems.length; i++) {
- tag = Byte.valueOf(elems[i].tag);
-
- if (indexOf(tag, PKCS9_VALUE_TAGS[index], 0) == -1)
- throwTagException(tag);
- }
-
- switch (index) {
- case 1: // email address
- case 2: // unstructured name
- case 8: // unstructured address
- { // open scope
- String[] values = new String[elems.length];
-
- for (int i=0; i < elems.length; i++)
- values[i] = elems[i].getAsString();
- value = values;
- } // close scope
- break;
-
- case 3: // content type
- value = elems[0].getOID();
- break;
-
- case 4: // message digest
- value = elems[0].getOctetString();
- break;
-
- case 5: // signing time
- value = (new DerInputStream(elems[0].toByteArray())).getUTCTime();
- break;
-
- case 6: // countersignature
- { // open scope
- SignerInfo[] values = new SignerInfo[elems.length];
- for (int i=0; i < elems.length; i++)
- values[i] =
- new SignerInfo(elems[i].toDerInputStream());
- value = values;
- } // close scope
- break;
-
- case 7: // challenge password
- value = elems[0].getAsString();
- break;
-
- case 9: // extended-certificate attribute -- not
- // supported
- throw new IOException("PKCS9 extended-certificate " +
- "attribute not supported.");
-
- case 10: // IssuerAndSerialNumber attribute -- not
- // supported
- throw new IOException("PKCS9 IssuerAndSerialNumber " +
- "attribute not supported.");
-
- case 11: // passwordCheck attribute -- not
- // supported
- throw new IOException("PKCS9 passwordCheck " +
- "attribute not supported.");
- case 12: // PublicKey attribute -- not
- // supported
- throw new IOException("PKCS9 PublicKey " +
- "attribute not supported.");
- case 13: // SigningDescription attribute -- not
- // supported
- throw new IOException("PKCS9 SigningDescription " +
- "attribute not supported.");
- case 14: // ExtensionRequest attribute
- value =
- new CertificateExtensions(elems[0].toDerInputStream());
-
- // break unnecessary
-
- default: // can't happen
- }
+ DerInputStream derIn = new DerInputStream(derVal.toByteArray());
+ DerValue[] val = derIn.getSequence(2);
+
+ if (derIn.available() != 0)
+ throw new IOException("Excess data parsing PKCS9Attribute");
+
+ if (val.length != 2)
+ throw new IOException("PKCS9Attribute doesn't have two components");
+
+ DerValue[] elems;
+
+ // get the oid
+ ObjectIdentifier oid = val[0].getOID();
+
+ index = indexOf(oid, PKCS9_OIDS, 1);
+ Byte tag;
+
+ if (index == -1)
+ throw new IOException("Invalid OID for PKCS9 attribute: " +
+ oid);
+
+ elems = new DerInputStream(val[1].toByteArray()).getSet(1);
+
+ // check single valued have only one value
+ if (SINGLE_VALUED[index] && elems.length > 1)
+ throwSingleValuedException();
+
+ // check for illegal element tags
+ for (int i = 0; i < elems.length; i++) {
+ tag = Byte.valueOf(elems[i].tag);
+
+ if (indexOf(tag, PKCS9_VALUE_TAGS[index], 0) == -1)
+ throwTagException(tag);
+ }
+
+ switch (index) {
+ case 1: // email address
+ case 2: // unstructured name
+ case 8: // unstructured address
+ { // open scope
+ String[] values = new String[elems.length];
+
+ for (int i = 0; i < elems.length; i++)
+ values[i] = elems[i].getAsString();
+ value = values;
+ } // close scope
+ break;
+
+ case 3: // content type
+ value = elems[0].getOID();
+ break;
+
+ case 4: // message digest
+ value = elems[0].getOctetString();
+ break;
+
+ case 5: // signing time
+ value = (new DerInputStream(elems[0].toByteArray())).getUTCTime();
+ break;
+
+ case 6: // countersignature
+ { // open scope
+ SignerInfo[] values = new SignerInfo[elems.length];
+ for (int i = 0; i < elems.length; i++)
+ values[i] =
+ new SignerInfo(elems[i].toDerInputStream());
+ value = values;
+ } // close scope
+ break;
+
+ case 7: // challenge password
+ value = elems[0].getAsString();
+ break;
+
+ case 9: // extended-certificate attribute -- not
+ // supported
+ throw new IOException("PKCS9 extended-certificate " +
+ "attribute not supported.");
+
+ case 10: // IssuerAndSerialNumber attribute -- not
+ // supported
+ throw new IOException("PKCS9 IssuerAndSerialNumber " +
+ "attribute not supported.");
+
+ case 11: // passwordCheck attribute -- not
+ // supported
+ throw new IOException("PKCS9 passwordCheck " +
+ "attribute not supported.");
+ case 12: // PublicKey attribute -- not
+ // supported
+ throw new IOException("PKCS9 PublicKey " +
+ "attribute not supported.");
+ case 13: // SigningDescription attribute -- not
+ // supported
+ throw new IOException("PKCS9 SigningDescription " +
+ "attribute not supported.");
+ case 14: // ExtensionRequest attribute
+ value =
+ new CertificateExtensions(elems[0].toDerInputStream());
+
+ // break unnecessary
+
+ default: // can't happen
+ }
}
/**
* Write the DER encoding of this attribute to an output stream.
*
- * <P> N.B.: This method always encodes values of
- * ChallengePassword and UnstructuredAddress attributes as ASN.1
- * <code>PrintableString</code>s, without checking whether they
- * should be encoded as <code>T61String</code>s.
+ * <P>
+ * N.B.: This method always encodes values of ChallengePassword and
+ * UnstructuredAddress attributes as ASN.1 <code>PrintableString</code>s,
+ * without checking whether they should be encoded as <code>T61String</code>
+ * s.
*/
public void derEncode(OutputStream out) throws IOException {
- DerOutputStream temp = new DerOutputStream();
- temp.putOID(getOID());
- switch (index) {
- case 1: // email address
- case 2: // unstructured name
- { // open scope
- String[] values = (String[]) value;
- DerOutputStream[] temps = new
- DerOutputStream[values.length];
-
- for (int i=0; i < values.length; i++) {
- temps[i] = new DerOutputStream();
-
- temps[i].putIA5String( values[i]);
- }
- temp.putOrderedSetOf(DerValue.tag_Set, temps);
- } // close scope
- break;
-
- case 3: // content type
- {
- DerOutputStream temp2 = new DerOutputStream();
- temp2.putOID((ObjectIdentifier) value);
- temp.write(DerValue.tag_Set, temp2.toByteArray());
- }
- break;
-
- case 4: // message digest
- {
- DerOutputStream temp2 = new DerOutputStream();
- temp2.putOctetString((byte[]) value);
- temp.write(DerValue.tag_Set, temp2.toByteArray());
- }
- break;
-
- case 5: // signing time
- {
- DerOutputStream temp2 = new DerOutputStream();
- temp2.putUTCTime((Date) value);
- temp.write(DerValue.tag_Set, temp2.toByteArray());
- }
- break;
-
- case 6: // countersignature
- temp.putOrderedSetOf(DerValue.tag_Set, (DerEncoder[]) value);
- break;
-
- case 7: // challenge password
- {
- DerOutputStream temp2 = new DerOutputStream();
- temp2.putPrintableString((String) value);
- temp.write(DerValue.tag_Set, temp2.toByteArray());
- }
- break;
-
- case 8: // unstructured address
- { // open scope
- String[] values = (String[]) value;
- DerOutputStream[] temps = new
- DerOutputStream[values.length];
-
- for (int i=0; i < values.length; i++) {
- temps[i] = new DerOutputStream();
-
- temps[i].putPrintableString(values[i]);
- }
- temp.putOrderedSetOf(DerValue.tag_Set, temps);
- } // close scope
- break;
-
- case 9: // extended-certificate attribute -- not
- // supported
- throw new IOException("PKCS9 extended-certificate " +
- "attribute not supported.");
-
- case 10: // IssuerAndSerialNumber attribute -- not
- // supported
- throw new IOException("PKCS9 IssuerAndSerialNumber " +
- "attribute not supported.");
-
- case 11: // passwordCheck attribute -- not
- // supported
- throw new IOException("PKCS9 passwordCheck " +
- "attribute not supported.");
- case 12: // PublicKey attribute -- not
- // supported
- throw new IOException("PKCS9 PublicKey " +
- "attribute not supported.");
- case 13: // SigningDescription attribute -- not
- // supported
- throw new IOException("PKCS9 SigningDescription " +
- "attribute not supported.");
- case 14: // ExtensionRequest attribute
- try {
- DerOutputStream temp2 = new DerOutputStream();
- //temp2.putSequence((CertificateExtensions) value);
- ((CertificateExtensions)value).encode(temp2);
- temp.write(DerValue.tag_Sequence, temp2.toByteArray());
- } catch (CertificateException e) {
- throw new IOException("PKCS9 extension attributes not encoded");
- }
-
- // break unnecessary
- default: // can't happen
- }
-
- DerOutputStream derOut = new DerOutputStream();
- derOut.write(DerValue.tag_Sequence, temp.toByteArray());
-
- out.write(derOut.toByteArray());
-
+ DerOutputStream temp = new DerOutputStream();
+ temp.putOID(getOID());
+ switch (index) {
+ case 1: // email address
+ case 2: // unstructured name
+ { // open scope
+ String[] values = (String[]) value;
+ DerOutputStream[] temps = new
+ DerOutputStream[values.length];
+
+ for (int i = 0; i < values.length; i++) {
+ temps[i] = new DerOutputStream();
+
+ temps[i].putIA5String(values[i]);
+ }
+ temp.putOrderedSetOf(DerValue.tag_Set, temps);
+ } // close scope
+ break;
+
+ case 3: // content type
+ {
+ DerOutputStream temp2 = new DerOutputStream();
+ temp2.putOID((ObjectIdentifier) value);
+ temp.write(DerValue.tag_Set, temp2.toByteArray());
+ }
+ break;
+
+ case 4: // message digest
+ {
+ DerOutputStream temp2 = new DerOutputStream();
+ temp2.putOctetString((byte[]) value);
+ temp.write(DerValue.tag_Set, temp2.toByteArray());
+ }
+ break;
+
+ case 5: // signing time
+ {
+ DerOutputStream temp2 = new DerOutputStream();
+ temp2.putUTCTime((Date) value);
+ temp.write(DerValue.tag_Set, temp2.toByteArray());
+ }
+ break;
+
+ case 6: // countersignature
+ temp.putOrderedSetOf(DerValue.tag_Set, (DerEncoder[]) value);
+ break;
+
+ case 7: // challenge password
+ {
+ DerOutputStream temp2 = new DerOutputStream();
+ temp2.putPrintableString((String) value);
+ temp.write(DerValue.tag_Set, temp2.toByteArray());
+ }
+ break;
+
+ case 8: // unstructured address
+ { // open scope
+ String[] values = (String[]) value;
+ DerOutputStream[] temps = new
+ DerOutputStream[values.length];
+
+ for (int i = 0; i < values.length; i++) {
+ temps[i] = new DerOutputStream();
+
+ temps[i].putPrintableString(values[i]);
+ }
+ temp.putOrderedSetOf(DerValue.tag_Set, temps);
+ } // close scope
+ break;
+
+ case 9: // extended-certificate attribute -- not
+ // supported
+ throw new IOException("PKCS9 extended-certificate " +
+ "attribute not supported.");
+
+ case 10: // IssuerAndSerialNumber attribute -- not
+ // supported
+ throw new IOException("PKCS9 IssuerAndSerialNumber " +
+ "attribute not supported.");
+
+ case 11: // passwordCheck attribute -- not
+ // supported
+ throw new IOException("PKCS9 passwordCheck " +
+ "attribute not supported.");
+ case 12: // PublicKey attribute -- not
+ // supported
+ throw new IOException("PKCS9 PublicKey " +
+ "attribute not supported.");
+ case 13: // SigningDescription attribute -- not
+ // supported
+ throw new IOException("PKCS9 SigningDescription " +
+ "attribute not supported.");
+ case 14: // ExtensionRequest attribute
+ try {
+ DerOutputStream temp2 = new DerOutputStream();
+ // temp2.putSequence((CertificateExtensions) value);
+ ((CertificateExtensions) value).encode(temp2);
+ temp.write(DerValue.tag_Sequence, temp2.toByteArray());
+ } catch (CertificateException e) {
+ throw new IOException("PKCS9 extension attributes not encoded");
+ }
+
+ // break unnecessary
+ default: // can't happen
+ }
+
+ DerOutputStream derOut = new DerOutputStream();
+ derOut.write(DerValue.tag_Sequence, temp.toByteArray());
+
+ out.write(derOut.toByteArray());
+
}
/**
- * Get the value of this attribute. If the attribute is
- * single-valued, return just the one value. If the attribute is
- * multiple-valued, return an array containing all the values.
- * It is possible for this array to be of length 0.
- *
- * <P> The following table gives the class of the value returned,
- * depending on the type of this attribute.
-
+ * Get the value of this attribute. If the attribute is single-valued,
+ * return just the one value. If the attribute is multiple-valued, return an
+ * array containing all the values. It is possible for this array to be of
+ * length 0.
+ *
+ * <P>
+ * The following table gives the class of the value returned, depending on
+ * the type of this attribute.
+ *
* <P>
* <TABLE BORDER CELLPADDING=8 ALIGN=CENTER>
- *
+ *
* <TR>
* <TH>OID</TH>
* <TH>Attribute Type Name</TH>
* <TH>Kind</TH>
* <TH>Value Class</TH>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.1</TD>
* <TD>EmailAddress</TD>
* <TD>Multiple-valued</TD>
* <TD><code>String[]</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.2</TD>
* <TD>UnstructuredName</TD>
* <TD>Multiple-valued</TD>
* <TD><code>String[]</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.3</TD>
* <TD>ContentType</TD>
* <TD>Single-valued</TD>
* <TD><code>ObjectIdentifier</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.4</TD>
* <TD>MessageDigest</TD>
* <TD>Single-valued</TD>
* <TD><code>byte[]</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.5</TD>
* <TD>SigningTime</TD>
* <TD>Single-valued</TD>
* <TD><code>Date</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.6</TD>
* <TD>Countersignature</TD>
* <TD>Multiple-valued</TD>
* <TD><code>SignerInfo[]</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.7</TD>
* <TD>ChallengePassword</TD>
* <TD>Single-valued</TD>
* <TD><code>String</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.8</TD>
* <TD>UnstructuredAddress</TD>
* <TD>Single-valued</TD>
* <TD><code>String[]</code></TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.9</TD>
* <TD>ExtendedCertificateAttributes</TD>
* <TD>Multiple-valued</TD>
* <TD>(not supported)</TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.10</TD>
* <TD>IssuerAndSerialNumber</TD>
* <TD>Single-valued</TD>
* <TD>(not supported)</TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.11</TD>
* <TD>PasswordCheck</TD>
* <TD>Single-valued</TD>
* <TD>(not supported)</TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.12</TD>
* <TD>PublicKey</TD>
* <TD>Single-valued</TD>
* <TD>(not supported)</TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.13</TD>
* <TD>SigningDescription</TD>
* <TD>Single-valued</TD>
* <TD>(not supported)</TD>
* </TR>
- *
+ *
* <TR>
* <TD>1.2.840.113549.1.9.14</TD>
* <TD>ExtensionRequest</TD>
* <TD>Single-valued</TD>
* <TD><code>Sequence</code></TD>
* </TR>
- *
+ *
* </TABLE>
- *
+ *
*/
public Object getValue() {
- return value;
+ return value;
}
- /**
+ /**
* Show whether this attribute is single-valued.
*/
public boolean isSingleValued() {
- return SINGLE_VALUED[index];
+ return SINGLE_VALUED[index];
}
- /**
- * Return the OID of this attribute.
+ /**
+ * Return the OID of this attribute.
*/
public ObjectIdentifier getOID() {
- return PKCS9_OIDS[index];
+ return PKCS9_OIDS[index];
}
- /**
- * Return the name of this attribute.
+ /**
+ * Return the name of this attribute.
*/
public String getName() {
- return (String) OID_NAME_TABLE.get(PKCS9_OIDS[index]);
+ return (String) OID_NAME_TABLE.get(PKCS9_OIDS[index]);
}
- /**
+ /**
* Return the OID for a given attribute name or null if we don't recognize
* the name.
*/
public static ObjectIdentifier getOID(String name) {
- return (ObjectIdentifier) NAME_OID_TABLE.get(name.toLowerCase());
+ return (ObjectIdentifier) NAME_OID_TABLE.get(name.toLowerCase());
}
- /**
+ /**
* Return the attribute name for a given OID or null if we don't recognize
* the oid.
*/
public static String getName(ObjectIdentifier oid) {
- return (String) OID_NAME_TABLE.get(oid);
+ return (String) OID_NAME_TABLE.get(oid);
}
- /**
+ /**
* Returns a string representation of this attribute.
*/
public String toString() {
- StringBuffer buf = new StringBuffer(100);
-
- buf.append("[");
-
- buf.append(OID_NAME_TABLE.get(PKCS9_OIDS[index]));
- buf.append(": ");
-
- if (SINGLE_VALUED[index]) {
- if (value instanceof byte[]) { // special case for octet string
- netscape.security.util.PrettyPrintFormat pp =
- new netscape.security.util.PrettyPrintFormat(" ", 20);
- String valuebits = pp.toHexString(((byte[])value));
- buf.append(valuebits);
- } else {
- buf.append(value.toString());
- }
- buf.append("]");
- return buf.toString();
- } else { // multiple-valued
- boolean first = true;
- Object[] values = (Object[]) value;
-
- for (int j=0; j < values.length; j++) {
- if (first)
- first = false;
- else
- buf.append(", ");
-
- buf.append(values[j].toString());
- }
- return buf.toString();
- }
+ StringBuffer buf = new StringBuffer(100);
+
+ buf.append("[");
+
+ buf.append(OID_NAME_TABLE.get(PKCS9_OIDS[index]));
+ buf.append(": ");
+
+ if (SINGLE_VALUED[index]) {
+ if (value instanceof byte[]) { // special case for octet string
+ netscape.security.util.PrettyPrintFormat pp =
+ new netscape.security.util.PrettyPrintFormat(" ", 20);
+ String valuebits = pp.toHexString(((byte[]) value));
+ buf.append(valuebits);
+ } else {
+ buf.append(value.toString());
+ }
+ buf.append("]");
+ return buf.toString();
+ } else { // multiple-valued
+ boolean first = true;
+ Object[] values = (Object[]) value;
+
+ for (int j = 0; j < values.length; j++) {
+ if (first)
+ first = false;
+ else
+ buf.append(", ");
+
+ buf.append(values[j].toString());
+ }
+ return buf.toString();
+ }
}
- /**
- * Beginning the search at <code>start</code>, find the first
- * index <code>i</code> such that <code>a[i] = obj</code>.
- *
+ /**
+ * Beginning the search at <code>start</code>, find the first index
+ * <code>i</code> such that <code>a[i] = obj</code>.
+ *
* @return the index, if found, and -1 otherwise.
*/
static int indexOf(Object obj, Object[] a, int start) {
- for (int i=start; i < a.length; i++) {
- if (obj.equals(a[i])) return i;
- }
- return -1;
+ for (int i = start; i < a.length; i++) {
+ if (obj.equals(a[i]))
+ return i;
+ }
+ return -1;
}
- /**
- * Throw an exception when there are multiple values for
- * a single-valued attribute.
+ /**
+ * Throw an exception when there are multiple values for a single-valued
+ * attribute.
*/
private void throwSingleValuedException() throws IOException {
- throw new IOException("Single-value attribute " +
- getOID() + " (" + getName() + ")" +
- " has multiple values.");
+ throw new IOException("Single-value attribute " +
+ getOID() + " (" + getName() + ")" +
+ " has multiple values.");
}
- /**
- * Throw an exception when the tag on a value encoding is
- * wrong for the attribute whose value it is.
+ /**
+ * Throw an exception when the tag on a value encoding is wrong for the
+ * attribute whose value it is.
*/
private void throwTagException(Byte tag)
- throws IOException {
- Byte[] expectedTags = PKCS9_VALUE_TAGS[index];
- StringBuffer msg = new StringBuffer(100);
+ throws IOException {
+ Byte[] expectedTags = PKCS9_VALUE_TAGS[index];
+ StringBuffer msg = new StringBuffer(100);
msg.append("Value of attribute ");
- msg.append(getOID().toString());
- msg.append(" (");
- msg.append(getName());
- msg.append(") has wrong tag: ");
- msg.append(tag.toString());
- msg.append(". Expected tags: ");
-
- msg.append(expectedTags[0].toString());
-
- for (int i = 1; i < expectedTags.length; i++) {
- msg.append(", ");
- msg.append(expectedTags[i].toString());
- }
- msg.append(".");
- throw new IOException(msg.toString());
+ msg.append(getOID().toString());
+ msg.append(" (");
+ msg.append(getName());
+ msg.append(") has wrong tag: ");
+ msg.append(tag.toString());
+ msg.append(". Expected tags: ");
+
+ msg.append(expectedTags[0].toString());
+
+ for (int i = 1; i < expectedTags.length; i++) {
+ msg.append(", ");
+ msg.append(expectedTags[i].toString());
+ }
+ msg.append(".");
+ throw new IOException(msg.toString());
}
}
diff --git a/pki/base/util/src/netscape/security/pkcs/PKCS9Attributes.java b/pki/base/util/src/netscape/security/pkcs/PKCS9Attributes.java
index aff0ee0f..f8f97aaa 100644
--- a/pki/base/util/src/netscape/security/pkcs/PKCS9Attributes.java
+++ b/pki/base/util/src/netscape/security/pkcs/PKCS9Attributes.java
@@ -27,180 +27,168 @@ import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
import netscape.security.util.ObjectIdentifier;
-
/**
- * A set of attributes of class PKCS9Attribute.
- *
+ * A set of attributes of class PKCS9Attribute.
+ *
* @version 1.2 97/12/10
* @author Douglas Hoover
*/
public class PKCS9Attributes {
/**
- * Attributes in this set indexed by OID.
+ * Attributes in this set indexed by OID.
*/
private final Hashtable attributes = new Hashtable(3);
/**
- * The keys of this hashtable are the OIDs of permitted attributes.
+ * The keys of this hashtable are the OIDs of permitted attributes.
*/
private final Hashtable permittedAttributes;
/**
- * The DER encoding of this attribute set. The tag byte must be
+ * The DER encoding of this attribute set. The tag byte must be
* DerValue.tag_SetOf.
- */
+ */
private final byte[] derEncoding;
/**
- * Construct a set of PKCS9 Attributes from its
- * DER encoding on a DerInputStream, accepting only attributes
- * with OIDs on the given
- * list. If the array is null, accept all attributes supported by
- * class PKCS9Attribute.
- *
- * @param permittedAttributes
- * Array of attribute OIDs that will be accepted.
- * @param buf
- * the contents of the DER encoding of the attribute set.
- *
- * @exception IOException
- * on i/o error, encoding syntax error, unacceptable or
- * unsupported attribute, or duplicate attribute.
- *
+ * Construct a set of PKCS9 Attributes from its DER encoding on a
+ * DerInputStream, accepting only attributes with OIDs on the given list. If
+ * the array is null, accept all attributes supported by class
+ * PKCS9Attribute.
+ *
+ * @param permittedAttributes Array of attribute OIDs that will be accepted.
+ * @param buf the contents of the DER encoding of the attribute set.
+ *
+ * @exception IOException on i/o error, encoding syntax error, unacceptable
+ * or unsupported attribute, or duplicate attribute.
+ *
* @see PKCS9Attribute
*/
public PKCS9Attributes(ObjectIdentifier[] permittedAttributes,
- DerInputStream in) throws IOException {
- if (permittedAttributes != null) {
- this.permittedAttributes =
- new Hashtable(permittedAttributes.length);
-
- for (int i = 0; i < permittedAttributes.length; i++)
- this.permittedAttributes.put(permittedAttributes[i],
- permittedAttributes[i]);
- } else {
- this.permittedAttributes = null;
- }
-
- // derEncoding initialized in <code>decode()</code>
- derEncoding = decode(in);
+ DerInputStream in) throws IOException {
+ if (permittedAttributes != null) {
+ this.permittedAttributes =
+ new Hashtable(permittedAttributes.length);
+
+ for (int i = 0; i < permittedAttributes.length; i++)
+ this.permittedAttributes.put(permittedAttributes[i],
+ permittedAttributes[i]);
+ } else {
+ this.permittedAttributes = null;
+ }
+
+ // derEncoding initialized in <code>decode()</code>
+ derEncoding = decode(in);
}
/**
- * Construct a set of PKCS9 Attributes from its contents of its
- * DER encoding on a DerInputStream. Accept all attributes
- * supported by class PKCS9Attribute.
- *
- * @exception IOException
- * on i/o error, encoding syntax error, or unsupported or
- * duplicate attribute.
- *
+ * Construct a set of PKCS9 Attributes from its contents of its DER encoding
+ * on a DerInputStream. Accept all attributes supported by class
+ * PKCS9Attribute.
+ *
+ * @exception IOException on i/o error, encoding syntax error, or
+ * unsupported or duplicate attribute.
+ *
* @see PKCS9Attribute
*/
public PKCS9Attributes(DerInputStream in) throws IOException {
- // anything goes
- // derEncoding initialized in <code>decode()</code>
- derEncoding = decode(in);
- permittedAttributes = null;
+ // anything goes
+ // derEncoding initialized in <code>decode()</code>
+ derEncoding = decode(in);
+ permittedAttributes = null;
}
/**
- * Construct a set of PKCS9 Attributes from the given array of
- * PCK9 attributes.
- * DER encoding on a DerInputStream. All attributes in
- * <code>attribs</code> must be
- * supported by class PKCS9Attribute.
- *
- * @exception IOException
- * on i/o error, encoding syntax error, or unsupported or
- * duplicate attribute.
- *
+ * Construct a set of PKCS9 Attributes from the given array of PCK9
+ * attributes. DER encoding on a DerInputStream. All attributes in
+ * <code>attribs</code> must be supported by class PKCS9Attribute.
+ *
+ * @exception IOException on i/o error, encoding syntax error, or
+ * unsupported or duplicate attribute.
+ *
* @see PKCS9Attribute
*/
- public PKCS9Attributes(PKCS9Attribute[] attribs)
- throws IllegalArgumentException, IOException {
- ObjectIdentifier oid;
- for (int i=0; i < attribs.length; i++) {
- oid = attribs[i].getOID();
- if (attributes.containsKey(oid))
- throw new IllegalArgumentException(
- "PKCSAttribute " + attribs[i].getOID() +
- " duplicated while constructing " +
- "PKCS9Attributes.");
-
- attributes.put(oid, attribs[i]);
- }
- derEncoding = generateDerEncoding();
- permittedAttributes = null;
+ public PKCS9Attributes(PKCS9Attribute[] attribs)
+ throws IllegalArgumentException, IOException {
+ ObjectIdentifier oid;
+ for (int i = 0; i < attribs.length; i++) {
+ oid = attribs[i].getOID();
+ if (attributes.containsKey(oid))
+ throw new IllegalArgumentException(
+ "PKCSAttribute " + attribs[i].getOID() +
+ " duplicated while constructing " +
+ "PKCS9Attributes.");
+
+ attributes.put(oid, attribs[i]);
+ }
+ derEncoding = generateDerEncoding();
+ permittedAttributes = null;
}
-
/**
- * Decode this set of PKCS9 attribute set from the contents of its
- * DER encoding.
- *
- * @param buf
- * the contents of the DER encoding of the attribute set.
- *
- * @exception IOException
- * on i/o error, encoding syntax error, unacceptable or
- * unsupported attribute, or duplicate attribute.
+ * Decode this set of PKCS9 attribute set from the contents of its DER
+ * encoding.
+ *
+ * @param buf the contents of the DER encoding of the attribute set.
+ *
+ * @exception IOException on i/o error, encoding syntax error, unacceptable
+ * or unsupported attribute, or duplicate attribute.
*/
private byte[] decode(DerInputStream in) throws IOException {
- DerValue val = in.getDerValue();
+ DerValue val = in.getDerValue();
- // save the DER encoding with its proper tag byte.
- byte[] derEncoding = val.toByteArray();
- derEncoding[0] = DerValue.tag_SetOf;
+ // save the DER encoding with its proper tag byte.
+ byte[] derEncoding = val.toByteArray();
+ derEncoding[0] = DerValue.tag_SetOf;
- DerInputStream derIn = new DerInputStream(derEncoding);
- DerValue[] derVals = derIn.getSet(3,true);
+ DerInputStream derIn = new DerInputStream(derEncoding);
+ DerValue[] derVals = derIn.getSet(3, true);
- PKCS9Attribute attrib;
- ObjectIdentifier oid;
- int index;
+ PKCS9Attribute attrib;
+ ObjectIdentifier oid;
+ int index;
- for (int i=0; i < derVals.length; i++) {
- attrib = new PKCS9Attribute(derVals[i]);
- oid = attrib.getOID();
+ for (int i = 0; i < derVals.length; i++) {
+ attrib = new PKCS9Attribute(derVals[i]);
+ oid = attrib.getOID();
- if (attributes.get(oid) != null)
- throw new IOException("Duplicate PKCS9 attribute: " + oid);
+ if (attributes.get(oid) != null)
+ throw new IOException("Duplicate PKCS9 attribute: " + oid);
- if (permittedAttributes != null &&
- !permittedAttributes.containsKey(oid))
- throw new IOException("Attribute " + oid +
- " not permitted in this attribute set");
-
- attributes.put(oid,attrib);
- }
- return derEncoding;
+ if (permittedAttributes != null &&
+ !permittedAttributes.containsKey(oid))
+ throw new IOException("Attribute " + oid +
+ " not permitted in this attribute set");
+
+ attributes.put(oid, attrib);
+ }
+ return derEncoding;
}
/**
- * Put the DER encoding of this PKCS9 attribute set on an
- * DerOutputStream, tagged with the given implicit tag.
- *
+ * Put the DER encoding of this PKCS9 attribute set on an DerOutputStream,
+ * tagged with the given implicit tag.
+ *
* @param tag the implicit tag to use in the DER encoding.
* @param out the output stream on which to put the DER encoding.
- *
- * @exception IOException on output error.
+ *
+ * @exception IOException on output error.
*/
public void encode(byte tag, OutputStream out) throws IOException {
- out.write(tag);
- out.write(derEncoding, 1, derEncoding.length -1);
+ out.write(tag);
+ out.write(derEncoding, 1, derEncoding.length - 1);
}
private byte[] generateDerEncoding() throws IOException {
- DerOutputStream out = new DerOutputStream();
- Object[] attribVals = attributes.values().toArray();
-
- out.putOrderedSetOf(DerValue.tag_SetOf,
- castToDerEncoder(attribVals));
- return out.toByteArray();
+ DerOutputStream out = new DerOutputStream();
+ Object[] attribVals = attributes.values().toArray();
+
+ out.putOrderedSetOf(DerValue.tag_SetOf,
+ castToDerEncoder(attribVals));
+ return out.toByteArray();
}
/**
@@ -208,113 +196,112 @@ public class PKCS9Attributes {
* DerValue.tag_SetOf.
*/
public byte[] getDerEncoding() throws IOException {
- return (byte[]) derEncoding.clone();
-
+ return (byte[]) derEncoding.clone();
+
}
/**
* Get an attribute from this set.
- */
+ */
public PKCS9Attribute getAttribute(ObjectIdentifier oid) {
- return (PKCS9Attribute) attributes.get(oid);
+ return (PKCS9Attribute) attributes.get(oid);
}
/**
* Get an attribute from this set.
- */
+ */
public PKCS9Attribute getAttribute(String name) {
- return (PKCS9Attribute) attributes.get(PKCS9Attribute.getOID(name));
+ return (PKCS9Attribute) attributes.get(PKCS9Attribute.getOID(name));
}
-
/**
* Get an array of all attributes in this set, in order of OID.
- */
+ */
public PKCS9Attribute[] getAttributes() {
- PKCS9Attribute[] attribs = new PKCS9Attribute[attributes.size()];
- ObjectIdentifier oid;
-
- int j = 0;
- for (int i=1; i < PKCS9Attribute.PKCS9_OIDS.length &&
- j < attribs.length; i++) {
- attribs[j] = getAttribute(PKCS9Attribute.PKCS9_OIDS[i]);
-
- if (attribs[j] != null)
- j++;
- }
- return attribs;
+ PKCS9Attribute[] attribs = new PKCS9Attribute[attributes.size()];
+ ObjectIdentifier oid;
+
+ int j = 0;
+ for (int i = 1; i < PKCS9Attribute.PKCS9_OIDS.length &&
+ j < attribs.length; i++) {
+ attribs[j] = getAttribute(PKCS9Attribute.PKCS9_OIDS[i]);
+
+ if (attribs[j] != null)
+ j++;
+ }
+ return attribs;
}
/**
* Get an attribute value by OID.
*/
- public Object getAttributeValue(ObjectIdentifier oid)
- throws IOException {
- try {
- Object value = getAttribute(oid).getValue();
- return value;
- } catch (NullPointerException ex) {
- throw new IOException("No value found for attribute " + oid);
- }
+ public Object getAttributeValue(ObjectIdentifier oid)
+ throws IOException {
+ try {
+ Object value = getAttribute(oid).getValue();
+ return value;
+ } catch (NullPointerException ex) {
+ throw new IOException("No value found for attribute " + oid);
+ }
}
- /**
- * Get an attribute value by type name.
+ /**
+ * Get an attribute value by type name.
*/
- public Object getAttributeValue(String name) throws IOException {
- ObjectIdentifier oid = PKCS9Attribute.getOID(name);
+ public Object getAttributeValue(String name) throws IOException {
+ ObjectIdentifier oid = PKCS9Attribute.getOID(name);
- if (oid == null)
- throw new IOException("Attribute name " + name +
- " not recognized or not supported.");
-
- return getAttributeValue(oid);
- }
+ if (oid == null)
+ throw new IOException("Attribute name " + name +
+ " not recognized or not supported.");
+ return getAttributeValue(oid);
+ }
- /**
+ /**
* Returns the PKCS9 block in a printable string form.
*/
public String toString() {
- StringBuffer buf = new StringBuffer(200);
- buf.append("PKCS9 Attributes: [\n\t");
-
- ObjectIdentifier oid;
- PKCS9Attribute value;
+ StringBuffer buf = new StringBuffer(200);
+ buf.append("PKCS9 Attributes: [\n\t");
+
+ ObjectIdentifier oid;
+ PKCS9Attribute value;
- boolean first = true;
- for (int i = 1; i < PKCS9Attribute.PKCS9_OIDS.length; i++) {
- value = getAttribute(PKCS9Attribute.PKCS9_OIDS[i]);
+ boolean first = true;
+ for (int i = 1; i < PKCS9Attribute.PKCS9_OIDS.length; i++) {
+ value = getAttribute(PKCS9Attribute.PKCS9_OIDS[i]);
- if (value == null) continue;
+ if (value == null)
+ continue;
- // we have a value; print it
- if (first)
- first = false;
- else
- buf.append(";\n\t");
+ // we have a value; print it
+ if (first)
+ first = false;
+ else
+ buf.append(";\n\t");
- buf.append(value.toString());
- }
+ buf.append(value.toString());
+ }
- buf.append("\n\t] (end PKCS9 Attributes)");
+ buf.append("\n\t] (end PKCS9 Attributes)");
- return buf.toString();
+ return buf.toString();
}
-
- /**
- * Cast an object array whose components are
- * <code>DerEncoder</code>s to <code>DerEncoder[]</code>.
+
+ /**
+ * Cast an object array whose components are <code>DerEncoder</code>s to
+ * <code>DerEncoder[]</code>.
*/
static DerEncoder[] castToDerEncoder(Object[] objs) {
- DerEncoder[] encoders = new DerEncoder[objs.length];
+ DerEncoder[] encoders = new DerEncoder[objs.length];
- for (int i=0; i < encoders.length; i++)
- encoders[i] = (DerEncoder) objs[i];
+ for (int i = 0; i < encoders.length; i++)
+ encoders[i] = (DerEncoder) objs[i];
- return encoders;
+ return encoders;
}
}
diff --git a/pki/base/util/src/netscape/security/pkcs/ParsingException.java b/pki/base/util/src/netscape/security/pkcs/ParsingException.java
index 64f67570..88e91a8d 100644
--- a/pki/base/util/src/netscape/security/pkcs/ParsingException.java
+++ b/pki/base/util/src/netscape/security/pkcs/ParsingException.java
@@ -26,10 +26,10 @@ public class ParsingException extends IOException {
private static final long serialVersionUID = -8135726194372647410L;
public ParsingException() {
- super();
+ super();
}
public ParsingException(String s) {
- super(s);
+ super(s);
}
}
diff --git a/pki/base/util/src/netscape/security/pkcs/SignerInfo.java b/pki/base/util/src/netscape/security/pkcs/SignerInfo.java
index d02fb03d..1cab5fef 100644
--- a/pki/base/util/src/netscape/security/pkcs/SignerInfo.java
+++ b/pki/base/util/src/netscape/security/pkcs/SignerInfo.java
@@ -38,8 +38,8 @@ import netscape.security.x509.X500Name;
/**
* A SignerInfo, as defined in PKCS#7's signedData type.
- *
- * @author Benjamin Renaud
+ *
+ * @author Benjamin Renaud
* @version 1.27 97/12/10
*/
public class SignerInfo implements DerEncoder {
@@ -54,301 +54,294 @@ public class SignerInfo implements DerEncoder {
PKCS9Attributes authenticatedAttributes;
PKCS9Attributes unauthenticatedAttributes;
- public SignerInfo(X500Name issuerName,
- BigInt serial,
- AlgorithmId digestAlgorithmId,
- AlgorithmId digestEncryptionAlgorithmId,
- byte[] encryptedDigest) {
- this.version = new BigInt(1);
- this.issuerName = issuerName;
- this.certificateSerialNumber = serial;
- this.digestAlgorithmId = digestAlgorithmId;
- this.digestEncryptionAlgorithmId = digestEncryptionAlgorithmId;
- this.encryptedDigest = encryptedDigest;
+ public SignerInfo(X500Name issuerName,
+ BigInt serial,
+ AlgorithmId digestAlgorithmId,
+ AlgorithmId digestEncryptionAlgorithmId,
+ byte[] encryptedDigest) {
+ this.version = new BigInt(1);
+ this.issuerName = issuerName;
+ this.certificateSerialNumber = serial;
+ this.digestAlgorithmId = digestAlgorithmId;
+ this.digestEncryptionAlgorithmId = digestEncryptionAlgorithmId;
+ this.encryptedDigest = encryptedDigest;
}
- public SignerInfo(X500Name issuerName,
- BigInt serial,
- AlgorithmId digestAlgorithmId,
- PKCS9Attributes authenticatedAttributes,
- AlgorithmId digestEncryptionAlgorithmId,
- byte[] encryptedDigest,
- PKCS9Attributes unauthenticatedAttributes) {
- this.version = new BigInt(1);
- this.issuerName = issuerName;
- this.certificateSerialNumber = serial;
- this.digestAlgorithmId = digestAlgorithmId;
- this.authenticatedAttributes = authenticatedAttributes;
- this.digestEncryptionAlgorithmId = digestEncryptionAlgorithmId;
- this.encryptedDigest = encryptedDigest;
- this.unauthenticatedAttributes = unauthenticatedAttributes;
+ public SignerInfo(X500Name issuerName,
+ BigInt serial,
+ AlgorithmId digestAlgorithmId,
+ PKCS9Attributes authenticatedAttributes,
+ AlgorithmId digestEncryptionAlgorithmId,
+ byte[] encryptedDigest,
+ PKCS9Attributes unauthenticatedAttributes) {
+ this.version = new BigInt(1);
+ this.issuerName = issuerName;
+ this.certificateSerialNumber = serial;
+ this.digestAlgorithmId = digestAlgorithmId;
+ this.authenticatedAttributes = authenticatedAttributes;
+ this.digestEncryptionAlgorithmId = digestEncryptionAlgorithmId;
+ this.encryptedDigest = encryptedDigest;
+ this.unauthenticatedAttributes = unauthenticatedAttributes;
}
- public SignerInfo(DerInputStream derin)
- throws IOException, ParsingException {
-
- // version
- version = derin.getInteger();
-
- // issuerAndSerialNumber
- DerValue[] issuerAndSerialNumber = derin.getSequence(2);
- byte[] issuerBytes = issuerAndSerialNumber[0].toByteArray();
- issuerName = new X500Name(new DerValue(DerValue.tag_Sequence,
- issuerBytes));
- certificateSerialNumber = issuerAndSerialNumber[1].getInteger();
-
- // digestAlgorithmId
- DerValue tmp = derin.getDerValue();
-
- digestAlgorithmId = AlgorithmId.parse(tmp);
-
- /*
- * check if set of auth attributes (implicit tag) is provided
- * (auth attributes are OPTIONAL)
- */
- if ((byte)(derin.peekByte()) == (byte)0xA0) {
- authenticatedAttributes = new PKCS9Attributes(derin);
- }
-
- // digestEncryptionAlgorithmId - little RSA naming scheme -
- // signature == encryption...
- tmp = derin.getDerValue();
-
- digestEncryptionAlgorithmId = AlgorithmId.parse(tmp);
-
- // encryptedDigest
- encryptedDigest = derin.getOctetString();
-
- /*
- * check if set of unauth attributes (implicit tag) is provided
- * (unauth attributes are OPTIONAL)
- */
- if (derin.available() != 0 && (byte)(derin.peekByte()) == (byte)0xA1) {
- unauthenticatedAttributes = new PKCS9Attributes(derin);
- }
-
- // all done
- if (derin.available() != 0) {
- throw new ParsingException("extra data at the end");
- }
+ public SignerInfo(DerInputStream derin)
+ throws IOException, ParsingException {
+
+ // version
+ version = derin.getInteger();
+
+ // issuerAndSerialNumber
+ DerValue[] issuerAndSerialNumber = derin.getSequence(2);
+ byte[] issuerBytes = issuerAndSerialNumber[0].toByteArray();
+ issuerName = new X500Name(new DerValue(DerValue.tag_Sequence,
+ issuerBytes));
+ certificateSerialNumber = issuerAndSerialNumber[1].getInteger();
+
+ // digestAlgorithmId
+ DerValue tmp = derin.getDerValue();
+
+ digestAlgorithmId = AlgorithmId.parse(tmp);
+
+ /*
+ * check if set of auth attributes (implicit tag) is provided (auth
+ * attributes are OPTIONAL)
+ */
+ if ((byte) (derin.peekByte()) == (byte) 0xA0) {
+ authenticatedAttributes = new PKCS9Attributes(derin);
+ }
+
+ // digestEncryptionAlgorithmId - little RSA naming scheme -
+ // signature == encryption...
+ tmp = derin.getDerValue();
+
+ digestEncryptionAlgorithmId = AlgorithmId.parse(tmp);
+
+ // encryptedDigest
+ encryptedDigest = derin.getOctetString();
+
+ /*
+ * check if set of unauth attributes (implicit tag) is provided (unauth
+ * attributes are OPTIONAL)
+ */
+ if (derin.available() != 0 && (byte) (derin.peekByte()) == (byte) 0xA1) {
+ unauthenticatedAttributes = new PKCS9Attributes(derin);
+ }
+
+ // all done
+ if (derin.available() != 0) {
+ throw new ParsingException("extra data at the end");
+ }
}
public void encode(DerOutputStream out) throws IOException {
-
- derEncode(out);
+
+ derEncode(out);
}
/**
- * DER encode this object onto an output stream.
- * Implements the <code>DerEncoder</code> interface.
- *
- * @param out
- * the output stream on which to write the DER encoding.
- *
+ * DER encode this object onto an output stream. Implements the
+ * <code>DerEncoder</code> interface.
+ *
+ * @param out the output stream on which to write the DER encoding.
+ *
* @exception IOException on encoding error.
*/
public void derEncode(OutputStream out) throws IOException {
- DerOutputStream seq = new DerOutputStream();
- seq.putInteger(version);
- DerOutputStream issuerAndSerialNumber = new DerOutputStream();
- issuerName.encode(issuerAndSerialNumber);
- issuerAndSerialNumber.putInteger(certificateSerialNumber);
- seq.write(DerValue.tag_Sequence, issuerAndSerialNumber);
-
- digestAlgorithmId.encode(seq);
-
- // encode authenticated attributes if there are any
- if (authenticatedAttributes != null)
- authenticatedAttributes.encode((byte)0xA0, seq);
-
- digestEncryptionAlgorithmId.encode(seq);
-
- seq.putOctetString(encryptedDigest);
-
- // encode unauthenticated attributes if there are any
- if (unauthenticatedAttributes != null)
- unauthenticatedAttributes.encode((byte)0xA1, seq);
-
- DerOutputStream tmp = new DerOutputStream();
- tmp.write(DerValue.tag_Sequence, seq);
-
- out.write(tmp.toByteArray());
- }
+ DerOutputStream seq = new DerOutputStream();
+ seq.putInteger(version);
+ DerOutputStream issuerAndSerialNumber = new DerOutputStream();
+ issuerName.encode(issuerAndSerialNumber);
+ issuerAndSerialNumber.putInteger(certificateSerialNumber);
+ seq.write(DerValue.tag_Sequence, issuerAndSerialNumber);
+
+ digestAlgorithmId.encode(seq);
+
+ // encode authenticated attributes if there are any
+ if (authenticatedAttributes != null)
+ authenticatedAttributes.encode((byte) 0xA0, seq);
+
+ digestEncryptionAlgorithmId.encode(seq);
+
+ seq.putOctetString(encryptedDigest);
+ // encode unauthenticated attributes if there are any
+ if (unauthenticatedAttributes != null)
+ unauthenticatedAttributes.encode((byte) 0xA1, seq);
+ DerOutputStream tmp = new DerOutputStream();
+ tmp.write(DerValue.tag_Sequence, seq);
+
+ out.write(tmp.toByteArray());
+ }
public X509Certificate getCertificate(PKCS7 block)
- throws IOException {
- return block.getCertificate(certificateSerialNumber, issuerName);
+ throws IOException {
+ return block.getCertificate(certificateSerialNumber, issuerName);
}
- /* Returns null if verify fails, this signerInfo if
- verify succeeds. */
- SignerInfo verify(PKCS7 block, byte[] data)
- throws NoSuchAlgorithmException, SignatureException {
-
- try {
-
- ContentInfo content = block.getContentInfo();
- if (data == null) {
- data = content.getContentBytes();
- }
-
- String digestAlgname =
- getDigestAlgorithmId().getName();
-
- byte[] dataSigned;
-
- // if there are authenticate attributes, get the message
- // digest and compare it with the digest of data
- if (authenticatedAttributes == null) {
- dataSigned = data;
- } else {
-
- // first, check content type
- ObjectIdentifier contentType = (ObjectIdentifier)
- authenticatedAttributes.getAttributeValue(
- PKCS9Attribute.CONTENT_TYPE_OID);
- if (contentType == null ||
- !contentType.equals(content.contentType))
- return null; // contentType does not match, bad SignerInfo
-
- // now, check message digest
- byte[] messageDigest = (byte[])
- authenticatedAttributes.getAttributeValue(
- PKCS9Attribute.MESSAGE_DIGEST_OID);
-
- if (messageDigest == null) // fail if there is no message digest
- return null;
-
- MessageDigest md = MessageDigest.getInstance(digestAlgname);
- byte[] computedMessageDigest = md.digest(data);
-
- if (messageDigest.length != computedMessageDigest.length)
- return null;
- for (int i = 0; i < messageDigest.length; i++) {
- if (messageDigest[i] != computedMessageDigest[i])
- return null;
- }
-
- // message digest attribute matched
- // digest of original data
-
- // the data actually signed is the DER encoding of
- // the authenticated attributes (tagged with
- // the "SET OF" tag, not 0xA0).
- dataSigned = authenticatedAttributes.getDerEncoding();
- }
-
- // put together digest algorithm and encryption algorithm
- // to form signing algorithm
- String encryptionAlgname =
- getDigestEncryptionAlgorithmId().getName();
-
- String algname;
- if (encryptionAlgname.equals("DSA") ||
- encryptionAlgname.equals("SHA1withDSA")) {
- algname = "DSA";
- } else {
- algname = digestAlgname + "/" + encryptionAlgname;
- }
-
- Signature sig = Signature.getInstance(algname);
- X509Certificate cert = getCertificate(block);
-
- if (cert == null) {
- return null;
- }
-
- PublicKey key = cert.getPublicKey();
- sig.initVerify(key);
-
- sig.update(dataSigned);
-
- if (sig.verify(encryptedDigest)) {
- return this;
- }
-
- } catch (IOException e) {
- throw new SignatureException("IO error verifying signature:\n" +
- e.getMessage());
-
- } catch (InvalidKeyException e) {
- throw new SignatureException("InvalidKey: " + e.getMessage());
-
- }
- return null;
+ /*
+ * Returns null if verify fails, this signerInfo if verify succeeds.
+ */
+ SignerInfo verify(PKCS7 block, byte[] data)
+ throws NoSuchAlgorithmException, SignatureException {
+
+ try {
+
+ ContentInfo content = block.getContentInfo();
+ if (data == null) {
+ data = content.getContentBytes();
+ }
+
+ String digestAlgname =
+ getDigestAlgorithmId().getName();
+
+ byte[] dataSigned;
+
+ // if there are authenticate attributes, get the message
+ // digest and compare it with the digest of data
+ if (authenticatedAttributes == null) {
+ dataSigned = data;
+ } else {
+
+ // first, check content type
+ ObjectIdentifier contentType = (ObjectIdentifier)
+ authenticatedAttributes.getAttributeValue(
+ PKCS9Attribute.CONTENT_TYPE_OID);
+ if (contentType == null ||
+ !contentType.equals(content.contentType))
+ return null; // contentType does not match, bad SignerInfo
+
+ // now, check message digest
+ byte[] messageDigest = (byte[])
+ authenticatedAttributes.getAttributeValue(
+ PKCS9Attribute.MESSAGE_DIGEST_OID);
+
+ if (messageDigest == null) // fail if there is no message digest
+ return null;
+
+ MessageDigest md = MessageDigest.getInstance(digestAlgname);
+ byte[] computedMessageDigest = md.digest(data);
+
+ if (messageDigest.length != computedMessageDigest.length)
+ return null;
+ for (int i = 0; i < messageDigest.length; i++) {
+ if (messageDigest[i] != computedMessageDigest[i])
+ return null;
+ }
+
+ // message digest attribute matched
+ // digest of original data
+
+ // the data actually signed is the DER encoding of
+ // the authenticated attributes (tagged with
+ // the "SET OF" tag, not 0xA0).
+ dataSigned = authenticatedAttributes.getDerEncoding();
+ }
+
+ // put together digest algorithm and encryption algorithm
+ // to form signing algorithm
+ String encryptionAlgname =
+ getDigestEncryptionAlgorithmId().getName();
+
+ String algname;
+ if (encryptionAlgname.equals("DSA") ||
+ encryptionAlgname.equals("SHA1withDSA")) {
+ algname = "DSA";
+ } else {
+ algname = digestAlgname + "/" + encryptionAlgname;
+ }
+
+ Signature sig = Signature.getInstance(algname);
+ X509Certificate cert = getCertificate(block);
+
+ if (cert == null) {
+ return null;
+ }
+
+ PublicKey key = cert.getPublicKey();
+ sig.initVerify(key);
+
+ sig.update(dataSigned);
+
+ if (sig.verify(encryptedDigest)) {
+ return this;
+ }
+
+ } catch (IOException e) {
+ throw new SignatureException("IO error verifying signature:\n" +
+ e.getMessage());
+
+ } catch (InvalidKeyException e) {
+ throw new SignatureException("InvalidKey: " + e.getMessage());
+
+ }
+ return null;
}
-
+
/* Verify the content of the pkcs7 block. */
SignerInfo verify(PKCS7 block)
- throws NoSuchAlgorithmException, SignatureException {
- return verify(block, null);
+ throws NoSuchAlgorithmException, SignatureException {
+ return verify(block, null);
}
-
public BigInt getVersion() {
- return version;
+ return version;
}
public X500Name getIssuerName() {
- return issuerName;
+ return issuerName;
}
public BigInt getCertificateSerialNumber() {
- return certificateSerialNumber;
+ return certificateSerialNumber;
}
public AlgorithmId getDigestAlgorithmId() {
- return digestAlgorithmId;
+ return digestAlgorithmId;
}
public PKCS9Attributes getAuthenticatedAttributes() {
- return authenticatedAttributes;
+ return authenticatedAttributes;
}
public AlgorithmId getDigestEncryptionAlgorithmId() {
- return digestEncryptionAlgorithmId;
+ return digestEncryptionAlgorithmId;
}
public byte[] getEncryptedDigest() {
- return encryptedDigest;
+ return encryptedDigest;
}
public PKCS9Attributes getUnauthenticatedAttributes() {
- return unauthenticatedAttributes;
+ return unauthenticatedAttributes;
}
public String toString() {
- netscape.security.util.PrettyPrintFormat pp =
- new netscape.security.util.PrettyPrintFormat(" ", 20);
- String digestbits = pp.toHexString(encryptedDigest);
-
- String out = "";
-
- out += "Signer Info for (issuer): " + issuerName + "\n";
- out += "\tversion: " + version + "\n";
- out += "\tcertificateSerialNumber: " + certificateSerialNumber +
- "\n";
- out += "\tdigestAlgorithmId: " + digestAlgorithmId + "\n";
- if (authenticatedAttributes != null) {
- out += "\tauthenticatedAttributes: " + authenticatedAttributes +
- "\n";
- }
- out += "\tdigestEncryptionAlgorithmId: " + digestEncryptionAlgorithmId +
- "\n";
-
- out += "\tencryptedDigest: " + "\n" +
- digestbits + "\n";
- if (unauthenticatedAttributes != null) {
- out += "\tunauthenticatedAttributes: " +
- unauthenticatedAttributes + "\n";
- }
- return out;
+ netscape.security.util.PrettyPrintFormat pp =
+ new netscape.security.util.PrettyPrintFormat(" ", 20);
+ String digestbits = pp.toHexString(encryptedDigest);
+
+ String out = "";
+
+ out += "Signer Info for (issuer): " + issuerName + "\n";
+ out += "\tversion: " + version + "\n";
+ out += "\tcertificateSerialNumber: " + certificateSerialNumber +
+ "\n";
+ out += "\tdigestAlgorithmId: " + digestAlgorithmId + "\n";
+ if (authenticatedAttributes != null) {
+ out += "\tauthenticatedAttributes: " + authenticatedAttributes +
+ "\n";
+ }
+ out += "\tdigestEncryptionAlgorithmId: " + digestEncryptionAlgorithmId +
+ "\n";
+
+ out += "\tencryptedDigest: " + "\n" +
+ digestbits + "\n";
+ if (unauthenticatedAttributes != null) {
+ out += "\tunauthenticatedAttributes: " +
+ unauthenticatedAttributes + "\n";
+ }
+ return out;
}
}
-
-
-
-
diff --git a/pki/base/util/src/netscape/security/provider/CMS.java b/pki/base/util/src/netscape/security/provider/CMS.java
index d89c6c4c..00ef76da 100644
--- a/pki/base/util/src/netscape/security/provider/CMS.java
+++ b/pki/base/util/src/netscape/security/provider/CMS.java
@@ -19,33 +19,34 @@ package netscape.security.provider;
import java.security.AccessController;
import java.security.Provider;
+
/**
* The CMS Security Provider.
*/
public final class CMS extends Provider {
- /**
+ /**
*
*/
private static final long serialVersionUID = 1065207998900104219L;
private static final String INFO = "CMS " +
- "(DSA key/parameter generation; DSA signing; " +
- "SHA-1, MD5 digests; SecureRandom; X.509 certificates)";
+ "(DSA key/parameter generation; DSA signing; " +
+ "SHA-1, MD5 digests; SecureRandom; X.509 certificates)";
public CMS() {
- /* We are the SUN provider */
+ /* We are the SUN provider */
super("CMS", 1.0, INFO);
AccessController.doPrivileged(new java.security.PrivilegedAction() {
- public Object run() {
- /*
- * Certificates
- */
- put("CertificateFactory.X.509", "netscape.security.provider.X509CertificateFactory");
- put("Alg.Alias.CertificateFactory.X.509", "X.509");
- return null;
- }
- });
- }
+ public Object run() {
+ /*
+ * Certificates
+ */
+ put("CertificateFactory.X.509", "netscape.security.provider.X509CertificateFactory");
+ put("Alg.Alias.CertificateFactory.X.509", "X.509");
+ return null;
+ }
+ });
+ }
}
diff --git a/pki/base/util/src/netscape/security/provider/DSA.java b/pki/base/util/src/netscape/security/provider/DSA.java
index 9fa5b9f6..b7295b95 100644
--- a/pki/base/util/src/netscape/security/provider/DSA.java
+++ b/pki/base/util/src/netscape/security/provider/DSA.java
@@ -37,14 +37,14 @@ import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
/**
- * The Digital Signature Standard (using the Digital Signature
- * Algorithm), as described in fips186 of the National Instute of
- * Standards and Technology (NIST), using fips180-1 (SHA-1).
- *
+ * The Digital Signature Standard (using the Digital Signature Algorithm), as
+ * described in fips186 of the National Instute of Standards and Technology
+ * (NIST), using fips180-1 (SHA-1).
+ *
* @author Benjamin Renaud
- *
+ *
* @version 1.86, 97/09/17
- *
+ *
* @see DSAPublicKey
* @see DSAPrivateKey
*/
@@ -65,7 +65,7 @@ public final class DSA extends Signature {
/* The private key, if any */
private BigInteger presetX;
-
+
/* The SHA hash for the data */
private MessageDigest dataSHA;
@@ -76,8 +76,8 @@ public final class DSA extends Signature {
private byte[] KseedAsByteArray;
/*
- * The random seed used to generate k
- * (prevent the same Kseed from being used twice in a row
+ * The random seed used to generate k (prevent the same Kseed from being
+ * used twice in a row
*/
private int[] previousKseed;
@@ -89,8 +89,8 @@ public final class DSA extends Signature {
* initialized before being usable for signing or verifying.
*/
public DSA() throws NoSuchAlgorithmException {
- super("SHA/DSA");
- dataSHA = MessageDigest.getInstance("SHA");
+ super("SHA/DSA");
+ dataSHA = MessageDigest.getInstance("SHA");
}
/**
@@ -98,20 +98,19 @@ public final class DSA extends Signature {
*
* @param privateKey the DSA private key
*
- * @exception InvalidKeyException if the key is not a valid DSA private
- * key.
+ * @exception InvalidKeyException if the key is not a valid DSA private key.
*/
protected void engineInitSign(PrivateKey privateKey)
- throws InvalidKeyException {
- if (!(privateKey instanceof java.security.interfaces.DSAPrivateKey)) {
- throw new InvalidKeyException("not a DSA private key: " +
- privateKey);
- }
- java.security.interfaces.DSAPrivateKey priv =
- (java.security.interfaces.DSAPrivateKey)privateKey;
-
- this.presetX = priv.getX();
- initialize(priv.getParams());
+ throws InvalidKeyException {
+ if (!(privateKey instanceof java.security.interfaces.DSAPrivateKey)) {
+ throw new InvalidKeyException("not a DSA private key: " +
+ privateKey);
+ }
+ java.security.interfaces.DSAPrivateKey priv =
+ (java.security.interfaces.DSAPrivateKey) privateKey;
+
+ this.presetX = priv.getX();
+ initialize(priv.getParams());
}
/**
@@ -119,412 +118,409 @@ public final class DSA extends Signature {
*
* @param publicKey the DSA public key.
*
- * @exception InvalidKeyException if the key is not a valid DSA public
- * key.
+ * @exception InvalidKeyException if the key is not a valid DSA public key.
*/
protected void engineInitVerify(PublicKey publicKey)
- throws InvalidKeyException {
- if (!(publicKey instanceof java.security.interfaces.DSAPublicKey)) {
- throw new InvalidKeyException("not a DSA public key: " +
- publicKey);
- }
- java.security.interfaces.DSAPublicKey pub =
- (java.security.interfaces.DSAPublicKey)publicKey;
- this.presetY = pub.getY();
- initialize(pub.getParams());
+ throws InvalidKeyException {
+ if (!(publicKey instanceof java.security.interfaces.DSAPublicKey)) {
+ throw new InvalidKeyException("not a DSA public key: " +
+ publicKey);
+ }
+ java.security.interfaces.DSAPublicKey pub =
+ (java.security.interfaces.DSAPublicKey) publicKey;
+ this.presetY = pub.getY();
+ initialize(pub.getParams());
}
private void initialize(DSAParams params) {
- dataSHA.reset();
- setParams(params);
+ dataSHA.reset();
+ setParams(params);
}
/**
- * Sign all the data thus far updated. The signature is formatted
- * according to the Canonical Encoding Rules, returned as a DER
- * sequence of Integer, r and s.
- *
- * @return a signature block formatted according to the Canonical
- * Encoding Rules.
- *
- * @exception SignatureException if the signature object was not
- * properly initialized, or if another exception occurs.
+ * Sign all the data thus far updated. The signature is formatted according
+ * to the Canonical Encoding Rules, returned as a DER sequence of Integer, r
+ * and s.
+ *
+ * @return a signature block formatted according to the Canonical Encoding
+ * Rules.
+ *
+ * @exception SignatureException if the signature object was not properly
+ * initialized, or if another exception occurs.
*
* @see netscape.security.provider.DSA#engineUpdate
* @see netscape.security.provider.DSA#engineVerify
*/
- protected byte[] engineSign() throws SignatureException {
- BigInteger k = generateK(presetQ);
- BigInteger r = generateR(presetP, presetQ, presetG, k);
- BigInteger s = generateS(presetX, presetQ, r, k);
-
- // got to convert to BigInt...
- BigInt rAsBigInt = new BigInt(r.toByteArray());
- BigInt sAsBigInt = new BigInt(s.toByteArray());
-
- try {
- DerOutputStream outseq = new DerOutputStream(100);
- outseq.putInteger(rAsBigInt);
- outseq.putInteger(sAsBigInt);
- DerValue result = new DerValue(DerValue.tag_Sequence,
- outseq.toByteArray());
-
- return result.toByteArray();
-
- } catch (IOException e) {
- throw new SignatureException("error encoding signature");
- }
+ protected byte[] engineSign() throws SignatureException {
+ BigInteger k = generateK(presetQ);
+ BigInteger r = generateR(presetP, presetQ, presetG, k);
+ BigInteger s = generateS(presetX, presetQ, r, k);
+
+ // got to convert to BigInt...
+ BigInt rAsBigInt = new BigInt(r.toByteArray());
+ BigInt sAsBigInt = new BigInt(s.toByteArray());
+
+ try {
+ DerOutputStream outseq = new DerOutputStream(100);
+ outseq.putInteger(rAsBigInt);
+ outseq.putInteger(sAsBigInt);
+ DerValue result = new DerValue(DerValue.tag_Sequence,
+ outseq.toByteArray());
+
+ return result.toByteArray();
+
+ } catch (IOException e) {
+ throw new SignatureException("error encoding signature");
+ }
}
/**
- * Verify all the data thus far updated.
- *
- * @param signature the alledged signature, encoded using the
- * Canonical Encoding Rules, as a sequence of integers, r and s.
- *
- * @exception SignatureException if the signature object was not
- * properly initialized, or if another exception occurs.
- *
+ * Verify all the data thus far updated.
+ *
+ * @param signature the alledged signature, encoded using the Canonical
+ * Encoding Rules, as a sequence of integers, r and s.
+ *
+ * @exception SignatureException if the signature object was not properly
+ * initialized, or if another exception occurs.
+ *
* @see netscape.security.provider.DSA#engineUpdate
- * @see netscape.security.provider.DSA#engineSign
+ * @see netscape.security.provider.DSA#engineSign
*/
- protected boolean engineVerify(byte[] signature)
- throws SignatureException {
-
- BigInteger r = null;
- BigInteger s = null;
- // first decode the signature.
- try {
- DerInputStream in = new DerInputStream(signature);
- DerValue[] values = in.getSequence(2);
-
- r = values[0].getInteger().toBigInteger();
- s = values[1].getInteger().toBigInteger();
-
- } catch (IOException e) {
- throw new SignatureException("invalid encoding for signature");
- }
- BigInteger w = generateW(presetP, presetQ, presetG, s);
- BigInteger v = generateV(presetY, presetP, presetQ, presetG, w, r);
-
- return v.equals(r);
+ protected boolean engineVerify(byte[] signature)
+ throws SignatureException {
+
+ BigInteger r = null;
+ BigInteger s = null;
+ // first decode the signature.
+ try {
+ DerInputStream in = new DerInputStream(signature);
+ DerValue[] values = in.getSequence(2);
+
+ r = values[0].getInteger().toBigInteger();
+ s = values[1].getInteger().toBigInteger();
+
+ } catch (IOException e) {
+ throw new SignatureException("invalid encoding for signature");
+ }
+ BigInteger w = generateW(presetP, presetQ, presetG, s);
+ BigInteger v = generateV(presetY, presetP, presetQ, presetG, w, r);
+
+ return v.equals(r);
}
BigInteger generateR(BigInteger p, BigInteger q, BigInteger g,
- BigInteger k) {
- BigInteger temp = g.modPow(k, p);
- return temp.remainder(q);
-
- }
-
- BigInteger generateS(BigInteger x, BigInteger q,
- BigInteger r, BigInteger k) {
-
- byte[] s2 = dataSHA.digest();
- BigInteger temp = new BigInteger(1, s2);
- BigInteger k1 = k.modInverse(q);
-
- BigInteger s = x.multiply(r);
- s = temp.add(s);
- s = k1.multiply(s);
- return s.remainder(q);
+ BigInteger k) {
+ BigInteger temp = g.modPow(k, p);
+ return temp.remainder(q);
+
+ }
+
+ BigInteger generateS(BigInteger x, BigInteger q,
+ BigInteger r, BigInteger k) {
+
+ byte[] s2 = dataSHA.digest();
+ BigInteger temp = new BigInteger(1, s2);
+ BigInteger k1 = k.modInverse(q);
+
+ BigInteger s = x.multiply(r);
+ s = temp.add(s);
+ s = k1.multiply(s);
+ return s.remainder(q);
}
BigInteger generateW(BigInteger p, BigInteger q,
- BigInteger g, BigInteger s) {
- return s.modInverse(q);
+ BigInteger g, BigInteger s) {
+ return s.modInverse(q);
}
BigInteger generateV(BigInteger y, BigInteger p,
- BigInteger q, BigInteger g,
- BigInteger w, BigInteger r) {
-
- byte[] s2 = dataSHA.digest();
- BigInteger temp = new BigInteger(1, s2);
-
- temp = temp.multiply(w);
- BigInteger u1 = temp.remainder(q);
-
- BigInteger u2 = (r.multiply(w)).remainder(q);
-
- BigInteger t1 = g.modPow(u1,p);
- BigInteger t2 = y.modPow(u2,p);
- BigInteger t3 = t1.multiply(t2);
- BigInteger t5 = t3.remainder(p);
- return t5.remainder(q);
+ BigInteger q, BigInteger g,
+ BigInteger w, BigInteger r) {
+
+ byte[] s2 = dataSHA.digest();
+ BigInteger temp = new BigInteger(1, s2);
+
+ temp = temp.multiply(w);
+ BigInteger u1 = temp.remainder(q);
+
+ BigInteger u2 = (r.multiply(w)).remainder(q);
+
+ BigInteger t1 = g.modPow(u1, p);
+ BigInteger t2 = y.modPow(u2, p);
+ BigInteger t3 = t1.multiply(t2);
+ BigInteger t5 = t3.remainder(p);
+ return t5.remainder(q);
}
/*
- * Please read bug report 4044247 for an alternative, faster,
- * NON-FIPS approved method to generate K
+ * Please read bug report 4044247 for an alternative, faster, NON-FIPS
+ * approved method to generate K
*/
BigInteger generateK(BigInteger q) {
- BigInteger k = null;
-
- // The application specified a Kseed for us to use.
- // Note that we do not allow usage of the same Kseed twice in a row
- if (Kseed != null && compareSeeds(Kseed, previousKseed) != 0) {
- k = generateK(Kseed, q);
- if (k.signum() > 0 && k.compareTo(q) < 0) {
- previousKseed = new int [Kseed.length];
- System.arraycopy(Kseed, 0, previousKseed, 0, Kseed.length);
- return k;
- }
- }
-
- // The application did not specify a Kseed for us to use.
- // We'll generate a new Kseed by getting random bytes from
- // a SecureRandom object.
- SecureRandom random = getSigningRandom();
-
- while (true) {
- int[] seed = new int[5];
-
- for (int i = 0; i < 5; i++)
- seed[i] = random.nextInt();
- k = generateK(seed, q);
- if (k.signum() > 0 && k.compareTo(q) < 0) {
- previousKseed = new int [seed.length];
- System.arraycopy(seed, 0, previousKseed, 0, seed.length);
- return k;
- }
- }
+ BigInteger k = null;
+
+ // The application specified a Kseed for us to use.
+ // Note that we do not allow usage of the same Kseed twice in a row
+ if (Kseed != null && compareSeeds(Kseed, previousKseed) != 0) {
+ k = generateK(Kseed, q);
+ if (k.signum() > 0 && k.compareTo(q) < 0) {
+ previousKseed = new int[Kseed.length];
+ System.arraycopy(Kseed, 0, previousKseed, 0, Kseed.length);
+ return k;
+ }
+ }
+
+ // The application did not specify a Kseed for us to use.
+ // We'll generate a new Kseed by getting random bytes from
+ // a SecureRandom object.
+ SecureRandom random = getSigningRandom();
+
+ while (true) {
+ int[] seed = new int[5];
+
+ for (int i = 0; i < 5; i++)
+ seed[i] = random.nextInt();
+ k = generateK(seed, q);
+ if (k.signum() > 0 && k.compareTo(q) < 0) {
+ previousKseed = new int[seed.length];
+ System.arraycopy(seed, 0, previousKseed, 0, seed.length);
+ return k;
+ }
+ }
}
// Use the application-specified SecureRandom Object if provided.
// Otherwise, use our default SecureRandom Object.
private SecureRandom getSigningRandom() {
- if (signingRandom == null) {
- if (appRandom != null)
- signingRandom = appRandom;
- else
- signingRandom = new SecureRandom();
- }
- return signingRandom;
+ if (signingRandom == null) {
+ if (appRandom != null)
+ signingRandom = appRandom;
+ else
+ signingRandom = new SecureRandom();
+ }
+ return signingRandom;
}
/*
- * return 0 if equal
- * return 1 if not equal
+ * return 0 if equal return 1 if not equal
*/
- private int compareSeeds(int []seed1, int []seed2) {
+ private int compareSeeds(int[] seed1, int[] seed2) {
- if ((seed1 == null && seed1 == null) ||
- (seed1 == null && seed2 != null) ||
- (seed1 != null && seed2 == null) ||
- seed1.length != seed2.length)
- return 1;
+ if ((seed1 == null && seed1 == null) ||
+ (seed1 == null && seed2 != null) ||
+ (seed1 != null && seed2 == null) ||
+ seed1.length != seed2.length)
+ return 1;
- for (int i = 0; i < seed1.length; i++) {
- if (seed1[i] != seed2[i])
- return 1;
- }
+ for (int i = 0; i < seed1.length; i++) {
+ if (seed1[i] != seed2[i])
+ return 1;
+ }
- return 0;
+ return 0;
}
/**
* Compute k for a DSA signature.
- *
- * @param seed the seed for generating k. This seed should be
- * secure. This is what is refered to as the KSEED in the DSA
- * specification.
- *
+ *
+ * @param seed the seed for generating k. This seed should be secure. This
+ * is what is refered to as the KSEED in the DSA specification.
+ *
* @param g the g parameter from the DSA key pair.
*/
BigInteger generateK(int[] seed, BigInteger q) {
- // check out t in the spec.
- int[] t = { 0xEFCDAB89, 0x98BADCFE, 0x10325476,
- 0xC3D2E1F0, 0x67452301 };
- //
- int[] tmp = DSA.SHA_7(seed, t);
- byte[] tmpBytes = new byte[tmp.length * 4];
- for (int i = 0; i < tmp.length; i++) {
- int k = tmp[i];
- for (int j = 0; j < 4; j++) {
- tmpBytes[(i * 4) + j] = (byte) (k >>> (24 - (j * 8)));
- }
- }
- BigInteger k = new BigInteger(1, tmpBytes).mod(q);
- return k;
+ // check out t in the spec.
+ int[] t = { 0xEFCDAB89, 0x98BADCFE, 0x10325476,
+ 0xC3D2E1F0, 0x67452301 };
+ //
+ int[] tmp = DSA.SHA_7(seed, t);
+ byte[] tmpBytes = new byte[tmp.length * 4];
+ for (int i = 0; i < tmp.length; i++) {
+ int k = tmp[i];
+ for (int j = 0; j < 4; j++) {
+ tmpBytes[(i * 4) + j] = (byte) (k >>> (24 - (j * 8)));
+ }
+ }
+ BigInteger k = new BigInteger(1, tmpBytes).mod(q);
+ return k;
}
- // Constants for each round
+ // Constants for each round
private static final int round1_kt = 0x5a827999;
private static final int round2_kt = 0x6ed9eba1;
private static final int round3_kt = 0x8f1bbcdc;
private static final int round4_kt = 0xca62c1d6;
- /**
- * Computes set 1 thru 7 of SHA-1 on m1. */
- static int[] SHA_7(int [] m1, int[] h) {
-
- int[] W = new int[80];
- System.arraycopy(m1,0,W,0,m1.length);
- int temp = 0;
-
- for (int t = 16; t <= 79; t++){
- temp = W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16];
- W[t] = ((temp << 1) | (temp >>>(32 - 1)));
- }
-
- int a = h[0],b = h[1],c = h[2], d = h[3], e = h[4];
- for (int i = 0; i < 20; i++) {
- temp = ((a<<5) | (a>>>(32-5))) +
- ((b&c)|((~b)&d))+ e + W[i] + round1_kt;
- e = d;
- d = c;
- c = ((b<<30) | (b>>>(32-30)));
- b = a;
- a = temp;
- }
-
- // Round 2
- for (int i = 20; i < 40; i++) {
- temp = ((a<<5) | (a>>>(32-5))) +
- (b ^ c ^ d) + e + W[i] + round2_kt;
- e = d;
- d = c;
- c = ((b<<30) | (b>>>(32-30)));
- b = a;
- a = temp;
- }
-
- // Round 3
- for (int i = 40; i < 60; i++) {
- temp = ((a<<5) | (a>>>(32-5))) +
- ((b&c)|(b&d)|(c&d)) + e + W[i] + round3_kt;
- e = d;
- d = c;
- c = ((b<<30) | (b>>>(32-30)));
- b = a;
- a = temp;
- }
-
- // Round 4
- for (int i = 60; i < 80; i++) {
- temp = ((a<<5) | (a>>>(32-5))) +
- (b ^ c ^ d) + e + W[i] + round4_kt;
- e = d;
- d = c;
- c = ((b<<30) | (b>>>(32-30)));
- b = a;
- a = temp;
- }
- int[] md = new int[5];
- md[0] = h[0] + a;
- md[1] = h[1] + b;
- md[2] = h[2] + c;
- md[3] = h[3] + d;
- md[4] = h[4] + e;
- return md;
- }
-
+ /**
+ * Computes set 1 thru 7 of SHA-1 on m1.
+ */
+ static int[] SHA_7(int[] m1, int[] h) {
+
+ int[] W = new int[80];
+ System.arraycopy(m1, 0, W, 0, m1.length);
+ int temp = 0;
+
+ for (int t = 16; t <= 79; t++) {
+ temp = W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16];
+ W[t] = ((temp << 1) | (temp >>> (32 - 1)));
+ }
+
+ int a = h[0], b = h[1], c = h[2], d = h[3], e = h[4];
+ for (int i = 0; i < 20; i++) {
+ temp = ((a << 5) | (a >>> (32 - 5))) +
+ ((b & c) | ((~b) & d)) + e + W[i] + round1_kt;
+ e = d;
+ d = c;
+ c = ((b << 30) | (b >>> (32 - 30)));
+ b = a;
+ a = temp;
+ }
+
+ // Round 2
+ for (int i = 20; i < 40; i++) {
+ temp = ((a << 5) | (a >>> (32 - 5))) +
+ (b ^ c ^ d) + e + W[i] + round2_kt;
+ e = d;
+ d = c;
+ c = ((b << 30) | (b >>> (32 - 30)));
+ b = a;
+ a = temp;
+ }
+
+ // Round 3
+ for (int i = 40; i < 60; i++) {
+ temp = ((a << 5) | (a >>> (32 - 5))) +
+ ((b & c) | (b & d) | (c & d)) + e + W[i] + round3_kt;
+ e = d;
+ d = c;
+ c = ((b << 30) | (b >>> (32 - 30)));
+ b = a;
+ a = temp;
+ }
+
+ // Round 4
+ for (int i = 60; i < 80; i++) {
+ temp = ((a << 5) | (a >>> (32 - 5))) +
+ (b ^ c ^ d) + e + W[i] + round4_kt;
+ e = d;
+ d = c;
+ c = ((b << 30) | (b >>> (32 - 30)));
+ b = a;
+ a = temp;
+ }
+ int[] md = new int[5];
+ md[0] = h[0] + a;
+ md[1] = h[1] + b;
+ md[2] = h[2] + c;
+ md[3] = h[3] + d;
+ md[4] = h[4] + e;
+ return md;
+ }
/**
- * This implementation recognizes the following parameter:<dl>
- *
- * <dt><tt>Kseed</tt>
+ * This implementation recognizes the following parameter:
+ * <dl>
+ *
+ * <dt><tt>Kseed</tt>
*
* <dd>a byte array.
- *
+ *
* </dl>
- *
+ *
* @deprecated
*/
protected void engineSetParameter(String key, Object param) {
- if (key.equals("KSEED")) {
+ if (key.equals("KSEED")) {
- if (param instanceof byte[]) {
+ if (param instanceof byte[]) {
- Kseed = byteArray2IntArray((byte[])param);
- KseedAsByteArray = (byte[])param;
+ Kseed = byteArray2IntArray((byte[]) param);
+ KseedAsByteArray = (byte[]) param;
- } else {
- debug("unrecognized param: " + key);
- throw new InvalidParameterException("Kseed not a byte array");
- }
+ } else {
+ debug("unrecognized param: " + key);
+ throw new InvalidParameterException("Kseed not a byte array");
+ }
- } else {
- throw new InvalidParameterException("invalid parameter");
- }
+ } else {
+ throw new InvalidParameterException("invalid parameter");
+ }
}
/**
- * Return the value of the requested parameter. Recognized
- * parameters are:
- *
+ * Return the value of the requested parameter. Recognized parameters are:
+ *
* <dl>
- *
- * <dt><tt>Kseed</tt>
+ *
+ * <dt><tt>Kseed</tt>
*
* <dd>a byte array.
- *
+ *
* </dl>
- *
+ *
* @return the value of the requested parameter.
- *
+ *
* @deprecated
*/
protected Object engineGetParameter(String key) {
- if (key.equals("KSEED")) {
- return KseedAsByteArray;
- } else {
- return null;
- }
- }
+ if (key.equals("KSEED")) {
+ return KseedAsByteArray;
+ } else {
+ return null;
+ }
+ }
/**
* Set the algorithm object.
*/
private void setParams(DSAParams params) {
- this.params = params;
- this.presetP = params.getP();
- this.presetQ = params.getQ();
- this.presetG = params.getG();
+ this.params = params;
+ this.presetP = params.getP();
+ this.presetQ = params.getQ();
+ this.presetG = params.getG();
}
/**
* Update a byte to be signed or verified.
- *
+ *
* @param b the byte to updated.
*/
protected void engineUpdate(byte b) {
- dataSHA.update(b);
+ dataSHA.update(b);
}
-
+
/**
* Update an array of bytes to be signed or verified.
*
* @param data the bytes to be updated.
*/
protected void engineUpdate(byte[] data, int off, int len) {
- dataSHA.update(data, off, len);
+ dataSHA.update(data, off, len);
}
/**
* Return a human readable rendition of the engine.
*/
public String toString() {
- String printable = "DSA Signature";
- if (presetP != null && presetQ != null && presetG != null) {
- printable += "\n\tp: " + presetP.toString(16);
- printable += "\n\tq: " + presetQ.toString(16);
- printable += "\n\tg: " + presetG.toString(16);
- } else {
- printable += "\n\t P, Q or G not initialized.";
- }
- if (presetY != null) {
- printable += "\n\ty: " + presetY.toString(16);
- }
- if (presetY == null && presetX == null) {
- printable += "\n\tUNINIIALIZED";
- }
- return printable;
+ String printable = "DSA Signature";
+ if (presetP != null && presetQ != null && presetG != null) {
+ printable += "\n\tp: " + presetP.toString(16);
+ printable += "\n\tq: " + presetQ.toString(16);
+ printable += "\n\tg: " + presetG.toString(16);
+ } else {
+ printable += "\n\t P, Q or G not initialized.";
+ }
+ if (presetY != null) {
+ printable += "\n\ty: " + presetY.toString(16);
+ }
+ if (presetY == null && presetX == null) {
+ printable += "\n\tUNINIIALIZED";
+ }
+ return printable;
}
/*
@@ -532,120 +528,129 @@ public final class DSA extends Signature {
*/
private int[] byteArray2IntArray(byte[] byteArray) {
- int j = 0;
- byte[] newBA;
- int mod = byteArray.length % 4;
-
- // guarantee that the incoming byteArray is a multiple of 4
- // (pad with 0's)
- switch (mod) {
- case 3: newBA = new byte[byteArray.length + 1]; break;
- case 2: newBA = new byte[byteArray.length + 2]; break;
- case 1: newBA = new byte[byteArray.length + 3]; break;
- default: newBA = new byte[byteArray.length + 0]; break;
- }
- System.arraycopy(byteArray, 0, newBA, 0, byteArray.length);
-
- // copy each set of 4 bytes in the byte array into an integer
- int[] newSeed = new int[newBA.length / 4];
- for (int i = 0; i < newBA.length; i += 4) {
- newSeed[j] = newBA[i + 3] & 0xFF;
- newSeed[j] |= (newBA[i + 2] << 8) & 0xFF00;
- newSeed[j] |= (newBA[i + 1] << 16) & 0xFF0000;
- newSeed[j] |= (newBA[i + 0] << 24) & 0xFF000000;
- j++;
- }
-
- return newSeed;
+ int j = 0;
+ byte[] newBA;
+ int mod = byteArray.length % 4;
+
+ // guarantee that the incoming byteArray is a multiple of 4
+ // (pad with 0's)
+ switch (mod) {
+ case 3:
+ newBA = new byte[byteArray.length + 1];
+ break;
+ case 2:
+ newBA = new byte[byteArray.length + 2];
+ break;
+ case 1:
+ newBA = new byte[byteArray.length + 3];
+ break;
+ default:
+ newBA = new byte[byteArray.length + 0];
+ break;
+ }
+ System.arraycopy(byteArray, 0, newBA, 0, byteArray.length);
+
+ // copy each set of 4 bytes in the byte array into an integer
+ int[] newSeed = new int[newBA.length / 4];
+ for (int i = 0; i < newBA.length; i += 4) {
+ newSeed[j] = newBA[i + 3] & 0xFF;
+ newSeed[j] |= (newBA[i + 2] << 8) & 0xFF00;
+ newSeed[j] |= (newBA[i + 1] << 16) & 0xFF0000;
+ newSeed[j] |= (newBA[i + 0] << 24) & 0xFF000000;
+ j++;
+ }
+
+ return newSeed;
}
- /* We include the test vectors from the DSA specification, FIPS
- 186, and the FIPS 186 Change No 1, which updates the test
- vector using SHA-1 instead of SHA (for both the G function and
- the message hash. */
+ /*
+ * We include the test vectors from the DSA specification, FIPS 186, and the
+ * FIPS 186 Change No 1, which updates the test vector using SHA-1 instead
+ * of SHA (for both the G function and the message hash.
+ */
static void testDSA() throws Exception {
- PrintStream p = System.out;
-
- DSA dsa = new DSA();
- int[] Kseed = { 0x687a66d9, 0x0648f993, 0x867e121f,
- 0x4ddf9ddb, 0x1205584 };
- BigInteger k = dsa.generateK(Kseed, q512);
- p.println("k: " + k.toString(16));
- BigInteger r = dsa.generateR(p512, q512, g512, k);
- p.println("r: " + r.toString(16));
- byte[] abc = { 0x61, 0x62, 0x63 };
- dsa.dataSHA.update(abc);
- BigInteger s = dsa.generateS(x512, q512, r, k);
- p.println("s: " + s.toString(16));
-
- dsa.dataSHA.update(abc);
- BigInteger w = dsa.generateW(p512, q512, g512, s);
- p.println("w: " + w.toString(16));
- BigInteger v = dsa.generateV(y512, p512, q512, g512, w, r);
- p.println("v: " + v.toString(16));
- if (v.equals(r)) {
- p.println("signature verifies.");
- } else {
- p.println("signature does not verify.");
- }
+ PrintStream p = System.out;
+
+ DSA dsa = new DSA();
+ int[] Kseed = { 0x687a66d9, 0x0648f993, 0x867e121f,
+ 0x4ddf9ddb, 0x1205584 };
+ BigInteger k = dsa.generateK(Kseed, q512);
+ p.println("k: " + k.toString(16));
+ BigInteger r = dsa.generateR(p512, q512, g512, k);
+ p.println("r: " + r.toString(16));
+ byte[] abc = { 0x61, 0x62, 0x63 };
+ dsa.dataSHA.update(abc);
+ BigInteger s = dsa.generateS(x512, q512, r, k);
+ p.println("s: " + s.toString(16));
+
+ dsa.dataSHA.update(abc);
+ BigInteger w = dsa.generateW(p512, q512, g512, s);
+ p.println("w: " + w.toString(16));
+ BigInteger v = dsa.generateV(y512, p512, q512, g512, w, r);
+ p.println("v: " + v.toString(16));
+ if (v.equals(r)) {
+ p.println("signature verifies.");
+ } else {
+ p.println("signature does not verify.");
+ }
}
/* Test vector: 512-bit keys generated by our key generator. */
- static BigInteger p512 =
- new BigInteger("fca682ce8e12caba26efccf7110e526db078b05edecb" +
- "cd1eb4a208f3ae1617ae01f35b91a47e6df63413c5e1" +
- "2ed0899bcd132acd50d99151bdc43ee737592e17", 16);
+ static BigInteger p512 =
+ new BigInteger("fca682ce8e12caba26efccf7110e526db078b05edecb" +
+ "cd1eb4a208f3ae1617ae01f35b91a47e6df63413c5e1" +
+ "2ed0899bcd132acd50d99151bdc43ee737592e17", 16);
+
+ static BigInteger q512 =
+ new BigInteger("962eddcc369cba8ebb260ee6b6a126d9346e38c5", 16);
- static BigInteger q512 =
- new BigInteger("962eddcc369cba8ebb260ee6b6a126d9346e38c5", 16);
-
- static BigInteger g512 =
- new BigInteger("678471b27a9cf44ee91a49c5147db1a9aaf244f05a43" +
- "4d6486931d2d14271b9e35030b71fd73da179069b32e" +
- "2935630e1c2062354d0da20a6c416e50be794ca4", 16);
+ static BigInteger g512 =
+ new BigInteger("678471b27a9cf44ee91a49c5147db1a9aaf244f05a43" +
+ "4d6486931d2d14271b9e35030b71fd73da179069b32e" +
+ "2935630e1c2062354d0da20a6c416e50be794ca4", 16);
- static BigInteger x512 =
- new BigInteger("3406c2d71b04b5fc0db62afcad58a6607d3de688", 16);
+ static BigInteger x512 =
+ new BigInteger("3406c2d71b04b5fc0db62afcad58a6607d3de688", 16);
static BigInteger y512 =
- new BigInteger("2d335d76b8ec9d610aa8f2cbb4b149fd96fdd" +
- "3a9a6e62bd6c2e01d406be4d1d72718a2fe08bea6d12f5e452474461f70f4" +
- "dea60508e9fe2eaec23d2ec5d1a866", 16);
+ new BigInteger("2d335d76b8ec9d610aa8f2cbb4b149fd96fdd" +
+ "3a9a6e62bd6c2e01d406be4d1d72718a2fe08bea6d12f5e452474461f70f4" +
+ "dea60508e9fe2eaec23d2ec5d1a866", 16);
/* Official NIST 512-bit test keys */
static String pString = "8df2a494492276aa3d25759bb06869cbeac0d83afb8d0" +
- "cf7cbb8324f0d7882e5d0762fc5b7210eafc2e9adac32ab7aac49693dfbf83724c2ec" +
- "0736ee31c80291";
+ "cf7cbb8324f0d7882e5d0762fc5b7210eafc2e9adac32ab7aac49693dfbf83724c2ec" +
+ "0736ee31c80291";
static BigInteger testP = new BigInteger(pString, 16);
static String gString = "626d027839ea0a13413163a55b4cb500299d5522956ce" +
- "fcb3bff10f399ce2c2e71cb9de5fa24babf58e5b79521925c9cc42e9f6f464b088cc5" +
- "72af53e6d78802";
+ "fcb3bff10f399ce2c2e71cb9de5fa24babf58e5b79521925c9cc42e9f6f464b088cc5" +
+ "72af53e6d78802";
static BigInteger testG = new BigInteger(gString, 16);
static BigInteger testQ = new BigInteger("c773218c737ec8ee993b4f2ded30" +
- "f48edace915f", 16);
+ "f48edace915f", 16);
- static BigInteger testX = new BigInteger("2070b3223dba372fde1c0ffc7b2e" +
- "3b498b260614", 16);
+ static BigInteger testX = new BigInteger("2070b3223dba372fde1c0ffc7b2e" +
+ "3b498b260614", 16);
static String yString = "19131871d75b1612a819f29d78d1b0d7346f7aa77" +
- "bb62a859bfd6c5675da9d212d3a36ef1672ef660b8c7c255cc0ec74858fba33f44c06" +
- "699630a76b030ee333";
+ "bb62a859bfd6c5675da9d212d3a36ef1672ef660b8c7c255cc0ec74858fba33f44c06" +
+ "699630a76b030ee333";
static BigInteger testY = new BigInteger(yString, 16);
/* End test vector values */
private static void debug(String s) {
- if (debug) {
- System.err.println(s);
- }
+ if (debug) {
+ System.err.println(s);
+ }
}
}
diff --git a/pki/base/util/src/netscape/security/provider/DSAKeyFactory.java b/pki/base/util/src/netscape/security/provider/DSAKeyFactory.java
index f2292e34..aa9e72eb 100755
--- a/pki/base/util/src/netscape/security/provider/DSAKeyFactory.java
+++ b/pki/base/util/src/netscape/security/provider/DSAKeyFactory.java
@@ -32,215 +32,205 @@ import java.security.spec.X509EncodedKeySpec;
/**
* This class implements the DSA key factory of the Sun provider.
- *
+ *
* @author Jan Luehe
- *
+ *
* @version 1.8, 97/12/10
- *
+ *
* @since JDK1.2
*/
public class DSAKeyFactory extends KeyFactorySpi {
/**
- * Generates a public key object from the provided key specification
- * (key material).
- *
+ * Generates a public key object from the provided key specification (key
+ * material).
+ *
* @param keySpec the specification (key material) of the public key
- *
+ *
* @return the public key
- *
- * @exception InvalidKeySpecException if the given key specification
- * is inappropriate for this key factory to produce a public key.
+ *
+ * @exception InvalidKeySpecException if the given key specification is
+ * inappropriate for this key factory to produce a public
+ * key.
*/
protected PublicKey engineGeneratePublic(KeySpec keySpec)
- throws InvalidKeySpecException {
- try {
- if (keySpec instanceof DSAPublicKeySpec) {
- DSAPublicKeySpec dsaPubKeySpec = (DSAPublicKeySpec)keySpec;
- return new DSAPublicKey(dsaPubKeySpec.getY(),
- dsaPubKeySpec.getP(),
- dsaPubKeySpec.getQ(),
- dsaPubKeySpec.getG());
-
- } else if (keySpec instanceof X509EncodedKeySpec) {
- return new DSAPublicKey
- (((X509EncodedKeySpec)keySpec).getEncoded());
-
- } else {
- throw new InvalidKeySpecException
- ("Inappropriate key specification");
- }
- } catch (InvalidKeyException e) {
- throw new InvalidKeySpecException
- ("Inappropriate key specification: " + e.getMessage());
- }
+ throws InvalidKeySpecException {
+ try {
+ if (keySpec instanceof DSAPublicKeySpec) {
+ DSAPublicKeySpec dsaPubKeySpec = (DSAPublicKeySpec) keySpec;
+ return new DSAPublicKey(dsaPubKeySpec.getY(),
+ dsaPubKeySpec.getP(),
+ dsaPubKeySpec.getQ(),
+ dsaPubKeySpec.getG());
+
+ } else if (keySpec instanceof X509EncodedKeySpec) {
+ return new DSAPublicKey(((X509EncodedKeySpec) keySpec).getEncoded());
+
+ } else {
+ throw new InvalidKeySpecException("Inappropriate key specification");
+ }
+ } catch (InvalidKeyException e) {
+ throw new InvalidKeySpecException("Inappropriate key specification: " + e.getMessage());
+ }
}
/**
- * Generates a private key object from the provided key specification
- * (key material).
- *
+ * Generates a private key object from the provided key specification (key
+ * material).
+ *
* @param keySpec the specification (key material) of the private key
- *
+ *
* @return the private key
- *
- * @exception InvalidKeySpecException if the given key specification
- * is inappropriate for this key factory to produce a private key.
+ *
+ * @exception InvalidKeySpecException if the given key specification is
+ * inappropriate for this key factory to produce a private
+ * key.
*/
protected PrivateKey engineGeneratePrivate(KeySpec keySpec)
- throws InvalidKeySpecException {
- try {
- if (keySpec instanceof DSAPrivateKeySpec) {
- DSAPrivateKeySpec dsaPrivKeySpec = (DSAPrivateKeySpec)keySpec;
- return new DSAPrivateKey(dsaPrivKeySpec.getX(),
- dsaPrivKeySpec.getP(),
- dsaPrivKeySpec.getQ(),
- dsaPrivKeySpec.getG());
-
- } else if (keySpec instanceof PKCS8EncodedKeySpec) {
- return new DSAPrivateKey
- (((PKCS8EncodedKeySpec)keySpec).getEncoded());
-
- } else {
- throw new InvalidKeySpecException
- ("Inappropriate key specification");
- }
- } catch (InvalidKeyException e) {
- throw new InvalidKeySpecException
- ("Inappropriate key specification: " + e.getMessage());
- }
+ throws InvalidKeySpecException {
+ try {
+ if (keySpec instanceof DSAPrivateKeySpec) {
+ DSAPrivateKeySpec dsaPrivKeySpec = (DSAPrivateKeySpec) keySpec;
+ return new DSAPrivateKey(dsaPrivKeySpec.getX(),
+ dsaPrivKeySpec.getP(),
+ dsaPrivKeySpec.getQ(),
+ dsaPrivKeySpec.getG());
+
+ } else if (keySpec instanceof PKCS8EncodedKeySpec) {
+ return new DSAPrivateKey(((PKCS8EncodedKeySpec) keySpec).getEncoded());
+
+ } else {
+ throw new InvalidKeySpecException("Inappropriate key specification");
+ }
+ } catch (InvalidKeyException e) {
+ throw new InvalidKeySpecException("Inappropriate key specification: " + e.getMessage());
+ }
}
/**
- * Returns a specification (key material) of the given key object
- * in the requested format.
- *
- * @param key the key
- *
+ * Returns a specification (key material) of the given key object in the
+ * requested format.
+ *
+ * @param key the key
+ *
* @param keySpec the requested format in which the key material shall be
- * returned
- *
- * @return the underlying key specification (key material) in the
- * requested format
- *
+ * returned
+ *
+ * @return the underlying key specification (key material) in the requested
+ * format
+ *
* @exception InvalidKeySpecException if the requested key specification is
- * inappropriate for the given key, or the given key cannot be processed
- * (e.g., the given key has an unrecognized algorithm or format).
+ * inappropriate for the given key, or the given key cannot
+ * be processed (e.g., the given key has an unrecognized
+ * algorithm or format).
*/
protected KeySpec engineGetKeySpec(Key key, Class keySpec)
- throws InvalidKeySpecException {
-
- DSAParams params;
-
- try {
-
- if (key instanceof java.security.interfaces.DSAPublicKey) {
-
- // Determine valid key specs
- Class dsaPubKeySpec = Class.forName
- ("java.security.spec.DSAPublicKeySpec");
- Class x509KeySpec = Class.forName
- ("java.security.spec.X509EncodedKeySpec");
-
- if (dsaPubKeySpec.isAssignableFrom(keySpec)) {
- java.security.interfaces.DSAPublicKey dsaPubKey
- = (java.security.interfaces.DSAPublicKey)key;
- params = dsaPubKey.getParams();
- return new DSAPublicKeySpec(dsaPubKey.getY(),
- params.getP(),
- params.getQ(),
- params.getG());
-
- } else if (x509KeySpec.isAssignableFrom(keySpec)) {
- return new X509EncodedKeySpec(key.getEncoded());
-
- } else {
- throw new InvalidKeySpecException
- ("Inappropriate key specification");
- }
-
- } else if (key instanceof java.security.interfaces.DSAPrivateKey) {
-
- // Determine valid key specs
- Class dsaPrivKeySpec = Class.forName
- ("java.security.spec.DSAPrivateKeySpec");
- Class pkcs8KeySpec = Class.forName
- ("java.security.spec.PKCS8EncodedKeySpec");
-
- if (dsaPrivKeySpec.isAssignableFrom(keySpec)) {
- java.security.interfaces.DSAPrivateKey dsaPrivKey
- = (java.security.interfaces.DSAPrivateKey)key;
- params = dsaPrivKey.getParams();
- return new DSAPrivateKeySpec(dsaPrivKey.getX(),
- params.getP(),
- params.getQ(),
- params.getG());
-
- } else if (pkcs8KeySpec.isAssignableFrom(keySpec)) {
- return new PKCS8EncodedKeySpec(key.getEncoded());
-
- } else {
- throw new InvalidKeySpecException
- ("Inappropriate key specification");
- }
-
- } else {
- throw new InvalidKeySpecException("Inappropriate key type");
- }
-
- } catch (ClassNotFoundException e) {
- throw new InvalidKeySpecException
- ("Unsupported key specification: " + e.getMessage());
- }
+ throws InvalidKeySpecException {
+
+ DSAParams params;
+
+ try {
+
+ if (key instanceof java.security.interfaces.DSAPublicKey) {
+
+ // Determine valid key specs
+ Class dsaPubKeySpec = Class.forName
+ ("java.security.spec.DSAPublicKeySpec");
+ Class x509KeySpec = Class.forName
+ ("java.security.spec.X509EncodedKeySpec");
+
+ if (dsaPubKeySpec.isAssignableFrom(keySpec)) {
+ java.security.interfaces.DSAPublicKey dsaPubKey = (java.security.interfaces.DSAPublicKey) key;
+ params = dsaPubKey.getParams();
+ return new DSAPublicKeySpec(dsaPubKey.getY(),
+ params.getP(),
+ params.getQ(),
+ params.getG());
+
+ } else if (x509KeySpec.isAssignableFrom(keySpec)) {
+ return new X509EncodedKeySpec(key.getEncoded());
+
+ } else {
+ throw new InvalidKeySpecException("Inappropriate key specification");
+ }
+
+ } else if (key instanceof java.security.interfaces.DSAPrivateKey) {
+
+ // Determine valid key specs
+ Class dsaPrivKeySpec = Class.forName
+ ("java.security.spec.DSAPrivateKeySpec");
+ Class pkcs8KeySpec = Class.forName
+ ("java.security.spec.PKCS8EncodedKeySpec");
+
+ if (dsaPrivKeySpec.isAssignableFrom(keySpec)) {
+ java.security.interfaces.DSAPrivateKey dsaPrivKey = (java.security.interfaces.DSAPrivateKey) key;
+ params = dsaPrivKey.getParams();
+ return new DSAPrivateKeySpec(dsaPrivKey.getX(),
+ params.getP(),
+ params.getQ(),
+ params.getG());
+
+ } else if (pkcs8KeySpec.isAssignableFrom(keySpec)) {
+ return new PKCS8EncodedKeySpec(key.getEncoded());
+
+ } else {
+ throw new InvalidKeySpecException("Inappropriate key specification");
+ }
+
+ } else {
+ throw new InvalidKeySpecException("Inappropriate key type");
+ }
+
+ } catch (ClassNotFoundException e) {
+ throw new InvalidKeySpecException("Unsupported key specification: " + e.getMessage());
+ }
}
/**
* Translates a key object, whose provider may be unknown or potentially
* untrusted, into a corresponding key object of this key factory.
- *
+ *
* @param key the key whose provider is unknown or untrusted
- *
+ *
* @return the translated key
- *
+ *
* @exception InvalidKeyException if the given key cannot be processed by
- * this key factory.
+ * this key factory.
*/
protected Key engineTranslateKey(Key key) throws InvalidKeyException {
- try {
-
- if (key instanceof java.security.interfaces.DSAPublicKey) {
- // Check if key originates from this factory
- if (key instanceof netscape.security.provider.DSAPublicKey) {
- return key;
- }
- // Convert key to spec
- DSAPublicKeySpec dsaPubKeySpec
- = (DSAPublicKeySpec)engineGetKeySpec
- (key, DSAPublicKeySpec.class);
- // Create key from spec, and return it
- return engineGeneratePublic(dsaPubKeySpec);
-
- } else if (key instanceof java.security.interfaces.DSAPrivateKey) {
- // Check if key originates from this factory
- if (key instanceof netscape.security.provider.DSAPrivateKey) {
- return key;
- }
- // Convert key to spec
- DSAPrivateKeySpec dsaPrivKeySpec
- = (DSAPrivateKeySpec)engineGetKeySpec
- (key, DSAPrivateKeySpec.class);
- // Create key from spec, and return it
- return engineGeneratePrivate(dsaPrivKeySpec);
-
- } else {
- throw new InvalidKeyException("Wrong algorithm type");
- }
-
- } catch (InvalidKeySpecException e) {
- throw new InvalidKeyException("Cannot translate key: "
+ try {
+
+ if (key instanceof java.security.interfaces.DSAPublicKey) {
+ // Check if key originates from this factory
+ if (key instanceof netscape.security.provider.DSAPublicKey) {
+ return key;
+ }
+ // Convert key to spec
+ DSAPublicKeySpec dsaPubKeySpec = (DSAPublicKeySpec) engineGetKeySpec
+ (key, DSAPublicKeySpec.class);
+ // Create key from spec, and return it
+ return engineGeneratePublic(dsaPubKeySpec);
+
+ } else if (key instanceof java.security.interfaces.DSAPrivateKey) {
+ // Check if key originates from this factory
+ if (key instanceof netscape.security.provider.DSAPrivateKey) {
+ return key;
+ }
+ // Convert key to spec
+ DSAPrivateKeySpec dsaPrivKeySpec = (DSAPrivateKeySpec) engineGetKeySpec
+ (key, DSAPrivateKeySpec.class);
+ // Create key from spec, and return it
+ return engineGeneratePrivate(dsaPrivKeySpec);
+
+ } else {
+ throw new InvalidKeyException("Wrong algorithm type");
+ }
+
+ } catch (InvalidKeySpecException e) {
+ throw new InvalidKeyException("Cannot translate key: "
+ e.getMessage());
- }
+ }
}
}
diff --git a/pki/base/util/src/netscape/security/provider/DSAKeyPairGenerator.java b/pki/base/util/src/netscape/security/provider/DSAKeyPairGenerator.java
index 4b781fa1..1e01033a 100644
--- a/pki/base/util/src/netscape/security/provider/DSAKeyPairGenerator.java
+++ b/pki/base/util/src/netscape/security/provider/DSAKeyPairGenerator.java
@@ -37,122 +37,114 @@ import java.util.Hashtable;
import netscape.security.x509.AlgIdDSA;
/**
- * This class generates DSA key parameters and public/private key
- * pairs according to the DSS standard NIST FIPS 186. It uses the
- * updated version of SHA, SHA-1 as described in FIPS 180-1.
- *
+ * This class generates DSA key parameters and public/private key pairs
+ * according to the DSS standard NIST FIPS 186. It uses the updated version of
+ * SHA, SHA-1 as described in FIPS 180-1.
+ *
* @author Benjamin Renaud
- *
+ *
* @version 1.23, 97/12/10
*/
-public class DSAKeyPairGenerator extends KeyPairGenerator
-implements java.security.interfaces.DSAKeyPairGenerator {
-
+public class DSAKeyPairGenerator extends KeyPairGenerator
+ implements java.security.interfaces.DSAKeyPairGenerator {
+
private static Hashtable precomputedParams;
static {
- /* We support precomputed parameter for 512, 768 and 1024 bit
- moduli. In this file we provide both the seed and counter
- value of the generation process for each of these seeds,
- for validation purposes. We also include the test vectors
- from the DSA specification, FIPS 186, and the FIPS 186
- Change No 1, which updates the test vector using SHA-1
- instead of SHA (for both the G function and the message
- hash.
- */
-
- precomputedParams = new Hashtable();
-
- /*
- * L = 512
- * SEED = b869c82b35d70e1b1ff91b28e37a62ecdc34409b
- * counter = 123
- */
- BigInteger p512 =
- new BigInteger("fca682ce8e12caba26efccf7110e526db078b05edecb" +
- "cd1eb4a208f3ae1617ae01f35b91a47e6df63413c5e1" +
- "2ed0899bcd132acd50d99151bdc43ee737592e17", 16);
-
- BigInteger q512 =
- new BigInteger("962eddcc369cba8ebb260ee6b6a126d9346e38c5", 16);
-
- BigInteger g512 =
- new BigInteger("678471b27a9cf44ee91a49c5147db1a9aaf244f05a43" +
- "4d6486931d2d14271b9e35030b71fd73da179069b32e" +
- "2935630e1c2062354d0da20a6c416e50be794ca4", 16);
-
- /*
- * L = 768
- * SEED = 77d0f8c4dad15eb8c4f2f8d6726cefd96d5bb399
- * counter = 263
- */
- BigInteger p768 =
- new BigInteger("e9e642599d355f37c97ffd3567120b8e25c9cd43e" +
- "927b3a9670fbec5d890141922d2c3b3ad24800937" +
- "99869d1e846aab49fab0ad26d2ce6a22219d470bc" +
- "e7d777d4a21fbe9c270b57f607002f3cef8393694" +
- "cf45ee3688c11a8c56ab127a3daf", 16);
-
- BigInteger q768 =
- new BigInteger("9cdbd84c9f1ac2f38d0f80f42ab952e7338bf511",
- 16);
-
- BigInteger g768 =
- new BigInteger("30470ad5a005fb14ce2d9dcd87e38bc7d1b1c5fac" +
- "baecbe95f190aa7a31d23c4dbbcbe06174544401a" +
- "5b2c020965d8c2bd2171d3668445771f74ba084d2" +
- "029d83c1c158547f3a9f1a2715be23d51ae4d3e5a" +
- "1f6a7064f316933a346d3f529252", 16);
-
-
- /*
- * L = 1024
- * SEED = 8d5155894229d5e689ee01e6018a237e2cae64cd
- * counter = 92
- */
- BigInteger p1024 =
- new BigInteger("fd7f53811d75122952df4a9c2eece4e7f611b7523c" +
- "ef4400c31e3f80b6512669455d402251fb593d8d58" +
- "fabfc5f5ba30f6cb9b556cd7813b801d346ff26660" +
- "b76b9950a5a49f9fe8047b1022c24fbba9d7feb7c6" +
- "1bf83b57e7c6a8a6150f04fb83f6d3c51ec3023554" +
- "135a169132f675f3ae2b61d72aeff22203199dd148" +
- "01c7", 16);
-
- BigInteger q1024 =
- new BigInteger("9760508f15230bccb292b982a2eb840bf0581cf5",
- 16);
-
- BigInteger g1024 =
- new BigInteger("f7e1a085d69b3ddecbbcab5c36b857b97994afbbfa" +
- "3aea82f9574c0b3d0782675159578ebad4594fe671" +
- "07108180b449167123e84c281613b7cf09328cc8a6" +
- "e13c167a8b547c8d28e0a3ae1e2bb3a675916ea37f" +
- "0bfa213562f1fb627a01243bcca4f1bea8519089a8" +
- "83dfe15ae59f06928b665e807b552564014c3bfecf" +
- "492a", 16);
-
- try {
- AlgIdDSA alg512 = new AlgIdDSA(p512, q512, g512);
- AlgIdDSA alg768 = new AlgIdDSA(p768, q768, g768);
- AlgIdDSA alg1024 = new AlgIdDSA(p1024, q1024, g1024);
-
- precomputedParams.put(Integer.valueOf(512), alg512);
- precomputedParams.put(Integer.valueOf(768), alg768);
- precomputedParams.put(Integer.valueOf(1024), alg1024);
-
- } catch (Exception e) {
- throw new InternalError("initializing precomputed " +
- "algorithm parameters for Sun DSA");
- }
+ /*
+ * We support precomputed parameter for 512, 768 and 1024 bit moduli. In
+ * this file we provide both the seed and counter value of the
+ * generation process for each of these seeds, for validation purposes.
+ * We also include the test vectors from the DSA specification, FIPS
+ * 186, and the FIPS 186 Change No 1, which updates the test vector
+ * using SHA-1 instead of SHA (for both the G function and the message
+ * hash.
+ */
+
+ precomputedParams = new Hashtable();
+
+ /*
+ * L = 512 SEED = b869c82b35d70e1b1ff91b28e37a62ecdc34409b counter = 123
+ */
+ BigInteger p512 =
+ new BigInteger("fca682ce8e12caba26efccf7110e526db078b05edecb" +
+ "cd1eb4a208f3ae1617ae01f35b91a47e6df63413c5e1" +
+ "2ed0899bcd132acd50d99151bdc43ee737592e17", 16);
+
+ BigInteger q512 =
+ new BigInteger("962eddcc369cba8ebb260ee6b6a126d9346e38c5", 16);
+
+ BigInteger g512 =
+ new BigInteger("678471b27a9cf44ee91a49c5147db1a9aaf244f05a43" +
+ "4d6486931d2d14271b9e35030b71fd73da179069b32e" +
+ "2935630e1c2062354d0da20a6c416e50be794ca4", 16);
+
+ /*
+ * L = 768 SEED = 77d0f8c4dad15eb8c4f2f8d6726cefd96d5bb399 counter = 263
+ */
+ BigInteger p768 =
+ new BigInteger("e9e642599d355f37c97ffd3567120b8e25c9cd43e" +
+ "927b3a9670fbec5d890141922d2c3b3ad24800937" +
+ "99869d1e846aab49fab0ad26d2ce6a22219d470bc" +
+ "e7d777d4a21fbe9c270b57f607002f3cef8393694" +
+ "cf45ee3688c11a8c56ab127a3daf", 16);
+
+ BigInteger q768 =
+ new BigInteger("9cdbd84c9f1ac2f38d0f80f42ab952e7338bf511",
+ 16);
+
+ BigInteger g768 =
+ new BigInteger("30470ad5a005fb14ce2d9dcd87e38bc7d1b1c5fac" +
+ "baecbe95f190aa7a31d23c4dbbcbe06174544401a" +
+ "5b2c020965d8c2bd2171d3668445771f74ba084d2" +
+ "029d83c1c158547f3a9f1a2715be23d51ae4d3e5a" +
+ "1f6a7064f316933a346d3f529252", 16);
+
+ /*
+ * L = 1024 SEED = 8d5155894229d5e689ee01e6018a237e2cae64cd counter = 92
+ */
+ BigInteger p1024 =
+ new BigInteger("fd7f53811d75122952df4a9c2eece4e7f611b7523c" +
+ "ef4400c31e3f80b6512669455d402251fb593d8d58" +
+ "fabfc5f5ba30f6cb9b556cd7813b801d346ff26660" +
+ "b76b9950a5a49f9fe8047b1022c24fbba9d7feb7c6" +
+ "1bf83b57e7c6a8a6150f04fb83f6d3c51ec3023554" +
+ "135a169132f675f3ae2b61d72aeff22203199dd148" +
+ "01c7", 16);
+
+ BigInteger q1024 =
+ new BigInteger("9760508f15230bccb292b982a2eb840bf0581cf5",
+ 16);
+
+ BigInteger g1024 =
+ new BigInteger("f7e1a085d69b3ddecbbcab5c36b857b97994afbbfa" +
+ "3aea82f9574c0b3d0782675159578ebad4594fe671" +
+ "07108180b449167123e84c281613b7cf09328cc8a6" +
+ "e13c167a8b547c8d28e0a3ae1e2bb3a675916ea37f" +
+ "0bfa213562f1fb627a01243bcca4f1bea8519089a8" +
+ "83dfe15ae59f06928b665e807b552564014c3bfecf" +
+ "492a", 16);
+
+ try {
+ AlgIdDSA alg512 = new AlgIdDSA(p512, q512, g512);
+ AlgIdDSA alg768 = new AlgIdDSA(p768, q768, g768);
+ AlgIdDSA alg1024 = new AlgIdDSA(p1024, q1024, g1024);
+
+ precomputedParams.put(Integer.valueOf(512), alg512);
+ precomputedParams.put(Integer.valueOf(768), alg768);
+ precomputedParams.put(Integer.valueOf(1024), alg1024);
+
+ } catch (Exception e) {
+ throw new InternalError("initializing precomputed " +
+ "algorithm parameters for Sun DSA");
+ }
}
-
/* The modulus length */
private int modlen = 1024;
-
+
/* Generate new parameters, even if we have precomputed ones. */
boolean generateNewParameters = false;
@@ -163,242 +155,236 @@ implements java.security.interfaces.DSAKeyPairGenerator {
SecureRandom random;
public DSAKeyPairGenerator() {
- super("DSA");
+ super("DSA");
}
public void initialize(int strength, SecureRandom random) {
- if ((strength < 512) || (strength > 1024) || (strength % 64 != 0)) {
- throw new InvalidParameterException
- ("Modulus size must range from 512 to 1024 "
- + "and be a multiple of 64");
- }
-
- /* Set the random */
- this.random = random;
- if (this.random == null) {
- this.random = new SecureRandom();
- }
-
- this.modlen = strength;
- DSAParams params = null;
-
- /* Find the precomputed parameters, if any */
- if (!generateNewParameters) {
- Integer mod = Integer.valueOf(this.modlen);
- params = (DSAParams)precomputedParams.get(mod);
- }
- if (params != null) {
- setParams(params);
- }
+ if ((strength < 512) || (strength > 1024) || (strength % 64 != 0)) {
+ throw new InvalidParameterException("Modulus size must range from 512 to 1024 "
+ + "and be a multiple of 64");
+ }
+
+ /* Set the random */
+ this.random = random;
+ if (this.random == null) {
+ this.random = new SecureRandom();
+ }
+
+ this.modlen = strength;
+ DSAParams params = null;
+
+ /* Find the precomputed parameters, if any */
+ if (!generateNewParameters) {
+ Integer mod = Integer.valueOf(this.modlen);
+ params = (DSAParams) precomputedParams.get(mod);
+ }
+ if (params != null) {
+ setParams(params);
+ }
}
/**
- * Initializes the DSA key pair generator. If <code>genParams</code>
- * is false, a set of pre-computed parameters is used. In this case,
+ * Initializes the DSA key pair generator. If <code>genParams</code> is
+ * false, a set of pre-computed parameters is used. In this case,
* <code>modelen</code> must be 512, 768, or 1024.
*/
public void initialize(int modlen, boolean genParams, SecureRandom random)
- throws InvalidParameterException {
- if (genParams == false && modlen != 512 && modlen != 768
- && modlen != 1024) {
- throw new InvalidParameterException
- ("No precomputed parameters for requested modulus size "
- + "available");
- }
- this.generateNewParameters = genParams;
- initialize(modlen, random);
+ throws InvalidParameterException {
+ if (genParams == false && modlen != 512 && modlen != 768
+ && modlen != 1024) {
+ throw new InvalidParameterException("No precomputed parameters for requested modulus size "
+ + "available");
+ }
+ this.generateNewParameters = genParams;
+ initialize(modlen, random);
}
/**
* Initializes the DSA object using a DSA parameter object.
- *
+ *
* @param params a fully initialized DSA parameter object.
*/
- public void initialize(DSAParams params, SecureRandom random)
- throws InvalidParameterException {
- initialize(params.getP().bitLength(), random);
- setParams(params);
+ public void initialize(DSAParams params, SecureRandom random)
+ throws InvalidParameterException {
+ initialize(params.getP().bitLength(), random);
+ setParams(params);
}
/**
* Initializes the DSA object using a parameter object.
- *
- * @param params the parameter set to be used to generate
- * the keys.
+ *
+ * @param params the parameter set to be used to generate the keys.
* @param random the source of randomness for this generator.
- *
- * @exception InvalidAlgorithmParameterException if the given parameters
- * are inappropriate for this key pair generator
+ *
+ * @exception InvalidAlgorithmParameterException if the given parameters are
+ * inappropriate for this key pair generator
*/
public void initialize(AlgorithmParameterSpec params, SecureRandom random)
- throws InvalidAlgorithmParameterException {
- if (!(params instanceof DSAParameterSpec)) {
- throw new InvalidAlgorithmParameterException
- ("Inappropriate parameter");
- }
- initialize(((DSAParameterSpec)params).getP().bitLength(),
- random);
- setParams((DSAParameterSpec)params);
+ throws InvalidAlgorithmParameterException {
+ if (!(params instanceof DSAParameterSpec)) {
+ throw new InvalidAlgorithmParameterException("Inappropriate parameter");
+ }
+ initialize(((DSAParameterSpec) params).getP().bitLength(),
+ random);
+ setParams((DSAParameterSpec) params);
}
/**
- * Generates a pair of keys usable by any JavaSecurity compliant
- * DSA implementation.
- *
- * @param rnd the source of random bits from which the random key
- * generation parameters are drawn. In particular, this includes
- * the XSEED parameter.
- *
- * @exception InvalidParameterException if the modulus is not
- * between 512 and 1024.
+ * Generates a pair of keys usable by any JavaSecurity compliant DSA
+ * implementation.
+ *
+ * @param rnd the source of random bits from which the random key generation
+ * parameters are drawn. In particular, this includes the XSEED
+ * parameter.
+ *
+ * @exception InvalidParameterException if the modulus is not between 512
+ * and 1024.
*/
public KeyPair generateKeyPair() {
- // set random if initialize() method has been skipped
- if (this.random == null) {
- this.random = new SecureRandom();
- }
-
- if (presetP == null || presetQ == null || presetG == null ||
- generateNewParameters) {
-
- AlgorithmParameterGenerator dsaParamGen;
-
- try {
- dsaParamGen = AlgorithmParameterGenerator.getInstance("DSA",
- "SUN");
- } catch (NoSuchAlgorithmException e) {
- // this should never happen, because we provide it
- throw new RuntimeException(e.getMessage());
- } catch (NoSuchProviderException e) {
- // this should never happen, because we provide it
- throw new RuntimeException(e.getMessage());
- }
-
- dsaParamGen.init(modlen, random);
-
- DSAParameterSpec dsaParamSpec;
- try {
- dsaParamSpec = (DSAParameterSpec)
- dsaParamGen.generateParameters().getParameterSpec
- (DSAParameterSpec.class);
- } catch (InvalidParameterSpecException e) {
- // this should never happen
- throw new RuntimeException(e.getMessage());
- }
- presetP = dsaParamSpec.getP();
- presetQ = dsaParamSpec.getQ();
- presetG = dsaParamSpec.getG();
- }
-
- return generateKeyPair(presetP, presetQ, presetG, random);
+ // set random if initialize() method has been skipped
+ if (this.random == null) {
+ this.random = new SecureRandom();
+ }
+
+ if (presetP == null || presetQ == null || presetG == null ||
+ generateNewParameters) {
+
+ AlgorithmParameterGenerator dsaParamGen;
+
+ try {
+ dsaParamGen = AlgorithmParameterGenerator.getInstance("DSA",
+ "SUN");
+ } catch (NoSuchAlgorithmException e) {
+ // this should never happen, because we provide it
+ throw new RuntimeException(e.getMessage());
+ } catch (NoSuchProviderException e) {
+ // this should never happen, because we provide it
+ throw new RuntimeException(e.getMessage());
+ }
+
+ dsaParamGen.init(modlen, random);
+
+ DSAParameterSpec dsaParamSpec;
+ try {
+ dsaParamSpec = (DSAParameterSpec)
+ dsaParamGen.generateParameters().getParameterSpec
+ (DSAParameterSpec.class);
+ } catch (InvalidParameterSpecException e) {
+ // this should never happen
+ throw new RuntimeException(e.getMessage());
+ }
+ presetP = dsaParamSpec.getP();
+ presetQ = dsaParamSpec.getQ();
+ presetG = dsaParamSpec.getG();
+ }
+
+ return generateKeyPair(presetP, presetQ, presetG, random);
}
public KeyPair generateKeyPair(BigInteger p, BigInteger q, BigInteger g,
- SecureRandom random) {
+ SecureRandom random) {
+
+ BigInteger x = generateX(random, q);
+ BigInteger y = generateY(x, p, g);
- BigInteger x = generateX(random, q);
- BigInteger y = generateY(x, p, g);
+ try {
+ DSAPublicKey pub = new DSAPublicKey(y, p, q, g);
+ DSAPrivateKey priv = new DSAPrivateKey(x, p, q, g);
- try {
- DSAPublicKey pub = new DSAPublicKey(y, p, q, g);
- DSAPrivateKey priv = new DSAPrivateKey(x, p, q, g);
-
- KeyPair pair = new KeyPair(pub, priv);
- return pair;
+ KeyPair pair = new KeyPair(pub, priv);
+ return pair;
- } catch (InvalidKeyException e) {
- throw new ProviderException(e.getMessage());
- }
+ } catch (InvalidKeyException e) {
+ throw new ProviderException(e.getMessage());
+ }
}
/* Test vectors from the DSA specs. */
private static int[] testXSeed = { 0xbd029bbe, 0x7f51960b, 0xcf9edb2b,
- 0x61f06f0f, 0xeb5a38b6 };
-
- private int[] x_t = { 0x67452301,0xefcdab89,0x98badcfe,
- 0x10325476,0xc3d2e1f0 };
+ 0x61f06f0f, 0xeb5a38b6 };
+
+ private int[] x_t = { 0x67452301, 0xefcdab89, 0x98badcfe,
+ 0x10325476, 0xc3d2e1f0 };
/**
- * Generate the private key component of the key pair using the
- * provided source of random bits. This method uses the random but
- * source passed to generate a seed and then calls the seed-based
- * generateX method.
+ * Generate the private key component of the key pair using the provided
+ * source of random bits. This method uses the random but source passed to
+ * generate a seed and then calls the seed-based generateX method.
*/
private BigInteger generateX(SecureRandom random, BigInteger q) {
- BigInteger x = null;
- while (true) {
- int[] seed = new int[5];
- for (int i = 0; i < 5; i++) {
- seed[i] = random.nextInt();
- }
- x = generateX(seed, q);
- if (x.signum() > 0 && (x.compareTo(q) < 0)) {
- break;
- }
- }
- return x;
+ BigInteger x = null;
+ while (true) {
+ int[] seed = new int[5];
+ for (int i = 0; i < 5; i++) {
+ seed[i] = random.nextInt();
+ }
+ x = generateX(seed, q);
+ if (x.signum() > 0 && (x.compareTo(q) < 0)) {
+ break;
+ }
+ }
+ return x;
}
/**
- * Given a seed, generate the private key component of the key
- * pair. In the terminology used in the DSA specification
- * (FIPS-186) seed is the XSEED quantity.
- *
- * @param seed the seed to use to generate the private key.
+ * Given a seed, generate the private key component of the key pair. In the
+ * terminology used in the DSA specification (FIPS-186) seed is the XSEED
+ * quantity.
+ *
+ * @param seed the seed to use to generate the private key.
*/
BigInteger generateX(int[] seed, BigInteger q) {
- /* Test vector
- int[] tseed = { 0xbd029bbe, 0x7f51960b, 0xcf9edb2b,
- 0x61f06f0f, 0xeb5a38b6 };
- seed = tseed;
- */
- // check out t in the spec.
- int[] t = { 0x67452301, 0xEFCDAB89, 0x98BADCFE,
- 0x10325476, 0xC3D2E1F0 };
- //
-
- int[] tmp = DSA.SHA_7(seed, t);
- byte[] tmpBytes = new byte[tmp.length * 4];
- for (int i = 0; i < tmp.length; i++) {
- int k = tmp[i];
- for (int j = 0; j < 4; j++) {
- tmpBytes[(i * 4) + j] = (byte) (k >>> (24 - (j * 8)));
- }
- }
- BigInteger x = new BigInteger(1, tmpBytes).mod(q);
- return x;
+ /*
+ * Test vector int[] tseed = { 0xbd029bbe, 0x7f51960b, 0xcf9edb2b,
+ * 0x61f06f0f, 0xeb5a38b6 }; seed = tseed;
+ */
+ // check out t in the spec.
+ int[] t = { 0x67452301, 0xEFCDAB89, 0x98BADCFE,
+ 0x10325476, 0xC3D2E1F0 };
+ //
+
+ int[] tmp = DSA.SHA_7(seed, t);
+ byte[] tmpBytes = new byte[tmp.length * 4];
+ for (int i = 0; i < tmp.length; i++) {
+ int k = tmp[i];
+ for (int j = 0; j < 4; j++) {
+ tmpBytes[(i * 4) + j] = (byte) (k >>> (24 - (j * 8)));
+ }
+ }
+ BigInteger x = new BigInteger(1, tmpBytes).mod(q);
+ return x;
}
/**
* Generate the public key component y of the key pair.
- *
+ *
* @param x the private key component.
*
* @param p the base parameter.
*/
BigInteger generateY(BigInteger x, BigInteger p, BigInteger g) {
- BigInteger y = g.modPow(x, p);
- return y;
+ BigInteger y = g.modPow(x, p);
+ return y;
}
-
+
/**
* Set the parameters.
*/
private void setParams(DSAParams params) {
- presetP = params.getP();
- presetQ = params.getQ();
- presetG = params.getG();
+ presetP = params.getP();
+ presetQ = params.getQ();
+ presetG = params.getG();
}
/**
* Set the parameters.
*/
private void setParams(DSAParameterSpec params) {
- presetP = params.getP();
- presetQ = params.getQ();
- presetG = params.getG();
+ presetP = params.getP();
+ presetQ = params.getQ();
+ presetG = params.getG();
}
}
diff --git a/pki/base/util/src/netscape/security/provider/DSAParameterGenerator.java b/pki/base/util/src/netscape/security/provider/DSAParameterGenerator.java
index cec2b97b..bff6452a 100755
--- a/pki/base/util/src/netscape/security/provider/DSAParameterGenerator.java
+++ b/pki/base/util/src/netscape/security/provider/DSAParameterGenerator.java
@@ -46,7 +46,7 @@ import java.security.spec.InvalidParameterSpecException;
*/
public class DSAParameterGenerator extends AlgorithmParameterGeneratorSpi {
-
+
// the modulus length
private int modLen = 1024; // default
@@ -62,239 +62,239 @@ public class DSAParameterGenerator extends AlgorithmParameterGeneratorSpi {
private SHA sha;
public DSAParameterGenerator() {
- this.sha = new SHA();
+ this.sha = new SHA();
}
/**
- * Initializes this parameter generator for a certain strength
- * and source of randomness.
- *
+ * Initializes this parameter generator for a certain strength and source of
+ * randomness.
+ *
* @param strength the strength (size of prime) in bits
* @param random the source of randomness
*/
protected void engineInit(int strength, SecureRandom random) {
- /*
- * Bruce Schneier, "Applied Cryptography", 2nd Edition,
- * Description of DSA:
- * [...] The algorithm uses the following parameter:
- * p=a prime number L bits long, when L ranges from 512 to 1024 and is
- * a multiple of 64. [...]
- */
- if ((strength < 512) || (strength > 1024) || (strength % 64 != 0)) {
- throw new InvalidParameterException
- ("Prime size must range from 512 to 1024 "
- + "and be a multiple of 64");
- }
- this.modLen = strength;
- this.random = random;
+ /*
+ * Bruce Schneier, "Applied Cryptography", 2nd Edition, Description of
+ * DSA: [...] The algorithm uses the following parameter: p=a prime
+ * number L bits long, when L ranges from 512 to 1024 and is a multiple
+ * of 64. [...]
+ */
+ if ((strength < 512) || (strength > 1024) || (strength % 64 != 0)) {
+ throw new InvalidParameterException("Prime size must range from 512 to 1024 "
+ + "and be a multiple of 64");
+ }
+ this.modLen = strength;
+ this.random = random;
}
/**
- * Initializes this parameter generator with a set of
- * algorithm-specific parameter generation values.
- *
+ * Initializes this parameter generator with a set of algorithm-specific
+ * parameter generation values.
+ *
* @param params the set of algorithm-specific parameter generation values
* @param random the source of randomness
- *
+ *
* @exception InvalidAlgorithmParameterException if the given parameter
- * generation values are inappropriate for this parameter generator
+ * generation values are inappropriate for this parameter
+ * generator
*/
protected void engineInit(AlgorithmParameterSpec genParamSpec,
- SecureRandom random)
- throws InvalidAlgorithmParameterException {
- throw new InvalidAlgorithmParameterException("Invalid parameter");
+ SecureRandom random)
+ throws InvalidAlgorithmParameterException {
+ throw new InvalidAlgorithmParameterException("Invalid parameter");
}
/**
* Generates the parameters.
- *
+ *
* @return the new AlgorithmParameters object
*/
protected AlgorithmParameters engineGenerateParameters() {
- AlgorithmParameters algParams = null;
- try {
- if (this.random == null) {
- this.random = new SecureRandom();
- }
-
- BigInteger[] pAndQ = generatePandQ(this.random, this.modLen);
- BigInteger paramP = pAndQ[0];
- BigInteger paramQ = pAndQ[1];
- BigInteger paramG = generateG(paramP, paramQ);
-
- DSAParameterSpec dsaParamSpec = new DSAParameterSpec(paramP,
- paramQ,
- paramG);
- algParams = AlgorithmParameters.getInstance("DSA", "SUN");
- algParams.init(dsaParamSpec);
- } catch (InvalidParameterSpecException e) {
- // this should never happen
- throw new RuntimeException(e.getMessage());
- } catch (NoSuchAlgorithmException e) {
- // this should never happen, because we provide it
- throw new RuntimeException(e.getMessage());
- } catch (NoSuchProviderException e) {
- // this should never happen, because we provide it
- throw new RuntimeException(e.getMessage());
- }
-
- return algParams;
+ AlgorithmParameters algParams = null;
+ try {
+ if (this.random == null) {
+ this.random = new SecureRandom();
+ }
+
+ BigInteger[] pAndQ = generatePandQ(this.random, this.modLen);
+ BigInteger paramP = pAndQ[0];
+ BigInteger paramQ = pAndQ[1];
+ BigInteger paramG = generateG(paramP, paramQ);
+
+ DSAParameterSpec dsaParamSpec = new DSAParameterSpec(paramP,
+ paramQ,
+ paramG);
+ algParams = AlgorithmParameters.getInstance("DSA", "SUN");
+ algParams.init(dsaParamSpec);
+ } catch (InvalidParameterSpecException e) {
+ // this should never happen
+ throw new RuntimeException(e.getMessage());
+ } catch (NoSuchAlgorithmException e) {
+ // this should never happen, because we provide it
+ throw new RuntimeException(e.getMessage());
+ } catch (NoSuchProviderException e) {
+ // this should never happen, because we provide it
+ throw new RuntimeException(e.getMessage());
+ }
+
+ return algParams;
}
/*
- * Generates the prime and subprime parameters for DSA,
- * using the provided source of randomness.
- * This method will generate new seeds until a suitable
- * seed has been found.
- *
- * @param random the source of randomness to generate the
- * seed
- * @param L the size of <code>p</code>, in bits.
- *
+ * Generates the prime and subprime parameters for DSA, using the provided
+ * source of randomness. This method will generate new seeds until a
+ * suitable seed has been found.
+ *
+ * @param random the source of randomness to generate the seed
+ *
+ * @param L the size of <code>p</code>, in bits.
+ *
* @return an array of BigInteger, with <code>p</code> at index 0 and
* <code>q</code> at index 1.
*/
BigInteger[] generatePandQ(SecureRandom random, int L) {
- BigInteger[] result = null;
- byte[] seed = new byte[20];
-
- while(result == null) {
- for (int i = 0; i < 20; i++) {
- seed[i] = (byte)random.nextInt();
- }
- result = generatePandQ(seed, L);
- }
- return result;
+ BigInteger[] result = null;
+ byte[] seed = new byte[20];
+
+ while (result == null) {
+ for (int i = 0; i < 20; i++) {
+ seed[i] = (byte) random.nextInt();
+ }
+ result = generatePandQ(seed, L);
+ }
+ return result;
}
/*
* Generates the prime and subprime parameters for DSA.
- *
+ *
* <p>The seed parameter corresponds to the <code>SEED</code> parameter
- * referenced in the FIPS specification of the DSA algorithm,
- * and L is the size of <code>p</code>, in bits.
- *
+ * referenced in the FIPS specification of the DSA algorithm, and L is the
+ * size of <code>p</code>, in bits.
+ *
* @param seed the seed to generate the parameters
+ *
* @param L the size of <code>p</code>, in bits.
- *
+ *
* @return an array of BigInteger, with <code>p</code> at index 0,
- * <code>q</code> at index 1, the seed at index 2, and the counter value
- * at index 3, or null if the seed does not yield suitable numbers.
+ * <code>q</code> at index 1, the seed at index 2, and the counter value at
+ * index 3, or null if the seed does not yield suitable numbers.
*/
BigInteger[] generatePandQ(byte[] seed, int L) {
- /* Useful variables */
- int g = seed.length * 8;
- int n = (L - 1) / 160;
- int b = (L - 1) % 160;
+ /* Useful variables */
+ int g = seed.length * 8;
+ int n = (L - 1) / 160;
+ int b = (L - 1) % 160;
- BigInteger SEED = new BigInteger(1, seed);
- BigInteger TWOG = TWO.pow(2 * g);
+ BigInteger SEED = new BigInteger(1, seed);
+ BigInteger TWOG = TWO.pow(2 * g);
- /* Step 2 (Step 1 is getting seed). */
- byte[] U1 = SHA(seed);
+ /* Step 2 (Step 1 is getting seed). */
+ byte[] U1 = SHA(seed);
byte[] U2 = SHA(toByteArray((SEED.add(ONE)).mod(TWOG)));
- xor(U1, U2);
- byte[] U = U1;
-
- /* Step 3: For q by setting the msb and lsb to 1 */
- U[0] |= 0x80;
- U[19] |= 1;
- BigInteger q = new BigInteger(1, U);
-
- /* Step 5 */
- if (!q.isProbablePrime(40)) {
- return null;
-
- } else {
- BigInteger V[] = new BigInteger[n + 1];
- BigInteger offset = TWO;
-
- /* Step 6 */
- for (int counter = 0; counter < 4096; counter++) {
-
- /* Step 7 */
- for (int k = 0; k <= n; k++) {
- BigInteger K = BigInteger.valueOf(k);
- BigInteger tmp = (SEED.add(offset).add(K)).mod(TWOG);
- V[k] = new BigInteger(1, SHA(toByteArray(tmp)));
- }
-
- /* Step 8 */
- BigInteger W = V[0];
- for (int i = 1; i < n; i++) {
- W = W.add(V[i].multiply(TWO.pow(i * 160)));
- }
- W = W.add((V[n].mod(TWO.pow(b))).multiply(TWO.pow(n * 160)));
-
- BigInteger TWOLm1 = TWO.pow(L - 1);
- BigInteger X = W.add(TWOLm1);
-
- /* Step 9 */
- BigInteger c = X.mod(q.multiply(TWO));
- BigInteger p = X.subtract(c.subtract(ONE));
-
- /* Step 10 - 13 */
- if (p.compareTo(TWOLm1) > -1 && p.isProbablePrime(15)) {
- BigInteger[] result = {p, q, SEED,
- BigInteger.valueOf(counter)};
- return result;
- }
- offset = offset.add(BigInteger.valueOf(n)).add(ONE);
- }
- return null;
- }
+ xor(U1, U2);
+ byte[] U = U1;
+
+ /* Step 3: For q by setting the msb and lsb to 1 */
+ U[0] |= 0x80;
+ U[19] |= 1;
+ BigInteger q = new BigInteger(1, U);
+
+ /* Step 5 */
+ if (!q.isProbablePrime(40)) {
+ return null;
+
+ } else {
+ BigInteger V[] = new BigInteger[n + 1];
+ BigInteger offset = TWO;
+
+ /* Step 6 */
+ for (int counter = 0; counter < 4096; counter++) {
+
+ /* Step 7 */
+ for (int k = 0; k <= n; k++) {
+ BigInteger K = BigInteger.valueOf(k);
+ BigInteger tmp = (SEED.add(offset).add(K)).mod(TWOG);
+ V[k] = new BigInteger(1, SHA(toByteArray(tmp)));
+ }
+
+ /* Step 8 */
+ BigInteger W = V[0];
+ for (int i = 1; i < n; i++) {
+ W = W.add(V[i].multiply(TWO.pow(i * 160)));
+ }
+ W = W.add((V[n].mod(TWO.pow(b))).multiply(TWO.pow(n * 160)));
+
+ BigInteger TWOLm1 = TWO.pow(L - 1);
+ BigInteger X = W.add(TWOLm1);
+
+ /* Step 9 */
+ BigInteger c = X.mod(q.multiply(TWO));
+ BigInteger p = X.subtract(c.subtract(ONE));
+
+ /* Step 10 - 13 */
+ if (p.compareTo(TWOLm1) > -1 && p.isProbablePrime(15)) {
+ BigInteger[] result = { p, q, SEED,
+ BigInteger.valueOf(counter) };
+ return result;
+ }
+ offset = offset.add(BigInteger.valueOf(n)).add(ONE);
+ }
+ return null;
+ }
}
/*
* Generates the <code>g</code> parameter for DSA.
- *
+ *
* @param p the prime, <code>p</code>.
+ *
* @param q the subprime, <code>q</code>.
- *
+ *
* @param the <code>g</code>
*/
BigInteger generateG(BigInteger p, BigInteger q) {
- BigInteger h = ONE;
- BigInteger pMinusOneOverQ = (p.subtract(ONE)).divide(q);
- BigInteger g = ONE;
- while (g.compareTo(TWO) < 0) {
- g = h.modPow(pMinusOneOverQ, p);
- h = h.add(ONE);
- }
- return g;
+ BigInteger h = ONE;
+ BigInteger pMinusOneOverQ = (p.subtract(ONE)).divide(q);
+ BigInteger g = ONE;
+ while (g.compareTo(TWO) < 0) {
+ g = h.modPow(pMinusOneOverQ, p);
+ h = h.add(ONE);
+ }
+ return g;
}
/*
* Returns the SHA-1 digest of some data
*/
private byte[] SHA(byte[] array) {
- sha.engineReset();
- sha.engineUpdate(array, 0, array.length);
- return sha.engineDigest();
+ sha.engineReset();
+ sha.engineUpdate(array, 0, array.length);
+ return sha.engineDigest();
}
/*
- * Converts the result of a BigInteger.toByteArray call to an exact
- * signed magnitude representation for any positive number.
+ * Converts the result of a BigInteger.toByteArray call to an exact signed
+ * magnitude representation for any positive number.
*/
private byte[] toByteArray(BigInteger bigInt) {
- byte[] result = bigInt.toByteArray();
- if (result[0] == 0) {
- byte[] tmp = new byte[result.length - 1];
- System.arraycopy(result, 1, tmp, 0, tmp.length);
- result = tmp;
- }
- return result;
+ byte[] result = bigInt.toByteArray();
+ if (result[0] == 0) {
+ byte[] tmp = new byte[result.length - 1];
+ System.arraycopy(result, 1, tmp, 0, tmp.length);
+ result = tmp;
+ }
+ return result;
}
/*
* XORs U2 into U1
*/
private void xor(byte[] U1, byte[] U2) {
- for (int i = 0; i < U1.length; i++) {
- U1[i] ^= U2[i];
- }
+ for (int i = 0; i < U1.length; i++) {
+ U1[i] ^= U2[i];
+ }
}
}
diff --git a/pki/base/util/src/netscape/security/provider/DSAParameters.java b/pki/base/util/src/netscape/security/provider/DSAParameters.java
index 70b7fa08..b5e5c462 100755
--- a/pki/base/util/src/netscape/security/provider/DSAParameters.java
+++ b/pki/base/util/src/netscape/security/provider/DSAParameters.java
@@ -29,14 +29,13 @@ import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
/**
- * This class implements the parameter set used by the
- * Digital Signature Algorithm as specified in the FIPS 186
- * standard.
- *
+ * This class implements the parameter set used by the Digital Signature
+ * Algorithm as specified in the FIPS 186 standard.
+ *
* @author Jan Luehe
- *
+ *
* @version 1.8, 97/12/10
- *
+ *
* @since JDK1.2
*/
@@ -51,82 +50,79 @@ public class DSAParameters extends AlgorithmParametersSpi {
// the base (g)
protected BigInteger g;
- protected void engineInit(AlgorithmParameterSpec paramSpec)
- throws InvalidParameterSpecException {
- if (!(paramSpec instanceof DSAParameterSpec)) {
- throw new InvalidParameterSpecException
- ("Inappropriate parameter specification");
- }
- this.p = ((DSAParameterSpec)paramSpec).getP();
- this.q = ((DSAParameterSpec)paramSpec).getQ();
- this.g = ((DSAParameterSpec)paramSpec).getG();
+ protected void engineInit(AlgorithmParameterSpec paramSpec)
+ throws InvalidParameterSpecException {
+ if (!(paramSpec instanceof DSAParameterSpec)) {
+ throw new InvalidParameterSpecException("Inappropriate parameter specification");
+ }
+ this.p = ((DSAParameterSpec) paramSpec).getP();
+ this.q = ((DSAParameterSpec) paramSpec).getQ();
+ this.g = ((DSAParameterSpec) paramSpec).getG();
}
protected void engineInit(byte[] params) throws IOException {
- DerValue encodedParams = new DerValue(params);
+ DerValue encodedParams = new DerValue(params);
- if (encodedParams.tag != DerValue.tag_Sequence) {
- throw new IOException("DSA params parsing error");
- }
+ if (encodedParams.tag != DerValue.tag_Sequence) {
+ throw new IOException("DSA params parsing error");
+ }
- encodedParams.data.reset();
+ encodedParams.data.reset();
- this.p = encodedParams.data.getInteger().toBigInteger();
- this.q = encodedParams.data.getInteger().toBigInteger();
- this.g = encodedParams.data.getInteger().toBigInteger();
+ this.p = encodedParams.data.getInteger().toBigInteger();
+ this.q = encodedParams.data.getInteger().toBigInteger();
+ this.g = encodedParams.data.getInteger().toBigInteger();
- if (encodedParams.data.available() != 0) {
- throw new IOException("encoded params have " +
- encodedParams.data.available() +
- " extra bytes");
- }
+ if (encodedParams.data.available() != 0) {
+ throw new IOException("encoded params have " +
+ encodedParams.data.available() +
+ " extra bytes");
+ }
}
protected void engineInit(byte[] params, String decodingMethod)
- throws IOException {
- engineInit(params);
+ throws IOException {
+ engineInit(params);
}
protected AlgorithmParameterSpec engineGetParameterSpec(Class paramSpec)
- throws InvalidParameterSpecException {
- try {
- Class dsaParamSpec = Class.forName
- ("java.security.spec.DSAParameterSpec");
- if (dsaParamSpec.isAssignableFrom(paramSpec)) {
- return new DSAParameterSpec(this.p, this.q, this.g);
- } else {
- throw new InvalidParameterSpecException
- ("Inappropriate parameter Specification");
- }
- } catch (ClassNotFoundException e) {
- throw new InvalidParameterSpecException
- ("Unsupported parameter specification: " + e.getMessage());
- }
+ throws InvalidParameterSpecException {
+ try {
+ Class dsaParamSpec = Class.forName
+ ("java.security.spec.DSAParameterSpec");
+ if (dsaParamSpec.isAssignableFrom(paramSpec)) {
+ return new DSAParameterSpec(this.p, this.q, this.g);
+ } else {
+ throw new InvalidParameterSpecException("Inappropriate parameter Specification");
+ }
+ } catch (ClassNotFoundException e) {
+ throw new InvalidParameterSpecException("Unsupported parameter specification: " + e.getMessage());
+ }
}
protected byte[] engineGetEncoded() throws IOException {
- DerOutputStream out = new DerOutputStream();
- DerOutputStream bytes = new DerOutputStream();
-
- bytes.putInteger(new BigInt(p.toByteArray()));
- bytes.putInteger(new BigInt(q.toByteArray()));
- bytes.putInteger(new BigInt(g.toByteArray()));
- out.write(DerValue.tag_Sequence, bytes);
- return out.toByteArray();
+ DerOutputStream out = new DerOutputStream();
+ DerOutputStream bytes = new DerOutputStream();
+
+ bytes.putInteger(new BigInt(p.toByteArray()));
+ bytes.putInteger(new BigInt(q.toByteArray()));
+ bytes.putInteger(new BigInt(g.toByteArray()));
+ out.write(DerValue.tag_Sequence, bytes);
+ return out.toByteArray();
}
protected byte[] engineGetEncoded(String encodingMethod)
- throws IOException {
- return engineGetEncoded();
+ throws IOException {
+ return engineGetEncoded();
}
/*
* Returns a formatted string describing the parameters.
*/
protected String engineToString() {
- return "\n\tp: " + new BigInt(p).toString()
- + "\n\tq: " + new BigInt(q).toString()
- + "\n\tg: " + new BigInt(g).toString()
- + "\n";
+ return "\n\tp: " + new BigInt(p).toString()
+ + "\n\tq: " + new BigInt(q).toString()
+ + "\n\tg: " + new BigInt(g).toString()
+ + "\n";
}
}
diff --git a/pki/base/util/src/netscape/security/provider/DSAPrivateKey.java b/pki/base/util/src/netscape/security/provider/DSAPrivateKey.java
index f480ea08..0cfc5e5e 100644
--- a/pki/base/util/src/netscape/security/provider/DSAPrivateKey.java
+++ b/pki/base/util/src/netscape/security/provider/DSAPrivateKey.java
@@ -33,18 +33,18 @@ import netscape.security.x509.AlgIdDSA;
/**
* A PKCS#8 private key for the Digital Signature Algorithm.
- *
+ *
* @author Benjamin Renaud
- *
+ *
* @version 1.47, 97/12/10
- *
+ *
* @see DSAPublicKey
* @see AlgIdDSA
* @see DSA
*/
-public final class DSAPrivateKey extends PKCS8Key
-implements java.security.interfaces.DSAPrivateKey, Serializable {
+public final class DSAPrivateKey extends PKCS8Key
+ implements java.security.interfaces.DSAPrivateKey, Serializable {
/** use serialVersionUID from JDK 1.1. for interoperability */
private static final long serialVersionUID = -3244453684193605938L;
@@ -61,28 +61,28 @@ implements java.security.interfaces.DSAPrivateKey, Serializable {
/**
* Make a DSA private key out of a private key and three parameters.
*/
- public DSAPrivateKey(BigInteger x, BigInteger p,
- BigInteger q, BigInteger g)
- throws InvalidKeyException {
- this.x = x;
- algid = new AlgIdDSA(p, q, g);
-
- try {
- key = new DerValue(DerValue.tag_Integer,
- x.toByteArray()).toByteArray();
- encode();
- } catch (IOException e) {
- throw new InvalidKeyException("could not DER encode x: " +
- e.getMessage());
- }
+ public DSAPrivateKey(BigInteger x, BigInteger p,
+ BigInteger q, BigInteger g)
+ throws InvalidKeyException {
+ this.x = x;
+ algid = new AlgIdDSA(p, q, g);
+
+ try {
+ key = new DerValue(DerValue.tag_Integer,
+ x.toByteArray()).toByteArray();
+ encode();
+ } catch (IOException e) {
+ throw new InvalidKeyException("could not DER encode x: " +
+ e.getMessage());
+ }
}
/**
* Make a DSA private key from its DER encoding (PKCS #8).
*/
public DSAPrivateKey(byte[] encoded) throws InvalidKeyException {
- clearOldKey();
- decode(encoded);
+ clearOldKey();
+ decode(encoded);
}
/**
@@ -90,58 +90,58 @@ implements java.security.interfaces.DSAPrivateKey, Serializable {
* parameters could not be parsed.
*/
public DSAParams getParams() {
- try {
- if (algid instanceof DSAParams) {
- return (DSAParams)algid;
- } else {
- DSAParameterSpec paramSpec;
- AlgorithmParameters algParams = algid.getParameters();
- if (algParams == null) {
- return null;
- }
- paramSpec = (DSAParameterSpec)algParams.getParameterSpec
- (DSAParameterSpec.class);
- return (DSAParams)paramSpec;
- }
- } catch (InvalidParameterSpecException e) {
- return null;
- }
+ try {
+ if (algid instanceof DSAParams) {
+ return (DSAParams) algid;
+ } else {
+ DSAParameterSpec paramSpec;
+ AlgorithmParameters algParams = algid.getParameters();
+ if (algParams == null) {
+ return null;
+ }
+ paramSpec = (DSAParameterSpec) algParams.getParameterSpec
+ (DSAParameterSpec.class);
+ return (DSAParams) paramSpec;
+ }
+ } catch (InvalidParameterSpecException e) {
+ return null;
+ }
}
/**
* Get the raw private key, x, without the parameters.
- *
+ *
*/
public BigInteger getX() {
- return x;
+ return x;
}
private void clearOldKey() {
- int i;
- if (this.encodedKey != null) {
- for (i = 0; i < this.encodedKey.length; i++) {
- this.encodedKey[i] = (byte)0x00;
- }
- }
- if (this.key != null) {
- for (i = 0; i < this.key.length; i++) {
- this.key[i] = (byte)0x00;
- }
- }
+ int i;
+ if (this.encodedKey != null) {
+ for (i = 0; i < this.encodedKey.length; i++) {
+ this.encodedKey[i] = (byte) 0x00;
+ }
+ }
+ if (this.key != null) {
+ for (i = 0; i < this.key.length; i++) {
+ this.key[i] = (byte) 0x00;
+ }
+ }
}
public String toString() {
- return "Sun DSA Private Key \nparameters:" + algid + "\nx: " +
- x.toString(16) + "\n";
+ return "Sun DSA Private Key \nparameters:" + algid + "\nx: " +
+ x.toString(16) + "\n";
}
protected void parseKeyBits() throws InvalidKeyException {
- DerInputStream in = new DerInputStream(key);
+ DerInputStream in = new DerInputStream(key);
- try {
- x = in.getInteger().toBigInteger();
- } catch (IOException e) {
- throw new InvalidKeyException(e.getMessage());
- }
+ try {
+ x = in.getInteger().toBigInteger();
+ } catch (IOException e) {
+ throw new InvalidKeyException(e.getMessage());
+ }
}
}
diff --git a/pki/base/util/src/netscape/security/provider/DSAPublicKey.java b/pki/base/util/src/netscape/security/provider/DSAPublicKey.java
index c3a6896c..bee55c96 100644
--- a/pki/base/util/src/netscape/security/provider/DSAPublicKey.java
+++ b/pki/base/util/src/netscape/security/provider/DSAPublicKey.java
@@ -34,18 +34,18 @@ import netscape.security.x509.X509Key;
/**
* An X.509 public key for the Digital Signature Algorithm.
- *
- * @author Benjamin Renaud
- *
+ *
+ * @author Benjamin Renaud
+ *
* @version 1.52, 97/12/10
- *
+ *
* @see DSAPrivateKey
* @see AlgIdDSA
* @see DSA
*/
-public final class DSAPublicKey extends X509Key
-implements java.security.interfaces.DSAPublicKey, Serializable {
+public final class DSAPublicKey extends X509Key
+ implements java.security.interfaces.DSAPublicKey, Serializable {
/** use serialVersionUID from JDK 1.1. for interoperability */
private static final long serialVersionUID = -2994193307391104133L;
@@ -54,7 +54,7 @@ implements java.security.interfaces.DSAPublicKey, Serializable {
private BigInteger y;
/*
- * Keep this constructor for backwards compatibility with JDK1.1.
+ * Keep this constructor for backwards compatibility with JDK1.1.
*/
public DSAPublicKey() {
}
@@ -63,26 +63,26 @@ implements java.security.interfaces.DSAPublicKey, Serializable {
* Make a DSA public key out of a public key and three parameters.
*/
public DSAPublicKey(BigInteger y, BigInteger p, BigInteger q,
- BigInteger g)
- throws InvalidKeyException {
- this.y = y;
- algid = new AlgIdDSA(p, q, g);
+ BigInteger g)
+ throws InvalidKeyException {
+ this.y = y;
+ algid = new AlgIdDSA(p, q, g);
- try {
- key = new DerValue(DerValue.tag_Integer,
- y.toByteArray()).toByteArray();
- encode();
- } catch (IOException e) {
- throw new InvalidKeyException("could not DER encode y: " +
- e.getMessage());
- }
+ try {
+ key = new DerValue(DerValue.tag_Integer,
+ y.toByteArray()).toByteArray();
+ encode();
+ } catch (IOException e) {
+ throw new InvalidKeyException("could not DER encode y: " +
+ e.getMessage());
+ }
}
/**
* Make a DSA public key from its DER encoding (X.509).
*/
public DSAPublicKey(byte[] encoded) throws InvalidKeyException {
- decode(encoded);
+ decode(encoded);
}
/**
@@ -90,44 +90,44 @@ implements java.security.interfaces.DSAPublicKey, Serializable {
* parameters could not be parsed.
*/
public DSAParams getParams() {
- try {
- if (algid instanceof DSAParams) {
- return (DSAParams)algid;
- } else {
- DSAParameterSpec paramSpec;
- AlgorithmParameters algParams = algid.getParameters();
- if (algParams == null) {
- return null;
- }
- paramSpec = (DSAParameterSpec)algParams.getParameterSpec
- (DSAParameterSpec.class);
- return (DSAParams)paramSpec;
- }
- } catch (InvalidParameterSpecException e) {
- return null;
- }
+ try {
+ if (algid instanceof DSAParams) {
+ return (DSAParams) algid;
+ } else {
+ DSAParameterSpec paramSpec;
+ AlgorithmParameters algParams = algid.getParameters();
+ if (algParams == null) {
+ return null;
+ }
+ paramSpec = (DSAParameterSpec) algParams.getParameterSpec
+ (DSAParameterSpec.class);
+ return (DSAParams) paramSpec;
+ }
+ } catch (InvalidParameterSpecException e) {
+ return null;
+ }
}
-
+
/**
* Get the raw public value, y, without the parameters.
- *
+ *
*/
public BigInteger getY() {
- return y;
+ return y;
}
public String toString() {
return "Sun DSA Public Key\n Parameters:" + algid
- + "\n y:\n" + (new BigInt(y)).toString() + "\n";
+ + "\n y:\n" + (new BigInt(y)).toString() + "\n";
}
protected void parseKeyBits() throws InvalidKeyException {
- try {
- DerInputStream in = new DerInputStream(key);
- y = in.getInteger().toBigInteger();
- } catch (IOException e) {
- throw new InvalidKeyException("Invalid key: y value\n" +
- e.getMessage());
- }
+ try {
+ DerInputStream in = new DerInputStream(key);
+ y = in.getInteger().toBigInteger();
+ } catch (IOException e) {
+ throw new InvalidKeyException("Invalid key: y value\n" +
+ e.getMessage());
+ }
}
}
diff --git a/pki/base/util/src/netscape/security/provider/MD5.java b/pki/base/util/src/netscape/security/provider/MD5.java
index a6adaac2..077db2b9 100644
--- a/pki/base/util/src/netscape/security/provider/MD5.java
+++ b/pki/base/util/src/netscape/security/provider/MD5.java
@@ -21,13 +21,13 @@ import java.security.DigestException;
import java.security.MessageDigestSpi;
/**
- * The MD5 class is used to compute an MD5 message digest over a given
- * buffer of bytes. It is an implementation of the RSA Data Security Inc
- * MD5 algorithim as described in internet RFC 1321.
- *
- * @version 1.24 97/12/10
- * @author Chuck McManis
- * @author Benjamin Renaud
+ * The MD5 class is used to compute an MD5 message digest over a given buffer of
+ * bytes. It is an implementation of the RSA Data Security Inc MD5 algorithim as
+ * described in internet RFC 1321.
+ *
+ * @version 1.24 97/12/10
+ * @author Chuck McManis
+ * @author Benjamin Renaud
*/
public final class MD5 extends MessageDigestSpi implements Cloneable {
@@ -38,7 +38,7 @@ public final class MD5 extends MessageDigestSpi implements Cloneable {
private String algorithm;
private int state[];
- private long count; // bit count AND buffer[] index aid
+ private long count; // bit count AND buffer[] index aid
private byte buffer[];
private int transformBuffer[];
@@ -62,321 +62,316 @@ public final class MD5 extends MessageDigestSpi implements Cloneable {
private static final int MD5_LENGTH = 16;
/**
- * Standard constructor, creates a new MD5 instance, allocates its
- * buffers from the heap.
+ * Standard constructor, creates a new MD5 instance, allocates its buffers
+ * from the heap.
*/
public MD5() {
- init();
+ init();
}
-
-
/* **********************************************************
- * The MD5 Functions. These are copied verbatim from
- * the RFC to insure accuracy. The results of this
- * implementation were checked against the RSADSI version.
+ * The MD5 Functions. These are copied verbatim from the RFC to insure
+ * accuracy. The results of this implementation were checked against the
+ * RSADSI version.
* **********************************************************
*/
private int F(int x, int y, int z) {
- return ((x & y) | ((~x) & z));
+ return ((x & y) | ((~x) & z));
}
private int G(int x, int y, int z) {
- return ((x & z) | (y & (~z)));
+ return ((x & z) | (y & (~z)));
}
private int H(int x, int y, int z) {
- return ((x ^ y) ^ z);
+ return ((x ^ y) ^ z);
}
private int I(int x, int y, int z) {
- return (y ^ (x | (~z)));
+ return (y ^ (x | (~z)));
}
private int rotateLeft(int a, int n) {
- return ((a << n) | (a >>> (32 - n)));
+ return ((a << n) | (a >>> (32 - n)));
}
private int FF(int a, int b, int c, int d, int x, int s, int ac) {
- a += F(b, c, d) + x + ac;
- a = rotateLeft(a, s);
- a += b;
- return a;
+ a += F(b, c, d) + x + ac;
+ a = rotateLeft(a, s);
+ a += b;
+ return a;
}
private int GG(int a, int b, int c, int d, int x, int s, int ac) {
- a += G(b, c, d) + x + ac;
- a = rotateLeft(a, s);
- a += b;
- return a;
+ a += G(b, c, d) + x + ac;
+ a = rotateLeft(a, s);
+ a += b;
+ return a;
}
private int HH(int a, int b, int c, int d, int x, int s, int ac) {
- a += H(b, c, d) + x + ac;
- a = rotateLeft(a, s);
- a += b;
- return a;
+ a += H(b, c, d) + x + ac;
+ a = rotateLeft(a, s);
+ a += b;
+ return a;
}
private int II(int a, int b, int c, int d, int x, int s, int ac) {
- a += I(b, c, d) + x + ac;
- a = rotateLeft(a, s);
- a += b;
- return a;
+ a += I(b, c, d) + x + ac;
+ a = rotateLeft(a, s);
+ a += b;
+ return a;
}
/**
* This is where the functions come together as the generic MD5
- * transformation operation, it is called by update() which is
- * synchronized (to protect transformBuffer). It consumes sixteen
- * bytes from the buffer, beginning at the specified offset.
+ * transformation operation, it is called by update() which is synchronized
+ * (to protect transformBuffer). It consumes sixteen bytes from the buffer,
+ * beginning at the specified offset.
*/
void transform(byte buf[], int offset) {
- int a, b, c, d;
- int x[] = transformBuffer;
-
- a = state[0];
- b = state[1];
- c = state[2];
- d = state[3];
-
- for (int i = 0; i < 16; i++) {
- x[i] = (int)buf[i*4+offset] & 0xff;
- for (int j = 1; j < 4; j++) {
- x[i] += ((int)buf[i*4+j+offset] & 0xff) << (j * 8);
- }
- }
-
- /* Round 1 */
- a = FF ( a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
- d = FF ( d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
- c = FF ( c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
- b = FF ( b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
- a = FF ( a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
- d = FF ( d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
- c = FF ( c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
- b = FF ( b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
- a = FF ( a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
- d = FF ( d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
- c = FF ( c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
- b = FF ( b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
- a = FF ( a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
- d = FF ( d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
- c = FF ( c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
- b = FF ( b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
-
- /* Round 2 */
- a = GG ( a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
- d = GG ( d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
- c = GG ( c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
- b = GG ( b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
- a = GG ( a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
- d = GG ( d, a, b, c, x[10], S22, 0x2441453); /* 22 */
- c = GG ( c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
- b = GG ( b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
- a = GG ( a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
- d = GG ( d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
- c = GG ( c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
- b = GG ( b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
- a = GG ( a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
- d = GG ( d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
- c = GG ( c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
- b = GG ( b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
-
- /* Round 3 */
- a = HH ( a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
- d = HH ( d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
- c = HH ( c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
- b = HH ( b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
- a = HH ( a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
- d = HH ( d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
- c = HH ( c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
- b = HH ( b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
- a = HH ( a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
- d = HH ( d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
- c = HH ( c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
- b = HH ( b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */
- a = HH ( a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
- d = HH ( d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
- c = HH ( c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
- b = HH ( b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */
-
- /* Round 4 */
- a = II ( a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
- d = II ( d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
- c = II ( c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
- b = II ( b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
- a = II ( a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
- d = II ( d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
- c = II ( c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
- b = II ( b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
- a = II ( a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
- d = II ( d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
- c = II ( c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
- b = II ( b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
- a = II ( a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
- d = II ( d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
- c = II ( c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
- b = II ( b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */
-
- state[0] += a;
- state[1] += b;
- state[2] += c;
- state[3] += d;
+ int a, b, c, d;
+ int x[] = transformBuffer;
+
+ a = state[0];
+ b = state[1];
+ c = state[2];
+ d = state[3];
+
+ for (int i = 0; i < 16; i++) {
+ x[i] = (int) buf[i * 4 + offset] & 0xff;
+ for (int j = 1; j < 4; j++) {
+ x[i] += ((int) buf[i * 4 + j + offset] & 0xff) << (j * 8);
+ }
+ }
+
+ /* Round 1 */
+ a = FF(a, b, c, d, x[0], S11, 0xd76aa478); /* 1 */
+ d = FF(d, a, b, c, x[1], S12, 0xe8c7b756); /* 2 */
+ c = FF(c, d, a, b, x[2], S13, 0x242070db); /* 3 */
+ b = FF(b, c, d, a, x[3], S14, 0xc1bdceee); /* 4 */
+ a = FF(a, b, c, d, x[4], S11, 0xf57c0faf); /* 5 */
+ d = FF(d, a, b, c, x[5], S12, 0x4787c62a); /* 6 */
+ c = FF(c, d, a, b, x[6], S13, 0xa8304613); /* 7 */
+ b = FF(b, c, d, a, x[7], S14, 0xfd469501); /* 8 */
+ a = FF(a, b, c, d, x[8], S11, 0x698098d8); /* 9 */
+ d = FF(d, a, b, c, x[9], S12, 0x8b44f7af); /* 10 */
+ c = FF(c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
+ b = FF(b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
+ a = FF(a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
+ d = FF(d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
+ c = FF(c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
+ b = FF(b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
+
+ /* Round 2 */
+ a = GG(a, b, c, d, x[1], S21, 0xf61e2562); /* 17 */
+ d = GG(d, a, b, c, x[6], S22, 0xc040b340); /* 18 */
+ c = GG(c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
+ b = GG(b, c, d, a, x[0], S24, 0xe9b6c7aa); /* 20 */
+ a = GG(a, b, c, d, x[5], S21, 0xd62f105d); /* 21 */
+ d = GG(d, a, b, c, x[10], S22, 0x2441453); /* 22 */
+ c = GG(c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
+ b = GG(b, c, d, a, x[4], S24, 0xe7d3fbc8); /* 24 */
+ a = GG(a, b, c, d, x[9], S21, 0x21e1cde6); /* 25 */
+ d = GG(d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
+ c = GG(c, d, a, b, x[3], S23, 0xf4d50d87); /* 27 */
+ b = GG(b, c, d, a, x[8], S24, 0x455a14ed); /* 28 */
+ a = GG(a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
+ d = GG(d, a, b, c, x[2], S22, 0xfcefa3f8); /* 30 */
+ c = GG(c, d, a, b, x[7], S23, 0x676f02d9); /* 31 */
+ b = GG(b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
+
+ /* Round 3 */
+ a = HH(a, b, c, d, x[5], S31, 0xfffa3942); /* 33 */
+ d = HH(d, a, b, c, x[8], S32, 0x8771f681); /* 34 */
+ c = HH(c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
+ b = HH(b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
+ a = HH(a, b, c, d, x[1], S31, 0xa4beea44); /* 37 */
+ d = HH(d, a, b, c, x[4], S32, 0x4bdecfa9); /* 38 */
+ c = HH(c, d, a, b, x[7], S33, 0xf6bb4b60); /* 39 */
+ b = HH(b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
+ a = HH(a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
+ d = HH(d, a, b, c, x[0], S32, 0xeaa127fa); /* 42 */
+ c = HH(c, d, a, b, x[3], S33, 0xd4ef3085); /* 43 */
+ b = HH(b, c, d, a, x[6], S34, 0x4881d05); /* 44 */
+ a = HH(a, b, c, d, x[9], S31, 0xd9d4d039); /* 45 */
+ d = HH(d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
+ c = HH(c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
+ b = HH(b, c, d, a, x[2], S34, 0xc4ac5665); /* 48 */
+
+ /* Round 4 */
+ a = II(a, b, c, d, x[0], S41, 0xf4292244); /* 49 */
+ d = II(d, a, b, c, x[7], S42, 0x432aff97); /* 50 */
+ c = II(c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
+ b = II(b, c, d, a, x[5], S44, 0xfc93a039); /* 52 */
+ a = II(a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
+ d = II(d, a, b, c, x[3], S42, 0x8f0ccc92); /* 54 */
+ c = II(c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
+ b = II(b, c, d, a, x[1], S44, 0x85845dd1); /* 56 */
+ a = II(a, b, c, d, x[8], S41, 0x6fa87e4f); /* 57 */
+ d = II(d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
+ c = II(c, d, a, b, x[6], S43, 0xa3014314); /* 59 */
+ b = II(b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
+ a = II(a, b, c, d, x[4], S41, 0xf7537e82); /* 61 */
+ d = II(d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
+ c = II(c, d, a, b, x[2], S43, 0x2ad7d2bb); /* 63 */
+ b = II(b, c, d, a, x[9], S44, 0xeb86d391); /* 64 */
+
+ state[0] += a;
+ state[1] += b;
+ state[2] += c;
+ state[3] += d;
}
/**
- * Initialize the MD5 state information and reset the bit count
- * to 0. Given this implementation you are constrained to counting
- * 2^64 bits.
+ * Initialize the MD5 state information and reset the bit count to 0. Given
+ * this implementation you are constrained to counting 2^64 bits.
*/
public void init() {
- state = new int[4];
- transformBuffer = new int[16];
- buffer = new byte[64];
- digestBits = new byte[16];
- count = 0;
- // Load magic initialization constants.
- state[0] = 0x67452301;
- state[1] = 0xefcdab89;
- state[2] = 0x98badcfe;
- state[3] = 0x10325476;
- for (int i = 0; i < digestBits.length; i++)
- digestBits[i] = 0;
+ state = new int[4];
+ transformBuffer = new int[16];
+ buffer = new byte[64];
+ digestBits = new byte[16];
+ count = 0;
+ // Load magic initialization constants.
+ state[0] = 0x67452301;
+ state[1] = 0xefcdab89;
+ state[2] = 0x98badcfe;
+ state[3] = 0x10325476;
+ for (int i = 0; i < digestBits.length; i++)
+ digestBits[i] = 0;
}
protected void engineReset() {
- init();
+ init();
}
/**
* Return the digest length in bytes
*/
protected int engineGetDigestLength() {
- return (MD5_LENGTH);
+ return (MD5_LENGTH);
}
/**
* Update adds the passed byte to the digested data.
*/
protected synchronized void engineUpdate(byte b) {
- int index;
-
- index = (int) ((count >>> 3) & 0x3f);
- count += 8;
- buffer[index] = b;
- if (index >= 63) {
- transform(buffer, 0);
- }
+ int index;
+
+ index = (int) ((count >>> 3) & 0x3f);
+ count += 8;
+ buffer[index] = b;
+ if (index >= 63) {
+ transform(buffer, 0);
+ }
}
/**
- * Update adds the selected part of an array of bytes to the digest.
- * This version is more efficient than the byte-at-a-time version;
- * it avoids data copies and reduces per-byte call overhead.
+ * Update adds the selected part of an array of bytes to the digest. This
+ * version is more efficient than the byte-at-a-time version; it avoids data
+ * copies and reduces per-byte call overhead.
*/
protected synchronized void engineUpdate(byte input[], int offset,
- int len) {
- int i;
-
- for (i = offset; len > 0; ) {
- int index = (int) ((count >>> 3) & 0x3f);
-
- if (index == 0 && len > 64) {
- count += (64 * 8);
- transform (input, i);
- len -= 64;
- i += 64;
- } else {
- count += 8;
- buffer[index] = input [i];
- if (index >= 63)
- transform (buffer, 0);
- i++;
- len--;
- }
- }
+ int len) {
+ int i;
+
+ for (i = offset; len > 0;) {
+ int index = (int) ((count >>> 3) & 0x3f);
+
+ if (index == 0 && len > 64) {
+ count += (64 * 8);
+ transform(input, i);
+ len -= 64;
+ i += 64;
+ } else {
+ count += 8;
+ buffer[index] = input[i];
+ if (index >= 63)
+ transform(buffer, 0);
+ i++;
+ len--;
+ }
+ }
}
/**
- * Perform the final computations, any buffered bytes are added
- * to the digest, the count is added to the digest, and the resulting
- * digest is stored. After calling final you will need to call
- * init() again to do another digest.
+ * Perform the final computations, any buffered bytes are added to the
+ * digest, the count is added to the digest, and the resulting digest is
+ * stored. After calling final you will need to call init() again to do
+ * another digest.
*/
private void finish() {
- byte bits[] = new byte[8];
- byte padding[];
- int i, index, padLen;
-
- for (i = 0; i < 8; i++) {
- bits[i] = (byte)((count >>> (i * 8)) & 0xff);
- }
-
- index = (int)(count >> 3) & 0x3f;
- padLen = (index < 56) ? (56 - index) : (120 - index);
- padding = new byte[padLen];
- padding[0] = (byte) 0x80;
- engineUpdate(padding, 0, padding.length);
- engineUpdate(bits, 0, bits.length);
-
- for (i = 0; i < 4; i++) {
- for (int j = 0; j < 4; j++) {
- digestBits[i*4+j] = (byte)((state[i] >>> (j * 8)) & 0xff);
- }
- }
+ byte bits[] = new byte[8];
+ byte padding[];
+ int i, index, padLen;
+
+ for (i = 0; i < 8; i++) {
+ bits[i] = (byte) ((count >>> (i * 8)) & 0xff);
+ }
+
+ index = (int) (count >> 3) & 0x3f;
+ padLen = (index < 56) ? (56 - index) : (120 - index);
+ padding = new byte[padLen];
+ padding[0] = (byte) 0x80;
+ engineUpdate(padding, 0, padding.length);
+ engineUpdate(bits, 0, bits.length);
+
+ for (i = 0; i < 4; i++) {
+ for (int j = 0; j < 4; j++) {
+ digestBits[i * 4 + j] = (byte) ((state[i] >>> (j * 8)) & 0xff);
+ }
+ }
}
/**
*/
protected byte[] engineDigest() {
- finish();
-
- byte[] result = new byte[MD5_LENGTH];
- System.arraycopy(digestBits, 0, result, 0, MD5_LENGTH);
+ finish();
+
+ byte[] result = new byte[MD5_LENGTH];
+ System.arraycopy(digestBits, 0, result, 0, MD5_LENGTH);
- init();
+ init();
- return result;
+ return result;
}
/**
*/
protected int engineDigest(byte[] buf, int offset, int len)
- throws DigestException {
- finish();
-
- if (len < MD5_LENGTH)
- throw new DigestException("partial digests not returned");
- if (buf.length - offset < MD5_LENGTH)
- throw new DigestException("insufficient space in the output " +
- "buffer to store the digest");
-
- System.arraycopy(digestBits, 0, buf, offset, MD5_LENGTH);
-
- init();
-
- return MD5_LENGTH;
+ throws DigestException {
+ finish();
+
+ if (len < MD5_LENGTH)
+ throw new DigestException("partial digests not returned");
+ if (buf.length - offset < MD5_LENGTH)
+ throw new DigestException("insufficient space in the output " +
+ "buffer to store the digest");
+
+ System.arraycopy(digestBits, 0, buf, offset, MD5_LENGTH);
+
+ init();
+
+ return MD5_LENGTH;
}
/*
* Clones this object.
*/
public Object clone() {
- MD5 that = null;
- try {
- that = (MD5)super.clone();
- that.state = (int[])this.state.clone();
- that.transformBuffer = (int[])this.transformBuffer.clone();
- that.buffer = (byte[])this.buffer.clone();
- that.digestBits = (byte[])this.digestBits.clone();
- that.count = this.count;
- return that;
- } catch (CloneNotSupportedException e) {
- }
- return that;
+ MD5 that = null;
+ try {
+ that = (MD5) super.clone();
+ that.state = (int[]) this.state.clone();
+ that.transformBuffer = (int[]) this.transformBuffer.clone();
+ that.buffer = (byte[]) this.buffer.clone();
+ that.digestBits = (byte[]) this.digestBits.clone();
+ that.count = this.count;
+ return that;
+ } catch (CloneNotSupportedException e) {
+ }
+ return that;
}
}
-
-
diff --git a/pki/base/util/src/netscape/security/provider/RSAPublicKey.java b/pki/base/util/src/netscape/security/provider/RSAPublicKey.java
index 4f5ec46b..b70d9f94 100644
--- a/pki/base/util/src/netscape/security/provider/RSAPublicKey.java
+++ b/pki/base/util/src/netscape/security/provider/RSAPublicKey.java
@@ -31,122 +31,122 @@ import netscape.security.x509.X509Key;
/**
* An X.509 public key for the RSA Algorithm.
- *
+ *
* @author galperin
- *
+ *
* @version $Revision$, $Date$
- *
+ *
*/
public final class RSAPublicKey extends X509Key implements Serializable {
- /* XXX This currently understands only PKCS#1 RSA Encryption OID
- and parameter format
- Later we may consider adding X509v3 OID for RSA keys. Besides
- different OID it also has a parameter equal to modulus size
- in bits (redundant!)
- */
+ /*
+ * XXX This currently understands only PKCS#1 RSA Encryption OID and
+ * parameter format Later we may consider adding X509v3 OID for RSA keys.
+ * Besides different OID it also has a parameter equal to modulus size in
+ * bits (redundant!)
+ */
- /**
+ /**
*
*/
private static final long serialVersionUID = 7764823589128565374L;
-private static final ObjectIdentifier ALGORITHM_OID =
- AlgorithmId.RSAEncryption_oid;
-
- private BigInt modulus;
- private BigInt publicExponent;
-
+ private static final ObjectIdentifier ALGORITHM_OID =
+ AlgorithmId.RSAEncryption_oid;
+
+ private BigInt modulus;
+ private BigInt publicExponent;
+
/*
- * Keep this constructor for backwards compatibility with JDK1.1.
+ * Keep this constructor for backwards compatibility with JDK1.1.
*/
- public RSAPublicKey() {
- }
+ public RSAPublicKey() {
+ }
/**
* Make a RSA public key out of a public exponent and modulus
*/
- public RSAPublicKey(BigInt modulus, BigInt publicExponent)
- throws InvalidKeyException {
- this.modulus = modulus;
- this.publicExponent = publicExponent;
- this.algid = new AlgorithmId(ALGORITHM_OID);
-
- try {
- DerOutputStream out = new DerOutputStream ();
-
- out.putInteger (modulus);
- out.putInteger (publicExponent);
- key = (new DerValue(DerValue.tag_Sequence,
- out.toByteArray())).toByteArray();
- encode();
- } catch (IOException ex) {
- throw new InvalidKeyException("could not DER encode : " +
- ex.getMessage());
- }
- }
-
+ public RSAPublicKey(BigInt modulus, BigInt publicExponent)
+ throws InvalidKeyException {
+ this.modulus = modulus;
+ this.publicExponent = publicExponent;
+ this.algid = new AlgorithmId(ALGORITHM_OID);
+
+ try {
+ DerOutputStream out = new DerOutputStream();
+
+ out.putInteger(modulus);
+ out.putInteger(publicExponent);
+ key = (new DerValue(DerValue.tag_Sequence,
+ out.toByteArray())).toByteArray();
+ encode();
+ } catch (IOException ex) {
+ throw new InvalidKeyException("could not DER encode : " +
+ ex.getMessage());
+ }
+ }
+
/**
* Make a RSA public key from its DER encoding (X.509).
*/
- public RSAPublicKey(byte[] encoded) throws InvalidKeyException {
- decode(encoded);
- }
-
+ public RSAPublicKey(byte[] encoded) throws InvalidKeyException {
+ decode(encoded);
+ }
+
/**
- * Get key size as number of bits in modulus
- * (Always rounded up to a multiple of 8)
- *
+ * Get key size as number of bits in modulus (Always rounded up to a
+ * multiple of 8)
+ *
*/
- public int getKeySize() {
- return this.modulus.byteLength() * 8;
- }
-
+ public int getKeySize() {
+ return this.modulus.byteLength() * 8;
+ }
+
/**
* Get the raw public exponent
- *
+ *
*/
- public BigInt getPublicExponent() {
- return this.publicExponent;
- }
-
+ public BigInt getPublicExponent() {
+ return this.publicExponent;
+ }
+
/**
* Get the raw modulus
- *
+ *
*/
- public BigInt getModulus() {
- return this.modulus;
- }
-
- public String toString() {
- return "RSA Public Key\n Algorithm: " + algid
- + "\n modulus:\n" + this.modulus.toString() + "\n"
- + "\n publicExponent:\n" + this.publicExponent.toString()
- + "\n";
- }
-
- protected void parseKeyBits() throws InvalidKeyException {
- if (!this.algid.getOID().equals(ALGORITHM_OID) &&
- !this.algid.getOID().equals(AlgorithmId.RSA_oid)) {
- throw new InvalidKeyException("Key algorithm OID is not RSA");
- }
-
- try {
- DerValue val = new DerValue (key);
- if (val.tag != DerValue.tag_Sequence) {
- throw new InvalidKeyException("Invalid RSA public key format:" +
- " must be a SEQUENCE");
- }
-
- DerInputStream in = val.data;
-
- this.modulus = in.getInteger();
- this.publicExponent = in.getInteger();
- } catch (IOException e) {
- throw new InvalidKeyException("Invalid RSA public key: " +
- e.getMessage());
- }
- }
-
+ public BigInt getModulus() {
+ return this.modulus;
+ }
+
+ public String toString() {
+ return "RSA Public Key\n Algorithm: " + algid
+ + "\n modulus:\n" + this.modulus.toString() + "\n"
+ + "\n publicExponent:\n" + this.publicExponent.toString()
+ + "\n";
+ }
+
+ protected void parseKeyBits() throws InvalidKeyException {
+ if (!this.algid.getOID().equals(ALGORITHM_OID) &&
+ !this.algid.getOID().equals(AlgorithmId.RSA_oid)) {
+ throw new InvalidKeyException("Key algorithm OID is not RSA");
+ }
+
+ try {
+ DerValue val = new DerValue(key);
+ if (val.tag != DerValue.tag_Sequence) {
+ throw new InvalidKeyException("Invalid RSA public key format:" +
+ " must be a SEQUENCE");
+ }
+
+ DerInputStream in = val.data;
+
+ this.modulus = in.getInteger();
+ this.publicExponent = in.getInteger();
+ } catch (IOException e) {
+ throw new InvalidKeyException("Invalid RSA public key: " +
+ e.getMessage());
+ }
+ }
+
}
diff --git a/pki/base/util/src/netscape/security/provider/SHA.java b/pki/base/util/src/netscape/security/provider/SHA.java
index 6e4bf51e..709fa48d 100644
--- a/pki/base/util/src/netscape/security/provider/SHA.java
+++ b/pki/base/util/src/netscape/security/provider/SHA.java
@@ -21,26 +21,28 @@ import java.security.DigestException;
import java.security.MessageDigestSpi;
/**
- * This class implements the Secure Hash Algorithm (SHA) developed by
- * the National Institute of Standards and Technology along with the
- * National Security Agency. This is the updated version of SHA
- * fip-180 as superseded by fip-180-1.
- *
- * <p>It implement JavaSecurity MessageDigest, and can be used by in
- * the Java Security framework, as a pluggable implementation, as a
- * filter for the digest stream classes.
+ * This class implements the Secure Hash Algorithm (SHA) developed by the
+ * National Institute of Standards and Technology along with the National
+ * Security Agency. This is the updated version of SHA fip-180 as superseded by
+ * fip-180-1.
*
- * @version 1.30 97/12/10
- * @author Roger Riggs
- * @author Benjamin Renaud
+ * <p>
+ * It implement JavaSecurity MessageDigest, and can be used by in the Java
+ * Security framework, as a pluggable implementation, as a filter for the digest
+ * stream classes.
+ *
+ * @version 1.30 97/12/10
+ * @author Roger Riggs
+ * @author Benjamin Renaud
*/
public class SHA extends MessageDigestSpi implements Cloneable {
- /* This private hookm controlled by the appropriate constructor,
- causes this class to implement the first version of SHA,
- as defined in FIPS 180, as opposed to FIPS 180-1. This was
- useful for DSA testing. */
+ /*
+ * This private hookm controlled by the appropriate constructor, causes this
+ * class to implement the first version of SHA, as defined in FIPS 180, as
+ * opposed to FIPS 180-1. This was useful for DSA testing.
+ */
private int version = 1;
private static final int SHA_LENGTH = 20;
@@ -52,199 +54,202 @@ public class SHA extends MessageDigestSpi implements Cloneable {
private int W[] = new int[80];
private long count = 0;
private final int countmax = 64;
- private final int countmask = (countmax-1);
+ private final int countmask = (countmax - 1);
private int AA, BB, CC, DD, EE;
SHA(int version) {
- this();
- this.version = version;
+ this();
+ this.version = version;
}
/**
* Creates a new SHA object.
*/
public SHA() {
- init();
+ init();
}
/**
* Return the length of the digest in bytes
*/
protected int engineGetDigestLength() {
- return (SHA_LENGTH);
+ return (SHA_LENGTH);
}
public void engineUpdate(byte b) {
- engineUpdate((int)b);
+ engineUpdate((int) b);
}
/**
* Update a byte.
- *
- * @param b the byte
+ *
+ * @param b the byte
*/
- private void engineUpdate(int b) {
- int word;
- int offset;
-
- /* compute word offset and bit offset within word the low bits
- of count are inverted to make put the bytes in the write
- order */
- word = ((int)count & countmask) >>> 2;
- offset = (~(int)count & 3) << 3;
-
- W[word] = (W[word] & ~(0xff << offset)) | ((b & 0xff) << offset);
-
- /* If this is the last byte of a block, compute the partial hash */
- if (((int)count & countmask) == countmask) {
- computeBlock();
- }
- count++;
+ private void engineUpdate(int b) {
+ int word;
+ int offset;
+
+ /*
+ * compute word offset and bit offset within word the low bits of count
+ * are inverted to make put the bytes in the write order
+ */
+ word = ((int) count & countmask) >>> 2;
+ offset = (~(int) count & 3) << 3;
+
+ W[word] = (W[word] & ~(0xff << offset)) | ((b & 0xff) << offset);
+
+ /* If this is the last byte of a block, compute the partial hash */
+ if (((int) count & countmask) == countmask) {
+ computeBlock();
+ }
+ count++;
}
-
+
/**
* Update a buffer.
- *
- * @param b the data to be updated.
- * @param off the start offset in the data
- * @param len the number of bytes to be updated.
+ *
+ * @param b the data to be updated.
+ * @param off the start offset in the data
+ * @param len the number of bytes to be updated.
*/
public void engineUpdate(byte b[], int off, int len) {
- int word;
- int offset;
-
- if ((off < 0) || (len < 0) || (off + len > b.length))
- throw new ArrayIndexOutOfBoundsException();
-
- // Use single writes until integer aligned
- while ((len > 0) &&
- ((int)count & 3) != 0) {
- engineUpdate(b[off]);
- off++;
- len--;
- }
-
- /* Assemble groups of 4 bytes to be inserted in integer array */
- for (;len >= 4; len -= 4, off += 4) {
-
- word = ((int)count & countmask) >> 2;
-
- W[word] = ((b[off] & 0xff) << 24) |
- ((b[off+1] & 0xff) << 16) |
- ((b[off+2] & 0xff) << 8) |
- ((b[off+3] & 0xff) );
-
- count += 4;
- if (((int)count & countmask) == 0) {
- computeBlock();
- }
- }
-
- /* Use single writes for last few bytes */
- for (; len > 0; len--, off++) {
- engineUpdate(b[off]);
- }
+ int word;
+ int offset;
+
+ if ((off < 0) || (len < 0) || (off + len > b.length))
+ throw new ArrayIndexOutOfBoundsException();
+
+ // Use single writes until integer aligned
+ while ((len > 0) &&
+ ((int) count & 3) != 0) {
+ engineUpdate(b[off]);
+ off++;
+ len--;
+ }
+
+ /* Assemble groups of 4 bytes to be inserted in integer array */
+ for (; len >= 4; len -= 4, off += 4) {
+
+ word = ((int) count & countmask) >> 2;
+
+ W[word] = ((b[off] & 0xff) << 24) |
+ ((b[off + 1] & 0xff) << 16) |
+ ((b[off + 2] & 0xff) << 8) |
+ ((b[off + 3] & 0xff));
+
+ count += 4;
+ if (((int) count & countmask) == 0) {
+ computeBlock();
+ }
+ }
+
+ /* Use single writes for last few bytes */
+ for (; len > 0; len--, off++) {
+ engineUpdate(b[off]);
+ }
}
-
+
/**
* Resets the buffers and hash value to start a new hash.
*/
public void init() {
- AA = 0x67452301;
- BB = 0xefcdab89;
- CC = 0x98badcfe;
- DD = 0x10325476;
- EE = 0xc3d2e1f0;
-
- for (int i = 0; i < 80; i++)
- W[i] = 0;
- count = 0;
+ AA = 0x67452301;
+ BB = 0xefcdab89;
+ CC = 0x98badcfe;
+ DD = 0x10325476;
+ EE = 0xc3d2e1f0;
+
+ for (int i = 0; i < 80; i++)
+ W[i] = 0;
+ count = 0;
}
/**
* Resets the buffers and hash value to start a new hash.
*/
public void engineReset() {
- init();
+ init();
}
-
+
/**
- * Computes the final hash and returns the final value as a
- * byte[20] array. The object is reset to be ready for further
- * use, as specified in the JavaSecurity MessageDigest
- * specification. */
+ * Computes the final hash and returns the final value as a byte[20] array.
+ * The object is reset to be ready for further use, as specified in the
+ * JavaSecurity MessageDigest specification.
+ */
public byte[] engineDigest() {
- byte hashvalue[] = new byte[SHA_LENGTH];
-
- try {
- int outLen = engineDigest(hashvalue, 0, hashvalue.length);
- } catch (DigestException e) {
- throw new InternalError("");
- }
- return hashvalue;
+ byte hashvalue[] = new byte[SHA_LENGTH];
+
+ try {
+ int outLen = engineDigest(hashvalue, 0, hashvalue.length);
+ } catch (DigestException e) {
+ throw new InternalError("");
+ }
+ return hashvalue;
}
/**
- * Computes the final hash and returns the final value as a
- * byte[20] array. The object is reset to be ready for further
- * use, as specified in the JavaSecurity MessageDigest
- * specification. */
+ * Computes the final hash and returns the final value as a byte[20] array.
+ * The object is reset to be ready for further use, as specified in the
+ * JavaSecurity MessageDigest specification.
+ */
public int engineDigest(byte[] hashvalue, int offset, int len)
- throws DigestException {
-
- if (len < SHA_LENGTH)
- throw new DigestException("partial digests not returned");
- if (hashvalue.length - offset < SHA_LENGTH)
- throw new DigestException("insufficient space in the output " +
- "buffer to store the digest");
-
- /* The number of bits before padding occurs */
- long bits = count << 3;
-
- engineUpdate(0x80);
-
- /* Pad with zeros until length is a multiple of 448 (the last two
- 32 ints are used a holder for bits (see above). */
- while ((int)(count & countmask) != 56) {
- engineUpdate(0);
- }
-
- W[14] = (int)(bits >>> 32);
- W[15] = (int)(bits & 0xffffffff);
-
- count += 8;
- computeBlock();
-
- // Copy out the result
- hashvalue[offset + 0] = (byte)(AA >>> 24);
- hashvalue[offset + 1] = (byte)(AA >>> 16);
- hashvalue[offset + 2] = (byte)(AA >>> 8);
- hashvalue[offset + 3] = (byte)(AA >>> 0);
-
- hashvalue[offset + 4] = (byte)(BB >>> 24);
- hashvalue[offset + 5] = (byte)(BB >>> 16);
- hashvalue[offset + 6] = (byte)(BB >>> 8);
- hashvalue[offset + 7] = (byte)(BB >>> 0);
-
- hashvalue[offset + 8] = (byte)(CC >>> 24);
- hashvalue[offset + 9] = (byte)(CC >>> 16);
- hashvalue[offset + 10] = (byte)(CC >>> 8);
- hashvalue[offset + 11] = (byte)(CC >>> 0);
-
- hashvalue[offset + 12] = (byte)(DD >>> 24);
- hashvalue[offset + 13] = (byte)(DD >>> 16);
- hashvalue[offset + 14] = (byte)(DD >>> 8);
- hashvalue[offset + 15] = (byte)(DD >>> 0);
-
- hashvalue[offset + 16] = (byte)(EE >>> 24);
- hashvalue[offset + 17] = (byte)(EE >>> 16);
- hashvalue[offset + 18] = (byte)(EE >>> 8);
- hashvalue[offset + 19] = (byte)(EE >>> 0);
-
- engineReset(); // remove the evidence
-
- return SHA_LENGTH;
+ throws DigestException {
+
+ if (len < SHA_LENGTH)
+ throw new DigestException("partial digests not returned");
+ if (hashvalue.length - offset < SHA_LENGTH)
+ throw new DigestException("insufficient space in the output " +
+ "buffer to store the digest");
+
+ /* The number of bits before padding occurs */
+ long bits = count << 3;
+
+ engineUpdate(0x80);
+
+ /*
+ * Pad with zeros until length is a multiple of 448 (the last two 32
+ * ints are used a holder for bits (see above).
+ */
+ while ((int) (count & countmask) != 56) {
+ engineUpdate(0);
+ }
+
+ W[14] = (int) (bits >>> 32);
+ W[15] = (int) (bits & 0xffffffff);
+
+ count += 8;
+ computeBlock();
+
+ // Copy out the result
+ hashvalue[offset + 0] = (byte) (AA >>> 24);
+ hashvalue[offset + 1] = (byte) (AA >>> 16);
+ hashvalue[offset + 2] = (byte) (AA >>> 8);
+ hashvalue[offset + 3] = (byte) (AA >>> 0);
+
+ hashvalue[offset + 4] = (byte) (BB >>> 24);
+ hashvalue[offset + 5] = (byte) (BB >>> 16);
+ hashvalue[offset + 6] = (byte) (BB >>> 8);
+ hashvalue[offset + 7] = (byte) (BB >>> 0);
+
+ hashvalue[offset + 8] = (byte) (CC >>> 24);
+ hashvalue[offset + 9] = (byte) (CC >>> 16);
+ hashvalue[offset + 10] = (byte) (CC >>> 8);
+ hashvalue[offset + 11] = (byte) (CC >>> 0);
+
+ hashvalue[offset + 12] = (byte) (DD >>> 24);
+ hashvalue[offset + 13] = (byte) (DD >>> 16);
+ hashvalue[offset + 14] = (byte) (DD >>> 8);
+ hashvalue[offset + 15] = (byte) (DD >>> 0);
+
+ hashvalue[offset + 16] = (byte) (EE >>> 24);
+ hashvalue[offset + 17] = (byte) (EE >>> 16);
+ hashvalue[offset + 18] = (byte) (EE >>> 8);
+ hashvalue[offset + 19] = (byte) (EE >>> 0);
+
+ engineReset(); // remove the evidence
+
+ return SHA_LENGTH;
}
// Constants for each round
@@ -255,95 +260,94 @@ public class SHA extends MessageDigestSpi implements Cloneable {
/**
* Compute a the hash for the current block.
- *
- * This is in the same vein as Peter Gutmann's algorithm listed in
- * the back of Applied Cryptography, Compact implementation of
- * "old" NIST Secure Hash Algorithm.
- *
+ *
+ * This is in the same vein as Peter Gutmann's algorithm listed in the back
+ * of Applied Cryptography, Compact implementation of "old" NIST Secure Hash
+ * Algorithm.
+ *
*/
private void computeBlock() {
- int temp, a, b, c, d, e;
-
- // The first 16 ints have the byte stream, compute the rest of
- // the buffer
- for (int t = 16; t <= 79; t++) {
- if (version == 0) {
- W[t] = W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16];
- } else {
- temp = W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16];
- W[t] = ((temp << 1) | (temp >>>(32 - 1)));
- }
- }
-
- a = AA;
- b = BB;
- c = CC;
- d = DD;
- e = EE;
-
- // Round 1
- for (int i = 0; i < 20; i++) {
- temp = ((a<<5) | (a>>>(32-5))) +
- ((b&c)|((~b)&d))+ e + W[i] + round1_kt;
- e = d;
- d = c;
- c = ((b<<30) | (b>>>(32-30)));
- b = a;
- a = temp;
- }
-
- // Round 2
- for (int i = 20; i < 40; i++) {
- temp = ((a<<5) | (a>>>(32-5))) +
- (b ^ c ^ d) + e + W[i] + round2_kt;
- e = d;
- d = c;
- c = ((b<<30) | (b>>>(32-30)));
- b = a;
- a = temp;
- }
-
- // Round 3
- for (int i = 40; i < 60; i++) {
- temp = ((a<<5) | (a>>>(32-5))) +
- ((b&c)|(b&d)|(c&d)) + e + W[i] + round3_kt;
- e = d;
- d = c;
- c = ((b<<30) | (b>>>(32-30)));
- b = a;
- a = temp;
- }
-
- // Round 4
- for (int i = 60; i < 80; i++) {
- temp = ((a<<5) | (a>>>(32-5))) +
- (b ^ c ^ d) + e + W[i] + round4_kt;
- e = d;
- d = c;
- c = ((b<<30) | (b>>>(32-30)));
- b = a;
- a = temp;
- }
- AA += a;
- BB += b;
- CC += c;
- DD += d;
- EE += e;
+ int temp, a, b, c, d, e;
+
+ // The first 16 ints have the byte stream, compute the rest of
+ // the buffer
+ for (int t = 16; t <= 79; t++) {
+ if (version == 0) {
+ W[t] = W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16];
+ } else {
+ temp = W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16];
+ W[t] = ((temp << 1) | (temp >>> (32 - 1)));
+ }
+ }
+
+ a = AA;
+ b = BB;
+ c = CC;
+ d = DD;
+ e = EE;
+
+ // Round 1
+ for (int i = 0; i < 20; i++) {
+ temp = ((a << 5) | (a >>> (32 - 5))) +
+ ((b & c) | ((~b) & d)) + e + W[i] + round1_kt;
+ e = d;
+ d = c;
+ c = ((b << 30) | (b >>> (32 - 30)));
+ b = a;
+ a = temp;
+ }
+
+ // Round 2
+ for (int i = 20; i < 40; i++) {
+ temp = ((a << 5) | (a >>> (32 - 5))) +
+ (b ^ c ^ d) + e + W[i] + round2_kt;
+ e = d;
+ d = c;
+ c = ((b << 30) | (b >>> (32 - 30)));
+ b = a;
+ a = temp;
+ }
+
+ // Round 3
+ for (int i = 40; i < 60; i++) {
+ temp = ((a << 5) | (a >>> (32 - 5))) +
+ ((b & c) | (b & d) | (c & d)) + e + W[i] + round3_kt;
+ e = d;
+ d = c;
+ c = ((b << 30) | (b >>> (32 - 30)));
+ b = a;
+ a = temp;
+ }
+
+ // Round 4
+ for (int i = 60; i < 80; i++) {
+ temp = ((a << 5) | (a >>> (32 - 5))) +
+ (b ^ c ^ d) + e + W[i] + round4_kt;
+ e = d;
+ d = c;
+ c = ((b << 30) | (b >>> (32 - 30)));
+ b = a;
+ a = temp;
+ }
+ AA += a;
+ BB += b;
+ CC += c;
+ DD += d;
+ EE += e;
}
/*
* Clones this object.
*/
public Object clone() {
- SHA that = null;
- try {
- that = (SHA)super.clone();
- that.W = new int[80];
- System.arraycopy(this.W, 0, that.W, 0, W.length);
- return that;
- } catch (CloneNotSupportedException e) {
- }
- return that;
+ SHA that = null;
+ try {
+ that = (SHA) super.clone();
+ that.W = new int[80];
+ System.arraycopy(this.W, 0, that.W, 0, W.length);
+ return that;
+ } catch (CloneNotSupportedException e) {
+ }
+ return that;
}
}
-
diff --git a/pki/base/util/src/netscape/security/provider/Sun.java b/pki/base/util/src/netscape/security/provider/Sun.java
index 36ef60d5..0af650a1 100644
--- a/pki/base/util/src/netscape/security/provider/Sun.java
+++ b/pki/base/util/src/netscape/security/provider/Sun.java
@@ -29,27 +29,25 @@ import java.security.Provider;
/**
* Defines the SUN provider.
- *
+ *
* Algorithm supported, and their names:
- *
- * - SHA-1 is the message digest scheme decribed FIPS 180-1.
- * Aliases for SHA-1 are SHA.
- *
- * - DSA is the signature scheme described in FIPS 186. (SHA used in
- * DSA is SHA-1: FIPS 186 with Change No 1.) Aliases for DSA are
- * SHA/DSA, SHA-1/DSA, SHA1/DSA, DSS and the object identifier
- * strings "OID.1.3.14.3.2.13", "OID.1.3.14.3.2.27" and
- * "OID.1.2.840.10040.4.3".
- *
- * - DSA is the key generation scheme as described in FIPS 186.
- * Aliases for DSA include the OID strings "OID.1.3.14.3.2.12"
- * and "OID.1.2.840.10040.4.1".
- *
- * - MD5 is the message digest scheme described in RFC 1321.
- * There are no aliases for MD5.
- *
- * Notes: The name of algorithm described in FIPS-180 is SHA-0, and is
- * not supported by the SUN provider.)
+ *
+ * - SHA-1 is the message digest scheme decribed FIPS 180-1. Aliases for SHA-1
+ * are SHA.
+ *
+ * - DSA is the signature scheme described in FIPS 186. (SHA used in DSA is
+ * SHA-1: FIPS 186 with Change No 1.) Aliases for DSA are SHA/DSA, SHA-1/DSA,
+ * SHA1/DSA, DSS and the object identifier strings "OID.1.3.14.3.2.13",
+ * "OID.1.3.14.3.2.27" and "OID.1.2.840.10040.4.3".
+ *
+ * - DSA is the key generation scheme as described in FIPS 186. Aliases for DSA
+ * include the OID strings "OID.1.3.14.3.2.12" and "OID.1.2.840.10040.4.1".
+ *
+ * - MD5 is the message digest scheme described in RFC 1321. There are no
+ * aliases for MD5.
+ *
+ * Notes: The name of algorithm described in FIPS-180 is SHA-0, and is not
+ * supported by the SUN provider.)
*/
public final class Sun extends Provider {
@@ -57,20 +55,20 @@ public final class Sun extends Provider {
*
*/
private static final long serialVersionUID = 9134942296334703727L;
- private static String info = "SUN Security Provider v1.0, " +
- "DSA signing and key generation, SHA-1 and MD5 message digests.";
+ private static String info = "SUN Security Provider v1.0, " +
+ "DSA signing and key generation, SHA-1 and MD5 message digests.";
public Sun() {
- /* We are the SUN provider */
- super("SUN", 1.0, info);
+ /* We are the SUN provider */
+ super("SUN", 1.0, info);
- try {
+ try {
-// AccessController.beginPrivileged();
+ // AccessController.beginPrivileged();
- /*
- * Signature engines
- */
+ /*
+ * Signature engines
+ */
put("Signature.DSA", "netscape.security.provider.DSA");
put("Alg.Alias.Signature.SHA/DSA", "DSA");
@@ -88,11 +86,11 @@ public final class Sun extends Provider {
put("Alg.Alias.Signature.SHAwithDSA", "DSA");
put("Alg.Alias.Signature.SHA1withDSA", "DSA");
- /*
- * Key Pair Generator engines
- */
- put("KeyPairGenerator.DSA",
- "netscape.security.provider.DSAKeyPairGenerator");
+ /*
+ * Key Pair Generator engines
+ */
+ put("KeyPairGenerator.DSA",
+ "netscape.security.provider.DSAKeyPairGenerator");
put("Alg.Alias.KeyPairGenerator.OID.1.3.14.3.2.12", "DSA");
put("Alg.Alias.KeyPairGenerator.OID.1.2.840.10040.4.1", "DSA");
@@ -101,35 +99,35 @@ public final class Sun extends Provider {
put("Alg.Alias.KeyPairGenerator.1.3.14.3.2.12", "DSA");
put("Alg.Alias.KeyPairGenerator.1.2.840.10040.4.1", "DSA");
- /*
- * Digest engines
- */
- put("MessageDigest.MD5", "netscape.security.provider.MD5");
- put("MessageDigest.SHA-1", "netscape.security.provider.SHA");
-
- put("Alg.Alias.MessageDigest.SHA", "SHA-1");
- put("Alg.Alias.MessageDigest.SHA1", "SHA-1");
+ /*
+ * Digest engines
+ */
+ put("MessageDigest.MD5", "netscape.security.provider.MD5");
+ put("MessageDigest.SHA-1", "netscape.security.provider.SHA");
+
+ put("Alg.Alias.MessageDigest.SHA", "SHA-1");
+ put("Alg.Alias.MessageDigest.SHA1", "SHA-1");
/*
* Algorithm Parameter Generator engines
*/
- put("AlgorithmParameterGenerator.DSA",
- "netscape.security.provider.DSAParameterGenerator");
+ put("AlgorithmParameterGenerator.DSA",
+ "netscape.security.provider.DSAParameterGenerator");
/*
* Algorithm Parameter engines
*/
- put("AlgorithmParameters.DSA",
- "netscape.security.provider.DSAParameters");
+ put("AlgorithmParameters.DSA",
+ "netscape.security.provider.DSAParameters");
put("Alg.Alias.AlgorithmParameters.1.3.14.3.2.12", "DSA");
put("Alg.Alias.AlgorithmParameters.1.2.840.10040.4.1", "DSA");
- /*
- * Key factories
- */
- put("KeyFactory.DSA", "netscape.security.provider.DSAKeyFactory");
-
- } finally {
-// AccessController.endPrivileged();
- }
+ /*
+ * Key factories
+ */
+ put("KeyFactory.DSA", "netscape.security.provider.DSAKeyFactory");
+
+ } finally {
+ // AccessController.endPrivileged();
+ }
}
}
diff --git a/pki/base/util/src/netscape/security/provider/SystemIdentity.java b/pki/base/util/src/netscape/security/provider/SystemIdentity.java
index e9fadf26..37f70788 100644
--- a/pki/base/util/src/netscape/security/provider/SystemIdentity.java
+++ b/pki/base/util/src/netscape/security/provider/SystemIdentity.java
@@ -27,9 +27,9 @@ import java.security.PublicKey;
/**
* An identity.
- *
- * @version 1.19, 09/12/97
- * @author Benjamin Renaud
+ *
+ * @version 1.19, 09/12/97
+ * @author Benjamin Renaud
*/
public class SystemIdentity extends Identity implements Serializable {
@@ -43,38 +43,38 @@ public class SystemIdentity extends Identity implements Serializable {
/* This exists only for serialization bc and don't use it! */
private boolean trusted = false;
- public SystemIdentity(String name, IdentityScope scope)
- throws InvalidParameterException, KeyManagementException {
- super(name, scope);
+ public SystemIdentity(String name, IdentityScope scope)
+ throws InvalidParameterException, KeyManagementException {
+ super(name, scope);
}
void setIdentityInfo(String info) {
- super.setInfo(info);
+ super.setInfo(info);
}
String getIndentityInfo() {
- return super.getInfo();
+ return super.getInfo();
}
/**
* Call back method into a protected method for package friends.
*/
void setIdentityPublicKey(PublicKey key) throws KeyManagementException {
- setPublicKey(key);
+ setPublicKey(key);
}
/**
* Call back method into a protected method for package friends.
*/
- void addIdentityCertificate(Certificate cert)
- throws KeyManagementException {
- addCertificate(cert);
+ void addIdentityCertificate(Certificate cert)
+ throws KeyManagementException {
+ addCertificate(cert);
}
void clearCertificates() throws KeyManagementException {
- Certificate[] certs = certificates();
- for (int i = 0; i < certs.length; i++) {
- removeCertificate(certs[i]);
- }
+ Certificate[] certs = certificates();
+ for (int i = 0; i < certs.length; i++) {
+ removeCertificate(certs[i]);
+ }
}
}
diff --git a/pki/base/util/src/netscape/security/provider/SystemSigner.java b/pki/base/util/src/netscape/security/provider/SystemSigner.java
index 3b5be37e..cf9a78cc 100644
--- a/pki/base/util/src/netscape/security/provider/SystemSigner.java
+++ b/pki/base/util/src/netscape/security/provider/SystemSigner.java
@@ -28,9 +28,10 @@ import java.security.Signer;
/**
* SunSecurity signer.
- *
- * @version 1.24, 09/12/97
- * @author Benjamin Renaud */
+ *
+ * @version 1.24, 09/12/97
+ * @author Benjamin Renaud
+ */
public class SystemSigner extends Signer {
/** use serialVersionUID from JDK 1.1. for interoperability */
@@ -39,52 +40,52 @@ public class SystemSigner extends Signer {
/* This exists only for serialization bc and don't use it! */
private boolean trusted = false;
- /**
+ /**
* Construct a signer with a given name.
*/
public SystemSigner(String name) {
- super(name);
+ super(name);
}
- /**
+ /**
* Construct a signer with a name and a scope.
- *
+ *
* @param name the signer's name.
- *
+ *
* @param scope the scope for this signer.
*/
public SystemSigner(String name, IdentityScope scope)
- throws KeyManagementException {
+ throws KeyManagementException {
- super(name, scope);
+ super(name, scope);
}
/* friendly callback for set keys */
- void setSignerKeyPair(KeyPair pair)
- throws InvalidParameterException, KeyException {
- setKeyPair(pair);
+ void setSignerKeyPair(KeyPair pair)
+ throws InvalidParameterException, KeyException {
+ setKeyPair(pair);
}
/* friendly callback for getting private keys */
PrivateKey getSignerPrivateKey() {
- return getPrivateKey();
+ return getPrivateKey();
}
void setSignerInfo(String s) {
- setInfo(s);
+ setInfo(s);
}
-
+
/**
* Call back method into a protected method for package friends.
*/
void addSignerCertificate(Certificate cert) throws KeyManagementException {
- addCertificate(cert);
+ addCertificate(cert);
}
void clearCertificates() throws KeyManagementException {
- Certificate[] certs = certificates();
- for (int i = 0; i < certs.length; i++) {
- removeCertificate(certs[i]);
- }
+ Certificate[] certs = certificates();
+ for (int i = 0; i < certs.length; i++) {
+ removeCertificate(certs[i]);
+ }
}
}
diff --git a/pki/base/util/src/netscape/security/provider/X509CertificateFactory.java b/pki/base/util/src/netscape/security/provider/X509CertificateFactory.java
index 8e21350b..9780983a 100644
--- a/pki/base/util/src/netscape/security/provider/X509CertificateFactory.java
+++ b/pki/base/util/src/netscape/security/provider/X509CertificateFactory.java
@@ -29,33 +29,33 @@ import netscape.security.x509.X509CRLImpl;
import netscape.security.x509.X509CertImpl;
import netscape.security.x509.X509ExtensionException;
-public class X509CertificateFactory extends CertificateFactorySpi {
+public class X509CertificateFactory extends CertificateFactorySpi {
+
+ public Certificate engineGenerateCertificate(InputStream inStream)
+ throws CertificateException {
+ return new X509CertImpl(inStream);
+ }
- public Certificate engineGenerateCertificate(InputStream inStream)
- throws CertificateException {
- return new X509CertImpl(inStream);
- }
public Collection<Certificate> engineGenerateCertificates(InputStream inStream)
- throws CertificateException {
- return null;
- }
-
- public CRL engineGenerateCRL(InputStream inStream)
- throws CRLException {
- X509CRLImpl crl = null;
- try {
- crl = new X509CRLImpl(inStream);
- }
- catch (X509ExtensionException e) {
- ;
- }
-
- return crl;
- }
-
- public Collection<CRL> engineGenerateCRLs(InputStream inStream)
- throws CRLException {
- return null;
- }
-
+ throws CertificateException {
+ return null;
+ }
+
+ public CRL engineGenerateCRL(InputStream inStream)
+ throws CRLException {
+ X509CRLImpl crl = null;
+ try {
+ crl = new X509CRLImpl(inStream);
+ } catch (X509ExtensionException e) {
+ ;
+ }
+
+ return crl;
+ }
+
+ public Collection<CRL> engineGenerateCRLs(InputStream inStream)
+ throws CRLException {
+ return null;
+ }
+
}
diff --git a/pki/base/util/src/netscape/security/util/ASN1CharStrConvMap.java b/pki/base/util/src/netscape/security/util/ASN1CharStrConvMap.java
index da0fd45c..d9efcb87 100644
--- a/pki/base/util/src/netscape/security/util/ASN1CharStrConvMap.java
+++ b/pki/base/util/src/netscape/security/util/ASN1CharStrConvMap.java
@@ -29,146 +29,139 @@ import sun.io.CharToByteUTF8;
* Maps a ASN.1 character string type to a CharToByte and ByteToChar converter.
* The converter is used to convert a DerValue of a ASN.1 character string type
* from bytes to unicode characters and vice versa.
- *
- * <p>A global default ASN1CharStrConvMap is created when the class is
- * initialized. The global default map is extensible.
- *
+ *
+ * <p>
+ * A global default ASN1CharStrConvMap is created when the class is initialized.
+ * The global default map is extensible.
+ *
* @author Lily Hsiao
* @author Slava Galperin
- *
+ *
*/
-public class ASN1CharStrConvMap
-{
+public class ASN1CharStrConvMap {
// public constructors
/**
* Constructs a ASN1CharStrConvMap.
*/
- public ASN1CharStrConvMap()
- {
+ public ASN1CharStrConvMap() {
}
/**
* Get a Character to Byte converter for the specified DER tag.
- *
- * @param tag A DER tag of a ASN.1 character string type,
- * for example DerValue.tag_PrintableString.
- *
- * @return A CharToByteConverter for the DER tag.
- *
- * @exception InstantiationException
- * if error occurs when instantiating the CharToByteConverter.
- * @exception IllegalAccessException
- * if error occurs when loading the CharToByteConverter class.
+ *
+ * @param tag A DER tag of a ASN.1 character string type, for example
+ * DerValue.tag_PrintableString.
+ *
+ * @return A CharToByteConverter for the DER tag.
+ *
+ * @exception InstantiationException if error occurs when instantiating the
+ * CharToByteConverter.
+ * @exception IllegalAccessException if error occurs when loading the
+ * CharToByteConverter class.
*/
public CharToByteConverter getCBC(byte tag)
- throws IllegalAccessException, InstantiationException
- {
- Byte tagObj = Byte.valueOf(tag);
- CharToByteConverter cbc = null;
- Class<CharToByteConverter> cbcClass;
- cbcClass = (Class<CharToByteConverter>)tag2CBC.get(tagObj);
- if (cbcClass == null)
- return null;
- cbc = (CharToByteConverter)cbcClass.newInstance();
- cbc.setSubstitutionMode(false);
- return cbc;
+ throws IllegalAccessException, InstantiationException {
+ Byte tagObj = Byte.valueOf(tag);
+ CharToByteConverter cbc = null;
+ Class<CharToByteConverter> cbcClass;
+ cbcClass = (Class<CharToByteConverter>) tag2CBC.get(tagObj);
+ if (cbcClass == null)
+ return null;
+ cbc = (CharToByteConverter) cbcClass.newInstance();
+ cbc.setSubstitutionMode(false);
+ return cbc;
}
/**
* Get a Byte to Character converter for the given DER tag.
- *
- * @param tag A DER tag of a ASN.1 character string type,
- * for example DerValue.tag_PrintableString.
- *
- * @return A ByteToCharConverter for the DER tag.
- *
- * @exception InstantiationException
- * if error occurs when instantiationg the ByteToCharConverter.
- * @exception IllegalAccessException
- * if error occurs when loading the ByteToCharConverter class.
+ *
+ * @param tag A DER tag of a ASN.1 character string type, for example
+ * DerValue.tag_PrintableString.
+ *
+ * @return A ByteToCharConverter for the DER tag.
+ *
+ * @exception InstantiationException if error occurs when instantiationg the
+ * ByteToCharConverter.
+ * @exception IllegalAccessException if error occurs when loading the
+ * ByteToCharConverter class.
*/
public ByteToCharConverter getBCC(byte tag)
- throws IllegalAccessException, InstantiationException
- {
- Byte tagObj = Byte.valueOf(tag);
- ByteToCharConverter bcc = null;
- Class<ByteToCharConverter> bccClass = tag2BCC.get(tagObj);
- if (bccClass == null)
- return null;
- bcc = (ByteToCharConverter)bccClass.newInstance();
- bcc.setSubstitutionMode(false);
- return bcc;
+ throws IllegalAccessException, InstantiationException {
+ Byte tagObj = Byte.valueOf(tag);
+ ByteToCharConverter bcc = null;
+ Class<ByteToCharConverter> bccClass = tag2BCC.get(tagObj);
+ if (bccClass == null)
+ return null;
+ bcc = (ByteToCharConverter) bccClass.newInstance();
+ bcc.setSubstitutionMode(false);
+ return bcc;
}
/**
* Add a tag-CharToByteConverter-ByteToCharConverter entry in the map.
- *
- * @param tag A DER tag of a ASN.1 character string type,
- * ex. DerValue.tag_IA5String
- * @param cbc A CharToByteConverter for the tag.
- * @param bcc A ByteToCharConverter for the tag.
+ *
+ * @param tag A DER tag of a ASN.1 character string type, ex.
+ * DerValue.tag_IA5String
+ * @param cbc A CharToByteConverter for the tag.
+ * @param bcc A ByteToCharConverter for the tag.
*/
- @SuppressWarnings("unchecked")
- public void addEntry(byte tag, Class<?> cbc, Class<?> bcc)
- {
- Class<CharToByteConverter> current_cbc;
- Class<ByteToCharConverter> current_bcc;
- Byte tagByte = Byte.valueOf(tag);
-
- current_cbc = (Class<CharToByteConverter>)tag2CBC.get(tagByte);
- current_bcc = (Class<ByteToCharConverter>)tag2BCC.get(tagByte);
- if (current_cbc != null || current_bcc != null)
- {
- if (current_cbc != cbc || current_bcc != bcc)
- {
- throw new IllegalArgumentException(
- "a DER tag to converter entry already exists.");
- }
- else {
- return;
- }
- }
- if (!CharToByteConverter.class.isAssignableFrom(cbc) ||
- !ByteToCharConverter.class.isAssignableFrom(bcc)) {
- throw new IllegalArgumentException(
- "arguments not a CharToByteConverter or ByteToCharConverter");
- }
- tag2CBC.put(tagByte, (Class<CharToByteConverter>) cbc);
- tag2BCC.put(tagByte, (Class<ByteToCharConverter>) bcc);
+ @SuppressWarnings("unchecked")
+ public void addEntry(byte tag, Class<?> cbc, Class<?> bcc) {
+ Class<CharToByteConverter> current_cbc;
+ Class<ByteToCharConverter> current_bcc;
+ Byte tagByte = Byte.valueOf(tag);
+
+ current_cbc = (Class<CharToByteConverter>) tag2CBC.get(tagByte);
+ current_bcc = (Class<ByteToCharConverter>) tag2BCC.get(tagByte);
+ if (current_cbc != null || current_bcc != null) {
+ if (current_cbc != cbc || current_bcc != bcc) {
+ throw new IllegalArgumentException(
+ "a DER tag to converter entry already exists.");
+ } else {
+ return;
+ }
+ }
+ if (!CharToByteConverter.class.isAssignableFrom(cbc) ||
+ !ByteToCharConverter.class.isAssignableFrom(bcc)) {
+ throw new IllegalArgumentException(
+ "arguments not a CharToByteConverter or ByteToCharConverter");
+ }
+ tag2CBC.put(tagByte, (Class<CharToByteConverter>) cbc);
+ tag2BCC.put(tagByte, (Class<ByteToCharConverter>) bcc);
}
/**
* Get and enumeration of all tags in the map.
- * @return An Enumeration of DER tags in the map as Bytes.
+ *
+ * @return An Enumeration of DER tags in the map as Bytes.
*/
- public Enumeration<Byte> getTags()
- {
- return tag2CBC.keys();
+ public Enumeration<Byte> getTags() {
+ return tag2CBC.keys();
}
// static public methods.
/**
* Get the global ASN1CharStrConvMap.
- * @return The global default ASN1CharStrConvMap.
+ *
+ * @return The global default ASN1CharStrConvMap.
*/
- static public ASN1CharStrConvMap getDefault()
- {
- return defaultMap;
+ static public ASN1CharStrConvMap getDefault() {
+ return defaultMap;
}
/**
* Set the global default ASN1CharStrConvMap.
- * @param newDefault The new default ASN1CharStrConvMap.
+ *
+ * @param newDefault The new default ASN1CharStrConvMap.
*/
- static public void setDefault(ASN1CharStrConvMap newDefault)
- {
- if (newDefault == null)
- throw new IllegalArgumentException(
- "Cannot set a null default Der Tag Converter map");
- defaultMap = newDefault;
+ static public void setDefault(ASN1CharStrConvMap newDefault) {
+ if (newDefault == null)
+ throw new IllegalArgumentException(
+ "Cannot set a null default Der Tag Converter map");
+ defaultMap = newDefault;
}
// private methods and variables.
@@ -182,50 +175,48 @@ public class ASN1CharStrConvMap
* Create the default converter map on initialization
*/
static {
- defaultMap = new ASN1CharStrConvMap();
- defaultMap.addEntry(DerValue.tag_PrintableString,
- (Class<?>)CharToBytePrintable.class, (Class<?>)ByteToCharPrintable.class);
- defaultMap.addEntry(DerValue.tag_VisibleString,
- CharToBytePrintable.class, ByteToCharPrintable.class);
- defaultMap.addEntry(DerValue.tag_IA5String,
- CharToByteIA5String.class, ByteToCharIA5String.class);
- defaultMap.addEntry(DerValue.tag_BMPString,
- // Changed by bskim
- //sun.io.CharToByteUnicode.class,
- //netscape.security.util.ByteToCharUnicode.class);
- sun.io.CharToByteUnicodeBig.class,
- sun.io.ByteToCharUnicodeBig.class);
- // Change end
- defaultMap.addEntry(DerValue.tag_UniversalString,
- CharToByteUniversalString.class,
- ByteToCharUniversalString.class);
- // XXX this is an oversimplified implementation of T.61 strings, it
- // doesn't handle all cases
- defaultMap.addEntry(DerValue.tag_T61String,
- latin1CBC.class, latin1BCC.class);
- // UTF8String added to ASN.1 in 1998
- defaultMap.addEntry(DerValue.tag_UTF8String,
- CharToByteUTF8.class,
- ByteToCharUTF8.class);
- defaultMap.addEntry(DerValue.tag_GeneralString,
- CharToByteUTF8.class,
- ByteToCharUTF8.class);
+ defaultMap = new ASN1CharStrConvMap();
+ defaultMap.addEntry(DerValue.tag_PrintableString,
+ (Class<?>) CharToBytePrintable.class, (Class<?>) ByteToCharPrintable.class);
+ defaultMap.addEntry(DerValue.tag_VisibleString,
+ CharToBytePrintable.class, ByteToCharPrintable.class);
+ defaultMap.addEntry(DerValue.tag_IA5String,
+ CharToByteIA5String.class, ByteToCharIA5String.class);
+ defaultMap.addEntry(DerValue.tag_BMPString,
+ // Changed by bskim
+ // sun.io.CharToByteUnicode.class,
+ // netscape.security.util.ByteToCharUnicode.class);
+ sun.io.CharToByteUnicodeBig.class,
+ sun.io.ByteToCharUnicodeBig.class);
+ // Change end
+ defaultMap.addEntry(DerValue.tag_UniversalString,
+ CharToByteUniversalString.class,
+ ByteToCharUniversalString.class);
+ // XXX this is an oversimplified implementation of T.61 strings, it
+ // doesn't handle all cases
+ defaultMap.addEntry(DerValue.tag_T61String,
+ latin1CBC.class, latin1BCC.class);
+ // UTF8String added to ASN.1 in 1998
+ defaultMap.addEntry(DerValue.tag_UTF8String,
+ CharToByteUTF8.class,
+ ByteToCharUTF8.class);
+ defaultMap.addEntry(DerValue.tag_GeneralString,
+ CharToByteUTF8.class,
+ ByteToCharUTF8.class);
};
};
class latin1CBC extends sun.io.CharToByteISO8859_1 {
- public latin1CBC() {
- super();
- subMode = false;
- }
+ public latin1CBC() {
+ super();
+ subMode = false;
+ }
}
class latin1BCC extends sun.io.ByteToCharISO8859_1 {
- public latin1BCC() {
- super();
- subMode = false;
- }
+ public latin1BCC() {
+ super();
+ subMode = false;
+ }
}
-
-
diff --git a/pki/base/util/src/netscape/security/util/BigInt.java b/pki/base/util/src/netscape/security/util/BigInt.java
index 10e4569d..9cfbb02c 100644
--- a/pki/base/util/src/netscape/security/util/BigInt.java
+++ b/pki/base/util/src/netscape/security/util/BigInt.java
@@ -19,180 +19,184 @@ package netscape.security.util;
import java.math.BigInteger;
-
/**
- * A low-overhead arbitrary-precision <em>unsigned</em> integer.
- * This is intended for use with ASN.1 parsing, and printing of
- * such parsed values. Convert to "BigInteger" if you need to do
- * arbitrary precision arithmetic, rather than just represent
- * the number as a wrapped array of bytes.
- *
- * <P><em><b>NOTE:</b> This class may eventually disappear, to
+ * A low-overhead arbitrary-precision <em>unsigned</em> integer. This is
+ * intended for use with ASN.1 parsing, and printing of such parsed values.
+ * Convert to "BigInteger" if you need to do arbitrary precision arithmetic,
+ * rather than just represent the number as a wrapped array of bytes.
+ *
+ * <P>
+ * <em><b>NOTE:</b> This class may eventually disappear, to
* be supplanted by big-endian byte arrays which hold both signed
* and unsigned arbitrary-precision integers.
- *
+ *
* @version 1.23
* @author David Brownell
*/
public final class BigInt {
// Big endian -- MSB first.
- private byte[] places;
+ private byte[] places;
/**
- * Constructs a "Big" integer from a set of (big-endian) bytes.
- * Leading zeroes should be stripped off.
- *
- * @param data a sequence of bytes, most significant bytes/digits
- * first. CONSUMED.
+ * Constructs a "Big" integer from a set of (big-endian) bytes. Leading
+ * zeroes should be stripped off.
+ *
+ * @param data a sequence of bytes, most significant bytes/digits first.
+ * CONSUMED.
*/
- public BigInt(byte[] data) { places = (byte[])data.clone(); }
+ public BigInt(byte[] data) {
+ places = (byte[]) data.clone();
+ }
/**
- * Constructs a "Big" integer from a "BigInteger", which must be
- * positive (or zero) in value.
+ * Constructs a "Big" integer from a "BigInteger", which must be positive
+ * (or zero) in value.
*/
public BigInt(BigInteger i) {
- byte[] temp = i.toByteArray();
-
- if ((temp [0] & 0x80) != 0)
- throw new IllegalArgumentException ("negative BigInteger");
-
- // XXX we assume exactly _one_ sign byte is used...
-
- if (temp [0] != 0)
- places = temp;
- else {
- // Note that if i = new BigInteger("0"),
- // i.toByteArray() contains only 1 zero.
- if (temp.length == 1) {
- places = new byte [1];
- places [0] = (byte) 0;
- } else {
- places = new byte [temp.length - 1];
- for (int j = 1; j < temp.length; j++)
- places [j - 1] = temp [j];
- }
- }
+ byte[] temp = i.toByteArray();
+
+ if ((temp[0] & 0x80) != 0)
+ throw new IllegalArgumentException("negative BigInteger");
+
+ // XXX we assume exactly _one_ sign byte is used...
+
+ if (temp[0] != 0)
+ places = temp;
+ else {
+ // Note that if i = new BigInteger("0"),
+ // i.toByteArray() contains only 1 zero.
+ if (temp.length == 1) {
+ places = new byte[1];
+ places[0] = (byte) 0;
+ } else {
+ places = new byte[temp.length - 1];
+ for (int j = 1; j < temp.length; j++)
+ places[j - 1] = temp[j];
+ }
+ }
}
/**
* Constructs a "Big" integer from a normal Java integer.
- *
+ *
* @param i the java primitive integer
*/
public BigInt(int i) {
- if (i < (1 << 8)) {
- places = new byte [1];
- places [0] = (byte) i;
- } else if (i < (1 << 16)) {
- places = new byte [2];
- places[0] = (byte) (i >> 8);
- places[1] = (byte) i;
- } else if (i < (1 << 24)) {
- places = new byte [3];
- places[0] = (byte) (i >> 16);
- places [1] = (byte) (i >> 8);
- places[2] = (byte) i;
- } else {
- places = new byte [4];
- places[0] = (byte) (i >> 24);
- places[1] = (byte) (i >> 16);
- places[2] = (byte) (i >> 8);
- places[3] = (byte) i;
- }
+ if (i < (1 << 8)) {
+ places = new byte[1];
+ places[0] = (byte) i;
+ } else if (i < (1 << 16)) {
+ places = new byte[2];
+ places[0] = (byte) (i >> 8);
+ places[1] = (byte) i;
+ } else if (i < (1 << 24)) {
+ places = new byte[3];
+ places[0] = (byte) (i >> 16);
+ places[1] = (byte) (i >> 8);
+ places[2] = (byte) i;
+ } else {
+ places = new byte[4];
+ places[0] = (byte) (i >> 24);
+ places[1] = (byte) (i >> 16);
+ places[2] = (byte) (i >> 8);
+ places[3] = (byte) i;
+ }
}
/**
* Converts the "big" integer to a java primitive integer.
- *
+ *
* @exception NumberFormatException if 32 bits is insufficient.
*/
public int toInt() {
- if (places.length > 4)
- throw new NumberFormatException ("BigInt.toInt, too big");
- int retval = 0, i = 0;
+ if (places.length > 4)
+ throw new NumberFormatException("BigInt.toInt, too big");
+ int retval = 0, i = 0;
for (; i < places.length; i++)
- retval = (retval << 8) + ((int)places[i] & 0xff);
- return retval;
+ retval = (retval << 8) + ((int) places[i] & 0xff);
+ return retval;
}
/**
- * Returns a hexadecimal printed representation. The value is
- * formatted to fit on lines of at least 75 characters, with
- * embedded newlines. Words are separated for readability,
- * with eight words (32 bytes) per line.
+ * Returns a hexadecimal printed representation. The value is formatted to
+ * fit on lines of at least 75 characters, with embedded newlines. Words are
+ * separated for readability, with eight words (32 bytes) per line.
*/
- public String toString() { return hexify(); }
+ public String toString() {
+ return hexify();
+ }
/**
- * Returns a BigInteger value which supports many arithmetic
- * operations. Assumes negative values will never occur.
+ * Returns a BigInteger value which supports many arithmetic operations.
+ * Assumes negative values will never occur.
*/
- public BigInteger toBigInteger ()
- { return new BigInteger(1, places); }
+ public BigInteger toBigInteger() {
+ return new BigInteger(1, places);
+ }
/**
* Returns the length of the data as a byte array.
*/
- public int byteLength() { return places.length; }
-
+ public int byteLength() {
+ return places.length;
+ }
/**
- * Returns the data as a byte array. The most significant bit
- * of the array is bit zero (as in <code>java.math.BigInteger</code>).
+ * Returns the data as a byte array. The most significant bit of the array
+ * is bit zero (as in <code>java.math.BigInteger</code>).
*/
- public byte [] toByteArray () {
+ public byte[] toByteArray() {
if (places.length == 0) {
- byte zero[] = new byte [1];
- zero [0] = (byte) 0;
- return zero;
- } else {
- return (byte [])places.clone();
- }
+ byte zero[] = new byte[1];
+ zero[0] = (byte) 0;
+ return zero;
+ } else {
+ return (byte[]) places.clone();
+ }
}
private static final String digits = "0123456789abcdef";
+
private String hexify() {
if (places.length == 0)
return " 0 ";
- StringBuffer buf = new StringBuffer (places.length * 2);
- buf.append (" "); // four spaces
- for (int i = 0; i < places.length; i++) {
- buf.append (digits.charAt ((places [i] >> 4) & 0x0f));
- buf.append (digits.charAt (places [i] & 0x0f));
- if (((i + 1) % 32) == 0) {
- if ((i + 1) != places.length)
- buf.append ("\n "); // line after four words
- } else if (((i + 1) % 4) == 0)
- buf.append (' '); // space between words
- }
- return buf.toString ();
+ StringBuffer buf = new StringBuffer(places.length * 2);
+ buf.append(" "); // four spaces
+ for (int i = 0; i < places.length; i++) {
+ buf.append(digits.charAt((places[i] >> 4) & 0x0f));
+ buf.append(digits.charAt(places[i] & 0x0f));
+ if (((i + 1) % 32) == 0) {
+ if ((i + 1) != places.length)
+ buf.append("\n "); // line after four words
+ } else if (((i + 1) % 4) == 0)
+ buf.append(' '); // space between words
+ }
+ return buf.toString();
}
/**
- * Returns true iff the parameter is a numerically equivalent
- * BigInt.
- *
+ * Returns true iff the parameter is a numerically equivalent BigInt.
+ *
* @param other the object being compared with this one.
*/
public boolean equals(Object other) {
- if (other instanceof BigInt)
- return equals ((BigInt) other);
- return false;
+ if (other instanceof BigInt)
+ return equals((BigInt) other);
+ return false;
}
/**
* Returns true iff the parameter is numerically equivalent.
- *
+ *
* @param other the BigInt being compared with this one.
*/
public boolean equals(BigInt other) {
if (this == other)
return true;
- byte[] otherPlaces = other.toByteArray();
+ byte[] otherPlaces = other.toByteArray();
if (places.length != otherPlaces.length)
return false;
for (int i = 0; i < places.length; i++)
diff --git a/pki/base/util/src/netscape/security/util/BitArray.java b/pki/base/util/src/netscape/security/util/BitArray.java
index 43af482d..d7b3bfcf 100644
--- a/pki/base/util/src/netscape/security/util/BitArray.java
+++ b/pki/base/util/src/netscape/security/util/BitArray.java
@@ -21,7 +21,7 @@ import java.io.ByteArrayOutputStream;
/**
* A packed array of booleans.
- *
+ *
* @author Joshua Bloch
* @author Douglas Hoover
* @version 1.2 97/12/10
@@ -35,224 +35,219 @@ public class BitArray {
private static final int BITS_PER_UNIT = 8;
private static int subscript(int idx) {
- return idx / BITS_PER_UNIT;
+ return idx / BITS_PER_UNIT;
}
private static int position(int idx) { // bits big-endian in each unit
- return 1 << (BITS_PER_UNIT - 1 - (idx % BITS_PER_UNIT));
+ return 1 << (BITS_PER_UNIT - 1 - (idx % BITS_PER_UNIT));
}
/**
* Creates a BitArray of the specified size, initialized to zeros.
*/
public BitArray(int length) throws IllegalArgumentException {
- if (length < 0) {
- throw new IllegalArgumentException("Negative length for BitArray");
- }
+ if (length < 0) {
+ throw new IllegalArgumentException("Negative length for BitArray");
+ }
- this.length = length;
+ this.length = length;
- repn = new byte[(length + BITS_PER_UNIT - 1)/BITS_PER_UNIT];
+ repn = new byte[(length + BITS_PER_UNIT - 1) / BITS_PER_UNIT];
}
-
/**
- * Creates a BitArray of the specified size, initialized from the
- * specified byte array. The most significant bit of a[0] gets
- * index zero in the BitArray. The array a must be large enough
- * to specify a value for every bit in the BitArray. In other words,
- * 8*a.length >= length.
+ * Creates a BitArray of the specified size, initialized from the specified
+ * byte array. The most significant bit of a[0] gets index zero in the
+ * BitArray. The array a must be large enough to specify a value for every
+ * bit in the BitArray. In other words, 8*a.length >= length.
*/
public BitArray(int length, byte[] a) throws IllegalArgumentException {
-
- if (length < 0) {
- throw new IllegalArgumentException("Negative length for BitArray");
- }
- if (a.length * BITS_PER_UNIT < length) {
- throw new IllegalArgumentException("Byte array too short to represent " +
- "bit array of given length");
- }
-
- this.length = length;
-
- int repLength = ((length + BITS_PER_UNIT - 1)/BITS_PER_UNIT);
- int unusedBits = repLength*BITS_PER_UNIT - length;
- byte bitMask = (byte) (0xFF << unusedBits);
-
- /*
- normalize the representation:
- 1. discard extra bytes
- 2. zero out extra bits in the last byte
- */
- repn = new byte[repLength];
- System.arraycopy(a, 0, repn, 0, repLength);
- if (repn.length > 0)
- repn[repn.length -1] = (byte) (repn[repn.length -1] & bitMask);
+
+ if (length < 0) {
+ throw new IllegalArgumentException("Negative length for BitArray");
+ }
+ if (a.length * BITS_PER_UNIT < length) {
+ throw new IllegalArgumentException("Byte array too short to represent " +
+ "bit array of given length");
+ }
+
+ this.length = length;
+
+ int repLength = ((length + BITS_PER_UNIT - 1) / BITS_PER_UNIT);
+ int unusedBits = repLength * BITS_PER_UNIT - length;
+ byte bitMask = (byte) (0xFF << unusedBits);
+
+ /*
+ * normalize the representation: 1. discard extra bytes 2. zero out
+ * extra bits in the last byte
+ */
+ repn = new byte[repLength];
+ System.arraycopy(a, 0, repn, 0, repLength);
+ if (repn.length > 0)
+ repn[repn.length - 1] = (byte) (repn[repn.length - 1] & bitMask);
}
/**
- * Create a BitArray whose bits are those of the given array
- * of Booleans.
+ * Create a BitArray whose bits are those of the given array of Booleans.
*/
public BitArray(boolean[] bits) {
- length = bits.length;
- repn = new byte[(length + 7)/8];
+ length = bits.length;
+ repn = new byte[(length + 7) / 8];
- for (int i=0; i < length; i++) {
- set(i, bits[i]);
- }
+ for (int i = 0; i < length; i++) {
+ set(i, bits[i]);
+ }
}
-
-
+
/**
- * Copy constructor (for cloning).
+ * Copy constructor (for cloning).
*/
private BitArray(BitArray ba) {
- length = ba.length;
- repn = (byte[]) ba.repn.clone();
+ length = ba.length;
+ repn = (byte[]) ba.repn.clone();
}
/**
- * Returns the indexed bit in this BitArray.
+ * Returns the indexed bit in this BitArray.
*/
public boolean get(int index) throws ArrayIndexOutOfBoundsException {
- if (index < 0 || index >= length) {
- throw new ArrayIndexOutOfBoundsException(Integer.toString(index));
- }
-
- return (repn[subscript(index)] & position(index)) != 0;
+ if (index < 0 || index >= length) {
+ throw new ArrayIndexOutOfBoundsException(Integer.toString(index));
+ }
+
+ return (repn[subscript(index)] & position(index)) != 0;
}
/**
- * Sets the indexed bit in this BitArray.
+ * Sets the indexed bit in this BitArray.
*/
public void set(int index, boolean value)
- throws ArrayIndexOutOfBoundsException {
- if (index < 0 || index >= length) {
- throw new ArrayIndexOutOfBoundsException(Integer.toString(index));
- }
- int idx = subscript(index);
- int bit = position(index);
-
- if (value) {
- repn[idx] |= bit;
- } else {
- repn[idx] &= ~bit;
- }
+ throws ArrayIndexOutOfBoundsException {
+ if (index < 0 || index >= length) {
+ throw new ArrayIndexOutOfBoundsException(Integer.toString(index));
+ }
+ int idx = subscript(index);
+ int bit = position(index);
+
+ if (value) {
+ repn[idx] |= bit;
+ } else {
+ repn[idx] &= ~bit;
+ }
}
/**
* Returns the length of this BitArray.
*/
public int length() {
- return length;
+ return length;
}
/**
- * Returns a Byte array containing the contents of this BitArray.
- * The bit stored at index zero in this BitArray will be copied
- * into the most significant bit of the zeroth element of the
- * returned byte array. The last byte of the returned byte array
- * will be contain zeros in any bits that do not have corresponding
- * bits in the BitArray. (This matters only if the BitArray's size
- * is not a multiple of 8.)
- */
+ * Returns a Byte array containing the contents of this BitArray. The bit
+ * stored at index zero in this BitArray will be copied into the most
+ * significant bit of the zeroth element of the returned byte array. The
+ * last byte of the returned byte array will be contain zeros in any bits
+ * that do not have corresponding bits in the BitArray. (This matters only
+ * if the BitArray's size is not a multiple of 8.)
+ */
public byte[] toByteArray() {
- return (byte[]) repn.clone();
+ return (byte[]) repn.clone();
}
public boolean equals(Object obj) {
- if (obj == this) return true;
- if (obj == null || !(obj instanceof BitArray)) return false;
-
- BitArray ba = (BitArray) obj;
-
- if (ba.length != length) return false;
-
- for (int i = 0; i < repn.length; i += 1) {
- if (repn[i] != ba.repn[i]) return false;
- }
- return true;
+ if (obj == this)
+ return true;
+ if (obj == null || !(obj instanceof BitArray))
+ return false;
+
+ BitArray ba = (BitArray) obj;
+
+ if (ba.length != length)
+ return false;
+
+ for (int i = 0; i < repn.length; i += 1) {
+ if (repn[i] != ba.repn[i])
+ return false;
+ }
+ return true;
}
/**
* Return a boolean array with the same bit values a this BitArray.
*/
public boolean[] toBooleanArray() {
- boolean[] bits = new boolean[length];
+ boolean[] bits = new boolean[length];
- for (int i=0; i < length; i++) {
- bits[i] = get(i);
- }
- return bits;
+ for (int i = 0; i < length; i++) {
+ bits[i] = get(i);
+ }
+ return bits;
}
/**
* Returns a hash code value for this bit array.
- *
- * @return a hash code value for this bit array.
+ *
+ * @return a hash code value for this bit array.
*/
public int hashCode() {
- int hashCode = 0;
+ int hashCode = 0;
- for (int i = 0; i < repn.length; i++)
- hashCode = 31*hashCode + repn[i];
+ for (int i = 0; i < repn.length; i++)
+ hashCode = 31 * hashCode + repn[i];
- return hashCode ^ length;
+ return hashCode ^ length;
}
-
public Object clone() {
- return new BitArray(this);
+ return new BitArray(this);
}
-
private static final byte[][] NYBBLE = {
- { (byte)'0',(byte)'0',(byte)'0',(byte)'0'},
- { (byte)'0',(byte)'0',(byte)'0',(byte)'1'},
- { (byte)'0',(byte)'0',(byte)'1',(byte)'0'},
- { (byte)'0',(byte)'0',(byte)'1',(byte)'1'},
- { (byte)'0',(byte)'1',(byte)'0',(byte)'0'},
- { (byte)'0',(byte)'1',(byte)'0',(byte)'1'},
- { (byte)'0',(byte)'1',(byte)'1',(byte)'0'},
- { (byte)'0',(byte)'1',(byte)'1',(byte)'1'},
- { (byte)'1',(byte)'0',(byte)'0',(byte)'0'},
- { (byte)'1',(byte)'0',(byte)'0',(byte)'1'},
- { (byte)'1',(byte)'0',(byte)'1',(byte)'0'},
- { (byte)'1',(byte)'0',(byte)'1',(byte)'1'},
- { (byte)'1',(byte)'1',(byte)'0',(byte)'0'},
- { (byte)'1',(byte)'1',(byte)'0',(byte)'1'},
- { (byte)'1',(byte)'1',(byte)'1',(byte)'0'},
- { (byte)'1',(byte)'1',(byte)'1',(byte)'1'}
+ { (byte) '0', (byte) '0', (byte) '0', (byte) '0' },
+ { (byte) '0', (byte) '0', (byte) '0', (byte) '1' },
+ { (byte) '0', (byte) '0', (byte) '1', (byte) '0' },
+ { (byte) '0', (byte) '0', (byte) '1', (byte) '1' },
+ { (byte) '0', (byte) '1', (byte) '0', (byte) '0' },
+ { (byte) '0', (byte) '1', (byte) '0', (byte) '1' },
+ { (byte) '0', (byte) '1', (byte) '1', (byte) '0' },
+ { (byte) '0', (byte) '1', (byte) '1', (byte) '1' },
+ { (byte) '1', (byte) '0', (byte) '0', (byte) '0' },
+ { (byte) '1', (byte) '0', (byte) '0', (byte) '1' },
+ { (byte) '1', (byte) '0', (byte) '1', (byte) '0' },
+ { (byte) '1', (byte) '0', (byte) '1', (byte) '1' },
+ { (byte) '1', (byte) '1', (byte) '0', (byte) '0' },
+ { (byte) '1', (byte) '1', (byte) '0', (byte) '1' },
+ { (byte) '1', (byte) '1', (byte) '1', (byte) '0' },
+ { (byte) '1', (byte) '1', (byte) '1', (byte) '1' }
};
private static final int BYTES_PER_LINE = 8;
/**
- * Returns a string representation of this BitArray.
+ * Returns a string representation of this BitArray.
*/
public String toString() {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
-
- for (int i = 0; i < repn.length - 1; i++) {
- out.write(NYBBLE[(repn[i] >> 4) & 0x0F], 0, 4);
- out.write(NYBBLE[repn[i] & 0x0F], 0, 4);
-
- if (i % BYTES_PER_LINE == BYTES_PER_LINE - 1) {
- out.write('\n');
- } else {
- out.write(' ');
- }
- }
-
- // in last byte of repn, use only the valid bits
- for (int i = BITS_PER_UNIT * (repn.length - 1); i < length; i++) {
- out.write(get(i) ? '1' : '0');
- }
-
- return new String(out.toByteArray());
-
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+
+ for (int i = 0; i < repn.length - 1; i++) {
+ out.write(NYBBLE[(repn[i] >> 4) & 0x0F], 0, 4);
+ out.write(NYBBLE[repn[i] & 0x0F], 0, 4);
+
+ if (i % BYTES_PER_LINE == BYTES_PER_LINE - 1) {
+ out.write('\n');
+ } else {
+ out.write(' ');
+ }
+ }
+
+ // in last byte of repn, use only the valid bits
+ for (int i = BITS_PER_UNIT * (repn.length - 1); i < length; i++) {
+ out.write(get(i) ? '1' : '0');
+ }
+
+ return new String(out.toByteArray());
+
}
-
-}
+}
diff --git a/pki/base/util/src/netscape/security/util/ByteArrayLexOrder.java b/pki/base/util/src/netscape/security/util/ByteArrayLexOrder.java
index 60aede10..9621deee 100644
--- a/pki/base/util/src/netscape/security/util/ByteArrayLexOrder.java
+++ b/pki/base/util/src/netscape/security/util/ByteArrayLexOrder.java
@@ -21,43 +21,41 @@ import java.util.Comparator;
/**
* Compare two byte arrays in lexicographical order.
- *
+ *
* @version 1.4 97/12/10
* @author D. N. Hoover
*/
public class ByteArrayLexOrder implements Comparator {
/**
- * Perform lexicographical comparison of two byte arrays,
- * regarding each byte as unsigned. That is, compare array entries
- * in order until they differ--the array with the smaller entry
- * is "smaller". If array entries are
- * equal till one array ends, then the longer array is "bigger".
- *
- * @param obj1 first byte array to compare.
- * @param obj2 second byte array to compare.
- * @return negative number if obj1 < obj2, 0 if obj1 == obj2,
- * positive number if obj1 > obj2.
- *
- * @exception <code>ClassCastException</code>
- * if either argument is not a byte array.
+ * Perform lexicographical comparison of two byte arrays, regarding each
+ * byte as unsigned. That is, compare array entries in order until they
+ * differ--the array with the smaller entry is "smaller". If array entries
+ * are equal till one array ends, then the longer array is "bigger".
+ *
+ * @param obj1 first byte array to compare.
+ * @param obj2 second byte array to compare.
+ * @return negative number if obj1 < obj2, 0 if obj1 == obj2, positive
+ * number if obj1 > obj2.
+ *
+ * @exception <code>ClassCastException</code> if either argument is not a
+ * byte array.
*/
public final int compare(Object obj1, Object obj2) {
- byte[] bytes1 = (byte[]) obj1;
- byte[] bytes2 = (byte[]) obj2;
+ byte[] bytes1 = (byte[]) obj1;
+ byte[] bytes2 = (byte[]) obj2;
- int diff;
- for (int i = 0; i < bytes1.length && i < bytes2.length; i++) {
- diff = (bytes1[i] & 0xFF) - (bytes2[i] & 0xFF);
- if (diff != 0) {
- return diff;
- }
- }
- // if array entries are equal till the first ends, then the
- // longer is "bigger"
- return bytes1.length - bytes2.length;
+ int diff;
+ for (int i = 0; i < bytes1.length && i < bytes2.length; i++) {
+ diff = (bytes1[i] & 0xFF) - (bytes2[i] & 0xFF);
+ if (diff != 0) {
+ return diff;
+ }
+ }
+ // if array entries are equal till the first ends, then the
+ // longer is "bigger"
+ return bytes1.length - bytes2.length;
}
-
}
diff --git a/pki/base/util/src/netscape/security/util/ByteArrayTagOrder.java b/pki/base/util/src/netscape/security/util/ByteArrayTagOrder.java
index 81f43747..81235d00 100644
--- a/pki/base/util/src/netscape/security/util/ByteArrayTagOrder.java
+++ b/pki/base/util/src/netscape/security/util/ByteArrayTagOrder.java
@@ -22,28 +22,27 @@ import java.util.Comparator;
public class ByteArrayTagOrder implements Comparator {
/**
- * Compare two byte arrays, by the order of their tags,
- * as defined in ITU-T X.680, sec. 6.4. (First compare
- * tag classes, then tag numbers, ignoring the constructivity bit.)
- *
- * @param obj1 first byte array to compare.
- * @param obj2 second byte array to compare.
- * @return negative number if obj1 < obj2, 0 if obj1 == obj2,
- * positive number if obj1 > obj2.
- *
- * @exception <code>ClassCastException</code>
- * if either argument is not a byte array.
+ * Compare two byte arrays, by the order of their tags, as defined in ITU-T
+ * X.680, sec. 6.4. (First compare tag classes, then tag numbers, ignoring
+ * the constructivity bit.)
+ *
+ * @param obj1 first byte array to compare.
+ * @param obj2 second byte array to compare.
+ * @return negative number if obj1 < obj2, 0 if obj1 == obj2, positive
+ * number if obj1 > obj2.
+ *
+ * @exception <code>ClassCastException</code> if either argument is not a
+ * byte array.
*/
public final int compare(Object obj1, Object obj2) {
- byte[] bytes1 = (byte[]) obj1;
- byte[] bytes2 = (byte[]) obj2;
+ byte[] bytes1 = (byte[]) obj1;
+ byte[] bytes2 = (byte[]) obj2;
- // tag order is same as byte order ignoring any difference in
- // the constructivity bit (0x02)
- return (bytes1[0] | 0x20) - (bytes2[0] | 0x20);
+ // tag order is same as byte order ignoring any difference in
+ // the constructivity bit (0x02)
+ return (bytes1[0] | 0x20) - (bytes2[0] | 0x20);
}
-
}
diff --git a/pki/base/util/src/netscape/security/util/ByteToCharIA5String.java b/pki/base/util/src/netscape/security/util/ByteToCharIA5String.java
index 69fab22a..2a98763b 100644
--- a/pki/base/util/src/netscape/security/util/ByteToCharIA5String.java
+++ b/pki/base/util/src/netscape/security/util/ByteToCharIA5String.java
@@ -22,48 +22,46 @@ import sun.io.ConversionBufferFullException;
import sun.io.UnknownCharacterException;
/**
- * Converts bytes in ASN.1 IA5String character set to unicode
- * characters.
- *
+ * Converts bytes in ASN.1 IA5String character set to unicode characters.
+ *
* @author Lily Hsiao
* @author Slava Galperin
*/
-public class ByteToCharIA5String extends ByteToCharConverter
-{
+public class ByteToCharIA5String extends ByteToCharConverter {
public String getCharacterEncoding() {
- return "ASN.1 IA5String";
+ return "ASN.1 IA5String";
}
public int convert(byte[] input, int inStart, int inEnd,
- char[] output, int outStart, int outEnd)
- throws ConversionBufferFullException,
- UnknownCharacterException
- {
- int j = outStart;
- for (int i = inStart; i < inEnd; i++, j++) {
- if (j >= outEnd) {
- byteOff = i;
- charOff = j;
- throw new ConversionBufferFullException();
- }
- if (!subMode && (input[i] & 0x80) != 0) {
- byteOff = i;
- charOff = j;
- badInputLength = 1;
- throw new UnknownCharacterException();
- }
- output[j] = (char) (input[i] & 0x7f);
- }
- byteOff = inEnd;
- charOff = j;
- return j - outStart;
+ char[] output, int outStart, int outEnd)
+ throws ConversionBufferFullException,
+ UnknownCharacterException {
+ int j = outStart;
+ for (int i = inStart; i < inEnd; i++, j++) {
+ if (j >= outEnd) {
+ byteOff = i;
+ charOff = j;
+ throw new ConversionBufferFullException();
+ }
+ if (!subMode && (input[i] & 0x80) != 0) {
+ byteOff = i;
+ charOff = j;
+ badInputLength = 1;
+ throw new UnknownCharacterException();
+ }
+ output[j] = (char) (input[i] & 0x7f);
+ }
+ byteOff = inEnd;
+ charOff = j;
+ return j - outStart;
}
public int flush(char[] output, int outStart, int outEnd) {
- return 0;
+ return 0;
}
- public void reset() { }
+ public void reset() {
+ }
}
diff --git a/pki/base/util/src/netscape/security/util/ByteToCharPrintable.java b/pki/base/util/src/netscape/security/util/ByteToCharPrintable.java
index 0607ad2e..905cdd17 100644
--- a/pki/base/util/src/netscape/security/util/ByteToCharPrintable.java
+++ b/pki/base/util/src/netscape/security/util/ByteToCharPrintable.java
@@ -23,66 +23,59 @@ import sun.io.MalformedInputException;
import sun.io.UnknownCharacterException;
/**
- * Converts bytes in ASN.1 Printable String character set to unicode
- * characters.
- *
+ * Converts bytes in ASN.1 Printable String character set to unicode characters.
+ *
* @author Lily Hsiao
* @author Slava Galperin
*/
-public class ByteToCharPrintable extends ByteToCharConverter
-{
+public class ByteToCharPrintable extends ByteToCharConverter {
- public String getCharacterEncoding()
- {
- return "ASN.1 Printable";
+ public String getCharacterEncoding() {
+ return "ASN.1 Printable";
}
public int convert(byte[] input, int inStart, int inEnd,
- char[] output, int outStart, int outEnd)
+ char[] output, int outStart, int outEnd)
throws MalformedInputException,
UnknownCharacterException,
- ConversionBufferFullException
- {
- int j = outStart;
- boolean hasNonPrintableChar = false;
+ ConversionBufferFullException {
+ int j = outStart;
+ boolean hasNonPrintableChar = false;
- for (int i = inStart; i < inEnd; i++, j++) {
- if (j >= outEnd) {
- byteOff = i;
- charOff = j;
- throw new ConversionBufferFullException();
- }
- if (!subMode &&
- !CharToBytePrintable.isPrintableChar((char) (input[i] & 0x7f))) {
- /* "bug" fix for 359010
- byteOff = i;
- charOff = j;
- badInputLength = 1;
- throw new UnknownCharacterException();
- */
- j--;
- hasNonPrintableChar = true;
- } else
- output[j] = (char) (input[i] & 0x7f);
- }
+ for (int i = inStart; i < inEnd; i++, j++) {
+ if (j >= outEnd) {
+ byteOff = i;
+ charOff = j;
+ throw new ConversionBufferFullException();
+ }
+ if (!subMode &&
+ !CharToBytePrintable.isPrintableChar((char) (input[i] & 0x7f))) {
+ /*
+ * "bug" fix for 359010 byteOff = i; charOff = j; badInputLength
+ * = 1; throw new UnknownCharacterException();
+ */
+ j--;
+ hasNonPrintableChar = true;
+ } else
+ output[j] = (char) (input[i] & 0x7f);
+ }
- if (hasNonPrintableChar == true) {
- //
- }
+ if (hasNonPrintableChar == true) {
+ //
+ }
- byteOff = inEnd;
- charOff = j;
- return j - outStart;
+ byteOff = inEnd;
+ charOff = j;
+ return j - outStart;
}
- public int flush( char[] output, int outStart, int outEnd )
- throws MalformedInputException, ConversionBufferFullException
- {
- return 0;
+ public int flush(char[] output, int outStart, int outEnd)
+ throws MalformedInputException, ConversionBufferFullException {
+ return 0;
}
- public void reset() { }
-
+ public void reset() {
+ }
}
diff --git a/pki/base/util/src/netscape/security/util/ByteToCharUnicode.java b/pki/base/util/src/netscape/security/util/ByteToCharUnicode.java
index 312b8a22..f3047bce 100644
--- a/pki/base/util/src/netscape/security/util/ByteToCharUnicode.java
+++ b/pki/base/util/src/netscape/security/util/ByteToCharUnicode.java
@@ -16,6 +16,7 @@
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package netscape.security.util;
+
import sun.io.ByteToCharUnicodeBig;
import sun.io.ByteToCharUnicodeLittle;
import sun.io.ConversionBufferFullException;
@@ -23,22 +24,21 @@ import sun.io.MalformedInputException;
/**
* Convert byte arrays containing Unicode characters into arrays of actual
- * Unicode characters, sensing the byte order automatically. To force a
+ * Unicode characters, sensing the byte order automatically. To force a
* particular byte order, use either the "UnicodeBig" or the "UnicodeLittle"
* encoding.
- *
+ *
* If the first character is a byte order mark, it will be interpreted and
- * discarded. Otherwise, the byte order is assumed to be BigEndian.
- * Either way, the byte order is decided by the first character. Later
- * byte order marks will be passed through as characters (if they indicate
- * the same byte order) or will cause an error (if they indicate the other
- * byte order).
- *
+ * discarded. Otherwise, the byte order is assumed to be BigEndian. Either way,
+ * the byte order is decided by the first character. Later byte order marks will
+ * be passed through as characters (if they indicate the same byte order) or
+ * will cause an error (if they indicate the other byte order).
+ *
* @see ByteToCharUnicodeLittle
* @see ByteToCharUnicodeBig
- *
- * @version 1.3, 96/11/23
- * @author Mark Reinhold
+ *
+ * @version 1.3, 96/11/23
+ * @author Mark Reinhold
*/
public class ByteToCharUnicode extends sun.io.ByteToCharConverter {
@@ -53,15 +53,18 @@ public class ByteToCharUnicode extends sun.io.ByteToCharConverter {
int byteOrder;
public ByteToCharUnicode() {
- byteOrder = AUTO;
+ byteOrder = AUTO;
}
public String getCharacterEncoding() {
- switch (byteOrder) {
- case BIG: return "UnicodeBig";
- case LITTLE: return "UnicodeLittle";
- default: return "Unicode";
- }
+ switch (byteOrder) {
+ case BIG:
+ return "UnicodeBig";
+ case LITTLE:
+ return "UnicodeLittle";
+ default:
+ return "Unicode";
+ }
}
boolean started = false;
@@ -69,119 +72,111 @@ public class ByteToCharUnicode extends sun.io.ByteToCharConverter {
boolean leftOver = false;
public int convert(byte[] in, int inOff, int inEnd,
- char[] out, int outOff, int outEnd)
- throws ConversionBufferFullException, MalformedInputException
- {
- byteOff = inOff;
- charOff = outOff;
-
- if (inOff >= inEnd)
- return 0;
-
- int b1, b2;
- int bc = 0;
- int inI = inOff, outI = outOff;
-
- if (leftOver) {
- b1 = leftOverByte & 0xff;
- leftOver = false;
- }
- else
- b1 = in[inI++] & 0xff;
- bc = 1;
-
- if (!started) { /* Read possible initial byte-order mark */
- if (inI < inEnd) {
- b2 = in[inI++] & 0xff;
- bc = 2;
-
- char c = (char) ((b1 << 8) | b2);
- int bo = AUTO;
-
- if (c == BYTE_ORDER_MARK)
- bo = BIG;
- else if (c == REVERSED_MARK)
- bo = LITTLE;
-
- if (byteOrder == AUTO) {
- if (bo == AUTO) {
+ char[] out, int outOff, int outEnd)
+ throws ConversionBufferFullException, MalformedInputException {
+ byteOff = inOff;
+ charOff = outOff;
+
+ if (inOff >= inEnd)
+ return 0;
+
+ int b1, b2;
+ int bc = 0;
+ int inI = inOff, outI = outOff;
+
+ if (leftOver) {
+ b1 = leftOverByte & 0xff;
+ leftOver = false;
+ } else
+ b1 = in[inI++] & 0xff;
+ bc = 1;
+
+ if (!started) { /* Read possible initial byte-order mark */
+ if (inI < inEnd) {
+ b2 = in[inI++] & 0xff;
+ bc = 2;
+
+ char c = (char) ((b1 << 8) | b2);
+ int bo = AUTO;
+
+ if (c == BYTE_ORDER_MARK)
+ bo = BIG;
+ else if (c == REVERSED_MARK)
+ bo = LITTLE;
+
+ if (byteOrder == AUTO) {
+ if (bo == AUTO) {
bo = BIG; // BigEndian by default
- }
- byteOrder = bo;
- if (inI < inEnd) {
- b1 = in[inI++] & 0xff;
- bc = 1;
- }
- }
- else if (bo == AUTO) {
- inI--;
- bc = 1;
- }
- else if (byteOrder == bo) {
- if (inI < inEnd) {
- b1 = in[inI++] & 0xff;
- bc = 1;
- }
- }
- else {
- badInputLength = bc;
- throw new
- MalformedInputException("Incorrect byte-order mark");
- }
-
- started = true;
- }
- }
-
- /* Loop invariant: (b1 contains the next input byte) && (bc == 1) */
- while (inI < inEnd) {
- b2 = in[inI++] & 0xff;
- bc = 2;
-
- char c;
- if (byteOrder == BIG)
- c = (char) ((b1 << 8) | b2);
- else
- c = (char) ((b2 << 8) | b1);
-
- if (c == REVERSED_MARK)
- throw new
- MalformedInputException("Reversed byte-order mark");
-
- if (outI >= outEnd)
- throw new ConversionBufferFullException();
- out[outI++] = c;
- byteOff = inI;
- charOff = outI;
-
- if (inI < inEnd) {
- b1 = in[inI++] & 0xff;
- bc = 1;
- }
- }
-
- if (bc == 1) {
- leftOverByte = b1;
- leftOver = true;
- }
-
- return outI - outOff;
+ }
+ byteOrder = bo;
+ if (inI < inEnd) {
+ b1 = in[inI++] & 0xff;
+ bc = 1;
+ }
+ } else if (bo == AUTO) {
+ inI--;
+ bc = 1;
+ } else if (byteOrder == bo) {
+ if (inI < inEnd) {
+ b1 = in[inI++] & 0xff;
+ bc = 1;
+ }
+ } else {
+ badInputLength = bc;
+ throw new MalformedInputException("Incorrect byte-order mark");
+ }
+
+ started = true;
+ }
+ }
+
+ /* Loop invariant: (b1 contains the next input byte) && (bc == 1) */
+ while (inI < inEnd) {
+ b2 = in[inI++] & 0xff;
+ bc = 2;
+
+ char c;
+ if (byteOrder == BIG)
+ c = (char) ((b1 << 8) | b2);
+ else
+ c = (char) ((b2 << 8) | b1);
+
+ if (c == REVERSED_MARK)
+ throw new MalformedInputException("Reversed byte-order mark");
+
+ if (outI >= outEnd)
+ throw new ConversionBufferFullException();
+ out[outI++] = c;
+ byteOff = inI;
+ charOff = outI;
+
+ if (inI < inEnd) {
+ b1 = in[inI++] & 0xff;
+ bc = 1;
+ }
+ }
+
+ if (bc == 1) {
+ leftOverByte = b1;
+ leftOver = true;
+ }
+
+ return outI - outOff;
}
public void reset() {
- leftOver = false;
- byteOff = charOff = 0;
+ leftOver = false;
+ byteOff = charOff = 0;
}
public int flush(char buf[], int off, int len)
- throws MalformedInputException
- {
- if (leftOver) {
- reset();
- throw new MalformedInputException();
- }
- byteOff = charOff = 0;
- return 0;
+ throws MalformedInputException {
+ if (leftOver) {
+ reset();
+ throw new MalformedInputException();
+ }
+ byteOff = charOff = 0;
+ return 0;
}
}
diff --git a/pki/base/util/src/netscape/security/util/ByteToCharUniversalString.java b/pki/base/util/src/netscape/security/util/ByteToCharUniversalString.java
index 77165b7f..6cf51974 100644
--- a/pki/base/util/src/netscape/security/util/ByteToCharUniversalString.java
+++ b/pki/base/util/src/netscape/security/util/ByteToCharUniversalString.java
@@ -22,78 +22,75 @@ import sun.io.ConversionBufferFullException;
import sun.io.UnknownCharacterException;
/**
- * Converts bytes in ASN.1 UniversalString character set to unicode
- * characters.
- *
+ * Converts bytes in ASN.1 UniversalString character set to unicode characters.
+ *
* @author Lily Hsiao
* @author Slava Galperin
*/
-public class ByteToCharUniversalString extends ByteToCharConverter
-{
+public class ByteToCharUniversalString extends ByteToCharConverter {
public String getCharacterEncoding() {
- return "ASN.1 UniversalString";
+ return "ASN.1 UniversalString";
}
public int convert(byte[] input, int inStart, int inEnd,
- char[] output, int outStart, int outEnd)
- throws ConversionBufferFullException,
- UnknownCharacterException
- {
- int j = outStart;
+ char[] output, int outStart, int outEnd)
+ throws ConversionBufferFullException,
+ UnknownCharacterException {
+ int j = outStart;
+ int i = inStart;
+ while (i < inEnd) {
+ // XXX we do not know what to do with truly UCS-4 characters here
+ // we also assumed network byte order
- int i = inStart;
- while(i < inEnd) {
- // XXX we do not know what to do with truly UCS-4 characters here
- // we also assumed network byte order
+ if (i + 3 >= inEnd ||
+ (!((input[i] == 0 && input[i + 1] == 0) ||
+ (input[i + 2] == 0 && input[i + 3] == 0)))) {
+ byteOff = i;
+ charOff = j;
+ throw new UnknownCharacterException();
+ }
+ if (input[i + 2] == 0 && input[i + 3] == 0) {
+ // Try to be a bit forgiving. If the byte order is
+ // reversed, we still try handle it.
- if ( i+3 >= inEnd ||
- (!((input[i] == 0 && input[i+1] == 0) ||
- (input[i+2] == 0 && input[i+3] == 0)))) {
- byteOff = i;
- charOff = j;
- throw new UnknownCharacterException();
- }
- if (input[i+2] == 0 && input[i+3] == 0) {
- // Try to be a bit forgiving. If the byte order is
- // reversed, we still try handle it.
+ // Sample Date Set (1):
+ // 0000000 f 0 \0 \0 213 0 \0 \0 S 0 \0 \0
+ // 0000014
- // Sample Date Set (1):
- // 0000000 f 0 \0 \0 213 0 \0 \0 S 0 \0 \0
- // 0000014
+ // Sample Date Set (2):
+ // 0000000 w \0 \0 \0 w \0 \0 \0 w \0 \0 \0 . \0 \0 \0
+ // 0000020 ( \0 \0 \0 t \0 \0 \0 o \0 \0 \0 b \0 \0 \0
+ // 0000040 e \0 \0 \0 | \0 \0 \0 n \0 \0 \0 o \0 \0 \0
+ // 0000060 t \0 \0 \0 t \0 \0 \0 o \0 \0 \0 b \0 \0 \0
+ // 0000100 e \0 \0 \0 ) \0 \0 \0 . \0 \0 \0 c \0 \0 \0
+ // 0000120 o \0 \0 \0 m \0 \0 \0
+ // 0000130
+ output[j] = (char) (((input[i + 1] << 8) & 0xff00) + (input[i] & 0x00ff));
+ } else {
+ // This should be the right order.
+ //
+ // 0000000 0000 00c4 0000 0064 0000 006d 0000 0069
+ // 0000020 0000 006e 0000 0020 0000 0051 0000 0041
+ // 0000040
- // Sample Date Set (2):
- // 0000000 w \0 \0 \0 w \0 \0 \0 w \0 \0 \0 . \0 \0 \0
- // 0000020 ( \0 \0 \0 t \0 \0 \0 o \0 \0 \0 b \0 \0 \0
- // 0000040 e \0 \0 \0 | \0 \0 \0 n \0 \0 \0 o \0 \0 \0
- // 0000060 t \0 \0 \0 t \0 \0 \0 o \0 \0 \0 b \0 \0 \0
- // 0000100 e \0 \0 \0 ) \0 \0 \0 . \0 \0 \0 c \0 \0 \0
- // 0000120 o \0 \0 \0 m \0 \0 \0
- // 0000130
- output[j] = (char)(((input[i+1] << 8)& 0xff00) + (input[i] & 0x00ff));
- } else {
- // This should be the right order.
- //
- // 0000000 0000 00c4 0000 0064 0000 006d 0000 0069
- // 0000020 0000 006e 0000 0020 0000 0051 0000 0041
- // 0000040
-
- // (input[i] == 0 && input[i+1] == 0)
- output[j] = (char)(((input[i+2] << 8)& 0xff00) + (input[i+3] & 0x00ff));
- }
- j++;
- i += 4;
- }
- byteOff = inEnd;
- charOff = j;
- return j - outStart;
+ // (input[i] == 0 && input[i+1] == 0)
+ output[j] = (char) (((input[i + 2] << 8) & 0xff00) + (input[i + 3] & 0x00ff));
+ }
+ j++;
+ i += 4;
+ }
+ byteOff = inEnd;
+ charOff = j;
+ return j - outStart;
}
public int flush(char[] output, int outStart, int outEnd) {
- return 0;
+ return 0;
}
- public void reset() { }
+ public void reset() {
+ }
}
diff --git a/pki/base/util/src/netscape/security/util/CertPrettyPrint.java b/pki/base/util/src/netscape/security/util/CertPrettyPrint.java
index caf7e648..f9305940 100644
--- a/pki/base/util/src/netscape/security/util/CertPrettyPrint.java
+++ b/pki/base/util/src/netscape/security/util/CertPrettyPrint.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package netscape.security.util;
-
import java.security.MessageDigest;
import java.security.PublicKey;
import java.security.cert.Certificate;
@@ -38,54 +37,55 @@ import org.mozilla.jss.asn1.SET;
import org.mozilla.jss.pkcs7.ContentInfo;
import org.mozilla.jss.pkcs7.SignedData;
-
/**
- * This class will display the certificate content in predefined
- * format.
- *
+ * This class will display the certificate content in predefined format.
+ *
* @author Jack Pan-Chen
* @version $Revision$, $Date$
*/
-public class CertPrettyPrint
-{
+public class CertPrettyPrint {
- /*==========================================================
- * constants
- *==========================================================*/
+ /*
+ * ========================================================== constants
+ * ==========================================================
+ */
private final static String CUSTOM_LOCALE = "Custom";
- /*==========================================================
- * variables
- *==========================================================*/
+ /*
+ * ========================================================== variables
+ * ==========================================================
+ */
private X509CertImpl mX509Cert = null;
private Certificate mCert = null;
private PrettyPrintFormat pp = null;
private byte[] mCert_b = null;
- /*==========================================================
- * constructors
- *==========================================================*/
+ /*
+ * ========================================================== constructors
+ * ==========================================================
+ */
public CertPrettyPrint(Certificate cert) {
if (cert instanceof X509CertImpl)
mX509Cert = (X509CertImpl) cert;
-
+
pp = new PrettyPrintFormat(":");
}
-
+
public CertPrettyPrint(byte[] certb) {
mCert_b = certb;
pp = new PrettyPrintFormat(":");
}
- /*==========================================================
- * public methods
- *==========================================================*/
+ /*
+ * ========================================================== public methods
+ * ==========================================================
+ */
/**
- * This method return string representation of the certificate
- * in predefined format using specified client local. I18N Support.
- *
+ * This method return string representation of the certificate in predefined
+ * format using specified client local. I18N Support.
+ *
* @param clientLocale Locale to be used for localization
* @return string representation of the certificate
*/
@@ -93,25 +93,25 @@ public class CertPrettyPrint
if (mX509Cert != null)
return X509toString(clientLocale);
- else if (mCert_b != null)
+ else if (mCert_b != null)
return pkcs7toString(clientLocale);
else
return null;
}
-
+
public String pkcs7toString(Locale clientLocale) {
String content = "";
try {
mX509Cert = new X509CertImpl(mCert_b);
return toString(clientLocale);
- } catch (Exception e) {
+ } catch (Exception e) {
}
ContentInfo ci = null;
try {
ci = (ContentInfo)
- ASN1Util.decode(ContentInfo.getTemplate(), mCert_b);
+ ASN1Util.decode(ContentInfo.getTemplate(), mCert_b);
} catch (Exception e) {
return "";
}
@@ -132,7 +132,7 @@ public class CertPrettyPrint
X509CertImpl certImpl = null;
try {
certImpl = new X509CertImpl(
- ASN1Util.encode(cert));
+ ASN1Util.encode(cert));
} catch (Exception e) {
}
@@ -150,17 +150,17 @@ public class CertPrettyPrint
public String stripCertBrackets(String s) {
if (s == null) {
- return s;
- }
+ return s;
+ }
if ((s.startsWith("-----BEGIN CERTIFICATE-----")) &&
- (s.endsWith("-----END CERTIFICATE-----"))) {
+ (s.endsWith("-----END CERTIFICATE-----"))) {
return (s.substring(27, (s.length() - 25)));
}
// To support Thawte's header and footer
if ((s.startsWith("-----BEGIN PKCS #7 SIGNED DATA-----")) &&
- (s.endsWith("-----END PKCS #7 SIGNED DATA-----"))) {
+ (s.endsWith("-----END PKCS #7 SIGNED DATA-----"))) {
return (s.substring(35, (s.length() - 33)));
}
@@ -187,15 +187,15 @@ public class CertPrettyPrint
public String X509toString(Locale clientLocale) {
- //get I18N resources
+ // get I18N resources
ResourceBundle resource = ResourceBundle.getBundle(
PrettyPrintResources.class.getName());
DateFormat dateFormater = DateFormat.getDateTimeInstance(
DateFormat.FULL, DateFormat.FULL, clientLocale);
- //get timezone and timezone ID
+ // get timezone and timezone ID
String tz = " ";
String tzid = " ";
-
+
StringBuffer sb = new StringBuffer();
try {
@@ -203,7 +203,7 @@ public class CertPrettyPrint
X509CertImpl.NAME + "." + X509CertImpl.INFO);
String serial2 = mX509Cert.getSerialNumber().toString(16).toUpperCase();
- //get correct instance of key
+ // get correct instance of key
PublicKey pKey = mX509Cert.getPublicKey();
X509Key key = null;
@@ -216,7 +216,7 @@ public class CertPrettyPrint
key = (X509Key) pKey;
}
- //take care of spki
+ // take care of spki
sb.append(pp.indent(4) + resource.getString(
PrettyPrintResources.TOKEN_CERTIFICATE) + "\n");
sb.append(pp.indent(8) + resource.getString(
@@ -226,24 +226,24 @@ public class CertPrettyPrint
sb.append((mX509Cert.getVersion() + 1) + "\n");
sb.append(pp.indent(12) + resource.getString(
PrettyPrintResources.TOKEN_SERIAL) + "0x" + serial2 + "\n");
- //XXX I18N Algorithm Name ?
+ // XXX I18N Algorithm Name ?
sb.append(pp.indent(12) + resource.getString(
PrettyPrintResources.TOKEN_SIGALG) + mX509Cert.getSigAlgName() +
- " - " + mX509Cert.getSigAlgOID() + "\n");
- //XXX I18N IssuerDN ?
+ " - " + mX509Cert.getSigAlgOID() + "\n");
+ // XXX I18N IssuerDN ?
sb.append(pp.indent(12) + resource.getString(
PrettyPrintResources.TOKEN_ISSUER) +
- mX509Cert.getIssuerDN().toString() + "\n");
+ mX509Cert.getIssuerDN().toString() + "\n");
sb.append(pp.indent(12) + resource.getString(
PrettyPrintResources.TOKEN_VALIDITY) + "\n");
String notBefore = dateFormater.format(mX509Cert.getNotBefore());
String notAfter = dateFormater.format(mX509Cert.getNotAfter());
- //get timezone and timezone ID
+ // get timezone and timezone ID
if (TimeZone.getDefault() != null) {
tz = TimeZone.getDefault().getDisplayName(
TimeZone.getDefault().inDaylightTime(
- mX509Cert.getNotBefore()),
+ mX509Cert.getNotBefore()),
TimeZone.SHORT,
clientLocale);
tzid = TimeZone.getDefault().getID();
@@ -252,23 +252,23 @@ public class CertPrettyPrint
if (tz.equals(tzid) || tzid.equals(CUSTOM_LOCALE)) {
// Do NOT append timezone ID
sb.append(pp.indent(16)
- + resource.getString(
- PrettyPrintResources.TOKEN_NOT_BEFORE)
- + notBefore
- + "\n");
+ + resource.getString(
+ PrettyPrintResources.TOKEN_NOT_BEFORE)
+ + notBefore
+ + "\n");
} else {
// Append timezone ID
sb.append(pp.indent(16)
- + resource.getString(
- PrettyPrintResources.TOKEN_NOT_BEFORE)
- + notBefore
- + " " + tzid + "\n");
+ + resource.getString(
+ PrettyPrintResources.TOKEN_NOT_BEFORE)
+ + notBefore
+ + " " + tzid + "\n");
}
// re-get timezone (just in case it is different . . .)
if (TimeZone.getDefault() != null) {
tz = TimeZone.getDefault().getDisplayName(
TimeZone.getDefault().inDaylightTime(
- mX509Cert.getNotAfter()),
+ mX509Cert.getNotAfter()),
TimeZone.SHORT,
clientLocale);
}
@@ -276,22 +276,22 @@ public class CertPrettyPrint
if (tz.equals(tzid) || tzid.equals(CUSTOM_LOCALE)) {
// Do NOT append timezone ID
sb.append(pp.indent(16)
- + resource.getString(
- PrettyPrintResources.TOKEN_NOT_AFTER)
- + notAfter
- + "\n");
+ + resource.getString(
+ PrettyPrintResources.TOKEN_NOT_AFTER)
+ + notAfter
+ + "\n");
} else {
// Append timezone ID
sb.append(pp.indent(16)
- + resource.getString(
- PrettyPrintResources.TOKEN_NOT_AFTER)
- + notAfter
- + " " + tzid + "\n");
+ + resource.getString(
+ PrettyPrintResources.TOKEN_NOT_AFTER)
+ + notAfter
+ + " " + tzid + "\n");
}
- //XXX I18N SubjectDN ?
+ // XXX I18N SubjectDN ?
sb.append(pp.indent(12) + resource.getString(
PrettyPrintResources.TOKEN_SUBJECT) +
- mX509Cert.getSubjectDN().toString() + "\n");
+ mX509Cert.getSubjectDN().toString() + "\n");
sb.append(pp.indent(12) + resource.getString(
PrettyPrintResources.TOKEN_SPKI) + "\n");
@@ -299,9 +299,9 @@ public class CertPrettyPrint
sb.append(pkpp.toString(clientLocale, 16, 16));
- //take care of extensions
- CertificateExtensions extensions = (CertificateExtensions)
- info.get(X509CertInfo.EXTENSIONS);
+ // take care of extensions
+ CertificateExtensions extensions = (CertificateExtensions)
+ info.get(X509CertInfo.EXTENSIONS);
sb.append(pp.indent(12) + resource.getString(
PrettyPrintResources.TOKEN_EXTENSIONS) + "\n");
@@ -313,19 +313,19 @@ public class CertPrettyPrint
sb.append(extpp.toString());
}
- //take care of signature
+ // take care of signature
sb.append(pp.indent(8) + resource.getString(
PrettyPrintResources.TOKEN_SIGNATURE) + "\n");
- //XXX I18N Algorithm Name ?
+ // XXX I18N Algorithm Name ?
sb.append(pp.indent(12) + resource.getString(
PrettyPrintResources.TOKEN_ALGORITHM) +
- mX509Cert.getSigAlgName() + " - " + mX509Cert.getSigAlgOID() + "\n");
+ mX509Cert.getSigAlgName() + " - " + mX509Cert.getSigAlgOID() + "\n");
sb.append(pp.indent(12) + resource.getString(
PrettyPrintResources.TOKEN_SIGNATURE) + "\n");
sb.append(pp.toHexString(mX509Cert.getSignature(), 16, 16));
// fingerprints
- String[] hashes = new String[] {"MD2", "MD5", "SHA1", "SHA256", "SHA512"};
+ String[] hashes = new String[] { "MD2", "MD5", "SHA1", "SHA256", "SHA512" };
String certFingerprints = "";
sb.append(pp.indent(8) + "FingerPrint\n");
@@ -334,7 +334,7 @@ public class CertPrettyPrint
md.update(mX509Cert.getEncoded());
certFingerprints += pp.indent(12) + hashes[i] + ":\n" +
- pp.toHexString(md.digest(), 16, 16);
+ pp.toHexString(md.digest(), 16, 16);
}
sb.append(certFingerprints);
@@ -343,5 +343,5 @@ public class CertPrettyPrint
return sb.toString();
}
-
+
}
diff --git a/pki/base/util/src/netscape/security/util/CharToByteIA5String.java b/pki/base/util/src/netscape/security/util/CharToByteIA5String.java
index f7c0d1e2..20ecb203 100644
--- a/pki/base/util/src/netscape/security/util/CharToByteIA5String.java
+++ b/pki/base/util/src/netscape/security/util/CharToByteIA5String.java
@@ -23,66 +23,72 @@ import sun.io.UnknownCharacterException;
/**
* Converts a string of ASN.1 IA5String characters to IA5String bytes.
- *
+ *
* @author Lily Hsiao
* @author Slava Galperin
*/
-public class CharToByteIA5String extends CharToByteConverter
-{
- /*
+public class CharToByteIA5String extends CharToByteConverter {
+ /*
* Returns the character set id for the conversion.
+ *
* @return the character set id.
*/
- public String getCharacterEncoding () {
- return "ASN.1 IA5String";
+ public String getCharacterEncoding() {
+ return "ASN.1 IA5String";
}
- /*
- * Converts an array of Unicode characters into an array of IA5String
- * bytes and returns the total number of characters converted.
- * If conversion cannot be done, UnknownCharacterException is
- * thrown. The character and byte offset will be set to the point
- * of the unknown character.
+ /*
+ * Converts an array of Unicode characters into an array of IA5String bytes
+ * and returns the total number of characters converted. If conversion
+ * cannot be done, UnknownCharacterException is thrown. The character and
+ * byte offset will be set to the point of the unknown character.
+ *
* @param input character array to convert.
+ *
* @param inStart offset from which to start the conversion.
+ *
* @param inEnd where to end the conversion.
+ *
* @param output byte array to store converted bytes.
+ *
* @param outStart starting offset in the output byte array.
+ *
* @param outEnd ending offset in the output byte array.
+ *
* @return the number of characters converted.
*/
public int convert(char[] input, int inStart, int inEnd,
- byte[] output, int outStart, int outEnd)
- throws ConversionBufferFullException,
- UnknownCharacterException
- {
- int j = outStart;
- for (int i = inStart; i < inEnd; i++, j++) {
- if (j >= outEnd) {
- charOff = i;
- byteOff = j;
- throw new ConversionBufferFullException();
- }
- if (!subMode && (input[i] & 0xFF80) != 0) {
- charOff = i;
- byteOff = j;
- badInputLength = 1;
- throw new UnknownCharacterException();
- }
-
- output[j] = (byte) (input[i] & 0x7f);
- }
- return j - outStart;
+ byte[] output, int outStart, int outEnd)
+ throws ConversionBufferFullException,
+ UnknownCharacterException {
+ int j = outStart;
+ for (int i = inStart; i < inEnd; i++, j++) {
+ if (j >= outEnd) {
+ charOff = i;
+ byteOff = j;
+ throw new ConversionBufferFullException();
+ }
+ if (!subMode && (input[i] & 0xFF80) != 0) {
+ charOff = i;
+ byteOff = j;
+ badInputLength = 1;
+ throw new UnknownCharacterException();
+ }
+
+ output[j] = (byte) (input[i] & 0x7f);
+ }
+ return j - outStart;
}
public int flush(byte[] output, int outStart, int outEnd) {
- return 0;
+ return 0;
}
- public void reset() { }
+ public void reset() {
+ }
public int getMaxBytesPerChar() {
- return 1;
+ return 1;
}
}
diff --git a/pki/base/util/src/netscape/security/util/CharToBytePrintable.java b/pki/base/util/src/netscape/security/util/CharToBytePrintable.java
index 970f7782..3fd01cf1 100644
--- a/pki/base/util/src/netscape/security/util/CharToBytePrintable.java
+++ b/pki/base/util/src/netscape/security/util/CharToBytePrintable.java
@@ -23,100 +23,100 @@ import sun.io.MalformedInputException;
import sun.io.UnknownCharacterException;
/**
- * Converts a string of ASN.1 PrintableString characters to PrintableString
+ * Converts a string of ASN.1 PrintableString characters to PrintableString
* bytes.
- *
+ *
* @author Lily Hsiao
* @author Slava Galperin
*/
-public class CharToBytePrintable extends CharToByteConverter
-{
+public class CharToBytePrintable extends CharToByteConverter {
/*
* returns the character set id for the conversion.
+ *
* @return the character set id.
*/
- public String getCharacterEncoding()
- {
- return "ASN.1 Printable";
+ public String getCharacterEncoding() {
+ return "ASN.1 Printable";
}
- public static boolean isPrintableChar( char c )
- {
- if ((c < 'A' || c > 'Z') &&
- (c < 'a' || c > 'z') &&
- (c < '0' || c > '9') &&
- (c != ' ') &&
- (c != '\'') &&
- (c != '(') &&
- (c != ')') &&
- (c != '+') &&
- (c != ',') &&
- (c != '-') &&
- (c != '.') &&
- (c != '/') &&
- (c != ':') &&
- (c != '=') &&
- (c != '?'))
- {
- return false;
- } else {
- return true;
- }
+ public static boolean isPrintableChar(char c) {
+ if ((c < 'A' || c > 'Z') &&
+ (c < 'a' || c > 'z') &&
+ (c < '0' || c > '9') &&
+ (c != ' ') &&
+ (c != '\'') &&
+ (c != '(') &&
+ (c != ')') &&
+ (c != '+') &&
+ (c != ',') &&
+ (c != '-') &&
+ (c != '.') &&
+ (c != '/') &&
+ (c != ':') &&
+ (c != '=') &&
+ (c != '?')) {
+ return false;
+ } else {
+ return true;
+ }
}
- /*
- * Converts an array of Unicode characters into an array of Printable
- * String bytes and returns the total number of characters converted.
- * If conversion cannot be done, UnknownCharacterException is
- * thrown. The character and byte offset will be set to the point
- * of the unknown character.
+ /*
+ * Converts an array of Unicode characters into an array of Printable String
+ * bytes and returns the total number of characters converted. If conversion
+ * cannot be done, UnknownCharacterException is thrown. The character and
+ * byte offset will be set to the point of the unknown character.
+ *
* @param input character array to convert.
+ *
* @param inStart offset from which to start the conversion.
+ *
* @param inEnd where to end the conversion.
+ *
* @param output byte array to store converted bytes.
+ *
* @param outStart starting offset in the output byte array.
+ *
* @param outEnd ending offset in the output byte array.
+ *
* @return the number of characters converted.
*/
- public int convert(char[] input, int inStart, int inEnd,
- byte[] output, int outStart, int outEnd)
- throws MalformedInputException, UnknownCharacterException,
- ConversionBufferFullException
- {
- int j = outStart;
- int i;
- for (i = inStart; i < inEnd ; i++, j++)
- {
- if (j >= outEnd) {
- charOff = i;
- byteOff = j;
- throw new ConversionBufferFullException();
- }
- if (!subMode && !isPrintableChar(input[i])) {
- charOff = i;
- byteOff = j;
- badInputLength = 1;
- throw new UnknownCharacterException();
- }
- output[j] = (byte) (input[i] & 0x7f);
- }
- charOff = i;
- byteOff = j;
- return j - outStart;
+ public int convert(char[] input, int inStart, int inEnd,
+ byte[] output, int outStart, int outEnd)
+ throws MalformedInputException, UnknownCharacterException,
+ ConversionBufferFullException {
+ int j = outStart;
+ int i;
+ for (i = inStart; i < inEnd; i++, j++) {
+ if (j >= outEnd) {
+ charOff = i;
+ byteOff = j;
+ throw new ConversionBufferFullException();
+ }
+ if (!subMode && !isPrintableChar(input[i])) {
+ charOff = i;
+ byteOff = j;
+ badInputLength = 1;
+ throw new UnknownCharacterException();
+ }
+ output[j] = (byte) (input[i] & 0x7f);
+ }
+ charOff = i;
+ byteOff = j;
+ return j - outStart;
}
public int flush(byte[] output, int outStart, int outEnd)
- throws MalformedInputException, ConversionBufferFullException
- {
- return 0;
+ throws MalformedInputException, ConversionBufferFullException {
+ return 0;
}
- public void reset() { }
+ public void reset() {
+ }
- public int getMaxBytesPerChar()
- {
- return 1;
+ public int getMaxBytesPerChar() {
+ return 1;
}
}
diff --git a/pki/base/util/src/netscape/security/util/CharToByteUniversalString.java b/pki/base/util/src/netscape/security/util/CharToByteUniversalString.java
index 0d566d53..03f6b0b8 100644
--- a/pki/base/util/src/netscape/security/util/CharToByteUniversalString.java
+++ b/pki/base/util/src/netscape/security/util/CharToByteUniversalString.java
@@ -23,63 +23,69 @@ import sun.io.UnknownCharacterException;
/**
* Converts a string of ASN.1 IA5String characters to IA5String bytes.
- *
+ *
* @author Lily Hsiao
* @author Slava Galperin
*/
-public class CharToByteUniversalString extends CharToByteConverter
-{
+public class CharToByteUniversalString extends CharToByteConverter {
/*
* Returns the character set id for the conversion.
+ *
* @return the character set id.
*/
- public String getCharacterEncoding () {
- return "ASN.1 UniversalString";
+ public String getCharacterEncoding() {
+ return "ASN.1 UniversalString";
}
/*
* Converts an array of Unicode characters into an array of UniversalString
- * bytes and returns the total number of characters converted.
- * If conversion cannot be done, UnknownCharacterException is
- * thrown. The character and byte offset will be set to the point
- * of the unknown character.
+ * bytes and returns the total number of characters converted. If conversion
+ * cannot be done, UnknownCharacterException is thrown. The character and
+ * byte offset will be set to the point of the unknown character.
+ *
* @param input character array to convert.
+ *
* @param inStart offset from which to start the conversion.
+ *
* @param inEnd where to end the conversion.
+ *
* @param output byte array to store converted bytes.
+ *
* @param outStart starting offset in the output byte array.
+ *
* @param outEnd ending offset in the output byte array.
+ *
* @return the number of characters converted.
*/
public int convert(char[] input, int inStart, int inEnd,
- byte[] output, int outStart, int outEnd)
- throws ConversionBufferFullException,
- UnknownCharacterException
- {
- int j = outStart;
- for (int i = inStart; i < inEnd; i++) {
- if (j+3 >= outEnd) {
- charOff = i;
- byteOff = j;
- throw new ConversionBufferFullException();
- }
- output[j++] = 0;
- output[j++] = 0;
- output[j++] = (byte) ((input[i] >> 8) & 0xff);
- output[j++] = (byte) (input[i] & 0xff);
- }
+ byte[] output, int outStart, int outEnd)
+ throws ConversionBufferFullException,
+ UnknownCharacterException {
+ int j = outStart;
+ for (int i = inStart; i < inEnd; i++) {
+ if (j + 3 >= outEnd) {
+ charOff = i;
+ byteOff = j;
+ throw new ConversionBufferFullException();
+ }
+ output[j++] = 0;
+ output[j++] = 0;
+ output[j++] = (byte) ((input[i] >> 8) & 0xff);
+ output[j++] = (byte) (input[i] & 0xff);
+ }
- return j - outStart;
+ return j - outStart;
}
public int flush(byte[] output, int outStart, int outEnd) {
- return 0;
+ return 0;
}
- public void reset() { }
+ public void reset() {
+ }
public int getMaxBytesPerChar() {
- return 4;
+ return 4;
}
}
diff --git a/pki/base/util/src/netscape/security/util/CrlPrettyPrint.java b/pki/base/util/src/netscape/security/util/CrlPrettyPrint.java
index ade21420..7d7ccf94 100644
--- a/pki/base/util/src/netscape/security/util/CrlPrettyPrint.java
+++ b/pki/base/util/src/netscape/security/util/CrlPrettyPrint.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package netscape.security.util;
-
import java.text.DateFormat;
import java.util.Iterator;
import java.util.Locale;
@@ -30,46 +29,46 @@ import netscape.security.x509.Extension;
import netscape.security.x509.RevokedCertificate;
import netscape.security.x509.X509CRLImpl;
-
/**
- * This class will display the certificate content in predefined
- * format.
- *
+ * This class will display the certificate content in predefined format.
+ *
* @author Andrew Wnuk
* @version $Revision$, $Date$
*/
-public class CrlPrettyPrint
-{
+public class CrlPrettyPrint {
- /*==========================================================
- * constants
- *==========================================================*/
+ /*
+ * ========================================================== constants
+ * ==========================================================
+ */
private final static String CUSTOM_LOCALE = "Custom";
- /*==========================================================
- * variables
- *==========================================================*/
+ /*
+ * ========================================================== variables
+ * ==========================================================
+ */
private X509CRLImpl mCRL = null;
private PrettyPrintFormat pp = null;
- /*==========================================================
- * constructors
- *==========================================================*/
+ /*
+ * ========================================================== constructors
+ * ==========================================================
+ */
public CrlPrettyPrint(X509CRLImpl crl) {
mCRL = crl;
pp = new PrettyPrintFormat(":");
}
- /*==========================================================
- * public methods
- *==========================================================*/
+ /*
+ * ========================================================== public methods
+ * ==========================================================
+ */
/**
- * This method return string representation of the certificate
- * revocation list in predefined format using specified client
- * local. I18N Support.
- *
+ * This method return string representation of the certificate revocation
+ * list in predefined format using specified client local. I18N Support.
+ *
* @param clientLocale Locale to be used for localization
* @return string representation of the certificate
*/
@@ -79,12 +78,12 @@ public class CrlPrettyPrint
public String toString(Locale clientLocale, long crlSize, long pageStart, long pageSize) {
- //get I18N resources
+ // get I18N resources
ResourceBundle resource = ResourceBundle.getBundle(
PrettyPrintResources.class.getName());
DateFormat dateFormater = DateFormat.getDateTimeInstance(
DateFormat.FULL, DateFormat.FULL, clientLocale);
- //get timezone and timezone ID
+ // get timezone and timezone ID
String tz = " ";
String tzid = " ";
@@ -100,10 +99,10 @@ public class CrlPrettyPrint
sb.append((mCRL.getVersion() + 1) + "\n");
sb.append(pp.indent(12) + resource.getString(
PrettyPrintResources.TOKEN_SIGALG) + mCRL.getSigAlgName() +
- " - " + mCRL.getSigAlgOID() + "\n");
+ " - " + mCRL.getSigAlgOID() + "\n");
sb.append(pp.indent(12) + resource.getString(
PrettyPrintResources.TOKEN_ISSUER) +
- mCRL.getIssuerDN().toString() + "\n");
+ mCRL.getIssuerDN().toString() + "\n");
// Format thisUpdate
String thisUpdate = dateFormater.format(mCRL.getThisUpdate());
@@ -111,7 +110,7 @@ public class CrlPrettyPrint
if (TimeZone.getDefault() != null) {
tz = TimeZone.getDefault().getDisplayName(
TimeZone.getDefault().inDaylightTime(
- mCRL.getThisUpdate()),
+ mCRL.getThisUpdate()),
TimeZone.SHORT,
clientLocale);
tzid = TimeZone.getDefault().getID();
@@ -120,17 +119,17 @@ public class CrlPrettyPrint
if (tz.equals(tzid) || tzid.equals(CUSTOM_LOCALE)) {
// Do NOT append timezone ID
sb.append(pp.indent(12)
- + resource.getString(
- PrettyPrintResources.TOKEN_THIS_UPDATE)
- + thisUpdate
- + "\n");
+ + resource.getString(
+ PrettyPrintResources.TOKEN_THIS_UPDATE)
+ + thisUpdate
+ + "\n");
} else {
// Append timezone ID
sb.append(pp.indent(12)
- + resource.getString(
- PrettyPrintResources.TOKEN_THIS_UPDATE)
- + thisUpdate
- + " " + tzid + "\n");
+ + resource.getString(
+ PrettyPrintResources.TOKEN_THIS_UPDATE)
+ + thisUpdate
+ + " " + tzid + "\n");
}
// Check for presence of NextUpdate
if (mCRL.getNextUpdate() != null) {
@@ -141,7 +140,7 @@ public class CrlPrettyPrint
if (TimeZone.getDefault() != null) {
tz = TimeZone.getDefault().getDisplayName(
TimeZone.getDefault().inDaylightTime(
- mCRL.getNextUpdate()),
+ mCRL.getNextUpdate()),
TimeZone.SHORT,
clientLocale);
}
@@ -149,17 +148,17 @@ public class CrlPrettyPrint
if (tz.equals(tzid) || tzid.equals(CUSTOM_LOCALE)) {
// Do NOT append timezone ID
sb.append(pp.indent(12)
- + resource.getString(
- PrettyPrintResources.TOKEN_NEXT_UPDATE)
- + nextUpdate
- + "\n");
+ + resource.getString(
+ PrettyPrintResources.TOKEN_NEXT_UPDATE)
+ + nextUpdate
+ + "\n");
} else {
// Append timezone ID
sb.append(pp.indent(12)
- + resource.getString(
- PrettyPrintResources.TOKEN_NEXT_UPDATE)
- + nextUpdate
- + " " + tzid + "\n");
+ + resource.getString(
+ PrettyPrintResources.TOKEN_NEXT_UPDATE)
+ + nextUpdate
+ + " " + tzid + "\n");
}
}
@@ -167,7 +166,7 @@ public class CrlPrettyPrint
sb.append(pp.indent(12) + resource.getString(
PrettyPrintResources.TOKEN_REVOKED_CERTIFICATES) + crlSize + "\n");
} else if ((crlSize == 0 && pageStart == 0 && pageSize == 0) ||
- (crlSize > 0 && pageStart > 0 && pageSize > 0)) {
+ (crlSize > 0 && pageStart > 0 && pageSize > 0)) {
sb.append(pp.indent(12) + resource.getString(
PrettyPrintResources.TOKEN_REVOKED_CERTIFICATES));
if (crlSize > 0 && pageStart > 0 && pageSize > 0) {
@@ -189,35 +188,35 @@ public class CrlPrettyPrint
if ((crlSize == 0) || ((pageStart <= l) && (pageStart + pageSize > l))) {
sb.append(pp.indent(16) + resource.getString(
PrettyPrintResources.TOKEN_SERIAL) + "0x" +
- revokedCert.getSerialNumber().toString(16).toUpperCase() + "\n");
+ revokedCert.getSerialNumber().toString(16).toUpperCase() + "\n");
String revocationDate =
- dateFormater.format(revokedCert.getRevocationDate());
+ dateFormater.format(revokedCert.getRevocationDate());
// re-get timezone
// (just in case it is different . . .)
if (TimeZone.getDefault() != null) {
tz = TimeZone.getDefault().getDisplayName(
TimeZone.getDefault().inDaylightTime(
- revokedCert.getRevocationDate()),
+ revokedCert.getRevocationDate()),
TimeZone.SHORT,
clientLocale);
}
// Specify revocationDate
if (tz.equals(tzid) ||
- tzid.equals(CUSTOM_LOCALE)) {
+ tzid.equals(CUSTOM_LOCALE)) {
// Do NOT append timezone ID
sb.append(pp.indent(16)
- + resource.getString(
- PrettyPrintResources.TOKEN_REVOCATION_DATE)
- + revocationDate
- + "\n");
+ + resource.getString(
+ PrettyPrintResources.TOKEN_REVOCATION_DATE)
+ + revocationDate
+ + "\n");
} else {
// Append timezone ID
sb.append(pp.indent(16)
- + resource.getString(
- PrettyPrintResources.TOKEN_REVOCATION_DATE)
- + revocationDate
- + " " + tzid + "\n");
+ + resource.getString(
+ PrettyPrintResources.TOKEN_REVOCATION_DATE)
+ + revocationDate
+ + " " + tzid + "\n");
}
if (revokedCert.hasExtensions()) {
sb.append(pp.indent(16) + resource.getString(
@@ -252,13 +251,13 @@ public class CrlPrettyPrint
}
}
- //take care of signature
+ // take care of signature
sb.append(pp.indent(8) + resource.getString(
PrettyPrintResources.TOKEN_SIGNATURE) + "\n");
- //XXX I18N Algorithm Name ?
+ // XXX I18N Algorithm Name ?
sb.append(pp.indent(12) + resource.getString(
PrettyPrintResources.TOKEN_ALGORITHM) +
- mCRL.getSigAlgName() + " - " + mCRL.getSigAlgOID() + "\n");
+ mCRL.getSigAlgName() + " - " + mCRL.getSigAlgOID() + "\n");
sb.append(pp.indent(12) + resource.getString(
PrettyPrintResources.TOKEN_SIGNATURE) + "\n");
sb.append(pp.toHexString(mCRL.getSignature(), 16, 16));
diff --git a/pki/base/util/src/netscape/security/util/DerEncoder.java b/pki/base/util/src/netscape/security/util/DerEncoder.java
index 53bf27a6..c0fabab9 100644
--- a/pki/base/util/src/netscape/security/util/DerEncoder.java
+++ b/pki/base/util/src/netscape/security/util/DerEncoder.java
@@ -21,20 +21,20 @@ import java.io.IOException;
import java.io.OutputStream;
/**
- * Interface to an object that knows how to write its own DER
- * encoding to an output stream.
- *
+ * Interface to an object that knows how to write its own DER encoding to an
+ * output stream.
+ *
* @version 1.2 97/12/10
* @author D. N. Hoover
*/
public interface DerEncoder {
-
+
/**
* DER encode this object and write the results to a stream.
- *
- * @param out the stream on which the DER encoding is written.
+ *
+ * @param out the stream on which the DER encoding is written.
*/
- public void derEncode(OutputStream out)
- throws IOException;
+ public void derEncode(OutputStream out)
+ throws IOException;
}
diff --git a/pki/base/util/src/netscape/security/util/DerInputBuffer.java b/pki/base/util/src/netscape/security/util/DerInputBuffer.java
index 74ab9f70..a4bbbef4 100644
--- a/pki/base/util/src/netscape/security/util/DerInputBuffer.java
+++ b/pki/base/util/src/netscape/security/util/DerInputBuffer.java
@@ -15,171 +15,171 @@
// (C) 2007 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
-package netscape.security.util ;
+package netscape.security.util;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
-
/**
- * DER input buffer ... this is the main abstraction in the DER library
- * which actively works with the "untyped byte stream" abstraction. It
- * does so with impunity, since it's not intended to be exposed to the
- * anyone who could violate the "typed value stream" DER model and hence
- * corrupt the input stream of DER values.
- *
+ * DER input buffer ... this is the main abstraction in the DER library which
+ * actively works with the "untyped byte stream" abstraction. It does so with
+ * impunity, since it's not intended to be exposed to the anyone who could
+ * violate the "typed value stream" DER model and hence corrupt the input stream
+ * of DER values.
+ *
* @version 1.11
* @author David Brownell
*/
class DerInputBuffer extends ByteArrayInputStream implements Cloneable {
- DerInputBuffer(byte[] buf) { super(buf); }
+ DerInputBuffer(byte[] buf) {
+ super(buf);
+ }
DerInputBuffer(byte[] buf, int offset, int len) {
super(buf, offset, len);
}
DerInputBuffer dup() {
- try {
- DerInputBuffer retval = (DerInputBuffer) clone ();
-
- retval.mark (Integer.MAX_VALUE);
- return retval;
- } catch (CloneNotSupportedException e) {
- throw new IllegalArgumentException (e.toString ());
- }
+ try {
+ DerInputBuffer retval = (DerInputBuffer) clone();
+
+ retval.mark(Integer.MAX_VALUE);
+ return retval;
+ } catch (CloneNotSupportedException e) {
+ throw new IllegalArgumentException(e.toString());
+ }
}
byte[] toByteArray() {
- int len = available();
+ int len = available();
if (len <= 0)
return null;
- byte[] retval = new byte[len];
+ byte[] retval = new byte[len];
- System.arraycopy(buf, pos, retval, 0, len);
- return retval;
+ System.arraycopy(buf, pos, retval, 0, len);
+ return retval;
}
int peek() throws IOException {
- if (pos >= count)
- throw new IOException ("out of data");
- else
- return buf [pos];
+ if (pos >= count)
+ throw new IOException("out of data");
+ else
+ return buf[pos];
}
/**
- * Compares this DerInputBuffer for equality with the specified
- * object.
+ * Compares this DerInputBuffer for equality with the specified object.
*/
public boolean equals(Object other) {
- if (other instanceof DerInputBuffer)
- return equals ((DerInputBuffer) other);
- else
- return false;
+ if (other instanceof DerInputBuffer)
+ return equals((DerInputBuffer) other);
+ else
+ return false;
}
boolean equals(DerInputBuffer other) {
- if (this == other)
- return true;
-
- int max = this.available();
- if (other.available() != max)
- return false;
- for (int i = 0; i < max; i++) {
- if (this.buf [this.pos + i] != other.buf [other.pos + i]) {
- return false;
- }
- }
- return true;
+ if (this == other)
+ return true;
+
+ int max = this.available();
+ if (other.available() != max)
+ return false;
+ for (int i = 0; i < max; i++) {
+ if (this.buf[this.pos + i] != other.buf[other.pos + i]) {
+ return false;
+ }
+ }
+ return true;
}
void truncate(int len) throws IOException {
- if (len > available ())
- throw new IOException ("insufficient data");
- count = pos + len;
+ if (len > available())
+ throw new IOException("insufficient data");
+ count = pos + len;
}
/**
- * Returns the unsigned integer which takes up the specified number
- * of bytes in this buffer.
+ * Returns the unsigned integer which takes up the specified number of bytes
+ * in this buffer.
*/
BigInt getUnsigned(int len) throws IOException {
- if (len > available ())
- throw new IOException ("short read, getInteger");
-
- /*
- * A prepended zero is used to ensure that the integer is
- * interpreted as unsigned even when the high order bit is
- * zero. We don't support signed BigInts.
- *
- * Fix this here ... BigInts aren't expected to have these,
- * and stuff like signing (sigsize = f(modulus)) misbehaves.
- */
- if (len > 1 && buf [pos] == 0) {
- len--;
- skip (1);
- }
-
- /*
- * Consume the rest of the buffer, returning its value as
- * an unsigned integer.
- */
- byte[] bytes = new byte[len];
-
- System.arraycopy (buf, pos, bytes, 0, len);
- skip (len);
- return new BigInt (bytes);
+ if (len > available())
+ throw new IOException("short read, getInteger");
+
+ /*
+ * A prepended zero is used to ensure that the integer is interpreted as
+ * unsigned even when the high order bit is zero. We don't support
+ * signed BigInts.
+ *
+ * Fix this here ... BigInts aren't expected to have these, and stuff
+ * like signing (sigsize = f(modulus)) misbehaves.
+ */
+ if (len > 1 && buf[pos] == 0) {
+ len--;
+ skip(1);
+ }
+
+ /*
+ * Consume the rest of the buffer, returning its value as an unsigned
+ * integer.
+ */
+ byte[] bytes = new byte[len];
+
+ System.arraycopy(buf, pos, bytes, 0, len);
+ skip(len);
+ return new BigInt(bytes);
}
/**
- * Returns the bit string which takes up the rest of this buffer.
- * This bit string must be byte-aligned.
- */
+ * Returns the bit string which takes up the rest of this buffer. This bit
+ * string must be byte-aligned.
+ */
byte[] getBitString() {
- if (pos >= count || buf [pos] != 0)
- return null;
- /*
- * Just copy the data into an aligned, padded octet buffer,
- * and consume the rest of the buffer.
- */
- int len = available ();
- byte[] retval = new byte[len - 1];
-
- System.arraycopy (buf, pos + 1, retval, 0, len - 1);
- pos = count;
- return retval;
+ if (pos >= count || buf[pos] != 0)
+ return null;
+ /*
+ * Just copy the data into an aligned, padded octet buffer, and consume
+ * the rest of the buffer.
+ */
+ int len = available();
+ byte[] retval = new byte[len - 1];
+
+ System.arraycopy(buf, pos + 1, retval, 0, len - 1);
+ pos = count;
+ return retval;
+ }
+
+ /**
+ * Returns the bit string which takes up the rest of this buffer. The bit
+ * string need not be byte-aligned.
+ */
+ BitArray getUnalignedBitString() {
+ if (pos >= count)
+ return null;
+ /*
+ * Just copy the data into an aligned, padded octet buffer, and consume
+ * the rest of the buffer.
+ */
+ int len = available();
+ byte[] bits = new byte[len - 1];
+ int length = bits.length * 8 - buf[pos]; // number of valid bits
+
+ System.arraycopy(buf, pos + 1, bits, 0, len - 1);
+
+ BitArray bitArray = new BitArray(length, bits);
+ pos = count;
+ return bitArray;
+ }
+
+ /**
+ * Package-access method to optimize output operations
+ */
+ void dump(OutputStream out, int length) throws IOException {
+ if (count < mark + length)
+ throw new IOException("short DER value (encode)");
+ out.write(buf, mark, length);
}
- /**
- * Returns the bit string which takes up the rest of this buffer.
- * The bit string need not be byte-aligned.
- */
- BitArray getUnalignedBitString() {
- if (pos >= count)
- return null;
- /*
- * Just copy the data into an aligned, padded octet buffer,
- * and consume the rest of the buffer.
- */
- int len = available();
- byte[] bits = new byte[len - 1];
- int length = bits.length*8 - buf[pos]; // number of valid bits
-
- System.arraycopy(buf, pos + 1, bits, 0, len - 1);
-
- BitArray bitArray = new BitArray(length, bits);
- pos = count;
- return bitArray;
- }
-
- /**
- * Package-access method to optimize output operations
- */
- void dump(OutputStream out, int length) throws IOException {
- if (count < mark + length)
- throw new IOException ("short DER value (encode)");
- out.write(buf,mark,length);
- }
-
}
diff --git a/pki/base/util/src/netscape/security/util/DerInputStream.java b/pki/base/util/src/netscape/security/util/DerInputStream.java
index fb73b761..0cf9ac0b 100644
--- a/pki/base/util/src/netscape/security/util/DerInputStream.java
+++ b/pki/base/util/src/netscape/security/util/DerInputStream.java
@@ -26,93 +26,92 @@ import java.util.TimeZone;
import java.util.Vector;
/**
- * A DER input stream, used for parsing ASN.1 DER-encoded data such as
- * that found in X.509 certificates. DER is a subset of BER/1, which has
- * the advantage that it allows only a single encoding of primitive data.
- * (High level data such as dates still support many encodings.) That is,
- * it uses the "Definite" Encoding Rules (DER) not the "Basic" ones (BER).
- *
- * <P>Note that, like BER/1, DER streams are streams of explicitly
- * tagged data values. Accordingly, this programming interface does
- * not expose any variant of the java.io.InputStream interface, since
- * that kind of input stream holds untagged data values and using that
- * I/O model could prevent correct parsing of the DER data.
- *
- * <P>At this time, this class supports only a subset of the types of DER
- * data encodings which are defined. That subset is sufficient for parsing
- * most X.509 certificates.
- *
+ * A DER input stream, used for parsing ASN.1 DER-encoded data such as that
+ * found in X.509 certificates. DER is a subset of BER/1, which has the
+ * advantage that it allows only a single encoding of primitive data. (High
+ * level data such as dates still support many encodings.) That is, it uses the
+ * "Definite" Encoding Rules (DER) not the "Basic" ones (BER).
+ *
+ * <P>
+ * Note that, like BER/1, DER streams are streams of explicitly tagged data
+ * values. Accordingly, this programming interface does not expose any variant
+ * of the java.io.InputStream interface, since that kind of input stream holds
+ * untagged data values and using that I/O model could prevent correct parsing
+ * of the DER data.
+ *
+ * <P>
+ * At this time, this class supports only a subset of the types of DER data
+ * encodings which are defined. That subset is sufficient for parsing most X.509
+ * certificates.
+ *
* @version 1.35
- *
+ *
* @author David Brownell
* @author Amit Kapoor
* @author Hemma Prafullchandra
*/
public class DerInputStream {
/*
- * This version only supports fully buffered DER. This is easy to
- * work with, though if large objects are manipulated DER becomes
- * awkward to deal with. That's where BER is useful, since BER
- * handles streaming data relatively well.
+ * This version only supports fully buffered DER. This is easy to work with,
+ * though if large objects are manipulated DER becomes awkward to deal with.
+ * That's where BER is useful, since BER handles streaming data relatively
+ * well.
*/
- DerInputBuffer buffer;
+ DerInputBuffer buffer;
/**
- * Create a DER input stream from a data buffer. The buffer is not
- * copied, it is shared. Accordingly, the buffer should be treated
- * as read-only.
- *
+ * Create a DER input stream from a data buffer. The buffer is not copied,
+ * it is shared. Accordingly, the buffer should be treated as read-only.
+ *
* @param data the buffer from which to create the string (CONSUMED)
*/
public DerInputStream(byte[] data) {
- buffer = new DerInputBuffer(data);
- buffer.mark(Integer.MAX_VALUE);
+ buffer = new DerInputBuffer(data);
+ buffer.mark(Integer.MAX_VALUE);
}
/**
- * Create a DER input stream from part of a data buffer.
- * The buffer is not copied, it is shared. Accordingly, the
- * buffer should be treated as read-only.
- *
+ * Create a DER input stream from part of a data buffer. The buffer is not
+ * copied, it is shared. Accordingly, the buffer should be treated as
+ * read-only.
+ *
* @param data the buffer from which to create the string (CONSUMED)
- * @param offset the first index of <em>data</em> which will
- * be read as DER input in the new stream
- * @param len how long a chunk of the buffer to use,
- * starting at "offset"
+ * @param offset the first index of <em>data</em> which will be read as DER
+ * input in the new stream
+ * @param len how long a chunk of the buffer to use, starting at "offset"
*/
public DerInputStream(byte[] data, int offset, int len) {
- buffer = new DerInputBuffer(data, offset, len);
- buffer.mark(Integer.MAX_VALUE);
+ buffer = new DerInputBuffer(data, offset, len);
+ buffer.mark(Integer.MAX_VALUE);
}
DerInputStream(DerInputBuffer buf) {
- buffer = buf;
- buffer.mark(Integer.MAX_VALUE);
+ buffer = buf;
+ buffer.mark(Integer.MAX_VALUE);
}
/**
* Creates a new DER input stream from part of this input stream.
*
- * @param len how long a chunk of the current input stream to use,
- * starting at the current position.
- * @param do_skip true if the existing data in the input stream should
- * be skipped. If this value is false, the next data read
- * on this stream and the newly created stream will be the
- * same.
+ * @param len how long a chunk of the current input stream to use, starting
+ * at the current position.
+ * @param do_skip true if the existing data in the input stream should be
+ * skipped. If this value is false, the next data read on this
+ * stream and the newly created stream will be the same.
*/
- public DerInputStream subStream(int len, boolean do_skip)
- throws IOException {
- DerInputBuffer newbuf = buffer.dup();
-
- newbuf.truncate(len);
- if (do_skip)
- buffer.skip(len);
- return new DerInputStream(newbuf);
+ public DerInputStream subStream(int len, boolean do_skip)
+ throws IOException {
+ DerInputBuffer newbuf = buffer.dup();
+
+ newbuf.truncate(len);
+ if (do_skip)
+ buffer.skip(len);
+ return new DerInputStream(newbuf);
}
/**
- * Return what has been written to this DerInputStream
- * as a byte array. Useful for debugging.
+ * Return what has been written to this DerInputStream as a byte array.
+ * Useful for debugging.
*/
public byte[] toByteArray() {
return buffer.toByteArray();
@@ -120,10 +119,9 @@ public class DerInputStream {
/*
* PRIMITIVES -- these are "universal" ASN.1 simple types.
- *
- * INTEGER, BIT STRING, OCTET STRING, NULL
- * OBJECT IDENTIFIER, SEQUENCE (OF), SET (OF)
- * PrintableString, T61String, IA5String, UTCTime
+ *
+ * INTEGER, BIT STRING, OCTET STRING, NULL OBJECT IDENTIFIER, SEQUENCE (OF),
+ * SET (OF) PrintableString, T61String, IA5String, UTCTime
*/
/**
@@ -133,245 +131,236 @@ public class DerInputStream {
if (buffer.read() != DerValue.tag_Integer)
throw new IOException("DER input, Integer tag error");
- return buffer.getUnsigned(getLength(buffer));
+ return buffer.getUnsigned(getLength(buffer));
}
/**
- * Get a bit string from the input stream. Only octet-aligned
- * bitstrings (multiples of eight bits in length) are handled
- * by this method.
+ * Get a bit string from the input stream. Only octet-aligned bitstrings
+ * (multiples of eight bits in length) are handled by this method.
*/
public byte[] getBitString() throws IOException {
- if (buffer.read() != DerValue.tag_BitString)
- throw new IOException("DER input not an bit string");
- int length = getLength(buffer);
-
- /*
- * This byte affects alignment and padding (for the last byte).
- * Use getUnalignedBitString() for none 8-bit aligned bit strings.
- */
- if (buffer.read() != 0)
- return null;
- length--;
-
- /*
- * Just read the data into an aligned, padded octet buffer.
- */
- byte[] retval = new byte[length];
- if (buffer.read(retval) != length)
- throw new IOException("short read of DER bit string");
- return retval;
+ if (buffer.read() != DerValue.tag_BitString)
+ throw new IOException("DER input not an bit string");
+ int length = getLength(buffer);
+
+ /*
+ * This byte affects alignment and padding (for the last byte). Use
+ * getUnalignedBitString() for none 8-bit aligned bit strings.
+ */
+ if (buffer.read() != 0)
+ return null;
+ length--;
+
+ /*
+ * Just read the data into an aligned, padded octet buffer.
+ */
+ byte[] retval = new byte[length];
+ if (buffer.read(retval) != length)
+ throw new IOException("short read of DER bit string");
+ return retval;
}
/**
- * Get a bit string from the input stream. The bit string need
- * not be byte-aligned.
+ * Get a bit string from the input stream. The bit string need not be
+ * byte-aligned.
*/
public BitArray getUnalignedBitString() throws IOException {
- if (buffer.read() != DerValue.tag_BitString)
- throw new IOException("DER input not a bit string");
+ if (buffer.read() != DerValue.tag_BitString)
+ throw new IOException("DER input not a bit string");
- int length = getLength(buffer) - 1;
+ int length = getLength(buffer) - 1;
- /*
- * First byte = number of excess bits in the last octet of the
- * representation.
- */
- int validBits = length*8 - buffer.read();
+ /*
+ * First byte = number of excess bits in the last octet of the
+ * representation.
+ */
+ int validBits = length * 8 - buffer.read();
- byte[] repn = new byte[length];
+ byte[] repn = new byte[length];
- if (buffer.read(repn) != length)
- throw new IOException("short read of DER bit string");
- return new BitArray(validBits, repn);
+ if (buffer.read(repn) != length)
+ throw new IOException("short read of DER bit string");
+ return new BitArray(validBits, repn);
}
/**
* Returns an ASN.1 OCTET STRING from the input stream.
*/
public byte[] getOctetString() throws IOException {
- if (buffer.read() != DerValue.tag_OctetString)
- throw new IOException("DER input not an octet string");
+ if (buffer.read() != DerValue.tag_OctetString)
+ throw new IOException("DER input not an octet string");
- int length = getLength(buffer);
- byte[] retval = new byte[length];
- if (buffer.read(retval) != length)
- throw new IOException("short read of DER octet string");
+ int length = getLength(buffer);
+ byte[] retval = new byte[length];
+ if (buffer.read(retval) != length)
+ throw new IOException("short read of DER octet string");
- return retval;
+ return retval;
}
/**
* Returns the asked number of bytes from the input stream.
*/
public void getBytes(byte[] val) throws IOException {
- if (val.length != 0) {
+ if (val.length != 0) {
if (buffer.read(val) != val.length) {
- throw new IOException("short read of DER octet string");
- }
- }
+ throw new IOException("short read of DER octet string");
+ }
+ }
}
/**
* Reads an encoded null value from the input stream.
*/
public void getNull() throws IOException {
- if (buffer.read() != DerValue.tag_Null || buffer.read() != 0)
- throw new IOException("getNull, bad data");
+ if (buffer.read() != DerValue.tag_Null || buffer.read() != 0)
+ throw new IOException("getNull, bad data");
}
/**
* Reads an X.200 style Object Identifier from the stream.
*/
public ObjectIdentifier getOID() throws IOException {
- return new ObjectIdentifier(this);
+ return new ObjectIdentifier(this);
}
/**
- * Return a sequence of encoded entities. ASN.1 sequences are
- * ordered, and they are often used, like a "struct" in C or C++,
- * to group data values. They may have optional or context
- * specific values.
- *
- * @param startLen guess about how long the sequence will be
- * (used to initialize an auto-growing data structure)
+ * Return a sequence of encoded entities. ASN.1 sequences are ordered, and
+ * they are often used, like a "struct" in C or C++, to group data values.
+ * They may have optional or context specific values.
+ *
+ * @param startLen guess about how long the sequence will be (used to
+ * initialize an auto-growing data structure)
* @return array of the values in the sequence
*/
public DerValue[] getSequence(int startLen) throws IOException {
- int b = buffer.read();
- if (b != DerValue.tag_Sequence)
- throw new IOException("Sequence tag error " + b);
- return readVector(startLen);
+ int b = buffer.read();
+ if (b != DerValue.tag_Sequence)
+ throw new IOException("Sequence tag error " + b);
+ return readVector(startLen);
}
public void skipSequence(int startLen) throws IOException {
- int b = buffer.read();
- if (b != DerValue.tag_Sequence)
- throw new IOException("Sequence tag error " + b);
- int len = getLength(buffer);
- buffer.skip(len);
+ int b = buffer.read();
+ if (b != DerValue.tag_Sequence)
+ throw new IOException("Sequence tag error " + b);
+ int len = getLength(buffer);
+ buffer.skip(len);
}
/**
- * Return a set of encoded entities. ASN.1 sets are unordered,
- * though DER may specify an order for some kinds of sets (such
- * as the attributes in an X.500 relative distinguished name)
- * to facilitate binary comparisons of encoded values.
- *
- * @param startLen guess about how large the set will be
- * (used to initialize an auto-growing data structure)
+ * Return a set of encoded entities. ASN.1 sets are unordered, though DER
+ * may specify an order for some kinds of sets (such as the attributes in an
+ * X.500 relative distinguished name) to facilitate binary comparisons of
+ * encoded values.
+ *
+ * @param startLen guess about how large the set will be (used to initialize
+ * an auto-growing data structure)
* @return array of the values in the sequence
*/
public DerValue[] getSet(int startLen) throws IOException {
- if (buffer.read() != DerValue.tag_Set)
- throw new IOException("Set tag error");
- return readVector(startLen);
+ if (buffer.read() != DerValue.tag_Set)
+ throw new IOException("Set tag error");
+ return readVector(startLen);
}
/**
- * Return a set of encoded entities. ASN.1 sets are unordered,
- * though DER may specify an order for some kinds of sets (such
- * as the attributes in an X.500 relative distinguished name)
- * to facilitate binary comparisons of encoded values.
- *
- * @param startLen guess about how large the set will be
- * (used to initialize an auto-growing data structure)
+ * Return a set of encoded entities. ASN.1 sets are unordered, though DER
+ * may specify an order for some kinds of sets (such as the attributes in an
+ * X.500 relative distinguished name) to facilitate binary comparisons of
+ * encoded values.
+ *
+ * @param startLen guess about how large the set will be (used to initialize
+ * an auto-growing data structure)
* @param implicit if true tag is assumed implicit.
* @return array of the values in the sequence
*/
public DerValue[] getSet(int startLen, boolean implicit) throws IOException {
int tag = buffer.read();
- if (!implicit) {
- if (tag != DerValue.tag_Set) {
- throw new IOException("Set tag error");
- }
- }
- return (readVector(startLen));
+ if (!implicit) {
+ if (tag != DerValue.tag_Set) {
+ throw new IOException("Set tag error");
+ }
+ }
+ return (readVector(startLen));
}
/*
- * Read a "vector" of values ... set or sequence have the
- * same encoding, except for the initial tag, so both use
- * this same helper routine.
+ * Read a "vector" of values ... set or sequence have the same encoding,
+ * except for the initial tag, so both use this same helper routine.
*/
protected DerValue[] readVector(int startLen) throws IOException {
- int len = getLength(buffer);
- DerInputStream newstr;
+ int len = getLength(buffer);
+ DerInputStream newstr;
- if (len == 0)
- // return empty array instead of null, which should be
- // used only for missing optionals
- return new DerValue[0];
+ if (len == 0)
+ // return empty array instead of null, which should be
+ // used only for missing optionals
+ return new DerValue[0];
- /*
- * Create a temporary stream from which to read the data,
- * unless it's not really needed.
- */
- if (buffer.available() == len)
- newstr = this;
- else
- newstr = subStream(len, true);
+ /*
+ * Create a temporary stream from which to read the data, unless it's
+ * not really needed.
+ */
+ if (buffer.available() == len)
+ newstr = this;
+ else
+ newstr = subStream(len, true);
- /*
- * Pull values out of the stream.
- */
- Vector vec = new Vector(startLen);
- DerValue value;
+ /*
+ * Pull values out of the stream.
+ */
+ Vector vec = new Vector(startLen);
+ DerValue value;
- do {
- value = new DerValue(newstr.buffer);
- vec.addElement(value);
- } while (newstr.available() > 0);
+ do {
+ value = new DerValue(newstr.buffer);
+ vec.addElement(value);
+ } while (newstr.available() > 0);
- if (newstr.available() != 0)
- throw new IOException("extra data at end of vector");
+ if (newstr.available() != 0)
+ throw new IOException("extra data at end of vector");
- /*
- * Now stick them into the array we're returning.
- */
- int i, max = vec.size();
- DerValue[] retval = new DerValue[max];
+ /*
+ * Now stick them into the array we're returning.
+ */
+ int i, max = vec.size();
+ DerValue[] retval = new DerValue[max];
- for (i = 0; i < max; i++)
- retval[i] = (DerValue) vec.elementAt(i);
+ for (i = 0; i < max; i++)
+ retval[i] = (DerValue) vec.elementAt(i);
- return retval;
+ return retval;
}
/**
- * Get a single DER-encoded value from the input stream.
- * It can often be useful to pull a value from the stream
- * and defer parsing it. For example, you can pull a nested
- * sequence out with one call, and only examine its elements
- * later when you really need to.
+ * Get a single DER-encoded value from the input stream. It can often be
+ * useful to pull a value from the stream and defer parsing it. For example,
+ * you can pull a nested sequence out with one call, and only examine its
+ * elements later when you really need to.
*/
public DerValue getDerValue() throws IOException {
- return new DerValue(buffer);
+ return new DerValue(buffer);
}
- public String getPrintableString() throws IOException
- {
- return (new DerValue(buffer)).getPrintableString();
+ public String getPrintableString() throws IOException {
+ return (new DerValue(buffer)).getPrintableString();
}
- public String getT61String() throws IOException
- {
- return (new DerValue(buffer)).getT61String();
+ public String getT61String() throws IOException {
+ return (new DerValue(buffer)).getT61String();
}
- public String getIA5String() throws IOException
- {
- return (new DerValue(buffer)).getIA5String();
+ public String getIA5String() throws IOException {
+ return (new DerValue(buffer)).getIA5String();
}
- public String getBMPString () throws IOException
- {
- return (new DerValue(buffer)).getBMPString();
+ public String getBMPString() throws IOException {
+ return (new DerValue(buffer)).getBMPString();
}
- public String getUniversalString () throws IOException
- {
- return (new DerValue(buffer)).getUniversalString();
+ public String getUniversalString() throws IOException {
+ return (new DerValue(buffer)).getUniversalString();
}
/**
@@ -380,7 +369,7 @@ public class DerInputStream {
public Date getUTCTime() throws IOException {
if (buffer.read() != DerValue.tag_UtcTime)
throw new IOException("DER input, UTCtime tag invalid ");
- if (buffer.available() < 11)
+ if (buffer.available() < 11)
throw new IOException("DER input, UTCtime short input");
int len = getLength(buffer);
@@ -389,44 +378,43 @@ public class DerInputStream {
throw new IOException("DER getUTCTime length error");
/*
- * UTC time encoded as ASCII chars, YYMMDDhhmmss.
- * If YY <= 50, we assume 20YY;
- * if YY > 50, we assume 19YY, as per IETF-PKIX part I.
+ * UTC time encoded as ASCII chars, YYMMDDhhmmss. If YY <= 50, we assume
+ * 20YY; if YY > 50, we assume 19YY, as per IETF-PKIX part I.
*/
int year, month, day, hour, minute, second;
- year = 10 * Character.digit((char)buffer.read(), 10);
- year += Character.digit((char)buffer.read(), 10);
- if (year <= 50) // origin 2000
+ year = 10 * Character.digit((char) buffer.read(), 10);
+ year += Character.digit((char) buffer.read(), 10);
+ if (year <= 50) // origin 2000
year += 2000;
else
- year += 1900; // origin 1900
+ year += 1900; // origin 1900
- month = 10 * Character.digit((char)buffer.read(), 10);
- month += Character.digit((char)buffer.read(), 10);
- month -= 1; // months are 0-11
+ month = 10 * Character.digit((char) buffer.read(), 10);
+ month += Character.digit((char) buffer.read(), 10);
+ month -= 1; // months are 0-11
- day = 10 * Character.digit((char)buffer.read(), 10);
- day += Character.digit((char)buffer.read(), 10);
+ day = 10 * Character.digit((char) buffer.read(), 10);
+ day += Character.digit((char) buffer.read(), 10);
- hour = 10 * Character.digit((char)buffer.read(), 10);
- hour += Character.digit((char)buffer.read(), 10);
+ hour = 10 * Character.digit((char) buffer.read(), 10);
+ hour += Character.digit((char) buffer.read(), 10);
- minute = 10 * Character.digit((char)buffer.read(), 10);
- minute += Character.digit((char)buffer.read(), 10);
+ minute = 10 * Character.digit((char) buffer.read(), 10);
+ minute += Character.digit((char) buffer.read(), 10);
- len -= 10;
+ len -= 10;
/**
- * We allow for non-encoded seconds, even though the
- * IETF-PKIX specification says that the seconds should
- * always be encoded even if it is zero.
+ * We allow for non-encoded seconds, even though the IETF-PKIX
+ * specification says that the seconds should always be encoded even if
+ * it is zero.
*/
if (len == 3 || len == 7) {
- second = 10 * Character.digit((char)buffer.read(), 10);
- second += Character.digit((char)buffer.read(), 10);
- len -= 2;
+ second = 10 * Character.digit((char) buffer.read(), 10);
+ second += Character.digit((char) buffer.read(), 10);
+ len -= 2;
} else
second = 0;
@@ -434,10 +422,10 @@ public class DerInputStream {
|| month > 11 || day > 31 || hour >= 24
|| minute >= 60 || second >= 60)
throw new IOException("Parse UTC time, invalid format");
-
- Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
- cal.set(year, month, day, hour, minute, second);
- cal.set(Calendar.MILLISECOND, 0); /* To clear millisecond field */
+
+ Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
+ cal.set(year, month, day, hour, minute, second);
+ cal.set(Calendar.MILLISECOND, 0); /* To clear millisecond field */
cal.set(Calendar.ERA, GregorianCalendar.AD);
Date readDate = cal.getTime();
long utcTime = readDate.getTime();
@@ -445,43 +433,41 @@ public class DerInputStream {
/*
* Finally, "Z" or "+hhmm" or "-hhmm" ... offsets change hhmm
*/
- if (! (len == 1 || len == 5))
+ if (!(len == 1 || len == 5))
throw new IOException("Parse UTC time, invalid offset");
switch (buffer.read()) {
- case '+':
- {
- int Htmp = 10 * Character.digit((char)buffer.read(), 10);
- Htmp += Character.digit((char)buffer.read(), 10);
- int Mtmp = 10 * Character.digit((char)buffer.read(), 10);
- Mtmp += Character.digit((char)buffer.read(), 10);
-
- if (Htmp >=24 || Mtmp >= 60)
- throw new IOException("Parse UTCtime, +hhmm");
-
- utcTime += ((Htmp * 60) + Mtmp) * 60 * 1000;
- }
- break;
-
- case '-':
- {
- int Htmp = 10 * Character.digit((char)buffer.read(), 10);
- Htmp += Character.digit((char)buffer.read(), 10);
- int Mtmp = 10 * Character.digit((char)buffer.read(), 10);
- Mtmp += Character.digit((char)buffer.read(), 10);
-
- if (Htmp >=24 || Mtmp >= 60)
- throw new IOException("Parse UTCtime, -hhmm");
-
- utcTime -= ((Htmp * 60) + Mtmp) * 60 * 1000;
- }
- break;
-
- case 'Z':
- break;
-
- default:
- throw new IOException("Parse UTCtime, garbage offset");
+ case '+': {
+ int Htmp = 10 * Character.digit((char) buffer.read(), 10);
+ Htmp += Character.digit((char) buffer.read(), 10);
+ int Mtmp = 10 * Character.digit((char) buffer.read(), 10);
+ Mtmp += Character.digit((char) buffer.read(), 10);
+
+ if (Htmp >= 24 || Mtmp >= 60)
+ throw new IOException("Parse UTCtime, +hhmm");
+
+ utcTime += ((Htmp * 60) + Mtmp) * 60 * 1000;
+ }
+ break;
+
+ case '-': {
+ int Htmp = 10 * Character.digit((char) buffer.read(), 10);
+ Htmp += Character.digit((char) buffer.read(), 10);
+ int Mtmp = 10 * Character.digit((char) buffer.read(), 10);
+ Mtmp += Character.digit((char) buffer.read(), 10);
+
+ if (Htmp >= 24 || Mtmp >= 60)
+ throw new IOException("Parse UTCtime, -hhmm");
+
+ utcTime -= ((Htmp * 60) + Mtmp) * 60 * 1000;
+ }
+ break;
+
+ case 'Z':
+ break;
+
+ default:
+ throw new IOException("Parse UTCtime, garbage offset");
}
readDate.setTime(utcTime);
return readDate;
@@ -491,49 +477,49 @@ public class DerInputStream {
* Get a Generalized encoded time value from the input stream.
*/
public Date getGeneralizedTime() throws IOException {
- if (buffer.read () != DerValue.tag_GeneralizedTime)
- throw new IOException ("DER input, GeneralizedTime tag invalid ");
-
- if (buffer.available() < 13)
- throw new IOException ("DER input, GeneralizedTime short input");
+ if (buffer.read() != DerValue.tag_GeneralizedTime)
+ throw new IOException("DER input, GeneralizedTime tag invalid ");
- int len = getLength (buffer);
+ if (buffer.available() < 13)
+ throw new IOException("DER input, GeneralizedTime short input");
+
+ int len = getLength(buffer);
/*
* Generalized time encoded as ASCII chars, YYYYMMDDhhmm[ss]
*/
int year, month, day, hour, minute, second;
- year = 1000 * Character.digit ((char)buffer.read (), 10);
- year += 100 * Character.digit ((char)buffer.read (), 10);
- year += 10 * Character.digit ((char)buffer.read (), 10);
- year += Character.digit ((char)buffer.read (), 10);
+ year = 1000 * Character.digit((char) buffer.read(), 10);
+ year += 100 * Character.digit((char) buffer.read(), 10);
+ year += 10 * Character.digit((char) buffer.read(), 10);
+ year += Character.digit((char) buffer.read(), 10);
- month = 10 * Character.digit ((char)buffer.read (), 10);
- month += Character.digit ((char)buffer.read (), 10);
- month -= 1; // Calendar months are 0-11
+ month = 10 * Character.digit((char) buffer.read(), 10);
+ month += Character.digit((char) buffer.read(), 10);
+ month -= 1; // Calendar months are 0-11
- day = 10 * Character.digit ((char)buffer.read (), 10);
- day += Character.digit ((char)buffer.read (), 10);
+ day = 10 * Character.digit((char) buffer.read(), 10);
+ day += Character.digit((char) buffer.read(), 10);
- hour = 10 * Character.digit ((char)buffer.read (), 10);
- hour += Character.digit ((char)buffer.read (), 10);
+ hour = 10 * Character.digit((char) buffer.read(), 10);
+ hour += Character.digit((char) buffer.read(), 10);
- minute = 10 * Character.digit ((char)buffer.read (), 10);
- minute += Character.digit ((char)buffer.read (), 10);
+ minute = 10 * Character.digit((char) buffer.read(), 10);
+ minute += Character.digit((char) buffer.read(), 10);
len -= 12;
/**
- * We allow for non-encoded seconds, even though the
- * IETF-PKIX specification says that the seconds should
- * always be encoded even if it is zero.
+ * We allow for non-encoded seconds, even though the IETF-PKIX
+ * specification says that the seconds should always be encoded even if
+ * it is zero.
*/
if (len == 3 || len == 7) {
- second = 10 * Character.digit ((char)buffer.read (), 10);
- second += Character.digit ((char)buffer.read (), 10);
- len -= 2;
+ second = 10 * Character.digit((char) buffer.read(), 10);
+ second += Character.digit((char) buffer.read(), 10);
+ len -= 2;
} else
second = 0;
@@ -541,12 +527,14 @@ public class DerInputStream {
|| month > 11 || day > 31 || hour >= 24
|| minute >= 60 || second >= 60)
throw new IOException("Parse Generalized time, invalid format");
-
-/* Shouldn't this construct a Gregorian calendar directly???
- * We don't really want locale dependant processing here */
- Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
- cal.set(year, month, day, hour, minute, second);
- cal.set(Calendar.MILLISECOND, 0); /* To clear millisecond field */
+
+ /*
+ * Shouldn't this construct a Gregorian calendar directly??? We don't
+ * really want locale dependant processing here
+ */
+ Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
+ cal.set(year, month, day, hour, minute, second);
+ cal.set(Calendar.MILLISECOND, 0); /* To clear millisecond field */
cal.set(Calendar.ERA, GregorianCalendar.AD);
Date readDate = cal.getTime();
long utcTime = readDate.getTime();
@@ -554,43 +542,41 @@ public class DerInputStream {
/*
* Finally, "Z" or "+hhmm" or "-hhmm" ... offsets change hhmm
*/
- if (! (len == 1 || len == 5))
- throw new IOException ("Parse Generalized time, invalid offset");
-
- switch (buffer.read ()) {
- case '+':
- {
- int Htmp = 10 * Character.digit((char)buffer.read(), 10);
- Htmp += Character.digit((char)buffer.read(), 10);
- int Mtmp = 10 * Character.digit((char)buffer.read(), 10);
- Mtmp += Character.digit((char)buffer.read(), 10);
-
- if (Htmp >=24 || Mtmp >= 60)
- throw new IOException("Parse GeneralizedTime, +hhmm");
-
- utcTime += ((Htmp * 60) + Mtmp) * 60 * 1000;
- }
- break;
-
- case '-':
- {
- int Htmp = 10 * Character.digit((char)buffer.read(), 10);
- Htmp += Character.digit((char)buffer.read(), 10);
- int Mtmp = 10 * Character.digit((char)buffer.read(), 10);
- Mtmp += Character.digit((char)buffer.read(), 10);
-
- if (Htmp >=24 || Mtmp >= 60)
- throw new IOException("Parse GeneralizedTime, -hhmm");
-
- utcTime -= ((Htmp * 60) + Mtmp) * 60 * 1000;
- }
- break;
-
- case 'Z':
- break;
-
- default:
- throw new IOException ("Parse GeneralizedTime, garbage offset");
+ if (!(len == 1 || len == 5))
+ throw new IOException("Parse Generalized time, invalid offset");
+
+ switch (buffer.read()) {
+ case '+': {
+ int Htmp = 10 * Character.digit((char) buffer.read(), 10);
+ Htmp += Character.digit((char) buffer.read(), 10);
+ int Mtmp = 10 * Character.digit((char) buffer.read(), 10);
+ Mtmp += Character.digit((char) buffer.read(), 10);
+
+ if (Htmp >= 24 || Mtmp >= 60)
+ throw new IOException("Parse GeneralizedTime, +hhmm");
+
+ utcTime += ((Htmp * 60) + Mtmp) * 60 * 1000;
+ }
+ break;
+
+ case '-': {
+ int Htmp = 10 * Character.digit((char) buffer.read(), 10);
+ Htmp += Character.digit((char) buffer.read(), 10);
+ int Mtmp = 10 * Character.digit((char) buffer.read(), 10);
+ Mtmp += Character.digit((char) buffer.read(), 10);
+
+ if (Htmp >= 24 || Mtmp >= 60)
+ throw new IOException("Parse GeneralizedTime, -hhmm");
+
+ utcTime -= ((Htmp * 60) + Mtmp) * 60 * 1000;
+ }
+ break;
+
+ case 'Z':
+ break;
+
+ default:
+ throw new IOException("Parse GeneralizedTime, garbage offset");
}
readDate.setTime(utcTime);
return readDate;
@@ -601,69 +587,71 @@ public class DerInputStream {
*/
// package private
int getByte() throws IOException {
- return (0x00ff & buffer.read());
+ return (0x00ff & buffer.read());
}
public int peekByte() throws IOException {
- return buffer.peek ();
+ return buffer.peek();
}
// package private
int getLength() throws IOException {
- return getLength (buffer);
+ return getLength(buffer);
}
/*
* Get a length from the input stream, allowing for at most 32 bits of
- * encoding to be used. (Not the same as getting a tagged integer!)
+ * encoding to be used. (Not the same as getting a tagged integer!)
*/
static int getLength(InputStream in) throws IOException {
- int value, tmp;
-
- tmp = in.read ();
- if ((tmp & 0x080) == 0x00) { // 1 byte datum?
- value = tmp;
- } else { // no, more ...
- tmp &= 0x07f;
-
- /*
- * NOTE: tmp == 0 indicates BER encoded data.
- * tmp > 4 indicates more than 4Gb of data.
- */
- if (tmp <= 0 || tmp > 4)
- throw new IOException("DerInput.getLength(): lengthTag="
- + tmp + ", "
- + ((tmp == 0) ? "Indefinite length encoding not supported"
+ int value, tmp;
+
+ tmp = in.read();
+ if ((tmp & 0x080) == 0x00) { // 1 byte datum?
+ value = tmp;
+ } else { // no, more ...
+ tmp &= 0x07f;
+
+ /*
+ * NOTE: tmp == 0 indicates BER encoded data. tmp > 4 indicates more
+ * than 4Gb of data.
+ */
+ if (tmp <= 0 || tmp > 4)
+ throw new IOException("DerInput.getLength(): lengthTag="
+ + tmp + ", "
+ + ((tmp == 0) ? "Indefinite length encoding not supported"
+ " or incorrect DER encoding."
: "too big."));
- for (value = 0; tmp > 0; tmp --) {
- value <<= 8;
- value += 0x0ff & in.read ();
- }
- }
- return value;
+ for (value = 0; tmp > 0; tmp--) {
+ value <<= 8;
+ value += 0x0ff & in.read();
+ }
+ }
+ return value;
}
/**
- * Mark the current position in the buffer, so that
- * a later call to <code>reset</code> will return here.
+ * Mark the current position in the buffer, so that a later call to
+ * <code>reset</code> will return here.
*/
- public void mark (int value) { buffer.mark (value); }
-
+ public void mark(int value) {
+ buffer.mark(value);
+ }
/**
- * Return to the position of the last <code>mark</code>
- * call. A mark is implicitly set at the beginning of
- * the stream when it is created.
+ * Return to the position of the last <code>mark</code> call. A mark is
+ * implicitly set at the beginning of the stream when it is created.
*/
- public void reset () { buffer.reset (); }
-
+ public void reset() {
+ buffer.reset();
+ }
/**
- * Returns the number of bytes available for reading.
- * This is most useful for testing whether the stream is
- * empty.
+ * Returns the number of bytes available for reading. This is most useful
+ * for testing whether the stream is empty.
*/
- public int available () { return buffer.available (); }
+ public int available() {
+ return buffer.available();
+ }
}
diff --git a/pki/base/util/src/netscape/security/util/DerOutputStream.java b/pki/base/util/src/netscape/security/util/DerOutputStream.java
index be42322f..aab57bcb 100644
--- a/pki/base/util/src/netscape/security/util/DerOutputStream.java
+++ b/pki/base/util/src/netscape/security/util/DerOutputStream.java
@@ -31,100 +31,105 @@ import java.util.TimeZone;
import sun.io.CharToByteConverter;
/**
- * Output stream marshaling DER-encoded data. This is eventually provided
- * in the form of a byte array; there is no advance limit on the size of
- * that byte array.
- *
- * <P>At this time, this class supports only a subset of the types of
- * DER data encodings which are defined. That subset is sufficient for
- * generating most X.509 certificates.
- *
+ * Output stream marshaling DER-encoded data. This is eventually provided in the
+ * form of a byte array; there is no advance limit on the size of that byte
+ * array.
+ *
+ * <P>
+ * At this time, this class supports only a subset of the types of DER data
+ * encodings which are defined. That subset is sufficient for generating most
+ * X.509 certificates.
+ *
* @version 1.32
- *
+ *
* @author David Brownell
* @author Amit Kapoor
* @author Hemma Prafullchandra
*/
-public class DerOutputStream
-extends ByteArrayOutputStream implements DerEncoder {
+public class DerOutputStream
+ extends ByteArrayOutputStream implements DerEncoder {
/**
* Construct an DER output stream.
- *
+ *
* @param size how large a buffer to preallocate.
*/
- public DerOutputStream(int size) { super(size); }
+ public DerOutputStream(int size) {
+ super(size);
+ }
/**
* Construct an DER output stream.
*/
- public DerOutputStream() { }
+ public DerOutputStream() {
+ }
/**
- * Writes tagged, pre-marshaled data. This calcuates and encodes
- * the length, so that the output data is the standard triple of
- * { tag, length, data } used by all DER values.
- *
+ * Writes tagged, pre-marshaled data. This calcuates and encodes the length,
+ * so that the output data is the standard triple of { tag, length, data }
+ * used by all DER values.
+ *
* @param tag the DER value tag for the data, such as
- * <em>DerValue.tag_Sequence</em>
+ * <em>DerValue.tag_Sequence</em>
* @param buf buffered data, which must be DER-encoded
*/
public void write(byte tag, byte[] buf) throws IOException {
- write(tag);
- putLength(buf.length);
- write(buf, 0, buf.length);
+ write(tag);
+ putLength(buf.length);
+ write(buf, 0, buf.length);
}
/**
- * Writes tagged data using buffer-to-buffer copy. As above,
- * this writes a standard DER record. This is often used when
- * efficiently encapsulating values in sequences.
- *
+ * Writes tagged data using buffer-to-buffer copy. As above, this writes a
+ * standard DER record. This is often used when efficiently encapsulating
+ * values in sequences.
+ *
* @param tag the DER value tag for the data, such as
- * <em>DerValue.tag_Sequence</em>
+ * <em>DerValue.tag_Sequence</em>
* @param out buffered data
*/
public void write(byte tag, DerOutputStream out) throws IOException {
- write(tag);
- putLength(out.count);
- write(out.buf, 0, out.count);
+ write(tag);
+ putLength(out.count);
+ write(out.buf, 0, out.count);
}
/**
- * Writes implicitly tagged data using buffer-to-buffer copy. As above,
- * this writes a standard DER record. This is often used when
- * efficiently encapsulating implicitly tagged values.
- *
+ * Writes implicitly tagged data using buffer-to-buffer copy. As above, this
+ * writes a standard DER record. This is often used when efficiently
+ * encapsulating implicitly tagged values.
+ *
* @param tag the DER value of the context-specific tag that replaces
- * original tag of the value in the output , such as in
- * <pre>
- * <em> <field> [N] IMPLICIT <type></em>
+ * original tag of the value in the output , such as in
+ *
+ * <pre>
+ * <em> <field> [N] IMPLICIT <type></em>
* </pre>
- * For example, <em>FooLength [1] IMPLICIT INTEGER</em>, with value=4;
- * would be encoded as "81 01 04" whereas in explicit
- * tagging it would be encoded as "A1 03 02 01 04".
- * Notice that the tag is A1 and not 81, this is because with
- * explicit tagging the form is always constructed.
+ *
+ * For example, <em>FooLength [1] IMPLICIT INTEGER</em>, with
+ * value=4; would be encoded as "81 01 04" whereas in explicit
+ * tagging it would be encoded as "A1 03 02 01 04". Notice that
+ * the tag is A1 and not 81, this is because with explicit
+ * tagging the form is always constructed.
* @param value original value being implicitly tagged
*/
public void writeImplicit(byte tag, DerOutputStream value)
- throws IOException {
- write(tag);
- write(value.buf, 1, value.count-1);
+ throws IOException {
+ write(tag);
+ write(value.buf, 1, value.count - 1);
}
/**
* Marshals pre-encoded DER value onto the output stream.
*/
public void putDerValue(DerValue val) throws IOException {
- val.encode(this);
+ val.encode(this);
}
/*
* PRIMITIVES -- these are "universal" ASN.1 simple types.
- *
- * BOOLEAN, INTEGER, BIT STRING, OCTET STRING, NULL
- * OBJECT IDENTIFIER, SEQUENCE(OF), SET(OF)
- * PrintableString, T61String, IA5String, UTCTime
+ *
+ * BOOLEAN, INTEGER, BIT STRING, OCTET STRING, NULL OBJECT IDENTIFIER,
+ * SEQUENCE(OF), SET(OF) PrintableString, T61String, IA5String, UTCTime
*/
/**
@@ -143,34 +148,32 @@ extends ByteArrayOutputStream implements DerEncoder {
/**
* Marshals a DER unsigned integer on the output stream.
*/
- public void putInteger(BigInt i) throws IOException
- {
- putUnsignedInteger(i.toByteArray());
- }
+ public void putInteger(BigInt i) throws IOException {
+ putUnsignedInteger(i.toByteArray());
+ }
/**
* Marshals a DER unsigned integer on the output stream.
*/
- public void putUnsignedInteger(byte [] integerBytes) throws IOException {
+ public void putUnsignedInteger(byte[] integerBytes) throws IOException {
- write(DerValue.tag_Integer);
- if ((integerBytes [0] & 0x080) != 0) {
- /*
- * prepend zero so it's not read as a negative number
- */
- putLength(integerBytes.length + 1);
- write(0);
- } else
- putLength(integerBytes.length);
- write(integerBytes, 0, integerBytes.length);
+ write(DerValue.tag_Integer);
+ if ((integerBytes[0] & 0x080) != 0) {
+ /*
+ * prepend zero so it's not read as a negative number
+ */
+ putLength(integerBytes.length + 1);
+ write(0);
+ } else
+ putLength(integerBytes.length);
+ write(integerBytes, 0, integerBytes.length);
}
/**
* Marshals a DER enumerated value on the output stream.
*/
- public void putEnumerated(int i) throws IOException
- {
- write(DerValue.tag_Enumerated);
+ public void putEnumerated(int i) throws IOException {
+ write(DerValue.tag_Enumerated);
int bytemask = 0xff000000;
int signmask = 0x80000000;
@@ -178,92 +181,91 @@ extends ByteArrayOutputStream implements DerEncoder {
if ((i & 0x80000000) != 0) {
// negative case
for (length = 4; length > 1; --length) {
- if((i & bytemask) != bytemask)
+ if ((i & bytemask) != bytemask)
break;
- bytemask = bytemask >>> 8;
- signmask = signmask >>> 8;
+ bytemask = bytemask >>> 8;
+ signmask = signmask >>> 8;
}
if ((i & signmask) == 0) {
// ensure negative case
- putLength(length+1);
+ putLength(length + 1);
write(0xff);
} else {
- putLength(length);
+ putLength(length);
}
// unrolled loop
switch (length) {
- case 4:
- write((byte)(i >>> 24));
- case 3:
- write((byte)(i >>> 16));
- case 2:
- write((byte)(i >>> 8));
- case 1:
- write((byte)i);
+ case 4:
+ write((byte) (i >>> 24));
+ case 3:
+ write((byte) (i >>> 16));
+ case 2:
+ write((byte) (i >>> 8));
+ case 1:
+ write((byte) i);
}
} else {
// positive case
for (length = 4; length > 0; --length) {
- if((i & bytemask) != 0)
+ if ((i & bytemask) != 0)
break;
- bytemask = bytemask >>> 8;
- signmask = signmask >>> 8;
+ bytemask = bytemask >>> 8;
+ signmask = signmask >>> 8;
}
if ((i & signmask) != 0) {
// ensure posititive case
- putLength(length+1);
+ putLength(length + 1);
write(0x00);
} else {
- putLength(length);
+ putLength(length);
}
// unrolled loop
switch (length) {
- case 4:
- write((byte)(i >>> 24));
- case 3:
- write((byte)(i >>> 16));
- case 2:
- write((byte)(i >>> 8));
- case 1:
- write((byte)i);
+ case 4:
+ write((byte) (i >>> 24));
+ case 3:
+ write((byte) (i >>> 16));
+ case 2:
+ write((byte) (i >>> 8));
+ case 1:
+ write((byte) i);
}
}
}
/**
- * Marshals a DER bit string on the output stream. The bit
- * string must be byte-aligned.
- *
+ * Marshals a DER bit string on the output stream. The bit string must be
+ * byte-aligned.
+ *
* @param bits the bit string, MSB first
*/
public void putBitString(byte[] bits) throws IOException {
- write(DerValue.tag_BitString);
- putLength(bits.length + 1);
- write(0); // all of last octet is used
- write(bits);
+ write(DerValue.tag_BitString);
+ putLength(bits.length + 1);
+ write(0); // all of last octet is used
+ write(bits);
}
/**
- * Converts a boolean array to a BitArray. Trims trailing 0 bits
- * in accordance with DER encoding standard. We assume the input is not
- * null.
+ * Converts a boolean array to a BitArray. Trims trailing 0 bits in
+ * accordance with DER encoding standard. We assume the input is not null.
*/
private static BitArray toBitArray(boolean[] bitString) {
- if( bitString.length == 0 ) {
+ if (bitString.length == 0) {
return new BitArray(bitString);
}
// find index of last 1 bit. -1 if there aren't any
int i;
- for(i=bitString.length-1; i >= 0; i--) {
- if(bitString[i]) {
+ for (i = bitString.length - 1; i >= 0; i--) {
+ if (bitString[i]) {
break;
}
}
- int length = i+1;
+ int length = i + 1;
// if length changed, copy to new appropriately-sized array
- if(length != bitString.length) {
+ if (length != bitString.length) {
boolean[] newBitString = new boolean[length];
System.arraycopy(bitString, 0, newBitString, 0, length);
bitString = newBitString;
@@ -273,30 +275,30 @@ extends ByteArrayOutputStream implements DerEncoder {
}
/**
- * Converts bit string to a BitArray, stripping off trailing 0 bits.
- * We assume that the bit string is not null.
+ * Converts bit string to a BitArray, stripping off trailing 0 bits. We
+ * assume that the bit string is not null.
*/
private static BitArray toBitArray(byte[] bitString) {
// compute length in bits of bit string
int length, i;
int maxIndex = 0;
- if( bitString.length == 0 ) {
+ if (bitString.length == 0) {
return new BitArray(0, bitString);
}
// find the index of the last byte with a 1 bit
- for( i = 0; i < bitString.length; i++) {
- if( bitString[i] != 0 ) {
+ for (i = 0; i < bitString.length; i++) {
+ if (bitString[i] != 0) {
maxIndex = i;
}
}
byte lastByte = bitString[maxIndex];
- length = (maxIndex+1) * 8; // maximum, might reduce in next step
+ length = (maxIndex + 1) * 8; // maximum, might reduce in next step
- // now find the last 1 bit in this last byte
- for(i=1; i <= 0x80; i <<= 1) {
- if( (lastByte & i) == 0 ) {
+ // now find the last 1 bit in this last byte
+ for (i = 1; i <= 0x80; i <<= 1) {
+ if ((lastByte & i) == 0) {
length--;
} else {
break;
@@ -305,345 +307,324 @@ extends ByteArrayOutputStream implements DerEncoder {
return new BitArray(length, bitString);
}
-
/**
- * Marshals a DER bit string on the output stream.
- * The bit strings need not be byte-aligned.
- *
+ * Marshals a DER bit string on the output stream. The bit strings need not
+ * be byte-aligned.
+ *
* @param bits the bit string, MSB first
*/
public void putUnalignedBitString(BitArray ba) throws IOException {
- byte[] bits = ba.toByteArray();
+ byte[] bits = ba.toByteArray();
- write(DerValue.tag_BitString);
- putLength(bits.length + 1);
- write(bits.length*8 - ba.length()); // excess bits in last octet
- write(bits);
+ write(DerValue.tag_BitString);
+ putLength(bits.length + 1);
+ write(bits.length * 8 - ba.length()); // excess bits in last octet
+ write(bits);
}
/**
- * Marshals a DER bit string on the output stream.
- * All trailing 0 bits will be stripped off in accordance with DER
- * encoding.
- *
+ * Marshals a DER bit string on the output stream. All trailing 0 bits will
+ * be stripped off in accordance with DER encoding.
+ *
* @param bits the bit string, MSB first
*/
public void putUnalignedBitString(byte[] bitString) throws IOException {
- putUnalignedBitString( toBitArray(bitString) );
+ putUnalignedBitString(toBitArray(bitString));
}
/**
- * Marshals a DER bit string on the output stream.
- * All trailing 0 bits will be stripped off in accordance with DER
- * encoding.
- *
+ * Marshals a DER bit string on the output stream. All trailing 0 bits will
+ * be stripped off in accordance with DER encoding.
+ *
* @param bits the bit string as an array of booleans.
*/
public void putUnalignedBitString(boolean[] bitString) throws IOException {
- putUnalignedBitString( toBitArray(bitString) );
+ putUnalignedBitString(toBitArray(bitString));
}
/**
* DER-encodes an ASN.1 OCTET STRING value on the output stream.
- *
+ *
* @param octets the octet string
*/
public void putOctetString(byte[] octets) throws IOException {
- write(DerValue.tag_OctetString, octets);
+ write(DerValue.tag_OctetString, octets);
}
/**
- * Marshals a DER "null" value on the output stream. These are
- * often used to indicate optional values which have been omitted.
+ * Marshals a DER "null" value on the output stream. These are often used to
+ * indicate optional values which have been omitted.
*/
public void putNull() throws IOException {
- write(DerValue.tag_Null);
- putLength(0);
+ write(DerValue.tag_Null);
+ putLength(0);
}
/**
- * Marshals an object identifier (OID) on the output stream.
- * Corresponds to the ASN.1 "OBJECT IDENTIFIER" construct.
+ * Marshals an object identifier (OID) on the output stream. Corresponds to
+ * the ASN.1 "OBJECT IDENTIFIER" construct.
*/
public void putOID(ObjectIdentifier oid) throws IOException {
- oid.encode(this);
+ oid.encode(this);
}
/**
- * Marshals a sequence on the output stream. This supports both
- * the ASN.1 "SEQUENCE" (zero to N values) and "SEQUENCE OF"
- * (one to N values) constructs.
+ * Marshals a sequence on the output stream. This supports both the ASN.1
+ * "SEQUENCE" (zero to N values) and "SEQUENCE OF" (one to N values)
+ * constructs.
*/
public void putSequence(DerValue[] seq) throws IOException {
- DerOutputStream bytes = new DerOutputStream();
- int i;
+ DerOutputStream bytes = new DerOutputStream();
+ int i;
- for (i = 0; i < seq.length; i++)
- seq [i].encode(bytes);
+ for (i = 0; i < seq.length; i++)
+ seq[i].encode(bytes);
- write(DerValue.tag_Sequence, bytes);
+ write(DerValue.tag_Sequence, bytes);
}
/**
- * Marshals the contents of a set on the output stream without
- * ordering the elements. Ok for BER encoding, but not for DER
- * encoding.
- *
- * For DER encoding, use orderedPutSet() or orderedPutSetOf().
+ * Marshals the contents of a set on the output stream without ordering the
+ * elements. Ok for BER encoding, but not for DER encoding.
+ *
+ * For DER encoding, use orderedPutSet() or orderedPutSetOf().
*/
public void putSet(DerValue[] set) throws IOException {
- DerOutputStream bytes = new DerOutputStream();
- int i;
+ DerOutputStream bytes = new DerOutputStream();
+ int i;
- for (i = 0; i < set.length; i++)
- set [i].encode(bytes);
+ for (i = 0; i < set.length; i++)
+ set[i].encode(bytes);
- write(DerValue.tag_Set, bytes);
+ write(DerValue.tag_Set, bytes);
}
/**
- * NSCP :
- * Like putOrderSetOf, except not sorted.
- * This may defy DER encoding but is needed for compatibility
- * with communicator.
+ * NSCP : Like putOrderSetOf, except not sorted. This may defy DER encoding
+ * but is needed for compatibility with communicator.
*/
public void putSet(byte tag, DerEncoder[] set) throws IOException {
- putOrderedSet(tag, set, null);
+ putOrderedSet(tag, set, null);
}
- /**
- * Marshals the contents of a set on the output stream. Sets
- * are semantically unordered, but DER requires that encodings of
- * set elements be sorted into ascending lexicographical order
- * before being output. Hence sets with the same tags and
- * elements have the same DER encoding.
- *
- * This method supports the ASN.1 "SET OF" construct, but not
- * "SET", which uses a different order.
+ /**
+ * Marshals the contents of a set on the output stream. Sets are
+ * semantically unordered, but DER requires that encodings of set elements
+ * be sorted into ascending lexicographical order before being output. Hence
+ * sets with the same tags and elements have the same DER encoding.
+ *
+ * This method supports the ASN.1 "SET OF" construct, but not "SET", which
+ * uses a different order.
*/
public void putOrderedSetOf(byte tag, DerEncoder[] set) throws IOException {
- putOrderedSet(tag, set, lexOrder);
+ putOrderedSet(tag, set, lexOrder);
}
- /**
- * Marshals the contents of a set on the output stream. Sets
- * are semantically unordered, but DER requires that encodings of
- * set elements be sorted into ascending tag order
- * before being output. Hence sets with the same tags and
- * elements have the same DER encoding.
- *
- * This method supports the ASN.1 "SET" construct, but not
- * "SET OF", which uses a different order.
+ /**
+ * Marshals the contents of a set on the output stream. Sets are
+ * semantically unordered, but DER requires that encodings of set elements
+ * be sorted into ascending tag order before being output. Hence sets with
+ * the same tags and elements have the same DER encoding.
+ *
+ * This method supports the ASN.1 "SET" construct, but not "SET OF", which
+ * uses a different order.
*/
public void putOrderedSet(byte tag, DerEncoder[] set) throws IOException {
- putOrderedSet(tag, set, tagOrder);
+ putOrderedSet(tag, set, tagOrder);
}
/**
- * Lexicographical order comparison on byte arrays, for ordering
- * elements of a SET OF objects in DER encoding.
+ * Lexicographical order comparison on byte arrays, for ordering elements of
+ * a SET OF objects in DER encoding.
*/
private static ByteArrayLexOrder lexOrder = new ByteArrayLexOrder();
/**
- * Tag order comparison on byte arrays, for ordering elements of
- * SET objects in DER encoding.
+ * Tag order comparison on byte arrays, for ordering elements of SET objects
+ * in DER encoding.
*/
private static ByteArrayTagOrder tagOrder = new ByteArrayTagOrder();
- /**
- * Marshals a the contents of a set on the output stream with the
- * encodings of its sorted in increasing order.
- *
+ /**
+ * Marshals a the contents of a set on the output stream with the encodings
+ * of its sorted in increasing order.
+ *
* @param order the order to use when sorting encodings of components.
*/
- private void putOrderedSet(byte tag, DerEncoder[] set,
- Comparator order) throws IOException {
- DerOutputStream[] streams = new DerOutputStream[set.length];
+ private void putOrderedSet(byte tag, DerEncoder[] set,
+ Comparator order) throws IOException {
+ DerOutputStream[] streams = new DerOutputStream[set.length];
- for (int i = 0; i < set.length; i++) {
- streams[i] = new DerOutputStream();
- set[i].derEncode(streams[i]);
- }
+ for (int i = 0; i < set.length; i++) {
+ streams[i] = new DerOutputStream();
+ set[i].derEncode(streams[i]);
+ }
- // order the element encodings
- byte[][] bufs = new byte[streams.length][];
- for (int i = 0; i < streams.length; i++) {
- bufs[i] = streams[i].toByteArray();
- }
- if (order != null) {
- Arrays.sort(bufs, order);
- }
+ // order the element encodings
+ byte[][] bufs = new byte[streams.length][];
+ for (int i = 0; i < streams.length; i++) {
+ bufs[i] = streams[i].toByteArray();
+ }
+ if (order != null) {
+ Arrays.sort(bufs, order);
+ }
- DerOutputStream bytes = new DerOutputStream();
- for (int i = 0; i < streams.length; i++) {
- bytes.write(bufs[i]);
- }
- write(tag, bytes);
+ DerOutputStream bytes = new DerOutputStream();
+ for (int i = 0; i < streams.length; i++) {
+ bytes.write(bufs[i]);
+ }
+ write(tag, bytes);
}
/**
* Converts string to printable and writes to der output stream.
*/
- public void putPrintableString(String s) throws IOException
- {
- putStringType(DerValue.tag_PrintableString, s);
+ public void putPrintableString(String s) throws IOException {
+ putStringType(DerValue.tag_PrintableString, s);
}
- public void putVisibleString(String s) throws IOException
- {
- putStringType(DerValue.tag_VisibleString, s);
+ public void putVisibleString(String s) throws IOException {
+ putStringType(DerValue.tag_VisibleString, s);
}
+
/**
* Marshals a string which is consists of BMP (unicode) characters
*/
- public void putBMPString(String s) throws IOException
- {
- putStringType(DerValue.tag_BMPString, s);
+ public void putBMPString(String s) throws IOException {
+ putStringType(DerValue.tag_BMPString, s);
}
- public void putGeneralString(String s) throws IOException
- {
- putStringType(DerValue.tag_GeneralString, s);
+ public void putGeneralString(String s) throws IOException {
+ putStringType(DerValue.tag_GeneralString, s);
}
-// /*
-// * T61 is an 8 bit extension to ASCII, escapes e.g. to Japanese
-// */
-// void putT61String(String s) throws IOException
-// {
-// // XXX IMPLEMENT ME
-//
-// throw new IOException("DerOutputStream.putT61String() NYI");
-// }
-
-// /*
-// * Universal String.
-// */
-// void putUniversalString(String s) throws IOException
-// {
-// // XXX IMPLEMENT ME
-//
-// throw new IOException("DerOutputStream.putUniversalString() NYI");
-// }
+ // /*
+ // * T61 is an 8 bit extension to ASCII, escapes e.g. to Japanese
+ // */
+ // void putT61String(String s) throws IOException
+ // {
+ // // XXX IMPLEMENT ME
+ //
+ // throw new IOException("DerOutputStream.putT61String() NYI");
+ // }
+
+ // /*
+ // * Universal String.
+ // */
+ // void putUniversalString(String s) throws IOException
+ // {
+ // // XXX IMPLEMENT ME
+ //
+ // throw new IOException("DerOutputStream.putUniversalString() NYI");
+ // }
/**
* Marshals a string which is consists of IA5(ASCII) characters
*/
- public void putIA5String(String s) throws IOException
- {
- putStringType(DerValue.tag_IA5String, s);
- }
-
- public void putUTF8String(String s) throws IOException
- {
- putStringType(DerValue.tag_UTF8String, s);
- }
-
- public void putStringType(byte tag, String s) throws IOException
- {
- int next_byte_index;
- CharToByteConverter cbc;
- byte buf[];
- try {
- cbc = ASN1CharStrConvMap.getDefault().getCBC(tag);
- if (cbc == null)
- throw new IOException("No character to byte converter for tag");
- buf= new byte[cbc.getMaxBytesPerChar()*s.length()];
- // Don't use convertAll() here b/c it does not throw
- // UnknownCharacterException.
- next_byte_index = cbc.convert(s.toCharArray(), 0, s.length(), buf, 0, buf.length);
- }
- catch (java.io.CharConversionException e) {
- throw new IOException("Not a valid string type "+ tag);
- }
- catch (IllegalAccessException e) {
- throw new IOException("Cannot load CharToByteConverter class "+
- "for DER tag "+tag);
- }
- catch (InstantiationException e) {
- throw new IOException("Cannot instantiate CharToByteConverter "+
- "class for DER tag "+tag);
- }
-
- //next_byte_index = cbc.nextByteIndex();
- write(tag);
- putLength(next_byte_index);
- write(buf, 0, next_byte_index);
- }
-
- private void put2DateBytes(byte[] buffer, int value, int offset)
- {
- int upper= value/10;
- int lower = value%10;
- buffer[offset] = (byte)((byte)upper + (byte)'0');
- buffer[offset+1] = (byte)((byte)lower + (byte)'0');
+ public void putIA5String(String s) throws IOException {
+ putStringType(DerValue.tag_IA5String, s);
+ }
+
+ public void putUTF8String(String s) throws IOException {
+ putStringType(DerValue.tag_UTF8String, s);
+ }
+
+ public void putStringType(byte tag, String s) throws IOException {
+ int next_byte_index;
+ CharToByteConverter cbc;
+ byte buf[];
+ try {
+ cbc = ASN1CharStrConvMap.getDefault().getCBC(tag);
+ if (cbc == null)
+ throw new IOException("No character to byte converter for tag");
+ buf = new byte[cbc.getMaxBytesPerChar() * s.length()];
+ // Don't use convertAll() here b/c it does not throw
+ // UnknownCharacterException.
+ next_byte_index = cbc.convert(s.toCharArray(), 0, s.length(), buf, 0, buf.length);
+ } catch (java.io.CharConversionException e) {
+ throw new IOException("Not a valid string type " + tag);
+ } catch (IllegalAccessException e) {
+ throw new IOException("Cannot load CharToByteConverter class " +
+ "for DER tag " + tag);
+ } catch (InstantiationException e) {
+ throw new IOException("Cannot instantiate CharToByteConverter " +
+ "class for DER tag " + tag);
+ }
+
+ // next_byte_index = cbc.nextByteIndex();
+ write(tag);
+ putLength(next_byte_index);
+ write(buf, 0, next_byte_index);
+ }
+
+ private void put2DateBytes(byte[] buffer, int value, int offset) {
+ int upper = value / 10;
+ int lower = value % 10;
+ buffer[offset] = (byte) ((byte) upper + (byte) '0');
+ buffer[offset + 1] = (byte) ((byte) lower + (byte) '0');
}
private static Calendar GMTGregorianCalendar = null;
- private Calendar getGMTGregorianCalendar()
- {
- if (GMTGregorianCalendar == null) {
- TimeZone tz = TimeZone.getTimeZone("GMT");
- GMTGregorianCalendar = new GregorianCalendar(tz);
- }
- return (Calendar)GMTGregorianCalendar.clone();
- }
-
- public byte[] getDateBytes(Date d, boolean UTC)
- {
-
+ private Calendar getGMTGregorianCalendar() {
+ if (GMTGregorianCalendar == null) {
+ TimeZone tz = TimeZone.getTimeZone("GMT");
+ GMTGregorianCalendar = new GregorianCalendar(tz);
+ }
+ return (Calendar) GMTGregorianCalendar.clone();
+ }
+
+ public byte[] getDateBytes(Date d, boolean UTC) {
+
byte[] datebytes;
if (UTC) {
datebytes = new byte[13];
- }
- else { // generalized time has 4 digits for yr
+ } else { // generalized time has 4 digits for yr
datebytes = new byte[15];
}
Calendar cal = getGMTGregorianCalendar();
cal.setTime(d);
- int i=0;
+ int i = 0;
if (!UTC) {
- put2DateBytes(datebytes,cal.get(Calendar.YEAR)/100,i);
- i+= 2;
+ put2DateBytes(datebytes, cal.get(Calendar.YEAR) / 100, i);
+ i += 2;
}
- put2DateBytes(datebytes,cal.get(Calendar.YEAR)%100 ,i);
+ put2DateBytes(datebytes, cal.get(Calendar.YEAR) % 100, i);
// Calendar's MONTH is zero-based
- i+= 2;
- put2DateBytes(datebytes,cal.get(Calendar.MONTH)+1 ,i);
- i+= 2;
- put2DateBytes(datebytes,cal.get(Calendar.DAY_OF_MONTH),i);
- i+= 2;
- put2DateBytes(datebytes,cal.get(Calendar.HOUR_OF_DAY) ,i);
- i+= 2;
- put2DateBytes(datebytes,cal.get(Calendar.MINUTE) ,i);
- i+= 2;
- put2DateBytes(datebytes,cal.get(Calendar.SECOND) ,i);
- i+= 2;
+ i += 2;
+ put2DateBytes(datebytes, cal.get(Calendar.MONTH) + 1, i);
+ i += 2;
+ put2DateBytes(datebytes, cal.get(Calendar.DAY_OF_MONTH), i);
+ i += 2;
+ put2DateBytes(datebytes, cal.get(Calendar.HOUR_OF_DAY), i);
+ i += 2;
+ put2DateBytes(datebytes, cal.get(Calendar.MINUTE), i);
+ i += 2;
+ put2DateBytes(datebytes, cal.get(Calendar.SECOND), i);
+ i += 2;
// datebytes[i] = 'Z';
- datebytes[i] = (byte)'Z';
-
+ datebytes[i] = (byte) 'Z';
+
return datebytes;
}
/**
* Marshals a DER UTC time/date value.
- *
- * <P>YYMMDDhhmmss{Z|+hhmm|-hhmm} ... emits only using Zulu time
- * and with seconds (even if seconds=0) as per IETF-PKIX partI.
+ *
+ * <P>
+ * YYMMDDhhmmss{Z|+hhmm|-hhmm} ... emits only using Zulu time and with
+ * seconds (even if seconds=0) as per IETF-PKIX partI.
*/
public void putUTCTime(Date d) throws IOException {
- /*
- * Format the date.
- */
-
+ /*
+ * Format the date.
+ */
- // This was the old code. Way too slow to be usable (stevep)
+ // This was the old code. Way too slow to be usable (stevep)
// String pattern = "yyMMddHHmmss'Z'";
// SimpleDateFormat sdf = new SimpleDateFormat(pattern);
@@ -651,37 +632,38 @@ extends ByteArrayOutputStream implements DerEncoder {
// sdf.setTimeZone(tz);
// byte[] utc = (sdf.format(d)).getBytes();
- byte[] datebytes = getDateBytes(d,true); // UTC = true
+ byte[] datebytes = getDateBytes(d, true); // UTC = true
- /*
- * Write the formatted date.
- */
- write (DerValue.tag_UtcTime);
+ /*
+ * Write the formatted date.
+ */
+ write(DerValue.tag_UtcTime);
putLength(datebytes.length);
write(datebytes);
}
/**
* Marshals a DER Generalized Time/date value.
- *
- * <P>YYYYMMDDhhmmss{Z|+hhmm|-hhmm} ... emits only using Zulu time
- * and with seconds (even if seconds=0) as per IETF-PKIX partI.
+ *
+ * <P>
+ * YYYYMMDDhhmmss{Z|+hhmm|-hhmm} ... emits only using Zulu time and with
+ * seconds (even if seconds=0) as per IETF-PKIX partI.
*/
public void putGeneralizedTime(Date d) throws IOException {
/*
* Format the date.
*/
TimeZone tz = TimeZone.getTimeZone("GMT");
-
- // This is way too slow to be usable (stevep)
+
+ // This is way too slow to be usable (stevep)
String pattern = "yyyyMMddHHmmss'Z'";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
sdf.setTimeZone(tz);
byte[] gt = (sdf.format(d)).getBytes();
- /*
- * Write the formatted date.
- */
+ /*
+ * Write the formatted date.
+ */
write(DerValue.tag_GeneralizedTime);
putLength(gt.length);
write(gt);
@@ -689,62 +671,61 @@ extends ByteArrayOutputStream implements DerEncoder {
/**
* Put the encoding of the length in the stream.
- *
+ *
* @param len the length of the attribute.
* @exception IOException on writing errors.
*/
public void putLength(int len) throws IOException {
- if (len < 128) {
- write ((byte)len);
+ if (len < 128) {
+ write((byte) len);
- } else if (len < (1 << 8)) {
- write ((byte)0x081);
- write ((byte)len);
+ } else if (len < (1 << 8)) {
+ write((byte) 0x081);
+ write((byte) len);
- } else if (len < (1 << 16)) {
- write ((byte)0x082);
- write ((byte) (len >> 8));
- write ((byte) len);
+ } else if (len < (1 << 16)) {
+ write((byte) 0x082);
+ write((byte) (len >> 8));
+ write((byte) len);
- } else if (len < (1 << 24)) {
- write ((byte)0x083);
- write ((byte) (len >> 16));
- write ((byte) (len >> 8));
- write ((byte) len);
+ } else if (len < (1 << 24)) {
+ write((byte) 0x083);
+ write((byte) (len >> 16));
+ write((byte) (len >> 8));
+ write((byte) len);
- } else {
- write ((byte)0x084);
- write ((byte) (len >> 24));
- write ((byte) (len >> 16));
- write ((byte) (len >> 8));
- write ((byte) len);
- }
+ } else {
+ write((byte) 0x084);
+ write((byte) (len >> 24));
+ write((byte) (len >> 16));
+ write((byte) (len >> 8));
+ write((byte) len);
+ }
}
/**
* Put the tag of the attribute in the stream.
- *
- * @param class the tag class type, one of UNIVERSAL, CONTEXT,
- * APPLICATION or PRIVATE
- * @param form if true, the value is constructed, otherwise it is
- * primitive.
+ *
+ * @param class the tag class type, one of UNIVERSAL, CONTEXT, APPLICATION
+ * or PRIVATE
+ * @param form if true, the value is constructed, otherwise it is primitive.
* @param val the tag value
*/
public void putTag(byte tagClass, boolean form, byte val) {
byte tag = (byte) (tagClass | val);
if (form) {
- tag |= (byte)0x20;
+ tag |= (byte) 0x20;
}
- write (tag);
+ write(tag);
}
/**
- * Write the current contents of this <code>DerOutputStream</code>
- * to an <code>OutputStream</code>.
- *
- * @exception IOException on output error.
+ * Write the current contents of this <code>DerOutputStream</code> to an
+ * <code>OutputStream</code>.
+ *
+ * @exception IOException on output error.
*/
public void derEncode(OutputStream out) throws IOException {
- out.write(toByteArray());
+ out.write(toByteArray());
}
}
diff --git a/pki/base/util/src/netscape/security/util/DerValue.java b/pki/base/util/src/netscape/security/util/DerValue.java
index 93ca2124..1db406fb 100644
--- a/pki/base/util/src/netscape/security/util/DerValue.java
+++ b/pki/base/util/src/netscape/security/util/DerValue.java
@@ -27,290 +27,306 @@ import netscape.security.x509.GenericValueConverter;
import sun.io.ByteToCharConverter;
/**
- * Represents a single DER-encoded value. DER encoding rules are a subset
- * of the "Basic" Encoding Rules (BER), but they only support a single way
- * ("Definite" encoding) to encode any given value.
- *
- * <P>All DER-encoded data are triples <em>{type, length, data}</em>. This
- * class represents such tagged values as they have been read (or constructed),
- * and provides structured access to the encoded data.
- *
- * <P>At this time, this class supports only a subset of the types of DER
- * data encodings which are defined. That subset is sufficient for parsing
- * most X.509 certificates, and working with selected additional formats
- * (such as PKCS #10 certificate requests, and some kinds of PKCS #7 data).
- *
+ * Represents a single DER-encoded value. DER encoding rules are a subset of the
+ * "Basic" Encoding Rules (BER), but they only support a single way ("Definite"
+ * encoding) to encode any given value.
+ *
+ * <P>
+ * All DER-encoded data are triples <em>{type, length, data}</em>. This class
+ * represents such tagged values as they have been read (or constructed), and
+ * provides structured access to the encoded data.
+ *
+ * <P>
+ * At this time, this class supports only a subset of the types of DER data
+ * encodings which are defined. That subset is sufficient for parsing most X.509
+ * certificates, and working with selected additional formats (such as PKCS #10
+ * certificate requests, and some kinds of PKCS #7 data).
+ *
* @version 1.43
- *
+ *
* @author David Brownell
* @author Amit Kapoor
* @author Hemma Prafullchandra
*/
public class DerValue {
/** The tag class types */
- public static final byte TAG_UNIVERSAL = (byte)0x000;
- public static final byte TAG_APPLICATION = (byte)0x040;
- public static final byte TAG_CONTEXT = (byte)0x080;
- public static final byte TAG_PRIVATE = (byte)0x0c0;
+ public static final byte TAG_UNIVERSAL = (byte) 0x000;
+ public static final byte TAG_APPLICATION = (byte) 0x040;
+ public static final byte TAG_CONTEXT = (byte) 0x080;
+ public static final byte TAG_PRIVATE = (byte) 0x0c0;
/** The DER tag of the value; one of the tag_ constants. */
- public byte tag;
+ public byte tag;
- protected DerInputBuffer buffer;
+ protected DerInputBuffer buffer;
/**
* The DER-encoded data of the value.
*/
- public DerInputStream data;
+ public DerInputStream data;
- private int length;
+ private int length;
/*
- * The type starts at the first byte of the encoding, and
- * is one of these tag_* values. That may be all the type
- * data that is needed.
+ * The type starts at the first byte of the encoding, and is one of these
+ * tag_* values. That may be all the type data that is needed.
*/
/*
- * These tags are the "universal" tags ... they mean the same
- * in all contexts. (Mask with 0x1f -- five bits.)
+ * These tags are the "universal" tags ... they mean the same in all
+ * contexts. (Mask with 0x1f -- five bits.)
*/
/** Tag value indicating an ASN.1 "BOOLEAN" value. */
- public final static byte tag_Boolean = 0x01;
+ public final static byte tag_Boolean = 0x01;
/** Tag value indicating an ASN.1 "INTEGER" value. */
- public final static byte tag_Integer = 0x02;
+ public final static byte tag_Integer = 0x02;
/** Tag value indicating an ASN.1 "BIT STRING" value. */
- public final static byte tag_BitString = 0x03;
+ public final static byte tag_BitString = 0x03;
/** Tag value indicating an ASN.1 "OCTET STRING" value. */
- public final static byte tag_OctetString = 0x04;
+ public final static byte tag_OctetString = 0x04;
/** Tag value indicating an ASN.1 "NULL" value. */
- public final static byte tag_Null = 0x05;
+ public final static byte tag_Null = 0x05;
/** Tag value indicating an ASN.1 "OBJECT IDENTIFIER" value. */
- public final static byte tag_ObjectId = 0x06;
+ public final static byte tag_ObjectId = 0x06;
/** Tag value including an ASN.1 "ENUMERATED" value */
- public final static byte tag_Enumerated = 0x0A;
+ public final static byte tag_Enumerated = 0x0A;
/** Tag value including a "printable" string */
- public final static byte tag_PrintableString = 0x13;
+ public final static byte tag_PrintableString = 0x13;
- public final static byte tag_VisibleString = 0x1A;
+ public final static byte tag_VisibleString = 0x1A;
/** Tag value including a "teletype" string */
- public final static byte tag_T61String = 0x14;
+ public final static byte tag_T61String = 0x14;
/** Tag value including an ASCII string */
- public final static byte tag_IA5String = 0x16;
+ public final static byte tag_IA5String = 0x16;
/** Tag value indicating an ASN.1 "UTCTime" value. */
- public final static byte tag_UtcTime = 0x17;
+ public final static byte tag_UtcTime = 0x17;
/** Tag value indicating an ASN.1 "GeneralizedTime" value. */
- public final static byte tag_GeneralizedTime = 0x18;
+ public final static byte tag_GeneralizedTime = 0x18;
/** Tag value indicating an ASN.1 "GeneralString" value. */
- public final static byte tag_GeneralString = 0x1B;
+ public final static byte tag_GeneralString = 0x1B;
/** Tag value indicating an ASN.1 "BMPString" value. */
- public final static byte tag_BMPString = 0x1E;
+ public final static byte tag_BMPString = 0x1E;
/** Tag value indicating an ASN.1 "UniversalString" value. */
- public final static byte tag_UniversalString = 0x1C;
+ public final static byte tag_UniversalString = 0x1C;
/** Tag value indicating an ASN.1 "UTF8String" value. (since 1998) */
- public final static byte tag_UTF8String = 0x0C;
+ public final static byte tag_UTF8String = 0x0C;
// CONSTRUCTED seq/set
- /** Tag value indicating an ASN.1
- * "SEQUENCE" (zero to N elements, order is significant). */
- public final static byte tag_Sequence = 0x30;
+ /**
+ * Tag value indicating an ASN.1 "SEQUENCE" (zero to N elements, order is
+ * significant).
+ */
+ public final static byte tag_Sequence = 0x30;
- /** Tag value indicating an ASN.1
- * "SEQUENCE OF" (one to N elements, order is significant). */
- public final static byte tag_SequenceOf = 0x30;
+ /**
+ * Tag value indicating an ASN.1 "SEQUENCE OF" (one to N elements, order is
+ * significant).
+ */
+ public final static byte tag_SequenceOf = 0x30;
- /** Tag value indicating an ASN.1
- * "SET" (zero to N members, order does not matter). */
- public final static byte tag_Set = 0x31;
+ /**
+ * Tag value indicating an ASN.1 "SET" (zero to N members, order does not
+ * matter).
+ */
+ public final static byte tag_Set = 0x31;
- /** Tag value indicating an ASN.1
- * "SET OF" (one to N members, order does not matter). */
- public final static byte tag_SetOf = 0x31;
+ /**
+ * Tag value indicating an ASN.1 "SET OF" (one to N members, order does not
+ * matter).
+ */
+ public final static byte tag_SetOf = 0x31;
/*
* These values are the high order bits for the other kinds of tags.
*/
- boolean isUniversal() { return ((tag & 0x0c0) == 0x000); }
- boolean isApplication() { return ((tag & 0x0c0) == 0x040); }
+ boolean isUniversal() {
+ return ((tag & 0x0c0) == 0x000);
+ }
+
+ boolean isApplication() {
+ return ((tag & 0x0c0) == 0x040);
+ }
/**
- * Returns true iff the CONTEXT SPECIFIC bit is set in the type tag.
- * This is associated with the ASN.1 "DEFINED BY" syntax.
+ * Returns true iff the CONTEXT SPECIFIC bit is set in the type tag. This is
+ * associated with the ASN.1 "DEFINED BY" syntax.
*/
- public boolean isContextSpecific() { return ((tag & 0x0c0) == 0x080); }
+ public boolean isContextSpecific() {
+ return ((tag & 0x0c0) == 0x080);
+ }
/**
* Returns true iff the CONTEXT SPECIFIC TAG matches the passed tag.
*/
public boolean isContextSpecific(byte cntxtTag) {
- if (!isContextSpecific ()) {
+ if (!isContextSpecific()) {
return false;
}
return ((tag & 0x01f) == cntxtTag);
}
- boolean isPrivate() { return ((tag & 0x0c0) == 0x0c0); }
+ boolean isPrivate() {
+ return ((tag & 0x0c0) == 0x0c0);
+ }
/** Returns true iff the CONSTRUCTED bit is set in the type tag. */
- public boolean isConstructed() { return ((tag & 0x020) == 0x020); }
+ public boolean isConstructed() {
+ return ((tag & 0x020) == 0x020);
+ }
/**
- * Creates a DER value from a string
- * using a generic way of determining the proper tag for the string.
- * Assumes the string is a Generic attribute value and uses
- * the converter for generic string values to convert to the Der Value.
+ * Creates a DER value from a string using a generic way of determining the
+ * proper tag for the string. Assumes the string is a Generic attribute
+ * value and uses the converter for generic string values to convert to the
+ * Der Value.
*/
- public DerValue (String value)
- throws IOException
- {
- AVAValueConverter genericValue = new GenericValueConverter();
- DerValue val;
+ public DerValue(String value)
+ throws IOException {
+ AVAValueConverter genericValue = new GenericValueConverter();
+ DerValue val;
- val = genericValue.getValue(value);
- tag = val.tag;
- buffer = val.buffer;
- length = val.length;
- data = val.data;
- data.mark (Integer.MAX_VALUE);
+ val = genericValue.getValue(value);
+ tag = val.tag;
+ buffer = val.buffer;
+ length = val.length;
+ data = val.data;
+ data.mark(Integer.MAX_VALUE);
}
/**
* Creates a DerValue from a tag and some DER-encoded data.
- *
+ *
* @param tag the DER type tag
* @param data the DER-encoded data
*/
public DerValue(byte tag, byte[] data) {
- this.tag = tag;
- buffer = new DerInputBuffer((byte[])data.clone());
- length = data.length;
- this.data = new DerInputStream (buffer);
- this.data.mark (Integer.MAX_VALUE);
+ this.tag = tag;
+ buffer = new DerInputBuffer((byte[]) data.clone());
+ length = data.length;
+ this.data = new DerInputStream(buffer);
+ this.data.mark(Integer.MAX_VALUE);
}
/*
* package private
*/
DerValue(DerInputBuffer in) throws IOException {
- // NOTE: This must handle the special value used
- // to terminate BER indefinite encodings (tag and
- // length are both zero)
+ // NOTE: This must handle the special value used
+ // to terminate BER indefinite encodings (tag and
+ // length are both zero)
- // XXX must also parse BER-encoded constructed
- // values such as sequences, sets...
+ // XXX must also parse BER-encoded constructed
+ // values such as sequences, sets...
- tag = (byte) in.read ();
- length = DerInputStream.getLength (in);
+ tag = (byte) in.read();
+ length = DerInputStream.getLength(in);
- buffer = in.dup ();
- buffer.truncate (length);
- data = new DerInputStream (buffer);
+ buffer = in.dup();
+ buffer.truncate(length);
+ data = new DerInputStream(buffer);
- in.skip (length);
+ in.skip(length);
}
/**
- * Get an ASN.1/DER encoded datum from a buffer. The
- * entire buffer must hold exactly one datum, including
- * its tag and length.
- *
+ * Get an ASN.1/DER encoded datum from a buffer. The entire buffer must hold
+ * exactly one datum, including its tag and length.
+ *
* @param buf buffer holding a single DER-encoded datum.
*/
public DerValue(byte[] buf) throws IOException {
- init (true, new ByteArrayInputStream (buf));
+ init(true, new ByteArrayInputStream(buf));
}
/**
- * Get an ASN.1/DER encoded datum from part of a buffer.
- * That part of the buffer must hold exactly one datum, including
- * its tag and length.
- *
+ * Get an ASN.1/DER encoded datum from part of a buffer. That part of the
+ * buffer must hold exactly one datum, including its tag and length.
+ *
* @param buf the buffer
* @param offset start point of the single DER-encoded dataum
* @param length how many bytes are in the encoded datum
*/
public DerValue(byte[] buf, int offset, int len) throws IOException {
- init (true, new ByteArrayInputStream (buf, offset, len));
+ init(true, new ByteArrayInputStream(buf, offset, len));
}
/**
- * Get an ASN1/DER encoded datum from an input stream. The
- * stream may have additional data following the encoded datum.
- *
- * @param in the input stream holding a single DER datum,
- * which may be followed by additional data
+ * Get an ASN1/DER encoded datum from an input stream. The stream may have
+ * additional data following the encoded datum.
+ *
+ * @param in the input stream holding a single DER datum, which may be
+ * followed by additional data
*/
public DerValue(InputStream in) throws IOException {
- init (false, in);
+ init(false, in);
}
/*
* helper routine
*/
- private void init (boolean fullyBuffered, InputStream in)
- throws IOException {
- byte[] bytes;
+ private void init(boolean fullyBuffered, InputStream in)
+ throws IOException {
+ byte[] bytes;
- tag = (byte) in.read ();
- length = DerInputStream.getLength (in);
+ tag = (byte) in.read();
+ length = DerInputStream.getLength(in);
/*
- if (length == 0)
- return;
- */
+ * if (length == 0) return;
+ */
- if (fullyBuffered && in.available () != length)
- throw new IOException ("extra DER value data (constructor)");
+ if (fullyBuffered && in.available() != length)
+ throw new IOException("extra DER value data (constructor)");
- bytes = new byte [length];
+ bytes = new byte[length];
- // n.b. readFully not needed in normal fullyBuffered case
- DataInputStream dis = new DataInputStream (in);
+ // n.b. readFully not needed in normal fullyBuffered case
+ DataInputStream dis = new DataInputStream(in);
- dis.readFully (bytes);
- buffer = new DerInputBuffer (bytes);
- data = new DerInputStream (buffer);
+ dis.readFully(bytes);
+ buffer = new DerInputBuffer(bytes);
+ data = new DerInputStream(buffer);
}
/**
* Encode an ASN1/DER encoded datum onto a DER output stream.
*/
public void encode(DerOutputStream out)
- throws IOException {
- out.write (tag);
- out.putLength (length);
- buffer.dump(out,length);
+ throws IOException {
+ out.write(tag);
+ out.putLength(length);
+ buffer.dump(out, length);
}
/**
* Returns an ASN.1 BOOLEAN
- *
+ *
* @return the boolean held in this DER value
*/
public boolean getBoolean() throws IOException {
if (tag != tag_Boolean) {
- throw new IOException ("DerValue.getBoolean, not a BOOLEAN " + tag);
+ throw new IOException("DerValue.getBoolean, not a BOOLEAN " + tag);
}
if (length != 1) {
- throw new IOException ("DerValue.getBoolean, invalid length " + length);
+ throw new IOException("DerValue.getBoolean, invalid length " + length);
}
if (buffer.read() != 0) {
return true;
@@ -320,376 +336,365 @@ public class DerValue {
/**
* Returns an ASN.1 OBJECT IDENTIFIER.
- *
+ *
* @return the OID held in this DER value
*/
public ObjectIdentifier getOID() throws IOException {
- if (tag != tag_ObjectId)
- throw new IOException ("DerValue.getOID, not an OID " + tag);
- return new ObjectIdentifier (buffer);
+ if (tag != tag_ObjectId)
+ throw new IOException("DerValue.getOID, not an OID " + tag);
+ return new ObjectIdentifier(buffer);
}
/**
* Returns an ASN.1 OCTET STRING
- *
+ *
* @return the octet string held in this DER value
*/
public byte[] getOctetString() throws IOException {
- if (tag != tag_OctetString)
- throw new IOException (
- "DerValue.getOctetString, not an Octet String: " + tag);
+ if (tag != tag_OctetString)
+ throw new IOException(
+ "DerValue.getOctetString, not an Octet String: " + tag);
- byte [] bytes = new byte [length];
+ byte[] bytes = new byte[length];
- if (buffer.read(bytes) != length)
- throw new IOException("short read on DerValue buffer");
- return bytes;
+ if (buffer.read(bytes) != length)
+ throw new IOException("short read on DerValue buffer");
+ return bytes;
}
/**
* Returns an ASN.1 unsigned integer value of enumerated value.
- *
+ *
* @return the (unsigned) integer held in this DER value
*/
- public int getEnumerated ()
- throws IOException
- {
+ public int getEnumerated()
+ throws IOException {
if (tag != tag_Enumerated)
- throw new IOException ("DerValue.getEnumerated, not an ENUMERATED " + tag);
+ throw new IOException("DerValue.getEnumerated, not an ENUMERATED " + tag);
if (length == 0)
return 0;
- if (length > 4 || length < 1)
- throw new IOException("DerValue.getEnumerated, invalid length " + length + "(must be between 1 and 4)");
-
- int value = 0;
- int nextbyte = buffer.read();
- if (nextbyte == -1)
- throw new IOException("short read on DerValue buffer");
- // perform sign extension
- value = (byte) nextbyte;
-
- for (int i = length - 1; i > 0; --i) {
- nextbyte = buffer.read();
- if (nextbyte == -1)
- throw new IOException("short read on DerValue buffer");
- value = 256 * value + nextbyte;
- }
- return value;
+ if (length > 4 || length < 1)
+ throw new IOException("DerValue.getEnumerated, invalid length " + length + "(must be between 1 and 4)");
+
+ int value = 0;
+ int nextbyte = buffer.read();
+ if (nextbyte == -1)
+ throw new IOException("short read on DerValue buffer");
+ // perform sign extension
+ value = (byte) nextbyte;
+
+ for (int i = length - 1; i > 0; --i) {
+ nextbyte = buffer.read();
+ if (nextbyte == -1)
+ throw new IOException("short read on DerValue buffer");
+ value = 256 * value + nextbyte;
+ }
+ return value;
}
/**
* Returns an ASN.1 unsigned INTEGER value.
- *
+ *
* @return the (unsigned) integer held in this DER value
*/
public BigInt getInteger() throws IOException {
if (tag != tag_Integer)
- throw new IOException ("DerValue.getInteger, not an int " + tag);
- return buffer.getUnsigned (data.available ());
+ throw new IOException("DerValue.getInteger, not an int " + tag);
+ return buffer.getUnsigned(data.available());
}
/**
- * Returns an ASN.1 unsigned INTEGER value, the parameter determining
- * if the tag is implicit.
- *
- * @param tagImplicit if true, ignores the tag value as it is
- * assumed implicit.
+ * Returns an ASN.1 unsigned INTEGER value, the parameter determining if the
+ * tag is implicit.
+ *
+ * @param tagImplicit if true, ignores the tag value as it is assumed
+ * implicit.
* @return the (unsigned) integer held in this DER value
*/
- public BigInt getInteger(boolean tagImplicit) throws IOException {
- if (!tagImplicit) {
- if (tag != tag_Integer) {
- throw new IOException("DerValue.getInteger, not an int "
+ public BigInt getInteger(boolean tagImplicit) throws IOException {
+ if (!tagImplicit) {
+ if (tag != tag_Integer) {
+ throw new IOException("DerValue.getInteger, not an int "
+ tag);
- }
- }
- return buffer.getUnsigned (data.available ());
- }
+ }
+ }
+ return buffer.getUnsigned(data.available());
+ }
/**
- * Returns an ASN.1 BIT STRING value. The bit string must be byte-aligned.
- *
+ * Returns an ASN.1 BIT STRING value. The bit string must be byte-aligned.
+ *
* @return the bit string held in this value
*/
public byte[] getBitString() throws IOException {
- if (tag != tag_BitString)
- throw new IOException (
- "DerValue.getBitString, not a bit string " + tag);
+ if (tag != tag_BitString)
+ throw new IOException(
+ "DerValue.getBitString, not a bit string " + tag);
- return buffer.getBitString ();
+ return buffer.getBitString();
}
/**
* Returns an ASN.1 BIT STRING value that need not be byte-aligned.
- *
+ *
* @return a BitArray representing the bit string held in this value
*/
public BitArray getUnalignedBitString() throws IOException {
- if (tag != tag_BitString)
+ if (tag != tag_BitString)
throw new IOException(
- "DerValue.getBitString, not a bit string " + tag);
-
- return buffer.getUnalignedBitString();
+ "DerValue.getBitString, not a bit string " + tag);
+
+ return buffer.getUnalignedBitString();
}
/**
- * Returns the name component as a Java string, regardless of its
- * encoding restrictions (ASCII, T61, Printable, etc).
+ * Returns the name component as a Java string, regardless of its encoding
+ * restrictions (ASCII, T61, Printable, etc).
*/
- public String getAsString () throws IOException
- {
- AVAValueConverter genericValue = new GenericValueConverter();
- return genericValue.getAsString(this);
+ public String getAsString() throws IOException {
+ AVAValueConverter genericValue = new GenericValueConverter();
+ return genericValue.getAsString(this);
}
/**
- * Returns an ASN.1 BIT STRING value, with the tag assumed implicit
- * based on the parameter. The bit string must be byte-aligned.
- *
+ * Returns an ASN.1 BIT STRING value, with the tag assumed implicit based on
+ * the parameter. The bit string must be byte-aligned.
+ *
* @param tagImplicit if true, the tag is assumed implicit.
* @return the bit string held in this value
*/
public byte[] getBitString(boolean tagImplicit) throws IOException {
if (!tagImplicit) {
if (tag != tag_BitString)
- throw new IOException ("DerValue.getBitString, not a bit string "
+ throw new IOException("DerValue.getBitString, not a bit string "
+ tag);
- }
- return buffer.getBitString ();
+ }
+ return buffer.getBitString();
}
/**
- * Returns an ASN.1 BIT STRING value, with the tag assumed implicit
- * based on the parameter. The bit string need not be byte-aligned.
- *
+ * Returns an ASN.1 BIT STRING value, with the tag assumed implicit based on
+ * the parameter. The bit string need not be byte-aligned.
+ *
* @param tagImplicit if true, the tag is assumed implicit.
* @return the bit string held in this value
*/
public BitArray getUnalignedBitString(boolean tagImplicit)
- throws IOException {
+ throws IOException {
if (!tagImplicit) {
if (tag != tag_BitString)
throw new IOException("DerValue.getBitString, not a bit string "
+ tag);
- }
+ }
return buffer.getUnalignedBitString();
}
/**
* Returns an ASN.1 STRING value
- *
+ *
* @return the printable string held in this value
*/
- public String getPrintableString ()
- throws IOException {
- if (tag != tag_PrintableString)
- throw new IOException (
- "DerValue.getPrintableString, not a string " + tag);
+ public String getPrintableString()
+ throws IOException {
+ if (tag != tag_PrintableString)
+ throw new IOException(
+ "DerValue.getPrintableString, not a string " + tag);
- return getASN1CharString();
+ return getASN1CharString();
}
/*
- * @eturns a string if the DerValue is a ASN.1 character string type and
- * if there is a ByteToChar converter for the type. Returns null otherwise.
+ * @eturns a string if the DerValue is a ASN.1 character string type and if
+ * there is a ByteToChar converter for the type. Returns null otherwise.
*/
public String getASN1CharString()
- throws IOException
- {
- ByteToCharConverter bcc;
- int ret;
- byte buf[];
- char cbuf[];
-
- try {
- bcc = ASN1CharStrConvMap.getDefault().getBCC(tag);
- if (bcc == null)
- return null;
-
- buf = new byte[length];
- cbuf = new char[bcc.getMaxCharsPerByte()*length];
- data.reset();
- data.getBytes(buf);
- ret = bcc.convert(buf, 0, buf.length, cbuf, 0, cbuf.length);
- }
- catch (java.io.CharConversionException e) {
- throw new IOException("Misformed DER value");
- }
- catch (IllegalAccessException e) {
- throw new IOException("Illegal Access loading ByteToCharConverter");
- }
- catch (InstantiationException e) {
- throw new IOException("Cannot instantiate ByteToCharConverter");
- }
- return new String(cbuf, 0, ret);
+ throws IOException {
+ ByteToCharConverter bcc;
+ int ret;
+ byte buf[];
+ char cbuf[];
+
+ try {
+ bcc = ASN1CharStrConvMap.getDefault().getBCC(tag);
+ if (bcc == null)
+ return null;
+
+ buf = new byte[length];
+ cbuf = new char[bcc.getMaxCharsPerByte() * length];
+ data.reset();
+ data.getBytes(buf);
+ ret = bcc.convert(buf, 0, buf.length, cbuf, 0, cbuf.length);
+ } catch (java.io.CharConversionException e) {
+ throw new IOException("Misformed DER value");
+ } catch (IllegalAccessException e) {
+ throw new IOException("Illegal Access loading ByteToCharConverter");
+ } catch (InstantiationException e) {
+ throw new IOException("Cannot instantiate ByteToCharConverter");
+ }
+ return new String(cbuf, 0, ret);
}
/**
* Returns an ASN.1 T61 (Teletype) STRING value
- *
+ *
* @return the teletype string held in this value
*/
public String getT61String() throws IOException {
- if (tag != tag_T61String)
- throw new IOException (
- "DerValue.getT61String, not T61 " + tag);
+ if (tag != tag_T61String)
+ throw new IOException(
+ "DerValue.getT61String, not T61 " + tag);
- return getASN1CharString ();
+ return getASN1CharString();
}
/**
* Returns an ASN.1 IA5 (ASCII) STRING value
- *
+ *
* @return the ASCII string held in this value
*/
public String getIA5String() throws IOException {
- if (tag != tag_IA5String)
- throw new IOException (
- "DerValue.getIA5String, not IA5 " + tag);
+ if (tag != tag_IA5String)
+ throw new IOException(
+ "DerValue.getIA5String, not IA5 " + tag);
- return getASN1CharString ();
+ return getASN1CharString();
}
- public String getBMPString ()
- throws IOException
- {
- if (tag != tag_BMPString)
- throw new IOException (
- "DerValue.getBMPString, not BMP " + tag);
+ public String getBMPString()
+ throws IOException {
+ if (tag != tag_BMPString)
+ throw new IOException(
+ "DerValue.getBMPString, not BMP " + tag);
- return getASN1CharString ();
+ return getASN1CharString();
}
- public String getUniversalString ()
- throws IOException
- {
- if (tag != tag_UniversalString)
- throw new IOException (
- "DerValue.getUniversalString, not UniversalString " + tag);
+ public String getUniversalString()
+ throws IOException {
+ if (tag != tag_UniversalString)
+ throw new IOException(
+ "DerValue.getUniversalString, not UniversalString " + tag);
- return getASN1CharString ();
+ return getASN1CharString();
}
- public String getUTF8String ()
- throws IOException
- {
- if (tag != tag_UTF8String)
- throw new IOException (
- "DerValue.getUTF8String, not UTF8String " + tag);
+ public String getUTF8String()
+ throws IOException {
+ if (tag != tag_UTF8String)
+ throw new IOException(
+ "DerValue.getUTF8String, not UTF8String " + tag);
- return getASN1CharString ();
+ return getASN1CharString();
}
/**
- * Returns true iff the other object is a DER value which
- * is bitwise equal to this one.
- *
+ * Returns true iff the other object is a DER value which is bitwise equal
+ * to this one.
+ *
* @param other the object being compared with this one
*/
public boolean equals(Object other) {
- if (other instanceof DerValue)
- return equals ((DerValue)other);
- else
- return false;
+ if (other instanceof DerValue)
+ return equals((DerValue) other);
+ else
+ return false;
}
/**
- * Bitwise equality comparison. DER encoded values have a single
- * encoding, so that bitwise equality of the encoded values is an
- * efficient way to establish equivalence of the unencoded values.
- *
+ * Bitwise equality comparison. DER encoded values have a single encoding,
+ * so that bitwise equality of the encoded values is an efficient way to
+ * establish equivalence of the unencoded values.
+ *
* @param other the object being compared with this one
*/
public boolean equals(DerValue other) {
- data.reset ();
- other.data.reset();
- if (this == other)
- return true;
- else if (tag != other.tag) {
- return false;
- } else {
- return buffer.equals (other.buffer);
- }
+ data.reset();
+ other.data.reset();
+ if (this == other)
+ return true;
+ else if (tag != other.tag) {
+ return false;
+ } else {
+ return buffer.equals(other.buffer);
+ }
}
/**
* Returns a printable representation of the value.
- *
+ *
* @return printable representation of the value
*/
public String toString() {
- try {
- String s = getAsString();
- if (s != null)
- return s;
- if (tag == tag_Null)
- return "[DerValue, null]";
- if (tag == tag_ObjectId)
- return "OID." + getOID ();
-
- // integers
- else
- return "[DerValue, tag = " + tag
- + ", length = " + length + "]";
- } catch (IOException e) {
- throw new IllegalArgumentException ("misformatted DER value");
- }
- }
-
- /**
- * Returns a DER-encoded value, such that if it's passed to the
- * DerValue constructor, a value equivalent to "this" is returned.
- *
+ try {
+ String s = getAsString();
+ if (s != null)
+ return s;
+ if (tag == tag_Null)
+ return "[DerValue, null]";
+ if (tag == tag_ObjectId)
+ return "OID." + getOID();
+
+ // integers
+ else
+ return "[DerValue, tag = " + tag
+ + ", length = " + length + "]";
+ } catch (IOException e) {
+ throw new IllegalArgumentException("misformatted DER value");
+ }
+ }
+
+ /**
+ * Returns a DER-encoded value, such that if it's passed to the DerValue
+ * constructor, a value equivalent to "this" is returned.
+ *
* @return DER-encoded value, including tag and length.
*/
public byte[] toByteArray() throws IOException {
- DerOutputStream out = new DerOutputStream ();
+ DerOutputStream out = new DerOutputStream();
- encode (out);
- data.reset ();
- return out.toByteArray ();
+ encode(out);
+ data.reset();
+ return out.toByteArray();
}
/**
- * For "set" and "sequence" types, this function may be used
- * to return a DER stream of the members of the set or sequence.
- * This operation is not supported for primitive types such as
- * integers or bit strings.
+ * For "set" and "sequence" types, this function may be used to return a DER
+ * stream of the members of the set or sequence. This operation is not
+ * supported for primitive types such as integers or bit strings.
*/
public DerInputStream toDerInputStream() throws IOException {
- if (tag == tag_Sequence || tag == tag_Set)
- return new DerInputStream (buffer);
- throw new IOException ("toDerInputStream rejects tag type " + tag);
+ if (tag == tag_Sequence || tag == tag_Set)
+ return new DerInputStream(buffer);
+ throw new IOException("toDerInputStream rejects tag type " + tag);
}
/**
* Get the length of the encoded value.
*/
public int length() {
- return length;
+ return length;
}
/**
* Create the tag of the attribute.
- *
- * @param class the tag class type, one of UNIVERSAL, CONTEXT,
- * APPLICATION or PRIVATE
- * @param form if true, the value is constructed, otherwise it
- * is primitive.
+ *
+ * @param class the tag class type, one of UNIVERSAL, CONTEXT, APPLICATION
+ * or PRIVATE
+ * @param form if true, the value is constructed, otherwise it is primitive.
* @param val the tag value
*/
public static byte createTag(byte tagClass, boolean form, byte val) {
byte tag = (byte) (tagClass | val);
if (form) {
- tag |= (byte)0x20;
+ tag |= (byte) 0x20;
}
return (tag);
}
/**
- * Set the tag of the attribute. Commonly used to reset the
- * tag value used for IMPLICIT encodings.
- *
+ * Set the tag of the attribute. Commonly used to reset the tag value used
+ * for IMPLICIT encodings.
+ *
* @param tag the tag value
*/
public void resetTag(byte tag) {
diff --git a/pki/base/util/src/netscape/security/util/ExtPrettyPrint.java b/pki/base/util/src/netscape/security/util/ExtPrettyPrint.java
index 0c62012d..d06675b3 100644
--- a/pki/base/util/src/netscape/security/util/ExtPrettyPrint.java
+++ b/pki/base/util/src/netscape/security/util/ExtPrettyPrint.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package netscape.security.util;
-
import java.math.BigInteger;
import java.text.DateFormat;
import java.util.Enumeration;
@@ -78,19 +77,18 @@ import netscape.security.x509.SubjectDirAttributesExtension;
import netscape.security.x509.SubjectKeyIdentifierExtension;
import netscape.security.x509.UserNotice;
-
/**
- * This class will display the certificate content in predefined
- * format.
- *
+ * This class will display the certificate content in predefined format.
+ *
* @author Andrew Wnuk
* @version $Revision$, $Date$
*/
public class ExtPrettyPrint {
- /*==========================================================
- * variables
- *==========================================================*/
+ /*
+ * ========================================================== variables
+ * ==========================================================
+ */
private Extension mExt = null;
private ResourceBundle mResource = null;
private ResourceBundle resource = null;
@@ -99,9 +97,10 @@ public class ExtPrettyPrint {
DateFormat dateFormater = null;
- /*==========================================================
- * constructors
- *==========================================================*/
+ /*
+ * ========================================================== constructors
+ * ==========================================================
+ */
public ExtPrettyPrint(Extension ext, int indentSize) {
mExt = ext;
@@ -110,23 +109,24 @@ public class ExtPrettyPrint {
pp = new PrettyPrintFormat(":");
}
- /*==========================================================
- * public methods
- *==========================================================*/
+ /*
+ * ========================================================== public methods
+ * ==========================================================
+ */
/**
- * This method return string representation of the certificate
- * in predefined format using specified client local. I18N Support.
- *
+ * This method return string representation of the certificate in predefined
+ * format using specified client local. I18N Support.
+ *
* @param clientLocale Locale to be used for localization
* @return string representation of the certificate
*/
- // public String toString(int indentSize) {
+ // public String toString(int indentSize) {
public String toString() {
StringBuffer sb = new StringBuffer();
- //check if the extension is known
+ // check if the extension is known
if (mExt instanceof KeyUsageExtension) {
return getKeyUsage();
}
@@ -220,19 +220,19 @@ public class ExtPrettyPrint {
return getCertificatePoliciesExtension();
}
- //unknown cert extension
+ // unknown cert extension
try {
String extName = OIDMap.getName(mExt.getExtensionId());
if (extName == null)
sb.append(pp.indent(mIndentSize) + mResource.getString(
PrettyPrintResources.TOKEN_IDENTIFIER) +
- mExt.getExtensionId().toString() + "\n");
+ mExt.getExtensionId().toString() + "\n");
else
sb.append(pp.indent(mIndentSize) + mResource.getString(
PrettyPrintResources.TOKEN_IDENTIFIER) + " " + extName + " - " +
- mExt.getExtensionId().toString() + "\n");
-
+ mExt.getExtensionId().toString() + "\n");
+
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(
PrettyPrintResources.TOKEN_CRITICAL));
if (mExt.isCritical()) {
@@ -252,9 +252,10 @@ public class ExtPrettyPrint {
}
- /*==========================================================
- * Private methods
- *==========================================================*/
+ /*
+ * ========================================================== Private
+ * methods==========================================================
+ */
private String getNSCCommentExtension() {
StringBuffer sb = new StringBuffer();
@@ -263,7 +264,7 @@ public class ExtPrettyPrint {
sb.append(pp.indent(mIndentSize) + mResource.getString(
PrettyPrintResources.TOKEN_IDENTIFIER));
sb.append(mResource.getString(PrettyPrintResources.TOKEN_NSC_COMMENT) +
- "- " + mExt.getExtensionId().toString() + "\n");
+ "- " + mExt.getExtensionId().toString() + "\n");
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(
PrettyPrintResources.TOKEN_CRITICAL));
if (mExt.isCritical()) {
@@ -287,7 +288,7 @@ public class ExtPrettyPrint {
sb.append(pp.indent(mIndentSize) + mResource.getString(
PrettyPrintResources.TOKEN_IDENTIFIER));
sb.append(mResource.getString(PrettyPrintResources.TOKEN_NAME_CONSTRAINTS) +
- "- " + mExt.getExtensionId().toString() + "\n");
+ "- " + mExt.getExtensionId().toString() + "\n");
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(
PrettyPrintResources.TOKEN_CRITICAL));
if (mExt.isCritical()) {
@@ -313,7 +314,7 @@ public class ExtPrettyPrint {
sb.append(pp.indent(mIndentSize) + mResource.getString(
PrettyPrintResources.TOKEN_IDENTIFIER));
sb.append(mResource.getString(PrettyPrintResources.TOKEN_OCSP_NOCHECK) +
- "- " + mExt.getExtensionId().toString() + "\n");
+ "- " + mExt.getExtensionId().toString() + "\n");
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(
PrettyPrintResources.TOKEN_CRITICAL));
if (mExt.isCritical()) {
@@ -327,7 +328,7 @@ public class ExtPrettyPrint {
} catch (Exception e) {
return sb.toString();
}
- }
+ }
private String getSubjectInfoAccessExtension() {
StringBuffer sb = new StringBuffer();
@@ -336,7 +337,7 @@ public class ExtPrettyPrint {
sb.append(pp.indent(mIndentSize) + mResource.getString(
PrettyPrintResources.TOKEN_IDENTIFIER));
sb.append(mResource.getString(PrettyPrintResources.TOKEN_SIA) +
- "- " + mExt.getExtensionId().toString() + "\n");
+ "- " + mExt.getExtensionId().toString() + "\n");
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(
PrettyPrintResources.TOKEN_CRITICAL));
if (mExt.isCritical()) {
@@ -352,18 +353,18 @@ public class ExtPrettyPrint {
for (int i = 0; i < aia.numberOfAccessDescription(); i++) {
AccessDescription ad = (AccessDescription)
- aia.getAccessDescription(i);
+ aia.getAccessDescription(i);
ObjectIdentifier method = ad.getMethod();
if (method.equals(SubjectInfoAccessExtension.METHOD_OCSP)) {
sb.append(pp.indent(mIndentSize + 8) + "Method #" + i + ": " +
- "ocsp" + "\n");
+ "ocsp" + "\n");
} else {
sb.append(pp.indent(mIndentSize + 8) + "Method #" + i + ": " +
- method.toString() + "\n");
+ method.toString() + "\n");
}
sb.append(pp.indent(mIndentSize + 8) + "Location #" + i + ": " +
- ad.getLocation().toString() + "\n");
+ ad.getLocation().toString() + "\n");
}
return sb.toString();
} catch (Exception e) {
@@ -378,7 +379,7 @@ public class ExtPrettyPrint {
sb.append(pp.indent(mIndentSize) + mResource.getString(
PrettyPrintResources.TOKEN_IDENTIFIER));
sb.append(mResource.getString(PrettyPrintResources.TOKEN_AIA) +
- "- " + mExt.getExtensionId().toString() + "\n");
+ "- " + mExt.getExtensionId().toString() + "\n");
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(
PrettyPrintResources.TOKEN_CRITICAL));
if (mExt.isCritical()) {
@@ -394,18 +395,18 @@ public class ExtPrettyPrint {
for (int i = 0; i < aia.numberOfAccessDescription(); i++) {
AccessDescription ad = (AccessDescription)
- aia.getAccessDescription(i);
+ aia.getAccessDescription(i);
ObjectIdentifier method = ad.getMethod();
if (method.equals(AuthInfoAccessExtension.METHOD_OCSP)) {
sb.append(pp.indent(mIndentSize + 8) + "Method #" + i + ": " +
- "ocsp" + "\n");
+ "ocsp" + "\n");
} else {
sb.append(pp.indent(mIndentSize + 8) + "Method #" + i + ": " +
- method.toString() + "\n");
+ method.toString() + "\n");
}
sb.append(pp.indent(mIndentSize + 8) + "Location #" + i + ": " +
- ad.getLocation().toString() + "\n");
+ ad.getLocation().toString() + "\n");
}
return sb.toString();
} catch (Exception e) {
@@ -420,7 +421,7 @@ public class ExtPrettyPrint {
sb.append(pp.indent(mIndentSize) + mResource.getString(
PrettyPrintResources.TOKEN_IDENTIFIER));
sb.append(mResource.getString(PrettyPrintResources.TOKEN_PRESENCE_SERVER) +
- "- " + mExt.getExtensionId().toString() + "\n");
+ "- " + mExt.getExtensionId().toString() + "\n");
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(
PrettyPrintResources.TOKEN_CRITICAL));
if (mExt.isCritical()) {
@@ -447,7 +448,7 @@ public class ExtPrettyPrint {
} catch (Exception e) {
return sb.toString();
}
- }
+ }
private String getPrivateKeyUsageExtension() {
StringBuffer sb = new StringBuffer();
@@ -456,7 +457,7 @@ public class ExtPrettyPrint {
sb.append(pp.indent(mIndentSize) + mResource.getString(
PrettyPrintResources.TOKEN_IDENTIFIER));
sb.append(mResource.getString(PrettyPrintResources.TOKEN_PRIVATE_KEY_USAGE) +
- "- " + mExt.getExtensionId().toString() + "\n");
+ "- " + mExt.getExtensionId().toString() + "\n");
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(
PrettyPrintResources.TOKEN_CRITICAL));
if (mExt.isCritical()) {
@@ -484,7 +485,7 @@ public class ExtPrettyPrint {
} catch (Exception e) {
return sb.toString();
}
- }
+ }
private String getExtendedKeyUsageExtension() {
StringBuffer sb = new StringBuffer();
@@ -493,7 +494,7 @@ public class ExtPrettyPrint {
sb.append(pp.indent(mIndentSize) + mResource.getString(
PrettyPrintResources.TOKEN_IDENTIFIER));
sb.append(mResource.getString(PrettyPrintResources.TOKEN_EXTENDED_KEY_USAGE) +
- "- " + mExt.getExtensionId().toString() + "\n");
+ "- " + mExt.getExtensionId().toString() + "\n");
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(
PrettyPrintResources.TOKEN_CRITICAL));
if (mExt.isCritical()) {
@@ -535,7 +536,7 @@ public class ExtPrettyPrint {
sb.append(pp.indent(mIndentSize) + mResource.getString(
PrettyPrintResources.TOKEN_IDENTIFIER));
sb.append(mResource.getString(PrettyPrintResources.TOKEN_KEY_USAGE) +
- "- " + mExt.getExtensionId().toString() + "\n");
+ "- " + mExt.getExtensionId().toString() + "\n");
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(
PrettyPrintResources.TOKEN_CRITICAL));
if (mExt.isCritical()) {
@@ -678,7 +679,7 @@ public class ExtPrettyPrint {
if (keyId != null) {
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(PrettyPrintResources.TOKEN_KEY_ID) + "\n");
sb.append(pp.toHexString(keyId.getIdentifier(), mIndentSize + 8, 16));
- // sb.append(pp.toHexString(keyId.getIdentifier(),24,16));
+ // sb.append(pp.toHexString(keyId.getIdentifier(),24,16));
}
GeneralNames authNames = (GeneralNames) id.get(AuthorityKeyIdentifierExtension.AUTH_NAME);
@@ -696,7 +697,7 @@ public class ExtPrettyPrint {
if (serial != null) {
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(PrettyPrintResources.TOKEN_SERIAL) +
- "0x" + serial.getNumber().toBigInteger().toString(16).toUpperCase() + "\n");
+ "0x" + serial.getNumber().toBigInteger().toString(16).toUpperCase() + "\n");
}
return sb.toString();
} catch (Exception e) {
@@ -713,7 +714,7 @@ public class ExtPrettyPrint {
try {
sb.append(pp.indent(mIndentSize) + mResource.getString(PrettyPrintResources.TOKEN_IDENTIFIER));
sb.append(mResource.getString(PrettyPrintResources.TOKEN_REVOCATION_REASON) + "- " +
- mExt.getExtensionId().toString() + "\n");
+ mExt.getExtensionId().toString() + "\n");
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(PrettyPrintResources.TOKEN_CRITICAL));
CRLReasonExtension ext = (CRLReasonExtension) mExt;
@@ -723,7 +724,7 @@ public class ExtPrettyPrint {
sb.append(mResource.getString(PrettyPrintResources.TOKEN_NO) + "\n");
}
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(PrettyPrintResources.TOKEN_REASON) +
- ext.getReason().toString() + "\n");
+ ext.getReason().toString() + "\n");
return sb.toString();
} catch (Exception e) {
@@ -738,23 +739,23 @@ public class ExtPrettyPrint {
StringBuffer sb = new StringBuffer();
try {
sb.append(pp.indent(mIndentSize) +
- mResource.getString(PrettyPrintResources.TOKEN_IDENTIFIER));
+ mResource.getString(PrettyPrintResources.TOKEN_IDENTIFIER));
sb.append(mResource.getString(
- PrettyPrintResources.TOKEN_INHIBIT_ANY_POLICY_EXT) + "- "+
- mExt.getExtensionId().toString() +"\n");
- sb.append(pp.indent(mIndentSize + 4) +
- mResource.getString(PrettyPrintResources.TOKEN_CRITICAL));
- InhibitAnyPolicyExtension ext = (InhibitAnyPolicyExtension)mExt;
+ PrettyPrintResources.TOKEN_INHIBIT_ANY_POLICY_EXT) + "- " +
+ mExt.getExtensionId().toString() + "\n");
+ sb.append(pp.indent(mIndentSize + 4) +
+ mResource.getString(PrettyPrintResources.TOKEN_CRITICAL));
+ InhibitAnyPolicyExtension ext = (InhibitAnyPolicyExtension) mExt;
if (((Extension) mExt).isCritical())
sb.append(mResource.getString(
- PrettyPrintResources.TOKEN_YES) + "\n");
+ PrettyPrintResources.TOKEN_YES) + "\n");
else
sb.append(mResource.getString(
- PrettyPrintResources.TOKEN_NO) + "\n");
+ PrettyPrintResources.TOKEN_NO) + "\n");
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(
- PrettyPrintResources.TOKEN_SKIP_CERTS));
+ PrettyPrintResources.TOKEN_SKIP_CERTS));
BigInt num = ext.getSkipCerts();
- sb.append(""+num.toInt() + "\n");
+ sb.append("" + num.toInt() + "\n");
return sb.toString();
} catch (Exception e) {
return "";
@@ -770,7 +771,7 @@ public class ExtPrettyPrint {
try {
sb.append(pp.indent(mIndentSize) + mResource.getString(PrettyPrintResources.TOKEN_IDENTIFIER));
sb.append(mResource.getString(PrettyPrintResources.TOKEN_BASIC_CONSTRAINTS) + "- " +
- mExt.getExtensionId().toString() + "\n");
+ mExt.getExtensionId().toString() + "\n");
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(PrettyPrintResources.TOKEN_CRITICAL));
BasicConstraintsExtension ext = (BasicConstraintsExtension) mExt;
@@ -792,14 +793,14 @@ public class ExtPrettyPrint {
if (pathLength != null) {
if (pathLength.longValue() >= 0) {
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(PrettyPrintResources.TOKEN_PATH_LEN) +
- pathLength.toString() + "\n");
+ pathLength.toString() + "\n");
} else if (pathLength.longValue() == -1 || pathLength.longValue() == -2) {
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(PrettyPrintResources.TOKEN_PATH_LEN) +
- mResource.getString(PrettyPrintResources.TOKEN_PATH_LEN_UNLIMITED) + "\n");
+ mResource.getString(PrettyPrintResources.TOKEN_PATH_LEN_UNLIMITED) + "\n");
} else {
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(PrettyPrintResources.TOKEN_PATH_LEN) +
- mResource.getString(PrettyPrintResources.TOKEN_PATH_LEN_INVALID) +
- " (" + pathLength.toString() + ")\n");
+ mResource.getString(PrettyPrintResources.TOKEN_PATH_LEN_INVALID) +
+ " (" + pathLength.toString() + ")\n");
}
}
@@ -818,7 +819,7 @@ public class ExtPrettyPrint {
try {
sb.append(pp.indent(mIndentSize) + mResource.getString(PrettyPrintResources.TOKEN_IDENTIFIER));
sb.append(mResource.getString(PrettyPrintResources.TOKEN_CRL_NUMBER) + "- " +
- mExt.getExtensionId().toString() + "\n");
+ mExt.getExtensionId().toString() + "\n");
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(PrettyPrintResources.TOKEN_CRITICAL));
CRLNumberExtension ext = (CRLNumberExtension) mExt;
@@ -831,8 +832,8 @@ public class ExtPrettyPrint {
if (crlNumber != null) {
sb.append(pp.indent(mIndentSize + 4) +
- mResource.getString(PrettyPrintResources.TOKEN_NUMBER) +
- crlNumber.toString() + "\n");
+ mResource.getString(PrettyPrintResources.TOKEN_NUMBER) +
+ crlNumber.toString() + "\n");
}
return sb.toString();
@@ -850,7 +851,7 @@ public class ExtPrettyPrint {
try {
sb.append(pp.indent(mIndentSize) + mResource.getString(PrettyPrintResources.TOKEN_IDENTIFIER));
sb.append(mResource.getString(PrettyPrintResources.TOKEN_DELTA_CRL_INDICATOR) + "- " +
- mExt.getExtensionId().toString() + "\n");
+ mExt.getExtensionId().toString() + "\n");
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(PrettyPrintResources.TOKEN_CRITICAL));
DeltaCRLIndicatorExtension ext = (DeltaCRLIndicatorExtension) mExt;
@@ -863,8 +864,8 @@ public class ExtPrettyPrint {
if (crlNumber != null) {
sb.append(pp.indent(mIndentSize + 4) +
- mResource.getString(PrettyPrintResources.TOKEN_BASE_CRL_NUMBER) +
- crlNumber.toString() + "\n");
+ mResource.getString(PrettyPrintResources.TOKEN_BASE_CRL_NUMBER) +
+ crlNumber.toString() + "\n");
}
return sb.toString();
@@ -882,7 +883,7 @@ public class ExtPrettyPrint {
try {
sb.append(pp.indent(mIndentSize) + mResource.getString(PrettyPrintResources.TOKEN_IDENTIFIER));
sb.append(mResource.getString(PrettyPrintResources.TOKEN_ISSUER_ALT_NAME) + "- " +
- mExt.getExtensionId().toString() + "\n");
+ mExt.getExtensionId().toString() + "\n");
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(PrettyPrintResources.TOKEN_CRITICAL));
IssuerAlternativeNameExtension ext = (IssuerAlternativeNameExtension) mExt;
@@ -896,7 +897,7 @@ public class ExtPrettyPrint {
if (issuerNames != null) {
sb.append(pp.indent(mIndentSize + 4) +
- mResource.getString(PrettyPrintResources.TOKEN_ISSUER_NAMES) + "\n");
+ mResource.getString(PrettyPrintResources.TOKEN_ISSUER_NAMES) + "\n");
for (int i = 0; i < issuerNames.size(); i++) {
GeneralName issuerName = (GeneralName) issuerNames.elementAt(i);
@@ -925,7 +926,7 @@ public class ExtPrettyPrint {
try {
sb.append(pp.indent(mIndentSize) + mResource.getString(PrettyPrintResources.TOKEN_IDENTIFIER));
sb.append(mResource.getString(PrettyPrintResources.TOKEN_SUBJECT_ALT_NAME) + "- " +
- mExt.getExtensionId().toString() + "\n");
+ mExt.getExtensionId().toString() + "\n");
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(PrettyPrintResources.TOKEN_CRITICAL));
SubjectAlternativeNameExtension ext = (SubjectAlternativeNameExtension) mExt;
@@ -965,7 +966,7 @@ public class ExtPrettyPrint {
try {
sb.append(pp.indent(mIndentSize) + mResource.getString(PrettyPrintResources.TOKEN_IDENTIFIER));
sb.append(mResource.getString(PrettyPrintResources.TOKEN_CERT_SCOPE_OF_USE) + "- " +
- mExt.getExtensionId().toString() + "\n");
+ mExt.getExtensionId().toString() + "\n");
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(PrettyPrintResources.TOKEN_CRITICAL));
CertificateScopeOfUseExtension ext = (CertificateScopeOfUseExtension) mExt;
@@ -978,7 +979,7 @@ public class ExtPrettyPrint {
if (entries != null) {
sb.append(pp.indent(mIndentSize + 4) +
- mResource.getString(PrettyPrintResources.TOKEN_SCOPE_OF_USE) + "\n");
+ mResource.getString(PrettyPrintResources.TOKEN_SCOPE_OF_USE) + "\n");
for (int i = 0; i < entries.size(); i++) {
CertificateScopeEntry se = (CertificateScopeEntry) entries.elementAt(i);
GeneralName gn = se.getGeneralName();
@@ -994,7 +995,7 @@ public class ExtPrettyPrint {
if (port != null) {
sb.append(pp.indent(mIndentSize + 8) + PrettyPrintResources.TOKEN_PORT +
- port.toBigInteger().toString() + "\n");
+ port.toBigInteger().toString() + "\n");
}
}
}
@@ -1016,12 +1017,12 @@ public class ExtPrettyPrint {
// Generic stuff: name, OID, criticality
//
sb.append(pp.indent(mIndentSize) +
- mResource.getString(PrettyPrintResources.TOKEN_IDENTIFIER));
+ mResource.getString(PrettyPrintResources.TOKEN_IDENTIFIER));
sb.append(mResource.getString(
PrettyPrintResources.TOKEN_FRESHEST_CRL_EXT) + "- " +
- mExt.getExtensionId().toString() + "\n");
+ mExt.getExtensionId().toString() + "\n");
sb.append(pp.indent(mIndentSize + 4) +
- mResource.getString(PrettyPrintResources.TOKEN_CRITICAL));
+ mResource.getString(PrettyPrintResources.TOKEN_CRITICAL));
if (((Extension) mExt).isCritical()) {
sb.append(mResource.getString(
PrettyPrintResources.TOKEN_YES) + "\n");
@@ -1039,7 +1040,7 @@ public class ExtPrettyPrint {
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(
PrettyPrintResources.TOKEN_CRLDP_NUMPOINTS)
- + numPoints + "\n");
+ + numPoints + "\n");
for (int i = 0; i < numPoints; i++) {
@@ -1053,8 +1054,8 @@ public class ExtPrettyPrint {
boolean isEmpty = true;
sb.append(pp.indent(idt) +
- mResource.getString(PrettyPrintResources.TOKEN_CRLDP_POINTN) +
- i + "\n");
+ mResource.getString(PrettyPrintResources.TOKEN_CRLDP_POINTN) +
+ i + "\n");
CRLDistributionPoint pt = ext.getPointAt(i);
@@ -1063,15 +1064,15 @@ public class ExtPrettyPrint {
if (pt.getFullName() != null) {
isEmpty = false;
sb.append(pp.indent(idt) +
- mResource.getString(PrettyPrintResources.TOKEN_CRLDP_DISTPOINT)
- + pt.getFullName() + "\n");
+ mResource.getString(PrettyPrintResources.TOKEN_CRLDP_DISTPOINT)
+ + pt.getFullName() + "\n");
}
if (pt.getRelativeName() != null) {
isEmpty = false;
sb.append(pp.indent(idt) +
- mResource.getString(PrettyPrintResources.TOKEN_CRLDP_DISTPOINT)
- + pt.getRelativeName() + "\n");
+ mResource.getString(PrettyPrintResources.TOKEN_CRLDP_DISTPOINT)
+ + pt.getRelativeName() + "\n");
}
if (pt.getReasons() != null) {
@@ -1080,15 +1081,15 @@ public class ExtPrettyPrint {
String reasonList = reasonBitsToReasonList(reasonBits);
sb.append(pp.indent(idt) +
- mResource.getString(PrettyPrintResources.TOKEN_CRLDP_REASONS)
- + reasonList + "\n");
+ mResource.getString(PrettyPrintResources.TOKEN_CRLDP_REASONS)
+ + reasonList + "\n");
}
-
+
if (pt.getCRLIssuer() != null) {
isEmpty = false;
sb.append(pp.indent(idt) +
- mResource.getString(PrettyPrintResources.TOKEN_CRLDP_CRLISSUER)
- + pt.getCRLIssuer() + "\n");
+ mResource.getString(PrettyPrintResources.TOKEN_CRLDP_CRLISSUER)
+ + pt.getCRLIssuer() + "\n");
}
if (isEmpty) {
@@ -1115,12 +1116,12 @@ public class ExtPrettyPrint {
// Generic stuff: name, OID, criticality
//
sb.append(pp.indent(mIndentSize) +
- mResource.getString(PrettyPrintResources.TOKEN_IDENTIFIER));
+ mResource.getString(PrettyPrintResources.TOKEN_IDENTIFIER));
sb.append(mResource.getString(
PrettyPrintResources.TOKEN_CRL_DP_EXT) + "- " +
- mExt.getExtensionId().toString() + "\n");
+ mExt.getExtensionId().toString() + "\n");
sb.append(pp.indent(mIndentSize + 4) +
- mResource.getString(PrettyPrintResources.TOKEN_CRITICAL));
+ mResource.getString(PrettyPrintResources.TOKEN_CRITICAL));
if (((Extension) mExt).isCritical()) {
sb.append(mResource.getString(
PrettyPrintResources.TOKEN_YES) + "\n");
@@ -1133,13 +1134,13 @@ public class ExtPrettyPrint {
// Now the CRLDP-specific stuff
//
CRLDistributionPointsExtension ext =
- (CRLDistributionPointsExtension) mExt;
+ (CRLDistributionPointsExtension) mExt;
int numPoints = ext.getNumPoints();
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(
PrettyPrintResources.TOKEN_CRLDP_NUMPOINTS)
- + numPoints + "\n");
+ + numPoints + "\n");
for (int i = 0; i < numPoints; i++) {
@@ -1153,8 +1154,8 @@ public class ExtPrettyPrint {
boolean isEmpty = true;
sb.append(pp.indent(idt) +
- mResource.getString(PrettyPrintResources.TOKEN_CRLDP_POINTN) +
- i + "\n");
+ mResource.getString(PrettyPrintResources.TOKEN_CRLDP_POINTN) +
+ i + "\n");
CRLDistributionPoint pt = ext.getPointAt(i);
@@ -1163,15 +1164,15 @@ public class ExtPrettyPrint {
if (pt.getFullName() != null) {
isEmpty = false;
sb.append(pp.indent(idt) +
- mResource.getString(PrettyPrintResources.TOKEN_CRLDP_DISTPOINT)
- + pt.getFullName() + "\n");
+ mResource.getString(PrettyPrintResources.TOKEN_CRLDP_DISTPOINT)
+ + pt.getFullName() + "\n");
}
if (pt.getRelativeName() != null) {
isEmpty = false;
sb.append(pp.indent(idt) +
- mResource.getString(PrettyPrintResources.TOKEN_CRLDP_DISTPOINT)
- + pt.getRelativeName() + "\n");
+ mResource.getString(PrettyPrintResources.TOKEN_CRLDP_DISTPOINT)
+ + pt.getRelativeName() + "\n");
}
if (pt.getReasons() != null) {
@@ -1180,15 +1181,15 @@ public class ExtPrettyPrint {
String reasonList = reasonBitsToReasonList(reasonBits);
sb.append(pp.indent(idt) +
- mResource.getString(PrettyPrintResources.TOKEN_CRLDP_REASONS)
- + reasonList + "\n");
+ mResource.getString(PrettyPrintResources.TOKEN_CRLDP_REASONS)
+ + reasonList + "\n");
}
-
+
if (pt.getCRLIssuer() != null) {
isEmpty = false;
sb.append(pp.indent(idt) +
- mResource.getString(PrettyPrintResources.TOKEN_CRLDP_CRLISSUER)
- + pt.getCRLIssuer() + "\n");
+ mResource.getString(PrettyPrintResources.TOKEN_CRLDP_CRLISSUER)
+ + pt.getCRLIssuer() + "\n");
}
if (isEmpty) {
@@ -1230,7 +1231,7 @@ public class ExtPrettyPrint {
try {
sb.append(pp.indent(mIndentSize) + mResource.getString(PrettyPrintResources.TOKEN_IDENTIFIER));
sb.append(mResource.getString(PrettyPrintResources.TOKEN_ISSUING_DIST_POINT) + "- " +
- mExt.getExtensionId().toString() + "\n");
+ mExt.getExtensionId().toString() + "\n");
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(PrettyPrintResources.TOKEN_CRITICAL));
if (((Extension) mExt).isCritical()) {
sb.append(mResource.getString(PrettyPrintResources.TOKEN_YES) + "\n");
@@ -1259,7 +1260,7 @@ public class ExtPrettyPrint {
}
if (relativeName != null) {
sb.append(pp.indent(mIndentSize + 8) + mResource.getString(PrettyPrintResources.TOKEN_RELATIVE_NAME) +
- relativeName.toString() + "\n");
+ relativeName.toString() + "\n");
}
}
@@ -1307,7 +1308,7 @@ public class ExtPrettyPrint {
sb.append(pp.indent(mIndentSize) + mResource.getString(
PrettyPrintResources.TOKEN_IDENTIFIER));
sb.append(mResource.getString(PrettyPrintResources.TOKEN_INVALIDITY_DATE) +
- "- " + mExt.getExtensionId().toString() + "\n");
+ "- " + mExt.getExtensionId().toString() + "\n");
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(
PrettyPrintResources.TOKEN_CRITICAL));
InvalidityDateExtension ext = (InvalidityDateExtension) mExt;
@@ -1319,9 +1320,9 @@ public class ExtPrettyPrint {
}
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(
PrettyPrintResources.TOKEN_DATE_OF_INVALIDITY) +
- ext.getInvalidityDate().toString() + "\n");
+ ext.getInvalidityDate().toString() + "\n");
return sb.toString();
- } catch (Exception e) {
+ } catch (Exception e) {
return "";
}
}
@@ -1336,7 +1337,7 @@ public class ExtPrettyPrint {
sb.append(pp.indent(mIndentSize) + mResource.getString(
PrettyPrintResources.TOKEN_IDENTIFIER));
sb.append(mResource.getString(PrettyPrintResources.TOKEN_CERTIFICATE_ISSUER) +
- "- " + mExt.getExtensionId().toString() + "\n");
+ "- " + mExt.getExtensionId().toString() + "\n");
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(
PrettyPrintResources.TOKEN_CRITICAL));
CertificateIssuerExtension ext = (CertificateIssuerExtension) mExt;
@@ -1352,7 +1353,7 @@ public class ExtPrettyPrint {
if (issuerNames != null) {
sb.append(pp.indent(mIndentSize + 4) +
- mResource.getString(PrettyPrintResources.TOKEN_ISSUER_NAMES) + "\n");
+ mResource.getString(PrettyPrintResources.TOKEN_ISSUER_NAMES) + "\n");
for (int i = 0; i < issuerNames.size(); i++) {
GeneralName issuerName = (GeneralName) issuerNames.elementAt(i);
@@ -1382,7 +1383,7 @@ public class ExtPrettyPrint {
sb.append(pp.indent(mIndentSize) + mResource.getString(
PrettyPrintResources.TOKEN_IDENTIFIER));
sb.append(mResource.getString(PrettyPrintResources.TOKEN_HOLD_INSTRUCTION) +
- "- " + mExt.getExtensionId().toString() + "\n");
+ "- " + mExt.getExtensionId().toString() + "\n");
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(
PrettyPrintResources.TOKEN_CRITICAL));
HoldInstructionExtension ext = (HoldInstructionExtension) mExt;
@@ -1394,9 +1395,9 @@ public class ExtPrettyPrint {
}
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(
PrettyPrintResources.TOKEN_HOLD_INSTRUCTION_CODE) +
- ext.getHoldInstructionCodeDescription() + "\n");
+ ext.getHoldInstructionCodeDescription() + "\n");
return sb.toString();
- } catch (Exception e) {
+ } catch (Exception e) {
return "";
}
}
@@ -1411,9 +1412,9 @@ public class ExtPrettyPrint {
sb.append(pp.indent(mIndentSize) + mResource.getString(
PrettyPrintResources.TOKEN_IDENTIFIER));
sb.append(
- mResource.getString(
- PrettyPrintResources.TOKEN_POLICY_CONSTRAINTS) +
- "- " + mExt.getExtensionId().toString() + "\n");
+ mResource.getString(
+ PrettyPrintResources.TOKEN_POLICY_CONSTRAINTS) +
+ "- " + mExt.getExtensionId().toString() + "\n");
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(
PrettyPrintResources.TOKEN_CRITICAL));
if (((Extension) mExt).isCritical()) {
@@ -1427,19 +1428,19 @@ public class ExtPrettyPrint {
int inhibit = ext.getInhibitPolicyMapping();
sb.append(
- pp.indent(mIndentSize + 4) +
- mResource.getString(
- PrettyPrintResources.TOKEN_REQUIRE_EXPLICIT_POLICY) +
- ((require == -1) ?
- mResource.getString(PrettyPrintResources.TOKEN_NOT_SET) :
- String.valueOf(require)) + "\n");
+ pp.indent(mIndentSize + 4) +
+ mResource.getString(
+ PrettyPrintResources.TOKEN_REQUIRE_EXPLICIT_POLICY) +
+ ((require == -1) ?
+ mResource.getString(PrettyPrintResources.TOKEN_NOT_SET) :
+ String.valueOf(require)) + "\n");
sb.append(
- pp.indent(mIndentSize + 4) +
- mResource.getString(
- PrettyPrintResources.TOKEN_INHIBIT_POLICY_MAPPING) +
- ((inhibit == -1) ?
- mResource.getString(PrettyPrintResources.TOKEN_NOT_SET) :
- String.valueOf(inhibit)) + "\n");
+ pp.indent(mIndentSize + 4) +
+ mResource.getString(
+ PrettyPrintResources.TOKEN_INHIBIT_POLICY_MAPPING) +
+ ((inhibit == -1) ?
+ mResource.getString(PrettyPrintResources.TOKEN_NOT_SET) :
+ String.valueOf(inhibit)) + "\n");
return sb.toString();
} catch (Exception e) {
return "";
@@ -1456,7 +1457,7 @@ public class ExtPrettyPrint {
sb.append(pp.indent(mIndentSize) + mResource.getString(
PrettyPrintResources.TOKEN_IDENTIFIER));
sb.append(mResource.getString(PrettyPrintResources.TOKEN_POLICY_MAPPINGS) +
- "- " + mExt.getExtensionId().toString() + "\n");
+ "- " + mExt.getExtensionId().toString() + "\n");
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(
PrettyPrintResources.TOKEN_CRITICAL));
if (((Extension) mExt).isCritical()) {
@@ -1469,27 +1470,27 @@ public class ExtPrettyPrint {
Enumeration<CertificatePolicyMap> maps = ext.getMappings();
sb.append(pp.indent(mIndentSize + 4) +
- mResource.getString(PrettyPrintResources.TOKEN_MAPPINGS));
+ mResource.getString(PrettyPrintResources.TOKEN_MAPPINGS));
if (maps == null || !maps.hasMoreElements()) {
sb.append(
- mResource.getString(PrettyPrintResources.TOKEN_NONE) + "\n");
+ mResource.getString(PrettyPrintResources.TOKEN_NONE) + "\n");
} else {
sb.append("\n");
for (int i = 0; maps.hasMoreElements(); i++) {
sb.append(pp.indent(mIndentSize + 8) +
- mResource.getString(
- PrettyPrintResources.TOKEN_MAP) + i + ":" + "\n");
- CertificatePolicyMap m =
- (CertificatePolicyMap) maps.nextElement();
+ mResource.getString(
+ PrettyPrintResources.TOKEN_MAP) + i + ":" + "\n");
+ CertificatePolicyMap m =
+ (CertificatePolicyMap) maps.nextElement();
sb.append(pp.indent(mIndentSize + 12) +
- mResource.getString(
- PrettyPrintResources.TOKEN_ISSUER_DOMAIN_POLICY) +
- m.getIssuerIdentifier().getIdentifier().toString() + "\n");
+ mResource.getString(
+ PrettyPrintResources.TOKEN_ISSUER_DOMAIN_POLICY) +
+ m.getIssuerIdentifier().getIdentifier().toString() + "\n");
sb.append(pp.indent(mIndentSize + 12) +
- mResource.getString(
- PrettyPrintResources.TOKEN_SUBJECT_DOMAIN_POLICY) +
- m.getSubjectIdentifier().getIdentifier().toString() + "\n");
+ mResource.getString(
+ PrettyPrintResources.TOKEN_SUBJECT_DOMAIN_POLICY) +
+ m.getSubjectIdentifier().getIdentifier().toString() + "\n");
}
}
return sb.toString();
@@ -1508,40 +1509,40 @@ public class ExtPrettyPrint {
sb.append(pp.indent(mIndentSize) + mResource.getString(
PrettyPrintResources.TOKEN_IDENTIFIER));
sb.append(mResource.getString(PrettyPrintResources.TOKEN_SUBJECT_DIR_ATTR) +
- "- " + mExt.getExtensionId().toString() + "\n");
+ "- " + mExt.getExtensionId().toString() + "\n");
sb.append(pp.indent(mIndentSize + 4) +
- mResource.getString(PrettyPrintResources.TOKEN_CRITICAL));
+ mResource.getString(PrettyPrintResources.TOKEN_CRITICAL));
if (((Extension) mExt).isCritical()) {
sb.append(mResource.getString(PrettyPrintResources.TOKEN_YES) + "\n");
} else {
sb.append(mResource.getString(PrettyPrintResources.TOKEN_NO) + "\n");
}
- SubjectDirAttributesExtension ext =
- (SubjectDirAttributesExtension) mExt;
+ SubjectDirAttributesExtension ext =
+ (SubjectDirAttributesExtension) mExt;
sb.append(pp.indent(mIndentSize + 4) +
- mResource.getString(PrettyPrintResources.TOKEN_ATTRIBUTES));
+ mResource.getString(PrettyPrintResources.TOKEN_ATTRIBUTES));
Enumeration<Attribute> attrs = ext.getAttributesList();
if (attrs == null || !attrs.hasMoreElements()) {
sb.append(
- mResource.getString(PrettyPrintResources.TOKEN_NONE) + "\n");
+ mResource.getString(PrettyPrintResources.TOKEN_NONE) + "\n");
} else {
sb.append("\n");
for (int j = 0; attrs.hasMoreElements(); j++) {
Attribute attr = (Attribute) attrs.nextElement();
sb.append(pp.indent(mIndentSize + 8) +
- mResource.getString(
- PrettyPrintResources.TOKEN_ATTRIBUTE) + j + ":" + "\n");
+ mResource.getString(
+ PrettyPrintResources.TOKEN_ATTRIBUTE) + j + ":" + "\n");
sb.append(pp.indent(mIndentSize + 12) +
- mResource.getString(
- PrettyPrintResources.TOKEN_IDENTIFIER) +
- attr.getOid().toString() + "\n");
+ mResource.getString(
+ PrettyPrintResources.TOKEN_IDENTIFIER) +
+ attr.getOid().toString() + "\n");
sb.append(pp.indent(mIndentSize + 12) +
- mResource.getString(
- PrettyPrintResources.TOKEN_VALUES));
+ mResource.getString(
+ PrettyPrintResources.TOKEN_VALUES));
Enumeration<String> values = attr.getValues();
if (values == null || !values.hasMoreElements()) {
@@ -1551,7 +1552,7 @@ public class ExtPrettyPrint {
for (int k = 0; values.hasMoreElements(); k++) {
String v = (String) values.nextElement();
- if (k != 0)
+ if (k != 0)
sb.append(",");
sb.append(v);
}
@@ -1572,7 +1573,7 @@ public class ExtPrettyPrint {
sb.append(pp.indent(mIndentSize) + mResource.getString(
PrettyPrintResources.TOKEN_IDENTIFIER));
sb.append(mResource.getString(PrettyPrintResources.TOKEN_CERT_POLICIES) +
- "- " + mExt.getExtensionId().toString() + "\n");
+ "- " + mExt.getExtensionId().toString() + "\n");
sb.append(pp.indent(mIndentSize + 4) + mResource.getString(
PrettyPrintResources.TOKEN_CRITICAL));
if (mExt.isCritical()) {
@@ -1586,7 +1587,7 @@ public class ExtPrettyPrint {
PrettyPrintResources.TOKEN_CERT_POLICIES) + "\n");
CertificatePoliciesExtension cp = (CertificatePoliciesExtension) mExt;
@SuppressWarnings("unchecked")
- Vector<CertificatePolicyInfo> cpv = (Vector<CertificatePolicyInfo>) cp.get("infos");
+ Vector<CertificatePolicyInfo> cpv = (Vector<CertificatePolicyInfo>) cp.get("infos");
Enumeration<CertificatePolicyInfo> e = cpv.elements();
if (e != null) {
@@ -1596,25 +1597,24 @@ public class ExtPrettyPrint {
sb.append(pp.indent(mIndentSize + 8) + "Policy Identifier: " + cpi.getPolicyIdentifier().getIdentifier().toString() + "\n");
PolicyQualifiers cpq = cpi.getPolicyQualifiers();
if (cpq != null) {
- for (int i=0; i < cpq.size(); i++) {
+ for (int i = 0; i < cpq.size(); i++) {
PolicyQualifierInfo pq = cpq.getInfoAt(i);
Qualifier q = pq.getQualifier();
if (q instanceof CPSuri) {
- sb.append(pp.indent(mIndentSize + 12) + "Policy Qualifier Identifier: CPS Pointer Qualifier - "
- + pq.getId() + "\n");
+ sb.append(pp.indent(mIndentSize + 12) + "Policy Qualifier Identifier: CPS Pointer Qualifier - "
+ + pq.getId() + "\n");
sb.append(pp.indent(mIndentSize + 12) + "Policy Qualifier Data: " + ((CPSuri) q).getURI() + "\n");
- }
- else if (q instanceof UserNotice) {
- sb.append(pp.indent(mIndentSize + 12) + "Policy Qualifier Identifier: CPS User Notice Qualifier - "
- + pq.getId() + "\n");
+ } else if (q instanceof UserNotice) {
+ sb.append(pp.indent(mIndentSize + 12) + "Policy Qualifier Identifier: CPS User Notice Qualifier - "
+ + pq.getId() + "\n");
NoticeReference nref = ((UserNotice) q).getNoticeReference();
DisplayText dt = ((UserNotice) q).getDisplayText();
- sb.append(pp.indent(mIndentSize +12) + "Policy Qualifier Data: \n");
- if (nref != null) {
- sb.append(pp.indent(mIndentSize+16) + "Organization: " + nref.getOrganization().toString() + "\n" );
- sb.append(pp.indent(mIndentSize+16) + "Notice Numbers: " );
+ sb.append(pp.indent(mIndentSize + 12) + "Policy Qualifier Data: \n");
+ if (nref != null) {
+ sb.append(pp.indent(mIndentSize + 16) + "Organization: " + nref.getOrganization().toString() + "\n");
+ sb.append(pp.indent(mIndentSize + 16) + "Notice Numbers: ");
int[] nums = nref.getNumbers();
- for (int k=0; k<nums.length; k++) {
+ for (int k = 0; k < nums.length; k++) {
if (k != 0) {
sb.append(",");
sb.append(nums[k]);
@@ -1625,9 +1625,9 @@ public class ExtPrettyPrint {
sb.append("\n");
}
if (dt != null) {
- sb.append(pp.indent(mIndentSize+16) + "Explicit Text: " + dt.toString() + "\n");
+ sb.append(pp.indent(mIndentSize + 16) + "Explicit Text: " + dt.toString() + "\n");
}
- }
+ }
}
}
}
@@ -1638,6 +1638,4 @@ public class ExtPrettyPrint {
}
}
-
}
-
diff --git a/pki/base/util/src/netscape/security/util/ObjectIdentifier.java b/pki/base/util/src/netscape/security/util/ObjectIdentifier.java
index 505db7a9..2e228b0d 100644
--- a/pki/base/util/src/netscape/security/util/ObjectIdentifier.java
+++ b/pki/base/util/src/netscape/security/util/ObjectIdentifier.java
@@ -21,62 +21,59 @@ import java.io.IOException;
import java.io.Serializable;
import java.util.StringTokenizer;
-
/**
* Represent an ISO Object Identifier.
- *
- * <P>Object Identifiers are arbitrary length hierarchical identifiers.
- * The individual components are numbers, and they define paths from the
- * root of an ISO-managed identifier space. You will sometimes see a
- * string name used instead of (or in addition to) the numerical id.
- * These are synonyms for the numerical IDs, but are not widely used
- * since most sites do not know all the requisite strings, while all
- * sites can parse the numeric forms.
- *
- * <P>So for example, JavaSoft has the sole authority to assign the
- * meaning to identifiers below the 1.3.6.1.4.42.2.17 node in the
- * hierarchy, and other organizations can easily acquire the ability
- * to assign such unique identifiers.
- *
+ *
+ * <P>
+ * Object Identifiers are arbitrary length hierarchical identifiers. The
+ * individual components are numbers, and they define paths from the root of an
+ * ISO-managed identifier space. You will sometimes see a string name used
+ * instead of (or in addition to) the numerical id. These are synonyms for the
+ * numerical IDs, but are not widely used since most sites do not know all the
+ * requisite strings, while all sites can parse the numeric forms.
+ *
+ * <P>
+ * So for example, JavaSoft has the sole authority to assign the meaning to
+ * identifiers below the 1.3.6.1.4.42.2.17 node in the hierarchy, and other
+ * organizations can easily acquire the ability to assign such unique
+ * identifiers.
+ *
* @version 1.23
- *
+ *
* @author David Brownell
* @author Amit Kapoor
* @author Hemma Prafullchandra
*/
-final public
-class ObjectIdentifier implements Serializable
-{
+final public class ObjectIdentifier implements Serializable {
/** use serialVersionUID from JDK 1.1. for interoperability */
private static final long serialVersionUID = 8697030238860181294L;
/**
- * Constructs an object identifier from a string. This string
- * should be of the form 1.23.34.45.56 etc.
+ * Constructs an object identifier from a string. This string should be of
+ * the form 1.23.34.45.56 etc.
*/
- public ObjectIdentifier (String oid)
- {
- if (oid == null)
- return;
-
+ public ObjectIdentifier(String oid) {
+ if (oid == null)
+ return;
+
int ch = '.';
- int start = 0;
+ int start = 0;
int end = 0;
-
+
// Calculate length of oid
componentLen = 0;
- while ((end = oid.indexOf(ch,start)) != -1) {
+ while ((end = oid.indexOf(ch, start)) != -1) {
start = end + 1;
componentLen += 1;
}
componentLen += 1;
components = new int[componentLen];
-
+
start = 0;
int i = 0;
String comp = null;
- while ((end = oid.indexOf(ch,start)) != -1) {
- comp = oid.substring(start,end);
+ while ((end = oid.indexOf(ch, start)) != -1) {
+ comp = oid.substring(start, end);
components[i++] = Integer.valueOf(comp).intValue();
start = end + 1;
}
@@ -85,271 +82,257 @@ class ObjectIdentifier implements Serializable
}
/**
- * Constructs an object ID from an array of integers. This
- * is used to construct constant object IDs.
+ * Constructs an object ID from an array of integers. This is used to
+ * construct constant object IDs.
*/
- public ObjectIdentifier (int values [])
- {
- try {
- components = (int []) values.clone ();
- componentLen = values.length;
- } catch (Throwable t) {
- System.out.println ("X509.ObjectIdentifier(), no cloning!");
- }
+ public ObjectIdentifier(int values[]) {
+ try {
+ components = (int[]) values.clone();
+ componentLen = values.length;
+ } catch (Throwable t) {
+ System.out.println("X509.ObjectIdentifier(), no cloning!");
+ }
}
-
/**
- * Constructs an object ID from an ASN.1 encoded input stream.
- * The encoding of the ID in the stream uses "DER", a BER/1 subset.
- * In this case, that means a triple { typeId, length, data }.
- *
- * <P><STRONG>NOTE:</STRONG> When an exception is thrown, the
- * input stream has not been returned to its "initial" state.
- *
+ * Constructs an object ID from an ASN.1 encoded input stream. The encoding
+ * of the ID in the stream uses "DER", a BER/1 subset. In this case, that
+ * means a triple { typeId, length, data }.
+ *
+ * <P>
+ * <STRONG>NOTE:</STRONG> When an exception is thrown, the input stream has
+ * not been returned to its "initial" state.
+ *
* @param in DER-encoded data holding an object ID
* @exception IOException indicates a decoding error
*/
- public ObjectIdentifier (DerInputStream in)
- throws IOException
- {
- byte type_id;
- int bufferEnd;
-
- /*
- * Object IDs are a "universal" type, and their tag needs only
- * one byte of encoding. Verify that the tag of this datum
- * is that of an object ID.
- *
- * Then get and check the length of the ID's encoding. We set
- * up so that we can use in.available() to check for the end of
- * this value in the data stream.
- */
- type_id = (byte) in.getByte ();
- if (type_id != DerValue.tag_ObjectId)
- throw new IOException (
- "X509.ObjectIdentifier() -- data isn't an object ID"
- + " (tag = " + type_id + ")"
- );
-
- bufferEnd = in.available () - in.getLength () - 1;
- if (bufferEnd < 0)
- throw new IOException (
- "X509.ObjectIdentifier() -- not enough data");
-
- initFromEncoding (in, bufferEnd);
+ public ObjectIdentifier(DerInputStream in)
+ throws IOException {
+ byte type_id;
+ int bufferEnd;
+
+ /*
+ * Object IDs are a "universal" type, and their tag needs only one byte
+ * of encoding. Verify that the tag of this datum is that of an object
+ * ID.
+ *
+ * Then get and check the length of the ID's encoding. We set up so that
+ * we can use in.available() to check for the end of this value in the
+ * data stream.
+ */
+ type_id = (byte) in.getByte();
+ if (type_id != DerValue.tag_ObjectId)
+ throw new IOException(
+ "X509.ObjectIdentifier() -- data isn't an object ID"
+ + " (tag = " + type_id + ")");
+
+ bufferEnd = in.available() - in.getLength() - 1;
+ if (bufferEnd < 0)
+ throw new IOException(
+ "X509.ObjectIdentifier() -- not enough data");
+
+ initFromEncoding(in, bufferEnd);
}
/*
- * Build the OID from the rest of a DER input buffer; the tag
- * and length have been removed/verified
+ * Build the OID from the rest of a DER input buffer; the tag and length
+ * have been removed/verified
*/
- ObjectIdentifier (DerInputBuffer buf) throws IOException
- {
- initFromEncoding (new DerInputStream (buf), 0);
+ ObjectIdentifier(DerInputBuffer buf) throws IOException {
+ initFromEncoding(new DerInputStream(buf), 0);
}
/*
- * Helper function -- get the OID from a stream, after tag and
- * length are verified.
+ * Helper function -- get the OID from a stream, after tag and length are
+ * verified.
*/
- private void initFromEncoding (DerInputStream in, int bufferEnd)
- throws IOException
- {
-
- /*
- * Now get the components ("sub IDs") one at a time. We fill a
- * temporary buffer, resizing it as needed.
- */
- int component;
- boolean first_subid = true;
-
- for (components = new int [allocationQuantum], componentLen = 0;
- in.available () > bufferEnd;
- ) {
- component = getComponent (in);
-
- if (first_subid) {
- int X, Y;
-
- /*
- * The ISO root has three children (0, 1, 2) and those nodes
- * aren't allowed to assign IDs larger than 39. These rules
- * are memorialized by some special casing in the BER encoding
- * of object IDs ... or maybe it's vice versa.
- *
- * NOTE: the allocation quantum is large enough that we know
- * we don't have to reallocate here!
- */
- if (component < 40)
- X = 0;
- else if (component < 80)
- X = 1;
- else
- X = 2;
- Y = component - ( X * 40);
-
- components [0] = X;
- components [1] = Y;
- componentLen = 2;
-
- first_subid = false;
-
- } else {
-
- /*
- * Other components are encoded less exotically. The only
- * potential trouble is the need to grow the array.
- */
- if (componentLen >= components.length) {
- int tmp_components [];
-
- tmp_components = new int [components.length
- + allocationQuantum];
- System.arraycopy (components, 0, tmp_components, 0,
- components.length);
- components = tmp_components;
- }
- components [componentLen++] = component;
- }
- }
-
- /*
- * Final sanity check -- if we didn't use exactly the number of bytes
- * specified, something's quite wrong.
- */
- if (in.available () != bufferEnd) {
- throw new IOException (
- "X509.ObjectIdentifier() -- malformed input data");
- }
- }
+ private void initFromEncoding(DerInputStream in, int bufferEnd)
+ throws IOException {
+
+ /*
+ * Now get the components ("sub IDs") one at a time. We fill a temporary
+ * buffer, resizing it as needed.
+ */
+ int component;
+ boolean first_subid = true;
+
+ for (components = new int[allocationQuantum], componentLen = 0; in.available() > bufferEnd;) {
+ component = getComponent(in);
+
+ if (first_subid) {
+ int X, Y;
+
+ /*
+ * The ISO root has three children (0, 1, 2) and those nodes
+ * aren't allowed to assign IDs larger than 39. These rules are
+ * memorialized by some special casing in the BER encoding of
+ * object IDs ... or maybe it's vice versa.
+ *
+ * NOTE: the allocation quantum is large enough that we know we
+ * don't have to reallocate here!
+ */
+ if (component < 40)
+ X = 0;
+ else if (component < 80)
+ X = 1;
+ else
+ X = 2;
+ Y = component - (X * 40);
+
+ components[0] = X;
+ components[1] = Y;
+ componentLen = 2;
+
+ first_subid = false;
+
+ } else {
+
+ /*
+ * Other components are encoded less exotically. The only
+ * potential trouble is the need to grow the array.
+ */
+ if (componentLen >= components.length) {
+ int tmp_components[];
+
+ tmp_components = new int[components.length
+ + allocationQuantum];
+ System.arraycopy(components, 0, tmp_components, 0,
+ components.length);
+ components = tmp_components;
+ }
+ components[componentLen++] = component;
+ }
+ }
+ /*
+ * Final sanity check -- if we didn't use exactly the number of bytes
+ * specified, something's quite wrong.
+ */
+ if (in.available() != bufferEnd) {
+ throw new IOException(
+ "X509.ObjectIdentifier() -- malformed input data");
+ }
+ }
/*
* n.b. the only public interface is DerOutputStream.putOID()
*/
- void encode (DerOutputStream out) throws IOException
- {
- DerOutputStream bytes = new DerOutputStream ();
- int i;
-
- bytes.write ((components [0] * 40) + components [1]);
- for (i = 2; i < componentLen; i++)
- putComponent (bytes, components [i]);
-
- /*
- * Now that we've constructed the component, encode
- * it in the stream we were given.
- */
- out.write (DerValue.tag_ObjectId, bytes);
+ void encode(DerOutputStream out) throws IOException {
+ DerOutputStream bytes = new DerOutputStream();
+ int i;
+
+ bytes.write((components[0] * 40) + components[1]);
+ for (i = 2; i < componentLen; i++)
+ putComponent(bytes, components[i]);
+
+ /*
+ * Now that we've constructed the component, encode it in the stream we
+ * were given.
+ */
+ out.write(DerValue.tag_ObjectId, bytes);
}
/*
- * Tricky OID component parsing technique ... note that one bit
- * per octet is lost, this returns at most 28 bits of component.
- * Also, notice this parses in big-endian format.
+ * Tricky OID component parsing technique ... note that one bit per octet is
+ * lost, this returns at most 28 bits of component. Also, notice this parses
+ * in big-endian format.
*/
- private static int getComponent (DerInputStream in)
- throws IOException
- {
+ private static int getComponent(DerInputStream in)
+ throws IOException {
int retval, i, tmp;
- for (i = 0, retval = 0; i < 4; i++) {
- retval <<= 7;
- tmp = in.getByte ();
- retval |= (tmp & 0x07f);
- if ((tmp & 0x080) == 0)
- return retval;
- }
+ for (i = 0, retval = 0; i < 4; i++) {
+ retval <<= 7;
+ tmp = in.getByte();
+ retval |= (tmp & 0x07f);
+ if ((tmp & 0x080) == 0)
+ return retval;
+ }
- throw new IOException ("X509.OID, component value too big");
+ throw new IOException("X509.OID, component value too big");
}
/*
- * Reverse of the above routine. Notice it needs to emit in
- * big-endian form, so it buffers the output until it's ready.
- * (Minimum length encoding is a DER requirement.)
+ * Reverse of the above routine. Notice it needs to emit in big-endian form,
+ * so it buffers the output until it's ready. (Minimum length encoding is a
+ * DER requirement.)
*/
- private static void putComponent (DerOutputStream out, int val)
- throws IOException
- {
- int i;
- byte buf [] = new byte [4] ;
-
- for (i = 0; i < 4; i++) {
- buf [i] = (byte) (val & 0x07f);
- val >>>= 7;
- if (val == 0)
- break;
- }
- for ( ; i > 0; --i)
- out.write (buf [i] | 0x080);
- out.write (buf [0]);
+ private static void putComponent(DerOutputStream out, int val)
+ throws IOException {
+ int i;
+ byte buf[] = new byte[4];
+
+ for (i = 0; i < 4; i++) {
+ buf[i] = (byte) (val & 0x07f);
+ val >>>= 7;
+ if (val == 0)
+ break;
+ }
+ for (; i > 0; --i)
+ out.write(buf[i] | 0x080);
+ out.write(buf[0]);
}
// XXX this API should probably facilitate the JDK sort utility
/**
- * Compares this identifier with another, for sorting purposes.
- * An identifier does not precede itself.
- *
+ * Compares this identifier with another, for sorting purposes. An
+ * identifier does not precede itself.
+ *
* @param other identifer that may precede this one.
- * @return true iff <em>other</em> precedes this one
- * in a particular sorting order.
+ * @return true iff <em>other</em> precedes this one in a particular sorting
+ * order.
*/
- public boolean precedes (ObjectIdentifier other)
- {
- int i;
-
- // shorter IDs go first
- if (other == this || componentLen < other.componentLen)
- return false;
- if (other.componentLen < componentLen)
- return true;
-
- // for each component, the lesser component goes first
- for (i = 0; i < componentLen; i++) {
- if (other.components [i] < components [i])
- return true;
- }
-
- // identical IDs don't precede each other
- return false;
+ public boolean precedes(ObjectIdentifier other) {
+ int i;
+
+ // shorter IDs go first
+ if (other == this || componentLen < other.componentLen)
+ return false;
+ if (other.componentLen < componentLen)
+ return true;
+
+ // for each component, the lesser component goes first
+ for (i = 0; i < componentLen; i++) {
+ if (other.components[i] < components[i])
+ return true;
+ }
+
+ // identical IDs don't precede each other
+ return false;
}
- public boolean equals (Object other)
- {
- if (other instanceof ObjectIdentifier)
- return equals ((ObjectIdentifier) other);
- else
- return false;
+ public boolean equals(Object other) {
+ if (other instanceof ObjectIdentifier)
+ return equals((ObjectIdentifier) other);
+ else
+ return false;
}
/**
* Compares this identifier with another, for equality.
- *
+ *
* @return true iff the names are identical.
*/
- public boolean equals (ObjectIdentifier other)
- {
- int i;
-
- if (other == this)
- return true;
- if (componentLen != other.componentLen)
- return false;
- for (i = 0; i < componentLen; i++) {
- if (components [i] != other.components [i])
- return false;
- }
- return true;
+ public boolean equals(ObjectIdentifier other) {
+ int i;
+
+ if (other == this)
+ return true;
+ if (componentLen != other.componentLen)
+ return false;
+ for (i = 0; i < componentLen; i++) {
+ if (components[i] != other.components[i])
+ return false;
+ }
+ return true;
}
public int hashCode() {
- int h=0;
- int oflow=0;
+ int h = 0;
+ int oflow = 0;
- for (int i=0;i<componentLen;i++) {
+ for (int i = 0; i < componentLen; i++) {
oflow = (h & 0xff800000) >> 23;
h <<= 9;
h += components[i];
@@ -359,90 +342,85 @@ class ObjectIdentifier implements Serializable
}
/**
- * Returns a string form of the object ID. The format is the
- * conventional "dot" notation for such IDs, without any
- * user-friendly descriptive strings, since those strings
- * will not be understood everywhere.
+ * Returns a string form of the object ID. The format is the conventional
+ * "dot" notation for such IDs, without any user-friendly descriptive
+ * strings, since those strings will not be understood everywhere.
*/
- public String toString ()
- {
- String retval;
- int i;
-
- for (i = 0, retval = ""; i < componentLen; i++) {
- if (i != 0)
- retval += ".";
- retval += components [i];
- }
- return retval;
+ public String toString() {
+ String retval;
+ int i;
+
+ for (i = 0, retval = ""; i < componentLen; i++) {
+ if (i != 0)
+ retval += ".";
+ retval += components[i];
+ }
+ return retval;
}
/*
- * To simplify, we assume no individual component of an object ID is
- * larger than 32 bits. Then we represent the path from the root as
- * an array that's (usually) only filled at the beginning.
+ * To simplify, we assume no individual component of an object ID is larger
+ * than 32 bits. Then we represent the path from the root as an array that's
+ * (usually) only filled at the beginning.
*/
- private int components []; // path from root
- private int componentLen; // how much is used.
+ private int components[]; // path from root
+ private int componentLen; // how much is used.
- private static final int allocationQuantum = 5; // >= 2
+ private static final int allocationQuantum = 5; // >= 2
/**
- * Netscape Enhancement:
- * This function implements a object identifier factory. It
- * should help reduces in-memory Object Identifier object.
- * This function also provide additional checking on the OID.
- * A valid OID should start with 0, 1, or 2.
- *
- * Notes:
- * This function never returns null. IOException is raised
- * in error conditions.
+ * Netscape Enhancement: This function implements a object identifier
+ * factory. It should help reduces in-memory Object Identifier object. This
+ * function also provide additional checking on the OID. A valid OID should
+ * start with 0, 1, or 2.
+ *
+ * Notes: This function never returns null. IOException is raised in error
+ * conditions.
*/
public static java.util.Hashtable mOIDs = new java.util.Hashtable();
+
public static ObjectIdentifier getObjectIdentifier(String oid)
- throws IOException
- {
- int value;
-
- if (oid == null)
- throw new IOException("empty object identifier");
-
- oid = oid.trim();
-
- ObjectIdentifier thisOID = (ObjectIdentifier)mOIDs.get(oid);
- if (thisOID != null)
- return thisOID;
-
- StringTokenizer token = new StringTokenizer(oid, ".");
- value = new Integer(token.nextToken()).intValue();
- /* First token should be 0, 1, 2 */
- if (value >= 0 && value <= 2) {
- value = new Integer(token.nextToken()).intValue();
- /* Second token should be 0 <= && >= 39 */
- if (value >= 0 && value <= 39) {
- thisOID = new ObjectIdentifier(oid);
- if (thisOID.toString().equals(oid)) {
- mOIDs.put(oid, thisOID);
- return thisOID;
- }
- throw new IOException("invalid oid " + oid);
- } else
- throw new IOException("invalid oid " + oid);
- } else
- throw new IOException("invalid oid " + oid);
+ throws IOException {
+ int value;
+
+ if (oid == null)
+ throw new IOException("empty object identifier");
+
+ oid = oid.trim();
+
+ ObjectIdentifier thisOID = (ObjectIdentifier) mOIDs.get(oid);
+ if (thisOID != null)
+ return thisOID;
+
+ StringTokenizer token = new StringTokenizer(oid, ".");
+ value = new Integer(token.nextToken()).intValue();
+ /* First token should be 0, 1, 2 */
+ if (value >= 0 && value <= 2) {
+ value = new Integer(token.nextToken()).intValue();
+ /* Second token should be 0 <= && >= 39 */
+ if (value >= 0 && value <= 39) {
+ thisOID = new ObjectIdentifier(oid);
+ if (thisOID.toString().equals(oid)) {
+ mOIDs.put(oid, thisOID);
+ return thisOID;
+ }
+ throw new IOException("invalid oid " + oid);
+ } else
+ throw new IOException("invalid oid " + oid);
+ } else
+ throw new IOException("invalid oid " + oid);
}
public static ObjectIdentifier getObjectIdentifier(int values[])
- throws IOException
- {
- String retval;
- int i;
-
- for (i = 0, retval = ""; i < values.length; i++) {
- if (i != 0)
- retval += ".";
- retval += values [i];
- }
- return getObjectIdentifier(retval);
+ throws IOException {
+ String retval;
+ int i;
+
+ for (i = 0, retval = ""; i < values.length; i++) {
+ if (i != 0)
+ retval += ".";
+ retval += values[i];
+ }
+ return getObjectIdentifier(retval);
}
}
diff --git a/pki/base/util/src/netscape/security/util/PrettyPrintFormat.java b/pki/base/util/src/netscape/security/util/PrettyPrintFormat.java
index 94a5d18c..a4ba2bcf 100644
--- a/pki/base/util/src/netscape/security/util/PrettyPrintFormat.java
+++ b/pki/base/util/src/netscape/security/util/PrettyPrintFormat.java
@@ -17,106 +17,103 @@
// --- END COPYRIGHT BLOCK ---
package netscape.security.util;
-
/**
- * This class will display the certificate content in predefined
- * format.
- *
+ * This class will display the certificate content in predefined format.
+ *
* @author Andrew Wnuk
* @version $Revision$, $Date$
*/
public class PrettyPrintFormat {
- /*==========================================================
- * variables
- *==========================================================*/
+ /*
+ * ========================================================== variables
+ * ==========================================================
+ */
private String mSeparator = "";
- private int mIndentSize = 0;
- private int mLineLen = 0;
-
- /*==========================================================
- * constants
- *
- *==========================================================*/
- private final static String spaces=
- " "+
- " "+
- " "+
- " "+
- " ";
-
- /*==========================================================
- * constructors
- *==========================================================*/
-
- public PrettyPrintFormat(String separator)
- {
- mSeparator = separator;
+ private int mIndentSize = 0;
+ private int mLineLen = 0;
+
+ /*
+ * ========================================================== constants
+ *
+ * ==========================================================
+ */
+ private final static String spaces =
+ " " +
+ " " +
+ " " +
+ " " +
+ " ";
+
+ /*
+ * ========================================================== constructors
+ * ==========================================================
+ */
+
+ public PrettyPrintFormat(String separator) {
+ mSeparator = separator;
}
- public PrettyPrintFormat(String separator, int lineLen)
- {
- mSeparator = separator;
- mLineLen = lineLen;
+ public PrettyPrintFormat(String separator, int lineLen) {
+ mSeparator = separator;
+ mLineLen = lineLen;
}
- public PrettyPrintFormat(String separator, int lineLen, int indentSize)
- {
- mSeparator = separator;
- mLineLen = lineLen;
- mIndentSize = indentSize;
+ public PrettyPrintFormat(String separator, int lineLen, int indentSize) {
+ mSeparator = separator;
+ mLineLen = lineLen;
+ mIndentSize = indentSize;
}
- /*==========================================================
- * Private methods
- *==========================================================*/
-
-
- /*==========================================================
- * public methods
- *==========================================================*/
+ /*
+ * ========================================================== Private
+ * methods==========================================================
+ */
+
+ /*
+ * ========================================================== public methods
+ * ==========================================================
+ */
/**
- * Provide white space indention
- * stevep - speed improvements. Factor of 10 improvement
+ * Provide white space indention stevep - speed improvements. Factor of 10
+ * improvement
+ *
* @param numSpace number of white space to be returned
* @return white spaces
*/
- public String indent(int size) {
- return spaces.substring(0,size);
- }
+ public String indent(int size) {
+ return spaces.substring(0, size);
+ }
private static final char[] hexdigits = {
- '0','1','2','3','4','5','6','7','8','9',
- 'A','B','C','D','E','F'
+ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
+ 'A', 'B', 'C', 'D', 'E', 'F'
};
-
/**
- * Convert Byte Array to Hex String Format
- * stevep - speedup by factor of 8
+ * Convert Byte Array to Hex String Format stevep - speedup by factor of 8
+ *
* @param byte array of data to hexify
- * @param indentSize number of spaces to prepend before each line
- * @param lineLen number of bytes to output on each line (0
- means: put everything on one line
- * @param separator the first character of this string will be used as
- the separator between bytes.
+ * @param indentSize number of spaces to prepend before each line
+ * @param lineLen number of bytes to output on each line (0 means: put
+ * everything on one line
+ * @param separator the first character of this string will be used as the
+ * separator between bytes.
* @return string representation
*/
- public String toHexString(byte[] in, int indentSize,
- int lineLen, String separator)
- {
+ public String toHexString(byte[] in, int indentSize,
+ int lineLen, String separator) {
StringBuffer sb = new StringBuffer();
int hexCount = 0;
char c[];
- int j=0;
+ int j = 0;
- if (lineLen ==0) {
- c = new char[in.length*3+1];
- }
- else {
- c = new char[lineLen*3+1];
+ if (lineLen == 0) {
+ c = new char[in.length * 3 + 1];
+ } else {
+ c = new char[lineLen * 3 + 1];
}
char sep = separator.charAt(0);
@@ -125,16 +122,16 @@ public class PrettyPrintFormat {
for (int i = 0; i < in.length; i++) {
if (lineLen > 0 && hexCount == lineLen) {
c[j++] = '\n';
- sb.append(c,0,j);
+ sb.append(c, 0, j);
sb.append(indent(indentSize));
- hexCount =0;
- j=0;
+ hexCount = 0;
+ j = 0;
}
byte x = in[i];
// output hex digits to buffer
c[j++] = hexdigits[(char) ((x >> 4) & 0xf)];
- c[j++] = hexdigits[(char) (x&0xf)];
+ c[j++] = hexdigits[(char) (x & 0xf)];
// if not last char, output separator
if (i != in.length - 1) {
@@ -143,25 +140,24 @@ public class PrettyPrintFormat {
hexCount++;
}
- if (j>0) {
+ if (j > 0) {
c[j++] = '\n';
- sb.append(c,0,j);
+ sb.append(c, 0, j);
}
-// sb.append("\n");
+ // sb.append("\n");
return sb.toString();
}
-
public String toHexString(byte[] in, int indentSize, int lineLen) {
- return toHexString(in,indentSize,lineLen,mSeparator);
+ return toHexString(in, indentSize, lineLen, mSeparator);
}
public String toHexString(byte[] in, int indentSize) {
- return toHexString(in,indentSize,mLineLen);
+ return toHexString(in, indentSize, mLineLen);
}
public String toHexString(byte[] in) {
- return toHexString(in,mIndentSize);
- }
+ return toHexString(in, mIndentSize);
+ }
}
diff --git a/pki/base/util/src/netscape/security/util/PrettyPrintResources.java b/pki/base/util/src/netscape/security/util/PrettyPrintResources.java
index 45b08206..09adc364 100644
--- a/pki/base/util/src/netscape/security/util/PrettyPrintResources.java
+++ b/pki/base/util/src/netscape/security/util/PrettyPrintResources.java
@@ -17,21 +17,19 @@
// --- END COPYRIGHT BLOCK ---
package netscape.security.util;
-
import java.util.ListResourceBundle;
import netscape.security.extensions.NSCertTypeExtension;
import netscape.security.x509.KeyUsageExtension;
-
/**
* Resource Boundle for the Pretty Print
- *
+ *
* @author Jack Pan-Chen
* @version $Revision$, $Date$
*/
-public class PrettyPrintResources extends ListResourceBundle {
+public class PrettyPrintResources extends ListResourceBundle {
/**
* Returns content
@@ -41,11 +39,10 @@ public class PrettyPrintResources extends ListResourceBundle {
}
/**
- * Constants. The suffix represents the number of
- * possible parameters.
+ * Constants. The suffix represents the number of possible parameters.
*/
- //certificate pretty print
+ // certificate pretty print
public final static String TOKEN_CERTIFICATE = "tokenCertificate";
public final static String TOKEN_DATA = "tokenData";
public final static String TOKEN_VERSION = "tokenVersion";
@@ -64,14 +61,14 @@ public class PrettyPrintResources extends ListResourceBundle {
public final static String TOKEN_EXTENSIONS = "tokenExtensions";
public final static String TOKEN_SIGNATURE = "tokenSignature";
- //extension pretty print
+ // extension pretty print
public final static String TOKEN_YES = "tokenYes";
public final static String TOKEN_NO = "tokenNo";
public final static String TOKEN_IDENTIFIER = "tokenIdentifier";
public final static String TOKEN_CRITICAL = "tokenCritical";
public final static String TOKEN_VALUE = "tokenValue";
- //specific extension token
+ // specific extension token
public final static String TOKEN_KEY_TYPE = "tokenKeyType";
public final static String TOKEN_CERT_TYPE = "tokenCertType";
public final static String TOKEN_SKI = "tokenSKI";
@@ -178,126 +175,126 @@ public class PrettyPrintResources extends ListResourceBundle {
public final static String TOKEN_CACHE_NOT_AVAILABLE = "cacheNotAvailable";
public final static String TOKEN_CACHE_IS_EMPTY = "cacheIsEmpty";
- //Tokens should have blank_space as trailer
+ // Tokens should have blank_space as trailer
static final Object[][] contents = {
- {TOKEN_CERTIFICATE, "Certificate: "},
- {TOKEN_DATA, "Data: "},
- {TOKEN_VERSION, "Version: "},
- {TOKEN_SERIAL, "Serial Number: "},
- {TOKEN_SIGALG, "Signature Algorithm: "},
- {TOKEN_ISSUER, "Issuer: "},
- {TOKEN_VALIDITY, "Validity: "},
- {TOKEN_NOT_BEFORE, "Not Before: "},
- {TOKEN_NOT_AFTER, "Not After: "},
- {TOKEN_SUBJECT, "Subject: "},
- {TOKEN_SPKI, "Subject Public Key Info: "},
- {TOKEN_ALGORITHM, "Algorithm: "},
- {TOKEN_PUBLIC_KEY, "Public Key: "},
- {TOKEN_PUBLIC_KEY_MODULUS, "Public Key Modulus: "},
- {TOKEN_PUBLIC_KEY_EXPONENT, "Exponent: "},
- {TOKEN_EXTENSIONS, "Extensions: "},
- {TOKEN_SIGNATURE, "Signature: "},
- {TOKEN_YES, "yes "},
- {TOKEN_NO, "no "},
- {TOKEN_IDENTIFIER, "Identifier: "},
- {TOKEN_CRITICAL, "Critical: "},
- {TOKEN_VALUE, "Value: "},
- {TOKEN_KEY_TYPE, "Key Type "},
- {TOKEN_CERT_TYPE, "Netscape Certificate Type "},
- {TOKEN_SKI, "Subject Key Identifier "},
- {TOKEN_AKI, "Authority Key Identifier "},
- {TOKEN_ACCESS_DESC, "Access Description: "},
- {TOKEN_OCSP_NOCHECK, "OCSP NoCheck: "},
- {TOKEN_EXTENDED_KEY_USAGE, "Extended Key Usage: "},
- {TOKEN_PRIVATE_KEY_USAGE, "Private Key Usage: "},
- {TOKEN_PRESENCE_SERVER, "Presence Server: "},
- {TOKEN_AIA, "Authority Info Access: "},
- {TOKEN_CERT_POLICIES, "Certificate Policies: "},
- {TOKEN_SIA, "Subject Info Access: "},
- {TOKEN_KEY_USAGE, "Key Usage: "},
- {KeyUsageExtension.DIGITAL_SIGNATURE, "Digital Signature "},
- {KeyUsageExtension.NON_REPUDIATION, "Non Repudiation "},
- {KeyUsageExtension.KEY_ENCIPHERMENT, "Key Encipherment "},
- {KeyUsageExtension.DATA_ENCIPHERMENT, "Data Encipherment "},
- {KeyUsageExtension.KEY_AGREEMENT, "Key Agreement "},
- {KeyUsageExtension.KEY_CERTSIGN, "Key CertSign "},
- {KeyUsageExtension.CRL_SIGN, "Crl Sign "},
- {KeyUsageExtension.ENCIPHER_ONLY, "Encipher Only "},
- {KeyUsageExtension.DECIPHER_ONLY, "Decipher Only "},
- {TOKEN_CERT_USAGE, "Certificate Usage: "},
- {NSCertTypeExtension.SSL_CLIENT, "SSL Client "},
- {NSCertTypeExtension.SSL_SERVER, "SSL Server "},
- {NSCertTypeExtension.EMAIL, "Secure Email "},
- {NSCertTypeExtension.OBJECT_SIGNING, "Object Signing "},
- {NSCertTypeExtension.SSL_CA, "SSL CA "},
- {NSCertTypeExtension.EMAIL_CA, "Secure Email CA "},
- {NSCertTypeExtension.OBJECT_SIGNING_CA, "ObjectSigning CA "},
- {TOKEN_KEY_ID, "Key Identifier: "},
- {TOKEN_AUTH_NAME, "Authority Name: "},
- {TOKEN_CRL, "Certificate Revocation List: "},
- {TOKEN_THIS_UPDATE, "This Update: "},
- {TOKEN_NEXT_UPDATE, "Next Update: "},
- {TOKEN_REVOKED_CERTIFICATES, "Revoked Certificates: "},
- {TOKEN_REVOCATION_DATE, "Revocation Date: "},
- {TOKEN_REVOCATION_REASON, "Revocation Reason "},
- {TOKEN_REASON, "Reason: "},
- {TOKEN_BASIC_CONSTRAINTS, "Basic Constraints "},
- {TOKEN_NAME_CONSTRAINTS, "Name Constraints "},
- {TOKEN_NSC_COMMENT, "Netscape Comment "},
- {TOKEN_IS_CA, "Is CA: "},
- {TOKEN_PATH_LEN, "Path Length Constraint: "},
- {TOKEN_PATH_LEN_UNLIMITED, "UNLIMITED"},
- {TOKEN_PATH_LEN_UNDEFINED, "UNDEFINED"},
- {TOKEN_PATH_LEN_INVALID, "INVALID"},
- {TOKEN_CRL_NUMBER, "CRL Number "},
- {TOKEN_NUMBER, "Number: "},
- {TOKEN_DELTA_CRL_INDICATOR, "Delta CRL Indicator "},
- {TOKEN_BASE_CRL_NUMBER, "Base CRL Number: "},
- {TOKEN_CERT_SCOPE_OF_USE, "Certificate Scope of Use "},
- {TOKEN_SCOPE_OF_USE, "Scope of Use: "},
- {TOKEN_PORT, "Port: "},
- {TOKEN_ISSUER_ALT_NAME, "Issuer Alternative Name "},
- {TOKEN_ISSUER_NAMES, "Issuer Names: "},
- {TOKEN_SUBJECT_ALT_NAME, "Subject Alternative Name "},
- {TOKEN_DECODING_ERROR, "Decoding Error"},
- {TOKEN_FRESHEST_CRL_EXT, "Freshest CRL "},
- {TOKEN_INHIBIT_ANY_POLICY_EXT, "Inhibit Any-Policy "},
- {TOKEN_SKIP_CERTS, "Skip Certs: "},
- {TOKEN_CRL_DP_EXT, "CRL Distribution Points "},
- {TOKEN_CRLDP_NUMPOINTS, "Number of Points: "},
- {TOKEN_CRLDP_POINTN, "Point "},
- {TOKEN_CRLDP_DISTPOINT, "Distribution Point: "},
- {TOKEN_CRLDP_REASONS, "Reason Flags: "},
- {TOKEN_CRLDP_CRLISSUER, "CRL Issuer: "},
- {TOKEN_ISSUING_DIST_POINT, "Issuing Distribution Point "},
- {TOKEN_DIST_POINT_NAME, "Distribution Point: "},
- {TOKEN_FULL_NAME, "Full Name: "},
- {TOKEN_RELATIVE_NAME, "Name Relative To CRL Issuer: "},
- {TOKEN_ONLY_USER_CERTS, "Only Contains User Certificates: "},
- {TOKEN_ONLY_CA_CERTS, "Only Contains CA Certificates: "},
- {TOKEN_ONLY_SOME_REASONS, "Only Some Reasons: "},
- {TOKEN_INDIRECT_CRL, "Indirect CRL: "},
- {TOKEN_INVALIDITY_DATE, "Invalidity Date "},
- {TOKEN_DATE_OF_INVALIDITY, "Invalidity Date: "},
- {TOKEN_CERTIFICATE_ISSUER, "Certificate Issuer "},
- {TOKEN_HOLD_INSTRUCTION, "Hold Instruction Code "},
- {TOKEN_HOLD_INSTRUCTION_CODE, "Hold Instruction Code: "},
- {TOKEN_POLICY_CONSTRAINTS, "Policy Constraints "},
- {TOKEN_INHIBIT_POLICY_MAPPING, "Inhibit Policy Mapping: "},
- {TOKEN_REQUIRE_EXPLICIT_POLICY, "Require Explicit Policy: "},
- {TOKEN_POLICY_MAPPINGS, "Policy Mappings "},
- {TOKEN_MAPPINGS, "Mappings: "},
- {TOKEN_MAP, "Map "},
- {TOKEN_ISSUER_DOMAIN_POLICY, "Issuer Domain Policy: "},
- {TOKEN_SUBJECT_DOMAIN_POLICY, "Subject Domain Policy: "},
- {TOKEN_SUBJECT_DIR_ATTR, "Subject Directory Attributes "},
- {TOKEN_ATTRIBUTES, "Attributes:" },
- {TOKEN_ATTRIBUTE, "Attribute "},
- {TOKEN_VALUES, "Values: "},
- {TOKEN_NOT_SET, "not set"},
- {TOKEN_NONE, "none"},
- {TOKEN_CACHE_NOT_AVAILABLE, "CRL cache is not available. "},
- {TOKEN_CACHE_IS_EMPTY, "CRL cache is empty. "},
+ { TOKEN_CERTIFICATE, "Certificate: " },
+ { TOKEN_DATA, "Data: " },
+ { TOKEN_VERSION, "Version: " },
+ { TOKEN_SERIAL, "Serial Number: " },
+ { TOKEN_SIGALG, "Signature Algorithm: " },
+ { TOKEN_ISSUER, "Issuer: " },
+ { TOKEN_VALIDITY, "Validity: " },
+ { TOKEN_NOT_BEFORE, "Not Before: " },
+ { TOKEN_NOT_AFTER, "Not After: " },
+ { TOKEN_SUBJECT, "Subject: " },
+ { TOKEN_SPKI, "Subject Public Key Info: " },
+ { TOKEN_ALGORITHM, "Algorithm: " },
+ { TOKEN_PUBLIC_KEY, "Public Key: " },
+ { TOKEN_PUBLIC_KEY_MODULUS, "Public Key Modulus: " },
+ { TOKEN_PUBLIC_KEY_EXPONENT, "Exponent: " },
+ { TOKEN_EXTENSIONS, "Extensions: " },
+ { TOKEN_SIGNATURE, "Signature: " },
+ { TOKEN_YES, "yes " },
+ { TOKEN_NO, "no " },
+ { TOKEN_IDENTIFIER, "Identifier: " },
+ { TOKEN_CRITICAL, "Critical: " },
+ { TOKEN_VALUE, "Value: " },
+ { TOKEN_KEY_TYPE, "Key Type " },
+ { TOKEN_CERT_TYPE, "Netscape Certificate Type " },
+ { TOKEN_SKI, "Subject Key Identifier " },
+ { TOKEN_AKI, "Authority Key Identifier " },
+ { TOKEN_ACCESS_DESC, "Access Description: " },
+ { TOKEN_OCSP_NOCHECK, "OCSP NoCheck: " },
+ { TOKEN_EXTENDED_KEY_USAGE, "Extended Key Usage: " },
+ { TOKEN_PRIVATE_KEY_USAGE, "Private Key Usage: " },
+ { TOKEN_PRESENCE_SERVER, "Presence Server: " },
+ { TOKEN_AIA, "Authority Info Access: " },
+ { TOKEN_CERT_POLICIES, "Certificate Policies: " },
+ { TOKEN_SIA, "Subject Info Access: " },
+ { TOKEN_KEY_USAGE, "Key Usage: " },
+ { KeyUsageExtension.DIGITAL_SIGNATURE, "Digital Signature " },
+ { KeyUsageExtension.NON_REPUDIATION, "Non Repudiation " },
+ { KeyUsageExtension.KEY_ENCIPHERMENT, "Key Encipherment " },
+ { KeyUsageExtension.DATA_ENCIPHERMENT, "Data Encipherment " },
+ { KeyUsageExtension.KEY_AGREEMENT, "Key Agreement " },
+ { KeyUsageExtension.KEY_CERTSIGN, "Key CertSign " },
+ { KeyUsageExtension.CRL_SIGN, "Crl Sign " },
+ { KeyUsageExtension.ENCIPHER_ONLY, "Encipher Only " },
+ { KeyUsageExtension.DECIPHER_ONLY, "Decipher Only " },
+ { TOKEN_CERT_USAGE, "Certificate Usage: " },
+ { NSCertTypeExtension.SSL_CLIENT, "SSL Client " },
+ { NSCertTypeExtension.SSL_SERVER, "SSL Server " },
+ { NSCertTypeExtension.EMAIL, "Secure Email " },
+ { NSCertTypeExtension.OBJECT_SIGNING, "Object Signing " },
+ { NSCertTypeExtension.SSL_CA, "SSL CA " },
+ { NSCertTypeExtension.EMAIL_CA, "Secure Email CA " },
+ { NSCertTypeExtension.OBJECT_SIGNING_CA, "ObjectSigning CA " },
+ { TOKEN_KEY_ID, "Key Identifier: " },
+ { TOKEN_AUTH_NAME, "Authority Name: " },
+ { TOKEN_CRL, "Certificate Revocation List: " },
+ { TOKEN_THIS_UPDATE, "This Update: " },
+ { TOKEN_NEXT_UPDATE, "Next Update: " },
+ { TOKEN_REVOKED_CERTIFICATES, "Revoked Certificates: " },
+ { TOKEN_REVOCATION_DATE, "Revocation Date: " },
+ { TOKEN_REVOCATION_REASON, "Revocation Reason " },
+ { TOKEN_REASON, "Reason: " },
+ { TOKEN_BASIC_CONSTRAINTS, "Basic Constraints " },
+ { TOKEN_NAME_CONSTRAINTS, "Name Constraints " },
+ { TOKEN_NSC_COMMENT, "Netscape Comment " },
+ { TOKEN_IS_CA, "Is CA: " },
+ { TOKEN_PATH_LEN, "Path Length Constraint: " },
+ { TOKEN_PATH_LEN_UNLIMITED, "UNLIMITED" },
+ { TOKEN_PATH_LEN_UNDEFINED, "UNDEFINED" },
+ { TOKEN_PATH_LEN_INVALID, "INVALID" },
+ { TOKEN_CRL_NUMBER, "CRL Number " },
+ { TOKEN_NUMBER, "Number: " },
+ { TOKEN_DELTA_CRL_INDICATOR, "Delta CRL Indicator " },
+ { TOKEN_BASE_CRL_NUMBER, "Base CRL Number: " },
+ { TOKEN_CERT_SCOPE_OF_USE, "Certificate Scope of Use " },
+ { TOKEN_SCOPE_OF_USE, "Scope of Use: " },
+ { TOKEN_PORT, "Port: " },
+ { TOKEN_ISSUER_ALT_NAME, "Issuer Alternative Name " },
+ { TOKEN_ISSUER_NAMES, "Issuer Names: " },
+ { TOKEN_SUBJECT_ALT_NAME, "Subject Alternative Name " },
+ { TOKEN_DECODING_ERROR, "Decoding Error" },
+ { TOKEN_FRESHEST_CRL_EXT, "Freshest CRL " },
+ { TOKEN_INHIBIT_ANY_POLICY_EXT, "Inhibit Any-Policy " },
+ { TOKEN_SKIP_CERTS, "Skip Certs: " },
+ { TOKEN_CRL_DP_EXT, "CRL Distribution Points " },
+ { TOKEN_CRLDP_NUMPOINTS, "Number of Points: " },
+ { TOKEN_CRLDP_POINTN, "Point " },
+ { TOKEN_CRLDP_DISTPOINT, "Distribution Point: " },
+ { TOKEN_CRLDP_REASONS, "Reason Flags: " },
+ { TOKEN_CRLDP_CRLISSUER, "CRL Issuer: " },
+ { TOKEN_ISSUING_DIST_POINT, "Issuing Distribution Point " },
+ { TOKEN_DIST_POINT_NAME, "Distribution Point: " },
+ { TOKEN_FULL_NAME, "Full Name: " },
+ { TOKEN_RELATIVE_NAME, "Name Relative To CRL Issuer: " },
+ { TOKEN_ONLY_USER_CERTS, "Only Contains User Certificates: " },
+ { TOKEN_ONLY_CA_CERTS, "Only Contains CA Certificates: " },
+ { TOKEN_ONLY_SOME_REASONS, "Only Some Reasons: " },
+ { TOKEN_INDIRECT_CRL, "Indirect CRL: " },
+ { TOKEN_INVALIDITY_DATE, "Invalidity Date " },
+ { TOKEN_DATE_OF_INVALIDITY, "Invalidity Date: " },
+ { TOKEN_CERTIFICATE_ISSUER, "Certificate Issuer " },
+ { TOKEN_HOLD_INSTRUCTION, "Hold Instruction Code " },
+ { TOKEN_HOLD_INSTRUCTION_CODE, "Hold Instruction Code: " },
+ { TOKEN_POLICY_CONSTRAINTS, "Policy Constraints " },
+ { TOKEN_INHIBIT_POLICY_MAPPING, "Inhibit Policy Mapping: " },
+ { TOKEN_REQUIRE_EXPLICIT_POLICY, "Require Explicit Policy: " },
+ { TOKEN_POLICY_MAPPINGS, "Policy Mappings " },
+ { TOKEN_MAPPINGS, "Mappings: " },
+ { TOKEN_MAP, "Map " },
+ { TOKEN_ISSUER_DOMAIN_POLICY, "Issuer Domain Policy: " },
+ { TOKEN_SUBJECT_DOMAIN_POLICY, "Subject Domain Policy: " },
+ { TOKEN_SUBJECT_DIR_ATTR, "Subject Directory Attributes " },
+ { TOKEN_ATTRIBUTES, "Attributes:" },
+ { TOKEN_ATTRIBUTE, "Attribute " },
+ { TOKEN_VALUES, "Values: " },
+ { TOKEN_NOT_SET, "not set" },
+ { TOKEN_NONE, "none" },
+ { TOKEN_CACHE_NOT_AVAILABLE, "CRL cache is not available. " },
+ { TOKEN_CACHE_IS_EMPTY, "CRL cache is empty. " },
};
}
diff --git a/pki/base/util/src/netscape/security/util/PubKeyPrettyPrint.java b/pki/base/util/src/netscape/security/util/PubKeyPrettyPrint.java
index 669e4c22..660d0036 100644
--- a/pki/base/util/src/netscape/security/util/PubKeyPrettyPrint.java
+++ b/pki/base/util/src/netscape/security/util/PubKeyPrettyPrint.java
@@ -17,7 +17,6 @@
// --- END COPYRIGHT BLOCK ---
package netscape.security.util;
-
import java.security.PublicKey;
import java.util.Locale;
import java.util.ResourceBundle;
@@ -25,42 +24,43 @@ import java.util.ResourceBundle;
import netscape.security.provider.RSAPublicKey;
import netscape.security.x509.X509Key;
-
/**
- * This class will display the certificate content in predefined
- * format.
- *
+ * This class will display the certificate content in predefined format.
+ *
* @author Jack Pan-Chen
* @author Andrew Wnuk
* @version $Revision$, $Date$
*/
public class PubKeyPrettyPrint {
- /*==========================================================
- * variables
- *==========================================================*/
+ /*
+ * ========================================================== variables
+ * ==========================================================
+ */
private X509Key mX509Key = null;
private PrettyPrintFormat pp = null;
- /*==========================================================
- * constructors
- *==========================================================*/
+ /*
+ * ========================================================== constructors
+ * ==========================================================
+ */
public PubKeyPrettyPrint(PublicKey key) {
if (key instanceof X509Key)
mX509Key = (X509Key) key;
-
+
pp = new PrettyPrintFormat(":");
}
- /*==========================================================
- * public methods
- *==========================================================*/
+ /*
+ * ========================================================== public methods
+ * ==========================================================
+ */
/**
- * This method return string representation of the certificate
- * in predefined format using specified client local. I18N Support.
- *
+ * This method return string representation of the certificate in predefined
+ * format using specified client local. I18N Support.
+ *
* @param clientLocale Locale to be used for localization
* @return string representation of the certificate
*/
@@ -71,11 +71,10 @@ public class PubKeyPrettyPrint {
else
return null;
}
-
- public String X509toString(Locale clientLocale, int indentSize, int lineLen) {
+ public String X509toString(Locale clientLocale, int indentSize, int lineLen) {
- //get I18N resources
+ // get I18N resources
ResourceBundle resource = ResourceBundle.getBundle(
PrettyPrintResources.class.getName());
@@ -84,11 +83,11 @@ public class PubKeyPrettyPrint {
try {
String alg = mX509Key.getAlgorithm();
- //XXX I18N Algorithm Name ?
+ // XXX I18N Algorithm Name ?
sb.append(pp.indent(indentSize) + resource.getString(
PrettyPrintResources.TOKEN_ALGORITHM) +
- alg + " - " +
- mX509Key.getAlgorithmId().getOID().toString() + "\n");
+ alg + " - " +
+ mX509Key.getAlgorithmId().getOID().toString() + "\n");
if (alg.equals("RSA")) {
@@ -98,12 +97,12 @@ public class PubKeyPrettyPrint {
PrettyPrintResources.TOKEN_PUBLIC_KEY) + "\n");
sb.append(pp.indent(indentSize + 4) + resource.getString(
PrettyPrintResources.TOKEN_PUBLIC_KEY_EXPONENT) +
- rsakey.getPublicExponent().toInt() + "\n");
+ rsakey.getPublicExponent().toInt() + "\n");
sb.append(pp.indent(indentSize + 4) + resource.getString(
PrettyPrintResources.TOKEN_PUBLIC_KEY_MODULUS) +
- "(" + rsakey.getKeySize() + " bits) :\n");
+ "(" + rsakey.getKeySize() + " bits) :\n");
sb.append(pp.toHexString(
- rsakey.getModulus().toByteArray(),
+ rsakey.getModulus().toByteArray(),
indentSize + 8, lineLen));
} else {
diff --git a/pki/base/util/src/netscape/security/x509/ACertAttrSet.java b/pki/base/util/src/netscape/security/x509/ACertAttrSet.java
index 098a5f2d..cac30ffb 100755
--- a/pki/base/util/src/netscape/security/x509/ACertAttrSet.java
+++ b/pki/base/util/src/netscape/security/x509/ACertAttrSet.java
@@ -28,60 +28,60 @@ import netscape.security.util.DerValue;
/**
* A plain certattr set used by pkcs10 to parse an unknown attribute.
+ *
* @author Lily Hsiao
*/
public class ACertAttrSet implements CertAttrSet {
- protected DerValue mDerValue = null;
+ protected DerValue mDerValue = null;
- public ACertAttrSet(DerValue derValue) throws IOException {
- mDerValue = derValue;
- }
+ public ACertAttrSet(DerValue derValue) throws IOException {
+ mDerValue = derValue;
+ }
- public DerValue getDerValue() {
- return mDerValue;
- }
+ public DerValue getDerValue() {
+ return mDerValue;
+ }
/**
* Returns a short string describing this certificate attribute.
- *
- * @return value of this certificate attribute in
- * printable form.
+ *
+ * @return value of this certificate attribute in printable form.
*/
public String toString() {
- return "ACertAttrSet value "+ (mDerValue == null ? "null" : "not null");
- }
+ return "ACertAttrSet value " + (mDerValue == null ? "null" : "not null");
+ }
/**
- * Encodes the attribute to the output stream in a format
- * that can be parsed by the <code>decode</code> method.
- *
+ * Encodes the attribute to the output stream in a format that can be parsed
+ * by the <code>decode</code> method.
+ *
* @param out the OutputStream to encode the attribute to.
*
* @exception CertificateException on encoding or validity errors.
* @exception IOException on other errors.
*/
public void encode(OutputStream out)
- throws CertificateException, IOException {
- mDerValue.encode((DerOutputStream)out);
- }
+ throws CertificateException, IOException {
+ mDerValue.encode((DerOutputStream) out);
+ }
/**
* Decodes the attribute in the input stream.
- *
+ *
* @param in the InputStream to read the encoded attribute from.
*
* @exception CertificateException on decoding or validity errors.
* @exception IOException on other errors.
*/
public void decode(InputStream in)
- throws CertificateException, IOException {
- throw new IOException("not supported");
- }
+ throws CertificateException, IOException {
+ throw new IOException("not supported");
+ }
/**
* Sets an attribute value within this CertAttrSet.
- *
+ *
* @param name the name of the attribute (e.g. "x509.info.key")
* @param obj the attribute object.
*
@@ -89,35 +89,35 @@ public class ACertAttrSet implements CertAttrSet {
* @exception IOException on other errors.
*/
public void set(String name, Object obj)
- throws CertificateException, IOException {
- throw new IOException("not supported");
- }
+ throws CertificateException, IOException {
+ throw new IOException("not supported");
+ }
/**
* Gets an attribute value for this CertAttrSet.
- *
+ *
* @param name the name of the attribute to return.
*
* @exception CertificateException on attribute handling errors.
* @exception IOException on other errors.
*/
public Object get(String name)
- throws CertificateException, IOException {
- throw new IOException("not supported");
- }
+ throws CertificateException, IOException {
+ throw new IOException("not supported");
+ }
/**
* Deletes an attribute value from this CertAttrSet.
- *
+ *
* @param name the name of the attribute to delete.
*
* @exception CertificateException on attribute handling errors.
* @exception IOException on other errors.
*/
public void delete(String name)
- throws CertificateException, IOException {
- throw new IOException("not supported");
- }
+ throws CertificateException, IOException {
+ throw new IOException("not supported");
+ }
/**
* Returns an enumeration of the names of the attributes existing within
@@ -126,15 +126,15 @@ public class ACertAttrSet implements CertAttrSet {
* @return an enumeration of the attribute names.
*/
public Enumeration<String> getAttributeNames() {
- return null;
- }
-
+ return null;
+ }
+
/**
* Returns the name (identifier) of this CertAttrSet.
*
* @return the name of this CertAttrSet.
*/
public String getName() {
- return "Generic Extension";
- }
+ return "Generic Extension";
+ }
}
diff --git a/pki/base/util/src/netscape/security/x509/AVA.java b/pki/base/util/src/netscape/security/x509/AVA.java
index 0614f41c..db5b1386 100644
--- a/pki/base/util/src/netscape/security/x509/AVA.java
+++ b/pki/base/util/src/netscape/security/x509/AVA.java
@@ -28,282 +28,272 @@ import netscape.security.util.DerValue;
import netscape.security.util.ObjectIdentifier;
import sun.io.ByteToCharConverter;
-
/**
- * X.500 Attribute-Value-Assertion (AVA): an attribute, as identified by
- * some attribute ID, has some particular value. Values are as a rule ASN.1
- * printable strings. A conventional set of type IDs is recognized when
- * parsing (and generating) RFC 1779 syntax strings.
- *
- * <P>AVAs are components of X.500 relative names. Think of them as being
- * individual fields of a database record. The attribute ID is how you
- * identify the field, and the value is part of a particular record.
- *
+ * X.500 Attribute-Value-Assertion (AVA): an attribute, as identified by some
+ * attribute ID, has some particular value. Values are as a rule ASN.1 printable
+ * strings. A conventional set of type IDs is recognized when parsing (and
+ * generating) RFC 1779 syntax strings.
+ *
+ * <P>
+ * AVAs are components of X.500 relative names. Think of them as being
+ * individual fields of a database record. The attribute ID is how you identify
+ * the field, and the value is part of a particular record.
+ *
* @see X500Name
* @see RDN
* @see LdapDNStrConverter
- *
+ *
* @version 1.14
- *
+ *
* @author David Brownell
* @author Amit Kapoor
* @author Hemma Prafullchandra
*/
// public ... when RDN is public and X.500Names can be
// constructed using RDNs, and all three classes are cleaner
-public final class AVA implements DerEncoder
-{
- ObjectIdentifier oid;
- DerValue value;
+public final class AVA implements DerEncoder {
+ ObjectIdentifier oid;
+ DerValue value;
- /**
- * Constructs an AVA from a Ldap DN string with one AVA component
- * using the global default LdapDNStrConverter.
+ /**
+ * Constructs an AVA from a Ldap DN string with one AVA component using the
+ * global default LdapDNStrConverter.
+ *
* @see LdapDNStrConverter
* @param avaString a Ldap DN string with one AVA component.
*/
public AVA(String avaString)
- throws IOException
- {
- AVA ava;
- ava = LdapDNStrConverter.getDefault().parseAVA(avaString);
- oid = ava.getOid();
- value = ava.getValue();
+ throws IOException {
+ AVA ava;
+ ava = LdapDNStrConverter.getDefault().parseAVA(avaString);
+ oid = ava.getOid();
+ value = ava.getValue();
}
/**
* Like AVA(String) with a DER encoding order given for Directory Strings.
*/
public AVA(String avaString, byte[] tags)
- throws IOException
- {
- AVA ava;
- ava = LdapDNStrConverter.getDefault().parseAVA(avaString, tags);
- oid = ava.getOid();
- value = ava.getValue();
+ throws IOException {
+ AVA ava;
+ ava = LdapDNStrConverter.getDefault().parseAVA(avaString, tags);
+ oid = ava.getOid();
+ value = ava.getValue();
}
- /**
- * Constructs an AVA from a Ldap DN string containing one AVA
- * component using the specified LdapDNStrConverter.
+ /**
+ * Constructs an AVA from a Ldap DN string containing one AVA component
+ * using the specified LdapDNStrConverter.
+ *
* @see LdapDNStrConverter
* @param avaString a Ldap DN string containing one AVA.
- * @param ldapDNStrConverter a LdapDNStrConverter
+ * @param ldapDNStrConverter a LdapDNStrConverter
*/
public AVA(String avaString, LdapDNStrConverter ldapDNStrConverter)
- throws IOException
- {
- AVA ava;
- ava = ldapDNStrConverter.parseAVA(avaString);
- oid = ava.getOid();
- value = ava.getValue();
+ throws IOException {
+ AVA ava;
+ ava = ldapDNStrConverter.parseAVA(avaString);
+ oid = ava.getOid();
+ value = ava.getValue();
}
- /**
+ /**
* Constructs an AVA from an OID and DerValue.
+ *
* @param type an ObjectIdentifier
* @param val a DerValue
*/
public AVA(ObjectIdentifier type, DerValue val)
- throws IOException
- {
- oid = type;
- value = val;
+ throws IOException {
+ oid = type;
+ value = val;
}
/**
- * Constructs an AVA from an input stream of UTF8 bytes that form
- * a Ldap DN string. Then parse the Ldap DN string using the global
- * default LdapDNStrConverter.
- * <br>
- * Parses an RFC 1779 style AVA string: CN=fee fie foe fum
- * or perhaps with quotes. Not all defined AVA tags are supported;
- * of current note are X.400 related ones (PRMD, ADMD, etc).
- *
- * This terminates at unescaped AVA separators ("+") or RDN
- * separators (",", ";"), or DN terminators (">"), and removes
- * cosmetic whitespace at the end of values.
+ * Constructs an AVA from an input stream of UTF8 bytes that form a Ldap DN
+ * string. Then parse the Ldap DN string using the global default
+ * LdapDNStrConverter. <br>
+ * Parses an RFC 1779 style AVA string: CN=fee fie foe fum or perhaps with
+ * quotes. Not all defined AVA tags are supported; of current note are X.400
+ * related ones (PRMD, ADMD, etc).
+ *
+ * This terminates at unescaped AVA separators ("+") or RDN separators (",",
+ * ";"), or DN terminators (">"), and removes cosmetic whitespace at the end
+ * of values.
*
* @see LdapDNStrConverter
* @param in the input stream.
*/
- public AVA (InputStream in) throws IOException
- {
- StringBuffer temp = new StringBuffer ();
- AVA a;
- byte[] buf = new byte[in.available()];
- char[] converted_chars;
- ByteToCharConverter bcc;
+ public AVA(InputStream in) throws IOException {
+ StringBuffer temp = new StringBuffer();
+ AVA a;
+ byte[] buf = new byte[in.available()];
+ char[] converted_chars;
+ ByteToCharConverter bcc;
- // convert from UTF8 bytes to java string then parse it.
- in.read(buf);
- try {
- bcc = ByteToCharConverter.getConverter("UTF8");
- }
- catch (java.io.UnsupportedEncodingException e) {
- throw new IOException("UTF8 encoding not supported");
- }
- converted_chars = bcc.convertAll(buf);
- temp.append(converted_chars);
+ // convert from UTF8 bytes to java string then parse it.
+ in.read(buf);
+ try {
+ bcc = ByteToCharConverter.getConverter("UTF8");
+ } catch (java.io.UnsupportedEncodingException e) {
+ throw new IOException("UTF8 encoding not supported");
+ }
+ converted_chars = bcc.convertAll(buf);
+ temp.append(converted_chars);
- a = LdapDNStrConverter.getDefault().parseAVA(temp.toString());
- oid = a.getOid();
- value = a.getValue();
+ a = LdapDNStrConverter.getDefault().parseAVA(temp.toString());
+ oid = a.getOid();
+ value = a.getValue();
}
/**
* Constructs an AVA from a Der Input Stream.
+ *
* @param in the Der Input Stream.
*/
- public AVA(DerInputStream in) throws IOException
- {
- DerValue assertion = in.getDerValue ();
+ public AVA(DerInputStream in) throws IOException {
+ DerValue assertion = in.getDerValue();
- /*
- * Individual attribute value assertions are SEQUENCE of two values.
- * That'd be a "struct" outside of ASN.1.
- */
- if (assertion.tag != DerValue.tag_Sequence)
- throw new CertParseError ("X500 AVA, not a sequence");
+ /*
+ * Individual attribute value assertions are SEQUENCE of two values.
+ * That'd be a "struct" outside of ASN.1.
+ */
+ if (assertion.tag != DerValue.tag_Sequence)
+ throw new CertParseError("X500 AVA, not a sequence");
ObjectIdentifier o = assertion.data.getOID();
oid = X500NameAttrMap.getDefault().getOid(o);
if (oid == null) {
- // NSCP #329837
- // if this OID is not recongized in our map (table),
- // it is fine. we just store it as regular OID.
- oid = o;
+ // NSCP #329837
+ // if this OID is not recongized in our map (table),
+ // it is fine. we just store it as regular OID.
+ oid = o;
}
- value = assertion.data.getDerValue ();
+ value = assertion.data.getDerValue();
- if (assertion.data.available () != 0)
- throw new CertParseError ("AVA, extra bytes = "
- + assertion.data.available ());
+ if (assertion.data.available() != 0)
+ throw new CertParseError("AVA, extra bytes = "
+ + assertion.data.available());
}
// other public methods.
- /**
+ /**
* Returns true if another AVA has the same OID and DerValue.
+ *
* @param other the other AVA.
* @return ture iff other AVA has same oid and value.
*/
- public boolean equals (AVA other)
- {
- return oid.equals (other.oid) && value.equals (other.value);
+ public boolean equals(AVA other) {
+ return oid.equals(other.oid) && value.equals(other.value);
}
- /**
- * Compares the AVA with an Object, returns true if the object is
- * an AVA and has the same OID and value.
+ /**
+ * Compares the AVA with an Object, returns true if the object is an AVA and
+ * has the same OID and value.
+ *
* @param other the other object.
* @return true iff other object is an AVA and has same oid and value.
*/
- public boolean equals (Object other)
- {
- if (other instanceof AVA)
- return equals ((AVA)other);
- else
- return false;
+ public boolean equals(Object other) {
+ if (other instanceof AVA)
+ return equals((AVA) other);
+ else
+ return false;
}
/**
- * Encodes the AVA to a Der output stream.
- * AVAs are encoded as a SEQUENCE of two elements.
+ * Encodes the AVA to a Der output stream. AVAs are encoded as a SEQUENCE of
+ * two elements.
+ *
* @param out The Der output stream.
*/
- public void encode (DerOutputStream out) throws IOException
- {
- derEncode(out);
+ public void encode(DerOutputStream out) throws IOException {
+ derEncode(out);
}
-
- /**
- * DER encode this object onto an output stream.
- * Implements the <code>DerEncoder</code> interface.
- *
- * @param out
- * the output stream on which to write the DER encoding.
- *
+
+ /**
+ * DER encode this object onto an output stream. Implements the
+ * <code>DerEncoder</code> interface.
+ *
+ * @param out the output stream on which to write the DER encoding.
+ *
* @exception IOException on encoding error.
*/
- public void derEncode (OutputStream out) throws IOException
- {
- DerOutputStream tmp = new DerOutputStream ();
- DerOutputStream tmp2 = new DerOutputStream ();
+ public void derEncode(OutputStream out) throws IOException {
+ DerOutputStream tmp = new DerOutputStream();
+ DerOutputStream tmp2 = new DerOutputStream();
- tmp.putOID (oid);
- value.encode (tmp);
- tmp2.write (DerValue.tag_Sequence, tmp);
- out.write(tmp2.toByteArray());
+ tmp.putOID(oid);
+ value.encode(tmp);
+ tmp2.write(DerValue.tag_Sequence, tmp);
+ out.write(tmp2.toByteArray());
}
/**
- * Returns a Ldap DN string with one AVA component using
- * the global default LdapDNStrConverter.
- * @return a Ldap DN string
+ * Returns a Ldap DN string with one AVA component using the global default
+ * LdapDNStrConverter.
+ *
+ * @return a Ldap DN string
* @exception IOException if an error occurs during conversion.
* @see LdapDNStrConverter
*/
public String toLdapDNString()
- throws IOException
- {
- LdapDNStrConverter v = LdapDNStrConverter.getDefault();
- return v.encodeAVA(this);
+ throws IOException {
+ LdapDNStrConverter v = LdapDNStrConverter.getDefault();
+ return v.encodeAVA(this);
}
/**
- * Returns a Ldap DN string with one AVA component using the specified
+ * Returns a Ldap DN string with one AVA component using the specified
* LdapDNStrConverter.
- * @return a Ldap DN string
- * @param ldapDNStrConverter a Ldap DN String Converter
+ *
+ * @return a Ldap DN string
+ * @param ldapDNStrConverter a Ldap DN String Converter
* @exception IOException if an error occurs during the conversion.
* @see LdapDNStrConverter
*/
public String toLdapDNString(LdapDNStrConverter ldapDNStrConverter)
- throws IOException
- {
- return ldapDNStrConverter.encodeAVA(this);
+ throws IOException {
+ return ldapDNStrConverter.encodeAVA(this);
}
/**
- * Returns a Ldap DN string with the AVA component using the global
- * default LdapDNStrConverter, or null if an error occurs in conversion.
- * @return a Ldap DN string containing the AVA, or null if an
- * error occurs in the conversion.
- */
- public String toString()
- {
- String s;
- try {
- // NOTE that a LdapDNString is returned here to match the
- // original source from sun. Could also return the raw value
- // (before Ldap escaping) here.
- s = toLdapDNString();
- }
- catch (IOException e) {
- return null;
- }
- return s;
+ * Returns a Ldap DN string with the AVA component using the global default
+ * LdapDNStrConverter, or null if an error occurs in conversion.
+ *
+ * @return a Ldap DN string containing the AVA, or null if an error occurs
+ * in the conversion.
+ */
+ public String toString() {
+ String s;
+ try {
+ // NOTE that a LdapDNString is returned here to match the
+ // original source from sun. Could also return the raw value
+ // (before Ldap escaping) here.
+ s = toLdapDNString();
+ } catch (IOException e) {
+ return null;
+ }
+ return s;
}
- /**
+ /**
* Returns the OID in the AVA.
+ *
* @return the ObjectIdentifier in this AVA.
*/
- public ObjectIdentifier getOid()
- {
- return oid;
+ public ObjectIdentifier getOid() {
+ return oid;
}
- /**
+ /**
* Returns the value in this AVA as a DerValue
+ *
* @return attribute value in this AVA.
*/
- public DerValue getValue()
- {
- return value;
+ public DerValue getValue() {
+ return value;
}
}
-
-
diff --git a/pki/base/util/src/netscape/security/x509/AVAValueConverter.java b/pki/base/util/src/netscape/security/x509/AVAValueConverter.java
index 87c386f1..4d12dbab 100644
--- a/pki/base/util/src/netscape/security/x509/AVAValueConverter.java
+++ b/pki/base/util/src/netscape/security/x509/AVAValueConverter.java
@@ -22,68 +22,66 @@ import java.io.IOException;
import netscape.security.util.DerValue;
/**
- * Interface for classes that convert a attribute value string to a
- * DER encoded ASN.1 value and vice versa.
- * The converters are associated with attribute types, such as
- * directory string, ia5string, etc.
+ * Interface for classes that convert a attribute value string to a DER encoded
+ * ASN.1 value and vice versa. The converters are associated with attribute
+ * types, such as directory string, ia5string, etc.
+ *
+ * <P>
+ * For example, to convert a string, such as an organization name for the "O"
+ * attribute to a DerValue, the "O" attribute is mapped to the DirStrConverter
+ * which is used to convert the organization name to a DER encoded Directory
+ * String which is a DerValue of a ASN.1 PrintableString, T.61String or
+ * UniversalString for the organization name.
*
- * <P>For example, to convert a string, such as an organization name for the
- * "O" attribute to a DerValue, the "O" attribute is mapped to the
- * DirStrConverter which is used to convert the organization name to a
- * DER encoded Directory String which is a DerValue of a ASN.1 PrintableString,
- * T.61String or UniversalString for the organization name.
- *
* @author Lily Hsiao, Slava Galperin at Netscape Communications, Inc.
*/
-public interface AVAValueConverter
-{
+public interface AVAValueConverter {
/**
* Converts a string to a DER encoded attribute value.
*
- * @param valueString An AVA value string not encoded in any form.
+ * @param valueString An AVA value string not encoded in any form.
+ *
+ * @return A DerValue object.
*
- * @return A DerValue object.
- *
- * @exception IOException if an error occurs during the conversion.
+ * @exception IOException if an error occurs during the conversion.
*/
- public DerValue getValue(String valueString)
- throws IOException;
-
+ public DerValue getValue(String valueString)
+ throws IOException;
/**
- * Converts a string to a DER encoded attribute value.
- * Specify the order of DER tags to use if more than one encoding is
- * possible. Currently Directory Strings can have different order
- * for backwards compatibility. By 2003 all should be UTF8String.
+ * Converts a string to a DER encoded attribute value. Specify the order of
+ * DER tags to use if more than one encoding is possible. Currently
+ * Directory Strings can have different order for backwards compatibility.
+ * By 2003 all should be UTF8String.
*
- * @param valueString An AVA value string not encoded in any form.
+ * @param valueString An AVA value string not encoded in any form.
*
- * @return A DerValue object.
- *
- * @exception IOException if an error occurs during the conversion.
+ * @return A DerValue object.
+ *
+ * @exception IOException if an error occurs during the conversion.
*/
- public DerValue getValue(String valueString, byte[] tags)
- throws IOException;
+ public DerValue getValue(String valueString, byte[] tags)
+ throws IOException;
/**
* Converts a BER encoded value to a DER encoded attribute value.
*
- * @param berStream A byte array of the BER encoded AVA value.
- * @return A DerValue object.
+ * @param berStream A byte array of the BER encoded AVA value.
+ * @return A DerValue object.
*/
- public DerValue getValue(byte[] berStream)
- throws IOException;
+ public DerValue getValue(byte[] berStream)
+ throws IOException;
/**
* Converts a DER encoded value to a string, not encoded in any form.
*
- * @param avaValue A DerValue object.
- *
- * @return A string for the value or null if it can't be converted.
- *
+ * @param avaValue A DerValue object.
+ *
+ * @return A string for the value or null if it can't be converted.
+ *
* @exception IOException if an error occurs during the conversion.
*/
- public String getAsString(DerValue avaValue)
- throws IOException;
+ public String getAsString(DerValue avaValue)
+ throws IOException;
}
diff --git a/pki/base/util/src/netscape/security/x509/AlgIdDSA.java b/pki/base/util/src/netscape/security/x509/AlgIdDSA.java
index 4e7030ce..656f28e8 100644
--- a/pki/base/util/src/netscape/security/x509/AlgIdDSA.java
+++ b/pki/base/util/src/netscape/security/x509/AlgIdDSA.java
@@ -26,25 +26,23 @@ import netscape.security.util.BigInt;
import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
-
/**
- * This class identifies DSS/DSA Algorithm variants, which are distinguished
- * by using different algorithm parameters <em>P, Q, G</em>. It uses the
- * NIST/IETF standard DER encoding. These are used to implement the Digital
- * Signature Standard (DSS), FIPS 186.
- *
- * <P><em><b>NOTE:</b> At this time, DSS/DSA Algorithm IDs must always
+ * This class identifies DSS/DSA Algorithm variants, which are distinguished by
+ * using different algorithm parameters <em>P, Q, G</em>. It uses the NIST/IETF
+ * standard DER encoding. These are used to implement the Digital Signature
+ * Standard (DSS), FIPS 186.
+ *
+ * <P>
+ * <em><b>NOTE:</b> At this time, DSS/DSA Algorithm IDs must always
* include these parameters. Use of DSS/DSA in modes where parameters are
* either implicit (e.g. a default applicable to a site or a larger scope),
* or are derived from some Certificate Authority's DSS certificate, is
* not currently supported. </em>
- *
+ *
* @version 1.31
* @author David Brownell
*/
-public final
-class AlgIdDSA extends AlgorithmId implements DSAParams
-{
+public final class AlgIdDSA extends AlgorithmId implements DSAParams {
/**
*
*/
@@ -52,133 +50,136 @@ class AlgIdDSA extends AlgorithmId implements DSAParams
/*
* The three unsigned integer parameters.
*/
- private BigInteger p , q, g;
+ private BigInteger p, q, g;
/** Returns the DSS/DSA parameter "P" */
- public BigInteger getP () { return p; }
+ public BigInteger getP() {
+ return p;
+ }
/** Returns the DSS/DSA parameter "Q" */
- public BigInteger getQ () { return q; }
+ public BigInteger getQ() {
+ return q;
+ }
/** Returns the DSS/DSA parameter "G" */
- public BigInteger getG () { return g; }
+ public BigInteger getG() {
+ return g;
+ }
/**
- * Default constructor. The OID and parameters must be
- * deserialized before this algorithm ID is used.
+ * Default constructor. The OID and parameters must be deserialized before
+ * this algorithm ID is used.
*/
// XXX deprecated for general use
- public AlgIdDSA () {}
+ public AlgIdDSA() {
+ }
- AlgIdDSA (DerValue val) throws IOException
- { super(val.getOID()); }
+ AlgIdDSA(DerValue val) throws IOException {
+ super(val.getOID());
+ }
/**
- * Construct an AlgIdDSA from an X.509 encoded byte array.
+ * Construct an AlgIdDSA from an X.509 encoded byte array.
*/
- public AlgIdDSA (byte[] encodedAlg) throws IOException
- { super (new DerValue(encodedAlg).getOID()); }
+ public AlgIdDSA(byte[] encodedAlg) throws IOException {
+ super(new DerValue(encodedAlg).getOID());
+ }
/**
- * Constructs a DSS/DSA Algorithm ID from unsigned integers that
- * define the algorithm parameters. Those integers are encoded
- * as big-endian byte arrays.
- *
+ * Constructs a DSS/DSA Algorithm ID from unsigned integers that define the
+ * algorithm parameters. Those integers are encoded as big-endian byte
+ * arrays.
+ *
* @param p the DSS/DSA paramter "P"
* @param q the DSS/DSA paramter "Q"
* @param g the DSS/DSA paramter "G"
*/
- public AlgIdDSA (byte p [], byte q [], byte g [])
- throws IOException
- {
- this (new BigInteger (1, p),
- new BigInteger (1, q),
- new BigInteger (1, g));
+ public AlgIdDSA(byte p[], byte q[], byte g[])
+ throws IOException {
+ this(new BigInteger(1, p),
+ new BigInteger(1, q),
+ new BigInteger(1, g));
}
/**
* Constructs a DSS/DSA Algorithm ID from numeric parameters.
- *
+ *
* @param p the DSS/DSA paramter "P"
* @param q the DSS/DSA paramter "Q"
* @param g the DSS/DSA paramter "G"
*/
- public AlgIdDSA (BigInteger p, BigInteger q, BigInteger g)
- {
- super (DSA_oid);
-
- try {
- this.p = p;
- this.q = q;
- this.g = g;
- initializeParams ();
-
- } catch (IOException e) {
- /* this should not happen */
- throw new ProviderException ("Construct DSS/DSA Algorithm ID");
- }
+ public AlgIdDSA(BigInteger p, BigInteger q, BigInteger g) {
+ super(DSA_oid);
+
+ try {
+ this.p = p;
+ this.q = q;
+ this.g = g;
+ initializeParams();
+
+ } catch (IOException e) {
+ /* this should not happen */
+ throw new ProviderException("Construct DSS/DSA Algorithm ID");
+ }
}
/**
* Returns "DSA", indicating the Digital Signature Algorithm (DSA) as
* defined by the Digital Signature Standard (DSS), FIPS 186.
*/
- public String getName ()
- { return "DSA"; }
-
+ public String getName() {
+ return "DSA";
+ }
/*
- * For algorithm IDs which haven't been created from a DER encoded
- * value, "params" must be created.
+ * For algorithm IDs which haven't been created from a DER encoded value,
+ * "params" must be created.
*/
- private void initializeParams ()
- throws IOException
- {
- DerOutputStream out = new DerOutputStream ();
-
- out.putInteger (new BigInt(p.toByteArray()));
- out.putInteger (new BigInt(q.toByteArray()));
- out.putInteger (new BigInt(g.toByteArray()));
- params = new DerValue (DerValue.tag_Sequence,out.toByteArray ());
+ private void initializeParams()
+ throws IOException {
+ DerOutputStream out = new DerOutputStream();
+
+ out.putInteger(new BigInt(p.toByteArray()));
+ out.putInteger(new BigInt(q.toByteArray()));
+ out.putInteger(new BigInt(g.toByteArray()));
+ params = new DerValue(DerValue.tag_Sequence, out.toByteArray());
}
/**
- * Parses algorithm parameters P, Q, and G. They're found
- * in the "params" member, which never needs to be changed.
+ * Parses algorithm parameters P, Q, and G. They're found in the "params"
+ * member, which never needs to be changed.
*/
- protected void decodeParams ()
- throws IOException
- {
- if (params == null || params.tag != DerValue.tag_Sequence)
- throw new IOException("DSA alg parsing error");
+ protected void decodeParams()
+ throws IOException {
+ if (params == null || params.tag != DerValue.tag_Sequence)
+ throw new IOException("DSA alg parsing error");
- params.data.reset ();
+ params.data.reset();
- this.p = params.data.getInteger ().toBigInteger();
- this.q = params.data.getInteger ().toBigInteger();
- this.g = params.data.getInteger ().toBigInteger();
+ this.p = params.data.getInteger().toBigInteger();
+ this.q = params.data.getInteger().toBigInteger();
+ this.g = params.data.getInteger().toBigInteger();
- if (params.data.available () != 0)
- throw new IOException ("AlgIdDSA params, extra="+
- params.data.available ());
+ if (params.data.available() != 0)
+ throw new IOException("AlgIdDSA params, extra=" +
+ params.data.available());
}
-
/*
* Returns a formatted string describing the parameters.
*/
- public String toString ()
- { return paramsToString (); }
+ public String toString() {
+ return paramsToString();
+ }
/*
* Returns a string describing the parameters.
*/
- protected String paramsToString ()
- {
- return
- "\n p:\n" + (new BigInt(p)).toString() +
- "\n q:\n" + (new BigInt(q)).toString() +
- "\n g:\n" + (new BigInt(g)).toString() +
- "\n";
+ protected String paramsToString() {
+ return "\n p:\n" + (new BigInt(p)).toString() +
+ "\n q:\n" + (new BigInt(q)).toString() +
+ "\n g:\n" + (new BigInt(g)).toString() +
+ "\n";
}
}
diff --git a/pki/base/util/src/netscape/security/x509/AlgorithmId.java b/pki/base/util/src/netscape/security/x509/AlgorithmId.java
index 28926261..5bc3a15c 100644
--- a/pki/base/util/src/netscape/security/x509/AlgorithmId.java
+++ b/pki/base/util/src/netscape/security/x509/AlgorithmId.java
@@ -30,25 +30,26 @@ import netscape.security.util.DerValue;
import netscape.security.util.ObjectIdentifier;
/**
- * This class identifies algorithms, such as cryptographic transforms, each
- * of which may be associated with parameters. Instances of this base class
- * are used when this runtime environment has no special knowledge of the
- * algorithm type, and may also be used in other cases. Equivalence is
- * defined according to OID and (where relevant) parameters.
- *
- * <P>Subclasses may be used, for example when when the algorithm ID has
- * associated parameters which some code (e.g. code using public keys) needs
- * to have parsed. Two examples of such algorithms are Diffie-Hellman key
- * exchange, and the Digital Signature Standard Algorithm (DSS/DSA).
- *
- * <P>The OID constants defined in this class correspond to some widely
- * used algorithms, for which conventional string names have been defined.
- * This class is not a general repository for OIDs, or for such string names.
- * Note that the mappings between algorithm IDs and algorithm names is
- * not one-to-one.
- *
+ * This class identifies algorithms, such as cryptographic transforms, each of
+ * which may be associated with parameters. Instances of this base class are
+ * used when this runtime environment has no special knowledge of the algorithm
+ * type, and may also be used in other cases. Equivalence is defined according
+ * to OID and (where relevant) parameters.
+ *
+ * <P>
+ * Subclasses may be used, for example when when the algorithm ID has associated
+ * parameters which some code (e.g. code using public keys) needs to have
+ * parsed. Two examples of such algorithms are Diffie-Hellman key exchange, and
+ * the Digital Signature Standard Algorithm (DSS/DSA).
+ *
+ * <P>
+ * The OID constants defined in this class correspond to some widely used
+ * algorithms, for which conventional string names have been defined. This class
+ * is not a general repository for OIDs, or for such string names. Note that the
+ * mappings between algorithm IDs and algorithm names is not one-to-one.
+ *
* @version 1.70
- *
+ *
* @author David Brownell
* @author Amit Kapoor
* @author Hemma Prafullchandra
@@ -64,416 +65,400 @@ public class AlgorithmId implements Serializable, DerEncoder {
/**
* The object identitifer being used for this algorithm.
*/
- private ObjectIdentifier algid = null;
+ private ObjectIdentifier algid = null;
// The (parsed) parameters
private AlgorithmParameters algParams;
/**
- * Parameters for this algorithm. These are stored in unparsed
- * DER-encoded form; subclasses can be made to automaticaly parse
- * them so there is fast access to these parameters.
+ * Parameters for this algorithm. These are stored in unparsed DER-encoded
+ * form; subclasses can be made to automaticaly parse them so there is fast
+ * access to these parameters.
*/
- protected DerValue params = null;
+ protected DerValue params = null;
-
- protected String paramsString = null;
+ protected String paramsString = null;
/**
- * Returns one of the algorithm IDs most commonly associated
- * with this algorithm name.
- *
+ * Returns one of the algorithm IDs most commonly associated with this
+ * algorithm name.
+ *
* @param algname the name being used
* @deprecated use the short get form of this method.
* @exception NoSuchAlgorithmException on error.
*/
- public static AlgorithmId getAlgorithmId(String algname)
- throws NoSuchAlgorithmException
- {
- return get(algname);
+ public static AlgorithmId getAlgorithmId(String algname)
+ throws NoSuchAlgorithmException {
+ return get(algname);
}
public AlgorithmParameters getParameters() {
- return this.algParams;
+ return this.algParams;
}
public String getParametersString() {
return this.paramsString;
}
- public void setParametersString(String paramStr) {
+ public void setParametersString(String paramStr) {
this.paramsString = paramStr;
}
-
+
/**
- * Returns one of the algorithm IDs most commonly associated
- * with this algorithm name.
- *
+ * Returns one of the algorithm IDs most commonly associated with this
+ * algorithm name.
+ *
* @param algname the name being used
* @exception NoSuchAlgorithmException on error.
*/
- public static AlgorithmId get(String algname)
- throws NoSuchAlgorithmException
- {
- ObjectIdentifier oid = algOID(algname);
+ public static AlgorithmId get(String algname)
+ throws NoSuchAlgorithmException {
+ ObjectIdentifier oid = algOID(algname);
- if (oid == null)
- throw new NoSuchAlgorithmException
- ("unrecognized algorithm name: " + algname);
+ if (oid == null)
+ throw new NoSuchAlgorithmException("unrecognized algorithm name: " + algname);
- return new AlgorithmId(oid);
+ return new AlgorithmId(oid);
}
/**
- * Parse (unmarshal) an ID from a DER sequence input value. This form
+ * Parse (unmarshal) an ID from a DER sequence input value. This form
* parsing might be used when expanding a value which has already been
* partially unmarshaled as a set or sequence member.
- *
+ *
* @exception IOException on error.
- * @param val the input value, which contains the algid and, if
- * there are any parameters, those parameters.
- * @return an ID for the algorithm. If the system is configured
- * appropriately, this may be an instance of a class
- * with some kind of special support for this algorithm.
- * In that case, you may "narrow" the type of the ID.
+ * @param val the input value, which contains the algid and, if there are
+ * any parameters, those parameters.
+ * @return an ID for the algorithm. If the system is configured
+ * appropriately, this may be an instance of a class with some kind
+ * of special support for this algorithm. In that case, you may
+ * "narrow" the type of the ID.
*/
public static AlgorithmId parse(DerValue val)
- throws IOException
- {
- if (val.tag != DerValue.tag_Sequence)
- throw new IOException("algid parse error, not a sequence");
-
- /*
- * Get the algorithm ID and any parameters.
- */
- ObjectIdentifier algid;
- DerValue params;
- DerInputStream in = val.toDerInputStream();
-
- algid = in.getOID();
- if (in.available() == 0)
- params = null;
- else {
- params = in.getDerValue();
- if (params.tag == DerValue.tag_Null)
- params = null;
- }
-
- /*
- * Figure out what class (if any) knows about this oid's
- * parameters. Make one, and give it the data to decode.
- */
- AlgorithmId alg = new AlgorithmId(algid, params);
- if (params != null)
- alg.decodeParams();
+ throws IOException {
+ if (val.tag != DerValue.tag_Sequence)
+ throw new IOException("algid parse error, not a sequence");
+ /*
+ * Get the algorithm ID and any parameters.
+ */
+ ObjectIdentifier algid;
+ DerValue params;
+ DerInputStream in = val.toDerInputStream();
+
+ algid = in.getOID();
+ if (in.available() == 0)
+ params = null;
+ else {
+ params = in.getDerValue();
+ if (params.tag == DerValue.tag_Null)
+ params = null;
+ }
/*
- * Set the raw params string in case
- * higher level code might want the info
- */
+ * Figure out what class (if any) knows about this oid's parameters.
+ * Make one, and give it the data to decode.
+ */
+ AlgorithmId alg = new AlgorithmId(algid, params);
+ if (params != null)
+ alg.decodeParams();
+
+ /*
+ * Set the raw params string in case higher level code might want the
+ * info
+ */
String paramStr = null;
- if ( params != null ) {
+ if (params != null) {
paramStr = params.toString();
}
alg.setParametersString(paramStr);
- return alg;
+ return alg;
+ }
+
+ public static AlgorithmId parse(byte[] val)
+ throws IOException {
+ return null;
}
- public static AlgorithmId parse(byte[] val)
- throws IOException
- {
- return null;
- }
-
/**
* Constructs a parameterless algorithm ID.
- *
+ *
* @param oid the identifier for the algorithm
*/
public AlgorithmId(ObjectIdentifier oid) {
- algid = oid;
+ algid = oid;
}
-
private AlgorithmId(ObjectIdentifier oid, DerValue params)
- throws IOException {
- this.algid = oid;
- this.params = params;
+ throws IOException {
+ this.algid = oid;
+ this.params = params;
if (this.params != null)
- decodeParams();
+ decodeParams();
}
-
/**
- * Constructs an algorithm ID which will be initialized
- * separately, for example by deserialization.
+ * Constructs an algorithm ID which will be initialized separately, for
+ * example by deserialization.
+ *
* @deprecated use one of the other constructors.
*/
- public AlgorithmId() { }
-
+ public AlgorithmId() {
+ }
protected void decodeParams() throws IOException {
- try {
- this.algParams = AlgorithmParameters.getInstance
- (this.algid.toString());
- } catch (NoSuchAlgorithmException e) {
- /*
- * This algorithm parameter type is not supported, so we cannot
- * parse the parameters.
- */
- this.algParams = null;
- return;
- }
- // Decode (parse) the parameters
- this.algParams.init(this.params.toByteArray());
+ try {
+ this.algParams = AlgorithmParameters.getInstance
+ (this.algid.toString());
+ } catch (NoSuchAlgorithmException e) {
+ /*
+ * This algorithm parameter type is not supported, so we cannot
+ * parse the parameters.
+ */
+ this.algParams = null;
+ return;
+ }
+ // Decode (parse) the parameters
+ this.algParams.init(this.params.toByteArray());
}
/**
* Marshal a DER-encoded "AlgorithmID" sequence on the DER stream.
*/
public final void encode(DerOutputStream out)
- throws IOException
- {
- derEncode(out);
+ throws IOException {
+ derEncode(out);
}
/**
- * DER encode this object onto an output stream.
- * Implements the <code>DerEncoder</code> interface.
- *
- * @param out
- * the output stream on which to write the DER encoding.
- *
+ * DER encode this object onto an output stream. Implements the
+ * <code>DerEncoder</code> interface.
+ *
+ * @param out the output stream on which to write the DER encoding.
+ *
* @exception IOException on encoding error.
*/
- public void derEncode (OutputStream out) throws IOException
- {
- DerOutputStream bytes = new DerOutputStream();
- DerOutputStream tmp = new DerOutputStream();
-
- bytes.putOID(algid);
- if (params == null)
- bytes.putNull();
- else
- bytes.putDerValue(params);
- tmp.write(DerValue.tag_Sequence, bytes);
- out.write(tmp.toByteArray());
+ public void derEncode(OutputStream out) throws IOException {
+ DerOutputStream bytes = new DerOutputStream();
+ DerOutputStream tmp = new DerOutputStream();
+
+ bytes.putOID(algid);
+ if (params == null)
+ bytes.putNull();
+ else
+ bytes.putDerValue(params);
+ tmp.write(DerValue.tag_Sequence, bytes);
+ out.write(tmp.toByteArray());
}
-// XXXX cleaning required
+ // XXXX cleaning required
/**
* Returns the DER-encoded X.509 AlgorithmId as a byte array.
*/
- public final byte[] encode() throws IOException
- {
- DerOutputStream out = new DerOutputStream ();
- DerOutputStream bytes = new DerOutputStream ();
-
- bytes.putOID(algid);
- if (params == null)
- bytes.putNull();
- else
- bytes.putDerValue(params);
- out.write(DerValue.tag_Sequence, bytes);
- return out.toByteArray();
+ public final byte[] encode() throws IOException {
+ DerOutputStream out = new DerOutputStream();
+ DerOutputStream bytes = new DerOutputStream();
+
+ bytes.putOID(algid);
+ if (params == null)
+ bytes.putNull();
+ else
+ bytes.putDerValue(params);
+ out.write(DerValue.tag_Sequence, bytes);
+ return out.toByteArray();
}
/**
- * Returns list of signing algorithms for a key algorithm such as
- * RSA or DSA.
+ * Returns list of signing algorithms for a key algorithm such as RSA or
+ * DSA.
*/
public static String[] getSigningAlgorithms(AlgorithmId alg) {
- ObjectIdentifier algOid = alg.getOID();
- //System.out.println("Key Alg oid "+algOid.toString());
- if (algOid.equals(DSA_oid) || algOid.equals(DSA_OIW_oid)) {
- return DSA_SIGNING_ALGORITHMS;
- } else if (algOid.equals(RSA_oid) || algOid.equals(RSAEncryption_oid)) {
- return RSA_SIGNING_ALGORITHMS;
- } else if (algOid.equals(ANSIX962_EC_Public_Key_oid) || algOid.equals(ANSIX962_SHA1_With_EC_oid)) {
- return EC_SIGNING_ALGORITHMS;
- } else {
- return null;
- }
+ ObjectIdentifier algOid = alg.getOID();
+ // System.out.println("Key Alg oid "+algOid.toString());
+ if (algOid.equals(DSA_oid) || algOid.equals(DSA_OIW_oid)) {
+ return DSA_SIGNING_ALGORITHMS;
+ } else if (algOid.equals(RSA_oid) || algOid.equals(RSAEncryption_oid)) {
+ return RSA_SIGNING_ALGORITHMS;
+ } else if (algOid.equals(ANSIX962_EC_Public_Key_oid) || algOid.equals(ANSIX962_SHA1_With_EC_oid)) {
+ return EC_SIGNING_ALGORITHMS;
+ } else {
+ return null;
+ }
}
/*
- * Translates from some common algorithm names to the
- * OID with which they're usually associated ... this mapping
- * is the reverse of the one below, except in those cases
- * where synonyms are supported or where a given algorithm
- * is commonly associated with multiple OIDs.
- */
- private static ObjectIdentifier algOID (String name)
- {
- // Digesting algorithms
-
- if (name.equals ("MD5"))
- return AlgorithmId.MD5_oid;
- if (name.equals ("MD2"))
- return AlgorithmId.MD2_oid;
- if (name.equals ("SHA") || name.equals ("SHA1")
- || name.equals("SHA-1"))
- return AlgorithmId.SHA_oid;
- if (name.equals ("SHA256") || name.equals("SHA-256"))
- return AlgorithmId.SHA256_oid;
- if (name.equals("SHA512") || name.equals("SHA-512"))
- return AlgorithmId.SHA512_oid;
-
- // Various public key algorithms
-
- if (name.equals ("RSA"))
- return AlgorithmId.RSA_oid;
-
- if (name.equals ("RSAEncryption"))
- return AlgorithmId.RSAEncryption_oid;
- if (name.equals ("Diffie-Hellman") || name.equals("DH"))
- return AlgorithmId.DH_oid;
- if (name.equals ("DSA"))
- return AlgorithmId.DSA_oid;
-
- // Common signature types
-
- if (name.equals ("SHA1withEC") || name.equals("SHA1/EC")
- || name.equals("1.2.840.10045.4.1"))
- return AlgorithmId.sha1WithEC_oid;
- if (name.equals ("SHA256withEC") || name.equals("SHA256/EC")
- || name.equals("1.2.840.10045.4.3.2"))
- return AlgorithmId.sha256WithEC_oid;
- if (name.equals ("SHA384withEC") || name.equals("SHA384/EC")
- || name.equals("1.2.840.10045.4.3.3"))
- return AlgorithmId.sha384WithEC_oid;
- if (name.equals ("SHA512withEC") || name.equals("SHA512/EC")
- || name.equals("1.2.840.10045.4.3.4"))
- return AlgorithmId.sha512WithEC_oid;
- if (name.equals ("SHA1withRSA") || name.equals("SHA1/RSA")
- || name.equals("1.2.840.113549.1.1.5"))
- return AlgorithmId.sha1WithRSAEncryption_oid;
- if (name.equals ("SHA256withRSA") || name.equals("SHA256/RSA")
- || name.equals("1.2.840.113549.1.1.11"))
- return AlgorithmId.sha256WithRSAEncryption_oid;
- if (name.equals ("SHA512withRSA") || name.equals("SHA512/RSA")
- || name.equals("1.2.840.113549.1.1.13"))
- return AlgorithmId.sha512WithRSAEncryption_oid;
- if (name.equals ("MD5withRSA") || name.equals("MD5/RSA"))
- return AlgorithmId.md5WithRSAEncryption_oid;
- if (name.equals ("MD2withRSA") || name.equals("MD2/RSA"))
- return AlgorithmId.md2WithRSAEncryption_oid;
- if (name.equals("SHAwithDSA") || name.equals("SHA1withDSA")
- || name.equals("SHA/DSA") || name.equals("SHA1/DSA"))
- return AlgorithmId.sha1WithDSA_oid;
-
- return null;
+ * Translates from some common algorithm names to the OID with which they're
+ * usually associated ... this mapping is the reverse of the one below,
+ * except in those cases where synonyms are supported or where a given
+ * algorithm is commonly associated with multiple OIDs.
+ */
+ private static ObjectIdentifier algOID(String name) {
+ // Digesting algorithms
+
+ if (name.equals("MD5"))
+ return AlgorithmId.MD5_oid;
+ if (name.equals("MD2"))
+ return AlgorithmId.MD2_oid;
+ if (name.equals("SHA") || name.equals("SHA1")
+ || name.equals("SHA-1"))
+ return AlgorithmId.SHA_oid;
+ if (name.equals("SHA256") || name.equals("SHA-256"))
+ return AlgorithmId.SHA256_oid;
+ if (name.equals("SHA512") || name.equals("SHA-512"))
+ return AlgorithmId.SHA512_oid;
+
+ // Various public key algorithms
+
+ if (name.equals("RSA"))
+ return AlgorithmId.RSA_oid;
+
+ if (name.equals("RSAEncryption"))
+ return AlgorithmId.RSAEncryption_oid;
+ if (name.equals("Diffie-Hellman") || name.equals("DH"))
+ return AlgorithmId.DH_oid;
+ if (name.equals("DSA"))
+ return AlgorithmId.DSA_oid;
+
+ // Common signature types
+
+ if (name.equals("SHA1withEC") || name.equals("SHA1/EC")
+ || name.equals("1.2.840.10045.4.1"))
+ return AlgorithmId.sha1WithEC_oid;
+ if (name.equals("SHA256withEC") || name.equals("SHA256/EC")
+ || name.equals("1.2.840.10045.4.3.2"))
+ return AlgorithmId.sha256WithEC_oid;
+ if (name.equals("SHA384withEC") || name.equals("SHA384/EC")
+ || name.equals("1.2.840.10045.4.3.3"))
+ return AlgorithmId.sha384WithEC_oid;
+ if (name.equals("SHA512withEC") || name.equals("SHA512/EC")
+ || name.equals("1.2.840.10045.4.3.4"))
+ return AlgorithmId.sha512WithEC_oid;
+ if (name.equals("SHA1withRSA") || name.equals("SHA1/RSA")
+ || name.equals("1.2.840.113549.1.1.5"))
+ return AlgorithmId.sha1WithRSAEncryption_oid;
+ if (name.equals("SHA256withRSA") || name.equals("SHA256/RSA")
+ || name.equals("1.2.840.113549.1.1.11"))
+ return AlgorithmId.sha256WithRSAEncryption_oid;
+ if (name.equals("SHA512withRSA") || name.equals("SHA512/RSA")
+ || name.equals("1.2.840.113549.1.1.13"))
+ return AlgorithmId.sha512WithRSAEncryption_oid;
+ if (name.equals("MD5withRSA") || name.equals("MD5/RSA"))
+ return AlgorithmId.md5WithRSAEncryption_oid;
+ if (name.equals("MD2withRSA") || name.equals("MD2/RSA"))
+ return AlgorithmId.md2WithRSAEncryption_oid;
+ if (name.equals("SHAwithDSA") || name.equals("SHA1withDSA")
+ || name.equals("SHA/DSA") || name.equals("SHA1/DSA"))
+ return AlgorithmId.sha1WithDSA_oid;
+
+ return null;
}
/*
- * For the inevitable cases where key or signature types are not
- * configured in an environment which encounters such keys or
- * signatures, we still attempt to provide user-friendly names
- * for some of the most common algorithms. Subclasses can of
- * course override getName().
- *
- * Wherever possible, the names are those defined by the IETF.
- * Such names are noted below.
- */
- private String algName()
- {
- // Common message digest algorithms
-
- if (algid.equals(AlgorithmId.MD5_oid))
- return "MD5"; // RFC 1423
- if (algid.equals(AlgorithmId.MD2_oid))
- return "MD2"; // RFC 1423
- if (algid.equals(AlgorithmId.SHA_oid))
- return "SHA";
- if (algid.equals(AlgorithmId.SHA256_oid))
- return "SHA256";
- if (algid.equals(AlgorithmId.SHA512_oid))
- return "SHA512";
-
- // Common key types
-
- if (algid.equals(AlgorithmId.ANSIX962_EC_Public_Key_oid))
- return "EC";
- if (algid.equals(AlgorithmId.RSAEncryption_oid)
- || algid.equals(AlgorithmId.RSA_oid))
- return "RSA";
- if (algid.equals(AlgorithmId.DH_oid)
+ * For the inevitable cases where key or signature types are not configured
+ * in an environment which encounters such keys or signatures, we still
+ * attempt to provide user-friendly names for some of the most common
+ * algorithms. Subclasses can of course override getName().
+ *
+ * Wherever possible, the names are those defined by the IETF. Such names
+ * are noted below.
+ */
+ private String algName() {
+ // Common message digest algorithms
+
+ if (algid.equals(AlgorithmId.MD5_oid))
+ return "MD5"; // RFC 1423
+ if (algid.equals(AlgorithmId.MD2_oid))
+ return "MD2"; // RFC 1423
+ if (algid.equals(AlgorithmId.SHA_oid))
+ return "SHA";
+ if (algid.equals(AlgorithmId.SHA256_oid))
+ return "SHA256";
+ if (algid.equals(AlgorithmId.SHA512_oid))
+ return "SHA512";
+
+ // Common key types
+
+ if (algid.equals(AlgorithmId.ANSIX962_EC_Public_Key_oid))
+ return "EC";
+ if (algid.equals(AlgorithmId.RSAEncryption_oid)
+ || algid.equals(AlgorithmId.RSA_oid))
+ return "RSA";
+ if (algid.equals(AlgorithmId.DH_oid)
|| algid.equals(AlgorithmId.DH_PKIX_oid))
- return "Diffie-Hellman";
- if (algid.equals(AlgorithmId.DSA_oid)
+ return "Diffie-Hellman";
+ if (algid.equals(AlgorithmId.DSA_oid)
|| algid.equals(AlgorithmId.DSA_OIW_oid))
- return "DSA";
-
- // Common signature types
-
- if (algid.equals (AlgorithmId.sha1WithEC_oid))
- return "SHA1withEC";
- if (algid.equals (AlgorithmId.sha256WithEC_oid))
- return "SHA256withEC";
- if (algid.equals (AlgorithmId.sha384WithEC_oid))
- return "SHA384withEC";
- if (algid.equals (AlgorithmId.sha512WithEC_oid))
- return "SHA512withEC";
- if (algid.equals (AlgorithmId.md5WithRSAEncryption_oid))
- return "MD5withRSA";
- if (algid.equals (AlgorithmId.md2WithRSAEncryption_oid))
- return "MD2withRSA";
- if (algid.equals (AlgorithmId.sha1WithRSAEncryption_oid))
- return "SHA1withRSA";
- if (algid.equals (AlgorithmId.sha256WithRSAEncryption_oid))
- return "SHA256withRSA";
- if (algid.equals (AlgorithmId.sha512WithRSAEncryption_oid))
- return "SHA512withRSA";
- if (algid.equals(AlgorithmId.sha1WithDSA_oid)
+ return "DSA";
+
+ // Common signature types
+
+ if (algid.equals(AlgorithmId.sha1WithEC_oid))
+ return "SHA1withEC";
+ if (algid.equals(AlgorithmId.sha256WithEC_oid))
+ return "SHA256withEC";
+ if (algid.equals(AlgorithmId.sha384WithEC_oid))
+ return "SHA384withEC";
+ if (algid.equals(AlgorithmId.sha512WithEC_oid))
+ return "SHA512withEC";
+ if (algid.equals(AlgorithmId.md5WithRSAEncryption_oid))
+ return "MD5withRSA";
+ if (algid.equals(AlgorithmId.md2WithRSAEncryption_oid))
+ return "MD2withRSA";
+ if (algid.equals(AlgorithmId.sha1WithRSAEncryption_oid))
+ return "SHA1withRSA";
+ if (algid.equals(AlgorithmId.sha256WithRSAEncryption_oid))
+ return "SHA256withRSA";
+ if (algid.equals(AlgorithmId.sha512WithRSAEncryption_oid))
+ return "SHA512withRSA";
+ if (algid.equals(AlgorithmId.sha1WithDSA_oid)
|| algid.equals(AlgorithmId.sha1WithDSA_OIW_oid)
|| algid.equals(AlgorithmId.shaWithDSA_OIW_oid))
- return "SHA1withDSA";
+ return "SHA1withDSA";
- // default returns a dot-notation ID
+ // default returns a dot-notation ID
- return "OID." + algid.toString ();
+ return "OID." + algid.toString();
}
/**
- * Returns the ISO OID for this algorithm. This is usually converted
- * to a string and used as part of an algorithm name, for example
- * "OID.1.3.14.3.2.13" style notation. Use the <code>getName</code>
- * call when you do not need to ensure cross-system portability
- * of algorithm names, or need a user friendly name.
+ * Returns the ISO OID for this algorithm. This is usually converted to a
+ * string and used as part of an algorithm name, for example
+ * "OID.1.3.14.3.2.13" style notation. Use the <code>getName</code> call
+ * when you do not need to ensure cross-system portability of algorithm
+ * names, or need a user friendly name.
*/
- final public ObjectIdentifier getOID ()
- { return algid; }
-
+ final public ObjectIdentifier getOID() {
+ return algid;
+ }
/**
- * Returns a name for the algorithm which may be more intelligible
- * to humans than the algorithm's OID, but which won't necessarily
- * be comprehensible on other systems. For example, this might
- * return a name such as "MD5withRSA" for a signature algorithm on
- * some systems. It also returns names like "OID.1.2.3.4", when
- * no particular name for the algorithm is known.
+ * Returns a name for the algorithm which may be more intelligible to humans
+ * than the algorithm's OID, but which won't necessarily be comprehensible
+ * on other systems. For example, this might return a name such as
+ * "MD5withRSA" for a signature algorithm on some systems. It also returns
+ * names like "OID.1.2.3.4", when no particular name for the algorithm is
+ * known.
*/
- public String getName()
- { return algName (); }
+ public String getName() {
+ return algName();
+ }
/**
* Returns a string describing the algorithm and its parameters.
*/
- public String toString()
- {
- return (algName() + paramsToString());
+ public String toString() {
+ return (algName() + paramsToString());
}
/**
- * Returns the DER encoded parameter, which can then be
- * used to initialize java.security.AlgorithmParamters.
- *
+ * Returns the DER encoded parameter, which can then be used to initialize
+ * java.security.AlgorithmParamters.
+ *
* @return DER encoded parameters, or null not present.
*/
public byte[] getEncodedParams() throws IOException {
@@ -484,66 +469,58 @@ public class AlgorithmId implements Serializable, DerEncoder {
}
/**
- * Provides a human-readable description of the algorithm parameters.
- * This may be redefined by subclasses which parse those parameters.
+ * Provides a human-readable description of the algorithm parameters. This
+ * may be redefined by subclasses which parse those parameters.
*/
- protected String paramsToString()
- {
- if (params == null) {
- return "";
- } else if (algParams != null) {
- return algParams.toString();
- } else {
- return ", params unparsed";
- }
+ protected String paramsToString() {
+ if (params == null) {
+ return "";
+ } else if (algParams != null) {
+ return algParams.toString();
+ } else {
+ return ", params unparsed";
+ }
}
-
/**
- * Returns true iff the argument indicates the same algorithm
- * with the same parameters.
+ * Returns true iff the argument indicates the same algorithm with the same
+ * parameters.
*/
- public boolean equals(AlgorithmId other)
- {
- if (!algid.equals (other.algid))
+ public boolean equals(AlgorithmId other) {
+ if (!algid.equals(other.algid))
+ return false;
+ else if (params == null && other.params == null)
+ return true;
+ else if (params == null)
return false;
- else if (params == null && other.params == null)
- return true;
- else if (params == null)
- return false;
- else
- return params.equals(other.params);
+ else
+ return params.equals(other.params);
}
-
/**
- * Compares this AlgorithmID to another. If algorithm parameters are
- * available, they are compared. Otherwise, just the object IDs
- * for the algorithm are compared.
- *
+ * Compares this AlgorithmID to another. If algorithm parameters are
+ * available, they are compared. Otherwise, just the object IDs for the
+ * algorithm are compared.
+ *
* @param other preferably an AlgorithmId, else an ObjectIdentifier
*/
- public boolean equals(Object other)
- {
- if (other instanceof AlgorithmId)
- return equals((AlgorithmId) other);
- else if (other instanceof ObjectIdentifier)
- return equals((ObjectIdentifier) other);
- else
- return false;
+ public boolean equals(Object other) {
+ if (other instanceof AlgorithmId)
+ return equals((AlgorithmId) other);
+ else if (other instanceof ObjectIdentifier)
+ return equals((ObjectIdentifier) other);
+ else
+ return false;
}
-
/**
- * Compares two algorithm IDs for equality. Returns true iff
- * they are the same algorithm, ignoring algorithm parameters.
+ * Compares two algorithm IDs for equality. Returns true iff they are the
+ * same algorithm, ignoring algorithm parameters.
*/
- public final boolean equals(ObjectIdentifier id)
- {
- return algid.equals(id);
+ public final boolean equals(ObjectIdentifier id) {
+ return algid.equals(id);
}
-
/*****************************************************************/
/*
@@ -553,37 +530,32 @@ public class AlgorithmId implements Serializable, DerEncoder {
private static final int MD5_data[] = { 1, 2, 840, 113549, 2, 5 };
// sha = { 1, 3, 14, 3, 2, 18 };
private static final int SHA1_OIW_data[] = { 1, 3, 14, 3, 2, 26 };
- private static final int SHA256_data[] = {2, 16, 840, 1, 101, 3, 4, 2, 1};
- private static final int SHA512_data[] = {2, 16, 840, 1, 101, 3, 4, 2, 3};
+ private static final int SHA256_data[] = { 2, 16, 840, 1, 101, 3, 4, 2, 1 };
+ private static final int SHA512_data[] = { 2, 16, 840, 1, 101, 3, 4, 2, 3 };
/**
- * Algorithm ID for the MD2 Message Digest Algorthm, from RFC 1319.
- * OID = 1.2.840.113549.2.2
+ * Algorithm ID for the MD2 Message Digest Algorthm, from RFC 1319. OID =
+ * 1.2.840.113549.2.2
*/
- public static final ObjectIdentifier
- MD2_oid = new ObjectIdentifier(MD2_data);
+ public static final ObjectIdentifier MD2_oid = new ObjectIdentifier(MD2_data);
/**
- * Algorithm ID for the MD5 Message Digest Algorthm, from RFC 1321.
- * OID = 1.2.840.113549.2.5
+ * Algorithm ID for the MD5 Message Digest Algorthm, from RFC 1321. OID =
+ * 1.2.840.113549.2.5
*/
- public static final ObjectIdentifier
- MD5_oid = new ObjectIdentifier(MD5_data);
+ public static final ObjectIdentifier MD5_oid = new ObjectIdentifier(MD5_data);
/**
- * Algorithm ID for the SHA1 Message Digest Algorithm, from FIPS 180-1.
- * This is sometimes called "SHA", though that is often confusing since
- * many people refer to FIPS 180 (which has an error) as defining SHA.
- * OID = 1.3.14.3.2.26
+ * Algorithm ID for the SHA1 Message Digest Algorithm, from FIPS 180-1. This
+ * is sometimes called "SHA", though that is often confusing since many
+ * people refer to FIPS 180 (which has an error) as defining SHA. OID =
+ * 1.3.14.3.2.26
*/
- public static final ObjectIdentifier
- SHA_oid = new ObjectIdentifier(SHA1_OIW_data);
+ public static final ObjectIdentifier SHA_oid = new ObjectIdentifier(SHA1_OIW_data);
- public static final ObjectIdentifier
- SHA256_oid = new ObjectIdentifier(SHA256_data);
+ public static final ObjectIdentifier SHA256_oid = new ObjectIdentifier(SHA256_data);
- public static final ObjectIdentifier
- SHA512_oid = new ObjectIdentifier(SHA512_data);
+ public static final ObjectIdentifier SHA512_oid = new ObjectIdentifier(SHA512_data);
/*
* COMMON PUBLIC KEY TYPES
@@ -600,216 +572,182 @@ public class AlgorithmId implements Serializable, DerEncoder {
private static final int ANSI_X962_sha1_with_ec_data[] =
{ 1, 2, 840, 10045, 4, 1 };
- public static final ObjectIdentifier
- ANSIX962_EC_Public_Key_oid = new ObjectIdentifier(ANSI_X962_public_key_data);
- public static final ObjectIdentifier
- ANSIX962_SHA1_With_EC_oid = new ObjectIdentifier(ANSI_X962_sha1_with_ec_data);
+ public static final ObjectIdentifier ANSIX962_EC_Public_Key_oid = new ObjectIdentifier(ANSI_X962_public_key_data);
+ public static final ObjectIdentifier ANSIX962_SHA1_With_EC_oid = new ObjectIdentifier(ANSI_X962_sha1_with_ec_data);
/*
- * Note the preferred OIDs are named simply with no "OIW" or
- * "PKIX" in them, even though they may point to data from these
- * specs; e.g. SHA_oid, DH_oid, DSA_oid, SHA1WithDSA_oid...
+ * Note the preferred OIDs are named simply with no "OIW" or "PKIX" in them,
+ * even though they may point to data from these specs; e.g. SHA_oid,
+ * DH_oid, DSA_oid, SHA1WithDSA_oid...
*/
/**
- * Algorithm ID for Diffie Hellman Key agreement, from PKCS #3.
- * Parameters include public values P and G, and may optionally specify
- * the length of the private key X. Alternatively, algorithm parameters
- * may be derived from another source such as a Certificate Authority's
- * certificate.
- * OID = 1.2.840.113549.1.3.1
+ * Algorithm ID for Diffie Hellman Key agreement, from PKCS #3. Parameters
+ * include public values P and G, and may optionally specify the length of
+ * the private key X. Alternatively, algorithm parameters may be derived
+ * from another source such as a Certificate Authority's certificate. OID =
+ * 1.2.840.113549.1.3.1
*/
- public static final ObjectIdentifier
- DH_oid = new ObjectIdentifier(DH_data);
+ public static final ObjectIdentifier DH_oid = new ObjectIdentifier(DH_data);
/**
- * Algorithm ID for the Diffie Hellman Key Agreement (DH), from the
- * IETF PKIX IPKI Part I.
- * Parameters may include public values P and G.
- * OID = 1.2.840.10046.2.1
+ * Algorithm ID for the Diffie Hellman Key Agreement (DH), from the IETF
+ * PKIX IPKI Part I. Parameters may include public values P and G. OID =
+ * 1.2.840.10046.2.1
*/
- public static final ObjectIdentifier
- DH_PKIX_oid = new ObjectIdentifier(DH_PKIX_data);
+ public static final ObjectIdentifier DH_PKIX_oid = new ObjectIdentifier(DH_PKIX_data);
/**
- * Algorithm ID for the Digital Signing Algorithm (DSA), from the
- * NIST OIW Stable Agreements part 12.
- * Parameters may include public values P, Q, and G; or these may be
- * derived from
- * another source such as a Certificate Authority's certificate.
- * OID = 1.3.14.3.2.12
+ * Algorithm ID for the Digital Signing Algorithm (DSA), from the NIST OIW
+ * Stable Agreements part 12. Parameters may include public values P, Q, and
+ * G; or these may be derived from another source such as a Certificate
+ * Authority's certificate. OID = 1.3.14.3.2.12
*/
- public static final ObjectIdentifier
- DSA_OIW_oid = new ObjectIdentifier(DSA_OIW_data);
+ public static final ObjectIdentifier DSA_OIW_oid = new ObjectIdentifier(DSA_OIW_data);
/**
- * Algorithm ID for the Digital Signing Algorithm (DSA), from the
- * IETF PKIX IPKI Part I.
- * Parameters may include public values P, Q, and G; or these may be
- * derived from
- * another source such as a Certificate Authority's certificate.
- * OID = 1.2.840.10040.4.1
+ * Algorithm ID for the Digital Signing Algorithm (DSA), from the IETF PKIX
+ * IPKI Part I. Parameters may include public values P, Q, and G; or these
+ * may be derived from another source such as a Certificate Authority's
+ * certificate. OID = 1.2.840.10040.4.1
*/
- public static final ObjectIdentifier
- DSA_oid = new ObjectIdentifier(DSA_PKIX_data);
+ public static final ObjectIdentifier DSA_oid = new ObjectIdentifier(DSA_PKIX_data);
/**
- * Algorithm ID for RSA keys used for any purpose, as defined in X.509.
- * The algorithm parameter is a single value, the number of bits in the
- * public modulus.
- * OID = 1.2.5.8.1.1
+ * Algorithm ID for RSA keys used for any purpose, as defined in X.509. The
+ * algorithm parameter is a single value, the number of bits in the public
+ * modulus. OID = 1.2.5.8.1.1
*/
- public static final ObjectIdentifier
- RSA_oid = new ObjectIdentifier(RSA_data);
-
+ public static final ObjectIdentifier RSA_oid = new ObjectIdentifier(RSA_data);
/**
- * Algorithm ID for RSA keys used with RSA encryption, as defined
- * in PKCS #1. There are no parameters associated with this algorithm.
- * OID = 1.2.840.113549.1.1.1
+ * Algorithm ID for RSA keys used with RSA encryption, as defined in PKCS
+ * #1. There are no parameters associated with this algorithm. OID =
+ * 1.2.840.113549.1.1.1
*/
- public static final ObjectIdentifier
- RSAEncryption_oid = new ObjectIdentifier(RSAEncryption_data);
-
+ public static final ObjectIdentifier RSAEncryption_oid = new ObjectIdentifier(RSAEncryption_data);
/*
* COMMON SIGNATURE ALGORITHMS
*/
- private static final int sha1WithEC_data[] =
- { 1, 2, 840, 10045, 4, 1 };
- private static final int sha256WithEC_data[] =
- { 1, 2, 840, 10045, 4, 3, 2 };
- private static final int sha384WithEC_data[] =
- { 1, 2, 840, 10045, 4, 3, 3 };
- private static final int sha512WithEC_data[] =
- { 1, 2, 840, 10045, 4, 3, 4 };
- private static final int md2WithRSAEncryption_data[] =
- { 1, 2, 840, 113549, 1, 1, 2 };
- private static final int md5WithRSAEncryption_data[] =
- { 1, 2, 840, 113549, 1, 1, 4 };
- private static final int sha1WithRSAEncryption_data[] =
- { 1, 2, 840, 113549 ,1, 1, 5 };
- private static final int sha256WithRSAEncryption_data[] =
- { 1, 2, 840, 113549 ,1, 1, 11 };
- private static final int sha512WithRSAEncryption_data[] =
- { 1, 2, 840, 113549 ,1, 1, 13 };
- private static final int sha1WithRSAEncryption_OIW_data[] =
- { 1, 3, 14, 3, 2, 29 };
- private static final int shaWithDSA_OIW_data[] =
- { 1, 3, 14, 3, 2, 13 };
- private static final int sha1WithDSA_OIW_data[] =
- { 1, 3, 14, 3, 2, 27 };
- private static final int dsaWithSHA1_PKIX_data[] =
- { 1, 2, 840, 10040, 4, 3 };
-
- public static final ObjectIdentifier
- sha1WithEC_oid = new
- ObjectIdentifier(sha1WithEC_data);
-
- public static final ObjectIdentifier
- sha256WithEC_oid = new
- ObjectIdentifier(sha256WithEC_data);
-
- public static final ObjectIdentifier
- sha384WithEC_oid = new
- ObjectIdentifier(sha384WithEC_data);
-
- public static final ObjectIdentifier
- sha512WithEC_oid = new
- ObjectIdentifier(sha512WithEC_data);
-
- /**
- * Identifies a signing algorithm where an MD2 digest is encrypted
- * using an RSA private key; defined in PKCS #1. Use of this
- * signing algorithm is discouraged due to MD2 vulnerabilities.
- * OID = 1.2.840.113549.1.1.2
- */
- public static final ObjectIdentifier
- md2WithRSAEncryption_oid = new
- ObjectIdentifier(md2WithRSAEncryption_data);
-
- /**
- * Identifies a signing algorithm where an MD5 digest is
- * encrypted using an RSA private key; defined in PKCS #1.
- * OID = 1.2.840.113549.1.1.4
- */
- public static final ObjectIdentifier
- md5WithRSAEncryption_oid = new
- ObjectIdentifier(md5WithRSAEncryption_data);
+ private static final int sha1WithEC_data[] =
+ { 1, 2, 840, 10045, 4, 1 };
+ private static final int sha256WithEC_data[] =
+ { 1, 2, 840, 10045, 4, 3, 2 };
+ private static final int sha384WithEC_data[] =
+ { 1, 2, 840, 10045, 4, 3, 3 };
+ private static final int sha512WithEC_data[] =
+ { 1, 2, 840, 10045, 4, 3, 4 };
+ private static final int md2WithRSAEncryption_data[] =
+ { 1, 2, 840, 113549, 1, 1, 2 };
+ private static final int md5WithRSAEncryption_data[] =
+ { 1, 2, 840, 113549, 1, 1, 4 };
+ private static final int sha1WithRSAEncryption_data[] =
+ { 1, 2, 840, 113549, 1, 1, 5 };
+ private static final int sha256WithRSAEncryption_data[] =
+ { 1, 2, 840, 113549, 1, 1, 11 };
+ private static final int sha512WithRSAEncryption_data[] =
+ { 1, 2, 840, 113549, 1, 1, 13 };
+ private static final int sha1WithRSAEncryption_OIW_data[] =
+ { 1, 3, 14, 3, 2, 29 };
+ private static final int shaWithDSA_OIW_data[] =
+ { 1, 3, 14, 3, 2, 13 };
+ private static final int sha1WithDSA_OIW_data[] =
+ { 1, 3, 14, 3, 2, 27 };
+ private static final int dsaWithSHA1_PKIX_data[] =
+ { 1, 2, 840, 10040, 4, 3 };
+
+ public static final ObjectIdentifier sha1WithEC_oid = new
+ ObjectIdentifier(sha1WithEC_data);
+
+ public static final ObjectIdentifier sha256WithEC_oid = new
+ ObjectIdentifier(sha256WithEC_data);
+
+ public static final ObjectIdentifier sha384WithEC_oid = new
+ ObjectIdentifier(sha384WithEC_data);
+
+ public static final ObjectIdentifier sha512WithEC_oid = new
+ ObjectIdentifier(sha512WithEC_data);
+
+ /**
+ * Identifies a signing algorithm where an MD2 digest is encrypted using an
+ * RSA private key; defined in PKCS #1. Use of this signing algorithm is
+ * discouraged due to MD2 vulnerabilities. OID = 1.2.840.113549.1.1.2
+ */
+ public static final ObjectIdentifier md2WithRSAEncryption_oid = new
+ ObjectIdentifier(md2WithRSAEncryption_data);
+
+ /**
+ * Identifies a signing algorithm where an MD5 digest is encrypted using an
+ * RSA private key; defined in PKCS #1. OID = 1.2.840.113549.1.1.4
+ */
+ public static final ObjectIdentifier md5WithRSAEncryption_oid = new
+ ObjectIdentifier(md5WithRSAEncryption_data);
/**
* The proper one for sha1/rsa
*/
- public static final ObjectIdentifier
- sha1WithRSAEncryption_oid = new
- ObjectIdentifier(sha1WithRSAEncryption_data);
+ public static final ObjectIdentifier sha1WithRSAEncryption_oid = new
+ ObjectIdentifier(sha1WithRSAEncryption_data);
/**
* The proper one for sha256/rsa
*/
- public static final ObjectIdentifier
- sha256WithRSAEncryption_oid = new
- ObjectIdentifier(sha256WithRSAEncryption_data);
+ public static final ObjectIdentifier sha256WithRSAEncryption_oid = new
+ ObjectIdentifier(sha256WithRSAEncryption_data);
/**
* The proper one for sha512/rsa
*/
- public static final ObjectIdentifier
- sha512WithRSAEncryption_oid = new
- ObjectIdentifier(sha512WithRSAEncryption_data);
+ public static final ObjectIdentifier sha512WithRSAEncryption_oid = new
+ ObjectIdentifier(sha512WithRSAEncryption_data);
/**
- * Identifies a signing algorithm where an SHA1 digest is
- * encrypted using an RSA private key; defined in NIST OIW.
- * OID = 1.3.14.3.2.29
+ * Identifies a signing algorithm where an SHA1 digest is encrypted using an
+ * RSA private key; defined in NIST OIW. OID = 1.3.14.3.2.29
*/
- public static final ObjectIdentifier
- sha1WithRSAEncryption_OIW_oid = new
- ObjectIdentifier(sha1WithRSAEncryption_OIW_data);
+ public static final ObjectIdentifier sha1WithRSAEncryption_OIW_oid = new
+ ObjectIdentifier(sha1WithRSAEncryption_OIW_data);
/**
- * Identifies the FIPS 186 "Digital Signature Standard" (DSS), where a
- * SHA digest is signed using the Digital Signing Algorithm (DSA).
- * This should not be used.
- * OID = 1.3.14.3.2.13
+ * Identifies the FIPS 186 "Digital Signature Standard" (DSS), where a SHA
+ * digest is signed using the Digital Signing Algorithm (DSA). This should
+ * not be used. OID = 1.3.14.3.2.13
*/
- public static final ObjectIdentifier
- shaWithDSA_OIW_oid = new ObjectIdentifier(shaWithDSA_OIW_data);
+ public static final ObjectIdentifier shaWithDSA_OIW_oid = new ObjectIdentifier(shaWithDSA_OIW_data);
/**
- * Identifies the FIPS 186 "Digital Signature Standard" (DSS), where a
- * SHA1 digest is signed using the Digital Signing Algorithm (DSA).
- * OID = 1.3.14.3.2.27
+ * Identifies the FIPS 186 "Digital Signature Standard" (DSS), where a SHA1
+ * digest is signed using the Digital Signing Algorithm (DSA). OID =
+ * 1.3.14.3.2.27
*/
- public static final ObjectIdentifier
- sha1WithDSA_OIW_oid = new ObjectIdentifier(sha1WithDSA_OIW_data);
+ public static final ObjectIdentifier sha1WithDSA_OIW_oid = new ObjectIdentifier(sha1WithDSA_OIW_data);
/**
- * Identifies the FIPS 186 "Digital Signature Standard" (DSS), where a
- * SHA1 digest is signed using the Digital Signing Algorithm (DSA).
- * OID = 1.2.840.10040.4.3
+ * Identifies the FIPS 186 "Digital Signature Standard" (DSS), where a SHA1
+ * digest is signed using the Digital Signing Algorithm (DSA). OID =
+ * 1.2.840.10040.4.3
*/
- public static final ObjectIdentifier
- sha1WithDSA_oid = new ObjectIdentifier(dsaWithSHA1_PKIX_data);
+ public static final ObjectIdentifier sha1WithDSA_oid = new ObjectIdentifier(dsaWithSHA1_PKIX_data);
- /**
+ /**
* Supported signing algorithms for a DSA key.
*/
- public static final String[] DSA_SIGNING_ALGORITHMS = new String[]
- { "SHA1withDSA" };
+ public static final String[] DSA_SIGNING_ALGORITHMS = new String[]
+ { "SHA1withDSA" };
- /**
+ /**
* Supported signing algorithms for a RSA key.
*/
- public static final String[] RSA_SIGNING_ALGORITHMS = new String[]
- { "SHA1withRSA", "SHA256withRSA", "SHA512withRSA", "MD5withRSA", "MD2withRSA" };
+ public static final String[] RSA_SIGNING_ALGORITHMS = new String[]
+ { "SHA1withRSA", "SHA256withRSA", "SHA512withRSA", "MD5withRSA", "MD2withRSA" };
- public static final String[] EC_SIGNING_ALGORITHMS = new String[]
- { "SHA1withEC", "SHA256withEC", "SHA384withEC", "SHA512withEC" };
+ public static final String[] EC_SIGNING_ALGORITHMS = new String[]
+ { "SHA1withEC", "SHA256withEC", "SHA384withEC", "SHA512withEC" };
- /**
+ /**
* All supported signing algorithms.
*/
- public static final String[] ALL_SIGNING_ALGORITHMS = new String[]
- { "SHA1withRSA", "MD5withRSA", "MD2withRSA", "SHA1withDSA", "SHA256withRSA", "SHA512withRSA", "SHA1withEC", "SHA256withEC", "SHA384withEC", "SHA512withEC" };
+ public static final String[] ALL_SIGNING_ALGORITHMS = new String[]
+ { "SHA1withRSA", "MD5withRSA", "MD2withRSA", "SHA1withDSA", "SHA256withRSA", "SHA512withRSA", "SHA1withEC", "SHA256withEC", "SHA384withEC", "SHA512withEC" };
}
diff --git a/pki/base/util/src/netscape/security/x509/Attribute.java b/pki/base/util/src/netscape/security/x509/Attribute.java
index b362f629..8ae865da 100644
--- a/pki/base/util/src/netscape/security/x509/Attribute.java
+++ b/pki/base/util/src/netscape/security/x509/Attribute.java
@@ -29,28 +29,30 @@ import netscape.security.util.DerValue;
import netscape.security.util.ObjectIdentifier;
/**
- * An attribute, as identified by some attribute ID, has some particular values.
- * Values are as a rule ASN.1 printable strings. A conventional set of type IDs
+ * An attribute, as identified by some attribute ID, has some particular values.
+ * Values are as a rule ASN.1 printable strings. A conventional set of type IDs
* is recognized when parsing. The following shows the syntax:
+ *
* <pre>
- *
+ *
* Attribute ::= SEQUENCE {
- * type AttributeType,
+ * type AttributeType,
* value SET OF AttributeValue
* -- at least one value is required --}
- *
+ *
* AttributeType ::= OBJECT IDENTIFIER
- *
+ *
* AttributeValue ::= ANY
- *
+ *
* </pre>
+ *
* Refer to draft-ietf-pkix-ipki-part1-11 for the support attributes listed on
* page 96 of the internet draft. The are listed here for easy reference: name,
- * common name, surname, given name, initials, generation qualifier, dn qualifier,
- * country name, locality name, state or province name, organization name, organization
- * unit name, title, pkcs9 email. Not all the attributes are supported. Please check
- * the X500NameAttrMap for defined attributes.
- *
+ * common name, surname, given name, initials, generation qualifier, dn
+ * qualifier, country name, locality name, state or province name, organization
+ * name, organization unit name, title, pkcs9 email. Not all the attributes are
+ * supported. Please check the X500NameAttrMap for defined attributes.
+ *
* @author Christine Ho
*/
@@ -60,72 +62,73 @@ public final class Attribute implements Serializable, DerEncoder {
*
*/
private static final long serialVersionUID = -931486084625476764L;
- //private variables
- ObjectIdentifier oid;
- Vector valueSet = new Vector();
+ // private variables
+ ObjectIdentifier oid;
+ Vector valueSet = new Vector();
transient protected X500NameAttrMap attrMap;
- //========== CONSTRUCTOR ==================================
+ // ========== CONSTRUCTOR ==================================
/**
* Construct an attribute from attribute type and attribute value
+ *
* @param oid the object identifier of the attribute type
* @param value the value string
*/
- public Attribute (ObjectIdentifier oid, String value)
- throws IOException
- {
+ public Attribute(ObjectIdentifier oid, String value)
+ throws IOException {
- //pre-condition verification
+ // pre-condition verification
if ((oid == null) || (value == null))
- throw new IOException("Invalid Input - null passed");
-
- attrMap = X500NameAttrMap.getDefault();
- this.oid = oid;
- valueSet.addElement(value);
+ throw new IOException("Invalid Input - null passed");
+
+ attrMap = X500NameAttrMap.getDefault();
+ this.oid = oid;
+ valueSet.addElement(value);
}
/**
* Construct an attribute from attribute type and attribute values
+ *
* @param oid the object identifier of the attribute type
* @param values String value vector
*/
- public Attribute (ObjectIdentifier oid, Vector values)
- throws IOException
- {
+ public Attribute(ObjectIdentifier oid, Vector values)
+ throws IOException {
- //pre-condition verification
+ // pre-condition verification
if ((oid == null) || (values == null))
- throw new IOException("Invalid Input - null passed");
-
- attrMap = X500NameAttrMap.getDefault();
- this.oid = oid;
-
- //copy the value into the valueSet list
- Enumeration vals = values.elements();
- while (vals.hasMoreElements()) {
- Object obj = vals.nextElement();
- if (obj instanceof String)
- valueSet.addElement(obj);
- else
- throw new IOException("values vectore must consist of String object");
- }
+ throw new IOException("Invalid Input - null passed");
+
+ attrMap = X500NameAttrMap.getDefault();
+ this.oid = oid;
+
+ // copy the value into the valueSet list
+ Enumeration vals = values.elements();
+ while (vals.hasMoreElements()) {
+ Object obj = vals.nextElement();
+ if (obj instanceof String)
+ valueSet.addElement(obj);
+ else
+ throw new IOException("values vectore must consist of String object");
+ }
}
/**
* Construct an attribute from attribute type and attribute values
- * @param oid attribute type string CN,OU,O,C,L,TITLE,ST,STREET,UID,MAIL,E,DC
+ *
+ * @param oid attribute type string
+ * CN,OU,O,C,L,TITLE,ST,STREET,UID,MAIL,E,DC
* @param values String value vector
*/
- public Attribute (String attr, Vector values)
- throws IOException
- {
+ public Attribute(String attr, Vector values)
+ throws IOException {
- //pre-condition verification
+ // pre-condition verification
if ((attr == null) || (values == null))
- throw new IOException("Invalid Input - null passed");
-
- ObjectIdentifier identifier = null;
+ throw new IOException("Invalid Input - null passed");
+
+ ObjectIdentifier identifier = null;
try {
identifier = new ObjectIdentifier(attr);
} catch (Exception e) {
@@ -133,155 +136,150 @@ public final class Attribute implements Serializable, DerEncoder {
ObjectIdentifier id = identifier;
if (identifier == null) {
- attrMap = X500NameAttrMap.getDefault();
- id = attrMap.getOid(attr);
+ attrMap = X500NameAttrMap.getDefault();
+ id = attrMap.getOid(attr);
if (id == null)
- throw new IOException("Attr is not supported - does not contain in attr map");
+ throw new IOException("Attr is not supported - does not contain in attr map");
+ }
+ this.oid = id;
+
+ // copy the value into the valueSet list
+ Enumeration vals = values.elements();
+ while (vals.hasMoreElements()) {
+ Object obj = vals.nextElement();
+ if (obj instanceof String)
+ valueSet.addElement(obj);
+ else
+ throw new IOException("Values vectore must consist of String object");
}
- this.oid = id;
-
- //copy the value into the valueSet list
- Enumeration vals = values.elements();
- while (vals.hasMoreElements()) {
- Object obj = vals.nextElement();
- if (obj instanceof String)
- valueSet.addElement(obj);
- else
- throw new IOException("Values vectore must consist of String object");
- }
}
/**
- * Construct an attribute from a der encoded object. This der
- * der encoded value should represent the attribute object.
+ * Construct an attribute from a der encoded object. This der der encoded
+ * value should represent the attribute object.
+ *
* @param value the attribute object in der encode form.
*/
- public Attribute (DerValue val)
- throws IOException
- {
+ public Attribute(DerValue val)
+ throws IOException {
- //pre-condition verification
- if (val == null)
- throw new IOException("Invalid Input - null passed");
+ // pre-condition verification
+ if (val == null)
+ throw new IOException("Invalid Input - null passed");
- attrMap = X500NameAttrMap.getDefault();
+ attrMap = X500NameAttrMap.getDefault();
- decodeThis(val);
+ decodeThis(val);
}
- //========== PUBLIC METHODS ==================================
+ // ========== PUBLIC METHODS ==================================
- /**
+ /**
* Returns the OID in the Attribute.
+ *
* @return the ObjectIdentifier in this Attribute.
*/
- public ObjectIdentifier getOid()
- {
- return oid;
+ public ObjectIdentifier getOid() {
+ return oid;
}
/**
* Returns enumeration of values in this attribute.
+ *
* @return Enumeration of values of this Attribute.
*/
- public Enumeration getValues()
- {
- if (valueSet == null) return null;
- return valueSet.elements();
+ public Enumeration getValues() {
+ if (valueSet == null)
+ return null;
+ return valueSet.elements();
}
/**
- * Encodes the Attribute to a Der output stream.
- * Attribute are encoded as a SEQUENCE of two elements.
+ * Encodes the Attribute to a Der output stream. Attribute are encoded as a
+ * SEQUENCE of two elements.
+ *
* @param out The Der output stream.
*/
- public void encode(DerOutputStream out) throws IOException
- {
- encodeThis(out);
+ public void encode(DerOutputStream out) throws IOException {
+ encodeThis(out);
}
- /**
- * DER encode this object onto an output stream.
- * Implements the <code>DerEncoder</code> interface.
- *
- * @param out
- * the output stream on which to write the DER encoding.
- *
+ /**
+ * DER encode this object onto an output stream. Implements the
+ * <code>DerEncoder</code> interface.
+ *
+ * @param out the output stream on which to write the DER encoding.
+ *
* @exception IOException on encoding error.
*/
- public void derEncode (OutputStream out) throws IOException
- {
- encodeThis(out);
+ public void derEncode(OutputStream out) throws IOException {
+ encodeThis(out);
}
/**
* Prints a string version of this extension.
*/
- public String toString()
- {
- String theoid = "Attribute: "+oid+"\n";
- String values = "Values: ";
- Enumeration n = valueSet.elements();
- if (n.hasMoreElements()) {
- values += (String)n.nextElement();
- while (n.hasMoreElements())
- values+= ","+(String)n.nextElement();
- }
- return theoid+values+"\n";
+ public String toString() {
+ String theoid = "Attribute: " + oid + "\n";
+ String values = "Values: ";
+ Enumeration n = valueSet.elements();
+ if (n.hasMoreElements()) {
+ values += (String) n.nextElement();
+ while (n.hasMoreElements())
+ values += "," + (String) n.nextElement();
+ }
+ return theoid + values + "\n";
}
+ // ========== PRIVATE METHODS ==================================
- //========== PRIVATE METHODS ==================================
-
- //encode the attribute object
+ // encode the attribute object
private void encodeThis(OutputStream out)
- throws IOException
- {
- DerOutputStream tmp = new DerOutputStream ();
- DerOutputStream tmp2 = new DerOutputStream ();
-
- tmp.putOID (oid);
- encodeValueSet(tmp);
- tmp2.write (DerValue.tag_Sequence, tmp);
- out.write(tmp2.toByteArray());
+ throws IOException {
+ DerOutputStream tmp = new DerOutputStream();
+ DerOutputStream tmp2 = new DerOutputStream();
+
+ tmp.putOID(oid);
+ encodeValueSet(tmp);
+ tmp2.write(DerValue.tag_Sequence, tmp);
+ out.write(tmp2.toByteArray());
}
- //encode the attribute object
+ // encode the attribute object
private void encodeValueSet(OutputStream out)
- throws IOException
- {
- DerOutputStream tmp = new DerOutputStream ();
- DerOutputStream tmp2 = new DerOutputStream ();
+ throws IOException {
+ DerOutputStream tmp = new DerOutputStream();
+ DerOutputStream tmp2 = new DerOutputStream();
- //get the attribute converter
+ // get the attribute converter
AVAValueConverter converter = attrMap.getValueConverter(oid);
if (converter == null) {
converter = new GenericValueConverter();
- //throw new IOException("Converter not found: unsupported attribute type");
+ // throw new
+ // IOException("Converter not found: unsupported attribute type");
}
- //loop through all the values and encode
- Enumeration vals = valueSet.elements();
- while (vals.hasMoreElements()) {
+ // loop through all the values and encode
+ Enumeration vals = valueSet.elements();
+ while (vals.hasMoreElements()) {
String val = (String) vals.nextElement();
- DerValue derobj = converter.getValue(val);
- derobj.encode(tmp);
- }
+ DerValue derobj = converter.getValue(val);
+ derobj.encode(tmp);
+ }
- tmp2.write (DerValue.tag_SetOf, tmp);
- out.write(tmp2.toByteArray());
+ tmp2.write(DerValue.tag_SetOf, tmp);
+ out.write(tmp2.toByteArray());
}
- //decode the attribute object
+ // decode the attribute object
private void decodeThis(DerValue val)
- throws IOException
- {
+ throws IOException {
- //pre-condition verification
- if (val == null) {
- throw new IOException("Invalid Input - null passed.");
- }
+ // pre-condition verification
+ if (val == null) {
+ throw new IOException("Invalid Input - null passed.");
+ }
if (val.tag != DerValue.tag_Sequence) {
throw new IOException("Invalid encoding for Attribute.");
@@ -291,31 +289,31 @@ public final class Attribute implements Serializable, DerEncoder {
throw new IOException("No data available in "
+ "passed DER encoded value.");
}
- this.oid = val.data.getDerValue().getOID();
+ this.oid = val.data.getDerValue().getOID();
if (val.data.available() == 0) {
throw new IOException("Invalid encoding for Attribute - value missing");
}
- decodeValueSet(val.data.getDerValue());
+ decodeValueSet(val.data.getDerValue());
- if (this.oid == null)
- throw new IOException("Invalid encoding for Attribute - OID missing");
+ if (this.oid == null)
+ throw new IOException("Invalid encoding for Attribute - OID missing");
}
- //decode the attribute value set
+ // decode the attribute value set
private void decodeValueSet(DerValue val)
- throws IOException
- {
- //pre-condition verification
- if (val == null) {
- throw new IOException("Invalid Input - null passed.");
- }
-
- AVAValueConverter converter = attrMap.getValueConverter(this.oid);
- if (converter == null) {
+ throws IOException {
+ // pre-condition verification
+ if (val == null) {
+ throw new IOException("Invalid Input - null passed.");
+ }
+
+ AVAValueConverter converter = attrMap.getValueConverter(this.oid);
+ if (converter == null) {
converter = new GenericValueConverter();
- //throw new IOException("Attribute is not supported - not in attr map");
+ // throw new
+ // IOException("Attribute is not supported - not in attr map");
}
if (val.tag != DerValue.tag_SetOf) {
@@ -326,13 +324,12 @@ public final class Attribute implements Serializable, DerEncoder {
throw new IOException("No data available in "
+ "passed DER encoded attribute value set.");
}
-
- //get the value set
- while (val.data.available() != 0) {
- DerValue value = val.data.getDerValue();
- valueSet.addElement(converter.getAsString(value));
- }
+
+ // get the value set
+ while (val.data.available() != 0) {
+ DerValue value = val.data.getDerValue();
+ valueSet.addElement(converter.getAsString(value));
+ }
}
}
-
diff --git a/pki/base/util/src/netscape/security/x509/AuthorityKeyIdentifierExtension.java b/pki/base/util/src/netscape/security/x509/AuthorityKeyIdentifierExtension.java
index 6e330f8a..367416b3 100644
--- a/pki/base/util/src/netscape/security/x509/AuthorityKeyIdentifierExtension.java
+++ b/pki/base/util/src/netscape/security/x509/AuthorityKeyIdentifierExtension.java
@@ -29,14 +29,15 @@ import netscape.security.util.DerValue;
/**
* This class represents the Authority Key Identifier Extension.
- *
- * <p>The authority key identifier extension provides a means of
- * identifying the particular public key used to sign a certificate.
- * This extension would be used where an issuer has multiple signing
- * keys (either due to multiple concurrent key pairs or due to
- * changeover).
+ *
+ * <p>
+ * The authority key identifier extension provides a means of identifying the
+ * particular public key used to sign a certificate. This extension would be
+ * used where an issuer has multiple signing keys (either due to multiple
+ * concurrent key pairs or due to changeover).
* <p>
* The ASN.1 syntax for this is:
+ *
* <pre>
* AuthorityKeyIdentifier ::= SEQUENCE {
* keyIdentifier [0] KeyIdentifier OPTIONAL,
@@ -45,6 +46,7 @@ import netscape.security.util.DerValue;
* }
* KeyIdentifier ::= OCTET STRING
* </pre>
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.9
@@ -52,15 +54,15 @@ import netscape.security.util.DerValue;
* @see CertAttrSet
*/
public class AuthorityKeyIdentifierExtension extends Extension
-implements CertAttrSet {
+ implements CertAttrSet {
/**
*
*/
private static final long serialVersionUID = -157913621972354170L;
/**
- * Identifier for this attribute, to be used with the
- * get, set, delete methods of Certificate, x509 type.
- */
+ * Identifier for this attribute, to be used with the get, set, delete
+ * methods of Certificate, x509 type.
+ */
public static final String IDENT =
"x509.info.extensions.AuthorityKeyIdentifier";
/**
@@ -75,9 +77,9 @@ implements CertAttrSet {
private static final byte TAG_NAMES = 1;
private static final byte TAG_SERIAL_NUM = 2;
- private KeyIdentifier id = null;
- private GeneralNames names = null;
- private SerialNumber serialNum = null;
+ private KeyIdentifier id = null;
+ private GeneralNames names = null;
+ private SerialNumber serialNum = null;
// Encode only the extension value
private void encodeThis() throws IOException {
@@ -91,9 +93,9 @@ implements CertAttrSet {
}
try {
if (names != null) {
- DerOutputStream tmp1 = new DerOutputStream();
- names.encode(tmp1);
- tmp.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
+ DerOutputStream tmp1 = new DerOutputStream();
+ names.encode(tmp1);
+ tmp.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
true, TAG_NAMES), tmp1);
}
} catch (Exception e) {
@@ -102,7 +104,7 @@ implements CertAttrSet {
if (serialNum != null) {
DerOutputStream tmp1 = new DerOutputStream();
serialNum.encode(tmp1);
- tmp.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
+ tmp.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
false, TAG_SERIAL_NUM), tmp1);
}
seq.write(DerValue.tag_Sequence, tmp);
@@ -112,10 +114,10 @@ implements CertAttrSet {
/**
* Exposed critical parameter. 99/11/03
*/
- public AuthorityKeyIdentifierExtension(boolean critical,
- KeyIdentifier kid, GeneralNames name,
+ public AuthorityKeyIdentifierExtension(boolean critical,
+ KeyIdentifier kid, GeneralNames name,
SerialNumber sn)
- throws IOException {
+ throws IOException {
this.id = kid;
this.names = name;
this.serialNum = sn;
@@ -126,18 +128,18 @@ implements CertAttrSet {
}
/**
- * The default constructor for this extension. Null parameters make
- * the element optional (not present).
- *
+ * The default constructor for this extension. Null parameters make the
+ * element optional (not present).
+ *
* @param id the KeyIdentifier associated with this extension.
* @param names the GeneralNames associated with this extension
- * @param serialNum the CertificateSerialNumber associated with
- * this extension.
+ * @param serialNum the CertificateSerialNumber associated with this
+ * extension.
* @exception IOException on error.
*/
public AuthorityKeyIdentifierExtension(KeyIdentifier kid, GeneralNames name,
SerialNumber sn)
- throws IOException {
+ throws IOException {
this.id = kid;
this.names = name;
this.serialNum = sn;
@@ -149,13 +151,13 @@ implements CertAttrSet {
/**
* Create the extension from the passed DER encoded value of the same.
- *
+ *
* @param critical true if the extension is to be treated as critical.
* @param value Array of DER encoded bytes of the actual value.
* @exception IOException on error.
*/
public AuthorityKeyIdentifierExtension(Boolean critical, Object value)
- throws IOException {
+ throws IOException {
this.extensionId = PKIXExtensions.AuthorityKey_Id;
this.critical = critical.booleanValue();
@@ -163,7 +165,7 @@ implements CertAttrSet {
throw new IOException("Illegal argument type");
int len = Array.getLength(value);
- byte[] extValue = new byte[len];
+ byte[] extValue = new byte[len];
System.arraycopy(value, 0, extValue, 0, len);
this.extensionValue = extValue;
@@ -174,14 +176,14 @@ implements CertAttrSet {
}
// NB. this is always encoded with the IMPLICIT tag
- // The checks only make sense if we assume implicit tagging,
- // with explicit tagging the form is always constructed.
+ // The checks only make sense if we assume implicit tagging,
+ // with explicit tagging the form is always constructed.
while (val.data.available() != 0) {
DerValue opt = val.data.getDerValue();
if (opt.isContextSpecific(TAG_ID) && !opt.isConstructed()) {
if (id != null)
- throw new IOException("Duplicate KeyIdentifier in " +
+ throw new IOException("Duplicate KeyIdentifier in " +
"AuthorityKeyIdentifier.");
opt.resetTag(DerValue.tag_OctetString);
id = new KeyIdentifier(opt);
@@ -189,27 +191,27 @@ implements CertAttrSet {
} else if (opt.isContextSpecific(TAG_NAMES) &&
opt.isConstructed()) {
if (names != null)
- throw new IOException("Duplicate GeneralNames in " +
+ throw new IOException("Duplicate GeneralNames in " +
"AuthorityKeyIdentifier.");
- try {
+ try {
opt.resetTag(DerValue.tag_Sequence);
names = new GeneralNames(opt);
- } catch (GeneralNamesException e) {
- throw new IOException(e.toString());
+ } catch (GeneralNamesException e) {
+ throw new IOException(e.toString());
}
} else if (opt.isContextSpecific(TAG_SERIAL_NUM) &&
!opt.isConstructed()) {
if (serialNum != null)
- throw new IOException("Duplicate SerialNumber in " +
+ throw new IOException("Duplicate SerialNumber in " +
"AuthorityKeyIdentifier.");
opt.resetTag(DerValue.tag_Integer);
serialNum = new SerialNumber(opt);
} else
throw new IOException("Invalid encoding of " +
"AuthorityKeyIdentifierExtension.");
- }
}
+ }
/**
* Return the object as a string.
@@ -230,7 +232,7 @@ implements CertAttrSet {
/**
* Decode the extension from the InputStream.
- *
+ *
* @param in the InputStream to unmarshal the contents from.
* @exception IOException on decoding or validity errors.
*/
@@ -240,7 +242,7 @@ implements CertAttrSet {
/**
* Write the extension to the OutputStream.
- *
+ *
* @param out the OutputStream to write the extension to.
* @exception IOException on error.
*/
@@ -252,7 +254,7 @@ implements CertAttrSet {
encodeThis();
}
super.encode(tmp);
- out.write(tmp.toByteArray());
+ out.write(tmp.toByteArray());
}
/**
@@ -260,73 +262,73 @@ implements CertAttrSet {
*/
public void set(String name, Object obj) throws IOException {
clearValue();
- if (name.equalsIgnoreCase(KEY_ID)) {
- if (!(obj instanceof KeyIdentifier)) {
- throw new IOException("Attribute value should be of " +
+ if (name.equalsIgnoreCase(KEY_ID)) {
+ if (!(obj instanceof KeyIdentifier)) {
+ throw new IOException("Attribute value should be of " +
"type KeyIdentifier.");
- }
- id = (KeyIdentifier)obj;
- } else if (name.equalsIgnoreCase(AUTH_NAME)) {
- if (!(obj instanceof GeneralNames)) {
- throw new IOException("Attribute value should be of " +
+ }
+ id = (KeyIdentifier) obj;
+ } else if (name.equalsIgnoreCase(AUTH_NAME)) {
+ if (!(obj instanceof GeneralNames)) {
+ throw new IOException("Attribute value should be of " +
"type GeneralNames.");
- }
- names = (GeneralNames)obj;
- } else if (name.equalsIgnoreCase(SERIAL_NUMBER)) {
- if (!(obj instanceof SerialNumber)) {
- throw new IOException("Attribute value should be of " +
+ }
+ names = (GeneralNames) obj;
+ } else if (name.equalsIgnoreCase(SERIAL_NUMBER)) {
+ if (!(obj instanceof SerialNumber)) {
+ throw new IOException("Attribute value should be of " +
"type SerialNumber.");
- }
- serialNum = (SerialNumber)obj;
- } else {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:AuthorityKeyIdentifier.");
- }
+ }
+ serialNum = (SerialNumber) obj;
+ } else {
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:AuthorityKeyIdentifier.");
+ }
}
/**
* Get the attribute value.
*/
public Object get(String name) throws IOException {
- if (name.equalsIgnoreCase(KEY_ID)) {
- return (id);
- } else if (name.equalsIgnoreCase(AUTH_NAME)) {
- return (names);
- } else if (name.equalsIgnoreCase(SERIAL_NUMBER)) {
- return (serialNum);
- } else {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:AuthorityKeyIdentifier.");
- }
+ if (name.equalsIgnoreCase(KEY_ID)) {
+ return (id);
+ } else if (name.equalsIgnoreCase(AUTH_NAME)) {
+ return (names);
+ } else if (name.equalsIgnoreCase(SERIAL_NUMBER)) {
+ return (serialNum);
+ } else {
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:AuthorityKeyIdentifier.");
+ }
}
/**
* Delete the attribute value.
*/
public void delete(String name) throws IOException {
- if (name.equalsIgnoreCase(KEY_ID)) {
- id = null;
- } else if (name.equalsIgnoreCase(AUTH_NAME)) {
- names = null;
- } else if (name.equalsIgnoreCase(SERIAL_NUMBER)) {
- serialNum = null;
- } else {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:AuthorityKeyIdentifier.");
- }
+ if (name.equalsIgnoreCase(KEY_ID)) {
+ id = null;
+ } else if (name.equalsIgnoreCase(AUTH_NAME)) {
+ names = null;
+ } else if (name.equalsIgnoreCase(SERIAL_NUMBER)) {
+ serialNum = null;
+ } else {
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:AuthorityKeyIdentifier.");
+ }
}
/**
* Return an enumeration of names of attributes existing within this
* attribute.
*/
- public Enumeration<String> getAttributeNames () {
+ public Enumeration<String> getAttributeNames() {
Vector<String> elements = new Vector<String>();
elements.addElement(KEY_ID);
elements.addElement(AUTH_NAME);
elements.addElement(SERIAL_NUMBER);
- return (elements.elements());
+ return (elements.elements());
}
}
diff --git a/pki/base/util/src/netscape/security/x509/BasicConstraintsExtension.java b/pki/base/util/src/netscape/security/x509/BasicConstraintsExtension.java
index a92625a8..d2e93f49 100644
--- a/pki/base/util/src/netscape/security/x509/BasicConstraintsExtension.java
+++ b/pki/base/util/src/netscape/security/x509/BasicConstraintsExtension.java
@@ -30,11 +30,12 @@ import netscape.security.util.DerValue;
/**
* This class represents the Basic Constraints Extension.
- *
- * <p>The basic constraints extension identifies whether the subject of the
- * certificate is a CA and how deep a certification path may exist
- * through that CA.
- *
+ *
+ * <p>
+ * The basic constraints extension identifies whether the subject of the
+ * certificate is a CA and how deep a certification path may exist through that
+ * CA.
+ *
* <pre>
* The ASN.1 syntax for this extension is:
* BasicConstraints ::= SEQUENCE {
@@ -42,6 +43,7 @@ import netscape.security.util.DerValue;
* pathLenConstraint INTEGER (0..MAX) OPTIONAL
* }
* </pre>
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.7
@@ -49,15 +51,15 @@ import netscape.security.util.DerValue;
* @see Extension
*/
public class BasicConstraintsExtension extends Extension
-implements CertAttrSet {
+ implements CertAttrSet {
/**
*
*/
private static final long serialVersionUID = 6213957094939885889L;
/**
- * Identifier for this attribute, to be used with the
- * get, set, delete methods of Certificate, x509 type.
- */
+ * Identifier for this attribute, to be used with the get, set, delete
+ * methods of Certificate, x509 type.
+ */
public static final String IDENT = "x509.info.extensions.BasicConstraints";
/**
* Attribute names.
@@ -66,8 +68,8 @@ implements CertAttrSet {
public static final String PATH_LEN = "path_len";
// Private data members
- private boolean ca = false;
- private int pathLen = -1;
+ private boolean ca = false;
+ private int pathLen = -1;
// Encode this extension value
private void encodeThis() throws IOException {
@@ -86,7 +88,7 @@ implements CertAttrSet {
/**
* Default constructor for this object.
- *
+ *
* @param ca true, if the subject of the Certificate is a CA.
* @param len specifies the depth of the certification path.
*/
@@ -104,7 +106,7 @@ implements CertAttrSet {
/**
* Default constructor for this object.
- *
+ *
* @param ca true, if the subject of the Certificate is a CA.
* @param len specifies the depth of the certification path.
*/
@@ -118,80 +120,76 @@ implements CertAttrSet {
/**
* Create the extension from the passed DER encoded value of the same.
- *
+ *
* @param extension the DER encoded value of the extension.
* @exception IOException on error.
*/
- public BasicConstraintsExtension(Boolean critical, Object value)
- throws IOException {
- this.extensionId = PKIXExtensions.BasicConstraints_Id;
- this.critical = critical.booleanValue();
+ public BasicConstraintsExtension(Boolean critical, Object value)
+ throws IOException {
+ this.extensionId = PKIXExtensions.BasicConstraints_Id;
+ this.critical = critical.booleanValue();
- if (value instanceof byte[]) {
- int len = Array.getLength(value);
- byte[] extValue = new byte[len];
- System.arraycopy(value, 0, extValue, 0, len);
+ if (value instanceof byte[]) {
+ int len = Array.getLength(value);
+ byte[] extValue = new byte[len];
+ System.arraycopy(value, 0, extValue, 0, len);
- this.extensionValue = extValue;
- DerValue val = new DerValue(extValue);
- if (val.tag != DerValue.tag_Sequence) {
- throw new IOException("Invalid encoding of BasicConstraints");
- }
+ this.extensionValue = extValue;
+ DerValue val = new DerValue(extValue);
+ if (val.tag != DerValue.tag_Sequence) {
+ throw new IOException("Invalid encoding of BasicConstraints");
+ }
- // non-CA cert with no limit to certification path length
- if (val.data == null || val.data.available() < 1) {
- this.ca = false;
- this.pathLen = -1;
- return;
- }
- DerValue opt = val.data.getDerValue();
- if (opt.tag != DerValue.tag_Boolean) {
- this.ca = false;
- } else {
- this.ca = true;
- if (val.data.available() != 0) {
- opt = val.data.getDerValue();
- } else {
- this.pathLen = -1;
- return;
- }
- }
- if (opt.tag != DerValue.tag_Integer) {
- throw new IOException("Invalid encoding of BasicConstraints");
- }
- this.pathLen = (opt.getInteger()).toInt();
- /*
- * Activate this check once again after PKIX profiling
- * is a standard and this check no longer imposes an
- * interoperability barrier.
- * if (ca) {
- * if (!this.critical) {
- * throw new IOException("Criticality cannot be false for CA.");
- * }
- * }
- */
- } else
- throw new IOException("Invalid argument type");
- }
+ // non-CA cert with no limit to certification path length
+ if (val.data == null || val.data.available() < 1) {
+ this.ca = false;
+ this.pathLen = -1;
+ return;
+ }
+ DerValue opt = val.data.getDerValue();
+ if (opt.tag != DerValue.tag_Boolean) {
+ this.ca = false;
+ } else {
+ this.ca = true;
+ if (val.data.available() != 0) {
+ opt = val.data.getDerValue();
+ } else {
+ this.pathLen = -1;
+ return;
+ }
+ }
+ if (opt.tag != DerValue.tag_Integer) {
+ throw new IOException("Invalid encoding of BasicConstraints");
+ }
+ this.pathLen = (opt.getInteger()).toInt();
+ /*
+ * Activate this check once again after PKIX profiling is a standard
+ * and this check no longer imposes an interoperability barrier. if
+ * (ca) { if (!this.critical) { throw new
+ * IOException("Criticality cannot be false for CA."); } }
+ */
+ } else
+ throw new IOException("Invalid argument type");
+ }
- /**
- * Return user readable form of extension.
- */
- public String toString() {
- String s = super.toString() + "BasicConstraints:[\n";
+ /**
+ * Return user readable form of extension.
+ */
+ public String toString() {
+ String s = super.toString() + "BasicConstraints:[\n";
- s += ((ca) ? ("CA:true") : ("CA:false")) + "\n";
- if (pathLen >= 0) {
- s += "PathLen:" + pathLen + "\n";
- } else {
- s += "PathLen: undefined\n";
- }
- return (s + "]\n");
- }
+ s += ((ca) ? ("CA:true") : ("CA:false")) + "\n";
+ if (pathLen >= 0) {
+ s += "PathLen:" + pathLen + "\n";
+ } else {
+ s += "PathLen: undefined\n";
+ }
+ return (s + "]\n");
+ }
/**
* Decode the extension from the InputStream.
- *
+ *
* @param in the InputStream to unmarshal the contents from.
* @exception IOException on decoding or validity errors.
*/
@@ -199,77 +197,73 @@ implements CertAttrSet {
throw new IOException("Method not to be called directly.");
}
- /**
- * Encode this extension value to the output stream.
- *
- * @param out the DerOutputStream to encode the extension to.
- */
- public void encode(OutputStream out) throws IOException {
- DerOutputStream tmp = new DerOutputStream();
- if (extensionValue == null) {
- this.extensionId = PKIXExtensions.BasicConstraints_Id;
-/* #57286 - so that profile can set critiality */
-/*
- if (ca) {
- critical = true;
- } else {
- critical = false;
- }
-*/
- encodeThis();
- }
- super.encode(tmp);
+ /**
+ * Encode this extension value to the output stream.
+ *
+ * @param out the DerOutputStream to encode the extension to.
+ */
+ public void encode(OutputStream out) throws IOException {
+ DerOutputStream tmp = new DerOutputStream();
+ if (extensionValue == null) {
+ this.extensionId = PKIXExtensions.BasicConstraints_Id;
+ /* #57286 - so that profile can set critiality */
+ /*
+ * if (ca) { critical = true; } else { critical = false; }
+ */
+ encodeThis();
+ }
+ super.encode(tmp);
- out.write(tmp.toByteArray());
- }
+ out.write(tmp.toByteArray());
+ }
/**
* Set the attribute value.
*/
public void set(String name, Object obj) throws IOException {
clearValue();
- if (name.equalsIgnoreCase(IS_CA)) {
- if (!(obj instanceof Boolean)) {
- throw new IOException("Attribute value should be of type Boolean.");
- }
- ca = ((Boolean)obj).booleanValue();
- } else if (name.equalsIgnoreCase(PATH_LEN)) {
- if (!(obj instanceof Integer)) {
- throw new IOException("Attribute value should be of type Integer.");
- }
- pathLen = ((Integer)obj).intValue();
- } else {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:BasicConstraints.");
- }
+ if (name.equalsIgnoreCase(IS_CA)) {
+ if (!(obj instanceof Boolean)) {
+ throw new IOException("Attribute value should be of type Boolean.");
+ }
+ ca = ((Boolean) obj).booleanValue();
+ } else if (name.equalsIgnoreCase(PATH_LEN)) {
+ if (!(obj instanceof Integer)) {
+ throw new IOException("Attribute value should be of type Integer.");
+ }
+ pathLen = ((Integer) obj).intValue();
+ } else {
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:BasicConstraints.");
+ }
}
/**
* Get the attribute value.
*/
public Object get(String name) throws IOException {
- if (name.equalsIgnoreCase(IS_CA)) {
- return (new Boolean(ca));
- } else if (name.equalsIgnoreCase(PATH_LEN)) {
- return (Integer.valueOf(pathLen));
- } else {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:BasicConstraints.");
- }
+ if (name.equalsIgnoreCase(IS_CA)) {
+ return (new Boolean(ca));
+ } else if (name.equalsIgnoreCase(PATH_LEN)) {
+ return (Integer.valueOf(pathLen));
+ } else {
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:BasicConstraints.");
+ }
}
/**
* Delete the attribute value.
*/
public void delete(String name) throws IOException {
- if (name.equalsIgnoreCase(IS_CA)) {
- ca = false;
- } else if (name.equalsIgnoreCase(PATH_LEN)) {
- pathLen = -1;
- } else {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:BasicConstraints.");
- }
+ if (name.equalsIgnoreCase(IS_CA)) {
+ ca = false;
+ } else if (name.equalsIgnoreCase(PATH_LEN)) {
+ pathLen = -1;
+ } else {
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:BasicConstraints.");
+ }
}
/**
@@ -281,7 +275,7 @@ implements CertAttrSet {
elements.addElement(IS_CA);
elements.addElement(PATH_LEN);
- return (elements.elements());
+ return (elements.elements());
}
}
diff --git a/pki/base/util/src/netscape/security/x509/CPSuri.java b/pki/base/util/src/netscape/security/x509/CPSuri.java
index 52ac0322..d0a2e076 100644
--- a/pki/base/util/src/netscape/security/x509/CPSuri.java
+++ b/pki/base/util/src/netscape/security/x509/CPSuri.java
@@ -22,12 +22,11 @@ import java.io.IOException;
import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
-
/**
* Represent the CPSuri Qualifier.
- *
+ *
* CPSuri ::= IA5String;
- *
+ *
* @author Thomas Kwan
*/
public class CPSuri extends Qualifier {
@@ -40,25 +39,25 @@ public class CPSuri extends Qualifier {
/**
* Create a PolicyQualifierInfo
- *
+ *
* @param id the ObjectIdentifier for the policy id.
*/
public CPSuri(String uri) {
- mURI = uri;
+ mURI = uri;
}
public CPSuri(DerValue val) throws IOException {
- mURI = val.getIA5String();
+ mURI = val.getIA5String();
}
/**
* Write the PolicyQualifier to the DerOutputStream.
- *
+ *
* @param out the DerOutputStream to write the object to.
* @exception IOException on errors.
*/
public void encode(DerOutputStream out) throws IOException {
- out.putIA5String(mURI);
+ out.putIA5String(mURI);
}
public String getURI() {
diff --git a/pki/base/util/src/netscape/security/x509/CRLDistributionPoint.java b/pki/base/util/src/netscape/security/x509/CRLDistributionPoint.java
index 8c88ec7e..f5043bac 100644
--- a/pki/base/util/src/netscape/security/x509/CRLDistributionPoint.java
+++ b/pki/base/util/src/netscape/security/x509/CRLDistributionPoint.java
@@ -43,11 +43,11 @@ import org.mozilla.jss.asn1.Tag;
* distributionPoint [0] DistributionPointName OPTIONAL,
* reasons [1] ReasonFlags OPTIONAL,
* cRLIssuer [2] GeneralNames OPTIONAL }
- *
+ *
* DistributionPointName ::= CHOICE {
* fullName [0] GeneralNames,
* nameRelativeToCRLIssuer [1] RelativeDistinguishedName }
- *
+ *
* ReasonFlags ::= BIT STRING {
* unused (0),
* keyCompromise (1),
@@ -90,31 +90,29 @@ public class CRLDistributionPoint implements ASN1Value {
}
/**
- * Sets the <code>fullName</code> of the
- * <code>DistributionPointName</code>. It may be set to <code>null</code>.
- * If it is set to a non-null value, <code>relativeName</code> will be
- * set to <code>null</code>, because at most one of these two attributes
- * can be specified at a time.
- * @exception GeneralNamesException If an error occurs encoding the
- * name.
+ * Sets the <code>fullName</code> of the <code>DistributionPointName</code>.
+ * It may be set to <code>null</code>. If it is set to a non-null value,
+ * <code>relativeName</code> will be set to <code>null</code>, because at
+ * most one of these two attributes can be specified at a time.
+ *
+ * @exception GeneralNamesException If an error occurs encoding the name.
*/
public void setFullName(GeneralNames fullName)
- throws GeneralNamesException, IOException
- {
+ throws GeneralNamesException, IOException {
this.fullName = fullName;
- if( fullName != null ) {
+ if (fullName != null) {
// encode the name to catch any problems with it
DerOutputStream derOut = new DerOutputStream();
fullName.encode(derOut);
try {
ANY raw = new ANY(derOut.toByteArray());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
- raw.encodeWithAlternateTag( Tag.get(0), bos );
- fullNameEncoding = new ANY( bos.toByteArray() );
- } catch(InvalidBERException e) {
+ raw.encodeWithAlternateTag(Tag.get(0), bos);
+ fullNameEncoding = new ANY(bos.toByteArray());
+ } catch (InvalidBERException e) {
// assume this won't happen, since it would imply a bug
// in DerOutputStream
- throw new GeneralNamesException( e.toString() );
+ throw new GeneralNamesException(e.toString());
}
this.relativeName = null;
@@ -123,20 +121,20 @@ public class CRLDistributionPoint implements ASN1Value {
/**
* Sets the <code>relativeName</code> of the
- * <code>DistributionPointName</code>. It may be set to <code>null</code>.
- * If it is set to a non-null value, <code>fullName</code> will be
- * set to <code>null</code>, because at most one of these two attributes
- * can be specified at a time.
+ * <code>DistributionPointName</code>. It may be set to <code>null</code>.
+ * If it is set to a non-null value, <code>fullName</code> will be set to
+ * <code>null</code>, because at most one of these two attributes can be
+ * specified at a time.
*/
public void setRelativeName(RDN relativeName) {
this.relativeName = relativeName;
- if( relativeName != null ) {
+ if (relativeName != null) {
this.fullName = null;
}
}
/**
- * Returns the reason flags for this distribution point. May be
+ * Returns the reason flags for this distribution point. May be
* <code>null</code>.
*/
public BitArray getReasons() {
@@ -144,50 +142,49 @@ public class CRLDistributionPoint implements ASN1Value {
}
/**
- * Sets the reason flags for this distribution point. May be set to
+ * Sets the reason flags for this distribution point. May be set to
* <code>null</code>.
*/
public void setReasons(BitArray reasons) {
this.reasons = reasons;
}
-
/**
- * Returns the CRLIssuer for the CRL at this distribution point.
- * May be <code>null</code>.
+ * Returns the CRLIssuer for the CRL at this distribution point. May be
+ * <code>null</code>.
*/
public GeneralNames getCRLIssuer() {
return CRLIssuer;
}
/**
- * Sets the CRLIssuer for the CRL at this distribution point.
- * May be set to <code>null</code>.
+ * Sets the CRLIssuer for the CRL at this distribution point. May be set to
+ * <code>null</code>.
+ *
* @exception GeneralNamesException If an error occurs encoding the name.
*/
public void setCRLIssuer(GeneralNames CRLIssuer)
- throws GeneralNamesException, IOException
- {
+ throws GeneralNamesException, IOException {
this.CRLIssuer = CRLIssuer;
-
- if( CRLIssuer != null ) {
+
+ if (CRLIssuer != null) {
// encode the name to catch any problems with it
DerOutputStream derOut = new DerOutputStream();
CRLIssuer.encode(derOut);
try {
- ANY raw = new ANY( derOut.toByteArray() );
+ ANY raw = new ANY(derOut.toByteArray());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
- raw.encodeWithAlternateTag( Tag.get(2), bos);
+ raw.encodeWithAlternateTag(Tag.get(2), bos);
CRLIssuerEncoding = new ANY(bos.toByteArray());
- } catch(InvalidBERException e) {
+ } catch (InvalidBERException e) {
throw new GeneralNamesException(e.toString());
}
}
}
- /////////////////////////////////////////////////////////////
+ // ///////////////////////////////////////////////////////////
// DER encoding
- /////////////////////////////////////////////////////////////
+ // ///////////////////////////////////////////////////////////
private static final Tag TAG = SEQUENCE.TAG;
@@ -200,53 +197,52 @@ public class CRLDistributionPoint implements ASN1Value {
}
public void encode(Tag implicitTag, OutputStream ostream)
- throws IOException
- {
+ throws IOException {
SEQUENCE seq = new SEQUENCE();
DerOutputStream derOut;
- try {
-
- // Encodes the DistributionPointName. Because DistributionPointName
- // is a CHOICE, the [0] tag is forced to be EXPLICIT.
- if( fullName != null ) {
- EXPLICIT distPoint = new EXPLICIT( Tag.get(0), fullNameEncoding);
- seq.addElement( distPoint );
- } else if( relativeName != null ) {
- derOut = new DerOutputStream();
- relativeName.encode(derOut);
- ANY rn = new ANY(derOut.toByteArray());
- EXPLICIT raw = new EXPLICIT( Tag.get(1), rn );
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- raw.encode( bos );
- ANY distPointName = new ANY(bos.toByteArray());
- EXPLICIT distPoint = new EXPLICIT( Tag.get(0), distPointName);
- seq.addElement( distPoint );
- }
+ try {
+
+ // Encodes the DistributionPointName. Because DistributionPointName
+ // is a CHOICE, the [0] tag is forced to be EXPLICIT.
+ if (fullName != null) {
+ EXPLICIT distPoint = new EXPLICIT(Tag.get(0), fullNameEncoding);
+ seq.addElement(distPoint);
+ } else if (relativeName != null) {
+ derOut = new DerOutputStream();
+ relativeName.encode(derOut);
+ ANY rn = new ANY(derOut.toByteArray());
+ EXPLICIT raw = new EXPLICIT(Tag.get(1), rn);
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ raw.encode(bos);
+ ANY distPointName = new ANY(bos.toByteArray());
+ EXPLICIT distPoint = new EXPLICIT(Tag.get(0), distPointName);
+ seq.addElement(distPoint);
+ }
- // Encodes the ReasonFlags.
- if( reasons != null ) {
- derOut = new DerOutputStream();
- derOut.putUnalignedBitString(reasons);
- ANY raw = new ANY(derOut.toByteArray());
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- raw.encodeWithAlternateTag(Tag.get(1), bos);
- ANY reasonEncoding = new ANY(bos.toByteArray());
- seq.addElement( Tag.get(1), reasonEncoding);
- }
+ // Encodes the ReasonFlags.
+ if (reasons != null) {
+ derOut = new DerOutputStream();
+ derOut.putUnalignedBitString(reasons);
+ ANY raw = new ANY(derOut.toByteArray());
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ raw.encodeWithAlternateTag(Tag.get(1), bos);
+ ANY reasonEncoding = new ANY(bos.toByteArray());
+ seq.addElement(Tag.get(1), reasonEncoding);
+ }
- // Encodes the CRLIssuer
- if( CRLIssuer != null ) {
- seq.addElement( Tag.get(2), CRLIssuerEncoding );
- }
+ // Encodes the CRLIssuer
+ if (CRLIssuer != null) {
+ seq.addElement(Tag.get(2), CRLIssuerEncoding);
+ }
- seq.encode(implicitTag, ostream);
+ seq.encode(implicitTag, ostream);
- } catch(InvalidBERException e) {
- // this shouldn't happen unless there is a bug in one of
+ } catch (InvalidBERException e) {
+ // this shouldn't happen unless there is a bug in one of
// the Sun encoding classes
throw new IOException(e.toString());
- }
+ }
}
// Template singleton
@@ -260,223 +256,208 @@ public class CRLDistributionPoint implements ASN1Value {
}
public static void main(String args[]) {
- try {
- if( args.length != 1 ) {
- System.out.println("Usage: CRLDistributionPoint <outfile>");
- System.exit(-1);
- }
-
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
-
- SEQUENCE cdps = new SEQUENCE();
-
- // URI only
- CRLDistributionPoint cdp = new CRLDistributionPoint();
- URIName uri = new URIName("http://www.mycrl.com/go/here");
- GeneralNames generalNames = new GeneralNames();
- generalNames.addElement(uri);
- cdp.setFullName(generalNames);
- cdps.addElement(cdp);
-
- // DN only
- cdp = new CRLDistributionPoint();
- X500Name dn = new X500Name("CN=Otis Smith,E=otis@fedoraproject.org"+
- ",OU=Certificate Server,O=Fedora,C=US");
- generalNames = new GeneralNames();
- generalNames.addElement(dn);
- cdp.setFullName(generalNames);
- cdps.addElement(cdp);
-
- // DN + reason
- BitArray ba = new BitArray(5, new byte[] {(byte)0x28} );
- cdp = new CRLDistributionPoint();
- cdp.setFullName(generalNames);
- cdp.setReasons(ba);
- cdps.addElement(cdp);
-
-
- // relative DN + reason + crlIssuer
- cdp = new CRLDistributionPoint();
- RDN rdn = new RDN("OU=foobar dept");
- cdp.setRelativeName(rdn);
- cdp.setReasons(ba);
- cdp.setCRLIssuer(generalNames);
- cdps.addElement(cdp);
-
- cdps.encode(bos);
-
- byte[] encoded = bos.toByteArray();
- (new FileOutputStream(args[0])).write(encoded);
-
- SEQUENCE.OF_Template seqt = new SEQUENCE.OF_Template(getTemplate());
-
- cdps = (SEQUENCE) ASN1Util.decode(seqt, encoded);
-
- int size = cdps.size();
- System.out.println("Total number of CDPs: " + size);
- for( int i = 0; i < size; i++) {
- System.out.println("\nCDP " + i);
- cdp = (CRLDistributionPoint) cdps.elementAt(i);
- GeneralNames gn = cdp.getFullName();
- if( gn == null ) {
- System.out.println("No full name");
- } else {
- System.out.println(gn);
- }
- rdn = cdp.getRelativeName();
- if( rdn == null ) {
- System.out.println("No relative name");
- } else {
- System.out.println(rdn);
- }
- if( cdp.getReasons() == null ) {
- System.out.println("No reasons");
- } else {
- System.out.println(cdp.getReasons());
- }
- gn = cdp.getCRLIssuer();
- if( gn == null ) {
- System.out.println("No cRLIssuer");
- } else {
- System.out.println(gn);
+ try {
+ if (args.length != 1) {
+ System.out.println("Usage: CRLDistributionPoint <outfile>");
+ System.exit(-1);
}
- }
- System.out.println("Done");
-
-
- } catch(Exception e) {
- e.printStackTrace();
- }
- }
-
-/**
- * Template for decoding CRLDistributionPoint.
- */
-public static class Template implements ASN1Template {
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
- public boolean tagMatch(Tag tag) {
- return TAG.equals(tag);
- }
+ SEQUENCE cdps = new SEQUENCE();
+
+ // URI only
+ CRLDistributionPoint cdp = new CRLDistributionPoint();
+ URIName uri = new URIName("http://www.mycrl.com/go/here");
+ GeneralNames generalNames = new GeneralNames();
+ generalNames.addElement(uri);
+ cdp.setFullName(generalNames);
+ cdps.addElement(cdp);
+
+ // DN only
+ cdp = new CRLDistributionPoint();
+ X500Name dn = new X500Name("CN=Otis Smith,E=otis@fedoraproject.org" +
+ ",OU=Certificate Server,O=Fedora,C=US");
+ generalNames = new GeneralNames();
+ generalNames.addElement(dn);
+ cdp.setFullName(generalNames);
+ cdps.addElement(cdp);
+
+ // DN + reason
+ BitArray ba = new BitArray(5, new byte[] { (byte) 0x28 });
+ cdp = new CRLDistributionPoint();
+ cdp.setFullName(generalNames);
+ cdp.setReasons(ba);
+ cdps.addElement(cdp);
+
+ // relative DN + reason + crlIssuer
+ cdp = new CRLDistributionPoint();
+ RDN rdn = new RDN("OU=foobar dept");
+ cdp.setRelativeName(rdn);
+ cdp.setReasons(ba);
+ cdp.setCRLIssuer(generalNames);
+ cdps.addElement(cdp);
+
+ cdps.encode(bos);
+
+ byte[] encoded = bos.toByteArray();
+ (new FileOutputStream(args[0])).write(encoded);
+
+ SEQUENCE.OF_Template seqt = new SEQUENCE.OF_Template(getTemplate());
+
+ cdps = (SEQUENCE) ASN1Util.decode(seqt, encoded);
+
+ int size = cdps.size();
+ System.out.println("Total number of CDPs: " + size);
+ for (int i = 0; i < size; i++) {
+ System.out.println("\nCDP " + i);
+ cdp = (CRLDistributionPoint) cdps.elementAt(i);
+ GeneralNames gn = cdp.getFullName();
+ if (gn == null) {
+ System.out.println("No full name");
+ } else {
+ System.out.println(gn);
+ }
+ rdn = cdp.getRelativeName();
+ if (rdn == null) {
+ System.out.println("No relative name");
+ } else {
+ System.out.println(rdn);
+ }
+ if (cdp.getReasons() == null) {
+ System.out.println("No reasons");
+ } else {
+ System.out.println(cdp.getReasons());
+ }
+ gn = cdp.getCRLIssuer();
+ if (gn == null) {
+ System.out.println("No cRLIssuer");
+ } else {
+ System.out.println(gn);
+ }
+ }
+ System.out.println("Done");
- public ASN1Value decode(InputStream istream)
- throws IOException, InvalidBERException
- {
- return decode(TAG, istream);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
}
- public ASN1Value decode(Tag implicitTag, InputStream istream)
- throws IOException, InvalidBERException
- {
- CRLDistributionPoint cdp = new CRLDistributionPoint();
-
- //
- // construct the top-level sequence
- //
-
- SEQUENCE.Template seqt = SEQUENCE.getTemplate();
-
- // distributionPoint
- seqt.addOptionalElement(
- new EXPLICIT.Template(Tag.get(0), ANY.getTemplate()) );
+ /**
+ * Template for decoding CRLDistributionPoint.
+ */
+ public static class Template implements ASN1Template {
- // reasons
- seqt.addOptionalElement( Tag.get(1), BIT_STRING.getTemplate());
+ public boolean tagMatch(Tag tag) {
+ return TAG.equals(tag);
+ }
- // cRLIssuer
- // This will have a tag of 2, but we can't say that here
- // because ANYs can't have implicit tags. We don't need to say
- // it, because we do check the tags on the other two elements
- // in the sequence, so we'll know if we get this one.
- seqt.addOptionalElement( ANY.getTemplate() );
+ public ASN1Value decode(InputStream istream)
+ throws IOException, InvalidBERException {
+ return decode(TAG, istream);
+ }
- //
- // decode the top-level sequence
- //
- SEQUENCE top = (SEQUENCE) seqt.decode(implicitTag, istream);
+ public ASN1Value decode(Tag implicitTag, InputStream istream)
+ throws IOException, InvalidBERException {
+ CRLDistributionPoint cdp = new CRLDistributionPoint();
+
+ //
+ // construct the top-level sequence
+ //
+
+ SEQUENCE.Template seqt = SEQUENCE.getTemplate();
+
+ // distributionPoint
+ seqt.addOptionalElement(
+ new EXPLICIT.Template(Tag.get(0), ANY.getTemplate()));
+
+ // reasons
+ seqt.addOptionalElement(Tag.get(1), BIT_STRING.getTemplate());
+
+ // cRLIssuer
+ // This will have a tag of 2, but we can't say that here
+ // because ANYs can't have implicit tags. We don't need to say
+ // it, because we do check the tags on the other two elements
+ // in the sequence, so we'll know if we get this one.
+ seqt.addOptionalElement(ANY.getTemplate());
+
+ //
+ // decode the top-level sequence
+ //
+ SEQUENCE top = (SEQUENCE) seqt.decode(implicitTag, istream);
+
+ // decode the distribution point name
+ if (top.elementAt(0) != null) {
+ EXPLICIT exp = (EXPLICIT) top.elementAt(0);
+ ANY distPoint = (ANY) exp.getContent();
+ if (distPoint.getTag().equals(Tag.get(0))) {
+ // fullName
+ try {
+ DerValue dv = new DerValue(distPoint.getEncoded());
+ // toFile("encodedFullName", distPoint.getEncoded());
+ dv.resetTag(DerValue.tag_Sequence);
+ cdp.setFullName(new GeneralNames(dv));
+ } catch (GeneralNamesException e) {
+ throw new InvalidBERException("fullName: " + e.toString());
+ } catch (IOException e) {
+ throw new InvalidBERException("fullName: " + e.toString());
+ }
+ } else if (distPoint.getTag().equals(Tag.get(1))) {
+ // relative name
+ try {
+ DerValue dv = new DerValue(distPoint.getEncoded());
+ /*
+ * dv is as follows: 0 12: [1] { 2 10: SET { 4 8:
+ * SEQUENCE { 6 3: OBJECT IDENTIFIER commonName (2 5 4
+ * 3) 11 1: PrintableString 'x' : } : } : }
+ */
+ dv = dv.data.getDerValue(); // skipping the tag
+ /*
+ * after the skipping, we have: 0 10: SET { 2 8:
+ * SEQUENCE { 4 3: OBJECT IDENTIFIER commonName (2 5 4
+ * 3) 9 1: PrintableString 'x' : } : }
+ */
+ dv.resetTag(DerValue.tag_Set);
+ cdp.setRelativeName(new RDN(dv));
+ } catch (IOException e) {
+ throw new InvalidBERException("relativeName " +
+ e.toString());
+ }
+ } else {
+ throw new InvalidBERException(
+ "Unknown tag " + distPoint.getTag() +
+ " in distributionPoint");
+ }
+ }
+ // decode the reasons
+ if (top.elementAt(1) != null) {
+ BIT_STRING bs = (BIT_STRING) top.elementAt(1);
+ byte[] bits = bs.getBits();
+ cdp.setReasons(
+ new BitArray((bits.length * 8) - bs.getPadCount(), bits));
+ }
- // decode the distribution point name
- if( top.elementAt(0) != null ) {
- EXPLICIT exp = (EXPLICIT) top.elementAt(0);
- ANY distPoint = (ANY) exp.getContent();
- if( distPoint.getTag().equals(Tag.get(0)) ) {
- // fullName
- try {
- DerValue dv = new DerValue(distPoint.getEncoded());
- //toFile("encodedFullName", distPoint.getEncoded());
- dv.resetTag(DerValue.tag_Sequence);
- cdp.setFullName( new GeneralNames(dv) );
- } catch(GeneralNamesException e) {
- throw new InvalidBERException( "fullName: " + e.toString());
- } catch(IOException e) {
- throw new InvalidBERException( "fullName: " + e.toString());
+ // decode the cRLIssuer
+ if (top.elementAt(2) != null) {
+ ANY issuer = (ANY) top.elementAt(2);
+ if (!issuer.getTag().equals(Tag.get(2))) {
+ throw new InvalidBERException("Invalid tag " + issuer.getTag());
}
- } else if( distPoint.getTag().equals(Tag.get(1)) ) {
- // relative name
try {
- DerValue dv = new DerValue(distPoint.getEncoded());
- /* dv is as follows:
- 0 12: [1] {
- 2 10: SET {
- 4 8: SEQUENCE {
- 6 3: OBJECT IDENTIFIER commonName (2 5 4 3)
- 11 1: PrintableString 'x'
- : }
- : }
- : }
- */
- dv = dv.data.getDerValue(); // skipping the tag
- /* after the skipping, we have:
- 0 10: SET {
- 2 8: SEQUENCE {
- 4 3: OBJECT IDENTIFIER commonName (2 5 4 3)
- 9 1: PrintableString 'x'
- : }
- : }
- */
- dv.resetTag(DerValue.tag_Set);
- cdp.setRelativeName( new RDN(dv) );
- } catch(IOException e) {
- throw new InvalidBERException( "relativeName " +
- e.toString() );
+ DerValue dv = new DerValue(issuer.getEncoded());
+ dv.resetTag(DerValue.tag_Sequence);
+ cdp.setCRLIssuer(new GeneralNames(dv));
+ } catch (GeneralNamesException e) {
+ throw new InvalidBERException("cRLIssuer " + e.toString());
+ } catch (IOException e) {
+ throw new InvalidBERException("cRLIssuer " + e.toString());
}
- } else {
- throw new InvalidBERException(
- "Unknown tag " + distPoint.getTag() +
- " in distributionPoint" );
}
- }
- // decode the reasons
- if( top.elementAt(1) != null ) {
- BIT_STRING bs = (BIT_STRING) top.elementAt(1);
- byte[] bits = bs.getBits();
- cdp.setReasons(
- new BitArray( (bits.length * 8) - bs.getPadCount(), bits) );
- }
+ return cdp;
- // decode the cRLIssuer
- if( top.elementAt(2) != null ) {
- ANY issuer = (ANY) top.elementAt(2);
- if( ! issuer.getTag().equals(Tag.get(2)) ) {
- throw new InvalidBERException("Invalid tag " + issuer.getTag());
- }
- try {
- DerValue dv = new DerValue( issuer.getEncoded() );
- dv.resetTag(DerValue.tag_Sequence);
- cdp.setCRLIssuer( new GeneralNames(dv) );
- } catch(GeneralNamesException e) {
- throw new InvalidBERException( "cRLIssuer " + e.toString() );
- } catch(IOException e) {
- throw new InvalidBERException( "cRLIssuer " + e.toString() );
- }
}
-
- return cdp;
-
}
-}
-
}
diff --git a/pki/base/util/src/netscape/security/x509/CRLDistributionPointsExtension.java b/pki/base/util/src/netscape/security/x509/CRLDistributionPointsExtension.java
index 812d2e76..0e6f5dbc 100644
--- a/pki/base/util/src/netscape/security/x509/CRLDistributionPointsExtension.java
+++ b/pki/base/util/src/netscape/security/x509/CRLDistributionPointsExtension.java
@@ -35,21 +35,21 @@ import org.mozilla.jss.asn1.InvalidBERException;
import org.mozilla.jss.asn1.SEQUENCE;
/**
- * An extension that tells applications where to find the CRL for
- * this certificate.
- *
+ * An extension that tells applications where to find the CRL for this
+ * certificate.
+ *
* <pre>
* cRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
- *
+ *
* DistributionPoint ::= SEQUENCE {
* distributionPoint [0] DistributionPointName OPTIONAL,
* reasons [1] ReasonFlags OPTIONAL,
* cRLIssuer [2] GeneralNames OPTIONAL }
- *
+ *
* DistributionPointName ::= CHOICE {
* fullName [0] GeneralNames,
* nameRelativeToCRLIssuer [1] RelativeDistinguishedName }
- *
+ *
* ReasonFlags ::= BIT STRING {
* unused (0),
* keyCompromise (1),
@@ -61,8 +61,7 @@ import org.mozilla.jss.asn1.SEQUENCE;
* </pre>
*/
public class CRLDistributionPointsExtension extends Extension
- implements CertAttrSet
-{
+ implements CertAttrSet {
/**
*
@@ -72,7 +71,7 @@ public class CRLDistributionPointsExtension extends Extension
private SEQUENCE distributionPoints = new SEQUENCE();
// Cached DER-encoding to improve performance.
- private byte[] cachedEncoding=null;
+ private byte[] cachedEncoding = null;
/**
* This constructor is called by the CertificateExtensions class to decode
@@ -80,30 +79,30 @@ public class CRLDistributionPointsExtension extends Extension
* extension.
*/
public CRLDistributionPointsExtension(Boolean critical, Object value)
- //throws IOException
+ // throws IOException
{
- try {
-
- this.extensionId = PKIXExtensions.CRLDistributionPoints_Id;
- this.critical = critical.booleanValue();
- this.extensionValue = (byte[])((byte[])value).clone();
-
- // decode the value
try {
- SEQUENCE.OF_Template seqOfCRLDP =
- new SEQUENCE.OF_Template( CRLDistributionPoint.getTemplate() );
- distributionPoints =
- (SEQUENCE) ASN1Util.decode( seqOfCRLDP, extensionValue );
- } catch(InvalidBERException e) {
- throw new IOException("Invalid BER-encoding: " + e.toString());
+ this.extensionId = PKIXExtensions.CRLDistributionPoints_Id;
+ this.critical = critical.booleanValue();
+ this.extensionValue = (byte[]) ((byte[]) value).clone();
+
+ // decode the value
+ try {
+ SEQUENCE.OF_Template seqOfCRLDP =
+ new SEQUENCE.OF_Template(CRLDistributionPoint.getTemplate());
+
+ distributionPoints =
+ (SEQUENCE) ASN1Util.decode(seqOfCRLDP, extensionValue);
+ } catch (InvalidBERException e) {
+ throw new IOException("Invalid BER-encoding: " + e.toString());
+ }
+ } catch (IOException e) {
+ System.out.println("Big error");
+ System.out.println(e);
+ e.printStackTrace();
+ // throw e;
}
- } catch(IOException e) {
- System.out.println("Big error");
- System.out.println(e);
- e.printStackTrace();
- //throw e;
- }
}
/**
@@ -143,20 +142,18 @@ public class CRLDistributionPointsExtension extends Extension
return (CRLDistributionPoint) distributionPoints.elementAt(index);
}
- /**
- * Sets the criticality of this extension. PKIX dictates that this
- * extension SHOULD NOT be critical, so applications can make it critical
- * if they have a very good reason. By default, the extension is not
- * critical.
+ /**
+ * Sets the criticality of this extension. PKIX dictates that this extension
+ * SHOULD NOT be critical, so applications can make it critical if they have
+ * a very good reason. By default, the extension is not critical.
*/
public void setCritical(boolean critical) {
this.critical = critical;
}
/**
- * Encodes this extension to the given DerOutputStream.
- * This method re-encodes each time it is called, so it is not very
- * efficient.
+ * Encodes this extension to the given DerOutputStream. This method
+ * re-encodes each time it is called, so it is not very efficient.
*/
public void encode(DerOutputStream out) throws IOException {
extensionValue = ASN1Util.encode(distributionPoints);
@@ -164,25 +161,26 @@ public class CRLDistributionPointsExtension extends Extension
}
/**
- * Should be called if any change is made to this data structure
- * so that the cached DER encoding can be discarded.
+ * Should be called if any change is made to this data structure so that the
+ * cached DER encoding can be discarded.
*/
public void flushCachedEncoding() {
cachedEncoding = null;
}
- /////////////////////////////////////////////////////////////
+ // ///////////////////////////////////////////////////////////
// CertAttrSet interface
// This interface is not really appropriate for this extension
// because it is so complicated. Therefore, we only provide a
// minimal implementation.
- /////////////////////////////////////////////////////////////
+ // ///////////////////////////////////////////////////////////
- static {
- try {
+ static {
+ try {
OIDMap.addAttribute(CRLDistributionPointsExtension.class.getName(),
OID, CRLDistributionPointsExtension.class.getSimpleName());
- } catch (CertificateException e) {}
+ } catch (CertificateException e) {
+ }
}
public String toString() {
@@ -193,9 +191,8 @@ public class CRLDistributionPointsExtension extends Extension
* DER-encodes this extension to the given OutputStream.
*/
public void encode(OutputStream ostream)
- throws CertificateException, IOException
- {
- if( cachedEncoding == null ) {
+ throws CertificateException, IOException {
+ if (cachedEncoding == null) {
// only re-encode if necessary
DerOutputStream tmp = new DerOutputStream();
encode(tmp);
@@ -205,103 +202,96 @@ public class CRLDistributionPointsExtension extends Extension
}
public void decode(InputStream in)
- throws CertificateException, IOException
- {
+ throws CertificateException, IOException {
throw new IOException("Not supported");
}
public void set(String name, Object obj)
- throws CertificateException, IOException
- {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:CRLDistributionPointsExtension");
+ throws CertificateException, IOException {
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:CRLDistributionPointsExtension");
}
public Object get(String name)
- throws CertificateException, IOException
- {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:CRLDistributionPointsExtension");
+ throws CertificateException, IOException {
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:CRLDistributionPointsExtension");
}
public void delete(String name)
- throws CertificateException, IOException
- {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:CRLDistributionPointsExtension");
+ throws CertificateException, IOException {
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:CRLDistributionPointsExtension");
}
+
/*
- * TODO use an empty collection to generate these
+ * TODO use an empty collection to generate these
*/
public Enumeration<String> getAttributeNames() {
return (new Vector<String>()).elements();
}
-
-
/**
* Test driver.
*/
public static void main(String args[]) {
- try {
-
- if( args.length != 1 ) {
- System.out.println("Usage: CRLDistributionPointsExtentions "+
- "<outfile>");
- System.exit(-1);
- }
+ try {
- BufferedOutputStream bos = new BufferedOutputStream(
- new FileOutputStream(args[0]) );
-
-
- // URI only
- CRLDistributionPoint cdp = new CRLDistributionPoint();
- URIName uri = new URIName("http://www.mycrl.com/go/here");
- GeneralNames generalNames = new GeneralNames();
- generalNames.addElement(uri);
- cdp.setFullName(generalNames);
- CRLDistributionPointsExtension crldpExt =
- new CRLDistributionPointsExtension(cdp);
-
- // DN only
- cdp = new CRLDistributionPoint();
- X500Name dn = new X500Name("CN=Otis Smith,E=otis@fedoraproject.org"+
- ",OU=Certificate Server,O=Fedora,C=US");
- generalNames = new GeneralNames();
- generalNames.addElement(dn);
- cdp.setFullName(generalNames);
- crldpExt.addPoint(cdp);
-
- // DN + reason
- BitArray ba = new BitArray(5, new byte[] {(byte)0x28} );
- cdp = new CRLDistributionPoint();
- cdp.setFullName(generalNames);
- cdp.setReasons(ba);
- crldpExt.addPoint(cdp);
-
-
- // relative DN + reason + crlIssuer
- cdp = new CRLDistributionPoint();
- RDN rdn = new RDN("OU=foobar dept");
- cdp.setRelativeName(rdn);
- cdp.setReasons(ba);
- cdp.setCRLIssuer(generalNames);
- crldpExt.addPoint(cdp);
-
- crldpExt.setCritical(true);
- crldpExt.encode(bos);
-
- bos.close();
-
- } catch(Exception e) {
+ if (args.length != 1) {
+ System.out.println("Usage: CRLDistributionPointsExtentions " +
+ "<outfile>");
+ System.exit(-1);
+ }
+
+ BufferedOutputStream bos = new BufferedOutputStream(
+ new FileOutputStream(args[0]));
+
+ // URI only
+ CRLDistributionPoint cdp = new CRLDistributionPoint();
+ URIName uri = new URIName("http://www.mycrl.com/go/here");
+ GeneralNames generalNames = new GeneralNames();
+ generalNames.addElement(uri);
+ cdp.setFullName(generalNames);
+ CRLDistributionPointsExtension crldpExt =
+ new CRLDistributionPointsExtension(cdp);
+
+ // DN only
+ cdp = new CRLDistributionPoint();
+ X500Name dn = new X500Name("CN=Otis Smith,E=otis@fedoraproject.org" +
+ ",OU=Certificate Server,O=Fedora,C=US");
+ generalNames = new GeneralNames();
+ generalNames.addElement(dn);
+ cdp.setFullName(generalNames);
+ crldpExt.addPoint(cdp);
+
+ // DN + reason
+ BitArray ba = new BitArray(5, new byte[] { (byte) 0x28 });
+ cdp = new CRLDistributionPoint();
+ cdp.setFullName(generalNames);
+ cdp.setReasons(ba);
+ crldpExt.addPoint(cdp);
+
+ // relative DN + reason + crlIssuer
+ cdp = new CRLDistributionPoint();
+ RDN rdn = new RDN("OU=foobar dept");
+ cdp.setRelativeName(rdn);
+ cdp.setReasons(ba);
+ cdp.setCRLIssuer(generalNames);
+ crldpExt.addPoint(cdp);
+
+ crldpExt.setCritical(true);
+ crldpExt.encode(bos);
+
+ bos.close();
+
+ } catch (Exception e) {
e.printStackTrace();
- }
+ }
}
- /**
- * Represents a reason that a cert may be revoked. These reasons are
+ /**
+ * Represents a reason that a cert may be revoked. These reasons are
* expressed in a ReasonFlags bit string.
*/
public static class Reason {
@@ -309,19 +299,21 @@ public class CRLDistributionPointsExtension extends Extension
private String name;
private byte bitMask;
- private Reason() { }
+ private Reason() {
+ }
+
private Reason(String name, byte bitMask) {
this.name = name;
this.bitMask = bitMask;
map.put(name, this);
- list.addElement(this);
+ list.addElement(this);
}
private static Hashtable<String, Reason> map = new Hashtable<String, Reason>();
- private static Vector<Reason> list = new Vector<Reason>();
+ private static Vector<Reason> list = new Vector<Reason>();
public static Reason fromString(String name) {
- return map.get(name);
+ return map.get(name);
}
public String getName() {
@@ -332,61 +324,61 @@ public class CRLDistributionPointsExtension extends Extension
return bitMask;
}
- /**
- * Given a bit array representing reason flags, extracts the reasons
- * and returns them as an array.
- *
- * @param bitFlags A bit vector containing reason flags.
- * @return An array of reasons contained in the bit vector.
- * May be zero-length but will not be null.
- */
- public static Reason[] bitArrayToReasonArray(byte bitFlags) {
- return bitArrayToReasonArray( new byte[] { bitFlags } );
- }
-
- /**
- * Given a bit array representing reason flags, extracts the reasons
- * and returns them as an array. Currently, only the first byte
- * of the bitflags are examined.
- *
- * @param bitFlags A bit vector containing reason flags. The format
- * is big-endian (MSB first). Only the first byte is examined.
- * @return An array of reasons contained in the bit vector.
- * May be zero-length but will not be null.
- */
- public static Reason[] bitArrayToReasonArray(byte[] bitFlags) {
- byte first = bitFlags[0];
- int size = list.size();
- Vector<Reason> result = new Vector<Reason>();
- for(int i = 0; i < size; i++) {
- Reason r = list.elementAt(i);
- byte b = r.getBitMask();
- if( (first & b) != 0 ) {
- result.addElement(r);
- }
- }
- size = result.size();
- Reason[] retval = new Reason[size];
- for(int i=0; i < size; i++) {
- retval[i] = result.elementAt(i);
- }
- return retval;
- }
-
+ /**
+ * Given a bit array representing reason flags, extracts the reasons and
+ * returns them as an array.
+ *
+ * @param bitFlags A bit vector containing reason flags.
+ * @return An array of reasons contained in the bit vector. May be
+ * zero-length but will not be null.
+ */
+ public static Reason[] bitArrayToReasonArray(byte bitFlags) {
+ return bitArrayToReasonArray(new byte[] { bitFlags });
+ }
+
+ /**
+ * Given a bit array representing reason flags, extracts the reasons and
+ * returns them as an array. Currently, only the first byte of the
+ * bitflags are examined.
+ *
+ * @param bitFlags A bit vector containing reason flags. The format is
+ * big-endian (MSB first). Only the first byte is examined.
+ * @return An array of reasons contained in the bit vector. May be
+ * zero-length but will not be null.
+ */
+ public static Reason[] bitArrayToReasonArray(byte[] bitFlags) {
+ byte first = bitFlags[0];
+ int size = list.size();
+ Vector<Reason> result = new Vector<Reason>();
+ for (int i = 0; i < size; i++) {
+ Reason r = list.elementAt(i);
+ byte b = r.getBitMask();
+ if ((first & b) != 0) {
+ result.addElement(r);
+ }
+ }
+ size = result.size();
+ Reason[] retval = new Reason[size];
+ for (int i = 0; i < size; i++) {
+ retval[i] = result.elementAt(i);
+ }
+ return retval;
+ }
+
public static final Reason UNUSED =
- new Reason("unused", (byte) 0x80);
+ new Reason("unused", (byte) 0x80);
public static final Reason KEY_COMPROMISE =
- new Reason("keyCompromise", (byte) 0x40);
+ new Reason("keyCompromise", (byte) 0x40);
public static final Reason CA_COMPROMISE =
- new Reason("cACompromise", (byte) 0x20);
+ new Reason("cACompromise", (byte) 0x20);
public static final Reason AFFILIATION_CHANGED =
- new Reason("affiliationChanged", (byte) 0x10);
+ new Reason("affiliationChanged", (byte) 0x10);
public static final Reason SUPERSEDED =
- new Reason("superseded", (byte) 0x08);
+ new Reason("superseded", (byte) 0x08);
public static final Reason CESSATION_OF_OPERATION =
- new Reason("cessationOfOperation", (byte) 0x04);
+ new Reason("cessationOfOperation", (byte) 0x04);
public static final Reason CERTIFICATE_HOLD =
- new Reason("certificateHold", (byte) 0x02);
+ new Reason("certificateHold", (byte) 0x02);
}
}
diff --git a/pki/base/util/src/netscape/security/x509/CRLExtensions.java b/pki/base/util/src/netscape/security/x509/CRLExtensions.java
index bba44eab..909cc60f 100755
--- a/pki/base/util/src/netscape/security/x509/CRLExtensions.java
+++ b/pki/base/util/src/netscape/security/x509/CRLExtensions.java
@@ -35,7 +35,7 @@ import netscape.security.util.DerValue;
/**
* This class defines the CRL Extensions.
- *
+ *
* @author Hemma Prafullchandra
* @version 1.4
*/
@@ -45,13 +45,13 @@ public class CRLExtensions extends Vector<Extension> {
*
*/
private static final long serialVersionUID = 365767738692986418L;
- private Hashtable<String,Extension> map;
+ private Hashtable<String, Extension> map;
// Parse the encoded extension
private void parseExtension(Extension ext) throws X509ExtensionException {
try {
Class<?> extClass = OIDMap.getClass(ext.getExtensionId());
- if (extClass == null) { // Unsupported extension
+ if (extClass == null) { // Unsupported extension
if (ext.isCritical()) {
throw new IOException("Unsupported CRITICAL extension: "
+ ext.getExtensionId());
@@ -65,23 +65,23 @@ public class CRLExtensions extends Vector<Extension> {
Constructor<?> cons = extClass.getConstructor(params);
byte[] extData = ext.getExtensionValue();
int extLen = extData.length;
- Object value = Array.newInstance(byte.class, extLen);
-
- for (int i = 0; i < extLen; i++) {
- Array.setByte(value, i, extData[i]);
- }
- Object[] passed = new Object[] {new Boolean(ext.isCritical()),
- value};
- CertAttrSet crlExt = (CertAttrSet)cons.newInstance(passed);
- map.put(crlExt.getName(), (Extension) crlExt);
+ Object value = Array.newInstance(byte.class, extLen);
+
+ for (int i = 0; i < extLen; i++) {
+ Array.setByte(value, i, extData[i]);
+ }
+ Object[] passed = new Object[] { new Boolean(ext.isCritical()),
+ value };
+ CertAttrSet crlExt = (CertAttrSet) cons.newInstance(passed);
+ map.put(crlExt.getName(), (Extension) crlExt);
addElement((Extension) crlExt);
} catch (InvocationTargetException invk) {
- throw new X509ExtensionException(
+ throw new X509ExtensionException(
invk.getTargetException().getMessage());
- } catch (Exception e) {
- throw new X509ExtensionException(e.toString());
+ } catch (Exception e) {
+ throw new X509ExtensionException(e.toString());
}
}
@@ -94,13 +94,13 @@ public class CRLExtensions extends Vector<Extension> {
/**
* Create the object, decoding the values from the passed DER stream.
- *
+ *
* @param in the DerInputStream to read the Extension from.
* @exception CRLException on decoding errors.
* @exception X509ExtensionException on extension handling errors.
*/
public CRLExtensions(DerInputStream in)
- throws CRLException, X509ExtensionException {
+ throws CRLException, X509ExtensionException {
map = new Hashtable<String, Extension>();
try {
@@ -117,13 +117,13 @@ public class CRLExtensions extends Vector<Extension> {
/**
* Decode the extensions from the InputStream.
- *
+ *
* @param in the InputStream to unmarshal the contents from.
* @exception CRLException on decoding or validity errors.
* @exception X509ExtensionException on extension handling errors.
*/
public void decode(InputStream in)
- throws CRLException, X509ExtensionException {
+ throws CRLException, X509ExtensionException {
try {
DerValue val = new DerValue(in);
DerInputStream str = val.toDerInputStream();
@@ -142,25 +142,25 @@ public class CRLExtensions extends Vector<Extension> {
/**
* Encode the extensions in DER form to the stream.
- *
+ *
* @param out the DerOutputStream to marshal the contents to.
- * @param isExplicit the tag indicating whether this is an entry
- * extension or a CRL extension.
+ * @param isExplicit the tag indicating whether this is an entry extension
+ * or a CRL extension.
* @exception CRLException on encoding errors.
*/
public void encode(OutputStream out, boolean isExplicit)
- throws CRLException {
+ throws CRLException {
try {
- // #381559
+ // #381559
if (size() == 0)
- return;
+ return;
DerOutputStream extOut = new DerOutputStream();
for (int i = 0; i < size(); i++) {
Object thisOne = elementAt(i);
if (thisOne instanceof CertAttrSet)
- ((CertAttrSet)thisOne).encode(extOut);
+ ((CertAttrSet) thisOne).encode(extOut);
else if (thisOne instanceof Extension)
- ((Extension)thisOne).encode(extOut);
+ ((Extension) thisOne).encode(extOut);
else
throw new CRLException("Illegal extension object");
}
@@ -171,7 +171,7 @@ public class CRLExtensions extends Vector<Extension> {
DerOutputStream tmp = new DerOutputStream();
if (isExplicit)
tmp.write(DerValue.createTag(DerValue.TAG_CONTEXT,
- true, (byte)0), seq);
+ true, (byte) 0), seq);
else
tmp = seq;
@@ -185,7 +185,7 @@ public class CRLExtensions extends Vector<Extension> {
/**
* Get the extension with this alias.
- *
+ *
* @param alias the identifier string for the extension to retrieve.
* @exception X509ExtensionException on extension handling errors.
*/
@@ -195,10 +195,10 @@ public class CRLExtensions extends Vector<Extension> {
String id = attr.getPrefix();
if (id.equalsIgnoreCase(X509CertImpl.NAME)) { // fully qualified
int index = alias.lastIndexOf(".");
- name = alias.substring(index + 1);
+ name = alias.substring(index + 1);
} else
name = alias;
- Extension ext = (Extension)map.get(name);
+ Extension ext = (Extension) map.get(name);
if (ext == null)
throw new X509ExtensionException("No extension found with name: "
+ alias);
@@ -207,12 +207,11 @@ public class CRLExtensions extends Vector<Extension> {
/**
* Set the extension value with this alias.
- *
+ *
* @param alias the identifier string for the extension to set.
- * @param obj the Object to set the extension identified by the
- * alias.
+ * @param obj the Object to set the extension identified by the alias.
* @exception IOException on errors.
- */
+ */
public void set(String alias, Extension obj) throws IOException {
map.put(alias, obj);
addElement(obj);
@@ -220,9 +219,10 @@ public class CRLExtensions extends Vector<Extension> {
/**
* Return an enumeration of names of the extensions.
- * @return an enumeration of the names of the extensions in this CRL.
- */
- public Enumeration<Extension> getElements () {
+ *
+ * @return an enumeration of the names of the extensions in this CRL.
+ */
+ public Enumeration<Extension> getElements() {
return (map.elements());
}
}
diff --git a/pki/base/util/src/netscape/security/x509/CRLNumberExtension.java b/pki/base/util/src/netscape/security/x509/CRLNumberExtension.java
index 8376662f..c83b5cf1 100755
--- a/pki/base/util/src/netscape/security/x509/CRLNumberExtension.java
+++ b/pki/base/util/src/netscape/security/x509/CRLNumberExtension.java
@@ -31,20 +31,20 @@ import netscape.security.util.DerValue;
/**
* Represent the CRL Number Extension.
- *
- * <p>This extension, if present, conveys a monotonically increasing
- * sequence number for each CRL issued by a given CA through a specific
- * CA X.500 Directory entry or CRL distribution point. This extension
- * allows users to easily determine when a particular CRL supersedes
- * another CRL.
- *
+ *
+ * <p>
+ * This extension, if present, conveys a monotonically increasing sequence
+ * number for each CRL issued by a given CA through a specific CA X.500
+ * Directory entry or CRL distribution point. This extension allows users to
+ * easily determine when a particular CRL supersedes another CRL.
+ *
* @author Hemma Prafullchandra
* @version 1.2
* @see Extension
* @see CertAttrSet
*/
public class CRLNumberExtension extends Extension
-implements CertAttrSet {
+ implements CertAttrSet {
/**
*
@@ -67,9 +67,9 @@ implements CertAttrSet {
}
/**
- * Create a CRLNumberExtension with the integer value .
- * The criticality is set to false.
- *
+ * Create a CRLNumberExtension with the integer value . The criticality is
+ * set to false.
+ *
* @param crlNum the value to be set for the extension.
*/
public CRLNumberExtension(int crlNum) throws IOException {
@@ -80,9 +80,9 @@ implements CertAttrSet {
}
/**
- * Create a CRLNumberExtension with the BigInteger value .
- * The criticality is set to false.
- *
+ * Create a CRLNumberExtension with the BigInteger value . The criticality
+ * is set to false.
+ *
* @param crlNum the value to be set for the extension.
*/
public CRLNumberExtension(BigInteger crlNum) throws IOException {
@@ -94,7 +94,7 @@ implements CertAttrSet {
/**
* Create a CRLNumberExtension with the BigInteger value .
- *
+ *
* @param critical true if the extension is to be treated as critical.
* @param crlNum the value to be set for the extension.
*/
@@ -107,21 +107,21 @@ implements CertAttrSet {
/**
* Create the extension from the passed DER encoded value of the same.
- *
+ *
* @param critical true if the extension is to be treated as critical.
* @param value Array of DER encoded bytes of the actual value.
* @exception IOException on error.
*/
public CRLNumberExtension(Boolean critical, Object value)
- throws IOException {
+ throws IOException {
this.extensionId = PKIXExtensions.CRLNumber_Id;
this.critical = critical.booleanValue();
int len = Array.getLength(value);
- byte[] extValue = new byte[len];
- for (int i = 0; i < len; i++) {
- extValue[i] = Array.getByte(value, i);
- }
+ byte[] extValue = new byte[len];
+ for (int i = 0; i < len; i++) {
+ extValue[i] = Array.getByte(value, i);
+ }
this.extensionValue = extValue;
DerValue val = new DerValue(extValue);
this.crlNumber = val.getInteger();
@@ -131,40 +131,42 @@ implements CertAttrSet {
* Set the attribute value.
*/
public void set(String name, Object obj) throws IOException {
- if (name.equalsIgnoreCase(NUMBER)) {
+ if (name.equalsIgnoreCase(NUMBER)) {
if (!(obj instanceof BigInteger)) {
- throw new IOException("Attribute must be of type BigInteger.");
- }
- crlNumber = new BigInt((BigInteger)obj);
- } else {
- throw new IOException("Attribute name not recognized by"
+ throw new IOException("Attribute must be of type BigInteger.");
+ }
+ crlNumber = new BigInt((BigInteger) obj);
+ } else {
+ throw new IOException("Attribute name not recognized by"
+ " CertAttrSet:CRLNumber.");
- }
+ }
}
/**
* Get the attribute value.
*/
public Object get(String name) throws IOException {
- if (name.equalsIgnoreCase(NUMBER)) {
- if (crlNumber == null) return null;
- else return crlNumber.toBigInteger();
- } else {
- throw new IOException("Attribute name not recognized by"
+ if (name.equalsIgnoreCase(NUMBER)) {
+ if (crlNumber == null)
+ return null;
+ else
+ return crlNumber.toBigInteger();
+ } else {
+ throw new IOException("Attribute name not recognized by"
+ " CertAttrSet:CRLNumber.");
- }
+ }
}
/**
* Delete the attribute value.
*/
public void delete(String name) throws IOException {
- if (name.equalsIgnoreCase(NUMBER)) {
+ if (name.equalsIgnoreCase(NUMBER)) {
crlNumber = null;
- } else {
- throw new IOException("Attribute name not recognized by"
+ } else {
+ throw new IOException("Attribute name not recognized by"
+ " CertAttrSet:CRLNumber.");
- }
+ }
}
/**
@@ -179,7 +181,7 @@ implements CertAttrSet {
/**
* Decode the extension from the InputStream.
- *
+ *
* @param in the InputStream to unmarshal the contents from.
* @exception IOException on decoding or validity errors.
*/
@@ -189,30 +191,30 @@ implements CertAttrSet {
/**
* Write the extension to the DerOutputStream.
- *
+ *
* @param out the DerOutputStream to write the extension to.
* @exception IOException on encoding errors.
*/
public void encode(OutputStream out) throws IOException {
- DerOutputStream tmp = new DerOutputStream();
-
- if (this.extensionValue == null) {
- this.extensionId = PKIXExtensions.CRLNumber_Id;
- this.critical = false;
- encodeThis();
- }
- super.encode(tmp);
- out.write(tmp.toByteArray());
+ DerOutputStream tmp = new DerOutputStream();
+
+ if (this.extensionValue == null) {
+ this.extensionId = PKIXExtensions.CRLNumber_Id;
+ this.critical = false;
+ encodeThis();
+ }
+ super.encode(tmp);
+ out.write(tmp.toByteArray());
}
/**
* Return an enumeration of names of attributes existing within this
* attribute.
*/
- public Enumeration<String> getAttributeNames () {
+ public Enumeration<String> getAttributeNames() {
Vector<String> elements = new Vector<String>();
elements.addElement(NUMBER);
- return (elements.elements());
+ return (elements.elements());
}
- }
+}
diff --git a/pki/base/util/src/netscape/security/x509/CRLReasonExtension.java b/pki/base/util/src/netscape/security/x509/CRLReasonExtension.java
index 363e54bf..313d552d 100644
--- a/pki/base/util/src/netscape/security/x509/CRLReasonExtension.java
+++ b/pki/base/util/src/netscape/security/x509/CRLReasonExtension.java
@@ -28,17 +28,18 @@ import netscape.security.util.DerValue;
/**
* Represent the CRLReason Extension of CRL entry.
- *
- * <p>This extension, if present, defines the identifies
- * the reason for the certificate revocation.
- *
+ *
+ * <p>
+ * This extension, if present, defines the identifies the reason for the
+ * certificate revocation.
+ *
* @author galperin
* @version $Revision$, $Date$
* @see Extension
* @see CertAttrSet
*/
-public final class CRLReasonExtension extends Extension implements CertAttrSet {
+public final class CRLReasonExtension extends Extension implements CertAttrSet {
/**
*
@@ -61,7 +62,7 @@ public final class CRLReasonExtension extends Extension implements CertAttrSet
/**
* Attribute names.
*/
- public static final String REASON = "value";
+ public static final String REASON = "value";
private RevocationReason mReason = null;
@@ -71,19 +72,18 @@ public final class CRLReasonExtension extends Extension implements CertAttrSet
/**
* Default constructor
- *
+ *
*/
public CRLReasonExtension() {
this.extensionId = PKIXExtensions.ReasonCode_Id;
this.critical = false;
- mReason = null;
+ mReason = null;
}
-
/**
* Create extension value for specific revocation reason
- *
+ *
*/
public CRLReasonExtension(RevocationReason reason) {
@@ -93,7 +93,7 @@ public final class CRLReasonExtension extends Extension implements CertAttrSet
}
public CRLReasonExtension(Boolean critical, RevocationReason reason)
- throws IOException {
+ throws IOException {
this.extensionId = PKIXExtensions.ReasonCode_Id;
this.critical = critical.booleanValue();
mReason = reason;
@@ -101,18 +101,18 @@ public final class CRLReasonExtension extends Extension implements CertAttrSet
/**
* Create the object from the passed DER encoded value.
- *
+ *
* @param derVal the DerValue decoded from the stream.
* @exception IOException on decoding errors.
*/
public CRLReasonExtension(Boolean critical, Object value)
- throws IOException {
- this.extensionId = PKIXExtensions.ReasonCode_Id;
+ throws IOException {
+ this.extensionId = PKIXExtensions.ReasonCode_Id;
this.critical = critical.booleanValue();
- byte[] extValue = (byte[])((byte[])value).clone();
- this.extensionValue = extValue;
- DerValue val = new DerValue(extValue);
+ byte[] extValue = (byte[]) ((byte[]) value).clone();
+ this.extensionValue = extValue;
+ DerValue val = new DerValue(extValue);
int reasonCode = val.getEnumerated();
mReason = RevocationReason.fromInt(reasonCode);
if (mReason == null)
@@ -124,36 +124,36 @@ public final class CRLReasonExtension extends Extension implements CertAttrSet
*/
public void set(String name, Object obj) throws IOException {
if (!(obj instanceof RevocationReason)) {
- throw new IOException("Attribute must be of type RevocationReason.");
- }
-
- if (name.equalsIgnoreCase(REASON)) {
- mReason = (RevocationReason)obj;
- } else {
- throw new IOException("Name not recognized by CRLReason");
- }
+ throw new IOException("Attribute must be of type RevocationReason.");
+ }
+
+ if (name.equalsIgnoreCase(REASON)) {
+ mReason = (RevocationReason) obj;
+ } else {
+ throw new IOException("Name not recognized by CRLReason");
+ }
}
/**
* Get the attribute value.
*/
public Object get(String name) throws IOException {
- if (name.equalsIgnoreCase(REASON)) {
- return mReason;
- } else {
- throw new IOException("Name not recognized by CRLReason");
- }
+ if (name.equalsIgnoreCase(REASON)) {
+ return mReason;
+ } else {
+ throw new IOException("Name not recognized by CRLReason");
+ }
}
/**
* Delete the attribute value.
*/
public void delete(String name) throws IOException {
- if (name.equalsIgnoreCase(REASON)) {
- mReason = null;
- } else {
- throw new IOException("Name not recognized by CRLReason");
- }
+ if (name.equalsIgnoreCase(REASON)) {
+ mReason = null;
+ } else {
+ throw new IOException("Name not recognized by CRLReason");
+ }
}
/**
@@ -166,7 +166,7 @@ public final class CRLReasonExtension extends Extension implements CertAttrSet
/**
* Decode the extension from the InputStream.
- *
+ *
* @param in the InputStream to unmarshal the contents from.
* @exception IOException on decoding or validity errors.
*/
@@ -183,21 +183,20 @@ public final class CRLReasonExtension extends Extension implements CertAttrSet
this.extensionValue = os.toByteArray();
}
-
/**
* Write the extension to the DerOutputStream.
- *
+ *
* @param out the OutputStream to write the extension to.
* @exception IOException on encoding errors.
*/
public void encode(OutputStream out) throws IOException {
- DerOutputStream tmp = new DerOutputStream();
+ DerOutputStream tmp = new DerOutputStream();
- if (this.extensionValue == null) {
- encodeThis();
- }
- super.encode(tmp);
- out.write(tmp.toByteArray());
+ if (this.extensionValue == null) {
+ encodeThis();
+ }
+ super.encode(tmp);
+ out.write(tmp.toByteArray());
}
@@ -205,22 +204,21 @@ public final class CRLReasonExtension extends Extension implements CertAttrSet
* Return an enumeration of names of attributes existing within this
* attribute.
*/
- public Enumeration<String> getAttributeNames () {
+ public Enumeration<String> getAttributeNames() {
Vector<String> elements = new Vector<String>();
elements.addElement(REASON);
- return (elements.elements());
+ return (elements.elements());
}
-
- public boolean equals(Object other) {
- if (this == other)
- return true;
- else if (other instanceof CRLReasonExtension)
- return ((CRLReasonExtension)other).mReason == mReason &&
- ((CRLReasonExtension)other).critical == critical;
- else
- return false;
- }
+ public boolean equals(Object other) {
+ if (this == other)
+ return true;
+ else if (other instanceof CRLReasonExtension)
+ return ((CRLReasonExtension) other).mReason == mReason &&
+ ((CRLReasonExtension) other).critical == critical;
+ else
+ return false;
+ }
}
diff --git a/pki/base/util/src/netscape/security/x509/CertAndKeyGen.java b/pki/base/util/src/netscape/security/x509/CertAndKeyGen.java
index 644bfe7e..dc3c020c 100644
--- a/pki/base/util/src/netscape/security/x509/CertAndKeyGen.java
+++ b/pki/base/util/src/netscape/security/x509/CertAndKeyGen.java
@@ -35,26 +35,28 @@ import java.util.Date;
import netscape.security.pkcs.PKCS10;
-
/**
- * Generate a pair of keys, and provide access to them. This class is
- * provided primarily for ease of use.
- *
- * <P>This provides some simple certificate management functionality.
- * Specifically, it allows you to create self-signed X.509 certificates
- * as well as PKCS 10 based certificate signing requests.
- *
- * <P>Keys for some public key signature algorithms have algorithm
- * parameters, such as DSS/DSA. Some sites' Certificate Authorities
- * adopt fixed algorithm parameters, which speeds up some operations
- * including key generation and signing. <em>At this time, this interface
+ * Generate a pair of keys, and provide access to them. This class is provided
+ * primarily for ease of use.
+ *
+ * <P>
+ * This provides some simple certificate management functionality. Specifically,
+ * it allows you to create self-signed X.509 certificates as well as PKCS 10
+ * based certificate signing requests.
+ *
+ * <P>
+ * Keys for some public key signature algorithms have algorithm parameters, such
+ * as DSS/DSA. Some sites' Certificate Authorities adopt fixed algorithm
+ * parameters, which speeds up some operations including key generation and
+ * signing. <em>At this time, this interface
* does not provide a way to provide such algorithm parameters, e.g.
* by providing the CA certificate which includes those parameters.</em>
- *
- * <P>Also, note that at this time only signature-capable keys may be
- * acquired through this interface. Diffie-Hellman keys, used for secure
- * key exchange, may be supported later.
- *
+ *
+ * <P>
+ * Also, note that at this time only signature-capable keys may be acquired
+ * through this interface. Diffie-Hellman keys, used for secure key exchange,
+ * may be supported later.
+ *
* @author David Brownell
* @author Hemma Prafullchandra
* @version 1.44
@@ -63,147 +65,137 @@ import netscape.security.pkcs.PKCS10;
*/
public final class CertAndKeyGen {
/**
- * Creates a CertAndKeyGen object for a particular key type
- * and signature algorithm.
- *
+ * Creates a CertAndKeyGen object for a particular key type and signature
+ * algorithm.
+ *
* @param keyType type of key, e.g. "RSA", "DSA"
* @param sigAlg name of the signature algorithm, e.g. "MD5WithRSA",
- * "MD2WithRSA", "SHAwithDSA".
+ * "MD2WithRSA", "SHAwithDSA".
* @exception NoSuchAlgorithmException on unrecognized algorithms.
*/
- public CertAndKeyGen (String keyType, String sigAlg)
- throws NoSuchAlgorithmException
- {
- keyGen = KeyPairGenerator.getInstance(keyType);
- this.sigAlg = sigAlg;
+ public CertAndKeyGen(String keyType, String sigAlg)
+ throws NoSuchAlgorithmException {
+ keyGen = KeyPairGenerator.getInstance(keyType);
+ this.sigAlg = sigAlg;
}
/**
- * Sets the source of random numbers used when generating keys.
- * If you do not provide one, a system default facility is used.
- * You may wish to provide your own source of random numbers
- * to get a reproducible sequence of keys and signatures, or
- * because you may be able to take advantage of strong sources
- * of randomness/entropy in your environment.
- *
+ * Sets the source of random numbers used when generating keys. If you do
+ * not provide one, a system default facility is used. You may wish to
+ * provide your own source of random numbers to get a reproducible sequence
+ * of keys and signatures, or because you may be able to take advantage of
+ * strong sources of randomness/entropy in your environment.
+ *
* @deprecated All random numbers come from PKCS #11 now.
*/
- public void setRandom (SecureRandom generator)
- {
+ public void setRandom(SecureRandom generator) {
}
// want "public void generate (X509Certificate)" ... inherit DSA/D-H param
/**
- * Generates a random public/private key pair, with a given key
- * size. Different algorithms provide different degrees of security
- * for the same key size, because of the "work factor" involved in
- * brute force attacks. As computers become faster, it becomes
- * easier to perform such attacks. Small keys are to be avoided.
- *
- * <P>Note that not all values of "keyBits" are valid for all
- * algorithms, and not all public key algorithms are currently
- * supported for use in X.509 certificates. If the algorithm
- * you specified does not produce X.509 compatible keys, an
- * invalid key exception is thrown.
- *
+ * Generates a random public/private key pair, with a given key size.
+ * Different algorithms provide different degrees of security for the same
+ * key size, because of the "work factor" involved in brute force attacks.
+ * As computers become faster, it becomes easier to perform such attacks.
+ * Small keys are to be avoided.
+ *
+ * <P>
+ * Note that not all values of "keyBits" are valid for all algorithms, and
+ * not all public key algorithms are currently supported for use in X.509
+ * certificates. If the algorithm you specified does not produce X.509
+ * compatible keys, an invalid key exception is thrown.
+ *
* @param keyBits the number of bits in the keys.
- * @exception InvalidKeyException if the environment does not
- * provide X.509 public keys for this signature algorithm.
+ * @exception InvalidKeyException if the environment does not provide X.509
+ * public keys for this signature algorithm.
*/
- public void generate (int keyBits)
- throws InvalidKeyException
- {
- KeyPair pair;
+ public void generate(int keyBits)
+ throws InvalidKeyException {
+ KeyPair pair;
- try {
- keyGen.initialize (keyBits);
- pair = keyGen.generateKeyPair ();
+ try {
+ keyGen.initialize(keyBits);
+ pair = keyGen.generateKeyPair();
- } catch (Exception e) {
- throw new IllegalArgumentException (e.getMessage ());
- }
-
- PublicKey publicKey = pair.getPublic();
+ } catch (Exception e) {
+ throw new IllegalArgumentException(e.getMessage());
+ }
- if (publicKey instanceof X509Key) {
- this.publicKey = (X509Key) publicKey;
-
- } else {
- throw new InvalidKeyException ("public key " + publicKey +
- " not an X509Key.");
- }
- privateKey = pair.getPrivate ();
- }
+ PublicKey publicKey = pair.getPublic();
+
+ if (publicKey instanceof X509Key) {
+ this.publicKey = (X509Key) publicKey;
+ } else {
+ throw new InvalidKeyException("public key " + publicKey +
+ " not an X509Key.");
+ }
+ privateKey = pair.getPrivate();
+ }
/**
* Returns the public key of the generated key pair.
*/
- public X509Key getPublicKey ()
- {
- return publicKey;
+ public X509Key getPublicKey() {
+ return publicKey;
}
-
/**
* Returns the private key of the generated key pair.
- *
- * <P><STRONG><em>Be extremely careful when handling private keys.
+ *
+ * <P>
+ * <STRONG><em>Be extremely careful when handling private keys.
* When private keys are not kept secret, they lose their ability
* to securely authenticate specific entities ... that is a huge
* security risk!</em></STRONG>
*/
- public PrivateKey getPrivateKey ()
- {
- return privateKey;
+ public PrivateKey getPrivateKey() {
+ return privateKey;
}
-
/**
- * Returns a self-signed X.509v1 certificate for the public key.
- * The certificate is immediately valid.
- *
- * <P>Such certificates normally are used to identify a "Certificate
- * Authority" (CA). Accordingly, they will not always be accepted by
- * other parties. However, such certificates are also useful when
- * you are bootstrapping your security infrastructure, or deploying
- * system prototypes.
- *
+ * Returns a self-signed X.509v1 certificate for the public key. The
+ * certificate is immediately valid.
+ *
+ * <P>
+ * Such certificates normally are used to identify a "Certificate Authority"
+ * (CA). Accordingly, they will not always be accepted by other parties.
+ * However, such certificates are also useful when you are bootstrapping
+ * your security infrastructure, or deploying system prototypes.
+ *
* @deprecated Use the new <a href =
- * "#getSelfCertificate(netscape.security.x509.X500Name, long)">
- *
+ * "#getSelfCertificate(netscape.security.x509.X500Name, long)">
+ *
* @param myname X.500 name of the subject (who is also the issuer)
* @param validity how long the certificate should be valid, in seconds
- */
- public X509Cert getSelfCert (X500Name myname, long validity)
- throws InvalidKeyException, SignatureException, NoSuchAlgorithmException
- {
- X509Certificate cert;
-
- try {
- cert = getSelfCertificate(myname, validity);
- return new X509Cert(cert.getEncoded());
- } catch (CertificateException e) {
- throw new SignatureException(e.getMessage());
- } catch (NoSuchProviderException e) {
- throw new NoSuchAlgorithmException(e.getMessage());
- } catch (IOException e) {
- throw new SignatureException(e.getMessage());
- }
+ */
+ public X509Cert getSelfCert(X500Name myname, long validity)
+ throws InvalidKeyException, SignatureException, NoSuchAlgorithmException {
+ X509Certificate cert;
+
+ try {
+ cert = getSelfCertificate(myname, validity);
+ return new X509Cert(cert.getEncoded());
+ } catch (CertificateException e) {
+ throw new SignatureException(e.getMessage());
+ } catch (NoSuchProviderException e) {
+ throw new NoSuchAlgorithmException(e.getMessage());
+ } catch (IOException e) {
+ throw new SignatureException(e.getMessage());
+ }
}
-
/**
- * Returns a self-signed X.509v3 certificate for the public key.
- * The certificate is immediately valid. No extensions.
- *
- * <P>Such certificates normally are used to identify a "Certificate
- * Authority" (CA). Accordingly, they will not always be accepted by
- * other parties. However, such certificates are also useful when
- * you are bootstrapping your security infrastructure, or deploying
- * system prototypes.
- *
+ * Returns a self-signed X.509v3 certificate for the public key. The
+ * certificate is immediately valid. No extensions.
+ *
+ * <P>
+ * Such certificates normally are used to identify a "Certificate Authority"
+ * (CA). Accordingly, they will not always be accepted by other parties.
+ * However, such certificates are also useful when you are bootstrapping
+ * your security infrastructure, or deploying system prototypes.
+ *
* @param myname X.500 name of the subject (who is also the issuer)
* @param validity how long the certificate should be valid, in seconds
* @exception CertificateException on certificate handling errors.
@@ -212,30 +204,29 @@ public final class CertAndKeyGen {
* @exception NoSuchAlgorithmException on unrecognized algorithms.
* @exception NoSuchProviderException on unrecognized providers.
*/
- public X509Certificate getSelfCertificate (X500Name myname, long validity)
- throws CertificateException, InvalidKeyException, SignatureException,
- NoSuchAlgorithmException, NoSuchProviderException
- {
- X500Signer issuer;
- X509CertImpl cert;
- Date firstDate, lastDate;
-
- try {
- issuer = getSigner (myname);
+ public X509Certificate getSelfCertificate(X500Name myname, long validity)
+ throws CertificateException, InvalidKeyException, SignatureException,
+ NoSuchAlgorithmException, NoSuchProviderException {
+ X500Signer issuer;
+ X509CertImpl cert;
+ Date firstDate, lastDate;
- firstDate = new Date ();
- lastDate = new Date ();
- lastDate.setTime (lastDate.getTime () + validity * 1000);
+ try {
+ issuer = getSigner(myname);
+
+ firstDate = new Date();
+ lastDate = new Date();
+ lastDate.setTime(lastDate.getTime() + validity * 1000);
CertificateValidity interval =
- new CertificateValidity(firstDate,lastDate);
-
+ new CertificateValidity(firstDate, lastDate);
+
X509CertInfo info = new X509CertInfo();
// Add all mandatory attributes
info.set(X509CertInfo.VERSION,
new CertificateVersion(CertificateVersion.V1));
info.set(X509CertInfo.SERIAL_NUMBER,
- new CertificateSerialNumber((int)(firstDate.getTime()/1000)));
+ new CertificateSerialNumber((int) (firstDate.getTime() / 1000)));
AlgorithmId algID = issuer.getAlgorithmId();
info.set(X509CertInfo.ALGORITHM_ID,
new CertificateAlgorithmId(algID));
@@ -245,63 +236,61 @@ public final class CertAndKeyGen {
info.set(X509CertInfo.ISSUER,
new CertificateIssuerName(issuer.getSigner()));
- cert = new X509CertImpl(info);
- cert.sign(privateKey, algID.getName());
+ cert = new X509CertImpl(info);
+ cert.sign(privateKey, algID.getName());
- return (X509Certificate)cert;
+ return (X509Certificate) cert;
- } catch (IOException e) {
- throw new CertificateEncodingException("getSelfCert: " +
+ } catch (IOException e) {
+ throw new CertificateEncodingException("getSelfCert: " +
e.getMessage());
- }
+ }
}
/**
- * Returns a PKCS #10 certificate request. The caller uses either
- * <code>PKCS10.print</code> or <code>PKCS10.toByteArray</code>
- * operations on the result, to get the request in an appropriate
- * transmission format.
- *
- * <P>PKCS #10 certificate requests are sent, along with some proof
- * of identity, to Certificate Authorities (CAs) which then issue
- * X.509 public key certificates.
- *
+ * Returns a PKCS #10 certificate request. The caller uses either
+ * <code>PKCS10.print</code> or <code>PKCS10.toByteArray</code> operations
+ * on the result, to get the request in an appropriate transmission format.
+ *
+ * <P>
+ * PKCS #10 certificate requests are sent, along with some proof of
+ * identity, to Certificate Authorities (CAs) which then issue X.509 public
+ * key certificates.
+ *
* @param myname X.500 name of the subject
* @exception InvalidKeyException on key handling errors.
* @exception SignatureException on signature handling errors.
*/
- public PKCS10 getCertRequest (X500Name myname)
- throws InvalidKeyException, SignatureException
- {
- PKCS10 req = new PKCS10 (publicKey);
+ public PKCS10 getCertRequest(X500Name myname)
+ throws InvalidKeyException, SignatureException {
+ PKCS10 req = new PKCS10(publicKey);
- try {
- req.encodeAndSign (getSigner (myname));
+ try {
+ req.encodeAndSign(getSigner(myname));
- } catch (CertificateException e) {
- throw new SignatureException (sigAlg + " CertificateException");
+ } catch (CertificateException e) {
+ throw new SignatureException(sigAlg + " CertificateException");
- } catch (IOException e) {
- throw new SignatureException (sigAlg + " IOException");
+ } catch (IOException e) {
+ throw new SignatureException(sigAlg + " IOException");
- } catch (NoSuchAlgorithmException e) {
- // "can't happen"
- throw new SignatureException (sigAlg + " unavailable?");
- }
- return req;
+ } catch (NoSuchAlgorithmException e) {
+ // "can't happen"
+ throw new SignatureException(sigAlg + " unavailable?");
+ }
+ return req;
}
- private X500Signer getSigner (X500Name me)
- throws InvalidKeyException, NoSuchAlgorithmException
- {
- Signature signature = Signature.getInstance(sigAlg);
+ private X500Signer getSigner(X500Name me)
+ throws InvalidKeyException, NoSuchAlgorithmException {
+ Signature signature = Signature.getInstance(sigAlg);
- signature.initSign (privateKey);
- return new X500Signer (signature, me);
+ signature.initSign(privateKey);
+ return new X500Signer(signature, me);
}
- private String sigAlg;
- private KeyPairGenerator keyGen;
- private X509Key publicKey;
- private PrivateKey privateKey;
+ private String sigAlg;
+ private KeyPairGenerator keyGen;
+ private X509Key publicKey;
+ private PrivateKey privateKey;
}
diff --git a/pki/base/util/src/netscape/security/x509/CertAttrSet.java b/pki/base/util/src/netscape/security/x509/CertAttrSet.java
index 4b9352c6..c395b2a2 100755
--- a/pki/base/util/src/netscape/security/x509/CertAttrSet.java
+++ b/pki/base/util/src/netscape/security/x509/CertAttrSet.java
@@ -26,14 +26,12 @@ import java.util.Enumeration;
/**
* This interface defines the methods required of a certificate attribute.
* Examples of X.509 certificate attributes are Validity, Issuer_Name, and
- * Subject Name. A CertAttrSet may compromise one attribute or many
- * attributes.
+ * Subject Name. A CertAttrSet may compromise one attribute or many attributes.
* <p>
- * A CertAttrSet itself can also be comprised of other sub-sets.
- * In the case of X.509 V3 certificates, for example, the "extensions"
- * attribute has subattributes, such as those for KeyUsage and
- * AuthorityKeyIdentifier.
- *
+ * A CertAttrSet itself can also be comprised of other sub-sets. In the case of
+ * X.509 V3 certificates, for example, the "extensions" attribute has
+ * subattributes, such as those for KeyUsage and AuthorityKeyIdentifier.
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.9
@@ -42,38 +40,37 @@ import java.util.Enumeration;
public interface CertAttrSet {
/**
* Returns a short string describing this certificate attribute.
- *
- * @return value of this certificate attribute in
- * printable form.
+ *
+ * @return value of this certificate attribute in printable form.
*/
String toString();
/**
- * Encodes the attribute to the output stream in a format
- * that can be parsed by the <code>decode</code> method.
- *
+ * Encodes the attribute to the output stream in a format that can be parsed
+ * by the <code>decode</code> method.
+ *
* @param out the OutputStream to encode the attribute to.
*
* @exception CertificateException on encoding or validity errors.
* @exception IOException on other errors.
*/
void encode(OutputStream out)
- throws CertificateException, IOException;
+ throws CertificateException, IOException;
/**
* Decodes the attribute in the input stream.
- *
+ *
* @param in the InputStream to read the encoded attribute from.
*
* @exception CertificateException on decoding or validity errors.
* @exception IOException on other errors.
*/
void decode(InputStream in)
- throws CertificateException, IOException;
+ throws CertificateException, IOException;
/**
* Sets an attribute value within this CertAttrSet.
- *
+ *
* @param name the name of the attribute (e.g. "x509.info.key")
* @param obj the attribute object.
*
@@ -81,29 +78,29 @@ public interface CertAttrSet {
* @exception IOException on other errors.
*/
void set(String name, Object obj)
- throws CertificateException, IOException;
+ throws CertificateException, IOException;
/**
* Gets an attribute value for this CertAttrSet.
- *
+ *
* @param name the name of the attribute to return.
*
* @exception CertificateException on attribute handling errors.
* @exception IOException on other errors.
*/
Object get(String name)
- throws CertificateException, IOException;
+ throws CertificateException, IOException;
/**
* Deletes an attribute value from this CertAttrSet.
- *
+ *
* @param name the name of the attribute to delete.
*
* @exception CertificateException on attribute handling errors.
* @exception IOException on other errors.
*/
void delete(String name)
- throws CertificateException, IOException;
+ throws CertificateException, IOException;
/**
* Returns an enumeration of the names of the attributes existing within
@@ -112,8 +109,7 @@ public interface CertAttrSet {
* @return an enumeration of the attribute names.
*/
Enumeration<String> getAttributeNames();
-
-
+
/**
* Returns the name (identifier) of this CertAttrSet.
*
diff --git a/pki/base/util/src/netscape/security/x509/CertException.java b/pki/base/util/src/netscape/security/x509/CertException.java
index 0b83ff11..d537f992 100644
--- a/pki/base/util/src/netscape/security/x509/CertException.java
+++ b/pki/base/util/src/netscape/security/x509/CertException.java
@@ -19,9 +19,9 @@ package netscape.security.x509;
/**
* CertException indicates one of a variety of certificate problems.
- *
+ *
* @version 1.18
- *
+ *
* @author David Brownell
* @author Amit Kapoor
* @author Hemma Prafullchandra
@@ -47,8 +47,10 @@ public class CertException extends SecurityException {
/** Indicates that the certificate has expired and so is not valid. */
public static final int verf_INVALID_EXPIRED = 4;
- /** Indicates that a certificate authority in the certification
- * chain is not trusted. */
+ /**
+ * Indicates that a certificate authority in the certification chain is not
+ * trusted.
+ */
public static final int verf_CA_UNTRUSTED = 5;
/** Indicates that the certification chain is too long. */
@@ -65,56 +67,55 @@ public class CertException extends SecurityException {
/** Indicates a problem with the certificate version */
public static final int err_INVALID_VERSION = 10;
-
+
/** Indicates a problem with the certificate format */
public static final int err_INVALID_FORMAT = 11;
-
+
/** Indicates a problem with the certificate encoding */
public static final int err_ENCODING = 12;
-
- // Private data members
- private int verfCode;
- private String moreData;
+ // Private data members
+ private int verfCode;
+ private String moreData;
/**
- * Constructs a certificate exception using an error code
- * (<code>verf_*</code>) and a string describing the context
- * of the error.
+ * Constructs a certificate exception using an error code (
+ * <code>verf_*</code>) and a string describing the context of the error.
*/
- public CertException(int code, String moredata)
- {
- verfCode = code;
- moreData = moredata;
+ public CertException(int code, String moredata) {
+ verfCode = code;
+ moreData = moredata;
}
/**
- * Constructs a certificate exception using just an error code,
- * without a string describing the context.
+ * Constructs a certificate exception using just an error code, without a
+ * string describing the context.
*/
- public CertException(int code)
- {
- verfCode = code;
+ public CertException(int code) {
+ verfCode = code;
}
/**
* Returns the error code with which the exception was created.
*/
- public int getVerfCode() { return verfCode; }
+ public int getVerfCode() {
+ return verfCode;
+ }
/**
- * Returns a string describing the context in which the exception
- * was reported.
+ * Returns a string describing the context in which the exception was
+ * reported.
*/
- public String getMoreData() { return moreData; }
+ public String getMoreData() {
+ return moreData;
+ }
/**
- * Return a string corresponding to the error code used to create
- * this exception.
+ * Return a string corresponding to the error code used to create this
+ * exception.
*/
- public String getVerfDescription()
- {
- switch (verfCode) {
+ public String getVerfDescription() {
+ switch (verfCode) {
case verf_INVALID_SIG:
return "The signature in the certificate is not valid.";
case verf_INVALID_REVOKED:
@@ -134,32 +135,30 @@ public class CertException extends SecurityException {
case err_INVALID_PUBLIC_KEY:
return "The public key was not in the correct format.";
case err_INVALID_VERSION:
- return "The certificate has an invalid version number.";
+ return "The certificate has an invalid version number.";
case err_INVALID_FORMAT:
- return "The certificate has an invalid format.";
+ return "The certificate has an invalid format.";
case err_ENCODING:
return "Problem encountered while encoding the data.";
default:
return "Unknown code: " + verfCode;
- }
+ }
}
/**
* Returns a string describing the certificate exception.
*/
- public String toString()
- {
- return "[Certificate Exception: " + getMessage() + "]";
+ public String toString() {
+ return "[Certificate Exception: " + getMessage() + "]";
}
/**
* Returns a string describing the certificate exception.
*/
- public String getMessage()
- {
- return getVerfDescription()
- + ( (moreData != null)
- ? ( "\n (" + moreData + ")" ) : "" );
+ public String getMessage() {
+ return getVerfDescription()
+ + ((moreData != null)
+ ? ("\n (" + moreData + ")") : "");
}
}
diff --git a/pki/base/util/src/netscape/security/x509/CertParseError.java b/pki/base/util/src/netscape/security/x509/CertParseError.java
index 2b9e444b..7328c720 100644
--- a/pki/base/util/src/netscape/security/x509/CertParseError.java
+++ b/pki/base/util/src/netscape/security/x509/CertParseError.java
@@ -23,21 +23,18 @@ package netscape.security.x509;
/**
* CertException indicates one of a variety of certificate problems.
- *
+ *
* @version 1.7
* @author David Brownell
*/
-class CertParseError extends CertException
-{
+class CertParseError extends CertException {
/**
*
*/
private static final long serialVersionUID = -7623327377774730807L;
- CertParseError (String where)
- {
- super (CertException.verf_PARSE_ERROR, where);
+ CertParseError(String where) {
+ super(CertException.verf_PARSE_ERROR, where);
}
}
-
diff --git a/pki/base/util/src/netscape/security/x509/CertificateAlgorithmId.java b/pki/base/util/src/netscape/security/x509/CertificateAlgorithmId.java
index 676df900..f46af776 100644
--- a/pki/base/util/src/netscape/security/x509/CertificateAlgorithmId.java
+++ b/pki/base/util/src/netscape/security/x509/CertificateAlgorithmId.java
@@ -32,7 +32,7 @@ import netscape.security.util.DerValue;
/**
* This class defines the AlgorithmId for the Certificate.
- *
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.7
@@ -43,11 +43,11 @@ public class CertificateAlgorithmId implements CertAttrSet, Serializable {
*/
private static final long serialVersionUID = 6084780721443376563L;
- private AlgorithmId algId;
+ private AlgorithmId algId;
/**
- * Identifier for this attribute, to be used with the
- * get, set, delete methods of Certificate, x509 type.
+ * Identifier for this attribute, to be used with the get, set, delete
+ * methods of Certificate, x509 type.
*/
public static final String IDENT = "x509.info.algorithmID";
/**
@@ -58,7 +58,7 @@ public class CertificateAlgorithmId implements CertAttrSet, Serializable {
/**
* Default constructor for the certificate attribute.
- *
+ *
* @param algId the Algorithm identifier
*/
public CertificateAlgorithmId(AlgorithmId algId) {
@@ -67,7 +67,7 @@ public class CertificateAlgorithmId implements CertAttrSet, Serializable {
/**
* Create the object, decoding the values from the passed DER stream.
- *
+ *
* @param in the DerInputStream to read the serial number from.
* @exception IOException on decoding errors.
*/
@@ -78,7 +78,7 @@ public class CertificateAlgorithmId implements CertAttrSet, Serializable {
/**
* Create the object, decoding the values from the passed stream.
- *
+ *
* @param in the InputStream to read the serial number from.
* @exception IOException on decoding errors.
*/
@@ -91,24 +91,25 @@ public class CertificateAlgorithmId implements CertAttrSet, Serializable {
* Return the algorithm identifier as user readable string.
*/
public String toString() {
- if (algId == null) return "";
+ if (algId == null)
+ return "";
return (algId.toString() +
", OID = " + (algId.getOID()).toString() + "\n");
}
private synchronized void writeObject(ObjectOutputStream stream)
- throws IOException {
+ throws IOException {
encode(stream);
}
private synchronized void readObject(ObjectInputStream stream)
- throws IOException {
- decode(stream);
+ throws IOException {
+ decode(stream);
}
/**
* Encode the algorithm identifier in DER form to the stream.
- *
+ *
* @param out the DerOutputStream to marshal the contents to.
* @exception IOException on errors.
*/
@@ -121,7 +122,7 @@ public class CertificateAlgorithmId implements CertAttrSet, Serializable {
/**
* Decode the algorithm identifier from the passed stream.
- *
+ *
* @param in the InputStream to unmarshal the contents from.
* @exception IOException on errors.
*/
@@ -138,7 +139,7 @@ public class CertificateAlgorithmId implements CertAttrSet, Serializable {
throw new IOException("Attribute must be of type AlgorithmId.");
}
if (name.equalsIgnoreCase(ALGORITHM)) {
- algId = (AlgorithmId)obj;
+ algId = (AlgorithmId) obj;
} else {
throw new IOException("Attribute name not recognized by " +
"CertAttrSet:CertificateAlgorithmId.");
@@ -178,11 +179,11 @@ public class CertificateAlgorithmId implements CertAttrSet, Serializable {
elements.addElement(ALGORITHM);
return (elements.elements());
}
-
- /**
- * Return the name of this attribute.
- */
- public String getName() {
- return (NAME);
- }
+
+ /**
+ * Return the name of this attribute.
+ */
+ public String getName() {
+ return (NAME);
+ }
}
diff --git a/pki/base/util/src/netscape/security/x509/CertificateChain.java b/pki/base/util/src/netscape/security/x509/CertificateChain.java
index df9f0140..b6032537 100644
--- a/pki/base/util/src/netscape/security/x509/CertificateChain.java
+++ b/pki/base/util/src/netscape/security/x509/CertificateChain.java
@@ -16,6 +16,7 @@
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package netscape.security.x509;
+
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -26,116 +27,111 @@ import netscape.security.pkcs.ContentInfo;
import netscape.security.pkcs.PKCS7;
import netscape.security.pkcs.SignerInfo;
-public class CertificateChain implements Serializable
-{
- public CertificateChain() { }
+public class CertificateChain implements Serializable {
+ public CertificateChain() {
+ }
- /**
- * constructs a certificate chain from a certificate.
- * @param cert a certificate
- */
- public CertificateChain(X509Certificate cert)
- {
- mChain = new X509Certificate[1];
- mChain[0] = cert;
- }
+ /**
+ * constructs a certificate chain from a certificate.
+ *
+ * @param cert a certificate
+ */
+ public CertificateChain(X509Certificate cert) {
+ mChain = new X509Certificate[1];
+ mChain[0] = cert;
+ }
- /**
- * constructs a certificate chain from a X509 certificate array.
- * @param chain a certificate array.
- */
- public CertificateChain(X509Certificate[] chain)
- {
- mChain = (X509Certificate[])chain.clone();
- }
+ /**
+ * constructs a certificate chain from a X509 certificate array.
+ *
+ * @param chain a certificate array.
+ */
+ public CertificateChain(X509Certificate[] chain) {
+ mChain = (X509Certificate[]) chain.clone();
+ }
- /**
- * returns the certificate at specified index in chain.
- * @param index the index.
- * @return the X509 certificate at the given index.
- */
- public X509Certificate getCertificate(int index)
- {
- return mChain[index];
- }
+ /**
+ * returns the certificate at specified index in chain.
+ *
+ * @param index the index.
+ * @return the X509 certificate at the given index.
+ */
+ public X509Certificate getCertificate(int index) {
+ return mChain[index];
+ }
- /**
- * returns the first certificate in chain.
- * @return the X509 certificate at the given index.
- */
- public X509Certificate getFirstCertificate()
- {
- return mChain[0];
- }
+ /**
+ * returns the first certificate in chain.
+ *
+ * @return the X509 certificate at the given index.
+ */
+ public X509Certificate getFirstCertificate() {
+ return mChain[0];
+ }
- /**
- * returns the certificate chain as an array of X509 certificates.
- * @return an array of X509 Certificates.
- */
- public X509Certificate[] getChain()
- {
- return (X509Certificate[])mChain.clone();
- }
+ /**
+ * returns the certificate chain as an array of X509 certificates.
+ *
+ * @return an array of X509 Certificates.
+ */
+ public X509Certificate[] getChain() {
+ return (X509Certificate[]) mChain.clone();
+ }
- public void encode(OutputStream out)
- throws IOException
- {
- encode(out, true);
- }
+ public void encode(OutputStream out)
+ throws IOException {
+ encode(out, true);
+ }
- /**
- * encode in PKCS7 blob.
- */
- public void encode(OutputStream out, boolean sort)
- throws IOException
- {
- PKCS7 p7 = new PKCS7(new AlgorithmId[0],
+ /**
+ * encode in PKCS7 blob.
+ */
+ public void encode(OutputStream out, boolean sort)
+ throws IOException {
+ PKCS7 p7 = new PKCS7(new AlgorithmId[0],
new ContentInfo(new byte[0]), mChain,
new SignerInfo[0]);
- p7.encodeSignedData(out, sort);
- }
+ p7.encodeSignedData(out, sort);
+ }
- /**
- * decode from PKCS7 blob.
- */
- public void decode(InputStream in)
- throws IOException
- {
- PKCS7 p7 = new PKCS7(in);
- mChain = p7.getCertificates();
- }
+ /**
+ * decode from PKCS7 blob.
+ */
+ public void decode(InputStream in)
+ throws IOException {
+ PKCS7 p7 = new PKCS7(in);
+ mChain = p7.getCertificates();
+ }
- /**
- * for serialization
- */
- private void writeObject(java.io.ObjectOutputStream out)
- throws IOException
- {
- encode(out);
- }
+ /**
+ * for serialization
+ */
+ private void writeObject(java.io.ObjectOutputStream out)
+ throws IOException {
+ encode(out);
+ }
- /**
- * for serialization
- */
- private void readObject(java.io.ObjectInputStream in)
- throws IOException
- {
- decode(in);
- }
+ /**
+ * for serialization
+ */
+ private void readObject(java.io.ObjectInputStream in)
+ throws IOException {
+ decode(in);
+ }
- /**
- * Converts the certificate chain to a readable string.
- */
- public String toString() {
- String s = "[\n";
- if (mChain == null)
- return "[empty]";
- for (int i = 0; i < mChain.length; i++) {
- s += mChain[i].toString();
- }
- s += "]\n";
- return s;
- }
+ /**
+ * Converts the certificate chain to a readable string.
+ */
+ public String toString() {
+ String s = "[\n";
+ if (mChain == null)
+ return "[empty]";
+ for (int i = 0; i < mChain.length; i++) {
+ s += mChain[i].toString();
+ }
+ s += "]\n";
+ return s;
+ }
- private X509Certificate[] mChain = null;
+ private X509Certificate[] mChain = null;
}
diff --git a/pki/base/util/src/netscape/security/x509/CertificateExtensions.java b/pki/base/util/src/netscape/security/x509/CertificateExtensions.java
index 6075715a..9dacd8c9 100644
--- a/pki/base/util/src/netscape/security/x509/CertificateExtensions.java
+++ b/pki/base/util/src/netscape/security/x509/CertificateExtensions.java
@@ -37,22 +37,22 @@ import netscape.security.util.DerValue;
/**
* This class defines the Extensions attribute for the Certificate.
- *
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.11
* @see CertAttrSet
*/
public class CertificateExtensions extends Vector<Extension>
-implements CertAttrSet, Serializable {
+ implements CertAttrSet, Serializable {
/**
*
*/
private static final long serialVersionUID = -7172635300185788849L;
/**
- * Identifier for this attribute, to be used with the
- * get, set, delete methods of Certificate, x509 type.
- */
+ * Identifier for this attribute, to be used with the get, set, delete
+ * methods of Certificate, x509 type.
+ */
public static final String IDENT = "x509.info.extensions";
/**
* name
@@ -65,8 +65,8 @@ implements CertAttrSet, Serializable {
public void parseExtension(Extension ext) throws IOException {
try {
@SuppressWarnings("unchecked")
- Class<Extension> extClass = (Class<Extension>) OIDMap.getClass(ext.getExtensionId());
- if (extClass == null) { // Unsupported extension
+ Class<Extension> extClass = (Class<Extension>) OIDMap.getClass(ext.getExtensionId());
+ if (extClass == null) { // Unsupported extension
if (ext.isCritical()) {
throw new IOException("Unsupported CRITICAL extension: "
+ ext.getExtensionId());
@@ -76,7 +76,7 @@ implements CertAttrSet, Serializable {
return;
}
}
- Class<?>[] params = {Boolean.class, Object.class};
+ Class<?>[] params = { Boolean.class, Object.class };
Constructor<Extension> cons = extClass.getConstructor(params);
byte[] extData = ext.getExtensionValue();
@@ -86,8 +86,8 @@ implements CertAttrSet, Serializable {
for (int i = 0; i < extLen; i++) {
Array.setByte(value, i, extData[i]);
}
- Object[] passed = new Object[]{new Boolean(ext.isCritical()),
- value};
+ Object[] passed = new Object[] { new Boolean(ext.isCritical()),
+ value };
Extension certExt = cons.newInstance(passed);
if (certExt != null && certExt.getName() != null) {
map.put(certExt.getName(), (Extension) certExt);
@@ -106,17 +106,17 @@ implements CertAttrSet, Serializable {
* Default constructor for the certificate attribute.
*/
public CertificateExtensions() {
- map = new Hashtable<String, Extension> ();
+ map = new Hashtable<String, Extension>();
}
/**
* Create the object, decoding the values from the passed DER stream.
- *
+ *
* @param in the DerInputStream to read the Extension from.
* @exception IOException on decoding errors.
*/
public CertificateExtensions(DerInputStream in)
- throws IOException {
+ throws IOException {
map = new Hashtable<String, Extension>();
DerValue[] exts = in.getSequence(5);
@@ -129,7 +129,7 @@ implements CertAttrSet, Serializable {
/**
* Decode the extensions from the InputStream.
- *
+ *
* @param in the InputStream to unmarshal the contents from.
* @exception IOException on decoding or validity errors.
*/
@@ -148,17 +148,17 @@ implements CertAttrSet, Serializable {
/**
* Decode the extensions from the InputStream.
- *
+ *
* @param in the InputStream to unmarshal the contents from.
* @exception IOException on decoding or validity errors.
*/
public void decodeEx(InputStream in) throws IOException {
DerValue val = new DerValue(in);
DerInputStream str = null;
- if (val.isConstructed() && val.isContextSpecific((byte)3)) {
- str = val.data;
+ if (val.isConstructed() && val.isContextSpecific((byte) 3)) {
+ str = val.data;
} else {
- str = val.toDerInputStream();
+ str = val.toDerInputStream();
}
map = new Hashtable<String, Extension>();
@@ -171,40 +171,40 @@ implements CertAttrSet, Serializable {
}
private synchronized void writeObject(ObjectOutputStream stream)
- throws CertificateException, IOException {
+ throws CertificateException, IOException {
encode(stream);
}
private synchronized void readObject(ObjectInputStream stream)
- throws CertificateException, IOException {
- decodeEx(stream);
+ throws CertificateException, IOException {
+ decodeEx(stream);
}
/**
* Encode the extensions in DER form to the stream.
- *
+ *
* @param out the DerOutputStream to marshal the contents to.
* @exception CertificateException on encoding errors.
* @exception IOException on errors.
*/
public void encode(OutputStream out)
- throws CertificateException, IOException {
+ throws CertificateException, IOException {
DerOutputStream extOut = new DerOutputStream();
for (int i = 0; i < size(); i++) {
Object thisOne = elementAt(i);
if (thisOne instanceof CertAttrSet)
- ((CertAttrSet)thisOne).encode(extOut);
+ ((CertAttrSet) thisOne).encode(extOut);
else if (thisOne instanceof Extension)
- ((Extension)thisOne).encode(extOut);
+ ((Extension) thisOne).encode(extOut);
else
throw new CertificateException("Invalid extension object");
}
DerOutputStream seq = new DerOutputStream();
- seq.write(DerValue.tag_Sequence,extOut);
+ seq.write(DerValue.tag_Sequence, extOut);
DerOutputStream tmp = new DerOutputStream();
- tmp.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)3),
+ tmp.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 3),
seq);
out.write(tmp.toByteArray());
@@ -212,17 +212,19 @@ implements CertAttrSet, Serializable {
/**
* Set the attribute value.
+ *
* @param name the extension name used in the cache.
* @param obj the object to set.
* @exception IOException if the object could not be cached.
*/
public void set(String name, Object obj) throws IOException {
- map.put(name,(Extension) obj);
+ map.put(name, (Extension) obj);
addElement((Extension) obj);
}
/**
* Get the attribute value.
+ *
* @param name the extension name used in the lookup.
* @exception IOException if named extension is not found.
*/
@@ -236,6 +238,7 @@ implements CertAttrSet, Serializable {
/**
* Delete the attribute value.
+ *
* @param name the extension name used in the lookup.
* @exception IOException if named extension is not found.
*/
@@ -248,9 +251,8 @@ implements CertAttrSet, Serializable {
removeElement(obj);
}
- public Enumeration<String> getNames()
- {
- return map.keys();
+ public Enumeration<String> getNames() {
+ return map.keys();
}
/**
@@ -261,15 +263,14 @@ implements CertAttrSet, Serializable {
return (map.elements());
}
-
- public Enumeration<String> getAttributeNames () {
+ public Enumeration<String> getAttributeNames() {
return (map.keys());
}
-
+
/**
* Return the name of this attribute.
*/
- public String getName () {
+ public String getName() {
return (NAME);
}
}
diff --git a/pki/base/util/src/netscape/security/x509/CertificateIssuerExtension.java b/pki/base/util/src/netscape/security/x509/CertificateIssuerExtension.java
index 55f21d2a..0c0df86e 100644
--- a/pki/base/util/src/netscape/security/x509/CertificateIssuerExtension.java
+++ b/pki/base/util/src/netscape/security/x509/CertificateIssuerExtension.java
@@ -28,22 +28,20 @@ import java.util.Vector;
import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
-
/**
* Represent the CRL Certificate Issuer Extension.
- *
- * <p>This CRL entry extension identifies the certificate
- * issuer associated with an entry in an indirect CRL,
- * i.e. a CRL that has the indirectCRL indicator set
+ *
+ * <p>
+ * This CRL entry extension identifies the certificate issuer associated with an
+ * entry in an indirect CRL, i.e. a CRL that has the indirectCRL indicator set
* in its issuing distribution point extension.
- *
+ *
* @see Extension
* @see CertAttrSet
*/
public class CertificateIssuerExtension extends Extension
- implements CertAttrSet
-{
+ implements CertAttrSet {
/**
*
*/
@@ -65,10 +63,10 @@ public class CertificateIssuerExtension extends Extension
try {
OIDMap.addAttribute(CertificateIssuerExtension.class.getName(),
OID, CertificateIssuerExtension.class.getSimpleName());
- } catch (CertificateException e) {}
+ } catch (CertificateException e) {
+ }
}
-
// Encode this extension
private void encodeThis() throws IOException {
DerOutputStream os = new DerOutputStream();
@@ -81,31 +79,29 @@ public class CertificateIssuerExtension extends Extension
}
/**
- * Create a CertificateIssuerExtension with the passed GeneralNames
- * and criticality.
- *
+ * Create a CertificateIssuerExtension with the passed GeneralNames and
+ * criticality.
+ *
* @param critical true if the extension is to be treated as critical.
* @param names the GeneralNames for the issuer.
* @exception IOException on error.
*/
public CertificateIssuerExtension(Boolean critical, GeneralNames names)
- throws IOException
- {
+ throws IOException {
this.names = names;
this.extensionId = PKIXExtensions.CertificateIssuer_Id;
this.critical = critical.booleanValue();
encodeThis();
}
- /**
+ /**
* Create a CertificateIssuerExtension with the passed GeneralNames.
- *
+ *
* @param names the GeneralNames for the issuer.
* @exception IOException on error.
*/
public CertificateIssuerExtension(GeneralNames names)
- throws IOException
- {
+ throws IOException {
this.names = names;
this.extensionId = PKIXExtensions.CertificateIssuer_Id;
this.critical = true;
@@ -123,14 +119,13 @@ public class CertificateIssuerExtension extends Extension
/**
* Create the extension from the passed DER encoded value.
- *
+ *
* @param critical true if the extension is to be treated as critical.
* @param value Array of DER encoded bytes of the actual value.
* @exception IOException on error.
*/
public CertificateIssuerExtension(Boolean critical, Object value)
- throws IOException
- {
+ throws IOException {
this.extensionId = PKIXExtensions.CertificateIssuer_Id;
this.critical = critical.booleanValue();
@@ -147,21 +142,22 @@ public class CertificateIssuerExtension extends Extension
throw new IOException("CertificateIssuerExtension: " +
e.toString());
}
- }
-
- /**
- * Returns a printable representation of the CertificateIssuerName.
- */
- public String toString() {
- if (names == null) return "";
- String s = super.toString() + "CertificateIssuerName [\n"
+ }
+
+ /**
+ * Returns a printable representation of the CertificateIssuerName.
+ */
+ public String toString() {
+ if (names == null)
+ return "";
+ String s = super.toString() + "CertificateIssuerName [\n"
+ names.toString() + "]\n";
- return (s);
- }
+ return (s);
+ }
/**
* Decode the extension from the InputStream.
- *
+ *
* @param in the InputStream to unmarshal the contents from.
* @exception IOException on decoding or validity errors.
*/
@@ -171,7 +167,7 @@ public class CertificateIssuerExtension extends Extension
/**
* Write the extension to the OutputStream.
- *
+ *
* @param out the OutputStream to write the extension to.
* @exception IOException on encoding error.
*/
@@ -195,9 +191,9 @@ public class CertificateIssuerExtension extends Extension
throw new IOException("Attribute value should be of" +
" type GeneralNames.");
}
- names = (GeneralNames)obj;
+ names = (GeneralNames) obj;
} else {
- throw new IOException("Attribute name not recognized by " +
+ throw new IOException("Attribute name not recognized by " +
"CertAttrSet:CertificateIssuerName.");
}
}
@@ -209,7 +205,7 @@ public class CertificateIssuerExtension extends Extension
if (name.equalsIgnoreCase(CERTIFICATE_ISSUER)) {
return (names);
} else {
- throw new IOException("Attribute name not recognized by " +
+ throw new IOException("Attribute name not recognized by " +
"CertAttrSet:CertificateIssuerName.");
}
}
@@ -221,7 +217,7 @@ public class CertificateIssuerExtension extends Extension
if (name.equalsIgnoreCase(CERTIFICATE_ISSUER)) {
names = null;
} else {
- throw new IOException("Attribute name not recognized by " +
+ throw new IOException("Attribute name not recognized by " +
"CertAttrSet:CertificateIssuerName.");
}
}
@@ -238,4 +234,3 @@ public class CertificateIssuerExtension extends Extension
}
}
-
diff --git a/pki/base/util/src/netscape/security/x509/CertificateIssuerName.java b/pki/base/util/src/netscape/security/x509/CertificateIssuerName.java
index 47c44ed4..4b51d59e 100644
--- a/pki/base/util/src/netscape/security/x509/CertificateIssuerName.java
+++ b/pki/base/util/src/netscape/security/x509/CertificateIssuerName.java
@@ -29,7 +29,7 @@ import netscape.security.util.DerValue;
/**
* This class defines the X500Name attribute for the Certificate.
- *
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.6
@@ -37,9 +37,9 @@ import netscape.security.util.DerValue;
*/
public class CertificateIssuerName implements CertAttrSet {
/**
- * Identifier for this attribute, to be used with the
- * get, set, delete methods of Certificate, x509 type.
- */
+ * Identifier for this attribute, to be used with the get, set, delete
+ * methods of Certificate, x509 type.
+ */
public static final String IDENT = "x509.info.issuer";
/**
* Sub attributes name for this CertAttrSet.
@@ -48,11 +48,11 @@ public class CertificateIssuerName implements CertAttrSet {
public static final String DN_NAME = "dname";
// Private data member
- private X500Name dnName;
+ private X500Name dnName;
/**
* Default constructor for the certificate attribute.
- *
+ *
* @param name the X500Name
*/
public CertificateIssuerName(X500Name name) {
@@ -61,7 +61,7 @@ public class CertificateIssuerName implements CertAttrSet {
/**
* Create the object, decoding the values from the passed DER stream.
- *
+ *
* @param in the DerInputStream to read the X500Name from.
* @exception IOException on decoding errors.
*/
@@ -71,7 +71,7 @@ public class CertificateIssuerName implements CertAttrSet {
/**
* Create the object, decoding the values from the passed stream.
- *
+ *
* @param in the InputStream to read the X500Name from.
* @exception IOException on decoding errors.
*/
@@ -84,13 +84,14 @@ public class CertificateIssuerName implements CertAttrSet {
* Return the name as user readable string.
*/
public String toString() {
- if (dnName == null) return "";
- return(dnName.toString());
+ if (dnName == null)
+ return "";
+ return (dnName.toString());
}
/**
* Encode the name in DER form to the stream.
- *
+ *
* @param out the DerOutputStream to marshal the contents to.
* @exception IOException on errors.
*/
@@ -103,7 +104,7 @@ public class CertificateIssuerName implements CertAttrSet {
/**
* Decode the name in DER form from the stream.
- *
+ *
* @param in the InputStream to marshal the contents from.
* @exception IOException on errors.
*/
@@ -120,7 +121,7 @@ public class CertificateIssuerName implements CertAttrSet {
throw new IOException("Attribute must be of type X500Name.");
}
if (name.equalsIgnoreCase(DN_NAME)) {
- this.dnName = (X500Name)obj;
+ this.dnName = (X500Name) obj;
} else {
throw new IOException("Attribute name not recognized by " +
"CertAttrSet:CertificateIssuerName.");
@@ -132,7 +133,7 @@ public class CertificateIssuerName implements CertAttrSet {
*/
public Object get(String name) throws IOException {
if (name.equalsIgnoreCase(DN_NAME)) {
- return(dnName);
+ return (dnName);
} else {
throw new IOException("Attribute name not recognized by " +
"CertAttrSet:CertificateIssuerName.");
@@ -166,6 +167,6 @@ public class CertificateIssuerName implements CertAttrSet {
* Return the name of this attribute.
*/
public String getName() {
- return(NAME);
+ return (NAME);
}
}
diff --git a/pki/base/util/src/netscape/security/x509/CertificateIssuerUniqueIdentity.java b/pki/base/util/src/netscape/security/x509/CertificateIssuerUniqueIdentity.java
index 52baa621..25989b58 100644
--- a/pki/base/util/src/netscape/security/x509/CertificateIssuerUniqueIdentity.java
+++ b/pki/base/util/src/netscape/security/x509/CertificateIssuerUniqueIdentity.java
@@ -28,21 +28,21 @@ import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
/**
- * This class defines the subject/issuer unique identity attribute
- * for the Certificate.
- *
+ * This class defines the subject/issuer unique identity attribute for the
+ * Certificate.
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.6
* @see CertAttrSet
*/
public class CertificateIssuerUniqueIdentity implements CertAttrSet {
- private UniqueIdentity id;
+ private UniqueIdentity id;
/**
- * Identifier for this attribute, to be used with the
- * get, set, delete methods of Certificate, x509 type.
- */
+ * Identifier for this attribute, to be used with the get, set, delete
+ * methods of Certificate, x509 type.
+ */
public static final String IDENT = "x509.info.issuerID";
/**
* Sub attributes name for this CertAttrSet.
@@ -52,7 +52,7 @@ public class CertificateIssuerUniqueIdentity implements CertAttrSet {
/**
* Default constructor for the certificate attribute.
- *
+ *
* @param key the UniqueIdentity
*/
public CertificateIssuerUniqueIdentity(UniqueIdentity id) {
@@ -61,35 +61,35 @@ public class CertificateIssuerUniqueIdentity implements CertAttrSet {
/**
* Create the object, decoding the values from the passed DER stream.
- *
+ *
* @param in the DerInputStream to read the UniqueIdentity from.
* @exception IOException on decoding errors.
*/
public CertificateIssuerUniqueIdentity(DerInputStream in)
- throws IOException {
+ throws IOException {
id = new UniqueIdentity(in);
}
/**
* Create the object, decoding the values from the passed stream.
- *
+ *
* @param in the InputStream to read the UniqueIdentity from.
* @exception IOException on decoding errors.
*/
public CertificateIssuerUniqueIdentity(InputStream in)
- throws IOException {
+ throws IOException {
DerValue val = new DerValue(in);
id = new UniqueIdentity(val);
}
/**
* Create the object, decoding the values from the passed DER value.
- *
+ *
* @param in the DerValue to read the UniqueIdentity from.
* @exception IOException on decoding errors.
*/
public CertificateIssuerUniqueIdentity(DerValue val)
- throws IOException {
+ throws IOException {
id = new UniqueIdentity(val);
}
@@ -97,13 +97,14 @@ public class CertificateIssuerUniqueIdentity implements CertAttrSet {
* Return the identity as user readable string.
*/
public String toString() {
- if (id == null) return "";
+ if (id == null)
+ return "";
return (id.toString());
}
/**
* Decode the identity in DER form from the stream.
- *
+ *
* @param in the InputStream to unmarshal the contents from.
* @exception IOException on errors.
*/
@@ -114,13 +115,13 @@ public class CertificateIssuerUniqueIdentity implements CertAttrSet {
/**
* Encode the identity in DER form to the stream.
- *
+ *
* @param out the DerOutputStream to marshal the contents to.
* @exception IOException on errors.
*/
public void encode(OutputStream out) throws IOException {
DerOutputStream tmp = new DerOutputStream();
- id.encode(tmp,DerValue.createTag(DerValue.TAG_CONTEXT,false,(byte)1));
+ id.encode(tmp, DerValue.createTag(DerValue.TAG_CONTEXT, false, (byte) 1));
out.write(tmp.toByteArray());
}
@@ -133,7 +134,7 @@ public class CertificateIssuerUniqueIdentity implements CertAttrSet {
throw new IOException("Attribute must be of type UniqueIdentity.");
}
if (name.equalsIgnoreCase(ID)) {
- id = (UniqueIdentity)obj;
+ id = (UniqueIdentity) obj;
} else {
throw new IOException("Attribute name not recognized by " +
"CertAttrSet: CertificateIssuerUniqueIdentity.");
diff --git a/pki/base/util/src/netscape/security/x509/CertificatePoliciesExtension.java b/pki/base/util/src/netscape/security/x509/CertificatePoliciesExtension.java
index 19a986b3..3eb2dcd4 100644
--- a/pki/base/util/src/netscape/security/x509/CertificatePoliciesExtension.java
+++ b/pki/base/util/src/netscape/security/x509/CertificatePoliciesExtension.java
@@ -16,7 +16,7 @@
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package netscape.security.x509;
-
+
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -29,59 +29,58 @@ import java.util.Vector;
import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
import netscape.security.util.ObjectIdentifier;
-
+
/**
* This class defines the Certificate Policies Extension.
*
- * <p>The certificate policies extension conatins a sequence of policy
- * information terms, each of which consists of an object identifier
- * (OID) and optional qualifiers. These policy information terms
- * indicate the policy under which the certificate has been issued and
- * the purposes for which the certificate may be used. Aplications with
- * specific policy requirements are expected to have a list of those
- * policies which they will accept and to compare the policy OIDs in the
- * certificate to that list. If this extension is critical, the path
- * validation software must be able to interpret this extension, or must
- * reject the certificate.
- *
+ * <p>
+ * The certificate policies extension conatins a sequence of policy information
+ * terms, each of which consists of an object identifier (OID) and optional
+ * qualifiers. These policy information terms indicate the policy under which
+ * the certificate has been issued and the purposes for which the certificate
+ * may be used. Aplications with specific policy requirements are expected to
+ * have a list of those policies which they will accept and to compare the
+ * policy OIDs in the certificate to that list. If this extension is critical,
+ * the path validation software must be able to interpret this extension, or
+ * must reject the certificate.
+ *
* <pre>
* CertificatePolicies ::= SEQUENECE OF PolicyInformation
* </pre>
- *
- *@author Christine Ho
- *@see Extension
- *@see CertAttrSet
+ *
+ * @author Christine Ho
+ * @see Extension
+ * @see CertAttrSet
*/
public class CertificatePoliciesExtension extends Extension
-implements CertAttrSet {
+ implements CertAttrSet {
/**
*
*/
private static final long serialVersionUID = -3729294064061837367L;
/**
- * Identifier for this attribute, to be used with the
- * get, set, delete methods of Certificate, x509 type.
+ * Identifier for this attribute, to be used with the get, set, delete
+ * methods of Certificate, x509 type.
*/
public static final String IDENT = "x509.info.extensions.CertificatePolicies";
/**
* Attribute names.
*/
- public static final String INFOS = "infos";
+ public static final String INFOS = "infos";
-
- // Private data members
+ // Private data members
private Vector<CertificatePolicyInfo> mInfos;
-
+
// Encode this extension value
private void encodeThis() throws IOException {
DerOutputStream os = new DerOutputStream();
DerOutputStream tmp = new DerOutputStream();
-
+
for (int i = 0; i < mInfos.size(); i++) {
- ((CertificatePolicyInfo)mInfos.elementAt(i)).encode(tmp);
+ ((CertificatePolicyInfo) mInfos.elementAt(i)).encode(tmp);
}
- os.write(DerValue.tag_Sequence,tmp);
+ os.write(DerValue.tag_Sequence, tmp);
extensionValue = os.toByteArray();
}
@@ -93,8 +92,8 @@ implements CertAttrSet {
}
/**
- * Create a CertificatePolicies with the Vector of CertificatePolicyInfo.
- *
+ * Create a CertificatePolicies with the Vector of CertificatePolicyInfo.
+ *
* @param infos the Vector of CertificatePolicyInfo.
*/
public CertificatePoliciesExtension(Vector<CertificatePolicyInfo> infos) throws IOException {
@@ -103,32 +102,32 @@ implements CertAttrSet {
this.critical = false;
encodeThis();
}
-
+
/**
* Create a default CertificatePoliciesExtension.
*/
- public CertificatePoliciesExtension() {
- this.extensionId = PKIXExtensions.CertificatePolicies_Id;
+ public CertificatePoliciesExtension() {
+ this.extensionId = PKIXExtensions.CertificatePolicies_Id;
critical = false;
- mInfos = new Vector<CertificatePolicyInfo>(1,1);
+ mInfos = new Vector<CertificatePolicyInfo>(1, 1);
}
/**
* Create the extension from the passed DER encoded value.
- *
+ *
* @param critical true if the extension is to be treated as critical.
* @param value Array of DER encoded bytes of the actual value.
* @exception IOException on error.
*/
public CertificatePoliciesExtension(Boolean critical, Object value)
- throws IOException {
- this.extensionId = PKIXExtensions.CertificatePolicies_Id;
+ throws IOException {
+ this.extensionId = PKIXExtensions.CertificatePolicies_Id;
this.critical = critical.booleanValue();
-
+
int len = Array.getLength(value);
- byte [] extValue = new byte[len];
+ byte[] extValue = new byte[len];
for (int i = 0; i < len; i++) {
- extValue[i] = Array.getByte(value, i);
+ extValue[i] = Array.getByte(value, i);
}
this.extensionValue = extValue;
DerValue val = new DerValue(extValue);
@@ -148,16 +147,17 @@ implements CertAttrSet {
* Returns a printable representation of the policy extension.
*/
public String toString() {
- if (mInfos == null) return "";
+ if (mInfos == null)
+ return "";
String s = super.toString() + "Certificate Policies [\n"
+ mInfos.toString() + "]\n";
-
+
return (s);
}
-
+
/**
* Write the extension to the OutputStream.
- *
+ *
* @param out the OutputStream to write the extension to.
* @exception IOException on encoding errors.
*/
@@ -174,32 +174,32 @@ implements CertAttrSet {
/**
* Decode the extension from the InputStream.
- *
+ *
* @param in the InputStream to unmarshal the contents from.
* @exception IOException on decoding or validity errors.
*/
public void decode(InputStream in) throws IOException {
throw new IOException("Method not to be called directly.");
}
-
+
/**
* Set the attribute value.
*/
@SuppressWarnings("unchecked")
- public void set(String name, Object obj) throws IOException {
+ public void set(String name, Object obj) throws IOException {
clearValue();
if (name.equalsIgnoreCase(INFOS)) {
if (!(obj instanceof Vector)) {
- throw new IOException("Attribute value should be of" +
+ throw new IOException("Attribute value should be of" +
" type Vector.");
}
- mInfos = (Vector<CertificatePolicyInfo>)obj;
+ mInfos = (Vector<CertificatePolicyInfo>) obj;
} else {
- throw new IOException("Attribute name not recognized by " +
+ throw new IOException("Attribute name not recognized by " +
"CertAttrSet:CertificatePoliciesExtension.");
}
}
-
+
/**
* Get the attribute value.
*/
@@ -207,11 +207,11 @@ implements CertAttrSet {
if (name.equalsIgnoreCase(INFOS)) {
return (mInfos);
} else {
- throw new IOException("Attribute name not recognized by " +
+ throw new IOException("Attribute name not recognized by " +
"CertAttrSet:CertificatePoliciesExtension.");
}
}
-
+
/**
* Delete the attribute value.
*/
@@ -219,115 +219,94 @@ implements CertAttrSet {
if (name.equalsIgnoreCase(INFOS)) {
mInfos = null;
} else {
- throw new IOException("Attribute name not recognized by " +
+ throw new IOException("Attribute name not recognized by " +
"CertAttrSet:CertificatePoliciesExtension.");
}
}
-
+
/**
- * Return an enumeration of attributes existing within this
- * attribute.
+ * Return an enumeration of attributes existing within this attribute.
*/
public Enumeration<Vector<CertificatePolicyInfo>> getAttributes() {
Vector<Vector<CertificatePolicyInfo>> elements = new Vector<Vector<CertificatePolicyInfo>>();
elements.addElement(mInfos);
return (elements.elements());
}
-
- private static final String[] NAMES = {INFOS};
- @Override
- public Enumeration<String> getAttributeNames() {
- // TODO Auto-generated method stub
- return Collections.enumeration(Arrays.asList(NAMES));
- }
-
-
- public static void main(String args[])
- {
-/** From ASN.1 dump
+ private static final String[] NAMES = { INFOS };
- 0 30 133: SEQUENCE {
- 3 30 45: . SEQUENCE {
- 5 06 3: . . OBJECT IDENTIFIER '1 2 3 5'
- 10 30 38: . . SEQUENCE {
- 12 30 36: . . . SEQUENCE {
- 14 06 8: . . . . OBJECT IDENTIFIER cps (1 3 6 1 5 5 7 2 1)
- : . . . . . (PKIX policy qualifier)
- 24 16 24: . . . . IA5String 'http://home.netscape.com'
- : . . . . }
- : . . . }
- : . . }
- 50 30 84: . SEQUENCE {
- 52 06 2: . . OBJECT IDENTIFIER '2 3 5'
- 56 30 78: . . SEQUENCE {
- 58 30 36: . . . SEQUENCE {
- 60 06 8: . . . . OBJECT IDENTIFIER cps (1 3 6 1 5 5 7 2 1)
- : . . . . . (PKIX policy qualifier)
- 70 16 24: . . . . IA5String 'http://home.netscape.com'
- : . . . . }
- 96 30 38: . . . SEQUENCE {
- 98 06 8: . . . . OBJECT IDENTIFIER unotice (1 3 6 1 5 5 7 2 2)
- : . . . . . (PKIX policy qualifier)
- 108 30 26: . . . . SEQUENCE {
- 110 30 16: . . . . . SEQUENCE {
- 112 1E 8: . . . . . . BMPString (1993) '_..o.r.g'
- 122 02 1: . . . . . . INTEGER 1
- 125 02 1: . . . . . . INTEGER 2
- : . . . . . . }
- 128 1E 6: . . . . . BMPString (1993) '_..d.t'
- : . . . . . }
- : . . . . }
- : . . . }
- : . . }
- : . }
+ @Override
+ public Enumeration<String> getAttributeNames() {
+ // TODO Auto-generated method stub
+ return Collections.enumeration(Arrays.asList(NAMES));
+ }
- **/
+ public static void main(String args[]) {
- CertificatePolicyId plcyId0 = new CertificatePolicyId(
- new ObjectIdentifier("1.2.3.5")
- );
- PolicyQualifiers qualifiers0 = new PolicyQualifiers();
- CPSuri cpsQualifier0 = new CPSuri("http://home.netscape.com");
- PolicyQualifierInfo qualifierInfo0 = new PolicyQualifierInfo(
- PolicyQualifierInfo.QT_CPS,
- cpsQualifier0
- );
- qualifiers0.add(qualifierInfo0);
- CertificatePolicyInfo info0 = new CertificatePolicyInfo(
- plcyId0, qualifiers0);
- CertificatePolicyId plcyId1 = new CertificatePolicyId(
- new ObjectIdentifier("2.3.5")
- );
- PolicyQualifiers qualifiers1 = new PolicyQualifiers();
- DisplayText org1 = new DisplayText(DisplayText.tag_BMPString,
- "org");
- int nums[] = {1, 2};
- NoticeReference nr1 = new NoticeReference(org1, nums);
- DisplayText dt1 = new DisplayText(DisplayText.tag_BMPString,
- "dt");
- UserNotice userNotice1 = new UserNotice(nr1, dt1);
- PolicyQualifierInfo qualifierInfo1 = new PolicyQualifierInfo(
- PolicyQualifierInfo.QT_UNOTICE,
- userNotice1
- );
- qualifiers1.add(qualifierInfo0);
- qualifiers1.add(qualifierInfo1);
- CertificatePolicyInfo info1 = new CertificatePolicyInfo(
- plcyId1, qualifiers1);
- Vector<CertificatePolicyInfo> infos = new Vector<CertificatePolicyInfo>();
- infos.addElement(info0);
- infos.addElement(info1);
- try {
- CertificatePoliciesExtension ext =
- new CertificatePoliciesExtension(infos);
+ /**
+ * From ASN.1 dump
+ *
+ * 0 30 133: SEQUENCE { 3 30 45: . SEQUENCE { 5 06 3: . . OBJECT
+ * IDENTIFIER '1 2 3 5' 10 30 38: . . SEQUENCE { 12 30 36: . . .
+ * SEQUENCE { 14 06 8: . . . . OBJECT IDENTIFIER cps (1 3 6 1 5 5 7 2 1)
+ * : . . . . . (PKIX policy qualifier) 24 16 24: . . . . IA5String
+ * 'http://home.netscape.com' : . . . . } : . . . } : . . } 50 30 84: .
+ * SEQUENCE { 52 06 2: . . OBJECT IDENTIFIER '2 3 5' 56 30 78: . .
+ * SEQUENCE { 58 30 36: . . . SEQUENCE { 60 06 8: . . . . OBJECT
+ * IDENTIFIER cps (1 3 6 1 5 5 7 2 1) : . . . . . (PKIX policy
+ * qualifier) 70 16 24: . . . . IA5String 'http://home.netscape.com' : .
+ * . . . } 96 30 38: . . . SEQUENCE { 98 06 8: . . . . OBJECT IDENTIFIER
+ * unotice (1 3 6 1 5 5 7 2 2) : . . . . . (PKIX policy qualifier) 108
+ * 30 26: . . . . SEQUENCE { 110 30 16: . . . . . SEQUENCE { 112 1E 8: .
+ * . . . . . BMPString (1993) '_..o.r.g' 122 02 1: . . . . . . INTEGER 1
+ * 125 02 1: . . . . . . INTEGER 2 : . . . . . . } 128 1E 6: . . . . .
+ * BMPString (1993) '_..d.t' : . . . . . } : . . . . } : . . . } : . . }
+ * : . }
+ **/
- // BASE64 encode the whole thing and write it to stdout
- System.out.println( com.netscape.osutil.OSUtil.BtoA(ext.getExtensionValue()) );
- } catch (IOException e) {
- System.out.println(e.toString());
- }
- }
+ CertificatePolicyId plcyId0 = new CertificatePolicyId(
+ new ObjectIdentifier("1.2.3.5")
+ );
+ PolicyQualifiers qualifiers0 = new PolicyQualifiers();
+ CPSuri cpsQualifier0 = new CPSuri("http://home.netscape.com");
+ PolicyQualifierInfo qualifierInfo0 = new PolicyQualifierInfo(
+ PolicyQualifierInfo.QT_CPS,
+ cpsQualifier0
+ );
+ qualifiers0.add(qualifierInfo0);
+ CertificatePolicyInfo info0 = new CertificatePolicyInfo(
+ plcyId0, qualifiers0);
+ CertificatePolicyId plcyId1 = new CertificatePolicyId(
+ new ObjectIdentifier("2.3.5")
+ );
+ PolicyQualifiers qualifiers1 = new PolicyQualifiers();
+ DisplayText org1 = new DisplayText(DisplayText.tag_BMPString,
+ "org");
+ int nums[] = { 1, 2 };
+ NoticeReference nr1 = new NoticeReference(org1, nums);
+ DisplayText dt1 = new DisplayText(DisplayText.tag_BMPString,
+ "dt");
+ UserNotice userNotice1 = new UserNotice(nr1, dt1);
+ PolicyQualifierInfo qualifierInfo1 = new PolicyQualifierInfo(
+ PolicyQualifierInfo.QT_UNOTICE,
+ userNotice1
+ );
+ qualifiers1.add(qualifierInfo0);
+ qualifiers1.add(qualifierInfo1);
+ CertificatePolicyInfo info1 = new CertificatePolicyInfo(
+ plcyId1, qualifiers1);
+ Vector<CertificatePolicyInfo> infos = new Vector<CertificatePolicyInfo>();
+ infos.addElement(info0);
+ infos.addElement(info1);
+ try {
+ CertificatePoliciesExtension ext =
+ new CertificatePoliciesExtension(infos);
+
+ // BASE64 encode the whole thing and write it to stdout
+ System.out.println(com.netscape.osutil.OSUtil.BtoA(ext.getExtensionValue()));
+ } catch (IOException e) {
+ System.out.println(e.toString());
+ }
+ }
-
}
diff --git a/pki/base/util/src/netscape/security/x509/CertificatePolicyId.java b/pki/base/util/src/netscape/security/x509/CertificatePolicyId.java
index 2577764f..bfc93b0b 100644
--- a/pki/base/util/src/netscape/security/x509/CertificatePolicyId.java
+++ b/pki/base/util/src/netscape/security/x509/CertificatePolicyId.java
@@ -23,10 +23,9 @@ import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
import netscape.security.util.ObjectIdentifier;
-
/**
* Represent the CertificatePolicyId ASN.1 object.
- *
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.5
@@ -40,7 +39,7 @@ public class CertificatePolicyId implements java.io.Serializable {
/**
* Create a CertificatePolicyId with the ObjectIdentifier.
- *
+ *
* @param id the ObjectIdentifier for the policy id.
*/
public CertificatePolicyId(ObjectIdentifier id) {
@@ -49,7 +48,7 @@ public class CertificatePolicyId implements java.io.Serializable {
/**
* Create the object from its Der encoded value.
- *
+ *
* @param val the DER encoded value for the same.
*/
public CertificatePolicyId(DerValue val) throws IOException {
@@ -76,7 +75,7 @@ public class CertificatePolicyId implements java.io.Serializable {
/**
* Write the CertificatePolicyId to the DerOutputStream.
- *
+ *
* @param out the DerOutputStream to write the object to.
* @exception IOException on errors.
*/
diff --git a/pki/base/util/src/netscape/security/x509/CertificatePolicyInfo.java b/pki/base/util/src/netscape/security/x509/CertificatePolicyInfo.java
index 50387261..33e541c6 100644
--- a/pki/base/util/src/netscape/security/x509/CertificatePolicyInfo.java
+++ b/pki/base/util/src/netscape/security/x509/CertificatePolicyInfo.java
@@ -21,38 +21,38 @@ import java.io.IOException;
import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
-
+
/**
* Represent the CertificatePolicyInformation ASN.1 object.
- *
- * @author Christine Ho
+ *
+ * @author Christine Ho
*/
public class CertificatePolicyInfo implements java.io.Serializable {
- /**
+ /**
*
*/
private static final long serialVersionUID = -8516006396099280477L;
private CertificatePolicyId mPolicyIdentifier;
- private PolicyQualifiers mPolicyQualifiers;
+ private PolicyQualifiers mPolicyQualifiers;
/**
* Create a CertificatePolicyInfo with the passed CertificatePolicyId's.
- *
+ *
* @param id the CertificatePolicyId.
*/
public CertificatePolicyInfo(CertificatePolicyId id) {
this.mPolicyIdentifier = id;
- this.mPolicyQualifiers= null;
+ this.mPolicyQualifiers = null;
}
public CertificatePolicyInfo(CertificatePolicyId id, PolicyQualifiers qualifiers) {
this.mPolicyIdentifier = id;
- this.mPolicyQualifiers= qualifiers;
+ this.mPolicyQualifiers = qualifiers;
}
/**
* Create the CertificatePolicyInfo from the DER encoded value.
- *
+ *
* @param val the DER encoded value of the same.
*/
public CertificatePolicyInfo(DerValue val) throws IOException {
@@ -60,18 +60,18 @@ public class CertificatePolicyInfo implements java.io.Serializable {
throw new IOException("Invalid encoding for CertificatePolicyInfo");
}
mPolicyIdentifier = new CertificatePolicyId(val.data.getDerValue());
- // The specification is not clear on whether qualifier is
- // optional or not. GTE CyberTrust Root certificate has
- // no qualifier.
- if (val.data.available() == 0) {
- mPolicyQualifiers = null;
- } else {
- mPolicyQualifiers = new PolicyQualifiers(val.data.getDerValue());
- }
+ // The specification is not clear on whether qualifier is
+ // optional or not. GTE CyberTrust Root certificate has
+ // no qualifier.
+ if (val.data.available() == 0) {
+ mPolicyQualifiers = null;
+ } else {
+ mPolicyQualifiers = new PolicyQualifiers(val.data.getDerValue());
+ }
}
-
+
/**
- * return the policy identifier of the policy info
+ * return the policy identifier of the policy info
*/
public CertificatePolicyId getPolicyIdentifier() {
return (mPolicyIdentifier);
@@ -91,20 +91,20 @@ public class CertificatePolicyInfo implements java.io.Serializable {
+ "]\n";
return (s);
}
-
+
/**
* Write the CertificatePolicyInfo to the DerOutputStream.
- *
+ *
* @param out the DerOutputStream to write the object to.
* @exception IOException on errors.
*/
public void encode(DerOutputStream out) throws IOException {
DerOutputStream tmp = new DerOutputStream();
-
+
mPolicyIdentifier.encode(tmp);
- if (mPolicyQualifiers != null) {
- mPolicyQualifiers.encode(tmp);
- }
- out.write(DerValue.tag_Sequence,tmp);
+ if (mPolicyQualifiers != null) {
+ mPolicyQualifiers.encode(tmp);
+ }
+ out.write(DerValue.tag_Sequence, tmp);
}
}
diff --git a/pki/base/util/src/netscape/security/x509/CertificatePolicyMap.java b/pki/base/util/src/netscape/security/x509/CertificatePolicyMap.java
index 7ae6ce10..75ddf331 100644
--- a/pki/base/util/src/netscape/security/x509/CertificatePolicyMap.java
+++ b/pki/base/util/src/netscape/security/x509/CertificatePolicyMap.java
@@ -24,7 +24,7 @@ import netscape.security.util.DerValue;
/**
* Represent the CertificatePolicyMap ASN.1 object.
- *
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.5
@@ -35,7 +35,7 @@ public class CertificatePolicyMap {
/**
* Create a CertificatePolicyMap with the passed CertificatePolicyId's.
- *
+ *
* @param issuer the CertificatePolicyId for the issuer CA.
* @param subject the CertificatePolicyId for the subject CA.
*/
@@ -47,7 +47,7 @@ public class CertificatePolicyMap {
/**
* Create the CertificatePolicyMap from the DER encoded value.
- *
+ *
* @param val the DER encoded value of the same.
*/
public CertificatePolicyMap(DerValue val) throws IOException {
@@ -86,7 +86,7 @@ public class CertificatePolicyMap {
/**
* Write the CertificatePolicyMap to the DerOutputStream.
- *
+ *
* @param out the DerOutputStream to write the object to.
* @exception IOException on errors.
*/
@@ -95,6 +95,6 @@ public class CertificatePolicyMap {
issuerDomain.encode(tmp);
subjectDomain.encode(tmp);
- out.write(DerValue.tag_Sequence,tmp);
+ out.write(DerValue.tag_Sequence, tmp);
}
}
diff --git a/pki/base/util/src/netscape/security/x509/CertificatePolicySet.java b/pki/base/util/src/netscape/security/x509/CertificatePolicySet.java
index fafa7764..86d9c107 100644
--- a/pki/base/util/src/netscape/security/x509/CertificatePolicySet.java
+++ b/pki/base/util/src/netscape/security/x509/CertificatePolicySet.java
@@ -26,17 +26,17 @@ import netscape.security.util.DerValue;
/**
* This class defines the certificate policy set ASN.1 object.
- *
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.4
*/
public class CertificatePolicySet {
- private Vector<CertificatePolicyId> ids;
+ private Vector<CertificatePolicyId> ids;
/**
* The default constructor for this class.
- *
+ *
* @param ids the sequence of CertificatePolicyId's.
*/
public CertificatePolicySet(Vector<CertificatePolicyId> ids) {
@@ -45,14 +45,14 @@ public class CertificatePolicySet {
/**
* Create the object from the DerValue.
- *
+ *
* @param in the passed DerInputStream.
* @exception IOException on decoding errors.
*/
public CertificatePolicySet(DerInputStream in) throws IOException {
ids = new Vector<CertificatePolicyId>(1, 1);
DerValue[] seq = in.getSequence(5);
-
+
for (int i = 0; i < seq.length; i++) {
CertificatePolicyId id = new CertificatePolicyId(seq[i]);
ids.addElement(id);
@@ -72,15 +72,15 @@ public class CertificatePolicySet {
/**
* Encode the policy set to the output stream.
- *
+ *
* @param out the DerOutputStream to encode the data to.
*/
public void encode(DerOutputStream out) throws IOException {
DerOutputStream tmp = new DerOutputStream();
for (int i = 0; i < ids.size(); i++) {
- ((CertificatePolicyId)ids.elementAt(i)).encode(tmp);
+ ((CertificatePolicyId) ids.elementAt(i)).encode(tmp);
}
- out.write(DerValue.tag_Sequence,tmp);
+ out.write(DerValue.tag_Sequence, tmp);
}
}
diff --git a/pki/base/util/src/netscape/security/x509/CertificateSerialNumber.java b/pki/base/util/src/netscape/security/x509/CertificateSerialNumber.java
index a73a9ec2..1b944ca1 100644
--- a/pki/base/util/src/netscape/security/x509/CertificateSerialNumber.java
+++ b/pki/base/util/src/netscape/security/x509/CertificateSerialNumber.java
@@ -30,7 +30,7 @@ import netscape.security.util.DerValue;
/**
* This class defines the SerialNumber attribute for the Certificate.
- *
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.6
@@ -38,8 +38,8 @@ import netscape.security.util.DerValue;
*/
public class CertificateSerialNumber implements CertAttrSet {
/**
- * Identifier for this attribute, to be used with the
- * get, set, delete methods of Certificate, x509 type.
+ * Identifier for this attribute, to be used with the get, set, delete
+ * methods of Certificate, x509 type.
*/
public static final String IDENT = "x509.info.serialNumber";
@@ -49,29 +49,29 @@ public class CertificateSerialNumber implements CertAttrSet {
public static final String NAME = "serialNumber";
public static final String NUMBER = "number";
- private SerialNumber serial;
+ private SerialNumber serial;
/**
* Default constructor for the certificate attribute.
- *
+ *
* @param serial the serial number for the certificate.
*/
public CertificateSerialNumber(BigInteger num) {
- this.serial = new SerialNumber(num);
+ this.serial = new SerialNumber(num);
}
/**
* Default constructor for the certificate attribute.
- *
+ *
* @param serial the serial number for the certificate.
*/
public CertificateSerialNumber(int num) {
- this.serial = new SerialNumber(num);
+ this.serial = new SerialNumber(num);
}
/**
* Create the object, decoding the values from the passed DER stream.
- *
+ *
* @param in the DerInputStream to read the serial number from.
* @exception IOException on decoding errors.
*/
@@ -81,7 +81,7 @@ public class CertificateSerialNumber implements CertAttrSet {
/**
* Create the object, decoding the values from the passed stream.
- *
+ *
* @param in the InputStream to read the serial number from.
* @exception IOException on decoding errors.
*/
@@ -91,7 +91,7 @@ public class CertificateSerialNumber implements CertAttrSet {
/**
* Create the object, decoding the values from the passed DerValue.
- *
+ *
* @param val the DER encoded value.
* @exception IOException on decoding errors.
*/
@@ -103,13 +103,14 @@ public class CertificateSerialNumber implements CertAttrSet {
* Return the serial number as user readable string.
*/
public String toString() {
- if (serial == null) return "";
+ if (serial == null)
+ return "";
return (serial.toString());
}
/**
* Encode the serial number in DER form to the stream.
- *
+ *
* @param out the DerOutputStream to marshal the contents to.
* @exception IOException on errors.
*/
@@ -122,7 +123,7 @@ public class CertificateSerialNumber implements CertAttrSet {
/**
* Decode the serial number in DER form from the stream.
- *
+ *
* @param in the InputStream to marshal the contents from.
* @exception IOException on errors.
*/
@@ -139,7 +140,7 @@ public class CertificateSerialNumber implements CertAttrSet {
throw new IOException("Attribute must be of type SerialNumber.");
}
if (name.equalsIgnoreCase(NUMBER)) {
- serial = (SerialNumber)obj;
+ serial = (SerialNumber) obj;
} else {
throw new IOException("Attribute name not recognized by " +
"CertAttrSet:CertificateSerialNumber.");
@@ -177,10 +178,10 @@ public class CertificateSerialNumber implements CertAttrSet {
public Enumeration<String> getAttributeNames() {
Vector<String> elements = new Vector<String>();
elements.addElement(NUMBER);
-
+
return (elements.elements());
}
-
+
/**
* Return the name of this attribute.
*/
diff --git a/pki/base/util/src/netscape/security/x509/CertificateSubjectName.java b/pki/base/util/src/netscape/security/x509/CertificateSubjectName.java
index e9c558ef..405a24eb 100644
--- a/pki/base/util/src/netscape/security/x509/CertificateSubjectName.java
+++ b/pki/base/util/src/netscape/security/x509/CertificateSubjectName.java
@@ -32,7 +32,7 @@ import netscape.security.util.DerValue;
/**
* This class defines the X500Name attribute for the Certificate.
- *
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.6
@@ -44,9 +44,9 @@ public class CertificateSubjectName implements CertAttrSet, Serializable {
*/
private static final long serialVersionUID = 503643453152834350L;
/**
- * Identifier for this attribute, to be used with the
- * get, set, delete methods of Certificate, x509 type.
- */
+ * Identifier for this attribute, to be used with the get, set, delete
+ * methods of Certificate, x509 type.
+ */
public static final String IDENT = "x509.info.subject";
/**
* Sub attributes name for this CertAttrSet.
@@ -55,11 +55,11 @@ public class CertificateSubjectName implements CertAttrSet, Serializable {
public static final String DN_NAME = "dname";
// Private data member
- private X500Name dnName;
+ private X500Name dnName;
/**
* Default constructor for the certificate attribute.
- *
+ *
* @param name the X500Name
*/
public CertificateSubjectName(X500Name name) {
@@ -68,7 +68,7 @@ public class CertificateSubjectName implements CertAttrSet, Serializable {
/**
* Create the object, decoding the values from the passed DER stream.
- *
+ *
* @param in the DerInputStream to read the X500Name from.
* @exception IOException on decoding errors.
*/
@@ -78,7 +78,7 @@ public class CertificateSubjectName implements CertAttrSet, Serializable {
/**
* Create the object, decoding the values from the passed stream.
- *
+ *
* @param in the InputStream to read the X500Name from.
* @exception IOException on decoding errors.
*/
@@ -91,23 +91,24 @@ public class CertificateSubjectName implements CertAttrSet, Serializable {
* Return the name as user readable string.
*/
public String toString() {
- if (dnName == null) return "";
- return(dnName.toString());
+ if (dnName == null)
+ return "";
+ return (dnName.toString());
}
private synchronized void writeObject(ObjectOutputStream stream)
- throws IOException {
+ throws IOException {
encode(stream);
}
private synchronized void readObject(ObjectInputStream stream)
- throws IOException {
- decodeEx(stream);
+ throws IOException {
+ decodeEx(stream);
}
/**
* Encode the name in DER form to the stream.
- *
+ *
* @param out the DerOutputStream to marshal the contents to.
* @exception IOException on errors.
*/
@@ -120,7 +121,7 @@ public class CertificateSubjectName implements CertAttrSet, Serializable {
/**
* Decode the name in DER form from the stream.
- *
+ *
* @param in the InputStream to marshal the contents from.
* @exception IOException on errors.
*/
@@ -133,7 +134,7 @@ public class CertificateSubjectName implements CertAttrSet, Serializable {
/**
* Decode the name in DER form from the stream.
- *
+ *
* @param in the InputStream to marshal the contents from.
* @exception IOException on errors.
*/
@@ -151,7 +152,7 @@ public class CertificateSubjectName implements CertAttrSet, Serializable {
throw new IOException("Attribute must be of type X500Name.");
}
if (name.equalsIgnoreCase(DN_NAME)) {
- this.dnName = (X500Name)obj;
+ this.dnName = (X500Name) obj;
} else {
throw new IOException("Attribute name not recognized by " +
"CertAttrSet:CertificateSubjectName.");
@@ -163,7 +164,7 @@ public class CertificateSubjectName implements CertAttrSet, Serializable {
*/
public Object get(String name) throws IOException {
if (name.equalsIgnoreCase(DN_NAME)) {
- return(dnName);
+ return (dnName);
} else {
throw new IOException("Attribute name not recognized by " +
"CertAttrSet:CertificateSubjectName.");
@@ -190,13 +191,13 @@ public class CertificateSubjectName implements CertAttrSet, Serializable {
Vector<String> elements = new Vector<String>();
elements.addElement(DN_NAME);
- return(elements.elements());
+ return (elements.elements());
}
/**
* Return the name of this attribute.
*/
public String getName() {
- return(NAME);
+ return (NAME);
}
}
diff --git a/pki/base/util/src/netscape/security/x509/CertificateSubjectUniqueIdentity.java b/pki/base/util/src/netscape/security/x509/CertificateSubjectUniqueIdentity.java
index 7a3294cb..fd0ca4fc 100644
--- a/pki/base/util/src/netscape/security/x509/CertificateSubjectUniqueIdentity.java
+++ b/pki/base/util/src/netscape/security/x509/CertificateSubjectUniqueIdentity.java
@@ -28,9 +28,9 @@ import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
/**
- * This class defines the subject/issuer unique identity attribute
- * for the Certificate.
- *
+ * This class defines the subject/issuer unique identity attribute for the
+ * Certificate.
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.6
@@ -38,9 +38,9 @@ import netscape.security.util.DerValue;
*/
public class CertificateSubjectUniqueIdentity implements CertAttrSet {
/**
- * Identifier for this attribute, to be used with the
- * get, set, delete methods of Certificate, x509 type.
- */
+ * Identifier for this attribute, to be used with the get, set, delete
+ * methods of Certificate, x509 type.
+ */
public static final String IDENT = "x509.info.subjectID";
/**
* Sub attributes name for this CertAttrSet.
@@ -48,11 +48,11 @@ public class CertificateSubjectUniqueIdentity implements CertAttrSet {
public static final String NAME = "subjectID";
public static final String ID = "id";
- private UniqueIdentity id;
+ private UniqueIdentity id;
/**
* Default constructor for the certificate attribute.
- *
+ *
* @param key the UniqueIdentity
*/
public CertificateSubjectUniqueIdentity(UniqueIdentity id) {
@@ -61,35 +61,35 @@ public class CertificateSubjectUniqueIdentity implements CertAttrSet {
/**
* Create the object, decoding the values from the passed DER stream.
- *
+ *
* @param in the DerInputStream to read the UniqueIdentity from.
* @exception IOException on decoding errors.
*/
public CertificateSubjectUniqueIdentity(DerInputStream in)
- throws IOException {
+ throws IOException {
id = new UniqueIdentity(in);
}
/**
* Create the object, decoding the values from the passed stream.
- *
+ *
* @param in the InputStream to read the UniqueIdentity from.
* @exception IOException on decoding errors.
*/
public CertificateSubjectUniqueIdentity(InputStream in)
- throws IOException {
+ throws IOException {
DerValue val = new DerValue(in);
id = new UniqueIdentity(val);
}
/**
* Create the object, decoding the values from the passed DER value.
- *
+ *
* @param in the DerValue to read the UniqueIdentity from.
* @exception IOException on decoding errors.
*/
public CertificateSubjectUniqueIdentity(DerValue val)
- throws IOException {
+ throws IOException {
id = new UniqueIdentity(val);
}
@@ -97,13 +97,14 @@ public class CertificateSubjectUniqueIdentity implements CertAttrSet {
* Return the identity as user readable string.
*/
public String toString() {
- if (id == null) return "";
- return(id.toString());
+ if (id == null)
+ return "";
+ return (id.toString());
}
/**
* Decode the identity in DER form from the stream.
- *
+ *
* @param in the InputStream to unmarshal the contents from.
* @exception IOException on errors.
*/
@@ -114,13 +115,13 @@ public class CertificateSubjectUniqueIdentity implements CertAttrSet {
/**
* Encode the identity in DER form to the stream.
- *
+ *
* @param out the DerOutputStream to marshal the contents to.
* @exception IOException on errors.
*/
public void encode(OutputStream out) throws IOException {
DerOutputStream tmp = new DerOutputStream();
- id.encode(tmp,DerValue.createTag(DerValue.TAG_CONTEXT,false,(byte)2));
+ id.encode(tmp, DerValue.createTag(DerValue.TAG_CONTEXT, false, (byte) 2));
out.write(tmp.toByteArray());
}
@@ -133,7 +134,7 @@ public class CertificateSubjectUniqueIdentity implements CertAttrSet {
throw new IOException("Attribute must be of type UniqueIdentity.");
}
if (name.equalsIgnoreCase(ID)) {
- id = (UniqueIdentity)obj;
+ id = (UniqueIdentity) obj;
} else {
throw new IOException("Attribute name not recognized by " +
"CertAttrSet: CertificateSubjectUniqueIdentity.");
@@ -145,7 +146,7 @@ public class CertificateSubjectUniqueIdentity implements CertAttrSet {
*/
public Object get(String name) throws IOException {
if (name.equalsIgnoreCase(ID)) {
- return(id);
+ return (id);
} else {
throw new IOException("Attribute name not recognized by " +
"CertAttrSet: CertificateSubjectUniqueIdentity.");
@@ -171,10 +172,10 @@ public class CertificateSubjectUniqueIdentity implements CertAttrSet {
public Enumeration<String> getAttributeNames() {
Vector<String> elements = new Vector<String>();
elements.addElement(ID);
-
+
return (elements.elements());
}
-
+
/**
* Return the name of this attribute.
*/
diff --git a/pki/base/util/src/netscape/security/x509/CertificateValidity.java b/pki/base/util/src/netscape/security/x509/CertificateValidity.java
index 8188e8b3..46625298 100644
--- a/pki/base/util/src/netscape/security/x509/CertificateValidity.java
+++ b/pki/base/util/src/netscape/security/x509/CertificateValidity.java
@@ -35,7 +35,7 @@ import netscape.security.util.DerValue;
/**
* This class defines the interval for which the certificate is valid.
- *
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.12
@@ -47,9 +47,9 @@ public class CertificateValidity implements CertAttrSet, Serializable {
*/
private static final long serialVersionUID = 8277703278213804194L;
/**
- * Identifier for this attribute, to be used with the
- * get, set, delete methods of Certificate, x509 type.
- */
+ * Identifier for this attribute, to be used with the get, set, delete
+ * methods of Certificate, x509 type.
+ */
public static final String IDENT = "x509.info.validity";
/**
* Sub attributes name for this CertAttrSet.
@@ -60,17 +60,17 @@ public class CertificateValidity implements CertAttrSet, Serializable {
private static final long YR_2050 = 2524636800000L;
// Private data members
- private Date notBefore;
- private Date notAfter;
+ private Date notBefore;
+ private Date notAfter;
// Returns the first time the certificate is valid.
- private Date getNotBefore() {
+ private Date getNotBefore() {
return (new Date(notBefore.getTime()));
}
// Returns the last time the certificate is valid.
private Date getNotAfter() {
- return (new Date(notAfter.getTime()));
+ return (new Date(notAfter.getTime()));
}
// Construct the class from the DerValue
@@ -108,15 +108,16 @@ public class CertificateValidity implements CertAttrSet, Serializable {
/**
* Default constructor for the class.
*/
- public CertificateValidity() { }
+ public CertificateValidity() {
+ }
/**
* The default constructor for this class for the specified interval.
- *
- * @param notBefore the date and time before which the certificate
- * is not valid.
- * @param notAfter the date and time after which the certificate is
- * not valid.
+ *
+ * @param notBefore the date and time before which the certificate is not
+ * valid.
+ * @param notAfter the date and time after which the certificate is not
+ * valid.
*/
public CertificateValidity(Date notBefore, Date notAfter) {
this.notBefore = notBefore;
@@ -125,7 +126,7 @@ public class CertificateValidity implements CertAttrSet, Serializable {
/**
* Create the object, decoding the values from the passed DER stream.
- *
+ *
* @param in the DerInputStream to read the CertificateValidity from.
* @exception IOException on decoding errors.
*/
@@ -141,12 +142,12 @@ public class CertificateValidity implements CertAttrSet, Serializable {
if (notBefore == null || notAfter == null)
return "";
return ("Validity: [From: " + notBefore.toString() +
- ",\n To: " + notAfter.toString() + "]");
+ ",\n To: " + notAfter.toString() + "]");
}
/**
* Decode the CertificateValidity period from the InputStream.
- *
+ *
* @param in the InputStream to unmarshal the contents from.
* @exception IOException on errors.
*/
@@ -156,18 +157,18 @@ public class CertificateValidity implements CertAttrSet, Serializable {
}
private synchronized void writeObject(ObjectOutputStream stream)
- throws IOException {
+ throws IOException {
encode(stream);
}
private synchronized void readObject(ObjectInputStream stream)
- throws IOException {
- decode(stream);
+ throws IOException {
+ decode(stream);
}
/**
* Encode the CertificateValidity period in DER form to the stream.
- *
+ *
* @param out the OutputStream to marshal the contents to.
* @exception IOException on errors.
*/
@@ -182,7 +183,7 @@ public class CertificateValidity implements CertAttrSet, Serializable {
DerOutputStream pair = new DerOutputStream();
if (notBefore.getTime() < YR_2050) {
- pair.putUTCTime(notBefore);
+ pair.putUTCTime(notBefore);
} else
pair.putGeneralizedTime(notBefore);
@@ -192,7 +193,7 @@ public class CertificateValidity implements CertAttrSet, Serializable {
pair.putGeneralizedTime(notAfter);
}
DerOutputStream seq = new DerOutputStream();
- seq.write(DerValue.tag_Sequence,pair);
+ seq.write(DerValue.tag_Sequence, pair);
out.write(seq.toByteArray());
}
@@ -205,9 +206,9 @@ public class CertificateValidity implements CertAttrSet, Serializable {
throw new IOException("Attribute must be of type Date.");
}
if (name.equalsIgnoreCase(NOT_BEFORE)) {
- notBefore = (Date)obj;
+ notBefore = (Date) obj;
} else if (name.equalsIgnoreCase(NOT_AFTER)) {
- notAfter = (Date)obj;
+ notAfter = (Date) obj;
} else {
throw new IOException("Attribute name not recognized by " +
"CertAttrSet: CertificateValidity.");
@@ -250,10 +251,10 @@ public class CertificateValidity implements CertAttrSet, Serializable {
Vector<String> elements = new Vector<String>();
elements.addElement(NOT_BEFORE);
elements.addElement(NOT_AFTER);
-
+
return (elements.elements());
}
-
+
/**
* Return the name of this attribute.
*/
@@ -263,34 +264,34 @@ public class CertificateValidity implements CertAttrSet, Serializable {
/**
* Verify that the current time is within the validity period.
- *
+ *
* @exception CertificateExpiredException if the certificate has expired.
- * @exception CertificateNotYetValidException if the certificate is not
- * yet valid.
+ * @exception CertificateNotYetValidException if the certificate is not yet
+ * valid.
*/
public void valid()
- throws CertificateNotYetValidException, CertificateExpiredException {
+ throws CertificateNotYetValidException, CertificateExpiredException {
Date now = new Date();
valid(now);
}
/**
* Verify that the passed time is within the validity period.
- * @param now the Date against which to compare the validity
- * period.
- *
+ *
+ * @param now the Date against which to compare the validity period.
+ *
* @exception CertificateExpiredException if the certificate has expired
- * with respect to the <code>Date</code> supplied.
- * @exception CertificateNotYetValidException if the certificate is not
- * yet valid with respect to the <code>Date</code> supplied.
+ * with respect to the <code>Date</code> supplied.
+ * @exception CertificateNotYetValidException if the certificate is not yet
+ * valid with respect to the <code>Date</code> supplied.
*
*/
public void valid(Date now)
- throws CertificateNotYetValidException, CertificateExpiredException {
+ throws CertificateNotYetValidException, CertificateExpiredException {
/*
- * we use the internal Dates rather than the passed in Date
- * because someone could override the Date methods after()
- * and before() to do something entirely different.
+ * we use the internal Dates rather than the passed in Date because
+ * someone could override the Date methods after() and before() to do
+ * something entirely different.
*/
if (notBefore.after(now)) {
throw new CertificateNotYetValidException("NotBefore: " +
diff --git a/pki/base/util/src/netscape/security/x509/CertificateVersion.java b/pki/base/util/src/netscape/security/x509/CertificateVersion.java
index 951509c7..2eb45bdb 100644
--- a/pki/base/util/src/netscape/security/x509/CertificateVersion.java
+++ b/pki/base/util/src/netscape/security/x509/CertificateVersion.java
@@ -30,7 +30,7 @@ import netscape.security.util.DerValue;
/**
* This class defines the version of the X509 Certificate.
- *
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.8
@@ -40,19 +40,19 @@ public class CertificateVersion implements CertAttrSet {
/**
* X509Certificate Version 1
*/
- public static final int V1 = 0;
+ public static final int V1 = 0;
/**
* X509Certificate Version 2
*/
- public static final int V2 = 1;
+ public static final int V2 = 1;
/**
* X509Certificate Version 3
*/
- public static final int V3 = 2;
+ public static final int V3 = 2;
/**
- * Identifier for this attribute, to be used with the
- * get, set, delete methods of Certificate, x509 type.
- */
+ * Identifier for this attribute, to be used with the get, set, delete
+ * methods of Certificate, x509 type.
+ */
public static final String IDENT = "x509.info.version";
/**
* Sub attributes name for this CertAttrSet.
@@ -64,8 +64,8 @@ public class CertificateVersion implements CertAttrSet {
int version = V1;
// Returns the version number.
- private int getVersion() {
- return(version);
+ private int getVersion() {
+ return (version);
}
// Construct the class from the passed DerValue
@@ -74,14 +74,14 @@ public class CertificateVersion implements CertAttrSet {
derVal = derVal.data.getDerValue();
version = derVal.getInteger().toInt();
if (derVal.data.available() != 0) {
- throw new IOException("X.509 version, bad format");
+ throw new IOException("X.509 version, bad format");
}
}
}
/**
- * The default constructor for this class,
- * sets the version to 0 (i.e. X.509 version 1).
+ * The default constructor for this class, sets the version to 0 (i.e. X.509
+ * version 1).
*/
public CertificateVersion() {
version = V1;
@@ -89,7 +89,7 @@ public class CertificateVersion implements CertAttrSet {
/**
* The constructor for this class for the required version.
- *
+ *
* @param version the version for the certificate.
* @exception IOException if the version is not valid.
*/
@@ -106,7 +106,7 @@ public class CertificateVersion implements CertAttrSet {
/**
* Create the object, decoding the values from the passed DER stream.
- *
+ *
* @param in the DerInputStream to read the CertificateVersion from.
* @exception IOException on decoding errors.
*/
@@ -119,7 +119,7 @@ public class CertificateVersion implements CertAttrSet {
/**
* Create the object, decoding the values from the passed stream.
- *
+ *
* @param in the InputStream to read the CertificateVersion from.
* @exception IOException on decoding errors.
*/
@@ -132,13 +132,13 @@ public class CertificateVersion implements CertAttrSet {
/**
* Create the object, decoding the values from the passed DerValue.
- *
+ *
* @param val the Der encoded value.
* @exception IOException on decoding errors.
*/
public CertificateVersion(DerValue val) throws IOException {
version = V1;
-
+
construct(val);
}
@@ -146,12 +146,12 @@ public class CertificateVersion implements CertAttrSet {
* Return the version number of the certificate.
*/
public String toString() {
- return("Version: V" + (version+1));
+ return ("Version: V" + (version + 1));
}
/**
* Encode the CertificateVersion period in DER form to the stream.
- *
+ *
* @param out the OutputStream to marshal the contents to.
* @exception IOException on errors.
*/
@@ -164,7 +164,7 @@ public class CertificateVersion implements CertAttrSet {
tmp.putInteger(new BigInt(version));
DerOutputStream seq = new DerOutputStream();
- seq.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0),
+ seq.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0),
tmp);
out.write(seq.toByteArray());
@@ -172,14 +172,14 @@ public class CertificateVersion implements CertAttrSet {
/**
* Decode the CertificateVersion period in DER form from the stream.
- *
+ *
* @param in the InputStream to unmarshal the contents from.
* @exception IOException on errors.
*/
public void decode(InputStream in) throws IOException {
DerValue derVal = new DerValue(in);
construct(derVal);
- }
+ }
/**
* Set the attribute value.
@@ -189,7 +189,7 @@ public class CertificateVersion implements CertAttrSet {
throw new IOException("Attribute must be of type Integer.");
}
if (name.equalsIgnoreCase(VERSION)) {
- version = ((Integer)obj).intValue();
+ version = ((Integer) obj).intValue();
} else {
throw new IOException("Attribute name not recognized by " +
"CertAttrSet: CertificateVersion.");
@@ -201,7 +201,7 @@ public class CertificateVersion implements CertAttrSet {
*/
public Object get(String name) throws IOException {
if (name.equalsIgnoreCase(VERSION)) {
- return(Integer.valueOf(getVersion()));
+ return (Integer.valueOf(getVersion()));
} else {
throw new IOException("Attribute name not recognized by " +
"CertAttrSet: CertificateVersion.");
@@ -235,13 +235,13 @@ public class CertificateVersion implements CertAttrSet {
* Return the name of this attribute.
*/
public String getName() {
- return(NAME);
+ return (NAME);
}
/**
* Compare versions.
*/
public int compare(int vers) {
- return(version - vers);
+ return (version - vers);
}
}
diff --git a/pki/base/util/src/netscape/security/x509/CertificateX509Key.java b/pki/base/util/src/netscape/security/x509/CertificateX509Key.java
index f3507a14..738acbca 100644
--- a/pki/base/util/src/netscape/security/x509/CertificateX509Key.java
+++ b/pki/base/util/src/netscape/security/x509/CertificateX509Key.java
@@ -32,7 +32,7 @@ import netscape.security.util.DerValue;
/**
* This class defines the X509Key attribute for the Certificate.
- *
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.5
@@ -44,9 +44,9 @@ public class CertificateX509Key implements CertAttrSet, Serializable {
*/
private static final long serialVersionUID = 6718749024328681131L;
/**
- * Identifier for this attribute, to be used with the
- * get, set, delete methods of Certificate, x509 type.
- */
+ * Identifier for this attribute, to be used with the get, set, delete
+ * methods of Certificate, x509 type.
+ */
public static final String IDENT = "x509.info.key";
/**
* Sub attributes name for this CertAttrSet.
@@ -55,11 +55,11 @@ public class CertificateX509Key implements CertAttrSet, Serializable {
public static final String KEY = "value";
// Private data member
- private X509Key key;
+ private X509Key key;
/**
* Default constructor for the certificate attribute.
- *
+ *
* @param key the X509Key
*/
public CertificateX509Key(X509Key key) {
@@ -68,7 +68,7 @@ public class CertificateX509Key implements CertAttrSet, Serializable {
/**
* Create the object, decoding the values from the passed DER stream.
- *
+ *
* @param in the DerInputStream to read the X509Key from.
* @exception IOException on decoding errors.
*/
@@ -79,7 +79,7 @@ public class CertificateX509Key implements CertAttrSet, Serializable {
/**
* Create the object, decoding the values from the passed stream.
- *
+ *
* @param in the InputStream to read the X509Key from.
* @exception IOException on decoding errors.
*/
@@ -92,13 +92,14 @@ public class CertificateX509Key implements CertAttrSet, Serializable {
* Return the key as printable string.
*/
public String toString() {
- if (key == null) return "";
- return(key.toString());
+ if (key == null)
+ return "";
+ return (key.toString());
}
/**
* Decode the key in DER form from the stream.
- *
+ *
* @param in the InputStream to unmarshal the contents from
* @exception IOException on decoding or validity errors.
*/
@@ -108,18 +109,18 @@ public class CertificateX509Key implements CertAttrSet, Serializable {
}
private synchronized void writeObject(ObjectOutputStream stream)
- throws IOException {
+ throws IOException {
encode(stream);
}
private synchronized void readObject(ObjectInputStream stream)
- throws IOException {
- decode(stream);
+ throws IOException {
+ decode(stream);
}
/**
* Encode the key in DER form to the stream.
- *
+ *
* @param out the OutputStream to marshal the contents to.
* @exception IOException on errors.
*/
@@ -138,7 +139,7 @@ public class CertificateX509Key implements CertAttrSet, Serializable {
throw new IOException("Attribute must be of type X509Key.");
}
if (name.equalsIgnoreCase(KEY)) {
- this.key = (X509Key)obj;
+ this.key = (X509Key) obj;
} else {
throw new IOException("Attribute name not recognized by " +
"CertAttrSet: CertificateX509Key.");
@@ -150,7 +151,7 @@ public class CertificateX509Key implements CertAttrSet, Serializable {
*/
public Object get(String name) throws IOException {
if (name.equalsIgnoreCase(KEY)) {
- return(key);
+ return (key);
} else {
throw new IOException("Attribute name not recognized by " +
"CertAttrSet: CertificateX509Key.");
@@ -161,12 +162,12 @@ public class CertificateX509Key implements CertAttrSet, Serializable {
* Delete the attribute value.
*/
public void delete(String name) throws IOException {
- if (name.equalsIgnoreCase(KEY)) {
- key = null;
- } else {
+ if (name.equalsIgnoreCase(KEY)) {
+ key = null;
+ } else {
throw new IOException("Attribute name not recognized by " +
"CertAttrSet: CertificateX509Key.");
- }
+ }
}
/**
@@ -177,13 +178,13 @@ public class CertificateX509Key implements CertAttrSet, Serializable {
Vector<String> elements = new Vector<String>();
elements.addElement(KEY);
- return(elements.elements());
+ return (elements.elements());
}
/**
* Return the name of this attribute.
*/
public String getName() {
- return(NAME);
+ return (NAME);
}
}
diff --git a/pki/base/util/src/netscape/security/x509/DNSName.java b/pki/base/util/src/netscape/security/x509/DNSName.java
index 361c2357..0b1bf773 100644
--- a/pki/base/util/src/netscape/security/x509/DNSName.java
+++ b/pki/base/util/src/netscape/security/x509/DNSName.java
@@ -23,9 +23,9 @@ import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
/**
- * This class implements the DNSName as required by the GeneralNames
- * ASN.1 object.
- *
+ * This class implements the DNSName as required by the GeneralNames ASN.1
+ * object.
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.4
@@ -39,7 +39,7 @@ public class DNSName implements GeneralNameInterface {
/**
* Create the DNSName object from the passed encoded Der value.
- *
+ *
* @param derValue the encoded DER DNSName.
* @exception IOException on error.
*/
@@ -49,7 +49,7 @@ public class DNSName implements GeneralNameInterface {
/**
* Create the DNSName object with the specified name.
- *
+ *
* @param name the DNSName.
*/
public DNSName(String name) {
@@ -65,7 +65,7 @@ public class DNSName implements GeneralNameInterface {
/**
* Encode the DNS name into the DerOutputStream.
- *
+ *
* @param out the DER stream to encode the DNSName to.
* @exception IOException on encoding errors.
*/
diff --git a/pki/base/util/src/netscape/security/x509/DeltaCRLIndicatorExtension.java b/pki/base/util/src/netscape/security/x509/DeltaCRLIndicatorExtension.java
index 5a56547a..3c8c791a 100755
--- a/pki/base/util/src/netscape/security/x509/DeltaCRLIndicatorExtension.java
+++ b/pki/base/util/src/netscape/security/x509/DeltaCRLIndicatorExtension.java
@@ -32,19 +32,19 @@ import netscape.security.util.DerValue;
/**
* Represent the Delta CRL Indicator Extension.
- *
- * <p>The delta CRL indicator is a critical CRL extension
- * that identifies a delta-CRL. The value of BaseCRLNumber
- * identifies the CRL number of the base CRL that was used
- * as the starting point in the generation of this delta- CRL.
- * The delta-CRL contains the changes between the base CRL
- * and the current CRL issued along with the delta-CRL.
- *
+ *
+ * <p>
+ * The delta CRL indicator is a critical CRL extension that identifies a
+ * delta-CRL. The value of BaseCRLNumber identifies the CRL number of the base
+ * CRL that was used as the starting point in the generation of this delta- CRL.
+ * The delta-CRL contains the changes between the base CRL and the current CRL
+ * issued along with the delta-CRL.
+ *
* @see Extension
* @see CertAttrSet
*/
public class DeltaCRLIndicatorExtension extends Extension
-implements CertAttrSet {
+ implements CertAttrSet {
/**
*
@@ -66,7 +66,8 @@ implements CertAttrSet {
try {
OIDMap.addAttribute(DeltaCRLIndicatorExtension.class.getName(),
OID, DeltaCRLIndicatorExtension.class.getSimpleName());
- } catch (CertificateException e) {}
+ } catch (CertificateException e) {
+ }
}
// Encode this extension value
@@ -79,9 +80,9 @@ implements CertAttrSet {
}
/**
- * Create a DeltaCRLIndicatorExtension with the integer value.
- * The criticality is set to true.
- *
+ * Create a DeltaCRLIndicatorExtension with the integer value. The
+ * criticality is set to true.
+ *
* @param baseCRLNum the value to be set for the extension.
*/
public DeltaCRLIndicatorExtension(int baseCRLNum) throws IOException {
@@ -92,9 +93,9 @@ implements CertAttrSet {
}
/**
- * Create a DeltaCRLIndicatorExtension with the BigInteger value.
- * The criticality is set to true.
- *
+ * Create a DeltaCRLIndicatorExtension with the BigInteger value. The
+ * criticality is set to true.
+ *
* @param baseCRLNum the value to be set for the extension.
*/
public DeltaCRLIndicatorExtension(BigInteger baseCRLNum) throws IOException {
@@ -106,12 +107,12 @@ implements CertAttrSet {
/**
* Create a DeltaCRLIndicatorExtension with the BigInteger value.
- *
+ *
* @param critical true if the extension is to be treated as critical.
* @param baseCRLNum the value to be set for the extension.
*/
public DeltaCRLIndicatorExtension(Boolean critical, BigInteger baseCRLNum)
- throws IOException {
+ throws IOException {
this.baseCRLNumber = new BigInt(baseCRLNum);
this.extensionId = PKIXExtensions.DeltaCRLIndicator_Id;
this.critical = critical.booleanValue();
@@ -120,13 +121,13 @@ implements CertAttrSet {
/**
* Create the extension from the passed DER encoded value of the same.
- *
+ *
* @param critical true if the extension is to be treated as critical.
* @param value Array of DER encoded bytes of the actual value.
* @exception IOException on error.
*/
public DeltaCRLIndicatorExtension(Boolean critical, Object value)
- throws IOException {
+ throws IOException {
this.extensionId = PKIXExtensions.DeltaCRLIndicator_Id;
this.critical = critical.booleanValue();
@@ -148,9 +149,9 @@ implements CertAttrSet {
if (!(obj instanceof BigInteger)) {
throw new IOException("Attribute must be of type BigInteger.");
}
- baseCRLNumber = new BigInt((BigInteger)obj);
+ baseCRLNumber = new BigInt((BigInteger) obj);
} else {
- throw new IOException("Attribute name not recognized by"+
+ throw new IOException("Attribute name not recognized by" +
" CertAttrSet:DeltaCRLIndicator.");
}
}
@@ -160,10 +161,12 @@ implements CertAttrSet {
*/
public Object get(String name) throws IOException {
if (name.equalsIgnoreCase(NUMBER)) {
- if (baseCRLNumber == null) return null;
- else return baseCRLNumber.toBigInteger();
+ if (baseCRLNumber == null)
+ return null;
+ else
+ return baseCRLNumber.toBigInteger();
} else {
- throw new IOException("Attribute name not recognized by"+
+ throw new IOException("Attribute name not recognized by" +
" CertAttrSet:DeltaCRLIndicator.");
}
}
@@ -175,7 +178,7 @@ implements CertAttrSet {
if (name.equalsIgnoreCase(NUMBER)) {
baseCRLNumber = null;
} else {
- throw new IOException("Attribute name not recognized by"+
+ throw new IOException("Attribute name not recognized by" +
" CertAttrSet:DeltaCRLIndicator.");
}
}
@@ -185,14 +188,14 @@ implements CertAttrSet {
*/
public String toString() {
String s = super.toString() + "Delta CRL Indicator: " +
- ((baseCRLNumber == null) ? "": baseCRLNumber.toString())
+ ((baseCRLNumber == null) ? "" : baseCRLNumber.toString())
+ "\n";
return (s);
}
/**
* Decode the extension from the InputStream.
- *
+ *
* @param in the InputStream to unmarshal the contents from.
* @exception IOException on decoding or validity errors.
*/
@@ -202,31 +205,30 @@ implements CertAttrSet {
/**
* Write the extension to the DerOutputStream.
- *
+ *
* @param out the DerOutputStream to write the extension to.
* @exception IOException on encoding errors.
*/
public void encode(OutputStream out) throws IOException {
- DerOutputStream tmp = new DerOutputStream();
-
- if (this.extensionValue == null) {
- this.extensionId = PKIXExtensions.DeltaCRLIndicator_Id;
- this.critical = true;
- encodeThis();
- }
- super.encode(tmp);
- out.write(tmp.toByteArray());
+ DerOutputStream tmp = new DerOutputStream();
+
+ if (this.extensionValue == null) {
+ this.extensionId = PKIXExtensions.DeltaCRLIndicator_Id;
+ this.critical = true;
+ encodeThis();
+ }
+ super.encode(tmp);
+ out.write(tmp.toByteArray());
}
/**
* Return an enumeration of names of attributes existing within this
* attribute.
*/
- public Enumeration<String> getAttributeNames () {
+ public Enumeration<String> getAttributeNames() {
Vector<String> elements = new Vector<String>();
elements.addElement(NUMBER);
return (elements.elements());
}
}
-
diff --git a/pki/base/util/src/netscape/security/x509/DirStrConverter.java b/pki/base/util/src/netscape/security/x509/DirStrConverter.java
index 261a909d..408210b9 100644
--- a/pki/base/util/src/netscape/security/x509/DirStrConverter.java
+++ b/pki/base/util/src/netscape/security/x509/DirStrConverter.java
@@ -25,174 +25,158 @@ import sun.io.CharToByteConverter;
/**
* A DirStrConverter converts a string to a DerValue of ASN.1 Directory String,
- * which is a CHOICE of Printable (subset of ASCII), T.61 (Teletex) or
- * Universal String (UCS-4), and vice versa.
- *
- * <p>The string to DerValue conversion is done as follows.
- * If the string has only PrintableString characters it is converted
- * to a ASN.1 Printable String using the PrintableString
- * CharToByteConverter from the global default ASN1CharStrConvMap.
- * If it has only characters covered in the PrintableString or T.61
- * character set it is converted to a ASN.1 T.61 string using the T.61
- * CharToByteConverter from the ASN1CharStrCovnMap.
- * Otherwise it is converted to a ASN.1 UniversalString (UCS-4 character set)
- * which covers all characters.
- *
+ * which is a CHOICE of Printable (subset of ASCII), T.61 (Teletex) or Universal
+ * String (UCS-4), and vice versa.
+ *
+ * <p>
+ * The string to DerValue conversion is done as follows. If the string has only
+ * PrintableString characters it is converted to a ASN.1 Printable String using
+ * the PrintableString CharToByteConverter from the global default
+ * ASN1CharStrConvMap. If it has only characters covered in the PrintableString
+ * or T.61 character set it is converted to a ASN.1 T.61 string using the T.61
+ * CharToByteConverter from the ASN1CharStrCovnMap. Otherwise it is converted to
+ * a ASN.1 UniversalString (UCS-4 character set) which covers all characters.
+ *
* @see AVAValueConverter
* @see ASN1CharStrConvMap
- *
+ *
* @author Lily Hsiao, Slava Galperin at Netscape Communications, Inc.
*/
-
-public class DirStrConverter implements AVAValueConverter
-{
+public class DirStrConverter implements AVAValueConverter {
// public constructors
/**
* Constructs a DirStrConverter.
*/
- public DirStrConverter()
- {
+ public DirStrConverter() {
}
// public functions
/**
* Converts a string to a DER encoded ASN1 Directory String, which is a
- * CHOICE of PrintableString, T.61String or UniversalString.
- * The string is taken as is i.e. should not be in Ldap DN string syntax.
- *
- * @param ds a string representing a directory string value.
- *
- * @return a DerValue
- *
- * @exception IOException if the string cannot be converted, such as
- * when a UniversalString CharToByteConverter
- * isn't available and the string contains
- * characters covered only in the universal
- * string (or UCS-4) character set.
+ * CHOICE of PrintableString, T.61String or UniversalString. The string is
+ * taken as is i.e. should not be in Ldap DN string syntax.
+ *
+ * @param ds a string representing a directory string value.
+ *
+ * @return a DerValue
+ *
+ * @exception IOException if the string cannot be converted, such as when a
+ * UniversalString CharToByteConverter isn't available and
+ * the string contains characters covered only in the
+ * universal string (or UCS-4) character set.
*/
- private static byte[] DefEncodingOrder =
- new byte[] {
- DerValue.tag_PrintableString,
- DerValue.tag_T61String,
- DerValue.tag_UniversalString
- };
-
- public static synchronized void
- setDefEncodingOrder(byte[] defEncodingOrder)
- {
- DefEncodingOrder = defEncodingOrder;
+ private static byte[] DefEncodingOrder =
+ new byte[] {
+ DerValue.tag_PrintableString,
+ DerValue.tag_T61String,
+ DerValue.tag_UniversalString
+ };
+
+ public static synchronized void
+ setDefEncodingOrder(byte[] defEncodingOrder) {
+ DefEncodingOrder = defEncodingOrder;
}
- public DerValue getValue(String ds)
- throws IOException
- {
- return getValue(ds, DefEncodingOrder);
+ public DerValue getValue(String ds)
+ throws IOException {
+ return getValue(ds, DefEncodingOrder);
}
/**
* Like getValue(String) with specified DER tags as encoding order.
*/
public DerValue getValue(String ds, byte[] tags)
- throws IOException
- {
- // try to convert to printable, then t61 the universal -
- // i.e. from minimal to the most liberal.
-
- int ret = -1;
- CharToByteConverter cbc;
- DerValue value;
- byte[] bbuf, derBuf;
- int i;
-
- if (tags == null || tags.length == 0)
- tags = DefEncodingOrder;
-
- bbuf = new byte[4*ds.length()];
- for (i = 0; i < tags.length; i++)
- {
- try {
- cbc = ASN1CharStrConvMap.getDefault().getCBC(tags[i]);
- if (cbc == null)
- continue;
- ret = cbc.convert(ds.toCharArray(), 0, ds.length(),
- bbuf, 0, bbuf.length);
- break;
- }
- catch (java.io.CharConversionException e) {
- continue;
- }
- catch (InstantiationException e) {
- throw new IOException("Cannot instantiate CharToByteConverter");
- }
- catch (IllegalAccessException e) {
- throw new IOException(
- "Illegal Access loading CharToByteConverter");
- }
- }
- if (ret == -1) {
- throw new IOException(
- "Cannot convert the directory string value to a ASN.1 type");
- }
-
- derBuf = new byte[ret];
- System.arraycopy(bbuf, 0, derBuf, 0, ret);
- return new DerValue(tags[i], derBuf);
+ throws IOException {
+ // try to convert to printable, then t61 the universal -
+ // i.e. from minimal to the most liberal.
+
+ int ret = -1;
+ CharToByteConverter cbc;
+ DerValue value;
+ byte[] bbuf, derBuf;
+ int i;
+
+ if (tags == null || tags.length == 0)
+ tags = DefEncodingOrder;
+
+ bbuf = new byte[4 * ds.length()];
+ for (i = 0; i < tags.length; i++) {
+ try {
+ cbc = ASN1CharStrConvMap.getDefault().getCBC(tags[i]);
+ if (cbc == null)
+ continue;
+ ret = cbc.convert(ds.toCharArray(), 0, ds.length(),
+ bbuf, 0, bbuf.length);
+ break;
+ } catch (java.io.CharConversionException e) {
+ continue;
+ } catch (InstantiationException e) {
+ throw new IOException("Cannot instantiate CharToByteConverter");
+ } catch (IllegalAccessException e) {
+ throw new IOException(
+ "Illegal Access loading CharToByteConverter");
+ }
+ }
+ if (ret == -1) {
+ throw new IOException(
+ "Cannot convert the directory string value to a ASN.1 type");
+ }
+
+ derBuf = new byte[ret];
+ System.arraycopy(bbuf, 0, derBuf, 0, ret);
+ return new DerValue(tags[i], derBuf);
}
/**
- * Creates a DerValue from a BER encoded value, obtained from for example
- * a attribute value in octothorpe form of a Ldap DN string.
- * Checks if the BER encoded value is legal for a DirectoryString.
- *
+ * Creates a DerValue from a BER encoded value, obtained from for example a
+ * attribute value in octothorpe form of a Ldap DN string. Checks if the BER
+ * encoded value is legal for a DirectoryString.
+ *
* NOTE: currently only supports DER encoding for the BER encoded value.
- *
- * @param berStream Byte array of a BER encoded value.
- *
- * @return DerValue object.
- *
- * @exception IOException If the BER value cannot be converted to a
- * valid Directory String DER value.
+ *
+ * @param berStream Byte array of a BER encoded value.
+ *
+ * @return DerValue object.
+ *
+ * @exception IOException If the BER value cannot be converted to a valid
+ * Directory String DER value.
*/
public DerValue getValue(byte[] berByteStream)
- throws IOException
- {
- DerValue value = new DerValue(berByteStream);
-
- /*
- if (value.tag != DerValue.tag_PrintableString &&
- value.tag != DerValue.tag_T61String &&
- value.tag != DerValue.tag_UniversalString)
- throw new IOException("Invalid Directory String AVA Value");
- */
-
- return value;
+ throws IOException {
+ DerValue value = new DerValue(berByteStream);
+
+ /*
+ * if (value.tag != DerValue.tag_PrintableString && value.tag !=
+ * DerValue.tag_T61String && value.tag != DerValue.tag_UniversalString)
+ * throw new IOException("Invalid Directory String AVA Value");
+ */
+
+ return value;
}
/**
- * Converts a DerValue to a string.
- * The string is not in any syntax, such as RFC1779 string syntax.
- *
- * @param avaValue a DerValue
- * @return a string if the value can be converted.
- * @exception IOException if a ByteToCharConverter needed for the
- * conversion is not available.
+ * Converts a DerValue to a string. The string is not in any syntax, such as
+ * RFC1779 string syntax.
+ *
+ * @param avaValue a DerValue
+ * @return a string if the value can be converted.
+ * @exception IOException if a ByteToCharConverter needed for the conversion
+ * is not available.
*/
public String getAsString(DerValue avaValue)
- throws IOException
- {
- /*
- if (avaValue.tag != DerValue.tag_PrintableString &&
- avaValue.tag != DerValue.tag_BMPString &&
- avaValue.tag != DerValue.tag_UniversalString &&
- avaValue.tag != DerValue.tag_T61String)
- throw new IllegalArgumentException(
- "Invalid Directory String value");
- // NOTE will return null if a ByteToCharConverter is not available.
- */
- return avaValue.getASN1CharString();
+ throws IOException {
+ /*
+ * if (avaValue.tag != DerValue.tag_PrintableString && avaValue.tag !=
+ * DerValue.tag_BMPString && avaValue.tag !=
+ * DerValue.tag_UniversalString && avaValue.tag !=
+ * DerValue.tag_T61String) throw new IllegalArgumentException(
+ * "Invalid Directory String value"); // NOTE will return null if a
+ * ByteToCharConverter is not available.
+ */
+ return avaValue.getASN1CharString();
}
}
diff --git a/pki/base/util/src/netscape/security/x509/DisplayText.java b/pki/base/util/src/netscape/security/x509/DisplayText.java
index 44bb4b76..f422b8de 100644
--- a/pki/base/util/src/netscape/security/x509/DisplayText.java
+++ b/pki/base/util/src/netscape/security/x509/DisplayText.java
@@ -22,47 +22,43 @@ import java.io.IOException;
import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
-
/**
* Represent the DisplayText.
- *
- * DisplayText ::= CHOICE {
- * visibleString VisibleString (SIZE (1..200)),
- * bmpString BMPString (SIZE (1..200)),
- * utf8String UTF8String (SIZE (1..200)),
- * }
- *
+ *
+ * DisplayText ::= CHOICE { visibleString VisibleString (SIZE (1..200)),
+ * bmpString BMPString (SIZE (1..200)), utf8String UTF8String (SIZE (1..200)), }
+ *
* @author Thomas Kwan
*/
public class DisplayText {
/** Tag value indicating an ASN.1 "BMPString" value. */
- public final static byte tag_IA5String = 0x16;
- public final static byte tag_BMPString = 0x1E;
- public final static byte tag_VisibleString = 0x1A;
- public final static byte tag_UTF8String = 0x0C;
+ public final static byte tag_IA5String = 0x16;
+ public final static byte tag_BMPString = 0x1E;
+ public final static byte tag_VisibleString = 0x1A;
+ public final static byte tag_UTF8String = 0x0C;
private byte mTag;
private String mS = null;
public DisplayText(byte tag, String s) {
- mTag = tag;
- mS = s;
+ mTag = tag;
+ mS = s;
}
public DisplayText(DerValue val) throws IOException {
- mTag = val.tag;
- mS = val.getAsString();
+ mTag = val.tag;
+ mS = val.getAsString();
}
/**
* Write the DisplayText to the DerOutputStream.
- *
+ *
* @param out the DerOutputStream to write the object to.
* @exception IOException on errors.
*/
public void encode(DerOutputStream out) throws IOException {
- out.putStringType(mTag, mS);
+ out.putStringType(mTag, mS);
}
public String getText() {
@@ -72,14 +68,11 @@ public class DisplayText {
public String toString() {
if (mTag == tag_IA5String) {
return "IA5String: " + mS;
- }
- else if (mTag == tag_BMPString) {
+ } else if (mTag == tag_BMPString) {
return "BMPString: " + mS;
- }
- else if (mTag == tag_VisibleString) {
+ } else if (mTag == tag_VisibleString) {
return "VisibleString: " + mS;
- }
- else {
+ } else {
return "UTF8String: " + mS;
}
}
diff --git a/pki/base/util/src/netscape/security/x509/EDIPartyName.java b/pki/base/util/src/netscape/security/x509/EDIPartyName.java
index 92f713ca..8993660d 100644
--- a/pki/base/util/src/netscape/security/x509/EDIPartyName.java
+++ b/pki/base/util/src/netscape/security/x509/EDIPartyName.java
@@ -24,14 +24,15 @@ import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
/**
- * This class defines the EDIPartyName of the GeneralName choice.
- * The ASN.1 syntax for this is:
+ * This class defines the EDIPartyName of the GeneralName choice. The ASN.1
+ * syntax for this is:
+ *
* <pre>
* EDIPartyName ::= SEQUENCE {
* nameAssigner [0] DirectoryString OPTIONAL,
* partyName [1] DirectoryString }
* </pre>
- *
+ *
* @author Hemma Prafullchandra
* @version 1.2
* @see GeneralName
@@ -53,7 +54,7 @@ public class EDIPartyName implements GeneralNameInterface {
/**
* Create the EDIPartyName object from the specified names.
- *
+ *
* @param assignerName the name of the assigner
* @param partyName the name of the EDI party.
*/
@@ -64,7 +65,7 @@ public class EDIPartyName implements GeneralNameInterface {
/**
* Create the EDIPartyName object from the specified name.
- *
+ *
* @param partyName the name of the EDI party.
*/
public EDIPartyName(String partyName) {
@@ -73,10 +74,10 @@ public class EDIPartyName implements GeneralNameInterface {
/**
* Create the EDIPartyName object from the passed encoded Der value.
- *
+ *
* @param derValue the encoded DER EDIPartyName.
* @exception IOException on error.
- */
+ */
public EDIPartyName(DerValue derValue) throws IOException {
DerInputStream in = new DerInputStream(derValue.toByteArray());
DerValue[] seq = in.getSequence(2);
@@ -87,20 +88,20 @@ public class EDIPartyName implements GeneralNameInterface {
for (int i = 0; i < len; i++) {
DerValue opt = seq[i];
- if (opt.isContextSpecific((byte)TAG_ASSIGNER) &&
- !opt.isConstructed()) {
+ if (opt.isContextSpecific((byte) TAG_ASSIGNER) &&
+ !opt.isConstructed()) {
if (assigner != null)
throw new IOException("Duplicate nameAssigner found in"
+ " EDIPartyName");
- opt = opt.data.getDerValue();
+ opt = opt.data.getDerValue();
assigner = opt.getAsString();
}
- if (opt.isContextSpecific((byte)TAG_PARTYNAME) &&
- !opt.isConstructed()) {
+ if (opt.isContextSpecific((byte) TAG_PARTYNAME) &&
+ !opt.isConstructed()) {
if (party != null)
throw new IOException("Duplicate partyName found in"
+ " EDIPartyName");
- opt = opt.data.getDerValue();
+ opt = opt.data.getDerValue();
party = opt.getAsString();
}
}
@@ -115,7 +116,7 @@ public class EDIPartyName implements GeneralNameInterface {
/**
* Encode the EDI party name into the DerOutputStream.
- *
+ *
* @param out the DER stream to encode the EDIPartyName to.
* @exception IOException on encoding errors.
*/
@@ -131,7 +132,7 @@ public class EDIPartyName implements GeneralNameInterface {
false, TAG_ASSIGNER), tmp2);
}
if (party == null)
- throw new IOException("Cannot have null partyName");
+ throw new IOException("Cannot have null partyName");
// XXX - shd check is chars fit into PrintableString
tmp.putPrintableString(party);
@@ -145,9 +146,9 @@ public class EDIPartyName implements GeneralNameInterface {
* Return the printable string.
*/
public String toString() {
- return ("EDIPartyName: " +
+ return ("EDIPartyName: " +
((assigner == null) ? "" :
- (" nameAssigner = " + assigner + ","))
+ (" nameAssigner = " + assigner + ","))
+ " partyName = " + party);
}
}
diff --git a/pki/base/util/src/netscape/security/x509/Extension.java b/pki/base/util/src/netscape/security/x509/Extension.java
index 41f3da6f..d5e49891 100644
--- a/pki/base/util/src/netscape/security/x509/Extension.java
+++ b/pki/base/util/src/netscape/security/x509/Extension.java
@@ -25,27 +25,29 @@ import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
import netscape.security.util.ObjectIdentifier;
-
/**
* Represent a X509 Extension Attribute.
- *
- * <p>Extensions are addiitonal attributes which can be inserted in a X509
- * v3 certificate. For example a "Driving License Certificate" could have
- * the driving license number as a extension.
- *
- * <p>Extensions are represented as a sequence of the extension identifier
- * (Object Identifier), a boolean flag stating whether the extension is to
- * be treated as being critical and the extension value itself (this is again
- * a DER encoding of the extension value).
+ *
+ * <p>
+ * Extensions are addiitonal attributes which can be inserted in a X509 v3
+ * certificate. For example a "Driving License Certificate" could have the
+ * driving license number as a extension.
+ *
+ * <p>
+ * Extensions are represented as a sequence of the extension identifier (Object
+ * Identifier), a boolean flag stating whether the extension is to be treated as
+ * being critical and the extension value itself (this is again a DER encoding
+ * of the extension value).
+ *
* <pre>
* ASN.1 definition of Extension:
* Extension ::= SEQUENCE {
- * ExtensionId OBJECT IDENTIFIER,
- * critical BOOLEAN DEFAULT FALSE,
- * extensionValue OCTET STRING
+ * ExtensionId OBJECT IDENTIFIER,
+ * critical BOOLEAN DEFAULT FALSE,
+ * extensionValue OCTET STRING
* }
* </pre>
- *
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.9
@@ -55,14 +57,15 @@ public class Extension implements Serializable {
*
*/
private static final long serialVersionUID = -643549610716024753L;
- protected ObjectIdentifier extensionId = null;
- protected boolean critical = false;
- protected byte[] extensionValue = null;
+ protected ObjectIdentifier extensionId = null;
+ protected boolean critical = false;
+ protected byte[] extensionValue = null;
/**
- * Default constructor. Used only by sub-classes.
+ * Default constructor. Used only by sub-classes.
*/
- public Extension() { }
+ public Extension() {
+ }
/**
* Constructs an extension from a DER encoded array of bytes.
@@ -107,8 +110,8 @@ public class Extension implements Serializable {
}
/**
- * Constructs an Extension from another extension. To be used for
- * creating decoded subclasses.
+ * Constructs an Extension from another extension. To be used for creating
+ * decoded subclasses.
*
* @param ext the extension to create from.
*/
@@ -120,7 +123,7 @@ public class Extension implements Serializable {
/**
* Write the extension to the DerOutputStream.
- *
+ *
* @param out the DerOutputStream to write the extension to.
* @exception IOException on encoding errors
*/
@@ -134,7 +137,7 @@ public class Extension implements Serializable {
if (critical)
bytes.putBoolean(critical);
if (extensionValue != null)
- bytes.putOctetString(extensionValue);
+ bytes.putOctetString(extensionValue);
out.write(DerValue.tag_Sequence, bytes);
}
@@ -147,11 +150,11 @@ public class Extension implements Serializable {
}
public void setCritical(boolean c) {
- critical = c;
+ critical = c;
}
public void clearValue() {
- extensionValue = null;
+ extensionValue = null;
}
/**
@@ -162,13 +165,13 @@ public class Extension implements Serializable {
}
public void setExtensionId(ObjectIdentifier oid) {
- extensionId = oid;
+ extensionId = oid;
}
/**
* Returns the extension value as an byte array for further processing.
- * Note, this is the raw DER value of the extension, not the DER
- * encoded octet string which is in the certificate.
+ * Note, this is the raw DER value of the extension, not the DER encoded
+ * octet string which is in the certificate.
*/
public byte[] getExtensionValue() {
if (extensionValue == null)
@@ -195,9 +198,9 @@ public class Extension implements Serializable {
}
return (s);
}
-
- public String getName(){
- return this.getClass().getSimpleName();
+
+ public String getName() {
+ return this.getClass().getSimpleName();
}
-
+
}
diff --git a/pki/base/util/src/netscape/security/x509/Extensions.java b/pki/base/util/src/netscape/security/x509/Extensions.java
index 328f4a2e..df153c2d 100644
--- a/pki/base/util/src/netscape/security/x509/Extensions.java
+++ b/pki/base/util/src/netscape/security/x509/Extensions.java
@@ -34,22 +34,22 @@ import netscape.security.util.DerValue;
/**
* This class defines the Extensions attribute for the Certificate.
- *
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.11
* @see CertAttrSet
*/
public class Extensions extends Vector<Extension>
-implements CertAttrSet {
+ implements CertAttrSet {
/**
*
*/
private static final long serialVersionUID = 4597917347772057433L;
/**
- * Identifier for this attribute, to be used with the
- * get, set, delete methods of Certificate, x509 type.
- */
+ * Identifier for this attribute, to be used with the get, set, delete
+ * methods of Certificate, x509 type.
+ */
public static final String IDENT = "x509.info.extensions";
/**
* name
@@ -62,8 +62,8 @@ implements CertAttrSet {
public void parseExtension(Extension ext) throws IOException {
try {
@SuppressWarnings("unchecked")
- Class<Extension> extClass = (Class<Extension>) OIDMap.getClass(ext.getExtensionId());
- if (extClass == null) { // Unsupported extension
+ Class<Extension> extClass = (Class<Extension>) OIDMap.getClass(ext.getExtensionId());
+ if (extClass == null) { // Unsupported extension
if (ext.isCritical()) {
throw new IOException("Unsupported CRITICAL extension: "
+ ext.getExtensionId());
@@ -78,23 +78,23 @@ implements CertAttrSet {
byte[] extData = ext.getExtensionValue();
int extLen = extData.length;
- Object value = Array.newInstance(byte.class, extLen);
-
- for (int i = 0; i < extLen; i++) {
- Array.setByte(value, i, extData[i]);
- }
- Object[] passed = new Object[] {new Boolean(ext.isCritical()),
- value};
+ Object value = Array.newInstance(byte.class, extLen);
+
+ for (int i = 0; i < extLen; i++) {
+ Array.setByte(value, i, extData[i]);
+ }
+ Object[] passed = new Object[] { new Boolean(ext.isCritical()),
+ value };
Extension certExt = cons.newInstance(passed);
- map.put(certExt.getName(), certExt);
+ map.put(certExt.getName(), certExt);
addElement(certExt);
} catch (NoSuchMethodException nosuch) {
throw new IOException(nosuch.toString());
} catch (InvocationTargetException invk) {
throw new IOException(invk.getTargetException().toString());
- } catch (Exception e) {
- throw new IOException(e.toString());
+ } catch (Exception e) {
+ throw new IOException(e.toString());
}
}
@@ -107,12 +107,12 @@ implements CertAttrSet {
/**
* Create the object, decoding the values from the passed DER stream.
- *
+ *
* @param in the DerInputStream to read the Extension from.
* @exception IOException on decoding errors.
*/
public Extensions(DerInputStream in)
- throws IOException {
+ throws IOException {
map = new Hashtable<String, Extension>();
DerValue[] exts = in.getSequence(5);
@@ -125,7 +125,7 @@ implements CertAttrSet {
/**
* Decode the extensions from the InputStream.
- *
+ *
* @param in the InputStream to unmarshal the contents from.
* @exception IOException on decoding or validity errors.
*/
@@ -144,44 +144,45 @@ implements CertAttrSet {
/**
* Encode the extensions in DER form to the stream.
- *
+ *
* @param out the DerOutputStream to marshal the contents to.
* @exception CertificateException on encoding errors.
* @exception IOException on errors.
*/
public void encode(OutputStream out)
- throws CertificateException, IOException {
+ throws CertificateException, IOException {
DerOutputStream extOut = new DerOutputStream();
for (int i = 0; i < size(); i++) {
Object thisOne = elementAt(i);
if (thisOne instanceof CertAttrSet)
- ((CertAttrSet)thisOne).encode(extOut);
+ ((CertAttrSet) thisOne).encode(extOut);
else if (thisOne instanceof Extension)
- ((Extension)thisOne).encode(extOut);
+ ((Extension) thisOne).encode(extOut);
else
throw new CertificateException("Invalid extension object");
}
DerOutputStream seq = new DerOutputStream();
- seq.write(DerValue.tag_Sequence,extOut);
-
+ seq.write(DerValue.tag_Sequence, extOut);
out.write(seq.toByteArray());
}
/**
* Set the attribute value.
+ *
* @param name the extension name used in the cache.
* @param obj the object to set.
* @exception IOException if the object could not be cached.
*/
public void set(String name, Object obj) throws IOException {
- map.put(name,(Extension) obj);
+ map.put(name, (Extension) obj);
addElement((Extension) obj);
}
/**
* Get the attribute value.
+ *
* @param name the extension name used in the lookup.
* @exception IOException if named extension is not found.
*/
@@ -195,6 +196,7 @@ implements CertAttrSet {
/**
* Delete the attribute value.
+ *
* @param name the extension name used in the lookup.
* @exception IOException if named extension is not found.
*/
@@ -211,14 +213,14 @@ implements CertAttrSet {
* Return an enumeration of names of attributes existing within this
* attribute.
*/
- public Enumeration<String> getAttributeNames () {
+ public Enumeration<String> getAttributeNames() {
return map.keys();
}
/**
* Return the name of this attribute.
*/
- public String getName () {
+ public String getName() {
return getClass().getSimpleName();
}
}
diff --git a/pki/base/util/src/netscape/security/x509/FreshestCRLExtension.java b/pki/base/util/src/netscape/security/x509/FreshestCRLExtension.java
index 2a479cfc..117a3f80 100644
--- a/pki/base/util/src/netscape/security/x509/FreshestCRLExtension.java
+++ b/pki/base/util/src/netscape/security/x509/FreshestCRLExtension.java
@@ -36,22 +36,21 @@ import org.mozilla.jss.asn1.InvalidBERException;
import org.mozilla.jss.asn1.SEQUENCE;
/**
- * An extension that tells applications where to find
- * the latest (freshest) delta CRL for this certificate
- * or full CRL.
- *
+ * An extension that tells applications where to find the latest (freshest)
+ * delta CRL for this certificate or full CRL.
+ *
* <pre>
* cRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
- *
+ *
* DistributionPoint ::= SEQUENCE {
* distributionPoint [0] DistributionPointName OPTIONAL,
* reasons [1] ReasonFlags OPTIONAL,
* cRLIssuer [2] GeneralNames OPTIONAL }
- *
+ *
* DistributionPointName ::= CHOICE {
* fullName [0] GeneralNames,
* nameRelativeToCRLIssuer [1] RelativeDistinguishedName }
- *
+ *
* ReasonFlags ::= BIT STRING {
* unused (0),
* keyCompromise (1),
@@ -63,8 +62,7 @@ import org.mozilla.jss.asn1.SEQUENCE;
* </pre>
*/
public class FreshestCRLExtension extends Extension
- implements CertAttrSet
-{
+ implements CertAttrSet {
/**
*
@@ -74,14 +72,13 @@ public class FreshestCRLExtension extends Extension
// vector of CRLDistributionPoint
private SEQUENCE distributionPoints = new SEQUENCE();
- public FreshestCRLExtension() {
+ public FreshestCRLExtension() {
this.extensionId = PKIXExtensions.FreshestCRL_Id;
this.critical = false;
}
// Cached DER-encoding to improve performance.
- private byte[] cachedEncoding=null;
-
+ private byte[] cachedEncoding = null;
// The Object Identifier for this extension.
public static final String OID = "2.5.29.46";
@@ -90,7 +87,8 @@ public class FreshestCRLExtension extends Extension
try {
OIDMap.addAttribute(FreshestCRLExtension.class.getName(),
OID, FreshestCRLExtension.class.getSimpleName());
- } catch (CertificateException e) {}
+ } catch (CertificateException e) {
+ }
}
/**
@@ -99,34 +97,34 @@ public class FreshestCRLExtension extends Extension
* extension.
*/
public FreshestCRLExtension(Boolean critical, Object value)
- //throws IOException
+ // throws IOException
{
- try {
- this.extensionId = PKIXExtensions.FreshestCRL_Id;
- this.critical = critical.booleanValue();
- this.extensionValue = (byte[])((byte[])value).clone();
-
- // decode the value
try {
- SEQUENCE.OF_Template seqOfCRLDP =
- new SEQUENCE.OF_Template( CRLDistributionPoint.getTemplate() );
-
- distributionPoints =
- (SEQUENCE) ASN1Util.decode( seqOfCRLDP, extensionValue );
- } catch(InvalidBERException e) {
- throw new IOException("Invalid BER-encoding: " + e.toString());
+ this.extensionId = PKIXExtensions.FreshestCRL_Id;
+ this.critical = critical.booleanValue();
+ this.extensionValue = (byte[]) ((byte[]) value).clone();
+
+ // decode the value
+ try {
+ SEQUENCE.OF_Template seqOfCRLDP =
+ new SEQUENCE.OF_Template(CRLDistributionPoint.getTemplate());
+
+ distributionPoints =
+ (SEQUENCE) ASN1Util.decode(seqOfCRLDP, extensionValue);
+ } catch (InvalidBERException e) {
+ throw new IOException("Invalid BER-encoding: " + e.toString());
+ }
+ } catch (IOException e) {
+ System.out.println("Big error");
+ System.out.println(e);
+ e.printStackTrace();
+ // throw e;
}
- } catch(IOException e) {
- System.out.println("Big error");
- System.out.println(e);
- e.printStackTrace();
- //throw e;
- }
}
/**
- * Creates a new FreshestCRL extension, with the given
- * distribution point as the first element.
+ * Creates a new FreshestCRL extension, with the given distribution point as
+ * the first element.
*/
public FreshestCRLExtension(CRLDistributionPoint dp) {
this.extensionId = PKIXExtensions.FreshestCRL_Id;
@@ -156,20 +154,18 @@ public class FreshestCRLExtension extends Extension
return (CRLDistributionPoint) distributionPoints.elementAt(index);
}
- /**
- * Sets the criticality of this extension. PKIX dictates that this
- * extension SHOULD NOT be critical, so applications can make it critical
- * if they have a very good reason. By default, the extension is not
- * critical.
+ /**
+ * Sets the criticality of this extension. PKIX dictates that this extension
+ * SHOULD NOT be critical, so applications can make it critical if they have
+ * a very good reason. By default, the extension is not critical.
*/
public void setCritical(boolean critical) {
this.critical = critical;
}
/**
- * Encodes this extension to the given DerOutputStream.
- * This method re-encodes each time it is called, so it is not very
- * efficient.
+ * Encodes this extension to the given DerOutputStream. This method
+ * re-encodes each time it is called, so it is not very efficient.
*/
public void encode(DerOutputStream out) throws IOException {
extensionValue = ASN1Util.encode(distributionPoints);
@@ -177,19 +173,19 @@ public class FreshestCRLExtension extends Extension
}
/**
- * Should be called if any change is made to this data structure
- * so that the cached DER encoding can be discarded.
+ * Should be called if any change is made to this data structure so that the
+ * cached DER encoding can be discarded.
*/
public void flushCachedEncoding() {
cachedEncoding = null;
}
- /////////////////////////////////////////////////////////////
+ // ///////////////////////////////////////////////////////////
// CertAttrSet interface
// This interface is not really appropriate for this extension
// because it is so complicated. Therefore, we only provide a
// minimal implementation.
- /////////////////////////////////////////////////////////////
+ // ///////////////////////////////////////////////////////////
public String toString() {
return FreshestCRLExtension.class.getSimpleName();
}
@@ -198,9 +194,8 @@ public class FreshestCRLExtension extends Extension
* DER-encodes this extension to the given OutputStream.
*/
public void encode(OutputStream ostream)
- throws CertificateException, IOException
- {
- if( cachedEncoding == null ) {
+ throws CertificateException, IOException {
+ if (cachedEncoding == null) {
// only re-encode if necessary
DerOutputStream tmp = new DerOutputStream();
encode(tmp);
@@ -210,30 +205,26 @@ public class FreshestCRLExtension extends Extension
}
public void decode(InputStream in)
- throws CertificateException, IOException
- {
+ throws CertificateException, IOException {
throw new IOException("Not supported");
}
public void set(String name, Object obj)
- throws CertificateException, IOException
- {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:FreshestCRLExtension");
+ throws CertificateException, IOException {
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:FreshestCRLExtension");
}
public Object get(String name)
- throws CertificateException, IOException
- {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:FreshestCRLExtension");
+ throws CertificateException, IOException {
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:FreshestCRLExtension");
}
public void delete(String name)
- throws CertificateException, IOException
- {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:FreshestCRLExtension");
+ throws CertificateException, IOException {
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:FreshestCRLExtension");
}
/*
@@ -243,70 +234,67 @@ public class FreshestCRLExtension extends Extension
return (new Vector<String>()).elements();
}
-
/**
* Test driver.
*/
public static void main(String args[]) {
- try {
-
- if( args.length != 1 ) {
- System.out.println("Usage: FreshestCRLExtentions "+
- "<outfile>");
- System.exit(-1);
- }
+ try {
- BufferedOutputStream bos = new BufferedOutputStream(
- new FileOutputStream(args[0]) );
-
-
- // URI only
- CRLDistributionPoint cdp = new CRLDistributionPoint();
- URIName uri = new URIName("http://www.mycrl.com/go/here");
- GeneralNames generalNames = new GeneralNames();
- generalNames.addElement(uri);
- cdp.setFullName(generalNames);
- FreshestCRLExtension crldpExt =
- new FreshestCRLExtension(cdp);
-
- // DN only
- cdp = new CRLDistributionPoint();
- X500Name dn = new X500Name("CN=Otis Smith,E=otis@fedoraproject.org"+
- ",OU=Certificate Server,O=Fedora,C=US");
- generalNames = new GeneralNames();
- generalNames.addElement(dn);
- cdp.setFullName(generalNames);
- crldpExt.addPoint(cdp);
-
- // DN + reason
- BitArray ba = new BitArray(5, new byte[] {(byte)0x28} );
- cdp = new CRLDistributionPoint();
- cdp.setFullName(generalNames);
- cdp.setReasons(ba);
- crldpExt.addPoint(cdp);
-
-
- // relative DN + reason + crlIssuer
- cdp = new CRLDistributionPoint();
- RDN rdn = new RDN("OU=foobar dept");
- cdp.setRelativeName(rdn);
- cdp.setReasons(ba);
- cdp.setCRLIssuer(generalNames);
- crldpExt.addPoint(cdp);
-
- crldpExt.setCritical(true);
- crldpExt.encode(bos);
-
- bos.close();
-
- } catch(Exception e) {
+ if (args.length != 1) {
+ System.out.println("Usage: FreshestCRLExtentions " +
+ "<outfile>");
+ System.exit(-1);
+ }
+
+ BufferedOutputStream bos = new BufferedOutputStream(
+ new FileOutputStream(args[0]));
+
+ // URI only
+ CRLDistributionPoint cdp = new CRLDistributionPoint();
+ URIName uri = new URIName("http://www.mycrl.com/go/here");
+ GeneralNames generalNames = new GeneralNames();
+ generalNames.addElement(uri);
+ cdp.setFullName(generalNames);
+ FreshestCRLExtension crldpExt =
+ new FreshestCRLExtension(cdp);
+
+ // DN only
+ cdp = new CRLDistributionPoint();
+ X500Name dn = new X500Name("CN=Otis Smith,E=otis@fedoraproject.org" +
+ ",OU=Certificate Server,O=Fedora,C=US");
+ generalNames = new GeneralNames();
+ generalNames.addElement(dn);
+ cdp.setFullName(generalNames);
+ crldpExt.addPoint(cdp);
+
+ // DN + reason
+ BitArray ba = new BitArray(5, new byte[] { (byte) 0x28 });
+ cdp = new CRLDistributionPoint();
+ cdp.setFullName(generalNames);
+ cdp.setReasons(ba);
+ crldpExt.addPoint(cdp);
+
+ // relative DN + reason + crlIssuer
+ cdp = new CRLDistributionPoint();
+ RDN rdn = new RDN("OU=foobar dept");
+ cdp.setRelativeName(rdn);
+ cdp.setReasons(ba);
+ cdp.setCRLIssuer(generalNames);
+ crldpExt.addPoint(cdp);
+
+ crldpExt.setCritical(true);
+ crldpExt.encode(bos);
+
+ bos.close();
+
+ } catch (Exception e) {
e.printStackTrace();
- }
+ }
}
- /**
- * Represents a reason that a cert may be revoked. These reasons are
+ /**
+ * Represents a reason that a cert may be revoked. These reasons are
* expressed in a ReasonFlags bit string.
*/
public static class Reason {
@@ -314,19 +302,21 @@ public class FreshestCRLExtension extends Extension
private String name;
private byte bitMask;
- private Reason() { }
+ private Reason() {
+ }
+
private Reason(String name, byte bitMask) {
this.name = name;
this.bitMask = bitMask;
map.put(name, this);
- list.addElement(this);
+ list.addElement(this);
}
private static Hashtable<String, Reason> map = new Hashtable<String, Reason>();
- private static Vector<Reason> list = new Vector<Reason>();
+ private static Vector<Reason> list = new Vector<Reason>();
public static Reason fromString(String name) {
- return map.get(name);
+ return map.get(name);
}
public String getName() {
@@ -337,61 +327,61 @@ public class FreshestCRLExtension extends Extension
return bitMask;
}
- /**
- * Given a bit array representing reason flags, extracts the reasons
- * and returns them as an array.
- *
- * @param bitFlags A bit vector containing reason flags.
- * @return An array of reasons contained in the bit vector.
- * May be zero-length but will not be null.
- */
- public static Reason[] bitArrayToReasonArray(byte bitFlags) {
- return bitArrayToReasonArray( new byte[] { bitFlags } );
- }
-
- /**
- * Given a bit array representing reason flags, extracts the reasons
- * and returns them as an array. Currently, only the first byte
- * of the bitflags are examined.
- *
- * @param bitFlags A bit vector containing reason flags. The format
- * is big-endian (MSB first). Only the first byte is examined.
- * @return An array of reasons contained in the bit vector.
- * May be zero-length but will not be null.
- */
- public static Reason[] bitArrayToReasonArray(byte[] bitFlags) {
- byte first = bitFlags[0];
- int size = list.size();
- Vector<Reason> result = new Vector<Reason>();
- for(int i = 0; i < size; i++) {
- Reason r = (Reason) list.elementAt(i);
- byte b = r.getBitMask();
- if( (first & b) != 0 ) {
- result.addElement(r);
- }
- }
- size = result.size();
- Reason[] retval = new Reason[size];
- for(int i=0; i < size; i++) {
- retval[i] = result.elementAt(i);
- }
- return retval;
- }
-
+ /**
+ * Given a bit array representing reason flags, extracts the reasons and
+ * returns them as an array.
+ *
+ * @param bitFlags A bit vector containing reason flags.
+ * @return An array of reasons contained in the bit vector. May be
+ * zero-length but will not be null.
+ */
+ public static Reason[] bitArrayToReasonArray(byte bitFlags) {
+ return bitArrayToReasonArray(new byte[] { bitFlags });
+ }
+
+ /**
+ * Given a bit array representing reason flags, extracts the reasons and
+ * returns them as an array. Currently, only the first byte of the
+ * bitflags are examined.
+ *
+ * @param bitFlags A bit vector containing reason flags. The format is
+ * big-endian (MSB first). Only the first byte is examined.
+ * @return An array of reasons contained in the bit vector. May be
+ * zero-length but will not be null.
+ */
+ public static Reason[] bitArrayToReasonArray(byte[] bitFlags) {
+ byte first = bitFlags[0];
+ int size = list.size();
+ Vector<Reason> result = new Vector<Reason>();
+ for (int i = 0; i < size; i++) {
+ Reason r = (Reason) list.elementAt(i);
+ byte b = r.getBitMask();
+ if ((first & b) != 0) {
+ result.addElement(r);
+ }
+ }
+ size = result.size();
+ Reason[] retval = new Reason[size];
+ for (int i = 0; i < size; i++) {
+ retval[i] = result.elementAt(i);
+ }
+ return retval;
+ }
+
public static final Reason UNUSED =
- new Reason("unused", (byte) 0x80);
+ new Reason("unused", (byte) 0x80);
public static final Reason KEY_COMPROMISE =
- new Reason("keyCompromise", (byte) 0x40);
+ new Reason("keyCompromise", (byte) 0x40);
public static final Reason CA_COMPROMISE =
- new Reason("cACompromise", (byte) 0x20);
+ new Reason("cACompromise", (byte) 0x20);
public static final Reason AFFILIATION_CHANGED =
- new Reason("affiliationChanged", (byte) 0x10);
+ new Reason("affiliationChanged", (byte) 0x10);
public static final Reason SUPERSEDED =
- new Reason("superseded", (byte) 0x08);
+ new Reason("superseded", (byte) 0x08);
public static final Reason CESSATION_OF_OPERATION =
- new Reason("cessationOfOperation", (byte) 0x04);
+ new Reason("cessationOfOperation", (byte) 0x04);
public static final Reason CERTIFICATE_HOLD =
- new Reason("certificateHold", (byte) 0x02);
+ new Reason("certificateHold", (byte) 0x02);
}
}
diff --git a/pki/base/util/src/netscape/security/x509/GeneralName.java b/pki/base/util/src/netscape/security/x509/GeneralName.java
index bc3395c5..f727ca8d 100644
--- a/pki/base/util/src/netscape/security/x509/GeneralName.java
+++ b/pki/base/util/src/netscape/security/x509/GeneralName.java
@@ -26,6 +26,7 @@ import netscape.security.util.DerValue;
* This class implements the ASN.1 GeneralName object class.
* <p>
* The ASN.1 syntax for this is:
+ *
* <pre>
* GeneralName ::= CHOICE {
* otherName [0] OtherName,
@@ -39,6 +40,7 @@ import netscape.security.util.DerValue;
* registeredID [8] OBJECT IDENTIFIER
* }
* </pre>
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.7
@@ -54,7 +56,7 @@ public class GeneralName implements GeneralNameInterface {
/**
* Default constructor for the class.
- *
+ *
* @param name the selected CHOICE from the list.
*/
public GeneralName(GeneralNameInterface name) {
@@ -63,90 +65,90 @@ public class GeneralName implements GeneralNameInterface {
/**
* Create the object from its DER encoded value.
- *
+ *
* @param encName the DER encoded GeneralName.
*/
public GeneralName(DerValue encName) throws IOException {
- short tag = (byte)(encName.tag & 0x1f);
+ short tag = (byte) (encName.tag & 0x1f);
- // NB. this is always encoded with the IMPLICIT tag
- // The checks only make sense if we assume implicit tagging,
- // with explicit tagging the form is always constructed.
+ // NB. this is always encoded with the IMPLICIT tag
+ // The checks only make sense if we assume implicit tagging,
+ // with explicit tagging the form is always constructed.
switch (tag) {
case GeneralNameInterface.NAME_RFC822:
if (encName.isContextSpecific() && !encName.isConstructed()) {
encName.resetTag(DerValue.tag_IA5String);
- name = new RFC822Name(encName);
+ name = new RFC822Name(encName);
} else
- throw new IOException("Invalid encoding of RFC822 name");
- break;
+ throw new IOException("Invalid encoding of RFC822 name");
+ break;
case GeneralNameInterface.NAME_DNS:
if (encName.isContextSpecific() && !encName.isConstructed()) {
encName.resetTag(DerValue.tag_IA5String);
- name = new DNSName(encName);
+ name = new DNSName(encName);
} else
- throw new IOException("Invalid encoding of DNS name");
- break;
+ throw new IOException("Invalid encoding of DNS name");
+ break;
case GeneralNameInterface.NAME_URI:
if (encName.isContextSpecific() && !encName.isConstructed()) {
encName.resetTag(DerValue.tag_IA5String);
- name = new URIName(encName);
+ name = new URIName(encName);
} else
- throw new IOException("Invalid encoding of URI");
- break;
+ throw new IOException("Invalid encoding of URI");
+ break;
case GeneralNameInterface.NAME_IP:
if (encName.isContextSpecific() && !encName.isConstructed()) {
encName.resetTag(DerValue.tag_OctetString);
- name = new IPAddressName(encName);
+ name = new IPAddressName(encName);
} else
- throw new IOException("Invalid encoding of IP address");
- break;
+ throw new IOException("Invalid encoding of IP address");
+ break;
- case GeneralNameInterface.NAME_ANY:
- if (encName.isContextSpecific() && encName.isConstructed()) {
- encName.resetTag(DerValue.tag_OctetString);
+ case GeneralNameInterface.NAME_ANY:
+ if (encName.isContextSpecific() && encName.isConstructed()) {
+ encName.resetTag(DerValue.tag_OctetString);
name = new OtherName(encName);
- } else
+ } else
throw new IOException("Invalid encoding of other name");
break;
case GeneralNameInterface.NAME_OID:
if (encName.isContextSpecific() && !encName.isConstructed()) {
encName.resetTag(DerValue.tag_ObjectId);
- name = new OIDName(encName);
+ name = new OIDName(encName);
} else
- throw new IOException("Invalid encoding of OID name");
- break;
+ throw new IOException("Invalid encoding of OID name");
+ break;
case GeneralNameInterface.NAME_DIRECTORY:
if (encName.isContextSpecific() && encName.isConstructed()) {
// Unlike the other cases, DirectoryName is EXPLICITly
// tagged, because the X.500 Name type is a CHOICE.
// Therefore, the sequence is actually nested in the
- // content of this value. We'll pretend it's an octet
+ // content of this value. We'll pretend it's an octet
// string so we can get at the content bytes.
encName.resetTag(DerValue.tag_OctetString);
byte[] content = encName.getOctetString();
- name = new X500Name( content );
+ name = new X500Name(content);
} else
- throw new IOException("Invalid encoding of Directory name");
- break;
+ throw new IOException("Invalid encoding of Directory name");
+ break;
case GeneralNameInterface.NAME_EDI:
if (encName.isContextSpecific() && encName.isConstructed()) {
encName.resetTag(DerValue.tag_Sequence);
name = new EDIPartyName(encName);
} else
- throw new IOException("Invalid encoding of EDI name");
- break;
+ throw new IOException("Invalid encoding of EDI name");
+ break;
default:
- throw new IOException("Unrecognized GeneralName tag, ("
- + tag +")");
- }
+ throw new IOException("Unrecognized GeneralName tag, ("
+ + tag + ")");
+ }
}
/**
@@ -163,35 +165,35 @@ public class GeneralName implements GeneralNameInterface {
return (name.toString());
}
- /**
- * Encode the name to the specified DerOutputStream.
- *
- * @param out the DerOutputStream to encode the the GeneralName to.
- * @exception IOException on encoding errors.
- */
- public void encode(DerOutputStream out) throws IOException {
- DerOutputStream tmp = new DerOutputStream();
- name.encode(tmp);
- int nameType = name.getType();
- boolean constructedForm;
-
- if (nameType == GeneralNameInterface.NAME_ANY ||
- nameType == GeneralNameInterface.NAME_X400 ||
- nameType == GeneralNameInterface.NAME_DIRECTORY ||
- nameType == GeneralNameInterface.NAME_EDI) {
- constructedForm = true;
- } else {
- constructedForm = false;
- }
-
- if( nameType == GeneralNameInterface.NAME_DIRECTORY ) {
- // EXPLICIT tag, because Name is a CHOICE type
- out.write(DerValue.createTag(DerValue.TAG_CONTEXT,
- constructedForm, (byte)nameType), tmp);
- } else {
- // IMPLICIT tag, the default
- out.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
- constructedForm, (byte)nameType), tmp);
- }
- }
+ /**
+ * Encode the name to the specified DerOutputStream.
+ *
+ * @param out the DerOutputStream to encode the the GeneralName to.
+ * @exception IOException on encoding errors.
+ */
+ public void encode(DerOutputStream out) throws IOException {
+ DerOutputStream tmp = new DerOutputStream();
+ name.encode(tmp);
+ int nameType = name.getType();
+ boolean constructedForm;
+
+ if (nameType == GeneralNameInterface.NAME_ANY ||
+ nameType == GeneralNameInterface.NAME_X400 ||
+ nameType == GeneralNameInterface.NAME_DIRECTORY ||
+ nameType == GeneralNameInterface.NAME_EDI) {
+ constructedForm = true;
+ } else {
+ constructedForm = false;
+ }
+
+ if (nameType == GeneralNameInterface.NAME_DIRECTORY) {
+ // EXPLICIT tag, because Name is a CHOICE type
+ out.write(DerValue.createTag(DerValue.TAG_CONTEXT,
+ constructedForm, (byte) nameType), tmp);
+ } else {
+ // IMPLICIT tag, the default
+ out.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
+ constructedForm, (byte) nameType), tmp);
+ }
+ }
}
diff --git a/pki/base/util/src/netscape/security/x509/GeneralNameInterface.java b/pki/base/util/src/netscape/security/x509/GeneralNameInterface.java
index 962206e0..6d86e11c 100644
--- a/pki/base/util/src/netscape/security/x509/GeneralNameInterface.java
+++ b/pki/base/util/src/netscape/security/x509/GeneralNameInterface.java
@@ -22,9 +22,9 @@ import java.io.IOException;
import netscape.security.util.DerOutputStream;
/**
- * This interface specifies the abstract methods which have to be
- * implemented by all the members of the GeneralNames ASN.1 object.
- *
+ * This interface specifies the abstract methods which have to be implemented by
+ * all the members of the GeneralNames ASN.1 object.
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.6
@@ -44,17 +44,15 @@ public interface GeneralNameInterface extends java.io.Serializable {
public static final int NAME_OID = 8;
/**
- * Return the type of the general name, as
- * defined above.
+ * Return the type of the general name, as defined above.
*/
int getType();
/**
* Encode the name to the specified DerOutputStream.
- *
+ *
* @param out the DerOutputStream to encode the GeneralName to.
- * @exception IOException thrown if the GeneralName could not be
- * encoded.
+ * @exception IOException thrown if the GeneralName could not be encoded.
*/
void encode(DerOutputStream out) throws IOException;
}
diff --git a/pki/base/util/src/netscape/security/x509/GeneralNames.java b/pki/base/util/src/netscape/security/x509/GeneralNames.java
index d647dd96..b855a7fd 100644
--- a/pki/base/util/src/netscape/security/x509/GeneralNames.java
+++ b/pki/base/util/src/netscape/security/x509/GeneralNames.java
@@ -25,12 +25,15 @@ import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
/**
- * This object class represents the GeneralNames type required in
- * X509 certificates.
- * <p>The ASN.1 syntax for this is:
+ * This object class represents the GeneralNames type required in X509
+ * certificates.
+ * <p>
+ * The ASN.1 syntax for this is:
+ *
* <pre>
* GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
* </pre>
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.7
@@ -43,17 +46,16 @@ public class GeneralNames extends Vector<GeneralNameInterface> {
/**
* Create the GeneralNames, decoding from the passed DerValue.
- *
- * <b>Caution when using this constructor. It may be broken!
- * Better to call addElement(gni) directly where gni is
- * a GeneralNameInterface object </b>
- *
+ *
+ * <b>Caution when using this constructor. It may be broken! Better to call
+ * addElement(gni) directly where gni is a GeneralNameInterface object </b>
+ *
* @param derVal the DerValue to construct the GeneralNames from.
* @exception GeneralNamesException on decoding error.
* @exception IOException on error.
*/
public GeneralNames(DerValue derVal)
- throws IOException, GeneralNamesException {
+ throws IOException, GeneralNamesException {
if (derVal.tag != DerValue.tag_Sequence) {
throw new IOException("Invalid encoding for GeneralNames.");
}
@@ -70,42 +72,41 @@ public class GeneralNames extends Vector<GeneralNameInterface> {
}
}
- /**
- * Create the GeneralNames
- *
- * @param names a non-empty array of names to put into the
- * generalNames
- */
-
- public GeneralNames(GeneralNameInterface[] names)
- throws GeneralNamesException {
- if (names == null || names.length==0)
- throw new GeneralNamesException("Cannot create empty GeneralNames");
-
- for (int i=0;i<names.length;i++) {
- addElement(names[i]);
- }
- }
+ /**
+ * Create the GeneralNames
+ *
+ * @param names a non-empty array of names to put into the generalNames
+ */
+ public GeneralNames(GeneralNameInterface[] names)
+ throws GeneralNamesException {
+ if (names == null || names.length == 0)
+ throw new GeneralNamesException("Cannot create empty GeneralNames");
+ for (int i = 0; i < names.length; i++) {
+ addElement(names[i]);
+ }
+ }
/**
* The default constructor for this class.
*/
public GeneralNames() {
- super(1,1);
+ super(1, 1);
}
/**
* Write the extension to the DerOutputStream.
- *
+ *
* @param out the DerOutputStream to write the extension to.
* @exception GeneralNamesException on encoding error.
* @exception IOException on error.
*/
public void encode(DerOutputStream out)
- throws IOException, GeneralNamesException {
- if (size() == 0) { return; }
+ throws IOException, GeneralNamesException {
+ if (size() == 0) {
+ return;
+ }
Enumeration<GeneralNameInterface> names = elements();
DerOutputStream temp = new DerOutputStream();
@@ -113,34 +114,35 @@ public class GeneralNames extends Vector<GeneralNameInterface> {
while (names.hasMoreElements()) {
Object obj = names.nextElement();
if (!(obj instanceof GeneralNameInterface)) {
- throw new GeneralNamesException("Element in GeneralNames "
+ throw new GeneralNamesException("Element in GeneralNames "
+ "not of type GeneralName.");
}
- GeneralNameInterface intf = (GeneralNameInterface)obj;
- if (obj instanceof GeneralName) {
- intf.encode(temp);
- } else {
- DerOutputStream gname = new DerOutputStream();
- intf.encode(gname);
- int nameType = intf.getType();
- // constructed form
- if (nameType == GeneralNameInterface.NAME_ANY ||
- nameType == GeneralNameInterface.NAME_X400 ||
- nameType == GeneralNameInterface.NAME_EDI) {
-
- temp.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
- true, (byte)nameType), gname);
- } else if ( nameType == GeneralNameInterface.NAME_DIRECTORY ) {
- // EXPLICIT tag because directoryName is a CHOICE
- temp.write(DerValue.createTag(DerValue.TAG_CONTEXT,
- true, (byte)nameType), gname);
- } else // primitive form
- temp.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
- false, (byte)nameType), gname);
- }
+ GeneralNameInterface intf = (GeneralNameInterface) obj;
+ if (obj instanceof GeneralName) {
+ intf.encode(temp);
+ } else {
+ DerOutputStream gname = new DerOutputStream();
+ intf.encode(gname);
+ int nameType = intf.getType();
+ // constructed form
+ if (nameType == GeneralNameInterface.NAME_ANY ||
+ nameType == GeneralNameInterface.NAME_X400 ||
+ nameType == GeneralNameInterface.NAME_EDI) {
+
+ temp.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
+ true, (byte) nameType), gname);
+ } else if (nameType == GeneralNameInterface.NAME_DIRECTORY) {
+ // EXPLICIT tag because directoryName is a CHOICE
+ temp.write(DerValue.createTag(DerValue.TAG_CONTEXT,
+ true, (byte) nameType), gname);
+ } else
+ // primitive form
+ temp.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
+ false, (byte) nameType), gname);
+ }
}
-
- out.write(DerValue.tag_Sequence,temp);
+
+ out.write(DerValue.tag_Sequence, temp);
}
}
diff --git a/pki/base/util/src/netscape/security/x509/GeneralNamesException.java b/pki/base/util/src/netscape/security/x509/GeneralNamesException.java
index 11c763fd..6309ed11 100644
--- a/pki/base/util/src/netscape/security/x509/GeneralNamesException.java
+++ b/pki/base/util/src/netscape/security/x509/GeneralNamesException.java
@@ -21,7 +21,7 @@ import java.security.GeneralSecurityException;
/**
* Generic General Names Exception.
- *
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.4
@@ -41,7 +41,7 @@ public class GeneralNamesException extends GeneralSecurityException {
/**
* Constructs the exception with the specified error message.
- *
+ *
* @param message the requisite error message.
*/
public GeneralNamesException(String message) {
diff --git a/pki/base/util/src/netscape/security/x509/GeneralSubtree.java b/pki/base/util/src/netscape/security/x509/GeneralSubtree.java
index 84ceca96..635427e0 100644
--- a/pki/base/util/src/netscape/security/x509/GeneralSubtree.java
+++ b/pki/base/util/src/netscape/security/x509/GeneralSubtree.java
@@ -26,6 +26,7 @@ import netscape.security.util.PrettyPrintFormat;
/**
* Represent the GeneralSubtree ASN.1 object, whose syntax is:
+ *
* <pre>
* GeneralSubtree ::= SEQUENCE {
* base GeneralName,
@@ -34,6 +35,7 @@ import netscape.security.util.PrettyPrintFormat;
* }
* BaseDistance ::= INTEGER (0..MAX)
* </pre>
+ *
* @version 1.5
* @author Amit Kapoor
* @author Hemma Prafullchandra
@@ -41,17 +43,17 @@ import netscape.security.util.PrettyPrintFormat;
public class GeneralSubtree {
private static final byte TAG_MIN = 0;
private static final byte TAG_MAX = 1;
- private static final int MIN_DEFAULT = 0;
+ private static final int MIN_DEFAULT = 0;
- private GeneralName name;
- private int minimum = MIN_DEFAULT;
- private int maximum = -1;
+ private GeneralName name;
+ private int minimum = MIN_DEFAULT;
+ private int maximum = -1;
private PrettyPrintFormat pp = new PrettyPrintFormat(":");
/**
* The default constructor for the class.
- *
+ *
* @param name the GeneralName
* @param min the minimum BaseDistance
* @param max the maximum BaseDistance
@@ -64,7 +66,7 @@ public class GeneralSubtree {
/**
* Create the object from its DER encoded form.
- *
+ *
* @param val the DER encoded from of the same.
*/
public GeneralSubtree(DerValue val) throws IOException {
@@ -81,13 +83,13 @@ public class GeneralSubtree {
if (opt.isContextSpecific(TAG_MIN) && !opt.isConstructed()) {
opt.resetTag(DerValue.tag_Integer);
- minimum = (opt.getInteger()).toInt();
+ minimum = (opt.getInteger()).toInt();
} else if (opt.isContextSpecific(TAG_MAX) && !opt.isConstructed()) {
opt.resetTag(DerValue.tag_Integer);
- maximum = (opt.getInteger()).toInt();
- } else
- throw new IOException("Invalid encoding of GeneralSubtree.");
+ maximum = (opt.getInteger()).toInt();
+ } else
+ throw new IOException("Invalid encoding of GeneralSubtree.");
}
}
@@ -96,31 +98,31 @@ public class GeneralSubtree {
*/
public String toString() {
String s = "\n GeneralSubtree: [\n" +
- " GeneralName: " + ((name == null) ? "" : name.toString()) +
- "\n Minimum: " + minimum;
- if (maximum == -1) {
- s += "\t Maximum: undefined";
- } else
- s += "\t Maximum: " + maximum;
- s += " ]\n";
+ " GeneralName: " + ((name == null) ? "" : name.toString()) +
+ "\n Minimum: " + minimum;
+ if (maximum == -1) {
+ s += "\t Maximum: undefined";
+ } else
+ s += "\t Maximum: " + maximum;
+ s += " ]\n";
return (s);
}
public String toPrint(int indent) {
- String s = "\n"+pp.indent(indent) + "GeneralSubtree: [\n" + pp.indent(indent+2) +
- "GeneralName: " + ((name == null) ? "" : name.toString()) +
- "\n"+pp.indent(indent+2) + "Minimum: " + minimum;
- if (maximum == -1) {
- s += "\n" + pp.indent(indent+2) + "Maximum: undefined";
- } else
- s += "\n" + pp.indent(indent+2) + "Maximum: " + maximum;
- s += "]\n";
+ String s = "\n" + pp.indent(indent) + "GeneralSubtree: [\n" + pp.indent(indent + 2) +
+ "GeneralName: " + ((name == null) ? "" : name.toString()) +
+ "\n" + pp.indent(indent + 2) + "Minimum: " + minimum;
+ if (maximum == -1) {
+ s += "\n" + pp.indent(indent + 2) + "Maximum: undefined";
+ } else
+ s += "\n" + pp.indent(indent + 2) + "Maximum: " + maximum;
+ s += "]\n";
return (s);
}
/**
* Encode the GeneralSubtree.
- *
+ *
* @param out the DerOutputStream to encode this object to.
*/
public void encode(DerOutputStream out) throws IOException {
@@ -128,8 +130,7 @@ public class GeneralSubtree {
name.encode(seq);
- if (minimum != MIN_DEFAULT)
- {
+ if (minimum != MIN_DEFAULT) {
DerOutputStream tmp = new DerOutputStream();
tmp.putInteger(new BigInt(minimum));
seq.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
@@ -141,7 +142,7 @@ public class GeneralSubtree {
seq.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
false, TAG_MAX), tmp);
}
- out.write(DerValue.tag_Sequence,seq);
+ out.write(DerValue.tag_Sequence, seq);
}
public GeneralName getGeneralName() {
diff --git a/pki/base/util/src/netscape/security/x509/GeneralSubtrees.java b/pki/base/util/src/netscape/security/x509/GeneralSubtrees.java
index 840fdf9e..37097ca7 100644
--- a/pki/base/util/src/netscape/security/x509/GeneralSubtrees.java
+++ b/pki/base/util/src/netscape/security/x509/GeneralSubtrees.java
@@ -27,19 +27,19 @@ import netscape.security.util.PrettyPrintFormat;
/**
* Represent the GeneralSubtrees ASN.1 object.
- *
+ *
* @version 1.4
- *
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
*/
public class GeneralSubtrees {
- private Vector<GeneralSubtree> trees;
+ private Vector<GeneralSubtree> trees;
private PrettyPrintFormat pp = new PrettyPrintFormat(":");
/**
* The default constructor for the class.
- *
+ *
* @param trees the sequence of GeneralSubtree.
*/
public GeneralSubtrees(Vector<GeneralSubtree> trees) {
@@ -48,7 +48,7 @@ public class GeneralSubtrees {
/**
* Create the object from the passed DER encoded form.
- *
+ *
* @param val the DER encoded form of the same.
*/
public GeneralSubtrees(DerValue val) throws IOException {
@@ -76,28 +76,28 @@ public class GeneralSubtrees {
public String toPrint(int indent) {
String s = "";
- GeneralSubtree element;
+ GeneralSubtree element;
- for (Enumeration<GeneralSubtree> e = trees.elements() ; e.hasMoreElements() ;) {
- element = (GeneralSubtree) e.nextElement();
- s = s + pp.indent(indent+4)+ element.toPrint(indent) +"\n";
- }
+ for (Enumeration<GeneralSubtree> e = trees.elements(); e.hasMoreElements();) {
+ element = (GeneralSubtree) e.nextElement();
+ s = s + pp.indent(indent + 4) + element.toPrint(indent) + "\n";
+ }
return (s);
}
/**
* Encode the GeneralSubtrees.
- *
+ *
* @param out the DerOutputStrean to encode this object to.
*/
public void encode(DerOutputStream out) throws IOException {
DerOutputStream seq = new DerOutputStream();
for (int i = 0; i < trees.size(); i++) {
- ((GeneralSubtree)trees.elementAt(i)).encode(seq);
+ ((GeneralSubtree) trees.elementAt(i)).encode(seq);
}
- out.write(DerValue.tag_Sequence,seq);
+ out.write(DerValue.tag_Sequence, seq);
}
public Vector<GeneralSubtree> getSubtrees() {
diff --git a/pki/base/util/src/netscape/security/x509/GenericValueConverter.java b/pki/base/util/src/netscape/security/x509/GenericValueConverter.java
index 5c906d09..3852a278 100644
--- a/pki/base/util/src/netscape/security/x509/GenericValueConverter.java
+++ b/pki/base/util/src/netscape/security/x509/GenericValueConverter.java
@@ -24,145 +24,133 @@ import netscape.security.util.DerValue;
import sun.io.CharToByteConverter;
/**
- * A GenericValueConverter converts a string that is not associated with
- * a particular attribute to a DER encoded ASN.1 character string type.
- * Currently supports PrintableString, IA5String, BMPString T.61String and
- * Universal String.
+ * A GenericValueConverter converts a string that is not associated with a
+ * particular attribute to a DER encoded ASN.1 character string type. Currently
+ * supports PrintableString, IA5String, BMPString T.61String and Universal
+ * String.
+ *
+ * <p>
+ * The conversion is done as follows. A CharToByteConverter is obtained for the
+ * all the character sets from the global default ASN1CharStrConvMap. The
+ * CharToByteConverters are then used to convert the string to the smallest
+ * character set first -- printableString. If the string contains characters
+ * outside of that character set, it is converted to the next character set --
+ * IA5String character set. If that is not enough it is converted to a
+ * BMPString, then Universal String which contains all characters.
*
- * <p>The conversion is done as follows.
- * A CharToByteConverter is obtained for the all the character sets
- * from the global default ASN1CharStrConvMap.
- * The CharToByteConverters are then used to convert the string to the
- * smallest character set first -- printableString.
- * If the string contains characters outside of that character set,
- * it is converted to the next character set -- IA5String character set.
- * If that is not enough it is converted to a BMPString, then
- * Universal String which contains all characters.
- *
* @author Lily Hsiao, Slava Galperin at Netscape Communications, Inc.
*
*/
-public class GenericValueConverter implements AVAValueConverter
-{
- public GenericValueConverter()
- {
+public class GenericValueConverter implements AVAValueConverter {
+ public GenericValueConverter() {
}
/**
- * Converts a string to a DER encoded ASN.1 primtable string, defined here
- * as a PrintableString, IA5String, T.61String, BMPString or
+ * Converts a string to a DER encoded ASN.1 primtable string, defined here
+ * as a PrintableString, IA5String, T.61String, BMPString or
* UniversalString. The string is not expected to be encoded in any form.
*
- * <p>If a CharToByteConverter is not available for a character set that
- * is needed to convert the string, the string cannot be converted and
- * an IOException is thrown. For example, if the string contains characters
- * outside the PrintableString character and only a PrintableString
+ * <p>
+ * If a CharToByteConverter is not available for a character set that is
+ * needed to convert the string, the string cannot be converted and an
+ * IOException is thrown. For example, if the string contains characters
+ * outside the PrintableString character and only a PrintableString
* CharToByteConverter is available then an IOException is thrown.
*
- * @param s A string representing a generic attribute string value.
- *
- * @return The DER value of the attribute.
+ * @param s A string representing a generic attribute string value.
+ *
+ * @return The DER value of the attribute.
*
- * @exception IOException if the string cannot be converted, such as
- * when a CharToByteConverter needed is
- * unavailable.
+ * @exception IOException if the string cannot be converted, such as when a
+ * CharToByteConverter needed is unavailable.
*/
public DerValue getValue(String s)
- throws IOException
- {
- return getValue(s, null);
+ throws IOException {
+ return getValue(s, null);
}
public DerValue getValue(String s, byte[] tags)
- throws IOException
- {
- // try to convert to printable, then t61 the universal -
- // i.e. from minimal coverage to the broadest.
- int ret = -1;
- CharToByteConverter cbc;
- DerValue value;
- byte[] bbuf, derBuf;
- int i;
+ throws IOException {
+ // try to convert to printable, then t61 the universal -
+ // i.e. from minimal coverage to the broadest.
+ int ret = -1;
+ CharToByteConverter cbc;
+ DerValue value;
+ byte[] bbuf, derBuf;
+ int i;
- if (tags == null || tags.length == 0)
- tags = DefEncodingTags;
+ if (tags == null || tags.length == 0)
+ tags = DefEncodingTags;
- bbuf = new byte[4*s.length()];
- for (i = 0; i < tags.length; i++)
- {
- try {
- cbc = ASN1CharStrConvMap.getDefault().getCBC(tags[i]);
- if (cbc == null)
- continue;
- ret = cbc.convert(s.toCharArray(), 0, s.length(),
- bbuf, 0, bbuf.length);
- break;
- }
- catch (java.io.CharConversionException e) {
- continue;
- }
- catch (InstantiationException e) {
- throw new IOException("Cannot instantiate CharToByteConverter");
- }
- catch (IllegalAccessException e) {
- throw new IOException(
- "Illegal Access loading CharToByteConverter");
- }
- }
- if (ret == -1) {
- throw new IllegalArgumentException(
- "Cannot convert the string value to a ASN.1 type");
- }
+ bbuf = new byte[4 * s.length()];
+ for (i = 0; i < tags.length; i++) {
+ try {
+ cbc = ASN1CharStrConvMap.getDefault().getCBC(tags[i]);
+ if (cbc == null)
+ continue;
+ ret = cbc.convert(s.toCharArray(), 0, s.length(),
+ bbuf, 0, bbuf.length);
+ break;
+ } catch (java.io.CharConversionException e) {
+ continue;
+ } catch (InstantiationException e) {
+ throw new IOException("Cannot instantiate CharToByteConverter");
+ } catch (IllegalAccessException e) {
+ throw new IOException(
+ "Illegal Access loading CharToByteConverter");
+ }
+ }
+ if (ret == -1) {
+ throw new IllegalArgumentException(
+ "Cannot convert the string value to a ASN.1 type");
+ }
- derBuf = new byte[ret];
- System.arraycopy(bbuf, 0, derBuf, 0, ret);
- return new DerValue(tags[i], derBuf);
+ derBuf = new byte[ret];
+ System.arraycopy(bbuf, 0, derBuf, 0, ret);
+ return new DerValue(tags[i], derBuf);
}
- /**
+ /**
* Creates a DerValue from the byte array of BER encoded value.
*
* NOTE: currently only supports DER encoding (a form of BER) on input .
- *
- * @param berStream Byte array of a BER encoded value.
- *
- * @return DerValue object.
*
- * @exception IOException If the BER value cannot be converted to a
- * valid Directory String DER value.
+ * @param berStream Byte array of a BER encoded value.
+ *
+ * @return DerValue object.
+ *
+ * @exception IOException If the BER value cannot be converted to a valid
+ * Directory String DER value.
*/
public DerValue getValue(byte[] berByteStream)
- throws IOException
- {
- // accepts any tag.
- DerValue value = new DerValue(berByteStream);
- return value;
+ throws IOException {
+ // accepts any tag.
+ DerValue value = new DerValue(berByteStream);
+ return value;
}
/**
- * Converts a DerValue of ASN1 Character string type to a java string
- * (the string is not encoded in any form).
+ * Converts a DerValue of ASN1 Character string type to a java string (the
+ * string is not encoded in any form).
*
- * @param avaValue A DerValue
- * @return A string representing the attribute value.
- * @exception IOException if a ByteToCharConverter needed for the
- * conversion is not available or if BER value
- * is not one of the ASN1 character string types
- * here.
+ * @param avaValue A DerValue
+ * @return A string representing the attribute value.
+ * @exception IOException if a ByteToCharConverter needed for the conversion
+ * is not available or if BER value is not one of the ASN1
+ * character string types here.
*/
- public String getAsString(DerValue avaValue)
- throws IOException
- {
- return avaValue.getASN1CharString();
+ public String getAsString(DerValue avaValue)
+ throws IOException {
+ return avaValue.getASN1CharString();
}
- private static byte DefEncodingTags[] = {
- DerValue.tag_PrintableString,
- DerValue.tag_IA5String,
- DerValue.tag_BMPString,
- DerValue.tag_UTF8String,
- DerValue.tag_T61String,
- DerValue.tag_UniversalString
- };
+ private static byte DefEncodingTags[] = {
+ DerValue.tag_PrintableString,
+ DerValue.tag_IA5String,
+ DerValue.tag_BMPString,
+ DerValue.tag_UTF8String,
+ DerValue.tag_T61String,
+ DerValue.tag_UniversalString
+ };
}
diff --git a/pki/base/util/src/netscape/security/x509/HoldInstructionExtension.java b/pki/base/util/src/netscape/security/x509/HoldInstructionExtension.java
index 7f996250..f355b93c 100644
--- a/pki/base/util/src/netscape/security/x509/HoldInstructionExtension.java
+++ b/pki/base/util/src/netscape/security/x509/HoldInstructionExtension.java
@@ -30,22 +30,20 @@ import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
import netscape.security.util.ObjectIdentifier;
-
/**
* Represent the CRL Hold Instruction Code Extension.
- *
- * <p>The hold instruction code is a non-critical CRL entry
- * extension that provides a registered instruction identifier
- * which indicates the action to be taken after encountering
- * a certificate that has been placed on hold.
- *
+ *
+ * <p>
+ * The hold instruction code is a non-critical CRL entry extension that provides
+ * a registered instruction identifier which indicates the action to be taken
+ * after encountering a certificate that has been placed on hold.
+ *
* @see Extension
* @see CertAttrSet
*/
-
public class HoldInstructionExtension extends Extension
-implements CertAttrSet {
+ implements CertAttrSet {
/**
*
@@ -62,35 +60,35 @@ implements CertAttrSet {
public static final String OID = "2.5.29.23";
public static final String NONE_HOLD_INSTR_OID_STR =
- "1.2.840.10040.2.1";
+ "1.2.840.10040.2.1";
public static final ObjectIdentifier NONE_HOLD_INSTR_OID =
- new ObjectIdentifier(NONE_HOLD_INSTR_OID_STR);
+ new ObjectIdentifier(NONE_HOLD_INSTR_OID_STR);
public static final String CALL_ISSUER_HOLD_INSTR_OID_STR =
- "1.2.840.10040.2.2";
+ "1.2.840.10040.2.2";
public static final ObjectIdentifier CALL_ISSUER_HOLD_INSTR_OID =
- new ObjectIdentifier(CALL_ISSUER_HOLD_INSTR_OID_STR);
+ new ObjectIdentifier(CALL_ISSUER_HOLD_INSTR_OID_STR);
public static final String REJECT_HOLD_INSTR_OID_STR =
- "1.2.840.10040.2.3";
+ "1.2.840.10040.2.3";
public static final ObjectIdentifier REJECT_HOLD_INSTR_OID =
- new ObjectIdentifier(REJECT_HOLD_INSTR_OID_STR);
+ new ObjectIdentifier(REJECT_HOLD_INSTR_OID_STR);
- private ObjectIdentifier holdInstructionCodeOIDs[] = {NONE_HOLD_INSTR_OID,
+ private ObjectIdentifier holdInstructionCodeOIDs[] = { NONE_HOLD_INSTR_OID,
CALL_ISSUER_HOLD_INSTR_OID,
- REJECT_HOLD_INSTR_OID};
+ REJECT_HOLD_INSTR_OID };
private ObjectIdentifier holdInstructionCodeOID = null;
- private String holdInstructionDescription[] = {"None",
+ private String holdInstructionDescription[] = { "None",
"Call Issuer",
- "Reject"};
-
+ "Reject" };
static {
try {
OIDMap.addAttribute(HoldInstructionExtension.class.getName(),
OID, HoldInstructionExtension.class.getSimpleName());
- } catch (CertificateException e) {}
+ } catch (CertificateException e) {
+ }
}
private int getHoldInstructionCodeFromOID(ObjectIdentifier oid) {
@@ -106,7 +104,7 @@ implements CertAttrSet {
if (oid != null) {
int i = getHoldInstructionCodeFromOID(oid);
if (i > 0 && i < 4)
- description = holdInstructionDescription[i-1];
+ description = holdInstructionDescription[i - 1];
}
return (description);
}
@@ -121,31 +119,29 @@ implements CertAttrSet {
}
/**
- * Create a HoldInstructionExtension with the date.
- * The criticality is set to false.
- *
+ * Create a HoldInstructionExtension with the date. The criticality is set
+ * to false.
+ *
* @param code the value to be set for the extension.
*/
public HoldInstructionExtension(int code)
- throws IOException
- {
+ throws IOException {
if (code < 1 || code > 3)
throw new IOException("Invalid hold instruction code");
- holdInstructionCodeOID = holdInstructionCodeOIDs[code-1];
+ holdInstructionCodeOID = holdInstructionCodeOIDs[code - 1];
this.extensionId = PKIXExtensions.HoldInstructionCode_Id;
this.critical = false;
encodeThis();
}
/**
- * Create a HoldInstructionExtension with the date.
- * The criticality is set to false.
- *
+ * Create a HoldInstructionExtension with the date. The criticality is set
+ * to false.
+ *
* @param oidStr the value to be set for the extension.
*/
public HoldInstructionExtension(String oidStr)
- throws IOException
- {
+ throws IOException {
ObjectIdentifier oid = new ObjectIdentifier(oidStr);
if (oid == null || getHoldInstructionCodeFromOID(oid) == 0)
throw new IOException("Invalid hold instruction code");
@@ -156,14 +152,13 @@ implements CertAttrSet {
}
/**
- * Create a HoldInstructionExtension with the date.
- * The criticality is set to false.
- *
+ * Create a HoldInstructionExtension with the date. The criticality is set
+ * to false.
+ *
* @param oid the value to be set for the extension.
*/
public HoldInstructionExtension(ObjectIdentifier oid)
- throws IOException
- {
+ throws IOException {
if (getHoldInstructionCodeFromOID(oid) == 0)
throw new IOException("Invalid hold instruction code");
holdInstructionCodeOID = oid;
@@ -173,33 +168,31 @@ implements CertAttrSet {
}
/**
- * Create a HoldInstructionExtension with the date.
- * The criticality is set to false.
- *
+ * Create a HoldInstructionExtension with the date. The criticality is set
+ * to false.
+ *
* @param critical true if the extension is to be treated as critical.
* @param code the value to be set for the extension.
*/
public HoldInstructionExtension(Boolean critical, int code)
- throws IOException
- {
+ throws IOException {
if (code < 1 || code > 3)
throw new IOException("Invalid hold instruction code");
- holdInstructionCodeOID = holdInstructionCodeOIDs[code-1];
+ holdInstructionCodeOID = holdInstructionCodeOIDs[code - 1];
this.extensionId = PKIXExtensions.HoldInstructionCode_Id;
this.critical = critical.booleanValue();
encodeThis();
}
/**
- * Create a HoldInstructionExtension with the date.
- * The criticality is set to false.
- *
+ * Create a HoldInstructionExtension with the date. The criticality is set
+ * to false.
+ *
* @param critical true if the extension is to be treated as critical.
* @param oidStr the value to be set for the extension.
*/
public HoldInstructionExtension(Boolean critical, String oidStr)
- throws IOException
- {
+ throws IOException {
ObjectIdentifier oid = new ObjectIdentifier(oidStr);
if (oid == null || getHoldInstructionCodeFromOID(oid) == 0)
throw new IOException("Invalid hold instruction code");
@@ -210,15 +203,14 @@ implements CertAttrSet {
}
/**
- * Create a HoldInstructionExtension with the date.
- * The criticality is set to false.
- *
+ * Create a HoldInstructionExtension with the date. The criticality is set
+ * to false.
+ *
* @param critical true if the extension is to be treated as critical.
* @param oid the value to be set for the extension.
*/
public HoldInstructionExtension(Boolean critical, ObjectIdentifier oid)
- throws IOException
- {
+ throws IOException {
if (getHoldInstructionCodeFromOID(oid) == 0)
throw new IOException("Invalid hold instruction code");
holdInstructionCodeOID = oid;
@@ -229,14 +221,13 @@ implements CertAttrSet {
/**
* Create the extension from the passed DER encoded value of the same.
- *
+ *
* @param critical true if the extension is to be treated as critical.
* @param value Array of DER encoded bytes of the actual value.
* @exception IOException on error.
*/
public HoldInstructionExtension(Boolean critical, Object value)
- throws IOException
- {
+ throws IOException {
this.extensionId = PKIXExtensions.HoldInstructionCode_Id;
this.critical = critical.booleanValue();
@@ -260,13 +251,11 @@ implements CertAttrSet {
/**
* Get the hold instruction code.
*/
- public ObjectIdentifier getHoldInstructionCode()
- {
+ public ObjectIdentifier getHoldInstructionCode() {
return holdInstructionCodeOID;
}
- public String getHoldInstructionCodeDescription()
- {
+ public String getHoldInstructionCodeDescription() {
return getHoldInstructionDescription(holdInstructionCodeOID);
}
@@ -278,9 +267,9 @@ implements CertAttrSet {
if (!(obj instanceof ObjectIdentifier)) {
throw new IOException("Attribute must be of type String.");
}
- holdInstructionCodeOID = (ObjectIdentifier)obj;
+ holdInstructionCodeOID = (ObjectIdentifier) obj;
} else {
- throw new IOException("Attribute name not recognized by"+
+ throw new IOException("Attribute name not recognized by" +
" CertAttrSet:HoldInstructionCode.");
}
}
@@ -292,7 +281,7 @@ implements CertAttrSet {
if (name.equalsIgnoreCase(HOLD_INSTRUCTION)) {
return holdInstructionCodeOID;
} else {
- throw new IOException("Attribute name not recognized by"+
+ throw new IOException("Attribute name not recognized by" +
" CertAttrSet:HoldInstructionCode.");
}
}
@@ -304,7 +293,7 @@ implements CertAttrSet {
if (name.equalsIgnoreCase(HOLD_INSTRUCTION)) {
holdInstructionCodeOID = null;
} else {
- throw new IOException("Attribute name not recognized by"+
+ throw new IOException("Attribute name not recognized by" +
" CertAttrSet:HoldInstructionCode.");
}
}
@@ -313,14 +302,14 @@ implements CertAttrSet {
* Returns a printable representation of the HoldInstructionExtension.
*/
public String toString() {
- String s = super.toString() + "Hold Instruction Code: "+
- getHoldInstructionDescription(holdInstructionCodeOID)+"\n";
+ String s = super.toString() + "Hold Instruction Code: " +
+ getHoldInstructionDescription(holdInstructionCodeOID) + "\n";
return (s);
}
/**
* Decode the extension from the InputStream.
- *
+ *
* @param in the InputStream to unmarshal the contents from.
* @exception IOException on decoding or validity errors.
*/
@@ -330,31 +319,30 @@ implements CertAttrSet {
/**
* Write the extension to the DerOutputStream.
- *
+ *
* @param out the DerOutputStream to write the extension to.
* @exception IOException on encoding errors.
*/
public void encode(OutputStream out) throws IOException {
- DerOutputStream tmp = new DerOutputStream();
-
- if (this.extensionValue == null) {
- this.extensionId = PKIXExtensions.HoldInstructionCode_Id;
- this.critical = true;
- encodeThis();
- }
- super.encode(tmp);
- out.write(tmp.toByteArray());
+ DerOutputStream tmp = new DerOutputStream();
+
+ if (this.extensionValue == null) {
+ this.extensionId = PKIXExtensions.HoldInstructionCode_Id;
+ this.critical = true;
+ encodeThis();
+ }
+ super.encode(tmp);
+ out.write(tmp.toByteArray());
}
/**
* Return an enumeration of names of attributes existing within this
* attribute.
*/
- public Enumeration<String> getAttributeNames () {
+ public Enumeration<String> getAttributeNames() {
Vector<String> elements = new Vector<String>();
elements.addElement(HOLD_INSTRUCTION);
return (elements.elements());
}
}
-
diff --git a/pki/base/util/src/netscape/security/x509/IA5StringConverter.java b/pki/base/util/src/netscape/security/x509/IA5StringConverter.java
index f3fa50da..da430154 100644
--- a/pki/base/util/src/netscape/security/x509/IA5StringConverter.java
+++ b/pki/base/util/src/netscape/security/x509/IA5StringConverter.java
@@ -24,109 +24,101 @@ import netscape.security.util.DerValue;
import sun.io.CharToByteConverter;
/**
- * A AVAValueConverter that converts a IA5String attribute to a DerValue
- * and vice versa. An example an attribute that is a IA5String string is "E".
+ * A AVAValueConverter that converts a IA5String attribute to a DerValue and
+ * vice versa. An example an attribute that is a IA5String string is "E".
+ *
* @see AVAValueConverter
- *
+ *
* @author Lily Hsiao, Slava Galperin at Netscape Communications, Inc.
*/
-public class IA5StringConverter implements AVAValueConverter
-{
- // public constructors
+public class IA5StringConverter implements AVAValueConverter {
+ // public constructors
- /*
+ /*
* Contructs a IA5String Converter.
*/
- public IA5StringConverter()
- {
- }
+ public IA5StringConverter() {
+ }
/*
* Converts a string with ASN.1 IA5String characters to a DerValue.
*
- * @param valueString a string with IA5String characters.
+ * @param valueString a string with IA5String characters.
*
- * @return a DerValue.
+ * @return a DerValue.
*
- * @exception IOException if a IA5String CharToByteConverter is not
- * available for the conversion.
+ * @exception IOException if a IA5String CharToByteConverter is not
+ * available for the conversion.
*/
public DerValue getValue(String valueString)
- throws IOException
- {
- return getValue(valueString, null);
+ throws IOException {
+ return getValue(valueString, null);
}
public DerValue getValue(String valueString, byte[] encodingOrder)
- throws IOException
- {
- ASN1CharStrConvMap map;
- CharToByteConverter cbc;
- byte[] bbuf = new byte[valueString.length()];
- map = ASN1CharStrConvMap.getDefault();
- try {
- cbc = map.getCBC(DerValue.tag_IA5String);
- if (cbc == null)
- throw new IOException("No CharToByteConverter for IA5String");
- cbc.convert(valueString.toCharArray(), 0, valueString.length(),
- bbuf, 0, bbuf.length);
- }
- catch (java.io.CharConversionException e) {
- throw new IllegalArgumentException(
- "Invalid IA5String AVA Value string");
- } catch (InstantiationException e) {
- throw new IOException("Cannot instantiate CharToByteConverter");
- } catch (IllegalAccessException e) {
- throw new IOException("Illegal access loading CharToByteConverter");
- }
- return new DerValue(DerValue.tag_IA5String, bbuf);
+ throws IOException {
+ ASN1CharStrConvMap map;
+ CharToByteConverter cbc;
+ byte[] bbuf = new byte[valueString.length()];
+ map = ASN1CharStrConvMap.getDefault();
+ try {
+ cbc = map.getCBC(DerValue.tag_IA5String);
+ if (cbc == null)
+ throw new IOException("No CharToByteConverter for IA5String");
+ cbc.convert(valueString.toCharArray(), 0, valueString.length(),
+ bbuf, 0, bbuf.length);
+ } catch (java.io.CharConversionException e) {
+ throw new IllegalArgumentException(
+ "Invalid IA5String AVA Value string");
+ } catch (InstantiationException e) {
+ throw new IOException("Cannot instantiate CharToByteConverter");
+ } catch (IllegalAccessException e) {
+ throw new IOException("Illegal access loading CharToByteConverter");
+ }
+ return new DerValue(DerValue.tag_IA5String, bbuf);
}
/*
- * Converts a BER encoded value of IA5String to a DER encoded value.
- * Checks if the BER encoded value is a IA5String.
- * NOTE only DER encoding is currently supported on for the BER
- * encoded value.
+ * Converts a BER encoded value of IA5String to a DER encoded value. Checks
+ * if the BER encoded value is a IA5String. NOTE only DER encoding is
+ * currently supported on for the BER encoded value.
*
- * @param berStream a byte array of the BER encoded value.
+ * @param berStream a byte array of the BER encoded value.
*
- * @return a DerValue.
+ * @return a DerValue.
*
- * @exception IOException if the BER value cannot be converted
- * to a IA5String DER value.
+ * @exception IOException if the BER value cannot be converted to a
+ * IA5String DER value.
*/
public DerValue getValue(byte[] berStream)
- throws IOException
- {
- DerValue value = new DerValue(berStream);
- if (value.tag == DerValue.tag_IA5String)
- return value;
- if (value.tag == DerValue.tag_PrintableString)
- return value;
- throw new IOException("Invalid IA5String AVA Value.");
+ throws IOException {
+ DerValue value = new DerValue(berStream);
+ if (value.tag == DerValue.tag_IA5String)
+ return value;
+ if (value.tag == DerValue.tag_PrintableString)
+ return value;
+ throw new IOException("Invalid IA5String AVA Value.");
}
/*
- * Converts a DerValue of IA5String to a java string with IA5String
- * characters.
+ * Converts a DerValue of IA5String to a java string with IA5String
+ * characters.
+ *
+ * @param avaValue a DerValue.
+ *
+ * @return a string with IA5String characters.
*
- * @param avaValue a DerValue.
- *
- * @return a string with IA5String characters.
- *
- * @exception IOException if the DerValue is not a IA5String i.e.
- * The DerValue cannot be converted to a string
- * with IA5String characters.
+ * @exception IOException if the DerValue is not a IA5String i.e. The
+ * DerValue cannot be converted to a string with IA5String characters.
*/
- public String getAsString(DerValue avaValue)
- throws IOException
- {
- if (avaValue.tag == DerValue.tag_IA5String)
- return avaValue.getIA5String();
- if (avaValue.tag == DerValue.tag_PrintableString)
- return avaValue.getPrintableString();
- throw new IOException("Invalid IA5String AVA Value.");
+ public String getAsString(DerValue avaValue)
+ throws IOException {
+ if (avaValue.tag == DerValue.tag_IA5String)
+ return avaValue.getIA5String();
+ if (avaValue.tag == DerValue.tag_PrintableString)
+ return avaValue.getPrintableString();
+ throw new IOException("Invalid IA5String AVA Value.");
}
}
diff --git a/pki/base/util/src/netscape/security/x509/IPAddressName.java b/pki/base/util/src/netscape/security/x509/IPAddressName.java
index 510a4f5a..6b4bd26b 100644
--- a/pki/base/util/src/netscape/security/x509/IPAddressName.java
+++ b/pki/base/util/src/netscape/security/x509/IPAddressName.java
@@ -24,15 +24,15 @@ import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
/**
- * This class implements the IPAddressName as required by the GeneralNames
- * ASN.1 object.
- *
+ * This class implements the IPAddressName as required by the GeneralNames ASN.1
+ * object.
+ *
* @see GeneralName
* @see GeneralNameInterface
* @see GeneralNames
- *
+ *
* @version 1.2
- *
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
*/
@@ -45,7 +45,7 @@ public class IPAddressName implements GeneralNameInterface {
/**
* Create the IPAddressName object from the passed encoded Der value.
- *
+ *
* @param derValue the encoded DER IPAddressName.
* @exception IOException on error.
*/
@@ -55,7 +55,7 @@ public class IPAddressName implements GeneralNameInterface {
/**
* Create the IPAddressName object with the specified name.
- *
+ *
* @param name the IPAddressName.
*/
public IPAddressName(byte[] address) {
@@ -68,55 +68,54 @@ public class IPAddressName implements GeneralNameInterface {
protected static final IPAddr IPv6 = new IPv6Addr();
/**
- * Create the IPAddressName object with a string representing the
- * ip address and a string representing the netmask, with encoding
- * having ip address encoding followed by the netmask encoding.
- * This form is needed for name constraints extension.
- *
- * @param s the ip address in the format: n.n.n.n or x:x:x:x:x:x:x:x (RFC 1884)
- * @param netmask the netmask address in the format: n.n.n.n or x:x:x:x:x:x:x:x (RFC 1884)
+ * Create the IPAddressName object with a string representing the ip address
+ * and a string representing the netmask, with encoding having ip address
+ * encoding followed by the netmask encoding. This form is needed for name
+ * constraints extension.
+ *
+ * @param s the ip address in the format: n.n.n.n or x:x:x:x:x:x:x:x (RFC
+ * 1884)
+ * @param netmask the netmask address in the format: n.n.n.n or
+ * x:x:x:x:x:x:x:x (RFC 1884)
*/
- public IPAddressName(String s, String netmask)
- {
- // Based on PKIX RFC2459. IPAddress has
- // 8 bytes (instead of 4 bytes) in the
- // context of NameConstraints
- IPAddr ipAddr = null;
- if (s.indexOf(':') != -1) {
- ipAddr = IPv6;
- address = new byte[IPv6_LEN*2];
- } else {
- ipAddr = IPv4;
- address = new byte[IPv4_LEN*2];
- }
- StringTokenizer st = new StringTokenizer(s,",");
- int numFilled = ipAddr.getIPAddr(st.nextToken(), address, 0);
- if (st.hasMoreTokens()) {
- ipAddr.getIPAddr(st.nextToken(), address, numFilled);
- }
- else {
- for (int i=numFilled; i < address.length; i++)
- address[i] = (byte)0xff;
- }
+ public IPAddressName(String s, String netmask) {
+ // Based on PKIX RFC2459. IPAddress has
+ // 8 bytes (instead of 4 bytes) in the
+ // context of NameConstraints
+ IPAddr ipAddr = null;
+ if (s.indexOf(':') != -1) {
+ ipAddr = IPv6;
+ address = new byte[IPv6_LEN * 2];
+ } else {
+ ipAddr = IPv4;
+ address = new byte[IPv4_LEN * 2];
+ }
+ StringTokenizer st = new StringTokenizer(s, ",");
+ int numFilled = ipAddr.getIPAddr(st.nextToken(), address, 0);
+ if (st.hasMoreTokens()) {
+ ipAddr.getIPAddr(st.nextToken(), address, numFilled);
+ } else {
+ for (int i = numFilled; i < address.length; i++)
+ address[i] = (byte) 0xff;
+ }
}
-
/**
- * Create the IPAddressName object with a string representing the
- * ip address.
- *
+ * Create the IPAddressName object with a string representing the ip
+ * address.
+ *
* @param s the ip address in the format: n.n.n.n or x:x:x:x:x:x:x:x
*/
public IPAddressName(String s) {
- IPAddr ipAddr = null;
- if (s.indexOf(':') != -1) {
- ipAddr = IPv6;
- address = new byte[IPv6_LEN];
- } else {
- ipAddr = IPv4;
- address = new byte[IPv4_LEN];
- }
- ipAddr.getIPAddr(s, address, 0);
+ IPAddr ipAddr = null;
+ if (s.indexOf(':') != -1) {
+ ipAddr = IPv6;
+ address = new byte[IPv6_LEN];
+ } else {
+ ipAddr = IPv4;
+ address = new byte[IPv4_LEN];
+ }
+ ipAddr.getIPAddr(s, address, 0);
}
/**
@@ -128,7 +127,7 @@ public class IPAddressName implements GeneralNameInterface {
/**
* Encode the IPAddress name into the DerOutputStream.
- *
+ *
* @param out the DER stream to encode the IPAddressName to.
* @exception IOException on encoding errors.
*/
@@ -142,137 +141,139 @@ public class IPAddressName implements GeneralNameInterface {
public String toString() {
if (address.length == 4) {
return ("IPAddress: " + (address[0] & 0xff) + "."
- + (address[1] & 0xff) + "."
- + (address[2] & 0xff) + "."
- + (address[3] & 0xff));
+ + (address[1] & 0xff) + "."
+ + (address[2] & 0xff) + "." + (address[3] & 0xff));
} else {
- String r= "IPAddress: " + Integer.toHexString(address[0] & 0xff);
+ String r = "IPAddress: " + Integer.toHexString(address[0] & 0xff);
String hexString = Integer.toHexString(address[1] & 0xff);
- if (hexString.length() ==1) {
- r = r+ "0" + hexString;
+ if (hexString.length() == 1) {
+ r = r + "0" + hexString;
} else {
r += hexString;
}
- for (int i=2; i < address.length; ) {
- r+= ":" + Integer.toHexString(address[i] & 0xff);
- hexString = Integer.toHexString(address[i+1] & 0xff);
- if (hexString.length() ==1) {
- r = r +"0" + hexString;
+ for (int i = 2; i < address.length;) {
+ r += ":" + Integer.toHexString(address[i] & 0xff);
+ hexString = Integer.toHexString(address[i + 1] & 0xff);
+ if (hexString.length() == 1) {
+ r = r + "0" + hexString;
} else {
r += hexString;
}
- i+=2;
+ i += 2;
}
return r;
}
}
}
-interface IPAddr
-{
- public int getIPAddr(String s, byte[] address, int start);
- public int getLength();
+interface IPAddr {
+ public int getIPAddr(String s, byte[] address, int start);
+
+ public int getLength();
}
-class IPv4Addr implements IPAddr
-{
- protected static final int IPv4_LEN = 4;
+class IPv4Addr implements IPAddr {
+ protected static final int IPv4_LEN = 4;
- /**
- * Gets an IP v4 address in the form n.n.n.n.
- */
- public int getIPAddr(String s, byte[] address, int start) {
- StringTokenizer st = new StringTokenizer(s,".");
- int nt = st.countTokens();
- if (nt != IPv4_LEN)
- throw new InvalidIPAddressException(s);
- try {
- int end = start+nt;
- for (int i=start; i<end; i++) {
- Integer j = new Integer(st.nextToken());
- address[i] = (byte)j.intValue();
- }
- } catch (NumberFormatException e) {
- throw new InvalidIPAddressException(s);
- }
- return nt;
- }
+ /**
+ * Gets an IP v4 address in the form n.n.n.n.
+ */
+ public int getIPAddr(String s, byte[] address, int start) {
+ StringTokenizer st = new StringTokenizer(s, ".");
+ int nt = st.countTokens();
+ if (nt != IPv4_LEN)
+ throw new InvalidIPAddressException(s);
+ try {
+ int end = start + nt;
+ for (int i = start; i < end; i++) {
+ Integer j = new Integer(st.nextToken());
+ address[i] = (byte) j.intValue();
+ }
+ } catch (NumberFormatException e) {
+ throw new InvalidIPAddressException(s);
+ }
+ return nt;
+ }
- public int getLength() { return IPv4_LEN; }
+ public int getLength() {
+ return IPv4_LEN;
+ }
}
-class IPv6Addr implements IPAddr
-{
- /**
- * Gets an IP address in the forms as defined in RFC1884:<br>
- * <ul>
- * <li>x:x:x:x:x:x:x:x
- * <li>...::xxx (using :: shorthand)
- * <li>...:n.n.n.n (with n.n.n.n at the end)
- * </ul>
- */
- public int getIPAddr(String s, byte[] address, int start) {
- int lastcolon = -2;
- int end = start+16;
- int idx = start;
- for (int i = start; i < address.length; i++)
- address[i] = 0;
- if (s.indexOf('.') != -1) { // has n.n.n.n at the end
- lastcolon = s.lastIndexOf(':');
- if (lastcolon == -1)
- throw new InvalidIPAddressException(s);
- end -= 4;
- IPAddressName.IPv4.getIPAddr(
- s.substring(lastcolon+1), address, end);
- }
- try {
- String s1 = s;
- if (lastcolon != -2)
- s1 = s.substring(0, lastcolon+1);
- int lastDoubleColon = s1.indexOf("::");
- String l = s1, r = null;
- StringTokenizer lt = null, rt = null;
- if (lastDoubleColon != -1) {
- l = s1.substring(0, lastDoubleColon);
- r = s1.substring(lastDoubleColon+2);
- if (l.length() == 0) l = null;
- if (r.length() == 0) r = null;
- }
- int at = 0;
- if (l != null) {
- lt = new StringTokenizer(l,":", false);
- at += lt.countTokens();
- }
- if (r != null) {
- rt = new StringTokenizer(r,":", false);
- at += rt.countTokens();
- }
- if (at > 8 ||
- (lastcolon!=-2 && (at>6 || (lastDoubleColon==-1 && at!=6))))
- throw new InvalidIPAddressException(s);
- if (l != null) {
- while(lt.hasMoreTokens()) {
- String tok = lt.nextToken();
- int j = Integer.parseInt(tok, 16);
- address[idx++] = (byte)((j>>8) & 0xFF);
- address[idx++] = (byte)(j & 0xFF);
- }
- }
- if (r != null) {
- idx = end-(rt.countTokens()*2);
- while(rt.hasMoreTokens()) {
- String tok = rt.nextToken();
- int j = Integer.parseInt(tok, 16);
- address[idx++] = (byte)((j>>8) & 0xFF);
- address[idx++] = (byte)(j & 0xFF);
- }
- }
- } catch (NumberFormatException e) {
- throw new InvalidIPAddressException(s);
- }
- return 16;
- }
+class IPv6Addr implements IPAddr {
+ /**
+ * Gets an IP address in the forms as defined in RFC1884:<br>
+ * <ul>
+ * <li>x:x:x:x:x:x:x:x
+ * <li>...::xxx (using :: shorthand)
+ * <li>...:n.n.n.n (with n.n.n.n at the end)
+ * </ul>
+ */
+ public int getIPAddr(String s, byte[] address, int start) {
+ int lastcolon = -2;
+ int end = start + 16;
+ int idx = start;
+ for (int i = start; i < address.length; i++)
+ address[i] = 0;
+ if (s.indexOf('.') != -1) { // has n.n.n.n at the end
+ lastcolon = s.lastIndexOf(':');
+ if (lastcolon == -1)
+ throw new InvalidIPAddressException(s);
+ end -= 4;
+ IPAddressName.IPv4.getIPAddr(
+ s.substring(lastcolon + 1), address, end);
+ }
+ try {
+ String s1 = s;
+ if (lastcolon != -2)
+ s1 = s.substring(0, lastcolon + 1);
+ int lastDoubleColon = s1.indexOf("::");
+ String l = s1, r = null;
+ StringTokenizer lt = null, rt = null;
+ if (lastDoubleColon != -1) {
+ l = s1.substring(0, lastDoubleColon);
+ r = s1.substring(lastDoubleColon + 2);
+ if (l.length() == 0)
+ l = null;
+ if (r.length() == 0)
+ r = null;
+ }
+ int at = 0;
+ if (l != null) {
+ lt = new StringTokenizer(l, ":", false);
+ at += lt.countTokens();
+ }
+ if (r != null) {
+ rt = new StringTokenizer(r, ":", false);
+ at += rt.countTokens();
+ }
+ if (at > 8 ||
+ (lastcolon != -2 && (at > 6 || (lastDoubleColon == -1 && at != 6))))
+ throw new InvalidIPAddressException(s);
+ if (l != null) {
+ while (lt.hasMoreTokens()) {
+ String tok = lt.nextToken();
+ int j = Integer.parseInt(tok, 16);
+ address[idx++] = (byte) ((j >> 8) & 0xFF);
+ address[idx++] = (byte) (j & 0xFF);
+ }
+ }
+ if (r != null) {
+ idx = end - (rt.countTokens() * 2);
+ while (rt.hasMoreTokens()) {
+ String tok = rt.nextToken();
+ int j = Integer.parseInt(tok, 16);
+ address[idx++] = (byte) ((j >> 8) & 0xFF);
+ address[idx++] = (byte) (j & 0xFF);
+ }
+ }
+ } catch (NumberFormatException e) {
+ throw new InvalidIPAddressException(s);
+ }
+ return 16;
+ }
- public int getLength() { return 16; }
+ public int getLength() {
+ return 16;
+ }
}
-
diff --git a/pki/base/util/src/netscape/security/x509/InvalidIPAddressException.java b/pki/base/util/src/netscape/security/x509/InvalidIPAddressException.java
index d58ff896..f544df20 100644
--- a/pki/base/util/src/netscape/security/x509/InvalidIPAddressException.java
+++ b/pki/base/util/src/netscape/security/x509/InvalidIPAddressException.java
@@ -17,16 +17,17 @@
// --- END COPYRIGHT BLOCK ---
package netscape.security.x509;
-public class InvalidIPAddressException extends RuntimeException
-{
- /**
+public class InvalidIPAddressException extends RuntimeException {
+ /**
*
*/
private static final long serialVersionUID = -1601934234587845028L;
+
public InvalidIPAddressException() {
- super();
- }
- public InvalidIPAddressException(String ip) {
- super("Invalid IP Address '"+ip+"'");
- }
+ super();
+ }
+
+ public InvalidIPAddressException(String ip) {
+ super("Invalid IP Address '" + ip + "'");
+ }
}
diff --git a/pki/base/util/src/netscape/security/x509/InvalidityDateExtension.java b/pki/base/util/src/netscape/security/x509/InvalidityDateExtension.java
index 30909664..ce2945a5 100755
--- a/pki/base/util/src/netscape/security/x509/InvalidityDateExtension.java
+++ b/pki/base/util/src/netscape/security/x509/InvalidityDateExtension.java
@@ -30,22 +30,21 @@ import netscape.security.util.DerInputStream;
import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
-
/**
* Represent the CRL Invalidity Date Extension.
- *
- * <p>This CRL entry extension, if present, provides the date
- * on which it is known or suspected that the private key was
- * compromised or that the certificate otherwise became invalid.
- * Invalidity date may be earlier than the revocation date.
- *
+ *
+ * <p>
+ * This CRL entry extension, if present, provides the date on which it is known
+ * or suspected that the private key was compromised or that the certificate
+ * otherwise became invalid. Invalidity date may be earlier than the revocation
+ * date.
+ *
* @see Extension
* @see CertAttrSet
*/
-
public class InvalidityDateExtension extends Extension
-implements CertAttrSet {
+ implements CertAttrSet {
/**
*
@@ -61,14 +60,14 @@ implements CertAttrSet {
*/
public static final String OID = "2.5.29.24";
-
private Date invalidityDate = null;
static {
try {
OIDMap.addAttribute(InvalidityDateExtension.class.getName(),
OID, InvalidityDateExtension.class.getSimpleName());
- } catch (CertificateException e) {}
+ } catch (CertificateException e) {
+ }
}
// Encode this extension value
@@ -81,14 +80,13 @@ implements CertAttrSet {
}
/**
- * Create a InvalidityDateExtension with the date.
- * The criticality is set to false.
- *
+ * Create a InvalidityDateExtension with the date. The criticality is set to
+ * false.
+ *
* @param dateOfInvalidity the value to be set for the extension.
*/
public InvalidityDateExtension(Date dateOfInvalidity)
- throws IOException
- {
+ throws IOException {
this.invalidityDate = dateOfInvalidity;
this.extensionId = PKIXExtensions.InvalidityDate_Id;
this.critical = false;
@@ -96,15 +94,14 @@ implements CertAttrSet {
}
/**
- * Create a InvalidityDateExtension with the date.
- * The criticality is set to false.
- *
+ * Create a InvalidityDateExtension with the date. The criticality is set to
+ * false.
+ *
* @param critical true if the extension is to be treated as critical.
* @param dateOfInvalidity the value to be set for the extension.
*/
public InvalidityDateExtension(Boolean critical, Date dateOfInvalidity)
- throws IOException
- {
+ throws IOException {
this.invalidityDate = dateOfInvalidity;
this.extensionId = PKIXExtensions.InvalidityDate_Id;
this.critical = critical.booleanValue();
@@ -113,14 +110,13 @@ implements CertAttrSet {
/**
* Create the extension from the passed DER encoded value of the same.
- *
+ *
* @param critical true if the extension is to be treated as critical.
* @param value Array of DER encoded bytes of the actual value.
* @exception IOException on error.
*/
public InvalidityDateExtension(Boolean critical, Object value)
- throws IOException
- {
+ throws IOException {
this.extensionId = PKIXExtensions.InvalidityDate_Id;
this.critical = critical.booleanValue();
@@ -142,8 +138,7 @@ implements CertAttrSet {
/**
* Get the invalidity date.
*/
- public Date getInvalidityDate()
- {
+ public Date getInvalidityDate() {
return invalidityDate;
}
@@ -155,9 +150,9 @@ implements CertAttrSet {
if (!(obj instanceof Date)) {
throw new IOException("Attribute must be of type Date.");
}
- invalidityDate = (Date)obj;
- } else {
- throw new IOException("Attribute name not recognized by"+
+ invalidityDate = (Date) obj;
+ } else {
+ throw new IOException("Attribute name not recognized by" +
" CertAttrSet:InvalidityDate.");
}
}
@@ -167,10 +162,12 @@ implements CertAttrSet {
*/
public Object get(String name) throws IOException {
if (name.equalsIgnoreCase(INVALIDITY_DATE)) {
- if (invalidityDate == null) return null;
- else return invalidityDate;
+ if (invalidityDate == null)
+ return null;
+ else
+ return invalidityDate;
} else {
- throw new IOException("Attribute name not recognized by"+
+ throw new IOException("Attribute name not recognized by" +
" CertAttrSet:InvalidityDate.");
}
}
@@ -182,7 +179,7 @@ implements CertAttrSet {
if (name.equalsIgnoreCase(INVALIDITY_DATE)) {
invalidityDate = null;
} else {
- throw new IOException("Attribute name not recognized by"+
+ throw new IOException("Attribute name not recognized by" +
" CertAttrSet:InvalidityDate.");
}
}
@@ -199,7 +196,7 @@ implements CertAttrSet {
/**
* Decode the extension from the InputStream.
- *
+ *
* @param in the InputStream to unmarshal the contents from.
* @exception IOException on decoding or validity errors.
*/
@@ -209,31 +206,30 @@ implements CertAttrSet {
/**
* Write the extension to the DerOutputStream.
- *
+ *
* @param out the DerOutputStream to write the extension to.
* @exception IOException on encoding errors.
*/
public void encode(OutputStream out) throws IOException {
- DerOutputStream tmp = new DerOutputStream();
-
- if (this.extensionValue == null) {
- this.extensionId = PKIXExtensions.InvalidityDate_Id;
- this.critical = true;
- encodeThis();
- }
- super.encode(tmp);
- out.write(tmp.toByteArray());
+ DerOutputStream tmp = new DerOutputStream();
+
+ if (this.extensionValue == null) {
+ this.extensionId = PKIXExtensions.InvalidityDate_Id;
+ this.critical = true;
+ encodeThis();
+ }
+ super.encode(tmp);
+ out.write(tmp.toByteArray());
}
/**
* Return an enumeration of names of attributes existing within this
* attribute.
*/
- public Enumeration<String> getAttributeNames () {
+ public Enumeration<String> getAttributeNames() {
Vector<String> elements = new Vector<String>();
elements.addElement(INVALIDITY_DATE);
return (elements.elements());
}
}
-
diff --git a/pki/base/util/src/netscape/security/x509/IssuerAlternativeNameExtension.java b/pki/base/util/src/netscape/security/x509/IssuerAlternativeNameExtension.java
index eeb05c91..a90530d3 100644
--- a/pki/base/util/src/netscape/security/x509/IssuerAlternativeNameExtension.java
+++ b/pki/base/util/src/netscape/security/x509/IssuerAlternativeNameExtension.java
@@ -29,15 +29,16 @@ import netscape.security.util.DerValue;
/**
* This represents the Issuer Alternative Name Extension.
- *
- * This extension, if present, allows the issuer to specify multiple
- * alternative names.
- *
- * <p>Extensions are represented as a sequence of the extension identifier
- * (Object Identifier), a boolean flag stating whether the extension is to
- * be treated as being critical and the extension value itself (this is again
- * a DER encoding of the extension value).
- *
+ *
+ * This extension, if present, allows the issuer to specify multiple alternative
+ * names.
+ *
+ * <p>
+ * Extensions are represented as a sequence of the extension identifier (Object
+ * Identifier), a boolean flag stating whether the extension is to be treated as
+ * being critical and the extension value itself (this is again a DER encoding
+ * of the extension value).
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.7
@@ -45,15 +46,15 @@ import netscape.security.util.DerValue;
* @see CertAttrSet
*/
public class IssuerAlternativeNameExtension
-extends Extension implements CertAttrSet {
+ extends Extension implements CertAttrSet {
/**
*
*/
private static final long serialVersionUID = -269518027483586255L;
/**
- * Identifier for this attribute, to be used with the
- * get, set, delete methods of Certificate, x509 type.
- */
+ * Identifier for this attribute, to be used with the get, set, delete
+ * methods of Certificate, x509 type.
+ */
public static final String IDENT =
"x509.info.extensions.IssuerAlternativeName";
/**
@@ -62,7 +63,7 @@ extends Extension implements CertAttrSet {
public static final String ISSUER_NAME = "issuer_name";
// private data members
- GeneralNames names;
+ GeneralNames names;
// Encode this extension
private void encodeThis() throws IOException {
@@ -77,13 +78,13 @@ extends Extension implements CertAttrSet {
/**
* Create a IssuerAlternativeNameExtension with the passed GeneralNames.
- *
+ *
* @param critical true if the extension is to be treated as critical.
* @param names the GeneralNames for the issuer.
* @exception IOException on error.
*/
public IssuerAlternativeNameExtension(Boolean critical, GeneralNames names)
- throws IOException {
+ throws IOException {
this.names = names;
this.extensionId = PKIXExtensions.IssuerAlternativeName_Id;
this.critical = critical.booleanValue();
@@ -92,12 +93,12 @@ extends Extension implements CertAttrSet {
/**
* Create a IssuerAlternativeNameExtension with the passed GeneralNames.
- *
+ *
* @param names the GeneralNames for the issuer.
* @exception IOException on error.
*/
public IssuerAlternativeNameExtension(GeneralNames names)
- throws IOException {
+ throws IOException {
this.names = names;
this.extensionId = PKIXExtensions.IssuerAlternativeName_Id;
this.critical = false;
@@ -115,21 +116,21 @@ extends Extension implements CertAttrSet {
/**
* Create the extension from the passed DER encoded value.
- *
+ *
* @param critical true if the extension is to be treated as critical.
* @param value Array of DER encoded bytes of the actual value.
* @exception IOException on error.
*/
public IssuerAlternativeNameExtension(Boolean critical, Object value)
- throws IOException {
+ throws IOException {
this.extensionId = PKIXExtensions.IssuerAlternativeName_Id;
this.critical = critical.booleanValue();
int len = Array.getLength(value);
- byte[] extValue = new byte[len];
- for (int i = 0; i < len; i++) {
- extValue[i] = Array.getByte(value, i);
- }
+ byte[] extValue = new byte[len];
+ for (int i = 0; i < len; i++) {
+ extValue[i] = Array.getByte(value, i);
+ }
this.extensionValue = extValue;
DerValue val = new DerValue(extValue);
try {
@@ -138,21 +139,22 @@ extends Extension implements CertAttrSet {
throw new IOException("IssuerAlternativeNameExtension"
+ e.toString());
}
- }
-
- /**
- * Returns a printable representation of the IssuerAlternativeName.
- */
- public String toString() {
- if (names == null) return "";
- String s = super.toString() + "IssuerAlternativeName [\n"
+ }
+
+ /**
+ * Returns a printable representation of the IssuerAlternativeName.
+ */
+ public String toString() {
+ if (names == null)
+ return "";
+ String s = super.toString() + "IssuerAlternativeName [\n"
+ names.toString() + "]\n";
- return (s);
- }
+ return (s);
+ }
/**
* Decode the extension from the InputStream.
- *
+ *
* @param in the InputStream to unmarshal the contents from.
* @exception IOException on decoding or validity errors.
*/
@@ -162,19 +164,19 @@ extends Extension implements CertAttrSet {
/**
* Write the extension to the OutputStream.
- *
+ *
* @param out the OutputStream to write the extension to.
* @exception IOException on encoding error.
*/
public void encode(OutputStream out) throws IOException {
DerOutputStream tmp = new DerOutputStream();
- if (extensionValue == null) {
+ if (extensionValue == null) {
extensionId = PKIXExtensions.IssuerAlternativeName_Id;
- critical = false;
- encodeThis();
- }
- super.encode(tmp);
- out.write(tmp.toByteArray());
+ critical = false;
+ encodeThis();
+ }
+ super.encode(tmp);
+ out.write(tmp.toByteArray());
}
/**
@@ -182,40 +184,40 @@ extends Extension implements CertAttrSet {
*/
public void set(String name, Object obj) throws IOException {
clearValue();
- if (name.equalsIgnoreCase(ISSUER_NAME)) {
- if (!(obj instanceof GeneralNames)) {
- throw new IOException("Attribute value should be of" +
+ if (name.equalsIgnoreCase(ISSUER_NAME)) {
+ if (!(obj instanceof GeneralNames)) {
+ throw new IOException("Attribute value should be of" +
" type GeneralNames.");
- }
- names = (GeneralNames)obj;
- } else {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:IssuerAlternativeName.");
- }
+ }
+ names = (GeneralNames) obj;
+ } else {
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:IssuerAlternativeName.");
+ }
}
/**
* Get the attribute value.
*/
public Object get(String name) throws IOException {
- if (name.equalsIgnoreCase(ISSUER_NAME)) {
- return (names);
- } else {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:IssuerAlternativeName.");
- }
+ if (name.equalsIgnoreCase(ISSUER_NAME)) {
+ return (names);
+ } else {
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:IssuerAlternativeName.");
+ }
}
/**
* Delete the attribute value.
*/
public void delete(String name) throws IOException {
- if (name.equalsIgnoreCase(ISSUER_NAME)) {
- names = null;
- } else {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:IssuerAlternativeName.");
- }
+ if (name.equalsIgnoreCase(ISSUER_NAME)) {
+ names = null;
+ } else {
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:IssuerAlternativeName.");
+ }
}
/**
@@ -226,7 +228,7 @@ extends Extension implements CertAttrSet {
Vector<String> elements = new Vector<String>();
elements.addElement(ISSUER_NAME);
- return (elements.elements());
+ return (elements.elements());
}
}
diff --git a/pki/base/util/src/netscape/security/x509/IssuingDistributionPoint.java b/pki/base/util/src/netscape/security/x509/IssuingDistributionPoint.java
index 090b0cb3..7aa7b802 100644
--- a/pki/base/util/src/netscape/security/x509/IssuingDistributionPoint.java
+++ b/pki/base/util/src/netscape/security/x509/IssuingDistributionPoint.java
@@ -42,11 +42,11 @@ import org.mozilla.jss.asn1.Tag;
* onlyContainsCACerts [2] BOOLEAN DEFAULT FALSE,
* onlySomeReasons [3] ReasonFlags OPTIONAL,
* indirectCRL [4] BOOLEAN DEFAULT FALSE }
- *
+ *
* DistributionPointName ::= CHOICE {
* fullName [0] GeneralNames,
* nameRelativeToCRLIssuer [1] RelativeDistinguishedName }
- *
+ *
* ReasonFlags ::= BIT STRING {
* unused (0),
* keyCompromise (1),
@@ -55,9 +55,9 @@ import org.mozilla.jss.asn1.Tag;
* superseded (4),
* cessationOfOperation (5),
* certificateHold (6) }
- *
+ *
* GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
- *
+ *
* GeneralName ::= CHOICE {
* otherName [0] OtherName,
* rfc822Name [1] IA5String,
@@ -68,41 +68,41 @@ import org.mozilla.jss.asn1.Tag;
* uniformResourceIdentifier [6] IA5String,
* iPAddress [7] OCTET STRING,
* registeredID [8] OBJECT IDENTIFIER}
- *
+ *
* OtherName ::= SEQUENCE {
* type-id OBJECT IDENTIFIER,
* value [0] EXPLICIT ANY DEFINED BY type-id }
- *
+ *
* EDIPartyName ::= SEQUENCE {
* nameAssigner [0] DirectoryString OPTIONAL,
* partyName [1] DirectoryString }
- *
+ *
* RelativeDistinguishedName ::=
* SET OF AttributeTypeAndValue
- *
+ *
* AttributeTypeAndValue ::= SEQUENCE {
* type AttributeType,
* value AttributeValue }
- *
+ *
* AttributeType ::= OBJECT IDENTIFIER
- *
+ *
* AttributeValue ::= ANY DEFINED BY AttributeType
* </pre>
- * See the documentation in <code>CRLDistributionPoint</code> for
- * the <code>DistributionPointName</code> and <code>ReasonFlags</code>
- * ASN.1 types.
+ *
+ * See the documentation in <code>CRLDistributionPoint</code> for the
+ * <code>DistributionPointName</code> and <code>ReasonFlags</code> ASN.1 types.
*/
public class IssuingDistributionPoint implements ASN1Value {
- // at most one of the following two may be specified. One or both can
+ // at most one of the following two may be specified. One or both can
// be null.
- private GeneralNames fullName=null;
- private RDN relativeName=null;
+ private GeneralNames fullName = null;
+ private RDN relativeName = null;
- private boolean onlyContainsUserCerts=false; // DEFAULT FALSE
- private boolean onlyContainsCACerts=false; // DEFAULT FALSE
- private BitArray onlySomeReasons=null; // optional, may be null
- private boolean indirectCRL=false; // DEFAULT FALSE
+ private boolean onlyContainsUserCerts = false; // DEFAULT FALSE
+ private boolean onlyContainsCACerts = false; // DEFAULT FALSE
+ private BitArray onlySomeReasons = null; // optional, may be null
+ private boolean indirectCRL = false; // DEFAULT FALSE
// cache encoding of fullName
private ANY fullNameEncoding;
@@ -124,31 +124,29 @@ public class IssuingDistributionPoint implements ASN1Value {
}
/**
- * Sets the <code>fullName</code> of the
- * <code>DistributionPointName</code>. It may be set to <code>null</code>.
- * If it is set to a non-null value, <code>relativeName</code> will be
- * set to <code>null</code>, because at most one of these two attributes
- * can be specified at a time.
- * @exception GeneralNamesException If an error occurs encoding the
- * name.
+ * Sets the <code>fullName</code> of the <code>DistributionPointName</code>.
+ * It may be set to <code>null</code>. If it is set to a non-null value,
+ * <code>relativeName</code> will be set to <code>null</code>, because at
+ * most one of these two attributes can be specified at a time.
+ *
+ * @exception GeneralNamesException If an error occurs encoding the name.
*/
public void setFullName(GeneralNames fullName)
- throws GeneralNamesException, IOException
- {
+ throws GeneralNamesException, IOException {
this.fullName = fullName;
- if( fullName != null ) {
+ if (fullName != null) {
// encode the name to catch any problems with it
DerOutputStream derOut = new DerOutputStream();
fullName.encode(derOut);
try {
ANY raw = new ANY(derOut.toByteArray());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
- raw.encodeWithAlternateTag( Tag.get(0), bos );
- fullNameEncoding = new ANY( bos.toByteArray() );
- } catch(InvalidBERException e) {
+ raw.encodeWithAlternateTag(Tag.get(0), bos);
+ fullNameEncoding = new ANY(bos.toByteArray());
+ } catch (InvalidBERException e) {
// assume this won't happen, since it would imply a bug
// in DerOutputStream
- throw new GeneralNamesException( e.toString() );
+ throw new GeneralNamesException(e.toString());
}
this.relativeName = null;
@@ -157,14 +155,14 @@ public class IssuingDistributionPoint implements ASN1Value {
/**
* Sets the <code>relativeName</code> of the
- * <code>DistributionPointName</code>. It may be set to <code>null</code>.
- * If it is set to a non-null value, <code>fullName</code> will be
- * set to <code>null</code>, because at most one of these two attributes
- * can be specified at a time.
+ * <code>DistributionPointName</code>. It may be set to <code>null</code>.
+ * If it is set to a non-null value, <code>fullName</code> will be set to
+ * <code>null</code>, because at most one of these two attributes can be
+ * specified at a time.
*/
public void setRelativeName(RDN relativeName) {
this.relativeName = relativeName;
- if( relativeName != null ) {
+ if (relativeName != null) {
this.fullName = null;
}
}
@@ -186,7 +184,7 @@ public class IssuingDistributionPoint implements ASN1Value {
}
/**
- * Returns the reason flags for this distribution point. May be
+ * Returns the reason flags for this distribution point. May be
* <code>null</code>.
*/
public BitArray getOnlySomeReasons() {
@@ -194,7 +192,7 @@ public class IssuingDistributionPoint implements ASN1Value {
}
/**
- * Sets the reason flags for this distribution point. May be set to
+ * Sets the reason flags for this distribution point. May be set to
* <code>null</code>.
*/
public void setOnlySomeReasons(BitArray reasons) {
@@ -209,10 +207,9 @@ public class IssuingDistributionPoint implements ASN1Value {
indirectCRL = b;
}
-
- /////////////////////////////////////////////////////////////
+ // ///////////////////////////////////////////////////////////
// DER encoding
- /////////////////////////////////////////////////////////////
+ // ///////////////////////////////////////////////////////////
private static final Tag TAG = SEQUENCE.TAG;
public Tag getTag() {
@@ -224,101 +221,99 @@ public class IssuingDistributionPoint implements ASN1Value {
}
public void encode(Tag implicitTag, OutputStream ostream)
- throws IOException
- {
+ throws IOException {
SEQUENCE seq = new SEQUENCE();
DerOutputStream derOut;
- try {
-
- // Encodes the DistributionPointName. Because DistributionPointName
- // is a CHOICE, the [0] tag is forced to be EXPLICIT.
- if( fullName != null ) {
- EXPLICIT distPoint = new EXPLICIT( Tag.get(0), fullNameEncoding);
- seq.addElement( distPoint );
- } else if( relativeName != null ) {
- derOut = new DerOutputStream();
- relativeName.encode(derOut);
- ANY raw = new ANY(derOut.toByteArray());
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- raw.encodeWithAlternateTag( Tag.get(1), bos );
- ANY distPointName = new ANY(bos.toByteArray());
- EXPLICIT distPoint = new EXPLICIT( Tag.get(0), distPointName);
- seq.addElement( distPoint );
- }
+ try {
- if( onlyContainsUserCerts != false ) {
- seq.addElement( Tag.get(1), new BOOLEAN(true));
- }
- if( onlyContainsCACerts != false ) {
- seq.addElement( Tag.get(2), new BOOLEAN(true));
- }
+ // Encodes the DistributionPointName. Because DistributionPointName
+ // is a CHOICE, the [0] tag is forced to be EXPLICIT.
+ if (fullName != null) {
+ EXPLICIT distPoint = new EXPLICIT(Tag.get(0), fullNameEncoding);
+ seq.addElement(distPoint);
+ } else if (relativeName != null) {
+ derOut = new DerOutputStream();
+ relativeName.encode(derOut);
+ ANY raw = new ANY(derOut.toByteArray());
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ raw.encodeWithAlternateTag(Tag.get(1), bos);
+ ANY distPointName = new ANY(bos.toByteArray());
+ EXPLICIT distPoint = new EXPLICIT(Tag.get(0), distPointName);
+ seq.addElement(distPoint);
+ }
- // Encodes the ReasonFlags.
- if( onlySomeReasons != null ) {
- derOut = new DerOutputStream();
- derOut.putUnalignedBitString(onlySomeReasons);
- ANY raw = new ANY(derOut.toByteArray());
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- raw.encodeWithAlternateTag(Tag.get(3), bos);
- ANY reasonEncoding = new ANY(bos.toByteArray());
- seq.addElement( reasonEncoding);
- }
+ if (onlyContainsUserCerts != false) {
+ seq.addElement(Tag.get(1), new BOOLEAN(true));
+ }
+ if (onlyContainsCACerts != false) {
+ seq.addElement(Tag.get(2), new BOOLEAN(true));
+ }
- if( indirectCRL != false ) {
- seq.addElement( Tag.get(4), new BOOLEAN(true));
- }
+ // Encodes the ReasonFlags.
+ if (onlySomeReasons != null) {
+ derOut = new DerOutputStream();
+ derOut.putUnalignedBitString(onlySomeReasons);
+ ANY raw = new ANY(derOut.toByteArray());
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ raw.encodeWithAlternateTag(Tag.get(3), bos);
+ ANY reasonEncoding = new ANY(bos.toByteArray());
+ seq.addElement(reasonEncoding);
+ }
+
+ if (indirectCRL != false) {
+ seq.addElement(Tag.get(4), new BOOLEAN(true));
+ }
- seq.encode(implicitTag, ostream);
+ seq.encode(implicitTag, ostream);
- } catch(InvalidBERException e) {
+ } catch (InvalidBERException e) {
// this shouldn't happen unless there is a bug in one of
// the Sun encoding classes
throw new IOException(e.toString());
- }
+ }
}
public static void main(String args[]) {
- try {
- if(args.length != 1) {
- System.out.println("Usage: IssuingDistributionPoint <outfile>");
- System.exit(-1);
- }
+ try {
+ if (args.length != 1) {
+ System.out.println("Usage: IssuingDistributionPoint <outfile>");
+ System.exit(-1);
+ }
- BufferedOutputStream bos = new BufferedOutputStream(
- new FileOutputStream(args[0]));
-
- SEQUENCE idps = new SEQUENCE();
-
- IssuingDistributionPoint idp = new IssuingDistributionPoint();
-
- X500Name dn = new X500Name("CN=Skovw Wjasldk,E=nicolson@netscape.com"+
- ",OU=Certificate Server,O=Netscape,C=US");
- GeneralNames generalNames = new GeneralNames();
- generalNames.addElement(dn);
- idp.setFullName(generalNames);
- idps.addElement(idp);
-
- idp = new IssuingDistributionPoint();
- URIName uri = new URIName("http://www.mycrl.com/go/here");
- generalNames = new GeneralNames();
- generalNames.addElement(uri);
- idp.setFullName(generalNames);
- idp.setOnlyContainsUserCerts(true);
- idp.setOnlyContainsCACerts(true);
- idp.setIndirectCRL(true);
- BitArray ba = new BitArray(5, new byte[] {(byte)0x28} );
- idp.setOnlySomeReasons(ba);
- idps.addElement(idp);
-
- idps.encode(bos);
- bos.close();
- } catch(Exception e) {
- e.printStackTrace();
- }
+ BufferedOutputStream bos = new BufferedOutputStream(
+ new FileOutputStream(args[0]));
+
+ SEQUENCE idps = new SEQUENCE();
+
+ IssuingDistributionPoint idp = new IssuingDistributionPoint();
+
+ X500Name dn = new X500Name("CN=Skovw Wjasldk,E=nicolson@netscape.com" +
+ ",OU=Certificate Server,O=Netscape,C=US");
+ GeneralNames generalNames = new GeneralNames();
+ generalNames.addElement(dn);
+ idp.setFullName(generalNames);
+ idps.addElement(idp);
+
+ idp = new IssuingDistributionPoint();
+ URIName uri = new URIName("http://www.mycrl.com/go/here");
+ generalNames = new GeneralNames();
+ generalNames.addElement(uri);
+ idp.setFullName(generalNames);
+ idp.setOnlyContainsUserCerts(true);
+ idp.setOnlyContainsCACerts(true);
+ idp.setIndirectCRL(true);
+ BitArray ba = new BitArray(5, new byte[] { (byte) 0x28 });
+ idp.setOnlySomeReasons(ba);
+ idps.addElement(idp);
+
+ idps.encode(bos);
+ bos.close();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
}
}
-
diff --git a/pki/base/util/src/netscape/security/x509/IssuingDistributionPointExtension.java b/pki/base/util/src/netscape/security/x509/IssuingDistributionPointExtension.java
index 2477591e..d3cc0a0e 100644
--- a/pki/base/util/src/netscape/security/x509/IssuingDistributionPointExtension.java
+++ b/pki/base/util/src/netscape/security/x509/IssuingDistributionPointExtension.java
@@ -33,9 +33,9 @@ import netscape.security.util.DerValue;
import org.mozilla.jss.asn1.ASN1Util;
/**
- * A critical CRL extension that identifies the CRL distribution point
- * for a particular CRL
- *
+ * A critical CRL extension that identifies the CRL distribution point for a
+ * particular CRL
+ *
* <pre>
* issuingDistributionPoint ::= SEQUENCE {
* distributionPoint [0] DistributionPointName OPTIONAL,
@@ -43,11 +43,11 @@ import org.mozilla.jss.asn1.ASN1Util;
* onlyContainsCACerts [2] BOOLEAN DEFAULT FALSE,
* onlySomeReasons [3] ReasonFlags OPTIONAL,
* indirectCRL [4] BOOLEAN DEFAULT FALSE }
- *
+ *
* DistributionPointName ::= CHOICE {
* fullName [0] GeneralNames,
* nameRelativeToCRLIssuer [1] RelativeDistinguishedName }
- *
+ *
* ReasonFlags ::= BIT STRING {
* unused (0),
* keyCompromise (1),
@@ -56,9 +56,9 @@ import org.mozilla.jss.asn1.ASN1Util;
* superseded (4),
* cessationOfOperation (5),
* certificateHold (6) }
- *
+ *
* GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
- *
+ *
* GeneralName ::= CHOICE {
* otherName [0] OtherName,
* rfc822Name [1] IA5String,
@@ -69,30 +69,29 @@ import org.mozilla.jss.asn1.ASN1Util;
* uniformResourceIdentifier [6] IA5String,
* iPAddress [7] OCTET STRING,
* registeredID [8] OBJECT IDENTIFIER}
- *
+ *
* OtherName ::= SEQUENCE {
* type-id OBJECT IDENTIFIER,
* value [0] EXPLICIT ANY DEFINED BY type-id }
- *
+ *
* EDIPartyName ::= SEQUENCE {
* nameAssigner [0] DirectoryString OPTIONAL,
* partyName [1] DirectoryString }
- *
+ *
* RelativeDistinguishedName ::=
* SET OF AttributeTypeAndValue
- *
+ *
* AttributeTypeAndValue ::= SEQUENCE {
* type AttributeType,
* value AttributeValue }
- *
+ *
* AttributeType ::= OBJECT IDENTIFIER
- *
+ *
* AttributeValue ::= ANY DEFINED BY AttributeType
* </pre>
*/
public class IssuingDistributionPointExtension extends Extension
- implements CertAttrSet
-{
+ implements CertAttrSet {
/**
*
*/
@@ -112,27 +111,26 @@ public class IssuingDistributionPointExtension extends Extension
private IssuingDistributionPoint issuingDistributionPoint = null;
// Cached DER-encoding to improve performance.
- private byte[] cachedEncoding=null;
-
+ private byte[] cachedEncoding = null;
static {
try {
OIDMap.addAttribute(IssuingDistributionPointExtension.class.getName(),
OID, IssuingDistributionPointExtension.class.getSimpleName());
- } catch (CertificateException e) {}
+ } catch (CertificateException e) {
+ }
}
-
/**
- * This constructor is very important, since it will be called
- * by the system.
+ * This constructor is very important, since it will be called by the
+ * system.
*/
public IssuingDistributionPointExtension(Boolean critical, Object value)
- throws IOException {
+ throws IOException {
this.extensionId = PKIXExtensions.IssuingDistributionPoint_Id;
this.critical = critical.booleanValue();
- this.extensionValue = (byte[])((byte[])value).clone();
+ this.extensionValue = (byte[]) ((byte[]) value).clone();
byte[] extValue = this.extensionValue;
issuingDistributionPoint = new IssuingDistributionPoint();
@@ -146,14 +144,14 @@ public class IssuingDistributionPointExtension extends Extension
if (opt != null) {
for (int i = 0; i < 5; i++) {
- if (opt.isContextSpecific((byte)i)) {
+ if (opt.isContextSpecific((byte) i)) {
if ((i == 0 && opt.isConstructed() && opt.data.available() != 0) ||
- (i != 0 && (!opt.isConstructed()) && opt.data.available() != 0)) {
+ (i != 0 && (!opt.isConstructed()) && opt.data.available() != 0)) {
if (i == 0) {
DerValue opt1 = opt.data.getDerValue();
if (opt1 != null) {
- if (opt1.isContextSpecific((byte)0)) {
+ if (opt1.isContextSpecific((byte) 0)) {
if (opt1.isConstructed() && opt1.data.available() != 0) {
opt1.resetTag(DerValue.tag_Sequence);
@@ -163,15 +161,15 @@ public class IssuingDistributionPointExtension extends Extension
issuingDistributionPoint.setFullName(fullName);
}
} catch (GeneralNamesException e) {
- throw new IOException("Invalid encoding of IssuingDistributionPoint "+e);
+ throw new IOException("Invalid encoding of IssuingDistributionPoint " + e);
} catch (IOException e) {
- throw new IOException("Invalid encoding of IssuingDistributionPoint "+e);
+ throw new IOException("Invalid encoding of IssuingDistributionPoint " + e);
}
} else {
throw new IOException("Invalid encoding of IssuingDistributionPoint");
}
- } else if (opt1.isContextSpecific((byte)1)) {
+ } else if (opt1.isContextSpecific((byte) 1)) {
if (opt1.isConstructed() && opt1.data.available() != 0) {
opt1.resetTag(DerValue.tag_Set);
@@ -181,7 +179,7 @@ public class IssuingDistributionPointExtension extends Extension
issuingDistributionPoint.setRelativeName(relativeName);
}
} catch (IOException e) {
- throw new IOException("Invalid encoding of IssuingDistributionPoint "+e);
+ throw new IOException("Invalid encoding of IssuingDistributionPoint " + e);
}
} else {
throw new IOException("Invalid encoding of IssuingDistributionPoint");
@@ -196,7 +194,7 @@ public class IssuingDistributionPointExtension extends Extension
issuingDistributionPoint.setOnlySomeReasons(reasons);
byte[] a = reasons.toByteArray();
} catch (IOException e) {
- throw new IOException("Invalid encoding of IssuingDistributionPoint "+e);
+ throw new IOException("Invalid encoding of IssuingDistributionPoint " + e);
}
} else {
@@ -211,7 +209,7 @@ public class IssuingDistributionPointExtension extends Extension
issuingDistributionPoint.setIndirectCRL(b);
}
} catch (IOException e) {
- throw new IOException("Invalid encoding of IssuingDistributionPoint "+e);
+ throw new IOException("Invalid encoding of IssuingDistributionPoint " + e);
}
}
} else {
@@ -226,10 +224,9 @@ public class IssuingDistributionPointExtension extends Extension
}
-
/**
- * Creates a new IssuingDistributionPoint extension, with the given
- * issuing distribution point as the first element.
+ * Creates a new IssuingDistributionPoint extension, with the given issuing
+ * distribution point as the first element.
*/
public IssuingDistributionPointExtension(IssuingDistributionPoint idp) {
this.extensionId = PKIXExtensions.IssuingDistributionPoint_Id;
@@ -244,27 +241,26 @@ public class IssuingDistributionPointExtension extends Extension
return issuingDistributionPoint;
}
- /**
- * Sets the criticality of this extension. PKIX dictates that this
- * extension SHOULD be critical, so applications can make it not critical
- * if they have a very good reason. By default, the extension is critical.
+ /**
+ * Sets the criticality of this extension. PKIX dictates that this extension
+ * SHOULD be critical, so applications can make it not critical if they have
+ * a very good reason. By default, the extension is critical.
*/
public void setCritical(boolean critical) {
this.critical = critical;
}
- /**
- * Gets the criticality of this extension. PKIX dictates that this
- * extension SHOULD be critical, so by default, the extension is critical.
+ /**
+ * Gets the criticality of this extension. PKIX dictates that this extension
+ * SHOULD be critical, so by default, the extension is critical.
*/
public boolean getCritical(boolean critical) {
return this.critical;
}
/**
- * Encodes this extension to the given DerOutputStream.
- * This method re-encodes each time it is called, so it is not very
- * efficient.
+ * Encodes this extension to the given DerOutputStream. This method
+ * re-encodes each time it is called, so it is not very efficient.
*/
public void encode(DerOutputStream out) throws IOException {
extensionValue = ASN1Util.encode(issuingDistributionPoint);
@@ -272,15 +268,16 @@ public class IssuingDistributionPointExtension extends Extension
}
/**
- * Should be called if any change is made to this data structure
- * so that the cached DER encoding can be discarded.
+ * Should be called if any change is made to this data structure so that the
+ * cached DER encoding can be discarded.
*/
public void flushCachedEncoding() {
cachedEncoding = null;
}
/**
- * Returns a printable representation of the IssuingDistributionPointExtension
+ * Returns a printable representation of the
+ * IssuingDistributionPointExtension
*/
public String toString() {
@@ -291,9 +288,8 @@ public class IssuingDistributionPointExtension extends Extension
* DER-encodes this extension to the given OutputStream.
*/
public void encode(OutputStream ostream)
- throws CertificateException, IOException
- {
- if( cachedEncoding == null ) {
+ throws CertificateException, IOException {
+ if (cachedEncoding == null) {
// only re-encode if necessary
DerOutputStream tmp = new DerOutputStream();
encode(tmp);
@@ -303,44 +299,40 @@ public class IssuingDistributionPointExtension extends Extension
}
public void decode(InputStream in)
- throws CertificateException, IOException
- {
+ throws CertificateException, IOException {
throw new IOException("Not supported");
}
public void set(String name, Object obj)
- throws CertificateException, IOException
- {
+ throws CertificateException, IOException {
if (name.equalsIgnoreCase(ISSUING_DISTRIBUTION_POINT)) {
if (!(obj instanceof IssuingDistributionPoint)) {
throw new IOException("Attribute value should be of type IssuingDistributionPoint.");
}
- issuingDistributionPoint = (IssuingDistributionPoint)obj;
+ issuingDistributionPoint = (IssuingDistributionPoint) obj;
} else {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:IssuingDistributionPointExtension");
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:IssuingDistributionPointExtension");
}
}
public Object get(String name)
- throws CertificateException, IOException
- {
+ throws CertificateException, IOException {
if (name.equalsIgnoreCase(ISSUING_DISTRIBUTION_POINT)) {
return issuingDistributionPoint;
} else {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:IssuingDistributionPointExtension");
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:IssuingDistributionPointExtension");
}
}
public void delete(String name)
- throws CertificateException, IOException
- {
+ throws CertificateException, IOException {
if (name.equalsIgnoreCase(ISSUING_DISTRIBUTION_POINT)) {
issuingDistributionPoint = null;
} else {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:IssuingDistributionPointExtension");
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:IssuingDistributionPointExtension");
}
}
@@ -348,70 +340,67 @@ public class IssuingDistributionPointExtension extends Extension
Vector<String> elements = new Vector<String>();
elements.addElement(ISSUING_DISTRIBUTION_POINT);
return (elements.elements());
-// return (new Vector()).elements();
+ // return (new Vector()).elements();
}
-
/**
* Test driver.
*/
public static void main(String args[]) {
- try {
+ try {
- if( args.length != 1 ) {
- System.out.println("Usage: IssuingDistributionPointExtension "+
- "<outfile>");
- System.exit(-1);
- }
+ if (args.length != 1) {
+ System.out.println("Usage: IssuingDistributionPointExtension " +
+ "<outfile>");
+ System.exit(-1);
+ }
- BufferedOutputStream bos = new BufferedOutputStream(
- new FileOutputStream(args[0]) );
-
-
- // URI only
- IssuingDistributionPoint idp = new IssuingDistributionPoint();
- URIName uri = new URIName("http://www.mycrl.com/go/here");
- GeneralNames generalNames = new GeneralNames();
- generalNames.addElement(uri);
- idp.setFullName(generalNames);
- IssuingDistributionPointExtension idpExt =
- new IssuingDistributionPointExtension(idp);
-
- // DN only
- idp = new IssuingDistributionPoint();
- X500Name dn = new X500Name("CN=Otis Smith,E=otis@fedoraproject.org"+
- ",OU=Certificate Server,O=Fedora,C=US");
- generalNames = new GeneralNames();
- generalNames.addElement(dn);
- idp.setFullName(generalNames);
- idpExt.set(IssuingDistributionPointExtension.ISSUING_DISTRIBUTION_POINT, idp);
-
- // DN + reason
- BitArray ba = new BitArray(5, new byte[] {(byte)0x28} );
- idp = new IssuingDistributionPoint();
- idp.setFullName(generalNames);
- idp.setOnlySomeReasons(ba);
- idpExt.set(IssuingDistributionPointExtension.ISSUING_DISTRIBUTION_POINT, idp);
-
-
- // relative DN + reason + crlIssuer
- idp = new IssuingDistributionPoint();
- RDN rdn = new RDN("OU=foobar dept");
- idp.setRelativeName(rdn);
- idp.setOnlySomeReasons(ba);
- idp.setOnlyContainsCACerts(true);
- idp.setOnlyContainsUserCerts(true);
- idp.setIndirectCRL(true);
- idpExt.set(IssuingDistributionPointExtension.ISSUING_DISTRIBUTION_POINT, idp);
-
- idpExt.setCritical(false);
- idpExt.encode(bos);
-
- bos.close();
-
- } catch(Exception e) {
+ BufferedOutputStream bos = new BufferedOutputStream(
+ new FileOutputStream(args[0]));
+
+ // URI only
+ IssuingDistributionPoint idp = new IssuingDistributionPoint();
+ URIName uri = new URIName("http://www.mycrl.com/go/here");
+ GeneralNames generalNames = new GeneralNames();
+ generalNames.addElement(uri);
+ idp.setFullName(generalNames);
+ IssuingDistributionPointExtension idpExt =
+ new IssuingDistributionPointExtension(idp);
+
+ // DN only
+ idp = new IssuingDistributionPoint();
+ X500Name dn = new X500Name("CN=Otis Smith,E=otis@fedoraproject.org" +
+ ",OU=Certificate Server,O=Fedora,C=US");
+ generalNames = new GeneralNames();
+ generalNames.addElement(dn);
+ idp.setFullName(generalNames);
+ idpExt.set(IssuingDistributionPointExtension.ISSUING_DISTRIBUTION_POINT, idp);
+
+ // DN + reason
+ BitArray ba = new BitArray(5, new byte[] { (byte) 0x28 });
+ idp = new IssuingDistributionPoint();
+ idp.setFullName(generalNames);
+ idp.setOnlySomeReasons(ba);
+ idpExt.set(IssuingDistributionPointExtension.ISSUING_DISTRIBUTION_POINT, idp);
+
+ // relative DN + reason + crlIssuer
+ idp = new IssuingDistributionPoint();
+ RDN rdn = new RDN("OU=foobar dept");
+ idp.setRelativeName(rdn);
+ idp.setOnlySomeReasons(ba);
+ idp.setOnlyContainsCACerts(true);
+ idp.setOnlyContainsUserCerts(true);
+ idp.setIndirectCRL(true);
+ idpExt.set(IssuingDistributionPointExtension.ISSUING_DISTRIBUTION_POINT, idp);
+
+ idpExt.setCritical(false);
+ idpExt.encode(bos);
+
+ bos.close();
+
+ } catch (Exception e) {
e.printStackTrace();
- }
+ }
}
}
diff --git a/pki/base/util/src/netscape/security/x509/KeyIdentifier.java b/pki/base/util/src/netscape/security/x509/KeyIdentifier.java
index dd0e49cb..631f6fd6 100644
--- a/pki/base/util/src/netscape/security/x509/KeyIdentifier.java
+++ b/pki/base/util/src/netscape/security/x509/KeyIdentifier.java
@@ -24,7 +24,7 @@ import netscape.security.util.DerValue;
/**
* Represent the Key Identifier ASN.1 object.
- *
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.4
@@ -38,7 +38,7 @@ public class KeyIdentifier implements java.io.Serializable {
/**
* Create a KeyIdentifier with the passed bit settings.
- *
+ *
* @param octetString the octet string identifying the key identifier.
*/
public KeyIdentifier(byte[] octetString) {
@@ -47,7 +47,7 @@ public class KeyIdentifier implements java.io.Serializable {
/**
* Create a KeyIdentifier from the DER encoded value.
- *
+ *
* @param val the DerValue
*/
public KeyIdentifier(DerValue val) throws IOException {
@@ -58,16 +58,16 @@ public class KeyIdentifier implements java.io.Serializable {
* Return the value of the KeyIdentifier as byte array.
*/
public byte[] getIdentifier() {
- return ((byte[])octetString.clone());
+ return ((byte[]) octetString.clone());
}
/**
* Returns a printable representation of the KeyUsage.
*/
public String toString() {
- netscape.security.util.PrettyPrintFormat pp =
- new netscape.security.util.PrettyPrintFormat(" ", 20);
- String octetbits = pp.toHexString(octetString);
+ netscape.security.util.PrettyPrintFormat pp =
+ new netscape.security.util.PrettyPrintFormat(" ", 20);
+ String octetbits = pp.toHexString(octetString);
String s = "KeyIdentifier [\n";
s += octetbits;
@@ -77,11 +77,11 @@ public class KeyIdentifier implements java.io.Serializable {
/**
* Write the KeyIdentifier to the DerOutputStream.
- *
+ *
* @param out the DerOutputStream to write the object to.
* @exception IOException
*/
- void encode (DerOutputStream out) throws IOException {
+ void encode(DerOutputStream out) throws IOException {
out.putOctetString(octetString);
}
}
diff --git a/pki/base/util/src/netscape/security/x509/KeyUsageExtension.java b/pki/base/util/src/netscape/security/x509/KeyUsageExtension.java
index 8d3aa21f..350e2e55 100644
--- a/pki/base/util/src/netscape/security/x509/KeyUsageExtension.java
+++ b/pki/base/util/src/netscape/security/x509/KeyUsageExtension.java
@@ -30,13 +30,14 @@ import netscape.security.util.DerValue;
/**
* Represent the Key Usage Extension.
- *
- * <p>This extension, if present, defines the purpose (e.g., encipherment,
- * signature, certificate signing) of the key contained in the certificate.
- * The usage restriction might be employed when a multipurpose key is to be
- * restricted (e.g., when an RSA key should be used only for signing or only
- * for key encipherment).
- *
+ *
+ * <p>
+ * This extension, if present, defines the purpose (e.g., encipherment,
+ * signature, certificate signing) of the key contained in the certificate. The
+ * usage restriction might be employed when a multipurpose key is to be
+ * restricted (e.g., when an RSA key should be used only for signing or only for
+ * key encipherment).
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.9
@@ -44,16 +45,16 @@ import netscape.security.util.DerValue;
* @see CertAttrSet
*/
public class KeyUsageExtension extends Extension
-implements CertAttrSet {
+ implements CertAttrSet {
/**
*
*/
private static final long serialVersionUID = 2899719374157256708L;
/**
- * Identifier for this attribute, to be used with the
- * get, set, delete methods of Certificate, x509 type.
- */
+ * Identifier for this attribute, to be used with the get, set, delete
+ * methods of Certificate, x509 type.
+ */
public static final String IDENT = "x509.info.extensions.KeyUsage";
/**
* Attribute names.
@@ -80,19 +81,19 @@ implements CertAttrSet {
public static final int NBITS = 9;
- public static String[] names = new String[NBITS];
-
- static {
- names[DIGITAL_SIGNATURE_BIT] = DIGITAL_SIGNATURE;
- names[NON_REPUDIATION_BIT] = NON_REPUDIATION;
- names[KEY_ENCIPHERMENT_BIT] = KEY_ENCIPHERMENT;
- names[DATA_ENCIPHERMENT_BIT] = DATA_ENCIPHERMENT;
- names[KEY_AGREEMENT_BIT] = KEY_AGREEMENT;
- names[KEY_CERTSIGN_BIT] = KEY_CERTSIGN;
- names[CRL_SIGN_BIT] = CRL_SIGN;
- names[ENCIPHER_ONLY_BIT] = ENCIPHER_ONLY;
- names[DECIPHER_ONLY_BIT] = DECIPHER_ONLY;
- }
+ public static String[] names = new String[NBITS];
+
+ static {
+ names[DIGITAL_SIGNATURE_BIT] = DIGITAL_SIGNATURE;
+ names[NON_REPUDIATION_BIT] = NON_REPUDIATION;
+ names[KEY_ENCIPHERMENT_BIT] = KEY_ENCIPHERMENT;
+ names[DATA_ENCIPHERMENT_BIT] = DATA_ENCIPHERMENT;
+ names[KEY_AGREEMENT_BIT] = KEY_AGREEMENT;
+ names[KEY_CERTSIGN_BIT] = KEY_CERTSIGN;
+ names[CRL_SIGN_BIT] = CRL_SIGN;
+ names[ENCIPHER_ONLY_BIT] = ENCIPHER_ONLY;
+ names[DECIPHER_ONLY_BIT] = DECIPHER_ONLY;
+ }
// Private data members
private boolean[] bitString;
@@ -106,12 +107,12 @@ implements CertAttrSet {
/**
* Check if bit is set.
- *
+ *
* @param position the position in the bit string to check.
*/
private boolean isSet(int position) {
- if (bitString.length <= position)
- return false;
+ if (bitString.length <= position)
+ return false;
return bitString[position];
}
@@ -119,32 +120,32 @@ implements CertAttrSet {
* Set the bit at the specified position.
*/
private void set(int position, boolean val) {
- // enlarge bitString if necessary
+ // enlarge bitString if necessary
if (position >= bitString.length) {
- boolean[] tmp = new boolean[position+1];
+ boolean[] tmp = new boolean[position + 1];
System.arraycopy(bitString, 0, tmp, 0, bitString.length);
bitString = tmp;
}
- bitString[position] = val;
+ bitString[position] = val;
}
/**
* Create a KeyUsageExtension with the passed bit settings. The criticality
* is set to true.
- *
+ *
* @param bitString the bits to be set for the extension.
*/
public KeyUsageExtension(boolean critical, byte[] bitString) throws IOException {
- this.bitString =
- new BitArray(bitString.length*8,bitString).toBooleanArray();
+ this.bitString =
+ new BitArray(bitString.length * 8, bitString).toBooleanArray();
this.extensionId = PKIXExtensions.KeyUsage_Id;
this.critical = critical;
encodeThis();
}
public KeyUsageExtension(byte[] bitString) throws IOException {
- this.bitString =
- new BitArray(bitString.length*8,bitString).toBooleanArray();
+ this.bitString =
+ new BitArray(bitString.length * 8, bitString).toBooleanArray();
this.extensionId = PKIXExtensions.KeyUsage_Id;
this.critical = true;
encodeThis();
@@ -153,7 +154,7 @@ implements CertAttrSet {
/**
* Create a KeyUsageExtension with the passed bit settings. The criticality
* is set to true.
- *
+ *
* @param bitString the bits to be set for the extension.
*/
public KeyUsageExtension(boolean critical, boolean[] bitString) throws IOException {
@@ -173,7 +174,7 @@ implements CertAttrSet {
/**
* Create a KeyUsageExtension with the passed bit settings. The criticality
* is set to true.
- *
+ *
* @param bitString the bits to be set for the extension.
*/
public KeyUsageExtension(BitArray bitString) throws IOException {
@@ -185,29 +186,27 @@ implements CertAttrSet {
/**
* Create the extension from the passed DER encoded value of the same.
- *
+ *
* @param critical true if the extension is to be treated as critical.
* @param value Array of DER encoded bytes of the actual value.
* @exception IOException on error.
*/
public KeyUsageExtension(Boolean critical, Object value)
- throws IOException {
+ throws IOException {
this.extensionId = PKIXExtensions.KeyUsage_Id;
this.critical = critical.booleanValue();
/*
- * The following check should be activated again after
- * the PKIX profiling work becomes standard and the check
- * is not a barrier to interoperability !
- * if (!this.critical) {
- * throw new IOException("KeyUsageExtension not marked critical,"
- * + " invalid profile.");
- * }
+ * The following check should be activated again after the PKIX
+ * profiling work becomes standard and the check is not a barrier to
+ * interoperability ! if (!this.critical) { throw new
+ * IOException("KeyUsageExtension not marked critical," +
+ * " invalid profile."); }
*/
int len = Array.getLength(value);
- byte[] extValue = new byte[len];
- for (int i = 0; i < len; i++) {
- extValue[i] = Array.getByte(value, i);
- }
+ byte[] extValue = new byte[len];
+ for (int i = 0; i < len; i++) {
+ extValue[i] = Array.getByte(value, i);
+ }
this.extensionValue = extValue;
DerValue val = new DerValue(extValue);
this.bitString = val.getUnalignedBitString().toBooleanArray();
@@ -228,88 +227,88 @@ implements CertAttrSet {
public void set(String name, Object obj) throws IOException {
clearValue();
if (!(obj instanceof Boolean)) {
- throw new IOException("Attribute must be of type Boolean.");
- }
- boolean val = ((Boolean)obj).booleanValue();
- if (name.equalsIgnoreCase(DIGITAL_SIGNATURE)) {
- set(0,val);
- } else if (name.equalsIgnoreCase(NON_REPUDIATION)) {
- set(1,val);
- } else if (name.equalsIgnoreCase(KEY_ENCIPHERMENT)) {
- set(2,val);
- } else if (name.equalsIgnoreCase(DATA_ENCIPHERMENT)) {
- set(3,val);
- } else if (name.equalsIgnoreCase(KEY_AGREEMENT)) {
- set(4,val);
- } else if (name.equalsIgnoreCase(KEY_CERTSIGN)) {
- set(5,val);
- } else if (name.equalsIgnoreCase(CRL_SIGN)) {
- set(6,val);
- } else if (name.equalsIgnoreCase(ENCIPHER_ONLY)) {
- set(7,val);
- } else if (name.equalsIgnoreCase(DECIPHER_ONLY)) {
- set(8,val);
- } else {
- throw new IOException("Attribute name not recognized by"
+ throw new IOException("Attribute must be of type Boolean.");
+ }
+ boolean val = ((Boolean) obj).booleanValue();
+ if (name.equalsIgnoreCase(DIGITAL_SIGNATURE)) {
+ set(0, val);
+ } else if (name.equalsIgnoreCase(NON_REPUDIATION)) {
+ set(1, val);
+ } else if (name.equalsIgnoreCase(KEY_ENCIPHERMENT)) {
+ set(2, val);
+ } else if (name.equalsIgnoreCase(DATA_ENCIPHERMENT)) {
+ set(3, val);
+ } else if (name.equalsIgnoreCase(KEY_AGREEMENT)) {
+ set(4, val);
+ } else if (name.equalsIgnoreCase(KEY_CERTSIGN)) {
+ set(5, val);
+ } else if (name.equalsIgnoreCase(CRL_SIGN)) {
+ set(6, val);
+ } else if (name.equalsIgnoreCase(ENCIPHER_ONLY)) {
+ set(7, val);
+ } else if (name.equalsIgnoreCase(DECIPHER_ONLY)) {
+ set(8, val);
+ } else {
+ throw new IOException("Attribute name not recognized by"
+ " CertAttrSet:KeyUsage.");
- }
- encodeThis();
+ }
+ encodeThis();
}
/**
* Get the attribute value.
*/
public Object get(String name) throws IOException {
- if (name.equalsIgnoreCase(DIGITAL_SIGNATURE)) {
- return new Boolean(isSet(0));
- } else if (name.equalsIgnoreCase(NON_REPUDIATION)) {
- return new Boolean(isSet(1));
- } else if (name.equalsIgnoreCase(KEY_ENCIPHERMENT)) {
- return new Boolean(isSet(2));
- } else if (name.equalsIgnoreCase(DATA_ENCIPHERMENT)) {
- return new Boolean(isSet(3));
- } else if (name.equalsIgnoreCase(KEY_AGREEMENT)) {
- return new Boolean(isSet(4));
- } else if (name.equalsIgnoreCase(KEY_CERTSIGN)) {
- return new Boolean(isSet(5));
- } else if (name.equalsIgnoreCase(CRL_SIGN)) {
- return new Boolean(isSet(6));
- } else if (name.equalsIgnoreCase(ENCIPHER_ONLY)) {
- return new Boolean(isSet(7));
- } else if (name.equalsIgnoreCase(DECIPHER_ONLY)) {
- return new Boolean(isSet(8));
- } else {
- throw new IOException("Attribute name not recognized by"
+ if (name.equalsIgnoreCase(DIGITAL_SIGNATURE)) {
+ return new Boolean(isSet(0));
+ } else if (name.equalsIgnoreCase(NON_REPUDIATION)) {
+ return new Boolean(isSet(1));
+ } else if (name.equalsIgnoreCase(KEY_ENCIPHERMENT)) {
+ return new Boolean(isSet(2));
+ } else if (name.equalsIgnoreCase(DATA_ENCIPHERMENT)) {
+ return new Boolean(isSet(3));
+ } else if (name.equalsIgnoreCase(KEY_AGREEMENT)) {
+ return new Boolean(isSet(4));
+ } else if (name.equalsIgnoreCase(KEY_CERTSIGN)) {
+ return new Boolean(isSet(5));
+ } else if (name.equalsIgnoreCase(CRL_SIGN)) {
+ return new Boolean(isSet(6));
+ } else if (name.equalsIgnoreCase(ENCIPHER_ONLY)) {
+ return new Boolean(isSet(7));
+ } else if (name.equalsIgnoreCase(DECIPHER_ONLY)) {
+ return new Boolean(isSet(8));
+ } else {
+ throw new IOException("Attribute name not recognized by"
+ " CertAttrSet:KeyUsage.");
- }
+ }
}
/**
* Delete the attribute value.
*/
public void delete(String name) throws IOException {
- if (name.equalsIgnoreCase(DIGITAL_SIGNATURE)) {
- set(0,false);
- } else if (name.equalsIgnoreCase(NON_REPUDIATION)) {
- set(1,false);
- } else if (name.equalsIgnoreCase(KEY_ENCIPHERMENT)) {
- set(2,false);
- } else if (name.equalsIgnoreCase(DATA_ENCIPHERMENT)) {
- set(3,false);
- } else if (name.equalsIgnoreCase(KEY_AGREEMENT)) {
- set(4,false);
- } else if (name.equalsIgnoreCase(KEY_CERTSIGN)) {
- set(5,false);
- } else if (name.equalsIgnoreCase(CRL_SIGN)) {
- set(6,false);
- } else if (name.equalsIgnoreCase(ENCIPHER_ONLY)) {
- set(7,false);
- } else if (name.equalsIgnoreCase(DECIPHER_ONLY)) {
- set(8,false);
- } else {
- throw new IOException("Attribute name not recognized by"
+ if (name.equalsIgnoreCase(DIGITAL_SIGNATURE)) {
+ set(0, false);
+ } else if (name.equalsIgnoreCase(NON_REPUDIATION)) {
+ set(1, false);
+ } else if (name.equalsIgnoreCase(KEY_ENCIPHERMENT)) {
+ set(2, false);
+ } else if (name.equalsIgnoreCase(DATA_ENCIPHERMENT)) {
+ set(3, false);
+ } else if (name.equalsIgnoreCase(KEY_AGREEMENT)) {
+ set(4, false);
+ } else if (name.equalsIgnoreCase(KEY_CERTSIGN)) {
+ set(5, false);
+ } else if (name.equalsIgnoreCase(CRL_SIGN)) {
+ set(6, false);
+ } else if (name.equalsIgnoreCase(ENCIPHER_ONLY)) {
+ set(7, false);
+ } else if (name.equalsIgnoreCase(DECIPHER_ONLY)) {
+ set(8, false);
+ } else {
+ throw new IOException("Attribute name not recognized by"
+ " CertAttrSet:KeyUsage.");
- }
+ }
}
/**
@@ -318,36 +317,37 @@ implements CertAttrSet {
public String toString() {
String s = super.toString() + "KeyUsage [\n";
- try {
- if (isSet(0)) {
- s += " DigitalSignature\n";
- }
- if (isSet(1)) {
- s += " Non_repudiation\n";
- }
- if (isSet(2)) {
- s += " Key_Encipherment\n";
- }
- if (isSet(3)) {
- s += " Data_Encipherment\n";
- }
- if (isSet(4)) {
- s += " Key_Agreement\n";
- }
- if (isSet(5)) {
- s += " Key_CertSign\n";
- }
- if (isSet(6)) {
- s += " Crl_Sign\n";
+ try {
+ if (isSet(0)) {
+ s += " DigitalSignature\n";
+ }
+ if (isSet(1)) {
+ s += " Non_repudiation\n";
+ }
+ if (isSet(2)) {
+ s += " Key_Encipherment\n";
+ }
+ if (isSet(3)) {
+ s += " Data_Encipherment\n";
+ }
+ if (isSet(4)) {
+ s += " Key_Agreement\n";
+ }
+ if (isSet(5)) {
+ s += " Key_CertSign\n";
+ }
+ if (isSet(6)) {
+ s += " Crl_Sign\n";
+ }
+ if (isSet(7)) {
+ s += " Encipher_Only\n";
+ }
+ if (isSet(8)) {
+ s += " Decipher_Only\n";
+ }
+ } catch (ArrayIndexOutOfBoundsException ex) {
}
- if (isSet(7)) {
- s += " Encipher_Only\n";
- }
- if (isSet(8)) {
- s += " Decipher_Only\n";
- }
- } catch (ArrayIndexOutOfBoundsException ex) {}
-
+
s += "]\n";
return (s);
@@ -355,7 +355,7 @@ implements CertAttrSet {
/**
* Decode the extension from the InputStream.
- *
+ *
* @param in the InputStream to unmarshal the contents from.
* @exception IOException on decoding or validity errors.
*/
@@ -365,27 +365,27 @@ implements CertAttrSet {
/**
* Write the extension to the DerOutputStream.
- *
+ *
* @param out the DerOutputStream to write the extension to.
* @exception IOException on encoding errors.
*/
public void encode(OutputStream out) throws IOException {
- DerOutputStream tmp = new DerOutputStream();
-
- if (this.extensionValue == null) {
- this.extensionId = PKIXExtensions.KeyUsage_Id;
- this.critical = true;
- encodeThis();
- }
- super.encode(tmp);
- out.write(tmp.toByteArray());
+ DerOutputStream tmp = new DerOutputStream();
+
+ if (this.extensionValue == null) {
+ this.extensionId = PKIXExtensions.KeyUsage_Id;
+ this.critical = true;
+ encodeThis();
+ }
+ super.encode(tmp);
+ out.write(tmp.toByteArray());
}
/**
* Return an enumeration of names of attributes existing within this
* attribute.
*/
- public Enumeration<String> getAttributeNames () {
+ public Enumeration<String> getAttributeNames() {
Vector<String> elements = new Vector<String>();
elements.addElement(DIGITAL_SIGNATURE);
elements.addElement(NON_REPUDIATION);
@@ -397,12 +397,11 @@ implements CertAttrSet {
elements.addElement(ENCIPHER_ONLY);
elements.addElement(DECIPHER_ONLY);
- return (elements.elements());
+ return (elements.elements());
}
-
public boolean[] getBits() {
- return (boolean[]) bitString.clone();
+ return (boolean[]) bitString.clone();
}
}
diff --git a/pki/base/util/src/netscape/security/x509/LdapDNStrConverter.java b/pki/base/util/src/netscape/security/x509/LdapDNStrConverter.java
index caf9ad01..26627ddc 100644
--- a/pki/base/util/src/netscape/security/x509/LdapDNStrConverter.java
+++ b/pki/base/util/src/netscape/security/x509/LdapDNStrConverter.java
@@ -20,64 +20,63 @@ package netscape.security.x509;
import java.io.IOException;
/**
- * Abstract class that converts a Ldap DN String to an X500Name, RDN or AVA
- * and vice versa, except the string is a java string in unicode.
+ * Abstract class that converts a Ldap DN String to an X500Name, RDN or AVA and
+ * vice versa, except the string is a java string in unicode.
*
* @author Lily Hsiao, Slava Galperin at Netscape Communications, Inc.
*/
-public abstract class LdapDNStrConverter
-{
- //
+public abstract class LdapDNStrConverter {
+ //
// public parsing methods.
//
/**
* Converts a Ldap DN string to a X500Name object.
- *
- * @param dn a Ldap DN String.
- *
- * @return an X500Name object for the Ldap DN String.
+ *
+ * @param dn a Ldap DN String.
+ *
+ * @return an X500Name object for the Ldap DN String.
*/
- public abstract X500Name parseDN(String dn)
- throws IOException;
+ public abstract X500Name parseDN(String dn)
+ throws IOException;
- /**
- * Like parseDN with a specified DER encoding order for Directory Strings.
- */
- public abstract X500Name parseDN(String dn, byte[] tags)
- throws IOException;
+ /**
+ * Like parseDN with a specified DER encoding order for Directory Strings.
+ */
+ public abstract X500Name parseDN(String dn, byte[] tags)
+ throws IOException;
- /**
+ /**
* Converts a Ldap DN string to a RDN object.
*
- * @param rdn a Ldap DN String
- *
- * @return an RDN object.
+ * @param rdn a Ldap DN String
+ *
+ * @return an RDN object.
*/
- public abstract RDN parseRDN(String rdn)
- throws IOException;
+ public abstract RDN parseRDN(String rdn)
+ throws IOException;
- /**
- * Like parseRDN with a specified DER encoding order for Directory Strings.
- */
- public abstract RDN parseRDN(String rdn, byte[] tags)
- throws IOException;
+ /**
+ * Like parseRDN with a specified DER encoding order for Directory Strings.
+ */
+ public abstract RDN parseRDN(String rdn, byte[] tags)
+ throws IOException;
- /**
+ /**
* Converts a Ldap DN string to a AVA object.
- *
- * @param ava a Ldap DN string.
- * @return an AVA object.
+ *
+ * @param ava a Ldap DN string.
+ * @return an AVA object.
*/
- public abstract AVA parseAVA(String ava)
- throws IOException;
+ public abstract AVA parseAVA(String ava)
+ throws IOException;
- /**
- * Like parseAVA with a specified DER encoding order for Directory Strings.
- */
- public abstract AVA parseAVA(String rdn, byte[] tags)
- throws IOException;
+ /**
+ * Like parseAVA with a specified DER encoding order for Directory Strings.
+ */
+ public abstract AVA parseAVA(String rdn, byte[] tags)
+ throws IOException;
//
// public encoding methods.
@@ -85,25 +84,25 @@ public abstract class LdapDNStrConverter
/**
* Converts a X500Name object to a Ldap dn string.
- *
- * @param dn an X500Name object.
- * @return a Ldap DN String.
+ *
+ * @param dn an X500Name object.
+ * @return a Ldap DN String.
*/
public abstract String encodeDN(X500Name dn) throws IOException;
/**
* Converts an RDN object to a Ldap dn string.
*
- * @param rdn an RDN object.
- * @return a Ldap dn string.
+ * @param rdn an RDN object.
+ * @return a Ldap dn string.
*/
public abstract String encodeRDN(RDN rdn) throws IOException;
/**
* Converts an AVA object to a Ldap dn string.
*
- * @param ava An AVA object.
- * @return A Ldap dn string.
+ * @param ava An AVA object.
+ * @return A Ldap dn string.
*/
public abstract String encodeAVA(AVA ava) throws IOException;
@@ -112,37 +111,34 @@ public abstract class LdapDNStrConverter
//
/**
- * Gets a global default Ldap DN String converter.
- * Currently it is LdapV3DNStrConverter object using the default
- * X500NameAttrMap and accepts unknown OIDs.
+ * Gets a global default Ldap DN String converter. Currently it is
+ * LdapV3DNStrConverter object using the default X500NameAttrMap and accepts
+ * unknown OIDs.
*
* @see netscape.security.x509.LdapV3DNStrConverter
- *
- * @return The global default LdapDNStrConverter instance.
+ *
+ * @return The global default LdapDNStrConverter instance.
*/
- public static LdapDNStrConverter getDefault()
- {
- return defaultConverter;
+ public static LdapDNStrConverter getDefault() {
+ return defaultConverter;
}
/**
* Set the global default LdapDNStrConverter object.
- *
- * @param defConverter A LdapDNStrConverter object to become
- * the global default.
+ *
+ * @param defConverter A LdapDNStrConverter object to become the global
+ * default.
*/
- public static void setDefault(LdapDNStrConverter defConverter)
- {
- if (defConverter == null)
- throw new IllegalArgumentException(
- "The default Ldap DN String converter cannot be set to null.");
- defaultConverter = defConverter;
+ public static void setDefault(LdapDNStrConverter defConverter) {
+ if (defConverter == null)
+ throw new IllegalArgumentException(
+ "The default Ldap DN String converter cannot be set to null.");
+ defaultConverter = defConverter;
}
//
// private static variables
//
- private static LdapDNStrConverter
- defaultConverter = new LdapV3DNStrConverter();
+ private static LdapDNStrConverter defaultConverter = new LdapV3DNStrConverter();
}
diff --git a/pki/base/util/src/netscape/security/x509/LdapV3DNStrConverter.java b/pki/base/util/src/netscape/security/x509/LdapV3DNStrConverter.java
index 114cc64a..e9e74073 100644
--- a/pki/base/util/src/netscape/security/x509/LdapV3DNStrConverter.java
+++ b/pki/base/util/src/netscape/security/x509/LdapV3DNStrConverter.java
@@ -31,21 +31,18 @@ import sun.io.ByteToCharConverter;
/**
* A converter that converts Ldap v3 DN strings as specified in
- * draft-ietf-asid-ldapv3-dn-03.txt to a X500Name, RDN or AVA and
- * vice versa.
- *
+ * draft-ietf-asid-ldapv3-dn-03.txt to a X500Name, RDN or AVA and vice versa.
+ *
* @see LdapDNStrConverter
* @see X500Name
* @see RDN
* @see AVA
* @see X500NameAttrMap
- *
+ *
* @author Lily Hsiao, Slava Galperin at Netscape Communications, Inc.
*/
-
-public class LdapV3DNStrConverter extends LdapDNStrConverter
-{
+public class LdapV3DNStrConverter extends LdapDNStrConverter {
//
// Constructors
//
@@ -53,31 +50,29 @@ public class LdapV3DNStrConverter extends LdapDNStrConverter
/**
* Constructs a LdapV3DNStrConverter using the global default
* X500NameAttrMap and accept OIDs not in the default X500NameAttrMap.
+ *
* @see X500NameAttrMap
*/
- public LdapV3DNStrConverter()
- {
+ public LdapV3DNStrConverter() {
attrMap = X500NameAttrMap.getDefault();
-
- acceptUnknownOids = true;
+ acceptUnknownOids = true;
}
/**
- * Constructs a LdapV3DNStrConverter using the specified X500NameAttrMap
- * and a boolean indicating whether to accept OIDs not listed in the
+ * Constructs a LdapV3DNStrConverter using the specified X500NameAttrMap and
+ * a boolean indicating whether to accept OIDs not listed in the
* X500NameAttrMap.
- *
- * @param attributeMap a X500NameAttrMap
- * @param doAcceptUnknownOids whether to convert unregistered OIDs
- * (oids not in the X500NameAttrMap)
+ *
+ * @param attributeMap a X500NameAttrMap
+ * @param doAcceptUnknownOids whether to convert unregistered OIDs (oids not
+ * in the X500NameAttrMap)
* @see X500NameAttrMap
*/
public LdapV3DNStrConverter(X500NameAttrMap attributeMap,
- boolean doAcceptUnknownOids)
- {
- attrMap = attributeMap;
- acceptUnknownOids = doAcceptUnknownOids;
+ boolean doAcceptUnknownOids) {
+ attrMap = attributeMap;
+ acceptUnknownOids = doAcceptUnknownOids;
}
@@ -88,276 +83,259 @@ public class LdapV3DNStrConverter extends LdapDNStrConverter
/**
* Parse a Ldap v3 DN string to a X500Name.
- *
- * @param dn a LDAP v3 DN String
- * @return a X500Name
+ *
+ * @param dn a LDAP v3 DN String
+ * @return a X500Name
* @exception IOException if an error occurs during the conversion.
*/
public X500Name parseDN(String dn)
- throws IOException
- {
- return parseDN(dn, null);
+ throws IOException {
+ return parseDN(dn, null);
}
/**
- * Like parseDN(String) with a DER encoding order given as argument for
+ * Like parseDN(String) with a DER encoding order given as argument for
* Directory Strings.
*/
public X500Name parseDN(String dn, byte[] encodingOrder)
- throws IOException
- {
- StringReader dn_reader = new StringReader(dn);
- PushbackReader in = new PushbackReader(dn_reader, 5);
- Vector<RDN> rdnVector = new Vector<RDN>();
+ throws IOException {
+ StringReader dn_reader = new StringReader(dn);
+ PushbackReader in = new PushbackReader(dn_reader, 5);
+ Vector<RDN> rdnVector = new Vector<RDN>();
RDN[] names;
- return parseDN(in, encodingOrder);
+ return parseDN(in, encodingOrder);
}
/**
* Parse a Ldap v3 DN string with a RDN component to a RDN
- *
- * @param rdn a LDAP v3 DN String
- * @return a RDN
+ *
+ * @param rdn a LDAP v3 DN String
+ * @return a RDN
* @exception IOException if an error occurs during the conversion.
*/
public RDN parseRDN(String rdn)
- throws IOException
- {
- return parseRDN(rdn, null);
+ throws IOException {
+ return parseRDN(rdn, null);
}
/**
- * Like parseRDN(String) with a DER encoding order given as argument for
+ * Like parseRDN(String) with a DER encoding order given as argument for
* Directory Strings.
*/
public RDN parseRDN(String rdn, byte[] encodingOrder)
- throws IOException
- {
- StringReader rdn_reader = new StringReader(rdn);
- PushbackReader in = new PushbackReader(rdn_reader, 5);
- Vector<AVA> avaVector = new Vector<AVA>();
+ throws IOException {
+ StringReader rdn_reader = new StringReader(rdn);
+ PushbackReader in = new PushbackReader(rdn_reader, 5);
+ Vector<AVA> avaVector = new Vector<AVA>();
AVA[] assertion;
- return parseRDN(in, null);
+ return parseRDN(in, null);
}
/**
* Parse a Ldap v3 DN string with a AVA component to a AVA.
- *
- * @param ava a LDAP v3 DN string
- * @return a AVA
+ *
+ * @param ava a LDAP v3 DN string
+ * @return a AVA
*/
public AVA parseAVA(String ava)
- throws IOException
- {
- return parseAVA(ava, null);
+ throws IOException {
+ return parseAVA(ava, null);
}
/**
- * Like parseDN(String) with a DER encoding order given as argument for
+ * Like parseDN(String) with a DER encoding order given as argument for
* Directory Strings.
*/
public AVA parseAVA(String ava, byte[] encodingOrder)
- throws IOException
- {
- StringReader ava_reader = new StringReader(ava);
- PushbackReader in = new PushbackReader(ava_reader, 5);
+ throws IOException {
+ StringReader ava_reader = new StringReader(ava);
+ PushbackReader in = new PushbackReader(ava_reader, 5);
- return parseAVA(in, encodingOrder);
+ return parseAVA(in, encodingOrder);
}
-
//
// public parsing methods called by other methods.
//
/**
* Parses a Ldap DN string in a string reader to a X500Name.
- *
- * @param in Pushback string reader for a Ldap DN string.
- * The pushback reader must have a pushback buffer size > 2.
- *
- * @return a X500Name
- *
- * @exception IOException if any reading or parsing error occurs.
+ *
+ * @param in Pushback string reader for a Ldap DN string. The pushback
+ * reader must have a pushback buffer size > 2.
+ *
+ * @return a X500Name
+ *
+ * @exception IOException if any reading or parsing error occurs.
*/
public X500Name parseDN(PushbackReader in)
- throws IOException
- {
- return parseDN(in, null);
+ throws IOException {
+ return parseDN(in, null);
}
/**
- * Like parseDN(PushbackReader in) with a DER encoding order given as
+ * Like parseDN(PushbackReader in) with a DER encoding order given as
* argument for Directory Strings.
*/
public X500Name parseDN(PushbackReader in, byte[] encodingOrder)
- throws IOException
- {
- RDN rdn;
- int lastChar;
+ throws IOException {
+ RDN rdn;
+ int lastChar;
Vector<RDN> rdnVector = new Vector<RDN>();
- RDN names[];
- int i,j;
+ RDN names[];
+ int i, j;
- do {
+ do {
rdn = parseRDN(in, encodingOrder);
rdnVector.addElement(rdn);
- lastChar = in.read();
- }
- while (lastChar == ',' || lastChar == ';');
+ lastChar = in.read();
+ } while (lastChar == ',' || lastChar == ';');
names = new RDN[rdnVector.size()];
- for (i=0, j=rdnVector.size()-1; i < rdnVector.size(); i++, j--)
- names[j] = (RDN)rdnVector.elementAt(i);
+ for (i = 0, j = rdnVector.size() - 1; i < rdnVector.size(); i++, j--)
+ names[j] = (RDN) rdnVector.elementAt(i);
return new X500Name(names);
}
/**
- * Parses Ldap DN string with a rdn component
- * from a string reader to a RDN. The string reader will point
- * to the separator after the rdn component or -1 if at end of string.
- *
- * @param in Pushback string reader containing a Ldap DN string with
- * at least one rdn component.
- * The pushback reader must have a pushback buffer size > 2.
- *
- * @return RDN object of the first rdn component in the Ldap DN string.
- *
+ * Parses Ldap DN string with a rdn component from a string reader to a RDN.
+ * The string reader will point to the separator after the rdn component or
+ * -1 if at end of string.
+ *
+ * @param in Pushback string reader containing a Ldap DN string with at
+ * least one rdn component. The pushback reader must have a
+ * pushback buffer size > 2.
+ *
+ * @return RDN object of the first rdn component in the Ldap DN string.
+ *
* @exception IOException if any read or parse error occurs.
*/
public RDN parseRDN(PushbackReader in)
- throws IOException
- {
- return parseRDN(in, null);
+ throws IOException {
+ return parseRDN(in, null);
}
/**
- * Like parseRDN(PushbackReader) with a DER encoding order given as
- * argument for Directory Strings.
+ * Like parseRDN(PushbackReader) with a DER encoding order given as argument
+ * for Directory Strings.
*/
public RDN parseRDN(PushbackReader in, byte[] encodingOrder)
- throws IOException
- {
- Vector<AVA> avaVector = new Vector<AVA>();
- AVA ava;
- int lastChar;
- AVA assertion[];
-
- do {
- ava = parseAVA(in, encodingOrder);
- avaVector.addElement(ava);
- lastChar = in.read();
- }
- while (lastChar == '+' );
-
- if (lastChar != -1)
- in.unread(lastChar);
-
- assertion = new AVA[avaVector.size()];
- for (int i = 0; i < avaVector.size(); i++)
- assertion[i] = (AVA)avaVector.elementAt(i);
- return new RDN(assertion);
+ throws IOException {
+ Vector<AVA> avaVector = new Vector<AVA>();
+ AVA ava;
+ int lastChar;
+ AVA assertion[];
+
+ do {
+ ava = parseAVA(in, encodingOrder);
+ avaVector.addElement(ava);
+ lastChar = in.read();
+ } while (lastChar == '+');
+
+ if (lastChar != -1)
+ in.unread(lastChar);
+
+ assertion = new AVA[avaVector.size()];
+ for (int i = 0; i < avaVector.size(); i++)
+ assertion[i] = (AVA) avaVector.elementAt(i);
+ return new RDN(assertion);
}
/**
- * Parses a Ldap DN string with a AVA component
- * from a string reader to an AVA. The string reader will point
- * to the AVA separator after the ava string or -1 if end of string.
- *
- * @param in a Pushback reader containg a Ldap string with
- * at least one AVA component.
- * The Pushback reader must have a pushback buffer size > 2.
- *
- * @return AVA object of the first AVA component in the Ldap DN string.
+ * Parses a Ldap DN string with a AVA component from a string reader to an
+ * AVA. The string reader will point to the AVA separator after the ava
+ * string or -1 if end of string.
+ *
+ * @param in a Pushback reader containg a Ldap string with at least one AVA
+ * component. The Pushback reader must have a pushback buffer
+ * size > 2.
+ *
+ * @return AVA object of the first AVA component in the Ldap DN string.
*/
public AVA parseAVA(PushbackReader in)
- throws IOException
- {
- return parseAVA(in, null);
+ throws IOException {
+ return parseAVA(in, null);
}
/**
- * Like parseAVA(PushbackReader) with a DER encoding order given as
- * argument for Directory Strings.
+ * Like parseAVA(PushbackReader) with a DER encoding order given as argument
+ * for Directory Strings.
*/
public AVA parseAVA(PushbackReader in, byte[] encodingOrder)
- throws IOException
- {
- int c;
- ObjectIdentifier oid;
- DerValue value;
- StringBuffer keywordBuf;
- StringBuffer valueBuf;
- ByteArrayOutputStream berStream;
+ throws IOException {
+ int c;
+ ObjectIdentifier oid;
+ DerValue value;
+ StringBuffer keywordBuf;
+ StringBuffer valueBuf;
+ ByteArrayOutputStream berStream;
char hexChar1, hexChar2;
- CharArrayWriter hexCharsBuf;
+ CharArrayWriter hexCharsBuf;
String endChars;
- /* First get the keyword indicating the attribute's type,
- * and map it to the appropriate OID.
+ /*
+ * First get the keyword indicating the attribute's type, and map it to
+ * the appropriate OID.
*/
- keywordBuf = new StringBuffer();
+ keywordBuf = new StringBuffer();
for (;;) {
- c = in.read ();
+ c = in.read();
if (c == '=')
break;
- if (c == -1)
- {
+ if (c == -1) {
throw new IOException("Bad AVA format: Missing '='");
}
- keywordBuf.append ((char)c);
+ keywordBuf.append((char) c);
}
- oid = parseAVAKeyword(keywordBuf.toString());
+ oid = parseAVAKeyword(keywordBuf.toString());
- /* Now parse the value. "#hex", a quoted string, or a string
- * terminated by "+", ",", ";", ">". Whitespace before or after
- * the value is stripped.
+ /*
+ * Now parse the value. "#hex", a quoted string, or a string terminated
+ * by "+", ",", ";", ">". Whitespace before or after the value is
+ * stripped.
*/
- for (c = in.read (); c == ' '; c = in.read ())
+ for (c = in.read(); c == ' '; c = in.read())
continue;
if (c == -1)
throw new IOException("Bad AVA format: Missing attribute value");
- if (c == '#')
- {
+ if (c == '#') {
/*
- * NOTE per LDAPv3 dn string ietf standard the value represented
- * by this form is a BER value. But we only support DER value here
+ * NOTE per LDAPv3 dn string ietf standard the value represented by
+ * this form is a BER value. But we only support DER value here
* which is only a form of BER.
*/
berStream = new ByteArrayOutputStream();
int b;
for (;;) {
- hexChar1 = (char)(c = in.read());
+ hexChar1 = (char) (c = in.read());
if (c == -1 || octoEndChars.indexOf(c) > 0) // end of value
break;
- hexChar2 = (char)(c = in.read());
- if (hexDigits.indexOf(hexChar1) == -1 ||
- hexDigits.indexOf(hexChar2) == -1)
+ hexChar2 = (char) (c = in.read());
+ if (hexDigits.indexOf(hexChar1) == -1 ||
+ hexDigits.indexOf(hexChar2) == -1)
throw new IOException("Bad AVA value: bad hex value.");
- b = (Character.digit(hexChar1, 16)<<4) +
- Character.digit(hexChar2, 16);
+ b = (Character.digit(hexChar1, 16) << 4) +
+ Character.digit(hexChar2, 16);
berStream.write(b);
}
if (berStream.size() == 0)
throw new IOException("bad AVA format: invalid hex value");
- value = parseAVAValue(berStream.toByteArray(), oid);
+ value = parseAVAValue(berStream.toByteArray(), oid);
- while (c == ' ' && c != -1)
+ while (c == ' ' && c != -1)
c = in.read();
- }
- else
- {
- valueBuf = new StringBuffer ();
- boolean quoted = false;
- if (c == '"') {
+ } else {
+ valueBuf = new StringBuffer();
+ boolean quoted = false;
+ if (c == '"') {
quoted = true;
endChars = quotedEndChars;
if ((c = in.read()) == -1)
- throw new IOException("Bad AVA format: Missing attrValue");
+ throw new IOException("Bad AVA format: Missing attrValue");
} else {
endChars = valueEndChars;
}
@@ -371,416 +349,395 @@ public class LdapV3DNStrConverter extends LdapDNStrConverter
throw new IOException("Bad AVA format: expecting " +
"escaped char.");
// expect escaping of special chars, space and CR.
- if (specialChars.indexOf((char)c) != -1 || c == '\n' ||
- c == '\\' || c == '"' || c == ' ') {
- valueBuf.append((char)c);
- }
- else if (hexDigits.indexOf(c) != -1) {
- hexCharsBuf = new CharArrayWriter();
- // handle sequence of '\' hexpair
- do {
- hexChar1 = (char)c;
- hexChar2 = (char)(c = in.read());
- if (hexDigits.indexOf((char)c) == -1)
- throw new IOException("Bad AVA format: " +
- "invalid escaped hex pair");
- hexCharsBuf.write(hexChar1);
- hexCharsBuf.write(hexChar2);
- // read ahead to next '\' hex-char if any.
- if ((c = in.read()) == -1)
- break;
- if (c != '\\') {
- in.unread(c);
- break;
- }
- if ((c = in.read()) == -1)
- throw new IOException("Bad AVA format: "+
- "expecting escaped char.");
- if (hexDigits.indexOf((char)c) == -1) {
- in.unread(c);
- in.unread((int)'\\');
- break;
- }
- } while (true);
- valueBuf.append(
- getStringFromHexpairs(hexCharsBuf.toCharArray()));
- }
- else {
+ if (specialChars.indexOf((char) c) != -1 || c == '\n' ||
+ c == '\\' || c == '"' || c == ' ') {
+ valueBuf.append((char) c);
+ } else if (hexDigits.indexOf(c) != -1) {
+ hexCharsBuf = new CharArrayWriter();
+ // handle sequence of '\' hexpair
+ do {
+ hexChar1 = (char) c;
+ hexChar2 = (char) (c = in.read());
+ if (hexDigits.indexOf((char) c) == -1)
+ throw new IOException("Bad AVA format: " +
+ "invalid escaped hex pair");
+ hexCharsBuf.write(hexChar1);
+ hexCharsBuf.write(hexChar2);
+ // read ahead to next '\' hex-char if any.
+ if ((c = in.read()) == -1)
+ break;
+ if (c != '\\') {
+ in.unread(c);
+ break;
+ }
+ if ((c = in.read()) == -1)
+ throw new IOException("Bad AVA format: " +
+ "expecting escaped char.");
+ if (hexDigits.indexOf((char) c) == -1) {
+ in.unread(c);
+ in.unread((int) '\\');
+ break;
+ }
+ } while (true);
+ valueBuf.append(
+ getStringFromHexpairs(hexCharsBuf.toCharArray()));
+ } else {
throw new IOException("Bad AVA format: " +
"invalid escaping");
}
- }
- else
- valueBuf.append((char)c);
+ } else
+ valueBuf.append((char) c);
c = in.read();
}
- value = parseAVAValue(
- valueBuf.toString().trim(), oid, encodingOrder);
+ value = parseAVAValue(
+ valueBuf.toString().trim(), oid, encodingOrder);
if (quoted) { // move to next non-white space
do {
c = in.read();
} while (c == ' ');
- if (c != -1 && valueEndChars.indexOf(c) == -1)
+ if (c != -1 && valueEndChars.indexOf(c) == -1)
throw new IOException(
- "Bad AVA format: separator expected at end of ava.");
+ "Bad AVA format: separator expected at end of ava.");
}
}
- if (c != -1)
- in.unread(c);
+ if (c != -1)
+ in.unread(c);
return new AVA(oid, value);
}
/**
- * Converts a AVA keyword from a Ldap DN string to an ObjectIdentifier
- * from the attribute map or, if this keyword is an OID not
- * in the attribute map, create a new ObjectIdentifier for the keyword
- * if acceptUnknownOids is true.
- *
- * @param avaKeyword AVA keyword from a Ldap DN string.
- *
- * @return a ObjectIdentifier object
- * @exception IOException if the keyword is an OID not in the attribute
- * map and acceptUnknownOids is false, or
- * if an error occurs during conversion.
+ * Converts a AVA keyword from a Ldap DN string to an ObjectIdentifier from
+ * the attribute map or, if this keyword is an OID not in the attribute map,
+ * create a new ObjectIdentifier for the keyword if acceptUnknownOids is
+ * true.
+ *
+ * @param avaKeyword AVA keyword from a Ldap DN string.
+ *
+ * @return a ObjectIdentifier object
+ * @exception IOException if the keyword is an OID not in the attribute map
+ * and acceptUnknownOids is false, or if an error occurs
+ * during conversion.
*/
public ObjectIdentifier parseAVAKeyword(String avaKeyword)
- throws IOException
- {
- String keyword = avaKeyword.toUpperCase().trim();
- String oid_str = null;
- ObjectIdentifier oid, new_oid;
-
-
- if (Character.digit(keyword.charAt(0), 10) != -1) {
- // value is an oid string of 1.2.3.4
- oid_str = keyword;
- }
- else if (keyword.startsWith("oid.") || keyword.startsWith("OID.")) {
- // value is an oid string of oid.1.2.3.4 or OID.1.2...
- oid_str = keyword.substring(4);
- }
-
- if (oid_str != null) {
- // value is an oid string of 1.2.3.4 or oid.1.2.3.4 or OID.1.2...
- new_oid = new ObjectIdentifier(oid_str);
- oid = attrMap.getOid(new_oid);
- if (oid == null) {
- if (!acceptUnknownOids)
- throw new IOException("Unknown AVA OID.");
- oid = new_oid;
- }
- }
- else {
- oid = attrMap.getOid(keyword);
- if (oid == null)
- throw new IOException("Unknown AVA keyword '"+keyword+"'.");
- }
-
- return oid;
+ throws IOException {
+ String keyword = avaKeyword.toUpperCase().trim();
+ String oid_str = null;
+ ObjectIdentifier oid, new_oid;
+
+ if (Character.digit(keyword.charAt(0), 10) != -1) {
+ // value is an oid string of 1.2.3.4
+ oid_str = keyword;
+ } else if (keyword.startsWith("oid.") || keyword.startsWith("OID.")) {
+ // value is an oid string of oid.1.2.3.4 or OID.1.2...
+ oid_str = keyword.substring(4);
+ }
+
+ if (oid_str != null) {
+ // value is an oid string of 1.2.3.4 or oid.1.2.3.4 or OID.1.2...
+ new_oid = new ObjectIdentifier(oid_str);
+ oid = attrMap.getOid(new_oid);
+ if (oid == null) {
+ if (!acceptUnknownOids)
+ throw new IOException("Unknown AVA OID.");
+ oid = new_oid;
+ }
+ } else {
+ oid = attrMap.getOid(keyword);
+ if (oid == null)
+ throw new IOException("Unknown AVA keyword '" + keyword + "'.");
+ }
+
+ return oid;
}
/**
- * Converts a AVA value from a Ldap dn string to a
- * DerValue according the attribute type. For example, a value for
- * CN, OU or O is expected to be a Directory String and will be converted
- * to a DerValue of ASN.1 type PrintableString, T61String or
- * UniversalString. A Directory String is a ASN.1 CHOICE of Printable,
- * T.61 or Universal string.
- *
- * @param avaValueString a attribute value from a Ldap DN string.
- * @param oid OID of the attribute.
- *
- * @return DerValue for the value.
- *
- * @exception IOException if an error occurs during conversion.
+ * Converts a AVA value from a Ldap dn string to a DerValue according the
+ * attribute type. For example, a value for CN, OU or O is expected to be a
+ * Directory String and will be converted to a DerValue of ASN.1 type
+ * PrintableString, T61String or UniversalString. A Directory String is a
+ * ASN.1 CHOICE of Printable, T.61 or Universal string.
+ *
+ * @param avaValueString a attribute value from a Ldap DN string.
+ * @param oid OID of the attribute.
+ *
+ * @return DerValue for the value.
+ *
+ * @exception IOException if an error occurs during conversion.
* @see AVAValueConverter
*/
public DerValue parseAVAValue(String avaValueString, ObjectIdentifier oid)
- throws IOException
- {
- return parseAVAValue(avaValueString, oid, null);
+ throws IOException {
+ return parseAVAValue(avaValueString, oid, null);
}
/**
- * Like parseAVAValue(String) with a DER encoding order given as argument
+ * Like parseAVAValue(String) with a DER encoding order given as argument
* for Directory Strings.
*/
public DerValue parseAVAValue(
- String avaValueString, ObjectIdentifier oid, byte[] encodingOrder)
- throws IOException
- {
- AVAValueConverter valueConverter = attrMap.getValueConverter(oid);
- if (valueConverter == null) {
- if (!acceptUnknownOids) {
- throw new IllegalArgumentException(
- "Unrecognized OID for AVA value conversion");
- } else {
- valueConverter = new GenericValueConverter();
- }
- }
- return valueConverter.getValue(avaValueString, encodingOrder);
+ String avaValueString, ObjectIdentifier oid, byte[] encodingOrder)
+ throws IOException {
+ AVAValueConverter valueConverter = attrMap.getValueConverter(oid);
+ if (valueConverter == null) {
+ if (!acceptUnknownOids) {
+ throw new IllegalArgumentException(
+ "Unrecognized OID for AVA value conversion");
+ } else {
+ valueConverter = new GenericValueConverter();
+ }
+ }
+ return valueConverter.getValue(avaValueString, encodingOrder);
}
/**
- * Converts a value in BER encoding, for example given in octothorpe form
- * in a Ldap v3 dn string, to a DerValue. Checks if the BER encoded value
- * is a legal value for the attribute. <p>
+ * Converts a value in BER encoding, for example given in octothorpe form in
+ * a Ldap v3 dn string, to a DerValue. Checks if the BER encoded value is a
+ * legal value for the attribute.
+ * <p>
* <strong><i>NOTE:</i></strong> only DER encoded values are supported for
* the BER encoded value.
- *
- * @param berValue a value in BER encoding
- * @param oid ObjectIdentifier of the attribute.
- *
- * @return DerValue for the BER encoded value
+ *
+ * @param berValue a value in BER encoding
+ * @param oid ObjectIdentifier of the attribute.
+ *
+ * @return DerValue for the BER encoded value
* @exception IOException if an error occurs during conversion.
*/
public DerValue parseAVAValue(byte[] berValue, ObjectIdentifier oid)
- throws IOException
- {
- AVAValueConverter valueConverter = attrMap.getValueConverter(oid);
- if (valueConverter == null && !acceptUnknownOids) {
- throw new IllegalArgumentException(
- "Unrecognized OID for AVA value conversion");
- } else {
- valueConverter = new GenericValueConverter();
- }
- return valueConverter.getValue(berValue);
+ throws IOException {
+ AVAValueConverter valueConverter = attrMap.getValueConverter(oid);
+ if (valueConverter == null && !acceptUnknownOids) {
+ throw new IllegalArgumentException(
+ "Unrecognized OID for AVA value conversion");
+ } else {
+ valueConverter = new GenericValueConverter();
+ }
+ return valueConverter.getValue(berValue);
}
-
//
// public encoding methods.
//
/**
* Converts a X500Name object to a Ldap v3 DN string (except in unicode).
- *
- * @param x500name a X500Name
- *
- * @return a Ldap v3 DN String (except in unicode).
- *
- * @exception IOException if an error is encountered during conversion.
+ *
+ * @param x500name a X500Name
+ *
+ * @return a Ldap v3 DN String (except in unicode).
+ *
+ * @exception IOException if an error is encountered during conversion.
*/
public String encodeDN(X500Name x500name)
- throws IOException
- {
- RDN[] rdns = x500name.getNames();
- // String fullname = null;
- StringBuffer fullname = new StringBuffer();
- String s;
- int i;
- if (rdns.length == 0)
- return "";
- i = rdns.length-1;
- fullname.append(encodeRDN(rdns[i--]));
- while (i >= 0) {
- s = encodeRDN(rdns[i--]);
- fullname.append(",");
- fullname.append(s);
- };
- return fullname.toString();
+ throws IOException {
+ RDN[] rdns = x500name.getNames();
+ // String fullname = null;
+ StringBuffer fullname = new StringBuffer();
+ String s;
+ int i;
+ if (rdns.length == 0)
+ return "";
+ i = rdns.length - 1;
+ fullname.append(encodeRDN(rdns[i--]));
+ while (i >= 0) {
+ s = encodeRDN(rdns[i--]);
+ fullname.append(",");
+ fullname.append(s);
+ }
+ ;
+ return fullname.toString();
}
/**
* Converts a RDN to a Ldap v3 DN string (except in unicode).
- *
- * @param rdn a RDN
- *
- * @return a LDAP v3 DN string (except in unicode).
- *
- * @exception IOException if an error is encountered during conversion.
+ *
+ * @param rdn a RDN
+ *
+ * @return a LDAP v3 DN string (except in unicode).
+ *
+ * @exception IOException if an error is encountered during conversion.
*/
public String encodeRDN(RDN rdn)
- throws IOException
- {
- AVA[] avas = rdn.getAssertion();
- // String relname = null;
- StringBuffer relname = new StringBuffer();
- String s;
- int i=0;
-
- relname.append(encodeAVA(avas[i++]));
- while (i <avas.length) {
- s = encodeAVA(avas[i++]);
- relname.append("+");
- relname.append(s);
- };
- return relname.toString();
+ throws IOException {
+ AVA[] avas = rdn.getAssertion();
+ // String relname = null;
+ StringBuffer relname = new StringBuffer();
+ String s;
+ int i = 0;
+
+ relname.append(encodeAVA(avas[i++]));
+ while (i < avas.length) {
+ s = encodeAVA(avas[i++]);
+ relname.append("+");
+ relname.append(s);
+ }
+ ;
+ return relname.toString();
}
/**
* Converts a AVA to a Ldap v3 DN String (except in unicode).
- *
- * @param ava an AVA
- *
- * @return a Ldap v3 DN string (except in unicode).
- *
- * @exception IOException If an error is encountered during exception.
+ *
+ * @param ava an AVA
+ *
+ * @return a Ldap v3 DN string (except in unicode).
+ *
+ * @exception IOException If an error is encountered during exception.
*/
public String encodeAVA(AVA ava)
- throws IOException
- {
- if(ava == null)
- {
- return "";
+ throws IOException {
+ if (ava == null) {
+ return "";
}
- ObjectIdentifier oid = ava.getOid();
- DerValue value = ava.getValue();
- String keyword, valueStr;
+ ObjectIdentifier oid = ava.getOid();
+ DerValue value = ava.getValue();
+ String keyword, valueStr;
- // get attribute name
+ // get attribute name
- keyword = encodeOID(oid);
- valueStr = encodeValue(value, oid);
+ keyword = encodeOID(oid);
+ valueStr = encodeValue(value, oid);
- return keyword+"="+valueStr;
+ return keyword + "=" + valueStr;
}
/**
- * Converts an OID to a attribute keyword in a Ldap v3 DN string
- * - either a keyword if known or a string of "1.2.3.4" syntax.
- *
- * @param oid a ObjectIdentifier
- *
- * @return a keyword to use in a Ldap V3 DN string.
- *
- * @exception IOException if an error is encountered during conversion.
+ * Converts an OID to a attribute keyword in a Ldap v3 DN string - either a
+ * keyword if known or a string of "1.2.3.4" syntax.
+ *
+ * @param oid a ObjectIdentifier
+ *
+ * @return a keyword to use in a Ldap V3 DN string.
+ *
+ * @exception IOException if an error is encountered during conversion.
*/
public String encodeOID(ObjectIdentifier oid)
- throws IOException
- {
- String keyword = attrMap.getName(oid);
- if (keyword == null) {
- if (acceptUnknownOids)
- keyword = oid.toString();
- else
- throw new IOException("Unknown OID");
- }
- return keyword;
+ throws IOException {
+ String keyword = attrMap.getName(oid);
+ if (keyword == null) {
+ if (acceptUnknownOids)
+ keyword = oid.toString();
+ else
+ throw new IOException("Unknown OID");
+ }
+ return keyword;
}
/**
- * Converts a value as a DerValue to a string in a Ldap V3 DN String.
- * If the value cannot be converted to a string it will be encoded in
- * octothorpe form.
- *
- * @param attrValue a value as a DerValue.
- * @param oid OID for the attribute.
- * @return a string for the value in a LDAP v3 DN String
+ * Converts a value as a DerValue to a string in a Ldap V3 DN String. If the
+ * value cannot be converted to a string it will be encoded in octothorpe
+ * form.
+ *
+ * @param attrValue a value as a DerValue.
+ * @param oid OID for the attribute.
+ * @return a string for the value in a LDAP v3 DN String
* @exception IOException if an error occurs during conversion.
*/
public String encodeValue(DerValue attrValue, ObjectIdentifier oid)
- throws IOException
- {
- /*
- * Construct the value with as little copying and garbage
- * production as practical.
- */
- StringBuffer retval = new StringBuffer (30);
- int i,j;
- String temp = null;
- AVAValueConverter valueConverter;
+ throws IOException {
+ /*
+ * Construct the value with as little copying and garbage production as
+ * practical.
+ */
+ StringBuffer retval = new StringBuffer(30);
+ int i, j;
+ String temp = null;
+ AVAValueConverter valueConverter;
X500NameAttrMap lAttrMap = attrMap;
-
- if(attrValue.tag == DerValue.tag_UTF8String)
- {
+ if (attrValue.tag == DerValue.tag_UTF8String) {
lAttrMap = X500NameAttrMap.getDirDefault();
-
+
+ }
+
+ valueConverter = lAttrMap.getValueConverter(oid);
+ if (valueConverter == null) {
+ if (acceptUnknownOids)
+ valueConverter = new GenericValueConverter();
+ else
+ throw new IOException(
+ "Unknown AVA type for encoding AVA value");
+ }
+
+ try {
+ temp = valueConverter.getAsString(attrValue);
+
+ if (temp == null) {
+ // convert to octothorpe form.
+ byte data[] = attrValue.toByteArray();
+
+ retval.append('#');
+ for (i = 0; i < data.length; i++) {
+ retval.append(hexDigits.charAt((data[i] >> 4) & 0x0f));
+ retval.append(hexDigits.charAt(data[i] & 0x0f));
+ }
+
+ } else {
+
+ retval.append(encodeString(temp));
+
+ }
+ } catch (IOException e) {
+ throw new IllegalArgumentException("malformed AVA DER Value");
}
- valueConverter = lAttrMap.getValueConverter(oid);
- if (valueConverter == null) {
- if (acceptUnknownOids)
- valueConverter = new GenericValueConverter();
- else
- throw new IOException(
- "Unknown AVA type for encoding AVA value");
- }
-
- try {
- temp = valueConverter.getAsString(attrValue);
-
- if (temp == null) {
- // convert to octothorpe form.
- byte data [] = attrValue.toByteArray();
-
- retval.append ('#');
- for (i = 0; i < data.length; i++) {
- retval.append (hexDigits.charAt ((data [i] >> 4) & 0x0f));
- retval.append (hexDigits.charAt (data [i] & 0x0f));
- }
-
- } else {
-
- retval.append(encodeString(temp));
-
- }
- } catch (IOException e) {
- throw new IllegalArgumentException ("malformed AVA DER Value");
- }
-
- return retval.toString ();
+ return retval.toString();
}
/**
* converts a raw value string to a string in Ldap V3 DN string format.
+ *
* @param valueStr a 'raw' value string.
* @return a attribute value string in Ldap V3 DN string format.
*/
- public String encodeString(String valueStr)
- {
- int i,j;
- int len;
- StringBuffer retval = new StringBuffer();
-
- /*
- * generate string according to ldapv3 DN. escaping is used.
- * Strings generated this way are acceptable by rfc1779
- * implementations.
- */
- len = valueStr.length ();
-
- // get index of first space at the end of the string.
- for (j = len-1; j >= 0 && valueStr.charAt(j) == ' '; j--)
- continue;
-
- // escape spaces at the beginning of the string.
- for (i = 0; i <= j && valueStr.charAt(i) == ' '; i++) {
- retval.append('\\');
- retval.append(valueStr.charAt(i));
- }
-
- // escape special characters in the middle of the string.
- for ( ; i <= j ; i++) {
- if (valueStr.charAt(i) == '\\') {
- retval.append('\\');
- retval.append(valueStr.charAt(i));
- } else
- if (specialChars.indexOf(valueStr.charAt(i)) != -1) {
- retval.append('\\');
- retval.append(valueStr.charAt(i));
- } else
- if (valueStr.charAt(i) == '"') {
+ public String encodeString(String valueStr) {
+ int i, j;
+ int len;
+ StringBuffer retval = new StringBuffer();
+
+ /*
+ * generate string according to ldapv3 DN. escaping is used. Strings
+ * generated this way are acceptable by rfc1779 implementations.
+ */
+ len = valueStr.length();
+
+ // get index of first space at the end of the string.
+ for (j = len - 1; j >= 0 && valueStr.charAt(j) == ' '; j--)
+ continue;
+
+ // escape spaces at the beginning of the string.
+ for (i = 0; i <= j && valueStr.charAt(i) == ' '; i++) {
+ retval.append('\\');
+ retval.append(valueStr.charAt(i));
+ }
+
+ // escape special characters in the middle of the string.
+ for (; i <= j; i++) {
+ if (valueStr.charAt(i) == '\\') {
retval.append('\\');
retval.append(valueStr.charAt(i));
- }
- else
- retval.append(valueStr.charAt(i));
- }
+ } else if (specialChars.indexOf(valueStr.charAt(i)) != -1) {
+ retval.append('\\');
+ retval.append(valueStr.charAt(i));
+ } else if (valueStr.charAt(i) == '"') {
+ retval.append('\\');
+ retval.append(valueStr.charAt(i));
+ } else
+ retval.append(valueStr.charAt(i));
+ }
- // esacape spaces at the end.
- for ( ; i < valueStr.length(); i++) {
- retval.append('\\');
- retval.append(' ');
- }
+ // esacape spaces at the end.
+ for (; i < valueStr.length(); i++) {
+ retval.append('\\');
+ retval.append(' ');
+ }
- return retval.toString();
+ return retval.toString();
}
//
@@ -789,22 +746,21 @@ public class LdapV3DNStrConverter extends LdapDNStrConverter
/**
* gets the X500NameAttrMap used by the converter.
+ *
* @return X500NameAttrMap used by this converter.
*/
- public X500NameAttrMap getAttrMap()
- {
- return attrMap;
+ public X500NameAttrMap getAttrMap() {
+ return attrMap;
}
/**
- * returns true if the converter accepts unregistered attributes i.e.
- * OIDS not in the X500NameAttrMap.
- * @return true if converter converts attributes not in the
- * X500NameAttrMap.
+ * returns true if the converter accepts unregistered attributes i.e. OIDS
+ * not in the X500NameAttrMap.
+ *
+ * @return true if converter converts attributes not in the X500NameAttrMap.
*/
- public boolean getAcceptUnknownOids()
- {
- return acceptUnknownOids;
+ public boolean getAcceptUnknownOids() {
+ return acceptUnknownOids;
}
//
@@ -825,56 +781,50 @@ public class LdapV3DNStrConverter extends LdapDNStrConverter
protected static final String octoEndChars = " " + valueEndChars;
/*
- * Values that aren't printable strings are emitted as BER-encoded
- * hex data.
+ * Values that aren't printable strings are emitted as BER-encoded hex data.
*/
protected static final String hexDigits = "0123456789ABCDEFabcdef";
-
/**
* Parse a sequence of hex pairs, each pair a UTF8 byte to a java string.
* For example, "4C75C48D" is "Luc", the last c with caron.
*/
protected static char[] getStringFromHexpairs(char[] hexPairs)
- throws UnsupportedEncodingException
- {
- ByteToCharConverter utf8_bcc;
- byte utf8_buf[];
- char char_buf[];
- int ret;
- int i,j;
-
- try {
- utf8_bcc = ByteToCharConverter.getConverter("UTF8");
- }
- catch (UnsupportedEncodingException e) {
- throw new UnsupportedEncodingException(
- "No UTF8 byte to char converter to use for "+
- "parsing LDAP DN String");
- }
- utf8_bcc.setSubstitutionMode(false);
-
- utf8_buf = new byte[hexPairs.length/2];
- char_buf = new char[utf8_buf.length*utf8_bcc.getMaxCharsPerByte()];
-
- for ( i=0,j=0 ; i < hexPairs.length ; i++,j++ )
- {
- utf8_buf[j] = (byte)
- ((Character.digit( hexPairs[i++], 16 ) << 4) +
- Character.digit( hexPairs[i], 16 ));
- }
- try {
- ret = utf8_bcc.convert( utf8_buf, 0, utf8_buf.length,
- char_buf, 0, char_buf.length );
- }
- catch (java.io.CharConversionException e) {
- throw new IllegalArgumentException(
- "Invalid hex pair in LDAP DN String." );
- }
-
- char [] out_buf = new char[ ret ];
- System.arraycopy( char_buf, 0, out_buf, 0, ret );
- return out_buf;
+ throws UnsupportedEncodingException {
+ ByteToCharConverter utf8_bcc;
+ byte utf8_buf[];
+ char char_buf[];
+ int ret;
+ int i, j;
+
+ try {
+ utf8_bcc = ByteToCharConverter.getConverter("UTF8");
+ } catch (UnsupportedEncodingException e) {
+ throw new UnsupportedEncodingException(
+ "No UTF8 byte to char converter to use for " +
+ "parsing LDAP DN String");
+ }
+ utf8_bcc.setSubstitutionMode(false);
+
+ utf8_buf = new byte[hexPairs.length / 2];
+ char_buf = new char[utf8_buf.length * utf8_bcc.getMaxCharsPerByte()];
+
+ for (i = 0, j = 0; i < hexPairs.length; i++, j++) {
+ utf8_buf[j] = (byte)
+ ((Character.digit(hexPairs[i++], 16) << 4) +
+ Character.digit(hexPairs[i], 16));
+ }
+ try {
+ ret = utf8_bcc.convert(utf8_buf, 0, utf8_buf.length,
+ char_buf, 0, char_buf.length);
+ } catch (java.io.CharConversionException e) {
+ throw new IllegalArgumentException(
+ "Invalid hex pair in LDAP DN String.");
+ }
+
+ char[] out_buf = new char[ret];
+ System.arraycopy(char_buf, 0, out_buf, 0, ret);
+ return out_buf;
}
}
diff --git a/pki/base/util/src/netscape/security/x509/NSCCommentExtension.java b/pki/base/util/src/netscape/security/x509/NSCCommentExtension.java
index bc68dadc..a3e823ac 100644
--- a/pki/base/util/src/netscape/security/x509/NSCCommentExtension.java
+++ b/pki/base/util/src/netscape/security/x509/NSCCommentExtension.java
@@ -16,7 +16,7 @@
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package netscape.security.x509;
-
+
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -32,49 +32,48 @@ import netscape.security.util.PrettyPrintFormat;
/**
* This class defines the NSCCommentExtension
*
- *@author asondhi
- *@see Extension
- *@see CertAttrSet
+ * @author asondhi
+ * @see Extension
+ * @see CertAttrSet
*/
public class NSCCommentExtension extends Extension
-implements CertAttrSet {
+ implements CertAttrSet {
/**
*
*/
private static final long serialVersionUID = 4066287070285105375L;
/**
- * Identifier for this attribute, to be used with the
- * get, set, delete methods of Certificate, x509 type.
+ * Identifier for this attribute, to be used with the get, set, delete
+ * methods of Certificate, x509 type.
*/
public static final String IDENT = "x509.info.extensions.CommentExtension";
/**
* Attribute names.
*/
- public static final String INFOS = "infos";
- public static final ObjectIdentifier OID =
- new ObjectIdentifier("2.16.840.1.113730.1.13");
+ public static final String INFOS = "infos";
+ public static final ObjectIdentifier OID =
+ new ObjectIdentifier("2.16.840.1.113730.1.13");
public String mComment = null;
-
- // Private data members
+ // Private data members
private Vector<Object> mInfos;
private PrettyPrintFormat pp = new PrettyPrintFormat(":");
-
+
// Encode this extension value
private void encodeThis() throws IOException {
DerOutputStream os = new DerOutputStream();
DerOutputStream tmp = new DerOutputStream();
-
- os.putIA5String(mComment);
+
+ os.putIA5String(mComment);
// os.write(DerValue.tag_Sequence,tmp);
- extensionValue = os.toByteArray();
+ extensionValue = os.toByteArray();
}
/**
- * Create a NSCCommentExtension with the Vector of CertificatePolicyInfo.
- *
+ * Create a NSCCommentExtension with the Vector of CertificatePolicyInfo.
+ *
* @param infos the Vector of CertificatePolicyInfo.
*/
public NSCCommentExtension(boolean critical, String comment) throws IOException {
@@ -83,61 +82,63 @@ implements CertAttrSet {
this.critical = critical;
encodeThis();
}
-
+
/**
* Create a default NSCCommentExtension.
*/
- public NSCCommentExtension(boolean critical) {
+ public NSCCommentExtension(boolean critical) {
this.extensionId = new ObjectIdentifier("2.16.840.1.113730.1.13");
this.critical = critical;
- mInfos = new Vector<Object>(1,1);
+ mInfos = new Vector<Object>(1, 1);
}
/**
* Create the extension from the passed DER encoded value.
- *
+ *
* @param critical true if the extension is to be treated as critical.
* @param value Array of DER encoded bytes of the actual value.
* @exception IOException on error.
*/
public NSCCommentExtension(Boolean critical, Object value)
- throws IOException {
- this.extensionId = new ObjectIdentifier("2.16.840.1.113730.1.13");
+ throws IOException {
+ this.extensionId = new ObjectIdentifier("2.16.840.1.113730.1.13");
this.critical = critical.booleanValue();
-
+
int len = Array.getLength(value);
- byte [] extValue = new byte[len];
+ byte[] extValue = new byte[len];
for (int i = 0; i < len; i++) {
- extValue[i] = Array.getByte(value, i);
+ extValue[i] = Array.getByte(value, i);
}
this.extensionValue = extValue;
DerValue val = new DerValue(extValue);
- mComment = val.getIA5String();
+ mComment = val.getIA5String();
}
/**
* Returns a printable representation of the policy extension.
*/
public String toString() {
- if (mInfos == null) return "";
+ if (mInfos == null)
+ return "";
String s = super.toString() + "Netscape Comment [\n"
+ mInfos.toString() + "]\n";
-
+
return (s);
}
-
+
public String toPrint(int indent) {
String s;
- s = "Comment :\n" + pp.indent(indent+4) +
- ((mComment == null) ? "" : mComment.trim()) + "\n";
-
+ s = "Comment :\n" + pp.indent(indent + 4) +
+ ((mComment == null) ? "" : mComment.trim()) + "\n";
+
return (s);
}
+
/**
* Write the extension to the OutputStream.
- *
+ *
* @param out the OutputStream to write the extension to.
* @exception IOException on encoding errors.
*/
@@ -154,14 +155,14 @@ implements CertAttrSet {
/**
* Decode the extension from the InputStream.
- *
+ *
* @param in the InputStream to unmarshal the contents from.
* @exception IOException on decoding or validity errors.
*/
public void decode(InputStream in) throws IOException {
throw new IOException("Method not to be called directly.");
}
-
+
public String getComment() {
return mComment;
}
@@ -170,20 +171,20 @@ implements CertAttrSet {
* Set the attribute value.
*/
@SuppressWarnings("unchecked")
- public void set(String name, Object obj) throws IOException {
+ public void set(String name, Object obj) throws IOException {
clearValue();
if (name.equalsIgnoreCase(INFOS)) {
if (!(obj instanceof Vector)) {
- throw new IOException("Attribute value should be of" +
+ throw new IOException("Attribute value should be of" +
" type Vector.");
}
- mInfos = (Vector<Object>)obj;
+ mInfos = (Vector<Object>) obj;
} else {
- throw new IOException("Attribute name not recognized by " +
+ throw new IOException("Attribute name not recognized by " +
"CertAttrSet:NSCCommentExtension.");
}
}
-
+
/**
* Get the attribute value.
*/
@@ -191,11 +192,11 @@ implements CertAttrSet {
if (name.equalsIgnoreCase(INFOS)) {
return (mInfos);
} else {
- throw new IOException("Attribute name not recognized by " +
+ throw new IOException("Attribute name not recognized by " +
"CertAttrSet:NSCCommentExtension.");
}
}
-
+
/**
* Delete the attribute value.
*/
@@ -203,20 +204,19 @@ implements CertAttrSet {
if (name.equalsIgnoreCase(INFOS)) {
mInfos = null;
} else {
- throw new IOException("Attribute name not recognized by " +
+ throw new IOException("Attribute name not recognized by " +
"CertAttrSet:NSCCommentExtension.");
}
}
-
+
/**
* Return an enumeration of names of attributes existing within this
* attribute.
*/
- public Enumeration<String> getAttributeNames () {
+ public Enumeration<String> getAttributeNames() {
Vector<String> elements = new Vector<String>();
elements.addElement(INFOS);
return (elements.elements());
}
-
}
diff --git a/pki/base/util/src/netscape/security/x509/NameConstraintsExtension.java b/pki/base/util/src/netscape/security/x509/NameConstraintsExtension.java
index c7928b85..08b6b7b3 100644
--- a/pki/base/util/src/netscape/security/x509/NameConstraintsExtension.java
+++ b/pki/base/util/src/netscape/security/x509/NameConstraintsExtension.java
@@ -28,18 +28,18 @@ import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
import netscape.security.util.PrettyPrintFormat;
-
/**
* This class defines the Name Constraints Extension.
* <p>
- * The name constraints extension provides permitted and excluded
- * subtrees that place restrictions on names that may be included within
- * a certificate issued by a given CA. Restrictions may apply to the
- * subject distinguished name or subject alternative names. Any name
- * matching a restriction in the excluded subtrees field is invalid
- * regardless of information appearing in the permitted subtrees.
+ * The name constraints extension provides permitted and excluded subtrees that
+ * place restrictions on names that may be included within a certificate issued
+ * by a given CA. Restrictions may apply to the subject distinguished name or
+ * subject alternative names. Any name matching a restriction in the excluded
+ * subtrees field is invalid regardless of information appearing in the
+ * permitted subtrees.
* <p>
* The ASN.1 syntax for this is:
+ *
* <pre>
* NameConstraints ::= SEQUENCE {
* permittedSubtrees [0] GeneralSubtrees OPTIONAL,
@@ -52,7 +52,7 @@ import netscape.security.util.PrettyPrintFormat;
* maximum [1] BaseDistance OPTIONAL }
* BaseDistance ::== INTEGER (0..MAX)
* </pre>
- *
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.10
@@ -60,15 +60,15 @@ import netscape.security.util.PrettyPrintFormat;
* @see CertAttrSet
*/
public class NameConstraintsExtension extends Extension
-implements CertAttrSet {
+ implements CertAttrSet {
/**
*
*/
private static final long serialVersionUID = -3506940192931244539L;
/**
- * Identifier for this attribute, to be used with the
- * get, set, delete methods of Certificate, x509 type.
- */
+ * Identifier for this attribute, to be used with the get, set, delete
+ * methods of Certificate, x509 type.
+ */
public static final String IDENT = "x509.info.extensions.NameConstraints";
/**
* Attribute names.
@@ -80,8 +80,8 @@ implements CertAttrSet {
private static final byte TAG_PERMITTED = 0;
private static final byte TAG_EXCLUDED = 1;
- private GeneralSubtrees permitted;
- private GeneralSubtrees excluded;
+ private GeneralSubtrees permitted;
+ private GeneralSubtrees excluded;
private PrettyPrintFormat pp = new PrettyPrintFormat(":");
@@ -90,13 +90,13 @@ implements CertAttrSet {
DerOutputStream seq = new DerOutputStream();
DerOutputStream tagged = new DerOutputStream();
- if ((permitted != null) &&(permitted.getSubtrees().size()>0)) {
+ if ((permitted != null) && (permitted.getSubtrees().size() > 0)) {
DerOutputStream tmp = new DerOutputStream();
permitted.encode(tmp);
tagged.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
true, TAG_PERMITTED), tmp);
}
- if ((excluded != null) && (excluded.getSubtrees().size()>0)) {
+ if ((excluded != null) && (excluded.getSubtrees().size() > 0)) {
DerOutputStream tmp = new DerOutputStream();
excluded.encode(tmp);
tagged.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
@@ -111,28 +111,27 @@ implements CertAttrSet {
}
/**
- * The default constructor for this class. Either parameter
- * can be set to null to indicate it is omitted but both
- * cannot be null.
- *
+ * The default constructor for this class. Either parameter can be set to
+ * null to indicate it is omitted but both cannot be null.
+ *
* @param permitted the permitted GeneralSubtrees (null for optional).
* @param excluded the excluded GeneralSubtrees (null for optional).
*/
public NameConstraintsExtension(GeneralSubtrees permitted,
GeneralSubtrees excluded)
- throws IOException {
- init(false, permitted, excluded);
+ throws IOException {
+ init(false, permitted, excluded);
}
- public NameConstraintsExtension(boolean critical,
- GeneralSubtrees permitted, GeneralSubtrees excluded)
- throws IOException {
- init(critical, permitted, excluded);
+ public NameConstraintsExtension(boolean critical,
+ GeneralSubtrees permitted, GeneralSubtrees excluded)
+ throws IOException {
+ init(critical, permitted, excluded);
}
- private void init(boolean critical,
- GeneralSubtrees permitted, GeneralSubtrees excluded)
- throws IOException {
+ private void init(boolean critical,
+ GeneralSubtrees permitted, GeneralSubtrees excluded)
+ throws IOException {
if (permitted == null && excluded == null) {
throw new IOException("NameConstraints: Invalid arguments");
}
@@ -146,13 +145,13 @@ implements CertAttrSet {
/**
* Create the extension from the passed DER encoded value.
- *
+ *
* @param critical true if the extension is to be treated as critical.
* @param value Array of DER encoded bytes of the actual value.
* @exception IOException on error.
*/
public NameConstraintsExtension(Boolean critical, Object value)
- throws IOException {
+ throws IOException {
this.extensionId = PKIXExtensions.NameConstraints_Id;
this.critical = critical.booleanValue();
@@ -160,7 +159,7 @@ implements CertAttrSet {
throw new IOException("Illegal argument type");
int len = Array.getLength(value);
- byte[] extValue = new byte[len];
+ byte[] extValue = new byte[len];
System.arraycopy(value, 0, extValue, 0, len);
this.extensionValue = extValue;
@@ -177,26 +176,26 @@ implements CertAttrSet {
DerValue opt = val.data.getDerValue();
if (opt.isContextSpecific(TAG_PERMITTED) && opt.isConstructed()) {
- if (permitted != null) {
- throw new IOException("Duplicate permitted " +
- "GeneralSubtrees in NameConstraintsExtension.");
- }
+ if (permitted != null) {
+ throw new IOException("Duplicate permitted " +
+ "GeneralSubtrees in NameConstraintsExtension.");
+ }
opt.resetTag(DerValue.tag_Sequence);
- permitted = new GeneralSubtrees(opt);
+ permitted = new GeneralSubtrees(opt);
} else if (opt.isContextSpecific(TAG_EXCLUDED) &&
opt.isConstructed()) {
- if (excluded != null) {
- throw new IOException("Duplicate excluded " +
+ if (excluded != null) {
+ throw new IOException("Duplicate excluded " +
"GeneralSubtrees in NameConstraintsExtension.");
- }
+ }
opt.resetTag(DerValue.tag_Sequence);
- excluded = new GeneralSubtrees(opt);
+ excluded = new GeneralSubtrees(opt);
} else
- throw new IOException("Invalid encoding of " +
+ throw new IOException("Invalid encoding of " +
"NameConstraintsExtension.");
- }
}
+ }
/**
* Return the printable string.
@@ -204,24 +203,23 @@ implements CertAttrSet {
public String toString() {
return (super.toString() + "NameConstraints: [" +
((permitted == null) ? "" :
- ("\n Permitted:" + permitted.toString())) +
+ ("\n Permitted:" + permitted.toString())) +
((excluded == null) ? "" :
- ("\n Excluded:" + excluded.toString()))
- + " ]\n");
+ ("\n Excluded:" + excluded.toString())) + " ]\n");
}
public String toPrint(int indent) {
- return ("GeneralSubtrees: "+
- ((permitted == null) ? "" :
- ("\n"+pp.indent(indent+2)+"Permitted:" + permitted.toPrint(indent+4))) +
- ((excluded == null) ? "" :
- ("\n"+pp.indent(indent+2)+"Excluded:" + excluded.toPrint(indent+4))) + "\n");
+ return ("GeneralSubtrees: " +
+ ((permitted == null) ? "" :
+ ("\n" + pp.indent(indent + 2) + "Permitted:" + permitted.toPrint(indent + 4))) +
+ ((excluded == null) ? "" :
+ ("\n" + pp.indent(indent + 2) + "Excluded:" + excluded.toPrint(indent + 4))) + "\n");
}
/**
* Decode the extension from the InputStream.
- *
+ *
* @param in the InputStream to unmarshal the contents from.
* @exception IOException on decoding or validity errors.
*/
@@ -231,7 +229,7 @@ implements CertAttrSet {
/**
* Write the extension to the OutputStream.
- *
+ *
* @param out the OutputStream to write the extension to.
* @exception IOException on encoding errors.
*/
@@ -242,7 +240,7 @@ implements CertAttrSet {
encodeThis();
}
super.encode(tmp);
- out.write(tmp.toByteArray());
+ out.write(tmp.toByteArray());
}
/**
@@ -250,62 +248,62 @@ implements CertAttrSet {
*/
public void set(String name, Object obj) throws IOException {
clearValue();
- if (name.equalsIgnoreCase(PERMITTED_SUBTREES)) {
- if (!(obj instanceof GeneralSubtrees)) {
- throw new IOException("Attribute value should be"
+ if (name.equalsIgnoreCase(PERMITTED_SUBTREES)) {
+ if (!(obj instanceof GeneralSubtrees)) {
+ throw new IOException("Attribute value should be"
+ " of type GeneralSubtrees.");
- }
- permitted = (GeneralSubtrees)obj;
- } else if (name.equalsIgnoreCase(EXCLUDED_SUBTREES)) {
- if (!(obj instanceof GeneralSubtrees)) {
- throw new IOException("Attribute value should be "
+ }
+ permitted = (GeneralSubtrees) obj;
+ } else if (name.equalsIgnoreCase(EXCLUDED_SUBTREES)) {
+ if (!(obj instanceof GeneralSubtrees)) {
+ throw new IOException("Attribute value should be "
+ "of type GeneralSubtrees.");
- }
- excluded = (GeneralSubtrees)obj;
- } else {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:NameConstraintsExtension.");
- }
+ }
+ excluded = (GeneralSubtrees) obj;
+ } else {
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:NameConstraintsExtension.");
+ }
}
/**
* Get the attribute value.
*/
public Object get(String name) throws IOException {
- if (name.equalsIgnoreCase(PERMITTED_SUBTREES)) {
- return (permitted);
- } else if (name.equalsIgnoreCase(EXCLUDED_SUBTREES)) {
- return (excluded);
- } else {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:NameConstraintsExtension.");
- }
+ if (name.equalsIgnoreCase(PERMITTED_SUBTREES)) {
+ return (permitted);
+ } else if (name.equalsIgnoreCase(EXCLUDED_SUBTREES)) {
+ return (excluded);
+ } else {
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:NameConstraintsExtension.");
+ }
}
/**
* Delete the attribute value.
*/
public void delete(String name) throws IOException {
- if (name.equalsIgnoreCase(PERMITTED_SUBTREES)) {
- permitted = null;
- } else if (name.equalsIgnoreCase(EXCLUDED_SUBTREES)) {
- excluded = null;
- } else {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:NameConstraintsExtension.");
- }
+ if (name.equalsIgnoreCase(PERMITTED_SUBTREES)) {
+ permitted = null;
+ } else if (name.equalsIgnoreCase(EXCLUDED_SUBTREES)) {
+ excluded = null;
+ } else {
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:NameConstraintsExtension.");
+ }
}
/**
* Return an enumeration of names of attributes existing within this
* attribute.
*/
- public Enumeration<String> getAttributeNames () {
+ public Enumeration<String> getAttributeNames() {
Vector<String> elements = new Vector<String>();
elements.addElement(PERMITTED_SUBTREES);
elements.addElement(EXCLUDED_SUBTREES);
- return (elements.elements());
+ return (elements.elements());
}
}
diff --git a/pki/base/util/src/netscape/security/x509/NoticeReference.java b/pki/base/util/src/netscape/security/x509/NoticeReference.java
index 9c232f3c..07a22a90 100644
--- a/pki/base/util/src/netscape/security/x509/NoticeReference.java
+++ b/pki/base/util/src/netscape/security/x509/NoticeReference.java
@@ -24,15 +24,12 @@ import netscape.security.util.BigInt;
import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
-
/**
* Represent the NoticeReference.
- *
- * NoticeReference ::= SEQUENCE {
- * organization DisplayText,
- * noticeNumbers SEQUENCE OF INTEGER
- * }
- *
+ *
+ * NoticeReference ::= SEQUENCE { organization DisplayText, noticeNumbers
+ * SEQUENCE OF INTEGER }
+ *
* @author Thomas Kwan
*/
public class NoticeReference {
@@ -41,8 +38,8 @@ public class NoticeReference {
private int mNumbers[] = null;
public NoticeReference(DisplayText org, int numbers[]) {
- mOrg = org;
- mNumbers = numbers;
+ mOrg = org;
+ mNumbers = numbers;
}
public NoticeReference(DerValue val) throws IOException {
@@ -54,32 +51,31 @@ public class NoticeReference {
if (integers.tag != DerValue.tag_Sequence) {
throw new IOException("Invalid encoding for NoticeReference (integers)");
}
- Vector<BigInt> num = new Vector<BigInt>();
+ Vector<BigInt> num = new Vector<BigInt>();
while (integers.data.available() != 0) {
- DerValue i = integers.data.getDerValue();
- BigInt bigI = i.getInteger();
- num.addElement(bigI);
- }
- if (num.size() <= 0)
- return;
- mNumbers = new int[num.size()];
- for (int i = 0; i < num.size(); i++) {
- mNumbers[i] = num.elementAt(i).toInt();
- }
+ DerValue i = integers.data.getDerValue();
+ BigInt bigI = i.getInteger();
+ num.addElement(bigI);
+ }
+ if (num.size() <= 0)
+ return;
+ mNumbers = new int[num.size()];
+ for (int i = 0; i < num.size(); i++) {
+ mNumbers[i] = num.elementAt(i).toInt();
+ }
}
- public DisplayText getOrganization()
- {
- return mOrg;
+ public DisplayText getOrganization() {
+ return mOrg;
}
public int[] getNumbers() {
- return mNumbers;
+ return mNumbers;
}
/**
* Write the NoticeReference to the DerOutputStream.
- *
+ *
* @param out the DerOutputStream to write the object to.
* @exception IOException on errors.
*/
@@ -87,10 +83,10 @@ public class NoticeReference {
DerOutputStream tmp = new DerOutputStream();
mOrg.encode(tmp);
DerOutputStream iseq = new DerOutputStream();
- for (int i = 0; i < mNumbers.length; i++) {
- iseq.putInteger(new BigInt(mNumbers[i]));
- }
- tmp.write(DerValue.tag_Sequence,iseq);
- out.write(DerValue.tag_Sequence,tmp);
+ for (int i = 0; i < mNumbers.length; i++) {
+ iseq.putInteger(new BigInt(mNumbers[i]));
+ }
+ tmp.write(DerValue.tag_Sequence, iseq);
+ out.write(DerValue.tag_Sequence, tmp);
}
}
diff --git a/pki/base/util/src/netscape/security/x509/OIDMap.java b/pki/base/util/src/netscape/security/x509/OIDMap.java
index 97e8d26e..02fe8b96 100644
--- a/pki/base/util/src/netscape/security/x509/OIDMap.java
+++ b/pki/base/util/src/netscape/security/x509/OIDMap.java
@@ -28,10 +28,10 @@ import java.util.Properties;
import netscape.security.util.ObjectIdentifier;
/**
- * This class defines the mapping from OID & name to classes and vice
- * versa. Used by CertificateExtensions & PKCS10 to get the java
- * classes associated with a particular OID/name.
- *
+ * This class defines the mapping from OID & name to classes and vice versa.
+ * Used by CertificateExtensions & PKCS10 to get the java classes associated
+ * with a particular OID/name.
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.12
@@ -39,16 +39,14 @@ import netscape.security.util.ObjectIdentifier;
public class OIDMap {
/**
- * Location for where the OID/Classes maps are stored on
- * the local system.
+ * Location for where the OID/Classes maps are stored on the local system.
*/
public static final String EXTENSIONS_HOME =
- (System.getProperty("java.home") + File.separator + "lib"
- + File.separator + "security" + File.separator + "cert"
- + File.separator);
+ (System.getProperty("java.home") + File.separator + "lib"
+ + File.separator + "security" + File.separator + "cert"
+ + File.separator);
/**
- * File names for where OIDs and Classes are registered
- * for V3 extensions.
+ * File names for where OIDs and Classes are registered for V3 extensions.
*/
public static final String EXTENSIONS_OIDS = "x509extensions.oid";
public static final String EXTENSIONS_CLASSES = "x509extensions.classes";
@@ -59,36 +57,36 @@ public class OIDMap {
X509CertInfo.EXTENSIONS;
private static final String AUTH_KEY_IDENTIFIER = ROOT + "." +
AuthorityKeyIdentifierExtension.class.getSimpleName();
- private static final String SUB_KEY_IDENTIFIER = ROOT + "." +
+ private static final String SUB_KEY_IDENTIFIER = ROOT + "." +
SubjectKeyIdentifierExtension.class.getSimpleName();
- private static final String KEY_USAGE = ROOT + "." +
+ private static final String KEY_USAGE = ROOT + "." +
KeyUsageExtension.class.getSimpleName();
- private static final String PRIVATE_KEY_USAGE = ROOT + "." +
+ private static final String PRIVATE_KEY_USAGE = ROOT + "." +
PrivateKeyUsageExtension.class.getSimpleName();
- private static final String POLICY_MAPPINGS = ROOT + "." +
+ private static final String POLICY_MAPPINGS = ROOT + "." +
PolicyMappingsExtension.class.getSimpleName();
- private static final String SUB_ALT_NAME = ROOT + "." +
+ private static final String SUB_ALT_NAME = ROOT + "." +
SubjectAlternativeNameExtension.class.getSimpleName();
- private static final String ISSUER_ALT_NAME = ROOT + "." +
+ private static final String ISSUER_ALT_NAME = ROOT + "." +
IssuerAlternativeNameExtension.class.getSimpleName();
- private static final String BASIC_CONSTRAINTS = ROOT + "." +
+ private static final String BASIC_CONSTRAINTS = ROOT + "." +
BasicConstraintsExtension.class.getSimpleName();
- private static final String NAME_CONSTRAINTS = ROOT + "." +
+ private static final String NAME_CONSTRAINTS = ROOT + "." +
NameConstraintsExtension.class.getSimpleName();
- private static final String POLICY_CONSTRAINTS = ROOT + "." +
+ private static final String POLICY_CONSTRAINTS = ROOT + "." +
PolicyConstraintsExtension.class.getSimpleName();
- private static final String CERT_POLICIES = //ROOT + "." +
- CertificatePoliciesExtension.class.getSimpleName();
- private static final String SUBJ_DIR_ATTR = //ROOT + "." +
- SubjectDirAttributesExtension.class.getSimpleName();
+ private static final String CERT_POLICIES = // ROOT + "." +
+ CertificatePoliciesExtension.class.getSimpleName();
+ private static final String SUBJ_DIR_ATTR = // ROOT + "." +
+ SubjectDirAttributesExtension.class.getSimpleName();
public static final String EXT_KEY_USAGE_NAME = "ExtendedKeyUsageExtension";
public static final String EXT_INHIBIT_ANY_POLICY_NAME = "InhibitAnyPolicyExtension";
- private static final String EXT_KEY_USAGE = //ROOT + "." +
- EXT_KEY_USAGE_NAME;
+ private static final String EXT_KEY_USAGE = // ROOT + "." +
+ EXT_KEY_USAGE_NAME;
- private static final String CRL_NUMBER = ROOT + "." +
+ private static final String CRL_NUMBER = ROOT + "." +
CRLNumberExtension.class.getSimpleName();
- private static final String CRL_REASON = ROOT + "." +
+ private static final String CRL_REASON = ROOT + "." +
CRLReasonExtension.class.getSimpleName();
private static final Hashtable<ObjectIdentifier, String> oid2Name = new Hashtable<ObjectIdentifier, String>();
@@ -103,25 +101,25 @@ public class OIDMap {
// Load the default name to oid map (EXTENSIONS_OIDS)
private static void loadNamesDefault(Properties props) {
- props.put(SUB_KEY_IDENTIFIER,"2.5.29.14");
- props.put(KEY_USAGE,"2.5.29.15");
- props.put(PRIVATE_KEY_USAGE,"2.5.29.16");
- props.put(SUB_ALT_NAME,"2.5.29.17");
- props.put(ISSUER_ALT_NAME,"2.5.29.18");
- props.put(BASIC_CONSTRAINTS,"2.5.29.19");
- props.put(CRL_NUMBER,"2.5.29.20");
- props.put(CRL_REASON,"2.5.29.21");
- props.put(NAME_CONSTRAINTS,"2.5.29.30");
- props.put(POLICY_MAPPINGS,"2.5.29.33");
- props.put(POLICY_CONSTRAINTS,"2.5.29.36");
- props.put(CERT_POLICIES,"2.5.29.32");
- props.put(AUTH_KEY_IDENTIFIER,"2.5.29.35");
- props.put(SUBJ_DIR_ATTR,"2.5.29.9");
- props.put(EXT_KEY_USAGE,"2.5.29.37");
+ props.put(SUB_KEY_IDENTIFIER, "2.5.29.14");
+ props.put(KEY_USAGE, "2.5.29.15");
+ props.put(PRIVATE_KEY_USAGE, "2.5.29.16");
+ props.put(SUB_ALT_NAME, "2.5.29.17");
+ props.put(ISSUER_ALT_NAME, "2.5.29.18");
+ props.put(BASIC_CONSTRAINTS, "2.5.29.19");
+ props.put(CRL_NUMBER, "2.5.29.20");
+ props.put(CRL_REASON, "2.5.29.21");
+ props.put(NAME_CONSTRAINTS, "2.5.29.30");
+ props.put(POLICY_MAPPINGS, "2.5.29.33");
+ props.put(POLICY_CONSTRAINTS, "2.5.29.36");
+ props.put(CERT_POLICIES, "2.5.29.32");
+ props.put(AUTH_KEY_IDENTIFIER, "2.5.29.35");
+ props.put(SUBJ_DIR_ATTR, "2.5.29.9");
+ props.put(EXT_KEY_USAGE, "2.5.29.37");
}
// Load the default name to class map (EXTENSIONS_CLASSES)
- private static void loadClassDefault (Properties props) {
+ private static void loadClassDefault(Properties props) {
props.put(AUTH_KEY_IDENTIFIER,
"netscape.security.x509.AuthorityKeyIdentifierExtension");
props.put(SUB_KEY_IDENTIFIER,
@@ -153,7 +151,7 @@ public class OIDMap {
}
// Return the file along with location
- private static File certificatePropFile (String fileName) {
+ private static File certificatePropFile(String fileName) {
return (new File(EXTENSIONS_HOME + fileName));
}
@@ -166,11 +164,11 @@ public class OIDMap {
loadNamesDefault(props);
} else {
try {
- FileInputStream fis = new FileInputStream(namesMap);
- props.load(fis);
+ FileInputStream fis = new FileInputStream(namesMap);
+ props.load(fis);
fis.close();
} catch (IOException e) {
- loadNamesDefault(props);
+ loadNamesDefault(props);
}
}
@@ -194,10 +192,10 @@ public class OIDMap {
loadClassDefault(props);
} else {
try {
- FileInputStream fis = new FileInputStream(classMap);
- props.load(fis);
+ FileInputStream fis = new FileInputStream(classMap);
+ props.load(fis);
} catch (IOException e) {
- loadClassDefault(props);
+ loadClassDefault(props);
}
}
@@ -212,92 +210,92 @@ public class OIDMap {
/**
* Add a name to lookup table.
- *
- * @param className the name of the fully qualified class implementing
- * the asn object.
- * @param oid the string representation of the object identifier for
- * the class.
+ *
+ * @param className the name of the fully qualified class implementing the
+ * asn object.
+ * @param oid the string representation of the object identifier for the
+ * class.
* @param name the name of the attribute.
* @exception CertificateException on errors.
*/
public static void addAttribute(String className, String oid, String name)
- throws CertificateException {
+ throws CertificateException {
ObjectIdentifier objId = new ObjectIdentifier(oid);
- if (oid2Name.get(objId) != null) {
- throw new CertificateException("Object identifier already exists.");
- }
- if (name2OID.get(name) != null) {
- throw new CertificateException("Name already exists.");
- }
- if (name2Class.get(className) != null) {
- throw new CertificateException("Class already exists.");
- }
- oid2Name.put(objId, name);
- name2OID.put(name, objId);
- name2Class.put(name, className);
+ if (oid2Name.get(objId) != null) {
+ throw new CertificateException("Object identifier already exists.");
+ }
+ if (name2OID.get(name) != null) {
+ throw new CertificateException("Name already exists.");
+ }
+ if (name2Class.get(className) != null) {
+ throw new CertificateException("Class already exists.");
+ }
+ oid2Name.put(objId, name);
+ name2OID.put(name, objId);
+ name2Class.put(name, className);
}
/**
* Return user friendly name associated with the OID.
- *
+ *
* @param oid the name of the object identifier to be returned.
- * @return the user friendly name or null if no name
- * is registered for this oid.
+ * @return the user friendly name or null if no name is registered for this
+ * oid.
*/
public static String getName(ObjectIdentifier oid) {
- return (String)oid2Name.get(oid);
- }
+ return (String) oid2Name.get(oid);
+ }
/**
* Return Object identifier for user friendly name.
- *
+ *
* @param name the user friendly name.
- * @return the Object Identifier or null if no oid
- * is registered for this name.
+ * @return the Object Identifier or null if no oid is registered for this
+ * name.
*/
public static ObjectIdentifier getOID(String name) {
- return (ObjectIdentifier)name2OID.get(name);
- }
+ return (ObjectIdentifier) name2OID.get(name);
+ }
/**
* Return the java class object associated with the user friendly name.
- *
+ *
* @param name the user friendly name.
* @exception CertificateException if class cannot be instantiated.
*/
public static Class<?> getClass(String name) throws CertificateException {
- String className = (String)name2Class.get(name);
+ String className = (String) name2Class.get(name);
if (className == null)
return null;
try {
Class<?> extClass = Class.forName(className);
- return (extClass);
- } catch (Exception e) {
- throw new CertificateException("Error instantiating class for "
+ return (extClass);
+ } catch (Exception e) {
+ throw new CertificateException("Error instantiating class for "
+ name + " " + e.toString());
- }
+ }
}
/**
* Return the java class object associated with the object identifier..
- *
+ *
* @param oid the name of the object identifier to be returned.
* @exception CertificateException if class cannot be instatiated.
*/
public static Class<?> getClass(ObjectIdentifier oid)
- throws CertificateException {
+ throws CertificateException {
String name = getName(oid);
if (name == null)
return null;
- String className = (String)name2Class.get(name);
+ String className = (String) name2Class.get(name);
if (className == null)
return null;
try {
Class<?> extClass = Class.forName(className);
- return (extClass);
- } catch (Exception e) {
- throw new CertificateException("Error instantiating class for "
+ return (extClass);
+ } catch (Exception e) {
+ throw new CertificateException("Error instantiating class for "
+ name + " " + e.toString());
- }
+ }
}
}
diff --git a/pki/base/util/src/netscape/security/x509/OIDName.java b/pki/base/util/src/netscape/security/x509/OIDName.java
index 61d44771..fe96225a 100644
--- a/pki/base/util/src/netscape/security/x509/OIDName.java
+++ b/pki/base/util/src/netscape/security/x509/OIDName.java
@@ -24,9 +24,9 @@ import netscape.security.util.DerValue;
import netscape.security.util.ObjectIdentifier;
/**
- * This class implements the OIDName as required by the GeneralNames
- * ASN.1 object.
- *
+ * This class implements the OIDName as required by the GeneralNames ASN.1
+ * object.
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.3
@@ -35,7 +35,7 @@ import netscape.security.util.ObjectIdentifier;
* @see GeneralNameInterface
*/
public class OIDName implements GeneralNameInterface {
- /**
+ /**
*
*/
private static final long serialVersionUID = 9198510631835117121L;
@@ -43,7 +43,7 @@ public class OIDName implements GeneralNameInterface {
/**
* Create the OIDName object from the passed encoded Der value.
- *
+ *
* @param derValue the encoded DER OIDName.
* @exception IOException on error.
*/
@@ -53,7 +53,7 @@ public class OIDName implements GeneralNameInterface {
/**
* Create the OIDName object with the specified name.
- *
+ *
* @param name the OIDName.
*/
public OIDName(ObjectIdentifier oid) {
@@ -61,7 +61,7 @@ public class OIDName implements GeneralNameInterface {
}
public OIDName(String oid) {
- this.oid = new ObjectIdentifier(oid);
+ this.oid = new ObjectIdentifier(oid);
}
/**
@@ -73,7 +73,7 @@ public class OIDName implements GeneralNameInterface {
/**
* Encode the OID name into the DerOutputStream.
- *
+ *
* @param out the DER stream to encode the OIDName to.
* @exception IOException on encoding errors.
*/
diff --git a/pki/base/util/src/netscape/security/x509/OtherName.java b/pki/base/util/src/netscape/security/x509/OtherName.java
index c4815bb2..1052d57d 100644
--- a/pki/base/util/src/netscape/security/x509/OtherName.java
+++ b/pki/base/util/src/netscape/security/x509/OtherName.java
@@ -25,20 +25,18 @@ import netscape.security.util.DerValue;
import netscape.security.util.ObjectIdentifier;
/**
- * This class implements the OtherName as required by the GeneralNames
- * ASN.1 object.
- *
- * OtherName ::= SEQUENCE {
- * type-id OBJECT IDENTIFIER,
- * value [0] EXPLICIT ANY DEFINED BY type-id
- * }
- *
+ * This class implements the OtherName as required by the GeneralNames ASN.1
+ * object.
+ *
+ * OtherName ::= SEQUENCE { type-id OBJECT IDENTIFIER, value [0] EXPLICIT ANY
+ * DEFINED BY type-id }
+ *
* @see GeneralName
* @see GeneralNameInterface
* @see GeneralNames
- *
+ *
* @version 1.2
- *
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
*/
@@ -52,7 +50,7 @@ public class OtherName implements GeneralNameInterface {
/**
* Create the IPAddressName object from the passed encoded Der value.
- *
+ *
* @param derValue the encoded DER IPAddressName.
* @exception IOException on error.
*/
@@ -61,61 +59,60 @@ public class OtherName implements GeneralNameInterface {
}
public OtherName(ObjectIdentifier oid, byte data[]) {
- mOID = oid;
- DerOutputStream dos = new DerOutputStream();
- try {
- dos.putDerValue(new DerValue(data));
- } catch (IOException e) {
- }
- mData = dos.toByteArray();
+ mOID = oid;
+ DerOutputStream dos = new DerOutputStream();
+ try {
+ dos.putDerValue(new DerValue(data));
+ } catch (IOException e) {
+ }
+ mData = dos.toByteArray();
}
/**
* Constructs a string-based other name.
*/
public OtherName(ObjectIdentifier oid, byte tag, String value) {
- mOID = oid;
- DerOutputStream dos = new DerOutputStream();
- try {
- if (tag == DerValue.tag_PrintableString) {
- dos.putPrintableString(value);
- } else if (tag == DerValue.tag_IA5String) {
- dos.putIA5String(value);
- } else if (tag == DerValue.tag_BMPString) {
- dos.putBMPString(value);
- } else if (tag == DerValue.tag_UTF8String) {
- dos.putUTF8String(value);
+ mOID = oid;
+ DerOutputStream dos = new DerOutputStream();
+ try {
+ if (tag == DerValue.tag_PrintableString) {
+ dos.putPrintableString(value);
+ } else if (tag == DerValue.tag_IA5String) {
+ dos.putIA5String(value);
+ } else if (tag == DerValue.tag_BMPString) {
+ dos.putBMPString(value);
+ } else if (tag == DerValue.tag_UTF8String) {
+ dos.putUTF8String(value);
+ }
+ } catch (IOException e) {
}
- } catch (IOException e) {
- }
- mData = dos.toByteArray();
+ mData = dos.toByteArray();
}
public OtherName(ObjectIdentifier oid, String value) {
- mOID = oid;
- DerOutputStream dos = new DerOutputStream();
- try {
- dos.putPrintableString(value);
- } catch (IOException e) {
- }
- mData = dos.toByteArray();
+ mOID = oid;
+ DerOutputStream dos = new DerOutputStream();
+ try {
+ dos.putPrintableString(value);
+ } catch (IOException e) {
+ }
+ mData = dos.toByteArray();
}
/**
* Create the IPAddressName object with the specified name.
- *
+ *
* @param name the IPAddressName.
*/
public OtherName(byte[] data) {
try {
- decodeThis(new DerValue(data));
+ decodeThis(new DerValue(data));
} catch (IOException e) {
}
}
- public ObjectIdentifier getOID()
- {
- return mOID;
+ public ObjectIdentifier getOID() {
+ return mOID;
}
/**
@@ -127,19 +124,19 @@ public class OtherName implements GeneralNameInterface {
/**
* Encode the IPAddress name into the DerOutputStream.
- *
+ *
* @param out the DER stream to encode the IPAddressName to.
* @exception IOException on encoding errors.
*/
public void encode(DerOutputStream out) throws IOException {
DerOutputStream tmp = new DerOutputStream();
- //encoding the attributes
+ // encoding the attributes
tmp.putOID(mOID);
DerOutputStream tmp1 = new DerOutputStream();
tmp1.write(mData);
tmp.write(DerValue.createTag(DerValue.TAG_CONTEXT, true,
- (byte)0x80), tmp1);
+ (byte) 0x80), tmp1);
out.write(DerValue.tag_SequenceOf, tmp);
}
@@ -152,16 +149,15 @@ public class OtherName implements GeneralNameInterface {
// Decode this extension value
private void decodeThis(DerValue derVal) throws IOException {
- // if (derVal.tag != DerValue.tag_Sequence) {
- // throw new IOException("Invalid encoding for other name");
- // }
-
+ // if (derVal.tag != DerValue.tag_Sequence) {
+ // throw new IOException("Invalid encoding for other name");
+ // }
// Decode all the Attributes
mOID = derVal.data.getOID();
- // skip tag
+ // skip tag
DerValue tag = derVal.data.getDerValue();
- // read data
+ // read data
DerValue data = tag.data.getDerValue();
mData = data.toByteArray();
}
@@ -176,21 +172,21 @@ public class OtherName implements GeneralNameInterface {
public String toString() {
if (mData != null) {
try {
- DerValue data = new DerValue(mData);
- if (data.tag == DerValue.tag_PrintableString) {
- return "OtherName: (PrintableString)" + mOID + "," + data.getPrintableString();
- } else if (data.tag == DerValue.tag_IA5String) {
- return "OtherName: (IA5String)" + mOID + "," + data.getIA5String();
- } else if (data.tag == DerValue.tag_BMPString) {
- return "OtherName: (BMPString)" + mOID + "," + data.getIA5String();
- } else if (data.tag == DerValue.tag_UTF8String) {
- return "OtherName: (UTF8String)" + mOID + "," + data.getUTF8String();
- } else {
- return "OtherName: (Any)" + mOID + "," + toStr(data.toByteArray());
- }
- } catch (IOException e) {
-
- return "OtherName: (Any)" + mOID + "," + toStr(mData);
+ DerValue data = new DerValue(mData);
+ if (data.tag == DerValue.tag_PrintableString) {
+ return "OtherName: (PrintableString)" + mOID + "," + data.getPrintableString();
+ } else if (data.tag == DerValue.tag_IA5String) {
+ return "OtherName: (IA5String)" + mOID + "," + data.getIA5String();
+ } else if (data.tag == DerValue.tag_BMPString) {
+ return "OtherName: (BMPString)" + mOID + "," + data.getIA5String();
+ } else if (data.tag == DerValue.tag_UTF8String) {
+ return "OtherName: (UTF8String)" + mOID + "," + data.getUTF8String();
+ } else {
+ return "OtherName: (Any)" + mOID + "," + toStr(data.toByteArray());
+ }
+ } catch (IOException e) {
+
+ return "OtherName: (Any)" + mOID + "," + toStr(mData);
}
} else {
return "OtherName: ";
@@ -200,13 +196,11 @@ public class OtherName implements GeneralNameInterface {
public String toStr(byte data[]) {
StringBuffer b = new StringBuffer();
for (int i = 0; i < data.length; i++) {
- if ((data[i] & 0xff) < 16) {
- b.append("0");
- }
- b.append(Integer.toString((int)(data[i] & 0xff), 0x10));
+ if ((data[i] & 0xff) < 16) {
+ b.append("0");
+ }
+ b.append(Integer.toString((int) (data[i] & 0xff), 0x10));
}
return b.toString();
}
}
-
-
diff --git a/pki/base/util/src/netscape/security/x509/PKIXExtensions.java b/pki/base/util/src/netscape/security/x509/PKIXExtensions.java
index 8593d923..04c52a7d 100644
--- a/pki/base/util/src/netscape/security/x509/PKIXExtensions.java
+++ b/pki/base/util/src/netscape/security/x509/PKIXExtensions.java
@@ -21,182 +21,167 @@ import netscape.security.util.ObjectIdentifier;
/**
* Lists all the object identifiers of the X509 extensions of the PKIX profile.
- *
- * <p>Extensions are addiitonal attributes which can be inserted in a X509
- * v3 certificate. For example a "Driving License Certificate" could have
- * the driving license number as a extension.
- *
- * <p>Extensions are represented as a sequence of the extension identifier
- * (Object Identifier), a boolean flag stating whether the extension is to
- * be treated as being critical and the extension value itself (this is again
- * a DER encoding of the extension value).
- *
+ *
+ * <p>
+ * Extensions are addiitonal attributes which can be inserted in a X509 v3
+ * certificate. For example a "Driving License Certificate" could have the
+ * driving license number as a extension.
+ *
+ * <p>
+ * Extensions are represented as a sequence of the extension identifier (Object
+ * Identifier), a boolean flag stating whether the extension is to be treated as
+ * being critical and the extension value itself (this is again a DER encoding
+ * of the extension value).
+ *
* @see Extension
- *
+ *
* @version 1.4
- *
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
*/
public class PKIXExtensions {
// The object identifiers
- private static final int AuthorityKey_data [] = { 2, 5, 29, 35 };
- private static final int SubjectKey_data [] = { 2, 5, 29, 14 };
- private static final int KeyUsage_data [] = { 2, 5, 29, 15 };
- private static final int PrivateKeyUsage_data [] = { 2, 5, 29, 16 };
- private static final int CertificatePolicies_data [] = { 2, 5, 29, 32 };
- private static final int PolicyMappings_data [] = { 2, 5, 29, 33 };
- private static final int SubjectAlternativeName_data [] = { 2, 5, 29, 17 };
- private static final int IssuerAlternativeName_data [] = { 2, 5, 29, 18 };
- private static final int SubjectDirectoryAttributes_data [] = { 2, 5, 29, 9 };
- private static final int BasicConstraints_data [] = { 2, 5, 29, 19 };
- private static final int NameConstraints_data [] = { 2, 5, 29, 30 };
- private static final int PolicyConstraints_data [] = { 2, 5, 29, 36 };
- private static final int CRLDistributionPoints_data [] = { 2, 5, 29, 31 };
- private static final int CRLNumber_data [] = { 2, 5, 29, 20 };
- private static final int IssuingDistributionPoint_data [] = { 2, 5, 29, 28 };
- private static final int DeltaCRLIndicator_data [] = { 2, 5, 29, 27 };
- private static final int ReasonCode_data [] = { 2, 5, 29, 21 };
- private static final int HoldInstructionCode_data [] = { 2, 5, 29, 23 };
- private static final int InvalidityDate_data [] = { 2, 5, 29, 24 };
- private static final int CertificateIssuer_data [] = { 2, 5, 29, 29 };
- private static final int FreshestCRL_data [] = { 2, 5, 29, 46 };
+ private static final int AuthorityKey_data[] = { 2, 5, 29, 35 };
+ private static final int SubjectKey_data[] = { 2, 5, 29, 14 };
+ private static final int KeyUsage_data[] = { 2, 5, 29, 15 };
+ private static final int PrivateKeyUsage_data[] = { 2, 5, 29, 16 };
+ private static final int CertificatePolicies_data[] = { 2, 5, 29, 32 };
+ private static final int PolicyMappings_data[] = { 2, 5, 29, 33 };
+ private static final int SubjectAlternativeName_data[] = { 2, 5, 29, 17 };
+ private static final int IssuerAlternativeName_data[] = { 2, 5, 29, 18 };
+ private static final int SubjectDirectoryAttributes_data[] = { 2, 5, 29, 9 };
+ private static final int BasicConstraints_data[] = { 2, 5, 29, 19 };
+ private static final int NameConstraints_data[] = { 2, 5, 29, 30 };
+ private static final int PolicyConstraints_data[] = { 2, 5, 29, 36 };
+ private static final int CRLDistributionPoints_data[] = { 2, 5, 29, 31 };
+ private static final int CRLNumber_data[] = { 2, 5, 29, 20 };
+ private static final int IssuingDistributionPoint_data[] = { 2, 5, 29, 28 };
+ private static final int DeltaCRLIndicator_data[] = { 2, 5, 29, 27 };
+ private static final int ReasonCode_data[] = { 2, 5, 29, 21 };
+ private static final int HoldInstructionCode_data[] = { 2, 5, 29, 23 };
+ private static final int InvalidityDate_data[] = { 2, 5, 29, 24 };
+ private static final int CertificateIssuer_data[] = { 2, 5, 29, 29 };
+ private static final int FreshestCRL_data[] = { 2, 5, 29, 46 };
/**
* Identifies the particular public key used to sign the certificate.
*/
- public static final ObjectIdentifier AuthorityKey_Id
- = new ObjectIdentifier(AuthorityKey_data);
+ public static final ObjectIdentifier AuthorityKey_Id = new ObjectIdentifier(AuthorityKey_data);
/**
* Identifies the particular public key used in an application.
*/
- public static final ObjectIdentifier SubjectKey_Id
- = new ObjectIdentifier(SubjectKey_data);
+ public static final ObjectIdentifier SubjectKey_Id = new ObjectIdentifier(SubjectKey_data);
/**
* Defines the purpose of the key contained in the certificate.
*/
- public static final ObjectIdentifier KeyUsage_Id
- = new ObjectIdentifier(KeyUsage_data);
+ public static final ObjectIdentifier KeyUsage_Id = new ObjectIdentifier(KeyUsage_data);
/**
- * Allows the certificate issuer to specify a different validity period
- * for the private key than the certificate.
+ * Allows the certificate issuer to specify a different validity period for
+ * the private key than the certificate.
*/
- public static final ObjectIdentifier PrivateKeyUsage_Id
- = new ObjectIdentifier(PrivateKeyUsage_data);
+ public static final ObjectIdentifier PrivateKeyUsage_Id = new ObjectIdentifier(PrivateKeyUsage_data);
/**
* Contains the sequence of policy information terms.
*/
- public static final ObjectIdentifier CertificatePolicies_Id
- = new ObjectIdentifier(CertificatePolicies_data);
+ public static final ObjectIdentifier CertificatePolicies_Id = new ObjectIdentifier(CertificatePolicies_data);
/**
* Lists pairs of objectidentifiers of policies considered equivalent by the
* issuing CA to the subject CA.
*/
- public static final ObjectIdentifier PolicyMappings_Id
- = new ObjectIdentifier(PolicyMappings_data);
+ public static final ObjectIdentifier PolicyMappings_Id = new ObjectIdentifier(PolicyMappings_data);
/**
- * Allows additional identities to be bound to the subject of the certificate.
+ * Allows additional identities to be bound to the subject of the
+ * certificate.
*/
- public static final ObjectIdentifier SubjectAlternativeName_Id
- = new ObjectIdentifier(SubjectAlternativeName_data);
+ public static final ObjectIdentifier SubjectAlternativeName_Id = new ObjectIdentifier(SubjectAlternativeName_data);
/**
- * Allows additional identities to be associated with the certificate issuer.
+ * Allows additional identities to be associated with the certificate
+ * issuer.
*/
public static final ObjectIdentifier IssuerAlternativeName_Id =
new ObjectIdentifier(IssuerAlternativeName_data);
/**
- * Identifies additional directory attributes.
- * This extension is always non-critical.
+ * Identifies additional directory attributes. This extension is always
+ * non-critical.
*/
- public static final ObjectIdentifier SubjectDirectoryAttributes_Id
- = new ObjectIdentifier(SubjectDirectoryAttributes_data);
+ public static final ObjectIdentifier SubjectDirectoryAttributes_Id = new ObjectIdentifier(SubjectDirectoryAttributes_data);
/**
- * Identifies whether the subject of the certificate is a CA and how deep
- * a certification path may exist through that CA.
+ * Identifies whether the subject of the certificate is a CA and how deep a
+ * certification path may exist through that CA.
*/
public static final ObjectIdentifier BasicConstraints_Id =
new ObjectIdentifier(BasicConstraints_data);
/**
- * Provides for permitted and excluded subtrees that place restrictions
- * on names that may be included within a certificate issued by a given CA.
+ * Provides for permitted and excluded subtrees that place restrictions on
+ * names that may be included within a certificate issued by a given CA.
*/
- public static final ObjectIdentifier NameConstraints_Id
- = new ObjectIdentifier(NameConstraints_data);
+ public static final ObjectIdentifier NameConstraints_Id = new ObjectIdentifier(NameConstraints_data);
/**
- * Used to either prohibit policy mapping or limit the set of policies
- * that can be in subsequent certificates.
+ * Used to either prohibit policy mapping or limit the set of policies that
+ * can be in subsequent certificates.
*/
- public static final ObjectIdentifier PolicyConstraints_Id
- = new ObjectIdentifier(PolicyConstraints_data);
+ public static final ObjectIdentifier PolicyConstraints_Id = new ObjectIdentifier(PolicyConstraints_data);
/**
* Identifies how CRL information is obtained.
*/
- public static final ObjectIdentifier CRLDistributionPoints_Id
- = new ObjectIdentifier(CRLDistributionPoints_data);
+ public static final ObjectIdentifier CRLDistributionPoints_Id = new ObjectIdentifier(CRLDistributionPoints_data);
/**
- * Conveys a monotonically increasing sequence number for each CRL
- * issued by a given CA.
+ * Conveys a monotonically increasing sequence number for each CRL issued by
+ * a given CA.
*/
- public static final ObjectIdentifier CRLNumber_Id
- = new ObjectIdentifier(CRLNumber_data);
+ public static final ObjectIdentifier CRLNumber_Id = new ObjectIdentifier(CRLNumber_data);
/**
* Identifies the CRL distribution point for a particular CRL.
*/
- public static final ObjectIdentifier IssuingDistributionPoint_Id
- = new ObjectIdentifier(IssuingDistributionPoint_data);
+ public static final ObjectIdentifier IssuingDistributionPoint_Id = new ObjectIdentifier(IssuingDistributionPoint_data);
/**
* Identifies the delta CRL.
*/
- public static final ObjectIdentifier DeltaCRLIndicator_Id
- = new ObjectIdentifier(DeltaCRLIndicator_data);
+ public static final ObjectIdentifier DeltaCRLIndicator_Id = new ObjectIdentifier(DeltaCRLIndicator_data);
/**
* Identifies the reason for the certificate revocation.
*/
- public static final ObjectIdentifier ReasonCode_Id
- = new ObjectIdentifier(ReasonCode_data);
+ public static final ObjectIdentifier ReasonCode_Id = new ObjectIdentifier(ReasonCode_data);
/**
* This extension provides a registered instruction identifier indicating
* the action to be taken, after encountering a certificate that has been
* placed on hold.
*/
- public static final ObjectIdentifier HoldInstructionCode_Id
- = new ObjectIdentifier(HoldInstructionCode_data);
+ public static final ObjectIdentifier HoldInstructionCode_Id = new ObjectIdentifier(HoldInstructionCode_data);
/**
* Identifies the date on which it is known or suspected that the private
* key was compromised or that the certificate otherwise became invalid.
*/
- public static final ObjectIdentifier InvalidityDate_Id
- = new ObjectIdentifier(InvalidityDate_data);
+ public static final ObjectIdentifier InvalidityDate_Id = new ObjectIdentifier(InvalidityDate_data);
/**
* Identifies the date on which it is known or suspected that the private
* key was compromised or that the certificate otherwise became invalid.
*/
- public static final ObjectIdentifier CertificateIssuer_Id
- = new ObjectIdentifier(CertificateIssuer_data);
+ public static final ObjectIdentifier CertificateIssuer_Id = new ObjectIdentifier(CertificateIssuer_data);
/**
* Identifies how delta CRL information is obtained.
*/
- public static final ObjectIdentifier FreshestCRL_Id
- = new ObjectIdentifier(FreshestCRL_data);
+ public static final ObjectIdentifier FreshestCRL_Id = new ObjectIdentifier(FreshestCRL_data);
}
diff --git a/pki/base/util/src/netscape/security/x509/PolicyConstraint.java b/pki/base/util/src/netscape/security/x509/PolicyConstraint.java
index 83bfa1a6..22f9cebe 100644
--- a/pki/base/util/src/netscape/security/x509/PolicyConstraint.java
+++ b/pki/base/util/src/netscape/security/x509/PolicyConstraint.java
@@ -26,7 +26,7 @@ import netscape.security.util.DerValue;
/**
* This class defines the PolicyConstraint ASN.1 object.
- *
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.4
@@ -42,7 +42,7 @@ public class PolicyConstraint {
/**
* The default constructor for this object
- *
+ *
* @param set the CertificatePolicySet (null for optional).
* @param require require explicit policy (-1 for optional).
* @param inhibit inhibit policy mapping (-1 for optional).
@@ -55,35 +55,35 @@ public class PolicyConstraint {
/**
* Create the PolicyConstraint from the DerValue.
- *
+ *
* @param val the DerValue of the PolicyConstraint.
* @exception IOException on decoding errors.
*/
public PolicyConstraint(DerValue val) throws IOException {
if (val.tag != DerValue.tag_Sequence) {
- throw new IOException("Sequence tag missing for PolicyConstraint.");
- }
- DerInputStream in = val.data;
- while (in != null && in.available() != 0) {
- DerValue next = in.getDerValue();
- switch (next.tag & 0x1f) {
- case TAG_SET:
- this.set = new CertificatePolicySet(next.data);
- break;
-
- case TAG_REQUIRE:
- next = next.data.getDerValue();
- this.require = (next.getInteger()).toInt();
- break;
-
- case TAG_INHIBIT:
- next = next.data.getDerValue();
- this.inhibit = (next.getInteger()).toInt();
- break;
-
- default:
- throw new IOException("Invalid tag option for PolicyConstraint.");
- }
+ throw new IOException("Sequence tag missing for PolicyConstraint.");
+ }
+ DerInputStream in = val.data;
+ while (in != null && in.available() != 0) {
+ DerValue next = in.getDerValue();
+ switch (next.tag & 0x1f) {
+ case TAG_SET:
+ this.set = new CertificatePolicySet(next.data);
+ break;
+
+ case TAG_REQUIRE:
+ next = next.data.getDerValue();
+ this.require = (next.getInteger()).toInt();
+ break;
+
+ case TAG_INHIBIT:
+ next = next.data.getDerValue();
+ this.inhibit = (next.getInteger()).toInt();
+ break;
+
+ default:
+ throw new IOException("Invalid tag option for PolicyConstraint.");
+ }
}
}
@@ -91,23 +91,23 @@ public class PolicyConstraint {
* Return user readable form of the object.
*/
public String toString() {
- String s = ((set != null) ?
- "PolicyConstraint: [\n"
- + " PolicySet:[" + set.toString() + "]\n"
- + " Require:" + require + "\n"
- + " Inhibit:" + inhibit + "\n"
- + "]\n" :
- "PolicyConstraint: [\n"
- + " PolicySet:[null]\n"
- + " Require:" + require + "\n"
- + " Inhibit:" + inhibit + "\n"
- + "]\n");
+ String s = ((set != null) ?
+ "PolicyConstraint: [\n"
+ + " PolicySet:[" + set.toString() + "]\n"
+ + " Require:" + require + "\n"
+ + " Inhibit:" + inhibit + "\n"
+ + "]\n" :
+ "PolicyConstraint: [\n"
+ + " PolicySet:[null]\n"
+ + " Require:" + require + "\n"
+ + " Inhibit:" + inhibit + "\n"
+ + "]\n");
return (s);
}
/**
* Encode the object to the output stream.
- *
+ *
* @param out the DerOutputStream to encode the object to.
*/
public void encode(DerOutputStream out) throws IOException {
@@ -131,6 +131,6 @@ public class PolicyConstraint {
tagged.write(DerValue.createTag(DerValue.TAG_CONTEXT,
true, TAG_INHIBIT), tmp);
}
- out.write(DerValue.tag_Sequence,tagged);
+ out.write(DerValue.tag_Sequence, tagged);
}
}
diff --git a/pki/base/util/src/netscape/security/x509/PolicyConstraintsExtension.java b/pki/base/util/src/netscape/security/x509/PolicyConstraintsExtension.java
index 39e7fbfb..6bbd82a0 100644
--- a/pki/base/util/src/netscape/security/x509/PolicyConstraintsExtension.java
+++ b/pki/base/util/src/netscape/security/x509/PolicyConstraintsExtension.java
@@ -30,16 +30,17 @@ import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
/**
- * This class defines the certificate extension which specifies the
- * Policy constraints.
+ * This class defines the certificate extension which specifies the Policy
+ * constraints.
* <p>
- * The policy constraints extension can be used in certificates issued
- * to CAs. The policy constraints extension constrains path validation
- * in two ways. It can be used to prohibit policy mapping or require
- * that each certificate in a path contain an acceptable policy
- * identifier.<p>
- * The ASN.1 syntax for this is (IMPLICIT tagging is defined in the
- * module definition):
+ * The policy constraints extension can be used in certificates issued to CAs.
+ * The policy constraints extension constrains path validation in two ways. It
+ * can be used to prohibit policy mapping or require that each certificate in a
+ * path contain an acceptable policy identifier.
+ * <p>
+ * The ASN.1 syntax for this is (IMPLICIT tagging is defined in the module
+ * definition):
+ *
* <pre>
* PolicyConstraints ::= SEQUENCE {
* requireExplicitPolicy [0] SkipCerts OPTIONAL,
@@ -47,6 +48,7 @@ import netscape.security.util.DerValue;
* }
* SkipCerts ::= INTEGER (0..MAX)
* </pre>
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.9
@@ -54,15 +56,15 @@ import netscape.security.util.DerValue;
* @see CertAttrSet
*/
public class PolicyConstraintsExtension extends Extension
-implements CertAttrSet {
+ implements CertAttrSet {
/**
*
*/
private static final long serialVersionUID = -3723759691127622370L;
/**
- * Identifier for this attribute, to be used with the
- * get, set, delete methods of Certificate, x509 type.
- */
+ * Identifier for this attribute, to be used with the get, set, delete
+ * methods of Certificate, x509 type.
+ */
public static final String IDENT = "x509.info.extensions.PolicyConstraints";
/**
* Attribute names.
@@ -86,72 +88,72 @@ implements CertAttrSet {
tmp.putInteger(new BigInt(require));
tagged.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
false, TAG_REQUIRE), tmp);
- }
+ }
if (inhibit != -1) {
- DerOutputStream tmp = new DerOutputStream();
+ DerOutputStream tmp = new DerOutputStream();
tmp.putInteger(new BigInt(inhibit));
tagged.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
false, TAG_INHIBIT), tmp);
}
seq.write(DerValue.tag_Sequence, tagged);
- extensionValue = seq.toByteArray();
+ extensionValue = seq.toByteArray();
}
/**
- * Create a PolicyConstraintsExtension object with criticality and
- * both require explicit policy and inhibit policy mapping.
+ * Create a PolicyConstraintsExtension object with criticality and both
+ * require explicit policy and inhibit policy mapping.
*
* @param critical whether this extension should be critical
* @param require require explicit policy (-1 for optional).
* @param inhibit inhibit policy mapping (-1 for optional).
*/
public PolicyConstraintsExtension(boolean crit, int require, int inhibit)
- throws IOException {
- init(crit, require, inhibit);
+ throws IOException {
+ init(crit, require, inhibit);
}
/**
- * Create a PolicyConstraintsExtension object with both
- * require explicit policy and inhibit policy mapping.
- *
+ * Create a PolicyConstraintsExtension object with both require explicit
+ * policy and inhibit policy mapping.
+ *
* @param require require explicit policy (-1 for optional).
* @param inhibit inhibit policy mapping (-1 for optional).
*/
public PolicyConstraintsExtension(int require, int inhibit)
- throws IOException {
- init(false, require, inhibit);
+ throws IOException {
+ init(false, require, inhibit);
}
private void init(boolean crit, int require, int inhibit)
- throws IOException {
+ throws IOException {
this.require = require;
this.inhibit = inhibit;
- this.extensionId = PKIXExtensions.PolicyConstraints_Id;
- this.critical = crit;
+ this.extensionId = PKIXExtensions.PolicyConstraints_Id;
+ this.critical = crit;
encodeThis();
}
/**
* Create the extension from its DER encoded value and criticality.
- *
+ *
* @param critical true if the extension is to be treated as critical.
* @param value Array of DER encoded bytes of the actual value.
* @exception IOException on error.
*/
public PolicyConstraintsExtension(Boolean critical, Object value)
- throws IOException {
- this.extensionId = PKIXExtensions.PolicyConstraints_Id;
- this.critical = critical.booleanValue();
+ throws IOException {
+ this.extensionId = PKIXExtensions.PolicyConstraints_Id;
+ this.critical = critical.booleanValue();
if (!(value instanceof byte[]))
throw new IOException("Illegal argument type");
int len = Array.getLength(value);
- byte[] extValue = new byte[len];
+ byte[] extValue = new byte[len];
System.arraycopy(value, 0, extValue, 0, len);
this.extensionValue = extValue;
- DerValue val = new DerValue(extValue);
+ DerValue val = new DerValue(extValue);
if (val.tag != DerValue.tag_Sequence) {
throw new IOException("Sequence tag missing for PolicyConstraint.");
}
@@ -162,7 +164,7 @@ implements CertAttrSet {
if (next.isContextSpecific(TAG_REQUIRE) && !next.isConstructed()) {
if (this.require != -1)
throw new IOException("Duplicate requireExplicitPolicy" +
- "found in the PolicyConstraintsExtension");
+ "found in the PolicyConstraintsExtension");
next.resetTag(DerValue.tag_Integer);
this.require = (next.getInteger()).toInt();
@@ -170,12 +172,12 @@ implements CertAttrSet {
!next.isConstructed()) {
if (this.inhibit != -1)
throw new IOException("Duplicate inhibitPolicyMapping" +
- "found in the PolicyConstraintsExtension");
+ "found in the PolicyConstraintsExtension");
next.resetTag(DerValue.tag_Integer);
this.inhibit = (next.getInteger()).toInt();
} else
throw new IOException("Invalid encoding of PolicyConstraint");
- }
+ }
}
/**
@@ -184,12 +186,12 @@ implements CertAttrSet {
public String toString() {
String s;
s = super.toString() + "PolicyConstraints: [" + " Require: ";
- if (require == -1)
+ if (require == -1)
s += "unspecified;";
else
s += require + ";";
s += "\tInhibit: ";
- if (inhibit == -1)
+ if (inhibit == -1)
s += "unspecified";
else
s += inhibit;
@@ -199,7 +201,7 @@ implements CertAttrSet {
/**
* Decode the extension from the InputStream.
- *
+ *
* @param in the InputStream to unmarshal the contents from.
* @exception IOException on decoding or validity errors.
*/
@@ -209,91 +211,90 @@ implements CertAttrSet {
/**
* Write the extension to the DerOutputStream.
- *
+ *
* @param out the DerOutputStream to write the extension to.
* @exception IOException on encoding errors.
*/
public void encode(OutputStream out) throws IOException {
DerOutputStream tmp = new DerOutputStream();
if (extensionValue == null) {
- extensionId = PKIXExtensions.PolicyConstraints_Id;
- encodeThis();
- }
- super.encode(tmp);
- out.write(tmp.toByteArray());
+ extensionId = PKIXExtensions.PolicyConstraints_Id;
+ encodeThis();
+ }
+ super.encode(tmp);
+ out.write(tmp.toByteArray());
}
/**
* Set the attribute value.
*/
public void set(String name, Object obj) throws IOException {
- clearValue();
- if (!(obj instanceof Integer)) {
- throw new IOException("Attribute value should be of type Integer.");
- }
- if (name.equalsIgnoreCase(REQUIRE)) {
- require = ((Integer)obj).intValue();
- } else if (name.equalsIgnoreCase(INHIBIT)) {
- inhibit = ((Integer)obj).intValue();
- } else {
- throw new IOException("Attribute name " + "[" + name + "]" +
- " not recognized by " +
- "CertAttrSet:PolicyConstraints.");
- }
+ clearValue();
+ if (!(obj instanceof Integer)) {
+ throw new IOException("Attribute value should be of type Integer.");
+ }
+ if (name.equalsIgnoreCase(REQUIRE)) {
+ require = ((Integer) obj).intValue();
+ } else if (name.equalsIgnoreCase(INHIBIT)) {
+ inhibit = ((Integer) obj).intValue();
+ } else {
+ throw new IOException("Attribute name " + "[" + name + "]" +
+ " not recognized by " +
+ "CertAttrSet:PolicyConstraints.");
+ }
}
/**
* Get the attribute value.
*/
public Object get(String name) throws IOException {
- if (name.equalsIgnoreCase(REQUIRE)) {
- return Integer.valueOf(require);
- } else if (name.equalsIgnoreCase(INHIBIT)) {
- return Integer.valueOf(inhibit);
- } else {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:PolicyConstraints.");
- }
+ if (name.equalsIgnoreCase(REQUIRE)) {
+ return Integer.valueOf(require);
+ } else if (name.equalsIgnoreCase(INHIBIT)) {
+ return Integer.valueOf(inhibit);
+ } else {
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:PolicyConstraints.");
+ }
}
/**
* Delete the attribute value.
*/
public void delete(String name) throws IOException {
- if (name.equalsIgnoreCase(REQUIRE)) {
- require = -1;
- } else if (name.equalsIgnoreCase(INHIBIT)) {
- inhibit = -1;
- } else {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:PolicyConstraints.");
- }
+ if (name.equalsIgnoreCase(REQUIRE)) {
+ require = -1;
+ } else if (name.equalsIgnoreCase(INHIBIT)) {
+ inhibit = -1;
+ } else {
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:PolicyConstraints.");
+ }
}
/**
* Return an enumeration of names of attributes existing within this
* attribute.
*/
- public Enumeration<String> getAttributeNames () {
+ public Enumeration<String> getAttributeNames() {
Vector<String> elements = new Vector<String>();
elements.addElement(REQUIRE);
elements.addElement(INHIBIT);
- return (elements.elements());
+ return (elements.elements());
}
-
/**
* returns the requireExplicitMapping parameter.
*/
public int getRequireExplicitMapping() {
- return require;
+ return require;
}
/**
- * returns the inhibitPolicyMapping parameter.
+ * returns the inhibitPolicyMapping parameter.
*/
public int getInhibitPolicyMapping() {
- return inhibit;
+ return inhibit;
}
}
diff --git a/pki/base/util/src/netscape/security/x509/PolicyMappingsExtension.java b/pki/base/util/src/netscape/security/x509/PolicyMappingsExtension.java
index c31acf92..f5333435 100644
--- a/pki/base/util/src/netscape/security/x509/PolicyMappingsExtension.java
+++ b/pki/base/util/src/netscape/security/x509/PolicyMappingsExtension.java
@@ -29,18 +29,20 @@ import netscape.security.util.DerValue;
/**
* Represent the Policy Mappings Extension.
- *
+ *
* This extension, if present, identifies the certificate policies considered
* identical between the issuing and the subject CA.
- * <p>Extensions are addiitonal attributes which can be inserted in a X509
- * v3 certificate. For example a "Driving License Certificate" could have
- * the driving license number as a extension.
- *
- * <p>Extensions are represented as a sequence of the extension identifier
- * (Object Identifier), a boolean flag stating whether the extension is to
- * be treated as being critical and the extension value itself (this is again
- * a DER encoding of the extension value).
- *
+ * <p>
+ * Extensions are addiitonal attributes which can be inserted in a X509 v3
+ * certificate. For example a "Driving License Certificate" could have the
+ * driving license number as a extension.
+ *
+ * <p>
+ * Extensions are represented as a sequence of the extension identifier (Object
+ * Identifier), a boolean flag stating whether the extension is to be treated as
+ * being critical and the extension value itself (this is again a DER encoding
+ * of the extension value).
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.7
@@ -48,15 +50,15 @@ import netscape.security.util.DerValue;
* @see CertAttrSet
*/
public class PolicyMappingsExtension extends Extension
-implements CertAttrSet {
+ implements CertAttrSet {
/**
*
*/
private static final long serialVersionUID = -4023336164621135851L;
/**
- * Identifier for this attribute, to be used with the
- * get, set, delete methods of Certificate, x509 type.
- */
+ * Identifier for this attribute, to be used with the get, set, delete
+ * methods of Certificate, x509 type.
+ */
public static final String IDENT = "x509.info.extensions.PolicyMappings";
/**
* Attribute names.
@@ -72,34 +74,34 @@ implements CertAttrSet {
DerOutputStream tmp = new DerOutputStream();
for (int i = 0; i < maps.size(); i++) {
- ((CertificatePolicyMap)maps.elementAt(i)).encode(tmp);
+ ((CertificatePolicyMap) maps.elementAt(i)).encode(tmp);
}
- os.write(DerValue.tag_Sequence,tmp);
+ os.write(DerValue.tag_Sequence, tmp);
extensionValue = os.toByteArray();
}
/**
* Create a PolicyMappings with the Vector of CertificatePolicyMap.
- *
+ *
* @param maps the Vector of CertificatePolicyMap.
*/
public PolicyMappingsExtension(Vector<CertificatePolicyMap> map) throws IOException {
- init(false, map);
+ init(false, map);
}
/**
* Create a PolicyMappings with the Vector of CertificatePolicyMap.
- *
+ *
* @param maps the Vector of CertificatePolicyMap.
*/
- public PolicyMappingsExtension(boolean critical, Vector<CertificatePolicyMap> map)
- throws IOException {
- init(critical, map);
- }
+ public PolicyMappingsExtension(boolean critical, Vector<CertificatePolicyMap> map)
+ throws IOException {
+ init(critical, map);
+ }
- /**
- * init policy with criticality and map.
- */
+ /**
+ * init policy with criticality and map.
+ */
private void init(boolean critical, Vector<CertificatePolicyMap> map) throws IOException {
this.maps = map;
this.extensionId = PKIXExtensions.PolicyMappings_Id;
@@ -113,26 +115,26 @@ implements CertAttrSet {
public PolicyMappingsExtension() {
extensionId = PKIXExtensions.PolicyMappings_Id;
critical = false;
- maps = new Vector<CertificatePolicyMap>(1,1);
+ maps = new Vector<CertificatePolicyMap>(1, 1);
}
/**
* Create the extension from the passed DER encoded value.
- *
+ *
* @param critical true if the extension is to be treated as critical.
* @param value Array of DER encoded bytes of the actual value.
* @exception IOException on error.
*/
public PolicyMappingsExtension(Boolean critical, Object value)
- throws IOException {
+ throws IOException {
this.extensionId = PKIXExtensions.PolicyMappings_Id;
this.critical = critical.booleanValue();
int len = Array.getLength(value);
- byte [] extValue = new byte[len];
- for (int i = 0; i < len; i++) {
- extValue[i] = Array.getByte(value, i);
- }
+ byte[] extValue = new byte[len];
+ for (int i = 0; i < len; i++) {
+ extValue[i] = Array.getByte(value, i);
+ }
this.extensionValue = extValue;
DerValue val = new DerValue(extValue);
if (val.tag != DerValue.tag_Sequence) {
@@ -151,7 +153,8 @@ implements CertAttrSet {
* Returns a printable representation of the policy map.
*/
public String toString() {
- if (maps == null) return "";
+ if (maps == null)
+ return "";
String s = super.toString() + "PolicyMappings [\n"
+ maps.toString() + "]\n";
@@ -160,7 +163,7 @@ implements CertAttrSet {
/**
* Write the extension to the OutputStream.
- *
+ *
* @param out the OutputStream to write the extension to.
* @exception IOException on encoding errors.
*/
@@ -172,12 +175,12 @@ implements CertAttrSet {
encodeThis();
}
super.encode(tmp);
- out.write(tmp.toByteArray());
+ out.write(tmp.toByteArray());
}
/**
* Decode the extension from the InputStream.
- *
+ *
* @param in the InputStream to unmarshal the contents from.
* @exception IOException on decoding or validity errors.
*/
@@ -188,63 +191,62 @@ implements CertAttrSet {
/**
* Set the attribute value.
*/
- @SuppressWarnings("unchecked")
- public void set(String name, Object obj) throws IOException {
- clearValue();
- if (name.equalsIgnoreCase(MAP)) {
- if (!(obj instanceof Vector)) {
- throw new IOException("Attribute value should be of" +
+ @SuppressWarnings("unchecked")
+ public void set(String name, Object obj) throws IOException {
+ clearValue();
+ if (name.equalsIgnoreCase(MAP)) {
+ if (!(obj instanceof Vector)) {
+ throw new IOException("Attribute value should be of" +
" type Vector.");
- }
- maps = (Vector<CertificatePolicyMap>)obj;
- } else {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:PolicyMappingsExtension.");
- }
+ }
+ maps = (Vector<CertificatePolicyMap>) obj;
+ } else {
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:PolicyMappingsExtension.");
+ }
}
/**
* Get the attribute value.
*/
public Object get(String name) throws IOException {
- if (name.equalsIgnoreCase(MAP)) {
- return (maps);
- } else {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:PolicyMappingsExtension.");
- }
+ if (name.equalsIgnoreCase(MAP)) {
+ return (maps);
+ } else {
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:PolicyMappingsExtension.");
+ }
}
/**
* Delete the attribute value.
*/
public void delete(String name) throws IOException {
- if (name.equalsIgnoreCase(MAP)) {
- maps = null;
- } else {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:PolicyMappingsExtension.");
- }
+ if (name.equalsIgnoreCase(MAP)) {
+ maps = null;
+ } else {
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:PolicyMappingsExtension.");
+ }
}
/**
* Return an enumeration of names of attributes existing within this
* attribute.
*/
- public Enumeration<String> getAttributeNames () {
+ public Enumeration<String> getAttributeNames() {
Vector<String> elements = new Vector<String>();
elements.addElement(MAP);
- return (elements.elements());
+ return (elements.elements());
}
-
/**
* Returns an enumeration of the mappings in the extension.
*/
public Enumeration<CertificatePolicyMap> getMappings() {
- if (maps == null)
- return null;
- return maps.elements();
+ if (maps == null)
+ return null;
+ return maps.elements();
}
}
diff --git a/pki/base/util/src/netscape/security/x509/PolicyQualifierInfo.java b/pki/base/util/src/netscape/security/x509/PolicyQualifierInfo.java
index da0ab384..bdaff872 100644
--- a/pki/base/util/src/netscape/security/x509/PolicyQualifierInfo.java
+++ b/pki/base/util/src/netscape/security/x509/PolicyQualifierInfo.java
@@ -23,18 +23,15 @@ import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
import netscape.security.util.ObjectIdentifier;
-
/**
* Represent the PolicyQualifierInfo.
- *
- * policyQualifierInfo ::= SEQUENCE {
- * policyQualifierId PolicyQualifierId
- * qualifier ANY DEFINED BY policyQualifierId
- * }
- *
+ *
+ * policyQualifierInfo ::= SEQUENCE { policyQualifierId PolicyQualifierId
+ * qualifier ANY DEFINED BY policyQualifierId }
+ *
* @author Thomas Kwan
*/
-public class PolicyQualifierInfo implements java.io.Serializable {
+public class PolicyQualifierInfo implements java.io.Serializable {
/**
*
@@ -42,57 +39,55 @@ public class PolicyQualifierInfo implements java.io.Serializable {
private static final long serialVersionUID = -2930016944517192379L;
public static final int OID_CPS[] = { 1, 3, 6, 1, 5, 5, 7, 2, 1 };
public static final ObjectIdentifier QT_CPS = new
- ObjectIdentifier(OID_CPS);
+ ObjectIdentifier(OID_CPS);
public static final int OID_UNOTICE[] = { 1, 3, 6, 1, 5, 5, 7, 2, 2 };
public static final ObjectIdentifier QT_UNOTICE = new
- ObjectIdentifier(OID_UNOTICE);
+ ObjectIdentifier(OID_UNOTICE);
private ObjectIdentifier mId = null;
private Qualifier mQualifier = null;
/**
* Create a PolicyQualifierInfo
- *
+ *
* @param id the ObjectIdentifier for the policy id.
*/
public PolicyQualifierInfo(ObjectIdentifier id, Qualifier qualifier) {
- mId = id;
- mQualifier = qualifier;
+ mId = id;
+ mQualifier = qualifier;
}
/**
* Create the object from its Der encoded value.
- *
+ *
* @param val the DER encoded value for the same.
*/
public PolicyQualifierInfo(DerValue val) throws IOException {
- if (val.tag != DerValue.tag_Sequence) {
- throw new IOException("Invalid encoding for PolicyQualifierInfo.");
- }
+ if (val.tag != DerValue.tag_Sequence) {
+ throw new IOException("Invalid encoding for PolicyQualifierInfo.");
+ }
DerValue did = val.data.getDerValue();
mId = did.getOID();
- if (val.data.available() != 0) {
- DerValue qualifier = val.data.getDerValue();
- if (qualifier.tag == DerValue.tag_IA5String) {
- mQualifier = new CPSuri(qualifier);
- } else {
- mQualifier = new UserNotice(qualifier);
- }
- }
+ if (val.data.available() != 0) {
+ DerValue qualifier = val.data.getDerValue();
+ if (qualifier.tag == DerValue.tag_IA5String) {
+ mQualifier = new CPSuri(qualifier);
+ } else {
+ mQualifier = new UserNotice(qualifier);
+ }
+ }
}
- public ObjectIdentifier getId()
- {
- return mId;
+ public ObjectIdentifier getId() {
+ return mId;
}
/**
* Returns object of type CPSuri or UserNotice.
*/
- public Qualifier getQualifier()
- {
- return mQualifier;
+ public Qualifier getQualifier() {
+ return mQualifier;
}
/**
@@ -108,14 +103,14 @@ public class PolicyQualifierInfo implements java.io.Serializable {
/**
* Write the PolicyQualifier to the DerOutputStream.
- *
+ *
* @param out the DerOutputStream to write the object to.
* @exception IOException on errors.
*/
public void encode(DerOutputStream out) throws IOException {
- DerOutputStream tmp = new DerOutputStream();
- tmp.putOID(mId);
- mQualifier.encode(tmp);
- out.write(DerValue.tag_Sequence,tmp);
+ DerOutputStream tmp = new DerOutputStream();
+ tmp.putOID(mId);
+ mQualifier.encode(tmp);
+ out.write(DerValue.tag_Sequence, tmp);
}
}
diff --git a/pki/base/util/src/netscape/security/x509/PolicyQualifiers.java b/pki/base/util/src/netscape/security/x509/PolicyQualifiers.java
index fd2c161b..ee756f50 100644
--- a/pki/base/util/src/netscape/security/x509/PolicyQualifiers.java
+++ b/pki/base/util/src/netscape/security/x509/PolicyQualifiers.java
@@ -23,12 +23,11 @@ import java.util.Vector;
import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
-
/**
* Represent the PolicyQualifiers.
- *
+ *
* policyQualifiers ::= SEQUENCE SIZE (1..MAX) OF PolicyQualifierInfo
- *
+ *
* @author Thomas Kwan
*/
public class PolicyQualifiers implements java.io.Serializable {
@@ -41,7 +40,7 @@ public class PolicyQualifiers implements java.io.Serializable {
/**
* Create a PolicyQualifiers with the ObjectIdentifier.
- *
+ *
* @param id the ObjectIdentifier for the policy id.
*/
public PolicyQualifiers() {
@@ -49,29 +48,28 @@ public class PolicyQualifiers implements java.io.Serializable {
/**
* Create the object from its Der encoded value.
- *
+ *
* @param val the DER encoded value for the same.
*/
public PolicyQualifiers(DerValue val) throws IOException {
- if (val.tag != DerValue.tag_Sequence) {
- throw new IOException("Invalid encoding for " + "PolicyQualifiers.");
- }
- while (val.data.available() != 0) {
- DerValue pq = val.data.getDerValue();
- PolicyQualifierInfo info = new PolicyQualifierInfo(pq);
- add(info);
- }
+ if (val.tag != DerValue.tag_Sequence) {
+ throw new IOException("Invalid encoding for " + "PolicyQualifiers.");
+ }
+ while (val.data.available() != 0) {
+ DerValue pq = val.data.getDerValue();
+ PolicyQualifierInfo info = new PolicyQualifierInfo(pq);
+ add(info);
+ }
}
public void add(PolicyQualifierInfo info) {
mInfo.addElement(info);
}
- public int size()
- {
+ public int size() {
return mInfo.size();
}
-
+
public PolicyQualifierInfo getInfoAt(int i) {
return mInfo.elementAt(i);
}
@@ -82,8 +80,8 @@ public class PolicyQualifiers implements java.io.Serializable {
public String toString() {
String s = "PolicyQualifiers: [";
for (int i = 0; i < mInfo.size(); i++) {
- PolicyQualifierInfo pq = mInfo.elementAt(i);
- s = s + pq.toString();
+ PolicyQualifierInfo pq = mInfo.elementAt(i);
+ s = s + pq.toString();
}
s = s + "]\n";
@@ -92,17 +90,17 @@ public class PolicyQualifiers implements java.io.Serializable {
/**
* Write the PolicyQualifiers to the DerOutputStream.
- *
+ *
* @param out the DerOutputStream to write the object to.
* @exception IOException on errors.
*/
public void encode(DerOutputStream out) throws IOException {
DerOutputStream tmp = new DerOutputStream();
-
+
for (int i = 0; i < mInfo.size(); i++) {
- PolicyQualifierInfo pq = mInfo.elementAt(i);
- pq.encode(tmp);
- }
+ PolicyQualifierInfo pq = mInfo.elementAt(i);
+ pq.encode(tmp);
+ }
out.write(DerValue.tag_Sequence, tmp);
}
diff --git a/pki/base/util/src/netscape/security/x509/PrintableConverter.java b/pki/base/util/src/netscape/security/x509/PrintableConverter.java
index b4c58739..5b327733 100644
--- a/pki/base/util/src/netscape/security/x509/PrintableConverter.java
+++ b/pki/base/util/src/netscape/security/x509/PrintableConverter.java
@@ -24,103 +24,94 @@ import netscape.security.util.DerValue;
import sun.io.CharToByteConverter;
/**
- * A AVAValueConverter that converts a Printable String attribute to a DerValue
+ * A AVAValueConverter that converts a Printable String attribute to a DerValue
* and vice versa. An example an attribute that is a printable string is "C".
- *
+ *
* @see ASN1CharStrConvMap
* @see AVAValueConverter
- *
+ *
* @author Lily Hsiao, Slava Galperin at Netscape Communications, Inc.
*/
-public class PrintableConverter implements AVAValueConverter
-{
+public class PrintableConverter implements AVAValueConverter {
// public constructors.
- public PrintableConverter()
- {
+ public PrintableConverter() {
}
/**
* Converts a string with ASN.1 Printable characters to a DerValue.
*
- * @param valueString a string with Printable characters.
+ * @param valueString a string with Printable characters.
*
- * @return a DerValue.
+ * @return a DerValue.
*
- * @exception IOException if a Printable CharToByteConverter is not
- * available for the conversion.
+ * @exception IOException if a Printable CharToByteConverter is not
+ * available for the conversion.
*/
public DerValue getValue(String valueString)
- throws IOException
- {
- return getValue(valueString, null);
+ throws IOException {
+ return getValue(valueString, null);
}
public DerValue getValue(String valueString, byte[] encodingOrder)
- throws IOException
- {
- CharToByteConverter printable;
- byte[] bbuf = new byte[valueString.length()];
- try {
- printable = ASN1CharStrConvMap.getDefault().getCBC(
- DerValue.tag_PrintableString);
- if (printable == null) {
- throw new IOException("No CharToByteConverter for printable");
- }
- printable.convert(valueString.toCharArray(), 0,
- valueString.length(), bbuf, 0, bbuf.length);
- }
- catch (java.io.CharConversionException e) {
- throw new IllegalArgumentException(
- "Invalid Printable String AVA Value");
- }
- catch (InstantiationException e) {
- throw new IOException("Cannot instantiate CharToByteConverter");
- }
- catch (IllegalAccessException e) {
- throw new IOException("Cannot load CharToByteConverter");
- }
- return new DerValue(DerValue.tag_PrintableString, bbuf);
+ throws IOException {
+ CharToByteConverter printable;
+ byte[] bbuf = new byte[valueString.length()];
+ try {
+ printable = ASN1CharStrConvMap.getDefault().getCBC(
+ DerValue.tag_PrintableString);
+ if (printable == null) {
+ throw new IOException("No CharToByteConverter for printable");
+ }
+ printable.convert(valueString.toCharArray(), 0,
+ valueString.length(), bbuf, 0, bbuf.length);
+ } catch (java.io.CharConversionException e) {
+ throw new IllegalArgumentException(
+ "Invalid Printable String AVA Value");
+ } catch (InstantiationException e) {
+ throw new IOException("Cannot instantiate CharToByteConverter");
+ } catch (IllegalAccessException e) {
+ throw new IOException("Cannot load CharToByteConverter");
+ }
+ return new DerValue(DerValue.tag_PrintableString, bbuf);
}
/**
* Converts a BER encoded value of PrintableString to a DER encoded value.
- * Checks if the BER encoded value is a PrintableString.
- * NOTE only DER encoded values are currently accepted on input.
+ * Checks if the BER encoded value is a PrintableString. NOTE only DER
+ * encoded values are currently accepted on input.
*
- * @param berStream A byte array of the BER encoded value.
+ * @param berStream A byte array of the BER encoded value.
*
- * @return A DerValue.
+ * @return A DerValue.
*
- * @exception IOException if the BER value cannot be converted to a
- * PrintableString DER value.
+ * @exception IOException if the BER value cannot be converted to a
+ * PrintableString DER value.
*/
public DerValue getValue(byte[] berStream)
- throws IOException
- {
- DerValue value = new DerValue(berStream);
- if (value.tag != DerValue.tag_PrintableString)
- throw new IOException("Invalid Printable String AVA Value");
- return value;
+ throws IOException {
+ DerValue value = new DerValue(berStream);
+ if (value.tag != DerValue.tag_PrintableString)
+ throw new IOException("Invalid Printable String AVA Value");
+ return value;
}
/**
- * Converts a DerValue of PrintableString to a java string with
- * PrintableString characters.
+ * Converts a DerValue of PrintableString to a java string with
+ * PrintableString characters.
*
- * @param avaValue a DerValue.
- *
- * @return a string with PrintableString characters.
- *
- * @exception IOException if the DerValue is not a PrintableString i.e.
- * The DerValue cannot be converted to a string
- * with PrintableString characters.
+ * @param avaValue a DerValue.
+ *
+ * @return a string with PrintableString characters.
+ *
+ * @exception IOException if the DerValue is not a PrintableString i.e. The
+ * DerValue cannot be converted to a string with
+ * PrintableString characters.
*/
public String getAsString(DerValue avaValue)
- throws IOException
- {
- return avaValue.getPrintableString();
+ throws IOException {
+ return avaValue.getPrintableString();
}
}
diff --git a/pki/base/util/src/netscape/security/x509/PrivateKeyUsageExtension.java b/pki/base/util/src/netscape/security/x509/PrivateKeyUsageExtension.java
index 98a7a4d3..2de41895 100644
--- a/pki/base/util/src/netscape/security/x509/PrivateKeyUsageExtension.java
+++ b/pki/base/util/src/netscape/security/x509/PrivateKeyUsageExtension.java
@@ -35,21 +35,22 @@ import netscape.security.util.DerValue;
/**
* This class defines the Private Key Usage Extension.
- *
- * <p>The Private Key Usage Period extension allows the certificate issuer
- * to specify a different validity period for the private key than the
- * certificate. This extension is intended for use with digital
- * signature keys. This extension consists of two optional components
- * notBefore and notAfter. The private key associated with the
- * certificate should not be used to sign objects before or after the
- * times specified by the two components, respectively.
- *
+ *
+ * <p>
+ * The Private Key Usage Period extension allows the certificate issuer to
+ * specify a different validity period for the private key than the certificate.
+ * This extension is intended for use with digital signature keys. This
+ * extension consists of two optional components notBefore and notAfter. The
+ * private key associated with the certificate should not be used to sign
+ * objects before or after the times specified by the two components,
+ * respectively.
+ *
* <pre>
* PrivateKeyUsagePeriod ::= SEQUENCE {
* notBefore [0] GeneralizedTime OPTIONAL,
* notAfter [1] GeneralizedTime OPTIONAL }
* </pre>
- *
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.12
@@ -57,15 +58,15 @@ import netscape.security.util.DerValue;
* @see CertAttrSet
*/
public class PrivateKeyUsageExtension extends Extension
-implements CertAttrSet {
+ implements CertAttrSet {
/**
*
*/
private static final long serialVersionUID = -7623695233957629936L;
/**
- * Identifier for this attribute, to be used with the
- * get, set, delete methods of Certificate, x509 type.
- */
+ * Identifier for this attribute, to be used with the get, set, delete
+ * methods of Certificate, x509 type.
+ */
public static final String IDENT = "x509.info.extensions.PrivateKeyUsage";
/**
* Sub attributes name for this CertAttrSet.
@@ -77,8 +78,8 @@ implements CertAttrSet {
private static final byte TAG_BEFORE = 0;
private static final byte TAG_AFTER = 1;
- private Date notBefore;
- private Date notAfter;
+ private Date notBefore;
+ private Date notAfter;
// Encode this extension value.
private void encodeThis() throws IOException {
@@ -103,14 +104,14 @@ implements CertAttrSet {
/**
* The default constructor for PrivateKeyUsageExtension.
- *
- * @param notBefore the date/time before which the private key
- * should not be used.
- * @param notAfter the date/time after which the private key
- * should not be used.
+ *
+ * @param notBefore the date/time before which the private key should not be
+ * used.
+ * @param notAfter the date/time after which the private key should not be
+ * used.
*/
public PrivateKeyUsageExtension(Date notBefore, Date notAfter)
- throws IOException {
+ throws IOException {
this.notBefore = notBefore;
this.notAfter = notAfter;
@@ -121,15 +122,15 @@ implements CertAttrSet {
/**
* Create the extension from the passed DER encoded value.
- *
+ *
* @param critical true if the extension is to be treated as critical.
* @param value Array of DER encoded bytes of the actual value.
- *
+ *
* @exception CertificateException on certificate parsing errors.
* @exception IOException on error.
*/
public PrivateKeyUsageExtension(Boolean critical, Object value)
- throws CertificateException, IOException {
+ throws CertificateException, IOException {
this.extensionId = PKIXExtensions.PrivateKeyUsage_Id;
this.critical = critical.booleanValue();
@@ -137,38 +138,38 @@ implements CertAttrSet {
throw new CertificateException("Illegal argument type");
int len = Array.getLength(value);
- byte[] extValue = new byte[len];
+ byte[] extValue = new byte[len];
System.arraycopy(value, 0, extValue, 0, len);
this.extensionValue = extValue;
- DerInputStream str = new DerInputStream(extValue);
- DerValue[] seq = str.getSequence(2);
+ DerInputStream str = new DerInputStream(extValue);
+ DerValue[] seq = str.getSequence(2);
- // NB. this is always encoded with the IMPLICIT tag
- // The checks only make sense if we assume implicit tagging,
- // with explicit tagging the form is always constructed.
- for (int i = 0; i < seq.length; i++) {
+ // NB. this is always encoded with the IMPLICIT tag
+ // The checks only make sense if we assume implicit tagging,
+ // with explicit tagging the form is always constructed.
+ for (int i = 0; i < seq.length; i++) {
DerValue opt = seq[i];
- if (opt.isContextSpecific((byte)TAG_BEFORE) &&
- !opt.isConstructed()) {
- if (notBefore != null) {
+ if (opt.isContextSpecific((byte) TAG_BEFORE) &&
+ !opt.isConstructed()) {
+ if (notBefore != null) {
throw new CertificateParsingException(
- "Duplicate notBefore in PrivateKeyUsage.");
- }
+ "Duplicate notBefore in PrivateKeyUsage.");
+ }
opt.resetTag(DerValue.tag_GeneralizedTime);
- str = new DerInputStream(opt.toByteArray());
- notBefore = str.getGeneralizedTime();
+ str = new DerInputStream(opt.toByteArray());
+ notBefore = str.getGeneralizedTime();
- } else if (opt.isContextSpecific((byte)TAG_AFTER) &&
+ } else if (opt.isContextSpecific((byte) TAG_AFTER) &&
!opt.isConstructed()) {
- if (notAfter != null) {
+ if (notAfter != null) {
throw new CertificateParsingException(
- "Duplicate notAfter in PrivateKeyUsage.");
- }
+ "Duplicate notAfter in PrivateKeyUsage.");
+ }
opt.resetTag(DerValue.tag_GeneralizedTime);
- str = new DerInputStream(opt.toByteArray());
- notAfter = str.getGeneralizedTime();
+ str = new DerInputStream(opt.toByteArray());
+ notAfter = str.getGeneralizedTime();
} else
throw new IOException("Invalid encoding of " +
"PrivateKeyUsageExtension");
@@ -179,7 +180,7 @@ implements CertAttrSet {
* Return the printable string.
*/
public String toString() {
- return(super.toString() +
+ return (super.toString() +
"PrivateKeyUsage: [From: " +
((notBefore == null) ? "" : notBefore.toString()) +
", To: " +
@@ -190,44 +191,44 @@ implements CertAttrSet {
* Return notBefore date
*/
public Date getNotBefore() {
- return(notBefore);
+ return (notBefore);
}
/**
* Return notAfter date
*/
public Date getNotAfter() {
- return(notAfter);
+ return (notAfter);
}
/**
* Verify that that the current time is within the validity period.
- *
+ *
* @exception CertificateExpiredException if the certificate has expired.
- * @exception CertificateNotYetValidException if the certificate is not
- * yet valid.
- */
+ * @exception CertificateNotYetValidException if the certificate is not yet
+ * valid.
+ */
public void valid()
- throws CertificateNotYetValidException, CertificateExpiredException {
+ throws CertificateNotYetValidException, CertificateExpiredException {
Date now = new Date();
valid(now);
}
/**
* Verify that that the passed time is within the validity period.
- *
+ *
* @exception CertificateExpiredException if the certificate has expired
- * with respect to the <code>Date</code> supplied.
- * @exception CertificateNotYetValidException if the certificate is not
- * yet valid with respect to the <code>Date</code> supplied.
- *
+ * with respect to the <code>Date</code> supplied.
+ * @exception CertificateNotYetValidException if the certificate is not yet
+ * valid with respect to the <code>Date</code> supplied.
+ *
*/
public void valid(Date now)
- throws CertificateNotYetValidException, CertificateExpiredException {
+ throws CertificateNotYetValidException, CertificateExpiredException {
/*
- * we use the internal Dates rather than the passed in Date
- * because someone could override the Date methods after()
- * and before() to do something entirely different.
+ * we use the internal Dates rather than the passed in Date because
+ * someone could override the Date methods after() and before() to do
+ * something entirely different.
*/
if (notBefore.after(now)) {
throw new CertificateNotYetValidException("NotBefore: " +
@@ -241,7 +242,7 @@ implements CertAttrSet {
/**
* Write the extension to the OutputStream.
- *
+ *
* @param out the OutputStream to write the extension to.
* @exception IOException on encoding errors.
*/
@@ -253,12 +254,12 @@ implements CertAttrSet {
encodeThis();
}
super.encode(tmp);
- out.write(tmp.toByteArray());
+ out.write(tmp.toByteArray());
}
/**
* Decode the extension from the InputStream.
- *
+ *
* @param in the InputStream to unmarshal the contents from.
* @exception CertificateException on decoding errors.
*/
@@ -268,52 +269,55 @@ implements CertAttrSet {
/**
* Set the attribute value.
+ *
* @exception CertificateException on attribute handling errors.
*/
public void set(String name, Object obj)
- throws CertificateException {
- clearValue();
+ throws CertificateException {
+ clearValue();
if (!(obj instanceof Date)) {
- throw new CertificateException("Attribute must be of type Date.");
- }
- if (name.equalsIgnoreCase(NOT_BEFORE)) {
- notBefore = (Date)obj;
- } else if (name.equalsIgnoreCase(NOT_AFTER)) {
- notAfter = (Date)obj;
- } else {
- throw new CertificateException("Attribute name not recognized by"
+ throw new CertificateException("Attribute must be of type Date.");
+ }
+ if (name.equalsIgnoreCase(NOT_BEFORE)) {
+ notBefore = (Date) obj;
+ } else if (name.equalsIgnoreCase(NOT_AFTER)) {
+ notAfter = (Date) obj;
+ } else {
+ throw new CertificateException("Attribute name not recognized by"
+ " CertAttrSet:PrivateKeyUsage.");
- }
+ }
}
/**
* Get the attribute value.
+ *
* @exception CertificateException on attribute handling errors.
*/
public Object get(String name) throws CertificateException {
- if (name.equalsIgnoreCase(NOT_BEFORE)) {
- return (new Date(notBefore.getTime()));
- } else if (name.equalsIgnoreCase(NOT_AFTER)) {
- return (new Date(notAfter.getTime()));
- } else {
- throw new CertificateException("Attribute name not recognized by"
+ if (name.equalsIgnoreCase(NOT_BEFORE)) {
+ return (new Date(notBefore.getTime()));
+ } else if (name.equalsIgnoreCase(NOT_AFTER)) {
+ return (new Date(notAfter.getTime()));
+ } else {
+ throw new CertificateException("Attribute name not recognized by"
+ " CertAttrSet:PrivateKeyUsage.");
- }
- }
+ }
+ }
/**
* Delete the attribute value.
+ *
* @exception CertificateException on attribute handling errors.
*/
public void delete(String name) throws CertificateException {
if (name.equalsIgnoreCase(NOT_BEFORE)) {
- notBefore = null;
- } else if (name.equalsIgnoreCase(NOT_AFTER)) {
- notAfter = null;
- } else {
- throw new CertificateException("Attribute name not recognized by"
+ notBefore = null;
+ } else if (name.equalsIgnoreCase(NOT_AFTER)) {
+ notAfter = null;
+ } else {
+ throw new CertificateException("Attribute name not recognized by"
+ " CertAttrSet:PrivateKeyUsage.");
- }
+ }
}
/**
@@ -322,11 +326,10 @@ implements CertAttrSet {
*/
public Enumeration<String> getAttributeNames() {
Vector<String> elements = new Vector<String>();
- elements.addElement(NOT_BEFORE);
- elements.addElement(NOT_AFTER);
-
- return(elements.elements());
+ elements.addElement(NOT_BEFORE);
+ elements.addElement(NOT_AFTER);
+
+ return (elements.elements());
}
-
}
diff --git a/pki/base/util/src/netscape/security/x509/Qualifier.java b/pki/base/util/src/netscape/security/x509/Qualifier.java
index 3d7168df..1016c44d 100644
--- a/pki/base/util/src/netscape/security/x509/Qualifier.java
+++ b/pki/base/util/src/netscape/security/x509/Qualifier.java
@@ -22,15 +22,11 @@ import java.io.IOException;
import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
-
/**
* Represent the Qualifier.
- *
- * Qualifier ::= CHOICE {
- * cPRuri CPSuri,
- * userNotice UserNotice
- * }
- *
+ *
+ * Qualifier ::= CHOICE { cPRuri CPSuri, userNotice UserNotice }
+ *
* @author Thomas Kwan
*/
public class Qualifier implements java.io.Serializable {
@@ -42,23 +38,23 @@ public class Qualifier implements java.io.Serializable {
/**
* Create a PolicyQualifierInfo
- *
+ *
* @param id the ObjectIdentifier for the policy id.
*/
public Qualifier() {
}
public Qualifier(DerValue val) throws IOException {
- // needs to override this
+ // needs to override this
}
/**
* Write the PolicyQualifier to the DerOutputStream.
- *
+ *
* @param out the DerOutputStream to write the object to.
* @exception IOException on errors.
*/
public void encode(DerOutputStream out) throws IOException {
- // needs to override this
+ // needs to override this
}
}
diff --git a/pki/base/util/src/netscape/security/x509/RDN.java b/pki/base/util/src/netscape/security/x509/RDN.java
index 3ea5afbc..ccb885c6 100644
--- a/pki/base/util/src/netscape/security/x509/RDN.java
+++ b/pki/base/util/src/netscape/security/x509/RDN.java
@@ -26,291 +26,276 @@ import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
import netscape.security.util.ObjectIdentifier;
-
/**
- * RDNs are a set of {attribute = value} assertions. Some of those
- * attributes are "distinguished" (unique w/in context). Order is
- * never relevant.
- *
- * Some X.500 names include only a single distinguished attribute
- * per RDN. This style is currently common.
- *
- * Note that DER-encoded RDNs sort AVAs by assertion OID ... so that
- * when we parse this data we don't have to worry about canonicalizing
- * it, but we'll need to sort them when we expose the RDN class more.
+ * RDNs are a set of {attribute = value} assertions. Some of those attributes
+ * are "distinguished" (unique w/in context). Order is never relevant.
+ *
+ * Some X.500 names include only a single distinguished attribute per RDN. This
+ * style is currently common.
+ *
+ * Note that DER-encoded RDNs sort AVAs by assertion OID ... so that when we
+ * parse this data we don't have to worry about canonicalizing it, but we'll
+ * need to sort them when we expose the RDN class more.
*
* @see X500Name
* @see AVA
* @see LdapDNStrConverter
*/
-public
-class RDN
-{
- // public constructors
+public class RDN {
+ // public constructors
- /**
- * Constructs a RDN from a Ldap DN String with one RDN component
- * using the global default LdapDNStrConverter.
+ /**
+ * Constructs a RDN from a Ldap DN String with one RDN component using the
+ * global default LdapDNStrConverter.
+ *
* @see LdapDNStrConverter
- * @param rdnString a Ldap DN string with one RDN component, e.g. as
- * defined in RFC1779.
- * @exception IOException if error occurs while parsing the string.
+ * @param rdnString a Ldap DN string with one RDN component, e.g. as defined
+ * in RFC1779.
+ * @exception IOException if error occurs while parsing the string.
*/
- public RDN (String rdnString)
- throws IOException
- {
- RDN rdn = LdapDNStrConverter.getDefault().parseRDN(rdnString);
- assertion = rdn.getAssertion();
+ public RDN(String rdnString)
+ throws IOException {
+ RDN rdn = LdapDNStrConverter.getDefault().parseRDN(rdnString);
+ assertion = rdn.getAssertion();
}
/**
- * Like RDN(String) with a DER encoding order given as argument for
+ * Like RDN(String) with a DER encoding order given as argument for
* Directory Strings.
*/
- public RDN (String rdnString, byte[] tags)
- throws IOException
- {
- RDN rdn = LdapDNStrConverter.getDefault().parseRDN(rdnString, tags);
- assertion = rdn.getAssertion();
+ public RDN(String rdnString, byte[] tags)
+ throws IOException {
+ RDN rdn = LdapDNStrConverter.getDefault().parseRDN(rdnString, tags);
+ assertion = rdn.getAssertion();
}
- /**
- * Constructs a RDN from a Ldap DN string with one RDN component
- * using the specified Ldap DN Str converter.
- * For example, RFC1779StrConverter can be passed to parse a Ldap
- * DN string in RFC1779 format.
+ /**
+ * Constructs a RDN from a Ldap DN string with one RDN component using the
+ * specified Ldap DN Str converter. For example, RFC1779StrConverter can be
+ * passed to parse a Ldap DN string in RFC1779 format.
+ *
* @see LdapDNStrConverter
* @param rdnString Ldap DN string.
* @param ldapDNStrConverter a LdapDNStrConverter.
*/
- public RDN (String rdnString, LdapDNStrConverter ldapDNStrConverter)
- throws IOException
- {
- RDN rdn = ldapDNStrConverter.parseRDN(rdnString);
- assertion = rdn.getAssertion();
+ public RDN(String rdnString, LdapDNStrConverter ldapDNStrConverter)
+ throws IOException {
+ RDN rdn = ldapDNStrConverter.parseRDN(rdnString);
+ assertion = rdn.getAssertion();
}
- /**
- * Constructs a RDN from a DerValue.
+ /**
+ * Constructs a RDN from a DerValue.
+ *
* @param set Der value of a set of AVAs.
*/
- public RDN (DerValue set) throws IOException
- {
- if (set.tag != DerValue.tag_Set)
- throw new CertParseError ("X500 RDN");
-
- int j_max = 50; // XXX j_max = f(data)!!
- int j;
- int i;
-
- AVA[] avas = new AVA [j_max];
-
-// create a temporary array big enough for a huge set of AVA's
- for (j = 0; j < j_max; j++) {
- avas [j] = new AVA (set.data);
- if (set.data.available() == 0) break;
- }
-
-// copy the elements into it
- if (j >= j_max-1) {
- assertion = new AVA[j+1];
- }
- else {
- assertion = new AVA[j+1];
- for (i = 0; i<(j+1); i++) {
- assertion[i] = avas[i];
- }
- }
-
- /*
- if (set.data.available () != 0)
- // throw new CertParseError ("X500 RDN 2");
- System.out.println (" ... RDN parse, ignored bytes = "
- + set.data.available ());
- */
+ public RDN(DerValue set) throws IOException {
+ if (set.tag != DerValue.tag_Set)
+ throw new CertParseError("X500 RDN");
+
+ int j_max = 50; // XXX j_max = f(data)!!
+ int j;
+ int i;
+
+ AVA[] avas = new AVA[j_max];
+
+ // create a temporary array big enough for a huge set of AVA's
+ for (j = 0; j < j_max; j++) {
+ avas[j] = new AVA(set.data);
+ if (set.data.available() == 0)
+ break;
+ }
+
+ // copy the elements into it
+ if (j >= j_max - 1) {
+ assertion = new AVA[j + 1];
+ } else {
+ assertion = new AVA[j + 1];
+ for (i = 0; i < (j + 1); i++) {
+ assertion[i] = avas[i];
+ }
+ }
+
+ /*
+ * if (set.data.available () != 0) // throw new CertParseError
+ * ("X500 RDN 2"); System.out.println
+ * (" ... RDN parse, ignored bytes = " + set.data.available ());
+ */
}
- /**
+ /**
* Constructs a RDN from a Der Input Stream.
+ *
* @param in a Der Input Stream.
*/
- public RDN (DerInputStream in) throws IOException
- {
- /* an RDN is a SET of avas */
- DerValue avaset[] = in.getSet(1);
- int i;
- assertion = new AVA[avaset.length];
- for (i = 0; i < assertion.length; i++)
- assertion[i] = new AVA(avaset[i].data);
+ public RDN(DerInputStream in) throws IOException {
+ /* an RDN is a SET of avas */
+ DerValue avaset[] = in.getSet(1);
+ int i;
+ assertion = new AVA[avaset.length];
+ for (i = 0; i < assertion.length; i++)
+ assertion[i] = new AVA(avaset[i].data);
}
/**
* Constructs a RDN from an array of AVA.
- *
- * @param avas a AVA Array.
+ *
+ * @param avas a AVA Array.
*/
- public RDN(AVA avas[])
- {
- assertion = (AVA[])avas.clone();
+ public RDN(AVA avas[]) {
+ assertion = (AVA[]) avas.clone();
}
/**
* convenience method.
*/
- public RDN(Vector<AVA> avaVector)
- {
- int size = avaVector.size();
- assertion = new AVA[size];
- for (int i = 0; i < size; i++) {
- assertion[i] = avaVector.elementAt(i);
- }
+ public RDN(Vector<AVA> avaVector) {
+ int size = avaVector.size();
+ assertion = new AVA[size];
+ for (int i = 0; i < size; i++) {
+ assertion[i] = avaVector.elementAt(i);
+ }
}
- /**
+ /**
* returns an array of AVA in the RDN.
+ *
* @return array of AVA in this RDN.
*/
- public AVA[] getAssertion()
- {
- return (AVA[])assertion.clone();
+ public AVA[] getAssertion() {
+ return (AVA[]) assertion.clone();
}
- /**
+ /**
* returns the number of AVAs in the RDN.
+ *
* @return number of AVAs in this RDN.
*/
- public int getAssertionLength()
- {
- return assertion.length;
+ public int getAssertionLength() {
+ return assertion.length;
}
- private AVA assertion [];
+ private AVA assertion[];
- private class AVAEnumerator implements Enumeration<AVA>
- {
- private int index;
+ private class AVAEnumerator implements Enumeration<AVA> {
+ private int index;
- public AVAEnumerator() { index = 0; }
+ public AVAEnumerator() {
+ index = 0;
+ }
- public boolean hasMoreElements()
- {
- return (index < assertion.length);
- }
+ public boolean hasMoreElements() {
+ return (index < assertion.length);
+ }
- public AVA nextElement()
- {
- AVA ava = null;
- if (index >= assertion.length)
- return null;
- return assertion[index++];
- }
+ public AVA nextElement() {
+ AVA ava = null;
+ if (index >= assertion.length)
+ return null;
+ return assertion[index++];
+ }
}
-
// other public methods.
- /**
- * Checks if this RDN is the same as another by comparing the AVAs
- * in the RDNs.
- *
+ /**
+ * Checks if this RDN is the same as another by comparing the AVAs in the
+ * RDNs.
+ *
* @param other the other RDN.
* @return true iff the other RDN is the same.
*/
- public boolean equals (RDN other)
- {
- int i;
-
- if (other == this)
- return true;
- if (assertion.length != other.assertion.length)
- return false;
-
- for (i = 0; i < assertion.length; i++)
- if (!assertion [i].equals (other.assertion [i]))
- return false;
-
- return true;
+ public boolean equals(RDN other) {
+ int i;
+
+ if (other == this)
+ return true;
+ if (assertion.length != other.assertion.length)
+ return false;
+
+ for (i = 0; i < assertion.length; i++)
+ if (!assertion[i].equals(other.assertion[i]))
+ return false;
+
+ return true;
}
- DerValue findAttribute (ObjectIdentifier oid)
- {
- int i;
+ DerValue findAttribute(ObjectIdentifier oid) {
+ int i;
- for (i = 0; i < assertion.length; i++)
- if (assertion [i].oid.equals (oid))
- return assertion [i].value;
- return null;
+ for (i = 0; i < assertion.length; i++)
+ if (assertion[i].oid.equals(oid))
+ return assertion[i].value;
+ return null;
}
- /**
+ /**
* Encodes this RDN to a Der output stream.
- *
+ *
* @param out the Der Output Stream.
*/
- public void encode(DerOutputStream out) throws IOException
- {
- DerOutputStream tmp = new DerOutputStream ();
- int i;
-
- for (i = 0; i < assertion.length; i++)
- assertion [i].encode (tmp);
- out.write (DerValue.tag_Set, tmp);
+ public void encode(DerOutputStream out) throws IOException {
+ DerOutputStream tmp = new DerOutputStream();
+ int i;
+
+ for (i = 0; i < assertion.length; i++)
+ assertion[i].encode(tmp);
+ out.write(DerValue.tag_Set, tmp);
}
- /**
+ /**
* returns an enumeration of AVAs that make up this RDN.
+ *
* @return an enumeration of AVAs that make up this RDN.
*/
- public Enumeration<AVA> getAVAs()
- {
- return new AVAEnumerator();
+ public Enumeration<AVA> getAVAs() {
+ return new AVAEnumerator();
}
/**
- * Returns a Ldap DN string with one RDN component using the
- * global default LdapDNStrConverter.
+ * Returns a Ldap DN string with one RDN component using the global default
+ * LdapDNStrConverter.
+ *
* @see LdapDNStrConverter
* @return the Ldap DN String of this RDN.
* @exception IOException if an error occurs during the conversion.
*/
- public String toLdapDNString ()
- throws IOException
- {
- return LdapDNStrConverter.getDefault().encodeRDN(this);
+ public String toLdapDNString()
+ throws IOException {
+ return LdapDNStrConverter.getDefault().encodeRDN(this);
}
/**
* Returns a Ldap DN String with this RDN component using the specified
* LdapDNStrConverter.
+ *
* @see LdapDNStrConverter
* @param ldapDNStrConverter a LdapDNStrConverter.
* @return a Ldap DN String.
* @exception IOException if an error occurs in the conversion.
*/
- public String toLdapDNString (LdapDNStrConverter ldapDNStrConverter)
- throws IOException
- {
- return ldapDNStrConverter.encodeRDN(this);
+ public String toLdapDNString(LdapDNStrConverter ldapDNStrConverter)
+ throws IOException {
+ return ldapDNStrConverter.encodeRDN(this);
}
/**
- * Returns a Ldap DN string with this RDN component using the global
- * default LdapDNStrConverter.
+ * Returns a Ldap DN string with this RDN component using the global default
+ * LdapDNStrConverter.
+ *
* @see LdapDNStrConverter
* @return the Ldap DN String with this RDN component, null if an error
- * occurs in the conversion.
+ * occurs in the conversion.
*/
- public String toString()
- {
- String s;
- try {
- s = toLdapDNString();
- }
- catch (IOException e) {
- return null;
- }
- return s;
+ public String toString() {
+ String s;
+ try {
+ s = toLdapDNString();
+ } catch (IOException e) {
+ return null;
+ }
+ return s;
}
}
diff --git a/pki/base/util/src/netscape/security/x509/RFC1779StrConverter.java b/pki/base/util/src/netscape/security/x509/RFC1779StrConverter.java
index 89383231..3a51274c 100644
--- a/pki/base/util/src/netscape/security/x509/RFC1779StrConverter.java
+++ b/pki/base/util/src/netscape/security/x509/RFC1779StrConverter.java
@@ -24,84 +24,79 @@ import netscape.security.util.ObjectIdentifier;
/**
* Converts a RFC 1779 string to a X500Name, RDN or AVA object and vice versa.
- *
+ *
* @see LdapDNStrConverter
* @see LdapV3DNStrConverter
- *
+ *
* @author Lily Hsiao, Slava Galperin at Netscape Communications, Inc.
*/
-public class RFC1779StrConverter extends LdapV3DNStrConverter
-{
+public class RFC1779StrConverter extends LdapV3DNStrConverter {
//
// Constructors.
- //
+ //
- /**
- * Constructs a RFC1779StrConverter using the global default
- * X500NameAttrMap and accepts OIDs not listed in the attribute map.
+ /**
+ * Constructs a RFC1779StrConverter using the global default X500NameAttrMap
+ * and accepts OIDs not listed in the attribute map.
*/
- public RFC1779StrConverter()
- {
- super();
+ public RFC1779StrConverter() {
+ super();
}
/**
- * Constructs a RFC1779StrConverter using the specified X500NameAttrMap
- * and boolean for whether to accept OIDs not in the X500NameAttrMap.
+ * Constructs a RFC1779StrConverter using the specified X500NameAttrMap and
+ * boolean for whether to accept OIDs not in the X500NameAttrMap.
*
- * @param attributeMap A X500NameAttrMap to use for this converter.
- * @param doAcceptUnknownOids Accept unregistered attributes, i.e. OIDs
- * not in the map).
+ * @param attributeMap A X500NameAttrMap to use for this converter.
+ * @param doAcceptUnknownOids Accept unregistered attributes, i.e. OIDs not
+ * in the map).
*/
- public RFC1779StrConverter(X500NameAttrMap attributeMap,
- boolean doAcceptUnknownOids)
- {
- super(attributeMap, doAcceptUnknownOids);
+ public RFC1779StrConverter(X500NameAttrMap attributeMap,
+ boolean doAcceptUnknownOids) {
+ super(attributeMap, doAcceptUnknownOids);
}
//
// overriding methods.
//
- /**
- * Converts a OID to a attribute keyword in a Ldap DN string or
- * to a "OID.1.2.3.4" string syntax as defined in RFC1779.
- *
- * @param oid an ObjectIdentifier.
- *
- * @return a attribute keyword or "OID.1.2.3.4" string.
- *
- * @exception IOException if an error occurs during the conversion.
+ /**
+ * Converts a OID to a attribute keyword in a Ldap DN string or to a
+ * "OID.1.2.3.4" string syntax as defined in RFC1779.
+ *
+ * @param oid an ObjectIdentifier.
+ *
+ * @return a attribute keyword or "OID.1.2.3.4" string.
+ *
+ * @exception IOException if an error occurs during the conversion.
*/
public String encodeOID(ObjectIdentifier oid)
- throws IOException
- {
- String keyword = attrMap.getName(oid);
- if (keyword == null)
- if (!acceptUnknownOids)
- throw new IllegalArgumentException("Unrecognized OID");
- else
- keyword = "OID" + "." + oid.toString();
- return keyword;
+ throws IOException {
+ String keyword = attrMap.getName(oid);
+ if (keyword == null)
+ if (!acceptUnknownOids)
+ throw new IllegalArgumentException("Unrecognized OID");
+ else
+ keyword = "OID" + "." + oid.toString();
+ return keyword;
}
- /**
- * Converts a attribute value as a DerValue to a string in a
- * RFC1779 Ldap DN string.
- *
- * @param attrValue an attribute value.
- * @param oid ObjectIdentifier for the attribute.
- * @return a string in RFC1779 syntax.
- * @exception IOException if an error occurs during the conversion.
+ /**
+ * Converts a attribute value as a DerValue to a string in a RFC1779 Ldap DN
+ * string.
+ *
+ * @param attrValue an attribute value.
+ * @param oid ObjectIdentifier for the attribute.
+ * @return a string in RFC1779 syntax.
+ * @exception IOException if an error occurs during the conversion.
*/
public String encodeValue(DerValue attrValue, ObjectIdentifier oid)
- throws IOException
- {
- String s = super.encodeValue(attrValue, oid);
- if (s.indexOf('\n') != -1)
- return "\""+s+"\"";
- else
- return s;
+ throws IOException {
+ String s = super.encodeValue(attrValue, oid);
+ if (s.indexOf('\n') != -1)
+ return "\"" + s + "\"";
+ else
+ return s;
}
}
diff --git a/pki/base/util/src/netscape/security/x509/RFC822Name.java b/pki/base/util/src/netscape/security/x509/RFC822Name.java
index 236e5ecb..e18ec82a 100644
--- a/pki/base/util/src/netscape/security/x509/RFC822Name.java
+++ b/pki/base/util/src/netscape/security/x509/RFC822Name.java
@@ -23,9 +23,9 @@ import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
/**
- * This class implements the RFC822Name as required by the GeneralNames
- * ASN.1 object.
- *
+ * This class implements the RFC822Name as required by the GeneralNames ASN.1
+ * object.
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.3
@@ -33,8 +33,7 @@ import netscape.security.util.DerValue;
* @see GeneralNames
* @see GeneralNameInterface
*/
-public class RFC822Name implements GeneralNameInterface
-{
+public class RFC822Name implements GeneralNameInterface {
/**
*
*/
@@ -43,7 +42,7 @@ public class RFC822Name implements GeneralNameInterface
/**
* Create the RFC822Name object from the passed encoded Der value.
- *
+ *
* @param derValue the encoded DER RFC822Name.
* @exception IOException on error.
*/
@@ -53,7 +52,7 @@ public class RFC822Name implements GeneralNameInterface
/**
* Create the RFC822Name object with the specified name.
- *
+ *
* @param name the RFC822Name.
*/
public RFC822Name(String name) {
@@ -69,7 +68,7 @@ public class RFC822Name implements GeneralNameInterface
/**
* Encode the RFC822 name into the DerOutputStream.
- *
+ *
* @param out the DER stream to encode the RFC822Name to.
* @exception IOException on encoding errors.
*/
diff --git a/pki/base/util/src/netscape/security/x509/ReasonFlags.java b/pki/base/util/src/netscape/security/x509/ReasonFlags.java
index 809323ad..8e54877c 100755
--- a/pki/base/util/src/netscape/security/x509/ReasonFlags.java
+++ b/pki/base/util/src/netscape/security/x509/ReasonFlags.java
@@ -28,10 +28,11 @@ import netscape.security.util.DerValue;
/**
* Represent the CRL Reason Flags.
- *
- * <p>This extension, if present, defines the identifies
- * the reason for the certificate revocation.
- *
+ *
+ * <p>
+ * This extension, if present, defines the identifies the reason for the
+ * certificate revocation.
+ *
* @author Hemma Prafullchandra
* @version 1.3
* @see Extension
@@ -47,19 +48,17 @@ public class ReasonFlags {
public static final String CA_COMPROMISE = "ca_compromise";
public static final String AFFLIATION_CHANGED = "affliation_changed";
public static final String SUPERSEDED = "superseded";
- public static final String CESSATION_OF_OPERATION
- = "cessation_of_operation";
+ public static final String CESSATION_OF_OPERATION = "cessation_of_operation";
public static final String CERTIFICATION_HOLD = "certification_hold";
public static final String PRIVILEGE_WITHDRAWN = "privilege_withdrawn";
public static final String AA_COMPROMISE = "aa_compromise";
-
// Private data members
private boolean[] bitString;
/**
* Check if bit is set.
- *
+ *
* @param position the position in the bit string to check.
*/
private boolean isSet(int position) {
@@ -70,27 +69,27 @@ public class ReasonFlags {
* Set the bit at the specified position.
*/
private void set(int position, boolean val) {
- // enlarge bitString if necessary
+ // enlarge bitString if necessary
if (position >= bitString.length) {
- boolean[] tmp = new boolean[position+1];
+ boolean[] tmp = new boolean[position + 1];
System.arraycopy(bitString, 0, tmp, 0, bitString.length);
bitString = tmp;
}
- bitString[position] = val;
+ bitString[position] = val;
}
/**
* Create a ReasonFlags with the passed bit settings.
- *
+ *
* @param reasons the bits to be set for the ReasonFlags.
*/
public ReasonFlags(byte[] reasons) {
- bitString = new BitArray(reasons.length*8, reasons).toBooleanArray();
+ bitString = new BitArray(reasons.length * 8, reasons).toBooleanArray();
}
/**
* Create a ReasonFlags with the passed bit settings.
- *
+ *
* @param reasons the bits to be set for the ReasonFlags.
*/
public ReasonFlags(boolean[] reasons) {
@@ -99,7 +98,7 @@ public class ReasonFlags {
/**
* Create a ReasonFlags with the passed bit settings.
- *
+ *
* @param reasons the bits to be set for the ReasonFlags.
*/
public ReasonFlags(BitArray reasons) {
@@ -108,10 +107,10 @@ public class ReasonFlags {
/**
* Create the object from the passed DER encoded value.
- *
+ *
* @param in the DerInputStream to read the ReasonFlags from.
* @exception IOException on decoding errors.
- */
+ */
public ReasonFlags(DerInputStream in) throws IOException {
DerValue derVal = in.getDerValue();
this.bitString = derVal.getUnalignedBitString(true).toBooleanArray();
@@ -119,10 +118,10 @@ public class ReasonFlags {
/**
* Create the object from the passed DER encoded value.
- *
+ *
* @param derVal the DerValue decoded from the stream.
* @exception IOException on decoding errors.
- */
+ */
public ReasonFlags(DerValue derVal) throws IOException {
this.bitString = derVal.getUnalignedBitString(true).toBooleanArray();
}
@@ -132,84 +131,84 @@ public class ReasonFlags {
*/
public void set(String name, Object obj) throws IOException {
if (!(obj instanceof Boolean)) {
- throw new IOException("Attribute must be of type Boolean.");
- }
- boolean val = ((Boolean)obj).booleanValue();
- if (name.equalsIgnoreCase(UNUSED)) {
- set(0,val);
- } else if (name.equalsIgnoreCase(KEY_COMPROMISE)) {
- set(1,val);
- } else if (name.equalsIgnoreCase(CA_COMPROMISE)) {
- set(2,val);
- } else if (name.equalsIgnoreCase(AFFLIATION_CHANGED)) {
- set(3,val);
- } else if (name.equalsIgnoreCase(SUPERSEDED)) {
- set(4,val);
- } else if (name.equalsIgnoreCase(CESSATION_OF_OPERATION)) {
- set(5,val);
- } else if (name.equalsIgnoreCase(CERTIFICATION_HOLD)) {
- set(6,val);
- } else if (name.equalsIgnoreCase(PRIVILEGE_WITHDRAWN)) {
- set(7,val);
- } else if (name.equalsIgnoreCase(AA_COMPROMISE)) {
- set(8,val);
- } else {
- throw new IOException("Name not recognized by ReasonFlags");
- }
+ throw new IOException("Attribute must be of type Boolean.");
+ }
+ boolean val = ((Boolean) obj).booleanValue();
+ if (name.equalsIgnoreCase(UNUSED)) {
+ set(0, val);
+ } else if (name.equalsIgnoreCase(KEY_COMPROMISE)) {
+ set(1, val);
+ } else if (name.equalsIgnoreCase(CA_COMPROMISE)) {
+ set(2, val);
+ } else if (name.equalsIgnoreCase(AFFLIATION_CHANGED)) {
+ set(3, val);
+ } else if (name.equalsIgnoreCase(SUPERSEDED)) {
+ set(4, val);
+ } else if (name.equalsIgnoreCase(CESSATION_OF_OPERATION)) {
+ set(5, val);
+ } else if (name.equalsIgnoreCase(CERTIFICATION_HOLD)) {
+ set(6, val);
+ } else if (name.equalsIgnoreCase(PRIVILEGE_WITHDRAWN)) {
+ set(7, val);
+ } else if (name.equalsIgnoreCase(AA_COMPROMISE)) {
+ set(8, val);
+ } else {
+ throw new IOException("Name not recognized by ReasonFlags");
+ }
}
/**
* Get the attribute value.
*/
public Object get(String name) throws IOException {
- if (name.equalsIgnoreCase(UNUSED)) {
- return new Boolean(isSet(0));
- } else if (name.equalsIgnoreCase(KEY_COMPROMISE)) {
- return new Boolean(isSet(1));
- } else if (name.equalsIgnoreCase(CA_COMPROMISE)) {
- return new Boolean(isSet(2));
- } else if (name.equalsIgnoreCase(AFFLIATION_CHANGED)) {
- return new Boolean(isSet(3));
- } else if (name.equalsIgnoreCase(SUPERSEDED)) {
- return new Boolean(isSet(4));
- } else if (name.equalsIgnoreCase(CESSATION_OF_OPERATION)) {
- return new Boolean(isSet(5));
- } else if (name.equalsIgnoreCase(CERTIFICATION_HOLD)) {
- return new Boolean(isSet(6));
- } else if (name.equalsIgnoreCase(PRIVILEGE_WITHDRAWN)) {
- return new Boolean(isSet(7));
- } else if (name.equalsIgnoreCase(AA_COMPROMISE)) {
- return new Boolean(isSet(8));
- } else {
- throw new IOException("Name not recognized by ReasonFlags");
- }
+ if (name.equalsIgnoreCase(UNUSED)) {
+ return new Boolean(isSet(0));
+ } else if (name.equalsIgnoreCase(KEY_COMPROMISE)) {
+ return new Boolean(isSet(1));
+ } else if (name.equalsIgnoreCase(CA_COMPROMISE)) {
+ return new Boolean(isSet(2));
+ } else if (name.equalsIgnoreCase(AFFLIATION_CHANGED)) {
+ return new Boolean(isSet(3));
+ } else if (name.equalsIgnoreCase(SUPERSEDED)) {
+ return new Boolean(isSet(4));
+ } else if (name.equalsIgnoreCase(CESSATION_OF_OPERATION)) {
+ return new Boolean(isSet(5));
+ } else if (name.equalsIgnoreCase(CERTIFICATION_HOLD)) {
+ return new Boolean(isSet(6));
+ } else if (name.equalsIgnoreCase(PRIVILEGE_WITHDRAWN)) {
+ return new Boolean(isSet(7));
+ } else if (name.equalsIgnoreCase(AA_COMPROMISE)) {
+ return new Boolean(isSet(8));
+ } else {
+ throw new IOException("Name not recognized by ReasonFlags");
+ }
}
/**
* Delete the attribute value.
*/
public void delete(String name) throws IOException {
- if (name.equalsIgnoreCase(UNUSED)) {
- set(0,false);
- } else if (name.equalsIgnoreCase(KEY_COMPROMISE)) {
- set(1,false);
- } else if (name.equalsIgnoreCase(CA_COMPROMISE)) {
- set(2,false);
- } else if (name.equalsIgnoreCase(AFFLIATION_CHANGED)) {
- set(3,false);
- } else if (name.equalsIgnoreCase(SUPERSEDED)) {
- set(4,false);
- } else if (name.equalsIgnoreCase(CESSATION_OF_OPERATION)) {
- set(5,false);
- } else if (name.equalsIgnoreCase(CERTIFICATION_HOLD)) {
- set(6,false);
- } else if (name.equalsIgnoreCase(PRIVILEGE_WITHDRAWN)) {
- set(7,false);
- } else if (name.equalsIgnoreCase(AA_COMPROMISE)) {
- set(8,false);
- } else {
- throw new IOException("Name not recognized by ReasonFlags");
- }
+ if (name.equalsIgnoreCase(UNUSED)) {
+ set(0, false);
+ } else if (name.equalsIgnoreCase(KEY_COMPROMISE)) {
+ set(1, false);
+ } else if (name.equalsIgnoreCase(CA_COMPROMISE)) {
+ set(2, false);
+ } else if (name.equalsIgnoreCase(AFFLIATION_CHANGED)) {
+ set(3, false);
+ } else if (name.equalsIgnoreCase(SUPERSEDED)) {
+ set(4, false);
+ } else if (name.equalsIgnoreCase(CESSATION_OF_OPERATION)) {
+ set(5, false);
+ } else if (name.equalsIgnoreCase(CERTIFICATION_HOLD)) {
+ set(6, false);
+ } else if (name.equalsIgnoreCase(PRIVILEGE_WITHDRAWN)) {
+ set(7, false);
+ } else if (name.equalsIgnoreCase(AA_COMPROMISE)) {
+ set(8, false);
+ } else {
+ throw new IOException("Name not recognized by ReasonFlags");
+ }
}
/**
@@ -218,35 +217,36 @@ public class ReasonFlags {
public String toString() {
String s = super.toString() + "Reason Flags [\n";
- try {
- if (isSet(0)) {
- s += " Unused\n";
- }
- if (isSet(1)) {
- s += " Key Compromise\n";
- }
- if (isSet(2)) {
- s += " CA_Compromise\n";
- }
- if (isSet(3)) {
- s += " Affiliation_Changed\n";
- }
- if (isSet(4)) {
- s += " Superseded\n";
- }
- if (isSet(5)) {
- s += " Cessation Of Operation\n";
- }
- if (isSet(6)) {
- s += " Certificate Hold\n";
- }
- if (isSet(7)) {
- s += " Privilege Withdrawn\n";
- }
- if (isSet(8)) {
- s += " AA Compromise\n";
+ try {
+ if (isSet(0)) {
+ s += " Unused\n";
+ }
+ if (isSet(1)) {
+ s += " Key Compromise\n";
+ }
+ if (isSet(2)) {
+ s += " CA_Compromise\n";
+ }
+ if (isSet(3)) {
+ s += " Affiliation_Changed\n";
+ }
+ if (isSet(4)) {
+ s += " Superseded\n";
+ }
+ if (isSet(5)) {
+ s += " Cessation Of Operation\n";
+ }
+ if (isSet(6)) {
+ s += " Certificate Hold\n";
+ }
+ if (isSet(7)) {
+ s += " Privilege Withdrawn\n";
+ }
+ if (isSet(8)) {
+ s += " AA Compromise\n";
+ }
+ } catch (ArrayIndexOutOfBoundsException ex) {
}
- } catch (ArrayIndexOutOfBoundsException ex) {}
s += "]\n";
@@ -255,7 +255,7 @@ public class ReasonFlags {
/**
* Write the extension to the DerOutputStream.
- *
+ *
* @param out the DerOutputStream to write the extension to.
* @exception IOException on encoding errors.
*/
@@ -267,7 +267,7 @@ public class ReasonFlags {
* Return an enumeration of names of attributes existing within this
* attribute.
*/
- public Enumeration<String> getElements () {
+ public Enumeration<String> getElements() {
Vector<String> elements = new Vector<String>();
elements.addElement(UNUSED);
elements.addElement(KEY_COMPROMISE);
@@ -279,6 +279,6 @@ public class ReasonFlags {
elements.addElement(PRIVILEGE_WITHDRAWN);
elements.addElement(AA_COMPROMISE);
- return (elements.elements());
+ return (elements.elements());
}
}
diff --git a/pki/base/util/src/netscape/security/x509/RevocationReason.java b/pki/base/util/src/netscape/security/x509/RevocationReason.java
index fc8c9634..419eb177 100644
--- a/pki/base/util/src/netscape/security/x509/RevocationReason.java
+++ b/pki/base/util/src/netscape/security/x509/RevocationReason.java
@@ -17,11 +17,10 @@
// --- END COPYRIGHT BLOCK ---
package netscape.security.x509;
-
/**
* Represent the enumerated type used in CRLReason Extension of CRL entry.
- *
- *
+ *
+ *
* @author galperin
* @version $Revision$, $Date$
*/
@@ -46,10 +45,10 @@ public final class RevocationReason {
/**
* Create a RevocationReason with the passed integer value.
- *
+ *
* @param reason integer value of the enumeration alternative.
*/
- private RevocationReason(int reason){
+ private RevocationReason(int reason) {
this.mReason = reason;
}
@@ -57,44 +56,64 @@ public final class RevocationReason {
return mReason;
}
- public static RevocationReason fromInt(int reason) {
- if (reason == UNSPECIFIED.mReason) return UNSPECIFIED;
- if (reason == KEY_COMPROMISE.mReason) return KEY_COMPROMISE;
- if (reason == CA_COMPROMISE.mReason) return CA_COMPROMISE;
- if (reason == AFFILIATION_CHANGED.mReason) return AFFILIATION_CHANGED;
- if (reason == SUPERSEDED.mReason) return SUPERSEDED;
- if (reason == CESSATION_OF_OPERATION.mReason) return CESSATION_OF_OPERATION;
- if (reason == CERTIFICATE_HOLD.mReason) return CERTIFICATE_HOLD;
- if (reason == REMOVE_FROM_CRL.mReason) return REMOVE_FROM_CRL;
- if (reason == PRIVILEGE_WITHDRAWN.mReason) return PRIVILEGE_WITHDRAWN;
- if (reason == AA_COMPROMISE.mReason) return AA_COMPROMISE;
- return null;
+ public static RevocationReason fromInt(int reason) {
+ if (reason == UNSPECIFIED.mReason)
+ return UNSPECIFIED;
+ if (reason == KEY_COMPROMISE.mReason)
+ return KEY_COMPROMISE;
+ if (reason == CA_COMPROMISE.mReason)
+ return CA_COMPROMISE;
+ if (reason == AFFILIATION_CHANGED.mReason)
+ return AFFILIATION_CHANGED;
+ if (reason == SUPERSEDED.mReason)
+ return SUPERSEDED;
+ if (reason == CESSATION_OF_OPERATION.mReason)
+ return CESSATION_OF_OPERATION;
+ if (reason == CERTIFICATE_HOLD.mReason)
+ return CERTIFICATE_HOLD;
+ if (reason == REMOVE_FROM_CRL.mReason)
+ return REMOVE_FROM_CRL;
+ if (reason == PRIVILEGE_WITHDRAWN.mReason)
+ return PRIVILEGE_WITHDRAWN;
+ if (reason == AA_COMPROMISE.mReason)
+ return AA_COMPROMISE;
+ return null;
}
- public boolean equals(Object other) {
- if (this == other)
- return true;
- else if (other instanceof RevocationReason)
- return ((RevocationReason)other).mReason == mReason;
- else
- return false;
- }
+ public boolean equals(Object other) {
+ if (this == other)
+ return true;
+ else if (other instanceof RevocationReason)
+ return ((RevocationReason) other).mReason == mReason;
+ else
+ return false;
+ }
- public int hashCode() {
- return mReason;
- }
+ public int hashCode() {
+ return mReason;
+ }
- public String toString() {
- if (equals(UNSPECIFIED)) return "Unspecified";
- if (equals(KEY_COMPROMISE)) return "Key_Compromise";
- if (equals(CA_COMPROMISE)) return "CA_Compromise";
- if (equals(AFFILIATION_CHANGED)) return "Affiliation_Changed";
- if (equals(SUPERSEDED)) return "Superseded";
- if (equals(CESSATION_OF_OPERATION)) return "Cessation_of_Operation";
- if (equals(CERTIFICATE_HOLD)) return "Certificate_Hold";
- if (equals(REMOVE_FROM_CRL)) return "Remove_from_CRL";
- if (equals(PRIVILEGE_WITHDRAWN)) return "Privilege_Withdrawn";
- if (equals(AA_COMPROMISE)) return "AA_Compromise";
- return "[UNDEFINED]";
- }
+ public String toString() {
+ if (equals(UNSPECIFIED))
+ return "Unspecified";
+ if (equals(KEY_COMPROMISE))
+ return "Key_Compromise";
+ if (equals(CA_COMPROMISE))
+ return "CA_Compromise";
+ if (equals(AFFILIATION_CHANGED))
+ return "Affiliation_Changed";
+ if (equals(SUPERSEDED))
+ return "Superseded";
+ if (equals(CESSATION_OF_OPERATION))
+ return "Cessation_of_Operation";
+ if (equals(CERTIFICATE_HOLD))
+ return "Certificate_Hold";
+ if (equals(REMOVE_FROM_CRL))
+ return "Remove_from_CRL";
+ if (equals(PRIVILEGE_WITHDRAWN))
+ return "Privilege_Withdrawn";
+ if (equals(AA_COMPROMISE))
+ return "AA_Compromise";
+ return "[UNDEFINED]";
+ }
}
diff --git a/pki/base/util/src/netscape/security/x509/RevokedCertImpl.java b/pki/base/util/src/netscape/security/x509/RevokedCertImpl.java
index b588a368..d8a649be 100755
--- a/pki/base/util/src/netscape/security/x509/RevokedCertImpl.java
+++ b/pki/base/util/src/netscape/security/x509/RevokedCertImpl.java
@@ -67,306 +67,283 @@ import netscape.security.util.ObjectIdentifier;
* @version 1.6 97/12/10
*/
-public class RevokedCertImpl extends RevokedCertificate implements Serializable{
+public class RevokedCertImpl extends RevokedCertificate implements Serializable {
/**
*
*/
- private static final long serialVersionUID = -3449642360223397701L;
-
-
- private SerialNumber serialNumber;
- private Date revocationDate;
- private CRLExtensions extensions = null;
- private byte[] revokedCert;
- private final static boolean isExplicit = false;
-
- /**
- * Default constructor.
- */
- public RevokedCertImpl() {
- }
-
- /**
- * Constructs a revoked certificate entry using the serial number and
- * revocation date.
- *
- * @param num
- * the serial number of the revoked certificate.
- * @param date
- * the Date on which revocation took place.
- */
- public RevokedCertImpl(BigInteger num, Date date) {
- this.serialNumber = new SerialNumber(num);
- this.revocationDate = date;
- }
-
- /**
- * Constructs a revoked certificate entry using the serial number,
- * revocation date and the entry extensions.
- *
- * @param num
- * the serial number of the revoked certificate.
- * @param date
- * the Date on which revocation took place.
- * @param crlEntryExts
- * the extensions for this entry.
- */
- public RevokedCertImpl(BigInteger num, Date date, CRLExtensions crlEntryExts) {
- this.serialNumber = new SerialNumber(num);
- this.revocationDate = date;
- this.extensions = crlEntryExts;
- }
-
- public byte[] getEncoded() throws CRLException {
- // XXX NOT IMPLEMENTED
- if (revokedCert == null) {
- DerOutputStream os = new DerOutputStream();
- try {
- encode(os);
- } catch (Exception e) {
- // revokedCert = null;
- }
- revokedCert = os.toByteArray();
- }
- return revokedCert;
- }
-
- public boolean hasUnsupportedCriticalExtension() {
- // XXX NOT IMPLEMENTED
- return true;
- }
-
- /**
- * Sets extensions for this impl.
- *
- * @param crlEntryExts
- * CRLExtensions
- */
- public void setExtensions(CRLExtensions crlEntryExts) {
- this.extensions = crlEntryExts;
- }
-
- /**
- * Unmarshals a revoked certificate from its encoded form.
- *
- * @param revokedCert
- * the encoded bytes.
- * @exception CRLException
- * on parsing errors.
- * @exception X509ExtensionException
- * on extension handling errors.
- */
- public RevokedCertImpl(byte[] revokedCert) throws CRLException,
- X509ExtensionException {
- try {
- DerValue derValue = new DerValue(revokedCert);
- parse(derValue);
- } catch (IOException e) {
- throw new CRLException("Parsing error: " + e.toString());
- }
- }
-
- /**
- * Unmarshals a revoked certificate from its encoded form.
- *
- * @param derValue
- * the DER value containing the revoked certificate.
- * @exception CRLException
- * on parsing errors.
- * @exception X509ExtensionException
- * on extension handling errors.
- */
- public RevokedCertImpl(DerValue derValue) throws CRLException,
- X509ExtensionException {
- parse(derValue);
- }
-
- /**
- * Returns true if this revoked certificate entry has extensions, otherwise
- * false.
- *
- * @return true if this CRL entry has extensions, otherwise false.
- */
- public boolean hasExtensions() {
- if (extensions == null)
- return false;
- else
- return true;
- }
-
- /**
- * Decode a revoked certificate from an input stream.
- *
- * @param inStrm
- * an input stream holding at least one revoked certificate
- * @exception CRLException
- * on parsing errors.
- * @exception X509ExtensionException
- * on extension handling errors.
- */
- public void decode(InputStream inStrm) throws CRLException,
- X509ExtensionException {
- try {
- DerValue derValue = new DerValue(inStrm);
- parse(derValue);
- } catch (IOException e) {
- throw new CRLException("Parsing error: " + e.toString());
- }
- }
-
- /**
- * Encodes the revoked certificate to an output stream.
- *
- * @param outStrm
- * an output stream to which the encoded revoked certificate is
- * written.
- * @exception CRLException
- * on encoding errors.
- * @exception X509ExtensionException
- * on extension handling errors.
- */
- public void encode(DerOutputStream outStrm) throws CRLException,
- X509ExtensionException {
- try {
- if (revokedCert == null) {
- DerOutputStream tmp = new DerOutputStream();
- // sequence { serialNumber, revocationDate, extensions }
- serialNumber.encode(tmp);
-
- // from 2050 should encode GeneralizedTime
- tmp.putUTCTime(revocationDate);
-
- if (extensions != null)
- extensions.encode(tmp, isExplicit);
-
- DerOutputStream seq = new DerOutputStream();
- seq.write(DerValue.tag_Sequence, tmp);
-
- revokedCert = seq.toByteArray();
- }
- outStrm.write(revokedCert);
- } catch (IOException e) {
- throw new CRLException("Encoding error: " + e.toString());
- }
- }
-
- /**
- * Gets the serial number for this RevokedCertificate, the
- * <em>userCertificate</em>.
- *
- * @return the serial number.
- */
- public BigInteger getSerialNumber() {
- return ((BigInt) serialNumber.getNumber()).toBigInteger();
- }
-
- /**
- * Gets the revocation date for this RevokedCertificate, the
- * <em>revocationDate</em>.
- *
- * @return the revocation date.
- */
- public Date getRevocationDate() {
- return (new Date(revocationDate.getTime()));
- }
-
- /**
- * Returns extensions for this impl.
- *
- * @return the CRLExtensions
- */
- public CRLExtensions getExtensions() {
- return extensions;
- }
-
- /**
- * Returns a printable string of this revoked certificate.
- *
- * @return value of this revoked certificate in a printable form.
- */
- public String toString() {
- StringBuffer sb = new StringBuffer();
-
- sb.append(serialNumber.toString());
- sb.append(" On: " + revocationDate.toString());
- if (extensions != null) {
- sb.append("\n");
- for (int i = 0; i < extensions.size(); i++)
- sb.append("Entry Extension[" + i + "]: "
- + ((Extension) (extensions.elementAt(i))).toString());
- }
- sb.append("\n");
- return (sb.toString());
- }
+ private static final long serialVersionUID = -3449642360223397701L;
+
+ private SerialNumber serialNumber;
+ private Date revocationDate;
+ private CRLExtensions extensions = null;
+ private byte[] revokedCert;
+ private final static boolean isExplicit = false;
/**
- * Gets a Set of the extension(s) marked CRITICAL in the
- * RevokedCertificate by OID strings.
- *
- * @return a set of the extension oid strings in the
- * Object that are marked critical.
+ * Default constructor.
+ */
+ public RevokedCertImpl() {
+ }
+
+ /**
+ * Constructs a revoked certificate entry using the serial number and
+ * revocation date.
+ *
+ * @param num the serial number of the revoked certificate.
+ * @param date the Date on which revocation took place.
+ */
+ public RevokedCertImpl(BigInteger num, Date date) {
+ this.serialNumber = new SerialNumber(num);
+ this.revocationDate = date;
+ }
+
+ /**
+ * Constructs a revoked certificate entry using the serial number,
+ * revocation date and the entry extensions.
+ *
+ * @param num the serial number of the revoked certificate.
+ * @param date the Date on which revocation took place.
+ * @param crlEntryExts the extensions for this entry.
+ */
+ public RevokedCertImpl(BigInteger num, Date date, CRLExtensions crlEntryExts) {
+ this.serialNumber = new SerialNumber(num);
+ this.revocationDate = date;
+ this.extensions = crlEntryExts;
+ }
+
+ public byte[] getEncoded() throws CRLException {
+ // XXX NOT IMPLEMENTED
+ if (revokedCert == null) {
+ DerOutputStream os = new DerOutputStream();
+ try {
+ encode(os);
+ } catch (Exception e) {
+ // revokedCert = null;
+ }
+ revokedCert = os.toByteArray();
+ }
+ return revokedCert;
+ }
+
+ public boolean hasUnsupportedCriticalExtension() {
+ // XXX NOT IMPLEMENTED
+ return true;
+ }
+
+ /**
+ * Sets extensions for this impl.
+ *
+ * @param crlEntryExts CRLExtensions
+ */
+ public void setExtensions(CRLExtensions crlEntryExts) {
+ this.extensions = crlEntryExts;
+ }
+
+ /**
+ * Unmarshals a revoked certificate from its encoded form.
+ *
+ * @param revokedCert the encoded bytes.
+ * @exception CRLException on parsing errors.
+ * @exception X509ExtensionException on extension handling errors.
+ */
+ public RevokedCertImpl(byte[] revokedCert) throws CRLException,
+ X509ExtensionException {
+ try {
+ DerValue derValue = new DerValue(revokedCert);
+ parse(derValue);
+ } catch (IOException e) {
+ throw new CRLException("Parsing error: " + e.toString());
+ }
+ }
+
+ /**
+ * Unmarshals a revoked certificate from its encoded form.
+ *
+ * @param derValue the DER value containing the revoked certificate.
+ * @exception CRLException on parsing errors.
+ * @exception X509ExtensionException on extension handling errors.
+ */
+ public RevokedCertImpl(DerValue derValue) throws CRLException,
+ X509ExtensionException {
+ parse(derValue);
+ }
+
+ /**
+ * Returns true if this revoked certificate entry has extensions, otherwise
+ * false.
+ *
+ * @return true if this CRL entry has extensions, otherwise false.
+ */
+ public boolean hasExtensions() {
+ if (extensions == null)
+ return false;
+ else
+ return true;
+ }
+
+ /**
+ * Decode a revoked certificate from an input stream.
+ *
+ * @param inStrm an input stream holding at least one revoked certificate
+ * @exception CRLException on parsing errors.
+ * @exception X509ExtensionException on extension handling errors.
+ */
+ public void decode(InputStream inStrm) throws CRLException,
+ X509ExtensionException {
+ try {
+ DerValue derValue = new DerValue(inStrm);
+ parse(derValue);
+ } catch (IOException e) {
+ throw new CRLException("Parsing error: " + e.toString());
+ }
+ }
+
+ /**
+ * Encodes the revoked certificate to an output stream.
+ *
+ * @param outStrm an output stream to which the encoded revoked certificate
+ * is written.
+ * @exception CRLException on encoding errors.
+ * @exception X509ExtensionException on extension handling errors.
+ */
+ public void encode(DerOutputStream outStrm) throws CRLException,
+ X509ExtensionException {
+ try {
+ if (revokedCert == null) {
+ DerOutputStream tmp = new DerOutputStream();
+ // sequence { serialNumber, revocationDate, extensions }
+ serialNumber.encode(tmp);
+
+ // from 2050 should encode GeneralizedTime
+ tmp.putUTCTime(revocationDate);
+
+ if (extensions != null)
+ extensions.encode(tmp, isExplicit);
+
+ DerOutputStream seq = new DerOutputStream();
+ seq.write(DerValue.tag_Sequence, tmp);
+
+ revokedCert = seq.toByteArray();
+ }
+ outStrm.write(revokedCert);
+ } catch (IOException e) {
+ throw new CRLException("Encoding error: " + e.toString());
+ }
+ }
+
+ /**
+ * Gets the serial number for this RevokedCertificate, the
+ * <em>userCertificate</em>.
+ *
+ * @return the serial number.
+ */
+ public BigInteger getSerialNumber() {
+ return ((BigInt) serialNumber.getNumber()).toBigInteger();
+ }
+
+ /**
+ * Gets the revocation date for this RevokedCertificate, the
+ * <em>revocationDate</em>.
+ *
+ * @return the revocation date.
+ */
+ public Date getRevocationDate() {
+ return (new Date(revocationDate.getTime()));
+ }
+
+ /**
+ * Returns extensions for this impl.
+ *
+ * @return the CRLExtensions
+ */
+ public CRLExtensions getExtensions() {
+ return extensions;
+ }
+
+ /**
+ * Returns a printable string of this revoked certificate.
+ *
+ * @return value of this revoked certificate in a printable form.
+ */
+ public String toString() {
+ StringBuffer sb = new StringBuffer();
+
+ sb.append(serialNumber.toString());
+ sb.append(" On: " + revocationDate.toString());
+ if (extensions != null) {
+ sb.append("\n");
+ for (int i = 0; i < extensions.size(); i++)
+ sb.append("Entry Extension[" + i + "]: "
+ + ((Extension) (extensions.elementAt(i))).toString());
+ }
+ sb.append("\n");
+ return (sb.toString());
+ }
+
+ /**
+ * Gets a Set of the extension(s) marked CRITICAL in the RevokedCertificate
+ * by OID strings.
+ *
+ * @return a set of the extension oid strings in the Object that are marked
+ * critical.
*/
public Set<String> getCriticalExtensionOIDs() {
if (extensions == null)
return null;
Set<String> extSet = new TreeSet<String>();
Extension ex;
- for (Enumeration<Extension> e = extensions.getElements();
- e.hasMoreElements();) {
+ for (Enumeration<Extension> e = extensions.getElements(); e.hasMoreElements();) {
ex = e.nextElement();
- if (ex.isCritical())
+ if (ex.isCritical())
extSet.add(ex.getExtensionId().toString());
- }
+ }
return extSet;
}
/**
* Gets a Set of the extension(s) marked NON-CRITICAL in the
* RevokedCertificate by OID strings.
- *
- * @return a set of the extension oid strings in the
- * Object that are marked critical.
+ *
+ * @return a set of the extension oid strings in the Object that are marked
+ * critical.
*/
public Set<String> getNonCriticalExtensionOIDs() {
if (extensions == null)
return null;
Set<String> extSet = new TreeSet<String>();
Extension ex;
- for (Enumeration<Extension> e = extensions.getElements();
- e.hasMoreElements();) {
+ for (Enumeration<Extension> e = extensions.getElements(); e.hasMoreElements();) {
ex = e.nextElement();
- if ( ! ex.isCritical())
+ if (!ex.isCritical())
extSet.add(ex.getExtensionId().toString());
- }
+ }
return extSet;
}
/**
- * Gets the DER encoded OCTET string for the extension value
- * (<em>extnValue</em>) identified by the passed in oid String.
- * The <code>oid</code> string is
- * represented by a set of positive whole number separated
- * by ".", that means,<br>
+ * Gets the DER encoded OCTET string for the extension value (
+ * <em>extnValue</em>) identified by the passed in oid String. The
+ * <code>oid</code> string is represented by a set of positive whole number
+ * separated by ".", that means,<br>
* &lt;positive whole number&gt;.&lt;positive whole number&gt;.&lt;positive
* whole number&gt;.&lt;...&gt;
- *
+ *
* @param oid the Object Identifier value for the extension.
* @return the DER encoded octet string of the extension value.
*/
public byte[] getExtensionValue(String oid) {
if (extensions == null)
return null;
- try {
- String extAlias = OIDMap.getName(new ObjectIdentifier(oid));
+ try {
+ String extAlias = OIDMap.getName(new ObjectIdentifier(oid));
Extension crlExt = null;
if (extAlias == null) { // may be unknown
ObjectIdentifier findOID = new ObjectIdentifier(oid);
Extension ex = null;
ObjectIdentifier inCertOID;
- for (Enumeration<Extension> e=extensions.getElements();
- e.hasMoreElements();) {
+ for (Enumeration<Extension> e = extensions.getElements(); e.hasMoreElements();) {
ex = e.nextElement();
inCertOID = ex.getExtensionId();
if (inCertOID.equals(findOID)) {
@@ -376,24 +353,24 @@ public class RevokedCertImpl extends RevokedCertificate implements Serializable{
}
} else
crlExt = extensions.get(extAlias);
- if (crlExt == null)
+ if (crlExt == null)
return null;
- byte[] extData = crlExt.getExtensionValue();
+ byte[] extData = crlExt.getExtensionValue();
if (extData == null)
return null;
- DerOutputStream out = new DerOutputStream();
- out.putOctetString(extData);
+ DerOutputStream out = new DerOutputStream();
+ out.putOctetString(extData);
return out.toByteArray();
} catch (Exception e) {
return null;
- }
+ }
}
private void parse(DerValue derVal)
- throws CRLException, X509ExtensionException {
+ throws CRLException, X509ExtensionException {
- if (derVal.tag != DerValue.tag_Sequence) {
+ if (derVal.tag != DerValue.tag_Sequence) {
throw new CRLException("Invalid encoded RevokedCertificate, " +
"starting sequence tag missing.");
}
@@ -413,9 +390,9 @@ public class RevokedCertImpl extends RevokedCertificate implements Serializable{
// revocationDate
try {
int nextByte = derVal.data.peekByte();
- if ((byte)nextByte == DerValue.tag_UtcTime) {
+ if ((byte) nextByte == DerValue.tag_UtcTime) {
this.revocationDate = derVal.data.getUTCTime();
- } else if ((byte)nextByte == DerValue.tag_GeneralizedTime) {
+ } else if ((byte) nextByte == DerValue.tag_GeneralizedTime) {
this.revocationDate = derVal.data.getGeneralizedTime();
} else {
throw new CRLException("Invalid encoding for RevokedCertificates");
@@ -426,7 +403,7 @@ public class RevokedCertImpl extends RevokedCertificate implements Serializable{
}
if (derVal.data.available() == 0)
- return; // no extensions
+ return; // no extensions
// crlEntryExtensions
try {
@@ -437,25 +414,25 @@ public class RevokedCertImpl extends RevokedCertificate implements Serializable{
}
}
- /**
- * Serialization write ... X.509 certificates serialize as themselves, and
- * they're parsed when they get read back. (Actually they serialize as some
- * type data from the serialization subsystem, then the cert data.)
- */
- private synchronized void writeObject(ObjectOutputStream stream)
- throws CRLException, X509ExtensionException, IOException {
- DerOutputStream dos = new DerOutputStream();
- encode(dos);
- dos.derEncode(stream);
- }
-
- /**
- * Serialization read ... X.509 certificates serialize as themselves, and
- * they're parsed when they get read back.
- */
- private synchronized void readObject(ObjectInputStream stream)
- throws CRLException, X509ExtensionException, IOException {
- decode(stream);
- }
+ /**
+ * Serialization write ... X.509 certificates serialize as themselves, and
+ * they're parsed when they get read back. (Actually they serialize as some
+ * type data from the serialization subsystem, then the cert data.)
+ */
+ private synchronized void writeObject(ObjectOutputStream stream)
+ throws CRLException, X509ExtensionException, IOException {
+ DerOutputStream dos = new DerOutputStream();
+ encode(dos);
+ dos.derEncode(stream);
+ }
+
+ /**
+ * Serialization read ... X.509 certificates serialize as themselves, and
+ * they're parsed when they get read back.
+ */
+ private synchronized void readObject(ObjectInputStream stream)
+ throws CRLException, X509ExtensionException, IOException {
+ decode(stream);
+ }
}
diff --git a/pki/base/util/src/netscape/security/x509/RevokedCertificate.java b/pki/base/util/src/netscape/security/x509/RevokedCertificate.java
index 7db553ad..9d644aa7 100644
--- a/pki/base/util/src/netscape/security/x509/RevokedCertificate.java
+++ b/pki/base/util/src/netscape/security/x509/RevokedCertificate.java
@@ -23,74 +23,73 @@ import java.security.cert.X509CRLEntry;
import java.util.Date;
/**
- * <p>Abstract class for a revoked certificate in a CRL (Certificate
- * Revocation List).
- *
+ * <p>
+ * Abstract class for a revoked certificate in a CRL (Certificate Revocation
+ * List).
+ *
* The ASN.1 definition for <em>revokedCertificates</em> is:
+ *
* <pre>
- * revokedCertificates SEQUENCE OF SEQUENCE {
- * userCertificate CertificateSerialNumber,
- * revocationDate ChoiceOfTime,
- * crlEntryExtensions Extensions OPTIONAL
- * -- if present, must be v2
- * } OPTIONAL
- *<p>
- * CertificateSerialNumber ::= INTEGER
- *<p>
- * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
- *<p>
- * Extension ::= SEQUENCE {
- * extnId OBJECT IDENTIFIER,
- * critical BOOLEAN DEFAULT FALSE,
- * extnValue OCTET STRING
- * -- contains a DER encoding of a value
- * -- of the type registered for use with
- * -- the extnId object identifier value
- * }
+ * revokedCertificates SEQUENCE OF SEQUENCE {
+ * userCertificate CertificateSerialNumber,
+ * revocationDate ChoiceOfTime,
+ * crlEntryExtensions Extensions OPTIONAL
+ * -- if present, must be v2
+ * } OPTIONAL
+ * <p>
+ * CertificateSerialNumber ::= INTEGER
+ * <p>
+ * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
+ * <p>
+ * Extension ::= SEQUENCE {
+ * extnId OBJECT IDENTIFIER,
+ * critical BOOLEAN DEFAULT FALSE,
+ * extnValue OCTET STRING
+ * -- contains a DER encoding of a value
+ * -- of the type registered for use with
+ * -- the extnId object identifier value
+ * }
* </pre>
*
* @see X509CRL
- *
+ *
* @author Hemma Prafullchandra
* @version 1.4 97/12/10
*/
public abstract class RevokedCertificate extends X509CRLEntry {
-/* implements X509Extension { */
+ /* implements X509Extension { */
/**
- * Gets the serial number for this RevokedCertificate,
- * the <em>userCertificate</em>.
+ * Gets the serial number for this RevokedCertificate, the
+ * <em>userCertificate</em>.
*
* @return the serial number.
*/
public abstract BigInteger getSerialNumber();
/**
- * Gets the revocation date for this RevokedCertificate,
- * the <em>revocationDate</em>.
+ * Gets the revocation date for this RevokedCertificate, the
+ * <em>revocationDate</em>.
*
* @return the revocation date.
*/
public abstract Date getRevocationDate();
/**
- * Returns true if this revoked certificate entry has
- * extensions.
- *
+ * Returns true if this revoked certificate entry has extensions.
+ *
* @return true if this entry has extensions, false otherwise.
*/
public abstract boolean hasExtensions();
-
-
/**
* Returns a string representation of this revoked certificate.
- *
+ *
* @return a string representation of this revoked certificate.
*/
public abstract String toString();
-
+
public abstract CRLExtensions getExtensions();
}
diff --git a/pki/base/util/src/netscape/security/x509/SerialNumber.java b/pki/base/util/src/netscape/security/x509/SerialNumber.java
index c59b03e0..a2d7109c 100644
--- a/pki/base/util/src/netscape/security/x509/SerialNumber.java
+++ b/pki/base/util/src/netscape/security/x509/SerialNumber.java
@@ -28,13 +28,13 @@ import netscape.security.util.DerValue;
/**
* This class defines the SerialNumber class used by certificates.
- *
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.5
*/
public class SerialNumber {
- private BigInt serialNum;
+ private BigInt serialNum;
// Construct the class from the DerValue
private void construct(DerValue derVal) throws IOException {
@@ -46,7 +46,7 @@ public class SerialNumber {
/**
* The default constructor for this class using BigInteger.
- *
+ *
* @param num the BigInteger number used to create the serial number.
*/
public SerialNumber(BigInteger num) {
@@ -56,10 +56,10 @@ public class SerialNumber {
public SerialNumber(BigInt num) {
serialNum = num;
}
-
+
/**
* The default constructor for this class using int.
- *
+ *
* @param num the BigInteger number used to create the serial number.
*/
public SerialNumber(int num) {
@@ -68,7 +68,7 @@ public class SerialNumber {
/**
* Create the object, decoding the values from the passed DER stream.
- *
+ *
* @param in the DerInputStream to read the SerialNumber from.
* @exception IOException on decoding errors.
*/
@@ -79,7 +79,7 @@ public class SerialNumber {
/**
* Create the object, decoding the values from the passed DerValue.
- *
+ *
* @param val the DerValue to read the SerialNumber from.
* @exception IOException on decoding errors.
*/
@@ -89,7 +89,7 @@ public class SerialNumber {
/**
* Create the object, decoding the values from the passed stream.
- *
+ *
* @param in the InputStream to read the SerialNumber from.
* @exception IOException on decoding errors.
*/
@@ -107,7 +107,7 @@ public class SerialNumber {
/**
* Encode the SerialNumber in DER form to the stream.
- *
+ *
* @param out the DerOutputStream to marshal the contents to.
* @exception IOException on errors.
*/
diff --git a/pki/base/util/src/netscape/security/x509/SubjectAlternativeNameExtension.java b/pki/base/util/src/netscape/security/x509/SubjectAlternativeNameExtension.java
index 53f4eadb..df0e0430 100644
--- a/pki/base/util/src/netscape/security/x509/SubjectAlternativeNameExtension.java
+++ b/pki/base/util/src/netscape/security/x509/SubjectAlternativeNameExtension.java
@@ -29,20 +29,23 @@ import netscape.security.util.DerValue;
/**
* This represents the Subject Alternative Name Extension.
- *
+ *
* This extension, if present, allows the subject to specify multiple
* alternative names.
- *
- * <p>Extensions are represented as a sequence of the extension identifier
- * (Object Identifier), a boolean flag stating whether the extension is to
- * be treated as being critical and the extension value itself (this is again
- * a DER encoding of the extension value).
+ *
+ * <p>
+ * Extensions are represented as a sequence of the extension identifier (Object
+ * Identifier), a boolean flag stating whether the extension is to be treated as
+ * being critical and the extension value itself (this is again a DER encoding
+ * of the extension value).
* <p>
* The ASN.1 syntax for this is:
+ *
* <pre>
* SubjectAltName ::= GeneralNames
* GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
* </pre>
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.9
@@ -50,15 +53,15 @@ import netscape.security.util.DerValue;
* @see CertAttrSet
*/
public class SubjectAlternativeNameExtension extends Extension
-implements CertAttrSet {
+ implements CertAttrSet {
/**
*
*/
private static final long serialVersionUID = -4022446008355607196L;
/**
- * Identifier for this attribute, to be used with the
- * get, set, delete methods of Certificate, x509 type.
- */
+ * Identifier for this attribute, to be used with the get, set, delete
+ * methods of Certificate, x509 type.
+ */
public static final String IDENT =
"x509.info.extensions.SubjectAlternativeName";
/**
@@ -67,7 +70,7 @@ implements CertAttrSet {
public static final String SUBJECT_NAME = "subject_name";
// private data members
- GeneralNames names;
+ GeneralNames names;
// Encode this extension
private void encodeThis() throws IOException {
@@ -82,19 +85,20 @@ implements CertAttrSet {
/**
* Create a SubjectAlternativeNameExtension with the passed GeneralNames.
- *
+ *
* @param names the GeneralNames for the subject.
* @exception IOException on error.
*/
public SubjectAlternativeNameExtension(boolean critical, GeneralNames names)
- throws IOException {
+ throws IOException {
this.names = names;
this.extensionId = PKIXExtensions.SubjectAlternativeName_Id;
this.critical = critical;
encodeThis();
}
+
public SubjectAlternativeNameExtension(GeneralNames names)
- throws IOException {
+ throws IOException {
this.names = names;
this.extensionId = PKIXExtensions.SubjectAlternativeName_Id;
this.critical = false;
@@ -112,13 +116,13 @@ implements CertAttrSet {
/**
* Create the extension from the passed DER encoded value.
- *
+ *
* @param critical true if the extension is to be treated as critical.
* @param value Array of DER encoded bytes of the actual value.
* @exception IOException on error.
*/
public SubjectAlternativeNameExtension(Boolean critical, Object value)
- throws IOException {
+ throws IOException {
this.extensionId = PKIXExtensions.SubjectAlternativeName_Id;
this.critical = critical.booleanValue();
@@ -127,7 +131,7 @@ implements CertAttrSet {
+ "Illegal argument type");
int len = Array.getLength(value);
- byte[] extValue = new byte[len];
+ byte[] extValue = new byte[len];
System.arraycopy(value, 0, extValue, 0, len);
this.extensionValue = extValue;
@@ -137,21 +141,22 @@ implements CertAttrSet {
} catch (GeneralNamesException e) {
throw new IOException("SubjectAlternativeName: " + e);
}
- }
-
- /**
- * Returns a printable representation of the SubjectAlternativeName.
- */
- public String toString() {
- if (names == null) return "";
- String s = super.toString() + "SubjectAlternativeName [\n"
+ }
+
+ /**
+ * Returns a printable representation of the SubjectAlternativeName.
+ */
+ public String toString() {
+ if (names == null)
+ return "";
+ String s = super.toString() + "SubjectAlternativeName [\n"
+ names.toString() + "]\n";
- return (s);
- }
+ return (s);
+ }
/**
* Decode the extension from the InputStream.
- *
+ *
* @param in the InputStream to unmarshal the contents from.
* @exception IOException on decoding or validity errors.
*/
@@ -161,71 +166,71 @@ implements CertAttrSet {
/**
* Write the extension to the OutputStream.
- *
+ *
* @param out the OutputStream to write the extension to.
* @exception IOException on encoding errors.
*/
public void encode(OutputStream out) throws IOException {
DerOutputStream tmp = new DerOutputStream();
if (extensionValue == null) {
- extensionId = PKIXExtensions.SubjectAlternativeName_Id;
- //critical = false;
- encodeThis();
- }
- super.encode(tmp);
- out.write(tmp.toByteArray());
+ extensionId = PKIXExtensions.SubjectAlternativeName_Id;
+ // critical = false;
+ encodeThis();
+ }
+ super.encode(tmp);
+ out.write(tmp.toByteArray());
}
/**
* Set the attribute value.
*/
public void set(String name, Object obj) throws IOException {
- clearValue();
- if (name.equalsIgnoreCase(SUBJECT_NAME)) {
- if (!(obj instanceof GeneralNames)) {
- throw new IOException("Attribute value should be of " +
+ clearValue();
+ if (name.equalsIgnoreCase(SUBJECT_NAME)) {
+ if (!(obj instanceof GeneralNames)) {
+ throw new IOException("Attribute value should be of " +
"type GeneralNames.");
- }
- names = (GeneralNames)obj;
- } else {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:SubjectAlternativeName.");
- }
+ }
+ names = (GeneralNames) obj;
+ } else {
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:SubjectAlternativeName.");
+ }
}
/**
* Get the attribute value.
*/
public Object get(String name) throws IOException {
- if (name.equalsIgnoreCase(SUBJECT_NAME)) {
- return (names);
- } else {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:SubjectAlternativeName.");
- }
+ if (name.equalsIgnoreCase(SUBJECT_NAME)) {
+ return (names);
+ } else {
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:SubjectAlternativeName.");
+ }
}
/**
* Delete the attribute value.
*/
public void delete(String name) throws IOException {
- if (name.equalsIgnoreCase(SUBJECT_NAME)) {
- names = null;
- } else {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:SubjectAlternativeName.");
- }
+ if (name.equalsIgnoreCase(SUBJECT_NAME)) {
+ names = null;
+ } else {
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:SubjectAlternativeName.");
+ }
}
/**
* Return an enumeration of names of attributes existing within this
* attribute.
*/
- public Enumeration<String> getAttributeNames () {
+ public Enumeration<String> getAttributeNames() {
Vector<String> elements = new Vector<String>();
elements.addElement(SUBJECT_NAME);
- return (elements.elements());
+ return (elements.elements());
}
}
diff --git a/pki/base/util/src/netscape/security/x509/SubjectDirAttributesExtension.java b/pki/base/util/src/netscape/security/x509/SubjectDirAttributesExtension.java
index 134f0435..931d398c 100644
--- a/pki/base/util/src/netscape/security/x509/SubjectDirAttributesExtension.java
+++ b/pki/base/util/src/netscape/security/x509/SubjectDirAttributesExtension.java
@@ -29,35 +29,36 @@ import netscape.security.util.DerValue;
/**
* This class represents the Subject Directory Attributes Extension.
- *
- * <p>The subject directory attributes extension is not recommended as an
- * essential part of this profile, but it may be used in local environments.
- * This extension MUST be non-critical.
- *
+ *
+ * <p>
+ * The subject directory attributes extension is not recommended as an essential
+ * part of this profile, but it may be used in local environments. This
+ * extension MUST be non-critical.
+ *
* <pre>
* The ASN.1 syntax for this extension is:
- *
+ *
* SubjectDirectoryAttributes ::= SEQUENCE (1..MAX) OF Attribute
- *
+ *
* Attribute ::= SEQUENCE {
- * type AttributeType,
+ * type AttributeType,
* value SET OF AttributeValue
* -- at least one value is required --}
- *
+ *
* AttributeType ::= OBJECT IDENTIFIER
- *
- * AttributeValue ::= ANY
- *
+ *
+ * AttributeValue ::= ANY
+ *
* </pre>
- *
+ *
* @author Christine Ho
* @version 1.7
- *
+ *
* @see CertAttrSet
* @see Extension
*/
public class SubjectDirAttributesExtension extends Extension
-implements CertAttrSet {
+ implements CertAttrSet {
/**
*
@@ -65,12 +66,13 @@ implements CertAttrSet {
private static final long serialVersionUID = -1215458115428197688L;
/**
- * Identifier for this attribute, to be used with the
- * get, set, delete methods of Certificate, x509 type.
- */
- //public static final String IDENT = "x509.info.extensions.SubjectDirectoryAttributes";
+ * Identifier for this attribute, to be used with the get, set, delete
+ * methods of Certificate, x509 type.
+ */
+ // public static final String IDENT =
+ // "x509.info.extensions.SubjectDirectoryAttributes";
public static final String IDENT = "Subject Directory Attributes";
-
+
/**
* Attribute names.
*/
@@ -83,12 +85,12 @@ implements CertAttrSet {
DerOutputStream out = new DerOutputStream();
DerOutputStream tmp = new DerOutputStream();
- //encoding the attributes
- Enumeration<Attribute> attrs = attrList.elements();
- while (attrs.hasMoreElements()) {
- Attribute attr = attrs.nextElement();
- attr.encode(tmp);
- }
+ // encoding the attributes
+ Enumeration<Attribute> attrs = attrList.elements();
+ while (attrs.hasMoreElements()) {
+ Attribute attr = attrs.nextElement();
+ attr.encode(tmp);
+ }
out.write(DerValue.tag_SequenceOf, tmp);
this.extensionValue = out.toByteArray();
@@ -98,12 +100,12 @@ implements CertAttrSet {
private void decodeThis(DerValue derVal) throws IOException {
if (derVal.tag != DerValue.tag_Sequence) {
- throw new IOException("Invalid encoding for "+
- "Subject Directory Attribute extension.");
+ throw new IOException("Invalid encoding for " +
+ "Subject Directory Attribute extension.");
}
if (derVal.data.available() == 0) {
- throw new IOException(this.getClass().getSimpleName()+" No data available in "
+ throw new IOException(this.getClass().getSimpleName() + " No data available in "
+ "passed DER encoded value.");
}
@@ -117,79 +119,79 @@ implements CertAttrSet {
/**
* Default constructor for this object.
- *
+ *
* @param derVal Der encoded value of this extension
*/
public SubjectDirAttributesExtension(DerValue derVal) throws IOException {
- this.extensionId = PKIXExtensions.SubjectDirectoryAttributes_Id;
- this.critical = false;
+ this.extensionId = PKIXExtensions.SubjectDirectoryAttributes_Id;
+ this.critical = false;
decodeThis(derVal);
}
/**
* Default constructor for this object.
- *
+ *
* @param list Attribute object list
*/
public SubjectDirAttributesExtension(Attribute[] list) throws IOException {
- this.extensionId = PKIXExtensions.SubjectDirectoryAttributes_Id;
- this.critical = false;
+ this.extensionId = PKIXExtensions.SubjectDirectoryAttributes_Id;
+ this.critical = false;
- if ((list == null)||(list.length==0)) {
+ if ((list == null) || (list.length == 0)) {
throw new IOException("No data available in "
+ "passed Attribute List.");
- }
+ }
// add the Attributes
for (int i = 0; i < list.length; i++) {
- attrList.addElement(list[i]);
- }
+ attrList.addElement(list[i]);
+ }
}
/**
* Constructor from parsing extension
- *
+ *
* @param list Attribute object list
*/
public SubjectDirAttributesExtension(Boolean crit, Object value)
- throws IOException {
+ throws IOException {
- this.extensionId = PKIXExtensions.SubjectDirectoryAttributes_Id;
+ this.extensionId = PKIXExtensions.SubjectDirectoryAttributes_Id;
this.critical = crit.booleanValue();
if (!(value instanceof byte[]))
- throw new IOException(this.getClass().getSimpleName()+"Illegal argument type");
+ throw new IOException(this.getClass().getSimpleName() + "Illegal argument type");
int len = Array.getLength(value);
byte[] extValue = new byte[len];
System.arraycopy(value, 0, extValue, 0, len);
this.extensionValue = extValue;
- decodeThis(new DerValue(extValue));
+ decodeThis(new DerValue(extValue));
}
/**
* Constructor for this object.
- *
+ *
* @param list Attribute object list
* @param critical The criticality
*/
- public SubjectDirAttributesExtension(Attribute[] list, boolean critical)
- throws IOException {
+ public SubjectDirAttributesExtension(Attribute[] list, boolean critical)
+ throws IOException {
- this.extensionId = PKIXExtensions.SubjectDirectoryAttributes_Id;
- this.critical = critical;
+ this.extensionId = PKIXExtensions.SubjectDirectoryAttributes_Id;
+ this.critical = critical;
- if ((list == null)||(list.length==0)) {
+ if ((list == null) || (list.length == 0)) {
throw new IOException("No data available in "
+ "passed Attribute List.");
- }
+ }
// add the Attributes
for (int i = 0; i < list.length; i++) {
- attrList.addElement(list[i]);
- }
+ attrList.addElement(list[i]);
+ }
}
/**
@@ -198,18 +200,18 @@ implements CertAttrSet {
public String toString() {
String s = super.toString() + "SubjectDirectoryAttributes:[\n";
- Enumeration<Attribute> attrs = attrList.elements();
- while (attrs.hasMoreElements()) {
- Attribute attr = attrs.nextElement();
- s += attr.toString();
- }
+ Enumeration<Attribute> attrs = attrList.elements();
+ while (attrs.hasMoreElements()) {
+ Attribute attr = attrs.nextElement();
+ s += attr.toString();
+ }
return (s + "]\n");
}
/**
* Decode the extension from the InputStream.
- *
+ *
* @param in the InputStream to unmarshal the contents from.
* @exception IOException on decoding or validity errors.
*/
@@ -218,44 +220,44 @@ implements CertAttrSet {
decodeThis(val);
}
- /**
- * Encode this extension value to the output stream.
- *
- * @param out the DerOutputStream to encode the extension to.
- */
- public void encode(OutputStream out) throws IOException {
- DerOutputStream tmp = new DerOutputStream();
- if (extensionValue == null) {
- this.extensionId = PKIXExtensions.SubjectDirectoryAttributes_Id;
- this.critical = false;
- encodeThis();
- }
- super.encode(tmp);
- out.write(tmp.toByteArray());
- }
+ /**
+ * Encode this extension value to the output stream.
+ *
+ * @param out the DerOutputStream to encode the extension to.
+ */
+ public void encode(OutputStream out) throws IOException {
+ DerOutputStream tmp = new DerOutputStream();
+ if (extensionValue == null) {
+ this.extensionId = PKIXExtensions.SubjectDirectoryAttributes_Id;
+ this.critical = false;
+ encodeThis();
+ }
+ super.encode(tmp);
+ out.write(tmp.toByteArray());
+ }
/**
* Set the attribute value.
*/
public void set(String name, Object obj) throws IOException {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:SubjectDirectoryAttributes.");
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:SubjectDirectoryAttributes.");
}
/**
* Get the attribute value.
*/
public Object get(String name) throws IOException {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:SubjectDirectoryAttributes.");
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:SubjectDirectoryAttributes.");
}
/**
* Delete the attribute value.
*/
public void delete(String name) throws IOException {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:SubjectDirectoryAttributes.");
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:SubjectDirectoryAttributes.");
}
/**
@@ -264,16 +266,15 @@ implements CertAttrSet {
*/
public Enumeration<String> getAttributeNames() {
Vector<String> elements = new Vector<String>();
- return (elements.elements());
+ return (elements.elements());
}
-
/**
* Returns an enumeration of attributes in the extension.
*/
public Enumeration<Attribute> getAttributesList() {
- if (attrList == null)
- return null;
- return attrList.elements();
+ if (attrList == null)
+ return null;
+ return attrList.elements();
}
}
diff --git a/pki/base/util/src/netscape/security/x509/SubjectKeyIdentifierExtension.java b/pki/base/util/src/netscape/security/x509/SubjectKeyIdentifierExtension.java
index cbaf2ce5..dfb0505d 100644
--- a/pki/base/util/src/netscape/security/x509/SubjectKeyIdentifierExtension.java
+++ b/pki/base/util/src/netscape/security/x509/SubjectKeyIdentifierExtension.java
@@ -29,20 +29,22 @@ import netscape.security.util.DerValue;
/**
* Represent the Subject Key Identifier Extension.
- *
+ *
* This extension, if present, provides a means of identifying the particular
- * public key used in an application. This extension by default is marked
+ * public key used in an application. This extension by default is marked
* non-critical.
- *
- * <p>Extensions are addiitonal attributes which can be inserted in a X509
- * v3 certificate. For example a "Driving License Certificate" could have
- * the driving license number as a extension.
- *
- * <p>Extensions are represented as a sequence of the extension identifier
- * (Object Identifier), a boolean flag stating whether the extension is to
- * be treated as being critical and the extension value itself (this is again
- * a DER encoding of the extension value).
- *
+ *
+ * <p>
+ * Extensions are addiitonal attributes which can be inserted in a X509 v3
+ * certificate. For example a "Driving License Certificate" could have the
+ * driving license number as a extension.
+ *
+ * <p>
+ * Extensions are represented as a sequence of the extension identifier (Object
+ * Identifier), a boolean flag stating whether the extension is to be treated as
+ * being critical and the extension value itself (this is again a DER encoding
+ * of the extension value).
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.7
@@ -50,15 +52,15 @@ import netscape.security.util.DerValue;
* @see CertAttrSet
*/
public class SubjectKeyIdentifierExtension extends Extension
-implements CertAttrSet {
+ implements CertAttrSet {
/**
*
*/
private static final long serialVersionUID = 2457721262590880939L;
/**
- * Identifier for this attribute, to be used with the
- * get, set, delete methods of Certificate, x509 type.
- */
+ * Identifier for this attribute, to be used with the get, set, delete
+ * methods of Certificate, x509 type.
+ */
public static final String IDENT =
"x509.info.extensions.SubjectKeyIdentifier";
/**
@@ -77,20 +79,22 @@ implements CertAttrSet {
}
/**
- * Create a SubjectKeyIdentifierExtension with the passed octet string.
- * The criticality is set to False.
+ * Create a SubjectKeyIdentifierExtension with the passed octet string. The
+ * criticality is set to False.
+ *
* @param octetString the octet string identifying the key identifier.
*/
- public SubjectKeyIdentifierExtension (boolean critical, byte[] octetString)
- throws IOException {
+ public SubjectKeyIdentifierExtension(boolean critical, byte[] octetString)
+ throws IOException {
id = new KeyIdentifier(octetString);
this.extensionId = PKIXExtensions.SubjectKey_Id;
this.critical = critical;
encodeThis();
}
- public SubjectKeyIdentifierExtension (byte[] octetString)
- throws IOException {
+
+ public SubjectKeyIdentifierExtension(byte[] octetString)
+ throws IOException {
id = new KeyIdentifier(octetString);
this.extensionId = PKIXExtensions.SubjectKey_Id;
@@ -100,21 +104,21 @@ implements CertAttrSet {
/**
* Create the extension from the passed DER encoded value.
- *
+ *
* @param critical true if the extension is to be treated as critical.
* @param value Array of DER encoded bytes of the actual value.
* @exception IOException on error.
*/
public SubjectKeyIdentifierExtension(Boolean critical, Object value)
- throws IOException {
+ throws IOException {
this.extensionId = PKIXExtensions.SubjectKey_Id;
this.critical = critical.booleanValue();
int len = Array.getLength(value);
- byte[] extValue = new byte[len];
- for (int i = 0; i < len; i++) {
- extValue[i] = Array.getByte(value,i);
- }
+ byte[] extValue = new byte[len];
+ for (int i = 0; i < len; i++) {
+ extValue[i] = Array.getByte(value, i);
+ }
this.extensionValue = extValue;
DerValue val = new DerValue(extValue);
this.id = new KeyIdentifier(val);
@@ -124,7 +128,8 @@ implements CertAttrSet {
* Returns a printable representation.
*/
public String toString() {
- if (id == null) return "";
+ if (id == null)
+ return "";
String s = super.toString() + "SubjectKeyIdentifier [\n"
+ id.toString() + "]\n";
return (s);
@@ -132,7 +137,7 @@ implements CertAttrSet {
/**
* Write the extension to the OutputStream.
- *
+ *
* @param out the OutputStream to write the extension to.
* @exception IOException on encoding errors.
*/
@@ -144,12 +149,12 @@ implements CertAttrSet {
encodeThis();
}
super.encode(tmp);
- out.write(tmp.toByteArray());
+ out.write(tmp.toByteArray());
}
/**
* Decode the extension from the InputStream.
- *
+ *
* @param in the InputStream to unmarshal the contents from.
* @exception IOException on decoding or validity errors.
*/
@@ -161,52 +166,52 @@ implements CertAttrSet {
* Set the attribute value.
*/
public void set(String name, Object obj) throws IOException {
- clearValue();
- if (name.equalsIgnoreCase(KEY_ID)) {
- if (!(obj instanceof KeyIdentifier)) {
- throw new IOException("Attribute value should be of" +
+ clearValue();
+ if (name.equalsIgnoreCase(KEY_ID)) {
+ if (!(obj instanceof KeyIdentifier)) {
+ throw new IOException("Attribute value should be of" +
" type KeyIdentifier.");
- }
- id = (KeyIdentifier)obj;
- } else {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:SubjectKeyIdentifierExtension.");
- }
+ }
+ id = (KeyIdentifier) obj;
+ } else {
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:SubjectKeyIdentifierExtension.");
+ }
}
/**
* Get the attribute value.
*/
public Object get(String name) throws IOException {
- if (name.equalsIgnoreCase(KEY_ID)) {
- return (id);
- } else {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:SubjectKeyIdentifierExtension.");
- }
+ if (name.equalsIgnoreCase(KEY_ID)) {
+ return (id);
+ } else {
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:SubjectKeyIdentifierExtension.");
+ }
}
/**
* Delete the attribute value.
*/
public void delete(String name) throws IOException {
- if (name.equalsIgnoreCase(KEY_ID)) {
- id = null;
- } else {
- throw new IOException("Attribute name not recognized by " +
- "CertAttrSet:SubjectKeyIdentifierExtension.");
- }
+ if (name.equalsIgnoreCase(KEY_ID)) {
+ id = null;
+ } else {
+ throw new IOException("Attribute name not recognized by " +
+ "CertAttrSet:SubjectKeyIdentifierExtension.");
+ }
}
/**
* Return an enumeration of names of attributes existing within this
* attribute.
*/
- public Enumeration<String> getAttributeNames () {
+ public Enumeration<String> getAttributeNames() {
Vector<String> elements = new Vector<String>();
elements.addElement(KEY_ID);
- return (elements.elements());
+ return (elements.elements());
}
}
diff --git a/pki/base/util/src/netscape/security/x509/URIName.java b/pki/base/util/src/netscape/security/x509/URIName.java
index 539ad249..ad04393f 100644
--- a/pki/base/util/src/netscape/security/x509/URIName.java
+++ b/pki/base/util/src/netscape/security/x509/URIName.java
@@ -23,9 +23,9 @@ import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
/**
- * This class implements the URIName as required by the GeneralNames
- * ASN.1 object.
- *
+ * This class implements the URIName as required by the GeneralNames ASN.1
+ * object.
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.3
@@ -42,7 +42,7 @@ public class URIName implements GeneralNameInterface {
/**
* Create the URIName object from the passed encoded Der value.
- *
+ *
* @param derValue the encoded DER URIName.
* @exception IOException on error.
*/
@@ -52,7 +52,7 @@ public class URIName implements GeneralNameInterface {
/**
* Create the URIName object with the specified name.
- *
+ *
* @param name the URIName.
*/
public URIName(String name) {
@@ -68,7 +68,7 @@ public class URIName implements GeneralNameInterface {
/**
* Encode the URI name into the DerOutputStream.
- *
+ *
* @param out the DER stream to encode the URIName to.
* @exception IOException on encoding errors.
*/
diff --git a/pki/base/util/src/netscape/security/x509/UniqueIdentity.java b/pki/base/util/src/netscape/security/x509/UniqueIdentity.java
index b59f7d7f..5113efea 100644
--- a/pki/base/util/src/netscape/security/x509/UniqueIdentity.java
+++ b/pki/base/util/src/netscape/security/x509/UniqueIdentity.java
@@ -26,18 +26,18 @@ import netscape.security.util.DerValue;
/**
* This class defines the UniqueIdentity class used by certificates.
- *
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.6
*/
public class UniqueIdentity {
// Private data members
- private BitArray id;
+ private BitArray id;
/**
* The default constructor for this class.
- *
+ *
* @param id the byte array containing the unique identifier.
*/
public UniqueIdentity(BitArray id) {
@@ -46,16 +46,16 @@ public class UniqueIdentity {
/**
* The default constructor for this class.
- *
+ *
* @param id the byte array containing the unique identifier.
*/
public UniqueIdentity(byte[] id) {
- this.id = new BitArray(id.length*8, id);
+ this.id = new BitArray(id.length * 8, id);
}
/**
* Create the object, decoding the values from the passed DER stream.
- *
+ *
* @param in the DerInputStream to read the UniqueIdentity from.
* @exception IOException on decoding errors.
*/
@@ -66,7 +66,7 @@ public class UniqueIdentity {
/**
* Create the object, decoding the values from the passed DER stream.
- *
+ *
* @param derVal the DerValue decoded from the stream.
* @param tag the tag the value is encoded under.
* @exception IOException on decoding errors.
@@ -84,14 +84,14 @@ public class UniqueIdentity {
/**
* Encode the UniqueIdentity in DER form to the stream.
- *
+ *
* @param out the DerOutputStream to marshal the contents to.
* @param tag enocode it under the following tag.
* @exception IOException on errors.
*/
public void encode(DerOutputStream out, byte tag) throws IOException {
- byte[] bytes = id.toByteArray();
- int excessBits = bytes.length*8 - id.length();
+ byte[] bytes = id.toByteArray();
+ int excessBits = bytes.length * 8 - id.length();
out.write(tag);
out.putLength(bytes.length + 1);
@@ -104,7 +104,8 @@ public class UniqueIdentity {
* Return the unique id.
*/
public boolean[] getId() {
- if (id == null) return null;
+ if (id == null)
+ return null;
return id.toBooleanArray();
}
diff --git a/pki/base/util/src/netscape/security/x509/UserNotice.java b/pki/base/util/src/netscape/security/x509/UserNotice.java
index ad649339..80f3b1b1 100644
--- a/pki/base/util/src/netscape/security/x509/UserNotice.java
+++ b/pki/base/util/src/netscape/security/x509/UserNotice.java
@@ -22,15 +22,12 @@ import java.io.IOException;
import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
-
/**
* Represent the UserNotice Qualifier.
- *
- * UserNotice ::= SEQUENCE {
- * noticeRef NoticeReference OPTIONAL,
- * explicitText DisplayText OPTIONAL
- * }
- *
+ *
+ * UserNotice ::= SEQUENCE { noticeRef NoticeReference OPTIONAL, explicitText
+ * DisplayText OPTIONAL }
+ *
* @author Thomas Kwan
*/
public class UserNotice extends Qualifier {
@@ -43,28 +40,28 @@ public class UserNotice extends Qualifier {
private DisplayText mDisplayText = null;
public UserNotice(NoticeReference ref, DisplayText text) {
- mNoticeReference = ref;
- mDisplayText = text;
+ mNoticeReference = ref;
+ mDisplayText = text;
}
public UserNotice(DerValue val) throws IOException {
- if (val.tag != DerValue.tag_Sequence) {
- throw new IOException("Invalid encoding for UserNotice");
- }
- // case 0: no element
- if (val.data.available() == 0)
- return;
- // case 1: 1 element
- DerValue inSeq = val.data.getDerValue();
- if (inSeq.tag == DerValue.tag_Sequence) {
- mNoticeReference = new NoticeReference(inSeq);
- } else {
- mDisplayText = new DisplayText(inSeq);
- }
- if (val.data.available() == 0)
- return;
- // case 2: 2 elements
- mDisplayText = new DisplayText(val.data.getDerValue());
+ if (val.tag != DerValue.tag_Sequence) {
+ throw new IOException("Invalid encoding for UserNotice");
+ }
+ // case 0: no element
+ if (val.data.available() == 0)
+ return;
+ // case 1: 1 element
+ DerValue inSeq = val.data.getDerValue();
+ if (inSeq.tag == DerValue.tag_Sequence) {
+ mNoticeReference = new NoticeReference(inSeq);
+ } else {
+ mDisplayText = new DisplayText(inSeq);
+ }
+ if (val.data.available() == 0)
+ return;
+ // case 2: 2 elements
+ mDisplayText = new DisplayText(val.data.getDerValue());
}
public NoticeReference getNoticeReference() {
@@ -77,21 +74,21 @@ public class UserNotice extends Qualifier {
/**
* Write the UserNotice to the DerOutputStream.
- *
+ *
* @param out the DerOutputStream to write the object to.
* @exception IOException on errors.
*/
public void encode(DerOutputStream out) throws IOException {
DerOutputStream tmp = new DerOutputStream();
- // OPTIONAL
- if (mNoticeReference != null) {
- mNoticeReference.encode(tmp);
- }
- // OPTIONAL
+ // OPTIONAL
+ if (mNoticeReference != null) {
+ mNoticeReference.encode(tmp);
+ }
+ // OPTIONAL
if (mDisplayText != null) {
- mDisplayText.encode(tmp);
+ mDisplayText.encode(tmp);
}
- out.write(DerValue.tag_Sequence,tmp);
+ out.write(DerValue.tag_Sequence, tmp);
}
}
diff --git a/pki/base/util/src/netscape/security/x509/X500Name.java b/pki/base/util/src/netscape/security/x509/X500Name.java
index 9efe6c00..6f33b800 100644
--- a/pki/base/util/src/netscape/security/x509/X500Name.java
+++ b/pki/base/util/src/netscape/security/x509/X500Name.java
@@ -27,19 +27,19 @@ import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
import netscape.security.util.ObjectIdentifier;
-
/**
- * X.500 names are used to identify entities, such as those which are
- * identified by X.509 certificates. They are world-wide, hierarchical,
- * and descriptive. Entities can be identified by attributes, and in
- * some systems can be searched for according to those attributes.
- *
- * <P><em>This class exposes only partial X.500 name functionality. Most
+ * X.500 names are used to identify entities, such as those which are identified
+ * by X.509 certificates. They are world-wide, hierarchical, and descriptive.
+ * Entities can be identified by attributes, and in some systems can be searched
+ * for according to those attributes.
+ *
+ * <P>
+ * <em>This class exposes only partial X.500 name functionality. Most
* notably, it works best if Relative Distinguished Names only have one
* (unique) attribute each, and if only the most common attributes need
* to be visible to applications. This limitation, and others, will
* be lifted over time.</em>
- *
+ *
* @author David Brownell
* @author Amit Kapoor
* @author Hemma Prafullchandra
@@ -52,7 +52,6 @@ import netscape.security.util.ObjectIdentifier;
* @see LdapDNStrConverter
*/
-
public class X500Name implements Principal, GeneralNameInterface {
/**
*
@@ -60,20 +59,18 @@ public class X500Name implements Principal, GeneralNameInterface {
private static final long serialVersionUID = -730790062013191108L;
/**
- * Constructs a name from a Ldap DN string, such
- * as &lb;CN=Dave, OU=JavaSoft, O=Sun Microsystems, C=US&rb;. The
- * older "/C=US/O=Sun Microsystems, Inc/OU=JavaSoft/CN=Dave" syntax
- * is not currently supported. (The former is RFC 1779 style.)
- *
+ * Constructs a name from a Ldap DN string, such as &lb;CN=Dave,
+ * OU=JavaSoft, O=Sun Microsystems, C=US&rb;. The older
+ * "/C=US/O=Sun Microsystems, Inc/OU=JavaSoft/CN=Dave" syntax is not
+ * currently supported. (The former is RFC 1779 style.)
+ *
* @param ldapDNString a Ldap DN String e.g. as defined in RFC1779
*/
- public X500Name (String ldapDNString)
- throws IOException
- {
- X500Name x500name;
+ public X500Name(String ldapDNString)
+ throws IOException {
+ X500Name x500name;
- if(ldapDNString == null || ldapDNString.equals(""))
- {
+ if (ldapDNString == null || ldapDNString.equals("")) {
clear();
return;
}
@@ -84,109 +81,102 @@ public class X500Name implements Principal, GeneralNameInterface {
/**
* Constructs a X500Name from a Ldap DN String using the specified
* LdapDNStrConverter. Also use the input tags.
+ *
* @see LdapDNStrConverter
- *
+ *
* @param ldapDNString a Ldap DN String e.g. as defined in RFC1779.
* @param ldapDNStrConverter A LdapDNStrConverter
*/
- public X500Name (String ldapDNString,LdapDNStrConverter ldapDNStrConverter,byte[] tags)
- throws IOException
- {
+ public X500Name(String ldapDNString, LdapDNStrConverter ldapDNStrConverter, byte[] tags)
+ throws IOException {
- if(ldapDNString == null || ldapDNString.equals(""))
- {
+ if (ldapDNString == null || ldapDNString.equals("")) {
clear();
return;
}
X500Name x500name;
- x500name = ldapDNStrConverter.parseDN(ldapDNString,tags);
+ x500name = ldapDNStrConverter.parseDN(ldapDNString, tags);
names = x500name.getNames();
}
- public X500Name (String ldapDNString, byte[] tags)
- throws IOException
- {
- if(ldapDNString == null || ldapDNString.equals(""))
- {
+ public X500Name(String ldapDNString, byte[] tags)
+ throws IOException {
+ if (ldapDNString == null || ldapDNString.equals("")) {
clear();
return;
}
- X500Name x500name;
- x500name = LdapDNStrConverter.getDefault().parseDN(ldapDNString, tags);
- names = x500name.getNames();
+ X500Name x500name;
+ x500name = LdapDNStrConverter.getDefault().parseDN(ldapDNString, tags);
+ names = x500name.getNames();
}
/**
* Constructs a X500Name from a Ldap DN String using the specified
* LdapDNStrConverter.
+ *
* @see LdapDNStrConverter
- *
+ *
* @param ldapDNString a Ldap DN String e.g. as defined in RFC1779.
* @param ldapDNStrConverter A LdapDNStrConverter
*/
- public X500Name (String ldapDNString,
- LdapDNStrConverter ldapDNStrConverter)
- throws IOException
- {
- if(ldapDNString == null || ldapDNString.equals(""))
- {
+ public X500Name(String ldapDNString,
+ LdapDNStrConverter ldapDNStrConverter)
+ throws IOException {
+ if (ldapDNString == null || ldapDNString.equals("")) {
clear();
return;
}
- X500Name x500name;
- x500name = ldapDNStrConverter.parseDN(ldapDNString);
- names = x500name.getNames();
+ X500Name x500name;
+ x500name = ldapDNStrConverter.parseDN(ldapDNString);
+ names = x500name.getNames();
}
/**
* Constructs a X500Name from fields common in enterprise application
* environments.
- *
+ *
* @param commonName common name of a person, e.g. "Vivette Davis"
* @param organizationUnit small organization name, e.g. "Purchasing"
* @param organizationName large organization name, e.g. "Onizuka, Inc."
* @param country two letter country code, e.g. "CH"
*/
- public X500Name (
- String commonName,
- String organizationUnit,
- String organizationName,
- String country
- ) throws IOException
- {
- DirStrConverter dirStrConverter = new DirStrConverter();
- PrintableConverter printableConverter = new PrintableConverter();
- DerValue val;
- AVA[] assertion = new AVA[1]; // array is cloned in constructors.
- int i = 4;
-
- names = new RDN [i];
- /*
- * NOTE: it's only on output that little-endian
- * ordering is used.
- */
- assertion[0] = new AVA(commonName_oid,
- dirStrConverter.getValue(commonName));
- names [--i] = new RDN (assertion);
-
- assertion[0] = new AVA(orgUnitName_oid,
- dirStrConverter.getValue(organizationUnit));
- names [--i] = new RDN (assertion);
-
- assertion[0] = new AVA(orgName_oid,
- dirStrConverter.getValue(organizationName));
- names [--i] = new RDN (assertion);
-
- assertion[0] = new AVA(countryName_oid,
- printableConverter.getValue(country));
- names [--i] = new RDN (assertion);
+ public X500Name(
+ String commonName,
+ String organizationUnit,
+ String organizationName,
+ String country) throws IOException {
+ DirStrConverter dirStrConverter = new DirStrConverter();
+ PrintableConverter printableConverter = new PrintableConverter();
+ DerValue val;
+ AVA[] assertion = new AVA[1]; // array is cloned in constructors.
+ int i = 4;
+
+ names = new RDN[i];
+ /*
+ * NOTE: it's only on output that little-endian ordering is used.
+ */
+ assertion[0] = new AVA(commonName_oid,
+ dirStrConverter.getValue(commonName));
+ names[--i] = new RDN(assertion);
+
+ assertion[0] = new AVA(orgUnitName_oid,
+ dirStrConverter.getValue(organizationUnit));
+ names[--i] = new RDN(assertion);
+
+ assertion[0] = new AVA(orgName_oid,
+ dirStrConverter.getValue(organizationName));
+ names[--i] = new RDN(assertion);
+
+ assertion[0] = new AVA(countryName_oid,
+ printableConverter.getValue(country));
+ names[--i] = new RDN(assertion);
}
/**
* Constructs a X500Name from fields common in Internet application
* environments.
- *
+ *
* @param commonName common name of a person, e.g. "Vivette Davis"
* @param organizationUnit small organization name, e.g. "Purchasing"
* @param organizationName large organization name, e.g. "Onizuka, Inc."
@@ -194,158 +184,149 @@ public class X500Name implements Principal, GeneralNameInterface {
* @param stateName state name, e.g. "California"
* @param country two letter country code, e.g. "CH"
*/
- public X500Name (
- String commonName,
- String organizationUnit,
- String organizationName,
- String localityName,
- String stateName,
- String country
- ) throws IOException
- {
- DirStrConverter dirStrConverter = new DirStrConverter();
- PrintableConverter printableConverter = new PrintableConverter();
- DerValue val;
- AVA[] assertion = new AVA[1]; // array is cloned in constructors.
- int i = 6;
-
- names = new RDN [i];
- /*
- * NOTE: it's only on output that little-endian
- * ordering is used.
- */
- assertion[0] = new AVA(commonName_oid,
- dirStrConverter.getValue(commonName));
- names [--i] = new RDN (assertion);
-
- assertion[0] = new AVA(orgUnitName_oid,
- dirStrConverter.getValue(organizationUnit));
- names [--i] = new RDN (assertion);
-
- assertion[0] = new AVA(orgName_oid,
- dirStrConverter.getValue(organizationName));
- names [--i] = new RDN (assertion);
-
- assertion[0] = new AVA(localityName_oid,
- dirStrConverter.getValue(localityName));
- names [--i] = new RDN (assertion);
-
- assertion[0] = new AVA(stateName_oid,
- dirStrConverter.getValue(stateName));
- names [--i] = new RDN (assertion);
-
- assertion[0] = new AVA(countryName_oid,
- printableConverter.getValue(country));
- names [--i] = new RDN (assertion);
- }
-
-
- /**
- * Constructs a name from an ASN.1 encoded value. The encoding
- * of the name in the stream uses DER (a BER/1 subset).
- *
+ public X500Name(
+ String commonName,
+ String organizationUnit,
+ String organizationName,
+ String localityName,
+ String stateName,
+ String country) throws IOException {
+ DirStrConverter dirStrConverter = new DirStrConverter();
+ PrintableConverter printableConverter = new PrintableConverter();
+ DerValue val;
+ AVA[] assertion = new AVA[1]; // array is cloned in constructors.
+ int i = 6;
+
+ names = new RDN[i];
+ /*
+ * NOTE: it's only on output that little-endian ordering is used.
+ */
+ assertion[0] = new AVA(commonName_oid,
+ dirStrConverter.getValue(commonName));
+ names[--i] = new RDN(assertion);
+
+ assertion[0] = new AVA(orgUnitName_oid,
+ dirStrConverter.getValue(organizationUnit));
+ names[--i] = new RDN(assertion);
+
+ assertion[0] = new AVA(orgName_oid,
+ dirStrConverter.getValue(organizationName));
+ names[--i] = new RDN(assertion);
+
+ assertion[0] = new AVA(localityName_oid,
+ dirStrConverter.getValue(localityName));
+ names[--i] = new RDN(assertion);
+
+ assertion[0] = new AVA(stateName_oid,
+ dirStrConverter.getValue(stateName));
+ names[--i] = new RDN(assertion);
+
+ assertion[0] = new AVA(countryName_oid,
+ printableConverter.getValue(country));
+ names[--i] = new RDN(assertion);
+ }
+
+ /**
+ * Constructs a name from an ASN.1 encoded value. The encoding of the name
+ * in the stream uses DER (a BER/1 subset).
+ *
* @param value a DER-encoded value holding an X.500 name.
*/
public X500Name(DerValue value) throws IOException {
- this(value.toDerInputStream());
+ this(value.toDerInputStream());
}
/**
- * Constructs a name from an ASN.1 encoded input stream. The encoding
- * of the name in the stream uses DER (a BER/1 subset).
- *
+ * Constructs a name from an ASN.1 encoded input stream. The encoding of the
+ * name in the stream uses DER (a BER/1 subset).
+ *
* @param in DER-encoded data holding an X.500 name.
*/
- public X500Name (DerInputStream in)
- throws IOException
- {
- parseDER (in);
+ public X500Name(DerInputStream in)
+ throws IOException {
+ parseDER(in);
}
/**
- * Constructs a name from an ASN.1 encoded byte array.
- *
+ * Constructs a name from an ASN.1 encoded byte array.
+ *
* @param name DER-encoded byte array holding an X.500 name.
*/
- public X500Name (byte[] name)
- throws IOException
- {
+ public X500Name(byte[] name)
+ throws IOException {
DerInputStream in = new DerInputStream(name);
- parseDER (in);
+ parseDER(in);
}
/**
- * Constructs a X500Name from array of RDN. The RDNs are expected to
- * be in big endian order i.e. most significant first.
+ * Constructs a X500Name from array of RDN. The RDNs are expected to be in
+ * big endian order i.e. most significant first.
+ *
* @param rdns an array of RDN.
*/
- public X500Name (RDN[] rdns)
- throws IOException
- {
- names = (RDN[])rdns.clone();
+ public X500Name(RDN[] rdns)
+ throws IOException {
+ names = (RDN[]) rdns.clone();
}
/**
* convenience method.
+ *
* @param rdns a vector of rdns.
*/
- public X500Name (Vector<RDN> rdnVector)
- throws IOException
- {
- int size = rdnVector.size();
- names = new RDN[size];
- for (int i = 0; i < size; i++) {
- names[i] = (RDN)rdnVector.elementAt(i);
- }
+ public X500Name(Vector<RDN> rdnVector)
+ throws IOException {
+ int size = rdnVector.size();
+ names = new RDN[size];
+ for (int i = 0; i < size; i++) {
+ names[i] = (RDN) rdnVector.elementAt(i);
+ }
}
/**
* Compares this name with another, for equality.
- *
+ *
* @return true iff the names are identical.
*/
- synchronized public boolean equals (X500Name other)
- {
- int i;
+ synchronized public boolean equals(X500Name other) {
+ int i;
- if (this == other)
- return true;
+ if (this == other)
+ return true;
- if (names.length != other.names.length)
- return false;
- for (i = 0; i < names.length; i++) {
- if (!names [i].equals (other.names [i]))
- return false;
- }
- return true;
+ if (names.length != other.names.length)
+ return false;
+ for (i = 0; i < names.length; i++) {
+ if (!names[i].equals(other.names[i]))
+ return false;
+ }
+ return true;
}
/**
- * Sets private data to a null state
+ * Sets private data to a null state
*/
- private void clear()
- {
+ private void clear() {
dn = "";
names = null;
}
/**
- * Returns the name component as a Java string, regardless of its
- * encoding restrictions.
+ * Returns the name component as a Java string, regardless of its encoding
+ * restrictions.
*/
- private String getString (DerValue attribute) throws IOException
- {
- String value = attribute.getAsString ();
+ private String getString(DerValue attribute) throws IOException {
+ String value = attribute.getAsString();
- if (value == null)
- throw new IOException ("not a DER string encoding, "
- + attribute.tag);
- else
- return value;
+ if (value == null)
+ throw new IOException("not a DER string encoding, "
+ + attribute.tag);
+ else
+ return value;
}
/**
@@ -356,281 +337,254 @@ public class X500Name implements Principal, GeneralNameInterface {
}
/**
- * Returns a "Country" name component. If more than one
- * such attribute exists, the topmost one is returned.
- *
+ * Returns a "Country" name component. If more than one such attribute
+ * exists, the topmost one is returned.
+ *
* @return "C=" component of the name, if any.
*/
- public String getCountry () throws IOException
- {
- DerValue attr = findAttribute (countryName_oid);
+ public String getCountry() throws IOException {
+ DerValue attr = findAttribute(countryName_oid);
- return getString (attr);
+ return getString(attr);
}
-
/**
- * Returns an "Organization" name component. If more than
- * one such attribute exists, the topmost one is returned.
- *
+ * Returns an "Organization" name component. If more than one such attribute
+ * exists, the topmost one is returned.
+ *
* @return "O=" component of the name, if any.
*/
- public String getOrganization () throws IOException
- {
- DerValue attr = findAttribute (orgName_oid);
+ public String getOrganization() throws IOException {
+ DerValue attr = findAttribute(orgName_oid);
- return getString (attr);
+ return getString(attr);
}
-
/**
- * Returns an "Organizational Unit" name component. If more
- * than one such attribute exists, the topmost one is returned.
- *
+ * Returns an "Organizational Unit" name component. If more than one such
+ * attribute exists, the topmost one is returned.
+ *
* @return "OU=" component of the name, if any.
*/
- public String getOrganizationalUnit () throws IOException
- {
- DerValue attr = findAttribute (orgUnitName_oid);
+ public String getOrganizationalUnit() throws IOException {
+ DerValue attr = findAttribute(orgUnitName_oid);
- return getString (attr);
+ return getString(attr);
}
-
/**
- * Returns a "Common Name" component. If more than one such
- * attribute exists, the topmost one is returned.
- *
+ * Returns a "Common Name" component. If more than one such attribute
+ * exists, the topmost one is returned.
+ *
* @return "CN=" component of the name, if any.
*/
- public String getCommonName () throws IOException
- {
- DerValue attr = findAttribute (commonName_oid);
+ public String getCommonName() throws IOException {
+ DerValue attr = findAttribute(commonName_oid);
- return getString (attr);
+ return getString(attr);
}
-
/**
- * Returns a "UID" component. If more than one such
- * attribute exists, the topmost one is returned.
- *
+ * Returns a "UID" component. If more than one such attribute exists, the
+ * topmost one is returned.
+ *
* @return "UID=" component of the name, if any.
*/
- public String getUserID () throws IOException
- {
- DerValue attr = findAttribute (uidName_oid);
+ public String getUserID() throws IOException {
+ DerValue attr = findAttribute(uidName_oid);
- return getString (attr);
+ return getString(attr);
}
-
/**
- * Returns a "Locality" name component. If more than one
- * such component exists, the topmost one is returned.
- *
+ * Returns a "Locality" name component. If more than one such component
+ * exists, the topmost one is returned.
+ *
* @return "L=" component of the name, if any.
*/
- public String getLocality () throws IOException
- {
- DerValue attr = findAttribute (localityName_oid);
+ public String getLocality() throws IOException {
+ DerValue attr = findAttribute(localityName_oid);
- return getString (attr);
+ return getString(attr);
}
-
/**
- * Returns a "State" name component. If more than one
- * such component exists, the topmost one is returned.
- *
+ * Returns a "State" name component. If more than one such component exists,
+ * the topmost one is returned.
+ *
* @return "S=" component of the name, if any.
*/
- public String getState () throws IOException
- {
- DerValue attr = findAttribute (stateName_oid);
+ public String getState() throws IOException {
+ DerValue attr = findAttribute(stateName_oid);
- return getString (attr);
+ return getString(attr);
}
/**
- * Returns a "Email" name component. If more than one
- * such component exists, the topmost one is returned.
- *
+ * Returns a "Email" name component. If more than one such component exists,
+ * the topmost one is returned.
+ *
* @return "E=" component of the name, if any.
*/
- public String getEmail() throws IOException
- {
- DerValue attr = findAttribute (email_oid);
- if (attr == null)
- return null;
- return getString (attr);
+ public String getEmail() throws IOException {
+ DerValue attr = findAttribute(email_oid);
+ if (attr == null)
+ return null;
+ return getString(attr);
}
/**
* Returns a Ldap DN String from the X500Name using the global default
* LdapDNStrConverter
+ *
* @see LdapDNStrConverter
* @return Ldap DN string of this X500Name using the default converter.
*/
public String toLdapDNString()
- throws IOException
- {
- if (dn == null)
- generateDN(LdapDNStrConverter.getDefault());
- return dn;
+ throws IOException {
+ if (dn == null)
+ generateDN(LdapDNStrConverter.getDefault());
+ return dn;
}
/**
- * Returns a Ldap DN String from the X500Name
- * using the specified LdapDNStrconverter.
- * For example, RFC1779String converter can be passed to convert the
- * DN to RFC1779 string syntax.
+ * Returns a Ldap DN String from the X500Name using the specified
+ * LdapDNStrconverter. For example, RFC1779String converter can be passed to
+ * convert the DN to RFC1779 string syntax.
+ *
* @see LdapDNStrConverter
* @param ldapDNStrConverter a LdapDNStrConverter
* @return Ldap DN string of the X500Name
*/
public String toLdapDNString(LdapDNStrConverter ldapDNStrConverter)
- throws IOException
- {
+ throws IOException {
- if (dn == null)
- generateDN(ldapDNStrConverter);
- return dn;
+ if (dn == null)
+ generateDN(ldapDNStrConverter);
+ return dn;
}
/**
- * Returns a Ldap DN string, using the global default LdapDNStrConverter
- * or null if an error occurs in the conversion.
+ * Returns a Ldap DN string, using the global default LdapDNStrConverter or
+ * null if an error occurs in the conversion.
*/
- public String toString()
- {
- String s;
- if(names == null)
- {
- s = "";
- return s;
+ public String toString() {
+ String s;
+ if (names == null) {
+ s = "";
+ return s;
}
- try {
- s = toLdapDNString();
- }
- catch (IOException e) {
- return null;
- }
- return s;
+ try {
+ s = toLdapDNString();
+ } catch (IOException e) {
+ return null;
+ }
+ return s;
}
/**
- * Returns the value of toString(). This call is needed to
- * implement the java.security.Principal interface.
+ * Returns the value of toString(). This call is needed to implement the
+ * java.security.Principal interface.
*/
- public String getName () { return toString (); }
-
+ public String getName() {
+ return toString();
+ }
- private String dn; // RFC 1779 style DN, or null
- private RDN names[]; // RDNs
+ private String dn; // RFC 1779 style DN, or null
+ private RDN names[]; // RDNs
/**
- * Find the first instance of this attribute in a "top down"
- * search of all the attributes in the name.
+ * Find the first instance of this attribute in a "top down" search of all
+ * the attributes in the name.
*/
- private DerValue findAttribute (ObjectIdentifier attribute)
- {
- int i;
- DerValue retval = null;
+ private DerValue findAttribute(ObjectIdentifier attribute) {
+ int i;
+ DerValue retval = null;
- for (i = 0; i < names.length; i++) {
- retval = names [i].findAttribute (attribute);
- if (retval != null)
- break;
- }
- return retval;
+ for (i = 0; i < names.length; i++) {
+ retval = names[i].findAttribute(attribute);
+ if (retval != null)
+ break;
+ }
+ return retval;
}
/**
* Returns an enumerator of RDNs in the X500Name.
+ *
* @return enumeration of rdns in this X500Name.
*/
- public Enumeration<RDN> getRDNs()
- {
- return new RDNEnumerator();
+ public Enumeration<RDN> getRDNs() {
+ return new RDNEnumerator();
}
/**
* Returns an array of RDN in the X500Name.
+ *
* @return array of RDN in this X500name.
*/
- public RDN[] getNames()
- {
- return (RDN[])names.clone();
+ public RDN[] getNames() {
+ return (RDN[]) names.clone();
}
/**
* Returns the number of RDNs in the X500Name.
+ *
* @return number of RDNs in this X500Name.
*/
- public int getNamesLength()
- {
- return names.length;
+ public int getNamesLength() {
+ return names.length;
}
/****************************************************************/
- private void parseDER (DerInputStream in) throws IOException
- {
- //
- // X.500 names are a "SEQUENCE OF" RDNs, which means one or
- // more and order matters. We scan them in order, which
- // conventionally is big-endian.
- //
- DerValue nameseq [] = in.getSequence (5);
- int i;
-
- if(nameseq.length != 0)
- {
- names = new RDN [nameseq.length];
- }
- else
- {
+ private void parseDER(DerInputStream in) throws IOException {
+ //
+ // X.500 names are a "SEQUENCE OF" RDNs, which means one or
+ // more and order matters. We scan them in order, which
+ // conventionally is big-endian.
+ //
+ DerValue nameseq[] = in.getSequence(5);
+ int i;
+
+ if (nameseq.length != 0) {
+ names = new RDN[nameseq.length];
+ } else {
clear();
}
-
- for (i = 0; i < nameseq.length; i++)
- names [i] = new RDN (nameseq [i]);
+ for (i = 0; i < nameseq.length; i++)
+ names[i] = new RDN(nameseq[i]);
}
/**
* Encodes the name in DER-encoded form.
- *
+ *
* @param out where to put the DER-encoded X.500 name
*/
- public void encode (DerOutputStream out) throws IOException
- {
- DerOutputStream tmp = new DerOutputStream ();
- int i;
+ public void encode(DerOutputStream out) throws IOException {
+ DerOutputStream tmp = new DerOutputStream();
+ int i;
int len = 0;
- if(names == null)
- {
- len = 0;
- }
- else
- {
+ if (names == null) {
+ len = 0;
+ } else {
len = names.length;
}
- for (i = 0; i < len; i++)
- names [i].encode (tmp);
+ for (i = 0; i < len; i++)
+ names[i].encode(tmp);
- out.write (DerValue.tag_Sequence, tmp);
+ out.write(DerValue.tag_Sequence, tmp);
}
/**
* Gets the name in DER-encoded form.
- *
- * @return the DER encoded byte array of this name,
- * null if no names are present.
+ *
+ * @return the DER encoded byte array of this name, null if no names are
+ * present.
*/
public byte[] getEncoded() throws IOException {
@@ -639,12 +593,9 @@ public class X500Name implements Principal, GeneralNameInterface {
int len = 0;
- if (names == null)
- {
+ if (names == null) {
len = 0;
- }
- else
- {
+ } else {
len = names.length;
}
@@ -656,51 +607,47 @@ public class X500Name implements Principal, GeneralNameInterface {
}
/*
- * Dump the printable form of a distinguished name. Each relative
- * name is separated from the next by a ",", and assertions in the
- * relative names have "label=value" syntax.
- *
+ * Dump the printable form of a distinguished name. Each relative name is
+ * separated from the next by a ",", and assertions in the relative names
+ * have "label=value" syntax.
+ *
* Uses RFC 1779 syntax (i.e. little-endian, comma separators)
- *
*/
private void generateDN(LdapDNStrConverter ldapDNStrConverter)
- throws IOException
- {
- if(names == null)
- return ;
+ throws IOException {
+ if (names == null)
+ return;
- dn = ldapDNStrConverter.encodeDN(this);
+ dn = ldapDNStrConverter.encodeDN(this);
}
- private class RDNEnumerator implements Enumeration<RDN>
- {
- private int index;
+ private class RDNEnumerator implements Enumeration<RDN> {
+ private int index;
- public RDNEnumerator() { index = 0; }
+ public RDNEnumerator() {
+ index = 0;
+ }
- public boolean hasMoreElements()
- {
- return (index < names.length);
- }
+ public boolean hasMoreElements() {
+ return (index < names.length);
+ }
- public RDN nextElement()
- {
- if (index >= names.length)
- return null;
- return names[index++];
- }
+ public RDN nextElement() {
+ if (index >= names.length)
+ return null;
+ return names[index++];
+ }
}
/****************************************************************/
/*
- * Maybe return a preallocated OID, to reduce storage costs
- * and speed recognition of common X.500 attributes.
+ * Maybe return a preallocated OID, to reduce storage costs and speed
+ * recognition of common X.500 attributes.
*/
- static ObjectIdentifier intern (ObjectIdentifier oid)
- throws IOException
- {
- return X500NameAttrMap.getDefault().getOid(oid);
+ static ObjectIdentifier intern(ObjectIdentifier oid)
+ throws IOException {
+ return X500NameAttrMap.getDefault().getOid(oid);
}
/*
@@ -708,56 +655,43 @@ public class X500Name implements Principal, GeneralNameInterface {
*/
/** OID for the "CN=" attribute, denoting a person's common name. */
- public static final ObjectIdentifier
- commonName_oid = X500NameAttrMap.getDefault().getOid("CN");
+ public static final ObjectIdentifier commonName_oid = X500NameAttrMap.getDefault().getOid("CN");
/** OID for the "UID=" attribute, denoting a person's ID. */
- public static final ObjectIdentifier
- uidName_oid = X500NameAttrMap.getDefault().getOid("UID");
+ public static final ObjectIdentifier uidName_oid = X500NameAttrMap.getDefault().getOid("UID");
/** OID for the "C=" attribute, denoting a country. */
- public static final ObjectIdentifier
- countryName_oid = X500NameAttrMap.getDefault().getOid("C");
+ public static final ObjectIdentifier countryName_oid = X500NameAttrMap.getDefault().getOid("C");
/** OID for the "L=" attribute, denoting a locality (such as a city) */
- public static final ObjectIdentifier
- localityName_oid = X500NameAttrMap.getDefault().getOid("L");
+ public static final ObjectIdentifier localityName_oid = X500NameAttrMap.getDefault().getOid("L");
/** OID for the "O=" attribute, denoting an organization name */
- public static final ObjectIdentifier
- orgName_oid = X500NameAttrMap.getDefault().getOid("O");
+ public static final ObjectIdentifier orgName_oid = X500NameAttrMap.getDefault().getOid("O");
/** OID for the "OU=" attribute, denoting an organizational unit name */
- public static final ObjectIdentifier
- orgUnitName_oid = X500NameAttrMap.getDefault().getOid("OU");
+ public static final ObjectIdentifier orgUnitName_oid = X500NameAttrMap.getDefault().getOid("OU");
/** OID for the "S=" attribute, denoting a state (such as Delaware) */
- public static final ObjectIdentifier
- stateName_oid = X500NameAttrMap.getDefault().getOid("ST");
+ public static final ObjectIdentifier stateName_oid = X500NameAttrMap.getDefault().getOid("ST");
/** OID for the "STREET=" attribute, denoting a street address. */
- public static final ObjectIdentifier
- streetAddress_oid = X500NameAttrMap.getDefault().getOid("STREET");
+ public static final ObjectIdentifier streetAddress_oid = X500NameAttrMap.getDefault().getOid("STREET");
/** OID for the "T=" attribute, denoting a person's title. */
- public static final ObjectIdentifier
- title_oid = X500NameAttrMap.getDefault().getOid("TITLE");
+ public static final ObjectIdentifier title_oid = X500NameAttrMap.getDefault().getOid("TITLE");
/** OID for the "E=" attribute, denoting a person's email address. */
- public static final ObjectIdentifier
- email_oid = X500NameAttrMap.getDefault().getOid("E");
+ public static final ObjectIdentifier email_oid = X500NameAttrMap.getDefault().getOid("E");
/*
- * OIDs from other sources which show up in X.500 names we
- * expect to deal with often
+ * OIDs from other sources which show up in X.500 names we expect to deal
+ * with often
*/
- private static final int ipAddress_data [] = // SKIP
- { 1, 3, 6, 1, 4, 1, 42, 2, 11, 2, 1 };
+ private static final int ipAddress_data[] = // SKIP
+ { 1, 3, 6, 1, 4, 1, 42, 2, 11, 2, 1 };
/** OID for "IP=" IP address attributes, used with SKIP. */
- public static final ObjectIdentifier
- ipAddress_oid = new ObjectIdentifier (ipAddress_data);
+ public static final ObjectIdentifier ipAddress_oid = new ObjectIdentifier(ipAddress_data);
}
-
-
diff --git a/pki/base/util/src/netscape/security/x509/X500NameAttrMap.java b/pki/base/util/src/netscape/security/x509/X500NameAttrMap.java
index 48bb8302..9052c1a9 100644
--- a/pki/base/util/src/netscape/security/x509/X500NameAttrMap.java
+++ b/pki/base/util/src/netscape/security/x509/X500NameAttrMap.java
@@ -23,28 +23,25 @@ import java.util.Hashtable;
import netscape.security.util.ObjectIdentifier;
/**
- * Maps an attribute name in an X500 AVA to its OID and a
- * converter for the attribute type. The converter converts from a string to
- * its DER encoded attribute value. * For example, "CN" maps to its OID of
- * 2.5.4.3 and the Directory String Converter. The Directory String
- * Converter converts from a string to a DerValue with tag Printable, T.61 or
- * UniversalString.
- *
+ * Maps an attribute name in an X500 AVA to its OID and a converter for the
+ * attribute type. The converter converts from a string to its DER encoded
+ * attribute value. * For example, "CN" maps to its OID of 2.5.4.3 and the
+ * Directory String Converter. The Directory String Converter converts from a
+ * string to a DerValue with tag Printable, T.61 or UniversalString.
+ *
* @author Lily Hsiao, Slava Galperin at Netscape Communications, Inc.
*
*/
-public class X500NameAttrMap
-{
+public class X500NameAttrMap {
//
// public constructors.
//
- /**
+ /**
* Construct a X500NameAttrMap.
*/
- public X500NameAttrMap()
- {
+ public X500NameAttrMap() {
}
//
@@ -53,164 +50,152 @@ public class X500NameAttrMap
/**
* Get the attribute name (keyword) of the specified OID.
- *
- * @param oid An ObjectIdentifier
- *
- * @return An attribute name (keyword string) for the OID.
+ *
+ * @param oid An ObjectIdentifier
+ *
+ * @return An attribute name (keyword string) for the OID.
*/
- public String getName(ObjectIdentifier oid)
- {
- // XXX assert oid != null
- return oid2Name.get(oid);
+ public String getName(ObjectIdentifier oid) {
+ // XXX assert oid != null
+ return oid2Name.get(oid);
}
/**
* Get the ObjectIdentifier of the attribute name.
- *
- * @param name An attribute name (string of ascii characters)
- *
- * @return An ObjectIdentifier for the attribute.
+ *
+ * @param name An attribute name (string of ascii characters)
+ *
+ * @return An ObjectIdentifier for the attribute.
*/
- public ObjectIdentifier getOid(String name)
- {
- // XXX assert name != null
- return name2OID.get(name.toUpperCase());
+ public ObjectIdentifier getOid(String name) {
+ // XXX assert name != null
+ return name2OID.get(name.toUpperCase());
}
- /**
+ /**
* Get the Attribute Value Converter for the specified attribute name.
- *
- * @param name An attribute name
- *
- * @return An attribute value converter for the attribute name
+ *
+ * @param name An attribute name
+ *
+ * @return An attribute value converter for the attribute name
*/
- public AVAValueConverter getValueConverter(String name)
- {
- ObjectIdentifier oid =
- name2OID.get(name.toUpperCase());
- if (oid == null) return null;
- return (AVAValueConverter)oid2ValueConverter.get(oid);
+ public AVAValueConverter getValueConverter(String name) {
+ ObjectIdentifier oid =
+ name2OID.get(name.toUpperCase());
+ if (oid == null)
+ return null;
+ return (AVAValueConverter) oid2ValueConverter.get(oid);
}
- /**
+ /**
* Get the Attribute Value Converter for the specified ObjectIdentifier.
- *
- * @param oid An ObjectIdentifier
- *
- * @return An AVAValueConverter for the OID.
+ *
+ * @param oid An ObjectIdentifier
+ *
+ * @return An AVAValueConverter for the OID.
*/
- public AVAValueConverter getValueConverter(ObjectIdentifier oid)
- {
- return (AVAValueConverter)oid2ValueConverter.get(oid);
+ public AVAValueConverter getValueConverter(ObjectIdentifier oid) {
+ return (AVAValueConverter) oid2ValueConverter.get(oid);
}
/**
* Get an Enumeration of all attribute names in this map.
- *
- * @return An Enumeration of all attribute names.
+ *
+ * @return An Enumeration of all attribute names.
*/
- public Enumeration<String> getAllNames()
- {
- return name2OID.keys();
+ public Enumeration<String> getAllNames() {
+ return name2OID.keys();
}
/**
* Get an Enumeration of all ObjectIdentifiers in this map.
- *
- * @return An Enumeration of all OIDs in this map.
+ *
+ * @return An Enumeration of all OIDs in this map.
*/
- public Enumeration<ObjectIdentifier> getAllOIDs()
- {
- return oid2Name.keys();
+ public Enumeration<ObjectIdentifier> getAllOIDs() {
+ return oid2Name.keys();
}
- /**
+ /**
* Get the ObjectIdentifier object in the map for the specified OID.
- *
- * @param oid An ObjectIdentifier.
- * @return The ObjectIdentifier object in this map for the OID.
+ *
+ * @param oid An ObjectIdentifier.
+ * @return The ObjectIdentifier object in this map for the OID.
*/
- public ObjectIdentifier getOid(ObjectIdentifier oid)
- {
- String name = oid2Name.get(oid);
- if (name == null)
- return null;
- return name2OID.get(name);
+ public ObjectIdentifier getOid(ObjectIdentifier oid) {
+ String name = oid2Name.get(oid);
+ if (name == null)
+ return null;
+ return name2OID.get(name);
}
-
//
- // public add methods.
+ // public add methods.
//
- /**
- * Adds a attribute name, ObjectIdentifier, AVAValueConverter entry
- * to the map.
- *
- * @param name An attribute name (string of ascii chars)
- * @param oid The ObjectIdentifier for the attribute.
- * @param valueConverter An AVAValueConverter object for converting
- * an value for this attribute from a string to
- * a DerValue and vice versa.
+ /**
+ * Adds a attribute name, ObjectIdentifier, AVAValueConverter entry to the
+ * map.
+ *
+ * @param name An attribute name (string of ascii chars)
+ * @param oid The ObjectIdentifier for the attribute.
+ * @param valueConverter An AVAValueConverter object for converting an value
+ * for this attribute from a string to a DerValue and vice versa.
*/
- public void addNameOID(String name, ObjectIdentifier oid,
- AVAValueConverter valueConverter)
- {
- // normalize name for case insensitive compare.
- ObjectIdentifier theOid;
+ public void addNameOID(String name, ObjectIdentifier oid,
+ AVAValueConverter valueConverter) {
+ // normalize name for case insensitive compare.
+ ObjectIdentifier theOid;
Class<? extends AVAValueConverter> expValueConverter;
- theOid = name2OID.get(name);
- if (theOid != null) {
- expValueConverter = oid2ValueConverter.get(theOid).getClass();
- if (!theOid.equals(oid) ||
- expValueConverter != valueConverter.getClass()) {
- throw new IllegalArgumentException(
- "Another keyword-oid-valueConverter triple already " +
- "exists in the X500NameAttrMap ");
- }
- return;
- }
- name2OID.put(name.toUpperCase(), oid);
- oid2Name.put(oid, name.toUpperCase());
- oid2ValueConverter.put(oid, valueConverter);
+ theOid = name2OID.get(name);
+ if (theOid != null) {
+ expValueConverter = oid2ValueConverter.get(theOid).getClass();
+ if (!theOid.equals(oid) ||
+ expValueConverter != valueConverter.getClass()) {
+ throw new IllegalArgumentException(
+ "Another keyword-oid-valueConverter triple already " +
+ "exists in the X500NameAttrMap ");
+ }
+ return;
+ }
+ name2OID.put(name.toUpperCase(), oid);
+ oid2Name.put(oid, name.toUpperCase());
+ oid2ValueConverter.put(oid, valueConverter);
}
//
// public static methods.
- //
+ //
- /**
+ /**
* Get the global default X500NameAttrMap.
*
- * @return The global default X500NameAttrMap.
+ * @return The global default X500NameAttrMap.
*/
- public static X500NameAttrMap getDefault()
- {
- return defMap;
+ public static X500NameAttrMap getDefault() {
+ return defMap;
}
/**
- * Get the global default X500NamAttrMap using the DirStrConverter.
- *
- * @return The global default X500NameAttrMap using the DirStrConverter.
+ * Get the global default X500NamAttrMap using the DirStrConverter.
+ *
+ * @return The global default X500NameAttrMap using the DirStrConverter.
*/
- public static X500NameAttrMap getDirDefault()
- {
- return defDirMap;
+ public static X500NameAttrMap getDirDefault() {
+ return defDirMap;
}
- /**
- * Set the global default X500NameAttrMap.
- *
- * @param newDefault The new default X500NameAttrMap.
+ /**
+ * Set the global default X500NameAttrMap.
+ *
+ * @param newDefault The new default X500NameAttrMap.
*/
- public static void setDefault(X500NameAttrMap newDefault)
- {
- // XXX assert newDef != null
- defMap = newDefault;
+ public static void setDefault(X500NameAttrMap newDefault) {
+ // XXX assert newDef != null
+ defMap = newDefault;
}
//
@@ -229,84 +214,83 @@ public class X500NameAttrMap
private static X500NameAttrMap defDirMap;
- /*
- * Create the default maps on initialization.
+ /*
+ * Create the default maps on initialization.
*/
static {
- defMap = new X500NameAttrMap();
- AVAValueConverter directoryStr = new DirStrConverter(),
- ia5Str = new IA5StringConverter();
- defMap.addNameOID("CN",
- new ObjectIdentifier("2.5.4.3"),
- directoryStr);
- defMap.addNameOID("OU",
- new ObjectIdentifier("2.5.4.11"),
- directoryStr);
- defMap.addNameOID("O",
- new ObjectIdentifier("2.5.4.10"),
- directoryStr);
- // serialNumber added for CEP support
- defMap.addNameOID("SERIALNUMBER",
- new ObjectIdentifier("2.5.4.5"),
- new PrintableConverter());
- defMap.addNameOID("C",
- new ObjectIdentifier("2.5.4.6"),
- new PrintableConverter());
- defMap.addNameOID("L",
- new ObjectIdentifier("2.5.4.7"),
- directoryStr);
- defMap.addNameOID("ST",
- new ObjectIdentifier("2.5.4.8"),
- directoryStr);
- defMap.addNameOID("STREET",
- new ObjectIdentifier("2.5.4.9"),
- directoryStr);
- defMap.addNameOID("TITLE",
- new ObjectIdentifier("2.5.4.12"),
- directoryStr);
- // RFC 1274 UserId, rfc822MailBox
- defMap.addNameOID("UID",
- new ObjectIdentifier("0.9.2342.19200300.100.1.1"),
- directoryStr);
- defMap.addNameOID("MAIL",
- new ObjectIdentifier("0.9.2342.19200300.100.1.3"),
- ia5Str);
- // PKCS9 e-mail address
- defMap.addNameOID("E",
- new ObjectIdentifier("1.2.840.113549.1.9.1"),
- ia5Str);
-
- // DC definition from draft-ietf-asid-ldap-domains-02.txt
- defMap.addNameOID("DC",
- new ObjectIdentifier("0.9.2342.19200300.100.1.25"),
- ia5Str);
-
- // more defined in RFC2459 used in Subject Directory Attr extension
- defMap.addNameOID("SN", // surname
- new ObjectIdentifier("2.5.4.4"),
- directoryStr);
- defMap.addNameOID("GIVENNAME",
- new ObjectIdentifier("2.5.4.42"),
- directoryStr);
- defMap.addNameOID("INITIALS",
- new ObjectIdentifier("2.5.4.43"),
- directoryStr);
- defMap.addNameOID("GENERATIONQUALIFIER",
- new ObjectIdentifier("2.5.4.44"),
- directoryStr);
- defMap.addNameOID("DNQUALIFIER",
- new ObjectIdentifier("2.5.4.46"),
- directoryStr);
-
- // these two added mainly for CEP support
- // PKCS9 unstructured name
- defMap.addNameOID("UNSTRUCTUREDNAME",
- new ObjectIdentifier("1.2.840.113549.1.9.2"),
- ia5Str);
- // PKCS9 unstructured address
- defMap.addNameOID("UNSTRUCTUREDADDRESS",
- new ObjectIdentifier("1.2.840.113549.1.9.8"),
- new PrintableConverter());
+ defMap = new X500NameAttrMap();
+ AVAValueConverter directoryStr = new DirStrConverter(), ia5Str = new IA5StringConverter();
+ defMap.addNameOID("CN",
+ new ObjectIdentifier("2.5.4.3"),
+ directoryStr);
+ defMap.addNameOID("OU",
+ new ObjectIdentifier("2.5.4.11"),
+ directoryStr);
+ defMap.addNameOID("O",
+ new ObjectIdentifier("2.5.4.10"),
+ directoryStr);
+ // serialNumber added for CEP support
+ defMap.addNameOID("SERIALNUMBER",
+ new ObjectIdentifier("2.5.4.5"),
+ new PrintableConverter());
+ defMap.addNameOID("C",
+ new ObjectIdentifier("2.5.4.6"),
+ new PrintableConverter());
+ defMap.addNameOID("L",
+ new ObjectIdentifier("2.5.4.7"),
+ directoryStr);
+ defMap.addNameOID("ST",
+ new ObjectIdentifier("2.5.4.8"),
+ directoryStr);
+ defMap.addNameOID("STREET",
+ new ObjectIdentifier("2.5.4.9"),
+ directoryStr);
+ defMap.addNameOID("TITLE",
+ new ObjectIdentifier("2.5.4.12"),
+ directoryStr);
+ // RFC 1274 UserId, rfc822MailBox
+ defMap.addNameOID("UID",
+ new ObjectIdentifier("0.9.2342.19200300.100.1.1"),
+ directoryStr);
+ defMap.addNameOID("MAIL",
+ new ObjectIdentifier("0.9.2342.19200300.100.1.3"),
+ ia5Str);
+ // PKCS9 e-mail address
+ defMap.addNameOID("E",
+ new ObjectIdentifier("1.2.840.113549.1.9.1"),
+ ia5Str);
+
+ // DC definition from draft-ietf-asid-ldap-domains-02.txt
+ defMap.addNameOID("DC",
+ new ObjectIdentifier("0.9.2342.19200300.100.1.25"),
+ ia5Str);
+
+ // more defined in RFC2459 used in Subject Directory Attr extension
+ defMap.addNameOID("SN", // surname
+ new ObjectIdentifier("2.5.4.4"),
+ directoryStr);
+ defMap.addNameOID("GIVENNAME",
+ new ObjectIdentifier("2.5.4.42"),
+ directoryStr);
+ defMap.addNameOID("INITIALS",
+ new ObjectIdentifier("2.5.4.43"),
+ directoryStr);
+ defMap.addNameOID("GENERATIONQUALIFIER",
+ new ObjectIdentifier("2.5.4.44"),
+ directoryStr);
+ defMap.addNameOID("DNQUALIFIER",
+ new ObjectIdentifier("2.5.4.46"),
+ directoryStr);
+
+ // these two added mainly for CEP support
+ // PKCS9 unstructured name
+ defMap.addNameOID("UNSTRUCTUREDNAME",
+ new ObjectIdentifier("1.2.840.113549.1.9.2"),
+ ia5Str);
+ // PKCS9 unstructured address
+ defMap.addNameOID("UNSTRUCTUREDADDRESS",
+ new ObjectIdentifier("1.2.840.113549.1.9.8"),
+ new PrintableConverter());
};
static {
@@ -319,17 +303,17 @@ public class X500NameAttrMap
defDirMap.addNameOID("OU",
new ObjectIdentifier("2.5.4.11"),
directoryStr);
- defDirMap.addNameOID("O",
+ defDirMap.addNameOID("O",
new ObjectIdentifier("2.5.4.10"),
directoryStr);
// serialNumber added for CEP support
defDirMap.addNameOID("SERIALNUMBER",
new ObjectIdentifier("2.5.4.5"),
directoryStr);
- defDirMap.addNameOID("C",
+ defDirMap.addNameOID("C",
new ObjectIdentifier("2.5.4.6"),
directoryStr);
- defDirMap.addNameOID("L",
+ defDirMap.addNameOID("L",
new ObjectIdentifier("2.5.4.7"),
directoryStr);
defDirMap.addNameOID("ST",
@@ -359,8 +343,8 @@ public class X500NameAttrMap
directoryStr);
// more defined in RFC2459 used in Subject Directory Attr extension
- defDirMap.addNameOID("SN", // surname
- new ObjectIdentifier("2.5.4.4"),
+ defDirMap.addNameOID("SN", // surname
+ new ObjectIdentifier("2.5.4.4"),
directoryStr);
defDirMap.addNameOID("GIVENNAME",
new ObjectIdentifier("2.5.4.42"),
@@ -387,4 +371,3 @@ public class X500NameAttrMap
};
}
-
diff --git a/pki/base/util/src/netscape/security/x509/X500Signer.java b/pki/base/util/src/netscape/security/x509/X500Signer.java
index 93be4ba8..5d1180dd 100644
--- a/pki/base/util/src/netscape/security/x509/X500Signer.java
+++ b/pki/base/util/src/netscape/security/x509/X500Signer.java
@@ -23,47 +23,49 @@ import java.security.SignatureException;
import java.security.Signer;
/**
- * This class provides a binding between a Signature object and an
- * authenticated X.500 name (from an X.509 certificate chain), which
- * is needed in many public key signing applications.
- *
- * <P>The name of the signer is important, both because knowing it is the
- * whole point of the signature, and because the associated X.509 certificate
- * is always used to verify the signature.
- *
- * <P><em>The X.509 certificate chain is temporarily not associated with
+ * This class provides a binding between a Signature object and an authenticated
+ * X.500 name (from an X.509 certificate chain), which is needed in many public
+ * key signing applications.
+ *
+ * <P>
+ * The name of the signer is important, both because knowing it is the whole
+ * point of the signature, and because the associated X.509 certificate is
+ * always used to verify the signature.
+ *
+ * <P>
+ * <em>The X.509 certificate chain is temporarily not associated with
* the signer, but this omission will be resolved.</em>
- *
+ *
* @version 1.18
- *
+ *
* @author David Brownell
* @author Amit Kapoor
* @author Hemma Prafullchandra
*/
-public final class X500Signer extends Signer
-{
+public final class X500Signer extends Signer {
/**
*
*/
private static final long serialVersionUID = -3148659822293810158L;
+
/**
- * Called for each chunk of the data being signed. That
- * is, you can present the data in many chunks, so that
- * it doesn't need to be in a single sequential buffer.
- *
+ * Called for each chunk of the data being signed. That is, you can present
+ * the data in many chunks, so that it doesn't need to be in a single
+ * sequential buffer.
+ *
* @param buf buffer holding the next chunk of the data to be signed
* @param offset starting point of to-be-signed data
* @param len how many bytes of data are to be signed
* @exception SignatureException on errors.
*/
public void update(byte buf[], int offset, int len)
- throws SignatureException {
- sig.update (buf, offset, len);
+ throws SignatureException {
+ sig.update(buf, offset, len);
}
/**
* Produces the signature for the data processed by update().
- *
+ *
* @exception SignatureException on errors.
*/
public byte[] sign() throws SignatureException {
@@ -73,43 +75,43 @@ public final class X500Signer extends Signer
/**
* Returns the algorithm used to sign.
*/
- public AlgorithmId getAlgorithmId() {
+ public AlgorithmId getAlgorithmId() {
return algid;
}
/**
* Returns the name of the signing agent.
*/
- public X500Name getSigner() {
+ public X500Name getSigner() {
return agent;
}
/*
- * Constructs a binding between a signature and an X500 name
- * from an X.509 certificate.
+ * Constructs a binding between a signature and an X500 name from an X.509
+ * certificate.
*/
- // package private ----hmmmmm ?????
+ // package private ----hmmmmm ?????
public X500Signer(Signature sig, X500Name agent) {
- if (sig == null || agent == null)
- throw new IllegalArgumentException ("null parameter");
+ if (sig == null || agent == null)
+ throw new IllegalArgumentException("null parameter");
- this.sig = sig;
- this.agent = agent;
+ this.sig = sig;
+ this.agent = agent;
- try {
- this.algid = AlgorithmId.getAlgorithmId(sig.getAlgorithm());
- String alg = sig.getAlgorithm();
- if( alg.equals("DSA") ) {
- alg = "SHA1withDSA";
- }
- this.algid = AlgorithmId.getAlgorithmId(alg);
+ try {
+ this.algid = AlgorithmId.getAlgorithmId(sig.getAlgorithm());
+ String alg = sig.getAlgorithm();
+ if (alg.equals("DSA")) {
+ alg = "SHA1withDSA";
+ }
+ this.algid = AlgorithmId.getAlgorithmId(alg);
- } catch (NoSuchAlgorithmException e) {
- throw new RuntimeException("internal error! " + e.getMessage());
- }
+ } catch (NoSuchAlgorithmException e) {
+ throw new RuntimeException("internal error! " + e.getMessage());
+ }
}
-
- private Signature sig;
- private X500Name agent; // XXX should be X509CertChain
- private AlgorithmId algid;
+
+ private Signature sig;
+ private X500Name agent; // XXX should be X509CertChain
+ private AlgorithmId algid;
}
diff --git a/pki/base/util/src/netscape/security/x509/X509AttributeName.java b/pki/base/util/src/netscape/security/x509/X509AttributeName.java
index 4f62f61a..2f6c46cb 100644
--- a/pki/base/util/src/netscape/security/x509/X509AttributeName.java
+++ b/pki/base/util/src/netscape/security/x509/X509AttributeName.java
@@ -19,7 +19,7 @@ package netscape.security.x509;
/**
* This class is used to parse attribute names like "x509.info.extensions".
- *
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.4
@@ -35,7 +35,7 @@ public class X509AttributeName {
/**
* Default constructor for the class. Name is of the form
* "x509.info.extensions".
- *
+ *
* @param name the attribute name.
*/
public X509AttributeName(String name) {
@@ -52,13 +52,13 @@ public class X509AttributeName {
* Return the prefix of the name.
*/
public String getPrefix() {
- return (prefix);
+ return (prefix);
}
/**
* Return the suffix of the name.
*/
public String getSuffix() {
- return (suffix);
+ return (suffix);
}
}
diff --git a/pki/base/util/src/netscape/security/x509/X509CRLImpl.java b/pki/base/util/src/netscape/security/x509/X509CRLImpl.java
index 14cf3c01..5c3588b6 100755
--- a/pki/base/util/src/netscape/security/x509/X509CRLImpl.java
+++ b/pki/base/util/src/netscape/security/x509/X509CRLImpl.java
@@ -51,19 +51,19 @@ import netscape.security.util.ObjectIdentifier;
* An implmentation for X509 CRL (Certificate Revocation List).
* <p>
* The X.509 v2 CRL format is described below in ASN.1:
+ *
* <pre>
* </pre>
* <p>
- * CertificateList ::= SEQUENCE {
- * tbsCertList TBSCertList,
- * signatureAlgorithm AlgorithmIdentifier,
- * signature BIT STRING }
+ * CertificateList ::= SEQUENCE { tbsCertList TBSCertList, signatureAlgorithm
+ * AlgorithmIdentifier, signature BIT STRING }
* <p>
- * A good description and profiling is provided in the IETF PKIX WG
- * draft, Part I: X.509 Certificate and CRL Profile,
+ * A good description and profiling is provided in the IETF PKIX WG draft, Part
+ * I: X.509 Certificate and CRL Profile,
* &lt;draft-ietf-pkix-ipki-part1-06.txt&gt;.
* <p>
* The ASN.1 definition of <code>tbsCertList</code> is:
+ *
* <pre>
* TBSCertList ::= SEQUENCE {
* version Version OPTIONAL,
@@ -82,7 +82,7 @@ import netscape.security.util.ObjectIdentifier;
* -- if present, must be v2
* }
* </pre>
- *
+ *
* @author Hemma Prafullchandra
* @version 1.8
* @see X509CRL
@@ -90,39 +90,38 @@ import netscape.security.util.ObjectIdentifier;
public class X509CRLImpl extends X509CRL {
// CRL data, and its envelope
- private byte[] signedCRL = null; // DER encoded crl
- private byte[] signature = null; // raw signature bits
- private byte[] tbsCertList = null; // DER encoded "to-be-signed" CRL
- private AlgorithmId sigAlgId; // sig alg in CRL
+ private byte[] signedCRL = null; // DER encoded crl
+ private byte[] signature = null; // raw signature bits
+ private byte[] tbsCertList = null; // DER encoded "to-be-signed" CRL
+ private AlgorithmId sigAlgId; // sig alg in CRL
// crl information
- private int version;
- private AlgorithmId infoSigAlgId; // sig alg in "to-be-signed" crl
- private X500Name issuer;
- private Date thisUpdate = null;
- private Date nextUpdate = null;
-// private static final Hashtable revokedCerts = new Hashtable();
- private Hashtable<BigInteger,RevokedCertificate> revokedCerts = new Hashtable<BigInteger, RevokedCertificate>();
-// private static CRLExtensions extensions = null;
- private CRLExtensions extensions = null;
+ private int version;
+ private AlgorithmId infoSigAlgId; // sig alg in "to-be-signed" crl
+ private X500Name issuer;
+ private Date thisUpdate = null;
+ private Date nextUpdate = null;
+ // private static final Hashtable revokedCerts = new Hashtable();
+ private Hashtable<BigInteger, RevokedCertificate> revokedCerts = new Hashtable<BigInteger, RevokedCertificate>();
+ // private static CRLExtensions extensions = null;
+ private CRLExtensions extensions = null;
private boolean entriesIncluded = true;
private final static boolean isExplicit = true;
private boolean readOnly = false;
/**
- * Unmarshals an X.509 CRL from its encoded form, parsing the encoded
- * bytes. This form of constructor is used by agents which
- * need to examine and use CRL contents. Note that the buffer
- * must include only one CRL, and no "garbage" may be left at
- * the end.
- *
+ * Unmarshals an X.509 CRL from its encoded form, parsing the encoded bytes.
+ * This form of constructor is used by agents which need to examine and use
+ * CRL contents. Note that the buffer must include only one CRL, and no
+ * "garbage" may be left at the end.
+ *
* @param crlData the encoded bytes, with no trailing padding.
* @exception CRLException on parsing errors.
* @exception X509ExtensionException on extension handling errors.
*/
public X509CRLImpl(byte[] crlData)
- throws CRLException, X509ExtensionException {
+ throws CRLException, X509ExtensionException {
try {
DerValue in = new DerValue(crlData);
@@ -134,7 +133,7 @@ public class X509CRLImpl extends X509CRL {
}
public X509CRLImpl(byte[] crlData, boolean includeEntries)
- throws CRLException, X509ExtensionException {
+ throws CRLException, X509ExtensionException {
try {
entriesIncluded = includeEntries;
DerValue in = new DerValue(crlData);
@@ -147,15 +146,15 @@ public class X509CRLImpl extends X509CRL {
}
/**
- * Unmarshals an X.509 CRL from an input stream. Only one CRL
- * is expected at the end of the input stream.
- *
+ * Unmarshals an X.509 CRL from an input stream. Only one CRL is expected at
+ * the end of the input stream.
+ *
* @param inStrm an input stream holding at least one CRL
* @exception CRLException on parsing errors.
* @exception X509ExtensionException on extension handling errors.
*/
public X509CRLImpl(InputStream inStrm)
- throws CRLException, X509ExtensionException {
+ throws CRLException, X509ExtensionException {
try {
DerValue val = new DerValue(inStrm);
@@ -168,7 +167,7 @@ public class X509CRLImpl extends X509CRL {
/**
* Initial CRL constructor, no revoked certs, and no extensions.
- *
+ *
* @param issuer the name of the CA issuing this CRL.
* @param thisUpdate the Date of this issue.
* @param nextUpdate the Date of the next CRL.
@@ -181,18 +180,18 @@ public class X509CRLImpl extends X509CRL {
/**
* CRL constructor, revoked certs, no extensions.
- *
+ *
* @param issuer the name of the CA issuing this CRL.
* @param thisUpdate the Date of this issue.
* @param nextUpdate the Date of the next CRL.
* @param badCerts the array of revoked certificates.
- *
+ *
* @exception CRLException on parsing/construction errors.
* @exception X509ExtensionException on extension handling errors.
*/
public X509CRLImpl(X500Name issuer, Date thisDate, Date nextDate,
RevokedCertificate[] badCerts)
- throws CRLException, X509ExtensionException {
+ throws CRLException, X509ExtensionException {
this.issuer = issuer;
this.thisUpdate = thisDate;
this.nextUpdate = nextDate;
@@ -205,19 +204,19 @@ public class X509CRLImpl extends X509CRL {
/**
* CRL constructor, revoked certs and extensions.
- *
+ *
* @param issuer the name of the CA issuing this CRL.
* @param thisUpdate the Date of this issue.
* @param nextUpdate the Date of the next CRL.
* @param badCerts the array of revoked certificates.
* @param crlExts the CRL extensions.
- *
+ *
* @exception CRLException on parsing/construction errors.
* @exception X509ExtensionException on extension handling errors.
*/
public X509CRLImpl(X500Name issuer, Date thisDate, Date nextDate,
RevokedCertificate[] badCerts, CRLExtensions crlExts)
- throws CRLException, X509ExtensionException {
+ throws CRLException, X509ExtensionException {
this.issuer = issuer;
this.thisUpdate = thisDate;
this.nextUpdate = nextDate;
@@ -237,13 +236,11 @@ public class X509CRLImpl extends X509CRL {
}
}
-
/**
- * CRL constructor, revoked certs and extensions.
- * This will be used by code that constructs CRL and uses
- * encodeInfo() in order to sign it using external means
- * (other than sign() method)
- *
+ * CRL constructor, revoked certs and extensions. This will be used by code
+ * that constructs CRL and uses encodeInfo() in order to sign it using
+ * external means (other than sign() method)
+ *
* @param issuer the name of the CA issuing this CRL.
* @param sigAlg signing algorithm id
* @param thisUpdate the Date of this issue.
@@ -253,29 +250,28 @@ public class X509CRLImpl extends X509CRL {
*/
public X509CRLImpl(X500Name issuer, AlgorithmId algId, Date thisDate, Date nextDate,
RevokedCertificate[] badCerts, CRLExtensions crlExts)
- throws CRLException, X509ExtensionException {
- this(issuer,thisDate,nextDate,badCerts,crlExts);
+ throws CRLException, X509ExtensionException {
+ this(issuer, thisDate, nextDate, badCerts, crlExts);
infoSigAlgId = algId;
}
-
/**
* CRL constructor, revoked certs and extensions.
- *
+ *
* @param issuer the name of the CA issuing this CRL.
* @param sigAlg signing algorithm id
* @param thisUpdate the Date of this issue.
* @param nextUpdate the Date of the next CRL.
* @param badCerts the hashtable of revoked certificates.
* @param crlExts the CRL extensions.
- *
+ *
* @exception CRLException on parsing/construction errors.
* @exception X509ExtensionException on extension handling errors.
*/
public X509CRLImpl(X500Name issuer, AlgorithmId algId,
Date thisDate, Date nextDate,
- Hashtable<BigInteger,RevokedCertificate> badCerts, CRLExtensions crlExts)
- throws CRLException, X509ExtensionException {
+ Hashtable<BigInteger, RevokedCertificate> badCerts, CRLExtensions crlExts)
+ throws CRLException, X509ExtensionException {
this.issuer = issuer;
this.thisUpdate = thisDate;
this.nextUpdate = nextDate;
@@ -287,10 +283,9 @@ public class X509CRLImpl extends X509CRL {
infoSigAlgId = algId;
}
-
/**
* Returns the ASN.1 DER encoded form of this CRL.
- *
+ *
* @exception CRLException if an encoding error occurs.
*/
public byte[] getEncoded() throws CRLException {
@@ -303,7 +298,7 @@ public class X509CRLImpl extends X509CRL {
/**
* Returns true if signedCRL was set.
- *
+ *
* @param byte array of containing signed CRL.
*/
public boolean setSignedCRL(byte[] crl) {
@@ -316,20 +311,20 @@ public class X509CRLImpl extends X509CRL {
return done;
}
- public boolean hasUnsupportedCriticalExtension() {
- // XXX NOT IMPLEMENTED
- return true;
- }
+ public boolean hasUnsupportedCriticalExtension() {
+ // XXX NOT IMPLEMENTED
+ return true;
+ }
/**
* Encodes the "to-be-signed" CRL to the OutputStream.
- *
+ *
* @param out the OutputStream to write to.
* @exception CRLException on encoding errors.
* @exception X509ExtensionException on extension encoding errors.
*/
public void encodeInfo(OutputStream out)
- throws CRLException, X509ExtensionException {
+ throws CRLException, X509ExtensionException {
try {
DerOutputStream tmp = new DerOutputStream();
DerOutputStream rCerts = new DerOutputStream();
@@ -346,10 +341,9 @@ public class X509CRLImpl extends X509CRL {
if (nextUpdate != null)
tmp.putUTCTime(nextUpdate);
- if (! revokedCerts.isEmpty()) {
- for (Enumeration<RevokedCertificate> e = revokedCerts.elements();
- e.hasMoreElements();)
- ((RevokedCertImpl)e.nextElement()).encode(rCerts);
+ if (!revokedCerts.isEmpty()) {
+ for (Enumeration<RevokedCertificate> e = revokedCerts.elements(); e.hasMoreElements();)
+ ((RevokedCertImpl) e.nextElement()).encode(rCerts);
tmp.write(DerValue.tag_Sequence, rCerts);
}
@@ -361,64 +355,61 @@ public class X509CRLImpl extends X509CRL {
tbsCertList = seq.toByteArray();
out.write(tbsCertList);
} catch (IOException e) {
- throw new CRLException("Encoding error: " + e.getMessage());
+ throw new CRLException("Encoding error: " + e.getMessage());
}
}
/**
- * Verifies that this CRL was signed using the
- * private key that corresponds to the specified public key.
- *
+ * Verifies that this CRL was signed using the private key that corresponds
+ * to the specified public key.
+ *
* @param key the PublicKey used to carry out the verification.
- *
- * @exception NoSuchAlgorithmException on unsupported signature
- * algorithms.
+ *
+ * @exception NoSuchAlgorithmException on unsupported signature algorithms.
* @exception InvalidKeyException on incorrect key.
* @exception NoSuchProviderException if there's no default provider.
* @exception SignatureException on signature errors.
* @exception CRLException on encoding errors.
*/
public void verify(PublicKey key)
- throws CRLException, NoSuchAlgorithmException, InvalidKeyException,
- NoSuchProviderException, SignatureException {
+ throws CRLException, NoSuchAlgorithmException, InvalidKeyException,
+ NoSuchProviderException, SignatureException {
verify(key, null);
}
/**
- * Verifies that this CRL was signed using the
- * private key that corresponds to the specified public key,
- * and that the signature verification was computed by
- * the given provider.
- *
+ * Verifies that this CRL was signed using the private key that corresponds
+ * to the specified public key, and that the signature verification was
+ * computed by the given provider.
+ *
* @param key the PublicKey used to carry out the verification.
* @param sigProvider the name of the signature provider.
- *
- * @exception NoSuchAlgorithmException on unsupported signature
- * algorithms.
+ *
+ * @exception NoSuchAlgorithmException on unsupported signature algorithms.
* @exception InvalidKeyException on incorrect key.
* @exception NoSuchProviderException on incorrect provider.
* @exception SignatureException on signature errors.
* @exception CRLException on encoding errors.
*/
public void verify(PublicKey key, String sigProvider)
- throws CRLException, NoSuchAlgorithmException, InvalidKeyException,
- NoSuchProviderException, SignatureException {
+ throws CRLException, NoSuchAlgorithmException, InvalidKeyException,
+ NoSuchProviderException, SignatureException {
if (signedCRL == null) {
throw new CRLException("Uninitialized CRL");
}
- Signature sigVerf = null;
+ Signature sigVerf = null;
String sigAlg = sigAlgId.getName();
if (sigProvider.equals("Mozilla-JSS")) {
- if (sigAlg.equals("MD5withRSA")) {
- sigAlg = "MD5/RSA";
- } else if (sigAlg.equals("MD2withRSA")) {
- sigAlg = "MD2/RSA";
- } else if (sigAlg.equals("SHA1withRSA")) {
- sigAlg = "SHA1/RSA";
- } else if (sigAlg.equals("SHA1withDSA")) {
- sigAlg = "SHA1/DSA";
- }
+ if (sigAlg.equals("MD5withRSA")) {
+ sigAlg = "MD5/RSA";
+ } else if (sigAlg.equals("MD2withRSA")) {
+ sigAlg = "MD2/RSA";
+ } else if (sigAlg.equals("SHA1withRSA")) {
+ sigAlg = "SHA1/RSA";
+ } else if (sigAlg.equals("SHA1withDSA")) {
+ sigAlg = "SHA1/DSA";
+ }
}
sigVerf = Signature.getInstance(sigAlg, sigProvider);
sigVerf.initVerify(key);
@@ -434,14 +425,12 @@ public class X509CRLImpl extends X509CRL {
}
/**
- * Encodes an X.509 CRL, and signs it using the key
- * passed.
- *
+ * Encodes an X.509 CRL, and signs it using the key passed.
+ *
* @param key the private key used for signing.
* @param algorithm the name of the signature algorithm used.
- *
- * @exception NoSuchAlgorithmException on unsupported signature
- * algorithms.
+ *
+ * @exception NoSuchAlgorithmException on unsupported signature algorithms.
* @exception InvalidKeyException on incorrect key.
* @exception NoSuchProviderException on incorrect provider.
* @exception SignatureException on signature errors.
@@ -449,21 +438,19 @@ public class X509CRLImpl extends X509CRL {
* @exception X509ExtensionException on any extension errors.
*/
public void sign(PrivateKey key, String algorithm)
- throws CRLException, NoSuchAlgorithmException, InvalidKeyException,
- NoSuchProviderException, SignatureException, X509ExtensionException {
+ throws CRLException, NoSuchAlgorithmException, InvalidKeyException,
+ NoSuchProviderException, SignatureException, X509ExtensionException {
sign(key, algorithm, null);
}
/**
- * Encodes an X.509 CRL, and signs it using the key
- * passed.
- *
+ * Encodes an X.509 CRL, and signs it using the key passed.
+ *
* @param key the private key used for signing.
* @param algorithm the name of the signature algorithm used.
* @param provider the name of the provider.
- *
- * @exception NoSuchAlgorithmException on unsupported signature
- * algorithms.
+ *
+ * @exception NoSuchAlgorithmException on unsupported signature algorithms.
* @exception InvalidKeyException on incorrect key.
* @exception NoSuchProviderException on incorrect provider.
* @exception SignatureException on signature errors.
@@ -471,8 +458,8 @@ public class X509CRLImpl extends X509CRL {
* @exception X509ExtensionException on any extension errors.
*/
public void sign(PrivateKey key, String algorithm, String provider)
- throws CRLException, NoSuchAlgorithmException, InvalidKeyException,
- NoSuchProviderException, SignatureException, X509ExtensionException {
+ throws CRLException, NoSuchAlgorithmException, InvalidKeyException,
+ NoSuchProviderException, SignatureException, X509ExtensionException {
try {
if (readOnly)
throw new CRLException("cannot over-write existing CRL");
@@ -484,7 +471,7 @@ public class X509CRLImpl extends X509CRL {
sigEngine.initSign(key);
- // in case the name is reset
+ // in case the name is reset
sigAlgId = AlgorithmId.get(sigEngine.getAlgorithm());
infoSigAlgId = sigAlgId;
@@ -515,12 +502,12 @@ public class X509CRLImpl extends X509CRL {
/**
* Returns a printable string of this CRL.
- *
+ *
* @return value of this CRL in a printable form.
*/
public String toString() {
StringBuffer sb = new StringBuffer();
- sb.append("X.509 CRL v" + (version+1) + "\n");
+ sb.append("X.509 CRL v" + (version + 1) + "\n");
sb.append("Signature Algorithm: " + sigAlgId.toString() +
", OID=" + (sigAlgId.getOID()).toString() + "\n");
sb.append("Issuer: " + issuer.toString() + "\n");
@@ -531,19 +518,18 @@ public class X509CRLImpl extends X509CRL {
sb.append("\nNO certificates have been revoked\n");
else {
sb.append("\nRevoked Certificates:\n");
- for (Enumeration<RevokedCertificate> e = revokedCerts.elements();
- e.hasMoreElements();)
- sb.append(((RevokedCertificate)e.nextElement()).toString());
+ for (Enumeration<RevokedCertificate> e = revokedCerts.elements(); e.hasMoreElements();)
+ sb.append(((RevokedCertificate) e.nextElement()).toString());
}
if (extensions != null) {
for (int i = 0; i < extensions.size(); i++) {
sb.append("\nCRL Extension[" + i + "]: " +
- ((Extension)(extensions.elementAt(i))).toString());
+ ((Extension) (extensions.elementAt(i))).toString());
}
}
- netscape.security.util.PrettyPrintFormat pp =
- new netscape.security.util.PrettyPrintFormat(" ", 20);
- String signaturebits = pp.toHexString(signature);
+ netscape.security.util.PrettyPrintFormat pp =
+ new netscape.security.util.PrettyPrintFormat(" ", 20);
+ String signaturebits = pp.toHexString(signature);
sb.append("\nSignature:\n" + signaturebits);
return sb.toString();
@@ -551,10 +537,9 @@ public class X509CRLImpl extends X509CRL {
/**
* Checks whether the given serial number is on this CRL.
- *
+ *
* @param serialNumber the number to check for.
- * @return true if the given serial number is on this CRL,
- * false otherwise.
+ * @return true if the given serial number is on this CRL, false otherwise.
*/
public boolean isRevoked(BigInteger serialNumber) {
if (revokedCerts == null || revokedCerts.isEmpty())
@@ -562,24 +547,25 @@ public class X509CRLImpl extends X509CRL {
return revokedCerts.containsKey(serialNumber);
}
- public boolean isRevoked(Certificate cert) {
- if (cert == null)
- return false;
- if (cert instanceof X509Certificate) {
- return isRevoked(((X509Certificate)cert).getSerialNumber());
- } else {
- return false;
- }
- }
+ public boolean isRevoked(Certificate cert) {
+ if (cert == null)
+ return false;
+ if (cert instanceof X509Certificate) {
+ return isRevoked(((X509Certificate) cert).getSerialNumber());
+ } else {
+ return false;
+ }
+ }
/**
- * Gets the version number from the CRL.
- * The ASN.1 definition for this is:
+ * Gets the version number from the CRL. The ASN.1 definition for this is:
+ *
* <pre>
* Version ::= INTEGER { v1(0), v2(1), v3(2) }
* -- v3 does not apply to CRLs but appears for consistency
* -- with definition of Version for certs
* </pre>
+ *
* @return the version number.
*/
public int getVersion() {
@@ -587,41 +573,41 @@ public class X509CRLImpl extends X509CRL {
}
/**
- * Gets the issuer distinguished name from this CRL.
- * The issuer name identifies the entity who has signed (and
- * issued the CRL). The issuer name field contains an
- * X.500 distinguished name (DN).
- * The ASN.1 definition for this is:
+ * Gets the issuer distinguished name from this CRL. The issuer name
+ * identifies the entity who has signed (and issued the CRL). The issuer
+ * name field contains an X.500 distinguished name (DN). The ASN.1
+ * definition for this is:
+ *
* <pre>
* issuer Name
- *
+ *
* Name ::= CHOICE { RDNSequence }
* RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
* RelativeDistinguishedName ::=
* SET OF AttributeValueAssertion
- *
+ *
* AttributeValueAssertion ::= SEQUENCE {
* AttributeType,
* AttributeValue }
* AttributeType ::= OBJECT IDENTIFIER
* AttributeValue ::= ANY
* </pre>
- * The Name describes a hierarchical name composed of attributes,
- * such as country name, and corresponding values, such as US.
- * The type of the component AttributeValue is determined by the
- * AttributeType; in general it will be a directoryString.
- * A directoryString is usually one of PrintableString,
- * TeletexString or UniversalString.
+ *
+ * The Name describes a hierarchical name composed of attributes, such as
+ * country name, and corresponding values, such as US. The type of the
+ * component AttributeValue is determined by the AttributeType; in general
+ * it will be a directoryString. A directoryString is usually one of
+ * PrintableString, TeletexString or UniversalString.
+ *
* @return the issuer name.
*/
public Principal getIssuerDN() {
- return (Principal)issuer;
+ return (Principal) issuer;
}
/**
- * Gets the thisUpdate date from the CRL.
- * The ASN.1 definition for this is:
- *
+ * Gets the thisUpdate date from the CRL. The ASN.1 definition for this is:
+ *
* @return the thisUpdate date from the CRL.
*/
public Date getThisUpdate() {
@@ -630,9 +616,8 @@ public class X509CRLImpl extends X509CRL {
/**
* Gets the nextUpdate date from the CRL.
- *
- * @return the nextUpdate date from the CRL, or null if
- * not present.
+ *
+ * @return the nextUpdate date from the CRL, or null if not present.
*/
public Date getNextUpdate() {
if (nextUpdate == null)
@@ -641,27 +626,25 @@ public class X509CRLImpl extends X509CRL {
}
/**
- * Get the revoked certificate from the CRL by the serial
- * number provided.
- *
- * @return the revoked certificate or null if there is
- * no entry in the CRL marked with the provided serial number.
+ * Get the revoked certificate from the CRL by the serial number provided.
+ *
+ * @return the revoked certificate or null if there is no entry in the CRL
+ * marked with the provided serial number.
* @see RevokedCertificate
*/
public X509CRLEntry getRevokedCertificate(BigInteger serialNumber) {
if (revokedCerts == null || revokedCerts.isEmpty())
return null;
RevokedCertificate badCert =
- (RevokedCertificate)revokedCerts.get(serialNumber);
+ (RevokedCertificate) revokedCerts.get(serialNumber);
return badCert;
}
/**
- * Gets all the revoked certificates from the CRL.
- * A Set of RevokedCertificate.
- *
- * @return all the revoked certificates or null if there are
- * none.
+ * Gets all the revoked certificates from the CRL. A Set of
+ * RevokedCertificate.
+ *
+ * @return all the revoked certificates or null if there are none.
* @see RevokedCertificate
*/
public Set<RevokedCertificate> getRevokedCertificates() {
@@ -674,11 +657,11 @@ public class X509CRLImpl extends X509CRL {
}
@SuppressWarnings("unchecked")
- public Hashtable<BigInteger,RevokedCertificate> getListOfRevokedCertificates() {
- if (revokedCerts == null){
+ public Hashtable<BigInteger, RevokedCertificate> getListOfRevokedCertificates() {
+ if (revokedCerts == null) {
return null;
- }else{
- return (Hashtable<BigInteger,RevokedCertificate>)revokedCerts.clone();
+ } else {
+ return (Hashtable<BigInteger, RevokedCertificate>) revokedCerts.clone();
}
}
@@ -690,16 +673,15 @@ public class X509CRLImpl extends X509CRL {
}
/**
- * Gets the DER encoded CRL information, the
- * <code>tbsCertList</code> from this CRL.
- * This can be used to verify the signature independently.
- *
+ * Gets the DER encoded CRL information, the <code>tbsCertList</code> from
+ * this CRL. This can be used to verify the signature independently.
+ *
* @return the DER encoded CRL information.
* @exception CRLException on parsing errors.
* @exception X509ExtensionException on extension parsing errors.
*/
public byte[] getTBSCertList()
- throws CRLException {
+ throws CRLException {
if (tbsCertList == null)
throw new CRLException("Uninitialized CRL");
byte[] dup = new byte[tbsCertList.length];
@@ -709,7 +691,7 @@ public class X509CRLImpl extends X509CRL {
/**
* Gets the raw Signature bits from the CRL.
- *
+ *
* @return the signature.
*/
public byte[] getSignature() {
@@ -722,7 +704,7 @@ public class X509CRLImpl extends X509CRL {
/**
* Returns true if signature was set.
- *
+ *
* @param byte array of containing CRL signature.
*/
public boolean setSignature(byte[] crlSignature) {
@@ -736,9 +718,9 @@ public class X509CRLImpl extends X509CRL {
}
/**
- * Gets the signature algorithm name for the CRL
- * signature algorithm. For example, the string "SHA1withDSA".
- * The ASN.1 definition for this is:
+ * Gets the signature algorithm name for the CRL signature algorithm. For
+ * example, the string "SHA1withDSA". The ASN.1 definition for this is:
+ *
* <pre>
* AlgorithmIdentifier ::= SEQUENCE {
* algorithm OBJECT IDENTIFIER,
@@ -747,118 +729,112 @@ public class X509CRLImpl extends X509CRL {
* -- registered for use with the
* -- algorithm object identifier value
* </pre>
- *
+ *
* @return the signature algorithm name.
*/
public String getSigAlgName() {
if (sigAlgId == null)
return null;
- return sigAlgId.getName();
+ return sigAlgId.getName();
}
/**
- * Gets the signature algorithm OID string from the CRL.
- * An OID is represented by a set of positive whole number separated
- * by ".", that means,<br>
+ * Gets the signature algorithm OID string from the CRL. An OID is
+ * represented by a set of positive whole number separated by ".", that
+ * means,<br>
* &lt;positive whole number&gt;.&lt;positive whole number&gt;.&lt;...&gt;
- * For example, the string "1.2.840.10040.4.3" identifies the SHA-1
- * with DSA signature algorithm, as per the PKIX part I.
- *
+ * For example, the string "1.2.840.10040.4.3" identifies the SHA-1 with DSA
+ * signature algorithm, as per the PKIX part I.
+ *
* @return the signature algorithm oid string.
*/
public String getSigAlgOID() {
if (sigAlgId == null)
return null;
- ObjectIdentifier oid = sigAlgId.getOID();
- return oid.toString();
+ ObjectIdentifier oid = sigAlgId.getOID();
+ return oid.toString();
}
/**
- * Gets the DER encoded signature algorithm parameters from this
- * CRL's signature algorithm. In most cases, the signature
- * algorithm parameters are null, the parameters are usually
- * supplied with the Public Key.
- *
- * @return the DER encoded signature algorithm parameters, or
- * null if no parameters are present.
+ * Gets the DER encoded signature algorithm parameters from this CRL's
+ * signature algorithm. In most cases, the signature algorithm parameters
+ * are null, the parameters are usually supplied with the Public Key.
+ *
+ * @return the DER encoded signature algorithm parameters, or null if no
+ * parameters are present.
*/
public byte[] getSigAlgParams() {
if (sigAlgId == null)
return null;
- try {
- return sigAlgId.getEncodedParams();
- } catch (IOException e) {
+ try {
+ return sigAlgId.getEncodedParams();
+ } catch (IOException e) {
return null;
- }
+ }
}
/**
- * Gets a Set of the extension(s) marked CRITICAL in the
- * CRL by OID strings.
- *
- * @return a set of the extension oid strings in the
- * CRL that are marked critical.
+ * Gets a Set of the extension(s) marked CRITICAL in the CRL by OID strings.
+ *
+ * @return a set of the extension oid strings in the CRL that are marked
+ * critical.
*/
public Set<String> getCriticalExtensionOIDs() {
if (extensions == null)
return null;
Set<String> extSet = new TreeSet<String>();
Extension ex;
- for (Enumeration<Extension> e = extensions.getElements();
- e.hasMoreElements();) {
- ex = e.nextElement();
- if (ex.isCritical()){
- extSet.add(((ObjectIdentifier)ex.getExtensionId()).toString());
+ for (Enumeration<Extension> e = extensions.getElements(); e.hasMoreElements();) {
+ ex = e.nextElement();
+ if (ex.isCritical()) {
+ extSet.add(((ObjectIdentifier) ex.getExtensionId()).toString());
}
}
return extSet;
}
/**
- * Gets a Set of the extension(s) marked NON-CRITICAL in the
- * CRL by OID strings.
- *
- * @return a set of the extension oid strings in the
- * CRL that are NOT marked critical.
+ * Gets a Set of the extension(s) marked NON-CRITICAL in the CRL by OID
+ * strings.
+ *
+ * @return a set of the extension oid strings in the CRL that are NOT marked
+ * critical.
*/
public Set<String> getNonCriticalExtensionOIDs() {
if (extensions == null)
return null;
Set<String> extSet = new TreeSet<String>();
Extension ex;
- for (Enumeration<Extension> e = extensions.getElements();
- e.hasMoreElements();) {
+ for (Enumeration<Extension> e = extensions.getElements(); e.hasMoreElements();) {
ex = e.nextElement();
- if ( ! ex.isCritical())
- extSet.add(((ObjectIdentifier)ex.getExtensionId()).toString());
- }
+ if (!ex.isCritical())
+ extSet.add(((ObjectIdentifier) ex.getExtensionId()).toString());
+ }
return extSet;
}
/**
- * Gets the DER encoded OCTET string for the extension value
- * (<code>extnValue</code>) identified by the passed in oid String.
- * The <code>oid</code> string is
- * represented by a set of positive whole number separated
- * by ".", that means,<br>
+ * Gets the DER encoded OCTET string for the extension value (
+ * <code>extnValue</code>) identified by the passed in oid String. The
+ * <code>oid</code> string is represented by a set of positive whole number
+ * separated by ".", that means,<br>
* &lt;positive whole number&gt;.&lt;positive whole number&gt;.&lt;...&gt;
- *
+ *
* @param oid the Object Identifier value for the extension.
* @return the der encoded octet string of the extension value.
*/
public byte[] getExtensionValue(String oid) {
if (extensions == null)
return null;
- try {
- String extAlias = OIDMap.getName(new ObjectIdentifier(oid));
+ try {
+ String extAlias = OIDMap.getName(new ObjectIdentifier(oid));
Extension crlExt = null;
if (extAlias == null) { // may be unknown
ObjectIdentifier findOID = new ObjectIdentifier(oid);
Extension ex = null;
ObjectIdentifier inCertOID;
- for (Enumeration<Extension> e=extensions.getElements();
- e.hasMoreElements();) {
+ for (Enumeration<Extension> e = extensions.getElements(); e.hasMoreElements();) {
ex = e.nextElement();
inCertOID = ex.getExtensionId();
if (inCertOID.equals(findOID)) {
@@ -868,35 +844,35 @@ public class X509CRLImpl extends X509CRL {
}
} else
crlExt = extensions.get(extAlias);
- if (crlExt == null)
+ if (crlExt == null)
return null;
- byte[] extData = crlExt.getExtensionValue();
+ byte[] extData = crlExt.getExtensionValue();
if (extData == null)
return null;
- DerOutputStream out = new DerOutputStream();
- out.putOctetString(extData);
+ DerOutputStream out = new DerOutputStream();
+ out.putOctetString(extData);
return out.toByteArray();
} catch (Exception e) {
return null;
- }
+ }
}
public BigInteger getCRLNumber() {
- try {
- CRLExtensions exts = getExtensions();
- if (exts == null)
- return null;
- Enumeration<Extension> e = exts.getElements();
- while (e.hasMoreElements()) {
- Extension ext = (Extension)e.nextElement();
- if (ext instanceof CRLNumberExtension) {
- CRLNumberExtension numExt = (CRLNumberExtension)ext;
- return (BigInteger)numExt.get(CRLNumberExtension.NUMBER);
- }
+ try {
+ CRLExtensions exts = getExtensions();
+ if (exts == null)
+ return null;
+ Enumeration<Extension> e = exts.getElements();
+ while (e.hasMoreElements()) {
+ Extension ext = (Extension) e.nextElement();
+ if (ext instanceof CRLNumberExtension) {
+ CRLNumberExtension numExt = (CRLNumberExtension) ext;
+ return (BigInteger) numExt.get(CRLNumberExtension.NUMBER);
+ }
+ }
+ } catch (Exception e) {
}
- } catch (Exception e) {
- }
- return null;
+ return null;
}
public BigInteger getDeltaBaseCRLNumber() {
@@ -906,10 +882,10 @@ public class X509CRLImpl extends X509CRL {
return null;
Enumeration<Extension> e = exts.getElements();
while (e.hasMoreElements()) {
- Extension ext = (Extension)e.nextElement();
+ Extension ext = (Extension) e.nextElement();
if (ext instanceof DeltaCRLIndicatorExtension) {
- DeltaCRLIndicatorExtension numExt = (DeltaCRLIndicatorExtension)ext;
- return (BigInteger)numExt.get(DeltaCRLIndicatorExtension.NUMBER);
+ DeltaCRLIndicatorExtension numExt = (DeltaCRLIndicatorExtension) ext;
+ return (BigInteger) numExt.get(DeltaCRLIndicatorExtension.NUMBER);
}
}
} catch (Exception e) {
@@ -924,7 +900,7 @@ public class X509CRLImpl extends X509CRL {
return false;
Enumeration<Extension> e = exts.getElements();
while (e.hasMoreElements()) {
- Extension ext = (Extension)e.nextElement();
+ Extension ext = (Extension) e.nextElement();
if (ext instanceof DeltaCRLIndicatorExtension) {
return true;
}
@@ -936,7 +912,7 @@ public class X509CRLImpl extends X509CRL {
/**
* Returns extensions for this impl.
- *
+ *
* @param extn CRLExtensions
*/
public CRLExtensions getExtensions() {
@@ -947,18 +923,17 @@ public class X509CRLImpl extends X509CRL {
return entriesIncluded;
}
-
/*********************************************************************/
/*
* Parses an X.509 CRL, should be used only by constructors.
*/
private void parse(DerValue val)
- throws CRLException, IOException, X509ExtensionException {
+ throws CRLException, IOException, X509ExtensionException {
parse(val, true);
}
private void parse(DerValue val, boolean includeEntries)
- throws CRLException, IOException, X509ExtensionException {
+ throws CRLException, IOException, X509ExtensionException {
// check if can over write the certificate
if (readOnly)
throw new CRLException("cannot over-write existing CRL");
@@ -991,22 +966,22 @@ public class X509CRLImpl extends X509CRL {
// parse the information
DerInputStream derStrm = seq[0].data;
- DerValue tmp;
- byte nextByte;
+ DerValue tmp;
+ byte nextByte;
// version (optional if v1)
- version = 0; // by default, version = v1 == 0
- nextByte = (byte)derStrm.peekByte();
+ version = 0; // by default, version = v1 == 0
+ nextByte = (byte) derStrm.peekByte();
if (nextByte == DerValue.tag_Integer) {
version = derStrm.getInteger().toInt();
- if (version != 1) // i.e. v2
+ if (version != 1) // i.e. v2
throw new CRLException("Invalid version");
}
tmp = derStrm.getDerValue();
// signature
{
AlgorithmId tmpId = AlgorithmId.parse(tmp);
- if (! tmpId.equals(sigAlgId))
+ if (!tmpId.equals(sigAlgId))
throw new CRLException("Signature algorithm mismatch");
infoSigAlgId = tmpId;
@@ -1017,7 +992,7 @@ public class X509CRLImpl extends X509CRL {
// thisUpdate
// check if UTCTime encoded or GeneralizedTime
- nextByte = (byte)derStrm.peekByte();
+ nextByte = (byte) derStrm.peekByte();
if (nextByte == DerValue.tag_UtcTime) {
thisUpdate = derStrm.getUTCTime();
} else if (nextByte == DerValue.tag_GeneralizedTime) {
@@ -1028,10 +1003,10 @@ public class X509CRLImpl extends X509CRL {
}
if (derStrm.available() == 0)
- return; // done parsing no more optional fields present
+ return; // done parsing no more optional fields present
// nextUpdate (optional)
- nextByte = (byte)derStrm.peekByte();
+ nextByte = (byte) derStrm.peekByte();
if (nextByte == DerValue.tag_UtcTime) {
nextUpdate = derStrm.getUTCTime();
} else if (nextByte == DerValue.tag_GeneralizedTime) {
@@ -1039,22 +1014,22 @@ public class X509CRLImpl extends X509CRL {
} // else it is not present
if (derStrm.available() == 0)
- return; // done parsing no more optional fields present
+ return; // done parsing no more optional fields present
// revokedCertificates (optional)
- nextByte = (byte)derStrm.peekByte();
+ nextByte = (byte) derStrm.peekByte();
if ((nextByte == DerValue.tag_SequenceOf)
- && (! ((nextByte & 0x0c0) == 0x080))) {
+ && (!((nextByte & 0x0c0) == 0x080))) {
if (includeEntries) {
DerValue[] badCerts = derStrm.getSequence(4);
for (int i = 0; i < badCerts.length; i++) {
RevokedCertImpl entry = new RevokedCertImpl(badCerts[i]);
if (entry.hasExtensions() && (version == 0))
throw new CRLException("Invalid encoding, extensions" +
- " not supported in CRL v1 entries.");
+ " not supported in CRL v1 entries.");
revokedCerts.put(entry.getSerialNumber(),
- (RevokedCertificate)entry);
+ (RevokedCertificate) entry);
}
} else {
derStrm.skipSequence(4);
@@ -1062,11 +1037,11 @@ public class X509CRLImpl extends X509CRL {
}
if (derStrm.available() == 0)
- return; // done parsing no extensions
+ return; // done parsing no extensions
// crlExtensions (optional)
tmp = derStrm.getDerValue();
- if (tmp.isConstructed() && tmp.isContextSpecific((byte)0)) {
+ if (tmp.isConstructed() && tmp.isContextSpecific((byte) 0)) {
if (version == 0)
throw new CRLException("Invalid encoding, extensions not" +
" supported in CRL v1.");
diff --git a/pki/base/util/src/netscape/security/x509/X509Cert.java b/pki/base/util/src/netscape/security/x509/X509Cert.java
index 873d25ab..d3c91820 100644
--- a/pki/base/util/src/netscape/security/x509/X509Cert.java
+++ b/pki/base/util/src/netscape/security/x509/X509Cert.java
@@ -41,14 +41,12 @@ import netscape.security.util.DerValue;
/**
* @author David Brownell
* @version 1.5
- *
+ *
* @see CertAndKeyGen
- * @deprecated Use the new X509Certificate class.
- * This class is only restored for backwards compatibility.
+ * @deprecated Use the new X509Certificate class. This class is only restored
+ * for backwards compatibility.
*/
-public
-class X509Cert implements Certificate, Serializable
-{
+public class X509Cert implements Certificate, Serializable {
/**
*
@@ -62,224 +60,210 @@ class X509Cert implements Certificate, Serializable
* decode</a> must later be called (or which may be deserialized).
*/
// XXX deprecated, delete this
- public X509Cert () { }
-
+ public X509Cert() {
+ }
/**
- * Unmarshals a certificate from its encoded form, parsing the
- * encoded bytes. This form of constructor is used by agents which
- * need to examine and use certificate contents. That is, this is
- * one of the more commonly used constructors. Note that the buffer
- * must include only a certificate, and no "garbage" may be left at
- * the end. If you need to ignore data at the end of a certificate,
- * use another constructor.
- *
+ * Unmarshals a certificate from its encoded form, parsing the encoded
+ * bytes. This form of constructor is used by agents which need to examine
+ * and use certificate contents. That is, this is one of the more commonly
+ * used constructors. Note that the buffer must include only a certificate,
+ * and no "garbage" may be left at the end. If you need to ignore data at
+ * the end of a certificate, use another constructor.
+ *
* @param cert the encoded bytes, with no terminatu (CONSUMED)
* @exception IOException when the certificate is improperly encoded.
*/
- public X509Cert (
- byte cert []
- ) throws IOException
- {
- DerValue in = new DerValue (cert);
+ public X509Cert(
+ byte cert[]) throws IOException {
+ DerValue in = new DerValue(cert);
- parse (in);
- if (in.data.available () != 0)
- throw new CertParseError ("garbage at end");
- signedCert = cert;
+ parse(in);
+ if (in.data.available() != 0)
+ throw new CertParseError("garbage at end");
+ signedCert = cert;
}
-
/**
- * Unmarshals a certificate from its encoded form, parsing the
- * encoded bytes. This form of constructor is used by agents which
- * need to examine and use certificate contents. That is, this is
- * one of the most commonly used constructors.
- *
+ * Unmarshals a certificate from its encoded form, parsing the encoded
+ * bytes. This form of constructor is used by agents which need to examine
+ * and use certificate contents. That is, this is one of the most commonly
+ * used constructors.
+ *
* @param buf the buffer holding the encoded bytes
* @param offset the offset in the buffer where the bytes begin
* @param len how many bytes of certificate exist
- *
+ *
* @exception IOException when the certificate is improperly encoded.
*/
- public X509Cert (
- byte buf [],
- int offset,
- int len
- ) throws IOException
- {
- DerValue in = new DerValue (buf, offset, len);
-
- parse (in);
- if (in.data.available () != 0)
- throw new CertParseError ("garbage at end");
- signedCert = new byte [len];
- System.arraycopy (buf, offset, signedCert, 0, len);
+ public X509Cert(
+ byte buf[],
+ int offset,
+ int len) throws IOException {
+ DerValue in = new DerValue(buf, offset, len);
+
+ parse(in);
+ if (in.data.available() != 0)
+ throw new CertParseError("garbage at end");
+ signedCert = new byte[len];
+ System.arraycopy(buf, offset, signedCert, 0, len);
}
-
/**
- * Unmarshal a certificate from its encoded form, parsing a DER value.
- * This form of constructor is used by agents which need to examine
- * and use certificate contents.
- *
+ * Unmarshal a certificate from its encoded form, parsing a DER value. This
+ * form of constructor is used by agents which need to examine and use
+ * certificate contents.
+ *
* @param derVal the der value containing the encoded cert.
* @exception IOException when the certificate is improperly encoded.
*/
- public X509Cert (DerValue derVal) throws IOException
- {
- parse (derVal);
- if (derVal.data.available () != 0)
- throw new CertParseError ("garbage at end");
- signedCert = derVal.toByteArray ();
+ public X509Cert(DerValue derVal) throws IOException {
+ parse(derVal);
+ if (derVal.data.available() != 0)
+ throw new CertParseError("garbage at end");
+ signedCert = derVal.toByteArray();
}
-
/**
- * Partially constructs a certificate from descriptive parameters.
- * This constructor may be used by Certificate Authority (CA) code,
- * which later <a href="#signAndEncode">signs and encodes</a> the
- * certificate. Also, self-signed certificates serve as CA certificates,
- * and are sometimes used as certificate requests.
- *
- * <P>Until the certificate has been signed and encoded, some of
- * the mandatory fields in the certificate will not be available
- * via accessor functions: the serial number, issuer name and signing
- * algorithm, and of course the signed certificate. The fields passed
- * to this constructor are available, and must be non-null.
- *
- * <P>Note that the public key being signed is generally independent of
- * the signature algorithm being used. So for example Diffie-Hellman
- * keys (which do not support signatures) can be placed in X.509
- * certificates when some other signature algorithm (e.g. DSS/DSA,
- * or one of the RSA based algorithms) is used.
- *
+ * Partially constructs a certificate from descriptive parameters. This
+ * constructor may be used by Certificate Authority (CA) code, which later
+ * <a href="#signAndEncode">signs and encodes</a> the certificate. Also,
+ * self-signed certificates serve as CA certificates, and are sometimes used
+ * as certificate requests.
+ *
+ * <P>
+ * Until the certificate has been signed and encoded, some of the mandatory
+ * fields in the certificate will not be available via accessor functions:
+ * the serial number, issuer name and signing algorithm, and of course the
+ * signed certificate. The fields passed to this constructor are available,
+ * and must be non-null.
+ *
+ * <P>
+ * Note that the public key being signed is generally independent of the
+ * signature algorithm being used. So for example Diffie-Hellman keys (which
+ * do not support signatures) can be placed in X.509 certificates when some
+ * other signature algorithm (e.g. DSS/DSA, or one of the RSA based
+ * algorithms) is used.
+ *
* @see CertAndKeyGen
- *
+ *
* @param subjectName the X.500 distinguished name being certified
- * @param subjectPublicKey the public key being certified. This
- * must be an "X509Key" implementing the "PublicKey" interface.
+ * @param subjectPublicKey the public key being certified. This must be an
+ * "X509Key" implementing the "PublicKey" interface.
* @param notBefore the first time the certificate is valid
* @param notAfter the last time the certificate is valid
- *
+ *
* @exception CertException if the public key is inappropriate
*/
- public X509Cert (
- X500Name subjectName,
- X509Key subjectPublicKey,
- Date notBefore,
- Date notAfter
- ) throws CertException
- {
- subject = subjectName;
-
- if (!(subjectPublicKey instanceof PublicKey))
- throw new CertException (CertException.err_INVALID_PUBLIC_KEY,
- "Doesn't implement PublicKey interface");
+ public X509Cert(
+ X500Name subjectName,
+ X509Key subjectPublicKey,
+ Date notBefore,
+ Date notAfter) throws CertException {
+ subject = subjectName;
- /*
- * The X509 cert API requires X509 keys, else things break.
- */
- pubkey = subjectPublicKey;
- notbefore = notBefore;
- notafter = notAfter;
- version = 0;
- }
+ if (!(subjectPublicKey instanceof PublicKey))
+ throw new CertException(CertException.err_INVALID_PUBLIC_KEY,
+ "Doesn't implement PublicKey interface");
+ /*
+ * The X509 cert API requires X509 keys, else things break.
+ */
+ pubkey = subjectPublicKey;
+ notbefore = notBefore;
+ notafter = notAfter;
+ version = 0;
+ }
/**
* Decode an X.509 certificate from an input stream.
- *
+ *
* @param in an input stream holding at least one certificate
* @exception IOException when the certificate is improperly encoded.
*/
- public void decode (InputStream in) throws IOException
- {
- DerValue val = new DerValue (in);
+ public void decode(InputStream in) throws IOException {
+ DerValue val = new DerValue(in);
- parse (val);
- if (val.data.available () != 0)
- throw new CertParseError ("garbage at end");
- signedCert = val.toByteArray ();
+ parse(val);
+ if (val.data.available() != 0)
+ throw new CertParseError("garbage at end");
+ signedCert = val.toByteArray();
}
-
/**
* Appends the certificate to an output stream.
- *
+ *
* @param out an input stream to which the certificate is appended.
* @exception IOException when appending fails.
*/
- public void encode (OutputStream out) throws IOException
- { out.write (getSignedCert ()); }
-
+ public void encode(OutputStream out) throws IOException {
+ out.write(getSignedCert());
+ }
/**
- * Compares two certificates. This is false if the
- * certificates are not both X.509 certs, otherwise it
- * compares them as binary data.
- *
+ * Compares two certificates. This is false if the certificates are not both
+ * X.509 certs, otherwise it compares them as binary data.
+ *
* @param other the object being compared with this one
* @return true iff the certificates are equivalent
*/
- public boolean equals (Object other)
- {
- if (other instanceof X509Cert)
- return equals ((X509Cert) other);
- else
- return false;
+ public boolean equals(Object other) {
+ if (other instanceof X509Cert)
+ return equals((X509Cert) other);
+ else
+ return false;
}
-
/**
- * Compares two certificates, returning false if any data
- * differs between the two.
- *
+ * Compares two certificates, returning false if any data differs between
+ * the two.
+ *
* @param other the object being compared with this one
* @return true iff the certificates are equivalent
*/
- public boolean equals (X509Cert src)
- {
- if (this == src)
- return true;
- if (signedCert == null || src.signedCert == null)
- return false;
- if (signedCert.length != src.signedCert.length)
- return false;
- for (int i = 0; i < signedCert.length; i++)
- if (signedCert [i] != src.signedCert [i])
- return false;
- return true;
+ public boolean equals(X509Cert src) {
+ if (this == src)
+ return true;
+ if (signedCert == null || src.signedCert == null)
+ return false;
+ if (signedCert.length != src.signedCert.length)
+ return false;
+ for (int i = 0; i < signedCert.length; i++)
+ if (signedCert[i] != src.signedCert[i])
+ return false;
+ return true;
}
-
/** Returns the "X.509" format identifier. */
- public String getFormat () // for Certificate
- { return "X.509"; }
-
+ public String getFormat() // for Certificate
+ {
+ return "X.509";
+ }
/** Returns <a href="#getIssuerName">getIssuerName</a> */
- public Principal getGuarantor () // for Certificate
- { return getIssuerName (); }
-
+ public Principal getGuarantor() // for Certificate
+ {
+ return getIssuerName();
+ }
/** Returns <a href="#getSubjectName">getSubjectName</a> */
- public Principal getPrincipal ()
- { return getSubjectName (); }
-
+ public Principal getPrincipal() {
+ return getSubjectName();
+ }
/**
- * Throws an exception if the certificate is invalid because it is
- * now outside of the certificate's validity period, or because it
- * was not signed using the verification key provided. Successfully
- * verifying a certificate does <em>not</em> indicate that one should
- * trust the entity which it represents.
- *
- * <P><em>Note that since this class represents only a single X.509
+ * Throws an exception if the certificate is invalid because it is now
+ * outside of the certificate's validity period, or because it was not
+ * signed using the verification key provided. Successfully verifying a
+ * certificate does <em>not</em> indicate that one should trust the entity
+ * which it represents.
+ *
+ * <P>
+ * <em>Note that since this class represents only a single X.509
* certificate, it cannot know anything about the certificate chain
* which is used to provide the verification key and to establish trust.
* Other code must manage and use those cert chains.
- *
+ *
* <P>For now, you must walk the cert chain being used to verify any
* given cert. Start at the root, which is a self-signed certificate;
* verify it using the key inside the certificate. Then use that to
@@ -289,351 +273,338 @@ class X509Cert implements Certificate, Serializable
* if any of the verification operations for its certificate chain
* were unsuccessful.
* </em>
- *
+ *
* @param issuerPublicKey the public key of the issuing CA
* @exception CertException when the certificate is not valid.
*/
- public void verify (PublicKey issuerPublicKey)
- throws CertException
- {
- Date now = new Date ();
-
- if (now.before (notbefore))
- throw new CertException (CertException.verf_INVALID_NOTBEFORE);
- if (now.after (notafter))
- throw new CertException (CertException.verf_INVALID_EXPIRED);
- if (signedCert == null)
- throw new CertException (CertException.verf_INVALID_SIG,
- "?? certificate is not signed yet ??");
-
- //
- // Verify the signature ...
- //
- String algName = null;
-
- try {
- Signature sigVerf = null;
-
- algName = issuerSigAlg.getName();
- sigVerf = Signature.getInstance(algName);
- sigVerf.initVerify (issuerPublicKey);
- sigVerf.update (rawCert, 0, rawCert.length);
-
- if (!sigVerf.verify (signature)) {
- throw new CertException (CertException.verf_INVALID_SIG,
- "Signature ... by <" + issuer + "> for <" + subject + ">");
- }
-
- // Gag -- too many catch clauses, let most through.
-
- } catch (NoSuchAlgorithmException e) {
- throw new CertException (CertException.verf_INVALID_SIG,
- "Unsupported signature algorithm (" + algName + ")");
-
- } catch (InvalidKeyException e) {
- // e.printStackTrace();
- throw new CertException (CertException.err_INVALID_PUBLIC_KEY,
- "Algorithm (" + algName + ") rejected public key");
-
- } catch (SignatureException e) {
- throw new CertException (CertException.verf_INVALID_SIG,
- "Signature by <" + issuer + "> for <" + subject + ">");
- }
+ public void verify(PublicKey issuerPublicKey)
+ throws CertException {
+ Date now = new Date();
+
+ if (now.before(notbefore))
+ throw new CertException(CertException.verf_INVALID_NOTBEFORE);
+ if (now.after(notafter))
+ throw new CertException(CertException.verf_INVALID_EXPIRED);
+ if (signedCert == null)
+ throw new CertException(CertException.verf_INVALID_SIG,
+ "?? certificate is not signed yet ??");
+
+ //
+ // Verify the signature ...
+ //
+ String algName = null;
+
+ try {
+ Signature sigVerf = null;
+
+ algName = issuerSigAlg.getName();
+ sigVerf = Signature.getInstance(algName);
+ sigVerf.initVerify(issuerPublicKey);
+ sigVerf.update(rawCert, 0, rawCert.length);
+
+ if (!sigVerf.verify(signature)) {
+ throw new CertException(CertException.verf_INVALID_SIG,
+ "Signature ... by <" + issuer + "> for <" + subject + ">");
+ }
+
+ // Gag -- too many catch clauses, let most through.
+
+ } catch (NoSuchAlgorithmException e) {
+ throw new CertException(CertException.verf_INVALID_SIG,
+ "Unsupported signature algorithm (" + algName + ")");
+
+ } catch (InvalidKeyException e) {
+ // e.printStackTrace();
+ throw new CertException(CertException.err_INVALID_PUBLIC_KEY,
+ "Algorithm (" + algName + ") rejected public key");
+
+ } catch (SignatureException e) {
+ throw new CertException(CertException.verf_INVALID_SIG,
+ "Signature by <" + issuer + "> for <" + subject + ">");
+ }
}
-
/**
- * Creates an X.509 certificate, and signs it using the issuer
- * passed (associating a signature algorithm and an X.500 name).
- * This operation is used to implement the certificate generation
- * functionality of a certificate authority.
- *
+ * Creates an X.509 certificate, and signs it using the issuer passed
+ * (associating a signature algorithm and an X.500 name). This operation is
+ * used to implement the certificate generation functionality of a
+ * certificate authority.
+ *
* @see #getSignedCert
* @see #getSigner
* @see CertAndKeyGen
- *
+ *
* @param serial the serial number of the certificate (non-null)
* @param issuer the certificate issuer (CA) (non-null)
* @return the signed certificate, as returned by getSignedCert
- *
- * @exception IOException if any of the data could not be encoded,
- * or when any mandatory data was omitted
+ *
+ * @exception IOException if any of the data could not be encoded, or when
+ * any mandatory data was omitted
* @exception SignatureException on signing failures
*/
- public byte []
- encodeAndSign (
- BigInt serial,
- X500Signer issuer
- ) throws IOException, SignatureException
- {
- rawCert = null;
+ public byte[]
+ encodeAndSign(
+ BigInt serial,
+ X500Signer issuer
+ ) throws IOException, SignatureException {
+ rawCert = null;
- /*
- * Get the remaining cert parameters, and make sure we have enough.
- *
- * We deduce version based on what attribute data are available
- * For now, we have no attributes, so we always deduce X.509v1 !
- */
- version = 0;
- serialnum = serial;
- this.issuer = issuer.getSigner ();
- issuerSigAlg = issuer.getAlgorithmId ();
-
- if (subject == null || pubkey == null
- || notbefore == null || notafter == null)
- throw new IOException ("not enough cert parameters");
+ /*
+ * Get the remaining cert parameters, and make sure we have enough.
+ *
+ * We deduce version based on what attribute data are available For now,
+ * we have no attributes, so we always deduce X.509v1 !
+ */
+ version = 0;
+ serialnum = serial;
+ this.issuer = issuer.getSigner();
+ issuerSigAlg = issuer.getAlgorithmId();
+
+ if (subject == null || pubkey == null
+ || notbefore == null || notafter == null)
+ throw new IOException("not enough cert parameters");
- /*
- * Encode the raw cert, create its signature and put it
- * into the envelope.
- */
- rawCert = DERencode ();
- signedCert = sign (issuer, rawCert);
- return signedCert;
+ /*
+ * Encode the raw cert, create its signature and put it into the
+ * envelope.
+ */
+ rawCert = DERencode();
+ signedCert = sign(issuer, rawCert);
+ return signedCert;
}
-
/**
- * Returns an X500Signer that may be used to create signatures. Those
- * signature may in turn be verified using this certificate (or a
- * copy of it).
- *
- * <P><em><b>NOTE:</b> If the private key is by itself capable of
+ * Returns an X500Signer that may be used to create signatures. Those
+ * signature may in turn be verified using this certificate (or a copy of
+ * it).
+ *
+ * <P>
+ * <em><b>NOTE:</b> If the private key is by itself capable of
* creating signatures, this fact may not be recognized at this time.
* Specifically, the case of DSS/DSA keys which get their algorithm
* parameters from higher in the certificate chain is not supportable
* without using an X509CertChain API, and there is no current support
* for other sources of algorithm parameters.</em>
- *
- * @param algorithm the signature algorithm to be used. Note that a
- * given public/private key pair may support several such algorithms.
- * @param privateKey the private key used to create the signature,
- * which must correspond to the public key in this certificate
+ *
+ * @param algorithm the signature algorithm to be used. Note that a given
+ * public/private key pair may support several such algorithms.
+ * @param privateKey the private key used to create the signature, which
+ * must correspond to the public key in this certificate
* @return the Signer object
- *
- * @exception NoSuchAlgorithmException if the signature
- * algorithm is not supported
- * @exception InvalidKeyException if either the key in the certificate,
- * or the private key parameter, does not support the requested
- * signature algorithm
- */
- public X500Signer getSigner (AlgorithmId algorithmId,
- PrivateKey privateKey)
- throws NoSuchAlgorithmException, InvalidKeyException
- {
- String algorithm;
- Signature sig;
-
- if (privateKey instanceof Key) {
- Key key = (Key)privateKey;
- algorithm = key.getAlgorithm();
- } else {
- throw new InvalidKeyException("private key not a key!");
- }
-
- sig = Signature.getInstance(algorithmId.getName());
-
- if (!pubkey.getAlgorithm ().equals (algorithm)) {
-
- throw new InvalidKeyException( "Private key algorithm " +
- algorithm +
- " incompatible with certificate " +
- pubkey.getAlgorithm());
- }
- sig.initSign (privateKey);
- return new X500Signer (sig, subject);
+ *
+ * @exception NoSuchAlgorithmException if the signature algorithm is not
+ * supported
+ * @exception InvalidKeyException if either the key in the certificate, or
+ * the private key parameter, does not support the requested
+ * signature algorithm
+ */
+ public X500Signer getSigner(AlgorithmId algorithmId,
+ PrivateKey privateKey)
+ throws NoSuchAlgorithmException, InvalidKeyException {
+ String algorithm;
+ Signature sig;
+
+ if (privateKey instanceof Key) {
+ Key key = (Key) privateKey;
+ algorithm = key.getAlgorithm();
+ } else {
+ throw new InvalidKeyException("private key not a key!");
+ }
+
+ sig = Signature.getInstance(algorithmId.getName());
+
+ if (!pubkey.getAlgorithm().equals(algorithm)) {
+
+ throw new InvalidKeyException("Private key algorithm " +
+ algorithm +
+ " incompatible with certificate " +
+ pubkey.getAlgorithm());
+ }
+ sig.initSign(privateKey);
+ return new X500Signer(sig, subject);
}
-
/**
- * Returns a signature object that may be used to verify signatures
- * created using a specified signature algorithm and the public key
- * contained in this certificate.
- *
- * <P><em><b>NOTE:</b> If the public key in this certificate is not by
+ * Returns a signature object that may be used to verify signatures created
+ * using a specified signature algorithm and the public key contained in
+ * this certificate.
+ *
+ * <P>
+ * <em><b>NOTE:</b> If the public key in this certificate is not by
* itself capable of verifying signatures, this may not be recognized
* at this time. Specifically, the case of DSS/DSA keys which get
* their algorithm parameters from higher in the certificate chain
* is not supportable without using an X509CertChain API, and there
* is no current support for other sources of algorithm parameters.</em>
- *
+ *
* @param algorithm the algorithm of the signature to be verified
* @return the Signature object
- * @exception NoSuchAlgorithmException if the signature
- * algorithm is not supported
- * @exception InvalidKeyException if the key in the certificate
- * does not support the requested signature algorithm
+ * @exception NoSuchAlgorithmException if the signature algorithm is not
+ * supported
+ * @exception InvalidKeyException if the key in the certificate does not
+ * support the requested signature algorithm
*/
public Signature getVerifier(String algorithm)
- throws NoSuchAlgorithmException, InvalidKeyException
- {
- String algName;
- Signature sig;
+ throws NoSuchAlgorithmException, InvalidKeyException {
+ String algName;
+ Signature sig;
- sig = Signature.getInstance(algorithm);
- sig.initVerify (pubkey);
- return sig;
+ sig = Signature.getInstance(algorithm);
+ sig.initVerify(pubkey);
+ return sig;
}
-
-
/**
- * Return the signed X.509 certificate as a byte array.
- * The bytes are in standard DER marshaled form.
- * Null is returned in the case of a partially constructed cert.
+ * Return the signed X.509 certificate as a byte array. The bytes are in
+ * standard DER marshaled form. Null is returned in the case of a partially
+ * constructed cert.
*/
- public byte [] getSignedCert ()
- { return signedCert; }
-
+ public byte[] getSignedCert() {
+ return signedCert;
+ }
/**
- * Returns the certificate's serial number.
- * Null is returned in the case of a partially constructed cert.
+ * Returns the certificate's serial number. Null is returned in the case of
+ * a partially constructed cert.
*/
- public BigInt getSerialNumber ()
- { return serialnum; }
-
+ public BigInt getSerialNumber() {
+ return serialnum;
+ }
/**
* Returns the subject's X.500 distinguished name.
*/
- public X500Name getSubjectName ()
- { return subject; }
-
+ public X500Name getSubjectName() {
+ return subject;
+ }
/**
- * Returns the certificate issuer's X.500 distinguished name.
- * Null is returned in the case of a partially constructed cert.
+ * Returns the certificate issuer's X.500 distinguished name. Null is
+ * returned in the case of a partially constructed cert.
*/
- public X500Name getIssuerName ()
- { return issuer; }
-
+ public X500Name getIssuerName() {
+ return issuer;
+ }
/**
- * Returns the algorithm used by the issuer to sign the certificate.
- * Null is returned in the case of a partially constructed cert.
+ * Returns the algorithm used by the issuer to sign the certificate. Null is
+ * returned in the case of a partially constructed cert.
*/
- public AlgorithmId getIssuerAlgorithmId ()
- { return issuerSigAlg; }
-
+ public AlgorithmId getIssuerAlgorithmId() {
+ return issuerSigAlg;
+ }
/**
* Returns the first time the certificate is valid.
*/
- public Date getNotBefore ()
- { return notbefore; }
-
+ public Date getNotBefore() {
+ return notbefore;
+ }
/**
* Returns the last time the certificate is valid.
*/
- public Date getNotAfter ()
- { return notafter; }
-
+ public Date getNotAfter() {
+ return notafter;
+ }
/**
- * Returns the subject's public key. Note that some public key
- * algorithms support an optional certificate generation policy
- * where the keys in the certificates are not in themselves sufficient
- * to perform a public key operation. Those keys need to be augmented
- * by algorithm parameters, which the certificate generation policy
- * chose not to place in the certificate.
- *
- * <P>Two such public key algorithms are: DSS/DSA, where algorithm
- * parameters could be acquired from a CA certificate in the chain
- * of issuers; and Diffie-Hellman, with a similar solution although
- * the CA then needs both a Diffie-Hellman certificate and a signature
- * capable certificate.
- */
- public PublicKey getPublicKey ()
- { return pubkey; }
-
+ * Returns the subject's public key. Note that some public key algorithms
+ * support an optional certificate generation policy where the keys in the
+ * certificates are not in themselves sufficient to perform a public key
+ * operation. Those keys need to be augmented by algorithm parameters, which
+ * the certificate generation policy chose not to place in the certificate.
+ *
+ * <P>
+ * Two such public key algorithms are: DSS/DSA, where algorithm parameters
+ * could be acquired from a CA certificate in the chain of issuers; and
+ * Diffie-Hellman, with a similar solution although the CA then needs both a
+ * Diffie-Hellman certificate and a signature capable certificate.
+ */
+ public PublicKey getPublicKey() {
+ return pubkey;
+ }
/**
- * Returns the X.509 version number of this certificate, zero based.
- * That is, "2" indicates an X.509 version 3 (1993) certificate,
- * and "0" indicates X.509v1 (1988).
- * Zero is returned in the case of a partially constructed cert.
+ * Returns the X.509 version number of this certificate, zero based. That
+ * is, "2" indicates an X.509 version 3 (1993) certificate, and "0"
+ * indicates X.509v1 (1988). Zero is returned in the case of a partially
+ * constructed cert.
*/
- public int getVersion ()
- { return version; }
+ public int getVersion() {
+ return version;
+ }
-
/**
- * Calculates a hash code value for the object. Objects
- * which are equal will also have the same hashcode.
+ * Calculates a hash code value for the object. Objects which are equal will
+ * also have the same hashcode.
*/
- public int hashCode ()
- {
- int retval = 0;
+ public int hashCode() {
+ int retval = 0;
- for (int i = 0; i < signedCert.length; i++)
- retval += signedCert [i] * i;
- return retval;
+ for (int i = 0; i < signedCert.length; i++)
+ retval += signedCert[i] * i;
+ return retval;
}
-
/**
- * Returns a printable representation of the certificate. This does not
- * contain all the information available to distinguish this from any
- * other certificate. The certificate must be fully constructed
- * before this function may be called; in particular, if you are
- * creating certificates you must call encodeAndSign() before calling
- * this function.
- */
- public String toString ()
- {
- String s;
+ * Returns a printable representation of the certificate. This does not
+ * contain all the information available to distinguish this from any other
+ * certificate. The certificate must be fully constructed before this
+ * function may be called; in particular, if you are creating certificates
+ * you must call encodeAndSign() before calling this function.
+ */
+ public String toString() {
+ String s;
- if (subject == null || pubkey == null
- || notbefore == null || notafter == null
- || issuer == null || issuerSigAlg == null
- || serialnum == null)
- throw new NullPointerException ("X.509 cert is incomplete");
+ if (subject == null || pubkey == null
+ || notbefore == null || notafter == null
+ || issuer == null || issuerSigAlg == null
+ || serialnum == null)
+ throw new NullPointerException("X.509 cert is incomplete");
s = " X.509v" + (version + 1) + " certificate,\n";
s += " Subject is " + subject + "\n";
s += " Key: " + pubkey;
s += " Validity <" + notbefore + "> until <" + notafter + ">\n";
s += " Issuer is " + issuer + "\n";
- s += " Issuer signature used " + issuerSigAlg.toString () + "\n";
- s += " Serial number = " + serialnum + "\n";
+ s += " Issuer signature used " + issuerSigAlg.toString() + "\n";
+ s += " Serial number = " + serialnum + "\n";
// optional v2, v3 extras
return "[\n" + s + "]";
}
-
/**
* Returns a printable representation of the certificate.
- *
+ *
* @param detailed true iff lots of detail is requested
*/
- public String toString (boolean detailed)
- { return toString (); }
-
+ public String toString(boolean detailed) {
+ return toString();
+ }
/*
* Certificate data, and its envelope
*/
- private byte rawCert [];
- private byte signature [];
- private byte signedCert [];
+ private byte rawCert[];
+ private byte signature[];
+ private byte signedCert[];
/*
* X509.v1 data (parsed)
*/
- private X500Name subject; // from subject
- private X509Key pubkey;
+ private X500Name subject; // from subject
+ private X509Key pubkey;
- private Date notafter; // from CA (constructor)
- private Date notbefore;
+ private Date notafter; // from CA (constructor)
+ private Date notbefore;
- private int version; // from CA (signAndEncode)
- private BigInt serialnum;
- private X500Name issuer;
- private AlgorithmId issuerSigAlg;
+ private int version; // from CA (signAndEncode)
+ private BigInt serialnum;
+ private X500Name issuer;
+ private AlgorithmId issuerSigAlg;
/*
* X509.v2 extensions
@@ -647,244 +618,228 @@ class X509Cert implements Certificate, Serializable
* Other extensions ... Netscape, Verisign, SET, etc
*/
-
/************************************************************/
/*
* Cert is a SIGNED ASN.1 macro, a three elment sequence:
- *
- * - Data to be signed (ToBeSigned) -- the "raw" cert
- * - Signature algorithm (SigAlgId)
- * - The signature bits
- *
- * This routine unmarshals the certificate, saving the signature
- * parts away for later verification.
+ *
+ * - Data to be signed (ToBeSigned) -- the "raw" cert - Signature algorithm
+ * (SigAlgId) - The signature bits
+ *
+ * This routine unmarshals the certificate, saving the signature parts away
+ * for later verification.
*/
- private void parse (DerValue val)
- throws IOException
- {
- DerValue seq [] = new DerValue [3];
-
- seq [0] = val.data.getDerValue ();
- seq [1] = val.data.getDerValue ();
- seq [2] = val.data.getDerValue ();
-
- if (val.data.available () != 0)
- throw new CertParseError ("signed overrun, bytes = "
- + val.data.available ());
- if (seq [0].tag != DerValue.tag_Sequence)
- throw new CertParseError ("signed fields invalid");
-
- rawCert = seq [0].toByteArray (); // XXX slow; fixme!
-
-
- issuerSigAlg = AlgorithmId.parse (seq [1]);
- signature = seq [2].getBitString ();
-
- if (seq [1].data.available () != 0) {
- // XXX why was this error check commented out?
- // It was originally part of the next check.
- throw new CertParseError ("algid field overrun");
- }
-
- if (seq [2].data.available () != 0)
- throw new CertParseError ("signed fields overrun");
-
- /*
- * Let's have fun parsing the cert itself.
- */
- DerInputStream in;
- DerValue tmp;
-
- in = seq [0].data;
-
- /*
- * Version -- this is optional (default zero). If it's there it's
- * the first field and is specially tagged.
- *
- * Both branches leave "tmp" holding a value for the serial
- * number that comes next.
- */
- version = 0;
- tmp = in.getDerValue ();
- if (tmp.isConstructed () && tmp.isContextSpecific ()) {
- version = tmp.data.getInteger ().toInt ();
- if (tmp.data.available () != 0)
- throw new IOException ("X.509 version, bad format");
- tmp = in.getDerValue ();
- }
+ private void parse(DerValue val)
+ throws IOException {
+ DerValue seq[] = new DerValue[3];
+
+ seq[0] = val.data.getDerValue();
+ seq[1] = val.data.getDerValue();
+ seq[2] = val.data.getDerValue();
+
+ if (val.data.available() != 0)
+ throw new CertParseError("signed overrun, bytes = "
+ + val.data.available());
+ if (seq[0].tag != DerValue.tag_Sequence)
+ throw new CertParseError("signed fields invalid");
+
+ rawCert = seq[0].toByteArray(); // XXX slow; fixme!
+
+ issuerSigAlg = AlgorithmId.parse(seq[1]);
+ signature = seq[2].getBitString();
+
+ if (seq[1].data.available() != 0) {
+ // XXX why was this error check commented out?
+ // It was originally part of the next check.
+ throw new CertParseError("algid field overrun");
+ }
+
+ if (seq[2].data.available() != 0)
+ throw new CertParseError("signed fields overrun");
/*
- * serial number ... an integer
- */
- serialnum = tmp.getInteger ();
+ * Let's have fun parsing the cert itself.
+ */
+ DerInputStream in;
+ DerValue tmp;
+
+ in = seq[0].data;
+
+ /*
+ * Version -- this is optional (default zero). If it's there it's the
+ * first field and is specially tagged.
+ *
+ * Both branches leave "tmp" holding a value for the serial number that
+ * comes next.
+ */
+ version = 0;
+ tmp = in.getDerValue();
+ if (tmp.isConstructed() && tmp.isContextSpecific()) {
+ version = tmp.data.getInteger().toInt();
+ if (tmp.data.available() != 0)
+ throw new IOException("X.509 version, bad format");
+ tmp = in.getDerValue();
+ }
+
+ /*
+ * serial number ... an integer
+ */
+ serialnum = tmp.getInteger();
/*
- * algorithm type for CA's signature ... needs to match the
- * one on the envelope, and that's about it! different IDs
- * may represent a signature attack. In general we want to
- * inherit parameters.
- */
- tmp = in.getDerValue ();
- {
- AlgorithmId algid;
-
+ * algorithm type for CA's signature ... needs to match the one on the
+ * envelope, and that's about it! different IDs may represent a
+ * signature attack. In general we want to inherit parameters.
+ */
+ tmp = in.getDerValue();
+ {
+ AlgorithmId algid;
- algid = AlgorithmId.parse(tmp);
+ algid = AlgorithmId.parse(tmp);
- if (!algid.equals (issuerSigAlg))
- throw new CertParseError ("CA Algorithm mismatch!");
+ if (!algid.equals(issuerSigAlg))
+ throw new CertParseError("CA Algorithm mismatch!");
- this.algid = algid;
- }
+ this.algid = algid;
+ }
/*
- * issuer name
- */
- issuer = new X500Name (in);
+ * issuer name
+ */
+ issuer = new X500Name(in);
/*
- * validity: SEQUENCE { start date, end date }
- */
- tmp = in.getDerValue ();
- if (tmp.tag != DerValue.tag_Sequence)
- throw new CertParseError ("corrupt validity field");
+ * validity: SEQUENCE { start date, end date }
+ */
+ tmp = in.getDerValue();
+ if (tmp.tag != DerValue.tag_Sequence)
+ throw new CertParseError("corrupt validity field");
- notbefore = tmp.data.getUTCTime ();
- notafter = tmp.data.getUTCTime ();
- if (tmp.data.available () != 0)
- throw new CertParseError ("excess validity data");
+ notbefore = tmp.data.getUTCTime();
+ notafter = tmp.data.getUTCTime();
+ if (tmp.data.available() != 0)
+ throw new CertParseError("excess validity data");
/*
- * subject name and public key
- */
- subject = new X500Name (in);
+ * subject name and public key
+ */
+ subject = new X500Name(in);
- tmp = in.getDerValue ();
- pubkey = X509Key.parse (tmp);
+ tmp = in.getDerValue();
+ pubkey = X509Key.parse(tmp);
/*
- * XXX for v2 and later, a bunch of tagged options follow
- */
-
- if (in.available () != 0) {
- /*
- * Until we parse V2/V3 data ... ignore it.
- *
- // throw new CertParseError ("excess cert data");
- System.out.println (
- "@end'o'cert, optional V2/V3 data unparsed: "
- + in.available ()
- + " bytes"
- );
- */
- }
+ * XXX for v2 and later, a bunch of tagged options follow
+ */
+
+ if (in.available() != 0) {
+ /*
+ * Until we parse V2/V3 data ... ignore it.
+ *
+ * // throw new CertParseError ("excess cert data");
+ * System.out.println (
+ * "@end'o'cert, optional V2/V3 data unparsed: " + in.available ()
+ * + " bytes" );
+ */
+ }
}
-
/*
* Encode only the parts that will later be signed.
*/
- private byte [] DERencode () throws IOException
- {
- DerOutputStream raw = new DerOutputStream ();
-
- encode (raw);
- return raw.toByteArray ();
- }
+ private byte[] DERencode() throws IOException {
+ DerOutputStream raw = new DerOutputStream();
+ encode(raw);
+ return raw.toByteArray();
+ }
/*
* Marshal the contents of a "raw" certificate into a DER sequence.
*/
- private void encode (DerOutputStream out) throws IOException
- {
- DerOutputStream tmp = new DerOutputStream ();
+ private void encode(DerOutputStream out) throws IOException {
+ DerOutputStream tmp = new DerOutputStream();
- /*
- * encode serial number, issuer signing algorithm,
- * and issuer name into the data we'll return
- */
- tmp.putInteger (serialnum);
- issuerSigAlg.encode (tmp);
- issuer.encode (tmp);
+ /*
+ * encode serial number, issuer signing algorithm, and issuer name into
+ * the data we'll return
+ */
+ tmp.putInteger(serialnum);
+ issuerSigAlg.encode(tmp);
+ issuer.encode(tmp);
- /*
- * Validity is a two element sequence ... encode the
- * elements, then wrap them into the data we'll return
- */
- {
- DerOutputStream seq = new DerOutputStream ();
+ /*
+ * Validity is a two element sequence ... encode the elements, then wrap
+ * them into the data we'll return
+ */
+ {
+ DerOutputStream seq = new DerOutputStream();
- seq.putUTCTime (notbefore);
- seq.putUTCTime (notafter);
- tmp.write (DerValue.tag_Sequence, seq);
- }
+ seq.putUTCTime(notbefore);
+ seq.putUTCTime(notafter);
+ tmp.write(DerValue.tag_Sequence, seq);
+ }
- /*
- * Encode subject (principal) and associated key
- */
- subject.encode (tmp);
- pubkey.encode (tmp);
+ /*
+ * Encode subject (principal) and associated key
+ */
+ subject.encode(tmp);
+ pubkey.encode(tmp);
- /*
- * Wrap the data; encoding of the "raw" cert is now complete.
- */
- out.write (DerValue.tag_Sequence, tmp);
+ /*
+ * Wrap the data; encoding of the "raw" cert is now complete.
+ */
+ out.write(DerValue.tag_Sequence, tmp);
}
-
/*
- * Calculate the signature of the "raw" certificate,
- * and marshal the cert with the signature and a
- * description of the signing algorithm.
+ * Calculate the signature of the "raw" certificate, and marshal the cert
+ * with the signature and a description of the signing algorithm.
*/
- private byte [] sign (X500Signer issuer, byte data [])
- throws IOException, SignatureException
- {
- /*
- * Encode the to-be-signed data, then the algorithm used
- * to create the signature.
- */
- DerOutputStream out = new DerOutputStream ();
- DerOutputStream tmp = new DerOutputStream ();
-
- tmp.write (data);
- issuer.getAlgorithmId ().encode(tmp);
+ private byte[] sign(X500Signer issuer, byte data[])
+ throws IOException, SignatureException {
+ /*
+ * Encode the to-be-signed data, then the algorithm used to create the
+ * signature.
+ */
+ DerOutputStream out = new DerOutputStream();
+ DerOutputStream tmp = new DerOutputStream();
+ tmp.write(data);
+ issuer.getAlgorithmId().encode(tmp);
- /*
- * Create and encode the signature itself.
- */
- issuer.update (data, 0, data.length);
- signature = issuer.sign ();
- tmp.putBitString (signature);
+ /*
+ * Create and encode the signature itself.
+ */
+ issuer.update(data, 0, data.length);
+ signature = issuer.sign();
+ tmp.putBitString(signature);
- /*
- * Wrap the signed data in a SEQUENCE { data, algorithm, sig }
- */
- out.write (DerValue.tag_Sequence, tmp);
- return out.toByteArray ();
+ /*
+ * Wrap the signed data in a SEQUENCE { data, algorithm, sig }
+ */
+ out.write(DerValue.tag_Sequence, tmp);
+ return out.toByteArray();
}
-
/**
- * Serialization write ... X.509 certificates serialize as
- * themselves, and they're parsed when they get read back.
- * (Actually they serialize as some type data from the
- * serialization subsystem, then the cert data.)
+ * Serialization write ... X.509 certificates serialize as themselves, and
+ * they're parsed when they get read back. (Actually they serialize as some
+ * type data from the serialization subsystem, then the cert data.)
*/
private synchronized void
- writeObject (java.io.ObjectOutputStream stream)
- throws IOException
- { encode(stream); }
+ writeObject(java.io.ObjectOutputStream stream)
+ throws IOException {
+ encode(stream);
+ }
/**
- * Serialization read ... X.509 certificates serialize as
- * themselves, and they're parsed when they get read back.
+ * Serialization read ... X.509 certificates serialize as themselves, and
+ * they're parsed when they get read back.
*/
private synchronized void
- readObject (ObjectInputStream stream)
- throws IOException
- { decode(stream); }
+ readObject(ObjectInputStream stream)
+ throws IOException {
+ decode(stream);
+ }
}
diff --git a/pki/base/util/src/netscape/security/x509/X509CertImpl.java b/pki/base/util/src/netscape/security/x509/X509CertImpl.java
index 220f32d8..8f653892 100755
--- a/pki/base/util/src/netscape/security/x509/X509CertImpl.java
+++ b/pki/base/util/src/netscape/security/x509/X509CertImpl.java
@@ -53,30 +53,33 @@ import netscape.security.util.ObjectIdentifier;
/**
* The X509CertImpl class represents an X.509 certificate. These certificates
- * are widely used to support authentication and other functionality in
- * Internet security systems. Common applications include Privacy Enhanced
- * Mail (PEM), Transport Layer Security (SSL), code signing for trusted
- * software distribution, and Secure Electronic Transactions (SET). There
- * is a commercial infrastructure ready to manage large scale deployments
- * of X.509 identity certificates.
- *
- * <P>These certificates are managed and vouched for by <em>Certificate
- * Authorities</em> (CAs). CAs are services which create certificates by
- * placing data in the X.509 standard format and then digitally signing
- * that data. Such signatures are quite difficult to forge. CAs act as
- * trusted third parties, making introductions between agents who have no
- * direct knowledge of each other. CA certificates are either signed by
- * themselves, or by some other CA such as a "root" CA.
- *
- * <P>RFC 1422 is very informative, though it does not describe much
- * of the recent work being done with X.509 certificates. That includes
- * a 1996 version (X.509v3) and a variety of enhancements being made to
- * facilitate an explosion of personal certificates used as "Internet
- * Drivers' Licences", or with SET for credit card transactions.
- *
- * <P>More recent work includes the IETF PKIX Working Group efforts,
- * especially part 1.
- *
+ * are widely used to support authentication and other functionality in Internet
+ * security systems. Common applications include Privacy Enhanced Mail (PEM),
+ * Transport Layer Security (SSL), code signing for trusted software
+ * distribution, and Secure Electronic Transactions (SET). There is a commercial
+ * infrastructure ready to manage large scale deployments of X.509 identity
+ * certificates.
+ *
+ * <P>
+ * These certificates are managed and vouched for by <em>Certificate
+ * Authorities</em> (CAs). CAs are services which create certificates by placing
+ * data in the X.509 standard format and then digitally signing that data. Such
+ * signatures are quite difficult to forge. CAs act as trusted third parties,
+ * making introductions between agents who have no direct knowledge of each
+ * other. CA certificates are either signed by themselves, or by some other CA
+ * such as a "root" CA.
+ *
+ * <P>
+ * RFC 1422 is very informative, though it does not describe much of the recent
+ * work being done with X.509 certificates. That includes a 1996 version
+ * (X.509v3) and a variety of enhancements being made to facilitate an explosion
+ * of personal certificates used as "Internet Drivers' Licences", or with SET
+ * for credit card transactions.
+ *
+ * <P>
+ * More recent work includes the IETF PKIX Working Group efforts, especially
+ * part 1.
+ *
* @author Dave Brownell
* @author Amit Kapoor
* @author Hemma Prafullchandra
@@ -84,7 +87,7 @@ import netscape.security.util.ObjectIdentifier;
* @see X509CertInfo
*/
public class X509CertImpl extends X509Certificate
-implements Serializable, DerEncoder {
+ implements Serializable, DerEncoder {
// Serialization compatibility with the X509CertImpl in x509v1.jar
// supporting the subset of X509Certificate on JDK1.1.x platforms.
static final long serialVersionUID = -2048442350420423405L;
@@ -100,8 +103,8 @@ implements Serializable, DerEncoder {
public static final String SIGNED_CERT = "signed_cert";
/**
- * The following are defined for ease-of-use. These
- * are the most frequently retrieved attributes.
+ * The following are defined for ease-of-use. These are the most frequently
+ * retrieved attributes.
*/
// x509.info.subject.dname
public static final String SUBJECT_DN = NAME + DOT + INFO + DOT +
@@ -131,10 +134,10 @@ implements Serializable, DerEncoder {
private boolean readOnly = false;
// Certificate data, and its envelope
- private byte[] signedCert;
- protected X509CertInfo info = null;
- protected AlgorithmId algId;
- protected byte[] signature;
+ private byte[] signedCert;
+ protected X509CertInfo info = null;
+ protected AlgorithmId algId;
+ protected byte[] signature;
// recognized extension OIDS
private static final String KEY_USAGE_OID = "2.5.29.15";
@@ -143,115 +146,114 @@ implements Serializable, DerEncoder {
/**
* Default constructor.
*/
- public X509CertImpl() { }
+ public X509CertImpl() {
+ }
/**
- * Unmarshals a certificate from its encoded form, parsing the
- * encoded bytes. This form of constructor is used by agents which
- * need to examine and use certificate contents. That is, this is
- * one of the more commonly used constructors. Note that the buffer
- * must include only a certificate, and no "garbage" may be left at
- * the end. If you need to ignore data at the end of a certificate,
- * use another constructor.
- *
+ * Unmarshals a certificate from its encoded form, parsing the encoded
+ * bytes. This form of constructor is used by agents which need to examine
+ * and use certificate contents. That is, this is one of the more commonly
+ * used constructors. Note that the buffer must include only a certificate,
+ * and no "garbage" may be left at the end. If you need to ignore data at
+ * the end of a certificate, use another constructor.
+ *
* @param certData the encoded bytes, with no trailing padding.
* @exception CertificateException on parsing and initialization errors.
*/
public X509CertImpl(byte[] certData)
- throws CertificateException {
- this(certData,null);
+ throws CertificateException {
+ this(certData, null);
}
- /**
- * As a special optimization, this constructor acts as X509CertImpl(byte[])
- * except that it takes an X509CertInfo which it uses as a 'hint' for
- * how to construct one field.
- *
- * @param certData the encode bytes, with no traiing padding
- * @param certInfo the certInfo which has already been constructed
- * from the certData
- */
+ /**
+ * As a special optimization, this constructor acts as X509CertImpl(byte[])
+ * except that it takes an X509CertInfo which it uses as a 'hint' for how to
+ * construct one field.
+ *
+ * @param certData the encode bytes, with no traiing padding
+ * @param certInfo the certInfo which has already been constructed from the
+ * certData
+ */
public X509CertImpl(byte[] certData, X509CertInfo certInfo)
- throws CertificateException {
+ throws CertificateException {
- // setting info here causes it to skip decoding in the parse()
- // method
- info = certInfo;
+ // setting info here causes it to skip decoding in the parse()
+ // method
+ info = certInfo;
try {
- DerValue in = new DerValue(certData);
+ DerValue in = new DerValue(certData);
parse(in);
signedCert = certData;
} catch (IOException e) {
- throw new CertificateException("Unable to initialize, " + e);
+ throw new CertificateException("Unable to initialize, " + e);
}
- }
+ }
/**
* unmarshals an X.509 certificate from an input stream.
- *
+ *
* @param in an input stream holding at least one certificate
* @exception CertificateException on parsing and initialization errors.
*/
public X509CertImpl(InputStream in)
- throws CertificateException {
+ throws CertificateException {
try {
- DerValue val = new DerValue(in);
+ DerValue val = new DerValue(in);
parse(val);
signedCert = val.toByteArray();
} catch (IOException e) {
- throw new CertificateException("Unable to initialize, " + e);
+ throw new CertificateException("Unable to initialize, " + e);
}
}
/**
- * Construct an initialized X509 Certificate. The certificate is stored
- * in raw form and has to be signed to be useful.
- *
+ * Construct an initialized X509 Certificate. The certificate is stored in
+ * raw form and has to be signed to be useful.
+ *
* @param certInfo the X509CertificateInfo which the Certificate is to be
- * created from.
+ * created from.
*/
public X509CertImpl(X509CertInfo certInfo) {
this.info = certInfo;
}
/**
- * Unmarshal a certificate from its encoded form, parsing a DER value.
- * This form of constructor is used by agents which need to examine
- * and use certificate contents.
- *
+ * Unmarshal a certificate from its encoded form, parsing a DER value. This
+ * form of constructor is used by agents which need to examine and use
+ * certificate contents.
+ *
* @param derVal the der value containing the encoded cert.
* @exception CertificateException on parsing and initialization errors.
*/
public X509CertImpl(DerValue derVal)
- throws CertificateException {
+ throws CertificateException {
try {
parse(derVal);
signedCert = derVal.toByteArray();
} catch (IOException e) {
- throw new CertificateException("Unable to initialize, " + e);
+ throw new CertificateException("Unable to initialize, " + e);
}
}
- public boolean hasUnsupportedCriticalExtension()
- {
- // XXX NOT IMPLEMENTED
- return true;
+ public boolean hasUnsupportedCriticalExtension() {
+ // XXX NOT IMPLEMENTED
+ return true;
}
/**
* Decode an X.509 certificate from an input stream.
- *
+ *
* @param in an input stream holding at least one certificate
* @exception CertificateException on parsing errors.
* @exception IOException on other errors.
*/
public void decode(InputStream in)
- throws CertificateException, IOException {
- DerValue val = new DerValue(in);
+ throws CertificateException, IOException {
+ DerValue val = new DerValue(in);
parse(val);
signedCert = val.toByteArray();
@@ -259,12 +261,12 @@ implements Serializable, DerEncoder {
/**
* Appends the certificate to an output stream.
- *
+ *
* @param out an input stream to which the certificate is appended.
* @exception CertificateEncodingException on encoding errors.
*/
public void encode(OutputStream out)
- throws CertificateEncodingException {
+ throws CertificateEncodingException {
if (signedCert == null)
throw new CertificateEncodingException(
"Null certificate to encode");
@@ -276,27 +278,25 @@ implements Serializable, DerEncoder {
}
/**
- * DER encode this object onto an output stream.
- * Implements the <code>DerEncoder</code> interface.
- *
- * @param out
- * the output stream on which to write the DER encoding.
- *
+ * DER encode this object onto an output stream. Implements the
+ * <code>DerEncoder</code> interface.
+ *
+ * @param out the output stream on which to write the DER encoding.
+ *
* @exception IOException on encoding error.
*/
- public void derEncode (OutputStream out) throws IOException {
+ public void derEncode(OutputStream out) throws IOException {
if (signedCert == null)
throw new IOException("Null certificate to encode");
- out.write(signedCert);
+ out.write(signedCert);
}
/**
- * Returns the encoded form of this certificate. It is
- * assumed that each certificate type would have only a single
- * form of encoding; for example, X.509 certificates would
- * be encoded as ASN.1 DER.
- *
+ * Returns the encoded form of this certificate. It is assumed that each
+ * certificate type would have only a single form of encoding; for example,
+ * X.509 certificates would be encoded as ASN.1 DER.
+ *
* @exception CertificateEncodingException if an encoding error occurs.
*/
public byte[] getEncoded() throws CertificateEncodingException {
@@ -310,50 +310,48 @@ implements Serializable, DerEncoder {
/**
* Throws an exception if the certificate was not signed using the
- * verification key provided. Successfully verifying a certificate
- * does <em>not</em> indicate that one should trust the entity which
- * it represents.
- *
+ * verification key provided. Successfully verifying a certificate does
+ * <em>not</em> indicate that one should trust the entity which it
+ * represents.
+ *
* @param key the public key used for verification.
- *
+ *
* @exception InvalidKeyException on incorrect key.
- * @exception NoSuchAlgorithmException on unsupported signature
- * algorithms.
+ * @exception NoSuchAlgorithmException on unsupported signature algorithms.
* @exception NoSuchProviderException if there's no default provider.
* @exception SignatureException on signature errors.
* @exception CertificateException on encoding errors.
*/
public void verify(PublicKey key)
- throws CertificateException, NoSuchAlgorithmException,
- InvalidKeyException, NoSuchProviderException, SignatureException {
+ throws CertificateException, NoSuchAlgorithmException,
+ InvalidKeyException, NoSuchProviderException, SignatureException {
verify(key, null);
}
/**
* Throws an exception if the certificate was not signed using the
- * verification key provided. Successfully verifying a certificate
- * does <em>not</em> indicate that one should trust the entity which
- * it represents.
- *
+ * verification key provided. Successfully verifying a certificate does
+ * <em>not</em> indicate that one should trust the entity which it
+ * represents.
+ *
* @param key the public key used for verification.
* @param sigProvider the name of the provider.
- *
- * @exception NoSuchAlgorithmException on unsupported signature
- * algorithms.
+ *
+ * @exception NoSuchAlgorithmException on unsupported signature algorithms.
* @exception InvalidKeyException on incorrect key.
* @exception NoSuchProviderException on incorrect provider.
* @exception SignatureException on signature errors.
* @exception CertificateException on encoding errors.
*/
public void verify(PublicKey key, String sigProvider)
- throws CertificateException, NoSuchAlgorithmException,
- InvalidKeyException, NoSuchProviderException, SignatureException {
+ throws CertificateException, NoSuchAlgorithmException,
+ InvalidKeyException, NoSuchProviderException, SignatureException {
if (signedCert == null) {
throw new CertificateEncodingException("Uninitialized certificate");
}
// Verify the signature ...
- Signature sigVerf = null;
+ Signature sigVerf = null;
sigVerf = Signature.getInstance(algId.getName(), sigProvider);
sigVerf.initVerify(key);
@@ -367,47 +365,45 @@ implements Serializable, DerEncoder {
}
/**
- * Creates an X.509 certificate, and signs it using the key
- * passed (associating a signature algorithm and an X.500 name).
- * This operation is used to implement the certificate generation
- * functionality of a certificate authority.
- *
+ * Creates an X.509 certificate, and signs it using the key passed
+ * (associating a signature algorithm and an X.500 name). This operation is
+ * used to implement the certificate generation functionality of a
+ * certificate authority.
+ *
* @param key the private key used for signing.
* @param algorithm the name of the signature algorithm used.
- *
+ *
* @exception InvalidKeyException on incorrect key.
- * @exception NoSuchAlgorithmException on unsupported signature
- * algorithms.
+ * @exception NoSuchAlgorithmException on unsupported signature algorithms.
* @exception NoSuchProviderException if there's no default provider.
* @exception SignatureException on signature errors.
* @exception CertificateException on encoding errors.
*/
public void sign(PrivateKey key, String algorithm)
- throws CertificateException, NoSuchAlgorithmException,
- InvalidKeyException, NoSuchProviderException, SignatureException {
+ throws CertificateException, NoSuchAlgorithmException,
+ InvalidKeyException, NoSuchProviderException, SignatureException {
sign(key, algorithm, null);
}
/**
- * Creates an X.509 certificate, and signs it using the key
- * passed (associating a signature algorithm and an X.500 name).
- * This operation is used to implement the certificate generation
- * functionality of a certificate authority.
- *
+ * Creates an X.509 certificate, and signs it using the key passed
+ * (associating a signature algorithm and an X.500 name). This operation is
+ * used to implement the certificate generation functionality of a
+ * certificate authority.
+ *
* @param key the private key used for signing.
* @param algorithm the name of the signature algorithm used.
* @param provider the name of the provider.
- *
- * @exception NoSuchAlgorithmException on unsupported signature
- * algorithms.
+ *
+ * @exception NoSuchAlgorithmException on unsupported signature algorithms.
* @exception InvalidKeyException on incorrect key.
* @exception NoSuchProviderException on incorrect provider.
* @exception SignatureException on signature errors.
* @exception CertificateException on encoding errors.
*/
public void sign(PrivateKey key, String algorithm, String provider)
- throws CertificateException, NoSuchAlgorithmException,
- InvalidKeyException, NoSuchProviderException, SignatureException {
+ throws CertificateException, NoSuchAlgorithmException,
+ InvalidKeyException, NoSuchProviderException, SignatureException {
try {
if (readOnly)
throw new CertificateEncodingException(
@@ -420,7 +416,7 @@ implements Serializable, DerEncoder {
sigEngine.initSign(key);
- // in case the name is reset
+ // in case the name is reset
algId = AlgorithmId.get(sigEngine.getAlgorithm());
DerOutputStream out = new DerOutputStream();
@@ -445,42 +441,42 @@ implements Serializable, DerEncoder {
} catch (IOException e) {
throw new CertificateEncodingException(e.toString());
- }
+ }
}
/**
- * Checks that the certificate is currently valid, i.e. the current
- * time is within the specified validity period.
- *
+ * Checks that the certificate is currently valid, i.e. the current time is
+ * within the specified validity period.
+ *
* @exception CertificateExpiredException if the certificate has expired.
- * @exception CertificateNotYetValidException if the certificate is not
- * yet valid.
+ * @exception CertificateNotYetValidException if the certificate is not yet
+ * valid.
*/
public void checkValidity()
- throws CertificateExpiredException, CertificateNotYetValidException {
+ throws CertificateExpiredException, CertificateNotYetValidException {
Date date = new Date();
checkValidity(date);
}
/**
- * Checks that the specified date is within the certificate's
- * validity period, or basically if the certificate would be
- * valid at the specified date/time.
- *
- * @param date the Date to check against to see if this certificate
- * is valid at that date/time.
- *
+ * Checks that the specified date is within the certificate's validity
+ * period, or basically if the certificate would be valid at the specified
+ * date/time.
+ *
+ * @param date the Date to check against to see if this certificate is valid
+ * at that date/time.
+ *
* @exception CertificateExpiredException if the certificate has expired
- * with respect to the <code>date</code> supplied.
- * @exception CertificateNotYetValidException if the certificate is not
- * yet valid with respect to the <code>date</code> supplied.
+ * with respect to the <code>date</code> supplied.
+ * @exception CertificateNotYetValidException if the certificate is not yet
+ * valid with respect to the <code>date</code> supplied.
*/
public void checkValidity(Date date)
- throws CertificateExpiredException, CertificateNotYetValidException {
+ throws CertificateExpiredException, CertificateNotYetValidException {
CertificateValidity interval = null;
try {
- interval = (CertificateValidity)info.get(CertificateValidity.NAME);
+ interval = (CertificateValidity) info.get(CertificateValidity.NAME);
} catch (Exception e) {
throw new CertificateNotYetValidException("Incorrect validity period");
}
@@ -491,12 +487,12 @@ implements Serializable, DerEncoder {
/**
* Return the requested attribute from the certificate.
- *
+ *
* @param name the name of the attribute.
* @exception CertificateParsingException on invalid attribute identifier.
*/
public Object get(String name)
- throws CertificateParsingException {
+ throws CertificateParsingException {
X509AttributeName attr = new X509AttributeName(name);
String id = attr.getPrefix();
if (!(id.equalsIgnoreCase(NAME))) {
@@ -510,37 +506,37 @@ implements Serializable, DerEncoder {
if (id.equalsIgnoreCase(INFO)) {
if (attr.getSuffix() != null) {
try {
- return info.get(attr.getSuffix());
+ return info.get(attr.getSuffix());
} catch (IOException e) {
throw new CertificateParsingException(e.toString());
} catch (CertificateException e) {
throw new CertificateParsingException(e.toString());
}
} else {
- return(info);
+ return (info);
}
} else if (id.equalsIgnoreCase(ALG_ID)) {
- return(algId);
+ return (algId);
} else if (id.equalsIgnoreCase(SIGNATURE)) {
- return(signature);
+ return (signature);
} else if (id.equalsIgnoreCase(SIGNED_CERT)) {
- return(signedCert);
+ return (signedCert);
} else {
throw new CertificateParsingException("Attribute name not "
- + "recognized or get() not allowed for the same: " + id);
+ + "recognized or get() not allowed for the same: " + id);
}
}
/**
* Set the requested attribute in the certificate.
- *
+ *
* @param name the name of the attribute.
* @param obj the value of the attribute.
* @exception CertificateException on invalid attribute identifier.
* @exception IOException on encoding error of attribute.
*/
public void set(String name, Object obj)
- throws CertificateException, IOException {
+ throws CertificateException, IOException {
// check if immutable
if (readOnly)
throw new CertificateException("cannot over-write existing"
@@ -557,15 +553,15 @@ implements Serializable, DerEncoder {
if (id.equalsIgnoreCase(INFO)) {
if (attr.getSuffix() == null) {
- if (!(obj instanceof X509CertInfo)) {
- throw new CertificateException("Attribute value should"
+ if (!(obj instanceof X509CertInfo)) {
+ throw new CertificateException("Attribute value should"
+ " be of type X509CertInfo.");
- }
- info = (X509CertInfo)obj;
- signedCert = null; //reset this as certificate data has changed
+ }
+ info = (X509CertInfo) obj;
+ signedCert = null; // reset this as certificate data has changed
} else {
- info.set(attr.getSuffix(), obj);
- signedCert = null; //reset this as certificate data has changed
+ info.set(attr.getSuffix(), obj);
+ signedCert = null; // reset this as certificate data has changed
}
} else {
throw new CertificateException("Attribute name not recognized or " +
@@ -575,13 +571,13 @@ implements Serializable, DerEncoder {
/**
* Delete the requested attribute from the certificate.
- *
+ *
* @param name the name of the attribute.
* @exception CertificateException on invalid attribute identifier.
* @exception IOException on other errors.
*/
public void delete(String name)
- throws CertificateException, IOException {
+ throws CertificateException, IOException {
// check if immutable
if (readOnly)
throw new CertificateException("cannot over-write existing"
@@ -599,9 +595,9 @@ implements Serializable, DerEncoder {
if (id.equalsIgnoreCase(INFO)) {
if (attr.getSuffix() != null) {
- info = null;
+ info = null;
} else {
- info.delete(attr.getSuffix());
+ info.delete(attr.getSuffix());
}
} else if (id.equalsIgnoreCase(ALG_ID)) {
algId = null;
@@ -626,21 +622,21 @@ implements Serializable, DerEncoder {
elements.addElement(NAME + DOT + SIGNATURE);
elements.addElement(NAME + DOT + SIGNED_CERT);
- return(elements.elements());
+ return (elements.elements());
}
/**
* Return the name of this attribute.
*/
public String getName() {
- return(NAME);
+ return (NAME);
}
/**
- * Returns a printable representation of the certificate. This does not
- * contain all the information available to distinguish this from any
- * other certificate. The certificate must be fully constructed
- * before this function may be called.
+ * Returns a printable representation of the certificate. This does not
+ * contain all the information available to distinguish this from any other
+ * certificate. The certificate must be fully constructed before this
+ * function may be called.
*/
public String toString() {
if (info == null || algId == null || signature == null)
@@ -652,9 +648,9 @@ implements Serializable, DerEncoder {
sb.append(info.toString() + "\n");
sb.append(" Algorithm: [" + algId.toString() + "]\n");
- netscape.security.util.PrettyPrintFormat pp =
- new netscape.security.util.PrettyPrintFormat(" ", 20);
- String signaturebits = pp.toHexString(signature);
+ netscape.security.util.PrettyPrintFormat pp =
+ new netscape.security.util.PrettyPrintFormat(" ", 20);
+ String signaturebits = pp.toHexString(signature);
sb.append(" Signature:\n" + signaturebits);
sb.append("]");
@@ -665,144 +661,144 @@ implements Serializable, DerEncoder {
/**
* Gets the publickey from this certificate.
- *
+ *
* @return the publickey.
*/
public PublicKey getPublicKey() {
if (info == null)
return null;
- try {
- PublicKey key = (PublicKey)info.get(CertificateX509Key.NAME
+ try {
+ PublicKey key = (PublicKey) info.get(CertificateX509Key.NAME
+ DOT + CertificateX509Key.KEY);
- return key;
+ return key;
} catch (Exception e) {
- return null;
- }
+ return null;
+ }
}
/**
* Gets the version number from the certificate.
- *
+ *
* @return the version number.
*/
public int getVersion() {
if (info == null)
return -1;
- try {
- int vers = ((Integer)info.get(CertificateVersion.NAME
+ try {
+ int vers = ((Integer) info.get(CertificateVersion.NAME
+ DOT + CertificateVersion.VERSION)).intValue();
- return vers;
+ return vers;
} catch (Exception e) {
return -1;
- }
+ }
}
/**
* Gets the serial number from the certificate.
- *
+ *
* @return the serial number.
*/
public BigInteger getSerialNumber() {
if (info == null)
return null;
- try {
- SerialNumber ser = (SerialNumber)info.get(
+ try {
+ SerialNumber ser = (SerialNumber) info.get(
CertificateSerialNumber.NAME + DOT +
- CertificateSerialNumber.NUMBER);
- return ((BigInt)ser.getNumber()).toBigInteger();
+ CertificateSerialNumber.NUMBER);
+ return ((BigInt) ser.getNumber()).toBigInteger();
} catch (Exception e) {
return null;
- }
+ }
}
/**
* Gets the subject distinguished name from the certificate.
- *
+ *
* @return the subject name.
*/
public Principal getSubjectDN() {
if (info == null)
return null;
- try {
- Principal subject = (Principal)info.get(
+ try {
+ Principal subject = (Principal) info.get(
CertificateSubjectName.NAME + DOT +
- CertificateSubjectName.DN_NAME);
- return subject;
+ CertificateSubjectName.DN_NAME);
+ return subject;
} catch (Exception e) {
return null;
- }
+ }
}
/**
* Gets the issuer distinguished name from the certificate.
- *
+ *
* @return the issuer name.
*/
public Principal getIssuerDN() {
if (info == null)
return null;
- try {
- Principal issuer = (Principal)info.get(
+ try {
+ Principal issuer = (Principal) info.get(
CertificateIssuerName.NAME + DOT +
- CertificateIssuerName.DN_NAME);
- return issuer;
+ CertificateIssuerName.DN_NAME);
+ return issuer;
} catch (Exception e) {
return null;
- }
+ }
}
/**
* Gets the notBefore date from the validity period of the certificate.
- *
+ *
* @return the start date of the validity period.
*/
public Date getNotBefore() {
if (info == null)
return null;
- try {
- Date d = (Date) info.get(CertificateValidity.NAME + DOT +
+ try {
+ Date d = (Date) info.get(CertificateValidity.NAME + DOT +
CertificateValidity.NOT_BEFORE);
- return d;
+ return d;
} catch (Exception e) {
return null;
- }
+ }
}
/**
* Gets the notAfter date from the validity period of the certificate.
- *
+ *
* @return the end date of the validity period.
*/
public Date getNotAfter() {
if (info == null)
return null;
- try {
- Date d = (Date) info.get(CertificateValidity.NAME + DOT +
+ try {
+ Date d = (Date) info.get(CertificateValidity.NAME + DOT +
CertificateValidity.NOT_AFTER);
- return d;
+ return d;
} catch (Exception e) {
return null;
- }
+ }
}
/**
* Gets the DER encoded certificate informations, the
- * <code>tbsCertificate</code> from this certificate.
- * This can be used to verify the signature independently.
- *
+ * <code>tbsCertificate</code> from this certificate. This can be used to
+ * verify the signature independently.
+ *
* @return the DER encoded certificate information.
* @exception CertificateEncodingException if an encoding error occurs.
*/
public byte[] getTBSCertificate() throws CertificateEncodingException {
if (info != null) {
- return info.getEncodedInfo();
+ return info.getEncodedInfo();
} else
throw new CertificateEncodingException("Uninitialized certificate");
}
/**
* Gets the raw Signature bits from the certificate.
- *
+ *
* @return the signature.
*/
public byte[] getSignature() {
@@ -814,172 +810,171 @@ implements Serializable, DerEncoder {
}
/**
- * Gets the signature algorithm name for the certificate
- * signature algorithm.
- * For example, the string "SHA-1/DSA" or "DSS".
- *
+ * Gets the signature algorithm name for the certificate signature
+ * algorithm. For example, the string "SHA-1/DSA" or "DSS".
+ *
* @return the signature algorithm name.
*/
public String getSigAlgName() {
if (algId == null)
return null;
- return (algId.getName());
+ return (algId.getName());
}
/**
- * Gets the signature algorithm OID string from the certificate.
- * For example, the string "1.2.840.10040.4.3"
- *
+ * Gets the signature algorithm OID string from the certificate. For
+ * example, the string "1.2.840.10040.4.3"
+ *
* @return the signature algorithm oid string.
*/
public String getSigAlgOID() {
if (algId == null)
return null;
- ObjectIdentifier oid = algId.getOID();
- return (oid.toString());
+ ObjectIdentifier oid = algId.getOID();
+ return (oid.toString());
}
/**
* Gets the DER encoded signature algorithm parameters from this
* certificate's signature algorithm.
- *
- * @return the DER encoded signature algorithm parameters, or
- * null if no parameters are present.
+ *
+ * @return the DER encoded signature algorithm parameters, or null if no
+ * parameters are present.
*/
public byte[] getSigAlgParams() {
if (algId == null)
return null;
- try {
- return algId.getEncodedParams();
- } catch (IOException e) {
+ try {
+ return algId.getEncodedParams();
+ } catch (IOException e) {
return null;
- }
+ }
}
/**
* Gets the Issuer Unique Identity from the certificate.
- *
+ *
* @return the Issuer Unique Identity.
*/
public boolean[] getIssuerUniqueID() {
if (info == null)
return null;
- try {
- UniqueIdentity id = (UniqueIdentity)info.get(
+ try {
+ UniqueIdentity id = (UniqueIdentity) info.get(
CertificateIssuerUniqueIdentity.NAME
- + DOT + CertificateIssuerUniqueIdentity.ID);
+ + DOT + CertificateIssuerUniqueIdentity.ID);
if (id == null)
return null;
else
return (id.getId());
} catch (Exception e) {
return null;
- }
+ }
}
/**
* Gets the Subject Unique Identity from the certificate.
- *
+ *
* @return the Subject Unique Identity.
*/
public boolean[] getSubjectUniqueID() {
if (info == null)
return null;
- try {
- UniqueIdentity id = (UniqueIdentity)info.get(
+ try {
+ UniqueIdentity id = (UniqueIdentity) info.get(
CertificateSubjectUniqueIdentity.NAME
- + DOT + CertificateSubjectUniqueIdentity.ID);
+ + DOT + CertificateSubjectUniqueIdentity.ID);
if (id == null)
return null;
else
return (id.getId());
} catch (Exception e) {
return null;
- }
+ }
}
/**
- * Gets a Set of the extension(s) marked CRITICAL in the
- * certificate by OID strings.
- *
- * @return a set of the extension oid strings in the
- * certificate that are marked critical.
+ * Gets a Set of the extension(s) marked CRITICAL in the certificate by OID
+ * strings.
+ *
+ * @return a set of the extension oid strings in the certificate that are
+ * marked critical.
*/
public Set<String> getCriticalExtensionOIDs() {
if (info == null)
return null;
- try {
- CertificateExtensions exts = (CertificateExtensions)info.get(
+ try {
+ CertificateExtensions exts = (CertificateExtensions) info.get(
CertificateExtensions.NAME);
- if (exts == null)
+ if (exts == null)
return null;
Set<String> extSet = new TreeSet<String>();
Extension ex;
- for (Enumeration<Extension> e = exts.getAttributes(); e.hasMoreElements(); ) {
+ for (Enumeration<Extension> e = exts.getAttributes(); e.hasMoreElements();) {
ex = e.nextElement();
- if (ex.isCritical())
- extSet.add(((ObjectIdentifier)ex.getExtensionId()).toString());
- }
+ if (ex.isCritical())
+ extSet.add(((ObjectIdentifier) ex.getExtensionId()).toString());
+ }
return extSet;
} catch (Exception e) {
return null;
- }
+ }
}
/**
- * Gets a Set of the extension(s) marked NON-CRITICAL in the
- * certificate by OID strings.
- *
- * @return a set of the extension oid strings in the
- * certificate that are NOT marked critical.
+ * Gets a Set of the extension(s) marked NON-CRITICAL in the certificate by
+ * OID strings.
+ *
+ * @return a set of the extension oid strings in the certificate that are
+ * NOT marked critical.
*/
public Set<String> getNonCriticalExtensionOIDs() {
if (info == null)
return null;
- try {
- CertificateExtensions exts = (CertificateExtensions)info.get(
+ try {
+ CertificateExtensions exts = (CertificateExtensions) info.get(
CertificateExtensions.NAME);
- if (exts == null)
+ if (exts == null)
return null;
Set<String> extSet = new TreeSet<String>();
Extension ex;
- for (Enumeration<Extension> e = exts.getAttributes(); e.hasMoreElements(); ) {
+ for (Enumeration<Extension> e = exts.getAttributes(); e.hasMoreElements();) {
ex = e.nextElement();
- if ( ! ex.isCritical())
- extSet.add(((ObjectIdentifier)ex.getExtensionId()).toString());
- }
+ if (!ex.isCritical())
+ extSet.add(((ObjectIdentifier) ex.getExtensionId()).toString());
+ }
return extSet;
} catch (Exception e) {
return null;
- }
+ }
}
public Extension getExtension(String oid) {
try {
- CertificateExtensions exts = (CertificateExtensions)info.get(
+ CertificateExtensions exts = (CertificateExtensions) info.get(
CertificateExtensions.NAME);
- if (exts == null)
- return null;
- ObjectIdentifier findOID = new ObjectIdentifier(oid);
- Extension ex = null;;
- ObjectIdentifier inCertOID;
- for (Enumeration<Extension> e=exts.getAttributes(); e.hasMoreElements();) {
- ex = e.nextElement();
- inCertOID = ex.getExtensionId();
- if (inCertOID.equals(findOID)) {
- return ex;
- }
- }
+ if (exts == null)
+ return null;
+ ObjectIdentifier findOID = new ObjectIdentifier(oid);
+ Extension ex = null;
+ ;
+ ObjectIdentifier inCertOID;
+ for (Enumeration<Extension> e = exts.getAttributes(); e.hasMoreElements();) {
+ ex = e.nextElement();
+ inCertOID = ex.getExtensionId();
+ if (inCertOID.equals(findOID)) {
+ return ex;
+ }
+ }
} catch (Exception e) {
- }
+ }
return null;
}
/**
- * Gets the DER encoded extension identified by the passed
- * in oid String.
- *
+ * Gets the DER encoded extension identified by the passed in oid String.
+ *
* @param oid the Object Identifier value for the extension.
*/
public byte[] getExtensionValue(String oid) {
@@ -989,33 +984,34 @@ implements Serializable, DerEncoder {
if (extAlias == null) { // may be unknown
// get the extensions, search thru' for this oid
- CertificateExtensions exts = (CertificateExtensions)info.get(
+ CertificateExtensions exts = (CertificateExtensions) info.get(
CertificateExtensions.NAME);
- if (exts == null)
- return null;
-
- ObjectIdentifier findOID = new ObjectIdentifier(oid);
- Extension ex = null;;
- ObjectIdentifier inCertOID;
- for (Enumeration<Extension> e=exts.getAttributes(); e.hasMoreElements();) {
- ex = e.nextElement();
- inCertOID = ex.getExtensionId();
- if (inCertOID.equals(findOID)) {
- certExt = ex;
- break;
- }
- }
+ if (exts == null)
+ return null;
+
+ ObjectIdentifier findOID = new ObjectIdentifier(oid);
+ Extension ex = null;
+ ;
+ ObjectIdentifier inCertOID;
+ for (Enumeration<Extension> e = exts.getAttributes(); e.hasMoreElements();) {
+ ex = e.nextElement();
+ inCertOID = ex.getExtensionId();
+ if (inCertOID.equals(findOID)) {
+ certExt = ex;
+ break;
+ }
+ }
} else { // there's sub-class that can handle this extension
- certExt = (Extension)this.get(extAlias);
+ certExt = (Extension) this.get(extAlias);
}
if (certExt == null)
- return null;
+ return null;
byte[] extData = certExt.getExtensionValue();
if (extData == null)
return null;
- DerOutputStream out = new DerOutputStream();
- out.putOctetString(extData);
+ DerOutputStream out = new DerOutputStream();
+ out.putOctetString(extData);
return out.toByteArray();
} catch (Exception e) {
return null;
@@ -1023,19 +1019,20 @@ implements Serializable, DerEncoder {
}
/**
- * Get a boolean array representing the bits of the KeyUsage extension,
- * (oid = 2.5.29.15).
+ * Get a boolean array representing the bits of the KeyUsage extension, (oid
+ * = 2.5.29.15).
+ *
* @return the bit values of this extension as an array of booleans.
*/
public boolean[] getKeyUsage() {
try {
- String extAlias = OIDMap.getName(new ObjectIdentifier(
+ String extAlias = OIDMap.getName(new ObjectIdentifier(
KEY_USAGE_OID));
- if (extAlias == null)
+ if (extAlias == null)
return null;
- KeyUsageExtension certExt = (KeyUsageExtension)this.get(extAlias);
- if (certExt == null)
+ KeyUsageExtension certExt = (KeyUsageExtension) this.get(extAlias);
+ if (certExt == null)
return null;
return certExt.getBits();
@@ -1045,24 +1042,24 @@ implements Serializable, DerEncoder {
}
/**
- * Get the certificate constraints path length from the
- * the critical BasicConstraints extension, (oid = 2.5.29.19).
+ * Get the certificate constraints path length from the the critical
+ * BasicConstraints extension, (oid = 2.5.29.19).
+ *
* @return the length of the constraint.
*/
public int getBasicConstraints() {
try {
- String extAlias = OIDMap.getName(new ObjectIdentifier(
+ String extAlias = OIDMap.getName(new ObjectIdentifier(
BASIC_CONSTRAINT_OID));
- if (extAlias == null)
+ if (extAlias == null)
return -1;
- BasicConstraintsExtension certExt =
- (BasicConstraintsExtension)this.get(extAlias);
- if (certExt == null)
+ BasicConstraintsExtension certExt =
+ (BasicConstraintsExtension) this.get(extAlias);
+ if (certExt == null)
return -1;
- if (((Boolean)certExt.get(BasicConstraintsExtension.IS_CA)
- ).booleanValue() == true)
- return ((Integer)certExt.get(
+ if (((Boolean) certExt.get(BasicConstraintsExtension.IS_CA)).booleanValue() == true)
+ return ((Integer) certExt.get(
BasicConstraintsExtension.PATH_LEN)).intValue();
else
return -1;
@@ -1080,11 +1077,11 @@ implements Serializable, DerEncoder {
return false;
BasicConstraintsExtension certExt =
- (BasicConstraintsExtension)this.get(extAlias);
+ (BasicConstraintsExtension) this.get(extAlias);
if (certExt == null)
return false;
- isCA = ((Boolean)certExt.get(BasicConstraintsExtension.IS_CA)).booleanValue();
+ isCA = ((Boolean) certExt.get(BasicConstraintsExtension.IS_CA)).booleanValue();
} catch (Exception e) {
return false;
}
@@ -1095,13 +1092,12 @@ implements Serializable, DerEncoder {
/*
* Cert is a SIGNED ASN.1 macro, a three elment sequence:
- *
- * - Data to be signed (ToBeSigned) -- the "raw" cert
- * - Signature algorithm (SigAlgId)
- * - The signature bits
- *
- * This routine unmarshals the certificate, saving the signature
- * parts away for later verification.
+ *
+ * - Data to be signed (ToBeSigned) -- the "raw" cert - Signature algorithm
+ * (SigAlgId) - The signature bits
+ *
+ * This routine unmarshals the certificate, saving the signature parts away
+ * for later verification.
*/
private void parse(DerValue val) throws CertificateException, IOException {
// check if can over write the certificate
@@ -1110,7 +1106,7 @@ implements Serializable, DerEncoder {
"cannot over-write existing certificate");
readOnly = true;
- DerValue seq[] = new DerValue[3];
+ DerValue seq[] = new DerValue[3];
seq[0] = val.data.getDerValue();
seq[1] = val.data.getDerValue();
@@ -1134,28 +1130,27 @@ implements Serializable, DerEncoder {
throw new CertificateParsingException("signed fields overrun");
// The CertificateInfo
- if (info == null) {
- info = new X509CertInfo(seq[0]);
- }
+ if (info == null) {
+ info = new X509CertInfo(seq[0]);
+ }
}
/**
- * Serialization write ... X.509 certificates serialize as
- * themselves, and they're parsed when they get read back.
- * (Actually they serialize as some type data from the
- * serialization subsystem, then the cert data.)
+ * Serialization write ... X.509 certificates serialize as themselves, and
+ * they're parsed when they get read back. (Actually they serialize as some
+ * type data from the serialization subsystem, then the cert data.)
*/
private synchronized void writeObject(ObjectOutputStream stream)
- throws CertificateException, IOException {
+ throws CertificateException, IOException {
encode(stream);
}
/**
- * Serialization read ... X.509 certificates serialize as
- * themselves, and they're parsed when they get read back.
+ * Serialization read ... X.509 certificates serialize as themselves, and
+ * they're parsed when they get read back.
*/
private synchronized void readObject(ObjectInputStream stream)
- throws CertificateException, IOException {
+ throws CertificateException, IOException {
decode(stream);
}
@@ -1168,13 +1163,14 @@ implements Serializable, DerEncoder {
private byte[] data1;
/**
- * Construct the alternate Certificate class with the Certificate
- * type and Certificate encoding bytes.
- *
+ * Construct the alternate Certificate class with the Certificate type
+ * and Certificate encoding bytes.
+ *
* <p>
- *
- * @param type the standard name of the Certificate type. <p>
- *
+ *
+ * @param type the standard name of the Certificate type.
+ * <p>
+ *
* @param data the Certificate data.
*/
protected CertificateRep1(String type, byte[] data) {
@@ -1184,26 +1180,25 @@ implements Serializable, DerEncoder {
/**
* Resolve the Certificate Object.
- *
+ *
* <p>
- *
+ *
* @return the resolved Certificate Object.
- *
- * @throws java.io.ObjectStreamException if the Certificate could not
- * be resolved.
+ *
+ * @throws java.io.ObjectStreamException if the Certificate could not be
+ * resolved.
*/
protected Object readResolve() throws java.io.ObjectStreamException {
try {
CertificateFactory cf = CertificateFactory.getInstance(type1);
return new X509CertImpl(data1);
-/*
- return cf.generateCertificate
- (new java.io.ByteArrayInputStream(data1));
-*/
+ /*
+ * return cf.generateCertificate (new
+ * java.io.ByteArrayInputStream(data1));
+ */
} catch (CertificateException e) {
- throw new java.io.NotSerializableException
- ("java.security.cert.Certificate: " +
+ throw new java.io.NotSerializableException("java.security.cert.Certificate: " +
type1 +
": " +
e.getMessage());
@@ -1216,8 +1211,7 @@ implements Serializable, DerEncoder {
try {
return new CertificateRep1("X.509", getEncoded());
} catch (CertificateException e) {
- throw new java.io.NotSerializableException
- ("java.security.cert.Certificate: " +
+ throw new java.io.NotSerializableException("java.security.cert.Certificate: " +
"X.509" +
": " +
e.getMessage());
diff --git a/pki/base/util/src/netscape/security/x509/X509CertInfo.java b/pki/base/util/src/netscape/security/x509/X509CertInfo.java
index 1178d6a3..f60d9a78 100644
--- a/pki/base/util/src/netscape/security/x509/X509CertInfo.java
+++ b/pki/base/util/src/netscape/security/x509/X509CertInfo.java
@@ -34,27 +34,28 @@ import netscape.security.util.DerInputStream;
import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
-
/**
* The X509CertInfo class represents X.509 certificate information.
- *
- * <P>X.509 certificates have several base data elements, including:<UL>
- *
- * <LI>The <em>Subject Name</em>, an X.500 Distinguished Name for
- * the entity (subject) for which the certificate was issued.
- *
- * <LI>The <em>Subject Public Key</em>, the public key of the subject.
- * This is one of the most important parts of the certificate.
- *
- * <LI>The <em>Validity Period</em>, a time period (e.g. six months)
- * within which the certificate is valid (unless revoked).
- *
- * <LI>The <em>Issuer Name</em>, an X.500 Distinguished Name for the
- * Certificate Authority (CA) which issued the certificate.
- *
- * <LI>A <em>Serial Number</em> assigned by the CA, for use in
- * certificate revocation and other applications.
- *
+ *
+ * <P>
+ * X.509 certificates have several base data elements, including:
+ * <UL>
+ *
+ * <LI>The <em>Subject Name</em>, an X.500 Distinguished Name for the entity
+ * (subject) for which the certificate was issued.
+ *
+ * <LI>The <em>Subject Public Key</em>, the public key of the subject. This is
+ * one of the most important parts of the certificate.
+ *
+ * <LI>The <em>Validity Period</em>, a time period (e.g. six months) within
+ * which the certificate is valid (unless revoked).
+ *
+ * <LI>The <em>Issuer Name</em>, an X.500 Distinguished Name for the Certificate
+ * Authority (CA) which issued the certificate.
+ *
+ * <LI>A <em>Serial Number</em> assigned by the CA, for use in certificate
+ * revocation and other applications.
+ *
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @version 1.16
@@ -68,9 +69,9 @@ public class X509CertInfo implements CertAttrSet, Serializable {
*/
private static final long serialVersionUID = -5094073467876311577L;
/**
- * Identifier for this attribute, to be used with the
- * get, set, delete methods of Certificate, x509 type.
- */
+ * Identifier for this attribute, to be used with the get, set, delete
+ * methods of Certificate, x509 type.
+ */
public static final String IDENT = "x509.info";
// Certificate attribute names
public static final String NAME = "info";
@@ -87,19 +88,19 @@ public class X509CertInfo implements CertAttrSet, Serializable {
// X509.v1 data
protected CertificateVersion version = new CertificateVersion();
- protected CertificateSerialNumber serialNum = null;
- protected CertificateAlgorithmId algId = null;
- protected CertificateIssuerName issuer = null;
- protected CertificateValidity interval = null;
- protected CertificateSubjectName subject = null;
- protected CertificateX509Key pubKey = null;
-
+ protected CertificateSerialNumber serialNum = null;
+ protected CertificateAlgorithmId algId = null;
+ protected CertificateIssuerName issuer = null;
+ protected CertificateValidity interval = null;
+ protected CertificateSubjectName subject = null;
+ protected CertificateX509Key pubKey = null;
+
// X509.v2 & v3 extensions
- protected CertificateIssuerUniqueIdentity issuerUniqueId = null;
- protected CertificateSubjectUniqueIdentity subjectUniqueId = null;
-
+ protected CertificateIssuerUniqueIdentity issuerUniqueId = null;
+ protected CertificateSubjectUniqueIdentity subjectUniqueId = null;
+
// X509.v3 extensions
- protected CertificateExtensions extensions = null;
+ protected CertificateExtensions extensions = null;
// Attribute numbers for internal manipulation
private static final int ATTR_VERSION = 1;
@@ -114,8 +115,8 @@ public class X509CertInfo implements CertAttrSet, Serializable {
private static final int ATTR_EXTENSIONS = 10;
// DER encoded CertificateInfo data
- private byte[] rawCertInfo = null;
-
+ private byte[] rawCertInfo = null;
+
// The certificate attribute name to integer mapping stored here
private static final Hashtable<String, Integer> map = new Hashtable<String, Integer>();
static {
@@ -130,7 +131,7 @@ public class X509CertInfo implements CertAttrSet, Serializable {
map.put(SUBJECT_ID, Integer.valueOf(ATTR_SUBJECT_ID));
map.put(EXTENSIONS, Integer.valueOf(ATTR_EXTENSIONS));
}
-
+
/**
* Construct an uninitialized X509CertInfo on which <a href="#decode">
* decode</a> must later be called (or which may be deserialized).
@@ -139,20 +140,19 @@ public class X509CertInfo implements CertAttrSet, Serializable {
}
/**
- * Unmarshals a certificate from its encoded form, parsing the
- * encoded bytes. This form of constructor is used by agents which
- * need to examine and use certificate contents. That is, this is
- * one of the more commonly used constructors. Note that the buffer
- * must include only a certificate, and no "garbage" may be left at
- * the end. If you need to ignore data at the end of a certificate,
- * use another constructor.
- *
+ * Unmarshals a certificate from its encoded form, parsing the encoded
+ * bytes. This form of constructor is used by agents which need to examine
+ * and use certificate contents. That is, this is one of the more commonly
+ * used constructors. Note that the buffer must include only a certificate,
+ * and no "garbage" may be left at the end. If you need to ignore data at
+ * the end of a certificate, use another constructor.
+ *
* @param cert the encoded bytes, with no trailing data.
* @exception CertificateParsingException on parsing errors.
*/
public X509CertInfo(byte[] cert) throws CertificateParsingException {
try {
- DerValue in = new DerValue(cert);
+ DerValue in = new DerValue(cert);
parse(in);
} catch (IOException e) {
@@ -161,10 +161,10 @@ public class X509CertInfo implements CertAttrSet, Serializable {
}
/**
- * Unmarshal a certificate from its encoded form, parsing a DER value.
- * This form of constructor is used by agents which need to examine
- * and use certificate contents.
- *
+ * Unmarshal a certificate from its encoded form, parsing a DER value. This
+ * form of constructor is used by agents which need to examine and use
+ * certificate contents.
+ *
* @param derVal the der value containing the encoded cert.
* @exception CertificateParsingException on parsing errors.
*/
@@ -178,35 +178,36 @@ public class X509CertInfo implements CertAttrSet, Serializable {
/**
* Decode an X.509 certificate from an input stream.
- *
+ *
* @param in an input stream holding at least one certificate
* @exception CertificateParsingException on decoding errors.
* @exception IOException on other errors.
*/
public void decode(InputStream in)
- throws CertificateParsingException, IOException {
- DerValue val = new DerValue(in);
+ throws CertificateParsingException, IOException {
+ DerValue val = new DerValue(in);
parse(val);
}
/**
* Appends the certificate to an output stream.
- *
+ *
* @param out an output stream to which the certificate is appended.
* @exception CertificateException on encoding errors.
* @exception IOException on other errors.
*/
public void encode(OutputStream out)
- throws CertificateException, IOException {
+ throws CertificateException, IOException {
encode(out, false);
}
/**
* Appends the certificate to an output stream.
- * @param out An output stream to which the certificate is appended.
- * @param ignoreCache Whether to ignore the internal cache when encoding.
- * (the cache can easily become out of date).
+ *
+ * @param out An output stream to which the certificate is appended.
+ * @param ignoreCache Whether to ignore the internal cache when encoding.
+ * (the cache can easily become out of date).
*/
public void encode(OutputStream out, boolean ignoreCache)
throws IOException, CertificateException {
@@ -235,19 +236,19 @@ public class X509CertInfo implements CertAttrSet, Serializable {
elements.addElement(SUBJECT_ID);
elements.addElement(EXTENSIONS);
- return(elements.elements());
+ return (elements.elements());
}
/**
* Return the name of this attribute.
*/
public String getName() {
- return(NAME);
+ return (NAME);
}
/**
* Returns the encoded certificate info.
- *
+ *
* @exception CertificateEncodingException on encoding information errors.
*/
public byte[] getEncodedInfo() throws CertificateEncodingException {
@@ -272,10 +273,9 @@ public class X509CertInfo implements CertAttrSet, Serializable {
}
/**
- * Compares two X509CertInfo objects. This is false if the
- * certificates are not both X.509 certs, otherwise it
- * compares them as binary data.
- *
+ * Compares two X509CertInfo objects. This is false if the certificates are
+ * not both X.509 certs, otherwise it compares them as binary data.
+ *
* @param other the object being compared with this one
* @return true iff the certificates are equivalent
*/
@@ -288,39 +288,39 @@ public class X509CertInfo implements CertAttrSet, Serializable {
}
/**
- * Compares two certificates, returning false if any data
- * differs between the two.
- *
+ * Compares two certificates, returning false if any data differs between
+ * the two.
+ *
* @param other the object being compared with this one
* @return true iff the certificates are equivalent
*/
public boolean equals(X509CertInfo other) {
if (this == other) {
- return(true);
+ return (true);
} else if (rawCertInfo == null || other.rawCertInfo == null) {
- return(false);
+ return (false);
} else if (rawCertInfo.length != other.rawCertInfo.length) {
- return(false);
+ return (false);
}
for (int i = 0; i < rawCertInfo.length; i++) {
if (rawCertInfo[i] != other.rawCertInfo[i]) {
- return(false);
+ return (false);
}
}
- return(true);
+ return (true);
}
/**
- * Calculates a hash code value for the object. Objects
- * which are equal will also have the same hashcode.
+ * Calculates a hash code value for the object. Objects which are equal will
+ * also have the same hashcode.
*/
public int hashCode() {
- int retval = 0;
+ int retval = 0;
for (int i = 1; i < rawCertInfo.length; i++) {
retval += rawCertInfo[i] * i;
}
- return(retval);
+ return (retval);
}
/**
@@ -329,8 +329,8 @@ public class X509CertInfo implements CertAttrSet, Serializable {
public String toString() {
if (subject == null || pubKey == null || interval == null
- || issuer == null || algId == null || serialNum == null) {
- throw new NullPointerException("X.509 cert is incomplete");
+ || issuer == null || algId == null || serialNum == null) {
+ throw new NullPointerException("X.509 cert is incomplete");
}
StringBuffer sb = new StringBuffer();
@@ -351,11 +351,11 @@ public class X509CertInfo implements CertAttrSet, Serializable {
sb.append(" Subject Id:\n" + subjectUniqueId.toString() + "\n");
}
if (extensions != null) {
- netscape.security.util.PrettyPrintFormat pp =
- new netscape.security.util.PrettyPrintFormat(" ", 20);
+ netscape.security.util.PrettyPrintFormat pp =
+ new netscape.security.util.PrettyPrintFormat(" ", 20);
for (int i = 0; i < extensions.size(); i++) {
- sb.append(" Extension[" + i + "] = ");
- Extension ext = (Extension)extensions.elementAt(i);
+ sb.append(" Extension[" + i + "] = ");
+ Extension ext = (Extension) extensions.elementAt(i);
try {
if (OIDMap.getClass(ext.getExtensionId()) == null) {
sb.append(ext.toString());
@@ -364,13 +364,13 @@ public class X509CertInfo implements CertAttrSet, Serializable {
DerOutputStream out = new DerOutputStream();
out.putOctetString(extValue);
extValue = out.toByteArray();
- String extValuebits = pp.toHexString(extValue);
+ String extValuebits = pp.toHexString(extValue);
sb.append("Extension unknown: "
+ "DER encoded OCTET string =\n"
+ extValuebits);
}
} else
- sb.append(ext.toString()); //sub-class exists
+ sb.append(ext.toString()); // sub-class exists
} catch (Exception e) {
sb.append(", Error parsing this extension");
}
@@ -382,14 +382,14 @@ public class X509CertInfo implements CertAttrSet, Serializable {
/**
* Set the certificate attribute.
- *
+ *
* @param name the name of the Certificate attribute.
* @param val the value of the Certificate attribute.
* @exception CertificateException on invalid attributes.
* @exception IOException on other errors.
*/
public void set(String name, Object val)
- throws CertificateException, IOException {
+ throws CertificateException, IOException {
X509AttributeName attrName = new X509AttributeName(name);
int attr = attributeMap(attrName.getPrefix());
@@ -403,81 +403,81 @@ public class X509CertInfo implements CertAttrSet, Serializable {
switch (attr) {
case ATTR_VERSION:
if (attrName.getSuffix() == null) {
- setVersion(val);
+ setVersion(val);
} else {
- version.set(attrName.getSuffix(),val);
+ version.set(attrName.getSuffix(), val);
}
break;
case ATTR_SERIAL:
if (attrName.getSuffix() == null) {
- setSerialNumber(val);
+ setSerialNumber(val);
} else {
- serialNum.set(attrName.getSuffix(),val);
+ serialNum.set(attrName.getSuffix(), val);
}
break;
case ATTR_ALGORITHM:
if (attrName.getSuffix() == null) {
- setAlgorithmId(val);
+ setAlgorithmId(val);
} else {
- algId.set(attrName.getSuffix(),val);
+ algId.set(attrName.getSuffix(), val);
}
break;
case ATTR_ISSUER:
if (attrName.getSuffix() == null) {
- setIssuer(val);
+ setIssuer(val);
} else {
- issuer.set(attrName.getSuffix(),val);
+ issuer.set(attrName.getSuffix(), val);
}
break;
case ATTR_VALIDITY:
if (attrName.getSuffix() == null) {
- setValidity(val);
+ setValidity(val);
} else {
- interval.set(attrName.getSuffix(),val);
+ interval.set(attrName.getSuffix(), val);
}
break;
case ATTR_SUBJECT:
if (attrName.getSuffix() == null) {
- setSubject(val);
+ setSubject(val);
} else {
- subject.set(attrName.getSuffix(),val);
+ subject.set(attrName.getSuffix(), val);
}
break;
case ATTR_KEY:
if (attrName.getSuffix() == null) {
- setKey(val);
+ setKey(val);
} else {
- pubKey.set(attrName.getSuffix(),val);
+ pubKey.set(attrName.getSuffix(), val);
}
break;
case ATTR_ISSUER_ID:
if (attrName.getSuffix() == null) {
- setIssuerUniqueId(val);
+ setIssuerUniqueId(val);
} else {
- issuerUniqueId.set(attrName.getSuffix(),val);
+ issuerUniqueId.set(attrName.getSuffix(), val);
}
break;
case ATTR_SUBJECT_ID:
if (attrName.getSuffix() == null) {
- setSubjectUniqueId(val);
+ setSubjectUniqueId(val);
} else {
- subjectUniqueId.set(attrName.getSuffix(),val);
+ subjectUniqueId.set(attrName.getSuffix(), val);
}
break;
case ATTR_EXTENSIONS:
if (attrName.getSuffix() == null) {
- setExtensions(val);
+ setExtensions(val);
} else {
- extensions.set(attrName.getSuffix(),val);
+ extensions.set(attrName.getSuffix(), val);
}
break;
}
@@ -485,13 +485,13 @@ public class X509CertInfo implements CertAttrSet, Serializable {
/**
* Delete the certificate attribute.
- *
+ *
* @param name the name of the Certificate attribute.
* @exception CertificateException on invalid attributes.
* @exception IOException on other errors.
*/
public void delete(String name)
- throws CertificateException, IOException {
+ throws CertificateException, IOException {
X509AttributeName attrName = new X509AttributeName(name);
int attr = attributeMap(attrName.getPrefix());
@@ -505,72 +505,72 @@ public class X509CertInfo implements CertAttrSet, Serializable {
switch (attr) {
case ATTR_VERSION:
if (attrName.getSuffix() == null) {
- version = null;
+ version = null;
} else {
- version.delete(attrName.getSuffix());
+ version.delete(attrName.getSuffix());
}
break;
case (ATTR_SERIAL):
if (attrName.getSuffix() == null) {
- serialNum = null;
+ serialNum = null;
} else {
- serialNum.delete(attrName.getSuffix());
+ serialNum.delete(attrName.getSuffix());
}
break;
case (ATTR_ALGORITHM):
if (attrName.getSuffix() == null) {
- algId = null;
+ algId = null;
} else {
- algId.delete(attrName.getSuffix());
+ algId.delete(attrName.getSuffix());
}
break;
case (ATTR_ISSUER):
if (attrName.getSuffix() == null) {
- issuer = null;
+ issuer = null;
} else {
- issuer.delete(attrName.getSuffix());
+ issuer.delete(attrName.getSuffix());
}
break;
case (ATTR_VALIDITY):
if (attrName.getSuffix() == null) {
- interval = null;
+ interval = null;
} else {
- interval.delete(attrName.getSuffix());
+ interval.delete(attrName.getSuffix());
}
break;
case (ATTR_SUBJECT):
if (attrName.getSuffix() == null) {
- subject = null;
+ subject = null;
} else {
- subject.delete(attrName.getSuffix());
+ subject.delete(attrName.getSuffix());
}
break;
case (ATTR_KEY):
if (attrName.getSuffix() == null) {
- pubKey = null;
+ pubKey = null;
} else {
- pubKey.delete(attrName.getSuffix());
+ pubKey.delete(attrName.getSuffix());
}
break;
case (ATTR_ISSUER_ID):
if (attrName.getSuffix() == null) {
- issuerUniqueId = null;
+ issuerUniqueId = null;
} else {
- issuerUniqueId.delete(attrName.getSuffix());
+ issuerUniqueId.delete(attrName.getSuffix());
}
break;
case (ATTR_SUBJECT_ID):
if (attrName.getSuffix() == null) {
- subjectUniqueId = null;
+ subjectUniqueId = null;
} else {
- subjectUniqueId.delete(attrName.getSuffix());
+ subjectUniqueId.delete(attrName.getSuffix());
}
break;
case (ATTR_EXTENSIONS):
if (attrName.getSuffix() == null) {
- extensions = null;
+ extensions = null;
} else {
- extensions.delete(attrName.getSuffix());
+ extensions.delete(attrName.getSuffix());
}
break;
}
@@ -578,14 +578,14 @@ public class X509CertInfo implements CertAttrSet, Serializable {
/**
* Get the certificate attribute.
- *
+ *
* @param name the name of the Certificate attribute.
- *
+ *
* @exception CertificateException on invalid attributes.
* @exception IOException on other errors.
*/
public Object get(String name)
- throws CertificateException, IOException {
+ throws CertificateException, IOException {
X509AttributeName attrName = new X509AttributeName(name);
int attr = attributeMap(attrName.getPrefix());
@@ -597,72 +597,72 @@ public class X509CertInfo implements CertAttrSet, Serializable {
switch (attr) {
case (ATTR_VERSION):
if (attrName.getSuffix() == null) {
- return(version);
+ return (version);
} else {
- return(version.get(attrName.getSuffix()));
+ return (version.get(attrName.getSuffix()));
}
case (ATTR_SERIAL):
if (attrName.getSuffix() == null) {
- return(serialNum);
+ return (serialNum);
} else {
- return(serialNum.get(attrName.getSuffix()));
+ return (serialNum.get(attrName.getSuffix()));
}
case (ATTR_ALGORITHM):
if (attrName.getSuffix() == null) {
- return(algId);
+ return (algId);
} else {
- return(algId.get(attrName.getSuffix()));
+ return (algId.get(attrName.getSuffix()));
}
case (ATTR_ISSUER):
if (attrName.getSuffix() == null) {
- return(issuer);
+ return (issuer);
} else {
- return(issuer.get(attrName.getSuffix()));
+ return (issuer.get(attrName.getSuffix()));
}
case (ATTR_VALIDITY):
if (attrName.getSuffix() == null) {
- return(interval);
+ return (interval);
} else {
- return(interval.get(attrName.getSuffix()));
+ return (interval.get(attrName.getSuffix()));
}
case (ATTR_SUBJECT):
if (attrName.getSuffix() == null) {
- return(subject);
+ return (subject);
} else {
- return(subject.get(attrName.getSuffix()));
+ return (subject.get(attrName.getSuffix()));
}
case (ATTR_KEY):
if (attrName.getSuffix() == null) {
- return(pubKey);
+ return (pubKey);
} else {
- return(pubKey.get(attrName.getSuffix()));
+ return (pubKey.get(attrName.getSuffix()));
}
case (ATTR_ISSUER_ID):
if (attrName.getSuffix() == null) {
- return(issuerUniqueId);
+ return (issuerUniqueId);
} else {
if (issuerUniqueId == null)
return null;
else
- return(issuerUniqueId.get(attrName.getSuffix()));
+ return (issuerUniqueId.get(attrName.getSuffix()));
}
case (ATTR_SUBJECT_ID):
if (attrName.getSuffix() == null) {
- return(subjectUniqueId);
+ return (subjectUniqueId);
} else {
if (subjectUniqueId == null)
return null;
else
- return(subjectUniqueId.get(attrName.getSuffix()));
+ return (subjectUniqueId.get(attrName.getSuffix()));
}
case (ATTR_EXTENSIONS):
if (attrName.getSuffix() == null) {
- return(extensions);
+ return (extensions);
} else {
if (extensions == null)
return null;
else
- return(extensions.get(attrName.getSuffix()));
+ return (extensions.get(attrName.getSuffix()));
}
}
return null;
@@ -672,9 +672,9 @@ public class X509CertInfo implements CertAttrSet, Serializable {
* This routine unmarshals the certificate information.
*/
private void parse(DerValue val)
- throws CertificateParsingException, IOException {
- DerInputStream in;
- DerValue tmp;
+ throws CertificateParsingException, IOException {
+ DerInputStream in;
+ DerValue tmp;
if (val.tag != DerValue.tag_Sequence) {
throw new CertificateParsingException("signed fields invalid");
@@ -685,11 +685,11 @@ public class X509CertInfo implements CertAttrSet, Serializable {
// Version
tmp = in.getDerValue();
- if (tmp.isContextSpecific((byte)0)) {
+ if (tmp.isContextSpecific((byte) 0)) {
version = new CertificateVersion(tmp);
tmp = in.getDerValue();
}
-
+
// Serial number ... an integer
serialNum = new CertificateSerialNumber(tmp);
@@ -699,7 +699,7 @@ public class X509CertInfo implements CertAttrSet, Serializable {
// Issuer name
issuer = new CertificateIssuerName(in);
- // validity: SEQUENCE { start date, end date }
+ // validity: SEQUENCE { start date, end date }
interval = new CertificateValidity(in);
// subject name
@@ -711,7 +711,7 @@ public class X509CertInfo implements CertAttrSet, Serializable {
// If more data available, make sure version is not v1.
if (in.available() != 0) {
if (version.compare(CertificateVersion.V1) == 0) {
- throw new CertificateParsingException("excess cert data");
+ throw new CertificateParsingException("excess cert data");
}
} else {
return;
@@ -719,19 +719,19 @@ public class X509CertInfo implements CertAttrSet, Serializable {
// Get the issuerUniqueId if present
tmp = in.getDerValue();
- if (tmp.isContextSpecific((byte)1)) {
+ if (tmp.isContextSpecific((byte) 1)) {
issuerUniqueId = new CertificateIssuerUniqueIdentity(tmp);
if (in.available() == 0) {
- return;
+ return;
}
tmp = in.getDerValue();
}
// Get the subjectUniqueId if present.
- if (tmp.isContextSpecific((byte)2)) {
+ if (tmp.isContextSpecific((byte) 2)) {
subjectUniqueId = new CertificateSubjectUniqueIdentity(tmp);
if (in.available() == 0) {
- return;
+ return;
}
tmp = in.getDerValue();
}
@@ -740,7 +740,7 @@ public class X509CertInfo implements CertAttrSet, Serializable {
if (version.compare(CertificateVersion.V3) != 0) {
throw new CertificateParsingException("excess cert data");
}
- if (tmp.isConstructed() && tmp.isContextSpecific((byte)3)) {
+ if (tmp.isConstructed() && tmp.isContextSpecific((byte) 3)) {
extensions = new CertificateExtensions(tmp.data);
}
}
@@ -749,7 +749,7 @@ public class X509CertInfo implements CertAttrSet, Serializable {
* Marshal the contents of a "raw" certificate into a DER sequence.
*/
private void emit(DerOutputStream out)
- throws CertificateException, IOException {
+ throws CertificateException, IOException {
DerOutputStream tmp = new DerOutputStream();
// version number, iff not V1
@@ -784,23 +784,22 @@ public class X509CertInfo implements CertAttrSet, Serializable {
}
/**
- * Serialization write ... X.509 certificates serialize as
- * themselves, and they're parsed when they get read back.
- * (Actually they serialize as some type data from the
- * serialization subsystem, then the cert data.)
+ * Serialization write ... X.509 certificates serialize as themselves, and
+ * they're parsed when they get read back. (Actually they serialize as some
+ * type data from the serialization subsystem, then the cert data.)
*/
private synchronized void writeObject(ObjectOutputStream stream)
- throws CertificateException, IOException {
+ throws CertificateException, IOException {
encode(stream);
}
/**
- * Serialization read ... X.509 certificates serialize as
- * themselves, and they're parsed when they get read back.
+ * Serialization read ... X.509 certificates serialize as themselves, and
+ * they're parsed when they get read back.
*/
private synchronized void readObject(ObjectInputStream stream)
- throws CertificateException, IOException {
- decode(stream);
+ throws CertificateException, IOException {
+ decode(stream);
}
/**
@@ -809,14 +808,14 @@ public class X509CertInfo implements CertAttrSet, Serializable {
private int attributeMap(String name) {
Integer num = map.get(name);
if (num == null) {
- return(0);
+ return (0);
}
- return(num.intValue());
+ return (num.intValue());
}
/**
* Set the version number of the certificate.
- *
+ *
* @param val the Object class value for the Extensions
* @exception CertificateException on invalid data.
*/
@@ -824,12 +823,12 @@ public class X509CertInfo implements CertAttrSet, Serializable {
if (!(val instanceof CertificateVersion)) {
throw new CertificateException("Version class type invalid.");
}
- version = (CertificateVersion)val;
+ version = (CertificateVersion) val;
}
/**
* Set the serial number of the certificate.
- *
+ *
* @param val the Object class value for the CertificateSerialNumber
* @exception CertificateException on invalid data.
*/
@@ -837,82 +836,82 @@ public class X509CertInfo implements CertAttrSet, Serializable {
if (!(val instanceof CertificateSerialNumber)) {
throw new CertificateException("SerialNumber class type invalid.");
}
- serialNum = (CertificateSerialNumber)val;
+ serialNum = (CertificateSerialNumber) val;
}
/**
* Set the algorithm id of the certificate.
- *
+ *
* @param val the Object class value for the AlgorithmId
* @exception CertificateException on invalid data.
*/
private void setAlgorithmId(Object val) throws CertificateException {
if (!(val instanceof CertificateAlgorithmId)) {
throw new CertificateException(
- "AlgorithmId class type invalid.");
+ "AlgorithmId class type invalid.");
}
- algId = (CertificateAlgorithmId)val;
+ algId = (CertificateAlgorithmId) val;
}
/**
* Set the issuer name of the certificate.
- *
+ *
* @param val the Object class value for the issuer
* @exception CertificateException on invalid data.
*/
private void setIssuer(Object val) throws CertificateException {
if (!(val instanceof CertificateIssuerName)) {
throw new CertificateException(
- "Issuer class type invalid.");
+ "Issuer class type invalid.");
}
- issuer = (CertificateIssuerName)val;
+ issuer = (CertificateIssuerName) val;
}
/**
* Set the validity interval of the certificate.
- *
+ *
* @param val the Object class value for the CertificateValidity
* @exception CertificateException on invalid data.
*/
private void setValidity(Object val) throws CertificateException {
if (!(val instanceof CertificateValidity)) {
throw new CertificateException(
- "CertificateValidity class type invalid.");
+ "CertificateValidity class type invalid.");
}
- interval = (CertificateValidity)val;
+ interval = (CertificateValidity) val;
}
/**
* Set the subject name of the certificate.
- *
+ *
* @param val the Object class value for the Subject
* @exception CertificateException on invalid data.
*/
private void setSubject(Object val) throws CertificateException {
if (!(val instanceof CertificateSubjectName)) {
throw new CertificateException(
- "Subject class type invalid.");
+ "Subject class type invalid.");
}
- subject = (CertificateSubjectName)val;
+ subject = (CertificateSubjectName) val;
}
/**
* Set the public key in the certificate.
- *
+ *
* @param val the Object class value for the PublicKey
* @exception CertificateException on invalid data.
*/
private void setKey(Object val) throws CertificateException {
if (!(val instanceof CertificateX509Key)) {
throw new CertificateException(
- "Key class type invalid.");
+ "Key class type invalid.");
}
- pubKey = (CertificateX509Key)val;
+ pubKey = (CertificateX509Key) val;
}
/**
* Set the Issuer Unique Identity in the certificate.
- *
+ *
* @param val the Object class value for the IssuerUniqueId
* @exception CertificateException
*/
@@ -922,14 +921,14 @@ public class X509CertInfo implements CertAttrSet, Serializable {
}
if (!(val instanceof CertificateIssuerUniqueIdentity)) {
throw new CertificateException(
- "IssuerUniqueId class type invalid.");
+ "IssuerUniqueId class type invalid.");
}
- issuerUniqueId = (CertificateIssuerUniqueIdentity)val;
+ issuerUniqueId = (CertificateIssuerUniqueIdentity) val;
}
/**
* Set the Subject Unique Identity in the certificate.
- *
+ *
* @param val the Object class value for the SubjectUniqueId
* @exception CertificateException
*/
@@ -939,14 +938,14 @@ public class X509CertInfo implements CertAttrSet, Serializable {
}
if (!(val instanceof CertificateSubjectUniqueIdentity)) {
throw new CertificateException(
- "SubjectUniqueId class type invalid.");
+ "SubjectUniqueId class type invalid.");
}
- subjectUniqueId = (CertificateSubjectUniqueIdentity)val;
+ subjectUniqueId = (CertificateSubjectUniqueIdentity) val;
}
/**
* Set the extensions in the certificate.
- *
+ *
* @param val the Object class value for the Extensions
* @exception CertificateException
*/
@@ -955,9 +954,9 @@ public class X509CertInfo implements CertAttrSet, Serializable {
throw new CertificateException("Invalid version");
}
if (!(val instanceof CertificateExtensions)) {
- throw new CertificateException(
- "Extensions class type invalid.");
+ throw new CertificateException(
+ "Extensions class type invalid.");
}
- extensions = (CertificateExtensions)val;
+ extensions = (CertificateExtensions) val;
}
}
diff --git a/pki/base/util/src/netscape/security/x509/X509ExtensionException.java b/pki/base/util/src/netscape/security/x509/X509ExtensionException.java
index 5b65b9b7..9908cda7 100644
--- a/pki/base/util/src/netscape/security/x509/X509ExtensionException.java
+++ b/pki/base/util/src/netscape/security/x509/X509ExtensionException.java
@@ -21,9 +21,8 @@ import java.security.GeneralSecurityException;
/**
* X.509 Extension Exception.
- *
- * @author Hemma Prafullchandra
- * 1.2
+ *
+ * @author Hemma Prafullchandra 1.2
*/
public class X509ExtensionException extends GeneralSecurityException {
@@ -33,19 +32,17 @@ public class X509ExtensionException extends GeneralSecurityException {
private static final long serialVersionUID = 8152491877676477910L;
/**
- * Constructs an X509ExtensionException with no detail message. A
- * detail message is a String that describes this particular
- * exception.
+ * Constructs an X509ExtensionException with no detail message. A detail
+ * message is a String that describes this particular exception.
*/
public X509ExtensionException() {
super();
}
/**
- * Constructs the exception with the specified detail
- * message. A detail message is a String that describes this
- * particular exception.
- *
+ * Constructs the exception with the specified detail message. A detail
+ * message is a String that describes this particular exception.
+ *
* @param message the detail message.
*/
public X509ExtensionException(String message) {
diff --git a/pki/base/util/src/netscape/security/x509/X509Key.java b/pki/base/util/src/netscape/security/x509/X509Key.java
index 81422ea4..72fa9879 100644
--- a/pki/base/util/src/netscape/security/x509/X509Key.java
+++ b/pki/base/util/src/netscape/security/x509/X509Key.java
@@ -36,20 +36,19 @@ import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
/**
- * Holds an X.509 key, for example a public key found in an X.509
- * certificate. Includes a description of the algorithm to be used
- * with the key; these keys normally are used as
- * "SubjectPublicKeyInfo".
- *
- * <P>While this class can represent any kind of X.509 key, it may be
- * desirable to provide subclasses which understand how to parse keying
- * data. For example, RSA public keys have two members, one for the
- * public modulus and one for the prime exponent. If such a class is
- * provided, it is used when parsing X.509 keys. If one is not provided,
- * the key still parses correctly.
- *
+ * Holds an X.509 key, for example a public key found in an X.509 certificate.
+ * Includes a description of the algorithm to be used with the key; these keys
+ * normally are used as "SubjectPublicKeyInfo".
+ *
+ * <P>
+ * While this class can represent any kind of X.509 key, it may be desirable to
+ * provide subclasses which understand how to parse keying data. For example,
+ * RSA public keys have two members, one for the public modulus and one for the
+ * prime exponent. If such a class is provided, it is used when parsing X.509
+ * keys. If one is not provided, the key still parses correctly.
+ *
* @version 1.74, 97/12/10
- * @author David Brownell
+ * @author David Brownell
*/
public class X509Key implements PublicKey {
@@ -66,207 +65,206 @@ public class X509Key implements PublicKey {
protected byte[] encodedKey;
/**
- * Default constructor. The key constructed must have its key
- * and algorithm initialized before it may be used, for example
- * by using <code>decode</code>.
+ * Default constructor. The key constructed must have its key and algorithm
+ * initialized before it may be used, for example by using
+ * <code>decode</code>.
*/
- public X509Key() { }
+ public X509Key() {
+ }
/*
- * Build and initialize as a "default" key. All X.509 key
- * data is stored and transmitted losslessly, but no knowledge
- * about this particular algorithm is available.
+ * Build and initialize as a "default" key. All X.509 key data is stored and
+ * transmitted losslessly, but no knowledge about this particular algorithm
+ * is available.
*/
public X509Key(AlgorithmId algid, byte[] key)
- throws InvalidKeyException {
- this.algid = algid;
- this.key = key;
- encode();
+ throws InvalidKeyException {
+ this.algid = algid;
+ this.key = key;
+ encode();
}
/**
- * Construct X.509 subject public key from a DER value. If
- * the runtime environment is configured with a specific class for
- * this kind of key, a subclass is returned. Otherwise, a generic
- * X509Key object is returned.
+ * Construct X.509 subject public key from a DER value. If the runtime
+ * environment is configured with a specific class for this kind of key, a
+ * subclass is returned. Otherwise, a generic X509Key object is returned.
+ *
+ * <P>
+ * This mechanism gurantees that keys (and algorithms) may be freely
+ * manipulated and transferred, without risk of losing information. Also,
+ * when a key (or algorithm) needs some special handling, that specific need
+ * can be accomodated.
*
- * <P>This mechanism gurantees that keys (and algorithms) may be
- * freely manipulated and transferred, without risk of losing
- * information. Also, when a key (or algorithm) needs some special
- * handling, that specific need can be accomodated.
- *
* @param in the DER-encoded SubjectPublicKeyInfo value
* @exception IOException on data format errors
*/
- public static X509Key parse(DerValue in) throws IOException
- {
- AlgorithmId algorithm;
- X509Key subjectKey;
+ public static X509Key parse(DerValue in) throws IOException {
+ AlgorithmId algorithm;
+ X509Key subjectKey;
- if (in.tag != DerValue.tag_Sequence)
- throw new IOException("corrupt subject key");
+ if (in.tag != DerValue.tag_Sequence)
+ throw new IOException("corrupt subject key");
- algorithm = AlgorithmId.parse(in.data.getDerValue ());
- try {
- subjectKey = buildX509Key(algorithm, in.data.getBitString ());
+ algorithm = AlgorithmId.parse(in.data.getDerValue());
+ try {
+ subjectKey = buildX509Key(algorithm, in.data.getBitString());
- } catch (InvalidKeyException e) {
- throw new IOException("subject key, " + e.getMessage());
- }
+ } catch (InvalidKeyException e) {
+ throw new IOException("subject key, " + e.getMessage());
+ }
- if (in.data.available () != 0)
- throw new IOException ("excess subject key");
- return subjectKey;
+ if (in.data.available() != 0)
+ throw new IOException("excess subject key");
+ return subjectKey;
}
/**
- * Parse the key bits. This may be redefined by subclasses to take
- * advantage of structure within the key. For example, RSA public
- * keys encapsulate two unsigned integers (modulus and exponent) as
- * DER values within the <code>key</code> bits; Diffie-Hellman and
- * DSS/DSA keys encapsulate a single unsigned integer.
- *
- * <P>This function is called when creating X.509 SubjectPublicKeyInfo
- * values using the X509Key member functions, such as <code>parse</code>
- * and <code>decode</code>.
- *
+ * Parse the key bits. This may be redefined by subclasses to take advantage
+ * of structure within the key. For example, RSA public keys encapsulate two
+ * unsigned integers (modulus and exponent) as DER values within the
+ * <code>key</code> bits; Diffie-Hellman and DSS/DSA keys encapsulate a
+ * single unsigned integer.
+ *
+ * <P>
+ * This function is called when creating X.509 SubjectPublicKeyInfo values
+ * using the X509Key member functions, such as <code>parse</code> and
+ * <code>decode</code>.
+ *
* @exception IOException on parsing errors.
* @exception InvalidKeyException on invalid key encodings.
*/
protected void parseKeyBits() throws IOException, InvalidKeyException {
- encode();
+ encode();
}
/*
- * Factory interface, building the kind of key associated with this
- * specific algorithm ID or else returning this generic base class.
- * See the description above.
+ * Factory interface, building the kind of key associated with this specific
+ * algorithm ID or else returning this generic base class. See the
+ * description above.
*/
static X509Key buildX509Key(AlgorithmId algid, byte[] key)
- throws IOException, InvalidKeyException
- {
- /*
- * Use the algid and key parameters to produce the ASN.1 encoding
- * of the key, which will then be used as the input to the
- * key factory.
- */
- DerOutputStream x509EncodedKeyStream = new DerOutputStream();
- encode(x509EncodedKeyStream, algid, key);
- X509EncodedKeySpec x509KeySpec
- = new X509EncodedKeySpec(x509EncodedKeyStream.toByteArray());
-
- try {
- // Instantiate the key factory of the appropriate algorithm
- KeyFactory keyFac = null;
- if (Security.getProvider("Mozilla-JSS") == null) {
- keyFac = KeyFactory.getInstance(algid.getName());
- } else {
- keyFac = KeyFactory.getInstance(algid.getName(),
- "Mozilla-JSS");
+ throws IOException, InvalidKeyException {
+ /*
+ * Use the algid and key parameters to produce the ASN.1 encoding of the
+ * key, which will then be used as the input to the key factory.
+ */
+ DerOutputStream x509EncodedKeyStream = new DerOutputStream();
+ encode(x509EncodedKeyStream, algid, key);
+ X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(x509EncodedKeyStream.toByteArray());
+
+ try {
+ // Instantiate the key factory of the appropriate algorithm
+ KeyFactory keyFac = null;
+ if (Security.getProvider("Mozilla-JSS") == null) {
+ keyFac = KeyFactory.getInstance(algid.getName());
+ } else {
+ keyFac = KeyFactory.getInstance(algid.getName(),
+ "Mozilla-JSS");
+ }
+
+ // Generate the public key
+ PublicKey pubKey = keyFac.generatePublic(x509KeySpec);
+
+ if (pubKey instanceof X509Key) {
+ /*
+ * Return specialized X509Key, where the structure within the
+ * key has been parsed
+ */
+ return (X509Key) pubKey;
+ }
+ } catch (NoSuchAlgorithmException e) {
+ // Return generic X509Key with opaque key data (see below)
+ } catch (InvalidKeySpecException e) {
+ throw new InvalidKeyException(e.toString());
+ } catch (Exception e) {
+ throw new InvalidKeyException(e.toString());
+ }
+
+ /*
+ * Try again using JDK1.1-style for backwards compatibility.
+ */
+ String classname = "";
+ try {
+ Properties props;
+ String keytype;
+ Provider sunProvider;
+
+ sunProvider = Security.getProvider("SUN");
+ if (sunProvider == null)
+ throw new InstantiationException();
+ classname = sunProvider.getProperty("PublicKey.X.509." +
+ algid.getName());
+ if (classname == null) {
+ throw new InstantiationException();
}
-
- // Generate the public key
- PublicKey pubKey = keyFac.generatePublic(x509KeySpec);
-
- if (pubKey instanceof X509Key) {
- /*
- * Return specialized X509Key, where the structure within the
- * key has been parsed
- */
- return (X509Key)pubKey;
- }
- } catch (NoSuchAlgorithmException e) {
- // Return generic X509Key with opaque key data (see below)
- } catch (InvalidKeySpecException e) {
- throw new InvalidKeyException(e.toString());
- } catch (Exception e) {
- throw new InvalidKeyException(e.toString());
- }
-
- /*
- * Try again using JDK1.1-style for backwards compatibility.
- */
- String classname = "";
- try {
- Properties props;
- String keytype;
- Provider sunProvider;
-
- sunProvider = Security.getProvider("SUN");
- if (sunProvider == null)
- throw new InstantiationException();
- classname = sunProvider.getProperty("PublicKey.X.509." +
- algid.getName());
- if (classname == null) {
- throw new InstantiationException();
- }
-
- Class<?> keyClass = Class.forName(classname);
- Object inst;
- X509Key result;
-
- inst = keyClass.newInstance();
- if (inst instanceof X509Key) {
- result = (X509Key) inst;
- result.algid = algid;
- result.key = key;
- result.parseKeyBits();
- return result;
- }
- } catch (ClassNotFoundException e) {
- } catch (InstantiationException e) {
- } catch (IllegalAccessException e) {
- // this should not happen.
- throw new IOException (classname + " [internal error]");
- }
-
- X509Key result = new X509Key();
- result.algid = algid;
- result.key = key;
- return result;
+
+ Class<?> keyClass = Class.forName(classname);
+ Object inst;
+ X509Key result;
+
+ inst = keyClass.newInstance();
+ if (inst instanceof X509Key) {
+ result = (X509Key) inst;
+ result.algid = algid;
+ result.key = key;
+ result.parseKeyBits();
+ return result;
+ }
+ } catch (ClassNotFoundException e) {
+ } catch (InstantiationException e) {
+ } catch (IllegalAccessException e) {
+ // this should not happen.
+ throw new IOException(classname + " [internal error]");
+ }
+
+ X509Key result = new X509Key();
+ result.algid = algid;
+ result.key = key;
+ return result;
}
/**
* Returns the algorithm to be used with this key.
*/
- public String getAlgorithm() {
- return algid.getName();
+ public String getAlgorithm() {
+ return algid.getName();
}
/**
* Returns the algorithm ID to be used with this key.
*/
- public AlgorithmId getAlgorithmId () { return algid; }
+ public AlgorithmId getAlgorithmId() {
+ return algid;
+ }
/**
* Encode SubjectPublicKeyInfo sequence on the DER output stream.
- *
+ *
* @exception IOException on encoding errors.
*/
- public final void encode(DerOutputStream out) throws IOException
- {
- encode(out, this.algid, this.key);
+ public final void encode(DerOutputStream out) throws IOException {
+ encode(out, this.algid, this.key);
}
/**
* Returns the DER-encoded form of the key as a byte array.
*/
public synchronized byte[] getEncoded() {
- byte[] result = null;
- try {
- result = encode();
- } catch (InvalidKeyException e) {
- }
- return result;
+ byte[] result = null;
+ try {
+ result = encode();
+ } catch (InvalidKeyException e) {
+ }
+ return result;
}
/**
* Returns the format for this key: "X.509"
*/
public String getFormat() {
- return "X.509";
+ return "X.509";
}
-
+
/**
* Returns the raw key as a byte array
*/
@@ -276,242 +274,241 @@ public class X509Key implements PublicKey {
/**
* Returns the DER-encoded form of the key as a byte array.
- *
+ *
* @exception InvalidKeyException on encoding errors.
*/
public byte[] encode() throws InvalidKeyException {
- if (encodedKey == null) {
- try {
- DerOutputStream out;
-
- out = new DerOutputStream ();
- encode (out);
- encodedKey = out.toByteArray();
-
- } catch (IOException e) {
- throw new InvalidKeyException ("IOException : " +
- e.getMessage());
- }
- }
- return copyEncodedKey(encodedKey);
+ if (encodedKey == null) {
+ try {
+ DerOutputStream out;
+
+ out = new DerOutputStream();
+ encode(out);
+ encodedKey = out.toByteArray();
+
+ } catch (IOException e) {
+ throw new InvalidKeyException("IOException : " +
+ e.getMessage());
+ }
+ }
+ return copyEncodedKey(encodedKey);
}
/*
* Returns a printable representation of the key
*/
- public String toString ()
- {
- netscape.security.util.PrettyPrintFormat pp =
- new netscape.security.util.PrettyPrintFormat(" ", 20);
- String keybits = pp.toHexString(key);
-
- return "algorithm = " + algid.toString ()
- + ", unparsed keybits = \n" + keybits;
+ public String toString() {
+ netscape.security.util.PrettyPrintFormat pp =
+ new netscape.security.util.PrettyPrintFormat(" ", 20);
+ String keybits = pp.toHexString(key);
+
+ return "algorithm = " + algid.toString()
+ + ", unparsed keybits = \n" + keybits;
}
- /**
- * Initialize an X509Key object from an input stream. The data on that
- * input stream must be encoded using DER, obeying the X.509
- * <code>SubjectPublicKeyInfo</code> format. That is, the data is a
- * sequence consisting of an algorithm ID and a bit string which holds
- * the key. (That bit string is often used to encapsulate another DER
- * encoded sequence.)
- *
- * <P>Subclasses should not normally redefine this method; they should
- * instead provide a <code>parseKeyBits</code> method to parse any
- * fields inside the <code>key</code> member.
- *
- * <P>The exception to this rule is that since private keys need not
- * be encoded using the X.509 <code>SubjectPublicKeyInfo</code> format,
- * private keys may override this method, <code>encode</code>, and
- * of course <code>getFormat</code>.
- *
- * @param in an input stream with a DER-encoded X.509
- * SubjectPublicKeyInfo value
+ /**
+ * Initialize an X509Key object from an input stream. The data on that input
+ * stream must be encoded using DER, obeying the X.509
+ * <code>SubjectPublicKeyInfo</code> format. That is, the data is a sequence
+ * consisting of an algorithm ID and a bit string which holds the key. (That
+ * bit string is often used to encapsulate another DER encoded sequence.)
+ *
+ * <P>
+ * Subclasses should not normally redefine this method; they should instead
+ * provide a <code>parseKeyBits</code> method to parse any fields inside the
+ * <code>key</code> member.
+ *
+ * <P>
+ * The exception to this rule is that since private keys need not be encoded
+ * using the X.509 <code>SubjectPublicKeyInfo</code> format, private keys
+ * may override this method, <code>encode</code>, and of course
+ * <code>getFormat</code>.
+ *
+ * @param in an input stream with a DER-encoded X.509 SubjectPublicKeyInfo
+ * value
* @exception InvalidKeyException on parsing errors.
*/
public void decode(InputStream in)
- throws InvalidKeyException
- {
- DerValue val;
-
- try {
- val = new DerValue (in);
- if (val.tag != DerValue.tag_Sequence)
- throw new InvalidKeyException ("invalid key format");
-
- algid = AlgorithmId.parse (val.data.getDerValue ());
- key = val.data.getBitString ();
- parseKeyBits ();
- if (val.data.available () != 0)
- throw new InvalidKeyException ("excess key data");
-
- } catch (IOException e) {
- // e.printStackTrace ();
- throw new InvalidKeyException("IOException : " +
- e.getMessage());
- }
+ throws InvalidKeyException {
+ DerValue val;
+
+ try {
+ val = new DerValue(in);
+ if (val.tag != DerValue.tag_Sequence)
+ throw new InvalidKeyException("invalid key format");
+
+ algid = AlgorithmId.parse(val.data.getDerValue());
+ key = val.data.getBitString();
+ parseKeyBits();
+ if (val.data.available() != 0)
+ throw new InvalidKeyException("excess key data");
+
+ } catch (IOException e) {
+ // e.printStackTrace ();
+ throw new InvalidKeyException("IOException : " +
+ e.getMessage());
+ }
}
public void decode(byte[] encodedKey) throws InvalidKeyException {
- decode(new ByteArrayInputStream(encodedKey));
+ decode(new ByteArrayInputStream(encodedKey));
}
/**
- * Serialization write ... X.509 keys serialize as
- * themselves, and they're parsed when they get read back.
+ * Serialization write ... X.509 keys serialize as themselves, and they're
+ * parsed when they get read back.
*/
private synchronized void
- writeObject (java.io.ObjectOutputStream stream)
- throws IOException {
- stream.write(getEncoded());
+ writeObject(java.io.ObjectOutputStream stream)
+ throws IOException {
+ stream.write(getEncoded());
}
/**
- * Serialization read ... X.509 keys serialize as
- * themselves, and they're parsed when they get read back.
+ * Serialization read ... X.509 keys serialize as themselves, and they're
+ * parsed when they get read back.
*/
private synchronized void
- readObject (ObjectInputStream stream)
- throws IOException {
+ readObject(ObjectInputStream stream)
+ throws IOException {
- try {
- decode(stream);
+ try {
+ decode(stream);
- } catch (InvalidKeyException e) {
- e.printStackTrace();
- throw new IOException("deserialized key is invalid: " +
- e.getMessage());
- }
+ } catch (InvalidKeyException e) {
+ e.printStackTrace();
+ throw new IOException("deserialized key is invalid: " +
+ e.getMessage());
+ }
}
public boolean equals(Object object) {
- if (this == object) {
- return true;
- }
-
- if (object instanceof Key) {
- Key key = (Key)object;
-
- byte[] b1;
- if (encodedKey != null) {
- b1 = encodedKey;
- } else {
- b1 = getEncoded();
- }
- byte[] b2 = key.getEncoded();
-
- return java.security.MessageDigest.isEqual(b1, b2);
- }
-
- return false;
+ if (this == object) {
+ return true;
+ }
+
+ if (object instanceof Key) {
+ Key key = (Key) object;
+
+ byte[] b1;
+ if (encodedKey != null) {
+ b1 = encodedKey;
+ } else {
+ b1 = getEncoded();
+ }
+ byte[] b2 = key.getEncoded();
+
+ return java.security.MessageDigest.isEqual(b1, b2);
+ }
+
+ return false;
}
-
+
/**
- * Calculates a hash code value for the object. Objects
- * which are equal will also have the same hashcode.
+ * Calculates a hash code value for the object. Objects which are equal will
+ * also have the same hashcode.
*/
public int hashCode() {
int retval = 0;
- byte[] b1 = getEncoded();
+ byte[] b1 = getEncoded();
for (int i = 1; i < b1.length; i++) {
retval += b1[i] * i;
}
- return(retval);
+ return (retval);
}
/*
* Make a copy of the encoded key.
*/
private byte[] copyEncodedKey(byte[] encodedKey) {
- int len = encodedKey.length;
- byte[] copy = new byte[len];
- System.arraycopy(encodedKey, 0, copy, 0, len);
- return copy;
+ int len = encodedKey.length;
+ byte[] copy = new byte[len];
+ System.arraycopy(encodedKey, 0, copy, 0, len);
+ return copy;
}
/*
* Produce SubjectPublicKey encoding from algorithm id and key material.
*/
static void encode(DerOutputStream out, AlgorithmId algid, byte[] key)
- throws IOException {
- DerOutputStream tmp = new DerOutputStream();
- algid.encode(tmp);
- tmp.putBitString(key);
- out.write(DerValue.tag_Sequence, tmp);
+ throws IOException {
+ DerOutputStream tmp = new DerOutputStream();
+ algid.encode(tmp);
+ tmp.putBitString(key);
+ out.write(DerValue.tag_Sequence, tmp);
}
- /*
- * parsePublicKey returns a PublicKey for use with package JSS from within netscape.security.*.
- * This function provide an interim solution for migrating from using the netscape.security.* package
- * to using the JSS package.
+
+ /*
+ * parsePublicKey returns a PublicKey for use with package JSS from within
+ * netscape.security.*. This function provide an interim solution for
+ * migrating from using the netscape.security.* package to using the JSS
+ * package.
*/
-
- public static PublicKey parsePublicKey(DerValue in) throws IOException
- {
- AlgorithmId algorithm;
- PublicKey subjectKey;
-
- if (in.tag != DerValue.tag_Sequence)
- throw new IOException("corrupt subject key");
-
- algorithm = AlgorithmId.parse(in.data.getDerValue ());
- try {
- subjectKey = buildPublicKey(algorithm, in.data.getBitString ());
-
- } catch (InvalidKeyException e) {
- throw new IOException("subject key, " + e.getMessage());
- }
-
- if (in.data.available () != 0)
- throw new IOException ("excess subject key");
- return subjectKey;
- }
- /* buildPublicKey returns a PublicKey for use with the JSS package from within netscape.security.*.
- * This function provide an interim solution for migrating from using the netscape.security.* package
- * to using the JSS package.
- */
- static PublicKey buildPublicKey(AlgorithmId algid, byte[] key)
- throws IOException, InvalidKeyException
- {
- /*
- * Use the algid and key parameters to produce the ASN.1 encoding
- * of the key, which will then be used as the input to the
- * key factory.
- */
- DerOutputStream x509EncodedKeyStream = new DerOutputStream();
- encode(x509EncodedKeyStream, algid, key);
- X509EncodedKeySpec x509KeySpec
- = new X509EncodedKeySpec(x509EncodedKeyStream.toByteArray());
-
- try {
- // Instantiate the key factory of the appropriate algorithm
- KeyFactory keyFac = null;
- if (Security.getProvider("Mozilla-JSS") == null) {
- keyFac = KeyFactory.getInstance(algid.getName());
- } else {
- keyFac = KeyFactory.getInstance(algid.getName(),
- "Mozilla-JSS");
- }
-
- // Generate the public key
- PublicKey pubKey = keyFac.generatePublic(x509KeySpec);
-
- /*
- * Return specialized X509Key, where the structure within the
- * key has been parsed
- */
- return pubKey;
- } catch (NoSuchAlgorithmException e) {
- // Return generic X509Key with opaque key data (see below)
- throw new InvalidKeyException(e.toString());
- } catch (InvalidKeySpecException e) {
- throw new InvalidKeyException(e.toString());
- } catch (Exception e) {
- throw new InvalidKeyException(e.toString());
- }
-
- }
+ public static PublicKey parsePublicKey(DerValue in) throws IOException {
+ AlgorithmId algorithm;
+ PublicKey subjectKey;
+
+ if (in.tag != DerValue.tag_Sequence)
+ throw new IOException("corrupt subject key");
+
+ algorithm = AlgorithmId.parse(in.data.getDerValue());
+ try {
+ subjectKey = buildPublicKey(algorithm, in.data.getBitString());
+
+ } catch (InvalidKeyException e) {
+ throw new IOException("subject key, " + e.getMessage());
+ }
+
+ if (in.data.available() != 0)
+ throw new IOException("excess subject key");
+ return subjectKey;
+ }
+
+ /*
+ * buildPublicKey returns a PublicKey for use with the JSS package from
+ * within netscape.security.*. This function provide an interim solution for
+ * migrating from using the netscape.security.* package to using the JSS
+ * package.
+ */
+ static PublicKey buildPublicKey(AlgorithmId algid, byte[] key)
+ throws IOException, InvalidKeyException {
+ /*
+ * Use the algid and key parameters to produce the ASN.1 encoding of the
+ * key, which will then be used as the input to the key factory.
+ */
+ DerOutputStream x509EncodedKeyStream = new DerOutputStream();
+ encode(x509EncodedKeyStream, algid, key);
+ X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(x509EncodedKeyStream.toByteArray());
+
+ try {
+ // Instantiate the key factory of the appropriate algorithm
+ KeyFactory keyFac = null;
+ if (Security.getProvider("Mozilla-JSS") == null) {
+ keyFac = KeyFactory.getInstance(algid.getName());
+ } else {
+ keyFac = KeyFactory.getInstance(algid.getName(),
+ "Mozilla-JSS");
+ }
+
+ // Generate the public key
+ PublicKey pubKey = keyFac.generatePublic(x509KeySpec);
+
+ /*
+ * Return specialized X509Key, where the structure within the key
+ * has been parsed
+ */
+ return pubKey;
+ } catch (NoSuchAlgorithmException e) {
+ // Return generic X509Key with opaque key data (see below)
+ throw new InvalidKeyException(e.toString());
+ } catch (InvalidKeySpecException e) {
+ throw new InvalidKeyException(e.toString());
+ } catch (Exception e) {
+ throw new InvalidKeyException(e.toString());
+ }
+
+ }
}
diff --git a/pki/base/util/test/com/netscape/security/extensions/GenericASN1ExtensionTest.java b/pki/base/util/test/com/netscape/security/extensions/GenericASN1ExtensionTest.java
index cc2f24c3..5364931d 100644
--- a/pki/base/util/test/com/netscape/security/extensions/GenericASN1ExtensionTest.java
+++ b/pki/base/util/test/com/netscape/security/extensions/GenericASN1ExtensionTest.java
@@ -12,7 +12,7 @@ import org.junit.Test;
public class GenericASN1ExtensionTest {
- //@Test
+ // @Test
public void testConstructorArgs() throws Exception {
String name1 = "testExtension1";
String oid1 = "1.2.3.4";
@@ -44,7 +44,7 @@ public class GenericASN1ExtensionTest {
GenericASN1Extension extension1 = new GenericASN1Extension(config);
Assert.assertEquals(name1, extension1.getName());
- //Assert.assertNotNull(OIDMap.getClass(name1));
+ // Assert.assertNotNull(OIDMap.getClass(name1));
String name2 = "testExtension2";
String oid2 = "2.4.6.8";
@@ -53,11 +53,11 @@ public class GenericASN1ExtensionTest {
GenericASN1Extension extension2 = new GenericASN1Extension(config);
Assert.assertEquals(name2, extension2.getName());
- //Assert.assertNotNull(OIDMap.getClass(name2));
+ // Assert.assertNotNull(OIDMap.getClass(name2));
OutputStream outputStream = new ByteArrayOutputStream();
- extension1.encode(outputStream );
- extension2.encode(outputStream );
-
+ extension1.encode(outputStream);
+ extension2.encode(outputStream);
+
}
@Test
@@ -66,7 +66,7 @@ public class GenericASN1ExtensionTest {
GenericASN1Extension extension = new GenericASN1Extension(true, value);
OutputStream outputStream = new ByteArrayOutputStream();
- extension.encode(outputStream );
-
+ extension.encode(outputStream);
+
}
}
diff --git a/pki/base/util/test/com/netscape/security/util/BMPStringTest.java b/pki/base/util/test/com/netscape/security/util/BMPStringTest.java
index e1dcb659..f3414f22 100644
--- a/pki/base/util/test/com/netscape/security/util/BMPStringTest.java
+++ b/pki/base/util/test/com/netscape/security/util/BMPStringTest.java
@@ -13,13 +13,13 @@ public class BMPStringTest {
public void testEncodingEmptyString() throws Exception {
String string = "";
- System.out.println("Encoding: ["+string+"]");
+ System.out.println("Encoding: [" + string + "]");
byte[] expected = JSSUtil.encode(tag, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = StringTestUtil.encode(tag, string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -30,12 +30,12 @@ public class BMPStringTest {
String input = "";
byte[] data = JSSUtil.encode(tag, input);
- System.out.println("Decoding: ["+StringTestUtil.toString(data)+"]");
+ System.out.println("Decoding: [" + StringTestUtil.toString(data) + "]");
- System.out.println(" - expected: ["+input+"]");
+ System.out.println(" - expected: [" + input + "]");
String output = StringTestUtil.decode(tag, data);
- System.out.println(" - actual : ["+output+"]");
+ System.out.println(" - actual : [" + output + "]");
Assert.assertEquals(input, output);
}
@@ -44,16 +44,16 @@ public class BMPStringTest {
public void testEncodingPrintableCharacters() throws Exception {
String string = StringTestUtil.PRINTABLE_CHARS;
- System.out.println("Encoding: ["+string+"]");
+ System.out.println("Encoding: [" + string + "]");
byte[] expected = JSSUtil.encode(tag, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = StringTestUtil.encode(tag, string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
actual = StringTestUtil.normalizeUnicode(actual);
- System.out.println(" - norm. : "+StringTestUtil.toString(actual));
+ System.out.println(" - norm. : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -64,12 +64,12 @@ public class BMPStringTest {
String input = StringTestUtil.PRINTABLE_CHARS;
byte[] data = JSSUtil.encode(tag, input);
- System.out.println("Decoding: ["+StringTestUtil.toString(data)+"]");
+ System.out.println("Decoding: [" + StringTestUtil.toString(data) + "]");
- System.out.println(" - expected: ["+input+"]");
+ System.out.println(" - expected: [" + input + "]");
String output = StringTestUtil.decode(tag, data);
- System.out.println(" - actual : ["+output+"]");
+ System.out.println(" - actual : [" + output + "]");
Assert.assertEquals(input, output);
}
@@ -78,16 +78,16 @@ public class BMPStringTest {
public void testEncodingNonPrintableCharacters() throws Exception {
String string = StringTestUtil.NON_PRINTABLE_CHARS;
- System.out.println("Encoding: ["+string+"]");
+ System.out.println("Encoding: [" + string + "]");
byte[] expected = JSSUtil.encode(tag, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = StringTestUtil.encode(tag, string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
actual = StringTestUtil.normalizeUnicode(actual);
- System.out.println(" - norm. : "+StringTestUtil.toString(actual));
+ System.out.println(" - norm. : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -98,12 +98,12 @@ public class BMPStringTest {
String input = StringTestUtil.NON_PRINTABLE_CHARS;
byte[] data = JSSUtil.encode(tag, input);
- System.out.println("Decoding: ["+StringTestUtil.toString(data)+"]");
+ System.out.println("Decoding: [" + StringTestUtil.toString(data) + "]");
- System.out.println(" - expected: ["+input+"]");
+ System.out.println(" - expected: [" + input + "]");
String output = StringTestUtil.decode(tag, data);
- System.out.println(" - actual : ["+output+"]");
+ System.out.println(" - actual : [" + output + "]");
Assert.assertEquals(input, output);
}
@@ -112,16 +112,16 @@ public class BMPStringTest {
public void testEncodingControlCharacters() throws Exception {
String string = StringTestUtil.CONTROL_CHARS;
- System.out.println("Encoding: ["+StringTestUtil.toString(string.getBytes())+"]");
+ System.out.println("Encoding: [" + StringTestUtil.toString(string.getBytes()) + "]");
byte[] expected = JSSUtil.encode(tag, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = StringTestUtil.encode(tag, string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
actual = StringTestUtil.normalizeUnicode(actual);
- System.out.println(" - norm. : "+StringTestUtil.toString(actual));
+ System.out.println(" - norm. : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -132,12 +132,12 @@ public class BMPStringTest {
String input = StringTestUtil.CONTROL_CHARS;
byte[] data = JSSUtil.encode(tag, input);
- System.out.println("Decoding: ["+StringTestUtil.toString(data)+"]");
+ System.out.println("Decoding: [" + StringTestUtil.toString(data) + "]");
- System.out.println(" - expected: ["+StringTestUtil.toString(input.getBytes())+"]");
+ System.out.println(" - expected: [" + StringTestUtil.toString(input.getBytes()) + "]");
String output = StringTestUtil.decode(tag, data);
- System.out.println(" - actual : ["+StringTestUtil.toString(output.getBytes())+"]");
+ System.out.println(" - actual : [" + StringTestUtil.toString(output.getBytes()) + "]");
Assert.assertEquals(input, output);
}
@@ -146,16 +146,16 @@ public class BMPStringTest {
public void testEncodingMultibyteCharacters() throws Exception {
String string = StringTestUtil.MULTIBYTE_CHARS;
- System.out.println("Encoding: ["+string+"]");
+ System.out.println("Encoding: [" + string + "]");
byte[] expected = JSSUtil.encode(tag, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = StringTestUtil.encode(tag, string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
actual = StringTestUtil.normalizeUnicode(actual);
- System.out.println(" - norm. : "+StringTestUtil.toString(actual));
+ System.out.println(" - norm. : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -166,12 +166,12 @@ public class BMPStringTest {
String input = StringTestUtil.MULTIBYTE_CHARS;
byte[] data = JSSUtil.encode(tag, input);
- System.out.println("Decoding: ["+StringTestUtil.toString(data)+"]");
+ System.out.println("Decoding: [" + StringTestUtil.toString(data) + "]");
- System.out.println(" - expected: ["+StringTestUtil.toString(input.getBytes())+"]");
+ System.out.println(" - expected: [" + StringTestUtil.toString(input.getBytes()) + "]");
String output = StringTestUtil.decode(tag, data);
- System.out.println(" - actual : ["+StringTestUtil.toString(output.getBytes())+"]");
+ System.out.println(" - actual : [" + StringTestUtil.toString(output.getBytes()) + "]");
Assert.assertEquals(input, output);
}
diff --git a/pki/base/util/test/com/netscape/security/util/IA5StringTest.java b/pki/base/util/test/com/netscape/security/util/IA5StringTest.java
index f101e549..73131d42 100644
--- a/pki/base/util/test/com/netscape/security/util/IA5StringTest.java
+++ b/pki/base/util/test/com/netscape/security/util/IA5StringTest.java
@@ -15,13 +15,13 @@ public class IA5StringTest {
public void testEncodingEmptyString() throws Exception {
String string = "";
- System.out.println("Encoding: ["+string+"]");
+ System.out.println("Encoding: [" + string + "]");
byte[] expected = JSSUtil.encode(tag, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = StringTestUtil.encode(tag, string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -32,12 +32,12 @@ public class IA5StringTest {
String input = "";
byte[] data = JSSUtil.encode(tag, input);
- System.out.println("Decoding: ["+StringTestUtil.toString(data)+"]");
+ System.out.println("Decoding: [" + StringTestUtil.toString(data) + "]");
- System.out.println(" - expected: ["+input+"]");
+ System.out.println(" - expected: [" + input + "]");
String output = StringTestUtil.decode(tag, data);
- System.out.println(" - actual : ["+output+"]");
+ System.out.println(" - actual : [" + output + "]");
Assert.assertEquals(input, output);
}
@@ -46,13 +46,13 @@ public class IA5StringTest {
public void testEncodingPrintableCharacters() throws Exception {
String string = StringTestUtil.PRINTABLE_CHARS;
- System.out.println("Encoding: ["+string+"]");
+ System.out.println("Encoding: [" + string + "]");
byte[] expected = JSSUtil.encode(tag, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = StringTestUtil.encode(tag, string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -63,12 +63,12 @@ public class IA5StringTest {
String input = StringTestUtil.PRINTABLE_CHARS;
byte[] data = JSSUtil.encode(tag, input);
- System.out.println("Decoding: ["+StringTestUtil.toString(data)+"]");
+ System.out.println("Decoding: [" + StringTestUtil.toString(data) + "]");
- System.out.println(" - expected: ["+input+"]");
+ System.out.println(" - expected: [" + input + "]");
String output = StringTestUtil.decode(tag, data);
- System.out.println(" - actual : ["+output+"]");
+ System.out.println(" - actual : [" + output + "]");
Assert.assertEquals(input, output);
}
@@ -77,13 +77,13 @@ public class IA5StringTest {
public void testEncodingNonPrintableCharacters() throws Exception {
String string = StringTestUtil.NON_PRINTABLE_CHARS;
- System.out.println("Encoding: ["+string+"]");
+ System.out.println("Encoding: [" + string + "]");
byte[] expected = JSSUtil.encode(tag, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = StringTestUtil.encode(tag, string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -94,12 +94,12 @@ public class IA5StringTest {
String input = StringTestUtil.NON_PRINTABLE_CHARS;
byte[] data = JSSUtil.encode(tag, input);
- System.out.println("Decoding: ["+StringTestUtil.toString(data)+"]");
+ System.out.println("Decoding: [" + StringTestUtil.toString(data) + "]");
- System.out.println(" - expected: ["+input+"]");
+ System.out.println(" - expected: [" + input + "]");
String output = StringTestUtil.decode(tag, data);
- System.out.println(" - actual : ["+output+"]");
+ System.out.println(" - actual : [" + output + "]");
Assert.assertEquals(input, output);
}
@@ -108,13 +108,13 @@ public class IA5StringTest {
public void testEncodingControlCharacters() throws Exception {
String string = StringTestUtil.CONTROL_CHARS;
- System.out.println("Encoding: ["+StringTestUtil.toString(string.getBytes())+"]");
+ System.out.println("Encoding: [" + StringTestUtil.toString(string.getBytes()) + "]");
byte[] expected = JSSUtil.encode(tag, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = StringTestUtil.encode(tag, string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -125,12 +125,12 @@ public class IA5StringTest {
String input = StringTestUtil.CONTROL_CHARS;
byte[] data = JSSUtil.encode(tag, input);
- System.out.println("Decoding: ["+StringTestUtil.toString(data)+"]");
+ System.out.println("Decoding: [" + StringTestUtil.toString(data) + "]");
- System.out.println(" - expected: ["+StringTestUtil.toString(input.getBytes())+"]");
+ System.out.println(" - expected: [" + StringTestUtil.toString(input.getBytes()) + "]");
String output = StringTestUtil.decode(tag, data);
- System.out.println(" - actual : ["+StringTestUtil.toString(output.getBytes())+"]");
+ System.out.println(" - actual : [" + StringTestUtil.toString(output.getBytes()) + "]");
Assert.assertEquals(input, output);
}
@@ -139,18 +139,18 @@ public class IA5StringTest {
public void testEncodingMultibyteCharacters() throws Exception {
String string = StringTestUtil.MULTIBYTE_CHARS;
- System.out.println("Encoding: ["+string+"]");
+ System.out.println("Encoding: [" + string + "]");
System.out.println(" - expected: IOException");
try {
byte[] actual = StringTestUtil.encode(tag, string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.fail();
} catch (Exception e) {
- System.out.println(" - actual : "+e.getClass().getSimpleName());
+ System.out.println(" - actual : " + e.getClass().getSimpleName());
Assert.assertTrue(e instanceof IOException);
}
}
@@ -161,18 +161,18 @@ public class IA5StringTest {
String input = StringTestUtil.MULTIBYTE_CHARS;
byte[] data = JSSUtil.encode(DerValue.tag_UTF8String, input);
- System.out.println("Decoding: ["+StringTestUtil.toString(data)+"]");
+ System.out.println("Decoding: [" + StringTestUtil.toString(data) + "]");
System.out.println(" - expected: IOException");
try {
String output = StringTestUtil.decode(tag, data);
- System.out.println(" - actual : ["+StringTestUtil.toString(output.getBytes())+"]");
+ System.out.println(" - actual : [" + StringTestUtil.toString(output.getBytes()) + "]");
Assert.fail();
} catch (Exception e) {
- System.out.println(" - actual : "+e.getClass().getSimpleName());
+ System.out.println(" - actual : " + e.getClass().getSimpleName());
Assert.assertTrue(e instanceof IOException);
}
}
diff --git a/pki/base/util/test/com/netscape/security/util/JSSUtil.java b/pki/base/util/test/com/netscape/security/util/JSSUtil.java
index abaab427..067de040 100644
--- a/pki/base/util/test/com/netscape/security/util/JSSUtil.java
+++ b/pki/base/util/test/com/netscape/security/util/JSSUtil.java
@@ -17,26 +17,26 @@ public class JSSUtil {
ASN1Value value;
switch (tag) {
- case DerValue.tag_BMPString:
- value = new BMPString(string);
- break;
- case DerValue.tag_IA5String:
- value = new IA5String(string);
- break;
- case DerValue.tag_PrintableString:
- value = new PrintableString(string);
- break;
- case DerValue.tag_T61String:
- value = new TeletexString(string);
- break;
- case DerValue.tag_UniversalString:
- value = new UniversalString(string);
- break;
- case DerValue.tag_UTF8String:
- value = new UTF8String(string);
- break;
- default:
- throw new Exception("Unsupported tag: "+tag);
+ case DerValue.tag_BMPString:
+ value = new BMPString(string);
+ break;
+ case DerValue.tag_IA5String:
+ value = new IA5String(string);
+ break;
+ case DerValue.tag_PrintableString:
+ value = new PrintableString(string);
+ break;
+ case DerValue.tag_T61String:
+ value = new TeletexString(string);
+ break;
+ case DerValue.tag_UniversalString:
+ value = new UniversalString(string);
+ break;
+ case DerValue.tag_UTF8String:
+ value = new UTF8String(string);
+ break;
+ default:
+ throw new Exception("Unsupported tag: " + tag);
}
return ASN1Util.encode(value);
}
diff --git a/pki/base/util/test/com/netscape/security/util/PrintableStringTest.java b/pki/base/util/test/com/netscape/security/util/PrintableStringTest.java
index 4d0bc2cb..194bc2f7 100644
--- a/pki/base/util/test/com/netscape/security/util/PrintableStringTest.java
+++ b/pki/base/util/test/com/netscape/security/util/PrintableStringTest.java
@@ -15,13 +15,13 @@ public class PrintableStringTest {
public void testEncodingEmptyString() throws Exception {
String string = "";
- System.out.println("Encoding: ["+string+"]");
+ System.out.println("Encoding: [" + string + "]");
byte[] expected = JSSUtil.encode(tag, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = StringTestUtil.encode(tag, string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -32,12 +32,12 @@ public class PrintableStringTest {
String input = "";
byte[] data = JSSUtil.encode(tag, input);
- System.out.println("Decoding: ["+StringTestUtil.toString(data)+"]");
+ System.out.println("Decoding: [" + StringTestUtil.toString(data) + "]");
- System.out.println(" - expected: ["+input+"]");
+ System.out.println(" - expected: [" + input + "]");
String output = StringTestUtil.decode(tag, data);
- System.out.println(" - actual : ["+output+"]");
+ System.out.println(" - actual : [" + output + "]");
Assert.assertEquals(input, output);
}
@@ -46,13 +46,13 @@ public class PrintableStringTest {
public void testEncodingPrintableCharacters() throws Exception {
String string = StringTestUtil.PRINTABLE_CHARS;
- System.out.println("Encoding: ["+string+"]");
+ System.out.println("Encoding: [" + string + "]");
byte[] expected = JSSUtil.encode(tag, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = StringTestUtil.encode(tag, string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -63,12 +63,12 @@ public class PrintableStringTest {
String input = StringTestUtil.PRINTABLE_CHARS;
byte[] data = JSSUtil.encode(tag, input);
- System.out.println("Decoding: ["+StringTestUtil.toString(data)+"]");
+ System.out.println("Decoding: [" + StringTestUtil.toString(data) + "]");
- System.out.println(" - expected: ["+input+"]");
+ System.out.println(" - expected: [" + input + "]");
String output = StringTestUtil.decode(tag, data);
- System.out.println(" - actual : ["+output+"]");
+ System.out.println(" - actual : [" + output + "]");
Assert.assertEquals(input, output);
}
@@ -77,18 +77,18 @@ public class PrintableStringTest {
public void testEncodingNonPrintableCharacters() throws Exception {
String string = StringTestUtil.NON_PRINTABLE_CHARS;
- System.out.println("Encoding: ["+StringTestUtil.toString(string.getBytes())+"]");
+ System.out.println("Encoding: [" + StringTestUtil.toString(string.getBytes()) + "]");
System.out.println(" - expected: IOException");
try {
byte[] actual = StringTestUtil.encode(tag, string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.fail();
} catch (Exception e) {
- System.out.println(" - actual : "+e.getClass().getSimpleName());
+ System.out.println(" - actual : " + e.getClass().getSimpleName());
Assert.assertTrue(e instanceof IOException);
}
}
@@ -99,18 +99,18 @@ public class PrintableStringTest {
String input = StringTestUtil.NON_PRINTABLE_CHARS;
byte[] data = JSSUtil.encode(DerValue.tag_UTF8String, input);
- System.out.println("Decoding: ["+StringTestUtil.toString(data)+"]");
+ System.out.println("Decoding: [" + StringTestUtil.toString(data) + "]");
System.out.println(" - expected: IOException");
try {
String output = StringTestUtil.decode(tag, data);
- System.out.println(" - actual : ["+StringTestUtil.toString(output.getBytes())+"]");
+ System.out.println(" - actual : [" + StringTestUtil.toString(output.getBytes()) + "]");
Assert.fail();
} catch (Exception e) {
- System.out.println(" - actual : "+e.getClass().getSimpleName());
+ System.out.println(" - actual : " + e.getClass().getSimpleName());
Assert.assertTrue(e instanceof IOException);
}
}
@@ -119,18 +119,18 @@ public class PrintableStringTest {
public void testEncodingControlCharacters() throws Exception {
String string = StringTestUtil.CONTROL_CHARS;
- System.out.println("Encoding: ["+StringTestUtil.toString(string.getBytes())+"]");
+ System.out.println("Encoding: [" + StringTestUtil.toString(string.getBytes()) + "]");
System.out.println(" - expected: IOException");
try {
byte[] actual = StringTestUtil.encode(tag, string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.fail();
} catch (Exception e) {
- System.out.println(" - actual : "+e.getClass().getSimpleName());
+ System.out.println(" - actual : " + e.getClass().getSimpleName());
Assert.assertTrue(e instanceof IOException);
}
}
@@ -141,18 +141,18 @@ public class PrintableStringTest {
String input = StringTestUtil.CONTROL_CHARS;
byte[] data = JSSUtil.encode(DerValue.tag_UTF8String, input);
- System.out.println("Decoding: ["+StringTestUtil.toString(data)+"]");
+ System.out.println("Decoding: [" + StringTestUtil.toString(data) + "]");
System.out.println(" - expected: IOException");
try {
String output = StringTestUtil.decode(tag, data);
- System.out.println(" - actual : ["+StringTestUtil.toString(output.getBytes())+"]");
+ System.out.println(" - actual : [" + StringTestUtil.toString(output.getBytes()) + "]");
Assert.fail();
} catch (Exception e) {
- System.out.println(" - actual : "+e.getClass().getSimpleName());
+ System.out.println(" - actual : " + e.getClass().getSimpleName());
Assert.assertTrue(e instanceof IOException);
}
}
@@ -161,18 +161,18 @@ public class PrintableStringTest {
public void testEncodingMultibyteCharacters() throws Exception {
String string = StringTestUtil.MULTIBYTE_CHARS;
- System.out.println("Encoding: ["+string+"]");
+ System.out.println("Encoding: [" + string + "]");
System.out.println(" - expected: IOException");
try {
byte[] actual = StringTestUtil.encode(tag, StringTestUtil.MULTIBYTE_CHARS);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.fail();
} catch (Exception e) {
- System.out.println(" - actual : "+e.getClass().getSimpleName());
+ System.out.println(" - actual : " + e.getClass().getSimpleName());
Assert.assertTrue(e instanceof IOException);
}
}
@@ -183,18 +183,18 @@ public class PrintableStringTest {
String input = StringTestUtil.MULTIBYTE_CHARS;
byte[] data = JSSUtil.encode(DerValue.tag_UTF8String, input);
- System.out.println("Decoding: ["+StringTestUtil.toString(data)+"]");
+ System.out.println("Decoding: [" + StringTestUtil.toString(data) + "]");
System.out.println(" - expected: IOException");
try {
String output = StringTestUtil.decode(tag, data);
- System.out.println(" - actual : ["+StringTestUtil.toString(output.getBytes())+"]");
+ System.out.println(" - actual : [" + StringTestUtil.toString(output.getBytes()) + "]");
Assert.fail();
} catch (Exception e) {
- System.out.println(" - actual : "+e.getClass().getSimpleName());
+ System.out.println(" - actual : " + e.getClass().getSimpleName());
Assert.assertTrue(e instanceof IOException);
}
}
diff --git a/pki/base/util/test/com/netscape/security/util/StringTestUtil.java b/pki/base/util/test/com/netscape/security/util/StringTestUtil.java
index 211ba518..06dc10ea 100644
--- a/pki/base/util/test/com/netscape/security/util/StringTestUtil.java
+++ b/pki/base/util/test/com/netscape/security/util/StringTestUtil.java
@@ -7,7 +7,7 @@ import netscape.security.util.DerValue;
public class StringTestUtil {
public final static String PRINTABLE_CHARS =
- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 \'()+,-./:=?";
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 \'()+,-./:=?";
public final static String NON_PRINTABLE_CHARS = "\"\\";
@@ -18,8 +18,9 @@ public class StringTestUtil {
public static String toString(byte[] array) {
StringBuffer sb = new StringBuffer();
- for (int i=0; i<array.length; i++) {
- if (i > 0) sb.append(" ");
+ for (int i = 0; i < array.length; i++) {
+ if (i > 0)
+ sb.append(" ");
sb.append(Integer.toHexString(0xff & array[i] | 0x100).substring(1).toUpperCase());
}
@@ -31,13 +32,14 @@ public class StringTestUtil {
DerValue value = new DerValue(data);
byte[] tmp = value.data.toByteArray();
- if (tmp[0] == -2 && tmp[1] == -1) { // remove optional big-endian byte-order mark
+ if (tmp[0] == -2 && tmp[1] == -1) { // remove optional big-endian
+ // byte-order mark
byte tag = value.tag;
int length = value.length() - 2;
DerOutputStream os = new DerOutputStream();
- os.putTag((byte)0, false, tag);
+ os.putTag((byte) 0, false, tag);
os.putLength(length);
os.write(tmp, 2, length);
@@ -70,7 +72,7 @@ public class StringTestUtil {
case DerValue.tag_UTF8String:
return is.getDerValue().getUTF8String();
default:
- throw new Exception("Unsupported tag: "+tag);
+ throw new Exception("Unsupported tag: " + tag);
}
}
}
diff --git a/pki/base/util/test/com/netscape/security/util/TeletexStringTest.java b/pki/base/util/test/com/netscape/security/util/TeletexStringTest.java
index 7217cae4..d6ce1cac 100644
--- a/pki/base/util/test/com/netscape/security/util/TeletexStringTest.java
+++ b/pki/base/util/test/com/netscape/security/util/TeletexStringTest.java
@@ -15,13 +15,13 @@ public class TeletexStringTest {
public void testEncodingEmptyString() throws Exception {
String string = "";
- System.out.println("Encoding: ["+string+"]");
+ System.out.println("Encoding: [" + string + "]");
byte[] expected = JSSUtil.encode(tag, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = StringTestUtil.encode(tag, string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -32,12 +32,12 @@ public class TeletexStringTest {
String input = "";
byte[] data = JSSUtil.encode(tag, input);
- System.out.println("Decoding: ["+StringTestUtil.toString(data)+"]");
+ System.out.println("Decoding: [" + StringTestUtil.toString(data) + "]");
- System.out.println(" - expected: ["+input+"]");
+ System.out.println(" - expected: [" + input + "]");
String output = StringTestUtil.decode(tag, data);
- System.out.println(" - actual : ["+output+"]");
+ System.out.println(" - actual : [" + output + "]");
Assert.assertEquals(input, output);
}
@@ -46,13 +46,13 @@ public class TeletexStringTest {
public void testEncodingPrintableCharacters() throws Exception {
String string = StringTestUtil.PRINTABLE_CHARS;
- System.out.println("Encoding: ["+string+"]");
+ System.out.println("Encoding: [" + string + "]");
byte[] expected = JSSUtil.encode(tag, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = StringTestUtil.encode(tag, string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -63,12 +63,12 @@ public class TeletexStringTest {
String input = StringTestUtil.PRINTABLE_CHARS;
byte[] data = JSSUtil.encode(tag, input);
- System.out.println("Decoding: ["+StringTestUtil.toString(data)+"]");
+ System.out.println("Decoding: [" + StringTestUtil.toString(data) + "]");
- System.out.println(" - expected: ["+input+"]");
+ System.out.println(" - expected: [" + input + "]");
String output = StringTestUtil.decode(tag, data);
- System.out.println(" - actual : ["+output+"]");
+ System.out.println(" - actual : [" + output + "]");
Assert.assertEquals(input, output);
}
@@ -77,13 +77,13 @@ public class TeletexStringTest {
public void testEncodingNonPrintableCharacters() throws Exception {
String string = StringTestUtil.NON_PRINTABLE_CHARS;
- System.out.println("Encoding: ["+string+"]");
+ System.out.println("Encoding: [" + string + "]");
byte[] expected = JSSUtil.encode(tag, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = StringTestUtil.encode(tag, string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -94,12 +94,12 @@ public class TeletexStringTest {
String input = StringTestUtil.NON_PRINTABLE_CHARS;
byte[] data = JSSUtil.encode(tag, input);
- System.out.println("Decoding: ["+StringTestUtil.toString(data)+"]");
+ System.out.println("Decoding: [" + StringTestUtil.toString(data) + "]");
- System.out.println(" - expected: ["+input+"]");
+ System.out.println(" - expected: [" + input + "]");
String output = StringTestUtil.decode(tag, data);
- System.out.println(" - actual : ["+output+"]");
+ System.out.println(" - actual : [" + output + "]");
Assert.assertEquals(input, output);
}
@@ -108,13 +108,13 @@ public class TeletexStringTest {
public void testEncodingControlCharacters() throws Exception {
String string = StringTestUtil.CONTROL_CHARS;
- System.out.println("Encoding: ["+StringTestUtil.toString(string.getBytes())+"]");
+ System.out.println("Encoding: [" + StringTestUtil.toString(string.getBytes()) + "]");
byte[] expected = JSSUtil.encode(tag, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = StringTestUtil.encode(tag, string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -125,12 +125,12 @@ public class TeletexStringTest {
String input = StringTestUtil.CONTROL_CHARS;
byte[] data = JSSUtil.encode(tag, input);
- System.out.println("Decoding: ["+StringTestUtil.toString(data)+"]");
+ System.out.println("Decoding: [" + StringTestUtil.toString(data) + "]");
- System.out.println(" - expected: ["+StringTestUtil.toString(input.getBytes())+"]");
+ System.out.println(" - expected: [" + StringTestUtil.toString(input.getBytes()) + "]");
String output = StringTestUtil.decode(tag, data);
- System.out.println(" - actual : ["+StringTestUtil.toString(output.getBytes())+"]");
+ System.out.println(" - actual : [" + StringTestUtil.toString(output.getBytes()) + "]");
Assert.assertEquals(input, output);
}
@@ -139,18 +139,18 @@ public class TeletexStringTest {
public void testEncodingMultibyteCharacters() throws Exception {
String string = StringTestUtil.MULTIBYTE_CHARS;
- System.out.println("Encoding: ["+string+"]");
+ System.out.println("Encoding: [" + string + "]");
System.out.println(" - expected: IOException");
try {
byte[] actual = StringTestUtil.encode(tag, string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.fail();
} catch (Exception e) {
- System.out.println(" - actual : "+e.getClass().getSimpleName());
+ System.out.println(" - actual : " + e.getClass().getSimpleName());
Assert.assertTrue(e instanceof IOException);
}
}
@@ -161,18 +161,18 @@ public class TeletexStringTest {
String input = StringTestUtil.MULTIBYTE_CHARS;
byte[] data = JSSUtil.encode(DerValue.tag_UTF8String, input);
- System.out.println("Decoding: ["+StringTestUtil.toString(data)+"]");
+ System.out.println("Decoding: [" + StringTestUtil.toString(data) + "]");
System.out.println(" - expected: IOException");
try {
String output = StringTestUtil.decode(tag, data);
- System.out.println(" - actual : ["+StringTestUtil.toString(output.getBytes())+"]");
+ System.out.println(" - actual : [" + StringTestUtil.toString(output.getBytes()) + "]");
Assert.fail();
} catch (Exception e) {
- System.out.println(" - actual : "+e.getClass().getSimpleName());
+ System.out.println(" - actual : " + e.getClass().getSimpleName());
Assert.assertTrue(e instanceof IOException);
}
}
diff --git a/pki/base/util/test/com/netscape/security/util/UTF8StringTest.java b/pki/base/util/test/com/netscape/security/util/UTF8StringTest.java
index 3256a8e3..f4ccd8c7 100644
--- a/pki/base/util/test/com/netscape/security/util/UTF8StringTest.java
+++ b/pki/base/util/test/com/netscape/security/util/UTF8StringTest.java
@@ -13,13 +13,13 @@ public class UTF8StringTest {
public void testEncodingEmptyString() throws Exception {
String string = "";
- System.out.println("Encoding: ["+string+"]");
+ System.out.println("Encoding: [" + string + "]");
byte[] expected = JSSUtil.encode(tag, "");
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = StringTestUtil.encode(tag, "");
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -30,12 +30,12 @@ public class UTF8StringTest {
String input = "";
byte[] data = JSSUtil.encode(tag, input);
- System.out.println("Decoding: ["+StringTestUtil.toString(data)+"]");
+ System.out.println("Decoding: [" + StringTestUtil.toString(data) + "]");
- System.out.println(" - expected: ["+input+"]");
+ System.out.println(" - expected: [" + input + "]");
String output = StringTestUtil.decode(tag, data);
- System.out.println(" - actual : ["+output+"]");
+ System.out.println(" - actual : [" + output + "]");
Assert.assertEquals(input, output);
}
@@ -44,13 +44,13 @@ public class UTF8StringTest {
public void testEncodingPrintableCharacters() throws Exception {
String string = StringTestUtil.PRINTABLE_CHARS;
- System.out.println("Encoding: ["+string+"]");
+ System.out.println("Encoding: [" + string + "]");
byte[] expected = JSSUtil.encode(tag, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = StringTestUtil.encode(tag, string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -61,12 +61,12 @@ public class UTF8StringTest {
String input = StringTestUtil.PRINTABLE_CHARS;
byte[] data = JSSUtil.encode(tag, input);
- System.out.println("Decoding: ["+StringTestUtil.toString(data)+"]");
+ System.out.println("Decoding: [" + StringTestUtil.toString(data) + "]");
- System.out.println(" - expected: ["+input+"]");
+ System.out.println(" - expected: [" + input + "]");
String output = StringTestUtil.decode(tag, data);
- System.out.println(" - actual : ["+output+"]");
+ System.out.println(" - actual : [" + output + "]");
Assert.assertEquals(input, output);
}
@@ -75,13 +75,13 @@ public class UTF8StringTest {
public void testEncodingNonPrintableCharacters() throws Exception {
String string = StringTestUtil.NON_PRINTABLE_CHARS;
- System.out.println("Encoding: ["+string+"]");
+ System.out.println("Encoding: [" + string + "]");
byte[] expected = JSSUtil.encode(tag, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = StringTestUtil.encode(tag, string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -92,12 +92,12 @@ public class UTF8StringTest {
String input = StringTestUtil.NON_PRINTABLE_CHARS;
byte[] data = JSSUtil.encode(tag, input);
- System.out.println("Decoding: ["+StringTestUtil.toString(data)+"]");
+ System.out.println("Decoding: [" + StringTestUtil.toString(data) + "]");
- System.out.println(" - expected: ["+input+"]");
+ System.out.println(" - expected: [" + input + "]");
String output = StringTestUtil.decode(tag, data);
- System.out.println(" - actual : ["+output+"]");
+ System.out.println(" - actual : [" + output + "]");
Assert.assertEquals(input, output);
}
@@ -106,13 +106,13 @@ public class UTF8StringTest {
public void testEncodingControlCharacters() throws Exception {
String string = StringTestUtil.CONTROL_CHARS;
- System.out.println("Encoding: ["+StringTestUtil.toString(string.getBytes())+"]");
+ System.out.println("Encoding: [" + StringTestUtil.toString(string.getBytes()) + "]");
byte[] expected = JSSUtil.encode(tag, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = StringTestUtil.encode(tag, string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -123,12 +123,12 @@ public class UTF8StringTest {
String input = StringTestUtil.CONTROL_CHARS;
byte[] data = JSSUtil.encode(tag, input);
- System.out.println("Decoding: ["+StringTestUtil.toString(data)+"]");
+ System.out.println("Decoding: [" + StringTestUtil.toString(data) + "]");
- System.out.println(" - expected: ["+StringTestUtil.toString(input.getBytes())+"]");
+ System.out.println(" - expected: [" + StringTestUtil.toString(input.getBytes()) + "]");
String output = StringTestUtil.decode(tag, data);
- System.out.println(" - actual : ["+StringTestUtil.toString(output.getBytes())+"]");
+ System.out.println(" - actual : [" + StringTestUtil.toString(output.getBytes()) + "]");
Assert.assertEquals(input, output);
}
@@ -137,13 +137,13 @@ public class UTF8StringTest {
public void testEncodingMultibyteCharacters() throws Exception {
String string = StringTestUtil.MULTIBYTE_CHARS;
- System.out.println("Encoding: ["+string+"]");
+ System.out.println("Encoding: [" + string + "]");
byte[] expected = JSSUtil.encode(tag, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = StringTestUtil.encode(tag, string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -154,12 +154,12 @@ public class UTF8StringTest {
String input = StringTestUtil.MULTIBYTE_CHARS;
byte[] data = JSSUtil.encode(tag, input);
- System.out.println("Decoding: ["+StringTestUtil.toString(data)+"]");
+ System.out.println("Decoding: [" + StringTestUtil.toString(data) + "]");
- System.out.println(" - expected: ["+StringTestUtil.toString(input.getBytes())+"]");
+ System.out.println(" - expected: [" + StringTestUtil.toString(input.getBytes()) + "]");
String output = StringTestUtil.decode(tag, data);
- System.out.println(" - actual : ["+StringTestUtil.toString(output.getBytes())+"]");
+ System.out.println(" - actual : [" + StringTestUtil.toString(output.getBytes()) + "]");
Assert.assertEquals(input, output);
}
diff --git a/pki/base/util/test/com/netscape/security/util/UniversalStringTest.java b/pki/base/util/test/com/netscape/security/util/UniversalStringTest.java
index aceae03b..d3e35d6e 100644
--- a/pki/base/util/test/com/netscape/security/util/UniversalStringTest.java
+++ b/pki/base/util/test/com/netscape/security/util/UniversalStringTest.java
@@ -13,13 +13,13 @@ public class UniversalStringTest {
public void testEncodingEmptyString() throws Exception {
String string = "";
- System.out.println("Encoding: ["+string+"]");
+ System.out.println("Encoding: [" + string + "]");
byte[] expected = JSSUtil.encode(tag, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = StringTestUtil.encode(tag, string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -30,12 +30,12 @@ public class UniversalStringTest {
String input = "";
byte[] data = JSSUtil.encode(tag, input);
- System.out.println("Decoding: ["+StringTestUtil.toString(data)+"]");
+ System.out.println("Decoding: [" + StringTestUtil.toString(data) + "]");
- System.out.println(" - expected: ["+input+"]");
+ System.out.println(" - expected: [" + input + "]");
String output = StringTestUtil.decode(tag, data);
- System.out.println(" - actual : ["+output+"]");
+ System.out.println(" - actual : [" + output + "]");
Assert.assertEquals(input, output);
}
@@ -44,13 +44,13 @@ public class UniversalStringTest {
public void testEncodingPrintableCharacters() throws Exception {
String string = StringTestUtil.PRINTABLE_CHARS;
- System.out.println("Encoding: ["+string+"]");
+ System.out.println("Encoding: [" + string + "]");
byte[] expected = JSSUtil.encode(tag, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = StringTestUtil.encode(tag, string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -61,12 +61,12 @@ public class UniversalStringTest {
String input = StringTestUtil.PRINTABLE_CHARS;
byte[] data = JSSUtil.encode(tag, input);
- System.out.println("Decoding: ["+StringTestUtil.toString(data)+"]");
+ System.out.println("Decoding: [" + StringTestUtil.toString(data) + "]");
- System.out.println(" - expected: ["+input+"]");
+ System.out.println(" - expected: [" + input + "]");
String output = StringTestUtil.decode(tag, data);
- System.out.println(" - actual : ["+output+"]");
+ System.out.println(" - actual : [" + output + "]");
Assert.assertEquals(input, output);
}
@@ -75,13 +75,13 @@ public class UniversalStringTest {
public void testEncodingNonPrintableCharacters() throws Exception {
String string = StringTestUtil.NON_PRINTABLE_CHARS;
- System.out.println("Encoding: ["+string+"]");
+ System.out.println("Encoding: [" + string + "]");
byte[] expected = JSSUtil.encode(tag, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = StringTestUtil.encode(tag, string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -92,12 +92,12 @@ public class UniversalStringTest {
String input = StringTestUtil.NON_PRINTABLE_CHARS;
byte[] data = JSSUtil.encode(tag, input);
- System.out.println("Decoding: ["+StringTestUtil.toString(data)+"]");
+ System.out.println("Decoding: [" + StringTestUtil.toString(data) + "]");
- System.out.println(" - expected: ["+input+"]");
+ System.out.println(" - expected: [" + input + "]");
String output = StringTestUtil.decode(tag, data);
- System.out.println(" - actual : ["+output+"]");
+ System.out.println(" - actual : [" + output + "]");
Assert.assertEquals(input, output);
}
@@ -106,13 +106,13 @@ public class UniversalStringTest {
public void testEncodingControlCharacters() throws Exception {
String string = StringTestUtil.CONTROL_CHARS;
- System.out.println("Encoding: ["+StringTestUtil.toString(string.getBytes())+"]");
+ System.out.println("Encoding: [" + StringTestUtil.toString(string.getBytes()) + "]");
byte[] expected = JSSUtil.encode(tag, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = StringTestUtil.encode(tag, string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -123,12 +123,12 @@ public class UniversalStringTest {
String input = StringTestUtil.CONTROL_CHARS;
byte[] data = JSSUtil.encode(tag, input);
- System.out.println("Decoding: ["+StringTestUtil.toString(data)+"]");
+ System.out.println("Decoding: [" + StringTestUtil.toString(data) + "]");
- System.out.println(" - expected: ["+StringTestUtil.toString(input.getBytes())+"]");
+ System.out.println(" - expected: [" + StringTestUtil.toString(input.getBytes()) + "]");
String output = StringTestUtil.decode(tag, data);
- System.out.println(" - actual : ["+StringTestUtil.toString(output.getBytes())+"]");
+ System.out.println(" - actual : [" + StringTestUtil.toString(output.getBytes()) + "]");
Assert.assertEquals(input, output);
}
@@ -137,13 +137,13 @@ public class UniversalStringTest {
public void testEncodingMultibyteCharacters() throws Exception {
String string = StringTestUtil.MULTIBYTE_CHARS;
- System.out.println("Encoding: ["+string+"]");
+ System.out.println("Encoding: [" + string + "]");
byte[] expected = JSSUtil.encode(tag, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = StringTestUtil.encode(tag, string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -154,12 +154,12 @@ public class UniversalStringTest {
String input = StringTestUtil.MULTIBYTE_CHARS;
byte[] data = JSSUtil.encode(tag, input);
- System.out.println("Decoding: ["+StringTestUtil.toString(data)+"]");
+ System.out.println("Decoding: [" + StringTestUtil.toString(data) + "]");
- System.out.println(" - expected: ["+StringTestUtil.toString(input.getBytes())+"]");
+ System.out.println(" - expected: [" + StringTestUtil.toString(input.getBytes()) + "]");
String output = StringTestUtil.decode(tag, data);
- System.out.println(" - actual : ["+StringTestUtil.toString(output.getBytes())+"]");
+ System.out.println(" - actual : [" + StringTestUtil.toString(output.getBytes()) + "]");
Assert.assertEquals(input, output);
}
diff --git a/pki/base/util/test/com/netscape/security/x509/DirStrConverterTest.java b/pki/base/util/test/com/netscape/security/x509/DirStrConverterTest.java
index ec8ddc51..7b5cea9c 100644
--- a/pki/base/util/test/com/netscape/security/x509/DirStrConverterTest.java
+++ b/pki/base/util/test/com/netscape/security/x509/DirStrConverterTest.java
@@ -15,13 +15,13 @@ public class DirStrConverterTest {
public void testEmptyString() throws Exception {
String string = "";
- System.out.println("Converting: ["+string+"]");
+ System.out.println("Converting: [" + string + "]");
byte[] expected = JSSUtil.encode(DerValue.tag_PrintableString, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = ConverterTestUtil.convert(new DirStrConverter(), string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -30,13 +30,13 @@ public class DirStrConverterTest {
public void testPrintableCharacters() throws Exception {
String string = StringTestUtil.PRINTABLE_CHARS;
- System.out.println("Converting: ["+string+"]");
+ System.out.println("Converting: [" + string + "]");
byte[] expected = JSSUtil.encode(DerValue.tag_PrintableString, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = ConverterTestUtil.convert(new DirStrConverter(), string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -45,13 +45,13 @@ public class DirStrConverterTest {
public void testControlCharacters() throws Exception {
String string = StringTestUtil.CONTROL_CHARS;
- System.out.println("Converting: ["+StringTestUtil.toString(string.getBytes())+"]");
+ System.out.println("Converting: [" + StringTestUtil.toString(string.getBytes()) + "]");
byte[] expected = JSSUtil.encode(DerValue.tag_T61String, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = ConverterTestUtil.convert(new DirStrConverter(), string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -60,13 +60,13 @@ public class DirStrConverterTest {
public void testMultibyteCharacters() throws Exception {
String string = StringTestUtil.MULTIBYTE_CHARS;
- System.out.println("Converting: ["+string+"]");
+ System.out.println("Converting: [" + string + "]");
byte[] expected = JSSUtil.encode(DerValue.tag_UniversalString, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = ConverterTestUtil.convert(new DirStrConverter(), string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -75,15 +75,15 @@ public class DirStrConverterTest {
public void testPrintableCharactersWithTags() throws Exception {
String string = StringTestUtil.PRINTABLE_CHARS;
- System.out.println("Converting: ["+string+"]");
+ System.out.println("Converting: [" + string + "]");
byte[] expected = JSSUtil.encode(DerValue.tag_IA5String, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = ConverterTestUtil.convert(new DirStrConverter(), string, new byte[] {
- DerValue.tag_IA5String, DerValue.tag_UTF8String
+ DerValue.tag_IA5String, DerValue.tag_UTF8String
});
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -92,15 +92,15 @@ public class DirStrConverterTest {
public void testMultibyteCharactersWithTags() throws Exception {
String string = StringTestUtil.MULTIBYTE_CHARS;
- System.out.println("Converting: ["+string+"]");
+ System.out.println("Converting: [" + string + "]");
byte[] expected = JSSUtil.encode(DerValue.tag_UTF8String, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = ConverterTestUtil.convert(new DirStrConverter(), string, new byte[] {
- DerValue.tag_IA5String, DerValue.tag_UTF8String
+ DerValue.tag_IA5String, DerValue.tag_UTF8String
});
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
diff --git a/pki/base/util/test/com/netscape/security/x509/GenericValueConverterTest.java b/pki/base/util/test/com/netscape/security/x509/GenericValueConverterTest.java
index bee2b241..e9bd1658 100644
--- a/pki/base/util/test/com/netscape/security/x509/GenericValueConverterTest.java
+++ b/pki/base/util/test/com/netscape/security/x509/GenericValueConverterTest.java
@@ -15,13 +15,13 @@ public class GenericValueConverterTest {
public void testEmptyString() throws Exception {
String string = "";
- System.out.println("Converting: ["+string+"]");
+ System.out.println("Converting: [" + string + "]");
byte[] expected = JSSUtil.encode(DerValue.tag_PrintableString, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = ConverterTestUtil.convert(new GenericValueConverter(), string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -30,13 +30,13 @@ public class GenericValueConverterTest {
public void testPrintableCharacters() throws Exception {
String string = StringTestUtil.PRINTABLE_CHARS;
- System.out.println("Converting: ["+string+"]");
+ System.out.println("Converting: [" + string + "]");
byte[] expected = JSSUtil.encode(DerValue.tag_PrintableString, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = ConverterTestUtil.convert(new GenericValueConverter(), string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -45,13 +45,13 @@ public class GenericValueConverterTest {
public void testControlCharacters() throws Exception {
String string = StringTestUtil.CONTROL_CHARS;
- System.out.println("Converting: ["+StringTestUtil.toString(string.getBytes())+"]");
+ System.out.println("Converting: [" + StringTestUtil.toString(string.getBytes()) + "]");
byte[] expected = JSSUtil.encode(DerValue.tag_IA5String, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = ConverterTestUtil.convert(new GenericValueConverter(), string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -60,16 +60,16 @@ public class GenericValueConverterTest {
public void testMultibyteCharacters() throws Exception {
String string = StringTestUtil.MULTIBYTE_CHARS;
- System.out.println("Converting: ["+string+"]");
+ System.out.println("Converting: [" + string + "]");
byte[] expected = JSSUtil.encode(DerValue.tag_BMPString, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = ConverterTestUtil.convert(new GenericValueConverter(), string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
actual = StringTestUtil.normalizeUnicode(actual);
- System.out.println(" - norm. : "+StringTestUtil.toString(actual));
+ System.out.println(" - norm. : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -78,15 +78,15 @@ public class GenericValueConverterTest {
public void testPrintableCharactersWithTags() throws Exception {
String string = StringTestUtil.PRINTABLE_CHARS;
- System.out.println("Converting: ["+string+"]");
+ System.out.println("Converting: [" + string + "]");
byte[] expected = JSSUtil.encode(DerValue.tag_T61String, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = ConverterTestUtil.convert(new GenericValueConverter(), string, new byte[] {
- DerValue.tag_T61String, DerValue.tag_UniversalString
+ DerValue.tag_T61String, DerValue.tag_UniversalString
});
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -95,15 +95,15 @@ public class GenericValueConverterTest {
public void testMultibyteCharactersWithTags() throws Exception {
String string = StringTestUtil.MULTIBYTE_CHARS;
- System.out.println("Converting: ["+string+"]");
+ System.out.println("Converting: [" + string + "]");
byte[] expected = JSSUtil.encode(DerValue.tag_UniversalString, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = ConverterTestUtil.convert(new GenericValueConverter(), string, new byte[] {
- DerValue.tag_T61String, DerValue.tag_UniversalString
+ DerValue.tag_T61String, DerValue.tag_UniversalString
});
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
diff --git a/pki/base/util/test/com/netscape/security/x509/IA5StringConverterTest.java b/pki/base/util/test/com/netscape/security/x509/IA5StringConverterTest.java
index 682e7384..e44f99ab 100644
--- a/pki/base/util/test/com/netscape/security/x509/IA5StringConverterTest.java
+++ b/pki/base/util/test/com/netscape/security/x509/IA5StringConverterTest.java
@@ -15,13 +15,13 @@ public class IA5StringConverterTest {
public void testEmptyString() throws Exception {
String string = "";
- System.out.println("Converting: ["+string+"]");
+ System.out.println("Converting: [" + string + "]");
byte[] expected = JSSUtil.encode(DerValue.tag_IA5String, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = ConverterTestUtil.convert(new IA5StringConverter(), string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -30,13 +30,13 @@ public class IA5StringConverterTest {
public void testPrintableCharacters() throws Exception {
String string = StringTestUtil.PRINTABLE_CHARS;
- System.out.println("Converting: ["+string+"]");
+ System.out.println("Converting: [" + string + "]");
byte[] expected = JSSUtil.encode(DerValue.tag_IA5String, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = ConverterTestUtil.convert(new IA5StringConverter(), string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -45,13 +45,13 @@ public class IA5StringConverterTest {
public void testControlCharacters() throws Exception {
String string = StringTestUtil.CONTROL_CHARS;
- System.out.println("Converting: ["+StringTestUtil.toString(string.getBytes())+"]");
+ System.out.println("Converting: [" + StringTestUtil.toString(string.getBytes()) + "]");
byte[] expected = JSSUtil.encode(DerValue.tag_IA5String, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = ConverterTestUtil.convert(new IA5StringConverter(), string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -60,18 +60,18 @@ public class IA5StringConverterTest {
public void testMultibyteCharacters() throws Exception {
String string = StringTestUtil.MULTIBYTE_CHARS;
- System.out.println("Converting: ["+string+"]");
+ System.out.println("Converting: [" + string + "]");
System.out.println(" - expected: IllegalArgumentException");
try {
byte[] actual = ConverterTestUtil.convert(new IA5StringConverter(), string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.fail();
} catch (Exception e) {
- System.out.println(" - actual : "+e.getClass().getSimpleName());
+ System.out.println(" - actual : " + e.getClass().getSimpleName());
Assert.assertTrue(e instanceof IllegalArgumentException);
}
}
diff --git a/pki/base/util/test/com/netscape/security/x509/PrintableConverterTest.java b/pki/base/util/test/com/netscape/security/x509/PrintableConverterTest.java
index acaa5c1b..cd578c04 100644
--- a/pki/base/util/test/com/netscape/security/x509/PrintableConverterTest.java
+++ b/pki/base/util/test/com/netscape/security/x509/PrintableConverterTest.java
@@ -15,13 +15,13 @@ public class PrintableConverterTest {
public void testEmptyString() throws Exception {
String string = "";
- System.out.println("Converting: ["+string+"]");
+ System.out.println("Converting: [" + string + "]");
byte[] expected = JSSUtil.encode(DerValue.tag_PrintableString, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = ConverterTestUtil.convert(new PrintableConverter(), string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -30,13 +30,13 @@ public class PrintableConverterTest {
public void testPrintableCharacters() throws Exception {
String string = StringTestUtil.PRINTABLE_CHARS;
- System.out.println("Converting: ["+string+"]");
+ System.out.println("Converting: [" + string + "]");
byte[] expected = JSSUtil.encode(DerValue.tag_PrintableString, string);
- System.out.println(" - expected: "+StringTestUtil.toString(expected));
+ System.out.println(" - expected: " + StringTestUtil.toString(expected));
byte[] actual = ConverterTestUtil.convert(new PrintableConverter(), string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.assertArrayEquals(expected, actual);
}
@@ -45,18 +45,18 @@ public class PrintableConverterTest {
public void testControlCharacters() throws Exception {
String string = StringTestUtil.CONTROL_CHARS;
- System.out.println("Converting: ["+StringTestUtil.toString(string.getBytes())+"]");
+ System.out.println("Converting: [" + StringTestUtil.toString(string.getBytes()) + "]");
System.out.println(" - expected: IllegalArgumentException");
try {
byte[] actual = ConverterTestUtil.convert(new PrintableConverter(), string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.fail();
} catch (Exception e) {
- System.out.println(" - actual : "+e.getClass().getSimpleName());
+ System.out.println(" - actual : " + e.getClass().getSimpleName());
Assert.assertTrue(e instanceof IllegalArgumentException);
}
}
@@ -65,18 +65,18 @@ public class PrintableConverterTest {
public void testMultibyteCharacters() throws Exception {
String string = StringTestUtil.MULTIBYTE_CHARS;
- System.out.println("Converting: ["+string+"]");
+ System.out.println("Converting: [" + string + "]");
System.out.println(" - expected: IllegalArgumentException");
try {
byte[] actual = ConverterTestUtil.convert(new PrintableConverter(), string);
- System.out.println(" - actual : "+StringTestUtil.toString(actual));
+ System.out.println(" - actual : " + StringTestUtil.toString(actual));
Assert.fail();
} catch (Exception e) {
- System.out.println(" - actual : "+e.getClass().getSimpleName());
+ System.out.println(" - actual : " + e.getClass().getSimpleName());
Assert.assertTrue(e instanceof IllegalArgumentException);
}
}